@undefineds.co/xpod 0.4.19 → 0.4.25
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/cloud.json +54 -11
- package/config/components-ignore.json +13 -8
- package/config/local.json +32 -1
- package/config/xpod.base.json +271 -1
- package/config/xpod.json +17 -1
- package/dist/agent-directory/client/AgentDirectoryClient.d.ts +54 -0
- package/dist/agent-directory/client/AgentDirectoryClient.js +152 -0
- package/dist/agent-directory/client/index.d.ts +1 -0
- package/dist/agent-directory/client/index.js +18 -0
- package/dist/agent-directory/index.d.ts +1 -0
- package/dist/agent-directory/index.js +18 -0
- package/dist/agent-directory/protocol.d.ts +126 -0
- package/dist/agent-directory/protocol.js +13 -0
- package/dist/agent-directory/protocol.jsonld +296 -0
- package/dist/api/ApiServer.d.ts +8 -0
- package/dist/api/ApiServer.js +75 -16
- package/dist/api/ai-gateway/AiGatewayService.d.ts +9 -1
- package/dist/api/ai-gateway/AiGatewayService.js +22 -7
- package/dist/api/ai-gateway/CloudGatewayModelsClient.d.ts +3 -0
- package/dist/api/ai-gateway/CloudGatewayModelsClient.js +2 -0
- package/dist/api/ai-gateway/InvocationMetadata.d.ts +9 -0
- package/dist/api/ai-gateway/InvocationMetadata.js +40 -0
- package/dist/api/ai-gateway/auth/AiConnectionsInvocationKeyIssuer.d.ts +14 -0
- package/dist/api/ai-gateway/auth/AiConnectionsInvocationKeyIssuer.js +24 -5
- package/dist/api/ai-gateway/connect/AuthorizationCallbackPage.d.ts +4 -0
- package/dist/api/ai-gateway/connect/AuthorizationCallbackPage.js +75 -0
- package/dist/api/ai-gateway/connect/LoopbackAuthorizationCallbackReceiver.js +6 -5
- package/dist/api/ai-gateway/connect/index.d.ts +15 -1
- package/dist/api/ai-gateway/connect/index.js +80 -13
- package/dist/api/ai-gateway/pod/HostedPodRoute.d.ts +0 -7
- package/dist/api/ai-gateway/pod/HostedPodRoute.js +3 -71
- package/dist/api/ai-gateway/pod/OwnerPodAccess.d.ts +0 -1
- package/dist/api/ai-gateway/pod/OwnerPodAccess.js +59 -19
- package/dist/api/ai-gateway/providers/AnthropicRuntimeAdapter.js +2 -0
- package/dist/api/ai-gateway/providers/BailianRuntimeAdapter.js +4 -0
- package/dist/api/ai-gateway/providers/OpenAiRuntimeAdapter.js +2 -1
- package/dist/api/ai-gateway/providers/ProviderRegistry.d.ts +2 -8
- package/dist/api/ai-gateway/providers/ProviderRegistry.js +21 -132
- package/dist/api/ai-gateway/providers/ProviderRuntimeAdapter.d.ts +3 -1
- package/dist/api/ai-gateway/providers/ProviderRuntimeAdapter.js +25 -4
- package/dist/api/ai-gateway/routing/ModelRouter.js +13 -0
- package/dist/api/auth/SolidSessionFactory.d.ts +2 -1
- package/dist/api/auth/SolidSessionFactory.js +33 -11
- package/dist/api/background-service-supervisor.d.ts +63 -0
- package/dist/api/background-service-supervisor.js +144 -0
- package/dist/api/chatkit/pod-store.d.ts +34 -4
- package/dist/api/chatkit/pod-store.js +315 -185
- package/dist/api/chatkit/store.d.ts +2 -1
- package/dist/api/chatkit/store.js +7 -8
- package/dist/api/container/common.js +94 -16
- package/dist/api/container/index.js +22 -6
- package/dist/api/container/rdf.d.ts +4 -0
- package/dist/api/container/rdf.js +5 -1
- package/dist/api/container/routes.js +30 -0
- package/dist/api/container/types.d.ts +4 -2
- package/dist/api/handlers/AdminHandler.d.ts +4 -3
- package/dist/api/handlers/AdminHandler.js +27 -39
- package/dist/api/handlers/AiConfigHandler.d.ts +12 -0
- package/dist/api/handlers/AiConfigHandler.js +14 -4
- package/dist/api/handlers/AiGatewayHandler.js +4 -0
- package/dist/api/handlers/AiGatewayManagementHandler.js +8 -0
- package/dist/api/handlers/DeviceNotificationRuntime.d.ts +1 -1
- package/dist/api/handlers/DeviceNotificationRuntime.js +5 -8
- package/dist/api/handlers/InngestHandler.d.ts +7 -0
- package/dist/api/handlers/InngestHandler.js +45 -0
- package/dist/api/handlers/NetworkSettingsHandler.d.ts +31 -1
- package/dist/api/handlers/NetworkSettingsHandler.js +76 -3
- package/dist/api/handlers/PodAccessFailureResponse.d.ts +2 -1
- package/dist/api/handlers/PodAccessFailureResponse.js +4 -5
- package/dist/api/handlers/PodDeletionGrantHandler.d.ts +9 -0
- package/dist/api/handlers/PodDeletionGrantHandler.js +129 -0
- package/dist/api/handlers/PodManagementHandler.d.ts +2 -0
- package/dist/api/handlers/PodManagementHandler.js +137 -71
- package/dist/api/handlers/ProvisionHandler.d.ts +2 -0
- package/dist/api/handlers/ProvisionHandler.js +13 -1
- package/dist/api/handlers/ReachabilityHandler.js +5 -0
- package/dist/api/handlers/RunHandler.js +7 -27
- package/dist/api/handlers/ServiceInfoHandler.d.ts +10 -0
- package/dist/api/handlers/ServiceInfoHandler.js +32 -0
- package/dist/api/handlers/SettingsHandler.js +5 -0
- package/dist/api/handlers/TaskHandler.d.ts +41 -0
- package/dist/api/handlers/TaskHandler.js +195 -0
- package/dist/api/matrix/PodMatrixStore.js +16 -9
- package/dist/api/network/EndpointReachabilityProbe.d.ts +40 -0
- package/dist/api/network/EndpointReachabilityProbe.js +129 -0
- package/dist/api/runs/AgentRuntimeTypes.d.ts +7 -0
- package/dist/api/runs/ConditionalResourceDocument.d.ts +20 -0
- package/dist/api/runs/ConditionalResourceDocument.js +100 -0
- package/dist/api/runs/EmbeddedInngestService.d.ts +80 -0
- package/dist/api/runs/EmbeddedInngestService.js +311 -37
- package/dist/api/runs/InngestRunExecutionBackend.d.ts +2 -2
- package/dist/api/runs/InngestRunExecutionBackend.js +5 -0
- package/dist/api/runs/ManagedRunWorker.d.ts +0 -2
- package/dist/api/runs/ManagedRunWorker.js +100 -75
- package/dist/api/runs/PiAgentRuntimeDriver.d.ts +32 -0
- package/dist/api/runs/PiAgentRuntimeDriver.js +229 -14
- package/dist/api/runs/PiAgentRuntimeWorker.js +12 -2
- package/dist/api/runs/PodRdfAccessScopeResolver.d.ts +16 -0
- package/dist/api/runs/PodRdfAccessScopeResolver.js +83 -0
- package/dist/api/runs/RdfRunContextRetriever.d.ts +1 -1
- package/dist/api/runs/RdfRunContextRetriever.js +5 -6
- package/dist/api/runs/RunApproval.d.ts +17 -0
- package/dist/api/runs/RunApproval.js +45 -0
- package/dist/api/runs/RunCancellation.d.ts +20 -0
- package/dist/api/runs/RunCancellation.js +83 -0
- package/dist/api/runs/RunExecutionBackend.d.ts +2 -0
- package/dist/api/runs/RunStateCenter.d.ts +0 -3
- package/dist/api/runs/RunStateCenter.js +129 -116
- package/dist/api/runs/RunStateMerge.d.ts +4 -0
- package/dist/api/runs/RunStateMerge.js +19 -0
- package/dist/api/runs/store.d.ts +6 -1
- package/dist/api/runs/store.js +19 -1
- package/dist/api/runtime.js +51 -21
- package/dist/api/service/provider-http-transport.d.ts +14 -1
- package/dist/api/service/provider-http-transport.js +173 -20
- package/dist/api/tasks/InngestTaskScheduler.d.ts +4 -4
- package/dist/api/tasks/TaskAgentBinding.d.ts +14 -0
- package/dist/api/tasks/TaskAgentBinding.js +25 -0
- package/dist/api/tasks/TaskAuthBinding.js +16 -2
- package/dist/api/tasks/TaskMaterializer.d.ts +5 -4
- package/dist/api/tasks/TaskMaterializer.js +167 -126
- package/dist/api/tasks/TaskService.d.ts +28 -3
- package/dist/api/tasks/TaskService.js +125 -44
- package/dist/api/tasks/cron.d.ts +2 -0
- package/dist/api/tasks/cron.js +51 -0
- package/dist/api/tasks/schema.d.ts +3 -0
- package/dist/api/tasks/store.d.ts +10 -1
- package/dist/authentication/ConfiguredLoopbackDPoPWebIdExtractor.d.ts +6 -1
- package/dist/authentication/ConfiguredLoopbackDPoPWebIdExtractor.js +33 -9
- package/dist/authentication/ConfiguredLoopbackDPoPWebIdExtractor.jsonld +9 -1
- package/dist/authentication/SolidTokenCaches.js +44 -10
- package/dist/cli/agent-fs/args.d.ts +37 -0
- package/dist/cli/agent-fs/args.js +254 -0
- package/dist/cli/agent-fs/auth-proxy.d.ts +27 -0
- package/dist/cli/agent-fs/auth-proxy.js +208 -0
- package/dist/cli/agent-fs/install.d.ts +18 -0
- package/dist/cli/agent-fs/install.js +54 -0
- package/dist/cli/agent-fs/mount.d.ts +35 -0
- package/dist/cli/agent-fs/mount.js +111 -0
- package/dist/cli/agent-fs/native.d.ts +6 -0
- package/dist/cli/agent-fs/native.js +104 -0
- package/dist/cli/agent-fs/pending-store.d.ts +14 -0
- package/dist/cli/agent-fs/pending-store.js +37 -0
- package/dist/cli/agent-fs/pod-lower.d.ts +127 -0
- package/dist/cli/agent-fs/pod-lower.js +398 -0
- package/dist/cli/agent-fs/rg-entry.d.ts +6 -0
- package/dist/cli/agent-fs/rg-entry.js +132 -0
- package/dist/cli/agent-fs/roots.d.ts +18 -0
- package/dist/cli/agent-fs/roots.js +152 -0
- package/dist/cli/agent-fs/runner.d.ts +18 -0
- package/dist/cli/agent-fs/runner.js +145 -0
- package/dist/cli/agent-fs/session-view.d.ts +7 -0
- package/dist/cli/agent-fs/session-view.js +31 -0
- package/dist/cli/commands/agent-fs.d.ts +2 -0
- package/dist/cli/commands/agent-fs.js +491 -0
- package/dist/cli/commands/start.d.ts +11 -18
- package/dist/cli/commands/start.js +38 -37
- package/dist/cli/commands/stop.js +7 -1
- package/dist/cli/index.js +11 -2
- package/dist/cli/lib/auth-context.d.ts +6 -0
- package/dist/cli/lib/auth-context.js +1 -1
- package/dist/cli/lib/launcher.d.ts +2 -0
- package/dist/cli/lib/launcher.js +19 -0
- package/dist/components/components.jsonld +18 -0
- package/dist/components/context.jsonld +472 -6
- package/dist/dns/cloudflare/CloudflareDnsProvider.d.ts +10 -1
- package/dist/dns/cloudflare/CloudflareDnsProvider.js +59 -28
- package/dist/edge/EdgeNodeAgent.d.ts +5 -0
- package/dist/edge/EdgeNodeAgent.js +8 -0
- package/dist/edge/acme/AcmeCertificateManager.d.ts +24 -0
- package/dist/edge/acme/AcmeCertificateManager.js +75 -7
- package/dist/edge/acme/AcmeCertificateManager.jsonld +24 -0
- package/dist/edge/acme/CertificateRenewalScheduler.d.ts +67 -0
- package/dist/edge/acme/CertificateRenewalScheduler.js +116 -0
- package/dist/edge/frp/FrpcProcessManager.d.ts +16 -0
- package/dist/edge/frp/FrpcProcessManager.js +73 -13
- package/dist/edge/reachability/ManagedClientFetch.d.ts +2 -0
- package/dist/edge/reachability/ManagedClientFetch.js +24 -12
- package/dist/edge/reachability/ManagedClientFetch.jsonld +4 -0
- package/dist/edge/reachability/ManagedRouteSelector.d.ts +2 -0
- package/dist/edge/reachability/ManagedRouteSelector.js +8 -13
- package/dist/edge/reachability/ManagedRouteSelector.jsonld +4 -0
- package/dist/edge/reachability/P2PDataPlane.d.ts +67 -4
- package/dist/edge/reachability/P2PDataPlane.js +156 -15
- package/dist/edge/reachability/P2PDataPlane.jsonld +64 -0
- package/dist/edge/reachability/P2PDataPlaneCrypto.d.ts +42 -0
- package/dist/edge/reachability/P2PDataPlaneCrypto.js +113 -0
- package/dist/edge/reachability/P2PDataPlaneCrypto.jsonld +69 -0
- package/dist/edge/reachability/P2PSignalingClient.d.ts +2 -0
- package/dist/edge/reachability/P2PSignalingClient.js +1 -0
- package/dist/edge/reachability/P2PSignalingClient.jsonld +4 -0
- package/dist/edge/reachability/ReachabilitySessionService.d.ts +19 -0
- package/dist/edge/reachability/ReachabilitySessionService.js +122 -52
- package/dist/edge/reachability/ReachabilitySessionService.jsonld +26 -0
- package/dist/edge/reachability/RouteValidation.d.ts +29 -0
- package/dist/edge/reachability/RouteValidation.js +58 -0
- package/dist/edge/reachability/TcpP2PDataPlaneTransport.d.ts +28 -4
- package/dist/edge/reachability/TcpP2PDataPlaneTransport.js +540 -32
- package/dist/edge/reachability/TcpP2PDataPlaneTransport.jsonld +51 -0
- package/dist/edge/reachability/TcpP2PSignalingSession.d.ts +7 -0
- package/dist/edge/reachability/TcpP2PSignalingSession.js +25 -1
- package/dist/edge/reachability/TcpP2PSignalingSession.jsonld +12 -0
- package/dist/edge/reachability/index.d.ts +1 -0
- package/dist/edge/reachability/index.js +1 -0
- package/dist/edge/reachability/types.d.ts +8 -0
- package/dist/edge/reachability/types.jsonld +8 -0
- package/dist/http/DeviceNotificationWebSocketServer.d.ts +5 -1
- package/dist/http/DeviceNotificationWebSocketServer.js +36 -8
- package/dist/http/DeviceNotificationWebSocketServer.jsonld +16 -0
- package/dist/http/HeadSafeResponseWriter.d.ts +9 -0
- package/dist/http/HeadSafeResponseWriter.js +22 -0
- package/dist/http/HeadSafeResponseWriter.jsonld +39 -0
- package/dist/http/LocalPodDeletionHttpHandler.d.ts +21 -0
- package/dist/http/LocalPodDeletionHttpHandler.js +125 -0
- package/dist/http/LocalPodDeletionHttpHandler.jsonld +115 -0
- package/dist/http/PodDeletionMutationGuard.d.ts +9 -0
- package/dist/http/PodDeletionMutationGuard.js +29 -0
- package/dist/http/PodDeletionMutationGuard.jsonld +58 -0
- package/dist/http/PodMutationLockingHttpHandler.d.ts +14 -0
- package/dist/http/PodMutationLockingHttpHandler.js +93 -0
- package/dist/http/PodMutationLockingHttpHandler.jsonld +99 -0
- package/dist/http/StoragePutOperationHandler.d.ts +7 -0
- package/dist/http/StoragePutOperationHandler.js +27 -0
- package/dist/http/StoragePutOperationHandler.jsonld +57 -0
- package/dist/http/SubgraphSparqlHttpHandler.d.ts +3 -1
- package/dist/http/SubgraphSparqlHttpHandler.js +107 -33
- package/dist/http/SubgraphSparqlHttpHandler.jsonld +19 -0
- package/dist/http/agent-directory/AgentDirectoryHttpHandler.d.ts +87 -0
- package/dist/http/agent-directory/AgentDirectoryHttpHandler.js +717 -0
- package/dist/http/agent-directory/AgentDirectoryHttpHandler.jsonld +302 -0
- package/dist/http/agent-directory/index.d.ts +1 -0
- package/dist/http/agent-directory/index.js +18 -0
- package/dist/identity/CloudProfilePreparationHandler.d.ts +7 -0
- package/dist/identity/CloudProfilePreparationHandler.js +24 -0
- package/dist/identity/CloudProfilePreparationHandler.jsonld +42 -0
- package/dist/identity/PodDeletionInteractionHandler.d.ts +12 -0
- package/dist/identity/PodDeletionInteractionHandler.js +35 -0
- package/dist/identity/PodDeletionInteractionHandler.jsonld +73 -0
- package/dist/identity/PodDeletionInventoryHandler.d.ts +11 -0
- package/dist/identity/PodDeletionInventoryHandler.js +40 -0
- package/dist/identity/PodDeletionInventoryHandler.jsonld +69 -0
- package/dist/identity/ValidatingIdentityProviderHttpHandler.js +29 -10
- package/dist/identity/drizzle/EdgeNodeRepository.d.ts +17 -0
- package/dist/identity/drizzle/EdgeNodeRepository.js +61 -0
- package/dist/identity/drizzle/PodDeletionOperationRepository.d.ts +64 -0
- package/dist/identity/drizzle/PodDeletionOperationRepository.js +241 -0
- package/dist/identity/drizzle/db.d.ts +8 -0
- package/dist/identity/drizzle/db.js +17 -0
- package/dist/index.d.ts +18 -1
- package/dist/index.js +28 -3
- package/dist/logging/log-secrets.d.ts +2 -0
- package/dist/logging/log-secrets.js +35 -0
- package/dist/logging/normalize-log.d.ts +5 -0
- package/dist/logging/normalize-log.js +12 -0
- package/dist/main.js +2 -0
- package/dist/pods/ReservedSuffixIdentifierGenerator.js +2 -1
- package/dist/provision/CloudProfileCreator.d.ts +35 -0
- package/dist/provision/CloudProfileCreator.js +229 -0
- package/dist/provision/CloudProfileCreator.jsonld +186 -0
- package/dist/provision/LocalPodProvisioningService.d.ts +2 -0
- package/dist/provision/LocalPodProvisioningService.js +76 -32
- package/dist/provision/LocalPodProvisioningService.jsonld +8 -0
- package/dist/provision/PodDeletionRoute.d.ts +2 -0
- package/dist/provision/PodDeletionRoute.js +12 -0
- package/dist/provision/PodMutationLock.d.ts +5 -0
- package/dist/provision/PodMutationLock.js +13 -0
- package/dist/provision/ProvisionPodCreator.d.ts +9 -13
- package/dist/provision/ProvisionPodCreator.js +48 -17
- package/dist/provision/ProvisionPodCreator.jsonld +31 -1
- package/dist/provision/ProvisionPodStore.js +19 -5
- package/dist/provision/ProvisionReceiptCodec.d.ts +4 -0
- package/dist/provision/ProvisionReceiptCodec.js +2 -0
- package/dist/runtime/GatewayAdminProxyAuth.d.ts +2 -2
- package/dist/runtime/Proxy.d.ts +2 -0
- package/dist/runtime/Proxy.js +55 -22
- package/dist/runtime/XpodRuntime.js +20 -4
- package/dist/runtime/bootstrap.js +1 -0
- package/dist/runtime/compat/ensureSupportedBun.d.ts +2 -0
- package/dist/runtime/compat/ensureSupportedBun.js +23 -0
- package/dist/runtime/css-process.d.ts +3 -3
- package/dist/runtime/gateway-locator-secret.js +9 -135
- package/dist/runtime/host/node/NodeRuntimeHost.d.ts +3 -2
- package/dist/runtime/host/node/NodeRuntimeHost.js +37 -8
- package/dist/runtime/host/types.d.ts +8 -1
- package/dist/runtime/index.d.ts +7 -1
- package/dist/runtime/index.js +21 -1
- package/dist/runtime/ingress-occupant.d.ts +39 -0
- package/dist/runtime/ingress-occupant.js +111 -0
- package/dist/runtime/ingress-port.d.ts +89 -0
- package/dist/runtime/ingress-port.js +165 -0
- package/dist/runtime/lifecycle.js +22 -5
- package/dist/runtime/local-secret-file.d.ts +9 -0
- package/dist/runtime/local-secret-file.js +152 -0
- package/dist/runtime/port-finder.d.ts +23 -8
- package/dist/runtime/port-finder.js +65 -30
- package/dist/runtime/port-reservations.d.ts +86 -0
- package/dist/runtime/port-reservations.js +183 -0
- package/dist/runtime/runner/node/CommunitySolidServerCssRunner.js +2 -0
- package/dist/runtime/runtime-types.d.ts +2 -0
- package/dist/runtime/safe-env.d.ts +1 -1
- package/dist/runtime/secret-cell-root-key.d.ts +7 -0
- package/dist/runtime/secret-cell-root-key.js +38 -0
- package/dist/runtime/socket-http.js +5 -1
- package/dist/runtime/socket-transport.js +3 -4
- package/dist/runtime/user-env.d.ts +2 -2
- package/dist/service/PodDataDeletionService.d.ts +28 -0
- package/dist/service/PodDataDeletionService.js +126 -0
- package/dist/service/PodDataDeletionService.jsonld +111 -0
- package/dist/service/PodDeletionLifecycleService.d.ts +39 -0
- package/dist/service/PodDeletionLifecycleService.js +262 -0
- package/dist/service/PodDeletionLifecycleService.jsonld +210 -0
- package/dist/shared/xpod-route-policy.d.ts +3 -1
- package/dist/shared/xpod-route-policy.js +19 -1
- package/dist/solidfs/LocalRdfAuthorityRecoveryInitializer.js +1 -1
- package/dist/solidfs/PodSolidFsHttpClient.d.ts +5 -5
- package/dist/solidfs/PodSolidFsHttpClient.js +14 -55
- package/dist/solidfs/PodSolidFsHydrator.d.ts +2 -4
- package/dist/solidfs/PodSolidFsHydrator.js +6 -6
- package/dist/solidfs/PodSolidFsSyncer.d.ts +10 -8
- package/dist/solidfs/PodSolidFsSyncer.js +20 -16
- package/dist/solidfs/RdfIndexSolidFsSyncer.d.ts +3 -0
- package/dist/solidfs/RdfIndexSolidFsSyncer.js +4 -3
- package/dist/solidfs/SolidFsSyncJournal.d.ts +11 -0
- package/dist/solidfs/SolidFsSyncJournal.js +130 -21
- package/dist/solidfs/SolidFsSyncJournal.jsonld +4 -0
- package/dist/storage/HierarchyLockingResourceStore.d.ts +17 -0
- package/dist/storage/HierarchyLockingResourceStore.js +147 -0
- package/dist/storage/HierarchyLockingResourceStore.jsonld +104 -0
- package/dist/storage/RepresentationPartialConvertingStore.js +11 -2
- package/dist/storage/SparqlUpdateResourceStore.js +5 -0
- package/dist/storage/StorageVersion.d.ts +16 -0
- package/dist/storage/StorageVersion.js +36 -0
- package/dist/storage/accessors/MinioDataAccessor.js +2 -1
- package/dist/storage/accessors/MixDataAccessor.d.ts +7 -0
- package/dist/storage/accessors/MixDataAccessor.js +99 -10
- package/dist/storage/accessors/MixDataAccessor.jsonld +8 -0
- package/dist/storage/accessors/SolidRdfDataAccessor.d.ts +3 -0
- package/dist/storage/accessors/SolidRdfDataAccessor.js +30 -7
- package/dist/storage/accessors/SolidRdfDataAccessor.jsonld +8 -0
- package/dist/storage/conditions/StorageETagHandler.d.ts +9 -0
- package/dist/storage/conditions/StorageETagHandler.js +32 -0
- package/dist/storage/conditions/StorageETagHandler.jsonld +34 -0
- package/dist/storage/locking/PodLifecycleLocker.d.ts +8 -0
- package/dist/storage/locking/PodLifecycleLocker.js +17 -0
- package/dist/storage/locking/PodLifecycleLocker.jsonld +47 -0
- package/dist/storage/locking/PodLifecycleRedisLocker.d.ts +19 -0
- package/dist/storage/locking/PodLifecycleRedisLocker.js +52 -0
- package/dist/storage/locking/PodLifecycleRedisLocker.jsonld +156 -0
- package/dist/storage/locking/UrlAwareRedisLocker.d.ts +21 -9
- package/dist/storage/locking/UrlAwareRedisLocker.js +80 -121
- package/dist/storage/locking/UrlAwareRedisLocker.jsonld +71 -21
- package/dist/storage/rdf/PostgresRdfEngine.d.ts +2 -1
- package/dist/storage/rdf/PostgresRdfEngine.js +3 -0
- package/dist/storage/rdf/PostgresRdfEngine.jsonld +4 -0
- package/dist/storage/rdf/RdfAccessScope.js +23 -18
- package/dist/supervisor/Supervisor.d.ts +29 -5
- package/dist/supervisor/Supervisor.js +137 -27
- package/dist/supervisor/types.d.ts +14 -1
- package/dist/test-utils/local-managed-client-p2p-e2e-smoke.js +15 -0
- package/dist/tunnel/LocalTunnelProvider.d.ts +7 -0
- package/dist/tunnel/LocalTunnelProvider.js +11 -3
- package/dist/tunnel/LocalTunnelProvider.jsonld +39 -0
- package/dist/tunnel/NgrokTunnelProvider.d.ts +2 -0
- package/dist/tunnel/NgrokTunnelProvider.js +3 -1
- package/dist/tunnel/NgrokTunnelProvider.jsonld +39 -0
- package/dist/tunnel/SakuraFrpTunnelProvider.d.ts +3 -1
- package/dist/tunnel/SakuraFrpTunnelProvider.js +7 -3
- package/dist/tunnel/TunnelClientManager.d.ts +73 -0
- package/dist/tunnel/TunnelClientManager.js +181 -0
- package/dist/tunnel/TunnelClientResolver.d.ts +56 -0
- package/dist/tunnel/TunnelClientResolver.js +135 -0
- package/dist/tunnel/TunnelDeclaredOrigin.d.ts +78 -0
- package/dist/tunnel/TunnelDeclaredOrigin.js +185 -0
- package/dist/tunnel/TunnelLifecycle.d.ts +9 -1
- package/dist/tunnel/TunnelLifecycle.js +24 -3
- package/dist/tunnel/TunnelProviderCatalog.d.ts +32 -0
- package/dist/tunnel/TunnelProviderCatalog.js +43 -0
- package/dist/util/identifiers/ClusterIdentifierStrategy.d.ts +1 -0
- package/dist/util/identifiers/ClusterIdentifierStrategy.js +3 -3
- package/node_modules/@inrupt/solid-client-authn-core/dist/authenticatedFetch/dpopUtils.d.ts +3 -1
- package/node_modules/@inrupt/solid-client-authn-core/dist/index.js +85 -58
- package/node_modules/@inrupt/solid-client-authn-core/dist/index.mjs +86 -59
- package/node_modules/@undefineds.co/ai-connections/dist/AiApiKeyPool.d.ts +3 -3
- package/node_modules/@undefineds.co/ai-connections/dist/AiApiKeyPool.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiAuthorizationActions.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiClientConfigurationSection.d.ts +2 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiClientConfigurationSection.js +39 -10
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectDialog.d.ts +5 -5
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectDialog.js +9 -8
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsHeader.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsHeader.js +4 -4
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsList.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsList.js +7 -6
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMain.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMain.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMainHeader.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.d.ts +6 -5
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +10 -8
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.d.ts +3 -3
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.js +11 -36
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialRow.d.ts +5 -3
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialRow.js +16 -4
- package/node_modules/@undefineds.co/ai-connections/dist/AiCustomProviderDialog.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiCustomProviderDialog.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiEndpointList.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.d.ts +10 -3
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.js +14 -5
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.d.ts +5 -4
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +84 -30
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayModelsSection.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayModelsSection.js +4 -4
- package/node_modules/@undefineds.co/ai-connections/dist/AiModelCatalog.d.ts +11 -5
- package/node_modules/@undefineds.co/ai-connections/dist/AiModelCatalog.js +16 -7
- package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.js +2 -4
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.d.ts +4 -4
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.js +14 -9
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.d.ts +2 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiQuotaCard.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiQuotaCard.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiSortableCredentialList.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/authorization-methods.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/client-visuals.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/collection-runtime.d.ts +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/collections.d.ts +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/collections.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/contract/ai-connections-client.d.ts +6 -6
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.js +9 -10
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/request.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/types.d.ts +8 -1
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client-config/base-adapter.d.ts +3 -3
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client-config/codex.d.ts +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client-config/index.cjs +42 -40
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client-config/index.d.ts +6 -6
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client-config/json-env-adapter.d.ts +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client-config/pi.d.ts +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client-config/transaction.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/contract/index.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/contract/provider-catalog.cjs +28 -15
- package/node_modules/@undefineds.co/ai-connections/dist/contract/provider-catalog.d.ts +4 -4
- package/node_modules/@undefineds.co/ai-connections/dist/contract/provider-catalog.js +18 -7
- package/node_modules/@undefineds.co/ai-connections/dist/controller.d.ts +5 -4
- package/node_modules/@undefineds.co/ai-connections/dist/controller.js +24 -9
- package/node_modules/@undefineds.co/ai-connections/dist/credential-labels.d.ts +5 -1
- package/node_modules/@undefineds.co/ai-connections/dist/credential-labels.js +24 -0
- package/node_modules/@undefineds.co/ai-connections/dist/display-wording.d.ts +2 -7
- package/node_modules/@undefineds.co/ai-connections/dist/display-wording.js +4 -25
- package/node_modules/@undefineds.co/ai-connections/dist/error-wording.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/error-wording.js +5 -1
- package/node_modules/@undefineds.co/ai-connections/dist/gateway-endpoints.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/index.d.ts +25 -25
- package/node_modules/@undefineds.co/ai-connections/dist/offering-endpoints.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/offering-label.d.ts +3 -1
- package/node_modules/@undefineds.co/ai-connections/dist/offering-label.js +7 -1
- package/node_modules/@undefineds.co/ai-connections/dist/provider-visuals.d.ts +4 -3
- package/node_modules/@undefineds.co/ai-connections/dist/provider-visuals.js +3 -2
- package/node_modules/@undefineds.co/ai-connections/dist/useAiConnectDialog.d.ts +3 -2
- package/node_modules/@undefineds.co/ai-connections/dist/useAiConnectDialog.js +18 -5
- package/node_modules/@undefineds.co/ai-connections/package.json +2 -2
- package/node_modules/@undefineds.co/drizzle-solid/dist/core/query-builders/select-query-builder.js +3 -0
- package/node_modules/@undefineds.co/drizzle-solid/dist/core/subject/resolver.js +2 -3
- package/node_modules/@undefineds.co/drizzle-solid/dist/core/triple/builder.js +2 -5
- package/node_modules/@undefineds.co/drizzle-solid/dist/core/uri/resolver.d.ts +2 -0
- package/node_modules/@undefineds.co/drizzle-solid/dist/core/uri/resolver.js +12 -3
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/query-builders/select-query-builder.js +3 -0
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/subject/resolver.js +2 -3
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/triple/builder.js +2 -5
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/uri/resolver.js +11 -3
- package/node_modules/@undefineds.co/drizzle-solid/package.json +1 -1
- package/node_modules/@undefineds.co/extension-sdk/dist/index.d.ts +6 -5
- package/node_modules/@undefineds.co/extension-sdk/dist/index.js +1 -0
- package/node_modules/@undefineds.co/extension-sdk/dist/layout.d.ts +39 -0
- package/node_modules/@undefineds.co/extension-sdk/dist/layout.js +40 -0
- package/node_modules/@undefineds.co/extension-sdk/dist/react/app-layout.d.ts +13 -1
- package/node_modules/@undefineds.co/extension-sdk/dist/react/app-layout.js +11 -3
- package/node_modules/@undefineds.co/extension-sdk/dist/react/solid-auth-boundary.d.ts +20 -2
- package/node_modules/@undefineds.co/extension-sdk/dist/react/solid-auth-boundary.js +142 -125
- package/node_modules/@undefineds.co/extension-sdk/dist/react/workspace-layout.d.ts +29 -5
- package/node_modules/@undefineds.co/extension-sdk/dist/react/workspace-layout.js +77 -13
- package/node_modules/@undefineds.co/extension-sdk/dist/react.d.ts +5 -5
- package/node_modules/@undefineds.co/extension-sdk/dist/shell-state.d.ts +55 -0
- package/node_modules/@undefineds.co/extension-sdk/dist/shell-state.js +1 -0
- package/node_modules/@undefineds.co/extension-sdk/dist/solid-permissions.d.ts +1 -1
- package/node_modules/@undefineds.co/extension-sdk/dist/testing.d.ts +1 -1
- package/node_modules/@undefineds.co/extension-sdk/dist/web.d.ts +6 -6
- package/node_modules/@undefineds.co/extension-sdk/package.json +2 -2
- package/node_modules/@undefineds.co/extensions/dist-cjs/adapters/langchain.js +49 -0
- package/node_modules/@undefineds.co/extensions/dist-cjs/adapters/llamaindex.js +54 -0
- package/node_modules/@undefineds.co/extensions/dist-cjs/index.js +22 -0
- package/node_modules/@undefineds.co/extensions/dist-cjs/package.json +3 -0
- package/node_modules/@undefineds.co/extensions/dist-cjs/paddleocr.js +304 -0
- package/node_modules/@undefineds.co/extensions/dist-cjs/reader.js +44 -0
- package/node_modules/@undefineds.co/extensions/dist-cjs/registry.js +99 -0
- package/node_modules/@undefineds.co/extensions/dist-cjs/types.js +2 -0
- package/node_modules/@undefineds.co/models/dist/approval.repository.d.ts +20 -0
- package/node_modules/@undefineds.co/models/dist/approval.repository.js +81 -0
- package/node_modules/@undefineds.co/models/dist/credential.schema.d.ts +12 -0
- package/node_modules/@undefineds.co/models/dist/credential.schema.js +5 -0
- package/node_modules/@undefineds.co/models/dist/index.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/index.js +1 -1
- package/node_modules/@undefineds.co/models/dist/namespaces.js +3 -0
- package/node_modules/@undefineds.co/models/dist/pod-storage-descriptor.d.ts +50 -0
- package/node_modules/@undefineds.co/models/dist/pod-storage-descriptor.js +16 -1
- package/node_modules/@undefineds.co/models/dist/schema.d.ts +10 -0
- package/node_modules/@undefineds.co/models/dist/task.schema.d.ts +6 -0
- package/node_modules/@undefineds.co/models/dist/task.schema.js +3 -0
- package/node_modules/@undefineds.co/models/package.json +2 -2
- package/node_modules/@undefineds.co/pod-collections/dist/index.cjs +33 -33
- package/node_modules/@undefineds.co/pod-collections/package.json +2 -2
- package/node_modules/@undefineds.co/shared-ui/dist/auth-surface.js +6 -6
- package/node_modules/@undefineds.co/shared-ui/dist/badge.d.ts +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/badge.js +2 -0
- package/node_modules/@undefineds.co/shared-ui/dist/brand-info.d.ts +9 -0
- package/node_modules/@undefineds.co/shared-ui/dist/brand-info.js +19 -0
- package/node_modules/@undefineds.co/shared-ui/dist/button.js +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/checkbox.d.ts +6 -0
- package/node_modules/@undefineds.co/shared-ui/dist/checkbox.js +16 -0
- package/node_modules/@undefineds.co/shared-ui/dist/confirmation-dialog.d.ts +16 -0
- package/node_modules/@undefineds.co/shared-ui/dist/confirmation-dialog.js +22 -0
- package/node_modules/@undefineds.co/shared-ui/dist/dialog.d.ts +3 -0
- package/node_modules/@undefineds.co/shared-ui/dist/dialog.js +5 -5
- package/node_modules/@undefineds.co/shared-ui/dist/email-input.d.ts +9 -0
- package/node_modules/@undefineds.co/shared-ui/dist/email-input.js +42 -0
- package/node_modules/@undefineds.co/shared-ui/dist/empty-state.d.ts +8 -0
- package/node_modules/@undefineds.co/shared-ui/dist/empty-state.js +6 -0
- package/node_modules/@undefineds.co/shared-ui/dist/focus.d.ts +3 -4
- package/node_modules/@undefineds.co/shared-ui/dist/focus.js +3 -4
- package/node_modules/@undefineds.co/shared-ui/dist/form-control.d.ts +2 -0
- package/node_modules/@undefineds.co/shared-ui/dist/form-control.js +3 -0
- package/node_modules/@undefineds.co/shared-ui/dist/form-field.d.ts +15 -0
- package/node_modules/@undefineds.co/shared-ui/dist/form-field.js +11 -0
- package/node_modules/@undefineds.co/shared-ui/dist/index.d.ts +45 -27
- package/node_modules/@undefineds.co/shared-ui/dist/index.js +18 -0
- package/node_modules/@undefineds.co/shared-ui/dist/input.js +2 -2
- package/node_modules/@undefineds.co/shared-ui/dist/list.d.ts +25 -0
- package/node_modules/@undefineds.co/shared-ui/dist/list.js +21 -0
- package/node_modules/@undefineds.co/shared-ui/dist/login/LocalReachabilitySummary.d.ts +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/login/LoginModal.d.ts +3 -1
- package/node_modules/@undefineds.co/shared-ui/dist/login/LoginModal.js +2 -0
- package/node_modules/@undefineds.co/shared-ui/dist/login/LoginView.d.ts +4 -1
- package/node_modules/@undefineds.co/shared-ui/dist/login/LoginView.js +3 -0
- package/node_modules/@undefineds.co/shared-ui/dist/login/error-messages.d.ts +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/login/index.d.ts +5 -5
- package/node_modules/@undefineds.co/shared-ui/dist/login/presentation.d.ts +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/login/provider-model.d.ts +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/login/types.d.ts +3 -3
- package/node_modules/@undefineds.co/shared-ui/dist/login.d.ts +16 -1
- package/node_modules/@undefineds.co/shared-ui/dist/login.js +16 -1
- package/node_modules/@undefineds.co/shared-ui/dist/meter.d.ts +24 -0
- package/node_modules/@undefineds.co/shared-ui/dist/meter.js +22 -0
- package/node_modules/@undefineds.co/shared-ui/dist/native-select.d.ts +5 -0
- package/node_modules/@undefineds.co/shared-ui/dist/native-select.js +7 -0
- package/node_modules/@undefineds.co/shared-ui/dist/notice.d.ts +25 -0
- package/node_modules/@undefineds.co/shared-ui/dist/notice.js +32 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/AccountSections.d.ts +148 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/AccountSections.js +73 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/ConsentView.d.ts +55 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/ConsentView.js +27 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/DeviceDialogs.d.ts +40 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/DeviceDialogs.js +33 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.d.ts +15 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.js +8 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpViews.d.ts +93 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpViews.js +89 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/NetworkPanel.d.ts +46 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/NetworkPanel.js +42 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignIn.d.ts +65 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignIn.js +65 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.d.ts +31 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.js +111 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/StorageBadge.d.ts +8 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/StorageBadge.js +7 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/XpodMark.d.ts +8 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/XpodMark.js +8 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/account-parts.d.ts +37 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/account-parts.js +33 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/copy.d.ts +161 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/copy.js +314 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/index.d.ts +20 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/index.js +18 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.d.ts +60 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.js +63 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/types.d.ts +14 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/types.js +1 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/webid-name.d.ts +5 -0
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/webid-name.js +14 -0
- package/node_modules/@undefineds.co/shared-ui/dist/search-input.d.ts +5 -0
- package/node_modules/@undefineds.co/shared-ui/dist/search-input.js +8 -0
- package/node_modules/@undefineds.co/shared-ui/dist/section-header.d.ts +13 -0
- package/node_modules/@undefineds.co/shared-ui/dist/section-header.js +10 -0
- package/node_modules/@undefineds.co/shared-ui/dist/segmented-control.d.ts +30 -0
- package/node_modules/@undefineds.co/shared-ui/dist/segmented-control.js +81 -0
- package/node_modules/@undefineds.co/shared-ui/dist/select.d.ts +10 -0
- package/node_modules/@undefineds.co/shared-ui/dist/select.js +20 -0
- package/node_modules/@undefineds.co/shared-ui/dist/setting-row.d.ts +23 -0
- package/node_modules/@undefineds.co/shared-ui/dist/setting-row.js +14 -0
- package/node_modules/@undefineds.co/shared-ui/dist/status.d.ts +35 -0
- package/node_modules/@undefineds.co/shared-ui/dist/status.js +29 -0
- package/node_modules/@undefineds.co/shared-ui/dist/storage-bootstrap.d.ts +3 -0
- package/node_modules/@undefineds.co/shared-ui/dist/storage-bootstrap.js +3 -0
- package/node_modules/@undefineds.co/shared-ui/dist/textarea.d.ts +4 -0
- package/node_modules/@undefineds.co/shared-ui/dist/textarea.js +6 -0
- package/node_modules/@undefineds.co/shared-ui/dist/theme.css +261 -83
- package/node_modules/@undefineds.co/shared-ui/dist/toast.js +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/tooltip.d.ts +2 -1
- package/node_modules/@undefineds.co/shared-ui/dist/tooltip.js +3 -2
- package/node_modules/@undefineds.co/shared-ui/dist/webid-auth.d.ts +5 -0
- package/node_modules/@undefineds.co/shared-ui/dist/webid-auth.js +5 -0
- package/node_modules/@undefineds.co/shared-ui/dist/workspace.d.ts +14 -0
- package/node_modules/@undefineds.co/shared-ui/dist/workspace.js +14 -0
- package/node_modules/@undefineds.co/shared-ui/package.json +3 -2
- package/node_modules/@undefineds.co/solid-sdk/dist/access-route.cjs +13 -9
- package/node_modules/@undefineds.co/solid-sdk/dist/access-route.d.ts +2 -1
- package/node_modules/@undefineds.co/solid-sdk/dist/access-route.js +20 -10
- package/node_modules/@undefineds.co/solid-sdk/dist/index.bun.js +9 -0
- package/node_modules/@undefineds.co/solid-sdk/dist/index.cjs +177 -101
- package/node_modules/@undefineds.co/solid-sdk/dist/index.d.ts +8 -8
- package/node_modules/@undefineds.co/solid-sdk/dist/local-route-fetch.cjs +61 -17
- package/node_modules/@undefineds.co/solid-sdk/dist/local-route-fetch.d.ts +23 -0
- package/node_modules/@undefineds.co/solid-sdk/dist/local-route-fetch.js +73 -11
- package/node_modules/@undefineds.co/solid-sdk/dist/react.d.ts +2 -2
- package/node_modules/@undefineds.co/solid-sdk/dist/session.cjs +333 -0
- package/node_modules/@undefineds.co/solid-sdk/dist/session.js +54 -25
- package/node_modules/@undefineds.co/solid-sdk/dist/storage-selection.d.ts +2 -2
- package/node_modules/@undefineds.co/solid-sdk/package.json +4 -2
- package/node_modules/jose/package.json +120 -30
- package/node_modules/openid-client/node_modules/jose/package.json +1 -1
- package/node_modules/openid-client/types/index.d.ts +623 -0
- package/package.json +13 -7
- package/scripts/patch-jose.js +5 -3
- package/static/app/assets/index-hMwukuNA.js +230 -0
- package/static/app/assets/inrupt-smoke.js +57 -56
- package/static/app/assets/main.css +1 -1
- package/static/app/assets/main.js +54 -14
- package/static/app/auth.html +2 -2
- package/static/app/brand/xpod-app-16.svg +1 -0
- package/static/app/brand/xpod-app-24.svg +1 -0
- package/static/app/index.html +3 -3
- package/static/app/inrupt-smoke.html +2 -1
- package/static/dashboard/assets/AccountAuthBoundary-BvoDydRz.js +1 -0
- package/static/dashboard/assets/DesktopOidcCallback-BwIj874x.js +1 -0
- package/static/dashboard/assets/DevicePages-jOjMcvsr.js +2 -0
- package/static/dashboard/assets/ModelsPage-CMTdfqBR.js +11 -0
- package/static/dashboard/assets/PaneListHeader-Dn5O0mwy.js +1 -0
- package/static/dashboard/assets/PodDeletionAuthorizationPanel-D3NOG6ZM.js +42 -0
- package/static/dashboard/assets/PodPage-BueBdJ9_.js +1 -0
- package/static/dashboard/assets/SystemSettingsPage-BNQP_Yuc.js +1 -0
- package/static/dashboard/assets/TasksPage-CxtLJiSF.js +1 -0
- package/static/dashboard/assets/TasksPage-DPpAgn4C.css +1 -0
- package/static/dashboard/assets/WebDesktopEntry-vnb4CZWp.js +1 -0
- package/static/dashboard/assets/XpodAiConnectionsPodStore-wx3Ttupm.js +18 -0
- package/static/dashboard/assets/XpodShellApp-5FWY8-d5.js +4 -0
- package/static/dashboard/assets/XpodShellApp-Bwom2xL3.css +1 -0
- package/static/dashboard/assets/account-session-DCUmCop1.js +1 -0
- package/static/dashboard/assets/button-By5Bgvmb.js +1 -0
- package/static/dashboard/assets/collection-runtime-BnomuB0E.js +1 -0
- package/static/dashboard/assets/createLucideIcon-bunMzPms.js +1 -0
- package/static/dashboard/assets/dashboard-C64R553B.css +1 -0
- package/static/dashboard/assets/dashboard-mlsg3yaw.js +12 -0
- package/static/dashboard/assets/index-DvMG5pHk.js +20 -0
- package/static/dashboard/assets/label-Bj03L9xs.js +1 -0
- package/static/dashboard/assets/nav-item-style-BNqWQY6p.js +1 -0
- package/static/dashboard/assets/safe-continuation-D9AhcWiB.js +1 -0
- package/static/dashboard/assets/section-header-CLCzbOp_.js +1 -0
- package/static/dashboard/assets/setting-row-DTCec8A2.js +1 -0
- package/static/dashboard/assets/xpod-remembered-login-Dr69A0Rv.js +295 -0
- package/static/dashboard/auth.html +2 -2
- package/static/dashboard/brand/xpod-app-16.svg +1 -0
- package/static/dashboard/brand/xpod-app-24.svg +1 -0
- package/static/dashboard/dashboard.html +4 -3
- package/static/settings/assets/AccountAuthBoundary-C0og_gIA.js +1 -0
- package/static/settings/assets/DesktopOidcCallback-C5q4oFZ0.js +1 -0
- package/static/settings/assets/DevicePages-fyHjjucT.js +2 -0
- package/static/settings/assets/ModelsPage-EyOByLyE.js +11 -0
- package/static/settings/assets/PaneListHeader-DqVlMe2D.js +1 -0
- package/static/settings/assets/PodDeletionAuthorizationPanel-DgVvarVY.js +42 -0
- package/static/settings/assets/PodPage-DY4Oi9wg.js +1 -0
- package/static/settings/assets/SystemSettingsPage-Crzm_DrI.js +1 -0
- package/static/settings/assets/TasksPage-CfXJbnlt.js +1 -0
- package/static/settings/assets/TasksPage-DPpAgn4C.css +1 -0
- package/static/settings/assets/WebDesktopEntry-BGC5eRF2.js +1 -0
- package/static/settings/assets/XpodAiConnectionsPodStore-CXcmgKmQ.js +3 -0
- package/static/settings/assets/XpodShellApp-Bwom2xL3.css +1 -0
- package/static/settings/assets/XpodShellApp-D1PS3Iut.js +4 -0
- package/static/settings/assets/XpodThemeProvider-C64R553B.css +1 -0
- package/static/settings/assets/XpodThemeProvider-CB6LepTA.js +12 -0
- package/static/settings/assets/account-session-BcLjCj0x.js +1 -0
- package/static/settings/assets/auth-callback-DSPQ28ar.js +1 -0
- package/static/settings/assets/button-BObT8pTE.js +1 -0
- package/static/settings/assets/collection-runtime-DzNbdZGe.js +1 -0
- package/static/settings/assets/createLucideIcon-BVsUxXpZ.js +1 -0
- package/static/settings/assets/index-browser-3WfrNbcG.js +273 -0
- package/static/settings/assets/index-ktjMkj7-.js +20 -0
- package/static/settings/assets/label-BrqO8_m_.js +1 -0
- package/static/settings/assets/nav-item-style-Di2CxkDU.js +1 -0
- package/static/settings/assets/safe-continuation-Dx6ceJpY.js +1 -0
- package/static/settings/assets/section-header-Dtl7yjVr.js +1 -0
- package/static/settings/assets/setting-row-BL6Hhe8N.js +1 -0
- package/static/settings/assets/settings-DaRBxoZk.js +1 -0
- package/static/settings/assets/xpod-remembered-login-Q66DH12t.js +295 -0
- package/static/settings/auth-callback.html +4 -3
- package/static/settings/auth.html +2 -2
- package/static/settings/brand/xpod-app-16.svg +1 -0
- package/static/settings/brand/xpod-app-24.svg +1 -0
- package/static/settings/settings.html +5 -4
- package/node_modules/@solid/access-token-verifier/node_modules/n3/browser/n3.min.js +0 -1
- package/node_modules/@solid/community-server/node_modules/n3/browser/n3.min.js +0 -1
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/aggregates.d.ts +0 -19
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/ast-to-sparql.d.ts +0 -66
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/compile-time-types.d.ts +0 -40
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/comunica-patch.d.ts +0 -2
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/conflict-resolution.d.ts +0 -110
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/discovery/composite-discovery.d.ts +0 -18
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/discovery/index.d.ts +0 -7
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/discovery/interop-discovery.d.ts +0 -36
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/discovery/interop-tables.d.ts +0 -37
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/discovery/interop-types.d.ts +0 -36
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/discovery/provider-cache.d.ts +0 -99
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/discovery/typeindex-discovery.d.ts +0 -32
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/discovery/types.d.ts +0 -132
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/exact-records.d.ts +0 -21
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/execution/index.d.ts +0 -14
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/execution/ldp-executor.d.ts +0 -76
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/execution/ldp-strategy.d.ts +0 -53
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/execution/pod-executor-types.d.ts +0 -9
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/execution/pod-executor.d.ts +0 -73
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/execution/sparql-strategy.d.ts +0 -31
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/execution/strategy-factory.d.ts +0 -42
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/execution/types.d.ts +0 -85
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/expressions.d.ts +0 -40
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/federated/executor.d.ts +0 -98
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/federated/index.d.ts +0 -3
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/federated/types.d.ts +0 -69
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/notifications/channels/base-channel.d.ts +0 -29
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/notifications/channels/index.d.ts +0 -4
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/notifications/channels/sse-channel.d.ts +0 -50
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/notifications/channels/websocket-channel.d.ts +0 -16
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/notifications/index.d.ts +0 -3
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/notifications/notifications-client.d.ts +0 -88
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/notifications/types.d.ts +0 -228
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/order-by.d.ts +0 -9
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/pod-database.d.ts +0 -548
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/pod-dialect.d.ts +0 -324
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/pod-discovery.d.ts +0 -20
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/pod-session.d.ts +0 -52
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/profile-manager.d.ts +0 -90
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/query-builders/default-id-template.d.ts +0 -10
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/query-builders/delete-query-builder.d.ts +0 -31
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/query-builders/helpers.d.ts +0 -11
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/query-builders/index.d.ts +0 -7
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/query-builders/insert-query-builder.d.ts +0 -37
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/query-builders/select-query-builder.d.ts +0 -150
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/query-builders/types.d.ts +0 -40
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/query-builders/update-query-builder.d.ts +0 -34
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/query-conditions.d.ts +0 -60
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/query-where-policy.d.ts +0 -8
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/rdf-constants.d.ts +0 -16
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/rdf-schema-parser.d.ts +0 -34
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/repository.d.ts +0 -78
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/resource-reference.d.ts +0 -31
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/resource-resolver/base-resolver.d.ts +0 -141
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/resource-resolver/document-resolver.d.ts +0 -36
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/resource-resolver/factory.d.ts +0 -27
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/resource-resolver/fragment-resolver.d.ts +0 -34
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/resource-resolver/index.d.ts +0 -11
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/resource-resolver/types.d.ts +0 -57
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/runtime/pod-runtime.d.ts +0 -60
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/schema/columns.d.ts +0 -74
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/schema/defs.d.ts +0 -101
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/schema/factories.d.ts +0 -29
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/schema/index.d.ts +0 -9
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/schema/pod-table.d.ts +0 -118
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/schema/relations.d.ts +0 -26
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/schema/solid-schema.d.ts +0 -22
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/schema/types.d.ts +0 -45
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/schema/utils.d.ts +0 -15
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/select-plan.d.ts +0 -50
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/services/pod-services.d.ts +0 -43
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/shape/generator.d.ts +0 -12
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/shape/index.d.ts +0 -4
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/shape/manager.d.ts +0 -45
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/shape/shacl-parser.d.ts +0 -19
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/shape/shacl.d.ts +0 -11
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/shape/types.d.ts +0 -149
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/shape/validator.d.ts +0 -11
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/solid-n3-client.d.ts +0 -86
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/sparql/builder/expression-builder.d.ts +0 -56
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/sparql/builder/select-builder.d.ts +0 -44
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/sparql/builder/update-builder.d.ts +0 -33
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/sparql/helpers.d.ts +0 -19
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/sparql/types.d.ts +0 -10
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/sparql-engine.d.ts +0 -16
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/sparql-executor.d.ts +0 -40
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/subject/index.d.ts +0 -29
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/subject/resolver.d.ts +0 -116
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/subject/types.d.ts +0 -97
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/triple/builder.d.ts +0 -86
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/triple/handlers/array.d.ts +0 -23
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/triple/handlers/default.d.ts +0 -20
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/triple/handlers/index.d.ts +0 -35
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/triple/handlers/inline.d.ts +0 -35
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/triple/handlers/inverse.d.ts +0 -26
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/triple/handlers/uri.d.ts +0 -28
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/triple/index.d.ts +0 -9
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/triple/types.d.ts +0 -156
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/typeindex-manager.d.ts +0 -130
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/types.d.ts +0 -57
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/uri/index.d.ts +0 -8
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/uri/resolver.d.ts +0 -153
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/uri/types.d.ts +0 -154
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/utils/debug-logger.d.ts +0 -19
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/utils/origin-auth.d.ts +0 -28
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/utils/pod-root.d.ts +0 -15
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/core/zod-integration.d.ts +0 -97
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/driver.d.ts +0 -60
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/index.d.ts +0 -31
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/pod.d.ts +0 -140
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/solid.d.ts +0 -21
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/test-utils/real-test-helpers.d.ts +0 -5
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/types/sparql-types.d.ts +0 -27
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/utils/find-by-iri.d.ts +0 -11
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/utils/helpers.d.ts +0 -17
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/utils/namespace.d.ts +0 -4
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/utils/rdf-helpers.d.ts +0 -17
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/utils/rdf-validation.d.ts +0 -27
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/utils/thing-operations.d.ts +0 -28
- package/node_modules/@undefineds.co/drizzle-solid/dist/esm/utils/webid-resolver.d.ts +0 -23
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/index.ts +0 -4
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/locales/index.ts +0 -1
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/mini/index.ts +0 -3
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/ZodError.ts +0 -330
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/benchmarks/datetime.ts +0 -58
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts +0 -80
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/benchmarks/index.ts +0 -59
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/benchmarks/ipv4.ts +0 -57
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/benchmarks/object.ts +0 -69
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/benchmarks/primitives.ts +0 -162
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/benchmarks/realworld.ts +0 -63
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/benchmarks/string.ts +0 -55
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/benchmarks/union.ts +0 -80
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/errors.ts +0 -13
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/external.ts +0 -6
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/helpers/enumUtil.ts +0 -17
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/helpers/errorUtil.ts +0 -8
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/helpers/parseUtil.ts +0 -176
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/helpers/partialUtil.ts +0 -34
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/helpers/typeAliases.ts +0 -2
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/helpers/util.ts +0 -224
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/index.ts +0 -4
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/locales/en.ts +0 -124
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/standard-schema.ts +0 -113
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/Mocker.ts +0 -54
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/all-errors.test.ts +0 -157
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/anyunknown.test.ts +0 -28
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/array.test.ts +0 -71
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/async-parsing.test.ts +0 -388
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/async-refinements.test.ts +0 -46
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/base.test.ts +0 -29
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/bigint.test.ts +0 -55
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/branded.test.ts +0 -53
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/catch.test.ts +0 -220
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/coerce.test.ts +0 -133
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/complex.test.ts +0 -70
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/custom.test.ts +0 -31
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/date.test.ts +0 -32
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/deepmasking.test.ts +0 -186
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/default.test.ts +0 -112
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/description.test.ts +0 -33
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/discriminated-unions.test.ts +0 -315
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/enum.test.ts +0 -80
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/error.test.ts +0 -551
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/firstparty.test.ts +0 -87
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts +0 -21
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/function.test.ts +0 -261
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/generics.test.ts +0 -48
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/instanceof.test.ts +0 -37
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/intersection.test.ts +0 -110
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/language-server.source.ts +0 -76
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/language-server.test.ts +0 -207
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/literal.test.ts +0 -36
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/map.test.ts +0 -110
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/masking.test.ts +0 -4
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/mocker.test.ts +0 -19
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/nan.test.ts +0 -24
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/nativeEnum.test.ts +0 -87
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/nullable.test.ts +0 -42
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/number.test.ts +0 -176
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/object-augmentation.test.ts +0 -29
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts +0 -29
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/object.test.ts +0 -434
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/optional.test.ts +0 -42
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/parseUtil.test.ts +0 -23
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/parser.test.ts +0 -41
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/partials.test.ts +0 -243
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/pickomit.test.ts +0 -111
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/pipeline.test.ts +0 -29
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/preprocess.test.ts +0 -186
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/primitive.test.ts +0 -440
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/promise.test.ts +0 -90
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/readonly.test.ts +0 -194
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/record.test.ts +0 -171
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/recursive.test.ts +0 -197
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/refine.test.ts +0 -313
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/safeparse.test.ts +0 -27
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/set.test.ts +0 -142
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/standard-schema.test.ts +0 -83
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/string.test.ts +0 -916
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/transformer.test.ts +0 -233
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/tuple.test.ts +0 -90
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/unions.test.ts +0 -57
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/validations.test.ts +0 -133
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/tests/void.test.ts +0 -15
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v3/types.ts +0 -5138
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/checks.ts +0 -32
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/coerce.ts +0 -27
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/compat.ts +0 -70
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/errors.ts +0 -82
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/external.ts +0 -52
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/from-json-schema.ts +0 -659
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/index.ts +0 -5
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/iso.ts +0 -90
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/parse.ts +0 -82
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/schemas.ts +0 -2672
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/anyunknown.test.ts +0 -26
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/apply.test.ts +0 -59
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/array.test.ts +0 -264
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/assignability.test.ts +0 -216
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/async-parsing.test.ts +0 -381
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/async-refinements.test.ts +0 -68
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/base.test.ts +0 -7
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/bigint.test.ts +0 -54
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/brand.test.ts +0 -106
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/catch.test.ts +0 -326
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/coalesce.test.ts +0 -20
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/codec-examples.test.ts +0 -573
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/codec.test.ts +0 -703
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/coerce.test.ts +0 -160
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/continuability.test.ts +0 -374
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/custom.test.ts +0 -40
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/date.test.ts +0 -62
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/datetime.test.ts +0 -302
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/default.test.ts +0 -409
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/describe-meta-checks.test.ts +0 -27
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/description.test.ts +0 -32
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/detached-methods.test.ts +0 -197
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts +0 -694
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/enum.test.ts +0 -285
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/error-utils.test.ts +0 -807
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/error.test.ts +0 -711
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/file.test.ts +0 -96
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/firstparty.test.ts +0 -179
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/fix-json-issue.test.ts +0 -26
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/from-json-schema.test.ts +0 -895
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/function.test.ts +0 -360
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/generics.test.ts +0 -72
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/global-config.test.ts +0 -39
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/hash.test.ts +0 -68
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/index.test.ts +0 -939
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/instanceof.test.ts +0 -60
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/intersection.test.ts +0 -198
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/jitless-allows-eval.test.ts +0 -46
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/json.test.ts +0 -109
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/lazy.test.ts +0 -227
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/literal.test.ts +0 -117
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/locales_ka.test.ts +0 -29
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/locales_ro.test.ts +0 -24
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/map.test.ts +0 -330
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/nan.test.ts +0 -21
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/nested-refine.test.ts +0 -168
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/nonoptional.test.ts +0 -101
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/nullable.test.ts +0 -22
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/number.test.ts +0 -325
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/object.test.ts +0 -717
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/optional.test.ts +0 -333
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/partial.test.ts +0 -450
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/pickomit.test.ts +0 -211
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/pipe.test.ts +0 -101
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/prefault.test.ts +0 -74
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/preprocess-types.test.ts +0 -26
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/preprocess.test.ts +0 -351
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/primitive.test.ts +0 -175
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/promise.test.ts +0 -81
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/prototypes.test.ts +0 -23
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/readonly.test.ts +0 -252
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/record.test.ts +0 -717
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts +0 -631
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/refine.test.ts +0 -633
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/registries.test.ts +0 -243
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/set.test.ts +0 -181
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/standard-schema.test.ts +0 -134
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/string-formats.test.ts +0 -125
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/string.test.ts +0 -1224
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/stringbool.test.ts +0 -106
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/template-literal.test.ts +0 -771
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/to-json-schema-methods.test.ts +0 -438
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts +0 -3125
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/transform.test.ts +0 -378
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/tuple.test.ts +0 -496
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/union.test.ts +0 -273
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/url.test.ts +0 -13
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/validations.test.ts +0 -283
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/classic/tests/void.test.ts +0 -12
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/api.ts +0 -1823
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/checks.ts +0 -1293
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/config.ts +0 -15
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/core.ts +0 -153
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/doc.ts +0 -44
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/errors.ts +0 -455
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/index.ts +0 -16
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/json-schema-generator.ts +0 -126
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/json-schema-processors.ts +0 -666
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/json-schema.ts +0 -147
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/parse.ts +0 -195
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/regexes.ts +0 -190
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/registries.ts +0 -105
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/schemas.ts +0 -4730
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/standard-schema.ts +0 -159
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/extend.test.ts +0 -59
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/index.test.ts +0 -46
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/locales/be.test.ts +0 -124
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/locales/el.test.ts +0 -215
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/locales/en.test.ts +0 -22
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/locales/es.test.ts +0 -181
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/locales/fr.test.ts +0 -72
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/locales/he.test.ts +0 -379
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/locales/hr.test.ts +0 -163
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/locales/nl.test.ts +0 -46
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/locales/ru.test.ts +0 -128
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/locales/tr.test.ts +0 -69
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/locales/uz.test.ts +0 -105
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/record-constructor.test.ts +0 -125
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/tests/recursive-tuples.test.ts +0 -45
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/to-json-schema.ts +0 -622
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/util.ts +0 -983
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/versions.ts +0 -5
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/core/zsf.ts +0 -323
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/index.ts +0 -4
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ar.ts +0 -115
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/az.ts +0 -111
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/be.ts +0 -176
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/bg.ts +0 -128
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ca.ts +0 -116
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/cs.ts +0 -118
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/da.ts +0 -123
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/de.ts +0 -116
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/el.ts +0 -121
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/en.ts +0 -123
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/eo.ts +0 -118
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/es.ts +0 -141
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/fa.ts +0 -126
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/fi.ts +0 -121
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/fr-CA.ts +0 -116
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/fr.ts +0 -132
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/he.ts +0 -246
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/hr.ts +0 -131
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/hu.ts +0 -117
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/hy.ts +0 -164
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/id.ts +0 -115
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/index.ts +0 -52
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/is.ts +0 -119
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/it.ts +0 -116
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ja.ts +0 -114
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ka.ts +0 -123
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/kh.ts +0 -7
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/km.ts +0 -119
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ko.ts +0 -121
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/lt.ts +0 -239
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/mk.ts +0 -118
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ms.ts +0 -115
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/nl.ts +0 -121
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/no.ts +0 -116
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ota.ts +0 -117
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/pl.ts +0 -118
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ps.ts +0 -126
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/pt.ts +0 -116
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ro.ts +0 -129
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ru.ts +0 -176
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/sl.ts +0 -118
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/sv.ts +0 -119
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ta.ts +0 -118
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/th.ts +0 -119
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/tr.ts +0 -111
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ua.ts +0 -7
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/uk.ts +0 -117
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/ur.ts +0 -119
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/uz.ts +0 -117
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/vi.ts +0 -117
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/yo.ts +0 -124
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/zh-CN.ts +0 -116
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/locales/zh-TW.ts +0 -115
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/checks.ts +0 -32
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/coerce.ts +0 -27
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/external.ts +0 -41
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/index.ts +0 -3
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/iso.ts +0 -66
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/parse.ts +0 -14
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/schemas.ts +0 -1947
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/apply.test.ts +0 -24
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/assignability.test.ts +0 -129
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/brand.test.ts +0 -94
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/checks.test.ts +0 -144
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/codec.test.ts +0 -548
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/computed.test.ts +0 -36
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/error.test.ts +0 -22
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/functions.test.ts +0 -5
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/index.test.ts +0 -993
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/number.test.ts +0 -95
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/object.test.ts +0 -227
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/prototypes.test.ts +0 -43
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/recursive-types.test.ts +0 -325
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/standard-schema.test.ts +0 -50
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4/mini/tests/string.test.ts +0 -352
- package/node_modules/@undefineds.co/drizzle-solid/node_modules/zod/src/v4-mini/index.ts +0 -3
- package/node_modules/@undefineds.co/models/node_modules/n3/browser/n3.min.js +0 -1
- package/node_modules/jose/dist/browser/index.js +0 -30
- package/node_modules/jose/dist/browser/jwe/compact/decrypt.js +0 -27
- package/node_modules/jose/dist/browser/jwe/compact/encrypt.js +0 -26
- package/node_modules/jose/dist/browser/jwe/flattened/decrypt.js +0 -161
- package/node_modules/jose/dist/browser/jwe/flattened/encrypt.js +0 -153
- package/node_modules/jose/dist/browser/jwe/general/decrypt.js +0 -31
- package/node_modules/jose/dist/browser/jwe/general/encrypt.js +0 -174
- package/node_modules/jose/dist/browser/jwk/embedded.js +0 -17
- package/node_modules/jose/dist/browser/jwk/thumbprint.js +0 -53
- package/node_modules/jose/dist/browser/jwks/local.js +0 -124
- package/node_modules/jose/dist/browser/jwks/remote.js +0 -139
- package/node_modules/jose/dist/browser/jws/compact/sign.js +0 -17
- package/node_modules/jose/dist/browser/jws/compact/verify.js +0 -21
- package/node_modules/jose/dist/browser/jws/flattened/sign.js +0 -81
- package/node_modules/jose/dist/browser/jws/flattened/verify.js +0 -122
- package/node_modules/jose/dist/browser/jws/general/sign.js +0 -67
- package/node_modules/jose/dist/browser/jws/general/verify.js +0 -24
- package/node_modules/jose/dist/browser/jwt/decrypt.js +0 -23
- package/node_modules/jose/dist/browser/jwt/encrypt.js +0 -68
- package/node_modules/jose/dist/browser/jwt/produce.js +0 -75
- package/node_modules/jose/dist/browser/jwt/sign.js +0 -20
- package/node_modules/jose/dist/browser/jwt/unsecured.js +0 -32
- package/node_modules/jose/dist/browser/jwt/verify.js +0 -15
- package/node_modules/jose/dist/browser/key/export.js +0 -12
- package/node_modules/jose/dist/browser/key/generate_key_pair.js +0 -4
- package/node_modules/jose/dist/browser/key/generate_secret.js +0 -4
- package/node_modules/jose/dist/browser/key/import.js +0 -45
- package/node_modules/jose/dist/browser/lib/aesgcmkw.js +0 -16
- package/node_modules/jose/dist/browser/lib/buffer_utils.js +0 -51
- package/node_modules/jose/dist/browser/lib/cek.js +0 -20
- package/node_modules/jose/dist/browser/lib/check_iv_length.js +0 -8
- package/node_modules/jose/dist/browser/lib/check_key_type.js +0 -77
- package/node_modules/jose/dist/browser/lib/check_p2s.js +0 -6
- package/node_modules/jose/dist/browser/lib/crypto_key.js +0 -157
- package/node_modules/jose/dist/browser/lib/decrypt_key_management.js +0 -129
- package/node_modules/jose/dist/browser/lib/encrypt_key_management.js +0 -89
- package/node_modules/jose/dist/browser/lib/epoch.js +0 -1
- package/node_modules/jose/dist/browser/lib/format_pem.js +0 -4
- package/node_modules/jose/dist/browser/lib/invalid_key_input.js +0 -31
- package/node_modules/jose/dist/browser/lib/is_disjoint.js +0 -22
- package/node_modules/jose/dist/browser/lib/is_jwk.js +0 -13
- package/node_modules/jose/dist/browser/lib/is_object.js +0 -16
- package/node_modules/jose/dist/browser/lib/iv.js +0 -20
- package/node_modules/jose/dist/browser/lib/jwt_claims_set.js +0 -104
- package/node_modules/jose/dist/browser/lib/private_symbols.js +0 -1
- package/node_modules/jose/dist/browser/lib/secs.js +0 -55
- package/node_modules/jose/dist/browser/lib/validate_algorithms.js +0 -11
- package/node_modules/jose/dist/browser/lib/validate_crit.js +0 -34
- package/node_modules/jose/dist/browser/package.json +0 -1
- package/node_modules/jose/dist/browser/runtime/aeskw.js +0 -32
- package/node_modules/jose/dist/browser/runtime/asn1.js +0 -205
- package/node_modules/jose/dist/browser/runtime/base64url.js +0 -37
- package/node_modules/jose/dist/browser/runtime/bogus.js +0 -6
- package/node_modules/jose/dist/browser/runtime/check_cek_length.js +0 -8
- package/node_modules/jose/dist/browser/runtime/check_key_length.js +0 -8
- package/node_modules/jose/dist/browser/runtime/decrypt.js +0 -91
- package/node_modules/jose/dist/browser/runtime/digest.js +0 -6
- package/node_modules/jose/dist/browser/runtime/ecdhes.js +0 -47
- package/node_modules/jose/dist/browser/runtime/encrypt.js +0 -76
- package/node_modules/jose/dist/browser/runtime/fetch_jwks.js +0 -34
- package/node_modules/jose/dist/browser/runtime/generate.js +0 -143
- package/node_modules/jose/dist/browser/runtime/get_sign_verify_key.js +0 -24
- package/node_modules/jose/dist/browser/runtime/is_key_like.js +0 -8
- package/node_modules/jose/dist/browser/runtime/jwk_to_key.js +0 -104
- package/node_modules/jose/dist/browser/runtime/key_to_jwk.js +0 -21
- package/node_modules/jose/dist/browser/runtime/normalize_key.js +0 -68
- package/node_modules/jose/dist/browser/runtime/pbes2kw.js +0 -51
- package/node_modules/jose/dist/browser/runtime/random.js +0 -2
- package/node_modules/jose/dist/browser/runtime/rsaes.js +0 -37
- package/node_modules/jose/dist/browser/runtime/runtime.js +0 -1
- package/node_modules/jose/dist/browser/runtime/sign.js +0 -11
- package/node_modules/jose/dist/browser/runtime/subtle_dsa.js +0 -28
- package/node_modules/jose/dist/browser/runtime/subtle_rsaes.js +0 -12
- package/node_modules/jose/dist/browser/runtime/timing_safe_equal.js +0 -19
- package/node_modules/jose/dist/browser/runtime/verify.js +0 -16
- package/node_modules/jose/dist/browser/runtime/webcrypto.js +0 -2
- package/node_modules/jose/dist/browser/util/base64url.js +0 -3
- package/node_modules/jose/dist/browser/util/decode_jwt.js +0 -32
- package/node_modules/jose/dist/browser/util/decode_protected_header.js +0 -34
- package/node_modules/jose/dist/browser/util/errors.js +0 -114
- package/node_modules/jose/dist/browser/util/runtime.js +0 -2
- package/node_modules/openid-client/node_modules/jose/dist/browser/index.js +0 -32
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwe/compact/decrypt.js +0 -27
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwe/compact/encrypt.js +0 -26
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwe/flattened/decrypt.js +0 -166
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwe/flattened/encrypt.js +0 -175
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwe/general/decrypt.js +0 -31
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwe/general/encrypt.js +0 -178
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwk/embedded.js +0 -17
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwk/thumbprint.js +0 -53
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwks/local.js +0 -116
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwks/remote.js +0 -76
- package/node_modules/openid-client/node_modules/jose/dist/browser/jws/compact/sign.js +0 -17
- package/node_modules/openid-client/node_modules/jose/dist/browser/jws/compact/verify.js +0 -21
- package/node_modules/openid-client/node_modules/jose/dist/browser/jws/flattened/sign.js +0 -81
- package/node_modules/openid-client/node_modules/jose/dist/browser/jws/flattened/verify.js +0 -115
- package/node_modules/openid-client/node_modules/jose/dist/browser/jws/general/sign.js +0 -67
- package/node_modules/openid-client/node_modules/jose/dist/browser/jws/general/verify.js +0 -24
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwt/decrypt.js +0 -23
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwt/encrypt.js +0 -68
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwt/produce.js +0 -54
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwt/sign.js +0 -21
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwt/unsecured.js +0 -32
- package/node_modules/openid-client/node_modules/jose/dist/browser/jwt/verify.js +0 -16
- package/node_modules/openid-client/node_modules/jose/dist/browser/key/export.js +0 -12
- package/node_modules/openid-client/node_modules/jose/dist/browser/key/generate_key_pair.js +0 -4
- package/node_modules/openid-client/node_modules/jose/dist/browser/key/generate_secret.js +0 -4
- package/node_modules/openid-client/node_modules/jose/dist/browser/key/import.js +0 -50
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/aesgcmkw.js +0 -14
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/buffer_utils.js +0 -51
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/cek.js +0 -20
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/check_iv_length.js +0 -8
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/check_key_type.js +0 -45
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/check_p2s.js +0 -6
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/crypto_key.js +0 -152
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/decrypt_key_management.js +0 -127
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/encrypt_key_management.js +0 -87
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/epoch.js +0 -1
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/format_pem.js +0 -4
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/invalid_key_input.js +0 -30
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/is_disjoint.js +0 -22
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/is_object.js +0 -16
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/iv.js +0 -20
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/jwt_claims_set.js +0 -102
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/secs.js +0 -44
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/validate_algorithms.js +0 -11
- package/node_modules/openid-client/node_modules/jose/dist/browser/lib/validate_crit.js +0 -34
- package/node_modules/openid-client/node_modules/jose/dist/browser/package.json +0 -1
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/aeskw.js +0 -32
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/asn1.js +0 -202
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/base64url.js +0 -37
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/bogus.js +0 -6
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/check_cek_length.js +0 -8
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/check_key_length.js +0 -8
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/decrypt.js +0 -85
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/digest.js +0 -6
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/ecdhes.js +0 -46
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/encrypt.js +0 -68
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/fetch_jwks.js +0 -34
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/generate.js +0 -141
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/get_sign_verify_key.js +0 -17
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/is_key_like.js +0 -5
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/jwk_to_key.js +0 -143
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/key_to_jwk.js +0 -21
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/pbes2kw.js +0 -51
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/random.js +0 -2
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/rsaes.js +0 -37
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/runtime.js +0 -1
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/sign.js +0 -11
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/subtle_dsa.js +0 -26
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/subtle_rsaes.js +0 -12
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/timing_safe_equal.js +0 -19
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/verify.js +0 -16
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/webcrypto.js +0 -2
- package/node_modules/openid-client/node_modules/jose/dist/browser/runtime/zlib.js +0 -7
- package/node_modules/openid-client/node_modules/jose/dist/browser/util/base64url.js +0 -3
- package/node_modules/openid-client/node_modules/jose/dist/browser/util/decode_jwt.js +0 -32
- package/node_modules/openid-client/node_modules/jose/dist/browser/util/decode_protected_header.js +0 -34
- package/node_modules/openid-client/node_modules/jose/dist/browser/util/errors.js +0 -158
- package/node_modules/openid-client/node_modules/jose/dist/browser/util/runtime.js +0 -2
- package/static/app/assets/index-BCZVzMpj.js +0 -230
- package/static/dashboard/assets/AiConfigContext-B5QP7ow2.js +0 -1
- package/static/dashboard/assets/AiConfigPage-C_TdlUjq.js +0 -1
- package/static/dashboard/assets/DocumentProcessingPanel-CormNOdI.js +0 -1
- package/static/dashboard/assets/IndexLifecyclePanel-S9wNNyHO.js +0 -1
- package/static/dashboard/assets/IndexSubjectPanel-CofZT1oE.js +0 -1
- package/static/dashboard/assets/ModelAssignmentsPanel-9tgOjj-y.js +0 -1
- package/static/dashboard/assets/ModelsPage-DZ46VnUh.js +0 -11
- package/static/dashboard/assets/NetworkPage-TwbIWASf.js +0 -2
- package/static/dashboard/assets/PaneListHeader-BtVnyutC.js +0 -1
- package/static/dashboard/assets/SearchIndexingPanel-BCq_YMOP.js +0 -1
- package/static/dashboard/assets/StatusSubjectPanel-DsUKTysU.js +0 -1
- package/static/dashboard/assets/StatusWorkspace-CaVJBRqI.js +0 -1
- package/static/dashboard/assets/SystemSettingsPage-DRWfPjtu.js +0 -1
- package/static/dashboard/assets/SystemSettingsSubjectPanel-CgDP7Ii2.js +0 -33
- package/static/dashboard/assets/XpodAiConnectionsPodStore-C9tHqutw.js +0 -18
- package/static/dashboard/assets/activity-tgjewO88.js +0 -1
- package/static/dashboard/assets/admin-C6qCRFiY.js +0 -1
- package/static/dashboard/assets/ai-connections-Dr4-rSzX.js +0 -1
- package/static/dashboard/assets/badge-Czun47II.js +0 -1
- package/static/dashboard/assets/collection-runtime-DnYlU23-.js +0 -1
- package/static/dashboard/assets/dashboard-CF8SbVSR.js +0 -306
- package/static/dashboard/assets/dashboard-DvuM3VTP.css +0 -1
- package/static/dashboard/assets/dialog-D-Yc_lg-.js +0 -1
- package/static/dashboard/assets/download-vFuOkjCi.js +0 -1
- package/static/dashboard/assets/external-link-Cg_VIecD.js +0 -1
- package/static/dashboard/assets/index-0au0WwkE.js +0 -1
- package/static/dashboard/assets/index-IXCNeEwi.js +0 -41
- package/static/dashboard/assets/index-YDcVky3o.js +0 -4
- package/static/dashboard/assets/key-round-9n1xgLbG.js +0 -1
- package/static/dashboard/assets/rotate-ccw-DJ6s86DW.js +0 -1
- package/static/dashboard/assets/settings-projection-CUkyprDQ.js +0 -1
- package/static/dashboard/assets/skeleton-Dg9HePtI.js +0 -1
- package/static/dashboard/assets/waypoints-uxc_qOzk.js +0 -1
- package/static/dashboard/assets/workspace-layout-BNtAXhPW.js +0 -1
- package/static/settings/assets/AiConfigContext-y6ha7pGs.js +0 -1
- package/static/settings/assets/AiConfigPage-CIcIWdXA.js +0 -1
- package/static/settings/assets/DocumentProcessingPanel-Oa_cxMcn.js +0 -1
- package/static/settings/assets/IndexLifecyclePanel-DlrnI0Kh.js +0 -1
- package/static/settings/assets/IndexSubjectPanel-Dhsl0W32.js +0 -1
- package/static/settings/assets/ModelAssignmentsPanel-CHoiRZeL.js +0 -1
- package/static/settings/assets/ModelsPage-CuNW1hGX.js +0 -11
- package/static/settings/assets/NetworkPage-BBD2Lc_P.js +0 -2
- package/static/settings/assets/PaneListHeader-C81adSBX.js +0 -1
- package/static/settings/assets/SearchIndexingPanel-Dc4QKWd0.js +0 -1
- package/static/settings/assets/StatusSubjectPanel-DuxOvqzS.js +0 -1
- package/static/settings/assets/StatusWorkspace-DeD3zi3G.js +0 -1
- package/static/settings/assets/SystemSettingsPage-8sHOaPb8.js +0 -1
- package/static/settings/assets/SystemSettingsSubjectPanel-B1JXut7S.js +0 -33
- package/static/settings/assets/XpodAiConnectionsPodStore-G0ClZksP.js +0 -3
- package/static/settings/assets/activity-DT8pzOea.js +0 -1
- package/static/settings/assets/admin-C6qCRFiY.js +0 -1
- package/static/settings/assets/ai-connections-DexTPyfC.js +0 -1
- package/static/settings/assets/auth-callback-1BlsOtMG.js +0 -1
- package/static/settings/assets/badge-CvKRjSY2.js +0 -1
- package/static/settings/assets/collection-runtime-C6ZAp2cM.js +0 -1
- package/static/settings/assets/dialog-LFluK7Nx.js +0 -1
- package/static/settings/assets/download-CZJeqUm1.js +0 -1
- package/static/settings/assets/external-link-BsDft3Oe.js +0 -1
- package/static/settings/assets/global-DvuM3VTP.css +0 -1
- package/static/settings/assets/global-cmKEraT4.js +0 -306
- package/static/settings/assets/index-BMPlaRWG.js +0 -1
- package/static/settings/assets/index-BiqSFOS1.js +0 -4
- package/static/settings/assets/index-XRgmPBKw.js +0 -41
- package/static/settings/assets/index-browser-B0slhJKc.js +0 -273
- package/static/settings/assets/key-round-D1XsWbN_.js +0 -1
- package/static/settings/assets/rotate-ccw-CEe0P0fY.js +0 -1
- package/static/settings/assets/settings-DfjkqEJ8.js +0 -1
- package/static/settings/assets/settings-projection-CUkyprDQ.js +0 -1
- package/static/settings/assets/skeleton-DA404w6m.js +0 -1
- package/static/settings/assets/waypoints-DJDWc4S9.js +0 -1
- package/static/settings/assets/workspace-layout-K38jT4OV.js +0 -1
- /package/static/app/assets/{_commonjsHelpers-B-UnjaXt.js → global-BsV9-QbH.js} +0 -0
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/XpodShellApp-D1PS3Iut.js","assets/XpodThemeProvider-CB6LepTA.js","assets/XpodThemeProvider-C64R553B.css","assets/button-BObT8pTE.js","assets/PodDeletionAuthorizationPanel-DgVvarVY.js","assets/account-session-BcLjCj0x.js","assets/safe-continuation-Dx6ceJpY.js","assets/nav-item-style-Di2CxkDU.js","assets/createLucideIcon-BVsUxXpZ.js","assets/XpodShellApp-Bwom2xL3.css","assets/index-browser-3WfrNbcG.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as createLucideIcon$1}from"./createLucideIcon-BVsUxXpZ.js";import{r as reactExports,j as jsxRuntimeExports,g as useXpodAuthWindowSurface,h as getXpodAuthSurfaceHost,_ as __vitePreload,k as getDefaultExportFromCjs}from"./XpodThemeProvider-CB6LepTA.js";import{c as cn,B as Button,u as useComposedRefs,e as createSlottable,d as controlFocusClass}from"./button-BObT8pTE.js";import{c as createContextScope,P as Primitive,q as useCallbackRef,r as useLayoutEffect2,f as Card,p as createLucideIcon,t as reactDomExports,v as Presence,w as DismissableLayer,y as useId,u as useControllableState,a as composeEventHandlers,z as Portal$1,I as Input}from"./PodDeletionAuthorizationPanel-DgVvarVY.js";import{X as XpodMark,f as resolveSolidLocalRouteUrl,h as createSolidLocalRouteFetch,p as probeSolidLocalRouteStatus}from"./account-session-BcLjCj0x.js";var __defProp$4=Object.defineProperty,__name$4=(n,e)=>__defProp$4(n,"name",{value:e,configurable:!0}),AVATAR_NAME="Avatar",[createAvatarContext,createAvatarScope]=createContextScope(AVATAR_NAME),STATIC_IMAGE_COUNT_STATE=[0,()=>{}],[AvatarProvider,useAvatarContext]=createAvatarContext(AVATAR_NAME),Avatar$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:r,...i}=e,[s,o]=reactExports.useState("idle"),[a,u]=useImageCount();return jsxRuntimeExports.jsx(AvatarProvider,{scope:r,imageLoadingStatus:s,setImageLoadingStatus:o,imageCount:a,setImageCount:u,children:jsxRuntimeExports.jsx(Primitive.span,{...i,ref:t})})},"Avatar")),IMAGE_NAME="AvatarImage",AvatarImage$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:r,src:i,onLoadingStatusChange:s,...o}=e,a=useAvatarContext(IMAGE_NAME,r);a.setImageCount;const u=useImageLoadingStatus(i,{referrerPolicy:o.referrerPolicy,crossOrigin:o.crossOrigin,loadingStatus:a.imageLoadingStatus,setLoadingStatus:a.setImageLoadingStatus}),c=useCallbackRef(d=>{s?.(d)}),l=reactExports.useRef(u);return useLayoutEffect2(()=>{const d=l.current;l.current=u,u!==d&&c(u)},[u,c]),u==="loaded"?jsxRuntimeExports.jsx(Primitive.img,{...o,ref:t,src:i}):null},"AvatarImage")),FALLBACK_NAME="AvatarFallback",AvatarFallback$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:r,delayMs:i,...s}=e,o=useAvatarContext(FALLBACK_NAME,r),[a,u]=reactExports.useState(i===void 0);return reactExports.useEffect(()=>{if(i!==void 0){const c=window.setTimeout(()=>u(!0),i);return()=>window.clearTimeout(c)}},[i]),a&&o.imageLoadingStatus!=="loaded"?jsxRuntimeExports.jsx(Primitive.span,{...s,ref:t}):null},"AvatarFallback"));function useImageLoadingStatus(n,{loadingStatus:e,setLoadingStatus:t,referrerPolicy:r,crossOrigin:i}){return useLayoutEffect2(()=>{if(!n){t("error");return}const s=new window.Image,o=__name$4(u=>{const c=u.currentTarget;t(getImageLoadingStatus(c))},"handleLoad"),a=__name$4(()=>t("error"),"handleError");return s.addEventListener("load",o),s.addEventListener("error",a),r&&(s.referrerPolicy=r),s.crossOrigin=i??null,s.src=n,t(getImageLoadingStatus(s)),()=>{s.removeEventListener("load",o),s.removeEventListener("error",a),t("idle")}},[n,i,r,t]),e}__name$4(useImageLoadingStatus,"useImageLoadingStatus");function getImageLoadingStatus(n){return n.complete?n.naturalWidth>0?"loaded":"error":"loading"}__name$4(getImageLoadingStatus,"getImageLoadingStatus");function useImageCount(){return STATIC_IMAGE_COUNT_STATE}__name$4(useImageCount,"useImageCount");function useUpdateImageCount(n){}__name$4(useUpdateImageCount,"useUpdateImageCount");const Avatar=reactExports.forwardRef(({className:n,...e},t)=>jsxRuntimeExports.jsx(Avatar$1,{ref:t,className:cn("relative flex shrink-0 overflow-hidden",n),...e}));Avatar.displayName=Avatar$1.displayName;const AvatarImage=reactExports.forwardRef(({className:n,...e},t)=>jsxRuntimeExports.jsx(AvatarImage$1,{ref:t,className:cn("h-full w-full object-cover",n),...e}));AvatarImage.displayName=AvatarImage$1.displayName;const AvatarFallback=reactExports.forwardRef(({className:n,...e},t)=>jsxRuntimeExports.jsx(AvatarFallback$1,{ref:t,className:cn("flex h-full w-full items-center justify-center bg-muted text-lg font-semibold",n),...e}));AvatarFallback.displayName=AvatarFallback$1.displayName;function AuthSurfaceBody({children:n,className:e}){return jsxRuntimeExports.jsx("div",{"data-testid":"auth-surface-body",className:cn("min-h-0",e),children:n})}const FOCUSABLE_SELECTOR=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function getFocusable(n){return Array.from(n.querySelectorAll(FOCUSABLE_SELECTOR)).filter(e=>e.getAttribute("aria-hidden")!=="true")}function AuthSurface({mode:n,title:e,children:t,presentation:r="standard",host:i="document",lead:s,onClose:o,closeLabel:a,closeOnEscape:u=!0,className:c,contentClassName:l}){const d=reactExports.useRef(null),f=reactExports.useRef(null),m=reactExports.useId();reactExports.useLayoutEffect(()=>{if(n!=="modal"||typeof document>"u")return;f.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const _=d.current;if(_){const T=getFocusable(_);(r==="compact"?_:T[0]??_).focus()}return()=>{f.current?.focus(),f.current=null}},[n,r]),reactExports.useLayoutEffect(()=>{if(n!=="modal"||typeof document>"u")return;const _=T=>{if(T.key==="Escape"){u&&o&&(T.preventDefault(),o());return}if(T.key!=="Tab")return;const C=d.current;if(!C)return;const U=getFocusable(C);if(U.length===0){T.preventDefault(),C.focus();return}const $=document.activeElement,W=U.indexOf($),re=T.shiftKey?W<=0?U.length-1:W-1:W===U.length-1?0:W+1;T.preventDefault(),U[re].focus()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[u,n,o]);const g=n==="modal"?{role:"dialog","aria-modal":!0,"aria-labelledby":m}:{role:"region","aria-labelledby":m},b=r==="compact",S=i==="window",w=b?"flex min-h-0 flex-1 flex-col overflow-y-auto":"max-h-[min(80vh,48rem)] overflow-y-auto",v=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[b?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h1",{id:m,className:"sr-only",children:e}),n==="modal"&&o&&a?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:o,"aria-label":a,className:"absolute right-2 top-2 z-[var(--layer-sticky)]",children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null]}):jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-border/60 p-4",children:[jsxRuntimeExports.jsx("h1",{id:m,className:"text-lg font-semibold text-foreground",children:e}),n==="modal"&&o&&a?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:o,"aria-label":a,children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null]}),s?jsxRuntimeExports.jsx("div",{"data-testid":"auth-surface-lead",className:cn(b?"shrink-0 px-5 pt-7 has-[[data-presentation=compact]]:pt-5":"border-b border-border/60 p-4"),children:s}):null,jsxRuntimeExports.jsx(AuthSurfaceBody,{className:cn(w,l),children:t})]});return jsxRuntimeExports.jsx("div",{"data-testid":`auth-surface-${n}`,"data-auth-surface-mode":n,"data-auth-surface-presentation":b?"compact":void 0,"data-auth-surface-host":S?"window":void 0,className:cn(S?"fixed inset-0 z-[var(--layer-modal)] flex items-stretch justify-stretch overflow-hidden bg-card p-0":n==="modal"?cn("fixed inset-0 z-[var(--layer-modal)] flex items-center justify-center p-4","bg-background"):n==="page"?"flex min-h-[100dvh] w-full items-center justify-center bg-background p-4":"flex min-h-0 w-full items-center justify-center p-4",c),children:S?jsxRuntimeExports.jsx("div",{ref:d,...g,"data-auth-surface-frame":"window",tabIndex:-1,className:"relative flex h-full min-h-0 w-full flex-col overflow-hidden bg-card text-card-foreground focus:outline-none",children:v}):b?jsxRuntimeExports.jsx("div",{ref:d,...g,"data-auth-surface-frame":"compact",tabIndex:-1,style:{outline:"none"},className:"flex h-[400px] w-[280px] max-h-[calc(100dvh-2rem)] max-w-[calc(100vw-2rem)] min-w-0 flex-col overflow-y-auto overscroll-contain focus:outline-none",children:v}):jsxRuntimeExports.jsx(Card,{ref:d,...g,tabIndex:-1,style:{outline:"none"},className:cn("relative flex min-h-0 w-full flex-col border-border bg-card text-card-foreground focus:outline-none",n==="embedded"?"max-w-none shadow-none":"max-w-lg"),children:v})})}const __iconNode$7=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Check=createLucideIcon("check",__iconNode$7);const __iconNode$6=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Cloud=createLucideIcon("cloud",__iconNode$6);const __iconNode$5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Info=createLucideIcon("info",__iconNode$5);const __iconNode$4=[["path",{d:"M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z",key:"1pdavp"}],["path",{d:"M20.054 15.987H3.946",key:"14rxg9"}]],Laptop=createLucideIcon("laptop",__iconNode$4);const __iconNode$3=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle$1=createLucideIcon("loader-circle",__iconNode$3);const __iconNode$2=[["path",{d:"M5 12h14",key:"1ays0h"}]],Minus=createLucideIcon("minus",__iconNode$2),sides=["top","right","bottom","left"],min=Math.min,max=Math.max,round=Math.round,floor=Math.floor,createCoords=n=>({x:n,y:n}),oppositeSideMap={left:"right",right:"left",bottom:"top",top:"bottom"};function clamp(n,e,t){return max(n,min(e,t))}function evaluate(n,e){return typeof n=="function"?n(e):n}function getSide(n){return n.split("-")[0]}function getAlignment(n){return n.split("-")[1]}function getOppositeAxis(n){return n==="x"?"y":"x"}function getAxisLength(n){return n==="y"?"height":"width"}function getSideAxis(n){const e=n[0];return e==="t"||e==="b"?"y":"x"}function getAlignmentAxis(n){return getOppositeAxis(getSideAxis(n))}function getAlignmentSides(n,e,t){t===void 0&&(t=!1);const r=getAlignment(n),i=getAlignmentAxis(n),s=getAxisLength(i);let o=i==="x"?r===(t?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(o=getOppositePlacement(o)),[o,getOppositePlacement(o)]}function getExpandedPlacements(n){const e=getOppositePlacement(n);return[getOppositeAlignmentPlacement(n),e,getOppositeAlignmentPlacement(e)]}function getOppositeAlignmentPlacement(n){return n.includes("start")?n.replace("start","end"):n.replace("end","start")}const lrPlacement=["left","right"],rlPlacement=["right","left"],tbPlacement=["top","bottom"],btPlacement=["bottom","top"];function getSideList(n,e,t){switch(n){case"top":case"bottom":return t?e?rlPlacement:lrPlacement:e?lrPlacement:rlPlacement;case"left":case"right":return e?tbPlacement:btPlacement;default:return[]}}function getOppositeAxisPlacements(n,e,t,r){const i=getAlignment(n);let s=getSideList(getSide(n),t==="start",r);return i&&(s=s.map(o=>o+"-"+i),e&&(s=s.concat(s.map(getOppositeAlignmentPlacement)))),s}function getOppositePlacement(n){const e=getSide(n);return oppositeSideMap[e]+n.slice(e.length)}function expandPaddingObject(n){var e,t,r,i;return{top:(e=n.top)!=null?e:0,right:(t=n.right)!=null?t:0,bottom:(r=n.bottom)!=null?r:0,left:(i=n.left)!=null?i:0}}function getPaddingObject(n){return typeof n!="number"?expandPaddingObject(n):{top:n,right:n,bottom:n,left:n}}function rectToClientRect(n){const{x:e,y:t,width:r,height:i}=n;return{width:r,height:i,top:t,left:e,right:e+r,bottom:t+i,x:e,y:t}}function computeCoordsFromPlacement(n,e,t){let{reference:r,floating:i}=n;const s=getSideAxis(e),o=getAlignmentAxis(e),a=getAxisLength(o),u=getSide(e),c=s==="y",l=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[a]/2-i[a]/2;let m;switch(u){case"top":m={x:l,y:r.y-i.height};break;case"bottom":m={x:l,y:r.y+r.height};break;case"right":m={x:r.x+r.width,y:d};break;case"left":m={x:r.x-i.width,y:d};break;default:m={x:r.x,y:r.y}}const g=getAlignment(e);return g&&(m[o]+=f*(g==="end"?1:-1)*(t&&c?-1:1)),m}async function detectOverflow(n,e){var t;e===void 0&&(e={});const{x:r,y:i,platform:s,rects:o,elements:a,strategy:u}=n,{boundary:c="clippingAncestors",rootBoundary:l="viewport",elementContext:d="floating",altBoundary:f=!1,padding:m=0}=evaluate(e,n),g=getPaddingObject(m),S=a[f?d==="floating"?"reference":"floating":d],w=rectToClientRect(await s.getClippingRect({element:(t=await(s.isElement==null?void 0:s.isElement(S)))==null||t?S:S.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:l,strategy:u})),v=d==="floating"?{x:r,y:i,width:o.floating.width,height:o.floating.height}:o.reference,_=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),T=await(s.isElement==null?void 0:s.isElement(_))&&await(s.getScale==null?void 0:s.getScale(_))||{x:1,y:1},C=rectToClientRect(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:_,strategy:u}):v);return{top:(w.top-C.top+g.top)/T.y,bottom:(C.bottom-w.bottom+g.bottom)/T.y,left:(w.left-C.left+g.left)/T.x,right:(C.right-w.right+g.right)/T.x}}const MAX_RESET_COUNT=50,computePosition$1=async(n,e,t)=>{const{placement:r="bottom",strategy:i="absolute",middleware:s=[],platform:o}=t,a=o.detectOverflow?o:{...o,detectOverflow},u=await(o.isRTL==null?void 0:o.isRTL(e));let c=await o.getElementRects({reference:n,floating:e,strategy:i}),{x:l,y:d}=computeCoordsFromPlacement(c,r,u),f=r,m=0;const g={};for(let b=0;b<s.length;b++){const S=s[b];if(!S)continue;const{name:w,fn:v}=S,{x:_,y:T,data:C,reset:U}=await v({x:l,y:d,initialPlacement:r,placement:f,strategy:i,middlewareData:g,rects:c,platform:a,elements:{reference:n,floating:e}});l=_??l,d=T??d,g[w]={...g[w],...C},U&&m<MAX_RESET_COUNT&&(m++,typeof U=="object"&&(U.placement&&(f=U.placement),U.rects&&(c=U.rects===!0?await o.getElementRects({reference:n,floating:e,strategy:i}):U.rects),{x:l,y:d}=computeCoordsFromPlacement(c,f,u)),b=-1)}return{x:l,y:d,placement:f,strategy:i,middlewareData:g}},arrow$3=n=>({name:"arrow",options:n,async fn(e){const{x:t,y:r,placement:i,rects:s,platform:o,elements:a,middlewareData:u}=e,{element:c,padding:l=0}=evaluate(n,e)||{};if(c==null)return{};const d=getPaddingObject(l),f={x:t,y:r},m=getAlignmentAxis(i),g=getAxisLength(m),b=await o.getDimensions(c),S=m==="y",w=S?"top":"left",v=S?"bottom":"right",_=S?"clientHeight":"clientWidth",T=s.reference[g]+s.reference[m]-f[m]-s.floating[g],C=f[m]-s.reference[m],U=await(o.getOffsetParent==null?void 0:o.getOffsetParent(c));let $=U?U[_]:0;(!$||!await(o.isElement==null?void 0:o.isElement(U)))&&($=a.floating[_]||s.floating[g]);const W=T/2-C/2,re=$/2-b[g]/2-1,D=min(d[w],re),V=min(d[v],re),he=$-b[g]-V,z=$/2-b[g]/2+W,_e=clamp(D,z,he),Ce=!u.arrow&&getAlignment(i)!=null&&z!==_e&&s.reference[g]/2-(z<D?D:V)-b[g]/2<0,Fe=Ce?z<D?z-D:z-he:0;return{[m]:f[m]+Fe,data:{[m]:_e,centerOffset:z-_e-Fe,...Ce&&{alignmentOffset:Fe}},reset:Ce}}}),flip$2=function(n){return n===void 0&&(n={}),{name:"flip",options:n,async fn(e){var t,r;const{placement:i,middlewareData:s,rects:o,initialPlacement:a,platform:u,elements:c}=e,{mainAxis:l=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:b=!0,...S}=evaluate(n,e);if((t=s.arrow)!=null&&t.alignmentOffset)return{};const w=getSide(i),v=getSideAxis(a),_=getSide(a)===a,T=await(u.isRTL==null?void 0:u.isRTL(c.floating)),C=f||(_||!b?[getOppositePlacement(a)]:getExpandedPlacements(a)),U=g!=="none";!f&&U&&C.push(...getOppositeAxisPlacements(a,b,g,T));const $=[a,...C],W=await u.detectOverflow(e,S),re=[];let D=((r=s.flip)==null?void 0:r.overflows)||[];if(l&&re.push(W[w]),d){const _e=getAlignmentSides(i,o,T);re.push(W[_e[0]],W[_e[1]])}if(D=[...D,{placement:i,overflows:re}],!re.every(_e=>_e<=0)){var V,he;const _e=(((V=s.flip)==null?void 0:V.index)||0)+1,Ce=$[_e];if(Ce&&(!(d==="alignment"?v!==getSideAxis(Ce):!1)||D.every(ae=>getSideAxis(ae.placement)===v?ae.overflows[0]>0:!0)))return{data:{index:_e,overflows:D},reset:{placement:Ce}};let Fe=(he=D.filter(ze=>ze.overflows[0]<=0).sort((ze,ae)=>ze.overflows[1]-ae.overflows[1])[0])==null?void 0:he.placement;if(!Fe)switch(m){case"bestFit":{var z;const ze=(z=D.filter(ae=>{if(U){const ve=getSideAxis(ae.placement);return ve===v||ve==="y"}return!0}).map(ae=>[ae.placement,ae.overflows.filter(ve=>ve>0).reduce((ve,L)=>ve+L,0)]).sort((ae,ve)=>ae[1]-ve[1])[0])==null?void 0:z[0];ze&&(Fe=ze);break}case"initialPlacement":Fe=a;break}if(i!==Fe)return{reset:{placement:Fe}}}return{}}}};function getSideOffsets(n,e){return{top:n.top-e.height,right:n.right-e.width,bottom:n.bottom-e.height,left:n.left-e.width}}function isAnySideFullyClipped(n){return sides.some(e=>n[e]>=0)}const hide$2=function(n){return n===void 0&&(n={}),{name:"hide",options:n,async fn(e){const{rects:t,platform:r}=e,{strategy:i="referenceHidden",...s}=evaluate(n,e);switch(i){case"referenceHidden":{const o=await r.detectOverflow(e,{...s,elementContext:"reference"}),a=getSideOffsets(o,t.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:isAnySideFullyClipped(a)}}}case"escaped":{const o=await r.detectOverflow(e,{...s,altBoundary:!0}),a=getSideOffsets(o,t.floating);return{data:{escapedOffsets:a,escaped:isAnySideFullyClipped(a)}}}default:return{}}}}},originSides=new Set(["left","top"]);async function convertValueToCoords(n,e){const{placement:t,platform:r,elements:i}=n,s=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=getSide(t),a=getAlignment(t),u=getSideAxis(t)==="y",c=originSides.has(o)?-1:1,l=s&&u?-1:1,d=evaluate(e,n);let{mainAxis:f,crossAxis:m,alignmentAxis:g}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return a&&typeof g=="number"&&(m=a==="end"?g*-1:g),u?{x:m*l,y:f*c}:{x:f*c,y:m*l}}const offset$2=function(n){return n===void 0&&(n=0),{name:"offset",options:n,async fn(e){var t,r;const{x:i,y:s,placement:o,middlewareData:a}=e,u=await convertValueToCoords(e,n);return o===((t=a.offset)==null?void 0:t.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:i+u.x,y:s+u.y,data:{...u,placement:o}}}}},shift$2=function(n){return n===void 0&&(n={}),{name:"shift",options:n,async fn(e){const{x:t,y:r,placement:i,platform:s}=e,{mainAxis:o=!0,crossAxis:a=!1,limiter:u={fn:v=>{let{x:_,y:T}=v;return{x:_,y:T}}},...c}=evaluate(n,e),l={x:t,y:r},d=await s.detectOverflow(e,c),f=getSideAxis(i),m=getOppositeAxis(f);let g=l[m],b=l[f];const S=(v,_)=>clamp(_+d[v==="y"?"top":"left"],_,_-d[v==="y"?"bottom":"right"]);o&&(g=S(m,g)),a&&(b=S(f,b));const w=u.fn({...e,[m]:g,[f]:b});return{...w,data:{x:w.x-t,y:w.y-r,enabled:{[m]:o,[f]:a}}}}}},limitShift$2=function(n){return n===void 0&&(n={}),{options:n,fn(e){var t,r;const{x:i,y:s,placement:o,rects:a,middlewareData:u}=e,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=evaluate(n,e),f={x:i,y:s},m=getSideAxis(o),g=getOppositeAxis(m);let b=f[g],S=f[m];const w=evaluate(c,e),v=typeof w=="number"?{mainAxis:w,crossAxis:0}:{mainAxis:(t=w.mainAxis)!=null?t:0,crossAxis:(r=w.crossAxis)!=null?r:0};if(l){const C=g==="y"?"height":"width",U=a.reference[g]-a.floating[C]+v.mainAxis,$=a.reference[g]+a.reference[C]-v.mainAxis;b<U?b=U:b>$&&(b=$)}if(d){var _,T;const C=g==="y"?"width":"height",U=originSides.has(getSide(o)),$=a.reference[m]-a.floating[C]+(U&&((_=u.offset)==null?void 0:_[m])||0)+(U?0:v.crossAxis),W=a.reference[m]+a.reference[C]+(U?0:((T=u.offset)==null?void 0:T[m])||0)-(U?v.crossAxis:0);S<$?S=$:S>W&&(S=W)}return{[g]:b,[m]:S}}}},size$2=function(n){return n===void 0&&(n={}),{name:"size",options:n,async fn(e){const{placement:t,rects:r,platform:i,elements:s}=e,{apply:o=()=>{},...a}=evaluate(n,e),u=await i.detectOverflow(e,a),c=getSide(t),l=getAlignment(t),d=getSideAxis(t)==="y",{width:f,height:m}=r.floating;let g,b;c==="top"||c==="bottom"?(g=c,b=l===(await(i.isRTL==null?void 0:i.isRTL(s.floating))?"start":"end")?"left":"right"):(b=c,g=l==="end"?"top":"bottom");const S=m-u.top-u.bottom,w=f-u.left-u.right,v=min(m-u[g],S),_=min(f-u[b],w),T=e.middlewareData.shift,C=!T;let U=v,$=_;T!=null&&T.enabled.x&&($=w),T!=null&&T.enabled.y&&(U=S),C&&!l&&(d?$=f-2*max(u.left,u.right):U=m-2*max(u.top,u.bottom)),await o({...e,availableWidth:$,availableHeight:U});const W=await i.getDimensions(s.floating);return f!==W.width||m!==W.height?{reset:{rects:!0}}:{}}}};function hasWindow(){return typeof window<"u"}function getNodeName(n){return isNode(n)?(n.nodeName||"").toLowerCase():"#document"}function getWindow(n){var e;return(n==null||(e=n.ownerDocument)==null?void 0:e.defaultView)||window}function getDocumentElement(n){var e;return(e=(isNode(n)?n.ownerDocument:n.document)||window.document)==null?void 0:e.documentElement}function isNode(n){return hasWindow()?n instanceof Node||n instanceof getWindow(n).Node:!1}function isElement(n){return hasWindow()?n instanceof Element||n instanceof getWindow(n).Element:!1}function isHTMLElement(n){return hasWindow()?n instanceof HTMLElement||n instanceof getWindow(n).HTMLElement:!1}function isShadowRoot(n){return!hasWindow()||typeof ShadowRoot>"u"?!1:n instanceof ShadowRoot||n instanceof getWindow(n).ShadowRoot}function isOverflowElement(n){const{overflow:e,overflowX:t,overflowY:r,display:i}=getComputedStyle$1(n);return/auto|scroll|overlay|hidden|clip/.test(e+r+t)&&i!=="inline"&&i!=="contents"}function isTableElement(n){return/^(table|td|th)$/.test(getNodeName(n))}function isTopLayer(n){try{if(n.matches(":popover-open"))return!0}catch{}try{return n.matches(":modal")}catch{return!1}}const willChangeRe=/transform|translate|scale|rotate|perspective|filter/,containRe=/paint|layout|strict|content/,isNotNone=n=>!!n&&n!=="none";let isWebKitValue;function isContainingBlock(n){const e=isElement(n)?getComputedStyle$1(n):n;return isNotNone(e.transform)||isNotNone(e.translate)||isNotNone(e.scale)||isNotNone(e.rotate)||isNotNone(e.perspective)||!isWebKit()&&(isNotNone(e.backdropFilter)||isNotNone(e.filter))||willChangeRe.test(e.willChange||"")||containRe.test(e.contain||"")}function getContainingBlock(n){let e=getParentNode(n);for(;isHTMLElement(e)&&!isLastTraversableNode(e);){if(isContainingBlock(e))return e;if(isTopLayer(e))return null;e=getParentNode(e)}return null}function isWebKit(){return isWebKitValue==null&&(isWebKitValue=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),isWebKitValue}function isLastTraversableNode(n){return/^(html|body|#document)$/.test(getNodeName(n))}function getComputedStyle$1(n){return getWindow(n).getComputedStyle(n)}function getNodeScroll(n){return isElement(n)?{scrollLeft:n.scrollLeft,scrollTop:n.scrollTop}:{scrollLeft:n.scrollX,scrollTop:n.scrollY}}function getParentNode(n){if(getNodeName(n)==="html")return n;const e=n.assignedSlot||n.parentNode||isShadowRoot(n)&&n.host||getDocumentElement(n);return isShadowRoot(e)?e.host:e}function getNearestOverflowAncestor(n){const e=getParentNode(n);return isLastTraversableNode(e)?(n.ownerDocument||n).body:isHTMLElement(e)&&isOverflowElement(e)?e:getNearestOverflowAncestor(e)}function getOverflowAncestors(n,e,t){var r;e===void 0&&(e=[]),t===void 0&&(t=!0);const i=getNearestOverflowAncestor(n),s=i===((r=n.ownerDocument)==null?void 0:r.body),o=getWindow(i);if(s){const a=getFrameElement(o);return e.concat(o,o.visualViewport||[],isOverflowElement(i)?i:[],a&&t?getOverflowAncestors(a):[])}else return e.concat(i,getOverflowAncestors(i,[],t))}function getFrameElement(n){return n.parent&&Object.getPrototypeOf(n.parent)?n.frameElement:null}function getCssDimensions(n){const e=getComputedStyle$1(n);let t=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const i=isHTMLElement(n),s=i?n.offsetWidth:t,o=i?n.offsetHeight:r,a=round(t)!==s||round(r)!==o;return a&&(t=s,r=o),{width:t,height:r,$:a}}function unwrapElement(n){return isElement(n)?n:n.contextElement}function getScale(n){const e=unwrapElement(n);if(!isHTMLElement(e))return createCoords(1);const t=e.getBoundingClientRect(),{width:r,height:i,$:s}=getCssDimensions(e);let o=(s?round(t.width):t.width)/r,a=(s?round(t.height):t.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!a||!Number.isFinite(a))&&(a=1),{x:o,y:a}}const noOffsets=createCoords(0);function getVisualOffsets(n){const e=getWindow(n);return!isWebKit()||!e.visualViewport?noOffsets:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function shouldAddVisualOffsets(n,e,t){return e===void 0&&(e=!1),!!t&&e&&t===getWindow(n)}function getBoundingClientRect(n,e,t,r){e===void 0&&(e=!1),t===void 0&&(t=!1);const i=n.getBoundingClientRect(),s=unwrapElement(n);let o=createCoords(1);e&&(r?isElement(r)&&(o=getScale(r)):o=getScale(n));const a=shouldAddVisualOffsets(s,t,r)?getVisualOffsets(s):createCoords(0);let u=(i.left+a.x)/o.x,c=(i.top+a.y)/o.y,l=i.width/o.x,d=i.height/o.y;if(s&&r){const f=getWindow(s),m=isElement(r)?getWindow(r):r;let g=f,b=getFrameElement(g);for(;b&&m!==g;){const S=getScale(b),w=b.getBoundingClientRect(),v=getComputedStyle$1(b),_=w.left+(b.clientLeft+parseFloat(v.paddingLeft))*S.x,T=w.top+(b.clientTop+parseFloat(v.paddingTop))*S.y;u*=S.x,c*=S.y,l*=S.x,d*=S.y,u+=_,c+=T,g=getWindow(b),b=getFrameElement(g)}}return rectToClientRect({width:l,height:d,x:u,y:c})}function getWindowScrollBarX(n,e){const t=getNodeScroll(n).scrollLeft;return e?e.left+t:getBoundingClientRect(getDocumentElement(n)).left+t}function getHTMLOffset(n,e){const t=n.getBoundingClientRect(),r=t.left+e.scrollLeft-getWindowScrollBarX(n,t),i=t.top+e.scrollTop;return{x:r,y:i}}function convertOffsetParentRelativeRectToViewportRelativeRect(n){let{elements:e,rect:t,offsetParent:r,strategy:i}=n;const s=i==="fixed",o=getDocumentElement(r),a=e?isTopLayer(e.floating):!1;if(r===o||a&&s)return t;let u={scrollLeft:0,scrollTop:0},c=createCoords(1);const l=createCoords(0),d=isHTMLElement(r);if((d||!s)&&((getNodeName(r)!=="body"||isOverflowElement(o))&&(u=getNodeScroll(r)),d)){const m=getBoundingClientRect(r);c=getScale(r),l.x=m.x+r.clientLeft,l.y=m.y+r.clientTop}const f=o&&!d&&!s?getHTMLOffset(o,u):createCoords(0);return{width:t.width*c.x,height:t.height*c.y,x:t.x*c.x-u.scrollLeft*c.x+l.x+f.x,y:t.y*c.y-u.scrollTop*c.y+l.y+f.y}}function getClientRects(n){return n.getClientRects?Array.from(n.getClientRects()):[]}function getDocumentRect(n){const e=getNodeScroll(n),t=n.ownerDocument.body,r=max(n.scrollWidth,n.clientWidth,t.scrollWidth,t.clientWidth),i=max(n.scrollHeight,n.clientHeight,t.scrollHeight,t.clientHeight);let s=-e.scrollLeft+getWindowScrollBarX(n);const o=-e.scrollTop;return getComputedStyle$1(t).direction==="rtl"&&(s+=max(n.clientWidth,t.clientWidth)-r),{width:r,height:i,x:s,y:o}}const SCROLLBAR_MAX=25;function getViewportRect(n,e,t){t===void 0&&(t="viewport");const r=t==="layoutViewport",i=getWindow(n),s=getDocumentElement(n),o=i.visualViewport;let a=s.clientWidth,u=s.clientHeight,c=0,l=0;if(o){const f=!isWebKit()||e==="fixed";r?f||(c=-o.offsetLeft,l=-o.offsetTop):(a=o.width,u=o.height,f&&(c=o.offsetLeft,l=o.offsetTop))}if(getWindowScrollBarX(s)<=0){const f=s.ownerDocument,m=f.body,g=getComputedStyle(m),b=f.compatMode==="CSS1Compat"&&parseFloat(g.marginLeft)+parseFloat(g.marginRight)||0,S=Math.abs(s.clientWidth-m.clientWidth-b),w=getComputedStyle(s).scrollbarGutter==="stable both-edges"?S/2:S;w<=SCROLLBAR_MAX&&(a-=w)}return{width:a,height:u,x:c,y:l}}function getInnerBoundingClientRect(n,e){const t=getBoundingClientRect(n,!0,e==="fixed"),r=t.top+n.clientTop,i=t.left+n.clientLeft,s=getScale(n),o=n.clientWidth*s.x,a=n.clientHeight*s.y,u=i*s.x,c=r*s.y;return{width:o,height:a,x:u,y:c}}function getClientRectFromClippingAncestor(n,e,t){let r;if(e==="viewport"||e==="layoutViewport")r=getViewportRect(n,t,e);else if(e==="document")r=getDocumentRect(getDocumentElement(n));else if(isElement(e))r=getInnerBoundingClientRect(e,t);else{const i=getVisualOffsets(n);r={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return rectToClientRect(r)}function getClippingElementAncestors(n,e){const t=e.get(n);if(t)return t;let r=getOverflowAncestors(n,[],!1).filter(a=>isElement(a)&&getNodeName(a)!=="body"),i=null;const s=getComputedStyle$1(n).position==="fixed";let o=s?getParentNode(n):n;for(;isElement(o)&&!isLastTraversableNode(o);){const a=getComputedStyle$1(o),u=isContainingBlock(o),c=i?i.position:s?"fixed":"";!u&&(c==="fixed"||c==="absolute"&&a.position==="static")?r=r.filter(d=>d!==o):i=a,o=getParentNode(o)}return e.set(n,r),r}function getClippingRect(n){let{element:e,boundary:t,rootBoundary:r,strategy:i}=n;const o=[...t==="clippingAncestors"?isTopLayer(e)?[]:getClippingElementAncestors(e,this._c):[].concat(t),r],a=getClientRectFromClippingAncestor(e,o[0],i);let u=a.top,c=a.right,l=a.bottom,d=a.left;for(let f=1;f<o.length;f++){const m=getClientRectFromClippingAncestor(e,o[f],i);u=max(m.top,u),c=min(m.right,c),l=min(m.bottom,l),d=max(m.left,d)}return{width:c-d,height:l-u,x:d,y:u}}function getDimensions(n){const{width:e,height:t}=getCssDimensions(n);return{width:e,height:t}}function getRectRelativeToOffsetParent(n,e,t){const r=isHTMLElement(e),i=getDocumentElement(e),s=t==="fixed",o=getBoundingClientRect(n,!0,s,e);let a={scrollLeft:0,scrollTop:0};const u=createCoords(0);if((r||!s)&&((getNodeName(e)!=="body"||isOverflowElement(i))&&(a=getNodeScroll(e)),r)){const f=getBoundingClientRect(e,!0,s,e);u.x=f.x+e.clientLeft,u.y=f.y+e.clientTop}!r&&i&&(u.x=getWindowScrollBarX(i));const c=i&&!r&&!s?getHTMLOffset(i,a):createCoords(0),l=o.left+a.scrollLeft-u.x-c.x,d=o.top+a.scrollTop-u.y-c.y;return{x:l,y:d,width:o.width,height:o.height}}function isStaticPositioned(n){return getComputedStyle$1(n).position==="static"}function getTrueOffsetParent(n,e){if(!isHTMLElement(n)||getComputedStyle$1(n).position==="fixed")return null;if(e)return e(n);let t=n.offsetParent;return getDocumentElement(n)===t&&(t=t.ownerDocument.body),t}function getOffsetParent(n,e){const t=getWindow(n);if(isTopLayer(n))return t;if(!isHTMLElement(n)){let i=getParentNode(n);for(;i&&!isLastTraversableNode(i);){if(isElement(i)&&!isStaticPositioned(i))return i;i=getParentNode(i)}return t}let r=getTrueOffsetParent(n,e);for(;r&&isTableElement(r)&&isStaticPositioned(r);)r=getTrueOffsetParent(r,e);return r&&isLastTraversableNode(r)&&isStaticPositioned(r)&&!isContainingBlock(r)?t:r||getContainingBlock(n)||t}const getElementRects=async function(n){const e=this.getOffsetParent||getOffsetParent,t=this.getDimensions,r=await t(n.floating);return{reference:getRectRelativeToOffsetParent(n.reference,await e(n.floating),n.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function isRTL(n){return getComputedStyle$1(n).direction==="rtl"}const platform={convertOffsetParentRelativeRectToViewportRelativeRect,getDocumentElement,getClippingRect,getOffsetParent,getElementRects,getClientRects,getDimensions,getScale,isElement,isRTL};function rectsAreEqual(n,e){return n.x===e.x&&n.y===e.y&&n.width===e.width&&n.height===e.height}function observeMove(n,e,t){let r=null,i;const s=getDocumentElement(n);function o(){var l;clearTimeout(i),(l=r)==null||l.disconnect(),r=null}function a(l,d){l===void 0&&(l=!1),d===void 0&&(d=1),o();const f=n.getBoundingClientRect(),{left:m,top:g,width:b,height:S}=f;if(l||e(),!b||!S)return;const w=floor(g),v=floor(s.clientWidth-(m+b)),_=floor(s.clientHeight-(g+S)),T=floor(m),U={rootMargin:-w+"px "+-v+"px "+-_+"px "+-T+"px",threshold:max(0,min(1,d))||1};let $=!0;function W(re){const D=re[0].intersectionRatio;if(!rectsAreEqual(f,n.getBoundingClientRect()))return a();if(D!==d){if(!$)return a();D?a(!1,D):i=setTimeout(()=>{a(!1,1e-7)},1e3)}$=!1}try{r=new IntersectionObserver(W,{...U,root:s.ownerDocument})}catch{r=new IntersectionObserver(W,U)}r.observe(n)}const u=getWindow(n),c=()=>a(t);return u.addEventListener("resize",c),a(!0),()=>{u.removeEventListener("resize",c),o()}}function autoUpdate(n,e,t,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,c=unwrapElement(n),l=i||s?[...c?getOverflowAncestors(c):[],...e?getOverflowAncestors(e):[]]:[];l.forEach(w=>{i&&w.addEventListener("scroll",t),s&&w.addEventListener("resize",t)});const d=c&&a?observeMove(c,t,s):null;let f=-1,m=null;o&&(m=new ResizeObserver(w=>{let[v]=w;v&&v.target===c&&m&&e&&(m.unobserve(e),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var _;(_=m)==null||_.observe(e)})),t()}),c&&!u&&m.observe(c),e&&m.observe(e));let g,b=u?getBoundingClientRect(n):null;u&&S();function S(){const w=getBoundingClientRect(n);b&&!rectsAreEqual(b,w)&&t(),b=w,g=requestAnimationFrame(S)}return t(),()=>{var w;l.forEach(v=>{i&&v.removeEventListener("scroll",t),s&&v.removeEventListener("resize",t)}),d?.(),(w=m)==null||w.disconnect(),m=null,u&&cancelAnimationFrame(g)}}const offset$1=offset$2,shift$1=shift$2,flip$1=flip$2,size$1=size$2,hide$1=hide$2,arrow$2=arrow$3,limitShift$1=limitShift$2,computePosition=(n,e,t)=>{const r=new Map,i=t??{},s={...platform,...i.platform,_c:r};return computePosition$1(n,e,{...i,platform:s})};var isClient=typeof document<"u",noop$2=function(){},index=isClient?reactExports.useLayoutEffect:noop$2;function deepEqual(n,e){if(n===e)return!0;if(typeof n!=typeof e)return!1;if(typeof n=="function"&&n.toString()===e.toString())return!0;let t,r,i;if(n&&e&&typeof n=="object"){if(Array.isArray(n)){if(t=n.length,t!==e.length)return!1;for(r=t;r--!==0;)if(!deepEqual(n[r],e[r]))return!1;return!0}if(i=Object.keys(n),t=i.length,t!==Object.keys(e).length)return!1;for(r=t;r--!==0;)if(!{}.hasOwnProperty.call(e,i[r]))return!1;for(r=t;r--!==0;){const s=i[r];if(!(s==="_owner"&&n.$$typeof)&&!deepEqual(n[s],e[s]))return!1}return!0}return n!==n&&e!==e}function getDPR(n){return typeof window>"u"?1:(n.ownerDocument.defaultView||window).devicePixelRatio||1}function roundByDPR(n,e){const t=getDPR(n);return Math.round(e*t)/t}function useLatestRef(n){const e=reactExports.useRef(n);return index(()=>{e.current=n}),e}function useFloating(n){n===void 0&&(n={});const{placement:e="bottom",strategy:t="absolute",middleware:r=[],platform:i,elements:{reference:s,floating:o}={},transform:a=!0,whileElementsMounted:u,open:c}=n,[l,d]=reactExports.useState({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[f,m]=reactExports.useState(r);deepEqual(f,r)||m(r);const[g,b]=reactExports.useState(null),[S,w]=reactExports.useState(null),v=reactExports.useCallback(ae=>{ae!==U.current&&(U.current=ae,b(ae))},[]),_=reactExports.useCallback(ae=>{ae!==$.current&&($.current=ae,w(ae))},[]),T=s||g,C=o||S,U=reactExports.useRef(null),$=reactExports.useRef(null),W=reactExports.useRef(l),re=u!=null,D=useLatestRef(u),V=useLatestRef(i),he=useLatestRef(c),z=reactExports.useCallback(()=>{if(!U.current||!$.current)return;const ae={placement:e,strategy:t,middleware:f};V.current&&(ae.platform=V.current),computePosition(U.current,$.current,ae).then(ve=>{const L={...ve,isPositioned:he.current!==!1};_e.current&&!deepEqual(W.current,L)&&(W.current=L,reactDomExports.flushSync(()=>{d(L)}))})},[f,e,t,V,he]);index(()=>{c===!1&&W.current.isPositioned&&(W.current.isPositioned=!1,d(ae=>({...ae,isPositioned:!1})))},[c]);const _e=reactExports.useRef(!1);index(()=>(_e.current=!0,()=>{_e.current=!1}),[]),index(()=>{if(T&&(U.current=T),C&&($.current=C),T&&C){if(D.current)return D.current(T,C,z);z()}},[T,C,z,D,re]);const Ce=reactExports.useMemo(()=>({reference:U,floating:$,setReference:v,setFloating:_}),[v,_]),Fe=reactExports.useMemo(()=>({reference:T,floating:C}),[T,C]),ze=reactExports.useMemo(()=>{const ae={position:t,left:0,top:0};if(!Fe.floating)return ae;const ve=roundByDPR(Fe.floating,l.x),L=roundByDPR(Fe.floating,l.y);return a?{...ae,transform:"translate("+ve+"px, "+L+"px)",...getDPR(Fe.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:ve,top:L}},[t,a,Fe.floating,l.x,l.y]);return reactExports.useMemo(()=>({...l,update:z,refs:Ce,elements:Fe,floatingStyles:ze}),[l,z,Ce,Fe,ze])}const arrow$1=n=>{function e(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:n,fn(t){const{element:r,padding:i}=typeof n=="function"?n(t):n;return r&&e(r)?r.current!=null?arrow$2({element:r.current,padding:i}).fn(t):{}:r?arrow$2({element:r,padding:i}).fn(t):{}}}},offset=(n,e)=>{const t=offset$1(n);return{name:t.name,fn:t.fn,options:[n,e]}},shift=(n,e)=>{const t=shift$1(n);return{name:t.name,fn:t.fn,options:[n,e]}},limitShift=(n,e)=>({fn:limitShift$1(n).fn,options:[n,e]}),flip=(n,e)=>{const t=flip$1(n);return{name:t.name,fn:t.fn,options:[n,e]}},size=(n,e)=>{const t=size$1(n);return{name:t.name,fn:t.fn,options:[n,e]}},hide=(n,e)=>{const t=hide$1(n);return{name:t.name,fn:t.fn,options:[n,e]}},arrow=(n,e)=>{const t=arrow$1(n);return{name:t.name,fn:t.fn,options:[n,e]}};var __defProp$3=Object.defineProperty,__name$3=(n,e)=>__defProp$3(n,"name",{value:e,configurable:!0});function useSize(n){const[e,t]=reactExports.useState(void 0);return useLayoutEffect2(()=>{if(n){t({width:n.offsetWidth,height:n.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const s=i[0];let o,a;if("borderBoxSize"in s){const u=s.borderBoxSize,c=Array.isArray(u)?u[0]:u;o=c.inlineSize,a=c.blockSize}else o=n.offsetWidth,a=n.offsetHeight;t({width:o,height:a})});return r.observe(n,{box:"border-box"}),()=>r.unobserve(n)}else t(void 0)},[n]),e}__name$3(useSize,"useSize");var __defProp$2=Object.defineProperty,__name$2=(n,e)=>__defProp$2(n,"name",{value:e,configurable:!0}),POPPER_NAME="Popper",[createPopperContext,createPopperScope]=createContextScope(POPPER_NAME),[PopperProvider,usePopperContext]=createPopperContext(POPPER_NAME),Popper=__name$2(n=>{const{__scopePopper:e,children:t}=n,[r,i]=reactExports.useState(null),[s,o]=reactExports.useState(void 0);return jsxRuntimeExports.jsx(PopperProvider,{scope:e,anchor:r,onAnchorChange:i,placementState:s,setPlacementState:o,children:t})},"Popper"),ANCHOR_NAME="PopperAnchor",PopperAnchor=reactExports.forwardRef(__name$2(function(e,t){const{__scopePopper:r,virtualRef:i,...s}=e,o=usePopperContext(ANCHOR_NAME,r),a=reactExports.useRef(null),u=o.onAnchorChange,c=reactExports.useCallback(b=>{a.current=b,b&&u(b)},[u]),l=useComposedRefs(t,c),d=reactExports.useRef(null);reactExports.useEffect(()=>{if(!i)return;const b=d.current;d.current=i.current,b!==d.current&&u(d.current)});const f=o.placementState&&getSideAndAlignFromPlacement(o.placementState),m=f?.[0],g=f?.[1];return i?null:jsxRuntimeExports.jsx(Primitive.div,{"data-radix-popper-side":m,"data-radix-popper-align":g,...s,ref:l})},"PopperAnchor")),CONTENT_NAME$1="PopperContent",[PopperContentProvider,useContentContext]=createPopperContext(CONTENT_NAME$1),PopperContent=reactExports.forwardRef(__name$2(function(e,t){const{__scopePopper:r,side:i="bottom",sideOffset:s=0,align:o="center",alignOffset:a=0,arrowPadding:u=0,avoidCollisions:c=!0,collisionBoundary:l=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:m=!1,updatePositionStrategy:g="optimized",onPlaced:b,...S}=e,w=usePopperContext(CONTENT_NAME$1,r),[v,_]=reactExports.useState(null),T=useComposedRefs(t,_),[C,U]=reactExports.useState(null),$=useSize(C),W=$?.width??0,re=$?.height??0,D=i+(o!=="center"?"-"+o:""),V=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},he=Array.isArray(l)?l:[l],z=he.length>0,_e={padding:V,boundary:he.filter(isNotNull),altBoundary:z},{refs:Ce,floatingStyles:Fe,placement:ze,isPositioned:ae,middlewareData:ve}=useFloating({strategy:"fixed",placement:D,whileElementsMounted:__name$2((...le)=>autoUpdate(...le,{animationFrame:g==="always"}),"whileElementsMounted"),elements:{reference:w.anchor},middleware:[offset({mainAxis:s+re,alignmentAxis:a}),c&&shift({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?limitShift():void 0,..._e}),c&&flip({..._e}),size({..._e,apply:__name$2(({elements:le,rects:Te,availableWidth:G,availableHeight:P})=>{const{width:x,height:A}=Te.reference,O=le.floating.style;O.setProperty("--radix-popper-available-width",`${G}px`),O.setProperty("--radix-popper-available-height",`${P}px`),O.setProperty("--radix-popper-anchor-width",`${x}px`),O.setProperty("--radix-popper-anchor-height",`${A}px`)},"apply")}),C&&arrow({element:C,padding:u}),transformOrigin({arrowWidth:W,arrowHeight:re}),m&&hide({strategy:"referenceHidden",..._e,boundary:z?_e.boundary:void 0})]}),L=w.setPlacementState;useLayoutEffect2(()=>(L(ze),()=>{L(void 0)}),[ze,L]);const[ie,xe]=getSideAndAlignFromPlacement(ze),ue=useCallbackRef(b);useLayoutEffect2(()=>{ae&&ue?.()},[ae,ue]);const De=ve.arrow?.x,ke=ve.arrow?.y,We=ve.arrow?.centerOffset!==0,[Oe,te]=reactExports.useState();return useLayoutEffect2(()=>{v&&te(window.getComputedStyle(v).zIndex)},[v]),jsxRuntimeExports.jsx("div",{ref:Ce.setFloating,"data-radix-popper-content-wrapper":"",style:{...Fe,transform:ae?Fe.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Oe,"--radix-popper-transform-origin":[ve.transformOrigin?.x,ve.transformOrigin?.y].join(" "),...ve.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:jsxRuntimeExports.jsx(PopperContentProvider,{scope:r,placedSide:ie,placedAlign:xe,onArrowChange:U,arrowX:De,arrowY:ke,shouldHideArrow:We,children:jsxRuntimeExports.jsx(Primitive.div,{"data-side":ie,"data-align":xe,...S,ref:T,style:{...S.style,animation:ae?S.style?.animation:"none"}})})})},"PopperContent"));function isNotNull(n){return n!==null}__name$2(isNotNull,"isNotNull");var transformOrigin=__name$2(n=>({name:"transformOrigin",options:n,fn(e){const{placement:t,rects:r,middlewareData:i}=e,o=i.arrow?.centerOffset!==0,a=o?0:n.arrowWidth,u=o?0:n.arrowHeight,[c,l]=getSideAndAlignFromPlacement(t),d={start:"0%",center:"50%",end:"100%"}[l],f=(i.arrow?.x??0)+a/2,m=(i.arrow?.y??0)+u/2;let g="",b="";return c==="bottom"?(g=o?d:`${f}px`,b=`${-u}px`):c==="top"?(g=o?d:`${f}px`,b=`${r.floating.height+u}px`):c==="right"?(g=`${-u}px`,b=o?d:`${m}px`):c==="left"&&(g=`${r.floating.width+u}px`,b=o?d:`${m}px`),{data:{x:g,y:b}}}}),"transformOrigin");function getSideAndAlignFromPlacement(n){const[e,t="center"]=n.split("-");return[e,t]}__name$2(getSideAndAlignFromPlacement,"getSideAndAlignFromPlacement");var Root2=Popper,Anchor=PopperAnchor,Content=PopperContent,__defProp$1=Object.defineProperty,__name$1=(n,e)=>__defProp$1(n,"name",{value:e,configurable:!0}),VISUALLY_HIDDEN_STYLES=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),VisuallyHidden=reactExports.forwardRef(__name$1(function(e,t){return jsxRuntimeExports.jsx(Primitive.span,{...e,ref:t,style:{...VISUALLY_HIDDEN_STYLES,...e.style}})},"VisuallyHidden")),Root=VisuallyHidden,__defProp=Object.defineProperty,__name=(n,e)=>__defProp(n,"name",{value:e,configurable:!0}),[createTooltipContext,createTooltipScope]=createContextScope("Tooltip",[createPopperScope]),usePopperScope=createPopperScope(),PROVIDER_NAME="TooltipProvider",DEFAULT_DELAY_DURATION=700,TOOLTIP_OPEN="tooltip.open",[TooltipProviderContextProvider,useTooltipProviderContext]=createTooltipContext(PROVIDER_NAME),TooltipProvider$1=__name(n=>{const{__scopeTooltip:e,delayDuration:t=DEFAULT_DELAY_DURATION,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:s}=n,o=reactExports.useRef(!0),a=reactExports.useRef(!1),u=reactExports.useRef(0);return reactExports.useEffect(()=>{const c=u.current;return()=>window.clearTimeout(c)},[]),jsxRuntimeExports.jsx(TooltipProviderContextProvider,{scope:e,isOpenDelayedRef:o,delayDuration:t,onOpen:reactExports.useCallback(()=>{r<=0||(window.clearTimeout(u.current),o.current=!1)},[r]),onClose:reactExports.useCallback(()=>{r<=0||(window.clearTimeout(u.current),u.current=window.setTimeout(()=>o.current=!0,r))},[r]),isPointerInTransitRef:a,onPointerInTransitChange:reactExports.useCallback(c=>{a.current=c},[]),disableHoverableContent:i,children:s})},"TooltipProvider"),TOOLTIP_NAME="Tooltip",[TooltipContextProvider,useTooltipContext]=createTooltipContext(TOOLTIP_NAME),Tooltip$1=__name(n=>{const{__scopeTooltip:e,children:t,open:r,defaultOpen:i,onOpenChange:s,disableHoverableContent:o,delayDuration:a}=n,u=useTooltipProviderContext(TOOLTIP_NAME,n.__scopeTooltip),c=usePopperScope(e),[l,d]=reactExports.useState(null),[f,m]=reactExports.useState(void 0),g=useId(),b=reactExports.useRef(0),S=o??u.disableHoverableContent,w=a??u.delayDuration,v=reactExports.useRef(!1),[_,T]=useControllableState({prop:r,defaultProp:i??!1,onChange:__name(D=>{D?(u.onOpen(),document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN))):u.onClose(),s?.(D)},"onChange"),caller:TOOLTIP_NAME}),C=reactExports.useMemo(()=>_?v.current?"delayed-open":"instant-open":"closed",[_]),U=reactExports.useCallback(()=>{window.clearTimeout(b.current),b.current=0,v.current=!1,T(!0)},[T]),$=reactExports.useCallback(()=>{window.clearTimeout(b.current),b.current=0,T(!1)},[T]),W=reactExports.useCallback(()=>{window.clearTimeout(b.current),b.current=window.setTimeout(()=>{v.current=!0,T(!0),b.current=0},w)},[w,T]);reactExports.useEffect(()=>()=>{b.current&&(window.clearTimeout(b.current),b.current=0)},[]);const re=f??g;return jsxRuntimeExports.jsx(Root2,{...c,children:jsxRuntimeExports.jsx(TooltipContextProvider,{scope:e,contentId:re,setContentId:m,open:_,stateAttribute:C,trigger:l,onTriggerChange:d,onTriggerEnter:reactExports.useCallback(()=>{u.isOpenDelayedRef.current?W():U()},[u.isOpenDelayedRef,W,U]),onTriggerLeave:reactExports.useCallback(()=>{S?$():(window.clearTimeout(b.current),b.current=0)},[$,S]),onOpen:U,onClose:$,disableHoverableContent:S,children:t})})},"Tooltip"),TRIGGER_NAME="TooltipTrigger",TooltipTrigger$1=reactExports.forwardRef(__name(function(e,t){const{__scopeTooltip:r,...i}=e,s=useTooltipContext(TRIGGER_NAME,r),o=useTooltipProviderContext(TRIGGER_NAME,r),a=usePopperScope(r),u=reactExports.useRef(null),c=useComposedRefs(t,u,s.onTriggerChange),l=reactExports.useRef(!1),d=reactExports.useRef(!1),f=reactExports.useCallback(()=>l.current=!1,[]);return reactExports.useEffect(()=>()=>document.removeEventListener("pointerup",f),[f]),jsxRuntimeExports.jsx(Anchor,{asChild:!0,...a,children:jsxRuntimeExports.jsx(Primitive.button,{"aria-describedby":s.open?s.contentId:void 0,"data-state":s.stateAttribute,...i,ref:c,onPointerMove:composeEventHandlers(e.onPointerMove,m=>{m.pointerType!=="touch"&&!d.current&&!o.isPointerInTransitRef.current&&(s.onTriggerEnter(),d.current=!0)}),onPointerLeave:composeEventHandlers(e.onPointerLeave,()=>{s.onTriggerLeave(),d.current=!1}),onPointerDown:composeEventHandlers(e.onPointerDown,()=>{s.open&&s.onClose(),l.current=!0,document.addEventListener("pointerup",f,{once:!0})}),onFocus:composeEventHandlers(e.onFocus,()=>{l.current||s.onOpen()}),onBlur:composeEventHandlers(e.onBlur,s.onClose),onClick:composeEventHandlers(e.onClick,s.onClose)})})},"TooltipTrigger")),PORTAL_NAME="TooltipPortal",[PortalProvider,usePortalContext]=createTooltipContext(PORTAL_NAME,{forceMount:void 0}),TooltipPortal$1=__name(n=>{const{__scopeTooltip:e,forceMount:t,children:r,container:i}=n,s=useTooltipContext(PORTAL_NAME,e);return jsxRuntimeExports.jsx(PortalProvider,{scope:e,forceMount:t,children:jsxRuntimeExports.jsx(Presence,{present:t||s.open,children:jsxRuntimeExports.jsx(Portal$1,{asChild:!0,container:i,children:r})})})},"TooltipPortal"),CONTENT_NAME="TooltipContent",TooltipContent$1=reactExports.forwardRef(__name(function(e,t){const r=usePortalContext(CONTENT_NAME,e.__scopeTooltip),{forceMount:i=r.forceMount,side:s="top",...o}=e,a=useTooltipContext(CONTENT_NAME,e.__scopeTooltip);return jsxRuntimeExports.jsx(Presence,{present:i||a.open,children:a.disableHoverableContent?jsxRuntimeExports.jsx(TooltipContentImpl,{side:s,...o,ref:t}):jsxRuntimeExports.jsx(TooltipContentHoverable,{side:s,...o,ref:t})})},"TooltipContent")),TooltipContentHoverable=reactExports.forwardRef(__name(function(e,t){const r=useTooltipContext(CONTENT_NAME,e.__scopeTooltip),i=useTooltipProviderContext(CONTENT_NAME,e.__scopeTooltip),s=reactExports.useRef(null),o=useComposedRefs(t,s),[a,u]=reactExports.useState(null),{trigger:c,onClose:l}=r,d=s.current,{onPointerInTransitChange:f}=i,m=reactExports.useCallback(()=>{u(null),f(!1)},[f]),g=reactExports.useCallback((b,S)=>{const w=b.currentTarget,v={x:b.clientX,y:b.clientY},_=getExitSideFromRect(v,w.getBoundingClientRect()),T=getPaddedExitPoints(v,_),C=getPointsFromRect(S.getBoundingClientRect()),U=getHull([...T,...C]);u(U),f(!0)},[f]);return reactExports.useEffect(()=>()=>m(),[m]),reactExports.useEffect(()=>{if(c&&d){const b=__name(w=>g(w,d),"handleTriggerLeave"),S=__name(w=>g(w,c),"handleContentLeave");return c.addEventListener("pointerleave",b),d.addEventListener("pointerleave",S),()=>{c.removeEventListener("pointerleave",b),d.removeEventListener("pointerleave",S)}}},[c,d,g,m]),reactExports.useEffect(()=>{if(a){const b=__name(S=>{const w=S.target,v={x:S.clientX,y:S.clientY},_=c?.contains(w)||d?.contains(w),T=!isPointInPolygon(v,a);_?m():T&&(m(),l())},"handleTrackPointerGrace");return document.addEventListener("pointermove",b),()=>document.removeEventListener("pointermove",b)}},[c,d,a,l,m]),jsxRuntimeExports.jsx(TooltipContentImpl,{...e,ref:o})},"TooltipContentHoverable")),Slottable=createSlottable("TooltipContent"),TooltipContentImpl=reactExports.forwardRef(__name(function(e,t){const{__scopeTooltip:r,children:i,"aria-label":s,id:o,onEscapeKeyDown:a,onPointerDownOutside:u,...c}=e,l=useTooltipContext(CONTENT_NAME,r),d=usePopperScope(r),{onClose:f}=l;reactExports.useEffect(()=>(document.addEventListener(TOOLTIP_OPEN,f),()=>document.removeEventListener(TOOLTIP_OPEN,f)),[f]),reactExports.useEffect(()=>{if(l.trigger){const g=__name(b=>{b.target instanceof Node&&b.target.contains(l.trigger)&&f()},"handleScroll");return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[l.trigger,f]);const{setContentId:m}=l;return useLayoutEffect2(()=>(m(o),()=>{m(void 0)}),[o,m]),jsxRuntimeExports.jsx(DismissableLayer,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:a,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:f,children:jsxRuntimeExports.jsxs(Content,{"data-state":l.stateAttribute,role:s?void 0:"tooltip",id:s?void 0:l.contentId,...d,...c,ref:t,style:{...c.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[jsxRuntimeExports.jsx(Slottable,{children:i}),s?jsxRuntimeExports.jsx(Root,{id:l.contentId,role:"tooltip",children:s}):null]})})},"TooltipContentImpl"));function getExitSideFromRect(n,e){const t=Math.abs(e.top-n.y),r=Math.abs(e.bottom-n.y),i=Math.abs(e.right-n.x),s=Math.abs(e.left-n.x);switch(Math.min(t,r,i,s)){case s:return"left";case i:return"right";case t:return"top";case r:return"bottom";default:throw new Error("unreachable")}}__name(getExitSideFromRect,"getExitSideFromRect");function getPaddedExitPoints(n,e,t=5){const r=[];switch(e){case"top":r.push({x:n.x-t,y:n.y+t},{x:n.x+t,y:n.y+t});break;case"bottom":r.push({x:n.x-t,y:n.y-t},{x:n.x+t,y:n.y-t});break;case"left":r.push({x:n.x+t,y:n.y-t},{x:n.x+t,y:n.y+t});break;case"right":r.push({x:n.x-t,y:n.y-t},{x:n.x-t,y:n.y+t});break}return r}__name(getPaddedExitPoints,"getPaddedExitPoints");function getPointsFromRect(n){const{top:e,right:t,bottom:r,left:i}=n;return[{x:i,y:e},{x:t,y:e},{x:t,y:r},{x:i,y:r}]}__name(getPointsFromRect,"getPointsFromRect");function isPointInPolygon(n,e){const{x:t,y:r}=n;let i=!1;for(let s=0,o=e.length-1;s<e.length;o=s++){const a=e[s],u=e[o],c=a.x,l=a.y,d=u.x,f=u.y;l>r!=f>r&&t<(d-c)*(r-l)/(f-l)+c&&(i=!i)}return i}__name(isPointInPolygon,"isPointInPolygon");function getHull(n){const e=n.slice();return e.sort((t,r)=>t.x<r.x?-1:t.x>r.x?1:t.y<r.y?-1:t.y>r.y?1:0),getHullPresorted(e)}__name(getHull,"getHull");function getHullPresorted(n){if(n.length<=1)return n.slice();const e=[];for(let r=0;r<n.length;r++){const i=n[r];for(;e.length>=2;){const s=e[e.length-1],o=e[e.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))e.pop();else break}e.push(i)}e.pop();const t=[];for(let r=n.length-1;r>=0;r--){const i=n[r];for(;t.length>=2;){const s=t[t.length-1],o=t[t.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))t.pop();else break}t.push(i)}return t.pop(),e.length===1&&t.length===1&&e[0].x===t[0].x&&e[0].y===t[0].y?e:e.concat(t)}__name(getHullPresorted,"getHullPresorted");var Provider=TooltipProvider$1,Root3=Tooltip$1,Trigger=TooltipTrigger$1,Portal=TooltipPortal$1,Content2=TooltipContent$1;const TooltipProvider=Provider,Tooltip=Root3,TooltipTrigger=Trigger,TooltipPortal=Portal,TooltipContent=reactExports.forwardRef(({className:n,sideOffset:e=4,...t},r)=>jsxRuntimeExports.jsx(Content2,{ref:r,sideOffset:e,className:cn("z-[var(--layer-popover)] overflow-hidden rounded-md border border-border/50 bg-popover","px-2 py-1 text-xs text-popover-foreground shadow-md","animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n),...t}));TooltipContent.displayName=Content2.displayName;function BrandInfo({logo:n,info:e,infoLabel:t="Details",className:r}){const[i,s]=reactExports.useState(!1),o=reactExports.useRef(null);return jsxRuntimeExports.jsxs("div",{className:cn("inline-flex min-w-0 items-center gap-1",r),children:[n,e!=null&&e!==!1?jsxRuntimeExports.jsx(TooltipProvider,{delayDuration:150,children:jsxRuntimeExports.jsxs(Tooltip,{open:i,onOpenChange:s,children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsx("button",{ref:o,type:"button","aria-label":t,"aria-expanded":i,className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-primary/10 hover:text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onPointerDown:a=>a.preventDefault(),onClick:a=>{a.preventDefault(),s(u=>!u)},children:jsxRuntimeExports.jsx(Info,{className:"h-4 w-4","aria-hidden":"true"})})}),jsxRuntimeExports.jsx(TooltipPortal,{children:jsxRuntimeExports.jsx(TooltipContent,{side:"bottom",align:"center",collisionPadding:12,onPointerDownOutside:a=>{a.target instanceof Node&&o.current?.contains(a.target)&&a.preventDefault()},className:"max-w-[min(320px,calc(100vw-24px))] space-y-2 p-3 text-left leading-relaxed [overflow-wrap:anywhere]",children:e})})]})}):null]})}const Checkbox=reactExports.forwardRef(({className:n,indeterminate:e=!1,...t},r)=>{const i=reactExports.useRef(null);return reactExports.useImperativeHandle(r,()=>i.current),reactExports.useEffect(()=>{i.current&&(i.current.indeterminate=e)}),jsxRuntimeExports.jsxs("span",{className:"relative inline-flex shrink-0 items-center justify-center align-middle",children:[jsxRuntimeExports.jsx("input",{...t,ref:i,type:"checkbox",className:cn("peer m-0 h-4 w-4 shrink-0 appearance-none rounded border border-input bg-background checked:border-primary checked:bg-primary checked:bg-none indeterminate:border-primary indeterminate:bg-primary indeterminate:bg-none disabled:cursor-not-allowed disabled:opacity-50",controlFocusClass,n)}),jsxRuntimeExports.jsx(Check,{"aria-hidden":"true",className:"pointer-events-none absolute hidden h-3 w-3 text-primary-foreground peer-checked:block peer-indeterminate:hidden peer-disabled:opacity-50",strokeWidth:3}),jsxRuntimeExports.jsx(Minus,{"aria-hidden":"true",className:"pointer-events-none absolute hidden h-3 w-3 text-primary-foreground peer-indeterminate:block peer-disabled:opacity-50",strokeWidth:3})]})});Checkbox.displayName="Checkbox";function FormField({label:n,error:e,hint:t,labelAside:r,children:i,className:s,...o}){const a=reactExports.useId(),u=`${a}-error`,c=`${a}-hint`,l=[e?u:void 0,t?c:void 0].filter(Boolean).join(" ")||void 0;return jsxRuntimeExports.jsxs("div",{...o,className:cn("flex flex-col gap-1.5",s),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("label",{htmlFor:a,className:"text-[13px] font-medium text-foreground",children:n}),r]}),i({id:a,...e?{"aria-invalid":!0}:{},"aria-describedby":l}),e?jsxRuntimeExports.jsx("p",{id:u,role:"alert",className:"text-[13px] text-destructive",children:e}):null,t?jsxRuntimeExports.jsx("div",{id:c,className:"text-[13px] text-muted-foreground",children:t}):null]})}const EmailInput=reactExports.forwardRef(({onInput:n,onChange:e,autoCapitalize:t="none",spellCheck:r=!1,...i},s)=>{const o=reactExports.useRef(null),a=reactExports.useRef(null);reactExports.useImperativeHandle(s,()=>o.current,[]);const u=reactExports.useCallback(l=>{const d=a.current??(a.current=l.ownerDocument.createElement("input"));d.type="email",d.multiple=l.multiple,d.required=l.required,d.value=l.value,l.setCustomValidity(d.validity.valid?"":d.validationMessage)},[]);reactExports.useLayoutEffect(()=>{o.current&&u(o.current)}),reactExports.useEffect(()=>{const l=o.current,d=l?.form;if(!l||!d)return;const f=()=>queueMicrotask(()=>u(l));return d.addEventListener("reset",f),()=>d.removeEventListener("reset",f)},[i.form,u]);const c=l=>{u(l),queueMicrotask(()=>u(l))};return jsxRuntimeExports.jsx(Input,{...i,ref:o,type:"text",inputMode:"email",autoCapitalize:t,spellCheck:r,onInput:l=>{c(l.currentTarget),n?.(l)},onChange:l=>{c(l.currentTarget),e?.(l)}})});EmailInput.displayName="EmailInput";const FOCUSABLE=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","summary",'[tabindex]:not([tabindex="-1"])'].join(","),PRIMARY_SELECTOR="[data-pod-sign-in-primary]";function isReachable(n){if(n.hidden||n.closest("[hidden]")||n.matches(":disabled"))return!1;const e=n.ownerDocument.defaultView?.getComputedStyle(n);if(e&&(e.display==="none"||e.visibility==="hidden"))return!1;for(let t=n.parentElement;t;t=t.parentElement){if(t.tagName!=="DETAILS"||t.open)continue;const r=Array.from(t.children).find(i=>i.tagName==="SUMMARY");if(!r||!(r===n||r.contains(n)))return!1}return!0}function useModalFocus(n,e){const t=reactExports.useRef(null),r=reactExports.useRef(e);return r.current=e,reactExports.useEffect(()=>{if(!n)return;const i=document.activeElement instanceof HTMLElement?document.activeElement:null;t.current?.focus();const s=o=>{if(o.key==="Escape"&&r.current){o.preventDefault(),r.current();return}if(o.key!=="Tab")return;const a=t.current;if(!a)return;const u=Array.from(a.querySelectorAll(FOCUSABLE)).filter(isReachable);if(u.length===0){o.preventDefault(),a.focus();return}const c=u.indexOf(document.activeElement);if(!o.shiftKey&&document.activeElement===a){const d=u.find(f=>f.matches(PRIMARY_SELECTOR));if(d){o.preventDefault(),d.focus();return}}const l=o.shiftKey?c<=0?u.length-1:c-1:c===u.length-1?0:c+1;o.preventDefault(),u[l]?.focus()};return document.addEventListener("keydown",s),()=>{document.removeEventListener("keydown",s),i?.focus()}},[n]),t}const bodyClass="flex min-h-0 w-full max-w-[480px] flex-1 flex-col";function PodSignInFrame({presentation:n,ariaLabel:e,appIntro:t,children:r,modal:i=!0,onClose:s,closeLabel:o,dataAttributes:a}){const u=n==="dialog"&&i,c=useModalFocus(u,s),l=t;if(n==="window")return jsxRuntimeExports.jsx("div",{role:"region","aria-label":e,"data-pod-sign-in-frame":"window",...a,className:"pod-sign-in flex h-full min-h-0 w-full min-w-0 justify-center overflow-hidden bg-background text-foreground",children:jsxRuntimeExports.jsx("div",{className:bodyClass,children:r})});if(n==="page")return jsxRuntimeExports.jsxs("div",{role:"region","aria-label":e,"data-pod-sign-in-frame":"page",...a,className:"pod-sign-in grid min-h-[100dvh] w-full bg-background text-foreground md:grid-cols-2",children:[l?jsxRuntimeExports.jsx("aside",{"data-pod-sign-in":"intro",className:"hidden flex-col justify-center gap-6 bg-[hsl(var(--sunken))] px-12 py-10 md:flex",children:l}):null,jsxRuntimeExports.jsx("div",{className:cn("flex min-w-0 items-center justify-center px-4 py-8",l?"":"md:col-span-2"),children:jsxRuntimeExports.jsx("div",{className:cn(bodyClass,"min-h-[520px]"),children:r})})]});const d=jsxRuntimeExports.jsxs("div",{ref:c,role:u?"dialog":"region","aria-modal":u?!0:void 0,"aria-label":e,tabIndex:-1,"data-pod-sign-in-frame":"dialog",...a,className:cn("pod-sign-in relative flex min-h-[min(440px,90dvh)] max-h-[90dvh] w-[min(480px,calc(100vw-2rem))] flex-col overflow-hidden rounded-xl border border-border bg-card text-card-foreground shadow-lg focus:outline-none motion-safe:animate-in motion-safe:fade-in-0"),children:[u&&s&&o?jsxRuntimeExports.jsx("button",{type:"button","aria-label":o,className:"absolute right-2 top-2 flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",onClick:s,children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null,jsxRuntimeExports.jsx("div",{className:cn(bodyClass,"mx-auto"),children:r})]});return u?jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[var(--layer-modal)] flex items-center justify-center bg-background/80 p-4",children:d}):jsxRuntimeExports.jsx("div",{className:"flex w-full items-center justify-center p-4",children:d})}function StorageBadge({kind:n,label:e}){const t=n==="cloud"?Cloud:Laptop;return jsxRuntimeExports.jsx("span",{role:"img","aria-label":e,title:e,"data-storage-kind":n,className:"flex h-[18px] w-[18px] items-center justify-center rounded-full border border-background bg-card text-foreground",children:jsxRuntimeExports.jsx(t,{"aria-hidden":"true",className:"h-3 w-3"})})}const zhCN={restoring:"正在恢复登录…",enterApp:"进入 {app}",reauthenticate:"重新登录",useAnother:"使用其他账号",expiredLine:"登录已过期,需要重新确认",chooseTitle:"登录",chooseLead:"用你的 WebID 账号登录,数据保存在你自己的 Pod 里",useXpod:"使用 Xpod 账号登录",useOtherSolid:"使用其他 Solid 账号",customLabel:"账号服务地址或 WebID",customPlaceholder:"https://example.com/",customSubmit:"继续",noAccount:"没有账号?",register:"注册 Xpod",noticeDetailsToggle:"详情",noticeCopy:"复制",noticeCopied:"已复制",whatIsPod:"什么是 Pod?",whatIsPodBody:"Pod 是保存你数据的个人空间。",whatIsWebId:"什么是 WebID?",whatIsWebIdBody:"WebID 是登录用的身份,它指向你的个人资料和 Pod。",signInWith:"使用 {service} 登录",select:"选择",selected:"已选择",choosePodTitle:"选择 Pod",choosePodLead:"选择要继续使用的 Pod",retry:"重试",goCreate:"去创建",refreshPage:"刷新页面",startAndEnter:"启动 Xpod 并进入",openXpod:"打开 Xpod",noticeUnreachable:"暂时连不上 Xpod,请稍后再试",noticeIncomplete:"登录没有完成,请再试一次",noticeNoWebId:"还没有 WebID",noticeCancelled:"登录已取消",noticeLocalStopped:"这台电脑上的 Xpod 没有运行",noticePending:"上次登录尚未结束",serviceLabel:"账号服务",signInTitle:"登录 {service}",returnToApp:"完成后回到 {app}",email:"邮箱",password:"密码",forgotPassword:"忘记密码?",rememberDevice:"在这台设备上保持登录",signIn:"登录",registerLink:"注册账号",registerTitle:"注册 {service}",username:"用户名",registerSubmit:"注册",haveAccount:"已有账号?登录",podElsewhereSummary:"想用你自己的独立部署存放 Pod?",podElsewhereBody:"注册后,可以在账号页的“存储”里把 Pod 建到你自己的独立部署上;它和当前账号服务是分开的,普通浏览器不会自动把 Pod 转到本机。",noWebIdTitle:"还没有 WebID",noWebIdLead:"新建一个 WebID 来登录 {app},数据存在它的 Pod 里",webIdName:"WebID 名称",noWebIdLocation:"存放在当前服务",createAndContinue:"创建并继续",chooseOtherLocation:"存到边缘设备(打开账号页)",consentTitle:"授权 {app}",unverifiedWarning:"未能验证这个应用的来源,请确认是你要使用的应用",chooseWebId:"用哪个 WebID 登录?",consentConsequence:"{app} 将以这个身份读写你的数据,之后可以在 Xpod 中收回。",requestDetails:"请求详情",scopes:"权限范围",clientId:"应用标识",webIdFull:"WebID",rememberChoice:"以后不再询问",manageAccount:"管理账号",switchAccount:"换一个账号",deny:"拒绝",allow:"允许",storageCloud:"数据存在 Xpod 云端",storageEdge:"数据存在边缘设备上",hostedStorage:"账号服务托管",independentStorage:"独立部署",identityAddress:"WebID(身份地址)",storageAddress:"Pod(存储地址)",showAddresses:"查看地址",webIdSectionTitle:"WebID",webIdEmpty:"还没有 WebID。新建一个,用它登录应用。",createWebId:"新建 WebID",linkExistingWebId:"关联已有 WebID",podOnDevice:"Pod 在 {device}",authorizedApps:"已授权 {count} 个应用",createStepName:"名称",createStepLocation:"存放在",createNameHint:"WebID 地址",changeDevice:"更换 ›",cannotChangeLater:"创建后不能直接更换,以后要换请使用迁移",createPod:"创建 WebID 和 Pod",startDeviceXpod:"启动这台设备上的 Xpod",creatingNote:"关闭页面不会中断创建",cancel:"取消",devicePickerTitle:"选择存放设备",addDevice:"+ 添加设备",deviceSectionTitle:"设备",deviceStatusOk:"正常",deviceStatusUnreachable:"⚠ 其他设备访问不到",deviceStatusStopped:"Xpod 已停止",deviceStatusOffline:"离线",deviceCloud:"Xpod 云端",deviceEdge:"边缘",podCount:"{count} 个 Pod",networkAction:"网络",fixAction:"处理",collapseAction:"收起",webIdSectionHint:"登录应用时使用的身份,数据存在它的 Pod 里",deviceSectionHint:"Pod 可以存放的地方,网络设置跟着设备走",credentialSectionHint:"让脚本或服务以某个 WebID 直接访问 Pod",startAction:"启动",networkTitle:"网络访问",probeLocal:"这台电脑",probeLan:"局域网",probeWan:"其他网络",probeIdle:"未检测",probeChecking:"检测中",probeOk:"可以访问",probeFailed:"不通",tunnelTitle:"选择隧道",enableAndRecheck:"开启并重新检测",enableAndCheck:"开启并检测",recheck:"重新检测",skipForNow:"跳过,稍后设置",reachableVia:"通过 {tunnel} 可以访问",networkFootnote:"只影响其他设备;这台电脑上照常可用",addDeviceTitle:"添加设备",stepInstall:"安装并登录",stepNetwork:"检查网络",stepDone:"完成",joinThisComputer:"把这台电脑加入",installOnOther:"在那台设备上安装 Xpod 边缘并登录本账号",waitingForDevice:"正在等待新设备上线,登录后这里会自动继续",deviceOnline:"已上线",finish:"完成",useThisDevice:"用这台设备",credentialSectionTitle:"密钥",credentialEmpty:"还没有密钥。",createCredential:"新建密钥",revokeCredential:"删除",resumeTitle:"{app} 正在等你完成授权",resumeWaiting:"在下面新建一个 WebID,完成后就能回去授权",resumeReady:"WebID 已就绪,可以回去授权了",resumeCancel:"取消授权",resumeContinue:"继续授权 {app}",close:"关闭"},en={restoring:"Restoring your sign-in…",enterApp:"Open {app}",reauthenticate:"Sign in again",useAnother:"Use another account",expiredLine:"Your sign-in expired. Please confirm again.",chooseTitle:"Sign in",chooseLead:"Sign in with your WebID account. Your data stays in your own Pod.",useXpod:"Sign in with Xpod",useOtherSolid:"Use another Solid account",customLabel:"Sign-in service address or WebID",customPlaceholder:"https://example.com/",customSubmit:"Continue",noAccount:"No account?",register:"Register for Xpod",noticeDetailsToggle:"Details",noticeCopy:"Copy",noticeCopied:"Copied",whatIsPod:"What is a Pod?",whatIsPodBody:"A Pod is a personal space that holds your data.",whatIsWebId:"What is a WebID?",whatIsWebIdBody:"A WebID is the identity you sign in with. It points to your profile and your Pod.",signInWith:"Sign in with {service}",select:"Select",selected:"Selected",choosePodTitle:"Choose a Pod",choosePodLead:"Choose the Pod to continue with",retry:"Retry",goCreate:"Create one",refreshPage:"Refresh page",startAndEnter:"Start Xpod and open",openXpod:"Open Xpod",noticeUnreachable:"Cannot reach Xpod right now. Please try again later.",noticeIncomplete:"Sign-in did not finish. Please try again.",noticeNoWebId:"No WebID yet",noticeCancelled:"Sign-in cancelled",noticeLocalStopped:"Xpod is not running on this computer",noticePending:"The previous sign-in has not finished",serviceLabel:"Sign-in service",signInTitle:"Sign in to {service}",returnToApp:"You will return to {app}",email:"Email",password:"Password",forgotPassword:"Forgot password?",rememberDevice:"Keep me signed in on this device",signIn:"Sign in",registerLink:"Register",registerTitle:"Register for {service}",username:"Username",registerSubmit:"Register",haveAccount:"Already have an account? Sign in",podElsewhereSummary:"Want it on your own standalone deployment?",podElsewhereBody:"After registering, create the Pod on your own standalone deployment under Storage on the account page; it is separate from this account service.",noWebIdTitle:"No WebID yet",noWebIdLead:"Create a WebID to sign in to {app}. Your data lives in its Pod.",webIdName:"WebID name",noWebIdLocation:"Stored on the current service",createAndContinue:"Create and continue",chooseOtherLocation:"Store on an edge device (open account page)",consentTitle:"Authorize {app}",unverifiedWarning:"We could not verify this application. Make sure it is the one you meant to use.",chooseWebId:"Which WebID do you sign in with?",consentConsequence:"{app} will read and write your data as this identity. You can revoke it later in Xpod.",requestDetails:"Request details",scopes:"Permissions",clientId:"Application ID",webIdFull:"WebID",rememberChoice:"Do not ask again",manageAccount:"Manage account",switchAccount:"Switch account",deny:"Deny",allow:"Allow",storageCloud:"Data is stored on Xpod Cloud",storageEdge:"Data is stored on an edge device",hostedStorage:"Hosted by account service",independentStorage:"Independent deployment",identityAddress:"WebID (identity address)",storageAddress:"Pod (storage address)",showAddresses:"View addresses",webIdSectionTitle:"WebID",webIdEmpty:"No WebID yet. Create one to sign in to applications.",createWebId:"New WebID",linkExistingWebId:"Link an existing WebID",podOnDevice:"Pod on {device}",authorizedApps:"{count} authorized apps",createStepName:"Name",createStepLocation:"Store on",createNameHint:"WebID address",changeDevice:"Change ›",cannotChangeLater:"It cannot be changed directly after creation. Use migration later.",createPod:"Create WebID and Pod",startDeviceXpod:"Start Xpod on this device",creatingNote:"Closing this page will not interrupt creation",cancel:"Cancel",devicePickerTitle:"Choose where to store",addDevice:"+ Add device",deviceSectionTitle:"Devices",deviceStatusOk:"Healthy",deviceStatusUnreachable:"⚠ Not reachable from other devices",deviceStatusStopped:"Xpod stopped",deviceStatusOffline:"Offline",deviceCloud:"Xpod Cloud",deviceEdge:"Edge",podCount:"{count} Pods",networkAction:"Network",fixAction:"Fix",collapseAction:"Collapse",webIdSectionHint:"The identity you sign in to apps with. Your data lives in its Pod.",deviceSectionHint:"Places a Pod can live. Network settings follow the device.",credentialSectionHint:"Let a script or service reach a Pod directly as one WebID.",startAction:"Start",networkTitle:"Network access",probeLocal:"This computer",probeLan:"Local network",probeWan:"Other networks",probeIdle:"Not checked",probeChecking:"Checking",probeOk:"Reachable",probeFailed:"Unreachable",tunnelTitle:"Choose a tunnel",enableAndRecheck:"Enable and recheck",enableAndCheck:"Enable and check",recheck:"Recheck",skipForNow:"Skip, set up later",reachableVia:"Reachable through {tunnel}",networkFootnote:"Only affects other devices. This computer keeps working as usual.",addDeviceTitle:"Add a device",stepInstall:"Install and sign in",stepNetwork:"Check network",stepDone:"Done",joinThisComputer:"Add this computer",installOnOther:"Install Xpod Edge on that device and sign in to this account",waitingForDevice:"Waiting for the new device to come online. This continues automatically after sign-in.",deviceOnline:"Online",finish:"Done",useThisDevice:"Use this device",credentialSectionTitle:"Credentials",credentialEmpty:"No credentials yet.",createCredential:"New credential",revokeCredential:"Delete",resumeTitle:"{app} is waiting for you to finish authorizing",resumeWaiting:"Create a WebID below, then you can go back and authorize",resumeReady:"Your WebID is ready. You can go back and authorize.",resumeCancel:"Cancel authorization",resumeContinue:"Continue authorizing {app}",close:"Close"},podSignInCopy={"zh-CN":zhCN,en};function resolvePodSignInCopy(n="zh-CN",e){return{...podSignInCopy[n],...e}}function formatCopy(n,e){return n.replace(/\{(\w+)\}/g,(t,r)=>{const i=e[r];return i===void 0?t:String(i)})}function IdpChrome({serviceName:n,serviceHost:e,icon:t,serviceLabel:r,locale:i}){const s=r??resolvePodSignInCopy(i).serviceLabel;return jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"idp-chrome",className:"flex min-h-14 shrink-0 items-center gap-3 border-b border-border bg-[hsl(var(--sunken))] px-6 py-2 text-[13px] text-foreground min-[400px]:px-8",children:[jsxRuntimeExports.jsx("span",{className:"flex shrink-0 items-center justify-center",children:t??jsxRuntimeExports.jsx(XpodMark,{size:24})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 max-w-[50%] shrink-0 truncate font-medium",children:[n," · ",s]}),e?jsxRuntimeExports.jsx("span",{className:"ml-auto truncate font-mono text-xs text-muted-foreground",children:e}):null]})}const primaryButtonClass="h-auto min-h-12 w-full whitespace-normal break-normal rounded-lg py-2 text-base font-medium leading-snug",outlineButtonClass=primaryButtonClass,textButtonClass="h-9 rounded-lg px-2 text-sm font-medium",fieldClass="h-12 w-full rounded-lg border border-input bg-card px-4 text-base text-foreground placeholder:text-muted-foreground disabled:opacity-60";function Spinner({className:n}){return jsxRuntimeExports.jsx(LoaderCircle$1,{"aria-hidden":"true",className:cn("h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none",n)})}function ActionButton({busy:n=!1,children:e,disabled:t,...r}){return jsxRuntimeExports.jsxs(Button,{type:"button",...r,disabled:t||n,"aria-busy":n||void 0,children:[n?jsxRuntimeExports.jsx(Spinner,{className:"mr-2"}):null,e]})}function SourceMark({icon:n,name:e}){return jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"source",className:"flex h-6 items-center gap-2 text-[13px] text-muted-foreground",children:[n?jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"flex h-6 w-6 shrink-0 items-center justify-center overflow-hidden rounded-md",children:n}):null,jsxRuntimeExports.jsx("span",{className:"truncate",children:e})]})}function PodAvatar({name:n,avatarUrl:e,storage:t,size:r=56}){return jsxRuntimeExports.jsxs("span",{className:"relative inline-flex shrink-0",style:{width:r,height:r},"data-pod-sign-in":"avatar",children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-full w-full rounded-full","aria-hidden":"true",children:[e?jsxRuntimeExports.jsx(AvatarImage,{src:e,alt:""}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"text-base",children:Array.from(n.trim())[0]?.toUpperCase()??"?"})]}),t?jsxRuntimeExports.jsx("span",{className:"absolute -bottom-0.5 -right-0.5",children:jsxRuntimeExports.jsx(StorageBadge,{kind:t.kind,label:t.label})}):null]})}function Field(n){return jsxRuntimeExports.jsx(FormField,{...n,"data-pod-sign-in":"field"})}function Disclosure({summary:n,children:e,className:t}){return jsxRuntimeExports.jsxs("details",{className:cn("text-[13px] text-muted-foreground",t),children:[jsxRuntimeExports.jsx("summary",{className:"cursor-pointer select-none rounded py-1 text-[13px] font-medium text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",children:n}),jsxRuntimeExports.jsx("div",{className:"pt-1 leading-5",children:e})]})}function CheckboxRow({checked:n,onChange:e,label:t,disabled:r}){return jsxRuntimeExports.jsxs("label",{className:"flex min-h-9 cursor-pointer items-center gap-2 text-sm text-foreground",children:[jsxRuntimeExports.jsx(Checkbox,{checked:n,disabled:r,onChange:i=>e(i.target.checked)}),t]})}function usePastDelay(n){const[e,t]=reactExports.useState(!1);return reactExports.useEffect(()=>{const r=setTimeout(()=>t(!0),n);return()=>clearTimeout(r)},[n]),e}function ScreenLayout({chrome:n,children:e,actions:t,onSubmit:r,mainClassName:i,...s}){const o=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[n,jsxRuntimeExports.jsx("div",{"data-pod-sign-in":"main",className:cn("flex min-h-0 flex-1 flex-col gap-7 overflow-y-auto px-6 pb-3 pt-7 min-[400px]:px-8 min-[400px]:pt-8",i),children:e}),t?jsxRuntimeExports.jsx("div",{"data-pod-sign-in":"actions",className:"flex shrink-0 flex-col gap-4 px-6 pb-7 pt-5 min-[400px]:px-8 min-[400px]:pb-8",children:t}):null]}),a="flex min-h-0 flex-1 flex-col";return r?jsxRuntimeExports.jsx("form",{...s,onSubmit:r,className:a,noValidate:!0,children:o}):jsxRuntimeExports.jsx("div",{...s,className:a,children:o})}function resolveIdpCopy({locale:n,copy:e}){return resolvePodSignInCopy(n,e)}function IdpFrameHeader({serviceName:n="Xpod",serviceHost:e,serviceIcon:t,locale:r,copy:i}){return jsxRuntimeExports.jsx(IdpChrome,{serviceName:n,serviceHost:e,icon:t,locale:r,serviceLabel:i?.serviceLabel})}const inputClass=fieldClass;function TextAction({href:n,onClick:e,disabled:t,className:r,children:i}){const s=cn(textButtonClass,"inline-flex shrink-0 items-center justify-center text-primary hover:underline",r);return n&&!t?jsxRuntimeExports.jsx("a",{href:n,className:s,children:i}):jsxRuntimeExports.jsx("button",{type:"button",className:s,disabled:t,onClick:e,children:i})}function IdpSignInView(n){const{serviceName:e,returnToAppName:t,error:r,fieldErrors:i,pending:s=!1,remember:o,defaultEmail:a="",defaultPassword:u="",onFieldChange:c,onRememberChange:l,onSubmit:d,onForgot:f,forgotHref:m,onRegister:g,registerHref:b,onUseOtherSolid:S}=n,w=resolveIdpCopy(n),[v,_]=reactExports.useState(a),[T,C]=reactExports.useState(u),U=$=>{$.preventDefault(),s||d({email:v.trim(),password:T})};return jsxRuntimeExports.jsxs(ScreenLayout,{"data-pod-sign-in-state":"idp-sign-in",chrome:jsxRuntimeExports.jsx(IdpFrameHeader,{...n}),onSubmit:U,actions:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[r?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-[13px] text-destructive",children:r}):null,jsxRuntimeExports.jsx(ActionButton,{type:"submit",className:primaryButtonClass,busy:s,children:w.signIn}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[g||b?jsxRuntimeExports.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-x-1 gap-y-0",children:[jsxRuntimeExports.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:w.noAccount}),jsxRuntimeExports.jsx(TextAction,{href:b,disabled:s,onClick:g,children:w.registerLink})]}):jsxRuntimeExports.jsx("span",{}),S?jsxRuntimeExports.jsx("button",{type:"button",className:cn(textButtonClass,"text-primary hover:underline"),disabled:s,onClick:S,children:w.useOtherSolid}):null]})]}),children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:formatCopy(w.signInTitle,{service:e})}),t?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:formatCopy(w.returnToApp,{app:t})}):null]}),jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"fields",className:"flex flex-col gap-5",children:[jsxRuntimeExports.jsx(Field,{label:w.email,error:i?.email,children:$=>jsxRuntimeExports.jsx(EmailInput,{...$,name:"email",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:v,disabled:s,onChange:W=>{_(W.target.value),c?.("email",W.target.value)}})}),jsxRuntimeExports.jsx(Field,{label:w.password,error:i?.password,labelAside:f||m?jsxRuntimeExports.jsx(TextAction,{className:"min-h-7 text-[13px]",href:m,onClick:f,children:w.forgotPassword}):void 0,children:$=>jsxRuntimeExports.jsx(Input,{...$,name:"password",type:"password",autoComplete:"current-password",className:inputClass,value:T,disabled:s,onChange:W=>{C(W.target.value),c?.("password",W.target.value)}})}),l?jsxRuntimeExports.jsx(CheckboxRow,{checked:o,onChange:l,label:w.rememberDevice,disabled:s}):null]})]})}function IdpRegisterView(n){const{serviceName:e,returnToAppName:t,usernamePreview:r,requireUsername:i,fieldErrors:s,error:o,pending:a=!1,defaultEmail:u="",defaultPassword:c="",defaultUsername:l="",onFieldChange:d,onSubmit:f,onSignIn:m}=n,g=resolveIdpCopy(n),[b,S]=reactExports.useState(l),[w,v]=reactExports.useState(u),[_,T]=reactExports.useState(c),C=U=>{U.preventDefault(),!a&&f({...i?{username:b.trim()}:{},email:w.trim(),password:_})};return jsxRuntimeExports.jsxs(ScreenLayout,{"data-pod-sign-in-state":"idp-register",chrome:jsxRuntimeExports.jsx(IdpFrameHeader,{...n}),onSubmit:C,actions:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[o?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-[13px] text-destructive",children:o}):null,jsxRuntimeExports.jsx(ActionButton,{type:"submit",className:primaryButtonClass,busy:a,children:g.registerSubmit}),m?jsxRuntimeExports.jsx("button",{type:"button",className:cn(textButtonClass,"self-center text-primary hover:underline"),disabled:a,onClick:m,children:g.haveAccount}):null]}),children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:formatCopy(g.registerTitle,{service:e})}),t?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:formatCopy(g.returnToApp,{app:t})}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-5",children:[i?jsxRuntimeExports.jsx(Field,{label:g.username,error:s?.username,hint:r?jsxRuntimeExports.jsx("span",{role:"status",className:"font-mono text-xs",children:r}):void 0,children:U=>jsxRuntimeExports.jsx(Input,{...U,name:"username",type:"text",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:b,disabled:a,onChange:$=>{S($.target.value),d?.("username",$.target.value)}})}):null,jsxRuntimeExports.jsx(Field,{label:g.email,error:s?.email,children:U=>jsxRuntimeExports.jsx(EmailInput,{...U,name:"email",autoComplete:"email",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:w,disabled:a,onChange:$=>{v($.target.value),d?.("email",$.target.value)}})}),jsxRuntimeExports.jsx(Field,{label:g.password,error:s?.password,children:U=>jsxRuntimeExports.jsx(Input,{...U,name:"password",type:"password",autoComplete:"new-password",className:inputClass,value:_,disabled:a,onChange:$=>{T($.target.value),d?.("password",$.target.value)}})}),jsxRuntimeExports.jsx(Disclosure,{summary:g.podElsewhereSummary,children:g.podElsewhereBody})]})]})}const __iconNode$1=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],CircleAlert=createLucideIcon$1("circle-alert",__iconNode$1);const __iconNode=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle=createLucideIcon$1("loader-circle",__iconNode);function WebAccountLayout({title:n,description:e,children:t,host:r="document",bare:i=!1,intro:s,serviceIcon:o}){const a=reactExports.useId(),u=r==="window",c=u?"window":"page";return jsxRuntimeExports.jsx("main",{"data-testid":"web-account-page",className:u?"h-dvh w-full overflow-hidden":void 0,children:jsxRuntimeExports.jsx(PodSignInFrame,{presentation:u?"window":"page",ariaLabel:n,appIntro:s,dataAttributes:{"data-web-account-layout":c,"data-web-account-host":u?"window":"document"},children:jsxRuntimeExports.jsx("div",{"data-testid":"web-account-panel","data-web-account-layout":c,"data-web-account-host":u?"window":"document",className:"flex min-h-0 min-w-0 flex-1 flex-col",children:i?t:jsxRuntimeExports.jsxs(ScreenLayout,{chrome:jsxRuntimeExports.jsx(IdpChrome,{serviceName:"Xpod",serviceHost:window.location.host,icon:o}),children:[jsxRuntimeExports.jsxs("header",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{id:a,className:"text-[17px] font-semibold text-foreground",children:n}),e?jsxRuntimeExports.jsx("p",{className:"text-sm leading-[22px] text-muted-foreground",children:e}):null]}),t]})})})})}const introCopy={"zh-CN":{name:"Xpod 账号服务",proposition:"一个账号,管理你的 WebID 和它背后的 Pod。",points:[{title:"WebID 是你的身份",detail:"登录应用时使用它;数据存在你自己的 Pod 里。"},{title:"Pod 存在哪里由你决定",detail:"Xpod 云端或你自己的设备,创建后可以在这里查看。"},{title:"密钥按需签发",detail:"为脚本或服务单独创建凭据,不再需要就撤销。"}]},en:{name:"Xpod accounts",proposition:"One account for your WebID and the Pod behind it.",points:[{title:"Your WebID is your identity",detail:"Apps sign you in with it; your data stays in your own Pod."},{title:"You choose where the Pod lives",detail:"Xpod cloud or your own device, reviewable here after creation."},{title:"Credentials on demand",detail:"Issue a key per script or service, and revoke it when it is done."}]}};function XpodAccountServiceIntro({serviceHost:n,locale:e="zh-CN"}){const t=introCopy[e];return jsxRuntimeExports.jsxs("div",{"data-testid":"web-account-introduction",className:"flex max-w-[460px] flex-col gap-7",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(XpodMark,{size:44}),jsxRuntimeExports.jsx("span",{className:"text-[22px] font-semibold leading-none text-foreground",children:t.name})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-3",children:[jsxRuntimeExports.jsx("h2",{className:"m-0 text-[28px] font-semibold leading-[38px] text-foreground",children:t.proposition}),n?jsxRuntimeExports.jsx("p",{className:"font-mono text-xs text-muted-foreground",children:n}):null]}),jsxRuntimeExports.jsx("ul",{className:"m-0 flex list-none flex-col gap-4 p-0",children:t.points.map(r=>jsxRuntimeExports.jsxs("li",{className:"flex gap-3",children:[jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"mt-2 h-2 w-2 shrink-0 rounded-full bg-primary"}),jsxRuntimeExports.jsxs("span",{className:"flex flex-col gap-0.5",children:[jsxRuntimeExports.jsx("span",{className:"text-[15px] font-semibold text-foreground",children:r.title}),jsxRuntimeExports.jsx("span",{className:"text-sm leading-[22px] text-muted-foreground",children:r.detail})]})]},r.title))})]})}function parseIdentity(n){if(!n||typeof n!="object")throw new Error("Missing deployment identity");const e=n;if(e.edition!=="cloud"&&e.edition!=="local"||typeof e.managed!="boolean")throw new Error("Invalid deployment identity");let t;if(e.edition==="local"&&e.managed&&typeof e.oidcIssuer=="string"){const i=new URL(e.oidcIssuer);if(!["http:","https:"].includes(i.protocol)||i.username||i.password||i.search||i.hash)throw new Error("Invalid account service");t=i.href.replace(/\/$/u,"")}let r;if(typeof e.publicUrl=="string"){const i=new URL(e.publicUrl);if(!["http:","https:"].includes(i.protocol)||i.username||i.password||i.search||i.hash)throw new Error("Invalid public service address");r=i.href}return{edition:e.edition,managed:e.managed,oidcIssuer:t,publicUrl:r}}function XpodDeploymentIdentity({renderLogo:n,className:e}={}){const[t,r]=reactExports.useState();reactExports.useEffect(()=>{const o=new AbortController;return(async()=>{try{const a=await fetch("/api/service-info",{headers:{accept:"application/json"},cache:"no-store",signal:o.signal});if(!a.ok)throw new Error("Deployment identity unavailable");const u=parseIdentity(await a.json());o.signal.aborted||r(u)}catch{o.signal.aborted||r(null)}})(),()=>o.abort()},[]);const i=t?t.edition==="cloud"?"云端":t.managed?"托管部署":"独立部署":t===null?"部署信息暂不可用":"正在识别部署…",s=n?n(i):jsxRuntimeExports.jsxs("span",{"data-testid":"xpod-deployment-logo",className:"inline-flex flex-col items-center gap-0.5",children:[jsxRuntimeExports.jsx(XpodMark,{size:24}),jsxRuntimeExports.jsx("span",{className:"text-[8px] font-medium leading-none text-primary",children:t?i:t===null?"未知":"…"}),t?null:jsxRuntimeExports.jsx("span",{className:"sr-only",children:i})]});return jsxRuntimeExports.jsx("div",{"data-testid":"xpod-deployment-identity",className:e,children:jsxRuntimeExports.jsx(BrandInfo,{logo:s,infoLabel:"部署详情",info:jsxRuntimeExports.jsxs("div",{className:"space-y-2 leading-relaxed",children:[jsxRuntimeExports.jsx("p",{className:"font-semibold",children:"部署详情"}),t?jsxRuntimeExports.jsxs("p",{children:["部署类型:",t.edition==="cloud"?"Cloud":t.managed?"Local · 云端托管":"Local · 独立部署"]}):jsxRuntimeExports.jsx("p",{children:i}),jsxRuntimeExports.jsxs("p",{children:["当前访问:",jsxRuntimeExports.jsx("span",{className:"font-mono",children:window.location.origin})]}),t?jsxRuntimeExports.jsxs("p",{children:[t.edition==="local"?"节点地址":"服务地址",":",jsxRuntimeExports.jsx("span",{className:"font-mono",children:t.publicUrl??(t.managed?"尚未分配":"尚未配置")})]}):null,t?.oidcIssuer&&t.oidcIssuer!==window.location.origin?jsxRuntimeExports.jsxs("p",{children:["账号服务:",jsxRuntimeExports.jsx("span",{className:"font-mono",children:t.oidcIssuer})]}):null]})})})}function XpodAuthSurface(n){const e=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(e==="window"),jsxRuntimeExports.jsx(AuthSurface,{...n,presentation:"compact",host:e})}function XpodSignInFrame({ariaLabel:n,children:e}){const t=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(t==="window"),jsxRuntimeExports.jsx(PodSignInFrame,{presentation:t==="window"?"window":"page",ariaLabel:n,children:e})}function XpodAccountPageSurface({title:n,children:e,bare:t=!1,intro:r,presentation:i="compact"}){const s=getXpodAuthSurfaceHost(),o=i==="compact";return useXpodAuthWindowSurface(s==="window",o?"account":"workspace"),jsxRuntimeExports.jsx(WebAccountLayout,{title:n,host:o?s:"document",bare:t,intro:r??jsxRuntimeExports.jsx(XpodAccountServiceIntro,{serviceHost:window.location.host}),serviceIcon:jsxRuntimeExports.jsx(XpodDeploymentIdentity,{}),children:e})}function credentialViewCopy(n){return{email:n.emailLabel,password:n.passwordLabel,username:n.usernameLabel,signIn:n.loginAction,registerSubmit:n.registerAction,rememberDevice:"记住账号"}}function XpodBlockingAccountCredentialsSurface(n){const e=getXpodAuthSurfaceHost(),t=n.mode!=="register";useXpodAuthWindowSurface(e==="window",t?"account":"workspace");const{mode:r,values:i,onChange:s,onSubmit:o,onFieldChange:a,onModeChange:u,rememberAccount:c=!0,onRememberAccountChange:l,pending:d=!1,errors:f,copy:m,surfaceTitle:g,footer:b,onForgot:S,onRegister:w,forgotHref:v,registerHref:_}=n,T={serviceName:"Xpod",serviceHost:window.location.host,serviceIcon:jsxRuntimeExports.jsx(XpodDeploymentIdentity,{}),copy:credentialViewCopy(m)},C=(U,$)=>{s({...i,[U]:$}),a?.(U,$)};return jsxRuntimeExports.jsxs(WebAccountLayout,{title:g,host:t?e:"document",bare:!0,intro:jsxRuntimeExports.jsx(XpodAccountServiceIntro,{serviceHost:window.location.host}),children:[r==="register"?jsxRuntimeExports.jsx(IdpRegisterView,{...T,requireUsername:!1,pending:d,defaultEmail:i.email,defaultPassword:i.password,error:f?.form,fieldErrors:{email:f?.email,password:f?.password},onFieldChange:C,onSubmit:U=>{o({...i,...U})},onSignIn:u?()=>u("login"):void 0}):jsxRuntimeExports.jsx(IdpSignInView,{...T,pending:d,remember:c,defaultEmail:i.email,defaultPassword:i.password,error:f?.form,fieldErrors:{email:f?.email,password:f?.password},onFieldChange:C,onRememberChange:l,onSubmit:U=>{o({...i,...U})},onForgot:S,forgotHref:v,registerHref:_,onRegister:w??(u?()=>u("register"):void 0)}),b?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:b}):null]})}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 r=0;r<n;r++)e+=urlAlphabet[t[r]%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:r,query:i}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:r,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,r,i=!1){this[SubqueryConfig]={sql:e,selection:t,alias:r,isWith:i}}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 i=(is(e,Subquery)?e[SubqueryConfig].selection:is(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is(i,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;const s=i.clone();return s.isSelectionField=!0,s}if(is(i,SQL)){if(this.config.sqlBehavior==="sql")return i;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(i,Column)?this.config.alias?new Proxy(i,new ColumnAliasProxyHandler(new Proxy(i.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):i:typeof i!="object"||i===null?i:new Proxy(i,new SelectionProxyHandler(this.config))}}function orderSelectedFields(n,e){return Object.entries(n).reduce((t,[r,i])=>{if(typeof r!="string")return t;const s=e?[...e,r]:[r];return is(i,Column)||is(i,SQL)||is(i,SQL.Aliased)?t.push({path:s,field:i}):is(i,Table)?t.push(...orderSelectedFields(i[Table.Symbol.Columns],s)):t.push(...orderSelectedFields(i,s)),t},[])}function applyMixins(n,e){for(const t of e)for(const r of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(n.prototype,r,Object.getOwnPropertyDescriptor(t.prototype,r)||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,r){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=r}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:r,session:i,dialect:s,withList:o,distinct:a}){super(),this.config={withList:o,table:e,fields:{...t},distinct:a},this.isPartialSelect=r,this.session=i,this.dialect=s,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,r)=>{const i=this.tableName,s=getTableLikeName(t);if(typeof s=="string"&&this.config.joins?.some(o=>o.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof i=="string"&&(this.config.fields={[i]:this.config.fields}),typeof s=="string"&&!is(t,SQL))){const o=is(t,Subquery)?t[SubqueryConfig].selection:is(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[s]=o}if(typeof r=="function"&&(r=r(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:r,table:t,joinType:e,alias:s}),typeof s=="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!0;break}case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!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:r,dialect:i,joinsNotNullableMap:s}=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 o=orderSelectedFields(r.fields),a=t.prepareQuery(i.sqlToQuery(this.getSQL()),o,e);return a.joinsNotNullableMap=s,a})}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,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,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 r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){const r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:i,escapeParam:s,prepareTyping:o,inlineParams:a,paramStartIndex:u}=r;return mergeQueries(e.map(c=>{if(is(c,StringChunk))return{sql:c.value.join(""),params:[]};if(is(c,Name))return{sql:i(c.value),params:[]};if(c===void 0)return{sql:"",params:[]};if(Array.isArray(c)){const l=[new StringChunk("(")];for(const[d,f]of c.entries())l.push(f),d<c.length-1&&l.push(new StringChunk(", "));return l.push(new StringChunk(")")),this.buildQueryFromSourceParams(l,r)}if(is(c,SQL))return this.buildQueryFromSourceParams(c.queryChunks,{...r,inlineParams:a||c.shouldInlineParams});if(is(c,Table)){const l=c[Table.Symbol.Schema],d=c[Table.Symbol.Name];return{sql:l===void 0?i(d):i(l)+"."+i(d),params:[]}}if(is(c,Column))return{sql:i(c.table[Table.Symbol.Name])+"."+i(c.name),params:[]};if(is(c,View)){const l=c[ViewBaseConfig].schema,d=c[ViewBaseConfig].name;return{sql:l===void 0?i(d):i(l)+"."+i(d),params:[]}}if(is(c,Param)){const l=c.value===null?null:c.encoder.mapToDriverValue(c.value);if(is(l,SQL))return this.buildQueryFromSourceParams([l],r);if(a)return{sql:this.mapInlineParam(l,r),params:[]};let d;return o!==void 0&&(d=[o(c.encoder)]),{sql:s(u.value++,l),params:[l],typings:d}}return is(c,Placeholder)?{sql:s(u.value++,c),params:[c]}:is(c,SQL.Aliased)&&c.fieldAlias!==void 0?{sql:i(c.fieldAlias),params:[]}:is(c,Subquery)?c[SubqueryConfig].isWith?{sql:i(c[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),c[SubqueryConfig].sql,new StringChunk(") "),new Name(c[SubqueryConfig].alias)],r):isSQLWrapper(c)?this.buildQueryFromSourceParams([new StringChunk("("),c.getSQL(),new StringChunk(")")],r):is(c,Relation)?this.buildQueryFromSourceParams([c.sourceTable,new StringChunk("."),sql.identifier(c.fieldName)],r):a?{sql:this.mapInlineParam(c,r),params:[]}:{sql:s(u.value++,c),params:[c]}}))}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 r=e.toString();return t(r==="[object Object]"?JSON.stringify(e):r)}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[r,i]of e.entries())t.push(i,new StringChunk(n[r+1]));return new SQL(t)}(function(n){function e(){return new SQL([])}n.empty=e;function t(u){return new SQL(u)}n.fromList=t;function r(u){return new SQL([new StringChunk(u)])}n.raw=r;function i(u,c){const l=[];for(const[d,f]of u.entries())d>0&&c!==void 0&&l.push(c),l.push(f);return new SQL(l)}n.join=i;function s(u){return new Name(u)}n.identifier=s;function o(u){return new Placeholder(u)}n.placeholder=o;function a(u,c){return new Param(u,c)}n.param=a})(sql||(sql={}));(function(n){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(r,i){this.sql=r,this.fieldAlias=i}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 i=e[Table.Symbol.Columns];if(!i)return i;const s={};return Object.keys(i).map(o=>{s[o]=new Proxy(i[o],new ColumnAliasProxyHandler(new Proxy(e,this)))}),s}const r=e[t];return is(r,Column)?new Proxy(r,new ColumnAliasProxyHandler(new Proxy(e,this))):r}}var _a$b;class ColumnBuilder{constructor(e,t,r={},i,s){this.name=e,this.dataType=t,this.options={...r},this._predicateUri=i,this.elementType=s??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,r={},i){this.name=e,this.dataType=t,this.options=r,this.tableName=i}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,r={}){super(e,"array",r),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 r=n.getPredicateUri?.()??n.options?.predicate,i=e.options?.predicate;if(r&&i&&r!==i)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${i}",子 schema 尝试改为 "${r}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(n,e){const t={};for(const[r,i]of Object.entries(n.columns))t[r]=i;for(const[r,i]of Object.entries(e)){const s=n.columns[r];if(s&&!(i instanceof PodColumnBase)){validateColumnOverride(i,s,r);const o=i;!o.getPredicateUri?.()&&!o.options?.predicate&&(o.options={...o.options,predicate:s.options?.predicate})}t[r]=i}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??{},r=resolveDate(t,e.now),i={yyyy:String(r.getUTCFullYear()),MM:String(r.getUTCMonth()+1).padStart(2,"0"),dd:String(r.getUTCDate()).padStart(2,"0")};return n.replace(/\{([^{}]+)\}/g,(s,o)=>{const a=o.trim();if(a==="key")return e.key;if(a==="yyyy")return i.yyyy;if(a==="MM")return i.MM;if(a==="dd")return i.dd;const u=resolveExpression(a,t,e);return u==null?"":String(u)})}function resolveDate(n,e=new Date){const t=n.createdAt??n.favoredAt??n.indexedAt??e,r=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(r.getTime())?r:e}function resolveExpression(n,e,t){const r=parseExpression(n);let i=resolveTemplatePath(r.path,e,t);for(const s of r.transforms)i=applyTransform(i,s,r.path,t);return r.selector?applyPathSelector(i,r.selector):i}function parseExpression(n){const e=n.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():n,[r,...i]=t.split("|").map(s=>s.trim()).filter(Boolean);return{path:r??n,transforms:i,selector:e?.[2]?.trim()}}function resolveTemplatePath(n,e,t){const r=n.split("."),i=r[0];return r.reduce((s,o,a)=>{if(typeof s=="string")return i?resolveResourceProperty(s,i,o,t):void 0;if(!(!s||typeof s!="object"))return i&&isResourceProperty(o)&&!((o==="id"||o==="key")&&o in s)?resolveResourceProperty(s,i,o,t):a>0&&o==="id"&&readRef(s)?extractResourceId(s,i??"",t):s[o]},e)}function isResourceProperty(n){return n==="id"||n==="key"||n==="doc"||n==="document"||n==="dir"||n==="owner"}function resolveResourceProperty(n,e,t,r){if(t==="id")return extractResourceId(n,e,r);const i=extractResourceId(n,e,r);if(i){if(t==="key"){const s=extractTemplateValuesForField(n,e,r);return s?.key??s?.id??deriveResourceKey(i)}if(t==="doc"||t==="document")return resourceDocument(i);if(t==="dir"||t==="owner")return deriveOwnerDir(i)}}function applyTransform(n,e,t,r){if(e==="slug")return slugifyValue(String(n??""));const i=extractResourceId(n,t,r);if(e==="resource")return i;if(e==="document")return i?resourceDocument(i):"";if(e==="owner")return i?deriveOwnerDir(i):"";const s=extractTemplateValuesForField(n,t,r);return e==="id"?s?.id??s?.key??i??"":s?.[e]??""}function extractResourceId(n,e,t){const r=readRef(n);if(!r)return null;const i=resolveLinkedResource(e,t);if(!i)return normalizePodDataResourceId$1(r);if(!isCompleteResourceId$1(r))return renderLinkedResourceId(i,r);const s=relativeSubjectFromRef$1(i,r);return normalizePodDataResourceId$1(s??r)}function extractTemplateValuesForField(n,e,t){const r=readRef(n);if(!r)return null;const i=resolveLinkedResource(e,t);if(!i)return null;const s=relativeSubjectFromRef$1(i,r)??(isCompleteResourceId$1(r)?null:renderLinkedResourceId(i,r));if(!s)return null;const o=resourceTemplate(i);return o?extractVarsFromTemplate(normalizePodDataResourceId$1(s),o):{id:normalizePodDataResourceId$1(s)}}function resolveLinkedResource(n,e){const t=e.links?.[n];if(t)return t;const r=e.resource?.columns?.[n];return r?.getLinkTable?.()??r?.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 r=n.columns?.id?.options?.defaultValue;return typeof r=="function"?String(r(e,{})):t.replace(/\{([^}]+)\}/g,(i,s)=>{const o=parseTemplateField(s);return o==="id"||o==="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 r=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const i of r){const s=e.indexOf(i);if(s<0)continue;let o=e.slice(s+i.length);return o.startsWith("/")&&(o=o.slice(1)),o.length>0?o:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(n,e){let t=0;const r=new Map,i=[];let s=0;for(const a of e.matchAll(/\{([^}]+)\}/g)){i.push(escapeRegExp$1(e.slice(s,a.index)));const u=`var${t++}`;r.set(u,parseTemplateField(a[1]??"")),i.push(`(?<${u}>.+?)`),s=a.index+a[0].length}i.push(escapeRegExp$1(e.slice(s)));const o=i.join("");try{const a=n.match(new RegExp(`^${o}$`));if(!a?.groups)return null;const u={};for(const[c,l]of Object.entries(a.groups)){const d=r.get(c);!d||l===void 0||(u[d]=decodeURIComponent(l))}return u}catch{return null}}function parseTemplateField(n){const e=n.split("|").map(r=>r.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 r=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!r)throw new Error(`Invalid id default path selector [${e}]`);const i=r[1]===""?0:normalizeSliceIndex(Number(r[1]),t.length),s=r[2]===""?t.length:normalizeSliceIndex(Number(r[2]),t.length);return t.slice(i,s).join("/")}function splitResourcePath(n){const e=readRef(n);if(!e)return null;const t=normalizePodDataResourceId$1(e),[r,i]=t.split("#"),s=(r??t).split("/").filter(Boolean);return i&&s.push(i),s}function normalizePodDataResourceId$1(n){const e=n.indexOf("#"),[t,r=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],i=t.indexOf("/.data/");return`${i>=0?t.slice(i+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${r}`}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("#"),r=t>=0?e.slice(0,t):e,i=t>=0?e.slice(t+1):"",s=r.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(s?.[1])return s[1];if(r==="task/index.ttl"&&i&&i!=="this")return`task/${i}`;const o=r.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(o?.[1])return o[1];const a=r.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(a?.[1])return a[1];const u=r.split("/").filter(Boolean);return u.length>1?u.slice(0,-1).join("/"):r}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 a=e.slice(t+1);if(a&&a!=="this"&&a!=="me"&&a!=="it")return a}const r=resourceDocument(e).replace(/\/+$/u,""),i=r.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(i?.[1])return i[1];const s=r.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(s?.[1])return s[1];const o=r.split("/").filter(Boolean);return o.length>0?o[o.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(r=>r.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 r=e.indexOf("#");if(r>=0)return e.slice(r)}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 r=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const i of r){const s=e.indexOf(i);if(s<0)continue;let o=e.slice(s+i.length);if(o.startsWith("/")&&(o=o.slice(1)),o.length>0)return o}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 r=new Map,i=[];let s=0;for(const a of e.matchAll(/\{([^}]+)\}/g)){i.push(escapeRegExp(e.slice(s,a.index)));const u=`var${t++}`;r.set(u,parseTemplateVariableField$1(a[1]??"")),i.push(`(?<${u}>.+?)`),s=a.index+a[0].length}i.push(escapeRegExp(e.slice(s)));const o=`^${i.join("")}$`;try{const a=n.match(new RegExp(o));if(!a?.groups)return null;const u={};for(const[c,l]of Object.entries(a.groups)){const d=r.get(c);if(!d||l===void 0)continue;const f=decodeURIComponent(l);if(d in u&&u[d]!==f)return null;u[d]=f}return u}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 r=qualifyFragmentResourceId(n,t),i=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n),s=i?extractTemplateValues(templateRelativeSubject(n,r),i):{id:decodeURIComponent(r)};return s?{resourceId:decodeURIComponent(r),templateValues:s}: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,r=readPodUrl(t);if(r)return resolvePodBaseUrl(r);const i=typeof e.getSession=="function"?e.getSession():e.session,s=readPodUrl(i);if(s)return resolvePodBaseUrl(s);const o=readWebId(i);return o&&o.includes("/profile/card#me")?resolvePodBaseUrl(o):null}function normalizePodDataResourceId(n){const e=n.indexOf("#"),[t,r=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],i=t.indexOf("/.data/");return`${i>=0?t.slice(i+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${r}`}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 r=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!r)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(r)||isTemplateCompleteResourceId(n,r))return normalizePodDataResourceId(r);const i=resolveDefaultResourceId(n,r,e);if(i)return normalizePodDataResourceId(i);const s=podResourceSubjectTemplate(n);return normalizePodDataResourceId(s?renderSubjectTemplateResourceId(s,r,e):r)}function buildPodResourceIri(n,e){const t=resolvePodBaseUrl(n);if(!t||/^https?:\/\//u.test(e))return e;const r=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(r.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(n,e,t){const r=resolveKnownTargetIri(t);if(r)return r;const i=resolvePodRootTargetPath(t);if(i)return buildPodResourceIri(n,i);const s=resolvePodResourceId(e,t),o=isResourceRelativeSubjectId(e,s)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(s)}`:e.resolveUri?.(s)??`/.data/${normalizePodDataResourceId(s)}`;return buildPodResourceIri(n,o)}function buildPodResourceIriForDatabase(n,e,t){const r=resolvePodBaseUrlFromDatabase(n);if(!r)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(r,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,r=podResourceSubjectTemplate(n);if(t||r)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 r=n.columns?.id?.options?.defaultValue;if(r===void 0)return null;if(typeof r=="string")return renderDefaultIdTemplate(r,{key:e,row:t,resource:n});if(typeof r!="function")return String(r);const i=r;return i.length===0?String(i()):String(i(e,t))}function renderSubjectTemplateResourceId(n,e,t){const r=n.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(r,{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,r){this.initialized=!1;const i=r.type;if(!i)throw new Error("podTable requires a type (RDF class) via options.type");const s=r.typeIndex,o=s==="private"||s==="public",a=this.resolveBase(r.base,e);this.resourcePath=a.resourcePath,this.containerPath=a.containerPath;const u=this.resolveSubjectTemplate(r.subjectTemplate,a.resourcePath,a.containerPath,e);this.subjectTemplate=u.template,this.hasCustomSubjectTemplate=u.isCustom,this.resourceMode=r.resourceMode??(r.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=r.sparqlEndpoint,this.registerTypeIndexEnabled=o&&r.autoRegister!==!1,this.config={name:e,base:a.resourcePath,type:resolveTermIri(i),namespace:r.namespace,typeIndex:o?s:void 0,saiRegistryPath:r.saiRegistryPath,autoRegister:r.autoRegister,containerPath:a.containerPath,hooks:r.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(r.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let c=0;for(const l of Object.values(t))if(l.options.primaryKey&&c++,l.table=this,l.tableName=e,!l.options.predicate&&!l._virtualId&&!r.namespace)throw new Error(`Column "${l.name}" in table "${e}" is missing a predicate.`);if(c!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${c}.`);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 r=t.replace(/\{id\}/g,e);return r.startsWith("#")?`${this.resourcePath}${r}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${r}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const r=this.normalizeBaseInput(e),i=this.normalizeResourcePath(r);if(i.endsWith("/")){const o=this.ensureTrailingSlash(i);return{resourcePath:o,containerPath:o}}const s=this.ensureTrailingSlash(this.deriveContainerPath(i));return{resourcePath:i,containerPath:s}}normalizeBaseInput(e){const t=e.trim(),r=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(r){const[,i,s]=r,o=i.toLowerCase(),a=s.trim();return o==="http"||o==="https"?`${o}://${a}`:a.startsWith("/")?a:`/${a}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const r=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return r.startsWith("/")?r:`/${r}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,r=t.lastIndexOf("/");return r===-1?"/":t.slice(0,r+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,r,i){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 r=(Array.isArray(e)?e:[e]).map(i=>resolveTermIri(i)).filter(i=>i&&i.length>0);return Array.from(new Set(r))}}_a$a=entityKind;PodTable[_a$a]="PodTable";function podTable(n,e,t){const r={};for(const[i,s]of Object.entries(e)){if(s instanceof PodColumnBase){r[i]=s;continue}let o;switch(s.dataType){case"integer":o=new PodIntegerColumn(s.name,s.options);break;case"datetime":o=new PodDateTimeColumn(s.name,s.options);break;case"boolean":o=new PodBooleanColumn(s.name,s.options);break;case"json":o=new PodJsonColumn(s.name,s.options);break;case"object":o=new PodObjectColumn(s.name,s.options);break;case"array":{const u=s.elementType??s.options.baseType??"string";o=new PodArrayColumn(s.name,u,s.options);break}case"uri":o=new PodUriColumn(s.name,s.options);break;default:o=new PodStringColumn(s.name,s.options);break}const a=s.getPredicateUri?.();a&&o.predicate(a),r[i]=o}return new PodTable(n,r,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 r=mergeSchemaColumns(this,e),i=[this.type];return this.subClassOf&&i.push(...this.subClassOf),solidSchema(r,{...t,subClassOf:i})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(n,e){const t={};for(const[r,i]of Object.entries(n)){if(i instanceof PodColumnBase){t[r]=i;continue}let s;switch(i.dataType){case"integer":s=new PodIntegerColumn(i.name,i.options);break;case"datetime":s=new PodDateTimeColumn(i.name,i.options);break;case"boolean":s=new PodBooleanColumn(i.name,i.options);break;case"json":s=new PodJsonColumn(i.name,i.options);break;case"object":s=new PodObjectColumn(i.name,i.options);break;case"array":{const a=i.elementType??i.options.baseType??"string";s=new PodArrayColumn(i.name,a,i.options);break}case"uri":s=new PodUriColumn(i.name,i.options);break;default:s=new PodStringColumn(i.name,i.options);break}const o=i.getPredicateUri?.();o&&s.predicate(o),t[r]=s}return new SolidSchema(t,e)}function isSolidSchema(n){return n instanceof SolidSchema||n?.$kind==="SolidSchema"}const XSD$8="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(n,e){if(!n)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const i=e.getMapping()?.columns?.[n.name];if(i?.predicate)return i.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,r){return Array.isArray(n)?n.map(i=>formatSingleValue(i,e,t,r)):formatSingleValue(n,e,t,r)}function formatSingleValue(n,e,t,r){if(n==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const i=String(n);if(i.startsWith("<")&&i.endsWith(">")){const s=i.slice(1,-1);return t&&!t.isAbsoluteUri(s)?`<${t.resolveLink(s,e,r)}>`:i}return t?`<${t.resolveLink(i,e,r)}>`:i.startsWith("<")?i:`<${i}>`}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$8}decimal>`:typeof n=="boolean"?`"${n}"^^<${XSD$8}boolean>`:n instanceof Date?`"${n.toISOString()}"^^<${XSD$8}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 r=t.resolveSubject(e,n);if(!r)throw new Error("Failed to generate subject URI");return r}var _a$9;class SPARQLExpression{constructor(){this[_a$9]="SPARQLExpression"}}_a$9=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,r){super(),this.left=e,this.operator=t,this.right=r,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()}`,r=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!r.ok)throw new Error(`SSE connection failed: ${r.status} ${r.statusText}`);if(!r.body)throw new Error("SSE response has no body");this.contentType=r.headers.get("content-type")||"",this._connected=!0,this.reader=r.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:r,value:i}=await this.reader.read();if(r){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const s=e.decode(i,{stream:!0});t+=s,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(r){r.name!=="AbortError"&&this.handleError(r)}}processTurtleBuffer(e){const t=e.split(`
|
|
3
|
+
`);let r="";for(let i=0;i<t.length;i++){const s=t[i];r+=s+`
|
|
4
|
+
`,s.trim().endsWith(".")&&(this.parseTurtleNotification(r.trim()),r="")}return r}processSSEBuffer(e){const t=e.split(`
|
|
5
|
+
|
|
6
|
+
`),r=t.pop()||"";for(const i of t)i.trim()&&this.parseSSEMessage(i);return r}parseTurtleNotification(e){try{const t=e.match(/<https:\/\/www\.w3\.org\/ns\/activitystreams#object>\s*<([^>]+)>/),r=e.match(/a\s*<https:\/\/www\.w3\.org\/ns\/activitystreams#(\w+)>/),i=e.match(/<https:\/\/www\.w3\.org\/ns\/activitystreams#published>\s*"([^"]+)"/),s=e.match(/<http:\/\/www\.w3\.org\/ns\/solid\/notifications#state>\s*"([^"]+)"/),o=e.match(/^<([^>]+)>/);if(!t||!r)return;const a={id:o?.[1]||`urn:notification:${Date.now()}`,type:r[1],object:t[1],published:i?.[1]||new Date().toISOString(),state:s?.[1]};this.handleMessage(JSON.stringify(a))}catch(t){console.warn("[SSE] Failed to parse Turtle notification:",t)}}parseNotification(e){e.startsWith("{")?this.handleMessage(e):e.includes("activitystreams")&&this.parseTurtleNotification(e)}parseSSEMessage(e){const t=e.split(`
|
|
7
|
+
`);let r="",i="message";for(const s of t)s.startsWith("data:")?r+=s.slice(5).trim():s.startsWith("event:")&&(i=s.slice(6).trim());r&&i==="message"&&this.handleMessage(r)}}const getWebSocket=()=>{if(typeof WebSocket<"u")return WebSocket;try{return require("ws")}catch{throw new Error('WebSocket is not available. Install "ws" package for Node.js support.')}};class WebSocketChannel extends BaseChannel{constructor(e){super(e),this.ws=null,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.reconnectDelay=1e3}async connect(){if(!this._connected)return new Promise((e,t)=>{try{const r=getWebSocket();this.ws=new r(this.config.receiveFrom),this.ws.onopen=()=>{this._connected=!0,this.reconnectAttempts=0,e()},this.ws.onmessage=i=>{const s=typeof i.data=="string"?i.data:i.data?.toString?.()||"";this.handleMessage(s)},this.ws.onerror=()=>{const i=new Error("WebSocket error");this.handleError(i),this._connected||t(i)},this.ws.onclose=i=>{this._connected=!1,!i.wasClean&&this.reconnectAttempts<this.maxReconnectAttempts?(this.reconnectAttempts++,setTimeout(()=>{this.connect().catch(()=>{})},this.reconnectDelay*this.reconnectAttempts)):this.handleClose()}}catch(r){t(r)}})}disconnect(){this.reconnectAttempts=this.maxReconnectAttempts,this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this._connected=!1}}const CHANNEL_TYPE_URI={"streaming-http":"http://www.w3.org/ns/solid/notifications#StreamingHTTPChannel2023",websocket:"http://www.w3.org/ns/solid/notifications#WebSocketChannel2023"},CHANNEL_NAMES={"streaming-http":"StreamingHTTPChannel2023",websocket:"WebSocketChannel2023"};class NotificationsClient{constructor(e,t){this.subscriptions=new Map,this.fetch=e,this.preferredChannels=t?.preferredChannels??["streaming-http","websocket"]}async subscribe(e,t){const r=await this.discoverNotificationService(e),s=(t.channel?[t.channel,...this.preferredChannels.filter(a=>a!==t.channel)]:this.preferredChannels).filter(a=>r.supportedChannels.includes(a));if(s.length===0)throw new Error(`No supported notification channels found for ${e}. Server supports: ${r.supportedChannels.join(", ")}`);let o=null;for(const a of s)try{return await this.connectChannel(a,e,r,t)}catch(u){console.log(`[Notifications] Channel "${a}" failed, trying next...`),o=u}throw o??new Error(`Failed to connect to any notification channel for ${e}`)}async resubscribe(e,t,r,i){let s;if(t==="streaming-http")s=this.buildSSEDirectUrl(r.baseEndpoint,e),console.log(`[Notifications] SSE reconnect to: ${s}`);else{const u=`${r.baseEndpoint}${CHANNEL_NAMES[t]}/`;s=(await this.createSubscription(u,e,t,i.features)).receiveFrom,console.log(`[Notifications] WebSocket resubscription created, receiveFrom: ${s}`)}const o=this.subscriptions.get(e),a=this.createChannelWithReconnect(t,s,i,o);return await a.connect(),a}async connectChannel(e,t,r,i){let s;if(e==="streaming-http")s=this.buildSSEDirectUrl(r.baseEndpoint,t),console.log(`[Notifications] SSE direct connect to: ${s}`);else{const u=`${r.baseEndpoint}${CHANNEL_NAMES[e]}/`;s=(await this.createSubscription(u,t,e,i.features)).receiveFrom,console.log(`[Notifications] WebSocket subscription created, receiveFrom: ${s}`)}const o=new SubscriptionImpl(t,e,null,()=>this.subscriptions.delete(t),this,i,r),a=this.createChannelWithReconnect(e,s,i,o);return await a.connect(),o.setChannel(a),this.subscriptions.set(t,o),o}buildSSEDirectUrl(e,t){return`${e.endsWith("/")?e:`${e}/`}StreamingHTTPChannel2023/${encodeURIComponent(t)}`}unsubscribeAll(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear()}async discoverNotificationService(e){const t=await this.discoverFromLinkHeader(e);if(t)return t;const r=new URL(e),i=`${r.origin}/.well-known/solid`;try{return await this.fetchStorageDescription(i,r.origin)}catch{return{baseEndpoint:`${r.origin}/.notifications/`,supportedChannels:["websocket","streaming-http"]}}}async discoverFromLinkHeader(e){try{const t=new URL(e),r=await this.discoverLinkHeader(e);if(!r)return null;const i=[],s=r.match(/<([^>]+)>;\s*rel="?http:\/\/www\.w3\.org\/ns\/solid\/terms#updatesViaStreamingHttp2023"?/);s&&i.push("streaming-http");const o=r.match(/<([^>]+)>;\s*rel="?http:\/\/www\.w3\.org\/ns\/solid\/terms#updatesViaWebSocketChannel2023"?/);if(o&&i.push("websocket"),s){const a=s[1],u=new URL(a),c=u.pathname.split("/"),l=c.findIndex(d=>d===".notifications");if(l!==-1){const d=c.slice(0,l+1).join("/")+"/";return i.includes("websocket")||i.push("websocket"),{baseEndpoint:`${u.origin}${d}`,supportedChannels:i}}}return o&&i.length>0?{baseEndpoint:`${t.origin}/.notifications/`,supportedChannels:i}:null}catch{return null}}async discoverLinkHeader(e){return(await this.fetch(e,{method:"HEAD"})).headers.get("Link")}async findStorageRoot(e){try{const s=(await this.fetch(e,{method:"HEAD"})).headers.get("Link");if(s){const o=s.match(/<([^>]+)>;\s*rel="?http:\/\/www\.w3\.org\/ns\/pim\/space#storage"?/);if(o)return o[1]}}catch{}const t=new URL(e),r=t.pathname.split("/").filter(Boolean);return r.length>0?`${t.origin}/${r[0]}/`:`${t.origin}/`}async fetchStorageDescription(e,t){const r=await this.fetch(e,{headers:{Accept:"text/turtle, application/ld+json"}});if(!r.ok)throw new Error(`Failed to fetch storage description: ${r.status}`);const i=await r.text(),s=[],o=/<http:\/\/www\.w3\.org\/ns\/solid\/notifications#subscription>\s+<([^>]+)>/g,a=/notify:subscription[>\s]+<([^>]+)>/g;let u;const c=[];for(;(u=o.exec(i))!==null;)c.push(u[1]);for(;(u=a.exec(i))!==null;)c.push(u[1]);for(const d of c)d.includes("WebSocketChannel2023")&&!s.includes("websocket")&&s.push("websocket"),d.includes("StreamingHTTPChannel2023")&&!s.includes("streaming-http")&&s.push("streaming-http");return s.length===0&&(i.includes("WebSocketChannel2023")&&s.push("websocket"),i.includes("StreamingHTTPChannel2023")&&s.push("streaming-http")),{baseEndpoint:`${new URL(t).origin}/.notifications/`,supportedChannels:s.length>0?s:["websocket"]}}async createSubscription(e,t,r,i){const s={"@context":["https://www.w3.org/ns/solid/notification/v1"],type:CHANNEL_TYPE_URI[r],topic:t,...i&&i.length>0?{features:i}:{}},o=`notify-sub-${Date.now()}`,a=await this.fetch(e,{method:"POST",headers:{"Content-Type":"application/ld+json",Accept:"application/ld+json","X-Request-ID":o},body:JSON.stringify(s)});if(!a.ok){const u=await a.text();throw new Error(`Failed to create subscription: ${a.status} ${a.statusText} - ${u}`)}return a.json()}createChannel(e,t,r){const i={receiveFrom:t,onNotification:r.onNotification,onError:r.onError,onClose:r.onClose,fetch:this.fetch};switch(e){case"streaming-http":return new SSEChannel(i);case"websocket":return new WebSocketChannel(i);default:throw new Error(`Unsupported channel type: ${e}`)}}createChannelWithReconnect(e,t,r,i){const s={receiveFrom:t,onNotification:r.onNotification,onError:r.onError,onClose:()=>{i?i.handleDisconnect():r.onClose?.()},fetch:this.fetch};switch(e){case"streaming-http":return new SSEChannel(s);case"websocket":return new WebSocketChannel(s);default:throw new Error(`Unsupported channel type: ${e}`)}}}class SubscriptionImpl{constructor(e,t,r,i,s,o,a){this._active=!0,this.reconnectAttempts=0,this.reconnectTimer=null,this.isReconnecting=!1,this._topic=e,this._channel=t,this.notificationChannel=r,this.onUnsubscribe=i,this.client=s,this.options=o,this.discovery=a}setChannel(e){this.notificationChannel=e}get active(){return this._active&&(this.notificationChannel?.connected||this.isReconnecting)}get channel(){return this._channel}get topic(){return this._topic}handleDisconnect(){if(!this._active)return;const e=this.options.autoReconnect!==!1,t=this.options.maxReconnectAttempts??5;if(!e){this.options.onClose?.();return}if(t>0&&this.reconnectAttempts>=t){console.log(`[Notifications] Max reconnect attempts (${t}) reached for ${this._topic}`),this.options.onClose?.();return}this.isReconnecting=!0,this.reconnectAttempts++;const r=this.options.reconnectDelayMs??1e3,i=Math.min(r*Math.pow(2,this.reconnectAttempts-1),3e4);console.log(`[Notifications] Connection lost for ${this._topic}, reconnecting in ${i}ms (attempt ${this.reconnectAttempts})`),this.options.onReconnect?.(this.reconnectAttempts),this.reconnectTimer=setTimeout(async()=>{try{const s=await this.client.resubscribe(this._topic,this._channel,this.discovery,this.options);this.notificationChannel=s,this.reconnectAttempts=0,this.isReconnecting=!1,console.log(`[Notifications] Reconnected successfully for ${this._topic}`)}catch(s){console.error(`[Notifications] Reconnect failed for ${this._topic}:`,s),this.isReconnecting=!1,this.handleDisconnect()}},i)}unsubscribe(){this._active&&(this._active=!1,this.isReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.notificationChannel?.disconnect(),this.onUnsubscribe())}}const SOLID={typeIndex:"http://www.w3.org/ns/solid/terms#publicTypeIndex",privateTypeIndex:"http://www.w3.org/ns/solid/terms#privateTypeIndex",oidcIssuer:"http://www.w3.org/ns/solid/terms#oidcIssuer"},INTEROP$1={hasRegistrySet:"http://www.w3.org/ns/solid/interop#hasRegistrySet"};class ProviderCache{constructor(e){this.cache=new Map,this.ttl=e?.ttl??1440*60*1e3,this.fetchFn=e?.fetch??fetch}async getWellKnown(e){const t=this.extractProvider(e),r=this.cache.get(t);if(r&&Date.now()<r.expiresAt)return this.applyToPod(r.paths,e);const i=await this.fetchWellKnown(e),s=this.extractPaths(i,e);return this.cache.set(t,{paths:s,expiresAt:Date.now()+this.ttl}),i}async discover(e,t,r,i){const s=await this.getWellKnown(e);if(s.registrySet){const o=await r(s.registrySet,t);if(o)return o}return s.typeIndex?i(s.typeIndex,t):null}setTTL(e){this.ttl=e}clear(){this.cache.clear()}clearProvider(e){this.cache.delete(e)}extractProvider(e){const t=new URL(e).host,r=t.split(".");return r.length>=2?r.slice(-2).join("."):t}async fetchWellKnown(e){const t=e.endsWith("/")?e:`${e}/`,r=`${t}.well-known/solid`;try{const i=await this.fetchFn(r,{headers:{Accept:"text/turtle, application/ld+json"}});if(!i.ok)return{};const s=i.headers.get("content-type")||"",o=await i.text();return s.includes("turtle")||s.includes("n3")?this.parseTurtle(o,t):s.includes("json")?this.parseJsonLd(o):this.parseTurtle(o,t)}catch{return{}}}parseTurtle(e,t){const r={raw:{}},i=e.split(/\s*;\s*|\s*\.\s*(?=\n|$)|\n/).map(s=>s.trim()).filter(Boolean);for(const s of i){if(s.includes("publicTypeIndex")||s.includes(SOLID.typeIndex)){const o=this.extractUrl(s);o&&(r.typeIndex=this.resolveUrl(o,t))}if(s.includes("privateTypeIndex")||s.includes(SOLID.privateTypeIndex)){const o=this.extractUrl(s);o&&(r.privateTypeIndex=this.resolveUrl(o,t))}if(s.includes("hasRegistrySet")||s.includes(INTEROP$1.hasRegistrySet)){const o=this.extractUrl(s);o&&(r.registrySet=this.resolveUrl(o,t))}if(s.includes("oidcIssuer")||s.includes(SOLID.oidcIssuer)){const o=this.extractUrl(s);o&&(r.oidcIssuer=this.resolveUrl(o,t))}}return r}extractUrl(e){const t=e.match(/<([^>]+)>/g);return t&&t.length>0?t[t.length-1].slice(1,-1):null}parseJsonLd(e){try{const t=JSON.parse(e),r={raw:{}},i=t["@graph"]||[t];for(const s of i)(s[SOLID.typeIndex]||s["solid:publicTypeIndex"])&&(r.typeIndex=this.extractJsonLdValue(s[SOLID.typeIndex]||s["solid:publicTypeIndex"])),(s[SOLID.privateTypeIndex]||s["solid:privateTypeIndex"])&&(r.privateTypeIndex=this.extractJsonLdValue(s[SOLID.privateTypeIndex]||s["solid:privateTypeIndex"])),(s[INTEROP$1.hasRegistrySet]||s["interop:hasRegistrySet"])&&(r.registrySet=this.extractJsonLdValue(s[INTEROP$1.hasRegistrySet]||s["interop:hasRegistrySet"])),(s[SOLID.oidcIssuer]||s["solid:oidcIssuer"])&&(r.oidcIssuer=this.extractJsonLdValue(s[SOLID.oidcIssuer]||s["solid:oidcIssuer"]));return r}catch{return{}}}extractJsonLdValue(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null)return e["@id"]}resolveUrl(e,t){return e.startsWith("http://")||e.startsWith("https://")?e:new URL(e,t).toString()}extractPaths(e,t){const r=t.endsWith("/")?t:`${t}/`,i={};return e.typeIndex&&(i.typeIndex=this.toRelativePath(e.typeIndex,r)),e.privateTypeIndex&&(i.privateTypeIndex=this.toRelativePath(e.privateTypeIndex,r)),e.registrySet&&(i.registrySet=this.toRelativePath(e.registrySet,r)),e.oidcIssuer&&(i.oidcIssuer=e.oidcIssuer),i}toRelativePath(e,t){return e.startsWith(t)?e.slice(t.length-1):e}applyToPod(e,t){const r=t.endsWith("/")?t:`${t}/`,i={};return e.typeIndex&&(i.typeIndex=this.toAbsoluteUrl(e.typeIndex,r)),e.privateTypeIndex&&(i.privateTypeIndex=this.toAbsoluteUrl(e.privateTypeIndex,r)),e.registrySet&&(i.registrySet=this.toAbsoluteUrl(e.registrySet,r)),e.oidcIssuer&&(i.oidcIssuer=e.oidcIssuer),i}toAbsoluteUrl(e,t){return e.startsWith("http://")||e.startsWith("https://")?e:e.startsWith("/")?`${t.slice(0,-1)}${e}`:`${t}${e}`}}class FederatedQueryExecutor{constructor(e){this.providerCache=e?.providerCache??new ProviderCache,this.fetchFn=e?.fetch??fetch,this.defaultTimeout=e?.timeout??3e4}async execute(e,t,r){const i=[],s=[...e];if(!t.isFederated||!t.discover)return{data:s};const o=t.table,a=t.discover,u=t.relationName??"items",c=o.type,l=[];for(let m=0;m<e.length;m++){const g=e[m],b=a(g);if(!b){s[m][u]=[];continue}const w=(Array.isArray(b)?b:[b]).filter(v=>typeof v=="string"&&v.length>0);if(w.length===0){s[m][u]=[];continue}l.push({index:m,webIds:w})}const d=r?.parallel??!0,f=r?.maxConcurrency??5;return d?await this.executeParallel(s,l,c,u,i,f,r?.timeout??this.defaultTimeout):await this.executeSequential(s,l,c,u,i,r?.timeout??this.defaultTimeout),{data:s,errors:i.length>0?i:void 0}}async executeParallel(e,t,r,i,s,o,a){for(let u=0;u<t.length;u+=o){const c=t.slice(u,u+o);await Promise.all(c.map(async l=>{try{const d=await this.discoverAndQuery(l.webIds,r,a);e[l.index][i]=d}catch(d){e[l.index][i]=[],s.push(this.createError([l.index,i],d,l.webIds[0]))}}))}}async executeSequential(e,t,r,i,s,o){for(const a of t)try{const u=await this.discoverAndQuery(a.webIds,r,o);e[a.index][i]=u}catch(u){e[a.index][i]=[],s.push(this.createError([a.index,i],u,a.webIds[0]))}}async discoverAndQuery(e,t,r){const i=[];for(const s of e){const o=this.extractPodUrl(s);if(!o)continue;const a=await this.providerCache.getWellKnown(o),u=await this.discoverContainer(o,a,t);if(!u)continue;const c=await this.queryContainer(u,t,r);i.push(...c)}return i}extractPodUrl(e){try{const t=new URL(e);return`${t.protocol}//${t.host}/`}catch{return null}}async discoverContainer(e,t,r){if(t.registrySet){const i=await this.discoverFromSAI(t.registrySet,r);if(i)return i}if(t.typeIndex){const i=await this.discoverFromTypeIndex(t.typeIndex,r);if(i)return i}return null}async discoverFromSAI(e,t){try{const r=await this.fetchFn(e,{headers:{Accept:"text/turtle"}});if(!r.ok)return null;const s=(await r.text()).match(/hasDataRegistry>\s*<([^>]+)>/);if(!s)return null;const o=this.resolveUrl(s[1],e),a=await this.fetchFn(o,{headers:{Accept:"text/turtle"}});if(!a.ok)return null;const c=(await a.text()).matchAll(/hasDataRegistration>\s*<([^>]+)>/g);for(const l of c){const d=this.resolveUrl(l[1],o),f=await this.fetchFn(d,{headers:{Accept:"text/turtle"}});if(!f.ok)continue;const g=(await f.text()).match(/registeredShapeTree>\s*<([^>]+)>/);if(!g)continue;const b=this.resolveUrl(g[1],d),S=await this.fetchFn(b,{headers:{Accept:"text/turtle"}});if(!S.ok)continue;if((await S.text()).includes(t))return d.endsWith("/")?d:d+"/"}return null}catch{return null}}resolveUrl(e,t){return e.startsWith("http://")||e.startsWith("https://")?e:new URL(e,t).toString()}async discoverFromTypeIndex(e,t){try{const r=await this.fetchFn(e,{headers:{Accept:"text/turtle"}});if(!r.ok)return null;const s=(await r.text()).split(/\s*[;.]\s*|\n/).map(u=>u.trim()).filter(Boolean);let o=!1,a=null;for(const u of s)if(u.includes("forClass")&&u.includes(t)&&(o=!0),o){if(u.includes("instance")&&!u.includes("instanceContainer")){const c=u.match(/<([^>]+)>/);if(c){a=c[1];break}}if(u.includes("instanceContainer")){const c=u.match(/<([^>]+)>/);if(c){a=c[1];break}}}return a}catch{return null}}async queryContainer(e,t,r){try{const i=new AbortController,s=setTimeout(()=>i.abort(),r),o=await this.fetchFn(e,{headers:{Accept:"text/turtle"},signal:i.signal});if(clearTimeout(s),!o.ok){if(o.status===403)throw new Error(`403 Forbidden: ${e}`);if(o.status===404)throw new Error(`404 Not Found: ${e}`);return[]}const a=await o.text();return this.parseTurtleResources(a,e,t)}catch(i){throw i instanceof Error&&i.name==="AbortError"?new Error(`Timeout: ${e}`):i}}parseTurtleResources(e,t,r){const i=[],s={},o=/@prefix\s+(\w+):\s*<([^>]+)>\s*\./g;let a;for(;(a=o.exec(e))!==null;)s[a[1]]=a[2];const u=new RegExp(`<([^>]+)>\\s+(?:a|rdf:type|<http://www\\.w3\\.org/1999/02/22-rdf-syntax-ns#type>)\\s+<${this.escapeRegex(r)}>`,"g"),c=[];for(;(a=u.exec(e))!==null;)c.push(a[1]);for(const l of c){const d=this.extractResourceProperties(e,l,s,t);d&&i.push(d)}return i}extractResourceProperties(e,t,r,i){const s={"@id":t,id:this.extractIdFromUri(t)},o=this.escapeRegex(t),a=new RegExp(`<${o}>\\s+<([^>]+)>\\s+<([^>]+)>`,"g");let u;for(;(u=a.exec(e))!==null;){const l=u[1],d=u[2],f=this.extractLocalName(l);l.includes("22-rdf-syntax-ns#type")||(s[f]=d)}const c=new RegExp(`<${o}>\\s+<([^>]+)>\\s+"([^"]*)"`,"g");for(;(u=c.exec(e))!==null;){const l=u[1],d=u[2],f=this.extractLocalName(l);s[f]=d}return s}extractIdFromUri(e){const t=e.indexOf("#");if(t!==-1)return e.slice(t);const r=e.lastIndexOf("/");return r!==-1?e.slice(r+1):e}extractLocalName(e){return e.includes("#")?e.split("#").pop()??e:e.split("/").pop()??e}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}createError(e,t,r){const i=t instanceof Error?t.message:String(t);let s="NETWORK_ERROR";return i.includes("403")||i.includes("Forbidden")?s="FORBIDDEN":i.includes("404")||i.includes("Not Found")?s="NOT_FOUND":i.includes("timeout")||i.includes("Timeout")?s="TIMEOUT":i.includes("discover")&&(s="DISCOVERY_FAILED"),{path:e,code:s,message:i,url:r}}}new FederatedQueryExecutor;var buffer={},base64Js={},hasRequiredBase64Js;function requireBase64Js(){if(hasRequiredBase64Js)return base64Js;hasRequiredBase64Js=1,base64Js.byteLength=a,base64Js.toByteArray=c,base64Js.fromByteArray=f;for(var n=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,s=r.length;i<s;++i)n[i]=r[i],e[r.charCodeAt(i)]=i;e[45]=62,e[95]=63;function o(m){var g=m.length;if(g%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=m.indexOf("=");b===-1&&(b=g);var S=b===g?0:4-b%4;return[b,S]}function a(m){var g=o(m),b=g[0],S=g[1];return(b+S)*3/4-S}function u(m,g,b){return(g+b)*3/4-b}function c(m){var g,b=o(m),S=b[0],w=b[1],v=new t(u(m,S,w)),_=0,T=w>0?S-4:S,C;for(C=0;C<T;C+=4)g=e[m.charCodeAt(C)]<<18|e[m.charCodeAt(C+1)]<<12|e[m.charCodeAt(C+2)]<<6|e[m.charCodeAt(C+3)],v[_++]=g>>16&255,v[_++]=g>>8&255,v[_++]=g&255;return w===2&&(g=e[m.charCodeAt(C)]<<2|e[m.charCodeAt(C+1)]>>4,v[_++]=g&255),w===1&&(g=e[m.charCodeAt(C)]<<10|e[m.charCodeAt(C+1)]<<4|e[m.charCodeAt(C+2)]>>2,v[_++]=g>>8&255,v[_++]=g&255),v}function l(m){return n[m>>18&63]+n[m>>12&63]+n[m>>6&63]+n[m&63]}function d(m,g,b){for(var S,w=[],v=g;v<b;v+=3)S=(m[v]<<16&16711680)+(m[v+1]<<8&65280)+(m[v+2]&255),w.push(l(S));return w.join("")}function f(m){for(var g,b=m.length,S=b%3,w=[],v=16383,_=0,T=b-S;_<T;_+=v)w.push(d(m,_,_+v>T?T:_+v));return S===1?(g=m[b-1],w.push(n[g>>2]+n[g<<4&63]+"==")):S===2&&(g=(m[b-2]<<8)+m[b-1],w.push(n[g>>10]+n[g>>4&63]+n[g<<2&63]+"=")),w.join("")}return base64Js}var ieee754={};var hasRequiredIeee754;function requireIeee754(){return hasRequiredIeee754||(hasRequiredIeee754=1,ieee754.read=function(n,e,t,r,i){var s,o,a=i*8-r-1,u=(1<<a)-1,c=u>>1,l=-7,d=t?i-1:0,f=t?-1:1,m=n[e+d];for(d+=f,s=m&(1<<-l)-1,m>>=-l,l+=a;l>0;s=s*256+n[e+d],d+=f,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=r;l>0;o=o*256+n[e+d],d+=f,l-=8);if(s===0)s=1-c;else{if(s===u)return o?NaN:(m?-1:1)*(1/0);o=o+Math.pow(2,r),s=s-c}return(m?-1:1)*o*Math.pow(2,s-r)},ieee754.write=function(n,e,t,r,i,s){var o,a,u,c=s*8-i-1,l=(1<<c)-1,d=l>>1,f=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,m=r?0:s-1,g=r?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=l):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+d>=1?e+=f/u:e+=f*Math.pow(2,1-d),e*u>=2&&(o++,u/=2),o+d>=l?(a=0,o=l):o+d>=1?(a=(e*u-1)*Math.pow(2,i),o=o+d):(a=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;n[t+m]=a&255,m+=g,a/=256,i-=8);for(o=o<<i|a,c+=i;c>0;n[t+m]=o&255,m+=g,o/=256,c-=8);n[t+m-g]|=b*128}),ieee754}var hasRequiredBuffer;function requireBuffer(){return hasRequiredBuffer||(hasRequiredBuffer=1,(function(n){const e=requireBase64Js(),t=requireIeee754(),r=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;n.Buffer=a,n.SlowBuffer=v,n.INSPECT_MAX_BYTES=50;const i=2147483647;n.kMaxLength=i,a.TYPED_ARRAY_SUPPORT=s(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{const B=new Uint8Array(1),R={foo:function(){return 42}};return Object.setPrototypeOf(R,Uint8Array.prototype),Object.setPrototypeOf(B,R),B.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(B){if(B>i)throw new RangeError('The value "'+B+'" is invalid for option "size"');const R=new Uint8Array(B);return Object.setPrototypeOf(R,a.prototype),R}function a(B,R,N){if(typeof B=="number"){if(typeof R=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(B)}return u(B,R,N)}a.poolSize=8192;function u(B,R,N){if(typeof B=="string")return f(B,R);if(ArrayBuffer.isView(B))return g(B);if(B==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof B);if(Y(B,ArrayBuffer)||B&&Y(B.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Y(B,SharedArrayBuffer)||B&&Y(B.buffer,SharedArrayBuffer)))return b(B,R,N);if(typeof B=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const F=B.valueOf&&B.valueOf();if(F!=null&&F!==B)return a.from(F,R,N);const me=S(B);if(me)return me;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof B[Symbol.toPrimitive]=="function")return a.from(B[Symbol.toPrimitive]("string"),R,N);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof B)}a.from=function(B,R,N){return u(B,R,N)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function c(B){if(typeof B!="number")throw new TypeError('"size" argument must be of type number');if(B<0)throw new RangeError('The value "'+B+'" is invalid for option "size"')}function l(B,R,N){return c(B),B<=0?o(B):R!==void 0?typeof N=="string"?o(B).fill(R,N):o(B).fill(R):o(B)}a.alloc=function(B,R,N){return l(B,R,N)};function d(B){return c(B),o(B<0?0:w(B)|0)}a.allocUnsafe=function(B){return d(B)},a.allocUnsafeSlow=function(B){return d(B)};function f(B,R){if((typeof R!="string"||R==="")&&(R="utf8"),!a.isEncoding(R))throw new TypeError("Unknown encoding: "+R);const N=_(B,R)|0;let F=o(N);const me=F.write(B,R);return me!==N&&(F=F.slice(0,me)),F}function m(B){const R=B.length<0?0:w(B.length)|0,N=o(R);for(let F=0;F<R;F+=1)N[F]=B[F]&255;return N}function g(B){if(Y(B,Uint8Array)){const R=new Uint8Array(B);return b(R.buffer,R.byteOffset,R.byteLength)}return m(B)}function b(B,R,N){if(R<0||B.byteLength<R)throw new RangeError('"offset" is outside of buffer bounds');if(B.byteLength<R+(N||0))throw new RangeError('"length" is outside of buffer bounds');let F;return R===void 0&&N===void 0?F=new Uint8Array(B):N===void 0?F=new Uint8Array(B,R):F=new Uint8Array(B,R,N),Object.setPrototypeOf(F,a.prototype),F}function S(B){if(a.isBuffer(B)){const R=w(B.length)|0,N=o(R);return N.length===0||B.copy(N,0,0,R),N}if(B.length!==void 0)return typeof B.length!="number"||Be(B.length)?o(0):m(B);if(B.type==="Buffer"&&Array.isArray(B.data))return m(B.data)}function w(B){if(B>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return B|0}function v(B){return+B!=B&&(B=0),a.alloc(+B)}a.isBuffer=function(R){return R!=null&&R._isBuffer===!0&&R!==a.prototype},a.compare=function(R,N){if(Y(R,Uint8Array)&&(R=a.from(R,R.offset,R.byteLength)),Y(N,Uint8Array)&&(N=a.from(N,N.offset,N.byteLength)),!a.isBuffer(R)||!a.isBuffer(N))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(R===N)return 0;let F=R.length,me=N.length;for(let Re=0,we=Math.min(F,me);Re<we;++Re)if(R[Re]!==N[Re]){F=R[Re],me=N[Re];break}return F<me?-1:me<F?1:0},a.isEncoding=function(R){switch(String(R).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}},a.concat=function(R,N){if(!Array.isArray(R))throw new TypeError('"list" argument must be an Array of Buffers');if(R.length===0)return a.alloc(0);let F;if(N===void 0)for(N=0,F=0;F<R.length;++F)N+=R[F].length;const me=a.allocUnsafe(N);let Re=0;for(F=0;F<R.length;++F){let we=R[F];if(Y(we,Uint8Array))Re+we.length>me.length?(a.isBuffer(we)||(we=a.from(we)),we.copy(me,Re)):Uint8Array.prototype.set.call(me,we,Re);else if(a.isBuffer(we))we.copy(me,Re);else throw new TypeError('"list" argument must be an Array of Buffers');Re+=we.length}return me};function _(B,R){if(a.isBuffer(B))return B.length;if(ArrayBuffer.isView(B)||Y(B,ArrayBuffer))return B.byteLength;if(typeof B!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof B);const N=B.length,F=arguments.length>2&&arguments[2]===!0;if(!F&&N===0)return 0;let me=!1;for(;;)switch(R){case"ascii":case"latin1":case"binary":return N;case"utf8":case"utf-8":return Q(B).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N*2;case"hex":return N>>>1;case"base64":return ne(B).length;default:if(me)return F?-1:Q(B).length;R=(""+R).toLowerCase(),me=!0}}a.byteLength=_;function T(B,R,N){let F=!1;if((R===void 0||R<0)&&(R=0),R>this.length||((N===void 0||N>this.length)&&(N=this.length),N<=0)||(N>>>=0,R>>>=0,N<=R))return"";for(B||(B="utf8");;)switch(B){case"hex":return ve(this,R,N);case"utf8":case"utf-8":return _e(this,R,N);case"ascii":return ze(this,R,N);case"latin1":case"binary":return ae(this,R,N);case"base64":return z(this,R,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,R,N);default:if(F)throw new TypeError("Unknown encoding: "+B);B=(B+"").toLowerCase(),F=!0}}a.prototype._isBuffer=!0;function C(B,R,N){const F=B[R];B[R]=B[N],B[N]=F}a.prototype.swap16=function(){const R=this.length;if(R%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let N=0;N<R;N+=2)C(this,N,N+1);return this},a.prototype.swap32=function(){const R=this.length;if(R%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let N=0;N<R;N+=4)C(this,N,N+3),C(this,N+1,N+2);return this},a.prototype.swap64=function(){const R=this.length;if(R%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let N=0;N<R;N+=8)C(this,N,N+7),C(this,N+1,N+6),C(this,N+2,N+5),C(this,N+3,N+4);return this},a.prototype.toString=function(){const R=this.length;return R===0?"":arguments.length===0?_e(this,0,R):T.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(R){if(!a.isBuffer(R))throw new TypeError("Argument must be a Buffer");return this===R?!0:a.compare(this,R)===0},a.prototype.inspect=function(){let R="";const N=n.INSPECT_MAX_BYTES;return R=this.toString("hex",0,N).replace(/(.{2})/g,"$1 ").trim(),this.length>N&&(R+=" ... "),"<Buffer "+R+">"},r&&(a.prototype[r]=a.prototype.inspect),a.prototype.compare=function(R,N,F,me,Re){if(Y(R,Uint8Array)&&(R=a.from(R,R.offset,R.byteLength)),!a.isBuffer(R))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof R);if(N===void 0&&(N=0),F===void 0&&(F=R?R.length:0),me===void 0&&(me=0),Re===void 0&&(Re=this.length),N<0||F>R.length||me<0||Re>this.length)throw new RangeError("out of range index");if(me>=Re&&N>=F)return 0;if(me>=Re)return-1;if(N>=F)return 1;if(N>>>=0,F>>>=0,me>>>=0,Re>>>=0,this===R)return 0;let we=Re-me,Qe=F-N;const et=Math.min(we,Qe),ot=this.slice(me,Re),ct=R.slice(N,F);for(let at=0;at<et;++at)if(ot[at]!==ct[at]){we=ot[at],Qe=ct[at];break}return we<Qe?-1:Qe<we?1:0};function U(B,R,N,F,me){if(B.length===0)return-1;if(typeof N=="string"?(F=N,N=0):N>2147483647?N=2147483647:N<-2147483648&&(N=-2147483648),N=+N,Be(N)&&(N=me?0:B.length-1),N<0&&(N=B.length+N),N>=B.length){if(me)return-1;N=B.length-1}else if(N<0)if(me)N=0;else return-1;if(typeof R=="string"&&(R=a.from(R,F)),a.isBuffer(R))return R.length===0?-1:$(B,R,N,F,me);if(typeof R=="number")return R=R&255,typeof Uint8Array.prototype.indexOf=="function"?me?Uint8Array.prototype.indexOf.call(B,R,N):Uint8Array.prototype.lastIndexOf.call(B,R,N):$(B,[R],N,F,me);throw new TypeError("val must be string, number or Buffer")}function $(B,R,N,F,me){let Re=1,we=B.length,Qe=R.length;if(F!==void 0&&(F=String(F).toLowerCase(),F==="ucs2"||F==="ucs-2"||F==="utf16le"||F==="utf-16le")){if(B.length<2||R.length<2)return-1;Re=2,we/=2,Qe/=2,N/=2}function et(ct,at){return Re===1?ct[at]:ct.readUInt16BE(at*Re)}let ot;if(me){let ct=-1;for(ot=N;ot<we;ot++)if(et(B,ot)===et(R,ct===-1?0:ot-ct)){if(ct===-1&&(ct=ot),ot-ct+1===Qe)return ct*Re}else ct!==-1&&(ot-=ot-ct),ct=-1}else for(N+Qe>we&&(N=we-Qe),ot=N;ot>=0;ot--){let ct=!0;for(let at=0;at<Qe;at++)if(et(B,ot+at)!==et(R,at)){ct=!1;break}if(ct)return ot}return-1}a.prototype.includes=function(R,N,F){return this.indexOf(R,N,F)!==-1},a.prototype.indexOf=function(R,N,F){return U(this,R,N,F,!0)},a.prototype.lastIndexOf=function(R,N,F){return U(this,R,N,F,!1)};function W(B,R,N,F){N=Number(N)||0;const me=B.length-N;F?(F=Number(F),F>me&&(F=me)):F=me;const Re=R.length;F>Re/2&&(F=Re/2);let we;for(we=0;we<F;++we){const Qe=parseInt(R.substr(we*2,2),16);if(Be(Qe))return we;B[N+we]=Qe}return we}function re(B,R,N,F){return ge(Q(R,B.length-N),B,N,F)}function D(B,R,N,F){return ge(de(R),B,N,F)}function V(B,R,N,F){return ge(ne(R),B,N,F)}function he(B,R,N,F){return ge(M(R,B.length-N),B,N,F)}a.prototype.write=function(R,N,F,me){if(N===void 0)me="utf8",F=this.length,N=0;else if(F===void 0&&typeof N=="string")me=N,F=this.length,N=0;else if(isFinite(N))N=N>>>0,isFinite(F)?(F=F>>>0,me===void 0&&(me="utf8")):(me=F,F=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const Re=this.length-N;if((F===void 0||F>Re)&&(F=Re),R.length>0&&(F<0||N<0)||N>this.length)throw new RangeError("Attempt to write outside buffer bounds");me||(me="utf8");let we=!1;for(;;)switch(me){case"hex":return W(this,R,N,F);case"utf8":case"utf-8":return re(this,R,N,F);case"ascii":case"latin1":case"binary":return D(this,R,N,F);case"base64":return V(this,R,N,F);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return he(this,R,N,F);default:if(we)throw new TypeError("Unknown encoding: "+me);me=(""+me).toLowerCase(),we=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function z(B,R,N){return R===0&&N===B.length?e.fromByteArray(B):e.fromByteArray(B.slice(R,N))}function _e(B,R,N){N=Math.min(B.length,N);const F=[];let me=R;for(;me<N;){const Re=B[me];let we=null,Qe=Re>239?4:Re>223?3:Re>191?2:1;if(me+Qe<=N){let et,ot,ct,at;switch(Qe){case 1:Re<128&&(we=Re);break;case 2:et=B[me+1],(et&192)===128&&(at=(Re&31)<<6|et&63,at>127&&(we=at));break;case 3:et=B[me+1],ot=B[me+2],(et&192)===128&&(ot&192)===128&&(at=(Re&15)<<12|(et&63)<<6|ot&63,at>2047&&(at<55296||at>57343)&&(we=at));break;case 4:et=B[me+1],ot=B[me+2],ct=B[me+3],(et&192)===128&&(ot&192)===128&&(ct&192)===128&&(at=(Re&15)<<18|(et&63)<<12|(ot&63)<<6|ct&63,at>65535&&at<1114112&&(we=at))}}we===null?(we=65533,Qe=1):we>65535&&(we-=65536,F.push(we>>>10&1023|55296),we=56320|we&1023),F.push(we),me+=Qe}return Fe(F)}const Ce=4096;function Fe(B){const R=B.length;if(R<=Ce)return String.fromCharCode.apply(String,B);let N="",F=0;for(;F<R;)N+=String.fromCharCode.apply(String,B.slice(F,F+=Ce));return N}function ze(B,R,N){let F="";N=Math.min(B.length,N);for(let me=R;me<N;++me)F+=String.fromCharCode(B[me]&127);return F}function ae(B,R,N){let F="";N=Math.min(B.length,N);for(let me=R;me<N;++me)F+=String.fromCharCode(B[me]);return F}function ve(B,R,N){const F=B.length;(!R||R<0)&&(R=0),(!N||N<0||N>F)&&(N=F);let me="";for(let Re=R;Re<N;++Re)me+=Je[B[Re]];return me}function L(B,R,N){const F=B.slice(R,N);let me="";for(let Re=0;Re<F.length-1;Re+=2)me+=String.fromCharCode(F[Re]+F[Re+1]*256);return me}a.prototype.slice=function(R,N){const F=this.length;R=~~R,N=N===void 0?F:~~N,R<0?(R+=F,R<0&&(R=0)):R>F&&(R=F),N<0?(N+=F,N<0&&(N=0)):N>F&&(N=F),N<R&&(N=R);const me=this.subarray(R,N);return Object.setPrototypeOf(me,a.prototype),me};function ie(B,R,N){if(B%1!==0||B<0)throw new RangeError("offset is not uint");if(B+R>N)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(R,N,F){R=R>>>0,N=N>>>0,F||ie(R,N,this.length);let me=this[R],Re=1,we=0;for(;++we<N&&(Re*=256);)me+=this[R+we]*Re;return me},a.prototype.readUintBE=a.prototype.readUIntBE=function(R,N,F){R=R>>>0,N=N>>>0,F||ie(R,N,this.length);let me=this[R+--N],Re=1;for(;N>0&&(Re*=256);)me+=this[R+--N]*Re;return me},a.prototype.readUint8=a.prototype.readUInt8=function(R,N){return R=R>>>0,N||ie(R,1,this.length),this[R]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(R,N){return R=R>>>0,N||ie(R,2,this.length),this[R]|this[R+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(R,N){return R=R>>>0,N||ie(R,2,this.length),this[R]<<8|this[R+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(R,N){return R=R>>>0,N||ie(R,4,this.length),(this[R]|this[R+1]<<8|this[R+2]<<16)+this[R+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(R,N){return R=R>>>0,N||ie(R,4,this.length),this[R]*16777216+(this[R+1]<<16|this[R+2]<<8|this[R+3])},a.prototype.readBigUInt64LE=Ne(function(R){R=R>>>0,x(R,"offset");const N=this[R],F=this[R+7];(N===void 0||F===void 0)&&A(R,this.length-8);const me=N+this[++R]*2**8+this[++R]*2**16+this[++R]*2**24,Re=this[++R]+this[++R]*2**8+this[++R]*2**16+F*2**24;return BigInt(me)+(BigInt(Re)<<BigInt(32))}),a.prototype.readBigUInt64BE=Ne(function(R){R=R>>>0,x(R,"offset");const N=this[R],F=this[R+7];(N===void 0||F===void 0)&&A(R,this.length-8);const me=N*2**24+this[++R]*2**16+this[++R]*2**8+this[++R],Re=this[++R]*2**24+this[++R]*2**16+this[++R]*2**8+F;return(BigInt(me)<<BigInt(32))+BigInt(Re)}),a.prototype.readIntLE=function(R,N,F){R=R>>>0,N=N>>>0,F||ie(R,N,this.length);let me=this[R],Re=1,we=0;for(;++we<N&&(Re*=256);)me+=this[R+we]*Re;return Re*=128,me>=Re&&(me-=Math.pow(2,8*N)),me},a.prototype.readIntBE=function(R,N,F){R=R>>>0,N=N>>>0,F||ie(R,N,this.length);let me=N,Re=1,we=this[R+--me];for(;me>0&&(Re*=256);)we+=this[R+--me]*Re;return Re*=128,we>=Re&&(we-=Math.pow(2,8*N)),we},a.prototype.readInt8=function(R,N){return R=R>>>0,N||ie(R,1,this.length),this[R]&128?(255-this[R]+1)*-1:this[R]},a.prototype.readInt16LE=function(R,N){R=R>>>0,N||ie(R,2,this.length);const F=this[R]|this[R+1]<<8;return F&32768?F|4294901760:F},a.prototype.readInt16BE=function(R,N){R=R>>>0,N||ie(R,2,this.length);const F=this[R+1]|this[R]<<8;return F&32768?F|4294901760:F},a.prototype.readInt32LE=function(R,N){return R=R>>>0,N||ie(R,4,this.length),this[R]|this[R+1]<<8|this[R+2]<<16|this[R+3]<<24},a.prototype.readInt32BE=function(R,N){return R=R>>>0,N||ie(R,4,this.length),this[R]<<24|this[R+1]<<16|this[R+2]<<8|this[R+3]},a.prototype.readBigInt64LE=Ne(function(R){R=R>>>0,x(R,"offset");const N=this[R],F=this[R+7];(N===void 0||F===void 0)&&A(R,this.length-8);const me=this[R+4]+this[R+5]*2**8+this[R+6]*2**16+(F<<24);return(BigInt(me)<<BigInt(32))+BigInt(N+this[++R]*2**8+this[++R]*2**16+this[++R]*2**24)}),a.prototype.readBigInt64BE=Ne(function(R){R=R>>>0,x(R,"offset");const N=this[R],F=this[R+7];(N===void 0||F===void 0)&&A(R,this.length-8);const me=(N<<24)+this[++R]*2**16+this[++R]*2**8+this[++R];return(BigInt(me)<<BigInt(32))+BigInt(this[++R]*2**24+this[++R]*2**16+this[++R]*2**8+F)}),a.prototype.readFloatLE=function(R,N){return R=R>>>0,N||ie(R,4,this.length),t.read(this,R,!0,23,4)},a.prototype.readFloatBE=function(R,N){return R=R>>>0,N||ie(R,4,this.length),t.read(this,R,!1,23,4)},a.prototype.readDoubleLE=function(R,N){return R=R>>>0,N||ie(R,8,this.length),t.read(this,R,!0,52,8)},a.prototype.readDoubleBE=function(R,N){return R=R>>>0,N||ie(R,8,this.length),t.read(this,R,!1,52,8)};function xe(B,R,N,F,me,Re){if(!a.isBuffer(B))throw new TypeError('"buffer" argument must be a Buffer instance');if(R>me||R<Re)throw new RangeError('"value" argument is out of bounds');if(N+F>B.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(R,N,F,me){if(R=+R,N=N>>>0,F=F>>>0,!me){const Qe=Math.pow(2,8*F)-1;xe(this,R,N,F,Qe,0)}let Re=1,we=0;for(this[N]=R&255;++we<F&&(Re*=256);)this[N+we]=R/Re&255;return N+F},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(R,N,F,me){if(R=+R,N=N>>>0,F=F>>>0,!me){const Qe=Math.pow(2,8*F)-1;xe(this,R,N,F,Qe,0)}let Re=F-1,we=1;for(this[N+Re]=R&255;--Re>=0&&(we*=256);)this[N+Re]=R/we&255;return N+F},a.prototype.writeUint8=a.prototype.writeUInt8=function(R,N,F){return R=+R,N=N>>>0,F||xe(this,R,N,1,255,0),this[N]=R&255,N+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(R,N,F){return R=+R,N=N>>>0,F||xe(this,R,N,2,65535,0),this[N]=R&255,this[N+1]=R>>>8,N+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(R,N,F){return R=+R,N=N>>>0,F||xe(this,R,N,2,65535,0),this[N]=R>>>8,this[N+1]=R&255,N+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(R,N,F){return R=+R,N=N>>>0,F||xe(this,R,N,4,4294967295,0),this[N+3]=R>>>24,this[N+2]=R>>>16,this[N+1]=R>>>8,this[N]=R&255,N+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(R,N,F){return R=+R,N=N>>>0,F||xe(this,R,N,4,4294967295,0),this[N]=R>>>24,this[N+1]=R>>>16,this[N+2]=R>>>8,this[N+3]=R&255,N+4};function ue(B,R,N,F,me){P(R,F,me,B,N,7);let Re=Number(R&BigInt(4294967295));B[N++]=Re,Re=Re>>8,B[N++]=Re,Re=Re>>8,B[N++]=Re,Re=Re>>8,B[N++]=Re;let we=Number(R>>BigInt(32)&BigInt(4294967295));return B[N++]=we,we=we>>8,B[N++]=we,we=we>>8,B[N++]=we,we=we>>8,B[N++]=we,N}function De(B,R,N,F,me){P(R,F,me,B,N,7);let Re=Number(R&BigInt(4294967295));B[N+7]=Re,Re=Re>>8,B[N+6]=Re,Re=Re>>8,B[N+5]=Re,Re=Re>>8,B[N+4]=Re;let we=Number(R>>BigInt(32)&BigInt(4294967295));return B[N+3]=we,we=we>>8,B[N+2]=we,we=we>>8,B[N+1]=we,we=we>>8,B[N]=we,N+8}a.prototype.writeBigUInt64LE=Ne(function(R,N=0){return ue(this,R,N,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=Ne(function(R,N=0){return De(this,R,N,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(R,N,F,me){if(R=+R,N=N>>>0,!me){const et=Math.pow(2,8*F-1);xe(this,R,N,F,et-1,-et)}let Re=0,we=1,Qe=0;for(this[N]=R&255;++Re<F&&(we*=256);)R<0&&Qe===0&&this[N+Re-1]!==0&&(Qe=1),this[N+Re]=(R/we>>0)-Qe&255;return N+F},a.prototype.writeIntBE=function(R,N,F,me){if(R=+R,N=N>>>0,!me){const et=Math.pow(2,8*F-1);xe(this,R,N,F,et-1,-et)}let Re=F-1,we=1,Qe=0;for(this[N+Re]=R&255;--Re>=0&&(we*=256);)R<0&&Qe===0&&this[N+Re+1]!==0&&(Qe=1),this[N+Re]=(R/we>>0)-Qe&255;return N+F},a.prototype.writeInt8=function(R,N,F){return R=+R,N=N>>>0,F||xe(this,R,N,1,127,-128),R<0&&(R=255+R+1),this[N]=R&255,N+1},a.prototype.writeInt16LE=function(R,N,F){return R=+R,N=N>>>0,F||xe(this,R,N,2,32767,-32768),this[N]=R&255,this[N+1]=R>>>8,N+2},a.prototype.writeInt16BE=function(R,N,F){return R=+R,N=N>>>0,F||xe(this,R,N,2,32767,-32768),this[N]=R>>>8,this[N+1]=R&255,N+2},a.prototype.writeInt32LE=function(R,N,F){return R=+R,N=N>>>0,F||xe(this,R,N,4,2147483647,-2147483648),this[N]=R&255,this[N+1]=R>>>8,this[N+2]=R>>>16,this[N+3]=R>>>24,N+4},a.prototype.writeInt32BE=function(R,N,F){return R=+R,N=N>>>0,F||xe(this,R,N,4,2147483647,-2147483648),R<0&&(R=4294967295+R+1),this[N]=R>>>24,this[N+1]=R>>>16,this[N+2]=R>>>8,this[N+3]=R&255,N+4},a.prototype.writeBigInt64LE=Ne(function(R,N=0){return ue(this,R,N,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=Ne(function(R,N=0){return De(this,R,N,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ke(B,R,N,F,me,Re){if(N+F>B.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("Index out of range")}function We(B,R,N,F,me){return R=+R,N=N>>>0,me||ke(B,R,N,4),t.write(B,R,N,F,23,4),N+4}a.prototype.writeFloatLE=function(R,N,F){return We(this,R,N,!0,F)},a.prototype.writeFloatBE=function(R,N,F){return We(this,R,N,!1,F)};function Oe(B,R,N,F,me){return R=+R,N=N>>>0,me||ke(B,R,N,8),t.write(B,R,N,F,52,8),N+8}a.prototype.writeDoubleLE=function(R,N,F){return Oe(this,R,N,!0,F)},a.prototype.writeDoubleBE=function(R,N,F){return Oe(this,R,N,!1,F)},a.prototype.copy=function(R,N,F,me){if(!a.isBuffer(R))throw new TypeError("argument should be a Buffer");if(F||(F=0),!me&&me!==0&&(me=this.length),N>=R.length&&(N=R.length),N||(N=0),me>0&&me<F&&(me=F),me===F||R.length===0||this.length===0)return 0;if(N<0)throw new RangeError("targetStart out of bounds");if(F<0||F>=this.length)throw new RangeError("Index out of range");if(me<0)throw new RangeError("sourceEnd out of bounds");me>this.length&&(me=this.length),R.length-N<me-F&&(me=R.length-N+F);const Re=me-F;return this===R&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(N,F,me):Uint8Array.prototype.set.call(R,this.subarray(F,me),N),Re},a.prototype.fill=function(R,N,F,me){if(typeof R=="string"){if(typeof N=="string"?(me=N,N=0,F=this.length):typeof F=="string"&&(me=F,F=this.length),me!==void 0&&typeof me!="string")throw new TypeError("encoding must be a string");if(typeof me=="string"&&!a.isEncoding(me))throw new TypeError("Unknown encoding: "+me);if(R.length===1){const we=R.charCodeAt(0);(me==="utf8"&&we<128||me==="latin1")&&(R=we)}}else typeof R=="number"?R=R&255:typeof R=="boolean"&&(R=Number(R));if(N<0||this.length<N||this.length<F)throw new RangeError("Out of range index");if(F<=N)return this;N=N>>>0,F=F===void 0?this.length:F>>>0,R||(R=0);let Re;if(typeof R=="number")for(Re=N;Re<F;++Re)this[Re]=R;else{const we=a.isBuffer(R)?R:a.from(R,me),Qe=we.length;if(Qe===0)throw new TypeError('The value "'+R+'" is invalid for argument "value"');for(Re=0;Re<F-N;++Re)this[Re+N]=we[Re%Qe]}return this};const te={};function le(B,R,N){te[B]=class extends N{constructor(){super(),Object.defineProperty(this,"message",{value:R.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${B}]`,this.stack,delete this.name}get code(){return B}set code(me){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:me,writable:!0})}toString(){return`${this.name} [${B}]: ${this.message}`}}}le("ERR_BUFFER_OUT_OF_BOUNDS",function(B){return B?`${B} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),le("ERR_INVALID_ARG_TYPE",function(B,R){return`The "${B}" argument must be of type number. Received type ${typeof R}`},TypeError),le("ERR_OUT_OF_RANGE",function(B,R,N){let F=`The value of "${B}" is out of range.`,me=N;return Number.isInteger(N)&&Math.abs(N)>2**32?me=Te(String(N)):typeof N=="bigint"&&(me=String(N),(N>BigInt(2)**BigInt(32)||N<-(BigInt(2)**BigInt(32)))&&(me=Te(me)),me+="n"),F+=` It must be ${R}. Received ${me}`,F},RangeError);function Te(B){let R="",N=B.length;const F=B[0]==="-"?1:0;for(;N>=F+4;N-=3)R=`_${B.slice(N-3,N)}${R}`;return`${B.slice(0,N)}${R}`}function G(B,R,N){x(R,"offset"),(B[R]===void 0||B[R+N]===void 0)&&A(R,B.length-(N+1))}function P(B,R,N,F,me,Re){if(B>N||B<R){const we=typeof R=="bigint"?"n":"";let Qe;throw R===0||R===BigInt(0)?Qe=`>= 0${we} and < 2${we} ** ${(Re+1)*8}${we}`:Qe=`>= -(2${we} ** ${(Re+1)*8-1}${we}) and < 2 ** ${(Re+1)*8-1}${we}`,new te.ERR_OUT_OF_RANGE("value",Qe,B)}G(F,me,Re)}function x(B,R){if(typeof B!="number")throw new te.ERR_INVALID_ARG_TYPE(R,"number",B)}function A(B,R,N){throw Math.floor(B)!==B?(x(B,N),new te.ERR_OUT_OF_RANGE("offset","an integer",B)):R<0?new te.ERR_BUFFER_OUT_OF_BOUNDS:new te.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${R}`,B)}const O=/[^+/0-9A-Za-z-_]/g;function H(B){if(B=B.split("=")[0],B=B.trim().replace(O,""),B.length<2)return"";for(;B.length%4!==0;)B=B+"=";return B}function Q(B,R){R=R||1/0;let N;const F=B.length;let me=null;const Re=[];for(let we=0;we<F;++we){if(N=B.charCodeAt(we),N>55295&&N<57344){if(!me){if(N>56319){(R-=3)>-1&&Re.push(239,191,189);continue}else if(we+1===F){(R-=3)>-1&&Re.push(239,191,189);continue}me=N;continue}if(N<56320){(R-=3)>-1&&Re.push(239,191,189),me=N;continue}N=(me-55296<<10|N-56320)+65536}else me&&(R-=3)>-1&&Re.push(239,191,189);if(me=null,N<128){if((R-=1)<0)break;Re.push(N)}else if(N<2048){if((R-=2)<0)break;Re.push(N>>6|192,N&63|128)}else if(N<65536){if((R-=3)<0)break;Re.push(N>>12|224,N>>6&63|128,N&63|128)}else if(N<1114112){if((R-=4)<0)break;Re.push(N>>18|240,N>>12&63|128,N>>6&63|128,N&63|128)}else throw new Error("Invalid code point")}return Re}function de(B){const R=[];for(let N=0;N<B.length;++N)R.push(B.charCodeAt(N)&255);return R}function M(B,R){let N,F,me;const Re=[];for(let we=0;we<B.length&&!((R-=2)<0);++we)N=B.charCodeAt(we),F=N>>8,me=N%256,Re.push(me),Re.push(F);return Re}function ne(B){return e.toByteArray(H(B))}function ge(B,R,N,F){let me;for(me=0;me<F&&!(me+N>=R.length||me>=B.length);++me)R[me+N]=B[me];return me}function Y(B,R){return B instanceof R||B!=null&&B.constructor!=null&&B.constructor.name!=null&&B.constructor.name===R.name}function Be(B){return B!==B}const Je=(function(){const B="0123456789abcdef",R=new Array(256);for(let N=0;N<16;++N){const F=N*16;for(let me=0;me<16;++me)R[F+me]=B[N]+B[me]}return R})();function Ne(B){return typeof BigInt>"u"?Ze:B}function Ze(){throw new Error("BigInt not supported")}})(buffer)),buffer}var bufferExports=requireBuffer();const RDF$3="http://www.w3.org/1999/02/22-rdf-syntax-ns#",XSD$7="http://www.w3.org/2001/XMLSchema#",SWAP$1="http://www.w3.org/2000/10/swap/",namespaces$2={xsd:{decimal:`${XSD$7}decimal`,boolean:`${XSD$7}boolean`,double:`${XSD$7}double`,integer:`${XSD$7}integer`,string:`${XSD$7}string`},rdf:{type:`${RDF$3}type`,nil:`${RDF$3}nil`,first:`${RDF$3}first`,rest:`${RDF$3}rest`,langString:`${RDF$3}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${SWAP$1}reify#forSome`,forAll:`${SWAP$1}reify#forAll`},log:{implies:`${SWAP$1}log#implies`,isImpliedBy:`${SWAP$1}log#isImpliedBy`}},{xsd:xsd$5}=namespaces$2,escapeSequence$1=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,escapeReplacements$1={"\\":"\\","'":"'",'"':'"',n:`
|
|
8
|
+
`,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},illegalIriChars$1=/[\x00-\x20<>\\"\{\}\|\^\`]/,lineModeRegExps$1={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},invalidRegExp$1=/$0^/;let N3Lexer$1=class{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$1)&&this[t]instanceof RegExp&&(this[t]=invalidRegExp$1)}else this._n3Mode=e.n3!==!1;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let r=this._input,i=r.length;for(;;){let a,u;for(;a=this._newline.exec(r);)this.comments&&(u=this._comment.exec(a[0]))&&s("comment",u[1],"",this._line,a[0].length),r=r.substr(a[0].length,r.length),i=r.length,this._line++;if(!a&&(a=this._whitespace.exec(r))&&(r=r.substr(a[0].length,r.length)),this._endOfFile.test(r))return t&&(this.comments&&(u=this._comment.exec(r))&&s("comment",u[1],"",this._line,r.length),r=null,s("eof","","",this._line,0)),this._input=r;const c=this._line,l=r[0];let d="",f="",m="",g=null,b=0,S=!1;switch(l){case"^":if(r.length<3)break;if(r[1]==="^"){if(this._previousMarker="^^",r=r.substr(2),r[0]!=="<"){S=!0;break}}else{this._n3Mode&&(b=1,d="^");break}case"<":if(g=this._unescapedIri.exec(r))d="IRI",f=g[1];else if(g=this._iri.exec(r)){if(f=this._unescape(g[1]),f===null||illegalIriChars$1.test(f))return o(this);d="IRI"}else r.length>1&&r[1]==="<"?(d="<<",b=2):this._n3Mode&&r.length>1&&r[1]==="="&&(b=2,this._isImpliedBy?(d="abbreviation",f="<"):(d="inverse",f=">"));break;case">":r.length>1&&r[1]===">"&&(d=">>",b=2);break;case"_":((g=this._blank.exec(r))||t&&(g=this._blank.exec(`${r} `)))&&(d="blank",m="_",f=g[1]);break;case'"':if(g=this._simpleQuotedString.exec(r))f=g[1];else if({value:f,matchLength:b}=this._parseLiteral(r),f===null)return o(this);(g!==null||b!==0)&&(d="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(g=this._simpleApostropheString.exec(r))f=g[1];else if({value:f,matchLength:b}=this._parseLiteral(r),f===null)return o(this);(g!==null||b!==0)&&(d="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(g=this._variable.exec(r))&&(d="var",f=g[0]);break;case"@":this._previousMarker==="literal"&&(g=this._langcode.exec(r))?(d="langcode",f=g[1]):(g=this._keyword.exec(r))&&(d=g[0]);break;case".":if(r.length===1?t:r[1]<"0"||r[1]>"9"){d=".",b=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(g=this._number.exec(r)||t&&(g=this._number.exec(`${r} `)))&&(d="literal",f=g[0],m=typeof g[1]=="string"?xsd$5.double:typeof g[2]=="string"?xsd$5.decimal:xsd$5.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(g=this._sparqlKeyword.exec(r))?d=g[0].toUpperCase():S=!0;break;case"f":case"t":(g=this._boolean.exec(r))?(d="literal",f=g[0],m=xsd$5.boolean):S=!0;break;case"a":(g=this._shortPredicates.exec(r))?(d="abbreviation",f="a"):S=!0;break;case"=":this._n3Mode&&r.length>1&&(d="abbreviation",r[1]!==">"?(b=1,f="="):(b=2,f=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(b=1,d=l);break;case"{":!this._lineMode&&r.length>=2&&(r[1]==="|"?(d="{|",b=2):(d=l,b=1));break;case"|":r.length>=2&&r[1]==="}"&&(d="|}",b=2);break;default:S=!0}if(S&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(g=this._prefix.exec(r))?(d="prefix",f=g[1]||""):((g=this._prefixed.exec(r))||t&&(g=this._prefixed.exec(`${r} `)))&&(d="prefixed",m=g[1]||"",f=this._unescape(g[2]))),this._previousMarker==="^^")switch(d){case"prefixed":d="type";break;case"IRI":d="typeIRI";break;default:d=""}if(!d)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?o(this):this._input=r;const w=b||g[0].length,v=s(d,f,m,c,w);this.previousToken=v,this._previousMarker=d,r=r.substr(w,r.length)}function s(a,u,c,l,d){const f=r?i-r.length:i,m=f+d,g={type:a,value:u,prefix:c,line:l,start:f,end:m};return e(null,g),g}function o(a){e(a._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1;const r=e.replace(escapeSequence$1,(i,s,o,a)=>{if(typeof s=="string")return String.fromCharCode(Number.parseInt(s,16));if(typeof o=="string"){let u=Number.parseInt(o,16);return u<=65535?String.fromCharCode(Number.parseInt(o,16)):String.fromCharCode(55296+((u-=65536)>>10),56320+(u&1023))}return a in escapeReplacements$1?escapeReplacements$1[a]:(t=!0,"")});return t?null:r}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],r=t.length;let i=Math.max(this._literalClosingPos,r);for(;(i=e.indexOf(t,i))>0;){let s=0;for(;e[i-s-1]==="\\";)s++;if(s%2===0){const o=e.substring(r,i),a=o.split(/\r\n|\r|\n/).length-1,u=i+r;if(r===1&&a!==0||r===3&&this._lineMode)break;return this._line+=a,{value:this._unescape(o),matchLength:u}}i++}this._literalClosingPos=e.length-r+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 r=[];let i;if(this._tokenizeToEnd((s,o)=>s?i=s:r.push(o),!0),i)throw i;return r}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",r=>{this._input!==null&&r.length!==0&&(this._pendingBuffer&&(r=bufferExports.Buffer.concat([this._pendingBuffer,r]),this._pendingBuffer=null),r[r.length-1]&128?this._pendingBuffer=r:(typeof this._input>"u"?this._input=this._readStartingBom(typeof r=="string"?r:r.toString()):this._input+=r,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}};const{rdf:rdf$4,xsd:xsd$4}=namespaces$2;let DEFAULTGRAPH$3,_blankNodeCounter$1=0;const DataFactory$2={namedNode:namedNode$1,blankNode:blankNode$1,variable:variable$1,literal:literal$1,defaultGraph:defaultGraph$1,quad:quad$1,triple:quad$1,fromTerm:fromTerm$1,fromQuad:fromQuad$1};let Term$1=class Un{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof Un?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}},NamedNode$2=class extends Term$1{get termType(){return"NamedNode"}},Literal$2=class kn extends Term$1{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$2(this.datatypeString)}get datatypeString(){const e=this.id,t=e.lastIndexOf('"')+1,r=t<e.length?e[t]:"";return r==="^"?e.substr(t+2):r!=="@"?xsd$4.string:rdf$4.langString}equals(e){return e instanceof kn?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}}}},BlankNode$2=class extends Term$1{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}},Variable$2=class extends Term$1{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}},DefaultGraph$2=class extends Term$1{constructor(){return super(""),DEFAULTGRAPH$3||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}};DEFAULTGRAPH$3=new DefaultGraph$2;function termFromId$1(n,e,t){if(e=e||DataFactory$2,!n)return e.defaultGraph();switch(n[0]){case"?":return e.variable(n.substr(1));case"_":return e.blankNode(n.substr(2));case'"':if(e===DataFactory$2)return new Literal$2(n);if(n[n.length-1]==='"')return e.literal(n.substr(1,n.length-2));const r=n.lastIndexOf('"',n.length-1);return e.literal(n.substr(1,r-1),n[r+1]==="@"?n.substr(r+2):e.namedNode(n.substr(r+3)));case"[":n=JSON.parse(n);break;default:if(!t||!Array.isArray(n))return e.namedNode(n)}return e.quad(termFromId$1(n[0],e,!0),termFromId$1(n[1],e,!0),termFromId$1(n[2],e,!0),n[3]&&termFromId$1(n[3],e,!0))}function termToId$1(n,e){if(typeof n=="string")return n;if(n instanceof Term$1&&n.termType!=="Quad")return n.id;if(!n)return DEFAULTGRAPH$3.id;switch(n.termType){case"NamedNode":return n.value;case"BlankNode":return`_:${n.value}`;case"Variable":return`?${n.value}`;case"DefaultGraph":return"";case"Literal":return`"${n.value}"${n.language?`@${n.language}`:n.datatype&&n.datatype.value!==xsd$4.string?`^^${n.datatype.value}`:""}`;case"Quad":const t=[termToId$1(n.subject,!0),termToId$1(n.predicate,!0),termToId$1(n.object,!0)];return n.graph&&n.graph.termType!=="DefaultGraph"&&t.push(termToId$1(n.graph,!0)),e?t:JSON.stringify(t);default:throw new Error(`Unexpected termType: ${n.termType}`)}}let Quad$2=class extends Term$1{constructor(e,t,r,i){super(""),this._subject=e,this._predicate=t,this._object=r,this._graph=i||DEFAULTGRAPH$3}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$1(n){return new NamedNode$2(n)}function blankNode$1(n){return new BlankNode$2(n||`n3-${_blankNodeCounter$1++}`)}function literal$1(n,e){if(typeof e=="string")return new Literal$2(`"${n}"@${e.toLowerCase()}`);let t=e?e.value:"";return t===""&&(typeof n=="boolean"?t=xsd$4.boolean:typeof n=="number"&&(Number.isFinite(n)?t=Number.isInteger(n)?xsd$4.integer:xsd$4.double:(t=xsd$4.double,Number.isNaN(n)||(n=n>0?"INF":"-INF")))),t===""||t===xsd$4.string?new Literal$2(`"${n}"`):new Literal$2(`"${n}"^^${t}`)}function variable$1(n){return new Variable$2(n)}function defaultGraph$1(){return DEFAULTGRAPH$3}function quad$1(n,e,t,r){return new Quad$2(n,e,t,r)}function fromTerm$1(n){if(n instanceof Term$1)return n;switch(n.termType){case"NamedNode":return namedNode$1(n.value);case"BlankNode":return blankNode$1(n.value);case"Variable":return variable$1(n.value);case"DefaultGraph":return DEFAULTGRAPH$3;case"Literal":return literal$1(n.value,n.language||n.datatype);case"Quad":return fromQuad$1(n);default:throw new Error(`Unexpected termType: ${n.termType}`)}}function fromQuad$1(n){if(n instanceof Quad$2)return n;if(n.termType!=="Quad")throw new Error(`Unexpected termType: ${n.termType}`);return quad$1(fromTerm$1(n.subject),fromTerm$1(n.predicate),fromTerm$1(n.object),fromTerm$1(n.graph))}let blankNodePrefix$1=0,N3Parser$1=class{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&initDataFactory$1(this,e.factory);const t=typeof e.format=="string"?e.format.match(/\w*$/)[0].toLowerCase():"",r=/turtle/.test(t),i=/trig/.test(t),s=/triple/.test(t),o=/quad/.test(t),a=this._n3Mode=/n3/.test(t),u=s||o;(this._supportsNamedGraphs=!(r||a))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||i||s||a),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=t===""||/star|\*$/.test(t),u&&(this._resolveRelativeIRI=c=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new N3Lexer$1({lineMode:u,n3:a,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){blankNodePrefix$1=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,r,i,s){const o=this._n3Mode;this._contextStack.push({type:e,subject:r,predicate:i,object:s,graph:t,inverse:o?this._inversePredicate:!1,blankPrefix:o?this._prefixes._:"",quantified:o?this._quantified:null}),o&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const r=this._contextStack.pop();if(!r||r.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=r.subject,this._predicate=r.predicate,this._object=r.object,this._graph=r.graph,this._n3Mode&&(this._inversePredicate=r.inverse,this._prefixes._=r.blankPrefix,this._quantified=r.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 r;switch(e.type){case"IRI":case"typeIRI":const i=this._resolveIRI(e.value);if(i===null)return this._error("Invalid IRI",e);r=this._factory.namedNode(i);break;case"type":case"prefixed":const s=this._prefixes[e.prefix];if(s===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);r=this._factory.namedNode(s+e.value);break;case"blank":r=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":r=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&r.id in this._quantified&&(r=this._quantified[r.id]),r}_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,r=null,i=this._readListItem;const s=this._subject,o=this._contextStack,a=o[o.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),i=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),o.length!==0&&o[o.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(i=this._readPredicate,this._subject===this.RDF_NIL)return i}else if(i=this._getContextEndReader(),this._object===this.RDF_NIL)return i;r=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,i=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),i=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(r===null&&(this._subject=r=this._factory.blankNode()),s===null?a.predicate===null?a.subject=r:a.object=r:this._emit(s,this.RDF_REST,r,this._graph),t!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,r,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(r,this.RDF_FIRST,t,this._graph)}return i}_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 r=this._readEntity(e);if(r===void 0)return;t=this._factory.literal(this._literalValue,r),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 r=this._completeLiteral(e);if(r)return this._object=r.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),r.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(r.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,r=this._graph;const i=this._subject,s=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,s&&(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 o=this._predicate,a=this._object;this._subject=this._factory.quad(i,o,a,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&&(r=this._readEntity(e))!==void 0){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(i!==null){const o=this._predicate,a=this._object;s?this._emit(a,o,i,r):this._emit(i,o,a,r)}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,r=t.length&&t[t.length-1];if(r&&r.type==="item"){const i=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,i,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,r;const i=this._factory.blankNode();if((r=this._readEntity(e))!==void 0)return this._predicate===null?(t=this._subject,this._subject=i):(t=this._object,this._object=i),this._emit(t,r,i,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let r,i;if((r=this._readEntity(e))!==void 0)return this._predicate===null?(i=this._subject,this._subject=t):(i=this._object,this._object=t),this._emit(t,r,i,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,r,i){this._callback(null,this._factory.quad(e,t,r,i||this.DEFAULTGRAPH))}_error(e,t){const r=new Error(`${e} on line ${t.line}.`);r.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(r),this._callback=noop$1}_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 r="",i=-1,s=-1,o=0,a="/";for(;i<t;){switch(a){case":":if(s<0&&e[++i]==="/"&&e[++i]==="/")for(;(s=i+1)<t&&e[s]!=="/";)i=s;break;case"?":case"#":i=t;break;case"/":if(e[i+1]===".")switch(a=e[++i+1],a){case"/":r+=e.substring(o,i-1),o=i+1;break;case void 0:case"?":case"#":return r+e.substring(o,i)+e.substr(i+1);case".":if(a=e[++i+1],a===void 0||a==="/"||a==="?"||a==="#"){if(r+=e.substring(o,i-2),(o=r.lastIndexOf("/"))>=s&&(r=r.substr(0,o)),a!=="/")return`${r}/${e.substr(i+1)}`;o=i+1}}}a=e[++i]}return r+e.substring(o)}parse(e,t,r){let i,s,o;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(i=t.onQuad,s=t.onPrefix,o=t.onComment):(i=t,s=r),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix$1++}_`,this._prefixCallback=s||noop$1,this._inversePredicate=!1,this._quantified=Object.create(null),!i){const u=[];let c;if(this._callback=(l,d)=>{l?c=l:d&&u.push(d)},this._lexer.tokenize(e).every(l=>this._readCallback=this._readCallback(l)),c)throw c;return u}let a=(u,c)=>{u!==null?(this._callback(u),this._callback=noop$1):this._readCallback&&(this._readCallback=this._readCallback(c))};o&&(this._lexer.comments=!0,a=(u,c)=>{u!==null?(this._callback(u),this._callback=noop$1):this._readCallback&&(c.type==="comment"?o(c.value):this._readCallback=this._readCallback(c))}),this._callback=i,this._lexer.tokenize(e,a)}};function noop$1(){}function initDataFactory$1(n,e){n._factory=e,n.DEFAULTGRAPH=e.defaultGraph(),n.RDF_FIRST=e.namedNode(namespaces$2.rdf.first),n.RDF_REST=e.namedNode(namespaces$2.rdf.rest),n.RDF_NIL=e.namedNode(namespaces$2.rdf.nil),n.N3_FORALL=e.namedNode(namespaces$2.r.forAll),n.N3_FORSOME=e.namedNode(namespaces$2.r.forSome),n.ABBREVIATIONS={a:e.namedNode(namespaces$2.rdf.type),"=":e.namedNode(namespaces$2.owl.sameAs),">":e.namedNode(namespaces$2.log.implies),"<":e.namedNode(namespaces$2.log.isImpliedBy)},n.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}initDataFactory$1(N3Parser$1.prototype,DataFactory$2);function isDefaultGraph$1(n){return!!n&&n.termType==="DefaultGraph"}function escapeRegex$2(n){return n.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}const BASE_UNSUPPORTED$1=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i,SUFFIX_SUPPORTED$1=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/,CURRENT$1="./",PARENT$1="../",QUERY$1="?",FRAGMENT$1="#";let BaseIRI$1=class $n{constructor(e){this.base=e,this._baseLength=0,this._baseMatcher=null,this._pathReplacements=new Array(e.length+1)}static supports(e){return!BASE_UNSUPPORTED$1.test(e)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!$n.supports(this.base))return this._baseMatcher=/.^/;const e=/^[^:]*:\/*/.exec(this.base)[0],t=["^",escapeRegex$2(e)],r=[],i=[],s=/[^/?#]*([/?#])/y;let o,a=0,u=0,c=s.lastIndex=e.length;for(;!a&&!u&&(o=s.exec(this.base));)o[1]===FRAGMENT$1?u=s.lastIndex-1:(t.push(escapeRegex$2(o[0]),"(?:"),r.push(")?"),o[1]!==QUERY$1?i.push(c=s.lastIndex):(a=c=s.lastIndex,u=this.base.indexOf(FRAGMENT$1,a),this._pathReplacements[a]=QUERY$1));for(let l=0;l<i.length;l++)this._pathReplacements[i[l]]=PARENT$1.repeat(i.length-l-1);return this._pathReplacements[i[i.length-1]]=CURRENT$1,this._baseLength=u>0?u:this.base.length,t.push(escapeRegex$2(this.base.substring(c,this._baseLength)),a?"(?:#|$)":"(?:[?#]|$)"),this._baseMatcher=new RegExp([...t,...r].join(""))}toRelative(e){const t=this._getBaseMatcher().exec(e);if(!t)return e;const r=t[0].length;if(r===this._baseLength&&r===e.length)return"";const i=this._pathReplacements[r];if(i){const s=e.substring(r);return i!==QUERY$1&&!SUFFIX_SUPPORTED$1.test(s)?e:i===CURRENT$1&&/^[^?#]/.test(s)?s:i+s}return e.substring(r-1)}};const DEFAULTGRAPH$2=DataFactory$2.defaultGraph(),{rdf:rdf$3,xsd:xsd$3}=namespaces$2,escape$2=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,escapeAll$1=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,escapedCharacters$1={"\\":"\\\\",'"':'\\"'," ":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};let SerializedTerm$1=class extends Term$1{equals(e){return e===this}},N3Writer$1=class{constructor(e,t){if(this._prefixRegex=/$0^/,e&&typeof e.write!="function"&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=t.end===void 0?!0:!!t.end;else{let r="";this._outputStream={write(i,s,o){r+=i,o&&o()},end:i=>{i&&i(null,r)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine):(this._lineMode=!1,this._graph=DEFAULTGRAPH$2,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseIri=new BaseIRI$1(t.baseIRI)))}get _inDefaultGraph(){return DEFAULTGRAPH$2.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_writeQuad(e,t,r,i,s){try{i.equals(this._graph)||(this._write((this._subject===null?"":this._inDefaultGraph?`.
|
|
9
|
+
`:`
|
|
10
|
+
}
|
|
11
|
+
`)+(DEFAULTGRAPH$2.equals(i)?"":`${this._encodeIriOrBlank(i)} {
|
|
12
|
+
`)),this._graph=i,this._subject=null),e.equals(this._subject)?t.equals(this._predicate)?this._write(`, ${this._encodeObject(r)}`,s):this._write(`;
|
|
13
|
+
${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,s):this._write(`${(this._subject===null?"":`.
|
|
14
|
+
`)+this._encodeSubject(this._subject=e)} ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,s)}catch(o){s&&s(o)}}_writeQuadLine(e,t,r,i,s){delete this._prefixMatch,this._write(this.quadToString(e,t,r,i),s)}quadToString(e,t,r,i){return`${this._encodeSubject(e)} ${this._encodeIriOrBlank(t)} ${this._encodeObject(r)}${i&&i.value?` ${this._encodeIriOrBlank(i)} .
|
|
15
|
+
`:` .
|
|
16
|
+
`}`}quadsToString(e){let t="";for(const r of e)t+=this.quadToString(r.subject,r.predicate,r.object,r.graph);return t}_encodeSubject(e){return e.termType==="Quad"?this._encodeQuad(e):this._encodeIriOrBlank(e)}_encodeIriOrBlank(e){if(e.termType!=="NamedNode")return this._lists&&e.value in this._lists&&(e=this.list(this._lists[e.value])),"id"in e?e.id:`_:${e.value}`;let t=e.value;this._baseIri&&(t=this._baseIri.toRelative(t)),escape$2.test(t)&&(t=t.replace(escapeAll$1,characterReplacer$1));const r=this._prefixRegex.exec(t);return r?r[1]?this._prefixIRIs[r[1]]+r[2]:t:`<${t}>`}_encodeLiteral(e){let t=e.value;if(escape$2.test(t)&&(t=t.replace(escapeAll$1,characterReplacer$1)),e.language)return`"${t}"@${e.language}`;if(this._lineMode){if(e.datatype.value===xsd$3.string)return`"${t}"`}else switch(e.datatype.value){case xsd$3.string:return`"${t}"`;case xsd$3.boolean:if(t==="true"||t==="false")return t;break;case xsd$3.integer:if(/^[+-]?\d+$/.test(t))return t;break;case xsd$3.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case xsd$3.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t;break}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){return e.value===rdf$3.type?"a":this._encodeIriOrBlank(e)}_encodeObject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeQuad({subject:e,predicate:t,object:r,graph:i}){return`<<${this._encodeSubject(e)} ${this._encodePredicate(t)} ${this._encodeObject(r)}${isDefaultGraph$1(i)?"":` ${this._encodeIriOrBlank(i)}`}>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(e,t,r,i,s){r===void 0?this._writeQuad(e.subject,e.predicate,e.object,e.graph,t):typeof i=="function"?this._writeQuad(e,t,r,DEFAULTGRAPH$2,i):this._writeQuad(e,t,r,i||DEFAULTGRAPH$2,s)}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}addPrefix(e,t,r){const i={};i[e]=t,this.addPrefixes(i,r)}addPrefixes(e,t){if(!this._prefixIRIs)return t&&t();let r=!1;for(let i in e){let s=e[i];typeof s!="string"&&(s=s.value),r=!0,this._subject!==null&&(this._write(this._inDefaultGraph?`.
|
|
17
|
+
`:`
|
|
18
|
+
}
|
|
19
|
+
`),this._subject=null,this._graph=""),this._prefixIRIs[s]=i+=":",this._write(`@prefix ${i} <${s}>.
|
|
20
|
+
`)}if(r){let i="",s="";for(const o in this._prefixIRIs)i+=i?`|${o}`:o,s+=(s?"|":"")+this._prefixIRIs[o];i=escapeRegex$2(i),this._prefixRegex=new RegExp(`^(?:${s})[^/]*$|^(${i})([_a-zA-Z0-9][\\-_a-zA-Z0-9]*)$`)}this._write(r?`
|
|
21
|
+
`:"",t)}blank(e,t){let r=e,i,s;switch(e===void 0?r=[]:e.termType?r=[{predicate:e,object:t}]:"length"in e||(r=[e]),s=r.length){case 0:return new SerializedTerm$1("[]");case 1:if(i=r[0],!(i.object instanceof SerializedTerm$1))return new SerializedTerm$1(`[ ${this._encodePredicate(i.predicate)} ${this._encodeObject(i.object)} ]`);default:let o="[";for(let a=0;a<s;a++)i=r[a],i.predicate.equals(e)?o+=`, ${this._encodeObject(i.object)}`:(o+=`${(a?`;
|
|
22
|
+
`:`
|
|
23
|
+
`)+this._encodePredicate(i.predicate)} ${this._encodeObject(i.object)}`,e=i.predicate);return new SerializedTerm$1(`${o}
|
|
24
|
+
]`)}}list(e){const t=e&&e.length||0,r=new Array(t);for(let i=0;i<t;i++)r[i]=this._encodeObject(e[i]);return new SerializedTerm$1(`(${r.join(" ")})`)}end(e){this._subject!==null&&(this._write(this._inDefaultGraph?`.
|
|
25
|
+
`:`
|
|
26
|
+
}
|
|
27
|
+
`),this._subject=null),this._write=this._blockedWrite;let t=e&&((r,i)=>{t=null,e(r,i)});if(this._endStream)try{return this._outputStream.end(t)}catch{}t&&t()}};function characterReplacer$1(n){let e=escapedCharacters$1[n];return e===void 0&&(n.length===1?(e=n.charCodeAt(0).toString(16),e="\\u0000".substr(0,6-e.length)+e):(e=((n.charCodeAt(0)-55296)*1024+n.charCodeAt(1)+9216).toString(16),e="\\U00000000".substr(0,10-e.length)+e)),e}var browser$3={exports:{}},stream$1={exports:{}},primordials$1,hasRequiredPrimordials$1;function requirePrimordials$1(){if(hasRequiredPrimordials$1)return primordials$1;hasRequiredPrimordials$1=1;class n extends Error{constructor(t){if(!Array.isArray(t))throw new TypeError(`Expected input to be an Array, got ${typeof t}`);let r="";for(let i=0;i<t.length;i++)r+=` ${t[i].stack}
|
|
28
|
+
`;super(r),this.name="AggregateError",this.errors=t}}return primordials$1={AggregateError:n,ArrayIsArray(e){return Array.isArray(e)},ArrayPrototypeIncludes(e,t){return e.includes(t)},ArrayPrototypeIndexOf(e,t){return e.indexOf(t)},ArrayPrototypeJoin(e,t){return e.join(t)},ArrayPrototypeMap(e,t){return e.map(t)},ArrayPrototypePop(e,t){return e.pop(t)},ArrayPrototypePush(e,t){return e.push(t)},ArrayPrototypeSlice(e,t,r){return e.slice(t,r)},Error,FunctionPrototypeCall(e,t,...r){return e.call(t,...r)},FunctionPrototypeSymbolHasInstance(e,t){return Function.prototype[Symbol.hasInstance].call(e,t)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(e,t){return Object.defineProperties(e,t)},ObjectDefineProperty(e,t,r){return Object.defineProperty(e,t,r)},ObjectGetOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)},ObjectKeys(e){return Object.keys(e)},ObjectSetPrototypeOf(e,t){return Object.setPrototypeOf(e,t)},Promise,PromisePrototypeCatch(e,t){return e.catch(t)},PromisePrototypeThen(e,t,r){return e.then(t,r)},PromiseReject(e){return Promise.reject(e)},PromiseResolve(e){return Promise.resolve(e)},ReflectApply:Reflect.apply,RegExpPrototypeTest(e,t){return e.test(t)},SafeSet:Set,String,StringPrototypeSlice(e,t,r){return e.slice(t,r)},StringPrototypeToLowerCase(e){return e.toLowerCase()},StringPrototypeToUpperCase(e){return e.toUpperCase()},StringPrototypeTrim(e){return e.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(e,t,r){return e.set(t,r)},Boolean,Uint8Array},primordials$1}var util$2={exports:{}},inspect$1,hasRequiredInspect$1;function requireInspect$1(){return hasRequiredInspect$1||(hasRequiredInspect$1=1,inspect$1={format(n,...e){return n.replace(/%([sdifj])/g,function(...[t,r]){const i=e.shift();return r==="f"?i.toFixed(6):r==="j"?JSON.stringify(i):r==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(n){switch(typeof n){case"string":if(n.includes("'"))if(n.includes('"')){if(!n.includes("`")&&!n.includes("${"))return`\`${n}\``}else return`"${n}"`;return`'${n}'`;case"number":return isNaN(n)?"NaN":Object.is(n,-0)?String(n):n;case"bigint":return`${String(n)}n`;case"boolean":case"undefined":return String(n);case"object":return"{}"}}}),inspect$1}var errors$1,hasRequiredErrors$1;function requireErrors$1(){if(hasRequiredErrors$1)return errors$1;hasRequiredErrors$1=1;const{format:n,inspect:e}=requireInspect$1(),{AggregateError:t}=requirePrimordials$1(),r=globalThis.AggregateError||t,i=Symbol("kIsNodeError"),s=["string","function","number","object","Function","Object","boolean","bigint","symbol"],o=/^([A-Z][a-z0-9]*)+$/,a="__node_internal_",u={};function c(S,w){if(!S)throw new u.ERR_INTERNAL_ASSERTION(w)}function l(S){let w="",v=S.length;const _=S[0]==="-"?1:0;for(;v>=_+4;v-=3)w=`_${S.slice(v-3,v)}${w}`;return`${S.slice(0,v)}${w}`}function d(S,w,v){if(typeof w=="function")return c(w.length<=v.length,`Code: ${S}; The provided arguments length (${v.length}) does not match the required ones (${w.length}).`),w(...v);const _=(w.match(/%[dfijoOs]/g)||[]).length;return c(_===v.length,`Code: ${S}; The provided arguments length (${v.length}) does not match the required ones (${_}).`),v.length===0?w:n(w,...v)}function f(S,w,v){v||(v=Error);class _ extends v{constructor(...C){super(d(S,w,C))}toString(){return`${this.name} [${S}]: ${this.message}`}}Object.defineProperties(_.prototype,{name:{value:v.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${S}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),_.prototype.code=S,_.prototype[i]=!0,u[S]=_}function m(S){const w=a+S.name;return Object.defineProperty(S,"name",{value:w}),S}function g(S,w){if(S&&w&&S!==w){if(Array.isArray(w.errors))return w.errors.push(S),w;const v=new r([w,S],w.message);return v.code=w.code,v}return S||w}class b extends Error{constructor(w="The operation was aborted",v=void 0){if(v!==void 0&&typeof v!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",v);super(w,v),this.code="ABORT_ERR",this.name="AbortError"}}return f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(S,w,v)=>{c(typeof S=="string","'name' must be a string"),Array.isArray(w)||(w=[w]);let _="The ";S.endsWith(" argument")?_+=`${S} `:_+=`"${S}" ${S.includes(".")?"property":"argument"} `,_+="must be ";const T=[],C=[],U=[];for(const W of w)c(typeof W=="string","All expected entries have to be of type string"),s.includes(W)?T.push(W.toLowerCase()):o.test(W)?C.push(W):(c(W!=="object",'The value "object" should be written as "Object"'),U.push(W));if(C.length>0){const W=T.indexOf("object");W!==-1&&(T.splice(T,W,1),C.push("Object"))}if(T.length>0){switch(T.length){case 1:_+=`of type ${T[0]}`;break;case 2:_+=`one of type ${T[0]} or ${T[1]}`;break;default:{const W=T.pop();_+=`one of type ${T.join(", ")}, or ${W}`}}(C.length>0||U.length>0)&&(_+=" or ")}if(C.length>0){switch(C.length){case 1:_+=`an instance of ${C[0]}`;break;case 2:_+=`an instance of ${C[0]} or ${C[1]}`;break;default:{const W=C.pop();_+=`an instance of ${C.join(", ")}, or ${W}`}}U.length>0&&(_+=" or ")}switch(U.length){case 0:break;case 1:U[0].toLowerCase()!==U[0]&&(_+="an "),_+=`${U[0]}`;break;case 2:_+=`one of ${U[0]} or ${U[1]}`;break;default:{const W=U.pop();_+=`one of ${U.join(", ")}, or ${W}`}}if(v==null)_+=`. Received ${v}`;else if(typeof v=="function"&&v.name)_+=`. Received function ${v.name}`;else if(typeof v=="object"){var $;if(($=v.constructor)!==null&&$!==void 0&&$.name)_+=`. Received an instance of ${v.constructor.name}`;else{const W=e(v,{depth:-1});_+=`. Received ${W}`}}else{let W=e(v,{colors:!1});W.length>25&&(W=`${W.slice(0,25)}...`),_+=`. Received type ${typeof v} (${W})`}return _},TypeError),f("ERR_INVALID_ARG_VALUE",(S,w,v="is invalid")=>{let _=e(w);return _.length>128&&(_=_.slice(0,128)+"..."),`The ${S.includes(".")?"property":"argument"} '${S}' ${v}. Received ${_}`},TypeError),f("ERR_INVALID_RETURN_VALUE",(S,w,v)=>{var _;const T=v!=null&&(_=v.constructor)!==null&&_!==void 0&&_.name?`instance of ${v.constructor.name}`:`type ${typeof v}`;return`Expected ${S} to be returned from the "${w}" function but got ${T}.`},TypeError),f("ERR_MISSING_ARGS",(...S)=>{c(S.length>0,"At least one arg needs to be specified");let w;const v=S.length;switch(S=(Array.isArray(S)?S:[S]).map(_=>`"${_}"`).join(" or "),v){case 1:w+=`The ${S[0]} argument`;break;case 2:w+=`The ${S[0]} and ${S[1]} arguments`;break;default:{const _=S.pop();w+=`The ${S.join(", ")}, and ${_} arguments`}break}return`${w} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(S,w,v)=>{c(w,'Missing "range" argument');let _;if(Number.isInteger(v)&&Math.abs(v)>2**32)_=l(String(v));else if(typeof v=="bigint"){_=String(v);const T=BigInt(2)**BigInt(32);(v>T||v<-T)&&(_=l(_)),_+="n"}else _=e(v);return`The value of "${S}" is out of range. It must be ${w}. Received ${_}`},RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),errors$1={AbortError:b,aggregateTwoErrors:m(g),hideStackFrames:m,codes:u},errors$1}var browser$2={exports:{}},hasRequiredBrowser$3;function requireBrowser$3(){if(hasRequiredBrowser$3)return browser$2.exports;hasRequiredBrowser$3=1;const{AbortController:n,AbortSignal:e}=typeof self<"u"?self:typeof window<"u"?window:void 0;return browser$2.exports=n,browser$2.exports.AbortSignal=e,browser$2.exports.default=n,browser$2.exports}var events={exports:{}},hasRequiredEvents;function requireEvents(){if(hasRequiredEvents)return events.exports;hasRequiredEvents=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(C,U,$){return Function.prototype.apply.call(C,U,$)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(C){return Object.getOwnPropertyNames(C).concat(Object.getOwnPropertySymbols(C))}:t=function(C){return Object.getOwnPropertyNames(C)};function r(T){console&&console.warn&&console.warn(T)}var i=Number.isNaN||function(C){return C!==C};function s(){s.init.call(this)}events.exports=s,events.exports.once=w,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(T){if(typeof T!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof T)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(T){if(typeof T!="number"||T<0||i(T))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+T+".");o=T}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(C){if(typeof C!="number"||C<0||i(C))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+C+".");return this._maxListeners=C,this};function u(T){return T._maxListeners===void 0?s.defaultMaxListeners:T._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(C){for(var U=[],$=1;$<arguments.length;$++)U.push(arguments[$]);var W=C==="error",re=this._events;if(re!==void 0)W=W&&re.error===void 0;else if(!W)return!1;if(W){var D;if(U.length>0&&(D=U[0]),D instanceof Error)throw D;var V=new Error("Unhandled error."+(D?" ("+D.message+")":""));throw V.context=D,V}var he=re[C];if(he===void 0)return!1;if(typeof he=="function")e(he,this,U);else for(var z=he.length,_e=g(he,z),$=0;$<z;++$)e(_e[$],this,U);return!0};function c(T,C,U,$){var W,re,D;if(a(U),re=T._events,re===void 0?(re=T._events=Object.create(null),T._eventsCount=0):(re.newListener!==void 0&&(T.emit("newListener",C,U.listener?U.listener:U),re=T._events),D=re[C]),D===void 0)D=re[C]=U,++T._eventsCount;else if(typeof D=="function"?D=re[C]=$?[U,D]:[D,U]:$?D.unshift(U):D.push(U),W=u(T),W>0&&D.length>W&&!D.warned){D.warned=!0;var V=new Error("Possible EventEmitter memory leak detected. "+D.length+" "+String(C)+" listeners added. Use emitter.setMaxListeners() to increase limit");V.name="MaxListenersExceededWarning",V.emitter=T,V.type=C,V.count=D.length,r(V)}return T}s.prototype.addListener=function(C,U){return c(this,C,U,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(C,U){return c(this,C,U,!0)};function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(T,C,U){var $={fired:!1,wrapFn:void 0,target:T,type:C,listener:U},W=l.bind($);return W.listener=U,$.wrapFn=W,W}s.prototype.once=function(C,U){return a(U),this.on(C,d(this,C,U)),this},s.prototype.prependOnceListener=function(C,U){return a(U),this.prependListener(C,d(this,C,U)),this},s.prototype.removeListener=function(C,U){var $,W,re,D,V;if(a(U),W=this._events,W===void 0)return this;if($=W[C],$===void 0)return this;if($===U||$.listener===U)--this._eventsCount===0?this._events=Object.create(null):(delete W[C],W.removeListener&&this.emit("removeListener",C,$.listener||U));else if(typeof $!="function"){for(re=-1,D=$.length-1;D>=0;D--)if($[D]===U||$[D].listener===U){V=$[D].listener,re=D;break}if(re<0)return this;re===0?$.shift():b($,re),$.length===1&&(W[C]=$[0]),W.removeListener!==void 0&&this.emit("removeListener",C,V||U)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(C){var U,$,W;if($=this._events,$===void 0)return this;if($.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):$[C]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete $[C]),this;if(arguments.length===0){var re=Object.keys($),D;for(W=0;W<re.length;++W)D=re[W],D!=="removeListener"&&this.removeAllListeners(D);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(U=$[C],typeof U=="function")this.removeListener(C,U);else if(U!==void 0)for(W=U.length-1;W>=0;W--)this.removeListener(C,U[W]);return this};function f(T,C,U){var $=T._events;if($===void 0)return[];var W=$[C];return W===void 0?[]:typeof W=="function"?U?[W.listener||W]:[W]:U?S(W):g(W,W.length)}s.prototype.listeners=function(C){return f(this,C,!0)},s.prototype.rawListeners=function(C){return f(this,C,!1)},s.listenerCount=function(T,C){return typeof T.listenerCount=="function"?T.listenerCount(C):m.call(T,C)},s.prototype.listenerCount=m;function m(T){var C=this._events;if(C!==void 0){var U=C[T];if(typeof U=="function")return 1;if(U!==void 0)return U.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(T,C){for(var U=new Array(C),$=0;$<C;++$)U[$]=T[$];return U}function b(T,C){for(;C+1<T.length;C++)T[C]=T[C+1];T.pop()}function S(T){for(var C=new Array(T.length),U=0;U<C.length;++U)C[U]=T[U].listener||T[U];return C}function w(T,C){return new Promise(function(U,$){function W(D){T.removeListener(C,re),$(D)}function re(){typeof T.removeListener=="function"&&T.removeListener("error",W),U([].slice.call(arguments))}_(T,C,re,{once:!0}),C!=="error"&&v(T,W,{once:!0})})}function v(T,C,U){typeof T.on=="function"&&_(T,"error",C,U)}function _(T,C,U,$){if(typeof T.on=="function")$.once?T.once(C,U):T.on(C,U);else if(typeof T.addEventListener=="function")T.addEventListener(C,function W(re){$.once&&T.removeEventListener(C,W),U(re)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof T)}return events.exports}var hasRequiredUtil$1;function requireUtil$1(){return hasRequiredUtil$1||(hasRequiredUtil$1=1,(function(n){const e=requireBuffer(),{format:t,inspect:r}=requireInspect$1(),{codes:{ERR_INVALID_ARG_TYPE:i}}=requireErrors$1(),{kResistStopPropagation:s,AggregateError:o,SymbolDispose:a}=requirePrimordials$1(),u=globalThis.AbortSignal||requireBrowser$3().AbortSignal,c=globalThis.AbortController||requireBrowser$3().AbortController,l=Object.getPrototypeOf(async function(){}).constructor,d=globalThis.Blob||e.Blob,f=typeof d<"u"?function(S){return S instanceof d}:function(S){return!1},m=(b,S)=>{if(b!==void 0&&(b===null||typeof b!="object"||!("aborted"in b)))throw new i(S,"AbortSignal",b)},g=(b,S)=>{if(typeof b!="function")throw new i(S,"Function",b)};n.exports={AggregateError:o,kEmptyObject:Object.freeze({}),once(b){let S=!1;return function(...w){S||(S=!0,b.apply(this,w))}},createDeferredPromise:function(){let b,S;return{promise:new Promise((v,_)=>{b=v,S=_}),resolve:b,reject:S}},promisify(b){return new Promise((S,w)=>{b((v,..._)=>v?w(v):S(..._))})},debuglog(){return function(){}},format:t,inspect:r,types:{isAsyncFunction(b){return b instanceof l},isArrayBufferView(b){return ArrayBuffer.isView(b)}},isBlob:f,deprecate(b,S){return b},addAbortListener:requireEvents().addAbortListener||function(S,w){if(S===void 0)throw new i("signal","AbortSignal",S);m(S,"signal"),g(w,"listener");let v;return S.aborted?queueMicrotask(()=>w()):(S.addEventListener("abort",w,{__proto__:null,once:!0,[s]:!0}),v=()=>{S.removeEventListener("abort",w)}),{__proto__:null,[a](){var _;(_=v)===null||_===void 0||_()}}},AbortSignalAny:u.any||function(S){if(S.length===1)return S[0];const w=new c,v=()=>w.abort();return S.forEach(_=>{m(_,"signals"),_.addEventListener("abort",v,{once:!0})}),w.signal.addEventListener("abort",()=>{S.forEach(_=>_.removeEventListener("abort",v))},{once:!0}),w.signal}},n.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")})(util$2)),util$2.exports}var operators$1={},validators$1,hasRequiredValidators$1;function requireValidators$1(){if(hasRequiredValidators$1)return validators$1;hasRequiredValidators$1=1;const{ArrayIsArray:n,ArrayPrototypeIncludes:e,ArrayPrototypeJoin:t,ArrayPrototypeMap:r,NumberIsInteger:i,NumberIsNaN:s,NumberMAX_SAFE_INTEGER:o,NumberMIN_SAFE_INTEGER:a,NumberParseInt:u,ObjectPrototypeHasOwnProperty:c,RegExpPrototypeExec:l,String:d,StringPrototypeToUpperCase:f,StringPrototypeTrim:m}=requirePrimordials$1(),{hideStackFrames:g,codes:{ERR_SOCKET_BAD_PORT:b,ERR_INVALID_ARG_TYPE:S,ERR_INVALID_ARG_VALUE:w,ERR_OUT_OF_RANGE:v,ERR_UNKNOWN_SIGNAL:_}}=requireErrors$1(),{normalizeEncoding:T}=requireUtil$1(),{isAsyncFunction:C,isArrayBufferView:U}=requireUtil$1().types,$={};function W(M){return M===(M|0)}function re(M){return M===M>>>0}const D=/^[0-7]+$/,V="must be a 32-bit unsigned integer or an octal string";function he(M,ne,ge){if(typeof M>"u"&&(M=ge),typeof M=="string"){if(l(D,M)===null)throw new w(ne,M,V);M=u(M,8)}return Ce(M,ne),M}const z=g((M,ne,ge=a,Y=o)=>{if(typeof M!="number")throw new S(ne,"number",M);if(!i(M))throw new v(ne,"an integer",M);if(M<ge||M>Y)throw new v(ne,`>= ${ge} && <= ${Y}`,M)}),_e=g((M,ne,ge=-2147483648,Y=2147483647)=>{if(typeof M!="number")throw new S(ne,"number",M);if(!i(M))throw new v(ne,"an integer",M);if(M<ge||M>Y)throw new v(ne,`>= ${ge} && <= ${Y}`,M)}),Ce=g((M,ne,ge=!1)=>{if(typeof M!="number")throw new S(ne,"number",M);if(!i(M))throw new v(ne,"an integer",M);const Y=ge?1:0,Be=4294967295;if(M<Y||M>Be)throw new v(ne,`>= ${Y} && <= ${Be}`,M)});function Fe(M,ne){if(typeof M!="string")throw new S(ne,"string",M)}function ze(M,ne,ge=void 0,Y){if(typeof M!="number")throw new S(ne,"number",M);if(ge!=null&&M<ge||Y!=null&&M>Y||(ge!=null||Y!=null)&&s(M))throw new v(ne,`${ge!=null?`>= ${ge}`:""}${ge!=null&&Y!=null?" && ":""}${Y!=null?`<= ${Y}`:""}`,M)}const ae=g((M,ne,ge)=>{if(!e(ge,M)){const Be="must be one of: "+t(r(ge,Je=>typeof Je=="string"?`'${Je}'`:d(Je)),", ");throw new w(ne,M,Be)}});function ve(M,ne){if(typeof M!="boolean")throw new S(ne,"boolean",M)}function L(M,ne,ge){return M==null||!c(M,ne)?ge:M[ne]}const ie=g((M,ne,ge=null)=>{const Y=L(ge,"allowArray",!1),Be=L(ge,"allowFunction",!1);if(!L(ge,"nullable",!1)&&M===null||!Y&&n(M)||typeof M!="object"&&(!Be||typeof M!="function"))throw new S(ne,"Object",M)}),xe=g((M,ne)=>{if(M!=null&&typeof M!="object"&&typeof M!="function")throw new S(ne,"a dictionary",M)}),ue=g((M,ne,ge=0)=>{if(!n(M))throw new S(ne,"Array",M);if(M.length<ge){const Y=`must be longer than ${ge}`;throw new w(ne,M,Y)}});function De(M,ne){ue(M,ne);for(let ge=0;ge<M.length;ge++)Fe(M[ge],`${ne}[${ge}]`)}function ke(M,ne){ue(M,ne);for(let ge=0;ge<M.length;ge++)ve(M[ge],`${ne}[${ge}]`)}function We(M,ne){ue(M,ne);for(let ge=0;ge<M.length;ge++){const Y=M[ge],Be=`${ne}[${ge}]`;if(Y==null)throw new S(Be,"AbortSignal",Y);G(Y,Be)}}function Oe(M,ne="signal"){if(Fe(M,ne),$[M]===void 0)throw $[f(M)]!==void 0?new _(M+" (signals must use all capital letters)"):new _(M)}const te=g((M,ne="buffer")=>{if(!U(M))throw new S(ne,["Buffer","TypedArray","DataView"],M)});function le(M,ne){const ge=T(ne),Y=M.length;if(ge==="hex"&&Y%2!==0)throw new w("encoding",ne,`is invalid for data of length ${Y}`)}function Te(M,ne="Port",ge=!0){if(typeof M!="number"&&typeof M!="string"||typeof M=="string"&&m(M).length===0||+M!==+M>>>0||M>65535||M===0&&!ge)throw new b(ne,M,ge);return M|0}const G=g((M,ne)=>{if(M!==void 0&&(M===null||typeof M!="object"||!("aborted"in M)))throw new S(ne,"AbortSignal",M)}),P=g((M,ne)=>{if(typeof M!="function")throw new S(ne,"Function",M)}),x=g((M,ne)=>{if(typeof M!="function"||C(M))throw new S(ne,"Function",M)}),A=g((M,ne)=>{if(M!==void 0)throw new S(ne,"undefined",M)});function O(M,ne,ge){if(!e(ge,M))throw new S(ne,`('${t(ge,"|")}')`,M)}const H=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function Q(M,ne){if(typeof M>"u"||!l(H,M))throw new w(ne,M,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function de(M){if(typeof M=="string")return Q(M,"hints"),M;if(n(M)){const ne=M.length;let ge="";if(ne===0)return ge;for(let Y=0;Y<ne;Y++){const Be=M[Y];Q(Be,"hints"),ge+=Be,Y!==ne-1&&(ge+=", ")}return ge}throw new w("hints",M,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}return validators$1={isInt32:W,isUint32:re,parseFileMode:he,validateArray:ue,validateStringArray:De,validateBooleanArray:ke,validateAbortSignalArray:We,validateBoolean:ve,validateBuffer:te,validateDictionary:xe,validateEncoding:le,validateFunction:P,validateInt32:_e,validateInteger:z,validateNumber:ze,validateObject:ie,validateOneOf:ae,validatePlainFunction:x,validatePort:Te,validateSignalName:Oe,validateString:Fe,validateUint32:Ce,validateUndefined:A,validateUnion:O,validateAbortSignal:G,validateLinkHeaderValue:de},validators$1}var endOfStream$1={exports:{}},browser$1={exports:{}},hasRequiredBrowser$2;function requireBrowser$2(){if(hasRequiredBrowser$2)return browser$1.exports;hasRequiredBrowser$2=1;var n=browser$1.exports={},e,t;function r(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?e=setTimeout:e=r}catch{e=r}try{typeof clearTimeout=="function"?t=clearTimeout:t=i}catch{t=i}})();function s(b){if(e===setTimeout)return setTimeout(b,0);if((e===r||!e)&&setTimeout)return e=setTimeout,setTimeout(b,0);try{return e(b,0)}catch{try{return e.call(null,b,0)}catch{return e.call(this,b,0)}}}function o(b){if(t===clearTimeout)return clearTimeout(b);if((t===i||!t)&&clearTimeout)return t=clearTimeout,clearTimeout(b);try{return t(b)}catch{try{return t.call(null,b)}catch{return t.call(this,b)}}}var a=[],u=!1,c,l=-1;function d(){!u||!c||(u=!1,c.length?a=c.concat(a):l=-1,a.length&&f())}function f(){if(!u){var b=s(d);u=!0;for(var S=a.length;S;){for(c=a,a=[];++l<S;)c&&c[l].run();l=-1,S=a.length}c=null,u=!1,o(b)}}n.nextTick=function(b){var S=new Array(arguments.length-1);if(arguments.length>1)for(var w=1;w<arguments.length;w++)S[w-1]=arguments[w];a.push(new m(b,S)),a.length===1&&!u&&s(f)};function m(b,S){this.fun=b,this.array=S}m.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={};function g(){}return n.on=g,n.addListener=g,n.once=g,n.off=g,n.removeListener=g,n.removeAllListeners=g,n.emit=g,n.prependListener=g,n.prependOnceListener=g,n.listeners=function(b){return[]},n.binding=function(b){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(b){throw new Error("process.chdir is not supported")},n.umask=function(){return 0},browser$1.exports}var utils$1,hasRequiredUtils$1;function requireUtils$1(){if(hasRequiredUtils$1)return utils$1;hasRequiredUtils$1=1;const{SymbolAsyncIterator:n,SymbolIterator:e,SymbolFor:t}=requirePrimordials$1(),r=t("nodejs.stream.destroyed"),i=t("nodejs.stream.errored"),s=t("nodejs.stream.readable"),o=t("nodejs.stream.writable"),a=t("nodejs.stream.disturbed"),u=t("nodejs.webstream.isClosedPromise"),c=t("nodejs.webstream.controllerErrorFunction");function l(L,ie=!1){var xe;return!!(L&&typeof L.pipe=="function"&&typeof L.on=="function"&&(!ie||typeof L.pause=="function"&&typeof L.resume=="function")&&(!L._writableState||((xe=L._readableState)===null||xe===void 0?void 0:xe.readable)!==!1)&&(!L._writableState||L._readableState))}function d(L){var ie;return!!(L&&typeof L.write=="function"&&typeof L.on=="function"&&(!L._readableState||((ie=L._writableState)===null||ie===void 0?void 0:ie.writable)!==!1))}function f(L){return!!(L&&typeof L.pipe=="function"&&L._readableState&&typeof L.on=="function"&&typeof L.write=="function")}function m(L){return L&&(L._readableState||L._writableState||typeof L.write=="function"&&typeof L.on=="function"||typeof L.pipe=="function"&&typeof L.on=="function")}function g(L){return!!(L&&!m(L)&&typeof L.pipeThrough=="function"&&typeof L.getReader=="function"&&typeof L.cancel=="function")}function b(L){return!!(L&&!m(L)&&typeof L.getWriter=="function"&&typeof L.abort=="function")}function S(L){return!!(L&&!m(L)&&typeof L.readable=="object"&&typeof L.writable=="object")}function w(L){return g(L)||b(L)||S(L)}function v(L,ie){return L==null?!1:ie===!0?typeof L[n]=="function":ie===!1?typeof L[e]=="function":typeof L[n]=="function"||typeof L[e]=="function"}function _(L){if(!m(L))return null;const ie=L._writableState,xe=L._readableState,ue=ie||xe;return!!(L.destroyed||L[r]||ue!=null&&ue.destroyed)}function T(L){if(!d(L))return null;if(L.writableEnded===!0)return!0;const ie=L._writableState;return ie!=null&&ie.errored?!1:typeof ie?.ended!="boolean"?null:ie.ended}function C(L,ie){if(!d(L))return null;if(L.writableFinished===!0)return!0;const xe=L._writableState;return xe!=null&&xe.errored?!1:typeof xe?.finished!="boolean"?null:!!(xe.finished||ie===!1&&xe.ended===!0&&xe.length===0)}function U(L){if(!l(L))return null;if(L.readableEnded===!0)return!0;const ie=L._readableState;return!ie||ie.errored?!1:typeof ie?.ended!="boolean"?null:ie.ended}function $(L,ie){if(!l(L))return null;const xe=L._readableState;return xe!=null&&xe.errored?!1:typeof xe?.endEmitted!="boolean"?null:!!(xe.endEmitted||ie===!1&&xe.ended===!0&&xe.length===0)}function W(L){return L&&L[s]!=null?L[s]:typeof L?.readable!="boolean"?null:_(L)?!1:l(L)&&L.readable&&!$(L)}function re(L){return L&&L[o]!=null?L[o]:typeof L?.writable!="boolean"?null:_(L)?!1:d(L)&&L.writable&&!T(L)}function D(L,ie){return m(L)?_(L)?!0:!(ie?.readable!==!1&&W(L)||ie?.writable!==!1&&re(L)):null}function V(L){var ie,xe;return m(L)?L.writableErrored?L.writableErrored:(ie=(xe=L._writableState)===null||xe===void 0?void 0:xe.errored)!==null&&ie!==void 0?ie:null:null}function he(L){var ie,xe;return m(L)?L.readableErrored?L.readableErrored:(ie=(xe=L._readableState)===null||xe===void 0?void 0:xe.errored)!==null&&ie!==void 0?ie:null:null}function z(L){if(!m(L))return null;if(typeof L.closed=="boolean")return L.closed;const ie=L._writableState,xe=L._readableState;return typeof ie?.closed=="boolean"||typeof xe?.closed=="boolean"?ie?.closed||xe?.closed:typeof L._closed=="boolean"&&_e(L)?L._closed:null}function _e(L){return typeof L._closed=="boolean"&&typeof L._defaultKeepAlive=="boolean"&&typeof L._removedConnection=="boolean"&&typeof L._removedContLen=="boolean"}function Ce(L){return typeof L._sent100=="boolean"&&_e(L)}function Fe(L){var ie;return typeof L._consuming=="boolean"&&typeof L._dumped=="boolean"&&((ie=L.req)===null||ie===void 0?void 0:ie.upgradeOrConnect)===void 0}function ze(L){if(!m(L))return null;const ie=L._writableState,xe=L._readableState,ue=ie||xe;return!ue&&Ce(L)||!!(ue&&ue.autoDestroy&&ue.emitClose&&ue.closed===!1)}function ae(L){var ie;return!!(L&&((ie=L[a])!==null&&ie!==void 0?ie:L.readableDidRead||L.readableAborted))}function ve(L){var ie,xe,ue,De,ke,We,Oe,te,le,Te;return!!(L&&((ie=(xe=(ue=(De=(ke=(We=L[i])!==null&&We!==void 0?We:L.readableErrored)!==null&&ke!==void 0?ke:L.writableErrored)!==null&&De!==void 0?De:(Oe=L._readableState)===null||Oe===void 0?void 0:Oe.errorEmitted)!==null&&ue!==void 0?ue:(te=L._writableState)===null||te===void 0?void 0:te.errorEmitted)!==null&&xe!==void 0?xe:(le=L._readableState)===null||le===void 0?void 0:le.errored)!==null&&ie!==void 0?ie:!((Te=L._writableState)===null||Te===void 0)&&Te.errored))}return utils$1={isDestroyed:_,kIsDestroyed:r,isDisturbed:ae,kIsDisturbed:a,isErrored:ve,kIsErrored:i,isReadable:W,kIsReadable:s,kIsClosedPromise:u,kControllerErrorFunction:c,kIsWritable:o,isClosed:z,isDuplexNodeStream:f,isFinished:D,isIterable:v,isReadableNodeStream:l,isReadableStream:g,isReadableEnded:U,isReadableFinished:$,isReadableErrored:he,isNodeStream:m,isWebStream:w,isWritable:re,isWritableNodeStream:d,isWritableStream:b,isWritableEnded:T,isWritableFinished:C,isWritableErrored:V,isServerRequest:Fe,isServerResponse:Ce,willEmitClose:ze,isTransformStream:S},utils$1}var hasRequiredEndOfStream$1;function requireEndOfStream$1(){if(hasRequiredEndOfStream$1)return endOfStream$1.exports;hasRequiredEndOfStream$1=1;const n=requireBrowser$2(),{AbortError:e,codes:t}=requireErrors$1(),{ERR_INVALID_ARG_TYPE:r,ERR_STREAM_PREMATURE_CLOSE:i}=t,{kEmptyObject:s,once:o}=requireUtil$1(),{validateAbortSignal:a,validateFunction:u,validateObject:c,validateBoolean:l}=requireValidators$1(),{Promise:d,PromisePrototypeThen:f,SymbolDispose:m}=requirePrimordials$1(),{isClosed:g,isReadable:b,isReadableNodeStream:S,isReadableStream:w,isReadableFinished:v,isReadableErrored:_,isWritable:T,isWritableNodeStream:C,isWritableStream:U,isWritableFinished:$,isWritableErrored:W,isNodeStream:re,willEmitClose:D,kIsClosedPromise:V}=requireUtils$1();let he;function z(ae){return ae.setHeader&&typeof ae.abort=="function"}const _e=()=>{};function Ce(ae,ve,L){var ie,xe;if(arguments.length===2?(L=ve,ve=s):ve==null?ve=s:c(ve,"options"),u(L,"callback"),a(ve.signal,"options.signal"),L=o(L),w(ae)||U(ae))return Fe(ae,ve,L);if(!re(ae))throw new r("stream",["ReadableStream","WritableStream","Stream"],ae);const ue=(ie=ve.readable)!==null&&ie!==void 0?ie:S(ae),De=(xe=ve.writable)!==null&&xe!==void 0?xe:C(ae),ke=ae._writableState,We=ae._readableState,Oe=()=>{ae.writable||Te()};let te=D(ae)&&S(ae)===ue&&C(ae)===De,le=$(ae,!1);const Te=()=>{le=!0,ae.destroyed&&(te=!1),!(te&&(!ae.readable||ue))&&(!ue||G)&&L.call(ae)};let G=v(ae,!1);const P=()=>{G=!0,ae.destroyed&&(te=!1),!(te&&(!ae.writable||De))&&(!De||le)&&L.call(ae)},x=M=>{L.call(ae,M)};let A=g(ae);const O=()=>{A=!0;const M=W(ae)||_(ae);if(M&&typeof M!="boolean")return L.call(ae,M);if(ue&&!G&&S(ae,!0)&&!v(ae,!1))return L.call(ae,new i);if(De&&!le&&!$(ae,!1))return L.call(ae,new i);L.call(ae)},H=()=>{A=!0;const M=W(ae)||_(ae);if(M&&typeof M!="boolean")return L.call(ae,M);L.call(ae)},Q=()=>{ae.req.on("finish",Te)};z(ae)?(ae.on("complete",Te),te||ae.on("abort",O),ae.req?Q():ae.on("request",Q)):De&&!ke&&(ae.on("end",Oe),ae.on("close",Oe)),!te&&typeof ae.aborted=="boolean"&&ae.on("aborted",O),ae.on("end",P),ae.on("finish",Te),ve.error!==!1&&ae.on("error",x),ae.on("close",O),A?n.nextTick(O):ke!=null&&ke.errorEmitted||We!=null&&We.errorEmitted?te||n.nextTick(H):(!ue&&(!te||b(ae))&&(le||T(ae)===!1)||!De&&(!te||T(ae))&&(G||b(ae)===!1)||We&&ae.req&&ae.aborted)&&n.nextTick(H);const de=()=>{L=_e,ae.removeListener("aborted",O),ae.removeListener("complete",Te),ae.removeListener("abort",O),ae.removeListener("request",Q),ae.req&&ae.req.removeListener("finish",Te),ae.removeListener("end",Oe),ae.removeListener("close",Oe),ae.removeListener("finish",Te),ae.removeListener("end",P),ae.removeListener("error",x),ae.removeListener("close",O)};if(ve.signal&&!A){const M=()=>{const ne=L;de(),ne.call(ae,new e(void 0,{cause:ve.signal.reason}))};if(ve.signal.aborted)n.nextTick(M);else{he=he||requireUtil$1().addAbortListener;const ne=he(ve.signal,M),ge=L;L=o((...Y)=>{ne[m](),ge.apply(ae,Y)})}}return de}function Fe(ae,ve,L){let ie=!1,xe=_e;if(ve.signal)if(xe=()=>{ie=!0,L.call(ae,new e(void 0,{cause:ve.signal.reason}))},ve.signal.aborted)n.nextTick(xe);else{he=he||requireUtil$1().addAbortListener;const De=he(ve.signal,xe),ke=L;L=o((...We)=>{De[m](),ke.apply(ae,We)})}const ue=(...De)=>{ie||n.nextTick(()=>L.apply(ae,De))};return f(ae[V].promise,ue,ue),_e}function ze(ae,ve){var L;let ie=!1;return ve===null&&(ve=s),(L=ve)!==null&&L!==void 0&&L.cleanup&&(l(ve.cleanup,"cleanup"),ie=ve.cleanup),new d((xe,ue)=>{const De=Ce(ae,ve,ke=>{ie&&De(),ke?ue(ke):xe()})})}return endOfStream$1.exports=Ce,endOfStream$1.exports.finished=ze,endOfStream$1.exports}var destroy_1$1,hasRequiredDestroy$1;function requireDestroy$1(){if(hasRequiredDestroy$1)return destroy_1$1;hasRequiredDestroy$1=1;const n=requireBrowser$2(),{aggregateTwoErrors:e,codes:{ERR_MULTIPLE_CALLBACK:t},AbortError:r}=requireErrors$1(),{Symbol:i}=requirePrimordials$1(),{kIsDestroyed:s,isDestroyed:o,isFinished:a,isServerRequest:u}=requireUtils$1(),c=i("kDestroy"),l=i("kConstruct");function d(D,V,he){D&&(D.stack,V&&!V.errored&&(V.errored=D),he&&!he.errored&&(he.errored=D))}function f(D,V){const he=this._readableState,z=this._writableState,_e=z||he;return z!=null&&z.destroyed||he!=null&&he.destroyed?(typeof V=="function"&&V(),this):(d(D,z,he),z&&(z.destroyed=!0),he&&(he.destroyed=!0),_e.constructed?m(this,D,V):this.once(c,function(Ce){m(this,e(Ce,D),V)}),this)}function m(D,V,he){let z=!1;function _e(Ce){if(z)return;z=!0;const Fe=D._readableState,ze=D._writableState;d(Ce,ze,Fe),ze&&(ze.closed=!0),Fe&&(Fe.closed=!0),typeof he=="function"&&he(Ce),Ce?n.nextTick(g,D,Ce):n.nextTick(b,D)}try{D._destroy(V||null,_e)}catch(Ce){_e(Ce)}}function g(D,V){S(D,V),b(D)}function b(D){const V=D._readableState,he=D._writableState;he&&(he.closeEmitted=!0),V&&(V.closeEmitted=!0),(he!=null&&he.emitClose||V!=null&&V.emitClose)&&D.emit("close")}function S(D,V){const he=D._readableState,z=D._writableState;z!=null&&z.errorEmitted||he!=null&&he.errorEmitted||(z&&(z.errorEmitted=!0),he&&(he.errorEmitted=!0),D.emit("error",V))}function w(){const D=this._readableState,V=this._writableState;D&&(D.constructed=!0,D.closed=!1,D.closeEmitted=!1,D.destroyed=!1,D.errored=null,D.errorEmitted=!1,D.reading=!1,D.ended=D.readable===!1,D.endEmitted=D.readable===!1),V&&(V.constructed=!0,V.destroyed=!1,V.closed=!1,V.closeEmitted=!1,V.errored=null,V.errorEmitted=!1,V.finalCalled=!1,V.prefinished=!1,V.ended=V.writable===!1,V.ending=V.writable===!1,V.finished=V.writable===!1)}function v(D,V,he){const z=D._readableState,_e=D._writableState;if(_e!=null&&_e.destroyed||z!=null&&z.destroyed)return this;z!=null&&z.autoDestroy||_e!=null&&_e.autoDestroy?D.destroy(V):V&&(V.stack,_e&&!_e.errored&&(_e.errored=V),z&&!z.errored&&(z.errored=V),he?n.nextTick(S,D,V):S(D,V))}function _(D,V){if(typeof D._construct!="function")return;const he=D._readableState,z=D._writableState;he&&(he.constructed=!1),z&&(z.constructed=!1),D.once(l,V),!(D.listenerCount(l)>1)&&n.nextTick(T,D)}function T(D){let V=!1;function he(z){if(V){v(D,z??new t);return}V=!0;const _e=D._readableState,Ce=D._writableState,Fe=Ce||_e;_e&&(_e.constructed=!0),Ce&&(Ce.constructed=!0),Fe.destroyed?D.emit(c,z):z?v(D,z,!0):n.nextTick(C,D)}try{D._construct(z=>{n.nextTick(he,z)})}catch(z){n.nextTick(he,z)}}function C(D){D.emit(l)}function U(D){return D?.setHeader&&typeof D.abort=="function"}function $(D){D.emit("close")}function W(D,V){D.emit("error",V),n.nextTick($,D)}function re(D,V){!D||o(D)||(!V&&!a(D)&&(V=new r),u(D)?(D.socket=null,D.destroy(V)):U(D)?D.abort():U(D.req)?D.req.abort():typeof D.destroy=="function"?D.destroy(V):typeof D.close=="function"?D.close():V?n.nextTick(W,D,V):n.nextTick($,D),D.destroyed||(D[s]=!0))}return destroy_1$1={construct:_,destroyer:re,destroy:f,undestroy:w,errorOrDestroy:v},destroy_1$1}var legacy$1,hasRequiredLegacy$1;function requireLegacy$1(){if(hasRequiredLegacy$1)return legacy$1;hasRequiredLegacy$1=1;const{ArrayIsArray:n,ObjectSetPrototypeOf:e}=requirePrimordials$1(),{EventEmitter:t}=requireEvents();function r(s){t.call(this,s)}e(r.prototype,t.prototype),e(r,t),r.prototype.pipe=function(s,o){const a=this;function u(b){s.writable&&s.write(b)===!1&&a.pause&&a.pause()}a.on("data",u);function c(){a.readable&&a.resume&&a.resume()}s.on("drain",c),!s._isStdio&&(!o||o.end!==!1)&&(a.on("end",d),a.on("close",f));let l=!1;function d(){l||(l=!0,s.end())}function f(){l||(l=!0,typeof s.destroy=="function"&&s.destroy())}function m(b){g(),t.listenerCount(this,"error")===0&&this.emit("error",b)}i(a,"error",m),i(s,"error",m);function g(){a.removeListener("data",u),s.removeListener("drain",c),a.removeListener("end",d),a.removeListener("close",f),a.removeListener("error",m),s.removeListener("error",m),a.removeListener("end",g),a.removeListener("close",g),s.removeListener("close",g)}return a.on("end",g),a.on("close",g),s.on("close",g),s.emit("pipe",a),s};function i(s,o,a){if(typeof s.prependListener=="function")return s.prependListener(o,a);!s._events||!s._events[o]?s.on(o,a):n(s._events[o])?s._events[o].unshift(a):s._events[o]=[a,s._events[o]]}return legacy$1={Stream:r,prependListener:i},legacy$1}var addAbortSignal$1={exports:{}},hasRequiredAddAbortSignal$1;function requireAddAbortSignal$1(){return hasRequiredAddAbortSignal$1||(hasRequiredAddAbortSignal$1=1,(function(n){const{SymbolDispose:e}=requirePrimordials$1(),{AbortError:t,codes:r}=requireErrors$1(),{isNodeStream:i,isWebStream:s,kControllerErrorFunction:o}=requireUtils$1(),a=requireEndOfStream$1(),{ERR_INVALID_ARG_TYPE:u}=r;let c;const l=(d,f)=>{if(typeof d!="object"||!("aborted"in d))throw new u(f,"AbortSignal",d)};n.exports.addAbortSignal=function(f,m){if(l(f,"signal"),!i(m)&&!s(m))throw new u("stream",["ReadableStream","WritableStream","Stream"],m);return n.exports.addAbortSignalNoValidate(f,m)},n.exports.addAbortSignalNoValidate=function(d,f){if(typeof d!="object"||!("aborted"in d))return f;const m=i(f)?()=>{f.destroy(new t(void 0,{cause:d.reason}))}:()=>{f[o](new t(void 0,{cause:d.reason}))};if(d.aborted)m();else{c=c||requireUtil$1().addAbortListener;const g=c(d,m);a(f,g[e])}return f}})(addAbortSignal$1)),addAbortSignal$1.exports}var buffer_list$1,hasRequiredBuffer_list$1;function requireBuffer_list$1(){if(hasRequiredBuffer_list$1)return buffer_list$1;hasRequiredBuffer_list$1=1;const{StringPrototypeSlice:n,SymbolIterator:e,TypedArrayPrototypeSet:t,Uint8Array:r}=requirePrimordials$1(),{Buffer:i}=requireBuffer(),{inspect:s}=requireUtil$1();return buffer_list$1=class{constructor(){this.head=null,this.tail=null,this.length=0}push(a){const u={data:a,next:null};this.length>0?this.tail.next=u:this.head=u,this.tail=u,++this.length}unshift(a){const u={data:a,next:this.head};this.length===0&&(this.tail=u),this.head=u,++this.length}shift(){if(this.length===0)return;const a=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,a}clear(){this.head=this.tail=null,this.length=0}join(a){if(this.length===0)return"";let u=this.head,c=""+u.data;for(;(u=u.next)!==null;)c+=a+u.data;return c}concat(a){if(this.length===0)return i.alloc(0);const u=i.allocUnsafe(a>>>0);let c=this.head,l=0;for(;c;)t(u,c.data,l),l+=c.data.length,c=c.next;return u}consume(a,u){const c=this.head.data;if(a<c.length){const l=c.slice(0,a);return this.head.data=c.slice(a),l}return a===c.length?this.shift():u?this._getString(a):this._getBuffer(a)}first(){return this.head.data}*[e](){for(let a=this.head;a;a=a.next)yield a.data}_getString(a){let u="",c=this.head,l=0;do{const d=c.data;if(a>d.length)u+=d,a-=d.length;else{a===d.length?(u+=d,++l,c.next?this.head=c.next:this.head=this.tail=null):(u+=n(d,0,a),this.head=c,c.data=n(d,a));break}++l}while((c=c.next)!==null);return this.length-=l,u}_getBuffer(a){const u=i.allocUnsafe(a),c=a;let l=this.head,d=0;do{const f=l.data;if(a>f.length)t(u,f,c-a),a-=f.length;else{a===f.length?(t(u,f,c-a),++d,l.next?this.head=l.next:this.head=this.tail=null):(t(u,new r(f.buffer,f.byteOffset,a),c-a),this.head=l,l.data=f.slice(a));break}++d}while((l=l.next)!==null);return this.length-=d,u}[Symbol.for("nodejs.util.inspect.custom")](a,u){return s(this,{...u,depth:0,customInspect:!1})}},buffer_list$1}var state$1,hasRequiredState$1;function requireState$1(){if(hasRequiredState$1)return state$1;hasRequiredState$1=1;const{MathFloor:n,NumberIsInteger:e}=requirePrimordials$1(),{validateInteger:t}=requireValidators$1(),{ERR_INVALID_ARG_VALUE:r}=requireErrors$1().codes;let i=16*1024,s=16;function o(l,d,f){return l.highWaterMark!=null?l.highWaterMark:d?l[f]:null}function a(l){return l?s:i}function u(l,d){t(d,"value",0),l?s=d:i=d}function c(l,d,f,m){const g=o(d,m,f);if(g!=null){if(!e(g)||g<0){const b=m?`options.${f}`:"options.highWaterMark";throw new r(b,g)}return n(g)}return a(l.objectMode)}return state$1={getHighWaterMark:c,getDefaultHighWaterMark:a,setDefaultHighWaterMark:u},state$1}var string_decoder={},safeBuffer={exports:{}};var hasRequiredSafeBuffer;function requireSafeBuffer(){return hasRequiredSafeBuffer||(hasRequiredSafeBuffer=1,(function(n,e){var t=requireBuffer(),r=t.Buffer;function i(o,a){for(var u in o)a[u]=o[u]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?n.exports=t:(i(t,e),e.Buffer=s);function s(o,a,u){return r(o,a,u)}s.prototype=Object.create(r.prototype),i(r,s),s.from=function(o,a,u){if(typeof o=="number")throw new TypeError("Argument must not be a number");return r(o,a,u)},s.alloc=function(o,a,u){if(typeof o!="number")throw new TypeError("Argument must be a number");var c=r(o);return a!==void 0?typeof u=="string"?c.fill(a,u):c.fill(a):c.fill(0),c},s.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r(o)},s.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(o)}})(safeBuffer,safeBuffer.exports)),safeBuffer.exports}var hasRequiredString_decoder;function requireString_decoder(){if(hasRequiredString_decoder)return string_decoder;hasRequiredString_decoder=1;var n=requireSafeBuffer().Buffer,e=n.isEncoding||function(w){switch(w=""+w,w&&w.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function t(w){if(!w)return"utf8";for(var v;;)switch(w){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return w;default:if(v)return;w=(""+w).toLowerCase(),v=!0}}function r(w){var v=t(w);if(typeof v!="string"&&(n.isEncoding===e||!e(w)))throw new Error("Unknown encoding: "+w);return v||w}string_decoder.StringDecoder=i;function i(w){this.encoding=r(w);var v;switch(this.encoding){case"utf16le":this.text=d,this.end=f,v=4;break;case"utf8":this.fillLast=u,v=4;break;case"base64":this.text=m,this.end=g,v=3;break;default:this.write=b,this.end=S;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(v)}i.prototype.write=function(w){if(w.length===0)return"";var v,_;if(this.lastNeed){if(v=this.fillLast(w),v===void 0)return"";_=this.lastNeed,this.lastNeed=0}else _=0;return _<w.length?v?v+this.text(w,_):this.text(w,_):v||""},i.prototype.end=l,i.prototype.text=c,i.prototype.fillLast=function(w){if(this.lastNeed<=w.length)return w.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);w.copy(this.lastChar,this.lastTotal-this.lastNeed,0,w.length),this.lastNeed-=w.length};function s(w){return w<=127?0:w>>5===6?2:w>>4===14?3:w>>3===30?4:w>>6===2?-1:-2}function o(w,v,_){var T=v.length-1;if(T<_)return 0;var C=s(v[T]);return C>=0?(C>0&&(w.lastNeed=C-1),C):--T<_||C===-2?0:(C=s(v[T]),C>=0?(C>0&&(w.lastNeed=C-2),C):--T<_||C===-2?0:(C=s(v[T]),C>=0?(C>0&&(C===2?C=0:w.lastNeed=C-3),C):0))}function a(w,v,_){if((v[0]&192)!==128)return w.lastNeed=0,"�";if(w.lastNeed>1&&v.length>1){if((v[1]&192)!==128)return w.lastNeed=1,"�";if(w.lastNeed>2&&v.length>2&&(v[2]&192)!==128)return w.lastNeed=2,"�"}}function u(w){var v=this.lastTotal-this.lastNeed,_=a(this,w);if(_!==void 0)return _;if(this.lastNeed<=w.length)return w.copy(this.lastChar,v,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);w.copy(this.lastChar,v,0,w.length),this.lastNeed-=w.length}function c(w,v){var _=o(this,w,v);if(!this.lastNeed)return w.toString("utf8",v);this.lastTotal=_;var T=w.length-(_-this.lastNeed);return w.copy(this.lastChar,0,T),w.toString("utf8",v,T)}function l(w){var v=w&&w.length?this.write(w):"";return this.lastNeed?v+"�":v}function d(w,v){if((w.length-v)%2===0){var _=w.toString("utf16le",v);if(_){var T=_.charCodeAt(_.length-1);if(T>=55296&&T<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=w[w.length-2],this.lastChar[1]=w[w.length-1],_.slice(0,-1)}return _}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=w[w.length-1],w.toString("utf16le",v,w.length-1)}function f(w){var v=w&&w.length?this.write(w):"";if(this.lastNeed){var _=this.lastTotal-this.lastNeed;return v+this.lastChar.toString("utf16le",0,_)}return v}function m(w,v){var _=(w.length-v)%3;return _===0?w.toString("base64",v):(this.lastNeed=3-_,this.lastTotal=3,_===1?this.lastChar[0]=w[w.length-1]:(this.lastChar[0]=w[w.length-2],this.lastChar[1]=w[w.length-1]),w.toString("base64",v,w.length-_))}function g(w){var v=w&&w.length?this.write(w):"";return this.lastNeed?v+this.lastChar.toString("base64",0,3-this.lastNeed):v}function b(w){return w.toString(this.encoding)}function S(w){return w&&w.length?this.write(w):""}return string_decoder}var from_1$1,hasRequiredFrom$1;function requireFrom$1(){if(hasRequiredFrom$1)return from_1$1;hasRequiredFrom$1=1;const n=requireBrowser$2(),{PromisePrototypeThen:e,SymbolAsyncIterator:t,SymbolIterator:r}=requirePrimordials$1(),{Buffer:i}=requireBuffer(),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_NULL_VALUES:o}=requireErrors$1().codes;function a(u,c,l){let d;if(typeof c=="string"||c instanceof i)return new u({objectMode:!0,...l,read(){this.push(c),this.push(null)}});let f;if(c&&c[t])f=!0,d=c[t]();else if(c&&c[r])f=!1,d=c[r]();else throw new s("iterable",["Iterable"],c);const m=new u({objectMode:!0,highWaterMark:1,...l});let g=!1;m._read=function(){g||(g=!0,S())},m._destroy=function(w,v){e(b(w),()=>n.nextTick(v,w),_=>n.nextTick(v,_||w))};async function b(w){const v=w!=null,_=typeof d.throw=="function";if(v&&_){const{value:T,done:C}=await d.throw(w);if(await T,C)return}if(typeof d.return=="function"){const{value:T}=await d.return();await T}}async function S(){for(;;){try{const{value:w,done:v}=f?await d.next():d.next();if(v)m.push(null);else{const _=w&&typeof w.then=="function"?await w:w;if(_===null)throw g=!1,new o;if(m.push(_))continue;g=!1}}catch(w){m.destroy(w)}break}}return m}return from_1$1=a,from_1$1}var readable$1,hasRequiredReadable$1;function requireReadable$1(){if(hasRequiredReadable$1)return readable$1;hasRequiredReadable$1=1;const n=requireBrowser$2(),{ArrayPrototypeIndexOf:e,NumberIsInteger:t,NumberIsNaN:r,NumberParseInt:i,ObjectDefineProperties:s,ObjectKeys:o,ObjectSetPrototypeOf:a,Promise:u,SafeSet:c,SymbolAsyncDispose:l,SymbolAsyncIterator:d,Symbol:f}=requirePrimordials$1();readable$1=Y,Y.ReadableState=ge;const{EventEmitter:m}=requireEvents(),{Stream:g,prependListener:b}=requireLegacy$1(),{Buffer:S}=requireBuffer(),{addAbortSignal:w}=requireAddAbortSignal$1(),v=requireEndOfStream$1();let _=requireUtil$1().debuglog("stream",k=>{_=k});const T=requireBuffer_list$1(),C=requireDestroy$1(),{getHighWaterMark:U,getDefaultHighWaterMark:$}=requireState$1(),{aggregateTwoErrors:W,codes:{ERR_INVALID_ARG_TYPE:re,ERR_METHOD_NOT_IMPLEMENTED:D,ERR_OUT_OF_RANGE:V,ERR_STREAM_PUSH_AFTER_EOF:he,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:z},AbortError:_e}=requireErrors$1(),{validateObject:Ce}=requireValidators$1(),Fe=f("kPaused"),{StringDecoder:ze}=requireString_decoder(),ae=requireFrom$1();a(Y.prototype,g.prototype),a(Y,g);const ve=()=>{},{errorOrDestroy:L}=C,ie=1,xe=2,ue=4,De=8,ke=16,We=32,Oe=64,te=128,le=256,Te=512,G=1024,P=2048,x=4096,A=8192,O=16384,H=32768,Q=65536,de=1<<17,M=1<<18;function ne(k){return{enumerable:!1,get(){return(this.state&k)!==0},set(j){j?this.state|=k:this.state&=~k}}}s(ge.prototype,{objectMode:ne(ie),ended:ne(xe),endEmitted:ne(ue),reading:ne(De),constructed:ne(ke),sync:ne(We),needReadable:ne(Oe),emittedReadable:ne(te),readableListening:ne(le),resumeScheduled:ne(Te),errorEmitted:ne(G),emitClose:ne(P),autoDestroy:ne(x),destroyed:ne(A),closed:ne(O),closeEmitted:ne(H),multiAwaitDrain:ne(Q),readingMore:ne(de),dataEmitted:ne(M)});function ge(k,j,Ie){typeof Ie!="boolean"&&(Ie=j instanceof requireDuplex$1()),this.state=P|x|ke|We,k&&k.objectMode&&(this.state|=ie),Ie&&k&&k.readableObjectMode&&(this.state|=ie),this.highWaterMark=k?U(this,k,"readableHighWaterMark",Ie):$(!1),this.buffer=new T,this.length=0,this.pipes=[],this.flowing=null,this[Fe]=null,k&&k.emitClose===!1&&(this.state&=~P),k&&k.autoDestroy===!1&&(this.state&=~x),this.errored=null,this.defaultEncoding=k&&k.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,k&&k.encoding&&(this.decoder=new ze(k.encoding),this.encoding=k.encoding)}function Y(k){if(!(this instanceof Y))return new Y(k);const j=this instanceof requireDuplex$1();this._readableState=new ge(k,this,j),k&&(typeof k.read=="function"&&(this._read=k.read),typeof k.destroy=="function"&&(this._destroy=k.destroy),typeof k.construct=="function"&&(this._construct=k.construct),k.signal&&!j&&w(k.signal,this)),g.call(this,k),C.construct(this,()=>{this._readableState.needReadable&&me(this,this._readableState)})}Y.prototype.destroy=C.destroy,Y.prototype._undestroy=C.undestroy,Y.prototype._destroy=function(k,j){j(k)},Y.prototype[m.captureRejectionSymbol]=function(k){this.destroy(k)},Y.prototype[l]=function(){let k;return this.destroyed||(k=this.readableEnded?null:new _e,this.destroy(k)),new u((j,Ie)=>v(this,Ae=>Ae&&Ae!==k?Ie(Ae):j(null)))},Y.prototype.push=function(k,j){return Be(this,k,j,!1)},Y.prototype.unshift=function(k,j){return Be(this,k,j,!0)};function Be(k,j,Ie,Ae){_("readableAddChunk",j);const Ve=k._readableState;let ht;if((Ve.state&ie)===0&&(typeof j=="string"?(Ie=Ie||Ve.defaultEncoding,Ve.encoding!==Ie&&(Ae&&Ve.encoding?j=S.from(j,Ie).toString(Ve.encoding):(j=S.from(j,Ie),Ie=""))):j instanceof S?Ie="":g._isUint8Array(j)?(j=g._uint8ArrayToBuffer(j),Ie=""):j!=null&&(ht=new re("chunk",["string","Buffer","Uint8Array"],j))),ht)L(k,ht);else if(j===null)Ve.state&=~De,R(k,Ve);else if((Ve.state&ie)!==0||j&&j.length>0)if(Ae)if((Ve.state&ue)!==0)L(k,new z);else{if(Ve.destroyed||Ve.errored)return!1;Je(k,Ve,j,!0)}else if(Ve.ended)L(k,new he);else{if(Ve.destroyed||Ve.errored)return!1;Ve.state&=~De,Ve.decoder&&!Ie?(j=Ve.decoder.write(j),Ve.objectMode||j.length!==0?Je(k,Ve,j,!1):me(k,Ve)):Je(k,Ve,j,!1)}else Ae||(Ve.state&=~De,me(k,Ve));return!Ve.ended&&(Ve.length<Ve.highWaterMark||Ve.length===0)}function Je(k,j,Ie,Ae){j.flowing&&j.length===0&&!j.sync&&k.listenerCount("data")>0?((j.state&Q)!==0?j.awaitDrainWriters.clear():j.awaitDrainWriters=null,j.dataEmitted=!0,k.emit("data",Ie)):(j.length+=j.objectMode?1:Ie.length,Ae?j.buffer.unshift(Ie):j.buffer.push(Ie),(j.state&Oe)!==0&&N(k)),me(k,j)}Y.prototype.isPaused=function(){const k=this._readableState;return k[Fe]===!0||k.flowing===!1},Y.prototype.setEncoding=function(k){const j=new ze(k);this._readableState.decoder=j,this._readableState.encoding=this._readableState.decoder.encoding;const Ie=this._readableState.buffer;let Ae="";for(const Ve of Ie)Ae+=j.write(Ve);return Ie.clear(),Ae!==""&&Ie.push(Ae),this._readableState.length=Ae.length,this};const Ne=1073741824;function Ze(k){if(k>Ne)throw new V("size","<= 1GiB",k);return k--,k|=k>>>1,k|=k>>>2,k|=k>>>4,k|=k>>>8,k|=k>>>16,k++,k}function B(k,j){return k<=0||j.length===0&&j.ended?0:(j.state&ie)!==0?1:r(k)?j.flowing&&j.length?j.buffer.first().length:j.length:k<=j.length?k:j.ended?j.length:0}Y.prototype.read=function(k){_("read",k),k===void 0?k=NaN:t(k)||(k=i(k,10));const j=this._readableState,Ie=k;if(k>j.highWaterMark&&(j.highWaterMark=Ze(k)),k!==0&&(j.state&=~te),k===0&&j.needReadable&&((j.highWaterMark!==0?j.length>=j.highWaterMark:j.length>0)||j.ended))return _("read: emitReadable",j.length,j.ended),j.length===0&&j.ended?$t(this):N(this),null;if(k=B(k,j),k===0&&j.ended)return j.length===0&&$t(this),null;let Ae=(j.state&Oe)!==0;if(_("need readable",Ae),(j.length===0||j.length-k<j.highWaterMark)&&(Ae=!0,_("length less than watermark",Ae)),j.ended||j.reading||j.destroyed||j.errored||!j.constructed)Ae=!1,_("reading, ended or constructing",Ae);else if(Ae){_("do read"),j.state|=De|We,j.length===0&&(j.state|=Oe);try{this._read(j.highWaterMark)}catch(ht){L(this,ht)}j.state&=~We,j.reading||(k=B(Ie,j))}let Ve;return k>0?Ve=dt(k,j):Ve=null,Ve===null?(j.needReadable=j.length<=j.highWaterMark,k=0):(j.length-=k,j.multiAwaitDrain?j.awaitDrainWriters.clear():j.awaitDrainWriters=null),j.length===0&&(j.ended||(j.needReadable=!0),Ie!==k&&j.ended&&$t(this)),Ve!==null&&!j.errorEmitted&&!j.closeEmitted&&(j.dataEmitted=!0,this.emit("data",Ve)),Ve};function R(k,j){if(_("onEofChunk"),!j.ended){if(j.decoder){const Ie=j.decoder.end();Ie&&Ie.length&&(j.buffer.push(Ie),j.length+=j.objectMode?1:Ie.length)}j.ended=!0,j.sync?N(k):(j.needReadable=!1,j.emittedReadable=!0,F(k))}}function N(k){const j=k._readableState;_("emitReadable",j.needReadable,j.emittedReadable),j.needReadable=!1,j.emittedReadable||(_("emitReadable",j.flowing),j.emittedReadable=!0,n.nextTick(F,k))}function F(k){const j=k._readableState;_("emitReadable_",j.destroyed,j.length,j.ended),!j.destroyed&&!j.errored&&(j.length||j.ended)&&(k.emit("readable"),j.emittedReadable=!1),j.needReadable=!j.flowing&&!j.ended&&j.length<=j.highWaterMark,at(k)}function me(k,j){!j.readingMore&&j.constructed&&(j.readingMore=!0,n.nextTick(Re,k,j))}function Re(k,j){for(;!j.reading&&!j.ended&&(j.length<j.highWaterMark||j.flowing&&j.length===0);){const Ie=j.length;if(_("maybeReadMore read 0"),k.read(0),Ie===j.length)break}j.readingMore=!1}Y.prototype._read=function(k){throw new D("_read()")},Y.prototype.pipe=function(k,j){const Ie=this,Ae=this._readableState;Ae.pipes.length===1&&(Ae.multiAwaitDrain||(Ae.multiAwaitDrain=!0,Ae.awaitDrainWriters=new c(Ae.awaitDrainWriters?[Ae.awaitDrainWriters]:[]))),Ae.pipes.push(k),_("pipe count=%d opts=%j",Ae.pipes.length,j);const ht=(!j||j.end!==!1)&&k!==n.stdout&&k!==n.stderr?rr:lt;Ae.endEmitted?n.nextTick(ht):Ie.once("end",ht),k.on("unpipe",gt);function gt(rt,Rt){_("onunpipe"),rt===Ie&&Rt&&Rt.hasUnpiped===!1&&(Rt.hasUnpiped=!0,ar())}function rr(){_("onend"),k.end()}let Pt,Et=!1;function ar(){_("cleanup"),k.removeListener("close",Jt),k.removeListener("finish",zt),Pt&&k.removeListener("drain",Pt),k.removeListener("error",nr),k.removeListener("unpipe",gt),Ie.removeListener("end",rr),Ie.removeListener("end",lt),Ie.removeListener("data",Ot),Et=!0,Pt&&Ae.awaitDrainWriters&&(!k._writableState||k._writableState.needDrain)&&Pt()}function fr(){Et||(Ae.pipes.length===1&&Ae.pipes[0]===k?(_("false write response, pause",0),Ae.awaitDrainWriters=k,Ae.multiAwaitDrain=!1):Ae.pipes.length>1&&Ae.pipes.includes(k)&&(_("false write response, pause",Ae.awaitDrainWriters.size),Ae.awaitDrainWriters.add(k)),Ie.pause()),Pt||(Pt=we(Ie,k),k.on("drain",Pt))}Ie.on("data",Ot);function Ot(rt){_("ondata");const Rt=k.write(rt);_("dest.write",Rt),Rt===!1&&fr()}function nr(rt){if(_("onerror",rt),lt(),k.removeListener("error",nr),k.listenerCount("error")===0){const Rt=k._writableState||k._readableState;Rt&&!Rt.errorEmitted?L(k,rt):k.emit("error",rt)}}b(k,"error",nr);function Jt(){k.removeListener("finish",zt),lt()}k.once("close",Jt);function zt(){_("onfinish"),k.removeListener("close",Jt),lt()}k.once("finish",zt);function lt(){_("unpipe"),Ie.unpipe(k)}return k.emit("pipe",Ie),k.writableNeedDrain===!0?fr():Ae.flowing||(_("pipe resume"),Ie.resume()),k};function we(k,j){return function(){const Ae=k._readableState;Ae.awaitDrainWriters===j?(_("pipeOnDrain",1),Ae.awaitDrainWriters=null):Ae.multiAwaitDrain&&(_("pipeOnDrain",Ae.awaitDrainWriters.size),Ae.awaitDrainWriters.delete(j)),(!Ae.awaitDrainWriters||Ae.awaitDrainWriters.size===0)&&k.listenerCount("data")&&k.resume()}}Y.prototype.unpipe=function(k){const j=this._readableState,Ie={hasUnpiped:!1};if(j.pipes.length===0)return this;if(!k){const Ve=j.pipes;j.pipes=[],this.pause();for(let ht=0;ht<Ve.length;ht++)Ve[ht].emit("unpipe",this,{hasUnpiped:!1});return this}const Ae=e(j.pipes,k);return Ae===-1?this:(j.pipes.splice(Ae,1),j.pipes.length===0&&this.pause(),k.emit("unpipe",this,Ie),this)},Y.prototype.on=function(k,j){const Ie=g.prototype.on.call(this,k,j),Ae=this._readableState;return k==="data"?(Ae.readableListening=this.listenerCount("readable")>0,Ae.flowing!==!1&&this.resume()):k==="readable"&&!Ae.endEmitted&&!Ae.readableListening&&(Ae.readableListening=Ae.needReadable=!0,Ae.flowing=!1,Ae.emittedReadable=!1,_("on readable",Ae.length,Ae.reading),Ae.length?N(this):Ae.reading||n.nextTick(et,this)),Ie},Y.prototype.addListener=Y.prototype.on,Y.prototype.removeListener=function(k,j){const Ie=g.prototype.removeListener.call(this,k,j);return k==="readable"&&n.nextTick(Qe,this),Ie},Y.prototype.off=Y.prototype.removeListener,Y.prototype.removeAllListeners=function(k){const j=g.prototype.removeAllListeners.apply(this,arguments);return(k==="readable"||k===void 0)&&n.nextTick(Qe,this),j};function Qe(k){const j=k._readableState;j.readableListening=k.listenerCount("readable")>0,j.resumeScheduled&&j[Fe]===!1?j.flowing=!0:k.listenerCount("data")>0?k.resume():j.readableListening||(j.flowing=null)}function et(k){_("readable nexttick read 0"),k.read(0)}Y.prototype.resume=function(){const k=this._readableState;return k.flowing||(_("resume"),k.flowing=!k.readableListening,ot(this,k)),k[Fe]=!1,this};function ot(k,j){j.resumeScheduled||(j.resumeScheduled=!0,n.nextTick(ct,k,j))}function ct(k,j){_("resume",j.reading),j.reading||k.read(0),j.resumeScheduled=!1,k.emit("resume"),at(k),j.flowing&&!j.reading&&k.read(0)}Y.prototype.pause=function(){return _("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(_("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[Fe]=!0,this};function at(k){const j=k._readableState;for(_("flow",j.flowing);j.flowing&&k.read()!==null;);}Y.prototype.wrap=function(k){let j=!1;k.on("data",Ae=>{!this.push(Ae)&&k.pause&&(j=!0,k.pause())}),k.on("end",()=>{this.push(null)}),k.on("error",Ae=>{L(this,Ae)}),k.on("close",()=>{this.destroy()}),k.on("destroy",()=>{this.destroy()}),this._read=()=>{j&&k.resume&&(j=!1,k.resume())};const Ie=o(k);for(let Ae=1;Ae<Ie.length;Ae++){const Ve=Ie[Ae];this[Ve]===void 0&&typeof k[Ve]=="function"&&(this[Ve]=k[Ve].bind(k))}return this},Y.prototype[d]=function(){return Qt(this)},Y.prototype.iterator=function(k){return k!==void 0&&Ce(k,"options"),Qt(this,k)};function Qt(k,j){typeof k.read!="function"&&(k=Y.wrap(k,{objectMode:!0}));const Ie=wt(k,j);return Ie.stream=k,Ie}async function*wt(k,j){let Ie=ve;function Ae(gt){this===k?(Ie(),Ie=ve):Ie=gt}k.on("readable",Ae);let Ve;const ht=v(k,{writable:!1},gt=>{Ve=gt?W(Ve,gt):null,Ie(),Ie=ve});try{for(;;){const gt=k.destroyed?null:k.read();if(gt!==null)yield gt;else{if(Ve)throw Ve;if(Ve===null)return;await new u(Ae)}}}catch(gt){throw Ve=W(Ve,gt),Ve}finally{(Ve||j?.destroyOnReturn!==!1)&&(Ve===void 0||k._readableState.autoDestroy)?C.destroyer(k,null):(k.off("readable",Ae),ht())}}s(Y.prototype,{readable:{__proto__:null,get(){const k=this._readableState;return!!k&&k.readable!==!1&&!k.destroyed&&!k.errorEmitted&&!k.endEmitted},set(k){this._readableState&&(this._readableState.readable=!!k)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(k){this._readableState&&(this._readableState.flowing=k)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(k){this._readableState&&(this._readableState.destroyed=k)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),s(ge.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[Fe]!==!1},set(k){this[Fe]=!!k}}}),Y._fromList=dt;function dt(k,j){if(j.length===0)return null;let Ie;return j.objectMode?Ie=j.buffer.shift():!k||k>=j.length?(j.decoder?Ie=j.buffer.join(""):j.buffer.length===1?Ie=j.buffer.first():Ie=j.buffer.concat(j.length),j.buffer.clear()):Ie=j.buffer.consume(k,j.decoder),Ie}function $t(k){const j=k._readableState;_("endReadable",j.endEmitted),j.endEmitted||(j.ended=!0,n.nextTick(yt,j,k))}function yt(k,j){if(_("endReadableNT",k.endEmitted,k.length),!k.errored&&!k.closeEmitted&&!k.endEmitted&&k.length===0){if(k.endEmitted=!0,j.emit("end"),j.writable&&j.allowHalfOpen===!1)n.nextTick(At,j);else if(k.autoDestroy){const Ie=j._writableState;(!Ie||Ie.autoDestroy&&(Ie.finished||Ie.writable===!1))&&j.destroy()}}}function At(k){k.writable&&!k.writableEnded&&!k.destroyed&&k.end()}Y.from=function(k,j){return ae(Y,k,j)};let It;function Bt(){return It===void 0&&(It={}),It}return Y.fromWeb=function(k,j){return Bt().newStreamReadableFromReadableStream(k,j)},Y.toWeb=function(k,j){return Bt().newReadableStreamFromStreamReadable(k,j)},Y.wrap=function(k,j){var Ie,Ae;return new Y({objectMode:(Ie=(Ae=k.readableObjectMode)!==null&&Ae!==void 0?Ae:k.objectMode)!==null&&Ie!==void 0?Ie:!0,...j,destroy(Ve,ht){C.destroyer(k,Ve),ht(Ve)}}).wrap(k)},readable$1}var writable$1,hasRequiredWritable$1;function requireWritable$1(){if(hasRequiredWritable$1)return writable$1;hasRequiredWritable$1=1;const n=requireBrowser$2(),{ArrayPrototypeSlice:e,Error:t,FunctionPrototypeSymbolHasInstance:r,ObjectDefineProperty:i,ObjectDefineProperties:s,ObjectSetPrototypeOf:o,StringPrototypeToLowerCase:a,Symbol:u,SymbolHasInstance:c}=requirePrimordials$1();writable$1=Ce,Ce.WritableState=z;const{EventEmitter:l}=requireEvents(),d=requireLegacy$1().Stream,{Buffer:f}=requireBuffer(),m=requireDestroy$1(),{addAbortSignal:g}=requireAddAbortSignal$1(),{getHighWaterMark:b,getDefaultHighWaterMark:S}=requireState$1(),{ERR_INVALID_ARG_TYPE:w,ERR_METHOD_NOT_IMPLEMENTED:v,ERR_MULTIPLE_CALLBACK:_,ERR_STREAM_CANNOT_PIPE:T,ERR_STREAM_DESTROYED:C,ERR_STREAM_ALREADY_FINISHED:U,ERR_STREAM_NULL_VALUES:$,ERR_STREAM_WRITE_AFTER_END:W,ERR_UNKNOWN_ENCODING:re}=requireErrors$1().codes,{errorOrDestroy:D}=m;o(Ce.prototype,d.prototype),o(Ce,d);function V(){}const he=u("kOnFinished");function z(x,A,O){typeof O!="boolean"&&(O=A instanceof requireDuplex$1()),this.objectMode=!!(x&&x.objectMode),O&&(this.objectMode=this.objectMode||!!(x&&x.writableObjectMode)),this.highWaterMark=x?b(this,x,"writableHighWaterMark",O):S(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const H=!!(x&&x.decodeStrings===!1);this.decodeStrings=!H,this.defaultEncoding=x&&x.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=L.bind(void 0,A),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,_e(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!x||x.emitClose!==!1,this.autoDestroy=!x||x.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[he]=[]}function _e(x){x.buffered=[],x.bufferedIndex=0,x.allBuffers=!0,x.allNoop=!0}z.prototype.getBuffer=function(){return e(this.buffered,this.bufferedIndex)},i(z.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Ce(x){const A=this instanceof requireDuplex$1();if(!A&&!r(Ce,this))return new Ce(x);this._writableState=new z(x,this,A),x&&(typeof x.write=="function"&&(this._write=x.write),typeof x.writev=="function"&&(this._writev=x.writev),typeof x.destroy=="function"&&(this._destroy=x.destroy),typeof x.final=="function"&&(this._final=x.final),typeof x.construct=="function"&&(this._construct=x.construct),x.signal&&g(x.signal,this)),d.call(this,x),m.construct(this,()=>{const O=this._writableState;O.writing||De(this,O),te(this,O)})}i(Ce,c,{__proto__:null,value:function(x){return r(this,x)?!0:this!==Ce?!1:x&&x._writableState instanceof z}}),Ce.prototype.pipe=function(){D(this,new T)};function Fe(x,A,O,H){const Q=x._writableState;if(typeof O=="function")H=O,O=Q.defaultEncoding;else{if(!O)O=Q.defaultEncoding;else if(O!=="buffer"&&!f.isEncoding(O))throw new re(O);typeof H!="function"&&(H=V)}if(A===null)throw new $;if(!Q.objectMode)if(typeof A=="string")Q.decodeStrings!==!1&&(A=f.from(A,O),O="buffer");else if(A instanceof f)O="buffer";else if(d._isUint8Array(A))A=d._uint8ArrayToBuffer(A),O="buffer";else throw new w("chunk",["string","Buffer","Uint8Array"],A);let de;return Q.ending?de=new W:Q.destroyed&&(de=new C("write")),de?(n.nextTick(H,de),D(x,de,!0),de):(Q.pendingcb++,ze(x,Q,A,O,H))}Ce.prototype.write=function(x,A,O){return Fe(this,x,A,O)===!0},Ce.prototype.cork=function(){this._writableState.corked++},Ce.prototype.uncork=function(){const x=this._writableState;x.corked&&(x.corked--,x.writing||De(this,x))},Ce.prototype.setDefaultEncoding=function(A){if(typeof A=="string"&&(A=a(A)),!f.isEncoding(A))throw new re(A);return this._writableState.defaultEncoding=A,this};function ze(x,A,O,H,Q){const de=A.objectMode?1:O.length;A.length+=de;const M=A.length<A.highWaterMark;return M||(A.needDrain=!0),A.writing||A.corked||A.errored||!A.constructed?(A.buffered.push({chunk:O,encoding:H,callback:Q}),A.allBuffers&&H!=="buffer"&&(A.allBuffers=!1),A.allNoop&&Q!==V&&(A.allNoop=!1)):(A.writelen=de,A.writecb=Q,A.writing=!0,A.sync=!0,x._write(O,H,A.onwrite),A.sync=!1),M&&!A.errored&&!A.destroyed}function ae(x,A,O,H,Q,de,M){A.writelen=H,A.writecb=M,A.writing=!0,A.sync=!0,A.destroyed?A.onwrite(new C("write")):O?x._writev(Q,A.onwrite):x._write(Q,de,A.onwrite),A.sync=!1}function ve(x,A,O,H){--A.pendingcb,H(O),ue(A),D(x,O)}function L(x,A){const O=x._writableState,H=O.sync,Q=O.writecb;if(typeof Q!="function"){D(x,new _);return}O.writing=!1,O.writecb=null,O.length-=O.writelen,O.writelen=0,A?(A.stack,O.errored||(O.errored=A),x._readableState&&!x._readableState.errored&&(x._readableState.errored=A),H?n.nextTick(ve,x,O,A,Q):ve(x,O,A,Q)):(O.buffered.length>O.bufferedIndex&&De(x,O),H?O.afterWriteTickInfo!==null&&O.afterWriteTickInfo.cb===Q?O.afterWriteTickInfo.count++:(O.afterWriteTickInfo={count:1,cb:Q,stream:x,state:O},n.nextTick(ie,O.afterWriteTickInfo)):xe(x,O,1,Q))}function ie({stream:x,state:A,count:O,cb:H}){return A.afterWriteTickInfo=null,xe(x,A,O,H)}function xe(x,A,O,H){for(!A.ending&&!x.destroyed&&A.length===0&&A.needDrain&&(A.needDrain=!1,x.emit("drain"));O-- >0;)A.pendingcb--,H();A.destroyed&&ue(A),te(x,A)}function ue(x){if(x.writing)return;for(let Q=x.bufferedIndex;Q<x.buffered.length;++Q){var A;const{chunk:de,callback:M}=x.buffered[Q],ne=x.objectMode?1:de.length;x.length-=ne,M((A=x.errored)!==null&&A!==void 0?A:new C("write"))}const O=x[he].splice(0);for(let Q=0;Q<O.length;Q++){var H;O[Q]((H=x.errored)!==null&&H!==void 0?H:new C("end"))}_e(x)}function De(x,A){if(A.corked||A.bufferProcessing||A.destroyed||!A.constructed)return;const{buffered:O,bufferedIndex:H,objectMode:Q}=A,de=O.length-H;if(!de)return;let M=H;if(A.bufferProcessing=!0,de>1&&x._writev){A.pendingcb-=de-1;const ne=A.allNoop?V:Y=>{for(let Be=M;Be<O.length;++Be)O[Be].callback(Y)},ge=A.allNoop&&M===0?O:e(O,M);ge.allBuffers=A.allBuffers,ae(x,A,!0,A.length,ge,"",ne),_e(A)}else{do{const{chunk:ne,encoding:ge,callback:Y}=O[M];O[M++]=null;const Be=Q?1:ne.length;ae(x,A,!1,Be,ne,ge,Y)}while(M<O.length&&!A.writing);M===O.length?_e(A):M>256?(O.splice(0,M),A.bufferedIndex=0):A.bufferedIndex=M}A.bufferProcessing=!1}Ce.prototype._write=function(x,A,O){if(this._writev)this._writev([{chunk:x,encoding:A}],O);else throw new v("_write()")},Ce.prototype._writev=null,Ce.prototype.end=function(x,A,O){const H=this._writableState;typeof x=="function"?(O=x,x=null,A=null):typeof A=="function"&&(O=A,A=null);let Q;if(x!=null){const de=Fe(this,x,A);de instanceof t&&(Q=de)}return H.corked&&(H.corked=1,this.uncork()),Q||(!H.errored&&!H.ending?(H.ending=!0,te(this,H,!0),H.ended=!0):H.finished?Q=new U("end"):H.destroyed&&(Q=new C("end"))),typeof O=="function"&&(Q||H.finished?n.nextTick(O,Q):H[he].push(O)),this};function ke(x){return x.ending&&!x.destroyed&&x.constructed&&x.length===0&&!x.errored&&x.buffered.length===0&&!x.finished&&!x.writing&&!x.errorEmitted&&!x.closeEmitted}function We(x,A){let O=!1;function H(Q){if(O){D(x,Q??_());return}if(O=!0,A.pendingcb--,Q){const de=A[he].splice(0);for(let M=0;M<de.length;M++)de[M](Q);D(x,Q,A.sync)}else ke(A)&&(A.prefinished=!0,x.emit("prefinish"),A.pendingcb++,n.nextTick(le,x,A))}A.sync=!0,A.pendingcb++;try{x._final(H)}catch(Q){H(Q)}A.sync=!1}function Oe(x,A){!A.prefinished&&!A.finalCalled&&(typeof x._final=="function"&&!A.destroyed?(A.finalCalled=!0,We(x,A)):(A.prefinished=!0,x.emit("prefinish")))}function te(x,A,O){ke(A)&&(Oe(x,A),A.pendingcb===0&&(O?(A.pendingcb++,n.nextTick((H,Q)=>{ke(Q)?le(H,Q):Q.pendingcb--},x,A)):ke(A)&&(A.pendingcb++,le(x,A))))}function le(x,A){A.pendingcb--,A.finished=!0;const O=A[he].splice(0);for(let H=0;H<O.length;H++)O[H]();if(x.emit("finish"),A.autoDestroy){const H=x._readableState;(!H||H.autoDestroy&&(H.endEmitted||H.readable===!1))&&x.destroy()}}s(Ce.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(x){this._writableState&&(this._writableState.destroyed=x)}},writable:{__proto__:null,get(){const x=this._writableState;return!!x&&x.writable!==!1&&!x.destroyed&&!x.errored&&!x.ending&&!x.ended},set(x){this._writableState&&(this._writableState.writable=!!x)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){const x=this._writableState;return x?!x.destroyed&&!x.ending&&x.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});const Te=m.destroy;Ce.prototype.destroy=function(x,A){const O=this._writableState;return!O.destroyed&&(O.bufferedIndex<O.buffered.length||O[he].length)&&n.nextTick(ue,O),Te.call(this,x,A),this},Ce.prototype._undestroy=m.undestroy,Ce.prototype._destroy=function(x,A){A(x)},Ce.prototype[l.captureRejectionSymbol]=function(x){this.destroy(x)};let G;function P(){return G===void 0&&(G={}),G}return Ce.fromWeb=function(x,A){return P().newStreamWritableFromWritableStream(x,A)},Ce.toWeb=function(x){return P().newWritableStreamFromStreamWritable(x)},writable$1}var duplexify$1,hasRequiredDuplexify$1;function requireDuplexify$1(){if(hasRequiredDuplexify$1)return duplexify$1;hasRequiredDuplexify$1=1;const n=requireBrowser$2(),e=requireBuffer(),{isReadable:t,isWritable:r,isIterable:i,isNodeStream:s,isReadableNodeStream:o,isWritableNodeStream:a,isDuplexNodeStream:u,isReadableStream:c,isWritableStream:l}=requireUtils$1(),d=requireEndOfStream$1(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:m,ERR_INVALID_RETURN_VALUE:g}}=requireErrors$1(),{destroyer:b}=requireDestroy$1(),S=requireDuplex$1(),w=requireReadable$1(),v=requireWritable$1(),{createDeferredPromise:_}=requireUtil$1(),T=requireFrom$1(),C=globalThis.Blob||e.Blob,U=typeof C<"u"?function(z){return z instanceof C}:function(z){return!1},$=globalThis.AbortController||requireBrowser$3().AbortController,{FunctionPrototypeCall:W}=requirePrimordials$1();class re extends S{constructor(z){super(z),z?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),z?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}}duplexify$1=function he(z,_e){if(u(z))return z;if(o(z))return V({readable:z});if(a(z))return V({writable:z});if(s(z))return V({writable:!1,readable:!1});if(c(z))return V({readable:w.fromWeb(z)});if(l(z))return V({writable:v.fromWeb(z)});if(typeof z=="function"){const{value:Fe,write:ze,final:ae,destroy:ve}=D(z);if(i(Fe))return T(re,Fe,{objectMode:!0,write:ze,final:ae,destroy:ve});const L=Fe?.then;if(typeof L=="function"){let ie;const xe=W(L,Fe,ue=>{if(ue!=null)throw new g("nully","body",ue)},ue=>{b(ie,ue)});return ie=new re({objectMode:!0,readable:!1,write:ze,final(ue){ae(async()=>{try{await xe,n.nextTick(ue,null)}catch(De){n.nextTick(ue,De)}})},destroy:ve})}throw new g("Iterable, AsyncIterable or AsyncFunction",_e,Fe)}if(U(z))return he(z.arrayBuffer());if(i(z))return T(re,z,{objectMode:!0,writable:!1});if(c(z?.readable)&&l(z?.writable))return re.fromWeb(z);if(typeof z?.writable=="object"||typeof z?.readable=="object"){const Fe=z!=null&&z.readable?o(z?.readable)?z?.readable:he(z.readable):void 0,ze=z!=null&&z.writable?a(z?.writable)?z?.writable:he(z.writable):void 0;return V({readable:Fe,writable:ze})}const Ce=z?.then;if(typeof Ce=="function"){let Fe;return W(Ce,z,ze=>{ze!=null&&Fe.push(ze),Fe.push(null)},ze=>{b(Fe,ze)}),Fe=new re({objectMode:!0,writable:!1,read(){}})}throw new m(_e,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],z)};function D(he){let{promise:z,resolve:_e}=_();const Ce=new $,Fe=Ce.signal;return{value:he((async function*(){for(;;){const ae=z;z=null;const{chunk:ve,done:L,cb:ie}=await ae;if(n.nextTick(ie),L)return;if(Fe.aborted)throw new f(void 0,{cause:Fe.reason});({promise:z,resolve:_e}=_()),yield ve}})(),{signal:Fe}),write(ae,ve,L){const ie=_e;_e=null,ie({chunk:ae,done:!1,cb:L})},final(ae){const ve=_e;_e=null,ve({done:!0,cb:ae})},destroy(ae,ve){Ce.abort(),ve(ae)}}}function V(he){const z=he.readable&&typeof he.readable.read!="function"?w.wrap(he.readable):he.readable,_e=he.writable;let Ce=!!t(z),Fe=!!r(_e),ze,ae,ve,L,ie;function xe(ue){const De=L;L=null,De?De(ue):ue&&ie.destroy(ue)}return ie=new re({readableObjectMode:!!(z!=null&&z.readableObjectMode),writableObjectMode:!!(_e!=null&&_e.writableObjectMode),readable:Ce,writable:Fe}),Fe&&(d(_e,ue=>{Fe=!1,ue&&b(z,ue),xe(ue)}),ie._write=function(ue,De,ke){_e.write(ue,De)?ke():ze=ke},ie._final=function(ue){_e.end(),ae=ue},_e.on("drain",function(){if(ze){const ue=ze;ze=null,ue()}}),_e.on("finish",function(){if(ae){const ue=ae;ae=null,ue()}})),Ce&&(d(z,ue=>{Ce=!1,ue&&b(z,ue),xe(ue)}),z.on("readable",function(){if(ve){const ue=ve;ve=null,ue()}}),z.on("end",function(){ie.push(null)}),ie._read=function(){for(;;){const ue=z.read();if(ue===null){ve=ie._read;return}if(!ie.push(ue))return}}),ie._destroy=function(ue,De){!ue&&L!==null&&(ue=new f),ve=null,ze=null,ae=null,L===null?De(ue):(L=De,b(_e,ue),b(z,ue))},ie}return duplexify$1}var duplex$1,hasRequiredDuplex$1;function requireDuplex$1(){if(hasRequiredDuplex$1)return duplex$1;hasRequiredDuplex$1=1;const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:e,ObjectKeys:t,ObjectSetPrototypeOf:r}=requirePrimordials$1();duplex$1=o;const i=requireReadable$1(),s=requireWritable$1();r(o.prototype,i.prototype),r(o,i);{const l=t(s.prototype);for(let d=0;d<l.length;d++){const f=l[d];o.prototype[f]||(o.prototype[f]=s.prototype[f])}}function o(l){if(!(this instanceof o))return new o(l);i.call(this,l),s.call(this,l),l?(this.allowHalfOpen=l.allowHalfOpen!==!1,l.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),l.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}n(o.prototype,{writable:{__proto__:null,...e(s.prototype,"writable")},writableHighWaterMark:{__proto__:null,...e(s.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...e(s.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...e(s.prototype,"writableBuffer")},writableLength:{__proto__:null,...e(s.prototype,"writableLength")},writableFinished:{__proto__:null,...e(s.prototype,"writableFinished")},writableCorked:{__proto__:null,...e(s.prototype,"writableCorked")},writableEnded:{__proto__:null,...e(s.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...e(s.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(l){this._readableState&&this._writableState&&(this._readableState.destroyed=l,this._writableState.destroyed=l)}}});let a;function u(){return a===void 0&&(a={}),a}o.fromWeb=function(l,d){return u().newStreamDuplexFromReadableWritablePair(l,d)},o.toWeb=function(l){return u().newReadableWritablePairFromDuplex(l)};let c;return o.from=function(l){return c||(c=requireDuplexify$1()),c(l,"body")},duplex$1}var transform$2,hasRequiredTransform$1;function requireTransform$1(){if(hasRequiredTransform$1)return transform$2;hasRequiredTransform$1=1;const{ObjectSetPrototypeOf:n,Symbol:e}=requirePrimordials$1();transform$2=o;const{ERR_METHOD_NOT_IMPLEMENTED:t}=requireErrors$1().codes,r=requireDuplex$1(),{getHighWaterMark:i}=requireState$1();n(o.prototype,r.prototype),n(o,r);const s=e("kCallback");function o(c){if(!(this instanceof o))return new o(c);const l=c?i(this,c,"readableHighWaterMark",!0):null;l===0&&(c={...c,highWaterMark:null,readableHighWaterMark:l,writableHighWaterMark:c.writableHighWaterMark||0}),r.call(this,c),this._readableState.sync=!1,this[s]=null,c&&(typeof c.transform=="function"&&(this._transform=c.transform),typeof c.flush=="function"&&(this._flush=c.flush)),this.on("prefinish",u)}function a(c){typeof this._flush=="function"&&!this.destroyed?this._flush((l,d)=>{if(l){c?c(l):this.destroy(l);return}d!=null&&this.push(d),this.push(null),c&&c()}):(this.push(null),c&&c())}function u(){this._final!==a&&a.call(this)}return o.prototype._final=a,o.prototype._transform=function(c,l,d){throw new t("_transform()")},o.prototype._write=function(c,l,d){const f=this._readableState,m=this._writableState,g=f.length;this._transform(c,l,(b,S)=>{if(b){d(b);return}S!=null&&this.push(S),m.ended||g===f.length||f.length<f.highWaterMark?d():this[s]=d})},o.prototype._read=function(){if(this[s]){const c=this[s];this[s]=null,c()}},transform$2}var passthrough$1,hasRequiredPassthrough$1;function requirePassthrough$1(){if(hasRequiredPassthrough$1)return passthrough$1;hasRequiredPassthrough$1=1;const{ObjectSetPrototypeOf:n}=requirePrimordials$1();passthrough$1=t;const e=requireTransform$1();n(t.prototype,e.prototype),n(t,e);function t(r){if(!(this instanceof t))return new t(r);e.call(this,r)}return t.prototype._transform=function(r,i,s){s(null,r)},passthrough$1}var pipeline_1$1,hasRequiredPipeline$1;function requirePipeline$1(){if(hasRequiredPipeline$1)return pipeline_1$1;hasRequiredPipeline$1=1;const n=requireBrowser$2(),{ArrayIsArray:e,Promise:t,SymbolAsyncIterator:r,SymbolDispose:i}=requirePrimordials$1(),s=requireEndOfStream$1(),{once:o}=requireUtil$1(),a=requireDestroy$1(),u=requireDuplex$1(),{aggregateTwoErrors:c,codes:{ERR_INVALID_ARG_TYPE:l,ERR_INVALID_RETURN_VALUE:d,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:m,ERR_STREAM_PREMATURE_CLOSE:g},AbortError:b}=requireErrors$1(),{validateFunction:S,validateAbortSignal:w}=requireValidators$1(),{isIterable:v,isReadable:_,isReadableNodeStream:T,isNodeStream:C,isTransformStream:U,isWebStream:$,isReadableStream:W,isReadableFinished:re}=requireUtils$1(),D=globalThis.AbortController||requireBrowser$3().AbortController;let V,he,z;function _e(ue,De,ke){let We=!1;ue.on("close",()=>{We=!0});const Oe=s(ue,{readable:De,writable:ke},te=>{We=!te});return{destroy:te=>{We||(We=!0,a.destroyer(ue,te||new m("pipe")))},cleanup:Oe}}function Ce(ue){return S(ue[ue.length-1],"streams[stream.length - 1]"),ue.pop()}function Fe(ue){if(v(ue))return ue;if(T(ue))return ze(ue);throw new l("val",["Readable","Iterable","AsyncIterable"],ue)}async function*ze(ue){he||(he=requireReadable$1()),yield*he.prototype[r].call(ue)}async function ae(ue,De,ke,{end:We}){let Oe,te=null;const le=P=>{if(P&&(Oe=P),te){const x=te;te=null,x()}},Te=()=>new t((P,x)=>{Oe?x(Oe):te=()=>{Oe?x(Oe):P()}});De.on("drain",le);const G=s(De,{readable:!1},le);try{De.writableNeedDrain&&await Te();for await(const P of ue)De.write(P)||await Te();We&&(De.end(),await Te()),ke()}catch(P){ke(Oe!==P?c(Oe,P):P)}finally{G(),De.off("drain",le)}}async function ve(ue,De,ke,{end:We}){U(De)&&(De=De.writable);const Oe=De.getWriter();try{for await(const te of ue)await Oe.ready,Oe.write(te).catch(()=>{});await Oe.ready,We&&await Oe.close(),ke()}catch(te){try{await Oe.abort(te),ke(te)}catch(le){ke(le)}}}function L(...ue){return ie(ue,o(Ce(ue)))}function ie(ue,De,ke){if(ue.length===1&&e(ue[0])&&(ue=ue[0]),ue.length<2)throw new f("streams");const We=new D,Oe=We.signal,te=ke?.signal,le=[];w(te,"options.signal");function Te(){Q(new b)}z=z||requireUtil$1().addAbortListener;let G;te&&(G=z(te,Te));let P,x;const A=[];let O=0;function H(ge){Q(ge,--O===0)}function Q(ge,Y){var Be;if(ge&&(!P||P.code==="ERR_STREAM_PREMATURE_CLOSE")&&(P=ge),!(!P&&!Y)){for(;A.length;)A.shift()(P);(Be=G)===null||Be===void 0||Be[i](),We.abort(),Y&&(P||le.forEach(Je=>Je()),n.nextTick(De,P,x))}}let de;for(let ge=0;ge<ue.length;ge++){const Y=ue[ge],Be=ge<ue.length-1,Je=ge>0,Ne=Be||ke?.end!==!1,Ze=ge===ue.length-1;if(C(Y)){let B=function(R){R&&R.name!=="AbortError"&&R.code!=="ERR_STREAM_PREMATURE_CLOSE"&&H(R)};if(Ne){const{destroy:R,cleanup:N}=_e(Y,Be,Je);A.push(R),_(Y)&&Ze&&le.push(N)}Y.on("error",B),_(Y)&&Ze&&le.push(()=>{Y.removeListener("error",B)})}if(ge===0)if(typeof Y=="function"){if(de=Y({signal:Oe}),!v(de))throw new d("Iterable, AsyncIterable or Stream","source",de)}else v(Y)||T(Y)||U(Y)?de=Y:de=u.from(Y);else if(typeof Y=="function"){if(U(de)){var M;de=Fe((M=de)===null||M===void 0?void 0:M.readable)}else de=Fe(de);if(de=Y(de,{signal:Oe}),Be){if(!v(de,!0))throw new d("AsyncIterable",`transform[${ge-1}]`,de)}else{var ne;V||(V=requirePassthrough$1());const B=new V({objectMode:!0}),R=(ne=de)===null||ne===void 0?void 0:ne.then;if(typeof R=="function")O++,R.call(de,me=>{x=me,me!=null&&B.write(me),Ne&&B.end(),n.nextTick(H)},me=>{B.destroy(me),n.nextTick(H,me)});else if(v(de,!0))O++,ae(de,B,H,{end:Ne});else if(W(de)||U(de)){const me=de.readable||de;O++,ae(me,B,H,{end:Ne})}else throw new d("AsyncIterable or Promise","destination",de);de=B;const{destroy:N,cleanup:F}=_e(de,!1,!0);A.push(N),Ze&&le.push(F)}}else if(C(Y)){if(T(de)){O+=2;const B=xe(de,Y,H,{end:Ne});_(Y)&&Ze&&le.push(B)}else if(U(de)||W(de)){const B=de.readable||de;O++,ae(B,Y,H,{end:Ne})}else if(v(de))O++,ae(de,Y,H,{end:Ne});else throw new l("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],de);de=Y}else if($(Y)){if(T(de))O++,ve(Fe(de),Y,H,{end:Ne});else if(W(de)||v(de))O++,ve(de,Y,H,{end:Ne});else if(U(de))O++,ve(de.readable,Y,H,{end:Ne});else throw new l("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],de);de=Y}else de=u.from(Y)}return(Oe!=null&&Oe.aborted||te!=null&&te.aborted)&&n.nextTick(Te),de}function xe(ue,De,ke,{end:We}){let Oe=!1;if(De.on("close",()=>{Oe||ke(new g)}),ue.pipe(De,{end:!1}),We){let te=function(){Oe=!0,De.end()};re(ue)?n.nextTick(te):ue.once("end",te)}else ke();return s(ue,{readable:!0,writable:!1},te=>{const le=ue._readableState;te&&te.code==="ERR_STREAM_PREMATURE_CLOSE"&&le&&le.ended&&!le.errored&&!le.errorEmitted?ue.once("end",ke).once("error",ke):ke(te)}),s(De,{readable:!1,writable:!0},ke)}return pipeline_1$1={pipelineImpl:ie,pipeline:L},pipeline_1$1}var compose$1,hasRequiredCompose$1;function requireCompose$1(){if(hasRequiredCompose$1)return compose$1;hasRequiredCompose$1=1;const{pipeline:n}=requirePipeline$1(),e=requireDuplex$1(),{destroyer:t}=requireDestroy$1(),{isNodeStream:r,isReadable:i,isWritable:s,isWebStream:o,isTransformStream:a,isWritableStream:u,isReadableStream:c}=requireUtils$1(),{AbortError:l,codes:{ERR_INVALID_ARG_VALUE:d,ERR_MISSING_ARGS:f}}=requireErrors$1(),m=requireEndOfStream$1();return compose$1=function(...b){if(b.length===0)throw new f("streams");if(b.length===1)return e.from(b[0]);const S=[...b];if(typeof b[0]=="function"&&(b[0]=e.from(b[0])),typeof b[b.length-1]=="function"){const V=b.length-1;b[V]=e.from(b[V])}for(let V=0;V<b.length;++V)if(!(!r(b[V])&&!o(b[V]))){if(V<b.length-1&&!(i(b[V])||c(b[V])||a(b[V])))throw new d(`streams[${V}]`,S[V],"must be readable");if(V>0&&!(s(b[V])||u(b[V])||a(b[V])))throw new d(`streams[${V}]`,S[V],"must be writable")}let w,v,_,T,C;function U(V){const he=T;T=null,he?he(V):V?C.destroy(V):!D&&!re&&C.destroy()}const $=b[0],W=n(b,U),re=!!(s($)||u($)||a($)),D=!!(i(W)||c(W)||a(W));if(C=new e({writableObjectMode:!!($!=null&&$.writableObjectMode),readableObjectMode:!!(W!=null&&W.readableObjectMode),writable:re,readable:D}),re){if(r($))C._write=function(he,z,_e){$.write(he,z)?_e():w=_e},C._final=function(he){$.end(),v=he},$.on("drain",function(){if(w){const he=w;w=null,he()}});else if(o($)){const z=(a($)?$.writable:$).getWriter();C._write=async function(_e,Ce,Fe){try{await z.ready,z.write(_e).catch(()=>{}),Fe()}catch(ze){Fe(ze)}},C._final=async function(_e){try{await z.ready,z.close().catch(()=>{}),v=_e}catch(Ce){_e(Ce)}}}const V=a(W)?W.readable:W;m(V,()=>{if(v){const he=v;v=null,he()}})}if(D){if(r(W))W.on("readable",function(){if(_){const V=_;_=null,V()}}),W.on("end",function(){C.push(null)}),C._read=function(){for(;;){const V=W.read();if(V===null){_=C._read;return}if(!C.push(V))return}};else if(o(W)){const he=(a(W)?W.readable:W).getReader();C._read=async function(){for(;;)try{const{value:z,done:_e}=await he.read();if(!C.push(z))return;if(_e){C.push(null);return}}catch{return}}}}return C._destroy=function(V,he){!V&&T!==null&&(V=new l),_=null,w=null,v=null,T===null?he(V):(T=he,r(W)&&t(W,V))},C},compose$1}var hasRequiredOperators$1;function requireOperators$1(){if(hasRequiredOperators$1)return operators$1;hasRequiredOperators$1=1;const n=globalThis.AbortController||requireBrowser$3().AbortController,{codes:{ERR_INVALID_ARG_VALUE:e,ERR_INVALID_ARG_TYPE:t,ERR_MISSING_ARGS:r,ERR_OUT_OF_RANGE:i},AbortError:s}=requireErrors$1(),{validateAbortSignal:o,validateInteger:a,validateObject:u}=requireValidators$1(),c=requirePrimordials$1().Symbol("kWeak"),l=requirePrimordials$1().Symbol("kResistStopPropagation"),{finished:d}=requireEndOfStream$1(),f=requireCompose$1(),{addAbortSignalNoValidate:m}=requireAddAbortSignal$1(),{isWritable:g,isNodeStream:b}=requireUtils$1(),{deprecate:S}=requireUtil$1(),{ArrayPrototypePush:w,Boolean:v,MathFloor:_,Number:T,NumberIsNaN:C,Promise:U,PromiseReject:$,PromiseResolve:W,PromisePrototypeThen:re,Symbol:D}=requirePrimordials$1(),V=D("kEmpty"),he=D("kEof");function z(te,le){if(le!=null&&u(le,"options"),le?.signal!=null&&o(le.signal,"options.signal"),b(te)&&!g(te))throw new e("stream",te,"must be writable");const Te=f(this,te);return le!=null&&le.signal&&m(le.signal,Te),Te}function _e(te,le){if(typeof te!="function")throw new t("fn",["Function","AsyncFunction"],te);le!=null&&u(le,"options"),le?.signal!=null&&o(le.signal,"options.signal");let Te=1;le?.concurrency!=null&&(Te=_(le.concurrency));let G=Te-1;return le?.highWaterMark!=null&&(G=_(le.highWaterMark)),a(Te,"options.concurrency",1),a(G,"options.highWaterMark",0),G+=Te,(async function*(){const x=requireUtil$1().AbortSignalAny([le?.signal].filter(v)),A=this,O=[],H={signal:x};let Q,de,M=!1,ne=0;function ge(){M=!0,Y()}function Y(){ne-=1,Be()}function Be(){de&&!M&&ne<Te&&O.length<G&&(de(),de=null)}async function Je(){try{for await(let Ne of A){if(M)return;if(x.aborted)throw new s;try{if(Ne=te(Ne,H),Ne===V)continue;Ne=W(Ne)}catch(Ze){Ne=$(Ze)}ne+=1,re(Ne,Y,ge),O.push(Ne),Q&&(Q(),Q=null),!M&&(O.length>=G||ne>=Te)&&await new U(Ze=>{de=Ze})}O.push(he)}catch(Ne){const Ze=$(Ne);re(Ze,Y,ge),O.push(Ze)}finally{M=!0,Q&&(Q(),Q=null)}}Je();try{for(;;){for(;O.length>0;){const Ne=await O[0];if(Ne===he)return;if(x.aborted)throw new s;Ne!==V&&(yield Ne),O.shift(),Be()}await new U(Ne=>{Q=Ne})}}finally{M=!0,de&&(de(),de=null)}}).call(this)}function Ce(te=void 0){return te!=null&&u(te,"options"),te?.signal!=null&&o(te.signal,"options.signal"),(async function*(){let Te=0;for await(const P of this){var G;if(te!=null&&(G=te.signal)!==null&&G!==void 0&&G.aborted)throw new s({cause:te.signal.reason});yield[Te++,P]}}).call(this)}async function Fe(te,le=void 0){for await(const Te of L.call(this,te,le))return!0;return!1}async function ze(te,le=void 0){if(typeof te!="function")throw new t("fn",["Function","AsyncFunction"],te);return!await Fe.call(this,async(...Te)=>!await te(...Te),le)}async function ae(te,le){for await(const Te of L.call(this,te,le))return Te}async function ve(te,le){if(typeof te!="function")throw new t("fn",["Function","AsyncFunction"],te);async function Te(G,P){return await te(G,P),V}for await(const G of _e.call(this,Te,le));}function L(te,le){if(typeof te!="function")throw new t("fn",["Function","AsyncFunction"],te);async function Te(G,P){return await te(G,P)?G:V}return _e.call(this,Te,le)}class ie extends r{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}async function xe(te,le,Te){var G;if(typeof te!="function")throw new t("reducer",["Function","AsyncFunction"],te);Te!=null&&u(Te,"options"),Te?.signal!=null&&o(Te.signal,"options.signal");let P=arguments.length>1;if(Te!=null&&(G=Te.signal)!==null&&G!==void 0&&G.aborted){const Q=new s(void 0,{cause:Te.signal.reason});throw this.once("error",()=>{}),await d(this.destroy(Q)),Q}const x=new n,A=x.signal;if(Te!=null&&Te.signal){const Q={once:!0,[c]:this,[l]:!0};Te.signal.addEventListener("abort",()=>x.abort(),Q)}let O=!1;try{for await(const Q of this){var H;if(O=!0,Te!=null&&(H=Te.signal)!==null&&H!==void 0&&H.aborted)throw new s;P?le=await te(le,Q,{signal:A}):(le=Q,P=!0)}if(!O&&!P)throw new ie}finally{x.abort()}return le}async function ue(te){te!=null&&u(te,"options"),te?.signal!=null&&o(te.signal,"options.signal");const le=[];for await(const G of this){var Te;if(te!=null&&(Te=te.signal)!==null&&Te!==void 0&&Te.aborted)throw new s(void 0,{cause:te.signal.reason});w(le,G)}return le}function De(te,le){const Te=_e.call(this,te,le);return(async function*(){for await(const P of Te)yield*P}).call(this)}function ke(te){if(te=T(te),C(te))return 0;if(te<0)throw new i("number",">= 0",te);return te}function We(te,le=void 0){return le!=null&&u(le,"options"),le?.signal!=null&&o(le.signal,"options.signal"),te=ke(te),(async function*(){var G;if(le!=null&&(G=le.signal)!==null&&G!==void 0&&G.aborted)throw new s;for await(const x of this){var P;if(le!=null&&(P=le.signal)!==null&&P!==void 0&&P.aborted)throw new s;te--<=0&&(yield x)}}).call(this)}function Oe(te,le=void 0){return le!=null&&u(le,"options"),le?.signal!=null&&o(le.signal,"options.signal"),te=ke(te),(async function*(){var G;if(le!=null&&(G=le.signal)!==null&&G!==void 0&&G.aborted)throw new s;for await(const x of this){var P;if(le!=null&&(P=le.signal)!==null&&P!==void 0&&P.aborted)throw new s;if(te-- >0&&(yield x),te<=0)return}}).call(this)}return operators$1.streamReturningOperators={asIndexedPairs:S(Ce,"readable.asIndexedPairs will be removed in a future version."),drop:We,filter:L,flatMap:De,map:_e,take:Oe,compose:z},operators$1.promiseReturningOperators={every:ze,forEach:ve,reduce:xe,toArray:ue,some:Fe,find:ae},operators$1}var promises$1,hasRequiredPromises$1;function requirePromises$1(){if(hasRequiredPromises$1)return promises$1;hasRequiredPromises$1=1;const{ArrayPrototypePop:n,Promise:e}=requirePrimordials$1(),{isIterable:t,isNodeStream:r,isWebStream:i}=requireUtils$1(),{pipelineImpl:s}=requirePipeline$1(),{finished:o}=requireEndOfStream$1();requireStream$1();function a(...u){return new e((c,l)=>{let d,f;const m=u[u.length-1];if(m&&typeof m=="object"&&!r(m)&&!t(m)&&!i(m)){const g=n(u);d=g.signal,f=g.end}s(u,(g,b)=>{g?l(g):c(b)},{signal:d,end:f})})}return promises$1={finished:o,pipeline:a},promises$1}var hasRequiredStream$1;function requireStream$1(){if(hasRequiredStream$1)return stream$1.exports;hasRequiredStream$1=1;const{Buffer:n}=requireBuffer(),{ObjectDefineProperty:e,ObjectKeys:t,ReflectApply:r}=requirePrimordials$1(),{promisify:{custom:i}}=requireUtil$1(),{streamReturningOperators:s,promiseReturningOperators:o}=requireOperators$1(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:a}}=requireErrors$1(),u=requireCompose$1(),{setDefaultHighWaterMark:c,getDefaultHighWaterMark:l}=requireState$1(),{pipeline:d}=requirePipeline$1(),{destroyer:f}=requireDestroy$1(),m=requireEndOfStream$1(),g=requirePromises$1(),b=requireUtils$1(),S=stream$1.exports=requireLegacy$1().Stream;S.isDestroyed=b.isDestroyed,S.isDisturbed=b.isDisturbed,S.isErrored=b.isErrored,S.isReadable=b.isReadable,S.isWritable=b.isWritable,S.Readable=requireReadable$1();for(const v of t(s)){let T=function(...C){if(new.target)throw a();return S.Readable.from(r(_,this,C))};const _=s[v];e(T,"name",{__proto__:null,value:_.name}),e(T,"length",{__proto__:null,value:_.length}),e(S.Readable.prototype,v,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}for(const v of t(o)){let T=function(...C){if(new.target)throw a();return r(_,this,C)};const _=o[v];e(T,"name",{__proto__:null,value:_.name}),e(T,"length",{__proto__:null,value:_.length}),e(S.Readable.prototype,v,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}S.Writable=requireWritable$1(),S.Duplex=requireDuplex$1(),S.Transform=requireTransform$1(),S.PassThrough=requirePassthrough$1(),S.pipeline=d;const{addAbortSignal:w}=requireAddAbortSignal$1();return S.addAbortSignal=w,S.finished=m,S.destroy=f,S.compose=u,S.setDefaultHighWaterMark=c,S.getDefaultHighWaterMark=l,e(S,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return g}}),e(d,i,{__proto__:null,enumerable:!0,get(){return g.pipeline}}),e(m,i,{__proto__:null,enumerable:!0,get(){return g.finished}}),S.Stream=S,S._isUint8Array=function(_){return _ instanceof Uint8Array},S._uint8ArrayToBuffer=function(_){return n.from(_.buffer,_.byteOffset,_.byteLength)},stream$1.exports}var hasRequiredBrowser$1;function requireBrowser$1(){return hasRequiredBrowser$1||(hasRequiredBrowser$1=1,(function(n){const e=requireStream$1(),t=requirePromises$1(),r=e.Readable.destroy;n.exports=e.Readable,n.exports._uint8ArrayToBuffer=e._uint8ArrayToBuffer,n.exports._isUint8Array=e._isUint8Array,n.exports.isDisturbed=e.isDisturbed,n.exports.isErrored=e.isErrored,n.exports.isReadable=e.isReadable,n.exports.Readable=e.Readable,n.exports.Writable=e.Writable,n.exports.Duplex=e.Duplex,n.exports.Transform=e.Transform,n.exports.PassThrough=e.PassThrough,n.exports.addAbortSignal=e.addAbortSignal,n.exports.finished=e.finished,n.exports.destroy=e.destroy,n.exports.destroy=r,n.exports.pipeline=e.pipeline,n.exports.compose=e.compose,Object.defineProperty(e,"promises",{configurable:!0,enumerable:!0,get(){return t}}),n.exports.Stream=e.Stream,n.exports.default=n.exports})(browser$3)),browser$3.exports}var browserExports$1=requireBrowser$1();const ITERATOR$1=Symbol("iter");function merge$2(n,e,t=4){if(t===0)return Object.assign(n,e);for(const r in e)n[r]=merge$2(n[r]||Object.create(null),e[r],t-1);return n}function intersect$1(n,e,t=4){let r=!1;for(const i in n)if(i in e){const s=t===0?null:intersect$1(n[i],e[i],t-1);if(s!==!1)r=r||Object.create(null),r[i]=s;else if(t===3)return!1}return r}function difference$1(n,e,t=4){let r=!1;for(const i in n)if(!(i in e))r=r||Object.create(null),r[i]=t===0?null:merge$2({},n[i],t-1);else if(t!==0){const s=difference$1(n[i],e[i],t-1);if(s!==!1)r=r||Object.create(null),r[i]=s;else if(t===3)return!1}return r}let N3EntityIndex$1=class{constructor(e={}){this._id=1,this._ids=Object.create(null),this._ids[""]=1,this._entities=Object.create(null),this._entities[1]="",this._blankNodeIndex=0,this._factory=e.factory||DataFactory$2}_termFromId(e){if(e[0]==="."){const t=this._entities,r=e.split(".");return this._factory.quad(this._termFromId(t[r[1]]),this._termFromId(t[r[2]]),this._termFromId(t[r[3]]),r[4]&&this._termFromId(t[r[4]]))}return termFromId$1(e,this._factory)}_termToNumericId(e){if(e.termType==="Quad"){const t=this._termToNumericId(e.subject),r=this._termToNumericId(e.predicate),i=this._termToNumericId(e.object);let s;return t&&r&&i&&(isDefaultGraph$1(e.graph)||(s=this._termToNumericId(e.graph)))&&this._ids[s?`.${t}.${r}.${i}.${s}`:`.${t}.${r}.${i}`]}return this._ids[termToId$1(e)]}_termToNewNumericId(e){const t=e&&e.termType==="Quad"?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${isDefaultGraph$1(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:termToId$1(e);return this._ids[t]||(this._ids[this._entities[++this._id]=t]=this._id)}createBlankNode(e){let t,r;if(e)for(t=e=`_:${e}`,r=1;this._ids[t];)t=e+r++;else do t=`_:b${this._blankNodeIndex++}`;while(this._ids[t]);return this._ids[t]=++this._id,this._entities[this._id]=t,this._factory.blankNode(t.substr(2))}},N3Store$1=class dr{constructor(e,t){this._size=0,this._graphs=Object.create(null),!t&&e&&!e[0]&&typeof e.match!="function"&&(t=e,e=null),t=t||{},this._factory=t.factory||DataFactory$2,this._entityIndex=t.entityIndex||new N3EntityIndex$1({factory:this._factory}),this._entities=this._entityIndex._entities,this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex),this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex),this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex),e&&this.addAll(e)}get size(){let e=this._size;if(e!==null)return e;e=0;const t=this._graphs;let r,i;for(const s in t)for(const o in r=t[s].subjects)for(const a in i=r[o])e+=Object.keys(i[a]).length;return this._size=e}_addToIndex(e,t,r,i){const s=e[t]||(e[t]={}),o=s[r]||(s[r]={}),a=i in o;return a||(o[i]=null),!a}_removeFromIndex(e,t,r,i){const s=e[t],o=s[r];delete o[i];for(const a in o)return;delete s[r];for(const a in s)return;delete e[t]}*_findInIndex(e,t,r,i,s,o,a,u){let c,l,d;const f=this._entities,m=this._termFromId(f[u]),g={subject:null,predicate:null,object:null};t&&((c=e,e={})[t]=c[t]);for(const b in e)if(l=e[b]){g[s]=this._termFromId(f[b]),r&&((c=l,l={})[r]=c[r]);for(const S in l)if(d=l[S]){g[o]=this._termFromId(f[S]);const w=i?i in d?[i]:[]:Object.keys(d);for(let v=0;v<w.length;v++)g[a]=this._termFromId(f[w[v]]),yield this._factory.quad(g.subject,g.predicate,g.object,m)}}}_loop(e,t){for(const r in e)t(r)}_loopByKey0(e,t,r){let i,s;if(i=e[t])for(s in i)r(s)}_loopByKey1(e,t,r){let i,s;for(i in e)s=e[i],s[t]&&r(i)}_loopBy2Keys(e,t,r,i){let s,o,a;if((s=e[t])&&(o=s[r]))for(a in o)i(a)}_countInIndex(e,t,r,i){let s=0,o,a,u;t&&((o=e,e={})[t]=o[t]);for(const c in e)if(a=e[c]){r&&((o=a,a={})[r]=o[r]);for(const l in a)(u=a[l])&&(i?i in u&&s++:s+=Object.keys(u).length)}return s}_getGraphs(e){return e=e===""?1:e&&(this._termToNumericId(e)||-1),typeof e!="number"?this._graphs:{[e]:this._graphs[e]}}_uniqueEntities(e){const t=Object.create(null);return r=>{r in t||(t[r]=!0,e(this._termFromId(this._entities[r],this._factory)))}}add(e){return this.addQuad(e),this}addQuad(e,t,r,i){t||(i=e.graph,r=e.object,t=e.predicate,e=e.subject),i=i?this._termToNewNumericId(i):1;let s=this._graphs[i];return s||(s=this._graphs[i]={subjects:{},predicates:{},objects:{}},Object.freeze(s)),e=this._termToNewNumericId(e),t=this._termToNewNumericId(t),r=this._termToNewNumericId(r),this._addToIndex(s.subjects,e,t,r)?(this._addToIndex(s.predicates,t,r,e),this._addToIndex(s.objects,r,e,t),this._size=null,!0):!1}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}delete(e){return this.removeQuad(e),this}has(e,t,r,i){return e&&e.subject&&({subject:e,predicate:t,object:r,graph:i}=e),!this.readQuads(e,t,r,i).next().done}import(e){return e.on("data",t=>{this.addQuad(t)}),e}removeQuad(e,t,r,i){t||({subject:e,predicate:t,object:r,graph:i}=e),i=i?this._termToNumericId(i):1;const s=this._graphs;let o,a,u;if(!(e=e&&this._termToNumericId(e))||!(t=t&&this._termToNumericId(t))||!(r=r&&this._termToNumericId(r))||!(o=s[i])||!(a=o.subjects[e])||!(u=a[t])||!(r in u))return!1;this._removeFromIndex(o.subjects,e,t,r),this._removeFromIndex(o.predicates,t,r,e),this._removeFromIndex(o.objects,r,e,t),this._size!==null&&this._size--;for(e in o.subjects)return!0;return delete s[i],!0}removeQuads(e){for(let t=0;t<e.length;t++)this.removeQuad(e[t])}remove(e){return e.on("data",t=>{this.removeQuad(t)}),e}removeMatches(e,t,r,i){const s=new browserExports$1.Readable({objectMode:!0}),o=this.readQuads(e,t,r,i);return s._read=a=>{for(;--a>=0;){const{done:u,value:c}=o.next();if(u){s.push(null);return}s.push(c)}},this.remove(s)}deleteGraph(e){return this.removeMatches(null,null,null,e)}getQuads(e,t,r,i){return[...this.readQuads(e,t,r,i)]}*readQuads(e,t,r,i){const s=this._getGraphs(i);let o,a,u,c;if(!(e&&!(a=this._termToNumericId(e))||t&&!(u=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(const l in s)(o=s[l])&&(a?c?yield*this._findInIndex(o.objects,c,a,u,"object","subject","predicate",l):yield*this._findInIndex(o.subjects,a,u,null,"subject","predicate","object",l):u?yield*this._findInIndex(o.predicates,u,c,null,"predicate","object","subject",l):c?yield*this._findInIndex(o.objects,c,null,null,"object","subject","predicate",l):yield*this._findInIndex(o.subjects,null,null,null,"subject","predicate","object",l))}match(e,t,r,i){return new DatasetCoreAndReadableStream$1(this,e,t,r,i,{entityIndex:this._entityIndex})}countQuads(e,t,r,i){const s=this._getGraphs(i);let o=0,a,u,c,l;if(e&&!(u=this._termToNumericId(e))||t&&!(c=this._termToNumericId(t))||r&&!(l=this._termToNumericId(r)))return 0;for(const d in s)(a=s[d])&&(e?r?o+=this._countInIndex(a.objects,l,u,c):o+=this._countInIndex(a.subjects,u,c,l):t?o+=this._countInIndex(a.predicates,c,l,u):o+=this._countInIndex(a.objects,l,u,c));return o}forEach(e,t,r,i,s){this.some(o=>(e(o,this),!1),t,r,i,s)}every(e,t,r,i,s){return!this.some(o=>!e(o,this),t,r,i,s)}some(e,t,r,i,s){for(const o of this.readQuads(t,r,i,s))if(e(o,this))return!0;return!1}getSubjects(e,t,r){const i=[];return this.forSubjects(s=>{i.push(s)},e,t,r),i}forSubjects(e,t,r,i){const s=this._getGraphs(i);let o,a,u;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(u=this._termToNumericId(r))))for(i in s)(o=s[i])&&(a?u?this._loopBy2Keys(o.predicates,a,u,e):this._loopByKey1(o.subjects,a,e):u?this._loopByKey0(o.objects,u,e):this._loop(o.subjects,e))}getPredicates(e,t,r){const i=[];return this.forPredicates(s=>{i.push(s)},e,t,r),i}forPredicates(e,t,r,i){const s=this._getGraphs(i);let o,a,u;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(u=this._termToNumericId(r))))for(i in s)(o=s[i])&&(a?u?this._loopBy2Keys(o.objects,u,a,e):this._loopByKey0(o.subjects,a,e):u?this._loopByKey1(o.predicates,u,e):this._loop(o.predicates,e))}getObjects(e,t,r){const i=[];return this.forObjects(s=>{i.push(s)},e,t,r),i}forObjects(e,t,r,i){const s=this._getGraphs(i);let o,a,u;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(u=this._termToNumericId(r))))for(i in s)(o=s[i])&&(a?u?this._loopBy2Keys(o.subjects,a,u,e):this._loopByKey1(o.objects,a,e):u?this._loopByKey0(o.predicates,u,e):this._loop(o.objects,e))}getGraphs(e,t,r){const i=[];return this.forGraphs(s=>{i.push(s)},e,t,r),i}forGraphs(e,t,r,i){for(const s in this._graphs)this.some(o=>(e(o.graph),!0),t,r,i,this._termFromId(this._entities[s]))}createBlankNode(e){return this._entityIndex.createBlankNode(e)}extractLists({remove:e=!1,ignoreErrors:t=!1}={}){const r={},i=t?(()=>!0):((a,u)=>{throw new Error(`${a.value} ${u}`)}),s=this.getQuads(null,namespaces$2.rdf.rest,namespaces$2.rdf.nil,null),o=e?[...s]:[];return s.forEach(a=>{const u=[];let c=!1,l,d;const f=a.graph;let m=a.subject;for(;m&&!c;){const g=this.getQuads(null,null,m,null),b=this.getQuads(m,null,null,null);let S,w=null,v=null,_=null;for(let T=0;T<b.length&&!c;T++)S=b[T],S.graph.equals(f)?l?c=i(m,"has non-list arcs out"):S.predicate.value===namespaces$2.rdf.first?w?c=i(m,"has multiple rdf:first arcs"):o.push(w=S):S.predicate.value===namespaces$2.rdf.rest?v?c=i(m,"has multiple rdf:rest arcs"):o.push(v=S):g.length?c=i(m,"can't be subject and object"):(l=S,d="subject"):c=i(m,"not confined to single graph");for(let T=0;T<g.length&&!c;++T)S=g[T],l?c=i(m,"can't have coreferences"):S.predicate.value===namespaces$2.rdf.rest?_?c=i(m,"has incoming rdf:rest arcs"):_=S:(l=S,d="object");w?u.unshift(w.object):c=i(m,"has no list head"),m=_&&_.subject}c?e=!1:l&&(r[l[d].value]=u)}),e&&this.removeQuads(o),r}addAll(e){if(e instanceof DatasetCoreAndReadableStream$1&&(e=e.filtered),Array.isArray(e))this.addQuads(e);else if(e instanceof dr&&e._entityIndex===this._entityIndex)e._size!==0&&(this._graphs=merge$2(this._graphs,e._graphs),this._size=null);else for(const t of e)this.add(t);return this}contains(e){if(e instanceof DatasetCoreAndReadableStream$1&&(e=e.filtered),e===this)return!0;if(!(e instanceof dr)||this._entityIndex!==e._entityIndex)return e.every(c=>this.has(c));const t=this._graphs,r=e._graphs;let i,s,o,a,u;for(const c in r){if(!(i=t[c]))return!1;i=i.subjects;for(const l in s=r[c].subjects){if(!(o=i[l]))return!1;for(const d in a=s[l]){if(!(u=o[d]))return!1;for(const f in a[d])if(!(f in u))return!1}}}return!0}deleteMatches(e,t,r,i){for(const s of this.match(e,t,r,i))this.removeQuad(s);return this}difference(e){if(e&&e instanceof DatasetCoreAndReadableStream$1&&(e=e.filtered),e===this)return new dr({entityIndex:this._entityIndex});if(e instanceof dr&&e._entityIndex===this._entityIndex){const t=new dr({entityIndex:this._entityIndex}),r=difference$1(this._graphs,e._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter(t=>!e.has(t))}equals(e){return e instanceof DatasetCoreAndReadableStream$1&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new dr({entityIndex:this._entityIndex});for(const r of this)e(r,this)&&t.add(r);return t}intersection(e){if(e instanceof DatasetCoreAndReadableStream$1&&(e=e.filtered),e===this){const t=new dr({entityIndex:this._entityIndex});return t._graphs=merge$2(Object.create(null),this._graphs),t._size=this._size,t}else if(e instanceof dr&&this._entityIndex===e._entityIndex){const t=new dr({entityIndex:this._entityIndex}),r=intersect$1(e._graphs,this._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter(t=>e.has(t))}map(e){const t=new dr({entityIndex:this._entityIndex});for(const r of this)t.add(e(r,this));return t}reduce(e,t){const r=this.readQuads();let i=t===void 0?r.next().value:t;for(const s of r)i=e(i,s,this);return i}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match()}toString(){return new N3Writer$1().quadsToString(this)}union(e){const t=new dr({entityIndex:this._entityIndex});return t._graphs=merge$2(Object.create(null),this._graphs),t._size=this._size,t.addAll(e),t}*[Symbol.iterator](){yield*this.readQuads()}};function indexMatch$1(n,e,t=0){const r=e[t];if(r&&!(r in n))return!1;let i=!1;for(const s in r?{[r]:n[r]}:n){const o=t===2?null:indexMatch$1(n[s],e,t+1);o!==!1&&(i=i||Object.create(null),i[s]=o)}return i}let DatasetCoreAndReadableStream$1=class Ln extends browserExports$1.Readable{constructor(e,t,r,i,s,o){super({objectMode:!0}),Object.assign(this,{n3Store:e,subject:t,predicate:r,object:i,graph:s,options:o})}get filtered(){if(!this._filtered){const{n3Store:e,graph:t,object:r,predicate:i,subject:s}=this,o=this._filtered=new N3Store$1({factory:e._factory,entityIndex:this.options.entityIndex});let a,u,c;if(s&&!(a=o._termToNumericId(s))||i&&!(u=o._termToNumericId(i))||r&&!(c=o._termToNumericId(r)))return o;const l=e._getGraphs(t);for(const d in l){let f,m,g,b;(b=l[d])&&(!a&&u?(m=indexMatch$1(b.predicates,[u,c,a]))&&(f=indexMatch$1(b.subjects,[a,u,c]),g=indexMatch$1(b.objects,[c,a,u])):c?(g=indexMatch$1(b.objects,[c,a,u]))&&(f=indexMatch$1(b.subjects,[a,u,c]),m=indexMatch$1(b.predicates,[u,c,a])):(f=indexMatch$1(b.subjects,[a,u,c]))&&(m=indexMatch$1(b.predicates,[u,c,a]),g=indexMatch$1(b.objects,[c,a,u])),f&&(o._graphs[d]={subjects:f,predicates:m,objects:g}))}o._size=null}return this._filtered}get size(){return this.filtered.size}_read(e){e>0&&!this[ITERATOR$1]&&(this[ITERATOR$1]=this[Symbol.iterator]());const t=this[ITERATOR$1];for(;--e>=0;){const{done:r,value:i}=t.next();if(r){this.push(null);return}this.push(i)}}addAll(e){return this.filtered.addAll(e)}contains(e){return this.filtered.contains(e)}deleteMatches(e,t,r,i){return this.filtered.deleteMatches(e,t,r,i)}difference(e){return this.filtered.difference(e)}equals(e){return this.filtered.equals(e)}every(e,t,r,i,s){return this.filtered.every(e,t,r,i,s)}filter(e){return this.filtered.filter(e)}forEach(e,t,r,i,s){return this.filtered.forEach(e,t,r,i,s)}import(e){return this.filtered.import(e)}intersection(e){return this.filtered.intersection(e)}map(e){return this.filtered.map(e)}some(e,t,r,i,s){return this.filtered.some(e,t,r,i,s)}toCanonical(){return this.filtered.toCanonical()}toStream(){return this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph)}union(e){return this._filtered?this._filtered.union(e):this.n3Store.match(this.subject,this.predicate,this.object,this.graph).addAll(e)}toArray(){return this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(e,t){return this.filtered.reduce(e,t)}toString(){return new N3Writer$1().quadsToString(this)}add(e){return this.filtered.add(e)}delete(e){return this.filtered.delete(e)}has(e){return this.filtered.has(e)}match(e,t,r,i){return new Ln(this.filtered,e,t,r,i,this.options)}*[Symbol.iterator](){yield*this._filtered||this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}};var _a$8;function isRecord$1(n){return typeof n=="object"&&n!==null}function isPodTable(n){return isRecord$1(n)&&"columns"in n&&"config"in n}function hasStringValue$1(n){return isRecord$1(n)&&typeof n.value=="string"}function isAbsoluteIri(n){return n.startsWith("http://")||n.startsWith("https://")}function normalizePodBase(n){return n.endsWith("/")?n:`${n}/`}function normalizeBaseRelativePath(n){return n.replace(/^\/+/u,"")}function hasDuplicatePathComposition(n){const t=n.split("#")[0].replace(/^https?:\/\/[^/]+/u,"").split("/").filter(Boolean);for(let r=0;r<t.length;r++)for(let i=2;r+i*2<=t.length;i++){const s=t.slice(r,r+i).join("/"),o=t.slice(r+i,r+i*2).join("/");if(s===o)return!0}return!1}function isBaseRelativeSubjectId(n){return!n||isAbsoluteIri(n)||n.startsWith("/")?!1:n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(n)}function isTimeLocatorKey(n){return["yyyy","MM","dd","HH","mm","ss","timestamp"].includes(n)}function parseTemplateVariableField(n){return n.split("|").map(e=>e.trim()).filter(Boolean)[0]??n}function escapeSparqlString(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r")}function hasTimeLocatorContext(n){return n.createdAt!==void 0||n.created_at!==void 0||n.dateCreated!==void 0}function getKnownRowIri(n){for(const e of["@id","subject","uri","source"]){const t=n[e];if(typeof t=="string"&&isAbsoluteIri(t))return t}}class PodDatabase{constructor(e,t,r){this.dialect=e,this.session=t,this.schema=r,this.notificationsClient=null,this.federatedExecutor=null,this.lastFederatedErrors=[]}getLastFederatedErrors(){return this.lastFederatedErrors}clearFederatedErrors(){this.lastFederatedErrors=[]}getFederatedExecutor(){return this.federatedExecutor||(this.federatedExecutor=new FederatedQueryExecutor({fetch:this.dialect.getAuthenticatedFetch()})),this.federatedExecutor}createTable(e,t){const r=e.table("default",t);return t.hooks&&(r.config.hooks=t.hooks),Reflect.set(r,"_db",this),r}select(e){return this.session.select(e)}insert(e){return this.session.insert(e)}update(e){return this.session.update(e)}delete(e){return this.session.delete(e)}resolvePodFileUrl(e){if(!e||typeof e!="string")throw new Error("resource file path must be a non-empty string");if(isAbsoluteIri(e))return e;const t=this.dialect.getPodUrl;if(typeof t!="function")throw new Error("Cannot resolve Pod file path because dialect.getPodUrl is not available");return new URL(normalizeBaseRelativePath(e),normalizePodBase(t.call(this.dialect))).toString()}getResourceFileInputs(e){const t=[];e.document&&t.push({...e.document,relationField:e.document.relationField??"document"}),e.source&&t.push({...e.source,relationField:e.source.relationField??"source"});for(const r of e.files??[])t.push({...r,relationField:r.relationField??"document"});return t}validateNoDuplicatePathComposition(e){const t=e.find(hasDuplicatePathComposition);if(t)throw new Error(`duplicate path composition detected: ${t}`)}async dryRunResourceWithDocument(e,t){if(!isRecord$1(t.row)||Array.isArray(t.row))throw new Error("dryRunResourceWithDocument requires a row object");const r=this.resolveRowIri(e,t.row),i=t.row.id,s=typeof i=="string"&&!isAbsoluteIri(i)?i:this.resolveRowId(e,t.row),o={...t.row},a=[],u=[s];for(const c of this.getResourceFileInputs(t)){const l=c.url??c.path;if(!l)throw new Error(`resource file '${c.relationField}' requires path or url`);u.push(l);const d=this.resolvePodFileUrl(l);o[c.relationField]=d,a.push({relationField:c.relationField,url:d,...c.contentType?{contentType:c.contentType}:{}})}return this.validateNoDuplicatePathComposition(u),{ok:!0,resourceId:s,resourceIri:r,row:o,rdfMutations:[{type:"upsert",subject:r,fields:Object.keys(o)}],fileWrites:a,warnings:[],errors:[]}}async upsertResourceWithDocument(e,t){const r=await this.dryRunResourceWithDocument(e,t),i=this.dialect.getAuthenticatedFetch(),s=[];try{for(const o of this.getResourceFileInputs(t)){const a=o.url??o.path;if(!a)throw new Error(`resource file '${o.relationField}' requires path or url`);const u=this.resolvePodFileUrl(a),c={};o.contentType&&(c["content-type"]=o.contentType);const l=await i(u,{method:"PUT",headers:c,body:o.content??""});if(!l.ok)throw new Error(`Failed to write resource file ${u}: HTTP ${l.status}`);s.push(u)}return await this.insert(e).values(r.row).execute(),r}catch(o){for(const a of s.reverse())try{await i(a,{method:"DELETE"})}catch{}throw o}}async moveDocumentAndRelink(e,t){const r=t.relationField??"document",i=t.fromUrl??(t.fromPath?this.resolvePodFileUrl(t.fromPath):void 0),s=t.toUrl??t.toPath;if(!s)throw new Error("moveDocumentAndRelink requires toPath or toUrl");const o=this.resolvePodFileUrl(s);this.validateNoDuplicatePathComposition([t.id,s]);const a=this.dialect.getAuthenticatedFetch();let u=t.content??null,c=t.contentType;if(u===null&&i){const f=await a(i,{method:"GET"});if(!f.ok)throw new Error(`Failed to read source document ${i}: HTTP ${f.status}`);u=await f.blob(),c=c??f.headers.get("content-type")??void 0}if(u===null)throw new Error("moveDocumentAndRelink requires content when fromPath/fromUrl is not provided");const l={};c&&(l["content-type"]=c);const d=await a(o,{method:"PUT",headers:l,body:u});if(!d.ok)throw new Error(`Failed to write destination document ${o}: HTTP ${d.status}`);try{const f=await this.updateById(e,t.id,{[r]:o});return i&&i!==o&&await a(i,{method:"DELETE"}),{fromUrl:i,toUrl:o,resource:f}}catch(f){try{await a(o,{method:"DELETE"})}catch{}throw f}}async deleteResourceWithDocument(e,t){const r=t.relationField??"document",i=await this.findById(e,t.id),s=t.url??(t.path?this.resolvePodFileUrl(t.path):void 0)??(typeof i?.[r]=="string"?i[r]:void 0),o=await this.deleteById(e,t.id);if(o&&s){const a=await this.dialect.getAuthenticatedFetch()(s,{method:"DELETE"});if(!a.ok&&a.status!==404)throw new Error(`Failed to delete resource file ${s}: HTTP ${a.status}`)}return{deleted:o,fileUrl:s}}async execute(e){return await this.executeSPARQL(e)}async executeSPARQL(e){if(typeof e!="string"||e.trim().length===0)throw new Error("executeSPARQL requires a non-empty SPARQL query string");return await this.dialect.executeSPARQL(e)}async batch(e){const t=[];for(const r of e)t.push(await r);return t}async findFirst(e,t){const r=this.select().from(e).limit(1);t&&Object.keys(t).length>0&&r.where(t);const i=await r;return i.length>0?i[0]:null}getLocatorTemplate(e){return e.getSubjectTemplate?.()??e.config?.subjectTemplate}getRequiredLocatorKeys(e){const t=this.getLocatorTemplate(e);if(!t)return["id"];const r=Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>parseTemplateVariableField(i[1])).filter(i=>i!=="index");return Array.from(new Set(r))}resolveResourceTargetIri(e,t,r){if(typeof t=="string")return isAbsoluteIri(t)?t:this.resolveLocatorSubject(e,{id:t},r);if(!isRecord$1(t)||Array.isArray(t))throw new Error(`${r} requires a resource IRI, base-relative id, row, or locator object`);const i=getKnownRowIri(t);return i||this.resolveLocatorSubject(e,t,r)}resolveLocatorSubject(e,t,r){if(!isRecord$1(t)||Array.isArray(t))throw new Error(`${r} requires a locator object`);if("@id"in t)throw new Error(`${r} does not accept '@id'. Use ${this.getIriAlternative(r)} instead.`);const i=t.id;if(typeof i=="string"&&isAbsoluteIri(i))throw new Error(`${r} does not accept a full IRI in locator.id. Use ${this.getIriAlternative(r)} instead.`);const s=this.getRequiredLocatorKeys(e),o=this.dialect.getResolver(e),a=hasTimeLocatorContext(t),u=s.filter(c=>t[c]!==void 0&&t[c]!==null?!1:!(a&&isTimeLocatorKey(c)));if(typeof i=="string"&&isBaseRelativeSubjectId(i)){const c=s.filter(l=>l!=="id");if(i.startsWith("#")&&c.length>0){const l=this.getLocatorTemplate(e)??"<exact-id>";throw new Error(`${r} requires a complete locator for subjectTemplate '${l}'. Missing [${c.join(", ")}]. Use a base-relative resource id that includes every storage slot.`)}return o.resolveSubject(e,t)}if(u.length>0){const c=this.getLocatorTemplate(e)??"<exact-id>";throw new Error(`${r} requires a complete locator for subjectTemplate '${c}'. Missing [${u.join(", ")}]. Use ${this.getIriAlternative(r)} when you already have a full IRI.`)}return o.resolveSubject(e,t)}resolveIdSubject(e,t,r){if(!t||typeof t!="string")throw new Error(`${r} requires a valid base-relative resource id string`);if(isAbsoluteIri(t))throw new Error(`${r} requires a base-relative resource id. Use ${this.getIriAlternative(r)} for full IRIs.`);const i=this.getLocatorTemplate(e)??"<exact-id>",s=this.getRequiredLocatorKeys(e).filter(a=>a!=="id"),o=this.dialect.getResolver(e);if(isBaseRelativeSubjectId(t)){if(t.startsWith("#")&&s.length>0)throw new Error(`${r} requires a base-relative resource id for subjectTemplate '${i}', got local fragment id '${t}'. Missing [${s.join(", ")}]. Use a base-relative id that includes every storage slot.`);return o.resolveSubject(e,{id:t.startsWith("#")?t.slice(1):t})}if(s.length>0)throw new Error(`${r} requires a base-relative resource id for subjectTemplate '${i}', got local id '${t}'. Missing [${s.join(", ")}]. Use a base-relative id that includes every storage slot.`);return o.resolveSubject(e,{id:t})}warnFindByLocatorDeprecation(){PodDatabase.findByLocatorDeprecationWarned||(PodDatabase.findByLocatorDeprecationWarned=!0,console.warn("[drizzle-solid] findByLocator(resource, locator) is deprecated and will be removed in a future release. Use findById(resource, id) for base-relative resource ids, findByResource(resource, target) for generic exact targets, or findByIri(resource, iri) for full IRIs."))}getIriAlternative(e){return e==="resolveLocatorIri"||e==="resolveLocatorId"?"the full IRI directly":e==="findById"||e==="findByResource"?"findByIri(resource, iri)":e==="updateById"||e==="updateByResource"?"updateByIri(resource, iri, data)":e==="deleteById"||e==="deleteByResource"?"deleteByIri(resource, iri)":`${e.replace("Locator","Iri")}(resource, iri)`}resolveLocatorIri(e,t){return this.resolveLocatorSubject(e,t,"resolveLocatorIri")}resolveLocatorId(e,t){const r=this.resolveLocatorSubject(e,t,"resolveLocatorId");return this.resolveBaseRelativeResourceId(e,r)}resolveResourceIri(e,t){return this.resolveResourceTargetIri(e,t,"resolveResourceIri")}resolveResourceId(e,t){const r=this.resolveResourceTargetIri(e,t,"resolveResourceId");return this.resolveBaseRelativeResourceId(e,r)}resolveRelationIri(e,t){return this.resolveResourceTargetIri(e,t,"resolveRelationIri")}resolveRowIri(e,t){if(!isRecord$1(t)||Array.isArray(t))throw new Error("resolveRowIri requires a row object");return getKnownRowIri(t)??this.resolveLocatorSubject(e,t,"resolveRowIri")}resolveRowId(e,t){if(!isRecord$1(t)||Array.isArray(t))throw new Error("resolveRowId requires a row object");const r=getKnownRowIri(t)??this.resolveLocatorSubject(e,t,"resolveRowId");return this.resolveBaseRelativeResourceId(e,r)}resolveBaseRelativeResourceId(e,t){return parsePodResourceRef(e,t)?.resourceId??this.dialect.getResolver(e).parseId(e,t)}needsShortIdSubjectLookup(e,t){return!t||typeof t!="string"||isAbsoluteIri(t)||isBaseRelativeSubjectId(t)?!1:this.getRequiredLocatorKeys(e).some(r=>r!=="id")}buildShortIdSubjectSuffix(e,t){const r=this.getLocatorTemplate(e)??"<exact-id>",i=Array.from(r.matchAll(/\{([^}]+)\}/g));let s=-1;for(let d=i.length-1;d>=0;d--)if(parseTemplateVariableField(i[d][1])==="id"){s=d;break}if(s<0)return t;const o=i[s],a=i[s-1],u=a?.index===void 0?0:a.index+a[0].length,c=o.index??0,l=c+o[0].length;return`${r.slice(u,c)}${t}${r.slice(l)}`}resolveShortIdLookupSource(e){const t=this.dialect;if(typeof t.resolveTableResource=="function"){const r=t.resolveTableResource(e);if(r.mode==="sparql"&&r.endpoint)return{kind:"sparql",resourceUrl:r.endpoint,descriptor:r}}return null}extractSubjectFromLookupRow(e){if(!isRecord$1(e))return null;const t=e.subject??e.s??e["?subject"]??e["?s"];return typeof t=="string"?t:hasStringValue$1(t)?t.value:null}subjectMatchesShortId(e,t,r,i){const s=parsePodResourceRef(e,t);return s?s.templateValues.id===r:t.endsWith(i)}getIndexedSubject(e,t){const r=this.dialect;return typeof r.lookupIndexedResourceSubject!="function"?null:r.lookupIndexedResourceSubject(e,t)}async lookupSubjectIriByShortId(e,t,r){const i=this.resolveShortIdLookupSource(e);if(!i){const d=this.getLocatorTemplate(e)??"<exact-id>";throw new Error(`${r} cannot resolve short id '${t}' for subjectTemplate '${d}' because no resource query source is available.`)}const s=this.buildShortIdSubjectSuffix(e,t),o=t,u={type:"SELECT",query:`SELECT DISTINCT ?subject WHERE {
|
|
29
|
+
${e.config?.type?`?subject ?typePredicate ?typeObject .
|
|
30
|
+
FILTER(?typePredicate = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> && ?typeObject = <${e.config.type}> && CONTAINS(STR(?subject), "${escapeSparqlString(o)}"))`:`?subject ?predicate ?object .
|
|
31
|
+
FILTER(CONTAINS(STR(?subject), "${escapeSparqlString(o)}"))`}
|
|
32
|
+
}
|
|
33
|
+
LIMIT 50`,prefixes:{}},c=i.kind==="sparql"?await this.dialect.executeOnResource(i.resourceUrl,u,i.descriptor):await this.dialect.getSPARQLExecutor().queryContainer(i.resourceUrl,u),l=Array.from(new Set(c.map(d=>this.extractSubjectFromLookupRow(d)).filter(d=>!!d).filter(d=>this.subjectMatchesShortId(e,d,t,s))));if(l.length>1)throw new Error(`${r} found multiple resources for short id '${t}' in '${e.config?.name??"resource"}'. Use a base-relative resource id or full IRI to disambiguate.`);return l[0]??this.getIndexedSubject(e,t)}async resolveIdSubjectForExactOperation(e,t,r){return this.needsShortIdSubjectLookup(e,t)?await this.lookupSubjectIriByShortId(e,t,r):this.resolveIdSubject(e,t,r)}async findById(e,t){const r=await this.resolveIdSubjectForExactOperation(e,t,"findById");return r?await this.findByIri(e,r):null}async findByLocator(e,t){this.warnFindByLocatorDeprecation();const r=this.resolveLocatorSubject(e,t,"findByLocator");return await this.findByIri(e,r)}async findByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.findById(e,t);const r=this.resolveResourceTargetIri(e,t,"findByResource");return await this.findByIri(e,r)}async findByIri(e,t){if(!t||typeof t!="string")throw new Error("findByIri requires a valid IRI string");const r=await this.findByIriViaExactResource(e,t);return r!==void 0?r:(await this.session.select().from(e).whereByIri(t).limit(1))[0]??null}getColumnPredicate(e,t){return t.options?.predicate??t.getPredicate?.(e.config.namespace)}async findByIriViaExactResource(e,t){if(!isPodTable(e))return;const r=this.parseIri(t).documentUrl,i=await this.readPredicateObjectRowsFromDocument(r,t);if(i===null)return null;if(i!==void 0){const u=this.mapPredicateObjectRows(e,t,i);if(u!==void 0)return u}if(typeof this.dialect.executeOnResource!="function")return;const s={type:"SELECT",query:`SELECT ?p ?o WHERE { <${t}> ?p ?o . }`,prefixes:{}};let o;try{o=await this.dialect.executeOnResource(r,s)}catch(u){if(this.isMissingExactResourceError(u))return;throw u}const a=this.mapPredicateObjectRows(e,t,o);if(a!==void 0)return a}async readPredicateObjectRowsFromDocument(e,t){const r=this.dialect.getAuthenticatedFetch;if(typeof r!="function")return;let i;try{i=await r.call(this.dialect)(e,{method:"GET",headers:{Accept:"text/turtle, application/ld+json;q=0.8, */*;q=0.1"}})}catch(a){return this.isMissingExactResourceError(a)?null:void 0}if(i.status===404)return null;if(!i.ok)return;const s=i.headers.get("content-type")??"";if(s&&!s.includes("text/turtle")&&!s.includes("application/n-triples")&&!s.includes("application/trig")&&!s.includes("application/ld+json"))return;const o=await i.text();if(!o.trim())return null;try{return new N3Parser$1({baseIRI:e,format:s.includes("application/n-triples")?"N-Triples":"text/turtle"}).parse(o).filter(c=>c.subject.termType==="NamedNode"&&c.subject.value===t).map(c=>({p:c.predicate.value,o:this.convertRdfTermToValue(c.object)}))}catch{return}}convertRdfTermToValue(e){if(e.termType==="NamedNode")return e.value;if(e.termType==="BlankNode")return`_:${e.value}`;if(e.termType!=="Literal")return e.value;const t=e.datatype?.value??"";if(t.includes("#integer")||t.includes("#int"))return parseInt(e.value,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e.value);if(t.includes("#boolean"))return e.value==="true";if(t.includes("#dateTime"))return new Date(e.value);if(t.includes("#json"))try{return JSON.parse(e.value)}catch{return e.value}return e.value}isMissingExactResourceError(e){if(!isRecord$1(e))return!1;if((e.status??e.statusCode)===404)return!0;const r=e.message;return typeof r=="string"&&/\b(?:HTTP status )?404\b/.test(r)}mapPredicateObjectRows(e,t,r){if(!Array.isArray(r)||r.length===0)return null;const i={subject:t,"@id":t,uri:t},s=this.extractIdFromIri(e,t);s!==void 0&&(i.id=s);let o=!1,a=!1,u=!1;for(const c of r){if(!isRecord$1(c))continue;const l=c.p??c.predicate??c["?p"],d=c.o??c.object??c["?o"];if(typeof l=="string"){l==="http://www.w3.org/1999/02/22-rdf-syntax-ns#type"&&d===e.config.type&&(o=!0);for(const[f,m]of Object.entries(e.columns??{})){if(m._virtualId)continue;const g=this.getColumnPredicate(e,m);if(!g||g==="@id"||g!==l)continue;if(m.options?.isArray||m.dataType==="array"){const S=Array.isArray(i[f])?i[f]:i[f]===void 0?[]:[i[f]];i[f]=[...S,d]}else i[f]===void 0&&(i[f]=d);m.dataType==="object"&&typeof d=="string"&&isAbsoluteIri(d)&&(u=!0),a=!0}}}if(!o&&!a)return null;if(!u)return i}extractIdFromIri(e,t){const r=parsePodResourceRef(e,t);if(r)return r.templateValues.id??r.resourceId;try{const a=this.dialect.getResolver(e).parseId(e,t);if(a)return a}catch{}const i=e.getSubjectTemplate?.()??e.config?.subjectTemplate;if(!i)return;if(i==="{id}.ttl"){const a=t.split("/").pop()??"";return a.endsWith(".ttl")?a.slice(0,-4):a||void 0}if(i==="{id}.ttl#it"){const u=t.split("#")[0].split("/").pop()??"";return u.endsWith(".ttl")?u.slice(0,-4):u||void 0}const s=t.indexOf("#");if(s>=0&&i.includes("{id}")&&i.startsWith("#"))return decodeURIComponent(t.slice(s+1));const o=t.split("#")[0].split("/").pop()??"";return o.endsWith(".ttl")?o.slice(0,-4):void 0}parseIri(e){const t=e.indexOf("#");return t>=0?{documentUrl:e.substring(0,t),fragment:e.substring(t+1)}:{documentUrl:e,fragment:null}}async subscribeByIri(e,t,r){if(!t||typeof t!="string")throw new Error("subscribeByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`subscribeByIri requires an absolute IRI, got: ${t}`);if(!this.notificationsClient){const o=this.dialect.getAuthenticatedFetch(),a={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(o,a)}const{documentUrl:i}=this.parseIri(t),s=await this.notificationsClient.subscribe(i,{channel:r.channel,features:r.features,onNotification:async o=>{try{if(o.type==="Update"){const a=await this.findByIri(e,t);a&&await r.onUpdate(a)}else o.type==="Delete"&&await r.onDelete?.()}catch(a){r.onError?.(a)}},onError:r.onError});return()=>s.unsubscribe()}async updateByIri(e,t,r){if(!t||typeof t!="string")throw new Error("updateByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`updateByIri requires an absolute IRI, got: ${t}`);const i=r;return await this.session.update(e).set(i).whereByIri(t),await this.findByIri(e,t)}async updateById(e,t,r){const i=await this.resolveIdSubjectForExactOperation(e,t,"updateById");return i?await this.updateByIri(e,i,r):null}async updateByLocator(e,t,r){const i=this.resolveLocatorSubject(e,t,"updateByLocator");return await this.updateByIri(e,i,r)}async updateByResource(e,t,r){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.updateById(e,t,r);const i=this.resolveResourceTargetIri(e,t,"updateByResource");return await this.updateByIri(e,i,r)}async deleteByIri(e,t){if(!t||typeof t!="string")throw new Error("deleteByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`deleteByIri requires an absolute IRI, got: ${t}`);return await this.findByIri(e,t)?(await this.session.delete(e).whereByIri(t),!0):!1}async deleteById(e,t){const r=await this.resolveIdSubjectForExactOperation(e,t,"deleteById");return r?await this.deleteByIri(e,r):!1}async deleteByLocator(e,t){const r=this.resolveLocatorSubject(e,t,"deleteByLocator");return await this.deleteByIri(e,r)}async deleteByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.deleteById(e,t);const r=this.resolveResourceTargetIri(e,t,"deleteByResource");return await this.deleteByIri(e,r)}async transaction(e){return await this.session.transaction(async t=>{const r=new PodDatabase(this.dialect,t,this.schema);return await e(r)})}getDialect(){return this.dialect}getSession(){return this.session}getSchema(){return this.schema}get discovery(){return this.dialect.getDiscovery()}async connect(){return await this.dialect.connect()}async disconnect(){return this.notificationsClient&&this.notificationsClient.unsubscribeAll(),await this.dialect.disconnect()}async subscribe(e,t){if(!this.notificationsClient){const s=this.dialect.getAuthenticatedFetch(),o={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(s,o)}const r=this.resolveResourceTopic(e,t.iri),i={channel:t.channel,features:t.features,onNotification:s=>{if(t.onNotification?.(s),!!(t.onCreate||t.onUpdate||t.onDelete||t.onAdd||t.onRemove)){const a={id:s.id,type:s.type,object:s.object,published:s.published,state:s.state};switch(s.type){case"Create":t.onCreate?.(a);break;case"Update":t.onUpdate?.(a);break;case"Delete":t.onDelete?.(a);break;case"Add":t.onAdd?.(a);break;case"Remove":t.onRemove?.(a);break}}},onError:t.onError,onClose:t.onClose};return this.notificationsClient.subscribe(r,i)}resolveResourceTopic(e,t){if(t){if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`iri must be an absolute URL, got: ${t}`);return t}const r=e.config.base||"";if(r.startsWith("http://")||r.startsWith("https://"))return r;const i=this.dialect.getPodUrl(),s=i.endsWith("/")?i:`${i}/`,o=r.startsWith("/")?r.slice(1):r;return`${s}${o}`}getConfig(){return this.dialect.getConfig()}async discoverTable(e){const t=await this.dialect.discoverDataLocations(e);if(t.length===0)return console.log(`[discoverTable] No data locations found for ${e}`),null;const r=t[0],i=r.shapes[0]?.url;if(console.log(`[discoverTable] Found location: ${r.container}, shape: ${i||"none"}`),i){const c=this.dialect.getShapeManager(),l=await c.loadShape(i,this.dialect.getAuthenticatedFetch());if(l){console.log(`[discoverTable] Loaded shape with ${l.properties.length} properties`);const d=c.shapeToTable(l,r.container);return await this.init(d.table),d.table}}console.log("[discoverTable] No shape available, creating basic table");const{podTable:s,string:o}=await __vitePreload(async()=>{const{podTable:c,string:l}=await import("./XpodShellApp-D1PS3Iut.js").then(d=>d.E);return{podTable:c,string:l}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),a=this.extractClassName(e),u=s(a,{id:o("id").primaryKey()},{type:e,base:r.container});return await this.init(u),u}async discoverTables(e){const t=[];for(const r of e){const i=await this.discoverTable(r);i&&t.push(i)}return t}async discover(e,t){return this.dialect.discoverDataLocations(e,t)}async discoverAll(){return this.dialect.discoverAll()}async discoverByApp(e){return this.dialect.discoverByApp(e)}async locationToTable(e,t){const r=t??{};let i;if(r.shape)typeof r.shape=="string"?(i=e.shapes.find(c=>c.url===r.shape),i||(i={url:r.shape,source:"config"})):i=r.shape;else if(r.appId){if(i=e.shapes.find(c=>c.registeredBy===r.appId),!i)throw new Error(`[locationToTable] No shape found for appId: ${r.appId}`)}else i=e.shapes[0];if(i?.url){const c=this.dialect.getShapeManager(),l=await c.loadShape(i.url,this.dialect.getAuthenticatedFetch());if(l){console.log(`[locationToTable] Loaded shape: ${i.url} (${l.properties.length} properties)`),i.registeredBy&&console.log(`[locationToTable] -> registeredBy: ${i.registeredBy}`);const d=c.shapeToTable(l,e.container);return await this.init(d.table),d.table}}console.log(`[locationToTable] No shape available, creating basic table for container: ${e.container}`);const{podTable:s,string:o}=await __vitePreload(async()=>{const{podTable:c,string:l}=await import("./XpodShellApp-D1PS3Iut.js").then(d=>d.E);return{podTable:c,string:l}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),a=this.extractContainerName(e.container),u=s(a,{id:o("id").primaryKey()},{type:"http://www.w3.org/2000/01/rdf-schema#Resource",base:e.container});return await this.init(u),u}extractContainerName(e){const t=e.replace(/\/$/,""),r=t.lastIndexOf("/");return r>=0&&t.substring(r+1).toLowerCase()||"data"}async discoverTablesFor(e,t,r){const i=await this.discover(e,t),s=[];for(const o of i){const a=await this.locationToTable(o,r);s.push(a)}return s}extractClassName(e){const t=e.lastIndexOf("#");if(t>=0)return e.substring(t+1).toLowerCase();const r=e.lastIndexOf("/");return r>=0?e.substring(r+1).toLowerCase():e.toLowerCase()}addSource(e){this.dialect.addSource(e)}removeSource(e){this.dialect.removeSource(e)}getSources(){return this.dialect.getSources()}async addSourcesFromTypeIndex(){return await this.dialect.addSourcesFromTypeIndex()}async init(...e){let t,r;const i=e[e.length-1];i&&typeof i=="object"&&!Array.isArray(i)&&!("columns"in i)?(t=i,r=e.slice(0,-1)):r=e;const s=[];for(const o of r)if(o)if(Array.isArray(o))for(const a of o)a&&s.push(a);else s.push(o);for(const o of s)if(typeof o.init=="function"?await o.init(this.dialect):await this.dialect.registerTable(o),t?.generateShape||t?.saveShape){const a=this.dialect.getShapeManager(),u=a.generateShape(o);if(t?.saveShape){const c=this.dialect.getPodUrl();let l=t.shapeLocation;l?l.startsWith("http")||(l=`${c}${l.replace(/^\//,"")}`):l=`${c}shapes/`,l.endsWith("/")||(l+="/");const d=`${l}${o.config.name}Shape.ttl`;try{await a.saveShape(u,d),console.log(`[init] Shape saved to: ${d}`)}catch(f){console.warn(`[init] Failed to save Shape to ${d}:`,f)}}}}get query(){return this.queryProxy||(this.queryProxy=this.buildQueryProxy()),this.queryProxy}buildQueryProxy(){const e=this.schema&&typeof this.schema=="object"?Object.entries(this.schema):[],t=new Map;for(const[s,o]of e)isPodTable(o)&&t.set(s,o);const r=(s,o)=>{const a=_=>{let T=null;const C=()=>(T||(T=_()),T);return{then:(U,$)=>C().then(U,$),catch:U=>C().catch(U),finally:U=>C().finally(U),[Symbol.toStringTag]:"Promise"}},u=(_,T,C)=>{const U={};for(const[$,W]of Object.entries(T)){if(W instanceof PodColumnBase){U[$]=_[W.name];continue}if(typeof W=="string"){U[$]=_[W]??_[W.split(".").pop()??W];continue}const re=W?.name;if(typeof re=="string"){U[$]=_[re];continue}U[$]=_[$]}if(C)for(const $ of Object.keys(C))U[$]=_[$]??[];return U},c=async _=>{this.clearFederatedErrors();let T=this.session.select().from(o);_?.where&&(T=T.where(_.where)),_?.orderBy&&(Array.isArray(_.orderBy)?_.orderBy:[_.orderBy]).forEach(W=>{T=T.orderBy(W.column,W.direction??"asc")}),typeof _?.limit=="number"&&(T=T.limit(_.limit)),typeof _?.offset=="number"&&(T=T.offset(_.offset));let C=await T;_?.with&&Object.keys(_.with).length>0&&(C=await this.eagerLoadWith(C,o,_.with,t));const U=_?.columns;return U&&(C=C.map($=>u($,U,_.with))),C},l=_=>a(()=>c(_)),d=async(_,T)=>{if(!_)return null;let C=[_];T?.with&&Object.keys(T.with).length>0&&(C=await this.eagerLoadWith(C,o,T.with,t));const U=T?.columns;return U&&(C=C.map($=>u($,U,T.with))),C[0]??null},f=_=>a(async()=>(await c({..._,limit:1}))[0]??null),m=_=>a(async()=>(await c({where:_?.where,columns:void 0,limit:void 0,offset:void 0})).length),g=()=>(_,T)=>a(async()=>await d(await this.findByLocator(o,_),T)),b=()=>(_,T)=>a(async()=>await d(await this.findById(o,_),T)),S=()=>(_,T)=>a(async()=>await d(await this.findByIri(o,_),T)),w=()=>(_,T)=>a(async()=>await d(await this.findByResource(o,_),T));return{findMany:l,findFirst:f,find:(_,T)=>w()(_,T),findById:b(),findByLocator:g(),findByIri:S(),findByResource:w(),count:m}},i={};return new Proxy(i,{get:(s,o)=>{if(typeof o!="string")return;const a=t.get(o);if(a)return r(o,a)}})}async eagerLoadWith(e,t,r,i){if(!e||e.length===0)return e;const s=this.dedupeBySubject(e);for(const[o,a]of Object.entries(r)){if(!a)continue;const u=t.relations?.[o],c=typeof a=="object"&&a.table?a.table:u?.table??i.get(o);if(!c)continue;if(isSolidSchema(c)||u?.isFederated){if(u&&u.discover)try{const W=await this.getFederatedExecutor().execute(s,{...u,relationName:o});W.errors&&W.errors.length>0&&this.lastFederatedErrors.push(...W.errors)}catch($){console.warn(`Federated relation "${o}" failed:`,$),s.forEach(W=>{W[o]=[]})}else console.warn(`Federated relation "${o}" missing discover function, skipping.`),s.forEach($=>{$[o]=[]});continue}const l=c,d=l.config.type,f=u?.fields&&u.fields.length>0?u.fields:Object.values(l.columns??{}),m=$=>!!($&&($.options?.linkTarget===t.config.type||$.options?.linkTable===t||$.getLinkTable?.()===t)),g=$=>!!($&&($.options?.linkTarget===d||$.options?.linkTable===l||$.getLinkTable?.()===l)),b=u?.fields&&u.fields.length>0?f:f.filter($=>m($)&&!$.isInverse?.());if(b.length===0){const W=(u?.references??[]).filter(Fe=>!!(Fe&&typeof Fe.isInverse=="function"&&Fe.isInverse()&&g(Fe))),re=Object.values(t.columns??{}),D=(W.length>0?W:re).filter(Fe=>typeof Fe.isInverse=="function"&&Fe.isInverse()&&g(Fe));if(D.length===0)continue;const V=s.map(Fe=>this.collectInverseLinkValues(Fe,D)),he=Array.from(new Set(V.flat().filter(Fe=>typeof Fe=="string"&&Fe.length>0)));if(he.length===0){e.forEach(Fe=>{Fe[o]=[]});continue}let z=this.session.select().from(l);z=z.whereByIri(he);const _e=await z,Ce=this.groupRowsByIri(_e);s.forEach((Fe,ze)=>{const ae=V[ze],ve=[];ae.forEach(L=>{const ie=Ce.get(L);ie&&ie.length>0&&ve.push(...ie)}),Fe[o]=ve});continue}const S=b[0],w=u?.references&&u.references[0],v=S.isLink(),_=s.map($=>this.resolveParentKey($,w,v)).filter($=>typeof $=="string"&&$.length>0);if(_.length===0)continue;let T=this.session.select().from(l);v?T=T.where(inArray(S,_)):T=T.where({[S.name]:_});const C=await T,U=new Map;for(const $ of C){const W=$[S.name],re=this.normalizeLiteralValue(W),D=v?this.collectLinkLookupKeys(W):re?[re]:[];for(const V of D){const he=U.get(V)??[];he.push($),U.set(V,he)}}s.forEach($=>{const W=v?Array.from(new Set([this.resolveParentKey($,w,!0),this.resolveIdFromRow($)].filter(D=>typeof D=="string"&&D.length>0))):[this.resolveParentKey($,w,!1)].filter(D=>typeof D=="string"&&D.length>0),re=[];for(const D of W){const V=U.get(D)??[];for(const he of V)re.includes(he)||re.push(he)}$[o]=re})}return s}dedupeBySubject(e){const t=new Map,r=[];for(const i of e){const s=this.resolveIriFromRow(i)??this.resolveIdFromRow(i);if(!s){r.push(`__anon_${r.length}`),t.set(r[r.length-1],{...i});continue}if(!t.has(s)){t.set(s,{...i}),r.push(s);continue}const o=t.get(s);if(o)for(const[a,u]of Object.entries(i)){if(u===void 0)continue;const c=o[a];if(c===void 0){o[a]=u;continue}const l=Array.isArray(c)?c:[c],d=Array.isArray(u)?u:[u],f=[...l];for(const m of d)f.some(g=>g===m)||f.push(m);o[a]=f.length===1?f[0]:f}}return r.map(i=>t.get(i)).filter(i=>i!==void 0)}resolveIdFromRow(e){if(!e)return;if(typeof e.id=="string"&&e.id.length>0)return e.id;const t=typeof e["@id"]=="string"?e["@id"]:void 0;if(t)return this.extractFragment(t)}resolveParentKey(e,t,r){if(t){const i=e[t.name];return r?this.normalizeLinkValue(i):this.normalizeLiteralValue(i)}return r?this.resolveIriFromRow(e):this.resolveIdFromRow(e)}resolveIriFromRow(e){if(e){if(typeof e["@id"]=="string"&&e["@id"].length>0)return e["@id"];if(typeof e.subject=="string"&&e.subject.length>0)return e.subject}}collectLinkLookupKeys(e){const t=[],r=this.normalizeLinkValue(e)??this.normalizeLiteralValue(e);if(r){t.push(r);const i=this.extractFragment(r);i&&!t.includes(i)&&t.push(i)}return t}normalizeLinkValue(e){if(e){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}normalizeLiteralValue(e){if(e!=null){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}collectInverseLinkValues(e,t){if(!t.length)return[];const r=[];for(const i of t){const s=e[i.name];if(s==null)continue;const o=a=>{const u=this.normalizeLinkValue(a)??(typeof a=="string"?a:void 0);u&&r.push(u)};Array.isArray(s)?s.forEach(o):o(s)}return r}groupRowsByIri(e){const t=new Map;for(const r of e){const i=this.normalizeLinkValue(r["@id"])??this.normalizeLinkValue(r.uri)??(typeof r["@id"]=="string"?r["@id"]:void 0);if(!i)continue;const s=t.get(i)??[];s.push(r),t.set(i,s)}return t}extractFragment(e){const t=e.includes("#")?e.split("#").pop():void 0;return t&&t.length>0?t:e.split("/").pop()??e}}_a$8=entityKind;PodDatabase[_a$8]="PodDatabase";PodDatabase.findByLocatorDeprecationWarned=!1;function isAggregateExpression(n){return!!n&&typeof n=="object"&&n.kind==="aggregate"}function inferSPARQLQueryType(n){const r=n.replace(/^\s*#.*$/gm,"").trim().replace(/^(?:\s*(?:PREFIX|BASE)\s+[^\n]+\n)*/i,"").trim().match(/^(SELECT|ASK|INSERT|DELETE|UPDATE|WITH|LOAD|CLEAR|CREATE|DROP|COPY|MOVE|ADD|CONSTRUCT|DESCRIBE)\b/i)?.[1]?.toUpperCase();switch(r){case"SELECT":case"ASK":case"INSERT":case"DELETE":case"UPDATE":return r;case"WITH":case"LOAD":case"CLEAR":case"CREATE":case"DROP":case"COPY":case"MOVE":case"ADD":return"UPDATE";default:return}}function createLiteralCondition(n,e,t){const r=n?`${n}.${e}`:e;return t==null?new UnaryExpression("IS NULL",r):Array.isArray(t)?new BinaryExpression(r,"IN",t):new BinaryExpression(r,"=",t)}function buildConditionTreeFromObject(n,e){if(!n)return;const t=Object.entries(n);if(t.length===0)return;const r=t.map(([i,s])=>createLiteralCondition(e,i,s));return r.length===1?r[0]:new LogicalExpression("AND",r)}function resolveRowSubject(n){if(!(!n||typeof n!="object")){if(typeof n["@id"]=="string"&&n["@id"].length>0)return n["@id"];if(typeof n.subject=="string"&&n.subject.length>0)return n.subject;if(typeof n.uri=="string"&&n.uri.length>0)return n.uri;if(typeof n.source=="string"&&n.source.length>0)return n.source;if(typeof n.id=="string"&&n.id.length>0)return n.id}}function orderRowsBySubjects(n,e){if(!n.length||!e.length)return n;const t=new Map,r=[];for(const s of n){const o=resolveRowSubject(s);if(!o){r.push(s);continue}const a=t.get(o)??[];a.push(s),t.set(o,a)}const i=[];for(const s of e){const o=t.get(s);o?.length&&(i.push(...o),t.delete(s))}for(const s of t.values())i.push(...s);return i.push(...r),i}function isSelectFieldMap(n){return!!n&&typeof n=="object"&&!(n instanceof PodColumnBase)&&!(n instanceof PodTable)&&!("aggregateType"in n)}function resolveFieldBindingCandidates(n,e){const t=new Set;if(typeof e=="string"){if(t.add(e),e.includes(".")){const[r,i]=e.split(".",2);i&&(t.add(`${r}.${i}`),t.add(i))}}else e instanceof PodColumnBase&&(e.table?.config?.name&&t.add(`${e.table.config.name}.${e.name}`),t.add(e.name));return Array.from(t)}function isEmptyProjectedValue(n){if(n==null)return!0;if(Array.isArray(n))return n.length===0;if(typeof n=="object"){const e=Object.values(n);return e.length>0&&e.every(t=>isEmptyProjectedValue(t))}return!1}function projectTableRow(n,e){const t=e.config.name,r={};let i=!1;for(const s of Object.keys(e.columns)){const a=(t?[`${t}.${s}`,s]:[s]).find(u=>n[u]!==void 0);r[s]=a?n[a]:void 0,r[s]!==void 0&&(i=!0)}return i?r:null}function projectFieldValue(n,e,t){if(t instanceof PodTable)return projectTableRow(n,t);if(isSelectFieldMap(t)){const r={};for(const[i,s]of Object.entries(t))r[i]=projectFieldValue(n,i,s);return isEmptyProjectedValue(r)?null:r}for(const r of resolveFieldBindingCandidates(e,t))if(n[r]!==void 0)return n[r];return n[e]}function projectReturningRow(n,e){if(!e||e===!0)return n;const t={};for(const[r,i]of Object.entries(e))t[r]=projectFieldValue(n,r,i);return t}function projectReturningRows(n,e){return!e||e===!0?n:n.map(t=>projectReturningRow(t,e))}const UUID_REGEX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,SINGLETON_FRAGMENTS=new Set(["#me","#this","#profile","#card"]);class UriResolverImpl{constructor(e=""){this.podUrl=e.replace(/\/$/,"")}setPodUrl(e){this.podUrl=e.replace(/\/$/,"")}resolveSubject(e,t,r,i){const s=i?.strict??!0,o=t["@id"]??t.id??t.uri;if(typeof o=="string"){if(this.isAbsoluteUri(o))return o;const l=this.resolveBaseRelativeSubjectId(e,o);if(l)return l;o.startsWith("#")&&this.acceptsFragmentOnlyResourceId(e)&&(t={...t,id:o.slice(1)})}const a=this.getEffectivePattern(e),u=this.getSubjectBaseUrl(e);if(this.isSingleton(e))return this.combineBaseAndPattern(u,a);const c=this.applyTemplate(a,t,r,e,s);return c===null?this.generateFallbackUri(u,a,r):this.isAbsoluteUri(c)?c:this.combineBaseAndPattern(u,c)}parseSubject(e,t){if(!e)return null;const r=e.indexOf("#"),i=r!==-1,s=i?e.slice(0,r):e,o=i?e.slice(r+1):void 0,a=this.extractPublicId(e,t),u=this.getResourceMode(t);return{uri:e,resourceUrl:s,fragment:o,id:a,mode:u}}getResourceUrl(e){const t=e.indexOf("#");return t!==-1?e.slice(0,t):e}getResourceMode(e){if(!(e.hasCustomTemplate?.()??!1)){const i=e.config?.base??"";return/\.(ttl|jsonld|json)$/i.test(i)?"fragment":"document"}return(e.config?.subjectTemplate??this.getDefaultPattern(e)).startsWith("#")?"fragment":"document"}getDefaultPattern(e){return"{id}"}resolveInlineChild(e,t,r,i){const s=r["@id"]??r.id;return typeof s=="string"?s:buildInlineChildUri(e,t,i)}isSingleton(e){const t=e.config?.subjectTemplate;return t?!!(SINGLETON_FRAGMENTS.has(t)||!t.includes("{")):!1}resolveLink(e,t,r){const i=String(e??""),s=r?.record&&typeof r.record=="object"?r.record:void 0;if(this.isAbsoluteUri(i))return i;if(i.startsWith("/")||i.startsWith("#")){const l=r?.baseUri||this.podUrl;if(l)try{return new URL(i,l).toString()}catch{}throw new Error(`Cannot resolve relative URI "${i}": no baseUri configured`)}const o=t.getLinkTable?.();if(o){const l=this.getTableUriInfo(o);if(l)return this.buildFullUri(i,l.baseUrl,l.subjectTemplate,o,r,s);throw new Error(`Cannot resolve URI "${i}": linked table "${o.config?.name}" has no base configured.`)}const a=t.getLinkTableName?.();if(a){if(r?.tableNameRegistry){const d=r.tableNameRegistry.get(a);if(d){const f=this.getTableUriInfo(d);if(f)return this.buildFullUri(i,f.baseUrl,f.subjectTemplate,d,r,s)}}const l=r?.tableNameRegistry?Array.from(r.tableNameRegistry.keys()).join(", "):"(no tables registered)";throw new Error(`Cannot resolve URI "${i}": table "${a}" not found in schema. Available tables: ${l}`)}const u=t.getLinkTarget?.();if(u){if(!r?.tableRegistry)throw new Error(`Cannot resolve URI "${i}" (links to ${u}): tableRegistry not configured. Ensure the schema is properly registered.`);const l=r.tableRegistry.get(u);if(l&&l.length>0){if(l.length>1){const m=l.map(g=>g.config?.name||"unknown").join(", ");throw new Error(`Ambiguous link target: class "${u}" has multiple tables [${m}]. Use .link('tableName') or .link(tableObject) to specify which table to use.`)}const d=l[0],f=this.getTableUriInfo(d);if(f)return this.buildFullUri(i,f.baseUrl,f.subjectTemplate,d,r,s)}throw new Error(`Cannot resolve URI "${i}": class "${u}" not found in tableRegistry. Available classes: ${Array.from(r.tableRegistry.keys()).join(", ")||"(none)"}`)}const c=r?.baseUri||this.podUrl;if(c&&this.isAbsoluteUri(c)){const l=c.endsWith("/")?c:`${c}/`;return this.buildFullUri(i,l)}throw new Error(`Cannot resolve URI "${i}". Either provide a full URI (https://...), or configure baseUri.`)}isAbsoluteUri(e){return!e||typeof e!="string"?!1:e.includes(":")&&(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("urn:")||e.startsWith("did:")||e.startsWith("mailto:")||e.startsWith("tel:")||e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))}isLinkColumn(e){return e?e.dataType==="uri"||e.isLink?.()||!!e.options?.linkTarget||!!e.options?.linkTableName||!!e.options?.linkTable:!1}findTargetTable(e,t){const r=e.getLinkTable?.()||e.options?.linkTable;if(r)return r;const i=e.getLinkTableName?.()||e.options?.linkTableName;if(i&&t?.tableNameRegistry){const o=t.tableNameRegistry.get(i);if(o)return o}const s=e.getLinkTarget?.()||e.options?.linkTarget;if(s&&t?.tableRegistry){const o=t.tableRegistry.get(s);if(o&&o.length===1)return o[0]}}extractLinkId(e,t,r){if(e?.startsWith("/")){const o=r?.baseUri||this.podUrl;if(o){const a=o.endsWith("/")?o:`${o}/`;e=new URL(e.replace(/^\/+/,""),a).toString()}}if(!e||!this.isAbsoluteUri(e))return e;const i=this.findTargetTable(t,r);if(!i)return e;const s=this.extractTemplateIdFromSubject(e,i);return s||e}getTableUriInfo(e){const t=e.config?.base;if(!t)return;const r=e.config?.subjectTemplate;return{baseUrl:this.toAbsoluteUrl(t),subjectTemplate:r}}buildFullUri(e,t,r,i,s,o){const a=String(e??"");if(!r){const f=this.combineBaseAndResourceId(t,a);return this.assertNoUnresolvedTemplate(f,void 0,i),f}if(!UUID_REGEX.test(a)&&a.includes("/")&&!a.includes("{")){const f=`${t}${a}`;return this.assertNoUnresolvedTemplate(f,r,i),f}const u=this.buildTemplateRecord(a,r,i,s,o),c=this.applyTemplate(r,u,void 0,i,!0,s);if(c===null)throw new Error(`[UriResolver] Failed to resolve URI template "${r}" for table "${i?.config?.name??"unknown"}"`);if(this.isAbsoluteUri(c))return this.assertNoUnresolvedTemplate(c,r,i),c;if(c.startsWith("#")){const m=`${t.endsWith("/")?t.slice(0,-1):t}${c}`;return this.assertNoUnresolvedTemplate(m,r,i),m}const d=`${t.endsWith("/")?t:`${t}/`}${c}`;return this.assertNoUnresolvedTemplate(d,r,i),d}buildTemplateRecord(e,t,r,i,s){const o={...s??{}};o.id=e;for(const a of t.matchAll(/\{([^}]+)\}/g)){const c=this.parseTemplateVariable(a[1]).field;if(c==="id"||c==="index"||c in o)continue;const l=this.resolveTemplateVariable(c,r,i,s);l!=null&&l!==""&&(o[c]=l)}return o}resolveTemplateVariable(e,t,r,i){if(!i||typeof i!="object")return;if(e in i){const u=t?.columns?.[e];return this.normalizeValue(i[e],u,r)}const s=`${e}Id`;if(s in i)return String(i[s]);const o=t?.columns?.[e],a=o?this.findTargetTable(o,r):void 0;if(a)for(const[u,c]of Object.entries(i)){const l=r?.currentTable?.columns?.[u];if((l?this.findTargetTable(l,r):void 0)===a)return this.normalizeValue(c,o,r)}}assertNoUnresolvedTemplate(e,t,r){if(/\{[^}]+\}/.test(e)){const i=r?.config?.name||"unknown";throw new Error(`[UriResolver] Unresolved URI template variable while resolving table "${i}" with template "${t??"<exact-id>"}": ${e}`)}}getEffectivePattern(e){if(e.hasCustomTemplate?.()??!1){const r=e.config?.subjectTemplate;if(r&&r.trim().length>0)return r}return this.getDefaultPattern(e)}getSubjectBaseUrl(e){const t=e.config?.base??"";return this.toAbsoluteUrl(t)}isBaseRelativeSubjectId(e){return!e||this.isAbsoluteUri(e)||e.startsWith("/")?!1:e.startsWith("#")||e.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(e)}acceptsFragmentOnlyResourceId(e){const t=e.config?.subjectTemplate;if(!t)return!1;const r=Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>this.parseTemplateVariable(i[1]).field);return t==="#{id}"||t.startsWith("#")&&r.length===1&&r[0]==="id"}resolveBaseRelativeSubjectId(e,t){if(!this.isBaseRelativeSubjectId(t))return null;const r=this.getSubjectBaseUrl(e);if(t.startsWith("#"))return this.acceptsFragmentOnlyResourceId(e)?`${r}${t}`:null;if(r.endsWith("/"))return`${r}${t}`;const i=r.lastIndexOf("/");return`${i>=0?r.slice(0,i+1):`${r}/`}${t}`}toAbsoluteUrl(e){if(!e)return this.podUrl;if(this.isAbsoluteUri(e))return e;const t=e.startsWith("/")?e:`/${e}`;return`${this.podUrl}${t}`}combineBaseAndPattern(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:e.endsWith("/")?`${e}${t}`:(e.endsWith(".ttl")||e.endsWith(".jsonld"))&&t.startsWith("#")?`${e}${t}`:`${e}/${t}`}combineBaseAndResourceId(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:`${e.endsWith("/")?e:`${e}/`}${t}`}normalizeValue(e,t,r){return e==null?"":typeof e=="string"&&this.isAbsoluteUri(e)&&t&&this.isLinkColumn(t)?this.extractLinkId(e,t,r):String(e)}parseTemplateVariable(e){const[t,...r]=e.split("|").map(i=>i.trim()).filter(Boolean);return{raw:e,field:t||e,transforms:r}}slugifyValue(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{Letter}\p{Number}]+/gu,"-").replace(/^-+|-+$/g,"")}applyTransforms(e,t,r,i){let s=this.normalizeValue(e,r,i);for(const o of t.transforms){if(o==="id"){s=r&&this.isLinkColumn(r)?this.extractLinkId(s,r,i):s;continue}o==="slug"&&(s=this.slugifyValue(s))}return s}applyTemplate(e,t,r,i,s=!0,o){if(!e.includes("{"))return e;const a=this.createTimeContext(t),u=[],c=e.replace(/(#?)\{([^}]+)\}/g,(l,d,f)=>{const m=this.parseTemplateVariable(f),g=m.field;if(g in a)return d+a[g];if(g==="index"&&r!==void 0)return d+String(r+1);let b=t[g];if(g==="id"&&b==null&&(b=t["@id"]??t.uri),b==null)return u.push(f),l;const S=i?.columns?.[g],w=o??(i?{tableRegistry:i[Symbol.for("drizzle:tableRegistry")],tableNameRegistry:i[Symbol.for("drizzle:tableNameRegistry")]}:void 0),v=this.applyTransforms(b,m,S,w);return d==="#"&&v.startsWith("#")?d+v.slice(1):d+v});if(u.length>0){if(s){const l=i?.config?.name||"unknown";throw new Error(`[UriResolver] Missing required fields for template "${e}" in table "${l}": [${u.join(", ")}]. Record keys: [${Object.keys(t).join(", ")}]. Record: ${JSON.stringify(t)}`)}return null}return c}createTimeContext(e){let t;const r=e.createdAt??e.created_at??e.dateCreated;r instanceof Date?t=r:typeof r=="string"||typeof r=="number"?t=new Date(r):t=new Date;const i=t.getUTCFullYear().toString(),s=(t.getUTCMonth()+1).toString().padStart(2,"0"),o=t.getUTCDate().toString().padStart(2,"0"),a=Math.floor(t.getTime()/1e3).toString();return{date:t,yyyy:i,MM:s,dd:o,timestamp:a}}generateFallbackUri(e,t,r){const i=r!==void 0?`row-${r+1}`:`row-${Date.now()}`;return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}#${i}`:`${e.endsWith("/")?e:`${e}/`}${i}.ttl`}extractRelativeSubjectId(e,t){const r=t.config?.base??"";let i="";if(r&&e.includes(r)){const s=e.indexOf(r);i=e.substring(s+r.length),i.startsWith("#")&&!(t.hasCustomTemplate?.()??!1)&&(i=`${r.split("/").filter(Boolean).pop()??""}${i}`),i.startsWith("/")&&(i=i.substring(1))}else if(!r)i=e;else return console.warn(`[UriResolver] Cannot extract ID: base "${r}" not found in URI "${e}"`),"";return i}extractPublicId(e,t){return this.extractTemplateIdFromSubject(e,t)??this.extractRelativeSubjectId(e,t)}extractTemplateIdFromSubject(e,t){const r=this.extractRelativeSubjectId(e,t),i=t.config?.subjectTemplate;return i?this.extractIdFromTemplate(r,i):r}extractIdFromTemplate(e,t){let r=t.replace(/[.+?^$[\]\\()]/g,"\\$&").replace(/\{id\}/g,"(?<id>.+?)").replace(/\{[^}]+\}/g,"(?:.+?)");r=`^${r}$`;try{const i=new RegExp(r),s=e.match(i);if(s&&s.groups?.id)return s.groups.id;if(s&&s[1])return s[1]}catch{}return null}}function buildInlineChildUri(n,e,t){const r=n.indexOf("#"),i=r>=0?n.slice(0,r):n,s=r>=0?n.slice(r+1):"",o=s?`${encodeURIComponent(s)}/`:"";return`${i}#${o}${encodeURIComponent(e)}-${t+1}`}function isOrderByExpression(n){if(!n||typeof n!="object")return!1;const e=n;return"column"in e&&(e.direction==="asc"||e.direction==="desc")}function isReservedIdentifierKey(n){return n==="id"||n==="@id"||n.endsWith(".id")||n.endsWith(".@id")}function isReservedIdentifierOperand(n){if(n instanceof PodColumnBase){const e=n;return n.name==="id"||n.options?.predicate==="@id"||e._virtualId===!0}return typeof n=="string"?isReservedIdentifierKey(n):!1}function conditionTargetsReservedIdentifier(n){return n.type==="binary_expr"?!!(isReservedIdentifierOperand(n.left)||isReservedIdentifierOperand(n.right)):n.type==="logical_expr"?n.expressions.some(e=>e!=null&&typeof e=="object"&&"type"in e&&conditionTargetsReservedIdentifier(e)):n.type==="unary_expr"?n.value!=null&&typeof n.value=="object"&&"type"in n.value&&conditionTargetsReservedIdentifier(n.value):!1}function createWhereIdentifierError(n){switch(n){case"select":return["Using 'id' or '@id' in where() is not supported.","Use findById(id) for base-relative resource ids,","or findByIri(iri) for full IRI exact lookups."].join(" ");case"update":return["Using 'id' or '@id' in where() is not supported.","Use updateById(id, data) for base-relative resource ids,","or updateByIri(iri, data) for full IRI exact updates."].join(" ");case"delete":return["Using 'id' or '@id' in where() is not supported.","Use deleteById(id) for base-relative resource ids,","or deleteByIri(iri) for full IRI exact deletes."].join(" ")}}function assertPublicWhereObject(n,e){if(e){for(const t of Object.keys(e))if(isReservedIdentifierKey(t))throw new Error(createWhereIdentifierError(n))}}function assertPublicWhereCondition(n,e){if(conditionTargetsReservedIdentifier(e))throw new Error(createWhereIdentifierError(n))}function assertPublicCursorCondition(n){let e=!1,t=!1;const r=i=>{if(i.type==="binary_expr"){if(isReservedIdentifierOperand(i.left)||isReservedIdentifierOperand(i.right)){if(![">",">=","<","<="].includes(i.operator))throw new Error("whereCursor() only supports range comparisons on 'id' or '@id'.");e=!0}else t=!0;return}if(i.type==="logical_expr"){for(const s of i.expressions)r(s);return}t=!0};if(r(n),!e||!t)throw new Error("whereCursor() requires a sort predicate plus an 'id' or '@id' range tie-breaker.")}var define_process_env_default$2={},_a$7;class SelectQueryBuilder{constructor(e,t){this.session=e,this.joins=[],this.orderByClauses=[],this.isDistinct=!1,this.tableAliases=new Map,this.aliasToTable=new Map,this.aliasUsage=new Map,this.joinFilters=[],this.groupByColumns=[],t&&this.setSelectedFields(t)}from(e){return this.selectedTable=e,this.primaryAlias=this.ensureAliasForTable(e),this}columns(e){return this.setSelectedFields(e),this}setSelectedFields(e){this.selectedFields={...e}}where(e){return e instanceof SQL?this.sql=e:this.isQueryCondition(e)?(assertPublicWhereCondition("select",e),this.processQueryCondition(e)):(assertPublicWhereObject("select",e),this.processWhereObject(e)),this}whereCursor(e){return assertPublicCursorCondition(e),this.processQueryCondition(e),this}whereByIri(e){return this.processWhereObject({"@id":e}),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,r=e.right,i=e.operator,s=typeof t=="string"?t:t?.name;if(i==="="&&s&&r!==void 0)return{[s]:r}}if(e.type==="logical_expr"){const t=e.operator,r=e.expressions;if(t==="AND"&&r){const i={};for(const s of r){const o=this.convertQueryConditionToSimple(s);if(!o||Object.keys(o).length===0)return{};for(const[a,u]of Object.entries(o))i[a]=u}return i}}return{}}extractTableFromCondition(e){if(e.type==="binary_expr"){const t=e.left;if(t&&typeof t=="object"&&"table"in t){const r=t.table;if(r)return this.tableAliases.get(r)}if(typeof t=="string"&&t.includes("."))return t.split(".")[0]}}leftJoin(e,t){return this.addJoin("leftJoin",e,t)}rightJoin(e,t){return this.addJoin("rightJoin",e,t)}innerJoin(e,t){return this.addJoin("innerJoin",e,t)}fullJoin(e,t){return this.addJoin("fullJoin",e,t)}crossJoin(e){return this.addJoin("crossJoin",e)}groupBy(...e){const t=e.map(r=>this.resolveColumnReference(r));return this.groupByColumns.push(...t),this}having(e){return this.havingCondition=typeof e=="function"?e(this.createSelectedFieldAliases()):e,this}createSelectedFieldAliases(){const e={};for(const t of Object.keys(this.selectedFields??{}))e[t]=new SelectionAliasExpression(t);return e}addJoin(e,t,r){if(e==="rightJoin"||e==="fullJoin")throw new Error(`${e} is not yet supported in Solid dialect`);const i=this.ensureAliasForTable(t),s=e==="crossJoin"?void 0:this.resolveJoinConditions(r,i);return this.joins.push({type:e,table:t,alias:i,rawCondition:r,resolvedConditions:s}),this}ensureAliasForTable(e){const t=this.tableAliases.get(e);if(t)return t;const r=e.config.name||"table",i=this.aliasUsage.get(r)??0,s=i+1;this.aliasUsage.set(r,s);const o=i===0?r:`${r}_${s}`;return this.tableAliases.set(e,o),this.aliasToTable.set(o,e),o}resolveJoinConditions(e,t){if(this.isQueryCondition(e))return this.resolveJoinConditionExpression(e,t);if(!e||typeof e!="object")throw new Error("JOIN condition must be an equality expression or column mapping");const r=Object.entries(e);if(r.length===0)throw new Error("JOIN condition cannot be empty");return r.map(([i,s])=>{const o=this.resolveColumnReference(i),a=this.resolveColumnReference(s);if(o.alias!==t&&a.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return{left:o,right:a}})}resolveJoinConditionExpression(e,t){if(e.type==="logical_expr"){const s=(e.operator??"").toUpperCase(),o=e.expressions??[];if(s!=="AND"||o.length===0)throw new Error("JOIN condition only supports equality expressions combined with AND");return o.flatMap(a=>this.resolveJoinConditionExpression(a,t))}if(e.type!=="binary_expr"||e.operator!=="=")throw new Error("JOIN condition only supports equality expressions");const r=this.getConditionColumnReference(e.left),i=this.getConditionColumnReference(e.right);if(!r||!i)throw new Error("JOIN equality must compare two table columns");if(r.alias!==t&&i.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return[{left:r,right:i}]}getConditionColumnReference(e,t){if(e instanceof PodColumnBase)return this.resolveColumnReference(e,t);if(typeof e=="string"){if(e.includes("."))return this.resolveColumnReference(e,t);const r=t??this.primaryAlias,i=r?this.aliasToTable.get(r):void 0;if(i&&e in(i.columns??{}))return this.resolveColumnReference(e,t)}}resolveColumnReference(e,t){if(e instanceof PodColumnBase){const r=e.table;if(!r)throw new Error(`Column ${e.name} is not associated with a table`);const i=this.ensureAliasForTable(r);return{table:r,alias:i,column:e.name}}if(typeof e=="string"){const{alias:r,column:i}=this.parseColumnReferenceString(e),s=r??t??this.primaryAlias;if(!s)throw new Error(`Unable to resolve table alias for column reference "${e}"`);const o=this.aliasToTable.get(s);if(!o)throw new Error(`Unknown table alias "${s}" in column reference "${e}"`);return{table:o,alias:s,column:i}}throw new Error("Unsupported column link type")}parseColumnReferenceString(e){const t=e.trim();if(!t.includes("."))return{column:t};const[r,i]=t.split(".",2);return{alias:r,column:i}}processWhereObject(e){if(!e)return;const t={...this.whereConditions??{}};for(const[r,i]of Object.entries(e)){const{alias:s,column:o}=this.parseColumnReferenceString(r),a=s??this.primaryAlias;if(!a||a===this.primaryAlias||!this.aliasToTable.has(a)){t[o]=i;continue}this.joinFilters.push(createLiteralCondition(a,o,i))}this.whereConditions=Object.keys(t).length>0?t:void 0}processQueryCondition(e){const t=this.extractTableFromCondition(e);if(t&&t!==this.primaryAlias){this.joinFilters.push(e);return}this.conditionTree=e;const r=this.convertQueryConditionToSimple(e);Object.keys(r).length>0&&(this.whereConditions=r)}applyInternalQueryCondition(e){return this.processQueryCondition(e),this}normalizeWhereConditions(){if(this.conditionTree)return this.conditionTree;const e=this.primaryAlias??this.selectedTable?.config.name;return buildConditionTreeFromObject(this.whereConditions,e)}toIR(){const e=this.normalizeWhereConditions();return this.buildQueryPlan(e)}buildQueryPlan(e){if(!this.selectedTable)throw new Error("No table specified for SELECT query");const t=this.joins.map(r=>({type:r.type,table:r.table,alias:r.alias,conditions:(r.resolvedConditions??[]).map(({left:i,right:s})=>({left:i,right:s}))}));return{baseTable:this.selectedTable,baseAlias:this.primaryAlias??this.selectedTable.config.name,select:this.selectedFields,selectAll:!this.selectedFields,where:this.whereConditions,conditionTree:e,joins:t.length>0?t:void 0,joinFilters:this.joinFilters.length>0?[...this.joinFilters]:void 0,groupBy:this.groupByColumns.length>0?[...this.groupByColumns]:void 0,having:this.havingCondition,orderBy:this.orderByClauses.length>0?this.orderByClauses.map(r=>({rawColumn:r.column,direction:r.direction})):void 0,distinct:this.isDistinct||void 0,limit:this.limitCount,offset:this.offsetCount,aliasToTable:new Map(this.aliasToTable),tableToAlias:new Map(this.tableAliases)}}limit(e){if(!Number.isInteger(e)||e<0)throw new Error("LIMIT must be a non-negative integer");return this.limitCount=e,this}offset(e){if(!Number.isInteger(e)||e<0)throw new Error("OFFSET must be a non-negative integer");return this.offsetCount=e,this}addOrderByClause(e,t="asc"){const r=typeof e=="string"?e:e.name;if(!r)throw new Error("ORDER BY requires a valid column name");this.orderByClauses.push({column:r,direction:t})}orderBy(...e){if(e.length===0)throw new Error("ORDER BY requires at least one column or expression");if(e.length===2&&(e[0]instanceof PodColumnBase||typeof e[0]=="string")&&(e[1]==="asc"||e[1]==="desc"))return this.addOrderByClause(e[0],e[1]),this;for(const t of e){if(isOrderByExpression(t)){this.addOrderByClause(t.column,t.direction);continue}if(t instanceof PodColumnBase||typeof t=="string"){this.addOrderByClause(t,"asc");continue}throw new Error("ORDER BY received an unsupported argument")}return this}distinct(e=!0){return this.isDistinct=e,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const r=this.sql.queryChunks.join(""),i=inferSPARQLQueryType(r);if(!i)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:i,query:r,prefixes:{}}}if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.joins.length>0)throw new Error(`${e} is not yet supported for JOIN queries in Solid dialect`);if(this.shouldUseProjectionFallback())throw new Error(`${e} does not support structured selections in Solid dialect`);const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertSelectPlan(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.limitCount===0)return[];if(this.sql)return await this.session.executeSql(this.sql,this.selectedTable);{const e=this.toIR(),t=e.conditionTree,r=this.joins.length>0,i=this.shouldUseAggregateFallback(),s=this.shouldUseProjectionFallback(),o=r||i;(r||i||s)&&(e.select=void 0,e.selectAll=!0);const a=o?{...e,limit:void 0,offset:void 0,orderBy:void 0,...r?{joins:void 0,joinFilters:void 0}:{},...i?{groupBy:void 0,having:void 0}:{}}:r?{...e,joins:void 0,joinFilters:void 0}:e,u={type:"select",table:this.selectedTable,where:t,limit:o?void 0:this.limitCount,offset:o?void 0:this.offsetCount,orderBy:o||this.orderByClauses.length===0?void 0:this.orderByClauses,distinct:this.isDistinct||void 0};if(u.plan=a,this.groupByColumns.length===0&&this.hasMixedAggregateSelection())throw new Error("Mixed aggregate and non-aggregate selections require groupBy columns");let c;if(!r&&!i&&!s?(this.selectedFields&&(u.select=this.selectedFields),c=await this.session.execute(u),c=this.applySubjectMetadata(c)):(r?u.select=void 0:!i&&!s?u.select=this.selectedFields:u.select=void 0,c=await this.session.execute(u),r||(c=this.applySubjectMetadata(c)),r&&(c=this.normalizeBaseRows(c),c=this.mergeRowsBySubject(c),c=await this.applyJoinFallback(c),c=this.applyJoinFilters(c))),i){let d=this.handleAggregateFallback(c);return d=this.applyHavingFilter(d),o&&(d=this.applyDeferredOrderBy(d),d=this.applyDeferredOffsetAndLimit(d)),d}let l=c;return r||(l=this.mergeRowsBySubject(l)),this.selectedTable&&(l=await this.hydrateInlineColumns(l,this.selectedTable,!r)),r&&(l=this.applyDeferredOrderBy(l)),this.selectedFields&&(l=l.map(d=>this.projectSelectedRow(d))),l=this.applyDistinctRows(l),r||(l=this.mergeRowsBySubject(l)),r&&(l=this.applyDeferredOffsetAndLimit(l)),l}}projectSelectedRow(e){return this.selectedFields?this.projectFieldMap(e,this.selectedFields):e}projectFieldMap(e,t,r=!0){const i={};for(const[s,o]of Object.entries(t))i[s]=this.projectFieldValue(e,s,o,r);return i}projectFieldValue(e,t,r,i=!0){if(isAggregateExpression(r))return i?e[t]:void 0;if(r instanceof PodTable)return this.projectTableValue(e,r);if(this.isSelectFieldMap(r)){const s=this.collectSelectionAliases(r),o=s.size===1&&!s.has(this.primaryAlias??""),a=this.projectFieldMap(e,r,!o);if(s.size===1){const[u]=Array.from(s);if(u&&u!==this.primaryAlias&&this.isProjectedValueEmpty(a))return null}return a}for(const s of this.resolveFieldBindingCandidates(t,r))if(e[s]!==void 0)return e[s];return i?e[t]:void 0}projectTableValue(e,t){const r=this.tableAliases.get(t)??t.config.name,i={};let s=!1;for(const o of Object.keys(t.columns)){const u=(r===this.primaryAlias?[o,`${r}.${o}`]:[`${r}.${o}`]).find(c=>e[c]!==void 0);i[o]=u?e[u]:void 0,i[o]!==void 0&&(s=!0)}return r!==this.primaryAlias&&!s?null:i}isSelectFieldMap(e){return!!e&&typeof e=="object"&&!(e instanceof PodColumnBase)&&!(e instanceof PodTable)&&!isAggregateExpression(e)}collectSelectionAliases(e){if(typeof e=="string"){const{alias:r}=this.parseColumnReferenceString(e);return new Set(r?[r]:this.primaryAlias?[this.primaryAlias]:[])}if(e instanceof PodColumnBase)return new Set([this.resolveColumnReference(e).alias]);if(e instanceof PodTable)return new Set([this.tableAliases.get(e)??e.config.name]);if(!this.isSelectFieldMap(e))return new Set;const t=new Set;for(const r of Object.values(e))for(const i of this.collectSelectionAliases(r))t.add(i);return t}isProjectedValueEmpty(e){if(e==null)return!0;if(Array.isArray(e))return e.length===0;if(typeof e=="object"){const t=Object.values(e);return t.length>0&&t.every(r=>this.isProjectedValueEmpty(r))}return!1}resolveFieldBindingCandidates(e,t){const r=new Set;if(typeof t=="string"){const{alias:i,column:s}=this.parseColumnReferenceString(t);r.add(t),r.add(s),i&&r.add(`${i}.${s}`)}else if(t instanceof PodColumnBase){const i=this.resolveColumnReference(t);r.add(`${i.alias}.${i.column}`),(!i.alias||i.alias===this.primaryAlias)&&r.add(t.name)}else if(t&&typeof t=="object"){const i=t.name;typeof i=="string"&&r.add(i)}return Array.from(r)}shouldUseProjectionFallback(){if(!this.selectedFields)return!1;const e=t=>!!(t instanceof PodTable||this.isSelectFieldMap(t));return Object.values(this.selectedFields).some(t=>e(t))}shouldUseAggregateFallback(){if(this.havingCondition)return!0;if(this.joins.length>0)return this.groupByColumns.length>0||this.hasAggregateSelection();if(this.groupByColumns.length>0||!this.selectedFields)return!1;const e=Object.values(this.selectedFields);return e.length>0&&e.every(t=>isAggregateExpression(t))}buildAggregateRow(e){const t={};if(!this.selectedFields)return t;for(const[r,i]of Object.entries(this.selectedFields))isAggregateExpression(i)&&(t[r]=this.computeAggregateValue(i,e));return t}computeAggregateValue(e,t){const r=this.resolveAggregateColumnRef(e);if(!r)return e.func==="count"?e.distinct?this.countDistinctRows(t):t.length:null;switch(e.func){case"count":return this.collectValuesForCount(r,t,!!e.distinct).length;case"sum":{const i=this.collectNumericValues(r,t,!!e.distinct);return i.length===0?null:i.reduce((s,o)=>s+o,0)}case"avg":{const i=this.collectNumericValues(r,t,!!e.distinct);return i.length===0?null:i.reduce((o,a)=>o+a,0)/i.length}case"min":{const i=this.collectNumericValues(r,t,!!e.distinct);return i.length===0?null:Math.min(...i)}case"max":{const i=this.collectNumericValues(r,t,!!e.distinct);return i.length===0?null:Math.max(...i)}default:return null}}resolveAggregateColumnRef(e){const t=e.column;if(t){if(typeof t=="string")return this.resolveColumnReference(t);if(t instanceof PodColumnBase)return this.resolveColumnReference(t);if(typeof t=="object"&&"name"in t){const r=t.name;if(typeof r=="string")return this.resolveColumnReference(r)}}}collectValuesForCount(e,t,r){const i=t.map(a=>this.getRowValueForColumn(a,e)).filter(a=>a!=null);if(!r)return i;const s=new Set,o=[];for(const a of i){const u=this.serializeValueForKey(a);s.has(u)||(s.add(u),o.push(a))}return o}collectNumericValues(e,t,r){const i=[],s=new Set;for(const o of t){const a=this.getRowValueForColumn(o,e);if(a==null)continue;const u=Number(a);if(!Number.isNaN(u))if(r){const c=this.serializeValueForKey(u);s.has(c)||(s.add(c),i.push(u))}else i.push(u)}return i}countDistinctRows(e){const t=new Set;for(const r of e){const i=this.serializeValueForKey(r);t.add(i)}return t.size}handleAggregateFallback(e){if(!this.selectedFields){if(this.groupByColumns.length===0)return e;const t=new Map;for(const r of e){const i=this.groupByColumns.map(o=>this.serializeValueForKey(this.getRowValueForColumn(r,o))),s=JSON.stringify(i);t.has(s)||t.set(s,r)}return Array.from(t.values())}return this.groupByColumns.length===0?[this.buildAggregateRow(e)]:this.buildGroupedAggregateRows(e)}buildGroupedAggregateRows(e){if(!this.selectedFields)return e;this.ensureGroupByValidity();const t=new Map;for(const i of e){const s=this.groupByColumns.map(a=>this.serializeValueForKey(this.getRowValueForColumn(i,a))),o=JSON.stringify(s);t.has(o)||t.set(o,{rows:[],first:i}),t.get(o)?.rows.push(i)}const r=[];for(const{rows:i,first:s}of t.values()){const o=this.buildAggregateRow(i),a={};for(const[u,c]of Object.entries(this.selectedFields))if(isAggregateExpression(c))a[u]=o[u];else{const l=this.resolveSelectFieldColumn(c);a[u]=l?this.getRowValueForColumn(s,l):void 0}r.push(a)}return r}ensureGroupByValidity(){if(!this.selectedFields)return;const e=this.groupByColumns.map(t=>`${t.alias}.${t.column}`);for(const t of Object.values(this.selectedFields)){if(isAggregateExpression(t))continue;const r=this.resolveSelectFieldColumn(t);if(!r)continue;const i=`${r.alias}.${r.column}`;if(!e.includes(i))throw new Error(`Column ${i} must appear in GROUP BY clause when mixed with aggregates`)}}resolveSelectFieldColumn(e){if(e instanceof PodColumnBase)return this.resolveColumnReference(e);if(typeof e=="string")return this.resolveColumnReference(e)}hasAggregateSelection(){return this.selectedFields?Object.values(this.selectedFields).some(e=>isAggregateExpression(e)):!1}hasMixedAggregateSelection(){if(!this.selectedFields)return!1;const e=Object.values(this.selectedFields),t=e.some(i=>isAggregateExpression(i)),r=e.some(i=>!isAggregateExpression(i));return t&&r}applySubjectMetadata(e){return e.map(t=>this.attachSubjectMetadata(t))}extractSubjectValue(e){const t=e.subject??e["@id"]??e.uri;if(typeof t=="object"&&t&&"value"in t){const r=t.value;return typeof r=="string"&&r.length>0?r:void 0}if(typeof t=="string"&&t.length>0)return t}attachSubjectMetadata(e){const t=this.extractSubjectValue(e);if(typeof t=="string"&&t.length>0&&(e["@id"]===void 0&&(e["@id"]=t),e.uri===void 0&&(e.uri=t),e.id===void 0)){const r=this.extractIdFromSubject(t,this.selectedTable);r!==void 0&&(e.id=r)}return e}normalizeBaseRows(e){if(!e.length)return e;const t=this.primaryAlias||this.ensureAliasForTable(this.selectedTable);return e.map(r=>{const i={...r};for(const[o,a]of Object.entries(r))o!==`${t}.${o}`&&(i[`${t}.${o}`]=a);const s=this.extractSubjectValue(r);if(s){i.subject=s,i["@id"]=s,i.uri=s,i[`${t}.subject`]=s,i[`${t}.@id`]=s,i[`${t}.uri`]=s;const o=this.extractIdFromSubject(s,this.selectedTable);o!==void 0&&(i.id===void 0&&(i.id=o),(this.shouldUseSubjectIdentityColumn(this.selectedTable,"id")||i[`${t}.id`]===void 0)&&(i[`${t}.id`]=o))}return i})}async hydrateInlineColumns(e,t,r=!0){if(!e.length)return e;const i=Object.values(t.columns??{}).filter(S=>this.isInlineObjectColumn(S));if(i.length===0)return e;r&&(e=this.mergeRowsBySubject(e));const s=new Map;i.forEach(S=>{const w=S.getPredicate(t.config.namespace);s.set(w,S)});const o=Array.from(new Set(e.map(S=>this.normalizeInlineIri(S["@id"]??S.subject??S.uri??S.id)).filter(S=>!!S)));if(o.length===0||s.size===0)return e;const a=Array.from(s.keys()).map(S=>`<${S}>`).join(" "),u=this.session.getDialect().getSPARQLExecutor(),c=[],l=new Map;for(const S of o){const w=this.inferSourceFromChild(S,t),v=l.get(w)??[];v.push(S),l.set(w,v)}for(const[S,w]of l.entries()){const _={type:"SELECT",query:`SELECT ?parent ?linkPred ?child ?pred ?obj WHERE {
|
|
34
|
+
VALUES ?parent { ${w.map(C=>`<${C}>`).join(" ")} }
|
|
35
|
+
VALUES ?linkPred { ${a} }
|
|
36
|
+
?parent ?linkPred ?child .
|
|
37
|
+
OPTIONAL { ?child ?pred ?obj . }
|
|
38
|
+
}`,prefixes:{}},T=await u.executeQueryWithSource(_,S);c.push(...T)}const d=t.config.namespace?.uri??t.config.namespace,f=new Map,m=new Map;c.forEach(S=>{const w=this.normalizeInlineIri(S.parent),v=this.normalizeInlineIri(S.linkPred),_=this.normalizeInlineIri(S.child),T=this.normalizeInlineIri(S.pred),C=this.normalizeInlineObjectValue(S.obj);if(!w||!v)return;const U=s.get(v);if(U){const D=f.get(w)??new Map,V=D.get(U.name)??[];_&&!V.includes(_)&&V.push(_),D.set(U.name,V),f.set(w,D)}if(!_||!T)return;const $=m.get(_)??{"@id":_,id:this.extractIdFromSubject(_,t)},W=this.normalizeInlinePredicateKey(T,d);if(C===void 0){m.set(_,$);return}const re=$[W];re===void 0?$[W]=C:Array.isArray(re)?$[W]=[...re,C]:$[W]=[re,C],m.set(_,$)});const g=S=>{if(Array.isArray(S))return S.map(v=>this.normalizeInlineIri(v)).filter(v=>!!v);const w=this.normalizeInlineIri(S);return w?[w]:[]},b=(S,w,v)=>{const _=S?f.get(S)?.get(v.name)??[]:[],C=(_.length>0?_:g(w)).map(U=>m.get(U)??{"@id":U,id:this.extractIdFromSubject(U,t)});return v.dataType==="array"?C:C[0]??null};return e.forEach(S=>{const w=this.normalizeInlineIri(S["@id"]??S.subject??S.uri??S.id);i.forEach(v=>{S[v.name]=b(w,S[v.name],v)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const r=e.lastIndexOf("#");if(r!==-1&&r<e.length-1)return e.slice(r+1);const i=e.lastIndexOf("/");return i!==-1&&i<e.length-1?e.slice(i+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((r,i)=>{for(const s of this.orderByClauses){const o=this.getOrderByValue(r,s.column),a=this.getOrderByValue(i,s.column),u=this.compareOrderByValues(o,a);if(u!==0)return s.direction==="desc"?-u:u}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,r=[];for(const i of e){const s=this.serializeValueForKey(i);t.has(s)||(t.add(s),r.push(i))}return r}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,r=t>0?e.slice(t):e;return this.limitCount===void 0?r:r.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const r=Object.keys(e).find(i=>i.endsWith(`.${t}`));if(r)return e[r]}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,r=[];return e.forEach(s=>{const o=this.normalizeInlineIri(s["@id"])??this.normalizeInlineIri(s.subject)??this.normalizeInlineIri(s.uri)??(typeof s.id=="string"?s.id:void 0);if(typeof process<"u"&&define_process_env_default$2?.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",o),!o){r.push(`__anon_${r.length}`),t.set(r[r.length-1],{...s});return}if(!t.has(o)){const c={...s};Object.entries(c).forEach(([l,d])=>{if(d===void 0)return;const f=this.getColumnDefinitionForRowKey(l);(f?.options?.isArray||f?.dataType==="array")&&!Array.isArray(d)&&(c[l]=[d])}),t.set(o,c),r.push(o);return}const a=t.get(o),u=c=>{if(c instanceof Date)return`date:${c.toISOString()}`;if(typeof c=="string")return`str:${c}`;if(typeof c=="number")return`num:${c}`;if(typeof c=="boolean")return`bool:${c}`;if(c==null)return"nil";try{return`obj:${JSON.stringify(c)}`}catch{return`obj:${String(c)}`}};Object.entries(s).forEach(([c,l])=>{if(l===void 0)return;const d=a[c];if(d===void 0){a[c]=l;return}const f=Array.isArray(d)?d:[d],m=Array.isArray(l)?l:[l],g=[...f];m.forEach(w=>{const v=u(w);g.some(_=>u(_)===v)||g.push(w)});const b=this.getColumnDefinitionForRowKey(c),S=b?.options?.isArray||b?.dataType==="array";!S&&g.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${c}' on subject '${o}'. Using first value.`),a[c]=g[0]):S?a[c]=g:a[c]=g.length===1?g[0]:g})}),r.map(s=>t.get(s))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,r]=e.split(".",2);if(!(!t||!r))return t===this.primaryAlias?this.selectedTable?.columns[r]:this.aliasToTable.get(t)?.columns?.[r]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const r=e.indexOf("#");if(r>0)return e.slice(0,r);if(e.startsWith("http://")||e.startsWith("https://"))return e;const i=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return i?i.startsWith("http")?i:`${this.session.getDialect().getPodUrl()}${i.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 r of this.joins){const i=await this.fetchJoinRows(r,t);t=this.mergeRowsWithJoin(t,r,i)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const g=await this.session.select().from(e.table);return this.normalizeJoinRows(e,g)}const r=e.resolvedConditions??[];if(r.length===0)return[];const[i]=r,s=i.left.alias===e.alias?i.left:i.right,o=s===i.left?i.right:i.left,a=new Map;for(const g of t){const b=this.getRowValueForColumn(g,o);if(b==null)continue;const S=this.serializeValueForKey(b);a.has(S)||a.set(S,b)}if(a.size===0)return[];const u=Array.from(a.values()),c=()=>this.session.select().from(e.table),l=e.table.getColumn(s.column),d=this.buildExactJoinLookupConditions(e,t);if(d&&d.length>0){const g=[];for(const b of d){const S=c(),v=await(conditionTargetsReservedIdentifier(b)?S.applyInternalQueryCondition(b):S.where(b));g.push(...v)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,g))}const f=this.buildJoinLookupCondition(l,u);if(f){const g=c(),S=await(conditionTargetsReservedIdentifier(f)?g.applyInternalQueryCondition(f):g.where(f));return this.normalizeJoinRows(e,S)}const m=await c();return this.normalizeJoinRows(e,m)}buildExactJoinLookupConditions(e,t){const r=e.resolvedConditions??[];if(r.length===0)return;const[i]=r,s=i.left.alias===e.alias?i.left:i.right,o=s===i.left?i.right:i.left,a=this.getRequiredSubjectTemplateVariables(e.table),u=s.column==="id"&&a.length>0;if(!u&&r.length===1)return;const c=new Map;for(const f of r){const m=f.left.alias===e.alias?f.left:f.right;c.set(m.column,f)}const l=[],d=new Set;for(const f of t){const m=this.getRowValueForColumn(f,o);if(m==null)continue;const g=typeof m=="string"&&this.isAbsoluteIri(m),b=[],S=[];let w=!1;for(const _ of r){const T=_.left.alias===e.alias?_.left:_.right,C=T===_.left?_.right:_.left,U=this.getRowValueForColumn(f,C);if(U==null){if(u&&!g&&a.includes(T.column))throw new Error(this.buildMissingJoinLocatorError(e,a.filter(W=>{const re=c.get(W);if(!re)return!0;const V=(re.left.alias===e.alias?re.left:re.right)===re.left?re.right:re.left,he=this.getRowValueForColumn(f,V);return he==null})));w=!0;break}const $=e.table.getColumn(T.column);if(!$){w=!0;break}b.push(eq($,U)),S.push(`${T.column}:${this.serializeValueForKey(U)}`)}if(w)continue;if(u&&!g){const _=a.filter(T=>{const C=c.get(T);if(!C)return!0;const $=(C.left.alias===e.alias?C.left:C.right)===C.left?C.right:C.left,W=this.getRowValueForColumn(f,$);return W==null});if(_.length>0)throw new Error(this.buildMissingJoinLocatorError(e,_))}if(b.length===0)continue;const v=S.join("|");d.has(v)||(d.add(v),l.push(b.length===1?b[0]:and(...b)))}return l.length>0?l: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(r=>r[1].split("|")[0]?.trim()||r[1]).filter(Boolean))).filter(r=>r!=="id"&&r!=="index"&&r!=="yyyy"&&r!=="MM"&&r!=="dd"&&r!=="HH"&&r!=="mm"&&r!=="ss"&&r!=="timestamp"&&r!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const r=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",i=Array.from(new Set(t)),s=i[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${r}" because locator variable(s) [${i.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${s}, join.${s})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(r=>{const i={};for(const[o,a]of Object.entries(r))i[`${e.alias}.${o}`]=a;const s=this.extractSubjectValue(r);if(s){i.subject=s,i["@id"]=s,i.uri=s,i[`${e.alias}.subject`]=s,i[`${e.alias}.@id`]=s,i[`${e.alias}.uri`]=s;const o=this.extractIdFromSubject(s,e.table);o!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||i[`${e.alias}.id`]===void 0)&&(i[`${e.alias}.id`]=o)}return i})}mergeRowsWithJoin(e,t,r){if(t.type==="crossJoin"){if(e.length===0||r.length===0)return[];const l=[];for(const d of e)for(const f of r)l.push({...d,...f});return l}const i=t.resolvedConditions??[];if(i.length===0)return e;const[s]=i,o=s.left.alias===t.alias?s.left:s.right,a=o===s.left?s.right:s.left,u=new Map;for(const l of r){const d=this.getRowValueForColumn(l,o);if(d==null)continue;const f=this.serializeValueForKey(d);u.has(f)||u.set(f,[]),u.get(f).push(l)}const c=[];for(const l of e){const d=this.getRowValueForColumn(l,a),f=this.serializeValueForKey(d),g=(d!=null?u.get(f)??[]:[]).filter(b=>this.joinRowMatchesAllConditions(l,b,t.alias,i));if(g.length===0){if(t.type==="innerJoin")continue;c.push({...l,...this.createEmptyJoinRow(t)});continue}for(const b of g)c.push({...l,...b})}return c}joinRowMatchesAllConditions(e,t,r,i){return i.every(s=>{const o=s.left.alias===r?s.left:s.right,a=o===s.left?s.right:s.left,u=this.getRowValueForColumn(e,a),c=this.getRowValueForColumn(t,o);return u==null||c===void 0||c===null?!1:this.serializeValueForKey(u)===this.serializeValueForKey(c)})}createEmptyJoinRow(e){const t={};for(const r of Object.keys(e.table.columns))t[`${e.alias}.${r}`]=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(r=>this.evaluateCondition(t,r)))}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 r=t.left,i=t.right,s=t.operator;if(!r)return!0;const o=this.resolveConditionOperandValue(e,r,this.primaryAlias),a=this.resolveConditionOperandValue(e,i);switch(s.toUpperCase()){case"=":return o===a;case"!=":case"<>":return o!==a;case">":return Number(o)>Number(a);case">=":return Number(o)>=Number(a);case"<":return Number(o)<Number(a);case"<=":return Number(o)<=Number(a);case"IN":return Array.isArray(a)&&a.includes(o);case"NOT IN":return Array.isArray(a)&&!a.includes(o);case"LIKE":return typeof o=="string"&&typeof a=="string"&&this.computeLikeMatch(o,a);default:return!0}}evaluateUnaryCondition(e,t){const r=t.operator,i=t.value;if(r.toUpperCase()==="NOT")return!this.evaluateCondition(e,i);if(!i)return!0;const s=this.resolveConditionOperandValue(e,i,this.primaryAlias);switch(r.toUpperCase()){case"IS NULL":return s==null;case"IS NOT NULL":return s!=null;default:return!0}}evaluateLogicalCondition(e,t){const r=t.operator,i=t.expressions??[];return r.toUpperCase()==="AND"?i.every(s=>this.evaluateCondition(e,s)):r.toUpperCase()==="OR"?i.some(s=>this.evaluateCondition(e,s)):!0}resolveConditionOperandValue(e,t,r){if(t instanceof SelectionAliasExpression)return e[t.alias];const i=this.getConditionColumnReference(t,r);return i?this.getRowValueForColumn(e,i):t}getColumnKeyCandidates(e){const t=[],r=this.primaryAlias;return e.alias===r&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const r=this.getColumnKeyCandidates(t);for(const i of r)if(i in e)return e[i]}shouldUseSubjectIdentityColumn(e,t){const r=e?.columns?.[t];return!!(r?._virtualId||r?.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 s=parsePodResourceRef(t,e);if(s)return s.templateValues.id??s.resourceId}if(t){const s=this.session.getDialect?.(),a=(s?.getUriResolver?.()??new UriResolverImpl(s?.getPodUrl?.()??"")).parseSubject(e,t);if(a&&a.id)return a.id}const r=e.indexOf("#");if(r!==-1)return e.slice(r);const i=e.lastIndexOf("/");if(i!==-1){const s=e.slice(i+1);if(s.length>0)return s}}computeLikeMatch(e,t){const r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r.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(s=>s.id||s["@id"]).filter(s=>typeof s=="string"&&s.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 r=this.getRowsWithDefaults();return{table:this.table,rows:r}}}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 r=this.sql.queryChunks.join(""),i=inferSPARQLQueryType(r);if(!i)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:i,query:r,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):[],r={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},i=await this.session.execute(r),s=this.returningFields?await this.fetchReturningRowsBySubjects(t):i;return await this.runAfterInsertHooks(s),s}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(r=>generateSubjectUri(r,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const r=this.buildHookContext();if(!r){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const i of e)try{await t.afterInsert(r,i)}catch(s){console.error("[InsertQueryBuilder] afterInsert hook failed:",s)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),r=e.getAuthenticatedFetch();return!t||!r?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:r},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(r=>this.applyDefaultValues(r))}applyDefaultValues(e){const t={...e},r=this.table?.columns??{},i=Object.entries(r);for(const[s,o]of i.filter(([,a])=>!this.isPrimaryKeyColumn(a)))this.applyDefaultValue(t,s,o);for(const[s,o]of i.filter(([,a])=>this.isPrimaryKeyColumn(a)))this.applyDefaultValue(t,s,o);return t}applyDefaultValue(e,t,r){if(e[t]===void 0){const i=r.options?.defaultValue;i!==void 0&&(e[t]=this.resolveDefaultValue(i,r,e))}}resolveDefaultValue(e,t,r){const i=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&i)return renderDefaultIdTemplate(e,{key:i,row:r,resource:this.table});if(typeof e!="function")return e;const s=e;return s.length===0?s():s(i,r)}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 r=this.normalizeWhereConditionsForUpdate();if(!r)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:r}}}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,r=e.right,i=typeof t=="string"?t:t?.name;if(i&&r!==void 0)return{[i]:r}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}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`);const r=this.toIR();return t.convertUpdate(r.data,r.where,r.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(),r=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(a=>resolveRowSubject(a)).filter(a=>typeof a=="string"&&a.length>0),i={type:"update",table:this.table,data:e.data,where:e.where,plan:e},s=await this.session.execute(i),o=this.returningFields?await this.fetchReturningRowsBySubjects(r):s;return await this.runAfterUpdateHooks(o),o}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),r=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),i=Object.entries(this.updateData??{}).filter(([,s])=>Array.isArray(s));return i.length===0?r:r.map(s=>{const o={...s};for(const[a,u]of i)a in o&&(o[a]=[...u]);return o})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const r=this.buildHookContext();if(!r){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const i=this.updateData??{};for(const s of e)try{await t.afterUpdate(r,s,i)}catch(o){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",o)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),r=e.getAuthenticatedFetch();return!t||!r?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:r},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 r=this.normalizeWhereConditionsForDelete();return{table:this.table,where:r}}}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,r=e.right,i=typeof t=="string"?t:t?.name;if(i&&r!==void 0)return{[i]:r}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}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`);const r=this.toIR();return t.convertDelete(r.where??{},r.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):[],r=t.map(a=>resolveRowSubject(a)).filter(a=>typeof a=="string"&&a.length>0),i={type:"delete",table:this.table,where:e.where,plan:e},s=await this.session.execute(i),o=this.returningFields?projectReturningRows(orderRowsBySubjects(t,r),this.returningFields):s;return await this.runAfterDeleteHooks(o),o}}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 r=this.session.select().from(this.table);return e&&(r=r.where(e)),await r}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const r=this.buildHookContext();if(!r){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const i of e)try{await t.afterDelete(r,i)}catch(s){console.error("[DeleteQueryBuilder] afterDelete hook failed:",s)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),r=e.getAuthenticatedFetch();return!t||!r?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:r},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,r={}){this.dialect=e,this._schema=t,this.options=r}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(r){if(t!=="best-effort")throw r;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(r){if(t!=="best-effort")throw r}}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 i of e.joins)i?.table&&await this.ensureInitialized(i.table);const r=await this.dialect.query(e);return this.updateSubjectIndex(e,r),r}updateSubjectIndex(e,t){if(e.type==="select")return;const r=this.dialect;if(typeof r.registerResourceSubject!="function"&&typeof r.unregisterResourceSubject!="function")return;const i=this.resolveOperationSubjects(e,t);if(e.type==="delete"){i.forEach(s=>r.unregisterResourceSubject?.(e.table,s));return}i.forEach(s=>r.registerResourceSubject?.(e.table,s))}resolveOperationSubjects(e,t){const r=new Set;for(const i of t){const s=this.getKnownRowIri(i);s&&r.add(s)}if(e.type==="insert"){const i=e.plan;(Array.isArray(i?.rows)?i.rows:[]).forEach(o=>{try{r.add(generateSubjectUri(o,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(r)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const r of["@id","subject","uri","source"]){const i=t[r];if(typeof i=="string"&&/^https?:\/\//.test(i))return i}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 r=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(i,s,o){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),r.call(this,i,s,o)},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 r=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!r||typeof r.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return r},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-3WfrNbcG.js").then(t=>t.i),__vite__mapDeps([10,1,2]));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,r)=>{try{const i=await e(t,r),s=new Map;i.headers&&i.headers.forEach((u,c)=>{s.set(c.toLowerCase(),u||"")});const a={...i,headers:{get:u=>{const c=u.toLowerCase();return s.get(c)||null},has:u=>{const c=u.toLowerCase();return s.has(c)},forEach:u=>{s.forEach((c,l)=>u(c,l))},entries:()=>s.entries(),keys:()=>s.keys(),values:()=>s.values(),[Symbol.iterator]:()=>s.entries(),includes:u=>{if(!u)return!1;for(const[c,l]of Array.from(s.entries()))if(c.toLowerCase().includes(u.toLowerCase())||l.toLowerCase().includes(u.toLowerCase()))return!0;return!1}},status:i.status||200,statusText:i.statusText||"OK",ok:i.ok!==void 0?i.ok:!0,url:i.url||(typeof t=="string"?t:t.toString()),type:i.type||"basic",redirected:i.redirected||!1,body:i.body,bodyUsed:i.bodyUsed||!1,includes:u=>{if(!u)return!1;for(const[c,l]of Array.from(s.entries()))if(c.toLowerCase().includes(u.toLowerCase())||l.toLowerCase().includes(u.toLowerCase()))return!0;return!1},text:async()=>{try{return await i.text()}catch(u){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(u)),""}},json:async()=>{try{return await i.json()}catch(u){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(u)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,r)}catch(u){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(u)),a}}};return a}catch(i){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(i)),i}}}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()},r=this.sources[0];if(!r)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",r)),await this.executeQueryWithSource(t,r)}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(s=>{const o=s,a={},u=(c,l)=>{const d=this.extractBindingKeyName(c);d&&(a[d]=this.convertComunicaTerm(l))};if(o&&typeof o.forEach=="function")o.forEach((c,l)=>u(l,c));else if(o&&typeof o.entries=="function")for(const[c,l]of o.entries())u(c,l);else for(const c in o)Object.prototype.hasOwnProperty.call(o,c)&&u(c,o[c]);return a})}catch(r){throw console.error("SELECT query failed:",this.formatError(r)),r}}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(r){throw console.error("ASK query failed:",this.formatError(r)),r}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const r=[];for(const i of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${i}:`,e.query.substring(0,100)+"...");let s=null;try{const c=await this.fetchFn(i,{method:"HEAD",headers:{Accept:"text/turtle"}});c.ok&&(s=c.headers.get("ETag"),this.logging&&s&&console.log(`[UPDATE] Got ETag for ${i}: ${s}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${i}, continuing without ETag`)}const o={"Content-Type":"application/sparql-update","If-Match":s??"*"},a=async c=>this.fetchFn(i,{method:"PATCH",headers:c,body:e.query}),u=await a(o);if(u.ok)r.push({success:!0,source:i,status:u.status}),await this.invalidateCache(t,i);else if(u.status===409||u.status===412){this.logging&&console.log(`[UPDATE] ${u.status} conflict for ${i}, trying multiple retry strategies`);let c=!1;if(u.status===412)try{const l=await this.fetchFn(i,{method:"HEAD",headers:{Accept:"text/turtle"}});if(l.ok){const d=l.headers.get("ETag");if(d){const f={...o,"If-Match":d},m=await a(f);m.ok&&(r.push({success:!0,source:i,status:m.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,i),c=!0)}}}catch(l){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",l)}if(!c)try{const l=await a({"Content-Type":"application/sparql-update"});l.ok&&(r.push({success:!0,source:i,status:l.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,i),c=!0)}catch(l){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",l)}if(!c)try{if((await this.fetchFn(i,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const d=await this.fetchFn(i,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});d.ok&&(r.push({success:!0,source:i,status:d.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,i),c=!0)}}catch(l){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",l)}if(!c){const l=await u.text();r.push({success:!1,source:i,error:`All retry strategies failed: ${u.status} ${u.statusText}`,details:l})}}else{const c=await u.text();r.push({success:!1,source:i,error:`${u.status} ${u.statusText}`,details:c})}}catch(s){r.push({success:!1,source:i,error:this.formatError(s)})}return r}catch(r){throw console.error("UPDATE query failed:",this.formatError(r)),r}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const r=e.invalidateHttpCache;if(typeof r=="function")try{await r.call(e,t)}catch(i){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(i))}}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 r=t.datatype.value;if(typeof r=="string"){if(r.includes("#integer")||r.includes("#int"))return parseInt(String(t.value),10);if(r.includes("#decimal")||r.includes("#double"))return parseFloat(String(t.value));if(r.includes("#boolean"))return t.value==="true";if(r.includes("#dateTime"))return new Date(String(t.value));if(r.includes("#json"))try{return JSON.parse(String(t.value))}catch(i){return console.warn("Failed to parse JSON value:",t.value,this.formatError(i)),t.value}else if(r.includes("#jsonArray")||r.includes("solid/terms#jsonArray"))try{const i=JSON.parse(String(t.value));return Array.isArray(i)?i:(console.warn("Expected array but got:",typeof i,i),[i])}catch(i){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(i)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const r=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let i;return t?i=t:i={type:"SELECT",query:`
|
|
39
|
+
SELECT ?subject ?predicate ?object WHERE {
|
|
40
|
+
?subject ?predicate ?object .
|
|
41
|
+
FILTER(STRSTARTS(STR(?subject), "${r}"))
|
|
42
|
+
}
|
|
43
|
+
`},this.executeQueryWithSource(i,r)}async executeQueryWithSource(e,t,r="auto"){try{if(r==="sparql"&&(e.type==="SELECT"||e.type==="ASK"))return await this.executeDirectSparqlQuery(e,t);const i=await this.initEngine(),s=this.createSourceRef(t,r);if(this.logging&&(console.log(`[Comunica] Executing ${e.type} query on ${t}:`,e.query),console.log("[Debug] sparqlQuery object:",JSON.stringify(e,null,2))),e.type==="SELECT"){const a=await(await i.queryBindings(e.query,{sources:[s],fetch:this.fetchFn})).toArray(),u=a.map(c=>{const l=c,d={};if(this.logging&&a.indexOf(c)===0&&(console.log("[Debug] Binding object:",l),console.log("[Debug] Binding type:",typeof l),console.log("[Debug] Binding constructor:",l.constructor?.name),console.log("[Debug] Binding keys:",Object.keys(l)),console.log("[Debug] Has entries method:",typeof l.entries),console.log("[Debug] Has keys method:",typeof l.keys),console.log("[Debug] Has get method:",typeof l.get)),l.entries&&typeof l.entries=="function")try{for(const[f,m]of l.entries()){const g=this.extractBindingKeyName(f);g&&(d[g]=this.convertComunicaTerm(m))}}catch(f){console.warn("[Warning] binding.entries() failed:",this.formatError(f))}else if(l.keys&&typeof l.keys=="function"&&typeof l.get=="function")try{for(const f of l.keys()){const m=l.get(f);if(m){const g=this.extractBindingKeyName(f);if(!g)continue;const b=this.convertComunicaTerm(m);d[g]=b,this.logging&&a.indexOf(c)===0&&(console.log(`[Debug] Variable: ${g}, Term: ${b}`),console.log("[Debug] Variable object:",f),console.log("[Debug] Term object:",m))}}}catch(f){console.warn("[Warning] binding.keys()/get() failed:",this.formatError(f))}if(Object.keys(d).length===0){for(const f in l)if(Object.prototype.hasOwnProperty.call(l,f)&&f!=="type"&&f!=="size"){const m=l[f];if(m){const g=this.extractBindingKeyName(f);g&&(d[g]=this.convertComunicaTerm(m))}}}return d});return this.logging&&console.log(`[Comunica] ${e.type} query results:`,u),u}else if(e.type==="ASK"){const o=await i.queryBoolean(e.query,{sources:[s],fetch:this.fetchFn});return this.logging&&console.log(`[Comunica] ${e.type} query result:`,o),[{result:o}]}else{const o=this.sources;this.sources=[t];try{const a=await this.executeUpdate(e,i),u=a.filter(c=>!c.success);if(u.length>0){const c=u[0],l=c&&c.error?c.error:"UPDATE operation failed";throw new Error(l)}return this.logging&&console.log(`[Comunica] ${e.type} operation completed successfully`),a}finally{this.sources=o}}}catch(i){throw this.logging&&console.error("[Comunica] Query execution failed:",this.formatError(i)),i}}async executeDirectSparqlQuery(e,t){const r=new URL(t);r.searchParams.set("query",e.query);const i=await this.fetchFn(r,{headers:{Accept:"application/sparql-results+json"}});if(!i.ok){const a=(await i.text()).trim(),u=a?`: ${a.slice(0,500)}`:"";throw new Error(`SPARQL endpoint returned HTTP ${i.status}${u}`)}const s=await i.json();if(e.type==="ASK")return[{result:s.boolean===!0}];const o=s.results?.bindings;return Array.isArray(o)?o.map(a=>{const u={};for(const[c,l]of Object.entries(a)){if(!l||typeof l!="object")continue;const d=l.type==="uri"?{termType:"NamedNode",value:l.value}:l.type==="bnode"?{termType:"BlankNode",value:l.value}:{termType:"Literal",value:l.value,datatype:l.datatype?{value:l.datatype}:void 0};u[c]=this.convertComunicaTerm(d)}return u}):[]}addSource(e){this.sources.includes(e)||this.sources.push(e)}removeSource(e){const t=this.sources.indexOf(e);t>-1&&this.sources.splice(t,1)}getSources(){return[...this.sources]}}const SolidSPARQLExecutor=ComunicaSPARQLExecutor,sparqlExecutor=Object.freeze(Object.defineProperty({__proto__:null,ComunicaSPARQLExecutor,SolidSPARQLExecutor},Symbol.toStringTag,{value:"Module"}));var define_process_env_default$1={};class PodExecutor{constructor(e){this.deps=e}async query(e){await this.deps.ensureConnected(),await this.deps.ensureTableResourcePath(e.table);const t=this.deps.resolveTableResource(e.table),r=e.type==="select"?this.getSelectStrategy(e,t):this.deps.getLdpStrategy(),{containerUrl:i,resourceUrl:s}=this.deps.resolveTableUrls(e.table),o=this.deps.normalizeResourceUrl(s),u=(e.type==="select"?this.getExactSelectResourceUrl(e):void 0)??(e.type==="select"&&t.mode==="sparql"?t.endpoint:o);try{switch(e.type){case"select":return await this.executeSelect(e,r,i,u);case"insert":return await this.executeInsert(e,r,i,o,t);case"update":return await this.executeUpdate(e,r,i,o,t);case"delete":return await this.executeDelete(e,r,i,o,t);default:throw new Error(`Unsupported operation type: ${e.type}`)}}catch(c){throw typeof process<"u"&&define_process_env_default$1?.LINX_DEBUG==="1"&&console.error(`${e.type.toUpperCase()} operation failed:`,c),c}}shouldSkipResourcePreparation(){return this.deps.shouldSkipResourcePreparation?.()??!1}shouldUseWriteTimeResourcePreparation(){return this.deps.shouldUseWriteTimeResourcePreparation?.()??this.shouldSkipResourcePreparation()}shouldContinueAfterResourcePreparationError(){return this.deps.shouldContinueAfterResourcePreparationError?.()??!1}async prepareResource(e,t){if(!this.shouldSkipResourcePreparation())try{await t()}catch(r){if(!this.shouldContinueAfterResourcePreparationError())throw r;typeof process<"u"&&define_process_env_default$1?.LINX_DEBUG==="1"&&console.warn(`[${e}] Resource preparation failed; continuing in best-effort mode:`,r)}}async executeSelect(e,t,r,i){let s;if(e.plan&&this.deps.isSelectPlan(e.plan))s=e.plan;else{if(e.plan&&!this.deps.isSelectPlan(e.plan))throw new Error("Invalid plan supplied for select operation");{const a=e.table.config.name??"table",u={baseTable:e.table,baseAlias:a,selectAll:!0,conditionTree:e.where,limit:e.limit,offset:e.offset,distinct:e.distinct,aliasToTable:new Map([[a,e.table]]),tableToAlias:new Map([[e.table,a]])};u._simpleSelectOptions=e.sql?void 0:{table:e.table,where:e.where,limit:e.limit,offset:e.offset,orderBy:e.orderBy,distinct:e.distinct},u._sql=e.sql,s=u}}return await t.executeSelect(s,r,i)}getSelectStrategy(e,t){return this.deps.getStrategy(e.table)}isExactIriSelect(e){const t=e.where;if(!t||typeof t!="object"||"type"in t)return!1;const r=t["@id"];return typeof r=="string"&&r.startsWith("http")}getExactSelectResourceUrl(e){if(!this.isExactIriSelect(e))return;const t=e.where["@id"],r=t.indexOf("#");return r>=0?t.slice(0,r):t}async executeInsert(e,t,r,i,s){const o=Array.isArray(e.values)?e.values:[e.values];if(!o||o.length===0)throw new Error("INSERT operation requires at least one value");const a=this.shouldUseWriteTimeResourcePreparation(),u=a&&!this.shouldSkipResourcePreparation();if(!a&&!this.deps.preparedContainers.has(this.deps.normalizeContainerKey(r))&&await this.prepareResource("INSERT",()=>this.deps.ensureContainerExists(r)),s.mode==="ldp"&&!a&&!this.deps.preparedResources.has(this.deps.normalizeResourceKey(i))&&await this.prepareResource("INSERT",()=>this.deps.ensureResourceExists(i,{createIfMissing:!0})),s.mode==="ldp"&&!a)for(const d of o)try{const f=this.deps.sparqlConverter.generateSubjectUri(d,e.table),m={type:"ASK",query:`ASK { <${f}> ?p ?o }`,prefixes:{}};if((await this.deps.sparqlExecutor.executeQueryWithSource(m,i))[0]?.result)throw new Error(`Duplicate primary key: ${f} already exists.`)}catch(f){if(f.message&&f.message.includes("Duplicate primary key"))throw f;await this.deps.sparqlExecutor.invalidateHttpCache(i)}const c={...this.deps.isInsertPlan(e.plan)?e.plan:{table:e.table,rows:o},ensureContainerExists:a?void 0:async d=>{await this.prepareResource("INSERT",()=>this.deps.ensureContainerExists(d))},repairContainerOnWriteFailure:u?async d=>{await this.prepareResource("INSERT",()=>this.deps.ensureContainerExists(d))}:void 0,skipResourceExistenceCheck:a||this.deps.isInsertPlan(e.plan)&&e.plan.skipResourceExistenceCheck===!0,tableRegistry:this.deps.getTableRegistries?.().tableRegistry,tableNameRegistry:this.deps.getTableRegistries?.().tableNameRegistry};if(!t.executeInsert)throw new Error("Strategy does not support INSERT operations");return await t.executeInsert(c,r,i)}async executeUpdate(e,t,r,i,s){if(!e.data)throw new Error("UPDATE operation requires data");if(!e.where||Object.keys(e.where).length===0)throw new Error("UPDATE operation requires where conditions to locate target resources");if(s.mode==="ldp"&&!this.shouldUseWriteTimeResourcePreparation()){if(!this.deps.preparedContainers.has(this.deps.normalizeContainerKey(r)))try{await this.prepareResource("UPDATE",()=>this.deps.ensureContainerExists(r))}catch(u){const c=u instanceof Error?u.message:String(u);if(c.includes("Failed to check container: 401")||c.includes("Failed to check container: 403"))console.warn(`[UPDATE] Skipping container existence check for ${r}: ${c}`);else throw u}this.deps.preparedResources.has(this.deps.normalizeResourceKey(i))||await this.prepareResource("UPDATE",()=>this.deps.ensureResourceExists(i,{createIfMissing:!1}))}const o=this.deps.isUpdatePlan(e.plan)?e.plan:{table:e.table,data:e.data,where:e.where};if(s.mode==="sparql"){const u=await this.deps.ensureIdentifierCondition(o.where,o.table,i);if(!u)return console.warn("[UPDATE] No matching subjects found for provided condition, skipping update."),[];o.where=u}if(!t.executeUpdate)throw new Error("Strategy does not support UPDATE operations");return await t.executeUpdate(o,r,i)}async executeDelete(e,t,r,i,s){if(s.mode==="ldp"&&!this.shouldUseWriteTimeResourcePreparation()&&(this.deps.preparedContainers.has(this.deps.normalizeContainerKey(r))||await this.prepareResource("DELETE",()=>this.deps.ensureContainerExists(r)),!(this.deps.preparedResources.has(this.deps.normalizeResourceKey(i))||this.shouldSkipResourcePreparation()?!0:await this.deps.resourceExists(i))))return console.log("[DELETE] Target resource does not exist, skipping execution"),[{success:!0,source:i,status:404}];const o=this.deps.isDeletePlan(e.plan)?e.plan:{table:e.table,where:e.where};if(s.mode==="sparql"&&o.where){const u=await this.deps.ensureIdentifierCondition(o.where,o.table,i);if(!u)return console.warn("[DELETE] No matching subjects found for provided condition, skipping delete."),[];o.where=u}if(!t.executeDelete)throw new Error("Strategy does not support DELETE operations");return await t.executeDelete(o,r,i)}}function isSameOrigin(n,e){try{const t=new URL(n),r=new URL(e);return t.origin===r.origin}catch{return!1}}function getFetchForOrigin(n,e,t){return isSameOrigin(n,e)?t:fetch}const normalize$1=n=>n.endsWith("/")?n:`${n}/`,pickSameOrigin=(n,e)=>{try{const t=new URL(n).origin;return e.find(i=>{try{return new URL(i).origin===t}catch{return!1}})||null}catch{return null}},deriveFromUrl=n=>{if(!n||n.trim().length===0)return null;try{const e=new URL(n),r=e.pathname.split("/").filter(Boolean)[0],i=r&&r!=="profile"?`/${r}/`:"/";return normalize$1(`${e.origin}${i}`)}catch{return null}};function resolvePodBase(n){const{webId:e,podUrl:t,storages:r}=n;if(t?.trim())try{return normalize$1(new URL(t).href)}catch{}const i=(r||[]).filter(Boolean);if(i.length>0){const c=pickSameOrigin(e,i)||i[0];return normalize$1(c)}const s=deriveFromUrl(t),o=deriveFromUrl(e),a=u=>{if(!u)return!1;try{return new URL(u).pathname!=="/"}catch{return!1}};if(a(s))return s;if(a(o))return o;if(s)return s;if(o)return o;try{const u=new URL(e);return normalize$1(u.origin)}catch{return normalize$1(e)}}const PIM_STORAGE="http://www.w3.org/ns/pim/space#storage",SOLID_POD="http://www.w3.org/ns/solid/terms#pod";class WebIdResolver{constructor(){this.cache=new Map}extractStorageFromProfile(e,t,r){const i=r?.split(";")[0]?.trim().toLowerCase(),o=new N3Parser$1({baseIRI:e,format:i==="application/n-triples"?"N-Triples":void 0}).parse(t),a=[PIM_STORAGE,SOLID_POD];for(const u of a){const c=o.find(l=>l.subject.value===e&&l.predicate.value===u);if(c?.object?.value)return c.object.value}return null}async resolveStorage(e,t){if(this.cache.has(e))return this.cache.get(e)??null;try{const i=await(t??fetch)(e,{headers:{Accept:"text/turtle, application/n-triples;q=0.9, text/n3;q=0.8, */*;q=0.1"}});if(!i.ok)throw new Error(`Failed to fetch WebID profile: ${i.status} ${i.statusText}`);const s=await i.text(),o=this.extractStorageFromProfile(e,s,i.headers.get("content-type"));if(o){const a=o.endsWith("/")?o:`${o}/`;return console.log(`[WebIdResolver] Resolved storage for ${e} -> ${a}`),this.cache.set(e,a),a}}catch(r){console.warn(`[WebIdResolver] Failed to resolve storage for ${e}`,r)}return null}clearCache(){this.cache.clear()}}const webIdResolver=new WebIdResolver,REQUEST_ID_DETECTION_TIMEOUT_MS=3e3;function generateRequestId(){const n=Date.now().toString(36),e=Math.random().toString(36).substring(2,8);return`${n}-${e}`}class PodRuntime{constructor(e){this.storageUrl=null,this.storageResolvedAt=0,this.connected=!1,this.wrappedFetch=null,this.requestIdSupported=null,this.storageTTL=300*1e3,this.session=e.session,this.webId=e.webId,this.podUrl=resolvePodBase({webId:this.webId,podUrl:e.podUrl}),this.explicitPodUrl=typeof e.podUrl=="string"&&e.podUrl.trim().length>0,e.storageTTL!==void 0&&(this.storageTTL=e.storageTTL)}async detectRequestIdSupport(){const e=new AbortController,t=setTimeout(()=>e.abort(),REQUEST_ID_DETECTION_TIMEOUT_MS);try{return((await globalThis.fetch(this.podUrl,{method:"OPTIONS",signal:e.signal})).headers.get("Access-Control-Allow-Headers")||"").toLowerCase().includes("x-request-id")}catch{return!1}finally{clearTimeout(t)}}createWrappedFetch(){const e=this.session.fetch,t=this;return async(r,i)=>{if(!t.requestIdSupported)return e(r,i);const s=generateRequestId(),o=new Headers(i?.headers);return o.has("X-Request-ID")||o.set("X-Request-ID",s),e(r,{...i,headers:o})}}getSession(){return this.session}getFetch(){return this.wrappedFetch||(this.wrappedFetch=this.createWrappedFetch()),this.wrappedFetch}getWebId(){return this.webId}getPodUrl(){return this.podUrl}getStorageUrl(){return this.storageUrl}isStorageExpired(){return this.storageResolvedAt?Date.now()-this.storageResolvedAt>this.storageTTL:!0}async getPodUrlWithRefresh(){return this.isStorageExpired()&&await this.refreshStorage(),this.podUrl}async refreshStorage(){if(this.explicitPodUrl)return this.storageUrl=this.podUrl,this.storageResolvedAt=Date.now(),this.storageUrl;webIdResolver.clearCache();const e=await webIdResolver.resolveStorage(this.webId,this.getFetch());return e&&(this.storageUrl=e,this.storageResolvedAt=Date.now(),!this.explicitPodUrl&&e!==this.podUrl&&(console.log(`[PodRuntime] Storage refreshed: ${e}`),this.podUrl=e)),this.storageUrl}setPodUrl(e){this.podUrl=e.endsWith("/")?e:`${e}/`}isConnected(){return this.connected}async connect(){if(!this.connected)try{if(console.log(`Connecting to Solid Pod: ${this.podUrl}`),console.log(`Using WebID: ${this.webId}`),this.explicitPodUrl){this.requestIdSupported=!1,this.wrappedFetch=this.createWrappedFetch(),this.storageUrl=this.podUrl,this.storageResolvedAt=Date.now(),this.connected=!0,console.log("Using explicit Pod URL; skipping Pod root probe");return}this.requestIdSupported=await this.detectRequestIdSupport(),this.wrappedFetch=this.createWrappedFetch();const e=await webIdResolver.resolveStorage(this.webId,this.wrappedFetch);e&&(this.storageUrl=e,this.storageResolvedAt=Date.now(),e!==this.podUrl&&(console.log(`[PodRuntime] IdP-SP separation detected: storage at ${e}`),this.podUrl=e));const t=await this.wrappedFetch(this.podUrl,{method:"HEAD"}),r=t.status;if(r===500&&!this.explicitPodUrl){const i=this.requestIdSupported?t.headers.get("X-Request-ID")||"unknown":"disabled";throw console.error(`Pod probe failed, X-Request-ID: ${i}`),new Error(`Failed to connect to Pod: ${r} ${t.statusText}`)}r===500&&this.explicitPodUrl&&console.warn(`Pod root returned ${r} for explicit Pod URL, continuing (child resources may still be writable)`),t.ok?console.log("Successfully connected to Solid Pod"):console.warn(r===401||r===403?`Pod root returned ${r}, continuing (child resources may still be writable)`:`Pod root returned ${r}, continuing (child resources may still be writable)`),this.connected=!0}catch(e){throw console.error("Failed to connect to Pod:",e),e}}async disconnect(){this.connected=!1,console.log("Disconnected from Solid Pod")}}var Wildcard={},hasRequiredWildcard;function requireWildcard(){if(hasRequiredWildcard)return Wildcard;hasRequiredWildcard=1;let n=class{constructor(){return e||this}equals(r){return r&&this.termType===r.termType}};Object.defineProperty(n.prototype,"value",{enumerable:!0,value:"*"}),Object.defineProperty(n.prototype,"termType",{enumerable:!0,value:"Wildcard"});var e=new n;return Wildcard.Wildcard=n,Wildcard}var SparqlParser_1,hasRequiredSparqlParser;function requireSparqlParser(){if(hasRequiredSparqlParser)return SparqlParser_1;hasRequiredSparqlParser=1;var n=(function(){var e=function(qe,je,He,Ge){for(He=He||{},Ge=qe.length;Ge--;He[qe[Ge]]=je);return He},t=[6,12,13,15,16,24,32,36,41,45,100,110,113,115,116,123,126,131,197,224,229,308,329,330,331,332,333],r=[2,247],i=[100,110,113,115,116,123,126,131,329,330,331,332,333],s=[2,409],o=[1,18],a=[1,27],u=[13,16,45,197,224,229,308],c=[28,29,53],l=[28,53],d=[1,42],f=[1,45],m=[1,41],g=[1,44],b=[123,126],S=[1,67],w=[39,45,87],v=[13,16,45,197,224,308],_=[1,87],T=[2,281],C=[1,86],U=[13,16,45,82,87,89,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312],$=[6,28,29,53,63,70,73,81,83,85],W=[6,13,16,28,29,53,63,70,73,81,83,85,87,308],re=[6,13,16,28,29,45,53,63,70,73,81,82,83,85,87,89,197,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314],D=[6,13,16,28,29,31,39,45,47,48,53,63,70,73,81,82,83,85,87,89,109,112,121,123,126,128,159,160,161,163,164,174,193,197,224,229,231,232,242,246,250,263,265,272,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314,317,318,335,337,338,340,341,342,343,344,345,346],V=[13,16,308],he=[112,132,327,334],z=[13,16,112,132,308],_e=[1,111],Ce=[1,117],Fe=[112,132,327,328,334],ze=[13,16,112,132,308,328],ae=[28,29,45,53,87],ve=[1,138],L=[1,151],ie=[1,128],xe=[1,127],ue=[1,129],De=[1,140],ke=[1,141],We=[1,142],Oe=[1,143],te=[1,144],le=[1,145],Te=[1,147],G=[1,148],P=[2,457],x=[1,158],A=[1,159],O=[1,160],H=[1,152],Q=[1,153],de=[1,156],M=[1,171],ne=[1,172],ge=[1,173],Y=[1,174],Be=[1,175],Je=[1,176],Ne=[1,167],Ze=[1,168],B=[1,169],R=[1,170],N=[1,157],F=[1,166],me=[1,161],Re=[1,162],we=[1,163],Qe=[1,164],et=[1,165],ot=[6,13,16,29,31,45,82,85,87,89,112,159,160,161,163,164,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335],ct=[1,195],at=[6,31,73,81,83,85],Qt=[2,285],wt=[1,199],dt=[1,201],$t=[6,31,70,73,81,83,85],yt=[2,283],At=[1,207],It=[1,218],Bt=[1,223],k=[1,219],j=[1,225],Ie=[1,226],Ae=[1,224],Ve=[6,63,70,73,81,83,85],ht=[1,236],gt=[2,334],rr=[1,243],Pt=[1,241],Et=[6,193],ar=[2,349],fr=[2,339],Ot=[28,128],nr=[47,48,193,272],Jt=[47,48,193,242,272],zt=[47,48,193,242,246,272],lt=[47,48,193,242,246,250,263,265,272,290,297,298,299,300,301,302,341,342,343,344,345,346],rt=[39,47,48,193,242,246,250,263,265,272,290,297,298,299,300,301,302,338,341,342,343,344,345,346],Rt=[1,271],Jr=[1,270],Ct=[6,13,16,29,31,39,45,47,48,70,73,76,78,81,82,83,85,87,89,112,159,160,161,163,164,193,231,242,246,250,263,265,268,269,270,271,272,273,274,276,277,279,280,283,285,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335,338,341,342,343,344,345,346,347,348,349,350,351],Ft=[1,281],tn=[1,280],Wt=[13,16,29,31,39,45,47,48,82,85,87,89,112,159,160,161,163,164,174,193,197,224,229,231,232,242,246,250,263,265,272,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314,317,318,335,338,341,342,343,344,345,346],Nr=[45,89],Or=[13,16,29,31,39,45,47,48,82,85,87,89,112,159,160,161,163,164,174,193,197,224,229,231,232,242,246,250,263,265,272,290,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314,317,318,335,338,341,342,343,344,345,346],jr=[13,16,31,82,174,294,295,296,297,298,299,300,301,302,303,304,305,306,308,312],Mr=[31,89],Br=[48,87],wr=[6,13,16,45,48,82,87,89,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,337,338],cr=[6,13,16,39,45,48,82,87,89,231,263,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,337,338,340],rn=[1,313],p=[6,85],h=[6,31,81,83,85],y=[2,361],E=[2,353],I=[1,343],q=[31,112,335],K=[13,16,29,31,45,48,82,85,87,89,112,159,160,161,163,164,193,197,224,229,231,232,272,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,317,318,335],ce=[13,16,29,31,45,48,82,85,87,89,112,159,160,161,163,164,193,197,224,229,231,232,272,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314,317,318,335],ee=[6,109,193],se=[31,112],oe=[13,16,45,82,87,224,263,265,268,269,270,271,273,274,276,277,279,280,283,285,294,295,296,297,298,299,300,301,302,303,304,305,306,308,312,346,347,348,349,350,351],pe=[1,390],Se=[1,391],Ee=[13,16,87,197,308,314],Pe=[13,16,39,45,82,87,224,263,265,268,269,270,271,273,274,276,277,279,280,283,285,294,295,296,297,298,299,300,301,302,303,304,305,306,308,312,346,347,348,349,350,351],$e=[1,417],Le=[1,418],Z=[13,16,48,197,229,308],fe=[6,31,85],ye=[6,13,16,31,45,73,81,83,85,268,269,270,271,273,274,276,277,279,280,283,285,308,346,347,348,349,350,351],be=[6,13,16,29,31,45,73,76,78,81,82,83,85,87,89,112,159,160,161,163,164,231,268,269,270,271,273,274,276,277,279,280,283,285,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335,346,347,348,349,350,351],Ue=[29,31,85,112,159,160,161,163,164],Me=[1,443],Ye=[1,444],Ke=[1,449],st=[31,112,193,232,318,335],Xe=[13,16,45,48,82,87,89,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312],tt=[13,16,31,45,48,82,87,89,112,193,231,232,272,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,317,318,335],bt=[13,16,29,31,45,48,82,85,87,89,112,159,160,161,163,164,193,231,232,272,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,317,318,335],St=[13,16,31,48,82,174,294,295,296,297,298,299,300,301,302,303,304,305,306,308,312],mt=[31,45],Ht=[1,507],jt=[1,508],qt=[6,13,16,29,31,39,45,47,48,63,70,73,76,78,81,82,83,85,87,89,112,159,160,161,163,164,193,231,242,246,250,263,265,268,269,270,271,272,273,274,276,277,279,280,283,285,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335,336,338,341,342,343,344,345,346,347,348,349,350,351],xt=[29,31,85,112,159,160,161,163,164,335],vt=[6,13,16,31,45,70,73,81,83,85,87,268,269,270,271,273,274,276,277,279,280,283,285,308,346,347,348,349,350,351],Lt=[13,16,31,45,48,82,87,89,112,193,197,231,232,272,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,317,318,335],Vt=[2,352],vr=[13,16,197,308,314],Er=[1,565],ur=[6,13,16,31,45,76,78,81,83,85,87,268,269,270,271,273,274,276,277,279,280,283,285,308,346,347,348,349,350,351],xr=[13,16,29,31,45,82,85,87,89,112,159,160,161,163,164,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312],ir=[13,16,29,31,45,82,85,87,89,112,159,160,161,163,164,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335],Ar=[13,16,87,308],Nt=[2,364],Mt=[29,31,85,112,159,160,161,163,164,193,232,318,335],Tr=[31,112,193,232,272,318,335],Xt=[2,359],Ur=[13,16,48,82,174,294,295,296,297,298,299,300,301,302,303,304,305,306,308,312],pr=[29,31,85,112,159,160,161,163,164,193,232,272,318,335],qr=[13,16,31,45,82,87,89,112,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312],Cr=[2,347],Yt={trace:function(){},yy:{},symbols_:{error:2,QueryOrUpdate:3,Prologue:4,QueryOrUpdate_group0:5,EOF:6,Query:7,Qry:8,Query_option0:9,Prologue_repetition0:10,BaseDecl:11,BASE:12,IRIREF:13,PrefixDecl:14,PREFIX:15,PNAME_NS:16,SelectClauseWildcard:17,Qry_repetition0:18,WhereClause:19,SolutionModifierNoGroup:20,SelectClauseVars:21,Qry_repetition1:22,SolutionModifier:23,CONSTRUCT:24,ConstructTemplate:25,Qry_repetition2:26,Qry_repetition3:27,WHERE:28,"{":29,Qry_option0:30,"}":31,DESCRIBE:32,Qry_group0:33,Qry_repetition4:34,Qry_option1:35,ASK:36,Qry_repetition5:37,SelectClauseBase:38,"*":39,SelectClauseVars_repetition_plus0:40,SELECT:41,SelectClauseBase_option0:42,SelectClauseItem:43,Var:44,"(":45,Expression:46,AS:47,")":48,SubSelect:49,SubSelect_option0:50,SubSelect_option1:51,DatasetClause:52,FROM:53,DatasetClause_option0:54,iri:55,WhereClause_option0:56,GroupGraphPattern:57,SolutionModifier_option0:58,SolutionModifierNoGroup_option0:59,SolutionModifierNoGroup_option1:60,SolutionModifierNoGroup_option2:61,GroupClause:62,GROUP:63,BY:64,GroupClause_repetition_plus0:65,GroupCondition:66,BuiltInCall:67,FunctionCall:68,HavingClause:69,HAVING:70,HavingClause_repetition_plus0:71,OrderClause:72,ORDER:73,OrderClause_repetition_plus0:74,OrderCondition:75,ASC:76,BrackettedExpression:77,DESC:78,Constraint:79,LimitOffsetClauses:80,LIMIT:81,INTEGER:82,OFFSET:83,ValuesClause:84,VALUES:85,InlineData:86,VAR:87,InlineData_repetition0:88,NIL:89,InlineData_repetition1:90,InlineData_repetition_plus2:91,InlineData_repetition3:92,DataBlock:93,DataBlockValueList:94,DataBlockValueList_repetition_plus0:95,Update:96,Update_repetition0:97,Update1:98,Update_option0:99,LOAD:100,Update1_option0:101,Update1_option1:102,Update1_group0:103,Update1_option2:104,GraphRefAll:105,Update1_group1:106,Update1_option3:107,GraphOrDefault:108,TO:109,CREATE:110,Update1_option4:111,GRAPH:112,INSERTDATA:113,QuadPattern:114,DELETEDATA:115,DELETEWHERE:116,Update1_option5:117,InsertDeleteClause:118,Update1_repetition0:119,IntoGraphClause:120,INTO:121,GraphRef:122,DELETE:123,InsertDeleteClause_option0:124,InsertClause:125,INSERT:126,UsingClause:127,USING:128,UsingClause_option0:129,WithClause:130,WITH:131,DEFAULT:132,GraphOrDefault_option0:133,GraphRefAll_group0:134,Quads:135,Quads_option0:136,Quads_repetition0:137,QuadsNotTriples:138,VarOrIri:139,QuadsNotTriples_option0:140,QuadsNotTriples_option1:141,QuadsNotTriples_option2:142,TriplesTemplate:143,TriplesTemplate_repetition0:144,TriplesSameSubject:145,TriplesTemplate_option0:146,GroupGraphPatternSub:147,GroupGraphPatternSub_option0:148,GroupGraphPatternSub_repetition0:149,GroupGraphPatternSubTail:150,GraphPatternNotTriples:151,GroupGraphPatternSubTail_option0:152,GroupGraphPatternSubTail_option1:153,TriplesBlock:154,TriplesBlock_repetition0:155,TriplesSameSubjectPath:156,TriplesBlock_option0:157,GroupOrUnionGraphPattern:158,OPTIONAL:159,MINUS:160,SERVICE:161,GraphPatternNotTriples_option0:162,FILTER:163,BIND:164,InlineDataOneVar:165,InlineDataFull:166,InlineDataOneVar_repetition0:167,InlineDataFull_repetition0:168,InlineDataFull_repetition_plus1:169,InlineDataFull_repetition2:170,DataBlockValue:171,Literal:172,QuotedTriple:173,UNDEF:174,GroupOrUnionGraphPattern_repetition0:175,ArgList:176,ArgList_option0:177,ArgList_repetition0:178,ExpressionList:179,ExpressionList_repetition0:180,ConstructTemplate_option0:181,ConstructTriples:182,ConstructTriples_repetition0:183,ConstructTriples_option0:184,VarOrTermOrQuotedTP:185,PropertyListNotEmpty:186,TriplesNode:187,PropertyList:188,PropertyList_option0:189,VerbObjectList:190,PropertyListNotEmpty_repetition0:191,SemiOptionalVerbObjectList:192,";":193,SemiOptionalVerbObjectList_option0:194,Verb:195,ObjectList:196,a:197,ObjectList_repetition0:198,Object:199,GraphNode:200,Object_option0:201,PropertyListPathNotEmpty:202,TriplesNodePath:203,TriplesSameSubjectPath_option0:204,O:205,PropertyListPathNotEmpty_repetition0:206,PropertyListPathNotEmptyTail:207,O_group0:208,ObjectListPath:209,ObjectListPath_repetition0:210,ObjectPath:211,GraphNodePath:212,ObjectPath_option0:213,Path:214,Path_repetition0:215,PathSequence:216,PathSequence_repetition0:217,PathEltOrInverse:218,PathElt:219,PathPrimary:220,PathElt_option0:221,PathEltOrInverse_option0:222,IriOrA:223,"!":224,PathNegatedPropertySet:225,PathOneInPropertySet:226,PathNegatedPropertySet_repetition0:227,PathNegatedPropertySet_option0:228,"^":229,TriplesNode_repetition_plus0:230,"[":231,"]":232,TriplesNodePath_repetition_plus0:233,VarOrTermOrQuotedTPExpr:234,VarOrTerm:235,GraphTerm:236,BlankNode:237,ConditionalOrExpression:238,ConditionalAndExpression:239,ConditionalOrExpression_repetition0:240,ConditionalOrExpressionTail:241,"||":242,RelationalExpression:243,ConditionalAndExpression_repetition0:244,ConditionalAndExpressionTail:245,"&&":246,NumericExpression:247,RelationalExpression_group0:248,RelationalExpression_option0:249,IN:250,MultiplicativeExpression:251,NumericExpression_repetition0:252,AdditiveExpressionTail:253,AdditiveExpressionTail_group0:254,NumericLiteralPositive:255,AdditiveExpressionTail_repetition0:256,NumericLiteralNegative:257,AdditiveExpressionTail_repetition1:258,UnaryExpression:259,MultiplicativeExpression_repetition0:260,MultiplicativeExpressionTail:261,MultiplicativeExpressionTail_group0:262,"+":263,PrimaryExpression:264,"-":265,ExprQuotedTP:266,Aggregate:267,FUNC_ARITY0:268,FUNC_ARITY1:269,FUNC_ARITY1_SPARQL_STAR:270,FUNC_ARITY2:271,",":272,FUNC_ARITY3:273,FUNC_ARITY3_SPARQL_STAR:274,BuiltInCall_group0:275,BOUND:276,BNODE:277,BuiltInCall_option0:278,EXISTS:279,COUNT:280,Aggregate_option0:281,Aggregate_group0:282,FUNC_AGGREGATE:283,Aggregate_option1:284,GROUP_CONCAT:285,Aggregate_option2:286,Aggregate_option3:287,GroupConcatSeparator:288,SEPARATOR:289,"=":290,String:291,LANGTAG:292,"^^":293,DECIMAL:294,DOUBLE:295,BOOLEAN:296,INTEGER_POSITIVE:297,DECIMAL_POSITIVE:298,DOUBLE_POSITIVE:299,INTEGER_NEGATIVE:300,DECIMAL_NEGATIVE:301,DOUBLE_NEGATIVE:302,STRING_LITERAL1:303,STRING_LITERAL2:304,STRING_LITERAL_LONG1:305,STRING_LITERAL_LONG2:306,PrefixedName:307,PNAME_LN:308,BLANK_NODE_LABEL:309,ANON:310,QuotedTP:311,"<<":312,qtSubjectOrObject:313,">>":314,DataValueTerm:315,AnnotationPattern:316,"{|":317,"|}":318,AnnotationPatternPath:319,ExprVarOrTerm:320,QueryOrUpdate_group0_option0:321,Prologue_repetition0_group0:322,Qry_group0_repetition_plus0:323,SelectClauseBase_option0_group0:324,DISTINCT:325,REDUCED:326,NAMED:327,SILENT:328,CLEAR:329,DROP:330,ADD:331,MOVE:332,COPY:333,ALL:334,".":335,UNION:336,"|":337,"/":338,PathElt_option0_group0:339,"?":340,"!=":341,"<":342,">":343,"<=":344,">=":345,NOT:346,CONCAT:347,COALESCE:348,SUBSTR:349,REGEX:350,REPLACE:351,$accept:0,$end:1},terminals_:{2:"error",6:"EOF",12:"BASE",13:"IRIREF",15:"PREFIX",16:"PNAME_NS",24:"CONSTRUCT",28:"WHERE",29:"{",31:"}",32:"DESCRIBE",36:"ASK",39:"*",41:"SELECT",45:"(",47:"AS",48:")",53:"FROM",63:"GROUP",64:"BY",70:"HAVING",73:"ORDER",76:"ASC",78:"DESC",81:"LIMIT",82:"INTEGER",83:"OFFSET",85:"VALUES",87:"VAR",89:"NIL",100:"LOAD",109:"TO",110:"CREATE",112:"GRAPH",113:"INSERTDATA",115:"DELETEDATA",116:"DELETEWHERE",121:"INTO",123:"DELETE",126:"INSERT",128:"USING",131:"WITH",132:"DEFAULT",159:"OPTIONAL",160:"MINUS",161:"SERVICE",163:"FILTER",164:"BIND",174:"UNDEF",193:";",197:"a",224:"!",229:"^",231:"[",232:"]",242:"||",246:"&&",250:"IN",263:"+",265:"-",268:"FUNC_ARITY0",269:"FUNC_ARITY1",270:"FUNC_ARITY1_SPARQL_STAR",271:"FUNC_ARITY2",272:",",273:"FUNC_ARITY3",274:"FUNC_ARITY3_SPARQL_STAR",276:"BOUND",277:"BNODE",279:"EXISTS",280:"COUNT",283:"FUNC_AGGREGATE",285:"GROUP_CONCAT",289:"SEPARATOR",290:"=",292:"LANGTAG",293:"^^",294:"DECIMAL",295:"DOUBLE",296:"BOOLEAN",297:"INTEGER_POSITIVE",298:"DECIMAL_POSITIVE",299:"DOUBLE_POSITIVE",300:"INTEGER_NEGATIVE",301:"DECIMAL_NEGATIVE",302:"DOUBLE_NEGATIVE",303:"STRING_LITERAL1",304:"STRING_LITERAL2",305:"STRING_LITERAL_LONG1",306:"STRING_LITERAL_LONG2",308:"PNAME_LN",309:"BLANK_NODE_LABEL",310:"ANON",312:"<<",314:">>",317:"{|",318:"|}",325:"DISTINCT",326:"REDUCED",327:"NAMED",328:"SILENT",329:"CLEAR",330:"DROP",331:"ADD",332:"MOVE",333:"COPY",334:"ALL",335:".",336:"UNION",337:"|",338:"/",340:"?",341:"!=",342:"<",343:">",344:"<=",345:">=",346:"NOT",347:"CONCAT",348:"COALESCE",349:"SUBSTR",350:"REGEX",351:"REPLACE"},productions_:[0,[3,3],[7,2],[4,1],[11,2],[14,3],[8,4],[8,4],[8,5],[8,7],[8,5],[8,4],[17,2],[21,2],[38,2],[43,1],[43,5],[49,4],[49,4],[52,3],[19,2],[23,2],[20,3],[62,3],[66,1],[66,1],[66,3],[66,5],[66,1],[69,2],[72,3],[75,2],[75,2],[75,1],[75,1],[80,2],[80,2],[80,4],[80,4],[84,2],[86,4],[86,4],[86,6],[86,2],[94,3],[96,3],[98,4],[98,3],[98,5],[98,4],[98,2],[98,2],[98,2],[98,5],[120,2],[118,3],[118,1],[125,2],[127,3],[130,2],[108,1],[108,2],[122,2],[105,1],[105,1],[114,3],[135,2],[138,7],[143,3],[57,3],[57,3],[147,2],[150,3],[154,3],[151,1],[151,2],[151,2],[151,3],[151,4],[151,2],[151,6],[151,1],[93,1],[93,1],[165,4],[166,4],[166,6],[171,1],[171,1],[171,1],[171,1],[158,2],[79,1],[79,1],[79,1],[68,2],[176,1],[176,5],[179,1],[179,4],[25,3],[182,3],[145,2],[145,2],[188,1],[186,2],[192,2],[190,2],[195,1],[195,1],[196,2],[199,2],[156,2],[156,2],[202,2],[207,1],[207,2],[205,2],[209,2],[211,2],[214,2],[216,2],[219,2],[218,2],[220,1],[220,2],[220,3],[225,1],[225,1],[225,4],[226,1],[226,2],[187,3],[187,3],[203,3],[203,3],[200,1],[200,1],[212,1],[212,1],[234,1],[235,1],[235,1],[139,1],[139,1],[44,1],[236,1],[236,1],[236,1],[236,1],[46,1],[238,2],[241,2],[239,2],[245,2],[243,1],[243,3],[243,4],[247,2],[253,2],[253,2],[253,2],[251,2],[261,2],[259,2],[259,2],[259,2],[259,1],[264,1],[264,1],[264,1],[264,1],[264,1],[264,1],[264,1],[77,3],[67,1],[67,2],[67,4],[67,4],[67,6],[67,8],[67,8],[67,2],[67,4],[67,2],[67,4],[67,3],[267,5],[267,5],[267,6],[288,4],[172,1],[172,2],[172,3],[172,1],[172,1],[172,1],[172,1],[172,1],[172,1],[255,1],[255,1],[255,1],[257,1],[257,1],[257,1],[291,1],[291,1],[291,1],[291,1],[55,1],[55,1],[307,1],[307,1],[237,1],[237,1],[311,5],[173,5],[313,1],[313,1],[313,1],[313,1],[313,1],[315,1],[315,1],[315,1],[185,1],[185,1],[185,1],[316,3],[319,3],[266,5],[320,1],[320,1],[320,1],[223,1],[223,1],[321,0],[321,1],[5,1],[5,1],[5,1],[9,0],[9,1],[322,1],[322,1],[10,0],[10,2],[18,0],[18,2],[22,0],[22,2],[26,0],[26,2],[27,0],[27,2],[30,0],[30,1],[323,1],[323,2],[33,1],[33,1],[34,0],[34,2],[35,0],[35,1],[37,0],[37,2],[40,1],[40,2],[324,1],[324,1],[42,0],[42,1],[50,0],[50,1],[51,0],[51,1],[54,0],[54,1],[56,0],[56,1],[58,0],[58,1],[59,0],[59,1],[60,0],[60,1],[61,0],[61,1],[65,1],[65,2],[71,1],[71,2],[74,1],[74,2],[88,0],[88,2],[90,0],[90,2],[91,1],[91,2],[92,0],[92,2],[95,1],[95,2],[97,0],[97,4],[99,0],[99,2],[101,0],[101,1],[102,0],[102,1],[103,1],[103,1],[104,0],[104,1],[106,1],[106,1],[106,1],[107,0],[107,1],[111,0],[111,1],[117,0],[117,1],[119,0],[119,2],[124,0],[124,1],[129,0],[129,1],[133,0],[133,1],[134,1],[134,1],[134,1],[136,0],[136,1],[137,0],[137,2],[140,0],[140,1],[141,0],[141,1],[142,0],[142,1],[144,0],[144,3],[146,0],[146,1],[148,0],[148,1],[149,0],[149,2],[152,0],[152,1],[153,0],[153,1],[155,0],[155,3],[157,0],[157,1],[162,0],[162,1],[167,0],[167,2],[168,0],[168,2],[169,1],[169,2],[170,0],[170,2],[175,0],[175,3],[177,0],[177,1],[178,0],[178,3],[180,0],[180,3],[181,0],[181,1],[183,0],[183,3],[184,0],[184,1],[189,0],[189,1],[191,0],[191,2],[194,0],[194,1],[198,0],[198,3],[201,0],[201,1],[204,0],[204,1],[206,0],[206,2],[208,1],[208,1],[210,0],[210,3],[213,0],[213,1],[215,0],[215,3],[217,0],[217,3],[339,1],[339,1],[339,1],[221,0],[221,1],[222,0],[222,1],[227,0],[227,3],[228,0],[228,1],[230,1],[230,2],[233,1],[233,2],[240,0],[240,2],[244,0],[244,2],[248,1],[248,1],[248,1],[248,1],[248,1],[248,1],[249,0],[249,1],[252,0],[252,2],[254,1],[254,1],[256,0],[256,2],[258,0],[258,2],[260,0],[260,2],[262,1],[262,1],[275,1],[275,1],[275,1],[275,1],[275,1],[278,0],[278,1],[281,0],[281,1],[282,1],[282,1],[284,0],[284,1],[286,0],[286,1],[287,0],[287,1]],performAction:function(je,He,Ge,nt,it,J,sr){var X=J.length-1;switch(it){case 1:if(J[X-1]=J[X-1]||{},pt.base&&(J[X-1].base=pt.base),pt.base="",J[X-1].prefixes=pt.prefixes,pt.prefixes=null,pt.pathOnly){if(J[X-1].type==="path"||"termType"in J[X-1])return J[X-1];throw new Error("Received full SPARQL query in path only mode")}else if(J[X-1].type==="path"||"termType"in J[X-1])throw new Error("Received only path in full SPARQL mode");if(J[X-1].type==="update"){const ft={};for(const _t of J[X-1].updates)if(_t.updateType==="insert"){const ut={};for(const Zt of _t.insert)if(Zt.type==="bgp"||Zt.type==="graph")for(const Gt of Zt.triples)Gt.subject.termType==="BlankNode"&&(ut[Gt.subject.value]=!0),Gt.predicate.termType==="BlankNode"&&(ut[Gt.predicate.value]=!0),Gt.object.termType==="BlankNode"&&(ut[Gt.object.value]=!0);for(const Zt of Object.keys(ut)){if(ft[Zt])throw new Error("Detected reuse blank node across different INSERT DATA clauses");ft[Zt]=!0}}}return J[X-1];case 2:this.$={...J[X-1],...J[X],type:"query"};break;case 4:pt.base=Qr(J[X]);break;case 5:pt.prefixes||(pt.prefixes={}),J[X-1]=J[X-1].substr(0,J[X-1].length-1),J[X]=Qr(J[X]),pt.prefixes[J[X-1]]=J[X];break;case 6:this.$={...J[X-3],...$r(J[X-2]),...J[X-1],...J[X]};break;case 7:if(!pt.skipValidation&&(_n(J[X-3].variables.map(_t=>Sn(_t.expression))).some(_t=>_t.aggregation==="count"&&!(_t.expression instanceof lr))||J[X].group)){for(const _t of J[X-3].variables)if(_t.termType==="Variable"){if(!J[X].group||!J[X].group.map(ut=>Kr(ut)).includes(Kr(_t)))throw Error("Projection of ungrouped variable (?"+Kr(_t)+")")}else if(Sn(_t.expression).length===0){const ut=zn(_t.expression);for(const Zt of ut)if(!J[X].group||!J[X].group.map||!J[X].group.map(Gt=>Kr(Gt)).includes(Kr(Zt)))throw Error("Use of ungrouped variable in projection of operation (?"+Kr(Zt)+")")}}const Zr=J[X-1].where.filter(ft=>ft.type==="query");if(Zr.length>0){const ft=J[X-3].variables.filter(ut=>ut.variable&&ut.variable.value).map(ut=>ut.variable.value),_t=_n(Zr.map(ut=>ut.variables)).map(ut=>ut.value||ut.variable.value);for(const ut of ft)if(_t.indexOf(ut)>=0)throw Error("Target id of 'AS' (?"+ut+") already used in subquery")}this.$=Ut(J[X-3],$r(J[X-2]),J[X-1],J[X]);break;case 8:this.$=Ut({queryType:"CONSTRUCT",template:J[X-3]},$r(J[X-2]),J[X-1],J[X]);break;case 9:this.$=Ut({queryType:"CONSTRUCT",template:J[X-2]=J[X-2]?J[X-2].triples:[]},$r(J[X-5]),{where:[{type:"bgp",triples:Vr([],J[X-2])}]},J[X]);break;case 10:this.$=Ut({queryType:"DESCRIBE",variables:J[X-3]==="*"?[new lr]:J[X-3]},$r(J[X-2]),J[X-1],J[X]);break;case 11:this.$=Ut({queryType:"ASK"},$r(J[X-2]),J[X-1],J[X]);break;case 12:this.$=Ut(J[X-1],{variables:[new lr]});break;case 13:const xn=J[X].map(ft=>ft.value||ft.variable.value),un=Wn(xn);if(un.length>0)throw Error("Two or more of the resulting columns have the same name (?"+un[0]+")");this.$=Ut(J[X-1],{variables:J[X]});break;case 14:this.$=Ut({queryType:"SELECT"},J[X]&&(J[X-1]=er(J[X]),J[X]={},J[X][J[X-1]]=!0,J[X]));break;case 16:case 27:this.$=zr(J[X-3],{variable:J[X-1]});break;case 17:case 18:this.$=Ut(J[X-3],J[X-2],J[X-1],J[X],{type:"query"});break;case 19:case 58:this.$={iri:J[X],named:!!J[X-1]};break;case 20:this.$={where:J[X].patterns};break;case 21:this.$=Ut(J[X-1],J[X]);break;case 22:this.$=Ut(J[X-2],J[X-1],J[X]);break;case 23:this.$={group:J[X]};break;case 24:case 25:case 28:case 31:case 33:case 34:this.$=zr(J[X]);break;case 26:this.$=zr(J[X-1]);break;case 29:this.$={having:J[X]};break;case 30:this.$={order:J[X]};break;case 32:this.$=zr(J[X],{descending:!0});break;case 35:this.$={limit:Hr(J[X])};break;case 36:this.$={offset:Hr(J[X])};break;case 37:this.$={limit:Hr(J[X-2]),offset:Hr(J[X])};break;case 38:this.$={limit:Hr(J[X]),offset:Hr(J[X-2])};break;case 39:case 43:this.$={type:"values",values:J[X]};break;case 40:case 84:this.$=J[X-1].map(ft=>({[J[X-3]]:ft}));break;case 41:case 85:this.$=J[X-1].map(()=>({}));break;case 42:case 86:var Pr=J[X-4].length;J[X-4]=J[X-4].map(hn),this.$=J[X-1].map(function(ft){if(ft.length!==Pr)throw Error("Inconsistent VALUES length");for(var _t={},ut=0;ut<Pr;ut++)_t["?"+J[X-4][ut].value]=ft[ut];return _t});break;case 44:case 65:case 100:case 126:case 175:this.$=J[X-1];break;case 45:this.$={type:"update",updates:kr(J[X-2],J[X-1])};break;case 46:this.$=Ut({type:"load",silent:!!J[X-2],source:J[X-1]},J[X]&&{destination:J[X]});break;case 47:this.$={type:er(J[X-2]),silent:!!J[X-1],graph:J[X]};break;case 48:this.$={type:er(J[X-4]),silent:!!J[X-3],source:J[X-2],destination:J[X]};break;case 49:this.$={type:"create",silent:!!J[X-2],graph:{type:"graph",name:J[X]}};break;case 50:this.$={updateType:"insert",insert:Pn(J[X])};break;case 51:this.$={updateType:"delete",delete:En(Pn(J[X]))};break;case 52:this.$={updateType:"deletewhere",delete:En(J[X])};break;case 53:this.$={updateType:"insertdelete",...J[X-4],...J[X-3],...$r(J[X-2],"using"),where:J[X].patterns};break;case 54:case 57:case 62:case 167:case 191:case 236:this.$=J[X];break;case 55:this.$={delete:En(J[X-1]),insert:J[X]||[]};break;case 56:this.$={delete:[],insert:J[X]};break;case 59:this.$={graph:J[X]};break;case 60:this.$={type:"graph",default:!0};break;case 61:case 63:this.$={type:"graph",name:J[X]};break;case 64:this.$={[er(J[X])]:!0};break;case 66:this.$=J[X-1]?br(J[X],[J[X-1]]):br(J[X]);break;case 67:var sn=Ut(J[X-3]||{triples:[]},{type:"graph",name:J[X-5]});this.$=J[X]?[sn,J[X]]:[sn];break;case 68:case 73:this.$={type:"bgp",triples:br(J[X-2],[J[X-1]])};break;case 69:this.$={type:"group",patterns:[J[X-1]]};break;case 70:for(const ft of J[X-1].filter(_t=>_t.type==="bind")){const _t=J[X-1].indexOf(ft),ut=new Set;for(const Zt of J[X-1].slice(0,_t))(Zt.type==="group"||Zt.type==="bgp")&&Fn(Zt).forEach(Gt=>ut.add(Gt));if(ut.has(ft.variable.value))throw Error("Variable used to bind is already bound (?"+ft.variable.value+")")}this.$={type:"group",patterns:J[X-1]};break;case 71:this.$=J[X-1]?br([J[X-1]],J[X]):br(J[X]);break;case 72:this.$=J[X]?[J[X-2],J[X]]:J[X-2];break;case 75:this.$=Ut(J[X],{type:"optional"});break;case 76:this.$=Ut(J[X],{type:"minus"});break;case 77:this.$=Ut(J[X],{type:"graph",name:J[X-1]});break;case 78:this.$=Ut(J[X],{type:"service",name:J[X-1],silent:!!J[X-2]});break;case 79:this.$={type:"filter",expression:J[X]};break;case 80:this.$={type:"bind",variable:J[X-1],expression:J[X-3]};break;case 89:this.$=Yr(J[X]);break;case 90:this.$=void 0;break;case 91:this.$=J[X-1].length?{type:"union",patterns:br(J[X-1].map(gn),[gn(J[X])])}:J[X];break;case 95:this.$={...J[X],function:J[X-1]};break;case 96:this.$={type:"functionCall",args:[]};break;case 97:this.$={type:"functionCall",args:kr(J[X-2],J[X-1]),distinct:!!J[X-3]};break;case 98:case 115:case 128:case 247:case 249:case 251:case 253:case 255:case 263:case 267:case 297:case 299:case 303:case 307:case 328:case 341:case 349:case 355:case 361:case 367:case 369:case 373:case 375:case 379:case 381:case 385:case 391:case 395:case 401:case 405:case 409:case 411:case 420:case 428:case 430:case 440:case 444:case 446:case 448:this.$=[];break;case 99:this.$=kr(J[X-2],J[X-1]);break;case 101:this.$=br(J[X-2],[J[X-1]]);break;case 102:case 112:this.$=vn(J[X].map(ft=>Ut(Rr(J[X-1]),ft)));break;case 103:this.$=vn(Vr(J[X].map(ft=>Ut(Rr(J[X-1].entity),ft)),J[X-1].triples));break;case 105:this.$=br([J[X-1]],J[X]);break;case 106:this.$=br(J[X]);break;case 107:this.$=bn(J[X-1],J[X]);break;case 109:case 237:this.$=pt.factory.namedNode(Tt);break;case 110:case 118:this.$=kr(J[X-1],J[X]);break;case 111:this.$=J[X]?{annotation:J[X],object:J[X-1]}:J[X-1];break;case 113:this.$=J[X]?vn(Vr(J[X].map(ft=>Ut(Rr(J[X-1].entity),ft)),J[X-1].triples)):J[X-1].triples;break;case 114:this.$=bn(...J[X-1],J[X]);break;case 116:this.$=bn(...J[X]);break;case 117:case 159:case 163:this.$=[J[X-1],J[X]];break;case 119:this.$=J[X]?{object:J[X-1],annotation:J[X]}:J[X-1];break;case 120:this.$=J[X-1].length?Wr("|",kr(J[X-1],J[X])):J[X];break;case 121:this.$=J[X-1].length?Wr("/",kr(J[X-1],J[X])):J[X];break;case 122:this.$=J[X]?Wr(J[X],[J[X-1]]):J[X-1];break;case 123:this.$=J[X-1]?Wr(J[X-1],[J[X]]):J[X];break;case 125:case 131:this.$=Wr(J[X-1],[J[X]]);break;case 129:this.$=Wr("|",kr(J[X-2],J[X-1]));break;case 132:case 134:this.$=qn(J[X-1]);break;case 133:case 135:this.$=Vn(J[X-1]);break;case 140:this.$={entity:J[X],triples:[]};break;case 145:this.$=hn(J[X]);break;case 149:this.$=pt.factory.namedNode(Dt);break;case 151:case 153:case 158:case 162:this.$=pn(J[X-1],J[X]);break;case 152:this.$=["||",J[X]];break;case 154:this.$=["&&",J[X]];break;case 156:this.$=Kt(J[X-1],[J[X-2],J[X]]);break;case 157:this.$=Kt(J[X-2]?"notin":"in",[J[X-3],J[X]]);break;case 160:this.$=["+",pn(J[X-1],J[X])];break;case 161:var on=Sr(J[X-1].value.replace("-",""),J[X-1].datatype);this.$=["-",pn(on,J[X])];break;case 164:this.$=Kt("UPLUS",[J[X]]);break;case 165:this.$=Kt(J[X-1],[J[X]]);break;case 166:this.$=Kt("UMINUS",[J[X]]);break;case 177:this.$=Kt(er(J[X-1]));break;case 178:this.$=Kt(er(J[X-3]),[J[X-1]]);break;case 179:this.$=Yr(Kt(er(J[X-3]),[J[X-1]]));break;case 180:this.$=Kt(er(J[X-5]),[J[X-3],J[X-1]]);break;case 181:this.$=Kt(er(J[X-7]),[J[X-5],J[X-3],J[X-1]]);break;case 182:this.$=Yr(Kt(er(J[X-7]),[J[X-5],J[X-3],J[X-1]]));break;case 183:this.$=Kt(er(J[X-1]),J[X]);break;case 184:this.$=Kt("bound",[hn(J[X-1])]);break;case 185:this.$=Kt(J[X-1],[]);break;case 186:this.$=Kt(J[X-3],[J[X-1]]);break;case 187:this.$=Kt(J[X-2]?"notexists":"exists",[gn(J[X])]);break;case 188:case 189:this.$=zr(J[X-1],{type:"aggregate",aggregation:er(J[X-4]),distinct:!!J[X-2]});break;case 190:this.$=zr(J[X-2],{type:"aggregate",aggregation:er(J[X-5]),distinct:!!J[X-3],separator:typeof J[X-1]=="string"?J[X-1]:" "});break;case 192:this.$=Sr(J[X]);break;case 193:this.$=On(J[X-1],er(J[X].substr(1)));break;case 194:this.$=Sr(J[X-2],J[X]);break;case 195:case 204:this.$=Sr(J[X],gr);break;case 196:case 205:this.$=Sr(J[X],mr);break;case 197:case 206:this.$=Sr(er(J[X]),nn);break;case 200:this.$=Sr(J[X].toLowerCase(),fn);break;case 201:this.$=Sr(J[X].substr(1),gr);break;case 202:this.$=Sr(J[X].substr(1),mr);break;case 203:this.$=Sr(J[X].substr(1).toLowerCase(),nn);break;case 207:case 208:this.$=Cn(J[X],1);break;case 209:case 210:this.$=Cn(J[X],3);break;case 211:this.$=pt.factory.namedNode(Qr(J[X]));break;case 213:var an=J[X].indexOf(":"),kt=J[X].substr(0,an),_r=pt.prefixes[kt];if(!_r)throw new Error("Unknown prefix: "+kt);var Lr=Qr(_r+J[X].substr(an+1));this.$=pt.factory.namedNode(Lr);break;case 214:if(J[X]=J[X].substr(0,J[X].length-1),!(J[X]in pt.prefixes))throw new Error("Unknown prefix: "+J[X]);var Lr=Qr(pt.prefixes[J[X]]);this.$=pt.factory.namedNode(Lr);break;case 215:this.$=Xr(J[X].replace(/^(_:)/,""));break;case 216:this.$=Xr();break;case 217:case 218:case 232:this.$=Yr(mn(J[X-3],J[X-2],J[X-1]));break;case 230:case 231:this.$=Yr(J[X-1]);break;case 248:case 250:case 252:case 254:case 256:case 260:case 264:case 268:case 270:case 292:case 294:case 296:case 298:case 300:case 302:case 304:case 306:case 329:case 342:case 356:case 368:case 370:case 372:case 374:case 392:case 402:case 425:case 427:case 429:case 431:case 441:case 445:case 447:case 449:J[X-1].push(J[X]);break;case 259:case 269:case 291:case 293:case 295:case 301:case 305:case 371:case 424:case 426:this.$=[J[X]];break;case 308:J[X-3].push(J[X-2]);break;case 350:case 362:case 376:case 380:case 382:case 386:case 396:case 406:case 410:case 412:case 421:J[X-2].push(J[X-1]);break}},table:[e(t,r,{3:1,4:2,10:3}),{1:[3]},e(i,[2,307],{5:4,7:5,321:6,214:7,8:8,96:9,215:10,17:11,21:12,97:16,38:17,6:[2,238],13:s,16:s,45:s,197:s,224:s,229:s,308:s,24:[1,13],32:[1,14],36:[1,15],41:o}),e([6,13,16,24,32,36,41,45,100,110,113,115,116,123,126,131,197,224,229,308,329,330,331,332,333],[2,3],{322:19,11:20,14:21,12:[1,22],15:[1,23]}),{6:[1,24]},{6:[2,240]},{6:[2,241]},{6:[2,242]},{6:[2,243],9:25,84:26,85:a},{6:[2,239]},e(u,[2,411],{216:28,217:29}),e(c,[2,249],{18:30}),e(c,[2,251],{22:31}),e(l,[2,255],{25:32,27:33,29:[1,34]}),{13:d,16:f,33:35,39:[1,37],44:39,55:40,87:m,139:38,307:43,308:g,323:36},e(c,[2,267],{37:46}),e(b,[2,326],{98:47,103:49,106:50,117:55,130:61,100:[1,48],110:[1,51],113:[1,52],115:[1,53],116:[1,54],131:[1,62],329:[1,56],330:[1,57],331:[1,58],332:[1,59],333:[1,60]}),{39:[1,63],40:64,43:65,44:66,45:S,87:m},e(w,[2,273],{42:68,324:69,325:[1,70],326:[1,71]}),e(t,[2,248]),e(t,[2,245]),e(t,[2,246]),{13:[1,72]},{16:[1,73]},{1:[2,1]},{6:[2,2]},{6:[2,244]},{45:[1,77],85:[1,78],86:74,87:[1,75],89:[1,76]},e([6,13,16,45,48,82,87,89,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312],[2,120],{337:[1,79]}),e(v,[2,418],{218:80,222:81,229:[1,82]}),{19:83,28:_,29:T,52:84,53:C,56:85},{19:88,28:_,29:T,52:89,53:C,56:85},e(c,[2,253],{26:90}),{28:[1,91],52:92,53:C},e(U,[2,385],{181:93,182:94,183:95,31:[2,383]}),e($,[2,263],{34:96}),e($,[2,261],{44:39,55:40,307:43,139:97,13:d,16:f,87:m,308:g}),e($,[2,262]),e(W,[2,259]),e(re,[2,143]),e(re,[2,144]),e([6,13,16,28,29,31,39,45,47,48,53,63,70,73,76,78,81,82,83,85,87,89,112,159,160,161,163,164,193,197,224,229,231,232,242,246,250,263,265,268,269,270,271,272,273,274,276,277,279,280,283,285,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314,317,318,335,338,341,342,343,344,345,346,347,348,349,350,351],[2,145]),e(D,[2,211]),e(D,[2,212]),e(D,[2,213]),e(D,[2,214]),{19:98,28:_,29:T,52:99,53:C,56:85},{6:[2,309],99:100,193:[1,101]},e(V,[2,311],{101:102,328:[1,103]}),e(he,[2,317],{104:104,328:[1,105]}),e(z,[2,322],{107:106,328:[1,107]}),{111:108,112:[2,324],328:[1,109]},{29:_e,114:110},{29:_e,114:112},{29:_e,114:113},{118:114,123:[1,115],125:116,126:Ce},e(Fe,[2,315]),e(Fe,[2,316]),e(ze,[2,319]),e(ze,[2,320]),e(ze,[2,321]),e(b,[2,327]),{13:d,16:f,55:118,307:43,308:g},e(c,[2,12]),e(c,[2,13],{44:66,43:119,45:S,87:m}),e(ae,[2,269]),e(ae,[2,15]),{13:d,16:f,44:136,45:ve,46:120,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(w,[2,14]),e(w,[2,274]),e(w,[2,271]),e(w,[2,272]),e(t,[2,4]),{13:[1,177]},e(ot,[2,39]),{29:[1,178]},{29:[1,179]},{87:[1,181],91:180},{45:[1,187],87:[1,185],89:[1,186],93:182,165:183,166:184},e(u,[2,410]),e([6,13,16,45,48,82,87,89,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,337],[2,121],{338:[1,188]}),{13:d,16:f,45:[1,193],55:194,197:ct,219:189,220:190,223:191,224:[1,192],307:43,308:g},e(v,[2,419]),e(at,Qt,{20:196,59:197,69:198,70:wt}),e(c,[2,250]),{29:dt,57:200},e(V,[2,279],{54:202,327:[1,203]}),{29:[2,282]},e($t,yt,{23:204,58:205,62:206,63:At}),e(c,[2,252]),{19:208,28:_,29:T,52:209,53:C,56:85},{29:[1,210]},e(l,[2,256]),{31:[1,211]},{31:[2,384]},{13:d,16:f,44:215,45:It,55:220,82:L,87:m,89:Bt,145:212,172:221,185:213,187:214,231:k,236:216,237:222,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,309:j,310:Ie,311:217,312:Ae},e(Ve,[2,265],{56:85,35:227,52:228,19:229,28:_,29:T,53:C}),e(W,[2,260]),e($t,yt,{58:205,62:206,23:230,63:At}),e(c,[2,268]),{6:[2,45]},e(t,r,{10:3,4:231}),{13:d,16:f,55:232,307:43,308:g},e(V,[2,312]),{105:233,112:ht,122:234,132:[1,237],134:235,327:[1,238],334:[1,239]},e(he,[2,318]),e(V,gt,{108:240,133:242,112:rr,132:Pt}),e(z,[2,323]),{112:[1,244]},{112:[2,325]},e(Et,[2,50]),e(U,ar,{135:245,136:246,143:247,144:248,31:fr,112:fr}),e(Et,[2,51]),e(Et,[2,52]),e(Ot,[2,328],{119:249}),{29:_e,114:250},e(Ot,[2,56]),{29:_e,114:251},e(b,[2,59]),e(ae,[2,270]),{47:[1,252]},e(nr,[2,150]),e(Jt,[2,428],{240:253}),e(zt,[2,430],{244:254}),e(zt,[2,155],{248:255,249:256,250:[2,438],290:[1,257],341:[1,258],342:[1,259],343:[1,260],344:[1,261],345:[1,262],346:[1,263]}),e(lt,[2,440],{252:264}),e(rt,[2,448],{260:265}),{13:d,16:f,44:136,45:ve,55:133,67:132,68:134,77:131,82:L,87:m,172:135,255:154,257:155,264:266,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{13:d,16:f,44:136,45:ve,55:133,67:132,68:134,77:131,82:L,87:m,172:135,255:154,257:155,264:267,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{13:d,16:f,44:136,45:ve,55:133,67:132,68:134,77:131,82:L,87:m,172:135,255:154,257:155,264:268,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(rt,[2,167]),e(rt,[2,168]),e(rt,[2,169]),e(rt,[2,170],{176:269,45:Rt,89:Jr}),e(rt,[2,171]),e(rt,[2,172]),e(rt,[2,173]),e(rt,[2,174]),{13:d,16:f,44:136,45:ve,46:272,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(Ct,[2,176]),{89:[1,273]},{45:[1,274]},{45:[1,275]},{45:[1,276]},{45:[1,277]},{45:[1,278]},{45:Ft,89:tn,179:279},{45:[1,282]},{45:[1,284],89:[1,283]},{279:[1,285]},e(Wt,[2,192],{292:[1,286],293:[1,287]}),e(Wt,[2,195]),e(Wt,[2,196]),e(Wt,[2,197]),e(Wt,[2,198]),e(Wt,[2,199]),e(Wt,[2,200]),{13:d,16:f,44:39,55:40,82:L,87:m,139:289,172:291,255:154,257:155,266:290,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,320:288},{45:[1,292]},{45:[1,293]},{45:[1,294]},e(Nr,[2,452]),e(Nr,[2,453]),e(Nr,[2,454]),e(Nr,[2,455]),e(Nr,[2,456]),{279:[2,458]},e(Or,[2,207]),e(Or,[2,208]),e(Or,[2,209]),e(Or,[2,210]),e(Wt,[2,201]),e(Wt,[2,202]),e(Wt,[2,203]),e(Wt,[2,204]),e(Wt,[2,205]),e(Wt,[2,206]),e(t,[2,5]),e(jr,[2,297],{88:295}),e(Mr,[2,299],{90:296}),{48:[1,297],87:[1,298]},e(Br,[2,301]),e(ot,[2,43]),e(ot,[2,82]),e(ot,[2,83]),{29:[1,299]},{29:[1,300]},{87:[1,302],169:301},e(u,[2,412]),e(wr,[2,123]),e(wr,[2,416],{221:303,339:304,39:[1,306],263:[1,307],340:[1,305]}),e(cr,[2,124]),{13:d,16:f,45:[1,311],55:194,89:[1,310],197:ct,223:312,225:308,226:309,229:rn,307:43,308:g},e(u,s,{215:10,214:314}),e(cr,[2,236]),e(cr,[2,237]),e(p,[2,6]),e(h,[2,287],{60:315,72:316,73:[1,317]}),e(at,[2,286]),{13:d,16:f,45:ve,55:323,67:321,68:322,71:318,77:320,79:319,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,307:43,308:g,346:F,347:me,348:Re,349:we,350:Qe,351:et},e([6,31,63,70,73,81,83,85],[2,20]),e(U,y,{38:17,49:324,147:325,17:326,21:327,148:328,154:329,155:330,29:E,31:E,85:E,112:E,159:E,160:E,161:E,163:E,164:E,41:o}),{13:d,16:f,55:331,307:43,308:g},e(V,[2,280]),e(p,[2,7]),e(at,Qt,{59:197,69:198,20:332,70:wt}),e($t,[2,284]),{64:[1,333]},e($t,yt,{58:205,62:206,23:334,63:At}),e(c,[2,254]),e(U,ar,{144:248,30:335,143:336,31:[2,257]}),e(c,[2,100]),{31:[2,387],184:337,335:[1,338]},{13:d,16:f,44:39,55:40,87:m,139:342,186:339,190:340,195:341,197:I,307:43,308:g},e(q,[2,389],{44:39,55:40,307:43,190:340,195:341,139:342,188:344,189:345,186:346,13:d,16:f,87:m,197:I,308:g}),e(K,[2,227]),e(K,[2,228]),e(K,[2,229]),{13:d,16:f,44:215,45:It,55:220,82:L,87:m,89:Bt,172:221,185:351,187:350,200:348,230:347,231:k,234:349,236:216,237:222,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,309:j,310:Ie,311:217,312:Ae},{13:d,16:f,44:39,55:40,87:m,139:342,186:352,190:340,195:341,197:I,307:43,308:g},e(K,[2,146]),e(K,[2,147]),e(K,[2,148]),e(K,[2,149]),{13:d,16:f,44:354,55:355,82:L,87:m,172:357,237:356,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,309:j,310:Ie,311:358,312:Ae,313:353},e(ce,[2,215]),e(ce,[2,216]),e($t,yt,{58:205,62:206,23:359,63:At}),e($,[2,264]),e(Ve,[2,266]),e(p,[2,11]),e(i,[2,308],{6:[2,310]}),e(Et,[2,313],{102:360,120:361,121:[1,362]}),e(Et,[2,47]),e(Et,[2,63]),e(Et,[2,64]),{13:d,16:f,55:363,307:43,308:g},e(Et,[2,336]),e(Et,[2,337]),e(Et,[2,338]),{109:[1,364]},e(ee,[2,60]),{13:d,16:f,55:365,307:43,308:g},e(V,[2,335]),{13:d,16:f,55:366,307:43,308:g},{31:[1,367]},e(se,[2,341],{137:368}),e(se,[2,340]),{13:d,16:f,44:215,45:It,55:220,82:L,87:m,89:Bt,145:369,172:221,185:213,187:214,231:k,236:216,237:222,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,309:j,310:Ie,311:217,312:Ae},{28:[1,370],127:371,128:[1,372]},e(Ot,[2,330],{124:373,125:374,126:Ce}),e(Ot,[2,57]),{44:375,87:m},e(nr,[2,151],{241:376,242:[1,377]}),e(Jt,[2,153],{245:378,246:[1,379]}),{13:d,16:f,44:136,45:ve,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,247:380,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{250:[1,381]},e(oe,[2,432]),e(oe,[2,433]),e(oe,[2,434]),e(oe,[2,435]),e(oe,[2,436]),e(oe,[2,437]),{250:[2,439]},e([47,48,193,242,246,250,272,290,341,342,343,344,345,346],[2,158],{253:382,254:383,255:384,257:385,263:[1,386],265:[1,387],297:M,298:ne,299:ge,300:Y,301:Be,302:Je}),e(lt,[2,162],{261:388,262:389,39:pe,338:Se}),e(rt,[2,164]),e(rt,[2,165]),e(rt,[2,166]),e(Ct,[2,95]),e(Ct,[2,96]),e(oe,[2,377],{177:392,325:[1,393]}),{48:[1,394]},e(Ct,[2,177]),{13:d,16:f,44:136,45:ve,46:395,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{13:d,16:f,44:136,45:ve,46:396,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{13:d,16:f,44:136,45:ve,46:397,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{13:d,16:f,44:136,45:ve,46:398,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{13:d,16:f,44:136,45:ve,46:399,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(Ct,[2,183]),e(Ct,[2,98]),e(oe,[2,381],{180:400}),{87:[1,401]},e(Ct,[2,185]),{13:d,16:f,44:136,45:ve,46:402,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{29:dt,57:403},e(Wt,[2,193]),{13:d,16:f,55:404,307:43,308:g},{13:d,16:f,44:39,55:40,87:m,139:342,195:405,197:I,307:43,308:g},e(Ee,[2,233]),e(Ee,[2,234]),e(Ee,[2,235]),e(Pe,[2,459],{281:406,325:[1,407]}),e(oe,[2,463],{284:408,325:[1,409]}),e(oe,[2,465],{286:410,325:[1,411]}),{13:d,16:f,31:[1,412],55:414,82:L,171:413,172:415,173:416,174:$e,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:Le},{31:[1,419],89:[1,420]},{29:[1,421]},e(Br,[2,302]),e(jr,[2,367],{167:422}),e(Mr,[2,369],{168:423}),{48:[1,424],87:[1,425]},e(Br,[2,371]),e(wr,[2,122]),e(wr,[2,417]),e(wr,[2,413]),e(wr,[2,414]),e(wr,[2,415]),e(cr,[2,125]),e(cr,[2,127]),e(cr,[2,128]),e(Z,[2,420],{227:426}),e(cr,[2,130]),{13:d,16:f,55:194,197:ct,223:427,307:43,308:g},{48:[1,428]},e(fe,[2,289],{61:429,80:430,81:[1,431],83:[1,432]}),e(h,[2,288]),{64:[1,433]},e(at,[2,29],{307:43,267:139,275:146,278:149,77:320,67:321,68:322,55:323,79:434,13:d,16:f,45:ve,268:De,269:ke,270:We,271:Oe,273:te,274:le,276:Te,277:G,279:P,280:x,283:A,285:O,308:g,346:F,347:me,348:Re,349:we,350:Qe,351:et}),e(ye,[2,293]),e(be,[2,92]),e(be,[2,93]),e(be,[2,94]),{45:Rt,89:Jr,176:269},{31:[1,435]},{31:[1,436]},{19:437,28:_,29:T,56:85},{19:438,28:_,29:T,56:85},e(Ue,[2,355],{149:439}),e(Ue,[2,354]),{13:d,16:f,44:215,45:Me,55:220,82:L,87:m,89:Bt,156:440,172:221,185:441,203:442,231:Ye,236:216,237:222,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,309:j,310:Ie,311:217,312:Ae},e($,[2,19]),e(fe,[2,21]),{13:d,16:f,44:450,45:Ke,55:323,65:445,66:446,67:447,68:448,87:m,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,307:43,308:g,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(p,[2,8]),{31:[1,451]},{31:[2,258]},{31:[2,101]},e(U,[2,386],{31:[2,388]}),e(q,[2,102]),e(st,[2,391],{191:452}),e(U,[2,395],{196:453,198:454}),e(U,[2,108]),e(U,[2,109]),e(q,[2,103]),e(q,[2,104]),e(q,[2,390]),{13:d,16:f,44:215,45:It,48:[1,455],55:220,82:L,87:m,89:Bt,172:221,185:351,187:350,200:456,231:k,234:349,236:216,237:222,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,309:j,310:Ie,311:217,312:Ae},e(Xe,[2,424]),e(tt,[2,136]),e(tt,[2,137]),e(bt,[2,140]),{232:[1,457]},{13:d,16:f,44:39,55:40,87:m,139:342,195:458,197:I,307:43,308:g},e(Ee,[2,219]),e(Ee,[2,220]),e(Ee,[2,221]),e(Ee,[2,222]),e(Ee,[2,223]),e(p,[2,10]),e(Et,[2,46]),e(Et,[2,314]),{112:ht,122:459},e(Et,[2,62]),e(V,gt,{133:242,108:460,112:rr,132:Pt}),e(ee,[2,61]),e(Et,[2,49]),e([6,28,126,128,193],[2,65]),{31:[2,66],112:[1,462],138:461},e(se,[2,351],{146:463,335:[1,464]}),{29:dt,57:465},e(Ot,[2,329]),e(V,[2,332],{129:466,327:[1,467]}),e(Ot,[2,55]),e(Ot,[2,331]),{48:[1,468]},e(Jt,[2,429]),{13:d,16:f,44:136,45:ve,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,239:469,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(zt,[2,431]),{13:d,16:f,44:136,45:ve,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,243:470,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(zt,[2,156]),{45:Ft,89:tn,179:471},e(lt,[2,441]),{13:d,16:f,44:136,45:ve,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,251:472,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(rt,[2,444],{256:473}),e(rt,[2,446],{258:474}),e(oe,[2,442]),e(oe,[2,443]),e(rt,[2,449]),{13:d,16:f,44:136,45:ve,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,255:154,257:155,259:475,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(oe,[2,450]),e(oe,[2,451]),e(oe,[2,379],{178:476}),e(oe,[2,378]),e([6,13,16,29,31,39,45,47,48,73,76,78,81,82,83,85,87,89,112,159,160,161,163,164,193,231,242,246,250,263,265,268,269,270,271,272,273,274,276,277,279,280,283,285,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335,338,341,342,343,344,345,346,347,348,349,350,351],[2,175]),{48:[1,477]},{48:[1,478]},{272:[1,479]},{272:[1,480]},{272:[1,481]},{13:d,16:f,44:136,45:ve,46:482,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{48:[1,483]},{48:[1,484]},e(Ct,[2,187]),e(Wt,[2,194]),{13:d,16:f,44:39,55:40,82:L,87:m,139:289,172:291,255:154,257:155,266:290,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,320:485},{13:d,16:f,39:[1,487],44:136,45:ve,46:488,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,282:486,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(Pe,[2,460]),{13:d,16:f,44:136,45:ve,46:489,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(oe,[2,464]),{13:d,16:f,44:136,45:ve,46:490,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(oe,[2,466]),e(ot,[2,40]),e(jr,[2,298]),e(St,[2,87]),e(St,[2,88]),e(St,[2,89]),e(St,[2,90]),{13:d,16:f,55:492,82:L,172:493,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,311:494,312:Ae,315:491},e(ot,[2,41]),e(Mr,[2,300]),e(mt,[2,303],{92:495}),{13:d,16:f,31:[1,496],55:414,82:L,171:497,172:415,173:416,174:$e,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:Le},{31:[1,498],89:[1,499]},{29:[1,500]},e(Br,[2,372]),{13:d,16:f,48:[2,422],55:194,197:ct,223:312,226:502,228:501,229:rn,307:43,308:g},e(cr,[2,131]),e(cr,[2,126]),e(fe,[2,22]),e(fe,[2,290]),{82:[1,503]},{82:[1,504]},{13:d,16:f,44:510,45:ve,55:323,67:321,68:322,74:505,75:506,76:Ht,77:320,78:jt,79:509,87:m,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,307:43,308:g,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(ye,[2,294]),e(qt,[2,69]),e(qt,[2,70]),e(at,Qt,{59:197,69:198,20:511,70:wt}),e($t,yt,{58:205,62:206,23:512,63:At}),{29:[2,375],31:[2,71],84:522,85:a,112:[1,518],150:513,151:514,158:515,159:[1,516],160:[1,517],161:[1,519],163:[1,520],164:[1,521],175:523},e(Ue,[2,363],{157:524,335:[1,525]}),e(u,s,{215:10,202:526,205:527,208:528,214:529,44:530,87:m}),e(xt,[2,399],{215:10,205:527,208:528,214:529,44:530,204:531,202:532,13:s,16:s,45:s,197:s,224:s,229:s,308:s,87:m}),{13:d,16:f,44:215,45:Me,55:220,82:L,87:m,89:Bt,172:221,185:351,203:536,212:534,231:Ye,233:533,234:535,236:216,237:222,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,309:j,310:Ie,311:217,312:Ae},e(u,s,{215:10,205:527,208:528,214:529,44:530,202:537,87:m}),e($t,[2,23],{307:43,267:139,275:146,278:149,55:323,67:447,68:448,44:450,66:538,13:d,16:f,45:Ke,87:m,268:De,269:ke,270:We,271:Oe,273:te,274:le,276:Te,277:G,279:P,280:x,283:A,285:O,308:g,346:F,347:me,348:Re,349:we,350:Qe,351:et}),e(vt,[2,291]),e(vt,[2,24]),e(vt,[2,25]),{13:d,16:f,44:136,45:ve,46:539,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(vt,[2,28]),e($t,yt,{58:205,62:206,23:540,63:At}),e([31,112,232,318,335],[2,105],{192:541,193:[1,542]}),e(st,[2,107]),{13:d,16:f,44:215,45:It,55:220,82:L,87:m,89:Bt,172:221,185:351,187:350,199:543,200:544,231:k,234:349,236:216,237:222,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,309:j,310:Ie,311:217,312:Ae},e(Lt,[2,132]),e(Xe,[2,425]),e(Lt,[2,133]),{13:d,16:f,44:354,55:355,82:L,87:m,172:357,237:356,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,309:j,310:Ie,311:358,312:Ae,313:545},e(Et,[2,54]),e(Et,[2,48]),e(se,[2,342]),{13:d,16:f,44:39,55:40,87:m,139:546,307:43,308:g},e(se,[2,68]),e(U,[2,350],{31:Vt,112:Vt}),e(Et,[2,53]),{13:d,16:f,55:547,307:43,308:g},e(V,[2,333]),e(ae,[2,16]),e(Jt,[2,152]),e(zt,[2,154]),e(zt,[2,157]),e(lt,[2,159]),e(lt,[2,160],{262:389,261:548,39:pe,338:Se}),e(lt,[2,161],{262:389,261:549,39:pe,338:Se}),e(rt,[2,163]),{13:d,16:f,44:136,45:ve,46:550,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(Ct,[2,178]),e(Ct,[2,179]),{13:d,16:f,44:136,45:ve,46:551,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{13:d,16:f,44:136,45:ve,46:552,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{13:d,16:f,44:136,45:ve,46:553,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{48:[1,554],272:[1,555]},e(Ct,[2,184]),e(Ct,[2,186]),{314:[1,556]},{48:[1,557]},{48:[2,461]},{48:[2,462]},{48:[1,558]},{48:[2,467],193:[1,561],287:559,288:560},{13:d,16:f,55:194,197:ct,223:562,307:43,308:g},e(vr,[2,224]),e(vr,[2,225]),e(vr,[2,226]),{31:[1,563],45:Er,94:564},e(ot,[2,84]),e(jr,[2,368]),e(ot,[2,85]),e(Mr,[2,370]),e(mt,[2,373],{170:566}),{48:[1,567]},{48:[2,423],337:[1,568]},e(fe,[2,35],{83:[1,569]}),e(fe,[2,36],{81:[1,570]}),e(h,[2,30],{307:43,267:139,275:146,278:149,77:320,67:321,68:322,55:323,79:509,44:510,75:571,13:d,16:f,45:ve,76:Ht,78:jt,87:m,268:De,269:ke,270:We,271:Oe,273:te,274:le,276:Te,277:G,279:P,280:x,283:A,285:O,308:g,346:F,347:me,348:Re,349:we,350:Qe,351:et}),e(ur,[2,295]),{45:ve,77:572},{45:ve,77:573},e(ur,[2,33]),e(ur,[2,34]),{31:[2,275],50:574,84:575,85:a},{31:[2,277],51:576,84:577,85:a},e(Ue,[2,356]),e(xr,[2,357],{152:578,335:[1,579]}),e(ir,[2,74]),{29:dt,57:580},{29:dt,57:581},{13:d,16:f,44:39,55:40,87:m,139:582,307:43,308:g},e(Ar,[2,365],{162:583,328:[1,584]}),{13:d,16:f,45:ve,55:323,67:321,68:322,77:320,79:585,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,307:43,308:g,346:F,347:me,348:Re,349:we,350:Qe,351:et},{45:[1,586]},e(ir,[2,81]),{29:dt,57:587},e(Ue,[2,73]),e(U,[2,362],{29:Nt,31:Nt,85:Nt,112:Nt,159:Nt,160:Nt,161:Nt,163:Nt,164:Nt}),e(xt,[2,112]),e(Mt,[2,401],{206:588}),e(U,[2,405],{209:589,210:590}),e(U,[2,403]),e(U,[2,404]),e(xt,[2,113]),e(xt,[2,400]),{13:d,16:f,44:215,45:Me,48:[1,591],55:220,82:L,87:m,89:Bt,172:221,185:351,203:536,212:592,231:Ye,234:535,236:216,237:222,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,309:j,310:Ie,311:217,312:Ae},e(Xe,[2,426]),e(bt,[2,138]),e(bt,[2,139]),{232:[1,593]},e(vt,[2,292]),{47:[1,595],48:[1,594]},e(p,[2,9]),e(st,[2,392]),e(st,[2,393],{44:39,55:40,307:43,195:341,139:342,194:596,190:597,13:d,16:f,87:m,197:I,308:g}),e(st,[2,110],{272:[1,598]}),e(Tr,[2,397],{201:599,316:600,317:[1,601]}),{314:[1,602]},{29:[1,603]},e(Ot,[2,58]),e(rt,[2,445]),e(rt,[2,447]),{48:[1,604],272:[1,605]},{48:[1,606]},{272:[1,607]},{272:[1,608]},e(Ct,[2,99]),e(oe,[2,382]),e([13,16,39,47,48,87,193,197,242,246,250,263,265,272,290,297,298,299,300,301,302,308,314,338,341,342,343,344,345,346],[2,232]),e(Ct,[2,188]),e(Ct,[2,189]),{48:[1,609]},{48:[2,468]},{289:[1,610]},{13:d,16:f,55:492,82:L,172:493,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,311:494,312:Ae,315:611},e(ot,[2,42]),e(mt,[2,304]),{13:d,16:f,55:414,82:L,95:612,171:613,172:415,173:416,174:$e,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:Le},{31:[1,614],45:Er,94:615},e(cr,[2,129]),e(Z,[2,421]),{82:[1,616]},{82:[1,617]},e(ur,[2,296]),e(ur,[2,31]),e(ur,[2,32]),{31:[2,17]},{31:[2,276]},{31:[2,18]},{31:[2,278]},e(U,y,{155:330,153:618,154:619,29:Xt,31:Xt,85:Xt,112:Xt,159:Xt,160:Xt,161:Xt,163:Xt,164:Xt}),e(xr,[2,358]),e(ir,[2,75]),e(ir,[2,76]),{29:dt,57:620},{13:d,16:f,44:39,55:40,87:m,139:621,307:43,308:g},e(Ar,[2,366]),e(ir,[2,79]),{13:d,16:f,44:136,45:ve,46:622,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(ir,[2,91],{336:[1,623]}),e([29,31,85,112,159,160,161,163,164,232,318,335],[2,114],{207:624,193:[1,625]}),e(Mt,[2,117]),{13:d,16:f,44:215,45:Me,55:220,82:L,87:m,89:Bt,172:221,185:351,203:536,211:626,212:627,231:Ye,234:535,236:216,237:222,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,309:j,310:Ie,311:217,312:Ae},e(K,[2,134]),e(Xe,[2,427]),e(K,[2,135]),e(vt,[2,26]),{44:628,87:m},e(st,[2,106]),e(st,[2,394]),e(U,[2,396]),e(Tr,[2,111]),e(Tr,[2,398]),{13:d,16:f,44:39,55:40,87:m,139:342,186:629,190:340,195:341,197:I,307:43,308:g},e(ce,[2,217]),e(U,ar,{144:248,140:630,143:631,31:[2,343]}),e(Ct,[2,97]),e(oe,[2,380]),e(Ct,[2,180]),{13:d,16:f,44:136,45:ve,46:632,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},{13:d,16:f,44:136,45:ve,46:633,55:133,67:132,68:134,77:131,82:L,87:m,172:135,224:ie,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:xe,264:130,265:ue,266:137,267:139,268:De,269:ke,270:We,271:Oe,273:te,274:le,275:146,276:Te,277:G,278:149,279:P,280:x,283:A,285:O,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:N,346:F,347:me,348:Re,349:we,350:Qe,351:et},e(Ct,[2,190]),{290:[1,634]},{314:[1,635]},{13:d,16:f,48:[1,636],55:414,82:L,171:637,172:415,173:416,174:$e,255:154,257:155,291:150,294:H,295:Q,296:de,297:M,298:ne,299:ge,300:Y,301:Be,302:Je,303:Ne,304:Ze,305:B,306:R,307:43,308:g,312:Le},e(Ur,[2,305]),e(ot,[2,86]),e(mt,[2,374]),e(fe,[2,37]),e(fe,[2,38]),e(Ue,[2,72]),e(Ue,[2,360]),e(ir,[2,77]),{29:dt,57:638},{47:[1,639]},{29:[2,376]},e(Mt,[2,402]),e(Mt,[2,115],{215:10,208:528,214:529,44:530,205:640,13:s,16:s,45:s,197:s,224:s,229:s,308:s,87:m}),e(Mt,[2,118],{272:[1,641]}),e(pr,[2,407],{213:642,319:643,317:[1,644]}),{48:[1,645]},{318:[1,646]},{31:[1,647]},{31:[2,344]},{48:[1,648]},{48:[1,649]},{291:650,303:Ne,304:Ze,305:B,306:R},e(St,[2,218]),e(mt,[2,44]),e(Ur,[2,306]),e(ir,[2,78]),{44:651,87:m},e(Mt,[2,116]),e(U,[2,406]),e(pr,[2,119]),e(pr,[2,408]),e(u,s,{215:10,205:527,208:528,214:529,44:530,202:652,87:m}),e(vt,[2,27]),e(Tr,[2,230]),e(qr,[2,345],{141:653,335:[1,654]}),e(Ct,[2,181]),e(Ct,[2,182]),{48:[2,191]},{48:[1,655]},{318:[1,656]},e(U,ar,{144:248,142:657,143:658,31:Cr,112:Cr}),e(qr,[2,346]),e(ir,[2,80]),e(pr,[2,231]),e(se,[2,67]),e(se,[2,348])],defaultActions:{5:[2,240],6:[2,241],7:[2,242],9:[2,239],24:[2,1],25:[2,2],26:[2,244],87:[2,282],94:[2,384],100:[2,45],109:[2,325],166:[2,458],263:[2,439],336:[2,258],337:[2,101],487:[2,461],488:[2,462],560:[2,468],574:[2,17],575:[2,276],576:[2,18],577:[2,278],623:[2,376],631:[2,344],650:[2,191]},parseError:function(je,He){if(He.recoverable)this.trace(je);else{var Ge=new Error(je);throw Ge.hash=He,Ge}},parse:function(je){var He=this,Ge=[0],nt=[null],it=[],J=this.table,sr="",X=0,Pr=0,sn=2,on=1,an=it.slice.call(arguments,1),kt=Object.create(this.lexer),_r={yy:{}};for(var Lr in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Lr)&&(_r.yy[Lr]=this.yy[Lr]);kt.setInput(je,_r.yy),_r.yy.lexer=kt,_r.yy.parser=this,typeof kt.yylloc>"u"&&(kt.yylloc={});var Zr=kt.yylloc;it.push(Zr);var xn=kt.options&&kt.options.ranges;typeof _r.yy.parseError=="function"?this.parseError=_r.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var un=function(){var Gr;return Gr=kt.lex()||on,typeof Gr!="number"&&(Gr=He.symbols_[Gr]||Gr),Gr},ft,_t,ut,Zt,Gt={},ln,Ir,Nn,dn;;){if(_t=Ge[Ge.length-1],this.defaultActions[_t]?ut=this.defaultActions[_t]:((ft===null||typeof ft>"u")&&(ft=un()),ut=J[_t]&&J[_t][ft]),typeof ut>"u"||!ut.length||!ut[0]){var Tn="";dn=[];for(ln in J[_t])this.terminals_[ln]&&ln>sn&&dn.push("'"+this.terminals_[ln]+"'");kt.showPosition?Tn="Parse error on line "+(X+1)+`:
|
|
44
|
+
`+kt.showPosition()+`
|
|
45
|
+
Expecting `+dn.join(", ")+", got '"+(this.terminals_[ft]||ft)+"'":Tn="Parse error on line "+(X+1)+": Unexpected "+(ft==on?"end of input":"'"+(this.terminals_[ft]||ft)+"'"),this.parseError(Tn,{text:kt.match,token:this.terminals_[ft]||ft,line:kt.yylineno,loc:Zr,expected:dn})}if(ut[0]instanceof Array&&ut.length>1)throw new Error("Parse Error: multiple actions possible at state: "+_t+", token: "+ft);switch(ut[0]){case 1:Ge.push(ft),nt.push(kt.yytext),it.push(kt.yylloc),Ge.push(ut[1]),ft=null,Pr=kt.yyleng,sr=kt.yytext,X=kt.yylineno,Zr=kt.yylloc;break;case 2:if(Ir=this.productions_[ut[1]][1],Gt.$=nt[nt.length-Ir],Gt._$={first_line:it[it.length-(Ir||1)].first_line,last_line:it[it.length-1].last_line,first_column:it[it.length-(Ir||1)].first_column,last_column:it[it.length-1].last_column},xn&&(Gt._$.range=[it[it.length-(Ir||1)].range[0],it[it.length-1].range[1]]),Zt=this.performAction.apply(Gt,[sr,Pr,X,_r.yy,ut[1],nt,it].concat(an)),typeof Zt<"u")return Zt;Ir&&(Ge=Ge.slice(0,-1*Ir*2),nt=nt.slice(0,-1*Ir),it=it.slice(0,-1*Ir)),Ge.push(this.productions_[ut[1]][0]),nt.push(Gt.$),it.push(Gt._$),Nn=J[Ge[Ge.length-2]][Ge[Ge.length-1]],Ge.push(Nn);break;case 3:return!0}}return!0}},lr=requireWildcard().Wildcard,tr="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Tt=tr+"type",hr=tr+"first",Fr=tr+"rest",Dt=tr+"nil",Dr="http://www.w3.org/2001/XMLSchema#",gr=Dr+"integer",mr=Dr+"decimal",nn=Dr+"double",fn=Dr+"boolean",yr="",Rn="",In="";function er(qe){return qe.toLowerCase()}function kr(qe,je){return qe.push(je),qe}function Vr(qe,je){return qe.push.apply(qe,je),qe}function Ut(qe){qe||(qe={});for(var je=1,He=arguments.length,Ge;je<He&&(Ge=arguments[je]||{});je++)for(var nt in Ge)qe[nt]=Ge[nt];return qe}function br(){for(var qe=[],je=0,He=arguments.length;je<He;je++)qe=qe.concat.apply(qe,arguments[je]);return qe}function Qr(qe){if(qe[0]==="<"&&(qe=qe.substring(1,qe.length-1)),/^[a-z][a-z0-9.+-]*:/i.test(qe))return qe;if(!pt.base)throw new Error("Cannot resolve relative IRI "+qe+" because no base IRI was set.");switch(yr!==pt.base&&(yr=pt.base,Rn=yr.replace(/[^\/:]*$/,""),In=yr.match(/^(?:[a-z]+:\/*)?[^\/]*/)[0]),qe[0]){case void 0:return yr;case"#":return yr+qe;case"?":return yr.replace(/(?:\?.*)?$/,qe);case"/":return In+qe;default:return Rn+qe}}function hn(qe){if(qe){var je=qe[0];if(je==="?"||je==="$")return pt.factory.variable(qe.substr(1))}return qe}function Kt(qe,je){return{type:"operation",operator:qe,args:je||[]}}function zr(qe,je){var He={expression:qe==="*"?new lr:qe};if(je)for(var Ge in je)He[Ge]=je[Ge];return He}function Wr(qe,je){return{type:"path",pathType:qe,items:je}}function pn(qe,je){for(var He=0,Ge=je.length,nt;He<Ge&&(nt=je[He]);He++)qe=Kt(nt[0],[qe,nt[1]]);return qe}function $r(qe,je){var He=[],Ge=[],nt=qe.length,it,J={};if(!nt)return null;for(var sr=0;sr<nt&&(it=qe[sr]);sr++)(it.named?Ge:He).push(it.iri);return J[je||"from"]={default:He,named:Ge},J}function Hr(qe){return parseInt(qe,10)}function gn(qe){return qe.type==="group"&&qe.patterns.length===1?qe.patterns[0]:qe}function Sr(qe,je){return je&&je.termType!=="NamedNode"&&(je=pt.factory.namedNode(je)),pt.factory.literal(qe,je)}function On(qe,je){return pt.factory.literal(qe,je)}function mn(qe,je,He){if(!("termType"in je))throw new Error("Nested triples cannot contain paths");return pt.factory.quad(qe,je,He)}function Rr(qe,je,He,Ge){var nt={};return qe!=null&&(nt.subject=qe),je!=null&&(nt.predicate=je),He!=null&&(nt.object=He),Ge!=null&&(nt.annotations=Ge),nt}function Xr(qe){return typeof qe=="string"?qe.startsWith("e_")?pt.factory.blankNode(qe):pt.factory.blankNode("e_"+qe):pt.factory.blankNode("g_"+An++)}var An=0;pt._resetBlanks=function(){An=0};var jn=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\(.)/g,Mn={"\\":"\\","'":"'",'"':'"',t:" ",b:"\b",n:`
|
|
46
|
+
`,r:"\r",f:"\f"},Bn=/[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/,yn=String.fromCharCode;function Cn(qe,je){qe=qe.substring(je,qe.length-je);try{qe=qe.replace(jn,function(He,Ge,nt,it){var J;if(Ge){if(J=parseInt(Ge,16),isNaN(J))throw new Error;return yn(J)}else if(nt){if(J=parseInt(nt,16),isNaN(J))throw new Error;return J<65535?yn(J):yn(55296+((J-=65536)>>10),56320+(J&1023))}else{var sr=Mn[it];if(!sr)throw new Error;return sr}})}catch{return""}if(Bn.exec(qe))throw new Error("Invalid unicode codepoint of surrogate pair without corresponding codepoint in "+qe);return qe}function qn(qe){var je=Xr(),He=je,Ge=[],nt,it=[];qe.forEach(function(Pr){Ge.push(Pr.entity),Vr(it,Pr.triples)});for(var J=0,sr=0,X=Ge.length,nt=Array(X*2);J<X;)nt[sr++]=Rr(He,pt.factory.namedNode(hr),Ge[J]),nt[sr++]=Rr(He,pt.factory.namedNode(Fr),He=++J<X?Xr():pt.factory.namedNode(Dt));return{entity:je,triples:Vr(nt,it)}}function Vn(qe){var je=Xr();return{entity:je,triples:qe.map(function(He){return Ut(Rr(je),He)})}}function bn(qe,je,He){var Ge=[],nt=[];return je.forEach(function(it){let J=null;it.annotation&&(J=it.annotation,it=it.object),Ge.push(Rr(null,qe,it.entity,J)),Vr(nt,it.triples)}),br(Ge,He||[],nt)}function Kr(qe){return qe.variable?qe.variable.value:qe.value||qe.expression.value}function Sn(qe){if(!qe)return[];if(qe.type==="aggregate")return[qe];if(qe.type==="operation"){const je=[];for(const He of qe.args)je.push(...Sn(He));return je}return[]}function zn(qe){const je=new Set,He=function(Ge){Ge&&(Ge.termType==="Variable"?je.add(Ge):Ge.type==="operation"&&Ge.args.forEach(He))};return He(qe),je}function _n(qe,je=1,He=[]){for(const Ge of qe)je>0&&Ge instanceof Array?_n(Ge,je-1,He):He.push(Ge);return He}function wn(qe){return qe.termType==="Variable"}function Fn(qe){if(qe.triples){const je=[];for(const He of qe.triples)wn(He.subject)&&je.push(He.subject.value),wn(He.predicate)&&je.push(He.predicate.value),wn(He.object)&&je.push(He.object.value);return je}else if(qe.patterns){const je=[];for(const He of qe.patterns)je.push(...Fn(He));return je}return[]}function Wn(qe){const je=qe.slice().sort(),He=[];for(let Ge=0;Ge<je.length-1;Ge++)je[Ge+1]==je[Ge]&&He.push(je[Ge]);return He}function Yr(qe){if(!pt.sparqlStar)throw new Error("SPARQL-star support is not enabled");return qe}function Dn(qe,je,He){for(const Ge of je){const nt=Rr("subject"in Ge?Ge.subject:qe,Ge.predicate,Ge.object);He.push(nt),Ge.annotations&&Dn(mn(qe,Ge.predicate,Ge.object),Ge.annotations,He)}}function vn(qe){if(pt.sparqlStar){const je=[];return qe.forEach(He=>{const Ge=Rr(He.subject,He.predicate,He.object);je.push(Ge),He.annotations&&Dn(mn(He.subject,He.predicate,He.object),He.annotations,je)}),je}return qe}function Pn(qe){for(const je of qe){if(je.type==="graph"&&je.name.termType==="Variable")throw new Error("Detected illegal variable in GRAPH");if(je.type==="bgp"||je.type==="graph"){for(const He of je.triples)if(He.subject.termType==="Variable"||He.predicate.termType==="Variable"||He.object.termType==="Variable")throw new Error("Detected illegal variable in BGP")}}return qe}function En(qe){for(const je of qe)if(je.type==="bgp"){for(const He of je.triples)if(He.subject.termType==="BlankNode"||He.predicate.termType==="BlankNode"||He.object.termType==="BlankNode")throw new Error("Detected illegal blank node in BGP")}return qe}var Hn=(function(){var qe={EOF:1,parseError:function(He,Ge){if(this.yy.parser)this.yy.parser.parseError(He,Ge);else throw new Error(He)},setInput:function(je,He){return this.yy=He||this.yy||{},this._input=je,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var je=this._input[0];this.yytext+=je,this.yyleng++,this.offset++,this.match+=je,this.matched+=je;var He=je.match(/(?:\r\n?|\n).*/g);return He?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),je},unput:function(je){var He=je.length,Ge=je.split(/(?:\r\n?|\n)/g);this._input=je+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-He),this.offset-=He;var nt=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),Ge.length-1&&(this.yylineno-=Ge.length-1);var it=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:Ge?(Ge.length===nt.length?this.yylloc.first_column:0)+nt[nt.length-Ge.length].length-Ge[0].length:this.yylloc.first_column-He},this.options.ranges&&(this.yylloc.range=[it[0],it[0]+this.yyleng-He]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).
|
|
47
|
+
`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},less:function(je){this.unput(this.match.slice(je))},pastInput:function(){var je=this.matched.substr(0,this.matched.length-this.match.length);return(je.length>20?"...":"")+je.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var je=this.match;return je.length<20&&(je+=this._input.substr(0,20-je.length)),(je.substr(0,20)+(je.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var je=this.pastInput(),He=new Array(je.length+1).join("-");return je+this.upcomingInput()+`
|
|
48
|
+
`+He+"^"},test_match:function(je,He){var Ge,nt,it;if(this.options.backtrack_lexer&&(it={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(it.yylloc.range=this.yylloc.range.slice(0))),nt=je[0].match(/(?:\r\n?|\n).*/g),nt&&(this.yylineno+=nt.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:nt?nt[nt.length-1].length-nt[nt.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+je[0].length},this.yytext+=je[0],this.match+=je[0],this.matches=je,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(je[0].length),this.matched+=je[0],Ge=this.performAction.call(this,this.yy,this,He,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),Ge)return Ge;if(this._backtrack){for(var J in it)this[J]=it[J];return!1}return!1},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var je,He,Ge,nt;this._more||(this.yytext="",this.match="");for(var it=this._currentRules(),J=0;J<it.length;J++)if(Ge=this._input.match(this.rules[it[J]]),Ge&&(!He||Ge[0].length>He[0].length)){if(He=Ge,nt=J,this.options.backtrack_lexer){if(je=this.test_match(Ge,it[J]),je!==!1)return je;if(this._backtrack){He=!1;continue}else return!1}else if(!this.options.flex)break}return He?(je=this.test_match(He,it[nt]),je!==!1?je:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text.
|
|
49
|
+
`+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var He=this.next();return He||this.lex()},begin:function(He){this.conditionStack.push(He)},popState:function(){var He=this.conditionStack.length-1;return He>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(He){return He=this.conditionStack.length-1-Math.abs(He||0),He>=0?this.conditionStack[He]:"INITIAL"},pushState:function(He){this.begin(He)},stateStackSize:function(){return this.conditionStack.length},options:{flex:!0,"case-insensitive":!0},performAction:function(He,Ge,nt,it){switch(nt){case 0:break;case 1:return 12;case 2:return 15;case 3:return 41;case 4:return 325;case 5:return 326;case 6:return 45;case 7:return 47;case 8:return 48;case 9:return 39;case 10:return 24;case 11:return 28;case 12:return 29;case 13:return 31;case 14:return 32;case 15:return 36;case 16:return 53;case 17:return 327;case 18:return 63;case 19:return 64;case 20:return 70;case 21:return 73;case 22:return 76;case 23:return 78;case 24:return 81;case 25:return 83;case 26:return 85;case 27:return 193;case 28:return 100;case 29:return 328;case 30:return 121;case 31:return 329;case 32:return 330;case 33:return 110;case 34:return 331;case 35:return 109;case 36:return 332;case 37:return 333;case 38:return 113;case 39:return 115;case 40:return 116;case 41:return 131;case 42:return 123;case 43:return 126;case 44:return 128;case 45:return 132;case 46:return 112;case 47:return 334;case 48:return 335;case 49:return 159;case 50:return 161;case 51:return 164;case 52:return 174;case 53:return 160;case 54:return 336;case 55:return 163;case 56:return 312;case 57:return 314;case 58:return 317;case 59:return 318;case 60:return 272;case 61:return 197;case 62:return 337;case 63:return 338;case 64:return 229;case 65:return 340;case 66:return 263;case 67:return 224;case 68:return 231;case 69:return 232;case 70:return 242;case 71:return 246;case 72:return 290;case 73:return 341;case 74:return 342;case 75:return 343;case 76:return 344;case 77:return 345;case 78:return 250;case 79:return 346;case 80:return 265;case 81:return 276;case 82:return 277;case 83:return 268;case 84:return 269;case 85:return 270;case 86:return 271;case 87:return 347;case 88:return 348;case 89:return 273;case 90:return 274;case 91:return 350;case 92:return 349;case 93:return 351;case 94:return 279;case 95:return 280;case 96:return 283;case 97:return 285;case 98:return 289;case 99:return 293;case 100:return 296;case 101:return 13;case 102:return 16;case 103:return 308;case 104:return 309;case 105:return 87;case 106:return 292;case 107:return 82;case 108:return 294;case 109:return 295;case 110:return 297;case 111:return 298;case 112:return 299;case 113:return 300;case 114:return 301;case 115:return 302;case 116:return"EXPONENT";case 117:return 303;case 118:return 304;case 119:return 305;case 120:return 306;case 121:return 89;case 122:return 310;case 123:return 6;case 124:return"INVALID";case 125:console.log(Ge.yytext);break}},rules:[/^(?:\s+|(#[^\n\r]*))/i,/^(?:BASE)/i,/^(?:PREFIX)/i,/^(?:SELECT)/i,/^(?:DISTINCT)/i,/^(?:REDUCED)/i,/^(?:\()/i,/^(?:AS)/i,/^(?:\))/i,/^(?:\*)/i,/^(?:CONSTRUCT)/i,/^(?:WHERE)/i,/^(?:\{)/i,/^(?:\})/i,/^(?:DESCRIBE)/i,/^(?:ASK)/i,/^(?:FROM)/i,/^(?:NAMED)/i,/^(?:GROUP)/i,/^(?:BY)/i,/^(?:HAVING)/i,/^(?:ORDER)/i,/^(?:ASC)/i,/^(?:DESC)/i,/^(?:LIMIT)/i,/^(?:OFFSET)/i,/^(?:VALUES)/i,/^(?:;)/i,/^(?:LOAD)/i,/^(?:SILENT)/i,/^(?:INTO)/i,/^(?:CLEAR)/i,/^(?:DROP)/i,/^(?:CREATE)/i,/^(?:ADD)/i,/^(?:TO)/i,/^(?:MOVE)/i,/^(?:COPY)/i,/^(?:INSERT((\s+|(#[^\n\r]*)\n\r?)+)DATA)/i,/^(?:DELETE((\s+|(#[^\n\r]*)\n\r?)+)DATA)/i,/^(?:DELETE((\s+|(#[^\n\r]*)\n\r?)+)WHERE)/i,/^(?:WITH)/i,/^(?:DELETE)/i,/^(?:INSERT)/i,/^(?:USING)/i,/^(?:DEFAULT)/i,/^(?:GRAPH)/i,/^(?:ALL)/i,/^(?:\.)/i,/^(?:OPTIONAL)/i,/^(?:SERVICE)/i,/^(?:BIND)/i,/^(?:UNDEF)/i,/^(?:MINUS)/i,/^(?:UNION)/i,/^(?:FILTER)/i,/^(?:<<)/i,/^(?:>>)/i,/^(?:\{\|)/i,/^(?:\|\})/i,/^(?:,)/i,/^(?:a)/i,/^(?:\|)/i,/^(?:\/)/i,/^(?:\^)/i,/^(?:\?)/i,/^(?:\+)/i,/^(?:!)/i,/^(?:\[)/i,/^(?:\])/i,/^(?:\|\|)/i,/^(?:&&)/i,/^(?:=)/i,/^(?:!=)/i,/^(?:<)/i,/^(?:>)/i,/^(?:<=)/i,/^(?:>=)/i,/^(?:IN)/i,/^(?:NOT)/i,/^(?:-)/i,/^(?:BOUND)/i,/^(?:BNODE)/i,/^(?:(RAND|NOW|UUID|STRUUID))/i,/^(?:(LANG|DATATYPE|IRI|URI|ABS|CEIL|FLOOR|ROUND|STRLEN|STR|UCASE|LCASE|ENCODE_FOR_URI|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|MD5|SHA1|SHA256|SHA384|SHA512|isIRI|isURI|isBLANK|isLITERAL|isNUMERIC))/i,/^(?:(SUBJECT|PREDICATE|OBJECT|isTRIPLE))/i,/^(?:(LANGMATCHES|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|STRLANG|STRDT|sameTerm))/i,/^(?:CONCAT)/i,/^(?:COALESCE)/i,/^(?:IF)/i,/^(?:TRIPLE)/i,/^(?:REGEX)/i,/^(?:SUBSTR)/i,/^(?:REPLACE)/i,/^(?:EXISTS)/i,/^(?:COUNT)/i,/^(?:SUM|MIN|MAX|AVG|SAMPLE)/i,/^(?:GROUP_CONCAT)/i,/^(?:SEPARATOR)/i,/^(?:\^\^)/i,/^(?:true|false)/i,/^(?:(<(?:[^<>\"\{\}\|\^`\\\u0000-\u0020])*>))/i,/^(?:((([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.)*(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040]))?)?:))/i,/^(?:(((([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.)*(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040]))?)?:)((?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|:|[0-9]|((%([0-9A-Fa-f])([0-9A-Fa-f]))|(\\(_|~|\.|-|!|\$|&|'|\(|\)|\*|\+|,|;|=|\/|\?|#|@|%))))(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.|:|((%([0-9A-Fa-f])([0-9A-Fa-f]))|(\\(_|~|\.|-|!|\$|&|'|\(|\)|\*|\+|,|;|=|\/|\?|#|@|%))))*(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|:|((%([0-9A-Fa-f])([0-9A-Fa-f]))|(\\(_|~|\.|-|!|\$|&|'|\(|\)|\*|\+|,|;|=|\/|\?|#|@|%)))))?)))/i,/^(?:(_:(?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|[0-9])(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.)*(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040]))?))/i,/^(?:([\?\$]((?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|[0-9])(?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])*)))/i,/^(?:(@[a-zA-Z]+(?:-[a-zA-Z0-9]+)*))/i,/^(?:([0-9]+))/i,/^(?:([0-9]*\.[0-9]+))/i,/^(?:([0-9]+\.[0-9]*([eE][+-]?[0-9]+)|\.([0-9])+([eE][+-]?[0-9]+)|([0-9])+([eE][+-]?[0-9]+)))/i,/^(?:(\+([0-9]+)))/i,/^(?:(\+([0-9]*\.[0-9]+)))/i,/^(?:(\+([0-9]+\.[0-9]*([eE][+-]?[0-9]+)|\.([0-9])+([eE][+-]?[0-9]+)|([0-9])+([eE][+-]?[0-9]+))))/i,/^(?:(-([0-9]+)))/i,/^(?:(-([0-9]*\.[0-9]+)))/i,/^(?:(-([0-9]+\.[0-9]*([eE][+-]?[0-9]+)|\.([0-9])+([eE][+-]?[0-9]+)|([0-9])+([eE][+-]?[0-9]+))))/i,/^(?:([eE][+-]?[0-9]+))/i,/^(?:('(?:(?:[^\u0027\u005C\u000A\u000D])|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])))*'))/i,/^(?:("(?:(?:[^\u0022\u005C\u000A\u000D])|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])))*"))/i,/^(?:('''(?:(?:'|'')?(?:[^'\\]|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f]))))*'''))/i,/^(?:("""(?:(?:"|"")?(?:[^\"\\]|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f]))))*"""))/i,/^(?:(\((\u0020|\u0009|\u000D|\u000A)*\)))/i,/^(?:(\[(\u0020|\u0009|\u000D|\u000A)*\]))/i,/^(?:$)/i,/^(?:.)/i,/^(?:.)/i],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125],inclusive:!0}}};return qe})();Yt.lexer=Hn;function pt(){this.yy={}}return pt.prototype=Yt,Yt.Parser=pt,new pt})();return SparqlParser_1=n,SparqlParser_1}var SparqlGenerator,hasRequiredSparqlGenerator;function requireSparqlGenerator(){if(hasRequiredSparqlGenerator)return SparqlGenerator;hasRequiredSparqlGenerator=1;var n="http://www.w3.org/2001/XMLSchema#integer",e="http://www.w3.org/2001/XMLSchema#string";function t(f){this._options=f=f||{};var m=f.prefixes||{};this._prefixByIri={};var g=[];for(var b in m){var S=m[b];a(S)&&(this._prefixByIri[S]=b,g.push(S))}var w=g.join("|").replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&");this._prefixRegex=new RegExp("^("+w+")([a-zA-Z][\\-_a-zA-Z0-9]*)$"),this._usedPrefixes={},this._sparqlStar=f.sparqlStar,this._indent=a(f.indent)?f.indent:" ",this._newline=a(f.newline)?f.newline:`
|
|
50
|
+
`,this._explicitDatatype=!!f.explicitDatatype}t.prototype.toQuery=function(f){var m="";return f.queryType&&(m+=f.queryType.toUpperCase()+" "),f.reduced&&(m+="REDUCED "),f.distinct&&(m+="DISTINCT "),f.variables?m+=l(f.variables,void 0,function(g){return/^[?$]/.test(g)?g:u(g)?this.toEntity(g):"("+this.toExpression(g.expression)+" AS "+o(g.variable)+")"},this)+" ":f.template&&(m+=this.group(f.template,!0)+this._newline),f.from&&(m+=this.graphs("FROM ",f.from.default)+this.graphs("FROM NAMED ",f.from.named)),f.where&&(m+="WHERE "+this.group(f.where,!0)+this._newline),f.updates&&(m+=l(f.updates,";"+this._newline,this.toUpdate,this)),f.group&&(m+="GROUP BY "+l(f.group,void 0,function(g){var b=u(g.expression)?this.toEntity(g.expression):"("+this.toExpression(g.expression)+")";return g.variable?"("+b+" AS "+o(g.variable)+")":b},this)+this._newline),f.having&&(m+="HAVING ("+l(f.having,void 0,this.toExpression,this)+")"+this._newline),f.order&&(m+="ORDER BY "+l(f.order,void 0,function(g){var b="("+this.toExpression(g.expression)+")";return g.descending?"DESC "+b:b},this)+this._newline),Number.isInteger(f.offset)&&(m+="OFFSET "+f.offset+this._newline),Number.isInteger(f.limit)&&(m+="LIMIT "+f.limit+this._newline),f.values&&(m+=this.values(f)),m=this.baseAndPrefixes(f)+m,m.trim()},t.prototype.baseAndPrefixes=function(f){var m=f.base?"BASE <"+f.base+">"+this._newline:"",g="";for(var b in f.prefixes)(this._options.allPrefixes||this._usedPrefixes[b])&&(g+="PREFIX "+b+": <"+f.prefixes[b]+">"+this._newline);return m+g},t.prototype.toPattern=function(f){var m=f.type||f instanceof Array&&"array"||(f.subject&&f.predicate&&f.object?"triple":"");if(!(m in this))throw new Error("Unknown entry type: "+m);return this[m](f)},t.prototype.triple=function(f){return this.toEntity(f.subject)+" "+this.toEntity(f.predicate)+" "+this.toEntity(f.object)+"."},t.prototype.array=function(f){return l(f,this._newline,this.toPattern,this)},t.prototype.bgp=function(f){return this.encodeTriples(f.triples)},t.prototype.encodeTriples=function(f){if(!f.length)return"";for(var m=[],g=void 0,b=void 0,S=0;S<f.length;S++){var w=f[S];c(w.subject,g)?c(w.predicate,b)?m.push(","):(b=w.predicate,m.push(";"+this._newline,this._indent,this.toEntity(b))):(g&&m.push("."+this._newline),g=w.subject,b=w.predicate,m.push(this.toEntity(g)," ",this.toEntity(b))),m.push(" ",this.toEntity(w.object))}return m.push("."),m.join("")},t.prototype.graph=function(f){return"GRAPH "+this.toEntity(f.name)+" "+this.group(f)},t.prototype.graphs=function(f,m){return!m||m.length===0?"":l(m,"",function(g){return f+this.toEntity(g)+this._newline},this)},t.prototype.group=function(f,m){return f=m!==!0?this.array(f.patterns||f.triples):this.toPattern(f.type!=="group"?f:f.patterns),f.indexOf(this._newline)===-1?"{ "+f+" }":"{"+this._newline+this.indent(f)+this._newline+"}"},t.prototype.query=function(f){return this.toQuery(f)},t.prototype.filter=function(f){return"FILTER("+this.toExpression(f.expression)+")"},t.prototype.bind=function(f){return"BIND("+this.toExpression(f.expression)+" AS "+o(f.variable)+")"},t.prototype.optional=function(f){return"OPTIONAL "+this.group(f)},t.prototype.union=function(f){return l(f.patterns,this._newline+"UNION"+this._newline,function(m){return this.group(m,!0)},this)},t.prototype.minus=function(f){return"MINUS "+this.group(f)},t.prototype.values=function(f){var m=Object.keys(f.values.reduce(function(S,w){for(var v in w)S[v]=!0;return S},{})),g,b;return m.length===1?g=b="":(g="(",b=")"),"VALUES "+g+m.join(" ")+b+" {"+this._newline+l(f.values,this._newline,function(S){return" "+g+l(m,void 0,function(w){return S[w]?this.toEntity(S[w]):"UNDEF"},this)+b},this)+this._newline+"}"},t.prototype.service=function(f){return"SERVICE "+(f.silent?"SILENT ":"")+this.toEntity(f.name)+" "+this.group(f)},t.prototype.toExpression=function(f){if(u(f))return this.toEntity(f);switch(f.type.toLowerCase()){case"aggregate":return f.aggregation.toUpperCase()+"("+(f.distinct?"DISTINCT ":"")+this.toExpression(f.expression)+(typeof f.separator=="string"?'; SEPARATOR = "'+f.separator.replace(r,i)+'"':"")+")";case"functioncall":return this.toEntity(f.function)+"("+l(f.args,", ",this.toExpression,this)+")";case"operation":var m=f.operator.toUpperCase(),g=f.args||[];switch(f.operator.toLowerCase()){case"<":case">":case">=":case"<=":case"&&":case"||":case"=":case"!=":case"+":case"-":case"*":case"/":return(u(g[0])?this.toEntity(g[0]):"("+this.toExpression(g[0])+")")+" "+m+" "+(u(g[1])?this.toEntity(g[1]):"("+this.toExpression(g[1])+")");case"!":return"!("+this.toExpression(g[0])+")";case"uplus":return"+("+this.toExpression(g[0])+")";case"uminus":return"-("+this.toExpression(g[0])+")";case"notin":m="NOT IN";case"in":return this.toExpression(g[0])+" "+m+"("+(a(g[1])?g[1]:l(g[1],", ",this.toExpression,this))+")";case"notexists":m="NOT EXISTS";case"exists":return m+" "+this.group(g[0],!0);default:return m+"("+l(g,", ",this.toExpression,this)+")"}default:throw new Error("Unknown expression type: "+f.type)}},t.prototype.toEntity=function(f){if(u(f))switch(f.termType){case"Wildcard":return"*";case"Variable":return o(f);case"BlankNode":return"_:"+f.value;case"Literal":var m=f.value||"",g=f.language||"",b=f.datatype;if(f='"'+m.replace(r,i)+'"',g)f+="@"+g;else if(b){if(!this._explicitDatatype)switch(b.value){case e:return f;case n:if(/^\d+$/.test(m))return m+" "}f+="^^"+this.encodeIRI(b.value)}return f;case"Quad":if(!this._sparqlStar)throw new Error("SPARQL* support is not enabled");return f.graph&&f.graph.termType!=="DefaultGraph"?"<< GRAPH "+this.toEntity(f.graph)+" { "+this.toEntity(f.subject)+" "+this.toEntity(f.predicate)+" "+this.toEntity(f.object)+" } >>":"<< "+this.toEntity(f.subject)+" "+this.toEntity(f.predicate)+" "+this.toEntity(f.object)+" >>";default:return this.encodeIRI(f.value)}else{var S=f.items.map(this.toEntity,this),w=f.pathType;switch(w){case"^":case"!":return w+S[0];case"*":case"+":case"?":return"("+S[0]+w+")";default:return"("+S.join(w)+")"}}};var r=/["\\\t\n\r\b\f]/g,i=function(f){return s[f]},s={"\\":"\\\\",'"':'\\"'," ":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};t.prototype.encodeIRI=function(f){var m=this._prefixRegex.exec(f);if(m){var g=this._prefixByIri[m[1]];return this._usedPrefixes[g]=!0,g+":"+m[2]}return"<"+f+">"},t.prototype.toUpdate=function(f){switch(f.type||f.updateType){case"load":return"LOAD"+(f.source?" "+this.toEntity(f.source):"")+(f.destination?" INTO GRAPH "+this.toEntity(f.destination):"");case"insert":return"INSERT DATA "+this.group(f.insert,!0);case"delete":return"DELETE DATA "+this.group(f.delete,!0);case"deletewhere":return"DELETE WHERE "+this.group(f.delete,!0);case"insertdelete":return(f.graph?"WITH "+this.toEntity(f.graph)+this._newline:"")+(f.delete.length?"DELETE "+this.group(f.delete,!0)+this._newline:"")+(f.insert.length?"INSERT "+this.group(f.insert,!0)+this._newline:"")+(f.using?this.graphs("USING ",f.using.default):"")+(f.using?this.graphs("USING NAMED ",f.using.named):"")+"WHERE "+this.group(f.where,!0);case"add":case"copy":case"move":return f.type.toUpperCase()+" "+(f.silent?"SILENT ":"")+(f.source.default?"DEFAULT":this.toEntity(f.source.name))+" TO "+this.toEntity(f.destination.name);case"create":case"clear":case"drop":return f.type.toUpperCase()+(f.silent?" SILENT ":" ")+(f.graph.default?"DEFAULT":f.graph.named?"NAMED":f.graph.all?"ALL":"GRAPH "+this.toEntity(f.graph.name));default:throw new Error("Unknown update query type: "+f.type)}},t.prototype.indent=function(f){return f.replace(/^/gm,this._indent)};function o(f){return"?"+f.value}function a(f){return typeof f=="string"}function u(f){return typeof f.termType=="string"}function c(f,m){if(!f||!u(f)||!m||!u(m)||f.termType!==m.termType)return!1;switch(f.termType){case"Literal":return f.value===m.value&&f.language===m.language&&c(f.datatype,m.datatype);case"Quad":return c(f.subject,m.subject)&&c(f.predicate,m.predicate)&&c(f.object,m.object)&&c(f.graph,m.graph);default:return f.value===m.value}}function l(f,m,g,b){return f.map(g,b).join(a(m)?m:" ")}function d(f={}){return{stringify:function(m){var g=Object.create(f);return g.prefixes=m.prefixes,new t(g).toQuery(m)},createGenerator:function(){return new t(f)}}}return SparqlGenerator={Generator:d},SparqlGenerator}var rdfDataFactory={},BlankNode$1={},hasRequiredBlankNode;function requireBlankNode(){if(hasRequiredBlankNode)return BlankNode$1;hasRequiredBlankNode=1,Object.defineProperty(BlankNode$1,"__esModule",{value:!0}),BlankNode$1.BlankNode=void 0;class n{constructor(t){this.termType="BlankNode",this.value=t}equals(t){return!!t&&t.termType==="BlankNode"&&t.value===this.value}}return BlankNode$1.BlankNode=n,BlankNode$1}var DataFactory$1={},DefaultGraph$1={},hasRequiredDefaultGraph;function requireDefaultGraph(){if(hasRequiredDefaultGraph)return DefaultGraph$1;hasRequiredDefaultGraph=1,Object.defineProperty(DefaultGraph$1,"__esModule",{value:!0}),DefaultGraph$1.DefaultGraph=void 0;class n{constructor(){this.termType="DefaultGraph",this.value=""}equals(t){return!!t&&t.termType==="DefaultGraph"}}return DefaultGraph$1.DefaultGraph=n,n.INSTANCE=new n,DefaultGraph$1}var Literal$1={},NamedNode$1={},hasRequiredNamedNode;function requireNamedNode(){if(hasRequiredNamedNode)return NamedNode$1;hasRequiredNamedNode=1,Object.defineProperty(NamedNode$1,"__esModule",{value:!0}),NamedNode$1.NamedNode=void 0;class n{constructor(t){this.termType="NamedNode",this.value=t}equals(t){return!!t&&t.termType==="NamedNode"&&t.value===this.value}}return NamedNode$1.NamedNode=n,NamedNode$1}var hasRequiredLiteral;function requireLiteral(){if(hasRequiredLiteral)return Literal$1;hasRequiredLiteral=1,Object.defineProperty(Literal$1,"__esModule",{value:!0}),Literal$1.Literal=void 0;const n=requireNamedNode();class e{constructor(r,i){this.termType="Literal",this.value=r,typeof i=="string"?(this.language=i,this.datatype=e.RDF_LANGUAGE_STRING):i?(this.language="",this.datatype=i):(this.language="",this.datatype=e.XSD_STRING)}equals(r){return!!r&&r.termType==="Literal"&&r.value===this.value&&r.language===this.language&&this.datatype.equals(r.datatype)}}return Literal$1.Literal=e,e.RDF_LANGUAGE_STRING=new n.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),e.XSD_STRING=new n.NamedNode("http://www.w3.org/2001/XMLSchema#string"),Literal$1}var Quad$1={},hasRequiredQuad;function requireQuad(){if(hasRequiredQuad)return Quad$1;hasRequiredQuad=1,Object.defineProperty(Quad$1,"__esModule",{value:!0}),Quad$1.Quad=void 0;class n{constructor(t,r,i,s){this.termType="Quad",this.value="",this.subject=t,this.predicate=r,this.object=i,this.graph=s}equals(t){return!!t&&(t.termType==="Quad"||!t.termType)&&this.subject.equals(t.subject)&&this.predicate.equals(t.predicate)&&this.object.equals(t.object)&&this.graph.equals(t.graph)}}return Quad$1.Quad=n,Quad$1}var Variable$1={},hasRequiredVariable;function requireVariable(){if(hasRequiredVariable)return Variable$1;hasRequiredVariable=1,Object.defineProperty(Variable$1,"__esModule",{value:!0}),Variable$1.Variable=void 0;class n{constructor(t){this.termType="Variable",this.value=t}equals(t){return!!t&&t.termType==="Variable"&&t.value===this.value}}return Variable$1.Variable=n,Variable$1}var hasRequiredDataFactory;function requireDataFactory(){if(hasRequiredDataFactory)return DataFactory$1;hasRequiredDataFactory=1,Object.defineProperty(DataFactory$1,"__esModule",{value:!0}),DataFactory$1.DataFactory=void 0;const n=requireBlankNode(),e=requireDefaultGraph(),t=requireLiteral(),r=requireNamedNode(),i=requireQuad(),s=requireVariable();let o=0;class a{constructor(c){this.blankNodeCounter=0,c=c||{},this.blankNodePrefix=c.blankNodePrefix||`df_${o++}_`}namedNode(c){return new r.NamedNode(c)}blankNode(c){return new n.BlankNode(c||`${this.blankNodePrefix}${this.blankNodeCounter++}`)}literal(c,l){return new t.Literal(c,l)}variable(c){return new s.Variable(c)}defaultGraph(){return e.DefaultGraph.INSTANCE}quad(c,l,d,f){return new i.Quad(c,l,d,f||this.defaultGraph())}fromTerm(c){switch(c.termType){case"NamedNode":return this.namedNode(c.value);case"BlankNode":return this.blankNode(c.value);case"Literal":return c.language?this.literal(c.value,c.language):c.datatype.equals(t.Literal.XSD_STRING)?this.literal(c.value):this.literal(c.value,this.fromTerm(c.datatype));case"Variable":return this.variable(c.value);case"DefaultGraph":return this.defaultGraph();case"Quad":return this.quad(this.fromTerm(c.subject),this.fromTerm(c.predicate),this.fromTerm(c.object),this.fromTerm(c.graph))}}fromQuad(c){return this.fromTerm(c)}resetBlankNodeCounter(){this.blankNodeCounter=0}}return DataFactory$1.DataFactory=a,DataFactory$1}var hasRequiredRdfDataFactory;function requireRdfDataFactory(){return hasRequiredRdfDataFactory||(hasRequiredRdfDataFactory=1,(function(n){var e=rdfDataFactory&&rdfDataFactory.__createBinding||(Object.create?(function(r,i,s,o){o===void 0&&(o=s);var a=Object.getOwnPropertyDescriptor(i,s);(!a||("get"in a?!i.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,a)}):(function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]})),t=rdfDataFactory&&rdfDataFactory.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(n,"__esModule",{value:!0}),t(requireBlankNode(),n),t(requireDataFactory(),n),t(requireDefaultGraph(),n),t(requireLiteral(),n),t(requireNamedNode(),n),t(requireQuad(),n),t(requireVariable(),n)})(rdfDataFactory)),rdfDataFactory}var sparql,hasRequiredSparql;function requireSparql(){if(hasRequiredSparql)return sparql;hasRequiredSparql=1;const{Parser:n}=requireSparqlParser(),{Generator:e}=requireSparqlGenerator(),{Wildcard:t}=requireWildcard(),{DataFactory:r}=requireRdfDataFactory();function i({prefixes:s,baseIRI:o,factory:a,pathOnly:u,sparqlStar:c,skipValidation:l,skipUngroupedVariableCheck:d}={}){const f={};for(const g in s??{})f[g]=s[g];const m=new n;return m.parse=function(){return n.base=o||"",n.prefixes=Object.create(f),n.factory=a||new r,n.sparqlStar=!!c,n.pathOnly=!!u,n.skipValidation=!!l||!!d,n.prototype.parse.apply(m,arguments)},m._resetBlanks=n._resetBlanks,m}return sparql={Parser:i,Generator:e,Wildcard:t},sparql}var sparqlExports=requireSparql();class ExpressionBuilder{constructor(e=new UriResolverImpl){this.uriResolver=e}setTableContext(e){this.tableContext=e}getUriContext(){if(this.tableContext)return{baseUri:this.tableContext.baseUri,tableRegistry:this.tableContext.tableRegistry,tableNameRegistry:this.tableContext.tableNameRegistry}}buildWhereClause(e,t){const r=this.buildExpression(e,t);return r?`FILTER(${r})`:""}extractSubjectConstraint(e,t){const r=this.extractSubjectConstraintInternal(e,t);return r?.values?.length?r:null}isLinkColumn(e){return this.uriResolver.isLinkColumn(e)}formatLinkValue(e,t,r){const i=String(e);if(i.startsWith("<")&&i.endsWith(">")){const s=i.slice(1,-1);if(this.uriResolver.isAbsoluteUri(s))return i;const o=this.getUriContext();try{return`<${this.uriResolver.resolveLink(s,t,o)}>`}catch(a){const u=r.config?.name??"unknown",c=t?.name??"unknown";if(this.isPartialTemplateError(a))return{partial:!0,id:s};throw new Error(`[ExpressionBuilder] Failed to resolve URI for ${u}.${c}: ${a}`)}}if(i.startsWith("<"))return i;try{const s=this.getUriContext();return`<${this.uriResolver.resolveLink(i,t,s)}>`}catch(s){const o=r.config?.name??"unknown",a=t?.name??"unknown";if(this.isPartialTemplateError(s))return{partial:!0,id:i};throw new Error(`[ExpressionBuilder] Failed to resolve URI for ${o}.${a}: ${s}`)}}isPartialTemplateError(e){const t=String(e);return t.includes("Missing required fields for template")||t.includes("Unresolved URI template variable")}isPartialLinkValue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.partial===!0&&typeof e.id=="string"}formatPartialLinkCondition(e,t,r){if(!this.isPartialLinkValue(t))return;const i=t.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(r==="=")return`STRENDS(STR(${e}), "#${i}")`;if(r==="!=")return`!STRENDS(STR(${e}), "#${i}")`}parseTemplateVariable(e){const[t,...r]=e.split("|").map(i=>i.trim()).filter(Boolean);return{field:t||e,transforms:r}}getTemplateVariableFields(e){const t=e.config?.subjectTemplate??"";return t?Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(r=>this.parseTemplateVariable(r[1]).field))):[]}getMissingLocatorVariables(e){const t=new Set(["id","index","yyyy","MM","dd","HH","mm","ss","timestamp","date"]);return this.getTemplateVariableFields(e).filter(r=>!t.has(r))}buildMissingLocatorError(e){const t=e.config?.subjectTemplate??"",r=this.getMissingLocatorVariables(e);return new Error(`Cannot resolve subjectTemplate '${t}': missing required variable(s) [${r.join(", ")}] in query condition. Add eq(table.${r[0]}, value) to your where clause.`)}formatSubjectValue(e,t,r){const i=String(e??"");if(i.startsWith("<")&&i.endsWith(">")){const o=i.slice(1,-1);if(this.uriResolver.isAbsoluteUri(o))return i;const a=o.startsWith("#")?o.slice(1):o;try{return`<${this.uriResolver.resolveSubject(t,{id:a})}>`}catch(u){throw this.getMissingLocatorVariables(t).length>0?this.buildMissingLocatorError(t):u}}if(this.uriResolver.isAbsoluteUri(i))return`<${i}>`;const s=i.startsWith("#")?i.slice(1):i;try{return`<${this.uriResolver.resolveSubject(t,{id:s})}>`}catch(o){throw this.getMissingLocatorVariables(t).length>0?this.buildMissingLocatorError(t):o}}isDrizzleSQL(e){return!e||typeof e!="object"?!1:e.constructor?.[Symbol.for("drizzle:entityKind")]==="SQL"||Array.isArray(e.queryChunks)&&typeof e.getSQL=="function"}buildExpression(e,t){if(!e||typeof e!="object")return"";if(this.isDrizzleSQL(e))throw new Error("Drizzle-ORM operators are not supported. Please use the operators provided by drizzle-solid.");switch(e.type){case"logical_expr":return this.buildLogicalExpression(e,t);case"unary_expr":return this.buildUnaryExpression(e,t);case"binary_expr":return this.buildBinaryExpression(e,t);default:return""}}buildLogicalExpression(e,t){if(!e.expressions||e.expressions.length===0)return"";const r=e.expressions.map(s=>this.buildExpression(s,t)).filter(s=>s.length>0);if(r.length===0)return"";const i=e.operator==="OR"?" || ":" && ";return`(${r.join(i)})`}extractSubjectConstraintInternal(e,t){if(!e||typeof e!="object"||this.isDrizzleSQL(e))return null;if(e.type==="binary_expr")return this.extractSubjectConstraintFromBinary(e,t);if(e.type==="logical_expr"&&e.operator==="AND"&&Array.isArray(e.expressions)){const r=this.extractExactSubjectConstraintFromLogical(e,t);if(r)return r;let i=null;const s=[];for(const o of e.expressions){const a=this.extractSubjectConstraintInternal(o,t);if(a?.values?.length){i=i===null?[...a.values]:i.filter(u=>new Set(a.values).has(u)),a.remainingCondition&&s.push(a.remainingCondition);continue}s.push(o)}return i?.length?s.length===0?{values:i}:s.length===1?{values:i,remainingCondition:s[0]}:{values:i,remainingCondition:new LogicalExpression("AND",s)}:null}return null}extractSubjectConstraintFromBinary(e,t){if(e.operator!=="IN"||!Array.isArray(e.right)||e.right.length<=1)return null;const r=this.resolveColumnName(e.left);if(!r)return null;const i=t.columns[r],s=r==="id",o=s&&i?getPredicateForColumn(i,t):null,a=s&&o==="@id";if(!(r==="subject"||r==="@id"||a))return null;const c=[];for(const l of e.right){const d=this.formatSubjectValue(l,t,a);if(typeof d!="string"||!d.startsWith("<")||!d.endsWith(">"))return null;c.push(d.slice(1,-1))}return c.length>1?{values:c}:null}extractExactSubjectConstraintFromLogical(e,t){if(!(t.config?.subjectTemplate??"").includes("{"))return null;const i=new Set(["index","yyyy","MM","dd","HH","mm","ss","timestamp","date"]),s=this.getTemplateVariableFields(t).filter(l=>!i.has(l));if(s.length===0)return null;const o=new Map,a=[];for(const l of e.expressions){const d=l;if(d.type!=="binary_expr"||d.operator!=="="){a.push(l);continue}const f=this.resolveColumnName(d.left);if(!f||!s.includes(f)&&f!=="id"&&f!=="@id"&&f!=="subject"){a.push(l);continue}o.set(f,d.right)}if(!o.has("id")&&!o.has("@id")&&!o.has("subject"))return null;const u={};for(const l of s){if(!o.has(l))return null;u[l]=o.get(l)}o.has("@id")?u["@id"]=o.get("@id"):o.has("subject")?u["@id"]=o.get("subject"):u.id=o.get("id");const c=this.uriResolver.resolveSubject(t,u);return a.length===0?{values:[c]}:a.length===1?{values:[c],remainingCondition:a[0]}:{values:[c],remainingCondition:new LogicalExpression("AND",a)}}buildUnaryExpression(e,t){const r=e.operator;if(r==="NOT")return`!(${this.buildExpression(e.value,t)})`;const i=this.resolveColumnName(e.value);if(!i)return"";const s=t.columns[i],o=i==="id",a=o&&s?getPredicateForColumn(s,t):null,l=i==="subject"||i==="@id"||o&&a==="@id"?"?subject":`?${i}`;if(r==="IS NULL")return`!(BOUND(${l}))`;if(r==="IS NOT NULL")return`BOUND(${l})`;if(r==="EXISTS"||r==="NOT EXISTS"){const f=`EXISTS { ${String(e.value)} }`;return r==="NOT EXISTS"?`!(${f})`:f}return""}buildBinaryExpression(e,t){const r=this.resolveColumnName(e.left);if(!r)return"";const i=t.columns[r],s=r==="id",o=s&&i?getPredicateForColumn(i,t):null,a=s&&o==="@id",u=r==="subject"||r==="@id"||a,c=u?"?subject":`?${r}`,l=this.isLinkColumn(i);let d=e.right;if(e.operator==="IN"||e.operator==="NOT IN"){if(!Array.isArray(d)||d.length===0)return e.operator==="IN"?"false":"true";if(u){const w=d.map(_=>this.formatSubjectValue(_,t,a)).join(", "),v=`${c} IN(${w})`;return e.operator==="NOT IN"?`!(${v})`:v}const m=d.map(w=>l?this.formatLinkValue(w,i,t):formatValue(w,i,this.uriResolver,this.getUriContext()));if(m.some(w=>this.isPartialLinkValue(w))){const v=`(${m.map(_=>{if(this.isPartialLinkValue(_)){const C=_.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`STRENDS(STR(${c}), "#${C}")`}const T=Array.isArray(_)?_.join(", "):_;return`(${c} = ${T})`}).join(" || ")})`;return e.operator==="NOT IN"?`!(${v})`:v}const b=m.join(", "),S=`${c} IN(${b})`;return e.operator==="NOT IN"?`!(${S})`:S}if(e.operator==="REGEX"){const m=d.pattern??d,g=d.flags??"";return`REGEX(STR(${c}), "${m}", "${g}")`}if(e.operator==="LIKE"){let m=String(d).replace(/[.+^${}()|[\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");return`REGEX(STR(${c}), "^${m}$", "i")`}if(e.operator==="ILIKE"){let m=String(d).replace(/[.+^${}()|[\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");return`REGEX(STR(${c}), "^${m}$", "i")`}if(e.operator==="BETWEEN"||e.operator==="NOT BETWEEN"){if(!Array.isArray(d)||d.length!==2)return"";const[m,g]=d,b=formatValue(m,i,this.uriResolver,this.getUriContext()),S=formatValue(g,i,this.uriResolver,this.getUriContext()),w=`(${c} >= ${b} && ${c} <= ${S})`;return e.operator==="NOT BETWEEN"?`!${w}`:w}let f;if(u)f=this.formatSubjectValue(d,t,a);else if(l){const m=this.formatLinkValue(d,i,t),g=this.formatPartialLinkCondition(c,m,e.operator);if(g)return g;f=this.isPartialLinkValue(m)?`"${m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:m}else f=formatValue(d,i,this.uriResolver,this.getUriContext());if(u&&["<",">","<=",">="].includes(e.operator)){const g=String(f).replace(/^<|>$/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`(STR(${c}) ${e.operator} "${g}")`}return`(${c} ${e.operator} ${f})`}resolveColumnName(e){return typeof e=="string"?e.includes(".")?e.split(".")[1]:e:e&&typeof e=="object"&&"name"in e?e.name:e&&typeof e=="object"&&"column"in e?e.column:""}}class SelectBuilder{constructor(e,t=new UriResolverImpl){this.generator=new sparqlExports.Generator,this.prefixes=e,this.uriResolver=t,this.expressionBuilder=new ExpressionBuilder(t)}setTableContext(e){this.tableContext=e,this.expressionBuilder.setTableContext(e)}convertSelect(e,t,r,i,s=!0){const o={queryType:"SELECT",variables:this.buildSelectVariables(e,t),where:this.buildWherePatterns(e,t,r,i,s),type:"query",prefixes:this.prefixes};return i&&i.length>0&&!r&&(o.from={default:i.map(u=>({termType:"NamedNode",value:u})),named:[]}),typeof e.limit=="number"&&(o.limit=e.limit),typeof e.offset=="number"&&(o.offset=e.offset),Array.isArray(e.orderBy)&&e.orderBy.length>0&&(o.order=e.orderBy.map(u=>({expression:{termType:"Variable",value:u.column},descending:u.direction==="desc"}))),Array.isArray(e.groupBy)&&e.groupBy.length>0&&(o.group=e.groupBy.map(u=>({expression:{termType:"Variable",value:u}}))),Array.isArray(e.having)&&e.having.length>0&&(o.having=e.having),e.distinct&&(o.distinct=!0),{type:"SELECT",query:this.generator.stringify(o),prefixes:this.prefixes}}convertSelectPlan(e,t,r,i=!0){const s=e.orderBy?.map(u=>{const c=u.reference?.column??u.rawColumn;if(c)return{column:c,direction:u.direction}}).filter(u=>!!u),o=e.groupBy?.map(u=>u.column),a={select:e.select,columns:e.selectAll?"*":void 0,where:e.conditionTree??e.where,limit:e.limit,offset:e.offset,orderBy:s,groupBy:o,having:this.buildHavingExpressions(e),distinct:e.distinct};return this.convertSelect(a,e.baseTable,t,r,i)}buildHavingExpressions(e){if(!e.having)return;const t=this.buildHavingExpression(e.having,e.select,e.baseTable);if(!t)return;const r=Object.entries(this.prefixes).map(([l,d])=>`PREFIX ${l}: <${d}>`).join(`
|
|
51
|
+
`),i=e.groupBy?.map(l=>`?${l.column}`)??[],s=i.length>0?i.join(" "):"?subject",o=i.length>0?` GROUP BY ${i.join(" ")}`:"",a=`${r}
|
|
52
|
+
SELECT ${s} WHERE { ?subject ?predicate ?object . }${o} HAVING (${t})`;return new sparqlExports.Parser({skipUngroupedVariableCheck:!0}).parse(a).having}buildHavingExpression(e,t,r){switch(e.type){case"logical_expr":return this.buildHavingLogicalExpression(e,t,r);case"unary_expr":return this.buildHavingUnaryExpression(e,t,r);case"binary_expr":return this.buildHavingBinaryExpression(e,t,r);default:return""}}buildHavingLogicalExpression(e,t,r){const i=e.operator==="OR"?" || ":" && ",s=(e.expressions??[]).map(o=>this.buildHavingExpression(o,t,r)).filter(o=>o.length>0);return s.length===0?"":`(${s.join(i)})`}buildHavingUnaryExpression(e,t,r){const i=e.operator.toUpperCase();if(i==="NOT"){const o=this.buildHavingExpression(e.value,t,r);return o?`!(${o})`:""}if(i==="EXISTS"||i==="NOT EXISTS"){const o=`EXISTS { ${String(e.value)} }`;return i==="NOT EXISTS"?`!(${o})`:o}const s=this.buildHavingOperand(e.value,t,r);return s?i==="IS NULL"?`!(BOUND(${s}))`:i==="IS NOT NULL"?`BOUND(${s})`:"":""}buildHavingBinaryExpression(e,t,r){const i=this.buildHavingOperand(e.left,t,r);if(!i)return"";const s=e.operator.toUpperCase();if(s==="BETWEEN"||s==="NOT BETWEEN"){const a=Array.isArray(e.right)?e.right:[];if(a.length!==2)return"";const u=this.buildHavingOperand(a[0],t,r),c=this.buildHavingOperand(a[1],t,r),l=`(${i} >= ${u} && ${i} <= ${c})`;return s==="NOT BETWEEN"?`!${l}`:l}if(s==="IN"||s==="NOT IN"){const u=(Array.isArray(e.right)?e.right:[]).map(l=>this.buildHavingOperand(l,t,r)).join(", "),c=`${i} IN (${u})`;return s==="NOT IN"?`!(${c})`:c}const o=this.buildHavingOperand(e.right,t,r);return o?`${i} ${e.operator} ${o}`:""}buildHavingOperand(e,t,r){return e instanceof SelectionAliasExpression?this.buildHavingAliasOperand(e.alias,t,r):typeof e=="string"&&t&&e in t?this.buildHavingAliasOperand(e,t,r):e instanceof PodColumnBase?`?${resolveColumn(e,r).name}`:e&&typeof e=="object"&&"name"in e?`?${resolveColumn(e,r).name}`:typeof e=="string"&&r.columns[e]?`?${resolveColumn(e,r).name}`:String(formatValue(e,void 0,this.uriResolver,this.getUriContext()))}buildHavingAliasOperand(e,t,r){const i=t?.[e];return i?isAggregateExpression(i)?this.buildAggregateOperand(i,r):i instanceof PodColumnBase||typeof i=="string"||i&&typeof i=="object"&&"name"in i?`?${resolveColumn(i,r).name}`:`?${e}`:`?${e}`}buildAggregateOperand(e,t){const r=e.distinct?"DISTINCT ":"";if(!e.column)return`${e.func.toUpperCase()}(*)`;const i=resolveColumn(e.column,t);return`${e.func.toUpperCase()}(${r}?${i.name})`}getUriContext(){if(this.tableContext)return{baseUri:this.tableContext.baseUri,tableRegistry:this.tableContext.tableRegistry,tableNameRegistry:this.tableContext.tableNameRegistry}}convertSimpleSelect(e,t,r,i=!0){const s=e.table;s.config.type;const o={queryType:"SELECT",variables:[{termType:"Variable",value:"subject"}],where:this.buildWherePatterns(e,s,t,r,i),type:"query",prefixes:this.prefixes};return r&&r.length>0&&!t&&(o.from={default:r.map(a=>({termType:"NamedNode",value:a})),named:[]}),Object.keys(s.columns).forEach(a=>{const u=s.columns[a],c=getPredicateForColumn(u,s);c&&c!=="@id"&&o.variables.push({termType:"Variable",value:a})}),typeof e.limit=="number"&&(o.limit=e.limit),typeof e.offset=="number"&&(o.offset=e.offset),e.orderBy&&e.orderBy.length>0&&(o.order=e.orderBy.map(a=>({expression:{termType:"Variable",value:a.column},descending:a.direction==="desc"}))),e.distinct&&(o.distinct=!0),{type:"SELECT",query:this.generator.stringify(o),prefixes:this.prefixes}}buildSelectVariables(e,t){const r=e.select,i=Array.isArray(e.groupBy)&&e.groupBy.length>0;let s=!1;if(r&&typeof r=="object"&&Object.keys(r).length>0){const l=Object.values(r);s=l.length>0&&l.every(d=>isAggregateExpression(d))}const a=!s&&(!i||i&&e.groupBy.includes("subject"))?[{termType:"Variable",value:"subject"}]:[],u=new Set(["subject"]);for(const[l,d]of Object.entries(t.columns))getPredicateForColumn(d,t)==="@id"&&u.add(l);if(r&&typeof r=="object"&&Object.keys(r).length>0){const l=Object.entries(r).filter(([d])=>!u.has(d)).map(([d,f])=>this.buildSelectEntry(d,f,t));return a.concat(l)}if(e.columns==="*"||!e.columns){const l=Object.keys(t.columns).filter(d=>!u.has(d)).map(d=>({termType:"Variable",value:d}));return a.concat(l)}const c=e.columns.filter(l=>{const d=typeof l=="string"?l:l.name;return!u.has(d)}).map(l=>({termType:"Variable",value:typeof l=="string"?l:l.name}));return a.concat(c)}buildSelectEntry(e,t,r){if(isAggregateExpression(t))return this.buildAggregateSelectEntry(e,t,r);const s=resolveColumn(t,r).name;return e===s?{termType:"Variable",value:s}:{expression:{termType:"Variable",value:s},variable:{termType:"Variable",value:e}}}buildAggregateSelectEntry(e,t,r){const i=t.func,s=t.column?{termType:"Variable",value:resolveColumn(t.column,r).name}:new sparqlExports.Wildcard;return{expression:{type:"aggregate",aggregation:i,distinct:!!t.distinct,expression:s},variable:{termType:"Variable",value:e}}}buildWherePatterns(e,t,r,i,s=!0){const o=[],a=e.where?this.expressionBuilder.extractSubjectConstraint(e.where,t):null,u=a?a.remainingCondition:e.where;a?.values?.length&&o.push({type:"values",values:a.values.map(g=>({"?subject":{termType:"NamedNode",value:g}}))}),o.push({type:"bgp",triples:[{subject:{termType:"Variable",value:"subject"},predicate:{termType:"NamedNode",value:"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"},object:{termType:"NamedNode",value:t.config.type}}]});const c=[],l=[],d=new Set;if(u&&typeof u=="object"){const g=b=>{!b||typeof b!="object"||(b.left&&(typeof b.left=="string"?d.add(b.left):b.left.name&&d.add(b.left.name)),b.value&&(typeof b.value=="string"?d.add(b.value):b.value.name?d.add(b.value.name):typeof b.value=="object"&&g(b.value)),b.expressions&&Array.isArray(b.expressions)&&b.expressions.forEach(g))};g(u)}const f=e.select;let m=null;if(f&&typeof f=="object"&&Object.keys(f).length>0){m=new Set;const g=b=>b?typeof b=="string"?b:b.name?b.name:isAggregateExpression(b)&&b.column?g(b.column):null:null;for(const[b,S]of Object.entries(f)){m.add(b);const w=g(S);w&&m.add(w)}if(d.forEach(b=>m.add(b)),Array.isArray(e.orderBy))for(const b of e.orderBy)b.column&&m.add(b.column);if(Array.isArray(e.groupBy))for(const b of e.groupBy){const S=g(b);S&&m.add(S)}}if(Object.entries(t.columns).forEach(([g,b])=>{if(m&&!m.has(g))return;const S=getPredicateForColumn(b,t);if(S==="@id")return;const w={termType:"Variable",value:"subject"},v={termType:"Variable",value:g},_=b.options?.inverse,T={subject:_?v:w,predicate:{termType:"NamedNode",value:S},object:_?w:v};_?l.push(T):b.options?.required||d.has(g)?c.push(T):l.push(T)}),c.length>0&&o.push({type:"bgp",triples:c}),l.forEach(g=>{o.push({type:"optional",patterns:[{type:"bgp",triples:[g]}]})}),u){const g=this.expressionBuilder.buildWhereClause(u,t);if(g)try{const S=`${Object.entries(this.prefixes).map(([_,T])=>`PREFIX ${_}: <${T}>`).join(`
|
|
53
|
+
`)}
|
|
54
|
+
SELECT * WHERE { ${g} }`,v=new sparqlExports.Parser().parse(S);if(v.where){const _=v.where.find(T=>T.type==="filter");_&&o.push(_)}}catch(b){console.warn("Failed to parse filter string into AST:",g,b)}}return r?[{type:"graph",name:{termType:"NamedNode",value:r},patterns:o}]:s&&this.uriResolver.getResourceMode(t)==="document"&&(!i||i.length===0)?[{type:"graph",name:{termType:"Variable",value:"g"},patterns:o}]:o}}const XSD$6="http://www.w3.org/2001/XMLSchema#";class DefaultHandler{constructor(){this.name="default"}canHandle(e){const t=e.dataType;return t==="string"||t==="integer"||t==="boolean"||t==="datetime"||t==="json"}formatValue(e,t,r){switch(t.dataType){case"json":return{termType:"Literal",value:JSON.stringify(e),datatype:{termType:"NamedNode",value:`${XSD$6}json`}};case"string":return{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:`${XSD$6}string`}};case"integer":return{termType:"Literal",value:String(Number(e)),datatype:{termType:"NamedNode",value:`${XSD$6}integer`}};case"boolean":return{termType:"Literal",value:String(!!e),datatype:{termType:"NamedNode",value:`${XSD$6}boolean`}};case"datetime":return{termType:"Literal",value:(e instanceof Date?e:new Date(e)).toISOString(),datatype:{termType:"NamedNode",value:`${XSD$6}dateTime`}};default:return{termType:"Literal",value:String(e)}}}parseValue(e,t){const r=e.datatype?.value??"";switch(t.dataType){case"json":return JSON.parse(e.value);case"integer":return parseInt(e.value,10);case"boolean":return e.value==="true";case"datetime":return new Date(e.value);default:return r.includes("#integer")||r.includes("#int")?parseInt(e.value,10):r.includes("#boolean")?e.value==="true":r.includes("#dateTime")?new Date(e.value):e.value}}buildTriples(e,t,r,i,s,o){const a=this.formatValue(r,i);return{triples:[{subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:t},object:a}]}}}class UriHandler{constructor(){this.name="uri"}canHandle(e){return e.dataType==="uri"||e.isLink()}toUriContext(e){if(e)return{baseUri:e.baseUri,tableRegistry:e.tableRegistry,tableNameRegistry:e.tableNameRegistry,record:e.record,currentTable:e.currentTable}}formatValue(e,t,r){const i=String(e),s=this.toUriContext(r);return{termType:"NamedNode",value:(r?.uriResolver??new UriResolverImpl).resolveLink(i,t,s)}}parseValue(e,t){return e.value}buildTriples(e,t,r,i,s,o){const a=this.formatValue(r,i,o);return{triples:[{subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:t},object:a}]}}}const XSD$5="http://www.w3.org/2001/XMLSchema#";class ArrayHandler{constructor(){this.name="array"}canHandle(e){return e.options?.isArray===!0||e.dataType==="array"}formatValue(e,t,r){if(!Array.isArray(e))throw new Error("Array column requires array value");const i=t.options?.baseType??"string";return e.map(s=>this.formatSingleValue(s,i))}formatSingleValue(e,t){switch(t){case"json":return{termType:"Literal",value:JSON.stringify(e),datatype:{termType:"NamedNode",value:`${XSD$5}json`}};case"string":return{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:`${XSD$5}string`}};case"integer":return{termType:"Literal",value:String(Number(e)),datatype:{termType:"NamedNode",value:`${XSD$5}integer`}};case"boolean":return{termType:"Literal",value:String(!!e),datatype:{termType:"NamedNode",value:`${XSD$5}boolean`}};case"datetime":return{termType:"Literal",value:(e instanceof Date?e:new Date(e)).toISOString(),datatype:{termType:"NamedNode",value:`${XSD$5}dateTime`}};case"uri":return{termType:"NamedNode",value:String(e)};default:return{termType:"Literal",value:String(e)}}}parseValue(e,t){const r=t.options?.baseType??"string",i=e.datatype?.value??"";switch(r){case"json":return JSON.parse(e.value);case"integer":return parseInt(e.value,10);case"boolean":return e.value==="true";case"datetime":return new Date(e.value);case"uri":return e.value;default:return i.includes("#integer")?parseInt(e.value,10):i.includes("#boolean")?e.value==="true":i.includes("#dateTime")?new Date(e.value):e.value}}buildTriples(e,t,r,i,s,o){let a;return Array.isArray(r)?a=r:typeof r=="string"&&r.includes(",")?a=r.split(",").map(l=>l.trim()).filter(Boolean):a=[r],{triples:this.formatValue(a,i).map(l=>({subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:t},object:l}))}}}const XSD$4="http://www.w3.org/2001/XMLSchema#";class InverseHandler{constructor(){this.name="inverse"}canHandle(e){return e.options?.inverse===!0}toUriContext(e){if(e)return{baseUri:e.baseUri,tableRegistry:e.tableRegistry,tableNameRegistry:e.tableNameRegistry,record:e.record,currentTable:e.currentTable}}formatValue(e,t,r){if(t.options?.linkTarget||t.dataType==="uri"||t.isLink?.()){const i=String(e),s=this.toUriContext(r);return{termType:"NamedNode",value:(r?.uriResolver??new UriResolverImpl).resolveLink(i,t,s)}}return this.isUri(e)?{termType:"NamedNode",value:String(e)}:{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:`${XSD$4}string`}}}isUri(e){return typeof e!="string"?!1:e.startsWith("http://")||e.startsWith("https://")}parseValue(e,t){return e.value}buildTriples(e,t,r,i,s,o){return{triples:(Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(c=>c.trim()).filter(Boolean):[r]).map(c=>({subject:this.formatValue(c,i,o),predicate:{termType:"NamedNode",value:t},object:{termType:"NamedNode",value:e}}))}}}const XSD$3="http://www.w3.org/2001/XMLSchema#";class InlineObjectHandler{constructor(){this.name="inline"}canHandle(e){return e.dataType==="object"?!0:e.dataType==="array"?(e.elementType||e.options?.baseType)==="object":!1}formatValue(e,t,r){return typeof e=="string"?{termType:"NamedNode",value:e}:{termType:"Literal",value:JSON.stringify(e),datatype:{termType:"NamedNode",value:`${XSD$3}json`}}}parseValue(e,t){if(e.datatype?.value?.includes("#json"))try{return JSON.parse(e.value)}catch{return e.value}return e.termType==="NamedNode",e.value}buildTriples(e,t,r,i,s,o){const a=[],u=[];return(Array.isArray(r)?r:[r]).forEach((l,d)=>{if(!l||typeof l!="object")return;const f=l,m=o.resolveInlineChildUri(e,i.name,f,d);a.push({subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:t},object:{termType:"NamedNode",value:m}});const g=this.buildChildTriples(m,f,s,o);u.push(...g)}),{triples:a,childTriples:u}}buildChildTriples(e,t,r,i){const s=[],o=i.getNamespaceUri(r);return Object.entries(t).forEach(([a,u])=>{if(a==="id"||a==="@id"||u==null)return;const c=this.resolvePredicateUri(a,o);(Array.isArray(u)?[u]:[u]).forEach(d=>{const f=this.formatChildValue(d);s.push({subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:c},object:f})})}),s}resolvePredicateUri(e,t){return e.startsWith("http://")||e.startsWith("https://")?e:t?`${t}${e}`:`http://example.org/${e}`}formatChildValue(e){if(e==null)return{termType:"Literal",value:""};if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return{termType:"NamedNode",value:e};if(typeof e=="number"){const t=Number.isInteger(e)?`${XSD$3}integer`:`${XSD$3}decimal`;return{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:t}}}return typeof e=="boolean"?{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:`${XSD$3}boolean`}}:e instanceof Date?{termType:"Literal",value:e.toISOString(),datatype:{termType:"NamedNode",value:`${XSD$3}dateTime`}}:typeof e=="object"?{termType:"Literal",value:JSON.stringify(e),datatype:{termType:"NamedNode",value:`${XSD$3}json`}}:{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:`${XSD$3}string`}}}}class HandlerRegistry{constructor(){this.handlers=[],this.register(new InlineObjectHandler),this.register(new InverseHandler),this.register(new ArrayHandler),this.register(new UriHandler),this.register(new DefaultHandler)}register(e){this.handlers.push(e)}getHandler(e){for(const t of this.handlers)if(t.canHandle(e))return t;throw new Error(`No handler found for column: ${e.name} (type: ${e.dataType})`)}getAllHandlers(){return[...this.handlers]}}const handlerRegistry=new HandlerRegistry,RDF_TYPE="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",XSD$2="http://www.w3.org/2001/XMLSchema#";class TripleBuilderImpl{constructor(e){this.uriResolver=e??new UriResolverImpl}setTableRegistry(e,t){this.tableRegistry=e,this.tableNameRegistry=t}setBaseUri(e){this.baseUri=e}createContext(e,t){return{resolveInlineChildUri:this.resolveInlineChildUri.bind(this),getNamespaceUri:this.getNamespaceUri.bind(this),uriResolver:this.uriResolver,baseUri:this.baseUri,tableRegistry:this.tableRegistry,tableNameRegistry:this.tableNameRegistry,record:e,currentTable:t}}buildInsert(e,t,r,i){const s=handlerRegistry.getHandler(t),o=this.getPredicateUri(t,i),a=this.createContext(i?.__currentRecord,i);return s.buildTriples(e,o,r,t,i,a)}buildDelete(e,t,r,i=""){const s=this.getPredicateUri(t,r),o=`old_${t.name}${i}`;return t.dataType==="object"?this.buildInlineDeleteTriples(e,s,t.name,i):t.options?.inverse?{triples:[{subject:{termType:"Variable",value:o},predicate:{termType:"NamedNode",value:s},object:{termType:"NamedNode",value:e}}]}:{triples:[{subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:s},object:{termType:"Variable",value:o}}]}}buildInlineDeleteTriples(e,t,r,i){const s=`old_${r}${i}`,o=`op_${r}${i}`,a=`oo_${r}${i}`;return{triples:[{subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:t},object:{termType:"Variable",value:s}}],childTriples:[{subject:{termType:"Variable",value:s},predicate:{termType:"Variable",value:o},object:{termType:"Variable",value:a}}]}}buildTypeTriple(e,t){return{subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:RDF_TYPE},object:{termType:"NamedNode",value:t}}}toN3Strings(e){return e.map(t=>{const r=this.termToN3(t.subject),i=this.termToN3(t.predicate),s=this.termToN3(t.object);return`${r} ${i} ${s} .`})}termToN3(e){switch(e.termType){case"NamedNode":return`<${e.value}>`;case"Variable":return`?${e.value}`;case"BlankNode":return`_:${e.value}`;case"Literal":{if(e.value.includes(`
|
|
55
|
+
`)||e.value.includes("\r")){let i=e.value;if(i=i.replace(/"""/g,'"\\"\\""'),i.endsWith('"')){const s=i.match(/"*$/),o=s?s[0].length:0;o>0&&(i=i.slice(0,-o)+'\\"'.repeat(o))}if(e.language)return`"""${i}"""@${e.language}`;if(e.datatype){const s=e.datatype.value;return s===`${XSD$2}string`?`"""${i}"""`:s===`${XSD$2}integer`?e.value:`"""${i}"""^^<${s}>`}return`"""${i}"""`}const r=e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(e.language)return`"${r}"@${e.language}`;if(e.datatype){const i=e.datatype.value;return i===`${XSD$2}string`?`"${r}"`:i===`${XSD$2}integer`?e.value:`"${r}"^^<${i}>`}return`"${r}"`}default:return`"${e.value}"`}}buildN3Patch(e,t,r=[]){const i=g=>g.trim().endsWith(".")?g.trim():`${g.trim()} .`,s=e.map(i),o=t.map(i),a=r.map(i),u=s.length>0,c=a.length>0,l=u?` solid:delete {
|
|
56
|
+
${s.map(g=>` ${g}`).join(`
|
|
57
|
+
`)}
|
|
58
|
+
};
|
|
59
|
+
`:"",d=o.length>0?` solid:insert {
|
|
60
|
+
${o.map(g=>` ${g}`).join(`
|
|
61
|
+
`)}
|
|
62
|
+
};
|
|
63
|
+
`:"",f=c?` solid:where {
|
|
64
|
+
${a.map(g=>` ${g}`).join(`
|
|
65
|
+
`)}
|
|
66
|
+
}.
|
|
67
|
+
`:"",m=`@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
68
|
+
_:patch a solid:InsertDeletePatch;
|
|
69
|
+
`;if(!u&&!c){const g=d.endsWith(`;
|
|
70
|
+
`)?d.replace(/;\n$/,`.
|
|
71
|
+
`):d||` solid:insert { }.
|
|
72
|
+
`;return`${m}${g}`}return`${m}${l}${d}${f}`.replace(/;\n$/,`.
|
|
73
|
+
`)}getPredicateUri(e,t){if(e.options?.predicate==="@id")return"@id";if(e.options?.predicate)return e.options.predicate;const r=t.config?.namespace;return r?`${typeof r=="string"?r:r.uri}${e.name}`:`http://example.org/${e.name}`}formatValue(e,t){if(e==null)return'""';if(!t)return this.formatValueByInference(e);const i=handlerRegistry.getHandler(t).formatValue(e,t);return Array.isArray(i)?i.map(s=>this.termToN3(s)):this.termToN3(i)}formatValueByInference(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?`<${e}>`:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:typeof e=="number"?Number.isInteger(e)?String(e):`"${e}"^^<${XSD$2}decimal>`:typeof e=="boolean"?`"${e}"^^<${XSD$2}boolean>`:e instanceof Date?`"${e.toISOString()}"^^<${XSD$2}dateTime>`:typeof e=="object"?`"${JSON.stringify(e).replace(/"/g,'\\"')}"^^<${XSD$2}json>`:`"${String(e)}"`}resolveInlineChildUri(e,t,r,i){const s=typeof r["@id"]=="string"?r["@id"]:typeof r.id=="string"?r.id:void 0;return s||buildInlineChildUri(e,t,i)}getNamespaceUri(e){const t=e.config?.namespace;if(t)return typeof t=="string"?t:t.uri}}new TripleBuilderImpl(new UriResolverImpl);function getDocumentUriFromSubjectUri(n){const e=n.indexOf("#");return e!==-1?n.substring(0,e):n}class UpdateBuilder{constructor(e,t=new UriResolverImpl){this.toSparqlJsTriple=r=>r,this.generator=new sparqlExports.Generator,this.prefixes=e,this.uriResolver=t,this.tripleBuilder=new TripleBuilderImpl(t)}setTableContext(e){this.tableContext=e,this.tripleBuilder.setTableRegistry(e.tableRegistry,e.tableNameRegistry),e.baseUri&&this.tripleBuilder.setBaseUri(e.baseUri)}getUriContext(e,t){if(!(!this.tableContext&&!e&&!t))return{baseUri:this.tableContext?.baseUri,tableRegistry:this.tableContext?.tableRegistry,tableNameRegistry:this.tableContext?.tableNameRegistry,record:e,currentTable:t}}resolveLinkTerm(e,t,r,i){const s=String(e??"").replace(/^<|>$/g,"");if(this.uriResolver.isAbsoluteUri(s))return s;try{return this.uriResolver.resolveLink(s,t,this.getUriContext(i,r))}catch(o){const a=r.config?.name??"unknown",u=t?.name??"unknown";throw new Error(`[UpdateBuilder] Failed to resolve URI for ${a}.${u}: ${o}`)}}formatValueOrThrow(e,t,r,i){try{return formatValue(e,t,this.uriResolver,this.getUriContext(i,r))}catch(s){const o=r.config?.name??"unknown",a=t?.name??"unknown";throw new Error(`[UpdateBuilder] Failed to resolve URI for ${o}.${a}: ${s}`)}}convertInsert(e,t,r){if(!t&&!e)throw new Error("INSERT operation requires a target table");let i,s;if(Array.isArray(e)){if(i=e,!t)throw new Error("INSERT operation requires a target table");s=t}else i=e.rows,s=e.table;const o=new Set,a=[];for(const d of i)d.id&&(o.has(d.id)?a.push(d.id):o.add(d.id));if(a.length>0)throw new Error(`Duplicate IDs found in insert data: ${a.join(", ")}`);const u=this.buildInsertTriples(i,s),c=[];if(r){const d={type:"bgp",triples:u};c.push({updateType:"insert",insert:[{type:"graph",name:{termType:"NamedNode",value:r},patterns:[d]}]})}else{const d={};for(const f of u)if(f.subject&&f.subject.termType==="NamedNode"){const m=getDocumentUriFromSubjectUri(f.subject.value);d[m]||(d[m]=[]),d[m].push(f)}else d.__default__||(d.__default__=[]),d.__default__.push(f);for(const f in d){const g={type:"bgp",triples:d[f]};f==="__default__"?c.push({updateType:"insert",insert:[g]}):c.push({updateType:"insert",insert:[{type:"graph",name:{termType:"NamedNode",value:f},patterns:[g]}]})}}if(c.length===0)throw new Error("No valid insert statements generated");const l={type:"update",prefixes:this.prefixes,updates:c};return{type:"INSERT",query:this.generator.stringify(l),prefixes:this.prefixes}}buildInsertTriples(e,t){const r=[],i=t.config.type;for(const s of e){const o=generateSubjectUri(s,t,this.uriResolver),a={termType:"NamedNode",value:o};t.__currentRecord=s;try{r.push({subject:a,predicate:{termType:"NamedNode",value:"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"},object:{termType:"NamedNode",value:i}}),Object.entries(s).forEach(([u,c])=>{if(u==="id"||c===void 0||c===null)return;const l=t.columns[u];if(!l)return;const d=getPredicateForColumn(l,t);if(l.dataType==="object"||l.dataType==="json"||l.dataType==="array"&&(l.elementType==="object"||l.options?.baseType==="object")){const b=this.tripleBuilder.buildInsert(o,l,c,t);r.push(...b.triples.map(this.toSparqlJsTriple),...b.childTriples?.map(this.toSparqlJsTriple)??[]);return}if(l.options?.inverse){(Array.isArray(c)?c:[c]).forEach(S=>{const w=this.resolveLinkTerm(S,l,t,s);r.push({subject:{termType:"NamedNode",value:w},predicate:{termType:"NamedNode",value:d},object:a})});return}const m=this.formatValueOrThrow(c,l,t,s),g=this.parseTermString(m);r.push({subject:a,predicate:{termType:"NamedNode",value:d},object:g})})}finally{delete t.__currentRecord}}return r}convertUpdate(e,t,r,i){const s=this.extractSubjectRecords(t);if(s.length===0)throw new Error("UPDATE operation requires an id or @id condition to target a specific resource");const o=[];for(const u of s){const c=generateSubjectUri(u,r,this.uriResolver),d={termType:"NamedNode",value:i||getDocumentUriFromSubjectUri(c)},{deleteTriples:f,insertTriples:m,whereTriples:g}=this.buildUpdatePartsForRecord(c,e,r),b={type:"bgp",triples:f},S={type:"bgp",triples:g.length>0?g:f};if(f.length>0&&o.push({updateType:"insertdelete",delete:[{type:"graph",name:d,patterns:[b]}],insert:[],where:[{type:"graph",name:d,patterns:[S]}]}),m.length>0){const w={type:"bgp",triples:m};o.push({updateType:"insert",insert:[{type:"graph",name:d,patterns:[w]}]})}}if(o.length===0)throw new Error("No valid update statements generated for provided data");const a={type:"update",prefixes:this.prefixes,updates:o};return{type:"UPDATE",query:this.generator.stringify(a),prefixes:this.prefixes}}convertDelete(e,t,r){const i=[];let s=[],o=[];const a=this.extractSubjectRecords(e);if(a.length===0)if(r){const c={termType:"NamedNode",value:r};s.push({subject:{termType:"Variable",value:"s"},predicate:{termType:"Variable",value:"p"},object:{termType:"Variable",value:"o"}}),o.push({subject:{termType:"Variable",value:"s"},predicate:{termType:"NamedNode",value:"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"},object:{termType:"NamedNode",value:t.config.type}});const l={updateType:"insertdelete",delete:[{type:"graph",name:c,patterns:[{type:"bgp",triples:s}]}],insert:[],where:[{type:"graph",name:c,patterns:[{type:"bgp",triples:o}]}]};i.push(l)}else throw new Error("DELETE operation in Document Mode requires specific resource IDs or an explicit target graph.");else for(const c of a){const l=generateSubjectUri(c,t,this.uriResolver),f={termType:"NamedNode",value:r||getDocumentUriFromSubjectUri(l)},w={updateType:"insertdelete",delete:[{type:"graph",name:f,patterns:[{type:"bgp",triples:[{subject:{termType:"NamedNode",value:l},predicate:{termType:"Variable",value:"p"},object:{termType:"Variable",value:"o"}}]}]}],insert:[],where:[{type:"graph",name:f,patterns:[{type:"bgp",triples:[{subject:{termType:"NamedNode",value:l},predicate:{termType:"Variable",value:"p"},object:{termType:"Variable",value:"o"}}]}]}]};i.push(w)}if(i.length===0)throw new Error("No valid delete statements generated");const u={type:"update",prefixes:this.prefixes,updates:i};return{type:"DELETE",query:this.generator.stringify(u),prefixes:this.prefixes}}buildUpdatePartsForRecord(e,t,r){const i=[],s=[],o=[];return Object.entries(t).forEach(([a,u],c)=>{const l=r.columns[a];if(!l)return;const d=getPredicateForColumn(l,r),f=`old_${a}_${c}`,m=l.dataType==="object"||l.dataType==="array"&&(l.elementType==="object"||l.options?.baseType==="object"),g={termType:"NamedNode",value:e},b={termType:"NamedNode",value:d},S={termType:"Variable",value:f};if(l.dataType==="json"||l.dataType==="array"&&(l.elementType==="json"||l.options?.baseType==="json")){const v={subject:g,predicate:b,object:S};if(i.push(v),o.push(v),u!=null){const _=this.tripleBuilder.buildInsert(e,l,u,r);s.push(..._.triples.map(this.toSparqlJsTriple))}return}if(m){const v={termType:"Variable",value:`p_${f}`},_={termType:"Variable",value:`o_${f}`},T={subject:g,predicate:b,object:S},C={subject:S,predicate:v,object:_};if(i.push(T,C),o.push(T,C),u!=null){const U=this.tripleBuilder.buildInsert(e,l,u,r);s.push(...U.triples.map(this.toSparqlJsTriple),...U.childTriples?.map(this.toSparqlJsTriple)??[])}return}if(l.options?.inverse){const v={subject:S,predicate:b,object:g};if(i.push(v),o.push(v),u!=null){const _=this.resolveLinkTerm(u,l,r,t);s.push({subject:{termType:"NamedNode",value:_},predicate:b,object:g})}}else{const v={subject:g,predicate:b,object:S};if(i.push(v),o.push(v),u!=null){const _=this.formatValueOrThrow(u,l,r,t),T=this.parseTermString(_);s.push({subject:g,predicate:b,object:T})}}}),{deleteTriples:i,insertTriples:s,whereTriples:o}}parseTermString(e){if(typeof e!="string")return{termType:"Literal",value:String(e)};if(e.startsWith("<"))return{termType:"NamedNode",value:e.slice(1,-1)};if(e.startsWith("_:"))return{termType:"BlankNode",value:e.slice(2)};if(e.startsWith('"')){const t=e.lastIndexOf('"'),r=e.slice(1,t),i=e.slice(t+1);let s,o;if(i.startsWith("^^")){const a=i.slice(2);s={termType:"NamedNode",value:a.startsWith("<")?a.slice(1,-1):a}}else i.startsWith("@")&&(o=i.slice(1));return{termType:"Literal",value:r,datatype:s,language:o}}return{termType:"Literal",value:e}}extractSubjectRecords(e){if(!e)return[];if(this.isQueryCondition(e)){const t=this.findConditionValue(e,"id"),r=this.findConditionValue(e,"@id"),i={};return r&&(i["@id"]=r),t&&(i.id=t),Object.keys(i).length>0?[i]:[]}return typeof e=="object"&&(e.id||e["@id"])?[e]:[]}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e}findConditionValue(e,t){if(e.type==="binary_expr"&&e.operator==="="){const r=e.left,i=e.right;let s;if(typeof r=="string"?s=r.includes(".")?r.split(".")[1]:r:r&&typeof r=="object"&&"name"in r?s=r.name:r&&typeof r=="object"&&"column"in r&&(s=r.column),s===t&&i!=null)return typeof i=="object"&&"value"in i?i.value:i}if(e.type==="logical_expr"){const r=e.expressions||e.conditions||[];for(const i of r){const s=this.findConditionValue(i,t);if(s!==void 0)return s}}}}class ASTToSPARQLConverter{constructor(e,t,r){this.podUrl=e,this.webId=t,this.prefixes={rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",schema:"https://schema.org/",foaf:"http://xmlns.com/foaf/0.1/",dc:"http://purl.org/dc/terms/",solid:"http://www.w3.org/ns/solid/terms#",ldp:"http://www.w3.org/ns/ldp#",xsd:"http://www.w3.org/2001/XMLSchema#"},this.uriResolver=r??new UriResolverImpl(e),this.selectBuilder=new SelectBuilder(this.prefixes,this.uriResolver),this.updateBuilder=new UpdateBuilder(this.prefixes,this.uriResolver),this.expressionBuilder=new ExpressionBuilder(this.uriResolver)}setTableRegistry(e,t,r){this.tableContext={tableRegistry:e,tableNameRegistry:t,baseUri:r},this.selectBuilder.setTableContext(this.tableContext),this.expressionBuilder.setTableContext(this.tableContext),this.updateBuilder.setTableContext(this.tableContext)}convertSelect(e,t,r,i,s=!0){return this.selectBuilder.convertSelect(e,t,r,i,s)}buildWhereClauseForCondition(e,t){return this.expressionBuilder.buildWhereClause(e,t)}convertSelectPlan(e,t,r,i=!0){return this.selectBuilder.convertSelectPlan(e,t,r,i)}convertSimpleSelect(e,t,r,i=!0){return this.selectBuilder.convertSimpleSelect(e,t,r,i)}convertInsert(e,t,r){return this.updateBuilder.convertInsert(e,t,r)}convertUpdate(e,t,r,i){return this.updateBuilder.convertUpdate(e,t,r,i)}convertDelete(e,t,r){return this.updateBuilder.convertDelete(e,t,r)}getPrefixes(){return this.prefixes}addPrefix(e,t){this.prefixes[e]=t}getPredicateForColumnPublic(e,t){return getPredicateForColumn(e,t)}formatLiteralValue(e,t){return formatValue(e,t)}generateSubjectUri(e,t){return generateSubjectUri(e,t,this.uriResolver)}parseDrizzleAST(e,t){return{type:"select",columns:"*",where:this.parseWhereClause(e)}}parseWhereClause(e){return{}}}class TypeIndexDiscovery{constructor(e,t,r){this.manager=e,this.podUrl=t,this.uriResolver=r??new UriResolverImpl(t)}setPodUrl(e){this.podUrl=e}getPodUrl(){return typeof this.manager.getConfig=="function"?this.manager.getConfig().podUrl||this.podUrl:this.podUrl}async register(e,t){if(!e.shouldRegisterTypeIndex?.())return;e.config.name??JSON.stringify(e.config);const i=this.getRdfClass(e),s=e._.config?.isPublic?"public":"private";this.uriResolver.getResourceMode(e);let o=e.getContainerPath()||"/data/";const a=this.getPodUrl();let u=`${a.replace(/\/$/,"")}${o}`;const c=this.resolveTableResource(e);if(c.mode==="ldp"){const d=c.containerUrl,f=a.replace(/\/$/,"");d.startsWith(f)&&(o=d.substring(f.length),u=d.replace(/\/$/,"")+"/")}const l={rdfClass:i,containerPath:o,forClass:e.config.name,instanceContainer:u,visibility:s};try{const d=await this.manager.discoverSpecificType(i);d&&d.instanceContainer!==u&&console.warn(`[TypeIndexDiscovery] ⚠️ TypeIndex has different path for ${e.config.name}:
|
|
74
|
+
- TypeIndex: ${d.instanceContainer}
|
|
75
|
+
- Configured: ${u}
|
|
76
|
+
Updating TypeIndex to use configured path...`),await this.manager.registerType(l)}catch(d){this.handleRegistrationError(d,l,s)}}async discover(e,t){const r=[],i=await this.manager.discoverSpecificTypes([e]);for(const s of i)r.push({container:s.instanceContainer??s.containerPath,shapes:[],source:"typeindex"});return r}async isRegistered(e){return!!await this.manager.discoverSpecificType(e)}getRdfClass(e){return typeof e.config.type=="string"?e.config.type:e.config.type.value||String(e.config.type)}resolveTableResource(e){const t=e.getResourcePath?.()??e.config.base,r=e.getContainerPath()||"/data/";return{mode:"ldp",containerUrl:this.toAbsolute(r),resourceUrl:this.toAbsolute(t??r)}}toAbsolute(e){if(e.startsWith("http"))return e;const t=this.getPodUrl(),r=t.endsWith("/")?t:`${t}/`,i=e.startsWith("/")?e.slice(1):e;return`${r}${i}`}async handleRegistrationError(e,t,r){if((e instanceof Error?e.message:String(e)).includes("TypeIndex not found")){console.warn("[TypeIndexDiscovery] TypeIndex missing. Attempting to create.");try{const s=await this.manager.createTypeIndex(r==="public");await this.manager.registerType(t,s)}catch(s){console.warn("[TypeIndexDiscovery] Unable to create TypeIndex. Continuing without registration.",s)}}else console.warn("[TypeIndexDiscovery] TypeIndex registration failed. Continuing without registration.",e)}}const INTEROP={NS:"http://www.w3.org/ns/solid/interop#",ApplicationRegistration:"http://www.w3.org/ns/solid/interop#ApplicationRegistration",DataRegistration:"http://www.w3.org/ns/solid/interop#DataRegistration",AccessGrant:"http://www.w3.org/ns/solid/interop#AccessGrant",DataGrant:"http://www.w3.org/ns/solid/interop#DataGrant",RegistrySet:"http://www.w3.org/ns/solid/interop#RegistrySet",DataRegistry:"http://www.w3.org/ns/solid/interop#DataRegistry",hasRegistrySet:"http://www.w3.org/ns/solid/interop#hasRegistrySet",hasDataRegistry:"http://www.w3.org/ns/solid/interop#hasDataRegistry",hasDataRegistration:"http://www.w3.org/ns/solid/interop#hasDataRegistration",registeredShapeTree:"http://www.w3.org/ns/solid/interop#registeredShapeTree",registeredBy:"http://www.w3.org/ns/solid/interop#registeredBy",hasAccessGrant:"http://www.w3.org/ns/solid/interop#hasAccessGrant",hasDataGrant:"http://www.w3.org/ns/solid/interop#hasDataGrant",scopeOfGrant:"http://www.w3.org/ns/solid/interop#scopeOfGrant",dataOwner:"http://www.w3.org/ns/solid/interop#dataOwner",registeredShapeTreeProp:"http://www.w3.org/ns/solid/interop#registeredShapeTree"},SHAPETREES={NS:"http://www.w3.org/ns/shapetrees#",ShapeTree:"http://www.w3.org/ns/shapetrees#ShapeTree",expectsType:"http://www.w3.org/ns/shapetrees#expectsType",shape:"http://www.w3.org/ns/shapetrees#shape"},UDFS$1={NS:"https://vocab.undefineds.co/",subjectTemplate:"https://vocab.undefineds.co/subjectTemplate"},ns={prefix:"interop",uri:INTEROP.NS},registrySetSchema=solidSchema({id:id(),hasDataRegistry:uri("hasDataRegistry").array().predicate(INTEROP.hasDataRegistry),hasAgentRegistry:uri("hasAgentRegistry").array().predicate("http://www.w3.org/ns/solid/interop#hasAgentRegistry")},{type:INTEROP.RegistrySet,namespace:ns}),dataRegistrySchema=solidSchema({id:id(),hasDataRegistration:uri("hasDataRegistration").array().predicate(INTEROP.hasDataRegistration)},{type:INTEROP.DataRegistry,namespace:ns}),dataRegistrationSchema=solidSchema({id:id(),registeredShapeTree:uri("registeredShapeTree").predicate(INTEROP.registeredShapeTree),registeredBy:uri("registeredBy").predicate(INTEROP.registeredBy),registeredAt:string$2("registeredAt").predicate("http://www.w3.org/ns/solid/interop#registeredAt"),subjectTemplate:string$2("subjectTemplate").predicate(UDFS$1.subjectTemplate)},{type:INTEROP.DataRegistration,namespace:ns}),applicationRegistrationSchema=solidSchema({id:id(),registeredAgent:uri("registeredAgent").predicate("http://www.w3.org/ns/solid/interop#registeredAgent"),hasAccessGrant:uri("hasAccessGrant").predicate(INTEROP.hasAccessGrant)},{type:INTEROP.ApplicationRegistration,namespace:ns}),accessGrantSchema=solidSchema({id:id(),grantedBy:uri("grantedBy").predicate("http://www.w3.org/ns/solid/interop#grantedBy"),grantedAt:string$2("grantedAt").predicate("http://www.w3.org/ns/solid/interop#grantedAt"),grantee:uri("grantee").predicate("http://www.w3.org/ns/solid/interop#grantee"),hasDataGrant:uri("hasDataGrant").array().predicate(INTEROP.hasDataGrant)},{type:INTEROP.AccessGrant,namespace:ns}),dataGrantSchema=solidSchema({id:id(),registeredShapeTree:uri("registeredShapeTree").predicate(INTEROP.registeredShapeTree),hasDataRegistration:uri("hasDataRegistration").predicate(INTEROP.hasDataRegistration),scopeOfGrant:uri("scopeOfGrant").predicate(INTEROP.scopeOfGrant),accessMode:uri("accessMode").array().predicate("http://www.w3.org/ns/solid/interop#accessMode"),dataOwner:uri("dataOwner").predicate(INTEROP.dataOwner)},{type:INTEROP.DataGrant,namespace:ns});var link,hasRequiredLink;function requireLink(){if(hasRequiredLink)return link;hasRequiredLink=1;var n=/^utf-?8|ascii|utf-?16-?le|ucs-?2|base-?64|latin-?1$/i,e=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/\s|\uFEFF|\xA0/,r=/\r?\n[\x20\x09]+/g,i=/[;,"]/,s=/[;,"]|\s/,o=/^[!#$%&'*+\-\.^_`|~\da-zA-Z]+$/,a={IDLE:1,URI:2,ATTR:4};function u(g){return g.replace(e,"")}function c(g){return t.test(g)}function l(g,b){for(;c(g[b]);)b++;return b}function d(g){return s.test(g)||!o.test(g)}function f(g,b){return Object.keys(g).length===Object.keys(b).length&&Object.keys(g).every(S=>S in b&&g[S]===b[S])}class m{constructor(b){this.refs=[],b&&this.parse(b)}rel(b){for(var S=[],w=b.toLowerCase(),v=0;v<this.refs.length;v++)typeof this.refs[v].rel=="string"&&this.refs[v].rel.toLowerCase()===w&&S.push(this.refs[v]);return S}get(b,S){b=b.toLowerCase(),S=S.toLowerCase();for(var w=[],v=0;v<this.refs.length;v++)typeof this.refs[v][b]=="string"&&this.refs[v][b].toLowerCase()===S&&w.push(this.refs[v]);return w}set(b){return this.refs.push(b),this}setUnique(b){return this.refs.some(S=>f(S,b))||this.refs.push(b),this}has(b,S){b=b.toLowerCase(),S=S.toLowerCase();for(var w=0;w<this.refs.length;w++)if(typeof this.refs[w][b]=="string"&&this.refs[w][b].toLowerCase()===S)return!0;return!1}parse(b,_){_=_||0,b=_?b.slice(_):b,b=u(b).replace(r,"");for(var w=a.IDLE,v=b.length,_=0,T=null;_<v;)if(w===a.IDLE){if(c(b[_])){_++;continue}else if(b[_]==="<"){T!=null&&(T.rel!=null?this.refs.push(...m.expandRelations(T)):this.refs.push(T));var C=b.indexOf(">",_);if(C===-1)throw new Error("Expected end of URI delimiter at offset "+_);T={uri:b.slice(_+1,C)},_=C,w=a.URI}else throw new Error('Unexpected character "'+b[_]+'" at offset '+_);_++}else if(w===a.URI)if(c(b[_])){_++;continue}else if(b[_]===";")w=a.ATTR,_++;else if(b[_]===",")w=a.IDLE,_++;else throw new Error('Unexpected character "'+b[_]+'" at offset '+_);else if(w===a.ATTR){if(b[_]===";"||c(b[_])){_++;continue}var C=b.indexOf("=",_);C===-1&&(C=b.indexOf(";",_)),C===-1&&(C=b.length);var U=u(b.slice(_,C)).toLowerCase(),$="";if(_=C+1,_=l(b,_),b[_]==='"')for(_++;_<v;){if(b[_]==='"'){_++;break}b[_]==="\\"&&_++,$+=b[_],_++}else{for(var C=_+1;!i.test(b[C])&&C<v;)C++;$=b.slice(_,C),_=C}switch(T[U]&&m.isSingleOccurenceAttr(U)||(U[U.length-1]==="*"?T[U]=m.parseExtendedValue($):($=U==="type"?$.toLowerCase():$,T[U]!=null?Array.isArray(T[U])?T[U].push($):T[U]=[T[U],$]:T[U]=$)),b[_]){case",":w=a.IDLE;break;case";":w=a.ATTR;break}_++}else throw new Error('Unknown parser state "'+w+'"');return T!=null&&(T.rel!=null?this.refs.push(...m.expandRelations(T)):this.refs.push(T)),T=null,this}toString(){for(var b=[],S="",w=null,v=0;v<this.refs.length;v++)w=this.refs[v],S=Object.keys(this.refs[v]).reduce(function(_,T){return T==="uri"?_:_+"; "+m.formatAttribute(T,w[T])},"<"+w.uri+">"),b.push(S);return b.join(", ")}}return m.isCompatibleEncoding=function(g){return n.test(g)},m.parse=function(g,b){return new m().parse(g,b)},m.isSingleOccurenceAttr=function(g){return g==="rel"||g==="type"||g==="media"||g==="title"||g==="title*"},m.isTokenAttr=function(g){return g==="rel"||g==="type"||g==="anchor"},m.escapeQuotes=function(g){return g.replace(/"/g,'\\"')},m.expandRelations=function(g){var b=g.rel.split(" ");return b.map(function(S){var w=Object.assign({},g);return w.rel=S,w})},m.parseExtendedValue=function(g){var b=/([^']+)?(?:'([^']*)')?(.+)/.exec(g);return{language:b[2].toLowerCase(),encoding:m.isCompatibleEncoding(b[1])?null:b[1].toLowerCase(),value:m.isCompatibleEncoding(b[1])?decodeURIComponent(b[3]):b[3]}},m.formatExtendedAttribute=function(g,b){var S=(b.encoding||"utf-8").toUpperCase(),w=b.language||"en",v="";return typeof Buffer<"u"&&Buffer.isBuffer(b.value)&&m.isCompatibleEncoding(S)?v=b.value.toString(S):typeof Buffer<"u"&&Buffer.isBuffer(b.value)?v=b.value.toString("hex").replace(/[0-9a-f]{2}/gi,"%$1"):v=encodeURIComponent(b.value),g+"="+S+"'"+w+"'"+v},m.formatAttribute=function(g,b){return Array.isArray(b)?b.map(S=>m.formatAttribute(g,S)).join("; "):g[g.length-1]==="*"||typeof b!="string"?m.formatExtendedAttribute(g,b):(m.isTokenAttr(g)?b=d(b)?'"'+m.escapeQuotes(b)+'"':m.escapeQuotes(b):d(b)&&(b=encodeURIComponent(b),b=b.replace(/%20/g," ").replace(/%2C/g,",").replace(/%3B/g,";"),b='"'+b+'"'),g+"="+b)},link=m,link}class InruptClientError extends Error{}const PROBLEM_DETAILS_MIME="application/problem+json",DEFAULT_TYPE=new URL("about:blank");function asUrl$1(n,e){if(n!==void 0)try{return new URL(n,e)}catch{}}function buildProblemDetails(n){let e,t,r,i,s;if(n.headers.get("Content-Type")===PROBLEM_DETAILS_MIME)try{const o=JSON.parse(n.body),a=asUrl$1(o.type,n.url);a!==void 0&&(e=a),typeof o.title=="string"&&(t=o.title),typeof o.status=="number"&&(r=o.status),typeof o.detail=="string"&&(i=o.detail);const u=asUrl$1(o.instance,n.url);u!==void 0&&(s=u)}catch{}return Object.freeze({type:e??DEFAULT_TYPE,title:t??n.statusText,status:r??n.status,detail:i,instance:s})}class ClientHttpError extends InruptClientError{constructor(e,t,r,i){if(super(r,i),e.status>=200&&e.status<400)throw new InruptClientError(`A ClientHttpError cannot be built from a success response, got ${e.status} ${e.statusText}`);this.errorResponse=Object.freeze({status:e.status,statusText:e.statusText,headers:e.headers,url:e.url,body:t,ok:!1}),this.details=buildProblemDetails(this.errorResponse)}get response(){return this.errorResponse}get problemDetails(){return this.details}}function hasResourceInfo(n){const e=n;return typeof e=="object"&&typeof e.internal_resourceInfo=="object"}function hasServerResourceInfo(n){const e=n;return typeof e=="object"&&typeof e.internal_resourceInfo=="object"&&typeof e.internal_resourceInfo.linkedResources=="object"}function hasChangelog(n){const e=n;return typeof e.internal_changeLog=="object"&&Array.isArray(e.internal_changeLog.additions)&&Array.isArray(e.internal_changeLog.deletions)}class SolidClientError extends Error{}function internal_toIriString(n){return typeof n=="string"?n:n.value}function normalizeUrl(n,e={}){const t=new URL(n);return t.pathname=t.pathname.replace(/\/\/+/g,"/"),e.trailingSlash===!1&&t.pathname.slice(-1)==="/"&&(t.pathname=t.pathname.slice(0,t.pathname.length-1)),e.trailingSlash===!0&&t.pathname.slice(-1)!=="/"&&(t.pathname=`${t.pathname}/`),t.href}var linkExports=requireLink();const LinkHeader=getDefaultExportFromCjs(linkExports);function internal_parseResourceInfo(n){var e,t,r,i,s;const o=(t=(e=n.headers.get("Content-Type"))===null||e===void 0?void 0:e.split(";"))!==null&&t!==void 0?t:[],a=o.length>0&&["text/turtle","application/ld+json"].includes(o[0]),u={sourceIri:n.url,isRawData:!a,contentLocation:(r=n.headers.get("Content-Location"))!==null&&r!==void 0?r:void 0,contentType:(i=n.headers.get("Content-Type"))!==null&&i!==void 0?i:void 0,linkedResources:{},location:(s=n.headers.get("Location"))!==null&&s!==void 0?s:void 0},c=n.headers.get("Link");if(c){const d=LinkHeader.parse(c),f=d.get("rel","acl");f.length===1&&(u.aclUrl=new URL(f[0].uri,u.sourceIri).href),u.linkedResources=d.refs.reduce((m,g)=>{var b,S;return(b=m[S=g.rel])!==null&&b!==void 0||(m[S]=[]),m[g.rel].push(new URL(g.uri,u.sourceIri).href),m},u.linkedResources)}const l=n.headers.get("WAC-Allow");return l&&(u.permissions=parseWacAllowHeader(l)),u}function parseWacAllowHeader(n){function e(r){const i=r.split(" ");return i.includes("write")?{read:i.includes("read"),append:!0,write:!0,control:i.includes("control")}:{read:i.includes("read"),append:i.includes("append"),write:!1,control:i.includes("control")}}function t(r,i){const s=r.split(",").map(a=>a.split("=")).filter(a=>a.length===2&&a[0].trim()===i);if(s.length!==1)return"";const o=s[0][1].trim();return o.charAt(0)!=='"'||o.charAt(o.length-1)!=='"'?"":o.substring(1,o.length-1)}return{user:e(t(n,"user")),public:e(t(n,"public"))}}function internal_cloneResource(n){let e;return typeof n.slice=="function"?e=Object.assign(n.slice(),{...n}):e={...n},e}function internal_isUnsuccessfulResponse(n){return!n.ok}function internal_isAuthenticationFailureResponse(n){return n.status===401||n.status===403}const acl={Authorization:"http://www.w3.org/ns/auth/acl#Authorization",accessTo:"http://www.w3.org/ns/auth/acl#accessTo",agent:"http://www.w3.org/ns/auth/acl#agent",agentGroup:"http://www.w3.org/ns/auth/acl#agentGroup",agentClass:"http://www.w3.org/ns/auth/acl#agentClass",default:"http://www.w3.org/ns/auth/acl#default",defaultForNew:"http://www.w3.org/ns/auth/acl#defaultForNew",mode:"http://www.w3.org/ns/auth/acl#mode",origin:"http://www.w3.org/ns/auth/acl#origin"},rdf$2={type:"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"},ldp={BasicContainer:"http://www.w3.org/ns/ldp#BasicContainer",Resource:"http://www.w3.org/ns/ldp#Resource"},foaf={Agent:"http://xmlns.com/foaf/0.1/Agent"},acp={AccessControlResource:"http://www.w3.org/ns/solid/acp#AccessControlResource",agent:"http://www.w3.org/ns/solid/acp#agent"};async function getResourceInfo(n,e){var t,r;const i=await((t=e?.fetch)!==null&&t!==void 0?t:fetch)(normalizeUrl(n),{method:"HEAD"});return responseToResourceInfo(i,{ignoreAuthenticationErrors:(r=e?.ignoreAuthenticationErrors)!==null&&r!==void 0?r:!1})}function responseToResourceInfo(n,e={ignoreAuthenticationErrors:!1}){if(internal_isUnsuccessfulResponse(n)&&(!internal_isAuthenticationFailureResponse(n)||!e.ignoreAuthenticationErrors))throw new FetchError(`Fetching the metadata of the Resource at [${n.url}] failed: [${n.status}] [${n.statusText}].`,n);return{internal_resourceInfo:internal_parseResourceInfo(n)}}function getContentType(n){var e;return(e=n.internal_resourceInfo.contentType)!==null&&e!==void 0?e:null}function getSourceUrl(n){return hasResourceInfo(n)?n.internal_resourceInfo.sourceIri:null}const getSourceIri=getSourceUrl;function getLinkedResourceUrlAll(n){return n.internal_resourceInfo.linkedResources}class FetchError extends SolidClientError{constructor(e,t,r){super(e),this.response=t,typeof r=="string"?this.httpError=new ClientHttpError(t,r,e):this.httpError=new ClientHttpError(t,"",e)}get statusCode(){return this.response.status}get statusText(){return this.response.statusText}get problemDetails(){return this.httpError.problemDetails}}const RDF$2="http://www.w3.org/1999/02/22-rdf-syntax-ns#",XSD$1="http://www.w3.org/2001/XMLSchema#",SWAP="http://www.w3.org/2000/10/swap/",namespaces$1={xsd:{decimal:`${XSD$1}decimal`,boolean:`${XSD$1}boolean`,double:`${XSD$1}double`,integer:`${XSD$1}integer`,string:`${XSD$1}string`},rdf:{type:`${RDF$2}type`,nil:`${RDF$2}nil`,first:`${RDF$2}first`,rest:`${RDF$2}rest`,langString:`${RDF$2}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$2}=namespaces$1,escapeSequence=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,escapeReplacements={"\\":"\\","'":"'",'"':'"',n:`
|
|
77
|
+
`,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 r=this._input,i=r.length;for(;;){let a,u;for(;a=this._newline.exec(r);)this.comments&&(u=this._comment.exec(a[0]))&&s("comment",u[1],"",this._line,a[0].length),r=r.substr(a[0].length,r.length),i=r.length,this._line++;if(!a&&(a=this._whitespace.exec(r))&&(r=r.substr(a[0].length,r.length)),this._endOfFile.test(r))return t&&(this.comments&&(u=this._comment.exec(r))&&s("comment",u[1],"",this._line,r.length),r=null,s("eof","","",this._line,0)),this._input=r;const c=this._line,l=r[0];let d="",f="",m="",g=null,b=0,S=!1;switch(l){case"^":if(r.length<3)break;if(r[1]==="^"){if(this._previousMarker="^^",r=r.substr(2),r[0]!=="<"){S=!0;break}}else{this._n3Mode&&(b=1,d="^");break}case"<":if(g=this._unescapedIri.exec(r))d="IRI",f=g[1];else if(g=this._iri.exec(r)){if(f=this._unescape(g[1]),f===null||illegalIriChars.test(f))return o(this);d="IRI"}else r.length>1&&r[1]==="<"?(d="<<",b=2):this._n3Mode&&r.length>1&&r[1]==="="&&(b=2,this._isImpliedBy?(d="abbreviation",f="<"):(d="inverse",f=">"));break;case">":r.length>1&&r[1]===">"&&(d=">>",b=2);break;case"_":((g=this._blank.exec(r))||t&&(g=this._blank.exec(`${r} `)))&&(d="blank",m="_",f=g[1]);break;case'"':if(g=this._simpleQuotedString.exec(r))f=g[1];else if({value:f,matchLength:b}=this._parseLiteral(r),f===null)return o(this);(g!==null||b!==0)&&(d="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(g=this._simpleApostropheString.exec(r))f=g[1];else if({value:f,matchLength:b}=this._parseLiteral(r),f===null)return o(this);(g!==null||b!==0)&&(d="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(g=this._variable.exec(r))&&(d="var",f=g[0]);break;case"@":this._previousMarker==="literal"&&(g=this._langcode.exec(r))?(d="langcode",f=g[1]):(g=this._keyword.exec(r))&&(d=g[0]);break;case".":if(r.length===1?t:r[1]<"0"||r[1]>"9"){d=".",b=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(g=this._number.exec(r)||t&&(g=this._number.exec(`${r} `)))&&(d="literal",f=g[0],m=typeof g[1]=="string"?xsd$2.double:typeof g[2]=="string"?xsd$2.decimal:xsd$2.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(g=this._sparqlKeyword.exec(r))?d=g[0].toUpperCase():S=!0;break;case"f":case"t":(g=this._boolean.exec(r))?(d="literal",f=g[0],m=xsd$2.boolean):S=!0;break;case"a":(g=this._shortPredicates.exec(r))?(d="abbreviation",f="a"):S=!0;break;case"=":this._n3Mode&&r.length>1&&(d="abbreviation",r[1]!==">"?(b=1,f="="):(b=2,f=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(b=1,d=l);break;case"{":!this._lineMode&&r.length>=2&&(r[1]==="|"?(d="{|",b=2):(d=l,b=1));break;case"|":r.length>=2&&r[1]==="}"&&(d="|}",b=2);break;default:S=!0}if(S&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(g=this._prefix.exec(r))?(d="prefix",f=g[1]||""):((g=this._prefixed.exec(r))||t&&(g=this._prefixed.exec(`${r} `)))&&(d="prefixed",m=g[1]||"",f=this._unescape(g[2]))),this._previousMarker==="^^")switch(d){case"prefixed":d="type";break;case"IRI":d="typeIRI";break;default:d=""}if(!d)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?o(this):this._input=r;const w=b||g[0].length,v=s(d,f,m,c,w);this.previousToken=v,this._previousMarker=d,r=r.substr(w,r.length)}function s(a,u,c,l,d){const f=r?i-r.length:i,m=f+d,g={type:a,value:u,prefix:c,line:l,start:f,end:m};return e(null,g),g}function o(a){e(a._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1;const r=e.replace(escapeSequence,(i,s,o,a)=>{if(typeof s=="string")return String.fromCharCode(Number.parseInt(s,16));if(typeof o=="string"){let u=Number.parseInt(o,16);return u<=65535?String.fromCharCode(Number.parseInt(o,16)):String.fromCharCode(55296+((u-=65536)>>10),56320+(u&1023))}return a in escapeReplacements?escapeReplacements[a]:(t=!0,"")});return t?null:r}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],r=t.length;let i=Math.max(this._literalClosingPos,r);for(;(i=e.indexOf(t,i))>0;){let s=0;for(;e[i-s-1]==="\\";)s++;if(s%2===0){const o=e.substring(r,i),a=o.split(/\r\n|\r|\n/).length-1,u=i+r;if(r===1&&a!==0||r===3&&this._lineMode)break;return this._line+=a,{value:this._unescape(o),matchLength:u}}i++}this._literalClosingPos=e.length-r+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 r=[];let i;if(this._tokenizeToEnd((s,o)=>s?i=s:r.push(o),!0),i)throw i;return r}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",r=>{this._input!==null&&r.length!==0&&(this._pendingBuffer&&(r=bufferExports.Buffer.concat([this._pendingBuffer,r]),this._pendingBuffer=null),r[r.length-1]&128?this._pendingBuffer=r:(typeof this._input>"u"?this._input=this._readStartingBom(typeof r=="string"?r:r.toString()):this._input+=r,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}}const{rdf:rdf$1,xsd:xsd$1}=namespaces$1;let DEFAULTGRAPH$1,_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,r=t<e.length?e[t]:"";return r==="^"?e.substr(t+2):r!=="@"?xsd$1.string:rdf$1.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$1||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}}DEFAULTGRAPH$1=new DefaultGraph;function termFromId(n,e,t){if(e=e||DataFactory,!n)return e.defaultGraph();switch(n[0]){case"?":return e.variable(n.substr(1));case"_":return e.blankNode(n.substr(2));case'"':if(e===DataFactory)return new Literal(n);if(n[n.length-1]==='"')return e.literal(n.substr(1,n.length-2));const r=n.lastIndexOf('"',n.length-1);return e.literal(n.substr(1,r-1),n[r+1]==="@"?n.substr(r+2):e.namedNode(n.substr(r+3)));case"[":n=JSON.parse(n);break;default:if(!t||!Array.isArray(n))return e.namedNode(n)}return e.quad(termFromId(n[0],e,!0),termFromId(n[1],e,!0),termFromId(n[2],e,!0),n[3]&&termFromId(n[3],e,!0))}function termToId(n,e){if(typeof n=="string")return n;if(n instanceof Term&&n.termType!=="Quad")return n.id;if(!n)return DEFAULTGRAPH$1.id;switch(n.termType){case"NamedNode":return n.value;case"BlankNode":return`_:${n.value}`;case"Variable":return`?${n.value}`;case"DefaultGraph":return"";case"Literal":return`"${n.value}"${n.language?`@${n.language}`:n.datatype&&n.datatype.value!==xsd$1.string?`^^${n.datatype.value}`:""}`;case"Quad":const t=[termToId(n.subject,!0),termToId(n.predicate,!0),termToId(n.object,!0)];return n.graph&&n.graph.termType!=="DefaultGraph"&&t.push(termToId(n.graph,!0)),e?t:JSON.stringify(t);default:throw new Error(`Unexpected termType: ${n.termType}`)}}class Quad extends Term{constructor(e,t,r,i){super(""),this._subject=e,this._predicate=t,this._object=r,this._graph=i||DEFAULTGRAPH$1}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$1.boolean:typeof n=="number"&&(Number.isFinite(n)?t=Number.isInteger(n)?xsd$1.integer:xsd$1.double:(t=xsd$1.double,Number.isNaN(n)||(n=n>0?"INF":"-INF")))),t===""||t===xsd$1.string?new Literal(`"${n}"`):new Literal(`"${n}"^^${t}`)}function variable(n){return new Variable(n)}function defaultGraph(){return DEFAULTGRAPH$1}function quad(n,e,t,r){return new Quad(n,e,t,r)}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$1;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():"",r=/turtle/.test(t),i=/trig/.test(t),s=/triple/.test(t),o=/quad/.test(t),a=this._n3Mode=/n3/.test(t),u=s||o;(this._supportsNamedGraphs=!(r||a))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||i||s||a),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=t===""||/star|\*$/.test(t),u&&(this._resolveRelativeIRI=c=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new N3Lexer({lineMode:u,n3:a,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,r,i,s){const o=this._n3Mode;this._contextStack.push({type:e,subject:r,predicate:i,object:s,graph:t,inverse:o?this._inversePredicate:!1,blankPrefix:o?this._prefixes._:"",quantified:o?this._quantified:null}),o&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const r=this._contextStack.pop();if(!r||r.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=r.subject,this._predicate=r.predicate,this._object=r.object,this._graph=r.graph,this._n3Mode&&(this._inversePredicate=r.inverse,this._prefixes._=r.blankPrefix,this._quantified=r.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 r;switch(e.type){case"IRI":case"typeIRI":const i=this._resolveIRI(e.value);if(i===null)return this._error("Invalid IRI",e);r=this._factory.namedNode(i);break;case"type":case"prefixed":const s=this._prefixes[e.prefix];if(s===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);r=this._factory.namedNode(s+e.value);break;case"blank":r=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":r=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&r.id in this._quantified&&(r=this._quantified[r.id]),r}_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,r=null,i=this._readListItem;const s=this._subject,o=this._contextStack,a=o[o.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),i=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),o.length!==0&&o[o.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(i=this._readPredicate,this._subject===this.RDF_NIL)return i}else if(i=this._getContextEndReader(),this._object===this.RDF_NIL)return i;r=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,i=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),i=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(r===null&&(this._subject=r=this._factory.blankNode()),s===null?a.predicate===null?a.subject=r:a.object=r:this._emit(s,this.RDF_REST,r,this._graph),t!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,r,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(r,this.RDF_FIRST,t,this._graph)}return i}_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 r=this._readEntity(e);if(r===void 0)return;t=this._factory.literal(this._literalValue,r),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 r=this._completeLiteral(e);if(r)return this._object=r.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),r.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(r.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,r=this._graph;const i=this._subject,s=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,s&&(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 o=this._predicate,a=this._object;this._subject=this._factory.quad(i,o,a,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&&(r=this._readEntity(e))!==void 0){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(i!==null){const o=this._predicate,a=this._object;s?this._emit(a,o,i,r):this._emit(i,o,a,r)}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,r=t.length&&t[t.length-1];if(r&&r.type==="item"){const i=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,i,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,r;const i=this._factory.blankNode();if((r=this._readEntity(e))!==void 0)return this._predicate===null?(t=this._subject,this._subject=i):(t=this._object,this._object=i),this._emit(t,r,i,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let r,i;if((r=this._readEntity(e))!==void 0)return this._predicate===null?(i=this._subject,this._subject=t):(i=this._object,this._object=t),this._emit(t,r,i,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,r,i){this._callback(null,this._factory.quad(e,t,r,i||this.DEFAULTGRAPH))}_error(e,t){const r=new Error(`${e} on line ${t.line}.`);r.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(r),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 r="",i=-1,s=-1,o=0,a="/";for(;i<t;){switch(a){case":":if(s<0&&e[++i]==="/"&&e[++i]==="/")for(;(s=i+1)<t&&e[s]!=="/";)i=s;break;case"?":case"#":i=t;break;case"/":if(e[i+1]===".")switch(a=e[++i+1],a){case"/":r+=e.substring(o,i-1),o=i+1;break;case void 0:case"?":case"#":return r+e.substring(o,i)+e.substr(i+1);case".":if(a=e[++i+1],a===void 0||a==="/"||a==="?"||a==="#"){if(r+=e.substring(o,i-2),(o=r.lastIndexOf("/"))>=s&&(r=r.substr(0,o)),a!=="/")return`${r}/${e.substr(i+1)}`;o=i+1}}}a=e[++i]}return r+e.substring(o)}parse(e,t,r){let i,s,o;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(i=t.onQuad,s=t.onPrefix,o=t.onComment):(i=t,s=r),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix++}_`,this._prefixCallback=s||noop,this._inversePredicate=!1,this._quantified=Object.create(null),!i){const u=[];let c;if(this._callback=(l,d)=>{l?c=l:d&&u.push(d)},this._lexer.tokenize(e).every(l=>this._readCallback=this._readCallback(l)),c)throw c;return u}let a=(u,c)=>{u!==null?(this._callback(u),this._callback=noop):this._readCallback&&(this._readCallback=this._readCallback(c))};o&&(this._lexer.comments=!0,a=(u,c)=>{u!==null?(this._callback(u),this._callback=noop):this._readCallback&&(c.type==="comment"?o(c.value):this._readCallback=this._readCallback(c))}),this._callback=i,this._lexer.tokenize(e,a)}}function noop(){}function initDataFactory(n,e){n._factory=e,n.DEFAULTGRAPH=e.defaultGraph(),n.RDF_FIRST=e.namedNode(namespaces$1.rdf.first),n.RDF_REST=e.namedNode(namespaces$1.rdf.rest),n.RDF_NIL=e.namedNode(namespaces$1.rdf.nil),n.N3_FORALL=e.namedNode(namespaces$1.r.forAll),n.N3_FORSOME=e.namedNode(namespaces$1.r.forSome),n.ABBREVIATIONS={a:e.namedNode(namespaces$1.rdf.type),"=":e.namedNode(namespaces$1.owl.sameAs),">":e.namedNode(namespaces$1.log.implies),"<":e.namedNode(namespaces$1.log.isImpliedBy)},n.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}initDataFactory(N3Parser.prototype,DataFactory);function isDefaultGraph(n){return!!n&&n.termType==="DefaultGraph"}function escapeRegex$1(n){return n.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}const BASE_UNSUPPORTED=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i,SUFFIX_SUPPORTED=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/,CURRENT="./",PARENT="../",QUERY="?",FRAGMENT="#";class BaseIRI{constructor(e){this.base=e,this._baseLength=0,this._baseMatcher=null,this._pathReplacements=new Array(e.length+1)}static supports(e){return!BASE_UNSUPPORTED.test(e)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!BaseIRI.supports(this.base))return this._baseMatcher=/.^/;const e=/^[^:]*:\/*/.exec(this.base)[0],t=["^",escapeRegex$1(e)],r=[],i=[],s=/[^/?#]*([/?#])/y;let o,a=0,u=0,c=s.lastIndex=e.length;for(;!a&&!u&&(o=s.exec(this.base));)o[1]===FRAGMENT?u=s.lastIndex-1:(t.push(escapeRegex$1(o[0]),"(?:"),r.push(")?"),o[1]!==QUERY?i.push(c=s.lastIndex):(a=c=s.lastIndex,u=this.base.indexOf(FRAGMENT,a),this._pathReplacements[a]=QUERY));for(let l=0;l<i.length;l++)this._pathReplacements[i[l]]=PARENT.repeat(i.length-l-1);return this._pathReplacements[i[i.length-1]]=CURRENT,this._baseLength=u>0?u:this.base.length,t.push(escapeRegex$1(this.base.substring(c,this._baseLength)),a?"(?:#|$)":"(?:[?#]|$)"),this._baseMatcher=new RegExp([...t,...r].join(""))}toRelative(e){const t=this._getBaseMatcher().exec(e);if(!t)return e;const r=t[0].length;if(r===this._baseLength&&r===e.length)return"";const i=this._pathReplacements[r];if(i){const s=e.substring(r);return i!==QUERY&&!SUFFIX_SUPPORTED.test(s)?e:i===CURRENT&&/^[^?#]/.test(s)?s:i+s}return e.substring(r-1)}}const DEFAULTGRAPH=DataFactory.defaultGraph(),{rdf,xsd}=namespaces$1,escape$1=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,escapeAll=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,escapedCharacters={"\\":"\\\\",'"':'\\"'," ":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class SerializedTerm extends Term{equals(e){return e===this}}class N3Writer{constructor(e,t){if(this._prefixRegex=/$0^/,e&&typeof e.write!="function"&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=t.end===void 0?!0:!!t.end;else{let r="";this._outputStream={write(i,s,o){r+=i,o&&o()},end:i=>{i&&i(null,r)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine):(this._lineMode=!1,this._graph=DEFAULTGRAPH,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseIri=new BaseIRI(t.baseIRI)))}get _inDefaultGraph(){return DEFAULTGRAPH.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_writeQuad(e,t,r,i,s){try{i.equals(this._graph)||(this._write((this._subject===null?"":this._inDefaultGraph?`.
|
|
78
|
+
`:`
|
|
79
|
+
}
|
|
80
|
+
`)+(DEFAULTGRAPH.equals(i)?"":`${this._encodeIriOrBlank(i)} {
|
|
81
|
+
`)),this._graph=i,this._subject=null),e.equals(this._subject)?t.equals(this._predicate)?this._write(`, ${this._encodeObject(r)}`,s):this._write(`;
|
|
82
|
+
${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,s):this._write(`${(this._subject===null?"":`.
|
|
83
|
+
`)+this._encodeSubject(this._subject=e)} ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,s)}catch(o){s&&s(o)}}_writeQuadLine(e,t,r,i,s){delete this._prefixMatch,this._write(this.quadToString(e,t,r,i),s)}quadToString(e,t,r,i){return`${this._encodeSubject(e)} ${this._encodeIriOrBlank(t)} ${this._encodeObject(r)}${i&&i.value?` ${this._encodeIriOrBlank(i)} .
|
|
84
|
+
`:` .
|
|
85
|
+
`}`}quadsToString(e){let t="";for(const r of e)t+=this.quadToString(r.subject,r.predicate,r.object,r.graph);return t}_encodeSubject(e){return e.termType==="Quad"?this._encodeQuad(e):this._encodeIriOrBlank(e)}_encodeIriOrBlank(e){if(e.termType!=="NamedNode")return this._lists&&e.value in this._lists&&(e=this.list(this._lists[e.value])),"id"in e?e.id:`_:${e.value}`;let t=e.value;this._baseIri&&(t=this._baseIri.toRelative(t)),escape$1.test(t)&&(t=t.replace(escapeAll,characterReplacer));const r=this._prefixRegex.exec(t);return r?r[1]?this._prefixIRIs[r[1]]+r[2]:t:`<${t}>`}_encodeLiteral(e){let t=e.value;if(escape$1.test(t)&&(t=t.replace(escapeAll,characterReplacer)),e.language)return`"${t}"@${e.language}`;if(this._lineMode){if(e.datatype.value===xsd.string)return`"${t}"`}else switch(e.datatype.value){case xsd.string:return`"${t}"`;case xsd.boolean:if(t==="true"||t==="false")return t;break;case xsd.integer:if(/^[+-]?\d+$/.test(t))return t;break;case xsd.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case xsd.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t;break}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){return e.value===rdf.type?"a":this._encodeIriOrBlank(e)}_encodeObject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeQuad({subject:e,predicate:t,object:r,graph:i}){return`<<${this._encodeSubject(e)} ${this._encodePredicate(t)} ${this._encodeObject(r)}${isDefaultGraph(i)?"":` ${this._encodeIriOrBlank(i)}`}>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(e,t,r,i,s){r===void 0?this._writeQuad(e.subject,e.predicate,e.object,e.graph,t):typeof i=="function"?this._writeQuad(e,t,r,DEFAULTGRAPH,i):this._writeQuad(e,t,r,i||DEFAULTGRAPH,s)}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}addPrefix(e,t,r){const i={};i[e]=t,this.addPrefixes(i,r)}addPrefixes(e,t){if(!this._prefixIRIs)return t&&t();let r=!1;for(let i in e){let s=e[i];typeof s!="string"&&(s=s.value),r=!0,this._subject!==null&&(this._write(this._inDefaultGraph?`.
|
|
86
|
+
`:`
|
|
87
|
+
}
|
|
88
|
+
`),this._subject=null,this._graph=""),this._prefixIRIs[s]=i+=":",this._write(`@prefix ${i} <${s}>.
|
|
89
|
+
`)}if(r){let i="",s="";for(const o in this._prefixIRIs)i+=i?`|${o}`:o,s+=(s?"|":"")+this._prefixIRIs[o];i=escapeRegex$1(i),this._prefixRegex=new RegExp(`^(?:${s})[^/]*$|^(${i})([_a-zA-Z0-9][\\-_a-zA-Z0-9]*)$`)}this._write(r?`
|
|
90
|
+
`:"",t)}blank(e,t){let r=e,i,s;switch(e===void 0?r=[]:e.termType?r=[{predicate:e,object:t}]:"length"in e||(r=[e]),s=r.length){case 0:return new SerializedTerm("[]");case 1:if(i=r[0],!(i.object instanceof SerializedTerm))return new SerializedTerm(`[ ${this._encodePredicate(i.predicate)} ${this._encodeObject(i.object)} ]`);default:let o="[";for(let a=0;a<s;a++)i=r[a],i.predicate.equals(e)?o+=`, ${this._encodeObject(i.object)}`:(o+=`${(a?`;
|
|
91
|
+
`:`
|
|
92
|
+
`)+this._encodePredicate(i.predicate)} ${this._encodeObject(i.object)}`,e=i.predicate);return new SerializedTerm(`${o}
|
|
93
|
+
]`)}}list(e){const t=e&&e.length||0,r=new Array(t);for(let i=0;i<t;i++)r[i]=this._encodeObject(e[i]);return new SerializedTerm(`(${r.join(" ")})`)}end(e){this._subject!==null&&(this._write(this._inDefaultGraph?`.
|
|
94
|
+
`:`
|
|
95
|
+
}
|
|
96
|
+
`),this._subject=null),this._write=this._blockedWrite;let t=e&&((r,i)=>{t=null,e(r,i)});if(this._endStream)try{return this._outputStream.end(t)}catch{}t&&t()}}function characterReplacer(n){let e=escapedCharacters[n];return e===void 0&&(n.length===1?(e=n.charCodeAt(0).toString(16),e="\\u0000".substr(0,6-e.length)+e):(e=((n.charCodeAt(0)-55296)*1024+n.charCodeAt(1)+9216).toString(16),e="\\U00000000".substr(0,10-e.length)+e)),e}var browser={exports:{}},stream={exports:{}},primordials,hasRequiredPrimordials;function requirePrimordials(){if(hasRequiredPrimordials)return primordials;hasRequiredPrimordials=1;class n extends Error{constructor(t){if(!Array.isArray(t))throw new TypeError(`Expected input to be an Array, got ${typeof t}`);let r="";for(let i=0;i<t.length;i++)r+=` ${t[i].stack}
|
|
97
|
+
`;super(r),this.name="AggregateError",this.errors=t}}return primordials={AggregateError:n,ArrayIsArray(e){return Array.isArray(e)},ArrayPrototypeIncludes(e,t){return e.includes(t)},ArrayPrototypeIndexOf(e,t){return e.indexOf(t)},ArrayPrototypeJoin(e,t){return e.join(t)},ArrayPrototypeMap(e,t){return e.map(t)},ArrayPrototypePop(e,t){return e.pop(t)},ArrayPrototypePush(e,t){return e.push(t)},ArrayPrototypeSlice(e,t,r){return e.slice(t,r)},Error,FunctionPrototypeCall(e,t,...r){return e.call(t,...r)},FunctionPrototypeSymbolHasInstance(e,t){return Function.prototype[Symbol.hasInstance].call(e,t)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(e,t){return Object.defineProperties(e,t)},ObjectDefineProperty(e,t,r){return Object.defineProperty(e,t,r)},ObjectGetOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)},ObjectKeys(e){return Object.keys(e)},ObjectSetPrototypeOf(e,t){return Object.setPrototypeOf(e,t)},Promise,PromisePrototypeCatch(e,t){return e.catch(t)},PromisePrototypeThen(e,t,r){return e.then(t,r)},PromiseReject(e){return Promise.reject(e)},PromiseResolve(e){return Promise.resolve(e)},ReflectApply:Reflect.apply,RegExpPrototypeTest(e,t){return e.test(t)},SafeSet:Set,String,StringPrototypeSlice(e,t,r){return e.slice(t,r)},StringPrototypeToLowerCase(e){return e.toLowerCase()},StringPrototypeToUpperCase(e){return e.toUpperCase()},StringPrototypeTrim(e){return e.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(e,t,r){return e.set(t,r)},Boolean,Uint8Array},primordials}var util$1={exports:{}},inspect,hasRequiredInspect;function requireInspect(){return hasRequiredInspect||(hasRequiredInspect=1,inspect={format(n,...e){return n.replace(/%([sdifj])/g,function(...[t,r]){const i=e.shift();return r==="f"?i.toFixed(6):r==="j"?JSON.stringify(i):r==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(n){switch(typeof n){case"string":if(n.includes("'"))if(n.includes('"')){if(!n.includes("`")&&!n.includes("${"))return`\`${n}\``}else return`"${n}"`;return`'${n}'`;case"number":return isNaN(n)?"NaN":Object.is(n,-0)?String(n):n;case"bigint":return`${String(n)}n`;case"boolean":case"undefined":return String(n);case"object":return"{}"}}}),inspect}var errors,hasRequiredErrors;function requireErrors(){if(hasRequiredErrors)return errors;hasRequiredErrors=1;const{format:n,inspect:e}=requireInspect(),{AggregateError:t}=requirePrimordials(),r=globalThis.AggregateError||t,i=Symbol("kIsNodeError"),s=["string","function","number","object","Function","Object","boolean","bigint","symbol"],o=/^([A-Z][a-z0-9]*)+$/,a="__node_internal_",u={};function c(S,w){if(!S)throw new u.ERR_INTERNAL_ASSERTION(w)}function l(S){let w="",v=S.length;const _=S[0]==="-"?1:0;for(;v>=_+4;v-=3)w=`_${S.slice(v-3,v)}${w}`;return`${S.slice(0,v)}${w}`}function d(S,w,v){if(typeof w=="function")return c(w.length<=v.length,`Code: ${S}; The provided arguments length (${v.length}) does not match the required ones (${w.length}).`),w(...v);const _=(w.match(/%[dfijoOs]/g)||[]).length;return c(_===v.length,`Code: ${S}; The provided arguments length (${v.length}) does not match the required ones (${_}).`),v.length===0?w:n(w,...v)}function f(S,w,v){v||(v=Error);class _ extends v{constructor(...C){super(d(S,w,C))}toString(){return`${this.name} [${S}]: ${this.message}`}}Object.defineProperties(_.prototype,{name:{value:v.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${S}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),_.prototype.code=S,_.prototype[i]=!0,u[S]=_}function m(S){const w=a+S.name;return Object.defineProperty(S,"name",{value:w}),S}function g(S,w){if(S&&w&&S!==w){if(Array.isArray(w.errors))return w.errors.push(S),w;const v=new r([w,S],w.message);return v.code=w.code,v}return S||w}class b extends Error{constructor(w="The operation was aborted",v=void 0){if(v!==void 0&&typeof v!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",v);super(w,v),this.code="ABORT_ERR",this.name="AbortError"}}return f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(S,w,v)=>{c(typeof S=="string","'name' must be a string"),Array.isArray(w)||(w=[w]);let _="The ";S.endsWith(" argument")?_+=`${S} `:_+=`"${S}" ${S.includes(".")?"property":"argument"} `,_+="must be ";const T=[],C=[],U=[];for(const W of w)c(typeof W=="string","All expected entries have to be of type string"),s.includes(W)?T.push(W.toLowerCase()):o.test(W)?C.push(W):(c(W!=="object",'The value "object" should be written as "Object"'),U.push(W));if(C.length>0){const W=T.indexOf("object");W!==-1&&(T.splice(T,W,1),C.push("Object"))}if(T.length>0){switch(T.length){case 1:_+=`of type ${T[0]}`;break;case 2:_+=`one of type ${T[0]} or ${T[1]}`;break;default:{const W=T.pop();_+=`one of type ${T.join(", ")}, or ${W}`}}(C.length>0||U.length>0)&&(_+=" or ")}if(C.length>0){switch(C.length){case 1:_+=`an instance of ${C[0]}`;break;case 2:_+=`an instance of ${C[0]} or ${C[1]}`;break;default:{const W=C.pop();_+=`an instance of ${C.join(", ")}, or ${W}`}}U.length>0&&(_+=" or ")}switch(U.length){case 0:break;case 1:U[0].toLowerCase()!==U[0]&&(_+="an "),_+=`${U[0]}`;break;case 2:_+=`one of ${U[0]} or ${U[1]}`;break;default:{const W=U.pop();_+=`one of ${U.join(", ")}, or ${W}`}}if(v==null)_+=`. Received ${v}`;else if(typeof v=="function"&&v.name)_+=`. Received function ${v.name}`;else if(typeof v=="object"){var $;if(($=v.constructor)!==null&&$!==void 0&&$.name)_+=`. Received an instance of ${v.constructor.name}`;else{const W=e(v,{depth:-1});_+=`. Received ${W}`}}else{let W=e(v,{colors:!1});W.length>25&&(W=`${W.slice(0,25)}...`),_+=`. Received type ${typeof v} (${W})`}return _},TypeError),f("ERR_INVALID_ARG_VALUE",(S,w,v="is invalid")=>{let _=e(w);return _.length>128&&(_=_.slice(0,128)+"..."),`The ${S.includes(".")?"property":"argument"} '${S}' ${v}. Received ${_}`},TypeError),f("ERR_INVALID_RETURN_VALUE",(S,w,v)=>{var _;const T=v!=null&&(_=v.constructor)!==null&&_!==void 0&&_.name?`instance of ${v.constructor.name}`:`type ${typeof v}`;return`Expected ${S} to be returned from the "${w}" function but got ${T}.`},TypeError),f("ERR_MISSING_ARGS",(...S)=>{c(S.length>0,"At least one arg needs to be specified");let w;const v=S.length;switch(S=(Array.isArray(S)?S:[S]).map(_=>`"${_}"`).join(" or "),v){case 1:w+=`The ${S[0]} argument`;break;case 2:w+=`The ${S[0]} and ${S[1]} arguments`;break;default:{const _=S.pop();w+=`The ${S.join(", ")}, and ${_} arguments`}break}return`${w} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(S,w,v)=>{c(w,'Missing "range" argument');let _;if(Number.isInteger(v)&&Math.abs(v)>2**32)_=l(String(v));else if(typeof v=="bigint"){_=String(v);const T=BigInt(2)**BigInt(32);(v>T||v<-T)&&(_=l(_)),_+="n"}else _=e(v);return`The value of "${S}" is out of range. It must be ${w}. Received ${_}`},RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),errors={AbortError:b,aggregateTwoErrors:m(g),hideStackFrames:m,codes:u},errors}var hasRequiredUtil;function requireUtil(){return hasRequiredUtil||(hasRequiredUtil=1,(function(n){const e=requireBuffer(),{format:t,inspect:r}=requireInspect(),{codes:{ERR_INVALID_ARG_TYPE:i}}=requireErrors(),{kResistStopPropagation:s,AggregateError:o,SymbolDispose:a}=requirePrimordials(),u=globalThis.AbortSignal||requireBrowser$3().AbortSignal,c=globalThis.AbortController||requireBrowser$3().AbortController,l=Object.getPrototypeOf(async function(){}).constructor,d=globalThis.Blob||e.Blob,f=typeof d<"u"?function(S){return S instanceof d}:function(S){return!1},m=(b,S)=>{if(b!==void 0&&(b===null||typeof b!="object"||!("aborted"in b)))throw new i(S,"AbortSignal",b)},g=(b,S)=>{if(typeof b!="function")throw new i(S,"Function",b)};n.exports={AggregateError:o,kEmptyObject:Object.freeze({}),once(b){let S=!1;return function(...w){S||(S=!0,b.apply(this,w))}},createDeferredPromise:function(){let b,S;return{promise:new Promise((v,_)=>{b=v,S=_}),resolve:b,reject:S}},promisify(b){return new Promise((S,w)=>{b((v,..._)=>v?w(v):S(..._))})},debuglog(){return function(){}},format:t,inspect:r,types:{isAsyncFunction(b){return b instanceof l},isArrayBufferView(b){return ArrayBuffer.isView(b)}},isBlob:f,deprecate(b,S){return b},addAbortListener:requireEvents().addAbortListener||function(S,w){if(S===void 0)throw new i("signal","AbortSignal",S);m(S,"signal"),g(w,"listener");let v;return S.aborted?queueMicrotask(()=>w()):(S.addEventListener("abort",w,{__proto__:null,once:!0,[s]:!0}),v=()=>{S.removeEventListener("abort",w)}),{__proto__:null,[a](){var _;(_=v)===null||_===void 0||_()}}},AbortSignalAny:u.any||function(S){if(S.length===1)return S[0];const w=new c,v=()=>w.abort();return S.forEach(_=>{m(_,"signals"),_.addEventListener("abort",v,{once:!0})}),w.signal.addEventListener("abort",()=>{S.forEach(_=>_.removeEventListener("abort",v))},{once:!0}),w.signal}},n.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")})(util$1)),util$1.exports}var operators={},validators,hasRequiredValidators;function requireValidators(){if(hasRequiredValidators)return validators;hasRequiredValidators=1;const{ArrayIsArray:n,ArrayPrototypeIncludes:e,ArrayPrototypeJoin:t,ArrayPrototypeMap:r,NumberIsInteger:i,NumberIsNaN:s,NumberMAX_SAFE_INTEGER:o,NumberMIN_SAFE_INTEGER:a,NumberParseInt:u,ObjectPrototypeHasOwnProperty:c,RegExpPrototypeExec:l,String:d,StringPrototypeToUpperCase:f,StringPrototypeTrim:m}=requirePrimordials(),{hideStackFrames:g,codes:{ERR_SOCKET_BAD_PORT:b,ERR_INVALID_ARG_TYPE:S,ERR_INVALID_ARG_VALUE:w,ERR_OUT_OF_RANGE:v,ERR_UNKNOWN_SIGNAL:_}}=requireErrors(),{normalizeEncoding:T}=requireUtil(),{isAsyncFunction:C,isArrayBufferView:U}=requireUtil().types,$={};function W(M){return M===(M|0)}function re(M){return M===M>>>0}const D=/^[0-7]+$/,V="must be a 32-bit unsigned integer or an octal string";function he(M,ne,ge){if(typeof M>"u"&&(M=ge),typeof M=="string"){if(l(D,M)===null)throw new w(ne,M,V);M=u(M,8)}return Ce(M,ne),M}const z=g((M,ne,ge=a,Y=o)=>{if(typeof M!="number")throw new S(ne,"number",M);if(!i(M))throw new v(ne,"an integer",M);if(M<ge||M>Y)throw new v(ne,`>= ${ge} && <= ${Y}`,M)}),_e=g((M,ne,ge=-2147483648,Y=2147483647)=>{if(typeof M!="number")throw new S(ne,"number",M);if(!i(M))throw new v(ne,"an integer",M);if(M<ge||M>Y)throw new v(ne,`>= ${ge} && <= ${Y}`,M)}),Ce=g((M,ne,ge=!1)=>{if(typeof M!="number")throw new S(ne,"number",M);if(!i(M))throw new v(ne,"an integer",M);const Y=ge?1:0,Be=4294967295;if(M<Y||M>Be)throw new v(ne,`>= ${Y} && <= ${Be}`,M)});function Fe(M,ne){if(typeof M!="string")throw new S(ne,"string",M)}function ze(M,ne,ge=void 0,Y){if(typeof M!="number")throw new S(ne,"number",M);if(ge!=null&&M<ge||Y!=null&&M>Y||(ge!=null||Y!=null)&&s(M))throw new v(ne,`${ge!=null?`>= ${ge}`:""}${ge!=null&&Y!=null?" && ":""}${Y!=null?`<= ${Y}`:""}`,M)}const ae=g((M,ne,ge)=>{if(!e(ge,M)){const Be="must be one of: "+t(r(ge,Je=>typeof Je=="string"?`'${Je}'`:d(Je)),", ");throw new w(ne,M,Be)}});function ve(M,ne){if(typeof M!="boolean")throw new S(ne,"boolean",M)}function L(M,ne,ge){return M==null||!c(M,ne)?ge:M[ne]}const ie=g((M,ne,ge=null)=>{const Y=L(ge,"allowArray",!1),Be=L(ge,"allowFunction",!1);if(!L(ge,"nullable",!1)&&M===null||!Y&&n(M)||typeof M!="object"&&(!Be||typeof M!="function"))throw new S(ne,"Object",M)}),xe=g((M,ne)=>{if(M!=null&&typeof M!="object"&&typeof M!="function")throw new S(ne,"a dictionary",M)}),ue=g((M,ne,ge=0)=>{if(!n(M))throw new S(ne,"Array",M);if(M.length<ge){const Y=`must be longer than ${ge}`;throw new w(ne,M,Y)}});function De(M,ne){ue(M,ne);for(let ge=0;ge<M.length;ge++)Fe(M[ge],`${ne}[${ge}]`)}function ke(M,ne){ue(M,ne);for(let ge=0;ge<M.length;ge++)ve(M[ge],`${ne}[${ge}]`)}function We(M,ne){ue(M,ne);for(let ge=0;ge<M.length;ge++){const Y=M[ge],Be=`${ne}[${ge}]`;if(Y==null)throw new S(Be,"AbortSignal",Y);G(Y,Be)}}function Oe(M,ne="signal"){if(Fe(M,ne),$[M]===void 0)throw $[f(M)]!==void 0?new _(M+" (signals must use all capital letters)"):new _(M)}const te=g((M,ne="buffer")=>{if(!U(M))throw new S(ne,["Buffer","TypedArray","DataView"],M)});function le(M,ne){const ge=T(ne),Y=M.length;if(ge==="hex"&&Y%2!==0)throw new w("encoding",ne,`is invalid for data of length ${Y}`)}function Te(M,ne="Port",ge=!0){if(typeof M!="number"&&typeof M!="string"||typeof M=="string"&&m(M).length===0||+M!==+M>>>0||M>65535||M===0&&!ge)throw new b(ne,M,ge);return M|0}const G=g((M,ne)=>{if(M!==void 0&&(M===null||typeof M!="object"||!("aborted"in M)))throw new S(ne,"AbortSignal",M)}),P=g((M,ne)=>{if(typeof M!="function")throw new S(ne,"Function",M)}),x=g((M,ne)=>{if(typeof M!="function"||C(M))throw new S(ne,"Function",M)}),A=g((M,ne)=>{if(M!==void 0)throw new S(ne,"undefined",M)});function O(M,ne,ge){if(!e(ge,M))throw new S(ne,`('${t(ge,"|")}')`,M)}const H=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function Q(M,ne){if(typeof M>"u"||!l(H,M))throw new w(ne,M,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function de(M){if(typeof M=="string")return Q(M,"hints"),M;if(n(M)){const ne=M.length;let ge="";if(ne===0)return ge;for(let Y=0;Y<ne;Y++){const Be=M[Y];Q(Be,"hints"),ge+=Be,Y!==ne-1&&(ge+=", ")}return ge}throw new w("hints",M,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}return validators={isInt32:W,isUint32:re,parseFileMode:he,validateArray:ue,validateStringArray:De,validateBooleanArray:ke,validateAbortSignalArray:We,validateBoolean:ve,validateBuffer:te,validateDictionary:xe,validateEncoding:le,validateFunction:P,validateInt32:_e,validateInteger:z,validateNumber:ze,validateObject:ie,validateOneOf:ae,validatePlainFunction:x,validatePort:Te,validateSignalName:Oe,validateString:Fe,validateUint32:Ce,validateUndefined:A,validateUnion:O,validateAbortSignal:G,validateLinkHeaderValue:de},validators}var endOfStream={exports:{}},utils,hasRequiredUtils;function requireUtils(){if(hasRequiredUtils)return utils;hasRequiredUtils=1;const{SymbolAsyncIterator:n,SymbolIterator:e,SymbolFor:t}=requirePrimordials(),r=t("nodejs.stream.destroyed"),i=t("nodejs.stream.errored"),s=t("nodejs.stream.readable"),o=t("nodejs.stream.writable"),a=t("nodejs.stream.disturbed"),u=t("nodejs.webstream.isClosedPromise"),c=t("nodejs.webstream.controllerErrorFunction");function l(L,ie=!1){var xe;return!!(L&&typeof L.pipe=="function"&&typeof L.on=="function"&&(!ie||typeof L.pause=="function"&&typeof L.resume=="function")&&(!L._writableState||((xe=L._readableState)===null||xe===void 0?void 0:xe.readable)!==!1)&&(!L._writableState||L._readableState))}function d(L){var ie;return!!(L&&typeof L.write=="function"&&typeof L.on=="function"&&(!L._readableState||((ie=L._writableState)===null||ie===void 0?void 0:ie.writable)!==!1))}function f(L){return!!(L&&typeof L.pipe=="function"&&L._readableState&&typeof L.on=="function"&&typeof L.write=="function")}function m(L){return L&&(L._readableState||L._writableState||typeof L.write=="function"&&typeof L.on=="function"||typeof L.pipe=="function"&&typeof L.on=="function")}function g(L){return!!(L&&!m(L)&&typeof L.pipeThrough=="function"&&typeof L.getReader=="function"&&typeof L.cancel=="function")}function b(L){return!!(L&&!m(L)&&typeof L.getWriter=="function"&&typeof L.abort=="function")}function S(L){return!!(L&&!m(L)&&typeof L.readable=="object"&&typeof L.writable=="object")}function w(L){return g(L)||b(L)||S(L)}function v(L,ie){return L==null?!1:ie===!0?typeof L[n]=="function":ie===!1?typeof L[e]=="function":typeof L[n]=="function"||typeof L[e]=="function"}function _(L){if(!m(L))return null;const ie=L._writableState,xe=L._readableState,ue=ie||xe;return!!(L.destroyed||L[r]||ue!=null&&ue.destroyed)}function T(L){if(!d(L))return null;if(L.writableEnded===!0)return!0;const ie=L._writableState;return ie!=null&&ie.errored?!1:typeof ie?.ended!="boolean"?null:ie.ended}function C(L,ie){if(!d(L))return null;if(L.writableFinished===!0)return!0;const xe=L._writableState;return xe!=null&&xe.errored?!1:typeof xe?.finished!="boolean"?null:!!(xe.finished||ie===!1&&xe.ended===!0&&xe.length===0)}function U(L){if(!l(L))return null;if(L.readableEnded===!0)return!0;const ie=L._readableState;return!ie||ie.errored?!1:typeof ie?.ended!="boolean"?null:ie.ended}function $(L,ie){if(!l(L))return null;const xe=L._readableState;return xe!=null&&xe.errored?!1:typeof xe?.endEmitted!="boolean"?null:!!(xe.endEmitted||ie===!1&&xe.ended===!0&&xe.length===0)}function W(L){return L&&L[s]!=null?L[s]:typeof L?.readable!="boolean"?null:_(L)?!1:l(L)&&L.readable&&!$(L)}function re(L){return L&&L[o]!=null?L[o]:typeof L?.writable!="boolean"?null:_(L)?!1:d(L)&&L.writable&&!T(L)}function D(L,ie){return m(L)?_(L)?!0:!(ie?.readable!==!1&&W(L)||ie?.writable!==!1&&re(L)):null}function V(L){var ie,xe;return m(L)?L.writableErrored?L.writableErrored:(ie=(xe=L._writableState)===null||xe===void 0?void 0:xe.errored)!==null&&ie!==void 0?ie:null:null}function he(L){var ie,xe;return m(L)?L.readableErrored?L.readableErrored:(ie=(xe=L._readableState)===null||xe===void 0?void 0:xe.errored)!==null&&ie!==void 0?ie:null:null}function z(L){if(!m(L))return null;if(typeof L.closed=="boolean")return L.closed;const ie=L._writableState,xe=L._readableState;return typeof ie?.closed=="boolean"||typeof xe?.closed=="boolean"?ie?.closed||xe?.closed:typeof L._closed=="boolean"&&_e(L)?L._closed:null}function _e(L){return typeof L._closed=="boolean"&&typeof L._defaultKeepAlive=="boolean"&&typeof L._removedConnection=="boolean"&&typeof L._removedContLen=="boolean"}function Ce(L){return typeof L._sent100=="boolean"&&_e(L)}function Fe(L){var ie;return typeof L._consuming=="boolean"&&typeof L._dumped=="boolean"&&((ie=L.req)===null||ie===void 0?void 0:ie.upgradeOrConnect)===void 0}function ze(L){if(!m(L))return null;const ie=L._writableState,xe=L._readableState,ue=ie||xe;return!ue&&Ce(L)||!!(ue&&ue.autoDestroy&&ue.emitClose&&ue.closed===!1)}function ae(L){var ie;return!!(L&&((ie=L[a])!==null&&ie!==void 0?ie:L.readableDidRead||L.readableAborted))}function ve(L){var ie,xe,ue,De,ke,We,Oe,te,le,Te;return!!(L&&((ie=(xe=(ue=(De=(ke=(We=L[i])!==null&&We!==void 0?We:L.readableErrored)!==null&&ke!==void 0?ke:L.writableErrored)!==null&&De!==void 0?De:(Oe=L._readableState)===null||Oe===void 0?void 0:Oe.errorEmitted)!==null&&ue!==void 0?ue:(te=L._writableState)===null||te===void 0?void 0:te.errorEmitted)!==null&&xe!==void 0?xe:(le=L._readableState)===null||le===void 0?void 0:le.errored)!==null&&ie!==void 0?ie:!((Te=L._writableState)===null||Te===void 0)&&Te.errored))}return utils={isDestroyed:_,kIsDestroyed:r,isDisturbed:ae,kIsDisturbed:a,isErrored:ve,kIsErrored:i,isReadable:W,kIsReadable:s,kIsClosedPromise:u,kControllerErrorFunction:c,kIsWritable:o,isClosed:z,isDuplexNodeStream:f,isFinished:D,isIterable:v,isReadableNodeStream:l,isReadableStream:g,isReadableEnded:U,isReadableFinished:$,isReadableErrored:he,isNodeStream:m,isWebStream:w,isWritable:re,isWritableNodeStream:d,isWritableStream:b,isWritableEnded:T,isWritableFinished:C,isWritableErrored:V,isServerRequest:Fe,isServerResponse:Ce,willEmitClose:ze,isTransformStream:S},utils}var hasRequiredEndOfStream;function requireEndOfStream(){if(hasRequiredEndOfStream)return endOfStream.exports;hasRequiredEndOfStream=1;const n=requireBrowser$2(),{AbortError:e,codes:t}=requireErrors(),{ERR_INVALID_ARG_TYPE:r,ERR_STREAM_PREMATURE_CLOSE:i}=t,{kEmptyObject:s,once:o}=requireUtil(),{validateAbortSignal:a,validateFunction:u,validateObject:c,validateBoolean:l}=requireValidators(),{Promise:d,PromisePrototypeThen:f,SymbolDispose:m}=requirePrimordials(),{isClosed:g,isReadable:b,isReadableNodeStream:S,isReadableStream:w,isReadableFinished:v,isReadableErrored:_,isWritable:T,isWritableNodeStream:C,isWritableStream:U,isWritableFinished:$,isWritableErrored:W,isNodeStream:re,willEmitClose:D,kIsClosedPromise:V}=requireUtils();let he;function z(ae){return ae.setHeader&&typeof ae.abort=="function"}const _e=()=>{};function Ce(ae,ve,L){var ie,xe;if(arguments.length===2?(L=ve,ve=s):ve==null?ve=s:c(ve,"options"),u(L,"callback"),a(ve.signal,"options.signal"),L=o(L),w(ae)||U(ae))return Fe(ae,ve,L);if(!re(ae))throw new r("stream",["ReadableStream","WritableStream","Stream"],ae);const ue=(ie=ve.readable)!==null&&ie!==void 0?ie:S(ae),De=(xe=ve.writable)!==null&&xe!==void 0?xe:C(ae),ke=ae._writableState,We=ae._readableState,Oe=()=>{ae.writable||Te()};let te=D(ae)&&S(ae)===ue&&C(ae)===De,le=$(ae,!1);const Te=()=>{le=!0,ae.destroyed&&(te=!1),!(te&&(!ae.readable||ue))&&(!ue||G)&&L.call(ae)};let G=v(ae,!1);const P=()=>{G=!0,ae.destroyed&&(te=!1),!(te&&(!ae.writable||De))&&(!De||le)&&L.call(ae)},x=M=>{L.call(ae,M)};let A=g(ae);const O=()=>{A=!0;const M=W(ae)||_(ae);if(M&&typeof M!="boolean")return L.call(ae,M);if(ue&&!G&&S(ae,!0)&&!v(ae,!1))return L.call(ae,new i);if(De&&!le&&!$(ae,!1))return L.call(ae,new i);L.call(ae)},H=()=>{A=!0;const M=W(ae)||_(ae);if(M&&typeof M!="boolean")return L.call(ae,M);L.call(ae)},Q=()=>{ae.req.on("finish",Te)};z(ae)?(ae.on("complete",Te),te||ae.on("abort",O),ae.req?Q():ae.on("request",Q)):De&&!ke&&(ae.on("end",Oe),ae.on("close",Oe)),!te&&typeof ae.aborted=="boolean"&&ae.on("aborted",O),ae.on("end",P),ae.on("finish",Te),ve.error!==!1&&ae.on("error",x),ae.on("close",O),A?n.nextTick(O):ke!=null&&ke.errorEmitted||We!=null&&We.errorEmitted?te||n.nextTick(H):(!ue&&(!te||b(ae))&&(le||T(ae)===!1)||!De&&(!te||T(ae))&&(G||b(ae)===!1)||We&&ae.req&&ae.aborted)&&n.nextTick(H);const de=()=>{L=_e,ae.removeListener("aborted",O),ae.removeListener("complete",Te),ae.removeListener("abort",O),ae.removeListener("request",Q),ae.req&&ae.req.removeListener("finish",Te),ae.removeListener("end",Oe),ae.removeListener("close",Oe),ae.removeListener("finish",Te),ae.removeListener("end",P),ae.removeListener("error",x),ae.removeListener("close",O)};if(ve.signal&&!A){const M=()=>{const ne=L;de(),ne.call(ae,new e(void 0,{cause:ve.signal.reason}))};if(ve.signal.aborted)n.nextTick(M);else{he=he||requireUtil().addAbortListener;const ne=he(ve.signal,M),ge=L;L=o((...Y)=>{ne[m](),ge.apply(ae,Y)})}}return de}function Fe(ae,ve,L){let ie=!1,xe=_e;if(ve.signal)if(xe=()=>{ie=!0,L.call(ae,new e(void 0,{cause:ve.signal.reason}))},ve.signal.aborted)n.nextTick(xe);else{he=he||requireUtil().addAbortListener;const De=he(ve.signal,xe),ke=L;L=o((...We)=>{De[m](),ke.apply(ae,We)})}const ue=(...De)=>{ie||n.nextTick(()=>L.apply(ae,De))};return f(ae[V].promise,ue,ue),_e}function ze(ae,ve){var L;let ie=!1;return ve===null&&(ve=s),(L=ve)!==null&&L!==void 0&&L.cleanup&&(l(ve.cleanup,"cleanup"),ie=ve.cleanup),new d((xe,ue)=>{const De=Ce(ae,ve,ke=>{ie&&De(),ke?ue(ke):xe()})})}return endOfStream.exports=Ce,endOfStream.exports.finished=ze,endOfStream.exports}var destroy_1,hasRequiredDestroy;function requireDestroy(){if(hasRequiredDestroy)return destroy_1;hasRequiredDestroy=1;const n=requireBrowser$2(),{aggregateTwoErrors:e,codes:{ERR_MULTIPLE_CALLBACK:t},AbortError:r}=requireErrors(),{Symbol:i}=requirePrimordials(),{kIsDestroyed:s,isDestroyed:o,isFinished:a,isServerRequest:u}=requireUtils(),c=i("kDestroy"),l=i("kConstruct");function d(D,V,he){D&&(D.stack,V&&!V.errored&&(V.errored=D),he&&!he.errored&&(he.errored=D))}function f(D,V){const he=this._readableState,z=this._writableState,_e=z||he;return z!=null&&z.destroyed||he!=null&&he.destroyed?(typeof V=="function"&&V(),this):(d(D,z,he),z&&(z.destroyed=!0),he&&(he.destroyed=!0),_e.constructed?m(this,D,V):this.once(c,function(Ce){m(this,e(Ce,D),V)}),this)}function m(D,V,he){let z=!1;function _e(Ce){if(z)return;z=!0;const Fe=D._readableState,ze=D._writableState;d(Ce,ze,Fe),ze&&(ze.closed=!0),Fe&&(Fe.closed=!0),typeof he=="function"&&he(Ce),Ce?n.nextTick(g,D,Ce):n.nextTick(b,D)}try{D._destroy(V||null,_e)}catch(Ce){_e(Ce)}}function g(D,V){S(D,V),b(D)}function b(D){const V=D._readableState,he=D._writableState;he&&(he.closeEmitted=!0),V&&(V.closeEmitted=!0),(he!=null&&he.emitClose||V!=null&&V.emitClose)&&D.emit("close")}function S(D,V){const he=D._readableState,z=D._writableState;z!=null&&z.errorEmitted||he!=null&&he.errorEmitted||(z&&(z.errorEmitted=!0),he&&(he.errorEmitted=!0),D.emit("error",V))}function w(){const D=this._readableState,V=this._writableState;D&&(D.constructed=!0,D.closed=!1,D.closeEmitted=!1,D.destroyed=!1,D.errored=null,D.errorEmitted=!1,D.reading=!1,D.ended=D.readable===!1,D.endEmitted=D.readable===!1),V&&(V.constructed=!0,V.destroyed=!1,V.closed=!1,V.closeEmitted=!1,V.errored=null,V.errorEmitted=!1,V.finalCalled=!1,V.prefinished=!1,V.ended=V.writable===!1,V.ending=V.writable===!1,V.finished=V.writable===!1)}function v(D,V,he){const z=D._readableState,_e=D._writableState;if(_e!=null&&_e.destroyed||z!=null&&z.destroyed)return this;z!=null&&z.autoDestroy||_e!=null&&_e.autoDestroy?D.destroy(V):V&&(V.stack,_e&&!_e.errored&&(_e.errored=V),z&&!z.errored&&(z.errored=V),he?n.nextTick(S,D,V):S(D,V))}function _(D,V){if(typeof D._construct!="function")return;const he=D._readableState,z=D._writableState;he&&(he.constructed=!1),z&&(z.constructed=!1),D.once(l,V),!(D.listenerCount(l)>1)&&n.nextTick(T,D)}function T(D){let V=!1;function he(z){if(V){v(D,z??new t);return}V=!0;const _e=D._readableState,Ce=D._writableState,Fe=Ce||_e;_e&&(_e.constructed=!0),Ce&&(Ce.constructed=!0),Fe.destroyed?D.emit(c,z):z?v(D,z,!0):n.nextTick(C,D)}try{D._construct(z=>{n.nextTick(he,z)})}catch(z){n.nextTick(he,z)}}function C(D){D.emit(l)}function U(D){return D?.setHeader&&typeof D.abort=="function"}function $(D){D.emit("close")}function W(D,V){D.emit("error",V),n.nextTick($,D)}function re(D,V){!D||o(D)||(!V&&!a(D)&&(V=new r),u(D)?(D.socket=null,D.destroy(V)):U(D)?D.abort():U(D.req)?D.req.abort():typeof D.destroy=="function"?D.destroy(V):typeof D.close=="function"?D.close():V?n.nextTick(W,D,V):n.nextTick($,D),D.destroyed||(D[s]=!0))}return destroy_1={construct:_,destroyer:re,destroy:f,undestroy:w,errorOrDestroy:v},destroy_1}var legacy,hasRequiredLegacy;function requireLegacy(){if(hasRequiredLegacy)return legacy;hasRequiredLegacy=1;const{ArrayIsArray:n,ObjectSetPrototypeOf:e}=requirePrimordials(),{EventEmitter:t}=requireEvents();function r(s){t.call(this,s)}e(r.prototype,t.prototype),e(r,t),r.prototype.pipe=function(s,o){const a=this;function u(b){s.writable&&s.write(b)===!1&&a.pause&&a.pause()}a.on("data",u);function c(){a.readable&&a.resume&&a.resume()}s.on("drain",c),!s._isStdio&&(!o||o.end!==!1)&&(a.on("end",d),a.on("close",f));let l=!1;function d(){l||(l=!0,s.end())}function f(){l||(l=!0,typeof s.destroy=="function"&&s.destroy())}function m(b){g(),t.listenerCount(this,"error")===0&&this.emit("error",b)}i(a,"error",m),i(s,"error",m);function g(){a.removeListener("data",u),s.removeListener("drain",c),a.removeListener("end",d),a.removeListener("close",f),a.removeListener("error",m),s.removeListener("error",m),a.removeListener("end",g),a.removeListener("close",g),s.removeListener("close",g)}return a.on("end",g),a.on("close",g),s.on("close",g),s.emit("pipe",a),s};function i(s,o,a){if(typeof s.prependListener=="function")return s.prependListener(o,a);!s._events||!s._events[o]?s.on(o,a):n(s._events[o])?s._events[o].unshift(a):s._events[o]=[a,s._events[o]]}return legacy={Stream:r,prependListener:i},legacy}var addAbortSignal={exports:{}},hasRequiredAddAbortSignal;function requireAddAbortSignal(){return hasRequiredAddAbortSignal||(hasRequiredAddAbortSignal=1,(function(n){const{SymbolDispose:e}=requirePrimordials(),{AbortError:t,codes:r}=requireErrors(),{isNodeStream:i,isWebStream:s,kControllerErrorFunction:o}=requireUtils(),a=requireEndOfStream(),{ERR_INVALID_ARG_TYPE:u}=r;let c;const l=(d,f)=>{if(typeof d!="object"||!("aborted"in d))throw new u(f,"AbortSignal",d)};n.exports.addAbortSignal=function(f,m){if(l(f,"signal"),!i(m)&&!s(m))throw new u("stream",["ReadableStream","WritableStream","Stream"],m);return n.exports.addAbortSignalNoValidate(f,m)},n.exports.addAbortSignalNoValidate=function(d,f){if(typeof d!="object"||!("aborted"in d))return f;const m=i(f)?()=>{f.destroy(new t(void 0,{cause:d.reason}))}:()=>{f[o](new t(void 0,{cause:d.reason}))};if(d.aborted)m();else{c=c||requireUtil().addAbortListener;const g=c(d,m);a(f,g[e])}return f}})(addAbortSignal)),addAbortSignal.exports}var buffer_list,hasRequiredBuffer_list;function requireBuffer_list(){if(hasRequiredBuffer_list)return buffer_list;hasRequiredBuffer_list=1;const{StringPrototypeSlice:n,SymbolIterator:e,TypedArrayPrototypeSet:t,Uint8Array:r}=requirePrimordials(),{Buffer:i}=requireBuffer(),{inspect:s}=requireUtil();return buffer_list=class{constructor(){this.head=null,this.tail=null,this.length=0}push(a){const u={data:a,next:null};this.length>0?this.tail.next=u:this.head=u,this.tail=u,++this.length}unshift(a){const u={data:a,next:this.head};this.length===0&&(this.tail=u),this.head=u,++this.length}shift(){if(this.length===0)return;const a=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,a}clear(){this.head=this.tail=null,this.length=0}join(a){if(this.length===0)return"";let u=this.head,c=""+u.data;for(;(u=u.next)!==null;)c+=a+u.data;return c}concat(a){if(this.length===0)return i.alloc(0);const u=i.allocUnsafe(a>>>0);let c=this.head,l=0;for(;c;)t(u,c.data,l),l+=c.data.length,c=c.next;return u}consume(a,u){const c=this.head.data;if(a<c.length){const l=c.slice(0,a);return this.head.data=c.slice(a),l}return a===c.length?this.shift():u?this._getString(a):this._getBuffer(a)}first(){return this.head.data}*[e](){for(let a=this.head;a;a=a.next)yield a.data}_getString(a){let u="",c=this.head,l=0;do{const d=c.data;if(a>d.length)u+=d,a-=d.length;else{a===d.length?(u+=d,++l,c.next?this.head=c.next:this.head=this.tail=null):(u+=n(d,0,a),this.head=c,c.data=n(d,a));break}++l}while((c=c.next)!==null);return this.length-=l,u}_getBuffer(a){const u=i.allocUnsafe(a),c=a;let l=this.head,d=0;do{const f=l.data;if(a>f.length)t(u,f,c-a),a-=f.length;else{a===f.length?(t(u,f,c-a),++d,l.next?this.head=l.next:this.head=this.tail=null):(t(u,new r(f.buffer,f.byteOffset,a),c-a),this.head=l,l.data=f.slice(a));break}++d}while((l=l.next)!==null);return this.length-=d,u}[Symbol.for("nodejs.util.inspect.custom")](a,u){return s(this,{...u,depth:0,customInspect:!1})}},buffer_list}var state,hasRequiredState;function requireState(){if(hasRequiredState)return state;hasRequiredState=1;const{MathFloor:n,NumberIsInteger:e}=requirePrimordials(),{validateInteger:t}=requireValidators(),{ERR_INVALID_ARG_VALUE:r}=requireErrors().codes;let i=16*1024,s=16;function o(l,d,f){return l.highWaterMark!=null?l.highWaterMark:d?l[f]:null}function a(l){return l?s:i}function u(l,d){t(d,"value",0),l?s=d:i=d}function c(l,d,f,m){const g=o(d,m,f);if(g!=null){if(!e(g)||g<0){const b=m?`options.${f}`:"options.highWaterMark";throw new r(b,g)}return n(g)}return a(l.objectMode)}return state={getHighWaterMark:c,getDefaultHighWaterMark:a,setDefaultHighWaterMark:u},state}var from_1,hasRequiredFrom;function requireFrom(){if(hasRequiredFrom)return from_1;hasRequiredFrom=1;const n=requireBrowser$2(),{PromisePrototypeThen:e,SymbolAsyncIterator:t,SymbolIterator:r}=requirePrimordials(),{Buffer:i}=requireBuffer(),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_NULL_VALUES:o}=requireErrors().codes;function a(u,c,l){let d;if(typeof c=="string"||c instanceof i)return new u({objectMode:!0,...l,read(){this.push(c),this.push(null)}});let f;if(c&&c[t])f=!0,d=c[t]();else if(c&&c[r])f=!1,d=c[r]();else throw new s("iterable",["Iterable"],c);const m=new u({objectMode:!0,highWaterMark:1,...l});let g=!1;m._read=function(){g||(g=!0,S())},m._destroy=function(w,v){e(b(w),()=>n.nextTick(v,w),_=>n.nextTick(v,_||w))};async function b(w){const v=w!=null,_=typeof d.throw=="function";if(v&&_){const{value:T,done:C}=await d.throw(w);if(await T,C)return}if(typeof d.return=="function"){const{value:T}=await d.return();await T}}async function S(){for(;;){try{const{value:w,done:v}=f?await d.next():d.next();if(v)m.push(null);else{const _=w&&typeof w.then=="function"?await w:w;if(_===null)throw g=!1,new o;if(m.push(_))continue;g=!1}}catch(w){m.destroy(w)}break}}return m}return from_1=a,from_1}var readable,hasRequiredReadable;function requireReadable(){if(hasRequiredReadable)return readable;hasRequiredReadable=1;const n=requireBrowser$2(),{ArrayPrototypeIndexOf:e,NumberIsInteger:t,NumberIsNaN:r,NumberParseInt:i,ObjectDefineProperties:s,ObjectKeys:o,ObjectSetPrototypeOf:a,Promise:u,SafeSet:c,SymbolAsyncDispose:l,SymbolAsyncIterator:d,Symbol:f}=requirePrimordials();readable=Y,Y.ReadableState=ge;const{EventEmitter:m}=requireEvents(),{Stream:g,prependListener:b}=requireLegacy(),{Buffer:S}=requireBuffer(),{addAbortSignal:w}=requireAddAbortSignal(),v=requireEndOfStream();let _=requireUtil().debuglog("stream",k=>{_=k});const T=requireBuffer_list(),C=requireDestroy(),{getHighWaterMark:U,getDefaultHighWaterMark:$}=requireState(),{aggregateTwoErrors:W,codes:{ERR_INVALID_ARG_TYPE:re,ERR_METHOD_NOT_IMPLEMENTED:D,ERR_OUT_OF_RANGE:V,ERR_STREAM_PUSH_AFTER_EOF:he,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:z},AbortError:_e}=requireErrors(),{validateObject:Ce}=requireValidators(),Fe=f("kPaused"),{StringDecoder:ze}=requireString_decoder(),ae=requireFrom();a(Y.prototype,g.prototype),a(Y,g);const ve=()=>{},{errorOrDestroy:L}=C,ie=1,xe=2,ue=4,De=8,ke=16,We=32,Oe=64,te=128,le=256,Te=512,G=1024,P=2048,x=4096,A=8192,O=16384,H=32768,Q=65536,de=1<<17,M=1<<18;function ne(k){return{enumerable:!1,get(){return(this.state&k)!==0},set(j){j?this.state|=k:this.state&=~k}}}s(ge.prototype,{objectMode:ne(ie),ended:ne(xe),endEmitted:ne(ue),reading:ne(De),constructed:ne(ke),sync:ne(We),needReadable:ne(Oe),emittedReadable:ne(te),readableListening:ne(le),resumeScheduled:ne(Te),errorEmitted:ne(G),emitClose:ne(P),autoDestroy:ne(x),destroyed:ne(A),closed:ne(O),closeEmitted:ne(H),multiAwaitDrain:ne(Q),readingMore:ne(de),dataEmitted:ne(M)});function ge(k,j,Ie){typeof Ie!="boolean"&&(Ie=j instanceof requireDuplex()),this.state=P|x|ke|We,k&&k.objectMode&&(this.state|=ie),Ie&&k&&k.readableObjectMode&&(this.state|=ie),this.highWaterMark=k?U(this,k,"readableHighWaterMark",Ie):$(!1),this.buffer=new T,this.length=0,this.pipes=[],this.flowing=null,this[Fe]=null,k&&k.emitClose===!1&&(this.state&=~P),k&&k.autoDestroy===!1&&(this.state&=~x),this.errored=null,this.defaultEncoding=k&&k.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,k&&k.encoding&&(this.decoder=new ze(k.encoding),this.encoding=k.encoding)}function Y(k){if(!(this instanceof Y))return new Y(k);const j=this instanceof requireDuplex();this._readableState=new ge(k,this,j),k&&(typeof k.read=="function"&&(this._read=k.read),typeof k.destroy=="function"&&(this._destroy=k.destroy),typeof k.construct=="function"&&(this._construct=k.construct),k.signal&&!j&&w(k.signal,this)),g.call(this,k),C.construct(this,()=>{this._readableState.needReadable&&me(this,this._readableState)})}Y.prototype.destroy=C.destroy,Y.prototype._undestroy=C.undestroy,Y.prototype._destroy=function(k,j){j(k)},Y.prototype[m.captureRejectionSymbol]=function(k){this.destroy(k)},Y.prototype[l]=function(){let k;return this.destroyed||(k=this.readableEnded?null:new _e,this.destroy(k)),new u((j,Ie)=>v(this,Ae=>Ae&&Ae!==k?Ie(Ae):j(null)))},Y.prototype.push=function(k,j){return Be(this,k,j,!1)},Y.prototype.unshift=function(k,j){return Be(this,k,j,!0)};function Be(k,j,Ie,Ae){_("readableAddChunk",j);const Ve=k._readableState;let ht;if((Ve.state&ie)===0&&(typeof j=="string"?(Ie=Ie||Ve.defaultEncoding,Ve.encoding!==Ie&&(Ae&&Ve.encoding?j=S.from(j,Ie).toString(Ve.encoding):(j=S.from(j,Ie),Ie=""))):j instanceof S?Ie="":g._isUint8Array(j)?(j=g._uint8ArrayToBuffer(j),Ie=""):j!=null&&(ht=new re("chunk",["string","Buffer","Uint8Array"],j))),ht)L(k,ht);else if(j===null)Ve.state&=~De,R(k,Ve);else if((Ve.state&ie)!==0||j&&j.length>0)if(Ae)if((Ve.state&ue)!==0)L(k,new z);else{if(Ve.destroyed||Ve.errored)return!1;Je(k,Ve,j,!0)}else if(Ve.ended)L(k,new he);else{if(Ve.destroyed||Ve.errored)return!1;Ve.state&=~De,Ve.decoder&&!Ie?(j=Ve.decoder.write(j),Ve.objectMode||j.length!==0?Je(k,Ve,j,!1):me(k,Ve)):Je(k,Ve,j,!1)}else Ae||(Ve.state&=~De,me(k,Ve));return!Ve.ended&&(Ve.length<Ve.highWaterMark||Ve.length===0)}function Je(k,j,Ie,Ae){j.flowing&&j.length===0&&!j.sync&&k.listenerCount("data")>0?((j.state&Q)!==0?j.awaitDrainWriters.clear():j.awaitDrainWriters=null,j.dataEmitted=!0,k.emit("data",Ie)):(j.length+=j.objectMode?1:Ie.length,Ae?j.buffer.unshift(Ie):j.buffer.push(Ie),(j.state&Oe)!==0&&N(k)),me(k,j)}Y.prototype.isPaused=function(){const k=this._readableState;return k[Fe]===!0||k.flowing===!1},Y.prototype.setEncoding=function(k){const j=new ze(k);this._readableState.decoder=j,this._readableState.encoding=this._readableState.decoder.encoding;const Ie=this._readableState.buffer;let Ae="";for(const Ve of Ie)Ae+=j.write(Ve);return Ie.clear(),Ae!==""&&Ie.push(Ae),this._readableState.length=Ae.length,this};const Ne=1073741824;function Ze(k){if(k>Ne)throw new V("size","<= 1GiB",k);return k--,k|=k>>>1,k|=k>>>2,k|=k>>>4,k|=k>>>8,k|=k>>>16,k++,k}function B(k,j){return k<=0||j.length===0&&j.ended?0:(j.state&ie)!==0?1:r(k)?j.flowing&&j.length?j.buffer.first().length:j.length:k<=j.length?k:j.ended?j.length:0}Y.prototype.read=function(k){_("read",k),k===void 0?k=NaN:t(k)||(k=i(k,10));const j=this._readableState,Ie=k;if(k>j.highWaterMark&&(j.highWaterMark=Ze(k)),k!==0&&(j.state&=~te),k===0&&j.needReadable&&((j.highWaterMark!==0?j.length>=j.highWaterMark:j.length>0)||j.ended))return _("read: emitReadable",j.length,j.ended),j.length===0&&j.ended?$t(this):N(this),null;if(k=B(k,j),k===0&&j.ended)return j.length===0&&$t(this),null;let Ae=(j.state&Oe)!==0;if(_("need readable",Ae),(j.length===0||j.length-k<j.highWaterMark)&&(Ae=!0,_("length less than watermark",Ae)),j.ended||j.reading||j.destroyed||j.errored||!j.constructed)Ae=!1,_("reading, ended or constructing",Ae);else if(Ae){_("do read"),j.state|=De|We,j.length===0&&(j.state|=Oe);try{this._read(j.highWaterMark)}catch(ht){L(this,ht)}j.state&=~We,j.reading||(k=B(Ie,j))}let Ve;return k>0?Ve=dt(k,j):Ve=null,Ve===null?(j.needReadable=j.length<=j.highWaterMark,k=0):(j.length-=k,j.multiAwaitDrain?j.awaitDrainWriters.clear():j.awaitDrainWriters=null),j.length===0&&(j.ended||(j.needReadable=!0),Ie!==k&&j.ended&&$t(this)),Ve!==null&&!j.errorEmitted&&!j.closeEmitted&&(j.dataEmitted=!0,this.emit("data",Ve)),Ve};function R(k,j){if(_("onEofChunk"),!j.ended){if(j.decoder){const Ie=j.decoder.end();Ie&&Ie.length&&(j.buffer.push(Ie),j.length+=j.objectMode?1:Ie.length)}j.ended=!0,j.sync?N(k):(j.needReadable=!1,j.emittedReadable=!0,F(k))}}function N(k){const j=k._readableState;_("emitReadable",j.needReadable,j.emittedReadable),j.needReadable=!1,j.emittedReadable||(_("emitReadable",j.flowing),j.emittedReadable=!0,n.nextTick(F,k))}function F(k){const j=k._readableState;_("emitReadable_",j.destroyed,j.length,j.ended),!j.destroyed&&!j.errored&&(j.length||j.ended)&&(k.emit("readable"),j.emittedReadable=!1),j.needReadable=!j.flowing&&!j.ended&&j.length<=j.highWaterMark,at(k)}function me(k,j){!j.readingMore&&j.constructed&&(j.readingMore=!0,n.nextTick(Re,k,j))}function Re(k,j){for(;!j.reading&&!j.ended&&(j.length<j.highWaterMark||j.flowing&&j.length===0);){const Ie=j.length;if(_("maybeReadMore read 0"),k.read(0),Ie===j.length)break}j.readingMore=!1}Y.prototype._read=function(k){throw new D("_read()")},Y.prototype.pipe=function(k,j){const Ie=this,Ae=this._readableState;Ae.pipes.length===1&&(Ae.multiAwaitDrain||(Ae.multiAwaitDrain=!0,Ae.awaitDrainWriters=new c(Ae.awaitDrainWriters?[Ae.awaitDrainWriters]:[]))),Ae.pipes.push(k),_("pipe count=%d opts=%j",Ae.pipes.length,j);const ht=(!j||j.end!==!1)&&k!==n.stdout&&k!==n.stderr?rr:lt;Ae.endEmitted?n.nextTick(ht):Ie.once("end",ht),k.on("unpipe",gt);function gt(rt,Rt){_("onunpipe"),rt===Ie&&Rt&&Rt.hasUnpiped===!1&&(Rt.hasUnpiped=!0,ar())}function rr(){_("onend"),k.end()}let Pt,Et=!1;function ar(){_("cleanup"),k.removeListener("close",Jt),k.removeListener("finish",zt),Pt&&k.removeListener("drain",Pt),k.removeListener("error",nr),k.removeListener("unpipe",gt),Ie.removeListener("end",rr),Ie.removeListener("end",lt),Ie.removeListener("data",Ot),Et=!0,Pt&&Ae.awaitDrainWriters&&(!k._writableState||k._writableState.needDrain)&&Pt()}function fr(){Et||(Ae.pipes.length===1&&Ae.pipes[0]===k?(_("false write response, pause",0),Ae.awaitDrainWriters=k,Ae.multiAwaitDrain=!1):Ae.pipes.length>1&&Ae.pipes.includes(k)&&(_("false write response, pause",Ae.awaitDrainWriters.size),Ae.awaitDrainWriters.add(k)),Ie.pause()),Pt||(Pt=we(Ie,k),k.on("drain",Pt))}Ie.on("data",Ot);function Ot(rt){_("ondata");const Rt=k.write(rt);_("dest.write",Rt),Rt===!1&&fr()}function nr(rt){if(_("onerror",rt),lt(),k.removeListener("error",nr),k.listenerCount("error")===0){const Rt=k._writableState||k._readableState;Rt&&!Rt.errorEmitted?L(k,rt):k.emit("error",rt)}}b(k,"error",nr);function Jt(){k.removeListener("finish",zt),lt()}k.once("close",Jt);function zt(){_("onfinish"),k.removeListener("close",Jt),lt()}k.once("finish",zt);function lt(){_("unpipe"),Ie.unpipe(k)}return k.emit("pipe",Ie),k.writableNeedDrain===!0?fr():Ae.flowing||(_("pipe resume"),Ie.resume()),k};function we(k,j){return function(){const Ae=k._readableState;Ae.awaitDrainWriters===j?(_("pipeOnDrain",1),Ae.awaitDrainWriters=null):Ae.multiAwaitDrain&&(_("pipeOnDrain",Ae.awaitDrainWriters.size),Ae.awaitDrainWriters.delete(j)),(!Ae.awaitDrainWriters||Ae.awaitDrainWriters.size===0)&&k.listenerCount("data")&&k.resume()}}Y.prototype.unpipe=function(k){const j=this._readableState,Ie={hasUnpiped:!1};if(j.pipes.length===0)return this;if(!k){const Ve=j.pipes;j.pipes=[],this.pause();for(let ht=0;ht<Ve.length;ht++)Ve[ht].emit("unpipe",this,{hasUnpiped:!1});return this}const Ae=e(j.pipes,k);return Ae===-1?this:(j.pipes.splice(Ae,1),j.pipes.length===0&&this.pause(),k.emit("unpipe",this,Ie),this)},Y.prototype.on=function(k,j){const Ie=g.prototype.on.call(this,k,j),Ae=this._readableState;return k==="data"?(Ae.readableListening=this.listenerCount("readable")>0,Ae.flowing!==!1&&this.resume()):k==="readable"&&!Ae.endEmitted&&!Ae.readableListening&&(Ae.readableListening=Ae.needReadable=!0,Ae.flowing=!1,Ae.emittedReadable=!1,_("on readable",Ae.length,Ae.reading),Ae.length?N(this):Ae.reading||n.nextTick(et,this)),Ie},Y.prototype.addListener=Y.prototype.on,Y.prototype.removeListener=function(k,j){const Ie=g.prototype.removeListener.call(this,k,j);return k==="readable"&&n.nextTick(Qe,this),Ie},Y.prototype.off=Y.prototype.removeListener,Y.prototype.removeAllListeners=function(k){const j=g.prototype.removeAllListeners.apply(this,arguments);return(k==="readable"||k===void 0)&&n.nextTick(Qe,this),j};function Qe(k){const j=k._readableState;j.readableListening=k.listenerCount("readable")>0,j.resumeScheduled&&j[Fe]===!1?j.flowing=!0:k.listenerCount("data")>0?k.resume():j.readableListening||(j.flowing=null)}function et(k){_("readable nexttick read 0"),k.read(0)}Y.prototype.resume=function(){const k=this._readableState;return k.flowing||(_("resume"),k.flowing=!k.readableListening,ot(this,k)),k[Fe]=!1,this};function ot(k,j){j.resumeScheduled||(j.resumeScheduled=!0,n.nextTick(ct,k,j))}function ct(k,j){_("resume",j.reading),j.reading||k.read(0),j.resumeScheduled=!1,k.emit("resume"),at(k),j.flowing&&!j.reading&&k.read(0)}Y.prototype.pause=function(){return _("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(_("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[Fe]=!0,this};function at(k){const j=k._readableState;for(_("flow",j.flowing);j.flowing&&k.read()!==null;);}Y.prototype.wrap=function(k){let j=!1;k.on("data",Ae=>{!this.push(Ae)&&k.pause&&(j=!0,k.pause())}),k.on("end",()=>{this.push(null)}),k.on("error",Ae=>{L(this,Ae)}),k.on("close",()=>{this.destroy()}),k.on("destroy",()=>{this.destroy()}),this._read=()=>{j&&k.resume&&(j=!1,k.resume())};const Ie=o(k);for(let Ae=1;Ae<Ie.length;Ae++){const Ve=Ie[Ae];this[Ve]===void 0&&typeof k[Ve]=="function"&&(this[Ve]=k[Ve].bind(k))}return this},Y.prototype[d]=function(){return Qt(this)},Y.prototype.iterator=function(k){return k!==void 0&&Ce(k,"options"),Qt(this,k)};function Qt(k,j){typeof k.read!="function"&&(k=Y.wrap(k,{objectMode:!0}));const Ie=wt(k,j);return Ie.stream=k,Ie}async function*wt(k,j){let Ie=ve;function Ae(gt){this===k?(Ie(),Ie=ve):Ie=gt}k.on("readable",Ae);let Ve;const ht=v(k,{writable:!1},gt=>{Ve=gt?W(Ve,gt):null,Ie(),Ie=ve});try{for(;;){const gt=k.destroyed?null:k.read();if(gt!==null)yield gt;else{if(Ve)throw Ve;if(Ve===null)return;await new u(Ae)}}}catch(gt){throw Ve=W(Ve,gt),Ve}finally{(Ve||j?.destroyOnReturn!==!1)&&(Ve===void 0||k._readableState.autoDestroy)?C.destroyer(k,null):(k.off("readable",Ae),ht())}}s(Y.prototype,{readable:{__proto__:null,get(){const k=this._readableState;return!!k&&k.readable!==!1&&!k.destroyed&&!k.errorEmitted&&!k.endEmitted},set(k){this._readableState&&(this._readableState.readable=!!k)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(k){this._readableState&&(this._readableState.flowing=k)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(k){this._readableState&&(this._readableState.destroyed=k)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),s(ge.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[Fe]!==!1},set(k){this[Fe]=!!k}}}),Y._fromList=dt;function dt(k,j){if(j.length===0)return null;let Ie;return j.objectMode?Ie=j.buffer.shift():!k||k>=j.length?(j.decoder?Ie=j.buffer.join(""):j.buffer.length===1?Ie=j.buffer.first():Ie=j.buffer.concat(j.length),j.buffer.clear()):Ie=j.buffer.consume(k,j.decoder),Ie}function $t(k){const j=k._readableState;_("endReadable",j.endEmitted),j.endEmitted||(j.ended=!0,n.nextTick(yt,j,k))}function yt(k,j){if(_("endReadableNT",k.endEmitted,k.length),!k.errored&&!k.closeEmitted&&!k.endEmitted&&k.length===0){if(k.endEmitted=!0,j.emit("end"),j.writable&&j.allowHalfOpen===!1)n.nextTick(At,j);else if(k.autoDestroy){const Ie=j._writableState;(!Ie||Ie.autoDestroy&&(Ie.finished||Ie.writable===!1))&&j.destroy()}}}function At(k){k.writable&&!k.writableEnded&&!k.destroyed&&k.end()}Y.from=function(k,j){return ae(Y,k,j)};let It;function Bt(){return It===void 0&&(It={}),It}return Y.fromWeb=function(k,j){return Bt().newStreamReadableFromReadableStream(k,j)},Y.toWeb=function(k,j){return Bt().newReadableStreamFromStreamReadable(k,j)},Y.wrap=function(k,j){var Ie,Ae;return new Y({objectMode:(Ie=(Ae=k.readableObjectMode)!==null&&Ae!==void 0?Ae:k.objectMode)!==null&&Ie!==void 0?Ie:!0,...j,destroy(Ve,ht){C.destroyer(k,Ve),ht(Ve)}}).wrap(k)},readable}var writable,hasRequiredWritable;function requireWritable(){if(hasRequiredWritable)return writable;hasRequiredWritable=1;const n=requireBrowser$2(),{ArrayPrototypeSlice:e,Error:t,FunctionPrototypeSymbolHasInstance:r,ObjectDefineProperty:i,ObjectDefineProperties:s,ObjectSetPrototypeOf:o,StringPrototypeToLowerCase:a,Symbol:u,SymbolHasInstance:c}=requirePrimordials();writable=Ce,Ce.WritableState=z;const{EventEmitter:l}=requireEvents(),d=requireLegacy().Stream,{Buffer:f}=requireBuffer(),m=requireDestroy(),{addAbortSignal:g}=requireAddAbortSignal(),{getHighWaterMark:b,getDefaultHighWaterMark:S}=requireState(),{ERR_INVALID_ARG_TYPE:w,ERR_METHOD_NOT_IMPLEMENTED:v,ERR_MULTIPLE_CALLBACK:_,ERR_STREAM_CANNOT_PIPE:T,ERR_STREAM_DESTROYED:C,ERR_STREAM_ALREADY_FINISHED:U,ERR_STREAM_NULL_VALUES:$,ERR_STREAM_WRITE_AFTER_END:W,ERR_UNKNOWN_ENCODING:re}=requireErrors().codes,{errorOrDestroy:D}=m;o(Ce.prototype,d.prototype),o(Ce,d);function V(){}const he=u("kOnFinished");function z(x,A,O){typeof O!="boolean"&&(O=A instanceof requireDuplex()),this.objectMode=!!(x&&x.objectMode),O&&(this.objectMode=this.objectMode||!!(x&&x.writableObjectMode)),this.highWaterMark=x?b(this,x,"writableHighWaterMark",O):S(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const H=!!(x&&x.decodeStrings===!1);this.decodeStrings=!H,this.defaultEncoding=x&&x.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=L.bind(void 0,A),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,_e(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!x||x.emitClose!==!1,this.autoDestroy=!x||x.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[he]=[]}function _e(x){x.buffered=[],x.bufferedIndex=0,x.allBuffers=!0,x.allNoop=!0}z.prototype.getBuffer=function(){return e(this.buffered,this.bufferedIndex)},i(z.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Ce(x){const A=this instanceof requireDuplex();if(!A&&!r(Ce,this))return new Ce(x);this._writableState=new z(x,this,A),x&&(typeof x.write=="function"&&(this._write=x.write),typeof x.writev=="function"&&(this._writev=x.writev),typeof x.destroy=="function"&&(this._destroy=x.destroy),typeof x.final=="function"&&(this._final=x.final),typeof x.construct=="function"&&(this._construct=x.construct),x.signal&&g(x.signal,this)),d.call(this,x),m.construct(this,()=>{const O=this._writableState;O.writing||De(this,O),te(this,O)})}i(Ce,c,{__proto__:null,value:function(x){return r(this,x)?!0:this!==Ce?!1:x&&x._writableState instanceof z}}),Ce.prototype.pipe=function(){D(this,new T)};function Fe(x,A,O,H){const Q=x._writableState;if(typeof O=="function")H=O,O=Q.defaultEncoding;else{if(!O)O=Q.defaultEncoding;else if(O!=="buffer"&&!f.isEncoding(O))throw new re(O);typeof H!="function"&&(H=V)}if(A===null)throw new $;if(!Q.objectMode)if(typeof A=="string")Q.decodeStrings!==!1&&(A=f.from(A,O),O="buffer");else if(A instanceof f)O="buffer";else if(d._isUint8Array(A))A=d._uint8ArrayToBuffer(A),O="buffer";else throw new w("chunk",["string","Buffer","Uint8Array"],A);let de;return Q.ending?de=new W:Q.destroyed&&(de=new C("write")),de?(n.nextTick(H,de),D(x,de,!0),de):(Q.pendingcb++,ze(x,Q,A,O,H))}Ce.prototype.write=function(x,A,O){return Fe(this,x,A,O)===!0},Ce.prototype.cork=function(){this._writableState.corked++},Ce.prototype.uncork=function(){const x=this._writableState;x.corked&&(x.corked--,x.writing||De(this,x))},Ce.prototype.setDefaultEncoding=function(A){if(typeof A=="string"&&(A=a(A)),!f.isEncoding(A))throw new re(A);return this._writableState.defaultEncoding=A,this};function ze(x,A,O,H,Q){const de=A.objectMode?1:O.length;A.length+=de;const M=A.length<A.highWaterMark;return M||(A.needDrain=!0),A.writing||A.corked||A.errored||!A.constructed?(A.buffered.push({chunk:O,encoding:H,callback:Q}),A.allBuffers&&H!=="buffer"&&(A.allBuffers=!1),A.allNoop&&Q!==V&&(A.allNoop=!1)):(A.writelen=de,A.writecb=Q,A.writing=!0,A.sync=!0,x._write(O,H,A.onwrite),A.sync=!1),M&&!A.errored&&!A.destroyed}function ae(x,A,O,H,Q,de,M){A.writelen=H,A.writecb=M,A.writing=!0,A.sync=!0,A.destroyed?A.onwrite(new C("write")):O?x._writev(Q,A.onwrite):x._write(Q,de,A.onwrite),A.sync=!1}function ve(x,A,O,H){--A.pendingcb,H(O),ue(A),D(x,O)}function L(x,A){const O=x._writableState,H=O.sync,Q=O.writecb;if(typeof Q!="function"){D(x,new _);return}O.writing=!1,O.writecb=null,O.length-=O.writelen,O.writelen=0,A?(A.stack,O.errored||(O.errored=A),x._readableState&&!x._readableState.errored&&(x._readableState.errored=A),H?n.nextTick(ve,x,O,A,Q):ve(x,O,A,Q)):(O.buffered.length>O.bufferedIndex&&De(x,O),H?O.afterWriteTickInfo!==null&&O.afterWriteTickInfo.cb===Q?O.afterWriteTickInfo.count++:(O.afterWriteTickInfo={count:1,cb:Q,stream:x,state:O},n.nextTick(ie,O.afterWriteTickInfo)):xe(x,O,1,Q))}function ie({stream:x,state:A,count:O,cb:H}){return A.afterWriteTickInfo=null,xe(x,A,O,H)}function xe(x,A,O,H){for(!A.ending&&!x.destroyed&&A.length===0&&A.needDrain&&(A.needDrain=!1,x.emit("drain"));O-- >0;)A.pendingcb--,H();A.destroyed&&ue(A),te(x,A)}function ue(x){if(x.writing)return;for(let Q=x.bufferedIndex;Q<x.buffered.length;++Q){var A;const{chunk:de,callback:M}=x.buffered[Q],ne=x.objectMode?1:de.length;x.length-=ne,M((A=x.errored)!==null&&A!==void 0?A:new C("write"))}const O=x[he].splice(0);for(let Q=0;Q<O.length;Q++){var H;O[Q]((H=x.errored)!==null&&H!==void 0?H:new C("end"))}_e(x)}function De(x,A){if(A.corked||A.bufferProcessing||A.destroyed||!A.constructed)return;const{buffered:O,bufferedIndex:H,objectMode:Q}=A,de=O.length-H;if(!de)return;let M=H;if(A.bufferProcessing=!0,de>1&&x._writev){A.pendingcb-=de-1;const ne=A.allNoop?V:Y=>{for(let Be=M;Be<O.length;++Be)O[Be].callback(Y)},ge=A.allNoop&&M===0?O:e(O,M);ge.allBuffers=A.allBuffers,ae(x,A,!0,A.length,ge,"",ne),_e(A)}else{do{const{chunk:ne,encoding:ge,callback:Y}=O[M];O[M++]=null;const Be=Q?1:ne.length;ae(x,A,!1,Be,ne,ge,Y)}while(M<O.length&&!A.writing);M===O.length?_e(A):M>256?(O.splice(0,M),A.bufferedIndex=0):A.bufferedIndex=M}A.bufferProcessing=!1}Ce.prototype._write=function(x,A,O){if(this._writev)this._writev([{chunk:x,encoding:A}],O);else throw new v("_write()")},Ce.prototype._writev=null,Ce.prototype.end=function(x,A,O){const H=this._writableState;typeof x=="function"?(O=x,x=null,A=null):typeof A=="function"&&(O=A,A=null);let Q;if(x!=null){const de=Fe(this,x,A);de instanceof t&&(Q=de)}return H.corked&&(H.corked=1,this.uncork()),Q||(!H.errored&&!H.ending?(H.ending=!0,te(this,H,!0),H.ended=!0):H.finished?Q=new U("end"):H.destroyed&&(Q=new C("end"))),typeof O=="function"&&(Q||H.finished?n.nextTick(O,Q):H[he].push(O)),this};function ke(x){return x.ending&&!x.destroyed&&x.constructed&&x.length===0&&!x.errored&&x.buffered.length===0&&!x.finished&&!x.writing&&!x.errorEmitted&&!x.closeEmitted}function We(x,A){let O=!1;function H(Q){if(O){D(x,Q??_());return}if(O=!0,A.pendingcb--,Q){const de=A[he].splice(0);for(let M=0;M<de.length;M++)de[M](Q);D(x,Q,A.sync)}else ke(A)&&(A.prefinished=!0,x.emit("prefinish"),A.pendingcb++,n.nextTick(le,x,A))}A.sync=!0,A.pendingcb++;try{x._final(H)}catch(Q){H(Q)}A.sync=!1}function Oe(x,A){!A.prefinished&&!A.finalCalled&&(typeof x._final=="function"&&!A.destroyed?(A.finalCalled=!0,We(x,A)):(A.prefinished=!0,x.emit("prefinish")))}function te(x,A,O){ke(A)&&(Oe(x,A),A.pendingcb===0&&(O?(A.pendingcb++,n.nextTick((H,Q)=>{ke(Q)?le(H,Q):Q.pendingcb--},x,A)):ke(A)&&(A.pendingcb++,le(x,A))))}function le(x,A){A.pendingcb--,A.finished=!0;const O=A[he].splice(0);for(let H=0;H<O.length;H++)O[H]();if(x.emit("finish"),A.autoDestroy){const H=x._readableState;(!H||H.autoDestroy&&(H.endEmitted||H.readable===!1))&&x.destroy()}}s(Ce.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(x){this._writableState&&(this._writableState.destroyed=x)}},writable:{__proto__:null,get(){const x=this._writableState;return!!x&&x.writable!==!1&&!x.destroyed&&!x.errored&&!x.ending&&!x.ended},set(x){this._writableState&&(this._writableState.writable=!!x)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){const x=this._writableState;return x?!x.destroyed&&!x.ending&&x.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});const Te=m.destroy;Ce.prototype.destroy=function(x,A){const O=this._writableState;return!O.destroyed&&(O.bufferedIndex<O.buffered.length||O[he].length)&&n.nextTick(ue,O),Te.call(this,x,A),this},Ce.prototype._undestroy=m.undestroy,Ce.prototype._destroy=function(x,A){A(x)},Ce.prototype[l.captureRejectionSymbol]=function(x){this.destroy(x)};let G;function P(){return G===void 0&&(G={}),G}return Ce.fromWeb=function(x,A){return P().newStreamWritableFromWritableStream(x,A)},Ce.toWeb=function(x){return P().newWritableStreamFromStreamWritable(x)},writable}var duplexify,hasRequiredDuplexify;function requireDuplexify(){if(hasRequiredDuplexify)return duplexify;hasRequiredDuplexify=1;const n=requireBrowser$2(),e=requireBuffer(),{isReadable:t,isWritable:r,isIterable:i,isNodeStream:s,isReadableNodeStream:o,isWritableNodeStream:a,isDuplexNodeStream:u,isReadableStream:c,isWritableStream:l}=requireUtils(),d=requireEndOfStream(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:m,ERR_INVALID_RETURN_VALUE:g}}=requireErrors(),{destroyer:b}=requireDestroy(),S=requireDuplex(),w=requireReadable(),v=requireWritable(),{createDeferredPromise:_}=requireUtil(),T=requireFrom(),C=globalThis.Blob||e.Blob,U=typeof C<"u"?function(z){return z instanceof C}:function(z){return!1},$=globalThis.AbortController||requireBrowser$3().AbortController,{FunctionPrototypeCall:W}=requirePrimordials();class re extends S{constructor(z){super(z),z?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),z?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}}duplexify=function he(z,_e){if(u(z))return z;if(o(z))return V({readable:z});if(a(z))return V({writable:z});if(s(z))return V({writable:!1,readable:!1});if(c(z))return V({readable:w.fromWeb(z)});if(l(z))return V({writable:v.fromWeb(z)});if(typeof z=="function"){const{value:Fe,write:ze,final:ae,destroy:ve}=D(z);if(i(Fe))return T(re,Fe,{objectMode:!0,write:ze,final:ae,destroy:ve});const L=Fe?.then;if(typeof L=="function"){let ie;const xe=W(L,Fe,ue=>{if(ue!=null)throw new g("nully","body",ue)},ue=>{b(ie,ue)});return ie=new re({objectMode:!0,readable:!1,write:ze,final(ue){ae(async()=>{try{await xe,n.nextTick(ue,null)}catch(De){n.nextTick(ue,De)}})},destroy:ve})}throw new g("Iterable, AsyncIterable or AsyncFunction",_e,Fe)}if(U(z))return he(z.arrayBuffer());if(i(z))return T(re,z,{objectMode:!0,writable:!1});if(c(z?.readable)&&l(z?.writable))return re.fromWeb(z);if(typeof z?.writable=="object"||typeof z?.readable=="object"){const Fe=z!=null&&z.readable?o(z?.readable)?z?.readable:he(z.readable):void 0,ze=z!=null&&z.writable?a(z?.writable)?z?.writable:he(z.writable):void 0;return V({readable:Fe,writable:ze})}const Ce=z?.then;if(typeof Ce=="function"){let Fe;return W(Ce,z,ze=>{ze!=null&&Fe.push(ze),Fe.push(null)},ze=>{b(Fe,ze)}),Fe=new re({objectMode:!0,writable:!1,read(){}})}throw new m(_e,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],z)};function D(he){let{promise:z,resolve:_e}=_();const Ce=new $,Fe=Ce.signal;return{value:he((async function*(){for(;;){const ae=z;z=null;const{chunk:ve,done:L,cb:ie}=await ae;if(n.nextTick(ie),L)return;if(Fe.aborted)throw new f(void 0,{cause:Fe.reason});({promise:z,resolve:_e}=_()),yield ve}})(),{signal:Fe}),write(ae,ve,L){const ie=_e;_e=null,ie({chunk:ae,done:!1,cb:L})},final(ae){const ve=_e;_e=null,ve({done:!0,cb:ae})},destroy(ae,ve){Ce.abort(),ve(ae)}}}function V(he){const z=he.readable&&typeof he.readable.read!="function"?w.wrap(he.readable):he.readable,_e=he.writable;let Ce=!!t(z),Fe=!!r(_e),ze,ae,ve,L,ie;function xe(ue){const De=L;L=null,De?De(ue):ue&&ie.destroy(ue)}return ie=new re({readableObjectMode:!!(z!=null&&z.readableObjectMode),writableObjectMode:!!(_e!=null&&_e.writableObjectMode),readable:Ce,writable:Fe}),Fe&&(d(_e,ue=>{Fe=!1,ue&&b(z,ue),xe(ue)}),ie._write=function(ue,De,ke){_e.write(ue,De)?ke():ze=ke},ie._final=function(ue){_e.end(),ae=ue},_e.on("drain",function(){if(ze){const ue=ze;ze=null,ue()}}),_e.on("finish",function(){if(ae){const ue=ae;ae=null,ue()}})),Ce&&(d(z,ue=>{Ce=!1,ue&&b(z,ue),xe(ue)}),z.on("readable",function(){if(ve){const ue=ve;ve=null,ue()}}),z.on("end",function(){ie.push(null)}),ie._read=function(){for(;;){const ue=z.read();if(ue===null){ve=ie._read;return}if(!ie.push(ue))return}}),ie._destroy=function(ue,De){!ue&&L!==null&&(ue=new f),ve=null,ze=null,ae=null,L===null?De(ue):(L=De,b(_e,ue),b(z,ue))},ie}return duplexify}var duplex,hasRequiredDuplex;function requireDuplex(){if(hasRequiredDuplex)return duplex;hasRequiredDuplex=1;const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:e,ObjectKeys:t,ObjectSetPrototypeOf:r}=requirePrimordials();duplex=o;const i=requireReadable(),s=requireWritable();r(o.prototype,i.prototype),r(o,i);{const l=t(s.prototype);for(let d=0;d<l.length;d++){const f=l[d];o.prototype[f]||(o.prototype[f]=s.prototype[f])}}function o(l){if(!(this instanceof o))return new o(l);i.call(this,l),s.call(this,l),l?(this.allowHalfOpen=l.allowHalfOpen!==!1,l.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),l.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}n(o.prototype,{writable:{__proto__:null,...e(s.prototype,"writable")},writableHighWaterMark:{__proto__:null,...e(s.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...e(s.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...e(s.prototype,"writableBuffer")},writableLength:{__proto__:null,...e(s.prototype,"writableLength")},writableFinished:{__proto__:null,...e(s.prototype,"writableFinished")},writableCorked:{__proto__:null,...e(s.prototype,"writableCorked")},writableEnded:{__proto__:null,...e(s.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...e(s.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(l){this._readableState&&this._writableState&&(this._readableState.destroyed=l,this._writableState.destroyed=l)}}});let a;function u(){return a===void 0&&(a={}),a}o.fromWeb=function(l,d){return u().newStreamDuplexFromReadableWritablePair(l,d)},o.toWeb=function(l){return u().newReadableWritablePairFromDuplex(l)};let c;return o.from=function(l){return c||(c=requireDuplexify()),c(l,"body")},duplex}var transform$1,hasRequiredTransform;function requireTransform(){if(hasRequiredTransform)return transform$1;hasRequiredTransform=1;const{ObjectSetPrototypeOf:n,Symbol:e}=requirePrimordials();transform$1=o;const{ERR_METHOD_NOT_IMPLEMENTED:t}=requireErrors().codes,r=requireDuplex(),{getHighWaterMark:i}=requireState();n(o.prototype,r.prototype),n(o,r);const s=e("kCallback");function o(c){if(!(this instanceof o))return new o(c);const l=c?i(this,c,"readableHighWaterMark",!0):null;l===0&&(c={...c,highWaterMark:null,readableHighWaterMark:l,writableHighWaterMark:c.writableHighWaterMark||0}),r.call(this,c),this._readableState.sync=!1,this[s]=null,c&&(typeof c.transform=="function"&&(this._transform=c.transform),typeof c.flush=="function"&&(this._flush=c.flush)),this.on("prefinish",u)}function a(c){typeof this._flush=="function"&&!this.destroyed?this._flush((l,d)=>{if(l){c?c(l):this.destroy(l);return}d!=null&&this.push(d),this.push(null),c&&c()}):(this.push(null),c&&c())}function u(){this._final!==a&&a.call(this)}return o.prototype._final=a,o.prototype._transform=function(c,l,d){throw new t("_transform()")},o.prototype._write=function(c,l,d){const f=this._readableState,m=this._writableState,g=f.length;this._transform(c,l,(b,S)=>{if(b){d(b);return}S!=null&&this.push(S),m.ended||g===f.length||f.length<f.highWaterMark?d():this[s]=d})},o.prototype._read=function(){if(this[s]){const c=this[s];this[s]=null,c()}},transform$1}var passthrough,hasRequiredPassthrough;function requirePassthrough(){if(hasRequiredPassthrough)return passthrough;hasRequiredPassthrough=1;const{ObjectSetPrototypeOf:n}=requirePrimordials();passthrough=t;const e=requireTransform();n(t.prototype,e.prototype),n(t,e);function t(r){if(!(this instanceof t))return new t(r);e.call(this,r)}return t.prototype._transform=function(r,i,s){s(null,r)},passthrough}var pipeline_1,hasRequiredPipeline;function requirePipeline(){if(hasRequiredPipeline)return pipeline_1;hasRequiredPipeline=1;const n=requireBrowser$2(),{ArrayIsArray:e,Promise:t,SymbolAsyncIterator:r,SymbolDispose:i}=requirePrimordials(),s=requireEndOfStream(),{once:o}=requireUtil(),a=requireDestroy(),u=requireDuplex(),{aggregateTwoErrors:c,codes:{ERR_INVALID_ARG_TYPE:l,ERR_INVALID_RETURN_VALUE:d,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:m,ERR_STREAM_PREMATURE_CLOSE:g},AbortError:b}=requireErrors(),{validateFunction:S,validateAbortSignal:w}=requireValidators(),{isIterable:v,isReadable:_,isReadableNodeStream:T,isNodeStream:C,isTransformStream:U,isWebStream:$,isReadableStream:W,isReadableFinished:re}=requireUtils(),D=globalThis.AbortController||requireBrowser$3().AbortController;let V,he,z;function _e(ue,De,ke){let We=!1;ue.on("close",()=>{We=!0});const Oe=s(ue,{readable:De,writable:ke},te=>{We=!te});return{destroy:te=>{We||(We=!0,a.destroyer(ue,te||new m("pipe")))},cleanup:Oe}}function Ce(ue){return S(ue[ue.length-1],"streams[stream.length - 1]"),ue.pop()}function Fe(ue){if(v(ue))return ue;if(T(ue))return ze(ue);throw new l("val",["Readable","Iterable","AsyncIterable"],ue)}async function*ze(ue){he||(he=requireReadable()),yield*he.prototype[r].call(ue)}async function ae(ue,De,ke,{end:We}){let Oe,te=null;const le=P=>{if(P&&(Oe=P),te){const x=te;te=null,x()}},Te=()=>new t((P,x)=>{Oe?x(Oe):te=()=>{Oe?x(Oe):P()}});De.on("drain",le);const G=s(De,{readable:!1},le);try{De.writableNeedDrain&&await Te();for await(const P of ue)De.write(P)||await Te();We&&(De.end(),await Te()),ke()}catch(P){ke(Oe!==P?c(Oe,P):P)}finally{G(),De.off("drain",le)}}async function ve(ue,De,ke,{end:We}){U(De)&&(De=De.writable);const Oe=De.getWriter();try{for await(const te of ue)await Oe.ready,Oe.write(te).catch(()=>{});await Oe.ready,We&&await Oe.close(),ke()}catch(te){try{await Oe.abort(te),ke(te)}catch(le){ke(le)}}}function L(...ue){return ie(ue,o(Ce(ue)))}function ie(ue,De,ke){if(ue.length===1&&e(ue[0])&&(ue=ue[0]),ue.length<2)throw new f("streams");const We=new D,Oe=We.signal,te=ke?.signal,le=[];w(te,"options.signal");function Te(){Q(new b)}z=z||requireUtil().addAbortListener;let G;te&&(G=z(te,Te));let P,x;const A=[];let O=0;function H(ge){Q(ge,--O===0)}function Q(ge,Y){var Be;if(ge&&(!P||P.code==="ERR_STREAM_PREMATURE_CLOSE")&&(P=ge),!(!P&&!Y)){for(;A.length;)A.shift()(P);(Be=G)===null||Be===void 0||Be[i](),We.abort(),Y&&(P||le.forEach(Je=>Je()),n.nextTick(De,P,x))}}let de;for(let ge=0;ge<ue.length;ge++){const Y=ue[ge],Be=ge<ue.length-1,Je=ge>0,Ne=Be||ke?.end!==!1,Ze=ge===ue.length-1;if(C(Y)){let B=function(R){R&&R.name!=="AbortError"&&R.code!=="ERR_STREAM_PREMATURE_CLOSE"&&H(R)};if(Ne){const{destroy:R,cleanup:N}=_e(Y,Be,Je);A.push(R),_(Y)&&Ze&&le.push(N)}Y.on("error",B),_(Y)&&Ze&&le.push(()=>{Y.removeListener("error",B)})}if(ge===0)if(typeof Y=="function"){if(de=Y({signal:Oe}),!v(de))throw new d("Iterable, AsyncIterable or Stream","source",de)}else v(Y)||T(Y)||U(Y)?de=Y:de=u.from(Y);else if(typeof Y=="function"){if(U(de)){var M;de=Fe((M=de)===null||M===void 0?void 0:M.readable)}else de=Fe(de);if(de=Y(de,{signal:Oe}),Be){if(!v(de,!0))throw new d("AsyncIterable",`transform[${ge-1}]`,de)}else{var ne;V||(V=requirePassthrough());const B=new V({objectMode:!0}),R=(ne=de)===null||ne===void 0?void 0:ne.then;if(typeof R=="function")O++,R.call(de,me=>{x=me,me!=null&&B.write(me),Ne&&B.end(),n.nextTick(H)},me=>{B.destroy(me),n.nextTick(H,me)});else if(v(de,!0))O++,ae(de,B,H,{end:Ne});else if(W(de)||U(de)){const me=de.readable||de;O++,ae(me,B,H,{end:Ne})}else throw new d("AsyncIterable or Promise","destination",de);de=B;const{destroy:N,cleanup:F}=_e(de,!1,!0);A.push(N),Ze&&le.push(F)}}else if(C(Y)){if(T(de)){O+=2;const B=xe(de,Y,H,{end:Ne});_(Y)&&Ze&&le.push(B)}else if(U(de)||W(de)){const B=de.readable||de;O++,ae(B,Y,H,{end:Ne})}else if(v(de))O++,ae(de,Y,H,{end:Ne});else throw new l("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],de);de=Y}else if($(Y)){if(T(de))O++,ve(Fe(de),Y,H,{end:Ne});else if(W(de)||v(de))O++,ve(de,Y,H,{end:Ne});else if(U(de))O++,ve(de.readable,Y,H,{end:Ne});else throw new l("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],de);de=Y}else de=u.from(Y)}return(Oe!=null&&Oe.aborted||te!=null&&te.aborted)&&n.nextTick(Te),de}function xe(ue,De,ke,{end:We}){let Oe=!1;if(De.on("close",()=>{Oe||ke(new g)}),ue.pipe(De,{end:!1}),We){let te=function(){Oe=!0,De.end()};re(ue)?n.nextTick(te):ue.once("end",te)}else ke();return s(ue,{readable:!0,writable:!1},te=>{const le=ue._readableState;te&&te.code==="ERR_STREAM_PREMATURE_CLOSE"&&le&&le.ended&&!le.errored&&!le.errorEmitted?ue.once("end",ke).once("error",ke):ke(te)}),s(De,{readable:!1,writable:!0},ke)}return pipeline_1={pipelineImpl:ie,pipeline:L},pipeline_1}var compose,hasRequiredCompose;function requireCompose(){if(hasRequiredCompose)return compose;hasRequiredCompose=1;const{pipeline:n}=requirePipeline(),e=requireDuplex(),{destroyer:t}=requireDestroy(),{isNodeStream:r,isReadable:i,isWritable:s,isWebStream:o,isTransformStream:a,isWritableStream:u,isReadableStream:c}=requireUtils(),{AbortError:l,codes:{ERR_INVALID_ARG_VALUE:d,ERR_MISSING_ARGS:f}}=requireErrors(),m=requireEndOfStream();return compose=function(...b){if(b.length===0)throw new f("streams");if(b.length===1)return e.from(b[0]);const S=[...b];if(typeof b[0]=="function"&&(b[0]=e.from(b[0])),typeof b[b.length-1]=="function"){const V=b.length-1;b[V]=e.from(b[V])}for(let V=0;V<b.length;++V)if(!(!r(b[V])&&!o(b[V]))){if(V<b.length-1&&!(i(b[V])||c(b[V])||a(b[V])))throw new d(`streams[${V}]`,S[V],"must be readable");if(V>0&&!(s(b[V])||u(b[V])||a(b[V])))throw new d(`streams[${V}]`,S[V],"must be writable")}let w,v,_,T,C;function U(V){const he=T;T=null,he?he(V):V?C.destroy(V):!D&&!re&&C.destroy()}const $=b[0],W=n(b,U),re=!!(s($)||u($)||a($)),D=!!(i(W)||c(W)||a(W));if(C=new e({writableObjectMode:!!($!=null&&$.writableObjectMode),readableObjectMode:!!(W!=null&&W.readableObjectMode),writable:re,readable:D}),re){if(r($))C._write=function(he,z,_e){$.write(he,z)?_e():w=_e},C._final=function(he){$.end(),v=he},$.on("drain",function(){if(w){const he=w;w=null,he()}});else if(o($)){const z=(a($)?$.writable:$).getWriter();C._write=async function(_e,Ce,Fe){try{await z.ready,z.write(_e).catch(()=>{}),Fe()}catch(ze){Fe(ze)}},C._final=async function(_e){try{await z.ready,z.close().catch(()=>{}),v=_e}catch(Ce){_e(Ce)}}}const V=a(W)?W.readable:W;m(V,()=>{if(v){const he=v;v=null,he()}})}if(D){if(r(W))W.on("readable",function(){if(_){const V=_;_=null,V()}}),W.on("end",function(){C.push(null)}),C._read=function(){for(;;){const V=W.read();if(V===null){_=C._read;return}if(!C.push(V))return}};else if(o(W)){const he=(a(W)?W.readable:W).getReader();C._read=async function(){for(;;)try{const{value:z,done:_e}=await he.read();if(!C.push(z))return;if(_e){C.push(null);return}}catch{return}}}}return C._destroy=function(V,he){!V&&T!==null&&(V=new l),_=null,w=null,v=null,T===null?he(V):(T=he,r(W)&&t(W,V))},C},compose}var hasRequiredOperators;function requireOperators(){if(hasRequiredOperators)return operators;hasRequiredOperators=1;const n=globalThis.AbortController||requireBrowser$3().AbortController,{codes:{ERR_INVALID_ARG_VALUE:e,ERR_INVALID_ARG_TYPE:t,ERR_MISSING_ARGS:r,ERR_OUT_OF_RANGE:i},AbortError:s}=requireErrors(),{validateAbortSignal:o,validateInteger:a,validateObject:u}=requireValidators(),c=requirePrimordials().Symbol("kWeak"),l=requirePrimordials().Symbol("kResistStopPropagation"),{finished:d}=requireEndOfStream(),f=requireCompose(),{addAbortSignalNoValidate:m}=requireAddAbortSignal(),{isWritable:g,isNodeStream:b}=requireUtils(),{deprecate:S}=requireUtil(),{ArrayPrototypePush:w,Boolean:v,MathFloor:_,Number:T,NumberIsNaN:C,Promise:U,PromiseReject:$,PromiseResolve:W,PromisePrototypeThen:re,Symbol:D}=requirePrimordials(),V=D("kEmpty"),he=D("kEof");function z(te,le){if(le!=null&&u(le,"options"),le?.signal!=null&&o(le.signal,"options.signal"),b(te)&&!g(te))throw new e("stream",te,"must be writable");const Te=f(this,te);return le!=null&&le.signal&&m(le.signal,Te),Te}function _e(te,le){if(typeof te!="function")throw new t("fn",["Function","AsyncFunction"],te);le!=null&&u(le,"options"),le?.signal!=null&&o(le.signal,"options.signal");let Te=1;le?.concurrency!=null&&(Te=_(le.concurrency));let G=Te-1;return le?.highWaterMark!=null&&(G=_(le.highWaterMark)),a(Te,"options.concurrency",1),a(G,"options.highWaterMark",0),G+=Te,(async function*(){const x=requireUtil().AbortSignalAny([le?.signal].filter(v)),A=this,O=[],H={signal:x};let Q,de,M=!1,ne=0;function ge(){M=!0,Y()}function Y(){ne-=1,Be()}function Be(){de&&!M&&ne<Te&&O.length<G&&(de(),de=null)}async function Je(){try{for await(let Ne of A){if(M)return;if(x.aborted)throw new s;try{if(Ne=te(Ne,H),Ne===V)continue;Ne=W(Ne)}catch(Ze){Ne=$(Ze)}ne+=1,re(Ne,Y,ge),O.push(Ne),Q&&(Q(),Q=null),!M&&(O.length>=G||ne>=Te)&&await new U(Ze=>{de=Ze})}O.push(he)}catch(Ne){const Ze=$(Ne);re(Ze,Y,ge),O.push(Ze)}finally{M=!0,Q&&(Q(),Q=null)}}Je();try{for(;;){for(;O.length>0;){const Ne=await O[0];if(Ne===he)return;if(x.aborted)throw new s;Ne!==V&&(yield Ne),O.shift(),Be()}await new U(Ne=>{Q=Ne})}}finally{M=!0,de&&(de(),de=null)}}).call(this)}function Ce(te=void 0){return te!=null&&u(te,"options"),te?.signal!=null&&o(te.signal,"options.signal"),(async function*(){let Te=0;for await(const P of this){var G;if(te!=null&&(G=te.signal)!==null&&G!==void 0&&G.aborted)throw new s({cause:te.signal.reason});yield[Te++,P]}}).call(this)}async function Fe(te,le=void 0){for await(const Te of L.call(this,te,le))return!0;return!1}async function ze(te,le=void 0){if(typeof te!="function")throw new t("fn",["Function","AsyncFunction"],te);return!await Fe.call(this,async(...Te)=>!await te(...Te),le)}async function ae(te,le){for await(const Te of L.call(this,te,le))return Te}async function ve(te,le){if(typeof te!="function")throw new t("fn",["Function","AsyncFunction"],te);async function Te(G,P){return await te(G,P),V}for await(const G of _e.call(this,Te,le));}function L(te,le){if(typeof te!="function")throw new t("fn",["Function","AsyncFunction"],te);async function Te(G,P){return await te(G,P)?G:V}return _e.call(this,Te,le)}class ie extends r{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}async function xe(te,le,Te){var G;if(typeof te!="function")throw new t("reducer",["Function","AsyncFunction"],te);Te!=null&&u(Te,"options"),Te?.signal!=null&&o(Te.signal,"options.signal");let P=arguments.length>1;if(Te!=null&&(G=Te.signal)!==null&&G!==void 0&&G.aborted){const Q=new s(void 0,{cause:Te.signal.reason});throw this.once("error",()=>{}),await d(this.destroy(Q)),Q}const x=new n,A=x.signal;if(Te!=null&&Te.signal){const Q={once:!0,[c]:this,[l]:!0};Te.signal.addEventListener("abort",()=>x.abort(),Q)}let O=!1;try{for await(const Q of this){var H;if(O=!0,Te!=null&&(H=Te.signal)!==null&&H!==void 0&&H.aborted)throw new s;P?le=await te(le,Q,{signal:A}):(le=Q,P=!0)}if(!O&&!P)throw new ie}finally{x.abort()}return le}async function ue(te){te!=null&&u(te,"options"),te?.signal!=null&&o(te.signal,"options.signal");const le=[];for await(const G of this){var Te;if(te!=null&&(Te=te.signal)!==null&&Te!==void 0&&Te.aborted)throw new s(void 0,{cause:te.signal.reason});w(le,G)}return le}function De(te,le){const Te=_e.call(this,te,le);return(async function*(){for await(const P of Te)yield*P}).call(this)}function ke(te){if(te=T(te),C(te))return 0;if(te<0)throw new i("number",">= 0",te);return te}function We(te,le=void 0){return le!=null&&u(le,"options"),le?.signal!=null&&o(le.signal,"options.signal"),te=ke(te),(async function*(){var G;if(le!=null&&(G=le.signal)!==null&&G!==void 0&&G.aborted)throw new s;for await(const x of this){var P;if(le!=null&&(P=le.signal)!==null&&P!==void 0&&P.aborted)throw new s;te--<=0&&(yield x)}}).call(this)}function Oe(te,le=void 0){return le!=null&&u(le,"options"),le?.signal!=null&&o(le.signal,"options.signal"),te=ke(te),(async function*(){var G;if(le!=null&&(G=le.signal)!==null&&G!==void 0&&G.aborted)throw new s;for await(const x of this){var P;if(le!=null&&(P=le.signal)!==null&&P!==void 0&&P.aborted)throw new s;if(te-- >0&&(yield x),te<=0)return}}).call(this)}return operators.streamReturningOperators={asIndexedPairs:S(Ce,"readable.asIndexedPairs will be removed in a future version."),drop:We,filter:L,flatMap:De,map:_e,take:Oe,compose:z},operators.promiseReturningOperators={every:ze,forEach:ve,reduce:xe,toArray:ue,some:Fe,find:ae},operators}var promises,hasRequiredPromises;function requirePromises(){if(hasRequiredPromises)return promises;hasRequiredPromises=1;const{ArrayPrototypePop:n,Promise:e}=requirePrimordials(),{isIterable:t,isNodeStream:r,isWebStream:i}=requireUtils(),{pipelineImpl:s}=requirePipeline(),{finished:o}=requireEndOfStream();requireStream();function a(...u){return new e((c,l)=>{let d,f;const m=u[u.length-1];if(m&&typeof m=="object"&&!r(m)&&!t(m)&&!i(m)){const g=n(u);d=g.signal,f=g.end}s(u,(g,b)=>{g?l(g):c(b)},{signal:d,end:f})})}return promises={finished:o,pipeline:a},promises}var hasRequiredStream;function requireStream(){if(hasRequiredStream)return stream.exports;hasRequiredStream=1;const{Buffer:n}=requireBuffer(),{ObjectDefineProperty:e,ObjectKeys:t,ReflectApply:r}=requirePrimordials(),{promisify:{custom:i}}=requireUtil(),{streamReturningOperators:s,promiseReturningOperators:o}=requireOperators(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:a}}=requireErrors(),u=requireCompose(),{setDefaultHighWaterMark:c,getDefaultHighWaterMark:l}=requireState(),{pipeline:d}=requirePipeline(),{destroyer:f}=requireDestroy(),m=requireEndOfStream(),g=requirePromises(),b=requireUtils(),S=stream.exports=requireLegacy().Stream;S.isDestroyed=b.isDestroyed,S.isDisturbed=b.isDisturbed,S.isErrored=b.isErrored,S.isReadable=b.isReadable,S.isWritable=b.isWritable,S.Readable=requireReadable();for(const v of t(s)){let T=function(...C){if(new.target)throw a();return S.Readable.from(r(_,this,C))};const _=s[v];e(T,"name",{__proto__:null,value:_.name}),e(T,"length",{__proto__:null,value:_.length}),e(S.Readable.prototype,v,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}for(const v of t(o)){let T=function(...C){if(new.target)throw a();return r(_,this,C)};const _=o[v];e(T,"name",{__proto__:null,value:_.name}),e(T,"length",{__proto__:null,value:_.length}),e(S.Readable.prototype,v,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}S.Writable=requireWritable(),S.Duplex=requireDuplex(),S.Transform=requireTransform(),S.PassThrough=requirePassthrough(),S.pipeline=d;const{addAbortSignal:w}=requireAddAbortSignal();return S.addAbortSignal=w,S.finished=m,S.destroy=f,S.compose=u,S.setDefaultHighWaterMark=c,S.getDefaultHighWaterMark=l,e(S,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return g}}),e(d,i,{__proto__:null,enumerable:!0,get(){return g.pipeline}}),e(m,i,{__proto__:null,enumerable:!0,get(){return g.finished}}),S.Stream=S,S._isUint8Array=function(_){return _ instanceof Uint8Array},S._uint8ArrayToBuffer=function(_){return n.from(_.buffer,_.byteOffset,_.byteLength)},stream.exports}var hasRequiredBrowser;function requireBrowser(){return hasRequiredBrowser||(hasRequiredBrowser=1,(function(n){const e=requireStream(),t=requirePromises(),r=e.Readable.destroy;n.exports=e.Readable,n.exports._uint8ArrayToBuffer=e._uint8ArrayToBuffer,n.exports._isUint8Array=e._isUint8Array,n.exports.isDisturbed=e.isDisturbed,n.exports.isErrored=e.isErrored,n.exports.isReadable=e.isReadable,n.exports.Readable=e.Readable,n.exports.Writable=e.Writable,n.exports.Duplex=e.Duplex,n.exports.Transform=e.Transform,n.exports.PassThrough=e.PassThrough,n.exports.addAbortSignal=e.addAbortSignal,n.exports.finished=e.finished,n.exports.destroy=e.destroy,n.exports.destroy=r,n.exports.pipeline=e.pipeline,n.exports.compose=e.compose,Object.defineProperty(e,"promises",{configurable:!0,enumerable:!0,get(){return t}}),n.exports.Stream=e.Stream,n.exports.default=n.exports})(browser)),browser.exports}var browserExports=requireBrowser();const ITERATOR=Symbol("iter");function merge$1(n,e,t=4){if(t===0)return Object.assign(n,e);for(const r in e)n[r]=merge$1(n[r]||Object.create(null),e[r],t-1);return n}function intersect(n,e,t=4){let r=!1;for(const i in n)if(i in e){const s=t===0?null:intersect(n[i],e[i],t-1);if(s!==!1)r=r||Object.create(null),r[i]=s;else if(t===3)return!1}return r}function difference(n,e,t=4){let r=!1;for(const i in n)if(!(i in e))r=r||Object.create(null),r[i]=t===0?null:merge$1({},n[i],t-1);else if(t!==0){const s=difference(n[i],e[i],t-1);if(s!==!1)r=r||Object.create(null),r[i]=s;else if(t===3)return!1}return r}class N3EntityIndex{constructor(e={}){this._id=1,this._ids=Object.create(null),this._ids[""]=1,this._entities=Object.create(null),this._entities[1]="",this._blankNodeIndex=0,this._factory=e.factory||DataFactory}_termFromId(e){if(e[0]==="."){const t=this._entities,r=e.split(".");return this._factory.quad(this._termFromId(t[r[1]]),this._termFromId(t[r[2]]),this._termFromId(t[r[3]]),r[4]&&this._termFromId(t[r[4]]))}return termFromId(e,this._factory)}_termToNumericId(e){if(e.termType==="Quad"){const t=this._termToNumericId(e.subject),r=this._termToNumericId(e.predicate),i=this._termToNumericId(e.object);let s;return t&&r&&i&&(isDefaultGraph(e.graph)||(s=this._termToNumericId(e.graph)))&&this._ids[s?`.${t}.${r}.${i}.${s}`:`.${t}.${r}.${i}`]}return this._ids[termToId(e)]}_termToNewNumericId(e){const t=e&&e.termType==="Quad"?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${isDefaultGraph(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:termToId(e);return this._ids[t]||(this._ids[this._entities[++this._id]=t]=this._id)}createBlankNode(e){let t,r;if(e)for(t=e=`_:${e}`,r=1;this._ids[t];)t=e+r++;else do t=`_:b${this._blankNodeIndex++}`;while(this._ids[t]);return this._ids[t]=++this._id,this._entities[this._id]=t,this._factory.blankNode(t.substr(2))}}class N3Store{constructor(e,t){this._size=0,this._graphs=Object.create(null),!t&&e&&!e[0]&&typeof e.match!="function"&&(t=e,e=null),t=t||{},this._factory=t.factory||DataFactory,this._entityIndex=t.entityIndex||new N3EntityIndex({factory:this._factory}),this._entities=this._entityIndex._entities,this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex),this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex),this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex),e&&this.addAll(e)}get size(){let e=this._size;if(e!==null)return e;e=0;const t=this._graphs;let r,i;for(const s in t)for(const o in r=t[s].subjects)for(const a in i=r[o])e+=Object.keys(i[a]).length;return this._size=e}_addToIndex(e,t,r,i){const s=e[t]||(e[t]={}),o=s[r]||(s[r]={}),a=i in o;return a||(o[i]=null),!a}_removeFromIndex(e,t,r,i){const s=e[t],o=s[r];delete o[i];for(const a in o)return;delete s[r];for(const a in s)return;delete e[t]}*_findInIndex(e,t,r,i,s,o,a,u){let c,l,d;const f=this._entities,m=this._termFromId(f[u]),g={subject:null,predicate:null,object:null};t&&((c=e,e={})[t]=c[t]);for(const b in e)if(l=e[b]){g[s]=this._termFromId(f[b]),r&&((c=l,l={})[r]=c[r]);for(const S in l)if(d=l[S]){g[o]=this._termFromId(f[S]);const w=i?i in d?[i]:[]:Object.keys(d);for(let v=0;v<w.length;v++)g[a]=this._termFromId(f[w[v]]),yield this._factory.quad(g.subject,g.predicate,g.object,m)}}}_loop(e,t){for(const r in e)t(r)}_loopByKey0(e,t,r){let i,s;if(i=e[t])for(s in i)r(s)}_loopByKey1(e,t,r){let i,s;for(i in e)s=e[i],s[t]&&r(i)}_loopBy2Keys(e,t,r,i){let s,o,a;if((s=e[t])&&(o=s[r]))for(a in o)i(a)}_countInIndex(e,t,r,i){let s=0,o,a,u;t&&((o=e,e={})[t]=o[t]);for(const c in e)if(a=e[c]){r&&((o=a,a={})[r]=o[r]);for(const l in a)(u=a[l])&&(i?i in u&&s++:s+=Object.keys(u).length)}return s}_getGraphs(e){return e=e===""?1:e&&(this._termToNumericId(e)||-1),typeof e!="number"?this._graphs:{[e]:this._graphs[e]}}_uniqueEntities(e){const t=Object.create(null);return r=>{r in t||(t[r]=!0,e(this._termFromId(this._entities[r],this._factory)))}}add(e){return this.addQuad(e),this}addQuad(e,t,r,i){t||(i=e.graph,r=e.object,t=e.predicate,e=e.subject),i=i?this._termToNewNumericId(i):1;let s=this._graphs[i];return s||(s=this._graphs[i]={subjects:{},predicates:{},objects:{}},Object.freeze(s)),e=this._termToNewNumericId(e),t=this._termToNewNumericId(t),r=this._termToNewNumericId(r),this._addToIndex(s.subjects,e,t,r)?(this._addToIndex(s.predicates,t,r,e),this._addToIndex(s.objects,r,e,t),this._size=null,!0):!1}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}delete(e){return this.removeQuad(e),this}has(e,t,r,i){return e&&e.subject&&({subject:e,predicate:t,object:r,graph:i}=e),!this.readQuads(e,t,r,i).next().done}import(e){return e.on("data",t=>{this.addQuad(t)}),e}removeQuad(e,t,r,i){t||({subject:e,predicate:t,object:r,graph:i}=e),i=i?this._termToNumericId(i):1;const s=this._graphs;let o,a,u;if(!(e=e&&this._termToNumericId(e))||!(t=t&&this._termToNumericId(t))||!(r=r&&this._termToNumericId(r))||!(o=s[i])||!(a=o.subjects[e])||!(u=a[t])||!(r in u))return!1;this._removeFromIndex(o.subjects,e,t,r),this._removeFromIndex(o.predicates,t,r,e),this._removeFromIndex(o.objects,r,e,t),this._size!==null&&this._size--;for(e in o.subjects)return!0;return delete s[i],!0}removeQuads(e){for(let t=0;t<e.length;t++)this.removeQuad(e[t])}remove(e){return e.on("data",t=>{this.removeQuad(t)}),e}removeMatches(e,t,r,i){const s=new browserExports.Readable({objectMode:!0}),o=this.readQuads(e,t,r,i);return s._read=a=>{for(;--a>=0;){const{done:u,value:c}=o.next();if(u){s.push(null);return}s.push(c)}},this.remove(s)}deleteGraph(e){return this.removeMatches(null,null,null,e)}getQuads(e,t,r,i){return[...this.readQuads(e,t,r,i)]}*readQuads(e,t,r,i){const s=this._getGraphs(i);let o,a,u,c;if(!(e&&!(a=this._termToNumericId(e))||t&&!(u=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(const l in s)(o=s[l])&&(a?c?yield*this._findInIndex(o.objects,c,a,u,"object","subject","predicate",l):yield*this._findInIndex(o.subjects,a,u,null,"subject","predicate","object",l):u?yield*this._findInIndex(o.predicates,u,c,null,"predicate","object","subject",l):c?yield*this._findInIndex(o.objects,c,null,null,"object","subject","predicate",l):yield*this._findInIndex(o.subjects,null,null,null,"subject","predicate","object",l))}match(e,t,r,i){return new DatasetCoreAndReadableStream(this,e,t,r,i,{entityIndex:this._entityIndex})}countQuads(e,t,r,i){const s=this._getGraphs(i);let o=0,a,u,c,l;if(e&&!(u=this._termToNumericId(e))||t&&!(c=this._termToNumericId(t))||r&&!(l=this._termToNumericId(r)))return 0;for(const d in s)(a=s[d])&&(e?r?o+=this._countInIndex(a.objects,l,u,c):o+=this._countInIndex(a.subjects,u,c,l):t?o+=this._countInIndex(a.predicates,c,l,u):o+=this._countInIndex(a.objects,l,u,c));return o}forEach(e,t,r,i,s){this.some(o=>(e(o,this),!1),t,r,i,s)}every(e,t,r,i,s){return!this.some(o=>!e(o,this),t,r,i,s)}some(e,t,r,i,s){for(const o of this.readQuads(t,r,i,s))if(e(o,this))return!0;return!1}getSubjects(e,t,r){const i=[];return this.forSubjects(s=>{i.push(s)},e,t,r),i}forSubjects(e,t,r,i){const s=this._getGraphs(i);let o,a,u;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(u=this._termToNumericId(r))))for(i in s)(o=s[i])&&(a?u?this._loopBy2Keys(o.predicates,a,u,e):this._loopByKey1(o.subjects,a,e):u?this._loopByKey0(o.objects,u,e):this._loop(o.subjects,e))}getPredicates(e,t,r){const i=[];return this.forPredicates(s=>{i.push(s)},e,t,r),i}forPredicates(e,t,r,i){const s=this._getGraphs(i);let o,a,u;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(u=this._termToNumericId(r))))for(i in s)(o=s[i])&&(a?u?this._loopBy2Keys(o.objects,u,a,e):this._loopByKey0(o.subjects,a,e):u?this._loopByKey1(o.predicates,u,e):this._loop(o.predicates,e))}getObjects(e,t,r){const i=[];return this.forObjects(s=>{i.push(s)},e,t,r),i}forObjects(e,t,r,i){const s=this._getGraphs(i);let o,a,u;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(u=this._termToNumericId(r))))for(i in s)(o=s[i])&&(a?u?this._loopBy2Keys(o.subjects,a,u,e):this._loopByKey1(o.objects,a,e):u?this._loopByKey0(o.predicates,u,e):this._loop(o.objects,e))}getGraphs(e,t,r){const i=[];return this.forGraphs(s=>{i.push(s)},e,t,r),i}forGraphs(e,t,r,i){for(const s in this._graphs)this.some(o=>(e(o.graph),!0),t,r,i,this._termFromId(this._entities[s]))}createBlankNode(e){return this._entityIndex.createBlankNode(e)}extractLists({remove:e=!1,ignoreErrors:t=!1}={}){const r={},i=t?(()=>!0):((a,u)=>{throw new Error(`${a.value} ${u}`)}),s=this.getQuads(null,namespaces$1.rdf.rest,namespaces$1.rdf.nil,null),o=e?[...s]:[];return s.forEach(a=>{const u=[];let c=!1,l,d;const f=a.graph;let m=a.subject;for(;m&&!c;){const g=this.getQuads(null,null,m,null),b=this.getQuads(m,null,null,null);let S,w=null,v=null,_=null;for(let T=0;T<b.length&&!c;T++)S=b[T],S.graph.equals(f)?l?c=i(m,"has non-list arcs out"):S.predicate.value===namespaces$1.rdf.first?w?c=i(m,"has multiple rdf:first arcs"):o.push(w=S):S.predicate.value===namespaces$1.rdf.rest?v?c=i(m,"has multiple rdf:rest arcs"):o.push(v=S):g.length?c=i(m,"can't be subject and object"):(l=S,d="subject"):c=i(m,"not confined to single graph");for(let T=0;T<g.length&&!c;++T)S=g[T],l?c=i(m,"can't have coreferences"):S.predicate.value===namespaces$1.rdf.rest?_?c=i(m,"has incoming rdf:rest arcs"):_=S:(l=S,d="object");w?u.unshift(w.object):c=i(m,"has no list head"),m=_&&_.subject}c?e=!1:l&&(r[l[d].value]=u)}),e&&this.removeQuads(o),r}addAll(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),Array.isArray(e))this.addQuads(e);else if(e instanceof N3Store&&e._entityIndex===this._entityIndex)e._size!==0&&(this._graphs=merge$1(this._graphs,e._graphs),this._size=null);else for(const t of e)this.add(t);return this}contains(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return!0;if(!(e instanceof N3Store)||this._entityIndex!==e._entityIndex)return e.every(c=>this.has(c));const t=this._graphs,r=e._graphs;let i,s,o,a,u;for(const c in r){if(!(i=t[c]))return!1;i=i.subjects;for(const l in s=r[c].subjects){if(!(o=i[l]))return!1;for(const d in a=s[l]){if(!(u=o[d]))return!1;for(const f in a[d])if(!(f in u))return!1}}}return!0}deleteMatches(e,t,r,i){for(const s of this.match(e,t,r,i))this.removeQuad(s);return this}difference(e){if(e&&e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return new N3Store({entityIndex:this._entityIndex});if(e instanceof N3Store&&e._entityIndex===this._entityIndex){const t=new N3Store({entityIndex:this._entityIndex}),r=difference(this._graphs,e._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter(t=>!e.has(t))}equals(e){return e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new N3Store({entityIndex:this._entityIndex});for(const r of this)e(r,this)&&t.add(r);return t}intersection(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this){const t=new N3Store({entityIndex:this._entityIndex});return t._graphs=merge$1(Object.create(null),this._graphs),t._size=this._size,t}else if(e instanceof N3Store&&this._entityIndex===e._entityIndex){const t=new N3Store({entityIndex:this._entityIndex}),r=intersect(e._graphs,this._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter(t=>e.has(t))}map(e){const t=new N3Store({entityIndex:this._entityIndex});for(const r of this)t.add(e(r,this));return t}reduce(e,t){const r=this.readQuads();let i=t===void 0?r.next().value:t;for(const s of r)i=e(i,s,this);return i}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match()}toString(){return new N3Writer().quadsToString(this)}union(e){const t=new N3Store({entityIndex:this._entityIndex});return t._graphs=merge$1(Object.create(null),this._graphs),t._size=this._size,t.addAll(e),t}*[Symbol.iterator](){yield*this.readQuads()}}function indexMatch(n,e,t=0){const r=e[t];if(r&&!(r in n))return!1;let i=!1;for(const s in r?{[r]:n[r]}:n){const o=t===2?null:indexMatch(n[s],e,t+1);o!==!1&&(i=i||Object.create(null),i[s]=o)}return i}class DatasetCoreAndReadableStream extends browserExports.Readable{constructor(e,t,r,i,s,o){super({objectMode:!0}),Object.assign(this,{n3Store:e,subject:t,predicate:r,object:i,graph:s,options:o})}get filtered(){if(!this._filtered){const{n3Store:e,graph:t,object:r,predicate:i,subject:s}=this,o=this._filtered=new N3Store({factory:e._factory,entityIndex:this.options.entityIndex});let a,u,c;if(s&&!(a=o._termToNumericId(s))||i&&!(u=o._termToNumericId(i))||r&&!(c=o._termToNumericId(r)))return o;const l=e._getGraphs(t);for(const d in l){let f,m,g,b;(b=l[d])&&(!a&&u?(m=indexMatch(b.predicates,[u,c,a]))&&(f=indexMatch(b.subjects,[a,u,c]),g=indexMatch(b.objects,[c,a,u])):c?(g=indexMatch(b.objects,[c,a,u]))&&(f=indexMatch(b.subjects,[a,u,c]),m=indexMatch(b.predicates,[u,c,a])):(f=indexMatch(b.subjects,[a,u,c]))&&(m=indexMatch(b.predicates,[u,c,a]),g=indexMatch(b.objects,[c,a,u])),f&&(o._graphs[d]={subjects:f,predicates:m,objects:g}))}o._size=null}return this._filtered}get size(){return this.filtered.size}_read(e){e>0&&!this[ITERATOR]&&(this[ITERATOR]=this[Symbol.iterator]());const t=this[ITERATOR];for(;--e>=0;){const{done:r,value:i}=t.next();if(r){this.push(null);return}this.push(i)}}addAll(e){return this.filtered.addAll(e)}contains(e){return this.filtered.contains(e)}deleteMatches(e,t,r,i){return this.filtered.deleteMatches(e,t,r,i)}difference(e){return this.filtered.difference(e)}equals(e){return this.filtered.equals(e)}every(e,t,r,i,s){return this.filtered.every(e,t,r,i,s)}filter(e){return this.filtered.filter(e)}forEach(e,t,r,i,s){return this.filtered.forEach(e,t,r,i,s)}import(e){return this.filtered.import(e)}intersection(e){return this.filtered.intersection(e)}map(e){return this.filtered.map(e)}some(e,t,r,i,s){return this.filtered.some(e,t,r,i,s)}toCanonical(){return this.filtered.toCanonical()}toStream(){return this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph)}union(e){return this._filtered?this._filtered.union(e):this.n3Store.match(this.subject,this.predicate,this.object,this.graph).addAll(e)}toArray(){return this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(e,t){return this.filtered.reduce(e,t)}toString(){return new N3Writer().quadsToString(this)}add(e){return this.filtered.add(e)}delete(e){return this.filtered.delete(e)}has(e){return this.filtered.has(e)}match(e,t,r,i){return new DatasetCoreAndReadableStream(this.filtered,e,t,r,i,this.options)}*[Symbol.iterator](){yield*this._filtered||this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}}const getTurtleParser=()=>{const n=[],e=[],t=[];return{onQuad:r=>{n.push(r)},onError:r=>{t.push(r)},onComplete:r=>{e.push(r)},parse:(r,i)=>{getParser(getSourceUrl(i)).parse(r,(s,o)=>{s?t.forEach(a=>a(s)):o?n.forEach(a=>a(o)):e.forEach(a=>a())})}}};function getParser(n){return new N3Parser({format:"text/turtle",baseIRI:n})}async function triplesToTurtle(n,e){const t="text/turtle",r=new N3Writer({format:t,prefixes:e?.prefixes}),i=n.map(a=>DataFactory.quad(a.subject,a.predicate,a.object,void 0));return r.addQuads(i),await new Promise((a,u)=>{r.end((c,l)=>{c?u(c):a(l)})})}const localNodeSkolemPrefix="https://inrupt.com/.well-known/sdk-local-node/",{freeze}=Object;function isLocalNodeIri(n){return n.substring(0,localNodeSkolemPrefix.length)===localNodeSkolemPrefix}function getLocalNodeName(n){return n.substring(localNodeSkolemPrefix.length)}function getLocalNodeIri(n){return`${localNodeSkolemPrefix}${n}`}function isBlankNodeId(n){return typeof n=="string"&&n.substring(0,2)==="_:"}function getBlankNodeValue(n){return n.substring(2)}function getBlankNodeId(n){return`_:${n.value}`}const xmlSchemaTypes={boolean:"http://www.w3.org/2001/XMLSchema#boolean",dateTime:"http://www.w3.org/2001/XMLSchema#dateTime",date:"http://www.w3.org/2001/XMLSchema#date",time:"http://www.w3.org/2001/XMLSchema#time",decimal:"http://www.w3.org/2001/XMLSchema#decimal",integer:"http://www.w3.org/2001/XMLSchema#integer",string:"http://www.w3.org/2001/XMLSchema#string",langString:"http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"};function serializeBoolean(n){return n?"true":"false"}function deserializeBoolean(n){return n==="true"||n==="1"?!0:n==="false"||n==="0"?!1:null}function serializeTime(n){let e,t;if(n.millisecond&&(n.millisecond<10?e=`00${n.millisecond}`:n.millisecond<100?e=`0${n.millisecond}`:e=n.millisecond),typeof n.timezoneHourOffset=="number"){const r=Math.abs(n.timezoneHourOffset)<10?`0${Math.abs(n.timezoneHourOffset)}`:Math.abs(n.timezoneHourOffset);t=n.timezoneHourOffset>=0?`+${r}`:`-${r}`,n.timezoneMinuteOffset?t=`${t}:${n.timezoneMinuteOffset<10?`0${n.timezoneMinuteOffset}`:n.timezoneMinuteOffset}`:t+=":00"}return`${n.hour<10?`0${n.hour}`:n.hour}:${n.minute<10?`0${n.minute}`:n.minute}:${n.second<10?`0${n.second}`:n.second}${n.millisecond?`.${e}`:""}${t||""}`}function deserializeTime(n){if(!/\d\d:\d\d:\d\d(\.\d+)?(Z|(\+|-)\d\d:\d\d)?/.test(n))return null;const[t,r]=splitTimeFromTimezone(n),[i,s,o]=t.split(":");let a=Number.parseInt(i,10),u=Number.parseInt(s,10);const[c,l]=o.split("."),d=Number.parseInt(c,10),f=l?Number.parseInt(l,10):void 0;u>=60&&(a+=1,u-=60);const m={hour:a,minute:u,second:d};if(typeof f=="number"&&(m.millisecond=f),typeof r=="string"){const[g,b]=getTimezoneOffsets(r);if(typeof g!="number"||g>24||typeof b!="number"||b>59)return null;m.timezoneHourOffset=g,m.timezoneMinuteOffset=b}return m}function serializeDatetime(n){return n.toISOString()}function deserializeDatetime(n){if(!/-?\d{4,}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|(\+|-)\d\d:\d\d)?/.test(n))return null;const[t,r]=n.split("T"),[i,s]=t.charAt(0)==="-"?[-1,t.substring(1)]:[1,t],[o,a,u]=s.split("-"),c=Number.parseInt(o,10)*i,l=Number.parseInt(a,10)-1,d=Number.parseInt(u,10),[f,m]=splitTimeFromTimezone(r),[g,b]=typeof m=="string"?getTimezoneOffsets(m):[0,0],[S,w,v]=f.split(":"),_=Number.parseInt(S,10)+g,T=Number.parseInt(w,10)+b,[C,U]=v.split("."),$=Number.parseInt(C,10),W=U?Number.parseInt(U,10):0,re=new Date(Date.UTC(c,l,d,_,T,$,W));return c>=0&&c<100&&re.setUTCFullYear(re.getUTCFullYear()-1900),re}function serializeDate(n){const e=n.getFullYear(),t=n.getMonth()+1,r=n.getDate(),[,i]=splitTimeFromTimezone(n.toISOString());return`${e}-${String(t).padStart(2,"0")}-${String(r).padStart(2,"0")}${i}`}function deserializeDate(n){if(!/-?\d{4,}-\d\d-\d\d(Z|(\+|-)\d\d:\d\d)?/.test(n))return null;const t=n,[r,i]=t.charAt(0)==="-"?[-1,t.substring(1)]:[1,t],[s,o,a]=i.split("-"),u=a.length>2?a.substring(0,2):a,c=Number.parseInt(s,10)*r,l=Number.parseInt(o,10)-1,d=Number.parseInt(u,10),f=12,m=new Date(Date.UTC(c,l,d,f));return c>=0&&c<100&&m.setUTCFullYear(m.getUTCFullYear()-1900),m}function splitTimeFromTimezone(n){if(n.endsWith("Z"))return[n.substring(0,n.length-1),"Z"];const e=n.split("+"),t=n.split("-");return e.length===1&&t.length===1?[e[0],void 0]:e.length>t.length?[e[0],`+${e[1]}`]:[t[0],`-${t[1]}`]}function getTimezoneOffsets(n){if(n==="Z")return[0,0];const e=n.charAt(0)==="+"?1:-1,[t,r]=n.substring(1).split(":"),i=Number.parseInt(t,10),s=Number.parseInt(r,10);return[i*e,s*e]}function serializeDecimal(n){return n.toString()}function deserializeDecimal(n){const e=Number.parseFloat(n);return Number.isNaN(e)?null:e}function serializeInteger(n){return n.toString()}function deserializeInteger(n){const e=Number.parseInt(n,10);return Number.isNaN(e)?null:e}function normalizeLocale(n){return n.toLowerCase()}function isNamedNode(n){return isTerm(n)&&n.termType==="NamedNode"}function isLiteral(n){return isTerm(n)&&n.termType==="Literal"}function isTerm(n){return n!==null&&typeof n=="object"&&typeof n.termType=="string"&&typeof n.value=="string"&&typeof n.equals=="function"}function isLocalNode(n){return isNamedNode(n)&&isLocalNodeIri(n.value)}function internal_isValidUrl(n){const e=internal_toIriString(n);if(typeof URL!="function")return!0;try{return new URL(e),!0}catch{return!1}}function resolveIriForLocalNode(n,e){return DataFactory.namedNode(resolveLocalIri(getLocalNodeName(n.value),e))}function resolveLocalIri(n,e){if(typeof URL!="function")throw new Error("The URL interface is not available, so an IRI cannot be determined.");const t=new URL(e);return t.hash=n,t.href}function addRdfJsQuadToDataset(n,e){var t;if(!["NamedNode","DefaultGraph"].includes(e.graph.termType))throw new Error(`Cannot parse Quads with nodes of type [${e.graph.termType}] as their Graph node.`);const i=e.graph.termType==="DefaultGraph"?"default":e.graph.value,s=(t=n.graphs[i])!==null&&t!==void 0?t:{};return freeze({...n,graphs:freeze({...n.graphs,[i]:addRdfJsQuadToGraph(s,e)})})}function addRdfJsQuadToGraph(n,e){var t;if(!["NamedNode","BlankNode"].includes(e.subject.termType))throw new Error(`Cannot parse Quads with nodes of type [${e.subject.termType}] as their Subject node.`);const i=e.subject.termType==="BlankNode"?`_:${e.subject.value}`:e.subject.value,s=(t=n[i])!==null&&t!==void 0?t:{type:"Subject",url:i,predicates:{}};return freeze({...n,[i]:addRdfJsQuadToSubject(s,e)})}function addRdfJsQuadToSubject(n,e){return freeze({...n,predicates:addRdfJsQuadToPredicates(n.predicates,e)})}function addRdfJsQuadToPredicates(n,e){var t;if(!["NamedNode"].includes(e.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${e.predicate.termType}] as their Predicate node.`);const i=e.predicate.value,s=(t=n[i])!==null&&t!==void 0?t:{};return freeze({...n,[i]:addRdfJsQuadToObjects(s,e)})}function addRdfJsQuadToObjects(n,e){var t,r,i,s,o,a,u,c;if(e.object.termType==="NamedNode"){const l=freeze([...(t=n.namedNodes)!==null&&t!==void 0?t:[],e.object.value]);return freeze({...n,namedNodes:l})}if(e.object.termType==="Literal"){if(e.object.datatype.value===xmlSchemaTypes.langString){const f=e.object.language.toLowerCase(),m=freeze([...(i=(r=n.langStrings)===null||r===void 0?void 0:r[f])!==null&&i!==void 0?i:[],e.object.value]),g=freeze({...(s=n.langStrings)!==null&&s!==void 0?s:{},[f]:m});return freeze({...n,langStrings:g})}const l=freeze([...(a=(o=n.literals)===null||o===void 0?void 0:o[e.object.datatype.value])!==null&&a!==void 0?a:[],e.object.value]),d=freeze({...(u=n.literals)!==null&&u!==void 0?u:{},[e.object.datatype.value]:l});return freeze({...n,literals:d})}if(e.object.termType==="BlankNode"){const l=freeze([...(c=n.blankNodes)!==null&&c!==void 0?c:[],getBlankNodeId(e.object)]);return freeze({...n,blankNodes:l})}throw new Error(`Objects of type [${e.object.termType}] are not supported.`)}function toRdfJsQuads(n,e={}){var t;const r=[],i=(t=e.dataFactory)!==null&&t!==void 0?t:DataFactory;return Object.keys(n.graphs).forEach(s=>{const o=n.graphs[s],a=s==="default"?i.defaultGraph():i.namedNode(s);Object.keys(o).forEach(u=>{const{predicates:c}=o[u],l=isBlankNodeId(u)?i.blankNode(getBlankNodeValue(u)):i.namedNode(u);r.push(...subjectToRdfJsQuads(c,l,a,e))})}),r}function subjectToRdfJsQuads(n,e,t,r={}){var i;const s=[],o=(i=r.dataFactory)!==null&&i!==void 0?i:DataFactory;return Object.keys(n).forEach(a=>{var u,c,l,d;const f=o.namedNode(a),m=(u=n[a].langStrings)!==null&&u!==void 0?u:{},g=(c=n[a].namedNodes)!==null&&c!==void 0?c:[],b=(l=n[a].literals)!==null&&l!==void 0?l:{},S=(d=n[a].blankNodes)!==null&&d!==void 0?d:[];Object.keys(b).forEach(_=>{const T=o.namedNode(_);b[_].forEach(U=>{const $=o.literal(U,T);s.push(o.quad(e,f,$,t))})}),Object.keys(m).forEach(_=>{m[_].forEach(C=>{const U=o.literal(C,_);s.push(o.quad(e,f,U,t))})}),g.forEach(_=>{const T=o.namedNode(_);s.push(o.quad(e,f,T,t))}),S.forEach(_=>{if(isBlankNodeId(_)){const T=o.blankNode(getBlankNodeValue(_));s.push(o.quad(e,f,T,t))}else{const T=o.blankNode(),C=o.quad(e,f,T,t),U=subjectToRdfJsQuads(_,T,t);s.push(C),s.push(...U)}})}),s}function fromRdfJsDataset(n){const e={graphs:{default:{}},type:"Dataset"};return Array.from(n).reduce((t,r)=>addRdfJsQuadToDataset(t,r),e)}const byteToHex=[];for(let n=0;n<256;++n)byteToHex.push((n+256).toString(16).slice(1));function unsafeStringify(n,e=0){return(byteToHex[n[e+0]]+byteToHex[n[e+1]]+byteToHex[n[e+2]]+byteToHex[n[e+3]]+"-"+byteToHex[n[e+4]]+byteToHex[n[e+5]]+"-"+byteToHex[n[e+6]]+byteToHex[n[e+7]]+"-"+byteToHex[n[e+8]]+byteToHex[n[e+9]]+"-"+byteToHex[n[e+10]]+byteToHex[n[e+11]]+byteToHex[n[e+12]]+byteToHex[n[e+13]]+byteToHex[n[e+14]]+byteToHex[n[e+15]]).toLowerCase()}let getRandomValues;const rnds8=new Uint8Array(16);function rng(){if(!getRandomValues){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");getRandomValues=crypto.getRandomValues.bind(crypto)}return getRandomValues(rnds8)}const randomUUID=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),native={randomUUID};function v4(n,e,t){if(native.randomUUID&&!n)return native.randomUUID();n=n||{};const r=n.random??n.rng?.()??rng();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,unsafeStringify(r)}function internal_getReadableValue(n){var e,t,r,i,s,o,a,u;if(isNamedNode(n))return`<${n.value}> (URL)`;if(isLiteral(n)){if(!isNamedNode(n.datatype))return`[${n.value}] (RDF/JS Literal of unknown type)`;let c;switch(n.datatype.value){case xmlSchemaTypes.boolean:return c=(t=(e=deserializeBoolean(n.value))===null||e===void 0?void 0:e.valueOf())!==null&&t!==void 0?t:`Invalid data: \`${n.value}\``,`${c} (boolean)`;case xmlSchemaTypes.dateTime:return c=(i=(r=deserializeDatetime(n.value))===null||r===void 0?void 0:r.toUTCString())!==null&&i!==void 0?i:`Invalid data: \`${n.value}\``,`${c} (datetime)`;case xmlSchemaTypes.decimal:return c=(o=(s=deserializeDecimal(n.value))===null||s===void 0?void 0:s.toString())!==null&&o!==void 0?o:`Invalid data: \`${n.value}\``,`${c} (decimal)`;case xmlSchemaTypes.integer:return c=(u=(a=deserializeInteger(n.value))===null||a===void 0?void 0:a.toString())!==null&&u!==void 0?u:`Invalid data: \`${n.value}\``,`${c} (integer)`;case xmlSchemaTypes.langString:return`"${n.value}" (${n.language} string)`;case xmlSchemaTypes.string:return`"${n.value}" (string)`;default:return`[${n.value}] (RDF/JS Literal of type: \`${n.datatype.value}\`)`}}return n.termType==="BlankNode"?`[${n.value}] (RDF/JS BlankNode)`:n.termType==="Quad"?"??? (nested RDF* Quad)":n.termType==="Variable"?`?${n.value} (RDF/JS Variable)`:n}function internal_throwIfNotThing(n){if(!isThing(n))throw new ThingExpectedError(n)}function internal_addAdditionsToChangeLog(n,e){const t=hasChangelog(n)?n.internal_changeLog:{additions:[],deletions:[]},[r,i]=e.filter(s=>!containsBlankNode(s)).reduce(([s,o],a)=>typeof o.find(c=>c.equals(a))<"u"?[s,o.filter(c=>!c.equals(a))]:[s.concat(a),o],[t.additions,t.deletions]);return freeze({...n,internal_changeLog:{additions:r,deletions:i}})}function internal_addDeletionsToChangeLog(n,e){const t=hasChangelog(n)?n.internal_changeLog:{additions:[],deletions:[]},[r,i]=e.filter(s=>!containsBlankNode(s)).reduce(([s,o],a)=>typeof s.find(c=>c.equals(a))<"u"?[s.filter(c=>!c.equals(a)),o]:[s,o.concat(a)],[t.additions,t.deletions]);return freeze({...n,internal_changeLog:{additions:r,deletions:i}})}function internal_withChangeLog(n){return hasChangelog(n)?n:freeze({...n,internal_changeLog:{additions:[],deletions:[]}})}function containsBlankNode(n){return n.subject.termType==="BlankNode"||n.object.termType==="BlankNode"}function getUrl(n,e){var t,r,i;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const s=internal_toIriString(e),o=(i=(r=(t=n.predicates[s])===null||t===void 0?void 0:t.namedNodes)===null||r===void 0?void 0:r[0])!==null&&i!==void 0?i:null;return o===null?null:isLocalNodeIri(o)?`#${getLocalNodeName(o)}`:o}const getIri=getUrl;function getUrlAll(n,e){var t,r,i;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const s=internal_toIriString(e);return(i=(r=(t=n.predicates[s])===null||t===void 0?void 0:t.namedNodes)===null||r===void 0?void 0:r.map(o=>isLocalNodeIri(o)?`#${getLocalNodeName(o)}`:o))!==null&&i!==void 0?i:[]}const getIriAll=getUrlAll;function getStringNoLocale(n,e){return internal_throwIfNotThing(n),getLiteralOfType(n,e,xmlSchemaTypes.string)}function getNamedNodeAll(n,e){return getIriAll(n,e).map(r=>DataFactory.namedNode(r))}function getLiteralAll(n,e){var t,r,i,s;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const o=internal_toIriString(e);let a=[];const u=(r=(t=n.predicates[o])===null||t===void 0?void 0:t.langStrings)!==null&&r!==void 0?r:{},c=Object.keys(u);for(const f of c){const g=u[f].map(b=>DataFactory.literal(b,f));a=a.concat(g)}const l=(s=(i=n.predicates[o])===null||i===void 0?void 0:i.literals)!==null&&s!==void 0?s:{},d=Object.keys(l);for(const f of d){const m=l[f],g=DataFactory.namedNode(f),b=m.map(S=>DataFactory.literal(S,g));a=a.concat(b)}return a}function getTermAll(n,e){var t,r;internal_throwIfNotThing(n);const i=getNamedNodeAll(n,e),s=getLiteralAll(n,e),o=internal_toIriString(e),u=((r=(t=n.predicates[o])===null||t===void 0?void 0:t.blankNodes)!==null&&r!==void 0?r:[]).map(l=>{const d=isBlankNodeId(l)?getBlankNodeValue(l):void 0;return DataFactory.blankNode(d)});return i.concat(s).concat(u)}function getLiteralOfType(n,e,t){var r,i,s,o;if(!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const a=internal_toIriString(e);return(o=(s=(i=(r=n.predicates[a])===null||r===void 0?void 0:r.literals)===null||i===void 0?void 0:i[t])===null||s===void 0?void 0:s[0])!==null&&o!==void 0?o:null}function getThing(n,e,t={}){var r;if(!internal_isValidUrl(e)&&!e.match(/^_:/))throw new ValidThingUrlExpectedError(e);const i=typeof t.scope<"u"?internal_toIriString(t.scope):"default",s=(r=n.graphs[i])!==null&&r!==void 0?r:{},o=internal_toIriString(e),a=isLocalNodeIri(o)&&hasServerResourceInfo(n)?resolveLocalIri(getLocalNodeName(o),getSourceUrl(n)):o,u=s[a];return typeof u>"u"?null:u}function getThingAll(n,e={acceptBlankNodes:!1}){var t;const r=typeof e.scope<"u"?internal_toIriString(e.scope):"default",i=(t=n.graphs[r])!==null&&t!==void 0?t:{};return Object.values(i).filter(s=>!isBlankNodeId(s.url)||e.acceptBlankNodes)}function setThing(n,e){var t;const r=isThingLocal(e)&&hasServerResourceInfo(n)?resolveLocalIri(getLocalNodeName(e.url),getSourceUrl(n)):e.url,i=n.graphs.default,s=freeze({...i,[r]:freeze({...e,url:r})}),o=freeze({...n.graphs,default:s}),a=DataFactory.namedNode(r),u=(t=n.graphs.default[r])===null||t===void 0?void 0:t.predicates,c=typeof u<"u"?subjectToRdfJsQuads(u,a,DataFactory.defaultGraph()):[],l=subjectToRdfJsQuads(e.predicates,a,DataFactory.defaultGraph());return internal_addAdditionsToChangeLog(internal_addDeletionsToChangeLog(freeze({...n,graphs:o}),c),l)}function removeThing(n,e){var t;let r;isNamedNode(e)?r=e.value:typeof e=="string"?r=isLocalNodeIri(e)&&hasServerResourceInfo(n)?resolveLocalIri(getLocalNodeName(e),getSourceUrl(n)):e:isThingLocal(e)?r=e.url:r=asIri(e);const s={...n.graphs.default};delete s[r];const o=freeze({...n.graphs,default:freeze(s)}),a=DataFactory.namedNode(r),u=(t=n.graphs.default[r])===null||t===void 0?void 0:t.predicates,c=typeof u<"u"?subjectToRdfJsQuads(u,a,DataFactory.defaultGraph()):[];return internal_addDeletionsToChangeLog(freeze({...n,graphs:o}),c)}function createThing(n={}){var e;if(typeof n.url<"u"){const{url:s}=n;if(!internal_isValidUrl(s))throw new ValidThingUrlExpectedError(s);return freeze({type:"Subject",predicates:freeze({}),url:s})}const t=(e=n.name)!==null&&e!==void 0?e:generateName(),r=getLocalNodeIri(t);return freeze({type:"Subject",predicates:freeze({}),url:r})}function isThing(n){return typeof n=="object"&&n!==null&&typeof n.type=="string"&&n.type==="Subject"}function asUrl(n,e){if(isThingLocal(n)){if(typeof e>"u")throw new Error("The URL of a Thing that has not been persisted cannot be determined without a base URL.");return resolveLocalIri(getLocalNodeName(n.url),e)}return n.url}const asIri=asUrl;function thingAsMarkdown(n){let e="";isThingLocal(n)?e+=`## Thing (no URL yet — identifier: \`#${getLocalNodeName(n.url)}\`)
|
|
98
|
+
`:e+=`## Thing: ${n.url}
|
|
99
|
+
`;const t=Object.keys(n.predicates);if(t.length===0)e+=`
|
|
100
|
+
<empty>
|
|
101
|
+
`;else for(const r of t){e+=`
|
|
102
|
+
Property: ${r}
|
|
103
|
+
`;const i=getTermAll(n,r);e+=i.reduce((s,o)=>`${s}- ${internal_getReadableValue(o)}
|
|
104
|
+
`,"")}return e}function isThingLocal(n){return isLocalNodeIri(n.url)}class ThingExpectedError extends SolidClientError{constructor(e){const t=`Expected a Thing, but received: [${e}].`;super(t),this.receivedValue=e}}class ValidPropertyUrlExpectedError extends SolidClientError{constructor(e){const t=isNamedNode(e)?e.value:e,r=`Expected a valid URL to identify a property, but received: [${t}].`;super(r),this.receivedProperty=t}}class ValidValueUrlExpectedError extends SolidClientError{constructor(e){const t=isNamedNode(e)?e.value:e,r=`Expected a valid URL value, but received: [${t}].`;super(r),this.receivedValue=t}}class ValidThingUrlExpectedError extends SolidClientError{constructor(e){const t=isNamedNode(e)?e.value:e,r=`Expected a valid URL to identify a Thing, but received: [${t}].`;super(r),this.receivedValue=t}}const generateName=()=>v4();function normalizeServerSideIri(n){const e=new URL(n);return e.hash="",e.href}function createSolidDataset(){return freeze({type:"Dataset",graphs:{default:{}}})}async function responseToSolidDataset(n,e={}){if(internal_isUnsuccessfulResponse(n)){const l=await n.clone().text();throw new FetchError(`Fetching the SolidDataset at [${n.url}] failed: [${n.status}] [${n.statusText}] ${l}.`,n,l)}const t=responseToResourceInfo(n),r={"text/turtle":getTurtleParser(),...e.parsers},i=getContentType(t);if(i===null)throw new Error(`Could not determine the content type of the Resource at [${getSourceUrl(t)}].`);const s=i.split(";")[0],o=r[s];if(typeof o>"u")throw new Error(`The Resource at [${getSourceUrl(t)}] has a MIME type of [${s}], but the only parsers available are for the following MIME types: [${Object.keys(r).join(", ")}].`);const a=await n.text(),u=await new Promise((l,d)=>{const f=new N3Store;o.onError(m=>{d(new Error(`Encountered an error parsing the Resource at [${getSourceUrl(t)}] with content type [${i}]: ${m}`))}),o.onQuad(m=>{f.add(m)}),o.onComplete(()=>{l(f)}),o.parse(a,t)}),c=freeze(fromRdfJsDataset(u));return freeze({...c,...t})}async function getSolidDataset(n,e){var t,r;const i=normalizeUrl(internal_toIriString(n)),s=Object.keys((t=e?.parsers)!==null&&t!==void 0?t:{}),o=s.length>0?s.join(", "):"text/turtle",a=await((r=e?.fetch)!==null&&r!==void 0?r:fetch)(i,{headers:{Accept:o}});if(internal_isUnsuccessfulResponse(a)){const c=await a.clone().text();throw new FetchError(`Fetching the Resource at [${i}] failed: [${a.status}] [${a.statusText}] ${c}.`,a,c)}return await responseToSolidDataset(a,e)}async function prepareSolidDatasetUpdate(n){const e=n.internal_changeLog.deletions.length>0?`DELETE DATA {${(await triplesToTurtle(n.internal_changeLog.deletions.map(getNamedNodesForLocalNodes))).trim()}};`:"",t=n.internal_changeLog.additions.length>0?`INSERT DATA {${(await triplesToTurtle(n.internal_changeLog.additions.map(getNamedNodesForLocalNodes))).trim()}};`:"";return{method:"PATCH",body:`${e} ${t}`,headers:{"Content-Type":"application/sparql-update"}}}async function prepareSolidDatasetCreation(n,e){return{method:"PUT",body:await triplesToTurtle(toRdfJsQuads(n).map(getNamedNodesForLocalNodes),e),headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:`<${ldp.Resource}>; rel="type"`}}}async function saveSolidDatasetAt(n,e,t){var r;const i=normalizeUrl(internal_toIriString(n)),s=internal_withChangeLog(e),o=isUpdate(s,i)?await prepareSolidDatasetUpdate(s):await prepareSolidDatasetCreation(s,t),a=await((r=t?.fetch)!==null&&r!==void 0?r:fetch)(i,o);if(internal_isUnsuccessfulResponse(a)){const d=isUpdate(s,i)?`The changes that were sent to the Pod are listed below.
|
|
105
|
+
|
|
106
|
+
${changeLogAsMarkdown(s)}`:`The SolidDataset that was sent to the Pod is listed below.
|
|
107
|
+
|
|
108
|
+
${solidDatasetAsMarkdown(s)}`,f=await a.clone().text();throw new FetchError(`Storing the Resource at [${i}] failed: [${a.status}] [${a.statusText}] ${f}.
|
|
109
|
+
|
|
110
|
+
${d}`,a,f)}const u={...internal_parseResourceInfo(a),isRawData:!1},c=freeze({...e,internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:u});return resolveLocalIrisInSolidDataset(c)}async function createContainerAt(n,e={}){var t,r;const i=normalizeUrl(internal_toIriString(n),{trailingSlash:!0}),s=await((t=e.fetch)!==null&&t!==void 0?t:fetch)(i,{method:"PUT",body:e.initialContent?await triplesToTurtle(toRdfJsQuads(e.initialContent).map(getNamedNodesForLocalNodes)):void 0,headers:{Accept:"text/turtle","Content-Type":"text/turtle","If-None-Match":"*",Link:`<${ldp.BasicContainer}>; rel="type"`}});if(internal_isUnsuccessfulResponse(s)){const u=e.initialContent===void 0?"empty":"non-empty",c=await s.clone().text();throw new FetchError(`Creating the ${u} Container at [${n}] failed: [${s.status}] [${s.statusText}] ${c}.`,s,c)}const o=internal_parseResourceInfo(s);return freeze({...(r=e.initialContent)!==null&&r!==void 0?r:createSolidDataset(),internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:o})}function isSourceIriEqualTo(n,e){return normalizeServerSideIri(n.internal_resourceInfo.sourceIri)===normalizeServerSideIri(e)}function isUpdate(n,e){return hasChangelog(n)&&hasResourceInfo(n)&&typeof n.internal_resourceInfo.sourceIri=="string"&&isSourceIriEqualTo(n,e)}function solidDatasetAsMarkdown(n){let e="";hasResourceInfo(n)?e+=`# SolidDataset: ${getSourceUrl(n)}
|
|
111
|
+
`:e+=`# SolidDataset (no URL yet)
|
|
112
|
+
`;const t=getThingAll(n);return t.length===0?e+=`
|
|
113
|
+
<empty>
|
|
114
|
+
`:t.forEach(r=>{e+=`
|
|
115
|
+
${thingAsMarkdown(r)}`,hasChangelog(n)&&(e+=`
|
|
116
|
+
${getReadableChangeLogSummary(n,r)}
|
|
117
|
+
`)}),e}function changeLogAsMarkdown(n){if(!hasResourceInfo(n))return"This is a newly initialized SolidDataset, so there is no source to compare it to.";if(!hasChangelog(n)||n.internal_changeLog.additions.length===0&&n.internal_changeLog.deletions.length===0)return`## Changes compared to ${getSourceUrl(n)}
|
|
118
|
+
|
|
119
|
+
This SolidDataset has not been modified since it was fetched from ${getSourceUrl(n)}.
|
|
120
|
+
`;let e=`## Changes compared to ${getSourceUrl(n)}
|
|
121
|
+
`;const t=sortChangeLogByThingAndProperty(n);return Object.keys(t).forEach(r=>{e+=`
|
|
122
|
+
### Thing: ${r}
|
|
123
|
+
`;const i=t[r];Object.keys(i).forEach(s=>{e+=`
|
|
124
|
+
Property: ${s}
|
|
125
|
+
`;const{deleted:o}=i[s],{added:a}=i[s];o.length>0&&(e+=`- Removed:
|
|
126
|
+
`,e+=o.reduce((u,c)=>`${u} - ${internal_getReadableValue(c)}
|
|
127
|
+
`,"")),a.length>0&&(e+=`- Added:
|
|
128
|
+
`,e+=a.reduce((u,c)=>`${u} - ${internal_getReadableValue(c)}
|
|
129
|
+
`,""))})}),e}function sortChangeLogByThingAndProperty(n){const e=Object.create(null);return n.internal_changeLog.deletions.forEach(t=>{var r,i,s;const o=isLocalNode(t.subject)?resolveIriForLocalNode(t.subject,getSourceUrl(n)):t.subject;if(!isNamedNode(o)||!isNamedNode(t.predicate))return;const a=internal_toIriString(o),u=internal_toIriString(t.predicate);(r=e[a])!==null&&r!==void 0||(e[a]=Object.create(null)),(i=(s=e[a])[u])!==null&&i!==void 0||(s[u]={added:[],deleted:[]}),e[a][u].deleted.push(t.object)}),n.internal_changeLog.additions.forEach(t=>{var r,i,s;const o=isLocalNode(t.subject)?resolveIriForLocalNode(t.subject,getSourceUrl(n)):t.subject;if(!isNamedNode(o)||!isNamedNode(t.predicate))return;const a=internal_toIriString(o),u=internal_toIriString(t.predicate);(r=e[a])!==null&&r!==void 0||(e[a]=Object.create(null)),(i=(s=e[a])[u])!==null&&i!==void 0||(s[u]={added:[],deleted:[]}),e[a][u].added.push(t.object)}),e}function getReadableChangeLogSummary(n,e){const t=DataFactory.namedNode(e.url),r=n.internal_changeLog.additions.reduce((a,u)=>u.subject.equals(t)?a+1:a,0),i=n.internal_changeLog.deletions.reduce((a,u)=>u.subject.equals(t)?a+1:a,0),s=r===1?"1 new value added":`${r} new values added`,o=i===1?"1 value removed":`${i} values removed`;return`(${s} / ${o})`}function getNamedNodesForLocalNodes(n){const e=isNamedNode(n.subject)?getNamedNodeFromLocalNode(n.subject):n.subject,t=isNamedNode(n.object)?getNamedNodeFromLocalNode(n.object):n.object;return DataFactory.quad(e,n.predicate,t,n.graph)}function getNamedNodeFromLocalNode(n){return isLocalNodeIri(n.value)?DataFactory.namedNode(`#${getLocalNodeName(n.value)}`):n}function resolveLocalIrisInSolidDataset(n){const e=getSourceUrl(n),t=n.graphs.default,i=Object.keys(t).reduce((o,a)=>{const u=resolveLocalIrisInThing(o[a],e),c=isLocalNodeIri(a)?`${e}#${getLocalNodeName(a)}`:a,l={...o};return delete l[a],l[c]=u,freeze(l)},t),s=freeze({...n.graphs,default:i});return freeze({...n,graphs:s})}function resolveLocalIrisInThing(n,e){const r=Object.keys(n.predicates).reduce((i,s)=>{var o;const a=(o=i[s].namedNodes)!==null&&o!==void 0?o:[];if(a.every(l=>!isLocalNodeIri(l)))return i;const u=freeze(a.map(l=>isLocalNodeIri(l)?`${e}#${getLocalNodeName(l)}`:l)),c=freeze({...i[s],namedNodes:u});return freeze({...i,[s]:c})},n.predicates);return freeze({...n,predicates:r,url:isLocalNodeIri(n.url)?`${e}#${getLocalNodeName(n.url)}`:n.url})}const addUrl=(n,e,t)=>{var r,i;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);if(!isThing(t)&&!internal_isValidUrl(t))throw new ValidValueUrlExpectedError(t);const s=internal_toIriString(e),o=(r=n.predicates[s])!==null&&r!==void 0?r:{},a=(i=o.namedNodes)!==null&&i!==void 0?i:[];let u;isNamedNode(t)?u=t.value:typeof t=="string"?u=t:isThingLocal(t)?u=t.url:u=asIri(t);const c=freeze(a.concat(internal_toIriString(u))),l=freeze({...o,namedNodes:c}),d=freeze({...n.predicates,[s]:l});return freeze({...n,predicates:d})},addIri=addUrl,addBoolean=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeBoolean(t),xmlSchemaTypes.boolean)),addDatetime=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeDatetime(t),xmlSchemaTypes.dateTime)),addDate=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeDate(t),xmlSchemaTypes.date)),addTime=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeTime(t),xmlSchemaTypes.time)),addDecimal=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeDecimal(t),xmlSchemaTypes.decimal)),addInteger=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeInteger(t),xmlSchemaTypes.integer));function addStringWithLocale(n,e,t,r){var i,s,o;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const a=internal_toIriString(e),u=normalizeLocale(r),c=(i=n.predicates[a])!==null&&i!==void 0?i:{},l=(s=c.langStrings)!==null&&s!==void 0?s:{},d=(o=l[u])!==null&&o!==void 0?o:[],f=freeze(d.concat(t)),m=freeze({...l,[u]:f}),g=freeze({...c,langStrings:m}),b=freeze({...n.predicates,[a]:g});return freeze({...n,predicates:b})}const addStringNoLocale=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,t,xmlSchemaTypes.string));function addNamedNode(n,e,t){return addUrl(n,e,t.value)}function addLiteral(n,e,t){if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);return t.datatype.value===xmlSchemaTypes.langString?addStringWithLocale(n,e,t.value,t.language):addLiteralOfType(n,e,t.value,t.datatype.value)}function addTerm(n,e,t){var r,i;if(t.termType==="NamedNode")return addNamedNode(n,e,t);if(t.termType==="Literal")return addLiteral(n,e,t);if(t.termType==="BlankNode"){if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const s=internal_toIriString(e),o=(r=n.predicates[s])!==null&&r!==void 0?r:{},a=(i=o.blankNodes)!==null&&i!==void 0?i:[],u=freeze(a.concat(getBlankNodeId(t))),c=freeze({...o,blankNodes:u}),l=freeze({...n.predicates,[s]:c});return freeze({...n,predicates:l})}throw new Error(`Term type [${t.termType}] is not supported by @inrupt/solid-client.`)}function addLiteralOfType(n,e,t,r){var i,s,o;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const a=internal_toIriString(e),u=(i=n.predicates[a])!==null&&i!==void 0?i:{},c=(s=u.literals)!==null&&s!==void 0?s:{},l=(o=c[r])!==null&&o!==void 0?o:[],d=freeze(l.concat(t)),f=freeze({...c,[r]:d}),m=freeze({...u,literals:f}),g=freeze({...n.predicates,[a]:m});return freeze({...n,predicates:g})}function removeAll(n,e){if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const t=internal_toIriString(e),r={...n.predicates};return delete r[t],freeze({...n,predicates:freeze(r)})}const removeUrl=(n,e,t)=>{var r,i,s;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const o=internal_toIriString(e);if(!isThing(t)&&!internal_isValidUrl(t))throw new ValidValueUrlExpectedError(t);const a=isThing(t)?asIri(t):internal_toIriString(t),u=freeze((s=(i=(r=n.predicates[o])===null||r===void 0?void 0:r.namedNodes)===null||i===void 0?void 0:i.filter(d=>d.toLowerCase()!==a.toLowerCase()))!==null&&s!==void 0?s:[]),c=freeze({...n.predicates[o],namedNodes:u}),l=freeze({...n.predicates,[o]:c});return freeze({...n,predicates:l})},removeIri=removeUrl,removeBoolean=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.boolean,r=>deserializeBoolean(r)===t)),removeDatetime=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.dateTime,r=>{var i;return((i=deserializeDatetime(r))===null||i===void 0?void 0:i.getTime())===t.getTime()})),removeDate=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.date,function(r){const i=deserializeDate(r);return i?i.getFullYear()===t.getFullYear()&&i.getMonth()===t.getMonth()&&i.getUTCDate()===t.getUTCDate():!1})),removeTime=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.time,function(r){const i=deserializeTime(r);return i?i.hour===t.hour&&i.minute===t.minute&&i.second===t.second&&i.millisecond===t.millisecond&&i.timezoneHourOffset===t.timezoneHourOffset&&i.timezoneMinuteOffset===t.timezoneMinuteOffset:!1})),removeDecimal=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.decimal,r=>deserializeDecimal(r)===t)),removeInteger=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.integer,r=>deserializeInteger(r)===t));function removeStringWithLocale(n,e,t,r){var i,s;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const o=internal_toIriString(e),a=(s=(i=n.predicates[o])===null||i===void 0?void 0:i.langStrings)!==null&&s!==void 0?s:{},u=Object.keys(a).find(g=>normalizeLocale(g)===normalizeLocale(r)&&Array.isArray(a[g])&&a[g].length>0);if(typeof u!="string")return n;const c=a[u],l=freeze(c.filter(g=>g!==t)),d=freeze({...a,[u]:l}),f=freeze({...n.predicates[o],langStrings:d}),m=freeze({...n.predicates,[o]:f});return freeze({...n,predicates:m})}const removeStringNoLocale=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.string,r=>r===t));function removeNamedNode(n,e,t){return removeUrl(n,e,t.value)}function removeLiteral(n,e,t){var r,i,s;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const o=t.datatype.value;if(o===xmlSchemaTypes.langString)return removeStringWithLocale(n,e,t.value,t.language);const a=internal_toIriString(e),u=(r=n.predicates[a])!==null&&r!==void 0?r:{},c=(i=u.literals)!==null&&i!==void 0?i:{},l=(s=c[o])!==null&&s!==void 0?s:[],d=freeze(l.filter(S=>S!==t.value)),f=freeze({...c,[o]:d}),m=freeze({...u,literals:f}),g=freeze({...n.predicates,[a]:m});return freeze({...n,predicates:g})}function removeLiteralMatching(n,e,t,r){var i,s,o;if(!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const a=internal_toIriString(e),u=(i=n.predicates[a])!==null&&i!==void 0?i:{},c=(s=u.literals)!==null&&s!==void 0?s:{},l=(o=c[t])!==null&&o!==void 0?o:[],d=freeze(l.filter(S=>!r(S))),f=freeze({...c,[t]:d}),m=freeze({...u,literals:f}),g=freeze({...n.predicates,[a]:m});return freeze({...n,predicates:g})}const setUrl=(n,e,t)=>{if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);if(!isThing(t)&&!internal_isValidUrl(t))throw new ValidValueUrlExpectedError(t);return addUrl(removeAll(n,e),e,t)},setIri=setUrl,setBoolean=(n,e,t)=>(internal_throwIfNotThing(n),addBoolean(removeAll(n,e),e,t)),setDatetime=(n,e,t)=>(internal_throwIfNotThing(n),addDatetime(removeAll(n,e),e,t)),setDate=(n,e,t)=>(internal_throwIfNotThing(n),addDate(removeAll(n,e),e,t)),setTime=(n,e,t)=>(internal_throwIfNotThing(n),addTime(removeAll(n,e),e,t)),setDecimal=(n,e,t)=>(internal_throwIfNotThing(n),addDecimal(removeAll(n,e),e,t)),setInteger=(n,e,t)=>(internal_throwIfNotThing(n),addInteger(removeAll(n,e),e,t));function setStringWithLocale(n,e,t,r){return internal_throwIfNotThing(n),addStringWithLocale(removeAll(n,e),e,t,r)}const setStringNoLocale=(n,e,t)=>(internal_throwIfNotThing(n),addStringNoLocale(removeAll(n,e),e,t));function setNamedNode(n,e,t){return internal_throwIfNotThing(n),addNamedNode(removeAll(n,e),e,t)}function setLiteral(n,e,t){return internal_throwIfNotThing(n),addLiteral(removeAll(n,e),e,t)}function setTerm(n,e,t){if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);return addTerm(removeAll(n,e),e,t)}function buildThing(n=createThing()){let e=isThing(n)?n:createThing(n);function t(o){return(a,u)=>(e=o(e,a,u),s)}function r(o){return(a,u)=>(e=o(e,a,u),s)}function i(o){return(a,u)=>(e=o(e,a,u),s)}const s={build:()=>e,addUrl:t(addUrl),addIri:t(addIri),addBoolean:t(addBoolean),addDatetime:t(addDatetime),addDate:t(addDate),addTime:t(addTime),addDecimal:t(addDecimal),addInteger:t(addInteger),addStringNoLocale:t(addStringNoLocale),addStringEnglish:(o,a)=>(e=addStringWithLocale(e,o,a,"en"),s),addStringWithLocale:(o,a,u)=>(e=addStringWithLocale(e,o,a,u),s),addNamedNode:t(addNamedNode),addLiteral:t(addLiteral),addTerm:t(addTerm),setUrl:r(setUrl),setIri:r(setIri),setBoolean:r(setBoolean),setDatetime:r(setDatetime),setDate:r(setDate),setTime:r(setTime),setDecimal:r(setDecimal),setInteger:r(setInteger),setStringNoLocale:r(setStringNoLocale),setStringEnglish:(o,a)=>(e=setStringWithLocale(e,o,a,"en"),s),setStringWithLocale:(o,a,u)=>(e=setStringWithLocale(e,o,a,u),s),setNamedNode:r(setNamedNode),setLiteral:r(setLiteral),setTerm:r(setTerm),removeAll:o=>(e=removeAll(e,o),s),removeUrl:i(removeUrl),removeIri:i(removeIri),removeBoolean:i(removeBoolean),removeDatetime:i(removeDatetime),removeDate:i(removeDate),removeTime:i(removeTime),removeDecimal:i(removeDecimal),removeInteger:i(removeInteger),removeStringNoLocale:i(removeStringNoLocale),removeStringEnglish:(o,a)=>buildThing(removeStringWithLocale(e,o,a,"en")),removeStringWithLocale:(o,a,u)=>buildThing(removeStringWithLocale(e,o,a,u)),removeNamedNode:i(removeNamedNode),removeLiteral:i(removeLiteral)};return s}const normalizeRdfClass=n=>n&&(n.startsWith("http://schema.org/")?n.replace("http://schema.org/","https://schema.org/"):n);class InteropDiscovery{constructor(e,t,r){this.webId=e,this.fetchFn=t,this.clientId=r,this.shapeTreeCache=new Map}async ensureRegistrySet(e,t,r){if(!r?.registryPath)throw new Error("Missing registryPath for SAI registry auto-creation.");const i=r.registryPath.endsWith("/")?r.registryPath:`${r.registryPath}/`,s=i.replace(/[^/]+\/$/,""),o=`${i}agents/`,a=`${i}set.ttl`,c=`${a}#set-drizzle-solid`,l=`${i}data-registry.ttl`,f=`${l}#data-registry`;try{s&&s!==i&&await createContainerAt(s,{fetch:this.fetchFn}),await createContainerAt(i,{fetch:this.fetchFn})}catch{}try{await createContainerAt(o,{fetch:this.fetchFn})}catch{}const m=setUrl(createThing({url:f}),"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",INTEROP.DataRegistry);let g;try{g=await getSolidDataset(l,{fetch:this.fetchFn})}catch{g=void 0}if(g){if(!getThing(g,f)){const C=setThing(g,m);await saveSolidDatasetAt(l,C,{fetch:this.fetchFn})}}else{let T=createSolidDataset();T=setThing(T,m),await saveSolidDatasetAt(l,T,{fetch:this.fetchFn})}let b=createThing({url:c});b=setUrl(b,"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",INTEROP.RegistrySet),b=addUrl(b,INTEROP.hasDataRegistry,f),b=addUrl(b,"http://www.w3.org/ns/solid/interop#hasAgentRegistry",o);let S;try{S=await getSolidDataset(a,{fetch:this.fetchFn})}catch{S=void 0}if(S){const T=getThing(S,c);if(T){const C=getPredicateForColumn(registrySetSchema.columns.hasDataRegistry,registrySetSchema),U=getPredicateForColumn(registrySetSchema.columns.hasAgentRegistry,registrySetSchema),$=getUrlAll(T,C),W=getUrlAll(T,U);let re=T;if($.includes(f)||(re=addUrl(re,C,f)),W.includes(o)||(re=addUrl(re,U,o)),re!==T){const D=setThing(S,re);await saveSolidDatasetAt(a,D,{fetch:this.fetchFn})}}else{const C=setThing(S,b);await saveSolidDatasetAt(a,C,{fetch:this.fetchFn})}}else{let T=createSolidDataset();T=setThing(T,b),await saveSolidDatasetAt(a,T,{fetch:this.fetchFn})}const w=setUrl(t,INTEROP.hasRegistrySet,c),v=setThing(e,w),_=this.webId.split("#")[0];return await saveSolidDatasetAt(_,v,{fetch:this.fetchFn}),c}async register(e,t){if(!t?.registryPath)throw new Error("registryPath is required for SAI registration.");const r=typeof e.config.type=="string"?e.config.type:e.config.type.value,i=normalizeRdfClass(r)??r;try{const s=await getSolidDataset(this.webId,{fetch:this.fetchFn}),o=getThing(s,this.webId);if(!o)throw new Error("Profile not found");let a=getUrl(o,INTEROP.hasRegistrySet),u,c;if(a)try{u=await getSolidDataset(a,{fetch:this.fetchFn}),c=getThing(u,a)}catch{u=void 0,c=void 0}if((!a||!c)&&(a=await this.ensureRegistrySet(s,o,t),u=await getSolidDataset(a,{fetch:this.fetchFn}),c=getThing(u,a),!c))throw new Error("RegistrySet not found");if(!t?.force&&(await this.discover(r)).length>0){console.log(`[InteropDiscovery] ${e.config.name} already registered, skipping`);return}const l=getPredicateForColumn(registrySetSchema.columns.hasDataRegistry,registrySetSchema),d=getUrlAll(c,l);if(d.length===0)throw new Error("No DataRegistry found");const f=d[0],m=t?.containerSlug??e.config.name,g=f.endsWith("/")?f:f+"/",b=`${g}${m}/`;try{await getSolidDataset(b,{fetch:this.fetchFn})}catch{await createContainerAt(b,{fetch:this.fetchFn})}const S=`${g}${m}`,w=`${S}#ShapeTree`;let v=createThing({url:w});v=setUrl(v,"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",SHAPETREES.ShapeTree),v=setUrl(v,SHAPETREES.expectsType,i),t?.shapeUrl&&(v=setUrl(v,SHAPETREES.shape,t.shapeUrl));let _=createThing({url:S});_=setUrl(_,"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",INTEROP.DataRegistration);const T=this.clientId&&/^https?:\/\//.test(this.clientId)?this.clientId:this.webId;_=setUrl(_,INTEROP.registeredBy,T),_=setDatetime(_,"http://www.w3.org/ns/solid/interop#registeredAt",new Date),_=setUrl(_,INTEROP.registeredShapeTree,w);const C=e.getSubjectTemplate();C&&(_=setStringNoLocale(_,UDFS$1.subjectTemplate,C));let U;try{U=await getSolidDataset(S,{fetch:this.fetchFn})}catch{U=null}let $=U??createSolidDataset(),W=!1;const re=getThing($,S);if(!re)$=setThing($,_),W=!0;else{let _e=re;const Ce=getUrl(re,INTEROP.registeredBy),Fe=getUrl(re,INTEROP.registeredShapeTree),ze=getStringNoLocale(re,UDFS$1.subjectTemplate);Ce||(_e=setUrl(_e,INTEROP.registeredBy,T)),Fe||(_e=setUrl(_e,INTEROP.registeredShapeTree,w)),!ze&&C&&(_e=setStringNoLocale(_e,UDFS$1.subjectTemplate,C)),_e!==re&&($=setThing($,_e),W=!0)}getThing($,w)||($=setThing($,v),W=!0),(!U||W)&&await saveSolidDatasetAt(S,$,{fetch:this.fetchFn});let V=await getSolidDataset(f,{fetch:this.fetchFn}),he=getThing(V,f);if(!he)throw new Error("Registry Thing missing in Dataset");const z=getPredicateForColumn(dataRegistrySchema.columns.hasDataRegistration,dataRegistrySchema);he=addUrl(he,z,S),V=setThing(V,he),await saveSolidDatasetAt(f,V,{fetch:this.fetchFn}),this.shapeTreeCache.set(w,{expectsType:i,shape:t?.shapeUrl}),console.log(`[InteropDiscovery] Registered ${e.config.name} at ${S}`),console.log(`[InteropDiscovery] -> ShapeTree: ${w}`),console.log(`[InteropDiscovery] -> expectsType: ${i}`),t?.shapeUrl&&console.log(`[InteropDiscovery] -> Shape: ${t.shapeUrl}`)}catch(s){throw console.error("[InteropDiscovery] Registration failed:",s),s}}async discover(e,t){try{const r=[],i=await getSolidDataset(this.webId,{fetch:this.fetchFn}),s=getThing(i,this.webId);if(!s)return[];const o=getUrlAll(s,INTEROP.hasRegistrySet);if(o.length===0)return[];for(const a of o){const u=await this.discoverDataRegistrationsRaw(a,e,t);r.push(...u);const c=await this.discoverAccessGrantsRaw(a,e,t);r.push(...c)}return this.mergeByContainer(r)}catch(r){return console.error("[InteropDiscovery] Discovery failed:",r),[]}}mergeByContainer(e){const t=new Map;for(const r of e){const i=t.get(r.container),s=r.shape?{url:r.shape,shapeTree:r.shapeTree,registeredBy:r.registeredBy,source:r.source}:void 0;i?(s&&!i.shapes.some(o=>o.url===s.url)&&i.shapes.push(s),!i.subjectTemplate&&r.subjectTemplate&&(i.subjectTemplate=r.subjectTemplate)):t.set(r.container,{container:r.container,subjectTemplate:r.subjectTemplate,shapes:s?[s]:[],source:r.source})}return Array.from(t.values())}async discoverDataRegistrationsRaw(e,t,r){const i=[],s=normalizeRdfClass(t)??t;try{const o=await getSolidDataset(e,{fetch:this.fetchFn}),a=getThing(o,e);if(!a)return[];const u=getPredicateForColumn(registrySetSchema.columns.hasDataRegistry,registrySetSchema),c=getUrlAll(a,u);for(const l of c)try{const d=await getSolidDataset(l,{fetch:this.fetchFn}),f=getThing(d,l);if(!f)continue;const m=getPredicateForColumn(dataRegistrySchema.columns.hasDataRegistration,dataRegistrySchema),g=getUrlAll(f,m);for(const b of g){const S=await getSolidDataset(b,{fetch:this.fetchFn}),w=getThing(S,b);if(!w)continue;const v=getPredicateForColumn(dataRegistrationSchema.columns.registeredShapeTree,dataRegistrationSchema),_=getUrl(w,v);if(!_)continue;const T=getPredicateForColumn(dataRegistrationSchema.columns.registeredBy,dataRegistrationSchema),C=getUrl(w,T),U=getStringNoLocale(w,UDFS$1.subjectTemplate)??void 0;if(r?.appId&&C!==r.appId)continue;const $=await this.resolveShapeTree(_);normalizeRdfClass($?.expectsType)===s&&i.push({container:b,source:"interop",subjectTemplate:U,shapeTree:_,shape:$?.shape,registeredBy:C??void 0})}}catch(d){console.warn(`[InteropDiscovery] Error checking registry ${l}:`,d)}}catch(o){console.warn(`[InteropDiscovery] Error exploring RegistrySet ${e}:`,o)}return i}async discoverAccessGrantsRaw(e,t,r){if(!this.clientId)return console.warn("[InteropDiscovery] No ClientID available, skipping Access Grant discovery"),[];const i=[],s=normalizeRdfClass(t)??t;try{const o=await getSolidDataset(e,{fetch:this.fetchFn}),a=getThing(o,e);if(!a)return console.warn(`[InteropDiscovery] RegistrySet Thing not found at ${e}`),[];const u=getPredicateForColumn(registrySetSchema.columns.hasAgentRegistry,registrySetSchema),c=getUrlAll(a,u);for(const l of c)try{const d=await getSolidDataset(l,{fetch:this.fetchFn}),f=getThing(d,l);if(!f)continue;const g=getUrlAll(f,"http://www.w3.org/ns/solid/interop#hasApplicationRegistration"),b=getUrlAll(f,"http://www.w3.org/ns/ldp#contains"),S=Array.from(new Set([...g,...b]));for(const w of S)try{const v=await getSolidDataset(w,{fetch:this.fetchFn}),_=getThingAll(v);for(const T of _){const C=getPredicateForColumn(applicationRegistrationSchema.columns.registeredAgent,applicationRegistrationSchema);if(getUrl(T,C)===this.clientId){const $=getPredicateForColumn(applicationRegistrationSchema.columns.hasAccessGrant,applicationRegistrationSchema),W=getUrlAll(T,$);for(const re of W){let D=getThing(v,re);if(!D){const z=await getSolidDataset(re,{fetch:this.fetchFn}).catch(()=>null);z&&(D=getThing(z,re))}if(!D)continue;const V=getPredicateForColumn(accessGrantSchema.columns.hasDataGrant,accessGrantSchema),he=getUrlAll(D,V);for(const z of he){let _e=getThing(v,z);if(!_e){const ie=await getSolidDataset(z,{fetch:this.fetchFn}).catch(()=>null);ie&&(_e=getThing(ie,z))}if(!_e)continue;const Ce=getPredicateForColumn(dataGrantSchema.columns.registeredShapeTree,dataGrantSchema),Fe=getUrl(_e,Ce);if(!Fe)continue;const ze=getPredicateForColumn(dataGrantSchema.columns.dataOwner,dataGrantSchema),ae=getUrl(_e,ze);if(r?.appId&&ae!==r.appId)continue;const ve=await this.resolveShapeTree(Fe);if(normalizeRdfClass(ve?.expectsType)===s){const ie=getPredicateForColumn(dataGrantSchema.columns.hasDataRegistration,dataGrantSchema),xe=getUrl(_e,ie);console.log(`[InteropDiscovery] Found matching Data Grant: ${z}`),console.log(`[InteropDiscovery] -> ShapeTree: ${Fe}`),console.log(`[InteropDiscovery] -> Shape: ${ve?.shape}`),console.log(`[InteropDiscovery] -> Data Registration: ${xe}`),xe&&i.push({container:xe,source:"interop",shapeTree:Fe,shape:ve?.shape,registeredBy:ae??void 0})}else console.log(`[InteropDiscovery] ShapeTree mismatch: ${Fe} vs ${t}`)}}}}}catch{}}catch(d){console.warn(`[InteropDiscovery] Error checking AgentRegistry ${l}:`,d)}}catch(o){console.warn("[InteropDiscovery] Error in AccessGrant discovery:",o)}return i}async isRegistered(e){return(await this.discover(e)).length>0}async discoverByApp(e){try{const i=(await this.discoverAll()).filter(s=>s.registeredBy===e).map(s=>({container:s.container,source:"interop",shapeTree:s.shapeTree,shape:s.shape,registeredBy:s.registeredBy}));return this.mergeByContainer(i)}catch(t){return console.error("[InteropDiscovery] discoverByApp failed:",t),[]}}async discoverAll(){const e=[];try{const t=await getSolidDataset(this.webId,{fetch:this.fetchFn}),r=getThing(t,this.webId);if(!r)return[];const i=getUrlAll(r,INTEROP.hasRegistrySet);for(const s of i)try{const o=await getSolidDataset(s,{fetch:this.fetchFn}),a=getThing(o,s);if(!a)continue;const u=getPredicateForColumn(registrySetSchema.columns.hasDataRegistry,registrySetSchema),c=getUrlAll(a,u);for(const l of c)try{const d=await getSolidDataset(l,{fetch:this.fetchFn}),f=getThing(d,l);if(!f)continue;const m=getPredicateForColumn(dataRegistrySchema.columns.hasDataRegistration,dataRegistrySchema),g=getUrlAll(f,m);for(const b of g)try{const S=await getSolidDataset(b,{fetch:this.fetchFn}),w=getThing(S,b);if(!w)continue;const v=getPredicateForColumn(dataRegistrationSchema.columns.registeredShapeTree,dataRegistrationSchema),_=getUrl(w,v);if(!_)continue;const T=getPredicateForColumn(dataRegistrationSchema.columns.registeredBy,dataRegistrationSchema),C=getUrl(w,T),U=getPredicateForColumn(dataRegistrationSchema.columns.registeredAt,dataRegistrationSchema),$=getUrl(w,U),W=$?new Date($):void 0,re=getStringNoLocale(w,UDFS$1.subjectTemplate)??void 0,D=await this.resolveShapeTree(_);e.push({registrationUrl:b,container:b,rdfClass:D?.expectsType??"",shapeTree:_,shape:D?.shape,subjectTemplate:re,registeredBy:C??void 0,registeredAt:W})}catch(S){console.warn(`[InteropDiscovery] Error reading registration ${b}:`,S)}}catch(d){console.warn(`[InteropDiscovery] Error reading registry ${l}:`,d)}}catch(o){console.warn(`[InteropDiscovery] Error reading RegistrySet ${s}:`,o)}}catch(t){console.error("[InteropDiscovery] discoverAll failed:",t)}return e}async checkShapeTreeMatchesClass(e,t){const r=await this.resolveShapeTree(e);return normalizeRdfClass(r?.expectsType)===(normalizeRdfClass(t)??t)}async resolveShapeTree(e){if(this.shapeTreeCache.has(e))return this.shapeTreeCache.get(e);try{const t=await getSolidDataset(e,{fetch:this.fetchFn}),r=getThing(t,e);if(!r)return this.shapeTreeCache.set(e,{}),null;const i=getUrl(r,SHAPETREES.expectsType)??void 0,s=getUrl(r,SHAPETREES.shape)??void 0,o={expectsType:i,shape:s};return this.shapeTreeCache.set(e,o),o}catch(t){return console.warn(`[InteropDiscovery] Failed to fetch ShapeTree ${e}:`,t),this.shapeTreeCache.set(e,{}),null}}}function mergeLocationsByContainer(n){const e=new Map;for(const t of n){const r=e.get(t.container);if(r)for(const i of t.shapes)r.shapes.some(s=>s.url===i.url)||r.shapes.push(i);else e.set(t.container,{container:t.container,subjectPattern:t.subjectPattern,shapes:[...t.shapes],source:t.source})}return Array.from(e.values())}class CompositeDiscovery{constructor(e){this.strategies=e}async register(e,t){const r=[];let i=!1;for(const s of this.strategies)if(!(s instanceof InteropDiscovery&&!t?.registryPath))try{await s.register(e,t),i=!0}catch(o){r.push(o),console.warn("Registration failed with strategy, trying next:",o)}if(!i){const s=r.length>0?` Errors: ${r.map(String).join("; ")}`:"";throw new Error(`Failed to register table with any discovery strategy.${s}`)}}async discover(e,t){const r=[];for(const i of this.strategies)try{const s=await i.discover(e,t);r.push(...s)}catch(s){console.warn("Discovery failed with strategy, trying next:",s)}return mergeLocationsByContainer(r)}async isRegistered(e){for(const t of this.strategies)if(await t.isRegistered(e))return!0;return!1}async discoverAll(){const e=[];for(const t of this.strategies)if(t.discoverAll)try{const r=await t.discoverAll();e.push(...r)}catch(r){console.warn("discoverAll failed with strategy:",r)}return e}async discoverByApp(e){const t=[];for(const r of this.strategies)if(r.discoverByApp)try{const i=await r.discoverByApp(e);t.push(...i)}catch(i){console.warn("discoverByApp failed with strategy:",i)}return mergeLocationsByContainer(t)}}function getContainerUrl(n){try{const e=new URL(n),t=e.pathname.lastIndexOf("/");return t<0?null:(e.pathname=e.pathname.slice(0,t+1),e.search="",e.hash="",e.toString())}catch{const e=n.lastIndexOf("/");return e>0?n.slice(0,e+1):null}}class LdpExecutor{constructor(e,t,r){this.sparqlExecutor=e,this.fetchFn=t,this.uriResolver=r,this.tripleBuilder=new TripleBuilderImpl(r)}setTableRegistry(e,t){this.tripleBuilder.setTableRegistry(e,t)}setBaseUri(e){this.tripleBuilder.setBaseUri(e)}async executeInsert(e,t,r,i={}){i.tableRegistry&&i.tableNameRegistry&&this.setTableRegistry(i.tableRegistry,i.tableNameRegistry);const s=[];if(e.forEach((f,m)=>{const g=this.uriResolver.resolveSubject(t,f,m);t.__currentRecord=f;try{const b=this.tripleBuilder.buildTypeTriple(g,t.config.type);s.push(...this.tripleBuilder.toN3Strings([b])),Object.entries(t.columns??{}).forEach(([S,w])=>{if(f[S]===void 0||f[S]===null||w._virtualId||(w.options?.predicate||w._predicateUri)==="@id")return;const _=this.tripleBuilder.buildInsert(g,w,f[S],t);s.push(...this.tripleBuilder.toN3Strings(_.triples)),_.childTriples&&_.childTriples.length>0&&s.push(...this.tripleBuilder.toN3Strings(_.childTriples))})}finally{delete t.__currentRecord}}),s.length===0)return[];if(this.uriResolver.getResourceMode(t)==="document"){const f=new Map;for(let g=0;g<e.length;g++){const b=e[g],S=this.uriResolver.resolveSubject(t,b,g);t.__currentRecord=b;try{const w=this.uriResolver.getResourceUrl(S),v=[],_=this.tripleBuilder.buildTypeTriple(S,t.config.type);if(v.push(...this.tripleBuilder.toN3Strings([_])),Object.entries(t.columns??{}).forEach(([C,U])=>{if(b[C]===void 0||b[C]===null||U._virtualId||(U.options?.predicate||U._predicateUri)==="@id")return;const W=this.tripleBuilder.buildInsert(S,U,b[C],t);v.push(...this.tripleBuilder.toN3Strings(W.triples)),W.childTriples&&W.childTriples.length>0&&v.push(...this.tripleBuilder.toN3Strings(W.childTriples))}),v.length===0)continue;const T=f.get(w)||{triples:[],hasFragmentSubject:!1};T.triples.push(...v),T.hasFragmentSubject=T.hasFragmentSubject||S.includes("#"),f.set(w,T)}finally{delete t.__currentRecord}}const m=[];for(const[g,b]of f.entries()){const S=b.triples,w=getContainerUrl(g);w&&i.ensureContainerExists&&await i.ensureContainerExists(w);let v=!1;if(!i.skipResourceExistenceCheck){const U=await this.fetchFn(g,{method:"HEAD"});v=U.ok||U.status===405}let _,T;if(i.skipResourceExistenceCheck){const U=`INSERT DATA {
|
|
130
|
+
${S.join(`
|
|
131
|
+
`)}
|
|
132
|
+
}`;if(_=await this.fetchFn(g,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:U}),T="patch",await this.shouldFallbackToN3Patch(_)){const $=await this.executeN3PatchInternal(g,[],S);_=new Response(null,{status:$[0]?.status??200}),T="n3"}if(_.status===404){const $=S.join(`
|
|
133
|
+
`);_=await this.fetchFn(g,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:$}),T="put",_=await this.repairContainerAndRetryPutIfNeeded(_,w,g,$,"text/turtle",i.repairContainerOnWriteFailure)}}else if(v){const U=`INSERT DATA {
|
|
134
|
+
${S.join(`
|
|
135
|
+
`)}
|
|
136
|
+
}`;if(_=await this.fetchFn(g,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:U}),T="patch",await this.shouldFallbackToN3Patch(_)){const $=await this.executeN3PatchInternal(g,[],S);_=new Response(null,{status:$[0]?.status??200}),T="n3"}}else{const U=S.join(`
|
|
137
|
+
`);_=await this.fetchFn(g,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:U}),T="put"}if(![200,201,202,204,205].includes(_.status)){const U=await _.text().catch(()=>"");throw new Error(`Write failed for ${g}: ${_.status} ${_.statusText}${U?` - ${U}`:""}`)}await this.sparqlExecutor.invalidateHttpCache(g);const C=g.lastIndexOf("/");if(C>0){const U=g.slice(0,C+1);await this.sparqlExecutor.invalidateHttpCache(U)}await this.sparqlExecutor.invalidateHttpCache(void 0).catch(()=>{}),m.push({success:!0,source:g,status:_.status,via:T})}return m}const a=getContainerUrl(r);a&&i.ensureContainerExists&&await i.ensureContainerExists(a);const u=`INSERT DATA {
|
|
138
|
+
${s.join(`
|
|
139
|
+
`)}
|
|
140
|
+
}`;let c=await this.fetchFn(r,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:u}),l="sparql-update";if(await this.shouldFallbackToN3Patch(c)){const f=await this.executeN3PatchInternal(r,[],s);c=new Response(null,{status:f[0]?.status??200}),l="n3"}if((c.status===404||c.status===201)&&(i.skipResourceExistenceCheck?!0:await this.fetchFn(r,{method:"HEAD"}).then(m=>!m.ok&&m.status!==405))){let m=await this.fetchFn(r,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:""});m=await this.repairContainerAndRetryPutIfNeeded(m,a,r,"","text/turtle",i.repairContainerOnWriteFailure),(m.ok||m.status===409||m.status===201)&&(c=await this.fetchFn(r,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:u}))}if(!c.ok){const f=await c.text().catch(()=>""),m=new Error(`SPARQL UPDATE INSERT failed: ${c.status} ${c.statusText}${f?` - ${f}`:""}`);throw m.status=c.status,m}await this.sparqlExecutor.invalidateHttpCache(r);const d=r.lastIndexOf("/");if(d>0){const f=r.slice(0,d+1);await this.sparqlExecutor.invalidateHttpCache(f)}return await this.sparqlExecutor.invalidateHttpCache(void 0).catch(()=>{}),[{success:!0,source:r,status:c.status,via:l}]}async repairContainerAndRetryPutIfNeeded(e,t,r,i,s,o){return!o||!t||!this.isMissingParentContainerResponse(e)?e:(await o(t),await this.fetchFn(r,{method:"PUT",headers:{"Content-Type":s},body:i}))}isMissingParentContainerResponse(e){return e.status===404||e.status===409}async executeUpdate(e,t,r,i){if(!r.length)return[];const s=[],o=this.uriResolver.getResourceMode(e);for(const a of r){const u=o==="document"?this.uriResolver.getResourceUrl(a):i,c=await this.buildUpdatePatchPayload(a,e,t,u);if(!c)continue;const{deleteTriples:l,insertTriples:d,deleteWherePatterns:f}=c,m=Object.entries(t).filter(([,_])=>_!==void 0);for(const[_]of m){if(_==="@id"||_==="subject")continue;const T=e.columns?.[_];if(!T||T._virtualId||T.options?.predicate==="@id"||!(T.dataType==="object"||T.dataType==="array"&&(T.elementType==="object"||T.options?.baseType==="object")))continue;const U=this.tripleBuilder.getPredicateUri(T,e),$=await this.fetchExistingObjects(u,a,U);for(const W of $){let re=W;if(!re.startsWith("<")&&!re.startsWith("_:")&&(re=`<${re}>`),l.push(`<${a}> <${U}> ${re} .`),re.startsWith("<")){const D=re.slice(1,-1),V=await this.fetchRecursiveTriplesToDelete(D,e,u);l.push(...V)}}}const g=Array.from(new Set(l)),b=Array.from(new Set(d)),S=g.filter(_=>!b.includes(_)),w=b.filter(_=>!g.includes(_));if(S.length===0&&w.length===0)continue;const v=await this.executeN3Patch(u,S,w,[],f);s.push(...v),await new Promise(_=>setTimeout(_,200))}return s}async executeDelete(e,t,r){const i=[],s=this.uriResolver.getResourceMode(t);for(const o of e)try{const a=s==="document"?this.uriResolver.getResourceUrl(o):r,u=await this.fetchRecursiveTriplesToDelete(o,t,a),c=Array.from(new Set(u));if(c.length>0){const l=await this.executeN3Patch(a,c,[],[]);i.push(...l)}}catch(a){throw console.error(`[DELETE] Failed to delete subject ${o}:`,a),a}return i}async retryWithBackoff(e,t=3){let r=null,i;for(let s=0;s<t;s++)try{const o=await e();if(r=o.response,o.result!==void 0)return{response:r,result:o.result};if(o.fallback){const a=await o.fallback();return{response:r,result:a}}if(!o.shouldRetry)break;await new Promise(a=>setTimeout(a,1e3*(s+1)))}catch(o){i=o,s<t-1&&await new Promise(a=>setTimeout(a,1e3*(s+1)))}return{response:r,lastError:i}}async buildPatchError(e,t,r){const i=e?await e.text().catch(()=>""):"",s=e?e.status:"Network Error",o=e?e.statusText:t instanceof Error?t.message:String(t),a=new Error(`${r} failed: ${s} ${o}${i?` - ${i}`:""}`);return a.status=s,a}async shouldFallbackToN3Patch(e){return e.status===415||e.status===405||e.status===400&&(await e.clone().text().catch(()=>"")).includes("prepared update source provenance is not uniquely identified")}async buildUpdatePatchPayload(e,t,r,i){const s=[],o=[],a=[];for(const[u,c]of Object.entries(r)){if(c===void 0||u==="@id"||u==="subject")continue;const l=t.columns?.[u];if(!l||l._virtualId||l.options?.predicate==="@id")continue;if(l.dataType==="object"||l.dataType==="array"&&(l.elementType==="object"||l.options?.baseType==="object")){if(c!==null){const w=this.tripleBuilder.buildInsert(e,l,c,t);o.push(...this.tripleBuilder.toN3Strings(w.triples)),w.childTriples&&o.push(...this.tripleBuilder.toN3Strings(w.childTriples))}continue}const f=this.tripleBuilder.getPredicateUri(l,t);if(!!l.options?.inverse){const v=(await this.fetchInverseSubjects(i,e,f)).map(T=>{let C=T;return!C.startsWith("<")&&!C.startsWith("_:")&&(C=`<${C}>`),`${C} <${f}> <${e}> .`}),_=c===null?[]:this.tripleBuilder.toN3Strings(this.tripleBuilder.buildInsert(e,l,c,t).triples);if(this.sameTripleSet(v,_))continue;s.push(...v),o.push(..._);continue}const b=(await this.fetchExistingObjects(i,e,f)).map(w=>`<${e}> <${f}> ${w} .`),S=c===null?[]:this.tripleBuilder.toN3Strings(this.tripleBuilder.buildInsert(e,l,c,t).triples);this.sameTripleSet(b,S)||(s.push(...b),o.push(...S))}return{deleteTriples:s,insertTriples:o,deleteWherePatterns:a}}sameTripleSet(e,t){if(e.length!==t.length)return!1;const r=new Set(t);return e.every(i=>r.has(i))}async executeN3Patch(e,t,r,i=[],s=[]){if(t.length===0&&r.length===0&&s.length===0)return[];const o=this.buildSparqlUpdate(t,r,s),{response:a,result:u,lastError:c}=await this.retryWithBackoff(async()=>{const l=await this.fetchFn(e,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:o});if(l.ok)return await this.sparqlExecutor.invalidateHttpCache(e),{response:l,result:[{success:!0,source:e,status:l.status,via:"sparql-update"}],shouldRetry:!1};if(await this.shouldFallbackToN3Patch(l)){const f=s.length>0?[...t,...s]:t,m=s.length>0?s:i;return{response:l,shouldRetry:!1,fallback:()=>this.executeN3PatchInternal(e,f,r,m)}}const d=l.status>=500||l.status===409;return{response:l,shouldRetry:d}});if(u)return u;throw await this.buildPatchError(a,c,"SPARQL UPDATE")}buildSparqlUpdate(e,t,r){const i=[];if(r.length>0)for(const s of r)i.push(`DELETE WHERE {
|
|
141
|
+
${s}
|
|
142
|
+
}`);return e.length>0&&i.push(`DELETE DATA {
|
|
143
|
+
${e.join(`
|
|
144
|
+
`)}
|
|
145
|
+
}`),t.length>0&&i.push(`INSERT DATA {
|
|
146
|
+
${t.join(`
|
|
147
|
+
`)}
|
|
148
|
+
}`),i.join(`;
|
|
149
|
+
`)}async executeN3PatchInternal(e,t,r,i=[]){const s=this.tripleBuilder.buildN3Patch(t,r,i),{response:o,result:a,lastError:u}=await this.retryWithBackoff(async()=>{let c=await this.fetchFn(e,{method:"PATCH",headers:{"Content-Type":"text/n3"},body:s});if(c.status===404){const d=await this.fetchFn(e,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:""});if(!d.ok&&d.status!==409)throw new Error(`Failed to create resource ${e}: ${d.status} ${d.statusText}`);c=await this.fetchFn(e,{method:"PATCH",headers:{"Content-Type":"text/n3"},body:s})}if(c.ok)return await this.sparqlExecutor.invalidateHttpCache(e),{response:c,result:[{success:!0,source:e,status:c.status,via:"n3"}],shouldRetry:!1};const l=c.status>=500||c.status===409;return{response:c,shouldRetry:l}});if(a)return a;throw await this.buildPatchError(o,u,"N3 PATCH")}formatTerm(e){if(!e)return"";if(e.termType==="NamedNode")return`<${e.value}>`;if(e.termType==="BlankNode")return`_:${e.value}`;if(e.termType==="Literal"){const r=`"${String(e.value??"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r")}"`;if(e.language)return`${r}@${e.language}`;if(e.datatype&&e.datatype.value){if(e.datatype.value==="http://www.w3.org/2001/XMLSchema#integer"||e.datatype.value.endsWith("#integer"))return e.value;if(e.datatype.value!=="http://www.w3.org/2001/XMLSchema#string")return`${r}^^<${e.datatype.value}>`}return r}return String(e.value??e)}async fetchRecursiveTriplesToDelete(e,t,r,i=new Set){if(i.has(e))return[];i.add(e);const s=`SELECT ?p ?o WHERE { <${e}> ?p ?o . }`,o=await this.sparqlExecutor.queryBindings(s,r),a=[],u=[];o.forEach(c=>{const l=c.get("p"),d=c.get("o");if(!(!l||!d)&&(a.push(`<${e}> ${this.formatTerm(l)} ${this.formatTerm(d)} .`),d.termType==="NamedNode")){const f=l.value;for(const[,m]of Object.entries(t.columns)){const g=this.tripleBuilder.getPredicateUri(m,t),b=m.dataType==="object"||m.dataType==="array"&&(m.elementType==="object"||m.options?.baseType==="object");g===f&&b&&typeof d.value=="string"&&u.push(d.value)}}});for(const c of u){const l=await this.fetchRecursiveTriplesToDelete(c,t,r,i);a.push(...l)}return a}async fetchExistingObjects(e,t,r){const i=`SELECT ?o WHERE { <${t}> <${r}> ?o . }`;return(await this.sparqlExecutor.queryBindings(i,e)).map(o=>{const a=o.get?.("o");return this.formatTerm(a)}).filter(o=>!!o)}async fetchInverseSubjects(e,t,r){const i=`SELECT ?s WHERE { ?s <${r}> <${t}> . }`;return(await this.sparqlExecutor.queryContainer(e,{type:"SELECT",query:i})).map(o=>o.s??o["?s"]).filter(Boolean)}}class LdpStrategy{constructor(e){this.mode="ldp",this.sparqlExecutor=e.sparqlExecutor,this.sparqlConverter=e.sparqlConverter,this.fetchFn=e.fetchFn,this.ldpExecutor=e.ldpExecutor,this.getResolver=e.getResolver,this.listContainerResources=e.listContainerResources,this.findSubjectsForCondition=e.findSubjectsForCondition}async executeSelect(e,t,r){const i=e.baseTable;if(!i)throw new Error("SELECT plan must have a baseTable");const s=this.getResolver(i),o=e.conditionTree,a=await s.resolveSelectSources(i,t,o,d=>this.listContainerResources(d||t));let u;const c=e;if(c._simpleSelectOptions)u=this.sparqlConverter.convertSimpleSelect(c._simpleSelectOptions,void 0,void 0,!1);else if(c._sql){const d=this.sparqlConverter.parseDrizzleAST(c._sql,i);u=this.sparqlConverter.convertSelect(d,i,void 0,void 0,!1)}else u=this.sparqlConverter.convertSelectPlan(e,void 0,void 0,!1);const l=[];for(const d of a)try{const f=await this.sparqlExecutor.queryContainer(d,u);l.push(...f)}catch(f){console.warn(`[LdpStrategy] Failed to query source ${d}:`,f)}return l}async executeInsert(e,t,r){return await this.ldpExecutor.executeInsert(e.rows,e.table,r,{ensureContainerExists:e.ensureContainerExists,repairContainerOnWriteFailure:e.repairContainerOnWriteFailure,skipResourceExistenceCheck:e.skipResourceExistenceCheck,tableRegistry:e.tableRegistry,tableNameRegistry:e.tableNameRegistry})}async executeUpdate(e,t,r){const s=await this.getResolver(e.table).resolveSubjectsForMutation(e.table,e.where,a=>this.findSubjectsForCondition(e.where,e.table,a),()=>this.listContainerResources(t));return s.length===0?[]:await this.ldpExecutor.executeUpdate(e.table,e.data,s,r)}async executeDelete(e,t,r){if(!e.where)return[];const s=await this.getResolver(e.table).resolveSubjectsForMutation(e.table,e.where,a=>this.findSubjectsForCondition(e.where,e.table,a),()=>this.listContainerResources(t));return s.length===0?[]:await this.ldpExecutor.executeDelete(s,e.table,r)}}class SparqlStrategy{constructor(e){this.mode="sparql",this.sparqlExecutor=e.sparqlExecutor,this.sparqlConverter=e.sparqlConverter,this.podUrl=e.podUrl,this.uriResolver=e.uriResolver,this.createQueryEngine=e.createQueryEngine}setPodUrl(e){this.podUrl=e}resolvePodResourceIri(e){if(!e||/^[a-z][a-z0-9+.-]*:/i.test(e))return e;const t=this.podUrl?.trim();if(!t)return e;const r=t.endsWith("/")?t:`${t}/`;if(e.startsWith("/"))return`${r.replace(/\/+$/,"")}${e}`;try{return new URL(e,r).toString()}catch{return e}}resolveTargetGraph(e,t=!1){return e?this.uriResolver.getResourceMode(e)==="document"?t?void 0:this.resolvePodResourceIri(e.config?.containerPath??e.getContainerPath?.()):this.resolvePodResourceIri(e.config?.base):void 0}async executeSelect(e,t,r){const i=e.baseTable,s=this.resolveTargetGraph(i,!0),o=i.getSparqlEndpoint?.(),a=this.resolvePodResourceIri(o)??r,u=o||a.includes("/sparql")?"sparql":"auto",c=e;let l;const d=s!==void 0;if(c._simpleSelectOptions)l=this.sparqlConverter.convertSimpleSelect(c._simpleSelectOptions,s,void 0,d);else if(c._sql&&e.baseTable){const g=this.sparqlConverter.parseDrizzleAST(c._sql,e.baseTable);l=this.sparqlConverter.convertSelect(g,e.baseTable,s,void 0,d)}else l=this.sparqlConverter.convertSelectPlan(e,s,void 0,d);if(isSameOrigin(a,this.podUrl))return await this.sparqlExecutor.executeQueryWithSource(l,a,u);const{ComunicaSPARQLExecutor:f}=await __vitePreload(async()=>{const{ComunicaSPARQLExecutor:g}=await Promise.resolve().then(()=>sparqlExecutor);return{ComunicaSPARQLExecutor:g}},void 0);return await new f({sources:[a],fetch,logging:!1,createQueryEngine:this.createQueryEngine}).executeQueryWithSource(l,a,u)}async executeInsert(){throw new Error("SPARQL mode INSERT is not supported directly; writes should route through LDP strategy")}async executeUpdate(){throw new Error("SPARQL mode UPDATE is not supported directly; writes should route through LDP strategy")}async executeDelete(){throw new Error("SPARQL mode DELETE is not supported directly; writes should route through LDP strategy")}}class ExecutionStrategyFactoryImpl{constructor(e){this.ldpStrategy=null,this.sparqlStrategy=null,this.deps=e}setPodUrl(e){this.deps.podUrl=e,this.sparqlStrategy?.setPodUrl(e)}getStrategy(e){return e.getSparqlEndpoint?.()?this.getSparqlStrategy():this.getLdpStrategy()}getLdpStrategy(){return this.getLdpStrategyInternal()}getLdpStrategyInternal(){if(!this.ldpStrategy){const e={sparqlExecutor:this.deps.sparqlExecutor,sparqlConverter:this.deps.sparqlConverter,fetchFn:this.deps.sessionFetch,ldpExecutor:this.deps.ldpExecutor,getResolver:this.deps.getResolver,listContainerResources:this.deps.listContainerResources,findSubjectsForCondition:this.deps.findSubjectsForCondition};this.ldpStrategy=new LdpStrategy(e)}return this.ldpStrategy}getSparqlStrategy(){if(!this.sparqlStrategy){const e={sparqlExecutor:this.deps.sparqlExecutor,sparqlConverter:this.deps.sparqlConverter,sessionFetch:this.deps.sessionFetch,podUrl:this.deps.podUrl,uriResolver:this.deps.uriResolver,createQueryEngine:this.deps.createQueryEngine};this.sparqlStrategy=new SparqlStrategy(e)}return this.sparqlStrategy}static getMode(e){return e.getSparqlEndpoint?.()?"sparql":"ldp"}}class BaseResourceResolver{constructor(e){this.podBaseUrl=e}parseId(e,t){return this.extractBaseRelativeResourceId(e,t)}resolveSubject(e,t,r){const i=this.getSubjectBaseUrl(e);let s=t.id??t["@id"]??t.uri;if(s&&this.isAbsoluteUri(s))return s;if(typeof s=="string"){const u=this.resolveBaseRelativeSubjectId(e,s);if(u)return u;s.startsWith("#")&&this.acceptsFragmentOnlyResourceId(e)&&(s=s.slice(1))}const o=this.getEffectiveTemplate(e),a=this.applyTemplate({...t,id:s},o,e,r);return i+a}parseTemplateId(e,t){const r=this.extractTemplateRelativeSubjectId(e,t);return this.extractIdFromTemplate(r,this.getEffectiveTemplate(e))}extractRelativeSubjectId(e,t){const r=this.getBaseUrlForTable(e);return t.startsWith(r)?t.substring(r.length):this.extractIdFallback(t)}extractBaseRelativeResourceId(e,t){const r=this.getContainerUrl(e);if(t.startsWith(r))return t.substring(r.length);const i=this.extractRelativeSubjectId(e,t);return i.startsWith("#")&&!(e.hasCustomTemplate?.()??!1)?`${this.getResourceUrl(e).split("/").filter(Boolean).pop()??""}${i}`:i}extractTemplateRelativeSubjectId(e,t){const r=this.resolveBaseUrl(e);return t.startsWith(r)?t.substring(r.length):this.extractRelativeSubjectId(e,t)}isBaseRelativeSubjectId(e){return!e||this.isAbsoluteUri(e)||e.startsWith("/")?!1:e.startsWith("#")||e.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(e)}acceptsFragmentOnlyResourceId(e){const t=this.getEffectiveTemplate(e),r=this.getTemplateVariables(t);return t==="#{id}"||t.startsWith("#")&&r.length===1&&r[0].field==="id"}resolveBaseRelativeSubjectId(e,t){if(!this.isBaseRelativeSubjectId(t))return null;const r=this.getSubjectBaseUrl(e);if(t.startsWith("#"))return this.acceptsFragmentOnlyResourceId(e)?`${r}${t}`:null;if(r.endsWith("/"))return`${r}${t}`;const i=r.lastIndexOf("/");return`${i>=0?r.slice(0,i+1):`${r}/`}${t}`}hasVirtualIdColumn(e){return!!e.columns?.id?._virtualId}getBaseUrlForTable(e){return this.resolveBaseUrl(e)}getSubjectBaseUrl(e){return this.acceptsFragmentOnlyResourceId(e)?this.getResourceUrl(e):this.getBaseUrlForTable(e)}getEffectiveTemplate(e){return e.config?.subjectTemplate?e.config.subjectTemplate:this.getDefaultTemplate()}generateUuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}applyTemplate(e,t,r,i){if(!t.includes("{"))return t;const s=this.createTimeContext(e);return t.replace(/(#?)\{([^}]+)\}/g,(o,a,u)=>{const c=this.parseTemplateVariable(u),l=c.field;if(l==="index"&&i!==void 0)return a+String(i+1);if(l in s)return a+s[l];let d=e[l];if(l==="id"&&d==null&&(d=e["@id"]??e.uri),d==null)return`${a}{${u}}`;const f=this.applyTemplateTransforms(d,c,r,l);return a==="#"&&f.startsWith("#")?a+f.slice(1):a+f})}extractVarsFromTemplate(e,t){let r=0;const i=new Map;let s=t.replace(/[.+?^$[\]\\()]/g,"\\$&").replace(/\{([^}]+)\}/g,(o,a)=>{const u=this.parseTemplateVariable(a),c=`var${r++}`;return i.set(c,u.field),`(?<${c}>.+?)`});s=`^${s}$`;try{const o=e.match(new RegExp(s));if(!o?.groups)return null;const a={};for(const[u,c]of Object.entries(o.groups)){const l=i.get(u);if(!(!l||c===void 0)){if(l in a&&a[l]!==c)return null;a[l]=c}}return a}catch{return null}}extractIdFromTemplate(e,t){return this.extractVarsFromTemplate(e,t)?.id??null}extractIdValues(e){if(!e)return[];const t=[];if(typeof e=="object"&&!("type"in e)){for(const[r,i]of Object.entries(e)){const s=this.normalizeConditionColumnName(r);s!=="id"&&s!=="@id"||(Array.isArray(i)?t.push(...i.map(String)):i!=null&&t.push(String(i)))}if(t.length>0)return t}return this.collectIdValues(e,t),t}extractTemplateValues(e,t){if(!e||t.length===0)return{};const r=Array.from(new Set(t.map(s=>this.parseTemplateVariable(s).field))),i={};if(typeof e=="object"&&!("type"in e)){for(const[s,o]of Object.entries(e)){const a=this.normalizeConditionColumnName(s);r.includes(a)&&o!=null&&!Array.isArray(o)&&(i[a]=String(o))}return i}for(const s of r){const o=this.collectColumnValue(e,s);o!==void 0&&(i[s]=o)}return i}collectColumnValue(e,t){if(e){if(e.type==="binary_expr"&&this.normalizeConditionColumnName(e.left)===t&&e.operator==="="&&e.right!=null)return String(e.right);if(e.type==="logical_expr"&&e.operator==="AND"&&Array.isArray(e.expressions))for(const r of e.expressions){const i=this.collectColumnValue(r,t);if(i!==void 0)return i}}}collectIdValues(e,t){if(e){if(e.type==="binary_expr"){const r=this.normalizeConditionColumnName(e.left);(r==="id"||r==="@id")&&(e.operator==="="&&e.right!=null?t.push(String(e.right)):e.operator==="IN"&&Array.isArray(e.right)&&t.push(...e.right.map(String)))}if(e.type==="logical_expr"&&Array.isArray(e.expressions))for(const r of e.expressions)this.collectIdValues(r,t)}}normalizeConditionColumnName(e){let t;if(typeof e=="string")t=e;else if(e&&typeof e=="object"&&"name"in e){const r=e.name;t=typeof r=="string"?r:void 0}return t?t.includes(".")?t.split(".").pop()??t:t:""}parseTemplateVariable(e){const[t,...r]=e.split("|").map(i=>i.trim()).filter(Boolean);return{raw:e,field:t||e,transforms:r}}getTemplateVariables(e){return Array.from(e.matchAll(/\{([^}]+)\}/g)).map(t=>this.parseTemplateVariable(t[1]))}createTimeContext(e){let t;const r=e.createdAt??e.created_at??e.dateCreated;return r instanceof Date?t=r:typeof r=="string"||typeof r=="number"?t=new Date(r):t=new Date,{yyyy:t.getUTCFullYear().toString(),MM:String(t.getUTCMonth()+1).padStart(2,"0"),dd:String(t.getUTCDate()).padStart(2,"0"),HH:String(t.getUTCHours()).padStart(2,"0"),mm:String(t.getUTCMinutes()).padStart(2,"0"),ss:String(t.getUTCSeconds()).padStart(2,"0")}}applyTemplateTransforms(e,t,r,i){let s=this.normalizeTemplateValue(e,r,i);for(const o of t.transforms){if(o==="id"){s=this.extractTemplateId(s,r,i);continue}o==="slug"&&(s=this.slugifyValue(s))}return s}normalizeTemplateValue(e,t,r){const i=String(e);if(!t||!r||!this.isAbsoluteUri(i))return i;const s=t.columns?.[r];return this.isLinkColumn(s)?this.extractTemplateId(i,t,r):i}extractTemplateId(e,t,r){if(e.startsWith("/")){const a=this.podBaseUrl.endsWith("/")?this.podBaseUrl:`${this.podBaseUrl}/`;e=new URL(e.replace(/^\/+/,""),a).toString()}if(!this.isAbsoluteUri(e))return e;const i=t&&r?t.columns?.[r]:void 0,s=i?.getLinkTable?.()??i?.options?.linkTable;if(s)return this.parseTemplateId(s,e)??this.parseId(s,e);const o=this.extractIdFallback(e);return o.startsWith("#")?o.slice(1):o.replace(/\.ttl$/i,"")}isLinkColumn(e){return!!(e?.getLinkTable?.()||e?.options?.linkTable||e?.getLinkTableName?.()||e?.options?.linkTableName||e?.getLinkTarget?.()||e?.options?.linkTarget)}slugifyValue(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{Letter}\p{Number}]+/gu,"-").replace(/^-+|-+$/g,"")}resolveBaseUrl(e){const t=e.config.base||e.config.name;if(t.startsWith("http://")||t.startsWith("https://"))return t;const r=this.podBaseUrl.endsWith("/")?this.podBaseUrl:`${this.podBaseUrl}/`,i=t.startsWith("/")?t.slice(1):t;return new URL(i,r).toString()}isAbsoluteUri(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("urn:")}extractIdFallback(e){const t=e.indexOf("#");if(t!==-1)return e.substring(t);const r=e.lastIndexOf("/");return r!==-1?e.substring(r+1):e}}const DEFAULT_TEMPLATE$1="{id}";class FragmentResourceResolver extends BaseResourceResolver{constructor(){super(...arguments),this.mode="fragment"}getDefaultTemplate(){return DEFAULT_TEMPLATE$1}getContainerUrl(e){const t=this.getResourceUrl(e),r=t.lastIndexOf("/");return t.substring(0,r+1)}getResourceUrl(e){return this.resolveBaseUrl(e)}getBaseUrlForTable(e){return this.getResourceUrl(e)}getResourceUrlForSubject(e){const t=e.indexOf("#");return t===-1?e:e.substring(0,t)}async resolveSelectSources(e,t,r,i){return[this.getResourceUrl(e)]}async resolveSubjectsForMutation(e,t,r,i){const s=this.extractIdValues(t);if(s.length>0)return s.map(a=>this.resolveSubject(e,{id:a}));const o=this.getResourceUrl(e);return r(o)}}class DebugLogger{constructor(e=!1,t="[drizzle-solid]"){this.enabled=e,this.prefix=t}log(e,...t){this.enabled&&console.log(`${this.prefix} ${e}`,...t)}warn(e,...t){this.enabled&&console.warn(`${this.prefix} ⚠️ ${e}`,...t)}error(e,...t){this.enabled&&console.error(`${this.prefix} ❌ ${e}`,...t)}group(e){this.enabled&&console.group(`${this.prefix} ${e}`)}groupEnd(){this.enabled&&console.groupEnd()}table(e){this.enabled&&console.table(e)}}let globalDebugLogger=null;function setGlobalDebugLogger(n){globalDebugLogger=n}function getGlobalDebugLogger(){return globalDebugLogger||(globalDebugLogger=new DebugLogger(!1)),globalDebugLogger}const DEFAULT_TEMPLATE="{id}";class DocumentResourceResolver extends BaseResourceResolver{constructor(){super(...arguments),this.mode="document"}buildUnsupportedCollectionReadError(e){return new Error(`Document-mode collection queries over plain LDP are not supported for table "${e.config.name}". Configure a global query capability (SPARQL endpoint or index), or use findById()/findByIri() for exact-target reads.`)}buildUnsupportedCollectionMutationError(e){return new Error(`Document-mode collection mutations over plain LDP are not supported for table "${e.config.name}". Use updateById()/updateByIri() or deleteById()/deleteByIri() for exact-target mutations.`)}getDefaultTemplate(){return DEFAULT_TEMPLATE}getContainerUrl(e){const t=e.getContainerPath();if(t.startsWith("http://")||t.startsWith("https://"))return t;const r=this.podBaseUrl.endsWith("/")?this.podBaseUrl:`${this.podBaseUrl}/`,i=t.startsWith("/")?t.slice(1):t;return new URL(i,r).toString()}getResourceUrl(e){return`${this.getContainerUrl(e)}${e.config.name}.ttl`}getBaseUrlForTable(e){return this.getContainerUrl(e)}getResourceUrlForSubject(e){const t=e.indexOf("#");return t!==-1?e.substring(0,t):e}async resolveSelectSources(e,t,r,i){const s=getGlobalDebugLogger(),o=this.getEffectiveTemplate(e),a=Array.from(new Set(this.getTemplateVariables(o).map(l=>l.field))).filter(l=>l!=="id"&&l!=="index"),u=this.extractIdValues(r),c=this.extractTemplateValues(r,a);if(u.length>0&&!("id"in c)&&(c.id=u[0]),s.group(`[Document Resolver] Resolving SELECT sources for table: ${e.name||"unknown"}`),s.log("Template:",o),s.log("ID values from condition:",u),s.log("Template values:",c),u.length>0){const l=u[0];if(this.isAbsoluteUri(l))return s.log("Full URI provided, using directly"),s.groupEnd(),u.map(d=>this.getResourceUrlForSubject(d))}if(u.length>0){if(a.every(f=>f in c)){s.log("All variables present, resolving directly");const f=u.map(m=>{const g=this.resolveSubject(e,{...c,id:m});return this.getResourceUrlForSubject(g)});return s.log("Resolved sources:",f),s.groupEnd(),f}const d=a.filter(f=>!(f in c));throw s.error("Missing required variables:",d),s.groupEnd(),new Error(`Cannot resolve subjectTemplate '${o}': missing required variable(s) [${d.join(", ")}] in query condition. Add eq(table.${d[0]}, value) to your where clause.`)}throw s.error("Document-mode LDP collection query is unsupported without an exact target"),s.groupEnd(),this.buildUnsupportedCollectionReadError(e)}async resolveSubjectsForMutation(e,t,r,i){const s=this.getEffectiveTemplate(e),o=Array.from(new Set(this.getTemplateVariables(s).map(c=>c.field))).filter(c=>c!=="id"&&c!=="index"),a=this.extractIdValues(t),u=this.extractTemplateValues(t,o);if(a.length>0&&!("id"in u)&&(u.id=a[0]),a.length>0){const c=a[0];if(this.isAbsoluteUri(c))return a}if(a.length>0){if(o.every(d=>d in u))return a.map(d=>this.resolveSubject(e,{...u,id:d}));const l=o.filter(d=>!(d in u));throw new Error(`Cannot resolve subjectTemplate '${s}' for mutation: missing required variable(s) [${l.join(", ")}] in query condition. Add eq(table.${l[0]}, value) to your where clause.`)}throw this.buildUnsupportedCollectionMutationError(e)}}class ResourceResolverFactoryImpl{constructor(e,t){this.resolverCache=new WeakMap,this.podBaseUrl=e,this.uriResolver=t??new UriResolverImpl}setPodBaseUrl(e){this.podBaseUrl=e,this.resolverCache=new WeakMap}getResolver(e){const t=this.resolverCache.get(e);if(t)return t;const i=this.determineMode(e)==="document"?new DocumentResourceResolver(this.podBaseUrl):new FragmentResourceResolver(this.podBaseUrl);return this.resolverCache.set(e,i),i}determineMode(e){return this.uriResolver.getResourceMode(e)}}const XSD={STRING:"http://www.w3.org/2001/XMLSchema#string",INTEGER:"http://www.w3.org/2001/XMLSchema#integer",BOOLEAN:"http://www.w3.org/2001/XMLSchema#boolean",DATETIME:"http://www.w3.org/2001/XMLSchema#dateTime",DATE:"http://www.w3.org/2001/XMLSchema#date",DECIMAL:"http://www.w3.org/2001/XMLSchema#decimal",DOUBLE:"http://www.w3.org/2001/XMLSchema#double",ANYURI:"http://www.w3.org/2001/XMLSchema#anyURI"},SHACL={NS:"http://www.w3.org/ns/shacl#",NODE_SHAPE:"http://www.w3.org/ns/shacl#NodeShape",TARGET_CLASS:"http://www.w3.org/ns/shacl#targetClass",PROPERTY:"http://www.w3.org/ns/shacl#property",PATH:"http://www.w3.org/ns/shacl#path",DATATYPE:"http://www.w3.org/ns/shacl#datatype",NODE_KIND:"http://www.w3.org/ns/shacl#nodeKind",MIN_COUNT:"http://www.w3.org/ns/shacl#minCount",MAX_COUNT:"http://www.w3.org/ns/shacl#maxCount",PATTERN:"http://www.w3.org/ns/shacl#pattern",NAME:"http://www.w3.org/ns/shacl#name",DESCRIPTION:"http://www.w3.org/ns/shacl#description",CLASS:"http://www.w3.org/ns/shacl#class",INVERSE_PATH:"http://www.w3.org/ns/shacl#inversePath",IRI:"http://www.w3.org/ns/shacl#IRI",LITERAL:"http://www.w3.org/ns/shacl#Literal",BLANK_NODE:"http://www.w3.org/ns/shacl#BlankNode"};var _a$2;function $constructor(n,e,t){function r(a,u){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:u,constr:o,traits:new Set},enumerable:!1}),a._zod.traits.has(n))return;a._zod.traits.add(n),e(a,u);const c=o.prototype,l=Object.keys(c);for(let d=0;d<l.length;d++){const f=l[d];f in a||(a[f]=c[f].bind(a))}}const i=t?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:n});function o(a){var u;const c=t?.Parent?new s:this;r(c,a),(u=c._zod).deferred??(u.deferred=[]);for(const l of c._zod.deferred)l();return c}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>t?.Parent&&a instanceof t.Parent?!0:a?._zod?.traits?.has(n)}),Object.defineProperty(o,"name",{value:n}),o}class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class $ZodEncodeError extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(_a$2=globalThis).__zod_globalConfig??(_a$2.__zod_globalConfig={});const globalConfig=globalThis.__zod_globalConfig;function config(n){return globalConfig}function getEnumValues(n){const e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,i])=>e.indexOf(+r)===-1).map(([r,i])=>i)}function jsonStringifyReplacer(n,e){return typeof e=="bigint"?e.toString():e}function cached(n){return{get value(){{const e=n();return Object.defineProperty(this,"value",{value:e}),e}}}}function nullish(n){return n==null}function cleanRegex(n){const e=n.startsWith("^")?1:0,t=n.endsWith("$")?n.length-1:n.length;return n.slice(e,t)}function floatSafeRemainder$1(n,e){const t=n/e,r=Math.round(t),i=Number.EPSILON*Math.max(Math.abs(t),1);return Math.abs(t-r)<i?0:t-r}const EVALUATING=Symbol("evaluating");function defineLazy(n,e,t){let r;Object.defineProperty(n,e,{get(){if(r!==EVALUATING)return r===void 0&&(r=EVALUATING,r=t()),r},set(i){Object.defineProperty(n,e,{value:i})},configurable:!0})}function assignProp(n,e,t){Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...n){const e={};for(const t of n){const r=Object.getOwnPropertyDescriptors(t);Object.assign(e,r)}return Object.defineProperties({},e)}function esc(n){return JSON.stringify(n)}function slugify(n){return n.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(...n)=>{};function isObject$1(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const n=Function;return new n(""),!0}catch{return!1}});function isPlainObject(n){if(isObject$1(n)===!1)return!1;const e=n.constructor;if(e===void 0||typeof e!="function")return!0;const t=e.prototype;return!(isObject$1(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function shallowClone(n){return isPlainObject(n)?{...n}:Array.isArray(n)?[...n]:n instanceof Map?new Map(n):n instanceof Set?new Set(n):n}const propertyKeyTypes=new Set(["string","number","symbol"]);function escapeRegex(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone$1(n,e,t){const r=new n._zod.constr(e??n._zod.def);return(!e||t?.parent)&&(r._zod.parent=n),r}function normalizeParams(n){const e=n;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function optionalKeys(n){return Object.keys(n).filter(e=>n[e]._zod.optin==="optional"&&n[e]._zod.optout==="optional")}const NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function pick(n,e){const t=n._zod.def,r=t.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=mergeDefs(n._zod.def,{get shape(){const o={};for(const a in e){if(!(a in t.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(o[a]=t.shape[a])}return assignProp(this,"shape",o),o},checks:[]});return clone$1(n,s)}function omit(n,e){const t=n._zod.def,r=t.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=mergeDefs(n._zod.def,{get shape(){const o={...n._zod.def.shape};for(const a in e){if(!(a in t.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete o[a]}return assignProp(this,"shape",o),o},checks:[]});return clone$1(n,s)}function extend(n,e){if(!isPlainObject(e))throw new Error("Invalid input to extend: expected a plain object");const t=n._zod.def.checks;if(t&&t.length>0){const s=n._zod.def.shape;for(const o in e)if(Object.getOwnPropertyDescriptor(s,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=mergeDefs(n._zod.def,{get shape(){const s={...n._zod.def.shape,...e};return assignProp(this,"shape",s),s}});return clone$1(n,i)}function safeExtend(n,e){if(!isPlainObject(e))throw new Error("Invalid input to safeExtend: expected a plain object");const t=mergeDefs(n._zod.def,{get shape(){const r={...n._zod.def.shape,...e};return assignProp(this,"shape",r),r}});return clone$1(n,t)}function merge(n,e){if(n._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const t=mergeDefs(n._zod.def,{get shape(){const r={...n._zod.def.shape,...e._zod.def.shape};return assignProp(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return clone$1(n,t)}function partial(n,e,t){const i=e._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const o=mergeDefs(e._zod.def,{get shape(){const a=e._zod.def.shape,u={...a};if(t)for(const c in t){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(u[c]=n?new n({type:"optional",innerType:a[c]}):a[c])}else for(const c in a)u[c]=n?new n({type:"optional",innerType:a[c]}):a[c];return assignProp(this,"shape",u),u},checks:[]});return clone$1(e,o)}function required(n,e,t){const r=mergeDefs(e._zod.def,{get shape(){const i=e._zod.def.shape,s={...i};if(t)for(const o in t){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(s[o]=new n({type:"nonoptional",innerType:i[o]}))}else for(const o in i)s[o]=new n({type:"nonoptional",innerType:i[o]});return assignProp(this,"shape",s),s}});return clone$1(e,r)}function aborted(n,e=0){if(n.aborted===!0)return!0;for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue!==!0)return!0;return!1}function explicitlyAborted(n,e=0){if(n.aborted===!0)return!0;for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue===!1)return!0;return!1}function prefixIssues(n,e){return e.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(n),t})}function unwrapMessage(n){return typeof n=="string"?n:n?.message}function finalizeIssue(n,e,t){const r=n.message?n.message:unwrapMessage(n.inst?._zod.def?.error?.(n))??unwrapMessage(e?.error?.(n))??unwrapMessage(t.customError?.(n))??unwrapMessage(t.localeError?.(n))??"Invalid input",{inst:i,continue:s,input:o,...a}=n;return a.path??(a.path=[]),a.message=r,e?.reportInput&&(a.input=o),a}function getLengthableOrigin(n){return Array.isArray(n)?"array":typeof n=="string"?"string":"unknown"}function issue(...n){const[e,t,r]=n;return typeof e=="string"?{message:e,code:"custom",input:t,inst:r}:{...e}}const initializer$1=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),n.message=JSON.stringify(e,jsonStringifyReplacer,2),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer$1),$ZodRealError=$constructor("$ZodError",initializer$1,{Parent:Error});function flattenError(n,e=t=>t.message){const t={},r=[];for(const i of n.issues)i.path.length>0?(t[i.path[0]]=t[i.path[0]]||[],t[i.path[0]].push(e(i))):r.push(e(i));return{formErrors:r,fieldErrors:t}}function formatError(n,e=t=>t.message){const t={_errors:[]},r=(i,s=[])=>{for(const o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>r({issues:a},[...s,...o.path]));else if(o.code==="invalid_key")r({issues:o.issues},[...s,...o.path]);else if(o.code==="invalid_element")r({issues:o.issues},[...s,...o.path]);else{const a=[...s,...o.path];if(a.length===0)t._errors.push(e(o));else{let u=t,c=0;for(;c<a.length;){const l=a[c];c===a.length-1?(u[l]=u[l]||{_errors:[]},u[l]._errors.push(e(o))):u[l]=u[l]||{_errors:[]},u=u[l],c++}}}};return r(n),t}const _parse=n=>(e,t,r,i)=>{const s=r?{...r,async:!1}:{async:!1},o=e._zod.run({value:t,issues:[]},s);if(o instanceof Promise)throw new $ZodAsyncError;if(o.issues.length){const a=new(i?.Err??n)(o.issues.map(u=>finalizeIssue(u,s,config())));throw captureStackTrace(a,i?.callee),a}return o.value},_parseAsync=n=>async(e,t,r,i)=>{const s=r?{...r,async:!0}:{async:!0};let o=e._zod.run({value:t,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const a=new(i?.Err??n)(o.issues.map(u=>finalizeIssue(u,s,config())));throw captureStackTrace(a,i?.callee),a}return o.value},_safeParse=n=>(e,t,r)=>{const i=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:t,issues:[]},i);if(s instanceof Promise)throw new $ZodAsyncError;return s.issues.length?{success:!1,error:new(n??$ZodError)(s.issues.map(o=>finalizeIssue(o,i,config())))}:{success:!0,data:s.value}},safeParse$1=_safeParse($ZodRealError),_safeParseAsync=n=>async(e,t,r)=>{const i=r?{...r,async:!0}:{async:!0};let s=e._zod.run({value:t,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new n(s.issues.map(o=>finalizeIssue(o,i,config())))}:{success:!0,data:s.value}},safeParseAsync$1=_safeParseAsync($ZodRealError),_encode=n=>(e,t,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return _parse(n)(e,t,i)},_decode=n=>(e,t,r)=>_parse(n)(e,t,r),_encodeAsync=n=>async(e,t,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return _parseAsync(n)(e,t,i)},_decodeAsync=n=>async(e,t,r)=>_parseAsync(n)(e,t,r),_safeEncode=n=>(e,t,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return _safeParse(n)(e,t,i)},_safeDecode=n=>(e,t,r)=>_safeParse(n)(e,t,r),_safeEncodeAsync=n=>async(e,t,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return _safeParseAsync(n)(e,t,i)},_safeDecodeAsync=n=>async(e,t,r)=>_safeParseAsync(n)(e,t,r),cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=n=>n?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji$1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function emoji(){return new RegExp(_emoji$1,"u")}const ipv4=/^(?:(?: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])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource="(?:(?:\\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])))",date$2=new RegExp(`^${dateSource}$`);function timeSource(n){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof n.precision=="number"?n.precision===-1?`${e}`:n.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${n.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time$1(n){return new RegExp(`^${timeSource(n)}$`)}function datetime$1(n){const e=timeSource({precision:n.precision}),t=["Z"];n.local&&t.push(""),n.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${t.join("|")})`;return new RegExp(`^${dateSource}T(?:${r})$`)}const string$1=n=>{const e=n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},integer=/^-?\d+$/,number$1=/^-?\d+(?:\.\d+)?$/,boolean$1=/^(?:true|false)$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,$ZodCheck=$constructor("$ZodCheck",(n,e)=>{var t;n._zod??(n._zod={}),n._zod.def=e,(t=n._zod).onattach??(t.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(n,e)=>{$ZodCheck.init(n,e);const t=numericOriginMap[typeof e.value];n._zod.onattach.push(r=>{const i=r._zod.bag,s=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),n._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:t,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(n,e)=>{$ZodCheck.init(n,e);const t=numericOriginMap[typeof e.value];n._zod.onattach.push(r=>{const i=r._zod.bag,s=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),n._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:t,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(n,e)=>{$ZodCheck.init(n,e),n._zod.onattach.push(t=>{var r;(r=t._zod.bag).multipleOf??(r.multipleOf=e.value)}),n._zod.check=t=>{if(typeof t.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof t.value=="bigint"?t.value%e.value===BigInt(0):floatSafeRemainder$1(t.value,e.value)===0)||t.issues.push({origin:typeof t.value,code:"not_multiple_of",divisor:e.value,input:t.value,inst:n,continue:!e.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(n,e)=>{$ZodCheck.init(n,e),e.format=e.format||"float64";const t=e.format?.includes("int"),r=t?"int":"number",[i,s]=NUMBER_FORMAT_RANGES[e.format];n._zod.onattach.push(o=>{const a=o._zod.bag;a.format=e.format,a.minimum=i,a.maximum=s,t&&(a.pattern=integer)}),n._zod.check=o=>{const a=o.value;if(t){if(!Number.isInteger(a)){o.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:a,inst:n});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,inclusive:!0,continue:!e.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,inclusive:!0,continue:!e.abort});return}}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:n,continue:!e.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:n,continue:!e.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(n,e)=>{var t;$ZodCheck.init(n,e),(t=n._zod.def).when??(t.when=r=>{const i=r.value;return!nullish(i)&&i.length!==void 0}),n._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(r._zod.bag.maximum=e.maximum)}),n._zod.check=r=>{const i=r.value;if(i.length<=e.maximum)return;const o=getLengthableOrigin(i);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:n,continue:!e.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(n,e)=>{var t;$ZodCheck.init(n,e),(t=n._zod.def).when??(t.when=r=>{const i=r.value;return!nullish(i)&&i.length!==void 0}),n._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(r._zod.bag.minimum=e.minimum)}),n._zod.check=r=>{const i=r.value;if(i.length>=e.minimum)return;const o=getLengthableOrigin(i);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:n,continue:!e.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(n,e)=>{var t;$ZodCheck.init(n,e),(t=n._zod.def).when??(t.when=r=>{const i=r.value;return!nullish(i)&&i.length!==void 0}),n._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),n._zod.check=r=>{const i=r.value,s=i.length;if(s===e.length)return;const o=getLengthableOrigin(i),a=s>e.length;r.issues.push({origin:o,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:n,continue:!e.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(n,e)=>{var t,r;$ZodCheck.init(n,e),n._zod.onattach.push(i=>{const s=i._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(t=n._zod).check??(t.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:n,continue:!e.abort})}):(r=n._zod).check??(r.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(n,e)=>{$ZodCheckStringFormat.init(n,e),n._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:n,continue:!e.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(n,e)=>{e.pattern??(e.pattern=lowercase),$ZodCheckStringFormat.init(n,e)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(n,e)=>{e.pattern??(e.pattern=uppercase),$ZodCheckStringFormat.init(n,e)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(n,e)=>{$ZodCheck.init(n,e);const t=escapeRegex(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${t}`:t);e.pattern=r,n._zod.onattach.push(i=>{const s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),n._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:n,continue:!e.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(n,e)=>{$ZodCheck.init(n,e);const t=new RegExp(`^${escapeRegex(e.prefix)}.*`);e.pattern??(e.pattern=t),n._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(t)}),n._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:n,continue:!e.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(n,e)=>{$ZodCheck.init(n,e);const t=new RegExp(`.*${escapeRegex(e.suffix)}$`);e.pattern??(e.pattern=t),n._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(t)}),n._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:n,continue:!e.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(n,e)=>{$ZodCheck.init(n,e),n._zod.check=t=>{t.value=e.tx(t.value)}});class Doc{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
|
|
150
|
+
`).filter(o=>o),i=Math.min(...r.map(o=>o.length-o.trimStart().length)),s=r.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(const o of s)this.content.push(o)}compile(){const e=Function,t=this?.args,i=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...t,i.join(`
|
|
151
|
+
`))}}const version={major:4,minor:4,patch:3},$ZodType=$constructor("$ZodType",(n,e)=>{var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=version;const r=[...n._zod.def.checks??[]];n._zod.traits.has("$ZodCheck")&&r.unshift(n);for(const i of r)for(const s of i._zod.onattach)s(n);if(r.length===0)(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{const i=(o,a,u)=>{let c=aborted(o),l;for(const d of a){if(d._zod.def.when){if(explicitlyAborted(o)||!d._zod.def.when(o))continue}else if(c)continue;const f=o.issues.length,m=d._zod.check(o);if(m instanceof Promise&&u?.async===!1)throw new $ZodAsyncError;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await m,o.issues.length!==f&&(c||(c=aborted(o,f)))});else{if(o.issues.length===f)continue;c||(c=aborted(o,f))}}return l?l.then(()=>o):o},s=(o,a,u)=>{if(aborted(o))return o.aborted=!0,o;const c=i(a,r,u);if(c instanceof Promise){if(u.async===!1)throw new $ZodAsyncError;return c.then(l=>n._zod.parse(l,u))}return n._zod.parse(c,u)};n._zod.run=(o,a)=>{if(a.skipChecks)return n._zod.parse(o,a);if(a.direction==="backward"){const c=n._zod.parse({value:o.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(l=>s(l,o,a)):s(c,o,a)}const u=n._zod.parse(o,a);if(u instanceof Promise){if(a.async===!1)throw new $ZodAsyncError;return u.then(c=>i(c,r,a))}return i(u,r,a)}}defineLazy(n,"~standard",()=>({validate:i=>{try{const s=safeParse$1(n,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return safeParseAsync$1(n,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),$ZodString=$constructor("$ZodString",(n,e)=>{$ZodType.init(n,e),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??string$1(n._zod.bag),n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:n}),t}}),$ZodStringFormat=$constructor("$ZodStringFormat",(n,e)=>{$ZodCheckStringFormat.init(n,e),$ZodString.init(n,e)}),$ZodGUID=$constructor("$ZodGUID",(n,e)=>{e.pattern??(e.pattern=guid),$ZodStringFormat.init(n,e)}),$ZodUUID=$constructor("$ZodUUID",(n,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=uuid(r))}else e.pattern??(e.pattern=uuid());$ZodStringFormat.init(n,e)}),$ZodEmail=$constructor("$ZodEmail",(n,e)=>{e.pattern??(e.pattern=email),$ZodStringFormat.init(n,e)}),$ZodURL=$constructor("$ZodURL",(n,e)=>{$ZodStringFormat.init(n,e),n._zod.check=t=>{try{const r=t.value.trim();if(!e.normalize&&e.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(r)){t.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:t.value,inst:n,continue:!e.abort});return}const i=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:t.value,inst:n,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:t.value,inst:n,continue:!e.abort})),e.normalize?t.value=i.href:t.value=r;return}catch{t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:n,continue:!e.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(n,e)=>{e.pattern??(e.pattern=emoji()),$ZodStringFormat.init(n,e)}),$ZodNanoID=$constructor("$ZodNanoID",(n,e)=>{e.pattern??(e.pattern=nanoid),$ZodStringFormat.init(n,e)}),$ZodCUID=$constructor("$ZodCUID",(n,e)=>{e.pattern??(e.pattern=cuid),$ZodStringFormat.init(n,e)}),$ZodCUID2=$constructor("$ZodCUID2",(n,e)=>{e.pattern??(e.pattern=cuid2),$ZodStringFormat.init(n,e)}),$ZodULID=$constructor("$ZodULID",(n,e)=>{e.pattern??(e.pattern=ulid),$ZodStringFormat.init(n,e)}),$ZodXID=$constructor("$ZodXID",(n,e)=>{e.pattern??(e.pattern=xid),$ZodStringFormat.init(n,e)}),$ZodKSUID=$constructor("$ZodKSUID",(n,e)=>{e.pattern??(e.pattern=ksuid),$ZodStringFormat.init(n,e)}),$ZodISODateTime=$constructor("$ZodISODateTime",(n,e)=>{e.pattern??(e.pattern=datetime$1(e)),$ZodStringFormat.init(n,e)}),$ZodISODate=$constructor("$ZodISODate",(n,e)=>{e.pattern??(e.pattern=date$2),$ZodStringFormat.init(n,e)}),$ZodISOTime=$constructor("$ZodISOTime",(n,e)=>{e.pattern??(e.pattern=time$1(e)),$ZodStringFormat.init(n,e)}),$ZodISODuration=$constructor("$ZodISODuration",(n,e)=>{e.pattern??(e.pattern=duration$1),$ZodStringFormat.init(n,e)}),$ZodIPv4=$constructor("$ZodIPv4",(n,e)=>{e.pattern??(e.pattern=ipv4),$ZodStringFormat.init(n,e),n._zod.bag.format="ipv4"}),$ZodIPv6=$constructor("$ZodIPv6",(n,e)=>{e.pattern??(e.pattern=ipv6),$ZodStringFormat.init(n,e),n._zod.bag.format="ipv6",n._zod.check=t=>{try{new URL(`http://[${t.value}]`)}catch{t.issues.push({code:"invalid_format",format:"ipv6",input:t.value,inst:n,continue:!e.abort})}}}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(n,e)=>{e.pattern??(e.pattern=cidrv4),$ZodStringFormat.init(n,e)}),$ZodCIDRv6=$constructor("$ZodCIDRv6",(n,e)=>{e.pattern??(e.pattern=cidrv6),$ZodStringFormat.init(n,e),n._zod.check=t=>{const r=t.value.split("/");try{if(r.length!==2)throw new Error;const[i,s]=r;if(!s)throw new Error;const o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${i}]`)}catch{t.issues.push({code:"invalid_format",format:"cidrv6",input:t.value,inst:n,continue:!e.abort})}}});function isValidBase64(n){if(n==="")return!0;if(/\s/.test(n)||n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}const $ZodBase64=$constructor("$ZodBase64",(n,e)=>{e.pattern??(e.pattern=base64),$ZodStringFormat.init(n,e),n._zod.bag.contentEncoding="base64",n._zod.check=t=>{isValidBase64(t.value)||t.issues.push({code:"invalid_format",format:"base64",input:t.value,inst:n,continue:!e.abort})}});function isValidBase64URL(n){if(!base64url.test(n))return!1;const e=n.replace(/[-_]/g,r=>r==="-"?"+":"/"),t=e.padEnd(Math.ceil(e.length/4)*4,"=");return isValidBase64(t)}const $ZodBase64URL=$constructor("$ZodBase64URL",(n,e)=>{e.pattern??(e.pattern=base64url),$ZodStringFormat.init(n,e),n._zod.bag.contentEncoding="base64url",n._zod.check=t=>{isValidBase64URL(t.value)||t.issues.push({code:"invalid_format",format:"base64url",input:t.value,inst:n,continue:!e.abort})}}),$ZodE164=$constructor("$ZodE164",(n,e)=>{e.pattern??(e.pattern=e164),$ZodStringFormat.init(n,e)});function isValidJWT$1(n,e=null){try{const t=n.split(".");if(t.length!==3)return!1;const[r]=t;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}const $ZodJWT=$constructor("$ZodJWT",(n,e)=>{$ZodStringFormat.init(n,e),n._zod.check=t=>{isValidJWT$1(t.value,e.alg)||t.issues.push({code:"invalid_format",format:"jwt",input:t.value,inst:n,continue:!e.abort})}}),$ZodNumber=$constructor("$ZodNumber",(n,e)=>{$ZodType.init(n,e),n._zod.pattern=n._zod.bag.pattern??number$1,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}const i=t.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return t;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return t.issues.push({expected:"number",code:"invalid_type",input:i,inst:n,...s?{received:s}:{}}),t}}),$ZodNumberFormat=$constructor("$ZodNumberFormat",(n,e)=>{$ZodCheckNumberFormat.init(n,e),$ZodNumber.init(n,e)}),$ZodBoolean=$constructor("$ZodBoolean",(n,e)=>{$ZodType.init(n,e),n._zod.pattern=boolean$1,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=!!t.value}catch{}const i=t.value;return typeof i=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:n}),t}}),$ZodAny=$constructor("$ZodAny",(n,e)=>{$ZodType.init(n,e),n._zod.parse=t=>t}),$ZodUnknown=$constructor("$ZodUnknown",(n,e)=>{$ZodType.init(n,e),n._zod.parse=t=>t}),$ZodNever=$constructor("$ZodNever",(n,e)=>{$ZodType.init(n,e),n._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)}),$ZodDate=$constructor("$ZodDate",(n,e)=>{$ZodType.init(n,e),n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=new Date(t.value)}catch{}const i=t.value,s=i instanceof Date;return s&&!Number.isNaN(i.getTime())||t.issues.push({expected:"date",code:"invalid_type",input:i,...s?{received:"Invalid Date"}:{},inst:n}),t}});function handleArrayResult(n,e,t){n.issues.length&&e.issues.push(...prefixIssues(t,n.issues)),e.value[t]=n.value}const $ZodArray=$constructor("$ZodArray",(n,e)=>{$ZodType.init(n,e),n._zod.parse=(t,r)=>{const i=t.value;if(!Array.isArray(i))return t.issues.push({expected:"array",code:"invalid_type",input:i,inst:n}),t;t.value=Array(i.length);const s=[];for(let o=0;o<i.length;o++){const a=i[o],u=e.element._zod.run({value:a,issues:[]},r);u instanceof Promise?s.push(u.then(c=>handleArrayResult(c,t,o))):handleArrayResult(u,t,o)}return s.length?Promise.all(s).then(()=>t):t}});function handlePropertyResult(n,e,t,r,i,s){const o=t in r;if(n.issues.length){if(i&&s&&!o)return;e.issues.push(...prefixIssues(t,n.issues))}if(!o&&!i){n.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[t]});return}n.value===void 0?o&&(e.value[t]=void 0):e.value[t]=n.value}function normalizeDef(n){const e=Object.keys(n.shape);for(const r of e)if(!n.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const t=optionalKeys(n.shape);return{...n,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(t)}}function handleCatchall(n,e,t,r,i,s){const o=[],a=i.keySet,u=i.catchall._zod,c=u.def.type,l=u.optin==="optional",d=u.optout==="optional";for(const f in e){if(f==="__proto__"||a.has(f))continue;if(c==="never"){o.push(f);continue}const m=u.run({value:e[f],issues:[]},r);m instanceof Promise?n.push(m.then(g=>handlePropertyResult(g,t,f,e,l,d))):handlePropertyResult(m,t,f,e,l,d)}return o.length&&t.issues.push({code:"unrecognized_keys",keys:o,input:e,inst:s}),n.length?Promise.all(n).then(()=>t):t}const $ZodObject=$constructor("$ZodObject",(n,e)=>{if($ZodType.init(n,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){const a=e.shape;Object.defineProperty(e,"shape",{get:()=>{const u={...a};return Object.defineProperty(e,"shape",{value:u}),u}})}const r=cached(()=>normalizeDef(e));defineLazy(n._zod,"propValues",()=>{const a=e.shape,u={};for(const c in a){const l=a[c]._zod;if(l.values){u[c]??(u[c]=new Set);for(const d of l.values)u[c].add(d)}}return u});const i=isObject$1,s=e.catchall;let o;n._zod.parse=(a,u)=>{o??(o=r.value);const c=a.value;if(!i(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:n}),a;a.value={};const l=[],d=o.shape;for(const f of o.keys){const m=d[f],g=m._zod.optin==="optional",b=m._zod.optout==="optional",S=m._zod.run({value:c[f],issues:[]},u);S instanceof Promise?l.push(S.then(w=>handlePropertyResult(w,a,f,c,g,b))):handlePropertyResult(S,a,f,c,g,b)}return s?handleCatchall(l,c,a,u,r.value,n):l.length?Promise.all(l).then(()=>a):a}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(n,e)=>{$ZodObject.init(n,e);const t=n._zod.parse,r=cached(()=>normalizeDef(e)),i=f=>{const m=new Doc(["shape","payload","ctx"]),g=r.value,b=_=>{const T=esc(_);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};m.write("const input = payload.value;");const S=Object.create(null);let w=0;for(const _ of g.keys)S[_]=`key_${w++}`;m.write("const newResult = {};");for(const _ of g.keys){const T=S[_],C=esc(_),U=f[_],$=U?._zod?.optin==="optional",W=U?._zod?.optout==="optional";m.write(`const ${T} = ${b(_)};`),$&&W?m.write(`
|
|
152
|
+
if (${T}.issues.length) {
|
|
153
|
+
if (${C} in input) {
|
|
154
|
+
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
|
|
155
|
+
...iss,
|
|
156
|
+
path: iss.path ? [${C}, ...iss.path] : [${C}]
|
|
157
|
+
})));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (${T}.value === undefined) {
|
|
162
|
+
if (${C} in input) {
|
|
163
|
+
newResult[${C}] = undefined;
|
|
164
|
+
}
|
|
165
|
+
} else {
|
|
166
|
+
newResult[${C}] = ${T}.value;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
`):$?m.write(`
|
|
170
|
+
if (${T}.issues.length) {
|
|
171
|
+
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
|
|
172
|
+
...iss,
|
|
173
|
+
path: iss.path ? [${C}, ...iss.path] : [${C}]
|
|
174
|
+
})));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (${T}.value === undefined) {
|
|
178
|
+
if (${C} in input) {
|
|
179
|
+
newResult[${C}] = undefined;
|
|
180
|
+
}
|
|
181
|
+
} else {
|
|
182
|
+
newResult[${C}] = ${T}.value;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
`):m.write(`
|
|
186
|
+
const ${T}_present = ${C} in input;
|
|
187
|
+
if (${T}.issues.length) {
|
|
188
|
+
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
|
|
189
|
+
...iss,
|
|
190
|
+
path: iss.path ? [${C}, ...iss.path] : [${C}]
|
|
191
|
+
})));
|
|
192
|
+
}
|
|
193
|
+
if (!${T}_present && !${T}.issues.length) {
|
|
194
|
+
payload.issues.push({
|
|
195
|
+
code: "invalid_type",
|
|
196
|
+
expected: "nonoptional",
|
|
197
|
+
input: undefined,
|
|
198
|
+
path: [${C}]
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (${T}_present) {
|
|
203
|
+
if (${T}.value === undefined) {
|
|
204
|
+
newResult[${C}] = undefined;
|
|
205
|
+
} else {
|
|
206
|
+
newResult[${C}] = ${T}.value;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
`)}m.write("payload.value = newResult;"),m.write("return payload;");const v=m.compile();return(_,T)=>v(f,_,T)};let s;const o=isObject$1,a=!globalConfig.jitless,c=a&&allowsEval.value,l=e.catchall;let d;n._zod.parse=(f,m)=>{d??(d=r.value);const g=f.value;return o(g)?a&&c&&m?.async===!1&&m.jitless!==!0?(s||(s=i(e.shape)),f=s(f,m),l?handleCatchall([],g,f,m,d,n):f):t(f,m):(f.issues.push({expected:"object",code:"invalid_type",input:g,inst:n}),f)}});function handleUnionResults(n,e,t,r){for(const s of n)if(s.issues.length===0)return e.value=s.value,e;const i=n.filter(s=>!aborted(s));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:n.map(s=>s.issues.map(o=>finalizeIssue(o,r,config())))}),e)}const $ZodUnion=$constructor("$ZodUnion",(n,e)=>{$ZodType.init(n,e),defineLazy(n._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),defineLazy(n._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),defineLazy(n._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),defineLazy(n._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>cleanRegex(i.source)).join("|")})$`)}});const t=e.options.length===1?e.options[0]._zod.run:null;n._zod.parse=(r,i)=>{if(t)return t(r,i);let s=!1;const o=[];for(const a of e.options){const u=a._zod.run({value:r.value,issues:[]},i);if(u instanceof Promise)o.push(u),s=!0;else{if(u.issues.length===0)return u;o.push(u)}}return s?Promise.all(o).then(a=>handleUnionResults(a,r,n,i)):handleUnionResults(o,r,n,i)}}),$ZodIntersection=$constructor("$ZodIntersection",(n,e)=>{$ZodType.init(n,e),n._zod.parse=(t,r)=>{const i=t.value,s=e.left._zod.run({value:i,issues:[]},r),o=e.right._zod.run({value:i,issues:[]},r);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([u,c])=>handleIntersectionResults(t,u,c)):handleIntersectionResults(t,s,o)}});function mergeValues$1(n,e){if(n===e)return{valid:!0,data:n};if(n instanceof Date&&e instanceof Date&&+n==+e)return{valid:!0,data:n};if(isPlainObject(n)&&isPlainObject(e)){const t=Object.keys(e),r=Object.keys(n).filter(s=>t.indexOf(s)!==-1),i={...n,...e};for(const s of r){const o=mergeValues$1(n[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(n)&&Array.isArray(e)){if(n.length!==e.length)return{valid:!1,mergeErrorPath:[]};const t=[];for(let r=0;r<n.length;r++){const i=n[r],s=e[r],o=mergeValues$1(i,s);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};t.push(o.data)}return{valid:!0,data:t}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(n,e,t){const r=new Map;let i;for(const a of e.issues)if(a.code==="unrecognized_keys"){i??(i=a);for(const u of a.keys)r.has(u)||r.set(u,{}),r.get(u).l=!0}else n.issues.push(a);for(const a of t.issues)if(a.code==="unrecognized_keys")for(const u of a.keys)r.has(u)||r.set(u,{}),r.get(u).r=!0;else n.issues.push(a);const s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&i&&n.issues.push({...i,keys:s}),aborted(n))return n;const o=mergeValues$1(e.value,t.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return n.value=o.data,n}const $ZodEnum=$constructor("$ZodEnum",(n,e)=>{$ZodType.init(n,e);const t=getEnumValues(e.entries),r=new Set(t);n._zod.values=r,n._zod.pattern=new RegExp(`^(${t.filter(i=>propertyKeyTypes.has(typeof i)).map(i=>typeof i=="string"?escapeRegex(i):i.toString()).join("|")})$`),n._zod.parse=(i,s)=>{const o=i.value;return r.has(o)||i.issues.push({code:"invalid_value",values:t,input:o,inst:n}),i}}),$ZodTransform=$constructor("$ZodTransform",(n,e)=>{$ZodType.init(n,e),n._zod.optin="optional",n._zod.parse=(t,r)=>{if(r.direction==="backward")throw new $ZodEncodeError(n.constructor.name);const i=e.transform(t.value,t);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(t.value=o,t.fallback=!0,t));if(i instanceof Promise)throw new $ZodAsyncError;return t.value=i,t.fallback=!0,t}});function handleOptionalResult(n,e){return e===void 0&&(n.issues.length||n.fallback)?{issues:[],value:void 0}:n}const $ZodOptional=$constructor("$ZodOptional",(n,e)=>{$ZodType.init(n,e),n._zod.optin="optional",n._zod.optout="optional",defineLazy(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),defineLazy(n._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${cleanRegex(t.source)})?$`):void 0}),n._zod.parse=(t,r)=>{if(e.innerType._zod.optin==="optional"){const i=t.value,s=e.innerType._zod.run(t,r);return s instanceof Promise?s.then(o=>handleOptionalResult(o,i)):handleOptionalResult(s,i)}return t.value===void 0?t:e.innerType._zod.run(t,r)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(n,e)=>{$ZodOptional.init(n,e),defineLazy(n._zod,"values",()=>e.innerType._zod.values),defineLazy(n._zod,"pattern",()=>e.innerType._zod.pattern),n._zod.parse=(t,r)=>e.innerType._zod.run(t,r)}),$ZodNullable=$constructor("$ZodNullable",(n,e)=>{$ZodType.init(n,e),defineLazy(n._zod,"optin",()=>e.innerType._zod.optin),defineLazy(n._zod,"optout",()=>e.innerType._zod.optout),defineLazy(n._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${cleanRegex(t.source)}|null)$`):void 0}),defineLazy(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),n._zod.parse=(t,r)=>t.value===null?t:e.innerType._zod.run(t,r)}),$ZodDefault=$constructor("$ZodDefault",(n,e)=>{$ZodType.init(n,e),n._zod.optin="optional",defineLazy(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,r)=>{if(r.direction==="backward")return e.innerType._zod.run(t,r);if(t.value===void 0)return t.value=e.defaultValue,t;const i=e.innerType._zod.run(t,r);return i instanceof Promise?i.then(s=>handleDefaultResult(s,e)):handleDefaultResult(i,e)}});function handleDefaultResult(n,e){return n.value===void 0&&(n.value=e.defaultValue),n}const $ZodPrefault=$constructor("$ZodPrefault",(n,e)=>{$ZodType.init(n,e),n._zod.optin="optional",defineLazy(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,r)=>(r.direction==="backward"||t.value===void 0&&(t.value=e.defaultValue),e.innerType._zod.run(t,r))}),$ZodNonOptional=$constructor("$ZodNonOptional",(n,e)=>{$ZodType.init(n,e),defineLazy(n._zod,"values",()=>{const t=e.innerType._zod.values;return t?new Set([...t].filter(r=>r!==void 0)):void 0}),n._zod.parse=(t,r)=>{const i=e.innerType._zod.run(t,r);return i instanceof Promise?i.then(s=>handleNonOptionalResult(s,n)):handleNonOptionalResult(i,n)}});function handleNonOptionalResult(n,e){return!n.issues.length&&n.value===void 0&&n.issues.push({code:"invalid_type",expected:"nonoptional",input:n.value,inst:e}),n}const $ZodCatch=$constructor("$ZodCatch",(n,e)=>{$ZodType.init(n,e),n._zod.optin="optional",defineLazy(n._zod,"optout",()=>e.innerType._zod.optout),defineLazy(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,r)=>{if(r.direction==="backward")return e.innerType._zod.run(t,r);const i=e.innerType._zod.run(t,r);return i instanceof Promise?i.then(s=>(t.value=s.value,s.issues.length&&(t.value=e.catchValue({...t,error:{issues:s.issues.map(o=>finalizeIssue(o,r,config()))},input:t.value}),t.issues=[],t.fallback=!0),t)):(t.value=i.value,i.issues.length&&(t.value=e.catchValue({...t,error:{issues:i.issues.map(s=>finalizeIssue(s,r,config()))},input:t.value}),t.issues=[],t.fallback=!0),t)}}),$ZodPipe=$constructor("$ZodPipe",(n,e)=>{$ZodType.init(n,e),defineLazy(n._zod,"values",()=>e.in._zod.values),defineLazy(n._zod,"optin",()=>e.in._zod.optin),defineLazy(n._zod,"optout",()=>e.out._zod.optout),defineLazy(n._zod,"propValues",()=>e.in._zod.propValues),n._zod.parse=(t,r)=>{if(r.direction==="backward"){const s=e.out._zod.run(t,r);return s instanceof Promise?s.then(o=>handlePipeResult(o,e.in,r)):handlePipeResult(s,e.in,r)}const i=e.in._zod.run(t,r);return i instanceof Promise?i.then(s=>handlePipeResult(s,e.out,r)):handlePipeResult(i,e.out,r)}});function handlePipeResult(n,e,t){return n.issues.length?(n.aborted=!0,n):e._zod.run({value:n.value,issues:n.issues,fallback:n.fallback},t)}const $ZodReadonly=$constructor("$ZodReadonly",(n,e)=>{$ZodType.init(n,e),defineLazy(n._zod,"propValues",()=>e.innerType._zod.propValues),defineLazy(n._zod,"values",()=>e.innerType._zod.values),defineLazy(n._zod,"optin",()=>e.innerType?._zod?.optin),defineLazy(n._zod,"optout",()=>e.innerType?._zod?.optout),n._zod.parse=(t,r)=>{if(r.direction==="backward")return e.innerType._zod.run(t,r);const i=e.innerType._zod.run(t,r);return i instanceof Promise?i.then(handleReadonlyResult):handleReadonlyResult(i)}});function handleReadonlyResult(n){return n.value=Object.freeze(n.value),n}const $ZodCustom=$constructor("$ZodCustom",(n,e)=>{$ZodCheck.init(n,e),$ZodType.init(n,e),n._zod.parse=(t,r)=>t,n._zod.check=t=>{const r=t.value,i=e.fn(r);if(i instanceof Promise)return i.then(s=>handleRefineResult(s,t,r,n));handleRefineResult(i,t,r,n)}});function handleRefineResult(n,e,t,r){if(!n){const i={code:"custom",input:t,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),e.issues.push(issue(i))}}var _a$1;class $ZodRegistry{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const i={...r,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function registry(){return new $ZodRegistry}(_a$1=globalThis).__zod_globalRegistry??(_a$1.__zod_globalRegistry=registry());const globalRegistry=globalThis.__zod_globalRegistry;function _string(n,e){return new n({type:"string",...normalizeParams(e)})}function _email(n,e){return new n({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(e)})}function _guid(n,e){return new n({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(e)})}function _uuid(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(e)})}function _uuidv4(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(e)})}function _uuidv6(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(e)})}function _uuidv7(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(e)})}function _url(n,e){return new n({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(e)})}function _emoji(n,e){return new n({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(e)})}function _nanoid(n,e){return new n({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(e)})}function _cuid(n,e){return new n({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(e)})}function _cuid2(n,e){return new n({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(e)})}function _ulid(n,e){return new n({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(e)})}function _xid(n,e){return new n({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(e)})}function _ksuid(n,e){return new n({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(e)})}function _ipv4(n,e){return new n({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(e)})}function _ipv6(n,e){return new n({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(e)})}function _cidrv4(n,e){return new n({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(e)})}function _cidrv6(n,e){return new n({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(e)})}function _base64(n,e){return new n({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(e)})}function _base64url(n,e){return new n({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(e)})}function _e164(n,e){return new n({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(e)})}function _jwt(n,e){return new n({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(e)})}function _isoDateTime(n,e){return new n({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(e)})}function _isoDate(n,e){return new n({type:"string",format:"date",check:"string_format",...normalizeParams(e)})}function _isoTime(n,e){return new n({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(e)})}function _isoDuration(n,e){return new n({type:"string",format:"duration",check:"string_format",...normalizeParams(e)})}function _number(n,e){return new n({type:"number",checks:[],...normalizeParams(e)})}function _int(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(e)})}function _boolean(n,e){return new n({type:"boolean",...normalizeParams(e)})}function _any(n){return new n({type:"any"})}function _unknown(n){return new n({type:"unknown"})}function _never(n,e){return new n({type:"never",...normalizeParams(e)})}function _date(n,e){return new n({type:"date",...normalizeParams(e)})}function _lt(n,e){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(e),value:n,inclusive:!1})}function _lte(n,e){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(e),value:n,inclusive:!0})}function _gt(n,e){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(e),value:n,inclusive:!1})}function _gte(n,e){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(e),value:n,inclusive:!0})}function _multipleOf(n,e){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(e),value:n})}function _maxLength(n,e){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(e),maximum:n})}function _minLength(n,e){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(e),minimum:n})}function _length(n,e){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(e),length:n})}function _regex(n,e){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(e),pattern:n})}function _lowercase(n){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(n)})}function _uppercase(n){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(n)})}function _includes(n,e){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(e),includes:n})}function _startsWith(n,e){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(e),prefix:n})}function _endsWith(n,e){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(e),suffix:n})}function _overwrite(n){return new $ZodCheckOverwrite({check:"overwrite",tx:n})}function _normalize(n){return _overwrite(e=>e.normalize(n))}function _trim(){return _overwrite(n=>n.trim())}function _toLowerCase(){return _overwrite(n=>n.toLowerCase())}function _toUpperCase(){return _overwrite(n=>n.toUpperCase())}function _slugify(){return _overwrite(n=>slugify(n))}function _array(n,e,t){return new n({type:"array",element:e,...normalizeParams(t)})}function _refine(n,e,t){return new n({type:"custom",check:"custom",fn:e,...normalizeParams(t)})}function _superRefine(n,e){const t=_check(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(issue(i,r.value,t._zod.def));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),r.issues.push(issue(s))}},n(r.value,r)),e);return t}function _check(n,e){const t=new $ZodCheck({check:"custom",...normalizeParams(e)});return t._zod.check=n,t}function initializeContext(n){let e=n?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:n.processors??{},metadataRegistry:n?.metadata??globalRegistry,target:e,unrepresentable:n?.unrepresentable??"throw",override:n?.override??(()=>{}),io:n?.io??"output",counter:0,seen:new Map,cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0}}function process$1(n,e,t={path:[],schemaPath:[]}){var r;const i=n._zod.def,s=e.seen.get(n);if(s)return s.count++,t.schemaPath.includes(n)&&(s.cycle=t.path),s.schema;const o={schema:{},count:1,cycle:void 0,path:t.path};e.seen.set(n,o);const a=n._zod.toJSONSchema?.();if(a)o.schema=a;else{const l={...t,schemaPath:[...t.schemaPath,n],path:t.path};if(n._zod.processJSONSchema)n._zod.processJSONSchema(e,o.schema,l);else{const f=o.schema,m=e.processors[i.type];if(!m)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);m(n,e,f,l)}const d=n._zod.parent;d&&(o.ref||(o.ref=d),process$1(d,e,l),e.seen.get(d).isParent=!0)}const u=e.metadataRegistry.get(n);return u&&Object.assign(o.schema,u),e.io==="input"&&isTransforming(n)&&(delete o.schema.examples,delete o.schema.default),e.io==="input"&&"_prefault"in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,e.seen.get(n).schema}function extractDefs(n,e){const t=n.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const o of n.seen.entries()){const a=n.metadataRegistry.get(o[0])?.id;if(a){const u=r.get(a);if(u&&u!==o[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,o[0])}}const i=o=>{const a=n.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const d=n.external.registry.get(o[0])?.id,f=n.external.uri??(g=>g);if(d)return{ref:f(d)};const m=o[1].defId??o[1].schema.id??`schema${n.counter++}`;return o[1].defId=m,{defId:m,ref:`${f("__shared")}#/${a}/${m}`}}if(o[1]===t)return{ref:"#"};const c=`#/${a}/`,l=o[1].schema.id??`__schema${n.counter++}`;return{defId:l,ref:c+l}},s=o=>{if(o[1].schema.$ref)return;const a=o[1],{ref:u,defId:c}=i(o);a.def={...a.schema},c&&(a.defId=c);const l=a.schema;for(const d in l)delete l[d];l.$ref=u};if(n.cycles==="throw")for(const o of n.seen.entries()){const a=o[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
211
|
+
|
|
212
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of n.seen.entries()){const a=o[1];if(e===o[0]){s(o);continue}if(n.external){const c=n.external.registry.get(o[0])?.id;if(e!==o[0]&&c){s(o);continue}}if(n.metadataRegistry.get(o[0])?.id){s(o);continue}if(a.cycle){s(o);continue}if(a.count>1&&n.reused==="ref"){s(o);continue}}}function finalize(n,e){const t=n.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=a=>{const u=n.seen.get(a);if(u.ref===null)return;const c=u.def??u.schema,l={...c},d=u.ref;if(u.ref=null,d){r(d);const m=n.seen.get(d),g=m.schema;if(g.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(g)):Object.assign(c,g),Object.assign(c,l),a._zod.parent===d)for(const S in c)S==="$ref"||S==="allOf"||S in l||delete c[S];if(g.$ref&&m.def)for(const S in c)S==="$ref"||S==="allOf"||S in m.def&&JSON.stringify(c[S])===JSON.stringify(m.def[S])&&delete c[S]}const f=a._zod.parent;if(f&&f!==d){r(f);const m=n.seen.get(f);if(m?.schema.$ref&&(c.$ref=m.schema.$ref,m.def))for(const g in c)g==="$ref"||g==="allOf"||g in m.def&&JSON.stringify(c[g])===JSON.stringify(m.def[g])&&delete c[g]}n.override({zodSchema:a,jsonSchema:c,path:u.path??[]})};for(const a of[...n.seen.entries()].reverse())r(a[0]);const i={};if(n.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":n.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":n.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":n.target,n.external?.uri){const a=n.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");i.$id=n.external.uri(a)}Object.assign(i,t.def??t.schema);const s=n.metadataRegistry.get(e)?.id;s!==void 0&&i.id===s&&delete i.id;const o=n.external?.defs??{};for(const a of n.seen.entries()){const u=a[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,o[u.defId]=u.def)}n.external||Object.keys(o).length>0&&(n.target==="draft-2020-12"?i.$defs=o:i.definitions=o);try{const a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(e,"input",n.processors),output:createStandardJSONSchemaMethod(e,"output",n.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(n,e){const t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);const r=n._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return isTransforming(r.element,t);if(r.type==="set")return isTransforming(r.valueType,t);if(r.type==="lazy")return isTransforming(r.getter(),t);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return isTransforming(r.innerType,t);if(r.type==="intersection")return isTransforming(r.left,t)||isTransforming(r.right,t);if(r.type==="record"||r.type==="map")return isTransforming(r.keyType,t)||isTransforming(r.valueType,t);if(r.type==="pipe")return n._zod.traits.has("$ZodCodec")?!0:isTransforming(r.in,t)||isTransforming(r.out,t);if(r.type==="object"){for(const i in r.shape)if(isTransforming(r.shape[i],t))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(isTransforming(i,t))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(isTransforming(i,t))return!0;return!!(r.rest&&isTransforming(r.rest,t))}return!1}const createToJSONSchemaMethod=(n,e={})=>t=>{const r=initializeContext({...t,processors:e});return process$1(n,r),extractDefs(r,n),finalize(r,n)},createStandardJSONSchemaMethod=(n,e,t={})=>r=>{const{libraryOptions:i,target:s}=r??{},o=initializeContext({...i??{},target:s,io:e,processors:t});return process$1(n,o),extractDefs(o,n),finalize(o,n)},formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},stringProcessor=(n,e,t,r)=>{const i=t;i.type="string";const{minimum:s,maximum:o,format:a,patterns:u,contentEncoding:c}=n._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof o=="number"&&(i.maxLength=o),a&&(i.format=formatMap[a]??a,i.format===""&&delete i.format,a==="time"&&delete i.format),c&&(i.contentEncoding=c),u&&u.size>0){const l=[...u];l.length===1?i.pattern=l[0].source:l.length>1&&(i.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},numberProcessor=(n,e,t,r)=>{const i=t,{minimum:s,maximum:o,format:a,multipleOf:u,exclusiveMaximum:c,exclusiveMinimum:l}=n._zod.bag;typeof a=="string"&&a.includes("int")?i.type="integer":i.type="number";const d=typeof l=="number"&&l>=(s??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(o??Number.POSITIVE_INFINITY),m=e.target==="draft-04"||e.target==="openapi-3.0";d?m?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof s=="number"&&(i.minimum=s),f?m?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o=="number"&&(i.maximum=o),typeof u=="number"&&(i.multipleOf=u)},booleanProcessor=(n,e,t,r)=>{t.type="boolean"},neverProcessor=(n,e,t,r)=>{t.not={}},anyProcessor=(n,e,t,r)=>{},unknownProcessor=(n,e,t,r)=>{},dateProcessor=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},enumProcessor=(n,e,t,r)=>{const i=n._zod.def,s=getEnumValues(i.entries);s.every(o=>typeof o=="number")&&(t.type="number"),s.every(o=>typeof o=="string")&&(t.type="string"),t.enum=s},customProcessor=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},transformProcessor=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},arrayProcessor=(n,e,t,r)=>{const i=t,s=n._zod.def,{minimum:o,maximum:a}=n._zod.bag;typeof o=="number"&&(i.minItems=o),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=process$1(s.element,e,{...r,path:[...r.path,"items"]})},objectProcessor=(n,e,t,r)=>{const i=t,s=n._zod.def;i.type="object",i.properties={};const o=s.shape;for(const c in o)i.properties[c]=process$1(o[c],e,{...r,path:[...r.path,"properties",c]});const a=new Set(Object.keys(o)),u=new Set([...a].filter(c=>{const l=s.shape[c]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));u.size>0&&(i.required=Array.from(u)),s.catchall?._zod.def.type==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=process$1(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},unionProcessor=(n,e,t,r)=>{const i=n._zod.def,s=i.inclusive===!1,o=i.options.map((a,u)=>process$1(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",u]}));s?t.oneOf=o:t.anyOf=o},intersectionProcessor=(n,e,t,r)=>{const i=n._zod.def,s=process$1(i.left,e,{...r,path:[...r.path,"allOf",0]}),o=process$1(i.right,e,{...r,path:[...r.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,u=[...a(s)?s.allOf:[s],...a(o)?o.allOf:[o]];t.allOf=u},nullableProcessor=(n,e,t,r)=>{const i=n._zod.def,s=process$1(i.innerType,e,r),o=e.seen.get(n);e.target==="openapi-3.0"?(o.ref=i.innerType,t.nullable=!0):t.anyOf=[s,{type:"null"}]},nonoptionalProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType},defaultProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType,t.default=JSON.parse(JSON.stringify(i.defaultValue))},prefaultProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType,e.io==="input"&&(t._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},catchProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=o},pipeProcessor=(n,e,t,r)=>{const i=n._zod.def,s=i.in._zod.traits.has("$ZodTransform"),o=e.io==="input"?s?i.out:i.in:i.out;process$1(o,e,r);const a=e.seen.get(n);a.ref=o},readonlyProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType,t.readOnly=!0},optionalProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType},ZodISODateTime=$constructor("ZodISODateTime",(n,e)=>{$ZodISODateTime.init(n,e),ZodStringFormat.init(n,e)});function datetime(n){return _isoDateTime(ZodISODateTime,n)}const ZodISODate=$constructor("ZodISODate",(n,e)=>{$ZodISODate.init(n,e),ZodStringFormat.init(n,e)});function date$1(n){return _isoDate(ZodISODate,n)}const ZodISOTime=$constructor("ZodISOTime",(n,e)=>{$ZodISOTime.init(n,e),ZodStringFormat.init(n,e)});function time(n){return _isoTime(ZodISOTime,n)}const ZodISODuration=$constructor("ZodISODuration",(n,e)=>{$ZodISODuration.init(n,e),ZodStringFormat.init(n,e)});function duration(n){return _isoDuration(ZodISODuration,n)}const initializer=(n,e)=>{$ZodError.init(n,e),n.name="ZodError",Object.defineProperties(n,{format:{value:t=>formatError(n,t)},flatten:{value:t=>flattenError(n,t)},addIssue:{value:t=>{n.issues.push(t),n.message=JSON.stringify(n.issues,jsonStringifyReplacer,2)}},addIssues:{value:t=>{n.issues.push(...t),n.message=JSON.stringify(n.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return n.issues.length===0}}})},ZodError$1=$constructor("ZodError",initializer),ZodRealError=$constructor("ZodError",initializer,{Parent:Error}),parse$1=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),encode$2=_encode(ZodRealError),decode$1=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError),_installedGroups=new WeakMap;function _installLazyMethods(n,e,t){const r=Object.getPrototypeOf(n);let i=_installedGroups.get(r);if(i||(i=new Set,_installedGroups.set(r,i)),!i.has(e)){i.add(e);for(const s in t){const o=t[s];Object.defineProperty(r,s,{configurable:!0,enumerable:!1,get(){const a=o.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}const ZodType$1=$constructor("ZodType",(n,e)=>($ZodType.init(n,e),Object.assign(n["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(n,"input"),output:createStandardJSONSchemaMethod(n,"output")}}),n.toJSONSchema=createToJSONSchemaMethod(n,{}),n.def=e,n.type=e.type,Object.defineProperty(n,"_def",{value:e}),n.parse=(t,r)=>parse$1(n,t,r,{callee:n.parse}),n.safeParse=(t,r)=>safeParse(n,t,r),n.parseAsync=async(t,r)=>parseAsync(n,t,r,{callee:n.parseAsync}),n.safeParseAsync=async(t,r)=>safeParseAsync(n,t,r),n.spa=n.safeParseAsync,n.encode=(t,r)=>encode$2(n,t,r),n.decode=(t,r)=>decode$1(n,t,r),n.encodeAsync=async(t,r)=>encodeAsync(n,t,r),n.decodeAsync=async(t,r)=>decodeAsync(n,t,r),n.safeEncode=(t,r)=>safeEncode(n,t,r),n.safeDecode=(t,r)=>safeDecode(n,t,r),n.safeEncodeAsync=async(t,r)=>safeEncodeAsync(n,t,r),n.safeDecodeAsync=async(t,r)=>safeDecodeAsync(n,t,r),_installLazyMethods(n,"ZodType",{check(...t){const r=this.def;return this.clone(mergeDefs(r,{checks:[...r.checks??[],...t.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,r){return clone$1(this,t,r)},brand(){return this},register(t,r){return t.add(this,r),this},refine(t,r){return this.check(refine(t,r))},superRefine(t,r){return this.check(superRefine(t,r))},overwrite(t){return this.check(_overwrite(t))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(t){return nonoptional(this,t)},array(){return array(this)},or(t){return union([this,t])},and(t){return intersection(this,t)},transform(t){return pipe(this,transform(t))},default(t){return _default(this,t)},prefault(t){return prefault(this,t)},catch(t){return _catch(this,t)},pipe(t){return pipe(this,t)},readonly(){return readonly(this)},describe(t){const r=this.clone();return globalRegistry.add(r,{description:t}),r},meta(...t){if(t.length===0)return globalRegistry.get(this);const r=this.clone();return globalRegistry.add(r,t[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t){return t(this)}}),Object.defineProperty(n,"description",{get(){return globalRegistry.get(n)?.description},configurable:!0}),n)),_ZodString=$constructor("_ZodString",(n,e)=>{$ZodString.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(r,i,s)=>stringProcessor(n,r,i);const t=n._zod.bag;n.format=t.format??null,n.minLength=t.minimum??null,n.maxLength=t.maximum??null,_installLazyMethods(n,"_ZodString",{regex(...r){return this.check(_regex(...r))},includes(...r){return this.check(_includes(...r))},startsWith(...r){return this.check(_startsWith(...r))},endsWith(...r){return this.check(_endsWith(...r))},min(...r){return this.check(_minLength(...r))},max(...r){return this.check(_maxLength(...r))},length(...r){return this.check(_length(...r))},nonempty(...r){return this.check(_minLength(1,...r))},lowercase(r){return this.check(_lowercase(r))},uppercase(r){return this.check(_uppercase(r))},trim(){return this.check(_trim())},normalize(...r){return this.check(_normalize(...r))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})}),ZodString$1=$constructor("ZodString",(n,e)=>{$ZodString.init(n,e),_ZodString.init(n,e),n.email=t=>n.check(_email(ZodEmail,t)),n.url=t=>n.check(_url(ZodURL,t)),n.jwt=t=>n.check(_jwt(ZodJWT,t)),n.emoji=t=>n.check(_emoji(ZodEmoji,t)),n.guid=t=>n.check(_guid(ZodGUID,t)),n.uuid=t=>n.check(_uuid(ZodUUID,t)),n.uuidv4=t=>n.check(_uuidv4(ZodUUID,t)),n.uuidv6=t=>n.check(_uuidv6(ZodUUID,t)),n.uuidv7=t=>n.check(_uuidv7(ZodUUID,t)),n.nanoid=t=>n.check(_nanoid(ZodNanoID,t)),n.guid=t=>n.check(_guid(ZodGUID,t)),n.cuid=t=>n.check(_cuid(ZodCUID,t)),n.cuid2=t=>n.check(_cuid2(ZodCUID2,t)),n.ulid=t=>n.check(_ulid(ZodULID,t)),n.base64=t=>n.check(_base64(ZodBase64,t)),n.base64url=t=>n.check(_base64url(ZodBase64URL,t)),n.xid=t=>n.check(_xid(ZodXID,t)),n.ksuid=t=>n.check(_ksuid(ZodKSUID,t)),n.ipv4=t=>n.check(_ipv4(ZodIPv4,t)),n.ipv6=t=>n.check(_ipv6(ZodIPv6,t)),n.cidrv4=t=>n.check(_cidrv4(ZodCIDRv4,t)),n.cidrv6=t=>n.check(_cidrv6(ZodCIDRv6,t)),n.e164=t=>n.check(_e164(ZodE164,t)),n.datetime=t=>n.check(datetime(t)),n.date=t=>n.check(date$1(t)),n.time=t=>n.check(time(t)),n.duration=t=>n.check(duration(t))});function string(n){return _string(ZodString$1,n)}const ZodStringFormat=$constructor("ZodStringFormat",(n,e)=>{$ZodStringFormat.init(n,e),_ZodString.init(n,e)}),ZodEmail=$constructor("ZodEmail",(n,e)=>{$ZodEmail.init(n,e),ZodStringFormat.init(n,e)}),ZodGUID=$constructor("ZodGUID",(n,e)=>{$ZodGUID.init(n,e),ZodStringFormat.init(n,e)}),ZodUUID=$constructor("ZodUUID",(n,e)=>{$ZodUUID.init(n,e),ZodStringFormat.init(n,e)}),ZodURL=$constructor("ZodURL",(n,e)=>{$ZodURL.init(n,e),ZodStringFormat.init(n,e)}),ZodEmoji=$constructor("ZodEmoji",(n,e)=>{$ZodEmoji.init(n,e),ZodStringFormat.init(n,e)}),ZodNanoID=$constructor("ZodNanoID",(n,e)=>{$ZodNanoID.init(n,e),ZodStringFormat.init(n,e)}),ZodCUID=$constructor("ZodCUID",(n,e)=>{$ZodCUID.init(n,e),ZodStringFormat.init(n,e)}),ZodCUID2=$constructor("ZodCUID2",(n,e)=>{$ZodCUID2.init(n,e),ZodStringFormat.init(n,e)}),ZodULID=$constructor("ZodULID",(n,e)=>{$ZodULID.init(n,e),ZodStringFormat.init(n,e)}),ZodXID=$constructor("ZodXID",(n,e)=>{$ZodXID.init(n,e),ZodStringFormat.init(n,e)}),ZodKSUID=$constructor("ZodKSUID",(n,e)=>{$ZodKSUID.init(n,e),ZodStringFormat.init(n,e)}),ZodIPv4=$constructor("ZodIPv4",(n,e)=>{$ZodIPv4.init(n,e),ZodStringFormat.init(n,e)}),ZodIPv6=$constructor("ZodIPv6",(n,e)=>{$ZodIPv6.init(n,e),ZodStringFormat.init(n,e)}),ZodCIDRv4=$constructor("ZodCIDRv4",(n,e)=>{$ZodCIDRv4.init(n,e),ZodStringFormat.init(n,e)}),ZodCIDRv6=$constructor("ZodCIDRv6",(n,e)=>{$ZodCIDRv6.init(n,e),ZodStringFormat.init(n,e)}),ZodBase64=$constructor("ZodBase64",(n,e)=>{$ZodBase64.init(n,e),ZodStringFormat.init(n,e)}),ZodBase64URL=$constructor("ZodBase64URL",(n,e)=>{$ZodBase64URL.init(n,e),ZodStringFormat.init(n,e)}),ZodE164=$constructor("ZodE164",(n,e)=>{$ZodE164.init(n,e),ZodStringFormat.init(n,e)}),ZodJWT=$constructor("ZodJWT",(n,e)=>{$ZodJWT.init(n,e),ZodStringFormat.init(n,e)}),ZodNumber$1=$constructor("ZodNumber",(n,e)=>{$ZodNumber.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(r,i,s)=>numberProcessor(n,r,i),_installLazyMethods(n,"ZodNumber",{gt(r,i){return this.check(_gt(r,i))},gte(r,i){return this.check(_gte(r,i))},min(r,i){return this.check(_gte(r,i))},lt(r,i){return this.check(_lt(r,i))},lte(r,i){return this.check(_lte(r,i))},max(r,i){return this.check(_lte(r,i))},int(r){return this.check(int(r))},safe(r){return this.check(int(r))},positive(r){return this.check(_gt(0,r))},nonnegative(r){return this.check(_gte(0,r))},negative(r){return this.check(_lt(0,r))},nonpositive(r){return this.check(_lte(0,r))},multipleOf(r,i){return this.check(_multipleOf(r,i))},step(r,i){return this.check(_multipleOf(r,i))},finite(){return this}});const t=n._zod.bag;n.minValue=Math.max(t.minimum??Number.NEGATIVE_INFINITY,t.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,n.maxValue=Math.min(t.maximum??Number.POSITIVE_INFINITY,t.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,n.isInt=(t.format??"").includes("int")||Number.isSafeInteger(t.multipleOf??.5),n.isFinite=!0,n.format=t.format??null});function number(n){return _number(ZodNumber$1,n)}const ZodNumberFormat=$constructor("ZodNumberFormat",(n,e)=>{$ZodNumberFormat.init(n,e),ZodNumber$1.init(n,e)});function int(n){return _int(ZodNumberFormat,n)}const ZodBoolean$1=$constructor("ZodBoolean",(n,e)=>{$ZodBoolean.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>booleanProcessor(n,t,r)});function boolean(n){return _boolean(ZodBoolean$1,n)}const ZodAny$1=$constructor("ZodAny",(n,e)=>{$ZodAny.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>anyProcessor()});function any(){return _any(ZodAny$1)}const ZodUnknown$1=$constructor("ZodUnknown",(n,e)=>{$ZodUnknown.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>unknownProcessor()});function unknown(){return _unknown(ZodUnknown$1)}const ZodNever$1=$constructor("ZodNever",(n,e)=>{$ZodNever.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>neverProcessor(n,t,r)});function never(n){return _never(ZodNever$1,n)}const ZodDate$1=$constructor("ZodDate",(n,e)=>{$ZodDate.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(r,i,s)=>dateProcessor(n,r),n.min=(r,i)=>n.check(_gte(r,i)),n.max=(r,i)=>n.check(_lte(r,i));const t=n._zod.bag;n.minDate=t.minimum?new Date(t.minimum):null,n.maxDate=t.maximum?new Date(t.maximum):null});function date(n){return _date(ZodDate$1,n)}const ZodArray$1=$constructor("ZodArray",(n,e)=>{$ZodArray.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>arrayProcessor(n,t,r,i),n.element=e.element,_installLazyMethods(n,"ZodArray",{min(t,r){return this.check(_minLength(t,r))},nonempty(t){return this.check(_minLength(1,t))},max(t,r){return this.check(_maxLength(t,r))},length(t,r){return this.check(_length(t,r))},unwrap(){return this.element}})});function array(n,e){return _array(ZodArray$1,n,e)}const ZodObject$1=$constructor("ZodObject",(n,e)=>{$ZodObjectJIT.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>objectProcessor(n,t,r,i),defineLazy(n,"shape",()=>e.shape),_installLazyMethods(n,"ZodObject",{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(t){return this.clone({...this._zod.def,catchall:t})},passthrough(){return this.clone({...this._zod.def,catchall:unknown()})},loose(){return this.clone({...this._zod.def,catchall:unknown()})},strict(){return this.clone({...this._zod.def,catchall:never()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(t){return extend(this,t)},safeExtend(t){return safeExtend(this,t)},merge(t){return merge(this,t)},pick(t){return pick(this,t)},omit(t){return omit(this,t)},partial(...t){return partial(ZodOptional$1,this,t[0])},required(...t){return required(ZodNonOptional,this,t[0])}})});function object(n,e){const t={type:"object",shape:n??{},...normalizeParams(e)};return new ZodObject$1(t)}const ZodUnion$1=$constructor("ZodUnion",(n,e)=>{$ZodUnion.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>unionProcessor(n,t,r,i),n.options=e.options});function union(n,e){return new ZodUnion$1({type:"union",options:n,...normalizeParams(e)})}const ZodIntersection$1=$constructor("ZodIntersection",(n,e)=>{$ZodIntersection.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>intersectionProcessor(n,t,r,i)});function intersection(n,e){return new ZodIntersection$1({type:"intersection",left:n,right:e})}const ZodEnum$1=$constructor("ZodEnum",(n,e)=>{$ZodEnum.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(r,i,s)=>enumProcessor(n,r,i),n.enum=e.entries,n.options=Object.values(e.entries);const t=new Set(Object.keys(e.entries));n.extract=(r,i)=>{const s={};for(const o of r)if(t.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new ZodEnum$1({...e,checks:[],...normalizeParams(i),entries:s})},n.exclude=(r,i)=>{const s={...e.entries};for(const o of r)if(t.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new ZodEnum$1({...e,checks:[],...normalizeParams(i),entries:s})}});function _enum(n,e){const t=Array.isArray(n)?Object.fromEntries(n.map(r=>[r,r])):n;return new ZodEnum$1({type:"enum",entries:t,...normalizeParams(e)})}const ZodTransform=$constructor("ZodTransform",(n,e)=>{$ZodTransform.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>transformProcessor(n,t),n._zod.parse=(t,r)=>{if(r.direction==="backward")throw new $ZodEncodeError(n.constructor.name);t.addIssue=s=>{if(typeof s=="string")t.issues.push(issue(s,t.value,e));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=t.value),o.inst??(o.inst=n),t.issues.push(issue(o))}};const i=e.transform(t.value,t);return i instanceof Promise?i.then(s=>(t.value=s,t.fallback=!0,t)):(t.value=i,t.fallback=!0,t)}});function transform(n){return new ZodTransform({type:"transform",transform:n})}const ZodOptional$1=$constructor("ZodOptional",(n,e)=>{$ZodOptional.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>optionalProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function optional(n){return new ZodOptional$1({type:"optional",innerType:n})}const ZodExactOptional=$constructor("ZodExactOptional",(n,e)=>{$ZodExactOptional.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>optionalProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function exactOptional(n){return new ZodExactOptional({type:"optional",innerType:n})}const ZodNullable$1=$constructor("ZodNullable",(n,e)=>{$ZodNullable.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>nullableProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function nullable(n){return new ZodNullable$1({type:"nullable",innerType:n})}const ZodDefault$1=$constructor("ZodDefault",(n,e)=>{$ZodDefault.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>defaultProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType,n.removeDefault=n.unwrap});function _default(n,e){return new ZodDefault$1({type:"default",innerType:n,get defaultValue(){return typeof e=="function"?e():shallowClone(e)}})}const ZodPrefault=$constructor("ZodPrefault",(n,e)=>{$ZodPrefault.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>prefaultProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function prefault(n,e){return new ZodPrefault({type:"prefault",innerType:n,get defaultValue(){return typeof e=="function"?e():shallowClone(e)}})}const ZodNonOptional=$constructor("ZodNonOptional",(n,e)=>{$ZodNonOptional.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>nonoptionalProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function nonoptional(n,e){return new ZodNonOptional({type:"nonoptional",innerType:n,...normalizeParams(e)})}const ZodCatch$1=$constructor("ZodCatch",(n,e)=>{$ZodCatch.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>catchProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType,n.removeCatch=n.unwrap});function _catch(n,e){return new ZodCatch$1({type:"catch",innerType:n,catchValue:typeof e=="function"?e:()=>e})}const ZodPipe=$constructor("ZodPipe",(n,e)=>{$ZodPipe.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>pipeProcessor(n,t,r,i),n.in=e.in,n.out=e.out});function pipe(n,e){return new ZodPipe({type:"pipe",in:n,out:e})}const ZodReadonly$1=$constructor("ZodReadonly",(n,e)=>{$ZodReadonly.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>readonlyProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function readonly(n){return new ZodReadonly$1({type:"readonly",innerType:n})}const ZodCustom=$constructor("ZodCustom",(n,e)=>{$ZodCustom.init(n,e),ZodType$1.init(n,e),n._zod.processJSONSchema=(t,r,i)=>customProcessor(n,t)});function refine(n,e={}){return _refine(ZodCustom,n,e)}function superRefine(n,e){return _superRefine(n,e)}async function parseSHACL(n,e){const t=new N3Store$1,r=new N3Parser$1({baseIRI:e});return new Promise((i,s)=>{const o=[];r.parse(n,(a,u,c)=>{if(a){s(a);return}if(u)o.push(u);else{t.addQuads(o);try{const l=extractShapes(t);i(l)}catch(l){s(l)}}})})}function extractShapes(n){const e=[],t=n.getQuads(null,new NamedNode$2("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),new NamedNode$2(SHACL.NODE_SHAPE),null);for(const r of t){const i=r.subject;if(i.termType==="NamedNode"||i.termType==="BlankNode"){const s=extractShape(n,i);s&&e.push(s)}}return e}function extractShape(n,e){const t=n.getQuads(e,new NamedNode$2(SHACL.TARGET_CLASS),null,null);if(t.length===0)return null;const r=t[0].object.value,i=n.getQuads(e,new NamedNode$2(SHACL.NAME),null,null),s=i.length>0?i[0].object.value:void 0,o=n.getQuads(e,new NamedNode$2(SHACL.DESCRIPTION),null,null),a=o.length>0?o[0].object.value:void 0,u=n.getQuads(e,new NamedNode$2(SHACL.PROPERTY),null,null),c=[];for(const l of u){const d=l.object,f=extractProperty(n,d);f&&c.push(f)}return{uri:e.value,targetClass:r,name:s,description:a,properties:c}}function extractProperty(n,e){const t=n.getQuads(e,new NamedNode$2(SHACL.PATH),null,null);if(t.length===0)return null;let r,i=!1;const s=t[0].object;if(s.termType==="BlankNode"){const T=n.getQuads(s,new NamedNode$2(SHACL.INVERSE_PATH),null,null);if(T.length>0)r=T[0].object.value,i=!0;else return null}else r=s.value;const o=n.getQuads(e,new NamedNode$2(SHACL.NAME),null,null),a=o.length>0?o[0].object.value:extractNameFromPath(r),u=n.getQuads(e,new NamedNode$2(SHACL.DATATYPE),null,null),c=u.length>0?u[0].object.value:void 0,l=n.getQuads(e,new NamedNode$2(SHACL.NODE_KIND),null,null),d=l.length>0?l[0].object.value:void 0,f=n.getQuads(e,new NamedNode$2(SHACL.MIN_COUNT),null,null),m=f.length>0?parseInt(f[0].object.value,10):void 0,g=n.getQuads(e,new NamedNode$2(SHACL.MAX_COUNT),null,null),b=g.length>0?parseInt(g[0].object.value,10):void 0,S=n.getQuads(e,new NamedNode$2(SHACL.PATTERN),null,null),w=S.length>0?S[0].object.value:void 0,v=n.getQuads(e,new NamedNode$2(SHACL.CLASS),null,null),_=v.length>0?v[0].object.value:void 0;return{path:r,name:a,datatype:c,nodeKind:d,minCount:m,maxCount:b,pattern:w,class:_,inverse:i}}function extractNameFromPath(n){const e=n.lastIndexOf("#");if(e>=0)return n.substring(e+1);const t=n.lastIndexOf("/");return t>=0?n.substring(t+1):n}function xsdToDrizzleType(n){if(!n)return"string";switch(n){case XSD.STRING:return"string";case XSD.INTEGER:return"integer";case XSD.BOOLEAN:return"boolean";case XSD.DATETIME:case XSD.DATE:return"datetime";case XSD.DECIMAL:case XSD.DOUBLE:return"number";case XSD.ANYURI:return"uri";default:return"string"}}function nodeKindToDrizzleType(n){if(n)switch(n){case SHACL.IRI:return"uri";case SHACL.LITERAL:return"string";case SHACL.BLANK_NODE:return"object";default:return}}class DrizzleShapeManager{constructor(e,t){this.podUrl=e.endsWith("/")?e:`${e}/`,this.authenticatedFetch=t??globalThis.fetch}generateShape(e){const t=typeof e.config.type=="string"?e.config.type:e.config.type.value;let i=e.getResourcePath?.()||e.getContainerPath();i&&!i.startsWith("http")&&(i=`${this.podUrl}${i.replace(/^\//,"")}`),i||(i=this.podUrl);const a=`${i.endsWith("/")?`${i}shapes/`:`${i.substring(0,i.lastIndexOf("/")+1)}shapes/`}${e.config.name}Shape.ttl#${e.config.name}Shape`,u=[];return Object.entries(e.columns).forEach(([c,l])=>{if(c==="id")return;const d=getPredicateForColumn(l,e);if(!d||d.includes("example.org/unknown"))return;const f={path:d,name:l.name,minCount:l.options?.required?1:void 0,maxCount:l.dataType==="array"||l.options?.isArray?void 0:1};if(l.options?.inverse&&(f.inverse=!0),l.dataType==="uri"||l.options?.linkTarget)f.datatype=l.dataType==="uri"?XSD.ANYURI:void 0,f.nodeKind=SHACL.IRI,f.class=l.options?.linkTarget;else switch(l.dataType){case"string":f.datatype=XSD.STRING,f.nodeKind=SHACL.LITERAL;break;case"integer":f.datatype=XSD.INTEGER,f.nodeKind=SHACL.LITERAL;break;case"boolean":f.datatype=XSD.BOOLEAN,f.nodeKind=SHACL.LITERAL;break;case"datetime":f.datatype=XSD.DATETIME,f.nodeKind=SHACL.LITERAL;break;case"object":case"json":f.nodeKind=SHACL.BLANK_NODE;break;case"array":f.minCount=l.options?.required?1:0;break}u.push(f)}),{uri:a,name:`${e.config.name} Shape`,description:`SHACL Shape for the ${e.config.name} PodTable.`,targetClass:t,properties:u.filter(c=>c.path!==SHACL.PATH)}}toSHACL(e){const t=[`@prefix sh: <${SHACL.NS}> .`,`@prefix xsd: <${XSD.ANYURI.slice(0,XSD.ANYURI.lastIndexOf("#")+1)}> .`,"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .","@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .","@prefix schema: <https://schema.org/> .","@prefix foaf: <http://xmlns.com/foaf/0.1/> .","@prefix dc: <http://purl.org/dc/terms/> .",`@prefix : <${e.uri.slice(0,e.uri.indexOf("#")+1)}>`,"",`:${e.name?.replace(/\s/g,"")} a sh:NodeShape ;`,` sh:targetClass <${e.targetClass}> ;`," sh:closed false ;"];return e.name&&t.push(` sh:name "${e.name}" ;`),e.description&&(t.push(` sh:description "${e.description}" ;`),t.push(` rdfs:comment """${e.description}""" ;`)),e.properties.forEach(r=>{t.push(" sh:property ["),t.push(` sh:path ${r.inverse?`[ sh:inversePath <${r.path}> ]`:`<${r.path}>`} ;`),r.name&&t.push(` sh:name "${r.name}" ;`),r.datatype&&t.push(` sh:datatype <${r.datatype}> ;`),r.nodeKind&&t.push(` sh:nodeKind <${r.nodeKind}> ;`),typeof r.minCount=="number"&&t.push(` sh:minCount ${r.minCount} ;`),typeof r.maxCount=="number"&&t.push(` sh:maxCount ${r.maxCount} ;`),r.pattern&&t.push(` sh:pattern "${r.pattern}" ;`),r.class&&t.push(` sh:class <${r.class}> ;`),t[t.length-1]=t[t.length-1].replace(/\s;$/,""),t.push(" ] ;")}),t[t.length-1]=t[t.length-1].replace(/\s;$/," ."),t.join(`
|
|
213
|
+
`)}async saveShape(e,t,r){const i=r??this.authenticatedFetch,s=this.toSHACL(e),o=await i(t,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:s});if(!o.ok){const a=await o.text().catch(()=>"");throw new Error(`Failed to save shape to ${t}: ${o.status} ${o.statusText}${a?` - ${a}`:""}`)}}async loadShape(e,t){const r=t??this.authenticatedFetch;try{const i=await r(e,{headers:{Accept:"text/turtle, application/ld+json"}});if(!i.ok)return console.warn(`[ShapeManager] Failed to fetch Shape from ${e}: ${i.status}`),null;const s=await i.text(),o=await parseSHACL(s,e);return o.length===0?(console.warn(`[ShapeManager] No shapes found in ${e}`),null):o.find(u=>u.uri===e||e.includes(u.uri))||o[0]}catch(i){return console.error(`[ShapeManager] Error loading Shape from ${e}:`,i),null}}shapeToTable(e,t){const r=this.extractTableName(e),i={id:string$2("id").primaryKey()};for(const o of e.properties){const a=o.name||this.extractNameFromPath(o.path),u=this.propertyToColumn(o,a);u&&(i[a]=u)}const s=podTable(r,i,{type:e.targetClass,base:t});return{name:r,table:s,shape:e}}extractTableName(e){return e.name?e.name.replace(/\s+/g,"_").replace(/Shape$/i,"").toLowerCase():this.extractNameFromPath(e.targetClass).toLowerCase()}extractNameFromPath(e){const t=e.lastIndexOf("#");if(t>=0)return e.substring(t+1);const r=e.lastIndexOf("/");return r>=0?e.substring(r+1):e}propertyToColumn(e,t){let r="string";if(e.nodeKind){const a=nodeKindToDrizzleType(e.nodeKind);a&&(r=a)}e.datatype&&(r=xsdToDrizzleType(e.datatype)),e.class&&(r="uri");const i=e.maxCount===void 0||e.maxCount>1,s=e.minCount!==void 0&&e.minCount>0;let o;switch(r){case"string":o=string$2(t).predicate(e.path);break;case"integer":o=integer$1(t).predicate(e.path);break;case"boolean":o=boolean$2(t).predicate(e.path);break;case"datetime":o=date$3(t).predicate(e.path);break;case"uri":o=uri(t).predicate(e.path),e.class&&(o=o.link(e.class));break;case"object":o=object$1(t).predicate(e.path);break;default:o=string$2(t).predicate(e.path)}return s&&(o=o.notNull()),i&&(o=o.array()),e.inverse&&(o=o.inverse()),o}validate(e,t){try{return this.shapeToZod(t).parse(e),{valid:!0}}catch(r){const i=r instanceof ZodError$1?r.issues:r&&Array.isArray(r.errors)?r.errors:void 0;return i?{valid:!1,errors:i.map(s=>({path:s.path?String(s.path[0]):"",message:s.message,constraint:s.code||"unknown",value:void 0}))}:{valid:!1,errors:[{path:"",message:String(r)}]}}}shapeToZod(e){const t={};return e.properties.forEach(r=>{if(!r.name)return;let i=any();if(r.nodeKind===SHACL.IRI)i=string().url().or(string().startsWith("http"));else if(r.datatype)switch(r.datatype){case XSD.STRING:i=string(),r.pattern&&(i=i.regex(new RegExp(r.pattern)));break;case XSD.INTEGER:i=number().int().or(string().regex(/^\d+$/));break;case XSD.DECIMAL:case XSD.DOUBLE:i=number().or(string().regex(/^-?\d*\.?\d+$/));break;case XSD.BOOLEAN:i=boolean().or(string().regex(/^(true|false|1|0)$/i));break;case XSD.DATETIME:case XSD.DATE:i=date().or(string().datetime({offset:!0}));break;case XSD.ANYURI:i=string();break}const s=r.maxCount!==1,o=r.minCount!==void 0&&r.minCount>0;s?(i=array(i),o?i=i.min(r.minCount):i=i.optional()):o||(i=i.optional()),t[r.name]=i}),object(t)}}const CACHE_TTL=300*1e3;class TypeIndexManager{constructor(e,t,r=globalThis.fetch){this.typeIndexCache=null,this.cachedTypeIndexUrl=null,this.webId=e,this.podUrl=t,this.fetchFn=r}getConfig(){return{webId:this.webId,podUrl:this.podUrl,fetch:this.fetchFn,autoCreate:!0}}updateConfig(e){this.webId=e.webId,this.podUrl=e.podUrl,e.fetch&&(this.fetchFn=e.fetch),this.clearCache()}clearCache(){this.typeIndexCache=null}async findTypeIndex(){if(this.typeIndexCache&&Date.now()-this.typeIndexCache.timestamp<CACHE_TTL)return this.typeIndexCache.url;try{let e,t;try{if(console.log("Fetching WebID profile document..."),e=await getSolidDataset(this.webId,{fetch:this.fetchFn}),e||(console.warn("WebID document is empty, attempting to refetch..."),e=await getSolidDataset(this.webId,{fetch:this.fetchFn})),e)if(t=getThing(e,this.webId),t)console.log("Successfully loaded profile from WebID document");else{console.warn("Profile thing not found in dataset, trying alternative approaches...");const i=getThingAll(e);i.length>0&&(t=i[0],console.log("Using first thing from dataset as profile"))}}catch(i){console.warn("Could not fetch WebID document:",i)}if(t){const i=this.extractStorages(t);this.podUrl=resolvePodBase({webId:this.webId,podUrl:this.podUrl,storages:i});const s=getUrl(t,"http://www.w3.org/ns/solid/terms#privateTypeIndex");if(s){const c=Array.isArray(s)?s[0]:s;return console.log(`Found Private TypeIndex in profile: ${c}`),this.cachedTypeIndexUrl=c,c}const o=getUrl(t,"http://www.w3.org/ns/solid/terms#publicTypeIndex");if(o){const c=Array.isArray(o)?o[0]:o;return console.log(`Found Public TypeIndex in profile: ${c}`),this.cachedTypeIndexUrl=c,c}const a=getUrl(t,"http://www.w3.org/ns/solid/terms#typeIndex");if(a){const c=Array.isArray(a)?a[0]:a;return console.log(`Found legacy TypeIndex in profile: ${c}`),this.cachedTypeIndexUrl=c,c}const u=getUrl(t,"http://www.w3.org/ns/pim/space#storage");if(u){const c=Array.isArray(u)?u[0]:u;try{const l=await getSolidDataset(c,{fetch:this.fetchFn}),d=getThing(l,c);if(d){const f=getUrl(d,"http://www.w3.org/ns/solid/terms#privateTypeIndex");if(f){const g=Array.isArray(f)?f[0]:f;return console.log(`Found Private TypeIndex in storage: ${g}`),this.cachedTypeIndexUrl=g,g}const m=getUrl(d,"http://www.w3.org/ns/solid/terms#publicTypeIndex");if(m){const g=Array.isArray(m)?m[0]:m;return console.log(`Found Public TypeIndex in storage: ${g}`),this.cachedTypeIndexUrl=g,g}}}catch(l){console.log("Could not access storage directory:",l)}}}else console.warn("Could not find profile in WebID document, trying fallback methods");const r=[this.joinWithPodBase("settings/privateTypeIndex.ttl"),this.joinWithPodBase("settings/publicTypeIndex.ttl"),this.joinWithPodBase("settings/typeIndex.ttl")];for(const i of r)try{return await getSolidDataset(i,{fetch:this.fetchFn}),console.log(`Found TypeIndex at standard location: ${i}`),this.cachedTypeIndexUrl=i,i}catch{}return console.log("No TypeIndex found"),null}catch(e){return console.error("Error finding TypeIndex:",e),null}}async createTypeIndex(e=!1){return e?this.createPublicTypeIndex():this.createPrivateTypeIndex()}async createPrivateTypeIndex(){const e=this.joinWithPodBase("settings/privateTypeIndex.ttl");try{const t=buildThing(createThing({url:e})).addUrl("http://www.w3.org/1999/02/22-rdf-syntax-ns#type","http://www.w3.org/ns/solid/terms#TypeIndex").addStringNoLocale("http://xmlns.com/foaf/0.1/name","Private Type Index").addStringNoLocale("http://purl.org/dc/terms/description","Private type index for this Pod").build(),r=setThing(createSolidDataset(),t);return await saveSolidDatasetAt(e,r,{fetch:this.fetchFn}),await this.linkTypeIndexToProfile(e,!1),console.log(`Private TypeIndex created and linked to profile: ${e}`),e}catch(t){throw console.error("Error creating private TypeIndex:",t),t}}async createPublicTypeIndex(){const e=this.joinWithPodBase("settings/publicTypeIndex.ttl");try{const t=buildThing(createThing({url:e})).addUrl("http://www.w3.org/1999/02/22-rdf-syntax-ns#type","http://www.w3.org/ns/solid/terms#TypeIndex").addStringNoLocale("http://xmlns.com/foaf/0.1/name","Public Type Index").addStringNoLocale("http://purl.org/dc/terms/description","Public type index for this Pod").build(),r=setThing(createSolidDataset(),t);return await saveSolidDatasetAt(e,r,{fetch:this.fetchFn}),await this.linkTypeIndexToProfile(e,!0),console.log(`Public TypeIndex created and linked to profile: ${e}`),e}catch(t){throw console.error("Error creating public TypeIndex:",t),t}}async linkTypeIndexToProfile(e,t){try{const r=await getSolidDataset(this.webId,{fetch:this.fetchFn}),i=getThing(r,this.webId);if(!i)throw new Error("Could not find profile in WebID document");const s=t?"http://www.w3.org/ns/solid/terms#publicTypeIndex":"http://www.w3.org/ns/solid/terms#privateTypeIndex",o=buildThing(i).addUrl(s,e).build(),a=setThing(r,o);await saveSolidDatasetAt(this.webId,a,{fetch:this.fetchFn}),console.log(`${t?"public":"private"} TypeIndex linked to profile: ${e}`)}catch(r){throw console.error("Error linking TypeIndex to profile:",r),r}}async registerType(e,t){let r=t;if(!r){const i=await this.findTypeIndexByVisibility(e.visibility==="public");if(!i)throw new Error("TypeIndex not found. Please create one first.");r=i}try{let i;try{i=await getSolidDataset(r,{fetch:this.fetchFn})}catch{i=createSolidDataset()}const s=e.instanceContainer||`${this.podUrl}${e.containerPath}`,o=`#${e.forClass.toLowerCase()}`,a=buildThing(createThing({url:`${r}${o}`})).addUrl("http://www.w3.org/1999/02/22-rdf-syntax-ns#type","http://www.w3.org/ns/solid/terms#TypeRegistration").addUrl("http://www.w3.org/ns/solid/terms#forClass",e.rdfClass).addUrl("http://www.w3.org/ns/solid/terms#instanceContainer",s).addStringNoLocale("http://xmlns.com/foaf/0.1/name",e.forClass).build();i=setThing(i,a),await saveSolidDatasetAt(r,i,{fetch:this.fetchFn});const u=e.visibility==="public"?"public":"private";console.log(`Type ${e.forClass} registered to ${u} TypeIndex: ${r}`)}catch(i){throw console.error("Error registering type:",i),i}}async findTypeIndexByVisibility(e){try{let t,r;try{console.log("Fetching WebID profile document for TypeIndex visibility check..."),t=await getSolidDataset(this.webId,{fetch:this.fetchFn}),t&&(r=getThing(t,this.webId))}catch(s){console.warn("Could not fetch WebID document for visibility check:",s)}if(r){const o=getUrl(r,e?"http://www.w3.org/ns/solid/terms#publicTypeIndex":"http://www.w3.org/ns/solid/terms#privateTypeIndex");if(o){const a=Array.isArray(o)?o[0]:o;return console.log(`Found ${e?"public":"private"} TypeIndex in profile: ${a}`),a}}const i=e?this.joinWithPodBase("settings/publicTypeIndex.ttl"):this.joinWithPodBase("settings/privateTypeIndex.ttl");try{return await getSolidDataset(i,{fetch:this.fetchFn}),console.log(`Found ${e?"public":"private"} TypeIndex at standard location: ${i}`),i}catch{return console.log(`No ${e?"public":"private"} TypeIndex found`),null}}catch(t){return console.error(`Error finding ${e?"public":"private"} TypeIndex:`,t),null}}joinWithPodBase(e){try{const t=this.getUserBaseUrl();return new URL(e,t).toString()}catch{return`${this.getUserBaseUrl()}${e}`.replace(/\/+$/,"")}}getUserBaseUrl(e){return resolvePodBase({webId:this.webId,podUrl:this.podUrl,storages:e})}extractStorages(e){try{return e?[...getUrlAll(e,"http://www.w3.org/ns/solid/terms#storage")||[],...getUrlAll(e,"http://www.w3.org/ns/pim/space#storage")||[]].filter(Boolean):[]}catch{return[]}}async discoverTypes(e){const t=e||await this.findTypeIndex();if(!t)return[];try{const r=await getSolidDataset(t,{fetch:this.fetchFn}),i=[],s=getThingAll(r);console.log(`[TypeIndex] Discovery on ${t} found ${s.length} things.`);for(const o of s)if(getUrl(o,"http://www.w3.org/1999/02/22-rdf-syntax-ns#type")==="http://www.w3.org/ns/solid/terms#TypeRegistration"){const u=getUrl(o,"http://www.w3.org/ns/solid/terms#forClass"),c=getUrl(o,"http://www.w3.org/ns/solid/terms#instanceContainer"),l=getStringNoLocale(o,"http://xmlns.com/foaf/0.1/name");if(u&&c){let d=c.replace(this.podUrl,"");d.endsWith("/")||(d+="/"),i.push({rdfClass:u,containerPath:d,forClass:l||this.deriveNameFromRdfClass(u),instanceContainer:c})}}return i}catch(r){return console.error("Error discovering types:",r),[]}}deriveNameFromRdfClass(e){try{const t=new URL(e);return t.hash?t.hash.slice(1):t.pathname.split("/").pop()||"Unknown"}catch{return"Unknown"}}async discoverSpecificType(e){try{const t=await this.findTypeIndex();if(t){const o=(await this.discoverTypes(t)).find(a=>a.rdfClass===e);if(o)return o}const i=(await this.discoverTypesFromProfile()).find(s=>s.rdfClass===e);return i||null}catch(t){return console.error(`Error discovering specific type ${e}:`,t),null}}async discoverSpecificTypes(e){const t=[];for(const r of e){const i=await this.discoverSpecificType(r);i&&t.push(i)}return t}async discoverTable(e){const t=await this.discoverSpecificType(e);if(!t)return null;const r=t.containerPath,i=this.inferColumnsFromRdfClass(e);return{name:t.forClass.toLowerCase(),columns:i,config:{containerPath:r,rdfClass:t.rdfClass}}}async discoverTables(e){const t=[];for(const r of e){const i=await this.discoverTable(r);i&&t.push(i)}return t}inferColumnsFromRdfClass(e){const t={id:{type:"int",primaryKey:!0}};return e.includes("schema.org/Person")?{...t,name:{type:"string",required:!0},email:{type:"string",required:!1}}:e.includes("schema.org/BlogPosting")?{...t,title:{type:"string",required:!0},content:{type:"string",required:!1},author:{type:"string",required:!1}}:e.includes("schema.org/Comment")?{...t,text:{type:"string",required:!0},author:{type:"string",required:!1}}:{...t,name:{type:"string",required:!0}}}async autoDiscoverAndRegister(e){const t=this.webId,r=e??this.webId;e&&e!==this.webId&&(this.webId=e);try{const i=await this.findTypeIndex();if(!i)return console.log("No TypeIndex found for user"),[];const s=await this.discoverTypes(i);return console.log(`Discovered ${s.length} types from TypeIndex for ${r}`),s}catch(i){return console.error("Error in auto discovery:",i),[]}finally{e&&e!==t&&(this.webId=t)}}async isTypeRegistered(e,t){return(await this.discoverTypes(t)).some(i=>i.rdfClass===e)}async discoverTypesFromProfile(){try{const e=await getSolidDataset(this.webId,{fetch:this.fetchFn}),t=getThing(e,this.webId);if(!t)throw new Error("Could not find profile in WebID document");const r=getUrl(t,"http://www.w3.org/ns/pim/space#storage"),i=[];if(r){const s=Array.isArray(r)?r[0]:r,o=await getSolidDataset(s,{fetch:this.fetchFn}),a=getThing(o,s);if(a){const u=getUrl(a,"http://www.w3.org/ns/ldp#contains");if(u){const c=Array.isArray(u)?u:[u];for(const l of c)try{const d=await getSolidDataset(l,{fetch:this.fetchFn}),f=getThing(d,l);if(f){const m=getStringNoLocale(f,"http://xmlns.com/foaf/0.1/name");if(m){const g=this.inferRdfClassFromContainerName(m);let b=l.replace(this.podUrl,"");b.endsWith("/")||(b+="/"),i.push({rdfClass:g,containerPath:b,forClass:this.capitalizeFirst(m),instanceContainer:l})}}}catch(d){console.warn(`Could not access container ${l}:`,d)}}}}return i}catch(e){return console.error("Error discovering types from profile:",e),[]}}inferRdfClassFromContainerName(e){const t=e.toLowerCase();return{people:"http://schema.org/Person",persons:"http://schema.org/Person",users:"http://schema.org/Person",posts:"http://schema.org/BlogPosting",articles:"http://schema.org/Article",events:"http://schema.org/Event",places:"http://schema.org/Place",organizations:"http://schema.org/Organization",products:"http://schema.org/Product",reviews:"http://schema.org/Review",comments:"http://schema.org/Comment",photos:"http://schema.org/ImageObject",images:"http://schema.org/ImageObject",documents:"http://schema.org/Document",files:"http://schema.org/MediaObject"}[t]||`https://example.com/vocab#${this.capitalizeFirst(e)}`}capitalizeFirst(e){return e.charAt(0).toUpperCase()+e.slice(1)}}class PodServices{constructor(e){const t=e.runtime,r=t.getPodUrl(),i=t.getWebId(),s=t.getFetch();this.uriResolver=new UriResolverImpl(r),this.sparqlConverter=new ASTToSPARQLConverter(r,i,this.uriResolver),this.sparqlExecutor=new SolidSPARQLExecutor({sources:[r],fetch:s,logging:!1,createQueryEngine:e.createQueryEngine}),this.ldpExecutor=new LdpExecutor(this.sparqlExecutor,s,this.uriResolver),this.typeIndexManager=new TypeIndexManager(i,r,s);const o=new TypeIndexDiscovery(this.typeIndexManager,r,this.uriResolver);if(e.disableInteropDiscovery)this.discovery=new CompositeDiscovery([o]);else{const a=new InteropDiscovery(i,s,e.clientId);this.discovery=new CompositeDiscovery([o,a])}this.shapeManager=new DrizzleShapeManager(r,s),this.resolverFactory=new ResourceResolverFactoryImpl(r,this.uriResolver),this.strategyFactory=new ExecutionStrategyFactoryImpl({sparqlExecutor:this.sparqlExecutor,sparqlConverter:this.sparqlConverter,sessionFetch:s,podUrl:r,createQueryEngine:e.createQueryEngine,ldpExecutor:this.ldpExecutor,uriResolver:this.uriResolver,getResolver:a=>this.resolverFactory.getResolver(a),listContainerResources:e.listContainerResources,findSubjectsForCondition:e.findSubjectsForCondition})}getUriResolver(){return this.uriResolver}getSparqlConverter(){return this.sparqlConverter}getSparqlExecutor(){return this.sparqlExecutor}getLdpExecutor(){return this.ldpExecutor}getTypeIndexManager(){return this.typeIndexManager}getDiscovery(){return this.discovery}getShapeManager(){return this.shapeManager}getResolverFactory(){return this.resolverFactory}getStrategyFactory(){return this.strategyFactory}}var define_process_env_default={},_a;function isRecord(n){return typeof n=="object"&&n!==null}function hasStringValue(n){return isRecord(n)&&typeof n.value=="string"}class PodDialect{constructor(e){this.registeredTables=new Set,this.preparedContainers=new Set,this.preparedResources=new Set,this.shortIdSubjectIndex=new Map,this.currentTableRegistry=new Map,this.currentTableNameRegistry=new Map,this.config=e;const t=e.session;this.debugLogger=new DebugLogger(e.debug||typeof process<"u"&&define_process_env_default?.LINX_DEBUG==="1"),setGlobalDebugLogger(this.debugLogger),this.debugLogger.log("Initializing PodDialect with config:",{debug:e.debug,disableInteropDiscovery:e.disableInteropDiscovery,storageTTL:e.storageTTL});const r=t.info.webId,i=t.info.clientId||t.info.client_id||(typeof process<"u"?define_process_env_default?.SOLID_CLIENT_ID:void 0);if(!r)throw new Error("Session中未找到webId");this.runtime=new PodRuntime({session:t,webId:r,podUrl:e.podUrl,storageTTL:e.storageTTL}),this.webId=this.runtime.getWebId(),this.podUrl=this.runtime.getPodUrl(),this.services=new PodServices({runtime:this.runtime,clientId:i,createQueryEngine:e.createQueryEngine,disableInteropDiscovery:e.disableInteropDiscovery,listContainerResources:s=>this.listContainerResources(s),findSubjectsForCondition:(s,o,a)=>this.findSubjectsForCondition(s,o,a)}),this.uriResolver=this.services.getUriResolver(),this.sparqlConverter=this.services.getSparqlConverter(),this.sparqlExecutor=this.services.getSparqlExecutor(),this.ldpExecutor=this.services.getLdpExecutor(),this.typeIndexManager=this.services.getTypeIndexManager(),this.discovery=this.services.getDiscovery(),this.shapeManager=this.services.getShapeManager(),this.resolverFactory=this.services.getResolverFactory(),this.strategyFactory=this.services.getStrategyFactory(),this.executor=new PodExecutor({ensureConnected:async()=>{this.runtime.isConnected()||await this.connect()},ensureTableResourcePath:s=>this.ensureTableResourcePath(s),resolveTableResource:s=>this.resolveTableResource(s),resolveTableUrls:s=>this.resolveTableUrls(s),normalizeResourceUrl:s=>this.normalizeResourceUrl(s),normalizeContainerKey:s=>this.normalizeContainerKey(s),normalizeResourceKey:s=>this.normalizeResourceKey(s),ensureContainerExists:s=>this.ensureContainerExists(s),ensureResourceExists:(s,o)=>this.ensureResourceExists(s,o),shouldSkipResourcePreparation:()=>this.shouldSkipResourcePreparation(),shouldUseWriteTimeResourcePreparation:()=>this.shouldUseWriteTimeResourcePreparation(),shouldContinueAfterResourcePreparationError:()=>this.shouldContinueAfterResourcePreparationError(),getTableRegistries:()=>({tableRegistry:this.currentTableRegistry,tableNameRegistry:this.currentTableNameRegistry}),ensureIdentifierCondition:(s,o,a)=>this.ensureIdentifierCondition(s,o,a),resourceExists:s=>this.resourceExists(s),getStrategy:s=>this.getStrategy(s),getLdpStrategy:()=>this.strategyFactory.getLdpStrategy(),preparedContainers:this.preparedContainers,preparedResources:this.preparedResources,sparqlConverter:this.sparqlConverter,sparqlExecutor:this.sparqlExecutor,isSelectPlan:s=>this.isSelectPlan(s),isInsertPlan:s=>this.isInsertPlan(s),isUpdatePlan:s=>this.isUpdatePlan(s),isDeletePlan:s=>this.isDeletePlan(s)})}getResolver(e){return this.resolverFactory.getResolver(e)}buildShortIdSubjectIndexKey(e,t){const r=e.config?.base??e.getResourcePath?.()??e.getContainerPath?.()??"",i=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"<exact-id>",s=e.getType?.()??e.config?.type??"";return`${e.config?.name??""}|${r}|${i}|${s}|${t}`}registerResourceSubject(e,t){const r=parsePodResourceRef(e,t)?.templateValues.id;if(!r)return;const i=this.buildShortIdSubjectIndexKey(e,r),s=this.shortIdSubjectIndex.get(i)??new Set;s.add(t),this.shortIdSubjectIndex.set(i,s)}unregisterResourceSubject(e,t){const r=parsePodResourceRef(e,t)?.templateValues.id;if(!r)return;const i=this.buildShortIdSubjectIndexKey(e,r),s=this.shortIdSubjectIndex.get(i);s&&(s.delete(t),s.size===0&&this.shortIdSubjectIndex.delete(i))}lookupIndexedResourceSubject(e,t){const r=this.shortIdSubjectIndex.get(this.buildShortIdSubjectIndexKey(e,t));if(!r||r.size===0)return null;if(r.size>1)throw new Error(`Indexed short id '${t}' for resource '${e.config?.name??"resource"}' is ambiguous. Use a base-relative resource id or full IRI to disambiguate.`);return Array.from(r)[0]??null}getStrategy(e){return this.strategyFactory.getStrategy(e)}getShapeManager(){return this.services.getShapeManager()}getUriResolver(){return this.services.getUriResolver()}getDiscovery(){return this.services.getDiscovery()}setSchema(e){const t=new Map,r=new Map;for(const[i,s]of Object.entries(e))if(s&&typeof s=="object"&&"config"in s){const o=s,a=o.getType?.()||o.config?.type,u=o.config?.name||i;if(r.set(u,o),a){const c=t.get(a)||[];c.push(o),t.set(a,c)}}this.currentTableRegistry=t,this.currentTableNameRegistry=r,this.refreshBaseUrlFromRuntime()}refreshBaseUrlFromRuntime(){const e=this.runtime.getPodUrl();e&&(this.podUrl!==e&&(this.podUrl=e,this.preparedContainers.clear(),this.preparedResources.clear()),this.uriResolver.setPodUrl(this.podUrl),this.resolverFactory.setPodBaseUrl(this.podUrl),this.strategyFactory.setPodUrl(this.podUrl),this.typeIndexManager.updateConfig({...this.typeIndexManager.getConfig(),podUrl:this.podUrl}),this.ldpExecutor.setBaseUri(this.podUrl),(this.currentTableRegistry.size>0||this.currentTableNameRegistry.size>0)&&(this.ldpExecutor.setTableRegistry(this.currentTableRegistry,this.currentTableNameRegistry),this.sparqlConverter.setTableRegistry(this.currentTableRegistry,this.currentTableNameRegistry,this.podUrl)))}async findSubjectsForCondition(e,t,r){const i=this.buildSubjectLookupPlan(t,e),s=this.sparqlConverter.convertSelectPlan(i),o=this.normalizeResourceUrl(r);return(await this.executeOnResource(o,s)).map(u=>this.extractSubjectFromRow(u)).filter(u=>!!u)}async connect(){await this.runtime.connect(),this.refreshBaseUrlFromRuntime()}async disconnect(){await this.runtime.disconnect()}isConnected(){return this.runtime.isConnected()}extractUserPathFromWebId(){if(!this.webId)return"";try{const t=new URL(this.webId).pathname.split("/");if(t.length>=2)return`/${t[1]}/`}catch(e){console.warn("Failed to parse webId:",this.webId,e)}return""}resolveTableResource(e){const t=e.getSparqlEndpoint?.();if(t)return{mode:"sparql",endpoint:this.isAbsoluteUrl(t)?t:this.resolveAbsoluteUrl(t)};const{containerUrl:r,resourceUrl:i}=this.resolveLdpResource(e);return{mode:"ldp",containerUrl:r,resourceUrl:i}}resolveTableUrls(e){return this.resolveLdpResource(e)}resolveLdpResource(e){const t=typeof e.getResourcePath=="function"?e.getResourcePath():void 0;if(t){const S=this.resolveAbsoluteUrl(t);if(t.endsWith("/")){const C=S.endsWith("/")?S:`${S}/`;return{containerUrl:C,resourceUrl:C}}const v=this.normalizeResourceUrl(S),_=v.lastIndexOf("/");return{containerUrl:_>=0?`${v.slice(0,_+1)}`:`${v}/`,resourceUrl:v}}const r=e.getContainerPath()||"/data/",i=r.startsWith("http://")||r.startsWith("https://"),s=S=>S.endsWith("/")?S:`${S}/`;if(i){if(r.endsWith("/")){const _=s(r);return{containerUrl:_,resourceUrl:`${_}${e.config.name}.ttl`}}const S=r,w=S.lastIndexOf("/");if(w===-1)throw new Error(`Invalid containerPath for table ${e.config.name}: ${r}`);return{containerUrl:s(S.slice(0,w+1)),resourceUrl:S}}const o=this.extractUserPathFromWebId(),a=r.replace(/^\/+/,""),u=this.podUrl.endsWith("/")?this.podUrl:`${this.podUrl}/`,c=o.replace(/^\/+/,""),l=c&&a.startsWith(c);if(r.endsWith("/")){const S=l?a:`${c}${a}`,w=s(`${u}${S.replace(/^\/+/,"")}`);return{containerUrl:w,resourceUrl:`${w}${e.config.name}.ttl`}}const d=l?a:`${c}${a}`,f=d.lastIndexOf("/"),m=f>=0?d.slice(0,f+1):c,g=s(`${u}${m.replace(/^\/+/,"")}`),b=`${u}${d.replace(/^\/+/,"")}`;return{containerUrl:g,resourceUrl:b}}async resourceExists(e){const t=this.normalizeResourceUrl(e);if(this.preparedResources.has(t))return!0;try{const r=await this.runtime.getFetch()(t,{method:"HEAD"});return r.ok||r.status===409?(this.markResourcePrepared(t),!0):r.status===404?!1:r.status===405?(await this.runtime.getFetch()(t,{method:"GET",headers:{Accept:"text/turtle"}})).ok?(this.markResourcePrepared(t),!0):!1:r.status===401||r.status===403?(this.markResourcePrepared(t),!0):r.ok}catch(r){this.debugLogger.warn("[PodDialect] Failed to check resource existence via HEAD, falling back to GET",r);try{return(await this.runtime.getFetch()(t,{method:"GET",headers:{Accept:"text/turtle"}})).ok?(this.markResourcePrepared(t),!0):!1}catch(i){return this.debugLogger.warn("[PodDialect] Resource existence fallback GET failed",i),!1}}}normalizeResourceUrl(e){if(!e)return e;let t=e;for(;t.endsWith("/")&&!t.endsWith("://");)t=t.slice(0,-1);return t}normalizeContainerKey(e){const t=e.startsWith("http")?e:this.resolveAbsoluteUrl(e);return t.endsWith("/")?t:`${t}/`}normalizeResourceKey(e){const t=e.startsWith("http")?e:this.resolveAbsoluteUrl(e);return this.normalizeResourceUrl(t)}isStorageRootContainer(e){const t=this.runtime.getStorageUrl()??this.runtime.getPodUrl();return this.normalizeContainerKey(e)===this.normalizeContainerKey(t)}markContainerPrepared(e){this.preparedContainers.add(this.normalizeContainerKey(e))}markResourcePrepared(e){this.preparedResources.add(this.normalizeResourceKey(e))}isAbsoluteUrl(e){return/^https?:\/\//i.test(e)}resolveAbsoluteUrl(e){if(!e)return this.podUrl.replace(/\/$/,"");if(this.isAbsoluteUrl(e))return e;const t=e.replace(/^(\.\/)+/,""),r=this.podUrl.endsWith("/")?this.podUrl:`${this.podUrl}/`,i=t.endsWith("/"),o=this.extractUserPathFromWebId().replace(/^\/+|\/+$/g,"");let u=t.replace(/^\/+/,"");const c=o.length>0?`${o}/`:"";if(o.length>0){let d=!1;try{d=new URL(r).pathname.replace(/^\/+|\/+$/g,"").startsWith(o)}catch{d=!1}!d&&(u.length===0||u!==o&&!u.startsWith(c))&&(u=u.length>0?`${o}/${u}`:o)}i&&!u.endsWith("/")&&(u=`${u}/`);const l=new URL(u,r).toString();return!i&&l.endsWith("/")?l.replace(/\/$/,""):l}async ensureResourceExists(e,t={}){const{createIfMissing:r=!0}=t,i=this.normalizeResourceUrl(e);if(this.preparedResources.has(i))return;if(await this.resourceExists(i)){this.markResourcePrepared(i);return}if(!r)throw new Error(`Resource not found: ${i}`);for(let o=0;o<3;o++)try{const a=await this.runtime.getFetch()(i,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:""});if(a.ok||[201,202,204,409].includes(a.status)){await this.sparqlExecutor.invalidateHttpCache(i),this.markResourcePrepared(i);return}if(a.status>=500){this.debugLogger.warn(`[PodDialect] ensureResourceExists attempt ${o+1}/3 failed with ${a.status}, retrying...`),await new Promise(c=>setTimeout(c,1e3));continue}const u=await this.readErrorResponseBody(a);throw new Error(this.formatResourcePreparationError("Failed to create resource",a.status,a.statusText,i,u))}catch(a){if(o===2)throw this.debugLogger.error("[PodDialect] ensureResourceExists failed after 3 attempts:",a),a;this.debugLogger.warn(`[PodDialect] ensureResourceExists attempt ${o+1}/3 failed with error:`,a),await new Promise(u=>setTimeout(u,1e3))}}async executeOnResource(e,t,r){const i=this.normalizeResourceUrl(e);if(r?.mode==="sparql")return await this.executeOnSparqlEndpoint(r.endpoint,t);if(t.type==="SELECT"||t.type==="ASK")return await this.sparqlExecutor.queryContainer(i,t);throw new Error("LDP mode does not support SPARQL UPDATE; use N3 patch helpers instead.")}getFetchForEndpoint(e){return getFetchForOrigin(e,this.podUrl,this.runtime.getFetch())}async executeOnSparqlEndpoint(e,t){const r=this.getFetchForEndpoint(e);if(t.type==="SELECT"||t.type==="ASK")return isSameOrigin(e,this.podUrl)?await this.sparqlExecutor.executeQueryWithSource(t,e,"sparql"):await new ComunicaSPARQLExecutor({sources:[e],fetch,logging:!1,createQueryEngine:this.config.createQueryEngine}).executeQueryWithSource(t,e,"sparql");const i=await r(e,{method:"POST",headers:{"Content-Type":"application/sparql-update"},body:t.query});if(!i.ok){const s=await i.text().catch(()=>"");throw new Error(`SPARQL endpoint update failed: ${i.status} ${i.statusText}${s?` - ${s}`:""}`)}return[{success:!0,source:e,status:i.status,via:"sparql-endpoint"}]}async ensureTableResourcePath(e){const t=typeof e.config.type=="string"?e.config.type:String(e.config.type),r=e.getResourcePath?.();if(!e.config.typeIndex){if(r&&r.trim().length>0)return;console.log(`[AutoDiscover] Table ${e.config.name} has no resourcePath, using default container path`),e.config.containerPath="/data/";return}console.log(`[AutoDiscover] Table ${e.config.name} has typeIndex enabled, discovering from TypeIndex/SAI...`);try{const s=(await this.discovery.discover(t))[0];if(s){let o=s.container;o.endsWith("/")||(o+="/"),s.subjectTemplate&&(e.setSubjectTemplate(s.subjectTemplate),console.log(`[AutoDiscover] ✓ Applied subjectTemplate from discovery: ${s.subjectTemplate}`));const a=this.uriResolver.getResourceMode(e);let u;a==="document"?u=o:u=`${o}${e.config.name}.ttl`,console.log(`[AutoDiscover] ✓ Found resource path from TypeIndex: ${u} (mode: ${a})`),e.setBase(u),await this.tryDiscoverSparqlEndpoint(e,o)}else{if(r&&r.trim().length>0){console.log(`[AutoDiscover] No discovery result, using configured path: ${r}`);return}throw new Error(`[AutoDiscover] No data location found for type ${t}. Please ensure the data is registered in TypeIndex or SAI Registry.`)}}catch(i){if(r&&r.trim().length>0){console.warn("[AutoDiscover] Discovery process failed, using configured path:",r);return}throw console.warn("[AutoDiscover] Discovery process failed:",i),i}}async tryDiscoverSparqlEndpoint(e,t){if(e.getSparqlEndpoint())return;const r=`${t.replace(/\/$/,"")}/-/sparql`;try{(await this.runtime.getFetch()(r,{method:"OPTIONS"})).ok&&(console.log(`[AutoDiscover] ✓ Found SPARQL endpoint: ${r}`),e.setSparqlEndpoint(r))}catch{}}async query(e){return this.executor.query(e)}collectSelectSources(e){const t=new Set,{resourceUrl:r}=this.resolveTableUrls(e.baseTable);if(t.add(r),e.joins)for(const i of e.joins){const{resourceUrl:s}=this.resolveTableUrls(i.table);t.add(s)}return Array.from(t)}buildIdInConditionFromSubjects(e){if(!(!e||e.length===0))return new BinaryExpression("@id","IN",e)}isInsertPlan(e){return!!(e&&typeof e.table<"u"&&Array.isArray(e.rows))}isUpdatePlan(e){return!!(e&&typeof e.table<"u"&&"data"in e)}isDeletePlan(e){if(!e)return!1;const t=e;return typeof t.table>"u"?!1:typeof t.rows>"u"&&typeof t.data>"u"}isSelectPlan(e){return e?typeof e.baseTable<"u":!1}buildSubjectLookupPlan(e,t){const r=e.config.name??"table";return{baseTable:e,baseAlias:r,selectAll:!0,conditionTree:t,aliasToTable:new Map([[r,e]]),tableToAlias:new Map([[e,r]])}}isQueryConditionNode(e){return e instanceof BinaryExpression||e instanceof LogicalExpression||e instanceof UnaryExpression}extractSubjectFromRow(e){const t=e.subject??e["?subject"];return t?typeof t=="string"?t:hasStringValue(t)?t.value:null:null}conditionTargetsIdentifier(e){if(!e)return!1;if(e.type==="binary_expr"){const t=e.left,r=typeof t=="string"?t:t instanceof PodColumnBase?t.name:void 0;if(r==="@id"||r==="id")return!0}if(e.type==="logical_expr"){const t=e.expressions;if(Array.isArray(t))return t.some(r=>this.isQueryConditionNode(r)&&this.conditionTargetsIdentifier(r))}if(e.type==="unary_expr"){const t=e.value;if(t&&typeof t=="object"&&"type"in t)return this.conditionTargetsIdentifier(t)}return!1}async rewriteIdentifierConditionWithSubjects(e,t){const r=this.getResolver(t);try{const i=await r.resolveSubjectsForMutation(t,e,async()=>[],async()=>[]);return this.buildIdInConditionFromSubjects(i)}catch(i){const s=t.getSubjectTemplate?.()??t.config?.subjectTemplate??"<exact-id>";throw(i instanceof Error?i.message:String(i)).includes("missing required variable")?new Error(`Cannot resolve mutation target for table "${t.config.name??"unknown"}" with subjectTemplate "${s}" from where() alone. Use an explicit @id via db.updateByIri()/db.deleteByIri() (or the internal whereByIri()).`):i}}async ensureIdentifierCondition(e,t,r){if(e)return this.conditionTargetsIdentifier(e)?await this.rewriteIdentifierConditionWithSubjects(e,t):await this.rewriteWhereConditionWithSubjects(e,t,r)}async rewriteWhereConditionWithSubjects(e,t,r){if(!e)return;const i=await this.findSubjectsForCondition(e,t,r);return this.buildIdInConditionFromSubjects(i)}async executeSql(e,t){const r=e.queryChunks.join("");let i;if(r.toLowerCase().includes("select"))i="select";else if(r.toLowerCase().includes("insert"))i="insert";else if(r.toLowerCase().includes("update"))i="update";else if(r.toLowerCase().includes("delete"))i="delete";else throw new Error(`Unsupported SQL operation: ${r}`);const s={type:i,table:t,sql:e,values:e.params||[]};return this.query(s)}addNamespace(e,t){this.sparqlConverter.addPrefix(e,t)}getConfig(){return{podUrl:this.podUrl,webId:this.webId,connected:this.runtime.isConnected()}}getAuthenticatedFetch(){return this.runtime.getFetch()}getSPARQLConverter(){return this.sparqlConverter}getSPARQLExecutor(){return this.sparqlExecutor}getPodUrl(){return this.runtime.getPodUrl()}getWebId(){return this.runtime.getWebId()}async discoverDataLocations(e,t){return this.discovery.discover(e,t)}async discoverAll(){return this.discovery.discoverAll?this.discovery.discoverAll():[]}async discoverByApp(e){return this.discovery.discoverByApp?this.discovery.discoverByApp(e):[]}addSource(e){this.sparqlExecutor.addSource(e)}removeSource(e){this.sparqlExecutor.removeSource(e)}getSources(){return this.sparqlExecutor.getSources()}async addSourcesFromTypeIndex(){try{const e=await this.typeIndexManager.discoverTypes();for(const t of e)if(t.instanceContainer)this.sparqlExecutor.addSource(t.instanceContainer);else if(t.containerPath){const r=t.containerPath.startsWith("http")?t.containerPath:`${this.podUrl}${t.containerPath}`;this.sparqlExecutor.addSource(r)}console.log(`✅ 从 TypeIndex 自动添加了 ${e.length} 个数据源`)}catch(e){console.warn("⚠️ 无法从 TypeIndex 自动添加数据源:",e)}}async queryContainer(e,t,r){const i=this.sparqlConverter.parseDrizzleAST(t,r),s=this.sparqlConverter.convertSelect(i,r),o=r?.config?.containerPath||e;return this.sparqlExecutor.queryContainer(o,s)}async getPodMetadata(){if(!this.runtime.isConnected())throw new Error("Not connected to Pod");return{podUrl:this.podUrl,webId:this.webId,connected:this.runtime.isConnected(),sources:this.sparqlExecutor.getSources()}}stripSPARQLProlog(e){return e.replace(/^\s*#.*$/gm,"").trim().replace(/^(?:\s*(?:PREFIX|BASE)\s+[^\n]+\n)*/i,"").trim()}looksLikeRawSQL(e){const t=this.stripSPARQLProlog(e);return!!(/^SELECT\b[\s\S]*\bFROM\b\s+(?!<|[?$])/i.test(t)&&!/\{/m.test(t)||/^INSERT\s+INTO\b/i.test(t)||/^UPDATE\s+[A-Za-z_`"][\w$`"]*\s+SET\b/i.test(t)||/^DELETE\s+FROM\b/i.test(t))}inferSPARQLQueryType(e){const r=this.stripSPARQLProlog(e).match(/^(SELECT|ASK|INSERT|DELETE|UPDATE|WITH|LOAD|CLEAR|CREATE|DROP|COPY|MOVE|ADD|CONSTRUCT|DESCRIBE)\b/i)?.[1]?.toUpperCase();switch(r){case"SELECT":case"ASK":case"INSERT":case"DELETE":case"UPDATE":return r;case"WITH":case"LOAD":case"CLEAR":case"CREATE":case"DROP":case"COPY":case"MOVE":case"ADD":return"UPDATE";default:return}}async executeSPARQL(e){if(!this.runtime.isConnected())throw new Error("Not connected to Pod");if(this.looksLikeRawSQL(e))throw new Error("executeSPARQL only accepts SPARQL text; raw SQL is not supported in Solid dialect");const t=this.inferSPARQLQueryType(e);if(!t)throw new Error("Unsupported SPARQL query type. Supported types: SELECT, ASK, INSERT, DELETE, UPDATE");const r={type:t,query:e,prefixes:{}};return this.sparqlExecutor.executeQuery(r)}async transaction(e){console.log("Starting transaction");try{const t=await e(this);return console.log("Transaction completed successfully"),t}catch(t){throw console.error("Transaction failed:",t),t}}getResourcePreparationMode(){return this.config.resourcePreparation??"best-effort"}shouldSkipResourcePreparation(){return this.getResourcePreparationMode()==="off"}shouldUseWriteTimeResourcePreparation(){const e=this.getResourcePreparationMode();return e==="best-effort"||e==="off"}shouldContinueAfterResourcePreparationError(){return this.getResourcePreparationMode()==="best-effort"}async registerTable(e){if(this.shouldSkipResourcePreparation()){e.markInitialized?.(!0);return}if(e.config.autoRegister===!1){e.markInitialized?.(!0);return}const t=e.config.name??JSON.stringify(e.config);if(this.registeredTables.has(t)){e.markInitialized?.(!0);return}try{const r=this.resolveTableResource(e);if(r.mode!=="sparql")if(this.shouldUseWriteTimeResourcePreparation())try{e.setBase?.(r.resourceUrl)}catch(i){this.debugLogger.warn(`[registerTable] setBase failed for ${e.config.name}:`,i)}else{await this.ensureContainerExists(r.containerUrl);try{await this.ensureResourceExists(r.resourceUrl,{createIfMissing:!0}),this.markResourcePrepared(r.resourceUrl)}catch(i){this.debugLogger.warn(`[registerTable] ensureResourceExists failed for ${r.resourceUrl}:`,i)}this.markContainerPrepared(r.containerUrl);try{e.setBase?.(r.resourceUrl)}catch(i){this.debugLogger.warn(`[registerTable] setBase failed for ${e.config.name}:`,i)}}}catch(r){if(this.debugLogger.warn(`[registerTable] Resource preparation failed for ${e.config.name}:`,r),this.config.resourcePreparation==="strict")throw r}this.registeredTables.add(t),this.shouldUseWriteTimeResourcePreparation()||await this.discovery.register(e,{registryPath:e.config.saiRegistryPath}),e.markInitialized?.(!0)}async findTypeIndex(){return this.typeIndexManager.findTypeIndex()}async createTypeIndex(){return this.typeIndexManager.createTypeIndex()}async discoverTypes(e){return this.typeIndexManager.discoverTypes(e)}async autoDiscoverAndRegister(e){return this.typeIndexManager.autoDiscoverAndRegister(e)}async discoverTypesFromProfile(){return this.typeIndexManager.discoverTypesFromProfile()}async discoverSpecificType(e){return this.typeIndexManager.discoverSpecificType(e)}async discoverSpecificTypes(e){return this.typeIndexManager.discoverSpecificTypes(e)}async discoverTable(e){return this.typeIndexManager.discoverTable(e)}async discoverTables(e){return this.typeIndexManager.discoverTables(e)}async isTypeRegistered(e,t){return this.typeIndexManager.isTypeRegistered(e,t)}getTypeIndexManager(){return this.typeIndexManager}async ensureContainerExists(e){try{const t=this.normalizeContainerKey(e);if(this.preparedContainers.has(t))return;if(this.isStorageRootContainer(t)){this.markContainerPrepared(t);return}const r=await this.runtime.getFetch()(t,{method:"HEAD"});if(r.status===401||r.status===403){this.debugLogger.log(`[Container] ${t} 不允许 HEAD,视为已存在`),this.markContainerPrepared(t);return}if(r.status===404||r.status===500){const i=this.getParentContainer(t);i&&i!==t&&(this.debugLogger.log(`[Container] 先创建父容器: ${i}`),await this.ensureContainerExists(i)),this.debugLogger.log(`[Container] 创建容器: ${t}`);const s=await this.createContainerWithRetry(t);if(s.ok)this.debugLogger.log(`[Container] 容器创建成功: ${s.status}`),await this.sparqlExecutor.invalidateHttpCache(t),this.markContainerPrepared(t);else if(s.status===409)this.debugLogger.log(`[Container] 容器已存在(409冲突): ${t}`),this.markContainerPrepared(t);else{const o=await this.readErrorResponseBody(s);throw new Error(this.formatResourcePreparationError("Failed to create container",s.status,s.statusText,t,o))}}else if(r.status===200)this.debugLogger.log(`[Container] 容器已存在: ${t}`),this.markContainerPrepared(t);else if(r.status===409)this.debugLogger.log(`[Container] 容器已存在(409冲突): ${t}`),this.markContainerPrepared(t);else if(!r.ok)throw new Error(this.formatResourcePreparationError("Failed to check container",r.status,r.statusText,t))}catch(t){throw this.debugLogger.error("[Container] 确保容器存在时出错:",t),t}}async createContainerWithRetry(e){let t=null;for(let r=0;r<3;r+=1){const i=await this.runtime.getFetch()(e,{method:"PUT",headers:{"Content-Type":"text/turtle",Link:'<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'}});if(t=i,i.ok||i.status===409||i.status<500)return i;this.debugLogger.warn(`[Container] 创建容器失败 ${r+1}/3: ${i.status} ${i.statusText} (${e})`),r<2&&await this.sleep(250*(r+1))}return t}async sleep(e){await new Promise(t=>setTimeout(t,e))}async readErrorResponseBody(e){const t=e;if(typeof t.text!="function")return"";try{return(await t.text()).trim().slice(0,1e3)}catch{return""}}formatResourcePreparationError(e,t,r,i,s=""){const o=s?` - ${s}`:"";return`${e}: ${t} ${r} (${i})${o}`}getParentContainer(e){try{const t=new URL(e),r=t.pathname.split("/").filter(i=>i.length>0);return r.length<=1?null:(r.pop(),t.pathname="/"+r.join("/")+"/",t.toString())}catch(t){return this.debugLogger.error("[Container] 解析父容器 URL 失败:",t),null}}async listContainerResources(e){const t=this.normalizeContainerKey(e),r=[];try{const i={type:"SELECT",query:`
|
|
214
|
+
PREFIX ldp: <http://www.w3.org/ns/ldp#>
|
|
215
|
+
SELECT ?resource WHERE {
|
|
216
|
+
<${t}> ldp:contains ?resource .
|
|
217
|
+
}
|
|
218
|
+
`,prefixes:{ldp:"http://www.w3.org/ns/ldp#"}},s=await this.sparqlExecutor.queryContainer(t,i);for(const o of s){const a=o.resource;if(a){const u=hasStringValue(a)?a.value:String(a);r.push(u)}}}catch(i){console.warn("[listContainerResources] SPARQL query failed:",i)}return r}}_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},r=new PodDialect(t);e?.schema&&r.setSchema(e.schema);const i=new PodAsyncSession(r);return new PodDatabase(r,i,e?.schema)}function createRepositoryDescriptor(n){const{namespace:e,table:t,searchableFields:r,defaultSort:i,cache:s}=n,o=n.searchAccessor??(w=>{const v=w?w.search:void 0;return typeof v=="string"?v:void 0}),a=n.transform??(w=>w),u={create:n.invalidations?.create??["list"],update:n.invalidations?.update??["list","detail"],remove:n.invalidations?.remove??["list","detail"]},c=w=>{const v=t[w];if(v)return v;const _=t.config?.name;return _?`${_}.${w}`:w},l=w=>{const v=[],_=o(w)?.trim();if(_&&r?.length){const C=`%${_}%`,U=r.map($=>like(c($),C));U.length===1?v.push(U[0]):U.length>1&&v.push(or(...U))}const T=n.filter?.({table:t,filters:w});if(T&&v.push(T),v.length!==0)return v.length===1?v[0]:and(...v)},d=async(w,v)=>{let _=w.select().from(t);const T=l(v);return T&&(_=_.where(T)),i&&(_=_.orderBy(c(i.field),i.direction)),(await _.execute()).map(U=>a(U))},f=async(w,v)=>{const _=await w.findByIri(t,v);return _?a(_):null},m=n.disableMutations?.create?void 0:async(w,v)=>{const _=v.id,T=typeof _=="string"&&_.length>0?_:crypto.randomUUID(),C={...v,id:T},U=await w.insert(t).values(C).execute(),$=Array.isArray(U)?U?.[0]:U;if($&&typeof $=="object"&&!("success"in $))return a($);const W=$&&typeof $=="object"&&"source"in $?$.source:null,re=W?w.resolveRowIri(t,{...C,source:W}):w.resolveRowIri(t,C);return{...C,id:w.resolveRowId(t,{...C,"@id":re}),"@id":re,subject:re,uri:re,source:W??re}},g=n.disableMutations?.update?void 0:async(w,v,_)=>{const T=await w.updateByIri(t,v,_);if(T)return a(T);const C=await f(w,v);if(!C)throw new Error(`Failed to load ${e} record after update`);return C},b=n.disableMutations?.remove?void 0:async(w,v)=>(await w.deleteByIri(t,v),{id:v}),S=typeof t.getResourcePath=="function"?t.getResourcePath():t.config?.base??"";return{namespace:e,resourcePath:S,searchableFields:r,defaultSort:i,cache:s,invalidations:u,list:d,detail:f,create:m,update:g,remove:b}}function createResourceRepositoryDescriptor(n){const{resource:e,filter:t,...r}=n;return createRepositoryDescriptor({...r,table:e,filter:t?({table:i,filters:s})=>t({resource:i,filters:s}):void 0})}const definePodRepository=createResourceRepositoryDescriptor;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$1={PREFIX:"rdf",NAMESPACE:_NAMESPACE$h,PREFIX_AND_NAMESPACE:{rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#"},NS:_NS$h,Property:_NS$h("Property"),HTML:_NS$h("HTML"),langString:_NS$h("langString"),PlainLiteral:_NS$h("PlainLiteral"),Statement:_NS$h("Statement"),Bag:_NS$h("Bag"),Seq:_NS$h("Seq"),Alt:_NS$h("Alt"),List:_NS$h("List"),XMLLiteral:_NS$h("XMLLiteral"),JSON:_NS$h("JSON"),CompoundLiteral:_NS$h("CompoundLiteral"),type:_NS$h("type"),subject:_NS$h("subject"),predicate:_NS$h("predicate"),object:_NS$h("object"),value:_NS$h("value"),nil:_NS$h("nil"),first:_NS$h("first"),rest:_NS$h("rest"),language:_NS$h("language"),direction:_NS$h("direction")},_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 r=(i=>ABSOLUTE_IRI$1.test(i)?i:`${e}${i}`);return r.prefix=n,r.uri=e,r.NAMESPACE=e,r.term=i=>r(i),Object.entries(t).forEach(([i,s])=>{Object.defineProperty(r,i,{value:r(s),enumerable:!0})}),r},DCTerms=DCTERMS,RDF=RDF$1,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",lastFailureCode:"lastFailureCode",lastFailureAt:"lastFailureAt",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",dueAt:"dueAt",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;const namespaces=Object.freeze(Object.defineProperty({__proto__:null,AS,DCTerms,FOAF,LDP,MEETING,ODRL,RDF,SCHEMA,SIOC,UDFS,VCARD,WF},Symbol.toStringTag,{value:"Module"})),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 crypto$1=crypto,isCryptoKey=n=>n instanceof CryptoKey,encoder=new TextEncoder,decoder=new TextDecoder;function concat(...n){const e=n.reduce((i,{length:s})=>i+s,0),t=new Uint8Array(e);let r=0;for(const i of n)t.set(i,r),r+=i.length;return t}const encodeBase64=n=>{let e=n;typeof e=="string"&&(e=encoder.encode(e));const t=32768,r=[];for(let i=0;i<e.length;i+=t)r.push(String.fromCharCode.apply(null,e.subarray(i,i+t)));return btoa(r.join(""))},encode$1=n=>encodeBase64(n).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),decodeBase64=n=>{const e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t},decode=n=>{let e=n;e instanceof Uint8Array&&(e=decoder.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return decodeBase64(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class JOSEError extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}JOSEError.code="ERR_JOSE_GENERIC";class JWTClaimValidationFailed extends JOSEError{constructor(e,t,r="unspecified",i="unspecified"){super(e,{cause:{claim:r,reason:i,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=i,this.payload=t}}JWTClaimValidationFailed.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class JWTExpired extends JOSEError{constructor(e,t,r="unspecified",i="unspecified"){super(e,{cause:{claim:r,reason:i,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=i,this.payload=t}}JWTExpired.code="ERR_JWT_EXPIRED";class JOSEAlgNotAllowed extends JOSEError{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}JOSEAlgNotAllowed.code="ERR_JOSE_ALG_NOT_ALLOWED";class JOSENotSupported extends JOSEError{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}JOSENotSupported.code="ERR_JOSE_NOT_SUPPORTED";class JWEDecryptionFailed extends JOSEError{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}JWEDecryptionFailed.code="ERR_JWE_DECRYPTION_FAILED";class JWEInvalid extends JOSEError{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}JWEInvalid.code="ERR_JWE_INVALID";class JWSInvalid extends JOSEError{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}JWSInvalid.code="ERR_JWS_INVALID";class JWTInvalid extends JOSEError{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}JWTInvalid.code="ERR_JWT_INVALID";class JWKInvalid extends JOSEError{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}JWKInvalid.code="ERR_JWK_INVALID";class JWKSInvalid extends JOSEError{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}JWKSInvalid.code="ERR_JWKS_INVALID";class JWKSNoMatchingKey extends JOSEError{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}JWKSNoMatchingKey.code="ERR_JWKS_NO_MATCHING_KEY";class JWKSMultipleMatchingKeys extends JOSEError{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}JWKSMultipleMatchingKeys.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class JWKSTimeout extends JOSEError{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}JWKSTimeout.code="ERR_JWKS_TIMEOUT";class JWSSignatureVerificationFailed extends JOSEError{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}JWSSignatureVerificationFailed.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function unusable(n,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${n}`)}function isAlgorithm(n,e){return n.name===e}function getHashLength(n){return parseInt(n.name.slice(4),10)}function getNamedCurve(n){switch(n){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function checkUsage(n,e){if(e.length&&!e.some(t=>n.usages.includes(t))){let t="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const r=e.pop();t+=`one of ${e.join(", ")}, or ${r}.`}else e.length===2?t+=`one of ${e[0]} or ${e[1]}.`:t+=`${e[0]}.`;throw new TypeError(t)}}function checkSigCryptoKey(n,e,...t){switch(e){case"HS256":case"HS384":case"HS512":{if(!isAlgorithm(n.algorithm,"HMAC"))throw unusable("HMAC");const r=parseInt(e.slice(2),10);if(getHashLength(n.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!isAlgorithm(n.algorithm,"RSASSA-PKCS1-v1_5"))throw unusable("RSASSA-PKCS1-v1_5");const r=parseInt(e.slice(2),10);if(getHashLength(n.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!isAlgorithm(n.algorithm,"RSA-PSS"))throw unusable("RSA-PSS");const r=parseInt(e.slice(2),10);if(getHashLength(n.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":{if(n.algorithm.name!=="Ed25519"&&n.algorithm.name!=="Ed448")throw unusable("Ed25519 or Ed448");break}case"Ed25519":{if(!isAlgorithm(n.algorithm,"Ed25519"))throw unusable("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!isAlgorithm(n.algorithm,"ECDSA"))throw unusable("ECDSA");const r=getNamedCurve(e);if(n.algorithm.namedCurve!==r)throw unusable(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}checkUsage(n,t)}function message(n,e,...t){if(t=t.filter(Boolean),t.length>2){const r=t.pop();n+=`one of type ${t.join(", ")}, or ${r}.`}else t.length===2?n+=`one of type ${t[0]} or ${t[1]}.`:n+=`of type ${t[0]}.`;return e==null?n+=` Received ${e}`:typeof e=="function"&&e.name?n+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(n+=` Received an instance of ${e.constructor.name}`),n}const invalidKeyInput=(n,...e)=>message("Key must be ",n,...e);function withAlg(n,e,...t){return message(`Key for the ${n} algorithm must be `,e,...t)}const isKeyLike=n=>isCryptoKey(n)?!0:n?.[Symbol.toStringTag]==="KeyObject",types=["CryptoKey"],isDisjoint=(...n)=>{const e=n.filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(const r of e){const i=Object.keys(r);if(!t||t.size===0){t=new Set(i);continue}for(const s of i){if(t.has(s))return!1;t.add(s)}}return!0};function isObjectLike(n){return typeof n=="object"&&n!==null}function isObject(n){if(!isObjectLike(n)||Object.prototype.toString.call(n)!=="[object Object]")return!1;if(Object.getPrototypeOf(n)===null)return!0;let e=n;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(n)===e}const checkKeyLength=(n,e)=>{if(n.startsWith("RS")||n.startsWith("PS")){const{modulusLength:t}=e.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${n} requires key modulusLength to be 2048 bits or larger`)}};function isJWK(n){return isObject(n)&&typeof n.kty=="string"}function isPrivateJWK(n){return n.kty!=="oct"&&typeof n.d=="string"}function isPublicJWK(n){return n.kty!=="oct"&&typeof n.d>"u"}function isSecretJWK(n){return isJWK(n)&&n.kty==="oct"&&typeof n.k=="string"}function subtleMapping(n){let e,t;switch(n.kty){case"RSA":{switch(n.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${n.alg.slice(-3)}`},t=n.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.alg.slice(-3)}`},t=n.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(n.alg.slice(-3),10)||1}`},t=n.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(n.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},t=n.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},t=n.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},t=n.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:n.crv},t=n.d?["deriveBits"]:[];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(n.alg){case"Ed25519":e={name:"Ed25519"},t=n.d?["sign"]:["verify"];break;case"EdDSA":e={name:n.crv},t=n.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:n.crv},t=n.d?["deriveBits"]:[];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}const parse=async n=>{if(!n.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:t}=subtleMapping(n),r=[e,n.ext??!1,n.key_ops??t],i={...n};return delete i.alg,delete i.use,crypto$1.subtle.importKey("jwk",i,...r)},exportKeyValue=n=>decode(n);let privCache,pubCache;const isKeyObject=n=>n?.[Symbol.toStringTag]==="KeyObject",importAndCache=async(n,e,t,r,i=!1)=>{let s=n.get(e);if(s?.[r])return s[r];const o=await parse({...t,alg:r});return i&&Object.freeze(e),s?s[r]=o:n.set(e,{[r]:o}),o},normalizePublicKey=(n,e)=>{if(isKeyObject(n)){let t=n.export({format:"jwk"});return delete t.d,delete t.dp,delete t.dq,delete t.p,delete t.q,delete t.qi,t.k?exportKeyValue(t.k):(pubCache||(pubCache=new WeakMap),importAndCache(pubCache,n,t,e))}return isJWK(n)?n.k?decode(n.k):(pubCache||(pubCache=new WeakMap),importAndCache(pubCache,n,n,e,!0)):n},normalizePrivateKey=(n,e)=>{if(isKeyObject(n)){let t=n.export({format:"jwk"});return t.k?exportKeyValue(t.k):(privCache||(privCache=new WeakMap),importAndCache(privCache,n,t,e))}return isJWK(n)?n.k?decode(n.k):(privCache||(privCache=new WeakMap),importAndCache(privCache,n,n,e,!0)):n},normalize={normalizePublicKey,normalizePrivateKey};async function importJWK(n,e){if(!isObject(n))throw new TypeError("JWK must be an object");switch(e||(e=n.alg),n.kty){case"oct":if(typeof n.k!="string"||!n.k)throw new TypeError('missing "k" (Key Value) Parameter value');return decode(n.k);case"RSA":if("oth"in n&&n.oth!==void 0)throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return parse({...n,alg:e});default:throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value')}}const tag=n=>n?.[Symbol.toStringTag],jwkMatchesOp=(n,e,t)=>{if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&e.key_ops.includes?.(t)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${t}`);if(e.alg!==void 0&&e.alg!==n)throw new TypeError(`Invalid key for this operation, when present its alg must be ${n}`);return!0},symmetricTypeCheck=(n,e,t,r)=>{if(!(e instanceof Uint8Array)){if(r&&isJWK(e)){if(isSecretJWK(e)&&jwkMatchesOp(n,e,t))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!isKeyLike(e))throw new TypeError(withAlg(n,e,...types,"Uint8Array",r?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${tag(e)} instances for symmetric algorithms must be of type "secret"`)}},asymmetricTypeCheck=(n,e,t,r)=>{if(r&&isJWK(e))switch(t){case"sign":if(isPrivateJWK(e)&&jwkMatchesOp(n,e,t))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(isPublicJWK(e)&&jwkMatchesOp(n,e,t))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!isKeyLike(e))throw new TypeError(withAlg(n,e,...types,r?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${tag(e)} instances for asymmetric algorithms must not be of type "secret"`);if(t==="sign"&&e.type==="public")throw new TypeError(`${tag(e)} instances for asymmetric algorithm signing must be of type "private"`);if(t==="decrypt"&&e.type==="public")throw new TypeError(`${tag(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&t==="verify"&&e.type==="private")throw new TypeError(`${tag(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&t==="encrypt"&&e.type==="private")throw new TypeError(`${tag(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function checkKeyType(n,e,t,r){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?symmetricTypeCheck(e,t,r,n):asymmetricTypeCheck(e,t,r,n)}checkKeyType.bind(void 0,!1);const checkKeyTypeWithJwk=checkKeyType.bind(void 0,!0);function validateCrit(n,e,t,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new n('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(o=>typeof o!="string"||o.length===0))throw new n('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;t!==void 0?s=new Map([...Object.entries(t),...e.entries()]):s=e;for(const o of r.crit){if(!s.has(o))throw new JOSENotSupported(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new n(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&r[o]===void 0)throw new n(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(r.crit)}const validateAlgorithms=(n,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(t=>typeof t!="string")))throw new TypeError(`"${n}" option must be an array of strings`);if(e)return new Set(e)},keyToJWK=async n=>{if(n instanceof Uint8Array)return{kty:"oct",k:encode$1(n)};if(!isCryptoKey(n))throw new TypeError(invalidKeyInput(n,...types,"Uint8Array"));if(!n.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:e,key_ops:t,alg:r,use:i,...s}=await crypto$1.subtle.exportKey("jwk",n);return s};async function exportJWK(n){return keyToJWK(n)}function subtleDsa(n,e){const t=`SHA-${n.slice(-3)}`;switch(n){case"HS256":case"HS384":case"HS512":return{hash:t,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:t,name:"RSA-PSS",saltLength:n.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:t,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:t,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new JOSENotSupported(`alg ${n} is not supported either by JOSE or your javascript runtime`)}}async function getCryptoKey(n,e,t){if(t==="sign"&&(e=await normalize.normalizePrivateKey(e,n)),t==="verify"&&(e=await normalize.normalizePublicKey(e,n)),isCryptoKey(e))return checkSigCryptoKey(e,n,t),e;if(e instanceof Uint8Array){if(!n.startsWith("HS"))throw new TypeError(invalidKeyInput(e,...types));return crypto$1.subtle.importKey("raw",e,{hash:`SHA-${n.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(invalidKeyInput(e,...types,"Uint8Array","JSON Web Key"))}const verify=async(n,e,t,r)=>{const i=await getCryptoKey(n,e,"verify");checkKeyLength(n,i);const s=subtleDsa(n,i.algorithm);try{return await crypto$1.subtle.verify(s,i,t,r)}catch{return!1}};async function flattenedVerify(n,e,t){if(!isObject(n))throw new JWSInvalid("Flattened JWS must be an object");if(n.protected===void 0&&n.header===void 0)throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(n.protected!==void 0&&typeof n.protected!="string")throw new JWSInvalid("JWS Protected Header incorrect type");if(n.payload===void 0)throw new JWSInvalid("JWS Payload missing");if(typeof n.signature!="string")throw new JWSInvalid("JWS Signature missing or incorrect type");if(n.header!==void 0&&!isObject(n.header))throw new JWSInvalid("JWS Unprotected Header incorrect type");let r={};if(n.protected)try{const b=decode(n.protected);r=JSON.parse(decoder.decode(b))}catch{throw new JWSInvalid("JWS Protected Header is invalid")}if(!isDisjoint(r,n.header))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...r,...n.header},s=validateCrit(JWSInvalid,new Map([["b64",!0]]),t?.crit,r,i);let o=!0;if(s.has("b64")&&(o=r.b64,typeof o!="boolean"))throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=i;if(typeof a!="string"||!a)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');const u=t&&validateAlgorithms("algorithms",t.algorithms);if(u&&!u.has(a))throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof n.payload!="string")throw new JWSInvalid("JWS Payload must be a string")}else if(typeof n.payload!="string"&&!(n.payload instanceof Uint8Array))throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof e=="function"?(e=await e(r,n),c=!0,checkKeyTypeWithJwk(a,e,"verify"),isJWK(e)&&(e=await importJWK(e,a))):checkKeyTypeWithJwk(a,e,"verify");const l=concat(encoder.encode(n.protected??""),encoder.encode("."),typeof n.payload=="string"?encoder.encode(n.payload):n.payload);let d;try{d=decode(n.signature)}catch{throw new JWSInvalid("Failed to base64url decode the signature")}if(!await verify(a,e,d,l))throw new JWSSignatureVerificationFailed;let m;if(o)try{m=decode(n.payload)}catch{throw new JWSInvalid("Failed to base64url decode the payload")}else typeof n.payload=="string"?m=encoder.encode(n.payload):m=n.payload;const g={payload:m};return n.protected!==void 0&&(g.protectedHeader=r),n.header!==void 0&&(g.unprotectedHeader=n.header),c?{...g,key:e}:g}async function compactVerify(n,e,t){if(n instanceof Uint8Array&&(n=decoder.decode(n)),typeof n!="string")throw new JWSInvalid("Compact JWS must be a string or Uint8Array");const{0:r,1:i,2:s,length:o}=n.split(".");if(o!==3)throw new JWSInvalid("Invalid Compact JWS");const a=await flattenedVerify({payload:i,protected:r,signature:s},e,t),u={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...u,key:a.key}:u}const epoch=n=>Math.floor(n.getTime()/1e3),minute=60,hour=minute*60,day=hour*24,week=day*7,year=day*365.25,REGEX=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,secs=n=>{const e=REGEX.exec(n);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const t=parseFloat(e[2]),r=e[3].toLowerCase();let i;switch(r){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(t);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(t*minute);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(t*hour);break;case"day":case"days":case"d":i=Math.round(t*day);break;case"week":case"weeks":case"w":i=Math.round(t*week);break;default:i=Math.round(t*year);break}return e[1]==="-"||e[4]==="ago"?-i:i},normalizeTyp=n=>n.toLowerCase().replace(/^application\//,""),checkAudiencePresence=(n,e)=>typeof n=="string"?e.includes(n):Array.isArray(n)?e.some(Set.prototype.has.bind(new Set(n))):!1,jwtPayload=(n,e,t={})=>{let r;try{r=JSON.parse(decoder.decode(e))}catch{}if(!isObject(r))throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");const{typ:i}=t;if(i&&(typeof n.typ!="string"||normalizeTyp(n.typ)!==normalizeTyp(i)))throw new JWTClaimValidationFailed('unexpected "typ" JWT header value',r,"typ","check_failed");const{requiredClaims:s=[],issuer:o,subject:a,audience:u,maxTokenAge:c}=t,l=[...s];c!==void 0&&l.push("iat"),u!==void 0&&l.push("aud"),a!==void 0&&l.push("sub"),o!==void 0&&l.push("iss");for(const g of new Set(l.reverse()))if(!(g in r))throw new JWTClaimValidationFailed(`missing required "${g}" claim`,r,g,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new JWTClaimValidationFailed('unexpected "iss" claim value',r,"iss","check_failed");if(a&&r.sub!==a)throw new JWTClaimValidationFailed('unexpected "sub" claim value',r,"sub","check_failed");if(u&&!checkAudiencePresence(r.aud,typeof u=="string"?[u]:u))throw new JWTClaimValidationFailed('unexpected "aud" claim value',r,"aud","check_failed");let d;switch(typeof t.clockTolerance){case"string":d=secs(t.clockTolerance);break;case"number":d=t.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:f}=t,m=epoch(f||new Date);if((r.iat!==void 0||c)&&typeof r.iat!="number")throw new JWTClaimValidationFailed('"iat" claim must be a number',r,"iat","invalid");if(r.nbf!==void 0){if(typeof r.nbf!="number")throw new JWTClaimValidationFailed('"nbf" claim must be a number',r,"nbf","invalid");if(r.nbf>m+d)throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed',r,"nbf","check_failed")}if(r.exp!==void 0){if(typeof r.exp!="number")throw new JWTClaimValidationFailed('"exp" claim must be a number',r,"exp","invalid");if(r.exp<=m-d)throw new JWTExpired('"exp" claim timestamp check failed',r,"exp","check_failed")}if(c){const g=m-r.iat,b=typeof c=="number"?c:secs(c);if(g-d>b)throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)',r,"iat","check_failed");if(g<0-d)throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',r,"iat","check_failed")}return r};async function jwtVerify(n,e,t){const r=await compactVerify(n,e,t);if(r.protectedHeader.crit?.includes("b64")&&r.protectedHeader.b64===!1)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");const s={payload:jwtPayload(r.protectedHeader,r.payload,t),protectedHeader:r.protectedHeader};return typeof e=="function"?{...s,key:r.key}:s}const sign=async(n,e,t)=>{const r=await getCryptoKey(n,e,"sign");checkKeyLength(n,r);const i=await crypto$1.subtle.sign(subtleDsa(n,r.algorithm),r,t);return new Uint8Array(i)};class FlattenedSign{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!isDisjoint(this._protectedHeader,this._unprotectedHeader))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader},i=validateCrit(JWSInvalid,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r);let s=!0;if(i.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=r;if(typeof o!="string"||!o)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');checkKeyTypeWithJwk(o,e,"sign");let a=this._payload;s&&(a=encoder.encode(encode$1(a)));let u;this._protectedHeader?u=encoder.encode(encode$1(JSON.stringify(this._protectedHeader))):u=encoder.encode("");const c=concat(u,encoder.encode("."),a),l=await sign(o,e,c),d={signature:encode$1(l),payload:""};return s&&(d.payload=decoder.decode(a)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=decoder.decode(u)),d}}class CompactSign{constructor(e){this._flattened=new FlattenedSign(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function validateInput(n,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${n} input`);return e}class ProduceJWT{constructor(e={}){if(!isObject(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:validateInput("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:validateInput("setNotBefore",epoch(e))}:this._payload={...this._payload,nbf:epoch(new Date)+secs(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:validateInput("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:validateInput("setExpirationTime",epoch(e))}:this._payload={...this._payload,exp:epoch(new Date)+secs(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:epoch(new Date)}:e instanceof Date?this._payload={...this._payload,iat:validateInput("setIssuedAt",epoch(e))}:typeof e=="string"?this._payload={...this._payload,iat:validateInput("setIssuedAt",epoch(new Date)+secs(e))}:this._payload={...this._payload,iat:validateInput("setIssuedAt",e)},this}}class SignJWT extends ProduceJWT{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new CompactSign(encoder.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}function getKtyFromAlg(n){switch(typeof n=="string"&&n.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set')}}function isJWKSLike(n){return n&&typeof n=="object"&&Array.isArray(n.keys)&&n.keys.every(isJWKLike)}function isJWKLike(n){return isObject(n)}function clone(n){return typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}class LocalJWKSet{constructor(e){if(this._cached=new WeakMap,!isJWKSLike(e))throw new JWKSInvalid("JSON Web Key Set malformed");this._jwks=clone(e)}async getKey(e,t){const{alg:r,kid:i}={...e,...t?.header},s=getKtyFromAlg(r),o=this._jwks.keys.filter(c=>{let l=s===c.kty;if(l&&typeof i=="string"&&(l=i===c.kid),l&&typeof c.alg=="string"&&(l=r===c.alg),l&&typeof c.use=="string"&&(l=c.use==="sig"),l&&Array.isArray(c.key_ops)&&(l=c.key_ops.includes("verify")),l)switch(r){case"ES256":l=c.crv==="P-256";break;case"ES256K":l=c.crv==="secp256k1";break;case"ES384":l=c.crv==="P-384";break;case"ES512":l=c.crv==="P-521";break;case"Ed25519":l=c.crv==="Ed25519";break;case"EdDSA":l=c.crv==="Ed25519"||c.crv==="Ed448";break}return l}),{0:a,length:u}=o;if(u===0)throw new JWKSNoMatchingKey;if(u!==1){const c=new JWKSMultipleMatchingKeys,{_cached:l}=this;throw c[Symbol.asyncIterator]=async function*(){for(const d of o)try{yield await importWithAlgCache(l,d,r)}catch{}},c}return importWithAlgCache(this._cached,a,r)}}async function importWithAlgCache(n,e,t){const r=n.get(e)||n.set(e,{}).get(e);if(r[t]===void 0){const i=await importJWK({...e,ext:!0},t);if(i instanceof Uint8Array||i.type!=="public")throw new JWKSInvalid("JSON Web Key Set members must be public keys");r[t]=i}return r[t]}function createLocalJWKSet(n){const e=new LocalJWKSet(n),t=async(r,i)=>e.getKey(r,i);return Object.defineProperties(t,{jwks:{value:()=>clone(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),t}const fetchJwks=async(n,e,t)=>{let r,i,s=!1;typeof AbortController=="function"&&(r=new AbortController,i=setTimeout(()=>{s=!0,r.abort()},e));const o=await fetch(n.href,{signal:r?r.signal:void 0,redirect:"manual",headers:t.headers}).catch(a=>{throw s?new JWKSTimeout:a});if(i!==void 0&&clearTimeout(i),o.status!==200)throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function isCloudflareWorkers(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let USER_AGENT;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(USER_AGENT="jose/v5.10.0");const jwksCache=Symbol();function isFreshJwksCache(n,e){return!(typeof n!="object"||n===null||!("uat"in n)||typeof n.uat!="number"||Date.now()-n.uat>=e||!("jwks"in n)||!isObject(n.jwks)||!Array.isArray(n.jwks.keys)||!Array.prototype.every.call(n.jwks.keys,isObject))}class RemoteJWKSet{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:t?.agent,headers:t?.headers},this._timeoutDuration=typeof t?.timeoutDuration=="number"?t?.timeoutDuration:5e3,this._cooldownDuration=typeof t?.cooldownDuration=="number"?t?.cooldownDuration:3e4,this._cacheMaxAge=typeof t?.cacheMaxAge=="number"?t?.cacheMaxAge:6e5,t?.[jwksCache]!==void 0&&(this._cache=t?.[jwksCache],isFreshJwksCache(t?.[jwksCache],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=createLocalJWKSet(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,t){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof JWKSNoMatchingKey&&this.coolingDown()===!1)return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&isCloudflareWorkers()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);USER_AGENT&&!e.has("User-Agent")&&(e.set("User-Agent",USER_AGENT),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=fetchJwks(this._url,this._timeoutDuration,this._options).then(t=>{this._local=createLocalJWKSet(t),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=t),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch}}function createRemoteJWKSet(n,e){const t=new RemoteJWKSet(n,e),r=async(i,s)=>t.getKey(i,s);return Object.defineProperties(r,{coolingDown:{get:()=>t.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>t.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>t.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!t._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>t._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}const encode=encode$1;function getModulusLengthOption(n){const e=n?.modulusLength??2048;if(typeof e!="number"||e<2048)throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function generateKeyPair$1(n,e){let t,r;switch(n){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:getModulusLengthOption(e)},r=["sign","verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:getModulusLengthOption(e)},r=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:getModulusLengthOption(e)},r=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=["sign","verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=["sign","verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=["sign","verify"];break;case"Ed25519":t={name:"Ed25519"},r=["sign","verify"];break;case"EdDSA":{r=["sign","verify"];const i="Ed25519";switch(i){case"Ed25519":case"Ed448":t={name:i};break;default:throw new JOSENotSupported("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{r=["deriveKey","deriveBits"];const i="P-256";switch(i){case"P-256":case"P-384":case"P-521":{t={name:"ECDH",namedCurve:i};break}case"X25519":case"X448":t={name:i};break;default:throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto$1.subtle.generateKey(t,!1,r)}async function generateKeyPair(n,e){return generateKeyPair$1(n,e)}const SOLID_CLIENT_AUTHN_KEY_PREFIX="solidClientAuthn:",PREFERRED_SIGNING_ALG=["ES256","RS256"],EVENTS={ERROR:"error",LOGIN:"login",LOGOUT:"logout",NEW_REFRESH_TOKEN:"newRefreshToken",NEW_TOKENS:"newTokens",AUTHORIZATION_REQUEST:"authorizationRequest",SESSION_EXPIRED:"sessionExpired",SESSION_EXTENDED:"sessionExtended",SESSION_RESTORED:"sessionRestore",TIMEOUT_SET:"timeoutSet"},REFRESH_BEFORE_EXPIRATION_SECONDS=5,SCOPE_OPENID="openid",SCOPE_OFFLINE="offline_access",SCOPE_WEBID="webid",DEFAULT_SCOPES=[SCOPE_OPENID,SCOPE_OFFLINE,SCOPE_WEBID];class AggregateHandler{handleables;constructor(e){this.handleables=e,this.handleables=e}async getProperHandler(e){const t=await Promise.all(this.handleables.map(r=>r.canHandle(...e)));for(let r=0;r<t.length;r+=1)if(t[r])return this.handleables[r];return null}async canHandle(...e){return await this.getProperHandler(e)!==null}async handle(...e){const t=await this.getProperHandler(e);if(t)return t.handle(...e);throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${e.map(r=>{try{return JSON.stringify(r)}catch{return r.toString()}}).join(", ")}`)}}async function getWebidFromTokenPayload(n,e,t,r){let i,s;try{const{payload:o}=await jwtVerify(n,createRemoteJWKSet(new URL(e)),{issuer:t,audience:r});i=o}catch(o){throw new Error(`Token verification failed: ${o.stack}`)}if(typeof i.azp=="string"&&(s=i.azp),typeof i.webid=="string")return{webId:i.webid,clientId:s};if(typeof i.sub!="string")throw new Error(`The token ${JSON.stringify(i)} is invalid: it has no 'webid' claim and no 'sub' claim.`);try{return new URL(i.sub),{webId:i.sub,clientId:s}}catch(o){throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${i.sub}] is invalid as a URL - error [${o}].`)}}function normalizeScopes(n){return Array.isArray(n)?Array.from(new Set([...DEFAULT_SCOPES,...n.filter(e=>typeof e=="string"&&!e.includes(" "))])):DEFAULT_SCOPES}function isValidRedirectUrl(n){try{const e=new URL(n),t=!e.searchParams.has("code")&&!e.searchParams.has("state"),r=e.hash==="";return t&&r}catch{return!1}}function removeOpenIdParams(n){const e=new URL(n);return e.searchParams.delete("state"),e.searchParams.delete("code"),e.searchParams.delete("error"),e.searchParams.delete("error_description"),e.searchParams.delete("iss"),e}function booleanWithFallback(n,e){return typeof n=="boolean"?!!n:!!e}class AuthorizationCodeWithPkceOidcHandlerBase{storageUtility;redirector;constructor(e,t){this.storageUtility=e,this.redirector=t,this.storageUtility=e,this.redirector=t}parametersGuard=e=>e.issuerConfiguration.grantTypesSupported!==void 0&&e.issuerConfiguration.grantTypesSupported.indexOf("authorization_code")>-1&&e.redirectUrl!==void 0;async canHandle(e){return this.parametersGuard(e)}async setupRedirectHandler({oidcLoginOptions:e,state:t,codeVerifier:r,targetUrl:i}){if(!this.parametersGuard(e))throw new Error("The authorization code grant requires a redirectUrl.");await Promise.all([this.storageUtility.setForUser(t,{sessionId:e.sessionId}),this.storageUtility.setForUser(e.sessionId,{codeVerifier:r,issuer:e.issuer.toString(),redirectUrl:e.redirectUrl,dpop:(!!e.dpop).toString(),keepAlive:booleanWithFallback(e.keepAlive,!0).toString()})]),this.redirector.redirect(i,{handleRedirect:e.handleRedirect})}}class GeneralLogoutHandler{sessionInfoManager;constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class IRpLogoutHandler{redirector;constructor(e){this.redirector=e,this.redirector=e}async canHandle(e,t){return t?.logoutType==="idp"}async handle(e,t){if(t?.logoutType!=="idp")throw new Error("Attempting to call idp logout handler to perform app logout");if(t.toLogoutUrl===void 0)throw new Error("Cannot perform IDP logout. Did you log in using the OIDC authentication flow?");this.redirector.redirect(t.toLogoutUrl(t),{handleRedirect:t.handleRedirect})}}class IWaterfallLogoutHandler{handlers;constructor(e,t){this.handlers=[new GeneralLogoutHandler(e),new IRpLogoutHandler(t)]}async canHandle(){return!0}async handle(e,t){for(const r of this.handlers)await r.canHandle(e,t)&&await r.handle(e,t)}}function getUnauthenticatedSession(){return{isLoggedIn:!1,sessionId:v4(),fetch:(...n)=>fetch(...n)}}async function clear$1(n,e){await Promise.all([e.deleteAllUserData(n,{secure:!1}),e.deleteAllUserData(n,{secure:!0})])}class SessionInfoManagerBase{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}update(e,t){throw new Error("Not Implemented")}set(e,t){throw new Error("Not Implemented")}get(e){throw new Error("Not implemented")}async getAll(){throw new Error("Not implemented")}async clear(e){return clear$1(e,this.storageUtility)}async register(e){throw new Error("Not implemented")}async getRegisteredSessionIdAll(){throw new Error("Not implemented")}async clearAll(){throw new Error("Not implemented")}async setOidcContext(e,t){throw new Error("Not implemented")}}function getEndSessionUrl({endSessionEndpoint:n,idTokenHint:e,postLogoutRedirectUri:t,state:r}){const i=new URL(n);return e!==void 0&&i.searchParams.append("id_token_hint",e),t!==void 0&&(i.searchParams.append("post_logout_redirect_uri",t),r!==void 0&&i.searchParams.append("state",r)),i.toString()}function maybeBuildRpInitiatedLogout({endSessionEndpoint:n,idTokenHint:e}){if(n!==void 0)return function({state:r,postLogoutUrl:i}){return getEndSessionUrl({endSessionEndpoint:n,idTokenHint:e,state:r,postLogoutRedirectUri:i})}}function isSupportedTokenType(n){return typeof n=="string"&&["DPoP","Bearer"].includes(n)}function isValidUrl$1(n){try{return new URL(n),!0}catch{return!1}}function determineSigningAlg(n,e){return e.find(t=>n.includes(t))??null}function isStaticClient(n){return n.clientId!==void 0&&!isValidUrl$1(n.clientId)}function isSolidOidcClient(n,e){return e.scopesSupported.includes("webid")&&n.clientId!==void 0&&isValidUrl$1(n.clientId)}function isKnownClientType(n){return typeof n=="string"&&["dynamic","static","solid-oidc"].includes(n)}async function handleRegistration(n,e,t,r){let i;if(isSolidOidcClient(n,e))i={clientId:n.clientId,clientName:n.clientName,clientType:"solid-oidc"};else if(isStaticClient(n))i={clientId:n.clientId,clientSecret:n.clientSecret,clientName:n.clientName,clientType:"static"};else return r.getClient({sessionId:n.sessionId,clientName:n.clientName,redirectUrl:n.redirectUrl},e);const s={clientId:i.clientId,clientType:i.clientType};return i.clientType==="static"&&(s.clientSecret=i.clientSecret),i.clientName&&(s.clientName=i.clientName),await t.setForUser(n.sessionId,s),i}const boundFetch=(n,e)=>fetch(n,e);let ClientAuthentication$1=class{loginHandler;redirectHandler;logoutHandler;sessionInfoManager;issuerConfigFetcher;boundLogout;constructor(e,t,r,i,s){this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=i,this.issuerConfigFetcher=s,this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=i,this.issuerConfigFetcher=s}fetch=boundFetch;logout=async(e,t)=>{await this.logoutHandler.handle(e,t?.logoutType==="idp"?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=boundFetch,delete this.boundLogout};getSessionInfo=async e=>this.sessionInfoManager.get(e);getAllSessionInfo=async()=>this.sessionInfoManager.getAll()};async function loadOidcContextFromStorage(n,e,t){try{const[r,i,s,o,a]=await Promise.all([e.getForUser(n,"issuer",{errorIfNull:!0}),e.getForUser(n,"codeVerifier"),e.getForUser(n,"redirectUrl"),e.getForUser(n,"dpop",{errorIfNull:!0}),e.getForUser(n,"keepAlive")]);await e.deleteForUser(n,"codeVerifier");const u=await t.fetchConfig(r);return{codeVerifier:i,redirectUrl:s,issuerConfig:u,dpop:o==="true",keepAlive:typeof a=="string"?a==="true":!0}}catch(r){throw new Error(`Failed to retrieve OIDC context from storage associated with session [${n}]: ${r}`)}}async function saveSessionInfoToStorage(n,e,t,r,i,s,o,a){t!==void 0&&await n.setForUser(e,{webId:t},{secure:o}),r!==void 0&&await n.setForUser(e,{clientId:r},{secure:o}),await n.setForUser(e,{isLoggedIn:i},{secure:o})}class StorageUtility{secureStorage;insecureStorage;constructor(e,t){this.secureStorage=e,this.insecureStorage=t,this.secureStorage=e,this.insecureStorage=t}getKey(e){return`solidClientAuthenticationUser:${e}`}async getUserData(e,t){const r=await(t?this.secureStorage:this.insecureStorage).get(this.getKey(e));if(r===void 0)return{};try{return JSON.parse(r)}catch{throw new Error(`Data for user [${e}] in [${t?"secure":"unsecure"}] storage is corrupted - expected valid JSON, but got: ${r}`)}}async setUserData(e,t,r){await(r?this.secureStorage:this.insecureStorage).set(this.getKey(e),JSON.stringify(t))}async get(e,t){const r=await(t?.secure?this.secureStorage:this.insecureStorage).get(e);if(r===void 0&&t?.errorIfNull)throw new Error(`[${e}] is not stored`);return r}async set(e,t,r){return(r?.secure?this.secureStorage:this.insecureStorage).set(e,t)}async delete(e,t){return(t?.secure?this.secureStorage:this.insecureStorage).delete(e)}async getForUser(e,t,r){const i=await this.getUserData(e,r?.secure);let s;if((!i||!i[t])&&(s=void 0),s=i[t],s===void 0&&r?.errorIfNull)throw new Error(`Field [${t}] for user [${e}] is not stored`);return s||void 0}async setForUser(e,t,r){let i;try{i=await this.getUserData(e,r?.secure)}catch{i={}}await this.setUserData(e,{...i,...t},r?.secure)}async deleteForUser(e,t,r){const i=await this.getUserData(e,r?.secure);delete i[t],await this.setUserData(e,i,r?.secure)}async deleteAllUserData(e,t){await(t?.secure?this.secureStorage:this.insecureStorage).delete(this.getKey(e))}}class InMemoryStorage{map={};async get(e){return this.map[e]||void 0}async set(e,t){this.map[e]=t}async delete(e){delete this.map[e]}}class ConfigurationError extends Error{constructor(e){super(e)}}class InvalidResponseError extends Error{missingFields;constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class OidcProviderError extends Error{error;errorDescription;constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function normalizeHTU(n){const e=new URL(n);return new URL(e.pathname,e.origin).toString()}async function createDpopHeader(n,e,t,r){return new SignJWT({htu:normalizeHTU(n),htm:e.toUpperCase(),jti:v4(),...r===void 0?{}:{ath:encode(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(r))))}}).setProtectedHeader({alg:PREFERRED_SIGNING_ALG[0],jwk:t.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(t.privateKey,{})}async function generateDpopKeyPair(){const{privateKey:n,publicKey:e}=await generateKeyPair(PREFERRED_SIGNING_ALG[0]),t={privateKey:n,publicKey:await exportJWK(e)};return[t.publicKey.alg]=PREFERRED_SIGNING_ALG,t}const DEFAULT_EXPIRATION_TIME_SECONDS=600;function isExpectedAuthError(n){return[401,403].includes(n)}async function buildDpopFetchOptions(n,e,t,r){const i=new Headers(r?.headers);return i.set("Authorization",`DPoP ${e}`),i.set("DPoP",await createDpopHeader(n,r?.method??"get",t,e)),{...r,headers:i}}async function buildAuthenticatedHeaders(n,e,t,r){if(t!==void 0)return buildDpopFetchOptions(n,e,t,r);const i=new Headers(r?.headers);return i.set("Authorization",`Bearer ${e}`),{...r,headers:i}}async function makeAuthenticatedRequest(n,e,t,r,i=fetch){return i(e,await buildAuthenticatedHeaders(e.toString(),n,r,t))}async function refreshAccessToken(n,e,t){const r=await n.tokenRefresher.refresh(n.sessionId,n.refreshToken,e);return t?.emit(EVENTS.SESSION_EXTENDED,r.expiresIn??DEFAULT_EXPIRATION_TIME_SECONDS),{accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:r.expiresIn}}const computeRefreshDelay=n=>n!==void 0?n-REFRESH_BEFORE_EXPIRATION_SECONDS>0?n-REFRESH_BEFORE_EXPIRATION_SECONDS:n:DEFAULT_EXPIRATION_TIME_SECONDS;function buildAuthenticatedFetch(n,e){let t=n,r=Date.now()+(e?.expiresIn??DEFAULT_EXPIRATION_TIME_SECONDS)*1e3,i,s,o=!1,a,u,c=0;const l=6e4,d=e?.refreshOptions;if(d!==void 0){const f=async()=>o?!1:s||(s=(async()=>{try{const{accessToken:m,refreshToken:g,expiresIn:b}=await refreshAccessToken(d,e.dpopKey,e.eventEmitter);return t=m,r=Date.now()+(b??DEFAULT_EXPIRATION_TIME_SECONDS)*1e3,c=0,g!==void 0&&(d.refreshToken=g),clearTimeout(u),u=setTimeout(f,computeRefreshDelay(b)*1e3),e.eventEmitter?.emit(EVENTS.TIMEOUT_SET,u),!0}catch(m){a=m;const g=m instanceof OidcProviderError&&m.error!=="server_error"&&m.error!=="temporarily_unavailable";g&&(e?.eventEmitter?.emit(EVENTS.ERROR,m.error,m.errorDescription),e?.eventEmitter?.emit(EVENTS.SESSION_EXPIRED));const b=m instanceof InvalidResponseError&&m.missingFields.includes("access_token");if(b&&e?.eventEmitter?.emit(EVENTS.SESSION_EXPIRED),o=g||b,!g&&!b){const S=Math.min(1e3*2**c,l);c+=1,clearTimeout(u),u=setTimeout(f,S),e?.eventEmitter?.emit(EVENTS.TIMEOUT_SET,u)}return!1}})().finally(()=>{s=void 0}),s);i=async()=>{if(!await f())throw a},u=setTimeout(f,computeRefreshDelay(e.expiresIn)*1e3),e.eventEmitter?.emit(EVENTS.TIMEOUT_SET,u)}else if(e!==void 0&&e.eventEmitter!==void 0){const f=setTimeout(()=>{e.eventEmitter.emit(EVENTS.SESSION_EXPIRED)},computeRefreshDelay(e.expiresIn)*1e3);e.eventEmitter.emit(EVENTS.TIMEOUT_SET,f)}return async(f,m)=>{i&&Date.now()>=r&&await i();let g=await makeAuthenticatedRequest(t,f,m,e?.dpopKey,e?.fetch);const b=!g.ok&&!isExpectedAuthError(g.status);return g.ok||b||g.url!==f&&e?.dpopKey!==void 0&&(g=await makeAuthenticatedRequest(t,g.url,m,e.dpopKey,e.fetch)),g}}var eventsExports=requireEvents();const EventEmitter=getDefaultExportFromCjs(eventsExports);var oidcClient_min$1={exports:{}},oidcClient_min=oidcClient_min$1.exports,hasRequiredOidcClient_min;function requireOidcClient_min(){return hasRequiredOidcClient_min||(hasRequiredOidcClient_min=1,(function(n,e){(function(r,i){n.exports=i()})(oidcClient_min,(function(){return(function(t){var r={};function i(s){if(r[s])return r[s].exports;var o=r[s]={i:s,l:!1,exports:{}};return t[s].call(o.exports,o,o.exports,i),o.l=!0,o.exports}return i.m=t,i.c=r,i.d=function(s,o,a){i.o(s,o)||Object.defineProperty(s,o,{enumerable:!0,get:a})},i.r=function(s){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(s,"__esModule",{value:!0})},i.t=function(s,o){if(1&o&&(s=i(s)),8&o||4&o&&typeof s=="object"&&s&&s.__esModule)return s;var a=Object.create(null);if(i.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:s}),2&o&&typeof s!="string")for(var u in s)i.d(a,u,(function(c){return s[c]}).bind(null,u));return a},i.n=function(s){var o=s&&s.__esModule?function(){return s.default}:function(){return s};return i.d(o,"a",o),o},i.o=function(s,o){return Object.prototype.hasOwnProperty.call(s,o)},i.p="",i(i.s=22)})([function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0});var s=(function(){function c(l,d){for(var f=0;f<d.length;f++){var m=d[f];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(l,m.key,m)}}return function(l,d,f){return d&&c(l.prototype,d),f&&c(l,f),l}})(),o={debug:function(){},info:function(){},warn:function(){},error:function(){}},a=void 0,u=void 0;(r.Log=(function(){function c(){(function(d,f){if(!(d instanceof f))throw new TypeError("Cannot call a class as a function")})(this,c)}return c.reset=function(){u=3,a=o},c.debug=function(){if(u>=4){for(var d=arguments.length,f=Array(d),m=0;m<d;m++)f[m]=arguments[m];a.debug.apply(a,Array.from(f))}},c.info=function(){if(u>=3){for(var d=arguments.length,f=Array(d),m=0;m<d;m++)f[m]=arguments[m];a.info.apply(a,Array.from(f))}},c.warn=function(){if(u>=2){for(var d=arguments.length,f=Array(d),m=0;m<d;m++)f[m]=arguments[m];a.warn.apply(a,Array.from(f))}},c.error=function(){if(u>=1){for(var d=arguments.length,f=Array(d),m=0;m<d;m++)f[m]=arguments[m];a.error.apply(a,Array.from(f))}},s(c,null,[{key:"NONE",get:function(){return 0}},{key:"ERROR",get:function(){return 1}},{key:"WARN",get:function(){return 2}},{key:"INFO",get:function(){return 3}},{key:"DEBUG",get:function(){return 4}},{key:"level",get:function(){return u},set:function(d){if(!(0<=d&&d<=4))throw new Error("Invalid log level");u=d}},{key:"logger",get:function(){return a},set:function(d){if(!d.debug&&d.info&&(d.debug=d.info),!(d.debug&&d.info&&d.warn&&d.error))throw new Error("Invalid logger");a=d}}]),c})()).reset()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0});var s=(function(){function c(l,d){for(var f=0;f<d.length;f++){var m=d[f];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(l,m.key,m)}}return function(l,d,f){return d&&c(l.prototype,d),f&&c(l,f),l}})(),o={setInterval:(function(c){function l(d,f){return c.apply(this,arguments)}return l.toString=function(){return c.toString()},l})((function(c,l){return setInterval(c,l)})),clearInterval:(function(c){function l(d){return c.apply(this,arguments)}return l.toString=function(){return c.toString()},l})((function(c){return clearInterval(c)}))},a=!1,u=null;r.Global=(function(){function c(){(function(d,f){if(!(d instanceof f))throw new TypeError("Cannot call a class as a function")})(this,c)}return c._testing=function(){a=!0},c.setXMLHttpRequest=function(d){u=d},s(c,null,[{key:"location",get:function(){if(!a)return location}},{key:"localStorage",get:function(){if(!a&&typeof window<"u")return localStorage}},{key:"sessionStorage",get:function(){if(!a&&typeof window<"u")return sessionStorage}},{key:"XMLHttpRequest",get:function(){if(!a&&typeof window<"u")return u||XMLHttpRequest}},{key:"timer",get:function(){if(!a)return o}}]),c})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.MetadataService=void 0;var s=(function(){function l(d,f){for(var m=0;m<f.length;m++){var g=f[m];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(d,g.key,g)}}return function(d,f,m){return f&&l(d.prototype,f),m&&l(d,m),d}})(),o=i(0),a=i(7);function u(l,d){if(!(l instanceof d))throw new TypeError("Cannot call a class as a function")}var c=".well-known/openid-configuration";r.MetadataService=(function(){function l(d){var f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:a.JsonService;if(u(this,l),!d)throw o.Log.error("MetadataService: No settings passed to MetadataService"),new Error("settings");this._settings=d,this._jsonService=new f(["application/jwk-set+json"])}return l.prototype.resetSigningKeys=function(){this._settings=this._settings||{},this._settings.signingKeys=void 0},l.prototype.getMetadata=function(){var f=this;return this._settings.metadata?(o.Log.debug("MetadataService.getMetadata: Returning metadata from settings"),Promise.resolve(this._settings.metadata)):this.metadataUrl?(o.Log.debug("MetadataService.getMetadata: getting metadata from",this.metadataUrl),this._jsonService.getJson(this.metadataUrl).then((function(m){o.Log.debug("MetadataService.getMetadata: json received");var g=f._settings.metadataSeed||{};return f._settings.metadata=Object.assign({},g,m),f._settings.metadata}))):(o.Log.error("MetadataService.getMetadata: No authority or metadataUrl configured on settings"),Promise.reject(new Error("No authority or metadataUrl configured on settings")))},l.prototype.getIssuer=function(){return this._getMetadataProperty("issuer")},l.prototype.getAuthorizationEndpoint=function(){return this._getMetadataProperty("authorization_endpoint")},l.prototype.getUserInfoEndpoint=function(){return this._getMetadataProperty("userinfo_endpoint")},l.prototype.getTokenEndpoint=function(){var f=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return this._getMetadataProperty("token_endpoint",f)},l.prototype.getCheckSessionIframe=function(){return this._getMetadataProperty("check_session_iframe",!0)},l.prototype.getEndSessionEndpoint=function(){return this._getMetadataProperty("end_session_endpoint",!0)},l.prototype.getRevocationEndpoint=function(){return this._getMetadataProperty("revocation_endpoint",!0)},l.prototype.getKeysEndpoint=function(){return this._getMetadataProperty("jwks_uri",!0)},l.prototype._getMetadataProperty=function(f){var m=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return o.Log.debug("MetadataService.getMetadataProperty for: "+f),this.getMetadata().then((function(g){if(o.Log.debug("MetadataService.getMetadataProperty: metadata recieved"),g[f]===void 0){if(m===!0)return void o.Log.warn("MetadataService.getMetadataProperty: Metadata does not contain optional property "+f);throw o.Log.error("MetadataService.getMetadataProperty: Metadata does not contain property "+f),new Error("Metadata does not contain property "+f)}return g[f]}))},l.prototype.getSigningKeys=function(){var f=this;return this._settings.signingKeys?(o.Log.debug("MetadataService.getSigningKeys: Returning signingKeys from settings"),Promise.resolve(this._settings.signingKeys)):this._getMetadataProperty("jwks_uri").then((function(m){return o.Log.debug("MetadataService.getSigningKeys: jwks_uri received",m),f._jsonService.getJson(m).then((function(g){if(o.Log.debug("MetadataService.getSigningKeys: key set received",g),!g.keys)throw o.Log.error("MetadataService.getSigningKeys: Missing keys on keyset"),new Error("Missing keys on keyset");return f._settings.signingKeys=g.keys,f._settings.signingKeys}))}))},s(l,[{key:"metadataUrl",get:function(){return this._metadataUrl||(this._settings.metadataUrl?this._metadataUrl=this._settings.metadataUrl:(this._metadataUrl=this._settings.authority,this._metadataUrl&&this._metadataUrl.indexOf(c)<0&&(this._metadataUrl[this._metadataUrl.length-1]!=="/"&&(this._metadataUrl+="/"),this._metadataUrl+=c))),this._metadataUrl}}]),l})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.UrlUtility=void 0;var s=i(0),o=i(1);r.UrlUtility=(function(){function a(){(function(c,l){if(!(c instanceof l))throw new TypeError("Cannot call a class as a function")})(this,a)}return a.addQueryParam=function(c,l,d){return c.indexOf("?")<0&&(c+="?"),c[c.length-1]!=="?"&&(c+="&"),c+=encodeURIComponent(l),c+="=",c+=encodeURIComponent(d)},a.parseUrlFragment=function(c){var l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#",d=arguments.length>2&&arguments[2]!==void 0?arguments[2]:o.Global;typeof c!="string"&&(c=d.location.href);var f=c.lastIndexOf(l);f>=0&&(c=c.substr(f+1)),l==="?"&&(f=c.indexOf("#"))>=0&&(c=c.substr(0,f));for(var m,g={},b=/([^&=]+)=([^&]*)/g,S=0;m=b.exec(c);)if(g[decodeURIComponent(m[1])]=decodeURIComponent(m[2].replace(/\+/g," ")),S++>50)return s.Log.error("UrlUtility.parseUrlFragment: response exceeded expected number of parameters",c),{error:"Response exceeded expected number of parameters"};for(var w in g)return g;return{}},a})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.JoseUtil=void 0;var s=i(26),o=(function(u){return u&&u.__esModule?u:{default:u}})(i(33));r.JoseUtil=(0,o.default)({jws:s.jws,KeyUtil:s.KeyUtil,X509:s.X509,crypto:s.crypto,hextob64u:s.hextob64u,b64tohex:s.b64tohex,AllowedSigningAlgs:s.AllowedSigningAlgs})},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.OidcClientSettings=void 0;var s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(w){return typeof w}:function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w},o=(function(){function w(v,_){for(var T=0;T<_.length;T++){var C=_[T];C.enumerable=C.enumerable||!1,C.configurable=!0,"value"in C&&(C.writable=!0),Object.defineProperty(v,C.key,C)}}return function(v,_,T){return _&&w(v.prototype,_),T&&w(v,T),v}})(),a=i(0),u=i(23),c=i(6),l=i(24),d=i(2);function f(w,v){if(!(w instanceof v))throw new TypeError("Cannot call a class as a function")}var m=".well-known/openid-configuration",g="id_token",b="openid",S="client_secret_post";r.OidcClientSettings=(function(){function w(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},_=v.authority,T=v.metadataUrl,C=v.metadata,U=v.signingKeys,$=v.metadataSeed,W=v.client_id,re=v.client_secret,D=v.response_type,V=D===void 0?g:D,he=v.scope,z=he===void 0?b:he,_e=v.redirect_uri,Ce=v.post_logout_redirect_uri,Fe=v.client_authentication,ze=Fe===void 0?S:Fe,ae=v.prompt,ve=v.display,L=v.max_age,ie=v.ui_locales,xe=v.acr_values,ue=v.resource,De=v.response_mode,ke=v.filterProtocolClaims,We=ke===void 0||ke,Oe=v.loadUserInfo,te=Oe===void 0||Oe,le=v.staleStateAge,Te=le===void 0?900:le,G=v.clockSkew,P=G===void 0?300:G,x=v.clockService,A=x===void 0?new u.ClockService:x,O=v.userInfoJwtIssuer,H=O===void 0?"OP":O,Q=v.mergeClaims,de=Q!==void 0&&Q,M=v.stateStore,ne=M===void 0?new c.WebStorageStateStore:M,ge=v.ResponseValidatorCtor,Y=ge===void 0?l.ResponseValidator:ge,Be=v.MetadataServiceCtor,Je=Be===void 0?d.MetadataService:Be,Ne=v.extraQueryParams,Ze=Ne===void 0?{}:Ne,B=v.extraTokenParams,R=B===void 0?{}:B;f(this,w),this._authority=_,this._metadataUrl=T,this._metadata=C,this._metadataSeed=$,this._signingKeys=U,this._client_id=W,this._client_secret=re,this._response_type=V,this._scope=z,this._redirect_uri=_e,this._post_logout_redirect_uri=Ce,this._client_authentication=ze,this._prompt=ae,this._display=ve,this._max_age=L,this._ui_locales=ie,this._acr_values=xe,this._resource=ue,this._response_mode=De,this._filterProtocolClaims=!!We,this._loadUserInfo=!!te,this._staleStateAge=Te,this._clockSkew=P,this._clockService=A,this._userInfoJwtIssuer=H,this._mergeClaims=!!de,this._stateStore=ne,this._validator=new Y(this),this._metadataService=new Je(this),this._extraQueryParams=(Ze===void 0?"undefined":s(Ze))==="object"?Ze:{},this._extraTokenParams=(R===void 0?"undefined":s(R))==="object"?R:{}}return w.prototype.getEpochTime=function(){return this._clockService.getEpochTime()},o(w,[{key:"client_id",get:function(){return this._client_id},set:function(_){if(this._client_id)throw a.Log.error("OidcClientSettings.set_client_id: client_id has already been assigned."),new Error("client_id has already been assigned.");this._client_id=_}},{key:"client_secret",get:function(){return this._client_secret}},{key:"response_type",get:function(){return this._response_type}},{key:"scope",get:function(){return this._scope}},{key:"redirect_uri",get:function(){return this._redirect_uri}},{key:"post_logout_redirect_uri",get:function(){return this._post_logout_redirect_uri}},{key:"client_authentication",get:function(){return this._client_authentication}},{key:"prompt",get:function(){return this._prompt}},{key:"display",get:function(){return this._display}},{key:"max_age",get:function(){return this._max_age}},{key:"ui_locales",get:function(){return this._ui_locales}},{key:"acr_values",get:function(){return this._acr_values}},{key:"resource",get:function(){return this._resource}},{key:"response_mode",get:function(){return this._response_mode}},{key:"authority",get:function(){return this._authority},set:function(_){if(this._authority)throw a.Log.error("OidcClientSettings.set_authority: authority has already been assigned."),new Error("authority has already been assigned.");this._authority=_}},{key:"metadataUrl",get:function(){return this._metadataUrl||(this._metadataUrl=this.authority,this._metadataUrl&&this._metadataUrl.indexOf(m)<0&&(this._metadataUrl[this._metadataUrl.length-1]!=="/"&&(this._metadataUrl+="/"),this._metadataUrl+=m)),this._metadataUrl}},{key:"metadata",get:function(){return this._metadata},set:function(_){this._metadata=_}},{key:"metadataSeed",get:function(){return this._metadataSeed},set:function(_){this._metadataSeed=_}},{key:"signingKeys",get:function(){return this._signingKeys},set:function(_){this._signingKeys=_}},{key:"filterProtocolClaims",get:function(){return this._filterProtocolClaims}},{key:"loadUserInfo",get:function(){return this._loadUserInfo}},{key:"staleStateAge",get:function(){return this._staleStateAge}},{key:"clockSkew",get:function(){return this._clockSkew}},{key:"userInfoJwtIssuer",get:function(){return this._userInfoJwtIssuer}},{key:"mergeClaims",get:function(){return this._mergeClaims}},{key:"stateStore",get:function(){return this._stateStore}},{key:"validator",get:function(){return this._validator}},{key:"metadataService",get:function(){return this._metadataService}},{key:"extraQueryParams",get:function(){return this._extraQueryParams},set:function(_){(_===void 0?"undefined":s(_))==="object"?this._extraQueryParams=_:this._extraQueryParams={}}},{key:"extraTokenParams",get:function(){return this._extraTokenParams},set:function(_){(_===void 0?"undefined":s(_))==="object"?this._extraTokenParams=_:this._extraTokenParams={}}}]),w})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.WebStorageStateStore=void 0;var s=i(0),o=i(1);function a(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")}r.WebStorageStateStore=(function(){function u(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},l=c.prefix,d=l===void 0?"oidc.":l,f=c.store,m=f===void 0?o.Global.localStorage:f;a(this,u),this._store=m,this._prefix=d}return u.prototype.set=function(l,d){return s.Log.debug("WebStorageStateStore.set",l),l=this._prefix+l,this._store.setItem(l,d),Promise.resolve()},u.prototype.get=function(l){s.Log.debug("WebStorageStateStore.get",l),l=this._prefix+l;var d=this._store.getItem(l);return Promise.resolve(d)},u.prototype.remove=function(l){s.Log.debug("WebStorageStateStore.remove",l),l=this._prefix+l;var d=this._store.getItem(l);return this._store.removeItem(l),Promise.resolve(d)},u.prototype.getAllKeys=function(){s.Log.debug("WebStorageStateStore.getAllKeys");for(var l=[],d=0;d<this._store.length;d++){var f=this._store.key(d);f.indexOf(this._prefix)===0&&l.push(f.substr(this._prefix.length))}return Promise.resolve(l)},u})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.JsonService=void 0;var s=i(0),o=i(1);function a(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")}r.JsonService=(function(){function u(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:o.Global.XMLHttpRequest,d=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;a(this,u),c&&Array.isArray(c)?this._contentTypes=c.slice():this._contentTypes=[],this._contentTypes.push("application/json"),d&&this._contentTypes.push("application/jwt"),this._XMLHttpRequest=l,this._jwtHandler=d}return u.prototype.getJson=function(l,d){var f=this;if(!l)throw s.Log.error("JsonService.getJson: No url passed"),new Error("url");return s.Log.debug("JsonService.getJson, url: ",l),new Promise((function(m,g){var b=new f._XMLHttpRequest;b.open("GET",l);var S=f._contentTypes,w=f._jwtHandler;b.onload=function(){if(s.Log.debug("JsonService.getJson: HTTP response received, status",b.status),b.status===200){var v=b.getResponseHeader("Content-Type");if(v){var _=S.find((function(T){if(v.startsWith(T))return!0}));if(_=="application/jwt")return void w(b).then(m,g);if(_)try{return void m(JSON.parse(b.responseText))}catch(T){return s.Log.error("JsonService.getJson: Error parsing JSON response",T.message),void g(T)}}g(Error("Invalid response Content-Type: "+v+", from URL: "+l))}else g(Error(b.statusText+" ("+b.status+")"))},b.onerror=function(){s.Log.error("JsonService.getJson: network error"),g(Error("Network Error"))},d&&(s.Log.debug("JsonService.getJson: token passed, setting Authorization header"),b.setRequestHeader("Authorization","Bearer "+d)),b.send()}))},u.prototype.postForm=function(l,d,f){var m=this;if(!l)throw s.Log.error("JsonService.postForm: No url passed"),new Error("url");return s.Log.debug("JsonService.postForm, url: ",l),new Promise((function(g,b){var S=new m._XMLHttpRequest;S.open("POST",l);var w=m._contentTypes;S.onload=function(){if(s.Log.debug("JsonService.postForm: HTTP response received, status",S.status),S.status!==200){if(S.status===400&&(U=S.getResponseHeader("Content-Type"))&&w.find((function($){if(U.startsWith($))return!0})))try{var C=JSON.parse(S.responseText);if(C&&C.error)return s.Log.error("JsonService.postForm: Error from server: ",C.error),void b(new Error(C.error))}catch($){return s.Log.error("JsonService.postForm: Error parsing JSON response",$.message),void b($)}b(Error(S.statusText+" ("+S.status+")"))}else{var U;if((U=S.getResponseHeader("Content-Type"))&&w.find((function($){if(U.startsWith($))return!0})))try{return void g(JSON.parse(S.responseText))}catch($){return s.Log.error("JsonService.postForm: Error parsing JSON response",$.message),void b($)}b(Error("Invalid response Content-Type: "+U+", from URL: "+l))}},S.onerror=function(){s.Log.error("JsonService.postForm: network error"),b(Error("Network Error"))};var v="";for(var _ in d){var T=d[_];T&&(v.length>0&&(v+="&"),v+=encodeURIComponent(_),v+="=",v+=encodeURIComponent(T))}S.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),f!==void 0&&S.setRequestHeader("Authorization","Basic "+btoa(f)),S.send(v)}))},u})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.SigninRequest=void 0;var s=i(0),o=i(3),a=i(13);r.SigninRequest=(function(){function u(c){var l=c.url,d=c.client_id,f=c.redirect_uri,m=c.response_type,g=c.scope,b=c.authority,S=c.data,w=c.prompt,v=c.display,_=c.max_age,T=c.ui_locales,C=c.id_token_hint,U=c.login_hint,$=c.acr_values,W=c.resource,re=c.response_mode,D=c.request,V=c.request_uri,he=c.extraQueryParams,z=c.request_type,_e=c.client_secret,Ce=c.extraTokenParams,Fe=c.skipUserInfo;if((function(ue,De){if(!(ue instanceof De))throw new TypeError("Cannot call a class as a function")})(this,u),!l)throw s.Log.error("SigninRequest.ctor: No url passed"),new Error("url");if(!d)throw s.Log.error("SigninRequest.ctor: No client_id passed"),new Error("client_id");if(!f)throw s.Log.error("SigninRequest.ctor: No redirect_uri passed"),new Error("redirect_uri");if(!m)throw s.Log.error("SigninRequest.ctor: No response_type passed"),new Error("response_type");if(!g)throw s.Log.error("SigninRequest.ctor: No scope passed"),new Error("scope");if(!b)throw s.Log.error("SigninRequest.ctor: No authority passed"),new Error("authority");var ze=u.isOidc(m),ae=u.isCode(m);re||(re=u.isCode(m)?"query":null),this.state=new a.SigninState({nonce:ze,data:S,client_id:d,authority:b,redirect_uri:f,code_verifier:ae,request_type:z,response_mode:re,client_secret:_e,scope:g,extraTokenParams:Ce,skipUserInfo:Fe}),l=o.UrlUtility.addQueryParam(l,"client_id",d),l=o.UrlUtility.addQueryParam(l,"redirect_uri",f),l=o.UrlUtility.addQueryParam(l,"response_type",m),l=o.UrlUtility.addQueryParam(l,"scope",g),l=o.UrlUtility.addQueryParam(l,"state",this.state.id),ze&&(l=o.UrlUtility.addQueryParam(l,"nonce",this.state.nonce)),ae&&(l=o.UrlUtility.addQueryParam(l,"code_challenge",this.state.code_challenge),l=o.UrlUtility.addQueryParam(l,"code_challenge_method","S256"));var ve={prompt:w,display:v,max_age:_,ui_locales:T,id_token_hint:C,login_hint:U,acr_values:$,resource:W,request:D,request_uri:V,response_mode:re};for(var L in ve)ve[L]&&(l=o.UrlUtility.addQueryParam(l,L,ve[L]));for(var ie in he)l=o.UrlUtility.addQueryParam(l,ie,he[ie]);this.url=l}return u.isOidc=function(l){return!!l.split(/\s+/g).filter((function(d){return d==="id_token"}))[0]},u.isOAuth=function(l){return!!l.split(/\s+/g).filter((function(d){return d==="token"}))[0]},u.isCode=function(l){return!!l.split(/\s+/g).filter((function(d){return d==="code"}))[0]},u})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.State=void 0;var s=(function(){function c(l,d){for(var f=0;f<d.length;f++){var m=d[f];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(l,m.key,m)}}return function(l,d,f){return d&&c(l.prototype,d),f&&c(l,f),l}})(),o=i(0),a=(function(l){return l&&l.__esModule?l:{default:l}})(i(14));function u(c,l){if(!(c instanceof l))throw new TypeError("Cannot call a class as a function")}r.State=(function(){function c(){var l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},d=l.id,f=l.data,m=l.created,g=l.request_type;u(this,c),this._id=d||(0,a.default)(),this._data=f,this._created=typeof m=="number"&&m>0?m:parseInt(Date.now()/1e3),this._request_type=g}return c.prototype.toStorageString=function(){return o.Log.debug("State.toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})},c.fromStorageString=function(d){return o.Log.debug("State.fromStorageString"),new c(JSON.parse(d))},c.clearStaleState=function(d,f){var m=Date.now()/1e3-f;return d.getAllKeys().then((function(g){o.Log.debug("State.clearStaleState: got keys",g);for(var b=[],S=function(T){var C=g[T];v=d.get(C).then((function(U){var $=!1;if(U)try{var W=c.fromStorageString(U);o.Log.debug("State.clearStaleState: got item from key: ",C,W.created),W.created<=m&&($=!0)}catch(re){o.Log.error("State.clearStaleState: Error parsing state for key",C,re.message),$=!0}else o.Log.debug("State.clearStaleState: no item in storage for key: ",C),$=!0;if($)return o.Log.debug("State.clearStaleState: removed item for key: ",C),d.remove(C)})),b.push(v)},w=0;w<g.length;w++){var v;S(w)}return o.Log.debug("State.clearStaleState: waiting on promise count:",b.length),Promise.all(b)}))},s(c,[{key:"id",get:function(){return this._id}},{key:"data",get:function(){return this._data}},{key:"created",get:function(){return this._created}},{key:"request_type",get:function(){return this._request_type}}]),c})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.OidcClient=void 0;var s=(function(){function S(w,v){for(var _=0;_<v.length;_++){var T=v[_];T.enumerable=T.enumerable||!1,T.configurable=!0,"value"in T&&(T.writable=!0),Object.defineProperty(w,T.key,T)}}return function(w,v,_){return v&&S(w.prototype,v),_&&S(w,_),w}})(),o=i(0),a=i(5),u=i(12),c=i(8),l=i(34),d=i(35),f=i(36),m=i(13),g=i(9);function b(S,w){if(!(S instanceof w))throw new TypeError("Cannot call a class as a function")}r.OidcClient=(function(){function S(){var w=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};b(this,S),w instanceof a.OidcClientSettings?this._settings=w:this._settings=new a.OidcClientSettings(w)}return S.prototype.createSigninRequest=function(){var v=this,_=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},T=_.response_type,C=_.scope,U=_.redirect_uri,$=_.data,W=_.state,re=_.prompt,D=_.display,V=_.max_age,he=_.ui_locales,z=_.id_token_hint,_e=_.login_hint,Ce=_.acr_values,Fe=_.resource,ze=_.request,ae=_.request_uri,ve=_.response_mode,L=_.extraQueryParams,ie=_.extraTokenParams,xe=_.request_type,ue=_.skipUserInfo,De=arguments[1];o.Log.debug("OidcClient.createSigninRequest");var ke=this._settings.client_id;T=T||this._settings.response_type,C=C||this._settings.scope,U=U||this._settings.redirect_uri,re=re||this._settings.prompt,D=D||this._settings.display,V=V||this._settings.max_age,he=he||this._settings.ui_locales,Ce=Ce||this._settings.acr_values,Fe=Fe||this._settings.resource,ve=ve||this._settings.response_mode,L=L||this._settings.extraQueryParams,ie=ie||this._settings.extraTokenParams;var We=this._settings.authority;return c.SigninRequest.isCode(T)&&T!=="code"?Promise.reject(new Error("OpenID Connect hybrid flow is not supported")):this._metadataService.getAuthorizationEndpoint().then((function(Oe){o.Log.debug("OidcClient.createSigninRequest: Received authorization endpoint",Oe);var te=new c.SigninRequest({url:Oe,client_id:ke,redirect_uri:U,response_type:T,scope:C,data:$||W,authority:We,prompt:re,display:D,max_age:V,ui_locales:he,id_token_hint:z,login_hint:_e,acr_values:Ce,resource:Fe,request:ze,request_uri:ae,extraQueryParams:L,extraTokenParams:ie,request_type:xe,response_mode:ve,client_secret:v._settings.client_secret,skipUserInfo:ue}),le=te.state;return(De=De||v._stateStore).set(le.id,le.toStorageString()).then((function(){return te}))}))},S.prototype.readSigninResponseState=function(v,_){var T=arguments.length>2&&arguments[2]!==void 0&&arguments[2];o.Log.debug("OidcClient.readSigninResponseState");var C=this._settings.response_mode==="query"||!this._settings.response_mode&&c.SigninRequest.isCode(this._settings.response_type),U=C?"?":"#",$=new l.SigninResponse(v,U);if(!$.state)return o.Log.error("OidcClient.readSigninResponseState: No state in response"),Promise.reject(new Error("No state in response"));_=_||this._stateStore;var W=T?_.remove.bind(_):_.get.bind(_);return W($.state).then((function(re){if(!re)throw o.Log.error("OidcClient.readSigninResponseState: No matching state found in storage"),new Error("No matching state found in storage");return{state:m.SigninState.fromStorageString(re),response:$}}))},S.prototype.processSigninResponse=function(v,_){var T=this;return o.Log.debug("OidcClient.processSigninResponse"),this.readSigninResponseState(v,_,!0).then((function(C){var U=C.state,$=C.response;return o.Log.debug("OidcClient.processSigninResponse: Received state from storage; validating response"),T._validator.validateSigninResponse(U,$)}))},S.prototype.createSignoutRequest=function(){var v=this,_=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},T=_.id_token_hint,C=_.data,U=_.state,$=_.post_logout_redirect_uri,W=_.extraQueryParams,re=_.request_type,D=arguments[1];return o.Log.debug("OidcClient.createSignoutRequest"),$=$||this._settings.post_logout_redirect_uri,W=W||this._settings.extraQueryParams,this._metadataService.getEndSessionEndpoint().then((function(V){if(!V)throw o.Log.error("OidcClient.createSignoutRequest: No end session endpoint url returned"),new Error("no end session endpoint");o.Log.debug("OidcClient.createSignoutRequest: Received end session endpoint",V);var he=new d.SignoutRequest({url:V,id_token_hint:T,post_logout_redirect_uri:$,data:C||U,extraQueryParams:W,request_type:re}),z=he.state;return z&&(o.Log.debug("OidcClient.createSignoutRequest: Signout request has state to persist"),(D=D||v._stateStore).set(z.id,z.toStorageString())),he}))},S.prototype.readSignoutResponseState=function(v,_){var T=arguments.length>2&&arguments[2]!==void 0&&arguments[2];o.Log.debug("OidcClient.readSignoutResponseState");var C=new f.SignoutResponse(v);if(!C.state)return o.Log.debug("OidcClient.readSignoutResponseState: No state in response"),C.error?(o.Log.warn("OidcClient.readSignoutResponseState: Response was error: ",C.error),Promise.reject(new u.ErrorResponse(C))):Promise.resolve({state:void 0,response:C});var U=C.state;_=_||this._stateStore;var $=T?_.remove.bind(_):_.get.bind(_);return $(U).then((function(W){if(!W)throw o.Log.error("OidcClient.readSignoutResponseState: No matching state found in storage"),new Error("No matching state found in storage");return{state:g.State.fromStorageString(W),response:C}}))},S.prototype.processSignoutResponse=function(v,_){var T=this;return o.Log.debug("OidcClient.processSignoutResponse"),this.readSignoutResponseState(v,_,!0).then((function(C){var U=C.state,$=C.response;return U?(o.Log.debug("OidcClient.processSignoutResponse: Received state from storage; validating response"),T._validator.validateSignoutResponse(U,$)):(o.Log.debug("OidcClient.processSignoutResponse: No state from storage; skipping validating response"),$)}))},S.prototype.clearStaleState=function(v){return o.Log.debug("OidcClient.clearStaleState"),v=v||this._stateStore,g.State.clearStaleState(v,this.settings.staleStateAge)},s(S,[{key:"_stateStore",get:function(){return this.settings.stateStore}},{key:"_validator",get:function(){return this.settings.validator}},{key:"_metadataService",get:function(){return this.settings.metadataService}},{key:"settings",get:function(){return this._settings}},{key:"metadataService",get:function(){return this._metadataService}}]),S})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.TokenClient=void 0;var s=i(7),o=i(2),a=i(0);function u(c,l){if(!(c instanceof l))throw new TypeError("Cannot call a class as a function")}r.TokenClient=(function(){function c(l){var d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:s.JsonService,f=arguments.length>2&&arguments[2]!==void 0?arguments[2]:o.MetadataService;if(u(this,c),!l)throw a.Log.error("TokenClient.ctor: No settings passed"),new Error("settings");this._settings=l,this._jsonService=new d,this._metadataService=new f(this._settings)}return c.prototype.exchangeCode=function(){var d=this,f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(f=Object.assign({},f)).grant_type=f.grant_type||"authorization_code",f.client_id=f.client_id||this._settings.client_id,f.client_secret=f.client_secret||this._settings.client_secret,f.redirect_uri=f.redirect_uri||this._settings.redirect_uri;var m=void 0,g=f._client_authentication||this._settings._client_authentication;return delete f._client_authentication,f.code?f.redirect_uri?f.code_verifier?f.client_id?f.client_secret||g!="client_secret_basic"?(g=="client_secret_basic"&&(m=f.client_id+":"+f.client_secret,delete f.client_id,delete f.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(b){return a.Log.debug("TokenClient.exchangeCode: Received token endpoint"),d._jsonService.postForm(b,f,m).then((function(S){return a.Log.debug("TokenClient.exchangeCode: response received"),S}))}))):(a.Log.error("TokenClient.exchangeCode: No client_secret passed"),Promise.reject(new Error("A client_secret is required"))):(a.Log.error("TokenClient.exchangeCode: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(a.Log.error("TokenClient.exchangeCode: No code_verifier passed"),Promise.reject(new Error("A code_verifier is required"))):(a.Log.error("TokenClient.exchangeCode: No redirect_uri passed"),Promise.reject(new Error("A redirect_uri is required"))):(a.Log.error("TokenClient.exchangeCode: No code passed"),Promise.reject(new Error("A code is required")))},c.prototype.exchangeRefreshToken=function(){var d=this,f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(f=Object.assign({},f)).grant_type=f.grant_type||"refresh_token",f.client_id=f.client_id||this._settings.client_id,f.client_secret=f.client_secret||this._settings.client_secret;var m=void 0,g=f._client_authentication||this._settings._client_authentication;return delete f._client_authentication,f.refresh_token?f.client_id?(g=="client_secret_basic"&&(m=f.client_id+":"+f.client_secret,delete f.client_id,delete f.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(b){return a.Log.debug("TokenClient.exchangeRefreshToken: Received token endpoint"),d._jsonService.postForm(b,f,m).then((function(S){return a.Log.debug("TokenClient.exchangeRefreshToken: response received"),S}))}))):(a.Log.error("TokenClient.exchangeRefreshToken: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(a.Log.error("TokenClient.exchangeRefreshToken: No refresh_token passed"),Promise.reject(new Error("A refresh_token is required")))},c})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.ErrorResponse=void 0;var s=i(0);function o(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")}function a(u,c){if(!u)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!c||typeof c!="object"&&typeof c!="function"?u:c}r.ErrorResponse=(function(u){function c(){var l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},d=l.error,f=l.error_description,m=l.error_uri,g=l.state,b=l.session_state;if(o(this,c),!d)throw s.Log.error("No error passed to ErrorResponse"),new Error("error");var S=a(this,u.call(this,f||d));return S.name="ErrorResponse",S.error=d,S.error_description=f,S.error_uri=m,S.state=g,S.session_state=b,S}return(function(d,f){if(typeof f!="function"&&f!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof f);d.prototype=Object.create(f&&f.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),f&&(Object.setPrototypeOf?Object.setPrototypeOf(d,f):d.__proto__=f)})(c,u),c})(Error)},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.SigninState=void 0;var s=(function(){function f(m,g){for(var b=0;b<g.length;b++){var S=g[b];S.enumerable=S.enumerable||!1,S.configurable=!0,"value"in S&&(S.writable=!0),Object.defineProperty(m,S.key,S)}}return function(m,g,b){return g&&f(m.prototype,g),b&&f(m,b),m}})(),o=i(0),a=i(9),u=i(4),c=(function(m){return m&&m.__esModule?m:{default:m}})(i(14));function l(f,m){if(!(f instanceof m))throw new TypeError("Cannot call a class as a function")}function d(f,m){if(!f)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!m||typeof m!="object"&&typeof m!="function"?f:m}r.SigninState=(function(f){function m(){var g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},b=g.nonce,S=g.authority,w=g.client_id,v=g.redirect_uri,_=g.code_verifier,T=g.response_mode,C=g.client_secret,U=g.scope,$=g.extraTokenParams,W=g.skipUserInfo;l(this,m);var re=d(this,f.call(this,arguments[0]));if(b===!0?re._nonce=(0,c.default)():b&&(re._nonce=b),_===!0?re._code_verifier=(0,c.default)()+(0,c.default)()+(0,c.default)():_&&(re._code_verifier=_),re.code_verifier){var D=u.JoseUtil.hashString(re.code_verifier,"SHA256");re._code_challenge=u.JoseUtil.hexToBase64Url(D)}return re._redirect_uri=v,re._authority=S,re._client_id=w,re._response_mode=T,re._client_secret=C,re._scope=U,re._extraTokenParams=$,re._skipUserInfo=W,re}return(function(b,S){if(typeof S!="function"&&S!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof S);b.prototype=Object.create(S&&S.prototype,{constructor:{value:b,enumerable:!1,writable:!0,configurable:!0}}),S&&(Object.setPrototypeOf?Object.setPrototypeOf(b,S):b.__proto__=S)})(m,f),m.prototype.toStorageString=function(){return o.Log.debug("SigninState.toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,nonce:this.nonce,code_verifier:this.code_verifier,redirect_uri:this.redirect_uri,authority:this.authority,client_id:this.client_id,response_mode:this.response_mode,client_secret:this.client_secret,scope:this.scope,extraTokenParams:this.extraTokenParams,skipUserInfo:this.skipUserInfo})},m.fromStorageString=function(b){return o.Log.debug("SigninState.fromStorageString"),new m(JSON.parse(b))},s(m,[{key:"nonce",get:function(){return this._nonce}},{key:"authority",get:function(){return this._authority}},{key:"client_id",get:function(){return this._client_id}},{key:"redirect_uri",get:function(){return this._redirect_uri}},{key:"code_verifier",get:function(){return this._code_verifier}},{key:"code_challenge",get:function(){return this._code_challenge}},{key:"response_mode",get:function(){return this._response_mode}},{key:"client_secret",get:function(){return this._client_secret}},{key:"scope",get:function(){return this._scope}},{key:"extraTokenParams",get:function(){return this._extraTokenParams}},{key:"skipUserInfo",get:function(){return this._skipUserInfo}}]),m})(a.State)},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(){return(s!="undefined"&&s!==null&&s.getRandomValues!==void 0?o:a)().replace(/-/g,"")};var s=typeof window<"u"?window.crypto||window.msCrypto:null;function o(){return("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,(function(u){return(u^s.getRandomValues(new Uint8Array(1))[0]&15>>u/4).toString(16)}))}function a(){return("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,(function(u){return(u^16*Math.random()>>u/4).toString(16)}))}t.exports=r.default},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.User=void 0;var s=(function(){function a(u,c){for(var l=0;l<c.length;l++){var d=c[l];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(u,d.key,d)}}return function(u,c,l){return c&&a(u.prototype,c),l&&a(u,l),u}})(),o=i(0);r.User=(function(){function a(u){var c=u.id_token,l=u.session_state,d=u.access_token,f=u.refresh_token,m=u.token_type,g=u.scope,b=u.profile,S=u.expires_at,w=u.state;(function(_,T){if(!(_ instanceof T))throw new TypeError("Cannot call a class as a function")})(this,a),this.id_token=c,this.session_state=l,this.access_token=d,this.refresh_token=f,this.token_type=m,this.scope=g,this.profile=b,this.expires_at=S,this.state=w}return a.prototype.toStorageString=function(){return o.Log.debug("User.toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})},a.fromStorageString=function(c){return o.Log.debug("User.fromStorageString"),new a(JSON.parse(c))},s(a,[{key:"expires_in",get:function(){if(this.expires_at){var c=parseInt(Date.now()/1e3);return this.expires_at-c}},set:function(c){var l=parseInt(c);if(typeof l=="number"&&l>0){var d=parseInt(Date.now()/1e3);this.expires_at=d+l}}},{key:"expired",get:function(){var c=this.expires_in;if(c!==void 0)return c<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}}]),a})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.AccessTokenEvents=void 0;var s=i(0),o=i(46);function a(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")}r.AccessTokenEvents=(function(){function u(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},l=c.accessTokenExpiringNotificationTime,d=l===void 0?60:l,f=c.accessTokenExpiringTimer,m=f===void 0?new o.Timer("Access token expiring"):f,g=c.accessTokenExpiredTimer,b=g===void 0?new o.Timer("Access token expired"):g;a(this,u),this._accessTokenExpiringNotificationTime=d,this._accessTokenExpiring=m,this._accessTokenExpired=b}return u.prototype.load=function(l){if(l.access_token&&l.expires_in!==void 0){var d=l.expires_in;if(s.Log.debug("AccessTokenEvents.load: access token present, remaining duration:",d),d>0){var f=d-this._accessTokenExpiringNotificationTime;f<=0&&(f=1),s.Log.debug("AccessTokenEvents.load: registering expiring timer in:",f),this._accessTokenExpiring.init(f)}else s.Log.debug("AccessTokenEvents.load: canceling existing expiring timer becase we're past expiration."),this._accessTokenExpiring.cancel();var m=d+1;s.Log.debug("AccessTokenEvents.load: registering expired timer in:",m),this._accessTokenExpired.init(m)}else this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},u.prototype.unload=function(){s.Log.debug("AccessTokenEvents.unload: canceling existing access token timers"),this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},u.prototype.addAccessTokenExpiring=function(l){this._accessTokenExpiring.addHandler(l)},u.prototype.removeAccessTokenExpiring=function(l){this._accessTokenExpiring.removeHandler(l)},u.prototype.addAccessTokenExpired=function(l){this._accessTokenExpired.addHandler(l)},u.prototype.removeAccessTokenExpired=function(l){this._accessTokenExpired.removeHandler(l)},u})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.Event=void 0;var s=i(0);r.Event=(function(){function o(a){(function(c,l){if(!(c instanceof l))throw new TypeError("Cannot call a class as a function")})(this,o),this._name=a,this._callbacks=[]}return o.prototype.addHandler=function(u){this._callbacks.push(u)},o.prototype.removeHandler=function(u){var c=this._callbacks.findIndex((function(l){return l===u}));c>=0&&this._callbacks.splice(c,1)},o.prototype.raise=function(){s.Log.debug("Event: Raising event: "+this._name);for(var u=0;u<this._callbacks.length;u++){var c;(c=this._callbacks)[u].apply(c,arguments)}},o})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.SessionMonitor=void 0;var s=(function(){function l(d,f){for(var m=0;m<f.length;m++){var g=f[m];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(d,g.key,g)}}return function(d,f,m){return f&&l(d.prototype,f),m&&l(d,m),d}})(),o=i(0),a=i(19),u=i(1);function c(l,d){if(!(l instanceof d))throw new TypeError("Cannot call a class as a function")}r.SessionMonitor=(function(){function l(d){var f=this,m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:a.CheckSessionIFrame,g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:u.Global.timer;if(c(this,l),!d)throw o.Log.error("SessionMonitor.ctor: No user manager passed to SessionMonitor"),new Error("userManager");this._userManager=d,this._CheckSessionIFrameCtor=m,this._timer=g,this._userManager.events.addUserLoaded(this._start.bind(this)),this._userManager.events.addUserUnloaded(this._stop.bind(this)),Promise.resolve(this._userManager.getUser().then((function(b){b?f._start(b):f._settings.monitorAnonymousSession&&f._userManager.querySessionStatus().then((function(S){var w={session_state:S.session_state};S.sub&&S.sid&&(w.profile={sub:S.sub,sid:S.sid}),f._start(w)})).catch((function(S){o.Log.error("SessionMonitor ctor: error from querySessionStatus:",S.message)}))})).catch((function(b){o.Log.error("SessionMonitor ctor: error from getUser:",b.message)})))}return l.prototype._start=function(f){var m=this,g=f.session_state;g&&(f.profile?(this._sub=f.profile.sub,this._sid=f.profile.sid,o.Log.debug("SessionMonitor._start: session_state:",g,", sub:",this._sub)):(this._sub=void 0,this._sid=void 0,o.Log.debug("SessionMonitor._start: session_state:",g,", anonymous user")),this._checkSessionIFrame?this._checkSessionIFrame.start(g):this._metadataService.getCheckSessionIframe().then((function(b){if(b){o.Log.debug("SessionMonitor._start: Initializing check session iframe");var S=m._client_id,w=m._checkSessionInterval,v=m._stopCheckSessionOnError;m._checkSessionIFrame=new m._CheckSessionIFrameCtor(m._callback.bind(m),S,b,w,v),m._checkSessionIFrame.load().then((function(){m._checkSessionIFrame.start(g)}))}else o.Log.warn("SessionMonitor._start: No check session iframe found in the metadata")})).catch((function(b){o.Log.error("SessionMonitor._start: Error from getCheckSessionIframe:",b.message)})))},l.prototype._stop=function(){var f=this;if(this._sub=void 0,this._sid=void 0,this._checkSessionIFrame&&(o.Log.debug("SessionMonitor._stop"),this._checkSessionIFrame.stop()),this._settings.monitorAnonymousSession)var m=this._timer.setInterval((function(){f._timer.clearInterval(m),f._userManager.querySessionStatus().then((function(g){var b={session_state:g.session_state};g.sub&&g.sid&&(b.profile={sub:g.sub,sid:g.sid}),f._start(b)})).catch((function(g){o.Log.error("SessionMonitor: error from querySessionStatus:",g.message)}))}),1e3)},l.prototype._callback=function(){var f=this;this._userManager.querySessionStatus().then((function(m){var g=!0;m?m.sub===f._sub?(g=!1,f._checkSessionIFrame.start(m.session_state),m.sid===f._sid?o.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",m.session_state):(o.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",m.session_state),f._userManager.events._raiseUserSessionChanged())):o.Log.debug("SessionMonitor._callback: Different subject signed into OP:",m.sub):o.Log.debug("SessionMonitor._callback: Subject no longer signed into OP"),g&&(f._sub?(o.Log.debug("SessionMonitor._callback: SessionMonitor._callback; raising signed out event"),f._userManager.events._raiseUserSignedOut()):(o.Log.debug("SessionMonitor._callback: SessionMonitor._callback; raising signed in event"),f._userManager.events._raiseUserSignedIn()))})).catch((function(m){f._sub&&(o.Log.debug("SessionMonitor._callback: Error calling queryCurrentSigninSession; raising signed out event",m.message),f._userManager.events._raiseUserSignedOut())}))},s(l,[{key:"_settings",get:function(){return this._userManager.settings}},{key:"_metadataService",get:function(){return this._userManager.metadataService}},{key:"_client_id",get:function(){return this._settings.client_id}},{key:"_checkSessionInterval",get:function(){return this._settings.checkSessionInterval}},{key:"_stopCheckSessionOnError",get:function(){return this._settings.stopCheckSessionOnError}}]),l})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.CheckSessionIFrame=void 0;var s=i(0);function o(a,u){if(!(a instanceof u))throw new TypeError("Cannot call a class as a function")}r.CheckSessionIFrame=(function(){function a(u,c,l,d){var f=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4];o(this,a),this._callback=u,this._client_id=c,this._url=l,this._interval=d||2e3,this._stopOnError=f;var m=l.indexOf("/",l.indexOf("//")+2);this._frame_origin=l.substr(0,m),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.width=0,this._frame.height=0,this._frame.src=l}return a.prototype.load=function(){var c=this;return new Promise((function(l){c._frame.onload=function(){l()},window.document.body.appendChild(c._frame),c._boundMessageEvent=c._message.bind(c),window.addEventListener("message",c._boundMessageEvent,!1)}))},a.prototype._message=function(c){c.origin===this._frame_origin&&c.source===this._frame.contentWindow&&(c.data==="error"?(s.Log.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):c.data==="changed"?(s.Log.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):s.Log.debug("CheckSessionIFrame: "+c.data+" message from check session op iframe"))},a.prototype.start=function(c){var l=this;if(this._session_state!==c){s.Log.debug("CheckSessionIFrame.start"),this.stop(),this._session_state=c;var d=function(){l._frame.contentWindow.postMessage(l._client_id+" "+l._session_state,l._frame_origin)};d(),this._timer=window.setInterval(d,this._interval)}},a.prototype.stop=function(){this._session_state=null,this._timer&&(s.Log.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)},a})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.TokenRevocationClient=void 0;var s=i(0),o=i(2),a=i(1);function u(d,f){if(!(d instanceof f))throw new TypeError("Cannot call a class as a function")}var c="access_token",l="refresh_token";r.TokenRevocationClient=(function(){function d(f){var m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:a.Global.XMLHttpRequest,g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:o.MetadataService;if(u(this,d),!f)throw s.Log.error("TokenRevocationClient.ctor: No settings provided"),new Error("No settings provided.");this._settings=f,this._XMLHttpRequestCtor=m,this._metadataService=new g(this._settings)}return d.prototype.revoke=function(m,g){var b=this,S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"access_token";if(!m)throw s.Log.error("TokenRevocationClient.revoke: No token provided"),new Error("No token provided.");if(S!==c&&S!=l)throw s.Log.error("TokenRevocationClient.revoke: Invalid token type"),new Error("Invalid token type.");return this._metadataService.getRevocationEndpoint().then((function(w){if(w){s.Log.debug("TokenRevocationClient.revoke: Revoking "+S);var v=b._settings.client_id,_=b._settings.client_secret;return b._revoke(w,v,_,m,S)}if(g)throw s.Log.error("TokenRevocationClient.revoke: Revocation not supported"),new Error("Revocation not supported")}))},d.prototype._revoke=function(m,g,b,S,w){var v=this;return new Promise((function(_,T){var C=new v._XMLHttpRequestCtor;C.open("POST",m),C.onload=function(){s.Log.debug("TokenRevocationClient.revoke: HTTP response received, status",C.status),C.status===200?_():T(Error(C.statusText+" ("+C.status+")"))},C.onerror=function(){s.Log.debug("TokenRevocationClient.revoke: Network Error."),T("Network Error")};var U="client_id="+encodeURIComponent(g);b&&(U+="&client_secret="+encodeURIComponent(b)),U+="&token_type_hint="+encodeURIComponent(w),U+="&token="+encodeURIComponent(S),C.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),C.send(U)}))},d})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.CordovaPopupWindow=void 0;var s=(function(){function a(u,c){for(var l=0;l<c.length;l++){var d=c[l];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(u,d.key,d)}}return function(u,c,l){return c&&a(u.prototype,c),l&&a(u,l),u}})(),o=i(0);r.CordovaPopupWindow=(function(){function a(u){var c=this;(function(d,f){if(!(d instanceof f))throw new TypeError("Cannot call a class as a function")})(this,a),this._promise=new Promise((function(l,d){c._resolve=l,c._reject=d})),this.features=u.popupWindowFeatures||"location=no,toolbar=no,zoom=no",this.target=u.popupWindowTarget||"_blank",this.redirect_uri=u.startUrl,o.Log.debug("CordovaPopupWindow.ctor: redirect_uri: "+this.redirect_uri)}return a.prototype._isInAppBrowserInstalled=function(c){return["cordova-plugin-inappbrowser","cordova-plugin-inappbrowser.inappbrowser","org.apache.cordova.inappbrowser"].some((function(l){return c.hasOwnProperty(l)}))},a.prototype.navigate=function(c){if(c&&c.url){if(!window.cordova)return this._error("cordova is undefined");var l=window.cordova.require("cordova/plugin_list").metadata;if(this._isInAppBrowserInstalled(l)===!1)return this._error("InAppBrowser plugin not found");this._popup=cordova.InAppBrowser.open(c.url,this.target,this.features),this._popup?(o.Log.debug("CordovaPopupWindow.navigate: popup successfully created"),this._exitCallbackEvent=this._exitCallback.bind(this),this._loadStartCallbackEvent=this._loadStartCallback.bind(this),this._popup.addEventListener("exit",this._exitCallbackEvent,!1),this._popup.addEventListener("loadstart",this._loadStartCallbackEvent,!1)):this._error("Error opening popup window")}else this._error("No url provided");return this.promise},a.prototype._loadStartCallback=function(c){c.url.indexOf(this.redirect_uri)===0&&this._success({url:c.url})},a.prototype._exitCallback=function(c){this._error(c)},a.prototype._success=function(c){this._cleanup(),o.Log.debug("CordovaPopupWindow: Successful response from cordova popup window"),this._resolve(c)},a.prototype._error=function(c){this._cleanup(),o.Log.error(c),this._reject(new Error(c))},a.prototype.close=function(){this._cleanup()},a.prototype._cleanup=function(){this._popup&&(o.Log.debug("CordovaPopupWindow: cleaning up popup"),this._popup.removeEventListener("exit",this._exitCallbackEvent,!1),this._popup.removeEventListener("loadstart",this._loadStartCallbackEvent,!1),this._popup.close()),this._popup=null},s(a,[{key:"promise",get:function(){return this._promise}}]),a})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0});var s=i(0),o=i(10),a=i(5),u=i(6),c=i(37),l=i(38),d=i(16),f=i(2),m=i(48),g=i(49),b=i(19),S=i(20),w=i(18),v=i(1),_=i(15),T=i(50);r.default={Version:T.Version,Log:s.Log,OidcClient:o.OidcClient,OidcClientSettings:a.OidcClientSettings,WebStorageStateStore:u.WebStorageStateStore,InMemoryWebStorage:c.InMemoryWebStorage,UserManager:l.UserManager,AccessTokenEvents:d.AccessTokenEvents,MetadataService:f.MetadataService,CordovaPopupNavigator:m.CordovaPopupNavigator,CordovaIFrameNavigator:g.CordovaIFrameNavigator,CheckSessionIFrame:b.CheckSessionIFrame,TokenRevocationClient:S.TokenRevocationClient,SessionMonitor:w.SessionMonitor,Global:v.Global,User:_.User},t.exports=r.default},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.ClockService=(function(){function s(){(function(a,u){if(!(a instanceof u))throw new TypeError("Cannot call a class as a function")})(this,s)}return s.prototype.getEpochTime=function(){return Promise.resolve(Date.now()/1e3|0)},s})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.ResponseValidator=void 0;var s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(g){return typeof g}:function(g){return g&&typeof Symbol=="function"&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g},o=i(0),a=i(2),u=i(25),c=i(11),l=i(12),d=i(4);function f(g,b){if(!(g instanceof b))throw new TypeError("Cannot call a class as a function")}var m=["nonce","at_hash","iat","nbf","exp","aud","iss","c_hash"];r.ResponseValidator=(function(){function g(b){var S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:a.MetadataService,w=arguments.length>2&&arguments[2]!==void 0?arguments[2]:u.UserInfoService,v=arguments.length>3&&arguments[3]!==void 0?arguments[3]:d.JoseUtil,_=arguments.length>4&&arguments[4]!==void 0?arguments[4]:c.TokenClient;if(f(this,g),!b)throw o.Log.error("ResponseValidator.ctor: No settings passed to ResponseValidator"),new Error("settings");this._settings=b,this._metadataService=new S(this._settings),this._userInfoService=new w(this._settings),this._joseUtil=v,this._tokenClient=new _(this._settings)}return g.prototype.validateSigninResponse=function(S,w){var v=this;return o.Log.debug("ResponseValidator.validateSigninResponse"),this._processSigninParams(S,w).then((function(_){return o.Log.debug("ResponseValidator.validateSigninResponse: state processed"),v._validateTokens(S,_).then((function(T){return o.Log.debug("ResponseValidator.validateSigninResponse: tokens validated"),v._processClaims(S,T).then((function(C){return o.Log.debug("ResponseValidator.validateSigninResponse: claims processed"),C}))}))}))},g.prototype.validateSignoutResponse=function(S,w){return S.id!==w.state?(o.Log.error("ResponseValidator.validateSignoutResponse: State does not match"),Promise.reject(new Error("State does not match"))):(o.Log.debug("ResponseValidator.validateSignoutResponse: state validated"),w.state=S.data,w.error?(o.Log.warn("ResponseValidator.validateSignoutResponse: Response was error",w.error),Promise.reject(new l.ErrorResponse(w))):Promise.resolve(w))},g.prototype._processSigninParams=function(S,w){if(S.id!==w.state)return o.Log.error("ResponseValidator._processSigninParams: State does not match"),Promise.reject(new Error("State does not match"));if(!S.client_id)return o.Log.error("ResponseValidator._processSigninParams: No client_id on state"),Promise.reject(new Error("No client_id on state"));if(!S.authority)return o.Log.error("ResponseValidator._processSigninParams: No authority on state"),Promise.reject(new Error("No authority on state"));if(this._settings.authority){if(this._settings.authority&&this._settings.authority!==S.authority)return o.Log.error("ResponseValidator._processSigninParams: authority mismatch on settings vs. signin state"),Promise.reject(new Error("authority mismatch on settings vs. signin state"))}else this._settings.authority=S.authority;if(this._settings.client_id){if(this._settings.client_id&&this._settings.client_id!==S.client_id)return o.Log.error("ResponseValidator._processSigninParams: client_id mismatch on settings vs. signin state"),Promise.reject(new Error("client_id mismatch on settings vs. signin state"))}else this._settings.client_id=S.client_id;return o.Log.debug("ResponseValidator._processSigninParams: state validated"),w.state=S.data,w.error?(o.Log.warn("ResponseValidator._processSigninParams: Response was error",w.error),Promise.reject(new l.ErrorResponse(w))):S.nonce&&!w.id_token?(o.Log.error("ResponseValidator._processSigninParams: Expecting id_token in response"),Promise.reject(new Error("No id_token in response"))):!S.nonce&&w.id_token?(o.Log.error("ResponseValidator._processSigninParams: Not expecting id_token in response"),Promise.reject(new Error("Unexpected id_token in response"))):S.code_verifier&&!w.code?(o.Log.error("ResponseValidator._processSigninParams: Expecting code in response"),Promise.reject(new Error("No code in response"))):!S.code_verifier&&w.code?(o.Log.error("ResponseValidator._processSigninParams: Not expecting code in response"),Promise.reject(new Error("Unexpected code in response"))):(w.scope||(w.scope=S.scope),Promise.resolve(w))},g.prototype._processClaims=function(S,w){var v=this;if(w.isOpenIdConnect){if(o.Log.debug("ResponseValidator._processClaims: response is OIDC, processing claims"),w.profile=this._filterProtocolClaims(w.profile),S.skipUserInfo!==!0&&this._settings.loadUserInfo&&w.access_token)return o.Log.debug("ResponseValidator._processClaims: loading user info"),this._userInfoService.getClaims(w.access_token).then((function(_){return o.Log.debug("ResponseValidator._processClaims: user info claims received from user info endpoint"),_.sub!==w.profile.sub?(o.Log.error("ResponseValidator._processClaims: sub from user info endpoint does not match sub in id_token"),Promise.reject(new Error("sub from user info endpoint does not match sub in id_token"))):(w.profile=v._mergeClaims(w.profile,_),o.Log.debug("ResponseValidator._processClaims: user info claims received, updated profile:",w.profile),w)}));o.Log.debug("ResponseValidator._processClaims: not loading user info")}else o.Log.debug("ResponseValidator._processClaims: response is not OIDC, not processing claims");return Promise.resolve(w)},g.prototype._mergeClaims=function(S,w){var v=Object.assign({},S);for(var _ in w){var T=w[_];Array.isArray(T)||(T=[T]);for(var C=0;C<T.length;C++){var U=T[C];v[_]?Array.isArray(v[_])?v[_].indexOf(U)<0&&v[_].push(U):v[_]!==U&&((U===void 0?"undefined":s(U))==="object"&&this._settings.mergeClaims?v[_]=this._mergeClaims(v[_],U):v[_]=[v[_],U]):v[_]=U}}return v},g.prototype._filterProtocolClaims=function(S){o.Log.debug("ResponseValidator._filterProtocolClaims, incoming claims:",S);var w=Object.assign({},S);return this._settings._filterProtocolClaims?(m.forEach((function(v){delete w[v]})),o.Log.debug("ResponseValidator._filterProtocolClaims: protocol claims filtered",w)):o.Log.debug("ResponseValidator._filterProtocolClaims: protocol claims not filtered"),w},g.prototype._validateTokens=function(S,w){return w.code?(o.Log.debug("ResponseValidator._validateTokens: Validating code"),this._processCode(S,w)):w.id_token?w.access_token?(o.Log.debug("ResponseValidator._validateTokens: Validating id_token and access_token"),this._validateIdTokenAndAccessToken(S,w)):(o.Log.debug("ResponseValidator._validateTokens: Validating id_token"),this._validateIdToken(S,w)):(o.Log.debug("ResponseValidator._validateTokens: No code to process or id_token to validate"),Promise.resolve(w))},g.prototype._processCode=function(S,w){var v=this,_={client_id:S.client_id,client_secret:S.client_secret,code:w.code,redirect_uri:S.redirect_uri,code_verifier:S.code_verifier};return S.extraTokenParams&&s(S.extraTokenParams)==="object"&&Object.assign(_,S.extraTokenParams),this._tokenClient.exchangeCode(_).then((function(T){for(var C in T)w[C]=T[C];return w.id_token?(o.Log.debug("ResponseValidator._processCode: token response successful, processing id_token"),v._validateIdTokenAttributes(S,w)):(o.Log.debug("ResponseValidator._processCode: token response successful, returning response"),w)}))},g.prototype._validateIdTokenAttributes=function(S,w){var v=this;return this._metadataService.getIssuer().then((function(_){var T=S.client_id,C=v._settings.clockSkew;return o.Log.debug("ResponseValidator._validateIdTokenAttributes: Validaing JWT attributes; using clock skew (in seconds) of: ",C),v._settings.getEpochTime().then((function(U){return v._joseUtil.validateJwtAttributes(w.id_token,_,T,C,U).then((function($){return S.nonce&&S.nonce!==$.nonce?(o.Log.error("ResponseValidator._validateIdTokenAttributes: Invalid nonce in id_token"),Promise.reject(new Error("Invalid nonce in id_token"))):$.sub?(w.profile=$,w):(o.Log.error("ResponseValidator._validateIdTokenAttributes: No sub present in id_token"),Promise.reject(new Error("No sub present in id_token")))}))}))}))},g.prototype._validateIdTokenAndAccessToken=function(S,w){var v=this;return this._validateIdToken(S,w).then((function(_){return v._validateAccessToken(_)}))},g.prototype._getSigningKeyForJwt=function(S){var w=this;return this._metadataService.getSigningKeys().then((function(v){var _=S.header.kid;if(!v)return o.Log.error("ResponseValidator._validateIdToken: No signing keys from metadata"),Promise.reject(new Error("No signing keys from metadata"));o.Log.debug("ResponseValidator._validateIdToken: Received signing keys");var T=void 0;if(_)T=v.filter((function(C){return C.kid===_}))[0];else{if((v=w._filterByAlg(v,S.header.alg)).length>1)return o.Log.error("ResponseValidator._validateIdToken: No kid found in id_token and more than one key found in metadata"),Promise.reject(new Error("No kid found in id_token and more than one key found in metadata"));T=v[0]}return Promise.resolve(T)}))},g.prototype._getSigningKeyForJwtWithSingleRetry=function(S){var w=this;return this._getSigningKeyForJwt(S).then((function(v){return v?Promise.resolve(v):(w._metadataService.resetSigningKeys(),w._getSigningKeyForJwt(S))}))},g.prototype._validateIdToken=function(S,w){var v=this;if(!S.nonce)return o.Log.error("ResponseValidator._validateIdToken: No nonce on state"),Promise.reject(new Error("No nonce on state"));var _=this._joseUtil.parseJwt(w.id_token);return _&&_.header&&_.payload?S.nonce!==_.payload.nonce?(o.Log.error("ResponseValidator._validateIdToken: Invalid nonce in id_token"),Promise.reject(new Error("Invalid nonce in id_token"))):this._metadataService.getIssuer().then((function(T){return o.Log.debug("ResponseValidator._validateIdToken: Received issuer"),v._getSigningKeyForJwtWithSingleRetry(_).then((function(C){if(!C)return o.Log.error("ResponseValidator._validateIdToken: No key matching kid or alg found in signing keys"),Promise.reject(new Error("No key matching kid or alg found in signing keys"));var U=S.client_id,$=v._settings.clockSkew;return o.Log.debug("ResponseValidator._validateIdToken: Validaing JWT; using clock skew (in seconds) of: ",$),v._joseUtil.validateJwt(w.id_token,C,T,U,$).then((function(){return o.Log.debug("ResponseValidator._validateIdToken: JWT validation successful"),_.payload.sub?(w.profile=_.payload,w):(o.Log.error("ResponseValidator._validateIdToken: No sub present in id_token"),Promise.reject(new Error("No sub present in id_token")))}))}))})):(o.Log.error("ResponseValidator._validateIdToken: Failed to parse id_token",_),Promise.reject(new Error("Failed to parse id_token")))},g.prototype._filterByAlg=function(S,w){var v=null;if(w.startsWith("RS"))v="RSA";else if(w.startsWith("PS"))v="PS";else{if(!w.startsWith("ES"))return o.Log.debug("ResponseValidator._filterByAlg: alg not supported: ",w),[];v="EC"}return o.Log.debug("ResponseValidator._filterByAlg: Looking for keys that match kty: ",v),S=S.filter((function(_){return _.kty===v})),o.Log.debug("ResponseValidator._filterByAlg: Number of keys that match kty: ",v,S.length),S},g.prototype._validateAccessToken=function(S){if(!S.profile)return o.Log.error("ResponseValidator._validateAccessToken: No profile loaded from id_token"),Promise.reject(new Error("No profile loaded from id_token"));if(!S.profile.at_hash)return o.Log.error("ResponseValidator._validateAccessToken: No at_hash in id_token"),Promise.reject(new Error("No at_hash in id_token"));if(!S.id_token)return o.Log.error("ResponseValidator._validateAccessToken: No id_token"),Promise.reject(new Error("No id_token"));var w=this._joseUtil.parseJwt(S.id_token);if(!w||!w.header)return o.Log.error("ResponseValidator._validateAccessToken: Failed to parse id_token",w),Promise.reject(new Error("Failed to parse id_token"));var v=w.header.alg;if(!v||v.length!==5)return o.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",v),Promise.reject(new Error("Unsupported alg: "+v));var _=v.substr(2,3);if(!_)return o.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",v,_),Promise.reject(new Error("Unsupported alg: "+v));if((_=parseInt(_))!==256&&_!==384&&_!==512)return o.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",v,_),Promise.reject(new Error("Unsupported alg: "+v));var T="sha"+_,C=this._joseUtil.hashString(S.access_token,T);if(!C)return o.Log.error("ResponseValidator._validateAccessToken: access_token hash failed:",T),Promise.reject(new Error("Failed to validate at_hash"));var U=C.substr(0,C.length/2),$=this._joseUtil.hexToBase64Url(U);return $!==S.profile.at_hash?(o.Log.error("ResponseValidator._validateAccessToken: Failed to validate at_hash",$,S.profile.at_hash),Promise.reject(new Error("Failed to validate at_hash"))):(o.Log.debug("ResponseValidator._validateAccessToken: success"),Promise.resolve(S))},g})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.UserInfoService=void 0;var s=i(7),o=i(2),a=i(0),u=i(4);function c(l,d){if(!(l instanceof d))throw new TypeError("Cannot call a class as a function")}r.UserInfoService=(function(){function l(d){var f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:s.JsonService,m=arguments.length>2&&arguments[2]!==void 0?arguments[2]:o.MetadataService,g=arguments.length>3&&arguments[3]!==void 0?arguments[3]:u.JoseUtil;if(c(this,l),!d)throw a.Log.error("UserInfoService.ctor: No settings passed"),new Error("settings");this._settings=d,this._jsonService=new f(void 0,void 0,this._getClaimsFromJwt.bind(this)),this._metadataService=new m(this._settings),this._joseUtil=g}return l.prototype.getClaims=function(f){var m=this;return f?this._metadataService.getUserInfoEndpoint().then((function(g){return a.Log.debug("UserInfoService.getClaims: received userinfo url",g),m._jsonService.getJson(g,f).then((function(b){return a.Log.debug("UserInfoService.getClaims: claims received",b),b}))})):(a.Log.error("UserInfoService.getClaims: No token passed"),Promise.reject(new Error("A token is required")))},l.prototype._getClaimsFromJwt=function(f){var m=this;try{var g=this._joseUtil.parseJwt(f.responseText);if(!g||!g.header||!g.payload)return a.Log.error("UserInfoService._getClaimsFromJwt: Failed to parse JWT",g),Promise.reject(new Error("Failed to parse id_token"));var b=g.header.kid,S=void 0;switch(this._settings.userInfoJwtIssuer){case"OP":S=this._metadataService.getIssuer();break;case"ANY":S=Promise.resolve(g.payload.iss);break;default:S=Promise.resolve(this._settings.userInfoJwtIssuer)}return S.then((function(w){return a.Log.debug("UserInfoService._getClaimsFromJwt: Received issuer:"+w),m._metadataService.getSigningKeys().then((function(v){if(!v)return a.Log.error("UserInfoService._getClaimsFromJwt: No signing keys from metadata"),Promise.reject(new Error("No signing keys from metadata"));a.Log.debug("UserInfoService._getClaimsFromJwt: Received signing keys");var _=void 0;if(b)_=v.filter((function(U){return U.kid===b}))[0];else{if((v=m._filterByAlg(v,g.header.alg)).length>1)return a.Log.error("UserInfoService._getClaimsFromJwt: No kid found in id_token and more than one key found in metadata"),Promise.reject(new Error("No kid found in id_token and more than one key found in metadata"));_=v[0]}if(!_)return a.Log.error("UserInfoService._getClaimsFromJwt: No key matching kid or alg found in signing keys"),Promise.reject(new Error("No key matching kid or alg found in signing keys"));var T=m._settings.client_id,C=m._settings.clockSkew;return a.Log.debug("UserInfoService._getClaimsFromJwt: Validaing JWT; using clock skew (in seconds) of: ",C),m._joseUtil.validateJwt(f.responseText,_,w,T,C,void 0,!0).then((function(){return a.Log.debug("UserInfoService._getClaimsFromJwt: JWT validation successful"),g.payload}))}))}))}catch(w){return a.Log.error("UserInfoService._getClaimsFromJwt: Error parsing JWT response",w.message),void reject(w)}},l.prototype._filterByAlg=function(f,m){var g=null;if(m.startsWith("RS"))g="RSA";else if(m.startsWith("PS"))g="PS";else{if(!m.startsWith("ES"))return a.Log.debug("UserInfoService._filterByAlg: alg not supported: ",m),[];g="EC"}return a.Log.debug("UserInfoService._filterByAlg: Looking for keys that match kty: ",g),f=f.filter((function(b){return b.kty===g})),a.Log.debug("UserInfoService._filterByAlg: Number of keys that match kty: ",g,f.length),f},l})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.AllowedSigningAlgs=r.b64tohex=r.hextob64u=r.crypto=r.X509=r.KeyUtil=r.jws=void 0;var s=i(27);r.jws=s.jws,r.KeyUtil=s.KEYUTIL,r.X509=s.X509,r.crypto=s.crypto,r.hextob64u=s.hextob64u,r.b64tohex=s.b64tohex,r.AllowedSigningAlgs=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"]},function(t,r,i){(function(s){Object.defineProperty(r,"__esModule",{value:!0});var o,a,u,c,l,d,f,m,g,b,S,w=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(p){return typeof p}:function(p){return p&&typeof Symbol=="function"&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p},v={},_={},T=T||(o=Math,u=(a={}).lib={},c=u.Base=(function(){function p(){}return{extend:function(y){p.prototype=this;var E=new p;return y&&E.mixIn(y),E.hasOwnProperty("init")||(E.init=function(){E.$super.init.apply(this,arguments)}),E.init.prototype=E,E.$super=this,E},create:function(){var y=this.extend();return y.init.apply(y,arguments),y},init:function(){},mixIn:function(y){for(var E in y)y.hasOwnProperty(E)&&(this[E]=y[E]);y.hasOwnProperty("toString")&&(this.toString=y.toString)},clone:function(){return this.init.prototype.extend(this)}}})(),l=u.WordArray=c.extend({init:function(h,y){h=this.words=h||[],this.sigBytes=y??4*h.length},toString:function(h){return(h||f).stringify(this)},concat:function(h){var y=this.words,E=h.words,I=this.sigBytes,q=h.sigBytes;if(this.clamp(),I%4)for(var K=0;K<q;K++){var ce=E[K>>>2]>>>24-K%4*8&255;y[I+K>>>2]|=ce<<24-(I+K)%4*8}else for(K=0;K<q;K+=4)y[I+K>>>2]=E[K>>>2];return this.sigBytes+=q,this},clamp:function(){var h=this.words,y=this.sigBytes;h[y>>>2]&=4294967295<<32-y%4*8,h.length=o.ceil(y/4)},clone:function(){var h=c.clone.call(this);return h.words=this.words.slice(0),h},random:function(h){for(var y=[],E=0;E<h;E+=4)y.push(4294967296*o.random()|0);return new l.init(y,h)}}),d=a.enc={},f=d.Hex={stringify:function(h){for(var y=h.words,E=h.sigBytes,I=[],q=0;q<E;q++){var K=y[q>>>2]>>>24-q%4*8&255;I.push((K>>>4).toString(16)),I.push((15&K).toString(16))}return I.join("")},parse:function(h){for(var y=h.length,E=[],I=0;I<y;I+=2)E[I>>>3]|=parseInt(h.substr(I,2),16)<<24-I%8*4;return new l.init(E,y/2)}},m=d.Latin1={stringify:function(h){for(var y=h.words,E=h.sigBytes,I=[],q=0;q<E;q++){var K=y[q>>>2]>>>24-q%4*8&255;I.push(String.fromCharCode(K))}return I.join("")},parse:function(h){for(var y=h.length,E=[],I=0;I<y;I++)E[I>>>2]|=(255&h.charCodeAt(I))<<24-I%4*8;return new l.init(E,y)}},g=d.Utf8={stringify:function(h){try{return decodeURIComponent(escape(m.stringify(h)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(h){return m.parse(unescape(encodeURIComponent(h)))}},b=u.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new l.init,this._nDataBytes=0},_append:function(h){typeof h=="string"&&(h=g.parse(h)),this._data.concat(h),this._nDataBytes+=h.sigBytes},_process:function(h){var y=this._data,E=y.words,I=y.sigBytes,q=this.blockSize,K=I/(4*q),ce=(K=h?o.ceil(K):o.max((0|K)-this._minBufferSize,0))*q,ee=o.min(4*ce,I);if(ce){for(var se=0;se<ce;se+=q)this._doProcessBlock(E,se);var oe=E.splice(0,ce);y.sigBytes-=ee}return new l.init(oe,ee)},clone:function(){var h=c.clone.call(this);return h._data=this._data.clone(),h},_minBufferSize:0}),u.Hasher=b.extend({cfg:c.extend(),init:function(h){this.cfg=this.cfg.extend(h),this.reset()},reset:function(){b.reset.call(this),this._doReset()},update:function(h){return this._append(h),this._process(),this},finalize:function(h){return h&&this._append(h),this._doFinalize()},blockSize:16,_createHelper:function(h){return function(y,E){return new h.init(E).finalize(y)}},_createHmacHelper:function(h){return function(y,E){return new S.HMAC.init(h,E).finalize(y)}}}),S=a.algo={},a);(function(p){var h,y=(h=T).lib,E=y.Base,I=y.WordArray;(h=h.x64={}).Word=E.extend({init:function(K,ce){this.high=K,this.low=ce}}),h.WordArray=E.extend({init:function(K,ce){K=this.words=K||[],this.sigBytes=ce??8*K.length},toX32:function(){for(var K=this.words,ce=K.length,ee=[],se=0;se<ce;se++){var oe=K[se];ee.push(oe.high),ee.push(oe.low)}return I.create(ee,this.sigBytes)},clone:function(){for(var K=E.clone.call(this),ce=K.words=this.words.slice(0),ee=ce.length,se=0;se<ee;se++)ce[se]=ce[se].clone();return K}})})(),(function(){var p=T,h=p.lib.WordArray;p.enc.Base64={stringify:function(E){var I=E.words,q=E.sigBytes,K=this._map;E.clamp(),E=[];for(var ce=0;ce<q;ce+=3)for(var ee=(I[ce>>>2]>>>24-ce%4*8&255)<<16|(I[ce+1>>>2]>>>24-(ce+1)%4*8&255)<<8|I[ce+2>>>2]>>>24-(ce+2)%4*8&255,se=0;4>se&&ce+.75*se<q;se++)E.push(K.charAt(ee>>>6*(3-se)&63));if(I=K.charAt(64))for(;E.length%4;)E.push(I);return E.join("")},parse:function(E){var I=E.length,q=this._map;(K=q.charAt(64))&&(K=E.indexOf(K))!=-1&&(I=K);for(var K=[],ce=0,ee=0;ee<I;ee++)if(ee%4){var se=q.indexOf(E.charAt(ee-1))<<ee%4*2,oe=q.indexOf(E.charAt(ee))>>>6-ee%4*2;K[ce>>>2]|=(se|oe)<<24-ce%4*8,ce++}return h.create(K,ce)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})(),(function(p){for(var h=T,y=(I=h.lib).WordArray,E=I.Hasher,I=h.algo,q=[],K=[],ce=function($e){return 4294967296*($e-(0|$e))|0},ee=2,se=0;64>se;){var oe;e:{oe=ee;for(var pe=p.sqrt(oe),Se=2;Se<=pe;Se++)if(!(oe%Se)){oe=!1;break e}oe=!0}oe&&(8>se&&(q[se]=ce(p.pow(ee,.5))),K[se]=ce(p.pow(ee,1/3)),se++),ee++}var Ee=[];I=I.SHA256=E.extend({_doReset:function(){this._hash=new y.init(q.slice(0))},_doProcessBlock:function($e,Le){for(var Z=this._hash.words,fe=Z[0],ye=Z[1],be=Z[2],Ue=Z[3],Me=Z[4],Ye=Z[5],Ke=Z[6],st=Z[7],Xe=0;64>Xe;Xe++){if(16>Xe)Ee[Xe]=0|$e[Le+Xe];else{var tt=Ee[Xe-15],bt=Ee[Xe-2];Ee[Xe]=((tt<<25|tt>>>7)^(tt<<14|tt>>>18)^tt>>>3)+Ee[Xe-7]+((bt<<15|bt>>>17)^(bt<<13|bt>>>19)^bt>>>10)+Ee[Xe-16]}tt=st+((Me<<26|Me>>>6)^(Me<<21|Me>>>11)^(Me<<7|Me>>>25))+(Me&Ye^~Me&Ke)+K[Xe]+Ee[Xe],bt=((fe<<30|fe>>>2)^(fe<<19|fe>>>13)^(fe<<10|fe>>>22))+(fe&ye^fe&be^ye&be),st=Ke,Ke=Ye,Ye=Me,Me=Ue+tt|0,Ue=be,be=ye,ye=fe,fe=tt+bt|0}Z[0]=Z[0]+fe|0,Z[1]=Z[1]+ye|0,Z[2]=Z[2]+be|0,Z[3]=Z[3]+Ue|0,Z[4]=Z[4]+Me|0,Z[5]=Z[5]+Ye|0,Z[6]=Z[6]+Ke|0,Z[7]=Z[7]+st|0},_doFinalize:function(){var $e=this._data,Le=$e.words,Z=8*this._nDataBytes,fe=8*$e.sigBytes;return Le[fe>>>5]|=128<<24-fe%32,Le[14+(fe+64>>>9<<4)]=p.floor(Z/4294967296),Le[15+(fe+64>>>9<<4)]=Z,$e.sigBytes=4*Le.length,this._process(),this._hash},clone:function(){var $e=E.clone.call(this);return $e._hash=this._hash.clone(),$e}}),h.SHA256=E._createHelper(I),h.HmacSHA256=E._createHmacHelper(I)})(Math),(function(){function p(){return E.create.apply(E,arguments)}for(var h=T,y=h.lib.Hasher,E=(q=h.x64).Word,I=q.WordArray,q=h.algo,K=[p(1116352408,3609767458),p(1899447441,602891725),p(3049323471,3964484399),p(3921009573,2173295548),p(961987163,4081628472),p(1508970993,3053834265),p(2453635748,2937671579),p(2870763221,3664609560),p(3624381080,2734883394),p(310598401,1164996542),p(607225278,1323610764),p(1426881987,3590304994),p(1925078388,4068182383),p(2162078206,991336113),p(2614888103,633803317),p(3248222580,3479774868),p(3835390401,2666613458),p(4022224774,944711139),p(264347078,2341262773),p(604807628,2007800933),p(770255983,1495990901),p(1249150122,1856431235),p(1555081692,3175218132),p(1996064986,2198950837),p(2554220882,3999719339),p(2821834349,766784016),p(2952996808,2566594879),p(3210313671,3203337956),p(3336571891,1034457026),p(3584528711,2466948901),p(113926993,3758326383),p(338241895,168717936),p(666307205,1188179964),p(773529912,1546045734),p(1294757372,1522805485),p(1396182291,2643833823),p(1695183700,2343527390),p(1986661051,1014477480),p(2177026350,1206759142),p(2456956037,344077627),p(2730485921,1290863460),p(2820302411,3158454273),p(3259730800,3505952657),p(3345764771,106217008),p(3516065817,3606008344),p(3600352804,1432725776),p(4094571909,1467031594),p(275423344,851169720),p(430227734,3100823752),p(506948616,1363258195),p(659060556,3750685593),p(883997877,3785050280),p(958139571,3318307427),p(1322822218,3812723403),p(1537002063,2003034995),p(1747873779,3602036899),p(1955562222,1575990012),p(2024104815,1125592928),p(2227730452,2716904306),p(2361852424,442776044),p(2428436474,593698344),p(2756734187,3733110249),p(3204031479,2999351573),p(3329325298,3815920427),p(3391569614,3928383900),p(3515267271,566280711),p(3940187606,3454069534),p(4118630271,4000239992),p(116418474,1914138554),p(174292421,2731055270),p(289380356,3203993006),p(460393269,320620315),p(685471733,587496836),p(852142971,1086792851),p(1017036298,365543100),p(1126000580,2618297676),p(1288033470,3409855158),p(1501505948,4234509866),p(1607167915,987167468),p(1816402316,1246189591)],ce=[],ee=0;80>ee;ee++)ce[ee]=p();q=q.SHA512=y.extend({_doReset:function(){this._hash=new I.init([new E.init(1779033703,4089235720),new E.init(3144134277,2227873595),new E.init(1013904242,4271175723),new E.init(2773480762,1595750129),new E.init(1359893119,2917565137),new E.init(2600822924,725511199),new E.init(528734635,4215389547),new E.init(1541459225,327033209)])},_doProcessBlock:function(oe,pe){for(var Se=(ye=this._hash.words)[0],Ee=ye[1],Pe=ye[2],$e=ye[3],Le=ye[4],Z=ye[5],fe=ye[6],ye=ye[7],be=Se.high,Ue=Se.low,Me=Ee.high,Ye=Ee.low,Ke=Pe.high,st=Pe.low,Xe=$e.high,tt=$e.low,bt=Le.high,St=Le.low,mt=Z.high,Ht=Z.low,jt=fe.high,qt=fe.low,xt=ye.high,vt=ye.low,Lt=be,Vt=Ue,vr=Me,Er=Ye,ur=Ke,xr=st,ir=Xe,Ar=tt,Nt=bt,Mt=St,Tr=mt,Xt=Ht,Ur=jt,pr=qt,qr=xt,Cr=vt,Yt=0;80>Yt;Yt++){var lr=ce[Yt];if(16>Yt)var tr=lr.high=0|oe[pe+2*Yt],Tt=lr.low=0|oe[pe+2*Yt+1];else{tr=((Tt=(tr=ce[Yt-15]).high)>>>1|(hr=tr.low)<<31)^(Tt>>>8|hr<<24)^Tt>>>7;var hr=(hr>>>1|Tt<<31)^(hr>>>8|Tt<<24)^(hr>>>7|Tt<<25),Fr=((Tt=(Fr=ce[Yt-2]).high)>>>19|(Dt=Fr.low)<<13)^(Tt<<3|Dt>>>29)^Tt>>>6,Dt=(Dt>>>19|Tt<<13)^(Dt<<3|Tt>>>29)^(Dt>>>6|Tt<<26),Dr=(Tt=ce[Yt-7]).high,gr=(mr=ce[Yt-16]).high,mr=mr.low;tr=(tr=(tr=tr+Dr+((Tt=hr+Tt.low)>>>0<hr>>>0?1:0))+Fr+((Tt=Tt+Dt)>>>0<Dt>>>0?1:0))+gr+((Tt=Tt+mr)>>>0<mr>>>0?1:0),lr.high=tr,lr.low=Tt}Dr=Nt&Tr^~Nt&Ur,mr=Mt&Xt^~Mt&pr,lr=Lt&vr^Lt&ur^vr&ur;var nn=Vt&Er^Vt&xr^Er&xr,fn=(hr=(Lt>>>28|Vt<<4)^(Lt<<30|Vt>>>2)^(Lt<<25|Vt>>>7),Fr=(Vt>>>28|Lt<<4)^(Vt<<30|Lt>>>2)^(Vt<<25|Lt>>>7),(Dt=K[Yt]).high),yr=Dt.low;gr=qr+((Nt>>>14|Mt<<18)^(Nt>>>18|Mt<<14)^(Nt<<23|Mt>>>9))+((Dt=Cr+((Mt>>>14|Nt<<18)^(Mt>>>18|Nt<<14)^(Mt<<23|Nt>>>9)))>>>0<Cr>>>0?1:0),qr=Ur,Cr=pr,Ur=Tr,pr=Xt,Tr=Nt,Xt=Mt,Nt=ir+(gr=(gr=(gr=gr+Dr+((Dt=Dt+mr)>>>0<mr>>>0?1:0))+fn+((Dt=Dt+yr)>>>0<yr>>>0?1:0))+tr+((Dt=Dt+Tt)>>>0<Tt>>>0?1:0))+((Mt=Ar+Dt|0)>>>0<Ar>>>0?1:0)|0,ir=ur,Ar=xr,ur=vr,xr=Er,vr=Lt,Er=Vt,Lt=gr+(lr=hr+lr+((Tt=Fr+nn)>>>0<Fr>>>0?1:0))+((Vt=Dt+Tt|0)>>>0<Dt>>>0?1:0)|0}Ue=Se.low=Ue+Vt,Se.high=be+Lt+(Ue>>>0<Vt>>>0?1:0),Ye=Ee.low=Ye+Er,Ee.high=Me+vr+(Ye>>>0<Er>>>0?1:0),st=Pe.low=st+xr,Pe.high=Ke+ur+(st>>>0<xr>>>0?1:0),tt=$e.low=tt+Ar,$e.high=Xe+ir+(tt>>>0<Ar>>>0?1:0),St=Le.low=St+Mt,Le.high=bt+Nt+(St>>>0<Mt>>>0?1:0),Ht=Z.low=Ht+Xt,Z.high=mt+Tr+(Ht>>>0<Xt>>>0?1:0),qt=fe.low=qt+pr,fe.high=jt+Ur+(qt>>>0<pr>>>0?1:0),vt=ye.low=vt+Cr,ye.high=xt+qr+(vt>>>0<Cr>>>0?1:0)},_doFinalize:function(){var oe=this._data,pe=oe.words,Se=8*this._nDataBytes,Ee=8*oe.sigBytes;return pe[Ee>>>5]|=128<<24-Ee%32,pe[30+(Ee+128>>>10<<5)]=Math.floor(Se/4294967296),pe[31+(Ee+128>>>10<<5)]=Se,oe.sigBytes=4*pe.length,this._process(),this._hash.toX32()},clone:function(){var oe=y.clone.call(this);return oe._hash=this._hash.clone(),oe},blockSize:32}),h.SHA512=y._createHelper(q),h.HmacSHA512=y._createHmacHelper(q)})(),(function(){var p=T,h=(I=p.x64).Word,y=I.WordArray,E=(I=p.algo).SHA512,I=I.SHA384=E.extend({_doReset:function(){this._hash=new y.init([new h.init(3418070365,3238371032),new h.init(1654270250,914150663),new h.init(2438529370,812702999),new h.init(355462360,4144912697),new h.init(1731405415,4290775857),new h.init(2394180231,1750603025),new h.init(3675008525,1694076839),new h.init(1203062813,3204075428)])},_doFinalize:function(){var K=E._doFinalize.call(this);return K.sigBytes-=16,K}});p.SHA384=E._createHelper(I),p.HmacSHA384=E._createHmacHelper(I)})();var C,U="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function $(p){var h,y,E="";for(h=0;h+3<=p.length;h+=3)y=parseInt(p.substring(h,h+3),16),E+=U.charAt(y>>6)+U.charAt(63&y);for(h+1==p.length?(y=parseInt(p.substring(h,h+1),16),E+=U.charAt(y<<2)):h+2==p.length&&(y=parseInt(p.substring(h,h+2),16),E+=U.charAt(y>>2)+U.charAt((3&y)<<4)),"=";(3&E.length)>0;)E+="=";return E}function W(p){var h,y,E,I="",q=0;for(h=0;h<p.length&&p.charAt(h)!="=";++h)(E=U.indexOf(p.charAt(h)))<0||(q==0?(I+=Ce(E>>2),y=3&E,q=1):q==1?(I+=Ce(y<<2|E>>4),y=15&E,q=2):q==2?(I+=Ce(y),I+=Ce(E>>2),y=3&E,q=3):(I+=Ce(y<<2|E>>4),I+=Ce(15&E),q=0));return q==1&&(I+=Ce(y<<2)),I}function re(p){var h,y=W(p),E=new Array;for(h=0;2*h<y.length;++h)E[h]=parseInt(y.substring(2*h,2*h+2),16);return E}function D(p,h,y){p!=null&&(typeof p=="number"?this.fromNumber(p,h,y):h==null&&typeof p!="string"?this.fromString(p,256):this.fromString(p,h))}function V(){return new D(null)}v.appName=="Microsoft Internet Explorer"?(D.prototype.am=function(h,y,E,I,q,K){for(var ce=32767&y,ee=y>>15;--K>=0;){var se=32767&this[h],oe=this[h++]>>15,pe=ee*se+oe*ce;q=((se=ce*se+((32767&pe)<<15)+E[I]+(1073741823&q))>>>30)+(pe>>>15)+ee*oe+(q>>>30),E[I++]=1073741823&se}return q},C=30):v.appName!="Netscape"?(D.prototype.am=function(h,y,E,I,q,K){for(;--K>=0;){var ce=y*this[h++]+E[I]+q;q=Math.floor(ce/67108864),E[I++]=67108863&ce}return q},C=26):(D.prototype.am=function(h,y,E,I,q,K){for(var ce=16383&y,ee=y>>14;--K>=0;){var se=16383&this[h],oe=this[h++]>>14,pe=ee*se+oe*ce;q=((se=ce*se+((16383&pe)<<14)+E[I]+q)>>28)+(pe>>14)+ee*oe,E[I++]=268435455&se}return q},C=28),D.prototype.DB=C,D.prototype.DM=(1<<C)-1,D.prototype.DV=1<<C,D.prototype.FV=Math.pow(2,52),D.prototype.F1=52-C,D.prototype.F2=2*C-52;var he,z,_e=new Array;for(he=48,z=0;z<=9;++z)_e[he++]=z;for(he=97,z=10;z<36;++z)_e[he++]=z;for(he=65,z=10;z<36;++z)_e[he++]=z;function Ce(p){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(p)}function Fe(p,h){var y=_e[p.charCodeAt(h)];return y??-1}function ze(p){var h=V();return h.fromInt(p),h}function ae(p){var h,y=1;return(h=p>>>16)!=0&&(p=h,y+=16),(h=p>>8)!=0&&(p=h,y+=8),(h=p>>4)!=0&&(p=h,y+=4),(h=p>>2)!=0&&(p=h,y+=2),(h=p>>1)!=0&&(p=h,y+=1),y}function ve(p){this.m=p}function L(p){this.m=p,this.mp=p.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<p.DB-15)-1,this.mt2=2*p.t}function ie(p,h){return p&h}function xe(p,h){return p|h}function ue(p,h){return p^h}function De(p,h){return p&~h}function ke(p){if(p==0)return-1;var h=0;return(65535&p)==0&&(p>>=16,h+=16),(255&p)==0&&(p>>=8,h+=8),(15&p)==0&&(p>>=4,h+=4),(3&p)==0&&(p>>=2,h+=2),(1&p)==0&&++h,h}function We(p){for(var h=0;p!=0;)p&=p-1,++h;return h}function Oe(){}function te(p){return p}function le(p){this.r2=V(),this.q3=V(),D.ONE.dlShiftTo(2*p.t,this.r2),this.mu=this.r2.divide(p),this.m=p}ve.prototype.convert=function(h){return h.s<0||h.compareTo(this.m)>=0?h.mod(this.m):h},ve.prototype.revert=function(h){return h},ve.prototype.reduce=function(h){h.divRemTo(this.m,null,h)},ve.prototype.mulTo=function(h,y,E){h.multiplyTo(y,E),this.reduce(E)},ve.prototype.sqrTo=function(h,y){h.squareTo(y),this.reduce(y)},L.prototype.convert=function(h){var y=V();return h.abs().dlShiftTo(this.m.t,y),y.divRemTo(this.m,null,y),h.s<0&&y.compareTo(D.ZERO)>0&&this.m.subTo(y,y),y},L.prototype.revert=function(h){var y=V();return h.copyTo(y),this.reduce(y),y},L.prototype.reduce=function(h){for(;h.t<=this.mt2;)h[h.t++]=0;for(var y=0;y<this.m.t;++y){var E=32767&h[y],I=E*this.mpl+((E*this.mph+(h[y]>>15)*this.mpl&this.um)<<15)&h.DM;for(h[E=y+this.m.t]+=this.m.am(0,I,h,y,0,this.m.t);h[E]>=h.DV;)h[E]-=h.DV,h[++E]++}h.clamp(),h.drShiftTo(this.m.t,h),h.compareTo(this.m)>=0&&h.subTo(this.m,h)},L.prototype.mulTo=function(h,y,E){h.multiplyTo(y,E),this.reduce(E)},L.prototype.sqrTo=function(h,y){h.squareTo(y),this.reduce(y)},D.prototype.copyTo=function(h){for(var y=this.t-1;y>=0;--y)h[y]=this[y];h.t=this.t,h.s=this.s},D.prototype.fromInt=function(h){this.t=1,this.s=h<0?-1:0,h>0?this[0]=h:h<-1?this[0]=h+this.DV:this.t=0},D.prototype.fromString=function(h,y){var E;if(y==16)E=4;else if(y==8)E=3;else if(y==256)E=8;else if(y==2)E=1;else if(y==32)E=5;else{if(y!=4)return void this.fromRadix(h,y);E=2}this.t=0,this.s=0;for(var I=h.length,q=!1,K=0;--I>=0;){var ce=E==8?255&h[I]:Fe(h,I);ce<0?h.charAt(I)=="-"&&(q=!0):(q=!1,K==0?this[this.t++]=ce:K+E>this.DB?(this[this.t-1]|=(ce&(1<<this.DB-K)-1)<<K,this[this.t++]=ce>>this.DB-K):this[this.t-1]|=ce<<K,(K+=E)>=this.DB&&(K-=this.DB))}E==8&&(128&h[0])!=0&&(this.s=-1,K>0&&(this[this.t-1]|=(1<<this.DB-K)-1<<K)),this.clamp(),q&&D.ZERO.subTo(this,this)},D.prototype.clamp=function(){for(var h=this.s&this.DM;this.t>0&&this[this.t-1]==h;)--this.t},D.prototype.dlShiftTo=function(h,y){var E;for(E=this.t-1;E>=0;--E)y[E+h]=this[E];for(E=h-1;E>=0;--E)y[E]=0;y.t=this.t+h,y.s=this.s},D.prototype.drShiftTo=function(h,y){for(var E=h;E<this.t;++E)y[E-h]=this[E];y.t=Math.max(this.t-h,0),y.s=this.s},D.prototype.lShiftTo=function(h,y){var E,I=h%this.DB,q=this.DB-I,K=(1<<q)-1,ce=Math.floor(h/this.DB),ee=this.s<<I&this.DM;for(E=this.t-1;E>=0;--E)y[E+ce+1]=this[E]>>q|ee,ee=(this[E]&K)<<I;for(E=ce-1;E>=0;--E)y[E]=0;y[ce]=ee,y.t=this.t+ce+1,y.s=this.s,y.clamp()},D.prototype.rShiftTo=function(h,y){y.s=this.s;var E=Math.floor(h/this.DB);if(E>=this.t)y.t=0;else{var I=h%this.DB,q=this.DB-I,K=(1<<I)-1;y[0]=this[E]>>I;for(var ce=E+1;ce<this.t;++ce)y[ce-E-1]|=(this[ce]&K)<<q,y[ce-E]=this[ce]>>I;I>0&&(y[this.t-E-1]|=(this.s&K)<<q),y.t=this.t-E,y.clamp()}},D.prototype.subTo=function(h,y){for(var E=0,I=0,q=Math.min(h.t,this.t);E<q;)I+=this[E]-h[E],y[E++]=I&this.DM,I>>=this.DB;if(h.t<this.t){for(I-=h.s;E<this.t;)I+=this[E],y[E++]=I&this.DM,I>>=this.DB;I+=this.s}else{for(I+=this.s;E<h.t;)I-=h[E],y[E++]=I&this.DM,I>>=this.DB;I-=h.s}y.s=I<0?-1:0,I<-1?y[E++]=this.DV+I:I>0&&(y[E++]=I),y.t=E,y.clamp()},D.prototype.multiplyTo=function(h,y){var E=this.abs(),I=h.abs(),q=E.t;for(y.t=q+I.t;--q>=0;)y[q]=0;for(q=0;q<I.t;++q)y[q+E.t]=E.am(0,I[q],y,q,0,E.t);y.s=0,y.clamp(),this.s!=h.s&&D.ZERO.subTo(y,y)},D.prototype.squareTo=function(h){for(var y=this.abs(),E=h.t=2*y.t;--E>=0;)h[E]=0;for(E=0;E<y.t-1;++E){var I=y.am(E,y[E],h,2*E,0,1);(h[E+y.t]+=y.am(E+1,2*y[E],h,2*E+1,I,y.t-E-1))>=y.DV&&(h[E+y.t]-=y.DV,h[E+y.t+1]=1)}h.t>0&&(h[h.t-1]+=y.am(E,y[E],h,2*E,0,1)),h.s=0,h.clamp()},D.prototype.divRemTo=function(h,y,E){var I=h.abs();if(!(I.t<=0)){var q=this.abs();if(q.t<I.t)return y?.fromInt(0),void(E!=null&&this.copyTo(E));E==null&&(E=V());var K=V(),ce=this.s,ee=h.s,se=this.DB-ae(I[I.t-1]);se>0?(I.lShiftTo(se,K),q.lShiftTo(se,E)):(I.copyTo(K),q.copyTo(E));var oe=K.t,pe=K[oe-1];if(pe!=0){var Se=pe*(1<<this.F1)+(oe>1?K[oe-2]>>this.F2:0),Ee=this.FV/Se,Pe=(1<<this.F1)/Se,$e=1<<this.F2,Le=E.t,Z=Le-oe,fe=y??V();for(K.dlShiftTo(Z,fe),E.compareTo(fe)>=0&&(E[E.t++]=1,E.subTo(fe,E)),D.ONE.dlShiftTo(oe,fe),fe.subTo(K,K);K.t<oe;)K[K.t++]=0;for(;--Z>=0;){var ye=E[--Le]==pe?this.DM:Math.floor(E[Le]*Ee+(E[Le-1]+$e)*Pe);if((E[Le]+=K.am(0,ye,E,Z,0,oe))<ye)for(K.dlShiftTo(Z,fe),E.subTo(fe,E);E[Le]<--ye;)E.subTo(fe,E)}y!=null&&(E.drShiftTo(oe,y),ce!=ee&&D.ZERO.subTo(y,y)),E.t=oe,E.clamp(),se>0&&E.rShiftTo(se,E),ce<0&&D.ZERO.subTo(E,E)}}},D.prototype.invDigit=function(){if(this.t<1)return 0;var h=this[0];if((1&h)==0)return 0;var y=3&h;return(y=(y=(y=(y=y*(2-(15&h)*y)&15)*(2-(255&h)*y)&255)*(2-((65535&h)*y&65535))&65535)*(2-h*y%this.DV)%this.DV)>0?this.DV-y:-y},D.prototype.isEven=function(){return(this.t>0?1&this[0]:this.s)==0},D.prototype.exp=function(h,y){if(h>4294967295||h<1)return D.ONE;var E=V(),I=V(),q=y.convert(this),K=ae(h)-1;for(q.copyTo(E);--K>=0;)if(y.sqrTo(E,I),(h&1<<K)>0)y.mulTo(I,q,E);else{var ce=E;E=I,I=ce}return y.revert(E)},D.prototype.toString=function(h){if(this.s<0)return"-"+this.negate().toString(h);var y;if(h==16)y=4;else if(h==8)y=3;else if(h==2)y=1;else if(h==32)y=5;else{if(h!=4)return this.toRadix(h);y=2}var E,I=(1<<y)-1,q=!1,K="",ce=this.t,ee=this.DB-ce*this.DB%y;if(ce-- >0)for(ee<this.DB&&(E=this[ce]>>ee)>0&&(q=!0,K=Ce(E));ce>=0;)ee<y?(E=(this[ce]&(1<<ee)-1)<<y-ee,E|=this[--ce]>>(ee+=this.DB-y)):(E=this[ce]>>(ee-=y)&I,ee<=0&&(ee+=this.DB,--ce)),E>0&&(q=!0),q&&(K+=Ce(E));return q?K:"0"},D.prototype.negate=function(){var h=V();return D.ZERO.subTo(this,h),h},D.prototype.abs=function(){return this.s<0?this.negate():this},D.prototype.compareTo=function(h){var y=this.s-h.s;if(y!=0)return y;var E=this.t;if((y=E-h.t)!=0)return this.s<0?-y:y;for(;--E>=0;)if((y=this[E]-h[E])!=0)return y;return 0},D.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+ae(this[this.t-1]^this.s&this.DM)},D.prototype.mod=function(h){var y=V();return this.abs().divRemTo(h,null,y),this.s<0&&y.compareTo(D.ZERO)>0&&h.subTo(y,y),y},D.prototype.modPowInt=function(h,y){var E;return E=h<256||y.isEven()?new ve(y):new L(y),this.exp(h,E)},D.ZERO=ze(0),D.ONE=ze(1),Oe.prototype.convert=te,Oe.prototype.revert=te,Oe.prototype.mulTo=function(h,y,E){h.multiplyTo(y,E)},Oe.prototype.sqrTo=function(h,y){h.squareTo(y)},le.prototype.convert=function(h){if(h.s<0||h.t>2*this.m.t)return h.mod(this.m);if(h.compareTo(this.m)<0)return h;var y=V();return h.copyTo(y),this.reduce(y),y},le.prototype.revert=function(h){return h},le.prototype.reduce=function(h){for(h.drShiftTo(this.m.t-1,this.r2),h.t>this.m.t+1&&(h.t=this.m.t+1,h.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);h.compareTo(this.r2)<0;)h.dAddOffset(1,this.m.t+1);for(h.subTo(this.r2,h);h.compareTo(this.m)>=0;)h.subTo(this.m,h)},le.prototype.mulTo=function(h,y,E){h.multiplyTo(y,E),this.reduce(E)},le.prototype.sqrTo=function(h,y){h.squareTo(y),this.reduce(y)};var Te=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],G=(1<<26)/Te[Te.length-1];function P(){this.i=0,this.j=0,this.S=new Array}D.prototype.chunkSize=function(h){return Math.floor(Math.LN2*this.DB/Math.log(h))},D.prototype.toRadix=function(h){if(h==null&&(h=10),this.signum()==0||h<2||h>36)return"0";var y=this.chunkSize(h),E=Math.pow(h,y),I=ze(E),q=V(),K=V(),ce="";for(this.divRemTo(I,q,K);q.signum()>0;)ce=(E+K.intValue()).toString(h).substr(1)+ce,q.divRemTo(I,q,K);return K.intValue().toString(h)+ce},D.prototype.fromRadix=function(h,y){this.fromInt(0),y==null&&(y=10);for(var E=this.chunkSize(y),I=Math.pow(y,E),q=!1,K=0,ce=0,ee=0;ee<h.length;++ee){var se=Fe(h,ee);se<0?h.charAt(ee)=="-"&&this.signum()==0&&(q=!0):(ce=y*ce+se,++K>=E&&(this.dMultiply(I),this.dAddOffset(ce,0),K=0,ce=0))}K>0&&(this.dMultiply(Math.pow(y,K)),this.dAddOffset(ce,0)),q&&D.ZERO.subTo(this,this)},D.prototype.fromNumber=function(h,y,E){if(typeof y=="number")if(h<2)this.fromInt(1);else for(this.fromNumber(h,E),this.testBit(h-1)||this.bitwiseTo(D.ONE.shiftLeft(h-1),xe,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(y);)this.dAddOffset(2,0),this.bitLength()>h&&this.subTo(D.ONE.shiftLeft(h-1),this);else{var I=new Array,q=7&h;I.length=1+(h>>3),y.nextBytes(I),q>0?I[0]&=(1<<q)-1:I[0]=0,this.fromString(I,256)}},D.prototype.bitwiseTo=function(h,y,E){var I,q,K=Math.min(h.t,this.t);for(I=0;I<K;++I)E[I]=y(this[I],h[I]);if(h.t<this.t){for(q=h.s&this.DM,I=K;I<this.t;++I)E[I]=y(this[I],q);E.t=this.t}else{for(q=this.s&this.DM,I=K;I<h.t;++I)E[I]=y(q,h[I]);E.t=h.t}E.s=y(this.s,h.s),E.clamp()},D.prototype.changeBit=function(h,y){var E=D.ONE.shiftLeft(h);return this.bitwiseTo(E,y,E),E},D.prototype.addTo=function(h,y){for(var E=0,I=0,q=Math.min(h.t,this.t);E<q;)I+=this[E]+h[E],y[E++]=I&this.DM,I>>=this.DB;if(h.t<this.t){for(I+=h.s;E<this.t;)I+=this[E],y[E++]=I&this.DM,I>>=this.DB;I+=this.s}else{for(I+=this.s;E<h.t;)I+=h[E],y[E++]=I&this.DM,I>>=this.DB;I+=h.s}y.s=I<0?-1:0,I>0?y[E++]=I:I<-1&&(y[E++]=this.DV+I),y.t=E,y.clamp()},D.prototype.dMultiply=function(h){this[this.t]=this.am(0,h-1,this,0,0,this.t),++this.t,this.clamp()},D.prototype.dAddOffset=function(h,y){if(h!=0){for(;this.t<=y;)this[this.t++]=0;for(this[y]+=h;this[y]>=this.DV;)this[y]-=this.DV,++y>=this.t&&(this[this.t++]=0),++this[y]}},D.prototype.multiplyLowerTo=function(h,y,E){var I,q=Math.min(this.t+h.t,y);for(E.s=0,E.t=q;q>0;)E[--q]=0;for(I=E.t-this.t;q<I;++q)E[q+this.t]=this.am(0,h[q],E,q,0,this.t);for(I=Math.min(h.t,y);q<I;++q)this.am(0,h[q],E,q,0,y-q);E.clamp()},D.prototype.multiplyUpperTo=function(h,y,E){--y;var I=E.t=this.t+h.t-y;for(E.s=0;--I>=0;)E[I]=0;for(I=Math.max(y-this.t,0);I<h.t;++I)E[this.t+I-y]=this.am(y-I,h[I],E,0,0,this.t+I-y);E.clamp(),E.drShiftTo(1,E)},D.prototype.modInt=function(h){if(h<=0)return 0;var y=this.DV%h,E=this.s<0?h-1:0;if(this.t>0)if(y==0)E=this[0]%h;else for(var I=this.t-1;I>=0;--I)E=(y*E+this[I])%h;return E},D.prototype.millerRabin=function(h){var y=this.subtract(D.ONE),E=y.getLowestSetBit();if(E<=0)return!1;var I=y.shiftRight(E);(h=h+1>>1)>Te.length&&(h=Te.length);for(var q=V(),K=0;K<h;++K){q.fromInt(Te[Math.floor(Math.random()*Te.length)]);var ce=q.modPow(I,this);if(ce.compareTo(D.ONE)!=0&&ce.compareTo(y)!=0){for(var ee=1;ee++<E&&ce.compareTo(y)!=0;)if((ce=ce.modPowInt(2,this)).compareTo(D.ONE)==0)return!1;if(ce.compareTo(y)!=0)return!1}}return!0},D.prototype.clone=function(){var h=V();return this.copyTo(h),h},D.prototype.intValue=function(){if(this.s<0){if(this.t==1)return this[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this[0];if(this.t==0)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},D.prototype.byteValue=function(){return this.t==0?this.s:this[0]<<24>>24},D.prototype.shortValue=function(){return this.t==0?this.s:this[0]<<16>>16},D.prototype.signum=function(){return this.s<0?-1:this.t<=0||this.t==1&&this[0]<=0?0:1},D.prototype.toByteArray=function(){var h=this.t,y=new Array;y[0]=this.s;var E,I=this.DB-h*this.DB%8,q=0;if(h-- >0)for(I<this.DB&&(E=this[h]>>I)!=(this.s&this.DM)>>I&&(y[q++]=E|this.s<<this.DB-I);h>=0;)I<8?(E=(this[h]&(1<<I)-1)<<8-I,E|=this[--h]>>(I+=this.DB-8)):(E=this[h]>>(I-=8)&255,I<=0&&(I+=this.DB,--h)),(128&E)!=0&&(E|=-256),q==0&&(128&this.s)!=(128&E)&&++q,(q>0||E!=this.s)&&(y[q++]=E);return y},D.prototype.equals=function(h){return this.compareTo(h)==0},D.prototype.min=function(h){return this.compareTo(h)<0?this:h},D.prototype.max=function(h){return this.compareTo(h)>0?this:h},D.prototype.and=function(h){var y=V();return this.bitwiseTo(h,ie,y),y},D.prototype.or=function(h){var y=V();return this.bitwiseTo(h,xe,y),y},D.prototype.xor=function(h){var y=V();return this.bitwiseTo(h,ue,y),y},D.prototype.andNot=function(h){var y=V();return this.bitwiseTo(h,De,y),y},D.prototype.not=function(){for(var h=V(),y=0;y<this.t;++y)h[y]=this.DM&~this[y];return h.t=this.t,h.s=~this.s,h},D.prototype.shiftLeft=function(h){var y=V();return h<0?this.rShiftTo(-h,y):this.lShiftTo(h,y),y},D.prototype.shiftRight=function(h){var y=V();return h<0?this.lShiftTo(-h,y):this.rShiftTo(h,y),y},D.prototype.getLowestSetBit=function(){for(var h=0;h<this.t;++h)if(this[h]!=0)return h*this.DB+ke(this[h]);return this.s<0?this.t*this.DB:-1},D.prototype.bitCount=function(){for(var h=0,y=this.s&this.DM,E=0;E<this.t;++E)h+=We(this[E]^y);return h},D.prototype.testBit=function(h){var y=Math.floor(h/this.DB);return y>=this.t?this.s!=0:(this[y]&1<<h%this.DB)!=0},D.prototype.setBit=function(h){return this.changeBit(h,xe)},D.prototype.clearBit=function(h){return this.changeBit(h,De)},D.prototype.flipBit=function(h){return this.changeBit(h,ue)},D.prototype.add=function(h){var y=V();return this.addTo(h,y),y},D.prototype.subtract=function(h){var y=V();return this.subTo(h,y),y},D.prototype.multiply=function(h){var y=V();return this.multiplyTo(h,y),y},D.prototype.divide=function(h){var y=V();return this.divRemTo(h,y,null),y},D.prototype.remainder=function(h){var y=V();return this.divRemTo(h,null,y),y},D.prototype.divideAndRemainder=function(h){var y=V(),E=V();return this.divRemTo(h,y,E),new Array(y,E)},D.prototype.modPow=function(h,y){var E,I,q=h.bitLength(),K=ze(1);if(q<=0)return K;E=q<18?1:q<48?3:q<144?4:q<768?5:6,I=q<8?new ve(y):y.isEven()?new le(y):new L(y);var ce=new Array,ee=3,se=E-1,oe=(1<<E)-1;if(ce[1]=I.convert(this),E>1){var pe=V();for(I.sqrTo(ce[1],pe);ee<=oe;)ce[ee]=V(),I.mulTo(pe,ce[ee-2],ce[ee]),ee+=2}var Se,Ee,Pe=h.t-1,$e=!0,Le=V();for(q=ae(h[Pe])-1;Pe>=0;){for(q>=se?Se=h[Pe]>>q-se&oe:(Se=(h[Pe]&(1<<q+1)-1)<<se-q,Pe>0&&(Se|=h[Pe-1]>>this.DB+q-se)),ee=E;(1&Se)==0;)Se>>=1,--ee;if((q-=ee)<0&&(q+=this.DB,--Pe),$e)ce[Se].copyTo(K),$e=!1;else{for(;ee>1;)I.sqrTo(K,Le),I.sqrTo(Le,K),ee-=2;ee>0?I.sqrTo(K,Le):(Ee=K,K=Le,Le=Ee),I.mulTo(Le,ce[Se],K)}for(;Pe>=0&&(h[Pe]&1<<q)==0;)I.sqrTo(K,Le),Ee=K,K=Le,Le=Ee,--q<0&&(q=this.DB-1,--Pe)}return I.revert(K)},D.prototype.modInverse=function(h){var y=h.isEven();if(this.isEven()&&y||h.signum()==0)return D.ZERO;for(var E=h.clone(),I=this.clone(),q=ze(1),K=ze(0),ce=ze(0),ee=ze(1);E.signum()!=0;){for(;E.isEven();)E.rShiftTo(1,E),y?(q.isEven()&&K.isEven()||(q.addTo(this,q),K.subTo(h,K)),q.rShiftTo(1,q)):K.isEven()||K.subTo(h,K),K.rShiftTo(1,K);for(;I.isEven();)I.rShiftTo(1,I),y?(ce.isEven()&&ee.isEven()||(ce.addTo(this,ce),ee.subTo(h,ee)),ce.rShiftTo(1,ce)):ee.isEven()||ee.subTo(h,ee),ee.rShiftTo(1,ee);E.compareTo(I)>=0?(E.subTo(I,E),y&&q.subTo(ce,q),K.subTo(ee,K)):(I.subTo(E,I),y&&ce.subTo(q,ce),ee.subTo(K,ee))}return I.compareTo(D.ONE)!=0?D.ZERO:ee.compareTo(h)>=0?ee.subtract(h):ee.signum()<0?(ee.addTo(h,ee),ee.signum()<0?ee.add(h):ee):ee},D.prototype.pow=function(h){return this.exp(h,new Oe)},D.prototype.gcd=function(h){var y=this.s<0?this.negate():this.clone(),E=h.s<0?h.negate():h.clone();if(y.compareTo(E)<0){var I=y;y=E,E=I}var q=y.getLowestSetBit(),K=E.getLowestSetBit();if(K<0)return y;for(q<K&&(K=q),K>0&&(y.rShiftTo(K,y),E.rShiftTo(K,E));y.signum()>0;)(q=y.getLowestSetBit())>0&&y.rShiftTo(q,y),(q=E.getLowestSetBit())>0&&E.rShiftTo(q,E),y.compareTo(E)>=0?(y.subTo(E,y),y.rShiftTo(1,y)):(E.subTo(y,E),E.rShiftTo(1,E));return K>0&&E.lShiftTo(K,E),E},D.prototype.isProbablePrime=function(h){var y,E=this.abs();if(E.t==1&&E[0]<=Te[Te.length-1]){for(y=0;y<Te.length;++y)if(E[0]==Te[y])return!0;return!1}if(E.isEven())return!1;for(y=1;y<Te.length;){for(var I=Te[y],q=y+1;q<Te.length&&I<G;)I*=Te[q++];for(I=E.modInt(I);y<q;)if(I%Te[y++]==0)return!1}return E.millerRabin(h)},D.prototype.square=function(){var h=V();return this.squareTo(h),h},P.prototype.init=function(h){var y,E,I;for(y=0;y<256;++y)this.S[y]=y;for(E=0,y=0;y<256;++y)E=E+this.S[y]+h[y%h.length]&255,I=this.S[y],this.S[y]=this.S[E],this.S[E]=I;this.i=0,this.j=0},P.prototype.next=function(){var h;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,h=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=h,this.S[h+this.S[this.i]&255]};var x,A,O;function H(){(function(h){A[O++]^=255&h,A[O++]^=h>>8&255,A[O++]^=h>>16&255,A[O++]^=h>>24&255,O>=256&&(O-=256)})(new Date().getTime())}if(A==null){var Q;if(A=new Array,O=0,_!==void 0&&(_.crypto!==void 0||_.msCrypto!==void 0)){var de=_.crypto||_.msCrypto;if(de.getRandomValues){var M=new Uint8Array(32);for(de.getRandomValues(M),Q=0;Q<32;++Q)A[O++]=M[Q]}else if(v.appName=="Netscape"&&v.appVersion<"5"){var ne=_.crypto.random(32);for(Q=0;Q<ne.length;++Q)A[O++]=255&ne.charCodeAt(Q)}}for(;O<256;)Q=Math.floor(65536*Math.random()),A[O++]=Q>>>8,A[O++]=255&Q;O=0,H()}function ge(){if(x==null){for(H(),(x=(function(){return new P})()).init(A),O=0;O<A.length;++O)A[O]=0;O=0}return x.next()}function Y(){}function Be(p,h){return new D(p,h)}function Je(p,h,y){for(var E="",I=0;E.length<h;)E+=y(String.fromCharCode.apply(String,p.concat([(4278190080&I)>>24,(16711680&I)>>16,(65280&I)>>8,255&I]))),I+=1;return E}function Ne(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}function Ze(p,h){this.x=h,this.q=p}function B(p,h,y,E){this.curve=p,this.x=h,this.y=y,this.z=E??D.ONE,this.zinv=null}function R(p,h,y){this.q=p,this.a=this.fromBigInteger(h),this.b=this.fromBigInteger(y),this.infinity=new B(this,null,null)}Y.prototype.nextBytes=function(h){var y;for(y=0;y<h.length;++y)h[y]=ge()},Ne.prototype.doPublic=function(h){return h.modPowInt(this.e,this.n)},Ne.prototype.setPublic=function(h,y){if(this.isPublic=!0,this.isPrivate=!1,typeof h!="string")this.n=h,this.e=y;else{if(!(h!=null&&y!=null&&h.length>0&&y.length>0))throw"Invalid RSA public key";this.n=Be(h,16),this.e=parseInt(y,16)}},Ne.prototype.encrypt=function(h){var y=(function(K,ce){if(ce<K.length+11)throw"Message too long for RSA";for(var ee=new Array,se=K.length-1;se>=0&&ce>0;){var oe=K.charCodeAt(se--);oe<128?ee[--ce]=oe:oe>127&&oe<2048?(ee[--ce]=63&oe|128,ee[--ce]=oe>>6|192):(ee[--ce]=63&oe|128,ee[--ce]=oe>>6&63|128,ee[--ce]=oe>>12|224)}ee[--ce]=0;for(var pe=new Y,Se=new Array;ce>2;){for(Se[0]=0;Se[0]==0;)pe.nextBytes(Se);ee[--ce]=Se[0]}return ee[--ce]=2,ee[--ce]=0,new D(ee)})(h,this.n.bitLength()+7>>3);if(y==null)return null;var E=this.doPublic(y);if(E==null)return null;var I=E.toString(16);return(1&I.length)==0?I:"0"+I},Ne.prototype.encryptOAEP=function(h,y,E){var I=(function(ee,se,oe,pe){var Se=F.crypto.MessageDigest,Ee=F.crypto.Util,Pe=null;if(oe||(oe="sha1"),typeof oe=="string"&&(Pe=Se.getCanonicalAlgName(oe),pe=Se.getHashLength(Pe),oe=function(Ke){return At(Ee.hashHex(It(Ke),Pe))}),ee.length+2*pe+2>se)throw"Message too long for RSA";var $e,Le="";for($e=0;$e<se-ee.length-2*pe-2;$e+=1)Le+="\0";var Z=oe("")+Le+""+ee,fe=new Array(pe);new Y().nextBytes(fe);var ye=Je(fe,Z.length,oe),be=[];for($e=0;$e<Z.length;$e+=1)be[$e]=Z.charCodeAt($e)^ye.charCodeAt($e);var Ue=Je(be,fe.length,oe),Me=[0];for($e=0;$e<fe.length;$e+=1)Me[$e+1]=fe[$e]^Ue.charCodeAt($e);return new D(Me.concat(be))})(h,this.n.bitLength()+7>>3,y,E);if(I==null)return null;var q=this.doPublic(I);if(q==null)return null;var K=q.toString(16);return(1&K.length)==0?K:"0"+K},Ne.prototype.type="RSA",Ze.prototype.equals=function(h){return h==this||this.q.equals(h.q)&&this.x.equals(h.x)},Ze.prototype.toBigInteger=function(){return this.x},Ze.prototype.negate=function(){return new Ze(this.q,this.x.negate().mod(this.q))},Ze.prototype.add=function(h){return new Ze(this.q,this.x.add(h.toBigInteger()).mod(this.q))},Ze.prototype.subtract=function(h){return new Ze(this.q,this.x.subtract(h.toBigInteger()).mod(this.q))},Ze.prototype.multiply=function(h){return new Ze(this.q,this.x.multiply(h.toBigInteger()).mod(this.q))},Ze.prototype.square=function(){return new Ze(this.q,this.x.square().mod(this.q))},Ze.prototype.divide=function(h){return new Ze(this.q,this.x.multiply(h.toBigInteger().modInverse(this.q)).mod(this.q))},B.prototype.getX=function(){return this.zinv==null&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))},B.prototype.getY=function(){return this.zinv==null&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))},B.prototype.equals=function(h){return h==this||(this.isInfinity()?h.isInfinity():h.isInfinity()?this.isInfinity():!!h.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(h.z)).mod(this.curve.q).equals(D.ZERO)&&h.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(h.z)).mod(this.curve.q).equals(D.ZERO))},B.prototype.isInfinity=function(){return this.x==null&&this.y==null||this.z.equals(D.ZERO)&&!this.y.toBigInteger().equals(D.ZERO)},B.prototype.negate=function(){return new B(this.curve,this.x,this.y.negate(),this.z)},B.prototype.add=function(h){if(this.isInfinity())return h;if(h.isInfinity())return this;var y=h.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(h.z)).mod(this.curve.q),E=h.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(h.z)).mod(this.curve.q);if(D.ZERO.equals(E))return D.ZERO.equals(y)?this.twice():this.curve.getInfinity();var I=new D("3"),q=this.x.toBigInteger(),K=this.y.toBigInteger(),ce=(h.x.toBigInteger(),h.y.toBigInteger(),E.square()),ee=ce.multiply(E),se=q.multiply(ce),oe=y.square().multiply(this.z),pe=oe.subtract(se.shiftLeft(1)).multiply(h.z).subtract(ee).multiply(E).mod(this.curve.q),Se=se.multiply(I).multiply(y).subtract(K.multiply(ee)).subtract(oe.multiply(y)).multiply(h.z).add(y.multiply(ee)).mod(this.curve.q),Ee=ee.multiply(this.z).multiply(h.z).mod(this.curve.q);return new B(this.curve,this.curve.fromBigInteger(pe),this.curve.fromBigInteger(Se),Ee)},B.prototype.twice=function(){if(this.isInfinity())return this;if(this.y.toBigInteger().signum()==0)return this.curve.getInfinity();var h=new D("3"),y=this.x.toBigInteger(),E=this.y.toBigInteger(),I=E.multiply(this.z),q=I.multiply(E).mod(this.curve.q),K=this.curve.a.toBigInteger(),ce=y.square().multiply(h);D.ZERO.equals(K)||(ce=ce.add(this.z.square().multiply(K)));var ee=(ce=ce.mod(this.curve.q)).square().subtract(y.shiftLeft(3).multiply(q)).shiftLeft(1).multiply(I).mod(this.curve.q),se=ce.multiply(h).multiply(y).subtract(q.shiftLeft(1)).shiftLeft(2).multiply(q).subtract(ce.square().multiply(ce)).mod(this.curve.q),oe=I.square().multiply(I).shiftLeft(3).mod(this.curve.q);return new B(this.curve,this.curve.fromBigInteger(ee),this.curve.fromBigInteger(se),oe)},B.prototype.multiply=function(h){if(this.isInfinity())return this;if(h.signum()==0)return this.curve.getInfinity();var y,E=h,I=E.multiply(new D("3")),q=this.negate(),K=this,ce=this.curve.q.subtract(h),ee=ce.multiply(new D("3")),se=new B(this.curve,this.x,this.y),oe=se.negate();for(y=I.bitLength()-2;y>0;--y){K=K.twice();var pe=I.testBit(y);pe!=E.testBit(y)&&(K=K.add(pe?this:q))}for(y=ee.bitLength()-2;y>0;--y){se=se.twice();var Se=ee.testBit(y);Se!=ce.testBit(y)&&(se=se.add(Se?se:oe))}return K},B.prototype.multiplyTwo=function(h,y,E){var I;I=h.bitLength()>E.bitLength()?h.bitLength()-1:E.bitLength()-1;for(var q=this.curve.getInfinity(),K=this.add(y);I>=0;)q=q.twice(),h.testBit(I)?q=E.testBit(I)?q.add(K):q.add(this):E.testBit(I)&&(q=q.add(y)),--I;return q},R.prototype.getQ=function(){return this.q},R.prototype.getA=function(){return this.a},R.prototype.getB=function(){return this.b},R.prototype.equals=function(h){return h==this||this.q.equals(h.q)&&this.a.equals(h.a)&&this.b.equals(h.b)},R.prototype.getInfinity=function(){return this.infinity},R.prototype.fromBigInteger=function(h){return new Ze(this.q,h)},R.prototype.decodePointHex=function(h){switch(parseInt(h.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:return null;case 4:case 6:case 7:var y=(h.length-2)/2,E=h.substr(2,y),I=h.substr(y+2,y);return new B(this,this.fromBigInteger(new D(E,16)),this.fromBigInteger(new D(I,16)));default:return null}},Ze.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)},B.prototype.getEncoded=function(p){var h=function(K,ce){var ee=K.toByteArrayUnsigned();if(ce<ee.length)ee=ee.slice(ee.length-ce);else for(;ce>ee.length;)ee.unshift(0);return ee},y=this.getX().toBigInteger(),E=this.getY().toBigInteger(),I=h(y,32);return p?E.isEven()?I.unshift(2):I.unshift(3):(I.unshift(4),I=I.concat(h(E,32))),I},B.decodeFrom=function(p,h){h[0];var y=h.length-1,E=h.slice(1,1+y/2),I=h.slice(1+y/2,1+y);E.unshift(0),I.unshift(0);var q=new D(E),K=new D(I);return new B(p,p.fromBigInteger(q),p.fromBigInteger(K))},B.decodeFromHex=function(p,h){h.substr(0,2);var y=h.length-2,E=h.substr(2,y/2),I=h.substr(2+y/2,y/2),q=new D(E,16),K=new D(I,16);return new B(p,p.fromBigInteger(q),p.fromBigInteger(K))},B.prototype.add2D=function(p){if(this.isInfinity())return p;if(p.isInfinity())return this;if(this.x.equals(p.x))return this.y.equals(p.y)?this.twice():this.curve.getInfinity();var h=p.x.subtract(this.x),y=p.y.subtract(this.y).divide(h),E=y.square().subtract(this.x).subtract(p.x),I=y.multiply(this.x.subtract(E)).subtract(this.y);return new B(this.curve,E,I)},B.prototype.twice2D=function(){if(this.isInfinity())return this;if(this.y.toBigInteger().signum()==0)return this.curve.getInfinity();var p=this.curve.fromBigInteger(D.valueOf(2)),h=this.curve.fromBigInteger(D.valueOf(3)),y=this.x.square().multiply(h).add(this.curve.a).divide(this.y.multiply(p)),E=y.square().subtract(this.x.multiply(p)),I=y.multiply(this.x.subtract(E)).subtract(this.y);return new B(this.curve,E,I)},B.prototype.multiply2D=function(p){if(this.isInfinity())return this;if(p.signum()==0)return this.curve.getInfinity();var h,y=p,E=y.multiply(new D("3")),I=this.negate(),q=this;for(h=E.bitLength()-2;h>0;--h){q=q.twice();var K=E.testBit(h);K!=y.testBit(h)&&(q=q.add2D(K?this:I))}return q},B.prototype.isOnCurve=function(){var p=this.getX().toBigInteger(),h=this.getY().toBigInteger(),y=this.curve.getA().toBigInteger(),E=this.curve.getB().toBigInteger(),I=this.curve.getQ(),q=h.multiply(h).mod(I),K=p.multiply(p).multiply(p).add(y.multiply(p)).add(E).mod(I);return q.equals(K)},B.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"},B.prototype.validate=function(){var p=this.curve.getQ();if(this.isInfinity())throw new Error("Point is at infinity.");var h=this.getX().toBigInteger(),y=this.getY().toBigInteger();if(h.compareTo(D.ONE)<0||h.compareTo(p.subtract(D.ONE))>0)throw new Error("x coordinate out of bounds");if(y.compareTo(D.ONE)<0||y.compareTo(p.subtract(D.ONE))>0)throw new Error("y coordinate out of bounds");if(!this.isOnCurve())throw new Error("Point is not on the curve.");if(this.multiply(p).isInfinity())throw new Error("Point is not a scalar multiple of G.");return!0};var N=(function(){var p=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)|(?:"(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))*"))',"g"),h=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),y={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:`
|
|
219
|
+
`,r:"\r",t:" "};function E(K,ce,ee){return ce?y[ce]:String.fromCharCode(parseInt(ee,16))}var I=new String(""),q=Object.hasOwnProperty;return function(K,ce){var ee,se,oe=K.match(p),pe=oe[0],Se=!1;pe==="{"?ee={}:pe==="["?ee=[]:(ee=[],Se=!0);for(var Ee=[ee],Pe=1-Se,$e=oe.length;Pe<$e;++Pe){var Le;switch((pe=oe[Pe]).charCodeAt(0)){default:(Le=Ee[0])[se||Le.length]=+pe,se=void 0;break;case 34:if((pe=pe.substring(1,pe.length-1)).indexOf("\\")!==-1&&(pe=pe.replace(h,E)),Le=Ee[0],!se){if(!(Le instanceof Array)){se=pe||I;break}se=Le.length}Le[se]=pe,se=void 0;break;case 91:Le=Ee[0],Ee.unshift(Le[se||Le.length]=[]),se=void 0;break;case 93:Ee.shift();break;case 102:(Le=Ee[0])[se||Le.length]=!1,se=void 0;break;case 110:(Le=Ee[0])[se||Le.length]=null,se=void 0;break;case 116:(Le=Ee[0])[se||Le.length]=!0,se=void 0;break;case 123:Le=Ee[0],Ee.unshift(Le[se||Le.length]={}),se=void 0;break;case 125:Ee.shift()}}if(Se){if(Ee.length!==1)throw new Error;ee=ee[0]}else if(Ee.length)throw new Error;return ce&&(ee=(function Z(fe,ye){var be=fe[ye];if(be&&(be===void 0?"undefined":w(be))==="object"){var Ue=null;for(var Me in be)if(q.call(be,Me)&&be!==fe){var Ye=Z(be,Me);Ye!==void 0?be[Me]=Ye:(Ue||(Ue=[]),Ue.push(Me))}if(Ue)for(var Ke=Ue.length;--Ke>=0;)delete be[Ue[Ke]]}return ce.call(fe,ye,be)})({"":ee},"")),ee}})();F!==void 0&&F||(r.KJUR=F={}),F.asn1!==void 0&&F.asn1||(F.asn1={}),F.asn1.ASN1Util=new function(){this.integerToByteHex=function(p){var h=p.toString(16);return h.length%2==1&&(h="0"+h),h},this.bigIntToMinTwosComplementsHex=function(p){var h=p.toString(16);if(h.substr(0,1)!="-")h.length%2==1?h="0"+h:h.match(/^[0-7]/)||(h="00"+h);else{var y=h.substr(1).length;y%2==1?y+=1:h.match(/^[0-7]/)||(y+=2);for(var E="",I=0;I<y;I++)E+="f";h=new D(E,16).xor(p).add(D.ONE).toString(16).replace(/^-/,"")}return h},this.getPEMStringFromHex=function(p,h){return Ie(p,h)},this.newObject=function(p){var h=F.asn1,y=h.ASN1Object,E=h.DERBoolean,I=h.DERInteger,q=h.DERBitString,K=h.DEROctetString,ce=h.DERNull,ee=h.DERObjectIdentifier,se=h.DEREnumerated,oe=h.DERUTF8String,pe=h.DERNumericString,Se=h.DERPrintableString,Ee=h.DERTeletexString,Pe=h.DERIA5String,$e=h.DERUTCTime,Le=h.DERGeneralizedTime,Z=h.DERVisibleString,fe=h.DERBMPString,ye=h.DERSequence,be=h.DERSet,Ue=h.DERTaggedObject,Me=h.ASN1Util.newObject;if(p instanceof h.ASN1Object)return p;var Ye=Object.keys(p);if(Ye.length!=1)throw new Error("key of param shall be only one.");var Ke=Ye[0];if(":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":"+Ke+":")==-1)throw new Error("undefined key: "+Ke);if(Ke=="bool")return new E(p[Ke]);if(Ke=="int")return new I(p[Ke]);if(Ke=="bitstr")return new q(p[Ke]);if(Ke=="octstr")return new K(p[Ke]);if(Ke=="null")return new ce(p[Ke]);if(Ke=="oid")return new ee(p[Ke]);if(Ke=="enum")return new se(p[Ke]);if(Ke=="utf8str")return new oe(p[Ke]);if(Ke=="numstr")return new pe(p[Ke]);if(Ke=="prnstr")return new Se(p[Ke]);if(Ke=="telstr")return new Ee(p[Ke]);if(Ke=="ia5str")return new Pe(p[Ke]);if(Ke=="utctime")return new $e(p[Ke]);if(Ke=="gentime")return new Le(p[Ke]);if(Ke=="visstr")return new Z(p[Ke]);if(Ke=="bmpstr")return new fe(p[Ke]);if(Ke=="asn1")return new y(p[Ke]);if(Ke=="seq"){for(var st=p[Ke],Xe=[],tt=0;tt<st.length;tt++){var bt=Me(st[tt]);Xe.push(bt)}return new ye({array:Xe})}if(Ke=="set"){for(st=p[Ke],Xe=[],tt=0;tt<st.length;tt++)bt=Me(st[tt]),Xe.push(bt);return new be({array:Xe})}if(Ke=="tag"){var St=p[Ke];if(Object.prototype.toString.call(St)==="[object Array]"&&St.length==3){var mt=Me(St[2]);return new Ue({tag:St[0],explicit:St[1],obj:mt})}return new Ue(St)}},this.jsonToASN1HEX=function(p){return this.newObject(p).getEncodedHex()}},F.asn1.ASN1Util.oidHexToInt=function(p){for(var h="",y=parseInt(p.substr(0,2),16),E=(h=Math.floor(y/40)+"."+y%40,""),I=2;I<p.length;I+=2){var q=("00000000"+parseInt(p.substr(I,2),16).toString(2)).slice(-8);E+=q.substr(1,7),q.substr(0,1)=="0"&&(h=h+"."+new D(E,2).toString(10),E="")}return h},F.asn1.ASN1Util.oidIntToHex=function(p){var h=function(ee){var se=ee.toString(16);return se.length==1&&(se="0"+se),se},y=function(ee){var se="",oe=new D(ee,10).toString(2),pe=7-oe.length%7;pe==7&&(pe=0);for(var Se="",Ee=0;Ee<pe;Ee++)Se+="0";for(oe=Se+oe,Ee=0;Ee<oe.length-1;Ee+=7){var Pe=oe.substr(Ee,7);Ee!=oe.length-7&&(Pe="1"+Pe),se+=h(parseInt(Pe,2))}return se};if(!p.match(/^[0-9.]+$/))throw"malformed oid string: "+p;var E="",I=p.split("."),q=40*parseInt(I[0])+parseInt(I[1]);E+=h(q),I.splice(0,2);for(var K=0;K<I.length;K++)E+=y(I[K]);return E},F.asn1.ASN1Object=function(p){this.params=null,this.getLengthHexFromValue=function(){if(this.hV===void 0||this.hV==null)throw new Error("this.hV is null or undefined");if(this.hV.length%2==1)throw new Error("value hex must be even length: n=0,v="+this.hV);var h=this.hV.length/2,y=h.toString(16);if(y.length%2==1&&(y="0"+y),h<128)return y;var E=y.length/2;if(E>15)throw"ASN.1 length too long to represent by 8x: n = "+h.toString(16);return(128+E).toString(16)+y},this.getEncodedHex=function(){return(this.hTLV==null||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getValueHex=function(){return this.getEncodedHex(),this.hV},this.getFreshValueHex=function(){return""},this.setByParam=function(h){this.params=h},p!=null&&p.tlv!=null&&(this.hTLV=p.tlv,this.isModified=!1)},F.asn1.DERAbstractString=function(p){F.asn1.DERAbstractString.superclass.constructor.call(this),this.getString=function(){return this.s},this.setString=function(h){this.hTLV=null,this.isModified=!0,this.s=h,this.hV=$t(this.s).toLowerCase()},this.setStringHex=function(h){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=h},this.getFreshValueHex=function(){return this.hV},p!==void 0&&(typeof p=="string"?this.setString(p):p.str!==void 0?this.setString(p.str):p.hex!==void 0&&this.setStringHex(p.hex))},lt(F.asn1.DERAbstractString,F.asn1.ASN1Object),F.asn1.DERAbstractTime=function(p){F.asn1.DERAbstractTime.superclass.constructor.call(this),this.localDateToUTC=function(h){var y=h.getTime()+6e4*h.getTimezoneOffset();return new Date(y)},this.formatDate=function(h,y,E){var I=this.zeroPadding,q=this.localDateToUTC(h),K=String(q.getFullYear());y=="utc"&&(K=K.substr(2,2));var ce=K+I(String(q.getMonth()+1),2)+I(String(q.getDate()),2)+I(String(q.getHours()),2)+I(String(q.getMinutes()),2)+I(String(q.getSeconds()),2);if(E===!0){var ee=q.getMilliseconds();if(ee!=0){var se=I(String(ee),3);ce=ce+"."+(se=se.replace(/[0]+$/,""))}}return ce+"Z"},this.zeroPadding=function(h,y){return h.length>=y?h:new Array(y-h.length+1).join("0")+h},this.getString=function(){return this.s},this.setString=function(h){this.hTLV=null,this.isModified=!0,this.s=h,this.hV=ct(h)},this.setByDateValue=function(h,y,E,I,q,K){var ce=new Date(Date.UTC(h,y-1,E,I,q,K,0));this.setByDate(ce)},this.getFreshValueHex=function(){return this.hV}},lt(F.asn1.DERAbstractTime,F.asn1.ASN1Object),F.asn1.DERAbstractStructured=function(p){F.asn1.DERAbstractString.superclass.constructor.call(this),this.setByASN1ObjectArray=function(h){this.hTLV=null,this.isModified=!0,this.asn1Array=h},this.appendASN1Object=function(h){this.hTLV=null,this.isModified=!0,this.asn1Array.push(h)},this.asn1Array=new Array,p!==void 0&&p.array!==void 0&&(this.asn1Array=p.array)},lt(F.asn1.DERAbstractStructured,F.asn1.ASN1Object),F.asn1.DERBoolean=function(p){F.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=p==0?"010100":"0101ff"},lt(F.asn1.DERBoolean,F.asn1.ASN1Object),F.asn1.DERInteger=function(p){F.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.setByBigInteger=function(h){this.hTLV=null,this.isModified=!0,this.hV=F.asn1.ASN1Util.bigIntToMinTwosComplementsHex(h)},this.setByInteger=function(h){var y=new D(String(h),10);this.setByBigInteger(y)},this.setValueHex=function(h){this.hV=h},this.getFreshValueHex=function(){return this.hV},p!==void 0&&(p.bigint!==void 0?this.setByBigInteger(p.bigint):p.int!==void 0?this.setByInteger(p.int):typeof p=="number"?this.setByInteger(p):p.hex!==void 0&&this.setValueHex(p.hex))},lt(F.asn1.DERInteger,F.asn1.ASN1Object),F.asn1.DERBitString=function(p){if(p!==void 0&&p.obj!==void 0){var h=F.asn1.ASN1Util.newObject(p.obj);p.hex="00"+h.getEncodedHex()}F.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(y){this.hTLV=null,this.isModified=!0,this.hV=y},this.setUnusedBitsAndHexValue=function(y,E){if(y<0||7<y)throw"unused bits shall be from 0 to 7: u = "+y;var I="0"+y;this.hTLV=null,this.isModified=!0,this.hV=I+E},this.setByBinaryString=function(y){var E=8-(y=y.replace(/0+$/,"")).length%8;E==8&&(E=0);for(var I=0;I<=E;I++)y+="0";var q="";for(I=0;I<y.length-1;I+=8){var K=y.substr(I,8),ce=parseInt(K,2).toString(16);ce.length==1&&(ce="0"+ce),q+=ce}this.hTLV=null,this.isModified=!0,this.hV="0"+E+q},this.setByBooleanArray=function(y){for(var E="",I=0;I<y.length;I++)y[I]==1?E+="1":E+="0";this.setByBinaryString(E)},this.newFalseArray=function(y){for(var E=new Array(y),I=0;I<y;I++)E[I]=!1;return E},this.getFreshValueHex=function(){return this.hV},p!==void 0&&(typeof p=="string"&&p.toLowerCase().match(/^[0-9a-f]+$/)?this.setHexValueIncludingUnusedBits(p):p.hex!==void 0?this.setHexValueIncludingUnusedBits(p.hex):p.bin!==void 0?this.setByBinaryString(p.bin):p.array!==void 0&&this.setByBooleanArray(p.array))},lt(F.asn1.DERBitString,F.asn1.ASN1Object),F.asn1.DEROctetString=function(p){if(p!==void 0&&p.obj!==void 0){var h=F.asn1.ASN1Util.newObject(p.obj);p.hex=h.getEncodedHex()}F.asn1.DEROctetString.superclass.constructor.call(this,p),this.hT="04"},lt(F.asn1.DEROctetString,F.asn1.DERAbstractString),F.asn1.DERNull=function(){F.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},lt(F.asn1.DERNull,F.asn1.ASN1Object),F.asn1.DERObjectIdentifier=function(p){F.asn1.DERObjectIdentifier.superclass.constructor.call(this),this.hT="06",this.setValueHex=function(h){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=h},this.setValueOidString=function(h){var y=(function(I){var q=function(Se){var Ee=Se.toString(16);return Ee.length==1&&(Ee="0"+Ee),Ee},K=function(Se){var Ee="",Pe=parseInt(Se,10).toString(2),$e=7-Pe.length%7;$e==7&&($e=0);for(var Le="",Z=0;Z<$e;Z++)Le+="0";for(Pe=Le+Pe,Z=0;Z<Pe.length-1;Z+=7){var fe=Pe.substr(Z,7);Z!=Pe.length-7&&(fe="1"+fe),Ee+=q(parseInt(fe,2))}return Ee};try{if(!I.match(/^[0-9.]+$/))return null;var ce="",ee=I.split("."),se=40*parseInt(ee[0],10)+parseInt(ee[1],10);ce+=q(se),ee.splice(0,2);for(var oe=0;oe<ee.length;oe++)ce+=K(ee[oe]);return ce}catch{return null}})(h);if(y==null)throw new Error("malformed oid string: "+h);this.hTLV=null,this.isModified=!0,this.s=null,this.hV=y},this.setValueName=function(h){var y=F.asn1.x509.OID.name2oid(h);if(y==="")throw new Error("DERObjectIdentifier oidName undefined: "+h);this.setValueOidString(y)},this.setValueNameOrOid=function(h){h.match(/^[0-2].[0-9.]+$/)?this.setValueOidString(h):this.setValueName(h)},this.getFreshValueHex=function(){return this.hV},this.setByParam=function(h){typeof h=="string"?this.setValueNameOrOid(h):h.oid!==void 0?this.setValueNameOrOid(h.oid):h.name!==void 0?this.setValueNameOrOid(h.name):h.hex!==void 0&&this.setValueHex(h.hex)},p!==void 0&&this.setByParam(p)},lt(F.asn1.DERObjectIdentifier,F.asn1.ASN1Object),F.asn1.DEREnumerated=function(p){F.asn1.DEREnumerated.superclass.constructor.call(this),this.hT="0a",this.setByBigInteger=function(h){this.hTLV=null,this.isModified=!0,this.hV=F.asn1.ASN1Util.bigIntToMinTwosComplementsHex(h)},this.setByInteger=function(h){var y=new D(String(h),10);this.setByBigInteger(y)},this.setValueHex=function(h){this.hV=h},this.getFreshValueHex=function(){return this.hV},p!==void 0&&(p.int!==void 0?this.setByInteger(p.int):typeof p=="number"?this.setByInteger(p):p.hex!==void 0&&this.setValueHex(p.hex))},lt(F.asn1.DEREnumerated,F.asn1.ASN1Object),F.asn1.DERUTF8String=function(p){F.asn1.DERUTF8String.superclass.constructor.call(this,p),this.hT="0c"},lt(F.asn1.DERUTF8String,F.asn1.DERAbstractString),F.asn1.DERNumericString=function(p){F.asn1.DERNumericString.superclass.constructor.call(this,p),this.hT="12"},lt(F.asn1.DERNumericString,F.asn1.DERAbstractString),F.asn1.DERPrintableString=function(p){F.asn1.DERPrintableString.superclass.constructor.call(this,p),this.hT="13"},lt(F.asn1.DERPrintableString,F.asn1.DERAbstractString),F.asn1.DERTeletexString=function(p){F.asn1.DERTeletexString.superclass.constructor.call(this,p),this.hT="14"},lt(F.asn1.DERTeletexString,F.asn1.DERAbstractString),F.asn1.DERIA5String=function(p){F.asn1.DERIA5String.superclass.constructor.call(this,p),this.hT="16"},lt(F.asn1.DERIA5String,F.asn1.DERAbstractString),F.asn1.DERVisibleString=function(p){F.asn1.DERIA5String.superclass.constructor.call(this,p),this.hT="1a"},lt(F.asn1.DERVisibleString,F.asn1.DERAbstractString),F.asn1.DERBMPString=function(p){F.asn1.DERBMPString.superclass.constructor.call(this,p),this.hT="1e"},lt(F.asn1.DERBMPString,F.asn1.DERAbstractString),F.asn1.DERUTCTime=function(p){F.asn1.DERUTCTime.superclass.constructor.call(this,p),this.hT="17",this.setByDate=function(h){this.hTLV=null,this.isModified=!0,this.date=h,this.s=this.formatDate(this.date,"utc"),this.hV=ct(this.s)},this.getFreshValueHex=function(){return this.date===void 0&&this.s===void 0&&(this.date=new Date,this.s=this.formatDate(this.date,"utc"),this.hV=ct(this.s)),this.hV},p!==void 0&&(p.str!==void 0?this.setString(p.str):typeof p=="string"&&p.match(/^[0-9]{12}Z$/)?this.setString(p):p.hex!==void 0?this.setStringHex(p.hex):p.date!==void 0&&this.setByDate(p.date))},lt(F.asn1.DERUTCTime,F.asn1.DERAbstractTime),F.asn1.DERGeneralizedTime=function(p){F.asn1.DERGeneralizedTime.superclass.constructor.call(this,p),this.hT="18",this.withMillis=!1,this.setByDate=function(h){this.hTLV=null,this.isModified=!0,this.date=h,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=ct(this.s)},this.getFreshValueHex=function(){return this.date===void 0&&this.s===void 0&&(this.date=new Date,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=ct(this.s)),this.hV},p!==void 0&&(p.str!==void 0?this.setString(p.str):typeof p=="string"&&p.match(/^[0-9]{14}Z$/)?this.setString(p):p.hex!==void 0?this.setStringHex(p.hex):p.date!==void 0&&this.setByDate(p.date),p.millis===!0&&(this.withMillis=!0))},lt(F.asn1.DERGeneralizedTime,F.asn1.DERAbstractTime),F.asn1.DERSequence=function(p){F.asn1.DERSequence.superclass.constructor.call(this,p),this.hT="30",this.getFreshValueHex=function(){for(var h="",y=0;y<this.asn1Array.length;y++)h+=this.asn1Array[y].getEncodedHex();return this.hV=h,this.hV}},lt(F.asn1.DERSequence,F.asn1.DERAbstractStructured),F.asn1.DERSet=function(p){F.asn1.DERSet.superclass.constructor.call(this,p),this.hT="31",this.sortFlag=!0,this.getFreshValueHex=function(){for(var h=new Array,y=0;y<this.asn1Array.length;y++){var E=this.asn1Array[y];h.push(E.getEncodedHex())}return this.sortFlag==1&&h.sort(),this.hV=h.join(""),this.hV},p!==void 0&&p.sortflag!==void 0&&p.sortflag==0&&(this.sortFlag=!1)},lt(F.asn1.DERSet,F.asn1.DERAbstractStructured),F.asn1.DERTaggedObject=function(p){F.asn1.DERTaggedObject.superclass.constructor.call(this);var h=F.asn1;this.hT="a0",this.hV="",this.isExplicit=!0,this.asn1Object=null,this.setASN1Object=function(y,E,I){this.hT=E,this.isExplicit=y,this.asn1Object=I,this.isExplicit?(this.hV=this.asn1Object.getEncodedHex(),this.hTLV=null,this.isModified=!0):(this.hV=null,this.hTLV=I.getEncodedHex(),this.hTLV=this.hTLV.replace(/^../,E),this.isModified=!1)},this.getFreshValueHex=function(){return this.hV},this.setByParam=function(y){y.tag!=null&&(this.hT=y.tag),y.explicit!=null&&(this.isExplicit=y.explicit),y.tage!=null&&(this.hT=y.tage,this.isExplicit=!0),y.tagi!=null&&(this.hT=y.tagi,this.isExplicit=!1),y.obj!=null&&(y.obj instanceof h.ASN1Object?(this.asn1Object=y.obj,this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)):w(y.obj)=="object"&&(this.asn1Object=h.ASN1Util.newObject(y.obj),this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)))},p!=null&&this.setByParam(p)},lt(F.asn1.DERTaggedObject,F.asn1.ASN1Object);var F,me,Re,we=new function(){};function Qe(p){for(var h=new Array,y=0;y<p.length;y++)h[y]=p.charCodeAt(y);return h}function et(p){for(var h="",y=0;y<p.length;y++)h+=String.fromCharCode(p[y]);return h}function ot(p){for(var h="",y=0;y<p.length;y++){var E=p[y].toString(16);E.length==1&&(E="0"+E),h+=E}return h}function ct(p){return ot(Qe(p))}function at(p){return p=(p=(p=p.replace(/\=/g,"")).replace(/\+/g,"-")).replace(/\//g,"_")}function Qt(p){return p.length%4==2?p+="==":p.length%4==3&&(p+="="),p=(p=p.replace(/-/g,"+")).replace(/_/g,"/")}function wt(p){return p.length%2==1&&(p="0"+p),at($(p))}function dt(p){return W(Qt(p))}function $t(p){return gt(Ot(p))}function yt(p){return decodeURIComponent(rr(p))}function At(p){for(var h="",y=0;y<p.length-1;y+=2)h+=String.fromCharCode(parseInt(p.substr(y,2),16));return h}function It(p){for(var h="",y=0;y<p.length;y++)h+=("0"+p.charCodeAt(y).toString(16)).slice(-2);return h}function Bt(p){return $(p)}function k(p){var h=Bt(p).replace(/(.{64})/g,`$1\r
|
|
220
|
+
`);return h=h.replace(/\r\n$/,"")}function j(p){return W(p.replace(/[^0-9A-Za-z\/+=]*/g,""))}function Ie(p,h){return"-----BEGIN "+h+`-----\r
|
|
221
|
+
`+k(p)+`\r
|
|
222
|
+
-----END `+h+`-----\r
|
|
223
|
+
`}function Ae(p,h){if(p.indexOf("-----BEGIN ")==-1)throw"can't find PEM header: "+h;return j(p=h!==void 0?(p=p.replace(new RegExp("^[^]*-----BEGIN "+h+"-----"),"")).replace(new RegExp("-----END "+h+"-----[^]*$"),""):(p=p.replace(/^[^]*-----BEGIN [^-]+-----/,"")).replace(/-----END [^-]+-----[^]*$/,""))}function Ve(p){var h,y,E,I,q,K,ce,ee,se,oe,pe;if(pe=p.match(/^(\d{2}|\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/))return ee=pe[1],h=parseInt(ee),ee.length===2&&(50<=h&&h<100?h=1900+h:0<=h&&h<50&&(h=2e3+h)),y=parseInt(pe[2])-1,E=parseInt(pe[3]),I=parseInt(pe[4]),q=parseInt(pe[5]),K=parseInt(pe[6]),ce=0,(se=pe[7])!==""&&(oe=(se.substr(1)+"00").substr(0,3),ce=parseInt(oe)),Date.UTC(h,y,E,I,q,K,ce);throw"unsupported zulu format: "+p}function ht(p){return~~(Ve(p)/1e3)}function gt(p){return p.replace(/%/g,"")}function rr(p){return p.replace(/(..)/g,"%$1")}function Pt(p){var h="malformed IPv6 address";if(!p.match(/^[0-9A-Fa-f:]+$/))throw h;var y=(p=p.toLowerCase()).split(":").length-1;if(y<2)throw h;var E=":".repeat(7-y+2),I=(p=p.replace("::",E)).split(":");if(I.length!=8)throw h;for(var q=0;q<8;q++)I[q]=("0000"+I[q]).slice(-4);return I.join("")}function Et(p){if(!p.match(/^[0-9A-Fa-f]{32}$/))throw"malformed IPv6 address octet";for(var h=(p=p.toLowerCase()).match(/.{1,4}/g),y=0;y<8;y++)h[y]=h[y].replace(/^0+/,""),h[y]==""&&(h[y]="0");var E=(p=":"+h.join(":")+":").match(/:(0:){2,}/g);if(E===null)return p.slice(1,-1);var I="";for(y=0;y<E.length;y++)E[y].length>I.length&&(I=E[y]);return(p=p.replace(I,"::")).slice(1,-1)}function ar(p){var h="malformed hex value";if(!p.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))throw h;if(p.length!=8)return p.length==32?Et(p):p;try{return parseInt(p.substr(0,2),16)+"."+parseInt(p.substr(2,2),16)+"."+parseInt(p.substr(4,2),16)+"."+parseInt(p.substr(6,2),16)}catch{throw h}}function fr(p){return p.match(/.{4}/g).map((function(y){var E=parseInt(y.substr(0,2),16),I=parseInt(y.substr(2),16);if(E==0&I<128)return String.fromCharCode(I);if(E<8){var q=128|63&I;return yt((192|(7&E)<<3|(192&I)>>6).toString(16)+q.toString(16))}q=128|(15&E)<<2|(192&I)>>6;var K=128|63&I;return yt((224|(240&E)>>4).toString(16)+q.toString(16)+K.toString(16))})).join("")}function Ot(p){for(var h=encodeURIComponent(p),y="",E=0;E<h.length;E++)h[E]=="%"?(y+=h.substr(E,3),E+=2):y=y+"%"+ct(h[E]);return y}function nr(p){return!(p.length%2!=0||!p.match(/^[0-9a-f]+$/)&&!p.match(/^[0-9A-F]+$/))}function Jt(p){return p.length%2==1?"0"+p:p.substr(0,1)>"7"?"00"+p:p}we.getLblen=function(p,h){if(p.substr(h+2,1)!="8")return 1;var y=parseInt(p.substr(h+3,1));return y==0?-1:0<y&&y<10?y+1:-2},we.getL=function(p,h){var y=we.getLblen(p,h);return y<1?"":p.substr(h+2,2*y)},we.getVblen=function(p,h){var y;return(y=we.getL(p,h))==""?-1:(y.substr(0,1)==="8"?new D(y.substr(2),16):new D(y,16)).intValue()},we.getVidx=function(p,h){var y=we.getLblen(p,h);return y<0?y:h+2*(y+1)},we.getV=function(p,h){var y=we.getVidx(p,h),E=we.getVblen(p,h);return p.substr(y,2*E)},we.getTLV=function(p,h){return p.substr(h,2)+we.getL(p,h)+we.getV(p,h)},we.getTLVblen=function(p,h){return 2+2*we.getLblen(p,h)+2*we.getVblen(p,h)},we.getNextSiblingIdx=function(p,h){return we.getVidx(p,h)+2*we.getVblen(p,h)},we.getChildIdx=function(p,h){var y,E,I,q=we,K=[];y=q.getVidx(p,h),E=2*q.getVblen(p,h),p.substr(h,2)=="03"&&(y+=2,E-=2),I=0;for(var ce=y;I<=E;){var ee=q.getTLVblen(p,ce);if((I+=ee)<=E&&K.push(ce),ce+=ee,I>=E)break}return K},we.getNthChildIdx=function(p,h,y){return we.getChildIdx(p,h)[y]},we.getIdxbyList=function(p,h,y,E){var I,q,K=we;return y.length==0?E!==void 0&&p.substr(h,2)!==E?-1:h:(I=y.shift())>=(q=K.getChildIdx(p,h)).length?-1:K.getIdxbyList(p,q[I],y,E)},we.getIdxbyListEx=function(p,h,y,E){var I,q,K=we;if(y.length==0)return E!==void 0&&p.substr(h,2)!==E?-1:h;I=y.shift(),q=K.getChildIdx(p,h);for(var ce=0,ee=0;ee<q.length;ee++){var se=p.substr(q[ee],2);if(typeof I=="number"&&!K.isContextTag(se)&&ce==I||typeof I=="string"&&K.isContextTag(se,I))return K.getIdxbyListEx(p,q[ee],y,E);K.isContextTag(se)||ce++}return-1},we.getTLVbyList=function(p,h,y,E){var I=we,q=I.getIdxbyList(p,h,y,E);return q==-1||q>=p.length?null:I.getTLV(p,q)},we.getTLVbyListEx=function(p,h,y,E){var I=we,q=I.getIdxbyListEx(p,h,y,E);return q==-1?null:I.getTLV(p,q)},we.getVbyList=function(p,h,y,E,I){var q,K,ce=we;return(q=ce.getIdxbyList(p,h,y,E))==-1||q>=p.length?null:(K=ce.getV(p,q),I===!0&&(K=K.substr(2)),K)},we.getVbyListEx=function(p,h,y,E,I){var q,K,ce=we;return(q=ce.getIdxbyListEx(p,h,y,E))==-1?null:(K=ce.getV(p,q),p.substr(q,2)=="03"&&I!==!1&&(K=K.substr(2)),K)},we.getInt=function(p,h,y){y==null&&(y=-1);try{var E=p.substr(h,2);if(E!="02"&&E!="03")return y;var I=we.getV(p,h);return E=="02"?parseInt(I,16):(function(K){try{var ce=K.substr(0,2);if(ce=="00")return parseInt(K.substr(2),16);var ee=parseInt(ce,16),se=K.substr(2),oe=parseInt(se,16).toString(2);return oe=="0"&&(oe="00000000"),oe=oe.slice(0,0-ee),parseInt(oe,2)}catch{return-1}})(I)}catch{return y}},we.getOID=function(p,h,y){y==null&&(y=null);try{return p.substr(h,2)!="06"?y:(function(I){if(!nr(I))return null;try{var q=[],K=I.substr(0,2),ce=parseInt(K,16);q[0]=new String(Math.floor(ce/40)),q[1]=new String(ce%40);for(var ee=I.substr(2),se=[],oe=0;oe<ee.length/2;oe++)se.push(parseInt(ee.substr(2*oe,2),16));var pe=[],Se="";for(oe=0;oe<se.length;oe++)128&se[oe]?Se+=zt((127&se[oe]).toString(2),7):(Se+=zt((127&se[oe]).toString(2),7),pe.push(new String(parseInt(Se,2))),Se="");var Ee=q.join(".");return pe.length>0&&(Ee=Ee+"."+pe.join(".")),Ee}catch{return null}})(we.getV(p,h))}catch{return y}},we.getOIDName=function(p,h,y){y==null&&(y=null);try{var E=we.getOID(p,h,y);if(E==y)return y;var I=F.asn1.x509.OID.oid2name(E);return I==""?E:I}catch{return y}},we.getString=function(p,h,y){y==null&&(y=null);try{return At(we.getV(p,h))}catch{return y}},we.hextooidstr=function(p){var h=function(Se,Ee){return Se.length>=Ee?Se:new Array(Ee-Se.length+1).join("0")+Se},y=[],E=p.substr(0,2),I=parseInt(E,16);y[0]=new String(Math.floor(I/40)),y[1]=new String(I%40);for(var q=p.substr(2),K=[],ce=0;ce<q.length/2;ce++)K.push(parseInt(q.substr(2*ce,2),16));var ee=[],se="";for(ce=0;ce<K.length;ce++)128&K[ce]?se+=h((127&K[ce]).toString(2),7):(se+=h((127&K[ce]).toString(2),7),ee.push(new String(parseInt(se,2))),se="");var oe=y.join(".");return ee.length>0&&(oe=oe+"."+ee.join(".")),oe},we.dump=function(p,h,y,E){var I=we,q=I.getV,K=I.dump,ce=I.getChildIdx,ee=p;p instanceof F.asn1.ASN1Object&&(ee=p.getEncodedHex());var se=function(Ke,st){return Ke.length<=2*st?Ke:Ke.substr(0,st)+"..(total "+Ke.length/2+"bytes).."+Ke.substr(Ke.length-st,st)};h===void 0&&(h={ommit_long_octet:32}),y===void 0&&(y=0),E===void 0&&(E="");var oe,pe=h.ommit_long_octet;if((oe=ee.substr(y,2))=="01")return(Se=q(ee,y))=="00"?E+`BOOLEAN FALSE
|
|
224
|
+
`:E+`BOOLEAN TRUE
|
|
225
|
+
`;if(oe=="02")return E+"INTEGER "+se(Se=q(ee,y),pe)+`
|
|
226
|
+
`;if(oe=="03"){var Se=q(ee,y);if(I.isASN1HEX(Se.substr(2))){var Ee=E+`BITSTRING, encapsulates
|
|
227
|
+
`;return Ee+=K(Se.substr(2),h,0,E+" ")}return E+"BITSTRING "+se(Se,pe)+`
|
|
228
|
+
`}if(oe=="04")return Se=q(ee,y),I.isASN1HEX(Se)?(Ee=E+`OCTETSTRING, encapsulates
|
|
229
|
+
`,Ee+=K(Se,h,0,E+" ")):E+"OCTETSTRING "+se(Se,pe)+`
|
|
230
|
+
`;if(oe=="05")return E+`NULL
|
|
231
|
+
`;if(oe=="06"){var Pe=q(ee,y),$e=F.asn1.ASN1Util.oidHexToInt(Pe),Le=F.asn1.x509.OID.oid2name($e),Z=$e.replace(/\./g," ");return Le!=""?E+"ObjectIdentifier "+Le+" ("+Z+`)
|
|
232
|
+
`:E+"ObjectIdentifier ("+Z+`)
|
|
233
|
+
`}if(oe=="0a")return E+"ENUMERATED "+parseInt(q(ee,y))+`
|
|
234
|
+
`;if(oe=="0c")return E+"UTF8String '"+yt(q(ee,y))+`'
|
|
235
|
+
`;if(oe=="13")return E+"PrintableString '"+yt(q(ee,y))+`'
|
|
236
|
+
`;if(oe=="14")return E+"TeletexString '"+yt(q(ee,y))+`'
|
|
237
|
+
`;if(oe=="16")return E+"IA5String '"+yt(q(ee,y))+`'
|
|
238
|
+
`;if(oe=="17")return E+"UTCTime "+yt(q(ee,y))+`
|
|
239
|
+
`;if(oe=="18")return E+"GeneralizedTime "+yt(q(ee,y))+`
|
|
240
|
+
`;if(oe=="1a")return E+"VisualString '"+yt(q(ee,y))+`'
|
|
241
|
+
`;if(oe=="1e")return E+"BMPString '"+fr(q(ee,y))+`'
|
|
242
|
+
`;if(oe=="30"){if(ee.substr(y,4)=="3000")return E+`SEQUENCE {}
|
|
243
|
+
`;Ee=E+`SEQUENCE
|
|
244
|
+
`;var fe=h;if(((Ue=ce(ee,y)).length==2||Ue.length==3)&&ee.substr(Ue[0],2)=="06"&&ee.substr(Ue[Ue.length-1],2)=="04"){Le=I.oidname(q(ee,Ue[0]));var ye=JSON.parse(JSON.stringify(h));ye.x509ExtName=Le,fe=ye}for(var be=0;be<Ue.length;be++)Ee+=K(ee,fe,Ue[be],E+" ");return Ee}if(oe=="31"){Ee=E+`SET
|
|
245
|
+
`;var Ue=ce(ee,y);for(be=0;be<Ue.length;be++)Ee+=K(ee,h,Ue[be],E+" ");return Ee}if((128&(oe=parseInt(oe,16)))!=0){var Me=31&oe;if((32&oe)!=0){for(Ee=E+"["+Me+`]
|
|
246
|
+
`,Ue=ce(ee,y),be=0;be<Ue.length;be++)Ee+=K(ee,h,Ue[be],E+" ");return Ee}if(Se=q(ee,y),we.isASN1HEX(Se)){var Ee=E+"["+Me+`]
|
|
247
|
+
`;return Ee+=K(Se,h,0,E+" ")}return(Se.substr(0,8)=="68747470"||h.x509ExtName==="subjectAltName"&&Me==2)&&(Se=yt(Se)),Ee=E+"["+Me+"] "+Se+`
|
|
248
|
+
`}return E+"UNKNOWN("+oe+") "+q(ee,y)+`
|
|
249
|
+
`},we.isContextTag=function(p,h){var y,E;p=p.toLowerCase();try{y=parseInt(p,16)}catch{return-1}if(h===void 0)return(192&y)==128;try{return h.match(/^\[[0-9]+\]$/)!=null&&!((E=parseInt(h.substr(1,h.length-1),10))>31)&&(192&y)==128&&(31&y)==E}catch{return!1}},we.isASN1HEX=function(p){var h=we;if(p.length%2==1)return!1;var y=h.getVblen(p,0),E=p.substr(0,2),I=h.getL(p,0);return p.length-E.length-I.length==2*y},we.checkStrictDER=function(p,h,y,E,I){var q=we;if(y===void 0){if(typeof p!="string")throw new Error("not hex string");if(p=p.toLowerCase(),!F.lang.String.isHex(p))throw new Error("not hex string");y=p.length,I=(E=p.length/2)<128?1:Math.ceil(E.toString(16))+1}if(q.getL(p,h).length>2*I)throw new Error("L of TLV too long: idx="+h);var K=q.getVblen(p,h);if(K>E)throw new Error("value of L too long than hex: idx="+h);var ce=q.getTLV(p,h),ee=ce.length-2-q.getL(p,h).length;if(ee!==2*K)throw new Error("V string length and L's value not the same:"+ee+"/"+2*K);if(h===0&&p.length!=ce.length)throw new Error("total length and TLV length unmatch:"+p.length+"!="+ce.length);var se=p.substr(h,2);if(se==="02"){var oe=q.getVidx(p,h);if(p.substr(oe,2)=="00"&&p.charCodeAt(oe+2)<56)throw new Error("not least zeros for DER INTEGER")}if(32&parseInt(se,16)){for(var pe=q.getVblen(p,h),Se=0,Ee=q.getChildIdx(p,h),Pe=0;Pe<Ee.length;Pe++)Se+=q.getTLV(p,Ee[Pe]).length,q.checkStrictDER(p,Ee[Pe],y,E,I);if(2*pe!=Se)throw new Error("sum of children's TLV length and L unmatch: "+2*pe+"!="+Se)}},we.oidname=function(p){var h=F.asn1;F.lang.String.isHex(p)&&(p=h.ASN1Util.oidHexToInt(p));var y=h.x509.OID.oid2name(p);return y===""&&(y=p),y},F!==void 0&&F||(r.KJUR=F={}),F.lang!==void 0&&F.lang||(F.lang={}),F.lang.String=function(){},typeof s=="function"?(r.utf8tob64u=me=function(h){return at(s.from(h,"utf8").toString("base64"))},r.b64utoutf8=Re=function(h){return s.from(Qt(h),"base64").toString("utf8")}):(r.utf8tob64u=me=function(h){return wt(gt(Ot(h)))},r.b64utoutf8=Re=function(h){return decodeURIComponent(rr(dt(h)))}),F.lang.String.isInteger=function(p){return!!p.match(/^[0-9]+$/)||!!p.match(/^-[0-9]+$/)},F.lang.String.isHex=function(p){return nr(p)},F.lang.String.isBase64=function(p){return!(!(p=p.replace(/\s+/g,"")).match(/^[0-9A-Za-z+\/]+={0,3}$/)||p.length%4!=0)},F.lang.String.isBase64URL=function(p){return!p.match(/[+/=]/)&&(p=Qt(p),F.lang.String.isBase64(p))},F.lang.String.isIntegerArray=function(p){return!!(p=p.replace(/\s+/g,"")).match(/^\[[0-9,]+\]$/)},F.lang.String.isPrintable=function(p){return p.match(/^[0-9A-Za-z '()+,-./:=?]*$/)!==null},F.lang.String.isIA5=function(p){return p.match(/^[\x20-\x21\x23-\x7f]*$/)!==null},F.lang.String.isMail=function(p){return p.match(/^[A-Za-z0-9]{1}[A-Za-z0-9_.-]*@{1}[A-Za-z0-9_.-]{1,}\.[A-Za-z0-9]{1,}$/)!==null};var zt=function(h,y,E){return E==null&&(E="0"),h.length>=y?h:new Array(y-h.length+1).join(E)+h};function lt(p,h){var y=function(){};y.prototype=h.prototype,p.prototype=new y,p.prototype.constructor=p,p.superclass=h.prototype,h.prototype.constructor==Object.prototype.constructor&&(h.prototype.constructor=h)}F!==void 0&&F||(r.KJUR=F={}),F.crypto!==void 0&&F.crypto||(F.crypto={}),F.crypto.Util=new function(){this.DIGESTINFOHEAD={sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",ripemd160:"3021300906052b2403020105000414"},this.DEFAULTPROVIDER={md5:"cryptojs",sha1:"cryptojs",sha224:"cryptojs",sha256:"cryptojs",sha384:"cryptojs",sha512:"cryptojs",ripemd160:"cryptojs",hmacmd5:"cryptojs",hmacsha1:"cryptojs",hmacsha224:"cryptojs",hmacsha256:"cryptojs",hmacsha384:"cryptojs",hmacsha512:"cryptojs",hmacripemd160:"cryptojs",MD5withRSA:"cryptojs/jsrsa",SHA1withRSA:"cryptojs/jsrsa",SHA224withRSA:"cryptojs/jsrsa",SHA256withRSA:"cryptojs/jsrsa",SHA384withRSA:"cryptojs/jsrsa",SHA512withRSA:"cryptojs/jsrsa",RIPEMD160withRSA:"cryptojs/jsrsa",MD5withECDSA:"cryptojs/jsrsa",SHA1withECDSA:"cryptojs/jsrsa",SHA224withECDSA:"cryptojs/jsrsa",SHA256withECDSA:"cryptojs/jsrsa",SHA384withECDSA:"cryptojs/jsrsa",SHA512withECDSA:"cryptojs/jsrsa",RIPEMD160withECDSA:"cryptojs/jsrsa",SHA1withDSA:"cryptojs/jsrsa",SHA224withDSA:"cryptojs/jsrsa",SHA256withDSA:"cryptojs/jsrsa",MD5withRSAandMGF1:"cryptojs/jsrsa",SHAwithRSAandMGF1:"cryptojs/jsrsa",SHA1withRSAandMGF1:"cryptojs/jsrsa",SHA224withRSAandMGF1:"cryptojs/jsrsa",SHA256withRSAandMGF1:"cryptojs/jsrsa",SHA384withRSAandMGF1:"cryptojs/jsrsa",SHA512withRSAandMGF1:"cryptojs/jsrsa",RIPEMD160withRSAandMGF1:"cryptojs/jsrsa"},this.CRYPTOJSMESSAGEDIGESTNAME={md5:T.algo.MD5,sha1:T.algo.SHA1,sha224:T.algo.SHA224,sha256:T.algo.SHA256,sha384:T.algo.SHA384,sha512:T.algo.SHA512,ripemd160:T.algo.RIPEMD160},this.getDigestInfoHex=function(p,h){if(this.DIGESTINFOHEAD[h]===void 0)throw"alg not supported in Util.DIGESTINFOHEAD: "+h;return this.DIGESTINFOHEAD[h]+p},this.getPaddedDigestInfoHex=function(p,h,y){var E=this.getDigestInfoHex(p,h),I=y/4;if(E.length+22>I)throw"key is too short for SigAlg: keylen="+y+","+h;for(var q="0001",K="00"+E,ce="",ee=I-q.length-K.length,se=0;se<ee;se+=2)ce+="ff";return q+ce+K},this.hashString=function(p,h){return new F.crypto.MessageDigest({alg:h}).digestString(p)},this.hashHex=function(p,h){return new F.crypto.MessageDigest({alg:h}).digestHex(p)},this.sha1=function(p){return this.hashString(p,"sha1")},this.sha256=function(p){return this.hashString(p,"sha256")},this.sha256Hex=function(p){return this.hashHex(p,"sha256")},this.sha512=function(p){return this.hashString(p,"sha512")},this.sha512Hex=function(p){return this.hashHex(p,"sha512")},this.isKey=function(p){return p instanceof Ne||p instanceof F.crypto.DSA||p instanceof F.crypto.ECDSA}},F.crypto.Util.md5=function(p){return new F.crypto.MessageDigest({alg:"md5",prov:"cryptojs"}).digestString(p)},F.crypto.Util.ripemd160=function(p){return new F.crypto.MessageDigest({alg:"ripemd160",prov:"cryptojs"}).digestString(p)},F.crypto.Util.SECURERANDOMGEN=new Y,F.crypto.Util.getRandomHexOfNbytes=function(p){var h=new Array(p);return F.crypto.Util.SECURERANDOMGEN.nextBytes(h),ot(h)},F.crypto.Util.getRandomBigIntegerOfNbytes=function(p){return new D(F.crypto.Util.getRandomHexOfNbytes(p),16)},F.crypto.Util.getRandomHexOfNbits=function(p){var h=p%8,y=new Array((p-h)/8+1);return F.crypto.Util.SECURERANDOMGEN.nextBytes(y),y[0]=(255<<h&255^255)&y[0],ot(y)},F.crypto.Util.getRandomBigIntegerOfNbits=function(p){return new D(F.crypto.Util.getRandomHexOfNbits(p),16)},F.crypto.Util.getRandomBigIntegerZeroToMax=function(p){for(var h=p.bitLength();;){var y=F.crypto.Util.getRandomBigIntegerOfNbits(h);if(p.compareTo(y)!=-1)return y}},F.crypto.Util.getRandomBigIntegerMinToMax=function(p,h){var y=p.compareTo(h);if(y==1)throw"biMin is greater than biMax";if(y==0)return p;var E=h.subtract(p);return F.crypto.Util.getRandomBigIntegerZeroToMax(E).add(p)},F.crypto.MessageDigest=function(p){this.setAlgAndProvider=function(h,y){if((h=F.crypto.MessageDigest.getCanonicalAlgName(h))!==null&&y===void 0&&(y=F.crypto.Util.DEFAULTPROVIDER[h]),":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(h)!=-1&&y=="cryptojs"){try{this.md=F.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[h].create()}catch(E){throw"setAlgAndProvider hash alg set fail alg="+h+"/"+E}this.updateString=function(E){this.md.update(E)},this.updateHex=function(E){var I=T.enc.Hex.parse(E);this.md.update(I)},this.digest=function(){return this.md.finalize().toString(T.enc.Hex)},this.digestString=function(E){return this.updateString(E),this.digest()},this.digestHex=function(E){return this.updateHex(E),this.digest()}}if(":sha256:".indexOf(h)!=-1&&y=="sjcl"){try{this.md=new sjcl.hash.sha256}catch(E){throw"setAlgAndProvider hash alg set fail alg="+h+"/"+E}this.updateString=function(E){this.md.update(E)},this.updateHex=function(E){var I=sjcl.codec.hex.toBits(E);this.md.update(I)},this.digest=function(){var E=this.md.finalize();return sjcl.codec.hex.fromBits(E)},this.digestString=function(E){return this.updateString(E),this.digest()},this.digestHex=function(E){return this.updateHex(E),this.digest()}}},this.updateString=function(h){throw"updateString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.updateHex=function(h){throw"updateHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digest=function(){throw"digest() not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestString=function(h){throw"digestString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestHex=function(h){throw"digestHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},p!==void 0&&p.alg!==void 0&&(this.algName=p.alg,p.prov===void 0&&(this.provName=F.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName))},F.crypto.MessageDigest.getCanonicalAlgName=function(p){return typeof p=="string"&&(p=(p=p.toLowerCase()).replace(/-/,"")),p},F.crypto.MessageDigest.getHashLength=function(p){var h=F.crypto.MessageDigest,y=h.getCanonicalAlgName(p);if(h.HASHLENGTH[y]===void 0)throw"not supported algorithm: "+p;return h.HASHLENGTH[y]},F.crypto.MessageDigest.HASHLENGTH={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,ripemd160:20},F.crypto.Mac=function(p){this.setAlgAndProvider=function(h,y){if((h=h.toLowerCase())==null&&(h="hmacsha1"),(h=h.toLowerCase()).substr(0,4)!="hmac")throw"setAlgAndProvider unsupported HMAC alg: "+h;y===void 0&&(y=F.crypto.Util.DEFAULTPROVIDER[h]),this.algProv=h+"/"+y;var E=h.substr(4);if(":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(E)!=-1&&y=="cryptojs"){try{var I=F.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[E];this.mac=T.algo.HMAC.create(I,this.pass)}catch(q){throw"setAlgAndProvider hash alg set fail hashAlg="+E+"/"+q}this.updateString=function(q){this.mac.update(q)},this.updateHex=function(q){var K=T.enc.Hex.parse(q);this.mac.update(K)},this.doFinal=function(){return this.mac.finalize().toString(T.enc.Hex)},this.doFinalString=function(q){return this.updateString(q),this.doFinal()},this.doFinalHex=function(q){return this.updateHex(q),this.doFinal()}}},this.updateString=function(h){throw"updateString(str) not supported for this alg/prov: "+this.algProv},this.updateHex=function(h){throw"updateHex(hex) not supported for this alg/prov: "+this.algProv},this.doFinal=function(){throw"digest() not supported for this alg/prov: "+this.algProv},this.doFinalString=function(h){throw"digestString(str) not supported for this alg/prov: "+this.algProv},this.doFinalHex=function(h){throw"digestHex(hex) not supported for this alg/prov: "+this.algProv},this.setPassword=function(h){if(typeof h=="string"){var y=h;return h.length%2!=1&&h.match(/^[0-9A-Fa-f]+$/)||(y=It(h)),void(this.pass=T.enc.Hex.parse(y))}if((h===void 0?"undefined":w(h))!="object")throw"KJUR.crypto.Mac unsupported password type: "+h;if(y=null,h.hex!==void 0){if(h.hex.length%2!=0||!h.hex.match(/^[0-9A-Fa-f]+$/))throw"Mac: wrong hex password: "+h.hex;y=h.hex}if(h.utf8!==void 0&&(y=$t(h.utf8)),h.rstr!==void 0&&(y=It(h.rstr)),h.b64!==void 0&&(y=W(h.b64)),h.b64u!==void 0&&(y=dt(h.b64u)),y==null)throw"KJUR.crypto.Mac unsupported password type: "+h;this.pass=T.enc.Hex.parse(y)},p!==void 0&&(p.pass!==void 0&&this.setPassword(p.pass),p.alg!==void 0&&(this.algName=p.alg,p.prov===void 0&&(this.provName=F.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName)))},F.crypto.Signature=function(p){var h=null;if(this._setAlgNames=function(){var y=this.algName.match(/^(.+)with(.+)$/);y&&(this.mdAlgName=y[1].toLowerCase(),this.pubkeyAlgName=y[2].toLowerCase(),this.pubkeyAlgName=="rsaandmgf1"&&this.mdAlgName=="sha"&&(this.mdAlgName="sha1"))},this._zeroPaddingOfSignature=function(y,E){for(var I="",q=E/4-y.length,K=0;K<q;K++)I+="0";return I+y},this.setAlgAndProvider=function(y,E){if(this._setAlgNames(),E!="cryptojs/jsrsa")throw new Error("provider not supported: "+E);if(":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(this.mdAlgName)!=-1){try{this.md=new F.crypto.MessageDigest({alg:this.mdAlgName})}catch(I){throw new Error("setAlgAndProvider hash alg set fail alg="+this.mdAlgName+"/"+I)}this.init=function(I,q){var K=null;try{K=q===void 0?rt.getKey(I):rt.getKey(I,q)}catch(ce){throw"init failed:"+ce}if(K.isPrivate===!0)this.prvKey=K,this.state="SIGN";else{if(K.isPublic!==!0)throw"init failed.:"+K;this.pubKey=K,this.state="VERIFY"}},this.updateString=function(I){this.md.updateString(I)},this.updateHex=function(I){this.md.updateHex(I)},this.sign=function(){if(this.sHashHex=this.md.digest(),this.prvKey===void 0&&this.ecprvhex!==void 0&&this.eccurvename!==void 0&&F.crypto.ECDSA!==void 0&&(this.prvKey=new F.crypto.ECDSA({curve:this.eccurvename,prv:this.ecprvhex})),this.prvKey instanceof Ne&&this.pubkeyAlgName==="rsaandmgf1")this.hSign=this.prvKey.signWithMessageHashPSS(this.sHashHex,this.mdAlgName,this.pssSaltLen);else if(this.prvKey instanceof Ne&&this.pubkeyAlgName==="rsa")this.hSign=this.prvKey.signWithMessageHash(this.sHashHex,this.mdAlgName);else if(this.prvKey instanceof F.crypto.ECDSA)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex);else{if(!(this.prvKey instanceof F.crypto.DSA))throw"Signature: unsupported private key alg: "+this.pubkeyAlgName;this.hSign=this.prvKey.signWithMessageHash(this.sHashHex)}return this.hSign},this.signString=function(I){return this.updateString(I),this.sign()},this.signHex=function(I){return this.updateHex(I),this.sign()},this.verify=function(I){if(this.sHashHex=this.md.digest(),this.pubKey===void 0&&this.ecpubhex!==void 0&&this.eccurvename!==void 0&&F.crypto.ECDSA!==void 0&&(this.pubKey=new F.crypto.ECDSA({curve:this.eccurvename,pub:this.ecpubhex})),this.pubKey instanceof Ne&&this.pubkeyAlgName==="rsaandmgf1")return this.pubKey.verifyWithMessageHashPSS(this.sHashHex,I,this.mdAlgName,this.pssSaltLen);if(this.pubKey instanceof Ne&&this.pubkeyAlgName==="rsa")return this.pubKey.verifyWithMessageHash(this.sHashHex,I);if(F.crypto.ECDSA!==void 0&&this.pubKey instanceof F.crypto.ECDSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,I);if(F.crypto.DSA!==void 0&&this.pubKey instanceof F.crypto.DSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,I);throw"Signature: unsupported public key alg: "+this.pubkeyAlgName}}},this.init=function(y,E){throw"init(key, pass) not supported for this alg:prov="+this.algProvName},this.updateString=function(y){throw"updateString(str) not supported for this alg:prov="+this.algProvName},this.updateHex=function(y){throw"updateHex(hex) not supported for this alg:prov="+this.algProvName},this.sign=function(){throw"sign() not supported for this alg:prov="+this.algProvName},this.signString=function(y){throw"digestString(str) not supported for this alg:prov="+this.algProvName},this.signHex=function(y){throw"digestHex(hex) not supported for this alg:prov="+this.algProvName},this.verify=function(y){throw"verify(hSigVal) not supported for this alg:prov="+this.algProvName},this.initParams=p,p!==void 0&&(p.alg!==void 0&&(this.algName=p.alg,p.prov===void 0?this.provName=F.crypto.Util.DEFAULTPROVIDER[this.algName]:this.provName=p.prov,this.algProvName=this.algName+":"+this.provName,this.setAlgAndProvider(this.algName,this.provName),this._setAlgNames()),p.psssaltlen!==void 0&&(this.pssSaltLen=p.psssaltlen),p.prvkeypem!==void 0)){if(p.prvkeypas!==void 0)throw"both prvkeypem and prvkeypas parameters not supported";try{h=rt.getKey(p.prvkeypem),this.init(h)}catch(y){throw"fatal error to load pem private key: "+y}}},F.crypto.Cipher=function(p){},F.crypto.Cipher.encrypt=function(p,h,y){if(h instanceof Ne&&h.isPublic){var E=F.crypto.Cipher.getAlgByKeyAndName(h,y);if(E==="RSA")return h.encrypt(p);if(E==="RSAOAEP")return h.encryptOAEP(p,"sha1");var I=E.match(/^RSAOAEP(\d+)$/);if(I!==null)return h.encryptOAEP(p,"sha"+I[1]);throw"Cipher.encrypt: unsupported algorithm for RSAKey: "+y}throw"Cipher.encrypt: unsupported key or algorithm"},F.crypto.Cipher.decrypt=function(p,h,y){if(h instanceof Ne&&h.isPrivate){var E=F.crypto.Cipher.getAlgByKeyAndName(h,y);if(E==="RSA")return h.decrypt(p);if(E==="RSAOAEP")return h.decryptOAEP(p,"sha1");var I=E.match(/^RSAOAEP(\d+)$/);if(I!==null)return h.decryptOAEP(p,"sha"+I[1]);throw"Cipher.decrypt: unsupported algorithm for RSAKey: "+y}throw"Cipher.decrypt: unsupported key or algorithm"},F.crypto.Cipher.getAlgByKeyAndName=function(p,h){if(p instanceof Ne){if(":RSA:RSAOAEP:RSAOAEP224:RSAOAEP256:RSAOAEP384:RSAOAEP512:".indexOf(h)!=-1)return h;if(h==null)return"RSA";throw"getAlgByKeyAndName: not supported algorithm name for RSAKey: "+h}throw"getAlgByKeyAndName: not supported algorithm name: "+h},F.crypto.OID=new function(){this.oidhex2name={"2a864886f70d010101":"rsaEncryption","2a8648ce3d0201":"ecPublicKey","2a8648ce380401":"dsa","2a8648ce3d030107":"secp256r1","2b8104001f":"secp192k1","2b81040021":"secp224r1","2b8104000a":"secp256k1","2b81040023":"secp521r1","2b81040022":"secp384r1","2a8648ce380403":"SHA1withDSA","608648016503040301":"SHA224withDSA","608648016503040302":"SHA256withDSA"}},F!==void 0&&F||(r.KJUR=F={}),F.crypto!==void 0&&F.crypto||(F.crypto={}),F.crypto.ECDSA=function(p){var h=Error,y=D,E=B,I=F.crypto.ECDSA,q=F.crypto.ECParameterDB,K=I.getName,ce=we,ee=ce.getVbyListEx,se=ce.isASN1HEX,oe=new Y;this.type="EC",this.isPrivate=!1,this.isPublic=!1,this.getBigRandom=function(pe){return new y(pe.bitLength(),oe).mod(pe.subtract(y.ONE)).add(y.ONE)},this.setNamedCurve=function(pe){this.ecparams=q.getByName(pe),this.prvKeyHex=null,this.pubKeyHex=null,this.curveName=pe},this.setPrivateKeyHex=function(pe){this.isPrivate=!0,this.prvKeyHex=pe},this.setPublicKeyHex=function(pe){this.isPublic=!0,this.pubKeyHex=pe},this.getPublicKeyXYHex=function(){var pe=this.pubKeyHex;if(pe.substr(0,2)!=="04")throw"this method supports uncompressed format(04) only";var Se=this.ecparams.keylen/4;if(pe.length!==2+2*Se)throw"malformed public key hex length";var Ee={};return Ee.x=pe.substr(2,Se),Ee.y=pe.substr(2+Se),Ee},this.getShortNISTPCurveName=function(){var pe=this.curveName;return pe==="secp256r1"||pe==="NIST P-256"||pe==="P-256"||pe==="prime256v1"?"P-256":pe==="secp384r1"||pe==="NIST P-384"||pe==="P-384"?"P-384":null},this.generateKeyPairHex=function(){var pe=this.ecparams.n,Se=this.getBigRandom(pe),Ee=this.ecparams.G.multiply(Se),Pe=Ee.getX().toBigInteger(),$e=Ee.getY().toBigInteger(),Le=this.ecparams.keylen/4,Z=("0000000000"+Se.toString(16)).slice(-Le),fe="04"+("0000000000"+Pe.toString(16)).slice(-Le)+("0000000000"+$e.toString(16)).slice(-Le);return this.setPrivateKeyHex(Z),this.setPublicKeyHex(fe),{ecprvhex:Z,ecpubhex:fe}},this.signWithMessageHash=function(pe){return this.signHex(pe,this.prvKeyHex)},this.signHex=function(pe,Se){var Ee=new y(Se,16),Pe=this.ecparams.n,$e=new y(pe.substring(0,this.ecparams.keylen/4),16);do var Le=this.getBigRandom(Pe),Z=this.ecparams.G.multiply(Le).getX().toBigInteger().mod(Pe);while(Z.compareTo(y.ZERO)<=0);var fe=Le.modInverse(Pe).multiply($e.add(Ee.multiply(Z))).mod(Pe);return I.biRSSigToASN1Sig(Z,fe)},this.sign=function(pe,Se){var Ee=Se,Pe=this.ecparams.n,$e=y.fromByteArrayUnsigned(pe);do var Le=this.getBigRandom(Pe),Z=this.ecparams.G.multiply(Le).getX().toBigInteger().mod(Pe);while(Z.compareTo(D.ZERO)<=0);var fe=Le.modInverse(Pe).multiply($e.add(Ee.multiply(Z))).mod(Pe);return this.serializeSig(Z,fe)},this.verifyWithMessageHash=function(pe,Se){return this.verifyHex(pe,Se,this.pubKeyHex)},this.verifyHex=function(pe,Se,Ee){try{var Pe,$e,Le=I.parseSigHex(Se);Pe=Le.r,$e=Le.s;var Z=E.decodeFromHex(this.ecparams.curve,Ee),fe=new y(pe.substring(0,this.ecparams.keylen/4),16);return this.verifyRaw(fe,Pe,$e,Z)}catch{return!1}},this.verify=function(pe,Se,Ee){var Pe,$e,Le;if(Bitcoin.Util.isArray(Se)){var Z=this.parseSig(Se);Pe=Z.r,$e=Z.s}else{if((Se===void 0?"undefined":w(Se))!=="object"||!Se.r||!Se.s)throw"Invalid value for signature";Pe=Se.r,$e=Se.s}if(Ee instanceof B)Le=Ee;else{if(!Bitcoin.Util.isArray(Ee))throw"Invalid format for pubkey value, must be byte array or ECPointFp";Le=E.decodeFrom(this.ecparams.curve,Ee)}var fe=y.fromByteArrayUnsigned(pe);return this.verifyRaw(fe,Pe,$e,Le)},this.verifyRaw=function(pe,Se,Ee,Pe){var $e=this.ecparams.n,Le=this.ecparams.G;if(Se.compareTo(y.ONE)<0||Se.compareTo($e)>=0||Ee.compareTo(y.ONE)<0||Ee.compareTo($e)>=0)return!1;var Z=Ee.modInverse($e),fe=pe.multiply(Z).mod($e),ye=Se.multiply(Z).mod($e);return Le.multiply(fe).add(Pe.multiply(ye)).getX().toBigInteger().mod($e).equals(Se)},this.serializeSig=function(pe,Se){var Ee=pe.toByteArraySigned(),Pe=Se.toByteArraySigned(),$e=[];return $e.push(2),$e.push(Ee.length),($e=$e.concat(Ee)).push(2),$e.push(Pe.length),($e=$e.concat(Pe)).unshift($e.length),$e.unshift(48),$e},this.parseSig=function(pe){var Se;if(pe[0]!=48)throw new Error("Signature not a valid DERSequence");if(pe[Se=2]!=2)throw new Error("First element in signature must be a DERInteger");var Ee=pe.slice(Se+2,Se+2+pe[Se+1]);if(pe[Se+=2+pe[Se+1]]!=2)throw new Error("Second element in signature must be a DERInteger");var Pe=pe.slice(Se+2,Se+2+pe[Se+1]);return Se+=2+pe[Se+1],{r:y.fromByteArrayUnsigned(Ee),s:y.fromByteArrayUnsigned(Pe)}},this.parseSigCompact=function(pe){if(pe.length!==65)throw"Signature has the wrong length";var Se=pe[0]-27;if(Se<0||Se>7)throw"Invalid signature type";var Ee=this.ecparams.n;return{r:y.fromByteArrayUnsigned(pe.slice(1,33)).mod(Ee),s:y.fromByteArrayUnsigned(pe.slice(33,65)).mod(Ee),i:Se}},this.readPKCS5PrvKeyHex=function(pe){if(se(pe)===!1)throw new Error("not ASN.1 hex string");var Se,Ee,Pe;try{Se=ee(pe,0,["[0]",0],"06"),Ee=ee(pe,0,[1],"04");try{Pe=ee(pe,0,["[1]",0],"03")}catch{}}catch{throw new Error("malformed PKCS#1/5 plain ECC private key")}if(this.curveName=K(Se),this.curveName===void 0)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(Pe),this.setPrivateKeyHex(Ee),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(pe){if(se(pe)===!1)throw new h("not ASN.1 hex string");var Se,Ee,Pe;try{ee(pe,0,[1,0],"06"),Se=ee(pe,0,[1,1],"06"),Ee=ee(pe,0,[2,0,1],"04");try{Pe=ee(pe,0,[2,0,"[1]",0],"03")}catch{}}catch{throw new h("malformed PKCS#8 plain ECC private key")}if(this.curveName=K(Se),this.curveName===void 0)throw new h("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(Pe),this.setPrivateKeyHex(Ee),this.isPublic=!1},this.readPKCS8PubKeyHex=function(pe){if(se(pe)===!1)throw new h("not ASN.1 hex string");var Se,Ee;try{ee(pe,0,[0,0],"06"),Se=ee(pe,0,[0,1],"06"),Ee=ee(pe,0,[1],"03")}catch{throw new h("malformed PKCS#8 ECC public key")}if(this.curveName=K(Se),this.curveName===null)throw new h("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(Ee)},this.readCertPubKeyHex=function(pe,Se){if(se(pe)===!1)throw new h("not ASN.1 hex string");var Ee,Pe;try{Ee=ee(pe,0,[0,5,0,1],"06"),Pe=ee(pe,0,[0,5,1],"03")}catch{throw new h("malformed X.509 certificate ECC public key")}if(this.curveName=K(Ee),this.curveName===null)throw new h("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(Pe)},p!==void 0&&p.curve!==void 0&&(this.curveName=p.curve),this.curveName===void 0&&(this.curveName="secp256r1"),this.setNamedCurve(this.curveName),p!==void 0&&(p.prv!==void 0&&this.setPrivateKeyHex(p.prv),p.pub!==void 0&&this.setPublicKeyHex(p.pub))},F.crypto.ECDSA.parseSigHex=function(p){var h=F.crypto.ECDSA.parseSigHexInHexRS(p);return{r:new D(h.r,16),s:new D(h.s,16)}},F.crypto.ECDSA.parseSigHexInHexRS=function(p){var h=we,y=h.getChildIdx,E=h.getV;if(h.checkStrictDER(p,0),p.substr(0,2)!="30")throw new Error("signature is not a ASN.1 sequence");var I=y(p,0);if(I.length!=2)throw new Error("signature shall have two elements");var q=I[0],K=I[1];if(p.substr(q,2)!="02")throw new Error("1st item not ASN.1 integer");if(p.substr(K,2)!="02")throw new Error("2nd item not ASN.1 integer");return{r:E(p,q),s:E(p,K)}},F.crypto.ECDSA.asn1SigToConcatSig=function(p){var h=F.crypto.ECDSA.parseSigHexInHexRS(p),y=h.r,E=h.s;if(y.substr(0,2)=="00"&&y.length%32==2&&(y=y.substr(2)),E.substr(0,2)=="00"&&E.length%32==2&&(E=E.substr(2)),y.length%32==30&&(y="00"+y),E.length%32==30&&(E="00"+E),y.length%32!=0)throw"unknown ECDSA sig r length error";if(E.length%32!=0)throw"unknown ECDSA sig s length error";return y+E},F.crypto.ECDSA.concatSigToASN1Sig=function(p){if(p.length/2*8%128!=0)throw"unknown ECDSA concatinated r-s sig length error";var h=p.substr(0,p.length/2),y=p.substr(p.length/2);return F.crypto.ECDSA.hexRSSigToASN1Sig(h,y)},F.crypto.ECDSA.hexRSSigToASN1Sig=function(p,h){var y=new D(p,16),E=new D(h,16);return F.crypto.ECDSA.biRSSigToASN1Sig(y,E)},F.crypto.ECDSA.biRSSigToASN1Sig=function(p,h){var y=F.asn1,E=new y.DERInteger({bigint:p}),I=new y.DERInteger({bigint:h});return new y.DERSequence({array:[E,I]}).getEncodedHex()},F.crypto.ECDSA.getName=function(p){return p==="2b8104001f"?"secp192k1":p==="2a8648ce3d030107"?"secp256r1":p==="2b8104000a"?"secp256k1":p==="2b81040021"?"secp224r1":p==="2b81040022"?"secp384r1":"|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(p)!==-1?"secp256r1":"|secp256k1|".indexOf(p)!==-1?"secp256k1":"|secp224r1|NIST P-224|P-224|".indexOf(p)!==-1?"secp224r1":"|secp384r1|NIST P-384|P-384|".indexOf(p)!==-1?"secp384r1":null},F!==void 0&&F||(r.KJUR=F={}),F.crypto!==void 0&&F.crypto||(F.crypto={}),F.crypto.ECParameterDB=new function(){var p={},h={};function y(E){return new D(E,16)}this.getByName=function(E){var I=E;if(h[I]!==void 0&&(I=h[E]),p[I]!==void 0)return p[I];throw"unregistered EC curve name: "+I},this.regist=function(E,I,q,K,ce,ee,se,oe,pe,Se,Ee,Pe){p[E]={};var $e=y(q),Le=y(K),Z=y(ce),fe=y(ee),ye=y(se),be=new R($e,Le,Z),Ue=be.decodePointHex("04"+oe+pe);p[E].name=E,p[E].keylen=I,p[E].curve=be,p[E].G=Ue,p[E].n=fe,p[E].h=ye,p[E].oid=Ee,p[E].info=Pe;for(var Me=0;Me<Se.length;Me++)h[Se[Me]]=E}},F.crypto.ECParameterDB.regist("secp128r1",128,"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC","E87579C11079F43DD824993C2CEE5ED3","FFFFFFFE0000000075A30D1B9038A115","1","161FF7528B899B2D0C28607CA52C5B86","CF5AC8395BAFEB13C02DA292DDED7A83",[],"","secp128r1 : SECG curve over a 128 bit prime field"),F.crypto.ECParameterDB.regist("secp160k1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73","0","7","0100000000000000000001B8FA16DFAB9ACA16B6B3","1","3B4C382CE37AA192A4019E763036F4F5DD4D7EBB","938CF935318FDCED6BC28286531733C3F03C4FEE",[],"","secp160k1 : SECG curve over a 160 bit prime field"),F.crypto.ECParameterDB.regist("secp160r1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC","1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45","0100000000000000000001F4C8F927AED3CA752257","1","4A96B5688EF573284664698968C38BB913CBFC82","23A628553168947D59DCC912042351377AC5FB32",[],"","secp160r1 : SECG curve over a 160 bit prime field"),F.crypto.ECParameterDB.regist("secp192k1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37","0","3","FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D","1","DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D","9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D",[]),F.crypto.ECParameterDB.regist("secp192r1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC","64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1","FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831","1","188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012","07192B95FFC8DA78631011ED6B24CDD573F977A11E794811",[]),F.crypto.ECParameterDB.regist("secp224r1",224,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE","B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4","FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D","1","B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21","BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34",[]),F.crypto.ECParameterDB.regist("secp256k1",256,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F","0","7","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141","1","79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798","483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",[]),F.crypto.ECParameterDB.regist("secp256r1",256,"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC","5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B","FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551","1","6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296","4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",["NIST P-256","P-256","prime256v1"]),F.crypto.ECParameterDB.regist("secp384r1",384,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC","B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973","1","AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7","3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f",["NIST P-384","P-384"]),F.crypto.ECParameterDB.regist("secp521r1",521,"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC","051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409","1","C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66","011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",["NIST P-521","P-521"]);var rt=(function(){var p=function(se,oe,pe){return h(T.AES,se,oe,pe)},h=function(se,oe,pe,Se){var Ee=T.enc.Hex.parse(oe),Pe=T.enc.Hex.parse(pe),$e=T.enc.Hex.parse(Se),Le={};Le.key=Pe,Le.iv=$e,Le.ciphertext=Ee;var Z=se.decrypt(Le,Pe,{iv:$e});return T.enc.Hex.stringify(Z)},y=function(se,oe,pe){return E(T.AES,se,oe,pe)},E=function(se,oe,pe,Se){var Ee=T.enc.Hex.parse(oe),Pe=T.enc.Hex.parse(pe),$e=T.enc.Hex.parse(Se),Le=se.encrypt(Ee,Pe,{iv:$e}),Z=T.enc.Hex.parse(Le.toString());return T.enc.Base64.stringify(Z)},I={"AES-256-CBC":{proc:p,eproc:y,keylen:32,ivlen:16},"AES-192-CBC":{proc:p,eproc:y,keylen:24,ivlen:16},"AES-128-CBC":{proc:p,eproc:y,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:function(se,oe,pe){return h(T.TripleDES,se,oe,pe)},eproc:function(se,oe,pe){return E(T.TripleDES,se,oe,pe)},keylen:24,ivlen:8},"DES-CBC":{proc:function(se,oe,pe){return h(T.DES,se,oe,pe)},eproc:function(se,oe,pe){return E(T.DES,se,oe,pe)},keylen:8,ivlen:8}},q=function(se){var oe={},pe=se.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"));pe&&(oe.cipher=pe[1],oe.ivsalt=pe[2]);var Se=se.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));Se&&(oe.type=Se[1]);var Ee=-1,Pe=0;se.indexOf(`\r
|
|
250
|
+
\r
|
|
251
|
+
`)!=-1&&(Ee=se.indexOf(`\r
|
|
252
|
+
\r
|
|
253
|
+
`),Pe=2),se.indexOf(`
|
|
254
|
+
|
|
255
|
+
`)!=-1&&(Ee=se.indexOf(`
|
|
256
|
+
|
|
257
|
+
`),Pe=1);var $e=se.indexOf("-----END");if(Ee!=-1&&$e!=-1){var Le=se.substring(Ee+2*Pe,$e-Pe);Le=Le.replace(/\s+/g,""),oe.data=Le}return oe},K=function(se,oe,pe){for(var Se=pe.substring(0,16),Ee=T.enc.Hex.parse(Se),Pe=T.enc.Utf8.parse(oe),$e=I[se].keylen+I[se].ivlen,Le="",Z=null;;){var fe=T.algo.MD5.create();if(Z!=null&&fe.update(Z),fe.update(Pe),fe.update(Ee),Z=fe.finalize(),(Le+=T.enc.Hex.stringify(Z)).length>=2*$e)break}var ye={};return ye.keyhex=Le.substr(0,2*I[se].keylen),ye.ivhex=Le.substr(2*I[se].keylen,2*I[se].ivlen),ye},ce=function(se,oe,pe,Se){var Ee=T.enc.Base64.parse(se),Pe=T.enc.Hex.stringify(Ee);return(0,I[oe].proc)(Pe,pe,Se)};return{version:"1.0.0",parsePKCS5PEM:function(se){return q(se)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(se,oe,pe){return K(se,oe,pe)},decryptKeyB64:function(se,oe,pe,Se){return ce(se,oe,pe,Se)},getDecryptedKeyHex:function(se,oe){var pe=q(se),Se=(pe.type,pe.cipher),Ee=pe.ivsalt,Pe=pe.data,$e=K(Se,oe,Ee).keyhex;return ce(Pe,Se,$e,Ee)},getEncryptedPKCS5PEMFromPrvKeyHex:function(se,oe,pe,Se,Ee){var Pe="";if(Se!==void 0&&Se!=null||(Se="AES-256-CBC"),I[Se]===void 0)throw new Error("KEYUTIL unsupported algorithm: "+Se);Ee!==void 0&&Ee!=null||(Ee=(function(Z){var fe=T.lib.WordArray.random(Z);return T.enc.Hex.stringify(fe)})(I[Se].ivlen).toUpperCase());var $e=(function(Z,fe,ye,be){return(0,I[fe].eproc)(Z,ye,be)})(oe,Se,K(Se,pe,Ee).keyhex,Ee);return Pe="-----BEGIN "+se+` PRIVATE KEY-----\r
|
|
258
|
+
`,Pe+=`Proc-Type: 4,ENCRYPTED\r
|
|
259
|
+
`,Pe+="DEK-Info: "+Se+","+Ee+`\r
|
|
260
|
+
`,Pe+=`\r
|
|
261
|
+
`,Pe+=$e.replace(/(.{64})/g,`$1\r
|
|
262
|
+
`),Pe+=`\r
|
|
263
|
+
-----END `+se+` PRIVATE KEY-----\r
|
|
264
|
+
`},parseHexOfEncryptedPKCS8:function(se){var oe=we,pe=oe.getChildIdx,Se=oe.getV,Ee={},Pe=pe(se,0);if(Pe.length!=2)throw new Error("malformed format: SEQUENCE(0).items != 2: "+Pe.length);Ee.ciphertext=Se(se,Pe[1]);var $e=pe(se,Pe[0]);if($e.length!=2)throw new Error("malformed format: SEQUENCE(0.0).items != 2: "+$e.length);if(Se(se,$e[0])!="2a864886f70d01050d")throw new Error("this only supports pkcs5PBES2");var Le=pe(se,$e[1]);if($e.length!=2)throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: "+Le.length);var Z=pe(se,Le[1]);if(Z.length!=2)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+Z.length);if(Se(se,Z[0])!="2a864886f70d0307")throw"this only supports TripleDES";Ee.encryptionSchemeAlg="TripleDES",Ee.encryptionSchemeIV=Se(se,Z[1]);var fe=pe(se,Le[0]);if(fe.length!=2)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+fe.length);if(Se(se,fe[0])!="2a864886f70d01050c")throw new Error("this only supports pkcs5PBKDF2");var ye=pe(se,fe[1]);if(ye.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+ye.length);Ee.pbkdf2Salt=Se(se,ye[0]);var be=Se(se,ye[1]);try{Ee.pbkdf2Iter=parseInt(be,16)}catch{throw new Error("malformed format pbkdf2Iter: "+be)}return Ee},getPBKDF2KeyHexFromParam:function(se,oe){var pe=T.enc.Hex.parse(se.pbkdf2Salt),Se=se.pbkdf2Iter,Ee=T.PBKDF2(oe,pe,{keySize:6,iterations:Se});return T.enc.Hex.stringify(Ee)},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(se,oe){var pe=Ae(se,"ENCRYPTED PRIVATE KEY"),Se=this.parseHexOfEncryptedPKCS8(pe),Ee=rt.getPBKDF2KeyHexFromParam(Se,oe),Pe={};Pe.ciphertext=T.enc.Hex.parse(Se.ciphertext);var $e=T.enc.Hex.parse(Ee),Le=T.enc.Hex.parse(Se.encryptionSchemeIV),Z=T.TripleDES.decrypt(Pe,$e,{iv:Le});return T.enc.Hex.stringify(Z)},getKeyFromEncryptedPKCS8PEM:function(se,oe){var pe=this._getPlainPKCS8HexFromEncryptedPKCS8PEM(se,oe);return this.getKeyFromPlainPrivatePKCS8Hex(pe)},parsePlainPrivatePKCS8Hex:function(se){var oe=we,pe=oe.getChildIdx,Se=oe.getV,Ee={algparam:null};if(se.substr(0,2)!="30")throw new Error("malformed plain PKCS8 private key(code:001)");var Pe=pe(se,0);if(Pe.length<3)throw new Error("malformed plain PKCS8 private key(code:002)");if(se.substr(Pe[1],2)!="30")throw new Error("malformed PKCS8 private key(code:003)");var $e=pe(se,Pe[1]);if($e.length!=2)throw new Error("malformed PKCS8 private key(code:004)");if(se.substr($e[0],2)!="06")throw new Error("malformed PKCS8 private key(code:005)");if(Ee.algoid=Se(se,$e[0]),se.substr($e[1],2)=="06"&&(Ee.algparam=Se(se,$e[1])),se.substr(Pe[2],2)!="04")throw new Error("malformed PKCS8 private key(code:006)");return Ee.keyidx=oe.getVidx(se,Pe[2]),Ee},getKeyFromPlainPrivatePKCS8PEM:function(se){var oe=Ae(se,"PRIVATE KEY");return this.getKeyFromPlainPrivatePKCS8Hex(oe)},getKeyFromPlainPrivatePKCS8Hex:function(se){var oe,pe=this.parsePlainPrivatePKCS8Hex(se);if(pe.algoid=="2a864886f70d010101")oe=new Ne;else if(pe.algoid=="2a8648ce380401")oe=new F.crypto.DSA;else{if(pe.algoid!="2a8648ce3d0201")throw new Error("unsupported private key algorithm");oe=new F.crypto.ECDSA}return oe.readPKCS8PrvKeyHex(se),oe},_getKeyFromPublicPKCS8Hex:function(se){var oe,pe=we.getVbyList(se,0,[0,0],"06");if(pe==="2a864886f70d010101")oe=new Ne;else if(pe==="2a8648ce380401")oe=new F.crypto.DSA;else{if(pe!=="2a8648ce3d0201")throw new Error("unsupported PKCS#8 public key hex");oe=new F.crypto.ECDSA}return oe.readPKCS8PubKeyHex(se),oe},parsePublicRawRSAKeyHex:function(se){var oe=we,pe=oe.getChildIdx,Se=oe.getV,Ee={};if(se.substr(0,2)!="30")throw new Error("malformed RSA key(code:001)");var Pe=pe(se,0);if(Pe.length!=2)throw new Error("malformed RSA key(code:002)");if(se.substr(Pe[0],2)!="02")throw new Error("malformed RSA key(code:003)");if(Ee.n=Se(se,Pe[0]),se.substr(Pe[1],2)!="02")throw new Error("malformed RSA key(code:004)");return Ee.e=Se(se,Pe[1]),Ee},parsePublicPKCS8Hex:function(se){var oe=we,pe=oe.getChildIdx,Se=oe.getV,Ee={algparam:null},Pe=pe(se,0);if(Pe.length!=2)throw new Error("outer DERSequence shall have 2 elements: "+Pe.length);var $e=Pe[0];if(se.substr($e,2)!="30")throw new Error("malformed PKCS8 public key(code:001)");var Le=pe(se,$e);if(Le.length!=2)throw new Error("malformed PKCS8 public key(code:002)");if(se.substr(Le[0],2)!="06")throw new Error("malformed PKCS8 public key(code:003)");if(Ee.algoid=Se(se,Le[0]),se.substr(Le[1],2)=="06"?Ee.algparam=Se(se,Le[1]):se.substr(Le[1],2)=="30"&&(Ee.algparam={},Ee.algparam.p=oe.getVbyList(se,Le[1],[0],"02"),Ee.algparam.q=oe.getVbyList(se,Le[1],[1],"02"),Ee.algparam.g=oe.getVbyList(se,Le[1],[2],"02")),se.substr(Pe[1],2)!="03")throw new Error("malformed PKCS8 public key(code:004)");return Ee.key=Se(se,Pe[1]).substr(2),Ee}}})();rt.getKey=function(p,h,y){var E=(Le=we).getChildIdx,I=(Le.getV,Le.getVbyList),q=F.crypto,K=q.ECDSA,ce=q.DSA,ee=Ne,se=Ae,oe=rt;if(ee!==void 0&&p instanceof ee||K!==void 0&&p instanceof K||ce!==void 0&&p instanceof ce)return p;if(p.curve!==void 0&&p.xy!==void 0&&p.d===void 0)return new K({pub:p.xy,curve:p.curve});if(p.curve!==void 0&&p.d!==void 0)return new K({prv:p.d,curve:p.curve});if(p.kty===void 0&&p.n!==void 0&&p.e!==void 0&&p.d===void 0)return(tt=new ee).setPublic(p.n,p.e),tt;if(p.kty===void 0&&p.n!==void 0&&p.e!==void 0&&p.d!==void 0&&p.p!==void 0&&p.q!==void 0&&p.dp!==void 0&&p.dq!==void 0&&p.co!==void 0&&p.qi===void 0)return(tt=new ee).setPrivateEx(p.n,p.e,p.d,p.p,p.q,p.dp,p.dq,p.co),tt;if(p.kty===void 0&&p.n!==void 0&&p.e!==void 0&&p.d!==void 0&&p.p===void 0)return(tt=new ee).setPrivate(p.n,p.e,p.d),tt;if(p.p!==void 0&&p.q!==void 0&&p.g!==void 0&&p.y!==void 0&&p.x===void 0)return(tt=new ce).setPublic(p.p,p.q,p.g,p.y),tt;if(p.p!==void 0&&p.q!==void 0&&p.g!==void 0&&p.y!==void 0&&p.x!==void 0)return(tt=new ce).setPrivate(p.p,p.q,p.g,p.y,p.x),tt;if(p.kty==="RSA"&&p.n!==void 0&&p.e!==void 0&&p.d===void 0)return(tt=new ee).setPublic(dt(p.n),dt(p.e)),tt;if(p.kty==="RSA"&&p.n!==void 0&&p.e!==void 0&&p.d!==void 0&&p.p!==void 0&&p.q!==void 0&&p.dp!==void 0&&p.dq!==void 0&&p.qi!==void 0)return(tt=new ee).setPrivateEx(dt(p.n),dt(p.e),dt(p.d),dt(p.p),dt(p.q),dt(p.dp),dt(p.dq),dt(p.qi)),tt;if(p.kty==="RSA"&&p.n!==void 0&&p.e!==void 0&&p.d!==void 0)return(tt=new ee).setPrivate(dt(p.n),dt(p.e),dt(p.d)),tt;if(p.kty==="EC"&&p.crv!==void 0&&p.x!==void 0&&p.y!==void 0&&p.d===void 0){var pe=(Xe=new K({curve:p.crv})).ecparams.keylen/4,Se="04"+("0000000000"+dt(p.x)).slice(-pe)+("0000000000"+dt(p.y)).slice(-pe);return Xe.setPublicKeyHex(Se),Xe}if(p.kty==="EC"&&p.crv!==void 0&&p.x!==void 0&&p.y!==void 0&&p.d!==void 0){pe=(Xe=new K({curve:p.crv})).ecparams.keylen/4,Se="04"+("0000000000"+dt(p.x)).slice(-pe)+("0000000000"+dt(p.y)).slice(-pe);var Ee=("0000000000"+dt(p.d)).slice(-pe);return Xe.setPublicKeyHex(Se),Xe.setPrivateKeyHex(Ee),Xe}if(y==="pkcs5prv"){var Pe,$e=p,Le=we;if((Pe=E($e,0)).length===9)(tt=new ee).readPKCS5PrvKeyHex($e);else if(Pe.length===6)(tt=new ce).readPKCS5PrvKeyHex($e);else{if(!(Pe.length>2&&$e.substr(Pe[1],2)==="04"))throw new Error("unsupported PKCS#1/5 hexadecimal key");(tt=new K).readPKCS5PrvKeyHex($e)}return tt}if(y==="pkcs8prv")return tt=oe.getKeyFromPlainPrivatePKCS8Hex(p);if(y==="pkcs8pub")return oe._getKeyFromPublicPKCS8Hex(p);if(y==="x509pub")return Ft.getPublicKeyFromCertHex(p);if(p.indexOf("-END CERTIFICATE-",0)!=-1||p.indexOf("-END X509 CERTIFICATE-",0)!=-1||p.indexOf("-END TRUSTED CERTIFICATE-",0)!=-1)return Ft.getPublicKeyFromCertPEM(p);if(p.indexOf("-END PUBLIC KEY-")!=-1){var Z=Ae(p,"PUBLIC KEY");return oe._getKeyFromPublicPKCS8Hex(Z)}if(p.indexOf("-END RSA PRIVATE KEY-")!=-1&&p.indexOf("4,ENCRYPTED")==-1){var fe=se(p,"RSA PRIVATE KEY");return oe.getKey(fe,null,"pkcs5prv")}if(p.indexOf("-END DSA PRIVATE KEY-")!=-1&&p.indexOf("4,ENCRYPTED")==-1){var ye=I(mt=se(p,"DSA PRIVATE KEY"),0,[1],"02"),be=I(mt,0,[2],"02"),Ue=I(mt,0,[3],"02"),Me=I(mt,0,[4],"02"),Ye=I(mt,0,[5],"02");return(tt=new ce).setPrivate(new D(ye,16),new D(be,16),new D(Ue,16),new D(Me,16),new D(Ye,16)),tt}if(p.indexOf("-END EC PRIVATE KEY-")!=-1&&p.indexOf("4,ENCRYPTED")==-1)return fe=se(p,"EC PRIVATE KEY"),oe.getKey(fe,null,"pkcs5prv");if(p.indexOf("-END PRIVATE KEY-")!=-1)return oe.getKeyFromPlainPrivatePKCS8PEM(p);if(p.indexOf("-END RSA PRIVATE KEY-")!=-1&&p.indexOf("4,ENCRYPTED")!=-1){var Ke=oe.getDecryptedKeyHex(p,h),st=new Ne;return st.readPKCS5PrvKeyHex(Ke),st}if(p.indexOf("-END EC PRIVATE KEY-")!=-1&&p.indexOf("4,ENCRYPTED")!=-1){var Xe,tt=I(mt=oe.getDecryptedKeyHex(p,h),0,[1],"04"),bt=I(mt,0,[2,0],"06"),St=I(mt,0,[3,0],"03").substr(2);if(F.crypto.OID.oidhex2name[bt]===void 0)throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+bt);return(Xe=new K({curve:F.crypto.OID.oidhex2name[bt]})).setPublicKeyHex(St),Xe.setPrivateKeyHex(tt),Xe.isPublic=!1,Xe}if(p.indexOf("-END DSA PRIVATE KEY-")!=-1&&p.indexOf("4,ENCRYPTED")!=-1){var mt;return ye=I(mt=oe.getDecryptedKeyHex(p,h),0,[1],"02"),be=I(mt,0,[2],"02"),Ue=I(mt,0,[3],"02"),Me=I(mt,0,[4],"02"),Ye=I(mt,0,[5],"02"),(tt=new ce).setPrivate(new D(ye,16),new D(be,16),new D(Ue,16),new D(Me,16),new D(Ye,16)),tt}if(p.indexOf("-END ENCRYPTED PRIVATE KEY-")!=-1)return oe.getKeyFromEncryptedPKCS8PEM(p,h);throw new Error("not supported argument")},rt.generateKeypair=function(p,h){if(p=="RSA"){var y=h;(K=new Ne).generate(y,"10001"),K.isPrivate=!0,K.isPublic=!0;var E=new Ne,I=K.n.toString(16),q=K.e.toString(16);return E.setPublic(I,q),E.isPrivate=!1,E.isPublic=!0,(ce={}).prvKeyObj=K,ce.pubKeyObj=E,ce}if(p=="EC"){var K,ce,ee=h,se=new F.crypto.ECDSA({curve:ee}).generateKeyPairHex();return(K=new F.crypto.ECDSA({curve:ee})).setPublicKeyHex(se.ecpubhex),K.setPrivateKeyHex(se.ecprvhex),K.isPrivate=!0,K.isPublic=!1,(E=new F.crypto.ECDSA({curve:ee})).setPublicKeyHex(se.ecpubhex),E.isPrivate=!1,E.isPublic=!0,(ce={}).prvKeyObj=K,ce.pubKeyObj=E,ce}throw new Error("unknown algorithm: "+p)},rt.getPEM=function(p,h,y,E,I,q){var K=F,ce=K.asn1,ee=ce.DERObjectIdentifier,se=ce.DERInteger,oe=ce.ASN1Util.newObject,pe=ce.x509.SubjectPublicKeyInfo,Se=K.crypto,Ee=Se.DSA,Pe=Se.ECDSA,$e=Ne;function Le(Xe){return oe({seq:[{int:0},{int:{bigint:Xe.n}},{int:Xe.e},{int:{bigint:Xe.d}},{int:{bigint:Xe.p}},{int:{bigint:Xe.q}},{int:{bigint:Xe.dmp1}},{int:{bigint:Xe.dmq1}},{int:{bigint:Xe.coeff}}]})}function Z(Xe){return oe({seq:[{int:1},{octstr:{hex:Xe.prvKeyHex}},{tag:["a0",!0,{oid:{name:Xe.curveName}}]},{tag:["a1",!0,{bitstr:{hex:"00"+Xe.pubKeyHex}}]}]})}function fe(Xe){return oe({seq:[{int:0},{int:{bigint:Xe.p}},{int:{bigint:Xe.q}},{int:{bigint:Xe.g}},{int:{bigint:Xe.y}},{int:{bigint:Xe.x}}]})}if(($e!==void 0&&p instanceof $e||Ee!==void 0&&p instanceof Ee||Pe!==void 0&&p instanceof Pe)&&p.isPublic==1&&(h===void 0||h=="PKCS8PUB"))return Ie(Me=new pe(p).getEncodedHex(),"PUBLIC KEY");if(h=="PKCS1PRV"&&$e!==void 0&&p instanceof $e&&(y===void 0||y==null)&&p.isPrivate==1)return Ie(Me=Le(p).getEncodedHex(),"RSA PRIVATE KEY");if(h=="PKCS1PRV"&&Pe!==void 0&&p instanceof Pe&&(y===void 0||y==null)&&p.isPrivate==1){var ye=new ee({name:p.curveName}).getEncodedHex(),be=Z(p).getEncodedHex(),Ue="";return Ue+=Ie(ye,"EC PARAMETERS"),Ue+=Ie(be,"EC PRIVATE KEY")}if(h=="PKCS1PRV"&&Ee!==void 0&&p instanceof Ee&&(y===void 0||y==null)&&p.isPrivate==1)return Ie(Me=fe(p).getEncodedHex(),"DSA PRIVATE KEY");if(h=="PKCS5PRV"&&$e!==void 0&&p instanceof $e&&y!==void 0&&y!=null&&p.isPrivate==1){var Me=Le(p).getEncodedHex();return E===void 0&&(E="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",Me,y,E,q)}if(h=="PKCS5PRV"&&Pe!==void 0&&p instanceof Pe&&y!==void 0&&y!=null&&p.isPrivate==1)return Me=Z(p).getEncodedHex(),E===void 0&&(E="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",Me,y,E,q);if(h=="PKCS5PRV"&&Ee!==void 0&&p instanceof Ee&&y!==void 0&&y!=null&&p.isPrivate==1)return Me=fe(p).getEncodedHex(),E===void 0&&(E="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",Me,y,E,q);var Ye=function(tt,bt){var St=Ke(tt,bt);return new oe({seq:[{seq:[{oid:{name:"pkcs5PBES2"}},{seq:[{seq:[{oid:{name:"pkcs5PBKDF2"}},{seq:[{octstr:{hex:St.pbkdf2Salt}},{int:St.pbkdf2Iter}]}]},{seq:[{oid:{name:"des-EDE3-CBC"}},{octstr:{hex:St.encryptionSchemeIV}}]}]}]},{octstr:{hex:St.ciphertext}}]}).getEncodedHex()},Ke=function(tt,bt){var St=T.lib.WordArray.random(8),mt=T.lib.WordArray.random(8),Ht=T.PBKDF2(bt,St,{keySize:6,iterations:100}),jt=T.enc.Hex.parse(tt),qt=T.TripleDES.encrypt(jt,Ht,{iv:mt})+"",xt={};return xt.ciphertext=qt,xt.pbkdf2Salt=T.enc.Hex.stringify(St),xt.pbkdf2Iter=100,xt.encryptionSchemeAlg="DES-EDE3-CBC",xt.encryptionSchemeIV=T.enc.Hex.stringify(mt),xt};if(h=="PKCS8PRV"&&$e!=null&&p instanceof $e&&p.isPrivate==1){var st=Le(p).getEncodedHex();return Me=oe({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:st}}]}).getEncodedHex(),y===void 0||y==null?Ie(Me,"PRIVATE KEY"):Ie(be=Ye(Me,y),"ENCRYPTED PRIVATE KEY")}if(h=="PKCS8PRV"&&Pe!==void 0&&p instanceof Pe&&p.isPrivate==1)return st=new oe({seq:[{int:1},{octstr:{hex:p.prvKeyHex}},{tag:["a1",!0,{bitstr:{hex:"00"+p.pubKeyHex}}]}]}).getEncodedHex(),Me=oe({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:p.curveName}}]},{octstr:{hex:st}}]}).getEncodedHex(),y===void 0||y==null?Ie(Me,"PRIVATE KEY"):Ie(be=Ye(Me,y),"ENCRYPTED PRIVATE KEY");if(h=="PKCS8PRV"&&Ee!==void 0&&p instanceof Ee&&p.isPrivate==1)return st=new se({bigint:p.x}).getEncodedHex(),Me=oe({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:p.p}},{int:{bigint:p.q}},{int:{bigint:p.g}}]}]},{octstr:{hex:st}}]}).getEncodedHex(),y===void 0||y==null?Ie(Me,"PRIVATE KEY"):Ie(be=Ye(Me,y),"ENCRYPTED PRIVATE KEY");throw new Error("unsupported object nor format")},rt.getKeyFromCSRPEM=function(p){var h=Ae(p,"CERTIFICATE REQUEST");return rt.getKeyFromCSRHex(h)},rt.getKeyFromCSRHex=function(p){var h=rt.parseCSRHex(p);return rt.getKey(h.p8pubkeyhex,null,"pkcs8pub")},rt.parseCSRHex=function(p){var h=we,y=h.getChildIdx,E=h.getTLV,I={},q=p;if(q.substr(0,2)!="30")throw new Error("malformed CSR(code:001)");var K=y(q,0);if(K.length<1)throw new Error("malformed CSR(code:002)");if(q.substr(K[0],2)!="30")throw new Error("malformed CSR(code:003)");var ce=y(q,K[0]);if(ce.length<3)throw new Error("malformed CSR(code:004)");return I.p8pubkeyhex=E(q,ce[2]),I},rt.getKeyID=function(p){var h=rt,y=we;typeof p=="string"&&p.indexOf("BEGIN ")!=-1&&(p=h.getKey(p));var E=Ae(h.getPEM(p)),I=y.getIdxbyList(E,0,[1]),q=y.getV(E,I).substring(2);return F.crypto.Util.hashHex(q,"sha1")},rt.getJWKFromKey=function(p){var h={};if(p instanceof Ne&&p.isPrivate)return h.kty="RSA",h.n=wt(p.n.toString(16)),h.e=wt(p.e.toString(16)),h.d=wt(p.d.toString(16)),h.p=wt(p.p.toString(16)),h.q=wt(p.q.toString(16)),h.dp=wt(p.dmp1.toString(16)),h.dq=wt(p.dmq1.toString(16)),h.qi=wt(p.coeff.toString(16)),h;if(p instanceof Ne&&p.isPublic)return h.kty="RSA",h.n=wt(p.n.toString(16)),h.e=wt(p.e.toString(16)),h;if(p instanceof F.crypto.ECDSA&&p.isPrivate){if((E=p.getShortNISTPCurveName())!=="P-256"&&E!=="P-384")throw new Error("unsupported curve name for JWT: "+E);var y=p.getPublicKeyXYHex();return h.kty="EC",h.crv=E,h.x=wt(y.x),h.y=wt(y.y),h.d=wt(p.prvKeyHex),h}if(p instanceof F.crypto.ECDSA&&p.isPublic){var E;if((E=p.getShortNISTPCurveName())!=="P-256"&&E!=="P-384")throw new Error("unsupported curve name for JWT: "+E);return y=p.getPublicKeyXYHex(),h.kty="EC",h.crv=E,h.x=wt(y.x),h.y=wt(y.y),h}throw new Error("not supported key object")},Ne.getPosArrayOfChildrenFromHex=function(p){return we.getChildIdx(p,0)},Ne.getHexValueArrayOfChildrenFromHex=function(p){var h,y=we.getV,E=y(p,(h=Ne.getPosArrayOfChildrenFromHex(p))[0]),I=y(p,h[1]),q=y(p,h[2]),K=y(p,h[3]),ce=y(p,h[4]),ee=y(p,h[5]),se=y(p,h[6]),oe=y(p,h[7]),pe=y(p,h[8]);return(h=new Array).push(E,I,q,K,ce,ee,se,oe,pe),h},Ne.prototype.readPrivateKeyFromPEMString=function(p){var h=Ae(p),y=Ne.getHexValueArrayOfChildrenFromHex(h);this.setPrivateEx(y[1],y[2],y[3],y[4],y[5],y[6],y[7],y[8])},Ne.prototype.readPKCS5PrvKeyHex=function(p){var h=Ne.getHexValueArrayOfChildrenFromHex(p);this.setPrivateEx(h[1],h[2],h[3],h[4],h[5],h[6],h[7],h[8])},Ne.prototype.readPKCS8PrvKeyHex=function(p){var h,y,E,I,q,K,ce,ee,se=we,oe=se.getVbyListEx;if(se.isASN1HEX(p)===!1)throw new Error("not ASN.1 hex string");try{h=oe(p,0,[2,0,1],"02"),y=oe(p,0,[2,0,2],"02"),E=oe(p,0,[2,0,3],"02"),I=oe(p,0,[2,0,4],"02"),q=oe(p,0,[2,0,5],"02"),K=oe(p,0,[2,0,6],"02"),ce=oe(p,0,[2,0,7],"02"),ee=oe(p,0,[2,0,8],"02")}catch{throw new Error("malformed PKCS#8 plain RSA private key")}this.setPrivateEx(h,y,E,I,q,K,ce,ee)},Ne.prototype.readPKCS5PubKeyHex=function(p){var h=we,y=h.getV;if(h.isASN1HEX(p)===!1)throw new Error("keyHex is not ASN.1 hex string");var E=h.getChildIdx(p,0);if(E.length!==2||p.substr(E[0],2)!=="02"||p.substr(E[1],2)!=="02")throw new Error("wrong hex for PKCS#5 public key");var I=y(p,E[0]),q=y(p,E[1]);this.setPublic(I,q)},Ne.prototype.readPKCS8PubKeyHex=function(p){var h=we;if(h.isASN1HEX(p)===!1)throw new Error("not ASN.1 hex string");if(h.getTLVbyListEx(p,0,[0,0])!=="06092a864886f70d010101")throw new Error("not PKCS8 RSA public key");var y=h.getTLVbyListEx(p,0,[1,0]);this.readPKCS5PubKeyHex(y)},Ne.prototype.readCertPubKeyHex=function(p,h){var y,E;(y=new Ft).readCertHex(p),E=y.getPublicKeyHex(),this.readPKCS8PubKeyHex(E)};function Rt(p,h){for(var y="",E=h/4-p.length,I=0;I<E;I++)y+="0";return y+p}function Jr(p,h,y){for(var E="",I=0;E.length<h;)E+=At(y(It(p+String.fromCharCode.apply(String,[(4278190080&I)>>24,(16711680&I)>>16,(65280&I)>>8,255&I])))),I+=1;return E}function Ct(p){for(var h in F.crypto.Util.DIGESTINFOHEAD){var y=F.crypto.Util.DIGESTINFOHEAD[h],E=y.length;if(p.substring(0,E)==y)return[h,p.substring(E)]}return[]}function Ft(p){var h,y=we,E=y.getChildIdx,I=y.getV,q=y.getTLV,K=y.getVbyList,ce=y.getVbyListEx,ee=y.getTLVbyList,se=y.getTLVbyListEx,oe=y.getIdxbyList,pe=y.getIdxbyListEx,Se=y.getVidx,Ee=y.getInt,Pe=y.oidname,$e=y.hextooidstr,Le=Ae;try{h=F.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV}catch{}this.HEX2STAG={"0c":"utf8",13:"prn",16:"ia5","1a":"vis","1e":"bmp"},this.hex=null,this.version=0,this.foffset=0,this.aExtInfo=null,this.getVersion=function(){if(this.hex===null||this.version!==0)return this.version;var Z=ee(this.hex,0,[0,0]);if(Z.substr(0,2)=="a0"){var fe=ee(Z,0,[0]),ye=Ee(fe,0);if(ye<0||2<ye)throw new Error("malformed version field");return this.version=ye+1,this.version}return this.version=1,this.foffset=-1,1},this.getSerialNumberHex=function(){return ce(this.hex,0,[0,0],"02")},this.getSignatureAlgorithmField=function(){var Z=se(this.hex,0,[0,1]);return this.getAlgorithmIdentifierName(Z)},this.getAlgorithmIdentifierName=function(Z){for(var fe in h)if(Z===h[fe])return fe;return Pe(ce(Z,0,[0],"06"))},this.getIssuer=function(){return this.getX500Name(this.getIssuerHex())},this.getIssuerHex=function(){return ee(this.hex,0,[0,3+this.foffset],"30")},this.getIssuerString=function(){return this.getIssuer().str},this.getSubject=function(){return this.getX500Name(this.getSubjectHex())},this.getSubjectHex=function(){return ee(this.hex,0,[0,5+this.foffset],"30")},this.getSubjectString=function(){return this.getSubject().str},this.getNotBefore=function(){var Z=K(this.hex,0,[0,4+this.foffset,0]);return Z=Z.replace(/(..)/g,"%$1"),Z=decodeURIComponent(Z)},this.getNotAfter=function(){var Z=K(this.hex,0,[0,4+this.foffset,1]);return Z=Z.replace(/(..)/g,"%$1"),Z=decodeURIComponent(Z)},this.getPublicKeyHex=function(){return y.getTLVbyList(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyIdx=function(){return oe(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyContentIdx=function(){var Z=this.getPublicKeyIdx();return oe(this.hex,Z,[1,0],"30")},this.getPublicKey=function(){return rt.getKey(this.getPublicKeyHex(),null,"pkcs8pub")},this.getSignatureAlgorithmName=function(){var Z=ee(this.hex,0,[1],"30");return this.getAlgorithmIdentifierName(Z)},this.getSignatureValueHex=function(){return K(this.hex,0,[2],"03",!0)},this.verifySignature=function(Z){var fe=this.getSignatureAlgorithmField(),ye=this.getSignatureValueHex(),be=ee(this.hex,0,[0],"30"),Ue=new F.crypto.Signature({alg:fe});return Ue.init(Z),Ue.updateHex(be),Ue.verify(ye)},this.parseExt=function(Z){var fe,ye,be;if(Z===void 0){if(be=this.hex,this.version!==3)return-1;fe=oe(be,0,[0,7,0],"30"),ye=E(be,fe)}else{be=Ae(Z);var Ue=oe(be,0,[0,3,0,0],"06");if(I(be,Ue)!="2a864886f70d01090e")return void(this.aExtInfo=new Array);fe=oe(be,0,[0,3,0,1,0],"30"),ye=E(be,fe),this.hex=be}this.aExtInfo=new Array;for(var Me=0;Me<ye.length;Me++){var Ye={critical:!1},Ke=0;E(be,ye[Me]).length===3&&(Ye.critical=!0,Ke=1),Ye.oid=y.hextooidstr(K(be,ye[Me],[0],"06"));var st=oe(be,ye[Me],[1+Ke]);Ye.vidx=Se(be,st),this.aExtInfo.push(Ye)}},this.getExtInfo=function(Z){var fe=this.aExtInfo,ye=Z;if(Z.match(/^[0-9.]+$/)||(ye=F.asn1.x509.OID.name2oid(Z)),ye!==""){for(var be=0;be<fe.length;be++)if(fe[be].oid===ye)return fe[be]}},this.getExtBasicConstraints=function(Z,fe){if(Z===void 0&&fe===void 0){var ye=this.getExtInfo("basicConstraints");if(ye===void 0)return;Z=q(this.hex,ye.vidx),fe=ye.critical}var be={extname:"basicConstraints"};if(fe&&(be.critical=!0),Z==="3000")return be;if(Z==="30030101ff")return be.cA=!0,be;if(Z.substr(0,12)==="30060101ff02"){var Ue=I(Z,10),Me=parseInt(Ue,16);return be.cA=!0,be.pathLen=Me,be}throw new Error("hExtV parse error: "+Z)},this.getExtKeyUsage=function(Z,fe){if(Z===void 0&&fe===void 0){var ye=this.getExtInfo("keyUsage");if(ye===void 0)return;Z=q(this.hex,ye.vidx),fe=ye.critical}var be={extname:"keyUsage"};return fe&&(be.critical=!0),be.names=this.getExtKeyUsageString(Z).split(","),be},this.getExtKeyUsageBin=function(Z){if(Z===void 0){var fe=this.getExtInfo("keyUsage");if(fe===void 0)return"";Z=q(this.hex,fe.vidx)}if(Z.length!=8&&Z.length!=10)throw new Error("malformed key usage value: "+Z);var ye="000000000000000"+parseInt(Z.substr(6),16).toString(2);return Z.length==8&&(ye=ye.slice(-8)),Z.length==10&&(ye=ye.slice(-16)),(ye=ye.replace(/0+$/,""))==""&&(ye="0"),ye},this.getExtKeyUsageString=function(Z){for(var fe=this.getExtKeyUsageBin(Z),ye=new Array,be=0;be<fe.length;be++)fe.substr(be,1)=="1"&&ye.push(Ft.KEYUSAGE_NAME[be]);return ye.join(",")},this.getExtSubjectKeyIdentifier=function(Z,fe){if(Z===void 0&&fe===void 0){var ye=this.getExtInfo("subjectKeyIdentifier");if(ye===void 0)return;Z=q(this.hex,ye.vidx),fe=ye.critical}var be={extname:"subjectKeyIdentifier"};fe&&(be.critical=!0);var Ue=I(Z,0);return be.kid={hex:Ue},be},this.getExtAuthorityKeyIdentifier=function(Z,fe){if(Z===void 0&&fe===void 0){var ye=this.getExtInfo("authorityKeyIdentifier");if(ye===void 0)return;Z=q(this.hex,ye.vidx),fe=ye.critical}var be={extname:"authorityKeyIdentifier"};fe&&(be.critical=!0);for(var Ue=E(Z,0),Me=0;Me<Ue.length;Me++){var Ye=Z.substr(Ue[Me],2);if(Ye==="80"&&(be.kid={hex:I(Z,Ue[Me])}),Ye==="a1"){var Ke=q(Z,Ue[Me]),st=this.getGeneralNames(Ke);be.issuer=st[0].dn}Ye==="82"&&(be.sn={hex:I(Z,Ue[Me])})}return be},this.getExtExtKeyUsage=function(Z,fe){if(Z===void 0&&fe===void 0){var ye=this.getExtInfo("extKeyUsage");if(ye===void 0)return;Z=q(this.hex,ye.vidx),fe=ye.critical}var be={extname:"extKeyUsage",array:[]};fe&&(be.critical=!0);for(var Ue=E(Z,0),Me=0;Me<Ue.length;Me++)be.array.push(Pe(I(Z,Ue[Me])));return be},this.getExtExtKeyUsageName=function(){var Z=this.getExtInfo("extKeyUsage");if(Z===void 0)return Z;var fe=new Array,ye=q(this.hex,Z.vidx);if(ye==="")return fe;for(var be=E(ye,0),Ue=0;Ue<be.length;Ue++)fe.push(Pe(I(ye,be[Ue])));return fe},this.getExtSubjectAltName=function(Z,fe){if(Z===void 0&&fe===void 0){var ye=this.getExtInfo("subjectAltName");if(ye===void 0)return;Z=q(this.hex,ye.vidx),fe=ye.critical}var be={extname:"subjectAltName",array:[]};return fe&&(be.critical=!0),be.array=this.getGeneralNames(Z),be},this.getExtIssuerAltName=function(Z,fe){if(Z===void 0&&fe===void 0){var ye=this.getExtInfo("issuerAltName");if(ye===void 0)return;Z=q(this.hex,ye.vidx),fe=ye.critical}var be={extname:"issuerAltName",array:[]};return fe&&(be.critical=!0),be.array=this.getGeneralNames(Z),be},this.getGeneralNames=function(Z){for(var fe=E(Z,0),ye=[],be=0;be<fe.length;be++){var Ue=this.getGeneralName(q(Z,fe[be]));Ue!==void 0&&ye.push(Ue)}return ye},this.getGeneralName=function(Z){var fe=Z.substr(0,2),ye=I(Z,0),be=At(ye);return fe=="81"?{rfc822:be}:fe=="82"?{dns:be}:fe=="86"?{uri:be}:fe=="87"?{ip:ar(ye)}:fe=="a4"?{dn:this.getX500Name(ye)}:void 0},this.getExtSubjectAltName2=function(){var Z,fe,ye,be=this.getExtInfo("subjectAltName");if(be===void 0)return be;for(var Ue=new Array,Me=q(this.hex,be.vidx),Ye=E(Me,0),Ke=0;Ke<Ye.length;Ke++)ye=Me.substr(Ye[Ke],2),Z=I(Me,Ye[Ke]),ye==="81"&&(fe=yt(Z),Ue.push(["MAIL",fe])),ye==="82"&&(fe=yt(Z),Ue.push(["DNS",fe])),ye==="84"&&(fe=Ft.hex2dn(Z,0),Ue.push(["DN",fe])),ye==="86"&&(fe=yt(Z),Ue.push(["URI",fe])),ye==="87"&&(fe=ar(Z),Ue.push(["IP",fe]));return Ue},this.getExtCRLDistributionPoints=function(Z,fe){if(Z===void 0&&fe===void 0){var ye=this.getExtInfo("cRLDistributionPoints");if(ye===void 0)return;Z=q(this.hex,ye.vidx),fe=ye.critical}var be={extname:"cRLDistributionPoints",array:[]};fe&&(be.critical=!0);for(var Ue=E(Z,0),Me=0;Me<Ue.length;Me++){var Ye=q(Z,Ue[Me]);be.array.push(this.getDistributionPoint(Ye))}return be},this.getDistributionPoint=function(Z){for(var fe={},ye=E(Z,0),be=0;be<ye.length;be++){var Ue=Z.substr(ye[be],2),Me=q(Z,ye[be]);Ue=="a0"&&(fe.dpname=this.getDistributionPointName(Me))}return fe},this.getDistributionPointName=function(Z){for(var fe={},ye=E(Z,0),be=0;be<ye.length;be++){var Ue=Z.substr(ye[be],2),Me=q(Z,ye[be]);Ue=="a0"&&(fe.full=this.getGeneralNames(Me))}return fe},this.getExtCRLDistributionPointsURI=function(){var Z=this.getExtInfo("cRLDistributionPoints");if(Z===void 0)return Z;for(var fe=new Array,ye=E(this.hex,Z.vidx),be=0;be<ye.length;be++)try{var Ue=yt(K(this.hex,ye[be],[0,0,0],"86"));fe.push(Ue)}catch{}return fe},this.getExtAIAInfo=function(){var Z=this.getExtInfo("authorityInfoAccess");if(Z===void 0)return Z;for(var fe={ocsp:[],caissuer:[]},ye=E(this.hex,Z.vidx),be=0;be<ye.length;be++){var Ue=K(this.hex,ye[be],[0],"06"),Me=K(this.hex,ye[be],[1],"86");Ue==="2b06010505073001"&&fe.ocsp.push(yt(Me)),Ue==="2b06010505073002"&&fe.caissuer.push(yt(Me))}return fe},this.getExtAuthorityInfoAccess=function(Z,fe){if(Z===void 0&&fe===void 0){var ye=this.getExtInfo("authorityInfoAccess");if(ye===void 0)return;Z=q(this.hex,ye.vidx),fe=ye.critical}var be={extname:"authorityInfoAccess",array:[]};fe&&(be.critical=!0);for(var Ue=E(Z,0),Me=0;Me<Ue.length;Me++){var Ye=ce(Z,Ue[Me],[0],"06"),Ke=yt(K(Z,Ue[Me],[1],"86"));if(Ye=="2b06010505073001")be.array.push({ocsp:Ke});else{if(Ye!="2b06010505073002")throw new Error("unknown method: "+Ye);be.array.push({caissuer:Ke})}}return be},this.getExtCertificatePolicies=function(Z,fe){if(Z===void 0&&fe===void 0){var ye=this.getExtInfo("certificatePolicies");if(ye===void 0)return;Z=q(this.hex,ye.vidx),fe=ye.critical}var be={extname:"certificatePolicies",array:[]};fe&&(be.critical=!0);for(var Ue=E(Z,0),Me=0;Me<Ue.length;Me++){var Ye=q(Z,Ue[Me]),Ke=this.getPolicyInformation(Ye);be.array.push(Ke)}return be},this.getPolicyInformation=function(Z){var fe={},ye=K(Z,0,[0],"06");fe.policyoid=Pe(ye);var be=pe(Z,0,[1],"30");if(be!=-1){fe.array=[];for(var Ue=E(Z,be),Me=0;Me<Ue.length;Me++){var Ye=q(Z,Ue[Me]),Ke=this.getPolicyQualifierInfo(Ye);fe.array.push(Ke)}}return fe},this.getPolicyQualifierInfo=function(Z){var fe={},ye=K(Z,0,[0],"06");if(ye==="2b06010505070201"){var be=ce(Z,0,[1],"16");fe.cps=At(be)}else if(ye==="2b06010505070202"){var Ue=ee(Z,0,[1],"30");fe.unotice=this.getUserNotice(Ue)}return fe},this.getUserNotice=function(Z){for(var fe={},ye=E(Z,0),be=0;be<ye.length;be++){var Ue=q(Z,ye[be]);Ue.substr(0,2)!="30"&&(fe.exptext=this.getDisplayText(Ue))}return fe},this.getDisplayText=function(Z){var fe={};return fe.type={"0c":"utf8",16:"ia5","1a":"vis","1e":"bmp"}[Z.substr(0,2)],fe.str=At(I(Z,0)),fe},this.getExtCRLNumber=function(Z,fe){var ye={extname:"cRLNumber"};if(fe&&(ye.critical=!0),Z.substr(0,2)=="02")return ye.num={hex:I(Z,0)},ye;throw new Error("hExtV parse error: "+Z)},this.getExtCRLReason=function(Z,fe){var ye={extname:"cRLReason"};if(fe&&(ye.critical=!0),Z.substr(0,2)=="0a")return ye.code=parseInt(I(Z,0),16),ye;throw new Error("hExtV parse error: "+Z)},this.getExtOcspNonce=function(Z,fe){var ye={extname:"ocspNonce"};fe&&(ye.critical=!0);var be=I(Z,0);return ye.hex=be,ye},this.getExtOcspNoCheck=function(Z,fe){var ye={extname:"ocspNoCheck"};return fe&&(ye.critical=!0),ye},this.getExtAdobeTimeStamp=function(Z,fe){if(Z===void 0&&fe===void 0){var ye=this.getExtInfo("adobeTimeStamp");if(ye===void 0)return;Z=q(this.hex,ye.vidx),fe=ye.critical}var be={extname:"adobeTimeStamp"};fe&&(be.critical=!0);var Ue=E(Z,0);if(Ue.length>1){var Me=q(Z,Ue[1]),Ye=this.getGeneralName(Me);Ye.uri!=null&&(be.uri=Ye.uri)}if(Ue.length>2){var Ke=q(Z,Ue[2]);Ke=="0101ff"&&(be.reqauth=!0),Ke=="010100"&&(be.reqauth=!1)}return be},this.getX500NameRule=function(Z){for(var fe=null,ye=[],be=0;be<Z.length;be++)for(var Ue=Z[be],Me=0;Me<Ue.length;Me++)ye.push(Ue[Me]);for(be=0;be<ye.length;be++){var Ye=ye[be],Ke=Ye.ds,st=Ye.value,Xe=Ye.type;if(Ke!="prn"&&Ke!="utf8"&&Ke!="ia5")return"mixed";if(Ke=="ia5"){if(Xe!="CN")return"mixed";if(F.lang.String.isMail(st))continue;return"mixed"}if(Xe=="C"){if(Ke=="prn")continue;return"mixed"}if(fe==null)fe=Ke;else if(fe!==Ke)return"mixed"}return fe??"prn"},this.getX500Name=function(Z){var fe=this.getX500NameArray(Z);return{array:fe,str:this.dnarraytostr(fe)}},this.getX500NameArray=function(Z){for(var fe=[],ye=E(Z,0),be=0;be<ye.length;be++)fe.push(this.getRDN(q(Z,ye[be])));return fe},this.getRDN=function(Z){for(var fe=[],ye=E(Z,0),be=0;be<ye.length;be++)fe.push(this.getAttrTypeAndValue(q(Z,ye[be])));return fe},this.getAttrTypeAndValue=function(Z){var fe={type:null,value:null,ds:null},ye=E(Z,0),be=K(Z,ye[0],[],"06"),Ue=K(Z,ye[1],[]),Me=F.asn1.ASN1Util.oidHexToInt(be);return fe.type=F.asn1.x509.OID.oid2atype(Me),fe.ds=this.HEX2STAG[Z.substr(ye[1],2)],fe.ds!="bmp"?fe.value=yt(Ue):fe.value=fr(Ue),fe},this.readCertPEM=function(Z){this.readCertHex(Le(Z))},this.readCertHex=function(Z){this.hex=Z,this.getVersion();try{oe(this.hex,0,[0,7],"a3"),this.parseExt()}catch{}},this.getParam=function(){var Z={};return Z.version=this.getVersion(),Z.serial={hex:this.getSerialNumberHex()},Z.sigalg=this.getSignatureAlgorithmField(),Z.issuer=this.getIssuer(),Z.notbefore=this.getNotBefore(),Z.notafter=this.getNotAfter(),Z.subject=this.getSubject(),Z.sbjpubkey=Ie(this.getPublicKeyHex(),"PUBLIC KEY"),this.aExtInfo.length>0&&(Z.ext=this.getExtParamArray()),Z.sighex=this.getSignatureValueHex(),Z},this.getExtParamArray=function(Z){Z==null&&pe(this.hex,0,[0,"[3]"])!=-1&&(Z=se(this.hex,0,[0,"[3]",0],"30"));for(var fe=[],ye=E(Z,0),be=0;be<ye.length;be++){var Ue=q(Z,ye[be]),Me=this.getExtParam(Ue);Me!=null&&fe.push(Me)}return fe},this.getExtParam=function(Z){var fe=E(Z,0).length;if(fe!=2&&fe!=3)throw new Error("wrong number elements in Extension: "+fe+" "+Z);var ye=$e(K(Z,0,[0],"06")),be=!1;fe==3&&ee(Z,0,[1])=="0101ff"&&(be=!0);var Ue=ee(Z,0,[fe-1,0]),Me=void 0;if(ye=="2.5.29.14"?Me=this.getExtSubjectKeyIdentifier(Ue,be):ye=="2.5.29.15"?Me=this.getExtKeyUsage(Ue,be):ye=="2.5.29.17"?Me=this.getExtSubjectAltName(Ue,be):ye=="2.5.29.18"?Me=this.getExtIssuerAltName(Ue,be):ye=="2.5.29.19"?Me=this.getExtBasicConstraints(Ue,be):ye=="2.5.29.31"?Me=this.getExtCRLDistributionPoints(Ue,be):ye=="2.5.29.32"?Me=this.getExtCertificatePolicies(Ue,be):ye=="2.5.29.35"?Me=this.getExtAuthorityKeyIdentifier(Ue,be):ye=="2.5.29.37"?Me=this.getExtExtKeyUsage(Ue,be):ye=="1.3.6.1.5.5.7.1.1"?Me=this.getExtAuthorityInfoAccess(Ue,be):ye=="2.5.29.20"?Me=this.getExtCRLNumber(Ue,be):ye=="2.5.29.21"?Me=this.getExtCRLReason(Ue,be):ye=="1.3.6.1.5.5.7.48.1.2"?Me=this.getExtOcspNonce(Ue,be):ye=="1.3.6.1.5.5.7.48.1.5"?Me=this.getExtOcspNoCheck(Ue,be):ye=="1.2.840.113583.1.1.9.1"&&(Me=this.getExtAdobeTimeStamp(Ue,be)),Me!=null)return Me;var Ye={extname:ye,extn:Ue};return be&&(Ye.critical=!0),Ye},this.findExt=function(Z,fe){for(var ye=0;ye<Z.length;ye++)if(Z[ye].extname==fe)return Z[ye];return null},this.updateExtCDPFullURI=function(Z,fe){var ye=this.findExt(Z,"cRLDistributionPoints");if(ye!=null&&ye.array!=null){for(var be=ye.array,Ue=0;Ue<be.length;Ue++)if(be[Ue].dpname!=null&&be[Ue].dpname.full!=null)for(var Me=be[Ue].dpname.full,Ye=0;Ye<Me.length;Ye++){var Ke=Me[Ue];Ke.uri!=null&&(Ke.uri=fe)}}},this.updateExtAIAOCSP=function(Z,fe){var ye=this.findExt(Z,"authorityInfoAccess");if(ye!=null&&ye.array!=null)for(var be=ye.array,Ue=0;Ue<be.length;Ue++)be[Ue].ocsp!=null&&(be[Ue].ocsp=fe)},this.updateExtAIACAIssuer=function(Z,fe){var ye=this.findExt(Z,"authorityInfoAccess");if(ye!=null&&ye.array!=null)for(var be=ye.array,Ue=0;Ue<be.length;Ue++)be[Ue].caissuer!=null&&(be[Ue].caissuer=fe)},this.dnarraytostr=function(Z){return"/"+Z.map((function(fe){return(function(be){return be.map((function(Ue){return(function(Ye){return Ye.type+"="+Ye.value})(Ue).replace(/\+/,"\\+")})).join("+")})(fe).replace(/\//,"\\/")})).join("/")},this.getInfo=function(){var Z,fe,ye,be=function(Ht){return JSON.stringify(Ht.array).replace(/[\[\]\{\}\"]/g,"")},Ue=function(Ht){for(var jt="",qt=Ht.array,xt=0;xt<qt.length;xt++){var vt=qt[xt];if(jt+=" policy oid: "+vt.policyoid+`
|
|
265
|
+
`,vt.array!==void 0)for(var Lt=0;Lt<vt.array.length;Lt++){var Vt=vt.array[Lt];Vt.cps!==void 0&&(jt+=" cps: "+Vt.cps+`
|
|
266
|
+
`)}}return jt},Me=function(Ht){for(var jt="",qt=Ht.array,xt=0;xt<qt.length;xt++){var vt=qt[xt];try{vt.dpname.full[0].uri!==void 0&&(jt+=" "+vt.dpname.full[0].uri+`
|
|
267
|
+
`)}catch{}try{vt.dname.full[0].dn.hex!==void 0&&(jt+=" "+Ft.hex2dn(vt.dpname.full[0].dn.hex)+`
|
|
268
|
+
`)}catch{}}return jt},Ye=function(Ht){for(var jt="",qt=Ht.array,xt=0;xt<qt.length;xt++){var vt=qt[xt];vt.caissuer!==void 0&&(jt+=" caissuer: "+vt.caissuer+`
|
|
269
|
+
`),vt.ocsp!==void 0&&(jt+=" ocsp: "+vt.ocsp+`
|
|
270
|
+
`)}return jt};if(Z=`Basic Fields
|
|
271
|
+
`,Z+=" serial number: "+this.getSerialNumberHex()+`
|
|
272
|
+
`,Z+=" signature algorithm: "+this.getSignatureAlgorithmField()+`
|
|
273
|
+
`,Z+=" issuer: "+this.getIssuerString()+`
|
|
274
|
+
`,Z+=" notBefore: "+this.getNotBefore()+`
|
|
275
|
+
`,Z+=" notAfter: "+this.getNotAfter()+`
|
|
276
|
+
`,Z+=" subject: "+this.getSubjectString()+`
|
|
277
|
+
`,Z+=` subject public key info:
|
|
278
|
+
`,Z+=" key algorithm: "+(fe=this.getPublicKey()).type+`
|
|
279
|
+
`,fe.type==="RSA"&&(Z+=" n="+Jt(fe.n.toString(16)).substr(0,16)+`...
|
|
280
|
+
`,Z+=" e="+Jt(fe.e.toString(16))+`
|
|
281
|
+
`),(ye=this.aExtInfo)!=null){Z+=`X509v3 Extensions:
|
|
282
|
+
`;for(var Ke=0;Ke<ye.length;Ke++){var st=ye[Ke],Xe=F.asn1.x509.OID.oid2name(st.oid);Xe===""&&(Xe=st.oid);var tt="";if(st.critical===!0&&(tt="CRITICAL"),Z+=" "+Xe+" "+tt+`:
|
|
283
|
+
`,Xe==="basicConstraints"){var bt=this.getExtBasicConstraints();bt.cA===void 0?Z+=` {}
|
|
284
|
+
`:(Z+=" cA=true",bt.pathLen!==void 0&&(Z+=", pathLen="+bt.pathLen),Z+=`
|
|
285
|
+
`)}else if(Xe==="keyUsage")Z+=" "+this.getExtKeyUsageString()+`
|
|
286
|
+
`;else if(Xe==="subjectKeyIdentifier")Z+=" "+this.getExtSubjectKeyIdentifier().kid.hex+`
|
|
287
|
+
`;else if(Xe==="authorityKeyIdentifier"){var St=this.getExtAuthorityKeyIdentifier();St.kid!==void 0&&(Z+=" kid="+St.kid.hex+`
|
|
288
|
+
`)}else Xe==="extKeyUsage"?Z+=" "+this.getExtExtKeyUsage().array.join(", ")+`
|
|
289
|
+
`:Xe==="subjectAltName"?Z+=" "+be(this.getExtSubjectAltName())+`
|
|
290
|
+
`:Xe==="cRLDistributionPoints"?Z+=Me(this.getExtCRLDistributionPoints()):Xe==="authorityInfoAccess"?Z+=Ye(this.getExtAuthorityInfoAccess()):Xe==="certificatePolicies"&&(Z+=Ue(this.getExtCertificatePolicies()))}}return Z+="signature algorithm: "+this.getSignatureAlgorithmName()+`
|
|
291
|
+
`,Z+="signature: "+this.getSignatureValueHex().substr(0,16)+`...
|
|
292
|
+
`},typeof p=="string"&&(p.indexOf("-----BEGIN")!=-1?this.readCertPEM(p):F.lang.String.isHex(p)&&this.readCertHex(p))}Ne.prototype.sign=function(p,h){var y=(function(I){return F.crypto.Util.hashString(I,h)})(p);return this.signWithMessageHash(y,h)},Ne.prototype.signWithMessageHash=function(p,h){var y=Be(F.crypto.Util.getPaddedDigestInfoHex(p,h,this.n.bitLength()),16);return Rt(this.doPrivate(y).toString(16),this.n.bitLength())},Ne.prototype.signPSS=function(p,h,y){var E=(function(q){return F.crypto.Util.hashHex(q,h)})(It(p));return y===void 0&&(y=-1),this.signWithMessageHashPSS(E,h,y)},Ne.prototype.signWithMessageHashPSS=function(p,h,y){var E,I=At(p),q=I.length,K=this.n.bitLength()-1,ce=Math.ceil(K/8),ee=function(Z){return F.crypto.Util.hashHex(Z,h)};if(y===-1||y===void 0)y=q;else if(y===-2)y=ce-q-2;else if(y<-2)throw new Error("invalid salt length");if(ce<q+y+2)throw new Error("data too long");var se="";y>0&&(se=new Array(y),new Y().nextBytes(se),se=String.fromCharCode.apply(String,se));var oe=At(ee(It("\0\0\0\0\0\0\0\0"+I+se))),pe=[];for(E=0;E<ce-y-q-2;E+=1)pe[E]=0;var Se=String.fromCharCode.apply(String,pe)+""+se,Ee=Jr(oe,Se.length,ee),Pe=[];for(E=0;E<Se.length;E+=1)Pe[E]=Se.charCodeAt(E)^Ee.charCodeAt(E);var $e=65280>>8*ce-K&255;for(Pe[0]&=~$e,E=0;E<q;E++)Pe.push(oe.charCodeAt(E));return Pe.push(188),Rt(this.doPrivate(new D(Pe)).toString(16),this.n.bitLength())},Ne.prototype.verify=function(p,h){if((h=h.toLowerCase()).match(/^[0-9a-f]+$/)==null)return!1;var y=Be(h,16),E=this.n.bitLength();if(y.bitLength()>E)return!1;var I=this.doPublic(y).toString(16);if(I.length+3!=E/4)return!1;var q=Ct(I.replace(/^1f+00/,""));if(q.length==0)return!1;var K=q[0];return q[1]==(function(ee){return F.crypto.Util.hashString(ee,K)})(p)},Ne.prototype.verifyWithMessageHash=function(p,h){if(h.length!=Math.ceil(this.n.bitLength()/4))return!1;var y=Be(h,16);if(y.bitLength()>this.n.bitLength())return 0;var E=Ct(this.doPublic(y).toString(16).replace(/^1f+00/,""));return E.length==0?!1:(E[0],E[1]==p)},Ne.prototype.verifyPSS=function(p,h,y,E){var I=(function(K){return F.crypto.Util.hashHex(K,y)})(It(p));return E===void 0&&(E=-1),this.verifyWithMessageHashPSS(I,h,y,E)},Ne.prototype.verifyWithMessageHashPSS=function(p,h,y,E){if(h.length!=Math.ceil(this.n.bitLength()/4))return!1;var I,q=new D(h,16),K=function(ye){return F.crypto.Util.hashHex(ye,y)},ce=At(p),ee=ce.length,se=this.n.bitLength()-1,oe=Math.ceil(se/8);if(E===-1||E===void 0)E=ee;else if(E===-2)E=oe-ee-2;else if(E<-2)throw new Error("invalid salt length");if(oe<ee+E+2)throw new Error("data too long");var pe=this.doPublic(q).toByteArray();for(I=0;I<pe.length;I+=1)pe[I]&=255;for(;pe.length<oe;)pe.unshift(0);if(pe[oe-1]!==188)throw new Error("encoded message does not end in 0xbc");var Se=(pe=String.fromCharCode.apply(String,pe)).substr(0,oe-ee-1),Ee=pe.substr(Se.length,ee),Pe=65280>>8*oe-se&255;if((Se.charCodeAt(0)&Pe)!=0)throw new Error("bits beyond keysize not zero");var $e=Jr(Ee,Se.length,K),Le=[];for(I=0;I<Se.length;I+=1)Le[I]=Se.charCodeAt(I)^$e.charCodeAt(I);Le[0]&=~Pe;var Z=oe-ee-E-2;for(I=0;I<Z;I+=1)if(Le[I]!==0)throw new Error("leftmost octets not zero");if(Le[Z]!==1)throw new Error("0x01 marker not found");return Ee===At(K(It("\0\0\0\0\0\0\0\0"+ce+String.fromCharCode.apply(String,Le.slice(-E)))))},Ne.SALT_LEN_HLEN=-1,Ne.SALT_LEN_MAX=-2,Ne.SALT_LEN_RECOVER=-2,Ft.hex2dn=function(p,h){h===void 0&&(h=0);var y=new Ft;return we.getTLV(p,h),y.getX500Name(p).str},Ft.hex2rdn=function(p,h){if(h===void 0&&(h=0),p.substr(h,2)!=="31")throw new Error("malformed RDN");for(var y=new Array,E=we.getChildIdx(p,h),I=0;I<E.length;I++)y.push(Ft.hex2attrTypeValue(p,E[I]));return(y=y.map((function(q){return q.replace("+","\\+")}))).join("+")},Ft.hex2attrTypeValue=function(p,h){var y=we,E=y.getV;if(h===void 0&&(h=0),p.substr(h,2)!=="30")throw new Error("malformed attribute type and value");var I=y.getChildIdx(p,h);I.length!==2||p.substr(I[0],2);var q=E(p,I[0]),K=F.asn1.ASN1Util.oidHexToInt(q);return F.asn1.x509.OID.oid2atype(K)+"="+At(E(p,I[1]))},Ft.getPublicKeyFromCertHex=function(p){var h=new Ft;return h.readCertHex(p),h.getPublicKey()},Ft.getPublicKeyFromCertPEM=function(p){var h=new Ft;return h.readCertPEM(p),h.getPublicKey()},Ft.getPublicKeyInfoPropOfCertPEM=function(p){var h,y,E=we.getVbyList,I={};return I.algparam=null,(h=new Ft).readCertPEM(p),y=h.getPublicKeyHex(),I.keyhex=E(y,0,[1],"03").substr(2),I.algoid=E(y,0,[0,0],"06"),I.algoid==="2a8648ce3d0201"&&(I.algparam=E(y,0,[0,1],"06")),I},Ft.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],F!==void 0&&F||(r.KJUR=F={}),F.jws!==void 0&&F.jws||(F.jws={}),F.jws.JWS=function(){var p=F.jws.JWS.isSafeJSONString;this.parseJWS=function(h,y){if(this.parsedJWS===void 0||!y&&this.parsedJWS.sigvalH===void 0){var E=h.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(E==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var I=E[1],q=E[2],K=E[3],ce=I+"."+q;if(this.parsedJWS={},this.parsedJWS.headB64U=I,this.parsedJWS.payloadB64U=q,this.parsedJWS.sigvalB64U=K,this.parsedJWS.si=ce,!y){var ee=dt(K),se=Be(ee,16);this.parsedJWS.sigvalH=ee,this.parsedJWS.sigvalBI=se}var oe=Re(I),pe=Re(q);if(this.parsedJWS.headS=oe,this.parsedJWS.payloadS=pe,!p(oe,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+oe}}},F.jws.JWS.sign=function(p,h,y,E,I){var q,K,ce,ee=F,se=ee.jws.JWS,oe=se.readSafeJSONString,pe=se.isSafeJSONString,Se=ee.crypto,Ee=(Se.ECDSA,Se.Mac),Pe=Se.Signature,$e=JSON;if(typeof h!="string"&&(h===void 0?"undefined":w(h))!="object")throw"spHeader must be JSON string or object: "+h;if((h===void 0?"undefined":w(h))=="object"&&(K=h,q=$e.stringify(K)),typeof h=="string"){if(!pe(q=h))throw"JWS Head is not safe JSON string: "+q;K=oe(q)}if(ce=y,(y===void 0?"undefined":w(y))=="object"&&(ce=$e.stringify(y)),p!=""&&p!=null||K.alg===void 0||(p=K.alg),p!=""&&p!=null&&K.alg===void 0&&(K.alg=p,q=$e.stringify(K)),p!==K.alg)throw"alg and sHeader.alg doesn't match: "+p+"!="+K.alg;var Le=null;if(se.jwsalg2sigalg[p]===void 0)throw"unsupported alg name: "+p;Le=se.jwsalg2sigalg[p];var Z=me(q)+"."+me(ce),fe="";if(Le.substr(0,4)=="Hmac"){if(E===void 0)throw"mac key shall be specified for HS* alg";var ye=new Ee({alg:Le,prov:"cryptojs",pass:E});ye.updateString(Z),fe=ye.doFinal()}else if(Le.indexOf("withECDSA")!=-1){(Ue=new Pe({alg:Le})).init(E,I),Ue.updateString(Z);var be=Ue.sign();fe=F.crypto.ECDSA.asn1SigToConcatSig(be)}else{var Ue;Le!="none"&&((Ue=new Pe({alg:Le})).init(E,I),Ue.updateString(Z),fe=Ue.sign())}return Z+"."+wt(fe)},F.jws.JWS.verify=function(p,h,y){var E,I=F,q=I.jws.JWS,K=q.readSafeJSONString,ce=I.crypto,ee=ce.ECDSA,se=ce.Mac,oe=ce.Signature;w(Ne)!==void 0&&(E=Ne);var pe=p.split(".");if(pe.length!==3)return!1;var Se=pe[0]+"."+pe[1],Ee=dt(pe[2]),Pe=K(Re(pe[0])),$e=null,Le=null;if(Pe.alg===void 0)throw"algorithm not specified in header";if(Le=($e=Pe.alg).substr(0,2),y!=null&&Object.prototype.toString.call(y)==="[object Array]"&&y.length>0&&(":"+y.join(":")+":").indexOf(":"+$e+":")==-1)throw"algorithm '"+$e+"' not accepted in the list";if($e!="none"&&h===null)throw"key shall be specified to verify.";if(typeof h=="string"&&h.indexOf("-----BEGIN ")!=-1&&(h=rt.getKey(h)),!(Le!="RS"&&Le!="PS"||h instanceof E))throw"key shall be a RSAKey obj for RS* and PS* algs";if(Le=="ES"&&!(h instanceof ee))throw"key shall be a ECDSA obj for ES* algs";var Z=null;if(q.jwsalg2sigalg[Pe.alg]===void 0)throw"unsupported alg name: "+$e;if((Z=q.jwsalg2sigalg[$e])=="none")throw"not supported";if(Z.substr(0,4)=="Hmac"){if(h===void 0)throw"hexadecimal key shall be specified for HMAC";var fe=new se({alg:Z,pass:h});return fe.updateString(Se),Ee==fe.doFinal()}if(Z.indexOf("withECDSA")!=-1){var ye,be=null;try{be=ee.concatSigToASN1Sig(Ee)}catch{return!1}return(ye=new oe({alg:Z})).init(h),ye.updateString(Se),ye.verify(be)}return(ye=new oe({alg:Z})).init(h),ye.updateString(Se),ye.verify(Ee)},F.jws.JWS.parse=function(p){var h,y,E,I=p.split("."),q={};if(I.length!=2&&I.length!=3)throw"malformed sJWS: wrong number of '.' splitted elements";return h=I[0],y=I[1],I.length==3&&(E=I[2]),q.headerObj=F.jws.JWS.readSafeJSONString(Re(h)),q.payloadObj=F.jws.JWS.readSafeJSONString(Re(y)),q.headerPP=JSON.stringify(q.headerObj,null," "),q.payloadObj==null?q.payloadPP=Re(y):q.payloadPP=JSON.stringify(q.payloadObj,null," "),E!==void 0&&(q.sigHex=dt(E)),q},F.jws.JWS.verifyJWT=function(p,h,y){var E=F.jws,I=E.JWS,q=I.readSafeJSONString,K=I.inArray,ce=I.includedArray,ee=p.split("."),se=ee[0],oe=ee[1],pe=(dt(ee[2]),q(Re(se))),Se=q(Re(oe));if(pe.alg===void 0)return!1;if(y.alg===void 0)throw"acceptField.alg shall be specified";if(!K(pe.alg,y.alg)||Se.iss!==void 0&&w(y.iss)==="object"&&!K(Se.iss,y.iss)||Se.sub!==void 0&&w(y.sub)==="object"&&!K(Se.sub,y.sub))return!1;if(Se.aud!==void 0&&w(y.aud)==="object"){if(typeof Se.aud=="string"){if(!K(Se.aud,y.aud))return!1}else if(w(Se.aud)=="object"&&!ce(Se.aud,y.aud))return!1}var Ee=E.IntDate.getNow();return y.verifyAt!==void 0&&typeof y.verifyAt=="number"&&(Ee=y.verifyAt),y.gracePeriod!==void 0&&typeof y.gracePeriod=="number"||(y.gracePeriod=0),!(Se.exp!==void 0&&typeof Se.exp=="number"&&Se.exp+y.gracePeriod<Ee)&&!(Se.nbf!==void 0&&typeof Se.nbf=="number"&&Ee<Se.nbf-y.gracePeriod)&&!(Se.iat!==void 0&&typeof Se.iat=="number"&&Ee<Se.iat-y.gracePeriod)&&(Se.jti===void 0||y.jti===void 0||Se.jti===y.jti)&&!!I.verify(p,h,y.alg)},F.jws.JWS.includedArray=function(p,h){var y=F.jws.JWS.inArray;if(p===null||(p===void 0?"undefined":w(p))!=="object"||typeof p.length!="number")return!1;for(var E=0;E<p.length;E++)if(!y(p[E],h))return!1;return!0},F.jws.JWS.inArray=function(p,h){if(h===null||(h===void 0?"undefined":w(h))!=="object"||typeof h.length!="number")return!1;for(var y=0;y<h.length;y++)if(h[y]==p)return!0;return!1},F.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"},F.jws.JWS.isSafeJSONString=function(p,h,y){var E=null;try{return((E=N(p))===void 0?"undefined":w(E))!="object"||E.constructor===Array?0:(h&&(h[y]=E),1)}catch{return 0}},F.jws.JWS.readSafeJSONString=function(p){var h=null;try{return((h=N(p))===void 0?"undefined":w(h))!="object"||h.constructor===Array?null:h}catch{return null}},F.jws.JWS.getEncodedSignatureValueFromJWS=function(p){var h=p.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(h==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return h[1]},F.jws.JWS.getJWKthumbprint=function(p){if(p.kty!=="RSA"&&p.kty!=="EC"&&p.kty!=="oct")throw"unsupported algorithm for JWK Thumprint";var h="{";if(p.kty==="RSA"){if(typeof p.n!="string"||typeof p.e!="string")throw"wrong n and e value for RSA key";h+='"e":"'+p.e+'",',h+='"kty":"'+p.kty+'",',h+='"n":"'+p.n+'"}'}else if(p.kty==="EC"){if(typeof p.crv!="string"||typeof p.x!="string"||typeof p.y!="string")throw"wrong crv, x and y value for EC key";h+='"crv":"'+p.crv+'",',h+='"kty":"'+p.kty+'",',h+='"x":"'+p.x+'",',h+='"y":"'+p.y+'"}'}else if(p.kty==="oct"){if(typeof p.k!="string")throw"wrong k value for oct(symmetric) key";h+='"kty":"'+p.kty+'",',h+='"k":"'+p.k+'"}'}var y=It(h);return wt(F.crypto.Util.hashHex(y,"sha256"))},F.jws.IntDate={},F.jws.IntDate.get=function(p){var h=F.jws.IntDate,y=h.getNow,E=h.getZulu;if(p=="now")return y();if(p=="now + 1hour")return y()+3600;if(p=="now + 1day")return y()+86400;if(p=="now + 1month")return y()+2592e3;if(p=="now + 1year")return y()+31536e3;if(p.match(/Z$/))return E(p);if(p.match(/^[0-9]+$/))return parseInt(p);throw"unsupported format: "+p},F.jws.IntDate.getZulu=function(p){return ht(p)},F.jws.IntDate.getNow=function(){return~~(new Date/1e3)},F.jws.IntDate.intDate2UTCString=function(p){return new Date(1e3*p).toUTCString()},F.jws.IntDate.intDate2Zulu=function(p){var h=new Date(1e3*p);return("0000"+h.getUTCFullYear()).slice(-4)+("00"+(h.getUTCMonth()+1)).slice(-2)+("00"+h.getUTCDate()).slice(-2)+("00"+h.getUTCHours()).slice(-2)+("00"+h.getUTCMinutes()).slice(-2)+("00"+h.getUTCSeconds()).slice(-2)+"Z"},r.SecureRandom=Y,r.rng_seed_time=H,r.BigInteger=D,r.RSAKey=Ne;var tn=F.crypto.EDSA;r.EDSA=tn;var Wt=F.crypto.DSA;r.DSA=Wt;var Nr=F.crypto.Signature;r.Signature=Nr;var Or=F.crypto.MessageDigest;r.MessageDigest=Or;var jr=F.crypto.Mac;r.Mac=jr;var Mr=F.crypto.Cipher;r.Cipher=Mr,r.KEYUTIL=rt,r.ASN1HEX=we,r.X509=Ft,r.CryptoJS=T,r.b64tohex=W,r.b64toBA=re,r.stoBA=Qe,r.BAtos=et,r.BAtohex=ot,r.stohex=ct,r.stob64=function(h){return $(ct(h))},r.stob64u=function(h){return at($(ct(h)))},r.b64utos=function(h){return et(re(Qt(h)))},r.b64tob64u=at,r.b64utob64=Qt,r.hex2b64=$,r.hextob64u=wt,r.b64utohex=dt,r.utf8tob64u=me,r.b64utoutf8=Re,r.utf8tob64=function(h){return $(gt(Ot(h)))},r.b64toutf8=function(h){return decodeURIComponent(rr(W(h)))},r.utf8tohex=$t,r.hextoutf8=yt,r.hextorstr=At,r.rstrtohex=It,r.hextob64=Bt,r.hextob64nl=k,r.b64nltohex=j,r.hextopem=Ie,r.pemtohex=Ae,r.hextoArrayBuffer=function(h){if(h.length%2!=0)throw"input is not even length";if(h.match(/^[0-9A-Fa-f]+$/)==null)throw"input is not hexadecimal";for(var y=new ArrayBuffer(h.length/2),E=new DataView(y),I=0;I<h.length/2;I++)E.setUint8(I,parseInt(h.substr(2*I,2),16));return y},r.ArrayBuffertohex=function(h){for(var y="",E=new DataView(h),I=0;I<h.byteLength;I++)y+=("00"+E.getUint8(I).toString(16)).slice(-2);return y},r.zulutomsec=Ve,r.zulutosec=ht,r.zulutodate=function(h){return new Date(Ve(h))},r.datetozulu=function(h,y,E){var I,q=h.getUTCFullYear();if(y){if(q<1950||2049<q)throw"not proper year for UTCTime: "+q;I=(""+q).slice(-2)}else I=("000"+q).slice(-4);if(I+=("0"+(h.getUTCMonth()+1)).slice(-2),I+=("0"+h.getUTCDate()).slice(-2),I+=("0"+h.getUTCHours()).slice(-2),I+=("0"+h.getUTCMinutes()).slice(-2),I+=("0"+h.getUTCSeconds()).slice(-2),E){var K=h.getUTCMilliseconds();K!==0&&(I+="."+(K=(K=("00"+K).slice(-3)).replace(/0+$/g,"")))}return I+="Z"},r.uricmptohex=gt,r.hextouricmp=rr,r.ipv6tohex=Pt,r.hextoipv6=Et,r.hextoip=ar,r.iptohex=function(h){var y="malformed IP address";if(!(h=h.toLowerCase(h)).match(/^[0-9.]+$/)){if(h.match(/^[0-9a-f:]+$/)&&h.indexOf(":")!==-1)return Pt(h);throw y}var E=h.split(".");if(E.length!==4)throw y;var I="";try{for(var q=0;q<4;q++)I+=("0"+parseInt(E[q]).toString(16)).slice(-2);return I}catch{throw y}},r.encodeURIComponentAll=Ot,r.newline_toUnix=function(h){return h=h.replace(/\r\n/gm,`
|
|
293
|
+
`)},r.newline_toDos=function(h){return h=(h=h.replace(/\r\n/gm,`
|
|
294
|
+
`)).replace(/\n/gm,`\r
|
|
295
|
+
`)},r.hextoposhex=Jt,r.intarystrtohex=function(h){h=(h=(h=h.replace(/^\s*\[\s*/,"")).replace(/\s*\]\s*$/,"")).replace(/\s*/g,"");try{return h.split(/,/).map((function(y,E,I){var q=parseInt(y);if(q<0||255<q)throw"integer not in range 0-255";return("00"+q.toString(16)).slice(-2)})).join("")}catch(y){throw"malformed integer array string: "+y}},r.strdiffidx=function(h,y){var E=h.length;h.length>y.length&&(E=y.length);for(var I=0;I<E;I++)if(h.charCodeAt(I)!=y.charCodeAt(I))return I;return h.length!=y.length?E:-1},r.KJUR=F;var Br=F.crypto;r.crypto=Br;var wr=F.asn1;r.asn1=wr;var cr=F.jws;r.jws=cr;var rn=F.lang;r.lang=rn}).call(this,i(28).Buffer)},function(t,r,i){(function(s){var o=i(30),a=i(31),u=i(32);function c(){return d.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function l(G,P){if(c()<P)throw new RangeError("Invalid typed array length");return d.TYPED_ARRAY_SUPPORT?(G=new Uint8Array(P)).__proto__=d.prototype:(G===null&&(G=new d(P)),G.length=P),G}function d(G,P,x){if(!(d.TYPED_ARRAY_SUPPORT||this instanceof d))return new d(G,P,x);if(typeof G=="number"){if(typeof P=="string")throw new Error("If encoding is specified then the first argument must be a string");return g(this,G)}return f(this,G,P,x)}function f(G,P,x,A){if(typeof P=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&P instanceof ArrayBuffer?(function(H,Q,de,M){if(Q.byteLength,de<0||Q.byteLength<de)throw new RangeError("'offset' is out of bounds");if(Q.byteLength<de+(M||0))throw new RangeError("'length' is out of bounds");return Q=de===void 0&&M===void 0?new Uint8Array(Q):M===void 0?new Uint8Array(Q,de):new Uint8Array(Q,de,M),d.TYPED_ARRAY_SUPPORT?(H=Q).__proto__=d.prototype:H=b(H,Q),H})(G,P,x,A):typeof P=="string"?(function(H,Q,de){if(typeof de=="string"&&de!==""||(de="utf8"),!d.isEncoding(de))throw new TypeError('"encoding" must be a valid string encoding');var M=0|w(Q,de),ne=(H=l(H,M)).write(Q,de);return ne!==M&&(H=H.slice(0,ne)),H})(G,P,x):(function(H,Q){if(d.isBuffer(Q)){var de=0|S(Q.length);return(H=l(H,de)).length===0||Q.copy(H,0,0,de),H}if(Q){if(typeof ArrayBuffer<"u"&&Q.buffer instanceof ArrayBuffer||"length"in Q)return typeof Q.length!="number"||(function(ne){return ne!=ne})(Q.length)?l(H,0):b(H,Q);if(Q.type==="Buffer"&&u(Q.data))return b(H,Q.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(G,P)}function m(G){if(typeof G!="number")throw new TypeError('"size" argument must be a number');if(G<0)throw new RangeError('"size" argument must not be negative')}function g(G,P){if(m(P),G=l(G,P<0?0:0|S(P)),!d.TYPED_ARRAY_SUPPORT)for(var x=0;x<P;++x)G[x]=0;return G}function b(G,P){var x=P.length<0?0:0|S(P.length);G=l(G,x);for(var A=0;A<x;A+=1)G[A]=255&P[A];return G}function S(G){if(G>=c())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+c().toString(16)+" bytes");return 0|G}function w(G,P){if(d.isBuffer(G))return G.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(G)||G instanceof ArrayBuffer))return G.byteLength;typeof G!="string"&&(G=""+G);var x=G.length;if(x===0)return 0;for(var A=!1;;)switch(P){case"ascii":case"latin1":case"binary":return x;case"utf8":case"utf-8":case void 0:return te(G).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*x;case"hex":return x>>>1;case"base64":return le(G).length;default:if(A)return te(G).length;P=(""+P).toLowerCase(),A=!0}}function v(G,P,x){var A=!1;if((P===void 0||P<0)&&(P=0),P>this.length||((x===void 0||x>this.length)&&(x=this.length),x<=0)||(x>>>=0)<=(P>>>=0))return"";for(G||(G="utf8");;)switch(G){case"hex":return ze(this,P,x);case"utf8":case"utf-8":return z(this,P,x);case"ascii":return Ce(this,P,x);case"latin1":case"binary":return Fe(this,P,x);case"base64":return he(this,P,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ae(this,P,x);default:if(A)throw new TypeError("Unknown encoding: "+G);G=(G+"").toLowerCase(),A=!0}}function _(G,P,x){var A=G[P];G[P]=G[x],G[x]=A}function T(G,P,x,A,O){if(G.length===0)return-1;if(typeof x=="string"?(A=x,x=0):x>2147483647?x=2147483647:x<-2147483648&&(x=-2147483648),x=+x,isNaN(x)&&(x=O?0:G.length-1),x<0&&(x=G.length+x),x>=G.length){if(O)return-1;x=G.length-1}else if(x<0){if(!O)return-1;x=0}if(typeof P=="string"&&(P=d.from(P,A)),d.isBuffer(P))return P.length===0?-1:C(G,P,x,A,O);if(typeof P=="number")return P&=255,d.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?O?Uint8Array.prototype.indexOf.call(G,P,x):Uint8Array.prototype.lastIndexOf.call(G,P,x):C(G,[P],x,A,O);throw new TypeError("val must be string, number or Buffer")}function C(G,P,x,A,O){var H,Q=1,de=G.length,M=P.length;if(A!==void 0&&((A=String(A).toLowerCase())==="ucs2"||A==="ucs-2"||A==="utf16le"||A==="utf-16le")){if(G.length<2||P.length<2)return-1;Q=2,de/=2,M/=2,x/=2}function ne(Je,Ne){return Q===1?Je[Ne]:Je.readUInt16BE(Ne*Q)}if(O){var ge=-1;for(H=x;H<de;H++)if(ne(G,H)===ne(P,ge===-1?0:H-ge)){if(ge===-1&&(ge=H),H-ge+1===M)return ge*Q}else ge!==-1&&(H-=H-ge),ge=-1}else for(x+M>de&&(x=de-M),H=x;H>=0;H--){for(var Y=!0,Be=0;Be<M;Be++)if(ne(G,H+Be)!==ne(P,Be)){Y=!1;break}if(Y)return H}return-1}function U(G,P,x,A){x=Number(x)||0;var O=G.length-x;A?(A=Number(A))>O&&(A=O):A=O;var H=P.length;if(H%2!=0)throw new TypeError("Invalid hex string");A>H/2&&(A=H/2);for(var Q=0;Q<A;++Q){var de=parseInt(P.substr(2*Q,2),16);if(isNaN(de))return Q;G[x+Q]=de}return Q}function $(G,P,x,A){return Te(te(P,G.length-x),G,x,A)}function W(G,P,x,A){return Te((function(H){for(var Q=[],de=0;de<H.length;++de)Q.push(255&H.charCodeAt(de));return Q})(P),G,x,A)}function re(G,P,x,A){return W(G,P,x,A)}function D(G,P,x,A){return Te(le(P),G,x,A)}function V(G,P,x,A){return Te((function(H,Q){for(var de,M,ne,ge=[],Y=0;Y<H.length&&!((Q-=2)<0);++Y)M=(de=H.charCodeAt(Y))>>8,ne=de%256,ge.push(ne),ge.push(M);return ge})(P,G.length-x),G,x,A)}function he(G,P,x){return P===0&&x===G.length?o.fromByteArray(G):o.fromByteArray(G.slice(P,x))}function z(G,P,x){x=Math.min(G.length,x);for(var A=[],O=P;O<x;){var H,Q,de,M,ne=G[O],ge=null,Y=ne>239?4:ne>223?3:ne>191?2:1;if(O+Y<=x)switch(Y){case 1:ne<128&&(ge=ne);break;case 2:(192&(H=G[O+1]))==128&&(M=(31&ne)<<6|63&H)>127&&(ge=M);break;case 3:H=G[O+1],Q=G[O+2],(192&H)==128&&(192&Q)==128&&(M=(15&ne)<<12|(63&H)<<6|63&Q)>2047&&(M<55296||M>57343)&&(ge=M);break;case 4:H=G[O+1],Q=G[O+2],de=G[O+3],(192&H)==128&&(192&Q)==128&&(192&de)==128&&(M=(15&ne)<<18|(63&H)<<12|(63&Q)<<6|63&de)>65535&&M<1114112&&(ge=M)}ge===null?(ge=65533,Y=1):ge>65535&&(ge-=65536,A.push(ge>>>10&1023|55296),ge=56320|1023&ge),A.push(ge),O+=Y}return(function(Je){var Ne=Je.length;if(Ne<=_e)return String.fromCharCode.apply(String,Je);for(var Ze="",B=0;B<Ne;)Ze+=String.fromCharCode.apply(String,Je.slice(B,B+=_e));return Ze})(A)}r.Buffer=d,r.SlowBuffer=function(P){return+P!=P&&(P=0),d.alloc(+P)},r.INSPECT_MAX_BYTES=50,d.TYPED_ARRAY_SUPPORT=s.TYPED_ARRAY_SUPPORT!==void 0?s.TYPED_ARRAY_SUPPORT:(function(){try{var P=new Uint8Array(1);return P.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},P.foo()===42&&typeof P.subarray=="function"&&P.subarray(1,1).byteLength===0}catch{return!1}})(),r.kMaxLength=c(),d.poolSize=8192,d._augment=function(G){return G.__proto__=d.prototype,G},d.from=function(G,P,x){return f(null,G,P,x)},d.TYPED_ARRAY_SUPPORT&&(d.prototype.__proto__=Uint8Array.prototype,d.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&d[Symbol.species]===d&&Object.defineProperty(d,Symbol.species,{value:null,configurable:!0})),d.alloc=function(G,P,x){return(function(O,H,Q,de){return m(H),H<=0?l(O,H):Q!==void 0?typeof de=="string"?l(O,H).fill(Q,de):l(O,H).fill(Q):l(O,H)})(null,G,P,x)},d.allocUnsafe=function(G){return g(null,G)},d.allocUnsafeSlow=function(G){return g(null,G)},d.isBuffer=function(P){return!(P==null||!P._isBuffer)},d.compare=function(P,x){if(!d.isBuffer(P)||!d.isBuffer(x))throw new TypeError("Arguments must be Buffers");if(P===x)return 0;for(var A=P.length,O=x.length,H=0,Q=Math.min(A,O);H<Q;++H)if(P[H]!==x[H]){A=P[H],O=x[H];break}return A<O?-1:O<A?1:0},d.isEncoding=function(P){switch(String(P).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}},d.concat=function(P,x){if(!u(P))throw new TypeError('"list" argument must be an Array of Buffers');if(P.length===0)return d.alloc(0);var A;if(x===void 0)for(x=0,A=0;A<P.length;++A)x+=P[A].length;var O=d.allocUnsafe(x),H=0;for(A=0;A<P.length;++A){var Q=P[A];if(!d.isBuffer(Q))throw new TypeError('"list" argument must be an Array of Buffers');Q.copy(O,H),H+=Q.length}return O},d.byteLength=w,d.prototype._isBuffer=!0,d.prototype.swap16=function(){var P=this.length;if(P%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var x=0;x<P;x+=2)_(this,x,x+1);return this},d.prototype.swap32=function(){var P=this.length;if(P%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var x=0;x<P;x+=4)_(this,x,x+3),_(this,x+1,x+2);return this},d.prototype.swap64=function(){var P=this.length;if(P%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var x=0;x<P;x+=8)_(this,x,x+7),_(this,x+1,x+6),_(this,x+2,x+5),_(this,x+3,x+4);return this},d.prototype.toString=function(){var P=0|this.length;return P===0?"":arguments.length===0?z(this,0,P):v.apply(this,arguments)},d.prototype.equals=function(P){if(!d.isBuffer(P))throw new TypeError("Argument must be a Buffer");return this===P||d.compare(this,P)===0},d.prototype.inspect=function(){var P="",x=r.INSPECT_MAX_BYTES;return this.length>0&&(P=this.toString("hex",0,x).match(/.{2}/g).join(" "),this.length>x&&(P+=" ... ")),"<Buffer "+P+">"},d.prototype.compare=function(P,x,A,O,H){if(!d.isBuffer(P))throw new TypeError("Argument must be a Buffer");if(x===void 0&&(x=0),A===void 0&&(A=P?P.length:0),O===void 0&&(O=0),H===void 0&&(H=this.length),x<0||A>P.length||O<0||H>this.length)throw new RangeError("out of range index");if(O>=H&&x>=A)return 0;if(O>=H)return-1;if(x>=A)return 1;if(this===P)return 0;for(var Q=(H>>>=0)-(O>>>=0),de=(A>>>=0)-(x>>>=0),M=Math.min(Q,de),ne=this.slice(O,H),ge=P.slice(x,A),Y=0;Y<M;++Y)if(ne[Y]!==ge[Y]){Q=ne[Y],de=ge[Y];break}return Q<de?-1:de<Q?1:0},d.prototype.includes=function(P,x,A){return this.indexOf(P,x,A)!==-1},d.prototype.indexOf=function(P,x,A){return T(this,P,x,A,!0)},d.prototype.lastIndexOf=function(P,x,A){return T(this,P,x,A,!1)},d.prototype.write=function(P,x,A,O){if(x===void 0)O="utf8",A=this.length,x=0;else if(A===void 0&&typeof x=="string")O=x,A=this.length,x=0;else{if(!isFinite(x))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");x|=0,isFinite(A)?(A|=0,O===void 0&&(O="utf8")):(O=A,A=void 0)}var H=this.length-x;if((A===void 0||A>H)&&(A=H),P.length>0&&(A<0||x<0)||x>this.length)throw new RangeError("Attempt to write outside buffer bounds");O||(O="utf8");for(var Q=!1;;)switch(O){case"hex":return U(this,P,x,A);case"utf8":case"utf-8":return $(this,P,x,A);case"ascii":return W(this,P,x,A);case"latin1":case"binary":return re(this,P,x,A);case"base64":return D(this,P,x,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,P,x,A);default:if(Q)throw new TypeError("Unknown encoding: "+O);O=(""+O).toLowerCase(),Q=!0}},d.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var _e=4096;function Ce(G,P,x){var A="";x=Math.min(G.length,x);for(var O=P;O<x;++O)A+=String.fromCharCode(127&G[O]);return A}function Fe(G,P,x){var A="";x=Math.min(G.length,x);for(var O=P;O<x;++O)A+=String.fromCharCode(G[O]);return A}function ze(G,P,x){var A=G.length;(!P||P<0)&&(P=0),(!x||x<0||x>A)&&(x=A);for(var O="",H=P;H<x;++H)O+=Oe(G[H]);return O}function ae(G,P,x){for(var A=G.slice(P,x),O="",H=0;H<A.length;H+=2)O+=String.fromCharCode(A[H]+256*A[H+1]);return O}function ve(G,P,x){if(G%1!=0||G<0)throw new RangeError("offset is not uint");if(G+P>x)throw new RangeError("Trying to access beyond buffer length")}function L(G,P,x,A,O,H){if(!d.isBuffer(G))throw new TypeError('"buffer" argument must be a Buffer instance');if(P>O||P<H)throw new RangeError('"value" argument is out of bounds');if(x+A>G.length)throw new RangeError("Index out of range")}function ie(G,P,x,A){P<0&&(P=65535+P+1);for(var O=0,H=Math.min(G.length-x,2);O<H;++O)G[x+O]=(P&255<<8*(A?O:1-O))>>>8*(A?O:1-O)}function xe(G,P,x,A){P<0&&(P=4294967295+P+1);for(var O=0,H=Math.min(G.length-x,4);O<H;++O)G[x+O]=P>>>8*(A?O:3-O)&255}function ue(G,P,x,A,O,H){if(x+A>G.length)throw new RangeError("Index out of range");if(x<0)throw new RangeError("Index out of range")}function De(G,P,x,A,O){return O||ue(G,0,x,4),a.write(G,P,x,A,23,4),x+4}function ke(G,P,x,A,O){return O||ue(G,0,x,8),a.write(G,P,x,A,52,8),x+8}d.prototype.slice=function(P,x){var A,O=this.length;if((P=~~P)<0?(P+=O)<0&&(P=0):P>O&&(P=O),(x=x===void 0?O:~~x)<0?(x+=O)<0&&(x=0):x>O&&(x=O),x<P&&(x=P),d.TYPED_ARRAY_SUPPORT)(A=this.subarray(P,x)).__proto__=d.prototype;else{var H=x-P;A=new d(H,void 0);for(var Q=0;Q<H;++Q)A[Q]=this[Q+P]}return A},d.prototype.readUIntLE=function(P,x,A){P|=0,x|=0,A||ve(P,x,this.length);for(var O=this[P],H=1,Q=0;++Q<x&&(H*=256);)O+=this[P+Q]*H;return O},d.prototype.readUIntBE=function(P,x,A){P|=0,x|=0,A||ve(P,x,this.length);for(var O=this[P+--x],H=1;x>0&&(H*=256);)O+=this[P+--x]*H;return O},d.prototype.readUInt8=function(P,x){return x||ve(P,1,this.length),this[P]},d.prototype.readUInt16LE=function(P,x){return x||ve(P,2,this.length),this[P]|this[P+1]<<8},d.prototype.readUInt16BE=function(P,x){return x||ve(P,2,this.length),this[P]<<8|this[P+1]},d.prototype.readUInt32LE=function(P,x){return x||ve(P,4,this.length),(this[P]|this[P+1]<<8|this[P+2]<<16)+16777216*this[P+3]},d.prototype.readUInt32BE=function(P,x){return x||ve(P,4,this.length),16777216*this[P]+(this[P+1]<<16|this[P+2]<<8|this[P+3])},d.prototype.readIntLE=function(P,x,A){P|=0,x|=0,A||ve(P,x,this.length);for(var O=this[P],H=1,Q=0;++Q<x&&(H*=256);)O+=this[P+Q]*H;return O>=(H*=128)&&(O-=Math.pow(2,8*x)),O},d.prototype.readIntBE=function(P,x,A){P|=0,x|=0,A||ve(P,x,this.length);for(var O=x,H=1,Q=this[P+--O];O>0&&(H*=256);)Q+=this[P+--O]*H;return Q>=(H*=128)&&(Q-=Math.pow(2,8*x)),Q},d.prototype.readInt8=function(P,x){return x||ve(P,1,this.length),128&this[P]?-1*(255-this[P]+1):this[P]},d.prototype.readInt16LE=function(P,x){x||ve(P,2,this.length);var A=this[P]|this[P+1]<<8;return 32768&A?4294901760|A:A},d.prototype.readInt16BE=function(P,x){x||ve(P,2,this.length);var A=this[P+1]|this[P]<<8;return 32768&A?4294901760|A:A},d.prototype.readInt32LE=function(P,x){return x||ve(P,4,this.length),this[P]|this[P+1]<<8|this[P+2]<<16|this[P+3]<<24},d.prototype.readInt32BE=function(P,x){return x||ve(P,4,this.length),this[P]<<24|this[P+1]<<16|this[P+2]<<8|this[P+3]},d.prototype.readFloatLE=function(P,x){return x||ve(P,4,this.length),a.read(this,P,!0,23,4)},d.prototype.readFloatBE=function(P,x){return x||ve(P,4,this.length),a.read(this,P,!1,23,4)},d.prototype.readDoubleLE=function(P,x){return x||ve(P,8,this.length),a.read(this,P,!0,52,8)},d.prototype.readDoubleBE=function(P,x){return x||ve(P,8,this.length),a.read(this,P,!1,52,8)},d.prototype.writeUIntLE=function(P,x,A,O){P=+P,x|=0,A|=0,O||L(this,P,x,A,Math.pow(2,8*A)-1,0);var H=1,Q=0;for(this[x]=255&P;++Q<A&&(H*=256);)this[x+Q]=P/H&255;return x+A},d.prototype.writeUIntBE=function(P,x,A,O){P=+P,x|=0,A|=0,O||L(this,P,x,A,Math.pow(2,8*A)-1,0);var H=A-1,Q=1;for(this[x+H]=255&P;--H>=0&&(Q*=256);)this[x+H]=P/Q&255;return x+A},d.prototype.writeUInt8=function(P,x,A){return P=+P,x|=0,A||L(this,P,x,1,255,0),d.TYPED_ARRAY_SUPPORT||(P=Math.floor(P)),this[x]=255&P,x+1},d.prototype.writeUInt16LE=function(P,x,A){return P=+P,x|=0,A||L(this,P,x,2,65535,0),d.TYPED_ARRAY_SUPPORT?(this[x]=255&P,this[x+1]=P>>>8):ie(this,P,x,!0),x+2},d.prototype.writeUInt16BE=function(P,x,A){return P=+P,x|=0,A||L(this,P,x,2,65535,0),d.TYPED_ARRAY_SUPPORT?(this[x]=P>>>8,this[x+1]=255&P):ie(this,P,x,!1),x+2},d.prototype.writeUInt32LE=function(P,x,A){return P=+P,x|=0,A||L(this,P,x,4,4294967295,0),d.TYPED_ARRAY_SUPPORT?(this[x+3]=P>>>24,this[x+2]=P>>>16,this[x+1]=P>>>8,this[x]=255&P):xe(this,P,x,!0),x+4},d.prototype.writeUInt32BE=function(P,x,A){return P=+P,x|=0,A||L(this,P,x,4,4294967295,0),d.TYPED_ARRAY_SUPPORT?(this[x]=P>>>24,this[x+1]=P>>>16,this[x+2]=P>>>8,this[x+3]=255&P):xe(this,P,x,!1),x+4},d.prototype.writeIntLE=function(P,x,A,O){if(P=+P,x|=0,!O){var H=Math.pow(2,8*A-1);L(this,P,x,A,H-1,-H)}var Q=0,de=1,M=0;for(this[x]=255&P;++Q<A&&(de*=256);)P<0&&M===0&&this[x+Q-1]!==0&&(M=1),this[x+Q]=(P/de>>0)-M&255;return x+A},d.prototype.writeIntBE=function(P,x,A,O){if(P=+P,x|=0,!O){var H=Math.pow(2,8*A-1);L(this,P,x,A,H-1,-H)}var Q=A-1,de=1,M=0;for(this[x+Q]=255&P;--Q>=0&&(de*=256);)P<0&&M===0&&this[x+Q+1]!==0&&(M=1),this[x+Q]=(P/de>>0)-M&255;return x+A},d.prototype.writeInt8=function(P,x,A){return P=+P,x|=0,A||L(this,P,x,1,127,-128),d.TYPED_ARRAY_SUPPORT||(P=Math.floor(P)),P<0&&(P=255+P+1),this[x]=255&P,x+1},d.prototype.writeInt16LE=function(P,x,A){return P=+P,x|=0,A||L(this,P,x,2,32767,-32768),d.TYPED_ARRAY_SUPPORT?(this[x]=255&P,this[x+1]=P>>>8):ie(this,P,x,!0),x+2},d.prototype.writeInt16BE=function(P,x,A){return P=+P,x|=0,A||L(this,P,x,2,32767,-32768),d.TYPED_ARRAY_SUPPORT?(this[x]=P>>>8,this[x+1]=255&P):ie(this,P,x,!1),x+2},d.prototype.writeInt32LE=function(P,x,A){return P=+P,x|=0,A||L(this,P,x,4,2147483647,-2147483648),d.TYPED_ARRAY_SUPPORT?(this[x]=255&P,this[x+1]=P>>>8,this[x+2]=P>>>16,this[x+3]=P>>>24):xe(this,P,x,!0),x+4},d.prototype.writeInt32BE=function(P,x,A){return P=+P,x|=0,A||L(this,P,x,4,2147483647,-2147483648),P<0&&(P=4294967295+P+1),d.TYPED_ARRAY_SUPPORT?(this[x]=P>>>24,this[x+1]=P>>>16,this[x+2]=P>>>8,this[x+3]=255&P):xe(this,P,x,!1),x+4},d.prototype.writeFloatLE=function(P,x,A){return De(this,P,x,!0,A)},d.prototype.writeFloatBE=function(P,x,A){return De(this,P,x,!1,A)},d.prototype.writeDoubleLE=function(P,x,A){return ke(this,P,x,!0,A)},d.prototype.writeDoubleBE=function(P,x,A){return ke(this,P,x,!1,A)},d.prototype.copy=function(P,x,A,O){if(A||(A=0),O||O===0||(O=this.length),x>=P.length&&(x=P.length),x||(x=0),O>0&&O<A&&(O=A),O===A||P.length===0||this.length===0)return 0;if(x<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("sourceStart out of bounds");if(O<0)throw new RangeError("sourceEnd out of bounds");O>this.length&&(O=this.length),P.length-x<O-A&&(O=P.length-x+A);var H,Q=O-A;if(this===P&&A<x&&x<O)for(H=Q-1;H>=0;--H)P[H+x]=this[H+A];else if(Q<1e3||!d.TYPED_ARRAY_SUPPORT)for(H=0;H<Q;++H)P[H+x]=this[H+A];else Uint8Array.prototype.set.call(P,this.subarray(A,A+Q),x);return Q},d.prototype.fill=function(P,x,A,O){if(typeof P=="string"){if(typeof x=="string"?(O=x,x=0,A=this.length):typeof A=="string"&&(O=A,A=this.length),P.length===1){var H=P.charCodeAt(0);H<256&&(P=H)}if(O!==void 0&&typeof O!="string")throw new TypeError("encoding must be a string");if(typeof O=="string"&&!d.isEncoding(O))throw new TypeError("Unknown encoding: "+O)}else typeof P=="number"&&(P&=255);if(x<0||this.length<x||this.length<A)throw new RangeError("Out of range index");if(A<=x)return this;var Q;if(x>>>=0,A=A===void 0?this.length:A>>>0,P||(P=0),typeof P=="number")for(Q=x;Q<A;++Q)this[Q]=P;else{var de=d.isBuffer(P)?P:te(new d(P,O).toString()),M=de.length;for(Q=0;Q<A-x;++Q)this[Q+x]=de[Q%M]}return this};var We=/[^+\/0-9A-Za-z-_]/g;function Oe(G){return G<16?"0"+G.toString(16):G.toString(16)}function te(G,P){var x;P=P||1/0;for(var A=G.length,O=null,H=[],Q=0;Q<A;++Q){if((x=G.charCodeAt(Q))>55295&&x<57344){if(!O){if(x>56319){(P-=3)>-1&&H.push(239,191,189);continue}if(Q+1===A){(P-=3)>-1&&H.push(239,191,189);continue}O=x;continue}if(x<56320){(P-=3)>-1&&H.push(239,191,189),O=x;continue}x=65536+(O-55296<<10|x-56320)}else O&&(P-=3)>-1&&H.push(239,191,189);if(O=null,x<128){if((P-=1)<0)break;H.push(x)}else if(x<2048){if((P-=2)<0)break;H.push(x>>6|192,63&x|128)}else if(x<65536){if((P-=3)<0)break;H.push(x>>12|224,x>>6&63|128,63&x|128)}else{if(!(x<1114112))throw new Error("Invalid code point");if((P-=4)<0)break;H.push(x>>18|240,x>>12&63|128,x>>6&63|128,63&x|128)}}return H}function le(G){return o.toByteArray((function(x){if((x=(function(O){return O.trim?O.trim():O.replace(/^\s+|\s+$/g,"")})(x).replace(We,"")).length<2)return"";for(;x.length%4!=0;)x+="=";return x})(G))}function Te(G,P,x,A){for(var O=0;O<A&&!(O+x>=P.length||O>=G.length);++O)P[O+x]=G[O];return O}}).call(this,i(29))},function(t,r){var i;i=(function(){return this})();try{i=i||new Function("return this")()}catch{typeof window=="object"&&(i=window)}t.exports=i},function(t,r,i){r.byteLength=function(g){var b=d(g),S=b[0],w=b[1];return 3*(S+w)/4-w},r.toByteArray=function(g){var b,S,w=d(g),v=w[0],_=w[1],T=new a((function(W,re,D){return 3*(re+D)/4-D})(0,v,_)),C=0,U=_>0?v-4:v;for(S=0;S<U;S+=4)b=o[g.charCodeAt(S)]<<18|o[g.charCodeAt(S+1)]<<12|o[g.charCodeAt(S+2)]<<6|o[g.charCodeAt(S+3)],T[C++]=b>>16&255,T[C++]=b>>8&255,T[C++]=255&b;return _===2&&(b=o[g.charCodeAt(S)]<<2|o[g.charCodeAt(S+1)]>>4,T[C++]=255&b),_===1&&(b=o[g.charCodeAt(S)]<<10|o[g.charCodeAt(S+1)]<<4|o[g.charCodeAt(S+2)]>>2,T[C++]=b>>8&255,T[C++]=255&b),T},r.fromByteArray=function(g){for(var b,S=g.length,w=S%3,v=[],_=16383,T=0,C=S-w;T<C;T+=_)v.push(f(g,T,T+_>C?C:T+_));return w===1?(b=g[S-1],v.push(s[b>>2]+s[b<<4&63]+"==")):w===2&&(b=(g[S-2]<<8)+g[S-1],v.push(s[b>>10]+s[b>>4&63]+s[b<<2&63]+"=")),v.join("")};for(var s=[],o=[],a=typeof Uint8Array<"u"?Uint8Array:Array,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,l=u.length;c<l;++c)s[c]=u[c],o[u.charCodeAt(c)]=c;function d(m){var g=m.length;if(g%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=m.indexOf("=");return b===-1&&(b=g),[b,b===g?0:4-b%4]}function f(m,g,b){for(var S,w,v=[],_=g;_<b;_+=3)S=(m[_]<<16&16711680)+(m[_+1]<<8&65280)+(255&m[_+2]),v.push(s[(w=S)>>18&63]+s[w>>12&63]+s[w>>6&63]+s[63&w]);return v.join("")}o[45]=62,o[95]=63},function(t,r){r.read=function(i,s,o,a,u){var c,l,d=8*u-a-1,f=(1<<d)-1,m=f>>1,g=-7,b=o?u-1:0,S=o?-1:1,w=i[s+b];for(b+=S,c=w&(1<<-g)-1,w>>=-g,g+=d;g>0;c=256*c+i[s+b],b+=S,g-=8);for(l=c&(1<<-g)-1,c>>=-g,g+=a;g>0;l=256*l+i[s+b],b+=S,g-=8);if(c===0)c=1-m;else{if(c===f)return l?NaN:1/0*(w?-1:1);l+=Math.pow(2,a),c-=m}return(w?-1:1)*l*Math.pow(2,c-a)},r.write=function(i,s,o,a,u,c){var l,d,f,m=8*c-u-1,g=(1<<m)-1,b=g>>1,S=u===23?Math.pow(2,-24)-Math.pow(2,-77):0,w=a?0:c-1,v=a?1:-1,_=s<0||s===0&&1/s<0?1:0;for(s=Math.abs(s),isNaN(s)||s===1/0?(d=isNaN(s)?1:0,l=g):(l=Math.floor(Math.log(s)/Math.LN2),s*(f=Math.pow(2,-l))<1&&(l--,f*=2),(s+=l+b>=1?S/f:S*Math.pow(2,1-b))*f>=2&&(l++,f/=2),l+b>=g?(d=0,l=g):l+b>=1?(d=(s*f-1)*Math.pow(2,u),l+=b):(d=s*Math.pow(2,b-1)*Math.pow(2,u),l=0));u>=8;i[o+w]=255&d,w+=v,d/=256,u-=8);for(l=l<<u|d,m+=u;m>0;i[o+w]=255&l,w+=v,l/=256,m-=8);i[o+w-v]|=128*_}},function(t,r){var i={}.toString;t.exports=Array.isArray||function(s){return i.call(s)=="[object Array]"}},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(a){var u=a.jws,c=a.KeyUtil,l=a.X509,d=a.crypto,f=a.hextob64u,m=a.b64tohex,g=a.AllowedSigningAlgs;return(function(){function b(){(function(w,v){if(!(w instanceof v))throw new TypeError("Cannot call a class as a function")})(this,b)}return b.parseJwt=function(w){s.Log.debug("JoseUtil.parseJwt");try{var v=u.JWS.parse(w);return{header:v.headerObj,payload:v.payloadObj}}catch(_){s.Log.error(_)}},b.validateJwt=function(w,v,_,T,C,U,$){s.Log.debug("JoseUtil.validateJwt");try{if(v.kty==="RSA")if(v.e&&v.n)v=c.getKey(v);else{if(!v.x5c||!v.x5c.length)return s.Log.error("JoseUtil.validateJwt: RSA key missing key material",v),Promise.reject(new Error("RSA key missing key material"));var W=m(v.x5c[0]);v=l.getPublicKeyFromCertHex(W)}else{if(v.kty!=="EC")return s.Log.error("JoseUtil.validateJwt: Unsupported key type",v&&v.kty),Promise.reject(new Error(v.kty));if(!(v.crv&&v.x&&v.y))return s.Log.error("JoseUtil.validateJwt: EC key missing key material",v),Promise.reject(new Error("EC key missing key material"));v=c.getKey(v)}return b._validateJwt(w,v,_,T,C,U,$)}catch(re){return s.Log.error(re&&re.message||re),Promise.reject("JWT validation failed")}},b.validateJwtAttributes=function(w,v,_,T,C,U){T||(T=0),C||(C=parseInt(Date.now()/1e3));var $=b.parseJwt(w).payload;if(!$.iss)return s.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if($.iss!==v)return s.Log.error("JoseUtil._validateJwt: Invalid issuer in token",$.iss),Promise.reject(new Error("Invalid issuer in token: "+$.iss));if(!$.aud)return s.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!($.aud===_||Array.isArray($.aud)&&$.aud.indexOf(_)>=0))return s.Log.error("JoseUtil._validateJwt: Invalid audience in token",$.aud),Promise.reject(new Error("Invalid audience in token: "+$.aud));if($.azp&&$.azp!==_)return s.Log.error("JoseUtil._validateJwt: Invalid azp in token",$.azp),Promise.reject(new Error("Invalid azp in token: "+$.azp));if(!U){var W=C+T,re=C-T;if(!$.iat)return s.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(W<$.iat)return s.Log.error("JoseUtil._validateJwt: iat is in the future",$.iat),Promise.reject(new Error("iat is in the future: "+$.iat));if($.nbf&&W<$.nbf)return s.Log.error("JoseUtil._validateJwt: nbf is in the future",$.nbf),Promise.reject(new Error("nbf is in the future: "+$.nbf));if(!$.exp)return s.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if($.exp<re)return s.Log.error("JoseUtil._validateJwt: exp is in the past",$.exp),Promise.reject(new Error("exp is in the past:"+$.exp))}return Promise.resolve($)},b._validateJwt=function(w,v,_,T,C,U,$){return b.validateJwtAttributes(w,_,T,C,U,$).then((function(W){try{return u.JWS.verify(w,v,g)?W:(s.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(re){return s.Log.error(re&&re.message||re),Promise.reject(new Error("signature validation failed"))}}))},b.hashString=function(w,v){try{return d.Util.hashString(w,v)}catch(_){s.Log.error(_)}},b.hexToBase64Url=function(w){try{return f(w)}catch(v){s.Log.error(v)}},b})()};var s=i(0);t.exports=r.default},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.SigninResponse=void 0;var s=(function(){function u(c,l){for(var d=0;d<l.length;d++){var f=l[d];f.enumerable=f.enumerable||!1,f.configurable=!0,"value"in f&&(f.writable=!0),Object.defineProperty(c,f.key,f)}}return function(c,l,d){return l&&u(c.prototype,l),d&&u(c,d),c}})(),o=i(3);function a(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")}r.SigninResponse=(function(){function u(c){var l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#";a(this,u);var d=o.UrlUtility.parseUrlFragment(c,l);this.error=d.error,this.error_description=d.error_description,this.error_uri=d.error_uri,this.code=d.code,this.state=d.state,this.id_token=d.id_token,this.session_state=d.session_state,this.access_token=d.access_token,this.token_type=d.token_type,this.scope=d.scope,this.profile=void 0,this.expires_in=d.expires_in}return s(u,[{key:"expires_in",get:function(){if(this.expires_at){var l=parseInt(Date.now()/1e3);return this.expires_at-l}},set:function(l){var d=parseInt(l);if(typeof d=="number"&&d>0){var f=parseInt(Date.now()/1e3);this.expires_at=f+d}}},{key:"expired",get:function(){var l=this.expires_in;if(l!==void 0)return l<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),u})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.SignoutRequest=void 0;var s=i(0),o=i(3),a=i(9);r.SignoutRequest=function u(c){var l=c.url,d=c.id_token_hint,f=c.post_logout_redirect_uri,m=c.data,g=c.extraQueryParams,b=c.request_type;if((function(v,_){if(!(v instanceof _))throw new TypeError("Cannot call a class as a function")})(this,u),!l)throw s.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var S in d&&(l=o.UrlUtility.addQueryParam(l,"id_token_hint",d)),f&&(l=o.UrlUtility.addQueryParam(l,"post_logout_redirect_uri",f),m&&(this.state=new a.State({data:m,request_type:b}),l=o.UrlUtility.addQueryParam(l,"state",this.state.id))),g)l=o.UrlUtility.addQueryParam(l,S,g[S]);this.url=l}},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.SignoutResponse=void 0;var s=i(3);r.SignoutResponse=function o(a){(function(l,d){if(!(l instanceof d))throw new TypeError("Cannot call a class as a function")})(this,o);var u=s.UrlUtility.parseUrlFragment(a,"?");this.error=u.error,this.error_description=u.error_description,this.error_uri=u.error_uri,this.state=u.state}},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.InMemoryWebStorage=void 0;var s=(function(){function a(u,c){for(var l=0;l<c.length;l++){var d=c[l];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(u,d.key,d)}}return function(u,c,l){return c&&a(u.prototype,c),l&&a(u,l),u}})(),o=i(0);r.InMemoryWebStorage=(function(){function a(){(function(c,l){if(!(c instanceof l))throw new TypeError("Cannot call a class as a function")})(this,a),this._data={}}return a.prototype.getItem=function(c){return o.Log.debug("InMemoryWebStorage.getItem",c),this._data[c]},a.prototype.setItem=function(c,l){o.Log.debug("InMemoryWebStorage.setItem",c),this._data[c]=l},a.prototype.removeItem=function(c){o.Log.debug("InMemoryWebStorage.removeItem",c),delete this._data[c]},a.prototype.key=function(c){return Object.getOwnPropertyNames(this._data)[c]},s(a,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),a})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.UserManager=void 0;var s=(function(){function _(T,C){for(var U=0;U<C.length;U++){var $=C[U];$.enumerable=$.enumerable||!1,$.configurable=!0,"value"in $&&($.writable=!0),Object.defineProperty(T,$.key,$)}}return function(T,C,U){return C&&_(T.prototype,C),U&&_(T,U),T}})(),o=i(0),a=i(10),u=i(39),c=i(15),l=i(45),d=i(47),f=i(18),m=i(8),g=i(20),b=i(11),S=i(4);function w(_,T){if(!(_ instanceof T))throw new TypeError("Cannot call a class as a function")}function v(_,T){if(!_)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!T||typeof T!="object"&&typeof T!="function"?_:T}r.UserManager=(function(_){function T(){var C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:d.SilentRenewService,$=arguments.length>2&&arguments[2]!==void 0?arguments[2]:f.SessionMonitor,W=arguments.length>3&&arguments[3]!==void 0?arguments[3]:g.TokenRevocationClient,re=arguments.length>4&&arguments[4]!==void 0?arguments[4]:b.TokenClient,D=arguments.length>5&&arguments[5]!==void 0?arguments[5]:S.JoseUtil;w(this,T),C instanceof u.UserManagerSettings||(C=new u.UserManagerSettings(C));var V=v(this,_.call(this,C));return V._events=new l.UserManagerEvents(C),V._silentRenewService=new U(V),V.settings.automaticSilentRenew&&(o.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),V.startSilentRenew()),V.settings.monitorSession&&(o.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),V._sessionMonitor=new $(V)),V._tokenRevocationClient=new W(V._settings),V._tokenClient=new re(V._settings),V._joseUtil=D,V}return(function(U,$){if(typeof $!="function"&&$!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof $);U.prototype=Object.create($&&$.prototype,{constructor:{value:U,enumerable:!1,writable:!0,configurable:!0}}),$&&(Object.setPrototypeOf?Object.setPrototypeOf(U,$):U.__proto__=$)})(T,_),T.prototype.getUser=function(){var U=this;return this._loadUser().then((function($){return $?(o.Log.info("UserManager.getUser: user loaded"),U._events.load($,!1),$):(o.Log.info("UserManager.getUser: user not found in storage"),null)}))},T.prototype.removeUser=function(){var U=this;return this.storeUser(null).then((function(){o.Log.info("UserManager.removeUser: user removed from storage"),U._events.unload()}))},T.prototype.signinRedirect=function(){var U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(U=Object.assign({},U)).request_type="si:r";var $={useReplaceToNavigate:U.useReplaceToNavigate};return this._signinStart(U,this._redirectNavigator,$).then((function(){o.Log.info("UserManager.signinRedirect: successful")}))},T.prototype.signinRedirectCallback=function(U){return this._signinEnd(U||this._redirectNavigator.url).then((function($){return $.profile&&$.profile.sub?o.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",$.profile.sub):o.Log.info("UserManager.signinRedirectCallback: no sub"),$}))},T.prototype.signinPopup=function(){var U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(U=Object.assign({},U)).request_type="si:p";var $=U.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return $?(U.redirect_uri=$,U.display="popup",this._signin(U,this._popupNavigator,{startUrl:$,popupWindowFeatures:U.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:U.popupWindowTarget||this.settings.popupWindowTarget}).then((function(W){return W&&(W.profile&&W.profile.sub?o.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",W.profile.sub):o.Log.info("UserManager.signinPopup: no sub")),W}))):(o.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},T.prototype.signinPopupCallback=function(U){return this._signinCallback(U,this._popupNavigator).then((function($){return $&&($.profile&&$.profile.sub?o.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",$.profile.sub):o.Log.info("UserManager.signinPopupCallback: no sub")),$})).catch((function($){o.Log.error($.message)}))},T.prototype.signinSilent=function(){var U=this,$=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return $=Object.assign({},$),this._loadUser().then((function(W){return W&&W.refresh_token?($.refresh_token=W.refresh_token,U._useRefreshToken($)):($.request_type="si:s",$.id_token_hint=$.id_token_hint||U.settings.includeIdTokenInSilentRenew&&W&&W.id_token,W&&U._settings.validateSubOnSilentRenew&&(o.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",W.profile.sub),$.current_sub=W.profile.sub),U._signinSilentIframe($))}))},T.prototype._useRefreshToken=function(){var U=this,$=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._tokenClient.exchangeRefreshToken($).then((function(W){return W?W.access_token?U._loadUser().then((function(re){if(re){var D=Promise.resolve();return W.id_token&&(D=U._validateIdTokenFromTokenRefreshToken(re.profile,W.id_token)),D.then((function(){return o.Log.debug("UserManager._useRefreshToken: refresh token response success"),re.id_token=W.id_token||re.id_token,re.access_token=W.access_token,re.refresh_token=W.refresh_token||re.refresh_token,re.expires_in=W.expires_in,U.storeUser(re).then((function(){return U._events.load(re),re}))}))}return null})):(o.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(o.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},T.prototype._validateIdTokenFromTokenRefreshToken=function(U,$){var W=this;return this._metadataService.getIssuer().then((function(re){return W.settings.getEpochTime().then((function(D){return W._joseUtil.validateJwtAttributes($,re,W._settings.client_id,W._settings.clockSkew,D).then((function(V){return V?V.sub!==U.sub?(o.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"))):V.auth_time&&V.auth_time!==U.auth_time?(o.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"))):V.azp&&V.azp!==U.azp?(o.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"))):!V.azp&&U.azp?(o.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:(o.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},T.prototype._signinSilentIframe=function(){var U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},$=U.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return $?(U.redirect_uri=$,U.prompt=U.prompt||"none",this._signin(U,this._iframeNavigator,{startUrl:$,silentRequestTimeout:U.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(W){return W&&(W.profile&&W.profile.sub?o.Log.info("UserManager.signinSilent: successful, signed in sub: ",W.profile.sub):o.Log.info("UserManager.signinSilent: no sub")),W}))):(o.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},T.prototype.signinSilentCallback=function(U){return this._signinCallback(U,this._iframeNavigator).then((function($){return $&&($.profile&&$.profile.sub?o.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",$.profile.sub):o.Log.info("UserManager.signinSilentCallback: no sub")),$}))},T.prototype.signinCallback=function(U){var $=this;return this.readSigninResponseState(U).then((function(W){var re=W.state;return W.response,re.request_type==="si:r"?$.signinRedirectCallback(U):re.request_type==="si:p"?$.signinPopupCallback(U):re.request_type==="si:s"?$.signinSilentCallback(U):Promise.reject(new Error("invalid response_type in state"))}))},T.prototype.signoutCallback=function(U,$){var W=this;return this.readSignoutResponseState(U).then((function(re){var D=re.state,V=re.response;return D?D.request_type==="so:r"?W.signoutRedirectCallback(U):D.request_type==="so:p"?W.signoutPopupCallback(U,$):Promise.reject(new Error("invalid response_type in state")):V}))},T.prototype.querySessionStatus=function(){var U=this,$=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};($=Object.assign({},$)).request_type="si:s";var W=$.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return W?($.redirect_uri=W,$.prompt="none",$.response_type=$.response_type||this.settings.query_status_response_type,$.scope=$.scope||"openid",$.skipUserInfo=!0,this._signinStart($,this._iframeNavigator,{startUrl:W,silentRequestTimeout:$.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(re){return U.processSigninResponse(re.url).then((function(D){if(o.Log.debug("UserManager.querySessionStatus: got signin response"),D.session_state&&D.profile.sub)return o.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",D.profile.sub),{session_state:D.session_state,sub:D.profile.sub,sid:D.profile.sid};o.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(D){if(D.session_state&&U.settings.monitorAnonymousSession&&(D.message=="login_required"||D.message=="consent_required"||D.message=="interaction_required"||D.message=="account_selection_required"))return o.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:D.session_state};throw D}))}))):(o.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},T.prototype._signin=function(U,$){var W=this,re=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signinStart(U,$,re).then((function(D){return W._signinEnd(D.url,U)}))},T.prototype._signinStart=function(U,$){var W=this,re=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return $.prepare(re).then((function(D){return o.Log.debug("UserManager._signinStart: got navigator window handle"),W.createSigninRequest(U).then((function(V){return o.Log.debug("UserManager._signinStart: got signin request"),re.url=V.url,re.id=V.state.id,D.navigate(re)})).catch((function(V){throw D.close&&(o.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),D.close()),V}))}))},T.prototype._signinEnd=function(U){var $=this,W=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.processSigninResponse(U).then((function(re){o.Log.debug("UserManager._signinEnd: got signin response");var D=new c.User(re);if(W.current_sub){if(W.current_sub!==D.profile.sub)return o.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",D.profile.sub),Promise.reject(new Error("login_required"));o.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return $.storeUser(D).then((function(){return o.Log.debug("UserManager._signinEnd: user stored"),$._events.load(D),D}))}))},T.prototype._signinCallback=function(U,$){o.Log.debug("UserManager._signinCallback");var W=this._settings.response_mode==="query"||!this._settings.response_mode&&m.SigninRequest.isCode(this._settings.response_type)?"?":"#";return $.callback(U,void 0,W)},T.prototype.signoutRedirect=function(){var U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(U=Object.assign({},U)).request_type="so:r";var $=U.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;$&&(U.post_logout_redirect_uri=$);var W={useReplaceToNavigate:U.useReplaceToNavigate};return this._signoutStart(U,this._redirectNavigator,W).then((function(){o.Log.info("UserManager.signoutRedirect: successful")}))},T.prototype.signoutRedirectCallback=function(U){return this._signoutEnd(U||this._redirectNavigator.url).then((function($){return o.Log.info("UserManager.signoutRedirectCallback: successful"),$}))},T.prototype.signoutPopup=function(){var U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(U=Object.assign({},U)).request_type="so:p";var $=U.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return U.post_logout_redirect_uri=$,U.display="popup",U.post_logout_redirect_uri&&(U.state=U.state||{}),this._signout(U,this._popupNavigator,{startUrl:$,popupWindowFeatures:U.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:U.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){o.Log.info("UserManager.signoutPopup: successful")}))},T.prototype.signoutPopupCallback=function(U,$){return $===void 0&&typeof U=="boolean"&&($=U,U=null),this._popupNavigator.callback(U,$,"?").then((function(){o.Log.info("UserManager.signoutPopupCallback: successful")}))},T.prototype._signout=function(U,$){var W=this,re=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signoutStart(U,$,re).then((function(D){return W._signoutEnd(D.url)}))},T.prototype._signoutStart=function(){var U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},$=this,W=arguments[1],re=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return W.prepare(re).then((function(D){return o.Log.debug("UserManager._signoutStart: got navigator window handle"),$._loadUser().then((function(V){return o.Log.debug("UserManager._signoutStart: loaded current user from storage"),($._settings.revokeAccessTokenOnSignout?$._revokeInternal(V):Promise.resolve()).then((function(){var he=U.id_token_hint||V&&V.id_token;return he&&(o.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),U.id_token_hint=he),$.removeUser().then((function(){return o.Log.debug("UserManager._signoutStart: user removed, creating signout request"),$.createSignoutRequest(U).then((function(z){return o.Log.debug("UserManager._signoutStart: got signout request"),re.url=z.url,z.state&&(re.id=z.state.id),D.navigate(re)}))}))}))})).catch((function(V){throw D.close&&(o.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),D.close()),V}))}))},T.prototype._signoutEnd=function(U){return this.processSignoutResponse(U).then((function($){return o.Log.debug("UserManager._signoutEnd: got signout response"),$}))},T.prototype.revokeAccessToken=function(){var U=this;return this._loadUser().then((function($){return U._revokeInternal($,!0).then((function(W){if(W)return o.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),$.access_token=null,$.refresh_token=null,$.expires_at=null,$.token_type=null,U.storeUser($).then((function(){o.Log.debug("UserManager.revokeAccessToken: user stored"),U._events.load($)}))}))})).then((function(){o.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},T.prototype._revokeInternal=function(U,$){var W=this;if(U){var re=U.access_token,D=U.refresh_token;return this._revokeAccessTokenInternal(re,$).then((function(V){return W._revokeRefreshTokenInternal(D,$).then((function(he){return V||he||o.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),V||he}))}))}return Promise.resolve(!1)},T.prototype._revokeAccessTokenInternal=function(U,$){return!U||U.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(U,$).then((function(){return!0}))},T.prototype._revokeRefreshTokenInternal=function(U,$){return U?this._tokenRevocationClient.revoke(U,$,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},T.prototype.startSilentRenew=function(){this._silentRenewService.start()},T.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},T.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(U){return U?(o.Log.debug("UserManager._loadUser: user storageString loaded"),c.User.fromStorageString(U)):(o.Log.debug("UserManager._loadUser: no user storageString"),null)}))},T.prototype.storeUser=function(U){if(U){o.Log.debug("UserManager.storeUser: storing user");var $=U.toStorageString();return this._userStore.set(this._userStoreKey,$)}return o.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},s(T,[{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}}]),T})(a.OidcClient)},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.UserManagerSettings=void 0;var s=(function(){function b(S,w){for(var v=0;v<w.length;v++){var _=w[v];_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(S,_.key,_)}}return function(S,w,v){return w&&b(S.prototype,w),v&&b(S,v),S}})(),o=(i(0),i(5)),a=i(40),u=i(41),c=i(43),l=i(6),d=i(1),f=i(8);function m(b,S){if(!(b instanceof S))throw new TypeError("Cannot call a class as a function")}function g(b,S){if(!b)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!S||typeof S!="object"&&typeof S!="function"?b:S}r.UserManagerSettings=(function(b){function S(){var w=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},v=w.popup_redirect_uri,_=w.popup_post_logout_redirect_uri,T=w.popupWindowFeatures,C=w.popupWindowTarget,U=w.silent_redirect_uri,$=w.silentRequestTimeout,W=w.automaticSilentRenew,re=W!==void 0&&W,D=w.validateSubOnSilentRenew,V=D!==void 0&&D,he=w.includeIdTokenInSilentRenew,z=he===void 0||he,_e=w.monitorSession,Ce=_e===void 0||_e,Fe=w.monitorAnonymousSession,ze=Fe!==void 0&&Fe,ae=w.checkSessionInterval,ve=ae===void 0?2e3:ae,L=w.stopCheckSessionOnError,ie=L===void 0||L,xe=w.query_status_response_type,ue=w.revokeAccessTokenOnSignout,De=ue!==void 0&&ue,ke=w.accessTokenExpiringNotificationTime,We=ke===void 0?60:ke,Oe=w.redirectNavigator,te=Oe===void 0?new a.RedirectNavigator:Oe,le=w.popupNavigator,Te=le===void 0?new u.PopupNavigator:le,G=w.iframeNavigator,P=G===void 0?new c.IFrameNavigator:G,x=w.userStore,A=x===void 0?new l.WebStorageStateStore({store:d.Global.sessionStorage}):x;m(this,S);var O=g(this,b.call(this,arguments[0]));return O._popup_redirect_uri=v,O._popup_post_logout_redirect_uri=_,O._popupWindowFeatures=T,O._popupWindowTarget=C,O._silent_redirect_uri=U,O._silentRequestTimeout=$,O._automaticSilentRenew=re,O._validateSubOnSilentRenew=V,O._includeIdTokenInSilentRenew=z,O._accessTokenExpiringNotificationTime=We,O._monitorSession=Ce,O._monitorAnonymousSession=ze,O._checkSessionInterval=ve,O._stopCheckSessionOnError=ie,xe?O._query_status_response_type=xe:arguments[0]&&arguments[0].response_type?O._query_status_response_type=f.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":O._query_status_response_type="id_token",O._revokeAccessTokenOnSignout=De,O._redirectNavigator=te,O._popupNavigator=Te,O._iframeNavigator=P,O._userStore=A,O}return(function(v,_){if(typeof _!="function"&&_!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof _);v.prototype=Object.create(_&&_.prototype,{constructor:{value:v,enumerable:!1,writable:!0,configurable:!0}}),_&&(Object.setPrototypeOf?Object.setPrototypeOf(v,_):v.__proto__=_)})(S,b),s(S,[{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}}]),S})(o.OidcClientSettings)},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.RedirectNavigator=void 0;var s=(function(){function a(u,c){for(var l=0;l<c.length;l++){var d=c[l];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(u,d.key,d)}}return function(u,c,l){return c&&a(u.prototype,c),l&&a(u,l),u}})(),o=i(0);r.RedirectNavigator=(function(){function a(){(function(c,l){if(!(c instanceof l))throw new TypeError("Cannot call a class as a function")})(this,a)}return a.prototype.prepare=function(){return Promise.resolve(this)},a.prototype.navigate=function(c){return c&&c.url?(c.useReplaceToNavigate?window.location.replace(c.url):window.location=c.url,Promise.resolve()):(o.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},s(a,[{key:"url",get:function(){return window.location.href}}]),a})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.PopupNavigator=void 0;var s=i(0),o=i(42);r.PopupNavigator=(function(){function a(){(function(c,l){if(!(c instanceof l))throw new TypeError("Cannot call a class as a function")})(this,a)}return a.prototype.prepare=function(c){var l=new o.PopupWindow(c);return Promise.resolve(l)},a.prototype.callback=function(c,l,d){s.Log.debug("PopupNavigator.callback");try{return o.PopupWindow.notifyOpener(c,l,d),Promise.resolve()}catch(f){return Promise.reject(f)}},a})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.PopupWindow=void 0;var s=(function(){function u(c,l){for(var d=0;d<l.length;d++){var f=l[d];f.enumerable=f.enumerable||!1,f.configurable=!0,"value"in f&&(f.writable=!0),Object.defineProperty(c,f.key,f)}}return function(c,l,d){return l&&u(c.prototype,l),d&&u(c,d),c}})(),o=i(0),a=i(3);r.PopupWindow=(function(){function u(c){var l=this;(function(g,b){if(!(g instanceof b))throw new TypeError("Cannot call a class as a function")})(this,u),this._promise=new Promise((function(m,g){l._resolve=m,l._reject=g}));var d=c.popupWindowTarget||"_blank",f=c.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",d,f),this._popup&&(o.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return u.prototype.navigate=function(l){return this._popup?l&&l.url?(o.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=l.id,this._id&&(window["popupCallback_"+l.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=l.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},u.prototype._success=function(l){o.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(l)},u.prototype._error=function(l){o.Log.error("PopupWindow.error: ",l),this._cleanup(),this._reject(new Error(l))},u.prototype.close=function(){this._cleanup(!1)},u.prototype._cleanup=function(l){o.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!l&&this._popup.close(),this._popup=null},u.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},u.prototype._callback=function(l,d){this._cleanup(d),l?(o.Log.debug("PopupWindow.callback success"),this._success({url:l})):(o.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},u.notifyOpener=function(l,d,f){if(window.opener){if(l=l||window.location.href){var m=a.UrlUtility.parseUrlFragment(l,f);if(m.state){var g="popupCallback_"+m.state,b=window.opener[g];b?(o.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),b(l,d)):o.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else o.Log.warn("PopupWindow.notifyOpener: no state found in response url")}}else o.Log.warn("PopupWindow.notifyOpener: no window.opener. Can't complete notification.")},s(u,[{key:"promise",get:function(){return this._promise}}]),u})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.IFrameNavigator=void 0;var s=i(0),o=i(44);r.IFrameNavigator=(function(){function a(){(function(c,l){if(!(c instanceof l))throw new TypeError("Cannot call a class as a function")})(this,a)}return a.prototype.prepare=function(c){var l=new o.IFrameWindow(c);return Promise.resolve(l)},a.prototype.callback=function(c){s.Log.debug("IFrameNavigator.callback");try{return o.IFrameWindow.notifyParent(c),Promise.resolve()}catch(l){return Promise.reject(l)}},a})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.IFrameWindow=void 0;var s=(function(){function a(u,c){for(var l=0;l<c.length;l++){var d=c[l];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(u,d.key,d)}}return function(u,c,l){return c&&a(u.prototype,c),l&&a(u,l),u}})(),o=i(0);r.IFrameWindow=(function(){function a(u){var c=this;(function(d,f){if(!(d instanceof f))throw new TypeError("Cannot call a class as a function")})(this,a),this._promise=new Promise((function(l,d){c._resolve=l,c._reject=d})),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 a.prototype.navigate=function(c){if(c&&c.url){var l=c.silentRequestTimeout||1e4;o.Log.debug("IFrameWindow.navigate: Using timeout of:",l),this._timer=window.setTimeout(this._timeout.bind(this),l),this._frame.src=c.url}else this._error("No url provided");return this.promise},a.prototype._success=function(c){this._cleanup(),o.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(c)},a.prototype._error=function(c){this._cleanup(),o.Log.error(c),this._reject(new Error(c))},a.prototype.close=function(){this._cleanup()},a.prototype._cleanup=function(){this._frame&&(o.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)},a.prototype._timeout=function(){o.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},a.prototype._message=function(c){if(o.Log.debug("IFrameWindow.message"),this._timer&&c.origin===this._origin&&c.source===this._frame.contentWindow&&typeof c.data=="string"&&(c.data.startsWith("http://")||c.data.startsWith("https://"))){var l=c.data;l?this._success({url:l}):this._error("Invalid response from frame")}},a.notifyParent=function(c){o.Log.debug("IFrameWindow.notifyParent"),(c=c||window.location.href)&&(o.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(c,location.protocol+"//"+location.host))},s(a,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),a})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.UserManagerEvents=void 0;var s=i(0),o=i(16),a=i(17);r.UserManagerEvents=(function(u){function c(l){(function(m,g){if(!(m instanceof g))throw new TypeError("Cannot call a class as a function")})(this,c);var d=(function(m,g){if(!m)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!g||typeof g!="object"&&typeof g!="function"?m:g})(this,u.call(this,l));return d._userLoaded=new a.Event("User loaded"),d._userUnloaded=new a.Event("User unloaded"),d._silentRenewError=new a.Event("Silent renew error"),d._userSignedIn=new a.Event("User signed in"),d._userSignedOut=new a.Event("User signed out"),d._userSessionChanged=new a.Event("User session changed"),d}return(function(d,f){if(typeof f!="function"&&f!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof f);d.prototype=Object.create(f&&f.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),f&&(Object.setPrototypeOf?Object.setPrototypeOf(d,f):d.__proto__=f)})(c,u),c.prototype.load=function(d){var f=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];s.Log.debug("UserManagerEvents.load"),u.prototype.load.call(this,d),f&&this._userLoaded.raise(d)},c.prototype.unload=function(){s.Log.debug("UserManagerEvents.unload"),u.prototype.unload.call(this),this._userUnloaded.raise()},c.prototype.addUserLoaded=function(d){this._userLoaded.addHandler(d)},c.prototype.removeUserLoaded=function(d){this._userLoaded.removeHandler(d)},c.prototype.addUserUnloaded=function(d){this._userUnloaded.addHandler(d)},c.prototype.removeUserUnloaded=function(d){this._userUnloaded.removeHandler(d)},c.prototype.addSilentRenewError=function(d){this._silentRenewError.addHandler(d)},c.prototype.removeSilentRenewError=function(d){this._silentRenewError.removeHandler(d)},c.prototype._raiseSilentRenewError=function(d){s.Log.debug("UserManagerEvents._raiseSilentRenewError",d.message),this._silentRenewError.raise(d)},c.prototype.addUserSignedIn=function(d){this._userSignedIn.addHandler(d)},c.prototype.removeUserSignedIn=function(d){this._userSignedIn.removeHandler(d)},c.prototype._raiseUserSignedIn=function(){s.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},c.prototype.addUserSignedOut=function(d){this._userSignedOut.addHandler(d)},c.prototype.removeUserSignedOut=function(d){this._userSignedOut.removeHandler(d)},c.prototype._raiseUserSignedOut=function(){s.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},c.prototype.addUserSessionChanged=function(d){this._userSessionChanged.addHandler(d)},c.prototype.removeUserSessionChanged=function(d){this._userSessionChanged.removeHandler(d)},c.prototype._raiseUserSessionChanged=function(){s.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},c})(o.AccessTokenEvents)},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.Timer=void 0;var s=(function(){function d(f,m){for(var g=0;g<m.length;g++){var b=m[g];b.enumerable=b.enumerable||!1,b.configurable=!0,"value"in b&&(b.writable=!0),Object.defineProperty(f,b.key,b)}}return function(f,m,g){return m&&d(f.prototype,m),g&&d(f,g),f}})(),o=i(0),a=i(1),u=i(17);function c(d,f){if(!(d instanceof f))throw new TypeError("Cannot call a class as a function")}function l(d,f){if(!d)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!f||typeof f!="object"&&typeof f!="function"?d:f}r.Timer=(function(d){function f(m){var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:a.Global.timer,b=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;c(this,f);var S=l(this,d.call(this,m));return S._timer=g,S._nowFunc=b||function(){return Date.now()/1e3},S}return(function(g,b){if(typeof b!="function"&&b!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof b);g.prototype=Object.create(b&&b.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(g,b):g.__proto__=b)})(f,d),f.prototype.init=function(g){g<=0&&(g=1),g=parseInt(g);var b=this.now+g;if(this.expiration===b&&this._timerHandle)o.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),o.Log.debug("Timer.init timer "+this._name+" for duration:",g),this._expiration=b;var S=5;g<S&&(S=g),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*S)}},f.prototype.cancel=function(){this._timerHandle&&(o.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},f.prototype._callback=function(){var g=this._expiration-this.now;o.Log.debug("Timer.callback; "+this._name+" timer expires in:",g),this._expiration<=this.now&&(this.cancel(),d.prototype.raise.call(this))},s(f,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),f})(u.Event)},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.SilentRenewService=void 0;var s=i(0);r.SilentRenewService=(function(){function o(a){(function(c,l){if(!(c instanceof l))throw new TypeError("Cannot call a class as a function")})(this,o),this._userManager=a}return o.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then((function(u){})).catch((function(u){s.Log.error("SilentRenewService.start: Error from getUser:",u.message)})))},o.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},o.prototype._tokenExpiring=function(){var u=this;this._userManager.signinSilent().then((function(c){s.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")}),(function(c){s.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",c.message),u._userManager.events._raiseSilentRenewError(c)}))},o})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.CordovaPopupNavigator=void 0;var s=i(21);r.CordovaPopupNavigator=(function(){function o(){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,o)}return o.prototype.prepare=function(u){var c=new s.CordovaPopupWindow(u);return Promise.resolve(c)},o})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.CordovaIFrameNavigator=void 0;var s=i(21);r.CordovaIFrameNavigator=(function(){function o(){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,o)}return o.prototype.prepare=function(u){u.popupWindowFeatures="hidden=yes";var c=new s.CordovaPopupWindow(u);return Promise.resolve(c)},o})()},function(t,r,i){Object.defineProperty(r,"__esModule",{value:!0}),r.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),r={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"]},i={"Content-Type":"application/json"},s=await fetch(e.registrationEndpoint.toString(),{method:"POST",headers:i,body:JSON.stringify(r)});if(s.ok){const o=await s.json();return validateRegistrationResponse(o,n),{clientId:o.client_id,clientSecret:o.client_secret,expiresAt:o.client_secret_expires_at,idTokenSignedResponseAlg:o.id_token_signed_response_alg,clientType:"dynamic"}}throw s.status===400&&processErrorResponse(await s.json(),n),new Error(`Dynamic client registration failed: the server returned ${s.status} ${s.statusText} - ${await s.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,r){validatePreconditions(n,t);const i={"content-type":"application/x-www-form-urlencoded"};let s;r&&(s=await generateDpopKeyPair(),i.DPoP=await createDpopHeader(n.tokenEndpoint,"POST",s)),e.clientSecret&&(i.Authorization=`Basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`);const o={grant_type:t.grantType,redirect_uri:t.redirectUrl,code:t.code,code_verifier:t.codeVerifier,client_id:e.clientId},a={method:"POST",headers:i,body:new URLSearchParams(o).toString()},c=await(await fetch(n.tokenEndpoint,a)).json(),l=validateTokenEndpointResponse(c,r),{webId:d,clientId:f}=await getWebidFromTokenPayload(l.id_token,n.jwksUri,n.issuer,e.clientId);return{accessToken:l.access_token,idToken:l.id_token,refreshToken:hasRefreshToken(l)?l.refresh_token:void 0,webId:d,clientId:f,dpopKey:s,expiresIn:l.expires_in}}const isValidUrl=n=>{try{return new URL(n),!0}catch{return!1}};async function refresh(n,e,t,r){if(t.clientId===void 0)throw new Error("No client ID available when trying to refresh the access token.");const i={grant_type:"refresh_token",refresh_token:n};let s={};r!==void 0&&(s={DPoP:await createDpopHeader(e.tokenEndpoint,"POST",r)});let o={};t.clientSecret!==void 0?o={Authorization:`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`}:isValidUrl(t.clientId)&&(i.client_id=t.clientId);const a=await fetch(e.tokenEndpoint,{method:"POST",body:new URLSearchParams(i).toString(),headers:{...s,...o,"Content-Type":"application/x-www-form-urlencoded"}});let u;try{u=await a.json()}catch{throw new Error(`The token endpoint of issuer ${e.issuer} returned a malformed response.`)}const c=validateTokenEndpointResponse(u,r!==void 0),{webId:l}=await getWebidFromTokenPayload(c.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:c.access_token,idToken:c.id_token,refreshToken:typeof c.refresh_token=="string"?c.refresh_token:void 0,webId:l,dpopKey:r,expiresIn:c.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 r=0;r<=e.length;r+=1){const i=e.key(r);i&&(i.match(/^oidc\..+$/)||i.match(/^solidClientAuthenticationUser:.+$/))&&t.push(i)}t.forEach(r=>e.removeItem(r))}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 r=e.redirectUrl??normalizeCallbackUrl(window.location.href);if(!isValidRedirectUrl(r))throw new Error(`${r} 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:r,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 r=await this.redirectHandler.handle(e,t,void 0);return this.fetch=r.fetch.bind(window),this.boundLogout=r.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:r.isLoggedIn,webId:r.webId,sessionId:r.sessionId,expirationDate:r.expirationDate,clientAppId:r.clientAppId}}catch(r){await this.cleanUrlAfterRedirect(e),t.emit(EVENTS.ERROR,"redirect",r);return}};async cleanUrlAfterRedirect(e){const t=removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(r=>{setTimeout(()=>r(),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,r,i){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=r,this.clientRegistrar=i,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=r,this.clientRegistrar=i}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),r=await handleRegistration(e,t,this.storageUtility,this.clientRegistrar),i={issuer:t.issuer,dpop:e.tokenType.toLowerCase()==="dpop",...e,issuerConfiguration:t,client:r,scopes:normalizeScopes(e.customScopes)};return this.oidcHandler.handle(i)}}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"},r=new oidcClient_minExports.OidcClient(t);try{const i=await r.createSigninRequest();return await this.setupRedirectHandler({oidcLoginOptions:e,state:i.state._id,codeVerifier:i.state._code_verifier,targetUrl:i.url.toString()})}catch(i){console.error(i)}}}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 r=new URL(WELL_KNOWN_OPENID_CONFIG,e.endsWith("/")?e:`${e}/`).href,i=await fetch(r);try{t=processConfig(await i.json())}catch(s){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${s.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,r,i,s,o,a,u,c]=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 o=="string"&&!isValidRedirectUrl(o)){await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})]);return}if(c!==void 0&&!isSupportedTokenType(c))throw new Error(`Tokens of type [${c}] are not supported.`);if(!(i===void 0&&t===void 0&&r===void 0&&a===void 0))return{sessionId:e,webId:r,isLoggedIn:t==="true",redirectUrl:o,refreshToken:a,issuer:u,clientAppId:i,clientAppSecret:s,tokenType:c??"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,r,i,s,o){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=r,this.clientRegistrar=i,this.tokerRefresher=s,this.fetch=o,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=r,this.clientRegistrar=i,this.tokerRefresher=s}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 r=new URL(e),i=r.searchParams.get("state"),s=await this.storageUtility.getForUser(i,"sessionId",{errorIfNull:!0}),{issuerConfig:o,codeVerifier:a,redirectUrl:u,dpop:c}=await loadOidcContextFromStorage(s,this.storageUtility,this.issuerConfigFetcher),l=r.searchParams.get("iss");if(typeof l=="string"&&l!==o.issuer)throw new Error(`The value of the iss parameter (${l}) does not match the issuer identifier of the authorization server (${o.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(a===void 0)throw new Error(`The code verifier for session ${s} is missing from storage.`);if(u===void 0)throw new Error(`The redirect URL for session ${s} is missing from storage.`);const d=await this.clientRegistrar.getClient({sessionId:s},o),f=Date.now(),m=await getTokens(o,d,{grantType:"authorization_code",code:r.searchParams.get("code"),codeVerifier:a,redirectUrl:u},c);window.localStorage.removeItem(`oidc.${i}`);let g;m.refreshToken!==void 0&&(g={sessionId:s,refreshToken:m.refreshToken,tokenRefresher:this.tokerRefresher});const b=buildAuthenticatedFetch(m.accessToken,{dpopKey:m.dpopKey,refreshOptions:g,eventEmitter:t,expiresIn:m.expiresIn,fetch:this.fetch});await saveSessionInfoToStorage(this.storageUtility,s,m.webId,m.clientId,"true",void 0,!0);const S=await this.sessionInfoManager.get(s);if(!S)throw new Error(`Could not retrieve session: [${s}].`);return Object.assign(S,{fetch:b,getLogoutUrl:maybeBuildRpInitiatedLogout({idTokenHint:m.idToken,endSessionEndpoint:o.endSessionEndpoint}),expirationDate:typeof m.expiresIn=="number"?f+m.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[r,i,s,o,a]=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})]),u=s!==void 0?Number.parseInt(s,10):-1,c=i!==void 0&&u!==0&&Math.floor(Date.now()/1e3)>u;if(r&&isKnownClientType(a)&&!c)return i!==void 0?{clientId:r,clientSecret:i,clientName:o,clientType:"dynamic",expiresAt:u}:{clientId:r,clientName:o,clientType:a};try{const l=await registerClient(e,t),d={clientId:l.clientId,clientType:"dynamic"};return l.clientSecret!==void 0&&(d.clientSecret=l.clientSecret,d.expiresAt=String(l.expiresAt)),l.idTokenSignedResponseAlg&&(d.idTokenSignedResponseAlg=l.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,d,{secure:!1}),l}catch(l){throw new Error("Client registration failed.",{cause:l})}}}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 r=new URL(e),i=r.searchParams.get("error"),s=r.searchParams.get("error_description");t.emit(EVENTS.ERROR,i,s)}return getUnauthenticatedSession()}}class TokenRefresher{storageUtility;issuerConfigFetcher;clientRegistrar;constructor(e,t,r){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=r,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=r}async refresh(e,t,r,i){const s=await loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),o=await this.clientRegistrar.getClient({sessionId:e},s.issuerConfig);if(t===void 0)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(s.dpop&&r===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 a=await refresh(t,s.issuerConfig,o,r);return a.refreshToken!==void 0&&i?.emit(EVENTS.NEW_REFRESH_TOKEN,a.refreshToken),a}}function getClientAuthenticationWithDependencies(n){const e=new InMemoryStorage,t=n.secureStorage||e,r=n.insecureStorage||new BrowserStorage,i=new StorageUtilityBrowser(t,r),s=new IssuerConfigFetcher(i),o=new ClientRegistrar(i),a=new SessionInfoManager(i),u=new TokenRefresher(i,s,o),c=new Redirector,l=new OidcLoginHandler(i,new AuthorizationCodeWithPkceOidcHandler(i,c),s,o),d=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(i,a,s,o,u,n.fetch),new FallbackRedirectHandler]);return new ClientAuthentication(l,d,new IWaterfallLogoutHandler(a,c),a,s)}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 r=await e.validateCurrentSession(n);return r!==null?(window.localStorage.setItem(KEY_CURRENT_URL,window.location.href),await e.login({sessionId:n,prompt:"none",oidcIssuer:r.issuer,redirectUrl:r.redirectUrl,clientId:r.clientAppId,clientSecret:r.clientAppSecret,tokenType:r.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,r=t.url??window.location.href;this.tokenRequestInProgress=!0;const i=await this.clientAuthentication.handleIncomingRedirect(r,this.events);try{await this.xpodErrorLogout}catch(s){throw this.tokenRequestInProgress=!1,s}if(isLoggedIn(i)){this.setSessionInfo(i);const s=window.localStorage.getItem(KEY_CURRENT_URL);s===null?this.events.emit(EVENTS.LOGIN):(window.localStorage.removeItem(KEY_CURRENT_URL),this.events.emit(EVENTS.SESSION_RESTORED,s))}else if(t.restorePreviousSession===!0){const s=window.localStorage.getItem(KEY_CURRENT_SESSION);if(s!==null&&await silentlyAuthenticate(s,this.clientAuthentication,this))return new Promise(()=>{})}return this.tokenRequestInProgress=!1,i};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})}}async function chooseAccessRoute(n,e={}){const t=usableRoutes(n,e.managedClient??!0,e.allowLocalOnlyRoutes??!1);if(t.length===0)return null;const r=t[0];if(isSelfProvenRoute(r))return r;const i=e.probe??defaultProbe,s=e.probeTimeoutMs??1e3;return(await Promise.all(t.map(async a=>({route:a,ok:isSelfProvenRoute(a)||await probeWithTimeout(a,i,s)})))).find(a=>a.ok)?.route??null}function isSelfProvenRoute(n){return n.health==="healthy"}function usableRoutes(n,e,t){return n.routes.filter(r=>r.health!=="unreachable").filter(r=>e||!r.requiresManagedClient).filter(r=>t||r.visibility!=="local-only").slice().sort((r,i)=>r.priority-i.priority||r.id.localeCompare(i.id))}function createSolidAccessRouteFetch(n){const e=n.managedClient??!0;let t;const r=async u=>{const c=n.routes(),l=u===void 0?c:c.filter(m=>routeKey(m)!==u),d={canonicalUrl:l[0]?.canonicalUrl??"",routes:l},f=await chooseAccessRoute(d,{managedClient:e,...n.allowLocalOnlyRoutes===void 0?{}:{allowLocalOnlyRoutes:n.allowLocalOnlyRoutes},...n.probeTimeoutMs===void 0?{}:{probeTimeoutMs:n.probeTimeoutMs},...n.probe===void 0?{}:{probe:n.probe}});return t=f??void 0,f},i=async()=>t&&n.routes().some(u=>u.id===t?.id&&u.targetUrl===t?.targetUrl)?t:await r()??void 0,s=u=>createSolidLocalRouteFetch({fetch:n.fetch,routes:()=>[{canonicalBaseUrl:u.canonicalUrl,localBaseUrl:u.targetUrl}]}),o=u=>!!resolveSolidLocalRouteUrl(u,n.routes().map(toLocalRoute$1)),a=u=>{const c=requestUrl(u);if(!c||!o(c))return;const l=n.routes(),d=usableRoutes({canonicalUrl:l[0]?.canonicalUrl??"",routes:l},e,n.allowLocalOnlyRoutes??!1)[0];if(!(!d||sameOrigin(d.targetUrl,c)))return c};return async(u,c)=>{const l=requestUrl(u);if(!l||!o(l))return c===void 0?n.fetch.call(globalThis,u):n.fetch.call(globalThis,u,c);const d=await i();if(!d){const f=a(u);if(f)throw new NoUsableAccessRouteError(f.href,n.routes());return c===void 0?n.fetch.call(globalThis,u):n.fetch.call(globalThis,u,c)}try{return await s(d)(u,c)}catch(f){t=void 0;const m=(c?.method??(u instanceof Request?u.method:"GET")).toUpperCase();if(!["GET","HEAD","OPTIONS"].includes(m))throw f;await n.refreshRoutes?.();const g=await r(routeKey(d));if(g&&routeKey(g)!==routeKey(d))return s(g)(u,c);const b=requestUrl(u);throw b&&o(b)?new NoUsableAccessRouteError(b.href,n.routes(),f):f}}}function routeKey(n){return`${n.id}|${n.targetUrl}`}class NoUsableAccessRouteError extends Error{constructor(e,t,r){super(`No usable access route can reach ${e}`),this.url=e,this.routes=t,this.reason=r,this.name="NoUsableAccessRouteError"}}function toLocalRoute$1(n){return{canonicalBaseUrl:n.canonicalUrl,localBaseUrl:n.targetUrl}}function sameOrigin(n,e){try{return new URL(n).origin===e.origin}catch{return!1}}function requestUrl(n){if(n instanceof Request)try{return new URL(n.url)}catch{return}try{return new URL(String(n))}catch{return}}async function probeWithTimeout(n,e,t){const r=new AbortController,i=setTimeout(()=>r.abort(),t);try{return await Promise.resolve(e(n,r.signal))}catch{return!1}finally{clearTimeout(i)}}function answersAccessRoute(n){return n.status<500}async function defaultProbe(n,e){if(!n.targetUrl.startsWith("http://")&&!n.targetUrl.startsWith("https://"))return n.health==="healthy";const t=await fetch(new URL("/.well-known/solid",n.targetUrl),{method:"HEAD",signal:e});return answersAccessRoute(t)}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 r={status:"initializing"},i,s,o,a,u=!1,c=!1,l,d=!1,f=0,m=!1,g=0,b=0,S;const w=()=>{f+=1,m=!0},v=re=>{if(d||((re.status!=="authenticated"||r.status!=="authenticated"||r.webId!==re.webId)&&w(),re.status==="authenticated"&&(m=!1),r=re,areSnapshotsEqual(i,r)))return r;i=r;for(const D of t)D(r);return r},_=()=>{if(S){if(S.generation!==b||S.eventWebId&&S.eventWebId!==e.info.webId)return r;S.eventWebId=e.info.webId}return w(),i=void 0,v(snapshotFromSessionInfo(e.info))},T=()=>(b+=1,v({status:"anonymous"})),C=()=>(b+=1,v(snapshotFromSessionExpired(e.info))),U=(re,D)=>{if(S&&S.generation!==b)return;b+=1;const V=snapshotFromSessionError(D??re??"Solid session error",e.info);c&&(l=V),v(V)};e.events.on(EVENTS.LOGIN,_),e.events.on(EVENTS.SESSION_RESTORED,_),e.events.on(EVENTS.LOGOUT,T),e.events.on(EVENTS.SESSION_EXPIRED,C);const $=e.events;$.on(EVENTS.ERROR,U);const W=(re,D)=>{const V=new Promise((he,z)=>{a=()=>he(r),o=setTimeout(()=>{if(o=void 0,!d&&D.generation===b&&(b+=1,r.status==="initializing")){const Ce=new Error("Previous login is still completing. Reload before reconnecting.");Ce.name="SolidSessionPendingError",v(snapshotFromSessionError(Ce,e.info))}he(r)},15e3);const _e=()=>{s===V&&(clearTimeout(o),o=void 0,a=void 0,S===D&&(S=void 0),s=void 0,c=!1,l=void 0)};re.then(Ce=>{_e(),he(Ce)},Ce=>{_e(),z(Ce)})});return V};return{fetch:e.fetch,createAuthenticatedFetch(re){const D=f,V=()=>{if(d||g>0||m||D!==f||r.status!=="authenticated"||r.webId!==re||!e.info.isLoggedIn||e.info.webId!==re){const he=new Error("Authenticated session is no longer current");throw he.name="AbortError",he}};return async(he,z)=>{V();const _e=await(z===void 0?e.fetch(he):e.fetch(he,z));try{V()}catch(Ce){throw _e.body?.cancel().catch(()=>{}),Ce}return _e}},getSnapshot(){return r},initialize(re={}){if(s)return s;if(u||d)return Promise.resolve(r);const D={generation:++b,eventWebId:void 0};S=D;const V=z=>!d&&D.generation===b&&(!z?.isLoggedIn||!D.eventWebId||D.eventWebId===z.webId);c=!0,l=void 0,v({status:"initializing"});const he=e.handleIncomingRedirect({restorePreviousSession:re.restorePreviousSession??!0}).then(z=>{if(!V(z??e.info))return r;const _e=snapshotFromSessionInfo(z??e.info);return _e.status==="anonymous"&&l?.status==="error"?l:(u=!0,v(_e))}).catch(z=>V()?v(snapshotFromSessionError(z,e.info)):r);return s=W(he,D),s},handleIncomingRedirect(re){if(s)return s;if(d)return Promise.resolve(r);const D={generation:++b,eventWebId:void 0};S=D;const V=z=>!d&&D.generation===b&&(!z?.isLoggedIn||!D.eventWebId||D.eventWebId===z.webId);c=!0,l=void 0,v({status:"initializing"});const he=e.handleIncomingRedirect(re).then(z=>{if(!V(z??e.info))return r;const _e=snapshotFromSessionInfo(z??e.info);return _e.status==="anonymous"&&l?.status==="error"?l:(u=!0,v(_e))}).catch(z=>V()?v(snapshotFromSessionError(z,e.info)):r);return s=W(he,D),s},async login(re){b+=1,w(),g+=1;try{if(s){const D=new Error("Previous login is still completing. Reload before reconnecting.");throw D.name="SolidSessionPendingError",D}if(d)throw new Error("Solid session runtime is disposed");await e.login(re)}catch(D){throw v(snapshotFromSessionError(D,e.info)),D}finally{g-=1}},async logout(re){b+=1,w(),g+=1;try{await e.logout(re),v({status:"anonymous"})}catch(D){throw v(snapshotFromSessionError(D,e.info)),D}finally{g-=1}},subscribe(re){return t.add(re),()=>{t.delete(re)}},dispose(){clearTimeout(o),b+=1,w(),d=!0,a?.(),a=void 0,t.clear(),e.events.off(EVENTS.LOGIN,_),e.events.off(EVENTS.SESSION_RESTORED,_),e.events.off(EVENTS.LOGOUT,T),e.events.off(EVENTS.SESSION_EXPIRED,C),$.off(EVENTS.ERROR,U)}}}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 r;try{r=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(r===e)return e;e=r}return e}function matchesAllowedPrefix(n,e){return e.some(t=>{if(t==="/")return n.startsWith("/");const r=t.endsWith("/")?t.slice(0,-1):t;return n===r||n.startsWith(`${r}/`)})}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(),r=decodeForValidation$1(t),i=r.split(/[?#]/,1)[0];if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||r.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(r)||r.startsWith("//")||i.split("/").some(s=>s==="..")||!matchesAllowedPrefix(i,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 r of Object.keys(e))if(RESERVED_AUTHORIZATION_PARAMETERS.has(r.toLowerCase()))throw new TypeError(`authorizationParameters cannot override ${r}`)}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,r=new Map,i=new Map,s=new Map,o=new Map,a=new Map,u=(d,f)=>{const m=validateWebId(d);if(f!==void 0){const S=normalizePodUrl(f),w=compositeKey(d,S);nextGeneration(a,w),s.get(w)?.controller.abort(),s.delete(w),r.delete(w);const v=t.get(m);v&&compositeKey(v.webId,v.podUrl)===w&&t.delete(m);return}nextGeneration(o,m),i.get(m)?.controller.abort(),i.delete(m);const g=t.get(m);g&&r.delete(compositeKey(g.webId,g.podUrl)),t.delete(m);const b=`${m}${KEY_SEPARATOR}`;for(const S of[...r.keys()])S.startsWith(b)&&r.delete(S);for(const[S,w]of[...s.entries()])S.startsWith(b)&&(nextGeneration(a,S),w.controller.abort(),s.delete(S))},c=d=>{if(d===void 0){t.clear(),r.clear();for(const f of i.values())f.controller.abort();for(const f of s.values())f.controller.abort();i.clear(),s.clear();for(const f of o.keys())nextGeneration(o,f);for(const f of a.keys())nextGeneration(a,f);return}if(typeof d=="string"){u(d);return}u(d.webId,d.podUrl)};return{open(d){const f=validateWebId(d.webId),m=d.podUrl===void 0?void 0:normalizePodUrl(d.podUrl);if(m!==void 0){const U=compositeKey(d.webId,m),$=r.get(U);if($)return Promise.resolve($);const W=s.get(U);if(W)return W.promise;const re=a.get(U)??0;a.set(U,re);const D=new AbortController,V=()=>!D.signal.aborted&&(a.get(U)??0)===re,he=()=>{if(!V())throw createAbortedOpenError()},z=l({webId:d.webId,podUrl:m,fetch:d.fetch,signal:D.signal,isCurrent:V,assertCurrent:he});s.set(U,{generation:re,promise:z,controller:D});const _e=()=>{const Ce=s.get(U);Ce?.generation===re&&Ce.promise===z&&s.delete(U)};return z.then(_e,_e),z}const g=t.get(f);if(g)return Promise.resolve(g);const b=i.get(f);if(b)return b.promise;const S=o.get(f)??0;o.set(f,S);const w=new AbortController,v=()=>!w.signal.aborted&&(o.get(f)??0)===S,_=()=>{if(!v())throw createAbortedOpenError()},T=(async()=>{const U=await e.discoverPod({webId:d.webId,fetch:d.fetch,signal:w.signal,isCurrent:v});return _(),l({webId:d.webId,podUrl:normalizePodUrl(U),fetch:d.fetch,signal:w.signal,isCurrent:v,assertCurrent:_,generation:S,webIdKey:f,discovered:!0})})();i.set(f,{generation:S,promise:T,controller:w});const C=()=>{const U=i.get(f);U?.generation===S&&U.promise===T&&i.delete(f)};return T.then(C,C),T},clear:c,dispose(){c()}};async function l(d){const f=compositeKey(d.webId,d.podUrl),m=r.get(f);if(m)return d.discovered&&d.webIdKey&&d.isCurrent()&&t.set(d.webIdKey,m),m;const g=await e.openDatabase({webId:d.webId,podUrl:d.podUrl,fetch:d.fetch,signal:d.signal,isCurrent:d.isCurrent});d.assertCurrent(),await e.hydrateCollections({webId:d.webId,podUrl:d.podUrl,database:g,signal:d.signal,isCurrent:d.isCurrent}),d.assertCurrent();const b={webId:d.webId,podUrl:d.podUrl,database:g,collections:"ready"};return d.isCurrent()&&(r.set(f,b),d.discovered&&d.webIdKey&&t.set(d.webIdKey,b)),b}}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,RDF.type,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;RDF.type,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;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.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),lastFailureCode:string$2("lastFailureCode").predicate(UDFS.lastFailureCode),lastFailureAt:timestamp("lastFailureAt").predicate(UDFS.lastFailureAt),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 r=normalizePodDataResourceId(e).match(/^chat\/(.+)\/index\.ttl#this$/);return r?.[1]?`chat/${r[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 r=t.match(/^task\/index\.ttl#([^#/]+)$/);if(r?.[1])return`task/${r[1]}`;const i=t.match(/^task\/(.+)\.ttl(?:#[^#/]+)?$/);return i?.[1]?`task/${i[1]}`:null}function issueDir(n){const e=typeof n?.issue=="string"?n.issue:void 0;if(!e)return null;const r=normalizePodDataResourceId(e).match(/^issues\/(.+)\.ttl(?:#[^#/]+)?$/);return r?.[1]?`issues/${r[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),dueAt:timestamp("dueAt").predicate(UDFS.dueAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),notes:text("notes").predicate(DCTerms.description),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"),r=workflowOwnerDir(e)??"reports";return renderDefaultIdTemplate(`${r}/{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.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:r,sourceModule:i,extractor:s}=e,o=t["@id"]||t.id;if(!o){console.warn("[StarredSync] Cannot create favorite: missing target URI");return}const a=s.getTitle(t),u={id:crypto.randomUUID(),targetType:r,target:o,title:a,snapshotContent:s.getContent?.(t),snapshotAuthor:s.getAuthor?.(t),sourceModule:i,searchText:s.getSearchText?.(t)??a,snapshotMeta:s.getSnapshotMeta?.(t),favoredAt:new Date,updatedAt:new Date};try{getDbInstance()||console.warn("[StarredSync] No db instance registered")}catch(c){console.error("[StarredSync] Failed to create favorite:",c)}}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,r)=>{if(!("starred"in r))return;const i=t.starred,s=t["@id"]||t.id;i?await createFavorite(e,n,t):await deleteFavorite(e,s)}}}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.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});const inboxNotificationResource=podTable("inbox_notification",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF.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=i=>{};function e(i){}n.assertIs=e;function t(i){throw new Error}n.assertNever=t,n.arrayToEnum=i=>{const s={};for(const o of i)s[o]=o;return s},n.getValidEnumValues=i=>{const s=n.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(const a of s)o[a]=i[a];return n.objectValues(o)},n.objectValues=i=>n.objectKeys(i).map(function(s){return i[s]}),n.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const s=[];for(const o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},n.find=(i,s)=>{for(const o of i)if(s(o))return o},n.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}n.joinValues=r,n.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(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=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};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(s){return s.message},r={_errors:[]},i=s=>{for(const o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let a=r,u=0;for(;u<o.path.length;){const c=o.path[u];u===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return i(this),r}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={},r=[];for(const i of this.issues)if(i.path.length>0){const s=i.path[0];t[s]=t[s]||[],t[s].push(e(i))}else r.push(e(i));return{formErrors:r,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:r,issueData:i}=n,s=[...t,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="";const u=r.filter(c=>!!c).slice().reverse();for(const c of u)a=c(o,{data:e,defaultError:a}).message;return{...i,path:s,message:a}};function addIssueToContext(n,e){const t=getErrorMap(),r=makeIssue({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===errorMap?void 0:errorMap].filter(i=>!!i)});n.common.issues.push(r)}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 r=[];for(const i of t){if(i.status==="aborted")return INVALID;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const i of t){const s=await i.key,o=await i.value;r.push({key:s,value:o})}return ParseStatus.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const i of t){const{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return INVALID;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(r[s.value]=o.value)}return{status:e.value,value:r}}}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,r,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=i}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:r,description:i}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,a)=>{const{message:u}=n;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??r??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:i}}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 r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parseSync({data:e,path:r.path,parent:r});return handleResult(r,i)}"~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 r=this._parseSync({data:e,path:[],parent:t});return isValid(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>isValid(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parse({data:e,path:r.path,parent:r}),s=await(isAsync(i)?i:Promise.resolve(i));return handleResult(r,s)}refine(e,t){const r=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,s)=>{const o=e(i),a=()=>s.addIssue({code:ZodIssueCode.custom,...r(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((r,i)=>e(r)?!0:(i.addIssue(typeof t=="function"?t(r,i):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 r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.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 s=this._getOrReturnCtx(e);return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:s.parsedType}),INVALID}const r=new ParseStatus;let i;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const o=e.data.length>s.value,a=e.data.length<s.value;(o||a)&&(i=this._getOrReturnCtx(e,i),o?addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")emailRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"email",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"emoji",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")uuidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"uuid",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")nanoidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")cuidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cuid",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")cuid2Regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")ulidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"ulid",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"url",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"regex",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?datetimeRegex(s).test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?dateRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?timeRegex(s).test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?durationRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"duration",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?isValidIP(e.data,s.version)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"ip",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?isValidJWT(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"jwt",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?isValidCidr(e.data,s.version)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cidr",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?base64Regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"base64",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?base64urlRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"base64url",code:ZodIssueCode.invalid_string,message:s.message}),r.dirty()):util.assertNever(s);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(i=>e.test(i),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(r)})}_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,r=(e.toString().split(".")[1]||"").length,i=t>r?t:r,s=Number.parseInt(n.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}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 s=this._getOrReturnCtx(e);return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:s.parsedType}),INVALID}let r;const i=new ParseStatus;for(const s of this._def.checks)s.kind==="int"?util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?floatSafeRemainder(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.not_finite,message:s.message}),i.dirty()):util.assertNever(s);return{status:i.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,r,i){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:errorUtil.toString(i)}]})}_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 r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.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 r;const i=new ParseStatus;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):util.assertNever(s);return{status:i.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,r,i){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:errorUtil.toString(i)}]})}_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 r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:r.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 s=this._getOrReturnCtx(e);return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:s.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return addIssueToContext(s,{code:ZodIssueCode.invalid_date}),INVALID}const r=new ParseStatus;let i;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):util.assertNever(s);return{status:r.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 r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:r.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 r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:r.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 r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:r.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 r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:r.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:r}=this._processInputParams(e),i=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(i.exactLength!==null){const o=t.data.length>i.exactLength.value,a=t.data.length<i.exactLength.value;(o||a)&&(addIssueToContext(t,{code:o?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:a?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&t.data.length<i.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&t.data.length>i.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>i.type._parseAsync(new ParseInputLazyPath(t,o,t.path,a)))).then(o=>ParseStatus.mergeArray(r,o));const s=[...t.data].map((o,a)=>i.type._parseSync(new ParseInputLazyPath(t,o,t.path,a)));return ParseStatus.mergeArray(r,s)}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 r=n.shape[t];e[t]=ZodOptional.create(deepPartialify(r))}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 c=this._getOrReturnCtx(e);return addIssueToContext(c,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:c.parsedType}),INVALID}const{status:r,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const c in i.data)o.includes(c)||a.push(c);const u=[];for(const c of o){const l=s[c],d=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new ParseInputLazyPath(i,d,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof ZodNever){const c=this._def.unknownKeys;if(c==="passthrough")for(const l of a)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")a.length>0&&(addIssueToContext(i,{code:ZodIssueCode.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const l of a){const d=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new ParseInputLazyPath(i,d,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const c=[];for(const l of u){const d=await l.key,f=await l.value;c.push({key:d,value:f,alwaysSet:l.alwaysSet})}return c}).then(c=>ParseStatus.mergeObjectSync(r,c)):ParseStatus.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{const i=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??i}:{message:i}}}:{}})}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 r of util.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const r of util.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const r of util.objectKeys(this.shape)){const i=this.shape[r];e&&!e[r]?t[r]=i:t[r]=i.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const r of util.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof ZodOptional;)s=s._def.innerType;t[r]=s}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),r=this._def.options;function i(s){for(const a of s)if(a.result.status==="valid")return a.result;for(const a of s)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;const o=s.map(a=>new ZodError(a.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:o}),INVALID}if(t.common.async)return Promise.all(r.map(async s=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(i);{let s;const o=[];for(const u of r){const c={...t,common:{...t.common,issues:[]},parent:null},l=u._parseSync({data:t.data,path:t.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;const a=o.map(u=>new ZodError(u));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:a}),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),r=getParsedType(e);if(n===e)return{valid:!0,data:n};if(t===ZodParsedType.object&&r===ZodParsedType.object){const i=util.objectKeys(e),s=util.objectKeys(n).filter(a=>i.indexOf(a)!==-1),o={...n,...e};for(const a of s){const u=mergeValues(n[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===ZodParsedType.array&&r===ZodParsedType.array){if(n.length!==e.length)return{valid:!1};const i=[];for(let s=0;s<n.length;s++){const o=n[s],a=e[s],u=mergeValues(o,a);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return t===ZodParsedType.date&&r===ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),i=(s,o)=>{if(isAborted(s)||isAborted(o))return INVALID;const a=mergeValues(s.value,o.value);return a.valid?((isDirty(s)||isDirty(o))&&t.dirty(),{status:t.value,value:a.data}):(addIssueToContext(r,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}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:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(r.data.length<this._def.items.length)return addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&r.data.length>this._def.items.length&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((o,a)=>{const u=this._def.items[a]||this._def.rest;return u?u._parse(new ParseInputLazyPath(r,o,r.path,a)):null}).filter(o=>!!o);return r.common.async?Promise.all(s).then(o=>ParseStatus.mergeArray(t,o)):ParseStatus.mergeArray(t,s)}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:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.object)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:r.parsedType}),INVALID;const i=[],s=this._def.keyType,o=this._def.valueType;for(const a in r.data)i.push({key:s._parse(new ParseInputLazyPath(r,a,r.path,a)),value:o._parse(new ParseInputLazyPath(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ParseStatus.mergeObjectAsync(t,i):ParseStatus.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(r)}):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:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.map)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:r.parsedType}),INVALID;const i=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([a,u],c)=>({key:i._parse(new ParseInputLazyPath(r,a,r.path,[c,"key"])),value:s._parse(new ParseInputLazyPath(r,u,r.path,[c,"value"]))}));if(r.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const u of o){const c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return INVALID;(c.status==="dirty"||l.status==="dirty")&&t.dirty(),a.set(c.value,l.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const u of o){const c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return INVALID;(c.status==="dirty"||l.status==="dirty")&&t.dirty(),a.set(c.value,l.value)}return{status:t.value,value:a}}}}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:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.set)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:r.parsedType}),INVALID;const i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());const s=this._def.valueType;function o(u){const c=new Set;for(const l of u){if(l.status==="aborted")return INVALID;l.status==="dirty"&&t.dirty(),c.add(l.value)}return{status:t.value,value:c}}const a=[...r.data.values()].map((u,c)=>s._parse(new ParseInputLazyPath(r,u,r.path,c)));return r.common.async?Promise.all(a).then(u=>o(u)):o(a)}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),r=this._def.values;return addIssueToContext(t,{expected:util.joinValues(r),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),r=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:r}),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(r=>!e.includes(r)),{...this._def,...t})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ZodParsedType.string&&r.parsedType!==ZodParsedType.number){const i=util.objectValues(t);return addIssueToContext(r,{expected:util.joinValues(i),received:r.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const i=util.objectValues(t);return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_enum_value,options:i}),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 r=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(r.then(i=>this._def.type.parseAsync(i,{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:r}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:o=>{addIssueToContext(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){const o=i.transform(r.data,s);if(r.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return INVALID;const u=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return u.status==="aborted"?INVALID:u.status==="dirty"||t.value==="dirty"?DIRTY(u.value):u});{if(t.value==="aborted")return INVALID;const a=this._def.schema._parseSync({data:o,path:r.path,parent:r});return a.status==="aborted"?INVALID:a.status==="dirty"||t.value==="dirty"?DIRTY(a.value):a}}if(i.type==="refinement"){const o=a=>{const u=i.refinement(a,s);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(i.type==="transform")if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!isValid(o))return INVALID;const a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>isValid(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:t.value,value:a})):INVALID);util.assertNever(i)}}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 r=t.data;return t.parsedType===ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,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),r={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return isAsync(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ZodError(r.common.issues)},input:r.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 r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:r.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),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?INVALID:s.status==="dirty"?(t.dirty(),DIRTY(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?INVALID:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}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),r=i=>(isValid(i)&&(i.value=Object.freeze(i.value)),i);return isAsync(t)?t.then(i=>r(i)):r(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.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},modelClassAliases={chat:"chat",language:"chat",embedding:"embedding",embeddings:"embedding",document_understanding:"document_understanding",rerank:"reranking",reranker:"reranking",reranking:"reranking",image:"image_generation",image_generation:"image_generation",transcription:"speech_recognition",speech_recognition:"speech_recognition",text_to_speech:"speech_synthesis",speech_synthesis:"speech_synthesis",video:"video_generation",video_generation:"video_generation"},AI_MODEL_CLASS_DEFAULT_CAPABILITY={[AI_MODEL_CLASS.chat]:AI_MODEL_CAPABILITY.chat,[AI_MODEL_CLASS.embedding]:AI_MODEL_CAPABILITY.embedding,[AI_MODEL_CLASS.document_understanding]:AI_MODEL_CAPABILITY.document_understanding,[AI_MODEL_CLASS.reranking]:AI_MODEL_CAPABILITY.reranking,[AI_MODEL_CLASS.image_generation]:AI_MODEL_CAPABILITY.image_generation,[AI_MODEL_CLASS.speech_recognition]:AI_MODEL_CAPABILITY.speech_recognition,[AI_MODEL_CLASS.speech_synthesis]:AI_MODEL_CAPABILITY.speech_synthesis,[AI_MODEL_CLASS.video_generation]:AI_MODEL_CAPABILITY.video_generation};new Set(AI_MODEL_MODALITIES);const capabilitySet=new Set(AI_MODEL_CAPABILITIES),capabilityUriSet=new Set(Object.values(AI_MODEL_CAPABILITY)),capabilityNameByUri=new Map(Object.entries(AI_MODEL_CAPABILITY).map(([n,e])=>[e,n]));new Map(Object.entries(AI_MODEL_CLASS).map(([n,e])=>[e,n]));const legacyCapabilityAliases={function_calling:"tool_call",function_call:"tool_call",rerank:"reranking",document:"document_understanding","document-parse":"document_understanding"};function toAIModelClassUri(n){if(n==null)return AI_MODEL_CLASS.chat;if(typeof n=="string"&&Object.values(AI_MODEL_CLASS).includes(n))return n;const e=typeof n=="string"?modelClassAliases[n.trim().toLowerCase()]:void 0;return e?AI_MODEL_CLASS[e]:void 0}function isAIModelCapability(n){return typeof n=="string"&&capabilitySet.has(n)}function isAIModelCapabilityUri(n){return typeof n=="string"&&capabilityUriSet.has(n)}function toAIModelCapabilityUri(n){if(isAIModelCapabilityUri(n))return n;if(typeof n!="string")return;const e=legacyCapabilityAliases[n]??n;return isAIModelCapability(e)?AI_MODEL_CAPABILITY[e]:void 0}function toAIModelCapabilityName(n){return typeof n=="string"?capabilityNameByUri.get(n):void 0}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 r of Object.values(t??{}))typeof r.options?.predicate=="string"&&(r.getPredicate=()=>r.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(/\/$/,""),r=t.split("/").pop()||t;return r.endsWith(".ttl")?r.slice(0,-4):r}function aiConfigResourceRefToModelId(n,e){return normalizeAIConfigModelId(n,e)}function normalizeAIConfigModelId(n,e){const t=normalizeAIConfigResourceId(n);if(!t.includes("/"))return t;const[r,...i]=t.split("/");return i.length===0||!e?t:normalizeAIConfigProviderId(r)===normalizeAIConfigProviderId(e)?i.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),r=normalizeAIConfigModelStorageId(e,t);return t&&r?`settings/providers/${buildAIConfigModelStorageId(t,r)}`:r}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."},lastFailureCode:{type:"string",predicate:UDFS.lastFailureCode,description:"Stable credential failure category. No upstream response body or secret."},lastFailureAt:{type:"timestamp",predicate:UDFS.lastFailureAt,description:"Time when the most recent credential failure was observed."},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","lastFailureCode","lastFailureAt","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.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.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."},dueAt:{type:"timestamp",predicate:UDFS.dueAt,description:"Deadline, independent of execution scheduling."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Time the task was completed."},notes:{type:"text",predicate:DCTerms.description,description:"User notes about the task."},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","dueAt","completedAt","notes","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(r=>!(t.source&&r.source!==t.source||t.resourceKind&&r.resourceKind!==t.resourceKind))},describe(t){return e.get(t)??null}}}createPodSchema();function createPodSchema(n=createPodModelDescriptorRegistry()){const e=(t={})=>{const r=t.uri??t.schemaUri;if(!r)return n.list();const i=n.describe(r);return i?[i]:[]};return{list:n.list,describe(t){const r=typeof t=="string"?t:"uri"in t?t.uri:t.schemaUri;return n.describe(r)},classes(t={}){return e(t).map(r=>({schemaUri:r.uri,resourceKind:r.resourceKind,class:r.class,namespace:r.namespace,source:r.source,trustLevel:r.trustLevel,description:r.description}))},search(t){const r=normalizeSearchTerms(t.query);return r.length===0?[]:n.list({source:t.source,resourceKind:t.resourceKind}).map(i=>scoreDescriptorSearch(i,r)).filter(i=>i!==null).sort((i,s)=>s.score-i.score||i.uri.localeCompare(s.uri)).slice(0,Math.max(1,t.limit??10))},predicates(t={}){return e(t).flatMap(r=>Object.entries(r.fields).filter(([i])=>!t.field||i===t.field).map(([i,s])=>({schemaUri:r.uri,field:i,predicate:s.predicate,type:s.type,required:!!s.required,secret:!!s.secret,array:!!s.array,description:s.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 r=0;const i=(s,o,a)=>{if(!o)return;const u=o.toLowerCase();for(const c of e)u.includes(c)&&(t.add(s),r+=a)};i("uri",n.uri,10),i("class",n.class,10),i("namespace",n.namespace,4),i("resourceKind",n.resourceKind,8),i("description",n.description,4),i("storage",`${n.storage.base}${n.storage.resourceIdPattern}`,3);for(const[s,o]of Object.entries(n.fields))i(`field:${s}`,s,6),i(`predicate:${s}`,o.predicate,6),i(`description:${s}`,o.description,3);for(const s of n.examples){i("example",s.request,3);for(const[o,a]of Object.entries(s.match))i(`example:${o}`,String(a),3)}return r<=0?null:{uri:n.uri,resourceKind:n.resourceKind,class:n.class,namespace:n.namespace,source:n.source,trustLevel:n.trustLevel,description:n.description,score:r,matchedFields:[...t].sort()}}async function filterWebIdsByStorageRoot(n,e,t){const r=normalizeStorageRoot(t);if(!r)return[];const i=Array.from(new Set(e.filter(o=>typeof o=="string"&&o.length>0)));return(await Promise.all(i.map(async o=>{const u=(await fetchProfileStorageUrls(n,o)).find(c=>storageUrlBelongsToRoot(c,r));return u?{webId:o,storageUrl:ensureTrailingSlash$1(u)}:void 0}))).filter(o=>!!o)}function storageUrlBelongsToRoot(n,e){const t=normalizeStorageUrl(n),r=normalizeStorageRoot(e);return!!(t&&r&&t.startsWith(r))}function normalizeStorageRoot(n){if(n)try{return ensureTrailingSlash$1(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 r=t.headers?.get?.("content-type")??"",i=await t.text().catch(()=>"");if(!i)return[];if(r.includes("json"))try{return uniqueNormalizedStorageUrls(extractStorageUrlsFromJson(JSON.parse(i)))}catch{return[]}return uniqueNormalizedStorageUrls(extractStorageUrlsFromTurtle(i))}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,r=(i,s=!1)=>{if(typeof i=="string"){s&&e.add(i);return}if(!(!i||typeof i!="object")&&!t.has(i)){if(t.add(i),Array.isArray(i)){for(const o of i)r(o,s);return}for(const[o,a]of Object.entries(i)){const u=SOLID_STORAGE_KEYS.has(o);if(s&&o==="@id"){r(a,!0);continue}r(a,s||u)}}};return r(n),Array.from(e)}function normalizeStorageUrl(n){try{return ensureTrailingSlash$1(new URL(n).toString())}catch{return}}function uniqueNormalizedStorageUrls(n){const e=new Set;for(const t of n){const r=normalizeStorageUrl(t);r&&e.add(r)}return Array.from(e)}function ensureTrailingSlash$1(n){return n.replace(/\/+$/u,"")+"/"}const XPOD_RETURN_PATH_PREFIXES=["/dashboard","/status","/network","/settings","/ai-config","/ai-connections","/tasks","/pod","/device","/inbox","/notifications"],desktopPages=new Set(["/tasks","/pod","/pod/models","/pod/search","/pod/apps","/pod/data","/device","/device/network","/device/services","/device/runtime","/device/logs","/inbox","/notifications"]);function isXpodProductPath(n){const e=n.replace(/\/$/u,"");return desktopPages.has(e)?!0:XPOD_RETURN_PATH_PREFIXES.slice(0,6).some(t=>e===t||e.startsWith(`${t}/`))}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),r=t.split(/[?#]/,1)[0];if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||t.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(t)||t.startsWith("//")||r.split("/").some(i=>i==="..")||!isXpodProductPath(r))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 r;try{r=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(r===e)return e;e=r}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),r=new URL(e).origin,i=new URL(t.identityProvider.url).origin,s=t.storageProvider?new URL(t.storageProvider.url).origin:void 0;if(t.id!==XPOD_LOGIN_ROUTE_ID||i!==r||s!==r||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:r},storageProvider:t.storageProvider?{...t.storageProvider,url:r}: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 ORIGIN_PRIORITY={loopback:10,lan:20,"public-direct":30};async function currentHostLocalPodRoutes(n,e,t={}){if(typeof window>"u")return[];const r=await fetchCurrentProvisionRouteStatus(e,t);return provisionLocalPodRoutes(n,r)}function provisionLocalPodRoutes(n,e,t=typeof window>"u"?"":window.location.href){const r=safeUrl(t);if(!r||!n)return[];if(e.managed===!0&&e.storageRoot&&e.oidcIssuer&&safeUrl(e.storageRoot)?.origin===safeUrl(e.oidcIssuer)?.origin)return[];const i=currentOriginRoute(n,e,r);return[...i?[i]:[],...advertisedRoutes(n,e)].sort((s,o)=>s.priority-o.priority||s.id.localeCompare(o.id))}function currentOriginRoute(n,e,t){const r=safeUrl(n);if(!r||!["http:","https:"].includes(r.protocol)||r.username||r.password||!podBelongsToCurrentHost(n,e))return;const i=safeUrl(e.storageRoot??"")??r;if(i.origin===t.origin)return;const s=currentOriginKind(t);return{id:`${s}-current-origin`,kind:s,canonicalUrl:`${i.origin}/`,targetUrl:`${t.origin}/`,priority:ORIGIN_PRIORITY[s],requiresManagedClient:s!=="public-direct",visibility:s==="loopback"?"local-only":"same-account",health:"healthy"}}function podBelongsToCurrentHost(n,e){return typeof window<"u"&&window.xpodDesktop?!0:e.managed!==!0||typeof e.storageRoot!="string"?!1:coveredByStorageRoot(n,e.storageRoot)}function coveredByStorageRoot(n,e){const t=safeUrl(e),r=safeUrl(n);return!t||!r?!1:r.origin===t.origin||r.href.startsWith(ensureTrailingSlash(t.href))}function advertisedRoutes(n,e){const t=safeUrl(n);if(!t)return[];const r=`${(safeUrl(e.storageRoot??"")??t).origin}/`;return(e.routes??[]).flatMap(i=>{const s=safeUrl(i.targetUrl);return!s||!["http:","https:"].includes(s.protocol)?[]:[{id:i.id,kind:i.kind,canonicalUrl:r,targetUrl:`${s.origin}/`,priority:i.priority,requiresManagedClient:i.requiresManagedClient??!0,visibility:i.visibility??"public",health:i.health??"unknown"}]})}function currentOriginKind(n){return isLoopbackHostname(n.hostname)?"loopback":isPrivateNetworkHostname(n.hostname)?"lan":"public-direct"}function isLoopbackHostname(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}function isPrivateNetworkHostname(n){const e=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u.exec(n);if(!e)return n.endsWith(".local");const t=Number(e[1]),r=Number(e[2]);return t===10||t===192&&r===168?!0:t===172&&r>=16&&r<=31}async function fetchCurrentProvisionRouteStatus(n,e={}){return typeof window>"u"||window.location.origin==="null"?{}:await probeSolidLocalRouteStatus({fetch:n,url:new URL("/provision/status",window.location.origin).href,signal:e.signal,read:async r=>{if(!r.ok||!r.headers.get("content-type")?.includes("application/json")){await r.arrayBuffer().catch(()=>{});return}const i=await r.json().catch(()=>{});return{managed:i?.managed===!0,storageRoot:typeof i?.publicUrl=="string"?i.publicUrl:void 0,routes:normalizeAdvertisedAccessRoutes(i?.routes)}}})??{}}function normalizeAdvertisedAccessRoutes(n){return Array.isArray(n)?n.flatMap(e=>{if(!e||typeof e!="object")return[];const t=e;return typeof t.targetUrl!="string"||typeof t.kind!="string"?[]:typeof t.priority!="number"||!Number.isFinite(t.priority)?[]:[{id:typeof t.id=="string"&&t.id?t.id:`${t.kind}-${t.targetUrl}`,kind:t.kind,targetUrl:t.targetUrl,priority:t.priority,...typeof t.requiresManagedClient=="boolean"?{requiresManagedClient:t.requiresManagedClient}:{},...typeof t.visibility=="string"?{visibility:t.visibility}:{},...typeof t.health=="string"?{health:t.health}:{}}]}):[]}function safeUrl(n){try{return new URL(n)}catch{return}}function ensureTrailingSlash(n){return n.endsWith("/")?n:`${n}/`}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$1(new URL(t.at(0)).toString())}function createXpodSolidRuntimeValue(n={}){const e=createXpodSolidRuntimeStoragePolicy(n.storage);let t=[],r,i;const s=createSolidAccessRouteFetch({fetch:globalThis.fetch,routes:()=>t,refreshRoutes:async()=>{await i?.()},allowLocalOnlyRoutes:!0,managedClient:!0}),o=n.sessionFactory?.({fetch:s})??createInruptSession(e.oidcSession,s);let a=readStoredOidcIssuer(e.issuer),u,c=0;const l=createSolidSessionRuntime({session:{get info(){return o.info},events:o.events,fetch:(m,g)=>g===void 0?o.fetch(m):o.fetch(m,g),login:m=>(c+=1,o.login(m)),logout:m=>(c+=1,o.logout(m)),handleIncomingRedirect:async m=>{const g=++c,b=typeof window>"u"?"http://localhost":window.location.origin,S=await resolveXpodLoginContext(b,globalThis.fetch);if(g!==c)throw new Error("Solid session changed during authority discovery");if(u=S.oidcIssuer,!u)throw new Error("暂时无法确认本机登录信息,请稍后重试。");if(r=S.provisionRouteStatus,t=r?provisionLocalPodRoutes(r.storageRoot,r):[],typeof m!="string"&&m?.restorePreviousSession){const w=new URL(m.url??window.location.href);if(!w.searchParams.has("code")||!w.searchParams.has("state"))return o.handleIncomingRedirect({...m,restorePreviousSession:readActiveRestoreIssuer(e.oidcSession)===u})}return o.handleIncomingRedirect(m)}}}),d={...l,dispose:()=>{c+=1,l.dispose()}},f=createPodRuntime({adapter:{discoverPod:discoverPodUrlFromWebId,openDatabase:({podUrl:m,fetch:g})=>drizzle({get info(){return o.info},fetch:g},{podUrl:m,schema:{aiProvider:aiProviderResource,credential:credentialResource},resourcePreparation:"off"}),hydrateCollections:()=>{}}});return{session:d,pod:f,storage:e,transportFetch:s,getIssuer:()=>readIssuerFromSessionInfo(o.info)??a??readStoredOidcIssuer(e.issuer),getProvisionRouteStatus:()=>r,getExpectedIssuer:()=>u,setIssuer:m=>{const g=normalizeXpodOidcIssuer(m);a=g,g&&writeStoredOidcIssuer(g,e.issuer)},setLocalPodRoutes:m=>{t=m?[...m]:[],m===void 0&&(r=void 0)},setLocalPodRoutesRefresh:m=>{i=m},resolveLocalUrl:m=>resolveSolidLocalRouteUrl(m,t.map(toLocalRoute))?.href??m}}function toLocalRoute(n){return{canonicalBaseUrl:n.canonicalUrl,localBaseUrl:n.targetUrl}}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=r=>inruptStorageKey(e,r);return{get:async r=>n.getItem(t(r))??void 0,set:async(r,i)=>{n.setItem(t(r),i)},delete:async r=>{n.removeItem(t(r))}}}function inruptStorageKey(n,e){return`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${n}:${e}`}function readActiveRestoreIssuer(n){try{const e=getOptionalPersistentStorage()?.getItem("solidClientAuthenticationUser:currentSession");if(!e)return;const t=n?.getItem(inruptStorageKey("insecure",`solidClientAuthenticationUser:${e}`));return t?normalizeXpodOidcIssuer(JSON.parse(t).issuer):void 0}catch{return}}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=new AbortController;let r;const i=new Promise((s,o)=>{r=setTimeout(()=>{t.abort(),o(new Error("暂时无法确认本机登录信息,请稍后重试。"))},5e3)});try{const s=await Promise.race([e("/provision/status",{headers:{Accept:"application/json"},credentials:"include",signal:t.signal}).catch(()=>{}),i]);if(s?.status===404)return{oidcIssuer:normalizeXpodOidcIssuer(n)};const o=s?.ok?await Promise.race([s.json().catch(()=>{}),i]):void 0,a=normalizeXpodOidcIssuer(o?.oidcIssuer),u=normalizeXpodOidcIssuer(o?.publicUrl),c=u?{provisionRouteStatus:{managed:o?.managed===!0,storageRoot:u,oidcIssuer:a,routes:normalizeAdvertisedAccessRoutes(o?.routes)}}:{};if(o?.managed===!1)return{oidcIssuer:a??normalizeXpodOidcIssuer(n),...c};const l=typeof o?.provisionCode=="string"&&o.provisionCode.trim()?o.provisionCode.trim():void 0;if(!a||o?.managed===!0&&!l)throw new Error("暂时无法确认本机登录信息,请稍后重试。");return{oidcIssuer:a,provisionCode:l,...c}}finally{clearTimeout(r)}}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),r=assertXpodLoginRoute(t.route,e),i=normalizeXpodReturnTo(t.returnTo);return{...t,route:r,authorizationSurface:"redirect",discovery:"strict",...i===void 0?{}:{returnTo:i}}}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 r=normalizeXpodOidcIssuer(e),i=normalizeXpodOidcIssuer(t);return!r||!i||r!==i?!1:isHttpResourceUrl(n.webId)}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{}}function hasInvalidWebIdWhitespace(n){return n!==n.trim()||/[\r\n\t]/.test(n)}const 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",XPOD_ACCOUNT_REMEMBER_CHOICE_KEY="xpod.account-remember-choice.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 r=normalizeRememberedXpodLogin(JSON.parse(t),n.origin??currentOrigin());return r||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),r}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(n,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const r=normalizeRememberedXpodLogin(n,e.origin??currentOrigin());if(r)try{t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(r));const i=r.issuer??normalizedIssuer(e.origin??currentOrigin()??"");return clearPendingEmailForIssuer(t,i),clearPendingEmailForIssuer(optionalTemporaryStorage(),i),r}catch{return}}function clearRememberedXpodLogin(n=optionalPersistentStorage()){for(const e of[n,optionalTemporaryStorage()])try{e?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),e?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),e?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(n,e){if(!n||!e.webId||!e.selectedStorage)return!1;const t=validatedWebId(n.webId),r=validatedWebId(n.storageBinding.webId),i=normalizedUrl(n.storageBinding.storageUrl,!0),s=validatedWebId(e.webId),o=validatedWebId(e.selectedStorage.webId),a=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!r||!i||!s||!o||!a||t!==r||s!==o||t!==s||i!==a?!1:rememberedXpodAccountMatchesActive(n,e)}function rememberedXpodAccountMatchesActive(n,e){return n?matchingOptionalEmail(n.account.email,e.accountEmail):!1}function readXpodAccountRememberChoice(n,e=optionalPersistentStorage()){try{const r=JSON.parse(e?.getItem(XPOD_ACCOUNT_REMEMBER_CHOICE_KEY)??"{}")[normalizedIssuer(n??currentOrigin()??"")];return typeof r=="boolean"?r:void 0}catch{return}}function optionalTemporaryStorage(){try{return typeof window>"u"?void 0:window.sessionStorage}catch{return}}function clearPendingEmailForIssuer(n,e){const t=n?.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);(!t||t===e)&&(n?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY))}function rememberPendingXpodAccountEmail(n,e=optionalPersistentStorage(),t,r=!0,i=optionalTemporaryStorage()){const s=normalizedEmail(n);if(!s)return;const o=normalizedIssuer(t??currentOrigin()??"");try{const a=JSON.parse(e?.getItem(XPOD_ACCOUNT_REMEMBER_CHOICE_KEY)??"{}"),u=a&&typeof a=="object"&&!Array.isArray(a)?a:{};if(e?.setItem(XPOD_ACCOUNT_REMEMBER_CHOICE_KEY,JSON.stringify({...u,[o]:r})),!r){clearPendingEmailForIssuer(e,o);const l=readRememberedXpodLogin({storage:e});(!l?.issuer||l.issuer===o)&&e?.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}const c=r?e:i;return c?(c.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,s),c.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,o),r&&clearPendingEmailForIssuer(i,o),s):void 0}catch{return}}function readPendingXpodAccountEmail(n=optionalPersistentStorage(),e,t=optionalTemporaryStorage()){const r=readXpodAccountRememberChoice(e,n)===!1?t:n;if(r)try{const i=normalizedEmail(r.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const s=r.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!s){r.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),r.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}if(s!==normalizedIssuer(e))return}return i||r.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),i}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.issuer!==void 0&&!normalizedUrl(t.issuer)||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const r=t.account,i=t.storageBinding,s=normalizedEmail(r.email),o=validatedWebId(t.webId),a=validatedWebId(i.webId),u=normalizedUrl(i.storageUrl,!0);if(r.email!==void 0&&!s||!o||!a||!u||o!==a)return;const c=normalizedAvatarUrl(r.avatarUrl,[o,u,e]);return{...typeof t.issuer=="string"?{issuer:normalizedIssuer(t.issuer)}:{},account:{...s?{email:s}:{},...normalizedText(r.id)?{id:normalizedText(r.id)}:{},...normalizedText(r.username)?{username:normalizedText(r.username)}:{},...normalizedText(r.displayName)?{displayName:normalizedText(r.displayName)}:{},...c?{avatarUrl:c}:{}},webId:o,storageBinding:{webId:o,storageUrl:u},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 r=new URL(t).origin;return e.some(i=>{const s=normalizedUrl(i);return s&&new URL(s).origin===r})?t:void 0}function matchingOptionalEmail(n,e){const t=normalizedEmail(n)?.toLowerCase(),r=normalizedEmail(e)?.toLowerCase();return!t||!r||t===r}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}export{createThing as $,AI_MODEL_CLASS_DEFAULT_CAPABILITY as A,aiProviderResource as B,CircleAlert as C,configureSparqlEngine as D,EmailInput as E,FormField as F,aiModelResource as G,getLinkedResourceUrlAll as H,acp as I,internal_cloneResource as J,getSolidDataset as K,LoaderCircle as L,freeze as M,NoUsableAccessRouteError as N,getSourceUrl as O,getResourceInfo as P,getSourceIri as Q,getThingAll as R,getIriAll as S,rdf$2 as T,acl as U,setThing as V,WebAccountLayout as W,XpodDeploymentIdentity as X,setIri as Y,removeIri as Z,removeAll as _,credentialResource as a,isSolidSchema as a$,addIri as a0,removeThing as a1,subjectToRdfJsQuads as a2,DataFactory as a3,getIri as a4,saveSolidDatasetAt as a5,createSolidDataset as a6,foaf as a7,getThing as a8,getUrlAll as a9,ActionButton as aA,primaryButtonClass as aB,textButtonClass as aC,Disclosure as aD,outlineButtonClass as aE,Field as aF,string$2 as aG,podTable as aH,ColumnBuilder as aI,PodArrayColumn as aJ,PodBooleanColumn as aK,PodColumnBase as aL,PodDateTimeColumn as aM,PodIntegerColumn as aN,PodJsonColumn as aO,PodObjectColumn as aP,PodStringColumn as aQ,PodTable as aR,PodUriColumn as aS,SolidSchema as aT,boolean$2 as aU,date$3 as aV,generateNanoId as aW,hasStringValue$2 as aX,hasTermValue as aY,id as aZ,integer$1 as a_,buildThing as aa,Avatar as ab,AvatarImage as ac,AvatarFallback as ad,Check as ae,Tooltip as af,TooltipTrigger as ag,TooltipContent as ah,TooltipProvider as ai,Info as aj,LoaderCircle$1 as ak,requireBuffer as al,requireLink as am,requireBrowser$2 as an,requireSparql as ao,requireEvents as ap,requireBrowser$3 as aq,requireString_decoder as ar,bufferExports as as,resolvePodSignInCopy as at,usePastDelay as au,SourceMark as av,ScreenLayout as aw,PodAvatar as ax,Spinner as ay,formatCopy as az,XpodAuthSurface as b,json as b0,mergeSchemaColumns as b1,object$1 as b2,real as b3,resolveTermIri as b4,solidSchema as b5,text as b6,timestamp as b7,uri as b8,validateColumnOverride as b9,namespaces as bA,pickSolidProfileDisplayName as ba,VCARD as bb,FOAF as bc,readRememberedXpodLogin as bd,rememberedXpodLoginMatchesActive as be,rememberXpodLogin as bf,XPOD_LOGIN_ROUTE_ID as bg,hasInvalidWebIdWhitespace as bh,normalizeWebIdLoginTransaction as bi,isCurrentXpodSessionSnapshot as bj,clearStoredXpodOidcIssuer as bk,fetchCurrentProvisionRouteStatus as bl,currentHostLocalPodRoutes as bm,snapshotToState as bn,normalizeXpodLoginTransaction as bo,resolveXpodLoginContext as bp,withXpodProvisionScope as bq,safeAuthError as br,XpodSolidRuntimeContext as bs,approvalResource as bt,inboxNotificationResource as bu,runResource as bv,taskResource as bw,clearRememberedXpodLogin as bx,createXpodLoginRoute as by,XpodSignInFrame as bz,credentialDescriptor as c,createXpodSolidRuntimeValue as d,assertXpodLoginRoute as e,XPOD_SOLID_SESSION_ID_STORAGE_KEY as f,XPOD_LAST_OIDC_ISSUER_STORAGE_KEY as g,normalizeAdvertisedAccessRoutes as h,filterWebIdsByStorageRoot as i,getXpodSolidRuntimeValue as j,readPendingXpodAccountEmail as k,XpodBlockingAccountCredentialsSurface as l,rememberPendingXpodAccountEmail as m,normalizeXpodReturnTo as n,useXpodSolidRuntimeContext as o,provisionLocalPodRoutes as p,XpodAccountPageSurface as q,readXpodAccountRememberChoice as r,storageUrlBelongsToRoot as s,Checkbox as t,useSize as u,toAIModelCapabilityUri as v,toAIModelCapabilityName as w,toAIModelClassUri as x,aiConfigModelRef as y,AI_MODEL_CLASS as z};
|