@undefineds.co/xpod 0.4.11 → 0.4.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/config/components-ignore.json +5 -1
  2. package/config/notifications.json +68 -0
  3. package/config/xpod.base.json +9 -11
  4. package/dist/ai/service/AiCredentialSecret.d.ts +30 -0
  5. package/dist/ai/service/AiCredentialSecret.js +120 -0
  6. package/dist/ai/service/CredentialReaderImpl.d.ts +18 -0
  7. package/dist/ai/service/CredentialReaderImpl.js +81 -5
  8. package/dist/ai/service/CredentialReaderImpl.jsonld +42 -2
  9. package/dist/ai/service/EmbeddingModelPolicy.d.ts +79 -0
  10. package/dist/ai/service/EmbeddingModelPolicy.js +134 -0
  11. package/dist/ai/service/EmbeddingProviderError.js +6 -0
  12. package/dist/ai/service/EmbeddingServiceImpl.d.ts +13 -1
  13. package/dist/ai/service/EmbeddingServiceImpl.js +18 -5
  14. package/dist/ai/service/EmbeddingServiceImpl.jsonld +35 -0
  15. package/dist/ai/service/index.d.ts +2 -0
  16. package/dist/ai/service/index.js +2 -0
  17. package/dist/api/ai-gateway/connect/index.d.ts +20 -2
  18. package/dist/api/ai-gateway/connect/index.js +162 -16
  19. package/dist/api/ai-gateway/credentials/AiCredentialSecretDecoder.d.ts +12 -0
  20. package/dist/api/ai-gateway/credentials/AiCredentialSecretDecoder.js +30 -0
  21. package/dist/api/ai-gateway/errors.d.ts +1 -1
  22. package/dist/api/ai-gateway/models/GatewayEmbeddingModelCatalog.d.ts +11 -0
  23. package/dist/api/ai-gateway/models/GatewayEmbeddingModelCatalog.js +31 -0
  24. package/dist/api/ai-gateway/models/PodModelSelectionRepository.js +7 -3
  25. package/dist/api/ai-gateway/models/ProviderCustomModelsService.d.ts +18 -0
  26. package/dist/api/ai-gateway/models/ProviderCustomModelsService.js +23 -0
  27. package/dist/api/ai-gateway/models/ProviderModelDiscoveryAdapters.d.ts +3 -1
  28. package/dist/api/ai-gateway/models/ProviderModelDiscoveryAdapters.js +2 -45
  29. package/dist/api/ai-gateway/models/ProviderModelSelectionService.d.ts +10 -0
  30. package/dist/api/ai-gateway/models/ProviderModelSelectionService.js +57 -20
  31. package/dist/api/ai-gateway/models/ProviderModelType.d.ts +28 -0
  32. package/dist/api/ai-gateway/models/ProviderModelType.js +34 -0
  33. package/dist/api/ai-gateway/models/ProviderModelsAdapter.d.ts +10 -0
  34. package/dist/api/ai-gateway/models/ProviderModelsAdapter.js +3 -4
  35. package/dist/api/ai-gateway/models/index.d.ts +1 -0
  36. package/dist/api/ai-gateway/models/index.js +3 -1
  37. package/dist/api/ai-gateway/providers/CustomRuntimeAdapter.d.ts +7 -0
  38. package/dist/api/ai-gateway/providers/CustomRuntimeAdapter.js +9 -2
  39. package/dist/api/ai-gateway/providers/ModelsDevCatalog.d.ts +7 -1
  40. package/dist/api/ai-gateway/providers/ModelsDevCatalog.js +4 -10
  41. package/dist/api/ai-gateway/providers/ProviderRegistry.d.ts +107 -0
  42. package/dist/api/ai-gateway/providers/ProviderRegistry.js +244 -21
  43. package/dist/api/ai-gateway/providers/ProviderRuntimeRegistry.d.ts +5 -0
  44. package/dist/api/ai-gateway/providers/ProviderRuntimeRegistry.js +5 -1
  45. package/dist/api/ai-gateway/quota/SubscriptionQuotaAdapters.d.ts +12 -4
  46. package/dist/api/ai-gateway/quota/SubscriptionQuotaAdapters.js +11 -11
  47. package/dist/api/ai-gateway/routing/ModelRouter.d.ts +14 -0
  48. package/dist/api/ai-gateway/routing/ModelRouter.js +43 -4
  49. package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.d.ts +9 -1
  50. package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.js +3 -27
  51. package/dist/api/chatkit/pod-store.d.ts +31 -0
  52. package/dist/api/chatkit/pod-store.js +132 -8
  53. package/dist/api/container/common.js +24 -4
  54. package/dist/api/container/routes.js +17 -2
  55. package/dist/api/container/types.d.ts +3 -1
  56. package/dist/api/handlers/AdminHandler.d.ts +13 -0
  57. package/dist/api/handlers/AdminHandler.js +47 -18
  58. package/dist/api/handlers/AiConfigHandler.d.ts +6 -0
  59. package/dist/api/handlers/AiConfigHandler.js +28 -0
  60. package/dist/api/handlers/AiGatewayManagementHandler.js +36 -0
  61. package/dist/api/runs/RdfRunContextRetriever.d.ts +14 -0
  62. package/dist/api/runs/RdfRunContextRetriever.js +41 -5
  63. package/dist/api/runtime.js +2 -1
  64. package/dist/cli/commands/secret.d.ts +1 -0
  65. package/dist/cli/commands/secret.js +25 -7
  66. package/dist/components/components.jsonld +3 -1
  67. package/dist/components/context.jsonld +53 -1
  68. package/dist/http/SubgraphSparqlHttpHandler.d.ts +59 -2
  69. package/dist/http/SubgraphSparqlHttpHandler.js +145 -13
  70. package/dist/http/SubgraphSparqlHttpHandler.jsonld +37 -0
  71. package/dist/identity/drizzle/EdgeNodeRepository.d.ts +0 -12
  72. package/dist/identity/drizzle/EdgeNodeRepository.js +5 -13
  73. package/dist/index.d.ts +2 -1
  74. package/dist/index.js +7 -3
  75. package/dist/logging/log-file.d.ts +17 -0
  76. package/dist/logging/log-file.js +69 -0
  77. package/dist/main.js +2 -1
  78. package/dist/notifications/NotificationChannelSweeper.d.ts +50 -0
  79. package/dist/notifications/NotificationChannelSweeper.js +131 -0
  80. package/dist/notifications/NotificationChannelSweeper.jsonld +136 -0
  81. package/dist/notifications/ReclaimingWebSocket2023Storer.d.ts +25 -0
  82. package/dist/notifications/ReclaimingWebSocket2023Storer.js +56 -0
  83. package/dist/notifications/ReclaimingWebSocket2023Storer.jsonld +77 -0
  84. package/dist/notifications/index.d.ts +2 -0
  85. package/dist/notifications/index.js +2 -0
  86. package/dist/runtime/Proxy.d.ts +37 -0
  87. package/dist/runtime/Proxy.js +88 -16
  88. package/dist/runtime/bootstrap.js +2 -1
  89. package/dist/runtime/upgrade/BunNativeUpgradeRelay.d.ts +116 -0
  90. package/dist/runtime/upgrade/BunNativeUpgradeRelay.js +423 -0
  91. package/dist/runtime/upgrade/UpgradeHandshake.d.ts +63 -0
  92. package/dist/runtime/upgrade/UpgradeHandshake.js +199 -0
  93. package/dist/runtime/upgrade/WebSocketFrames.d.ts +67 -0
  94. package/dist/runtime/upgrade/WebSocketFrames.js +224 -0
  95. package/node_modules/@undefineds.co/ai-connections/dist/AiApiKeyPool.js +8 -1
  96. package/node_modules/@undefineds.co/ai-connections/dist/AiAuthorizationActions.d.ts +11 -2
  97. package/node_modules/@undefineds.co/ai-connections/dist/AiAuthorizationActions.js +27 -10
  98. package/node_modules/@undefineds.co/ai-connections/dist/AiClientConfigurationSection.d.ts +7 -0
  99. package/node_modules/@undefineds.co/ai-connections/dist/AiClientConfigurationSection.js +13 -11
  100. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectDialog.js +1 -1
  101. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsList.js +10 -6
  102. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMain.d.ts +15 -0
  103. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMain.js +29 -3
  104. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMainHeader.js +18 -3
  105. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.d.ts +16 -1
  106. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +92 -20
  107. package/node_modules/@undefineds.co/ai-connections/dist/AiCopyButton.d.ts +35 -0
  108. package/node_modules/@undefineds.co/ai-connections/dist/AiCopyButton.js +45 -0
  109. package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.js +71 -11
  110. package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialRow.js +9 -7
  111. package/node_modules/@undefineds.co/ai-connections/dist/AiEndpointList.d.ts +23 -0
  112. package/node_modules/@undefineds.co/ai-connections/dist/AiEndpointList.js +24 -0
  113. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.d.ts +13 -4
  114. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +35 -38
  115. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayModelsSection.d.ts +21 -0
  116. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayModelsSection.js +51 -0
  117. package/node_modules/@undefineds.co/ai-connections/dist/AiInfoTooltip.d.ts +15 -0
  118. package/node_modules/@undefineds.co/ai-connections/dist/AiInfoTooltip.js +16 -0
  119. package/node_modules/@undefineds.co/ai-connections/dist/AiModelCatalog.d.ts +175 -0
  120. package/node_modules/@undefineds.co/ai-connections/dist/AiModelCatalog.js +133 -0
  121. package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.js +2 -2
  122. package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.js +13 -64
  123. package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.d.ts +21 -0
  124. package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.js +12 -0
  125. package/node_modules/@undefineds.co/ai-connections/dist/AiRowAction.d.ts +15 -0
  126. package/node_modules/@undefineds.co/ai-connections/dist/AiRowAction.js +12 -0
  127. package/node_modules/@undefineds.co/ai-connections/dist/AiSortableCredentialList.js +2 -1
  128. package/node_modules/@undefineds.co/ai-connections/dist/ai-connections-client.d.ts +7 -0
  129. package/node_modules/@undefineds.co/ai-connections/dist/ai-connections-client.js +6 -0
  130. package/node_modules/@undefineds.co/ai-connections/dist/authorization-methods.d.ts +36 -5
  131. package/node_modules/@undefineds.co/ai-connections/dist/authorization-methods.js +52 -9
  132. package/node_modules/@undefineds.co/ai-connections/dist/client/normalize.js +30 -3
  133. package/node_modules/@undefineds.co/ai-connections/dist/client/types.d.ts +21 -1
  134. package/node_modules/@undefineds.co/ai-connections/dist/client-config/base-adapter.d.ts +1 -3
  135. package/node_modules/@undefineds.co/ai-connections/dist/client-config/base-adapter.js +3 -7
  136. package/node_modules/@undefineds.co/ai-connections/dist/client-config/index.cjs +9 -7
  137. package/node_modules/@undefineds.co/ai-connections/dist/collection-runtime.d.ts +46 -0
  138. package/node_modules/@undefineds.co/ai-connections/dist/collection-runtime.js +231 -0
  139. package/node_modules/@undefineds.co/ai-connections/dist/collections.d.ts +119 -0
  140. package/node_modules/@undefineds.co/ai-connections/dist/collections.js +173 -0
  141. package/node_modules/@undefineds.co/ai-connections/dist/controller.d.ts +71 -5
  142. package/node_modules/@undefineds.co/ai-connections/dist/controller.js +285 -16
  143. package/node_modules/@undefineds.co/ai-connections/dist/credential-labels.d.ts +5 -0
  144. package/node_modules/@undefineds.co/ai-connections/dist/credential-labels.js +8 -3
  145. package/node_modules/@undefineds.co/ai-connections/dist/credential-storage.d.ts +59 -0
  146. package/node_modules/@undefineds.co/ai-connections/dist/credential-storage.js +131 -0
  147. package/node_modules/@undefineds.co/ai-connections/dist/endpoint-urls.d.ts +15 -0
  148. package/node_modules/@undefineds.co/ai-connections/dist/endpoint-urls.js +20 -0
  149. package/node_modules/@undefineds.co/ai-connections/dist/gateway-endpoints.d.ts +14 -0
  150. package/node_modules/@undefineds.co/ai-connections/dist/gateway-endpoints.js +20 -0
  151. package/node_modules/@undefineds.co/ai-connections/dist/index.d.ts +8 -0
  152. package/node_modules/@undefineds.co/ai-connections/dist/index.js +8 -0
  153. package/node_modules/@undefineds.co/ai-connections/dist/manifest.js +1 -1
  154. package/node_modules/@undefineds.co/ai-connections/dist/offering-endpoints.d.ts +14 -0
  155. package/node_modules/@undefineds.co/ai-connections/dist/offering-endpoints.js +17 -0
  156. package/node_modules/@undefineds.co/ai-connections/dist/provider-catalog.cjs +68 -1
  157. package/node_modules/@undefineds.co/ai-connections/dist/provider-catalog.d.ts +75 -1
  158. package/node_modules/@undefineds.co/ai-connections/dist/provider-catalog.js +119 -0
  159. package/node_modules/@undefineds.co/ai-connections/dist/provider-visuals.d.ts +5 -0
  160. package/node_modules/@undefineds.co/ai-connections/dist/provider-visuals.js +5 -0
  161. package/node_modules/@undefineds.co/ai-connections/dist/service-access.js +2 -27
  162. package/node_modules/@undefineds.co/ai-connections/package.json +1 -0
  163. package/node_modules/@undefineds.co/extension-sdk/dist/manifest.d.ts +1 -1
  164. package/node_modules/@undefineds.co/extension-sdk/dist/manifest.js +2 -0
  165. package/node_modules/@undefineds.co/extension-sdk/dist/web.d.ts +150 -0
  166. package/node_modules/@undefineds.co/extension-sdk/package.json +2 -1
  167. package/node_modules/@undefineds.co/models/README.md +1 -1
  168. package/node_modules/@undefineds.co/models/dist/ai-config/index.d.ts +3 -3
  169. package/node_modules/@undefineds.co/models/dist/ai-gateway.schema.d.ts +5 -0
  170. package/node_modules/@undefineds.co/models/dist/ai-gateway.schema.js +9 -0
  171. package/node_modules/@undefineds.co/models/dist/ai-runtime.repository.d.ts +1 -1
  172. package/node_modules/@undefineds.co/models/dist/approval.repository.d.ts +2 -2
  173. package/node_modules/@undefineds.co/models/dist/audit.presentation.d.ts +2 -2
  174. package/node_modules/@undefineds.co/models/dist/capture.repository.d.ts +1 -1
  175. package/node_modules/@undefineds.co/models/dist/chat-project.repository.d.ts +1 -1
  176. package/node_modules/@undefineds.co/models/dist/chat.repository.d.ts +2 -2
  177. package/node_modules/@undefineds.co/models/dist/control-request.repository.d.ts +2 -2
  178. package/node_modules/@undefineds.co/models/dist/conversation-share.repository.d.ts +1 -1
  179. package/node_modules/@undefineds.co/models/dist/credential.schema.d.ts +12 -0
  180. package/node_modules/@undefineds.co/models/dist/credential.schema.js +15 -1
  181. package/node_modules/@undefineds.co/models/dist/discovery/index.d.ts +2 -2
  182. package/node_modules/@undefineds.co/models/dist/discovery/providers.json +248 -7
  183. package/node_modules/@undefineds.co/models/dist/discovery/types.d.ts +31 -0
  184. package/node_modules/@undefineds.co/models/dist/extension/index.d.ts +1 -1
  185. package/node_modules/@undefineds.co/models/dist/favorite/index.d.ts +2 -2
  186. package/node_modules/@undefineds.co/models/dist/fixtures/contracts-chat-contact.d.ts +5 -5
  187. package/node_modules/@undefineds.co/models/dist/import/index.d.ts +1 -1
  188. package/node_modules/@undefineds.co/models/dist/index.d.ts +73 -73
  189. package/node_modules/@undefineds.co/models/dist/index.js +1 -1
  190. package/node_modules/@undefineds.co/models/dist/input-request.repository.d.ts +2 -2
  191. package/node_modules/@undefineds.co/models/dist/knowledge/index.d.ts +1 -1
  192. package/node_modules/@undefineds.co/models/dist/message.repository.d.ts +1 -1
  193. package/node_modules/@undefineds.co/models/dist/namespaces.js +5 -0
  194. package/node_modules/@undefineds.co/models/dist/pod-storage-descriptor.d.ts +4815 -26
  195. package/node_modules/@undefineds.co/models/dist/pod-storage-descriptor.js +482 -132
  196. package/node_modules/@undefineds.co/models/dist/schema.d.ts +4 -0
  197. package/node_modules/@undefineds.co/models/dist/session/index.d.ts +1 -1
  198. package/node_modules/@undefineds.co/models/dist/settings/index.d.ts +1 -1
  199. package/node_modules/@undefineds.co/models/dist/sidecar/persistence-mapping.d.ts +5 -5
  200. package/node_modules/@undefineds.co/models/dist/thread.repository.d.ts +2 -2
  201. package/node_modules/@undefineds.co/models/dist/types/message-block.d.ts +1 -1
  202. package/node_modules/@undefineds.co/models/dist/vocab/_namespaces.d.ts +1 -1
  203. package/node_modules/@undefineds.co/models/dist/vocab/index.d.ts +10 -10
  204. package/node_modules/@undefineds.co/models/dist/vocab/sidecar.vocab.d.ts +1 -0
  205. package/node_modules/@undefineds.co/models/dist/vocab/sidecar.vocab.js +1 -0
  206. package/node_modules/@undefineds.co/models/package.json +4 -2
  207. package/node_modules/@undefineds.co/pod-collections/README.md +71 -0
  208. package/node_modules/@undefineds.co/pod-collections/dist/diff.d.ts +85 -0
  209. package/node_modules/@undefineds.co/pod-collections/dist/diff.js +166 -0
  210. package/node_modules/@undefineds.co/pod-collections/dist/feed.d.ts +17 -0
  211. package/node_modules/@undefineds.co/pod-collections/dist/feed.js +27 -0
  212. package/node_modules/@undefineds.co/pod-collections/dist/index.cjs +1042 -0
  213. package/node_modules/@undefineds.co/pod-collections/dist/index.d.ts +37 -0
  214. package/node_modules/@undefineds.co/pod-collections/dist/index.js +89 -0
  215. package/node_modules/@undefineds.co/pod-collections/dist/layout.d.ts +75 -0
  216. package/node_modules/@undefineds.co/pod-collections/dist/layout.js +173 -0
  217. package/node_modules/@undefineds.co/pod-collections/dist/mapping.d.ts +78 -0
  218. package/node_modules/@undefineds.co/pod-collections/dist/mapping.js +287 -0
  219. package/node_modules/@undefineds.co/pod-collections/dist/mutations.d.ts +83 -0
  220. package/node_modules/@undefineds.co/pod-collections/dist/mutations.js +273 -0
  221. package/node_modules/@undefineds.co/pod-collections/dist/react.d.ts +21 -0
  222. package/node_modules/@undefineds.co/pod-collections/dist/react.js +22 -0
  223. package/node_modules/@undefineds.co/pod-collections/dist/read.d.ts +65 -0
  224. package/node_modules/@undefineds.co/pod-collections/dist/read.js +31 -0
  225. package/node_modules/@undefineds.co/pod-collections/dist/sync.d.ts +66 -0
  226. package/node_modules/@undefineds.co/pod-collections/dist/sync.js +260 -0
  227. package/node_modules/@undefineds.co/pod-collections/dist/types.d.ts +155 -0
  228. package/node_modules/@undefineds.co/pod-collections/dist/types.js +9 -0
  229. package/node_modules/@undefineds.co/pod-collections/package.json +42 -0
  230. package/package.json +15 -7
  231. package/static/app/assets/main.css +1 -1
  232. package/static/auth-callback/assets/AiConfigContext-DnQs1ZpW.js +1 -0
  233. package/static/auth-callback/assets/AiConfigPage-DOtvlxH0.js +1 -0
  234. package/static/auth-callback/assets/DocumentProcessingPanel-BS2voQgL.js +1 -0
  235. package/static/auth-callback/assets/IndexLifecyclePanel-Cvt0cJtN.js +1 -0
  236. package/static/auth-callback/assets/{IndexSubjectPanel-BbUqop4b.js → IndexSubjectPanel-Dhf01GqF.js} +1 -1
  237. package/static/auth-callback/assets/ModelAssignmentsPanel-BJutWaAF.js +1 -0
  238. package/static/auth-callback/assets/ModelsPage-BRS0sje3.js +11 -0
  239. package/static/auth-callback/assets/{NetworkPage-Vp2PrMxs.js → NetworkPage-B3qBfANA.js} +2 -2
  240. package/static/auth-callback/assets/{PaneListHeader-DY7baSFl.js → PaneListHeader-QQeJGTp4.js} +1 -1
  241. package/static/auth-callback/assets/SearchIndexingPanel-MyNUSEwT.js +1 -0
  242. package/static/auth-callback/assets/{StatusSubjectPanel-ArIS-TxT.js → StatusSubjectPanel-DQkEVsFs.js} +1 -1
  243. package/static/{settings/assets/StatusWorkspace-CoMFRXoV.js → auth-callback/assets/StatusWorkspace-Dkv63Uwk.js} +1 -1
  244. package/static/auth-callback/assets/{SystemSettingsPage-BDvT1NUz.js → SystemSettingsPage-TIsUfX5d.js} +1 -1
  245. package/static/{dashboard/assets/SystemSettingsSubjectPanel-WaE8mTQi.js → auth-callback/assets/SystemSettingsSubjectPanel-BJWEt2-7.js} +5 -5
  246. package/static/auth-callback/assets/XpodAiConnectionsPodStore-BJiXm-PF.js +3 -0
  247. package/static/auth-callback/assets/{activity-D1Dsfa_0.js → activity-5hNeNKnL.js} +1 -1
  248. package/static/auth-callback/assets/ai-connections-CryuHGKW.js +1 -0
  249. package/static/auth-callback/assets/{auth-callback-Cmf4hXVZ.js → auth-callback-CAFZ3R0B.js} +6 -6
  250. package/static/auth-callback/assets/auth-callback-rk080mvG.css +1 -0
  251. package/static/auth-callback/assets/{badge-CZsHq3Ih.js → badge-CAIPI0CB.js} +1 -1
  252. package/static/auth-callback/assets/collection-runtime-D9s7h9YA.js +1 -0
  253. package/static/auth-callback/assets/dialog-BjA109aX.js +1 -0
  254. package/static/auth-callback/assets/{download-DU9ntlHw.js → download-B3Up5W2G.js} +1 -1
  255. package/static/auth-callback/assets/{external-link-BfzaaZDx.js → external-link-BTXgSPzB.js} +1 -1
  256. package/static/auth-callback/assets/index-BppXlxcp.js +41 -0
  257. package/static/auth-callback/assets/index-CirW4CJf.js +1 -0
  258. package/static/auth-callback/assets/index-DlLYWOhw.js +4 -0
  259. package/static/auth-callback/assets/{index-browser-BNFqqC74.js → index-browser-DtU38ni3.js} +1 -1
  260. package/static/auth-callback/assets/{key-round-BwP3DBWo.js → key-round-CQCOrZ7x.js} +1 -1
  261. package/static/auth-callback/assets/layout-DB3pMyTl.js +1 -0
  262. package/static/auth-callback/assets/pod-collections-host-KnnGFZHL.js +8 -0
  263. package/static/auth-callback/assets/{rotate-ccw-VMwnmyab.js → rotate-ccw-C1zM2KtS.js} +1 -1
  264. package/static/auth-callback/assets/{skeleton-CoD55rBT.js → skeleton-Cqp7_M9-.js} +1 -1
  265. package/static/auth-callback/assets/{waypoints-DRo_1Ca7.js → waypoints-Bj6gAUSQ.js} +1 -1
  266. package/static/auth-callback/assets/{workspace-layout--mcXl3My.js → workspace-layout-DK8mDzrY.js} +1 -1
  267. package/static/auth-callback/auth-callback.html +2 -2
  268. package/static/dashboard/assets/AiConfigContext-BsE7MqX8.js +1 -0
  269. package/static/dashboard/assets/AiConfigPage-DvM-lRXa.js +1 -0
  270. package/static/dashboard/assets/DocumentProcessingPanel-BPfdlfuf.js +1 -0
  271. package/static/dashboard/assets/IndexLifecyclePanel--m0AGxvh.js +1 -0
  272. package/static/dashboard/assets/{IndexSubjectPanel-B2cXwl8X.js → IndexSubjectPanel-Bb7m1k3d.js} +1 -1
  273. package/static/dashboard/assets/ModelAssignmentsPanel-BLi_zbMa.js +1 -0
  274. package/static/dashboard/assets/ModelsPage-CxdpgnfR.js +11 -0
  275. package/static/dashboard/assets/{NetworkPage-DV2V0qWO.js → NetworkPage-BAIPw-D_.js} +2 -2
  276. package/static/dashboard/assets/{PaneListHeader-D0c1yCFH.js → PaneListHeader-BBCMei0r.js} +1 -1
  277. package/static/dashboard/assets/SearchIndexingPanel-Ck4Y-xjR.js +1 -0
  278. package/static/dashboard/assets/{StatusSubjectPanel-oPSECj7i.js → StatusSubjectPanel-D1KWfAXE.js} +1 -1
  279. package/static/dashboard/assets/{StatusWorkspace-PdovQPKa.js → StatusWorkspace-JbA5gzXx.js} +1 -1
  280. package/static/dashboard/assets/{SystemSettingsPage-CtNDklkx.js → SystemSettingsPage-BbwQWsSR.js} +1 -1
  281. package/static/{settings/assets/SystemSettingsSubjectPanel-DExjDo_v.js → dashboard/assets/SystemSettingsSubjectPanel-N117nMt5.js} +5 -5
  282. package/static/dashboard/assets/XpodAiConnectionsPodStore-CdDOb4SV.js +18 -0
  283. package/static/dashboard/assets/{activity-B9ylSoyr.js → activity-DX1I96o_.js} +1 -1
  284. package/static/dashboard/assets/ai-connections-DwCRqOQa.js +1 -0
  285. package/static/dashboard/assets/{badge-BNbFbpIb.js → badge-k2vhtDqH.js} +1 -1
  286. package/static/dashboard/assets/collection-runtime-BFQ8teQJ.js +1 -0
  287. package/static/dashboard/assets/{dashboard-CD-FFVRD.js → dashboard-DWZ-fmCT.js} +4 -4
  288. package/static/dashboard/assets/dashboard-rk080mvG.css +1 -0
  289. package/static/dashboard/assets/dialog-1CCw-iHT.js +1 -0
  290. package/static/dashboard/assets/{download-nOP38LtW.js → download-C6-SNY1q.js} +1 -1
  291. package/static/dashboard/assets/{external-link-Bh2ewN9E.js → external-link-BgPcZ_j2.js} +1 -1
  292. package/static/dashboard/assets/index-6LcIUIYO.js +1 -0
  293. package/static/dashboard/assets/index-D7A8U6Pt.js +41 -0
  294. package/static/dashboard/assets/index-UD6QOE7H.js +4 -0
  295. package/static/dashboard/assets/{key-round-bGmguBLv.js → key-round-BOd7Jo0Q.js} +1 -1
  296. package/static/dashboard/assets/layout-DB3pMyTl.js +1 -0
  297. package/static/dashboard/assets/pod-collections-host-KnnGFZHL.js +8 -0
  298. package/static/dashboard/assets/{rotate-ccw-D2x__ODW.js → rotate-ccw-CCgJqsvx.js} +1 -1
  299. package/static/dashboard/assets/{skeleton-VOqft8WS.js → skeleton-Bc7abAn5.js} +1 -1
  300. package/static/dashboard/assets/{waypoints-fgRqm4oH.js → waypoints-s-opmJxx.js} +1 -1
  301. package/static/dashboard/assets/{workspace-layout-DV4dgeHX.js → workspace-layout-DqIQeTBV.js} +1 -1
  302. package/static/dashboard/dashboard.html +2 -2
  303. package/static/settings/assets/AiConfigContext-BB9KZySa.js +1 -0
  304. package/static/settings/assets/AiConfigPage-DGSXUkLs.js +1 -0
  305. package/static/settings/assets/DocumentProcessingPanel-Da2Re6Rg.js +1 -0
  306. package/static/settings/assets/IndexLifecyclePanel-BSZuIzgr.js +1 -0
  307. package/static/settings/assets/{IndexSubjectPanel-BgbI9c-a.js → IndexSubjectPanel-CFd0ay-r.js} +1 -1
  308. package/static/settings/assets/ModelAssignmentsPanel-CSAryvWJ.js +1 -0
  309. package/static/settings/assets/ModelsPage-BQwCwLHU.js +11 -0
  310. package/static/settings/assets/{NetworkPage-C8OA9Mtp.js → NetworkPage-BKymvsQc.js} +2 -2
  311. package/static/settings/assets/{PaneListHeader-COvlPJWj.js → PaneListHeader-Bjh3hRdQ.js} +1 -1
  312. package/static/settings/assets/SearchIndexingPanel-MjKL5QLU.js +1 -0
  313. package/static/settings/assets/{StatusSubjectPanel-BuLml7qn.js → StatusSubjectPanel-Bvl6K4mx.js} +1 -1
  314. package/static/settings/assets/StatusWorkspace-B0NzrP--.js +1 -0
  315. package/static/settings/assets/{SystemSettingsPage-DlzmaWV-.js → SystemSettingsPage-D2z6Z4FE.js} +1 -1
  316. package/static/{auth-callback/assets/SystemSettingsSubjectPanel-CDqRuC4t.js → settings/assets/SystemSettingsSubjectPanel-4sxma4X4.js} +5 -5
  317. package/static/settings/assets/XpodAiConnectionsPodStore-BkNQ8fZx.js +3 -0
  318. package/static/settings/assets/{activity-TLerXgMs.js → activity-CgJJGpjx.js} +1 -1
  319. package/static/settings/assets/ai-connections-CryuHGKW.js +1 -0
  320. package/static/settings/assets/{badge-Bcs8iWrH.js → badge-C4NypVyT.js} +1 -1
  321. package/static/settings/assets/collection-runtime-CTLCDxAi.js +1 -0
  322. package/static/settings/assets/dialog-Csq0vWUi.js +1 -0
  323. package/static/settings/assets/{download-Ct3QmHPt.js → download-DaLJJ-Wp.js} +1 -1
  324. package/static/settings/assets/{external-link-C8KiHbss.js → external-link--w_iW5Au.js} +1 -1
  325. package/static/settings/assets/index-B0mQa59b.js +4 -0
  326. package/static/settings/assets/index-BukHiu4y.js +1 -0
  327. package/static/settings/assets/index-COmVnZi2.js +41 -0
  328. package/static/settings/assets/{index-browser-CazX1pc2.js → index-browser-BGpvHwD0.js} +1 -1
  329. package/static/settings/assets/{key-round-B19YD1GA.js → key-round-Bk4YRjBu.js} +1 -1
  330. package/static/settings/assets/layout-DB3pMyTl.js +1 -0
  331. package/static/settings/assets/pod-collections-host-KnnGFZHL.js +8 -0
  332. package/static/settings/assets/{rotate-ccw-AQm2kMgU.js → rotate-ccw-TCabbqsr.js} +1 -1
  333. package/static/settings/assets/{settings-C-VBtt9r.js → settings-CJWpdbNC.js} +5 -5
  334. package/static/settings/assets/settings-rk080mvG.css +1 -0
  335. package/static/settings/assets/{skeleton-DyZ1OBYf.js → skeleton-JDHYVe7t.js} +1 -1
  336. package/static/settings/assets/{waypoints-CC3wq-SU.js → waypoints-DDvEl-MU.js} +1 -1
  337. package/static/settings/assets/{workspace-layout-BxXNKgf9.js → workspace-layout-DV5QU30U.js} +1 -1
  338. package/static/settings/settings.html +2 -2
  339. package/static/auth-callback/assets/AiConfigContext-DqWRSm7n.js +0 -1
  340. package/static/auth-callback/assets/AiConfigPage-C5YYyvzl.js +0 -1
  341. package/static/auth-callback/assets/DocumentProcessingPanel-DZCiacBz.js +0 -1
  342. package/static/auth-callback/assets/IndexLifecyclePanel-CCLeOljB.js +0 -1
  343. package/static/auth-callback/assets/ModelAssignmentsPanel-jUUTDKuh.js +0 -1
  344. package/static/auth-callback/assets/ModelsPage-B08zdtff.js +0 -10
  345. package/static/auth-callback/assets/SearchIndexingPanel-D4YRg1-8.js +0 -1
  346. package/static/auth-callback/assets/StatusWorkspace-Cp5LQ9Yx.js +0 -1
  347. package/static/auth-callback/assets/ai-connections-CHNTKemd.js +0 -1
  348. package/static/auth-callback/assets/auth-callback-DWMMiFjh.css +0 -1
  349. package/static/auth-callback/assets/index-DSNnLUbU.js +0 -4
  350. package/static/auth-callback/assets/index-FHhHoKgp.js +0 -41
  351. package/static/dashboard/assets/AiConfigContext-BpPDKSzI.js +0 -1
  352. package/static/dashboard/assets/AiConfigPage-wsqEZDIX.js +0 -1
  353. package/static/dashboard/assets/DocumentProcessingPanel-CDSy3juc.js +0 -1
  354. package/static/dashboard/assets/IndexLifecyclePanel-CVd6vQCX.js +0 -1
  355. package/static/dashboard/assets/ModelAssignmentsPanel-BeBZhnQd.js +0 -1
  356. package/static/dashboard/assets/ModelsPage-B6McSCJw.js +0 -25
  357. package/static/dashboard/assets/SearchIndexingPanel-CGs0OZ12.js +0 -1
  358. package/static/dashboard/assets/ai-connections-CHNTKemd.js +0 -1
  359. package/static/dashboard/assets/dashboard-DWMMiFjh.css +0 -1
  360. package/static/dashboard/assets/index-PgS-Bt7X.js +0 -41
  361. package/static/dashboard/assets/index-QN2QgEwr.js +0 -4
  362. package/static/settings/assets/AiConfigContext-zKQYdfai.js +0 -1
  363. package/static/settings/assets/AiConfigPage-Bs1EE3Ei.js +0 -1
  364. package/static/settings/assets/DocumentProcessingPanel-CSFfdOXS.js +0 -1
  365. package/static/settings/assets/IndexLifecyclePanel-BR9Su49B.js +0 -1
  366. package/static/settings/assets/ModelAssignmentsPanel-C0BE7nbk.js +0 -1
  367. package/static/settings/assets/ModelsPage-CU-YQ8_7.js +0 -10
  368. package/static/settings/assets/SearchIndexingPanel-Bdd46mIV.js +0 -1
  369. package/static/settings/assets/ai-connections-CHNTKemd.js +0 -1
  370. package/static/settings/assets/index-1Q2cRjZd.js +0 -41
  371. package/static/settings/assets/index-DBO_Vq0P.js +0 -4
  372. package/static/settings/assets/settings-DWMMiFjh.css +0 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DBO_Vq0P.js","assets/admin-C6qCRFiY.js","assets/activity-TLerXgMs.js","assets/external-link-C8KiHbss.js","assets/index-1Q2cRjZd.js","assets/download-Ct3QmHPt.js","assets/key-round-B19YD1GA.js","assets/NetworkPage-C8OA9Mtp.js","assets/PaneListHeader-COvlPJWj.js","assets/waypoints-CC3wq-SU.js","assets/workspace-layout-BxXNKgf9.js","assets/badge-Bcs8iWrH.js","assets/rotate-ccw-AQm2kMgU.js","assets/StatusWorkspace-CoMFRXoV.js","assets/StatusSubjectPanel-BuLml7qn.js","assets/IndexSubjectPanel-BgbI9c-a.js","assets/skeleton-DyZ1OBYf.js","assets/ModelsPage-CU-YQ8_7.js","assets/ai-connections-CHNTKemd.js","assets/index-browser-CazX1pc2.js","assets/AiConfigPage-Bs1EE3Ei.js","assets/AiConfigContext-zKQYdfai.js","assets/ModelAssignmentsPanel-C0BE7nbk.js","assets/DocumentProcessingPanel-CSFfdOXS.js","assets/SearchIndexingPanel-Bdd46mIV.js","assets/IndexLifecyclePanel-BR9Su49B.js","assets/SystemSettingsPage-DlzmaWV-.js","assets/settings-projection-CUkyprDQ.js","assets/SystemSettingsSubjectPanel-DExjDo_v.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-B0mQa59b.js","assets/admin-C6qCRFiY.js","assets/activity-CgJJGpjx.js","assets/external-link--w_iW5Au.js","assets/index-COmVnZi2.js","assets/index-BukHiu4y.js","assets/download-DaLJJ-Wp.js","assets/key-round-Bk4YRjBu.js","assets/NetworkPage-BKymvsQc.js","assets/PaneListHeader-Bjh3hRdQ.js","assets/waypoints-DDvEl-MU.js","assets/workspace-layout-DV5QU30U.js","assets/badge-C4NypVyT.js","assets/rotate-ccw-TCabbqsr.js","assets/StatusWorkspace-B0NzrP--.js","assets/StatusSubjectPanel-Bvl6K4mx.js","assets/IndexSubjectPanel-CFd0ay-r.js","assets/skeleton-JDHYVe7t.js","assets/ModelsPage-BQwCwLHU.js","assets/ai-connections-CryuHGKW.js","assets/XpodAiConnectionsPodStore-BkNQ8fZx.js","assets/index-browser-BGpvHwD0.js","assets/dialog-Csq0vWUi.js","assets/AiConfigPage-DGSXUkLs.js","assets/AiConfigContext-BB9KZySa.js","assets/ModelAssignmentsPanel-CSAryvWJ.js","assets/DocumentProcessingPanel-Da2Re6Rg.js","assets/SearchIndexingPanel-MjKL5QLU.js","assets/IndexLifecyclePanel-BSZuIzgr.js","assets/SystemSettingsPage-D2z6Z4FE.js","assets/settings-projection-CUkyprDQ.js","assets/SystemSettingsSubjectPanel-4sxma4X4.js"])))=>i.map(i=>d[i]);
2
2
  function _mergeNamespaces(n,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in n)){const o=Object.getOwnPropertyDescriptor(i,s);o&&Object.defineProperty(n,s,o.get?o:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function t(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(s){if(s.ep)return;s.ep=!0;const o=t(s);fetch(s.href,o)}})();var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function i(){var s=!1;try{s=this instanceof i}catch{}return s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(i){var s=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return n[i]}})}),t}var jsxRuntime={exports:{}},reactJsxRuntime_production={};var hasRequiredReactJsxRuntime_production;function requireReactJsxRuntime_production(){if(hasRequiredReactJsxRuntime_production)return reactJsxRuntime_production;hasRequiredReactJsxRuntime_production=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,s,o){var l=null;if(o!==void 0&&(l=""+o),s.key!==void 0&&(l=""+s.key),"key"in s){o={};for(var u in s)u!=="key"&&(o[u]=s[u])}else o=s;return s=o.ref,{$$typeof:n,type:i,key:l,ref:s!==void 0?s:null,props:o}}return reactJsxRuntime_production.Fragment=e,reactJsxRuntime_production.jsx=t,reactJsxRuntime_production.jsxs=t,reactJsxRuntime_production}var hasRequiredJsxRuntime;function requireJsxRuntime(){return hasRequiredJsxRuntime||(hasRequiredJsxRuntime=1,jsxRuntime.exports=requireReactJsxRuntime_production()),jsxRuntime.exports}var jsxRuntimeExports=requireJsxRuntime(),react={exports:{}},react_production={};var hasRequiredReact_production;function requireReact_production(){if(hasRequiredReact_production)return react_production;hasRequiredReact_production=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),l=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),m=Symbol.iterator;function v(W){return W===null||typeof W!="object"?null:(W=m&&W[m]||W["@@iterator"],typeof W=="function"?W:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,x={};function A(W,de,te){this.props=W,this.context=de,this.refs=x,this.updater=te||S}A.prototype.isReactComponent={},A.prototype.setState=function(W,de){if(typeof W!="object"&&typeof W!="function"&&W!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,W,de,"setState")},A.prototype.forceUpdate=function(W){this.updater.enqueueForceUpdate(this,W,"forceUpdate")};function C(){}C.prototype=A.prototype;function T(W,de,te){this.props=W,this.context=de,this.refs=x,this.updater=te||S}var F=T.prototype=new C;F.constructor=T,E(F,A.prototype),F.isPureReactComponent=!0;var P=Array.isArray;function q(){}var O={H:null,A:null,T:null,S:null},G=Object.prototype.hasOwnProperty;function fe(W,de,te){var Te=te.ref;return{$$typeof:n,type:W,key:de,ref:Te!==void 0?Te:null,props:te}}function M(W,de){return fe(W.type,de,W.props)}function ee(W){return typeof W=="object"&&W!==null&&W.$$typeof===n}function Se(W){var de={"=":"=0",":":"=2"};return"$"+W.replace(/[=:]/g,function(te){return de[te]})}var re=/\/+/g;function Ae(W,de){return typeof W=="object"&&W!==null&&W.key!=null?Se(""+W.key):de.toString(36)}function ke(W){switch(W.status){case"fulfilled":return W.value;case"rejected":throw W.reason;default:switch(typeof W.status=="string"?W.then(q,q):(W.status="pending",W.then(function(de){W.status==="pending"&&(W.status="fulfilled",W.value=de)},function(de){W.status==="pending"&&(W.status="rejected",W.reason=de)})),W.status){case"fulfilled":return W.value;case"rejected":throw W.reason}}throw W}function he(W,de,te,Te,je){var He=typeof W;(He==="undefined"||He==="boolean")&&(W=null);var We=!1;if(W===null)We=!0;else switch(He){case"bigint":case"string":case"number":We=!0;break;case"object":switch(W.$$typeof){case n:case e:We=!0;break;case p:return We=W._init,he(We(W._payload),de,te,Te,je)}}if(We)return je=je(W),We=Te===""?"."+Ae(W,0):Te,P(je)?(te="",We!=null&&(te=We.replace(re,"$&/")+"/"),he(je,de,te,"",function(Be){return Be})):je!=null&&(ee(je)&&(je=M(je,te+(je.key==null||W&&W.key===je.key?"":(""+je.key).replace(re,"$&/")+"/")+We)),de.push(je)),1;We=0;var me=Te===""?".":Te+":";if(P(W))for(var ge=0;ge<W.length;ge++)Te=W[ge],He=me+Ae(Te,ge),We+=he(Te,de,te,He,je);else if(ge=v(W),typeof ge=="function")for(W=ge.call(W),ge=0;!(Te=W.next()).done;)Te=Te.value,He=me+Ae(Te,ge++),We+=he(Te,de,te,He,je);else if(He==="object"){if(typeof W.then=="function")return he(ke(W),de,te,Te,je);throw de=String(W),Error("Objects are not valid as a React child (found: "+(de==="[object Object]"?"object with keys {"+Object.keys(W).join(", ")+"}":de)+"). If you meant to render a collection of children, use an array instead.")}return We}function Oe(W,de,te){if(W==null)return W;var Te=[],je=0;return he(W,Te,"","",function(He){return de.call(te,He,je++)}),Te}function ce(W){if(W._status===-1){var de=W._result;de=de(),de.then(function(te){(W._status===0||W._status===-1)&&(W._status=1,W._result=te)},function(te){(W._status===0||W._status===-1)&&(W._status=2,W._result=te)}),W._status===-1&&(W._status=0,W._result=de)}if(W._status===1)return W._result.default;throw W._result}var Ue=typeof reportError=="function"?reportError:function(W){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var de=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof W=="object"&&W!==null&&typeof W.message=="string"?String(W.message):String(W),error:W});if(!window.dispatchEvent(de))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",W);return}console.error(W)},$={map:Oe,forEach:function(W,de,te){Oe(W,function(){de.apply(this,arguments)},te)},count:function(W){var de=0;return Oe(W,function(){de++}),de},toArray:function(W){return Oe(W,function(de){return de})||[]},only:function(W){if(!ee(W))throw Error("React.Children.only expected to receive a single React element child.");return W}};return react_production.Activity=g,react_production.Children=$,react_production.Component=A,react_production.Fragment=t,react_production.Profiler=s,react_production.PureComponent=T,react_production.StrictMode=i,react_production.Suspense=h,react_production.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=O,react_production.__COMPILER_RUNTIME={__proto__:null,c:function(W){return O.H.useMemoCache(W)}},react_production.cache=function(W){return function(){return W.apply(null,arguments)}},react_production.cacheSignal=function(){return null},react_production.cloneElement=function(W,de,te){if(W==null)throw Error("The argument must be a React element, but you passed "+W+".");var Te=E({},W.props),je=W.key;if(de!=null)for(He in de.key!==void 0&&(je=""+de.key),de)!G.call(de,He)||He==="key"||He==="__self"||He==="__source"||He==="ref"&&de.ref===void 0||(Te[He]=de[He]);var He=arguments.length-2;if(He===1)Te.children=te;else if(1<He){for(var We=Array(He),me=0;me<He;me++)We[me]=arguments[me+2];Te.children=We}return fe(W.type,je,Te)},react_production.createContext=function(W){return W={$$typeof:l,_currentValue:W,_currentValue2:W,_threadCount:0,Provider:null,Consumer:null},W.Provider=W,W.Consumer={$$typeof:o,_context:W},W},react_production.createElement=function(W,de,te){var Te,je={},He=null;if(de!=null)for(Te in de.key!==void 0&&(He=""+de.key),de)G.call(de,Te)&&Te!=="key"&&Te!=="__self"&&Te!=="__source"&&(je[Te]=de[Te]);var We=arguments.length-2;if(We===1)je.children=te;else if(1<We){for(var me=Array(We),ge=0;ge<We;ge++)me[ge]=arguments[ge+2];je.children=me}if(W&&W.defaultProps)for(Te in We=W.defaultProps,We)je[Te]===void 0&&(je[Te]=We[Te]);return fe(W,He,je)},react_production.createRef=function(){return{current:null}},react_production.forwardRef=function(W){return{$$typeof:u,render:W}},react_production.isValidElement=ee,react_production.lazy=function(W){return{$$typeof:p,_payload:{_status:-1,_result:W},_init:ce}},react_production.memo=function(W,de){return{$$typeof:d,type:W,compare:de===void 0?null:de}},react_production.startTransition=function(W){var de=O.T,te={};O.T=te;try{var Te=W(),je=O.S;je!==null&&je(te,Te),typeof Te=="object"&&Te!==null&&typeof Te.then=="function"&&Te.then(q,Ue)}catch(He){Ue(He)}finally{de!==null&&te.types!==null&&(de.types=te.types),O.T=de}},react_production.unstable_useCacheRefresh=function(){return O.H.useCacheRefresh()},react_production.use=function(W){return O.H.use(W)},react_production.useActionState=function(W,de,te){return O.H.useActionState(W,de,te)},react_production.useCallback=function(W,de){return O.H.useCallback(W,de)},react_production.useContext=function(W){return O.H.useContext(W)},react_production.useDebugValue=function(){},react_production.useDeferredValue=function(W,de){return O.H.useDeferredValue(W,de)},react_production.useEffect=function(W,de){return O.H.useEffect(W,de)},react_production.useEffectEvent=function(W){return O.H.useEffectEvent(W)},react_production.useId=function(){return O.H.useId()},react_production.useImperativeHandle=function(W,de,te){return O.H.useImperativeHandle(W,de,te)},react_production.useInsertionEffect=function(W,de){return O.H.useInsertionEffect(W,de)},react_production.useLayoutEffect=function(W,de){return O.H.useLayoutEffect(W,de)},react_production.useMemo=function(W,de){return O.H.useMemo(W,de)},react_production.useOptimistic=function(W,de){return O.H.useOptimistic(W,de)},react_production.useReducer=function(W,de,te){return O.H.useReducer(W,de,te)},react_production.useRef=function(W){return O.H.useRef(W)},react_production.useState=function(W){return O.H.useState(W)},react_production.useSyncExternalStore=function(W,de,te){return O.H.useSyncExternalStore(W,de,te)},react_production.useTransition=function(){return O.H.useTransition()},react_production.version="19.2.8",react_production}var hasRequiredReact;function requireReact(){return hasRequiredReact||(hasRequiredReact=1,react.exports=requireReact_production()),react.exports}var reactExports=requireReact();const React=getDefaultExportFromCjs(reactExports),React4=_mergeNamespaces({__proto__:null,default:React},[reactExports]);var client={exports:{}},reactDomClient_production={},scheduler={exports:{}},scheduler_production={};var hasRequiredScheduler_production;function requireScheduler_production(){return hasRequiredScheduler_production||(hasRequiredScheduler_production=1,(function(n){function e(he,Oe){var ce=he.length;he.push(Oe);e:for(;0<ce;){var Ue=ce-1>>>1,$=he[Ue];if(0<s($,Oe))he[Ue]=Oe,he[ce]=$,ce=Ue;else break e}}function t(he){return he.length===0?null:he[0]}function i(he){if(he.length===0)return null;var Oe=he[0],ce=he.pop();if(ce!==Oe){he[0]=ce;e:for(var Ue=0,$=he.length,W=$>>>1;Ue<W;){var de=2*(Ue+1)-1,te=he[de],Te=de+1,je=he[Te];if(0>s(te,ce))Te<$&&0>s(je,te)?(he[Ue]=je,he[Te]=ce,Ue=Te):(he[Ue]=te,he[de]=ce,Ue=de);else if(Te<$&&0>s(je,ce))he[Ue]=je,he[Te]=ce,Ue=Te;else break e}}return Oe}function s(he,Oe){var ce=he.sortIndex-Oe.sortIndex;return ce!==0?ce:he.id-Oe.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;n.unstable_now=function(){return o.now()}}else{var l=Date,u=l.now();n.unstable_now=function(){return l.now()-u}}var h=[],d=[],p=1,g=null,m=3,v=!1,S=!1,E=!1,x=!1,A=typeof setTimeout=="function"?setTimeout:null,C=typeof clearTimeout=="function"?clearTimeout:null,T=typeof setImmediate<"u"?setImmediate:null;function F(he){for(var Oe=t(d);Oe!==null;){if(Oe.callback===null)i(d);else if(Oe.startTime<=he)i(d),Oe.sortIndex=Oe.expirationTime,e(h,Oe);else break;Oe=t(d)}}function P(he){if(E=!1,F(he),!S)if(t(h)!==null)S=!0,q||(q=!0,Se());else{var Oe=t(d);Oe!==null&&ke(P,Oe.startTime-he)}}var q=!1,O=-1,G=5,fe=-1;function M(){return x?!0:!(n.unstable_now()-fe<G)}function ee(){if(x=!1,q){var he=n.unstable_now();fe=he;var Oe=!0;try{e:{S=!1,E&&(E=!1,C(O),O=-1),v=!0;var ce=m;try{t:{for(F(he),g=t(h);g!==null&&!(g.expirationTime>he&&M());){var Ue=g.callback;if(typeof Ue=="function"){g.callback=null,m=g.priorityLevel;var $=Ue(g.expirationTime<=he);if(he=n.unstable_now(),typeof $=="function"){g.callback=$,F(he),Oe=!0;break t}g===t(h)&&i(h),F(he)}else i(h);g=t(h)}if(g!==null)Oe=!0;else{var W=t(d);W!==null&&ke(P,W.startTime-he),Oe=!1}}break e}finally{g=null,m=ce,v=!1}Oe=void 0}}finally{Oe?Se():q=!1}}}var Se;if(typeof T=="function")Se=function(){T(ee)};else if(typeof MessageChannel<"u"){var re=new MessageChannel,Ae=re.port2;re.port1.onmessage=ee,Se=function(){Ae.postMessage(null)}}else Se=function(){A(ee,0)};function ke(he,Oe){O=A(function(){he(n.unstable_now())},Oe)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(he){he.callback=null},n.unstable_forceFrameRate=function(he){0>he||125<he?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):G=0<he?Math.floor(1e3/he):5},n.unstable_getCurrentPriorityLevel=function(){return m},n.unstable_next=function(he){switch(m){case 1:case 2:case 3:var Oe=3;break;default:Oe=m}var ce=m;m=Oe;try{return he()}finally{m=ce}},n.unstable_requestPaint=function(){x=!0},n.unstable_runWithPriority=function(he,Oe){switch(he){case 1:case 2:case 3:case 4:case 5:break;default:he=3}var ce=m;m=he;try{return Oe()}finally{m=ce}},n.unstable_scheduleCallback=function(he,Oe,ce){var Ue=n.unstable_now();switch(typeof ce=="object"&&ce!==null?(ce=ce.delay,ce=typeof ce=="number"&&0<ce?Ue+ce:Ue):ce=Ue,he){case 1:var $=-1;break;case 2:$=250;break;case 5:$=1073741823;break;case 4:$=1e4;break;default:$=5e3}return $=ce+$,he={id:p++,callback:Oe,priorityLevel:he,startTime:ce,expirationTime:$,sortIndex:-1},ce>Ue?(he.sortIndex=ce,e(d,he),t(h)===null&&he===t(d)&&(E?(C(O),O=-1):E=!0,ke(P,ce-Ue))):(he.sortIndex=$,e(h,he),S||v||(S=!0,q||(q=!0,Se()))),he},n.unstable_shouldYield=M,n.unstable_wrapCallback=function(he){var Oe=m;return function(){var ce=m;m=Oe;try{return he.apply(this,arguments)}finally{m=ce}}}})(scheduler_production)),scheduler_production}var hasRequiredScheduler;function requireScheduler(){return hasRequiredScheduler||(hasRequiredScheduler=1,scheduler.exports=requireScheduler_production()),scheduler.exports}var reactDom={exports:{}},reactDom_production={};var hasRequiredReactDom_production;function requireReactDom_production(){if(hasRequiredReactDom_production)return reactDom_production;hasRequiredReactDom_production=1;var n=requireReact();function e(h){var d="https://react.dev/errors/"+h;if(1<arguments.length){d+="?args[]="+encodeURIComponent(arguments[1]);for(var p=2;p<arguments.length;p++)d+="&args[]="+encodeURIComponent(arguments[p])}return"Minified React error #"+h+"; visit "+d+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function t(){}var i={d:{f:t,r:function(){throw Error(e(522))},D:t,C:t,L:t,m:t,X:t,S:t,M:t},p:0,findDOMNode:null},s=Symbol.for("react.portal");function o(h,d,p){var g=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:g==null?null:""+g,children:h,containerInfo:d,implementation:p}}var l=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function u(h,d){if(h==="font")return"";if(typeof d=="string")return d==="use-credentials"?d:""}return reactDom_production.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=i,reactDom_production.createPortal=function(h,d){var p=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!d||d.nodeType!==1&&d.nodeType!==9&&d.nodeType!==11)throw Error(e(299));return o(h,d,null,p)},reactDom_production.flushSync=function(h){var d=l.T,p=i.p;try{if(l.T=null,i.p=2,h)return h()}finally{l.T=d,i.p=p,i.d.f()}},reactDom_production.preconnect=function(h,d){typeof h=="string"&&(d?(d=d.crossOrigin,d=typeof d=="string"?d==="use-credentials"?d:"":void 0):d=null,i.d.C(h,d))},reactDom_production.prefetchDNS=function(h){typeof h=="string"&&i.d.D(h)},reactDom_production.preinit=function(h,d){if(typeof h=="string"&&d&&typeof d.as=="string"){var p=d.as,g=u(p,d.crossOrigin),m=typeof d.integrity=="string"?d.integrity:void 0,v=typeof d.fetchPriority=="string"?d.fetchPriority:void 0;p==="style"?i.d.S(h,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:g,integrity:m,fetchPriority:v}):p==="script"&&i.d.X(h,{crossOrigin:g,integrity:m,fetchPriority:v,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},reactDom_production.preinitModule=function(h,d){if(typeof h=="string")if(typeof d=="object"&&d!==null){if(d.as==null||d.as==="script"){var p=u(d.as,d.crossOrigin);i.d.M(h,{crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0})}}else d==null&&i.d.M(h)},reactDom_production.preload=function(h,d){if(typeof h=="string"&&typeof d=="object"&&d!==null&&typeof d.as=="string"){var p=d.as,g=u(p,d.crossOrigin);i.d.L(h,p,{crossOrigin:g,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0,type:typeof d.type=="string"?d.type:void 0,fetchPriority:typeof d.fetchPriority=="string"?d.fetchPriority:void 0,referrerPolicy:typeof d.referrerPolicy=="string"?d.referrerPolicy:void 0,imageSrcSet:typeof d.imageSrcSet=="string"?d.imageSrcSet:void 0,imageSizes:typeof d.imageSizes=="string"?d.imageSizes:void 0,media:typeof d.media=="string"?d.media:void 0})}},reactDom_production.preloadModule=function(h,d){if(typeof h=="string")if(d){var p=u(d.as,d.crossOrigin);i.d.m(h,{as:typeof d.as=="string"&&d.as!=="script"?d.as:void 0,crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0})}else i.d.m(h)},reactDom_production.requestFormReset=function(h){i.d.r(h)},reactDom_production.unstable_batchedUpdates=function(h,d){return h(d)},reactDom_production.useFormState=function(h,d,p){return l.H.useFormState(h,d,p)},reactDom_production.useFormStatus=function(){return l.H.useHostTransitionStatus()},reactDom_production.version="19.2.8",reactDom_production}var hasRequiredReactDom;function requireReactDom(){if(hasRequiredReactDom)return reactDom.exports;hasRequiredReactDom=1;function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),reactDom.exports=requireReactDom_production(),reactDom.exports}var hasRequiredReactDomClient_production;function requireReactDomClient_production(){if(hasRequiredReactDomClient_production)return reactDomClient_production;hasRequiredReactDomClient_production=1;var n=requireScheduler(),e=requireReact(),t=requireReactDom();function i(a){var c="https://react.dev/errors/"+a;if(1<arguments.length){c+="?args[]="+encodeURIComponent(arguments[1]);for(var f=2;f<arguments.length;f++)c+="&args[]="+encodeURIComponent(arguments[f])}return"Minified React error #"+a+"; visit "+c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(a){return!(!a||a.nodeType!==1&&a.nodeType!==9&&a.nodeType!==11)}function o(a){var c=a,f=a;if(a.alternate)for(;c.return;)c=c.return;else{a=c;do c=a,(c.flags&4098)!==0&&(f=c.return),a=c.return;while(a)}return c.tag===3?f:null}function l(a){if(a.tag===13){var c=a.memoizedState;if(c===null&&(a=a.alternate,a!==null&&(c=a.memoizedState)),c!==null)return c.dehydrated}return null}function u(a){if(a.tag===31){var c=a.memoizedState;if(c===null&&(a=a.alternate,a!==null&&(c=a.memoizedState)),c!==null)return c.dehydrated}return null}function h(a){if(o(a)!==a)throw Error(i(188))}function d(a){var c=a.alternate;if(!c){if(c=o(a),c===null)throw Error(i(188));return c!==a?null:a}for(var f=a,y=c;;){var R=f.return;if(R===null)break;var D=R.alternate;if(D===null){if(y=R.return,y!==null){f=y;continue}break}if(R.child===D.child){for(D=R.child;D;){if(D===f)return h(R),a;if(D===y)return h(R),c;D=D.sibling}throw Error(i(188))}if(f.return!==y.return)f=R,y=D;else{for(var Z=!1,ue=R.child;ue;){if(ue===f){Z=!0,f=R,y=D;break}if(ue===y){Z=!0,y=R,f=D;break}ue=ue.sibling}if(!Z){for(ue=D.child;ue;){if(ue===f){Z=!0,f=D,y=R;break}if(ue===y){Z=!0,y=D,f=R;break}ue=ue.sibling}if(!Z)throw Error(i(189))}}if(f.alternate!==y)throw Error(i(190))}if(f.tag!==3)throw Error(i(188));return f.stateNode.current===f?a:c}function p(a){var c=a.tag;if(c===5||c===26||c===27||c===6)return a;for(a=a.child;a!==null;){if(c=p(a),c!==null)return c;a=a.sibling}return null}var g=Object.assign,m=Symbol.for("react.element"),v=Symbol.for("react.transitional.element"),S=Symbol.for("react.portal"),E=Symbol.for("react.fragment"),x=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),C=Symbol.for("react.consumer"),T=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),P=Symbol.for("react.suspense"),q=Symbol.for("react.suspense_list"),O=Symbol.for("react.memo"),G=Symbol.for("react.lazy"),fe=Symbol.for("react.activity"),M=Symbol.for("react.memo_cache_sentinel"),ee=Symbol.iterator;function Se(a){return a===null||typeof a!="object"?null:(a=ee&&a[ee]||a["@@iterator"],typeof a=="function"?a:null)}var re=Symbol.for("react.client.reference");function Ae(a){if(a==null)return null;if(typeof a=="function")return a.$$typeof===re?null:a.displayName||a.name||null;if(typeof a=="string")return a;switch(a){case E:return"Fragment";case A:return"Profiler";case x:return"StrictMode";case P:return"Suspense";case q:return"SuspenseList";case fe:return"Activity"}if(typeof a=="object")switch(a.$$typeof){case S:return"Portal";case T:return a.displayName||"Context";case C:return(a._context.displayName||"Context")+".Consumer";case F:var c=a.render;return a=a.displayName,a||(a=c.displayName||c.name||"",a=a!==""?"ForwardRef("+a+")":"ForwardRef"),a;case O:return c=a.displayName||null,c!==null?c:Ae(a.type)||"Memo";case G:c=a._payload,a=a._init;try{return Ae(a(c))}catch{}}return null}var ke=Array.isArray,he=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Oe=t.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ce={pending:!1,data:null,method:null,action:null},Ue=[],$=-1;function W(a){return{current:a}}function de(a){0>$||(a.current=Ue[$],Ue[$]=null,$--)}function te(a,c){$++,Ue[$]=a.current,a.current=c}var Te=W(null),je=W(null),He=W(null),We=W(null);function me(a,c){switch(te(He,c),te(je,a),te(Te,null),c.nodeType){case 9:case 11:a=(a=c.documentElement)&&(a=a.namespaceURI)?Of(a):0;break;default:if(a=c.tagName,c=c.namespaceURI)c=Of(c),a=Mf(c,a);else switch(a){case"svg":a=1;break;case"math":a=2;break;default:a=0}}de(Te),te(Te,a)}function ge(){de(Te),de(je),de(He)}function Be(a){a.memoizedState!==null&&te(We,a);var c=Te.current,f=Mf(c,a.type);c!==f&&(te(je,a),te(Te,f))}function ie(a){je.current===a&&(de(Te),de(je)),We.current===a&&(de(We),ao._currentValue=ce)}var B,N;function k(a){if(B===void 0)try{throw Error()}catch(f){var c=f.stack.trim().match(/\n( *(at )?)/);B=c&&c[1]||"",N=-1<f.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<f.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+B+a+N}var H=!1;function ne(a,c){if(!a||H)return"";H=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var y={DetermineComponentFrameRoot:function(){try{if(c){var ft=function(){throw Error()};if(Object.defineProperty(ft.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ft,[])}catch(st){var rt=st}Reflect.construct(a,[],ft)}else{try{ft.call()}catch(st){rt=st}a.call(ft.prototype)}}else{try{throw Error()}catch(st){rt=st}(ft=a())&&typeof ft.catch=="function"&&ft.catch(function(){})}}catch(st){if(st&&rt&&typeof st.stack=="string")return[st.stack,rt.stack]}return[null,null]}};y.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var R=Object.getOwnPropertyDescriptor(y.DetermineComponentFrameRoot,"name");R&&R.configurable&&Object.defineProperty(y.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var D=y.DetermineComponentFrameRoot(),Z=D[0],ue=D[1];if(Z&&ue){var $e=Z.split(`
@@ -9,7 +9,7 @@ Error generating stack: `+y.message+`
9
9
  `+y.stack}}var J=Object.prototype.hasOwnProperty,_e=n.unstable_scheduleCallback,Ie=n.unstable_cancelCallback,ye=n.unstable_shouldYield,at=n.unstable_requestPaint,ht=n.unstable_now,Je=n.unstable_getCurrentPriorityLevel,gt=n.unstable_ImmediatePriority,Y=n.unstable_UserBlockingPriority,U=n.unstable_NormalPriority,z=n.unstable_LowPriority,j=n.unstable_IdlePriority,Ne=n.log,Ve=n.unstable_setDisableYieldValue,Le=null,mt=null;function St(a){if(typeof Ne=="function"&&Ve(a),mt&&typeof mt.setStrictMode=="function")try{mt.setStrictMode(Le,a)}catch{}}var Rt=Math.clz32?Math.clz32:on,kt=Math.log,Ft=Math.LN2;function on(a){return a>>>=0,a===0?32:31-(kt(a)/Ft|0)|0}var er=256,Ut=262144,xr=4194304;function Bt(a){var c=a&42;if(c!==0)return c;switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return a&261888;case 262144:case 524288:case 1048576:case 2097152:return a&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return a&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return a}}function hr(a,c,f){var y=a.pendingLanes;if(y===0)return 0;var R=0,D=a.suspendedLanes,Z=a.pingedLanes;a=a.warmLanes;var ue=y&134217727;return ue!==0?(y=ue&~D,y!==0?R=Bt(y):(Z&=ue,Z!==0?R=Bt(Z):f||(f=ue&~a,f!==0&&(R=Bt(f))))):(ue=y&~D,ue!==0?R=Bt(ue):Z!==0?R=Bt(Z):f||(f=y&~a,f!==0&&(R=Bt(f)))),R===0?0:c!==0&&c!==R&&(c&D)===0&&(D=R&-R,f=c&-c,D>=f||D===32&&(f&4194048)!==0)?c:R}function ir(a,c){return(a.pendingLanes&~(a.suspendedLanes&~a.pingedLanes)&c)===0}function Wr(a,c){switch(a){case 1:case 2:case 4:case 8:case 64:return c+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return c+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function V(){var a=xr;return xr<<=1,(xr&62914560)===0&&(xr=4194304),a}function K(a){for(var c=[],f=0;31>f;f++)c.push(a);return c}function ze(a,c){a.pendingLanes|=c,c!==268435456&&(a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0)}function Ke(a,c,f,y,R,D){var Z=a.pendingLanes;a.pendingLanes=f,a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0,a.expiredLanes&=f,a.entangledLanes&=f,a.errorRecoveryDisabledLanes&=f,a.shellSuspendCounter=0;var ue=a.entanglements,$e=a.expirationTimes,et=a.hiddenUpdates;for(f=Z&~f;0<f;){var ct=31-Rt(f),ft=1<<ct;ue[ct]=0,$e[ct]=-1;var rt=et[ct];if(rt!==null)for(et[ct]=null,ct=0;ct<rt.length;ct++){var st=rt[ct];st!==null&&(st.lane&=-536870913)}f&=~ft}y!==0&&lt(a,y,0),D!==0&&R===0&&a.tag!==0&&(a.suspendedLanes|=D&~(Z&~c))}function lt(a,c,f){a.pendingLanes|=c,a.suspendedLanes&=~c;var y=31-Rt(c);a.entangledLanes|=c,a.entanglements[y]=a.entanglements[y]|1073741824|f&261930}function jt(a,c){var f=a.entangledLanes|=c;for(a=a.entanglements;f;){var y=31-Rt(f),R=1<<y;R&c|a[y]&c&&(a[y]|=c),f&=~R}}function Wt(a,c){var f=c&-c;return f=(f&42)!==0?1:ln(f),(f&(a.suspendedLanes|c))!==0?0:f}function ln(a){switch(a){case 2:a=1;break;case 8:a=4;break;case 32:a=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:a=128;break;case 268435456:a=134217728;break;default:a=0}return a}function Er(a){return a&=-a,2<a?8<a?(a&134217727)!==0?32:268435456:8:2}function ar(){var a=Oe.p;return a!==0?a:(a=window.event,a===void 0?32:ch(a.type))}function Sn(a,c){var f=Oe.p;try{return Oe.p=a,c()}finally{Oe.p=f}}var Kr=Math.random().toString(36).slice(2),zt="__reactFiber$"+Kr,pr="__reactProps$"+Kr,Pr="__reactContainer$"+Kr,zr="__reactEvents$"+Kr,Lt="__reactListeners$"+Kr,Tt="__reactHandles$"+Kr,gr="__reactResources$"+Kr,li="__reactMarker$"+Kr;function Sr(a){delete a[zt],delete a[pr],delete a[zr],delete a[Lt],delete a[Tt]}function lr(a){var c=a[zt];if(c)return c;for(var f=a.parentNode;f;){if(c=f[Pr]||f[zt]){if(f=c.alternate,c.child!==null||f!==null&&f.child!==null)for(a=Kf(a);a!==null;){if(f=a[zt])return f;a=Kf(a)}return c}a=f,f=a.parentNode}return null}function ci(a){if(a=a[zt]||a[Pr]){var c=a.tag;if(c===5||c===6||c===13||c===31||c===26||c===27||c===3)return a}return null}function kr(a){var c=a.tag;if(c===5||c===26||c===27||c===6)return a.stateNode;throw Error(i(33))}function xn(a){var c=a[gr];return c||(c=a[gr]={hoistableStyles:new Map,hoistableScripts:new Map}),c}function Rr(a){a[li]=!0}var vi=new Set,wi={};function En(a,c){gn(a,c),gn(a+"Capture",c)}function gn(a,c){for(wi[a]=c,a=0;a<c.length;a++)vi.add(c[a])}var Rn=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),ws={},_={};function b(a){return J.call(_,a)?!0:J.call(ws,a)?!1:Rn.test(a)?_[a]=!0:(ws[a]=!0,!1)}function w(a,c,f){if(b(c))if(f===null)a.removeAttribute(c);else{switch(typeof f){case"undefined":case"function":case"symbol":a.removeAttribute(c);return;case"boolean":var y=c.toLowerCase().slice(0,5);if(y!=="data-"&&y!=="aria-"){a.removeAttribute(c);return}}a.setAttribute(c,""+f)}}function I(a,c,f){if(f===null)a.removeAttribute(c);else{switch(typeof f){case"undefined":case"function":case"symbol":case"boolean":a.removeAttribute(c);return}a.setAttribute(c,""+f)}}function L(a,c,f,y){if(y===null)a.removeAttribute(f);else{switch(typeof y){case"undefined":case"function":case"symbol":case"boolean":a.removeAttribute(f);return}a.setAttributeNS(c,f,""+y)}}function Q(a){switch(typeof a){case"bigint":case"boolean":case"number":case"string":case"undefined":return a;case"object":return a;default:return""}}function se(a){var c=a.type;return(a=a.nodeName)&&a.toLowerCase()==="input"&&(c==="checkbox"||c==="radio")}function xe(a,c,f){var y=Object.getOwnPropertyDescriptor(a.constructor.prototype,c);if(!a.hasOwnProperty(c)&&typeof y<"u"&&typeof y.get=="function"&&typeof y.set=="function"){var R=y.get,D=y.set;return Object.defineProperty(a,c,{configurable:!0,get:function(){return R.call(this)},set:function(Z){f=""+Z,D.call(this,Z)}}),Object.defineProperty(a,c,{enumerable:y.enumerable}),{getValue:function(){return f},setValue:function(Z){f=""+Z},stopTracking:function(){a._valueTracker=null,delete a[c]}}}}function be(a){if(!a._valueTracker){var c=se(a)?"checked":"value";a._valueTracker=xe(a,c,""+a[c])}}function ve(a){if(!a)return!1;var c=a._valueTracker;if(!c)return!0;var f=c.getValue(),y="";return a&&(y=se(a)?a.checked?"true":"false":a.value),a=y,a!==f?(c.setValue(a),!0):!1}function we(a){if(a=a||(typeof document<"u"?document:void 0),typeof a>"u")return null;try{return a.activeElement||a.body}catch{return a.body}}var Ce=/[\n"\\]/g;function Fe(a){return a.replace(Ce,function(c){return"\\"+c.charCodeAt(0).toString(16)+" "})}function Me(a,c,f,y,R,D,Z,ue){a.name="",Z!=null&&typeof Z!="function"&&typeof Z!="symbol"&&typeof Z!="boolean"?a.type=Z:a.removeAttribute("type"),c!=null?Z==="number"?(c===0&&a.value===""||a.value!=c)&&(a.value=""+Q(c)):a.value!==""+Q(c)&&(a.value=""+Q(c)):Z!=="submit"&&Z!=="reset"||a.removeAttribute("value"),c!=null?Ye(a,Z,Q(c)):f!=null?Ye(a,Z,Q(f)):y!=null&&a.removeAttribute("value"),R==null&&D!=null&&(a.defaultChecked=!!D),R!=null&&(a.checked=R&&typeof R!="function"&&typeof R!="symbol"),ue!=null&&typeof ue!="function"&&typeof ue!="symbol"&&typeof ue!="boolean"?a.name=""+Q(ue):a.removeAttribute("name")}function Ze(a,c,f,y,R,D,Z,ue){if(D!=null&&typeof D!="function"&&typeof D!="symbol"&&typeof D!="boolean"&&(a.type=D),c!=null||f!=null){if(!(D!=="submit"&&D!=="reset"||c!=null)){be(a);return}f=f!=null?""+Q(f):"",c=c!=null?""+Q(c):f,ue||c===a.value||(a.value=c),a.defaultValue=c}y=y??R,y=typeof y!="function"&&typeof y!="symbol"&&!!y,a.checked=ue?a.checked:!!y,a.defaultChecked=!!y,Z!=null&&typeof Z!="function"&&typeof Z!="symbol"&&typeof Z!="boolean"&&(a.name=Z),be(a)}function Ye(a,c,f){c==="number"&&we(a.ownerDocument)===a||a.defaultValue===""+f||(a.defaultValue=""+f)}function tt(a,c,f,y){if(a=a.options,c){c={};for(var R=0;R<f.length;R++)c["$"+f[R]]=!0;for(f=0;f<a.length;f++)R=c.hasOwnProperty("$"+a[f].value),a[f].selected!==R&&(a[f].selected=R),R&&y&&(a[f].defaultSelected=!0)}else{for(f=""+Q(f),c=null,R=0;R<a.length;R++){if(a[R].value===f){a[R].selected=!0,y&&(a[R].defaultSelected=!0);return}c!==null||a[R].disabled||(c=a[R])}c!==null&&(c.selected=!0)}}function ae(a,c,f){if(c!=null&&(c=""+Q(c),c!==a.value&&(a.value=c),f==null)){a.defaultValue!==c&&(a.defaultValue=c);return}a.defaultValue=f!=null?""+Q(f):""}function Re(a,c,f,y){if(c==null){if(y!=null){if(f!=null)throw Error(i(92));if(ke(y)){if(1<y.length)throw Error(i(93));y=y[0]}f=y}f==null&&(f=""),c=f}f=Q(c),a.defaultValue=f,y=a.textContent,y===f&&y!==""&&y!==null&&(a.value=y),be(a)}function De(a,c){if(c){var f=a.firstChild;if(f&&f===a.lastChild&&f.nodeType===3){f.nodeValue=c;return}}a.textContent=c}var Pe=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Qe(a,c,f){var y=c.indexOf("--")===0;f==null||typeof f=="boolean"||f===""?y?a.setProperty(c,""):c==="float"?a.cssFloat="":a[c]="":y?a.setProperty(c,f):typeof f!="number"||f===0||Pe.has(c)?c==="float"?a.cssFloat=f:a[c]=(""+f).trim():a[c]=f+"px"}function it(a,c,f){if(c!=null&&typeof c!="object")throw Error(i(62));if(a=a.style,f!=null){for(var y in f)!f.hasOwnProperty(y)||c!=null&&c.hasOwnProperty(y)||(y.indexOf("--")===0?a.setProperty(y,""):y==="float"?a.cssFloat="":a[y]="");for(var R in c)y=c[R],c.hasOwnProperty(R)&&f[R]!==y&&Qe(a,R,y)}else for(var D in c)c.hasOwnProperty(D)&&Qe(a,D,c[D])}function _t(a){if(a.indexOf("-")===-1)return!1;switch(a){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var pt=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),Dt=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function bt(a){return Dt.test(""+a)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":a}function vt(){}var Jt=null;function Qt(a){return a=a.target||a.srcElement||window,a.correspondingUseElement&&(a=a.correspondingUseElement),a.nodeType===3?a.parentNode:a}var qt=null,Dr=null;function jr(a){var c=ci(a);if(c&&(a=c.stateNode)){var f=a[pr]||null;e:switch(a=c.stateNode,c.type){case"input":if(Me(a,f.value,f.defaultValue,f.defaultValue,f.checked,f.defaultChecked,f.type,f.name),c=f.name,f.type==="radio"&&c!=null){for(f=a;f.parentNode;)f=f.parentNode;for(f=f.querySelectorAll('input[name="'+Fe(""+c)+'"][type="radio"]'),c=0;c<f.length;c++){var y=f[c];if(y!==a&&y.form===a.form){var R=y[pr]||null;if(!R)throw Error(i(90));Me(y,R.value,R.defaultValue,R.defaultValue,R.checked,R.defaultChecked,R.type,R.name)}}for(c=0;c<f.length;c++)y=f[c],y.form===a.form&&ve(y)}break e;case"textarea":ae(a,f.value,f.defaultValue);break e;case"select":c=f.value,c!=null&&tt(a,!!f.multiple,c,!1)}}}var $r=!1;function cr(a,c,f){if($r)return a(c,f);$r=!0;try{var y=a(c);return y}finally{if($r=!1,(qt!==null||Dr!==null)&&(el(),qt&&(c=qt,a=Dr,Dr=qt=null,jr(c),a)))for(c=0;c<a.length;c++)jr(a[c])}}function Yt(a,c){var f=a.stateNode;if(f===null)return null;var y=f[pr]||null;if(y===null)return null;f=y[c];e:switch(c){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(y=!y.disabled)||(a=a.type,y=!(a==="button"||a==="input"||a==="select"||a==="textarea")),a=!y;break e;default:a=!1}if(a)return null;if(f&&typeof f!="function")throw Error(i(231,c,typeof f));return f}var sr=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Or=!1;if(sr)try{var vn={};Object.defineProperty(vn,"passive",{get:function(){Or=!0}}),window.addEventListener("test",vn,vn),window.removeEventListener("test",vn,vn)}catch{Or=!1}var nn=null,mn=null,Tn=null;function yn(){if(Tn)return Tn;var a,c=mn,f=c.length,y,R="value"in nn?nn.value:nn.textContent,D=R.length;for(a=0;a<f&&c[a]===R[a];a++);var Z=f-a;for(y=1;y<=Z&&c[f-y]===R[D-y];y++);return Tn=R.slice(a,1<y?1-y:void 0)}function Un(a){var c=a.keyCode;return"charCode"in a?(a=a.charCode,a===0&&c===13&&(a=13)):a=c,a===10&&(a=13),32<=a||a===13?a:0}function wr(){return!0}function Mr(){return!1}function Nr(a){function c(f,y,R,D,Z){this._reactName=f,this._targetInst=R,this.type=y,this.nativeEvent=D,this.target=Z,this.currentTarget=null;for(var ue in a)a.hasOwnProperty(ue)&&(f=a[ue],this[ue]=f?f(D):D[ue]);return this.isDefaultPrevented=(D.defaultPrevented!=null?D.defaultPrevented:D.returnValue===!1)?wr:Mr,this.isPropagationStopped=Mr,this}return g(c.prototype,{preventDefault:function(){this.defaultPrevented=!0;var f=this.nativeEvent;f&&(f.preventDefault?f.preventDefault():typeof f.returnValue!="unknown"&&(f.returnValue=!1),this.isDefaultPrevented=wr)},stopPropagation:function(){var f=this.nativeEvent;f&&(f.stopPropagation?f.stopPropagation():typeof f.cancelBubble!="unknown"&&(f.cancelBubble=!0),this.isPropagationStopped=wr)},persist:function(){},isPersistent:wr}),c}var Lr={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},zn=Nr(Lr),bn=g({},Lr,{view:0,detail:0}),zi=Nr(bn),Vn,en,sn,tn=g({},bn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Tr,button:0,buttons:0,relatedTarget:function(a){return a.relatedTarget===void 0?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){return"movementX"in a?a.movementX:(a!==sn&&(sn&&a.type==="mousemove"?(Vn=a.screenX-sn.screenX,en=a.screenY-sn.screenY):en=Vn=0,sn=a),Vn)},movementY:function(a){return"movementY"in a?a.movementY:en}}),ur=Nr(tn),Pn=g({},tn,{dataTransfer:0}),gi=Nr(Pn),Fr=g({},bn,{relatedTarget:0}),Hn=Nr(Fr),Wn=g({},Lr,{animationName:0,elapsedTime:0,pseudoElement:0}),Kn=Nr(Wn),Ms=g({},Lr,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),wa=Nr(Ms),Zn=g({},Lr,{data:0}),xa=Nr(Zn),uo={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},un={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},xi={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Vi(a){var c=this.nativeEvent;return c.getModifierState?c.getModifierState(a):(a=xi[a])?!!c[a]:!1}function Tr(){return Vi}var Gn=g({},bn,{key:function(a){if(a.key){var c=uo[a.key]||a.key;if(c!=="Unidentified")return c}return a.type==="keypress"?(a=Un(a),a===13?"Enter":String.fromCharCode(a)):a.type==="keydown"||a.type==="keyup"?un[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Tr,charCode:function(a){return a.type==="keypress"?Un(a):0},keyCode:function(a){return a.type==="keydown"||a.type==="keyup"?a.keyCode:0},which:function(a){return a.type==="keypress"?Un(a):a.type==="keydown"||a.type==="keyup"?a.keyCode:0}}),xs=Nr(Gn),Ea=g({},tn,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Zr=Nr(Ea),Hi=g({},bn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Tr}),Wi=Nr(Hi),Ra=g({},Lr,{propertyName:0,elapsedTime:0,pseudoElement:0}),Ei=Nr(Ra),Ki=g({},tn,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),Ta=Nr(Ki),Jn=g({},Lr,{newState:0,oldState:0}),wl=Nr(Jn),Aa=[9,13,27,32],kn=sr&&"CompositionEvent"in window,ui=null;sr&&"documentMode"in document&&(ui=document.documentMode);var fo=sr&&"TextEvent"in window&&!ui,ho=sr&&(!kn||ui&&8<ui&&11>=ui),po=" ",go=!1;function Bs(a,c){switch(a){case"keyup":return Aa.indexOf(c.keyCode)!==-1;case"keydown":return c.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ca(a){return a=a.detail,typeof a=="object"&&"data"in a?a.data:null}var Zi=!1;function xl(a,c){switch(a){case"compositionend":return Ca(c);case"keypress":return c.which!==32?null:(go=!0,po);case"textInput":return a=c.data,a===po&&go?null:a;default:return null}}function Ia(a,c){if(Zi)return a==="compositionend"||!kn&&Bs(a,c)?(a=yn(),Tn=mn=nn=null,Zi=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(c.ctrlKey||c.altKey||c.metaKey)||c.ctrlKey&&c.altKey){if(c.char&&1<c.char.length)return c.char;if(c.which)return String.fromCharCode(c.which)}return null;case"compositionend":return ho&&c.locale!=="ko"?null:c.data;default:return null}}var Gi={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function qs(a){var c=a&&a.nodeName&&a.nodeName.toLowerCase();return c==="input"?!!Gi[a.type]:c==="textarea"}function mo(a,c,f,y){qt?Dr?Dr.push(y):Dr=[y]:qt=y,c=ol(c,"onChange"),0<c.length&&(f=new zn("onChange","change",null,f,y),a.push({event:f,listeners:c}))}var Ri=null,Ti=null;function yo(a){Uf(a,0)}function zs(a){var c=kr(a);if(ve(c))return a}function Ji(a,c){if(a==="change")return c}var Da=!1;if(sr){var Es;if(sr){var Vs="oninput"in document;if(!Vs){var Hs=document.createElement("div");Hs.setAttribute("oninput","return;"),Vs=typeof Hs.oninput=="function"}Es=Vs}else Es=!1;Da=Es&&(!document.documentMode||9<document.documentMode)}function bo(){Ri&&(Ri.detachEvent("onpropertychange",$t),Ti=Ri=null)}function $t(a){if(a.propertyName==="value"&&zs(Ti)){var c=[];mo(c,Ti,a,Qt(a)),cr(yo,c)}}function ot(a,c,f){a==="focusin"?(bo(),Ri=c,Ti=f,Ri.attachEvent("onpropertychange",$t)):a==="focusout"&&bo()}function nt(a){if(a==="selectionchange"||a==="keyup"||a==="keydown")return zs(Ti)}function ut(a,c){if(a==="click")return zs(c)}function yt(a,c){if(a==="input"||a==="change")return zs(c)}function At(a,c){return a===c&&(a!==0||1/a===1/c)||a!==a&&c!==c}var wt=typeof Object.is=="function"?Object.is:At;function oe(a,c){if(wt(a,c))return!0;if(typeof a!="object"||a===null||typeof c!="object"||c===null)return!1;var f=Object.keys(a),y=Object.keys(c);if(f.length!==y.length)return!1;for(y=0;y<f.length;y++){var R=f[y];if(!J.call(c,R)||!wt(a[R],c[R]))return!1}return!0}function _n(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function pe(a,c){var f=_n(a);a=0;for(var y;f;){if(f.nodeType===3){if(y=a+f.textContent.length,a<=c&&y>=c)return{node:f,offset:c-a};a=y}e:{for(;f;){if(f.nextSibling){f=f.nextSibling;break e}f=f.parentNode}f=void 0}f=_n(f)}}function di(a,c){return a&&c?a===c?!0:a&&a.nodeType===3?!1:c&&c.nodeType===3?di(a,c.parentNode):"contains"in a?a.contains(c):a.compareDocumentPosition?!!(a.compareDocumentPosition(c)&16):!1:!1}function Rs(a){a=a!=null&&a.ownerDocument!=null&&a.ownerDocument.defaultView!=null?a.ownerDocument.defaultView:window;for(var c=we(a.document);c instanceof a.HTMLIFrameElement;){try{var f=typeof c.contentWindow.location.href=="string"}catch{f=!1}if(f)a=c.contentWindow;else break;c=we(a.document)}return c}function Qi(a){var c=a&&a.nodeName&&a.nodeName.toLowerCase();return c&&(c==="input"&&(a.type==="text"||a.type==="search"||a.type==="tel"||a.type==="url"||a.type==="password")||c==="textarea"||a.contentEditable==="true")}var Ws=sr&&"documentMode"in document&&11>=document.documentMode,mr=null,An=null,Ln=null,mi=!1;function Ks(a,c,f){var y=f.window===f?f.document:f.nodeType===9?f:f.ownerDocument;mi||mr==null||mr!==we(y)||(y=mr,"selectionStart"in y&&Qi(y)?y={start:y.selectionStart,end:y.selectionEnd}:(y=(y.ownerDocument&&y.ownerDocument.defaultView||window).getSelection(),y={anchorNode:y.anchorNode,anchorOffset:y.anchorOffset,focusNode:y.focusNode,focusOffset:y.focusOffset}),Ln&&oe(Ln,y)||(Ln=y,y=ol(An,"onSelect"),0<y.length&&(c=new zn("onSelect","select",null,c,f),a.push({event:c,listeners:y}),c.target=mr)))}function Qn(a,c){var f={};return f[a.toLowerCase()]=c.toLowerCase(),f["Webkit"+a]="webkit"+c,f["Moz"+a]="moz"+c,f}var Nt={animationend:Qn("Animation","AnimationEnd"),animationiteration:Qn("Animation","AnimationIteration"),animationstart:Qn("Animation","AnimationStart"),transitionrun:Qn("Transition","TransitionRun"),transitionstart:Qn("Transition","TransitionStart"),transitioncancel:Qn("Transition","TransitionCancel"),transitionend:Qn("Transition","TransitionEnd")},Xt={},Pt={};sr&&(Pt=document.createElement("div").style,"AnimationEvent"in window||(delete Nt.animationend.animation,delete Nt.animationiteration.animation,delete Nt.animationstart.animation),"TransitionEvent"in window||delete Nt.transitionend.transition);function Ar(a){if(Xt[a])return Xt[a];if(!Nt[a])return a;var c=Nt[a],f;for(f in c)if(c.hasOwnProperty(f)&&f in Pt)return Xt[a]=c[f];return a}var Gr=Ar("animationend"),Ts=Ar("animationiteration"),Xn=Ar("animationstart"),_o=Ar("transitionrun"),Zs=Ar("transitionstart"),Na=Ar("transitioncancel"),Ai=Ar("transitionend"),du=new Map,El="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");El.push("scrollEnd");function fi(a,c){du.set(a,c),En(c,[a])}var So=typeof reportError=="function"?reportError:function(a){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var c=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof a=="object"&&a!==null&&typeof a.message=="string"?String(a.message):String(a),error:a});if(!window.dispatchEvent(c))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",a);return}console.error(a)},Yn=[],Gs=0,Rl=0;function vo(){for(var a=Gs,c=Rl=Gs=0;c<a;){var f=Yn[c];Yn[c++]=null;var y=Yn[c];Yn[c++]=null;var R=Yn[c];Yn[c++]=null;var D=Yn[c];if(Yn[c++]=null,y!==null&&R!==null){var Z=y.pending;Z===null?R.next=R:(R.next=Z.next,Z.next=R),y.pending=R}D!==0&&fu(f,R,D)}}function wo(a,c,f,y){Yn[Gs++]=a,Yn[Gs++]=c,Yn[Gs++]=f,Yn[Gs++]=y,Rl|=y,a.lanes|=y,a=a.alternate,a!==null&&(a.lanes|=y)}function Tl(a,c,f,y){return wo(a,c,f,y),xo(a)}function As(a,c){return wo(a,null,null,c),xo(a)}function fu(a,c,f){a.lanes|=f;var y=a.alternate;y!==null&&(y.lanes|=f);for(var R=!1,D=a.return;D!==null;)D.childLanes|=f,y=D.alternate,y!==null&&(y.childLanes|=f),D.tag===22&&(a=D.stateNode,a===null||a._visibility&1||(R=!0)),a=D,D=D.return;return a.tag===3?(D=a.stateNode,R&&c!==null&&(R=31-Rt(f),a=D.hiddenUpdates,y=a[R],y===null?a[R]=[c]:y.push(c),c.lane=f|536870912),D):null}function xo(a){if(50<Ya)throw Ya=0,kc=null,Error(i(185));for(var c=a.return;c!==null;)a=c,c=a.return;return a.tag===3?a.stateNode:null}var Js={};function wh(a,c,f,y){this.tag=a,this.key=f,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=c,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=y,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function jn(a,c,f,y){return new wh(a,c,f,y)}function Al(a){return a=a.prototype,!(!a||!a.isReactComponent)}function Ci(a,c){var f=a.alternate;return f===null?(f=jn(a.tag,c,a.key,a.mode),f.elementType=a.elementType,f.type=a.type,f.stateNode=a.stateNode,f.alternate=a,a.alternate=f):(f.pendingProps=c,f.type=a.type,f.flags=0,f.subtreeFlags=0,f.deletions=null),f.flags=a.flags&65011712,f.childLanes=a.childLanes,f.lanes=a.lanes,f.child=a.child,f.memoizedProps=a.memoizedProps,f.memoizedState=a.memoizedState,f.updateQueue=a.updateQueue,c=a.dependencies,f.dependencies=c===null?null:{lanes:c.lanes,firstContext:c.firstContext},f.sibling=a.sibling,f.index=a.index,f.ref=a.ref,f.refCleanup=a.refCleanup,f}function hu(a,c){a.flags&=65011714;var f=a.alternate;return f===null?(a.childLanes=0,a.lanes=c,a.child=null,a.subtreeFlags=0,a.memoizedProps=null,a.memoizedState=null,a.updateQueue=null,a.dependencies=null,a.stateNode=null):(a.childLanes=f.childLanes,a.lanes=f.lanes,a.child=f.child,a.subtreeFlags=0,a.deletions=null,a.memoizedProps=f.memoizedProps,a.memoizedState=f.memoizedState,a.updateQueue=f.updateQueue,a.type=f.type,c=f.dependencies,a.dependencies=c===null?null:{lanes:c.lanes,firstContext:c.firstContext}),a}function Eo(a,c,f,y,R,D){var Z=0;if(y=a,typeof a=="function")Al(a)&&(Z=1);else if(typeof a=="string")Z=Ap(a,f,Te.current)?26:a==="html"||a==="head"||a==="body"?27:5;else e:switch(a){case fe:return a=jn(31,f,c,R),a.elementType=fe,a.lanes=D,a;case E:return Cs(f.children,R,D,c);case x:Z=8,R|=24;break;case A:return a=jn(12,f,c,R|2),a.elementType=A,a.lanes=D,a;case P:return a=jn(13,f,c,R),a.elementType=P,a.lanes=D,a;case q:return a=jn(19,f,c,R),a.elementType=q,a.lanes=D,a;default:if(typeof a=="object"&&a!==null)switch(a.$$typeof){case T:Z=10;break e;case C:Z=9;break e;case F:Z=11;break e;case O:Z=14;break e;case G:Z=16,y=null;break e}Z=29,f=Error(i(130,a===null?"null":typeof a,"")),y=null}return c=jn(Z,f,c,R),c.elementType=a,c.type=y,c.lanes=D,c}function Cs(a,c,f,y){return a=jn(7,a,y,c),a.lanes=f,a}function Cl(a,c,f){return a=jn(6,a,null,c),a.lanes=f,a}function pu(a){var c=jn(18,null,null,0);return c.stateNode=a,c}function Il(a,c,f){return c=jn(4,a.children!==null?a.children:[],a.key,c),c.lanes=f,c.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation},c}var gu=new WeakMap;function ei(a,c){if(typeof a=="object"&&a!==null){var f=gu.get(a);return f!==void 0?f:(c={value:a,source:c,stack:Ee(c)},gu.set(a,c),c)}return{value:a,source:c,stack:Ee(c)}}var Qs=[],Xs=0,Ro=null,Fa=0,ti=[],ri=0,Xi=null,yi=1,bi="";function Ii(a,c){Qs[Xs++]=Fa,Qs[Xs++]=Ro,Ro=a,Fa=c}function mu(a,c,f){ti[ri++]=yi,ti[ri++]=bi,ti[ri++]=Xi,Xi=a;var y=yi;a=bi;var R=32-Rt(y)-1;y&=~(1<<R),f+=1;var D=32-Rt(c)+R;if(30<D){var Z=R-R%5;D=(y&(1<<Z)-1).toString(32),y>>=Z,R-=Z,yi=1<<32-Rt(c)+R|f<<R|y,bi=D+a}else yi=1<<D|f<<R|y,bi=a}function Dl(a){a.return!==null&&(Ii(a,1),mu(a,1,0))}function Nl(a){for(;a===Ro;)Ro=Qs[--Xs],Qs[Xs]=null,Fa=Qs[--Xs],Qs[Xs]=null;for(;a===Xi;)Xi=ti[--ri],ti[ri]=null,bi=ti[--ri],ti[ri]=null,yi=ti[--ri],ti[ri]=null}function yu(a,c){ti[ri++]=yi,ti[ri++]=bi,ti[ri++]=Xi,yi=c.id,bi=c.overflow,Xi=a}var dn=null,Cr=null,Gt=!1,Yi=null,ni=!1,Fl=Error(i(519));function es(a){var c=Error(i(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Ua(ei(c,a)),Fl}function bu(a){var c=a.stateNode,f=a.type,y=a.memoizedProps;switch(c[zt]=a,c[pr]=y,f){case"dialog":Ht("cancel",c),Ht("close",c);break;case"iframe":case"object":case"embed":Ht("load",c);break;case"video":case"audio":for(f=0;f<to.length;f++)Ht(to[f],c);break;case"source":Ht("error",c);break;case"img":case"image":case"link":Ht("error",c),Ht("load",c);break;case"details":Ht("toggle",c);break;case"input":Ht("invalid",c),Ze(c,y.value,y.defaultValue,y.checked,y.defaultChecked,y.type,y.name,!0);break;case"select":Ht("invalid",c);break;case"textarea":Ht("invalid",c),Re(c,y.value,y.defaultValue,y.children)}f=y.children,typeof f!="string"&&typeof f!="number"&&typeof f!="bigint"||c.textContent===""+f||y.suppressHydrationWarning===!0||jf(c.textContent,f)?(y.popover!=null&&(Ht("beforetoggle",c),Ht("toggle",c)),y.onScroll!=null&&Ht("scroll",c),y.onScrollEnd!=null&&Ht("scrollend",c),y.onClick!=null&&(c.onclick=vt),c=!0):c=!1,c||es(a,!0)}function _u(a){for(dn=a.return;dn;)switch(dn.tag){case 5:case 31:case 13:ni=!1;return;case 27:case 3:ni=!0;return;default:dn=dn.return}}function Ys(a){if(a!==dn)return!1;if(!Gt)return _u(a),Gt=!0,!1;var c=a.tag,f;if((f=c!==3&&c!==27)&&((f=c===5)&&(f=a.type,f=!(f!=="form"&&f!=="button")||Jc(a.type,a.memoizedProps)),f=!f),f&&Cr&&es(a),_u(a),c===13){if(a=a.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(i(317));Cr=Wf(a)}else if(c===31){if(a=a.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(i(317));Cr=Wf(a)}else c===27?(c=Cr,ms(a.type)?(a=tu,tu=null,Cr=a):Cr=c):Cr=dn?si(a.stateNode.nextSibling):null;return!0}function Is(){Cr=dn=null,Gt=!1}function Ul(){var a=Yi;return a!==null&&(Nn===null?Nn=a:Nn.push.apply(Nn,a),Yi=null),a}function Ua(a){Yi===null?Yi=[a]:Yi.push(a)}var Pl=W(null),Ds=null,Di=null;function ts(a,c,f){te(Pl,c._currentValue),c._currentValue=f}function Ni(a){a._currentValue=Pl.current,de(Pl)}function kl(a,c,f){for(;a!==null;){var y=a.alternate;if((a.childLanes&c)!==c?(a.childLanes|=c,y!==null&&(y.childLanes|=c)):y!==null&&(y.childLanes&c)!==c&&(y.childLanes|=c),a===f)break;a=a.return}}function Ll(a,c,f,y){var R=a.child;for(R!==null&&(R.return=a);R!==null;){var D=R.dependencies;if(D!==null){var Z=R.child;D=D.firstContext;e:for(;D!==null;){var ue=D;D=R;for(var $e=0;$e<c.length;$e++)if(ue.context===c[$e]){D.lanes|=f,ue=D.alternate,ue!==null&&(ue.lanes|=f),kl(D.return,f,a),y||(Z=null);break e}D=ue.next}}else if(R.tag===18){if(Z=R.return,Z===null)throw Error(i(341));Z.lanes|=f,D=Z.alternate,D!==null&&(D.lanes|=f),kl(Z,f,a),Z=null}else Z=R.child;if(Z!==null)Z.return=R;else for(Z=R;Z!==null;){if(Z===a){Z=null;break}if(R=Z.sibling,R!==null){R.return=Z.return,Z=R;break}Z=Z.return}R=Z}}function ea(a,c,f,y){a=null;for(var R=c,D=!1;R!==null;){if(!D){if((R.flags&524288)!==0)D=!0;else if((R.flags&262144)!==0)break}if(R.tag===10){var Z=R.alternate;if(Z===null)throw Error(i(387));if(Z=Z.memoizedProps,Z!==null){var ue=R.type;wt(R.pendingProps.value,Z.value)||(a!==null?a.push(ue):a=[ue])}}else if(R===We.current){if(Z=R.alternate,Z===null)throw Error(i(387));Z.memoizedState.memoizedState!==R.memoizedState.memoizedState&&(a!==null?a.push(ao):a=[ao])}R=R.return}a!==null&&Ll(c,a,f,y),c.flags|=262144}function To(a){for(a=a.firstContext;a!==null;){if(!wt(a.context._currentValue,a.memoizedValue))return!0;a=a.next}return!1}function Ns(a){Ds=a,Di=null,a=a.dependencies,a!==null&&(a.firstContext=null)}function fn(a){return Su(Ds,a)}function Ao(a,c){return Ds===null&&Ns(a),Su(a,c)}function Su(a,c){var f=c._currentValue;if(c={context:c,memoizedValue:f,next:null},Di===null){if(a===null)throw Error(i(308));Di=c,a.dependencies={lanes:0,firstContext:c},a.flags|=524288}else Di=Di.next=c;return f}var xh=typeof AbortController<"u"?AbortController:function(){var a=[],c=this.signal={aborted:!1,addEventListener:function(f,y){a.push(y)}};this.abort=function(){c.aborted=!0,a.forEach(function(f){return f()})}},Eh=n.unstable_scheduleCallback,Rh=n.unstable_NormalPriority,Jr={$$typeof:T,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function jl(){return{controller:new xh,data:new Map,refCount:0}}function Pa(a){a.refCount--,a.refCount===0&&Eh(Rh,function(){a.controller.abort()})}var ka=null,$l=0,ta=0,ra=null;function Th(a,c){if(ka===null){var f=ka=[];$l=0,ta=Bc(),ra={status:"pending",value:void 0,then:function(y){f.push(y)}}}return $l++,c.then(vu,vu),c}function vu(){if(--$l===0&&ka!==null){ra!==null&&(ra.status="fulfilled");var a=ka;ka=null,ta=0,ra=null;for(var c=0;c<a.length;c++)(0,a[c])()}}function Ah(a,c){var f=[],y={status:"pending",value:null,reason:null,then:function(R){f.push(R)}};return a.then(function(){y.status="fulfilled",y.value=c;for(var R=0;R<f.length;R++)(0,f[R])(c)},function(R){for(y.status="rejected",y.reason=R,R=0;R<f.length;R++)(0,f[R])(void 0)}),y}var wu=he.S;he.S=function(a,c){of=ht(),typeof c=="object"&&c!==null&&typeof c.then=="function"&&Th(a,c),wu!==null&&wu(a,c)};var Fs=W(null);function Ol(){var a=Fs.current;return a!==null?a:vr.pooledCache}function Co(a,c){c===null?te(Fs,Fs.current):te(Fs,c.pool)}function xu(){var a=Ol();return a===null?null:{parent:Jr._currentValue,pool:a}}var na=Error(i(460)),Ml=Error(i(474)),Io=Error(i(542)),Do={then:function(){}};function Eu(a){return a=a.status,a==="fulfilled"||a==="rejected"}function Ru(a,c,f){switch(f=a[f],f===void 0?a.push(c):f!==c&&(c.then(vt,vt),c=f),c.status){case"fulfilled":return c.value;case"rejected":throw a=c.reason,Au(a),a;default:if(typeof c.status=="string")c.then(vt,vt);else{if(a=vr,a!==null&&100<a.shellSuspendCounter)throw Error(i(482));a=c,a.status="pending",a.then(function(y){if(c.status==="pending"){var R=c;R.status="fulfilled",R.value=y}},function(y){if(c.status==="pending"){var R=c;R.status="rejected",R.reason=y}})}switch(c.status){case"fulfilled":return c.value;case"rejected":throw a=c.reason,Au(a),a}throw Ps=c,na}}function Us(a){try{var c=a._init;return c(a._payload)}catch(f){throw f!==null&&typeof f=="object"&&typeof f.then=="function"?(Ps=f,na):f}}var Ps=null;function Tu(){if(Ps===null)throw Error(i(459));var a=Ps;return Ps=null,a}function Au(a){if(a===na||a===Io)throw Error(i(483))}var ia=null,La=0;function No(a){var c=La;return La+=1,ia===null&&(ia=[]),Ru(ia,a,c)}function ja(a,c){c=c.props.ref,a.ref=c!==void 0?c:null}function Fo(a,c){throw c.$$typeof===m?Error(i(525)):(a=Object.prototype.toString.call(c),Error(i(31,a==="[object Object]"?"object with keys {"+Object.keys(c).join(", ")+"}":a)))}function Cu(a){function c(Ge,qe){if(a){var Xe=Ge.deletions;Xe===null?(Ge.deletions=[qe],Ge.flags|=16):Xe.push(qe)}}function f(Ge,qe){if(!a)return null;for(;qe!==null;)c(Ge,qe),qe=qe.sibling;return null}function y(Ge){for(var qe=new Map;Ge!==null;)Ge.key!==null?qe.set(Ge.key,Ge):qe.set(Ge.index,Ge),Ge=Ge.sibling;return qe}function R(Ge,qe){return Ge=Ci(Ge,qe),Ge.index=0,Ge.sibling=null,Ge}function D(Ge,qe,Xe){return Ge.index=Xe,a?(Xe=Ge.alternate,Xe!==null?(Xe=Xe.index,Xe<qe?(Ge.flags|=67108866,qe):Xe):(Ge.flags|=67108866,qe)):(Ge.flags|=1048576,qe)}function Z(Ge){return a&&Ge.alternate===null&&(Ge.flags|=67108866),Ge}function ue(Ge,qe,Xe,dt){return qe===null||qe.tag!==6?(qe=Cl(Xe,Ge.mode,dt),qe.return=Ge,qe):(qe=R(qe,Xe),qe.return=Ge,qe)}function $e(Ge,qe,Xe,dt){var Ct=Xe.type;return Ct===E?ct(Ge,qe,Xe.props.children,dt,Xe.key):qe!==null&&(qe.elementType===Ct||typeof Ct=="object"&&Ct!==null&&Ct.$$typeof===G&&Us(Ct)===qe.type)?(qe=R(qe,Xe.props),ja(qe,Xe),qe.return=Ge,qe):(qe=Eo(Xe.type,Xe.key,Xe.props,null,Ge.mode,dt),ja(qe,Xe),qe.return=Ge,qe)}function et(Ge,qe,Xe,dt){return qe===null||qe.tag!==4||qe.stateNode.containerInfo!==Xe.containerInfo||qe.stateNode.implementation!==Xe.implementation?(qe=Il(Xe,Ge.mode,dt),qe.return=Ge,qe):(qe=R(qe,Xe.children||[]),qe.return=Ge,qe)}function ct(Ge,qe,Xe,dt,Ct){return qe===null||qe.tag!==7?(qe=Cs(Xe,Ge.mode,dt,Ct),qe.return=Ge,qe):(qe=R(qe,Xe),qe.return=Ge,qe)}function ft(Ge,qe,Xe){if(typeof qe=="string"&&qe!==""||typeof qe=="number"||typeof qe=="bigint")return qe=Cl(""+qe,Ge.mode,Xe),qe.return=Ge,qe;if(typeof qe=="object"&&qe!==null){switch(qe.$$typeof){case v:return Xe=Eo(qe.type,qe.key,qe.props,null,Ge.mode,Xe),ja(Xe,qe),Xe.return=Ge,Xe;case S:return qe=Il(qe,Ge.mode,Xe),qe.return=Ge,qe;case G:return qe=Us(qe),ft(Ge,qe,Xe)}if(ke(qe)||Se(qe))return qe=Cs(qe,Ge.mode,Xe,null),qe.return=Ge,qe;if(typeof qe.then=="function")return ft(Ge,No(qe),Xe);if(qe.$$typeof===T)return ft(Ge,Ao(Ge,qe),Xe);Fo(Ge,qe)}return null}function rt(Ge,qe,Xe,dt){var Ct=qe!==null?qe.key:null;if(typeof Xe=="string"&&Xe!==""||typeof Xe=="number"||typeof Xe=="bigint")return Ct!==null?null:ue(Ge,qe,""+Xe,dt);if(typeof Xe=="object"&&Xe!==null){switch(Xe.$$typeof){case v:return Xe.key===Ct?$e(Ge,qe,Xe,dt):null;case S:return Xe.key===Ct?et(Ge,qe,Xe,dt):null;case G:return Xe=Us(Xe),rt(Ge,qe,Xe,dt)}if(ke(Xe)||Se(Xe))return Ct!==null?null:ct(Ge,qe,Xe,dt,null);if(typeof Xe.then=="function")return rt(Ge,qe,No(Xe),dt);if(Xe.$$typeof===T)return rt(Ge,qe,Ao(Ge,Xe),dt);Fo(Ge,Xe)}return null}function st(Ge,qe,Xe,dt,Ct){if(typeof dt=="string"&&dt!==""||typeof dt=="number"||typeof dt=="bigint")return Ge=Ge.get(Xe)||null,ue(qe,Ge,""+dt,Ct);if(typeof dt=="object"&&dt!==null){switch(dt.$$typeof){case v:return Ge=Ge.get(dt.key===null?Xe:dt.key)||null,$e(qe,Ge,dt,Ct);case S:return Ge=Ge.get(dt.key===null?Xe:dt.key)||null,et(qe,Ge,dt,Ct);case G:return dt=Us(dt),st(Ge,qe,Xe,dt,Ct)}if(ke(dt)||Se(dt))return Ge=Ge.get(Xe)||null,ct(qe,Ge,dt,Ct,null);if(typeof dt.then=="function")return st(Ge,qe,Xe,No(dt),Ct);if(dt.$$typeof===T)return st(Ge,qe,Xe,Ao(qe,dt),Ct);Fo(qe,dt)}return null}function xt(Ge,qe,Xe,dt){for(var Ct=null,tr=null,Et=qe,Mt=qe=0,Zt=null;Et!==null&&Mt<Xe.length;Mt++){Et.index>Mt?(Zt=Et,Et=null):Zt=Et.sibling;var rr=rt(Ge,Et,Xe[Mt],dt);if(rr===null){Et===null&&(Et=Zt);break}a&&Et&&rr.alternate===null&&c(Ge,Et),qe=D(rr,qe,Mt),tr===null?Ct=rr:tr.sibling=rr,tr=rr,Et=Zt}if(Mt===Xe.length)return f(Ge,Et),Gt&&Ii(Ge,Mt),Ct;if(Et===null){for(;Mt<Xe.length;Mt++)Et=ft(Ge,Xe[Mt],dt),Et!==null&&(qe=D(Et,qe,Mt),tr===null?Ct=Et:tr.sibling=Et,tr=Et);return Gt&&Ii(Ge,Mt),Ct}for(Et=y(Et);Mt<Xe.length;Mt++)Zt=st(Et,Ge,Mt,Xe[Mt],dt),Zt!==null&&(a&&Zt.alternate!==null&&Et.delete(Zt.key===null?Mt:Zt.key),qe=D(Zt,qe,Mt),tr===null?Ct=Zt:tr.sibling=Zt,tr=Zt);return a&&Et.forEach(function(vs){return c(Ge,vs)}),Gt&&Ii(Ge,Mt),Ct}function It(Ge,qe,Xe,dt){if(Xe==null)throw Error(i(151));for(var Ct=null,tr=null,Et=qe,Mt=qe=0,Zt=null,rr=Xe.next();Et!==null&&!rr.done;Mt++,rr=Xe.next()){Et.index>Mt?(Zt=Et,Et=null):Zt=Et.sibling;var vs=rt(Ge,Et,rr.value,dt);if(vs===null){Et===null&&(Et=Zt);break}a&&Et&&vs.alternate===null&&c(Ge,Et),qe=D(vs,qe,Mt),tr===null?Ct=vs:tr.sibling=vs,tr=vs,Et=Zt}if(rr.done)return f(Ge,Et),Gt&&Ii(Ge,Mt),Ct;if(Et===null){for(;!rr.done;Mt++,rr=Xe.next())rr=ft(Ge,rr.value,dt),rr!==null&&(qe=D(rr,qe,Mt),tr===null?Ct=rr:tr.sibling=rr,tr=rr);return Gt&&Ii(Ge,Mt),Ct}for(Et=y(Et);!rr.done;Mt++,rr=Xe.next())rr=st(Et,Ge,Mt,rr.value,dt),rr!==null&&(a&&rr.alternate!==null&&Et.delete(rr.key===null?Mt:rr.key),qe=D(rr,qe,Mt),tr===null?Ct=rr:tr.sibling=rr,tr=rr);return a&&Et.forEach(function($p){return c(Ge,$p)}),Gt&&Ii(Ge,Mt),Ct}function _r(Ge,qe,Xe,dt){if(typeof Xe=="object"&&Xe!==null&&Xe.type===E&&Xe.key===null&&(Xe=Xe.props.children),typeof Xe=="object"&&Xe!==null){switch(Xe.$$typeof){case v:e:{for(var Ct=Xe.key;qe!==null;){if(qe.key===Ct){if(Ct=Xe.type,Ct===E){if(qe.tag===7){f(Ge,qe.sibling),dt=R(qe,Xe.props.children),dt.return=Ge,Ge=dt;break e}}else if(qe.elementType===Ct||typeof Ct=="object"&&Ct!==null&&Ct.$$typeof===G&&Us(Ct)===qe.type){f(Ge,qe.sibling),dt=R(qe,Xe.props),ja(dt,Xe),dt.return=Ge,Ge=dt;break e}f(Ge,qe);break}else c(Ge,qe);qe=qe.sibling}Xe.type===E?(dt=Cs(Xe.props.children,Ge.mode,dt,Xe.key),dt.return=Ge,Ge=dt):(dt=Eo(Xe.type,Xe.key,Xe.props,null,Ge.mode,dt),ja(dt,Xe),dt.return=Ge,Ge=dt)}return Z(Ge);case S:e:{for(Ct=Xe.key;qe!==null;){if(qe.key===Ct)if(qe.tag===4&&qe.stateNode.containerInfo===Xe.containerInfo&&qe.stateNode.implementation===Xe.implementation){f(Ge,qe.sibling),dt=R(qe,Xe.children||[]),dt.return=Ge,Ge=dt;break e}else{f(Ge,qe);break}else c(Ge,qe);qe=qe.sibling}dt=Il(Xe,Ge.mode,dt),dt.return=Ge,Ge=dt}return Z(Ge);case G:return Xe=Us(Xe),_r(Ge,qe,Xe,dt)}if(ke(Xe))return xt(Ge,qe,Xe,dt);if(Se(Xe)){if(Ct=Se(Xe),typeof Ct!="function")throw Error(i(150));return Xe=Ct.call(Xe),It(Ge,qe,Xe,dt)}if(typeof Xe.then=="function")return _r(Ge,qe,No(Xe),dt);if(Xe.$$typeof===T)return _r(Ge,qe,Ao(Ge,Xe),dt);Fo(Ge,Xe)}return typeof Xe=="string"&&Xe!==""||typeof Xe=="number"||typeof Xe=="bigint"?(Xe=""+Xe,qe!==null&&qe.tag===6?(f(Ge,qe.sibling),dt=R(qe,Xe),dt.return=Ge,Ge=dt):(f(Ge,qe),dt=Cl(Xe,Ge.mode,dt),dt.return=Ge,Ge=dt),Z(Ge)):f(Ge,qe)}return function(Ge,qe,Xe,dt){try{La=0;var Ct=_r(Ge,qe,Xe,dt);return ia=null,Ct}catch(Et){if(Et===na||Et===Io)throw Et;var tr=jn(29,Et,null,Ge.mode);return tr.lanes=dt,tr.return=Ge,tr}}}var ks=Cu(!0),Iu=Cu(!1),rs=!1;function Bl(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ql(a,c){a=a.updateQueue,c.updateQueue===a&&(c.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,callbacks:null})}function ss(a){return{lane:a,tag:0,payload:null,callback:null,next:null}}function as(a,c,f){var y=a.updateQueue;if(y===null)return null;if(y=y.shared,(nr&2)!==0){var R=y.pending;return R===null?c.next=c:(c.next=R.next,R.next=c),y.pending=c,c=xo(a),fu(a,null,f),c}return wo(a,y,c,f),xo(a)}function $a(a,c,f){if(c=c.updateQueue,c!==null&&(c=c.shared,(f&4194048)!==0)){var y=c.lanes;y&=a.pendingLanes,f|=y,c.lanes=f,jt(a,f)}}function zl(a,c){var f=a.updateQueue,y=a.alternate;if(y!==null&&(y=y.updateQueue,f===y)){var R=null,D=null;if(f=f.firstBaseUpdate,f!==null){do{var Z={lane:f.lane,tag:f.tag,payload:f.payload,callback:null,next:null};D===null?R=D=Z:D=D.next=Z,f=f.next}while(f!==null);D===null?R=D=c:D=D.next=c}else R=D=c;f={baseState:y.baseState,firstBaseUpdate:R,lastBaseUpdate:D,shared:y.shared,callbacks:y.callbacks},a.updateQueue=f;return}a=f.lastBaseUpdate,a===null?f.firstBaseUpdate=c:a.next=c,f.lastBaseUpdate=c}var Vl=!1;function Oa(){if(Vl){var a=ra;if(a!==null)throw a}}function Ma(a,c,f,y){Vl=!1;var R=a.updateQueue;rs=!1;var D=R.firstBaseUpdate,Z=R.lastBaseUpdate,ue=R.shared.pending;if(ue!==null){R.shared.pending=null;var $e=ue,et=$e.next;$e.next=null,Z===null?D=et:Z.next=et,Z=$e;var ct=a.alternate;ct!==null&&(ct=ct.updateQueue,ue=ct.lastBaseUpdate,ue!==Z&&(ue===null?ct.firstBaseUpdate=et:ue.next=et,ct.lastBaseUpdate=$e))}if(D!==null){var ft=R.baseState;Z=0,ct=et=$e=null,ue=D;do{var rt=ue.lane&-536870913,st=rt!==ue.lane;if(st?(Kt&rt)===rt:(y&rt)===rt){rt!==0&&rt===ta&&(Vl=!0),ct!==null&&(ct=ct.next={lane:0,tag:ue.tag,payload:ue.payload,callback:null,next:null});e:{var xt=a,It=ue;rt=c;var _r=f;switch(It.tag){case 1:if(xt=It.payload,typeof xt=="function"){ft=xt.call(_r,ft,rt);break e}ft=xt;break e;case 3:xt.flags=xt.flags&-65537|128;case 0:if(xt=It.payload,rt=typeof xt=="function"?xt.call(_r,ft,rt):xt,rt==null)break e;ft=g({},ft,rt);break e;case 2:rs=!0}}rt=ue.callback,rt!==null&&(a.flags|=64,st&&(a.flags|=8192),st=R.callbacks,st===null?R.callbacks=[rt]:st.push(rt))}else st={lane:rt,tag:ue.tag,payload:ue.payload,callback:ue.callback,next:null},ct===null?(et=ct=st,$e=ft):ct=ct.next=st,Z|=rt;if(ue=ue.next,ue===null){if(ue=R.shared.pending,ue===null)break;st=ue,ue=st.next,st.next=null,R.lastBaseUpdate=st,R.shared.pending=null}}while(!0);ct===null&&($e=ft),R.baseState=$e,R.firstBaseUpdate=et,R.lastBaseUpdate=ct,D===null&&(R.shared.lanes=0),ds|=Z,a.lanes=Z,a.memoizedState=ft}}function Du(a,c){if(typeof a!="function")throw Error(i(191,a));a.call(c)}function Nu(a,c){var f=a.callbacks;if(f!==null)for(a.callbacks=null,a=0;a<f.length;a++)Du(f[a],c)}var sa=W(null),Uo=W(0);function Fu(a,c){a=Mi,te(Uo,a),te(sa,c),Mi=a|c.baseLanes}function Hl(){te(Uo,Mi),te(sa,sa.current)}function Wl(){Mi=Uo.current,de(sa),de(Uo)}var $n=W(null),ii=null;function os(a){var c=a.alternate;te(Vr,Vr.current&1),te($n,a),ii===null&&(c===null||sa.current!==null||c.memoizedState!==null)&&(ii=a)}function Kl(a){te(Vr,Vr.current),te($n,a),ii===null&&(ii=a)}function Uu(a){a.tag===22?(te(Vr,Vr.current),te($n,a),ii===null&&(ii=a)):ls()}function ls(){te(Vr,Vr.current),te($n,$n.current)}function On(a){de($n),ii===a&&(ii=null),de(Vr)}var Vr=W(0);function Po(a){for(var c=a;c!==null;){if(c.tag===13){var f=c.memoizedState;if(f!==null&&(f=f.dehydrated,f===null||Yc(f)||eu(f)))return c}else if(c.tag===19&&(c.memoizedProps.revealOrder==="forwards"||c.memoizedProps.revealOrder==="backwards"||c.memoizedProps.revealOrder==="unstable_legacy-backwards"||c.memoizedProps.revealOrder==="together")){if((c.flags&128)!==0)return c}else if(c.child!==null){c.child.return=c,c=c.child;continue}if(c===a)break;for(;c.sibling===null;){if(c.return===null||c.return===a)return null;c=c.return}c.sibling.return=c.return,c=c.sibling}return null}var Fi=0,Ot=null,yr=null,Qr=null,ko=!1,aa=!1,Ls=!1,Lo=0,Ba=0,oa=null,Ch=0;function Br(){throw Error(i(321))}function Zl(a,c){if(c===null)return!1;for(var f=0;f<c.length&&f<a.length;f++)if(!wt(a[f],c[f]))return!1;return!0}function Gl(a,c,f,y,R,D){return Fi=D,Ot=c,c.memoizedState=null,c.updateQueue=null,c.lanes=0,he.H=a===null||a.memoizedState===null?yd:uc,Ls=!1,D=f(y,R),Ls=!1,aa&&(D=ku(c,f,y,R)),Pu(a),D}function Pu(a){he.H=Va;var c=yr!==null&&yr.next!==null;if(Fi=0,Qr=yr=Ot=null,ko=!1,Ba=0,oa=null,c)throw Error(i(300));a===null||Xr||(a=a.dependencies,a!==null&&To(a)&&(Xr=!0))}function ku(a,c,f,y){Ot=a;var R=0;do{if(aa&&(oa=null),Ba=0,aa=!1,25<=R)throw Error(i(301));if(R+=1,Qr=yr=null,a.updateQueue!=null){var D=a.updateQueue;D.lastEffect=null,D.events=null,D.stores=null,D.memoCache!=null&&(D.memoCache.index=0)}he.H=bd,D=c(f,y)}while(aa);return D}function Ih(){var a=he.H,c=a.useState()[0];return c=typeof c.then=="function"?qa(c):c,a=a.useState()[0],(yr!==null?yr.memoizedState:null)!==a&&(Ot.flags|=1024),c}function Jl(){var a=Lo!==0;return Lo=0,a}function Ql(a,c,f){c.updateQueue=a.updateQueue,c.flags&=-2053,a.lanes&=~f}function Xl(a){if(ko){for(a=a.memoizedState;a!==null;){var c=a.queue;c!==null&&(c.pending=null),a=a.next}ko=!1}Fi=0,Qr=yr=Ot=null,aa=!1,Ba=Lo=0,oa=null}function wn(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Qr===null?Ot.memoizedState=Qr=a:Qr=Qr.next=a,Qr}function Hr(){if(yr===null){var a=Ot.alternate;a=a!==null?a.memoizedState:null}else a=yr.next;var c=Qr===null?Ot.memoizedState:Qr.next;if(c!==null)Qr=c,yr=a;else{if(a===null)throw Ot.alternate===null?Error(i(467)):Error(i(310));yr=a,a={memoizedState:yr.memoizedState,baseState:yr.baseState,baseQueue:yr.baseQueue,queue:yr.queue,next:null},Qr===null?Ot.memoizedState=Qr=a:Qr=Qr.next=a}return Qr}function jo(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function qa(a){var c=Ba;return Ba+=1,oa===null&&(oa=[]),a=Ru(oa,a,c),c=Ot,(Qr===null?c.memoizedState:Qr.next)===null&&(c=c.alternate,he.H=c===null||c.memoizedState===null?yd:uc),a}function $o(a){if(a!==null&&typeof a=="object"){if(typeof a.then=="function")return qa(a);if(a.$$typeof===T)return fn(a)}throw Error(i(438,String(a)))}function Yl(a){var c=null,f=Ot.updateQueue;if(f!==null&&(c=f.memoCache),c==null){var y=Ot.alternate;y!==null&&(y=y.updateQueue,y!==null&&(y=y.memoCache,y!=null&&(c={data:y.data.map(function(R){return R.slice()}),index:0})))}if(c==null&&(c={data:[],index:0}),f===null&&(f=jo(),Ot.updateQueue=f),f.memoCache=c,f=c.data[c.index],f===void 0)for(f=c.data[c.index]=Array(a),y=0;y<a;y++)f[y]=M;return c.index++,f}function Ui(a,c){return typeof c=="function"?c(a):c}function Oo(a){var c=Hr();return ec(c,yr,a)}function ec(a,c,f){var y=a.queue;if(y===null)throw Error(i(311));y.lastRenderedReducer=f;var R=a.baseQueue,D=y.pending;if(D!==null){if(R!==null){var Z=R.next;R.next=D.next,D.next=Z}c.baseQueue=R=D,y.pending=null}if(D=a.baseState,R===null)a.memoizedState=D;else{c=R.next;var ue=Z=null,$e=null,et=c,ct=!1;do{var ft=et.lane&-536870913;if(ft!==et.lane?(Kt&ft)===ft:(Fi&ft)===ft){var rt=et.revertLane;if(rt===0)$e!==null&&($e=$e.next={lane:0,revertLane:0,gesture:null,action:et.action,hasEagerState:et.hasEagerState,eagerState:et.eagerState,next:null}),ft===ta&&(ct=!0);else if((Fi&rt)===rt){et=et.next,rt===ta&&(ct=!0);continue}else ft={lane:0,revertLane:et.revertLane,gesture:null,action:et.action,hasEagerState:et.hasEagerState,eagerState:et.eagerState,next:null},$e===null?(ue=$e=ft,Z=D):$e=$e.next=ft,Ot.lanes|=rt,ds|=rt;ft=et.action,Ls&&f(D,ft),D=et.hasEagerState?et.eagerState:f(D,ft)}else rt={lane:ft,revertLane:et.revertLane,gesture:et.gesture,action:et.action,hasEagerState:et.hasEagerState,eagerState:et.eagerState,next:null},$e===null?(ue=$e=rt,Z=D):$e=$e.next=rt,Ot.lanes|=ft,ds|=ft;et=et.next}while(et!==null&&et!==c);if($e===null?Z=D:$e.next=ue,!wt(D,a.memoizedState)&&(Xr=!0,ct&&(f=ra,f!==null)))throw f;a.memoizedState=D,a.baseState=Z,a.baseQueue=$e,y.lastRenderedState=D}return R===null&&(y.lanes=0),[a.memoizedState,y.dispatch]}function tc(a){var c=Hr(),f=c.queue;if(f===null)throw Error(i(311));f.lastRenderedReducer=a;var y=f.dispatch,R=f.pending,D=c.memoizedState;if(R!==null){f.pending=null;var Z=R=R.next;do D=a(D,Z.action),Z=Z.next;while(Z!==R);wt(D,c.memoizedState)||(Xr=!0),c.memoizedState=D,c.baseQueue===null&&(c.baseState=D),f.lastRenderedState=D}return[D,y]}function Lu(a,c,f){var y=Ot,R=Hr(),D=Gt;if(D){if(f===void 0)throw Error(i(407));f=f()}else f=c();var Z=!wt((yr||R).memoizedState,f);if(Z&&(R.memoizedState=f,Xr=!0),R=R.queue,ic(Ou.bind(null,y,R,a),[a]),R.getSnapshot!==c||Z||Qr!==null&&Qr.memoizedState.tag&1){if(y.flags|=2048,la(9,{destroy:void 0},$u.bind(null,y,R,f,c),null),vr===null)throw Error(i(349));D||(Fi&127)!==0||ju(y,c,f)}return f}function ju(a,c,f){a.flags|=16384,a={getSnapshot:c,value:f},c=Ot.updateQueue,c===null?(c=jo(),Ot.updateQueue=c,c.stores=[a]):(f=c.stores,f===null?c.stores=[a]:f.push(a))}function $u(a,c,f,y){c.value=f,c.getSnapshot=y,Mu(c)&&Bu(a)}function Ou(a,c,f){return f(function(){Mu(c)&&Bu(a)})}function Mu(a){var c=a.getSnapshot;a=a.value;try{var f=c();return!wt(a,f)}catch{return!0}}function Bu(a){var c=As(a,2);c!==null&&Fn(c,a,2)}function rc(a){var c=wn();if(typeof a=="function"){var f=a;if(a=f(),Ls){St(!0);try{f()}finally{St(!1)}}}return c.memoizedState=c.baseState=a,c.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ui,lastRenderedState:a},c}function qu(a,c,f,y){return a.baseState=f,ec(a,yr,typeof y=="function"?y:Ui)}function Dh(a,c,f,y,R){if(qo(a))throw Error(i(485));if(a=c.action,a!==null){var D={payload:R,action:a,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(Z){D.listeners.push(Z)}};he.T!==null?f(!0):D.isTransition=!1,y(D),f=c.pending,f===null?(D.next=c.pending=D,zu(c,D)):(D.next=f.next,c.pending=f.next=D)}}function zu(a,c){var f=c.action,y=c.payload,R=a.state;if(c.isTransition){var D=he.T,Z={};he.T=Z;try{var ue=f(R,y),$e=he.S;$e!==null&&$e(Z,ue),Vu(a,c,ue)}catch(et){nc(a,c,et)}finally{D!==null&&Z.types!==null&&(D.types=Z.types),he.T=D}}else try{D=f(R,y),Vu(a,c,D)}catch(et){nc(a,c,et)}}function Vu(a,c,f){f!==null&&typeof f=="object"&&typeof f.then=="function"?f.then(function(y){Hu(a,c,y)},function(y){return nc(a,c,y)}):Hu(a,c,f)}function Hu(a,c,f){c.status="fulfilled",c.value=f,Wu(c),a.state=f,c=a.pending,c!==null&&(f=c.next,f===c?a.pending=null:(f=f.next,c.next=f,zu(a,f)))}function nc(a,c,f){var y=a.pending;if(a.pending=null,y!==null){y=y.next;do c.status="rejected",c.reason=f,Wu(c),c=c.next;while(c!==y)}a.action=null}function Wu(a){a=a.listeners;for(var c=0;c<a.length;c++)(0,a[c])()}function Ku(a,c){return c}function Zu(a,c){if(Gt){var f=vr.formState;if(f!==null){e:{var y=Ot;if(Gt){if(Cr){t:{for(var R=Cr,D=ni;R.nodeType!==8;){if(!D){R=null;break t}if(R=si(R.nextSibling),R===null){R=null;break t}}D=R.data,R=D==="F!"||D==="F"?R:null}if(R){Cr=si(R.nextSibling),y=R.data==="F!";break e}}es(y)}y=!1}y&&(c=f[0])}}return f=wn(),f.memoizedState=f.baseState=c,y={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ku,lastRenderedState:c},f.queue=y,f=pd.bind(null,Ot,y),y.dispatch=f,y=rc(!1),D=cc.bind(null,Ot,!1,y.queue),y=wn(),R={state:c,dispatch:null,action:a,pending:null},y.queue=R,f=Dh.bind(null,Ot,R,D,f),R.dispatch=f,y.memoizedState=a,[c,f,!1]}function Gu(a){var c=Hr();return Ju(c,yr,a)}function Ju(a,c,f){if(c=ec(a,c,Ku)[0],a=Oo(Ui)[0],typeof c=="object"&&c!==null&&typeof c.then=="function")try{var y=qa(c)}catch(Z){throw Z===na?Io:Z}else y=c;c=Hr();var R=c.queue,D=R.dispatch;return f!==c.memoizedState&&(Ot.flags|=2048,la(9,{destroy:void 0},Nh.bind(null,R,f),null)),[y,D,a]}function Nh(a,c){a.action=c}function Qu(a){var c=Hr(),f=yr;if(f!==null)return Ju(c,f,a);Hr(),c=c.memoizedState,f=Hr();var y=f.queue.dispatch;return f.memoizedState=a,[c,y,!1]}function la(a,c,f,y){return a={tag:a,create:f,deps:y,inst:c,next:null},c=Ot.updateQueue,c===null&&(c=jo(),Ot.updateQueue=c),f=c.lastEffect,f===null?c.lastEffect=a.next=a:(y=f.next,f.next=a,a.next=y,c.lastEffect=a),a}function Xu(){return Hr().memoizedState}function Mo(a,c,f,y){var R=wn();Ot.flags|=a,R.memoizedState=la(1|c,{destroy:void 0},f,y===void 0?null:y)}function Bo(a,c,f,y){var R=Hr();y=y===void 0?null:y;var D=R.memoizedState.inst;yr!==null&&y!==null&&Zl(y,yr.memoizedState.deps)?R.memoizedState=la(c,D,f,y):(Ot.flags|=a,R.memoizedState=la(1|c,D,f,y))}function Yu(a,c){Mo(8390656,8,a,c)}function ic(a,c){Bo(2048,8,a,c)}function Fh(a){Ot.flags|=4;var c=Ot.updateQueue;if(c===null)c=jo(),Ot.updateQueue=c,c.events=[a];else{var f=c.events;f===null?c.events=[a]:f.push(a)}}function ed(a){var c=Hr().memoizedState;return Fh({ref:c,nextImpl:a}),function(){if((nr&2)!==0)throw Error(i(440));return c.impl.apply(void 0,arguments)}}function td(a,c){return Bo(4,2,a,c)}function rd(a,c){return Bo(4,4,a,c)}function nd(a,c){if(typeof c=="function"){a=a();var f=c(a);return function(){typeof f=="function"?f():c(null)}}if(c!=null)return a=a(),c.current=a,function(){c.current=null}}function sd(a,c,f){f=f!=null?f.concat([a]):null,Bo(4,4,nd.bind(null,c,a),f)}function sc(){}function ad(a,c){var f=Hr();c=c===void 0?null:c;var y=f.memoizedState;return c!==null&&Zl(c,y[1])?y[0]:(f.memoizedState=[a,c],a)}function od(a,c){var f=Hr();c=c===void 0?null:c;var y=f.memoizedState;if(c!==null&&Zl(c,y[1]))return y[0];if(y=a(),Ls){St(!0);try{a()}finally{St(!1)}}return f.memoizedState=[y,c],y}function ac(a,c,f){return f===void 0||(Fi&1073741824)!==0&&(Kt&261930)===0?a.memoizedState=c:(a.memoizedState=f,a=cf(),Ot.lanes|=a,ds|=a,f)}function ld(a,c,f,y){return wt(f,c)?f:sa.current!==null?(a=ac(a,f,y),wt(a,c)||(Xr=!0),a):(Fi&42)===0||(Fi&1073741824)!==0&&(Kt&261930)===0?(Xr=!0,a.memoizedState=f):(a=cf(),Ot.lanes|=a,ds|=a,c)}function cd(a,c,f,y,R){var D=Oe.p;Oe.p=D!==0&&8>D?D:8;var Z=he.T,ue={};he.T=ue,cc(a,!1,c,f);try{var $e=R(),et=he.S;if(et!==null&&et(ue,$e),$e!==null&&typeof $e=="object"&&typeof $e.then=="function"){var ct=Ah($e,y);za(a,c,ct,qn(a))}else za(a,c,y,qn(a))}catch(ft){za(a,c,{then:function(){},status:"rejected",reason:ft},qn())}finally{Oe.p=D,Z!==null&&ue.types!==null&&(Z.types=ue.types),he.T=Z}}function Uh(){}function oc(a,c,f,y){if(a.tag!==5)throw Error(i(476));var R=ud(a).queue;cd(a,R,c,ce,f===null?Uh:function(){return dd(a),f(y)})}function ud(a){var c=a.memoizedState;if(c!==null)return c;c={memoizedState:ce,baseState:ce,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ui,lastRenderedState:ce},next:null};var f={};return c.next={memoizedState:f,baseState:f,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ui,lastRenderedState:f},next:null},a.memoizedState=c,a=a.alternate,a!==null&&(a.memoizedState=c),c}function dd(a){var c=ud(a);c.next===null&&(c=a.alternate.memoizedState),za(a,c.next.queue,{},qn())}function lc(){return fn(ao)}function fd(){return Hr().memoizedState}function hd(){return Hr().memoizedState}function Ph(a){for(var c=a.return;c!==null;){switch(c.tag){case 24:case 3:var f=qn();a=ss(f);var y=as(c,a,f);y!==null&&(Fn(y,c,f),$a(y,c,f)),c={cache:jl()},a.payload=c;return}c=c.return}}function kh(a,c,f){var y=qn();f={lane:y,revertLane:0,gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null},qo(a)?gd(c,f):(f=Tl(a,c,f,y),f!==null&&(Fn(f,a,y),md(f,c,y)))}function pd(a,c,f){var y=qn();za(a,c,f,y)}function za(a,c,f,y){var R={lane:y,revertLane:0,gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null};if(qo(a))gd(c,R);else{var D=a.alternate;if(a.lanes===0&&(D===null||D.lanes===0)&&(D=c.lastRenderedReducer,D!==null))try{var Z=c.lastRenderedState,ue=D(Z,f);if(R.hasEagerState=!0,R.eagerState=ue,wt(ue,Z))return wo(a,c,R,0),vr===null&&vo(),!1}catch{}if(f=Tl(a,c,R,y),f!==null)return Fn(f,a,y),md(f,c,y),!0}return!1}function cc(a,c,f,y){if(y={lane:2,revertLane:Bc(),gesture:null,action:y,hasEagerState:!1,eagerState:null,next:null},qo(a)){if(c)throw Error(i(479))}else c=Tl(a,f,y,2),c!==null&&Fn(c,a,2)}function qo(a){var c=a.alternate;return a===Ot||c!==null&&c===Ot}function gd(a,c){aa=ko=!0;var f=a.pending;f===null?c.next=c:(c.next=f.next,f.next=c),a.pending=c}function md(a,c,f){if((f&4194048)!==0){var y=c.lanes;y&=a.pendingLanes,f|=y,c.lanes=f,jt(a,f)}}var Va={readContext:fn,use:$o,useCallback:Br,useContext:Br,useEffect:Br,useImperativeHandle:Br,useLayoutEffect:Br,useInsertionEffect:Br,useMemo:Br,useReducer:Br,useRef:Br,useState:Br,useDebugValue:Br,useDeferredValue:Br,useTransition:Br,useSyncExternalStore:Br,useId:Br,useHostTransitionStatus:Br,useFormState:Br,useActionState:Br,useOptimistic:Br,useMemoCache:Br,useCacheRefresh:Br};Va.useEffectEvent=Br;var yd={readContext:fn,use:$o,useCallback:function(a,c){return wn().memoizedState=[a,c===void 0?null:c],a},useContext:fn,useEffect:Yu,useImperativeHandle:function(a,c,f){f=f!=null?f.concat([a]):null,Mo(4194308,4,nd.bind(null,c,a),f)},useLayoutEffect:function(a,c){return Mo(4194308,4,a,c)},useInsertionEffect:function(a,c){Mo(4,2,a,c)},useMemo:function(a,c){var f=wn();c=c===void 0?null:c;var y=a();if(Ls){St(!0);try{a()}finally{St(!1)}}return f.memoizedState=[y,c],y},useReducer:function(a,c,f){var y=wn();if(f!==void 0){var R=f(c);if(Ls){St(!0);try{f(c)}finally{St(!1)}}}else R=c;return y.memoizedState=y.baseState=R,a={pending:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:R},y.queue=a,a=a.dispatch=kh.bind(null,Ot,a),[y.memoizedState,a]},useRef:function(a){var c=wn();return a={current:a},c.memoizedState=a},useState:function(a){a=rc(a);var c=a.queue,f=pd.bind(null,Ot,c);return c.dispatch=f,[a.memoizedState,f]},useDebugValue:sc,useDeferredValue:function(a,c){var f=wn();return ac(f,a,c)},useTransition:function(){var a=rc(!1);return a=cd.bind(null,Ot,a.queue,!0,!1),wn().memoizedState=a,[!1,a]},useSyncExternalStore:function(a,c,f){var y=Ot,R=wn();if(Gt){if(f===void 0)throw Error(i(407));f=f()}else{if(f=c(),vr===null)throw Error(i(349));(Kt&127)!==0||ju(y,c,f)}R.memoizedState=f;var D={value:f,getSnapshot:c};return R.queue=D,Yu(Ou.bind(null,y,D,a),[a]),y.flags|=2048,la(9,{destroy:void 0},$u.bind(null,y,D,f,c),null),f},useId:function(){var a=wn(),c=vr.identifierPrefix;if(Gt){var f=bi,y=yi;f=(y&~(1<<32-Rt(y)-1)).toString(32)+f,c="_"+c+"R_"+f,f=Lo++,0<f&&(c+="H"+f.toString(32)),c+="_"}else f=Ch++,c="_"+c+"r_"+f.toString(32)+"_";return a.memoizedState=c},useHostTransitionStatus:lc,useFormState:Zu,useActionState:Zu,useOptimistic:function(a){var c=wn();c.memoizedState=c.baseState=a;var f={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return c.queue=f,c=cc.bind(null,Ot,!0,f),f.dispatch=c,[a,c]},useMemoCache:Yl,useCacheRefresh:function(){return wn().memoizedState=Ph.bind(null,Ot)},useEffectEvent:function(a){var c=wn(),f={impl:a};return c.memoizedState=f,function(){if((nr&2)!==0)throw Error(i(440));return f.impl.apply(void 0,arguments)}}},uc={readContext:fn,use:$o,useCallback:ad,useContext:fn,useEffect:ic,useImperativeHandle:sd,useInsertionEffect:td,useLayoutEffect:rd,useMemo:od,useReducer:Oo,useRef:Xu,useState:function(){return Oo(Ui)},useDebugValue:sc,useDeferredValue:function(a,c){var f=Hr();return ld(f,yr.memoizedState,a,c)},useTransition:function(){var a=Oo(Ui)[0],c=Hr().memoizedState;return[typeof a=="boolean"?a:qa(a),c]},useSyncExternalStore:Lu,useId:fd,useHostTransitionStatus:lc,useFormState:Gu,useActionState:Gu,useOptimistic:function(a,c){var f=Hr();return qu(f,yr,a,c)},useMemoCache:Yl,useCacheRefresh:hd};uc.useEffectEvent=ed;var bd={readContext:fn,use:$o,useCallback:ad,useContext:fn,useEffect:ic,useImperativeHandle:sd,useInsertionEffect:td,useLayoutEffect:rd,useMemo:od,useReducer:tc,useRef:Xu,useState:function(){return tc(Ui)},useDebugValue:sc,useDeferredValue:function(a,c){var f=Hr();return yr===null?ac(f,a,c):ld(f,yr.memoizedState,a,c)},useTransition:function(){var a=tc(Ui)[0],c=Hr().memoizedState;return[typeof a=="boolean"?a:qa(a),c]},useSyncExternalStore:Lu,useId:fd,useHostTransitionStatus:lc,useFormState:Qu,useActionState:Qu,useOptimistic:function(a,c){var f=Hr();return yr!==null?qu(f,yr,a,c):(f.baseState=a,[a,f.queue.dispatch])},useMemoCache:Yl,useCacheRefresh:hd};bd.useEffectEvent=ed;function dc(a,c,f,y){c=a.memoizedState,f=f(y,c),f=f==null?c:g({},c,f),a.memoizedState=f,a.lanes===0&&(a.updateQueue.baseState=f)}var fc={enqueueSetState:function(a,c,f){a=a._reactInternals;var y=qn(),R=ss(y);R.payload=c,f!=null&&(R.callback=f),c=as(a,R,y),c!==null&&(Fn(c,a,y),$a(c,a,y))},enqueueReplaceState:function(a,c,f){a=a._reactInternals;var y=qn(),R=ss(y);R.tag=1,R.payload=c,f!=null&&(R.callback=f),c=as(a,R,y),c!==null&&(Fn(c,a,y),$a(c,a,y))},enqueueForceUpdate:function(a,c){a=a._reactInternals;var f=qn(),y=ss(f);y.tag=2,c!=null&&(y.callback=c),c=as(a,y,f),c!==null&&(Fn(c,a,f),$a(c,a,f))}};function _d(a,c,f,y,R,D,Z){return a=a.stateNode,typeof a.shouldComponentUpdate=="function"?a.shouldComponentUpdate(y,D,Z):c.prototype&&c.prototype.isPureReactComponent?!oe(f,y)||!oe(R,D):!0}function Sd(a,c,f,y){a=c.state,typeof c.componentWillReceiveProps=="function"&&c.componentWillReceiveProps(f,y),typeof c.UNSAFE_componentWillReceiveProps=="function"&&c.UNSAFE_componentWillReceiveProps(f,y),c.state!==a&&fc.enqueueReplaceState(c,c.state,null)}function js(a,c){var f=c;if("ref"in c){f={};for(var y in c)y!=="ref"&&(f[y]=c[y])}if(a=a.defaultProps){f===c&&(f=g({},f));for(var R in a)f[R]===void 0&&(f[R]=a[R])}return f}function vd(a){So(a)}function wd(a){console.error(a)}function xd(a){So(a)}function zo(a,c){try{var f=a.onUncaughtError;f(c.value,{componentStack:c.stack})}catch(y){setTimeout(function(){throw y})}}function Ed(a,c,f){try{var y=a.onCaughtError;y(f.value,{componentStack:f.stack,errorBoundary:c.tag===1?c.stateNode:null})}catch(R){setTimeout(function(){throw R})}}function hc(a,c,f){return f=ss(f),f.tag=3,f.payload={element:null},f.callback=function(){zo(a,c)},f}function Rd(a){return a=ss(a),a.tag=3,a}function Td(a,c,f,y){var R=f.type.getDerivedStateFromError;if(typeof R=="function"){var D=y.value;a.payload=function(){return R(D)},a.callback=function(){Ed(c,f,y)}}var Z=f.stateNode;Z!==null&&typeof Z.componentDidCatch=="function"&&(a.callback=function(){Ed(c,f,y),typeof R!="function"&&(fs===null?fs=new Set([this]):fs.add(this));var ue=y.stack;this.componentDidCatch(y.value,{componentStack:ue!==null?ue:""})})}function Lh(a,c,f,y,R){if(f.flags|=32768,y!==null&&typeof y=="object"&&typeof y.then=="function"){if(c=f.alternate,c!==null&&ea(c,f,R,!0),f=$n.current,f!==null){switch(f.tag){case 31:case 13:return ii===null?tl():f.alternate===null&&qr===0&&(qr=3),f.flags&=-257,f.flags|=65536,f.lanes=R,y===Do?f.flags|=16384:(c=f.updateQueue,c===null?f.updateQueue=new Set([y]):c.add(y),$c(a,y,R)),!1;case 22:return f.flags|=65536,y===Do?f.flags|=16384:(c=f.updateQueue,c===null?(c={transitions:null,markerInstances:null,retryQueue:new Set([y])},f.updateQueue=c):(f=c.retryQueue,f===null?c.retryQueue=new Set([y]):f.add(y)),$c(a,y,R)),!1}throw Error(i(435,f.tag))}return $c(a,y,R),tl(),!1}if(Gt)return c=$n.current,c!==null?((c.flags&65536)===0&&(c.flags|=256),c.flags|=65536,c.lanes=R,y!==Fl&&(a=Error(i(422),{cause:y}),Ua(ei(a,f)))):(y!==Fl&&(c=Error(i(423),{cause:y}),Ua(ei(c,f))),a=a.current.alternate,a.flags|=65536,R&=-R,a.lanes|=R,y=ei(y,f),R=hc(a.stateNode,y,R),zl(a,R),qr!==4&&(qr=2)),!1;var D=Error(i(520),{cause:y});if(D=ei(D,f),Xa===null?Xa=[D]:Xa.push(D),qr!==4&&(qr=2),c===null)return!0;y=ei(y,f),f=c;do{switch(f.tag){case 3:return f.flags|=65536,a=R&-R,f.lanes|=a,a=hc(f.stateNode,y,a),zl(f,a),!1;case 1:if(c=f.type,D=f.stateNode,(f.flags&128)===0&&(typeof c.getDerivedStateFromError=="function"||D!==null&&typeof D.componentDidCatch=="function"&&(fs===null||!fs.has(D))))return f.flags|=65536,R&=-R,f.lanes|=R,R=Rd(R),Td(R,a,f,y),zl(f,R),!1}f=f.return}while(f!==null);return!1}var pc=Error(i(461)),Xr=!1;function hn(a,c,f,y){c.child=a===null?Iu(c,null,f,y):ks(c,a.child,f,y)}function Ad(a,c,f,y,R){f=f.render;var D=c.ref;if("ref"in y){var Z={};for(var ue in y)ue!=="ref"&&(Z[ue]=y[ue])}else Z=y;return Ns(c),y=Gl(a,c,f,Z,D,R),ue=Jl(),a!==null&&!Xr?(Ql(a,c,R),Pi(a,c,R)):(Gt&&ue&&Dl(c),c.flags|=1,hn(a,c,y,R),c.child)}function Cd(a,c,f,y,R){if(a===null){var D=f.type;return typeof D=="function"&&!Al(D)&&D.defaultProps===void 0&&f.compare===null?(c.tag=15,c.type=D,Id(a,c,D,y,R)):(a=Eo(f.type,null,y,c,c.mode,R),a.ref=c.ref,a.return=c,c.child=a)}if(D=a.child,!wc(a,R)){var Z=D.memoizedProps;if(f=f.compare,f=f!==null?f:oe,f(Z,y)&&a.ref===c.ref)return Pi(a,c,R)}return c.flags|=1,a=Ci(D,y),a.ref=c.ref,a.return=c,c.child=a}function Id(a,c,f,y,R){if(a!==null){var D=a.memoizedProps;if(oe(D,y)&&a.ref===c.ref)if(Xr=!1,c.pendingProps=y=D,wc(a,R))(a.flags&131072)!==0&&(Xr=!0);else return c.lanes=a.lanes,Pi(a,c,R)}return gc(a,c,f,y,R)}function Dd(a,c,f,y){var R=y.children,D=a!==null?a.memoizedState:null;if(a===null&&c.stateNode===null&&(c.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),y.mode==="hidden"){if((c.flags&128)!==0){if(D=D!==null?D.baseLanes|f:f,a!==null){for(y=c.child=a.child,R=0;y!==null;)R=R|y.lanes|y.childLanes,y=y.sibling;y=R&~D}else y=0,c.child=null;return Nd(a,c,D,f,y)}if((f&536870912)!==0)c.memoizedState={baseLanes:0,cachePool:null},a!==null&&Co(c,D!==null?D.cachePool:null),D!==null?Fu(c,D):Hl(),Uu(c);else return y=c.lanes=536870912,Nd(a,c,D!==null?D.baseLanes|f:f,f,y)}else D!==null?(Co(c,D.cachePool),Fu(c,D),ls(),c.memoizedState=null):(a!==null&&Co(c,null),Hl(),ls());return hn(a,c,R,f),c.child}function Ha(a,c){return a!==null&&a.tag===22||c.stateNode!==null||(c.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),c.sibling}function Nd(a,c,f,y,R){var D=Ol();return D=D===null?null:{parent:Jr._currentValue,pool:D},c.memoizedState={baseLanes:f,cachePool:D},a!==null&&Co(c,null),Hl(),Uu(c),a!==null&&ea(a,c,y,!0),c.childLanes=R,null}function Vo(a,c){return c=Wo({mode:c.mode,children:c.children},a.mode),c.ref=a.ref,a.child=c,c.return=a,c}function Fd(a,c,f){return ks(c,a.child,null,f),a=Vo(c,c.pendingProps),a.flags|=2,On(c),c.memoizedState=null,a}function jh(a,c,f){var y=c.pendingProps,R=(c.flags&128)!==0;if(c.flags&=-129,a===null){if(Gt){if(y.mode==="hidden")return a=Vo(c,y),c.lanes=536870912,Ha(null,a);if(Kl(c),(a=Cr)?(a=Hf(a,ni),a=a!==null&&a.data==="&"?a:null,a!==null&&(c.memoizedState={dehydrated:a,treeContext:Xi!==null?{id:yi,overflow:bi}:null,retryLane:536870912,hydrationErrors:null},f=pu(a),f.return=c,c.child=f,dn=c,Cr=null)):a=null,a===null)throw es(c);return c.lanes=536870912,null}return Vo(c,y)}var D=a.memoizedState;if(D!==null){var Z=D.dehydrated;if(Kl(c),R)if(c.flags&256)c.flags&=-257,c=Fd(a,c,f);else if(c.memoizedState!==null)c.child=a.child,c.flags|=128,c=null;else throw Error(i(558));else if(Xr||ea(a,c,f,!1),R=(f&a.childLanes)!==0,Xr||R){if(y=vr,y!==null&&(Z=Wt(y,f),Z!==0&&Z!==D.retryLane))throw D.retryLane=Z,As(a,Z),Fn(y,a,Z),pc;tl(),c=Fd(a,c,f)}else a=D.treeContext,Cr=si(Z.nextSibling),dn=c,Gt=!0,Yi=null,ni=!1,a!==null&&yu(c,a),c=Vo(c,y),c.flags|=4096;return c}return a=Ci(a.child,{mode:y.mode,children:y.children}),a.ref=c.ref,c.child=a,a.return=c,a}function Ho(a,c){var f=c.ref;if(f===null)a!==null&&a.ref!==null&&(c.flags|=4194816);else{if(typeof f!="function"&&typeof f!="object")throw Error(i(284));(a===null||a.ref!==f)&&(c.flags|=4194816)}}function gc(a,c,f,y,R){return Ns(c),f=Gl(a,c,f,y,void 0,R),y=Jl(),a!==null&&!Xr?(Ql(a,c,R),Pi(a,c,R)):(Gt&&y&&Dl(c),c.flags|=1,hn(a,c,f,R),c.child)}function Ud(a,c,f,y,R,D){return Ns(c),c.updateQueue=null,f=ku(c,y,f,R),Pu(a),y=Jl(),a!==null&&!Xr?(Ql(a,c,D),Pi(a,c,D)):(Gt&&y&&Dl(c),c.flags|=1,hn(a,c,f,D),c.child)}function Pd(a,c,f,y,R){if(Ns(c),c.stateNode===null){var D=Js,Z=f.contextType;typeof Z=="object"&&Z!==null&&(D=fn(Z)),D=new f(y,D),c.memoizedState=D.state!==null&&D.state!==void 0?D.state:null,D.updater=fc,c.stateNode=D,D._reactInternals=c,D=c.stateNode,D.props=y,D.state=c.memoizedState,D.refs={},Bl(c),Z=f.contextType,D.context=typeof Z=="object"&&Z!==null?fn(Z):Js,D.state=c.memoizedState,Z=f.getDerivedStateFromProps,typeof Z=="function"&&(dc(c,f,Z,y),D.state=c.memoizedState),typeof f.getDerivedStateFromProps=="function"||typeof D.getSnapshotBeforeUpdate=="function"||typeof D.UNSAFE_componentWillMount!="function"&&typeof D.componentWillMount!="function"||(Z=D.state,typeof D.componentWillMount=="function"&&D.componentWillMount(),typeof D.UNSAFE_componentWillMount=="function"&&D.UNSAFE_componentWillMount(),Z!==D.state&&fc.enqueueReplaceState(D,D.state,null),Ma(c,y,D,R),Oa(),D.state=c.memoizedState),typeof D.componentDidMount=="function"&&(c.flags|=4194308),y=!0}else if(a===null){D=c.stateNode;var ue=c.memoizedProps,$e=js(f,ue);D.props=$e;var et=D.context,ct=f.contextType;Z=Js,typeof ct=="object"&&ct!==null&&(Z=fn(ct));var ft=f.getDerivedStateFromProps;ct=typeof ft=="function"||typeof D.getSnapshotBeforeUpdate=="function",ue=c.pendingProps!==ue,ct||typeof D.UNSAFE_componentWillReceiveProps!="function"&&typeof D.componentWillReceiveProps!="function"||(ue||et!==Z)&&Sd(c,D,y,Z),rs=!1;var rt=c.memoizedState;D.state=rt,Ma(c,y,D,R),Oa(),et=c.memoizedState,ue||rt!==et||rs?(typeof ft=="function"&&(dc(c,f,ft,y),et=c.memoizedState),($e=rs||_d(c,f,$e,y,rt,et,Z))?(ct||typeof D.UNSAFE_componentWillMount!="function"&&typeof D.componentWillMount!="function"||(typeof D.componentWillMount=="function"&&D.componentWillMount(),typeof D.UNSAFE_componentWillMount=="function"&&D.UNSAFE_componentWillMount()),typeof D.componentDidMount=="function"&&(c.flags|=4194308)):(typeof D.componentDidMount=="function"&&(c.flags|=4194308),c.memoizedProps=y,c.memoizedState=et),D.props=y,D.state=et,D.context=Z,y=$e):(typeof D.componentDidMount=="function"&&(c.flags|=4194308),y=!1)}else{D=c.stateNode,ql(a,c),Z=c.memoizedProps,ct=js(f,Z),D.props=ct,ft=c.pendingProps,rt=D.context,et=f.contextType,$e=Js,typeof et=="object"&&et!==null&&($e=fn(et)),ue=f.getDerivedStateFromProps,(et=typeof ue=="function"||typeof D.getSnapshotBeforeUpdate=="function")||typeof D.UNSAFE_componentWillReceiveProps!="function"&&typeof D.componentWillReceiveProps!="function"||(Z!==ft||rt!==$e)&&Sd(c,D,y,$e),rs=!1,rt=c.memoizedState,D.state=rt,Ma(c,y,D,R),Oa();var st=c.memoizedState;Z!==ft||rt!==st||rs||a!==null&&a.dependencies!==null&&To(a.dependencies)?(typeof ue=="function"&&(dc(c,f,ue,y),st=c.memoizedState),(ct=rs||_d(c,f,ct,y,rt,st,$e)||a!==null&&a.dependencies!==null&&To(a.dependencies))?(et||typeof D.UNSAFE_componentWillUpdate!="function"&&typeof D.componentWillUpdate!="function"||(typeof D.componentWillUpdate=="function"&&D.componentWillUpdate(y,st,$e),typeof D.UNSAFE_componentWillUpdate=="function"&&D.UNSAFE_componentWillUpdate(y,st,$e)),typeof D.componentDidUpdate=="function"&&(c.flags|=4),typeof D.getSnapshotBeforeUpdate=="function"&&(c.flags|=1024)):(typeof D.componentDidUpdate!="function"||Z===a.memoizedProps&&rt===a.memoizedState||(c.flags|=4),typeof D.getSnapshotBeforeUpdate!="function"||Z===a.memoizedProps&&rt===a.memoizedState||(c.flags|=1024),c.memoizedProps=y,c.memoizedState=st),D.props=y,D.state=st,D.context=$e,y=ct):(typeof D.componentDidUpdate!="function"||Z===a.memoizedProps&&rt===a.memoizedState||(c.flags|=4),typeof D.getSnapshotBeforeUpdate!="function"||Z===a.memoizedProps&&rt===a.memoizedState||(c.flags|=1024),y=!1)}return D=y,Ho(a,c),y=(c.flags&128)!==0,D||y?(D=c.stateNode,f=y&&typeof f.getDerivedStateFromError!="function"?null:D.render(),c.flags|=1,a!==null&&y?(c.child=ks(c,a.child,null,R),c.child=ks(c,null,f,R)):hn(a,c,f,R),c.memoizedState=D.state,a=c.child):a=Pi(a,c,R),a}function kd(a,c,f,y){return Is(),c.flags|=256,hn(a,c,f,y),c.child}var mc={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function yc(a){return{baseLanes:a,cachePool:xu()}}function bc(a,c,f){return a=a!==null?a.childLanes&~f:0,c&&(a|=Bn),a}function Ld(a,c,f){var y=c.pendingProps,R=!1,D=(c.flags&128)!==0,Z;if((Z=D)||(Z=a!==null&&a.memoizedState===null?!1:(Vr.current&2)!==0),Z&&(R=!0,c.flags&=-129),Z=(c.flags&32)!==0,c.flags&=-33,a===null){if(Gt){if(R?os(c):ls(),(a=Cr)?(a=Hf(a,ni),a=a!==null&&a.data!=="&"?a:null,a!==null&&(c.memoizedState={dehydrated:a,treeContext:Xi!==null?{id:yi,overflow:bi}:null,retryLane:536870912,hydrationErrors:null},f=pu(a),f.return=c,c.child=f,dn=c,Cr=null)):a=null,a===null)throw es(c);return eu(a)?c.lanes=32:c.lanes=536870912,null}var ue=y.children;return y=y.fallback,R?(ls(),R=c.mode,ue=Wo({mode:"hidden",children:ue},R),y=Cs(y,R,f,null),ue.return=c,y.return=c,ue.sibling=y,c.child=ue,y=c.child,y.memoizedState=yc(f),y.childLanes=bc(a,Z,f),c.memoizedState=mc,Ha(null,y)):(os(c),_c(c,ue))}var $e=a.memoizedState;if($e!==null&&(ue=$e.dehydrated,ue!==null)){if(D)c.flags&256?(os(c),c.flags&=-257,c=Sc(a,c,f)):c.memoizedState!==null?(ls(),c.child=a.child,c.flags|=128,c=null):(ls(),ue=y.fallback,R=c.mode,y=Wo({mode:"visible",children:y.children},R),ue=Cs(ue,R,f,null),ue.flags|=2,y.return=c,ue.return=c,y.sibling=ue,c.child=y,ks(c,a.child,null,f),y=c.child,y.memoizedState=yc(f),y.childLanes=bc(a,Z,f),c.memoizedState=mc,c=Ha(null,y));else if(os(c),eu(ue)){if(Z=ue.nextSibling&&ue.nextSibling.dataset,Z)var et=Z.dgst;Z=et,y=Error(i(419)),y.stack="",y.digest=Z,Ua({value:y,source:null,stack:null}),c=Sc(a,c,f)}else if(Xr||ea(a,c,f,!1),Z=(f&a.childLanes)!==0,Xr||Z){if(Z=vr,Z!==null&&(y=Wt(Z,f),y!==0&&y!==$e.retryLane))throw $e.retryLane=y,As(a,y),Fn(Z,a,y),pc;Yc(ue)||tl(),c=Sc(a,c,f)}else Yc(ue)?(c.flags|=192,c.child=a.child,c=null):(a=$e.treeContext,Cr=si(ue.nextSibling),dn=c,Gt=!0,Yi=null,ni=!1,a!==null&&yu(c,a),c=_c(c,y.children),c.flags|=4096);return c}return R?(ls(),ue=y.fallback,R=c.mode,$e=a.child,et=$e.sibling,y=Ci($e,{mode:"hidden",children:y.children}),y.subtreeFlags=$e.subtreeFlags&65011712,et!==null?ue=Ci(et,ue):(ue=Cs(ue,R,f,null),ue.flags|=2),ue.return=c,y.return=c,y.sibling=ue,c.child=y,Ha(null,y),y=c.child,ue=a.child.memoizedState,ue===null?ue=yc(f):(R=ue.cachePool,R!==null?($e=Jr._currentValue,R=R.parent!==$e?{parent:$e,pool:$e}:R):R=xu(),ue={baseLanes:ue.baseLanes|f,cachePool:R}),y.memoizedState=ue,y.childLanes=bc(a,Z,f),c.memoizedState=mc,Ha(a.child,y)):(os(c),f=a.child,a=f.sibling,f=Ci(f,{mode:"visible",children:y.children}),f.return=c,f.sibling=null,a!==null&&(Z=c.deletions,Z===null?(c.deletions=[a],c.flags|=16):Z.push(a)),c.child=f,c.memoizedState=null,f)}function _c(a,c){return c=Wo({mode:"visible",children:c},a.mode),c.return=a,a.child=c}function Wo(a,c){return a=jn(22,a,null,c),a.lanes=0,a}function Sc(a,c,f){return ks(c,a.child,null,f),a=_c(c,c.pendingProps.children),a.flags|=2,c.memoizedState=null,a}function jd(a,c,f){a.lanes|=c;var y=a.alternate;y!==null&&(y.lanes|=c),kl(a.return,c,f)}function vc(a,c,f,y,R,D){var Z=a.memoizedState;Z===null?a.memoizedState={isBackwards:c,rendering:null,renderingStartTime:0,last:y,tail:f,tailMode:R,treeForkCount:D}:(Z.isBackwards=c,Z.rendering=null,Z.renderingStartTime=0,Z.last=y,Z.tail=f,Z.tailMode=R,Z.treeForkCount=D)}function $d(a,c,f){var y=c.pendingProps,R=y.revealOrder,D=y.tail;y=y.children;var Z=Vr.current,ue=(Z&2)!==0;if(ue?(Z=Z&1|2,c.flags|=128):Z&=1,te(Vr,Z),hn(a,c,y,f),y=Gt?Fa:0,!ue&&a!==null&&(a.flags&128)!==0)e:for(a=c.child;a!==null;){if(a.tag===13)a.memoizedState!==null&&jd(a,f,c);else if(a.tag===19)jd(a,f,c);else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===c)break e;for(;a.sibling===null;){if(a.return===null||a.return===c)break e;a=a.return}a.sibling.return=a.return,a=a.sibling}switch(R){case"forwards":for(f=c.child,R=null;f!==null;)a=f.alternate,a!==null&&Po(a)===null&&(R=f),f=f.sibling;f=R,f===null?(R=c.child,c.child=null):(R=f.sibling,f.sibling=null),vc(c,!1,R,f,D,y);break;case"backwards":case"unstable_legacy-backwards":for(f=null,R=c.child,c.child=null;R!==null;){if(a=R.alternate,a!==null&&Po(a)===null){c.child=R;break}a=R.sibling,R.sibling=f,f=R,R=a}vc(c,!0,f,null,D,y);break;case"together":vc(c,!1,null,null,void 0,y);break;default:c.memoizedState=null}return c.child}function Pi(a,c,f){if(a!==null&&(c.dependencies=a.dependencies),ds|=c.lanes,(f&c.childLanes)===0)if(a!==null){if(ea(a,c,f,!1),(f&c.childLanes)===0)return null}else return null;if(a!==null&&c.child!==a.child)throw Error(i(153));if(c.child!==null){for(a=c.child,f=Ci(a,a.pendingProps),c.child=f,f.return=c;a.sibling!==null;)a=a.sibling,f=f.sibling=Ci(a,a.pendingProps),f.return=c;f.sibling=null}return c.child}function wc(a,c){return(a.lanes&c)!==0?!0:(a=a.dependencies,!!(a!==null&&To(a)))}function $h(a,c,f){switch(c.tag){case 3:me(c,c.stateNode.containerInfo),ts(c,Jr,a.memoizedState.cache),Is();break;case 27:case 5:Be(c);break;case 4:me(c,c.stateNode.containerInfo);break;case 10:ts(c,c.type,c.memoizedProps.value);break;case 31:if(c.memoizedState!==null)return c.flags|=128,Kl(c),null;break;case 13:var y=c.memoizedState;if(y!==null)return y.dehydrated!==null?(os(c),c.flags|=128,null):(f&c.child.childLanes)!==0?Ld(a,c,f):(os(c),a=Pi(a,c,f),a!==null?a.sibling:null);os(c);break;case 19:var R=(a.flags&128)!==0;if(y=(f&c.childLanes)!==0,y||(ea(a,c,f,!1),y=(f&c.childLanes)!==0),R){if(y)return $d(a,c,f);c.flags|=128}if(R=c.memoizedState,R!==null&&(R.rendering=null,R.tail=null,R.lastEffect=null),te(Vr,Vr.current),y)break;return null;case 22:return c.lanes=0,Dd(a,c,f,c.pendingProps);case 24:ts(c,Jr,a.memoizedState.cache)}return Pi(a,c,f)}function Od(a,c,f){if(a!==null)if(a.memoizedProps!==c.pendingProps)Xr=!0;else{if(!wc(a,f)&&(c.flags&128)===0)return Xr=!1,$h(a,c,f);Xr=(a.flags&131072)!==0}else Xr=!1,Gt&&(c.flags&1048576)!==0&&mu(c,Fa,c.index);switch(c.lanes=0,c.tag){case 16:e:{var y=c.pendingProps;if(a=Us(c.elementType),c.type=a,typeof a=="function")Al(a)?(y=js(a,y),c.tag=1,c=Pd(null,c,a,y,f)):(c.tag=0,c=gc(null,c,a,y,f));else{if(a!=null){var R=a.$$typeof;if(R===F){c.tag=11,c=Ad(null,c,a,y,f);break e}else if(R===O){c.tag=14,c=Cd(null,c,a,y,f);break e}}throw c=Ae(a)||a,Error(i(306,c,""))}}return c;case 0:return gc(a,c,c.type,c.pendingProps,f);case 1:return y=c.type,R=js(y,c.pendingProps),Pd(a,c,y,R,f);case 3:e:{if(me(c,c.stateNode.containerInfo),a===null)throw Error(i(387));y=c.pendingProps;var D=c.memoizedState;R=D.element,ql(a,c),Ma(c,y,null,f);var Z=c.memoizedState;if(y=Z.cache,ts(c,Jr,y),y!==D.cache&&Ll(c,[Jr],f,!0),Oa(),y=Z.element,D.isDehydrated)if(D={element:y,isDehydrated:!1,cache:Z.cache},c.updateQueue.baseState=D,c.memoizedState=D,c.flags&256){c=kd(a,c,y,f);break e}else if(y!==R){R=ei(Error(i(424)),c),Ua(R),c=kd(a,c,y,f);break e}else for(a=c.stateNode.containerInfo,a.nodeType===9?a=a.body:a=a.nodeName==="HTML"?a.ownerDocument.body:a,Cr=si(a.firstChild),dn=c,Gt=!0,Yi=null,ni=!0,f=Iu(c,null,y,f),c.child=f;f;)f.flags=f.flags&-3|4096,f=f.sibling;else{if(Is(),y===R){c=Pi(a,c,f);break e}hn(a,c,y,f)}c=c.child}return c;case 26:return Ho(a,c),a===null?(f=Qf(c.type,null,c.pendingProps,null))?c.memoizedState=f:Gt||(f=c.type,a=c.pendingProps,y=ll(He.current).createElement(f),y[zt]=c,y[pr]=a,pn(y,f,a),Rr(y),c.stateNode=y):c.memoizedState=Qf(c.type,a.memoizedProps,c.pendingProps,a.memoizedState),null;case 27:return Be(c),a===null&&Gt&&(y=c.stateNode=Zf(c.type,c.pendingProps,He.current),dn=c,ni=!0,R=Cr,ms(c.type)?(tu=R,Cr=si(y.firstChild)):Cr=R),hn(a,c,c.pendingProps.children,f),Ho(a,c),a===null&&(c.flags|=4194304),c.child;case 5:return a===null&&Gt&&((R=y=Cr)&&(y=pp(y,c.type,c.pendingProps,ni),y!==null?(c.stateNode=y,dn=c,Cr=si(y.firstChild),ni=!1,R=!0):R=!1),R||es(c)),Be(c),R=c.type,D=c.pendingProps,Z=a!==null?a.memoizedProps:null,y=D.children,Jc(R,D)?y=null:Z!==null&&Jc(R,Z)&&(c.flags|=32),c.memoizedState!==null&&(R=Gl(a,c,Ih,null,null,f),ao._currentValue=R),Ho(a,c),hn(a,c,y,f),c.child;case 6:return a===null&&Gt&&((a=f=Cr)&&(f=gp(f,c.pendingProps,ni),f!==null?(c.stateNode=f,dn=c,Cr=null,a=!0):a=!1),a||es(c)),null;case 13:return Ld(a,c,f);case 4:return me(c,c.stateNode.containerInfo),y=c.pendingProps,a===null?c.child=ks(c,null,y,f):hn(a,c,y,f),c.child;case 11:return Ad(a,c,c.type,c.pendingProps,f);case 7:return hn(a,c,c.pendingProps,f),c.child;case 8:return hn(a,c,c.pendingProps.children,f),c.child;case 12:return hn(a,c,c.pendingProps.children,f),c.child;case 10:return y=c.pendingProps,ts(c,c.type,y.value),hn(a,c,y.children,f),c.child;case 9:return R=c.type._context,y=c.pendingProps.children,Ns(c),R=fn(R),y=y(R),c.flags|=1,hn(a,c,y,f),c.child;case 14:return Cd(a,c,c.type,c.pendingProps,f);case 15:return Id(a,c,c.type,c.pendingProps,f);case 19:return $d(a,c,f);case 31:return jh(a,c,f);case 22:return Dd(a,c,f,c.pendingProps);case 24:return Ns(c),y=fn(Jr),a===null?(R=Ol(),R===null&&(R=vr,D=jl(),R.pooledCache=D,D.refCount++,D!==null&&(R.pooledCacheLanes|=f),R=D),c.memoizedState={parent:y,cache:R},Bl(c),ts(c,Jr,R)):((a.lanes&f)!==0&&(ql(a,c),Ma(c,null,null,f),Oa()),R=a.memoizedState,D=c.memoizedState,R.parent!==y?(R={parent:y,cache:y},c.memoizedState=R,c.lanes===0&&(c.memoizedState=c.updateQueue.baseState=R),ts(c,Jr,y)):(y=D.cache,ts(c,Jr,y),y!==R.cache&&Ll(c,[Jr],f,!0))),hn(a,c,c.pendingProps.children,f),c.child;case 29:throw c.pendingProps}throw Error(i(156,c.tag))}function ki(a){a.flags|=4}function xc(a,c,f,y,R){if((c=(a.mode&32)!==0)&&(c=!1),c){if(a.flags|=16777216,(R&335544128)===R)if(a.stateNode.complete)a.flags|=8192;else if(hf())a.flags|=8192;else throw Ps=Do,Ml}else a.flags&=-16777217}function Md(a,c){if(c.type!=="stylesheet"||(c.state.loading&4)!==0)a.flags&=-16777217;else if(a.flags|=16777216,!rh(c))if(hf())a.flags|=8192;else throw Ps=Do,Ml}function Ko(a,c){c!==null&&(a.flags|=4),a.flags&16384&&(c=a.tag!==22?V():536870912,a.lanes|=c,fa|=c)}function Wa(a,c){if(!Gt)switch(a.tailMode){case"hidden":c=a.tail;for(var f=null;c!==null;)c.alternate!==null&&(f=c),c=c.sibling;f===null?a.tail=null:f.sibling=null;break;case"collapsed":f=a.tail;for(var y=null;f!==null;)f.alternate!==null&&(y=f),f=f.sibling;y===null?c||a.tail===null?a.tail=null:a.tail.sibling=null:y.sibling=null}}function Ir(a){var c=a.alternate!==null&&a.alternate.child===a.child,f=0,y=0;if(c)for(var R=a.child;R!==null;)f|=R.lanes|R.childLanes,y|=R.subtreeFlags&65011712,y|=R.flags&65011712,R.return=a,R=R.sibling;else for(R=a.child;R!==null;)f|=R.lanes|R.childLanes,y|=R.subtreeFlags,y|=R.flags,R.return=a,R=R.sibling;return a.subtreeFlags|=y,a.childLanes=f,c}function Oh(a,c,f){var y=c.pendingProps;switch(Nl(c),c.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Ir(c),null;case 1:return Ir(c),null;case 3:return f=c.stateNode,y=null,a!==null&&(y=a.memoizedState.cache),c.memoizedState.cache!==y&&(c.flags|=2048),Ni(Jr),ge(),f.pendingContext&&(f.context=f.pendingContext,f.pendingContext=null),(a===null||a.child===null)&&(Ys(c)?ki(c):a===null||a.memoizedState.isDehydrated&&(c.flags&256)===0||(c.flags|=1024,Ul())),Ir(c),null;case 26:var R=c.type,D=c.memoizedState;return a===null?(ki(c),D!==null?(Ir(c),Md(c,D)):(Ir(c),xc(c,R,null,y,f))):D?D!==a.memoizedState?(ki(c),Ir(c),Md(c,D)):(Ir(c),c.flags&=-16777217):(a=a.memoizedProps,a!==y&&ki(c),Ir(c),xc(c,R,a,y,f)),null;case 27:if(ie(c),f=He.current,R=c.type,a!==null&&c.stateNode!=null)a.memoizedProps!==y&&ki(c);else{if(!y){if(c.stateNode===null)throw Error(i(166));return Ir(c),null}a=Te.current,Ys(c)?bu(c):(a=Zf(R,y,f),c.stateNode=a,ki(c))}return Ir(c),null;case 5:if(ie(c),R=c.type,a!==null&&c.stateNode!=null)a.memoizedProps!==y&&ki(c);else{if(!y){if(c.stateNode===null)throw Error(i(166));return Ir(c),null}if(D=Te.current,Ys(c))bu(c);else{var Z=ll(He.current);switch(D){case 1:D=Z.createElementNS("http://www.w3.org/2000/svg",R);break;case 2:D=Z.createElementNS("http://www.w3.org/1998/Math/MathML",R);break;default:switch(R){case"svg":D=Z.createElementNS("http://www.w3.org/2000/svg",R);break;case"math":D=Z.createElementNS("http://www.w3.org/1998/Math/MathML",R);break;case"script":D=Z.createElement("div"),D.innerHTML="<script><\/script>",D=D.removeChild(D.firstChild);break;case"select":D=typeof y.is=="string"?Z.createElement("select",{is:y.is}):Z.createElement("select"),y.multiple?D.multiple=!0:y.size&&(D.size=y.size);break;default:D=typeof y.is=="string"?Z.createElement(R,{is:y.is}):Z.createElement(R)}}D[zt]=c,D[pr]=y;e:for(Z=c.child;Z!==null;){if(Z.tag===5||Z.tag===6)D.appendChild(Z.stateNode);else if(Z.tag!==4&&Z.tag!==27&&Z.child!==null){Z.child.return=Z,Z=Z.child;continue}if(Z===c)break e;for(;Z.sibling===null;){if(Z.return===null||Z.return===c)break e;Z=Z.return}Z.sibling.return=Z.return,Z=Z.sibling}c.stateNode=D;e:switch(pn(D,R,y),R){case"button":case"input":case"select":case"textarea":y=!!y.autoFocus;break e;case"img":y=!0;break e;default:y=!1}y&&ki(c)}}return Ir(c),xc(c,c.type,a===null?null:a.memoizedProps,c.pendingProps,f),null;case 6:if(a&&c.stateNode!=null)a.memoizedProps!==y&&ki(c);else{if(typeof y!="string"&&c.stateNode===null)throw Error(i(166));if(a=He.current,Ys(c)){if(a=c.stateNode,f=c.memoizedProps,y=null,R=dn,R!==null)switch(R.tag){case 27:case 5:y=R.memoizedProps}a[zt]=c,a=!!(a.nodeValue===f||y!==null&&y.suppressHydrationWarning===!0||jf(a.nodeValue,f)),a||es(c,!0)}else a=ll(a).createTextNode(y),a[zt]=c,c.stateNode=a}return Ir(c),null;case 31:if(f=c.memoizedState,a===null||a.memoizedState!==null){if(y=Ys(c),f!==null){if(a===null){if(!y)throw Error(i(318));if(a=c.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(i(557));a[zt]=c}else Is(),(c.flags&128)===0&&(c.memoizedState=null),c.flags|=4;Ir(c),a=!1}else f=Ul(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=f),a=!0;if(!a)return c.flags&256?(On(c),c):(On(c),null);if((c.flags&128)!==0)throw Error(i(558))}return Ir(c),null;case 13:if(y=c.memoizedState,a===null||a.memoizedState!==null&&a.memoizedState.dehydrated!==null){if(R=Ys(c),y!==null&&y.dehydrated!==null){if(a===null){if(!R)throw Error(i(318));if(R=c.memoizedState,R=R!==null?R.dehydrated:null,!R)throw Error(i(317));R[zt]=c}else Is(),(c.flags&128)===0&&(c.memoizedState=null),c.flags|=4;Ir(c),R=!1}else R=Ul(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=R),R=!0;if(!R)return c.flags&256?(On(c),c):(On(c),null)}return On(c),(c.flags&128)!==0?(c.lanes=f,c):(f=y!==null,a=a!==null&&a.memoizedState!==null,f&&(y=c.child,R=null,y.alternate!==null&&y.alternate.memoizedState!==null&&y.alternate.memoizedState.cachePool!==null&&(R=y.alternate.memoizedState.cachePool.pool),D=null,y.memoizedState!==null&&y.memoizedState.cachePool!==null&&(D=y.memoizedState.cachePool.pool),D!==R&&(y.flags|=2048)),f!==a&&f&&(c.child.flags|=8192),Ko(c,c.updateQueue),Ir(c),null);case 4:return ge(),a===null&&Hc(c.stateNode.containerInfo),Ir(c),null;case 10:return Ni(c.type),Ir(c),null;case 19:if(de(Vr),y=c.memoizedState,y===null)return Ir(c),null;if(R=(c.flags&128)!==0,D=y.rendering,D===null)if(R)Wa(y,!1);else{if(qr!==0||a!==null&&(a.flags&128)!==0)for(a=c.child;a!==null;){if(D=Po(a),D!==null){for(c.flags|=128,Wa(y,!1),a=D.updateQueue,c.updateQueue=a,Ko(c,a),c.subtreeFlags=0,a=f,f=c.child;f!==null;)hu(f,a),f=f.sibling;return te(Vr,Vr.current&1|2),Gt&&Ii(c,y.treeForkCount),c.child}a=a.sibling}y.tail!==null&&ht()>Xo&&(c.flags|=128,R=!0,Wa(y,!1),c.lanes=4194304)}else{if(!R)if(a=Po(D),a!==null){if(c.flags|=128,R=!0,a=a.updateQueue,c.updateQueue=a,Ko(c,a),Wa(y,!0),y.tail===null&&y.tailMode==="hidden"&&!D.alternate&&!Gt)return Ir(c),null}else 2*ht()-y.renderingStartTime>Xo&&f!==536870912&&(c.flags|=128,R=!0,Wa(y,!1),c.lanes=4194304);y.isBackwards?(D.sibling=c.child,c.child=D):(a=y.last,a!==null?a.sibling=D:c.child=D,y.last=D)}return y.tail!==null?(a=y.tail,y.rendering=a,y.tail=a.sibling,y.renderingStartTime=ht(),a.sibling=null,f=Vr.current,te(Vr,R?f&1|2:f&1),Gt&&Ii(c,y.treeForkCount),a):(Ir(c),null);case 22:case 23:return On(c),Wl(),y=c.memoizedState!==null,a!==null?a.memoizedState!==null!==y&&(c.flags|=8192):y&&(c.flags|=8192),y?(f&536870912)!==0&&(c.flags&128)===0&&(Ir(c),c.subtreeFlags&6&&(c.flags|=8192)):Ir(c),f=c.updateQueue,f!==null&&Ko(c,f.retryQueue),f=null,a!==null&&a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(f=a.memoizedState.cachePool.pool),y=null,c.memoizedState!==null&&c.memoizedState.cachePool!==null&&(y=c.memoizedState.cachePool.pool),y!==f&&(c.flags|=2048),a!==null&&de(Fs),null;case 24:return f=null,a!==null&&(f=a.memoizedState.cache),c.memoizedState.cache!==f&&(c.flags|=2048),Ni(Jr),Ir(c),null;case 25:return null;case 30:return null}throw Error(i(156,c.tag))}function Mh(a,c){switch(Nl(c),c.tag){case 1:return a=c.flags,a&65536?(c.flags=a&-65537|128,c):null;case 3:return Ni(Jr),ge(),a=c.flags,(a&65536)!==0&&(a&128)===0?(c.flags=a&-65537|128,c):null;case 26:case 27:case 5:return ie(c),null;case 31:if(c.memoizedState!==null){if(On(c),c.alternate===null)throw Error(i(340));Is()}return a=c.flags,a&65536?(c.flags=a&-65537|128,c):null;case 13:if(On(c),a=c.memoizedState,a!==null&&a.dehydrated!==null){if(c.alternate===null)throw Error(i(340));Is()}return a=c.flags,a&65536?(c.flags=a&-65537|128,c):null;case 19:return de(Vr),null;case 4:return ge(),null;case 10:return Ni(c.type),null;case 22:case 23:return On(c),Wl(),a!==null&&de(Fs),a=c.flags,a&65536?(c.flags=a&-65537|128,c):null;case 24:return Ni(Jr),null;case 25:return null;default:return null}}function Bd(a,c){switch(Nl(c),c.tag){case 3:Ni(Jr),ge();break;case 26:case 27:case 5:ie(c);break;case 4:ge();break;case 31:c.memoizedState!==null&&On(c);break;case 13:On(c);break;case 19:de(Vr);break;case 10:Ni(c.type);break;case 22:case 23:On(c),Wl(),a!==null&&de(Fs);break;case 24:Ni(Jr)}}function Ka(a,c){try{var f=c.updateQueue,y=f!==null?f.lastEffect:null;if(y!==null){var R=y.next;f=R;do{if((f.tag&a)===a){y=void 0;var D=f.create,Z=f.inst;y=D(),Z.destroy=y}f=f.next}while(f!==R)}}catch(ue){fr(c,c.return,ue)}}function cs(a,c,f){try{var y=c.updateQueue,R=y!==null?y.lastEffect:null;if(R!==null){var D=R.next;y=D;do{if((y.tag&a)===a){var Z=y.inst,ue=Z.destroy;if(ue!==void 0){Z.destroy=void 0,R=c;var $e=f,et=ue;try{et()}catch(ct){fr(R,$e,ct)}}}y=y.next}while(y!==D)}}catch(ct){fr(c,c.return,ct)}}function qd(a){var c=a.updateQueue;if(c!==null){var f=a.stateNode;try{Nu(c,f)}catch(y){fr(a,a.return,y)}}}function zd(a,c,f){f.props=js(a.type,a.memoizedProps),f.state=a.memoizedState;try{f.componentWillUnmount()}catch(y){fr(a,c,y)}}function Za(a,c){try{var f=a.ref;if(f!==null){switch(a.tag){case 26:case 27:case 5:var y=a.stateNode;break;case 30:y=a.stateNode;break;default:y=a.stateNode}typeof f=="function"?a.refCleanup=f(y):f.current=y}}catch(R){fr(a,c,R)}}function _i(a,c){var f=a.ref,y=a.refCleanup;if(f!==null)if(typeof y=="function")try{y()}catch(R){fr(a,c,R)}finally{a.refCleanup=null,a=a.alternate,a!=null&&(a.refCleanup=null)}else if(typeof f=="function")try{f(null)}catch(R){fr(a,c,R)}else f.current=null}function Vd(a){var c=a.type,f=a.memoizedProps,y=a.stateNode;try{e:switch(c){case"button":case"input":case"select":case"textarea":f.autoFocus&&y.focus();break e;case"img":f.src?y.src=f.src:f.srcSet&&(y.srcset=f.srcSet)}}catch(R){fr(a,a.return,R)}}function Ec(a,c,f){try{var y=a.stateNode;lp(y,a.type,f,c),y[pr]=c}catch(R){fr(a,a.return,R)}}function Hd(a){return a.tag===5||a.tag===3||a.tag===26||a.tag===27&&ms(a.type)||a.tag===4}function Rc(a){e:for(;;){for(;a.sibling===null;){if(a.return===null||Hd(a.return))return null;a=a.return}for(a.sibling.return=a.return,a=a.sibling;a.tag!==5&&a.tag!==6&&a.tag!==18;){if(a.tag===27&&ms(a.type)||a.flags&2||a.child===null||a.tag===4)continue e;a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}function Tc(a,c,f){var y=a.tag;if(y===5||y===6)a=a.stateNode,c?(f.nodeType===9?f.body:f.nodeName==="HTML"?f.ownerDocument.body:f).insertBefore(a,c):(c=f.nodeType===9?f.body:f.nodeName==="HTML"?f.ownerDocument.body:f,c.appendChild(a),f=f._reactRootContainer,f!=null||c.onclick!==null||(c.onclick=vt));else if(y!==4&&(y===27&&ms(a.type)&&(f=a.stateNode,c=null),a=a.child,a!==null))for(Tc(a,c,f),a=a.sibling;a!==null;)Tc(a,c,f),a=a.sibling}function Zo(a,c,f){var y=a.tag;if(y===5||y===6)a=a.stateNode,c?f.insertBefore(a,c):f.appendChild(a);else if(y!==4&&(y===27&&ms(a.type)&&(f=a.stateNode),a=a.child,a!==null))for(Zo(a,c,f),a=a.sibling;a!==null;)Zo(a,c,f),a=a.sibling}function Wd(a){var c=a.stateNode,f=a.memoizedProps;try{for(var y=a.type,R=c.attributes;R.length;)c.removeAttributeNode(R[0]);pn(c,y,f),c[zt]=a,c[pr]=f}catch(D){fr(a,a.return,D)}}var Li=!1,Yr=!1,Ac=!1,Kd=typeof WeakSet=="function"?WeakSet:Set,an=null;function Bh(a,c){if(a=a.containerInfo,Zc=gl,a=Rs(a),Qi(a)){if("selectionStart"in a)var f={start:a.selectionStart,end:a.selectionEnd};else e:{f=(f=a.ownerDocument)&&f.defaultView||window;var y=f.getSelection&&f.getSelection();if(y&&y.rangeCount!==0){f=y.anchorNode;var R=y.anchorOffset,D=y.focusNode;y=y.focusOffset;try{f.nodeType,D.nodeType}catch{f=null;break e}var Z=0,ue=-1,$e=-1,et=0,ct=0,ft=a,rt=null;t:for(;;){for(var st;ft!==f||R!==0&&ft.nodeType!==3||(ue=Z+R),ft!==D||y!==0&&ft.nodeType!==3||($e=Z+y),ft.nodeType===3&&(Z+=ft.nodeValue.length),(st=ft.firstChild)!==null;)rt=ft,ft=st;for(;;){if(ft===a)break t;if(rt===f&&++et===R&&(ue=Z),rt===D&&++ct===y&&($e=Z),(st=ft.nextSibling)!==null)break;ft=rt,rt=ft.parentNode}ft=st}f=ue===-1||$e===-1?null:{start:ue,end:$e}}else f=null}f=f||{start:0,end:0}}else f=null;for(Gc={focusedElem:a,selectionRange:f},gl=!1,an=c;an!==null;)if(c=an,a=c.child,(c.subtreeFlags&1028)!==0&&a!==null)a.return=c,an=a;else for(;an!==null;){switch(c=an,D=c.alternate,a=c.flags,c.tag){case 0:if((a&4)!==0&&(a=c.updateQueue,a=a!==null?a.events:null,a!==null))for(f=0;f<a.length;f++)R=a[f],R.ref.impl=R.nextImpl;break;case 11:case 15:break;case 1:if((a&1024)!==0&&D!==null){a=void 0,f=c,R=D.memoizedProps,D=D.memoizedState,y=f.stateNode;try{var xt=js(f.type,R);a=y.getSnapshotBeforeUpdate(xt,D),y.__reactInternalSnapshotBeforeUpdate=a}catch(It){fr(f,f.return,It)}}break;case 3:if((a&1024)!==0){if(a=c.stateNode.containerInfo,f=a.nodeType,f===9)Xc(a);else if(f===1)switch(a.nodeName){case"HEAD":case"HTML":case"BODY":Xc(a);break;default:a.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((a&1024)!==0)throw Error(i(163))}if(a=c.sibling,a!==null){a.return=c.return,an=a;break}an=c.return}}function Zd(a,c,f){var y=f.flags;switch(f.tag){case 0:case 11:case 15:$i(a,f),y&4&&Ka(5,f);break;case 1:if($i(a,f),y&4)if(a=f.stateNode,c===null)try{a.componentDidMount()}catch(Z){fr(f,f.return,Z)}else{var R=js(f.type,c.memoizedProps);c=c.memoizedState;try{a.componentDidUpdate(R,c,a.__reactInternalSnapshotBeforeUpdate)}catch(Z){fr(f,f.return,Z)}}y&64&&qd(f),y&512&&Za(f,f.return);break;case 3:if($i(a,f),y&64&&(a=f.updateQueue,a!==null)){if(c=null,f.child!==null)switch(f.child.tag){case 27:case 5:c=f.child.stateNode;break;case 1:c=f.child.stateNode}try{Nu(a,c)}catch(Z){fr(f,f.return,Z)}}break;case 27:c===null&&y&4&&Wd(f);case 26:case 5:$i(a,f),c===null&&y&4&&Vd(f),y&512&&Za(f,f.return);break;case 12:$i(a,f);break;case 31:$i(a,f),y&4&&Qd(a,f);break;case 13:$i(a,f),y&4&&Xd(a,f),y&64&&(a=f.memoizedState,a!==null&&(a=a.dehydrated,a!==null&&(f=Jh.bind(null,f),mp(a,f))));break;case 22:if(y=f.memoizedState!==null||Li,!y){c=c!==null&&c.memoizedState!==null||Yr,R=Li;var D=Yr;Li=y,(Yr=c)&&!D?Oi(a,f,(f.subtreeFlags&8772)!==0):$i(a,f),Li=R,Yr=D}break;case 30:break;default:$i(a,f)}}function Gd(a){var c=a.alternate;c!==null&&(a.alternate=null,Gd(c)),a.child=null,a.deletions=null,a.sibling=null,a.tag===5&&(c=a.stateNode,c!==null&&Sr(c)),a.stateNode=null,a.return=null,a.dependencies=null,a.memoizedProps=null,a.memoizedState=null,a.pendingProps=null,a.stateNode=null,a.updateQueue=null}var Ur=null,Cn=!1;function ji(a,c,f){for(f=f.child;f!==null;)Jd(a,c,f),f=f.sibling}function Jd(a,c,f){if(mt&&typeof mt.onCommitFiberUnmount=="function")try{mt.onCommitFiberUnmount(Le,f)}catch{}switch(f.tag){case 26:Yr||_i(f,c),ji(a,c,f),f.memoizedState?f.memoizedState.count--:f.stateNode&&(f=f.stateNode,f.parentNode.removeChild(f));break;case 27:Yr||_i(f,c);var y=Ur,R=Cn;ms(f.type)&&(Ur=f.stateNode,Cn=!1),ji(a,c,f),no(f.stateNode),Ur=y,Cn=R;break;case 5:Yr||_i(f,c);case 6:if(y=Ur,R=Cn,Ur=null,ji(a,c,f),Ur=y,Cn=R,Ur!==null)if(Cn)try{(Ur.nodeType===9?Ur.body:Ur.nodeName==="HTML"?Ur.ownerDocument.body:Ur).removeChild(f.stateNode)}catch(D){fr(f,c,D)}else try{Ur.removeChild(f.stateNode)}catch(D){fr(f,c,D)}break;case 18:Ur!==null&&(Cn?(a=Ur,zf(a.nodeType===9?a.body:a.nodeName==="HTML"?a.ownerDocument.body:a,f.stateNode),va(a)):zf(Ur,f.stateNode));break;case 4:y=Ur,R=Cn,Ur=f.stateNode.containerInfo,Cn=!0,ji(a,c,f),Ur=y,Cn=R;break;case 0:case 11:case 14:case 15:cs(2,f,c),Yr||cs(4,f,c),ji(a,c,f);break;case 1:Yr||(_i(f,c),y=f.stateNode,typeof y.componentWillUnmount=="function"&&zd(f,c,y)),ji(a,c,f);break;case 21:ji(a,c,f);break;case 22:Yr=(y=Yr)||f.memoizedState!==null,ji(a,c,f),Yr=y;break;default:ji(a,c,f)}}function Qd(a,c){if(c.memoizedState===null&&(a=c.alternate,a!==null&&(a=a.memoizedState,a!==null))){a=a.dehydrated;try{va(a)}catch(f){fr(c,c.return,f)}}}function Xd(a,c){if(c.memoizedState===null&&(a=c.alternate,a!==null&&(a=a.memoizedState,a!==null&&(a=a.dehydrated,a!==null))))try{va(a)}catch(f){fr(c,c.return,f)}}function qh(a){switch(a.tag){case 31:case 13:case 19:var c=a.stateNode;return c===null&&(c=a.stateNode=new Kd),c;case 22:return a=a.stateNode,c=a._retryCache,c===null&&(c=a._retryCache=new Kd),c;default:throw Error(i(435,a.tag))}}function Go(a,c){var f=qh(a);c.forEach(function(y){if(!f.has(y)){f.add(y);var R=Qh.bind(null,a,y);y.then(R,R)}})}function In(a,c){var f=c.deletions;if(f!==null)for(var y=0;y<f.length;y++){var R=f[y],D=a,Z=c,ue=Z;e:for(;ue!==null;){switch(ue.tag){case 27:if(ms(ue.type)){Ur=ue.stateNode,Cn=!1;break e}break;case 5:Ur=ue.stateNode,Cn=!1;break e;case 3:case 4:Ur=ue.stateNode.containerInfo,Cn=!0;break e}ue=ue.return}if(Ur===null)throw Error(i(160));Jd(D,Z,R),Ur=null,Cn=!1,D=R.alternate,D!==null&&(D.return=null),R.return=null}if(c.subtreeFlags&13886)for(c=c.child;c!==null;)Yd(c,a),c=c.sibling}var hi=null;function Yd(a,c){var f=a.alternate,y=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:In(c,a),Dn(a),y&4&&(cs(3,a,a.return),Ka(3,a),cs(5,a,a.return));break;case 1:In(c,a),Dn(a),y&512&&(Yr||f===null||_i(f,f.return)),y&64&&Li&&(a=a.updateQueue,a!==null&&(y=a.callbacks,y!==null&&(f=a.shared.hiddenCallbacks,a.shared.hiddenCallbacks=f===null?y:f.concat(y))));break;case 26:var R=hi;if(In(c,a),Dn(a),y&512&&(Yr||f===null||_i(f,f.return)),y&4){var D=f!==null?f.memoizedState:null;if(y=a.memoizedState,f===null)if(y===null)if(a.stateNode===null){e:{y=a.type,f=a.memoizedProps,R=R.ownerDocument||R;t:switch(y){case"title":D=R.getElementsByTagName("title")[0],(!D||D[li]||D[zt]||D.namespaceURI==="http://www.w3.org/2000/svg"||D.hasAttribute("itemprop"))&&(D=R.createElement(y),R.head.insertBefore(D,R.querySelector("head > title"))),pn(D,y,f),D[zt]=a,Rr(D),y=D;break e;case"link":var Z=eh("link","href",R).get(y+(f.href||""));if(Z){for(var ue=0;ue<Z.length;ue++)if(D=Z[ue],D.getAttribute("href")===(f.href==null||f.href===""?null:f.href)&&D.getAttribute("rel")===(f.rel==null?null:f.rel)&&D.getAttribute("title")===(f.title==null?null:f.title)&&D.getAttribute("crossorigin")===(f.crossOrigin==null?null:f.crossOrigin)){Z.splice(ue,1);break t}}D=R.createElement(y),pn(D,y,f),R.head.appendChild(D);break;case"meta":if(Z=eh("meta","content",R).get(y+(f.content||""))){for(ue=0;ue<Z.length;ue++)if(D=Z[ue],D.getAttribute("content")===(f.content==null?null:""+f.content)&&D.getAttribute("name")===(f.name==null?null:f.name)&&D.getAttribute("property")===(f.property==null?null:f.property)&&D.getAttribute("http-equiv")===(f.httpEquiv==null?null:f.httpEquiv)&&D.getAttribute("charset")===(f.charSet==null?null:f.charSet)){Z.splice(ue,1);break t}}D=R.createElement(y),pn(D,y,f),R.head.appendChild(D);break;default:throw Error(i(468,y))}D[zt]=a,Rr(D),y=D}a.stateNode=y}else th(R,a.type,a.stateNode);else a.stateNode=Yf(R,y,a.memoizedProps);else D!==y?(D===null?f.stateNode!==null&&(f=f.stateNode,f.parentNode.removeChild(f)):D.count--,y===null?th(R,a.type,a.stateNode):Yf(R,y,a.memoizedProps)):y===null&&a.stateNode!==null&&Ec(a,a.memoizedProps,f.memoizedProps)}break;case 27:In(c,a),Dn(a),y&512&&(Yr||f===null||_i(f,f.return)),f!==null&&y&4&&Ec(a,a.memoizedProps,f.memoizedProps);break;case 5:if(In(c,a),Dn(a),y&512&&(Yr||f===null||_i(f,f.return)),a.flags&32){R=a.stateNode;try{De(R,"")}catch(xt){fr(a,a.return,xt)}}y&4&&a.stateNode!=null&&(R=a.memoizedProps,Ec(a,R,f!==null?f.memoizedProps:R)),y&1024&&(Ac=!0);break;case 6:if(In(c,a),Dn(a),y&4){if(a.stateNode===null)throw Error(i(162));y=a.memoizedProps,f=a.stateNode;try{f.nodeValue=y}catch(xt){fr(a,a.return,xt)}}break;case 3:if(dl=null,R=hi,hi=cl(c.containerInfo),In(c,a),hi=R,Dn(a),y&4&&f!==null&&f.memoizedState.isDehydrated)try{va(c.containerInfo)}catch(xt){fr(a,a.return,xt)}Ac&&(Ac=!1,ef(a));break;case 4:y=hi,hi=cl(a.stateNode.containerInfo),In(c,a),Dn(a),hi=y;break;case 12:In(c,a),Dn(a);break;case 31:In(c,a),Dn(a),y&4&&(y=a.updateQueue,y!==null&&(a.updateQueue=null,Go(a,y)));break;case 13:In(c,a),Dn(a),a.child.flags&8192&&a.memoizedState!==null!=(f!==null&&f.memoizedState!==null)&&(Qo=ht()),y&4&&(y=a.updateQueue,y!==null&&(a.updateQueue=null,Go(a,y)));break;case 22:R=a.memoizedState!==null;var $e=f!==null&&f.memoizedState!==null,et=Li,ct=Yr;if(Li=et||R,Yr=ct||$e,In(c,a),Yr=ct,Li=et,Dn(a),y&8192)e:for(c=a.stateNode,c._visibility=R?c._visibility&-2:c._visibility|1,R&&(f===null||$e||Li||Yr||$s(a)),f=null,c=a;;){if(c.tag===5||c.tag===26){if(f===null){$e=f=c;try{if(D=$e.stateNode,R)Z=D.style,typeof Z.setProperty=="function"?Z.setProperty("display","none","important"):Z.display="none";else{ue=$e.stateNode;var ft=$e.memoizedProps.style,rt=ft!=null&&ft.hasOwnProperty("display")?ft.display:null;ue.style.display=rt==null||typeof rt=="boolean"?"":(""+rt).trim()}}catch(xt){fr($e,$e.return,xt)}}}else if(c.tag===6){if(f===null){$e=c;try{$e.stateNode.nodeValue=R?"":$e.memoizedProps}catch(xt){fr($e,$e.return,xt)}}}else if(c.tag===18){if(f===null){$e=c;try{var st=$e.stateNode;R?Vf(st,!0):Vf($e.stateNode,!1)}catch(xt){fr($e,$e.return,xt)}}}else if((c.tag!==22&&c.tag!==23||c.memoizedState===null||c===a)&&c.child!==null){c.child.return=c,c=c.child;continue}if(c===a)break e;for(;c.sibling===null;){if(c.return===null||c.return===a)break e;f===c&&(f=null),c=c.return}f===c&&(f=null),c.sibling.return=c.return,c=c.sibling}y&4&&(y=a.updateQueue,y!==null&&(f=y.retryQueue,f!==null&&(y.retryQueue=null,Go(a,f))));break;case 19:In(c,a),Dn(a),y&4&&(y=a.updateQueue,y!==null&&(a.updateQueue=null,Go(a,y)));break;case 30:break;case 21:break;default:In(c,a),Dn(a)}}function Dn(a){var c=a.flags;if(c&2){try{for(var f,y=a.return;y!==null;){if(Hd(y)){f=y;break}y=y.return}if(f==null)throw Error(i(160));switch(f.tag){case 27:var R=f.stateNode,D=Rc(a);Zo(a,D,R);break;case 5:var Z=f.stateNode;f.flags&32&&(De(Z,""),f.flags&=-33);var ue=Rc(a);Zo(a,ue,Z);break;case 3:case 4:var $e=f.stateNode.containerInfo,et=Rc(a);Tc(a,et,$e);break;default:throw Error(i(161))}}catch(ct){fr(a,a.return,ct)}a.flags&=-3}c&4096&&(a.flags&=-4097)}function ef(a){if(a.subtreeFlags&1024)for(a=a.child;a!==null;){var c=a;ef(c),c.tag===5&&c.flags&1024&&c.stateNode.reset(),a=a.sibling}}function $i(a,c){if(c.subtreeFlags&8772)for(c=c.child;c!==null;)Zd(a,c.alternate,c),c=c.sibling}function $s(a){for(a=a.child;a!==null;){var c=a;switch(c.tag){case 0:case 11:case 14:case 15:cs(4,c,c.return),$s(c);break;case 1:_i(c,c.return);var f=c.stateNode;typeof f.componentWillUnmount=="function"&&zd(c,c.return,f),$s(c);break;case 27:no(c.stateNode);case 26:case 5:_i(c,c.return),$s(c);break;case 22:c.memoizedState===null&&$s(c);break;case 30:$s(c);break;default:$s(c)}a=a.sibling}}function Oi(a,c,f){for(f=f&&(c.subtreeFlags&8772)!==0,c=c.child;c!==null;){var y=c.alternate,R=a,D=c,Z=D.flags;switch(D.tag){case 0:case 11:case 15:Oi(R,D,f),Ka(4,D);break;case 1:if(Oi(R,D,f),y=D,R=y.stateNode,typeof R.componentDidMount=="function")try{R.componentDidMount()}catch(et){fr(y,y.return,et)}if(y=D,R=y.updateQueue,R!==null){var ue=y.stateNode;try{var $e=R.shared.hiddenCallbacks;if($e!==null)for(R.shared.hiddenCallbacks=null,R=0;R<$e.length;R++)Du($e[R],ue)}catch(et){fr(y,y.return,et)}}f&&Z&64&&qd(D),Za(D,D.return);break;case 27:Wd(D);case 26:case 5:Oi(R,D,f),f&&y===null&&Z&4&&Vd(D),Za(D,D.return);break;case 12:Oi(R,D,f);break;case 31:Oi(R,D,f),f&&Z&4&&Qd(R,D);break;case 13:Oi(R,D,f),f&&Z&4&&Xd(R,D);break;case 22:D.memoizedState===null&&Oi(R,D,f),Za(D,D.return);break;case 30:break;default:Oi(R,D,f)}c=c.sibling}}function Cc(a,c){var f=null;a!==null&&a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(f=a.memoizedState.cachePool.pool),a=null,c.memoizedState!==null&&c.memoizedState.cachePool!==null&&(a=c.memoizedState.cachePool.pool),a!==f&&(a!=null&&a.refCount++,f!=null&&Pa(f))}function Ic(a,c){a=null,c.alternate!==null&&(a=c.alternate.memoizedState.cache),c=c.memoizedState.cache,c!==a&&(c.refCount++,a!=null&&Pa(a))}function pi(a,c,f,y){if(c.subtreeFlags&10256)for(c=c.child;c!==null;)tf(a,c,f,y),c=c.sibling}function tf(a,c,f,y){var R=c.flags;switch(c.tag){case 0:case 11:case 15:pi(a,c,f,y),R&2048&&Ka(9,c);break;case 1:pi(a,c,f,y);break;case 3:pi(a,c,f,y),R&2048&&(a=null,c.alternate!==null&&(a=c.alternate.memoizedState.cache),c=c.memoizedState.cache,c!==a&&(c.refCount++,a!=null&&Pa(a)));break;case 12:if(R&2048){pi(a,c,f,y),a=c.stateNode;try{var D=c.memoizedProps,Z=D.id,ue=D.onPostCommit;typeof ue=="function"&&ue(Z,c.alternate===null?"mount":"update",a.passiveEffectDuration,-0)}catch($e){fr(c,c.return,$e)}}else pi(a,c,f,y);break;case 31:pi(a,c,f,y);break;case 13:pi(a,c,f,y);break;case 23:break;case 22:D=c.stateNode,Z=c.alternate,c.memoizedState!==null?D._visibility&2?pi(a,c,f,y):Ga(a,c):D._visibility&2?pi(a,c,f,y):(D._visibility|=2,ca(a,c,f,y,(c.subtreeFlags&10256)!==0||!1)),R&2048&&Cc(Z,c);break;case 24:pi(a,c,f,y),R&2048&&Ic(c.alternate,c);break;default:pi(a,c,f,y)}}function ca(a,c,f,y,R){for(R=R&&((c.subtreeFlags&10256)!==0||!1),c=c.child;c!==null;){var D=a,Z=c,ue=f,$e=y,et=Z.flags;switch(Z.tag){case 0:case 11:case 15:ca(D,Z,ue,$e,R),Ka(8,Z);break;case 23:break;case 22:var ct=Z.stateNode;Z.memoizedState!==null?ct._visibility&2?ca(D,Z,ue,$e,R):Ga(D,Z):(ct._visibility|=2,ca(D,Z,ue,$e,R)),R&&et&2048&&Cc(Z.alternate,Z);break;case 24:ca(D,Z,ue,$e,R),R&&et&2048&&Ic(Z.alternate,Z);break;default:ca(D,Z,ue,$e,R)}c=c.sibling}}function Ga(a,c){if(c.subtreeFlags&10256)for(c=c.child;c!==null;){var f=a,y=c,R=y.flags;switch(y.tag){case 22:Ga(f,y),R&2048&&Cc(y.alternate,y);break;case 24:Ga(f,y),R&2048&&Ic(y.alternate,y);break;default:Ga(f,y)}c=c.sibling}}var Ja=8192;function ua(a,c,f){if(a.subtreeFlags&Ja)for(a=a.child;a!==null;)rf(a,c,f),a=a.sibling}function rf(a,c,f){switch(a.tag){case 26:ua(a,c,f),a.flags&Ja&&a.memoizedState!==null&&Cp(f,hi,a.memoizedState,a.memoizedProps);break;case 5:ua(a,c,f);break;case 3:case 4:var y=hi;hi=cl(a.stateNode.containerInfo),ua(a,c,f),hi=y;break;case 22:a.memoizedState===null&&(y=a.alternate,y!==null&&y.memoizedState!==null?(y=Ja,Ja=16777216,ua(a,c,f),Ja=y):ua(a,c,f));break;default:ua(a,c,f)}}function nf(a){var c=a.alternate;if(c!==null&&(a=c.child,a!==null)){c.child=null;do c=a.sibling,a.sibling=null,a=c;while(a!==null)}}function Qa(a){var c=a.deletions;if((a.flags&16)!==0){if(c!==null)for(var f=0;f<c.length;f++){var y=c[f];an=y,af(y,a)}nf(a)}if(a.subtreeFlags&10256)for(a=a.child;a!==null;)sf(a),a=a.sibling}function sf(a){switch(a.tag){case 0:case 11:case 15:Qa(a),a.flags&2048&&cs(9,a,a.return);break;case 3:Qa(a);break;case 12:Qa(a);break;case 22:var c=a.stateNode;a.memoizedState!==null&&c._visibility&2&&(a.return===null||a.return.tag!==13)?(c._visibility&=-3,Jo(a)):Qa(a);break;default:Qa(a)}}function Jo(a){var c=a.deletions;if((a.flags&16)!==0){if(c!==null)for(var f=0;f<c.length;f++){var y=c[f];an=y,af(y,a)}nf(a)}for(a=a.child;a!==null;){switch(c=a,c.tag){case 0:case 11:case 15:cs(8,c,c.return),Jo(c);break;case 22:f=c.stateNode,f._visibility&2&&(f._visibility&=-3,Jo(c));break;default:Jo(c)}a=a.sibling}}function af(a,c){for(;an!==null;){var f=an;switch(f.tag){case 0:case 11:case 15:cs(8,f,c);break;case 23:case 22:if(f.memoizedState!==null&&f.memoizedState.cachePool!==null){var y=f.memoizedState.cachePool.pool;y!=null&&y.refCount++}break;case 24:Pa(f.memoizedState.cache)}if(y=f.child,y!==null)y.return=f,an=y;else e:for(f=a;an!==null;){y=an;var R=y.sibling,D=y.return;if(Gd(y),y===f){an=null;break e}if(R!==null){R.return=D,an=R;break e}an=D}}}var zh={getCacheForType:function(a){var c=fn(Jr),f=c.data.get(a);return f===void 0&&(f=a(),c.data.set(a,f)),f},cacheSignal:function(){return fn(Jr).controller.signal}},Vh=typeof WeakMap=="function"?WeakMap:Map,nr=0,vr=null,Vt=null,Kt=0,dr=0,Mn=null,us=!1,da=!1,Dc=!1,Mi=0,qr=0,ds=0,Os=0,Nc=0,Bn=0,fa=0,Xa=null,Nn=null,Fc=!1,Qo=0,of=0,Xo=1/0,Yo=null,fs=null,rn=0,hs=null,ha=null,Bi=0,Uc=0,Pc=null,lf=null,Ya=0,kc=null;function qn(){return(nr&2)!==0&&Kt!==0?Kt&-Kt:he.T!==null?Bc():ar()}function cf(){if(Bn===0)if((Kt&536870912)===0||Gt){var a=Ut;Ut<<=1,(Ut&3932160)===0&&(Ut=262144),Bn=a}else Bn=536870912;return a=$n.current,a!==null&&(a.flags|=32),Bn}function Fn(a,c,f){(a===vr&&(dr===2||dr===9)||a.cancelPendingCommit!==null)&&(pa(a,0),ps(a,Kt,Bn,!1)),ze(a,f),((nr&2)===0||a!==vr)&&(a===vr&&((nr&2)===0&&(Os|=f),qr===4&&ps(a,Kt,Bn,!1)),Si(a))}function uf(a,c,f){if((nr&6)!==0)throw Error(i(327));var y=!f&&(c&127)===0&&(c&a.expiredLanes)===0||ir(a,c),R=y?Kh(a,c):jc(a,c,!0),D=y;do{if(R===0){da&&!y&&ps(a,c,0,!1);break}else{if(f=a.current.alternate,D&&!Hh(f)){R=jc(a,c,!1),D=!1;continue}if(R===2){if(D=c,a.errorRecoveryDisabledLanes&D)var Z=0;else Z=a.pendingLanes&-536870913,Z=Z!==0?Z:Z&536870912?536870912:0;if(Z!==0){c=Z;e:{var ue=a;R=Xa;var $e=ue.current.memoizedState.isDehydrated;if($e&&(pa(ue,Z).flags|=256),Z=jc(ue,Z,!1),Z!==2){if(Dc&&!$e){ue.errorRecoveryDisabledLanes|=D,Os|=D,R=4;break e}D=Nn,Nn=R,D!==null&&(Nn===null?Nn=D:Nn.push.apply(Nn,D))}R=Z}if(D=!1,R!==2)continue}}if(R===1){pa(a,0),ps(a,c,0,!0);break}e:{switch(y=a,D=R,D){case 0:case 1:throw Error(i(345));case 4:if((c&4194048)!==c)break;case 6:ps(y,c,Bn,!us);break e;case 2:Nn=null;break;case 3:case 5:break;default:throw Error(i(329))}if((c&62914560)===c&&(R=Qo+300-ht(),10<R)){if(ps(y,c,Bn,!us),hr(y,0,!0)!==0)break e;Bi=c,y.timeoutHandle=Bf(df.bind(null,y,f,Nn,Yo,Fc,c,Bn,Os,fa,us,D,"Throttled",-0,0),R);break e}df(y,f,Nn,Yo,Fc,c,Bn,Os,fa,us,D,null,-0,0)}}break}while(!0);Si(a)}function df(a,c,f,y,R,D,Z,ue,$e,et,ct,ft,rt,st){if(a.timeoutHandle=-1,ft=c.subtreeFlags,ft&8192||(ft&16785408)===16785408){ft={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:vt},rf(c,D,ft);var xt=(D&62914560)===D?Qo-ht():(D&4194048)===D?of-ht():0;if(xt=Ip(ft,xt),xt!==null){Bi=D,a.cancelPendingCommit=xt(_f.bind(null,a,c,D,f,y,R,Z,ue,$e,ct,ft,null,rt,st)),ps(a,D,Z,!et);return}}_f(a,c,D,f,y,R,Z,ue,$e)}function Hh(a){for(var c=a;;){var f=c.tag;if((f===0||f===11||f===15)&&c.flags&16384&&(f=c.updateQueue,f!==null&&(f=f.stores,f!==null)))for(var y=0;y<f.length;y++){var R=f[y],D=R.getSnapshot;R=R.value;try{if(!wt(D(),R))return!1}catch{return!1}}if(f=c.child,c.subtreeFlags&16384&&f!==null)f.return=c,c=f;else{if(c===a)break;for(;c.sibling===null;){if(c.return===null||c.return===a)return!0;c=c.return}c.sibling.return=c.return,c=c.sibling}}return!0}function ps(a,c,f,y){c&=~Nc,c&=~Os,a.suspendedLanes|=c,a.pingedLanes&=~c,y&&(a.warmLanes|=c),y=a.expirationTimes;for(var R=c;0<R;){var D=31-Rt(R),Z=1<<D;y[D]=-1,R&=~Z}f!==0&&lt(a,f,c)}function el(){return(nr&6)===0?(eo(0),!1):!0}function Lc(){if(Vt!==null){if(dr===0)var a=Vt.return;else a=Vt,Di=Ds=null,Xl(a),ia=null,La=0,a=Vt;for(;a!==null;)Bd(a.alternate,a),a=a.return;Vt=null}}function pa(a,c){var f=a.timeoutHandle;f!==-1&&(a.timeoutHandle=-1,dp(f)),f=a.cancelPendingCommit,f!==null&&(a.cancelPendingCommit=null,f()),Bi=0,Lc(),vr=a,Vt=f=Ci(a.current,null),Kt=c,dr=0,Mn=null,us=!1,da=ir(a,c),Dc=!1,fa=Bn=Nc=Os=ds=qr=0,Nn=Xa=null,Fc=!1,(c&8)!==0&&(c|=c&32);var y=a.entangledLanes;if(y!==0)for(a=a.entanglements,y&=c;0<y;){var R=31-Rt(y),D=1<<R;c|=a[R],y&=~D}return Mi=c,vo(),f}function ff(a,c){Ot=null,he.H=Va,c===na||c===Io?(c=Tu(),dr=3):c===Ml?(c=Tu(),dr=4):dr=c===pc?8:c!==null&&typeof c=="object"&&typeof c.then=="function"?6:1,Mn=c,Vt===null&&(qr=1,zo(a,ei(c,a.current)))}function hf(){var a=$n.current;return a===null?!0:(Kt&4194048)===Kt?ii===null:(Kt&62914560)===Kt||(Kt&536870912)!==0?a===ii:!1}function pf(){var a=he.H;return he.H=Va,a===null?Va:a}function gf(){var a=he.A;return he.A=zh,a}function tl(){qr=4,us||(Kt&4194048)!==Kt&&$n.current!==null||(da=!0),(ds&134217727)===0&&(Os&134217727)===0||vr===null||ps(vr,Kt,Bn,!1)}function jc(a,c,f){var y=nr;nr|=2;var R=pf(),D=gf();(vr!==a||Kt!==c)&&(Yo=null,pa(a,c)),c=!1;var Z=qr;e:do try{if(dr!==0&&Vt!==null){var ue=Vt,$e=Mn;switch(dr){case 8:Lc(),Z=6;break e;case 3:case 2:case 9:case 6:$n.current===null&&(c=!0);var et=dr;if(dr=0,Mn=null,ga(a,ue,$e,et),f&&da){Z=0;break e}break;default:et=dr,dr=0,Mn=null,ga(a,ue,$e,et)}}Wh(),Z=qr;break}catch(ct){ff(a,ct)}while(!0);return c&&a.shellSuspendCounter++,Di=Ds=null,nr=y,he.H=R,he.A=D,Vt===null&&(vr=null,Kt=0,vo()),Z}function Wh(){for(;Vt!==null;)mf(Vt)}function Kh(a,c){var f=nr;nr|=2;var y=pf(),R=gf();vr!==a||Kt!==c?(Yo=null,Xo=ht()+500,pa(a,c)):da=ir(a,c);e:do try{if(dr!==0&&Vt!==null){c=Vt;var D=Mn;t:switch(dr){case 1:dr=0,Mn=null,ga(a,c,D,1);break;case 2:case 9:if(Eu(D)){dr=0,Mn=null,yf(c);break}c=function(){dr!==2&&dr!==9||vr!==a||(dr=7),Si(a)},D.then(c,c);break e;case 3:dr=7;break e;case 4:dr=5;break e;case 7:Eu(D)?(dr=0,Mn=null,yf(c)):(dr=0,Mn=null,ga(a,c,D,7));break;case 5:var Z=null;switch(Vt.tag){case 26:Z=Vt.memoizedState;case 5:case 27:var ue=Vt;if(Z?rh(Z):ue.stateNode.complete){dr=0,Mn=null;var $e=ue.sibling;if($e!==null)Vt=$e;else{var et=ue.return;et!==null?(Vt=et,rl(et)):Vt=null}break t}}dr=0,Mn=null,ga(a,c,D,5);break;case 6:dr=0,Mn=null,ga(a,c,D,6);break;case 8:Lc(),qr=6;break e;default:throw Error(i(462))}}Zh();break}catch(ct){ff(a,ct)}while(!0);return Di=Ds=null,he.H=y,he.A=R,nr=f,Vt!==null?0:(vr=null,Kt=0,vo(),qr)}function Zh(){for(;Vt!==null&&!ye();)mf(Vt)}function mf(a){var c=Od(a.alternate,a,Mi);a.memoizedProps=a.pendingProps,c===null?rl(a):Vt=c}function yf(a){var c=a,f=c.alternate;switch(c.tag){case 15:case 0:c=Ud(f,c,c.pendingProps,c.type,void 0,Kt);break;case 11:c=Ud(f,c,c.pendingProps,c.type.render,c.ref,Kt);break;case 5:Xl(c);default:Bd(f,c),c=Vt=hu(c,Mi),c=Od(f,c,Mi)}a.memoizedProps=a.pendingProps,c===null?rl(a):Vt=c}function ga(a,c,f,y){Di=Ds=null,Xl(c),ia=null,La=0;var R=c.return;try{if(Lh(a,R,c,f,Kt)){qr=1,zo(a,ei(f,a.current)),Vt=null;return}}catch(D){if(R!==null)throw Vt=R,D;qr=1,zo(a,ei(f,a.current)),Vt=null;return}c.flags&32768?(Gt||y===1?a=!0:da||(Kt&536870912)!==0?a=!1:(us=a=!0,(y===2||y===9||y===3||y===6)&&(y=$n.current,y!==null&&y.tag===13&&(y.flags|=16384))),bf(c,a)):rl(c)}function rl(a){var c=a;do{if((c.flags&32768)!==0){bf(c,us);return}a=c.return;var f=Oh(c.alternate,c,Mi);if(f!==null){Vt=f;return}if(c=c.sibling,c!==null){Vt=c;return}Vt=c=a}while(c!==null);qr===0&&(qr=5)}function bf(a,c){do{var f=Mh(a.alternate,a);if(f!==null){f.flags&=32767,Vt=f;return}if(f=a.return,f!==null&&(f.flags|=32768,f.subtreeFlags=0,f.deletions=null),!c&&(a=a.sibling,a!==null)){Vt=a;return}Vt=a=f}while(a!==null);qr=6,Vt=null}function _f(a,c,f,y,R,D,Z,ue,$e){a.cancelPendingCommit=null;do nl();while(rn!==0);if((nr&6)!==0)throw Error(i(327));if(c!==null){if(c===a.current)throw Error(i(177));if(D=c.lanes|c.childLanes,D|=Rl,Ke(a,f,D,Z,ue,$e),a===vr&&(Vt=vr=null,Kt=0),ha=c,hs=a,Bi=f,Uc=D,Pc=R,lf=y,(c.subtreeFlags&10256)!==0||(c.flags&10256)!==0?(a.callbackNode=null,a.callbackPriority=0,Xh(U,function(){return Ef(),null})):(a.callbackNode=null,a.callbackPriority=0),y=(c.flags&13878)!==0,(c.subtreeFlags&13878)!==0||y){y=he.T,he.T=null,R=Oe.p,Oe.p=2,Z=nr,nr|=4;try{Bh(a,c,f)}finally{nr=Z,Oe.p=R,he.T=y}}rn=1,Sf(),vf(),wf()}}function Sf(){if(rn===1){rn=0;var a=hs,c=ha,f=(c.flags&13878)!==0;if((c.subtreeFlags&13878)!==0||f){f=he.T,he.T=null;var y=Oe.p;Oe.p=2;var R=nr;nr|=4;try{Yd(c,a);var D=Gc,Z=Rs(a.containerInfo),ue=D.focusedElem,$e=D.selectionRange;if(Z!==ue&&ue&&ue.ownerDocument&&di(ue.ownerDocument.documentElement,ue)){if($e!==null&&Qi(ue)){var et=$e.start,ct=$e.end;if(ct===void 0&&(ct=et),"selectionStart"in ue)ue.selectionStart=et,ue.selectionEnd=Math.min(ct,ue.value.length);else{var ft=ue.ownerDocument||document,rt=ft&&ft.defaultView||window;if(rt.getSelection){var st=rt.getSelection(),xt=ue.textContent.length,It=Math.min($e.start,xt),_r=$e.end===void 0?It:Math.min($e.end,xt);!st.extend&&It>_r&&(Z=_r,_r=It,It=Z);var Ge=pe(ue,It),qe=pe(ue,_r);if(Ge&&qe&&(st.rangeCount!==1||st.anchorNode!==Ge.node||st.anchorOffset!==Ge.offset||st.focusNode!==qe.node||st.focusOffset!==qe.offset)){var Xe=ft.createRange();Xe.setStart(Ge.node,Ge.offset),st.removeAllRanges(),It>_r?(st.addRange(Xe),st.extend(qe.node,qe.offset)):(Xe.setEnd(qe.node,qe.offset),st.addRange(Xe))}}}}for(ft=[],st=ue;st=st.parentNode;)st.nodeType===1&&ft.push({element:st,left:st.scrollLeft,top:st.scrollTop});for(typeof ue.focus=="function"&&ue.focus(),ue=0;ue<ft.length;ue++){var dt=ft[ue];dt.element.scrollLeft=dt.left,dt.element.scrollTop=dt.top}}gl=!!Zc,Gc=Zc=null}finally{nr=R,Oe.p=y,he.T=f}}a.current=c,rn=2}}function vf(){if(rn===2){rn=0;var a=hs,c=ha,f=(c.flags&8772)!==0;if((c.subtreeFlags&8772)!==0||f){f=he.T,he.T=null;var y=Oe.p;Oe.p=2;var R=nr;nr|=4;try{Zd(a,c.alternate,c)}finally{nr=R,Oe.p=y,he.T=f}}rn=3}}function wf(){if(rn===4||rn===3){rn=0,at();var a=hs,c=ha,f=Bi,y=lf;(c.subtreeFlags&10256)!==0||(c.flags&10256)!==0?rn=5:(rn=0,ha=hs=null,xf(a,a.pendingLanes));var R=a.pendingLanes;if(R===0&&(fs=null),Er(f),c=c.stateNode,mt&&typeof mt.onCommitFiberRoot=="function")try{mt.onCommitFiberRoot(Le,c,void 0,(c.current.flags&128)===128)}catch{}if(y!==null){c=he.T,R=Oe.p,Oe.p=2,he.T=null;try{for(var D=a.onRecoverableError,Z=0;Z<y.length;Z++){var ue=y[Z];D(ue.value,{componentStack:ue.stack})}}finally{he.T=c,Oe.p=R}}(Bi&3)!==0&&nl(),Si(a),R=a.pendingLanes,(f&261930)!==0&&(R&42)!==0?a===kc?Ya++:(Ya=0,kc=a):Ya=0,eo(0)}}function xf(a,c){(a.pooledCacheLanes&=c)===0&&(c=a.pooledCache,c!=null&&(a.pooledCache=null,Pa(c)))}function nl(){return Sf(),vf(),wf(),Ef()}function Ef(){if(rn!==5)return!1;var a=hs,c=Uc;Uc=0;var f=Er(Bi),y=he.T,R=Oe.p;try{Oe.p=32>f?32:f,he.T=null,f=Pc,Pc=null;var D=hs,Z=Bi;if(rn=0,ha=hs=null,Bi=0,(nr&6)!==0)throw Error(i(331));var ue=nr;if(nr|=4,sf(D.current),tf(D,D.current,Z,f),nr=ue,eo(0,!1),mt&&typeof mt.onPostCommitFiberRoot=="function")try{mt.onPostCommitFiberRoot(Le,D)}catch{}return!0}finally{Oe.p=R,he.T=y,xf(a,c)}}function Rf(a,c,f){c=ei(f,c),c=hc(a.stateNode,c,2),a=as(a,c,2),a!==null&&(ze(a,2),Si(a))}function fr(a,c,f){if(a.tag===3)Rf(a,a,f);else for(;c!==null;){if(c.tag===3){Rf(c,a,f);break}else if(c.tag===1){var y=c.stateNode;if(typeof c.type.getDerivedStateFromError=="function"||typeof y.componentDidCatch=="function"&&(fs===null||!fs.has(y))){a=ei(f,a),f=Rd(2),y=as(c,f,2),y!==null&&(Td(f,y,c,a),ze(y,2),Si(y));break}}c=c.return}}function $c(a,c,f){var y=a.pingCache;if(y===null){y=a.pingCache=new Vh;var R=new Set;y.set(c,R)}else R=y.get(c),R===void 0&&(R=new Set,y.set(c,R));R.has(f)||(Dc=!0,R.add(f),a=Gh.bind(null,a,c,f),c.then(a,a))}function Gh(a,c,f){var y=a.pingCache;y!==null&&y.delete(c),a.pingedLanes|=a.suspendedLanes&f,a.warmLanes&=~f,vr===a&&(Kt&f)===f&&(qr===4||qr===3&&(Kt&62914560)===Kt&&300>ht()-Qo?(nr&2)===0&&pa(a,0):Nc|=f,fa===Kt&&(fa=0)),Si(a)}function Tf(a,c){c===0&&(c=V()),a=As(a,c),a!==null&&(ze(a,c),Si(a))}function Jh(a){var c=a.memoizedState,f=0;c!==null&&(f=c.retryLane),Tf(a,f)}function Qh(a,c){var f=0;switch(a.tag){case 31:case 13:var y=a.stateNode,R=a.memoizedState;R!==null&&(f=R.retryLane);break;case 19:y=a.stateNode;break;case 22:y=a.stateNode._retryCache;break;default:throw Error(i(314))}y!==null&&y.delete(c),Tf(a,f)}function Xh(a,c){return _e(a,c)}var il=null,ma=null,Oc=!1,sl=!1,Mc=!1,gs=0;function Si(a){a!==ma&&a.next===null&&(ma===null?il=ma=a:ma=ma.next=a),sl=!0,Oc||(Oc=!0,ep())}function eo(a,c){if(!Mc&&sl){Mc=!0;do for(var f=!1,y=il;y!==null;){if(a!==0){var R=y.pendingLanes;if(R===0)var D=0;else{var Z=y.suspendedLanes,ue=y.pingedLanes;D=(1<<31-Rt(42|a)+1)-1,D&=R&~(Z&~ue),D=D&201326741?D&201326741|1:D?D|2:0}D!==0&&(f=!0,Df(y,D))}else D=Kt,D=hr(y,y===vr?D:0,y.cancelPendingCommit!==null||y.timeoutHandle!==-1),(D&3)===0||ir(y,D)||(f=!0,Df(y,D));y=y.next}while(f);Mc=!1}}function Yh(){Af()}function Af(){sl=Oc=!1;var a=0;gs!==0&&up()&&(a=gs);for(var c=ht(),f=null,y=il;y!==null;){var R=y.next,D=Cf(y,c);D===0?(y.next=null,f===null?il=R:f.next=R,R===null&&(ma=f)):(f=y,(a!==0||(D&3)!==0)&&(sl=!0)),y=R}rn!==0&&rn!==5||eo(a),gs!==0&&(gs=0)}function Cf(a,c){for(var f=a.suspendedLanes,y=a.pingedLanes,R=a.expirationTimes,D=a.pendingLanes&-62914561;0<D;){var Z=31-Rt(D),ue=1<<Z,$e=R[Z];$e===-1?((ue&f)===0||(ue&y)!==0)&&(R[Z]=Wr(ue,c)):$e<=c&&(a.expiredLanes|=ue),D&=~ue}if(c=vr,f=Kt,f=hr(a,a===c?f:0,a.cancelPendingCommit!==null||a.timeoutHandle!==-1),y=a.callbackNode,f===0||a===c&&(dr===2||dr===9)||a.cancelPendingCommit!==null)return y!==null&&y!==null&&Ie(y),a.callbackNode=null,a.callbackPriority=0;if((f&3)===0||ir(a,f)){if(c=f&-f,c===a.callbackPriority)return c;switch(y!==null&&Ie(y),Er(f)){case 2:case 8:f=Y;break;case 32:f=U;break;case 268435456:f=j;break;default:f=U}return y=If.bind(null,a),f=_e(f,y),a.callbackPriority=c,a.callbackNode=f,c}return y!==null&&y!==null&&Ie(y),a.callbackPriority=2,a.callbackNode=null,2}function If(a,c){if(rn!==0&&rn!==5)return a.callbackNode=null,a.callbackPriority=0,null;var f=a.callbackNode;if(nl()&&a.callbackNode!==f)return null;var y=Kt;return y=hr(a,a===vr?y:0,a.cancelPendingCommit!==null||a.timeoutHandle!==-1),y===0?null:(uf(a,y,c),Cf(a,ht()),a.callbackNode!=null&&a.callbackNode===f?If.bind(null,a):null)}function Df(a,c){if(nl())return null;uf(a,c,!0)}function ep(){fp(function(){(nr&6)!==0?_e(gt,Yh):Af()})}function Bc(){if(gs===0){var a=ta;a===0&&(a=er,er<<=1,(er&261888)===0&&(er=256)),gs=a}return gs}function Nf(a){return a==null||typeof a=="symbol"||typeof a=="boolean"?null:typeof a=="function"?a:bt(""+a)}function Ff(a,c){var f=c.ownerDocument.createElement("input");return f.name=c.name,f.value=c.value,a.id&&f.setAttribute("form",a.id),c.parentNode.insertBefore(f,c),a=new FormData(a),f.parentNode.removeChild(f),a}function tp(a,c,f,y,R){if(c==="submit"&&f&&f.stateNode===R){var D=Nf((R[pr]||null).action),Z=y.submitter;Z&&(c=(c=Z[pr]||null)?Nf(c.formAction):Z.getAttribute("formAction"),c!==null&&(D=c,Z=null));var ue=new zn("action","action",null,y,R);a.push({event:ue,listeners:[{instance:null,listener:function(){if(y.defaultPrevented){if(gs!==0){var $e=Z?Ff(R,Z):new FormData(R);oc(f,{pending:!0,data:$e,method:R.method,action:D},null,$e)}}else typeof D=="function"&&(ue.preventDefault(),$e=Z?Ff(R,Z):new FormData(R),oc(f,{pending:!0,data:$e,method:R.method,action:D},D,$e))},currentTarget:R}]})}}for(var qc=0;qc<El.length;qc++){var zc=El[qc],rp=zc.toLowerCase(),np=zc[0].toUpperCase()+zc.slice(1);fi(rp,"on"+np)}fi(Gr,"onAnimationEnd"),fi(Ts,"onAnimationIteration"),fi(Xn,"onAnimationStart"),fi("dblclick","onDoubleClick"),fi("focusin","onFocus"),fi("focusout","onBlur"),fi(_o,"onTransitionRun"),fi(Zs,"onTransitionStart"),fi(Na,"onTransitionCancel"),fi(Ai,"onTransitionEnd"),gn("onMouseEnter",["mouseout","mouseover"]),gn("onMouseLeave",["mouseout","mouseover"]),gn("onPointerEnter",["pointerout","pointerover"]),gn("onPointerLeave",["pointerout","pointerover"]),En("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),En("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),En("onBeforeInput",["compositionend","keypress","textInput","paste"]),En("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),En("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),En("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var to="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),ip=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(to));function Uf(a,c){c=(c&4)!==0;for(var f=0;f<a.length;f++){var y=a[f],R=y.event;y=y.listeners;e:{var D=void 0;if(c)for(var Z=y.length-1;0<=Z;Z--){var ue=y[Z],$e=ue.instance,et=ue.currentTarget;if(ue=ue.listener,$e!==D&&R.isPropagationStopped())break e;D=ue,R.currentTarget=et;try{D(R)}catch(ct){So(ct)}R.currentTarget=null,D=$e}else for(Z=0;Z<y.length;Z++){if(ue=y[Z],$e=ue.instance,et=ue.currentTarget,ue=ue.listener,$e!==D&&R.isPropagationStopped())break e;D=ue,R.currentTarget=et;try{D(R)}catch(ct){So(ct)}R.currentTarget=null,D=$e}}}}function Ht(a,c){var f=c[zr];f===void 0&&(f=c[zr]=new Set);var y=a+"__bubble";f.has(y)||(Pf(c,a,2,!1),f.add(y))}function Vc(a,c,f){var y=0;c&&(y|=4),Pf(f,a,y,c)}var al="_reactListening"+Math.random().toString(36).slice(2);function Hc(a){if(!a[al]){a[al]=!0,vi.forEach(function(f){f!=="selectionchange"&&(ip.has(f)||Vc(f,!1,a),Vc(f,!0,a))});var c=a.nodeType===9?a:a.ownerDocument;c===null||c[al]||(c[al]=!0,Vc("selectionchange",!1,c))}}function Pf(a,c,f,y){switch(ch(c)){case 2:var R=Fp;break;case 8:R=Up;break;default:R=au}f=R.bind(null,c,f,a),R=void 0,!Or||c!=="touchstart"&&c!=="touchmove"&&c!=="wheel"||(R=!0),y?R!==void 0?a.addEventListener(c,f,{capture:!0,passive:R}):a.addEventListener(c,f,!0):R!==void 0?a.addEventListener(c,f,{passive:R}):a.addEventListener(c,f,!1)}function Wc(a,c,f,y,R){var D=y;if((c&1)===0&&(c&2)===0&&y!==null)e:for(;;){if(y===null)return;var Z=y.tag;if(Z===3||Z===4){var ue=y.stateNode.containerInfo;if(ue===R)break;if(Z===4)for(Z=y.return;Z!==null;){var $e=Z.tag;if(($e===3||$e===4)&&Z.stateNode.containerInfo===R)return;Z=Z.return}for(;ue!==null;){if(Z=lr(ue),Z===null)return;if($e=Z.tag,$e===5||$e===6||$e===26||$e===27){y=D=Z;continue e}ue=ue.parentNode}}y=y.return}cr(function(){var et=D,ct=Qt(f),ft=[];e:{var rt=du.get(a);if(rt!==void 0){var st=zn,xt=a;switch(a){case"keypress":if(Un(f)===0)break e;case"keydown":case"keyup":st=xs;break;case"focusin":xt="focus",st=Hn;break;case"focusout":xt="blur",st=Hn;break;case"beforeblur":case"afterblur":st=Hn;break;case"click":if(f.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":st=ur;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":st=gi;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":st=Wi;break;case Gr:case Ts:case Xn:st=Kn;break;case Ai:st=Ei;break;case"scroll":case"scrollend":st=zi;break;case"wheel":st=Ta;break;case"copy":case"cut":case"paste":st=wa;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":st=Zr;break;case"toggle":case"beforetoggle":st=wl}var It=(c&4)!==0,_r=!It&&(a==="scroll"||a==="scrollend"),Ge=It?rt!==null?rt+"Capture":null:rt;It=[];for(var qe=et,Xe;qe!==null;){var dt=qe;if(Xe=dt.stateNode,dt=dt.tag,dt!==5&&dt!==26&&dt!==27||Xe===null||Ge===null||(dt=Yt(qe,Ge),dt!=null&&It.push(ro(qe,dt,Xe))),_r)break;qe=qe.return}0<It.length&&(rt=new st(rt,xt,null,f,ct),ft.push({event:rt,listeners:It}))}}if((c&7)===0){e:{if(rt=a==="mouseover"||a==="pointerover",st=a==="mouseout"||a==="pointerout",rt&&f!==Jt&&(xt=f.relatedTarget||f.fromElement)&&(lr(xt)||xt[Pr]))break e;if((st||rt)&&(rt=ct.window===ct?ct:(rt=ct.ownerDocument)?rt.defaultView||rt.parentWindow:window,st?(xt=f.relatedTarget||f.toElement,st=et,xt=xt?lr(xt):null,xt!==null&&(_r=o(xt),It=xt.tag,xt!==_r||It!==5&&It!==27&&It!==6)&&(xt=null)):(st=null,xt=et),st!==xt)){if(It=ur,dt="onMouseLeave",Ge="onMouseEnter",qe="mouse",(a==="pointerout"||a==="pointerover")&&(It=Zr,dt="onPointerLeave",Ge="onPointerEnter",qe="pointer"),_r=st==null?rt:kr(st),Xe=xt==null?rt:kr(xt),rt=new It(dt,qe+"leave",st,f,ct),rt.target=_r,rt.relatedTarget=Xe,dt=null,lr(ct)===et&&(It=new It(Ge,qe+"enter",xt,f,ct),It.target=Xe,It.relatedTarget=_r,dt=It),_r=dt,st&&xt)t:{for(It=sp,Ge=st,qe=xt,Xe=0,dt=Ge;dt;dt=It(dt))Xe++;dt=0;for(var Ct=qe;Ct;Ct=It(Ct))dt++;for(;0<Xe-dt;)Ge=It(Ge),Xe--;for(;0<dt-Xe;)qe=It(qe),dt--;for(;Xe--;){if(Ge===qe||qe!==null&&Ge===qe.alternate){It=Ge;break t}Ge=It(Ge),qe=It(qe)}It=null}else It=null;st!==null&&kf(ft,rt,st,It,!1),xt!==null&&_r!==null&&kf(ft,_r,xt,It,!0)}}e:{if(rt=et?kr(et):window,st=rt.nodeName&&rt.nodeName.toLowerCase(),st==="select"||st==="input"&&rt.type==="file")var tr=Ji;else if(qs(rt))if(Da)tr=yt;else{tr=nt;var Et=ot}else st=rt.nodeName,!st||st.toLowerCase()!=="input"||rt.type!=="checkbox"&&rt.type!=="radio"?et&&_t(et.elementType)&&(tr=Ji):tr=ut;if(tr&&(tr=tr(a,et))){mo(ft,tr,f,ct);break e}Et&&Et(a,rt,et),a==="focusout"&&et&&rt.type==="number"&&et.memoizedProps.value!=null&&Ye(rt,"number",rt.value)}switch(Et=et?kr(et):window,a){case"focusin":(qs(Et)||Et.contentEditable==="true")&&(mr=Et,An=et,Ln=null);break;case"focusout":Ln=An=mr=null;break;case"mousedown":mi=!0;break;case"contextmenu":case"mouseup":case"dragend":mi=!1,Ks(ft,f,ct);break;case"selectionchange":if(Ws)break;case"keydown":case"keyup":Ks(ft,f,ct)}var Mt;if(kn)e:{switch(a){case"compositionstart":var Zt="onCompositionStart";break e;case"compositionend":Zt="onCompositionEnd";break e;case"compositionupdate":Zt="onCompositionUpdate";break e}Zt=void 0}else Zi?Bs(a,f)&&(Zt="onCompositionEnd"):a==="keydown"&&f.keyCode===229&&(Zt="onCompositionStart");Zt&&(ho&&f.locale!=="ko"&&(Zi||Zt!=="onCompositionStart"?Zt==="onCompositionEnd"&&Zi&&(Mt=yn()):(nn=ct,mn="value"in nn?nn.value:nn.textContent,Zi=!0)),Et=ol(et,Zt),0<Et.length&&(Zt=new xa(Zt,a,null,f,ct),ft.push({event:Zt,listeners:Et}),Mt?Zt.data=Mt:(Mt=Ca(f),Mt!==null&&(Zt.data=Mt)))),(Mt=fo?xl(a,f):Ia(a,f))&&(Zt=ol(et,"onBeforeInput"),0<Zt.length&&(Et=new xa("onBeforeInput","beforeinput",null,f,ct),ft.push({event:Et,listeners:Zt}),Et.data=Mt)),tp(ft,a,et,f,ct)}Uf(ft,c)})}function ro(a,c,f){return{instance:a,listener:c,currentTarget:f}}function ol(a,c){for(var f=c+"Capture",y=[];a!==null;){var R=a,D=R.stateNode;if(R=R.tag,R!==5&&R!==26&&R!==27||D===null||(R=Yt(a,f),R!=null&&y.unshift(ro(a,R,D)),R=Yt(a,c),R!=null&&y.push(ro(a,R,D))),a.tag===3)return y;a=a.return}return[]}function sp(a){if(a===null)return null;do a=a.return;while(a&&a.tag!==5&&a.tag!==27);return a||null}function kf(a,c,f,y,R){for(var D=c._reactName,Z=[];f!==null&&f!==y;){var ue=f,$e=ue.alternate,et=ue.stateNode;if(ue=ue.tag,$e!==null&&$e===y)break;ue!==5&&ue!==26&&ue!==27||et===null||($e=et,R?(et=Yt(f,D),et!=null&&Z.unshift(ro(f,et,$e))):R||(et=Yt(f,D),et!=null&&Z.push(ro(f,et,$e)))),f=f.return}Z.length!==0&&a.push({event:c,listeners:Z})}var ap=/\r\n?/g,op=/\u0000|\uFFFD/g;function Lf(a){return(typeof a=="string"?a:""+a).replace(ap,`
10
10
  `).replace(op,"")}function jf(a,c){return c=Lf(c),Lf(a)===c}function br(a,c,f,y,R,D){switch(f){case"children":typeof y=="string"?c==="body"||c==="textarea"&&y===""||De(a,y):(typeof y=="number"||typeof y=="bigint")&&c!=="body"&&De(a,""+y);break;case"className":I(a,"class",y);break;case"tabIndex":I(a,"tabindex",y);break;case"dir":case"role":case"viewBox":case"width":case"height":I(a,f,y);break;case"style":it(a,y,D);break;case"data":if(c!=="object"){I(a,"data",y);break}case"src":case"href":if(y===""&&(c!=="a"||f!=="href")){a.removeAttribute(f);break}if(y==null||typeof y=="function"||typeof y=="symbol"||typeof y=="boolean"){a.removeAttribute(f);break}y=bt(""+y),a.setAttribute(f,y);break;case"action":case"formAction":if(typeof y=="function"){a.setAttribute(f,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof D=="function"&&(f==="formAction"?(c!=="input"&&br(a,c,"name",R.name,R,null),br(a,c,"formEncType",R.formEncType,R,null),br(a,c,"formMethod",R.formMethod,R,null),br(a,c,"formTarget",R.formTarget,R,null)):(br(a,c,"encType",R.encType,R,null),br(a,c,"method",R.method,R,null),br(a,c,"target",R.target,R,null)));if(y==null||typeof y=="symbol"||typeof y=="boolean"){a.removeAttribute(f);break}y=bt(""+y),a.setAttribute(f,y);break;case"onClick":y!=null&&(a.onclick=vt);break;case"onScroll":y!=null&&Ht("scroll",a);break;case"onScrollEnd":y!=null&&Ht("scrollend",a);break;case"dangerouslySetInnerHTML":if(y!=null){if(typeof y!="object"||!("__html"in y))throw Error(i(61));if(f=y.__html,f!=null){if(R.children!=null)throw Error(i(60));a.innerHTML=f}}break;case"multiple":a.multiple=y&&typeof y!="function"&&typeof y!="symbol";break;case"muted":a.muted=y&&typeof y!="function"&&typeof y!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(y==null||typeof y=="function"||typeof y=="boolean"||typeof y=="symbol"){a.removeAttribute("xlink:href");break}f=bt(""+y),a.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",f);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":y!=null&&typeof y!="function"&&typeof y!="symbol"?a.setAttribute(f,""+y):a.removeAttribute(f);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":y&&typeof y!="function"&&typeof y!="symbol"?a.setAttribute(f,""):a.removeAttribute(f);break;case"capture":case"download":y===!0?a.setAttribute(f,""):y!==!1&&y!=null&&typeof y!="function"&&typeof y!="symbol"?a.setAttribute(f,y):a.removeAttribute(f);break;case"cols":case"rows":case"size":case"span":y!=null&&typeof y!="function"&&typeof y!="symbol"&&!isNaN(y)&&1<=y?a.setAttribute(f,y):a.removeAttribute(f);break;case"rowSpan":case"start":y==null||typeof y=="function"||typeof y=="symbol"||isNaN(y)?a.removeAttribute(f):a.setAttribute(f,y);break;case"popover":Ht("beforetoggle",a),Ht("toggle",a),w(a,"popover",y);break;case"xlinkActuate":L(a,"http://www.w3.org/1999/xlink","xlink:actuate",y);break;case"xlinkArcrole":L(a,"http://www.w3.org/1999/xlink","xlink:arcrole",y);break;case"xlinkRole":L(a,"http://www.w3.org/1999/xlink","xlink:role",y);break;case"xlinkShow":L(a,"http://www.w3.org/1999/xlink","xlink:show",y);break;case"xlinkTitle":L(a,"http://www.w3.org/1999/xlink","xlink:title",y);break;case"xlinkType":L(a,"http://www.w3.org/1999/xlink","xlink:type",y);break;case"xmlBase":L(a,"http://www.w3.org/XML/1998/namespace","xml:base",y);break;case"xmlLang":L(a,"http://www.w3.org/XML/1998/namespace","xml:lang",y);break;case"xmlSpace":L(a,"http://www.w3.org/XML/1998/namespace","xml:space",y);break;case"is":w(a,"is",y);break;case"innerText":case"textContent":break;default:(!(2<f.length)||f[0]!=="o"&&f[0]!=="O"||f[1]!=="n"&&f[1]!=="N")&&(f=pt.get(f)||f,w(a,f,y))}}function Kc(a,c,f,y,R,D){switch(f){case"style":it(a,y,D);break;case"dangerouslySetInnerHTML":if(y!=null){if(typeof y!="object"||!("__html"in y))throw Error(i(61));if(f=y.__html,f!=null){if(R.children!=null)throw Error(i(60));a.innerHTML=f}}break;case"children":typeof y=="string"?De(a,y):(typeof y=="number"||typeof y=="bigint")&&De(a,""+y);break;case"onScroll":y!=null&&Ht("scroll",a);break;case"onScrollEnd":y!=null&&Ht("scrollend",a);break;case"onClick":y!=null&&(a.onclick=vt);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!wi.hasOwnProperty(f))e:{if(f[0]==="o"&&f[1]==="n"&&(R=f.endsWith("Capture"),c=f.slice(2,R?f.length-7:void 0),D=a[pr]||null,D=D!=null?D[f]:null,typeof D=="function"&&a.removeEventListener(c,D,R),typeof y=="function")){typeof D!="function"&&D!==null&&(f in a?a[f]=null:a.hasAttribute(f)&&a.removeAttribute(f)),a.addEventListener(c,y,R);break e}f in a?a[f]=y:y===!0?a.setAttribute(f,""):w(a,f,y)}}}function pn(a,c,f){switch(c){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Ht("error",a),Ht("load",a);var y=!1,R=!1,D;for(D in f)if(f.hasOwnProperty(D)){var Z=f[D];if(Z!=null)switch(D){case"src":y=!0;break;case"srcSet":R=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(i(137,c));default:br(a,c,D,Z,f,null)}}R&&br(a,c,"srcSet",f.srcSet,f,null),y&&br(a,c,"src",f.src,f,null);return;case"input":Ht("invalid",a);var ue=D=Z=R=null,$e=null,et=null;for(y in f)if(f.hasOwnProperty(y)){var ct=f[y];if(ct!=null)switch(y){case"name":R=ct;break;case"type":Z=ct;break;case"checked":$e=ct;break;case"defaultChecked":et=ct;break;case"value":D=ct;break;case"defaultValue":ue=ct;break;case"children":case"dangerouslySetInnerHTML":if(ct!=null)throw Error(i(137,c));break;default:br(a,c,y,ct,f,null)}}Ze(a,D,ue,$e,et,Z,R,!1);return;case"select":Ht("invalid",a),y=Z=D=null;for(R in f)if(f.hasOwnProperty(R)&&(ue=f[R],ue!=null))switch(R){case"value":D=ue;break;case"defaultValue":Z=ue;break;case"multiple":y=ue;default:br(a,c,R,ue,f,null)}c=D,f=Z,a.multiple=!!y,c!=null?tt(a,!!y,c,!1):f!=null&&tt(a,!!y,f,!0);return;case"textarea":Ht("invalid",a),D=R=y=null;for(Z in f)if(f.hasOwnProperty(Z)&&(ue=f[Z],ue!=null))switch(Z){case"value":y=ue;break;case"defaultValue":R=ue;break;case"children":D=ue;break;case"dangerouslySetInnerHTML":if(ue!=null)throw Error(i(91));break;default:br(a,c,Z,ue,f,null)}Re(a,y,R,D);return;case"option":for($e in f)f.hasOwnProperty($e)&&(y=f[$e],y!=null)&&($e==="selected"?a.selected=y&&typeof y!="function"&&typeof y!="symbol":br(a,c,$e,y,f,null));return;case"dialog":Ht("beforetoggle",a),Ht("toggle",a),Ht("cancel",a),Ht("close",a);break;case"iframe":case"object":Ht("load",a);break;case"video":case"audio":for(y=0;y<to.length;y++)Ht(to[y],a);break;case"image":Ht("error",a),Ht("load",a);break;case"details":Ht("toggle",a);break;case"embed":case"source":case"link":Ht("error",a),Ht("load",a);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(et in f)if(f.hasOwnProperty(et)&&(y=f[et],y!=null))switch(et){case"children":case"dangerouslySetInnerHTML":throw Error(i(137,c));default:br(a,c,et,y,f,null)}return;default:if(_t(c)){for(ct in f)f.hasOwnProperty(ct)&&(y=f[ct],y!==void 0&&Kc(a,c,ct,y,f,void 0));return}}for(ue in f)f.hasOwnProperty(ue)&&(y=f[ue],y!=null&&br(a,c,ue,y,f,null))}function lp(a,c,f,y){switch(c){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var R=null,D=null,Z=null,ue=null,$e=null,et=null,ct=null;for(st in f){var ft=f[st];if(f.hasOwnProperty(st)&&ft!=null)switch(st){case"checked":break;case"value":break;case"defaultValue":$e=ft;default:y.hasOwnProperty(st)||br(a,c,st,null,y,ft)}}for(var rt in y){var st=y[rt];if(ft=f[rt],y.hasOwnProperty(rt)&&(st!=null||ft!=null))switch(rt){case"type":D=st;break;case"name":R=st;break;case"checked":et=st;break;case"defaultChecked":ct=st;break;case"value":Z=st;break;case"defaultValue":ue=st;break;case"children":case"dangerouslySetInnerHTML":if(st!=null)throw Error(i(137,c));break;default:st!==ft&&br(a,c,rt,st,y,ft)}}Me(a,Z,ue,$e,et,ct,D,R);return;case"select":st=Z=ue=rt=null;for(D in f)if($e=f[D],f.hasOwnProperty(D)&&$e!=null)switch(D){case"value":break;case"multiple":st=$e;default:y.hasOwnProperty(D)||br(a,c,D,null,y,$e)}for(R in y)if(D=y[R],$e=f[R],y.hasOwnProperty(R)&&(D!=null||$e!=null))switch(R){case"value":rt=D;break;case"defaultValue":ue=D;break;case"multiple":Z=D;default:D!==$e&&br(a,c,R,D,y,$e)}c=ue,f=Z,y=st,rt!=null?tt(a,!!f,rt,!1):!!y!=!!f&&(c!=null?tt(a,!!f,c,!0):tt(a,!!f,f?[]:"",!1));return;case"textarea":st=rt=null;for(ue in f)if(R=f[ue],f.hasOwnProperty(ue)&&R!=null&&!y.hasOwnProperty(ue))switch(ue){case"value":break;case"children":break;default:br(a,c,ue,null,y,R)}for(Z in y)if(R=y[Z],D=f[Z],y.hasOwnProperty(Z)&&(R!=null||D!=null))switch(Z){case"value":rt=R;break;case"defaultValue":st=R;break;case"children":break;case"dangerouslySetInnerHTML":if(R!=null)throw Error(i(91));break;default:R!==D&&br(a,c,Z,R,y,D)}ae(a,rt,st);return;case"option":for(var xt in f)rt=f[xt],f.hasOwnProperty(xt)&&rt!=null&&!y.hasOwnProperty(xt)&&(xt==="selected"?a.selected=!1:br(a,c,xt,null,y,rt));for($e in y)rt=y[$e],st=f[$e],y.hasOwnProperty($e)&&rt!==st&&(rt!=null||st!=null)&&($e==="selected"?a.selected=rt&&typeof rt!="function"&&typeof rt!="symbol":br(a,c,$e,rt,y,st));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var It in f)rt=f[It],f.hasOwnProperty(It)&&rt!=null&&!y.hasOwnProperty(It)&&br(a,c,It,null,y,rt);for(et in y)if(rt=y[et],st=f[et],y.hasOwnProperty(et)&&rt!==st&&(rt!=null||st!=null))switch(et){case"children":case"dangerouslySetInnerHTML":if(rt!=null)throw Error(i(137,c));break;default:br(a,c,et,rt,y,st)}return;default:if(_t(c)){for(var _r in f)rt=f[_r],f.hasOwnProperty(_r)&&rt!==void 0&&!y.hasOwnProperty(_r)&&Kc(a,c,_r,void 0,y,rt);for(ct in y)rt=y[ct],st=f[ct],!y.hasOwnProperty(ct)||rt===st||rt===void 0&&st===void 0||Kc(a,c,ct,rt,y,st);return}}for(var Ge in f)rt=f[Ge],f.hasOwnProperty(Ge)&&rt!=null&&!y.hasOwnProperty(Ge)&&br(a,c,Ge,null,y,rt);for(ft in y)rt=y[ft],st=f[ft],!y.hasOwnProperty(ft)||rt===st||rt==null&&st==null||br(a,c,ft,rt,y,st)}function $f(a){switch(a){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function cp(){if(typeof performance.getEntriesByType=="function"){for(var a=0,c=0,f=performance.getEntriesByType("resource"),y=0;y<f.length;y++){var R=f[y],D=R.transferSize,Z=R.initiatorType,ue=R.duration;if(D&&ue&&$f(Z)){for(Z=0,ue=R.responseEnd,y+=1;y<f.length;y++){var $e=f[y],et=$e.startTime;if(et>ue)break;var ct=$e.transferSize,ft=$e.initiatorType;ct&&$f(ft)&&($e=$e.responseEnd,Z+=ct*($e<ue?1:(ue-et)/($e-et)))}if(--y,c+=8*(D+Z)/(R.duration/1e3),a++,10<a)break}}if(0<a)return c/a/1e6}return navigator.connection&&(a=navigator.connection.downlink,typeof a=="number")?a:5}var Zc=null,Gc=null;function ll(a){return a.nodeType===9?a:a.ownerDocument}function Of(a){switch(a){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function Mf(a,c){if(a===0)switch(c){case"svg":return 1;case"math":return 2;default:return 0}return a===1&&c==="foreignObject"?0:a}function Jc(a,c){return a==="textarea"||a==="noscript"||typeof c.children=="string"||typeof c.children=="number"||typeof c.children=="bigint"||typeof c.dangerouslySetInnerHTML=="object"&&c.dangerouslySetInnerHTML!==null&&c.dangerouslySetInnerHTML.__html!=null}var Qc=null;function up(){var a=window.event;return a&&a.type==="popstate"?a===Qc?!1:(Qc=a,!0):(Qc=null,!1)}var Bf=typeof setTimeout=="function"?setTimeout:void 0,dp=typeof clearTimeout=="function"?clearTimeout:void 0,qf=typeof Promise=="function"?Promise:void 0,fp=typeof queueMicrotask=="function"?queueMicrotask:typeof qf<"u"?function(a){return qf.resolve(null).then(a).catch(hp)}:Bf;function hp(a){setTimeout(function(){throw a})}function ms(a){return a==="head"}function zf(a,c){var f=c,y=0;do{var R=f.nextSibling;if(a.removeChild(f),R&&R.nodeType===8)if(f=R.data,f==="/$"||f==="/&"){if(y===0){a.removeChild(R),va(c);return}y--}else if(f==="$"||f==="$?"||f==="$~"||f==="$!"||f==="&")y++;else if(f==="html")no(a.ownerDocument.documentElement);else if(f==="head"){f=a.ownerDocument.head,no(f);for(var D=f.firstChild;D;){var Z=D.nextSibling,ue=D.nodeName;D[li]||ue==="SCRIPT"||ue==="STYLE"||ue==="LINK"&&D.rel.toLowerCase()==="stylesheet"||f.removeChild(D),D=Z}}else f==="body"&&no(a.ownerDocument.body);f=R}while(f);va(c)}function Vf(a,c){var f=a;a=0;do{var y=f.nextSibling;if(f.nodeType===1?c?(f._stashedDisplay=f.style.display,f.style.display="none"):(f.style.display=f._stashedDisplay||"",f.getAttribute("style")===""&&f.removeAttribute("style")):f.nodeType===3&&(c?(f._stashedText=f.nodeValue,f.nodeValue=""):f.nodeValue=f._stashedText||""),y&&y.nodeType===8)if(f=y.data,f==="/$"){if(a===0)break;a--}else f!=="$"&&f!=="$?"&&f!=="$~"&&f!=="$!"||a++;f=y}while(f)}function Xc(a){var c=a.firstChild;for(c&&c.nodeType===10&&(c=c.nextSibling);c;){var f=c;switch(c=c.nextSibling,f.nodeName){case"HTML":case"HEAD":case"BODY":Xc(f),Sr(f);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(f.rel.toLowerCase()==="stylesheet")continue}a.removeChild(f)}}function pp(a,c,f,y){for(;a.nodeType===1;){var R=f;if(a.nodeName.toLowerCase()!==c.toLowerCase()){if(!y&&(a.nodeName!=="INPUT"||a.type!=="hidden"))break}else if(y){if(!a[li])switch(c){case"meta":if(!a.hasAttribute("itemprop"))break;return a;case"link":if(D=a.getAttribute("rel"),D==="stylesheet"&&a.hasAttribute("data-precedence"))break;if(D!==R.rel||a.getAttribute("href")!==(R.href==null||R.href===""?null:R.href)||a.getAttribute("crossorigin")!==(R.crossOrigin==null?null:R.crossOrigin)||a.getAttribute("title")!==(R.title==null?null:R.title))break;return a;case"style":if(a.hasAttribute("data-precedence"))break;return a;case"script":if(D=a.getAttribute("src"),(D!==(R.src==null?null:R.src)||a.getAttribute("type")!==(R.type==null?null:R.type)||a.getAttribute("crossorigin")!==(R.crossOrigin==null?null:R.crossOrigin))&&D&&a.hasAttribute("async")&&!a.hasAttribute("itemprop"))break;return a;default:return a}}else if(c==="input"&&a.type==="hidden"){var D=R.name==null?null:""+R.name;if(R.type==="hidden"&&a.getAttribute("name")===D)return a}else return a;if(a=si(a.nextSibling),a===null)break}return null}function gp(a,c,f){if(c==="")return null;for(;a.nodeType!==3;)if((a.nodeType!==1||a.nodeName!=="INPUT"||a.type!=="hidden")&&!f||(a=si(a.nextSibling),a===null))return null;return a}function Hf(a,c){for(;a.nodeType!==8;)if((a.nodeType!==1||a.nodeName!=="INPUT"||a.type!=="hidden")&&!c||(a=si(a.nextSibling),a===null))return null;return a}function Yc(a){return a.data==="$?"||a.data==="$~"}function eu(a){return a.data==="$!"||a.data==="$?"&&a.ownerDocument.readyState!=="loading"}function mp(a,c){var f=a.ownerDocument;if(a.data==="$~")a._reactRetry=c;else if(a.data!=="$?"||f.readyState!=="loading")c();else{var y=function(){c(),f.removeEventListener("DOMContentLoaded",y)};f.addEventListener("DOMContentLoaded",y),a._reactRetry=y}}function si(a){for(;a!=null;a=a.nextSibling){var c=a.nodeType;if(c===1||c===3)break;if(c===8){if(c=a.data,c==="$"||c==="$!"||c==="$?"||c==="$~"||c==="&"||c==="F!"||c==="F")break;if(c==="/$"||c==="/&")return null}}return a}var tu=null;function Wf(a){a=a.nextSibling;for(var c=0;a;){if(a.nodeType===8){var f=a.data;if(f==="/$"||f==="/&"){if(c===0)return si(a.nextSibling);c--}else f!=="$"&&f!=="$!"&&f!=="$?"&&f!=="$~"&&f!=="&"||c++}a=a.nextSibling}return null}function Kf(a){a=a.previousSibling;for(var c=0;a;){if(a.nodeType===8){var f=a.data;if(f==="$"||f==="$!"||f==="$?"||f==="$~"||f==="&"){if(c===0)return a;c--}else f!=="/$"&&f!=="/&"||c++}a=a.previousSibling}return null}function Zf(a,c,f){switch(c=ll(f),a){case"html":if(a=c.documentElement,!a)throw Error(i(452));return a;case"head":if(a=c.head,!a)throw Error(i(453));return a;case"body":if(a=c.body,!a)throw Error(i(454));return a;default:throw Error(i(451))}}function no(a){for(var c=a.attributes;c.length;)a.removeAttributeNode(c[0]);Sr(a)}var ai=new Map,Gf=new Set;function cl(a){return typeof a.getRootNode=="function"?a.getRootNode():a.nodeType===9?a:a.ownerDocument}var qi=Oe.d;Oe.d={f:yp,r:bp,D:_p,C:Sp,L:vp,m:wp,X:Ep,S:xp,M:Rp};function yp(){var a=qi.f(),c=el();return a||c}function bp(a){var c=ci(a);c!==null&&c.tag===5&&c.type==="form"?dd(c):qi.r(a)}var ya=typeof document>"u"?null:document;function Jf(a,c,f){var y=ya;if(y&&typeof c=="string"&&c){var R=Fe(c);R='link[rel="'+a+'"][href="'+R+'"]',typeof f=="string"&&(R+='[crossorigin="'+f+'"]'),Gf.has(R)||(Gf.add(R),a={rel:a,crossOrigin:f,href:c},y.querySelector(R)===null&&(c=y.createElement("link"),pn(c,"link",a),Rr(c),y.head.appendChild(c)))}}function _p(a){qi.D(a),Jf("dns-prefetch",a,null)}function Sp(a,c){qi.C(a,c),Jf("preconnect",a,c)}function vp(a,c,f){qi.L(a,c,f);var y=ya;if(y&&a&&c){var R='link[rel="preload"][as="'+Fe(c)+'"]';c==="image"&&f&&f.imageSrcSet?(R+='[imagesrcset="'+Fe(f.imageSrcSet)+'"]',typeof f.imageSizes=="string"&&(R+='[imagesizes="'+Fe(f.imageSizes)+'"]')):R+='[href="'+Fe(a)+'"]';var D=R;switch(c){case"style":D=ba(a);break;case"script":D=Sa(a)}ai.has(D)||(a=g({rel:"preload",href:c==="image"&&f&&f.imageSrcSet?void 0:a,as:c},f),ai.set(D,a),y.querySelector(R)!==null||c==="style"&&y.querySelector(io(D))||c==="script"&&y.querySelector(so(D))||(c=y.createElement("link"),pn(c,"link",a),Rr(c),y.head.appendChild(c)))}}function wp(a,c){qi.m(a,c);var f=ya;if(f&&a){var y=c&&typeof c.as=="string"?c.as:"script",R='link[rel="modulepreload"][as="'+Fe(y)+'"][href="'+Fe(a)+'"]',D=R;switch(y){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":D=Sa(a)}if(!ai.has(D)&&(a=g({rel:"modulepreload",href:a},c),ai.set(D,a),f.querySelector(R)===null)){switch(y){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(f.querySelector(so(D)))return}y=f.createElement("link"),pn(y,"link",a),Rr(y),f.head.appendChild(y)}}}function xp(a,c,f){qi.S(a,c,f);var y=ya;if(y&&a){var R=xn(y).hoistableStyles,D=ba(a);c=c||"default";var Z=R.get(D);if(!Z){var ue={loading:0,preload:null};if(Z=y.querySelector(io(D)))ue.loading=5;else{a=g({rel:"stylesheet",href:a,"data-precedence":c},f),(f=ai.get(D))&&ru(a,f);var $e=Z=y.createElement("link");Rr($e),pn($e,"link",a),$e._p=new Promise(function(et,ct){$e.onload=et,$e.onerror=ct}),$e.addEventListener("load",function(){ue.loading|=1}),$e.addEventListener("error",function(){ue.loading|=2}),ue.loading|=4,ul(Z,c,y)}Z={type:"stylesheet",instance:Z,count:1,state:ue},R.set(D,Z)}}}function Ep(a,c){qi.X(a,c);var f=ya;if(f&&a){var y=xn(f).hoistableScripts,R=Sa(a),D=y.get(R);D||(D=f.querySelector(so(R)),D||(a=g({src:a,async:!0},c),(c=ai.get(R))&&nu(a,c),D=f.createElement("script"),Rr(D),pn(D,"link",a),f.head.appendChild(D)),D={type:"script",instance:D,count:1,state:null},y.set(R,D))}}function Rp(a,c){qi.M(a,c);var f=ya;if(f&&a){var y=xn(f).hoistableScripts,R=Sa(a),D=y.get(R);D||(D=f.querySelector(so(R)),D||(a=g({src:a,async:!0,type:"module"},c),(c=ai.get(R))&&nu(a,c),D=f.createElement("script"),Rr(D),pn(D,"link",a),f.head.appendChild(D)),D={type:"script",instance:D,count:1,state:null},y.set(R,D))}}function Qf(a,c,f,y){var R=(R=He.current)?cl(R):null;if(!R)throw Error(i(446));switch(a){case"meta":case"title":return null;case"style":return typeof f.precedence=="string"&&typeof f.href=="string"?(c=ba(f.href),f=xn(R).hoistableStyles,y=f.get(c),y||(y={type:"style",instance:null,count:0,state:null},f.set(c,y)),y):{type:"void",instance:null,count:0,state:null};case"link":if(f.rel==="stylesheet"&&typeof f.href=="string"&&typeof f.precedence=="string"){a=ba(f.href);var D=xn(R).hoistableStyles,Z=D.get(a);if(Z||(R=R.ownerDocument||R,Z={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},D.set(a,Z),(D=R.querySelector(io(a)))&&!D._p&&(Z.instance=D,Z.state.loading=5),ai.has(a)||(f={rel:"preload",as:"style",href:f.href,crossOrigin:f.crossOrigin,integrity:f.integrity,media:f.media,hrefLang:f.hrefLang,referrerPolicy:f.referrerPolicy},ai.set(a,f),D||Tp(R,a,f,Z.state))),c&&y===null)throw Error(i(528,""));return Z}if(c&&y!==null)throw Error(i(529,""));return null;case"script":return c=f.async,f=f.src,typeof f=="string"&&c&&typeof c!="function"&&typeof c!="symbol"?(c=Sa(f),f=xn(R).hoistableScripts,y=f.get(c),y||(y={type:"script",instance:null,count:0,state:null},f.set(c,y)),y):{type:"void",instance:null,count:0,state:null};default:throw Error(i(444,a))}}function ba(a){return'href="'+Fe(a)+'"'}function io(a){return'link[rel="stylesheet"]['+a+"]"}function Xf(a){return g({},a,{"data-precedence":a.precedence,precedence:null})}function Tp(a,c,f,y){a.querySelector('link[rel="preload"][as="style"]['+c+"]")?y.loading=1:(c=a.createElement("link"),y.preload=c,c.addEventListener("load",function(){return y.loading|=1}),c.addEventListener("error",function(){return y.loading|=2}),pn(c,"link",f),Rr(c),a.head.appendChild(c))}function Sa(a){return'[src="'+Fe(a)+'"]'}function so(a){return"script[async]"+a}function Yf(a,c,f){if(c.count++,c.instance===null)switch(c.type){case"style":var y=a.querySelector('style[data-href~="'+Fe(f.href)+'"]');if(y)return c.instance=y,Rr(y),y;var R=g({},f,{"data-href":f.href,"data-precedence":f.precedence,href:null,precedence:null});return y=(a.ownerDocument||a).createElement("style"),Rr(y),pn(y,"style",R),ul(y,f.precedence,a),c.instance=y;case"stylesheet":R=ba(f.href);var D=a.querySelector(io(R));if(D)return c.state.loading|=4,c.instance=D,Rr(D),D;y=Xf(f),(R=ai.get(R))&&ru(y,R),D=(a.ownerDocument||a).createElement("link"),Rr(D);var Z=D;return Z._p=new Promise(function(ue,$e){Z.onload=ue,Z.onerror=$e}),pn(D,"link",y),c.state.loading|=4,ul(D,f.precedence,a),c.instance=D;case"script":return D=Sa(f.src),(R=a.querySelector(so(D)))?(c.instance=R,Rr(R),R):(y=f,(R=ai.get(D))&&(y=g({},f),nu(y,R)),a=a.ownerDocument||a,R=a.createElement("script"),Rr(R),pn(R,"link",y),a.head.appendChild(R),c.instance=R);case"void":return null;default:throw Error(i(443,c.type))}else c.type==="stylesheet"&&(c.state.loading&4)===0&&(y=c.instance,c.state.loading|=4,ul(y,f.precedence,a));return c.instance}function ul(a,c,f){for(var y=f.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),R=y.length?y[y.length-1]:null,D=R,Z=0;Z<y.length;Z++){var ue=y[Z];if(ue.dataset.precedence===c)D=ue;else if(D!==R)break}D?D.parentNode.insertBefore(a,D.nextSibling):(c=f.nodeType===9?f.head:f,c.insertBefore(a,c.firstChild))}function ru(a,c){a.crossOrigin==null&&(a.crossOrigin=c.crossOrigin),a.referrerPolicy==null&&(a.referrerPolicy=c.referrerPolicy),a.title==null&&(a.title=c.title)}function nu(a,c){a.crossOrigin==null&&(a.crossOrigin=c.crossOrigin),a.referrerPolicy==null&&(a.referrerPolicy=c.referrerPolicy),a.integrity==null&&(a.integrity=c.integrity)}var dl=null;function eh(a,c,f){if(dl===null){var y=new Map,R=dl=new Map;R.set(f,y)}else R=dl,y=R.get(f),y||(y=new Map,R.set(f,y));if(y.has(a))return y;for(y.set(a,null),f=f.getElementsByTagName(a),R=0;R<f.length;R++){var D=f[R];if(!(D[li]||D[zt]||a==="link"&&D.getAttribute("rel")==="stylesheet")&&D.namespaceURI!=="http://www.w3.org/2000/svg"){var Z=D.getAttribute(c)||"";Z=a+Z;var ue=y.get(Z);ue?ue.push(D):y.set(Z,[D])}}return y}function th(a,c,f){a=a.ownerDocument||a,a.head.insertBefore(f,c==="title"?a.querySelector("head > title"):null)}function Ap(a,c,f){if(f===1||c.itemProp!=null)return!1;switch(a){case"meta":case"title":return!0;case"style":if(typeof c.precedence!="string"||typeof c.href!="string"||c.href==="")break;return!0;case"link":if(typeof c.rel!="string"||typeof c.href!="string"||c.href===""||c.onLoad||c.onError)break;return c.rel==="stylesheet"?(a=c.disabled,typeof c.precedence=="string"&&a==null):!0;case"script":if(c.async&&typeof c.async!="function"&&typeof c.async!="symbol"&&!c.onLoad&&!c.onError&&c.src&&typeof c.src=="string")return!0}return!1}function rh(a){return!(a.type==="stylesheet"&&(a.state.loading&3)===0)}function Cp(a,c,f,y){if(f.type==="stylesheet"&&(typeof y.media!="string"||matchMedia(y.media).matches!==!1)&&(f.state.loading&4)===0){if(f.instance===null){var R=ba(y.href),D=c.querySelector(io(R));if(D){c=D._p,c!==null&&typeof c=="object"&&typeof c.then=="function"&&(a.count++,a=fl.bind(a),c.then(a,a)),f.state.loading|=4,f.instance=D,Rr(D);return}D=c.ownerDocument||c,y=Xf(y),(R=ai.get(R))&&ru(y,R),D=D.createElement("link"),Rr(D);var Z=D;Z._p=new Promise(function(ue,$e){Z.onload=ue,Z.onerror=$e}),pn(D,"link",y),f.instance=D}a.stylesheets===null&&(a.stylesheets=new Map),a.stylesheets.set(f,c),(c=f.state.preload)&&(f.state.loading&3)===0&&(a.count++,f=fl.bind(a),c.addEventListener("load",f),c.addEventListener("error",f))}}var iu=0;function Ip(a,c){return a.stylesheets&&a.count===0&&pl(a,a.stylesheets),0<a.count||0<a.imgCount?function(f){var y=setTimeout(function(){if(a.stylesheets&&pl(a,a.stylesheets),a.unsuspend){var D=a.unsuspend;a.unsuspend=null,D()}},6e4+c);0<a.imgBytes&&iu===0&&(iu=62500*cp());var R=setTimeout(function(){if(a.waitingForImages=!1,a.count===0&&(a.stylesheets&&pl(a,a.stylesheets),a.unsuspend)){var D=a.unsuspend;a.unsuspend=null,D()}},(a.imgBytes>iu?50:800)+c);return a.unsuspend=f,function(){a.unsuspend=null,clearTimeout(y),clearTimeout(R)}}:null}function fl(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)pl(this,this.stylesheets);else if(this.unsuspend){var a=this.unsuspend;this.unsuspend=null,a()}}}var hl=null;function pl(a,c){a.stylesheets=null,a.unsuspend!==null&&(a.count++,hl=new Map,c.forEach(Dp,a),hl=null,fl.call(a))}function Dp(a,c){if(!(c.state.loading&4)){var f=hl.get(a);if(f)var y=f.get(null);else{f=new Map,hl.set(a,f);for(var R=a.querySelectorAll("link[data-precedence],style[data-precedence]"),D=0;D<R.length;D++){var Z=R[D];(Z.nodeName==="LINK"||Z.getAttribute("media")!=="not all")&&(f.set(Z.dataset.precedence,Z),y=Z)}y&&f.set(null,y)}R=c.instance,Z=R.getAttribute("data-precedence"),D=f.get(Z)||y,D===y&&f.set(null,R),f.set(Z,R),this.count++,y=fl.bind(this),R.addEventListener("load",y),R.addEventListener("error",y),D?D.parentNode.insertBefore(R,D.nextSibling):(a=a.nodeType===9?a.head:a,a.insertBefore(R,a.firstChild)),c.state.loading|=4}}var ao={$$typeof:T,Provider:null,Consumer:null,_currentValue:ce,_currentValue2:ce,_threadCount:0};function Np(a,c,f,y,R,D,Z,ue,$e){this.tag=1,this.containerInfo=a,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=K(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=K(0),this.hiddenUpdates=K(null),this.identifierPrefix=y,this.onUncaughtError=R,this.onCaughtError=D,this.onRecoverableError=Z,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=$e,this.incompleteTransitions=new Map}function nh(a,c,f,y,R,D,Z,ue,$e,et,ct,ft){return a=new Np(a,c,f,Z,$e,et,ct,ft,ue),c=1,D===!0&&(c|=24),D=jn(3,null,null,c),a.current=D,D.stateNode=a,c=jl(),c.refCount++,a.pooledCache=c,c.refCount++,D.memoizedState={element:y,isDehydrated:f,cache:c},Bl(D),a}function ih(a){return a?(a=Js,a):Js}function sh(a,c,f,y,R,D){R=ih(R),y.context===null?y.context=R:y.pendingContext=R,y=ss(c),y.payload={element:f},D=D===void 0?null:D,D!==null&&(y.callback=D),f=as(a,y,c),f!==null&&(Fn(f,a,c),$a(f,a,c))}function ah(a,c){if(a=a.memoizedState,a!==null&&a.dehydrated!==null){var f=a.retryLane;a.retryLane=f!==0&&f<c?f:c}}function su(a,c){ah(a,c),(a=a.alternate)&&ah(a,c)}function oh(a){if(a.tag===13||a.tag===31){var c=As(a,67108864);c!==null&&Fn(c,a,67108864),su(a,67108864)}}function lh(a){if(a.tag===13||a.tag===31){var c=qn();c=ln(c);var f=As(a,c);f!==null&&Fn(f,a,c),su(a,c)}}var gl=!0;function Fp(a,c,f,y){var R=he.T;he.T=null;var D=Oe.p;try{Oe.p=2,au(a,c,f,y)}finally{Oe.p=D,he.T=R}}function Up(a,c,f,y){var R=he.T;he.T=null;var D=Oe.p;try{Oe.p=8,au(a,c,f,y)}finally{Oe.p=D,he.T=R}}function au(a,c,f,y){if(gl){var R=ou(y);if(R===null)Wc(a,c,y,ml,f),uh(a,y);else if(kp(R,a,c,f,y))y.stopPropagation();else if(uh(a,y),c&4&&-1<Pp.indexOf(a)){for(;R!==null;){var D=ci(R);if(D!==null)switch(D.tag){case 3:if(D=D.stateNode,D.current.memoizedState.isDehydrated){var Z=Bt(D.pendingLanes);if(Z!==0){var ue=D;for(ue.pendingLanes|=2,ue.entangledLanes|=2;Z;){var $e=1<<31-Rt(Z);ue.entanglements[1]|=$e,Z&=~$e}Si(D),(nr&6)===0&&(Xo=ht()+500,eo(0))}}break;case 31:case 13:ue=As(D,2),ue!==null&&Fn(ue,D,2),el(),su(D,2)}if(D=ou(y),D===null&&Wc(a,c,y,ml,f),D===R)break;R=D}R!==null&&y.stopPropagation()}else Wc(a,c,y,null,f)}}function ou(a){return a=Qt(a),lu(a)}var ml=null;function lu(a){if(ml=null,a=lr(a),a!==null){var c=o(a);if(c===null)a=null;else{var f=c.tag;if(f===13){if(a=l(c),a!==null)return a;a=null}else if(f===31){if(a=u(c),a!==null)return a;a=null}else if(f===3){if(c.stateNode.current.memoizedState.isDehydrated)return c.tag===3?c.stateNode.containerInfo:null;a=null}else c!==a&&(a=null)}}return ml=a,null}function ch(a){switch(a){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(Je()){case gt:return 2;case Y:return 8;case U:case z:return 32;case j:return 268435456;default:return 32}default:return 32}}var cu=!1,ys=null,bs=null,_s=null,oo=new Map,lo=new Map,Ss=[],Pp="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function uh(a,c){switch(a){case"focusin":case"focusout":ys=null;break;case"dragenter":case"dragleave":bs=null;break;case"mouseover":case"mouseout":_s=null;break;case"pointerover":case"pointerout":oo.delete(c.pointerId);break;case"gotpointercapture":case"lostpointercapture":lo.delete(c.pointerId)}}function co(a,c,f,y,R,D){return a===null||a.nativeEvent!==D?(a={blockedOn:c,domEventName:f,eventSystemFlags:y,nativeEvent:D,targetContainers:[R]},c!==null&&(c=ci(c),c!==null&&oh(c)),a):(a.eventSystemFlags|=y,c=a.targetContainers,R!==null&&c.indexOf(R)===-1&&c.push(R),a)}function kp(a,c,f,y,R){switch(c){case"focusin":return ys=co(ys,a,c,f,y,R),!0;case"dragenter":return bs=co(bs,a,c,f,y,R),!0;case"mouseover":return _s=co(_s,a,c,f,y,R),!0;case"pointerover":var D=R.pointerId;return oo.set(D,co(oo.get(D)||null,a,c,f,y,R)),!0;case"gotpointercapture":return D=R.pointerId,lo.set(D,co(lo.get(D)||null,a,c,f,y,R)),!0}return!1}function dh(a){var c=lr(a.target);if(c!==null){var f=o(c);if(f!==null){if(c=f.tag,c===13){if(c=l(f),c!==null){a.blockedOn=c,Sn(a.priority,function(){lh(f)});return}}else if(c===31){if(c=u(f),c!==null){a.blockedOn=c,Sn(a.priority,function(){lh(f)});return}}else if(c===3&&f.stateNode.current.memoizedState.isDehydrated){a.blockedOn=f.tag===3?f.stateNode.containerInfo:null;return}}}a.blockedOn=null}function yl(a){if(a.blockedOn!==null)return!1;for(var c=a.targetContainers;0<c.length;){var f=ou(a.nativeEvent);if(f===null){f=a.nativeEvent;var y=new f.constructor(f.type,f);Jt=y,f.target.dispatchEvent(y),Jt=null}else return c=ci(f),c!==null&&oh(c),a.blockedOn=f,!1;c.shift()}return!0}function fh(a,c,f){yl(a)&&f.delete(c)}function Lp(){cu=!1,ys!==null&&yl(ys)&&(ys=null),bs!==null&&yl(bs)&&(bs=null),_s!==null&&yl(_s)&&(_s=null),oo.forEach(fh),lo.forEach(fh)}function bl(a,c){a.blockedOn===c&&(a.blockedOn=null,cu||(cu=!0,n.unstable_scheduleCallback(n.unstable_NormalPriority,Lp)))}var _l=null;function hh(a){_l!==a&&(_l=a,n.unstable_scheduleCallback(n.unstable_NormalPriority,function(){_l===a&&(_l=null);for(var c=0;c<a.length;c+=3){var f=a[c],y=a[c+1],R=a[c+2];if(typeof y!="function"){if(lu(y||f)===null)continue;break}var D=ci(f);D!==null&&(a.splice(c,3),c-=3,oc(D,{pending:!0,data:R,method:f.method,action:y},y,R))}}))}function va(a){function c($e){return bl($e,a)}ys!==null&&bl(ys,a),bs!==null&&bl(bs,a),_s!==null&&bl(_s,a),oo.forEach(c),lo.forEach(c);for(var f=0;f<Ss.length;f++){var y=Ss[f];y.blockedOn===a&&(y.blockedOn=null)}for(;0<Ss.length&&(f=Ss[0],f.blockedOn===null);)dh(f),f.blockedOn===null&&Ss.shift();if(f=(a.ownerDocument||a).$$reactFormReplay,f!=null)for(y=0;y<f.length;y+=3){var R=f[y],D=f[y+1],Z=R[pr]||null;if(typeof D=="function")Z||hh(f);else if(Z){var ue=null;if(D&&D.hasAttribute("formAction")){if(R=D,Z=D[pr]||null)ue=Z.formAction;else if(lu(R)!==null)continue}else ue=Z.action;typeof ue=="function"?f[y+1]=ue:(f.splice(y,3),y-=3),hh(f)}}}function ph(){function a(D){D.canIntercept&&D.info==="react-transition"&&D.intercept({handler:function(){return new Promise(function(Z){return R=Z})},focusReset:"manual",scroll:"manual"})}function c(){R!==null&&(R(),R=null),y||setTimeout(f,20)}function f(){if(!y&&!navigation.transition){var D=navigation.currentEntry;D&&D.url!=null&&navigation.navigate(D.url,{state:D.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var y=!1,R=null;return navigation.addEventListener("navigate",a),navigation.addEventListener("navigatesuccess",c),navigation.addEventListener("navigateerror",c),setTimeout(f,100),function(){y=!0,navigation.removeEventListener("navigate",a),navigation.removeEventListener("navigatesuccess",c),navigation.removeEventListener("navigateerror",c),R!==null&&(R(),R=null)}}}function uu(a){this._internalRoot=a}Sl.prototype.render=uu.prototype.render=function(a){var c=this._internalRoot;if(c===null)throw Error(i(409));var f=c.current,y=qn();sh(f,y,a,c,null,null)},Sl.prototype.unmount=uu.prototype.unmount=function(){var a=this._internalRoot;if(a!==null){this._internalRoot=null;var c=a.containerInfo;sh(a.current,2,null,a,null,null),el(),c[Pr]=null}};function Sl(a){this._internalRoot=a}Sl.prototype.unstable_scheduleHydration=function(a){if(a){var c=ar();a={blockedOn:null,target:a,priority:c};for(var f=0;f<Ss.length&&c!==0&&c<Ss[f].priority;f++);Ss.splice(f,0,a),f===0&&dh(a)}};var gh=e.version;if(gh!=="19.2.8")throw Error(i(527,gh,"19.2.8"));Oe.findDOMNode=function(a){var c=a._reactInternals;if(c===void 0)throw typeof a.render=="function"?Error(i(188)):(a=Object.keys(a).join(","),Error(i(268,a)));return a=d(c),a=a!==null?p(a):null,a=a===null?null:a.stateNode,a};var jp={bundleType:0,version:"19.2.8",rendererPackageName:"react-dom",currentDispatcherRef:he,reconcilerVersion:"19.2.8"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var vl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!vl.isDisabled&&vl.supportsFiber)try{Le=vl.inject(jp),mt=vl}catch{}}return reactDomClient_production.createRoot=function(a,c){if(!s(a))throw Error(i(299));var f=!1,y="",R=vd,D=wd,Z=xd;return c!=null&&(c.unstable_strictMode===!0&&(f=!0),c.identifierPrefix!==void 0&&(y=c.identifierPrefix),c.onUncaughtError!==void 0&&(R=c.onUncaughtError),c.onCaughtError!==void 0&&(D=c.onCaughtError),c.onRecoverableError!==void 0&&(Z=c.onRecoverableError)),c=nh(a,1,!1,null,null,f,y,null,R,D,Z,ph),a[Pr]=c.current,Hc(a),new uu(c)},reactDomClient_production.hydrateRoot=function(a,c,f){if(!s(a))throw Error(i(299));var y=!1,R="",D=vd,Z=wd,ue=xd,$e=null;return f!=null&&(f.unstable_strictMode===!0&&(y=!0),f.identifierPrefix!==void 0&&(R=f.identifierPrefix),f.onUncaughtError!==void 0&&(D=f.onUncaughtError),f.onCaughtError!==void 0&&(Z=f.onCaughtError),f.onRecoverableError!==void 0&&(ue=f.onRecoverableError),f.formState!==void 0&&($e=f.formState)),c=nh(a,1,!0,c,f??null,y,R,$e,D,Z,ue,ph),c.context=ih(null),f=c.current,y=qn(),y=ln(y),R=ss(y),R.callback=null,as(f,R,y),f=y,c.current.lanes=f,ze(c,f),Si(c),a[Pr]=c.current,Hc(a),new Sl(c)},reactDomClient_production.version="19.2.8",reactDomClient_production}var hasRequiredClient;function requireClient(){if(hasRequiredClient)return client.exports;hasRequiredClient=1;function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),client.exports=requireReactDomClient_production(),client.exports}var clientExports=requireClient(),__defProp$6=Object.defineProperty,__name$6=(n,e)=>__defProp$6(n,"name",{value:e,configurable:!0});function createContext2(n,e){const t=reactExports.createContext(e);t.displayName=n+"Context";const i=__name$6(o=>{const{children:l,...u}=o,h=reactExports.useMemo(()=>u,Object.values(u));return jsxRuntimeExports.jsx(t.Provider,{value:h,children:l})},"Provider");i.displayName=n+"Provider";function s(o,l={}){const{optional:u=!1}=l,h=reactExports.useContext(t);if(h)return h;if(e!==void 0)return e;if(!u)throw new Error(`\`${o}\` must be used within \`${n}\``)}return __name$6(s,"useContext"),[i,s]}__name$6(createContext2,"createContext");function createContextScope(n,e=[]){let t=[];function i(o,l){const u=reactExports.createContext(l);u.displayName=o+"Context";const h=t.length;t=[...t,l];const d=__name$6(g=>{const{scope:m,children:v,...S}=g,E=m?.[n]?.[h]||u,x=reactExports.useMemo(()=>S,Object.values(S));return jsxRuntimeExports.jsx(E.Provider,{value:x,children:v})},"Provider");d.displayName=o+"Provider";function p(g,m,v={}){const{optional:S=!1}=v,E=m?.[n]?.[h]||u,x=reactExports.useContext(E);if(x)return x;if(l!==void 0)return l;if(!S)throw new Error(`\`${g}\` must be used within \`${o}\``)}return __name$6(p,"useContext"),[d,p]}__name$6(i,"createContext");const s=__name$6(()=>{const o=t.map(l=>reactExports.createContext(l));return __name$6(function(u){const h=u?.[n]||o;return reactExports.useMemo(()=>({[`__scope${n}`]:{...u,[n]:h}}),[u,h])},"useScope")},"createScope");return s.scopeName=n,[i,composeContextScopes(s,...e)]}__name$6(createContextScope,"createContextScope");function composeContextScopes(...n){const e=n[0];if(n.length===1)return e;const t=__name$6(()=>{const i=n.map(s=>({useScope:s(),scopeName:s.scopeName}));return __name$6(function(o){const l=i.reduce((u,{useScope:h,scopeName:d})=>{const g=h(o)[`__scope${d}`];return{...u,...g}},{});return reactExports.useMemo(()=>({[`__scope${e.scopeName}`]:l}),[l])},"useComposedScopes")},"createScope");return t.scopeName=e.scopeName,t}__name$6(composeContextScopes,"composeContextScopes");var __defProp$5=Object.defineProperty,__name$5=(n,e)=>__defProp$5(n,"name",{value:e,configurable:!0});function useCallbackRef(n){const e=reactExports.useRef(n);return reactExports.useEffect(()=>{e.current=n}),reactExports.useMemo(()=>((...t)=>e.current?.(...t)),[])}__name$5(useCallbackRef,"useCallbackRef");var useLayoutEffect2=globalThis?.document?reactExports.useLayoutEffect:()=>{},reactDomExports=requireReactDom(),__defProp$4=Object.defineProperty,__name$4=(n,e)=>__defProp$4(n,"name",{value:e,configurable:!0});function setRef(n,e){if(typeof n=="function")return n(e);n!=null&&(n.current=e)}__name$4(setRef,"setRef");function composeRefs(...n){return e=>{let t=!1;const i=n.map(s=>{const o=setRef(s,e);return!t&&typeof o=="function"&&(t=!0),o});if(t)return()=>{for(let s=0;s<i.length;s++){const o=i[s];typeof o=="function"?o():setRef(n[s],null)}}}}__name$4(composeRefs,"composeRefs");function useComposedRefs(...n){return reactExports.useCallback(composeRefs(...n),n)}__name$4(useComposedRefs,"useComposedRefs");var __defProp$3=Object.defineProperty,__name$3=(n,e)=>__defProp$3(n,"name",{value:e,configurable:!0});function createSlot(n){const e=reactExports.forwardRef((t,i)=>{let{children:s,...o}=t,l=null,u=!1;const h=[];isLazyComponent(s)&&typeof use=="function"&&(s=use(s._payload)),reactExports.Children.forEach(s,m=>{if(isSlottable(m)){u=!0;const v=m;let S="child"in v.props?v.props.child:v.props.children;isLazyComponent(S)&&typeof use=="function"&&(S=use(S._payload)),l=getSlottableElementFromSlottable(v,S),h.push(l?.props?.children)}else h.push(m)}),l?l=reactExports.cloneElement(l,void 0,h):!u&&reactExports.Children.count(s)===1&&reactExports.isValidElement(s)&&(l=s);const d=l?getElementRef(l):void 0,p=useComposedRefs(i,d);if(!l){if(s||s===0)throw new Error(u?createSlottableError(n):createSlotError(n));return s}const g=mergeProps(o,l.props??{});return l.type!==reactExports.Fragment&&(g.ref=i?p:d),reactExports.cloneElement(l,g)});return e.displayName=`${n}.Slot`,e}__name$3(createSlot,"createSlot");var Slot=createSlot("Slot"),SLOTTABLE_IDENTIFIER=Symbol.for("radix.slottable");function createSlottable(n){const e=__name$3(t=>"child"in t?t.children(t.child):t.children,"Slottable");return e.displayName=`${n}.Slottable`,e.__radixId=SLOTTABLE_IDENTIFIER,e}__name$3(createSlottable,"createSlottable");var getSlottableElementFromSlottable=__name$3((n,e)=>{if("child"in n.props){const t=n.props.child;return reactExports.isValidElement(t)?reactExports.cloneElement(t,void 0,n.props.children(t.props.children)):null}return reactExports.isValidElement(e)?e:null},"getSlottableElementFromSlottable");function mergeProps(n,e){const t={...e};for(const i in e){const s=n[i],o=e[i];/^on[A-Z]/.test(i)?s&&o?t[i]=(...u)=>{const h=o(...u);return s(...u),h}:s&&(t[i]=s):i==="style"?t[i]={...s,...o}:i==="className"&&(t[i]=[s,o].filter(Boolean).join(" "))}return{...n,...t}}__name$3(mergeProps,"mergeProps");function getElementRef(n){let e=Object.getOwnPropertyDescriptor(n.props,"ref")?.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=Object.getOwnPropertyDescriptor(n,"ref")?.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}__name$3(getElementRef,"getElementRef");function isSlottable(n){return reactExports.isValidElement(n)&&typeof n.type=="function"&&"__radixId"in n.type&&n.type.__radixId===SLOTTABLE_IDENTIFIER}__name$3(isSlottable,"isSlottable");var REACT_LAZY_TYPE=Symbol.for("react.lazy");function isLazyComponent(n){return n!=null&&typeof n=="object"&&"$$typeof"in n&&n.$$typeof===REACT_LAZY_TYPE&&"_payload"in n&&isPromiseLike(n._payload)}__name$3(isLazyComponent,"isLazyComponent");function isPromiseLike(n){return typeof n=="object"&&n!==null&&"then"in n}__name$3(isPromiseLike,"isPromiseLike");var createSlotError=__name$3(n=>`${n} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),createSlottableError=__name$3(n=>`${n} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),use=React4[" use ".trim().toString()],__defProp$2=Object.defineProperty,__name$2=(n,e)=>__defProp$2(n,"name",{value:e,configurable:!0}),NODES=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Primitive=NODES.reduce((n,e)=>{const t=createSlot(`Primitive.${e}`),i=reactExports.forwardRef((s,o)=>{const{asChild:l,...u}=s,h=l?t:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),jsxRuntimeExports.jsx(h,{...u,ref:o})});return i.displayName=`Primitive.${e}`,{...n,[e]:i}},{});function dispatchDiscreteCustomEvent(n,e){n&&reactDomExports.flushSync(()=>n.dispatchEvent(e))}__name$2(dispatchDiscreteCustomEvent,"dispatchDiscreteCustomEvent");var __defProp$1=Object.defineProperty,__name$1=(n,e)=>__defProp$1(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$1(function(e,t){const{__scopeAvatar:i,...s}=e,[o,l]=reactExports.useState("idle"),[u,h]=useImageCount();return jsxRuntimeExports.jsx(AvatarProvider,{scope:i,imageLoadingStatus:o,setImageLoadingStatus:l,imageCount:u,setImageCount:h,children:jsxRuntimeExports.jsx(Primitive.span,{...s,ref:t})})},"Avatar")),IMAGE_NAME="AvatarImage",AvatarImage$1=reactExports.forwardRef(__name$1(function(e,t){const{__scopeAvatar:i,src:s,onLoadingStatusChange:o,...l}=e,u=useAvatarContext(IMAGE_NAME,i);u.setImageCount;const h=useImageLoadingStatus(s,{referrerPolicy:l.referrerPolicy,crossOrigin:l.crossOrigin,loadingStatus:u.imageLoadingStatus,setLoadingStatus:u.setImageLoadingStatus}),d=useCallbackRef(g=>{o?.(g)}),p=reactExports.useRef(h);return useLayoutEffect2(()=>{const g=p.current;p.current=h,h!==g&&d(h)},[h,d]),h==="loaded"?jsxRuntimeExports.jsx(Primitive.img,{...l,ref:t,src:s}):null},"AvatarImage")),FALLBACK_NAME="AvatarFallback",AvatarFallback$1=reactExports.forwardRef(__name$1(function(e,t){const{__scopeAvatar:i,delayMs:s,...o}=e,l=useAvatarContext(FALLBACK_NAME,i),[u,h]=reactExports.useState(s===void 0);return reactExports.useEffect(()=>{if(s!==void 0){const d=window.setTimeout(()=>h(!0),s);return()=>window.clearTimeout(d)}},[s]),u&&l.imageLoadingStatus!=="loaded"?jsxRuntimeExports.jsx(Primitive.span,{...o,ref:t}):null},"AvatarFallback"));function useImageLoadingStatus(n,{loadingStatus:e,setLoadingStatus:t,referrerPolicy:i,crossOrigin:s}){return useLayoutEffect2(()=>{if(!n){t("error");return}const o=new window.Image,l=__name$1(h=>{const d=h.currentTarget;t(getImageLoadingStatus(d))},"handleLoad"),u=__name$1(()=>t("error"),"handleError");return o.addEventListener("load",l),o.addEventListener("error",u),i&&(o.referrerPolicy=i),o.crossOrigin=s??null,o.src=n,t(getImageLoadingStatus(o)),()=>{o.removeEventListener("load",l),o.removeEventListener("error",u),t("idle")}},[n,s,i,t]),e}__name$1(useImageLoadingStatus,"useImageLoadingStatus");function getImageLoadingStatus(n){return n.complete?n.naturalWidth>0?"loaded":"error":"loading"}__name$1(getImageLoadingStatus,"getImageLoadingStatus");function useImageCount(){return STATIC_IMAGE_COUNT_STATE}__name$1(useImageCount,"useImageCount");function useUpdateImageCount(n){}__name$1(useUpdateImageCount,"useUpdateImageCount");function r(n){var e,t,i="";if(typeof n=="string"||typeof n=="number")i+=n;else if(typeof n=="object")if(Array.isArray(n)){var s=n.length;for(e=0;e<s;e++)n[e]&&(t=r(n[e]))&&(i&&(i+=" "),i+=t)}else for(t in n)n[t]&&(i&&(i+=" "),i+=t);return i}function clsx(){for(var n,e,t=0,i="",s=arguments.length;t<s;t++)(n=arguments[t])&&(e=r(n))&&(i&&(i+=" "),i+=e);return i}const concatArrays=(n,e)=>{const t=new Array(n.length+e.length);for(let i=0;i<n.length;i++)t[i]=n[i];for(let i=0;i<e.length;i++)t[n.length+i]=e[i];return t},createClassValidatorObject=(n,e)=>({classGroupId:n,validator:e}),createClassPartObject=(n=new Map,e=null,t)=>({nextPart:n,validators:e,classGroupId:t}),CLASS_PART_SEPARATOR="-",EMPTY_CONFLICTS=[],ARBITRARY_PROPERTY_PREFIX="arbitrary..",createClassGroupUtils=n=>{const e=createClassMap(n),{conflictingClassGroups:t,conflictingClassGroupModifiers:i}=n;return{getClassGroupId:l=>{if(l.startsWith("[")&&l.endsWith("]"))return getGroupIdForArbitraryProperty(l);const u=l.split(CLASS_PART_SEPARATOR),h=u[0]===""&&u.length>1?1:0;return getGroupRecursive(u,h,e)},getConflictingClassGroupIds:(l,u)=>{if(u){const h=i[l],d=t[l];return h?d?concatArrays(d,h):h:d||EMPTY_CONFLICTS}return t[l]||EMPTY_CONFLICTS}}},getGroupRecursive=(n,e,t)=>{if(n.length-e===0)return t.classGroupId;const s=n[e],o=t.nextPart.get(s);if(o){const d=getGroupRecursive(n,e+1,o);if(d)return d}const l=t.validators;if(l===null)return;const u=e===0?n.join(CLASS_PART_SEPARATOR):n.slice(e).join(CLASS_PART_SEPARATOR),h=l.length;for(let d=0;d<h;d++){const p=l[d];if(p.validator(u))return p.classGroupId}},getGroupIdForArbitraryProperty=n=>n.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=n.slice(1,-1),t=e.indexOf(":"),i=e.slice(0,t);return i?ARBITRARY_PROPERTY_PREFIX+i:void 0})(),createClassMap=n=>{const{theme:e,classGroups:t}=n;return processClassGroups(t,e)},processClassGroups=(n,e)=>{const t=createClassPartObject();for(const i in n){const s=n[i];processClassesRecursively(s,t,i,e)}return t},processClassesRecursively=(n,e,t,i)=>{const s=n.length;for(let o=0;o<s;o++){const l=n[o];processClassDefinition(l,e,t,i)}},processClassDefinition=(n,e,t,i)=>{if(typeof n=="string"){processStringDefinition(n,e,t);return}if(typeof n=="function"){processFunctionDefinition(n,e,t,i);return}processObjectDefinition(n,e,t,i)},processStringDefinition=(n,e,t)=>{const i=n===""?e:getPart(e,n);i.classGroupId=t},processFunctionDefinition=(n,e,t,i)=>{if(isThemeGetter(n)){processClassesRecursively(n(i),e,t,i);return}e.validators===null&&(e.validators=[]),e.validators.push(createClassValidatorObject(t,n))},processObjectDefinition=(n,e,t,i)=>{const s=Object.entries(n),o=s.length;for(let l=0;l<o;l++){const[u,h]=s[l];processClassesRecursively(h,getPart(e,u),t,i)}},getPart=(n,e)=>{let t=n;const i=e.split(CLASS_PART_SEPARATOR),s=i.length;for(let o=0;o<s;o++){const l=i[o];let u=t.nextPart.get(l);u||(u=createClassPartObject(),t.nextPart.set(l,u)),t=u}return t},isThemeGetter=n=>"isThemeGetter"in n&&n.isThemeGetter===!0,createLruCache=n=>{if(n<1)return{get:()=>{},set:()=>{}};let e=0,t=Object.create(null),i=Object.create(null);const s=(o,l)=>{t[o]=l,e++,e>n&&(e=0,i=t,t=Object.create(null))};return{get(o){let l=t[o];if(l!==void 0)return l;if((l=i[o])!==void 0)return s(o,l),l},set(o,l){o in t?t[o]=l:s(o,l)}}},IMPORTANT_MODIFIER="!",MODIFIER_SEPARATOR=":",EMPTY_MODIFIERS=[],createResultObject=(n,e,t,i,s)=>({modifiers:n,hasImportantModifier:e,baseClassName:t,maybePostfixModifierPosition:i,isExternal:s}),createParseClassName=n=>{const{prefix:e,experimentalParseClassName:t}=n;let i=s=>{const o=[];let l=0,u=0,h=0,d;const p=s.length;for(let E=0;E<p;E++){const x=s[E];if(l===0&&u===0){if(x===MODIFIER_SEPARATOR){o.push(s.slice(h,E)),h=E+1;continue}if(x==="/"){d=E;continue}}x==="["?l++:x==="]"?l--:x==="("?u++:x===")"&&u--}const g=o.length===0?s:s.slice(h);let m=g,v=!1;g.endsWith(IMPORTANT_MODIFIER)?(m=g.slice(0,-1),v=!0):g.startsWith(IMPORTANT_MODIFIER)&&(m=g.slice(1),v=!0);const S=d&&d>h?d-h:void 0;return createResultObject(o,v,m,S)};if(e){const s=e+MODIFIER_SEPARATOR,o=i;i=l=>l.startsWith(s)?o(l.slice(s.length)):createResultObject(EMPTY_MODIFIERS,!1,l,void 0,!0)}if(t){const s=i;i=o=>t({className:o,parseClassName:s})}return i},createSortModifiers=n=>{const e=new Map;return n.orderSensitiveModifiers.forEach((t,i)=>{e.set(t,1e6+i)}),t=>{const i=[];let s=[];for(let o=0;o<t.length;o++){const l=t[o],u=l[0]==="[",h=e.has(l);u||h?(s.length>0&&(s.sort(),i.push(...s),s=[]),i.push(l)):s.push(l)}return s.length>0&&(s.sort(),i.push(...s)),i}},createConfigUtils=n=>({cache:createLruCache(n.cacheSize),parseClassName:createParseClassName(n),sortModifiers:createSortModifiers(n),postfixLookupClassGroupIds:createPostfixLookupClassGroupIds(n),...createClassGroupUtils(n)}),createPostfixLookupClassGroupIds=n=>{const e=Object.create(null),t=n.postfixLookupClassGroups;if(t)for(let i=0;i<t.length;i++)e[t[i]]=!0;return e},SPLIT_CLASSES_REGEX=/\s+/,mergeClassList=(n,e)=>{const{parseClassName:t,getClassGroupId:i,getConflictingClassGroupIds:s,sortModifiers:o,postfixLookupClassGroupIds:l}=e,u=[],h=n.trim().split(SPLIT_CLASSES_REGEX);let d="";for(let p=h.length-1;p>=0;p-=1){const g=h[p],{isExternal:m,modifiers:v,hasImportantModifier:S,baseClassName:E,maybePostfixModifierPosition:x}=t(g);if(m){d=g+(d.length>0?" "+d:d);continue}let A=!!x,C;if(A){const O=E.substring(0,x);C=i(O);const G=C&&l[C]?i(E):void 0;G&&G!==C&&(C=G,A=!1)}else C=i(E);if(!C){if(!A){d=g+(d.length>0?" "+d:d);continue}if(C=i(E),!C){d=g+(d.length>0?" "+d:d);continue}A=!1}const T=v.length===0?"":v.length===1?v[0]:o(v).join(":"),F=S?T+IMPORTANT_MODIFIER:T,P=F+C;if(u.indexOf(P)>-1)continue;u.push(P);const q=s(C,A);for(let O=0;O<q.length;++O){const G=q[O];u.push(F+G)}d=g+(d.length>0?" "+d:d)}return d},twJoin=(...n)=>{let e=0,t,i,s="";for(;e<n.length;)(t=n[e++])&&(i=toValue(t))&&(s&&(s+=" "),s+=i);return s},toValue=n=>{if(typeof n=="string")return n;let e,t="";for(let i=0;i<n.length;i++)n[i]&&(e=toValue(n[i]))&&(t&&(t+=" "),t+=e);return t},createTailwindMerge=(n,...e)=>{let t,i,s,o;const l=h=>{const d=e.reduce((p,g)=>g(p),n());return t=createConfigUtils(d),i=t.cache.get,s=t.cache.set,o=u,u(h)},u=h=>{const d=i(h);if(d)return d;const p=mergeClassList(h,t);return s(h,p),p};return o=l,(...h)=>o(twJoin(...h))},fallbackThemeArr=[],fromTheme=n=>{const e=t=>t[n]||fallbackThemeArr;return e.isThemeGetter=!0,e},arbitraryValueRegex=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,arbitraryVariableRegex=/^\((?:(\w[\w-]*):)?(.+)\)$/i,fractionRegex=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,tshirtUnitRegex=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,lengthUnitRegex=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,colorFunctionRegex=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,shadowRegex=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,imageRegex=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,isFraction=n=>fractionRegex.test(n),isNumber=n=>!!n&&!Number.isNaN(Number(n)),isInteger=n=>!!n&&Number.isInteger(Number(n)),isPercent=n=>n.endsWith("%")&&isNumber(n.slice(0,-1)),isTshirtSize=n=>tshirtUnitRegex.test(n),isAny=()=>!0,isLengthOnly=n=>lengthUnitRegex.test(n)&&!colorFunctionRegex.test(n),isNever=()=>!1,isShadow=n=>shadowRegex.test(n),isImage=n=>imageRegex.test(n),isAnyNonArbitrary=n=>!isArbitraryValue(n)&&!isArbitraryVariable(n),isNamedContainerQuery=n=>n.startsWith("@container")&&(n[10]==="/"&&n[11]!==void 0||n[11]==="s"&&n[16]!==void 0&&n.startsWith("-size/",10)||n[11]==="n"&&n[18]!==void 0&&n.startsWith("-normal/",10)),isArbitrarySize=n=>getIsArbitraryValue(n,isLabelSize,isNever),isArbitraryValue=n=>arbitraryValueRegex.test(n),isArbitraryLength=n=>getIsArbitraryValue(n,isLabelLength,isLengthOnly),isArbitraryNumber=n=>getIsArbitraryValue(n,isLabelNumber,isNumber),isArbitraryWeight=n=>getIsArbitraryValue(n,isLabelWeight,isAny),isArbitraryFamilyName=n=>getIsArbitraryValue(n,isLabelFamilyName,isNever),isArbitraryPosition=n=>getIsArbitraryValue(n,isLabelPosition,isNever),isArbitraryImage=n=>getIsArbitraryValue(n,isLabelImage,isImage),isArbitraryShadow=n=>getIsArbitraryValue(n,isLabelShadow,isShadow),isArbitraryVariable=n=>arbitraryVariableRegex.test(n),isArbitraryVariableLength=n=>getIsArbitraryVariable(n,isLabelLength),isArbitraryVariableFamilyName=n=>getIsArbitraryVariable(n,isLabelFamilyName),isArbitraryVariablePosition=n=>getIsArbitraryVariable(n,isLabelPosition),isArbitraryVariableSize=n=>getIsArbitraryVariable(n,isLabelSize),isArbitraryVariableImage=n=>getIsArbitraryVariable(n,isLabelImage),isArbitraryVariableShadow=n=>getIsArbitraryVariable(n,isLabelShadow,!0),isArbitraryVariableWeight=n=>getIsArbitraryVariable(n,isLabelWeight,!0),getIsArbitraryValue=(n,e,t)=>{const i=arbitraryValueRegex.exec(n);return i?i[1]?e(i[1]):t(i[2]):!1},getIsArbitraryVariable=(n,e,t=!1)=>{const i=arbitraryVariableRegex.exec(n);return i?i[1]?e(i[1]):t:!1},isLabelPosition=n=>n==="position"||n==="percentage",isLabelImage=n=>n==="image"||n==="url",isLabelSize=n=>n==="length"||n==="size"||n==="bg-size",isLabelLength=n=>n==="length",isLabelNumber=n=>n==="number",isLabelFamilyName=n=>n==="family-name",isLabelWeight=n=>n==="number"||n==="weight",isLabelShadow=n=>n==="shadow",getDefaultConfig=()=>{const n=fromTheme("color"),e=fromTheme("font"),t=fromTheme("text"),i=fromTheme("font-weight"),s=fromTheme("tracking"),o=fromTheme("leading"),l=fromTheme("breakpoint"),u=fromTheme("container"),h=fromTheme("spacing"),d=fromTheme("radius"),p=fromTheme("shadow"),g=fromTheme("inset-shadow"),m=fromTheme("text-shadow"),v=fromTheme("drop-shadow"),S=fromTheme("blur"),E=fromTheme("perspective"),x=fromTheme("aspect"),A=fromTheme("ease"),C=fromTheme("animate"),T=()=>["auto","avoid","all","avoid-page","page","left","right","column"],F=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],P=()=>[...F(),isArbitraryVariable,isArbitraryValue],q=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto","contain","none"],G=()=>[isArbitraryVariable,isArbitraryValue,h],fe=()=>[isFraction,"full","auto",...G()],M=()=>[isInteger,"none","subgrid",isArbitraryVariable,isArbitraryValue],ee=()=>["auto",{span:["full",isInteger,isArbitraryVariable,isArbitraryValue]},isInteger,isArbitraryVariable,isArbitraryValue],Se=()=>[isInteger,"auto",isArbitraryVariable,isArbitraryValue],re=()=>["auto","min","max","fr",isArbitraryVariable,isArbitraryValue],Ae=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],ke=()=>["start","end","center","stretch","center-safe","end-safe"],he=()=>["auto",...G()],Oe=()=>[isFraction,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...G()],ce=()=>[isFraction,"screen","full","dvw","lvw","svw","min","max","fit",...G()],Ue=()=>[isFraction,"screen","full","lh","dvh","lvh","svh","min","max","fit",...G()],$=()=>[n,isArbitraryVariable,isArbitraryValue],W=()=>[...F(),isArbitraryVariablePosition,isArbitraryPosition,{position:[isArbitraryVariable,isArbitraryValue]}],de=()=>["no-repeat",{repeat:["","x","y","space","round"]}],te=()=>["auto","cover","contain",isArbitraryVariableSize,isArbitrarySize,{size:[isArbitraryVariable,isArbitraryValue]}],Te=()=>[isPercent,isArbitraryVariableLength,isArbitraryLength],je=()=>["","none","full",d,isArbitraryVariable,isArbitraryValue],He=()=>["",isNumber,isArbitraryVariableLength,isArbitraryLength],We=()=>["solid","dashed","dotted","double"],me=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ge=()=>[isNumber,isPercent,isArbitraryVariablePosition,isArbitraryPosition],Be=()=>["","none",S,isArbitraryVariable,isArbitraryValue],ie=()=>["none",isNumber,isArbitraryVariable,isArbitraryValue],B=()=>["none",isNumber,isArbitraryVariable,isArbitraryValue],N=()=>[isNumber,isArbitraryVariable,isArbitraryValue],k=()=>[isFraction,"full",...G()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[isTshirtSize],breakpoint:[isTshirtSize],color:[isAny],container:[isTshirtSize],"drop-shadow":[isTshirtSize],ease:["in","out","in-out"],font:[isAnyNonArbitrary],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[isTshirtSize],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[isTshirtSize],shadow:[isTshirtSize],spacing:["px",isNumber],text:[isTshirtSize],"text-shadow":[isTshirtSize],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",isFraction,isArbitraryValue,isArbitraryVariable,x]}],container:["container"],"container-type":[{"@container":["","normal","size",isArbitraryVariable,isArbitraryValue]}],"container-named":[isNamedContainerQuery],columns:[{columns:[isNumber,isArbitraryValue,isArbitraryVariable,u]}],"break-after":[{"break-after":T()}],"break-before":[{"break-before":T()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:P()}],overflow:[{overflow:q()}],"overflow-x":[{"overflow-x":q()}],"overflow-y":[{"overflow-y":q()}],overscroll:[{overscroll:O()}],"overscroll-x":[{"overscroll-x":O()}],"overscroll-y":[{"overscroll-y":O()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:fe()}],"inset-x":[{"inset-x":fe()}],"inset-y":[{"inset-y":fe()}],start:[{"inset-s":fe(),start:fe()}],end:[{"inset-e":fe(),end:fe()}],"inset-bs":[{"inset-bs":fe()}],"inset-be":[{"inset-be":fe()}],top:[{top:fe()}],right:[{right:fe()}],bottom:[{bottom:fe()}],left:[{left:fe()}],visibility:["visible","invisible","collapse"],z:[{z:[isInteger,"auto",isArbitraryVariable,isArbitraryValue]}],basis:[{basis:[isFraction,"full","auto",u,...G()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[isNumber,isFraction,"auto","initial","none",isArbitraryValue]}],grow:[{grow:["",isNumber,isArbitraryVariable,isArbitraryValue]}],shrink:[{shrink:["",isNumber,isArbitraryVariable,isArbitraryValue]}],order:[{order:[isInteger,"first","last","none",isArbitraryVariable,isArbitraryValue]}],"grid-cols":[{"grid-cols":M()}],"col-start-end":[{col:ee()}],"col-start":[{"col-start":Se()}],"col-end":[{"col-end":Se()}],"grid-rows":[{"grid-rows":M()}],"row-start-end":[{row:ee()}],"row-start":[{"row-start":Se()}],"row-end":[{"row-end":Se()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":re()}],"auto-rows":[{"auto-rows":re()}],gap:[{gap:G()}],"gap-x":[{"gap-x":G()}],"gap-y":[{"gap-y":G()}],"justify-content":[{justify:[...Ae(),"normal"]}],"justify-items":[{"justify-items":[...ke(),"normal"]}],"justify-self":[{"justify-self":["auto",...ke()]}],"align-content":[{content:["normal",...Ae()]}],"align-items":[{items:[...ke(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...ke(),{baseline:["","last"]}]}],"place-content":[{"place-content":Ae()}],"place-items":[{"place-items":[...ke(),"baseline"]}],"place-self":[{"place-self":["auto",...ke()]}],p:[{p:G()}],px:[{px:G()}],py:[{py:G()}],ps:[{ps:G()}],pe:[{pe:G()}],pbs:[{pbs:G()}],pbe:[{pbe:G()}],pt:[{pt:G()}],pr:[{pr:G()}],pb:[{pb:G()}],pl:[{pl:G()}],m:[{m:he()}],mx:[{mx:he()}],my:[{my:he()}],ms:[{ms:he()}],me:[{me:he()}],mbs:[{mbs:he()}],mbe:[{mbe:he()}],mt:[{mt:he()}],mr:[{mr:he()}],mb:[{mb:he()}],ml:[{ml:he()}],"space-x":[{"space-x":G()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":G()}],"space-y-reverse":["space-y-reverse"],size:[{size:Oe()}],"inline-size":[{inline:["auto",...ce()]}],"min-inline-size":[{"min-inline":["auto",...ce()]}],"max-inline-size":[{"max-inline":["none",...ce()]}],"block-size":[{block:["auto",...Ue()]}],"min-block-size":[{"min-block":["auto",...Ue()]}],"max-block-size":[{"max-block":["none",...Ue()]}],w:[{w:[u,"screen",...Oe()]}],"min-w":[{"min-w":[u,"screen","none",...Oe()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[l]},...Oe()]}],h:[{h:["screen","lh",...Oe()]}],"min-h":[{"min-h":["screen","lh","none",...Oe()]}],"max-h":[{"max-h":["screen","lh",...Oe()]}],"font-size":[{text:["base",t,isArbitraryVariableLength,isArbitraryLength]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[i,isArbitraryVariableWeight,isArbitraryWeight]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",isPercent,isArbitraryValue]}],"font-family":[{font:[isArbitraryVariableFamilyName,isArbitraryFamilyName,e]}],"font-features":[{"font-features":[isArbitraryValue]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,isArbitraryVariable,isArbitraryValue]}],"line-clamp":[{"line-clamp":[isNumber,"none",isArbitraryVariable,isArbitraryNumber]}],leading:[{leading:[o,...G()]}],"list-image":[{"list-image":["none",isArbitraryVariable,isArbitraryValue]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",isArbitraryVariable,isArbitraryValue]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:$()}],"text-color":[{text:$()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...We(),"wavy"]}],"text-decoration-thickness":[{decoration:[isNumber,"from-font","auto",isArbitraryVariable,isArbitraryLength]}],"text-decoration-color":[{decoration:$()}],"underline-offset":[{"underline-offset":[isNumber,"auto",isArbitraryVariable,isArbitraryValue]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:G()}],"tab-size":[{tab:[isInteger,isArbitraryVariable,isArbitraryValue]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",isArbitraryVariable,isArbitraryValue]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",isArbitraryVariable,isArbitraryValue]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:W()}],"bg-repeat":[{bg:de()}],"bg-size":[{bg:te()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},isInteger,isArbitraryVariable,isArbitraryValue],radial:["",isArbitraryVariable,isArbitraryValue],conic:[isInteger,isArbitraryVariable,isArbitraryValue]},isArbitraryVariableImage,isArbitraryImage]}],"bg-color":[{bg:$()}],"gradient-from-pos":[{from:Te()}],"gradient-via-pos":[{via:Te()}],"gradient-to-pos":[{to:Te()}],"gradient-from":[{from:$()}],"gradient-via":[{via:$()}],"gradient-to":[{to:$()}],rounded:[{rounded:je()}],"rounded-s":[{"rounded-s":je()}],"rounded-e":[{"rounded-e":je()}],"rounded-t":[{"rounded-t":je()}],"rounded-r":[{"rounded-r":je()}],"rounded-b":[{"rounded-b":je()}],"rounded-l":[{"rounded-l":je()}],"rounded-ss":[{"rounded-ss":je()}],"rounded-se":[{"rounded-se":je()}],"rounded-ee":[{"rounded-ee":je()}],"rounded-es":[{"rounded-es":je()}],"rounded-tl":[{"rounded-tl":je()}],"rounded-tr":[{"rounded-tr":je()}],"rounded-br":[{"rounded-br":je()}],"rounded-bl":[{"rounded-bl":je()}],"border-w":[{border:He()}],"border-w-x":[{"border-x":He()}],"border-w-y":[{"border-y":He()}],"border-w-s":[{"border-s":He()}],"border-w-e":[{"border-e":He()}],"border-w-bs":[{"border-bs":He()}],"border-w-be":[{"border-be":He()}],"border-w-t":[{"border-t":He()}],"border-w-r":[{"border-r":He()}],"border-w-b":[{"border-b":He()}],"border-w-l":[{"border-l":He()}],"divide-x":[{"divide-x":He()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":He()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...We(),"hidden","none"]}],"divide-style":[{divide:[...We(),"hidden","none"]}],"border-color":[{border:$()}],"border-color-x":[{"border-x":$()}],"border-color-y":[{"border-y":$()}],"border-color-s":[{"border-s":$()}],"border-color-e":[{"border-e":$()}],"border-color-bs":[{"border-bs":$()}],"border-color-be":[{"border-be":$()}],"border-color-t":[{"border-t":$()}],"border-color-r":[{"border-r":$()}],"border-color-b":[{"border-b":$()}],"border-color-l":[{"border-l":$()}],"divide-color":[{divide:$()}],"outline-style":[{outline:[...We(),"none","hidden"]}],"outline-offset":[{"outline-offset":[isNumber,isArbitraryVariable,isArbitraryValue]}],"outline-w":[{outline:["",isNumber,isArbitraryVariableLength,isArbitraryLength]}],"outline-color":[{outline:$()}],shadow:[{shadow:["","none",p,isArbitraryVariableShadow,isArbitraryShadow]}],"shadow-color":[{shadow:$()}],"inset-shadow":[{"inset-shadow":["none",g,isArbitraryVariableShadow,isArbitraryShadow]}],"inset-shadow-color":[{"inset-shadow":$()}],"ring-w":[{ring:He()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:$()}],"ring-offset-w":[{"ring-offset":[isNumber,isArbitraryLength]}],"ring-offset-color":[{"ring-offset":$()}],"inset-ring-w":[{"inset-ring":He()}],"inset-ring-color":[{"inset-ring":$()}],"text-shadow":[{"text-shadow":["none",m,isArbitraryVariableShadow,isArbitraryShadow]}],"text-shadow-color":[{"text-shadow":$()}],opacity:[{opacity:[isNumber,isArbitraryVariable,isArbitraryValue]}],"mix-blend":[{"mix-blend":[...me(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":me()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[isNumber]}],"mask-image-linear-from-pos":[{"mask-linear-from":ge()}],"mask-image-linear-to-pos":[{"mask-linear-to":ge()}],"mask-image-linear-from-color":[{"mask-linear-from":$()}],"mask-image-linear-to-color":[{"mask-linear-to":$()}],"mask-image-t-from-pos":[{"mask-t-from":ge()}],"mask-image-t-to-pos":[{"mask-t-to":ge()}],"mask-image-t-from-color":[{"mask-t-from":$()}],"mask-image-t-to-color":[{"mask-t-to":$()}],"mask-image-r-from-pos":[{"mask-r-from":ge()}],"mask-image-r-to-pos":[{"mask-r-to":ge()}],"mask-image-r-from-color":[{"mask-r-from":$()}],"mask-image-r-to-color":[{"mask-r-to":$()}],"mask-image-b-from-pos":[{"mask-b-from":ge()}],"mask-image-b-to-pos":[{"mask-b-to":ge()}],"mask-image-b-from-color":[{"mask-b-from":$()}],"mask-image-b-to-color":[{"mask-b-to":$()}],"mask-image-l-from-pos":[{"mask-l-from":ge()}],"mask-image-l-to-pos":[{"mask-l-to":ge()}],"mask-image-l-from-color":[{"mask-l-from":$()}],"mask-image-l-to-color":[{"mask-l-to":$()}],"mask-image-x-from-pos":[{"mask-x-from":ge()}],"mask-image-x-to-pos":[{"mask-x-to":ge()}],"mask-image-x-from-color":[{"mask-x-from":$()}],"mask-image-x-to-color":[{"mask-x-to":$()}],"mask-image-y-from-pos":[{"mask-y-from":ge()}],"mask-image-y-to-pos":[{"mask-y-to":ge()}],"mask-image-y-from-color":[{"mask-y-from":$()}],"mask-image-y-to-color":[{"mask-y-to":$()}],"mask-image-radial":[{"mask-radial":[isArbitraryVariable,isArbitraryValue]}],"mask-image-radial-from-pos":[{"mask-radial-from":ge()}],"mask-image-radial-to-pos":[{"mask-radial-to":ge()}],"mask-image-radial-from-color":[{"mask-radial-from":$()}],"mask-image-radial-to-color":[{"mask-radial-to":$()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":F()}],"mask-image-conic-pos":[{"mask-conic":[isNumber]}],"mask-image-conic-from-pos":[{"mask-conic-from":ge()}],"mask-image-conic-to-pos":[{"mask-conic-to":ge()}],"mask-image-conic-from-color":[{"mask-conic-from":$()}],"mask-image-conic-to-color":[{"mask-conic-to":$()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:W()}],"mask-repeat":[{mask:de()}],"mask-size":[{mask:te()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",isArbitraryVariable,isArbitraryValue]}],filter:[{filter:["","none",isArbitraryVariable,isArbitraryValue]}],blur:[{blur:Be()}],brightness:[{brightness:[isNumber,isArbitraryVariable,isArbitraryValue]}],contrast:[{contrast:[isNumber,isArbitraryVariable,isArbitraryValue]}],"drop-shadow":[{"drop-shadow":["","none",v,isArbitraryVariableShadow,isArbitraryShadow]}],"drop-shadow-color":[{"drop-shadow":$()}],grayscale:[{grayscale:["",isNumber,isArbitraryVariable,isArbitraryValue]}],"hue-rotate":[{"hue-rotate":[isNumber,isArbitraryVariable,isArbitraryValue]}],invert:[{invert:["",isNumber,isArbitraryVariable,isArbitraryValue]}],saturate:[{saturate:[isNumber,isArbitraryVariable,isArbitraryValue]}],sepia:[{sepia:["",isNumber,isArbitraryVariable,isArbitraryValue]}],"backdrop-filter":[{"backdrop-filter":["","none",isArbitraryVariable,isArbitraryValue]}],"backdrop-blur":[{"backdrop-blur":Be()}],"backdrop-brightness":[{"backdrop-brightness":[isNumber,isArbitraryVariable,isArbitraryValue]}],"backdrop-contrast":[{"backdrop-contrast":[isNumber,isArbitraryVariable,isArbitraryValue]}],"backdrop-grayscale":[{"backdrop-grayscale":["",isNumber,isArbitraryVariable,isArbitraryValue]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[isNumber,isArbitraryVariable,isArbitraryValue]}],"backdrop-invert":[{"backdrop-invert":["",isNumber,isArbitraryVariable,isArbitraryValue]}],"backdrop-opacity":[{"backdrop-opacity":[isNumber,isArbitraryVariable,isArbitraryValue]}],"backdrop-saturate":[{"backdrop-saturate":[isNumber,isArbitraryVariable,isArbitraryValue]}],"backdrop-sepia":[{"backdrop-sepia":["",isNumber,isArbitraryVariable,isArbitraryValue]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":G()}],"border-spacing-x":[{"border-spacing-x":G()}],"border-spacing-y":[{"border-spacing-y":G()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",isArbitraryVariable,isArbitraryValue]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[isNumber,"initial",isArbitraryVariable,isArbitraryValue]}],ease:[{ease:["linear","initial",A,isArbitraryVariable,isArbitraryValue]}],delay:[{delay:[isNumber,isArbitraryVariable,isArbitraryValue]}],animate:[{animate:["none",C,isArbitraryVariable,isArbitraryValue]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[E,isArbitraryVariable,isArbitraryValue]}],"perspective-origin":[{"perspective-origin":P()}],rotate:[{rotate:ie()}],"rotate-x":[{"rotate-x":ie()}],"rotate-y":[{"rotate-y":ie()}],"rotate-z":[{"rotate-z":ie()}],scale:[{scale:B()}],"scale-x":[{"scale-x":B()}],"scale-y":[{"scale-y":B()}],"scale-z":[{"scale-z":B()}],"scale-3d":["scale-3d"],skew:[{skew:N()}],"skew-x":[{"skew-x":N()}],"skew-y":[{"skew-y":N()}],transform:[{transform:[isArbitraryVariable,isArbitraryValue,"","none","gpu","cpu"]}],"transform-origin":[{origin:P()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:k()}],"translate-x":[{"translate-x":k()}],"translate-y":[{"translate-y":k()}],"translate-z":[{"translate-z":k()}],"translate-none":["translate-none"],zoom:[{zoom:[isInteger,isArbitraryVariable,isArbitraryValue]}],accent:[{accent:$()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:$()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",isArbitraryVariable,isArbitraryValue]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":$()}],"scrollbar-track-color":[{"scrollbar-track":$()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mbs":[{"scroll-mbs":G()}],"scroll-mbe":[{"scroll-mbe":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pbs":[{"scroll-pbs":G()}],"scroll-pbe":[{"scroll-pbe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",isArbitraryVariable,isArbitraryValue]}],fill:[{fill:["none",...$()]}],"stroke-w":[{stroke:[isNumber,isArbitraryVariableLength,isArbitraryLength,isArbitraryNumber]}],stroke:[{stroke:["none",...$()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},twMerge=createTailwindMerge(getDefaultConfig);function cn(...n){return twMerge(clsx(n))}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;const falsyToString=n=>typeof n=="boolean"?`${n}`:n===0?"0":n,cx=clsx,cva=(n,e)=>t=>{var i;if(e?.variants==null)return cx(n,t?.class,t?.className);const{variants:s,defaultVariants:o}=e,l=Object.keys(s).map(d=>{const p=t?.[d],g=o?.[d];if(p===null)return null;const m=falsyToString(p)||falsyToString(g);return s[d][m]}),u=t&&Object.entries(t).reduce((d,p)=>{let[g,m]=p;return m===void 0||(d[g]=m),d},{}),h=e==null||(i=e.compoundVariants)===null||i===void 0?void 0:i.reduce((d,p)=>{let{class:g,className:m,...v}=p;return Object.entries(v).every(S=>{let[E,x]=S;return Array.isArray(x)?x.includes({...o,...u}[E]):{...o,...u}[E]===x})?[...d,g,m]:d},[]);return cx(n,l,h,t?.class,t?.className)},controlFocusClass="focus:outline-none focus:ring-0 focus-visible:border-ring",interactiveFocusClass="focus:outline-none focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",buttonFocusClass="focus:outline-none focus:ring-0 focus-visible:outline-none",buttonVariants=cva(`inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors ${buttonFocusClass} disabled:pointer-events-none disabled:opacity-50`,{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90 focus-visible:bg-primary/80",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 focus-visible:bg-destructive/80",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground focus-visible:border-ring focus-visible:bg-accent focus-visible:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80 focus-visible:bg-secondary/70",ghost:"hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline focus-visible:underline",subtle:"bg-muted text-muted-foreground hover:bg-muted/80 focus-visible:bg-muted/60"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Button=reactExports.forwardRef(({className:n,variant:e,size:t,asChild:i=!1,...s},o)=>{const l=i?Slot:"button";return jsxRuntimeExports.jsx(l,{className:cn(buttonVariants({variant:e,size:t,className:n})),ref:o,...s})});Button.displayName="Button";const Card=reactExports.forwardRef(({className:n,...e},t)=>jsxRuntimeExports.jsx("div",{ref:t,className:cn("rounded-2xl border border-border/50 bg-card shadow-lg shadow-black/5 transition-all duration-200",n),...e}));Card.displayName="Card";const CardHeader=reactExports.forwardRef(({className:n,...e},t)=>jsxRuntimeExports.jsx("div",{ref:t,className:cn("flex flex-col gap-1 p-6",n),...e}));CardHeader.displayName="CardHeader";const CardTitle=reactExports.forwardRef(({className:n,...e},t)=>jsxRuntimeExports.jsx("h3",{ref:t,className:cn("text-2xl font-semibold tracking-tight",n),...e}));CardTitle.displayName="CardTitle";const CardDescription=reactExports.forwardRef(({className:n,...e},t)=>jsxRuntimeExports.jsx("p",{ref:t,className:cn("text-sm text-muted-foreground",n),...e}));CardDescription.displayName="CardDescription";const CardContent=reactExports.forwardRef(({className:n,...e},t)=>jsxRuntimeExports.jsx("div",{ref:t,className:cn("p-6 pt-0",n),...e}));CardContent.displayName="CardContent";const CardFooter=reactExports.forwardRef(({className:n,...e},t)=>jsxRuntimeExports.jsx("div",{ref:t,className:cn("flex items-center p-6 pt-0",n),...e}));CardFooter.displayName="CardFooter";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:i="standard",host:s="document",lead:o,onClose:l,closeLabel:u,closeOnEscape:h=!0,className:d,contentClassName:p}){const g=reactExports.useRef(null),m=reactExports.useRef(null),v=reactExports.useId();reactExports.useLayoutEffect(()=>{if(n!=="modal"||typeof document>"u")return;m.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const T=g.current;if(T){const F=getFocusable(T);(i==="compact"?T:F[0]??T).focus()}return()=>{m.current?.focus(),m.current=null}},[n,i]),reactExports.useLayoutEffect(()=>{if(n!=="modal"||typeof document>"u")return;const T=F=>{if(F.key==="Escape"){h&&l&&(F.preventDefault(),l());return}if(F.key!=="Tab")return;const P=g.current;if(!P)return;const q=getFocusable(P);if(q.length===0){F.preventDefault(),P.focus();return}const O=document.activeElement,G=q.indexOf(O),fe=F.shiftKey?G<=0?q.length-1:G-1:G===q.length-1?0:G+1;F.preventDefault(),q[fe].focus()};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[h,n,l]);const S=n==="modal"?{role:"dialog","aria-modal":!0,"aria-labelledby":v}:{role:"region","aria-labelledby":v},E=i==="compact",x=s==="window",A=E?"flex min-h-0 flex-1 flex-col overflow-y-auto":"max-h-[min(80vh,48rem)] overflow-y-auto",C=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[E?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h1",{id:v,className:"sr-only",children:e}),n==="modal"&&l&&u?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:l,"aria-label":u,className:"absolute right-2 top-2 z-10",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:v,className:"text-lg font-semibold text-foreground",children:e}),n==="modal"&&l&&u?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:l,"aria-label":u,children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null]}),o?jsxRuntimeExports.jsx("div",{"data-testid":"auth-surface-lead",className:cn(E?"shrink-0 px-5 pt-7 has-[[data-presentation=compact]]:pt-5":"border-b border-border/60 p-4"),children:o}):null,jsxRuntimeExports.jsx(AuthSurfaceBody,{className:cn(A,p),children:t})]});return jsxRuntimeExports.jsx("div",{"data-testid":`auth-surface-${n}`,"data-auth-surface-mode":n,"data-auth-surface-presentation":E?"compact":void 0,"data-auth-surface-host":x?"window":void 0,className:cn(x?"fixed inset-0 z-50 flex items-stretch justify-stretch overflow-hidden bg-card p-0":n==="modal"?cn("fixed inset-0 z-50 flex items-center justify-center p-4",E?"bg-black/50":"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",d),children:x?jsxRuntimeExports.jsx("div",{ref:g,...S,"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:C}):jsxRuntimeExports.jsx(Card,{ref:g,...S,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",E?"h-[400px] w-[280px] max-h-[calc(100dvh-2rem)] max-w-[calc(100vw-2rem)] overflow-hidden rounded-xl border-border/50 shadow-lg shadow-black/5":n==="embedded"?"max-w-none shadow-none":"max-w-lg"),children:C})})}const toKebabCase$1=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),toCamelCase$1=n=>n.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,i)=>i?i.toUpperCase():t.toLowerCase()),toPascalCase$1=n=>{const e=toCamelCase$1(n);return e.charAt(0).toUpperCase()+e.slice(1)},mergeClasses$1=(...n)=>n.filter((e,t,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===t).join(" ").trim(),hasA11yProp$1=n=>{for(const e in n)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var defaultAttributes$1={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Icon$1=reactExports.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:i,className:s="",children:o,iconNode:l,...u},h)=>reactExports.createElement("svg",{ref:h,...defaultAttributes$1,width:e,height:e,stroke:n,strokeWidth:i?Number(t)*24/Number(e):t,className:mergeClasses$1("lucide",s),...!o&&!hasA11yProp$1(u)&&{"aria-hidden":"true"},...u},[...l.map(([d,p])=>reactExports.createElement(d,p)),...Array.isArray(o)?o:[o]]));const createLucideIcon$1=(n,e)=>{const t=reactExports.forwardRef(({className:i,...s},o)=>reactExports.createElement(Icon$1,{ref:o,iconNode:e,className:mergeClasses$1(`lucide-${toKebabCase$1(toPascalCase$1(n))}`,`lucide-${n}`,i),...s}));return t.displayName=toPascalCase$1(n),t};const __iconNode$k=[["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$1=createLucideIcon$1("circle-alert",__iconNode$k);const __iconNode$j=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle$1=createLucideIcon$1("loader-circle",__iconNode$j);const __iconNode$i=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],TriangleAlert=createLucideIcon$1("triangle-alert",__iconNode$i);const __iconNode$h=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],X=createLucideIcon$1("x",__iconNode$h),Input=reactExports.forwardRef(({className:n,type:e="text",...t},i)=>jsxRuntimeExports.jsx("input",{ref:i,type:e,className:cn("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm transition-[border-color] file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",controlFocusClass,n),...t}));Input.displayName="Input";const Label=reactExports.forwardRef(({className:n,...e},t)=>jsxRuntimeExports.jsx("label",{ref:t,className:cn("text-sm font-medium leading-none text-muted-foreground",n),...e}));Label.displayName="Label";const LEGACY_LOGIN_ERROR_DEFAULT_COPY={dismissLabel:"Dismiss"},LEGACY_LOGIN_RESTORING_DEFAULT_COPY={label:"Restoring session…"},LEGACY_LOGIN_CONNECTING_DEFAULT_COPY={title:"Connecting…",detail:"Waiting for the provider",cancelLabel:"Cancel"},LEGACY_LOGIN_ACCOUNT_DEFAULT_COPY={expiredTitle:"Session expired",enterLabel:"Continue",switchLabel:"Switch account"},LEGACY_LOGIN_FAILURE_DEFAULT_COPY={title:"Sign-in failed",primaryLabel:"Retry",secondaryLabel:"Back"};function legacyLoginLabel(n,e){return n?.trim()?n:e}function LoginErrorBanner({error:n,onDismiss:e,dismissLabel:t}){if(!n)return null;const i=legacyLoginLabel(t,LEGACY_LOGIN_ERROR_DEFAULT_COPY.dismissLabel);return jsxRuntimeExports.jsxs("div",{role:"alert",className:"mx-5 mb-3 flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2",children:[jsxRuntimeExports.jsx(CircleAlert$1,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive","aria-hidden":"true"}),jsxRuntimeExports.jsx("p",{className:"flex-1 text-xs leading-relaxed text-destructive",children:n}),e?jsxRuntimeExports.jsx("button",{type:"button","aria-label":i,onClick:e,className:cn("shrink-0 cursor-pointer text-destructive/60 hover:text-destructive",interactiveFocusClass),children:jsxRuntimeExports.jsx(X,{className:"h-3.5 w-3.5","aria-hidden":"true"})}):null]})}function LoginAvatar({name:n,avatarUrl:e,size:t="lg",marker:i}){const s=t==="lg"?"h-16 w-16 text-xl":"h-10 w-10 text-sm";return jsxRuntimeExports.jsxs("div",{className:"relative shrink-0",children:[e?jsxRuntimeExports.jsx("img",{src:e,alt:n,className:cn(s,"rounded-[18%] border border-border/50 object-cover shadow-sm")}):jsxRuntimeExports.jsx("div",{"aria-hidden":"true",className:cn(s,"flex items-center justify-center rounded-[18%] bg-primary/10 font-semibold text-primary shadow-sm"),children:n.slice(0,1).toUpperCase()}),i?jsxRuntimeExports.jsx("div",{className:"absolute -bottom-1 -right-1",children:i}):null]})}function LoginRestoringView({accountName:n,avatarUrl:e,label:t}){const i=legacyLoginLabel(t,LEGACY_LOGIN_RESTORING_DEFAULT_COPY.label);return jsxRuntimeExports.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-4 p-6",role:"status",children:[n?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoginAvatar,{name:n,avatarUrl:e,size:"lg"}),jsxRuntimeExports.jsx("p",{className:"text-sm font-medium text-foreground",children:n})]}):null,jsxRuntimeExports.jsx(LoaderCircle$1,{className:"h-6 w-6 animate-spin text-muted-foreground","aria-hidden":"true"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:i})]})}function LoginConnectingView({title:n,detail:e,providerLabel:t,providerHost:i,onCancel:s,cancelLabel:o}){const l=legacyLoginLabel(n,LEGACY_LOGIN_CONNECTING_DEFAULT_COPY.title),u=legacyLoginLabel(e,LEGACY_LOGIN_CONNECTING_DEFAULT_COPY.detail),h=legacyLoginLabel(o,LEGACY_LOGIN_CONNECTING_DEFAULT_COPY.cancelLabel);return jsxRuntimeExports.jsxs("div",{className:"flex h-full flex-1 flex-col",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-6 py-8 text-center",role:"status",children:[jsxRuntimeExports.jsx(LoaderCircle$1,{className:"mb-4 h-8 w-8 animate-spin text-primary","aria-hidden":"true"}),jsxRuntimeExports.jsx("p",{className:"text-sm font-medium text-foreground",children:l}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:u}),t||i?jsxRuntimeExports.jsxs("div",{className:"mt-4 w-full max-w-[18rem] rounded-lg border border-border/60 bg-muted/30 px-3 py-2",children:[t?jsxRuntimeExports.jsx("p",{className:"truncate text-xs font-medium text-foreground",children:t}):null,i?jsxRuntimeExports.jsx("p",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:i}):null]}):null]}),s?jsxRuntimeExports.jsx("div",{className:"shrink-0 px-5 pb-5",children:jsxRuntimeExports.jsx("button",{type:"button",onClick:s,className:cn("h-9 w-full cursor-pointer rounded-md text-xs text-muted-foreground transition-colors hover:bg-muted/40 hover:text-foreground",interactiveFocusClass),children:h})}):null]})}function LoginAccountView({name:n,avatarUrl:e,bindingLabel:t,expired:i=!1,expiredTitle:s,expiredDescription:o,enterLabel:l,switchLabel:u,error:h,onDismissError:d,dismissErrorLabel:p,onEnter:g,onSwitchAccount:m,onReauthenticate:v}){const S=legacyLoginLabel(s,LEGACY_LOGIN_ACCOUNT_DEFAULT_COPY.expiredTitle),E=legacyLoginLabel(l,LEGACY_LOGIN_ACCOUNT_DEFAULT_COPY.enterLabel),x=legacyLoginLabel(u,LEGACY_LOGIN_ACCOUNT_DEFAULT_COPY.switchLabel);return jsxRuntimeExports.jsxs("div",{className:"flex h-full flex-1 flex-col",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-4 px-5 py-8",children:[i?jsxRuntimeExports.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full border border-primary/20 bg-primary/5 px-2.5 py-1 text-[11px] font-medium text-primary",children:[jsxRuntimeExports.jsx(CircleAlert$1,{className:"h-3.5 w-3.5","aria-hidden":"true"}),S]}):null,jsxRuntimeExports.jsx(LoginAvatar,{name:n,avatarUrl:e,size:"lg"}),jsxRuntimeExports.jsxs("div",{className:"space-y-1 text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-base font-semibold text-foreground",children:n}),t?jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:t}):null]}),i&&o?jsxRuntimeExports.jsx("p",{className:"max-w-[18rem] text-center text-xs leading-5 text-muted-foreground",children:o}):null]}),i?null:jsxRuntimeExports.jsx(LoginErrorBanner,{error:h,onDismiss:d,dismissLabel:p}),jsxRuntimeExports.jsxs("div",{className:"shrink-0 space-y-2 px-5 pb-5 pt-2",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:i&&v?v:g,className:cn("h-10 w-full cursor-pointer rounded-xl bg-primary text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:bg-primary/80",buttonFocusClass),children:E}),m?jsxRuntimeExports.jsx("button",{type:"button",onClick:m,className:cn("h-9 w-full cursor-pointer rounded-lg text-xs text-muted-foreground transition-colors hover:bg-muted/40 hover:text-foreground focus-visible:bg-muted/40 focus-visible:text-foreground",buttonFocusClass),children:x}):null]})]})}function LoginFailureView({title:n,description:e,primaryLabel:t,onPrimary:i,secondaryLabel:s,onSecondary:o}){const l=legacyLoginLabel(n,LEGACY_LOGIN_FAILURE_DEFAULT_COPY.title),u=legacyLoginLabel(t,LEGACY_LOGIN_FAILURE_DEFAULT_COPY.primaryLabel),h=legacyLoginLabel(s,LEGACY_LOGIN_FAILURE_DEFAULT_COPY.secondaryLabel);return jsxRuntimeExports.jsxs("div",{className:"flex h-full flex-1 flex-col",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 px-6 pb-5 pt-7 text-center",children:[jsxRuntimeExports.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-destructive/10",children:jsxRuntimeExports.jsx(TriangleAlert,{className:"h-6 w-6 text-destructive","aria-hidden":"true"})}),jsxRuntimeExports.jsx("p",{className:"text-base font-semibold text-foreground",children:l}),e?jsxRuntimeExports.jsx("p",{className:"max-w-[19rem] text-sm leading-6 text-muted-foreground",role:"alert",children:e}):null]}),jsxRuntimeExports.jsxs("div",{className:"shrink-0 space-y-2 px-4 pb-5",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:i,className:cn("h-9 w-full cursor-pointer rounded-md bg-primary text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:bg-primary/80 disabled:cursor-not-allowed disabled:opacity-50",buttonFocusClass),children:u}),o?jsxRuntimeExports.jsx("button",{type:"button",onClick:o,className:cn("h-9 w-full cursor-pointer rounded-md border border-border/60 bg-muted/30 text-sm font-medium text-foreground transition-colors hover:bg-muted/50 focus-visible:border-ring focus-visible:bg-muted/50",buttonFocusClass),children:h}):null]})]})}var __defProp=Object.defineProperty,__name=(n,e)=>__defProp(n,"name",{value:e,configurable:!0}),DEFAULT_ORIENTATION="horizontal",ORIENTATIONS=["horizontal","vertical"],Separator$1=reactExports.forwardRef(__name(function(e,t){const{decorative:i,orientation:s=DEFAULT_ORIENTATION,...o}=e,l=isValidOrientation(s)?s:DEFAULT_ORIENTATION,h=i?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return jsxRuntimeExports.jsx(Primitive.div,{"data-orientation":l,...h,...o,ref:t})},"Separator"));function isValidOrientation(n){return ORIENTATIONS.includes(n)}__name(isValidOrientation,"isValidOrientation");var Root=Separator$1;const Separator=reactExports.forwardRef(({className:n,orientation:e="horizontal",decorative:t=!0,...i},s)=>jsxRuntimeExports.jsx(Root,{ref:s,decorative:t,orientation:e,className:cn("shrink-0 bg-border",e==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",n),...i}));Separator.displayName=Root.displayName;const TOAST_DEFAULT_DURATION=3e3,toastVariants=cva("pointer-events-auto relative flex w-full items-start justify-between gap-3 overflow-hidden rounded-md border px-4 py-3 text-sm shadow-lg transition-opacity",{variants:{variant:{default:"border-border bg-background text-foreground",destructive:"border-destructive/30 bg-destructive/10 text-destructive",success:"border-green-500/20 bg-green-500/15 text-green-600"}},defaultVariants:{variant:"default"}});let count=0,entries=[];const listeners=new Set;function emit(){for(const n of listeners)n()}function removeToast(n){const e=entries.findIndex(t=>t.id===n);e<0||(clearTimeout(entries[e].timer),entries=entries.filter(t=>t.id!==n),emit())}function dismissToast(n){removeToast(n)}function toast(n){count=(count+1)%Number.MAX_SAFE_INTEGER;const e=count.toString(),t=n.duration??TOAST_DEFAULT_DURATION,i={id:e,title:n.title,description:n.description,variant:n.variant??"default",className:n.className,timer:setTimeout(()=>removeToast(e),t)};return entries=[...entries.slice(-2),i],emit(),e}function subscribe(n){return listeners.add(n),()=>{listeners.delete(n)}}function getSnapshot(){return entries}function Toaster({className:n}){const e=reactExports.useSyncExternalStore(subscribe,getSnapshot,getSnapshot);return jsxRuntimeExports.jsx("div",{"aria-live":"polite",role:"status",className:cn("pointer-events-none fixed bottom-4 right-4 z-[100] flex w-full max-w-sm flex-col gap-2",n),children:e.map(t=>jsxRuntimeExports.jsxs("div",{className:cn(toastVariants({variant:t.variant}),t.className),children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[t.title?jsxRuntimeExports.jsx("p",{className:"font-medium",children:t.title}):null,t.description?jsxRuntimeExports.jsx("p",{className:cn(t.title?"mt-0.5":void 0),children:t.description}):null]}),jsxRuntimeExports.jsx("button",{type:"button","aria-label":"关闭通知",className:cn("shrink-0 rounded-sm opacity-60 transition-opacity hover:opacity-100",interactiveFocusClass),onClick:()=>dismissToast(t.id),children:jsxRuntimeExports.jsx(X,{"aria-hidden":"true",className:"h-3.5 w-3.5"})})]},t.id))})}function WebIdLoginEntryView({copy:n,logo:e,pending:t=!1,error:i,onStart:s}){return jsxRuntimeExports.jsxs("div",{"data-testid":"webid-login-entry",className:"flex h-full min-h-0 flex-1 flex-col px-5 pb-5 pt-7",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-4 text-center",children:[e?jsxRuntimeExports.jsx("div",{className:"flex items-center justify-center",children:e}):null,n.title||n.description?jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[n.title?jsxRuntimeExports.jsx("h2",{className:"text-lg font-semibold text-foreground",children:n.title}):null,n.description?jsxRuntimeExports.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:n.description}):null]}):null,i?jsxRuntimeExports.jsx("p",{role:"alert",className:"max-w-[15rem] text-sm leading-5 text-destructive",children:i}):null]}),jsxRuntimeExports.jsxs(Button,{type:"button",className:"h-10 w-full shrink-0 rounded-xl",disabled:t,"aria-busy":t,onClick:()=>{s()},children:[t?jsxRuntimeExports.jsx(LoaderCircle$1,{"aria-hidden":"true",className:"mr-2 h-4 w-4 animate-spin"}):null,t?n.pendingLabel:n.startLabel]})]})}var ABSOLUTE_URL_REGEX=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,PROTOCOL_RELATIVE_URL_REGEX=/^[\\/]{2}/;function normalizeProtocolRelativeUrl(n,e){return e+n.replace(/\\/g,"/")}var PopStateEventType="popstate";function isLocation(n){return typeof n=="object"&&n!=null&&"pathname"in n&&"search"in n&&"hash"in n&&"state"in n&&"key"in n}function createBrowserHistory(n={}){function e(i,s){let o=s.state?.masked,{pathname:l,search:u,hash:h}=o||i.location;return createLocation("",{pathname:l,search:u,hash:h},s.state&&s.state.usr||null,s.state&&s.state.key||"default",o?{pathname:i.location.pathname,search:i.location.search,hash:i.location.hash}:void 0)}function t(i,s){return typeof s=="string"?s:createPath(s)}return getUrlBasedHistory(e,t,null,n)}function invariant(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function warning(n,e){if(!n){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function createKey(){return Math.random().toString(36).substring(2,10)}function getHistoryState(n,e){return{usr:n.state,key:n.key,idx:e,masked:n.mask?{pathname:n.pathname,search:n.search,hash:n.hash}:void 0}}function createLocation(n,e,t=null,i,s){return{pathname:typeof n=="string"?n:n.pathname,search:"",hash:"",...typeof e=="string"?parsePath(e):e,state:t,key:e&&e.key||i||createKey(),mask:s}}function createPath({pathname:n="/",search:e="",hash:t=""}){return e&&e!=="?"&&(n+=e.charAt(0)==="?"?e:"?"+e),t&&t!=="#"&&(n+=t.charAt(0)==="#"?t:"#"+t),n}function parsePath(n){let e={};if(n){let t=n.indexOf("#");t>=0&&(e.hash=n.substring(t),n=n.substring(0,t));let i=n.indexOf("?");i>=0&&(e.search=n.substring(i),n=n.substring(0,i)),n&&(e.pathname=n)}return e}function getUrlBasedHistory(n,e,t,i={}){let{window:s=document.defaultView,v5Compat:o=!1}=i,l=s.history,u="POP",h=null,d=p();d==null&&(d=0,l.replaceState({...l.state,idx:d},""));function p(){return(l.state||{idx:null}).idx}function g(){u="POP";let x=p(),A=x==null?null:x-d;d=x,h&&h({action:u,location:E.location,delta:A})}function m(x,A){u="PUSH";let C=isLocation(x)?x:createLocation(E.location,x,A);d=p()+1;let T=getHistoryState(C,d),F=E.createHref(C.mask||C);try{l.pushState(T,"",F)}catch(P){if(P instanceof DOMException&&P.name==="DataCloneError")throw P;s.location.assign(F)}o&&h&&h({action:u,location:E.location,delta:1})}function v(x,A){u="REPLACE";let C=isLocation(x)?x:createLocation(E.location,x,A);d=p();let T=getHistoryState(C,d),F=E.createHref(C.mask||C);l.replaceState(T,"",F),o&&h&&h({action:u,location:E.location,delta:0})}function S(x){return createBrowserURLImpl(s,x)}let E={get action(){return u},get location(){return n(s,l)},listen(x){if(h)throw new Error("A history only accepts one active listener");return s.addEventListener(PopStateEventType,g),h=x,()=>{s.removeEventListener(PopStateEventType,g),h=null}},createHref(x){return e(s,x)},createURL:S,encodeLocation(x){let A=S(x);return{pathname:A.pathname,search:A.search,hash:A.hash}},push:m,replace:v,go(x){return l.go(x)}};return E}function createBrowserURLImpl(n,e,t=!1){let i="http://localhost";n&&(i=n.location.origin!=="null"?n.location.origin:n.location.href),invariant(i,"No window.location.(origin|href) available to create URL");let s=typeof e=="string"?e:createPath(e);return s=s.replace(/ $/,"%20"),!t&&PROTOCOL_RELATIVE_URL_REGEX.test(s)&&(s=i+s),new URL(s,i)}function matchRoutes(n,e,t="/"){return matchRoutesImpl(n,e,t,!1)}function matchRoutesImpl(n,e,t,i,s){let o=typeof e=="string"?parsePath(e):e,l=stripBasename(o.pathname||"/",t);if(l==null)return null;let u=flattenAndRankRoutes(n),h=null,d=decodePath(l);for(let p=0;h==null&&p<u.length;++p)h=matchRouteBranch(u[p],d,i);return h}function flattenAndRankRoutes(n){let e=flattenRoutes(n);return rankRouteBranches(e),e}function flattenRoutes(n,e=[],t=[],i="",s=!1){let o=(l,u,h=s,d)=>{let p={relativePath:d===void 0?l.path||"":d,caseSensitive:l.caseSensitive===!0,childrenIndex:u,route:l};if(p.relativePath.startsWith("/")){if(!p.relativePath.startsWith(i)&&h)return;invariant(p.relativePath.startsWith(i),`Absolute route path "${p.relativePath}" nested under path "${i}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),p.relativePath=p.relativePath.slice(i.length)}let g=joinPaths([i,p.relativePath]),m=t.concat(p);l.children&&l.children.length>0&&(invariant(l.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${g}".`),flattenRoutes(l.children,e,m,g,h)),!(l.path==null&&!l.index)&&e.push({path:g,score:computeScore(g,l.index),routesMeta:m.map((v,S)=>{let[E,x]=compilePath(v.relativePath,v.caseSensitive,S===m.length-1);return{...v,matcher:E,compiledParams:x}})})};return n.forEach((l,u)=>{if(l.path===""||!l.path?.includes("?"))o(l,u);else for(let h of explodeOptionalSegments(l.path))o(l,u,!0,h)}),e}function explodeOptionalSegments(n){let e=n.split("/");if(e.length===0)return[];let[t,...i]=e,s=t.endsWith("?"),o=t.replace(/\?$/,"");if(i.length===0)return s?[o,""]:[o];let l=explodeOptionalSegments(i.join("/")),u=[];return u.push(...l.map(h=>h===""?o:[o,h].join("/"))),s&&u.push(...l),u.map(h=>n.startsWith("/")&&h===""?"/":h)}function rankRouteBranches(n){n.sort((e,t)=>e.score!==t.score?t.score-e.score:compareIndexes(e.routesMeta.map(i=>i.childrenIndex),t.routesMeta.map(i=>i.childrenIndex)))}var paramRe=/^:[\w-]+$/,dynamicSegmentValue=3,indexRouteValue=2,emptySegmentValue=1,staticSegmentValue=10,splatPenalty=-2,isSplat=n=>n==="*";function computeScore(n,e){let t=n.split("/"),i=t.length;return t.some(isSplat)&&(i+=splatPenalty),e&&(i+=indexRouteValue),t.filter(s=>!isSplat(s)).reduce((s,o)=>s+(paramRe.test(o)?dynamicSegmentValue:o===""?emptySegmentValue:staticSegmentValue),i)}function compareIndexes(n,e){return n.length===e.length&&n.slice(0,-1).every((i,s)=>i===e[s])?n[n.length-1]-e[e.length-1]:0}function matchRouteBranch(n,e,t=!1){let{routesMeta:i}=n,s={},o="/",l=[];for(let u=0;u<i.length;++u){let h=i[u],d=u===i.length-1,p=o==="/"?e:e.slice(o.length)||"/",g={path:h.relativePath,caseSensitive:h.caseSensitive,end:d},m=h.matcher&&h.compiledParams?matchPathImpl(g,p,h.matcher,h.compiledParams):matchPath(g,p),v=h.route;if(!m&&d&&t&&!i[i.length-1].route.index&&(m=matchPath({path:h.relativePath,caseSensitive:h.caseSensitive,end:!1},p)),!m)return null;Object.assign(s,m.params),l.push({params:s,pathname:joinPaths([o,m.pathname]),pathnameBase:normalizePathname(joinPaths([o,m.pathnameBase])),route:v}),m.pathnameBase!=="/"&&(o=joinPaths([o,m.pathnameBase]))}return l}function matchPath(n,e){typeof n=="string"&&(n={path:n,caseSensitive:!1,end:!0});let[t,i]=compilePath(n.path,n.caseSensitive,n.end);return matchPathImpl(n,e,t,i)}function matchPathImpl(n,e,t,i){let s=e.match(t);if(!s)return null;let o=s[0],l=o.replace(/(.)\/+$/,"$1"),u=s.slice(1);return{params:i.reduce((d,{paramName:p,isOptional:g},m)=>{if(p==="*"){let S=u[m]||"";l=o.slice(0,o.length-S.length).replace(/(.)\/+$/,"$1")}const v=u[m];return g&&!v?d[p]=void 0:d[p]=(v||"").replace(/%2F/g,"/"),d},{}),pathname:o,pathnameBase:l,pattern:n}}function compilePath(n,e=!1,t=!0){warning(n==="*"||!n.endsWith("*")||n.endsWith("/*"),`Route path "${n}" will be treated as if it were "${n.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${n.replace(/\*$/,"/*")}".`);let i=[],s="^"+n.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,u,h,d,p)=>{if(i.push({paramName:u,isOptional:h!=null}),h){let g=p.charAt(d+l.length);return g&&g!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return n.endsWith("*")?(i.push({paramName:"*"}),s+=n==="*"||n==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):t?s+="\\/*$":n!==""&&n!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,e?void 0:"i"),i]}function decodePath(n){try{return n.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return warning(!1,`The URL path "${n}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${e}).`),n}}function stripBasename(n,e){if(e==="/")return n;if(!n.toLowerCase().startsWith(e.toLowerCase()))return null;let t=e.endsWith("/")?e.length-1:e.length,i=n.charAt(t);return i&&i!=="/"?null:n.slice(t)||"/"}function resolvePath(n,e="/"){let{pathname:t,search:i="",hash:s=""}=typeof n=="string"?parsePath(n):n,o;return t?(t=removeDoubleSlashes(t),t.startsWith("/")?o=resolvePathname(t.substring(1),"/"):o=resolvePathname(t,e)):o=e,{pathname:o,search:normalizeSearch(i),hash:normalizeHash(s)}}function resolvePathname(n,e){let t=removeTrailingSlash(e).split("/");return n.split("/").forEach(s=>{s===".."?t.length>1&&t.pop():s!=="."&&t.push(s)}),t.length>1?t.join("/"):"/"}function getInvalidPathError(n,e,t,i){return`Cannot include a '${n}' character in a manually specified \`to.${e}\` field [${JSON.stringify(i)}]. Please separate it out to the \`to.${t}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function getPathContributingMatches(n){return n.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function getResolveToMatches(n){let e=getPathContributingMatches(n);return e.map((t,i)=>i===e.length-1?t.pathname:t.pathnameBase)}function resolveTo(n,e,t,i=!1){let s;typeof n=="string"?s=parsePath(n):(s={...n},invariant(!s.pathname||!s.pathname.includes("?"),getInvalidPathError("?","pathname","search",s)),invariant(!s.pathname||!s.pathname.includes("#"),getInvalidPathError("#","pathname","hash",s)),invariant(!s.search||!s.search.includes("#"),getInvalidPathError("#","search","hash",s)));let o=n===""||s.pathname==="",l=o?"/":s.pathname,u;if(l==null)u=t;else{let g=e.length-1;if(!i&&l.startsWith("..")){let m=l.split("/");for(;m[0]==="..";)m.shift(),g-=1;s.pathname=m.join("/")}u=g>=0?e[g]:"/"}let h=resolvePath(s,u),d=l&&l!=="/"&&l.endsWith("/"),p=(o||l===".")&&t.endsWith("/");return!h.pathname.endsWith("/")&&(d||p)&&(h.pathname+="/"),h}var removeDoubleSlashes=n=>n.replace(/[\\/]{2,}/g,"/"),joinPaths=n=>removeDoubleSlashes(n.join("/")),removeTrailingSlash=n=>n.replace(/\/+$/,""),normalizePathname=n=>removeTrailingSlash(n).replace(/^\/*/,"/"),normalizeSearch=n=>!n||n==="?"?"":n.startsWith("?")?n:"?"+n,normalizeHash=n=>!n||n==="#"?"":n.startsWith("#")?n:"#"+n,ErrorResponseImpl=class{constructor(n,e,t,i=!1){this.status=n,this.statusText=e||"",this.internal=i,t instanceof Error?(this.data=t.toString(),this.error=t):this.data=t}};function isRouteErrorResponse(n){return n!=null&&typeof n.status=="number"&&typeof n.statusText=="string"&&typeof n.internal=="boolean"&&"data"in n}function getRoutePattern(n){let e=n.map(t=>t.route.path).filter(Boolean);return joinPaths(e)||"/"}var isBrowser$1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function parseToInfo(n,e){let t=n;if(typeof t!="string"||!ABSOLUTE_URL_REGEX.test(t))return{absoluteURL:void 0,isExternal:!1,to:t};let i=t,s=!1;if(isBrowser$1)try{let o=new URL(window.location.href),l=PROTOCOL_RELATIVE_URL_REGEX.test(t)?new URL(normalizeProtocolRelativeUrl(t,o.protocol)):new URL(t),u=stripBasename(l.pathname,e);l.origin===o.origin&&u!=null?t=u+l.search+l.hash:s=!0}catch{warning(!1,`<Link to="${t}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:i,isExternal:s,to:t}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var validMutationMethodsArr=["POST","PUT","PATCH","DELETE"];new Set(validMutationMethodsArr);var validRequestMethodsArr=["GET",...validMutationMethodsArr];new Set(validRequestMethodsArr);var invalidProtocols=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];function hasInvalidProtocol(n){try{return invalidProtocols.includes(new URL(n).protocol)}catch{return!1}}var DataRouterContext=reactExports.createContext(null);DataRouterContext.displayName="DataRouter";var DataRouterStateContext=reactExports.createContext(null);DataRouterStateContext.displayName="DataRouterState";var RSCRouterContext=reactExports.createContext(!1);function useIsRSCRouterContext(){return reactExports.useContext(RSCRouterContext)}var ViewTransitionContext=reactExports.createContext({isTransitioning:!1});ViewTransitionContext.displayName="ViewTransition";var FetchersContext=reactExports.createContext(new Map);FetchersContext.displayName="Fetchers";var AwaitContext=reactExports.createContext(null);AwaitContext.displayName="Await";var NavigationContext=reactExports.createContext(null);NavigationContext.displayName="Navigation";var LocationContext=reactExports.createContext(null);LocationContext.displayName="Location";var RouteContext=reactExports.createContext({outlet:null,matches:[],isDataRoute:!1});RouteContext.displayName="Route";var RouteErrorContext=reactExports.createContext(null);RouteErrorContext.displayName="RouteError";var ERROR_DIGEST_BASE="REACT_ROUTER_ERROR",ERROR_DIGEST_REDIRECT="REDIRECT",ERROR_DIGEST_ROUTE_ERROR_RESPONSE="ROUTE_ERROR_RESPONSE";function decodeRedirectErrorDigest(n){if(n.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:{`))try{let e=JSON.parse(n.slice(28));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.location=="string"&&typeof e.reloadDocument=="boolean"&&typeof e.replace=="boolean")return e}catch{}}function decodeRouteErrorResponseDigest(n){if(n.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:{`))try{let e=JSON.parse(n.slice(40));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string")return new ErrorResponseImpl(e.status,e.statusText,e.data)}catch{}}function useHref(n,{relative:e}={}){invariant(useInRouterContext(),"useHref() may be used only in the context of a <Router> component.");let{basename:t,navigator:i}=reactExports.useContext(NavigationContext),{hash:s,pathname:o,search:l}=useResolvedPath(n,{relative:e}),u=o;return t!=="/"&&(u=o==="/"?t:joinPaths([t,o])),i.createHref({pathname:u,search:l,hash:s})}function useInRouterContext(){return reactExports.useContext(LocationContext)!=null}function useLocation(){return invariant(useInRouterContext(),"useLocation() may be used only in the context of a <Router> component."),reactExports.useContext(LocationContext).location}var navigateEffectWarning="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function useIsomorphicLayoutEffect(n){reactExports.useContext(NavigationContext).static||reactExports.useLayoutEffect(n)}function useNavigate(){let{isDataRoute:n}=reactExports.useContext(RouteContext);return n?useNavigateStable():useNavigateUnstable()}function useNavigateUnstable(){invariant(useInRouterContext(),"useNavigate() may be used only in the context of a <Router> component.");let n=reactExports.useContext(DataRouterContext),{basename:e,navigator:t}=reactExports.useContext(NavigationContext),{matches:i}=reactExports.useContext(RouteContext),{pathname:s}=useLocation(),o=JSON.stringify(getResolveToMatches(i)),l=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{l.current=!0}),reactExports.useCallback((h,d={})=>{if(warning(l.current,navigateEffectWarning),!l.current)return;if(typeof h=="number"){t.go(h);return}let p=resolveTo(h,JSON.parse(o),s,d.relative==="path");n==null&&e!=="/"&&(p.pathname=p.pathname==="/"?e:joinPaths([e,p.pathname])),(d.replace?t.replace:t.push)(p,d.state,d)},[e,t,o,s,n])}var OutletContext=reactExports.createContext(null);function useOutlet(n){let e=reactExports.useContext(RouteContext).outlet;return reactExports.useMemo(()=>e&&reactExports.createElement(OutletContext.Provider,{value:n},e),[e,n])}function useResolvedPath(n,{relative:e}={}){let{matches:t}=reactExports.useContext(RouteContext),{pathname:i}=useLocation(),s=JSON.stringify(getResolveToMatches(t));return reactExports.useMemo(()=>resolveTo(n,JSON.parse(s),i,e==="path"),[n,s,i,e])}function useRoutes(n,e){return useRoutesImpl(n)}function useRoutesImpl(n,e,t){invariant(useInRouterContext(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:i}=reactExports.useContext(NavigationContext),{matches:s}=reactExports.useContext(RouteContext),o=s[s.length-1],l=o?o.params:{},u=o?o.pathname:"/",h=o?o.pathnameBase:"/",d=o&&o.route;{let x=d&&d.path||"";warningOnce(u,!d||x.endsWith("*")||x.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${u}" (under <Route path="${x}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
11
11
 
12
- Please change the parent <Route path="${x}"> to <Route path="${x==="/"?"*":`${x}/*`}">.`)}let p=useLocation(),g;g=p;let m=g.pathname||"/",v=m;if(h!=="/"){let x=h.replace(/^\//,"").split("/");v="/"+m.replace(/^\//,"").split("/").slice(x.length).join("/")}let S=t&&t.state.matches.length?t.state.matches.map(x=>Object.assign(x,{route:t.manifest[x.route.id]||x.route})):matchRoutes(n,{pathname:v});return warning(d||S!=null,`No routes matched location "${g.pathname}${g.search}${g.hash}" `),warning(S==null||S[S.length-1].route.element!==void 0||S[S.length-1].route.Component!==void 0||S[S.length-1].route.lazy!==void 0,`Matched leaf route at location "${g.pathname}${g.search}${g.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`),_renderMatches(S&&S.map(x=>Object.assign({},x,{params:Object.assign({},l,x.params),pathname:joinPaths([h,i.encodeLocation?i.encodeLocation(x.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:x.pathname]),pathnameBase:x.pathnameBase==="/"?h:joinPaths([h,i.encodeLocation?i.encodeLocation(x.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:x.pathnameBase])})),s,t)}function DefaultErrorComponent(){let n=useRouteError(),e=isRouteErrorResponse(n)?`${n.status} ${n.statusText}`:n instanceof Error?n.message:JSON.stringify(n),t=n instanceof Error?n.stack:null,i="rgba(200,200,200, 0.5)",s={padding:"0.5rem",backgroundColor:i},o={padding:"2px 4px",backgroundColor:i},l=null;return console.error("Error handled by React Router default ErrorBoundary:",n),l=reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("p",null,"💿 Hey developer 👋"),reactExports.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",reactExports.createElement("code",{style:o},"ErrorBoundary")," or"," ",reactExports.createElement("code",{style:o},"errorElement")," prop on your route.")),reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("h2",null,"Unexpected Application Error!"),reactExports.createElement("h3",{style:{fontStyle:"italic"}},e),t?reactExports.createElement("pre",{style:s},t):null,l)}var defaultErrorElement=reactExports.createElement(DefaultErrorComponent,null),RenderErrorBoundary=class extends reactExports.Component{constructor(n){super(n),this.state={location:n.location,revalidation:n.revalidation,error:n.error}}static getDerivedStateFromError(n){return{error:n}}static getDerivedStateFromProps(n,e){return e.location!==n.location||e.revalidation!=="idle"&&n.revalidation==="idle"?{error:n.error,location:n.location,revalidation:n.revalidation}:{error:n.error!==void 0?n.error:e.error,location:e.location,revalidation:n.revalidation||e.revalidation}}componentDidCatch(n,e){this.props.onError?this.props.onError(n,e):console.error("React Router caught the following error during render",n)}render(){let n=this.state.error;if(this.context&&typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){const t=decodeRouteErrorResponseDigest(n.digest);t&&(n=t)}let e=n!==void 0?reactExports.createElement(RouteContext.Provider,{value:this.props.routeContext},reactExports.createElement(RouteErrorContext.Provider,{value:n,children:this.props.component})):this.props.children;return this.context?reactExports.createElement(RSCErrorHandler,{error:n},e):e}};RenderErrorBoundary.contextType=RSCRouterContext;var errorRedirectHandledMap=new WeakMap;function RSCErrorHandler({children:n,error:e}){let{basename:t}=reactExports.useContext(NavigationContext);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let i=decodeRedirectErrorDigest(e.digest);if(i){let s=errorRedirectHandledMap.get(e);if(s)throw s;let o=parseToInfo(i.location,t),l=o.absoluteURL||o.to;if(hasInvalidProtocol(l))throw new Error("Invalid redirect location");if(isBrowser$1&&!errorRedirectHandledMap.get(e))if(o.isExternal||i.reloadDocument)window.location.href=l;else{const u=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(o.to,{replace:i.replace}));throw errorRedirectHandledMap.set(e,u),u}return reactExports.createElement("meta",{httpEquiv:"refresh",content:`0;url=${l}`})}}return n}function RenderedRoute({routeContext:n,match:e,children:t}){let i=reactExports.useContext(DataRouterContext);return i&&i.static&&i.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=e.route.id),reactExports.createElement(RouteContext.Provider,{value:n},t)}function _renderMatches(n,e=[],t){let i=t?.state;if(n==null){if(!i)return null;if(i.errors)n=i.matches;else if(e.length===0&&!i.initialized&&i.matches.length>0)n=i.matches;else return null}let s=n,o=i?.errors;if(o!=null){let p=s.findIndex(g=>g.route.id&&o?.[g.route.id]!==void 0);invariant(p>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(",")}`),s=s.slice(0,Math.min(s.length,p+1))}let l=!1,u=-1;if(t&&i){l=i.renderFallback;for(let p=0;p<s.length;p++){let g=s[p];if((g.route.HydrateFallback||g.route.hydrateFallbackElement)&&(u=p),g.route.id){let{loaderData:m,errors:v}=i,S=g.route.loader&&!m.hasOwnProperty(g.route.id)&&(!v||v[g.route.id]===void 0);if(g.route.lazy||S){t.isStatic&&(l=!0),u>=0?s=s.slice(0,u+1):s=[s[0]];break}}}}let h=t?.onError,d=i&&h?(p,g)=>{h(p,{location:i.location,params:i.matches?.[0]?.params??{},pattern:getRoutePattern(i.matches),errorInfo:g})}:void 0;return s.reduceRight((p,g,m)=>{let v,S=!1,E=null,x=null;i&&(v=o&&g.route.id?o[g.route.id]:void 0,E=g.route.errorElement||defaultErrorElement,l&&(u<0&&m===0?(warningOnce("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),S=!0,x=null):u===m&&(S=!0,x=g.route.hydrateFallbackElement||null)));let A=e.concat(s.slice(0,m+1)),C=()=>{let T;return v?T=E:S?T=x:g.route.Component?T=reactExports.createElement(g.route.Component,null):g.route.element?T=g.route.element:T=p,reactExports.createElement(RenderedRoute,{match:g,routeContext:{outlet:p,matches:A,isDataRoute:i!=null},children:T})};return i&&(g.route.ErrorBoundary||g.route.errorElement||m===0)?reactExports.createElement(RenderErrorBoundary,{location:i.location,revalidation:i.revalidation,component:E,error:v,children:C(),routeContext:{outlet:null,matches:A,isDataRoute:!0},onError:d}):C()},null)}function getDataRouterConsoleError(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError(n)),e}function useDataRouterState(n){let e=reactExports.useContext(DataRouterStateContext);return invariant(e,getDataRouterConsoleError(n)),e}function useRouteContext(n){let e=reactExports.useContext(RouteContext);return invariant(e,getDataRouterConsoleError(n)),e}function useCurrentRouteId(n){let e=useRouteContext(n),t=e.matches[e.matches.length-1];return invariant(t.route.id,`${n} can only be used on routes that contain a unique "id"`),t.route.id}function useRouteId(){return useCurrentRouteId("useRouteId")}function useRouteError(){let n=reactExports.useContext(RouteErrorContext),e=useDataRouterState("useRouteError"),t=useCurrentRouteId("useRouteError");return n!==void 0?n:e.errors?.[t]}function useNavigateStable(){let{router:n}=useDataRouterContext("useNavigate"),e=useCurrentRouteId("useNavigate"),t=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{t.current=!0}),reactExports.useCallback(async(s,o={})=>{warning(t.current,navigateEffectWarning),t.current&&(typeof s=="number"?await n.navigate(s):await n.navigate(s,{fromRouteId:e,...o}))},[n,e])}var alreadyWarned={};function warningOnce(n,e,t){!e&&!alreadyWarned[n]&&(alreadyWarned[n]=!0,warning(!1,t))}reactExports.memo(DataRoutes2);function DataRoutes2({routes:n,manifest:e,future:t,state:i,isStatic:s,onError:o}){return useRoutesImpl(n,void 0,{manifest:e,state:i,isStatic:s,onError:o})}function Navigate({to:n,replace:e,state:t,relative:i}){invariant(useInRouterContext(),"<Navigate> may be used only in the context of a <Router> component.");let{static:s}=reactExports.useContext(NavigationContext);warning(!s,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:o}=reactExports.useContext(RouteContext),{pathname:l}=useLocation(),u=useNavigate(),h=resolveTo(n,getResolveToMatches(o),l,i==="path"),d=JSON.stringify(h);return reactExports.useEffect(()=>{u(JSON.parse(d),{replace:e,state:t,relative:i})},[u,d,i,e,t]),null}function Outlet(n){return useOutlet(n.context)}function Router({basename:n="/",children:e=null,location:t,navigationType:i="POP",navigator:s,static:o=!1,useTransitions:l}){invariant(!useInRouterContext(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let u=n.replace(/^\/*/,"/"),h=reactExports.useMemo(()=>({basename:u,navigator:s,static:o,useTransitions:l,future:{}}),[u,s,o,l]);typeof t=="string"&&(t=parsePath(t));let{pathname:d="/",search:p="",hash:g="",state:m=null,key:v="default",mask:S}=t,E=reactExports.useMemo(()=>{let x=stripBasename(d,u);return x==null?null:{location:{pathname:x,search:p,hash:g,state:m,key:v,mask:S},navigationType:i}},[u,d,p,g,m,v,i,S]);return warning(E!=null,`<Router basename="${u}"> is not able to match the URL "${d}${p}${g}" because it does not start with the basename, so the <Router> won't render anything.`),E==null?null:reactExports.createElement(NavigationContext.Provider,{value:h},reactExports.createElement(LocationContext.Provider,{children:e,value:E}))}var defaultMethod="get",defaultEncType="application/x-www-form-urlencoded";function isHtmlElement(n){return typeof HTMLElement<"u"&&n instanceof HTMLElement}function isButtonElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="button"}function isFormElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="form"}function isInputElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="input"}function isModifiedEvent(n){return!!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey)}function shouldProcessLinkClick(n,e){return n.button===0&&(!e||e==="_self")&&!isModifiedEvent(n)}var _formDataSupportsSubmitter=null;function isFormDataSubmitterSupported(){if(_formDataSupportsSubmitter===null)try{new FormData(document.createElement("form"),0),_formDataSupportsSubmitter=!1}catch{_formDataSupportsSubmitter=!0}return _formDataSupportsSubmitter}var supportedFormEncTypes=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function getFormEncType(n){return n!=null&&!supportedFormEncTypes.has(n)?(warning(!1,`"${n}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`),null):n}function getFormSubmissionInfo(n,e){let t,i,s,o,l;if(isFormElement(n)){let u=n.getAttribute("action");i=u?stripBasename(u,e):null,t=n.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("enctype"))||defaultEncType,o=new FormData(n)}else if(isButtonElement(n)||isInputElement(n)&&(n.type==="submit"||n.type==="image")){let u=n.form;if(u==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let h=n.getAttribute("formaction")||u.getAttribute("action");if(i=h?stripBasename(h,e):null,t=n.getAttribute("formmethod")||u.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("formenctype"))||getFormEncType(u.getAttribute("enctype"))||defaultEncType,o=new FormData(u,n),!isFormDataSubmitterSupported()){let{name:d,type:p,value:g}=n;if(p==="image"){let m=d?`${d}.`:"";o.append(`${m}x`,"0"),o.append(`${m}y`,"0")}else d&&o.append(d,g)}}else{if(isHtmlElement(n))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');t=defaultMethod,i=null,s=defaultEncType,l=n}return o&&s==="text/plain"&&(l=o,o=void 0),{action:i,method:t.toLowerCase(),encType:s,formData:o,body:l}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function invariant2(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function singleFetchUrl(n,e,t,i){let s=typeof n=="string"?new URL(n,typeof window>"u"?"server://singlefetch/":window.location.origin):n;return t?s.pathname.endsWith("/")?s.pathname=`${s.pathname}_.${i}`:s.pathname=`${s.pathname}.${i}`:s.pathname==="/"?s.pathname=`_root.${i}`:e&&stripBasename(s.pathname,e)==="/"?s.pathname=`${removeTrailingSlash(e)}/_root.${i}`:s.pathname=`${removeTrailingSlash(s.pathname)}.${i}`,s}async function loadRouteModule(n,e){if(n.id in e)return e[n.id];try{let t=await import(n.module);return e[n.id]=t,t}catch(t){return console.error(`Error loading route module \`${n.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function isHtmlLinkDescriptor(n){return n==null?!1:n.href==null?n.rel==="preload"&&typeof n.imageSrcSet=="string"&&typeof n.imageSizes=="string":typeof n.rel=="string"&&typeof n.href=="string"}async function getKeyedPrefetchLinks(n,e,t){let i=await Promise.all(n.map(async s=>{let o=e.routes[s.route.id];if(o){let l=await loadRouteModule(o,t);return l.links?l.links():[]}return[]}));return dedupeLinkDescriptors(i.flat(1).filter(isHtmlLinkDescriptor).filter(s=>s.rel==="stylesheet"||s.rel==="preload").map(s=>s.rel==="stylesheet"?{...s,rel:"prefetch",as:"style"}:{...s,rel:"prefetch"}))}function getNewMatchesForLinks(n,e,t,i,s,o){let l=(h,d)=>t[d]?h.route.id!==t[d].route.id:!0,u=(h,d)=>t[d].pathname!==h.pathname||t[d].route.path?.endsWith("*")&&t[d].params["*"]!==h.params["*"];return o==="assets"?e.filter((h,d)=>l(h,d)||u(h,d)):o==="data"?e.filter((h,d)=>{let p=i.routes[h.route.id];if(!p||!p.hasLoader)return!1;if(l(h,d)||u(h,d))return!0;if(h.route.shouldRevalidate){let g=h.route.shouldRevalidate({currentUrl:new URL(s.pathname+s.search+s.hash,window.origin),currentParams:t[0]?.params||{},nextUrl:new URL(n,window.origin),nextParams:h.params,defaultShouldRevalidate:!0});if(typeof g=="boolean")return g}return!0}):[]}function getModuleLinkHrefs(n,e,{includeHydrateFallback:t}={}){return dedupeHrefs(n.map(i=>{let s=e.routes[i.route.id];if(!s)return[];let o=[s.module];return s.clientActionModule&&(o=o.concat(s.clientActionModule)),s.clientLoaderModule&&(o=o.concat(s.clientLoaderModule)),t&&s.hydrateFallbackModule&&(o=o.concat(s.hydrateFallbackModule)),s.imports&&(o=o.concat(s.imports)),o}).flat(1))}function dedupeHrefs(n){return[...new Set(n)]}function sortKeys(n){let e={},t=Object.keys(n).sort();for(let i of t)e[i]=n[i];return e}function dedupeLinkDescriptors(n,e){let t=new Set;return new Set(e),n.reduce((i,s)=>{let o=JSON.stringify(sortKeys(s));return t.has(o)||(t.add(o),i.push({key:o,link:s})),i},[])}function useDataRouterContext2(){let n=reactExports.useContext(DataRouterContext);return invariant2(n,"You must render this element inside a <DataRouterContext.Provider> element"),n}function useDataRouterStateContext(){let n=reactExports.useContext(DataRouterStateContext);return invariant2(n,"You must render this element inside a <DataRouterStateContext.Provider> element"),n}var FrameworkContext=reactExports.createContext(void 0);FrameworkContext.displayName="FrameworkContext";function useFrameworkContext(){let n=reactExports.useContext(FrameworkContext);return invariant2(n,"You must render this element inside a <HydratedRouter> element"),n}function usePrefetchBehavior(n,e){let t=reactExports.useContext(FrameworkContext),[i,s]=reactExports.useState(!1),[o,l]=reactExports.useState(!1),{onFocus:u,onBlur:h,onMouseEnter:d,onMouseLeave:p,onTouchStart:g}=e,m=reactExports.useRef(null);reactExports.useEffect(()=>{if(n==="render"&&l(!0),n==="viewport"){let E=A=>{A.forEach(C=>{l(C.isIntersecting)})},x=new IntersectionObserver(E,{threshold:.5});return m.current&&x.observe(m.current),()=>{x.disconnect()}}},[n]),reactExports.useEffect(()=>{if(i){let E=setTimeout(()=>{l(!0)},100);return()=>{clearTimeout(E)}}},[i]);let v=()=>{s(!0)},S=()=>{s(!1),l(!1)};return t?n!=="intent"?[o,m,{}]:[o,m,{onFocus:composeEventHandlers(u,v),onBlur:composeEventHandlers(h,S),onMouseEnter:composeEventHandlers(d,v),onMouseLeave:composeEventHandlers(p,S),onTouchStart:composeEventHandlers(g,v)}]:[!1,m,{}]}function composeEventHandlers(n,e){return t=>{n&&n(t),t.defaultPrevented||e(t)}}function PrefetchPageLinks({page:n,...e}){let t=useIsRSCRouterContext(),{nonce:i}=useFrameworkContext(),{router:s}=useDataRouterContext2(),o=reactExports.useMemo(()=>matchRoutes(s.routes,n,s.basename),[s.routes,n,s.basename]);return o?(e.nonce==null&&i&&(e={...e,nonce:i}),t?reactExports.createElement(RSCPrefetchPageLinksImpl,{page:n,matches:o,...e}):reactExports.createElement(PrefetchPageLinksImpl,{page:n,matches:o,...e})):null}function useKeyedPrefetchLinks(n){let{manifest:e,routeModules:t}=useFrameworkContext(),[i,s]=reactExports.useState([]);return reactExports.useEffect(()=>{let o=!1;return getKeyedPrefetchLinks(n,e,t).then(l=>{o||s(l)}),()=>{o=!0}},[n,e,t]),i}function RSCPrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s}=useFrameworkContext(),{basename:o}=useDataRouterContext2(),l=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let u=singleFetchUrl(n,o,s.v8_trailingSlashAwareDataRequests,"rsc"),h=!1,d=[];for(let p of e)typeof p.route.shouldRevalidate=="function"?h=!0:d.push(p.route.id);return h&&d.length>0&&u.searchParams.set("_routes",d.join(",")),[u.pathname+u.search]},[o,s.v8_trailingSlashAwareDataRequests,n,i,e]);return reactExports.createElement(reactExports.Fragment,null,l.map(u=>reactExports.createElement("link",{key:u,rel:"prefetch",as:"fetch",href:u,...t})))}function PrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s,manifest:o,routeModules:l}=useFrameworkContext(),{basename:u}=useDataRouterContext2(),{loaderData:h,matches:d}=useDataRouterStateContext(),p=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,o,i,"data"),[n,e,d,o,i]),g=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,o,i,"assets"),[n,e,d,o,i]),m=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let E=new Set,x=!1;if(e.forEach(C=>{let T=o.routes[C.route.id];!T||!T.hasLoader||(!p.some(F=>F.route.id===C.route.id)&&C.route.id in h&&l[C.route.id]?.shouldRevalidate||T.hasClientLoader?x=!0:E.add(C.route.id))}),E.size===0)return[];let A=singleFetchUrl(n,u,s.v8_trailingSlashAwareDataRequests,"data");return x&&E.size>0&&A.searchParams.set("_routes",e.filter(C=>E.has(C.route.id)).map(C=>C.route.id).join(",")),[A.pathname+A.search]},[u,s.v8_trailingSlashAwareDataRequests,h,i,o,p,e,n,l]),v=reactExports.useMemo(()=>getModuleLinkHrefs(g,o),[g,o]),S=useKeyedPrefetchLinks(g);return reactExports.createElement(reactExports.Fragment,null,m.map(E=>reactExports.createElement("link",{key:E,rel:"prefetch",as:"fetch",href:E,...t})),v.map(E=>reactExports.createElement("link",{key:E,rel:"modulepreload",href:E,...t})),S.map(({key:E,link:x})=>reactExports.createElement("link",{key:E,nonce:t.nonce,...x,crossOrigin:x.crossOrigin??t.crossOrigin})))}function mergeRefs(...n){return e=>{n.forEach(t=>{typeof t=="function"?t(e):t!=null&&(t.current=e)})}}var isBrowser2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{isBrowser2&&(window.__reactRouterVersion="7.18.2")}catch{}function BrowserRouter({basename:n,children:e,useTransitions:t,window:i}){let s=reactExports.useRef();s.current==null&&(s.current=createBrowserHistory({window:i,v5Compat:!0}));let o=s.current,[l,u]=reactExports.useState({action:o.action,location:o.location}),h=reactExports.useCallback(d=>{t===!1?u(d):reactExports.startTransition(()=>u(d))},[t]);return reactExports.useLayoutEffect(()=>o.listen(h),[o,h]),reactExports.createElement(Router,{basename:n,children:e,location:l.location,navigationType:l.action,navigator:o,useTransitions:t})}var Link=reactExports.forwardRef(function({onClick:e,discover:t="render",prefetch:i="none",relative:s,reloadDocument:o,replace:l,mask:u,state:h,target:d,to:p,preventScrollReset:g,viewTransition:m,defaultShouldRevalidate:v,...S},E){let{basename:x,navigator:A,useTransitions:C}=reactExports.useContext(NavigationContext),T=typeof p=="string"&&ABSOLUTE_URL_REGEX.test(p),F=parseToInfo(p,x);p=F.to;let P=useHref(p,{relative:s}),q=useLocation(),O=null;if(u){let ke=resolveTo(u,[],q.mask?q.mask.pathname:"/",!0);x!=="/"&&(ke.pathname=ke.pathname==="/"?x:joinPaths([x,ke.pathname])),O=A.createHref(ke)}let[G,fe,M]=usePrefetchBehavior(i,S),ee=useLinkClickHandler(p,{replace:l,mask:u,state:h,target:d,preventScrollReset:g,relative:s,viewTransition:m,defaultShouldRevalidate:v,useTransitions:C});function Se(ke){e&&e(ke),ke.defaultPrevented||ee(ke)}let re=!(F.isExternal||o),Ae=reactExports.createElement("a",{...S,...M,href:(re?O:void 0)||F.absoluteURL||P,onClick:re?Se:e,ref:mergeRefs(E,fe),target:d,"data-discover":!T&&t==="render"?"true":void 0});return G&&!T?reactExports.createElement(reactExports.Fragment,null,Ae,reactExports.createElement(PrefetchPageLinks,{page:P})):Ae});Link.displayName="Link";var NavLink=reactExports.forwardRef(function({"aria-current":e="page",caseSensitive:t=!1,className:i="",end:s=!1,style:o,to:l,viewTransition:u,children:h,...d},p){let g=useResolvedPath(l,{relative:d.relative}),m=useLocation(),v=reactExports.useContext(DataRouterStateContext),{navigator:S,basename:E}=reactExports.useContext(NavigationContext),x=v!=null&&useViewTransitionState(g)&&u===!0,A=S.encodeLocation?S.encodeLocation(g).pathname:g.pathname,C=m.pathname,T=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;t||(C=C.toLowerCase(),T=T?T.toLowerCase():null,A=A.toLowerCase()),T&&E&&(T=stripBasename(T,E)||T);const F=A!=="/"&&A.endsWith("/")?A.length-1:A.length;let P=C===A||!s&&C.startsWith(A)&&C.charAt(F)==="/",q=T!=null&&(T===A||!s&&T.startsWith(A)&&T.charAt(A.length)==="/"),O={isActive:P,isPending:q,isTransitioning:x},G=P?e:void 0,fe;typeof i=="function"?fe=i(O):fe=[i,P?"active":null,q?"pending":null,x?"transitioning":null].filter(Boolean).join(" ");let M=typeof o=="function"?o(O):o;return reactExports.createElement(Link,{...d,"aria-current":G,className:fe,ref:p,style:M,to:l,viewTransition:u},typeof h=="function"?h(O):h)});NavLink.displayName="NavLink";var Form=reactExports.forwardRef(({discover:n="render",fetcherKey:e,navigate:t,reloadDocument:i,replace:s,state:o,method:l=defaultMethod,action:u,onSubmit:h,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m,...v},S)=>{let{useTransitions:E}=reactExports.useContext(NavigationContext),x=useSubmit(),A=useFormAction(u,{relative:d}),C=l.toLowerCase()==="get"?"get":"post",T=typeof u=="string"&&ABSOLUTE_URL_REGEX.test(u),F=P=>{if(h&&h(P),P.defaultPrevented)return;P.preventDefault();let q=P.nativeEvent.submitter,O=q?.getAttribute("formmethod")||l,G=()=>x(q||P.currentTarget,{fetcherKey:e,method:O,navigate:t,replace:s,state:o,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m});E&&t!==!1?reactExports.startTransition(()=>G()):G()};return reactExports.createElement("form",{ref:S,method:C,action:A,onSubmit:i?h:F,...v,"data-discover":!T&&n==="render"?"true":void 0})});Form.displayName="Form";function getDataRouterConsoleError2(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext3(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError2(n)),e}function useLinkClickHandler(n,{target:e,replace:t,mask:i,state:s,preventScrollReset:o,relative:l,viewTransition:u,defaultShouldRevalidate:h,useTransitions:d}={}){let p=useNavigate(),g=useLocation(),m=useResolvedPath(n,{relative:l});return reactExports.useCallback(v=>{if(shouldProcessLinkClick(v,e)){v.preventDefault();let S=t!==void 0?t:createPath(g)===createPath(m),E=()=>p(n,{replace:S,mask:i,state:s,preventScrollReset:o,relative:l,viewTransition:u,defaultShouldRevalidate:h});d?reactExports.startTransition(()=>E()):E()}},[g,p,m,t,i,s,e,n,o,l,u,h,d])}var fetcherId=0,getUniqueFetcherId=()=>`__${String(++fetcherId)}__`;function useSubmit(){let{router:n}=useDataRouterContext3("useSubmit"),{basename:e}=reactExports.useContext(NavigationContext),t=useRouteId(),i=n.fetch,s=n.navigate;return reactExports.useCallback(async(o,l={})=>{let{action:u,method:h,encType:d,formData:p,body:g}=getFormSubmissionInfo(o,e);if(l.navigate===!1){let m=l.fetcherKey||getUniqueFetcherId();await i(m,t,l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,flushSync:l.flushSync})}else await s(l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,replace:l.replace,state:l.state,fromRouteId:t,flushSync:l.flushSync,viewTransition:l.viewTransition})},[i,s,e,t])}function useFormAction(n,{relative:e}={}){let{basename:t}=reactExports.useContext(NavigationContext),i=reactExports.useContext(RouteContext);invariant(i,"useFormAction must be used inside a RouteContext");let[s]=i.matches.slice(-1),o={...useResolvedPath(n||".",{relative:e})},l=useLocation();if(n==null){o.search=l.search;let u=new URLSearchParams(o.search),h=u.getAll("index");if(h.some(p=>p==="")){u.delete("index"),h.filter(g=>g).forEach(g=>u.append("index",g));let p=u.toString();o.search=p?`?${p}`:""}}return(!n||n===".")&&s.route.index&&(o.search=o.search?o.search.replace(/^\?/,"?index&"):"?index"),t!=="/"&&(o.pathname=o.pathname==="/"?t:joinPaths([t,o.pathname])),createPath(o)}function useViewTransitionState(n,{relative:e}={}){let t=reactExports.useContext(ViewTransitionContext);invariant(t!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:i}=useDataRouterContext3("useViewTransitionState"),s=useResolvedPath(n,{relative:e});if(!t.isTransitioning)return!1;let o=stripBasename(t.currentLocation.pathname,i)||t.currentLocation.pathname,l=stripBasename(t.nextLocation.pathname,i)||t.nextLocation.pathname;return matchPath(s.pathname,l)!=null||matchPath(s.pathname,o)!=null}const mergeClasses=(...n)=>n.filter((e,t,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===t).join(" ").trim();const toKebabCase=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const toCamelCase=n=>n.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,i)=>i?i.toUpperCase():t.toLowerCase());const toPascalCase=n=>{const e=toCamelCase(n);return e.charAt(0).toUpperCase()+e.slice(1)};var defaultAttributes={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const hasA11yProp=n=>{for(const e in n)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};const Icon=reactExports.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:i,className:s="",children:o,iconNode:l,...u},h)=>reactExports.createElement("svg",{ref:h,...defaultAttributes,width:e,height:e,stroke:n,strokeWidth:i?Number(t)*24/Number(e):t,className:mergeClasses("lucide",s),...!o&&!hasA11yProp(u)&&{"aria-hidden":"true"},...u},[...l.map(([d,p])=>reactExports.createElement(d,p)),...Array.isArray(o)?o:[o]]));const createLucideIcon=(n,e)=>{const t=reactExports.forwardRef(({className:i,...s},o)=>reactExports.createElement(Icon,{ref:o,iconNode:e,className:mergeClasses(`lucide-${toKebabCase(toPascalCase(n))}`,`lucide-${n}`,i),...s}));return t.displayName=toPascalCase(n),t};const __iconNode$g=[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M9 13a4.5 4.5 0 0 0 3-4",key:"10igwf"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M12 13h4",key:"1ku699"}],["path",{d:"M12 18h6a2 2 0 0 1 2 2v1",key:"105ag5"}],["path",{d:"M12 8h8",key:"1lhi5i"}],["path",{d:"M16 8V5a2 2 0 0 1 2-2",key:"u6izg6"}],["circle",{cx:"16",cy:"13",r:".5",key:"ry7gng"}],["circle",{cx:"18",cy:"3",r:".5",key:"1aiba7"}],["circle",{cx:"20",cy:"21",r:".5",key:"yhc1fs"}],["circle",{cx:"20",cy:"8",r:".5",key:"1e43v0"}]],BrainCircuit=createLucideIcon("brain-circuit",__iconNode$g);const __iconNode$f=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ChevronRight=createLucideIcon("chevron-right",__iconNode$f);const __iconNode$e=[["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("circle-alert",__iconNode$e);const __iconNode$d=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],CircleCheckBig=createLucideIcon("circle-check-big",__iconNode$d);const __iconNode$c=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],CircleCheck=createLucideIcon("circle-check",__iconNode$c);const __iconNode$b=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Clock=createLucideIcon("clock",__iconNode$b);const __iconNode$a=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Copy=createLucideIcon("copy",__iconNode$a);const __iconNode$9=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Database=createLucideIcon("database",__iconNode$9);const __iconNode$8=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Gauge=createLucideIcon("gauge",__iconNode$8);const __iconNode$7=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Globe=createLucideIcon("globe",__iconNode$7);const __iconNode$6=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Layers=createLucideIcon("layers",__iconNode$6);const __iconNode$5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle=createLucideIcon("loader-circle",__iconNode$5);const __iconNode$4=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],LogOut=createLucideIcon("log-out",__iconNode$4);const __iconNode$3=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],RefreshCw=createLucideIcon("refresh-cw",__iconNode$3);const __iconNode$2=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Settings=createLucideIcon("settings",__iconNode$2);const __iconNode$1=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],Shield=createLucideIcon("shield",__iconNode$1);const __iconNode=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],Sparkles=createLucideIcon("sparkles",__iconNode);function AccountCredentialsFrame({frame:n,children:e}){return n==="bare"?jsxRuntimeExports.jsx("div",{"data-account-credentials-frame":"bare",className:"w-full text-card-foreground",children:e}):jsxRuntimeExports.jsx(Card,{"data-account-credentials-frame":"card",className:"w-full border-border bg-card text-card-foreground",children:e})}function setCredentialValue(n,e,t,i,s){i({...n,[e]:t}),s?.(e,t)}function FieldError({id:n,message:e}){return e?jsxRuntimeExports.jsxs("p",{id:n,role:"alert","aria-live":"polite",className:"flex items-center gap-1.5 text-sm text-destructive",children:[jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-4 w-4 shrink-0"}),e]}):null}function FloatingCredentialField({id:n,label:e,error:t,children:i}){return jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsxs("div",{"data-floating-field":"true",className:"relative",children:[i,jsxRuntimeExports.jsx(Label,{htmlFor:n,className:"pointer-events-none absolute left-3 top-0 z-[1] -translate-y-1/2 bg-card px-1 text-xs leading-none text-muted-foreground transition-[color,font-size,top,transform] duration-150 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:text-sm peer-focus:top-0 peer-focus:-translate-y-1/2 peer-focus:text-xs peer-focus:text-ring peer-disabled:opacity-50 peer-aria-[invalid=true]:text-destructive",children:e})]}),jsxRuntimeExports.jsx(FieldError,{id:`${n}-error`,message:t})]})}function StackedCredentialField({id:n,label:e,error:t,children:i}){return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:n,children:e}),i,jsxRuntimeExports.jsx(FieldError,{id:`${n}-error`,message:t})]})}function CredentialField({id:n,label:e,error:t,floating:i,children:s}){const o=i?FloatingCredentialField:StackedCredentialField;return jsxRuntimeExports.jsx(o,{id:n,label:e,error:t,children:s})}function AccountCredentialsView({mode:n,values:e,onChange:t,onSubmit:i,onFieldChange:s,onModeChange:o,rememberAccount:l=!0,onRememberAccountChange:u,pending:h=!1,errors:d,usernameAvailability:p="idle",usernameSuggestions:g=[],copy:m,frame:v="card",showHeader:S=!0,presentation:E="standard"}){const[x,A]=reactExports.useState(!1),[C,T]=reactExports.useState(!1),F=reactExports.useId(),P=reactExports.useId(),q=reactExports.useId(),O=reactExports.useId(),G=reactExports.useId(),fe=n==="register",M=typeof p=="string"?p:p.status,ee=fe&&e.password.length>0&&e.confirmation!==void 0&&e.password!==e.confirmation,Se=ee&&(x||C)?m.mismatchError:void 0,re=fe?m.registerAction:m.loginAction,Ae=E==="compact",ke=Ae?"peer h-11 rounded-xl px-3 pb-2 pt-4":void 0,he=ce=>{if(ce?.preventDefault(),!h){if(fe&&ee){A(!0);return}A(!1),i(e)}},Oe=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[S?jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{children:fe?m.registerTitle:m.loginTitle}),jsxRuntimeExports.jsx(CardDescription,{children:m.productName})]}):null,jsxRuntimeExports.jsx(CardContent,{className:cn(v==="bare"?"p-0":S?void 0:"pt-6"),children:jsxRuntimeExports.jsxs("form",{onSubmit:he,className:Ae?"space-y-3":"space-y-4",children:[fe?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(CredentialField,{floating:Ae,id:F,label:m.usernameLabel,error:d?.username,children:jsxRuntimeExports.jsx(Input,{id:F,name:"username",autoComplete:"username",placeholder:Ae?" ":m.usernamePlaceholder,title:m.usernamePlaceholder,value:e.username??"",disabled:h,"aria-invalid":d?.username?!0:void 0,"aria-describedby":d?.username?`${F}-error`:void 0,className:ke,onChange:ce=>setCredentialValue(e,"username",ce.currentTarget.value,t,s)})}),M==="checking"?jsxRuntimeExports.jsxs("p",{role:"status","aria-live":"polite",className:"text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{"aria-hidden":"true",className:"mr-1 inline h-3.5 w-3.5 animate-spin"}),m.usernameChecking]}):null,M==="available"?jsxRuntimeExports.jsxs("p",{"aria-live":"polite",className:"flex items-center gap-1 text-sm text-primary",children:[jsxRuntimeExports.jsx(CircleCheckBig,{"aria-hidden":"true",className:"h-4 w-4"}),m.usernameAvailable]}):null,M==="unavailable"&&!d?.username?jsxRuntimeExports.jsx("p",{"aria-live":"polite",className:"text-sm text-destructive",children:typeof p=="object"&&p.message?p.message:m.usernameUnavailable}):null,!Ae&&g.length>0?jsxRuntimeExports.jsxs("div",{className:"space-y-2","aria-label":m.suggestionsLabel,children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:m.suggestionsLabel}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-2",children:g.map(ce=>jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",size:"sm",disabled:h,onClick:()=>setCredentialValue(e,"username",ce,t,s),children:ce},ce))})]}):null]}):null,jsxRuntimeExports.jsx(CredentialField,{floating:Ae,id:P,label:m.emailLabel,error:d?.email,children:jsxRuntimeExports.jsx(Input,{id:P,name:"email",type:"email",autoComplete:"email",placeholder:Ae?" ":m.emailPlaceholder,title:m.emailPlaceholder,value:e.email??"",disabled:h,"aria-invalid":d?.email?!0:void 0,"aria-describedby":d?.email?`${P}-error`:void 0,className:ke,onChange:ce=>setCredentialValue(e,"email",ce.currentTarget.value,t,s)})}),jsxRuntimeExports.jsx(CredentialField,{floating:Ae,id:q,label:m.passwordLabel,error:d?.password,children:jsxRuntimeExports.jsx(Input,{id:q,name:"password",type:"password",autoComplete:fe?"new-password":"current-password",placeholder:Ae?" ":m.passwordPlaceholder,title:m.passwordPlaceholder,value:e.password,disabled:h,"aria-invalid":d?.password?!0:void 0,"aria-describedby":d?.password?`${q}-error`:void 0,className:ke,onChange:ce=>setCredentialValue(e,"password",ce.currentTarget.value,t,s)})}),fe?jsxRuntimeExports.jsx(CredentialField,{floating:Ae,id:O,label:m.confirmationLabel,error:Se??d?.confirmation,children:jsxRuntimeExports.jsx(Input,{id:O,name:"confirmation",type:"password",autoComplete:"new-password",placeholder:Ae?" ":m.confirmationPlaceholder,title:m.confirmationPlaceholder,value:e.confirmation??"",onBlur:()=>T(!0),disabled:h,"aria-invalid":Se||d?.confirmation?!0:void 0,"aria-describedby":Se||d?.confirmation?`${O}-error`:void 0,className:ke,onChange:ce=>{A(!1),setCredentialValue(e,"confirmation",ce.currentTarget.value,t,s)}})}):null,!fe&&u?jsxRuntimeExports.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[jsxRuntimeExports.jsx("input",{type:"checkbox",name:"remember",checked:l,disabled:h,onChange:ce=>u(ce.currentTarget.checked)}),"记住账号"]}):null,jsxRuntimeExports.jsx(FieldError,{id:G,message:d?.form}),jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs(Button,{type:"submit",className:cn("w-full",Ae&&"h-10 rounded-xl"),disabled:h,children:[h?jsxRuntimeExports.jsx(LoaderCircle,{"aria-hidden":"true",className:"mr-2 h-4 w-4 animate-spin"}):null,re]}),o?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",className:cn("w-full",Ae&&"h-9 rounded-lg text-xs"),disabled:h,onClick:()=>o(fe?"login":"register"),children:fe?m.switchToLogin:m.switchToRegister}):null]})]})})]});return jsxRuntimeExports.jsx(AccountCredentialsFrame,{frame:v,children:Oe})}function getXpodAuthSurfaceHost(){return globalThis.xpodDesktop?"window":"document"}function useXpodAuthWindowSurface(n=!0,e="auth"){reactExports.useEffect(()=>{if(n)return globalThis.xpodDesktop?.setWindowMode?.(e),()=>{globalThis.xpodDesktop?.setWindowMode?.("workspace")}},[n,e])}const xpodIconUrl="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2064%2064'%20fill='none'%3e%3cpath%20d='M32%207%2051%2016.5v13.8c0%2012.4-7.4%2021.2-19%2027.7-11.6-6.5-19-15.3-19-27.7V16.5L32%207Z'%20stroke='%238A72BE'%20stroke-width='5'%20stroke-linecap='round'%20stroke-linejoin='round'%20/%3e%3c/svg%3e",features=[{icon:Clock,title:"Your AI Secretary Never Stops",description:"Runs 24/7, even when you are not talking to it"},{icon:Layers,title:"All Your Pieces, In One Place",description:"Data, memory, and context come back into one system"},{icon:Shield,title:"One Secretary, Many Agents",description:"One aligned layer that can direct many agents while keeping privacy and control inside your boundary."}];function Brand({compact:n=!1}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("img",{src:xpodIconUrl,alt:"",className:n?"h-9 w-9":"h-12 w-12"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:`${n?"text-xl":"text-2xl"} font-bold leading-tight`,children:"Xpod"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Personal Messages Platform"})]})]})}function WebAccountLayout({title:n,description:e,children:t,presentation:i="standard",host:s="document"}){const o=reactExports.useId(),l=s==="window"&&i==="compact";return i==="compact"?jsxRuntimeExports.jsx("main",{"data-testid":"web-account-page",className:l?"flex h-dvh w-full items-center justify-center overflow-hidden bg-background text-foreground":"flex min-h-dvh items-center justify-center bg-muted/30 p-4 text-foreground sm:p-6",children:jsxRuntimeExports.jsxs("section",{role:"region","aria-labelledby":o,"data-testid":"web-account-panel","data-web-account-layout":"compact","data-web-account-host":l?"window":"document",className:l?"flex h-full w-full min-w-0 flex-col overflow-y-auto overscroll-contain px-5 py-5":"mx-auto 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 rounded-xl border bg-card px-5 py-5 shadow-lg shadow-black/5",children:[jsxRuntimeExports.jsx("div",{className:"mb-4 shrink-0",children:jsxRuntimeExports.jsx(Brand,{compact:!0})}),jsxRuntimeExports.jsxs("header",{className:"mb-4 shrink-0 text-center",children:[jsxRuntimeExports.jsx("h1",{id:o,className:"text-xl font-semibold tracking-tight",children:n}),e?jsxRuntimeExports.jsx("p",{className:"mt-2 text-xs leading-relaxed text-muted-foreground",children:e}):null]}),jsxRuntimeExports.jsx("div",{className:"min-w-0 shrink-0",children:t})]})}):jsxRuntimeExports.jsx("main",{"data-testid":"web-account-page",className:"flex min-h-dvh items-center justify-center bg-muted/30 p-4 text-foreground sm:p-8",children:jsxRuntimeExports.jsxs("div",{className:"grid w-full max-w-6xl items-center gap-8 lg:grid-cols-2 lg:gap-16",children:[jsxRuntimeExports.jsxs("aside",{"data-testid":"web-account-introduction","aria-label":"关于 Xpod",className:"hidden px-8 lg:block",children:[jsxRuntimeExports.jsx(Brand,{}),jsxRuntimeExports.jsxs("h1",{className:"mb-4 mt-8 text-3xl font-bold leading-tight",children:["Simplify Life with ",jsxRuntimeExports.jsx("span",{className:"text-primary",children:"Your AI Secretary"})]}),jsxRuntimeExports.jsx("p",{className:"mb-10 text-sm leading-relaxed text-muted-foreground",children:"An AI that never stops, knows your whole life, works for you—while guarding your privacy."}),jsxRuntimeExports.jsx("div",{className:"space-y-5",children:features.map(({icon:u,title:h,description:d})=>jsxRuntimeExports.jsxs("div",{className:"flex gap-3",children:[jsxRuntimeExports.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border bg-card",children:jsxRuntimeExports.jsx(u,{"aria-hidden":"true",className:"h-4 w-4 text-primary"})}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-sm font-medium",children:h}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:d})]})]},h))}),jsxRuntimeExports.jsxs("p",{className:"mt-12 text-xs text-muted-foreground",children:["Powered by ",jsxRuntimeExports.jsx("a",{href:"https://solidproject.org",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline-offset-4 hover:underline",children:"Solid Protocol"})]})]}),jsxRuntimeExports.jsxs("section",{role:"region","aria-labelledby":o,"data-testid":"web-account-panel","data-web-account-layout":"standard",className:"mx-auto w-full min-w-0 max-w-md rounded-3xl border bg-card p-6 shadow-lg shadow-black/5 sm:p-8 lg:mx-0",children:[jsxRuntimeExports.jsx("div",{className:"mb-8 lg:hidden",children:jsxRuntimeExports.jsx(Brand,{})}),jsxRuntimeExports.jsxs("header",{className:"mb-6",children:[jsxRuntimeExports.jsx("h2",{id:o,className:"text-2xl font-bold tracking-tight",children:n}),e?jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm leading-relaxed text-muted-foreground",children:e}):null]}),t]})]})})}function XpodAuthSurface(n){const e=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(e==="window"),jsxRuntimeExports.jsx(AuthSurface,{...n,presentation:"compact",host:e})}function XpodAccountPageSurface({title:n,children:e,presentation:t="compact"}){const i=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(i==="window"&&t==="compact","account"),jsxRuntimeExports.jsx(WebAccountLayout,{title:n,presentation:t,host:i,children:e})}function XpodBlockingAccountCredentialsSurface(n){const e=getXpodAuthSurfaceHost(),t="compact";return useXpodAuthWindowSurface(e==="window"&&t==="compact","account"),jsxRuntimeExports.jsxs(WebAccountLayout,{title:n.surfaceTitle,description:n.mode==="register"?"创建你的 Xpod 账号,开始使用个人存储空间。":"登录以继续使用你的身份与个人存储空间。",presentation:t,host:e,children:[jsxRuntimeExports.jsx(AccountCredentialsView,{...n,frame:"bare",showHeader:!1,presentation:t}),n.footer?jsxRuntimeExports.jsx("div",{className:"mt-6 space-y-3 border-t pt-5",children:n.footer}):null]})}function WebAccountFailureView({title:n="操作未完成",description:e,primaryLabel:t="重试",onPrimary:i,secondaryLabel:s="返回",onSecondary:o,pending:l=!1}){return jsxRuntimeExports.jsxs("div",{className:"flex min-h-44 flex-col items-center justify-center gap-4 px-5 py-8 text-center",children:[jsxRuntimeExports.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-destructive/10",children:jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-5 w-5 text-destructive"})}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-base font-semibold text-foreground",children:n}),e?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm leading-6 text-muted-foreground",children:e}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex w-full flex-col gap-2 sm:max-w-xs",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:i,className:"h-10 rounded-xl bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus-visible:bg-primary/80 disabled:cursor-not-allowed disabled:opacity-50",children:t}),o?jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:o,className:"h-9 rounded-lg border border-border bg-background px-4 text-sm font-medium text-foreground transition-colors hover:bg-muted/50 focus:outline-none focus-visible:border-ring",children:s}):null]})]})}let automaticLoginBlocked=!1,logoutState={status:"idle"},operation,inFlight;const logoutListeners=new Set,isXpodAutomaticLoginBlocked=()=>automaticLoginBlocked,getXpodProductLogoutState=()=>logoutState;function subscribeXpodProductLogout(n){return logoutListeners.add(n),()=>{logoutListeners.delete(n)}}function publish(n){logoutState=n,logoutListeners.forEach(e=>e())}function logoutXpodProduct(n,e,t={}){return inFlight||(automaticLoginBlocked=!0,operation={account:n,runtime:e,solidCleared:!1,onComplete:t.onComplete},retryXpodProductLogout())}function retryXpodProductLogout(){if(inFlight)return inFlight;if(!operation)return Promise.resolve();const n=operation;return inFlight=(async()=>{let t=n.solidCleared?"account":"solid";publish({status:"running",step:t});try{if(n.solidCleared||(await n.runtime?.logout(),n.solidCleared=!0),t="account",publish({status:"running",step:t}),await n.account.logout(),n.account.isAnonymous&&!n.account.isAnonymous())throw new Error("Account sign-out did not complete")}catch(i){throw publish({status:"error",step:t}),i}operation=void 0,publish({status:"idle"}),n.onComplete?.()})().finally(()=>{inFlight=void 0}),inFlight}const LogoutRecoveryOwner=reactExports.createContext(!1);function XpodProductLogoutBoundary({children:n}){const e=reactExports.useContext(LogoutRecoveryOwner),t=reactExports.useSyncExternalStore(subscribeXpodProductLogout,getXpodProductLogoutState,getXpodProductLogoutState);if(e)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});const i=t.status!=="idle";return jsxRuntimeExports.jsxs(LogoutRecoveryOwner.Provider,{value:!0,children:[i&&jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"退出 Xpod",children:t.status==="running"?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在退出…"}):jsxRuntimeExports.jsx(WebAccountFailureView,{title:"退出未完成",description:t.step==="account"?"账号会话尚未退出,请重试完成退出。":"WebID 会话尚未退出,请重试完成退出。",primaryLabel:"重试退出",onPrimary:()=>{retryXpodProductLogout().catch(()=>{})}})}),jsxRuntimeExports.jsx("div",{className:i?"hidden":"contents","aria-hidden":i||void 0,inert:i||void 0,children:n})]})}const AuthContext=reactExports.createContext(null);function useAuth(){const n=reactExports.useContext(AuthContext);if(!n)throw new Error("useAuth must be used within AuthProvider");return n}const scriptRel="modulepreload",assetsURL=function(n){return"/settings/"+n},seen={},__vitePreload=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let h=function(d){return Promise.all(d.map(p=>Promise.resolve(p).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=l?.nonce||l?.getAttribute("nonce");s=h(t.map(d=>{if(d=assetsURL(d),d in seen)return;seen[d]=!0;const p=d.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${g}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":scriptRel,p||(m.as="script"),m.crossOrigin="",m.href=d,u&&m.setAttribute("nonce",u),document.head.appendChild(m),p)return new Promise((v,S)=>{m.addEventListener("load",v),m.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return s.then(l=>{for(const u of l||[])u.status==="rejected"&&o(u.reason);return e().catch(o)})};function extractProfileUsernameFromWebId(n){try{const t=new URL(n).pathname.split("/").filter(Boolean).map(o=>decodeURIComponent(o)),i=t.indexOf("profile");if(i>0)return t[i-1];const s=t.find(o=>o!=="profile"&&o!=="card");if(s)return s}catch{}return"there"}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",generateNanoId=(n=21)=>{let e="";if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"){const t=globalThis.crypto.getRandomValues(new Uint8Array(n));for(let i=0;i<n;i++)e+=urlAlphabet[t[i]%urlAlphabet.length]}else{console.warn("Using Math.random fallback for NanoID generation.");for(let t=0;t<n;t++)e+=urlAlphabet[Math.floor(Math.random()*256)%urlAlphabet.length]}return e},hasStringValue$2=n=>typeof n=="object"&&n!==null&&typeof n.value=="string",hasTermValue=n=>typeof n=="object"&&n!==null&&typeof n.term=="object"&&n.term!==null&&typeof n.term?.value=="string",resolveTermIri=n=>{if(typeof n=="string")return n;if(hasStringValue$2(n))return n.value;if(hasTermValue(n))return n.term.value;throw new Error("Term must be a string or VocabTerm with a string value")},entityKind=Symbol.for("drizzle:entityKind");function is(n,e){if(!n||typeof n!="object")return!1;if(n instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,entityKind))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=n.constructor;if(t)for(;t;){if(entityKind in t&&t[entityKind]===e[entityKind])return!0;t=Object.getPrototypeOf(t)}return!1}class Column{table;static[entityKind]="Column";name;primary;notNull;default;defaultFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}const ViewBaseConfig=Symbol.for("drizzle:ViewBaseConfig");class View{static[entityKind]="View";[ViewBaseConfig];constructor({name:e,schema:t,selectedFields:i,query:s}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:i,query:s,isExisting:!s,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,i,s=!1){this[SubqueryConfig]={sql:e,selection:t,alias:i,isWith:s}}getSQL(){return new SQL([this])}}class SelectionProxyHandler{static[entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t===SubqueryConfig)return{...e[SubqueryConfig],selection:new Proxy(e[SubqueryConfig].selection,this)};if(t===ViewBaseConfig)return{...e[ViewBaseConfig],selectedFields:new Proxy(e[ViewBaseConfig].selectedFields,this)};if(typeof t=="symbol")return e[t];const s=(is(e,Subquery)?e[SubqueryConfig].selection:is(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is(s,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!s.isSelectionField)return s.sql;const o=s.clone();return o.isSelectionField=!0,o}if(is(s,SQL)){if(this.config.sqlBehavior==="sql")return s;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is(s,Column)?this.config.alias?new Proxy(s,new ColumnAliasProxyHandler(new Proxy(s.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):s:typeof s!="object"||s===null?s:new Proxy(s,new SelectionProxyHandler(this.config))}}function orderSelectedFields(n,e){return Object.entries(n).reduce((t,[i,s])=>{if(typeof i!="string")return t;const o=e?[...e,i]:[i];return is(s,Column)||is(s,SQL)||is(s,SQL.Aliased)?t.push({path:o,field:s}):is(s,Table)?t.push(...orderSelectedFields(s[Table.Symbol.Columns],o)):t.push(...orderSelectedFields(s,o)),t},[])}function applyMixins(n,e){for(const t of e)for(const i of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(n.prototype,i,Object.getOwnPropertyDescriptor(t.prototype,i)||Object.create(null))}function getTableLikeName(n){return is(n,Subquery)?n[SubqueryConfig].alias:is(n,View)?n[ViewBaseConfig].name:is(n,SQL)?void 0:n[Table.Symbol.IsAlias]?n[Table.Symbol.Name]:n[Table.Symbol.BaseName]}const TableName=Symbol.for("drizzle:Name"),Schema=Symbol.for("drizzle:Schema"),Columns=Symbol.for("drizzle:Columns"),OriginalName=Symbol.for("drizzle:OriginalName"),BaseName=Symbol.for("drizzle:BaseName"),IsAlias=Symbol.for("drizzle:IsAlias"),ExtraConfigBuilder=Symbol.for("drizzle:ExtraConfigBuilder"),IsDrizzleTable=Symbol.for("drizzle:IsDrizzleTable");class Table{static[entityKind]="Table";static Symbol={Name:TableName,Schema,OriginalName,Columns,BaseName,IsAlias,ExtraConfigBuilder};[TableName];[OriginalName];[Schema];[Columns];[BaseName];[IsAlias]=!1;[ExtraConfigBuilder]=void 0;[IsDrizzleTable]=!0;constructor(e,t,i){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=i}getSQL(){return new SQL([this])}}class QueryPromise{static[entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}const tracer={startActiveSpan(n,e){return e()}},InlineForeignKeys=Symbol.for("drizzle:PgInlineForeignKeys");class PgTable extends Table{static[entityKind]="PgTable";static Symbol=Object.assign({},Table.Symbol,{InlineForeignKeys});[InlineForeignKeys]=[];[Table.Symbol.ExtraConfigBuilder]=void 0}class TypedQueryBuilder{static[entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class PgSelectQueryBuilder extends TypedQueryBuilder{static[entityKind]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:e,fields:t,isPartialSelect:i,session:s,dialect:o,withList:l,distinct:u}){super(),this.config={withList:l,table:e,fields:{...t},distinct:u},this.isPartialSelect=i,this.session=s,this.dialect=o,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,i)=>{const s=this.tableName,o=getTableLikeName(t);if(typeof o=="string"&&this.config.joins?.some(l=>l.alias===o))throw new Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof s=="string"&&(this.config.fields={[s]:this.config.fields}),typeof o=="string"&&!is(t,SQL))){const l=is(t,Subquery)?t[SubqueryConfig].selection:is(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[o]=l}if(typeof i=="function"&&(i=i(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:t,joinType:e,alias:o}),typeof o=="string")switch(e){case"left":{this.joinsNotNullableMap[o]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[o]=!0;break}case"inner":{this.joinsNotNullableMap[o]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[o]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.orderBy=Array.isArray(t)?t:[t]}else this.config.orderBy=e;return this}limit(e){return this.config.limit=e,this}offset(e){return this.config.offset=e,this}for(e,t={}){return this.config.lockingClauses||(this.config.lockingClauses=[]),this.config.lockingClauses.push({strength:e,config:t}),this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){return new Proxy(new Subquery(this.getSQL(),this.config.fields,e),new SelectionProxyHandler({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}class PgSelect extends PgSelectQueryBuilder{static[entityKind]="PgSelect";_prepare(e){const{session:t,config:i,dialect:s,joinsNotNullableMap:o}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return tracer.startActiveSpan("drizzle.prepareQuery",()=>{const l=orderSelectedFields(i.fields),u=t.prepareQuery(s.sqlToQuery(this.getSQL()),l,e);return u.joinsNotNullableMap=o,u})}prepare(e){return this._prepare(e)}execute=e=>tracer.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e))}applyMixins(PgSelect,[QueryPromise]);class Relation{sourceTable;referencedTable;relationName;static[entityKind]="Relation";referencedTableName;fieldName;constructor(e,t,i){this.sourceTable=e,this.referencedTable=t,this.relationName=i,this.referencedTableName=t[Table.Symbol.Name]}}function isSQLWrapper(n){return typeof n=="object"&&n!==null&&"getSQL"in n&&typeof n.getSQL=="function"}function mergeQueries(n){const e={sql:"",params:[]};for(const t of n)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class StringChunk{static[entityKind]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new SQL([this])}}class SQL{queryChunks;static[entityKind]="SQL";decoder=noopDecoder;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tracer.startActiveSpan("drizzle.buildSQL",t=>{const i=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(e,t){const i=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:s,escapeParam:o,prepareTyping:l,inlineParams:u,paramStartIndex:h}=i;return mergeQueries(e.map(d=>{if(is(d,StringChunk))return{sql:d.value.join(""),params:[]};if(is(d,Name))return{sql:s(d.value),params:[]};if(d===void 0)return{sql:"",params:[]};if(Array.isArray(d)){const p=[new StringChunk("(")];for(const[g,m]of d.entries())p.push(m),g<d.length-1&&p.push(new StringChunk(", "));return p.push(new StringChunk(")")),this.buildQueryFromSourceParams(p,i)}if(is(d,SQL))return this.buildQueryFromSourceParams(d.queryChunks,{...i,inlineParams:u||d.shouldInlineParams});if(is(d,Table)){const p=d[Table.Symbol.Schema],g=d[Table.Symbol.Name];return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Column))return{sql:s(d.table[Table.Symbol.Name])+"."+s(d.name),params:[]};if(is(d,View)){const p=d[ViewBaseConfig].schema,g=d[ViewBaseConfig].name;return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Param)){const p=d.value===null?null:d.encoder.mapToDriverValue(d.value);if(is(p,SQL))return this.buildQueryFromSourceParams([p],i);if(u)return{sql:this.mapInlineParam(p,i),params:[]};let g;return l!==void 0&&(g=[l(d.encoder)]),{sql:o(h.value++,p),params:[p],typings:g}}return is(d,Placeholder)?{sql:o(h.value++,d),params:[d]}:is(d,SQL.Aliased)&&d.fieldAlias!==void 0?{sql:s(d.fieldAlias),params:[]}:is(d,Subquery)?d[SubqueryConfig].isWith?{sql:s(d[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),d[SubqueryConfig].sql,new StringChunk(") "),new Name(d[SubqueryConfig].alias)],i):isSQLWrapper(d)?this.buildQueryFromSourceParams([new StringChunk("("),d.getSQL(),new StringChunk(")")],i):is(d,Relation)?this.buildQueryFromSourceParams([d.sourceTable,new StringChunk("."),sql.identifier(d.fieldName)],i):u?{sql:this.mapInlineParam(d,i),params:[]}:{sql:o(h.value++,d),params:[d]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const i=e.toString();return t(i==="[object Object]"?JSON.stringify(e):i)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new SQL.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}}class Name{value;static[entityKind]="Name";brand;constructor(e){this.value=e}getSQL(){return new SQL([this])}}const noopDecoder={mapFromDriverValue:n=>n},noopEncoder={mapToDriverValue:n=>n};({...noopDecoder,...noopEncoder});class Param{value;encoder;static[entityKind]="Param";brand;constructor(e,t=noopEncoder){this.value=e,this.encoder=t}getSQL(){return new SQL([this])}}function sql(n,...e){const t=[];(e.length>0||n.length>0&&n[0]!=="")&&t.push(new StringChunk(n[0]));for(const[i,s]of e.entries())t.push(s,new StringChunk(n[i+1]));return new SQL(t)}(function(n){function e(){return new SQL([])}n.empty=e;function t(h){return new SQL(h)}n.fromList=t;function i(h){return new SQL([new StringChunk(h)])}n.raw=i;function s(h,d){const p=[];for(const[g,m]of h.entries())g>0&&d!==void 0&&p.push(d),p.push(m);return new SQL(p)}n.join=s;function o(h){return new Name(h)}n.identifier=o;function l(h){return new Placeholder(h)}n.placeholder=l;function u(h,d){return new Param(h,d)}n.param=u})(sql||(sql={}));(function(n){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(i,s){this.sql=i,this.fieldAlias=s}getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}n.Aliased=e})(SQL||(SQL={}));class Placeholder{name;static[entityKind]="Placeholder";constructor(e){this.name=e}getSQL(){return new SQL([this])}}Column.prototype.getSQL=function(){return new SQL([this])};class ColumnAliasProxyHandler{table;static[entityKind]="ColumnAliasProxyHandler";constructor(e){this.table=e}get(e,t){return t==="table"?this.table:e[t]}}class TableAliasProxyHandler{alias;replaceOriginalName;static[entityKind]="TableAliasProxyHandler";constructor(e,t){this.alias=e,this.replaceOriginalName=t}get(e,t){if(t===Table.Symbol.IsAlias)return!0;if(t===Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Table.Symbol.OriginalName)return this.alias;if(t===ViewBaseConfig)return{...e[ViewBaseConfig],name:this.alias,isAlias:!0};if(t===Table.Symbol.Columns){const s=e[Table.Symbol.Columns];if(!s)return s;const o={};return Object.keys(s).map(l=>{o[l]=new Proxy(s[l],new ColumnAliasProxyHandler(new Proxy(e,this)))}),o}const i=e[t];return is(i,Column)?new Proxy(i,new ColumnAliasProxyHandler(new Proxy(e,this))):i}}var _a$b;class ColumnBuilder{constructor(e,t,i={},s,o){this.name=e,this.dataType=t,this.options={...i},this._predicateUri=s,this.elementType=o??null}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){const t=this.options.isArray&&this.elementType?this.elementType:this.dataType;if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(t){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return String(Number(e));case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}parseValue(e,t){return this.parseSingleValue(e,t)}parseSingleValue(e,t){if(!t)return e;if(t.includes("#integer")||t.includes("#int"))return parseInt(e,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e);if(t.includes("#boolean"))return e==="true";if(t.includes("#dateTime"))return new Date(e);if(t.includes("#json"))try{return JSON.parse(e)}catch{return console.warn("Failed to parse JSON value:",e),e}return e.startsWith("http://")||e.startsWith("https://"),e}primaryKey(){return this._predicateUri="@id",this.options={...this.options,primaryKey:!0,required:!0,predicate:"@id"},this}notNull(){return this.options={...this.options,required:!0,notNull:!0},this}predicate(e){const t=resolveTermIri(e);return this._predicateUri=t,this.options={...this.options,predicate:t},this}default(e){return this.options={...this.options,defaultValue:e},this}defaultNow(){return this.options={...this.options,defaultValue:()=>new Date},this}inverse(e=!0){return this.options={...this.options,inverse:e},this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options={...this.options,linkTarget:e}:this.options={...this.options,linkTableName:e}:this.options={...this.options,linkTable:e},this}array(){return new ColumnBuilder(this.name,"array",{...this.options,baseType:this.dataType,isArray:!0},this._predicateUri,this.dataType)}getPredicateUri(){return this._predicateUri}}class PodColumnBase{constructor(e,t,i={},s){this.name=e,this.dataType=t,this.options=i,this.tableName=s}getPredicate(e){if(this.options.predicate)return this.options.predicate;if(e)return`${e.uri}${this.name}`;throw new Error(`Missing predicate for column "${this.name}"; please set namespace or predicate explicitly.`)}isLink(){return!!(this.options.linkTarget||this.options.linkTableName||this.options.linkTable)}getLinkTarget(){return this.options.linkTarget}getLinkTableName(){return this.options.linkTableName}getLinkTable(){return this.options.linkTable}primaryKey(){return this.options.primaryKey=!0,this.options.required=!0,this.options.predicate="@id",this}notNull(){return this.options.required=!0,this}default(e){return this.options.defaultValue=e,this}predicate(e){return this.options.predicate=resolveTermIri(e),this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options.linkTarget=e:this.options.linkTableName=e:this.options.linkTable=e,this}inverse(e=!0){return this.options.inverse=e,this}isInverse(){return this.options.inverse===!0}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(this.dataType){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return`"${Number(e)}"^^<http://www.w3.org/2001/XMLSchema#integer>`;case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}}_a$b=entityKind;PodColumnBase[_a$b]="PodColumn";class PodStringColumn extends PodColumnBase{constructor(e,t={}){super(e,"string",t)}}class PodIntegerColumn extends PodColumnBase{constructor(e,t={}){super(e,"integer",t)}}class PodBooleanColumn extends PodColumnBase{constructor(e,t={}){super(e,"boolean",t)}}class PodDateTimeColumn extends PodColumnBase{constructor(e,t={}){super(e,"datetime",t)}}class PodJsonColumn extends PodColumnBase{constructor(e,t={}){super(e,"json",t)}}class PodObjectColumn extends PodColumnBase{constructor(e,t={}){super(e,"object",t)}}class PodUriColumn extends PodColumnBase{constructor(e,t={}){super(e,"uri",t)}}class PodArrayColumn extends PodColumnBase{constructor(e,t,i={}){super(e,"array",i),this.elementType=t}}function boolean$2(n,e={}){return new ColumnBuilder(n,"boolean",e)}function timestamp(n,e={}){return new ColumnBuilder(n,"datetime",e)}function object$1(n,e={}){return new ColumnBuilder(n,"object",e)}function uri(n,e={}){return new ColumnBuilder(n,"uri",e)}function id(n="id",e={}){const t=new PodStringColumn(n,{...e,predicate:"@id",primaryKey:!0,required:!0,...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{}});return t._virtualId=!0,t}function string$2(n,e={}){return new ColumnBuilder(n,"string",e)}function integer$1(n,e={}){return new ColumnBuilder(n,"integer",e)}function date$3(n,e={}){return new ColumnBuilder(n,"datetime",e)}function text(n,e={}){return new ColumnBuilder(n,"string",e)}function real(n,e={}){return new ColumnBuilder(n,"integer",e)}function validateColumnOverride(n,e,t){const i=n.getPredicateUri?.()??n.options?.predicate,s=e.options?.predicate;if(i&&s&&i!==s)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${s}",子 schema 尝试改为 "${i}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(n,e){const t={};for(const[i,s]of Object.entries(n.columns))t[i]=s;for(const[i,s]of Object.entries(e)){const o=n.columns[i];if(o&&!(s instanceof PodColumnBase)){validateColumnOverride(s,o,i);const l=s;!l.getPredicateUri?.()&&!l.options?.predicate&&(l.options={...l.options,predicate:o.options?.predicate})}t[i]=s}return t}function renderDefaultIdTemplate(n,e){if(!/\{[^{}]+\}/.test(n))return n;if(/\{\s*id\s*\}/.test(n))throw new Error("id default template uses {key} for the generated local key; {id} is the final resource id");const t=e.row??{},i=resolveDate(t,e.now),s={yyyy:String(i.getUTCFullYear()),MM:String(i.getUTCMonth()+1).padStart(2,"0"),dd:String(i.getUTCDate()).padStart(2,"0")};return n.replace(/\{([^{}]+)\}/g,(o,l)=>{const u=l.trim();if(u==="key")return e.key;if(u==="yyyy")return s.yyyy;if(u==="MM")return s.MM;if(u==="dd")return s.dd;const h=resolveExpression(u,t,e);return h==null?"":String(h)})}function resolveDate(n,e=new Date){const t=n.createdAt??n.favoredAt??n.indexedAt??e,i=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(i.getTime())?i:e}function resolveExpression(n,e,t){const i=parseExpression(n);let s=resolveTemplatePath(i.path,e,t);for(const o of i.transforms)s=applyTransform(s,o,i.path,t);return i.selector?applyPathSelector(s,i.selector):s}function parseExpression(n){const e=n.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():n,[i,...s]=t.split("|").map(o=>o.trim()).filter(Boolean);return{path:i??n,transforms:s,selector:e?.[2]?.trim()}}function resolveTemplatePath(n,e,t){const i=n.split("."),s=i[0];return i.reduce((o,l,u)=>{if(typeof o=="string")return s?resolveResourceProperty(o,s,l,t):void 0;if(!(!o||typeof o!="object"))return s&&isResourceProperty(l)&&!((l==="id"||l==="key")&&l in o)?resolveResourceProperty(o,s,l,t):u>0&&l==="id"&&readRef(o)?extractResourceId(o,s??"",t):o[l]},e)}function isResourceProperty(n){return n==="id"||n==="key"||n==="doc"||n==="document"||n==="dir"||n==="owner"}function resolveResourceProperty(n,e,t,i){if(t==="id")return extractResourceId(n,e,i);const s=extractResourceId(n,e,i);if(s){if(t==="key"){const o=extractTemplateValuesForField(n,e,i);return o?.key??o?.id??deriveResourceKey(s)}if(t==="doc"||t==="document")return resourceDocument(s);if(t==="dir"||t==="owner")return deriveOwnerDir(s)}}function applyTransform(n,e,t,i){if(e==="slug")return slugifyValue(String(n??""));const s=extractResourceId(n,t,i);if(e==="resource")return s;if(e==="document")return s?resourceDocument(s):"";if(e==="owner")return s?deriveOwnerDir(s):"";const o=extractTemplateValuesForField(n,t,i);return e==="id"?o?.id??o?.key??s??"":o?.[e]??""}function extractResourceId(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return normalizePodDataResourceId$1(i);if(!isCompleteResourceId$1(i))return renderLinkedResourceId(s,i);const o=relativeSubjectFromRef$1(s,i);return normalizePodDataResourceId$1(o??i)}function extractTemplateValuesForField(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return null;const o=relativeSubjectFromRef$1(s,i)??(isCompleteResourceId$1(i)?null:renderLinkedResourceId(s,i));if(!o)return null;const l=resourceTemplate(s);return l?extractVarsFromTemplate(normalizePodDataResourceId$1(o),l):{id:normalizePodDataResourceId$1(o)}}function resolveLinkedResource(n,e){const t=e.links?.[n];if(t)return t;const i=e.resource?.columns?.[n];return i?.getLinkTable?.()??i?.options?.linkTable??null}function resourceTemplate(n){const e=n.getSubjectTemplate?.()??n.config?.subjectTemplate;if(e)return e;const t=n.columns?.id?.options?.defaultValue;return typeof t=="string"?t:null}function renderLinkedResourceId(n,e){const t=resourceTemplate(n);if(!t)return e;const i=n.columns?.id?.options?.defaultValue;return typeof i=="function"?String(i(e,{})):t.replace(/\{([^}]+)\}/g,(s,o)=>{const l=parseTemplateField(o);return l==="id"||l==="key"?e:""})}function readRef(n){if(typeof n=="string"&&n.length>0)return n;if(!n||typeof n!="object")return null;const e=n,t=e["@id"]??e.subject??e.id;return typeof t=="string"&&t.length>0?t:null}function resourcePath(n){return normalizeResourcePath$1(n.getResourcePath?.()??n.config?.base??"")}function relativeSubjectFromRef$1(n,e){const t=resourcePath(n);if(!t)return normalizePodDataResourceId$1(e);const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const o=e.indexOf(s);if(o<0)continue;let l=e.slice(o+s.length);return l.startsWith("/")&&(l=l.slice(1)),l.length>0?l:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(n,e){let t=0;const i=new Map,s=[];let o=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp$1(e.slice(o,u.index)));const h=`var${t++}`;i.set(h,parseTemplateField(u[1]??"")),s.push(`(?<${h}>.+?)`),o=u.index+u[0].length}s.push(escapeRegExp$1(e.slice(o)));const l=s.join("");try{const u=n.match(new RegExp(`^${l}$`));if(!u?.groups)return null;const h={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);!g||p===void 0||(h[g]=decodeURIComponent(p))}return h}catch{return null}}function parseTemplateField(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function escapeRegExp$1(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function applyPathSelector(n,e){const t=splitResourcePath(n);if(!t)return;if(/^-?\d+$/.test(e))return t[normalizeIndex(Number(e),t.length)];const i=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!i)throw new Error(`Invalid id default path selector [${e}]`);const s=i[1]===""?0:normalizeSliceIndex(Number(i[1]),t.length),o=i[2]===""?t.length:normalizeSliceIndex(Number(i[2]),t.length);return t.slice(s,o).join("/")}function splitResourcePath(n){const e=readRef(n);if(!e)return null;const t=normalizePodDataResourceId$1(e),[i,s]=t.split("#"),o=(i??t).split("/").filter(Boolean);return s&&o.push(s),o}function normalizePodDataResourceId$1(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function normalizeResourcePath$1(n){return n.trim().replace(/^(\.\/)+/,"")}function isCompleteResourceId$1(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function deriveOwnerDir(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#"),i=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):"",o=i.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(o?.[1])return o[1];if(i==="task/index.ttl"&&s&&s!=="this")return`task/${s}`;const l=i.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(l?.[1])return l[1];const u=i.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(u?.[1])return u[1];const h=i.split("/").filter(Boolean);return h.length>1?h.slice(0,-1).join("/"):i}function resourceDocument(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");return t>=0?e.slice(0,t):e}function deriveResourceKey(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");if(t>=0){const u=e.slice(t+1);if(u&&u!=="this"&&u!=="me"&&u!=="it")return u}const i=resourceDocument(e).replace(/\/+$/u,""),s=i.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(s?.[1])return s[1];const o=i.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(o?.[1])return o[1];const l=i.split("/").filter(Boolean);return l.length>0?l[l.length-1]:e}function slugifyValue(n){return n.normalize("NFKC").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^\p{Letter}\p{Number}.-]+/gu,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function normalizeIndex(n,e){return n<0?e+n:n}function normalizeSliceIndex(n,e){const t=n<0?e+n:n;return Math.max(0,Math.min(e,t))}function parseTemplateVariableField$1(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function normalizeResourcePath(n){return n.trim().replace(/^(\.\/)+/,"")}function podResourcePath(n){return normalizeResourcePath(n.getResourcePath?.()??n.config?.base??"")}function podResourceSubjectTemplate(n){return n.getSubjectTemplate?.()??n.config?.subjectTemplate}function podResourceIdDefaultTemplate(n){const e=n.columns?.id?.options?.defaultValue;return typeof e=="string"?e:void 0}function resourceRelativePrefix(n){const e=podResourcePath(n),t=normalizeResourcePath(n.getContainerPath?.()??n.config?.containerPath??"");return e?t&&e.startsWith(t)?normalizeResourcePath(e.slice(t.length)):e.split("/").pop()??e:""}function qualifyFragmentResourceId(n,e){if(!e.startsWith("#"))return e;const t=resourceRelativePrefix(n);return t?`${t}${e}`:e}function templateRelativeSubject(n,e){if((podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n))?.startsWith("#")&&!e.startsWith("#")){const i=e.indexOf("#");if(i>=0)return e.slice(i)}return e}function isBaseRelativeSubjectId$1(n){return!n||/^https?:\/\//.test(n)||n.startsWith("/")?!1:n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(n)}function isTemplateCompleteResourceId(n,e){if(!e||/^https?:\/\//.test(e)||e.startsWith("/"))return!1;const t=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n);return t?extractTemplateValues(templateRelativeSubject(n,e),t)!==null:!1}function isResourceRelativeSubjectId(n,e){return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)}function relativeSubjectFromRef(n,e){const t=podResourcePath(n);if(!t)return null;const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const o=e.indexOf(s);if(o<0)continue;let l=e.slice(o+s.length);if(l.startsWith("/")&&(l=l.slice(1)),l.length>0)return l}return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)?normalizeResourcePath(e):null}function extractTemplateValues(n,e){if(!e.includes("{"))return n===e?{}:null;let t=0;const i=new Map,s=[];let o=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp(e.slice(o,u.index)));const h=`var${t++}`;i.set(h,parseTemplateVariableField$1(u[1]??"")),s.push(`(?<${h}>.+?)`),o=u.index+u[0].length}s.push(escapeRegExp(e.slice(o)));const l=`^${s.join("")}$`;try{const u=n.match(new RegExp(l));if(!u?.groups)return null;const h={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);if(!g||p===void 0)continue;const m=decodeURIComponent(p);if(g in h&&h[g]!==m)return null;h[g]=m}return h}catch{return null}}function escapeRegExp(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function parsePodResourceRef(n,e){if(!e)return null;const t=relativeSubjectFromRef(n,e);if(!t)return null;const i=qualifyFragmentResourceId(n,t),s=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n),o=s?extractTemplateValues(templateRelativeSubject(n,i),s):{id:decodeURIComponent(i)};return o?{resourceId:decodeURIComponent(i),templateValues:o}:null}function extractPodResourceTemplateValue(n,e,t="id"){return parsePodResourceRef(n,e)?.templateValues[t]??null}function resolvePodBaseUrl(n){const e=n.trim();return e?e.includes("/profile/card#me")?e.replace("/profile/card#me","").replace(/\/+$/u,""):e.replace(/\/+$/u,""):""}function resolvePodBaseUrlFromDatabase(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getDialect=="function"?e.getDialect():null,i=readPodUrl(t);if(i)return resolvePodBaseUrl(i);const s=typeof e.getSession=="function"?e.getSession():e.session,o=readPodUrl(s);if(o)return resolvePodBaseUrl(o);const l=readWebId(s);return l&&l.includes("/profile/card#me")?resolvePodBaseUrl(l):null}function normalizePodDataResourceId(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function resolvePodResourceId(n,e){const t=resolveKnownTargetIri(e);if(t)return parsePodResourceRef(n,t)?.resourceId??normalizePodDataResourceId(t);if(typeof e=="string")return assertCompleteStringResourceId(n,e),normalizePodDataResourceId(e);const i=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!i)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(i)||isTemplateCompleteResourceId(n,i))return normalizePodDataResourceId(i);const s=resolveDefaultResourceId(n,i,e);if(s)return normalizePodDataResourceId(s);const o=podResourceSubjectTemplate(n);return normalizePodDataResourceId(o?renderSubjectTemplateResourceId(o,i,e):i)}function buildPodResourceIri(n,e){const t=resolvePodBaseUrl(n);if(!t||/^https?:\/\//u.test(e))return e;const i=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(i.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(n,e,t){const i=resolveKnownTargetIri(t);if(i)return i;const s=resolvePodRootTargetPath(t);if(s)return buildPodResourceIri(n,s);const o=resolvePodResourceId(e,t),l=isResourceRelativeSubjectId(e,o)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(o)}`:e.resolveUri?.(o)??`/.data/${normalizePodDataResourceId(o)}`;return buildPodResourceIri(n,l)}function buildPodResourceIriForDatabase(n,e,t){const i=resolvePodBaseUrlFromDatabase(n);if(!i)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(i,e,t)}function resolvePodResourceIriForDatabase(n,e,t){if(!t)return null;try{return buildPodResourceIriForDatabase(n,e,t)}catch{return null}}function resolveKnownTargetIri(n){if(typeof n=="string")return/^https?:\/\//u.test(n)?n:null;const e=n["@id"]??n.subject;return typeof e=="string"&&/^https?:\/\//u.test(e)?e:null}function resolvePodRootTargetPath(n){if(typeof n=="string")return n.startsWith("/")?n:null;const e=typeof n.id=="string"?n.id.trim():"";return e.startsWith("/")?e:null}function isCompleteResourceId(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function assertCompleteStringResourceId(n,e){if(isCompleteResourceId(e)||isTemplateCompleteResourceId(n,e))return;const t=n.columns?.id?.options?.defaultValue!==void 0,i=podResourceSubjectTemplate(n);if(t||i)throw new Error("resolvePodResourceId does not accept local keys as string targets. Pass a structured row object with id and required fields, or pass a complete resource id/IRI.")}function resolveDefaultResourceId(n,e,t){const i=n.columns?.id?.options?.defaultValue;if(i===void 0)return null;if(typeof i=="string")return renderDefaultIdTemplate(i,{key:e,row:t,resource:n});if(typeof i!="function")return String(i);const s=i;return s.length===0?String(s()):String(s(e,t))}function renderSubjectTemplateResourceId(n,e,t){const i=n.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(i,{key:encodeURIComponent(e),row:t})}function readPodUrl(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getPodUrl=="function"?e.getPodUrl():e.info?.podUrl??e.podUrl;return typeof t=="string"&&t.trim().length>0?t:null}function readWebId(n){if(!n||typeof n!="object")return null;const e=n,t=e.info?.webId??e.webId;return typeof t=="string"&&t.trim().length>0?t:null}var _a$a;class PodTable{constructor(e,t,i){this.initialized=!1;const s=i.type;if(!s)throw new Error("podTable requires a type (RDF class) via options.type");const o=i.typeIndex,l=o==="private"||o==="public",u=this.resolveBase(i.base,e);this.resourcePath=u.resourcePath,this.containerPath=u.containerPath;const h=this.resolveSubjectTemplate(i.subjectTemplate,u.resourcePath,u.containerPath,e);this.subjectTemplate=h.template,this.hasCustomSubjectTemplate=h.isCustom,this.resourceMode=i.resourceMode??(i.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=i.sparqlEndpoint,this.registerTypeIndexEnabled=l&&i.autoRegister!==!1,this.config={name:e,base:u.resourcePath,type:resolveTermIri(s),namespace:i.namespace,typeIndex:l?o:void 0,saiRegistryPath:i.saiRegistryPath,autoRegister:i.autoRegister,containerPath:u.containerPath,hooks:i.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(i.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let d=0;for(const p of Object.values(t))if(p.options.primaryKey&&d++,p.table=this,p.tableName=e,!p.options.predicate&&!p._virtualId&&!i.namespace)throw new Error(`Column "${p.name}" in table "${e}" is missing a predicate.`);if(d!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${d}.`);this.$inferSelect={},this.$inferInsert={},this.$inferUpdate={},this._={brand:"Table",config:this.config,name:e,schema:void 0,columns:t,inferSelect:{},inferInsert:{},inferUpdate:{}},this.mapping=this.buildTableMapping()}getContainerPath(){return this.containerPath}getType(){return this.config.type}getRdfClass(){return this.getType()}getNamespace(){return this.config.namespace}getSubjectTemplate(){return this.subjectTemplate}buildId(e){return resolvePodResourceId(this,e)}buildIri(e,t){return buildPodResourceIriForResource(e,this,t)}buildIriForDatabase(e,t){return buildPodResourceIriForDatabase(e,this,t)}resolveIriForDatabase(e,t){return resolvePodResourceIriForDatabase(e,this,t)}parseRef(e){return parsePodResourceRef(this,e)}extractTemplateValue(e,t="id"){return extractPodResourceTemplateValue(this,e,t)}hasCustomTemplate(){return this.hasCustomSubjectTemplate}getSubClassOf(){return[...this.parentClasses]}getMapping(){return this.mapping}get $schema(){return new SolidSchema(this.columns,{type:this.config.type,namespace:this.config.namespace,subjectTemplate:this.subjectTemplate,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0})}resolveUri(e){const t=this.subjectTemplate;if(!t)return/^https?:\/\//.test(e)||e.startsWith("/")?e:`${this.config.base.endsWith("/")?this.config.base:`${this.config.base}/`}${e}`;const i=t.replace(/\{id\}/g,e);return i.startsWith("#")?`${this.resourcePath}${i}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${i}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const i=this.normalizeBaseInput(e),s=this.normalizeResourcePath(i);if(s.endsWith("/")){const l=this.ensureTrailingSlash(s);return{resourcePath:l,containerPath:l}}const o=this.ensureTrailingSlash(this.deriveContainerPath(s));return{resourcePath:s,containerPath:o}}normalizeBaseInput(e){const t=e.trim(),i=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(i){const[,s,o]=i,l=s.toLowerCase(),u=o.trim();return l==="http"||l==="https"?`${l}://${u}`:u.startsWith("/")?u:`/${u}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const i=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return i.startsWith("/")?i:`/${i}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,i=t.lastIndexOf("/");return i===-1?"/":t.slice(0,i+1)}ensureTrailingSlash(e){return e.endsWith("/")?e:`${e}/`}getResourcePath(){return this.resourcePath}getResourceMode(){return this.resourceMode}getSparqlEndpoint(){return this.sparqlEndpoint}shouldRegisterTypeIndex(){return this.registerTypeIndexEnabled}async init(e){await e.registerTable(this)}isInitialized(){return this.initialized}markInitialized(e=!0){this.initialized=e}setBase(e){const t=this.resolveBase(e,this.config.name);this.resourcePath=t.resourcePath,this.containerPath=t.containerPath,this.config.base=t.resourcePath,this.config.containerPath=t.containerPath,this._?.config&&(this._.config.base=this.config.base,this._.config.containerPath=this.config.containerPath),this.hasCustomSubjectTemplate||(this.subjectTemplate=void 0,delete this.config.subjectTemplate,this._?.config&&delete this._.config.subjectTemplate),this.mapping=this.buildTableMapping()}setSubjectTemplate(e){this.subjectTemplate=e,this.hasCustomSubjectTemplate=!0,this.config.subjectTemplate=e,this._?.config&&(this._.config.subjectTemplate=e),this.mapping=this.buildTableMapping()}setSparqlEndpoint(e){this.sparqlEndpoint=e,this.resourceMode||(this.resourceMode="sparql")}getColumns(){return this.columns}getColumn(e){return this.columns[e]}hasColumn(e){return e in this.columns}resolveSubjectTemplate(e,t,i,s){return e&&e.trim().length>0?{template:e.trim(),isCustom:!0}:{template:void 0,isCustom:!1}}buildTableMapping(){const e={};for(const t of Object.values(this.columns))e[t.name]=this.buildColumnMapping(t);return{name:this.config.name,type:this.config.type,subjectTemplate:this.subjectTemplate,namespace:this.config.namespace,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0,columns:e,relations:this.relations}}buildColumnMapping(e){const t=e._virtualId?"@id":e.getPredicate(this.config.namespace);return{column:e.name,predicate:t,kind:e.isLink()?"object":"datatype",datatype:this.inferColumnDatatype(e),linkTarget:e.getLinkTarget(),isArray:e.options.isArray??!1,inverse:e.isInverse()}}inferColumnDatatype(e){switch(e.dataType){case"string":return"http://www.w3.org/2001/XMLSchema#string";case"integer":return"http://www.w3.org/2001/XMLSchema#integer";case"boolean":return"http://www.w3.org/2001/XMLSchema#boolean";case"datetime":return"http://www.w3.org/2001/XMLSchema#dateTime";case"json":case"object":return"http://www.w3.org/2001/XMLSchema#json";default:return}}normalizeParents(e){if(!e)return[];const i=(Array.isArray(e)?e:[e]).map(s=>resolveTermIri(s)).filter(s=>s&&s.length>0);return Array.from(new Set(i))}}_a$a=entityKind;PodTable[_a$a]="PodTable";function podTable(n,e,t){const i={};for(const[s,o]of Object.entries(e)){if(o instanceof PodColumnBase){i[s]=o;continue}let l;switch(o.dataType){case"integer":l=new PodIntegerColumn(o.name,o.options);break;case"datetime":l=new PodDateTimeColumn(o.name,o.options);break;case"boolean":l=new PodBooleanColumn(o.name,o.options);break;case"json":l=new PodJsonColumn(o.name,o.options);break;case"object":l=new PodObjectColumn(o.name,o.options);break;case"array":{const h=o.elementType??o.options.baseType??"string";l=new PodArrayColumn(o.name,h,o.options);break}case"uri":l=new PodUriColumn(o.name,o.options);break;default:l=new PodStringColumn(o.name,o.options);break}const u=o.getPredicateUri?.();u&&l.predicate(u),i[s]=l}return new PodTable(n,i,t)}class SolidSchema{constructor(e,t){this.columns=e,this.options=t,this.$kind="SolidSchema",this.namespace=t.namespace,this.subjectTemplate=t.subjectTemplate,this.subClassOf=t.subClassOf?Array.isArray(t.subClassOf)?t.subClassOf.map(resolveTermIri):[resolveTermIri(t.subClassOf)]:void 0}table(e,t){return new PodTable(e,this.columns,{...this.options,...t})}extend(e,t){const i=mergeSchemaColumns(this,e),s=[this.type];return this.subClassOf&&s.push(...this.subClassOf),solidSchema(i,{...t,subClassOf:s})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(n,e){const t={};for(const[i,s]of Object.entries(n)){if(s instanceof PodColumnBase){t[i]=s;continue}let 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 l=s.getPredicateUri?.();l&&o.predicate(l),t[i]=o}return new SolidSchema(t,e)}function isSolidSchema(n){return n instanceof SolidSchema||n?.$kind==="SolidSchema"}const index=Object.freeze(Object.defineProperty({__proto__:null,ColumnBuilder,PodArrayColumn,PodBooleanColumn,PodColumnBase,PodDateTimeColumn,PodIntegerColumn,PodJsonColumn,PodObjectColumn,PodStringColumn,PodTable,PodUriColumn,SolidSchema,boolean:boolean$2,date:date$3,generateNanoId,hasStringValue:hasStringValue$2,hasTermValue,id,integer:integer$1,isSolidSchema,mergeSchemaColumns,object:object$1,podTable,real,resolveTermIri,solidSchema,string:string$2,text,timestamp,uri,validateColumnOverride},Symbol.toStringTag,{value:"Module"})),XSD$9="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(n,e){if(!n)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const s=e.getMapping()?.columns?.[n.name];if(s?.predicate)return s.predicate}if(typeof n.getPredicateUri=="function")return n.getPredicateUri();if(n._predicateUri)return n._predicateUri;if(n.predicate&&typeof n.predicate=="string")return n.predicate;const t=e instanceof SolidSchema?e.options.namespace:e.config.namespace;if(typeof n.getPredicate=="function")try{return n.getPredicate(t)}catch{}return n.options?.predicate?n.options.predicate:t?`${typeof t=="string"?t:t.uri}${n.name}`:(n.name==="id"&&console.log("[DEBUG] getPredicateForColumn 'id' fallback to example.org. Column:",n),`http://example.org/${n.name}`)}function formatValue(n,e,t,i){return Array.isArray(n)?n.map(s=>formatSingleValue(s,e,t,i)):formatSingleValue(n,e,t,i)}function formatSingleValue(n,e,t,i){if(n==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const s=String(n);if(s.startsWith("<")&&s.endsWith(">")){const o=s.slice(1,-1);return t&&!t.isAbsoluteUri(o)?`<${t.resolveLink(o,e,i)}>`:s}return t?`<${t.resolveLink(s,e,i)}>`:s.startsWith("<")?s:`<${s}>`}return typeof n=="string"?!e&&(n.startsWith("http://")||n.startsWith("https://"))?`<${n}>`:`"${n.replace(/\\/g,"\\\\").replace(/"/g,'"')}"`:typeof n=="number"?Number.isInteger(n)?String(n):`"${n}"^^<${XSD$9}decimal>`:typeof n=="boolean"?`"${n}"^^<${XSD$9}boolean>`:n instanceof Date?`"${n.toISOString()}"^^<${XSD$9}dateTime>`:`"${String(n)}"`}function resolveColumn(n,e){if(n&&typeof n=="object"&&n instanceof PodColumnBase)return n;if(n&&typeof n=="object"&&"name"in n){const t=n.name;if(typeof t=="string"&&e.columns[t])return e.columns[t]}if(typeof n=="string"){const t=e.columns[n];if(t)return t}throw new Error(`Unable to resolve column reference for select field: ${String(n)}`)}function generateSubjectUri(n,e,t){const i=t.resolveSubject(e,n);if(!i)throw new Error("Failed to generate subject URI");return i}var _a$9;class SPARQLExpression{constructor(){this[_a$9]="SPARQLExpression"}}_a$9=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,i){super(),this.left=e,this.operator=t,this.right=i,this.type="binary_expr"}}class LogicalExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.expressions=t,this.type="logical_expr"}}class UnaryExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.value=t,this.type="unary_expr"}}class SelectionAliasExpression extends SPARQLExpression{constructor(e){super(),this.alias=e}}function eq(n,e){return new BinaryExpression(n,"=",e)}function like(n,e){return new BinaryExpression(n,"LIKE",e)}function inArray(n,e){return new BinaryExpression(n,"IN",e)}function and(...n){return new LogicalExpression("AND",n.filter(Boolean))}function or(...n){return new LogicalExpression("OR",n.filter(Boolean))}function parseActivityStreamsMessage(n){const e=JSON.parse(n);return{id:e.id||e["@id"]||"",type:e.type,object:typeof e.object=="string"?e.object:e.object?.id||e.object?.["@id"]||"",published:e.published||new Date().toISOString(),state:e.state}}class BaseChannel{constructor(e){this._connected=!1,this.config=e}get connected(){return this._connected}handleMessage(e){try{const t=parseActivityStreamsMessage(e);this.config.onNotification(t)}catch(t){this.handleError(new Error(`Failed to parse notification: ${t}`))}}handleError(e){this.config.onError?this.config.onError(e):console.error("[NotificationChannel] Error:",e)}handleClose(){this._connected=!1,this.config.onClose&&this.config.onClose()}}class SSEChannel extends BaseChannel{constructor(e){super(e),this.abortController=null,this.reader=null,this.contentType=""}async connect(){if(this._connected)return;this.abortController=new AbortController;const e=this.config.fetch||fetch;try{const t=`notify-sse-${Date.now()}`,i=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!i.ok)throw new Error(`SSE connection failed: ${i.status} ${i.statusText}`);if(!i.body)throw new Error("SSE response has no body");this.contentType=i.headers.get("content-type")||"",this._connected=!0,this.reader=i.body.getReader(),this.readStream()}catch(t){throw t.name!=="AbortError"&&this.handleError(t),t}}disconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader&&(this.reader.cancel().catch(()=>{}),this.reader=null),this._connected=!1,this.handleClose()}async readStream(){if(!this.reader)return;const e=new TextDecoder;let t="";try{for(;this._connected;){const{done:i,value:s}=await this.reader.read();if(i){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const o=e.decode(s,{stream:!0});t+=o,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(i){i.name!=="AbortError"&&this.handleError(i)}}processTurtleBuffer(e){const t=e.split(`
12
+ Please change the parent <Route path="${x}"> to <Route path="${x==="/"?"*":`${x}/*`}">.`)}let p=useLocation(),g;g=p;let m=g.pathname||"/",v=m;if(h!=="/"){let x=h.replace(/^\//,"").split("/");v="/"+m.replace(/^\//,"").split("/").slice(x.length).join("/")}let S=t&&t.state.matches.length?t.state.matches.map(x=>Object.assign(x,{route:t.manifest[x.route.id]||x.route})):matchRoutes(n,{pathname:v});return warning(d||S!=null,`No routes matched location "${g.pathname}${g.search}${g.hash}" `),warning(S==null||S[S.length-1].route.element!==void 0||S[S.length-1].route.Component!==void 0||S[S.length-1].route.lazy!==void 0,`Matched leaf route at location "${g.pathname}${g.search}${g.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`),_renderMatches(S&&S.map(x=>Object.assign({},x,{params:Object.assign({},l,x.params),pathname:joinPaths([h,i.encodeLocation?i.encodeLocation(x.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:x.pathname]),pathnameBase:x.pathnameBase==="/"?h:joinPaths([h,i.encodeLocation?i.encodeLocation(x.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:x.pathnameBase])})),s,t)}function DefaultErrorComponent(){let n=useRouteError(),e=isRouteErrorResponse(n)?`${n.status} ${n.statusText}`:n instanceof Error?n.message:JSON.stringify(n),t=n instanceof Error?n.stack:null,i="rgba(200,200,200, 0.5)",s={padding:"0.5rem",backgroundColor:i},o={padding:"2px 4px",backgroundColor:i},l=null;return console.error("Error handled by React Router default ErrorBoundary:",n),l=reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("p",null,"💿 Hey developer 👋"),reactExports.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",reactExports.createElement("code",{style:o},"ErrorBoundary")," or"," ",reactExports.createElement("code",{style:o},"errorElement")," prop on your route.")),reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("h2",null,"Unexpected Application Error!"),reactExports.createElement("h3",{style:{fontStyle:"italic"}},e),t?reactExports.createElement("pre",{style:s},t):null,l)}var defaultErrorElement=reactExports.createElement(DefaultErrorComponent,null),RenderErrorBoundary=class extends reactExports.Component{constructor(n){super(n),this.state={location:n.location,revalidation:n.revalidation,error:n.error}}static getDerivedStateFromError(n){return{error:n}}static getDerivedStateFromProps(n,e){return e.location!==n.location||e.revalidation!=="idle"&&n.revalidation==="idle"?{error:n.error,location:n.location,revalidation:n.revalidation}:{error:n.error!==void 0?n.error:e.error,location:e.location,revalidation:n.revalidation||e.revalidation}}componentDidCatch(n,e){this.props.onError?this.props.onError(n,e):console.error("React Router caught the following error during render",n)}render(){let n=this.state.error;if(this.context&&typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){const t=decodeRouteErrorResponseDigest(n.digest);t&&(n=t)}let e=n!==void 0?reactExports.createElement(RouteContext.Provider,{value:this.props.routeContext},reactExports.createElement(RouteErrorContext.Provider,{value:n,children:this.props.component})):this.props.children;return this.context?reactExports.createElement(RSCErrorHandler,{error:n},e):e}};RenderErrorBoundary.contextType=RSCRouterContext;var errorRedirectHandledMap=new WeakMap;function RSCErrorHandler({children:n,error:e}){let{basename:t}=reactExports.useContext(NavigationContext);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let i=decodeRedirectErrorDigest(e.digest);if(i){let s=errorRedirectHandledMap.get(e);if(s)throw s;let o=parseToInfo(i.location,t),l=o.absoluteURL||o.to;if(hasInvalidProtocol(l))throw new Error("Invalid redirect location");if(isBrowser$1&&!errorRedirectHandledMap.get(e))if(o.isExternal||i.reloadDocument)window.location.href=l;else{const u=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(o.to,{replace:i.replace}));throw errorRedirectHandledMap.set(e,u),u}return reactExports.createElement("meta",{httpEquiv:"refresh",content:`0;url=${l}`})}}return n}function RenderedRoute({routeContext:n,match:e,children:t}){let i=reactExports.useContext(DataRouterContext);return i&&i.static&&i.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=e.route.id),reactExports.createElement(RouteContext.Provider,{value:n},t)}function _renderMatches(n,e=[],t){let i=t?.state;if(n==null){if(!i)return null;if(i.errors)n=i.matches;else if(e.length===0&&!i.initialized&&i.matches.length>0)n=i.matches;else return null}let s=n,o=i?.errors;if(o!=null){let p=s.findIndex(g=>g.route.id&&o?.[g.route.id]!==void 0);invariant(p>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(",")}`),s=s.slice(0,Math.min(s.length,p+1))}let l=!1,u=-1;if(t&&i){l=i.renderFallback;for(let p=0;p<s.length;p++){let g=s[p];if((g.route.HydrateFallback||g.route.hydrateFallbackElement)&&(u=p),g.route.id){let{loaderData:m,errors:v}=i,S=g.route.loader&&!m.hasOwnProperty(g.route.id)&&(!v||v[g.route.id]===void 0);if(g.route.lazy||S){t.isStatic&&(l=!0),u>=0?s=s.slice(0,u+1):s=[s[0]];break}}}}let h=t?.onError,d=i&&h?(p,g)=>{h(p,{location:i.location,params:i.matches?.[0]?.params??{},pattern:getRoutePattern(i.matches),errorInfo:g})}:void 0;return s.reduceRight((p,g,m)=>{let v,S=!1,E=null,x=null;i&&(v=o&&g.route.id?o[g.route.id]:void 0,E=g.route.errorElement||defaultErrorElement,l&&(u<0&&m===0?(warningOnce("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),S=!0,x=null):u===m&&(S=!0,x=g.route.hydrateFallbackElement||null)));let A=e.concat(s.slice(0,m+1)),C=()=>{let T;return v?T=E:S?T=x:g.route.Component?T=reactExports.createElement(g.route.Component,null):g.route.element?T=g.route.element:T=p,reactExports.createElement(RenderedRoute,{match:g,routeContext:{outlet:p,matches:A,isDataRoute:i!=null},children:T})};return i&&(g.route.ErrorBoundary||g.route.errorElement||m===0)?reactExports.createElement(RenderErrorBoundary,{location:i.location,revalidation:i.revalidation,component:E,error:v,children:C(),routeContext:{outlet:null,matches:A,isDataRoute:!0},onError:d}):C()},null)}function getDataRouterConsoleError(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError(n)),e}function useDataRouterState(n){let e=reactExports.useContext(DataRouterStateContext);return invariant(e,getDataRouterConsoleError(n)),e}function useRouteContext(n){let e=reactExports.useContext(RouteContext);return invariant(e,getDataRouterConsoleError(n)),e}function useCurrentRouteId(n){let e=useRouteContext(n),t=e.matches[e.matches.length-1];return invariant(t.route.id,`${n} can only be used on routes that contain a unique "id"`),t.route.id}function useRouteId(){return useCurrentRouteId("useRouteId")}function useRouteError(){let n=reactExports.useContext(RouteErrorContext),e=useDataRouterState("useRouteError"),t=useCurrentRouteId("useRouteError");return n!==void 0?n:e.errors?.[t]}function useNavigateStable(){let{router:n}=useDataRouterContext("useNavigate"),e=useCurrentRouteId("useNavigate"),t=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{t.current=!0}),reactExports.useCallback(async(s,o={})=>{warning(t.current,navigateEffectWarning),t.current&&(typeof s=="number"?await n.navigate(s):await n.navigate(s,{fromRouteId:e,...o}))},[n,e])}var alreadyWarned={};function warningOnce(n,e,t){!e&&!alreadyWarned[n]&&(alreadyWarned[n]=!0,warning(!1,t))}reactExports.memo(DataRoutes2);function DataRoutes2({routes:n,manifest:e,future:t,state:i,isStatic:s,onError:o}){return useRoutesImpl(n,void 0,{manifest:e,state:i,isStatic:s,onError:o})}function Navigate({to:n,replace:e,state:t,relative:i}){invariant(useInRouterContext(),"<Navigate> may be used only in the context of a <Router> component.");let{static:s}=reactExports.useContext(NavigationContext);warning(!s,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:o}=reactExports.useContext(RouteContext),{pathname:l}=useLocation(),u=useNavigate(),h=resolveTo(n,getResolveToMatches(o),l,i==="path"),d=JSON.stringify(h);return reactExports.useEffect(()=>{u(JSON.parse(d),{replace:e,state:t,relative:i})},[u,d,i,e,t]),null}function Outlet(n){return useOutlet(n.context)}function Router({basename:n="/",children:e=null,location:t,navigationType:i="POP",navigator:s,static:o=!1,useTransitions:l}){invariant(!useInRouterContext(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let u=n.replace(/^\/*/,"/"),h=reactExports.useMemo(()=>({basename:u,navigator:s,static:o,useTransitions:l,future:{}}),[u,s,o,l]);typeof t=="string"&&(t=parsePath(t));let{pathname:d="/",search:p="",hash:g="",state:m=null,key:v="default",mask:S}=t,E=reactExports.useMemo(()=>{let x=stripBasename(d,u);return x==null?null:{location:{pathname:x,search:p,hash:g,state:m,key:v,mask:S},navigationType:i}},[u,d,p,g,m,v,i,S]);return warning(E!=null,`<Router basename="${u}"> is not able to match the URL "${d}${p}${g}" because it does not start with the basename, so the <Router> won't render anything.`),E==null?null:reactExports.createElement(NavigationContext.Provider,{value:h},reactExports.createElement(LocationContext.Provider,{children:e,value:E}))}var defaultMethod="get",defaultEncType="application/x-www-form-urlencoded";function isHtmlElement(n){return typeof HTMLElement<"u"&&n instanceof HTMLElement}function isButtonElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="button"}function isFormElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="form"}function isInputElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="input"}function isModifiedEvent(n){return!!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey)}function shouldProcessLinkClick(n,e){return n.button===0&&(!e||e==="_self")&&!isModifiedEvent(n)}var _formDataSupportsSubmitter=null;function isFormDataSubmitterSupported(){if(_formDataSupportsSubmitter===null)try{new FormData(document.createElement("form"),0),_formDataSupportsSubmitter=!1}catch{_formDataSupportsSubmitter=!0}return _formDataSupportsSubmitter}var supportedFormEncTypes=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function getFormEncType(n){return n!=null&&!supportedFormEncTypes.has(n)?(warning(!1,`"${n}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`),null):n}function getFormSubmissionInfo(n,e){let t,i,s,o,l;if(isFormElement(n)){let u=n.getAttribute("action");i=u?stripBasename(u,e):null,t=n.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("enctype"))||defaultEncType,o=new FormData(n)}else if(isButtonElement(n)||isInputElement(n)&&(n.type==="submit"||n.type==="image")){let u=n.form;if(u==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let h=n.getAttribute("formaction")||u.getAttribute("action");if(i=h?stripBasename(h,e):null,t=n.getAttribute("formmethod")||u.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("formenctype"))||getFormEncType(u.getAttribute("enctype"))||defaultEncType,o=new FormData(u,n),!isFormDataSubmitterSupported()){let{name:d,type:p,value:g}=n;if(p==="image"){let m=d?`${d}.`:"";o.append(`${m}x`,"0"),o.append(`${m}y`,"0")}else d&&o.append(d,g)}}else{if(isHtmlElement(n))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');t=defaultMethod,i=null,s=defaultEncType,l=n}return o&&s==="text/plain"&&(l=o,o=void 0),{action:i,method:t.toLowerCase(),encType:s,formData:o,body:l}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function invariant2(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function singleFetchUrl(n,e,t,i){let s=typeof n=="string"?new URL(n,typeof window>"u"?"server://singlefetch/":window.location.origin):n;return t?s.pathname.endsWith("/")?s.pathname=`${s.pathname}_.${i}`:s.pathname=`${s.pathname}.${i}`:s.pathname==="/"?s.pathname=`_root.${i}`:e&&stripBasename(s.pathname,e)==="/"?s.pathname=`${removeTrailingSlash(e)}/_root.${i}`:s.pathname=`${removeTrailingSlash(s.pathname)}.${i}`,s}async function loadRouteModule(n,e){if(n.id in e)return e[n.id];try{let t=await import(n.module);return e[n.id]=t,t}catch(t){return console.error(`Error loading route module \`${n.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function isHtmlLinkDescriptor(n){return n==null?!1:n.href==null?n.rel==="preload"&&typeof n.imageSrcSet=="string"&&typeof n.imageSizes=="string":typeof n.rel=="string"&&typeof n.href=="string"}async function getKeyedPrefetchLinks(n,e,t){let i=await Promise.all(n.map(async s=>{let o=e.routes[s.route.id];if(o){let l=await loadRouteModule(o,t);return l.links?l.links():[]}return[]}));return dedupeLinkDescriptors(i.flat(1).filter(isHtmlLinkDescriptor).filter(s=>s.rel==="stylesheet"||s.rel==="preload").map(s=>s.rel==="stylesheet"?{...s,rel:"prefetch",as:"style"}:{...s,rel:"prefetch"}))}function getNewMatchesForLinks(n,e,t,i,s,o){let l=(h,d)=>t[d]?h.route.id!==t[d].route.id:!0,u=(h,d)=>t[d].pathname!==h.pathname||t[d].route.path?.endsWith("*")&&t[d].params["*"]!==h.params["*"];return o==="assets"?e.filter((h,d)=>l(h,d)||u(h,d)):o==="data"?e.filter((h,d)=>{let p=i.routes[h.route.id];if(!p||!p.hasLoader)return!1;if(l(h,d)||u(h,d))return!0;if(h.route.shouldRevalidate){let g=h.route.shouldRevalidate({currentUrl:new URL(s.pathname+s.search+s.hash,window.origin),currentParams:t[0]?.params||{},nextUrl:new URL(n,window.origin),nextParams:h.params,defaultShouldRevalidate:!0});if(typeof g=="boolean")return g}return!0}):[]}function getModuleLinkHrefs(n,e,{includeHydrateFallback:t}={}){return dedupeHrefs(n.map(i=>{let s=e.routes[i.route.id];if(!s)return[];let o=[s.module];return s.clientActionModule&&(o=o.concat(s.clientActionModule)),s.clientLoaderModule&&(o=o.concat(s.clientLoaderModule)),t&&s.hydrateFallbackModule&&(o=o.concat(s.hydrateFallbackModule)),s.imports&&(o=o.concat(s.imports)),o}).flat(1))}function dedupeHrefs(n){return[...new Set(n)]}function sortKeys(n){let e={},t=Object.keys(n).sort();for(let i of t)e[i]=n[i];return e}function dedupeLinkDescriptors(n,e){let t=new Set;return new Set(e),n.reduce((i,s)=>{let o=JSON.stringify(sortKeys(s));return t.has(o)||(t.add(o),i.push({key:o,link:s})),i},[])}function useDataRouterContext2(){let n=reactExports.useContext(DataRouterContext);return invariant2(n,"You must render this element inside a <DataRouterContext.Provider> element"),n}function useDataRouterStateContext(){let n=reactExports.useContext(DataRouterStateContext);return invariant2(n,"You must render this element inside a <DataRouterStateContext.Provider> element"),n}var FrameworkContext=reactExports.createContext(void 0);FrameworkContext.displayName="FrameworkContext";function useFrameworkContext(){let n=reactExports.useContext(FrameworkContext);return invariant2(n,"You must render this element inside a <HydratedRouter> element"),n}function usePrefetchBehavior(n,e){let t=reactExports.useContext(FrameworkContext),[i,s]=reactExports.useState(!1),[o,l]=reactExports.useState(!1),{onFocus:u,onBlur:h,onMouseEnter:d,onMouseLeave:p,onTouchStart:g}=e,m=reactExports.useRef(null);reactExports.useEffect(()=>{if(n==="render"&&l(!0),n==="viewport"){let E=A=>{A.forEach(C=>{l(C.isIntersecting)})},x=new IntersectionObserver(E,{threshold:.5});return m.current&&x.observe(m.current),()=>{x.disconnect()}}},[n]),reactExports.useEffect(()=>{if(i){let E=setTimeout(()=>{l(!0)},100);return()=>{clearTimeout(E)}}},[i]);let v=()=>{s(!0)},S=()=>{s(!1),l(!1)};return t?n!=="intent"?[o,m,{}]:[o,m,{onFocus:composeEventHandlers(u,v),onBlur:composeEventHandlers(h,S),onMouseEnter:composeEventHandlers(d,v),onMouseLeave:composeEventHandlers(p,S),onTouchStart:composeEventHandlers(g,v)}]:[!1,m,{}]}function composeEventHandlers(n,e){return t=>{n&&n(t),t.defaultPrevented||e(t)}}function PrefetchPageLinks({page:n,...e}){let t=useIsRSCRouterContext(),{nonce:i}=useFrameworkContext(),{router:s}=useDataRouterContext2(),o=reactExports.useMemo(()=>matchRoutes(s.routes,n,s.basename),[s.routes,n,s.basename]);return o?(e.nonce==null&&i&&(e={...e,nonce:i}),t?reactExports.createElement(RSCPrefetchPageLinksImpl,{page:n,matches:o,...e}):reactExports.createElement(PrefetchPageLinksImpl,{page:n,matches:o,...e})):null}function useKeyedPrefetchLinks(n){let{manifest:e,routeModules:t}=useFrameworkContext(),[i,s]=reactExports.useState([]);return reactExports.useEffect(()=>{let o=!1;return getKeyedPrefetchLinks(n,e,t).then(l=>{o||s(l)}),()=>{o=!0}},[n,e,t]),i}function RSCPrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s}=useFrameworkContext(),{basename:o}=useDataRouterContext2(),l=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let u=singleFetchUrl(n,o,s.v8_trailingSlashAwareDataRequests,"rsc"),h=!1,d=[];for(let p of e)typeof p.route.shouldRevalidate=="function"?h=!0:d.push(p.route.id);return h&&d.length>0&&u.searchParams.set("_routes",d.join(",")),[u.pathname+u.search]},[o,s.v8_trailingSlashAwareDataRequests,n,i,e]);return reactExports.createElement(reactExports.Fragment,null,l.map(u=>reactExports.createElement("link",{key:u,rel:"prefetch",as:"fetch",href:u,...t})))}function PrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s,manifest:o,routeModules:l}=useFrameworkContext(),{basename:u}=useDataRouterContext2(),{loaderData:h,matches:d}=useDataRouterStateContext(),p=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,o,i,"data"),[n,e,d,o,i]),g=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,o,i,"assets"),[n,e,d,o,i]),m=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let E=new Set,x=!1;if(e.forEach(C=>{let T=o.routes[C.route.id];!T||!T.hasLoader||(!p.some(F=>F.route.id===C.route.id)&&C.route.id in h&&l[C.route.id]?.shouldRevalidate||T.hasClientLoader?x=!0:E.add(C.route.id))}),E.size===0)return[];let A=singleFetchUrl(n,u,s.v8_trailingSlashAwareDataRequests,"data");return x&&E.size>0&&A.searchParams.set("_routes",e.filter(C=>E.has(C.route.id)).map(C=>C.route.id).join(",")),[A.pathname+A.search]},[u,s.v8_trailingSlashAwareDataRequests,h,i,o,p,e,n,l]),v=reactExports.useMemo(()=>getModuleLinkHrefs(g,o),[g,o]),S=useKeyedPrefetchLinks(g);return reactExports.createElement(reactExports.Fragment,null,m.map(E=>reactExports.createElement("link",{key:E,rel:"prefetch",as:"fetch",href:E,...t})),v.map(E=>reactExports.createElement("link",{key:E,rel:"modulepreload",href:E,...t})),S.map(({key:E,link:x})=>reactExports.createElement("link",{key:E,nonce:t.nonce,...x,crossOrigin:x.crossOrigin??t.crossOrigin})))}function mergeRefs(...n){return e=>{n.forEach(t=>{typeof t=="function"?t(e):t!=null&&(t.current=e)})}}var isBrowser2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{isBrowser2&&(window.__reactRouterVersion="7.18.2")}catch{}function BrowserRouter({basename:n,children:e,useTransitions:t,window:i}){let s=reactExports.useRef();s.current==null&&(s.current=createBrowserHistory({window:i,v5Compat:!0}));let o=s.current,[l,u]=reactExports.useState({action:o.action,location:o.location}),h=reactExports.useCallback(d=>{t===!1?u(d):reactExports.startTransition(()=>u(d))},[t]);return reactExports.useLayoutEffect(()=>o.listen(h),[o,h]),reactExports.createElement(Router,{basename:n,children:e,location:l.location,navigationType:l.action,navigator:o,useTransitions:t})}var Link=reactExports.forwardRef(function({onClick:e,discover:t="render",prefetch:i="none",relative:s,reloadDocument:o,replace:l,mask:u,state:h,target:d,to:p,preventScrollReset:g,viewTransition:m,defaultShouldRevalidate:v,...S},E){let{basename:x,navigator:A,useTransitions:C}=reactExports.useContext(NavigationContext),T=typeof p=="string"&&ABSOLUTE_URL_REGEX.test(p),F=parseToInfo(p,x);p=F.to;let P=useHref(p,{relative:s}),q=useLocation(),O=null;if(u){let ke=resolveTo(u,[],q.mask?q.mask.pathname:"/",!0);x!=="/"&&(ke.pathname=ke.pathname==="/"?x:joinPaths([x,ke.pathname])),O=A.createHref(ke)}let[G,fe,M]=usePrefetchBehavior(i,S),ee=useLinkClickHandler(p,{replace:l,mask:u,state:h,target:d,preventScrollReset:g,relative:s,viewTransition:m,defaultShouldRevalidate:v,useTransitions:C});function Se(ke){e&&e(ke),ke.defaultPrevented||ee(ke)}let re=!(F.isExternal||o),Ae=reactExports.createElement("a",{...S,...M,href:(re?O:void 0)||F.absoluteURL||P,onClick:re?Se:e,ref:mergeRefs(E,fe),target:d,"data-discover":!T&&t==="render"?"true":void 0});return G&&!T?reactExports.createElement(reactExports.Fragment,null,Ae,reactExports.createElement(PrefetchPageLinks,{page:P})):Ae});Link.displayName="Link";var NavLink=reactExports.forwardRef(function({"aria-current":e="page",caseSensitive:t=!1,className:i="",end:s=!1,style:o,to:l,viewTransition:u,children:h,...d},p){let g=useResolvedPath(l,{relative:d.relative}),m=useLocation(),v=reactExports.useContext(DataRouterStateContext),{navigator:S,basename:E}=reactExports.useContext(NavigationContext),x=v!=null&&useViewTransitionState(g)&&u===!0,A=S.encodeLocation?S.encodeLocation(g).pathname:g.pathname,C=m.pathname,T=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;t||(C=C.toLowerCase(),T=T?T.toLowerCase():null,A=A.toLowerCase()),T&&E&&(T=stripBasename(T,E)||T);const F=A!=="/"&&A.endsWith("/")?A.length-1:A.length;let P=C===A||!s&&C.startsWith(A)&&C.charAt(F)==="/",q=T!=null&&(T===A||!s&&T.startsWith(A)&&T.charAt(A.length)==="/"),O={isActive:P,isPending:q,isTransitioning:x},G=P?e:void 0,fe;typeof i=="function"?fe=i(O):fe=[i,P?"active":null,q?"pending":null,x?"transitioning":null].filter(Boolean).join(" ");let M=typeof o=="function"?o(O):o;return reactExports.createElement(Link,{...d,"aria-current":G,className:fe,ref:p,style:M,to:l,viewTransition:u},typeof h=="function"?h(O):h)});NavLink.displayName="NavLink";var Form=reactExports.forwardRef(({discover:n="render",fetcherKey:e,navigate:t,reloadDocument:i,replace:s,state:o,method:l=defaultMethod,action:u,onSubmit:h,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m,...v},S)=>{let{useTransitions:E}=reactExports.useContext(NavigationContext),x=useSubmit(),A=useFormAction(u,{relative:d}),C=l.toLowerCase()==="get"?"get":"post",T=typeof u=="string"&&ABSOLUTE_URL_REGEX.test(u),F=P=>{if(h&&h(P),P.defaultPrevented)return;P.preventDefault();let q=P.nativeEvent.submitter,O=q?.getAttribute("formmethod")||l,G=()=>x(q||P.currentTarget,{fetcherKey:e,method:O,navigate:t,replace:s,state:o,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m});E&&t!==!1?reactExports.startTransition(()=>G()):G()};return reactExports.createElement("form",{ref:S,method:C,action:A,onSubmit:i?h:F,...v,"data-discover":!T&&n==="render"?"true":void 0})});Form.displayName="Form";function getDataRouterConsoleError2(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext3(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError2(n)),e}function useLinkClickHandler(n,{target:e,replace:t,mask:i,state:s,preventScrollReset:o,relative:l,viewTransition:u,defaultShouldRevalidate:h,useTransitions:d}={}){let p=useNavigate(),g=useLocation(),m=useResolvedPath(n,{relative:l});return reactExports.useCallback(v=>{if(shouldProcessLinkClick(v,e)){v.preventDefault();let S=t!==void 0?t:createPath(g)===createPath(m),E=()=>p(n,{replace:S,mask:i,state:s,preventScrollReset:o,relative:l,viewTransition:u,defaultShouldRevalidate:h});d?reactExports.startTransition(()=>E()):E()}},[g,p,m,t,i,s,e,n,o,l,u,h,d])}var fetcherId=0,getUniqueFetcherId=()=>`__${String(++fetcherId)}__`;function useSubmit(){let{router:n}=useDataRouterContext3("useSubmit"),{basename:e}=reactExports.useContext(NavigationContext),t=useRouteId(),i=n.fetch,s=n.navigate;return reactExports.useCallback(async(o,l={})=>{let{action:u,method:h,encType:d,formData:p,body:g}=getFormSubmissionInfo(o,e);if(l.navigate===!1){let m=l.fetcherKey||getUniqueFetcherId();await i(m,t,l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,flushSync:l.flushSync})}else await s(l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,replace:l.replace,state:l.state,fromRouteId:t,flushSync:l.flushSync,viewTransition:l.viewTransition})},[i,s,e,t])}function useFormAction(n,{relative:e}={}){let{basename:t}=reactExports.useContext(NavigationContext),i=reactExports.useContext(RouteContext);invariant(i,"useFormAction must be used inside a RouteContext");let[s]=i.matches.slice(-1),o={...useResolvedPath(n||".",{relative:e})},l=useLocation();if(n==null){o.search=l.search;let u=new URLSearchParams(o.search),h=u.getAll("index");if(h.some(p=>p==="")){u.delete("index"),h.filter(g=>g).forEach(g=>u.append("index",g));let p=u.toString();o.search=p?`?${p}`:""}}return(!n||n===".")&&s.route.index&&(o.search=o.search?o.search.replace(/^\?/,"?index&"):"?index"),t!=="/"&&(o.pathname=o.pathname==="/"?t:joinPaths([t,o.pathname])),createPath(o)}function useViewTransitionState(n,{relative:e}={}){let t=reactExports.useContext(ViewTransitionContext);invariant(t!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:i}=useDataRouterContext3("useViewTransitionState"),s=useResolvedPath(n,{relative:e});if(!t.isTransitioning)return!1;let o=stripBasename(t.currentLocation.pathname,i)||t.currentLocation.pathname,l=stripBasename(t.nextLocation.pathname,i)||t.nextLocation.pathname;return matchPath(s.pathname,l)!=null||matchPath(s.pathname,o)!=null}const mergeClasses=(...n)=>n.filter((e,t,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===t).join(" ").trim();const toKebabCase=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const toCamelCase=n=>n.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,i)=>i?i.toUpperCase():t.toLowerCase());const toPascalCase=n=>{const e=toCamelCase(n);return e.charAt(0).toUpperCase()+e.slice(1)};var defaultAttributes={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const hasA11yProp=n=>{for(const e in n)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};const Icon=reactExports.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:i,className:s="",children:o,iconNode:l,...u},h)=>reactExports.createElement("svg",{ref:h,...defaultAttributes,width:e,height:e,stroke:n,strokeWidth:i?Number(t)*24/Number(e):t,className:mergeClasses("lucide",s),...!o&&!hasA11yProp(u)&&{"aria-hidden":"true"},...u},[...l.map(([d,p])=>reactExports.createElement(d,p)),...Array.isArray(o)?o:[o]]));const createLucideIcon=(n,e)=>{const t=reactExports.forwardRef(({className:i,...s},o)=>reactExports.createElement(Icon,{ref:o,iconNode:e,className:mergeClasses(`lucide-${toKebabCase(toPascalCase(n))}`,`lucide-${n}`,i),...s}));return t.displayName=toPascalCase(n),t};const __iconNode$g=[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M9 13a4.5 4.5 0 0 0 3-4",key:"10igwf"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M12 13h4",key:"1ku699"}],["path",{d:"M12 18h6a2 2 0 0 1 2 2v1",key:"105ag5"}],["path",{d:"M12 8h8",key:"1lhi5i"}],["path",{d:"M16 8V5a2 2 0 0 1 2-2",key:"u6izg6"}],["circle",{cx:"16",cy:"13",r:".5",key:"ry7gng"}],["circle",{cx:"18",cy:"3",r:".5",key:"1aiba7"}],["circle",{cx:"20",cy:"21",r:".5",key:"yhc1fs"}],["circle",{cx:"20",cy:"8",r:".5",key:"1e43v0"}]],BrainCircuit=createLucideIcon("brain-circuit",__iconNode$g);const __iconNode$f=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ChevronRight=createLucideIcon("chevron-right",__iconNode$f);const __iconNode$e=[["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("circle-alert",__iconNode$e);const __iconNode$d=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],CircleCheckBig=createLucideIcon("circle-check-big",__iconNode$d);const __iconNode$c=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],CircleCheck=createLucideIcon("circle-check",__iconNode$c);const __iconNode$b=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Clock=createLucideIcon("clock",__iconNode$b);const __iconNode$a=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Copy=createLucideIcon("copy",__iconNode$a);const __iconNode$9=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Database=createLucideIcon("database",__iconNode$9);const __iconNode$8=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Gauge=createLucideIcon("gauge",__iconNode$8);const __iconNode$7=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Globe=createLucideIcon("globe",__iconNode$7);const __iconNode$6=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Layers=createLucideIcon("layers",__iconNode$6);const __iconNode$5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle=createLucideIcon("loader-circle",__iconNode$5);const __iconNode$4=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],LogOut=createLucideIcon("log-out",__iconNode$4);const __iconNode$3=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],RefreshCw=createLucideIcon("refresh-cw",__iconNode$3);const __iconNode$2=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Settings=createLucideIcon("settings",__iconNode$2);const __iconNode$1=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],Shield=createLucideIcon("shield",__iconNode$1);const __iconNode=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],Sparkles=createLucideIcon("sparkles",__iconNode);function AccountCredentialsFrame({frame:n,children:e}){return n==="bare"?jsxRuntimeExports.jsx("div",{"data-account-credentials-frame":"bare",className:"w-full text-card-foreground",children:e}):jsxRuntimeExports.jsx(Card,{"data-account-credentials-frame":"card",className:"w-full border-border bg-card text-card-foreground",children:e})}function setCredentialValue(n,e,t,i,s){i({...n,[e]:t}),s?.(e,t)}function FieldError({id:n,message:e}){return e?jsxRuntimeExports.jsxs("p",{id:n,role:"alert","aria-live":"polite",className:"flex items-center gap-1.5 text-sm text-destructive",children:[jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-4 w-4 shrink-0"}),e]}):null}function FloatingCredentialField({id:n,label:e,error:t,children:i}){return jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsxs("div",{"data-floating-field":"true",className:"relative",children:[i,jsxRuntimeExports.jsx(Label,{htmlFor:n,className:"pointer-events-none absolute left-3 top-0 z-[1] -translate-y-1/2 bg-card px-1 text-xs leading-none text-muted-foreground transition-[color,font-size,top,transform] duration-150 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:text-sm peer-focus:top-0 peer-focus:-translate-y-1/2 peer-focus:text-xs peer-focus:text-ring peer-disabled:opacity-50 peer-aria-[invalid=true]:text-destructive",children:e})]}),jsxRuntimeExports.jsx(FieldError,{id:`${n}-error`,message:t})]})}function StackedCredentialField({id:n,label:e,error:t,children:i}){return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:n,children:e}),i,jsxRuntimeExports.jsx(FieldError,{id:`${n}-error`,message:t})]})}function CredentialField({id:n,label:e,error:t,floating:i,children:s}){const o=i?FloatingCredentialField:StackedCredentialField;return jsxRuntimeExports.jsx(o,{id:n,label:e,error:t,children:s})}function AccountCredentialsView({mode:n,values:e,onChange:t,onSubmit:i,onFieldChange:s,onModeChange:o,rememberAccount:l=!0,onRememberAccountChange:u,pending:h=!1,errors:d,usernameAvailability:p="idle",usernameSuggestions:g=[],copy:m,frame:v="card",showHeader:S=!0,presentation:E="standard"}){const[x,A]=reactExports.useState(!1),[C,T]=reactExports.useState(!1),F=reactExports.useId(),P=reactExports.useId(),q=reactExports.useId(),O=reactExports.useId(),G=reactExports.useId(),fe=n==="register",M=typeof p=="string"?p:p.status,ee=fe&&e.password.length>0&&e.confirmation!==void 0&&e.password!==e.confirmation,Se=ee&&(x||C)?m.mismatchError:void 0,re=fe?m.registerAction:m.loginAction,Ae=E==="compact",ke=Ae?"peer h-11 rounded-xl px-3 pb-2 pt-4":void 0,he=ce=>{if(ce?.preventDefault(),!h){if(fe&&ee){A(!0);return}A(!1),i(e)}},Oe=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[S?jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{children:fe?m.registerTitle:m.loginTitle}),jsxRuntimeExports.jsx(CardDescription,{children:m.productName})]}):null,jsxRuntimeExports.jsx(CardContent,{className:cn(v==="bare"?"p-0":S?void 0:"pt-6"),children:jsxRuntimeExports.jsxs("form",{onSubmit:he,className:Ae?"space-y-3":"space-y-4",children:[fe?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(CredentialField,{floating:Ae,id:F,label:m.usernameLabel,error:d?.username,children:jsxRuntimeExports.jsx(Input,{id:F,name:"username",autoComplete:"username",placeholder:Ae?" ":m.usernamePlaceholder,title:m.usernamePlaceholder,value:e.username??"",disabled:h,"aria-invalid":d?.username?!0:void 0,"aria-describedby":d?.username?`${F}-error`:void 0,className:ke,onChange:ce=>setCredentialValue(e,"username",ce.currentTarget.value,t,s)})}),M==="checking"?jsxRuntimeExports.jsxs("p",{role:"status","aria-live":"polite",className:"text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{"aria-hidden":"true",className:"mr-1 inline h-3.5 w-3.5 animate-spin"}),m.usernameChecking]}):null,M==="available"?jsxRuntimeExports.jsxs("p",{"aria-live":"polite",className:"flex items-center gap-1 text-sm text-primary",children:[jsxRuntimeExports.jsx(CircleCheckBig,{"aria-hidden":"true",className:"h-4 w-4"}),m.usernameAvailable]}):null,M==="unavailable"&&!d?.username?jsxRuntimeExports.jsx("p",{"aria-live":"polite",className:"text-sm text-destructive",children:typeof p=="object"&&p.message?p.message:m.usernameUnavailable}):null,!Ae&&g.length>0?jsxRuntimeExports.jsxs("div",{className:"space-y-2","aria-label":m.suggestionsLabel,children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:m.suggestionsLabel}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-2",children:g.map(ce=>jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",size:"sm",disabled:h,onClick:()=>setCredentialValue(e,"username",ce,t,s),children:ce},ce))})]}):null]}):null,jsxRuntimeExports.jsx(CredentialField,{floating:Ae,id:P,label:m.emailLabel,error:d?.email,children:jsxRuntimeExports.jsx(Input,{id:P,name:"email",type:"email",autoComplete:"email",placeholder:Ae?" ":m.emailPlaceholder,title:m.emailPlaceholder,value:e.email??"",disabled:h,"aria-invalid":d?.email?!0:void 0,"aria-describedby":d?.email?`${P}-error`:void 0,className:ke,onChange:ce=>setCredentialValue(e,"email",ce.currentTarget.value,t,s)})}),jsxRuntimeExports.jsx(CredentialField,{floating:Ae,id:q,label:m.passwordLabel,error:d?.password,children:jsxRuntimeExports.jsx(Input,{id:q,name:"password",type:"password",autoComplete:fe?"new-password":"current-password",placeholder:Ae?" ":m.passwordPlaceholder,title:m.passwordPlaceholder,value:e.password,disabled:h,"aria-invalid":d?.password?!0:void 0,"aria-describedby":d?.password?`${q}-error`:void 0,className:ke,onChange:ce=>setCredentialValue(e,"password",ce.currentTarget.value,t,s)})}),fe?jsxRuntimeExports.jsx(CredentialField,{floating:Ae,id:O,label:m.confirmationLabel,error:Se??d?.confirmation,children:jsxRuntimeExports.jsx(Input,{id:O,name:"confirmation",type:"password",autoComplete:"new-password",placeholder:Ae?" ":m.confirmationPlaceholder,title:m.confirmationPlaceholder,value:e.confirmation??"",onBlur:()=>T(!0),disabled:h,"aria-invalid":Se||d?.confirmation?!0:void 0,"aria-describedby":Se||d?.confirmation?`${O}-error`:void 0,className:ke,onChange:ce=>{A(!1),setCredentialValue(e,"confirmation",ce.currentTarget.value,t,s)}})}):null,!fe&&u?jsxRuntimeExports.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[jsxRuntimeExports.jsx("input",{type:"checkbox",name:"remember",checked:l,disabled:h,onChange:ce=>u(ce.currentTarget.checked)}),"记住账号"]}):null,jsxRuntimeExports.jsx(FieldError,{id:G,message:d?.form}),jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs(Button,{type:"submit",className:cn("w-full",Ae&&"h-10 rounded-xl"),disabled:h,children:[h?jsxRuntimeExports.jsx(LoaderCircle,{"aria-hidden":"true",className:"mr-2 h-4 w-4 animate-spin"}):null,re]}),o?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",className:cn("w-full",Ae&&"h-9 rounded-lg text-xs"),disabled:h,onClick:()=>o(fe?"login":"register"),children:fe?m.switchToLogin:m.switchToRegister}):null]})]})})]});return jsxRuntimeExports.jsx(AccountCredentialsFrame,{frame:v,children:Oe})}function getXpodAuthSurfaceHost(){return globalThis.xpodDesktop?"window":"document"}function useXpodAuthWindowSurface(n=!0,e="auth"){reactExports.useEffect(()=>{if(n)return globalThis.xpodDesktop?.setWindowMode?.(e),()=>{globalThis.xpodDesktop?.setWindowMode?.("workspace")}},[n,e])}const xpodIconUrl="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2064%2064'%20fill='none'%3e%3cpath%20d='M32%207%2051%2016.5v13.8c0%2012.4-7.4%2021.2-19%2027.7-11.6-6.5-19-15.3-19-27.7V16.5L32%207Z'%20stroke='%238A72BE'%20stroke-width='5'%20stroke-linecap='round'%20stroke-linejoin='round'%20/%3e%3c/svg%3e",features=[{icon:Clock,title:"Your AI Secretary Never Stops",description:"Runs 24/7, even when you are not talking to it"},{icon:Layers,title:"All Your Pieces, In One Place",description:"Data, memory, and context come back into one system"},{icon:Shield,title:"One Secretary, Many Agents",description:"One aligned layer that can direct many agents while keeping privacy and control inside your boundary."}];function Brand({compact:n=!1}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("img",{src:xpodIconUrl,alt:"",className:n?"h-9 w-9":"h-12 w-12"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:`${n?"text-xl":"text-2xl"} font-bold leading-tight`,children:"Xpod"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Personal Messages Platform"})]})]})}function WebAccountLayout({title:n,description:e,children:t,presentation:i="standard",host:s="document"}){const o=reactExports.useId(),l=s==="window"&&i==="compact";return i==="compact"?jsxRuntimeExports.jsx("main",{"data-testid":"web-account-page",className:l?"flex h-dvh w-full items-center justify-center overflow-hidden bg-background text-foreground":"flex min-h-dvh items-center justify-center bg-muted/30 p-4 text-foreground sm:p-6",children:jsxRuntimeExports.jsxs("section",{role:"region","aria-labelledby":o,"data-testid":"web-account-panel","data-web-account-layout":"compact","data-web-account-host":l?"window":"document",className:l?"flex h-full w-full min-w-0 flex-col overflow-y-auto overscroll-contain px-5 py-5":"mx-auto 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 rounded-xl border bg-card px-5 py-5 shadow-lg shadow-black/5",children:[jsxRuntimeExports.jsx("div",{className:"mb-4 shrink-0",children:jsxRuntimeExports.jsx(Brand,{compact:!0})}),jsxRuntimeExports.jsxs("header",{className:"mb-4 shrink-0 text-center",children:[jsxRuntimeExports.jsx("h1",{id:o,className:"text-xl font-semibold tracking-tight",children:n}),e?jsxRuntimeExports.jsx("p",{className:"mt-2 text-xs leading-relaxed text-muted-foreground",children:e}):null]}),jsxRuntimeExports.jsx("div",{className:"min-w-0 shrink-0",children:t})]})}):jsxRuntimeExports.jsx("main",{"data-testid":"web-account-page",className:"flex min-h-dvh items-center justify-center bg-muted/30 p-4 text-foreground sm:p-8",children:jsxRuntimeExports.jsxs("div",{className:"grid w-full max-w-6xl items-center gap-8 lg:grid-cols-2 lg:gap-16",children:[jsxRuntimeExports.jsxs("aside",{"data-testid":"web-account-introduction","aria-label":"关于 Xpod",className:"hidden px-8 lg:block",children:[jsxRuntimeExports.jsx(Brand,{}),jsxRuntimeExports.jsxs("h1",{className:"mb-4 mt-8 text-3xl font-bold leading-tight",children:["Simplify Life with ",jsxRuntimeExports.jsx("span",{className:"text-primary",children:"Your AI Secretary"})]}),jsxRuntimeExports.jsx("p",{className:"mb-10 text-sm leading-relaxed text-muted-foreground",children:"An AI that never stops, knows your whole life, works for you—while guarding your privacy."}),jsxRuntimeExports.jsx("div",{className:"space-y-5",children:features.map(({icon:u,title:h,description:d})=>jsxRuntimeExports.jsxs("div",{className:"flex gap-3",children:[jsxRuntimeExports.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border bg-card",children:jsxRuntimeExports.jsx(u,{"aria-hidden":"true",className:"h-4 w-4 text-primary"})}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-sm font-medium",children:h}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:d})]})]},h))}),jsxRuntimeExports.jsxs("p",{className:"mt-12 text-xs text-muted-foreground",children:["Powered by ",jsxRuntimeExports.jsx("a",{href:"https://solidproject.org",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline-offset-4 hover:underline",children:"Solid Protocol"})]})]}),jsxRuntimeExports.jsxs("section",{role:"region","aria-labelledby":o,"data-testid":"web-account-panel","data-web-account-layout":"standard",className:"mx-auto w-full min-w-0 max-w-md rounded-3xl border bg-card p-6 shadow-lg shadow-black/5 sm:p-8 lg:mx-0",children:[jsxRuntimeExports.jsx("div",{className:"mb-8 lg:hidden",children:jsxRuntimeExports.jsx(Brand,{})}),jsxRuntimeExports.jsxs("header",{className:"mb-6",children:[jsxRuntimeExports.jsx("h2",{id:o,className:"text-2xl font-bold tracking-tight",children:n}),e?jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm leading-relaxed text-muted-foreground",children:e}):null]}),t]})]})})}function XpodAuthSurface(n){const e=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(e==="window"),jsxRuntimeExports.jsx(AuthSurface,{...n,presentation:"compact",host:e})}function XpodAccountPageSurface({title:n,children:e,presentation:t="compact"}){const i=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(i==="window"&&t==="compact","account"),jsxRuntimeExports.jsx(WebAccountLayout,{title:n,presentation:t,host:i,children:e})}function XpodBlockingAccountCredentialsSurface(n){const e=getXpodAuthSurfaceHost(),t="compact";return useXpodAuthWindowSurface(e==="window"&&t==="compact","account"),jsxRuntimeExports.jsxs(WebAccountLayout,{title:n.surfaceTitle,description:n.mode==="register"?"创建你的 Xpod 账号,开始使用个人存储空间。":"登录以继续使用你的身份与个人存储空间。",presentation:t,host:e,children:[jsxRuntimeExports.jsx(AccountCredentialsView,{...n,frame:"bare",showHeader:!1,presentation:t}),n.footer?jsxRuntimeExports.jsx("div",{className:"mt-6 space-y-3 border-t pt-5",children:n.footer}):null]})}function WebAccountFailureView({title:n="操作未完成",description:e,primaryLabel:t="重试",onPrimary:i,secondaryLabel:s="返回",onSecondary:o,pending:l=!1}){return jsxRuntimeExports.jsxs("div",{className:"flex min-h-44 flex-col items-center justify-center gap-4 px-5 py-8 text-center",children:[jsxRuntimeExports.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-destructive/10",children:jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-5 w-5 text-destructive"})}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-base font-semibold text-foreground",children:n}),e?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm leading-6 text-muted-foreground",children:e}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex w-full flex-col gap-2 sm:max-w-xs",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:i,className:"h-10 rounded-xl bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus-visible:bg-primary/80 disabled:cursor-not-allowed disabled:opacity-50",children:t}),o?jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:o,className:"h-9 rounded-lg border border-border bg-background px-4 text-sm font-medium text-foreground transition-colors hover:bg-muted/50 focus:outline-none focus-visible:border-ring",children:s}):null]})]})}let automaticLoginBlocked=!1,logoutState={status:"idle"},operation,inFlight;const logoutListeners=new Set,isXpodAutomaticLoginBlocked=()=>automaticLoginBlocked,getXpodProductLogoutState=()=>logoutState;function subscribeXpodProductLogout(n){return logoutListeners.add(n),()=>{logoutListeners.delete(n)}}function publish(n){logoutState=n,logoutListeners.forEach(e=>e())}function logoutXpodProduct(n,e,t={}){return inFlight||(automaticLoginBlocked=!0,operation={account:n,runtime:e,solidCleared:!1,onComplete:t.onComplete},retryXpodProductLogout())}function retryXpodProductLogout(){if(inFlight)return inFlight;if(!operation)return Promise.resolve();const n=operation;return inFlight=(async()=>{let t=n.solidCleared?"account":"solid";publish({status:"running",step:t});try{if(n.solidCleared||(await n.runtime?.logout(),n.solidCleared=!0),t="account",publish({status:"running",step:t}),await n.account.logout(),n.account.isAnonymous&&!n.account.isAnonymous())throw new Error("Account sign-out did not complete")}catch(i){throw publish({status:"error",step:t}),i}operation=void 0,publish({status:"idle"}),n.onComplete?.()})().finally(()=>{inFlight=void 0}),inFlight}const LogoutRecoveryOwner=reactExports.createContext(!1);function XpodProductLogoutBoundary({children:n}){const e=reactExports.useContext(LogoutRecoveryOwner),t=reactExports.useSyncExternalStore(subscribeXpodProductLogout,getXpodProductLogoutState,getXpodProductLogoutState);if(e)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});const i=t.status!=="idle";return jsxRuntimeExports.jsxs(LogoutRecoveryOwner.Provider,{value:!0,children:[i&&jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"退出 Xpod",children:t.status==="running"?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在退出…"}):jsxRuntimeExports.jsx(WebAccountFailureView,{title:"退出未完成",description:t.step==="account"?"账号会话尚未退出,请重试完成退出。":"WebID 会话尚未退出,请重试完成退出。",primaryLabel:"重试退出",onPrimary:()=>{retryXpodProductLogout().catch(()=>{})}})}),jsxRuntimeExports.jsx("div",{className:i?"hidden":"contents","aria-hidden":i||void 0,inert:i||void 0,children:n})]})}const AuthContext=reactExports.createContext(null);function useAuth(){const n=reactExports.useContext(AuthContext);if(!n)throw new Error("useAuth must be used within AuthProvider");return n}const scriptRel="modulepreload",assetsURL=function(n){return"/settings/"+n},seen={},__vitePreload=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let h=function(d){return Promise.all(d.map(p=>Promise.resolve(p).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=l?.nonce||l?.getAttribute("nonce");s=h(t.map(d=>{if(d=assetsURL(d),d in seen)return;seen[d]=!0;const p=d.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${g}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":scriptRel,p||(m.as="script"),m.crossOrigin="",m.href=d,u&&m.setAttribute("nonce",u),document.head.appendChild(m),p)return new Promise((v,S)=>{m.addEventListener("load",v),m.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return s.then(l=>{for(const u of l||[])u.status==="rejected"&&o(u.reason);return e().catch(o)})};function extractProfileUsernameFromWebId(n){try{const t=new URL(n).pathname.split("/").filter(Boolean).map(o=>decodeURIComponent(o)),i=t.indexOf("profile");if(i>0)return t[i-1];const s=t.find(o=>o!=="profile"&&o!=="card");if(s)return s}catch{}return"there"}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",generateNanoId=(n=21)=>{let e="";if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"){const t=globalThis.crypto.getRandomValues(new Uint8Array(n));for(let i=0;i<n;i++)e+=urlAlphabet[t[i]%urlAlphabet.length]}else{console.warn("Using Math.random fallback for NanoID generation.");for(let t=0;t<n;t++)e+=urlAlphabet[Math.floor(Math.random()*256)%urlAlphabet.length]}return e},hasStringValue$2=n=>typeof n=="object"&&n!==null&&typeof n.value=="string",hasTermValue=n=>typeof n=="object"&&n!==null&&typeof n.term=="object"&&n.term!==null&&typeof n.term?.value=="string",resolveTermIri=n=>{if(typeof n=="string")return n;if(hasStringValue$2(n))return n.value;if(hasTermValue(n))return n.term.value;throw new Error("Term must be a string or VocabTerm with a string value")},entityKind=Symbol.for("drizzle:entityKind");function is(n,e){if(!n||typeof n!="object")return!1;if(n instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,entityKind))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=n.constructor;if(t)for(;t;){if(entityKind in t&&t[entityKind]===e[entityKind])return!0;t=Object.getPrototypeOf(t)}return!1}class Column{table;static[entityKind]="Column";name;primary;notNull;default;defaultFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}const ViewBaseConfig=Symbol.for("drizzle:ViewBaseConfig");class View{static[entityKind]="View";[ViewBaseConfig];constructor({name:e,schema:t,selectedFields:i,query:s}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:i,query:s,isExisting:!s,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,i,s=!1){this[SubqueryConfig]={sql:e,selection:t,alias:i,isWith:s}}getSQL(){return new SQL([this])}}class SelectionProxyHandler{static[entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t===SubqueryConfig)return{...e[SubqueryConfig],selection:new Proxy(e[SubqueryConfig].selection,this)};if(t===ViewBaseConfig)return{...e[ViewBaseConfig],selectedFields:new Proxy(e[ViewBaseConfig].selectedFields,this)};if(typeof t=="symbol")return e[t];const s=(is(e,Subquery)?e[SubqueryConfig].selection:is(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is(s,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!s.isSelectionField)return s.sql;const o=s.clone();return o.isSelectionField=!0,o}if(is(s,SQL)){if(this.config.sqlBehavior==="sql")return s;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is(s,Column)?this.config.alias?new Proxy(s,new ColumnAliasProxyHandler(new Proxy(s.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):s:typeof s!="object"||s===null?s:new Proxy(s,new SelectionProxyHandler(this.config))}}function orderSelectedFields(n,e){return Object.entries(n).reduce((t,[i,s])=>{if(typeof i!="string")return t;const o=e?[...e,i]:[i];return is(s,Column)||is(s,SQL)||is(s,SQL.Aliased)?t.push({path:o,field:s}):is(s,Table)?t.push(...orderSelectedFields(s[Table.Symbol.Columns],o)):t.push(...orderSelectedFields(s,o)),t},[])}function applyMixins(n,e){for(const t of e)for(const i of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(n.prototype,i,Object.getOwnPropertyDescriptor(t.prototype,i)||Object.create(null))}function getTableLikeName(n){return is(n,Subquery)?n[SubqueryConfig].alias:is(n,View)?n[ViewBaseConfig].name:is(n,SQL)?void 0:n[Table.Symbol.IsAlias]?n[Table.Symbol.Name]:n[Table.Symbol.BaseName]}const TableName=Symbol.for("drizzle:Name"),Schema=Symbol.for("drizzle:Schema"),Columns=Symbol.for("drizzle:Columns"),OriginalName=Symbol.for("drizzle:OriginalName"),BaseName=Symbol.for("drizzle:BaseName"),IsAlias=Symbol.for("drizzle:IsAlias"),ExtraConfigBuilder=Symbol.for("drizzle:ExtraConfigBuilder"),IsDrizzleTable=Symbol.for("drizzle:IsDrizzleTable");class Table{static[entityKind]="Table";static Symbol={Name:TableName,Schema,OriginalName,Columns,BaseName,IsAlias,ExtraConfigBuilder};[TableName];[OriginalName];[Schema];[Columns];[BaseName];[IsAlias]=!1;[ExtraConfigBuilder]=void 0;[IsDrizzleTable]=!0;constructor(e,t,i){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=i}getSQL(){return new SQL([this])}}class QueryPromise{static[entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}const tracer={startActiveSpan(n,e){return e()}},InlineForeignKeys=Symbol.for("drizzle:PgInlineForeignKeys");class PgTable extends Table{static[entityKind]="PgTable";static Symbol=Object.assign({},Table.Symbol,{InlineForeignKeys});[InlineForeignKeys]=[];[Table.Symbol.ExtraConfigBuilder]=void 0}class TypedQueryBuilder{static[entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class PgSelectQueryBuilder extends TypedQueryBuilder{static[entityKind]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:e,fields:t,isPartialSelect:i,session:s,dialect:o,withList:l,distinct:u}){super(),this.config={withList:l,table:e,fields:{...t},distinct:u},this.isPartialSelect=i,this.session=s,this.dialect=o,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,i)=>{const s=this.tableName,o=getTableLikeName(t);if(typeof o=="string"&&this.config.joins?.some(l=>l.alias===o))throw new Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof s=="string"&&(this.config.fields={[s]:this.config.fields}),typeof o=="string"&&!is(t,SQL))){const l=is(t,Subquery)?t[SubqueryConfig].selection:is(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[o]=l}if(typeof i=="function"&&(i=i(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:t,joinType:e,alias:o}),typeof o=="string")switch(e){case"left":{this.joinsNotNullableMap[o]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[o]=!0;break}case"inner":{this.joinsNotNullableMap[o]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[o]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.orderBy=Array.isArray(t)?t:[t]}else this.config.orderBy=e;return this}limit(e){return this.config.limit=e,this}offset(e){return this.config.offset=e,this}for(e,t={}){return this.config.lockingClauses||(this.config.lockingClauses=[]),this.config.lockingClauses.push({strength:e,config:t}),this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){return new Proxy(new Subquery(this.getSQL(),this.config.fields,e),new SelectionProxyHandler({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}class PgSelect extends PgSelectQueryBuilder{static[entityKind]="PgSelect";_prepare(e){const{session:t,config:i,dialect:s,joinsNotNullableMap:o}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return tracer.startActiveSpan("drizzle.prepareQuery",()=>{const l=orderSelectedFields(i.fields),u=t.prepareQuery(s.sqlToQuery(this.getSQL()),l,e);return u.joinsNotNullableMap=o,u})}prepare(e){return this._prepare(e)}execute=e=>tracer.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e))}applyMixins(PgSelect,[QueryPromise]);class Relation{sourceTable;referencedTable;relationName;static[entityKind]="Relation";referencedTableName;fieldName;constructor(e,t,i){this.sourceTable=e,this.referencedTable=t,this.relationName=i,this.referencedTableName=t[Table.Symbol.Name]}}function isSQLWrapper(n){return typeof n=="object"&&n!==null&&"getSQL"in n&&typeof n.getSQL=="function"}function mergeQueries(n){const e={sql:"",params:[]};for(const t of n)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class StringChunk{static[entityKind]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new SQL([this])}}class SQL{queryChunks;static[entityKind]="SQL";decoder=noopDecoder;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tracer.startActiveSpan("drizzle.buildSQL",t=>{const i=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(e,t){const i=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:s,escapeParam:o,prepareTyping:l,inlineParams:u,paramStartIndex:h}=i;return mergeQueries(e.map(d=>{if(is(d,StringChunk))return{sql:d.value.join(""),params:[]};if(is(d,Name))return{sql:s(d.value),params:[]};if(d===void 0)return{sql:"",params:[]};if(Array.isArray(d)){const p=[new StringChunk("(")];for(const[g,m]of d.entries())p.push(m),g<d.length-1&&p.push(new StringChunk(", "));return p.push(new StringChunk(")")),this.buildQueryFromSourceParams(p,i)}if(is(d,SQL))return this.buildQueryFromSourceParams(d.queryChunks,{...i,inlineParams:u||d.shouldInlineParams});if(is(d,Table)){const p=d[Table.Symbol.Schema],g=d[Table.Symbol.Name];return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Column))return{sql:s(d.table[Table.Symbol.Name])+"."+s(d.name),params:[]};if(is(d,View)){const p=d[ViewBaseConfig].schema,g=d[ViewBaseConfig].name;return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Param)){const p=d.value===null?null:d.encoder.mapToDriverValue(d.value);if(is(p,SQL))return this.buildQueryFromSourceParams([p],i);if(u)return{sql:this.mapInlineParam(p,i),params:[]};let g;return l!==void 0&&(g=[l(d.encoder)]),{sql:o(h.value++,p),params:[p],typings:g}}return is(d,Placeholder)?{sql:o(h.value++,d),params:[d]}:is(d,SQL.Aliased)&&d.fieldAlias!==void 0?{sql:s(d.fieldAlias),params:[]}:is(d,Subquery)?d[SubqueryConfig].isWith?{sql:s(d[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),d[SubqueryConfig].sql,new StringChunk(") "),new Name(d[SubqueryConfig].alias)],i):isSQLWrapper(d)?this.buildQueryFromSourceParams([new StringChunk("("),d.getSQL(),new StringChunk(")")],i):is(d,Relation)?this.buildQueryFromSourceParams([d.sourceTable,new StringChunk("."),sql.identifier(d.fieldName)],i):u?{sql:this.mapInlineParam(d,i),params:[]}:{sql:o(h.value++,d),params:[d]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const i=e.toString();return t(i==="[object Object]"?JSON.stringify(e):i)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new SQL.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}}class Name{value;static[entityKind]="Name";brand;constructor(e){this.value=e}getSQL(){return new SQL([this])}}const noopDecoder={mapFromDriverValue:n=>n},noopEncoder={mapToDriverValue:n=>n};({...noopDecoder,...noopEncoder});class Param{value;encoder;static[entityKind]="Param";brand;constructor(e,t=noopEncoder){this.value=e,this.encoder=t}getSQL(){return new SQL([this])}}function sql(n,...e){const t=[];(e.length>0||n.length>0&&n[0]!=="")&&t.push(new StringChunk(n[0]));for(const[i,s]of e.entries())t.push(s,new StringChunk(n[i+1]));return new SQL(t)}(function(n){function e(){return new SQL([])}n.empty=e;function t(h){return new SQL(h)}n.fromList=t;function i(h){return new SQL([new StringChunk(h)])}n.raw=i;function s(h,d){const p=[];for(const[g,m]of h.entries())g>0&&d!==void 0&&p.push(d),p.push(m);return new SQL(p)}n.join=s;function o(h){return new Name(h)}n.identifier=o;function l(h){return new Placeholder(h)}n.placeholder=l;function u(h,d){return new Param(h,d)}n.param=u})(sql||(sql={}));(function(n){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(i,s){this.sql=i,this.fieldAlias=s}getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}n.Aliased=e})(SQL||(SQL={}));class Placeholder{name;static[entityKind]="Placeholder";constructor(e){this.name=e}getSQL(){return new SQL([this])}}Column.prototype.getSQL=function(){return new SQL([this])};class ColumnAliasProxyHandler{table;static[entityKind]="ColumnAliasProxyHandler";constructor(e){this.table=e}get(e,t){return t==="table"?this.table:e[t]}}class TableAliasProxyHandler{alias;replaceOriginalName;static[entityKind]="TableAliasProxyHandler";constructor(e,t){this.alias=e,this.replaceOriginalName=t}get(e,t){if(t===Table.Symbol.IsAlias)return!0;if(t===Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Table.Symbol.OriginalName)return this.alias;if(t===ViewBaseConfig)return{...e[ViewBaseConfig],name:this.alias,isAlias:!0};if(t===Table.Symbol.Columns){const s=e[Table.Symbol.Columns];if(!s)return s;const o={};return Object.keys(s).map(l=>{o[l]=new Proxy(s[l],new ColumnAliasProxyHandler(new Proxy(e,this)))}),o}const i=e[t];return is(i,Column)?new Proxy(i,new ColumnAliasProxyHandler(new Proxy(e,this))):i}}var _a$b;class ColumnBuilder{constructor(e,t,i={},s,o){this.name=e,this.dataType=t,this.options={...i},this._predicateUri=s,this.elementType=o??null}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){const t=this.options.isArray&&this.elementType?this.elementType:this.dataType;if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(t){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return String(Number(e));case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}parseValue(e,t){return this.parseSingleValue(e,t)}parseSingleValue(e,t){if(!t)return e;if(t.includes("#integer")||t.includes("#int"))return parseInt(e,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e);if(t.includes("#boolean"))return e==="true";if(t.includes("#dateTime"))return new Date(e);if(t.includes("#json"))try{return JSON.parse(e)}catch{return console.warn("Failed to parse JSON value:",e),e}return e.startsWith("http://")||e.startsWith("https://"),e}primaryKey(){return this._predicateUri="@id",this.options={...this.options,primaryKey:!0,required:!0,predicate:"@id"},this}notNull(){return this.options={...this.options,required:!0,notNull:!0},this}predicate(e){const t=resolveTermIri(e);return this._predicateUri=t,this.options={...this.options,predicate:t},this}default(e){return this.options={...this.options,defaultValue:e},this}defaultNow(){return this.options={...this.options,defaultValue:()=>new Date},this}inverse(e=!0){return this.options={...this.options,inverse:e},this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options={...this.options,linkTarget:e}:this.options={...this.options,linkTableName:e}:this.options={...this.options,linkTable:e},this}array(){return new ColumnBuilder(this.name,"array",{...this.options,baseType:this.dataType,isArray:!0},this._predicateUri,this.dataType)}getPredicateUri(){return this._predicateUri}}class PodColumnBase{constructor(e,t,i={},s){this.name=e,this.dataType=t,this.options=i,this.tableName=s}getPredicate(e){if(this.options.predicate)return this.options.predicate;if(e)return`${e.uri}${this.name}`;throw new Error(`Missing predicate for column "${this.name}"; please set namespace or predicate explicitly.`)}isLink(){return!!(this.options.linkTarget||this.options.linkTableName||this.options.linkTable)}getLinkTarget(){return this.options.linkTarget}getLinkTableName(){return this.options.linkTableName}getLinkTable(){return this.options.linkTable}primaryKey(){return this.options.primaryKey=!0,this.options.required=!0,this.options.predicate="@id",this}notNull(){return this.options.required=!0,this}default(e){return this.options.defaultValue=e,this}predicate(e){return this.options.predicate=resolveTermIri(e),this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options.linkTarget=e:this.options.linkTableName=e:this.options.linkTable=e,this}inverse(e=!0){return this.options.inverse=e,this}isInverse(){return this.options.inverse===!0}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(this.dataType){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return`"${Number(e)}"^^<http://www.w3.org/2001/XMLSchema#integer>`;case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}}_a$b=entityKind;PodColumnBase[_a$b]="PodColumn";class PodStringColumn extends PodColumnBase{constructor(e,t={}){super(e,"string",t)}}class PodIntegerColumn extends PodColumnBase{constructor(e,t={}){super(e,"integer",t)}}class PodBooleanColumn extends PodColumnBase{constructor(e,t={}){super(e,"boolean",t)}}class PodDateTimeColumn extends PodColumnBase{constructor(e,t={}){super(e,"datetime",t)}}class PodJsonColumn extends PodColumnBase{constructor(e,t={}){super(e,"json",t)}}class PodObjectColumn extends PodColumnBase{constructor(e,t={}){super(e,"object",t)}}class PodUriColumn extends PodColumnBase{constructor(e,t={}){super(e,"uri",t)}}class PodArrayColumn extends PodColumnBase{constructor(e,t,i={}){super(e,"array",i),this.elementType=t}}function boolean$2(n,e={}){return new ColumnBuilder(n,"boolean",e)}function timestamp(n,e={}){return new ColumnBuilder(n,"datetime",e)}function json(n,e={}){return new ColumnBuilder(n,"json",e)}function object$1(n,e={}){return new ColumnBuilder(n,"object",e)}function uri(n,e={}){return new ColumnBuilder(n,"uri",e)}function id(n="id",e={}){const t=new PodStringColumn(n,{...e,predicate:"@id",primaryKey:!0,required:!0,...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{}});return t._virtualId=!0,t}function string$2(n,e={}){return new ColumnBuilder(n,"string",e)}function integer$1(n,e={}){return new ColumnBuilder(n,"integer",e)}function date$3(n,e={}){return new ColumnBuilder(n,"datetime",e)}function text(n,e={}){return new ColumnBuilder(n,"string",e)}function real(n,e={}){return new ColumnBuilder(n,"integer",e)}function validateColumnOverride(n,e,t){const i=n.getPredicateUri?.()??n.options?.predicate,s=e.options?.predicate;if(i&&s&&i!==s)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${s}",子 schema 尝试改为 "${i}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(n,e){const t={};for(const[i,s]of Object.entries(n.columns))t[i]=s;for(const[i,s]of Object.entries(e)){const o=n.columns[i];if(o&&!(s instanceof PodColumnBase)){validateColumnOverride(s,o,i);const l=s;!l.getPredicateUri?.()&&!l.options?.predicate&&(l.options={...l.options,predicate:o.options?.predicate})}t[i]=s}return t}function renderDefaultIdTemplate(n,e){if(!/\{[^{}]+\}/.test(n))return n;if(/\{\s*id\s*\}/.test(n))throw new Error("id default template uses {key} for the generated local key; {id} is the final resource id");const t=e.row??{},i=resolveDate(t,e.now),s={yyyy:String(i.getUTCFullYear()),MM:String(i.getUTCMonth()+1).padStart(2,"0"),dd:String(i.getUTCDate()).padStart(2,"0")};return n.replace(/\{([^{}]+)\}/g,(o,l)=>{const u=l.trim();if(u==="key")return e.key;if(u==="yyyy")return s.yyyy;if(u==="MM")return s.MM;if(u==="dd")return s.dd;const h=resolveExpression(u,t,e);return h==null?"":String(h)})}function resolveDate(n,e=new Date){const t=n.createdAt??n.favoredAt??n.indexedAt??e,i=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(i.getTime())?i:e}function resolveExpression(n,e,t){const i=parseExpression(n);let s=resolveTemplatePath(i.path,e,t);for(const o of i.transforms)s=applyTransform(s,o,i.path,t);return i.selector?applyPathSelector(s,i.selector):s}function parseExpression(n){const e=n.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():n,[i,...s]=t.split("|").map(o=>o.trim()).filter(Boolean);return{path:i??n,transforms:s,selector:e?.[2]?.trim()}}function resolveTemplatePath(n,e,t){const i=n.split("."),s=i[0];return i.reduce((o,l,u)=>{if(typeof o=="string")return s?resolveResourceProperty(o,s,l,t):void 0;if(!(!o||typeof o!="object"))return s&&isResourceProperty(l)&&!((l==="id"||l==="key")&&l in o)?resolveResourceProperty(o,s,l,t):u>0&&l==="id"&&readRef(o)?extractResourceId(o,s??"",t):o[l]},e)}function isResourceProperty(n){return n==="id"||n==="key"||n==="doc"||n==="document"||n==="dir"||n==="owner"}function resolveResourceProperty(n,e,t,i){if(t==="id")return extractResourceId(n,e,i);const s=extractResourceId(n,e,i);if(s){if(t==="key"){const o=extractTemplateValuesForField(n,e,i);return o?.key??o?.id??deriveResourceKey(s)}if(t==="doc"||t==="document")return resourceDocument(s);if(t==="dir"||t==="owner")return deriveOwnerDir(s)}}function applyTransform(n,e,t,i){if(e==="slug")return slugifyValue(String(n??""));const s=extractResourceId(n,t,i);if(e==="resource")return s;if(e==="document")return s?resourceDocument(s):"";if(e==="owner")return s?deriveOwnerDir(s):"";const o=extractTemplateValuesForField(n,t,i);return e==="id"?o?.id??o?.key??s??"":o?.[e]??""}function extractResourceId(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return normalizePodDataResourceId$1(i);if(!isCompleteResourceId$1(i))return renderLinkedResourceId(s,i);const o=relativeSubjectFromRef$1(s,i);return normalizePodDataResourceId$1(o??i)}function extractTemplateValuesForField(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return null;const o=relativeSubjectFromRef$1(s,i)??(isCompleteResourceId$1(i)?null:renderLinkedResourceId(s,i));if(!o)return null;const l=resourceTemplate(s);return l?extractVarsFromTemplate(normalizePodDataResourceId$1(o),l):{id:normalizePodDataResourceId$1(o)}}function resolveLinkedResource(n,e){const t=e.links?.[n];if(t)return t;const i=e.resource?.columns?.[n];return i?.getLinkTable?.()??i?.options?.linkTable??null}function resourceTemplate(n){const e=n.getSubjectTemplate?.()??n.config?.subjectTemplate;if(e)return e;const t=n.columns?.id?.options?.defaultValue;return typeof t=="string"?t:null}function renderLinkedResourceId(n,e){const t=resourceTemplate(n);if(!t)return e;const i=n.columns?.id?.options?.defaultValue;return typeof i=="function"?String(i(e,{})):t.replace(/\{([^}]+)\}/g,(s,o)=>{const l=parseTemplateField(o);return l==="id"||l==="key"?e:""})}function readRef(n){if(typeof n=="string"&&n.length>0)return n;if(!n||typeof n!="object")return null;const e=n,t=e["@id"]??e.subject??e.id;return typeof t=="string"&&t.length>0?t:null}function resourcePath(n){return normalizeResourcePath$1(n.getResourcePath?.()??n.config?.base??"")}function relativeSubjectFromRef$1(n,e){const t=resourcePath(n);if(!t)return normalizePodDataResourceId$1(e);const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const o=e.indexOf(s);if(o<0)continue;let l=e.slice(o+s.length);return l.startsWith("/")&&(l=l.slice(1)),l.length>0?l:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(n,e){let t=0;const i=new Map,s=[];let o=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp$1(e.slice(o,u.index)));const h=`var${t++}`;i.set(h,parseTemplateField(u[1]??"")),s.push(`(?<${h}>.+?)`),o=u.index+u[0].length}s.push(escapeRegExp$1(e.slice(o)));const l=s.join("");try{const u=n.match(new RegExp(`^${l}$`));if(!u?.groups)return null;const h={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);!g||p===void 0||(h[g]=decodeURIComponent(p))}return h}catch{return null}}function parseTemplateField(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function escapeRegExp$1(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function applyPathSelector(n,e){const t=splitResourcePath(n);if(!t)return;if(/^-?\d+$/.test(e))return t[normalizeIndex(Number(e),t.length)];const i=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!i)throw new Error(`Invalid id default path selector [${e}]`);const s=i[1]===""?0:normalizeSliceIndex(Number(i[1]),t.length),o=i[2]===""?t.length:normalizeSliceIndex(Number(i[2]),t.length);return t.slice(s,o).join("/")}function splitResourcePath(n){const e=readRef(n);if(!e)return null;const t=normalizePodDataResourceId$1(e),[i,s]=t.split("#"),o=(i??t).split("/").filter(Boolean);return s&&o.push(s),o}function normalizePodDataResourceId$1(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function normalizeResourcePath$1(n){return n.trim().replace(/^(\.\/)+/,"")}function isCompleteResourceId$1(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function deriveOwnerDir(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#"),i=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):"",o=i.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(o?.[1])return o[1];if(i==="task/index.ttl"&&s&&s!=="this")return`task/${s}`;const l=i.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(l?.[1])return l[1];const u=i.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(u?.[1])return u[1];const h=i.split("/").filter(Boolean);return h.length>1?h.slice(0,-1).join("/"):i}function resourceDocument(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");return t>=0?e.slice(0,t):e}function deriveResourceKey(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");if(t>=0){const u=e.slice(t+1);if(u&&u!=="this"&&u!=="me"&&u!=="it")return u}const i=resourceDocument(e).replace(/\/+$/u,""),s=i.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(s?.[1])return s[1];const o=i.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(o?.[1])return o[1];const l=i.split("/").filter(Boolean);return l.length>0?l[l.length-1]:e}function slugifyValue(n){return n.normalize("NFKC").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^\p{Letter}\p{Number}.-]+/gu,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function normalizeIndex(n,e){return n<0?e+n:n}function normalizeSliceIndex(n,e){const t=n<0?e+n:n;return Math.max(0,Math.min(e,t))}function parseTemplateVariableField$1(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function normalizeResourcePath(n){return n.trim().replace(/^(\.\/)+/,"")}function podResourcePath(n){return normalizeResourcePath(n.getResourcePath?.()??n.config?.base??"")}function podResourceSubjectTemplate(n){return n.getSubjectTemplate?.()??n.config?.subjectTemplate}function podResourceIdDefaultTemplate(n){const e=n.columns?.id?.options?.defaultValue;return typeof e=="string"?e:void 0}function resourceRelativePrefix(n){const e=podResourcePath(n),t=normalizeResourcePath(n.getContainerPath?.()??n.config?.containerPath??"");return e?t&&e.startsWith(t)?normalizeResourcePath(e.slice(t.length)):e.split("/").pop()??e:""}function qualifyFragmentResourceId(n,e){if(!e.startsWith("#"))return e;const t=resourceRelativePrefix(n);return t?`${t}${e}`:e}function templateRelativeSubject(n,e){if((podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n))?.startsWith("#")&&!e.startsWith("#")){const i=e.indexOf("#");if(i>=0)return e.slice(i)}return e}function isBaseRelativeSubjectId$1(n){return!n||/^https?:\/\//.test(n)||n.startsWith("/")?!1:n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(n)}function isTemplateCompleteResourceId(n,e){if(!e||/^https?:\/\//.test(e)||e.startsWith("/"))return!1;const t=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n);return t?extractTemplateValues(templateRelativeSubject(n,e),t)!==null:!1}function isResourceRelativeSubjectId(n,e){return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)}function relativeSubjectFromRef(n,e){const t=podResourcePath(n);if(!t)return null;const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const o=e.indexOf(s);if(o<0)continue;let l=e.slice(o+s.length);if(l.startsWith("/")&&(l=l.slice(1)),l.length>0)return l}return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)?normalizeResourcePath(e):null}function extractTemplateValues(n,e){if(!e.includes("{"))return n===e?{}:null;let t=0;const i=new Map,s=[];let o=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp(e.slice(o,u.index)));const h=`var${t++}`;i.set(h,parseTemplateVariableField$1(u[1]??"")),s.push(`(?<${h}>.+?)`),o=u.index+u[0].length}s.push(escapeRegExp(e.slice(o)));const l=`^${s.join("")}$`;try{const u=n.match(new RegExp(l));if(!u?.groups)return null;const h={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);if(!g||p===void 0)continue;const m=decodeURIComponent(p);if(g in h&&h[g]!==m)return null;h[g]=m}return h}catch{return null}}function escapeRegExp(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function parsePodResourceRef(n,e){if(!e)return null;const t=relativeSubjectFromRef(n,e);if(!t)return null;const i=qualifyFragmentResourceId(n,t),s=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n),o=s?extractTemplateValues(templateRelativeSubject(n,i),s):{id:decodeURIComponent(i)};return o?{resourceId:decodeURIComponent(i),templateValues:o}:null}function extractPodResourceTemplateValue(n,e,t="id"){return parsePodResourceRef(n,e)?.templateValues[t]??null}function resolvePodBaseUrl(n){const e=n.trim();return e?e.includes("/profile/card#me")?e.replace("/profile/card#me","").replace(/\/+$/u,""):e.replace(/\/+$/u,""):""}function resolvePodBaseUrlFromDatabase(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getDialect=="function"?e.getDialect():null,i=readPodUrl(t);if(i)return resolvePodBaseUrl(i);const s=typeof e.getSession=="function"?e.getSession():e.session,o=readPodUrl(s);if(o)return resolvePodBaseUrl(o);const l=readWebId(s);return l&&l.includes("/profile/card#me")?resolvePodBaseUrl(l):null}function normalizePodDataResourceId(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function resolvePodResourceId(n,e){const t=resolveKnownTargetIri(e);if(t)return parsePodResourceRef(n,t)?.resourceId??normalizePodDataResourceId(t);if(typeof e=="string")return assertCompleteStringResourceId(n,e),normalizePodDataResourceId(e);const i=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!i)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(i)||isTemplateCompleteResourceId(n,i))return normalizePodDataResourceId(i);const s=resolveDefaultResourceId(n,i,e);if(s)return normalizePodDataResourceId(s);const o=podResourceSubjectTemplate(n);return normalizePodDataResourceId(o?renderSubjectTemplateResourceId(o,i,e):i)}function buildPodResourceIri(n,e){const t=resolvePodBaseUrl(n);if(!t||/^https?:\/\//u.test(e))return e;const i=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(i.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(n,e,t){const i=resolveKnownTargetIri(t);if(i)return i;const s=resolvePodRootTargetPath(t);if(s)return buildPodResourceIri(n,s);const o=resolvePodResourceId(e,t),l=isResourceRelativeSubjectId(e,o)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(o)}`:e.resolveUri?.(o)??`/.data/${normalizePodDataResourceId(o)}`;return buildPodResourceIri(n,l)}function buildPodResourceIriForDatabase(n,e,t){const i=resolvePodBaseUrlFromDatabase(n);if(!i)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(i,e,t)}function resolvePodResourceIriForDatabase(n,e,t){if(!t)return null;try{return buildPodResourceIriForDatabase(n,e,t)}catch{return null}}function resolveKnownTargetIri(n){if(typeof n=="string")return/^https?:\/\//u.test(n)?n:null;const e=n["@id"]??n.subject;return typeof e=="string"&&/^https?:\/\//u.test(e)?e:null}function resolvePodRootTargetPath(n){if(typeof n=="string")return n.startsWith("/")?n:null;const e=typeof n.id=="string"?n.id.trim():"";return e.startsWith("/")?e:null}function isCompleteResourceId(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function assertCompleteStringResourceId(n,e){if(isCompleteResourceId(e)||isTemplateCompleteResourceId(n,e))return;const t=n.columns?.id?.options?.defaultValue!==void 0,i=podResourceSubjectTemplate(n);if(t||i)throw new Error("resolvePodResourceId does not accept local keys as string targets. Pass a structured row object with id and required fields, or pass a complete resource id/IRI.")}function resolveDefaultResourceId(n,e,t){const i=n.columns?.id?.options?.defaultValue;if(i===void 0)return null;if(typeof i=="string")return renderDefaultIdTemplate(i,{key:e,row:t,resource:n});if(typeof i!="function")return String(i);const s=i;return s.length===0?String(s()):String(s(e,t))}function renderSubjectTemplateResourceId(n,e,t){const i=n.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(i,{key:encodeURIComponent(e),row:t})}function readPodUrl(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getPodUrl=="function"?e.getPodUrl():e.info?.podUrl??e.podUrl;return typeof t=="string"&&t.trim().length>0?t:null}function readWebId(n){if(!n||typeof n!="object")return null;const e=n,t=e.info?.webId??e.webId;return typeof t=="string"&&t.trim().length>0?t:null}var _a$a;class PodTable{constructor(e,t,i){this.initialized=!1;const s=i.type;if(!s)throw new Error("podTable requires a type (RDF class) via options.type");const o=i.typeIndex,l=o==="private"||o==="public",u=this.resolveBase(i.base,e);this.resourcePath=u.resourcePath,this.containerPath=u.containerPath;const h=this.resolveSubjectTemplate(i.subjectTemplate,u.resourcePath,u.containerPath,e);this.subjectTemplate=h.template,this.hasCustomSubjectTemplate=h.isCustom,this.resourceMode=i.resourceMode??(i.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=i.sparqlEndpoint,this.registerTypeIndexEnabled=l&&i.autoRegister!==!1,this.config={name:e,base:u.resourcePath,type:resolveTermIri(s),namespace:i.namespace,typeIndex:l?o:void 0,saiRegistryPath:i.saiRegistryPath,autoRegister:i.autoRegister,containerPath:u.containerPath,hooks:i.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(i.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let d=0;for(const p of Object.values(t))if(p.options.primaryKey&&d++,p.table=this,p.tableName=e,!p.options.predicate&&!p._virtualId&&!i.namespace)throw new Error(`Column "${p.name}" in table "${e}" is missing a predicate.`);if(d!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${d}.`);this.$inferSelect={},this.$inferInsert={},this.$inferUpdate={},this._={brand:"Table",config:this.config,name:e,schema:void 0,columns:t,inferSelect:{},inferInsert:{},inferUpdate:{}},this.mapping=this.buildTableMapping()}getContainerPath(){return this.containerPath}getType(){return this.config.type}getRdfClass(){return this.getType()}getNamespace(){return this.config.namespace}getSubjectTemplate(){return this.subjectTemplate}buildId(e){return resolvePodResourceId(this,e)}buildIri(e,t){return buildPodResourceIriForResource(e,this,t)}buildIriForDatabase(e,t){return buildPodResourceIriForDatabase(e,this,t)}resolveIriForDatabase(e,t){return resolvePodResourceIriForDatabase(e,this,t)}parseRef(e){return parsePodResourceRef(this,e)}extractTemplateValue(e,t="id"){return extractPodResourceTemplateValue(this,e,t)}hasCustomTemplate(){return this.hasCustomSubjectTemplate}getSubClassOf(){return[...this.parentClasses]}getMapping(){return this.mapping}get $schema(){return new SolidSchema(this.columns,{type:this.config.type,namespace:this.config.namespace,subjectTemplate:this.subjectTemplate,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0})}resolveUri(e){const t=this.subjectTemplate;if(!t)return/^https?:\/\//.test(e)||e.startsWith("/")?e:`${this.config.base.endsWith("/")?this.config.base:`${this.config.base}/`}${e}`;const i=t.replace(/\{id\}/g,e);return i.startsWith("#")?`${this.resourcePath}${i}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${i}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const i=this.normalizeBaseInput(e),s=this.normalizeResourcePath(i);if(s.endsWith("/")){const l=this.ensureTrailingSlash(s);return{resourcePath:l,containerPath:l}}const o=this.ensureTrailingSlash(this.deriveContainerPath(s));return{resourcePath:s,containerPath:o}}normalizeBaseInput(e){const t=e.trim(),i=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(i){const[,s,o]=i,l=s.toLowerCase(),u=o.trim();return l==="http"||l==="https"?`${l}://${u}`:u.startsWith("/")?u:`/${u}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const i=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return i.startsWith("/")?i:`/${i}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,i=t.lastIndexOf("/");return i===-1?"/":t.slice(0,i+1)}ensureTrailingSlash(e){return e.endsWith("/")?e:`${e}/`}getResourcePath(){return this.resourcePath}getResourceMode(){return this.resourceMode}getSparqlEndpoint(){return this.sparqlEndpoint}shouldRegisterTypeIndex(){return this.registerTypeIndexEnabled}async init(e){await e.registerTable(this)}isInitialized(){return this.initialized}markInitialized(e=!0){this.initialized=e}setBase(e){const t=this.resolveBase(e,this.config.name);this.resourcePath=t.resourcePath,this.containerPath=t.containerPath,this.config.base=t.resourcePath,this.config.containerPath=t.containerPath,this._?.config&&(this._.config.base=this.config.base,this._.config.containerPath=this.config.containerPath),this.hasCustomSubjectTemplate||(this.subjectTemplate=void 0,delete this.config.subjectTemplate,this._?.config&&delete this._.config.subjectTemplate),this.mapping=this.buildTableMapping()}setSubjectTemplate(e){this.subjectTemplate=e,this.hasCustomSubjectTemplate=!0,this.config.subjectTemplate=e,this._?.config&&(this._.config.subjectTemplate=e),this.mapping=this.buildTableMapping()}setSparqlEndpoint(e){this.sparqlEndpoint=e,this.resourceMode||(this.resourceMode="sparql")}getColumns(){return this.columns}getColumn(e){return this.columns[e]}hasColumn(e){return e in this.columns}resolveSubjectTemplate(e,t,i,s){return e&&e.trim().length>0?{template:e.trim(),isCustom:!0}:{template:void 0,isCustom:!1}}buildTableMapping(){const e={};for(const t of Object.values(this.columns))e[t.name]=this.buildColumnMapping(t);return{name:this.config.name,type:this.config.type,subjectTemplate:this.subjectTemplate,namespace:this.config.namespace,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0,columns:e,relations:this.relations}}buildColumnMapping(e){const t=e._virtualId?"@id":e.getPredicate(this.config.namespace);return{column:e.name,predicate:t,kind:e.isLink()?"object":"datatype",datatype:this.inferColumnDatatype(e),linkTarget:e.getLinkTarget(),isArray:e.options.isArray??!1,inverse:e.isInverse()}}inferColumnDatatype(e){switch(e.dataType){case"string":return"http://www.w3.org/2001/XMLSchema#string";case"integer":return"http://www.w3.org/2001/XMLSchema#integer";case"boolean":return"http://www.w3.org/2001/XMLSchema#boolean";case"datetime":return"http://www.w3.org/2001/XMLSchema#dateTime";case"json":case"object":return"http://www.w3.org/2001/XMLSchema#json";default:return}}normalizeParents(e){if(!e)return[];const i=(Array.isArray(e)?e:[e]).map(s=>resolveTermIri(s)).filter(s=>s&&s.length>0);return Array.from(new Set(i))}}_a$a=entityKind;PodTable[_a$a]="PodTable";function podTable(n,e,t){const i={};for(const[s,o]of Object.entries(e)){if(o instanceof PodColumnBase){i[s]=o;continue}let l;switch(o.dataType){case"integer":l=new PodIntegerColumn(o.name,o.options);break;case"datetime":l=new PodDateTimeColumn(o.name,o.options);break;case"boolean":l=new PodBooleanColumn(o.name,o.options);break;case"json":l=new PodJsonColumn(o.name,o.options);break;case"object":l=new PodObjectColumn(o.name,o.options);break;case"array":{const h=o.elementType??o.options.baseType??"string";l=new PodArrayColumn(o.name,h,o.options);break}case"uri":l=new PodUriColumn(o.name,o.options);break;default:l=new PodStringColumn(o.name,o.options);break}const u=o.getPredicateUri?.();u&&l.predicate(u),i[s]=l}return new PodTable(n,i,t)}class SolidSchema{constructor(e,t){this.columns=e,this.options=t,this.$kind="SolidSchema",this.namespace=t.namespace,this.subjectTemplate=t.subjectTemplate,this.subClassOf=t.subClassOf?Array.isArray(t.subClassOf)?t.subClassOf.map(resolveTermIri):[resolveTermIri(t.subClassOf)]:void 0}table(e,t){return new PodTable(e,this.columns,{...this.options,...t})}extend(e,t){const i=mergeSchemaColumns(this,e),s=[this.type];return this.subClassOf&&s.push(...this.subClassOf),solidSchema(i,{...t,subClassOf:s})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(n,e){const t={};for(const[i,s]of Object.entries(n)){if(s instanceof PodColumnBase){t[i]=s;continue}let 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 l=s.getPredicateUri?.();l&&o.predicate(l),t[i]=o}return new SolidSchema(t,e)}function isSolidSchema(n){return n instanceof SolidSchema||n?.$kind==="SolidSchema"}const index=Object.freeze(Object.defineProperty({__proto__:null,ColumnBuilder,PodArrayColumn,PodBooleanColumn,PodColumnBase,PodDateTimeColumn,PodIntegerColumn,PodJsonColumn,PodObjectColumn,PodStringColumn,PodTable,PodUriColumn,SolidSchema,boolean:boolean$2,date:date$3,generateNanoId,hasStringValue:hasStringValue$2,hasTermValue,id,integer:integer$1,isSolidSchema,json,mergeSchemaColumns,object:object$1,podTable,real,resolveTermIri,solidSchema,string:string$2,text,timestamp,uri,validateColumnOverride},Symbol.toStringTag,{value:"Module"})),XSD$9="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(n,e){if(!n)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const s=e.getMapping()?.columns?.[n.name];if(s?.predicate)return s.predicate}if(typeof n.getPredicateUri=="function")return n.getPredicateUri();if(n._predicateUri)return n._predicateUri;if(n.predicate&&typeof n.predicate=="string")return n.predicate;const t=e instanceof SolidSchema?e.options.namespace:e.config.namespace;if(typeof n.getPredicate=="function")try{return n.getPredicate(t)}catch{}return n.options?.predicate?n.options.predicate:t?`${typeof t=="string"?t:t.uri}${n.name}`:(n.name==="id"&&console.log("[DEBUG] getPredicateForColumn 'id' fallback to example.org. Column:",n),`http://example.org/${n.name}`)}function formatValue(n,e,t,i){return Array.isArray(n)?n.map(s=>formatSingleValue(s,e,t,i)):formatSingleValue(n,e,t,i)}function formatSingleValue(n,e,t,i){if(n==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const s=String(n);if(s.startsWith("<")&&s.endsWith(">")){const o=s.slice(1,-1);return t&&!t.isAbsoluteUri(o)?`<${t.resolveLink(o,e,i)}>`:s}return t?`<${t.resolveLink(s,e,i)}>`:s.startsWith("<")?s:`<${s}>`}return typeof n=="string"?!e&&(n.startsWith("http://")||n.startsWith("https://"))?`<${n}>`:`"${n.replace(/\\/g,"\\\\").replace(/"/g,'"')}"`:typeof n=="number"?Number.isInteger(n)?String(n):`"${n}"^^<${XSD$9}decimal>`:typeof n=="boolean"?`"${n}"^^<${XSD$9}boolean>`:n instanceof Date?`"${n.toISOString()}"^^<${XSD$9}dateTime>`:`"${String(n)}"`}function resolveColumn(n,e){if(n&&typeof n=="object"&&n instanceof PodColumnBase)return n;if(n&&typeof n=="object"&&"name"in n){const t=n.name;if(typeof t=="string"&&e.columns[t])return e.columns[t]}if(typeof n=="string"){const t=e.columns[n];if(t)return t}throw new Error(`Unable to resolve column reference for select field: ${String(n)}`)}function generateSubjectUri(n,e,t){const i=t.resolveSubject(e,n);if(!i)throw new Error("Failed to generate subject URI");return i}var _a$9;class SPARQLExpression{constructor(){this[_a$9]="SPARQLExpression"}}_a$9=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,i){super(),this.left=e,this.operator=t,this.right=i,this.type="binary_expr"}}class LogicalExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.expressions=t,this.type="logical_expr"}}class UnaryExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.value=t,this.type="unary_expr"}}class SelectionAliasExpression extends SPARQLExpression{constructor(e){super(),this.alias=e}}function eq(n,e){return new BinaryExpression(n,"=",e)}function like(n,e){return new BinaryExpression(n,"LIKE",e)}function inArray(n,e){return new BinaryExpression(n,"IN",e)}function and(...n){return new LogicalExpression("AND",n.filter(Boolean))}function or(...n){return new LogicalExpression("OR",n.filter(Boolean))}function parseActivityStreamsMessage(n){const e=JSON.parse(n);return{id:e.id||e["@id"]||"",type:e.type,object:typeof e.object=="string"?e.object:e.object?.id||e.object?.["@id"]||"",published:e.published||new Date().toISOString(),state:e.state}}class BaseChannel{constructor(e){this._connected=!1,this.config=e}get connected(){return this._connected}handleMessage(e){try{const t=parseActivityStreamsMessage(e);this.config.onNotification(t)}catch(t){this.handleError(new Error(`Failed to parse notification: ${t}`))}}handleError(e){this.config.onError?this.config.onError(e):console.error("[NotificationChannel] Error:",e)}handleClose(){this._connected=!1,this.config.onClose&&this.config.onClose()}}class SSEChannel extends BaseChannel{constructor(e){super(e),this.abortController=null,this.reader=null,this.contentType=""}async connect(){if(this._connected)return;this.abortController=new AbortController;const e=this.config.fetch||fetch;try{const t=`notify-sse-${Date.now()}`,i=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!i.ok)throw new Error(`SSE connection failed: ${i.status} ${i.statusText}`);if(!i.body)throw new Error("SSE response has no body");this.contentType=i.headers.get("content-type")||"",this._connected=!0,this.reader=i.body.getReader(),this.readStream()}catch(t){throw t.name!=="AbortError"&&this.handleError(t),t}}disconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader&&(this.reader.cancel().catch(()=>{}),this.reader=null),this._connected=!1,this.handleClose()}async readStream(){if(!this.reader)return;const e=new TextDecoder;let t="";try{for(;this._connected;){const{done:i,value:s}=await this.reader.read();if(i){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const o=e.decode(s,{stream:!0});t+=o,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(i){i.name!=="AbortError"&&this.handleError(i)}}processTurtleBuffer(e){const t=e.split(`
13
13
  `);let i="";for(let s=0;s<t.length;s++){const o=t[s];i+=o+`
14
14
  `,o.trim().endsWith(".")&&(this.parseTurtleNotification(i.trim()),i="")}return i}processSSEBuffer(e){const t=e.split(`
15
15
 
@@ -45,7 +45,7 @@ LIMIT 50`,prefixes:{}},d=s.kind==="sparql"?await this.dialect.executeOnResource(
45
45
  VALUES ?linkPred { ${u} }
46
46
  ?parent ?linkPred ?child .
47
47
  OPTIONAL { ?child ?pred ?obj . }
48
- }`,prefixes:{}},F=await h.executeQueryWithSource(T,x);d.push(...F)}const g=t.config.namespace?.uri??t.config.namespace,m=new Map,v=new Map;d.forEach(x=>{const A=this.normalizeInlineIri(x.parent),C=this.normalizeInlineIri(x.linkPred),T=this.normalizeInlineIri(x.child),F=this.normalizeInlineIri(x.pred),P=this.normalizeInlineObjectValue(x.obj);if(!A||!C)return;const q=o.get(C);if(q){const M=m.get(A)??new Map,ee=M.get(q.name)??[];T&&!ee.includes(T)&&ee.push(T),M.set(q.name,ee),m.set(A,M)}if(!T||!F)return;const O=v.get(T)??{"@id":T,id:this.extractIdFromSubject(T,t)},G=this.normalizeInlinePredicateKey(F,g);if(P===void 0){v.set(T,O);return}const fe=O[G];fe===void 0?O[G]=P:Array.isArray(fe)?O[G]=[...fe,P]:O[G]=[fe,P],v.set(T,O)});const S=x=>{if(Array.isArray(x))return x.map(C=>this.normalizeInlineIri(C)).filter(C=>!!C);const A=this.normalizeInlineIri(x);return A?[A]:[]},E=(x,A,C)=>{const T=x?m.get(x)?.get(C.name)??[]:[],P=(T.length>0?T:S(A)).map(q=>v.get(q)??{"@id":q,id:this.extractIdFromSubject(q,t)});return C.dataType==="array"?P:P[0]??null};return e.forEach(x=>{const A=this.normalizeInlineIri(x["@id"]??x.subject??x.uri??x.id);s.forEach(C=>{x[C.name]=E(A,x[C.name],C)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const i=e.lastIndexOf("#");if(i!==-1&&i<e.length-1)return e.slice(i+1);const s=e.lastIndexOf("/");return s!==-1&&s<e.length-1?e.slice(s+1):e}normalizeInlineObjectValue(e){if(e!=null)return typeof e=="object"&&"value"in e?e.value??void 0:e}normalizeInlineIri(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&typeof e["@id"]=="string")return e["@id"];if(typeof e=="object"&&typeof e.id=="string"&&e.id.includes("http"))return e.id;if(typeof e=="object"&&typeof e.value=="string")return e.value}}applyDeferredOrderBy(e){if(this.orderByClauses.length===0||e.length<2)return e;const t=[...e];return t.sort((i,s)=>{for(const o of this.orderByClauses){const l=this.getOrderByValue(i,o.column),u=this.getOrderByValue(s,o.column),h=this.compareOrderByValues(l,u);if(h!==0)return o.direction==="desc"?-h:h}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,i=[];for(const s of e){const o=this.serializeValueForKey(s);t.has(o)||(t.add(o),i.push(s))}return i}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,i=t>0?e.slice(t):e;return this.limitCount===void 0?i:i.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const i=Object.keys(e).find(s=>s.endsWith(`.${t}`));if(i)return e[i]}compareOrderByValues(e,t){return e===t?0:e==null?1:t==null?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}mergeRowsBySubject(e){const t=new Map,i=[];return e.forEach(o=>{const l=this.normalizeInlineIri(o["@id"])??this.normalizeInlineIri(o.subject)??this.normalizeInlineIri(o.uri)??(typeof o.id=="string"?o.id:void 0);if(typeof process<"u"&&define_process_env_default$2?.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",l),!l){i.push(`__anon_${i.length}`),t.set(i[i.length-1],{...o});return}if(!t.has(l)){const d={...o};Object.entries(d).forEach(([p,g])=>{if(g===void 0)return;const m=this.getColumnDefinitionForRowKey(p);(m?.options?.isArray||m?.dataType==="array")&&!Array.isArray(g)&&(d[p]=[g])}),t.set(l,d),i.push(l);return}const u=t.get(l),h=d=>{if(d instanceof Date)return`date:${d.toISOString()}`;if(typeof d=="string")return`str:${d}`;if(typeof d=="number")return`num:${d}`;if(typeof d=="boolean")return`bool:${d}`;if(d==null)return"nil";try{return`obj:${JSON.stringify(d)}`}catch{return`obj:${String(d)}`}};Object.entries(o).forEach(([d,p])=>{if(p===void 0)return;const g=u[d];if(g===void 0){u[d]=p;return}const m=Array.isArray(g)?g:[g],v=Array.isArray(p)?p:[p],S=[...m];v.forEach(A=>{const C=h(A);S.some(T=>h(T)===C)||S.push(A)});const E=this.getColumnDefinitionForRowKey(d),x=E?.options?.isArray||E?.dataType==="array";!x&&S.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${d}' on subject '${l}'. Using first value.`),u[d]=S[0]):x?u[d]=S:u[d]=S.length===1?S[0]:S})}),i.map(o=>t.get(o))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,i]=e.split(".",2);if(!(!t||!i))return t===this.primaryAlias?this.selectedTable?.columns[i]:this.aliasToTable.get(t)?.columns?.[i]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const i=e.indexOf("#");if(i>0)return e.slice(0,i);const s=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return s?s.startsWith("http")?s:`${this.session.getDialect().getPodUrl()}${s.replace(/^\//,"")}`:this.session.getDialect().getPodUrl()}isInlineObjectColumn(e){return e?e.dataType==="object"?!0:e.dataType==="array"?(e.elementType??e.options?.baseType)==="object":!1:!1}async applyJoinFallback(e){let t=e;for(const i of this.joins){const s=await this.fetchJoinRows(i,t);t=this.mergeRowsWithJoin(t,i,s)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const S=await this.session.select().from(e.table);return this.normalizeJoinRows(e,S)}const i=e.resolvedConditions??[];if(i.length===0)return[];const[s]=i,o=s.left.alias===e.alias?s.left:s.right,l=o===s.left?s.right:s.left,u=new Map;for(const S of t){const E=this.getRowValueForColumn(S,l);if(E==null)continue;const x=this.serializeValueForKey(E);u.has(x)||u.set(x,E)}if(u.size===0)return[];const h=Array.from(u.values()),d=()=>this.session.select().from(e.table),p=e.table.getColumn(o.column),g=this.buildExactJoinLookupConditions(e,t);if(g&&g.length>0){const S=[];for(const E of g){const x=d(),C=await(conditionTargetsReservedIdentifier(E)?x.applyInternalQueryCondition(E):x.where(E));S.push(...C)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,S))}const m=this.buildJoinLookupCondition(p,h);if(m){const S=d(),x=await(conditionTargetsReservedIdentifier(m)?S.applyInternalQueryCondition(m):S.where(m));return this.normalizeJoinRows(e,x)}const v=await d();return this.normalizeJoinRows(e,v)}buildExactJoinLookupConditions(e,t){const i=e.resolvedConditions??[];if(i.length===0)return;const[s]=i,o=s.left.alias===e.alias?s.left:s.right,l=o===s.left?s.right:s.left,u=this.getRequiredSubjectTemplateVariables(e.table),h=o.column==="id"&&u.length>0;if(!h&&i.length===1)return;const d=new Map;for(const m of i){const v=m.left.alias===e.alias?m.left:m.right;d.set(v.column,m)}const p=[],g=new Set;for(const m of t){const v=this.getRowValueForColumn(m,l);if(v==null)continue;const S=typeof v=="string"&&this.isAbsoluteIri(v),E=[],x=[];let A=!1;for(const T of i){const F=T.left.alias===e.alias?T.left:T.right,P=F===T.left?T.right:T.left,q=this.getRowValueForColumn(m,P);if(q==null){if(h&&!S&&u.includes(F.column))throw new Error(this.buildMissingJoinLocatorError(e,u.filter(G=>{const fe=d.get(G);if(!fe)return!0;const ee=(fe.left.alias===e.alias?fe.left:fe.right)===fe.left?fe.right:fe.left,Se=this.getRowValueForColumn(m,ee);return Se==null})));A=!0;break}const O=e.table.getColumn(F.column);if(!O){A=!0;break}E.push(eq(O,q)),x.push(`${F.column}:${this.serializeValueForKey(q)}`)}if(A)continue;if(h&&!S){const T=u.filter(F=>{const P=d.get(F);if(!P)return!0;const O=(P.left.alias===e.alias?P.left:P.right)===P.left?P.right:P.left,G=this.getRowValueForColumn(m,O);return G==null});if(T.length>0)throw new Error(this.buildMissingJoinLocatorError(e,T))}if(E.length===0)continue;const C=x.join("|");g.has(C)||(g.add(C),p.push(E.length===1?E[0]:and(...E)))}return p.length>0?p:void 0}buildJoinLookupCondition(e,t){if(!(!e||t.length===0))return t.length===1?eq(e,t[0]):inArray(e,t)}getRequiredSubjectTemplateVariables(e){const t=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"";return Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>i[1].split("|")[0]?.trim()||i[1]).filter(Boolean))).filter(i=>i!=="id"&&i!=="index"&&i!=="yyyy"&&i!=="MM"&&i!=="dd"&&i!=="HH"&&i!=="mm"&&i!=="ss"&&i!=="timestamp"&&i!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const i=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",s=Array.from(new Set(t)),o=s[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${i}" because locator variable(s) [${s.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${o}, join.${o})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(i=>{const s={};for(const[l,u]of Object.entries(i))s[`${e.alias}.${l}`]=u;const o=this.extractSubjectValue(i);if(o){s.subject=o,s["@id"]=o,s.uri=o,s[`${e.alias}.subject`]=o,s[`${e.alias}.@id`]=o,s[`${e.alias}.uri`]=o;const l=this.extractIdFromSubject(o,e.table);l!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||s[`${e.alias}.id`]===void 0)&&(s[`${e.alias}.id`]=l)}return s})}mergeRowsWithJoin(e,t,i){if(t.type==="crossJoin"){if(e.length===0||i.length===0)return[];const p=[];for(const g of e)for(const m of i)p.push({...g,...m});return p}const s=t.resolvedConditions??[];if(s.length===0)return e;const[o]=s,l=o.left.alias===t.alias?o.left:o.right,u=l===o.left?o.right:o.left,h=new Map;for(const p of i){const g=this.getRowValueForColumn(p,l);if(g==null)continue;const m=this.serializeValueForKey(g);h.has(m)||h.set(m,[]),h.get(m).push(p)}const d=[];for(const p of e){const g=this.getRowValueForColumn(p,u),m=this.serializeValueForKey(g),S=(g!=null?h.get(m)??[]:[]).filter(E=>this.joinRowMatchesAllConditions(p,E,t.alias,s));if(S.length===0){if(t.type==="innerJoin")continue;d.push({...p,...this.createEmptyJoinRow(t)});continue}for(const E of S)d.push({...p,...E})}return d}joinRowMatchesAllConditions(e,t,i,s){return s.every(o=>{const l=o.left.alias===i?o.left:o.right,u=l===o.left?o.right:o.left,h=this.getRowValueForColumn(e,u),d=this.getRowValueForColumn(t,l);return h==null||d===void 0||d===null?!1:this.serializeValueForKey(h)===this.serializeValueForKey(d)})}createEmptyJoinRow(e){const t={};for(const i of Object.keys(e.table.columns))t[`${e.alias}.${i}`]=void 0;return t[`${e.alias}.subject`]=void 0,t[`${e.alias}.id`]=void 0,t}applyJoinFilters(e){return this.joinFilters.length===0?e:e.filter(t=>this.joinFilters.every(i=>this.evaluateCondition(t,i)))}applyHavingFilter(e){return this.havingCondition?e.filter(t=>this.evaluateCondition(t,this.havingCondition)):e}evaluateCondition(e,t){switch(t.type){case"binary_expr":return this.evaluateBinaryCondition(e,t);case"unary_expr":return this.evaluateUnaryCondition(e,t);case"logical_expr":return this.evaluateLogicalCondition(e,t);default:return!0}}evaluateBinaryCondition(e,t){const i=t.left,s=t.right,o=t.operator;if(!i)return!0;const l=this.resolveConditionOperandValue(e,i,this.primaryAlias),u=this.resolveConditionOperandValue(e,s);switch(o.toUpperCase()){case"=":return l===u;case"!=":case"<>":return l!==u;case">":return Number(l)>Number(u);case">=":return Number(l)>=Number(u);case"<":return Number(l)<Number(u);case"<=":return Number(l)<=Number(u);case"IN":return Array.isArray(u)&&u.includes(l);case"NOT IN":return Array.isArray(u)&&!u.includes(l);case"LIKE":return typeof l=="string"&&typeof u=="string"&&this.computeLikeMatch(l,u);default:return!0}}evaluateUnaryCondition(e,t){const i=t.operator,s=t.value;if(i.toUpperCase()==="NOT")return!this.evaluateCondition(e,s);if(!s)return!0;const o=this.resolveConditionOperandValue(e,s,this.primaryAlias);switch(i.toUpperCase()){case"IS NULL":return o==null;case"IS NOT NULL":return o!=null;default:return!0}}evaluateLogicalCondition(e,t){const i=t.operator,s=t.expressions??[];return i.toUpperCase()==="AND"?s.every(o=>this.evaluateCondition(e,o)):i.toUpperCase()==="OR"?s.some(o=>this.evaluateCondition(e,o)):!0}resolveConditionOperandValue(e,t,i){if(t instanceof SelectionAliasExpression)return e[t.alias];const s=this.getConditionColumnReference(t,i);return s?this.getRowValueForColumn(e,s):t}getColumnKeyCandidates(e){const t=[],i=this.primaryAlias;return e.alias===i&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const i=this.getColumnKeyCandidates(t);for(const s of i)if(s in e)return e[s]}shouldUseSubjectIdentityColumn(e,t){const i=e?.columns?.[t];return!!(i?._virtualId||i?.options?.predicate==="@id")}serializeValueForKey(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}extractIdFromSubject(e,t){if(!e)return;if(t){const o=parsePodResourceRef(t,e);if(o)return o.templateValues.id??o.resourceId}if(t){const o=this.session.getDialect?.(),u=(o?.getUriResolver?.()??new UriResolverImpl(o?.getPodUrl?.()??"")).parseSubject(e,t);if(u&&u.id)return u.id}const i=e.indexOf("#");if(i!==-1)return e.slice(i);const s=e.lastIndexOf("/");if(s!==-1){const o=e.slice(s+1);if(o.length>0)return o}}computeLikeMatch(e,t){const i=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/%/g,".*").replace(/_/g,".")}$`,"i").test(e)}async selectIdsByCondition(e,t){return(await this.session.select({id:e.getColumn("id")??e.columns.id}).from(e).where(t).columns({"@id":e.columns.id})).map(o=>o.id||o["@id"]).filter(o=>typeof o=="string"&&o.length>0)}then(e,t){return this.execute().then(e,t)}}_a$7=entityKind;SelectQueryBuilder[_a$7]="SelectQueryBuilder";var _a$6;class InsertQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.getRowsWithDefaults();return{table:this.table,rows:i}}}values(e){return e instanceof SQL?this.sql=e:this.insertValues=e,this}returning(e){return this.returningFields=e??!0,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertInsert(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL insert in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.insertValues){const e=this.getRowsWithDefaults(),t=this.returningFields?this.getSubjectUris(e):[],i={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},s=await this.session.execute(i),o=this.returningFields?await this.fetchReturningRowsBySubjects(t):s;return await this.runAfterInsertHooks(o),o}else throw new Error("No values specified for INSERT query")}then(e,t){return this.execute().then(e,t)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e);return projectReturningRows(orderRowsBySubjects(t,e),this.returningFields)}getSubjectUris(e){const t=this.session.getDialect().getUriResolver?.();if(!t)throw new Error("returning() requires dialect URI resolver support");return e.map(i=>generateSubjectUri(i,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const i=this.buildHookContext();if(!i){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterInsert(i,s)}catch(o){console.error("[InsertQueryBuilder] afterInsert hook failed:",o)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}getRowsWithDefaults(){const e=this.insertValues;if(!e)throw new Error("No values specified for INSERT query");return(Array.isArray(e)?e:[e]).map(i=>this.applyDefaultValues(i))}applyDefaultValues(e){const t={...e},i=this.table?.columns??{},s=Object.entries(i);for(const[o,l]of s.filter(([,u])=>!this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,o,l);for(const[o,l]of s.filter(([,u])=>this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,o,l);return t}applyDefaultValue(e,t,i){if(e[t]===void 0){const s=i.options?.defaultValue;s!==void 0&&(e[t]=this.resolveDefaultValue(s,i,e))}}resolveDefaultValue(e,t,i){const s=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&s)return renderDefaultIdTemplate(e,{key:s,row:i,resource:this.table});if(typeof e!="function")return e;const o=e;return o.length===0?o():o(s,i)}isPrimaryKeyColumn(e){return e.options?.primaryKey===!0||e.options?.predicate==="@id"}}_a$6=entityKind;InsertQueryBuilder[_a$6]="InsertQueryBuilder";var _a$5;class UpdateQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{if(!this.updateData)throw new Error("No data specified for UPDATE query");const i=this.normalizeWhereConditionsForUpdate();if(!i)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:i}}}set(e){return e instanceof SQL?this.sql=e:this.updateData=e,this}returning(e){return this.returningFields=e??!0,this}where(e){if(e instanceof SQL)this.sql||(this.sql=e);else if(this.isQueryCondition(e)){assertPublicWhereCondition("update",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("update",e),this.whereConditions=e,this.conditionTree=void 0;return this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),o=inferSPARQLQueryType(s);if(!o)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:o,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertUpdate(i.data,i.where,i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL update in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.updateData){const e=this.toIR(),i=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"update",table:this.table,data:e.data,where:e.where,plan:e},o=await this.session.execute(s),l=this.returningFields?await this.fetchReturningRowsBySubjects(i):o;return await this.runAfterUpdateHooks(l),l}else throw new Error("No data specified for UPDATE query")}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];return!this.conditionTree&&typeof t=="string"?await this.session.select().from(this.table).whereByIri(t):await this.session.select().from(this.table).where(e)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e),i=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),s=Object.entries(this.updateData??{}).filter(([,o])=>Array.isArray(o));return s.length===0?i:i.map(o=>{const l={...o};for(const[u,h]of s)u in l&&(l[u]=[...h]);return l})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const i=this.buildHookContext();if(!i){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const s=this.updateData??{};for(const o of e)try{await t.afterUpdate(i,o,s)}catch(l){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",l)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$5=entityKind;UpdateQueryBuilder[_a$5]="UpdateQueryBuilder";var _a$4;class DeleteQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.normalizeWhereConditionsForDelete();return{table:this.table,where:i}}}where(e){if(e instanceof SQL)this.sql=e;else if(this.isQueryCondition(e)){assertPublicWhereCondition("delete",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("delete",e),this.whereConditions=e,this.conditionTree=void 0;return this}returning(e){return this.returningFields=e??!0,this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),o=inferSPARQLQueryType(s);if(!o)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:o,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertDelete(i.where??{},i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL delete in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else{const e=this.toIR(),t=this.returningFields?await this.fetchMatchedRows(e.where):[],i=t.map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"delete",table:this.table,where:e.where,plan:e},o=await this.session.execute(s),l=this.returningFields?projectReturningRows(orderRowsBySubjects(t,i),this.returningFields):o;return await this.runAfterDeleteHooks(l),l}}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];if(!this.conditionTree&&typeof t=="string")return await this.session.select().from(this.table).whereByIri(t);let i=this.session.select().from(this.table);return e&&(i=i.where(e)),await i}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const i=this.buildHookContext();if(!i){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterDelete(i,s)}catch(o){console.error("[DeleteQueryBuilder] afterDelete hook failed:",o)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$4=entityKind;DeleteQueryBuilder[_a$4]="DeleteQueryBuilder";var _a$3;class PodAsyncSession{constructor(e,t,i={}){this.dialect=e,this._schema=t,this.options=i}getSchema(){return this._schema}isConnected(){return this.dialect.isConnected()}getDialect(){return this.dialect}getOptions(){return this.options}async ensureInitialized(e){const t=typeof this.dialect.getResourcePreparationMode=="function"?this.dialect.getResourcePreparationMode():"best-effort";if(t==="off"){e&&typeof e.markInitialized=="function"&&e.markInitialized(!0);return}if(e&&typeof e.isInitialized=="function"){if(!e.isInitialized())try{typeof e.init=="function"?await e.init(this.dialect):await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i}}async execute(e){if(this.options.logger&&console.log("Executing operation:",e),!e||!e.type)throw new Error("Invalid operation: missing type");if(!e.table)throw new Error("Invalid operation: missing table");if(!["select","insert","update","delete"].includes(e.type))throw new Error(`Unsupported operation type: ${e.type}`);if(await this.ensureInitialized(e.table),Array.isArray(e.joins))for(const s of e.joins)s?.table&&await this.ensureInitialized(s.table);const i=await this.dialect.query(e);return this.updateSubjectIndex(e,i),i}updateSubjectIndex(e,t){if(e.type==="select")return;const i=this.dialect;if(typeof i.registerResourceSubject!="function"&&typeof i.unregisterResourceSubject!="function")return;const s=this.resolveOperationSubjects(e,t);if(e.type==="delete"){s.forEach(o=>i.unregisterResourceSubject?.(e.table,o));return}s.forEach(o=>i.registerResourceSubject?.(e.table,o))}resolveOperationSubjects(e,t){const i=new Set;for(const s of t){const o=this.getKnownRowIri(s);o&&i.add(o)}if(e.type==="insert"){const s=e.plan;(Array.isArray(s?.rows)?s.rows:[]).forEach(l=>{try{i.add(generateSubjectUri(l,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(i)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const i of["@id","subject","uri","source"]){const s=t[i];if(typeof s=="string"&&/^https?:\/\//.test(s))return s}return null}async executeSql(e,t){return this.options.logger&&console.log("Executing SQL AST:",e),await this.ensureInitialized(t),await this.dialect.executeSql(e,t)}select(e){return new SelectQueryBuilder(this,e)}insert(e){return new InsertQueryBuilder(this,e)}update(e){return new UpdateQueryBuilder(this,e)}delete(e){return new DeleteQueryBuilder(this,e)}async transaction(e){return await e(this)}}_a$3=entityKind;PodAsyncSession[_a$3]="PodAsyncSession";const resolveCreateRequire$1=()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(!nodeRequire)return null;const moduleLib=nodeRequire("module");return!moduleLib||typeof moduleLib.createRequire!="function"?null:moduleLib.createRequire}catch{return null}},createRequireFn=resolveCreateRequire$1(),isAbsoluteModuleFilename=n=>n.startsWith("file:")||n.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(n),moduleFilename=typeof __filename=="string"&&isAbsoluteModuleFilename(__filename)?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json",createDefaultRequireModule=()=>{if(!createRequireFn)return null;try{return createRequireFn(moduleFilename)}catch{return null}},defaultRequireModule=createDefaultRequireModule(),patchActionObserverHttp=(n,e)=>{if(!n)return!1;try{const t=n(e);if(t&&t.ActionObserverHttp){if(t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied)return!0;const i=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(s,o,l){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),i.call(this,s,o,l)},t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied=!0,!0}return!1}catch{return!1}},applyComunicaPatches=(n=defaultRequireModule)=>n?["@comunica/actor-query-result-serialize-sparql-json","@comunica/actor-query-result-serialize-stats","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-sparql-json","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-stats"].map(t=>patchActionObserverHttp(n,t)).some(Boolean):!1;applyComunicaPatches();let configuredQueryEngineFactory=null;const resolveCreateRequire=async()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(nodeRequire){const n=nodeRequire("module");if(n&&typeof n.createRequire=="function")return n.createRequire}}catch{}try{const n=await __vitePreload(()=>import("node:module"),[]);if(typeof n.createRequire=="function")return n.createRequire}catch{}return null},buildMissingComunicaError=n=>{const e=n instanceof Error&&n.message?` Original error: ${n.message}`:"";return new Error("A SPARQL query engine is required for this operation. Install `@comunica/query-sparql-solid` in the consuming app, or provide `sparql.createQueryEngine` to `drizzle(...)`, or call `configureSparqlEngine(...)` before executing LDP/SPARQL-client queries."+e)},loadComunicaModuleWithRequire=async n=>{const e=await resolveCreateRequire();if(!e)throw new Error("Node module resolution is not available in this runtime.");const t=e(n);applyComunicaPatches(t);const i=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!i||typeof i.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return i},loadDefaultComunicaModule=async()=>{try{return await loadComunicaModuleWithRequire(typeof __filename=="string"?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json")}catch(n){try{applyComunicaPatches();const e=await __vitePreload(()=>import("./index-browser-CazX1pc2.js").then(t=>t.i),[]);if(applyComunicaPatches(),e&&typeof e.QueryEngine=="function")return e}catch(e){throw buildMissingComunicaError(e??n)}throw buildMissingComunicaError(n)}},createDefaultQueryEngine=async()=>{const n=await loadDefaultComunicaModule();return new n.QueryEngine},configureSparqlEngine=n=>{configuredQueryEngineFactory=n?.createQueryEngine??null},getConfiguredSparqlEngineFactory=n=>n??configuredQueryEngineFactory??createDefaultQueryEngine;class ComunicaSPARQLExecutor{constructor(e){this.engine=null,this.sources=[...e.sources],this.fetchFn=this.createSafeFetch(e.fetch||fetch),this.logging=e.logging||!1,this.createQueryEngine=getConfiguredSparqlEngineFactory(e.createQueryEngine)}formatError(e){return e instanceof Error?e.message:String(e)}createSourceRef(e,t="auto"){return t==="sparql"?{type:"sparql",value:e}:e}createSafeFetch(e){return async(t,i)=>{try{const s=await e(t,i),o=new Map;s.headers&&s.headers.forEach((h,d)=>{o.set(d.toLowerCase(),h||"")});const u={...s,headers:{get:h=>{const d=h.toLowerCase();return o.get(d)||null},has:h=>{const d=h.toLowerCase();return o.has(d)},forEach:h=>{o.forEach((d,p)=>h(d,p))},entries:()=>o.entries(),keys:()=>o.keys(),values:()=>o.values(),[Symbol.iterator]:()=>o.entries(),includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(o.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1}},status:s.status||200,statusText:s.statusText||"OK",ok:s.ok!==void 0?s.ok:!0,url:s.url||(typeof t=="string"?t:t.toString()),type:s.type||"basic",redirected:s.redirected||!1,body:s.body,bodyUsed:s.bodyUsed||!1,includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(o.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1},text:async()=>{try{return await s.text()}catch(h){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(h)),""}},json:async()=>{try{return await s.json()}catch(h){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(h)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,i)}catch(h){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(h)),u}}};return u}catch(s){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(s)),s}}}async initEngine(){return this.engine||(this.engine=await this.createQueryEngine()),this.engine}async executeQuery(e){try{const t=await this.initEngine();if(this.logging&&console.log(`[Comunica] Executing ${e.type} query:`,e.query),e.type==="SELECT")return await this.executeSelectInternal(e,t);if(e.type==="ASK")return await this.executeAskInternal(e,t);if(["INSERT","UPDATE","DELETE"].includes(e.type))return await this.executeUpdate(e,t);throw new Error(`Unsupported query type: ${e.type}`)}catch(t){throw console.error("SPARQL query execution failed:",this.formatError(t)),t}}async executeSelect(e){try{this.logging&&console.log("[SPARQL] Executing SELECT query with full processing");const t={type:"SELECT",query:e.trim()},i=this.sources[0];if(!i)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",i)),await this.executeQueryWithSource(t,i)}catch(t){throw this.logging&&console.error("[Simple] SELECT query execution failed:",this.formatError(t)),t}}async queryBindings(e,t){return await(await(await this.initEngine()).queryBindings(e,{sources:[t],fetch:this.fetchFn})).toArray()}async executeSelectInternal(e,t){try{if(this.sources.length===0)throw new Error("No sources configured for SPARQL query");return(await(await t.queryBindings(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})).toArray()).map(o=>{const l=o,u={},h=(d,p)=>{const g=this.extractBindingKeyName(d);g&&(u[g]=this.convertComunicaTerm(p))};if(l&&typeof l.forEach=="function")l.forEach((d,p)=>h(p,d));else if(l&&typeof l.entries=="function")for(const[d,p]of l.entries())h(d,p);else for(const d in l)Object.prototype.hasOwnProperty.call(l,d)&&h(d,l[d]);return u})}catch(i){throw console.error("SELECT query failed:",this.formatError(i)),i}}async executeAskInternal(e,t){try{if(this.logging&&console.log("[Comunica] Executing ASK query:",e.query),this.sources.length===0)throw new Error("No sources configured for SPARQL query");return[{result:await t.queryBoolean(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})}]}catch(i){throw console.error("ASK query failed:",this.formatError(i)),i}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const i=[];for(const s of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${s}:`,e.query.substring(0,100)+"...");let o=null;try{const d=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});d.ok&&(o=d.headers.get("ETag"),this.logging&&o&&console.log(`[UPDATE] Got ETag for ${s}: ${o}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${s}, continuing without ETag`)}const l={"Content-Type":"application/sparql-update","If-Match":o??"*"},u=async d=>this.fetchFn(s,{method:"PATCH",headers:d,body:e.query}),h=await u(l);if(h.ok)i.push({success:!0,source:s,status:h.status}),await this.invalidateCache(t,s);else if(h.status===409||h.status===412){this.logging&&console.log(`[UPDATE] ${h.status} conflict for ${s}, trying multiple retry strategies`);let d=!1;if(h.status===412)try{const p=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});if(p.ok){const g=p.headers.get("ETag");if(g){const m={...l,"If-Match":g},v=await u(m);v.ok&&(i.push({success:!0,source:s,status:v.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,s),d=!0)}}}catch(p){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",p)}if(!d)try{const p=await u({"Content-Type":"application/sparql-update"});p.ok&&(i.push({success:!0,source:s,status:p.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,s),d=!0)}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",p)}if(!d)try{if((await this.fetchFn(s,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const g=await this.fetchFn(s,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});g.ok&&(i.push({success:!0,source:s,status:g.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,s),d=!0)}}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",p)}if(!d){const p=await h.text();i.push({success:!1,source:s,error:`All retry strategies failed: ${h.status} ${h.statusText}`,details:p})}}else{const d=await h.text();i.push({success:!1,source:s,error:`${h.status} ${h.statusText}`,details:d})}}catch(o){i.push({success:!1,source:s,error:this.formatError(o)})}return i}catch(i){throw console.error("UPDATE query failed:",this.formatError(i)),i}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const i=e.invalidateHttpCache;if(typeof i=="function")try{await i.call(e,t)}catch(s){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(s))}}extractBindingKeyName(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="object"){const t=e;if(t&&typeof t.value=="string"||t&&t.termType==="Variable"&&typeof t.value=="string")return t.value}return typeof e=="symbol"?e.description??e.toString():String(e)}convertComunicaTerm(e){if(!e)return null;const t=e;switch(t.termType){case"NamedNode":return t.value;case"Literal":if(t.datatype&&t.datatype.value){const i=t.datatype.value;if(typeof i=="string"){if(i.includes("#integer")||i.includes("#int"))return parseInt(String(t.value),10);if(i.includes("#decimal")||i.includes("#double"))return parseFloat(String(t.value));if(i.includes("#boolean"))return t.value==="true";if(i.includes("#dateTime"))return new Date(String(t.value));if(i.includes("#json"))try{return JSON.parse(String(t.value))}catch(s){return console.warn("Failed to parse JSON value:",t.value,this.formatError(s)),t.value}else if(i.includes("#jsonArray")||i.includes("solid/terms#jsonArray"))try{const s=JSON.parse(String(t.value));return Array.isArray(s)?s:(console.warn("Expected array but got:",typeof s,s),[s])}catch(s){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(s)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const i=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let s;return t?s=t:s={type:"SELECT",query:`
48
+ }`,prefixes:{}},F=await h.executeQueryWithSource(T,x);d.push(...F)}const g=t.config.namespace?.uri??t.config.namespace,m=new Map,v=new Map;d.forEach(x=>{const A=this.normalizeInlineIri(x.parent),C=this.normalizeInlineIri(x.linkPred),T=this.normalizeInlineIri(x.child),F=this.normalizeInlineIri(x.pred),P=this.normalizeInlineObjectValue(x.obj);if(!A||!C)return;const q=o.get(C);if(q){const M=m.get(A)??new Map,ee=M.get(q.name)??[];T&&!ee.includes(T)&&ee.push(T),M.set(q.name,ee),m.set(A,M)}if(!T||!F)return;const O=v.get(T)??{"@id":T,id:this.extractIdFromSubject(T,t)},G=this.normalizeInlinePredicateKey(F,g);if(P===void 0){v.set(T,O);return}const fe=O[G];fe===void 0?O[G]=P:Array.isArray(fe)?O[G]=[...fe,P]:O[G]=[fe,P],v.set(T,O)});const S=x=>{if(Array.isArray(x))return x.map(C=>this.normalizeInlineIri(C)).filter(C=>!!C);const A=this.normalizeInlineIri(x);return A?[A]:[]},E=(x,A,C)=>{const T=x?m.get(x)?.get(C.name)??[]:[],P=(T.length>0?T:S(A)).map(q=>v.get(q)??{"@id":q,id:this.extractIdFromSubject(q,t)});return C.dataType==="array"?P:P[0]??null};return e.forEach(x=>{const A=this.normalizeInlineIri(x["@id"]??x.subject??x.uri??x.id);s.forEach(C=>{x[C.name]=E(A,x[C.name],C)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const i=e.lastIndexOf("#");if(i!==-1&&i<e.length-1)return e.slice(i+1);const s=e.lastIndexOf("/");return s!==-1&&s<e.length-1?e.slice(s+1):e}normalizeInlineObjectValue(e){if(e!=null)return typeof e=="object"&&"value"in e?e.value??void 0:e}normalizeInlineIri(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&typeof e["@id"]=="string")return e["@id"];if(typeof e=="object"&&typeof e.id=="string"&&e.id.includes("http"))return e.id;if(typeof e=="object"&&typeof e.value=="string")return e.value}}applyDeferredOrderBy(e){if(this.orderByClauses.length===0||e.length<2)return e;const t=[...e];return t.sort((i,s)=>{for(const o of this.orderByClauses){const l=this.getOrderByValue(i,o.column),u=this.getOrderByValue(s,o.column),h=this.compareOrderByValues(l,u);if(h!==0)return o.direction==="desc"?-h:h}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,i=[];for(const s of e){const o=this.serializeValueForKey(s);t.has(o)||(t.add(o),i.push(s))}return i}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,i=t>0?e.slice(t):e;return this.limitCount===void 0?i:i.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const i=Object.keys(e).find(s=>s.endsWith(`.${t}`));if(i)return e[i]}compareOrderByValues(e,t){return e===t?0:e==null?1:t==null?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}mergeRowsBySubject(e){const t=new Map,i=[];return e.forEach(o=>{const l=this.normalizeInlineIri(o["@id"])??this.normalizeInlineIri(o.subject)??this.normalizeInlineIri(o.uri)??(typeof o.id=="string"?o.id:void 0);if(typeof process<"u"&&define_process_env_default$2?.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",l),!l){i.push(`__anon_${i.length}`),t.set(i[i.length-1],{...o});return}if(!t.has(l)){const d={...o};Object.entries(d).forEach(([p,g])=>{if(g===void 0)return;const m=this.getColumnDefinitionForRowKey(p);(m?.options?.isArray||m?.dataType==="array")&&!Array.isArray(g)&&(d[p]=[g])}),t.set(l,d),i.push(l);return}const u=t.get(l),h=d=>{if(d instanceof Date)return`date:${d.toISOString()}`;if(typeof d=="string")return`str:${d}`;if(typeof d=="number")return`num:${d}`;if(typeof d=="boolean")return`bool:${d}`;if(d==null)return"nil";try{return`obj:${JSON.stringify(d)}`}catch{return`obj:${String(d)}`}};Object.entries(o).forEach(([d,p])=>{if(p===void 0)return;const g=u[d];if(g===void 0){u[d]=p;return}const m=Array.isArray(g)?g:[g],v=Array.isArray(p)?p:[p],S=[...m];v.forEach(A=>{const C=h(A);S.some(T=>h(T)===C)||S.push(A)});const E=this.getColumnDefinitionForRowKey(d),x=E?.options?.isArray||E?.dataType==="array";!x&&S.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${d}' on subject '${l}'. Using first value.`),u[d]=S[0]):x?u[d]=S:u[d]=S.length===1?S[0]:S})}),i.map(o=>t.get(o))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,i]=e.split(".",2);if(!(!t||!i))return t===this.primaryAlias?this.selectedTable?.columns[i]:this.aliasToTable.get(t)?.columns?.[i]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const i=e.indexOf("#");if(i>0)return e.slice(0,i);const s=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return s?s.startsWith("http")?s:`${this.session.getDialect().getPodUrl()}${s.replace(/^\//,"")}`:this.session.getDialect().getPodUrl()}isInlineObjectColumn(e){return e?e.dataType==="object"?!0:e.dataType==="array"?(e.elementType??e.options?.baseType)==="object":!1:!1}async applyJoinFallback(e){let t=e;for(const i of this.joins){const s=await this.fetchJoinRows(i,t);t=this.mergeRowsWithJoin(t,i,s)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const S=await this.session.select().from(e.table);return this.normalizeJoinRows(e,S)}const i=e.resolvedConditions??[];if(i.length===0)return[];const[s]=i,o=s.left.alias===e.alias?s.left:s.right,l=o===s.left?s.right:s.left,u=new Map;for(const S of t){const E=this.getRowValueForColumn(S,l);if(E==null)continue;const x=this.serializeValueForKey(E);u.has(x)||u.set(x,E)}if(u.size===0)return[];const h=Array.from(u.values()),d=()=>this.session.select().from(e.table),p=e.table.getColumn(o.column),g=this.buildExactJoinLookupConditions(e,t);if(g&&g.length>0){const S=[];for(const E of g){const x=d(),C=await(conditionTargetsReservedIdentifier(E)?x.applyInternalQueryCondition(E):x.where(E));S.push(...C)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,S))}const m=this.buildJoinLookupCondition(p,h);if(m){const S=d(),x=await(conditionTargetsReservedIdentifier(m)?S.applyInternalQueryCondition(m):S.where(m));return this.normalizeJoinRows(e,x)}const v=await d();return this.normalizeJoinRows(e,v)}buildExactJoinLookupConditions(e,t){const i=e.resolvedConditions??[];if(i.length===0)return;const[s]=i,o=s.left.alias===e.alias?s.left:s.right,l=o===s.left?s.right:s.left,u=this.getRequiredSubjectTemplateVariables(e.table),h=o.column==="id"&&u.length>0;if(!h&&i.length===1)return;const d=new Map;for(const m of i){const v=m.left.alias===e.alias?m.left:m.right;d.set(v.column,m)}const p=[],g=new Set;for(const m of t){const v=this.getRowValueForColumn(m,l);if(v==null)continue;const S=typeof v=="string"&&this.isAbsoluteIri(v),E=[],x=[];let A=!1;for(const T of i){const F=T.left.alias===e.alias?T.left:T.right,P=F===T.left?T.right:T.left,q=this.getRowValueForColumn(m,P);if(q==null){if(h&&!S&&u.includes(F.column))throw new Error(this.buildMissingJoinLocatorError(e,u.filter(G=>{const fe=d.get(G);if(!fe)return!0;const ee=(fe.left.alias===e.alias?fe.left:fe.right)===fe.left?fe.right:fe.left,Se=this.getRowValueForColumn(m,ee);return Se==null})));A=!0;break}const O=e.table.getColumn(F.column);if(!O){A=!0;break}E.push(eq(O,q)),x.push(`${F.column}:${this.serializeValueForKey(q)}`)}if(A)continue;if(h&&!S){const T=u.filter(F=>{const P=d.get(F);if(!P)return!0;const O=(P.left.alias===e.alias?P.left:P.right)===P.left?P.right:P.left,G=this.getRowValueForColumn(m,O);return G==null});if(T.length>0)throw new Error(this.buildMissingJoinLocatorError(e,T))}if(E.length===0)continue;const C=x.join("|");g.has(C)||(g.add(C),p.push(E.length===1?E[0]:and(...E)))}return p.length>0?p:void 0}buildJoinLookupCondition(e,t){if(!(!e||t.length===0))return t.length===1?eq(e,t[0]):inArray(e,t)}getRequiredSubjectTemplateVariables(e){const t=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"";return Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>i[1].split("|")[0]?.trim()||i[1]).filter(Boolean))).filter(i=>i!=="id"&&i!=="index"&&i!=="yyyy"&&i!=="MM"&&i!=="dd"&&i!=="HH"&&i!=="mm"&&i!=="ss"&&i!=="timestamp"&&i!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const i=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",s=Array.from(new Set(t)),o=s[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${i}" because locator variable(s) [${s.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${o}, join.${o})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(i=>{const s={};for(const[l,u]of Object.entries(i))s[`${e.alias}.${l}`]=u;const o=this.extractSubjectValue(i);if(o){s.subject=o,s["@id"]=o,s.uri=o,s[`${e.alias}.subject`]=o,s[`${e.alias}.@id`]=o,s[`${e.alias}.uri`]=o;const l=this.extractIdFromSubject(o,e.table);l!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||s[`${e.alias}.id`]===void 0)&&(s[`${e.alias}.id`]=l)}return s})}mergeRowsWithJoin(e,t,i){if(t.type==="crossJoin"){if(e.length===0||i.length===0)return[];const p=[];for(const g of e)for(const m of i)p.push({...g,...m});return p}const s=t.resolvedConditions??[];if(s.length===0)return e;const[o]=s,l=o.left.alias===t.alias?o.left:o.right,u=l===o.left?o.right:o.left,h=new Map;for(const p of i){const g=this.getRowValueForColumn(p,l);if(g==null)continue;const m=this.serializeValueForKey(g);h.has(m)||h.set(m,[]),h.get(m).push(p)}const d=[];for(const p of e){const g=this.getRowValueForColumn(p,u),m=this.serializeValueForKey(g),S=(g!=null?h.get(m)??[]:[]).filter(E=>this.joinRowMatchesAllConditions(p,E,t.alias,s));if(S.length===0){if(t.type==="innerJoin")continue;d.push({...p,...this.createEmptyJoinRow(t)});continue}for(const E of S)d.push({...p,...E})}return d}joinRowMatchesAllConditions(e,t,i,s){return s.every(o=>{const l=o.left.alias===i?o.left:o.right,u=l===o.left?o.right:o.left,h=this.getRowValueForColumn(e,u),d=this.getRowValueForColumn(t,l);return h==null||d===void 0||d===null?!1:this.serializeValueForKey(h)===this.serializeValueForKey(d)})}createEmptyJoinRow(e){const t={};for(const i of Object.keys(e.table.columns))t[`${e.alias}.${i}`]=void 0;return t[`${e.alias}.subject`]=void 0,t[`${e.alias}.id`]=void 0,t}applyJoinFilters(e){return this.joinFilters.length===0?e:e.filter(t=>this.joinFilters.every(i=>this.evaluateCondition(t,i)))}applyHavingFilter(e){return this.havingCondition?e.filter(t=>this.evaluateCondition(t,this.havingCondition)):e}evaluateCondition(e,t){switch(t.type){case"binary_expr":return this.evaluateBinaryCondition(e,t);case"unary_expr":return this.evaluateUnaryCondition(e,t);case"logical_expr":return this.evaluateLogicalCondition(e,t);default:return!0}}evaluateBinaryCondition(e,t){const i=t.left,s=t.right,o=t.operator;if(!i)return!0;const l=this.resolveConditionOperandValue(e,i,this.primaryAlias),u=this.resolveConditionOperandValue(e,s);switch(o.toUpperCase()){case"=":return l===u;case"!=":case"<>":return l!==u;case">":return Number(l)>Number(u);case">=":return Number(l)>=Number(u);case"<":return Number(l)<Number(u);case"<=":return Number(l)<=Number(u);case"IN":return Array.isArray(u)&&u.includes(l);case"NOT IN":return Array.isArray(u)&&!u.includes(l);case"LIKE":return typeof l=="string"&&typeof u=="string"&&this.computeLikeMatch(l,u);default:return!0}}evaluateUnaryCondition(e,t){const i=t.operator,s=t.value;if(i.toUpperCase()==="NOT")return!this.evaluateCondition(e,s);if(!s)return!0;const o=this.resolveConditionOperandValue(e,s,this.primaryAlias);switch(i.toUpperCase()){case"IS NULL":return o==null;case"IS NOT NULL":return o!=null;default:return!0}}evaluateLogicalCondition(e,t){const i=t.operator,s=t.expressions??[];return i.toUpperCase()==="AND"?s.every(o=>this.evaluateCondition(e,o)):i.toUpperCase()==="OR"?s.some(o=>this.evaluateCondition(e,o)):!0}resolveConditionOperandValue(e,t,i){if(t instanceof SelectionAliasExpression)return e[t.alias];const s=this.getConditionColumnReference(t,i);return s?this.getRowValueForColumn(e,s):t}getColumnKeyCandidates(e){const t=[],i=this.primaryAlias;return e.alias===i&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const i=this.getColumnKeyCandidates(t);for(const s of i)if(s in e)return e[s]}shouldUseSubjectIdentityColumn(e,t){const i=e?.columns?.[t];return!!(i?._virtualId||i?.options?.predicate==="@id")}serializeValueForKey(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}extractIdFromSubject(e,t){if(!e)return;if(t){const o=parsePodResourceRef(t,e);if(o)return o.templateValues.id??o.resourceId}if(t){const o=this.session.getDialect?.(),u=(o?.getUriResolver?.()??new UriResolverImpl(o?.getPodUrl?.()??"")).parseSubject(e,t);if(u&&u.id)return u.id}const i=e.indexOf("#");if(i!==-1)return e.slice(i);const s=e.lastIndexOf("/");if(s!==-1){const o=e.slice(s+1);if(o.length>0)return o}}computeLikeMatch(e,t){const i=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/%/g,".*").replace(/_/g,".")}$`,"i").test(e)}async selectIdsByCondition(e,t){return(await this.session.select({id:e.getColumn("id")??e.columns.id}).from(e).where(t).columns({"@id":e.columns.id})).map(o=>o.id||o["@id"]).filter(o=>typeof o=="string"&&o.length>0)}then(e,t){return this.execute().then(e,t)}}_a$7=entityKind;SelectQueryBuilder[_a$7]="SelectQueryBuilder";var _a$6;class InsertQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.getRowsWithDefaults();return{table:this.table,rows:i}}}values(e){return e instanceof SQL?this.sql=e:this.insertValues=e,this}returning(e){return this.returningFields=e??!0,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertInsert(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL insert in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.insertValues){const e=this.getRowsWithDefaults(),t=this.returningFields?this.getSubjectUris(e):[],i={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},s=await this.session.execute(i),o=this.returningFields?await this.fetchReturningRowsBySubjects(t):s;return await this.runAfterInsertHooks(o),o}else throw new Error("No values specified for INSERT query")}then(e,t){return this.execute().then(e,t)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e);return projectReturningRows(orderRowsBySubjects(t,e),this.returningFields)}getSubjectUris(e){const t=this.session.getDialect().getUriResolver?.();if(!t)throw new Error("returning() requires dialect URI resolver support");return e.map(i=>generateSubjectUri(i,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const i=this.buildHookContext();if(!i){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterInsert(i,s)}catch(o){console.error("[InsertQueryBuilder] afterInsert hook failed:",o)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}getRowsWithDefaults(){const e=this.insertValues;if(!e)throw new Error("No values specified for INSERT query");return(Array.isArray(e)?e:[e]).map(i=>this.applyDefaultValues(i))}applyDefaultValues(e){const t={...e},i=this.table?.columns??{},s=Object.entries(i);for(const[o,l]of s.filter(([,u])=>!this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,o,l);for(const[o,l]of s.filter(([,u])=>this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,o,l);return t}applyDefaultValue(e,t,i){if(e[t]===void 0){const s=i.options?.defaultValue;s!==void 0&&(e[t]=this.resolveDefaultValue(s,i,e))}}resolveDefaultValue(e,t,i){const s=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&s)return renderDefaultIdTemplate(e,{key:s,row:i,resource:this.table});if(typeof e!="function")return e;const o=e;return o.length===0?o():o(s,i)}isPrimaryKeyColumn(e){return e.options?.primaryKey===!0||e.options?.predicate==="@id"}}_a$6=entityKind;InsertQueryBuilder[_a$6]="InsertQueryBuilder";var _a$5;class UpdateQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{if(!this.updateData)throw new Error("No data specified for UPDATE query");const i=this.normalizeWhereConditionsForUpdate();if(!i)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:i}}}set(e){return e instanceof SQL?this.sql=e:this.updateData=e,this}returning(e){return this.returningFields=e??!0,this}where(e){if(e instanceof SQL)this.sql||(this.sql=e);else if(this.isQueryCondition(e)){assertPublicWhereCondition("update",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("update",e),this.whereConditions=e,this.conditionTree=void 0;return this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),o=inferSPARQLQueryType(s);if(!o)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:o,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertUpdate(i.data,i.where,i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL update in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.updateData){const e=this.toIR(),i=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"update",table:this.table,data:e.data,where:e.where,plan:e},o=await this.session.execute(s),l=this.returningFields?await this.fetchReturningRowsBySubjects(i):o;return await this.runAfterUpdateHooks(l),l}else throw new Error("No data specified for UPDATE query")}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];return!this.conditionTree&&typeof t=="string"?await this.session.select().from(this.table).whereByIri(t):await this.session.select().from(this.table).where(e)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e),i=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),s=Object.entries(this.updateData??{}).filter(([,o])=>Array.isArray(o));return s.length===0?i:i.map(o=>{const l={...o};for(const[u,h]of s)u in l&&(l[u]=[...h]);return l})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const i=this.buildHookContext();if(!i){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const s=this.updateData??{};for(const o of e)try{await t.afterUpdate(i,o,s)}catch(l){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",l)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$5=entityKind;UpdateQueryBuilder[_a$5]="UpdateQueryBuilder";var _a$4;class DeleteQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.normalizeWhereConditionsForDelete();return{table:this.table,where:i}}}where(e){if(e instanceof SQL)this.sql=e;else if(this.isQueryCondition(e)){assertPublicWhereCondition("delete",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("delete",e),this.whereConditions=e,this.conditionTree=void 0;return this}returning(e){return this.returningFields=e??!0,this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),o=inferSPARQLQueryType(s);if(!o)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:o,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertDelete(i.where??{},i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL delete in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else{const e=this.toIR(),t=this.returningFields?await this.fetchMatchedRows(e.where):[],i=t.map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"delete",table:this.table,where:e.where,plan:e},o=await this.session.execute(s),l=this.returningFields?projectReturningRows(orderRowsBySubjects(t,i),this.returningFields):o;return await this.runAfterDeleteHooks(l),l}}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];if(!this.conditionTree&&typeof t=="string")return await this.session.select().from(this.table).whereByIri(t);let i=this.session.select().from(this.table);return e&&(i=i.where(e)),await i}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const i=this.buildHookContext();if(!i){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterDelete(i,s)}catch(o){console.error("[DeleteQueryBuilder] afterDelete hook failed:",o)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$4=entityKind;DeleteQueryBuilder[_a$4]="DeleteQueryBuilder";var _a$3;class PodAsyncSession{constructor(e,t,i={}){this.dialect=e,this._schema=t,this.options=i}getSchema(){return this._schema}isConnected(){return this.dialect.isConnected()}getDialect(){return this.dialect}getOptions(){return this.options}async ensureInitialized(e){const t=typeof this.dialect.getResourcePreparationMode=="function"?this.dialect.getResourcePreparationMode():"best-effort";if(t==="off"){e&&typeof e.markInitialized=="function"&&e.markInitialized(!0);return}if(e&&typeof e.isInitialized=="function"){if(!e.isInitialized())try{typeof e.init=="function"?await e.init(this.dialect):await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i}}async execute(e){if(this.options.logger&&console.log("Executing operation:",e),!e||!e.type)throw new Error("Invalid operation: missing type");if(!e.table)throw new Error("Invalid operation: missing table");if(!["select","insert","update","delete"].includes(e.type))throw new Error(`Unsupported operation type: ${e.type}`);if(await this.ensureInitialized(e.table),Array.isArray(e.joins))for(const s of e.joins)s?.table&&await this.ensureInitialized(s.table);const i=await this.dialect.query(e);return this.updateSubjectIndex(e,i),i}updateSubjectIndex(e,t){if(e.type==="select")return;const i=this.dialect;if(typeof i.registerResourceSubject!="function"&&typeof i.unregisterResourceSubject!="function")return;const s=this.resolveOperationSubjects(e,t);if(e.type==="delete"){s.forEach(o=>i.unregisterResourceSubject?.(e.table,o));return}s.forEach(o=>i.registerResourceSubject?.(e.table,o))}resolveOperationSubjects(e,t){const i=new Set;for(const s of t){const o=this.getKnownRowIri(s);o&&i.add(o)}if(e.type==="insert"){const s=e.plan;(Array.isArray(s?.rows)?s.rows:[]).forEach(l=>{try{i.add(generateSubjectUri(l,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(i)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const i of["@id","subject","uri","source"]){const s=t[i];if(typeof s=="string"&&/^https?:\/\//.test(s))return s}return null}async executeSql(e,t){return this.options.logger&&console.log("Executing SQL AST:",e),await this.ensureInitialized(t),await this.dialect.executeSql(e,t)}select(e){return new SelectQueryBuilder(this,e)}insert(e){return new InsertQueryBuilder(this,e)}update(e){return new UpdateQueryBuilder(this,e)}delete(e){return new DeleteQueryBuilder(this,e)}async transaction(e){return await e(this)}}_a$3=entityKind;PodAsyncSession[_a$3]="PodAsyncSession";const resolveCreateRequire$1=()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(!nodeRequire)return null;const moduleLib=nodeRequire("module");return!moduleLib||typeof moduleLib.createRequire!="function"?null:moduleLib.createRequire}catch{return null}},createRequireFn=resolveCreateRequire$1(),isAbsoluteModuleFilename=n=>n.startsWith("file:")||n.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(n),moduleFilename=typeof __filename=="string"&&isAbsoluteModuleFilename(__filename)?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json",createDefaultRequireModule=()=>{if(!createRequireFn)return null;try{return createRequireFn(moduleFilename)}catch{return null}},defaultRequireModule=createDefaultRequireModule(),patchActionObserverHttp=(n,e)=>{if(!n)return!1;try{const t=n(e);if(t&&t.ActionObserverHttp){if(t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied)return!0;const i=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(s,o,l){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),i.call(this,s,o,l)},t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied=!0,!0}return!1}catch{return!1}},applyComunicaPatches=(n=defaultRequireModule)=>n?["@comunica/actor-query-result-serialize-sparql-json","@comunica/actor-query-result-serialize-stats","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-sparql-json","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-stats"].map(t=>patchActionObserverHttp(n,t)).some(Boolean):!1;applyComunicaPatches();let configuredQueryEngineFactory=null;const resolveCreateRequire=async()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(nodeRequire){const n=nodeRequire("module");if(n&&typeof n.createRequire=="function")return n.createRequire}}catch{}try{const n=await __vitePreload(()=>import("node:module"),[]);if(typeof n.createRequire=="function")return n.createRequire}catch{}return null},buildMissingComunicaError=n=>{const e=n instanceof Error&&n.message?` Original error: ${n.message}`:"";return new Error("A SPARQL query engine is required for this operation. Install `@comunica/query-sparql-solid` in the consuming app, or provide `sparql.createQueryEngine` to `drizzle(...)`, or call `configureSparqlEngine(...)` before executing LDP/SPARQL-client queries."+e)},loadComunicaModuleWithRequire=async n=>{const e=await resolveCreateRequire();if(!e)throw new Error("Node module resolution is not available in this runtime.");const t=e(n);applyComunicaPatches(t);const i=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!i||typeof i.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return i},loadDefaultComunicaModule=async()=>{try{return await loadComunicaModuleWithRequire(typeof __filename=="string"?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json")}catch(n){try{applyComunicaPatches();const e=await __vitePreload(()=>import("./index-browser-BGpvHwD0.js").then(t=>t.i),[]);if(applyComunicaPatches(),e&&typeof e.QueryEngine=="function")return e}catch(e){throw buildMissingComunicaError(e??n)}throw buildMissingComunicaError(n)}},createDefaultQueryEngine=async()=>{const n=await loadDefaultComunicaModule();return new n.QueryEngine},configureSparqlEngine=n=>{configuredQueryEngineFactory=n?.createQueryEngine??null},getConfiguredSparqlEngineFactory=n=>n??configuredQueryEngineFactory??createDefaultQueryEngine;class ComunicaSPARQLExecutor{constructor(e){this.engine=null,this.sources=[...e.sources],this.fetchFn=this.createSafeFetch(e.fetch||fetch),this.logging=e.logging||!1,this.createQueryEngine=getConfiguredSparqlEngineFactory(e.createQueryEngine)}formatError(e){return e instanceof Error?e.message:String(e)}createSourceRef(e,t="auto"){return t==="sparql"?{type:"sparql",value:e}:e}createSafeFetch(e){return async(t,i)=>{try{const s=await e(t,i),o=new Map;s.headers&&s.headers.forEach((h,d)=>{o.set(d.toLowerCase(),h||"")});const u={...s,headers:{get:h=>{const d=h.toLowerCase();return o.get(d)||null},has:h=>{const d=h.toLowerCase();return o.has(d)},forEach:h=>{o.forEach((d,p)=>h(d,p))},entries:()=>o.entries(),keys:()=>o.keys(),values:()=>o.values(),[Symbol.iterator]:()=>o.entries(),includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(o.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1}},status:s.status||200,statusText:s.statusText||"OK",ok:s.ok!==void 0?s.ok:!0,url:s.url||(typeof t=="string"?t:t.toString()),type:s.type||"basic",redirected:s.redirected||!1,body:s.body,bodyUsed:s.bodyUsed||!1,includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(o.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1},text:async()=>{try{return await s.text()}catch(h){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(h)),""}},json:async()=>{try{return await s.json()}catch(h){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(h)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,i)}catch(h){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(h)),u}}};return u}catch(s){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(s)),s}}}async initEngine(){return this.engine||(this.engine=await this.createQueryEngine()),this.engine}async executeQuery(e){try{const t=await this.initEngine();if(this.logging&&console.log(`[Comunica] Executing ${e.type} query:`,e.query),e.type==="SELECT")return await this.executeSelectInternal(e,t);if(e.type==="ASK")return await this.executeAskInternal(e,t);if(["INSERT","UPDATE","DELETE"].includes(e.type))return await this.executeUpdate(e,t);throw new Error(`Unsupported query type: ${e.type}`)}catch(t){throw console.error("SPARQL query execution failed:",this.formatError(t)),t}}async executeSelect(e){try{this.logging&&console.log("[SPARQL] Executing SELECT query with full processing");const t={type:"SELECT",query:e.trim()},i=this.sources[0];if(!i)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",i)),await this.executeQueryWithSource(t,i)}catch(t){throw this.logging&&console.error("[Simple] SELECT query execution failed:",this.formatError(t)),t}}async queryBindings(e,t){return await(await(await this.initEngine()).queryBindings(e,{sources:[t],fetch:this.fetchFn})).toArray()}async executeSelectInternal(e,t){try{if(this.sources.length===0)throw new Error("No sources configured for SPARQL query");return(await(await t.queryBindings(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})).toArray()).map(o=>{const l=o,u={},h=(d,p)=>{const g=this.extractBindingKeyName(d);g&&(u[g]=this.convertComunicaTerm(p))};if(l&&typeof l.forEach=="function")l.forEach((d,p)=>h(p,d));else if(l&&typeof l.entries=="function")for(const[d,p]of l.entries())h(d,p);else for(const d in l)Object.prototype.hasOwnProperty.call(l,d)&&h(d,l[d]);return u})}catch(i){throw console.error("SELECT query failed:",this.formatError(i)),i}}async executeAskInternal(e,t){try{if(this.logging&&console.log("[Comunica] Executing ASK query:",e.query),this.sources.length===0)throw new Error("No sources configured for SPARQL query");return[{result:await t.queryBoolean(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})}]}catch(i){throw console.error("ASK query failed:",this.formatError(i)),i}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const i=[];for(const s of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${s}:`,e.query.substring(0,100)+"...");let o=null;try{const d=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});d.ok&&(o=d.headers.get("ETag"),this.logging&&o&&console.log(`[UPDATE] Got ETag for ${s}: ${o}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${s}, continuing without ETag`)}const l={"Content-Type":"application/sparql-update","If-Match":o??"*"},u=async d=>this.fetchFn(s,{method:"PATCH",headers:d,body:e.query}),h=await u(l);if(h.ok)i.push({success:!0,source:s,status:h.status}),await this.invalidateCache(t,s);else if(h.status===409||h.status===412){this.logging&&console.log(`[UPDATE] ${h.status} conflict for ${s}, trying multiple retry strategies`);let d=!1;if(h.status===412)try{const p=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});if(p.ok){const g=p.headers.get("ETag");if(g){const m={...l,"If-Match":g},v=await u(m);v.ok&&(i.push({success:!0,source:s,status:v.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,s),d=!0)}}}catch(p){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",p)}if(!d)try{const p=await u({"Content-Type":"application/sparql-update"});p.ok&&(i.push({success:!0,source:s,status:p.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,s),d=!0)}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",p)}if(!d)try{if((await this.fetchFn(s,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const g=await this.fetchFn(s,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});g.ok&&(i.push({success:!0,source:s,status:g.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,s),d=!0)}}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",p)}if(!d){const p=await h.text();i.push({success:!1,source:s,error:`All retry strategies failed: ${h.status} ${h.statusText}`,details:p})}}else{const d=await h.text();i.push({success:!1,source:s,error:`${h.status} ${h.statusText}`,details:d})}}catch(o){i.push({success:!1,source:s,error:this.formatError(o)})}return i}catch(i){throw console.error("UPDATE query failed:",this.formatError(i)),i}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const i=e.invalidateHttpCache;if(typeof i=="function")try{await i.call(e,t)}catch(s){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(s))}}extractBindingKeyName(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="object"){const t=e;if(t&&typeof t.value=="string"||t&&t.termType==="Variable"&&typeof t.value=="string")return t.value}return typeof e=="symbol"?e.description??e.toString():String(e)}convertComunicaTerm(e){if(!e)return null;const t=e;switch(t.termType){case"NamedNode":return t.value;case"Literal":if(t.datatype&&t.datatype.value){const i=t.datatype.value;if(typeof i=="string"){if(i.includes("#integer")||i.includes("#int"))return parseInt(String(t.value),10);if(i.includes("#decimal")||i.includes("#double"))return parseFloat(String(t.value));if(i.includes("#boolean"))return t.value==="true";if(i.includes("#dateTime"))return new Date(String(t.value));if(i.includes("#json"))try{return JSON.parse(String(t.value))}catch(s){return console.warn("Failed to parse JSON value:",t.value,this.formatError(s)),t.value}else if(i.includes("#jsonArray")||i.includes("solid/terms#jsonArray"))try{const s=JSON.parse(String(t.value));return Array.isArray(s)?s:(console.warn("Expected array but got:",typeof s,s),[s])}catch(s){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(s)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const i=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let s;return t?s=t:s={type:"SELECT",query:`
49
49
  SELECT ?subject ?predicate ?object WHERE {
50
50
  ?subject ?predicate ?object .
51
51
  FILTER(STRSTARTS(STR(?subject), "${i}"))
@@ -225,7 +225,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
225
225
  SELECT ?resource WHERE {
226
226
  <${t}> ldp:contains ?resource .
227
227
  }
228
- `,prefixes:{ldp:"http://www.w3.org/ns/ldp#"}},o=await this.sparqlExecutor.queryContainer(t,s);for(const l of o){const u=l.resource;if(u){const h=hasStringValue(u)?u.value:String(u);i.push(h)}}}catch(s){console.warn("[listContainerResources] SPARQL query failed:",s)}return i}}_a=entityKind;PodDialect[_a]="PodDialect";function drizzle(n,e){if(!n||!n.info.isLoggedIn)throw new Error("需要有效的已认证Session");const t={session:n,preferredChannels:e?.notifications?.preferredChannels,createQueryEngine:e?.sparql?.createQueryEngine,disableInteropDiscovery:e?.disableInteropDiscovery,podUrl:e?.podUrl??n.info.podUrl,resourcePreparation:e?.resourcePreparation,storageTTL:e?.storageTTL,debug:e?.debug??e?.logger},i=new PodDialect(t);e?.schema&&i.setSchema(e.schema);const s=new PodAsyncSession(i);return new PodDatabase(i,s,e?.schema)}function createRepositoryDescriptor(n){const{namespace:e,table:t,searchableFields:i,defaultSort:s,cache:o}=n,l=n.searchAccessor??(A=>{const C=A?A.search:void 0;return typeof C=="string"?C:void 0}),u=n.transform??(A=>A),h={create:n.invalidations?.create??["list"],update:n.invalidations?.update??["list","detail"],remove:n.invalidations?.remove??["list","detail"]},d=A=>{const C=t[A];if(C)return C;const T=t.config?.name;return T?`${T}.${A}`:A},p=A=>{const C=[],T=l(A)?.trim();if(T&&i?.length){const P=`%${T}%`,q=i.map(O=>like(d(O),P));q.length===1?C.push(q[0]):q.length>1&&C.push(or(...q))}const F=n.filter?.({table:t,filters:A});if(F&&C.push(F),C.length!==0)return C.length===1?C[0]:and(...C)},g=async(A,C)=>{let T=A.select().from(t);const F=p(C);return F&&(T=T.where(F)),s&&(T=T.orderBy(d(s.field),s.direction)),(await T.execute()).map(q=>u(q))},m=async(A,C)=>{const T=await A.findByIri(t,C);return T?u(T):null},v=n.disableMutations?.create?void 0:async(A,C)=>{const T=C.id,F=typeof T=="string"&&T.length>0?T:crypto.randomUUID(),P={...C,id:F},q=await A.insert(t).values(P).execute(),O=Array.isArray(q)?q?.[0]:q;if(O&&typeof O=="object"&&!("success"in O))return u(O);const G=O&&typeof O=="object"&&"source"in O?O.source:null,fe=G?A.resolveRowIri(t,{...P,source:G}):A.resolveRowIri(t,P);return{...P,id:A.resolveRowId(t,{...P,"@id":fe}),"@id":fe,subject:fe,uri:fe,source:G??fe}},S=n.disableMutations?.update?void 0:async(A,C,T)=>{const F=await A.updateByIri(t,C,T);if(F)return u(F);const P=await m(A,C);if(!P)throw new Error(`Failed to load ${e} record after update`);return P},E=n.disableMutations?.remove?void 0:async(A,C)=>(await A.deleteByIri(t,C),{id:C}),x=typeof t.getResourcePath=="function"?t.getResourcePath():t.config?.base??"";return{namespace:e,resourcePath:x,searchableFields:i,defaultSort:s,cache:o,invalidations:h,list:g,detail:m,create:v,update:S,remove:E}}function createResourceRepositoryDescriptor(n){const{resource:e,filter:t,...i}=n;return createRepositoryDescriptor({...i,table:e,filter:t?({table:s,filters:o})=>t({resource:s,filters:o}):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$2={type:_NS$h("type")},_NAMESPACE$3="http://www.w3.org/2006/vcard/ns#";function _NS$3(n){return _NAMESPACE$3+n}var VCARD={PREFIX:"vcard",NAMESPACE:_NAMESPACE$3,PREFIX_AND_NAMESPACE:{vcard:"http://www.w3.org/2006/vcard/ns#"},NS:_NS$3,Acquaintance:_NS$3("Acquaintance"),RelatedType:_NS$3("RelatedType"),Agent:_NS$3("Agent"),BBS:_NS$3("BBS"),TelephoneType:_NS$3("TelephoneType"),Car:_NS$3("Car"),Cell:_NS$3("Cell"),Child:_NS$3("Child"),Colleague:_NS$3("Colleague"),Contact:_NS$3("Contact"),Coresident:_NS$3("Coresident"),Coworker:_NS$3("Coworker"),Crush:_NS$3("Crush"),Date:_NS$3("Date"),Dom:_NS$3("Dom"),Type:_NS$3("Type"),Emergency:_NS$3("Emergency"),Fax:_NS$3("Fax"),Female:_NS$3("Female"),Gender:_NS$3("Gender"),Friend:_NS$3("Friend"),Home:_NS$3("Home"),ISDN:_NS$3("ISDN"),Internet:_NS$3("Internet"),Intl:_NS$3("Intl"),Kin:_NS$3("Kin"),Label:_NS$3("Label"),Male:_NS$3("Male"),Me:_NS$3("Me"),Met:_NS$3("Met"),Modem:_NS$3("Modem"),Msg:_NS$3("Msg"),Muse:_NS$3("Muse"),Neighbor:_NS$3("Neighbor"),None:_NS$3("None"),Other:_NS$3("Other"),PCS:_NS$3("PCS"),Pager:_NS$3("Pager"),Parcel:_NS$3("Parcel"),Parent:_NS$3("Parent"),Postal:_NS$3("Postal"),Pref:_NS$3("Pref"),Sibling:_NS$3("Sibling"),Spouse:_NS$3("Spouse"),Sweetheart:_NS$3("Sweetheart"),Tel:_NS$3("Tel"),Text:_NS$3("Text"),TextPhone:_NS$3("TextPhone"),Unknown:_NS$3("Unknown"),Video:_NS$3("Video"),Voice:_NS$3("Voice"),Work:_NS$3("Work"),X400:_NS$3("X400"),Address:_NS$3("Address"),Email:_NS$3("Email"),Group:_NS$3("Group"),Kind:_NS$3("Kind"),Individual:_NS$3("Individual"),Location:_NS$3("Location"),Organization:_NS$3("Organization"),VCard:_NS$3("VCard"),Name:_NS$3("Name"),adr:_NS$3("adr"),hasAddress:_NS$3("hasAddress"),agent:_NS$3("agent"),anniversary:_NS$3("anniversary"),bday:_NS$3("bday"),category:_NS$3("category"),class:_NS$3("class"),email:_NS$3("email"),hasEmail:_NS$3("hasEmail"),extended_address:_NS$3("extended-address"),geo:_NS$3("geo"),hasGeo:_NS$3("hasGeo"),hasAdditionalName:_NS$3("hasAdditionalName"),hasCalendarBusy:_NS$3("hasCalendarBusy"),hasCalendarLink:_NS$3("hasCalendarLink"),hasCalendarRequest:_NS$3("hasCalendarRequest"),hasCategory:_NS$3("hasCategory"),hasCountryName:_NS$3("hasCountryName"),hasFN:_NS$3("hasFN"),hasFamilyName:_NS$3("hasFamilyName"),hasGender:_NS$3("hasGender"),hasGivenName:_NS$3("hasGivenName"),hasHonorificPrefix:_NS$3("hasHonorificPrefix"),hasHonorificSuffix:_NS$3("hasHonorificSuffix"),hasInstantMessage:_NS$3("hasInstantMessage"),hasLanguage:_NS$3("hasLanguage"),hasLocality:_NS$3("hasLocality"),hasNickname:_NS$3("hasNickname"),nickname:_NS$3("nickname"),hasNote:_NS$3("hasNote"),hasOrganizationName:_NS$3("hasOrganizationName"),hasOrganizationUnit:_NS$3("hasOrganizationUnit"),hasPostalCode:_NS$3("hasPostalCode"),hasRegion:_NS$3("hasRegion"),hasRelated:_NS$3("hasRelated"),hasRole:_NS$3("hasRole"),hasSource:_NS$3("hasSource"),hasStreetAddress:_NS$3("hasStreetAddress"),hasTitle:_NS$3("hasTitle"),hasUID:_NS$3("hasUID"),hasValue:_NS$3("hasValue"),label:_NS$3("label"),language:_NS$3("language"),latitude:_NS$3("latitude"),longitude:_NS$3("longitude"),mailer:_NS$3("mailer"),note:_NS$3("note"),org:_NS$3("org"),organization_name:_NS$3("organization-name"),organization_unit:_NS$3("organization-unit"),post_office_box:_NS$3("post-office-box"),prodid:_NS$3("prodid"),rev:_NS$3("rev"),role:_NS$3("role"),sort_string:_NS$3("sort-string"),title:_NS$3("title"),tz:_NS$3("tz"),value:_NS$3("value"),country_name:_NS$3("country-name"),locality:_NS$3("locality"),postal_code:_NS$3("postal-code"),region:_NS$3("region"),street_address:_NS$3("street-address"),fn:_NS$3("fn"),hasMember:_NS$3("hasMember"),additional_name:_NS$3("additional-name"),family_name:_NS$3("family-name"),given_name:_NS$3("given-name"),honorific_prefix:_NS$3("honorific-prefix"),honorific_suffix:_NS$3("honorific-suffix"),hasKey:_NS$3("hasKey"),key:_NS$3("key"),hasLogo:_NS$3("hasLogo"),logo:_NS$3("logo"),hasName:_NS$3("hasName"),n:_NS$3("n"),hasPhoto:_NS$3("hasPhoto"),photo:_NS$3("photo"),hasSound:_NS$3("hasSound"),sound:_NS$3("sound"),hasTelephone:_NS$3("hasTelephone"),tel:_NS$3("tel"),hasURL:_NS$3("hasURL"),url:_NS$3("url")};const ABSOLUTE_IRI$1=/^[a-zA-Z][a-zA-Z\d+.-]*:/,createNamespace=(n,e,t)=>{const i=(s=>ABSOLUTE_IRI$1.test(s)?s:`${e}${s}`);return i.prefix=n,i.uri=e,i.NAMESPACE=e,i.term=s=>i(s),Object.entries(t).forEach(([s,o])=>{Object.defineProperty(i,s,{value:i(o),enumerable:!0})}),i},DCTerms=DCTERMS,RDF$1=RDF$2,ODRL=createNamespace("odrl","http://www.w3.org/ns/odrl/2/",{Policy:"Policy",target:"target",action:"action"});createNamespace("rdfs","http://www.w3.org/2000/01/rdf-schema#",{Class:"Class",label:"label",comment:"comment",subClassOf:"subClassOf",domain:"domain",range:"range"});createNamespace("owl","http://www.w3.org/2002/07/owl#",{Ontology:"Ontology",Class:"Class",ObjectProperty:"ObjectProperty",DatatypeProperty:"DatatypeProperty"});const SCHEMA=createNamespace("schema","http://schema.org/",{CreativeWork:"CreativeWork",MediaObject:"MediaObject",PropertyValue:"PropertyValue",about:"about",author:"author",dateCreated:"dateCreated",dateDeleted:"dateDeleted",description:"description",encodingFormat:"encodingFormat",fileSize:"fileSize",image:"image",name:"name",participant:"participant",reviewedBy:"reviewedBy",text:"text",url:"url"}),SIOC=createNamespace("sioc","http://rdfs.org/sioc/ns#",{Container:"Container",Post:"Post",Thread:"Thread",Forum:"Forum",content:"content",richContent:"richContent",hasReply:"has_reply",replyOf:"reply_of",hasCreator:"has_creator",createdAt:"created_at",hasContainer:"has_container",has_parent:"has_parent",numReplies:"num_replies",has_member:"has_member",about:"about"}),MEETING=createNamespace("mee","http://www.w3.org/ns/pim/meeting#",{LongChat:"LongChat",Message:"Message"}),WF=createNamespace("wf","http://www.w3.org/2005/01/wf/flow-1.0#",{message:"message",participation:"participation",participant:"participant"}),AS=createNamespace("as","https://www.w3.org/ns/activitystreams#",{Activity:"Activity",Announce:"Announce",Public:"Public",audience:"audience",actor:"actor",object:"object",target:"target"}),UDFS=createNamespace("udfs","https://undefineds.co/ns#",{ApprovalRequest:"ApprovalRequest",InputRequest:"InputRequest",CaptureCandidate:"CaptureCandidate",CaptureEvent:"CaptureEvent",AuditEntry:"AuditEntry",AutonomyGrant:"AutonomyGrant",Idea:"Idea",Issue:"Issue",Task:"Task",Schedule:"Schedule",AutomationRule:"AutomationRule",Delivery:"Delivery",Run:"Run",RunStep:"RunStep",Evidence:"Evidence",Report:"Report",Credential:"Credential",ApiKeyCredential:"ApiKeyCredential",OAuthCredential:"OAuthCredential",Provider:"Provider",Model:"Model",AIModel:"AIModel",ChatModel:"ChatModel",EmbeddingModel:"EmbeddingModel",DocumentUnderstandingModel:"DocumentUnderstandingModel",RerankingModel:"RerankingModel",ImageGenerationModel:"ImageGenerationModel",SpeechRecognitionModel:"SpeechRecognitionModel",SpeechSynthesisModel:"SpeechSynthesisModel",VideoGenerationModel:"VideoGenerationModel",ModelCapability:"ModelCapability",ChatCapability:"ChatCapability",EmbeddingCapability:"EmbeddingCapability",RerankingCapability:"RerankingCapability",ToolCallCapability:"ToolCallCapability",ReasoningCapability:"ReasoningCapability",WebCapability:"WebCapability",VisionCapability:"VisionCapability",OCRCapability:"OCRCapability",DocumentUnderstandingCapability:"DocumentUnderstandingCapability",StructuredOutputCapability:"StructuredOutputCapability",IndexingCapability:"IndexingCapability",ImageGenerationCapability:"ImageGenerationCapability",SpeechRecognitionCapability:"SpeechRecognitionCapability",SpeechSynthesisCapability:"SpeechSynthesisCapability",VideoGenerationCapability:"VideoGenerationCapability",AIConfig:"AIConfig",Note:"Note",VectorStore:"VectorStore",IndexedFile:"IndexedFile",AgentStatus:"AgentStatus",GatewayAccessKey:"GatewayAccessKey",QuotaSnapshot:"QuotaSnapshot",ChatProjectContext:"ChatProjectContext",ProjectMemory:"ProjectMemory",ConversationShare:"ConversationShare",Skill:"Skill",name:"name",favorite:"favorite",favoriteType:"favoriteType",favoriteTarget:"favoriteTarget",favoredAt:"favoredAt",conversation:"conversation",conversationType:"conversationType",conversationTitle:"conversationTitle",lastMessage:"lastMessage",lastActiveAt:"lastActiveAt",lastSyncedAt:"lastSyncedAt",sortKey:"sortKey",hasThread:"hasThread",inThread:"inThread",inScope:"inScope",participants:"participants",message:"message",messageContent:"messageContent",messageType:"messageType",messageStatus:"messageStatus",readBy:"readBy",Contact:"Contact",PersonContact:"PersonContact",AgentContact:"AgentContact",GroupContact:"GroupContact",hasContact:"hasContact",contactType:"contactType",externalPlatform:"externalPlatform",externalId:"externalId",alias:"alias",aiAssistant:"aiAssistant",aiModel:"aiModel",aiModels:"aiModels",aiProvider:"aiProvider",credential:"credential",systemPrompt:"systemPrompt",temperature:"temperature",maxTokens:"maxTokens",systemMessage:"systemMessage",provider:"provider",model:"model",displayName:"displayName",proxyUrl:"proxyUrl",hasModel:"hasModel",defaultModel:"defaultModel",modelType:"modelType",isProvidedBy:"isProvidedBy",inputModality:"inputModality",outputModality:"outputModality",capability:"capability",hasCapability:"hasCapability",contextLength:"contextLength",maxOutputTokens:"maxOutputTokens",pricingInput:"pricingInput",pricingOutput:"pricingOutput",apiKeyUrl:"apiKeyUrl",connectMode:"connectMode",homepage:"homepage",dimension:"dimension",supportsBackend:"supportsBackend",rotationPolicy:"rotationPolicy",metadata:"metadata",root:"root",webId:"webId",hasSkill:"hasSkill",skill:"skill",enabled:"enabled",memoryEnabled:"memoryEnabled",includeToolDetails:"includeToolDetails",excludedMessage:"excludedMessage",version:"version",checksum:"checksum",loadPolicy:"loadPolicy",credentialSource:"credentialSource",backend:"backend",runtime:"runtime",transport:"transport",endpoint:"endpoint",authorityPolicy:"authorityPolicy",toolPolicy:"toolPolicy",runtimeSnapshot:"runtimeSnapshot",tools:"tools",contextWindow:"contextWindow",contextRound:"contextRound",Agent:"Agent",agentCapability:"agentCapability",agentTool:"agentTool",agentConfig:"agentConfig",fileHash:"fileHash",syncStatus:"syncStatus",localPath:"localPath",isDefault:"isDefault",service:"service",label:"label",owner:"owner",secretHash:"secretHash",deployment:"deployment",balance:"balance",windows:"windows",observedAt:"observedAt",lastUsedAt:"lastUsedAt",failCount:"failCount",rateLimitResetAt:"rateLimitResetAt",authMode:"authMode",storageMode:"storageMode",secretPayload:"secretPayload",encryptedSecret:"encryptedSecret",wrappedDataKey:"wrappedDataKey",encryptionAlgorithm:"encryptionAlgorithm",keyVersion:"keyVersion",scopes:"scopes",accountLabel:"accountLabel",lastRefreshAt:"lastRefreshAt",reauthRequired:"reauthRequired",oauthRefreshToken:"oauthRefreshToken",oauthAccessToken:"oauthAccessToken",oauthExpiresAt:"oauthExpiresAt",projectId:"projectId",organizationId:"organizationId",secretType:"secretType",settingKey:"settingKey",settingValue:"settingValue",settingType:"settingType",apiKey:"apiKey",baseUrl:"baseUrl",inbox:"inbox",issue:"issue",task:"task",schedule:"schedule",automationRule:"automationRule",delivery:"delivery",deliveryKind:"deliveryKind",scheduleKind:"scheduleKind",ruleKind:"ruleKind",instruction:"instruction",input:"input",inputRequest:"inputRequest",captureCandidate:"captureCandidate",captureEvent:"captureEvent",captureDecision:"captureDecision",targetResource:"targetResource",suggestedType:"suggestedType",suggestedTarget:"suggestedTarget",confidence:"confidence",userCorrection:"userCorrection",trigger:"trigger",condition:"condition",actions:"actions",objective:"objective",payload:"payload",projection:"projection",target:"target",targetThread:"targetThread",targetSession:"targetSession",projectedRole:"projectedRole",consumedAt:"consumedAt",priority:"priority",commitment:"commitment",affectedArea:"affectedArea",currentUnderstanding:"currentUnderstanding",openQuestions:"openQuestions",conflicts:"conflicts",nextStep:"nextStep",promotedTo:"promotedTo",sourceMessage:"sourceMessage",parentIssue:"parentIssue",session:"session",status:"status",risk:"risk",assignedTo:"assignedTo",reason:"reason",resolvedAt:"resolvedAt",closedAt:"closedAt",action:"action",actor:"actor",actorRole:"actorRole",entry:"entry",context:"context",policy:"policy",pageKind:"pageKind",summary:"summary",body:"body",tags:"tags",source:"source",sourceKind:"sourceKind",sourceKey:"sourceKey",sourceHash:"sourceHash",fingerprint:"fingerprint",compiledAt:"compiledAt",compiledFrom:"compiledFrom",related:"related",approval:"approval",approvalOptions:"approvalOptions",inputOptions:"inputOptions",requestKind:"requestKind",requester:"requester",response:"response",answeredBy:"answeredBy",effect:"effect",expiresAt:"expiresAt",riskCeiling:"riskCeiling",revokedAt:"revokedAt",disabledAt:"disabledAt",archivedAt:"archivedAt",deletedAt:"deletedAt",pinnedAt:"pinnedAt",pinned:"pinned",muted:"muted",mutedAt:"mutedAt",unreadCount:"unreadCount",ttsModel:"ttsModel",videoModel:"videoModel",chatType:"chatType",workspace:"workspace",container:"container",policyRef:"policyRef",policyVersion:"policyVersion",parentThread:"parentThread",sessionStatus:"sessionStatus",runner:"runner",prompt:"prompt",externalRunId:"externalRunId",clientCredentialId:"clientCredentialId",appliedTo:"appliedTo",appliedOn:"appliedOn",appliedAt:"appliedAt",leaseOwner:"leaseOwner",leaseExpiresAt:"leaseExpiresAt",heartbeatAt:"heartbeatAt",cancelRequestedAt:"cancelRequestedAt",startedAt:"startedAt",startsAt:"startsAt",createdAt:"createdAt",updatedAt:"updatedAt",completedAt:"completedAt",nextRunAt:"nextRunAt",lastRunAt:"lastRunAt",lastTriggeredAt:"lastTriggeredAt",lastRunStatus:"lastRunStatus",cron:"cron",intervalSeconds:"intervalSeconds",timezone:"timezone",error:"error",run:"run",stepType:"stepType",evidence:"evidence",evidenceKind:"evidenceKind",report:"report",reportKind:"reportKind",outcome:"outcome",metricFacts:"metricFacts",publishedAt:"publishedAt",reviewer:"reviewer",sessionTool:"sessionTool",tokenUsage:"tokenUsage",noteKind:"noteKind",representationMediaType:"representationMediaType",readerEngine:"readerEngine",readerVersion:"readerVersion",generatedWithModel:"generatedWithModel",readerOptionsHash:"readerOptionsHash",representationHash:"representationHash",coverageUnit:"coverageUnit",coveredRange:"coveredRange",readUnits:"readUnits",totalUnits:"totalUnits",failureCategory:"failureCategory",chatModel:"chatModel",ocrModel:"ocrModel",readerModel:"readerModel",embeddingModel:"embeddingModel",indexerModel:"indexerModel",rerankerModel:"rerankerModel",ocrEnabled:"ocrEnabled",automaticOcr:"automaticOcr",imageRecognition:"imageRecognition",pdfRecognition:"pdfRecognition",tableRecognition:"tableRecognition",processingMode:"processingMode",readerPolicy:"readerPolicy",readerPriority:"readerPriority",maxFileSizeMb:"maxFileSizeMb",maxPages:"maxPages",chunkingStrategy:"chunkingStrategy",fileUrl:"fileUrl",vectorId:"vectorId",usageBytes:"usageBytes",lastError:"lastError",indexedAt:"indexedAt",lastActivityAt:"lastActivityAt",errorMessage:"errorMessage",groupOwner:"groupOwner",groupAdmin:"groupAdmin",senderName:"senderName",senderAvatarUrl:"senderAvatarUrl",mentions:"mentions",replyTo:"replyTo",routedBy:"routedBy",routeTargetAgent:"routeTargetAgent",coordinationId:"coordinationId",agent:"agent",toolCallId:"toolCallId",toolName:"toolName",toolArguments:"toolArguments",toolStatus:"toolStatus",toolResult:"toolResult",toolError:"toolError",toolDuration:"toolDuration",toolRisk:"toolRisk",approvalStatus:"approvalStatus",decisionBy:"decisionBy",decisionRole:"decisionRole",onBehalfOf:"onBehalfOf",approvalReason:"approvalReason",inboxItemId:"inboxItemId",taskProgressId:"taskProgressId",taskSteps:"taskSteps",currentStep:"currentStep",totalSteps:"totalSteps",sourceModule:"sourceModule",searchText:"searchText",snapshotMeta:"snapshotMeta"});UDFS.NAMESPACE;const solidProfileResource=podTable("profile",{id:id("id"),name:string$2("name").predicate(VCARD.fn),nick:string$2("nick").predicate(FOAF.nick),avatar:string$2("avatar").predicate(VCARD.hasPhoto),note:string$2("note").predicate(VCARD.note),email:string$2("email").predicate(VCARD.hasEmail),phone:string$2("phone").predicate(VCARD.hasTelephone),region:string$2("region").predicate(VCARD.region),gender:string$2("gender").predicate(VCARD.hasGender),favorite:string$2("favorite").predicate(UDFS.favorite),inbox:string$2("inbox").predicate(LDP.inbox)},{base:"idp:///profile/card",type:FOAF.Person,namespace:UDFS});definePodRepository({namespace:"profile",resource:solidProfileResource,searchableFields:["name","nick"],disableMutations:{create:!0,update:!0,remove:!0}});function pickSolidProfileDisplayName(n){return normalizeDisplayName(n?.name)??normalizeDisplayName(n?.nick)??null}function normalizeDisplayName(n){if(typeof n!="string")return null;const e=n.trim();return e||null}const RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",XSD="http://www.w3.org/2001/XMLSchema#",SWAP="http://www.w3.org/2000/10/swap/",namespaces={xsd:{decimal:`${XSD}decimal`,boolean:`${XSD}boolean`,double:`${XSD}double`,integer:`${XSD}integer`,string:`${XSD}string`},rdf:{type:`${RDF}type`,nil:`${RDF}nil`,first:`${RDF}first`,rest:`${RDF}rest`,langString:`${RDF}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${SWAP}reify#forSome`,forAll:`${SWAP}reify#forAll`},log:{implies:`${SWAP}log#implies`,isImpliedBy:`${SWAP}log#isImpliedBy`}},{xsd:xsd$1}=namespaces,escapeSequence=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,escapeReplacements={"\\":"\\","'":"'",'"':'"',n:`
228
+ `,prefixes:{ldp:"http://www.w3.org/ns/ldp#"}},o=await this.sparqlExecutor.queryContainer(t,s);for(const l of o){const u=l.resource;if(u){const h=hasStringValue(u)?u.value:String(u);i.push(h)}}}catch(s){console.warn("[listContainerResources] SPARQL query failed:",s)}return i}}_a=entityKind;PodDialect[_a]="PodDialect";function drizzle(n,e){if(!n||!n.info.isLoggedIn)throw new Error("需要有效的已认证Session");const t={session:n,preferredChannels:e?.notifications?.preferredChannels,createQueryEngine:e?.sparql?.createQueryEngine,disableInteropDiscovery:e?.disableInteropDiscovery,podUrl:e?.podUrl??n.info.podUrl,resourcePreparation:e?.resourcePreparation,storageTTL:e?.storageTTL,debug:e?.debug??e?.logger},i=new PodDialect(t);e?.schema&&i.setSchema(e.schema);const s=new PodAsyncSession(i);return new PodDatabase(i,s,e?.schema)}function createRepositoryDescriptor(n){const{namespace:e,table:t,searchableFields:i,defaultSort:s,cache:o}=n,l=n.searchAccessor??(A=>{const C=A?A.search:void 0;return typeof C=="string"?C:void 0}),u=n.transform??(A=>A),h={create:n.invalidations?.create??["list"],update:n.invalidations?.update??["list","detail"],remove:n.invalidations?.remove??["list","detail"]},d=A=>{const C=t[A];if(C)return C;const T=t.config?.name;return T?`${T}.${A}`:A},p=A=>{const C=[],T=l(A)?.trim();if(T&&i?.length){const P=`%${T}%`,q=i.map(O=>like(d(O),P));q.length===1?C.push(q[0]):q.length>1&&C.push(or(...q))}const F=n.filter?.({table:t,filters:A});if(F&&C.push(F),C.length!==0)return C.length===1?C[0]:and(...C)},g=async(A,C)=>{let T=A.select().from(t);const F=p(C);return F&&(T=T.where(F)),s&&(T=T.orderBy(d(s.field),s.direction)),(await T.execute()).map(q=>u(q))},m=async(A,C)=>{const T=await A.findByIri(t,C);return T?u(T):null},v=n.disableMutations?.create?void 0:async(A,C)=>{const T=C.id,F=typeof T=="string"&&T.length>0?T:crypto.randomUUID(),P={...C,id:F},q=await A.insert(t).values(P).execute(),O=Array.isArray(q)?q?.[0]:q;if(O&&typeof O=="object"&&!("success"in O))return u(O);const G=O&&typeof O=="object"&&"source"in O?O.source:null,fe=G?A.resolveRowIri(t,{...P,source:G}):A.resolveRowIri(t,P);return{...P,id:A.resolveRowId(t,{...P,"@id":fe}),"@id":fe,subject:fe,uri:fe,source:G??fe}},S=n.disableMutations?.update?void 0:async(A,C,T)=>{const F=await A.updateByIri(t,C,T);if(F)return u(F);const P=await m(A,C);if(!P)throw new Error(`Failed to load ${e} record after update`);return P},E=n.disableMutations?.remove?void 0:async(A,C)=>(await A.deleteByIri(t,C),{id:C}),x=typeof t.getResourcePath=="function"?t.getResourcePath():t.config?.base??"";return{namespace:e,resourcePath:x,searchableFields:i,defaultSort:s,cache:o,invalidations:h,list:g,detail:m,create:v,update:S,remove:E}}function createResourceRepositoryDescriptor(n){const{resource:e,filter:t,...i}=n;return createRepositoryDescriptor({...i,table:e,filter:t?({table:s,filters:o})=>t({resource:s,filters:o}):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$2={type:_NS$h("type")},_NAMESPACE$3="http://www.w3.org/2006/vcard/ns#";function _NS$3(n){return _NAMESPACE$3+n}var VCARD={PREFIX:"vcard",NAMESPACE:_NAMESPACE$3,PREFIX_AND_NAMESPACE:{vcard:"http://www.w3.org/2006/vcard/ns#"},NS:_NS$3,Acquaintance:_NS$3("Acquaintance"),RelatedType:_NS$3("RelatedType"),Agent:_NS$3("Agent"),BBS:_NS$3("BBS"),TelephoneType:_NS$3("TelephoneType"),Car:_NS$3("Car"),Cell:_NS$3("Cell"),Child:_NS$3("Child"),Colleague:_NS$3("Colleague"),Contact:_NS$3("Contact"),Coresident:_NS$3("Coresident"),Coworker:_NS$3("Coworker"),Crush:_NS$3("Crush"),Date:_NS$3("Date"),Dom:_NS$3("Dom"),Type:_NS$3("Type"),Emergency:_NS$3("Emergency"),Fax:_NS$3("Fax"),Female:_NS$3("Female"),Gender:_NS$3("Gender"),Friend:_NS$3("Friend"),Home:_NS$3("Home"),ISDN:_NS$3("ISDN"),Internet:_NS$3("Internet"),Intl:_NS$3("Intl"),Kin:_NS$3("Kin"),Label:_NS$3("Label"),Male:_NS$3("Male"),Me:_NS$3("Me"),Met:_NS$3("Met"),Modem:_NS$3("Modem"),Msg:_NS$3("Msg"),Muse:_NS$3("Muse"),Neighbor:_NS$3("Neighbor"),None:_NS$3("None"),Other:_NS$3("Other"),PCS:_NS$3("PCS"),Pager:_NS$3("Pager"),Parcel:_NS$3("Parcel"),Parent:_NS$3("Parent"),Postal:_NS$3("Postal"),Pref:_NS$3("Pref"),Sibling:_NS$3("Sibling"),Spouse:_NS$3("Spouse"),Sweetheart:_NS$3("Sweetheart"),Tel:_NS$3("Tel"),Text:_NS$3("Text"),TextPhone:_NS$3("TextPhone"),Unknown:_NS$3("Unknown"),Video:_NS$3("Video"),Voice:_NS$3("Voice"),Work:_NS$3("Work"),X400:_NS$3("X400"),Address:_NS$3("Address"),Email:_NS$3("Email"),Group:_NS$3("Group"),Kind:_NS$3("Kind"),Individual:_NS$3("Individual"),Location:_NS$3("Location"),Organization:_NS$3("Organization"),VCard:_NS$3("VCard"),Name:_NS$3("Name"),adr:_NS$3("adr"),hasAddress:_NS$3("hasAddress"),agent:_NS$3("agent"),anniversary:_NS$3("anniversary"),bday:_NS$3("bday"),category:_NS$3("category"),class:_NS$3("class"),email:_NS$3("email"),hasEmail:_NS$3("hasEmail"),extended_address:_NS$3("extended-address"),geo:_NS$3("geo"),hasGeo:_NS$3("hasGeo"),hasAdditionalName:_NS$3("hasAdditionalName"),hasCalendarBusy:_NS$3("hasCalendarBusy"),hasCalendarLink:_NS$3("hasCalendarLink"),hasCalendarRequest:_NS$3("hasCalendarRequest"),hasCategory:_NS$3("hasCategory"),hasCountryName:_NS$3("hasCountryName"),hasFN:_NS$3("hasFN"),hasFamilyName:_NS$3("hasFamilyName"),hasGender:_NS$3("hasGender"),hasGivenName:_NS$3("hasGivenName"),hasHonorificPrefix:_NS$3("hasHonorificPrefix"),hasHonorificSuffix:_NS$3("hasHonorificSuffix"),hasInstantMessage:_NS$3("hasInstantMessage"),hasLanguage:_NS$3("hasLanguage"),hasLocality:_NS$3("hasLocality"),hasNickname:_NS$3("hasNickname"),nickname:_NS$3("nickname"),hasNote:_NS$3("hasNote"),hasOrganizationName:_NS$3("hasOrganizationName"),hasOrganizationUnit:_NS$3("hasOrganizationUnit"),hasPostalCode:_NS$3("hasPostalCode"),hasRegion:_NS$3("hasRegion"),hasRelated:_NS$3("hasRelated"),hasRole:_NS$3("hasRole"),hasSource:_NS$3("hasSource"),hasStreetAddress:_NS$3("hasStreetAddress"),hasTitle:_NS$3("hasTitle"),hasUID:_NS$3("hasUID"),hasValue:_NS$3("hasValue"),label:_NS$3("label"),language:_NS$3("language"),latitude:_NS$3("latitude"),longitude:_NS$3("longitude"),mailer:_NS$3("mailer"),note:_NS$3("note"),org:_NS$3("org"),organization_name:_NS$3("organization-name"),organization_unit:_NS$3("organization-unit"),post_office_box:_NS$3("post-office-box"),prodid:_NS$3("prodid"),rev:_NS$3("rev"),role:_NS$3("role"),sort_string:_NS$3("sort-string"),title:_NS$3("title"),tz:_NS$3("tz"),value:_NS$3("value"),country_name:_NS$3("country-name"),locality:_NS$3("locality"),postal_code:_NS$3("postal-code"),region:_NS$3("region"),street_address:_NS$3("street-address"),fn:_NS$3("fn"),hasMember:_NS$3("hasMember"),additional_name:_NS$3("additional-name"),family_name:_NS$3("family-name"),given_name:_NS$3("given-name"),honorific_prefix:_NS$3("honorific-prefix"),honorific_suffix:_NS$3("honorific-suffix"),hasKey:_NS$3("hasKey"),key:_NS$3("key"),hasLogo:_NS$3("hasLogo"),logo:_NS$3("logo"),hasName:_NS$3("hasName"),n:_NS$3("n"),hasPhoto:_NS$3("hasPhoto"),photo:_NS$3("photo"),hasSound:_NS$3("hasSound"),sound:_NS$3("sound"),hasTelephone:_NS$3("hasTelephone"),tel:_NS$3("tel"),hasURL:_NS$3("hasURL"),url:_NS$3("url")};const ABSOLUTE_IRI$1=/^[a-zA-Z][a-zA-Z\d+.-]*:/,createNamespace=(n,e,t)=>{const i=(s=>ABSOLUTE_IRI$1.test(s)?s:`${e}${s}`);return i.prefix=n,i.uri=e,i.NAMESPACE=e,i.term=s=>i(s),Object.entries(t).forEach(([s,o])=>{Object.defineProperty(i,s,{value:i(o),enumerable:!0})}),i},DCTerms=DCTERMS,RDF$1=RDF$2,ODRL=createNamespace("odrl","http://www.w3.org/ns/odrl/2/",{Policy:"Policy",target:"target",action:"action"});createNamespace("rdfs","http://www.w3.org/2000/01/rdf-schema#",{Class:"Class",label:"label",comment:"comment",subClassOf:"subClassOf",domain:"domain",range:"range"});createNamespace("owl","http://www.w3.org/2002/07/owl#",{Ontology:"Ontology",Class:"Class",ObjectProperty:"ObjectProperty",DatatypeProperty:"DatatypeProperty"});const SCHEMA=createNamespace("schema","http://schema.org/",{CreativeWork:"CreativeWork",MediaObject:"MediaObject",PropertyValue:"PropertyValue",about:"about",author:"author",dateCreated:"dateCreated",dateDeleted:"dateDeleted",description:"description",encodingFormat:"encodingFormat",fileSize:"fileSize",image:"image",name:"name",participant:"participant",reviewedBy:"reviewedBy",text:"text",url:"url"}),SIOC=createNamespace("sioc","http://rdfs.org/sioc/ns#",{Container:"Container",Post:"Post",Thread:"Thread",Forum:"Forum",content:"content",richContent:"richContent",hasReply:"has_reply",replyOf:"reply_of",hasCreator:"has_creator",createdAt:"created_at",hasContainer:"has_container",has_parent:"has_parent",numReplies:"num_replies",has_member:"has_member",about:"about"}),MEETING=createNamespace("mee","http://www.w3.org/ns/pim/meeting#",{LongChat:"LongChat",Message:"Message"}),WF=createNamespace("wf","http://www.w3.org/2005/01/wf/flow-1.0#",{message:"message",participation:"participation",participant:"participant"}),AS=createNamespace("as","https://www.w3.org/ns/activitystreams#",{Activity:"Activity",Announce:"Announce",Public:"Public",audience:"audience",actor:"actor",object:"object",target:"target"}),UDFS=createNamespace("udfs","https://undefineds.co/ns#",{ApprovalRequest:"ApprovalRequest",InputRequest:"InputRequest",CaptureCandidate:"CaptureCandidate",CaptureEvent:"CaptureEvent",AuditEntry:"AuditEntry",AutonomyGrant:"AutonomyGrant",Idea:"Idea",Issue:"Issue",Task:"Task",Schedule:"Schedule",AutomationRule:"AutomationRule",Delivery:"Delivery",Run:"Run",RunStep:"RunStep",Evidence:"Evidence",Report:"Report",Credential:"Credential",ApiKeyCredential:"ApiKeyCredential",OAuthCredential:"OAuthCredential",Provider:"Provider",Model:"Model",AIModel:"AIModel",ChatModel:"ChatModel",EmbeddingModel:"EmbeddingModel",DocumentUnderstandingModel:"DocumentUnderstandingModel",RerankingModel:"RerankingModel",ImageGenerationModel:"ImageGenerationModel",SpeechRecognitionModel:"SpeechRecognitionModel",SpeechSynthesisModel:"SpeechSynthesisModel",VideoGenerationModel:"VideoGenerationModel",ModelCapability:"ModelCapability",ChatCapability:"ChatCapability",EmbeddingCapability:"EmbeddingCapability",RerankingCapability:"RerankingCapability",ToolCallCapability:"ToolCallCapability",ReasoningCapability:"ReasoningCapability",WebCapability:"WebCapability",VisionCapability:"VisionCapability",OCRCapability:"OCRCapability",DocumentUnderstandingCapability:"DocumentUnderstandingCapability",StructuredOutputCapability:"StructuredOutputCapability",IndexingCapability:"IndexingCapability",ImageGenerationCapability:"ImageGenerationCapability",SpeechRecognitionCapability:"SpeechRecognitionCapability",SpeechSynthesisCapability:"SpeechSynthesisCapability",VideoGenerationCapability:"VideoGenerationCapability",AIConfig:"AIConfig",Note:"Note",VectorStore:"VectorStore",IndexedFile:"IndexedFile",AgentStatus:"AgentStatus",GatewayAccessKey:"GatewayAccessKey",QuotaSnapshot:"QuotaSnapshot",ChatProjectContext:"ChatProjectContext",ProjectMemory:"ProjectMemory",ConversationShare:"ConversationShare",Skill:"Skill",name:"name",favorite:"favorite",favoriteType:"favoriteType",favoriteTarget:"favoriteTarget",favoredAt:"favoredAt",conversation:"conversation",conversationType:"conversationType",conversationTitle:"conversationTitle",lastMessage:"lastMessage",lastActiveAt:"lastActiveAt",lastSyncedAt:"lastSyncedAt",sortKey:"sortKey",hasThread:"hasThread",inThread:"inThread",inScope:"inScope",participants:"participants",message:"message",messageContent:"messageContent",messageType:"messageType",messageStatus:"messageStatus",readBy:"readBy",Contact:"Contact",PersonContact:"PersonContact",AgentContact:"AgentContact",GroupContact:"GroupContact",hasContact:"hasContact",contactType:"contactType",externalPlatform:"externalPlatform",externalId:"externalId",alias:"alias",aiAssistant:"aiAssistant",aiModel:"aiModel",aiModels:"aiModels",aiProvider:"aiProvider",credential:"credential",systemPrompt:"systemPrompt",temperature:"temperature",maxTokens:"maxTokens",systemMessage:"systemMessage",provider:"provider",model:"model",displayName:"displayName",proxyUrl:"proxyUrl",hasModel:"hasModel",defaultModel:"defaultModel",modelType:"modelType",isProvidedBy:"isProvidedBy",inputModality:"inputModality",outputModality:"outputModality",capability:"capability",hasCapability:"hasCapability",contextLength:"contextLength",maxOutputTokens:"maxOutputTokens",pricingInput:"pricingInput",pricingOutput:"pricingOutput",apiKeyUrl:"apiKeyUrl",connectMode:"connectMode",homepage:"homepage",dimension:"dimension",supportsBackend:"supportsBackend",rotationPolicy:"rotationPolicy",metadata:"metadata",root:"root",webId:"webId",hasSkill:"hasSkill",skill:"skill",enabled:"enabled",memoryEnabled:"memoryEnabled",includeToolDetails:"includeToolDetails",excludedMessage:"excludedMessage",version:"version",checksum:"checksum",loadPolicy:"loadPolicy",credentialSource:"credentialSource",backend:"backend",runtime:"runtime",transport:"transport",endpoint:"endpoint",authorityPolicy:"authorityPolicy",toolPolicy:"toolPolicy",runtimeSnapshot:"runtimeSnapshot",tools:"tools",contextWindow:"contextWindow",contextRound:"contextRound",Agent:"Agent",agentCapability:"agentCapability",agentTool:"agentTool",agentConfig:"agentConfig",fileHash:"fileHash",syncStatus:"syncStatus",localPath:"localPath",isDefault:"isDefault",service:"service",label:"label",owner:"owner",secretHash:"secretHash",deployment:"deployment",balance:"balance",windows:"windows",observedAt:"observedAt",lastUsedAt:"lastUsedAt",failCount:"failCount",rateLimitResetAt:"rateLimitResetAt",authMode:"authMode",offeringId:"offeringId",storageMode:"storageMode",secretPayload:"secretPayload",encryptedSecret:"encryptedSecret",wrappedDataKey:"wrappedDataKey",encryptionAlgorithm:"encryptionAlgorithm",keyVersion:"keyVersion",scopes:"scopes",accountLabel:"accountLabel",lastRefreshAt:"lastRefreshAt",reauthRequired:"reauthRequired",oauthRefreshToken:"oauthRefreshToken",oauthAccessToken:"oauthAccessToken",oauthExpiresAt:"oauthExpiresAt",projectId:"projectId",organizationId:"organizationId",secretType:"secretType",settingKey:"settingKey",settingValue:"settingValue",settingType:"settingType",apiKey:"apiKey",baseUrl:"baseUrl",inbox:"inbox",issue:"issue",task:"task",schedule:"schedule",automationRule:"automationRule",delivery:"delivery",deliveryKind:"deliveryKind",scheduleKind:"scheduleKind",ruleKind:"ruleKind",instruction:"instruction",input:"input",inputRequest:"inputRequest",captureCandidate:"captureCandidate",captureEvent:"captureEvent",captureDecision:"captureDecision",targetResource:"targetResource",suggestedType:"suggestedType",suggestedTarget:"suggestedTarget",confidence:"confidence",userCorrection:"userCorrection",trigger:"trigger",condition:"condition",actions:"actions",objective:"objective",payload:"payload",projection:"projection",target:"target",targetThread:"targetThread",targetSession:"targetSession",projectedRole:"projectedRole",consumedAt:"consumedAt",priority:"priority",commitment:"commitment",affectedArea:"affectedArea",currentUnderstanding:"currentUnderstanding",openQuestions:"openQuestions",conflicts:"conflicts",nextStep:"nextStep",promotedTo:"promotedTo",sourceMessage:"sourceMessage",parentIssue:"parentIssue",session:"session",status:"status",risk:"risk",assignedTo:"assignedTo",reason:"reason",resolvedAt:"resolvedAt",closedAt:"closedAt",action:"action",actor:"actor",actorRole:"actorRole",entry:"entry",context:"context",policy:"policy",pageKind:"pageKind",summary:"summary",body:"body",tags:"tags",source:"source",sourceKind:"sourceKind",sourceKey:"sourceKey",sourceHash:"sourceHash",fingerprint:"fingerprint",compiledAt:"compiledAt",compiledFrom:"compiledFrom",related:"related",approval:"approval",approvalOptions:"approvalOptions",inputOptions:"inputOptions",requestKind:"requestKind",requester:"requester",response:"response",answeredBy:"answeredBy",effect:"effect",expiresAt:"expiresAt",riskCeiling:"riskCeiling",revokedAt:"revokedAt",disabledAt:"disabledAt",archivedAt:"archivedAt",deletedAt:"deletedAt",pinnedAt:"pinnedAt",pinned:"pinned",muted:"muted",mutedAt:"mutedAt",unreadCount:"unreadCount",ttsModel:"ttsModel",videoModel:"videoModel",chatType:"chatType",workspace:"workspace",container:"container",policyRef:"policyRef",policyVersion:"policyVersion",parentThread:"parentThread",sessionStatus:"sessionStatus",runner:"runner",prompt:"prompt",externalRunId:"externalRunId",clientCredentialId:"clientCredentialId",appliedTo:"appliedTo",appliedOn:"appliedOn",appliedAt:"appliedAt",leaseOwner:"leaseOwner",leaseExpiresAt:"leaseExpiresAt",heartbeatAt:"heartbeatAt",cancelRequestedAt:"cancelRequestedAt",startedAt:"startedAt",startsAt:"startsAt",createdAt:"createdAt",updatedAt:"updatedAt",completedAt:"completedAt",nextRunAt:"nextRunAt",lastRunAt:"lastRunAt",lastTriggeredAt:"lastTriggeredAt",lastRunStatus:"lastRunStatus",cron:"cron",intervalSeconds:"intervalSeconds",timezone:"timezone",error:"error",run:"run",stepType:"stepType",evidence:"evidence",evidenceKind:"evidenceKind",report:"report",reportKind:"reportKind",outcome:"outcome",metricFacts:"metricFacts",publishedAt:"publishedAt",reviewer:"reviewer",sessionTool:"sessionTool",tokenUsage:"tokenUsage",noteKind:"noteKind",representationMediaType:"representationMediaType",readerEngine:"readerEngine",readerVersion:"readerVersion",generatedWithModel:"generatedWithModel",readerOptionsHash:"readerOptionsHash",representationHash:"representationHash",coverageUnit:"coverageUnit",coveredRange:"coveredRange",readUnits:"readUnits",totalUnits:"totalUnits",failureCategory:"failureCategory",chatModel:"chatModel",ocrModel:"ocrModel",readerModel:"readerModel",embeddingModel:"embeddingModel",indexerModel:"indexerModel",rerankerModel:"rerankerModel",ocrEnabled:"ocrEnabled",automaticOcr:"automaticOcr",imageRecognition:"imageRecognition",pdfRecognition:"pdfRecognition",tableRecognition:"tableRecognition",processingMode:"processingMode",readerPolicy:"readerPolicy",readerPriority:"readerPriority",maxFileSizeMb:"maxFileSizeMb",maxPages:"maxPages",chunkingStrategy:"chunkingStrategy",fileUrl:"fileUrl",vectorId:"vectorId",usageBytes:"usageBytes",lastError:"lastError",indexedAt:"indexedAt",lastActivityAt:"lastActivityAt",errorMessage:"errorMessage",groupOwner:"groupOwner",groupAdmin:"groupAdmin",senderName:"senderName",senderAvatarUrl:"senderAvatarUrl",mentions:"mentions",replyTo:"replyTo",routedBy:"routedBy",routeTargetAgent:"routeTargetAgent",coordinationId:"coordinationId",agent:"agent",toolCallId:"toolCallId",toolName:"toolName",toolArguments:"toolArguments",toolStatus:"toolStatus",toolResult:"toolResult",toolError:"toolError",toolDuration:"toolDuration",toolRisk:"toolRisk",approvalStatus:"approvalStatus",decisionBy:"decisionBy",decisionRole:"decisionRole",onBehalfOf:"onBehalfOf",approvalReason:"approvalReason",inboxItemId:"inboxItemId",taskProgressId:"taskProgressId",taskSteps:"taskSteps",currentStep:"currentStep",totalSteps:"totalSteps",sourceModule:"sourceModule",searchText:"searchText",snapshotMeta:"snapshotMeta"});UDFS.NAMESPACE;const solidProfileResource=podTable("profile",{id:id("id"),name:string$2("name").predicate(VCARD.fn),nick:string$2("nick").predicate(FOAF.nick),avatar:string$2("avatar").predicate(VCARD.hasPhoto),note:string$2("note").predicate(VCARD.note),email:string$2("email").predicate(VCARD.hasEmail),phone:string$2("phone").predicate(VCARD.hasTelephone),region:string$2("region").predicate(VCARD.region),gender:string$2("gender").predicate(VCARD.hasGender),favorite:string$2("favorite").predicate(UDFS.favorite),inbox:string$2("inbox").predicate(LDP.inbox)},{base:"idp:///profile/card",type:FOAF.Person,namespace:UDFS});definePodRepository({namespace:"profile",resource:solidProfileResource,searchableFields:["name","nick"],disableMutations:{create:!0,update:!0,remove:!0}});function pickSolidProfileDisplayName(n){return normalizeDisplayName(n?.name)??normalizeDisplayName(n?.nick)??null}function normalizeDisplayName(n){if(typeof n!="string")return null;const e=n.trim();return e||null}const RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",XSD="http://www.w3.org/2001/XMLSchema#",SWAP="http://www.w3.org/2000/10/swap/",namespaces={xsd:{decimal:`${XSD}decimal`,boolean:`${XSD}boolean`,double:`${XSD}double`,integer:`${XSD}integer`,string:`${XSD}string`},rdf:{type:`${RDF}type`,nil:`${RDF}nil`,first:`${RDF}first`,rest:`${RDF}rest`,langString:`${RDF}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${SWAP}reify#forSome`,forAll:`${SWAP}reify#forAll`},log:{implies:`${SWAP}log#implies`,isImpliedBy:`${SWAP}log#isImpliedBy`}},{xsd:xsd$1}=namespaces,escapeSequence=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,escapeReplacements={"\\":"\\","'":"'",'"':'"',n:`
229
229
  `,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},illegalIriChars=/[\x00-\x20<>\\"\{\}\|\^\`]/,lineModeRegExps={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},invalidRegExp=/$0^/;class N3Lexer{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const t in this)!(t in lineModeRegExps)&&this[t]instanceof RegExp&&(this[t]=invalidRegExp)}else this._n3Mode=e.n3!==!1;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let i=this._input,s=i.length;for(;;){let u,h;for(;u=this._newline.exec(i);)this.comments&&(h=this._comment.exec(u[0]))&&o("comment",h[1],"",this._line,u[0].length),i=i.substr(u[0].length,i.length),s=i.length,this._line++;if(!u&&(u=this._whitespace.exec(i))&&(i=i.substr(u[0].length,i.length)),this._endOfFile.test(i))return t&&(this.comments&&(h=this._comment.exec(i))&&o("comment",h[1],"",this._line,i.length),i=null,o("eof","","",this._line,0)),this._input=i;const d=this._line,p=i[0];let g="",m="",v="",S=null,E=0,x=!1;switch(p){case"^":if(i.length<3)break;if(i[1]==="^"){if(this._previousMarker="^^",i=i.substr(2),i[0]!=="<"){x=!0;break}}else{this._n3Mode&&(E=1,g="^");break}case"<":if(S=this._unescapedIri.exec(i))g="IRI",m=S[1];else if(S=this._iri.exec(i)){if(m=this._unescape(S[1]),m===null||illegalIriChars.test(m))return l(this);g="IRI"}else i.length>1&&i[1]==="<"?(g="<<",E=2):this._n3Mode&&i.length>1&&i[1]==="="&&(E=2,this._isImpliedBy?(g="abbreviation",m="<"):(g="inverse",m=">"));break;case">":i.length>1&&i[1]===">"&&(g=">>",E=2);break;case"_":((S=this._blank.exec(i))||t&&(S=this._blank.exec(`${i} `)))&&(g="blank",v="_",m=S[1]);break;case'"':if(S=this._simpleQuotedString.exec(i))m=S[1];else if({value:m,matchLength:E}=this._parseLiteral(i),m===null)return l(this);(S!==null||E!==0)&&(g="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(S=this._simpleApostropheString.exec(i))m=S[1];else if({value:m,matchLength:E}=this._parseLiteral(i),m===null)return l(this);(S!==null||E!==0)&&(g="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(S=this._variable.exec(i))&&(g="var",m=S[0]);break;case"@":this._previousMarker==="literal"&&(S=this._langcode.exec(i))?(g="langcode",m=S[1]):(S=this._keyword.exec(i))&&(g=S[0]);break;case".":if(i.length===1?t:i[1]<"0"||i[1]>"9"){g=".",E=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(S=this._number.exec(i)||t&&(S=this._number.exec(`${i} `)))&&(g="literal",m=S[0],v=typeof S[1]=="string"?xsd$1.double:typeof S[2]=="string"?xsd$1.decimal:xsd$1.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(S=this._sparqlKeyword.exec(i))?g=S[0].toUpperCase():x=!0;break;case"f":case"t":(S=this._boolean.exec(i))?(g="literal",m=S[0],v=xsd$1.boolean):x=!0;break;case"a":(S=this._shortPredicates.exec(i))?(g="abbreviation",m="a"):x=!0;break;case"=":this._n3Mode&&i.length>1&&(g="abbreviation",i[1]!==">"?(E=1,m="="):(E=2,m=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(E=1,g=p);break;case"{":!this._lineMode&&i.length>=2&&(i[1]==="|"?(g="{|",E=2):(g=p,E=1));break;case"|":i.length>=2&&i[1]==="}"&&(g="|}",E=2);break;default:x=!0}if(x&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(S=this._prefix.exec(i))?(g="prefix",m=S[1]||""):((S=this._prefixed.exec(i))||t&&(S=this._prefixed.exec(`${i} `)))&&(g="prefixed",v=S[1]||"",m=this._unescape(S[2]))),this._previousMarker==="^^")switch(g){case"prefixed":g="type";break;case"IRI":g="typeIRI";break;default:g=""}if(!g)return t||!/^'''|^"""/.test(i)&&/\n|\r/.test(i)?l(this):this._input=i;const A=E||S[0].length,C=o(g,m,v,d,A);this.previousToken=C,this._previousMarker=g,i=i.substr(A,i.length)}function o(u,h,d,p,g){const m=i?s-i.length:s,v=m+g,S={type:u,value:h,prefix:d,line:p,start:m,end:v};return e(null,S),S}function l(u){e(u._syntaxError(/^\S*/.exec(i)[0]))}}_unescape(e){let t=!1;const i=e.replace(escapeSequence,(s,o,l,u)=>{if(typeof o=="string")return String.fromCharCode(Number.parseInt(o,16));if(typeof l=="string"){let h=Number.parseInt(l,16);return h<=65535?String.fromCharCode(Number.parseInt(l,16)):String.fromCharCode(55296+((h-=65536)>>10),56320+(h&1023))}return u in escapeReplacements?escapeReplacements[u]:(t=!0,"")});return t?null:i}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],i=t.length;let s=Math.max(this._literalClosingPos,i);for(;(s=e.indexOf(t,s))>0;){let o=0;for(;e[s-o-1]==="\\";)o++;if(o%2===0){const l=e.substring(i,s),u=l.split(/\r\n|\r|\n/).length-1,h=s+i;if(i===1&&u!==0||i===3&&this._lineMode)break;return this._line+=u,{value:this._unescape(l),matchLength:h}}s++}this._literalClosingPos=e.length-i+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\uFEFF")?e.substr(1):e}tokenize(e,t){if(this._line=1,typeof e=="string")if(this._input=this._readStartingBom(e),typeof t=="function")queueMicrotask(()=>this._tokenizeToEnd(t,!0));else{const i=[];let s;if(this._tokenizeToEnd((o,l)=>o?s=o:i.push(l),!0),s)throw s;return i}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",i=>{this._input!==null&&i.length!==0&&(this._pendingBuffer&&(i=bufferExports.Buffer.concat([this._pendingBuffer,i]),this._pendingBuffer=null),i[i.length-1]&128?this._pendingBuffer=i:(typeof this._input>"u"?this._input=this._readStartingBom(typeof i=="string"?i:i.toString()):this._input+=i,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}}const{rdf,xsd}=namespaces;let DEFAULTGRAPH,_blankNodeCounter=0;const DataFactory={namedNode,blankNode,variable,literal,defaultGraph,quad,triple:quad,fromTerm,fromQuad};class Term{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof Term?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class NamedNode extends Term{get termType(){return"NamedNode"}}class Literal extends Term{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t<e.length&&e[t++]==="@"?e.substr(t).toLowerCase():""}get datatype(){return new NamedNode(this.datatypeString)}get datatypeString(){const e=this.id,t=e.lastIndexOf('"')+1,i=t<e.length?e[t]:"";return i==="^"?e.substr(t+2):i!=="@"?xsd.string:rdf.langString}equals(e){return e instanceof Literal?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}}class BlankNode extends Term{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class Variable extends Term{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}class DefaultGraph extends Term{constructor(){return super(""),DEFAULTGRAPH||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}}DEFAULTGRAPH=new DefaultGraph;class Quad extends Term{constructor(e,t,i,s){super(""),this._subject=e,this._predicate=t,this._object=i,this._graph=s||DEFAULTGRAPH}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(e){return!!e&&this._subject.equals(e.subject)&&this._predicate.equals(e.predicate)&&this._object.equals(e.object)&&this._graph.equals(e.graph)}}function namedNode(n){return new NamedNode(n)}function blankNode(n){return new BlankNode(n||`n3-${_blankNodeCounter++}`)}function literal(n,e){if(typeof e=="string")return new Literal(`"${n}"@${e.toLowerCase()}`);let t=e?e.value:"";return t===""&&(typeof n=="boolean"?t=xsd.boolean:typeof n=="number"&&(Number.isFinite(n)?t=Number.isInteger(n)?xsd.integer:xsd.double:(t=xsd.double,Number.isNaN(n)||(n=n>0?"INF":"-INF")))),t===""||t===xsd.string?new Literal(`"${n}"`):new Literal(`"${n}"^^${t}`)}function variable(n){return new Variable(n)}function defaultGraph(){return DEFAULTGRAPH}function quad(n,e,t,i){return new Quad(n,e,t,i)}function fromTerm(n){if(n instanceof Term)return n;switch(n.termType){case"NamedNode":return namedNode(n.value);case"BlankNode":return blankNode(n.value);case"Variable":return variable(n.value);case"DefaultGraph":return DEFAULTGRAPH;case"Literal":return literal(n.value,n.language||n.datatype);case"Quad":return fromQuad(n);default:throw new Error(`Unexpected termType: ${n.termType}`)}}function fromQuad(n){if(n instanceof Quad)return n;if(n.termType!=="Quad")throw new Error(`Unexpected termType: ${n.termType}`);return quad(fromTerm(n.subject),fromTerm(n.predicate),fromTerm(n.object),fromTerm(n.graph))}let blankNodePrefix=0;class N3Parser{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&initDataFactory(this,e.factory);const t=typeof e.format=="string"?e.format.match(/\w*$/)[0].toLowerCase():"",i=/turtle/.test(t),s=/trig/.test(t),o=/triple/.test(t),l=/quad/.test(t),u=this._n3Mode=/n3/.test(t),h=o||l;(this._supportsNamedGraphs=!(i||u))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(i||s||o||u),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=t===""||/star|\*$/.test(t),h&&(this._resolveRelativeIRI=d=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new N3Lexer({lineMode:h,n3:u,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){blankNodePrefix=0}_setBase(e){if(!e)this._base="",this._basePath="";else{const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}}_saveContext(e,t,i,s,o){const l=this._n3Mode;this._contextStack.push({type:e,subject:i,predicate:s,object:o,graph:t,inverse:l?this._inversePredicate:!1,blankPrefix:l?this._prefixes._:"",quantified:l?this._quantified:null}),l&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const i=this._contextStack.pop();if(!i||i.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=i.subject,this._predicate=i.predicate,this._object=i.object,this._graph=i.graph,this._n3Mode&&(this._inversePredicate=i.inverse,this._prefixes._=i.blankPrefix,this._quantified=i.quantified)}_readInTopContext(e){switch(e.type){case"eof":return this._graph!==null?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let i;switch(e.type){case"IRI":case"typeIRI":const s=this._resolveIRI(e.value);if(s===null)return this._error("Invalid IRI",e);i=this._factory.namedNode(s);break;case"type":case"prefixed":const o=this._prefixes[e.prefix];if(o===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);i=this._factory.namedNode(o+e.value);break;case"blank":i=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":i=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&i.id in this._quantified&&(i=this._quantified[i.id]),i}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(e.prefix.length===0)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._subject=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return this._predicate===null?this._error(`Unexpected ${t}`,e):(this._subject=null,t==="]"?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if((this._predicate=this._readEntity(e))===void 0)return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(e.prefix.length===0)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._object=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return e.type==="{"?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return e.type!=="{"?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return e.type==="]"?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if(e.type!=="]")return this._readBlankNodePunctuation(e);this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=this._predicate===null;return this._restoreContext("blank",e),this._object!==null?this._getContextEndReader():this._predicate!==null?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,i=null,s=this._readListItem;const o=this._subject,l=this._contextStack,u=l[l.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,i=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),s=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,i=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),l.length!==0&&l[l.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(s=this._readPredicate,this._subject===this.RDF_NIL)return s}else if(s=this._getContextEndReader(),this._object===this.RDF_NIL)return s;i=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,s=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),s=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if((t=this._readEntity(e))===void 0)return}if(i===null&&(this._subject=i=this._factory.blankNode()),o===null?u.predicate===null?u.subject=i:u.object=i:this._emit(o,this.RDF_REST,i,this._graph),t!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,i,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(i,this.RDF_FIRST,t,this._graph)}return s}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const i=this._readEntity(e);if(i===void 0)return;t=this._factory.literal(this._literalValue,i),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null;break}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const i=this._completeLiteral(e);if(i)return this._object=i.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),i.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(i.token))}_readFormulaTail(e){return e.type!=="}"?this._readPunctuation(e):(this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),this._object===null?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,i=this._graph;const s=this._subject,o=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,o&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const l=this._predicate,u=this._object;this._subject=this._factory.quad(s,l,u,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(i=this._readEntity(e))!==void 0){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(s!==null){const l=this._predicate,u=this._object;o?this._emit(u,l,s,i):this._emit(s,l,u,i)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return e.type!=="."?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return e.type!=="prefix"?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if(e.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t=e.type==="IRI"&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return e.type!=="]"?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):e.type!=="."?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if((t=this._readEntity(e,!0))!==void 0)break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(this._subject===null?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return e.type===","?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,i=t.length&&t[t.length-1];if(i&&i.type==="item"){const s=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,s,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,i;const s=this._factory.blankNode();if((i=this._readEntity(e))!==void 0)return this._predicate===null?(t=this._subject,this._subject=s):(t=this._object,this._object=s),this._emit(t,i,s,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let i,s;if((i=this._readEntity(e))!==void 0)return this._predicate===null?(s=this._subject,this._subject=t):(s=this._object,this._object=t),this._emit(t,i,s,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return e.type!==">>"?this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(e))!==void 0?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(e.type!==">>")return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),this._subject===null?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,i,s){this._callback(null,this._factory.quad(e,t,i,s||this.DEFAULTGRAPH))}_error(e,t){const i=new Error(`${e} on line ${t.line}.`);i.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(i),this._callback=noop}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return(e[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let i="",s=-1,o=-1,l=0,u="/";for(;s<t;){switch(u){case":":if(o<0&&e[++s]==="/"&&e[++s]==="/")for(;(o=s+1)<t&&e[o]!=="/";)s=o;break;case"?":case"#":s=t;break;case"/":if(e[s+1]===".")switch(u=e[++s+1],u){case"/":i+=e.substring(l,s-1),l=s+1;break;case void 0:case"?":case"#":return i+e.substring(l,s)+e.substr(s+1);case".":if(u=e[++s+1],u===void 0||u==="/"||u==="?"||u==="#"){if(i+=e.substring(l,s-2),(l=i.lastIndexOf("/"))>=o&&(i=i.substr(0,l)),u!=="/")return`${i}/${e.substr(s+1)}`;l=s+1}}}u=e[++s]}return i+e.substring(l)}parse(e,t,i){let s,o,l;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(s=t.onQuad,o=t.onPrefix,l=t.onComment):(s=t,o=i),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix++}_`,this._prefixCallback=o||noop,this._inversePredicate=!1,this._quantified=Object.create(null),!s){const h=[];let d;if(this._callback=(p,g)=>{p?d=p:g&&h.push(g)},this._lexer.tokenize(e).every(p=>this._readCallback=this._readCallback(p)),d)throw d;return h}let u=(h,d)=>{h!==null?(this._callback(h),this._callback=noop):this._readCallback&&(this._readCallback=this._readCallback(d))};l&&(this._lexer.comments=!0,u=(h,d)=>{h!==null?(this._callback(h),this._callback=noop):this._readCallback&&(d.type==="comment"?l(d.value):this._readCallback=this._readCallback(d))}),this._callback=s,this._lexer.tokenize(e,u)}}function noop(){}function initDataFactory(n,e){n._factory=e,n.DEFAULTGRAPH=e.defaultGraph(),n.RDF_FIRST=e.namedNode(namespaces.rdf.first),n.RDF_REST=e.namedNode(namespaces.rdf.rest),n.RDF_NIL=e.namedNode(namespaces.rdf.nil),n.N3_FORALL=e.namedNode(namespaces.r.forAll),n.N3_FORSOME=e.namedNode(namespaces.r.forSome),n.ABBREVIATIONS={a:e.namedNode(namespaces.rdf.type),"=":e.namedNode(namespaces.owl.sameAs),">":e.namedNode(namespaces.log.implies),"<":e.namedNode(namespaces.log.isImpliedBy)},n.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}initDataFactory(N3Parser.prototype,DataFactory);async function resolveSolidProfileIdentityFromWebIdDocument(n,e={}){const t=e.webId??n.info?.webId;if(!t?.trim()||typeof n.fetch!="function")return null;const i=stripHash(t),s=await n.fetch(i,{headers:{Accept:"text/turtle, application/ld+json;q=0.9, text/n3;q=0.8, */*;q=0.1"}});if(!s.ok)throw new Error(`Failed to fetch WebID profile: ${s.status} ${s.statusText}`.trim());const o=s.headers.get("content-type")??"",l=await s.text();if(!l.trim())return buildSolidProfileIdentity(t,null);const u=await parseSolidProfileDocument(l,{contentType:o,profileDocumentUrl:i,webId:t});return buildSolidProfileIdentity(t,u)}async function parseSolidProfileDocument(n,e){return(e.contentType?.toLowerCase()??"").includes("application/ld+json")||n.trimStart().startsWith("{")?parseJsonLdProfileDocument(n,e.webId):await parseTurtleProfileDocument(n,e)}async function parseTurtleProfileDocument(n,e){const t=N3Parser,s=new t({baseIRI:e.profileDocumentUrl}).parse(n);return pickProfileFromQuads(s,e.webId)}function parseJsonLdProfileDocument(n,e){try{const t=JSON.parse(n),i=Array.isArray(t)?t:isRecord$1(t)&&Array.isArray(t["@graph"])?t["@graph"]:[t],s=i.find(l=>isRecord$1(l)&&l["@id"]===e),o=isRecord$1(s)?s:i.find(isRecord$1);return o?normalizeProfileRow({id:e,name:pickJsonLdString(o,VCARD.fn),nick:pickJsonLdString(o,FOAF.nick),avatar:pickJsonLdString(o,VCARD.hasPhoto),note:pickJsonLdString(o,VCARD.note),email:pickJsonLdString(o,VCARD.hasEmail),phone:pickJsonLdString(o,VCARD.hasTelephone),region:pickJsonLdString(o,VCARD.region),gender:pickJsonLdString(o,VCARD.hasGender)}):null}catch{return null}}function pickProfileFromQuads(n,e){const t={id:e};for(const i of n){if(i.subject.value!==e)continue;const s=i.predicate.value,o=i.object.value;!s||!o||(s===VCARD.fn?t.name=o:s===FOAF.nick?t.nick=o:s===VCARD.hasPhoto?t.avatar=o:s===VCARD.note?t.note=o:s===VCARD.hasEmail?t.email=o:s===VCARD.hasTelephone?t.phone=o:s===VCARD.region?t.region=o:s===VCARD.hasGender&&(t.gender=o))}return normalizeProfileRow(t)}function buildSolidProfileIdentity(n,e){return{webId:n,profile:e,displayName:pickSolidProfileDisplayName(e),username:extractProfileUsernameFromWebId(n)}}function normalizeProfileRow(n){const e=Object.fromEntries(Object.entries(n).filter(([,t])=>typeof t=="string"&&t.trim()));return Object.keys(e).length>1?e:null}function pickJsonLdString(n,e){return normalizeJsonLdValue(n[e])}function normalizeJsonLdValue(n){if(typeof n=="string")return n;if(Array.isArray(n))return n.map(normalizeJsonLdValue).find(Boolean);if(isRecord$1(n))return normalizeJsonLdValue(n["@value"]??n["@id"])}function stripHash(n){const e=n.indexOf("#");return e>=0?n.slice(0,e):n}function isRecord$1(n){return typeof n=="object"&&n!==null}function useXpodProfileCardIdentity({accountIdentity:n,runtime:e}){const t=e?.state.status,i=t==="authenticated"&&e?e.webId??e.state.webId:n?.webId,s=t==="authenticated"&&i?void 0:n,o=s?.displayName,l=s?.username,u=s?.id,h=s?.webId,d=e?.fetch,p=reactExports.useMemo(()=>accountProfileFallback({displayName:o,username:l,id:u},i),[o,u,l,h,i]),g=`${i??""}\0${p.displayName}\0${p.username??""}`,[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1);reactExports.useEffect(()=>{const A=d;if(t!=="authenticated"||!A||!i)return;let C=!1,T;async function F(P,q){E(!0);try{const O=await resolveSolidProfileIdentityFromWebIdDocument({info:{webId:q},fetch:P});if(C||!O)return;const G=normalizedHttpUrl(O.profile?.avatar);let fe=G;if(G&&(fe=await resolveAuthenticatedAvatarUrl(P,G),T=fe?.startsWith("blob:")?fe:void 0),C){T&&URL.revokeObjectURL(T);return}v({key:g,value:{displayName:O.displayName??O.username??p.displayName,username:O.username||p.username,avatarUrl:fe??p.avatarUrl,avatarSourceUrl:G,note:O.profile?.note||p.note,region:O.profile?.region||p.region,webId:O.webId||p.webId,loading:!1,source:"webid-profile"}})}catch{C||v(void 0)}finally{C||E(!1)}}return F(A,i),()=>{C=!0,T&&URL.revokeObjectURL(T)}},[d,p,g,t,i]);const x=t==="authenticated"?S:!1;return t==="authenticated"&&m?.key===g?{...m.value,loading:x}:{...p,loading:x}}function accountProfileFallback(n,e){const t=n?.username||usernameFromWebId$1(e)||n?.id;return{displayName:n?.displayName||t||n?.id||"Xpod account",username:t,webId:e,loading:!1,source:"account"}}async function resolveAuthenticatedAvatarUrl(n,e){try{const t=await n(e);if(!t.ok)return e;const i=await t.blob();return URL.createObjectURL(i)}catch{return e}}function normalizedHttpUrl(n){if(n)try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"?e.href:void 0}catch{return}}function usernameFromWebId$1(n){if(n)try{const e=new URL(n);return e.pathname.split("/").filter(Boolean).at(0)||e.hostname}catch{return}}const crypto$1=crypto,isCryptoKey=n=>n instanceof CryptoKey,encoder=new TextEncoder,decoder=new TextDecoder;function concat(...n){const e=n.reduce((s,{length:o})=>s+o,0),t=new Uint8Array(e);let i=0;for(const s of n)t.set(s,i),i+=s.length;return t}const encodeBase64=n=>{let e=n;typeof e=="string"&&(e=encoder.encode(e));const t=32768,i=[];for(let s=0;s<e.length;s+=t)i.push(String.fromCharCode.apply(null,e.subarray(s,s+t)));return btoa(i.join(""))},encode=n=>encodeBase64(n).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),decodeBase64=n=>{const e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);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,i="unspecified",s="unspecified"){super(e,{cause:{claim:i,reason:s,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=i,this.reason=s,this.payload=t}}JWTClaimValidationFailed.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class JWTExpired extends JOSEError{constructor(e,t,i="unspecified",s="unspecified"){super(e,{cause:{claim:i,reason:s,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=i,this.reason=s,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 i=e.pop();t+=`one of ${e.join(", ")}, or ${i}.`}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 i=parseInt(e.slice(2),10);if(getHashLength(n.algorithm.hash)!==i)throw unusable(`SHA-${i}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!isAlgorithm(n.algorithm,"RSASSA-PKCS1-v1_5"))throw unusable("RSASSA-PKCS1-v1_5");const i=parseInt(e.slice(2),10);if(getHashLength(n.algorithm.hash)!==i)throw unusable(`SHA-${i}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!isAlgorithm(n.algorithm,"RSA-PSS"))throw unusable("RSA-PSS");const i=parseInt(e.slice(2),10);if(getHashLength(n.algorithm.hash)!==i)throw unusable(`SHA-${i}`,"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 i=getNamedCurve(e);if(n.algorithm.namedCurve!==i)throw unusable(i,"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 i=t.pop();n+=`one of type ${t.join(", ")}, or ${i}.`}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 i of e){const s=Object.keys(i);if(!t||t.size===0){t=new Set(s);continue}for(const o of s){if(t.has(o))return!1;t.add(o)}}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),i=[e,n.ext??!1,n.key_ops??t],s={...n};return delete s.alg,delete s.use,crypto$1.subtle.importKey("jwk",s,...i)},exportKeyValue=n=>decode(n);let privCache,pubCache;const isKeyObject=n=>n?.[Symbol.toStringTag]==="KeyObject",importAndCache=async(n,e,t,i,s=!1)=>{let o=n.get(e);if(o?.[i])return o[i];const l=await parse({...t,alg:i});return s&&Object.freeze(e),o?o[i]=l:n.set(e,{[i]:l}),l},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,i)=>{if(!(e instanceof Uint8Array)){if(i&&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",i?"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,i)=>{if(i&&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,i?"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,i){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?symmetricTypeCheck(e,t,i,n):asymmetricTypeCheck(e,t,i,n)}checkKeyType.bind(void 0,!1);const checkKeyTypeWithJwk=checkKeyType.bind(void 0,!0);function validateCrit(n,e,t,i,s){if(s.crit!==void 0&&i?.crit===void 0)throw new n('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||i.crit===void 0)return new Set;if(!Array.isArray(i.crit)||i.crit.length===0||i.crit.some(l=>typeof l!="string"||l.length===0))throw new n('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;t!==void 0?o=new Map([...Object.entries(t),...e.entries()]):o=e;for(const l of i.crit){if(!o.has(l))throw new JOSENotSupported(`Extension Header Parameter "${l}" is not recognized`);if(s[l]===void 0)throw new n(`Extension Header Parameter "${l}" is missing`);if(o.get(l)&&i[l]===void 0)throw new n(`Extension Header Parameter "${l}" MUST be integrity protected`)}return new Set(i.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(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:i,use:s,...o}=await crypto$1.subtle.exportKey("jwk",n);return o};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,i)=>{const s=await getCryptoKey(n,e,"verify");checkKeyLength(n,s);const o=subtleDsa(n,s.algorithm);try{return await crypto$1.subtle.verify(o,s,t,i)}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 i={};if(n.protected)try{const E=decode(n.protected);i=JSON.parse(decoder.decode(E))}catch{throw new JWSInvalid("JWS Protected Header is invalid")}if(!isDisjoint(i,n.header))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...i,...n.header},o=validateCrit(JWSInvalid,new Map([["b64",!0]]),t?.crit,i,s);let l=!0;if(o.has("b64")&&(l=i.b64,typeof l!="boolean"))throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:u}=s;if(typeof u!="string"||!u)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');const h=t&&validateAlgorithms("algorithms",t.algorithms);if(h&&!h.has(u))throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(l){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 d=!1;typeof e=="function"?(e=await e(i,n),d=!0,checkKeyTypeWithJwk(u,e,"verify"),isJWK(e)&&(e=await importJWK(e,u))):checkKeyTypeWithJwk(u,e,"verify");const p=concat(encoder.encode(n.protected??""),encoder.encode("."),typeof n.payload=="string"?encoder.encode(n.payload):n.payload);let g;try{g=decode(n.signature)}catch{throw new JWSInvalid("Failed to base64url decode the signature")}if(!await verify(u,e,g,p))throw new JWSSignatureVerificationFailed;let v;if(l)try{v=decode(n.payload)}catch{throw new JWSInvalid("Failed to base64url decode the payload")}else typeof n.payload=="string"?v=encoder.encode(n.payload):v=n.payload;const S={payload:v};return n.protected!==void 0&&(S.protectedHeader=i),n.header!==void 0&&(S.unprotectedHeader=n.header),d?{...S,key:e}:S}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:i,1:s,2:o,length:l}=n.split(".");if(l!==3)throw new JWSInvalid("Invalid Compact JWS");const u=await flattenedVerify({payload:s,protected:i,signature:o},e,t),h={payload:u.payload,protectedHeader:u.protectedHeader};return typeof e=="function"?{...h,key:u.key}:h}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]),i=e[3].toLowerCase();let s;switch(i){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(t);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(t*minute);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(t*hour);break;case"day":case"days":case"d":s=Math.round(t*day);break;case"week":case"weeks":case"w":s=Math.round(t*week);break;default:s=Math.round(t*year);break}return e[1]==="-"||e[4]==="ago"?-s:s},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 i;try{i=JSON.parse(decoder.decode(e))}catch{}if(!isObject(i))throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");const{typ:s}=t;if(s&&(typeof n.typ!="string"||normalizeTyp(n.typ)!==normalizeTyp(s)))throw new JWTClaimValidationFailed('unexpected "typ" JWT header value',i,"typ","check_failed");const{requiredClaims:o=[],issuer:l,subject:u,audience:h,maxTokenAge:d}=t,p=[...o];d!==void 0&&p.push("iat"),h!==void 0&&p.push("aud"),u!==void 0&&p.push("sub"),l!==void 0&&p.push("iss");for(const S of new Set(p.reverse()))if(!(S in i))throw new JWTClaimValidationFailed(`missing required "${S}" claim`,i,S,"missing");if(l&&!(Array.isArray(l)?l:[l]).includes(i.iss))throw new JWTClaimValidationFailed('unexpected "iss" claim value',i,"iss","check_failed");if(u&&i.sub!==u)throw new JWTClaimValidationFailed('unexpected "sub" claim value',i,"sub","check_failed");if(h&&!checkAudiencePresence(i.aud,typeof h=="string"?[h]:h))throw new JWTClaimValidationFailed('unexpected "aud" claim value',i,"aud","check_failed");let g;switch(typeof t.clockTolerance){case"string":g=secs(t.clockTolerance);break;case"number":g=t.clockTolerance;break;case"undefined":g=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=t,v=epoch(m||new Date);if((i.iat!==void 0||d)&&typeof i.iat!="number")throw new JWTClaimValidationFailed('"iat" claim must be a number',i,"iat","invalid");if(i.nbf!==void 0){if(typeof i.nbf!="number")throw new JWTClaimValidationFailed('"nbf" claim must be a number',i,"nbf","invalid");if(i.nbf>v+g)throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed',i,"nbf","check_failed")}if(i.exp!==void 0){if(typeof i.exp!="number")throw new JWTClaimValidationFailed('"exp" claim must be a number',i,"exp","invalid");if(i.exp<=v-g)throw new JWTExpired('"exp" claim timestamp check failed',i,"exp","check_failed")}if(d){const S=v-i.iat,E=typeof d=="number"?d:secs(d);if(S-g>E)throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)',i,"iat","check_failed");if(S<0-g)throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',i,"iat","check_failed")}return i};async function jwtVerify(n,e,t){const i=await compactVerify(n,e,t);if(i.protectedHeader.crit?.includes("b64")&&i.protectedHeader.b64===!1)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");const o={payload:jwtPayload(i.protectedHeader,i.payload,t),protectedHeader:i.protectedHeader};return typeof e=="function"?{...o,key:i.key}:o}const sign=async(n,e,t)=>{const i=await getCryptoKey(n,e,"sign");checkKeyLength(n,i);const s=await crypto$1.subtle.sign(subtleDsa(n,i.algorithm),i,t);return new Uint8Array(s)};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 i={...this._protectedHeader,...this._unprotectedHeader},s=validateCrit(JWSInvalid,new Map([["b64",!0]]),t?.crit,this._protectedHeader,i);let o=!0;if(s.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:l}=i;if(typeof l!="string"||!l)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');checkKeyTypeWithJwk(l,e,"sign");let u=this._payload;o&&(u=encoder.encode(encode(u)));let h;this._protectedHeader?h=encoder.encode(encode(JSON.stringify(this._protectedHeader))):h=encoder.encode("");const d=concat(h,encoder.encode("."),u),p=await sign(l,e,d),g={signature:encode(p),payload:""};return o&&(g.payload=decoder.decode(u)),this._unprotectedHeader&&(g.header=this._unprotectedHeader),this._protectedHeader&&(g.protected=decoder.decode(h)),g}}class CompactSign{constructor(e){this._flattened=new FlattenedSign(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const i=await this._flattened.sign(e,t);if(i.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${i.protected}.${i.payload}.${i.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 i=new CompactSign(encoder.encode(JSON.stringify(this._payload)));if(i.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 i.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:i,kid:s}={...e,...t?.header},o=getKtyFromAlg(i),l=this._jwks.keys.filter(d=>{let p=o===d.kty;if(p&&typeof s=="string"&&(p=s===d.kid),p&&typeof d.alg=="string"&&(p=i===d.alg),p&&typeof d.use=="string"&&(p=d.use==="sig"),p&&Array.isArray(d.key_ops)&&(p=d.key_ops.includes("verify")),p)switch(i){case"ES256":p=d.crv==="P-256";break;case"ES256K":p=d.crv==="secp256k1";break;case"ES384":p=d.crv==="P-384";break;case"ES512":p=d.crv==="P-521";break;case"Ed25519":p=d.crv==="Ed25519";break;case"EdDSA":p=d.crv==="Ed25519"||d.crv==="Ed448";break}return p}),{0:u,length:h}=l;if(h===0)throw new JWKSNoMatchingKey;if(h!==1){const d=new JWKSMultipleMatchingKeys,{_cached:p}=this;throw d[Symbol.asyncIterator]=async function*(){for(const g of l)try{yield await importWithAlgCache(p,g,i)}catch{}},d}return importWithAlgCache(this._cached,u,i)}}async function importWithAlgCache(n,e,t){const i=n.get(e)||n.set(e,{}).get(e);if(i[t]===void 0){const s=await importJWK({...e,ext:!0},t);if(s instanceof Uint8Array||s.type!=="public")throw new JWKSInvalid("JSON Web Key Set members must be public keys");i[t]=s}return i[t]}function createLocalJWKSet(n){const e=new LocalJWKSet(n),t=async(i,s)=>e.getKey(i,s);return Object.defineProperties(t,{jwks:{value:()=>clone(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),t}const fetchJwks=async(n,e,t)=>{let i,s,o=!1;typeof AbortController=="function"&&(i=new AbortController,s=setTimeout(()=>{o=!0,i.abort()},e));const l=await fetch(n.href,{signal:i?i.signal:void 0,redirect:"manual",headers:t.headers}).catch(u=>{throw o?new JWKSTimeout:u});if(s!==void 0&&clearTimeout(s),l.status!==200)throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await l.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(i){if(i instanceof JWKSNoMatchingKey&&this.coolingDown()===!1)return await this.reload(),this._local(e,t);throw i}}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),i=async(s,o)=>t.getKey(s,o);return Object.defineProperties(i,{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}}),i}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,i;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)},i=["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)},i=["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)},i=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":t={name:"ECDSA",namedCurve:"P-256"},i=["sign","verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},i=["sign","verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},i=["sign","verify"];break;case"Ed25519":t={name:"Ed25519"},i=["sign","verify"];break;case"EdDSA":{i=["sign","verify"];const s="Ed25519";switch(s){case"Ed25519":case"Ed448":t={name:s};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":{i=["deriveKey","deriveBits"];const s="P-256";switch(s){case"P-256":case"P-384":case"P-521":{t={name:"ECDH",namedCurve:s};break}case"X25519":case"X448":t={name:s};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,i)}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(i=>i.canHandle(...e)));for(let i=0;i<t.length;i+=1)if(t[i])return this.handleables[i];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(i=>{try{return JSON.stringify(i)}catch{return i.toString()}}).join(", ")}`)}}async function getWebidFromTokenPayload(n,e,t,i){let s,o;try{const{payload:l}=await jwtVerify(n,createRemoteJWKSet(new URL(e)),{issuer:t,audience:i});s=l}catch(l){throw new Error(`Token verification failed: ${l.stack}`)}if(typeof s.azp=="string"&&(o=s.azp),typeof s.webid=="string")return{webId:s.webid,clientId:o};if(typeof s.sub!="string")throw new Error(`The token ${JSON.stringify(s)} is invalid: it has no 'webid' claim and no 'sub' claim.`);try{return new URL(s.sub),{webId:s.sub,clientId:o}}catch(l){throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${s.sub}] is invalid as a URL - error [${l}].`)}}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"),i=e.hash==="";return t&&i}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:i,targetUrl:s}){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:i,issuer:e.issuer.toString(),redirectUrl:e.redirectUrl,dpop:(!!e.dpop).toString(),keepAlive:booleanWithFallback(e.keepAlive,!0).toString()})]),this.redirector.redirect(s,{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 i of this.handlers)await i.canHandle(e,t)&&await i.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:i}){const s=new URL(n);return e!==void 0&&s.searchParams.append("id_token_hint",e),t!==void 0&&(s.searchParams.append("post_logout_redirect_uri",t),i!==void 0&&s.searchParams.append("state",i)),s.toString()}function maybeBuildRpInitiatedLogout({endSessionEndpoint:n,idTokenHint:e}){if(n!==void 0)return function({state:i,postLogoutUrl:s}){return getEndSessionUrl({endSessionEndpoint:n,idTokenHint:e,state:i,postLogoutRedirectUri:s})}}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,i){let s;if(isSolidOidcClient(n,e))s={clientId:n.clientId,clientName:n.clientName,clientType:"solid-oidc"};else if(isStaticClient(n))s={clientId:n.clientId,clientSecret:n.clientSecret,clientName:n.clientName,clientType:"static"};else return i.getClient({sessionId:n.sessionId,clientName:n.clientName,redirectUrl:n.redirectUrl},e);const o={clientId:s.clientId,clientType:s.clientType};return s.clientType==="static"&&(o.clientSecret=s.clientSecret),s.clientName&&(o.clientName=s.clientName),await t.setForUser(n.sessionId,o),s}const boundFetch=(n,e)=>fetch(n,e);let ClientAuthentication$1=class{loginHandler;redirectHandler;logoutHandler;sessionInfoManager;issuerConfigFetcher;boundLogout;constructor(e,t,i,s,o){this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=i,this.sessionInfoManager=s,this.issuerConfigFetcher=o,this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=i,this.sessionInfoManager=s,this.issuerConfigFetcher=o}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[i,s,o,l,u]=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 h=await t.fetchConfig(i);return{codeVerifier:s,redirectUrl:o,issuerConfig:h,dpop:l==="true",keepAlive:typeof u=="string"?u==="true":!0}}catch(i){throw new Error(`Failed to retrieve OIDC context from storage associated with session [${n}]: ${i}`)}}async function saveSessionInfoToStorage(n,e,t,i,s,o,l,u){t!==void 0&&await n.setForUser(e,{webId:t},{secure:l}),i!==void 0&&await n.setForUser(e,{clientId:i},{secure:l}),await n.setForUser(e,{isLoggedIn:s},{secure:l})}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 i=await(t?this.secureStorage:this.insecureStorage).get(this.getKey(e));if(i===void 0)return{};try{return JSON.parse(i)}catch{throw new Error(`Data for user [${e}] in [${t?"secure":"unsecure"}] storage is corrupted - expected valid JSON, but got: ${i}`)}}async setUserData(e,t,i){await(i?this.secureStorage:this.insecureStorage).set(this.getKey(e),JSON.stringify(t))}async get(e,t){const i=await(t?.secure?this.secureStorage:this.insecureStorage).get(e);if(i===void 0&&t?.errorIfNull)throw new Error(`[${e}] is not stored`);return i}async set(e,t,i){return(i?.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,i){const s=await this.getUserData(e,i?.secure);let o;if((!s||!s[t])&&(o=void 0),o=s[t],o===void 0&&i?.errorIfNull)throw new Error(`Field [${t}] for user [${e}] is not stored`);return o||void 0}async setForUser(e,t,i){let s;try{s=await this.getUserData(e,i?.secure)}catch{s={}}await this.setUserData(e,{...s,...t},i?.secure)}async deleteForUser(e,t,i){const s=await this.getUserData(e,i?.secure);delete s[t],await this.setUserData(e,s,i?.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,i){super(e),this.error=t,this.errorDescription=i}}function normalizeHTU(n){const e=new URL(n);return new URL(e.pathname,e.origin).toString()}async function createDpopHeader(n,e,t){return new SignJWT({htu:normalizeHTU(n),htm:e.toUpperCase(),jti:v4()}).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,i){const s=new Headers(i?.headers);return s.set("Authorization",`DPoP ${e}`),s.set("DPoP",await createDpopHeader(n,i?.method??"get",t)),{...i,headers:s}}async function buildAuthenticatedHeaders(n,e,t,i){if(t!==void 0)return buildDpopFetchOptions(n,e,t,i);const s=new Headers(i?.headers);return s.set("Authorization",`Bearer ${e}`),{...i,headers:s}}async function makeAuthenticatedRequest(n,e,t,i,s=fetch){return s(e,await buildAuthenticatedHeaders(e.toString(),n,i,t))}async function refreshAccessToken(n,e,t){const i=await n.tokenRefresher.refresh(n.sessionId,n.refreshToken,e);return t?.emit(EVENTS.SESSION_EXTENDED,i.expiresIn??DEFAULT_EXPIRATION_TIME_SECONDS),{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.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,i,s=0;const o=6e4,l=e?.refreshOptions;if(l!==void 0){const u=async()=>{try{const{accessToken:h,refreshToken:d,expiresIn:p}=await refreshAccessToken(l,e.dpopKey,e.eventEmitter);t=h,s=0,d!==void 0&&(l.refreshToken=d),clearTimeout(i),i=setTimeout(u,computeRefreshDelay(p)*1e3),e.eventEmitter?.emit(EVENTS.TIMEOUT_SET,i)}catch(h){const d=h instanceof OidcProviderError&&h.error!=="server_error"&&h.error!=="temporarily_unavailable";d&&(e?.eventEmitter?.emit(EVENTS.ERROR,h.error,h.errorDescription),e?.eventEmitter?.emit(EVENTS.SESSION_EXPIRED));const p=h instanceof InvalidResponseError&&h.missingFields.includes("access_token");if(p&&e?.eventEmitter?.emit(EVENTS.SESSION_EXPIRED),!d&&!p){const g=Math.min(1e3*2**s,o);s+=1,clearTimeout(i),i=setTimeout(u,g),e?.eventEmitter?.emit(EVENTS.TIMEOUT_SET,i)}}};i=setTimeout(u,computeRefreshDelay(e.expiresIn)*1e3),e.eventEmitter?.emit(EVENTS.TIMEOUT_SET,i)}else if(e!==void 0&&e.eventEmitter!==void 0){const u=setTimeout(()=>{e.eventEmitter.emit(EVENTS.SESSION_EXPIRED)},computeRefreshDelay(e.expiresIn)*1e3);e.eventEmitter.emit(EVENTS.TIMEOUT_SET,u)}return async(u,h)=>{let d=await makeAuthenticatedRequest(t,u,h,e?.dpopKey,e?.fetch);const p=!d.ok&&!isExpectedAuthError(d.status);return d.ok||p||d.url!==u&&e?.dpopKey!==void 0&&(d=await makeAuthenticatedRequest(t,d.url,h,e.dpopKey,e.fetch)),d}}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(i,s){n.exports=s()})(oidcClient_min,(function(){return(function(t){var i={};function s(o){if(i[o])return i[o].exports;var l=i[o]={i:o,l:!1,exports:{}};return t[o].call(l.exports,l,l.exports,s),l.l=!0,l.exports}return s.m=t,s.c=i,s.d=function(o,l,u){s.o(o,l)||Object.defineProperty(o,l,{enumerable:!0,get:u})},s.r=function(o){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(o,"__esModule",{value:!0})},s.t=function(o,l){if(1&l&&(o=s(o)),8&l||4&l&&typeof o=="object"&&o&&o.__esModule)return o;var u=Object.create(null);if(s.r(u),Object.defineProperty(u,"default",{enumerable:!0,value:o}),2&l&&typeof o!="string")for(var h in o)s.d(u,h,(function(d){return o[d]}).bind(null,h));return u},s.n=function(o){var l=o&&o.__esModule?function(){return o.default}:function(){return o};return s.d(l,"a",l),l},s.o=function(o,l){return Object.prototype.hasOwnProperty.call(o,l)},s.p="",s(s.s=22)})([function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0});var o=(function(){function d(p,g){for(var m=0;m<g.length;m++){var v=g[m];v.enumerable=v.enumerable||!1,v.configurable=!0,"value"in v&&(v.writable=!0),Object.defineProperty(p,v.key,v)}}return function(p,g,m){return g&&d(p.prototype,g),m&&d(p,m),p}})(),l={debug:function(){},info:function(){},warn:function(){},error:function(){}},u=void 0,h=void 0;(i.Log=(function(){function d(){(function(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")})(this,d)}return d.reset=function(){h=3,u=l},d.debug=function(){if(h>=4){for(var g=arguments.length,m=Array(g),v=0;v<g;v++)m[v]=arguments[v];u.debug.apply(u,Array.from(m))}},d.info=function(){if(h>=3){for(var g=arguments.length,m=Array(g),v=0;v<g;v++)m[v]=arguments[v];u.info.apply(u,Array.from(m))}},d.warn=function(){if(h>=2){for(var g=arguments.length,m=Array(g),v=0;v<g;v++)m[v]=arguments[v];u.warn.apply(u,Array.from(m))}},d.error=function(){if(h>=1){for(var g=arguments.length,m=Array(g),v=0;v<g;v++)m[v]=arguments[v];u.error.apply(u,Array.from(m))}},o(d,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 h},set:function(g){if(!(0<=g&&g<=4))throw new Error("Invalid log level");h=g}},{key:"logger",get:function(){return u},set:function(g){if(!g.debug&&g.info&&(g.debug=g.info),!(g.debug&&g.info&&g.warn&&g.error))throw new Error("Invalid logger");u=g}}]),d})()).reset()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0});var o=(function(){function d(p,g){for(var m=0;m<g.length;m++){var v=g[m];v.enumerable=v.enumerable||!1,v.configurable=!0,"value"in v&&(v.writable=!0),Object.defineProperty(p,v.key,v)}}return function(p,g,m){return g&&d(p.prototype,g),m&&d(p,m),p}})(),l={setInterval:(function(d){function p(g,m){return d.apply(this,arguments)}return p.toString=function(){return d.toString()},p})((function(d,p){return setInterval(d,p)})),clearInterval:(function(d){function p(g){return d.apply(this,arguments)}return p.toString=function(){return d.toString()},p})((function(d){return clearInterval(d)}))},u=!1,h=null;i.Global=(function(){function d(){(function(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")})(this,d)}return d._testing=function(){u=!0},d.setXMLHttpRequest=function(g){h=g},o(d,null,[{key:"location",get:function(){if(!u)return location}},{key:"localStorage",get:function(){if(!u&&typeof window<"u")return localStorage}},{key:"sessionStorage",get:function(){if(!u&&typeof window<"u")return sessionStorage}},{key:"XMLHttpRequest",get:function(){if(!u&&typeof window<"u")return h||XMLHttpRequest}},{key:"timer",get:function(){if(!u)return l}}]),d})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.MetadataService=void 0;var o=(function(){function p(g,m){for(var v=0;v<m.length;v++){var S=m[v];S.enumerable=S.enumerable||!1,S.configurable=!0,"value"in S&&(S.writable=!0),Object.defineProperty(g,S.key,S)}}return function(g,m,v){return m&&p(g.prototype,m),v&&p(g,v),g}})(),l=s(0),u=s(7);function h(p,g){if(!(p instanceof g))throw new TypeError("Cannot call a class as a function")}var d=".well-known/openid-configuration";i.MetadataService=(function(){function p(g){var m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u.JsonService;if(h(this,p),!g)throw l.Log.error("MetadataService: No settings passed to MetadataService"),new Error("settings");this._settings=g,this._jsonService=new m(["application/jwk-set+json"])}return p.prototype.resetSigningKeys=function(){this._settings=this._settings||{},this._settings.signingKeys=void 0},p.prototype.getMetadata=function(){var m=this;return this._settings.metadata?(l.Log.debug("MetadataService.getMetadata: Returning metadata from settings"),Promise.resolve(this._settings.metadata)):this.metadataUrl?(l.Log.debug("MetadataService.getMetadata: getting metadata from",this.metadataUrl),this._jsonService.getJson(this.metadataUrl).then((function(v){l.Log.debug("MetadataService.getMetadata: json received");var S=m._settings.metadataSeed||{};return m._settings.metadata=Object.assign({},S,v),m._settings.metadata}))):(l.Log.error("MetadataService.getMetadata: No authority or metadataUrl configured on settings"),Promise.reject(new Error("No authority or metadataUrl configured on settings")))},p.prototype.getIssuer=function(){return this._getMetadataProperty("issuer")},p.prototype.getAuthorizationEndpoint=function(){return this._getMetadataProperty("authorization_endpoint")},p.prototype.getUserInfoEndpoint=function(){return this._getMetadataProperty("userinfo_endpoint")},p.prototype.getTokenEndpoint=function(){var m=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return this._getMetadataProperty("token_endpoint",m)},p.prototype.getCheckSessionIframe=function(){return this._getMetadataProperty("check_session_iframe",!0)},p.prototype.getEndSessionEndpoint=function(){return this._getMetadataProperty("end_session_endpoint",!0)},p.prototype.getRevocationEndpoint=function(){return this._getMetadataProperty("revocation_endpoint",!0)},p.prototype.getKeysEndpoint=function(){return this._getMetadataProperty("jwks_uri",!0)},p.prototype._getMetadataProperty=function(m){var v=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return l.Log.debug("MetadataService.getMetadataProperty for: "+m),this.getMetadata().then((function(S){if(l.Log.debug("MetadataService.getMetadataProperty: metadata recieved"),S[m]===void 0){if(v===!0)return void l.Log.warn("MetadataService.getMetadataProperty: Metadata does not contain optional property "+m);throw l.Log.error("MetadataService.getMetadataProperty: Metadata does not contain property "+m),new Error("Metadata does not contain property "+m)}return S[m]}))},p.prototype.getSigningKeys=function(){var m=this;return this._settings.signingKeys?(l.Log.debug("MetadataService.getSigningKeys: Returning signingKeys from settings"),Promise.resolve(this._settings.signingKeys)):this._getMetadataProperty("jwks_uri").then((function(v){return l.Log.debug("MetadataService.getSigningKeys: jwks_uri received",v),m._jsonService.getJson(v).then((function(S){if(l.Log.debug("MetadataService.getSigningKeys: key set received",S),!S.keys)throw l.Log.error("MetadataService.getSigningKeys: Missing keys on keyset"),new Error("Missing keys on keyset");return m._settings.signingKeys=S.keys,m._settings.signingKeys}))}))},o(p,[{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(d)<0&&(this._metadataUrl[this._metadataUrl.length-1]!=="/"&&(this._metadataUrl+="/"),this._metadataUrl+=d))),this._metadataUrl}}]),p})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UrlUtility=void 0;var o=s(0),l=s(1);i.UrlUtility=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.addQueryParam=function(d,p,g){return d.indexOf("?")<0&&(d+="?"),d[d.length-1]!=="?"&&(d+="&"),d+=encodeURIComponent(p),d+="=",d+=encodeURIComponent(g)},u.parseUrlFragment=function(d){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#",g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:l.Global;typeof d!="string"&&(d=g.location.href);var m=d.lastIndexOf(p);m>=0&&(d=d.substr(m+1)),p==="?"&&(m=d.indexOf("#"))>=0&&(d=d.substr(0,m));for(var v,S={},E=/([^&=]+)=([^&]*)/g,x=0;v=E.exec(d);)if(S[decodeURIComponent(v[1])]=decodeURIComponent(v[2].replace(/\+/g," ")),x++>50)return o.Log.error("UrlUtility.parseUrlFragment: response exceeded expected number of parameters",d),{error:"Response exceeded expected number of parameters"};for(var A in S)return S;return{}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.JoseUtil=void 0;var o=s(26),l=(function(h){return h&&h.__esModule?h:{default:h}})(s(33));i.JoseUtil=(0,l.default)({jws:o.jws,KeyUtil:o.KeyUtil,X509:o.X509,crypto:o.crypto,hextob64u:o.hextob64u,b64tohex:o.b64tohex,AllowedSigningAlgs:o.AllowedSigningAlgs})},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.OidcClientSettings=void 0;var o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(A){return typeof A}:function(A){return A&&typeof Symbol=="function"&&A.constructor===Symbol&&A!==Symbol.prototype?"symbol":typeof A},l=(function(){function A(C,T){for(var F=0;F<T.length;F++){var P=T[F];P.enumerable=P.enumerable||!1,P.configurable=!0,"value"in P&&(P.writable=!0),Object.defineProperty(C,P.key,P)}}return function(C,T,F){return T&&A(C.prototype,T),F&&A(C,F),C}})(),u=s(0),h=s(23),d=s(6),p=s(24),g=s(2);function m(A,C){if(!(A instanceof C))throw new TypeError("Cannot call a class as a function")}var v=".well-known/openid-configuration",S="id_token",E="openid",x="client_secret_post";i.OidcClientSettings=(function(){function A(){var C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},T=C.authority,F=C.metadataUrl,P=C.metadata,q=C.signingKeys,O=C.metadataSeed,G=C.client_id,fe=C.client_secret,M=C.response_type,ee=M===void 0?S:M,Se=C.scope,re=Se===void 0?E:Se,Ae=C.redirect_uri,ke=C.post_logout_redirect_uri,he=C.client_authentication,Oe=he===void 0?x:he,ce=C.prompt,Ue=C.display,$=C.max_age,W=C.ui_locales,de=C.acr_values,te=C.resource,Te=C.response_mode,je=C.filterProtocolClaims,He=je===void 0||je,We=C.loadUserInfo,me=We===void 0||We,ge=C.staleStateAge,Be=ge===void 0?900:ge,ie=C.clockSkew,B=ie===void 0?300:ie,N=C.clockService,k=N===void 0?new h.ClockService:N,H=C.userInfoJwtIssuer,ne=H===void 0?"OP":H,le=C.mergeClaims,Ee=le!==void 0&&le,J=C.stateStore,_e=J===void 0?new d.WebStorageStateStore:J,Ie=C.ResponseValidatorCtor,ye=Ie===void 0?p.ResponseValidator:Ie,at=C.MetadataServiceCtor,ht=at===void 0?g.MetadataService:at,Je=C.extraQueryParams,gt=Je===void 0?{}:Je,Y=C.extraTokenParams,U=Y===void 0?{}:Y;m(this,A),this._authority=T,this._metadataUrl=F,this._metadata=P,this._metadataSeed=O,this._signingKeys=q,this._client_id=G,this._client_secret=fe,this._response_type=ee,this._scope=re,this._redirect_uri=Ae,this._post_logout_redirect_uri=ke,this._client_authentication=Oe,this._prompt=ce,this._display=Ue,this._max_age=$,this._ui_locales=W,this._acr_values=de,this._resource=te,this._response_mode=Te,this._filterProtocolClaims=!!He,this._loadUserInfo=!!me,this._staleStateAge=Be,this._clockSkew=B,this._clockService=k,this._userInfoJwtIssuer=ne,this._mergeClaims=!!Ee,this._stateStore=_e,this._validator=new ye(this),this._metadataService=new ht(this),this._extraQueryParams=(gt===void 0?"undefined":o(gt))==="object"?gt:{},this._extraTokenParams=(U===void 0?"undefined":o(U))==="object"?U:{}}return A.prototype.getEpochTime=function(){return this._clockService.getEpochTime()},l(A,[{key:"client_id",get:function(){return this._client_id},set:function(T){if(this._client_id)throw u.Log.error("OidcClientSettings.set_client_id: client_id has already been assigned."),new Error("client_id has already been assigned.");this._client_id=T}},{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(T){if(this._authority)throw u.Log.error("OidcClientSettings.set_authority: authority has already been assigned."),new Error("authority has already been assigned.");this._authority=T}},{key:"metadataUrl",get:function(){return this._metadataUrl||(this._metadataUrl=this.authority,this._metadataUrl&&this._metadataUrl.indexOf(v)<0&&(this._metadataUrl[this._metadataUrl.length-1]!=="/"&&(this._metadataUrl+="/"),this._metadataUrl+=v)),this._metadataUrl}},{key:"metadata",get:function(){return this._metadata},set:function(T){this._metadata=T}},{key:"metadataSeed",get:function(){return this._metadataSeed},set:function(T){this._metadataSeed=T}},{key:"signingKeys",get:function(){return this._signingKeys},set:function(T){this._signingKeys=T}},{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(T){(T===void 0?"undefined":o(T))==="object"?this._extraQueryParams=T:this._extraQueryParams={}}},{key:"extraTokenParams",get:function(){return this._extraTokenParams},set:function(T){(T===void 0?"undefined":o(T))==="object"?this._extraTokenParams=T:this._extraTokenParams={}}}]),A})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.WebStorageStateStore=void 0;var o=s(0),l=s(1);function u(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")}i.WebStorageStateStore=(function(){function h(){var d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},p=d.prefix,g=p===void 0?"oidc.":p,m=d.store,v=m===void 0?l.Global.localStorage:m;u(this,h),this._store=v,this._prefix=g}return h.prototype.set=function(p,g){return o.Log.debug("WebStorageStateStore.set",p),p=this._prefix+p,this._store.setItem(p,g),Promise.resolve()},h.prototype.get=function(p){o.Log.debug("WebStorageStateStore.get",p),p=this._prefix+p;var g=this._store.getItem(p);return Promise.resolve(g)},h.prototype.remove=function(p){o.Log.debug("WebStorageStateStore.remove",p),p=this._prefix+p;var g=this._store.getItem(p);return this._store.removeItem(p),Promise.resolve(g)},h.prototype.getAllKeys=function(){o.Log.debug("WebStorageStateStore.getAllKeys");for(var p=[],g=0;g<this._store.length;g++){var m=this._store.key(g);m.indexOf(this._prefix)===0&&p.push(m.substr(this._prefix.length))}return Promise.resolve(p)},h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.JsonService=void 0;var o=s(0),l=s(1);function u(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")}i.JsonService=(function(){function h(){var d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l.Global.XMLHttpRequest,g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;u(this,h),d&&Array.isArray(d)?this._contentTypes=d.slice():this._contentTypes=[],this._contentTypes.push("application/json"),g&&this._contentTypes.push("application/jwt"),this._XMLHttpRequest=p,this._jwtHandler=g}return h.prototype.getJson=function(p,g){var m=this;if(!p)throw o.Log.error("JsonService.getJson: No url passed"),new Error("url");return o.Log.debug("JsonService.getJson, url: ",p),new Promise((function(v,S){var E=new m._XMLHttpRequest;E.open("GET",p);var x=m._contentTypes,A=m._jwtHandler;E.onload=function(){if(o.Log.debug("JsonService.getJson: HTTP response received, status",E.status),E.status===200){var C=E.getResponseHeader("Content-Type");if(C){var T=x.find((function(F){if(C.startsWith(F))return!0}));if(T=="application/jwt")return void A(E).then(v,S);if(T)try{return void v(JSON.parse(E.responseText))}catch(F){return o.Log.error("JsonService.getJson: Error parsing JSON response",F.message),void S(F)}}S(Error("Invalid response Content-Type: "+C+", from URL: "+p))}else S(Error(E.statusText+" ("+E.status+")"))},E.onerror=function(){o.Log.error("JsonService.getJson: network error"),S(Error("Network Error"))},g&&(o.Log.debug("JsonService.getJson: token passed, setting Authorization header"),E.setRequestHeader("Authorization","Bearer "+g)),E.send()}))},h.prototype.postForm=function(p,g,m){var v=this;if(!p)throw o.Log.error("JsonService.postForm: No url passed"),new Error("url");return o.Log.debug("JsonService.postForm, url: ",p),new Promise((function(S,E){var x=new v._XMLHttpRequest;x.open("POST",p);var A=v._contentTypes;x.onload=function(){if(o.Log.debug("JsonService.postForm: HTTP response received, status",x.status),x.status!==200){if(x.status===400&&(q=x.getResponseHeader("Content-Type"))&&A.find((function(O){if(q.startsWith(O))return!0})))try{var P=JSON.parse(x.responseText);if(P&&P.error)return o.Log.error("JsonService.postForm: Error from server: ",P.error),void E(new Error(P.error))}catch(O){return o.Log.error("JsonService.postForm: Error parsing JSON response",O.message),void E(O)}E(Error(x.statusText+" ("+x.status+")"))}else{var q;if((q=x.getResponseHeader("Content-Type"))&&A.find((function(O){if(q.startsWith(O))return!0})))try{return void S(JSON.parse(x.responseText))}catch(O){return o.Log.error("JsonService.postForm: Error parsing JSON response",O.message),void E(O)}E(Error("Invalid response Content-Type: "+q+", from URL: "+p))}},x.onerror=function(){o.Log.error("JsonService.postForm: network error"),E(Error("Network Error"))};var C="";for(var T in g){var F=g[T];F&&(C.length>0&&(C+="&"),C+=encodeURIComponent(T),C+="=",C+=encodeURIComponent(F))}x.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),m!==void 0&&x.setRequestHeader("Authorization","Basic "+btoa(m)),x.send(C)}))},h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SigninRequest=void 0;var o=s(0),l=s(3),u=s(13);i.SigninRequest=(function(){function h(d){var p=d.url,g=d.client_id,m=d.redirect_uri,v=d.response_type,S=d.scope,E=d.authority,x=d.data,A=d.prompt,C=d.display,T=d.max_age,F=d.ui_locales,P=d.id_token_hint,q=d.login_hint,O=d.acr_values,G=d.resource,fe=d.response_mode,M=d.request,ee=d.request_uri,Se=d.extraQueryParams,re=d.request_type,Ae=d.client_secret,ke=d.extraTokenParams,he=d.skipUserInfo;if((function(te,Te){if(!(te instanceof Te))throw new TypeError("Cannot call a class as a function")})(this,h),!p)throw o.Log.error("SigninRequest.ctor: No url passed"),new Error("url");if(!g)throw o.Log.error("SigninRequest.ctor: No client_id passed"),new Error("client_id");if(!m)throw o.Log.error("SigninRequest.ctor: No redirect_uri passed"),new Error("redirect_uri");if(!v)throw o.Log.error("SigninRequest.ctor: No response_type passed"),new Error("response_type");if(!S)throw o.Log.error("SigninRequest.ctor: No scope passed"),new Error("scope");if(!E)throw o.Log.error("SigninRequest.ctor: No authority passed"),new Error("authority");var Oe=h.isOidc(v),ce=h.isCode(v);fe||(fe=h.isCode(v)?"query":null),this.state=new u.SigninState({nonce:Oe,data:x,client_id:g,authority:E,redirect_uri:m,code_verifier:ce,request_type:re,response_mode:fe,client_secret:Ae,scope:S,extraTokenParams:ke,skipUserInfo:he}),p=l.UrlUtility.addQueryParam(p,"client_id",g),p=l.UrlUtility.addQueryParam(p,"redirect_uri",m),p=l.UrlUtility.addQueryParam(p,"response_type",v),p=l.UrlUtility.addQueryParam(p,"scope",S),p=l.UrlUtility.addQueryParam(p,"state",this.state.id),Oe&&(p=l.UrlUtility.addQueryParam(p,"nonce",this.state.nonce)),ce&&(p=l.UrlUtility.addQueryParam(p,"code_challenge",this.state.code_challenge),p=l.UrlUtility.addQueryParam(p,"code_challenge_method","S256"));var Ue={prompt:A,display:C,max_age:T,ui_locales:F,id_token_hint:P,login_hint:q,acr_values:O,resource:G,request:M,request_uri:ee,response_mode:fe};for(var $ in Ue)Ue[$]&&(p=l.UrlUtility.addQueryParam(p,$,Ue[$]));for(var W in Se)p=l.UrlUtility.addQueryParam(p,W,Se[W]);this.url=p}return h.isOidc=function(p){return!!p.split(/\s+/g).filter((function(g){return g==="id_token"}))[0]},h.isOAuth=function(p){return!!p.split(/\s+/g).filter((function(g){return g==="token"}))[0]},h.isCode=function(p){return!!p.split(/\s+/g).filter((function(g){return g==="code"}))[0]},h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.State=void 0;var o=(function(){function d(p,g){for(var m=0;m<g.length;m++){var v=g[m];v.enumerable=v.enumerable||!1,v.configurable=!0,"value"in v&&(v.writable=!0),Object.defineProperty(p,v.key,v)}}return function(p,g,m){return g&&d(p.prototype,g),m&&d(p,m),p}})(),l=s(0),u=(function(p){return p&&p.__esModule?p:{default:p}})(s(14));function h(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")}i.State=(function(){function d(){var p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},g=p.id,m=p.data,v=p.created,S=p.request_type;h(this,d),this._id=g||(0,u.default)(),this._data=m,this._created=typeof v=="number"&&v>0?v:parseInt(Date.now()/1e3),this._request_type=S}return d.prototype.toStorageString=function(){return l.Log.debug("State.toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})},d.fromStorageString=function(g){return l.Log.debug("State.fromStorageString"),new d(JSON.parse(g))},d.clearStaleState=function(g,m){var v=Date.now()/1e3-m;return g.getAllKeys().then((function(S){l.Log.debug("State.clearStaleState: got keys",S);for(var E=[],x=function(F){var P=S[F];C=g.get(P).then((function(q){var O=!1;if(q)try{var G=d.fromStorageString(q);l.Log.debug("State.clearStaleState: got item from key: ",P,G.created),G.created<=v&&(O=!0)}catch(fe){l.Log.error("State.clearStaleState: Error parsing state for key",P,fe.message),O=!0}else l.Log.debug("State.clearStaleState: no item in storage for key: ",P),O=!0;if(O)return l.Log.debug("State.clearStaleState: removed item for key: ",P),g.remove(P)})),E.push(C)},A=0;A<S.length;A++){var C;x(A)}return l.Log.debug("State.clearStaleState: waiting on promise count:",E.length),Promise.all(E)}))},o(d,[{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}}]),d})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.OidcClient=void 0;var o=(function(){function x(A,C){for(var T=0;T<C.length;T++){var F=C[T];F.enumerable=F.enumerable||!1,F.configurable=!0,"value"in F&&(F.writable=!0),Object.defineProperty(A,F.key,F)}}return function(A,C,T){return C&&x(A.prototype,C),T&&x(A,T),A}})(),l=s(0),u=s(5),h=s(12),d=s(8),p=s(34),g=s(35),m=s(36),v=s(13),S=s(9);function E(x,A){if(!(x instanceof A))throw new TypeError("Cannot call a class as a function")}i.OidcClient=(function(){function x(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};E(this,x),A instanceof u.OidcClientSettings?this._settings=A:this._settings=new u.OidcClientSettings(A)}return x.prototype.createSigninRequest=function(){var C=this,T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},F=T.response_type,P=T.scope,q=T.redirect_uri,O=T.data,G=T.state,fe=T.prompt,M=T.display,ee=T.max_age,Se=T.ui_locales,re=T.id_token_hint,Ae=T.login_hint,ke=T.acr_values,he=T.resource,Oe=T.request,ce=T.request_uri,Ue=T.response_mode,$=T.extraQueryParams,W=T.extraTokenParams,de=T.request_type,te=T.skipUserInfo,Te=arguments[1];l.Log.debug("OidcClient.createSigninRequest");var je=this._settings.client_id;F=F||this._settings.response_type,P=P||this._settings.scope,q=q||this._settings.redirect_uri,fe=fe||this._settings.prompt,M=M||this._settings.display,ee=ee||this._settings.max_age,Se=Se||this._settings.ui_locales,ke=ke||this._settings.acr_values,he=he||this._settings.resource,Ue=Ue||this._settings.response_mode,$=$||this._settings.extraQueryParams,W=W||this._settings.extraTokenParams;var He=this._settings.authority;return d.SigninRequest.isCode(F)&&F!=="code"?Promise.reject(new Error("OpenID Connect hybrid flow is not supported")):this._metadataService.getAuthorizationEndpoint().then((function(We){l.Log.debug("OidcClient.createSigninRequest: Received authorization endpoint",We);var me=new d.SigninRequest({url:We,client_id:je,redirect_uri:q,response_type:F,scope:P,data:O||G,authority:He,prompt:fe,display:M,max_age:ee,ui_locales:Se,id_token_hint:re,login_hint:Ae,acr_values:ke,resource:he,request:Oe,request_uri:ce,extraQueryParams:$,extraTokenParams:W,request_type:de,response_mode:Ue,client_secret:C._settings.client_secret,skipUserInfo:te}),ge=me.state;return(Te=Te||C._stateStore).set(ge.id,ge.toStorageString()).then((function(){return me}))}))},x.prototype.readSigninResponseState=function(C,T){var F=arguments.length>2&&arguments[2]!==void 0&&arguments[2];l.Log.debug("OidcClient.readSigninResponseState");var P=this._settings.response_mode==="query"||!this._settings.response_mode&&d.SigninRequest.isCode(this._settings.response_type),q=P?"?":"#",O=new p.SigninResponse(C,q);if(!O.state)return l.Log.error("OidcClient.readSigninResponseState: No state in response"),Promise.reject(new Error("No state in response"));T=T||this._stateStore;var G=F?T.remove.bind(T):T.get.bind(T);return G(O.state).then((function(fe){if(!fe)throw l.Log.error("OidcClient.readSigninResponseState: No matching state found in storage"),new Error("No matching state found in storage");return{state:v.SigninState.fromStorageString(fe),response:O}}))},x.prototype.processSigninResponse=function(C,T){var F=this;return l.Log.debug("OidcClient.processSigninResponse"),this.readSigninResponseState(C,T,!0).then((function(P){var q=P.state,O=P.response;return l.Log.debug("OidcClient.processSigninResponse: Received state from storage; validating response"),F._validator.validateSigninResponse(q,O)}))},x.prototype.createSignoutRequest=function(){var C=this,T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},F=T.id_token_hint,P=T.data,q=T.state,O=T.post_logout_redirect_uri,G=T.extraQueryParams,fe=T.request_type,M=arguments[1];return l.Log.debug("OidcClient.createSignoutRequest"),O=O||this._settings.post_logout_redirect_uri,G=G||this._settings.extraQueryParams,this._metadataService.getEndSessionEndpoint().then((function(ee){if(!ee)throw l.Log.error("OidcClient.createSignoutRequest: No end session endpoint url returned"),new Error("no end session endpoint");l.Log.debug("OidcClient.createSignoutRequest: Received end session endpoint",ee);var Se=new g.SignoutRequest({url:ee,id_token_hint:F,post_logout_redirect_uri:O,data:P||q,extraQueryParams:G,request_type:fe}),re=Se.state;return re&&(l.Log.debug("OidcClient.createSignoutRequest: Signout request has state to persist"),(M=M||C._stateStore).set(re.id,re.toStorageString())),Se}))},x.prototype.readSignoutResponseState=function(C,T){var F=arguments.length>2&&arguments[2]!==void 0&&arguments[2];l.Log.debug("OidcClient.readSignoutResponseState");var P=new m.SignoutResponse(C);if(!P.state)return l.Log.debug("OidcClient.readSignoutResponseState: No state in response"),P.error?(l.Log.warn("OidcClient.readSignoutResponseState: Response was error: ",P.error),Promise.reject(new h.ErrorResponse(P))):Promise.resolve({state:void 0,response:P});var q=P.state;T=T||this._stateStore;var O=F?T.remove.bind(T):T.get.bind(T);return O(q).then((function(G){if(!G)throw l.Log.error("OidcClient.readSignoutResponseState: No matching state found in storage"),new Error("No matching state found in storage");return{state:S.State.fromStorageString(G),response:P}}))},x.prototype.processSignoutResponse=function(C,T){var F=this;return l.Log.debug("OidcClient.processSignoutResponse"),this.readSignoutResponseState(C,T,!0).then((function(P){var q=P.state,O=P.response;return q?(l.Log.debug("OidcClient.processSignoutResponse: Received state from storage; validating response"),F._validator.validateSignoutResponse(q,O)):(l.Log.debug("OidcClient.processSignoutResponse: No state from storage; skipping validating response"),O)}))},x.prototype.clearStaleState=function(C){return l.Log.debug("OidcClient.clearStaleState"),C=C||this._stateStore,S.State.clearStaleState(C,this.settings.staleStateAge)},o(x,[{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}}]),x})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.TokenClient=void 0;var o=s(7),l=s(2),u=s(0);function h(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")}i.TokenClient=(function(){function d(p){var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:o.JsonService,m=arguments.length>2&&arguments[2]!==void 0?arguments[2]:l.MetadataService;if(h(this,d),!p)throw u.Log.error("TokenClient.ctor: No settings passed"),new Error("settings");this._settings=p,this._jsonService=new g,this._metadataService=new m(this._settings)}return d.prototype.exchangeCode=function(){var g=this,m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(m=Object.assign({},m)).grant_type=m.grant_type||"authorization_code",m.client_id=m.client_id||this._settings.client_id,m.client_secret=m.client_secret||this._settings.client_secret,m.redirect_uri=m.redirect_uri||this._settings.redirect_uri;var v=void 0,S=m._client_authentication||this._settings._client_authentication;return delete m._client_authentication,m.code?m.redirect_uri?m.code_verifier?m.client_id?m.client_secret||S!="client_secret_basic"?(S=="client_secret_basic"&&(v=m.client_id+":"+m.client_secret,delete m.client_id,delete m.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(E){return u.Log.debug("TokenClient.exchangeCode: Received token endpoint"),g._jsonService.postForm(E,m,v).then((function(x){return u.Log.debug("TokenClient.exchangeCode: response received"),x}))}))):(u.Log.error("TokenClient.exchangeCode: No client_secret passed"),Promise.reject(new Error("A client_secret is required"))):(u.Log.error("TokenClient.exchangeCode: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(u.Log.error("TokenClient.exchangeCode: No code_verifier passed"),Promise.reject(new Error("A code_verifier is required"))):(u.Log.error("TokenClient.exchangeCode: No redirect_uri passed"),Promise.reject(new Error("A redirect_uri is required"))):(u.Log.error("TokenClient.exchangeCode: No code passed"),Promise.reject(new Error("A code is required")))},d.prototype.exchangeRefreshToken=function(){var g=this,m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(m=Object.assign({},m)).grant_type=m.grant_type||"refresh_token",m.client_id=m.client_id||this._settings.client_id,m.client_secret=m.client_secret||this._settings.client_secret;var v=void 0,S=m._client_authentication||this._settings._client_authentication;return delete m._client_authentication,m.refresh_token?m.client_id?(S=="client_secret_basic"&&(v=m.client_id+":"+m.client_secret,delete m.client_id,delete m.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(E){return u.Log.debug("TokenClient.exchangeRefreshToken: Received token endpoint"),g._jsonService.postForm(E,m,v).then((function(x){return u.Log.debug("TokenClient.exchangeRefreshToken: response received"),x}))}))):(u.Log.error("TokenClient.exchangeRefreshToken: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(u.Log.error("TokenClient.exchangeRefreshToken: No refresh_token passed"),Promise.reject(new Error("A refresh_token is required")))},d})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.ErrorResponse=void 0;var o=s(0);function l(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")}function u(h,d){if(!h)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!d||typeof d!="object"&&typeof d!="function"?h:d}i.ErrorResponse=(function(h){function d(){var p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},g=p.error,m=p.error_description,v=p.error_uri,S=p.state,E=p.session_state;if(l(this,d),!g)throw o.Log.error("No error passed to ErrorResponse"),new Error("error");var x=u(this,h.call(this,m||g));return x.name="ErrorResponse",x.error=g,x.error_description=m,x.error_uri=v,x.state=S,x.session_state=E,x}return(function(g,m){if(typeof m!="function"&&m!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof m);g.prototype=Object.create(m&&m.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),m&&(Object.setPrototypeOf?Object.setPrototypeOf(g,m):g.__proto__=m)})(d,h),d})(Error)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SigninState=void 0;var o=(function(){function m(v,S){for(var E=0;E<S.length;E++){var x=S[E];x.enumerable=x.enumerable||!1,x.configurable=!0,"value"in x&&(x.writable=!0),Object.defineProperty(v,x.key,x)}}return function(v,S,E){return S&&m(v.prototype,S),E&&m(v,E),v}})(),l=s(0),u=s(9),h=s(4),d=(function(v){return v&&v.__esModule?v:{default:v}})(s(14));function p(m,v){if(!(m instanceof v))throw new TypeError("Cannot call a class as a function")}function g(m,v){if(!m)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!v||typeof v!="object"&&typeof v!="function"?m:v}i.SigninState=(function(m){function v(){var S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},E=S.nonce,x=S.authority,A=S.client_id,C=S.redirect_uri,T=S.code_verifier,F=S.response_mode,P=S.client_secret,q=S.scope,O=S.extraTokenParams,G=S.skipUserInfo;p(this,v);var fe=g(this,m.call(this,arguments[0]));if(E===!0?fe._nonce=(0,d.default)():E&&(fe._nonce=E),T===!0?fe._code_verifier=(0,d.default)()+(0,d.default)()+(0,d.default)():T&&(fe._code_verifier=T),fe.code_verifier){var M=h.JoseUtil.hashString(fe.code_verifier,"SHA256");fe._code_challenge=h.JoseUtil.hexToBase64Url(M)}return fe._redirect_uri=C,fe._authority=x,fe._client_id=A,fe._response_mode=F,fe._client_secret=P,fe._scope=q,fe._extraTokenParams=O,fe._skipUserInfo=G,fe}return(function(E,x){if(typeof x!="function"&&x!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof x);E.prototype=Object.create(x&&x.prototype,{constructor:{value:E,enumerable:!1,writable:!0,configurable:!0}}),x&&(Object.setPrototypeOf?Object.setPrototypeOf(E,x):E.__proto__=x)})(v,m),v.prototype.toStorageString=function(){return l.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})},v.fromStorageString=function(E){return l.Log.debug("SigninState.fromStorageString"),new v(JSON.parse(E))},o(v,[{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}}]),v})(u.State)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.default=function(){return(o!="undefined"&&o!==null&&o.getRandomValues!==void 0?l:u)().replace(/-/g,"")};var o=typeof window<"u"?window.crypto||window.msCrypto:null;function l(){return("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,(function(h){return(h^o.getRandomValues(new Uint8Array(1))[0]&15>>h/4).toString(16)}))}function u(){return("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,(function(h){return(h^16*Math.random()>>h/4).toString(16)}))}t.exports=i.default},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.User=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.User=(function(){function u(h){var d=h.id_token,p=h.session_state,g=h.access_token,m=h.refresh_token,v=h.token_type,S=h.scope,E=h.profile,x=h.expires_at,A=h.state;(function(T,F){if(!(T instanceof F))throw new TypeError("Cannot call a class as a function")})(this,u),this.id_token=d,this.session_state=p,this.access_token=g,this.refresh_token=m,this.token_type=v,this.scope=S,this.profile=E,this.expires_at=x,this.state=A}return u.prototype.toStorageString=function(){return l.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})},u.fromStorageString=function(d){return l.Log.debug("User.fromStorageString"),new u(JSON.parse(d))},o(u,[{key:"expires_in",get:function(){if(this.expires_at){var d=parseInt(Date.now()/1e3);return this.expires_at-d}},set:function(d){var p=parseInt(d);if(typeof p=="number"&&p>0){var g=parseInt(Date.now()/1e3);this.expires_at=g+p}}},{key:"expired",get:function(){var d=this.expires_in;if(d!==void 0)return d<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.AccessTokenEvents=void 0;var o=s(0),l=s(46);function u(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")}i.AccessTokenEvents=(function(){function h(){var d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},p=d.accessTokenExpiringNotificationTime,g=p===void 0?60:p,m=d.accessTokenExpiringTimer,v=m===void 0?new l.Timer("Access token expiring"):m,S=d.accessTokenExpiredTimer,E=S===void 0?new l.Timer("Access token expired"):S;u(this,h),this._accessTokenExpiringNotificationTime=g,this._accessTokenExpiring=v,this._accessTokenExpired=E}return h.prototype.load=function(p){if(p.access_token&&p.expires_in!==void 0){var g=p.expires_in;if(o.Log.debug("AccessTokenEvents.load: access token present, remaining duration:",g),g>0){var m=g-this._accessTokenExpiringNotificationTime;m<=0&&(m=1),o.Log.debug("AccessTokenEvents.load: registering expiring timer in:",m),this._accessTokenExpiring.init(m)}else o.Log.debug("AccessTokenEvents.load: canceling existing expiring timer becase we're past expiration."),this._accessTokenExpiring.cancel();var v=g+1;o.Log.debug("AccessTokenEvents.load: registering expired timer in:",v),this._accessTokenExpired.init(v)}else this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},h.prototype.unload=function(){o.Log.debug("AccessTokenEvents.unload: canceling existing access token timers"),this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},h.prototype.addAccessTokenExpiring=function(p){this._accessTokenExpiring.addHandler(p)},h.prototype.removeAccessTokenExpiring=function(p){this._accessTokenExpiring.removeHandler(p)},h.prototype.addAccessTokenExpired=function(p){this._accessTokenExpired.addHandler(p)},h.prototype.removeAccessTokenExpired=function(p){this._accessTokenExpired.removeHandler(p)},h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Event=void 0;var o=s(0);i.Event=(function(){function l(u){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,l),this._name=u,this._callbacks=[]}return l.prototype.addHandler=function(h){this._callbacks.push(h)},l.prototype.removeHandler=function(h){var d=this._callbacks.findIndex((function(p){return p===h}));d>=0&&this._callbacks.splice(d,1)},l.prototype.raise=function(){o.Log.debug("Event: Raising event: "+this._name);for(var h=0;h<this._callbacks.length;h++){var d;(d=this._callbacks)[h].apply(d,arguments)}},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SessionMonitor=void 0;var o=(function(){function p(g,m){for(var v=0;v<m.length;v++){var S=m[v];S.enumerable=S.enumerable||!1,S.configurable=!0,"value"in S&&(S.writable=!0),Object.defineProperty(g,S.key,S)}}return function(g,m,v){return m&&p(g.prototype,m),v&&p(g,v),g}})(),l=s(0),u=s(19),h=s(1);function d(p,g){if(!(p instanceof g))throw new TypeError("Cannot call a class as a function")}i.SessionMonitor=(function(){function p(g){var m=this,v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u.CheckSessionIFrame,S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:h.Global.timer;if(d(this,p),!g)throw l.Log.error("SessionMonitor.ctor: No user manager passed to SessionMonitor"),new Error("userManager");this._userManager=g,this._CheckSessionIFrameCtor=v,this._timer=S,this._userManager.events.addUserLoaded(this._start.bind(this)),this._userManager.events.addUserUnloaded(this._stop.bind(this)),Promise.resolve(this._userManager.getUser().then((function(E){E?m._start(E):m._settings.monitorAnonymousSession&&m._userManager.querySessionStatus().then((function(x){var A={session_state:x.session_state};x.sub&&x.sid&&(A.profile={sub:x.sub,sid:x.sid}),m._start(A)})).catch((function(x){l.Log.error("SessionMonitor ctor: error from querySessionStatus:",x.message)}))})).catch((function(E){l.Log.error("SessionMonitor ctor: error from getUser:",E.message)})))}return p.prototype._start=function(m){var v=this,S=m.session_state;S&&(m.profile?(this._sub=m.profile.sub,this._sid=m.profile.sid,l.Log.debug("SessionMonitor._start: session_state:",S,", sub:",this._sub)):(this._sub=void 0,this._sid=void 0,l.Log.debug("SessionMonitor._start: session_state:",S,", anonymous user")),this._checkSessionIFrame?this._checkSessionIFrame.start(S):this._metadataService.getCheckSessionIframe().then((function(E){if(E){l.Log.debug("SessionMonitor._start: Initializing check session iframe");var x=v._client_id,A=v._checkSessionInterval,C=v._stopCheckSessionOnError;v._checkSessionIFrame=new v._CheckSessionIFrameCtor(v._callback.bind(v),x,E,A,C),v._checkSessionIFrame.load().then((function(){v._checkSessionIFrame.start(S)}))}else l.Log.warn("SessionMonitor._start: No check session iframe found in the metadata")})).catch((function(E){l.Log.error("SessionMonitor._start: Error from getCheckSessionIframe:",E.message)})))},p.prototype._stop=function(){var m=this;if(this._sub=void 0,this._sid=void 0,this._checkSessionIFrame&&(l.Log.debug("SessionMonitor._stop"),this._checkSessionIFrame.stop()),this._settings.monitorAnonymousSession)var v=this._timer.setInterval((function(){m._timer.clearInterval(v),m._userManager.querySessionStatus().then((function(S){var E={session_state:S.session_state};S.sub&&S.sid&&(E.profile={sub:S.sub,sid:S.sid}),m._start(E)})).catch((function(S){l.Log.error("SessionMonitor: error from querySessionStatus:",S.message)}))}),1e3)},p.prototype._callback=function(){var m=this;this._userManager.querySessionStatus().then((function(v){var S=!0;v?v.sub===m._sub?(S=!1,m._checkSessionIFrame.start(v.session_state),v.sid===m._sid?l.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",v.session_state):(l.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",v.session_state),m._userManager.events._raiseUserSessionChanged())):l.Log.debug("SessionMonitor._callback: Different subject signed into OP:",v.sub):l.Log.debug("SessionMonitor._callback: Subject no longer signed into OP"),S&&(m._sub?(l.Log.debug("SessionMonitor._callback: SessionMonitor._callback; raising signed out event"),m._userManager.events._raiseUserSignedOut()):(l.Log.debug("SessionMonitor._callback: SessionMonitor._callback; raising signed in event"),m._userManager.events._raiseUserSignedIn()))})).catch((function(v){m._sub&&(l.Log.debug("SessionMonitor._callback: Error calling queryCurrentSigninSession; raising signed out event",v.message),m._userManager.events._raiseUserSignedOut())}))},o(p,[{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}}]),p})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CheckSessionIFrame=void 0;var o=s(0);function l(u,h){if(!(u instanceof h))throw new TypeError("Cannot call a class as a function")}i.CheckSessionIFrame=(function(){function u(h,d,p,g){var m=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4];l(this,u),this._callback=h,this._client_id=d,this._url=p,this._interval=g||2e3,this._stopOnError=m;var v=p.indexOf("/",p.indexOf("//")+2);this._frame_origin=p.substr(0,v),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=p}return u.prototype.load=function(){var d=this;return new Promise((function(p){d._frame.onload=function(){p()},window.document.body.appendChild(d._frame),d._boundMessageEvent=d._message.bind(d),window.addEventListener("message",d._boundMessageEvent,!1)}))},u.prototype._message=function(d){d.origin===this._frame_origin&&d.source===this._frame.contentWindow&&(d.data==="error"?(o.Log.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):d.data==="changed"?(o.Log.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):o.Log.debug("CheckSessionIFrame: "+d.data+" message from check session op iframe"))},u.prototype.start=function(d){var p=this;if(this._session_state!==d){o.Log.debug("CheckSessionIFrame.start"),this.stop(),this._session_state=d;var g=function(){p._frame.contentWindow.postMessage(p._client_id+" "+p._session_state,p._frame_origin)};g(),this._timer=window.setInterval(g,this._interval)}},u.prototype.stop=function(){this._session_state=null,this._timer&&(o.Log.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.TokenRevocationClient=void 0;var o=s(0),l=s(2),u=s(1);function h(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")}var d="access_token",p="refresh_token";i.TokenRevocationClient=(function(){function g(m){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u.Global.XMLHttpRequest,S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:l.MetadataService;if(h(this,g),!m)throw o.Log.error("TokenRevocationClient.ctor: No settings provided"),new Error("No settings provided.");this._settings=m,this._XMLHttpRequestCtor=v,this._metadataService=new S(this._settings)}return g.prototype.revoke=function(v,S){var E=this,x=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"access_token";if(!v)throw o.Log.error("TokenRevocationClient.revoke: No token provided"),new Error("No token provided.");if(x!==d&&x!=p)throw o.Log.error("TokenRevocationClient.revoke: Invalid token type"),new Error("Invalid token type.");return this._metadataService.getRevocationEndpoint().then((function(A){if(A){o.Log.debug("TokenRevocationClient.revoke: Revoking "+x);var C=E._settings.client_id,T=E._settings.client_secret;return E._revoke(A,C,T,v,x)}if(S)throw o.Log.error("TokenRevocationClient.revoke: Revocation not supported"),new Error("Revocation not supported")}))},g.prototype._revoke=function(v,S,E,x,A){var C=this;return new Promise((function(T,F){var P=new C._XMLHttpRequestCtor;P.open("POST",v),P.onload=function(){o.Log.debug("TokenRevocationClient.revoke: HTTP response received, status",P.status),P.status===200?T():F(Error(P.statusText+" ("+P.status+")"))},P.onerror=function(){o.Log.debug("TokenRevocationClient.revoke: Network Error."),F("Network Error")};var q="client_id="+encodeURIComponent(S);E&&(q+="&client_secret="+encodeURIComponent(E)),q+="&token_type_hint="+encodeURIComponent(A),q+="&token="+encodeURIComponent(x),P.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),P.send(q)}))},g})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaPopupWindow=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.CordovaPopupWindow=(function(){function u(h){var d=this;(function(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")})(this,u),this._promise=new Promise((function(p,g){d._resolve=p,d._reject=g})),this.features=h.popupWindowFeatures||"location=no,toolbar=no,zoom=no",this.target=h.popupWindowTarget||"_blank",this.redirect_uri=h.startUrl,l.Log.debug("CordovaPopupWindow.ctor: redirect_uri: "+this.redirect_uri)}return u.prototype._isInAppBrowserInstalled=function(d){return["cordova-plugin-inappbrowser","cordova-plugin-inappbrowser.inappbrowser","org.apache.cordova.inappbrowser"].some((function(p){return d.hasOwnProperty(p)}))},u.prototype.navigate=function(d){if(d&&d.url){if(!window.cordova)return this._error("cordova is undefined");var p=window.cordova.require("cordova/plugin_list").metadata;if(this._isInAppBrowserInstalled(p)===!1)return this._error("InAppBrowser plugin not found");this._popup=cordova.InAppBrowser.open(d.url,this.target,this.features),this._popup?(l.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},u.prototype._loadStartCallback=function(d){d.url.indexOf(this.redirect_uri)===0&&this._success({url:d.url})},u.prototype._exitCallback=function(d){this._error(d)},u.prototype._success=function(d){this._cleanup(),l.Log.debug("CordovaPopupWindow: Successful response from cordova popup window"),this._resolve(d)},u.prototype._error=function(d){this._cleanup(),l.Log.error(d),this._reject(new Error(d))},u.prototype.close=function(){this._cleanup()},u.prototype._cleanup=function(){this._popup&&(l.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},o(u,[{key:"promise",get:function(){return this._promise}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0});var o=s(0),l=s(10),u=s(5),h=s(6),d=s(37),p=s(38),g=s(16),m=s(2),v=s(48),S=s(49),E=s(19),x=s(20),A=s(18),C=s(1),T=s(15),F=s(50);i.default={Version:F.Version,Log:o.Log,OidcClient:l.OidcClient,OidcClientSettings:u.OidcClientSettings,WebStorageStateStore:h.WebStorageStateStore,InMemoryWebStorage:d.InMemoryWebStorage,UserManager:p.UserManager,AccessTokenEvents:g.AccessTokenEvents,MetadataService:m.MetadataService,CordovaPopupNavigator:v.CordovaPopupNavigator,CordovaIFrameNavigator:S.CordovaIFrameNavigator,CheckSessionIFrame:E.CheckSessionIFrame,TokenRevocationClient:x.TokenRevocationClient,SessionMonitor:A.SessionMonitor,Global:C.Global,User:T.User},t.exports=i.default},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.ClockService=(function(){function o(){(function(u,h){if(!(u instanceof h))throw new TypeError("Cannot call a class as a function")})(this,o)}return o.prototype.getEpochTime=function(){return Promise.resolve(Date.now()/1e3|0)},o})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.ResponseValidator=void 0;var o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(S){return typeof S}:function(S){return S&&typeof Symbol=="function"&&S.constructor===Symbol&&S!==Symbol.prototype?"symbol":typeof S},l=s(0),u=s(2),h=s(25),d=s(11),p=s(12),g=s(4);function m(S,E){if(!(S instanceof E))throw new TypeError("Cannot call a class as a function")}var v=["nonce","at_hash","iat","nbf","exp","aud","iss","c_hash"];i.ResponseValidator=(function(){function S(E){var x=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u.MetadataService,A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:h.UserInfoService,C=arguments.length>3&&arguments[3]!==void 0?arguments[3]:g.JoseUtil,T=arguments.length>4&&arguments[4]!==void 0?arguments[4]:d.TokenClient;if(m(this,S),!E)throw l.Log.error("ResponseValidator.ctor: No settings passed to ResponseValidator"),new Error("settings");this._settings=E,this._metadataService=new x(this._settings),this._userInfoService=new A(this._settings),this._joseUtil=C,this._tokenClient=new T(this._settings)}return S.prototype.validateSigninResponse=function(x,A){var C=this;return l.Log.debug("ResponseValidator.validateSigninResponse"),this._processSigninParams(x,A).then((function(T){return l.Log.debug("ResponseValidator.validateSigninResponse: state processed"),C._validateTokens(x,T).then((function(F){return l.Log.debug("ResponseValidator.validateSigninResponse: tokens validated"),C._processClaims(x,F).then((function(P){return l.Log.debug("ResponseValidator.validateSigninResponse: claims processed"),P}))}))}))},S.prototype.validateSignoutResponse=function(x,A){return x.id!==A.state?(l.Log.error("ResponseValidator.validateSignoutResponse: State does not match"),Promise.reject(new Error("State does not match"))):(l.Log.debug("ResponseValidator.validateSignoutResponse: state validated"),A.state=x.data,A.error?(l.Log.warn("ResponseValidator.validateSignoutResponse: Response was error",A.error),Promise.reject(new p.ErrorResponse(A))):Promise.resolve(A))},S.prototype._processSigninParams=function(x,A){if(x.id!==A.state)return l.Log.error("ResponseValidator._processSigninParams: State does not match"),Promise.reject(new Error("State does not match"));if(!x.client_id)return l.Log.error("ResponseValidator._processSigninParams: No client_id on state"),Promise.reject(new Error("No client_id on state"));if(!x.authority)return l.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!==x.authority)return l.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=x.authority;if(this._settings.client_id){if(this._settings.client_id&&this._settings.client_id!==x.client_id)return l.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=x.client_id;return l.Log.debug("ResponseValidator._processSigninParams: state validated"),A.state=x.data,A.error?(l.Log.warn("ResponseValidator._processSigninParams: Response was error",A.error),Promise.reject(new p.ErrorResponse(A))):x.nonce&&!A.id_token?(l.Log.error("ResponseValidator._processSigninParams: Expecting id_token in response"),Promise.reject(new Error("No id_token in response"))):!x.nonce&&A.id_token?(l.Log.error("ResponseValidator._processSigninParams: Not expecting id_token in response"),Promise.reject(new Error("Unexpected id_token in response"))):x.code_verifier&&!A.code?(l.Log.error("ResponseValidator._processSigninParams: Expecting code in response"),Promise.reject(new Error("No code in response"))):!x.code_verifier&&A.code?(l.Log.error("ResponseValidator._processSigninParams: Not expecting code in response"),Promise.reject(new Error("Unexpected code in response"))):(A.scope||(A.scope=x.scope),Promise.resolve(A))},S.prototype._processClaims=function(x,A){var C=this;if(A.isOpenIdConnect){if(l.Log.debug("ResponseValidator._processClaims: response is OIDC, processing claims"),A.profile=this._filterProtocolClaims(A.profile),x.skipUserInfo!==!0&&this._settings.loadUserInfo&&A.access_token)return l.Log.debug("ResponseValidator._processClaims: loading user info"),this._userInfoService.getClaims(A.access_token).then((function(T){return l.Log.debug("ResponseValidator._processClaims: user info claims received from user info endpoint"),T.sub!==A.profile.sub?(l.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"))):(A.profile=C._mergeClaims(A.profile,T),l.Log.debug("ResponseValidator._processClaims: user info claims received, updated profile:",A.profile),A)}));l.Log.debug("ResponseValidator._processClaims: not loading user info")}else l.Log.debug("ResponseValidator._processClaims: response is not OIDC, not processing claims");return Promise.resolve(A)},S.prototype._mergeClaims=function(x,A){var C=Object.assign({},x);for(var T in A){var F=A[T];Array.isArray(F)||(F=[F]);for(var P=0;P<F.length;P++){var q=F[P];C[T]?Array.isArray(C[T])?C[T].indexOf(q)<0&&C[T].push(q):C[T]!==q&&((q===void 0?"undefined":o(q))==="object"&&this._settings.mergeClaims?C[T]=this._mergeClaims(C[T],q):C[T]=[C[T],q]):C[T]=q}}return C},S.prototype._filterProtocolClaims=function(x){l.Log.debug("ResponseValidator._filterProtocolClaims, incoming claims:",x);var A=Object.assign({},x);return this._settings._filterProtocolClaims?(v.forEach((function(C){delete A[C]})),l.Log.debug("ResponseValidator._filterProtocolClaims: protocol claims filtered",A)):l.Log.debug("ResponseValidator._filterProtocolClaims: protocol claims not filtered"),A},S.prototype._validateTokens=function(x,A){return A.code?(l.Log.debug("ResponseValidator._validateTokens: Validating code"),this._processCode(x,A)):A.id_token?A.access_token?(l.Log.debug("ResponseValidator._validateTokens: Validating id_token and access_token"),this._validateIdTokenAndAccessToken(x,A)):(l.Log.debug("ResponseValidator._validateTokens: Validating id_token"),this._validateIdToken(x,A)):(l.Log.debug("ResponseValidator._validateTokens: No code to process or id_token to validate"),Promise.resolve(A))},S.prototype._processCode=function(x,A){var C=this,T={client_id:x.client_id,client_secret:x.client_secret,code:A.code,redirect_uri:x.redirect_uri,code_verifier:x.code_verifier};return x.extraTokenParams&&o(x.extraTokenParams)==="object"&&Object.assign(T,x.extraTokenParams),this._tokenClient.exchangeCode(T).then((function(F){for(var P in F)A[P]=F[P];return A.id_token?(l.Log.debug("ResponseValidator._processCode: token response successful, processing id_token"),C._validateIdTokenAttributes(x,A)):(l.Log.debug("ResponseValidator._processCode: token response successful, returning response"),A)}))},S.prototype._validateIdTokenAttributes=function(x,A){var C=this;return this._metadataService.getIssuer().then((function(T){var F=x.client_id,P=C._settings.clockSkew;return l.Log.debug("ResponseValidator._validateIdTokenAttributes: Validaing JWT attributes; using clock skew (in seconds) of: ",P),C._settings.getEpochTime().then((function(q){return C._joseUtil.validateJwtAttributes(A.id_token,T,F,P,q).then((function(O){return x.nonce&&x.nonce!==O.nonce?(l.Log.error("ResponseValidator._validateIdTokenAttributes: Invalid nonce in id_token"),Promise.reject(new Error("Invalid nonce in id_token"))):O.sub?(A.profile=O,A):(l.Log.error("ResponseValidator._validateIdTokenAttributes: No sub present in id_token"),Promise.reject(new Error("No sub present in id_token")))}))}))}))},S.prototype._validateIdTokenAndAccessToken=function(x,A){var C=this;return this._validateIdToken(x,A).then((function(T){return C._validateAccessToken(T)}))},S.prototype._getSigningKeyForJwt=function(x){var A=this;return this._metadataService.getSigningKeys().then((function(C){var T=x.header.kid;if(!C)return l.Log.error("ResponseValidator._validateIdToken: No signing keys from metadata"),Promise.reject(new Error("No signing keys from metadata"));l.Log.debug("ResponseValidator._validateIdToken: Received signing keys");var F=void 0;if(T)F=C.filter((function(P){return P.kid===T}))[0];else{if((C=A._filterByAlg(C,x.header.alg)).length>1)return l.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"));F=C[0]}return Promise.resolve(F)}))},S.prototype._getSigningKeyForJwtWithSingleRetry=function(x){var A=this;return this._getSigningKeyForJwt(x).then((function(C){return C?Promise.resolve(C):(A._metadataService.resetSigningKeys(),A._getSigningKeyForJwt(x))}))},S.prototype._validateIdToken=function(x,A){var C=this;if(!x.nonce)return l.Log.error("ResponseValidator._validateIdToken: No nonce on state"),Promise.reject(new Error("No nonce on state"));var T=this._joseUtil.parseJwt(A.id_token);return T&&T.header&&T.payload?x.nonce!==T.payload.nonce?(l.Log.error("ResponseValidator._validateIdToken: Invalid nonce in id_token"),Promise.reject(new Error("Invalid nonce in id_token"))):this._metadataService.getIssuer().then((function(F){return l.Log.debug("ResponseValidator._validateIdToken: Received issuer"),C._getSigningKeyForJwtWithSingleRetry(T).then((function(P){if(!P)return l.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 q=x.client_id,O=C._settings.clockSkew;return l.Log.debug("ResponseValidator._validateIdToken: Validaing JWT; using clock skew (in seconds) of: ",O),C._joseUtil.validateJwt(A.id_token,P,F,q,O).then((function(){return l.Log.debug("ResponseValidator._validateIdToken: JWT validation successful"),T.payload.sub?(A.profile=T.payload,A):(l.Log.error("ResponseValidator._validateIdToken: No sub present in id_token"),Promise.reject(new Error("No sub present in id_token")))}))}))})):(l.Log.error("ResponseValidator._validateIdToken: Failed to parse id_token",T),Promise.reject(new Error("Failed to parse id_token")))},S.prototype._filterByAlg=function(x,A){var C=null;if(A.startsWith("RS"))C="RSA";else if(A.startsWith("PS"))C="PS";else{if(!A.startsWith("ES"))return l.Log.debug("ResponseValidator._filterByAlg: alg not supported: ",A),[];C="EC"}return l.Log.debug("ResponseValidator._filterByAlg: Looking for keys that match kty: ",C),x=x.filter((function(T){return T.kty===C})),l.Log.debug("ResponseValidator._filterByAlg: Number of keys that match kty: ",C,x.length),x},S.prototype._validateAccessToken=function(x){if(!x.profile)return l.Log.error("ResponseValidator._validateAccessToken: No profile loaded from id_token"),Promise.reject(new Error("No profile loaded from id_token"));if(!x.profile.at_hash)return l.Log.error("ResponseValidator._validateAccessToken: No at_hash in id_token"),Promise.reject(new Error("No at_hash in id_token"));if(!x.id_token)return l.Log.error("ResponseValidator._validateAccessToken: No id_token"),Promise.reject(new Error("No id_token"));var A=this._joseUtil.parseJwt(x.id_token);if(!A||!A.header)return l.Log.error("ResponseValidator._validateAccessToken: Failed to parse id_token",A),Promise.reject(new Error("Failed to parse id_token"));var C=A.header.alg;if(!C||C.length!==5)return l.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",C),Promise.reject(new Error("Unsupported alg: "+C));var T=C.substr(2,3);if(!T)return l.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",C,T),Promise.reject(new Error("Unsupported alg: "+C));if((T=parseInt(T))!==256&&T!==384&&T!==512)return l.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",C,T),Promise.reject(new Error("Unsupported alg: "+C));var F="sha"+T,P=this._joseUtil.hashString(x.access_token,F);if(!P)return l.Log.error("ResponseValidator._validateAccessToken: access_token hash failed:",F),Promise.reject(new Error("Failed to validate at_hash"));var q=P.substr(0,P.length/2),O=this._joseUtil.hexToBase64Url(q);return O!==x.profile.at_hash?(l.Log.error("ResponseValidator._validateAccessToken: Failed to validate at_hash",O,x.profile.at_hash),Promise.reject(new Error("Failed to validate at_hash"))):(l.Log.debug("ResponseValidator._validateAccessToken: success"),Promise.resolve(x))},S})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserInfoService=void 0;var o=s(7),l=s(2),u=s(0),h=s(4);function d(p,g){if(!(p instanceof g))throw new TypeError("Cannot call a class as a function")}i.UserInfoService=(function(){function p(g){var m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:o.JsonService,v=arguments.length>2&&arguments[2]!==void 0?arguments[2]:l.MetadataService,S=arguments.length>3&&arguments[3]!==void 0?arguments[3]:h.JoseUtil;if(d(this,p),!g)throw u.Log.error("UserInfoService.ctor: No settings passed"),new Error("settings");this._settings=g,this._jsonService=new m(void 0,void 0,this._getClaimsFromJwt.bind(this)),this._metadataService=new v(this._settings),this._joseUtil=S}return p.prototype.getClaims=function(m){var v=this;return m?this._metadataService.getUserInfoEndpoint().then((function(S){return u.Log.debug("UserInfoService.getClaims: received userinfo url",S),v._jsonService.getJson(S,m).then((function(E){return u.Log.debug("UserInfoService.getClaims: claims received",E),E}))})):(u.Log.error("UserInfoService.getClaims: No token passed"),Promise.reject(new Error("A token is required")))},p.prototype._getClaimsFromJwt=function(m){var v=this;try{var S=this._joseUtil.parseJwt(m.responseText);if(!S||!S.header||!S.payload)return u.Log.error("UserInfoService._getClaimsFromJwt: Failed to parse JWT",S),Promise.reject(new Error("Failed to parse id_token"));var E=S.header.kid,x=void 0;switch(this._settings.userInfoJwtIssuer){case"OP":x=this._metadataService.getIssuer();break;case"ANY":x=Promise.resolve(S.payload.iss);break;default:x=Promise.resolve(this._settings.userInfoJwtIssuer)}return x.then((function(A){return u.Log.debug("UserInfoService._getClaimsFromJwt: Received issuer:"+A),v._metadataService.getSigningKeys().then((function(C){if(!C)return u.Log.error("UserInfoService._getClaimsFromJwt: No signing keys from metadata"),Promise.reject(new Error("No signing keys from metadata"));u.Log.debug("UserInfoService._getClaimsFromJwt: Received signing keys");var T=void 0;if(E)T=C.filter((function(q){return q.kid===E}))[0];else{if((C=v._filterByAlg(C,S.header.alg)).length>1)return u.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"));T=C[0]}if(!T)return u.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 F=v._settings.client_id,P=v._settings.clockSkew;return u.Log.debug("UserInfoService._getClaimsFromJwt: Validaing JWT; using clock skew (in seconds) of: ",P),v._joseUtil.validateJwt(m.responseText,T,A,F,P,void 0,!0).then((function(){return u.Log.debug("UserInfoService._getClaimsFromJwt: JWT validation successful"),S.payload}))}))}))}catch(A){return u.Log.error("UserInfoService._getClaimsFromJwt: Error parsing JWT response",A.message),void reject(A)}},p.prototype._filterByAlg=function(m,v){var S=null;if(v.startsWith("RS"))S="RSA";else if(v.startsWith("PS"))S="PS";else{if(!v.startsWith("ES"))return u.Log.debug("UserInfoService._filterByAlg: alg not supported: ",v),[];S="EC"}return u.Log.debug("UserInfoService._filterByAlg: Looking for keys that match kty: ",S),m=m.filter((function(E){return E.kty===S})),u.Log.debug("UserInfoService._filterByAlg: Number of keys that match kty: ",S,m.length),m},p})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.AllowedSigningAlgs=i.b64tohex=i.hextob64u=i.crypto=i.X509=i.KeyUtil=i.jws=void 0;var o=s(27);i.jws=o.jws,i.KeyUtil=o.KEYUTIL,i.X509=o.X509,i.crypto=o.crypto,i.hextob64u=o.hextob64u,i.b64tohex=o.b64tohex,i.AllowedSigningAlgs=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"]},function(t,i,s){(function(o){Object.defineProperty(i,"__esModule",{value:!0});var l,u,h,d,p,g,m,v,S,E,x,A=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(_){return typeof _}:function(_){return _&&typeof Symbol=="function"&&_.constructor===Symbol&&_!==Symbol.prototype?"symbol":typeof _},C={},T={},F=F||(l=Math,h=(u={}).lib={},d=h.Base=(function(){function _(){}return{extend:function(w){_.prototype=this;var I=new _;return w&&I.mixIn(w),I.hasOwnProperty("init")||(I.init=function(){I.$super.init.apply(this,arguments)}),I.init.prototype=I,I.$super=this,I},create:function(){var w=this.extend();return w.init.apply(w,arguments),w},init:function(){},mixIn:function(w){for(var I in w)w.hasOwnProperty(I)&&(this[I]=w[I]);w.hasOwnProperty("toString")&&(this.toString=w.toString)},clone:function(){return this.init.prototype.extend(this)}}})(),p=h.WordArray=d.extend({init:function(b,w){b=this.words=b||[],this.sigBytes=w??4*b.length},toString:function(b){return(b||m).stringify(this)},concat:function(b){var w=this.words,I=b.words,L=this.sigBytes,Q=b.sigBytes;if(this.clamp(),L%4)for(var se=0;se<Q;se++){var xe=I[se>>>2]>>>24-se%4*8&255;w[L+se>>>2]|=xe<<24-(L+se)%4*8}else for(se=0;se<Q;se+=4)w[L+se>>>2]=I[se>>>2];return this.sigBytes+=Q,this},clamp:function(){var b=this.words,w=this.sigBytes;b[w>>>2]&=4294967295<<32-w%4*8,b.length=l.ceil(w/4)},clone:function(){var b=d.clone.call(this);return b.words=this.words.slice(0),b},random:function(b){for(var w=[],I=0;I<b;I+=4)w.push(4294967296*l.random()|0);return new p.init(w,b)}}),g=u.enc={},m=g.Hex={stringify:function(b){for(var w=b.words,I=b.sigBytes,L=[],Q=0;Q<I;Q++){var se=w[Q>>>2]>>>24-Q%4*8&255;L.push((se>>>4).toString(16)),L.push((15&se).toString(16))}return L.join("")},parse:function(b){for(var w=b.length,I=[],L=0;L<w;L+=2)I[L>>>3]|=parseInt(b.substr(L,2),16)<<24-L%8*4;return new p.init(I,w/2)}},v=g.Latin1={stringify:function(b){for(var w=b.words,I=b.sigBytes,L=[],Q=0;Q<I;Q++){var se=w[Q>>>2]>>>24-Q%4*8&255;L.push(String.fromCharCode(se))}return L.join("")},parse:function(b){for(var w=b.length,I=[],L=0;L<w;L++)I[L>>>2]|=(255&b.charCodeAt(L))<<24-L%4*8;return new p.init(I,w)}},S=g.Utf8={stringify:function(b){try{return decodeURIComponent(escape(v.stringify(b)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(b){return v.parse(unescape(encodeURIComponent(b)))}},E=h.BufferedBlockAlgorithm=d.extend({reset:function(){this._data=new p.init,this._nDataBytes=0},_append:function(b){typeof b=="string"&&(b=S.parse(b)),this._data.concat(b),this._nDataBytes+=b.sigBytes},_process:function(b){var w=this._data,I=w.words,L=w.sigBytes,Q=this.blockSize,se=L/(4*Q),xe=(se=b?l.ceil(se):l.max((0|se)-this._minBufferSize,0))*Q,be=l.min(4*xe,L);if(xe){for(var ve=0;ve<xe;ve+=Q)this._doProcessBlock(I,ve);var we=I.splice(0,xe);w.sigBytes-=be}return new p.init(we,be)},clone:function(){var b=d.clone.call(this);return b._data=this._data.clone(),b},_minBufferSize:0}),h.Hasher=E.extend({cfg:d.extend(),init:function(b){this.cfg=this.cfg.extend(b),this.reset()},reset:function(){E.reset.call(this),this._doReset()},update:function(b){return this._append(b),this._process(),this},finalize:function(b){return b&&this._append(b),this._doFinalize()},blockSize:16,_createHelper:function(b){return function(w,I){return new b.init(I).finalize(w)}},_createHmacHelper:function(b){return function(w,I){return new x.HMAC.init(b,I).finalize(w)}}}),x=u.algo={},u);(function(_){var b,w=(b=F).lib,I=w.Base,L=w.WordArray;(b=b.x64={}).Word=I.extend({init:function(se,xe){this.high=se,this.low=xe}}),b.WordArray=I.extend({init:function(se,xe){se=this.words=se||[],this.sigBytes=xe??8*se.length},toX32:function(){for(var se=this.words,xe=se.length,be=[],ve=0;ve<xe;ve++){var we=se[ve];be.push(we.high),be.push(we.low)}return L.create(be,this.sigBytes)},clone:function(){for(var se=I.clone.call(this),xe=se.words=this.words.slice(0),be=xe.length,ve=0;ve<be;ve++)xe[ve]=xe[ve].clone();return se}})})(),(function(){var _=F,b=_.lib.WordArray;_.enc.Base64={stringify:function(I){var L=I.words,Q=I.sigBytes,se=this._map;I.clamp(),I=[];for(var xe=0;xe<Q;xe+=3)for(var be=(L[xe>>>2]>>>24-xe%4*8&255)<<16|(L[xe+1>>>2]>>>24-(xe+1)%4*8&255)<<8|L[xe+2>>>2]>>>24-(xe+2)%4*8&255,ve=0;4>ve&&xe+.75*ve<Q;ve++)I.push(se.charAt(be>>>6*(3-ve)&63));if(L=se.charAt(64))for(;I.length%4;)I.push(L);return I.join("")},parse:function(I){var L=I.length,Q=this._map;(se=Q.charAt(64))&&(se=I.indexOf(se))!=-1&&(L=se);for(var se=[],xe=0,be=0;be<L;be++)if(be%4){var ve=Q.indexOf(I.charAt(be-1))<<be%4*2,we=Q.indexOf(I.charAt(be))>>>6-be%4*2;se[xe>>>2]|=(ve|we)<<24-xe%4*8,xe++}return b.create(se,xe)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})(),(function(_){for(var b=F,w=(L=b.lib).WordArray,I=L.Hasher,L=b.algo,Q=[],se=[],xe=function(Ye){return 4294967296*(Ye-(0|Ye))|0},be=2,ve=0;64>ve;){var we;e:{we=be;for(var Ce=_.sqrt(we),Fe=2;Fe<=Ce;Fe++)if(!(we%Fe)){we=!1;break e}we=!0}we&&(8>ve&&(Q[ve]=xe(_.pow(be,.5))),se[ve]=xe(_.pow(be,1/3)),ve++),be++}var Me=[];L=L.SHA256=I.extend({_doReset:function(){this._hash=new w.init(Q.slice(0))},_doProcessBlock:function(Ye,tt){for(var ae=this._hash.words,Re=ae[0],De=ae[1],Pe=ae[2],Qe=ae[3],it=ae[4],_t=ae[5],pt=ae[6],Dt=ae[7],bt=0;64>bt;bt++){if(16>bt)Me[bt]=0|Ye[tt+bt];else{var vt=Me[bt-15],Jt=Me[bt-2];Me[bt]=((vt<<25|vt>>>7)^(vt<<14|vt>>>18)^vt>>>3)+Me[bt-7]+((Jt<<15|Jt>>>17)^(Jt<<13|Jt>>>19)^Jt>>>10)+Me[bt-16]}vt=Dt+((it<<26|it>>>6)^(it<<21|it>>>11)^(it<<7|it>>>25))+(it&_t^~it&pt)+se[bt]+Me[bt],Jt=((Re<<30|Re>>>2)^(Re<<19|Re>>>13)^(Re<<10|Re>>>22))+(Re&De^Re&Pe^De&Pe),Dt=pt,pt=_t,_t=it,it=Qe+vt|0,Qe=Pe,Pe=De,De=Re,Re=vt+Jt|0}ae[0]=ae[0]+Re|0,ae[1]=ae[1]+De|0,ae[2]=ae[2]+Pe|0,ae[3]=ae[3]+Qe|0,ae[4]=ae[4]+it|0,ae[5]=ae[5]+_t|0,ae[6]=ae[6]+pt|0,ae[7]=ae[7]+Dt|0},_doFinalize:function(){var Ye=this._data,tt=Ye.words,ae=8*this._nDataBytes,Re=8*Ye.sigBytes;return tt[Re>>>5]|=128<<24-Re%32,tt[14+(Re+64>>>9<<4)]=_.floor(ae/4294967296),tt[15+(Re+64>>>9<<4)]=ae,Ye.sigBytes=4*tt.length,this._process(),this._hash},clone:function(){var Ye=I.clone.call(this);return Ye._hash=this._hash.clone(),Ye}}),b.SHA256=I._createHelper(L),b.HmacSHA256=I._createHmacHelper(L)})(Math),(function(){function _(){return I.create.apply(I,arguments)}for(var b=F,w=b.lib.Hasher,I=(Q=b.x64).Word,L=Q.WordArray,Q=b.algo,se=[_(1116352408,3609767458),_(1899447441,602891725),_(3049323471,3964484399),_(3921009573,2173295548),_(961987163,4081628472),_(1508970993,3053834265),_(2453635748,2937671579),_(2870763221,3664609560),_(3624381080,2734883394),_(310598401,1164996542),_(607225278,1323610764),_(1426881987,3590304994),_(1925078388,4068182383),_(2162078206,991336113),_(2614888103,633803317),_(3248222580,3479774868),_(3835390401,2666613458),_(4022224774,944711139),_(264347078,2341262773),_(604807628,2007800933),_(770255983,1495990901),_(1249150122,1856431235),_(1555081692,3175218132),_(1996064986,2198950837),_(2554220882,3999719339),_(2821834349,766784016),_(2952996808,2566594879),_(3210313671,3203337956),_(3336571891,1034457026),_(3584528711,2466948901),_(113926993,3758326383),_(338241895,168717936),_(666307205,1188179964),_(773529912,1546045734),_(1294757372,1522805485),_(1396182291,2643833823),_(1695183700,2343527390),_(1986661051,1014477480),_(2177026350,1206759142),_(2456956037,344077627),_(2730485921,1290863460),_(2820302411,3158454273),_(3259730800,3505952657),_(3345764771,106217008),_(3516065817,3606008344),_(3600352804,1432725776),_(4094571909,1467031594),_(275423344,851169720),_(430227734,3100823752),_(506948616,1363258195),_(659060556,3750685593),_(883997877,3785050280),_(958139571,3318307427),_(1322822218,3812723403),_(1537002063,2003034995),_(1747873779,3602036899),_(1955562222,1575990012),_(2024104815,1125592928),_(2227730452,2716904306),_(2361852424,442776044),_(2428436474,593698344),_(2756734187,3733110249),_(3204031479,2999351573),_(3329325298,3815920427),_(3391569614,3928383900),_(3515267271,566280711),_(3940187606,3454069534),_(4118630271,4000239992),_(116418474,1914138554),_(174292421,2731055270),_(289380356,3203993006),_(460393269,320620315),_(685471733,587496836),_(852142971,1086792851),_(1017036298,365543100),_(1126000580,2618297676),_(1288033470,3409855158),_(1501505948,4234509866),_(1607167915,987167468),_(1816402316,1246189591)],xe=[],be=0;80>be;be++)xe[be]=_();Q=Q.SHA512=w.extend({_doReset:function(){this._hash=new L.init([new I.init(1779033703,4089235720),new I.init(3144134277,2227873595),new I.init(1013904242,4271175723),new I.init(2773480762,1595750129),new I.init(1359893119,2917565137),new I.init(2600822924,725511199),new I.init(528734635,4215389547),new I.init(1541459225,327033209)])},_doProcessBlock:function(we,Ce){for(var Fe=(De=this._hash.words)[0],Me=De[1],Ze=De[2],Ye=De[3],tt=De[4],ae=De[5],Re=De[6],De=De[7],Pe=Fe.high,Qe=Fe.low,it=Me.high,_t=Me.low,pt=Ze.high,Dt=Ze.low,bt=Ye.high,vt=Ye.low,Jt=tt.high,Qt=tt.low,qt=ae.high,Dr=ae.low,jr=Re.high,$r=Re.low,cr=De.high,Yt=De.low,sr=Pe,Or=Qe,vn=it,nn=_t,mn=pt,Tn=Dt,yn=bt,Un=vt,wr=Jt,Mr=Qt,Nr=qt,Lr=Dr,zn=jr,bn=$r,zi=cr,Vn=Yt,en=0;80>en;en++){var sn=xe[en];if(16>en)var tn=sn.high=0|we[Ce+2*en],ur=sn.low=0|we[Ce+2*en+1];else{tn=((ur=(tn=xe[en-15]).high)>>>1|(Pn=tn.low)<<31)^(ur>>>8|Pn<<24)^ur>>>7;var Pn=(Pn>>>1|ur<<31)^(Pn>>>8|ur<<24)^(Pn>>>7|ur<<25),gi=((ur=(gi=xe[en-2]).high)>>>19|(Fr=gi.low)<<13)^(ur<<3|Fr>>>29)^ur>>>6,Fr=(Fr>>>19|ur<<13)^(Fr<<3|ur>>>29)^(Fr>>>6|ur<<26),Hn=(ur=xe[en-7]).high,Wn=(Kn=xe[en-16]).high,Kn=Kn.low;tn=(tn=(tn=tn+Hn+((ur=Pn+ur.low)>>>0<Pn>>>0?1:0))+gi+((ur=ur+Fr)>>>0<Fr>>>0?1:0))+Wn+((ur=ur+Kn)>>>0<Kn>>>0?1:0),sn.high=tn,sn.low=ur}Hn=wr&Nr^~wr&zn,Kn=Mr&Lr^~Mr&bn,sn=sr&vn^sr&mn^vn&mn;var Ms=Or&nn^Or&Tn^nn&Tn,wa=(Pn=(sr>>>28|Or<<4)^(sr<<30|Or>>>2)^(sr<<25|Or>>>7),gi=(Or>>>28|sr<<4)^(Or<<30|sr>>>2)^(Or<<25|sr>>>7),(Fr=se[en]).high),Zn=Fr.low;Wn=zi+((wr>>>14|Mr<<18)^(wr>>>18|Mr<<14)^(wr<<23|Mr>>>9))+((Fr=Vn+((Mr>>>14|wr<<18)^(Mr>>>18|wr<<14)^(Mr<<23|wr>>>9)))>>>0<Vn>>>0?1:0),zi=zn,Vn=bn,zn=Nr,bn=Lr,Nr=wr,Lr=Mr,wr=yn+(Wn=(Wn=(Wn=Wn+Hn+((Fr=Fr+Kn)>>>0<Kn>>>0?1:0))+wa+((Fr=Fr+Zn)>>>0<Zn>>>0?1:0))+tn+((Fr=Fr+ur)>>>0<ur>>>0?1:0))+((Mr=Un+Fr|0)>>>0<Un>>>0?1:0)|0,yn=mn,Un=Tn,mn=vn,Tn=nn,vn=sr,nn=Or,sr=Wn+(sn=Pn+sn+((ur=gi+Ms)>>>0<gi>>>0?1:0))+((Or=Fr+ur|0)>>>0<Fr>>>0?1:0)|0}Qe=Fe.low=Qe+Or,Fe.high=Pe+sr+(Qe>>>0<Or>>>0?1:0),_t=Me.low=_t+nn,Me.high=it+vn+(_t>>>0<nn>>>0?1:0),Dt=Ze.low=Dt+Tn,Ze.high=pt+mn+(Dt>>>0<Tn>>>0?1:0),vt=Ye.low=vt+Un,Ye.high=bt+yn+(vt>>>0<Un>>>0?1:0),Qt=tt.low=Qt+Mr,tt.high=Jt+wr+(Qt>>>0<Mr>>>0?1:0),Dr=ae.low=Dr+Lr,ae.high=qt+Nr+(Dr>>>0<Lr>>>0?1:0),$r=Re.low=$r+bn,Re.high=jr+zn+($r>>>0<bn>>>0?1:0),Yt=De.low=Yt+Vn,De.high=cr+zi+(Yt>>>0<Vn>>>0?1:0)},_doFinalize:function(){var we=this._data,Ce=we.words,Fe=8*this._nDataBytes,Me=8*we.sigBytes;return Ce[Me>>>5]|=128<<24-Me%32,Ce[30+(Me+128>>>10<<5)]=Math.floor(Fe/4294967296),Ce[31+(Me+128>>>10<<5)]=Fe,we.sigBytes=4*Ce.length,this._process(),this._hash.toX32()},clone:function(){var we=w.clone.call(this);return we._hash=this._hash.clone(),we},blockSize:32}),b.SHA512=w._createHelper(Q),b.HmacSHA512=w._createHmacHelper(Q)})(),(function(){var _=F,b=(L=_.x64).Word,w=L.WordArray,I=(L=_.algo).SHA512,L=L.SHA384=I.extend({_doReset:function(){this._hash=new w.init([new b.init(3418070365,3238371032),new b.init(1654270250,914150663),new b.init(2438529370,812702999),new b.init(355462360,4144912697),new b.init(1731405415,4290775857),new b.init(2394180231,1750603025),new b.init(3675008525,1694076839),new b.init(1203062813,3204075428)])},_doFinalize:function(){var se=I._doFinalize.call(this);return se.sigBytes-=16,se}});_.SHA384=I._createHelper(L),_.HmacSHA384=I._createHmacHelper(L)})();var P,q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function O(_){var b,w,I="";for(b=0;b+3<=_.length;b+=3)w=parseInt(_.substring(b,b+3),16),I+=q.charAt(w>>6)+q.charAt(63&w);for(b+1==_.length?(w=parseInt(_.substring(b,b+1),16),I+=q.charAt(w<<2)):b+2==_.length&&(w=parseInt(_.substring(b,b+2),16),I+=q.charAt(w>>2)+q.charAt((3&w)<<4)),"=";(3&I.length)>0;)I+="=";return I}function G(_){var b,w,I,L="",Q=0;for(b=0;b<_.length&&_.charAt(b)!="=";++b)(I=q.indexOf(_.charAt(b)))<0||(Q==0?(L+=ke(I>>2),w=3&I,Q=1):Q==1?(L+=ke(w<<2|I>>4),w=15&I,Q=2):Q==2?(L+=ke(w),L+=ke(I>>2),w=3&I,Q=3):(L+=ke(w<<2|I>>4),L+=ke(15&I),Q=0));return Q==1&&(L+=ke(w<<2)),L}function fe(_){var b,w=G(_),I=new Array;for(b=0;2*b<w.length;++b)I[b]=parseInt(w.substring(2*b,2*b+2),16);return I}function M(_,b,w){_!=null&&(typeof _=="number"?this.fromNumber(_,b,w):b==null&&typeof _!="string"?this.fromString(_,256):this.fromString(_,b))}function ee(){return new M(null)}C.appName=="Microsoft Internet Explorer"?(M.prototype.am=function(b,w,I,L,Q,se){for(var xe=32767&w,be=w>>15;--se>=0;){var ve=32767&this[b],we=this[b++]>>15,Ce=be*ve+we*xe;Q=((ve=xe*ve+((32767&Ce)<<15)+I[L]+(1073741823&Q))>>>30)+(Ce>>>15)+be*we+(Q>>>30),I[L++]=1073741823&ve}return Q},P=30):C.appName!="Netscape"?(M.prototype.am=function(b,w,I,L,Q,se){for(;--se>=0;){var xe=w*this[b++]+I[L]+Q;Q=Math.floor(xe/67108864),I[L++]=67108863&xe}return Q},P=26):(M.prototype.am=function(b,w,I,L,Q,se){for(var xe=16383&w,be=w>>14;--se>=0;){var ve=16383&this[b],we=this[b++]>>14,Ce=be*ve+we*xe;Q=((ve=xe*ve+((16383&Ce)<<14)+I[L]+Q)>>28)+(Ce>>14)+be*we,I[L++]=268435455&ve}return Q},P=28),M.prototype.DB=P,M.prototype.DM=(1<<P)-1,M.prototype.DV=1<<P,M.prototype.FV=Math.pow(2,52),M.prototype.F1=52-P,M.prototype.F2=2*P-52;var Se,re,Ae=new Array;for(Se=48,re=0;re<=9;++re)Ae[Se++]=re;for(Se=97,re=10;re<36;++re)Ae[Se++]=re;for(Se=65,re=10;re<36;++re)Ae[Se++]=re;function ke(_){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(_)}function he(_,b){var w=Ae[_.charCodeAt(b)];return w??-1}function Oe(_){var b=ee();return b.fromInt(_),b}function ce(_){var b,w=1;return(b=_>>>16)!=0&&(_=b,w+=16),(b=_>>8)!=0&&(_=b,w+=8),(b=_>>4)!=0&&(_=b,w+=4),(b=_>>2)!=0&&(_=b,w+=2),(b=_>>1)!=0&&(_=b,w+=1),w}function Ue(_){this.m=_}function $(_){this.m=_,this.mp=_.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<_.DB-15)-1,this.mt2=2*_.t}function W(_,b){return _&b}function de(_,b){return _|b}function te(_,b){return _^b}function Te(_,b){return _&~b}function je(_){if(_==0)return-1;var b=0;return(65535&_)==0&&(_>>=16,b+=16),(255&_)==0&&(_>>=8,b+=8),(15&_)==0&&(_>>=4,b+=4),(3&_)==0&&(_>>=2,b+=2),(1&_)==0&&++b,b}function He(_){for(var b=0;_!=0;)_&=_-1,++b;return b}function We(){}function me(_){return _}function ge(_){this.r2=ee(),this.q3=ee(),M.ONE.dlShiftTo(2*_.t,this.r2),this.mu=this.r2.divide(_),this.m=_}Ue.prototype.convert=function(b){return b.s<0||b.compareTo(this.m)>=0?b.mod(this.m):b},Ue.prototype.revert=function(b){return b},Ue.prototype.reduce=function(b){b.divRemTo(this.m,null,b)},Ue.prototype.mulTo=function(b,w,I){b.multiplyTo(w,I),this.reduce(I)},Ue.prototype.sqrTo=function(b,w){b.squareTo(w),this.reduce(w)},$.prototype.convert=function(b){var w=ee();return b.abs().dlShiftTo(this.m.t,w),w.divRemTo(this.m,null,w),b.s<0&&w.compareTo(M.ZERO)>0&&this.m.subTo(w,w),w},$.prototype.revert=function(b){var w=ee();return b.copyTo(w),this.reduce(w),w},$.prototype.reduce=function(b){for(;b.t<=this.mt2;)b[b.t++]=0;for(var w=0;w<this.m.t;++w){var I=32767&b[w],L=I*this.mpl+((I*this.mph+(b[w]>>15)*this.mpl&this.um)<<15)&b.DM;for(b[I=w+this.m.t]+=this.m.am(0,L,b,w,0,this.m.t);b[I]>=b.DV;)b[I]-=b.DV,b[++I]++}b.clamp(),b.drShiftTo(this.m.t,b),b.compareTo(this.m)>=0&&b.subTo(this.m,b)},$.prototype.mulTo=function(b,w,I){b.multiplyTo(w,I),this.reduce(I)},$.prototype.sqrTo=function(b,w){b.squareTo(w),this.reduce(w)},M.prototype.copyTo=function(b){for(var w=this.t-1;w>=0;--w)b[w]=this[w];b.t=this.t,b.s=this.s},M.prototype.fromInt=function(b){this.t=1,this.s=b<0?-1:0,b>0?this[0]=b:b<-1?this[0]=b+this.DV:this.t=0},M.prototype.fromString=function(b,w){var I;if(w==16)I=4;else if(w==8)I=3;else if(w==256)I=8;else if(w==2)I=1;else if(w==32)I=5;else{if(w!=4)return void this.fromRadix(b,w);I=2}this.t=0,this.s=0;for(var L=b.length,Q=!1,se=0;--L>=0;){var xe=I==8?255&b[L]:he(b,L);xe<0?b.charAt(L)=="-"&&(Q=!0):(Q=!1,se==0?this[this.t++]=xe:se+I>this.DB?(this[this.t-1]|=(xe&(1<<this.DB-se)-1)<<se,this[this.t++]=xe>>this.DB-se):this[this.t-1]|=xe<<se,(se+=I)>=this.DB&&(se-=this.DB))}I==8&&(128&b[0])!=0&&(this.s=-1,se>0&&(this[this.t-1]|=(1<<this.DB-se)-1<<se)),this.clamp(),Q&&M.ZERO.subTo(this,this)},M.prototype.clamp=function(){for(var b=this.s&this.DM;this.t>0&&this[this.t-1]==b;)--this.t},M.prototype.dlShiftTo=function(b,w){var I;for(I=this.t-1;I>=0;--I)w[I+b]=this[I];for(I=b-1;I>=0;--I)w[I]=0;w.t=this.t+b,w.s=this.s},M.prototype.drShiftTo=function(b,w){for(var I=b;I<this.t;++I)w[I-b]=this[I];w.t=Math.max(this.t-b,0),w.s=this.s},M.prototype.lShiftTo=function(b,w){var I,L=b%this.DB,Q=this.DB-L,se=(1<<Q)-1,xe=Math.floor(b/this.DB),be=this.s<<L&this.DM;for(I=this.t-1;I>=0;--I)w[I+xe+1]=this[I]>>Q|be,be=(this[I]&se)<<L;for(I=xe-1;I>=0;--I)w[I]=0;w[xe]=be,w.t=this.t+xe+1,w.s=this.s,w.clamp()},M.prototype.rShiftTo=function(b,w){w.s=this.s;var I=Math.floor(b/this.DB);if(I>=this.t)w.t=0;else{var L=b%this.DB,Q=this.DB-L,se=(1<<L)-1;w[0]=this[I]>>L;for(var xe=I+1;xe<this.t;++xe)w[xe-I-1]|=(this[xe]&se)<<Q,w[xe-I]=this[xe]>>L;L>0&&(w[this.t-I-1]|=(this.s&se)<<Q),w.t=this.t-I,w.clamp()}},M.prototype.subTo=function(b,w){for(var I=0,L=0,Q=Math.min(b.t,this.t);I<Q;)L+=this[I]-b[I],w[I++]=L&this.DM,L>>=this.DB;if(b.t<this.t){for(L-=b.s;I<this.t;)L+=this[I],w[I++]=L&this.DM,L>>=this.DB;L+=this.s}else{for(L+=this.s;I<b.t;)L-=b[I],w[I++]=L&this.DM,L>>=this.DB;L-=b.s}w.s=L<0?-1:0,L<-1?w[I++]=this.DV+L:L>0&&(w[I++]=L),w.t=I,w.clamp()},M.prototype.multiplyTo=function(b,w){var I=this.abs(),L=b.abs(),Q=I.t;for(w.t=Q+L.t;--Q>=0;)w[Q]=0;for(Q=0;Q<L.t;++Q)w[Q+I.t]=I.am(0,L[Q],w,Q,0,I.t);w.s=0,w.clamp(),this.s!=b.s&&M.ZERO.subTo(w,w)},M.prototype.squareTo=function(b){for(var w=this.abs(),I=b.t=2*w.t;--I>=0;)b[I]=0;for(I=0;I<w.t-1;++I){var L=w.am(I,w[I],b,2*I,0,1);(b[I+w.t]+=w.am(I+1,2*w[I],b,2*I+1,L,w.t-I-1))>=w.DV&&(b[I+w.t]-=w.DV,b[I+w.t+1]=1)}b.t>0&&(b[b.t-1]+=w.am(I,w[I],b,2*I,0,1)),b.s=0,b.clamp()},M.prototype.divRemTo=function(b,w,I){var L=b.abs();if(!(L.t<=0)){var Q=this.abs();if(Q.t<L.t)return w?.fromInt(0),void(I!=null&&this.copyTo(I));I==null&&(I=ee());var se=ee(),xe=this.s,be=b.s,ve=this.DB-ce(L[L.t-1]);ve>0?(L.lShiftTo(ve,se),Q.lShiftTo(ve,I)):(L.copyTo(se),Q.copyTo(I));var we=se.t,Ce=se[we-1];if(Ce!=0){var Fe=Ce*(1<<this.F1)+(we>1?se[we-2]>>this.F2:0),Me=this.FV/Fe,Ze=(1<<this.F1)/Fe,Ye=1<<this.F2,tt=I.t,ae=tt-we,Re=w??ee();for(se.dlShiftTo(ae,Re),I.compareTo(Re)>=0&&(I[I.t++]=1,I.subTo(Re,I)),M.ONE.dlShiftTo(we,Re),Re.subTo(se,se);se.t<we;)se[se.t++]=0;for(;--ae>=0;){var De=I[--tt]==Ce?this.DM:Math.floor(I[tt]*Me+(I[tt-1]+Ye)*Ze);if((I[tt]+=se.am(0,De,I,ae,0,we))<De)for(se.dlShiftTo(ae,Re),I.subTo(Re,I);I[tt]<--De;)I.subTo(Re,I)}w!=null&&(I.drShiftTo(we,w),xe!=be&&M.ZERO.subTo(w,w)),I.t=we,I.clamp(),ve>0&&I.rShiftTo(ve,I),xe<0&&M.ZERO.subTo(I,I)}}},M.prototype.invDigit=function(){if(this.t<1)return 0;var b=this[0];if((1&b)==0)return 0;var w=3&b;return(w=(w=(w=(w=w*(2-(15&b)*w)&15)*(2-(255&b)*w)&255)*(2-((65535&b)*w&65535))&65535)*(2-b*w%this.DV)%this.DV)>0?this.DV-w:-w},M.prototype.isEven=function(){return(this.t>0?1&this[0]:this.s)==0},M.prototype.exp=function(b,w){if(b>4294967295||b<1)return M.ONE;var I=ee(),L=ee(),Q=w.convert(this),se=ce(b)-1;for(Q.copyTo(I);--se>=0;)if(w.sqrTo(I,L),(b&1<<se)>0)w.mulTo(L,Q,I);else{var xe=I;I=L,L=xe}return w.revert(I)},M.prototype.toString=function(b){if(this.s<0)return"-"+this.negate().toString(b);var w;if(b==16)w=4;else if(b==8)w=3;else if(b==2)w=1;else if(b==32)w=5;else{if(b!=4)return this.toRadix(b);w=2}var I,L=(1<<w)-1,Q=!1,se="",xe=this.t,be=this.DB-xe*this.DB%w;if(xe-- >0)for(be<this.DB&&(I=this[xe]>>be)>0&&(Q=!0,se=ke(I));xe>=0;)be<w?(I=(this[xe]&(1<<be)-1)<<w-be,I|=this[--xe]>>(be+=this.DB-w)):(I=this[xe]>>(be-=w)&L,be<=0&&(be+=this.DB,--xe)),I>0&&(Q=!0),Q&&(se+=ke(I));return Q?se:"0"},M.prototype.negate=function(){var b=ee();return M.ZERO.subTo(this,b),b},M.prototype.abs=function(){return this.s<0?this.negate():this},M.prototype.compareTo=function(b){var w=this.s-b.s;if(w!=0)return w;var I=this.t;if((w=I-b.t)!=0)return this.s<0?-w:w;for(;--I>=0;)if((w=this[I]-b[I])!=0)return w;return 0},M.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+ce(this[this.t-1]^this.s&this.DM)},M.prototype.mod=function(b){var w=ee();return this.abs().divRemTo(b,null,w),this.s<0&&w.compareTo(M.ZERO)>0&&b.subTo(w,w),w},M.prototype.modPowInt=function(b,w){var I;return I=b<256||w.isEven()?new Ue(w):new $(w),this.exp(b,I)},M.ZERO=Oe(0),M.ONE=Oe(1),We.prototype.convert=me,We.prototype.revert=me,We.prototype.mulTo=function(b,w,I){b.multiplyTo(w,I)},We.prototype.sqrTo=function(b,w){b.squareTo(w)},ge.prototype.convert=function(b){if(b.s<0||b.t>2*this.m.t)return b.mod(this.m);if(b.compareTo(this.m)<0)return b;var w=ee();return b.copyTo(w),this.reduce(w),w},ge.prototype.revert=function(b){return b},ge.prototype.reduce=function(b){for(b.drShiftTo(this.m.t-1,this.r2),b.t>this.m.t+1&&(b.t=this.m.t+1,b.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);b.compareTo(this.r2)<0;)b.dAddOffset(1,this.m.t+1);for(b.subTo(this.r2,b);b.compareTo(this.m)>=0;)b.subTo(this.m,b)},ge.prototype.mulTo=function(b,w,I){b.multiplyTo(w,I),this.reduce(I)},ge.prototype.sqrTo=function(b,w){b.squareTo(w),this.reduce(w)};var Be=[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],ie=(1<<26)/Be[Be.length-1];function B(){this.i=0,this.j=0,this.S=new Array}M.prototype.chunkSize=function(b){return Math.floor(Math.LN2*this.DB/Math.log(b))},M.prototype.toRadix=function(b){if(b==null&&(b=10),this.signum()==0||b<2||b>36)return"0";var w=this.chunkSize(b),I=Math.pow(b,w),L=Oe(I),Q=ee(),se=ee(),xe="";for(this.divRemTo(L,Q,se);Q.signum()>0;)xe=(I+se.intValue()).toString(b).substr(1)+xe,Q.divRemTo(L,Q,se);return se.intValue().toString(b)+xe},M.prototype.fromRadix=function(b,w){this.fromInt(0),w==null&&(w=10);for(var I=this.chunkSize(w),L=Math.pow(w,I),Q=!1,se=0,xe=0,be=0;be<b.length;++be){var ve=he(b,be);ve<0?b.charAt(be)=="-"&&this.signum()==0&&(Q=!0):(xe=w*xe+ve,++se>=I&&(this.dMultiply(L),this.dAddOffset(xe,0),se=0,xe=0))}se>0&&(this.dMultiply(Math.pow(w,se)),this.dAddOffset(xe,0)),Q&&M.ZERO.subTo(this,this)},M.prototype.fromNumber=function(b,w,I){if(typeof w=="number")if(b<2)this.fromInt(1);else for(this.fromNumber(b,I),this.testBit(b-1)||this.bitwiseTo(M.ONE.shiftLeft(b-1),de,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(w);)this.dAddOffset(2,0),this.bitLength()>b&&this.subTo(M.ONE.shiftLeft(b-1),this);else{var L=new Array,Q=7&b;L.length=1+(b>>3),w.nextBytes(L),Q>0?L[0]&=(1<<Q)-1:L[0]=0,this.fromString(L,256)}},M.prototype.bitwiseTo=function(b,w,I){var L,Q,se=Math.min(b.t,this.t);for(L=0;L<se;++L)I[L]=w(this[L],b[L]);if(b.t<this.t){for(Q=b.s&this.DM,L=se;L<this.t;++L)I[L]=w(this[L],Q);I.t=this.t}else{for(Q=this.s&this.DM,L=se;L<b.t;++L)I[L]=w(Q,b[L]);I.t=b.t}I.s=w(this.s,b.s),I.clamp()},M.prototype.changeBit=function(b,w){var I=M.ONE.shiftLeft(b);return this.bitwiseTo(I,w,I),I},M.prototype.addTo=function(b,w){for(var I=0,L=0,Q=Math.min(b.t,this.t);I<Q;)L+=this[I]+b[I],w[I++]=L&this.DM,L>>=this.DB;if(b.t<this.t){for(L+=b.s;I<this.t;)L+=this[I],w[I++]=L&this.DM,L>>=this.DB;L+=this.s}else{for(L+=this.s;I<b.t;)L+=b[I],w[I++]=L&this.DM,L>>=this.DB;L+=b.s}w.s=L<0?-1:0,L>0?w[I++]=L:L<-1&&(w[I++]=this.DV+L),w.t=I,w.clamp()},M.prototype.dMultiply=function(b){this[this.t]=this.am(0,b-1,this,0,0,this.t),++this.t,this.clamp()},M.prototype.dAddOffset=function(b,w){if(b!=0){for(;this.t<=w;)this[this.t++]=0;for(this[w]+=b;this[w]>=this.DV;)this[w]-=this.DV,++w>=this.t&&(this[this.t++]=0),++this[w]}},M.prototype.multiplyLowerTo=function(b,w,I){var L,Q=Math.min(this.t+b.t,w);for(I.s=0,I.t=Q;Q>0;)I[--Q]=0;for(L=I.t-this.t;Q<L;++Q)I[Q+this.t]=this.am(0,b[Q],I,Q,0,this.t);for(L=Math.min(b.t,w);Q<L;++Q)this.am(0,b[Q],I,Q,0,w-Q);I.clamp()},M.prototype.multiplyUpperTo=function(b,w,I){--w;var L=I.t=this.t+b.t-w;for(I.s=0;--L>=0;)I[L]=0;for(L=Math.max(w-this.t,0);L<b.t;++L)I[this.t+L-w]=this.am(w-L,b[L],I,0,0,this.t+L-w);I.clamp(),I.drShiftTo(1,I)},M.prototype.modInt=function(b){if(b<=0)return 0;var w=this.DV%b,I=this.s<0?b-1:0;if(this.t>0)if(w==0)I=this[0]%b;else for(var L=this.t-1;L>=0;--L)I=(w*I+this[L])%b;return I},M.prototype.millerRabin=function(b){var w=this.subtract(M.ONE),I=w.getLowestSetBit();if(I<=0)return!1;var L=w.shiftRight(I);(b=b+1>>1)>Be.length&&(b=Be.length);for(var Q=ee(),se=0;se<b;++se){Q.fromInt(Be[Math.floor(Math.random()*Be.length)]);var xe=Q.modPow(L,this);if(xe.compareTo(M.ONE)!=0&&xe.compareTo(w)!=0){for(var be=1;be++<I&&xe.compareTo(w)!=0;)if((xe=xe.modPowInt(2,this)).compareTo(M.ONE)==0)return!1;if(xe.compareTo(w)!=0)return!1}}return!0},M.prototype.clone=function(){var b=ee();return this.copyTo(b),b},M.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]},M.prototype.byteValue=function(){return this.t==0?this.s:this[0]<<24>>24},M.prototype.shortValue=function(){return this.t==0?this.s:this[0]<<16>>16},M.prototype.signum=function(){return this.s<0?-1:this.t<=0||this.t==1&&this[0]<=0?0:1},M.prototype.toByteArray=function(){var b=this.t,w=new Array;w[0]=this.s;var I,L=this.DB-b*this.DB%8,Q=0;if(b-- >0)for(L<this.DB&&(I=this[b]>>L)!=(this.s&this.DM)>>L&&(w[Q++]=I|this.s<<this.DB-L);b>=0;)L<8?(I=(this[b]&(1<<L)-1)<<8-L,I|=this[--b]>>(L+=this.DB-8)):(I=this[b]>>(L-=8)&255,L<=0&&(L+=this.DB,--b)),(128&I)!=0&&(I|=-256),Q==0&&(128&this.s)!=(128&I)&&++Q,(Q>0||I!=this.s)&&(w[Q++]=I);return w},M.prototype.equals=function(b){return this.compareTo(b)==0},M.prototype.min=function(b){return this.compareTo(b)<0?this:b},M.prototype.max=function(b){return this.compareTo(b)>0?this:b},M.prototype.and=function(b){var w=ee();return this.bitwiseTo(b,W,w),w},M.prototype.or=function(b){var w=ee();return this.bitwiseTo(b,de,w),w},M.prototype.xor=function(b){var w=ee();return this.bitwiseTo(b,te,w),w},M.prototype.andNot=function(b){var w=ee();return this.bitwiseTo(b,Te,w),w},M.prototype.not=function(){for(var b=ee(),w=0;w<this.t;++w)b[w]=this.DM&~this[w];return b.t=this.t,b.s=~this.s,b},M.prototype.shiftLeft=function(b){var w=ee();return b<0?this.rShiftTo(-b,w):this.lShiftTo(b,w),w},M.prototype.shiftRight=function(b){var w=ee();return b<0?this.lShiftTo(-b,w):this.rShiftTo(b,w),w},M.prototype.getLowestSetBit=function(){for(var b=0;b<this.t;++b)if(this[b]!=0)return b*this.DB+je(this[b]);return this.s<0?this.t*this.DB:-1},M.prototype.bitCount=function(){for(var b=0,w=this.s&this.DM,I=0;I<this.t;++I)b+=He(this[I]^w);return b},M.prototype.testBit=function(b){var w=Math.floor(b/this.DB);return w>=this.t?this.s!=0:(this[w]&1<<b%this.DB)!=0},M.prototype.setBit=function(b){return this.changeBit(b,de)},M.prototype.clearBit=function(b){return this.changeBit(b,Te)},M.prototype.flipBit=function(b){return this.changeBit(b,te)},M.prototype.add=function(b){var w=ee();return this.addTo(b,w),w},M.prototype.subtract=function(b){var w=ee();return this.subTo(b,w),w},M.prototype.multiply=function(b){var w=ee();return this.multiplyTo(b,w),w},M.prototype.divide=function(b){var w=ee();return this.divRemTo(b,w,null),w},M.prototype.remainder=function(b){var w=ee();return this.divRemTo(b,null,w),w},M.prototype.divideAndRemainder=function(b){var w=ee(),I=ee();return this.divRemTo(b,w,I),new Array(w,I)},M.prototype.modPow=function(b,w){var I,L,Q=b.bitLength(),se=Oe(1);if(Q<=0)return se;I=Q<18?1:Q<48?3:Q<144?4:Q<768?5:6,L=Q<8?new Ue(w):w.isEven()?new ge(w):new $(w);var xe=new Array,be=3,ve=I-1,we=(1<<I)-1;if(xe[1]=L.convert(this),I>1){var Ce=ee();for(L.sqrTo(xe[1],Ce);be<=we;)xe[be]=ee(),L.mulTo(Ce,xe[be-2],xe[be]),be+=2}var Fe,Me,Ze=b.t-1,Ye=!0,tt=ee();for(Q=ce(b[Ze])-1;Ze>=0;){for(Q>=ve?Fe=b[Ze]>>Q-ve&we:(Fe=(b[Ze]&(1<<Q+1)-1)<<ve-Q,Ze>0&&(Fe|=b[Ze-1]>>this.DB+Q-ve)),be=I;(1&Fe)==0;)Fe>>=1,--be;if((Q-=be)<0&&(Q+=this.DB,--Ze),Ye)xe[Fe].copyTo(se),Ye=!1;else{for(;be>1;)L.sqrTo(se,tt),L.sqrTo(tt,se),be-=2;be>0?L.sqrTo(se,tt):(Me=se,se=tt,tt=Me),L.mulTo(tt,xe[Fe],se)}for(;Ze>=0&&(b[Ze]&1<<Q)==0;)L.sqrTo(se,tt),Me=se,se=tt,tt=Me,--Q<0&&(Q=this.DB-1,--Ze)}return L.revert(se)},M.prototype.modInverse=function(b){var w=b.isEven();if(this.isEven()&&w||b.signum()==0)return M.ZERO;for(var I=b.clone(),L=this.clone(),Q=Oe(1),se=Oe(0),xe=Oe(0),be=Oe(1);I.signum()!=0;){for(;I.isEven();)I.rShiftTo(1,I),w?(Q.isEven()&&se.isEven()||(Q.addTo(this,Q),se.subTo(b,se)),Q.rShiftTo(1,Q)):se.isEven()||se.subTo(b,se),se.rShiftTo(1,se);for(;L.isEven();)L.rShiftTo(1,L),w?(xe.isEven()&&be.isEven()||(xe.addTo(this,xe),be.subTo(b,be)),xe.rShiftTo(1,xe)):be.isEven()||be.subTo(b,be),be.rShiftTo(1,be);I.compareTo(L)>=0?(I.subTo(L,I),w&&Q.subTo(xe,Q),se.subTo(be,se)):(L.subTo(I,L),w&&xe.subTo(Q,xe),be.subTo(se,be))}return L.compareTo(M.ONE)!=0?M.ZERO:be.compareTo(b)>=0?be.subtract(b):be.signum()<0?(be.addTo(b,be),be.signum()<0?be.add(b):be):be},M.prototype.pow=function(b){return this.exp(b,new We)},M.prototype.gcd=function(b){var w=this.s<0?this.negate():this.clone(),I=b.s<0?b.negate():b.clone();if(w.compareTo(I)<0){var L=w;w=I,I=L}var Q=w.getLowestSetBit(),se=I.getLowestSetBit();if(se<0)return w;for(Q<se&&(se=Q),se>0&&(w.rShiftTo(se,w),I.rShiftTo(se,I));w.signum()>0;)(Q=w.getLowestSetBit())>0&&w.rShiftTo(Q,w),(Q=I.getLowestSetBit())>0&&I.rShiftTo(Q,I),w.compareTo(I)>=0?(w.subTo(I,w),w.rShiftTo(1,w)):(I.subTo(w,I),I.rShiftTo(1,I));return se>0&&I.lShiftTo(se,I),I},M.prototype.isProbablePrime=function(b){var w,I=this.abs();if(I.t==1&&I[0]<=Be[Be.length-1]){for(w=0;w<Be.length;++w)if(I[0]==Be[w])return!0;return!1}if(I.isEven())return!1;for(w=1;w<Be.length;){for(var L=Be[w],Q=w+1;Q<Be.length&&L<ie;)L*=Be[Q++];for(L=I.modInt(L);w<Q;)if(L%Be[w++]==0)return!1}return I.millerRabin(b)},M.prototype.square=function(){var b=ee();return this.squareTo(b),b},B.prototype.init=function(b){var w,I,L;for(w=0;w<256;++w)this.S[w]=w;for(I=0,w=0;w<256;++w)I=I+this.S[w]+b[w%b.length]&255,L=this.S[w],this.S[w]=this.S[I],this.S[I]=L;this.i=0,this.j=0},B.prototype.next=function(){var b;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,b=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=b,this.S[b+this.S[this.i]&255]};var N,k,H;function ne(){(function(b){k[H++]^=255&b,k[H++]^=b>>8&255,k[H++]^=b>>16&255,k[H++]^=b>>24&255,H>=256&&(H-=256)})(new Date().getTime())}if(k==null){var le;if(k=new Array,H=0,T!==void 0&&(T.crypto!==void 0||T.msCrypto!==void 0)){var Ee=T.crypto||T.msCrypto;if(Ee.getRandomValues){var J=new Uint8Array(32);for(Ee.getRandomValues(J),le=0;le<32;++le)k[H++]=J[le]}else if(C.appName=="Netscape"&&C.appVersion<"5"){var _e=T.crypto.random(32);for(le=0;le<_e.length;++le)k[H++]=255&_e.charCodeAt(le)}}for(;H<256;)le=Math.floor(65536*Math.random()),k[H++]=le>>>8,k[H++]=255&le;H=0,ne()}function Ie(){if(N==null){for(ne(),(N=(function(){return new B})()).init(k),H=0;H<k.length;++H)k[H]=0;H=0}return N.next()}function ye(){}function at(_,b){return new M(_,b)}function ht(_,b,w){for(var I="",L=0;I.length<b;)I+=w(String.fromCharCode.apply(String,_.concat([(4278190080&L)>>24,(16711680&L)>>16,(65280&L)>>8,255&L]))),L+=1;return I}function Je(){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 gt(_,b){this.x=b,this.q=_}function Y(_,b,w,I){this.curve=_,this.x=b,this.y=w,this.z=I??M.ONE,this.zinv=null}function U(_,b,w){this.q=_,this.a=this.fromBigInteger(b),this.b=this.fromBigInteger(w),this.infinity=new Y(this,null,null)}ye.prototype.nextBytes=function(b){var w;for(w=0;w<b.length;++w)b[w]=Ie()},Je.prototype.doPublic=function(b){return b.modPowInt(this.e,this.n)},Je.prototype.setPublic=function(b,w){if(this.isPublic=!0,this.isPrivate=!1,typeof b!="string")this.n=b,this.e=w;else{if(!(b!=null&&w!=null&&b.length>0&&w.length>0))throw"Invalid RSA public key";this.n=at(b,16),this.e=parseInt(w,16)}},Je.prototype.encrypt=function(b){var w=(function(se,xe){if(xe<se.length+11)throw"Message too long for RSA";for(var be=new Array,ve=se.length-1;ve>=0&&xe>0;){var we=se.charCodeAt(ve--);we<128?be[--xe]=we:we>127&&we<2048?(be[--xe]=63&we|128,be[--xe]=we>>6|192):(be[--xe]=63&we|128,be[--xe]=we>>6&63|128,be[--xe]=we>>12|224)}be[--xe]=0;for(var Ce=new ye,Fe=new Array;xe>2;){for(Fe[0]=0;Fe[0]==0;)Ce.nextBytes(Fe);be[--xe]=Fe[0]}return be[--xe]=2,be[--xe]=0,new M(be)})(b,this.n.bitLength()+7>>3);if(w==null)return null;var I=this.doPublic(w);if(I==null)return null;var L=I.toString(16);return(1&L.length)==0?L:"0"+L},Je.prototype.encryptOAEP=function(b,w,I){var L=(function(be,ve,we,Ce){var Fe=j.crypto.MessageDigest,Me=j.crypto.Util,Ze=null;if(we||(we="sha1"),typeof we=="string"&&(Ze=Fe.getCanonicalAlgName(we),Ce=Fe.getHashLength(Ze),we=function(pt){return hr(Me.hashHex(ir(pt),Ze))}),be.length+2*Ce+2>ve)throw"Message too long for RSA";var Ye,tt="";for(Ye=0;Ye<ve-be.length-2*Ce-2;Ye+=1)tt+="\0";var ae=we("")+tt+""+be,Re=new Array(Ce);new ye().nextBytes(Re);var De=ht(Re,ae.length,we),Pe=[];for(Ye=0;Ye<ae.length;Ye+=1)Pe[Ye]=ae.charCodeAt(Ye)^De.charCodeAt(Ye);var Qe=ht(Pe,Re.length,we),it=[0];for(Ye=0;Ye<Re.length;Ye+=1)it[Ye+1]=Re[Ye]^Qe.charCodeAt(Ye);return new M(it.concat(Pe))})(b,this.n.bitLength()+7>>3,w,I);if(L==null)return null;var Q=this.doPublic(L);if(Q==null)return null;var se=Q.toString(16);return(1&se.length)==0?se:"0"+se},Je.prototype.type="RSA",gt.prototype.equals=function(b){return b==this||this.q.equals(b.q)&&this.x.equals(b.x)},gt.prototype.toBigInteger=function(){return this.x},gt.prototype.negate=function(){return new gt(this.q,this.x.negate().mod(this.q))},gt.prototype.add=function(b){return new gt(this.q,this.x.add(b.toBigInteger()).mod(this.q))},gt.prototype.subtract=function(b){return new gt(this.q,this.x.subtract(b.toBigInteger()).mod(this.q))},gt.prototype.multiply=function(b){return new gt(this.q,this.x.multiply(b.toBigInteger()).mod(this.q))},gt.prototype.square=function(){return new gt(this.q,this.x.square().mod(this.q))},gt.prototype.divide=function(b){return new gt(this.q,this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q))},Y.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))},Y.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))},Y.prototype.equals=function(b){return b==this||(this.isInfinity()?b.isInfinity():b.isInfinity()?this.isInfinity():!!b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q).equals(M.ZERO)&&b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q).equals(M.ZERO))},Y.prototype.isInfinity=function(){return this.x==null&&this.y==null||this.z.equals(M.ZERO)&&!this.y.toBigInteger().equals(M.ZERO)},Y.prototype.negate=function(){return new Y(this.curve,this.x,this.y.negate(),this.z)},Y.prototype.add=function(b){if(this.isInfinity())return b;if(b.isInfinity())return this;var w=b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q),I=b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q);if(M.ZERO.equals(I))return M.ZERO.equals(w)?this.twice():this.curve.getInfinity();var L=new M("3"),Q=this.x.toBigInteger(),se=this.y.toBigInteger(),xe=(b.x.toBigInteger(),b.y.toBigInteger(),I.square()),be=xe.multiply(I),ve=Q.multiply(xe),we=w.square().multiply(this.z),Ce=we.subtract(ve.shiftLeft(1)).multiply(b.z).subtract(be).multiply(I).mod(this.curve.q),Fe=ve.multiply(L).multiply(w).subtract(se.multiply(be)).subtract(we.multiply(w)).multiply(b.z).add(w.multiply(be)).mod(this.curve.q),Me=be.multiply(this.z).multiply(b.z).mod(this.curve.q);return new Y(this.curve,this.curve.fromBigInteger(Ce),this.curve.fromBigInteger(Fe),Me)},Y.prototype.twice=function(){if(this.isInfinity())return this;if(this.y.toBigInteger().signum()==0)return this.curve.getInfinity();var b=new M("3"),w=this.x.toBigInteger(),I=this.y.toBigInteger(),L=I.multiply(this.z),Q=L.multiply(I).mod(this.curve.q),se=this.curve.a.toBigInteger(),xe=w.square().multiply(b);M.ZERO.equals(se)||(xe=xe.add(this.z.square().multiply(se)));var be=(xe=xe.mod(this.curve.q)).square().subtract(w.shiftLeft(3).multiply(Q)).shiftLeft(1).multiply(L).mod(this.curve.q),ve=xe.multiply(b).multiply(w).subtract(Q.shiftLeft(1)).shiftLeft(2).multiply(Q).subtract(xe.square().multiply(xe)).mod(this.curve.q),we=L.square().multiply(L).shiftLeft(3).mod(this.curve.q);return new Y(this.curve,this.curve.fromBigInteger(be),this.curve.fromBigInteger(ve),we)},Y.prototype.multiply=function(b){if(this.isInfinity())return this;if(b.signum()==0)return this.curve.getInfinity();var w,I=b,L=I.multiply(new M("3")),Q=this.negate(),se=this,xe=this.curve.q.subtract(b),be=xe.multiply(new M("3")),ve=new Y(this.curve,this.x,this.y),we=ve.negate();for(w=L.bitLength()-2;w>0;--w){se=se.twice();var Ce=L.testBit(w);Ce!=I.testBit(w)&&(se=se.add(Ce?this:Q))}for(w=be.bitLength()-2;w>0;--w){ve=ve.twice();var Fe=be.testBit(w);Fe!=xe.testBit(w)&&(ve=ve.add(Fe?ve:we))}return se},Y.prototype.multiplyTwo=function(b,w,I){var L;L=b.bitLength()>I.bitLength()?b.bitLength()-1:I.bitLength()-1;for(var Q=this.curve.getInfinity(),se=this.add(w);L>=0;)Q=Q.twice(),b.testBit(L)?Q=I.testBit(L)?Q.add(se):Q.add(this):I.testBit(L)&&(Q=Q.add(w)),--L;return Q},U.prototype.getQ=function(){return this.q},U.prototype.getA=function(){return this.a},U.prototype.getB=function(){return this.b},U.prototype.equals=function(b){return b==this||this.q.equals(b.q)&&this.a.equals(b.a)&&this.b.equals(b.b)},U.prototype.getInfinity=function(){return this.infinity},U.prototype.fromBigInteger=function(b){return new gt(this.q,b)},U.prototype.decodePointHex=function(b){switch(parseInt(b.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:return null;case 4:case 6:case 7:var w=(b.length-2)/2,I=b.substr(2,w),L=b.substr(w+2,w);return new Y(this,this.fromBigInteger(new M(I,16)),this.fromBigInteger(new M(L,16)));default:return null}},gt.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)},Y.prototype.getEncoded=function(_){var b=function(se,xe){var be=se.toByteArrayUnsigned();if(xe<be.length)be=be.slice(be.length-xe);else for(;xe>be.length;)be.unshift(0);return be},w=this.getX().toBigInteger(),I=this.getY().toBigInteger(),L=b(w,32);return _?I.isEven()?L.unshift(2):L.unshift(3):(L.unshift(4),L=L.concat(b(I,32))),L},Y.decodeFrom=function(_,b){b[0];var w=b.length-1,I=b.slice(1,1+w/2),L=b.slice(1+w/2,1+w);I.unshift(0),L.unshift(0);var Q=new M(I),se=new M(L);return new Y(_,_.fromBigInteger(Q),_.fromBigInteger(se))},Y.decodeFromHex=function(_,b){b.substr(0,2);var w=b.length-2,I=b.substr(2,w/2),L=b.substr(2+w/2,w/2),Q=new M(I,16),se=new M(L,16);return new Y(_,_.fromBigInteger(Q),_.fromBigInteger(se))},Y.prototype.add2D=function(_){if(this.isInfinity())return _;if(_.isInfinity())return this;if(this.x.equals(_.x))return this.y.equals(_.y)?this.twice():this.curve.getInfinity();var b=_.x.subtract(this.x),w=_.y.subtract(this.y).divide(b),I=w.square().subtract(this.x).subtract(_.x),L=w.multiply(this.x.subtract(I)).subtract(this.y);return new Y(this.curve,I,L)},Y.prototype.twice2D=function(){if(this.isInfinity())return this;if(this.y.toBigInteger().signum()==0)return this.curve.getInfinity();var _=this.curve.fromBigInteger(M.valueOf(2)),b=this.curve.fromBigInteger(M.valueOf(3)),w=this.x.square().multiply(b).add(this.curve.a).divide(this.y.multiply(_)),I=w.square().subtract(this.x.multiply(_)),L=w.multiply(this.x.subtract(I)).subtract(this.y);return new Y(this.curve,I,L)},Y.prototype.multiply2D=function(_){if(this.isInfinity())return this;if(_.signum()==0)return this.curve.getInfinity();var b,w=_,I=w.multiply(new M("3")),L=this.negate(),Q=this;for(b=I.bitLength()-2;b>0;--b){Q=Q.twice();var se=I.testBit(b);se!=w.testBit(b)&&(Q=Q.add2D(se?this:L))}return Q},Y.prototype.isOnCurve=function(){var _=this.getX().toBigInteger(),b=this.getY().toBigInteger(),w=this.curve.getA().toBigInteger(),I=this.curve.getB().toBigInteger(),L=this.curve.getQ(),Q=b.multiply(b).mod(L),se=_.multiply(_).multiply(_).add(w.multiply(_)).add(I).mod(L);return Q.equals(se)},Y.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"},Y.prototype.validate=function(){var _=this.curve.getQ();if(this.isInfinity())throw new Error("Point is at infinity.");var b=this.getX().toBigInteger(),w=this.getY().toBigInteger();if(b.compareTo(M.ONE)<0||b.compareTo(_.subtract(M.ONE))>0)throw new Error("x coordinate out of bounds");if(w.compareTo(M.ONE)<0||w.compareTo(_.subtract(M.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(_).isInfinity())throw new Error("Point is not a scalar multiple of G.");return!0};var z=(function(){var _=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"),b=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),w={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:`
230
230
  `,r:"\r",t:" "};function I(se,xe,be){return xe?w[xe]:String.fromCharCode(parseInt(be,16))}var L=new String(""),Q=Object.hasOwnProperty;return function(se,xe){var be,ve,we=se.match(_),Ce=we[0],Fe=!1;Ce==="{"?be={}:Ce==="["?be=[]:(be=[],Fe=!0);for(var Me=[be],Ze=1-Fe,Ye=we.length;Ze<Ye;++Ze){var tt;switch((Ce=we[Ze]).charCodeAt(0)){default:(tt=Me[0])[ve||tt.length]=+Ce,ve=void 0;break;case 34:if((Ce=Ce.substring(1,Ce.length-1)).indexOf("\\")!==-1&&(Ce=Ce.replace(b,I)),tt=Me[0],!ve){if(!(tt instanceof Array)){ve=Ce||L;break}ve=tt.length}tt[ve]=Ce,ve=void 0;break;case 91:tt=Me[0],Me.unshift(tt[ve||tt.length]=[]),ve=void 0;break;case 93:Me.shift();break;case 102:(tt=Me[0])[ve||tt.length]=!1,ve=void 0;break;case 110:(tt=Me[0])[ve||tt.length]=null,ve=void 0;break;case 116:(tt=Me[0])[ve||tt.length]=!0,ve=void 0;break;case 123:tt=Me[0],Me.unshift(tt[ve||tt.length]={}),ve=void 0;break;case 125:Me.shift()}}if(Fe){if(Me.length!==1)throw new Error;be=be[0]}else if(Me.length)throw new Error;return xe&&(be=(function ae(Re,De){var Pe=Re[De];if(Pe&&(Pe===void 0?"undefined":A(Pe))==="object"){var Qe=null;for(var it in Pe)if(Q.call(Pe,it)&&Pe!==Re){var _t=ae(Pe,it);_t!==void 0?Pe[it]=_t:(Qe||(Qe=[]),Qe.push(it))}if(Qe)for(var pt=Qe.length;--pt>=0;)delete Pe[Qe[pt]]}return xe.call(Re,De,Pe)})({"":be},"")),be}})();j!==void 0&&j||(i.KJUR=j={}),j.asn1!==void 0&&j.asn1||(j.asn1={}),j.asn1.ASN1Util=new function(){this.integerToByteHex=function(_){var b=_.toString(16);return b.length%2==1&&(b="0"+b),b},this.bigIntToMinTwosComplementsHex=function(_){var b=_.toString(16);if(b.substr(0,1)!="-")b.length%2==1?b="0"+b:b.match(/^[0-7]/)||(b="00"+b);else{var w=b.substr(1).length;w%2==1?w+=1:b.match(/^[0-7]/)||(w+=2);for(var I="",L=0;L<w;L++)I+="f";b=new M(I,16).xor(_).add(M.ONE).toString(16).replace(/^-/,"")}return b},this.getPEMStringFromHex=function(_,b){return ze(_,b)},this.newObject=function(_){var b=j.asn1,w=b.ASN1Object,I=b.DERBoolean,L=b.DERInteger,Q=b.DERBitString,se=b.DEROctetString,xe=b.DERNull,be=b.DERObjectIdentifier,ve=b.DEREnumerated,we=b.DERUTF8String,Ce=b.DERNumericString,Fe=b.DERPrintableString,Me=b.DERTeletexString,Ze=b.DERIA5String,Ye=b.DERUTCTime,tt=b.DERGeneralizedTime,ae=b.DERVisibleString,Re=b.DERBMPString,De=b.DERSequence,Pe=b.DERSet,Qe=b.DERTaggedObject,it=b.ASN1Util.newObject;if(_ instanceof b.ASN1Object)return _;var _t=Object.keys(_);if(_t.length!=1)throw new Error("key of param shall be only one.");var pt=_t[0];if(":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":"+pt+":")==-1)throw new Error("undefined key: "+pt);if(pt=="bool")return new I(_[pt]);if(pt=="int")return new L(_[pt]);if(pt=="bitstr")return new Q(_[pt]);if(pt=="octstr")return new se(_[pt]);if(pt=="null")return new xe(_[pt]);if(pt=="oid")return new be(_[pt]);if(pt=="enum")return new ve(_[pt]);if(pt=="utf8str")return new we(_[pt]);if(pt=="numstr")return new Ce(_[pt]);if(pt=="prnstr")return new Fe(_[pt]);if(pt=="telstr")return new Me(_[pt]);if(pt=="ia5str")return new Ze(_[pt]);if(pt=="utctime")return new Ye(_[pt]);if(pt=="gentime")return new tt(_[pt]);if(pt=="visstr")return new ae(_[pt]);if(pt=="bmpstr")return new Re(_[pt]);if(pt=="asn1")return new w(_[pt]);if(pt=="seq"){for(var Dt=_[pt],bt=[],vt=0;vt<Dt.length;vt++){var Jt=it(Dt[vt]);bt.push(Jt)}return new De({array:bt})}if(pt=="set"){for(Dt=_[pt],bt=[],vt=0;vt<Dt.length;vt++)Jt=it(Dt[vt]),bt.push(Jt);return new Pe({array:bt})}if(pt=="tag"){var Qt=_[pt];if(Object.prototype.toString.call(Qt)==="[object Array]"&&Qt.length==3){var qt=it(Qt[2]);return new Qe({tag:Qt[0],explicit:Qt[1],obj:qt})}return new Qe(Qt)}},this.jsonToASN1HEX=function(_){return this.newObject(_).getEncodedHex()}},j.asn1.ASN1Util.oidHexToInt=function(_){for(var b="",w=parseInt(_.substr(0,2),16),I=(b=Math.floor(w/40)+"."+w%40,""),L=2;L<_.length;L+=2){var Q=("00000000"+parseInt(_.substr(L,2),16).toString(2)).slice(-8);I+=Q.substr(1,7),Q.substr(0,1)=="0"&&(b=b+"."+new M(I,2).toString(10),I="")}return b},j.asn1.ASN1Util.oidIntToHex=function(_){var b=function(be){var ve=be.toString(16);return ve.length==1&&(ve="0"+ve),ve},w=function(be){var ve="",we=new M(be,10).toString(2),Ce=7-we.length%7;Ce==7&&(Ce=0);for(var Fe="",Me=0;Me<Ce;Me++)Fe+="0";for(we=Fe+we,Me=0;Me<we.length-1;Me+=7){var Ze=we.substr(Me,7);Me!=we.length-7&&(Ze="1"+Ze),ve+=b(parseInt(Ze,2))}return ve};if(!_.match(/^[0-9.]+$/))throw"malformed oid string: "+_;var I="",L=_.split("."),Q=40*parseInt(L[0])+parseInt(L[1]);I+=b(Q),L.splice(0,2);for(var se=0;se<L.length;se++)I+=w(L[se]);return I},j.asn1.ASN1Object=function(_){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 b=this.hV.length/2,w=b.toString(16);if(w.length%2==1&&(w="0"+w),b<128)return w;var I=w.length/2;if(I>15)throw"ASN.1 length too long to represent by 8x: n = "+b.toString(16);return(128+I).toString(16)+w},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(b){this.params=b},_!=null&&_.tlv!=null&&(this.hTLV=_.tlv,this.isModified=!1)},j.asn1.DERAbstractString=function(_){j.asn1.DERAbstractString.superclass.constructor.call(this),this.getString=function(){return this.s},this.setString=function(b){this.hTLV=null,this.isModified=!0,this.s=b,this.hV=xr(this.s).toLowerCase()},this.setStringHex=function(b){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=b},this.getFreshValueHex=function(){return this.hV},_!==void 0&&(typeof _=="string"?this.setString(_):_.str!==void 0?this.setString(_.str):_.hex!==void 0&&this.setStringHex(_.hex))},Lt(j.asn1.DERAbstractString,j.asn1.ASN1Object),j.asn1.DERAbstractTime=function(_){j.asn1.DERAbstractTime.superclass.constructor.call(this),this.localDateToUTC=function(b){var w=b.getTime()+6e4*b.getTimezoneOffset();return new Date(w)},this.formatDate=function(b,w,I){var L=this.zeroPadding,Q=this.localDateToUTC(b),se=String(Q.getFullYear());w=="utc"&&(se=se.substr(2,2));var xe=se+L(String(Q.getMonth()+1),2)+L(String(Q.getDate()),2)+L(String(Q.getHours()),2)+L(String(Q.getMinutes()),2)+L(String(Q.getSeconds()),2);if(I===!0){var be=Q.getMilliseconds();if(be!=0){var ve=L(String(be),3);xe=xe+"."+(ve=ve.replace(/[0]+$/,""))}}return xe+"Z"},this.zeroPadding=function(b,w){return b.length>=w?b:new Array(w-b.length+1).join("0")+b},this.getString=function(){return this.s},this.setString=function(b){this.hTLV=null,this.isModified=!0,this.s=b,this.hV=kt(b)},this.setByDateValue=function(b,w,I,L,Q,se){var xe=new Date(Date.UTC(b,w-1,I,L,Q,se,0));this.setByDate(xe)},this.getFreshValueHex=function(){return this.hV}},Lt(j.asn1.DERAbstractTime,j.asn1.ASN1Object),j.asn1.DERAbstractStructured=function(_){j.asn1.DERAbstractString.superclass.constructor.call(this),this.setByASN1ObjectArray=function(b){this.hTLV=null,this.isModified=!0,this.asn1Array=b},this.appendASN1Object=function(b){this.hTLV=null,this.isModified=!0,this.asn1Array.push(b)},this.asn1Array=new Array,_!==void 0&&_.array!==void 0&&(this.asn1Array=_.array)},Lt(j.asn1.DERAbstractStructured,j.asn1.ASN1Object),j.asn1.DERBoolean=function(_){j.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=_==0?"010100":"0101ff"},Lt(j.asn1.DERBoolean,j.asn1.ASN1Object),j.asn1.DERInteger=function(_){j.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.setByBigInteger=function(b){this.hTLV=null,this.isModified=!0,this.hV=j.asn1.ASN1Util.bigIntToMinTwosComplementsHex(b)},this.setByInteger=function(b){var w=new M(String(b),10);this.setByBigInteger(w)},this.setValueHex=function(b){this.hV=b},this.getFreshValueHex=function(){return this.hV},_!==void 0&&(_.bigint!==void 0?this.setByBigInteger(_.bigint):_.int!==void 0?this.setByInteger(_.int):typeof _=="number"?this.setByInteger(_):_.hex!==void 0&&this.setValueHex(_.hex))},Lt(j.asn1.DERInteger,j.asn1.ASN1Object),j.asn1.DERBitString=function(_){if(_!==void 0&&_.obj!==void 0){var b=j.asn1.ASN1Util.newObject(_.obj);_.hex="00"+b.getEncodedHex()}j.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(w){this.hTLV=null,this.isModified=!0,this.hV=w},this.setUnusedBitsAndHexValue=function(w,I){if(w<0||7<w)throw"unused bits shall be from 0 to 7: u = "+w;var L="0"+w;this.hTLV=null,this.isModified=!0,this.hV=L+I},this.setByBinaryString=function(w){var I=8-(w=w.replace(/0+$/,"")).length%8;I==8&&(I=0);for(var L=0;L<=I;L++)w+="0";var Q="";for(L=0;L<w.length-1;L+=8){var se=w.substr(L,8),xe=parseInt(se,2).toString(16);xe.length==1&&(xe="0"+xe),Q+=xe}this.hTLV=null,this.isModified=!0,this.hV="0"+I+Q},this.setByBooleanArray=function(w){for(var I="",L=0;L<w.length;L++)w[L]==1?I+="1":I+="0";this.setByBinaryString(I)},this.newFalseArray=function(w){for(var I=new Array(w),L=0;L<w;L++)I[L]=!1;return I},this.getFreshValueHex=function(){return this.hV},_!==void 0&&(typeof _=="string"&&_.toLowerCase().match(/^[0-9a-f]+$/)?this.setHexValueIncludingUnusedBits(_):_.hex!==void 0?this.setHexValueIncludingUnusedBits(_.hex):_.bin!==void 0?this.setByBinaryString(_.bin):_.array!==void 0&&this.setByBooleanArray(_.array))},Lt(j.asn1.DERBitString,j.asn1.ASN1Object),j.asn1.DEROctetString=function(_){if(_!==void 0&&_.obj!==void 0){var b=j.asn1.ASN1Util.newObject(_.obj);_.hex=b.getEncodedHex()}j.asn1.DEROctetString.superclass.constructor.call(this,_),this.hT="04"},Lt(j.asn1.DEROctetString,j.asn1.DERAbstractString),j.asn1.DERNull=function(){j.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},Lt(j.asn1.DERNull,j.asn1.ASN1Object),j.asn1.DERObjectIdentifier=function(_){j.asn1.DERObjectIdentifier.superclass.constructor.call(this),this.hT="06",this.setValueHex=function(b){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=b},this.setValueOidString=function(b){var w=(function(L){var Q=function(Fe){var Me=Fe.toString(16);return Me.length==1&&(Me="0"+Me),Me},se=function(Fe){var Me="",Ze=parseInt(Fe,10).toString(2),Ye=7-Ze.length%7;Ye==7&&(Ye=0);for(var tt="",ae=0;ae<Ye;ae++)tt+="0";for(Ze=tt+Ze,ae=0;ae<Ze.length-1;ae+=7){var Re=Ze.substr(ae,7);ae!=Ze.length-7&&(Re="1"+Re),Me+=Q(parseInt(Re,2))}return Me};try{if(!L.match(/^[0-9.]+$/))return null;var xe="",be=L.split("."),ve=40*parseInt(be[0],10)+parseInt(be[1],10);xe+=Q(ve),be.splice(0,2);for(var we=0;we<be.length;we++)xe+=se(be[we]);return xe}catch{return null}})(b);if(w==null)throw new Error("malformed oid string: "+b);this.hTLV=null,this.isModified=!0,this.s=null,this.hV=w},this.setValueName=function(b){var w=j.asn1.x509.OID.name2oid(b);if(w==="")throw new Error("DERObjectIdentifier oidName undefined: "+b);this.setValueOidString(w)},this.setValueNameOrOid=function(b){b.match(/^[0-2].[0-9.]+$/)?this.setValueOidString(b):this.setValueName(b)},this.getFreshValueHex=function(){return this.hV},this.setByParam=function(b){typeof b=="string"?this.setValueNameOrOid(b):b.oid!==void 0?this.setValueNameOrOid(b.oid):b.name!==void 0?this.setValueNameOrOid(b.name):b.hex!==void 0&&this.setValueHex(b.hex)},_!==void 0&&this.setByParam(_)},Lt(j.asn1.DERObjectIdentifier,j.asn1.ASN1Object),j.asn1.DEREnumerated=function(_){j.asn1.DEREnumerated.superclass.constructor.call(this),this.hT="0a",this.setByBigInteger=function(b){this.hTLV=null,this.isModified=!0,this.hV=j.asn1.ASN1Util.bigIntToMinTwosComplementsHex(b)},this.setByInteger=function(b){var w=new M(String(b),10);this.setByBigInteger(w)},this.setValueHex=function(b){this.hV=b},this.getFreshValueHex=function(){return this.hV},_!==void 0&&(_.int!==void 0?this.setByInteger(_.int):typeof _=="number"?this.setByInteger(_):_.hex!==void 0&&this.setValueHex(_.hex))},Lt(j.asn1.DEREnumerated,j.asn1.ASN1Object),j.asn1.DERUTF8String=function(_){j.asn1.DERUTF8String.superclass.constructor.call(this,_),this.hT="0c"},Lt(j.asn1.DERUTF8String,j.asn1.DERAbstractString),j.asn1.DERNumericString=function(_){j.asn1.DERNumericString.superclass.constructor.call(this,_),this.hT="12"},Lt(j.asn1.DERNumericString,j.asn1.DERAbstractString),j.asn1.DERPrintableString=function(_){j.asn1.DERPrintableString.superclass.constructor.call(this,_),this.hT="13"},Lt(j.asn1.DERPrintableString,j.asn1.DERAbstractString),j.asn1.DERTeletexString=function(_){j.asn1.DERTeletexString.superclass.constructor.call(this,_),this.hT="14"},Lt(j.asn1.DERTeletexString,j.asn1.DERAbstractString),j.asn1.DERIA5String=function(_){j.asn1.DERIA5String.superclass.constructor.call(this,_),this.hT="16"},Lt(j.asn1.DERIA5String,j.asn1.DERAbstractString),j.asn1.DERVisibleString=function(_){j.asn1.DERIA5String.superclass.constructor.call(this,_),this.hT="1a"},Lt(j.asn1.DERVisibleString,j.asn1.DERAbstractString),j.asn1.DERBMPString=function(_){j.asn1.DERBMPString.superclass.constructor.call(this,_),this.hT="1e"},Lt(j.asn1.DERBMPString,j.asn1.DERAbstractString),j.asn1.DERUTCTime=function(_){j.asn1.DERUTCTime.superclass.constructor.call(this,_),this.hT="17",this.setByDate=function(b){this.hTLV=null,this.isModified=!0,this.date=b,this.s=this.formatDate(this.date,"utc"),this.hV=kt(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=kt(this.s)),this.hV},_!==void 0&&(_.str!==void 0?this.setString(_.str):typeof _=="string"&&_.match(/^[0-9]{12}Z$/)?this.setString(_):_.hex!==void 0?this.setStringHex(_.hex):_.date!==void 0&&this.setByDate(_.date))},Lt(j.asn1.DERUTCTime,j.asn1.DERAbstractTime),j.asn1.DERGeneralizedTime=function(_){j.asn1.DERGeneralizedTime.superclass.constructor.call(this,_),this.hT="18",this.withMillis=!1,this.setByDate=function(b){this.hTLV=null,this.isModified=!0,this.date=b,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=kt(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=kt(this.s)),this.hV},_!==void 0&&(_.str!==void 0?this.setString(_.str):typeof _=="string"&&_.match(/^[0-9]{14}Z$/)?this.setString(_):_.hex!==void 0?this.setStringHex(_.hex):_.date!==void 0&&this.setByDate(_.date),_.millis===!0&&(this.withMillis=!0))},Lt(j.asn1.DERGeneralizedTime,j.asn1.DERAbstractTime),j.asn1.DERSequence=function(_){j.asn1.DERSequence.superclass.constructor.call(this,_),this.hT="30",this.getFreshValueHex=function(){for(var b="",w=0;w<this.asn1Array.length;w++)b+=this.asn1Array[w].getEncodedHex();return this.hV=b,this.hV}},Lt(j.asn1.DERSequence,j.asn1.DERAbstractStructured),j.asn1.DERSet=function(_){j.asn1.DERSet.superclass.constructor.call(this,_),this.hT="31",this.sortFlag=!0,this.getFreshValueHex=function(){for(var b=new Array,w=0;w<this.asn1Array.length;w++){var I=this.asn1Array[w];b.push(I.getEncodedHex())}return this.sortFlag==1&&b.sort(),this.hV=b.join(""),this.hV},_!==void 0&&_.sortflag!==void 0&&_.sortflag==0&&(this.sortFlag=!1)},Lt(j.asn1.DERSet,j.asn1.DERAbstractStructured),j.asn1.DERTaggedObject=function(_){j.asn1.DERTaggedObject.superclass.constructor.call(this);var b=j.asn1;this.hT="a0",this.hV="",this.isExplicit=!0,this.asn1Object=null,this.setASN1Object=function(w,I,L){this.hT=I,this.isExplicit=w,this.asn1Object=L,this.isExplicit?(this.hV=this.asn1Object.getEncodedHex(),this.hTLV=null,this.isModified=!0):(this.hV=null,this.hTLV=L.getEncodedHex(),this.hTLV=this.hTLV.replace(/^../,I),this.isModified=!1)},this.getFreshValueHex=function(){return this.hV},this.setByParam=function(w){w.tag!=null&&(this.hT=w.tag),w.explicit!=null&&(this.isExplicit=w.explicit),w.tage!=null&&(this.hT=w.tage,this.isExplicit=!0),w.tagi!=null&&(this.hT=w.tagi,this.isExplicit=!1),w.obj!=null&&(w.obj instanceof b.ASN1Object?(this.asn1Object=w.obj,this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)):A(w.obj)=="object"&&(this.asn1Object=b.ASN1Util.newObject(w.obj),this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)))},_!=null&&this.setByParam(_)},Lt(j.asn1.DERTaggedObject,j.asn1.ASN1Object);var j,Ne,Ve,Le=new function(){};function mt(_){for(var b=new Array,w=0;w<_.length;w++)b[w]=_.charCodeAt(w);return b}function St(_){for(var b="",w=0;w<_.length;w++)b+=String.fromCharCode(_[w]);return b}function Rt(_){for(var b="",w=0;w<_.length;w++){var I=_[w].toString(16);I.length==1&&(I="0"+I),b+=I}return b}function kt(_){return Rt(mt(_))}function Ft(_){return _=(_=(_=_.replace(/\=/g,"")).replace(/\+/g,"-")).replace(/\//g,"_")}function on(_){return _.length%4==2?_+="==":_.length%4==3&&(_+="="),_=(_=_.replace(/-/g,"+")).replace(/_/g,"/")}function er(_){return _.length%2==1&&(_="0"+_),Ft(O(_))}function Ut(_){return G(on(_))}function xr(_){return Wt(zt(_))}function Bt(_){return decodeURIComponent(ln(_))}function hr(_){for(var b="",w=0;w<_.length-1;w+=2)b+=String.fromCharCode(parseInt(_.substr(w,2),16));return b}function ir(_){for(var b="",w=0;w<_.length;w++)b+=("0"+_.charCodeAt(w).toString(16)).slice(-2);return b}function Wr(_){return O(_)}function V(_){var b=Wr(_).replace(/(.{64})/g,`$1\r
231
231
  `);return b=b.replace(/\r\n$/,"")}function K(_){return G(_.replace(/[^0-9A-Za-z\/+=]*/g,""))}function ze(_,b){return"-----BEGIN "+b+`-----\r
@@ -303,4 +303,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
303
303
  `},typeof _=="string"&&(_.indexOf("-----BEGIN")!=-1?this.readCertPEM(_):j.lang.String.isHex(_)&&this.readCertHex(_))}Je.prototype.sign=function(_,b){var w=(function(L){return j.crypto.Util.hashString(L,b)})(_);return this.signWithMessageHash(w,b)},Je.prototype.signWithMessageHash=function(_,b){var w=at(j.crypto.Util.getPaddedDigestInfoHex(_,b,this.n.bitLength()),16);return gr(this.doPrivate(w).toString(16),this.n.bitLength())},Je.prototype.signPSS=function(_,b,w){var I=(function(Q){return j.crypto.Util.hashHex(Q,b)})(ir(_));return w===void 0&&(w=-1),this.signWithMessageHashPSS(I,b,w)},Je.prototype.signWithMessageHashPSS=function(_,b,w){var I,L=hr(_),Q=L.length,se=this.n.bitLength()-1,xe=Math.ceil(se/8),be=function(ae){return j.crypto.Util.hashHex(ae,b)};if(w===-1||w===void 0)w=Q;else if(w===-2)w=xe-Q-2;else if(w<-2)throw new Error("invalid salt length");if(xe<Q+w+2)throw new Error("data too long");var ve="";w>0&&(ve=new Array(w),new ye().nextBytes(ve),ve=String.fromCharCode.apply(String,ve));var we=hr(be(ir("\0\0\0\0\0\0\0\0"+L+ve))),Ce=[];for(I=0;I<xe-w-Q-2;I+=1)Ce[I]=0;var Fe=String.fromCharCode.apply(String,Ce)+""+ve,Me=li(we,Fe.length,be),Ze=[];for(I=0;I<Fe.length;I+=1)Ze[I]=Fe.charCodeAt(I)^Me.charCodeAt(I);var Ye=65280>>8*xe-se&255;for(Ze[0]&=~Ye,I=0;I<Q;I++)Ze.push(we.charCodeAt(I));return Ze.push(188),gr(this.doPrivate(new M(Ze)).toString(16),this.n.bitLength())},Je.prototype.verify=function(_,b){if((b=b.toLowerCase()).match(/^[0-9a-f]+$/)==null)return!1;var w=at(b,16),I=this.n.bitLength();if(w.bitLength()>I)return!1;var L=this.doPublic(w).toString(16);if(L.length+3!=I/4)return!1;var Q=Sr(L.replace(/^1f+00/,""));if(Q.length==0)return!1;var se=Q[0];return Q[1]==(function(be){return j.crypto.Util.hashString(be,se)})(_)},Je.prototype.verifyWithMessageHash=function(_,b){if(b.length!=Math.ceil(this.n.bitLength()/4))return!1;var w=at(b,16);if(w.bitLength()>this.n.bitLength())return 0;var I=Sr(this.doPublic(w).toString(16).replace(/^1f+00/,""));return I.length==0?!1:(I[0],I[1]==_)},Je.prototype.verifyPSS=function(_,b,w,I){var L=(function(se){return j.crypto.Util.hashHex(se,w)})(ir(_));return I===void 0&&(I=-1),this.verifyWithMessageHashPSS(L,b,w,I)},Je.prototype.verifyWithMessageHashPSS=function(_,b,w,I){if(b.length!=Math.ceil(this.n.bitLength()/4))return!1;var L,Q=new M(b,16),se=function(De){return j.crypto.Util.hashHex(De,w)},xe=hr(_),be=xe.length,ve=this.n.bitLength()-1,we=Math.ceil(ve/8);if(I===-1||I===void 0)I=be;else if(I===-2)I=we-be-2;else if(I<-2)throw new Error("invalid salt length");if(we<be+I+2)throw new Error("data too long");var Ce=this.doPublic(Q).toByteArray();for(L=0;L<Ce.length;L+=1)Ce[L]&=255;for(;Ce.length<we;)Ce.unshift(0);if(Ce[we-1]!==188)throw new Error("encoded message does not end in 0xbc");var Fe=(Ce=String.fromCharCode.apply(String,Ce)).substr(0,we-be-1),Me=Ce.substr(Fe.length,be),Ze=65280>>8*we-ve&255;if((Fe.charCodeAt(0)&Ze)!=0)throw new Error("bits beyond keysize not zero");var Ye=li(Me,Fe.length,se),tt=[];for(L=0;L<Fe.length;L+=1)tt[L]=Fe.charCodeAt(L)^Ye.charCodeAt(L);tt[0]&=~Ze;var ae=we-be-I-2;for(L=0;L<ae;L+=1)if(tt[L]!==0)throw new Error("leftmost octets not zero");if(tt[ae]!==1)throw new Error("0x01 marker not found");return Me===hr(se(ir("\0\0\0\0\0\0\0\0"+xe+String.fromCharCode.apply(String,tt.slice(-I)))))},Je.SALT_LEN_HLEN=-1,Je.SALT_LEN_MAX=-2,Je.SALT_LEN_RECOVER=-2,lr.hex2dn=function(_,b){b===void 0&&(b=0);var w=new lr;return Le.getTLV(_,b),w.getX500Name(_).str},lr.hex2rdn=function(_,b){if(b===void 0&&(b=0),_.substr(b,2)!=="31")throw new Error("malformed RDN");for(var w=new Array,I=Le.getChildIdx(_,b),L=0;L<I.length;L++)w.push(lr.hex2attrTypeValue(_,I[L]));return(w=w.map((function(Q){return Q.replace("+","\\+")}))).join("+")},lr.hex2attrTypeValue=function(_,b){var w=Le,I=w.getV;if(b===void 0&&(b=0),_.substr(b,2)!=="30")throw new Error("malformed attribute type and value");var L=w.getChildIdx(_,b);L.length!==2||_.substr(L[0],2);var Q=I(_,L[0]),se=j.asn1.ASN1Util.oidHexToInt(Q);return j.asn1.x509.OID.oid2atype(se)+"="+hr(I(_,L[1]))},lr.getPublicKeyFromCertHex=function(_){var b=new lr;return b.readCertHex(_),b.getPublicKey()},lr.getPublicKeyFromCertPEM=function(_){var b=new lr;return b.readCertPEM(_),b.getPublicKey()},lr.getPublicKeyInfoPropOfCertPEM=function(_){var b,w,I=Le.getVbyList,L={};return L.algparam=null,(b=new lr).readCertPEM(_),w=b.getPublicKeyHex(),L.keyhex=I(w,0,[1],"03").substr(2),L.algoid=I(w,0,[0,0],"06"),L.algoid==="2a8648ce3d0201"&&(L.algparam=I(w,0,[0,1],"06")),L},lr.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],j!==void 0&&j||(i.KJUR=j={}),j.jws!==void 0&&j.jws||(j.jws={}),j.jws.JWS=function(){var _=j.jws.JWS.isSafeJSONString;this.parseJWS=function(b,w){if(this.parsedJWS===void 0||!w&&this.parsedJWS.sigvalH===void 0){var I=b.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(I==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var L=I[1],Q=I[2],se=I[3],xe=L+"."+Q;if(this.parsedJWS={},this.parsedJWS.headB64U=L,this.parsedJWS.payloadB64U=Q,this.parsedJWS.sigvalB64U=se,this.parsedJWS.si=xe,!w){var be=Ut(se),ve=at(be,16);this.parsedJWS.sigvalH=be,this.parsedJWS.sigvalBI=ve}var we=Ve(L),Ce=Ve(Q);if(this.parsedJWS.headS=we,this.parsedJWS.payloadS=Ce,!_(we,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+we}}},j.jws.JWS.sign=function(_,b,w,I,L){var Q,se,xe,be=j,ve=be.jws.JWS,we=ve.readSafeJSONString,Ce=ve.isSafeJSONString,Fe=be.crypto,Me=(Fe.ECDSA,Fe.Mac),Ze=Fe.Signature,Ye=JSON;if(typeof b!="string"&&(b===void 0?"undefined":A(b))!="object")throw"spHeader must be JSON string or object: "+b;if((b===void 0?"undefined":A(b))=="object"&&(se=b,Q=Ye.stringify(se)),typeof b=="string"){if(!Ce(Q=b))throw"JWS Head is not safe JSON string: "+Q;se=we(Q)}if(xe=w,(w===void 0?"undefined":A(w))=="object"&&(xe=Ye.stringify(w)),_!=""&&_!=null||se.alg===void 0||(_=se.alg),_!=""&&_!=null&&se.alg===void 0&&(se.alg=_,Q=Ye.stringify(se)),_!==se.alg)throw"alg and sHeader.alg doesn't match: "+_+"!="+se.alg;var tt=null;if(ve.jwsalg2sigalg[_]===void 0)throw"unsupported alg name: "+_;tt=ve.jwsalg2sigalg[_];var ae=Ne(Q)+"."+Ne(xe),Re="";if(tt.substr(0,4)=="Hmac"){if(I===void 0)throw"mac key shall be specified for HS* alg";var De=new Me({alg:tt,prov:"cryptojs",pass:I});De.updateString(ae),Re=De.doFinal()}else if(tt.indexOf("withECDSA")!=-1){(Qe=new Ze({alg:tt})).init(I,L),Qe.updateString(ae);var Pe=Qe.sign();Re=j.crypto.ECDSA.asn1SigToConcatSig(Pe)}else{var Qe;tt!="none"&&((Qe=new Ze({alg:tt})).init(I,L),Qe.updateString(ae),Re=Qe.sign())}return ae+"."+er(Re)},j.jws.JWS.verify=function(_,b,w){var I,L=j,Q=L.jws.JWS,se=Q.readSafeJSONString,xe=L.crypto,be=xe.ECDSA,ve=xe.Mac,we=xe.Signature;A(Je)!==void 0&&(I=Je);var Ce=_.split(".");if(Ce.length!==3)return!1;var Fe=Ce[0]+"."+Ce[1],Me=Ut(Ce[2]),Ze=se(Ve(Ce[0])),Ye=null,tt=null;if(Ze.alg===void 0)throw"algorithm not specified in header";if(tt=(Ye=Ze.alg).substr(0,2),w!=null&&Object.prototype.toString.call(w)==="[object Array]"&&w.length>0&&(":"+w.join(":")+":").indexOf(":"+Ye+":")==-1)throw"algorithm '"+Ye+"' not accepted in the list";if(Ye!="none"&&b===null)throw"key shall be specified to verify.";if(typeof b=="string"&&b.indexOf("-----BEGIN ")!=-1&&(b=Tt.getKey(b)),!(tt!="RS"&&tt!="PS"||b instanceof I))throw"key shall be a RSAKey obj for RS* and PS* algs";if(tt=="ES"&&!(b instanceof be))throw"key shall be a ECDSA obj for ES* algs";var ae=null;if(Q.jwsalg2sigalg[Ze.alg]===void 0)throw"unsupported alg name: "+Ye;if((ae=Q.jwsalg2sigalg[Ye])=="none")throw"not supported";if(ae.substr(0,4)=="Hmac"){if(b===void 0)throw"hexadecimal key shall be specified for HMAC";var Re=new ve({alg:ae,pass:b});return Re.updateString(Fe),Me==Re.doFinal()}if(ae.indexOf("withECDSA")!=-1){var De,Pe=null;try{Pe=be.concatSigToASN1Sig(Me)}catch{return!1}return(De=new we({alg:ae})).init(b),De.updateString(Fe),De.verify(Pe)}return(De=new we({alg:ae})).init(b),De.updateString(Fe),De.verify(Me)},j.jws.JWS.parse=function(_){var b,w,I,L=_.split("."),Q={};if(L.length!=2&&L.length!=3)throw"malformed sJWS: wrong number of '.' splitted elements";return b=L[0],w=L[1],L.length==3&&(I=L[2]),Q.headerObj=j.jws.JWS.readSafeJSONString(Ve(b)),Q.payloadObj=j.jws.JWS.readSafeJSONString(Ve(w)),Q.headerPP=JSON.stringify(Q.headerObj,null," "),Q.payloadObj==null?Q.payloadPP=Ve(w):Q.payloadPP=JSON.stringify(Q.payloadObj,null," "),I!==void 0&&(Q.sigHex=Ut(I)),Q},j.jws.JWS.verifyJWT=function(_,b,w){var I=j.jws,L=I.JWS,Q=L.readSafeJSONString,se=L.inArray,xe=L.includedArray,be=_.split("."),ve=be[0],we=be[1],Ce=(Ut(be[2]),Q(Ve(ve))),Fe=Q(Ve(we));if(Ce.alg===void 0)return!1;if(w.alg===void 0)throw"acceptField.alg shall be specified";if(!se(Ce.alg,w.alg)||Fe.iss!==void 0&&A(w.iss)==="object"&&!se(Fe.iss,w.iss)||Fe.sub!==void 0&&A(w.sub)==="object"&&!se(Fe.sub,w.sub))return!1;if(Fe.aud!==void 0&&A(w.aud)==="object"){if(typeof Fe.aud=="string"){if(!se(Fe.aud,w.aud))return!1}else if(A(Fe.aud)=="object"&&!xe(Fe.aud,w.aud))return!1}var Me=I.IntDate.getNow();return w.verifyAt!==void 0&&typeof w.verifyAt=="number"&&(Me=w.verifyAt),w.gracePeriod!==void 0&&typeof w.gracePeriod=="number"||(w.gracePeriod=0),!(Fe.exp!==void 0&&typeof Fe.exp=="number"&&Fe.exp+w.gracePeriod<Me)&&!(Fe.nbf!==void 0&&typeof Fe.nbf=="number"&&Me<Fe.nbf-w.gracePeriod)&&!(Fe.iat!==void 0&&typeof Fe.iat=="number"&&Me<Fe.iat-w.gracePeriod)&&(Fe.jti===void 0||w.jti===void 0||Fe.jti===w.jti)&&!!L.verify(_,b,w.alg)},j.jws.JWS.includedArray=function(_,b){var w=j.jws.JWS.inArray;if(_===null||(_===void 0?"undefined":A(_))!=="object"||typeof _.length!="number")return!1;for(var I=0;I<_.length;I++)if(!w(_[I],b))return!1;return!0},j.jws.JWS.inArray=function(_,b){if(b===null||(b===void 0?"undefined":A(b))!=="object"||typeof b.length!="number")return!1;for(var w=0;w<b.length;w++)if(b[w]==_)return!0;return!1},j.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS384:"HmacSHA384",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none"},j.jws.JWS.isSafeJSONString=function(_,b,w){var I=null;try{return((I=z(_))===void 0?"undefined":A(I))!="object"||I.constructor===Array?0:(b&&(b[w]=I),1)}catch{return 0}},j.jws.JWS.readSafeJSONString=function(_){var b=null;try{return((b=z(_))===void 0?"undefined":A(b))!="object"||b.constructor===Array?null:b}catch{return null}},j.jws.JWS.getEncodedSignatureValueFromJWS=function(_){var b=_.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(b==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return b[1]},j.jws.JWS.getJWKthumbprint=function(_){if(_.kty!=="RSA"&&_.kty!=="EC"&&_.kty!=="oct")throw"unsupported algorithm for JWK Thumprint";var b="{";if(_.kty==="RSA"){if(typeof _.n!="string"||typeof _.e!="string")throw"wrong n and e value for RSA key";b+='"e":"'+_.e+'",',b+='"kty":"'+_.kty+'",',b+='"n":"'+_.n+'"}'}else if(_.kty==="EC"){if(typeof _.crv!="string"||typeof _.x!="string"||typeof _.y!="string")throw"wrong crv, x and y value for EC key";b+='"crv":"'+_.crv+'",',b+='"kty":"'+_.kty+'",',b+='"x":"'+_.x+'",',b+='"y":"'+_.y+'"}'}else if(_.kty==="oct"){if(typeof _.k!="string")throw"wrong k value for oct(symmetric) key";b+='"kty":"'+_.kty+'",',b+='"k":"'+_.k+'"}'}var w=ir(b);return er(j.crypto.Util.hashHex(w,"sha256"))},j.jws.IntDate={},j.jws.IntDate.get=function(_){var b=j.jws.IntDate,w=b.getNow,I=b.getZulu;if(_=="now")return w();if(_=="now + 1hour")return w()+3600;if(_=="now + 1day")return w()+86400;if(_=="now + 1month")return w()+2592e3;if(_=="now + 1year")return w()+31536e3;if(_.match(/Z$/))return I(_);if(_.match(/^[0-9]+$/))return parseInt(_);throw"unsupported format: "+_},j.jws.IntDate.getZulu=function(_){return jt(_)},j.jws.IntDate.getNow=function(){return~~(new Date/1e3)},j.jws.IntDate.intDate2UTCString=function(_){return new Date(1e3*_).toUTCString()},j.jws.IntDate.intDate2Zulu=function(_){var b=new Date(1e3*_);return("0000"+b.getUTCFullYear()).slice(-4)+("00"+(b.getUTCMonth()+1)).slice(-2)+("00"+b.getUTCDate()).slice(-2)+("00"+b.getUTCHours()).slice(-2)+("00"+b.getUTCMinutes()).slice(-2)+("00"+b.getUTCSeconds()).slice(-2)+"Z"},i.SecureRandom=ye,i.rng_seed_time=ne,i.BigInteger=M,i.RSAKey=Je;var ci=j.crypto.EDSA;i.EDSA=ci;var kr=j.crypto.DSA;i.DSA=kr;var xn=j.crypto.Signature;i.Signature=xn;var Rr=j.crypto.MessageDigest;i.MessageDigest=Rr;var vi=j.crypto.Mac;i.Mac=vi;var wi=j.crypto.Cipher;i.Cipher=wi,i.KEYUTIL=Tt,i.ASN1HEX=Le,i.X509=lr,i.CryptoJS=F,i.b64tohex=G,i.b64toBA=fe,i.stoBA=mt,i.BAtos=St,i.BAtohex=Rt,i.stohex=kt,i.stob64=function(b){return O(kt(b))},i.stob64u=function(b){return Ft(O(kt(b)))},i.b64utos=function(b){return St(fe(on(b)))},i.b64tob64u=Ft,i.b64utob64=on,i.hex2b64=O,i.hextob64u=er,i.b64utohex=Ut,i.utf8tob64u=Ne,i.b64utoutf8=Ve,i.utf8tob64=function(b){return O(Wt(zt(b)))},i.b64toutf8=function(b){return decodeURIComponent(ln(G(b)))},i.utf8tohex=xr,i.hextoutf8=Bt,i.hextorstr=hr,i.rstrtohex=ir,i.hextob64=Wr,i.hextob64nl=V,i.b64nltohex=K,i.hextopem=ze,i.pemtohex=Ke,i.hextoArrayBuffer=function(b){if(b.length%2!=0)throw"input is not even length";if(b.match(/^[0-9A-Fa-f]+$/)==null)throw"input is not hexadecimal";for(var w=new ArrayBuffer(b.length/2),I=new DataView(w),L=0;L<b.length/2;L++)I.setUint8(L,parseInt(b.substr(2*L,2),16));return w},i.ArrayBuffertohex=function(b){for(var w="",I=new DataView(b),L=0;L<b.byteLength;L++)w+=("00"+I.getUint8(L).toString(16)).slice(-2);return w},i.zulutomsec=lt,i.zulutosec=jt,i.zulutodate=function(b){return new Date(lt(b))},i.datetozulu=function(b,w,I){var L,Q=b.getUTCFullYear();if(w){if(Q<1950||2049<Q)throw"not proper year for UTCTime: "+Q;L=(""+Q).slice(-2)}else L=("000"+Q).slice(-4);if(L+=("0"+(b.getUTCMonth()+1)).slice(-2),L+=("0"+b.getUTCDate()).slice(-2),L+=("0"+b.getUTCHours()).slice(-2),L+=("0"+b.getUTCMinutes()).slice(-2),L+=("0"+b.getUTCSeconds()).slice(-2),I){var se=b.getUTCMilliseconds();se!==0&&(L+="."+(se=(se=("00"+se).slice(-3)).replace(/0+$/g,"")))}return L+="Z"},i.uricmptohex=Wt,i.hextouricmp=ln,i.ipv6tohex=Er,i.hextoipv6=ar,i.hextoip=Sn,i.iptohex=function(b){var w="malformed IP address";if(!(b=b.toLowerCase(b)).match(/^[0-9.]+$/)){if(b.match(/^[0-9a-f:]+$/)&&b.indexOf(":")!==-1)return Er(b);throw w}var I=b.split(".");if(I.length!==4)throw w;var L="";try{for(var Q=0;Q<4;Q++)L+=("0"+parseInt(I[Q]).toString(16)).slice(-2);return L}catch{throw w}},i.encodeURIComponentAll=zt,i.newline_toUnix=function(b){return b=b.replace(/\r\n/gm,`
304
304
  `)},i.newline_toDos=function(b){return b=(b=b.replace(/\r\n/gm,`
305
305
  `)).replace(/\n/gm,`\r
306
- `)},i.hextoposhex=Pr,i.intarystrtohex=function(b){b=(b=(b=b.replace(/^\s*\[\s*/,"")).replace(/\s*\]\s*$/,"")).replace(/\s*/g,"");try{return b.split(/,/).map((function(w,I,L){var Q=parseInt(w);if(Q<0||255<Q)throw"integer not in range 0-255";return("00"+Q.toString(16)).slice(-2)})).join("")}catch(w){throw"malformed integer array string: "+w}},i.strdiffidx=function(b,w){var I=b.length;b.length>w.length&&(I=w.length);for(var L=0;L<I;L++)if(b.charCodeAt(L)!=w.charCodeAt(L))return L;return b.length!=w.length?I:-1},i.KJUR=j;var En=j.crypto;i.crypto=En;var gn=j.asn1;i.asn1=gn;var Rn=j.jws;i.jws=Rn;var ws=j.lang;i.lang=ws}).call(this,s(28).Buffer)},function(t,i,s){(function(o){var l=s(30),u=s(31),h=s(32);function d(){return g.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function p(ie,B){if(d()<B)throw new RangeError("Invalid typed array length");return g.TYPED_ARRAY_SUPPORT?(ie=new Uint8Array(B)).__proto__=g.prototype:(ie===null&&(ie=new g(B)),ie.length=B),ie}function g(ie,B,N){if(!(g.TYPED_ARRAY_SUPPORT||this instanceof g))return new g(ie,B,N);if(typeof ie=="number"){if(typeof B=="string")throw new Error("If encoding is specified then the first argument must be a string");return S(this,ie)}return m(this,ie,B,N)}function m(ie,B,N,k){if(typeof B=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&B instanceof ArrayBuffer?(function(ne,le,Ee,J){if(le.byteLength,Ee<0||le.byteLength<Ee)throw new RangeError("'offset' is out of bounds");if(le.byteLength<Ee+(J||0))throw new RangeError("'length' is out of bounds");return le=Ee===void 0&&J===void 0?new Uint8Array(le):J===void 0?new Uint8Array(le,Ee):new Uint8Array(le,Ee,J),g.TYPED_ARRAY_SUPPORT?(ne=le).__proto__=g.prototype:ne=E(ne,le),ne})(ie,B,N,k):typeof B=="string"?(function(ne,le,Ee){if(typeof Ee=="string"&&Ee!==""||(Ee="utf8"),!g.isEncoding(Ee))throw new TypeError('"encoding" must be a valid string encoding');var J=0|A(le,Ee),_e=(ne=p(ne,J)).write(le,Ee);return _e!==J&&(ne=ne.slice(0,_e)),ne})(ie,B,N):(function(ne,le){if(g.isBuffer(le)){var Ee=0|x(le.length);return(ne=p(ne,Ee)).length===0||le.copy(ne,0,0,Ee),ne}if(le){if(typeof ArrayBuffer<"u"&&le.buffer instanceof ArrayBuffer||"length"in le)return typeof le.length!="number"||(function(_e){return _e!=_e})(le.length)?p(ne,0):E(ne,le);if(le.type==="Buffer"&&h(le.data))return E(ne,le.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(ie,B)}function v(ie){if(typeof ie!="number")throw new TypeError('"size" argument must be a number');if(ie<0)throw new RangeError('"size" argument must not be negative')}function S(ie,B){if(v(B),ie=p(ie,B<0?0:0|x(B)),!g.TYPED_ARRAY_SUPPORT)for(var N=0;N<B;++N)ie[N]=0;return ie}function E(ie,B){var N=B.length<0?0:0|x(B.length);ie=p(ie,N);for(var k=0;k<N;k+=1)ie[k]=255&B[k];return ie}function x(ie){if(ie>=d())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+d().toString(16)+" bytes");return 0|ie}function A(ie,B){if(g.isBuffer(ie))return ie.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(ie)||ie instanceof ArrayBuffer))return ie.byteLength;typeof ie!="string"&&(ie=""+ie);var N=ie.length;if(N===0)return 0;for(var k=!1;;)switch(B){case"ascii":case"latin1":case"binary":return N;case"utf8":case"utf-8":case void 0:return me(ie).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*N;case"hex":return N>>>1;case"base64":return ge(ie).length;default:if(k)return me(ie).length;B=(""+B).toLowerCase(),k=!0}}function C(ie,B,N){var k=!1;if((B===void 0||B<0)&&(B=0),B>this.length||((N===void 0||N>this.length)&&(N=this.length),N<=0)||(N>>>=0)<=(B>>>=0))return"";for(ie||(ie="utf8");;)switch(ie){case"hex":return Oe(this,B,N);case"utf8":case"utf-8":return re(this,B,N);case"ascii":return ke(this,B,N);case"latin1":case"binary":return he(this,B,N);case"base64":return Se(this,B,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ce(this,B,N);default:if(k)throw new TypeError("Unknown encoding: "+ie);ie=(ie+"").toLowerCase(),k=!0}}function T(ie,B,N){var k=ie[B];ie[B]=ie[N],ie[N]=k}function F(ie,B,N,k,H){if(ie.length===0)return-1;if(typeof N=="string"?(k=N,N=0):N>2147483647?N=2147483647:N<-2147483648&&(N=-2147483648),N=+N,isNaN(N)&&(N=H?0:ie.length-1),N<0&&(N=ie.length+N),N>=ie.length){if(H)return-1;N=ie.length-1}else if(N<0){if(!H)return-1;N=0}if(typeof B=="string"&&(B=g.from(B,k)),g.isBuffer(B))return B.length===0?-1:P(ie,B,N,k,H);if(typeof B=="number")return B&=255,g.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?H?Uint8Array.prototype.indexOf.call(ie,B,N):Uint8Array.prototype.lastIndexOf.call(ie,B,N):P(ie,[B],N,k,H);throw new TypeError("val must be string, number or Buffer")}function P(ie,B,N,k,H){var ne,le=1,Ee=ie.length,J=B.length;if(k!==void 0&&((k=String(k).toLowerCase())==="ucs2"||k==="ucs-2"||k==="utf16le"||k==="utf-16le")){if(ie.length<2||B.length<2)return-1;le=2,Ee/=2,J/=2,N/=2}function _e(ht,Je){return le===1?ht[Je]:ht.readUInt16BE(Je*le)}if(H){var Ie=-1;for(ne=N;ne<Ee;ne++)if(_e(ie,ne)===_e(B,Ie===-1?0:ne-Ie)){if(Ie===-1&&(Ie=ne),ne-Ie+1===J)return Ie*le}else Ie!==-1&&(ne-=ne-Ie),Ie=-1}else for(N+J>Ee&&(N=Ee-J),ne=N;ne>=0;ne--){for(var ye=!0,at=0;at<J;at++)if(_e(ie,ne+at)!==_e(B,at)){ye=!1;break}if(ye)return ne}return-1}function q(ie,B,N,k){N=Number(N)||0;var H=ie.length-N;k?(k=Number(k))>H&&(k=H):k=H;var ne=B.length;if(ne%2!=0)throw new TypeError("Invalid hex string");k>ne/2&&(k=ne/2);for(var le=0;le<k;++le){var Ee=parseInt(B.substr(2*le,2),16);if(isNaN(Ee))return le;ie[N+le]=Ee}return le}function O(ie,B,N,k){return Be(me(B,ie.length-N),ie,N,k)}function G(ie,B,N,k){return Be((function(ne){for(var le=[],Ee=0;Ee<ne.length;++Ee)le.push(255&ne.charCodeAt(Ee));return le})(B),ie,N,k)}function fe(ie,B,N,k){return G(ie,B,N,k)}function M(ie,B,N,k){return Be(ge(B),ie,N,k)}function ee(ie,B,N,k){return Be((function(ne,le){for(var Ee,J,_e,Ie=[],ye=0;ye<ne.length&&!((le-=2)<0);++ye)J=(Ee=ne.charCodeAt(ye))>>8,_e=Ee%256,Ie.push(_e),Ie.push(J);return Ie})(B,ie.length-N),ie,N,k)}function Se(ie,B,N){return B===0&&N===ie.length?l.fromByteArray(ie):l.fromByteArray(ie.slice(B,N))}function re(ie,B,N){N=Math.min(ie.length,N);for(var k=[],H=B;H<N;){var ne,le,Ee,J,_e=ie[H],Ie=null,ye=_e>239?4:_e>223?3:_e>191?2:1;if(H+ye<=N)switch(ye){case 1:_e<128&&(Ie=_e);break;case 2:(192&(ne=ie[H+1]))==128&&(J=(31&_e)<<6|63&ne)>127&&(Ie=J);break;case 3:ne=ie[H+1],le=ie[H+2],(192&ne)==128&&(192&le)==128&&(J=(15&_e)<<12|(63&ne)<<6|63&le)>2047&&(J<55296||J>57343)&&(Ie=J);break;case 4:ne=ie[H+1],le=ie[H+2],Ee=ie[H+3],(192&ne)==128&&(192&le)==128&&(192&Ee)==128&&(J=(15&_e)<<18|(63&ne)<<12|(63&le)<<6|63&Ee)>65535&&J<1114112&&(Ie=J)}Ie===null?(Ie=65533,ye=1):Ie>65535&&(Ie-=65536,k.push(Ie>>>10&1023|55296),Ie=56320|1023&Ie),k.push(Ie),H+=ye}return(function(ht){var Je=ht.length;if(Je<=Ae)return String.fromCharCode.apply(String,ht);for(var gt="",Y=0;Y<Je;)gt+=String.fromCharCode.apply(String,ht.slice(Y,Y+=Ae));return gt})(k)}i.Buffer=g,i.SlowBuffer=function(B){return+B!=B&&(B=0),g.alloc(+B)},i.INSPECT_MAX_BYTES=50,g.TYPED_ARRAY_SUPPORT=o.TYPED_ARRAY_SUPPORT!==void 0?o.TYPED_ARRAY_SUPPORT:(function(){try{var B=new Uint8Array(1);return B.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},B.foo()===42&&typeof B.subarray=="function"&&B.subarray(1,1).byteLength===0}catch{return!1}})(),i.kMaxLength=d(),g.poolSize=8192,g._augment=function(ie){return ie.__proto__=g.prototype,ie},g.from=function(ie,B,N){return m(null,ie,B,N)},g.TYPED_ARRAY_SUPPORT&&(g.prototype.__proto__=Uint8Array.prototype,g.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&g[Symbol.species]===g&&Object.defineProperty(g,Symbol.species,{value:null,configurable:!0})),g.alloc=function(ie,B,N){return(function(H,ne,le,Ee){return v(ne),ne<=0?p(H,ne):le!==void 0?typeof Ee=="string"?p(H,ne).fill(le,Ee):p(H,ne).fill(le):p(H,ne)})(null,ie,B,N)},g.allocUnsafe=function(ie){return S(null,ie)},g.allocUnsafeSlow=function(ie){return S(null,ie)},g.isBuffer=function(B){return!(B==null||!B._isBuffer)},g.compare=function(B,N){if(!g.isBuffer(B)||!g.isBuffer(N))throw new TypeError("Arguments must be Buffers");if(B===N)return 0;for(var k=B.length,H=N.length,ne=0,le=Math.min(k,H);ne<le;++ne)if(B[ne]!==N[ne]){k=B[ne],H=N[ne];break}return k<H?-1:H<k?1:0},g.isEncoding=function(B){switch(String(B).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},g.concat=function(B,N){if(!h(B))throw new TypeError('"list" argument must be an Array of Buffers');if(B.length===0)return g.alloc(0);var k;if(N===void 0)for(N=0,k=0;k<B.length;++k)N+=B[k].length;var H=g.allocUnsafe(N),ne=0;for(k=0;k<B.length;++k){var le=B[k];if(!g.isBuffer(le))throw new TypeError('"list" argument must be an Array of Buffers');le.copy(H,ne),ne+=le.length}return H},g.byteLength=A,g.prototype._isBuffer=!0,g.prototype.swap16=function(){var B=this.length;if(B%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var N=0;N<B;N+=2)T(this,N,N+1);return this},g.prototype.swap32=function(){var B=this.length;if(B%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var N=0;N<B;N+=4)T(this,N,N+3),T(this,N+1,N+2);return this},g.prototype.swap64=function(){var B=this.length;if(B%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var N=0;N<B;N+=8)T(this,N,N+7),T(this,N+1,N+6),T(this,N+2,N+5),T(this,N+3,N+4);return this},g.prototype.toString=function(){var B=0|this.length;return B===0?"":arguments.length===0?re(this,0,B):C.apply(this,arguments)},g.prototype.equals=function(B){if(!g.isBuffer(B))throw new TypeError("Argument must be a Buffer");return this===B||g.compare(this,B)===0},g.prototype.inspect=function(){var B="",N=i.INSPECT_MAX_BYTES;return this.length>0&&(B=this.toString("hex",0,N).match(/.{2}/g).join(" "),this.length>N&&(B+=" ... ")),"<Buffer "+B+">"},g.prototype.compare=function(B,N,k,H,ne){if(!g.isBuffer(B))throw new TypeError("Argument must be a Buffer");if(N===void 0&&(N=0),k===void 0&&(k=B?B.length:0),H===void 0&&(H=0),ne===void 0&&(ne=this.length),N<0||k>B.length||H<0||ne>this.length)throw new RangeError("out of range index");if(H>=ne&&N>=k)return 0;if(H>=ne)return-1;if(N>=k)return 1;if(this===B)return 0;for(var le=(ne>>>=0)-(H>>>=0),Ee=(k>>>=0)-(N>>>=0),J=Math.min(le,Ee),_e=this.slice(H,ne),Ie=B.slice(N,k),ye=0;ye<J;++ye)if(_e[ye]!==Ie[ye]){le=_e[ye],Ee=Ie[ye];break}return le<Ee?-1:Ee<le?1:0},g.prototype.includes=function(B,N,k){return this.indexOf(B,N,k)!==-1},g.prototype.indexOf=function(B,N,k){return F(this,B,N,k,!0)},g.prototype.lastIndexOf=function(B,N,k){return F(this,B,N,k,!1)},g.prototype.write=function(B,N,k,H){if(N===void 0)H="utf8",k=this.length,N=0;else if(k===void 0&&typeof N=="string")H=N,k=this.length,N=0;else{if(!isFinite(N))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");N|=0,isFinite(k)?(k|=0,H===void 0&&(H="utf8")):(H=k,k=void 0)}var ne=this.length-N;if((k===void 0||k>ne)&&(k=ne),B.length>0&&(k<0||N<0)||N>this.length)throw new RangeError("Attempt to write outside buffer bounds");H||(H="utf8");for(var le=!1;;)switch(H){case"hex":return q(this,B,N,k);case"utf8":case"utf-8":return O(this,B,N,k);case"ascii":return G(this,B,N,k);case"latin1":case"binary":return fe(this,B,N,k);case"base64":return M(this,B,N,k);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ee(this,B,N,k);default:if(le)throw new TypeError("Unknown encoding: "+H);H=(""+H).toLowerCase(),le=!0}},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ae=4096;function ke(ie,B,N){var k="";N=Math.min(ie.length,N);for(var H=B;H<N;++H)k+=String.fromCharCode(127&ie[H]);return k}function he(ie,B,N){var k="";N=Math.min(ie.length,N);for(var H=B;H<N;++H)k+=String.fromCharCode(ie[H]);return k}function Oe(ie,B,N){var k=ie.length;(!B||B<0)&&(B=0),(!N||N<0||N>k)&&(N=k);for(var H="",ne=B;ne<N;++ne)H+=We(ie[ne]);return H}function ce(ie,B,N){for(var k=ie.slice(B,N),H="",ne=0;ne<k.length;ne+=2)H+=String.fromCharCode(k[ne]+256*k[ne+1]);return H}function Ue(ie,B,N){if(ie%1!=0||ie<0)throw new RangeError("offset is not uint");if(ie+B>N)throw new RangeError("Trying to access beyond buffer length")}function $(ie,B,N,k,H,ne){if(!g.isBuffer(ie))throw new TypeError('"buffer" argument must be a Buffer instance');if(B>H||B<ne)throw new RangeError('"value" argument is out of bounds');if(N+k>ie.length)throw new RangeError("Index out of range")}function W(ie,B,N,k){B<0&&(B=65535+B+1);for(var H=0,ne=Math.min(ie.length-N,2);H<ne;++H)ie[N+H]=(B&255<<8*(k?H:1-H))>>>8*(k?H:1-H)}function de(ie,B,N,k){B<0&&(B=4294967295+B+1);for(var H=0,ne=Math.min(ie.length-N,4);H<ne;++H)ie[N+H]=B>>>8*(k?H:3-H)&255}function te(ie,B,N,k,H,ne){if(N+k>ie.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("Index out of range")}function Te(ie,B,N,k,H){return H||te(ie,0,N,4),u.write(ie,B,N,k,23,4),N+4}function je(ie,B,N,k,H){return H||te(ie,0,N,8),u.write(ie,B,N,k,52,8),N+8}g.prototype.slice=function(B,N){var k,H=this.length;if((B=~~B)<0?(B+=H)<0&&(B=0):B>H&&(B=H),(N=N===void 0?H:~~N)<0?(N+=H)<0&&(N=0):N>H&&(N=H),N<B&&(N=B),g.TYPED_ARRAY_SUPPORT)(k=this.subarray(B,N)).__proto__=g.prototype;else{var ne=N-B;k=new g(ne,void 0);for(var le=0;le<ne;++le)k[le]=this[le+B]}return k},g.prototype.readUIntLE=function(B,N,k){B|=0,N|=0,k||Ue(B,N,this.length);for(var H=this[B],ne=1,le=0;++le<N&&(ne*=256);)H+=this[B+le]*ne;return H},g.prototype.readUIntBE=function(B,N,k){B|=0,N|=0,k||Ue(B,N,this.length);for(var H=this[B+--N],ne=1;N>0&&(ne*=256);)H+=this[B+--N]*ne;return H},g.prototype.readUInt8=function(B,N){return N||Ue(B,1,this.length),this[B]},g.prototype.readUInt16LE=function(B,N){return N||Ue(B,2,this.length),this[B]|this[B+1]<<8},g.prototype.readUInt16BE=function(B,N){return N||Ue(B,2,this.length),this[B]<<8|this[B+1]},g.prototype.readUInt32LE=function(B,N){return N||Ue(B,4,this.length),(this[B]|this[B+1]<<8|this[B+2]<<16)+16777216*this[B+3]},g.prototype.readUInt32BE=function(B,N){return N||Ue(B,4,this.length),16777216*this[B]+(this[B+1]<<16|this[B+2]<<8|this[B+3])},g.prototype.readIntLE=function(B,N,k){B|=0,N|=0,k||Ue(B,N,this.length);for(var H=this[B],ne=1,le=0;++le<N&&(ne*=256);)H+=this[B+le]*ne;return H>=(ne*=128)&&(H-=Math.pow(2,8*N)),H},g.prototype.readIntBE=function(B,N,k){B|=0,N|=0,k||Ue(B,N,this.length);for(var H=N,ne=1,le=this[B+--H];H>0&&(ne*=256);)le+=this[B+--H]*ne;return le>=(ne*=128)&&(le-=Math.pow(2,8*N)),le},g.prototype.readInt8=function(B,N){return N||Ue(B,1,this.length),128&this[B]?-1*(255-this[B]+1):this[B]},g.prototype.readInt16LE=function(B,N){N||Ue(B,2,this.length);var k=this[B]|this[B+1]<<8;return 32768&k?4294901760|k:k},g.prototype.readInt16BE=function(B,N){N||Ue(B,2,this.length);var k=this[B+1]|this[B]<<8;return 32768&k?4294901760|k:k},g.prototype.readInt32LE=function(B,N){return N||Ue(B,4,this.length),this[B]|this[B+1]<<8|this[B+2]<<16|this[B+3]<<24},g.prototype.readInt32BE=function(B,N){return N||Ue(B,4,this.length),this[B]<<24|this[B+1]<<16|this[B+2]<<8|this[B+3]},g.prototype.readFloatLE=function(B,N){return N||Ue(B,4,this.length),u.read(this,B,!0,23,4)},g.prototype.readFloatBE=function(B,N){return N||Ue(B,4,this.length),u.read(this,B,!1,23,4)},g.prototype.readDoubleLE=function(B,N){return N||Ue(B,8,this.length),u.read(this,B,!0,52,8)},g.prototype.readDoubleBE=function(B,N){return N||Ue(B,8,this.length),u.read(this,B,!1,52,8)},g.prototype.writeUIntLE=function(B,N,k,H){B=+B,N|=0,k|=0,H||$(this,B,N,k,Math.pow(2,8*k)-1,0);var ne=1,le=0;for(this[N]=255&B;++le<k&&(ne*=256);)this[N+le]=B/ne&255;return N+k},g.prototype.writeUIntBE=function(B,N,k,H){B=+B,N|=0,k|=0,H||$(this,B,N,k,Math.pow(2,8*k)-1,0);var ne=k-1,le=1;for(this[N+ne]=255&B;--ne>=0&&(le*=256);)this[N+ne]=B/le&255;return N+k},g.prototype.writeUInt8=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,1,255,0),g.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),this[N]=255&B,N+1},g.prototype.writeUInt16LE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8):W(this,B,N,!0),N+2},g.prototype.writeUInt16BE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>8,this[N+1]=255&B):W(this,B,N,!1),N+2},g.prototype.writeUInt32LE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N+3]=B>>>24,this[N+2]=B>>>16,this[N+1]=B>>>8,this[N]=255&B):de(this,B,N,!0),N+4},g.prototype.writeUInt32BE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>24,this[N+1]=B>>>16,this[N+2]=B>>>8,this[N+3]=255&B):de(this,B,N,!1),N+4},g.prototype.writeIntLE=function(B,N,k,H){if(B=+B,N|=0,!H){var ne=Math.pow(2,8*k-1);$(this,B,N,k,ne-1,-ne)}var le=0,Ee=1,J=0;for(this[N]=255&B;++le<k&&(Ee*=256);)B<0&&J===0&&this[N+le-1]!==0&&(J=1),this[N+le]=(B/Ee>>0)-J&255;return N+k},g.prototype.writeIntBE=function(B,N,k,H){if(B=+B,N|=0,!H){var ne=Math.pow(2,8*k-1);$(this,B,N,k,ne-1,-ne)}var le=k-1,Ee=1,J=0;for(this[N+le]=255&B;--le>=0&&(Ee*=256);)B<0&&J===0&&this[N+le+1]!==0&&(J=1),this[N+le]=(B/Ee>>0)-J&255;return N+k},g.prototype.writeInt8=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,1,127,-128),g.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),B<0&&(B=255+B+1),this[N]=255&B,N+1},g.prototype.writeInt16LE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8):W(this,B,N,!0),N+2},g.prototype.writeInt16BE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>8,this[N+1]=255&B):W(this,B,N,!1),N+2},g.prototype.writeInt32LE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,4,2147483647,-2147483648),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8,this[N+2]=B>>>16,this[N+3]=B>>>24):de(this,B,N,!0),N+4},g.prototype.writeInt32BE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,4,2147483647,-2147483648),B<0&&(B=4294967295+B+1),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>24,this[N+1]=B>>>16,this[N+2]=B>>>8,this[N+3]=255&B):de(this,B,N,!1),N+4},g.prototype.writeFloatLE=function(B,N,k){return Te(this,B,N,!0,k)},g.prototype.writeFloatBE=function(B,N,k){return Te(this,B,N,!1,k)},g.prototype.writeDoubleLE=function(B,N,k){return je(this,B,N,!0,k)},g.prototype.writeDoubleBE=function(B,N,k){return je(this,B,N,!1,k)},g.prototype.copy=function(B,N,k,H){if(k||(k=0),H||H===0||(H=this.length),N>=B.length&&(N=B.length),N||(N=0),H>0&&H<k&&(H=k),H===k||B.length===0||this.length===0)return 0;if(N<0)throw new RangeError("targetStart out of bounds");if(k<0||k>=this.length)throw new RangeError("sourceStart out of bounds");if(H<0)throw new RangeError("sourceEnd out of bounds");H>this.length&&(H=this.length),B.length-N<H-k&&(H=B.length-N+k);var ne,le=H-k;if(this===B&&k<N&&N<H)for(ne=le-1;ne>=0;--ne)B[ne+N]=this[ne+k];else if(le<1e3||!g.TYPED_ARRAY_SUPPORT)for(ne=0;ne<le;++ne)B[ne+N]=this[ne+k];else Uint8Array.prototype.set.call(B,this.subarray(k,k+le),N);return le},g.prototype.fill=function(B,N,k,H){if(typeof B=="string"){if(typeof N=="string"?(H=N,N=0,k=this.length):typeof k=="string"&&(H=k,k=this.length),B.length===1){var ne=B.charCodeAt(0);ne<256&&(B=ne)}if(H!==void 0&&typeof H!="string")throw new TypeError("encoding must be a string");if(typeof H=="string"&&!g.isEncoding(H))throw new TypeError("Unknown encoding: "+H)}else typeof B=="number"&&(B&=255);if(N<0||this.length<N||this.length<k)throw new RangeError("Out of range index");if(k<=N)return this;var le;if(N>>>=0,k=k===void 0?this.length:k>>>0,B||(B=0),typeof B=="number")for(le=N;le<k;++le)this[le]=B;else{var Ee=g.isBuffer(B)?B:me(new g(B,H).toString()),J=Ee.length;for(le=0;le<k-N;++le)this[le+N]=Ee[le%J]}return this};var He=/[^+\/0-9A-Za-z-_]/g;function We(ie){return ie<16?"0"+ie.toString(16):ie.toString(16)}function me(ie,B){var N;B=B||1/0;for(var k=ie.length,H=null,ne=[],le=0;le<k;++le){if((N=ie.charCodeAt(le))>55295&&N<57344){if(!H){if(N>56319){(B-=3)>-1&&ne.push(239,191,189);continue}if(le+1===k){(B-=3)>-1&&ne.push(239,191,189);continue}H=N;continue}if(N<56320){(B-=3)>-1&&ne.push(239,191,189),H=N;continue}N=65536+(H-55296<<10|N-56320)}else H&&(B-=3)>-1&&ne.push(239,191,189);if(H=null,N<128){if((B-=1)<0)break;ne.push(N)}else if(N<2048){if((B-=2)<0)break;ne.push(N>>6|192,63&N|128)}else if(N<65536){if((B-=3)<0)break;ne.push(N>>12|224,N>>6&63|128,63&N|128)}else{if(!(N<1114112))throw new Error("Invalid code point");if((B-=4)<0)break;ne.push(N>>18|240,N>>12&63|128,N>>6&63|128,63&N|128)}}return ne}function ge(ie){return l.toByteArray((function(N){if((N=(function(H){return H.trim?H.trim():H.replace(/^\s+|\s+$/g,"")})(N).replace(He,"")).length<2)return"";for(;N.length%4!=0;)N+="=";return N})(ie))}function Be(ie,B,N,k){for(var H=0;H<k&&!(H+N>=B.length||H>=ie.length);++H)B[H+N]=ie[H];return H}}).call(this,s(29))},function(t,i){var s;s=(function(){return this})();try{s=s||new Function("return this")()}catch{typeof window=="object"&&(s=window)}t.exports=s},function(t,i,s){i.byteLength=function(S){var E=g(S),x=E[0],A=E[1];return 3*(x+A)/4-A},i.toByteArray=function(S){var E,x,A=g(S),C=A[0],T=A[1],F=new u((function(G,fe,M){return 3*(fe+M)/4-M})(0,C,T)),P=0,q=T>0?C-4:C;for(x=0;x<q;x+=4)E=l[S.charCodeAt(x)]<<18|l[S.charCodeAt(x+1)]<<12|l[S.charCodeAt(x+2)]<<6|l[S.charCodeAt(x+3)],F[P++]=E>>16&255,F[P++]=E>>8&255,F[P++]=255&E;return T===2&&(E=l[S.charCodeAt(x)]<<2|l[S.charCodeAt(x+1)]>>4,F[P++]=255&E),T===1&&(E=l[S.charCodeAt(x)]<<10|l[S.charCodeAt(x+1)]<<4|l[S.charCodeAt(x+2)]>>2,F[P++]=E>>8&255,F[P++]=255&E),F},i.fromByteArray=function(S){for(var E,x=S.length,A=x%3,C=[],T=16383,F=0,P=x-A;F<P;F+=T)C.push(m(S,F,F+T>P?P:F+T));return A===1?(E=S[x-1],C.push(o[E>>2]+o[E<<4&63]+"==")):A===2&&(E=(S[x-2]<<8)+S[x-1],C.push(o[E>>10]+o[E>>4&63]+o[E<<2&63]+"=")),C.join("")};for(var o=[],l=[],u=typeof Uint8Array<"u"?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=h.length;d<p;++d)o[d]=h[d],l[h.charCodeAt(d)]=d;function g(v){var S=v.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var E=v.indexOf("=");return E===-1&&(E=S),[E,E===S?0:4-E%4]}function m(v,S,E){for(var x,A,C=[],T=S;T<E;T+=3)x=(v[T]<<16&16711680)+(v[T+1]<<8&65280)+(255&v[T+2]),C.push(o[(A=x)>>18&63]+o[A>>12&63]+o[A>>6&63]+o[63&A]);return C.join("")}l[45]=62,l[95]=63},function(t,i){i.read=function(s,o,l,u,h){var d,p,g=8*h-u-1,m=(1<<g)-1,v=m>>1,S=-7,E=l?h-1:0,x=l?-1:1,A=s[o+E];for(E+=x,d=A&(1<<-S)-1,A>>=-S,S+=g;S>0;d=256*d+s[o+E],E+=x,S-=8);for(p=d&(1<<-S)-1,d>>=-S,S+=u;S>0;p=256*p+s[o+E],E+=x,S-=8);if(d===0)d=1-v;else{if(d===m)return p?NaN:1/0*(A?-1:1);p+=Math.pow(2,u),d-=v}return(A?-1:1)*p*Math.pow(2,d-u)},i.write=function(s,o,l,u,h,d){var p,g,m,v=8*d-h-1,S=(1<<v)-1,E=S>>1,x=h===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=u?0:d-1,C=u?1:-1,T=o<0||o===0&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(g=isNaN(o)?1:0,p=S):(p=Math.floor(Math.log(o)/Math.LN2),o*(m=Math.pow(2,-p))<1&&(p--,m*=2),(o+=p+E>=1?x/m:x*Math.pow(2,1-E))*m>=2&&(p++,m/=2),p+E>=S?(g=0,p=S):p+E>=1?(g=(o*m-1)*Math.pow(2,h),p+=E):(g=o*Math.pow(2,E-1)*Math.pow(2,h),p=0));h>=8;s[l+A]=255&g,A+=C,g/=256,h-=8);for(p=p<<h|g,v+=h;v>0;s[l+A]=255&p,A+=C,p/=256,v-=8);s[l+A-C]|=128*T}},function(t,i){var s={}.toString;t.exports=Array.isArray||function(o){return s.call(o)=="[object Array]"}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.default=function(u){var h=u.jws,d=u.KeyUtil,p=u.X509,g=u.crypto,m=u.hextob64u,v=u.b64tohex,S=u.AllowedSigningAlgs;return(function(){function E(){(function(A,C){if(!(A instanceof C))throw new TypeError("Cannot call a class as a function")})(this,E)}return E.parseJwt=function(A){o.Log.debug("JoseUtil.parseJwt");try{var C=h.JWS.parse(A);return{header:C.headerObj,payload:C.payloadObj}}catch(T){o.Log.error(T)}},E.validateJwt=function(A,C,T,F,P,q,O){o.Log.debug("JoseUtil.validateJwt");try{if(C.kty==="RSA")if(C.e&&C.n)C=d.getKey(C);else{if(!C.x5c||!C.x5c.length)return o.Log.error("JoseUtil.validateJwt: RSA key missing key material",C),Promise.reject(new Error("RSA key missing key material"));var G=v(C.x5c[0]);C=p.getPublicKeyFromCertHex(G)}else{if(C.kty!=="EC")return o.Log.error("JoseUtil.validateJwt: Unsupported key type",C&&C.kty),Promise.reject(new Error(C.kty));if(!(C.crv&&C.x&&C.y))return o.Log.error("JoseUtil.validateJwt: EC key missing key material",C),Promise.reject(new Error("EC key missing key material"));C=d.getKey(C)}return E._validateJwt(A,C,T,F,P,q,O)}catch(fe){return o.Log.error(fe&&fe.message||fe),Promise.reject("JWT validation failed")}},E.validateJwtAttributes=function(A,C,T,F,P,q){F||(F=0),P||(P=parseInt(Date.now()/1e3));var O=E.parseJwt(A).payload;if(!O.iss)return o.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(O.iss!==C)return o.Log.error("JoseUtil._validateJwt: Invalid issuer in token",O.iss),Promise.reject(new Error("Invalid issuer in token: "+O.iss));if(!O.aud)return o.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(O.aud===T||Array.isArray(O.aud)&&O.aud.indexOf(T)>=0))return o.Log.error("JoseUtil._validateJwt: Invalid audience in token",O.aud),Promise.reject(new Error("Invalid audience in token: "+O.aud));if(O.azp&&O.azp!==T)return o.Log.error("JoseUtil._validateJwt: Invalid azp in token",O.azp),Promise.reject(new Error("Invalid azp in token: "+O.azp));if(!q){var G=P+F,fe=P-F;if(!O.iat)return o.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(G<O.iat)return o.Log.error("JoseUtil._validateJwt: iat is in the future",O.iat),Promise.reject(new Error("iat is in the future: "+O.iat));if(O.nbf&&G<O.nbf)return o.Log.error("JoseUtil._validateJwt: nbf is in the future",O.nbf),Promise.reject(new Error("nbf is in the future: "+O.nbf));if(!O.exp)return o.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if(O.exp<fe)return o.Log.error("JoseUtil._validateJwt: exp is in the past",O.exp),Promise.reject(new Error("exp is in the past:"+O.exp))}return Promise.resolve(O)},E._validateJwt=function(A,C,T,F,P,q,O){return E.validateJwtAttributes(A,T,F,P,q,O).then((function(G){try{return h.JWS.verify(A,C,S)?G:(o.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(fe){return o.Log.error(fe&&fe.message||fe),Promise.reject(new Error("signature validation failed"))}}))},E.hashString=function(A,C){try{return g.Util.hashString(A,C)}catch(T){o.Log.error(T)}},E.hexToBase64Url=function(A){try{return m(A)}catch(C){o.Log.error(C)}},E})()};var o=s(0);t.exports=i.default},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SigninResponse=void 0;var o=(function(){function h(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(3);function u(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")}i.SigninResponse=(function(){function h(d){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#";u(this,h);var g=l.UrlUtility.parseUrlFragment(d,p);this.error=g.error,this.error_description=g.error_description,this.error_uri=g.error_uri,this.code=g.code,this.state=g.state,this.id_token=g.id_token,this.session_state=g.session_state,this.access_token=g.access_token,this.token_type=g.token_type,this.scope=g.scope,this.profile=void 0,this.expires_in=g.expires_in}return o(h,[{key:"expires_in",get:function(){if(this.expires_at){var p=parseInt(Date.now()/1e3);return this.expires_at-p}},set:function(p){var g=parseInt(p);if(typeof g=="number"&&g>0){var m=parseInt(Date.now()/1e3);this.expires_at=m+g}}},{key:"expired",get:function(){var p=this.expires_in;if(p!==void 0)return p<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutRequest=void 0;var o=s(0),l=s(3),u=s(9);i.SignoutRequest=function h(d){var p=d.url,g=d.id_token_hint,m=d.post_logout_redirect_uri,v=d.data,S=d.extraQueryParams,E=d.request_type;if((function(C,T){if(!(C instanceof T))throw new TypeError("Cannot call a class as a function")})(this,h),!p)throw o.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var x in g&&(p=l.UrlUtility.addQueryParam(p,"id_token_hint",g)),m&&(p=l.UrlUtility.addQueryParam(p,"post_logout_redirect_uri",m),v&&(this.state=new u.State({data:v,request_type:E}),p=l.UrlUtility.addQueryParam(p,"state",this.state.id))),S)p=l.UrlUtility.addQueryParam(p,x,S[x]);this.url=p}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutResponse=void 0;var o=s(3);i.SignoutResponse=function l(u){(function(p,g){if(!(p instanceof g))throw new TypeError("Cannot call a class as a function")})(this,l);var h=o.UrlUtility.parseUrlFragment(u,"?");this.error=h.error,this.error_description=h.error_description,this.error_uri=h.error_uri,this.state=h.state}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.InMemoryWebStorage=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.InMemoryWebStorage=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u),this._data={}}return u.prototype.getItem=function(d){return l.Log.debug("InMemoryWebStorage.getItem",d),this._data[d]},u.prototype.setItem=function(d,p){l.Log.debug("InMemoryWebStorage.setItem",d),this._data[d]=p},u.prototype.removeItem=function(d){l.Log.debug("InMemoryWebStorage.removeItem",d),delete this._data[d]},u.prototype.key=function(d){return Object.getOwnPropertyNames(this._data)[d]},o(u,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManager=void 0;var o=(function(){function T(F,P){for(var q=0;q<P.length;q++){var O=P[q];O.enumerable=O.enumerable||!1,O.configurable=!0,"value"in O&&(O.writable=!0),Object.defineProperty(F,O.key,O)}}return function(F,P,q){return P&&T(F.prototype,P),q&&T(F,q),F}})(),l=s(0),u=s(10),h=s(39),d=s(15),p=s(45),g=s(47),m=s(18),v=s(8),S=s(20),E=s(11),x=s(4);function A(T,F){if(!(T instanceof F))throw new TypeError("Cannot call a class as a function")}function C(T,F){if(!T)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!F||typeof F!="object"&&typeof F!="function"?T:F}i.UserManager=(function(T){function F(){var P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:g.SilentRenewService,O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:m.SessionMonitor,G=arguments.length>3&&arguments[3]!==void 0?arguments[3]:S.TokenRevocationClient,fe=arguments.length>4&&arguments[4]!==void 0?arguments[4]:E.TokenClient,M=arguments.length>5&&arguments[5]!==void 0?arguments[5]:x.JoseUtil;A(this,F),P instanceof h.UserManagerSettings||(P=new h.UserManagerSettings(P));var ee=C(this,T.call(this,P));return ee._events=new p.UserManagerEvents(P),ee._silentRenewService=new q(ee),ee.settings.automaticSilentRenew&&(l.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),ee.startSilentRenew()),ee.settings.monitorSession&&(l.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),ee._sessionMonitor=new O(ee)),ee._tokenRevocationClient=new G(ee._settings),ee._tokenClient=new fe(ee._settings),ee._joseUtil=M,ee}return(function(q,O){if(typeof O!="function"&&O!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof O);q.prototype=Object.create(O&&O.prototype,{constructor:{value:q,enumerable:!1,writable:!0,configurable:!0}}),O&&(Object.setPrototypeOf?Object.setPrototypeOf(q,O):q.__proto__=O)})(F,T),F.prototype.getUser=function(){var q=this;return this._loadUser().then((function(O){return O?(l.Log.info("UserManager.getUser: user loaded"),q._events.load(O,!1),O):(l.Log.info("UserManager.getUser: user not found in storage"),null)}))},F.prototype.removeUser=function(){var q=this;return this.storeUser(null).then((function(){l.Log.info("UserManager.removeUser: user removed from storage"),q._events.unload()}))},F.prototype.signinRedirect=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(q=Object.assign({},q)).request_type="si:r";var O={useReplaceToNavigate:q.useReplaceToNavigate};return this._signinStart(q,this._redirectNavigator,O).then((function(){l.Log.info("UserManager.signinRedirect: successful")}))},F.prototype.signinRedirectCallback=function(q){return this._signinEnd(q||this._redirectNavigator.url).then((function(O){return O.profile&&O.profile.sub?l.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinRedirectCallback: no sub"),O}))},F.prototype.signinPopup=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(q=Object.assign({},q)).request_type="si:p";var O=q.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return O?(q.redirect_uri=O,q.display="popup",this._signin(q,this._popupNavigator,{startUrl:O,popupWindowFeatures:q.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:q.popupWindowTarget||this.settings.popupWindowTarget}).then((function(G){return G&&(G.profile&&G.profile.sub?l.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",G.profile.sub):l.Log.info("UserManager.signinPopup: no sub")),G}))):(l.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},F.prototype.signinPopupCallback=function(q){return this._signinCallback(q,this._popupNavigator).then((function(O){return O&&(O.profile&&O.profile.sub?l.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinPopupCallback: no sub")),O})).catch((function(O){l.Log.error(O.message)}))},F.prototype.signinSilent=function(){var q=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return O=Object.assign({},O),this._loadUser().then((function(G){return G&&G.refresh_token?(O.refresh_token=G.refresh_token,q._useRefreshToken(O)):(O.request_type="si:s",O.id_token_hint=O.id_token_hint||q.settings.includeIdTokenInSilentRenew&&G&&G.id_token,G&&q._settings.validateSubOnSilentRenew&&(l.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",G.profile.sub),O.current_sub=G.profile.sub),q._signinSilentIframe(O))}))},F.prototype._useRefreshToken=function(){var q=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(O).then((function(G){return G?G.access_token?q._loadUser().then((function(fe){if(fe){var M=Promise.resolve();return G.id_token&&(M=q._validateIdTokenFromTokenRefreshToken(fe.profile,G.id_token)),M.then((function(){return l.Log.debug("UserManager._useRefreshToken: refresh token response success"),fe.id_token=G.id_token||fe.id_token,fe.access_token=G.access_token,fe.refresh_token=G.refresh_token||fe.refresh_token,fe.expires_in=G.expires_in,q.storeUser(fe).then((function(){return q._events.load(fe),fe}))}))}return null})):(l.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(l.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},F.prototype._validateIdTokenFromTokenRefreshToken=function(q,O){var G=this;return this._metadataService.getIssuer().then((function(fe){return G.settings.getEpochTime().then((function(M){return G._joseUtil.validateJwtAttributes(O,fe,G._settings.client_id,G._settings.clockSkew,M).then((function(ee){return ee?ee.sub!==q.sub?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: sub in id_token does not match current sub"),Promise.reject(new Error("sub in id_token does not match current sub"))):ee.auth_time&&ee.auth_time!==q.auth_time?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: auth_time in id_token does not match original auth_time"),Promise.reject(new Error("auth_time in id_token does not match original auth_time"))):ee.azp&&ee.azp!==q.azp?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp in id_token does not match original azp"),Promise.reject(new Error("azp in id_token does not match original azp"))):!ee.azp&&q.azp?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp not in id_token, but present in original id_token"),Promise.reject(new Error("azp not in id_token, but present in original id_token"))):void 0:(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},F.prototype._signinSilentIframe=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},O=q.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return O?(q.redirect_uri=O,q.prompt=q.prompt||"none",this._signin(q,this._iframeNavigator,{startUrl:O,silentRequestTimeout:q.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(G){return G&&(G.profile&&G.profile.sub?l.Log.info("UserManager.signinSilent: successful, signed in sub: ",G.profile.sub):l.Log.info("UserManager.signinSilent: no sub")),G}))):(l.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype.signinSilentCallback=function(q){return this._signinCallback(q,this._iframeNavigator).then((function(O){return O&&(O.profile&&O.profile.sub?l.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinSilentCallback: no sub")),O}))},F.prototype.signinCallback=function(q){var O=this;return this.readSigninResponseState(q).then((function(G){var fe=G.state;return G.response,fe.request_type==="si:r"?O.signinRedirectCallback(q):fe.request_type==="si:p"?O.signinPopupCallback(q):fe.request_type==="si:s"?O.signinSilentCallback(q):Promise.reject(new Error("invalid response_type in state"))}))},F.prototype.signoutCallback=function(q,O){var G=this;return this.readSignoutResponseState(q).then((function(fe){var M=fe.state,ee=fe.response;return M?M.request_type==="so:r"?G.signoutRedirectCallback(q):M.request_type==="so:p"?G.signoutPopupCallback(q,O):Promise.reject(new Error("invalid response_type in state")):ee}))},F.prototype.querySessionStatus=function(){var q=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(O=Object.assign({},O)).request_type="si:s";var G=O.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return G?(O.redirect_uri=G,O.prompt="none",O.response_type=O.response_type||this.settings.query_status_response_type,O.scope=O.scope||"openid",O.skipUserInfo=!0,this._signinStart(O,this._iframeNavigator,{startUrl:G,silentRequestTimeout:O.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(fe){return q.processSigninResponse(fe.url).then((function(M){if(l.Log.debug("UserManager.querySessionStatus: got signin response"),M.session_state&&M.profile.sub)return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",M.profile.sub),{session_state:M.session_state,sub:M.profile.sub,sid:M.profile.sid};l.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(M){if(M.session_state&&q.settings.monitorAnonymousSession&&(M.message=="login_required"||M.message=="consent_required"||M.message=="interaction_required"||M.message=="account_selection_required"))return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:M.session_state};throw M}))}))):(l.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype._signin=function(q,O){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signinStart(q,O,fe).then((function(M){return G._signinEnd(M.url,q)}))},F.prototype._signinStart=function(q,O){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return O.prepare(fe).then((function(M){return l.Log.debug("UserManager._signinStart: got navigator window handle"),G.createSigninRequest(q).then((function(ee){return l.Log.debug("UserManager._signinStart: got signin request"),fe.url=ee.url,fe.id=ee.state.id,M.navigate(fe)})).catch((function(ee){throw M.close&&(l.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),M.close()),ee}))}))},F.prototype._signinEnd=function(q){var O=this,G=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.processSigninResponse(q).then((function(fe){l.Log.debug("UserManager._signinEnd: got signin response");var M=new d.User(fe);if(G.current_sub){if(G.current_sub!==M.profile.sub)return l.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",M.profile.sub),Promise.reject(new Error("login_required"));l.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return O.storeUser(M).then((function(){return l.Log.debug("UserManager._signinEnd: user stored"),O._events.load(M),M}))}))},F.prototype._signinCallback=function(q,O){l.Log.debug("UserManager._signinCallback");var G=this._settings.response_mode==="query"||!this._settings.response_mode&&v.SigninRequest.isCode(this._settings.response_type)?"?":"#";return O.callback(q,void 0,G)},F.prototype.signoutRedirect=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(q=Object.assign({},q)).request_type="so:r";var O=q.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;O&&(q.post_logout_redirect_uri=O);var G={useReplaceToNavigate:q.useReplaceToNavigate};return this._signoutStart(q,this._redirectNavigator,G).then((function(){l.Log.info("UserManager.signoutRedirect: successful")}))},F.prototype.signoutRedirectCallback=function(q){return this._signoutEnd(q||this._redirectNavigator.url).then((function(O){return l.Log.info("UserManager.signoutRedirectCallback: successful"),O}))},F.prototype.signoutPopup=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(q=Object.assign({},q)).request_type="so:p";var O=q.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return q.post_logout_redirect_uri=O,q.display="popup",q.post_logout_redirect_uri&&(q.state=q.state||{}),this._signout(q,this._popupNavigator,{startUrl:O,popupWindowFeatures:q.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:q.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){l.Log.info("UserManager.signoutPopup: successful")}))},F.prototype.signoutPopupCallback=function(q,O){return O===void 0&&typeof q=="boolean"&&(O=q,q=null),this._popupNavigator.callback(q,O,"?").then((function(){l.Log.info("UserManager.signoutPopupCallback: successful")}))},F.prototype._signout=function(q,O){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signoutStart(q,O,fe).then((function(M){return G._signoutEnd(M.url)}))},F.prototype._signoutStart=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},O=this,G=arguments[1],fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return G.prepare(fe).then((function(M){return l.Log.debug("UserManager._signoutStart: got navigator window handle"),O._loadUser().then((function(ee){return l.Log.debug("UserManager._signoutStart: loaded current user from storage"),(O._settings.revokeAccessTokenOnSignout?O._revokeInternal(ee):Promise.resolve()).then((function(){var Se=q.id_token_hint||ee&&ee.id_token;return Se&&(l.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),q.id_token_hint=Se),O.removeUser().then((function(){return l.Log.debug("UserManager._signoutStart: user removed, creating signout request"),O.createSignoutRequest(q).then((function(re){return l.Log.debug("UserManager._signoutStart: got signout request"),fe.url=re.url,re.state&&(fe.id=re.state.id),M.navigate(fe)}))}))}))})).catch((function(ee){throw M.close&&(l.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),M.close()),ee}))}))},F.prototype._signoutEnd=function(q){return this.processSignoutResponse(q).then((function(O){return l.Log.debug("UserManager._signoutEnd: got signout response"),O}))},F.prototype.revokeAccessToken=function(){var q=this;return this._loadUser().then((function(O){return q._revokeInternal(O,!0).then((function(G){if(G)return l.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),O.access_token=null,O.refresh_token=null,O.expires_at=null,O.token_type=null,q.storeUser(O).then((function(){l.Log.debug("UserManager.revokeAccessToken: user stored"),q._events.load(O)}))}))})).then((function(){l.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},F.prototype._revokeInternal=function(q,O){var G=this;if(q){var fe=q.access_token,M=q.refresh_token;return this._revokeAccessTokenInternal(fe,O).then((function(ee){return G._revokeRefreshTokenInternal(M,O).then((function(Se){return ee||Se||l.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),ee||Se}))}))}return Promise.resolve(!1)},F.prototype._revokeAccessTokenInternal=function(q,O){return!q||q.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(q,O).then((function(){return!0}))},F.prototype._revokeRefreshTokenInternal=function(q,O){return q?this._tokenRevocationClient.revoke(q,O,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},F.prototype.startSilentRenew=function(){this._silentRenewService.start()},F.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},F.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(q){return q?(l.Log.debug("UserManager._loadUser: user storageString loaded"),d.User.fromStorageString(q)):(l.Log.debug("UserManager._loadUser: no user storageString"),null)}))},F.prototype.storeUser=function(q){if(q){l.Log.debug("UserManager.storeUser: storing user");var O=q.toStorageString();return this._userStore.set(this._userStoreKey,O)}return l.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},o(F,[{key:"_redirectNavigator",get:function(){return this.settings.redirectNavigator}},{key:"_popupNavigator",get:function(){return this.settings.popupNavigator}},{key:"_iframeNavigator",get:function(){return this.settings.iframeNavigator}},{key:"_userStore",get:function(){return this.settings.userStore}},{key:"events",get:function(){return this._events}},{key:"_userStoreKey",get:function(){return"user:"+this.settings.authority+":"+this.settings.client_id}}]),F})(u.OidcClient)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerSettings=void 0;var o=(function(){function E(x,A){for(var C=0;C<A.length;C++){var T=A[C];T.enumerable=T.enumerable||!1,T.configurable=!0,"value"in T&&(T.writable=!0),Object.defineProperty(x,T.key,T)}}return function(x,A,C){return A&&E(x.prototype,A),C&&E(x,C),x}})(),l=(s(0),s(5)),u=s(40),h=s(41),d=s(43),p=s(6),g=s(1),m=s(8);function v(E,x){if(!(E instanceof x))throw new TypeError("Cannot call a class as a function")}function S(E,x){if(!E)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!x||typeof x!="object"&&typeof x!="function"?E:x}i.UserManagerSettings=(function(E){function x(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},C=A.popup_redirect_uri,T=A.popup_post_logout_redirect_uri,F=A.popupWindowFeatures,P=A.popupWindowTarget,q=A.silent_redirect_uri,O=A.silentRequestTimeout,G=A.automaticSilentRenew,fe=G!==void 0&&G,M=A.validateSubOnSilentRenew,ee=M!==void 0&&M,Se=A.includeIdTokenInSilentRenew,re=Se===void 0||Se,Ae=A.monitorSession,ke=Ae===void 0||Ae,he=A.monitorAnonymousSession,Oe=he!==void 0&&he,ce=A.checkSessionInterval,Ue=ce===void 0?2e3:ce,$=A.stopCheckSessionOnError,W=$===void 0||$,de=A.query_status_response_type,te=A.revokeAccessTokenOnSignout,Te=te!==void 0&&te,je=A.accessTokenExpiringNotificationTime,He=je===void 0?60:je,We=A.redirectNavigator,me=We===void 0?new u.RedirectNavigator:We,ge=A.popupNavigator,Be=ge===void 0?new h.PopupNavigator:ge,ie=A.iframeNavigator,B=ie===void 0?new d.IFrameNavigator:ie,N=A.userStore,k=N===void 0?new p.WebStorageStateStore({store:g.Global.sessionStorage}):N;v(this,x);var H=S(this,E.call(this,arguments[0]));return H._popup_redirect_uri=C,H._popup_post_logout_redirect_uri=T,H._popupWindowFeatures=F,H._popupWindowTarget=P,H._silent_redirect_uri=q,H._silentRequestTimeout=O,H._automaticSilentRenew=fe,H._validateSubOnSilentRenew=ee,H._includeIdTokenInSilentRenew=re,H._accessTokenExpiringNotificationTime=He,H._monitorSession=ke,H._monitorAnonymousSession=Oe,H._checkSessionInterval=Ue,H._stopCheckSessionOnError=W,de?H._query_status_response_type=de:arguments[0]&&arguments[0].response_type?H._query_status_response_type=m.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":H._query_status_response_type="id_token",H._revokeAccessTokenOnSignout=Te,H._redirectNavigator=me,H._popupNavigator=Be,H._iframeNavigator=B,H._userStore=k,H}return(function(C,T){if(typeof T!="function"&&T!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof T);C.prototype=Object.create(T&&T.prototype,{constructor:{value:C,enumerable:!1,writable:!0,configurable:!0}}),T&&(Object.setPrototypeOf?Object.setPrototypeOf(C,T):C.__proto__=T)})(x,E),o(x,[{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}}]),x})(l.OidcClientSettings)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.RedirectNavigator=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.RedirectNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(){return Promise.resolve(this)},u.prototype.navigate=function(d){return d&&d.url?(d.useReplaceToNavigate?window.location.replace(d.url):window.location=d.url,Promise.resolve()):(l.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},o(u,[{key:"url",get:function(){return window.location.href}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupNavigator=void 0;var o=s(0),l=s(42);i.PopupNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.PopupWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d,p,g){o.Log.debug("PopupNavigator.callback");try{return l.PopupWindow.notifyOpener(d,p,g),Promise.resolve()}catch(m){return Promise.reject(m)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupWindow=void 0;var o=(function(){function h(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(0),u=s(3);i.PopupWindow=(function(){function h(d){var p=this;(function(S,E){if(!(S instanceof E))throw new TypeError("Cannot call a class as a function")})(this,h),this._promise=new Promise((function(v,S){p._resolve=v,p._reject=S}));var g=d.popupWindowTarget||"_blank",m=d.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",g,m),this._popup&&(l.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return h.prototype.navigate=function(p){return this._popup?p&&p.url?(l.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=p.id,this._id&&(window["popupCallback_"+p.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=p.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},h.prototype._success=function(p){l.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(p)},h.prototype._error=function(p){l.Log.error("PopupWindow.error: ",p),this._cleanup(),this._reject(new Error(p))},h.prototype.close=function(){this._cleanup(!1)},h.prototype._cleanup=function(p){l.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!p&&this._popup.close(),this._popup=null},h.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},h.prototype._callback=function(p,g){this._cleanup(g),p?(l.Log.debug("PopupWindow.callback success"),this._success({url:p})):(l.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},h.notifyOpener=function(p,g,m){if(window.opener){if(p=p||window.location.href){var v=u.UrlUtility.parseUrlFragment(p,m);if(v.state){var S="popupCallback_"+v.state,E=window.opener[S];E?(l.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),E(p,g)):l.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else l.Log.warn("PopupWindow.notifyOpener: no state found in response url")}}else l.Log.warn("PopupWindow.notifyOpener: no window.opener. Can't complete notification.")},o(h,[{key:"promise",get:function(){return this._promise}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameNavigator=void 0;var o=s(0),l=s(44);i.IFrameNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.IFrameWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d){o.Log.debug("IFrameNavigator.callback");try{return l.IFrameWindow.notifyParent(d),Promise.resolve()}catch(p){return Promise.reject(p)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameWindow=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.IFrameWindow=(function(){function u(h){var d=this;(function(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")})(this,u),this._promise=new Promise((function(p,g){d._resolve=p,d._reject=g})),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.width=0,this._frame.height=0,window.document.body.appendChild(this._frame)}return u.prototype.navigate=function(d){if(d&&d.url){var p=d.silentRequestTimeout||1e4;l.Log.debug("IFrameWindow.navigate: Using timeout of:",p),this._timer=window.setTimeout(this._timeout.bind(this),p),this._frame.src=d.url}else this._error("No url provided");return this.promise},u.prototype._success=function(d){this._cleanup(),l.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(d)},u.prototype._error=function(d){this._cleanup(),l.Log.error(d),this._reject(new Error(d))},u.prototype.close=function(){this._cleanup()},u.prototype._cleanup=function(){this._frame&&(l.Log.debug("IFrameWindow: cleanup"),window.removeEventListener("message",this._boundMessageEvent,!1),window.clearTimeout(this._timer),window.document.body.removeChild(this._frame),this._timer=null,this._frame=null,this._boundMessageEvent=null)},u.prototype._timeout=function(){l.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},u.prototype._message=function(d){if(l.Log.debug("IFrameWindow.message"),this._timer&&d.origin===this._origin&&d.source===this._frame.contentWindow&&typeof d.data=="string"&&(d.data.startsWith("http://")||d.data.startsWith("https://"))){var p=d.data;p?this._success({url:p}):this._error("Invalid response from frame")}},u.notifyParent=function(d){l.Log.debug("IFrameWindow.notifyParent"),(d=d||window.location.href)&&(l.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(d,location.protocol+"//"+location.host))},o(u,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerEvents=void 0;var o=s(0),l=s(16),u=s(17);i.UserManagerEvents=(function(h){function d(p){(function(v,S){if(!(v instanceof S))throw new TypeError("Cannot call a class as a function")})(this,d);var g=(function(v,S){if(!v)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!S||typeof S!="object"&&typeof S!="function"?v:S})(this,h.call(this,p));return g._userLoaded=new u.Event("User loaded"),g._userUnloaded=new u.Event("User unloaded"),g._silentRenewError=new u.Event("Silent renew error"),g._userSignedIn=new u.Event("User signed in"),g._userSignedOut=new u.Event("User signed out"),g._userSessionChanged=new u.Event("User session changed"),g}return(function(g,m){if(typeof m!="function"&&m!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof m);g.prototype=Object.create(m&&m.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),m&&(Object.setPrototypeOf?Object.setPrototypeOf(g,m):g.__proto__=m)})(d,h),d.prototype.load=function(g){var m=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];o.Log.debug("UserManagerEvents.load"),h.prototype.load.call(this,g),m&&this._userLoaded.raise(g)},d.prototype.unload=function(){o.Log.debug("UserManagerEvents.unload"),h.prototype.unload.call(this),this._userUnloaded.raise()},d.prototype.addUserLoaded=function(g){this._userLoaded.addHandler(g)},d.prototype.removeUserLoaded=function(g){this._userLoaded.removeHandler(g)},d.prototype.addUserUnloaded=function(g){this._userUnloaded.addHandler(g)},d.prototype.removeUserUnloaded=function(g){this._userUnloaded.removeHandler(g)},d.prototype.addSilentRenewError=function(g){this._silentRenewError.addHandler(g)},d.prototype.removeSilentRenewError=function(g){this._silentRenewError.removeHandler(g)},d.prototype._raiseSilentRenewError=function(g){o.Log.debug("UserManagerEvents._raiseSilentRenewError",g.message),this._silentRenewError.raise(g)},d.prototype.addUserSignedIn=function(g){this._userSignedIn.addHandler(g)},d.prototype.removeUserSignedIn=function(g){this._userSignedIn.removeHandler(g)},d.prototype._raiseUserSignedIn=function(){o.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},d.prototype.addUserSignedOut=function(g){this._userSignedOut.addHandler(g)},d.prototype.removeUserSignedOut=function(g){this._userSignedOut.removeHandler(g)},d.prototype._raiseUserSignedOut=function(){o.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},d.prototype.addUserSessionChanged=function(g){this._userSessionChanged.addHandler(g)},d.prototype.removeUserSessionChanged=function(g){this._userSessionChanged.removeHandler(g)},d.prototype._raiseUserSessionChanged=function(){o.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},d})(l.AccessTokenEvents)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Timer=void 0;var o=(function(){function g(m,v){for(var S=0;S<v.length;S++){var E=v[S];E.enumerable=E.enumerable||!1,E.configurable=!0,"value"in E&&(E.writable=!0),Object.defineProperty(m,E.key,E)}}return function(m,v,S){return v&&g(m.prototype,v),S&&g(m,S),m}})(),l=s(0),u=s(1),h=s(17);function d(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")}function p(g,m){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!m||typeof m!="object"&&typeof m!="function"?g:m}i.Timer=(function(g){function m(v){var S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u.Global.timer,E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;d(this,m);var x=p(this,g.call(this,v));return x._timer=S,x._nowFunc=E||function(){return Date.now()/1e3},x}return(function(S,E){if(typeof E!="function"&&E!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof E);S.prototype=Object.create(E&&E.prototype,{constructor:{value:S,enumerable:!1,writable:!0,configurable:!0}}),E&&(Object.setPrototypeOf?Object.setPrototypeOf(S,E):S.__proto__=E)})(m,g),m.prototype.init=function(S){S<=0&&(S=1),S=parseInt(S);var E=this.now+S;if(this.expiration===E&&this._timerHandle)l.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),l.Log.debug("Timer.init timer "+this._name+" for duration:",S),this._expiration=E;var x=5;S<x&&(x=S),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*x)}},m.prototype.cancel=function(){this._timerHandle&&(l.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},m.prototype._callback=function(){var S=this._expiration-this.now;l.Log.debug("Timer.callback; "+this._name+" timer expires in:",S),this._expiration<=this.now&&(this.cancel(),g.prototype.raise.call(this))},o(m,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),m})(h.Event)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SilentRenewService=void 0;var o=s(0);i.SilentRenewService=(function(){function l(u){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,l),this._userManager=u}return l.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then((function(h){})).catch((function(h){o.Log.error("SilentRenewService.start: Error from getUser:",h.message)})))},l.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},l.prototype._tokenExpiring=function(){var h=this;this._userManager.signinSilent().then((function(d){o.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")}),(function(d){o.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",d.message),h._userManager.events._raiseSilentRenewError(d)}))},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaPopupNavigator=void 0;var o=s(21);i.CordovaPopupNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){var d=new o.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaIFrameNavigator=void 0;var o=s(21);i.CordovaIFrameNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){h.popupWindowFeatures="hidden=yes";var d=new o.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Version="1.11.6"}])}))})(oidcClient_min$1)),oidcClient_min$1.exports}var oidcClient_minExports=requireOidcClient_min();function processErrorResponse(n,e){throw n.error==="invalid_redirect_uri"?new Error(`Dynamic client registration failed: the provided redirect uri [${e.redirectUrl?.toString()}] is invalid - ${n.error_description??""}`):n.error==="invalid_client_metadata"?new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(e)} is invalid - ${n.error_description??""}`):new Error(`Dynamic client registration failed: ${n.error} - ${n.error_description??""}`)}function hasClientId(n){return typeof n.client_id=="string"}function hasRedirectUri(n){return Array.isArray(n.redirect_uris)&&n.redirect_uris.every(e=>typeof e=="string")}function validateRegistrationResponse(n,e){if(!hasClientId(n))throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(n)}`);if(e.redirectUrl&&hasRedirectUri(n)&&n.redirect_uris[0]!==e.redirectUrl.toString())throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(n.redirect_uris)} don't match the provided ${JSON.stringify([e.redirectUrl.toString()])}`);return!0}async function registerClient(n,e){if(!e.registrationEndpoint)throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");if(!Array.isArray(e.idTokenSigningAlgValuesSupported))throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");const t=determineSigningAlg(e.idTokenSigningAlgValuesSupported,PREFERRED_SIGNING_ALG),i={client_name:n.clientName,application_type:"web",redirect_uris:[n.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:t,grant_types:["authorization_code","refresh_token"]},s={"Content-Type":"application/json"},o=await fetch(e.registrationEndpoint.toString(),{method:"POST",headers:s,body:JSON.stringify(i)});if(o.ok){const l=await o.json();return validateRegistrationResponse(l,n),{clientId:l.client_id,clientSecret:l.client_secret,expiresAt:l.client_secret_expires_at,idTokenSignedResponseAlg:l.id_token_signed_response_alg,clientType:"dynamic"}}throw o.status===400&&processErrorResponse(await o.json(),n),new Error(`Dynamic client registration failed: the server returned ${o.status} ${o.statusText} - ${await o.text()}`)}function hasError(n){return n.error!==void 0&&typeof n.error=="string"}function hasErrorDescription(n){return n.error_description!==void 0&&typeof n.error_description=="string"}function hasErrorUri(n){return n.error_uri!==void 0&&typeof n.error_uri=="string"}function hasAccessToken(n){return n.access_token!==void 0&&typeof n.access_token=="string"}function hasIdToken(n){return n.id_token!==void 0&&typeof n.id_token=="string"}function hasRefreshToken(n){return n.refresh_token!==void 0&&typeof n.refresh_token=="string"}function hasTokenType(n){return n.token_type!==void 0&&typeof n.token_type=="string"}function hasExpiresIn(n){return n.expires_in===void 0||typeof n.expires_in=="number"}function validatePreconditions(n,e){if(e.grantType&&(!n.grantTypesSupported||!n.grantTypesSupported.includes(e.grantType)))throw new Error(`The issuer [${n.issuer}] does not support the [${e.grantType}] grant`);if(!n.tokenEndpoint)throw new Error(`This issuer [${n.issuer}] does not have a token endpoint`)}function validateTokenEndpointResponse(n,e){if(hasError(n))throw new OidcProviderError(`Token endpoint returned error [${n.error}]${hasErrorDescription(n)?`: ${n.error_description}`:""}${hasErrorUri(n)?` (see ${n.error_uri})`:""}`,n.error,hasErrorDescription(n)?n.error_description:void 0);if(!hasAccessToken(n))throw new InvalidResponseError(["access_token"]);if(!hasIdToken(n))throw new InvalidResponseError(["id_token"]);if(!hasTokenType(n))throw new InvalidResponseError(["token_type"]);if(!hasExpiresIn(n))throw new InvalidResponseError(["expires_in"]);if(!e&&n.token_type.toLowerCase()!=="bearer")throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${n.token_type}].`);return n}async function getTokens(n,e,t,i){validatePreconditions(n,t);const s={"content-type":"application/x-www-form-urlencoded"};let o;i&&(o=await generateDpopKeyPair(),s.DPoP=await createDpopHeader(n.tokenEndpoint,"POST",o)),e.clientSecret&&(s.Authorization=`Basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`);const l={grant_type:t.grantType,redirect_uri:t.redirectUrl,code:t.code,code_verifier:t.codeVerifier,client_id:e.clientId},u={method:"POST",headers:s,body:new URLSearchParams(l).toString()},d=await(await fetch(n.tokenEndpoint,u)).json(),p=validateTokenEndpointResponse(d,i),{webId:g,clientId:m}=await getWebidFromTokenPayload(p.id_token,n.jwksUri,n.issuer,e.clientId);return{accessToken:p.access_token,idToken:p.id_token,refreshToken:hasRefreshToken(p)?p.refresh_token:void 0,webId:g,clientId:m,dpopKey:o,expiresIn:p.expires_in}}const isValidUrl=n=>{try{return new URL(n),!0}catch{return!1}};async function refresh(n,e,t,i){if(t.clientId===void 0)throw new Error("No client ID available when trying to refresh the access token.");const s={grant_type:"refresh_token",refresh_token:n};let o={};i!==void 0&&(o={DPoP:await createDpopHeader(e.tokenEndpoint,"POST",i)});let l={};t.clientSecret!==void 0?l={Authorization:`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`}:isValidUrl(t.clientId)&&(s.client_id=t.clientId);const u=await fetch(e.tokenEndpoint,{method:"POST",body:new URLSearchParams(s).toString(),headers:{...o,...l,"Content-Type":"application/x-www-form-urlencoded"}});let h;try{h=await u.json()}catch{throw new Error(`The token endpoint of issuer ${e.issuer} returned a malformed response.`)}const d=validateTokenEndpointResponse(h,i!==void 0),{webId:p}=await getWebidFromTokenPayload(d.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:d.access_token,idToken:d.id_token,refreshToken:typeof d.refresh_token=="string"?d.refresh_token:void 0,webId:p,dpopKey:i,expiresIn:d.expires_in}}function normalizeCallbackUrl(n){const e=removeOpenIdParams(n);return e.hash="",n.includes(`${e.origin}/`)?e.href:`${e.origin}${e.href.substring(e.origin.length+1)}`}async function clearOidcPersistentStorage(){await new oidcClient_minExports.OidcClient({response_mode:"query"}).clearStaleState(new oidcClient_minExports.WebStorageStateStore({}));const e=window.localStorage,t=[];for(let i=0;i<=e.length;i+=1){const s=e.key(i);s&&(s.match(/^oidc\..+$/)||s.match(/^solidClientAuthenticationUser:.+$/))&&t.push(s)}t.forEach(i=>e.removeItem(i))}class StorageUtilityBrowser extends StorageUtility{constructor(e,t){super(e,t)}}class ClientAuthentication extends ClientAuthentication$1{login=async(e,t)=>{e.prompt!=="none"&&await this.sessionInfoManager.clear(e.sessionId);const i=e.redirectUrl??normalizeCallbackUrl(window.location.href);if(!isValidRedirectUrl(i))throw new Error(`${i} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);await this.loginHandler.handle({...e,redirectUrl:i,clientName:e.clientName??e.clientId,eventEmitter:t})};validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return t===void 0||t.clientAppId===void 0||t.issuer===void 0?null:t};handleIncomingRedirect=async(e,t)=>{try{const i=await this.redirectHandler.handle(e,t,void 0);return this.fetch=i.fetch.bind(window),this.boundLogout=i.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:i.isLoggedIn,webId:i.webId,sessionId:i.sessionId,expirationDate:i.expirationDate,clientAppId:i.clientAppId}}catch(i){await this.cleanUrlAfterRedirect(e),t.emit(EVENTS.ERROR,"redirect",i);return}};async cleanUrlAfterRedirect(e){const t=removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(i=>{setTimeout(()=>i(),1)})}}function hasIssuer(n){return typeof n.oidcIssuer=="string"}function hasRedirectUrl(n){return typeof n.redirectUrl=="string"}class OidcLoginHandler{storageUtility;oidcHandler;issuerConfigFetcher;clientRegistrar;constructor(e,t,i,s){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s}async canHandle(e){return hasIssuer(e)&&hasRedirectUrl(e)}async handle(e){if(!hasIssuer(e))throw new ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!hasRedirectUrl(e))throw new ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),i=await handleRegistration(e,t,this.storageUtility,this.clientRegistrar),s={issuer:t.issuer,dpop:e.tokenType.toLowerCase()==="dpop",...e,issuerConfiguration:t,client:i,scopes:normalizeScopes(e.customScopes)};return this.oidcHandler.handle(s)}}class AuthorizationCodeWithPkceOidcHandler extends AuthorizationCodeWithPkceOidcHandlerBase{async handle(e){const t={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:e.prompt??"consent"},i=new oidcClient_minExports.OidcClient(t);try{const s=await i.createSigninRequest();return await this.setupRedirectHandler({oidcLoginOptions:e,state:s.state._id,codeVerifier:s.state._code_verifier,targetUrl:s.url.toString()})}catch(s){console.error(s)}}}const WELL_KNOWN_OPENID_CONFIG=".well-known/openid-configuration",issuerConfigKeyMap={issuer:{toKey:"issuer",convertToUrl:!0},authorization_endpoint:{toKey:"authorizationEndpoint",convertToUrl:!0},token_endpoint:{toKey:"tokenEndpoint",convertToUrl:!0},userinfo_endpoint:{toKey:"userinfoEndpoint",convertToUrl:!0},jwks_uri:{toKey:"jwksUri",convertToUrl:!0},registration_endpoint:{toKey:"registrationEndpoint",convertToUrl:!0},end_session_endpoint:{toKey:"endSessionEndpoint",convertToUrl:!0},scopes_supported:{toKey:"scopesSupported"},response_types_supported:{toKey:"responseTypesSupported"},response_modes_supported:{toKey:"responseModesSupported"},grant_types_supported:{toKey:"grantTypesSupported"},acr_values_supported:{toKey:"acrValuesSupported"},subject_types_supported:{toKey:"subjectTypesSupported"},id_token_signing_alg_values_supported:{toKey:"idTokenSigningAlgValuesSupported"},id_token_encryption_alg_values_supported:{toKey:"idTokenEncryptionAlgValuesSupported"},id_token_encryption_enc_values_supported:{toKey:"idTokenEncryptionEncValuesSupported"},userinfo_signing_alg_values_supported:{toKey:"userinfoSigningAlgValuesSupported"},userinfo_encryption_alg_values_supported:{toKey:"userinfoEncryptionAlgValuesSupported"},userinfo_encryption_enc_values_supported:{toKey:"userinfoEncryptionEncValuesSupported"},request_object_signing_alg_values_supported:{toKey:"requestObjectSigningAlgValuesSupported"},request_object_encryption_alg_values_supported:{toKey:"requestObjectEncryptionAlgValuesSupported"},request_object_encryption_enc_values_supported:{toKey:"requestObjectEncryptionEncValuesSupported"},token_endpoint_auth_methods_supported:{toKey:"tokenEndpointAuthMethodsSupported"},token_endpoint_auth_signing_alg_values_supported:{toKey:"tokenEndpointAuthSigningAlgValuesSupported"},display_values_supported:{toKey:"displayValuesSupported"},claim_types_supported:{toKey:"claimTypesSupported"},claims_supported:{toKey:"claimsSupported"},service_documentation:{toKey:"serviceDocumentation"},claims_locales_supported:{toKey:"claimsLocalesSupported"},ui_locales_supported:{toKey:"uiLocalesSupported"},claims_parameter_supported:{toKey:"claimsParameterSupported"},request_parameter_supported:{toKey:"requestParameterSupported"},request_uri_parameter_supported:{toKey:"requestUriParameterSupported"},require_request_uri_registration:{toKey:"requireRequestUriRegistration"},op_policy_uri:{toKey:"opPolicyUri",convertToUrl:!0},op_tos_uri:{toKey:"opTosUri",convertToUrl:!0}};function processConfig(n){const e={};return Object.keys(n).forEach(t=>{issuerConfigKeyMap[t]&&(e[issuerConfigKeyMap[t].toKey]=n[t])}),Array.isArray(e.scopesSupported)||(e.scopesSupported=["openid"]),e}class IssuerConfigFetcher{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}static getLocalStorageKey(e){return`issuerConfig:${e}`}async fetchConfig(e){let t;const i=new URL(WELL_KNOWN_OPENID_CONFIG,e.endsWith("/")?e:`${e}/`).href,s=await fetch(i);try{t=processConfig(await s.json())}catch(o){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${o.message}`)}return await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t}}async function clear(n,e){await clear$1(n,e),await clearOidcPersistentStorage()}class SessionInfoManager extends SessionInfoManagerBase{async get(e){const[t,i,s,o,l,u,h,d]=await Promise.all([this.storageUtility.getForUser(e,"isLoggedIn",{secure:!0}),this.storageUtility.getForUser(e,"webId",{secure:!0}),this.storageUtility.getForUser(e,"clientId",{secure:!1}),this.storageUtility.getForUser(e,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e,"redirectUrl",{secure:!1}),this.storageUtility.getForUser(e,"refreshToken",{secure:!0}),this.storageUtility.getForUser(e,"issuer",{secure:!1}),this.storageUtility.getForUser(e,"tokenType",{secure:!1})]);if(typeof l=="string"&&!isValidRedirectUrl(l)){await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})]);return}if(d!==void 0&&!isSupportedTokenType(d))throw new Error(`Tokens of type [${d}] are not supported.`);if(!(s===void 0&&t===void 0&&i===void 0&&u===void 0))return{sessionId:e,webId:i,isLoggedIn:t==="true",redirectUrl:l,refreshToken:u,issuer:h,clientAppId:s,clientAppSecret:o,tokenType:d??"DPoP"}}async clear(e){return clear(e,this.storageUtility)}}class FallbackRedirectHandler{async canHandle(e){try{return new URL(e),!0}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e){return getUnauthenticatedSession()}}class AuthCodeRedirectHandler{storageUtility;sessionInfoManager;issuerConfigFetcher;clientRegistrar;tokerRefresher;fetch;constructor(e,t,i,s,o,l){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=o,this.fetch=l,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=o}async canHandle(e){try{const t=new URL(e);return t.searchParams.get("code")!==null&&t.searchParams.get("state")!==null}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(!await this.canHandle(e))throw new Error(`AuthCodeRedirectHandler cannot handle [${e}]: it is missing one of [code, state].`);const i=new URL(e),s=i.searchParams.get("state"),o=await this.storageUtility.getForUser(s,"sessionId",{errorIfNull:!0}),{issuerConfig:l,codeVerifier:u,redirectUrl:h,dpop:d}=await loadOidcContextFromStorage(o,this.storageUtility,this.issuerConfigFetcher),p=i.searchParams.get("iss");if(typeof p=="string"&&p!==l.issuer)throw new Error(`The value of the iss parameter (${p}) does not match the issuer identifier of the authorization server (${l.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(u===void 0)throw new Error(`The code verifier for session ${o} is missing from storage.`);if(h===void 0)throw new Error(`The redirect URL for session ${o} is missing from storage.`);const g=await this.clientRegistrar.getClient({sessionId:o},l),m=Date.now(),v=await getTokens(l,g,{grantType:"authorization_code",code:i.searchParams.get("code"),codeVerifier:u,redirectUrl:h},d);window.localStorage.removeItem(`oidc.${s}`);let S;v.refreshToken!==void 0&&(S={sessionId:o,refreshToken:v.refreshToken,tokenRefresher:this.tokerRefresher});const E=buildAuthenticatedFetch(v.accessToken,{dpopKey:v.dpopKey,refreshOptions:S,eventEmitter:t,expiresIn:v.expiresIn,fetch:this.fetch});await saveSessionInfoToStorage(this.storageUtility,o,v.webId,v.clientId,"true",void 0,!0);const x=await this.sessionInfoManager.get(o);if(!x)throw new Error(`Could not retrieve session: [${o}].`);return Object.assign(x,{fetch:E,getLogoutUrl:maybeBuildRpInitiatedLogout({idTokenHint:v.idToken,endSessionEndpoint:l.endSessionEndpoint}),expirationDate:typeof v.expiresIn=="number"?m+v.expiresIn*1e3:void 0})}}class AggregateRedirectHandler extends AggregateHandler{constructor(e){super(e)}}class BrowserStorage{get storage(){return window.localStorage}async get(e){return this.storage.getItem(e)||void 0}async set(e,t){this.storage.setItem(e,t)}async delete(e){this.storage.removeItem(e)}}class Redirector{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class ClientRegistrar{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[i,s,o,l,u]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"expiresAt",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]),h=o!==void 0?Number.parseInt(o,10):-1,d=s!==void 0&&h!==0&&Math.floor(Date.now()/1e3)>h;if(i&&isKnownClientType(u)&&!d)return s!==void 0?{clientId:i,clientSecret:s,clientName:l,clientType:"dynamic",expiresAt:h}:{clientId:i,clientName:l,clientType:u};try{const p=await registerClient(e,t),g={clientId:p.clientId,clientType:"dynamic"};return p.clientSecret!==void 0&&(g.clientSecret=p.clientSecret,g.expiresAt=String(p.expiresAt)),p.idTokenSignedResponseAlg&&(g.idTokenSignedResponseAlg=p.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,g,{secure:!1}),p}catch(p){throw new Error("Client registration failed.",{cause:p})}}}class ErrorOidcHandler{async canHandle(e){try{return new URL(e).searchParams.has("error")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(t!==void 0){const i=new URL(e),s=i.searchParams.get("error"),o=i.searchParams.get("error_description");t.emit(EVENTS.ERROR,s,o)}return getUnauthenticatedSession()}}class TokenRefresher{storageUtility;issuerConfigFetcher;clientRegistrar;constructor(e,t,i){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i}async refresh(e,t,i,s){const o=await loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),l=await this.clientRegistrar.getClient({sessionId:e},o.issuerConfig);if(t===void 0)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(o.dpop&&i===void 0)throw new Error(`For session [${e}], the key bound to the DPoP access token must be provided to refresh said access token.`);const u=await refresh(t,o.issuerConfig,l,i);return u.refreshToken!==void 0&&s?.emit(EVENTS.NEW_REFRESH_TOKEN,u.refreshToken),u}}function getClientAuthenticationWithDependencies(n){const e=new InMemoryStorage,t=n.secureStorage||e,i=n.insecureStorage||new BrowserStorage,s=new StorageUtilityBrowser(t,i),o=new IssuerConfigFetcher(s),l=new ClientRegistrar(s),u=new SessionInfoManager(s),h=new TokenRefresher(s,o,l),d=new Redirector,p=new OidcLoginHandler(s,new AuthorizationCodeWithPkceOidcHandler(s,d),o,l),g=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(s,u,o,l,h,n.fetch),new FallbackRedirectHandler]);return new ClientAuthentication(p,g,new IWaterfallLogoutHandler(u,d),u,o)}const KEY_CURRENT_SESSION=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`,KEY_CURRENT_URL=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;async function silentlyAuthenticate(n,e,t){const i=await e.validateCurrentSession(n);return i!==null?(window.localStorage.setItem(KEY_CURRENT_URL,window.location.href),await e.login({sessionId:n,prompt:"none",oidcIssuer:i.issuer,redirectUrl:i.redirectUrl,clientId:i.clientAppId,clientSecret:i.clientAppSecret,tokenType:i.tokenType??"DPoP"},t.events),!0):!1}function isLoggedIn(n){return!!n?.isLoggedIn}class Session{info;events;clientAuthentication;tokenRequestInProgress=!1;xpodErrorLogout=Promise.resolve();constructor(e={},t=void 0){this.events=new EventEmitter,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=getClientAuthenticationWithDependencies({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage,fetch:e.fetch}):this.clientAuthentication=getClientAuthenticationWithDependencies({fetch:e.fetch}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??v4(),isLoggedIn:!1},this.events.on(EVENTS.LOGIN,()=>window.localStorage.setItem(KEY_CURRENT_SESSION,this.info.sessionId)),this.events.on(EVENTS.SESSION_EXPIRED,()=>this.internalLogout(!1)),this.events.on(EVENTS.ERROR,()=>{this.xpodErrorLogout=this.xpodErrorLogout.then(()=>this.internalLogout(!1),()=>this.internalLogout(!1)),this.xpodErrorLogout.catch(()=>{})})}login=async e=>(await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:e.tokenType??"DPoP"},this.events),new Promise(()=>{}));fetch=(e,t)=>this.clientAuthentication.fetch(e,t);internalLogout=async(e,t)=>{window.localStorage.removeItem(KEY_CURRENT_SESSION),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(EVENTS.LOGOUT)};logout=async e=>this.internalLogout(!0,e);handleIncomingRedirect=async(e={})=>{if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const t=typeof e=="string"?{url:e}:e,i=t.url??window.location.href;this.tokenRequestInProgress=!0;const s=await this.clientAuthentication.handleIncomingRedirect(i,this.events);try{await this.xpodErrorLogout}catch(o){throw this.tokenRequestInProgress=!1,o}if(isLoggedIn(s)){this.setSessionInfo(s);const o=window.localStorage.getItem(KEY_CURRENT_URL);o===null?this.events.emit(EVENTS.LOGIN):(window.localStorage.removeItem(KEY_CURRENT_URL),this.events.emit(EVENTS.SESSION_RESTORED,o))}else if(t.restorePreviousSession===!0){const o=window.localStorage.getItem(KEY_CURRENT_SESSION);if(o!==null&&await silentlyAuthenticate(o,this.clientAuthentication,this))return new Promise(()=>{})}return this.tokenRequestInProgress=!1,s};setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.clientAppId=e.clientAppId,this.info.expirationDate=e.expirationDate,this.events.on(EVENTS.SESSION_EXTENDED,t=>{this.info.expirationDate=Date.now()+t*1e3})}}function snapshotFromSessionInfo(n){return n?.isLoggedIn&&n.webId?{status:"authenticated",webId:n.webId}:{status:"anonymous"}}function normalizeError(n){return n instanceof Error?n:new Error(String(n))}function snapshotFromSessionError(n,e){return{status:"error",webId:e.webId,error:normalizeError(n)}}function snapshotFromSessionExpired(n){return{status:"expired",...n.webId===void 0?{}:{webId:n.webId}}}function areSnapshotsEqual(n,e){return!n||n.status!==e.status||n.webId!==e.webId?!1:n.status==="error"&&e.status==="error"?n.error===e.error:!0}function createSolidSessionRuntime(n={}){const e=n.session??new Session,t=new Set;let i={status:"initializing"},s,o,l=!1,u=!1,h,d=!1,p=0,g=!1,m=0,v=0,S;const E=()=>{p+=1,g=!0},x=q=>{if(d||((q.status!=="authenticated"||i.status!=="authenticated"||i.webId!==q.webId)&&E(),q.status==="authenticated"&&(g=!1),i=q,areSnapshotsEqual(s,i)))return i;s=i;for(const O of t)O(i);return i},A=()=>{if(S){if(S.generation!==v||S.eventWebId&&S.eventWebId!==e.info.webId)return i;S.eventWebId=e.info.webId}return E(),s=void 0,x(snapshotFromSessionInfo(e.info))},C=()=>(v+=1,x({status:"anonymous"})),T=()=>(v+=1,x(snapshotFromSessionExpired(e.info))),F=(q,O)=>{v+=1;const G=snapshotFromSessionError(O??q??"Solid session error",e.info);u&&(h=G),x(G)};e.events.on(EVENTS.LOGIN,A),e.events.on(EVENTS.SESSION_RESTORED,A),e.events.on(EVENTS.LOGOUT,C),e.events.on(EVENTS.SESSION_EXPIRED,T);const P=e.events;return P.on(EVENTS.ERROR,F),{fetch:e.fetch,createAuthenticatedFetch(q){const O=p,G=()=>{if(d||m>0||g||O!==p||i.status!=="authenticated"||i.webId!==q||!e.info.isLoggedIn||e.info.webId!==q){const fe=new Error("Authenticated session is no longer current");throw fe.name="AbortError",fe}};return async(fe,M)=>{G();const ee=await(M===void 0?e.fetch(fe):e.fetch(fe,M));try{G()}catch(Se){throw ee.body?.cancel().catch(()=>{}),Se}return ee}},getSnapshot(){return i},initialize(q={}){if(o)return o;if(l||d)return Promise.resolve(i);const O={generation:++v,eventWebId:void 0};S=O;const G=M=>!d&&O.generation===v&&(!M?.isLoggedIn||!O.eventWebId||O.eventWebId===M.webId);u=!0,h=void 0,x({status:"initializing"});const fe=e.handleIncomingRedirect({restorePreviousSession:q.restorePreviousSession??!0}).then(M=>{if(!G(M??e.info))return i;const ee=snapshotFromSessionInfo(M??e.info);return ee.status==="anonymous"&&h?.status==="error"?h:(l=!0,x(ee))}).catch(M=>G()?x(snapshotFromSessionError(M,e.info)):i).finally(()=>{o===fe&&(S===O&&(S=void 0),o=void 0,u=!1,h=void 0)});return o=fe,o},handleIncomingRedirect(q){if(o)return o;if(d)return Promise.resolve(i);const O={generation:++v,eventWebId:void 0};S=O;const G=M=>!d&&O.generation===v&&(!M?.isLoggedIn||!O.eventWebId||O.eventWebId===M.webId);u=!0,h=void 0,x({status:"initializing"});const fe=e.handleIncomingRedirect(q).then(M=>{if(!G(M??e.info))return i;const ee=snapshotFromSessionInfo(M??e.info);return ee.status==="anonymous"&&h?.status==="error"?h:(l=!0,x(ee))}).catch(M=>G()?x(snapshotFromSessionError(M,e.info)):i).finally(()=>{o===fe&&(S===O&&(S=void 0),o=void 0,u=!1,h=void 0)});return o=fe,fe},async login(q){v+=1,E(),m+=1;try{if(o){const O=new Error("Previous login is still completing. Reload before reconnecting.");throw O.name="SolidSessionPendingError",O}if(d)throw new Error("Solid session runtime is disposed");await e.login(q)}catch(O){throw x(snapshotFromSessionError(O,e.info)),O}finally{m-=1}},async logout(q){v+=1,E(),m+=1;try{await e.logout(q),x({status:"anonymous"})}catch(O){throw x(snapshotFromSessionError(O,e.info)),O}finally{m-=1}},subscribe(q){return t.add(q),()=>{t.delete(q)}},dispose(){v+=1,E(),d=!0,t.clear(),e.events.off(EVENTS.LOGIN,A),e.events.off(EVENTS.SESSION_RESTORED,A),e.events.off(EVENTS.LOGOUT,C),e.events.off(EVENTS.SESSION_EXPIRED,T),P.off(EVENTS.ERROR,F)}}}const ENDPOINT_PROTOCOLS=new Set(["http:","https:"]),RESERVED_AUTHORIZATION_PARAMETERS=new Set(["state","redirect_uri","client_id","response_type","code_challenge","code_challenge_method"]);function normalizeEndpoint(n,e){if(!n||typeof n.url!="string"||n.url.trim()==="")throw new TypeError(`${e}.url must be a non-empty absolute URL`);if(typeof n.label!="string")throw new TypeError(`${e}.label must be a string`);let t;try{t=new URL(n.url.trim())}catch{throw new TypeError(`${e}.url must be a valid absolute URL`)}if(!ENDPOINT_PROTOCOLS.has(t.protocol))throw new TypeError(`${e}.url must use http or https`);if(t.username||t.password)throw new TypeError(`${e}.url must not contain credentials`);if(t.hash)throw new TypeError(`${e}.url must not contain a fragment`);return{url:t.href,label:n.label}}function validateWebId(n){if(typeof n!="string"||n===""||/[\s\u0000-\u001f\u007f-\u009f]/u.test(n))throw new TypeError("webId must be a non-empty identifier without whitespace or control characters");return n}function normalizeStorageBinding(n){if(!n||typeof n.storageUrl!="string"||n.storageUrl.trim()==="")throw new TypeError("selectedStorage.storageUrl must be a non-empty absolute URL");validateWebId(n.webId);let e;try{e=new URL(n.storageUrl.trim())}catch{throw new TypeError("selectedStorage.storageUrl must be a valid absolute URL")}if(!ENDPOINT_PROTOCOLS.has(e.protocol))throw new TypeError("selectedStorage.storageUrl must use http or https");if(e.username||e.password)throw new TypeError("selectedStorage.storageUrl must not contain credentials");if(e.hash)throw new TypeError("selectedStorage.storageUrl must not contain a fragment");return{storageUrl:e.href,webId:n.webId,...n.label===void 0?{}:{label:n.label}}}function ensureEnum(n,e,t){if(!e.includes(n))throw new TypeError(`${t} has an unsupported value`);return n}function normalizeWebIdLoginRoute(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("route.id must be a non-empty opaque identifier");if(typeof n.label!="string")throw new TypeError("route.label must be a string");return{id:n.id.trim(),label:n.label,...n.description===void 0?{}:{description:n.description},...n.badge===void 0?{}:{badge:{label:n.badge.label,tone:ensureEnum(n.badge.tone,["neutral","primary","success","warning","danger"],"route.badge.tone")}},identityProvider:normalizeEndpoint(n.identityProvider,"route.identityProvider"),...n.storageProvider===void 0?{}:{storageProvider:normalizeEndpoint(n.storageProvider,"route.storageProvider")},availability:ensureEnum(n.availability,["ready","starting","unavailable"],"route.availability"),...n.unavailableReason===void 0?{}:{unavailableReason:n.unavailableReason}}}function decodeForValidation$1(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}function matchesAllowedPrefix(n,e){return e.some(t=>{if(t==="/")return n.startsWith("/");const i=t.endsWith("/")?t.slice(0,-1):t;return n===i||n.startsWith(`${i}/`)})}function normalizeApplicationReturnTo(n,e){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const t=n.trim(),i=decodeForValidation$1(t),s=i.split(/[?#]/,1)[0];if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||i.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(i)||i.startsWith("//")||s.split("/").some(o=>o==="..")||!matchesAllowedPrefix(s,e))throw new TypeError("returnTo must be a safe path within the application allow-list");return t}function normalizeWebIdLoginTransaction(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("transaction.id must be a non-empty opaque identifier");const e=n.authorizationParameters===void 0?void 0:{...n.authorizationParameters};if(e){for(const i of Object.keys(e))if(RESERVED_AUTHORIZATION_PARAMETERS.has(i.toLowerCase()))throw new TypeError(`authorizationParameters cannot override ${i}`)}const t=n.prompt===void 0?void 0:ensureEnum(n.prompt,["login","consent","select_account"],"transaction.prompt");return{id:n.id,route:normalizeWebIdLoginRoute(n.route),...n.selectedStorage===void 0?{}:{selectedStorage:normalizeStorageBinding(n.selectedStorage)},authorizationSurface:ensureEnum(n.authorizationSurface,["redirect","popup","embedded","external"],"transaction.authorizationSurface"),...t===void 0?{}:{prompt:t},discovery:ensureEnum(n.discovery,["standard","strict"],"transaction.discovery"),...e===void 0?{}:{authorizationParameters:e},...n.returnTo===void 0?{}:{returnTo:normalizeApplicationReturnTo(n.returnTo,["/"])}}}const KEY_SEPARATOR="\0";function normalizePodUrl(n){if(typeof n!="string"||n.trim()==="")throw new TypeError("podUrl must be a non-empty absolute URL");let e;try{e=new URL(n.trim())}catch{throw new TypeError("podUrl must be a valid absolute URL")}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("podUrl must use http or https");if(e.username||e.password||e.hash)throw new TypeError("podUrl must not contain credentials or a fragment");return e.href}function compositeKey(n,e){return`${n}${KEY_SEPARATOR}${e}`}function nextGeneration(n,e){const t=(n.get(e)??0)+1;return n.set(e,t),t}function createAbortedOpenError(){const n=new Error("Pod open aborted because the runtime identity changed");return n.name="AbortError",n}function createPodRuntime(n){const{adapter:e}=n,t=new Map,i=new Map,s=new Map,o=new Map,l=new Map,u=new Map,h=(g,m)=>{const v=validateWebId(g);if(m!==void 0){const x=normalizePodUrl(m),A=compositeKey(g,x);nextGeneration(u,A),o.get(A)?.controller.abort(),o.delete(A),i.delete(A);const C=t.get(v);C&&compositeKey(C.webId,C.podUrl)===A&&t.delete(v);return}nextGeneration(l,v),s.get(v)?.controller.abort(),s.delete(v);const S=t.get(v);S&&i.delete(compositeKey(S.webId,S.podUrl)),t.delete(v);const E=`${v}${KEY_SEPARATOR}`;for(const x of[...i.keys()])x.startsWith(E)&&i.delete(x);for(const[x,A]of[...o.entries()])x.startsWith(E)&&(nextGeneration(u,x),A.controller.abort(),o.delete(x))},d=g=>{if(g===void 0){t.clear(),i.clear();for(const m of s.values())m.controller.abort();for(const m of o.values())m.controller.abort();s.clear(),o.clear();for(const m of l.keys())nextGeneration(l,m);for(const m of u.keys())nextGeneration(u,m);return}if(typeof g=="string"){h(g);return}h(g.webId,g.podUrl)};return{open(g){const m=validateWebId(g.webId),v=g.podUrl===void 0?void 0:normalizePodUrl(g.podUrl);if(v!==void 0){const q=compositeKey(g.webId,v),O=i.get(q);if(O)return Promise.resolve(O);const G=o.get(q);if(G)return G.promise;const fe=u.get(q)??0;u.set(q,fe);const M=new AbortController,ee=()=>!M.signal.aborted&&(u.get(q)??0)===fe,Se=()=>{if(!ee())throw createAbortedOpenError()},re=p({webId:g.webId,podUrl:v,fetch:g.fetch,signal:M.signal,isCurrent:ee,assertCurrent:Se});o.set(q,{generation:fe,promise:re,controller:M});const Ae=()=>{const ke=o.get(q);ke?.generation===fe&&ke.promise===re&&o.delete(q)};return re.then(Ae,Ae),re}const S=t.get(m);if(S)return Promise.resolve(S);const E=s.get(m);if(E)return E.promise;const x=l.get(m)??0;l.set(m,x);const A=new AbortController,C=()=>!A.signal.aborted&&(l.get(m)??0)===x,T=()=>{if(!C())throw createAbortedOpenError()},F=(async()=>{const q=await e.discoverPod({webId:g.webId,fetch:g.fetch,signal:A.signal,isCurrent:C});return T(),p({webId:g.webId,podUrl:normalizePodUrl(q),fetch:g.fetch,signal:A.signal,isCurrent:C,assertCurrent:T,generation:x,webIdKey:m,discovered:!0})})();s.set(m,{generation:x,promise:F,controller:A});const P=()=>{const q=s.get(m);q?.generation===x&&q.promise===F&&s.delete(m)};return F.then(P,P),F},clear:d,dispose(){d()}};async function p(g){const m=compositeKey(g.webId,g.podUrl),v=i.get(m);if(v)return g.discovered&&g.webIdKey&&g.isCurrent()&&t.set(g.webIdKey,v),v;const S=await e.openDatabase({webId:g.webId,podUrl:g.podUrl,fetch:g.fetch,signal:g.signal,isCurrent:g.isCurrent});g.assertCurrent(),await e.hydrateCollections({webId:g.webId,podUrl:g.podUrl,database:S,signal:g.signal,isCurrent:g.isCurrent}),g.assertCurrent();const E={webId:g.webId,podUrl:g.podUrl,database:S,collections:"ready"};return g.isCurrent()&&(i.set(m,E),g.discovered&&g.webIdKey&&t.set(g.webIdKey,E)),E}}const SolidRuntimeContext=reactExports.createContext(null);function SolidRuntimeProvider({value:n,children:e}){return reactExports.createElement(SolidRuntimeContext.Provider,{value:n},e)}const SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER="x-xpod-canonical-url",SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER="x-xpod-canonical-origin",SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER="x-xpod-canonical-host",SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER="x-xpod-local-route-url";async function discoverSolidLocalRoute(n){let e;try{e=await n.fetch.call(globalThis,n.statusUrl??"/provision/status",{credentials:"include",headers:{accept:"application/json"}})}catch{return}if(!e?.ok)return;const t=await e.json().catch(()=>{});if(typeof t?.publicUrl=="string")try{return normalizeRoute({canonicalBaseUrl:t.publicUrl,localBaseUrl:n.localBaseUrl})}catch{return}}function resolveSolidLocalRouteUrl(n,e){let t;try{t=n instanceof URL?new URL(n.href):new URL(n)}catch{return}const i=e.map(normalizeRoute).filter(s=>isInsideBase(t,s.canonicalBaseUrl)).sort((s,o)=>o.canonicalBaseUrl.length-s.canonicalBaseUrl.length)[0];return i?replaceBase(t,i):void 0}function createSolidLocalRouteFetch(n){return async(e,t)=>{const i=requestUrl(e);if(!i)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const s=n.routes(),o=resolveSolidLocalRouteUrl(i,s);if(!o)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const l=routedHeaders(e,t,i,o);let u;if(e instanceof Request){const d=new Request(new Request(o,e),{headers:l});u=t===void 0?await n.fetch.call(globalThis,d):await n.fetch.call(globalThis,d,{...t,headers:l})}else u=await n.fetch.call(globalThis,o,{...t,headers:l});const h=resolveSolidLocalRouteUrl(u.url,s.map(d=>({canonicalBaseUrl:d.localBaseUrl,localBaseUrl:d.canonicalBaseUrl})));return h?withResponseUrl(u,h.href):u}}function withResponseUrl(n,e){const t=n.clone.bind(n);return Object.defineProperties(n,{url:{value:e,configurable:!0},clone:{value:()=>withResponseUrl(t(),e),configurable:!0}}),n}function requestUrl(n){if(n instanceof Request)return new URL(n.url);try{return new URL(String(n))}catch{return}}function normalizeRoute(n){return{canonicalBaseUrl:normalizeBaseUrl(n.canonicalBaseUrl),localBaseUrl:normalizeBaseUrl(n.localBaseUrl)}}function normalizeBaseUrl(n){const e=new URL(n);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("Solid local routes must use http or https");return e.search="",e.hash="",e.href.endsWith("/")?e.href:`${e.href}/`}function isInsideBase(n,e){const t=new URL(e);return n.origin===t.origin&&n.pathname.startsWith(t.pathname)}function replaceBase(n,e){const t=new URL(e.canonicalBaseUrl),i=new URL(e.localBaseUrl),s=n.pathname.slice(t.pathname.length),o=new URL(s,i);return o.search=n.search,o.hash=n.hash,o}function routedHeaders(n,e,t,i){const s=n instanceof Request?n:void 0,o=new Headers(s?.headers??void 0);return new Headers(e?.headers??void 0).forEach((l,u)=>o.set(u,l)),o.set(SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER,t.toString()),o.set(SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER,t.origin),o.set(SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER,t.host),o.set(SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER,i.toString()),o}SCHEMA.image,UDFS.hasContact,WF.participant,UDFS.metadata,UDFS.favorite,UDFS.muted,UDFS.unreadCount,UDFS.lastActiveAt,UDFS.lastMessage,SCHEMA.text;SIOC.has_parent,SIOC.has_member,WF.message,UDFS.messageType,SIOC.content,SIOC.richContent,UDFS.messageStatus,SCHEMA.dateDeleted,UDFS.senderName,UDFS.senderAvatarUrl,UDFS.mentions,UDFS.replyTo,UDFS.routedBy,UDFS.routeTargetAgent,UDFS.coordinationId;SCHEMA.about,UDFS.contactType,AS.audience,UDFS.externalPlatform,UDFS.externalId,UDFS.alias,UDFS.favorite,UDFS.sortKey,UDFS.deletedAt,UDFS.lastSyncedAt;SIOC.has_parent,UDFS.favorite,UDFS.metadata,UDFS.workspace,SIOC.Thread;UDFS.actor,UDFS.conversation,UDFS.inThread,UDFS.sessionStatus,UDFS.sessionTool,UDFS.tokenUsage,UDFS.message,UDFS.policy,UDFS.policyVersion,UDFS.metadata,UDFS.archivedAt;UDFS.instruction,UDFS.prompt,UDFS.issue,UDFS.message,UDFS.workspace,UDFS.status,UDFS.priority,UDFS.assignedTo,UDFS.source,UDFS.metadata;UDFS.task,UDFS.status,UDFS.scheduleKind,UDFS.cron,UDFS.intervalSeconds,UDFS.timezone,UDFS.startsAt,UDFS.nextRunAt,UDFS.lastRunAt,UDFS.metadata;UDFS.status,UDFS.ruleKind,UDFS.task,UDFS.schedule,UDFS.source,UDFS.target,UDFS.condition,UDFS.actions,UDFS.metadata,UDFS.lastTriggeredAt,UDFS.lastRunStatus;UDFS.deliveryKind,UDFS.status,UDFS.task,UDFS.source,AS.target,UDFS.conversation,UDFS.inThread,UDFS.targetThread,UDFS.targetSession,AS.actor,AS.object,UDFS.objective,UDFS.payload,UDFS.projection,UDFS.projectedRole,UDFS.metadata,UDFS.error,UDFS.startedAt,UDFS.consumedAt,UDFS.completedAt;UDFS.task,UDFS.delivery,UDFS.trigger,UDFS.input,UDFS.inThread,UDFS.workspace,UDFS.status,UDFS.runner,UDFS.prompt,UDFS.externalRunId,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.heartbeatAt,UDFS.cancelRequestedAt,UDFS.error,UDFS.metadata,UDFS.startedAt,UDFS.completedAt;UDFS.evidenceKind,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.outcome,UDFS.metadata;UDFS.reportKind,UDFS.status,UDFS.outcome,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.evidence,SCHEMA.reviewedBy,UDFS.metricFacts,UDFS.metadata;UDFS.run,UDFS.stepType,UDFS.payload;UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.status,UDFS.sourceHash,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,UDFS.metadata;UDFS.captureCandidate,UDFS.targetResource,UDFS.captureDecision,UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.userCorrection,UDFS.approval,UDFS.inputRequest,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,SCHEMA.about,UDFS.metadata;UDFS.session,UDFS.toolCallId,UDFS.toolName,ODRL.target,ODRL.action,UDFS.risk,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.reason,UDFS.context,UDFS.approvalOptions,UDFS.policyVersion,UDFS.expiresAt,UDFS.resolvedAt;UDFS.session,UDFS.conversation,UDFS.inThread,UDFS.run,UDFS.task,UDFS.requester,UDFS.requestKind,UDFS.prompt,UDFS.context,UDFS.inputOptions,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.response,UDFS.answeredBy,UDFS.onBehalfOf,UDFS.reason,UDFS.metadata,UDFS.expiresAt,UDFS.resolvedAt;UDFS.action,UDFS.actor,UDFS.actorRole,UDFS.onBehalfOf,UDFS.session,UDFS.entry,UDFS.toolCallId,UDFS.toolName,UDFS.approval,UDFS.policy,UDFS.policyVersion;ODRL.target,ODRL.action,UDFS.pageKind,UDFS.status,UDFS.tags,UDFS.sourceKind,UDFS.sourceHash,UDFS.compiledAt,UDFS.compiledFrom,UDFS.effect,UDFS.riskCeiling,UDFS.policy,UDFS.context,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.revokedAt;UDFS.summary,UDFS.body,UDFS.source,UDFS.related;AS.actor,AS.object;UDFS.Note,SIOC.about,UDFS.noteKind,UDFS.sourceKey,UDFS.fingerprint,UDFS.readerEngine,UDFS.readerVersion,UDFS.generatedWithModel,UDFS.sourceHash,UDFS.readerOptionsHash,UDFS.representationHash,UDFS.representationMediaType,UDFS.coverageUnit,UDFS.coveredRange,UDFS.readUnits,UDFS.totalUnits,UDFS.status;const ContactClass={PERSON:UDFS.PersonContact,AGENT:UDFS.AgentContact,GROUP:UDFS.GroupContact},contactResource=podTable("contact",{id:id("id").default("{key}.ttl"),name:string$2("name").predicate(VCARD.fn).notNull(),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),about:uri("about").predicate(SCHEMA.about).notNull(),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([ContactClass.PERSON]),contactType:string$2("contactType").predicate(UDFS.contactType).notNull(),isPublic:boolean$2("isPublic").predicate(AS.audience).default(!1),externalPlatform:string$2("externalPlatform").predicate(UDFS.externalPlatform),externalId:string$2("externalId").predicate(UDFS.externalId),alias:string$2("alias").predicate(UDFS.alias),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),note:text("note").predicate(VCARD.note),sortKey:string$2("sortKey").predicate(UDFS.sortKey),gender:string$2("gender").predicate(VCARD.hasGender),province:string$2("province").predicate(VCARD.region),city:string$2("city").predicate(VCARD.locality),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt),lastSyncedAt:timestamp("lastSyncedAt").predicate(UDFS.lastSyncedAt)},{base:"/.data/contacts/",sparqlEndpoint:"/.data/contacts/-/sparql",type:VCARD.Individual,namespace:UDFS});definePodRepository({namespace:"contact",resource:contactResource,searchableFields:["name","alias","note"],defaultSort:{field:"name",direction:"asc"}});const ChatStatus={ACTIVE:"active"},chatResource=podTable("chats",{id:id("id").default("{key}/index.ttl#this"),title:string$2("title").predicate(DCTerms.title).notNull(),description:string$2("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(SCHEMA.image),author:uri("author").predicate(DCTerms.creator),status:string$2("status").predicate(UDFS.status).notNull().default(ChatStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),muted:boolean$2("muted").predicate(UDFS.muted).default(!1),unreadCount:integer$1("unreadCount").predicate(UDFS.unreadCount).default(0),contact:uri("contact").predicate(UDFS.hasContact).link(contactResource),participants:uri("participants").array().predicate(WF.participant),metadata:object$1("metadata").predicate(UDFS.metadata),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt),lastMessage:uri("lastMessage").predicate(UDFS.lastMessage),lastMessagePreview:text("lastMessagePreview").predicate(SCHEMA.text),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat/",sparqlEndpoint:"/.data/chat/-/sparql",type:MEETING.LongChat,namespace:UDFS});definePodRepository({namespace:"chat",resource:chatResource,searchableFields:["title","description"],defaultSort:{field:"lastActiveAt",direction:"desc"}});const ProviderAuthMode={apiKey:"apiKey"},credentialResource=podTable("credential",{id:id("id").default("credentials.ttl#{key}"),provider:uri("provider").predicate(UDFS.provider).link("aiProvider"),authMode:string$2("authMode").predicate(UDFS.authMode).default(ProviderAuthMode.apiKey),service:string$2("service").predicate(UDFS.service).notNull().default("ai"),status:string$2("status").predicate(UDFS.status).notNull().default("active"),apiKey:string$2("apiKey").predicate(UDFS.apiKey),storageMode:string$2("storageMode").predicate(UDFS.storageMode),secretPayload:string$2("secretPayload").predicate(UDFS.secretPayload),encryptedSecret:string$2("encryptedSecret").predicate(UDFS.encryptedSecret),wrappedDataKey:string$2("wrappedDataKey").predicate(UDFS.wrappedDataKey),encryptionAlgorithm:string$2("encryptionAlgorithm").predicate(UDFS.encryptionAlgorithm),keyVersion:string$2("keyVersion").predicate(UDFS.keyVersion),scopes:text("scopes").array().predicate(UDFS.scopes),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),accountLabel:string$2("accountLabel").predicate(UDFS.accountLabel),lastRefreshAt:timestamp("lastRefreshAt").predicate(UDFS.lastRefreshAt),reauthRequired:boolean$2("reauthRequired").predicate(UDFS.reauthRequired).default(!1),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),label:string$2("label").predicate(UDFS.label),isDefault:boolean$2("isDefault").predicate(UDFS.isDefault).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).defaultNow(),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),clientCredentialId:string$2("clientCredentialId").predicate(UDFS.clientCredentialId),appliedTo:string$2("appliedTo").predicate(UDFS.appliedTo),appliedOn:string$2("appliedOn").predicate(UDFS.appliedOn),appliedAt:timestamp("appliedAt").predicate(UDFS.appliedAt),failCount:integer$1("failCount").predicate(UDFS.failCount).default(0),rateLimitResetAt:timestamp("rateLimitResetAt").predicate(UDFS.rateLimitResetAt),oauthRefreshToken:string$2("oauthRefreshToken").predicate(UDFS.oauthRefreshToken),oauthAccessToken:string$2("oauthAccessToken").predicate(UDFS.oauthAccessToken),oauthExpiresAt:timestamp("oauthExpiresAt").predicate(UDFS.oauthExpiresAt),projectId:string$2("projectId").predicate(UDFS.projectId),organizationId:string$2("organizationId").predicate(UDFS.organizationId)},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:UDFS.Credential,namespace:UDFS});function resourceKey(n,e){return n&&n.length>0?n:`${e}_${Math.random().toString(36).slice(2,12)}`}function workflowOwnerDir(n){return taskDir(n)??runDir(n)??deliveryDir(n)??issueDir(n)??threadDir(n)??chatDir(n)??aboutDir(n)}function chatDir(n){const e=typeof n?.chat=="string"?n.chat:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^chat\/(.+)\/index\.ttl#this$/);return i?.[1]?`chat/${i[1]}`:null}function threadDir(n){const e=typeof n?.thread=="string"?n.thread:void 0;return e?normalizePodDataResourceId(e).match(/^((?:chat|task)\/.+)\/index\.ttl#[^#/]+$/)?.[1]??null:null}function taskDir(n){const e=typeof n?.task=="string"?n.task:void 0;if(!e)return null;const t=normalizePodDataResourceId(e);if(t==="task/index.ttl#this")return"task";const i=t.match(/^task\/index\.ttl#([^#/]+)$/);if(i?.[1])return`task/${i[1]}`;const s=t.match(/^task\/(.+)\.ttl(?:#[^#/]+)?$/);return s?.[1]?`task/${s[1]}`:null}function issueDir(n){const e=typeof n?.issue=="string"?n.issue:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^issues\/(.+)\.ttl(?:#[^#/]+)?$/);return i?.[1]?`issues/${i[1]}`:null}function deliveryDir(n){const e=typeof n?.delivery=="string"?n.delivery:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/deliveries\.ttl#[^#/]+$/)?.[1]??null:null}function runDir(n){const e=typeof n?.run=="string"?n.run:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/runs\.ttl#[^#/]+$/)?.[1]??null:null}function aboutDir(n){const e=typeof n?.about=="string"?n.about:void 0;return e?runDir({run:e})??deliveryDir({delivery:e})??taskDir({task:e})??issueDir({issue:e})??threadDir({thread:e})??chatDir({chat:e}):null}const ThreadStatus={ACTIVE:"active"},threadResource=podTable("thread",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/index.ttl#{key}",{key:resourceKey(n,"thread"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),title:string$2("title").predicate(DCTerms.title),status:string$2("status").predicate(UDFS.status).notNull().default(ThreadStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),workspace:uri("workspace").predicate(UDFS.workspace),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:SIOC.Thread,namespace:UDFS});definePodRepository({namespace:"thread",resource:threadResource,searchableFields:["title"],defaultSort:{field:"updatedAt",direction:"desc"}});const MessageRole={USER:"user"},MessageStatus={COMPLETED:"completed"},messageResource=podTable("chat_message",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/{yyyy}/{MM}/{dd}/messages.ttl#{key}",{key:resourceKey(n,"msg"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),chat:uri("chat").predicate(WF.message).inverse().link(chatResource),thread:uri("thread").predicate(SIOC.has_member).inverse().link(threadResource),maker:uri("maker").predicate(FOAF.maker),role:string$2("role").predicate(UDFS.messageType).notNull().default(MessageRole.USER),content:text("content").predicate(SIOC.content).notNull(),richContent:text("richContent").predicate(SIOC.richContent),status:string$2("status").predicate(UDFS.messageStatus).notNull().default(MessageStatus.COMPLETED),toolName:string$2("toolName").predicate(UDFS.toolName),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),metadata:object$1("metadata").predicate(UDFS.metadata),replacedBy:string$2("replacedBy").predicate(DCTerms.isReplacedBy),deletedAt:timestamp("deletedAt").predicate(SCHEMA.dateDeleted),senderName:string$2("senderName").predicate(UDFS.senderName),senderAvatarUrl:uri("senderAvatarUrl").predicate(UDFS.senderAvatarUrl),mentions:uri("mentions").array().predicate(UDFS.mentions),replyTo:uri("replyTo").predicate(UDFS.replyTo),routedBy:uri("routedBy").predicate(UDFS.routedBy),routeTargetAgent:uri("routeTargetAgent").predicate(UDFS.routeTargetAgent),coordinationId:string$2("coordinationId").predicate(UDFS.coordinationId),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:MEETING.Message,namespace:UDFS}),exactFilterColumns={parent:messageResource.parent,chat:messageResource.chat,thread:messageResource.thread,maker:messageResource.maker,role:messageResource.role,status:messageResource.status,toolName:messageResource.toolName,toolCallId:messageResource.toolCallId,coordinationId:messageResource.coordinationId};function exactFilter$1(n,e){return e===void 0?void 0:eq(exactFilterColumns[n],e)}function messageListFilter(n){if(!n)return;const e=[exactFilter$1("parent",n.parent),exactFilter$1("chat",n.chat),exactFilter$1("thread",n.thread),exactFilter$1("maker",n.maker),exactFilter$1("role",n.role),exactFilter$1("status",n.status),exactFilter$1("toolName",n.toolName),exactFilter$1("toolCallId",n.toolCallId),exactFilter$1("coordinationId",n.coordinationId)].filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}definePodRepository({namespace:"message",resource:messageResource,searchableFields:["content"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>messageListFilter(n)});function chatProjectMemoryResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const chatProjectContextResource=podTable("chatProjectContext",{id:id("id"),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),instructions:text("instructions").predicate(UDFS.systemMessage),memoryEnabled:boolean$2("memoryEnabled").predicate(UDFS.memoryEnabled).notNull().default(!0),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-projects/",sparqlEndpoint:"/.data/chat-projects/-/sparql",type:UDFS.ChatProjectContext,namespace:UDFS}),chatProjectMemoryResource=podTable("chatProjectMemory",{id:id("id").default(n=>n?chatProjectMemoryResourceId(n):""),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),text:text("text").predicate(SCHEMA.text).notNull(),sourceMessage:uri("sourceMessage").predicate(UDFS.sourceMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-project-memories/",sparqlEndpoint:"/.data/chat-project-memories/-/sparql",type:UDFS.ProjectMemory,namespace:UDFS});definePodRepository({namespace:"chat-project-context",resource:chatProjectContextResource,defaultSort:{field:"updatedAt",direction:"desc"},filter:({filters:n})=>n?.workspace?eq(chatProjectContextResource.workspace,n.workspace):void 0});definePodRepository({namespace:"chat-project-memory",resource:chatProjectMemoryResource,searchableFields:["text"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>n?.workspace?eq(chatProjectMemoryResource.workspace,n.workspace):void 0});function conversationShareResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const conversationShareResource=podTable("conversationShare",{id:id("id").default(n=>n?conversationShareResourceId(n):""),thread:uri("thread").predicate(UDFS.targetThread).notNull(),resourceUrl:uri("resourceUrl").predicate(SCHEMA.url).notNull(),includeToolDetails:boolean$2("includeToolDetails").predicate(UDFS.includeToolDetails).notNull().default(!1),excludedMessageIds:string$2("excludedMessageIds").array().predicate(UDFS.excludedMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/chat-shares/",sparqlEndpoint:"/.data/chat-shares/-/sparql",type:UDFS.ConversationShare,namespace:UDFS});definePodRepository({namespace:"conversation-share",resource:conversationShareResource,defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>n?.thread?eq(conversationShareResource.thread,n.thread):void 0});const TaskStatus={OPEN:"open"},taskResource=podTable("task",{id:id("id").default("index.ttl#{key}"),title:string$2("title").predicate(DCTerms.title),instruction:text("instruction").predicate(UDFS.instruction).notNull(),prompt:text("prompt").predicate(UDFS.prompt),issue:uri("issue").predicate(UDFS.issue).link("issue"),message:uri("message").predicate(UDFS.message),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(TaskStatus.OPEN),priority:string$2("priority").predicate(UDFS.priority),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),source:uri("source").predicate(DCTerms.source),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/task/",sparqlEndpoint:"/.data/task/-/sparql",type:UDFS.Task,namespace:UDFS}),ScheduleStatus={ACTIVE:"active"},ScheduleKind={ONCE:"once"},scheduleResource=podTable("schedule",{id:id("id"),task:uri("task").predicate(UDFS.task).notNull().link(taskResource),status:string$2("status").predicate(UDFS.status).notNull().default(ScheduleStatus.ACTIVE),scheduleKind:string$2("scheduleKind").predicate(UDFS.scheduleKind).notNull().default(ScheduleKind.ONCE),cron:string$2("cron").predicate(UDFS.cron),intervalSeconds:integer$1("intervalSeconds").predicate(UDFS.intervalSeconds),timezone:string$2("timezone").predicate(UDFS.timezone),startsAt:timestamp("startsAt").predicate(UDFS.startsAt),nextRunAt:timestamp("nextRunAt").predicate(UDFS.nextRunAt),lastRunAt:timestamp("lastRunAt").predicate(UDFS.lastRunAt),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Schedule,namespace:UDFS}),AutomationRuleStatus={ACTIVE:"active"},AutomationRuleKind={EVENT:"event"};podTable("automation_rule",{id:id("id"),title:string$2("title").predicate(DCTerms.title).notNull(),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default(AutomationRuleStatus.ACTIVE),ruleKind:string$2("ruleKind").predicate(UDFS.ruleKind).notNull().default(AutomationRuleKind.EVENT),task:uri("task").predicate(UDFS.task).link(taskResource),schedule:uri("schedule").predicate(UDFS.schedule).link(scheduleResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),condition:object$1("condition").predicate(UDFS.condition),actions:object$1("actions").predicate(UDFS.actions),metadata:object$1("metadata").predicate(UDFS.metadata),lastTriggeredAt:timestamp("lastTriggeredAt").predicate(UDFS.lastTriggeredAt),lastRunStatus:string$2("lastRunStatus").predicate(UDFS.lastRunStatus),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.AutomationRule,namespace:UDFS});const DeliveryStatus={PENDING:"pending"},DeliveryKind={TASK_DISPATCH:"task_dispatch"},deliveryResource=podTable("delivery",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/deliveries.ttl#{key}"),kind:string$2("kind").predicate(UDFS.deliveryKind).notNull().default(DeliveryKind.TASK_DISPATCH),status:string$2("status").predicate(UDFS.status).notNull().default(DeliveryStatus.PENDING),task:uri("task").predicate(UDFS.task).link(taskResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),targetThread:uri("targetThread").predicate(UDFS.targetThread).link(threadResource),targetSession:uri("targetSession").predicate(UDFS.targetSession),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object),objective:text("objective").predicate(UDFS.objective),payload:object$1("payload").predicate(UDFS.payload),projection:object$1("projection").predicate(UDFS.projection),projectedRole:string$2("projectedRole").predicate(UDFS.projectedRole),metadata:object$1("metadata").predicate(UDFS.metadata),error:text("error").predicate(UDFS.error),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),dispatchedAt:timestamp("dispatchedAt").predicate(UDFS.startedAt),consumedAt:timestamp("consumedAt").predicate(UDFS.consumedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Delivery,namespace:UDFS}),issueResource=podTable("issue",{id:id("id").default("{key}.ttl"),title:string$2("title").predicate(DCTerms.title).notNull(),document:uri("document").predicate(DCTerms.source),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("open"),priority:string$2("priority").predicate(UDFS.priority).default("medium"),labels:text("labels").array().predicate(UDFS.tags),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),parentIssue:uri("parentIssue").predicate(UDFS.parentIssue).link("issue"),tasks:uri("tasks").predicate(UDFS.task).array(),createdBy:uri("createdBy").predicate(DCTerms.creator),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),closedAt:timestamp("closedAt").predicate(UDFS.closedAt),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/.data/issues/",sparqlEndpoint:"/.data/issues/-/sparql",type:UDFS.Issue,namespace:UDFS}),RunStatus={QUEUED:"queued"},runResource=podTable("run",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/runs.ttl#{key}"),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),trigger:uri("trigger").predicate(UDFS.trigger),input:uri("input").predicate(UDFS.input),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(RunStatus.QUEUED),runner:string$2("runner").predicate(UDFS.runner).notNull(),prompt:string$2("prompt").predicate(UDFS.prompt),externalRunId:string$2("externalRunId").predicate(UDFS.externalRunId),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),heartbeatAt:timestamp("heartbeatAt").predicate(UDFS.heartbeatAt),cancelRequestedAt:timestamp("cancelRequestedAt").predicate(UDFS.cancelRequestedAt),error:string$2("error").predicate(UDFS.error),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Run,namespace:UDFS});podTable("run_step",{id:id("id").default("{run.doc}#{key}"),run:uri("run").predicate(UDFS.run).notNull().link(runResource),stepType:string$2("stepType").predicate(UDFS.stepType).notNull(),message:string$2("message").predicate(DCTerms.description),payload:object$1("payload").predicate(UDFS.payload),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.RunStep,namespace:UDFS});const evidenceResource=podTable("evidence",{id:id("id").default("evidence/{yyyy}/{MM}/{dd}.ttl#{key}"),evidenceKind:string$2("evidenceKind").predicate(UDFS.evidenceKind).notNull(),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),summary:text("summary").predicate(DCTerms.abstract),source:uri("source").predicate(DCTerms.source),actor:uri("actor").predicate(DCTerms.creator),outcome:string$2("outcome").predicate(UDFS.outcome),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Evidence,namespace:UDFS}),ReportStatus={DRAFT:"draft"};podTable("report",{id:id("id").default((n,e)=>{const t=resourceKey(n,"report"),i=workflowOwnerDir(e)??"reports";return renderDefaultIdTemplate(`${i}/{yyyy}/{MM}/{dd}/reports.ttl#{key}`,{key:t,row:e})}),reportKind:string$2("reportKind").predicate(UDFS.reportKind).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(ReportStatus.DRAFT),outcome:string$2("outcome").predicate(UDFS.outcome),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),evidence:uri("evidence").predicate(UDFS.evidence).array().link(evidenceResource),summary:text("summary").predicate(DCTerms.abstract).notNull(),reviewer:uri("reviewer").predicate(SCHEMA.reviewedBy),actor:uri("actor").predicate(DCTerms.creator),source:uri("source").predicate(DCTerms.source),metricFacts:object$1("metricFacts").predicate(UDFS.metricFacts),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),publishedAt:timestamp("publishedAt").predicate(DCTerms.issued),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Report,namespace:UDFS});podTable("idea",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),summary:string$2("summary").predicate(DCTerms.abstract).notNull(),document:uri("document").predicate(DCTerms.source),input:text("input").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("captured"),commitment:string$2("commitment").predicate(UDFS.commitment).notNull().default("thought"),affectedArea:string$2("affectedArea").predicate(UDFS.affectedArea),currentUnderstanding:text("currentUnderstanding").predicate(UDFS.currentUnderstanding),openQuestions:text("openQuestions").array().predicate(UDFS.openQuestions),related:uri("related").array().predicate(DCTerms.relation),conflicts:text("conflicts").array().predicate(UDFS.conflicts),nextStep:text("nextStep").predicate(UDFS.nextStep),promotedTo:uri("promotedTo").predicate(UDFS.promotedTo),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),sourceMessages:uri("sourceMessages").array().predicate(DCTerms.source),createdBy:uri("createdBy").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/ideas/",sparqlEndpoint:"/.data/ideas/-/sparql",type:UDFS.Idea,namespace:UDFS});definePodRepository({namespace:"issue",resource:issueResource,searchableFields:["title","description"],defaultSort:{field:"updatedAt",direction:"desc"}});var MessageBlockType;(function(n){n.UNKNOWN="unknown",n.MAIN_TEXT="main_text",n.THINKING="thinking",n.IMAGE="image",n.CODE="code",n.TOOL="tool",n.TOOL_APPROVAL="tool_approval",n.TASK_PROGRESS="task_progress",n.FILE="file",n.ERROR="error",n.CITATION="citation"})(MessageBlockType||(MessageBlockType={}));var MessageBlockStatus;(function(n){n.PENDING="pending",n.PROCESSING="processing",n.STREAMING="streaming",n.SUCCESS="success",n.ERROR="error",n.PAUSED="paused"})(MessageBlockStatus||(MessageBlockStatus={}));const fixtureToolCallBlock={type:"tool",toolCallId:"toolcall-1",toolName:"write_file",arguments:{path:"README.md",content:"hello"},status:"waiting_approval",duration:123},fixtureToolApprovalBlock={type:"tool_approval",toolCallId:"toolcall-1",toolName:"write_file",toolDescription:"Write a file in the workspace",arguments:{path:"README.md",content:"hello"},risk:"medium",status:"pending",decisionRole:"human"},fixtureTaskProgressBlock={type:"task_progress",task:"https://pod.example/.data/task/index.ttl#task-1",title:"CP0 contract baseline",steps:[{id:"s1",label:"Freeze contracts",status:"done",duration:10},{id:"s2",label:"Add namespaces",status:"running"}],currentStep:2,totalSteps:2};JSON.stringify({blocks:[fixtureToolCallBlock,fixtureToolApprovalBlock,fixtureTaskProgressBlock]});const favoriteResource=podTable("favorite",{id:id("id"),targetType:uri("targetType").predicate(RDF$1.type).notNull(),target:uri("target").predicate(UDFS.favoriteTarget).notNull(),title:string$2("title").predicate(DCTerms.title).notNull(),snapshotContent:text("snapshotContent").predicate(SCHEMA.text),snapshotAuthor:string$2("snapshotAuthor").predicate(SCHEMA.author),sourceModule:string$2("sourceModule").predicate(UDFS.sourceModule),searchText:text("searchText").predicate(UDFS.searchText),snapshotMeta:text("snapshotMeta").predicate(UDFS.snapshotMeta),favoredAt:timestamp("favoredAt").predicate(UDFS.favoredAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/favorites/",sparqlEndpoint:"/.data/favorites/-/sparql",type:SCHEMA.CreativeWork,namespace:UDFS});async function createFavorite(n,e,t){const{rdfType:i,sourceModule:s,extractor:o}=e,l=t["@id"]||t.id;if(!l){console.warn("[StarredSync] Cannot create favorite: missing target URI");return}const u=o.getTitle(t),h={id:crypto.randomUUID(),targetType:i,target:l,title:u,snapshotContent:o.getContent?.(t),snapshotAuthor:o.getAuthor?.(t),sourceModule:s,searchText:o.getSearchText?.(t)??u,snapshotMeta:o.getSnapshotMeta?.(t),favoredAt:new Date,updatedAt:new Date};try{getDbInstance()||console.warn("[StarredSync] No db instance registered")}catch(d){console.error("[StarredSync] Failed to create favorite:",d)}}async function deleteFavorite(n,e){if(e)try{const t=getDbInstance()}catch(t){console.error("[StarredSync] Failed to delete favorite:",t)}}function createStarredSyncHook(n){return{afterUpdate:async(e,t,i)=>{if(!("starred"in i))return;const s=t.starred,o=t["@id"]||t.id;s?await createFavorite(e,n,t):await deleteFavorite(e,o)}}}let dbInstance=null;function getDbInstance(){return dbInstance}const chatSnapshotExtractor={getTitle:n=>n.title||"未命名对话",getContent:n=>n.lastMessagePreview},threadSnapshotExtractor={getTitle:n=>n.title||"未命名话题"};createStarredSyncHook({rdfType:MEETING.LongChat,sourceModule:"chat",extractor:chatSnapshotExtractor});createStarredSyncHook({rdfType:SIOC.Thread,sourceModule:"thread",extractor:threadSnapshotExtractor});const approvalResource=podTable("approval",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId).notNull(),toolName:string$2("toolName").predicate(UDFS.toolName).notNull(),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),risk:string$2("risk").predicate(UDFS.risk).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default("pending"),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),context:text("context").predicate(UDFS.context),approvalOptions:text("approvalOptions").predicate(UDFS.approvalOptions),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/approvals/",sparqlEndpoint:"/.data/approvals/-/sparql",type:UDFS.ApprovalRequest,namespace:UDFS}),InputRequestStatus={PENDING:"pending"},inputRequestResource=podTable("input_request",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),run:uri("run").predicate(UDFS.run).link(runResource),task:uri("task").predicate(UDFS.task).link(taskResource),requester:uri("requester").predicate(UDFS.requester),requestKind:string$2("requestKind").predicate(UDFS.requestKind).notNull().default("user-input"),prompt:text("prompt").predicate(UDFS.prompt).notNull(),context:text("context").predicate(UDFS.context),inputOptions:text("inputOptions").predicate(UDFS.inputOptions),status:string$2("status").predicate(UDFS.status).notNull().default(InputRequestStatus.PENDING),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),response:text("response").predicate(UDFS.response),answeredBy:uri("answeredBy").predicate(UDFS.answeredBy),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/input-requests/",sparqlEndpoint:"/.data/input-requests/-/sparql",type:UDFS.InputRequest,namespace:UDFS}),CaptureCandidateStatus={CANDIDATE:"candidate"},captureCandidateResource=podTable("capture_candidate",{id:id("id").default("candidates/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),summary:text("summary").predicate(DCTerms.abstract).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence).notNull().default("medium"),reason:text("reason").predicate(UDFS.reason),status:string$2("status").predicate(UDFS.status).notNull().default(CaptureCandidateStatus.CANDIDATE),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureCandidate,namespace:UDFS}),captureEventResource=podTable("capture_event",{id:id("id").default("events/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),captureCandidate:uri("captureCandidate").predicate(UDFS.captureCandidate).link(captureCandidateResource),targetResource:uri("targetResource").predicate(UDFS.targetResource),decision:string$2("decision").predicate(UDFS.captureDecision).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence),reason:text("reason").predicate(UDFS.reason),userCorrection:text("userCorrection").predicate(UDFS.userCorrection),approval:uri("approval").predicate(UDFS.approval).link(approvalResource),inputRequest:uri("inputRequest").predicate(UDFS.inputRequest).link(inputRequestResource),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),about:uri("about").predicate(SCHEMA.about),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureEvent,namespace:UDFS}),candidateExactFilterColumns={source:captureCandidateResource.source,suggestedType:captureCandidateResource.suggestedType,suggestedTarget:captureCandidateResource.suggestedTarget,status:captureCandidateResource.status,chat:captureCandidateResource.chat,thread:captureCandidateResource.thread,task:captureCandidateResource.task,run:captureCandidateResource.run},eventExactFilterColumns={source:captureEventResource.source,captureCandidate:captureEventResource.captureCandidate,targetResource:captureEventResource.targetResource,decision:captureEventResource.decision,approval:captureEventResource.approval,inputRequest:captureEventResource.inputRequest,chat:captureEventResource.chat,thread:captureEventResource.thread,task:captureEventResource.task,run:captureEventResource.run};function exactFilter(n,e,t){return t===void 0?void 0:eq(n[e],t)}function combineFilters(n){const e=n.filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}function captureCandidateListFilter(n){if(n)return combineFilters([exactFilter(candidateExactFilterColumns,"source",n.source),exactFilter(candidateExactFilterColumns,"suggestedType",n.suggestedType),exactFilter(candidateExactFilterColumns,"suggestedTarget",n.suggestedTarget),exactFilter(candidateExactFilterColumns,"status",n.status),exactFilter(candidateExactFilterColumns,"chat",n.chat),exactFilter(candidateExactFilterColumns,"thread",n.thread),exactFilter(candidateExactFilterColumns,"task",n.task),exactFilter(candidateExactFilterColumns,"run",n.run)])}function captureEventListFilter(n){if(n)return combineFilters([exactFilter(eventExactFilterColumns,"source",n.source),exactFilter(eventExactFilterColumns,"captureCandidate",n.captureCandidate),exactFilter(eventExactFilterColumns,"targetResource",n.targetResource),exactFilter(eventExactFilterColumns,"decision",n.decision),exactFilter(eventExactFilterColumns,"approval",n.approval),exactFilter(eventExactFilterColumns,"inputRequest",n.inputRequest),exactFilter(eventExactFilterColumns,"chat",n.chat),exactFilter(eventExactFilterColumns,"thread",n.thread),exactFilter(eventExactFilterColumns,"task",n.task),exactFilter(eventExactFilterColumns,"run",n.run)])}definePodRepository({namespace:"capture-candidate",resource:captureCandidateResource,searchableFields:["summary","reason"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureCandidateListFilter(n)});definePodRepository({namespace:"capture-event",resource:captureEventResource,searchableFields:["reason","userCorrection"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureEventListFilter(n)});podTable("settings",{id:id("id").default((n,e)=>{const t=typeof e?.key=="string"?e.key:n;return t?`${encodeURIComponent(t)}.ttl`:""}),key:string$2("key").predicate(UDFS.settingKey).notNull(),value:text("value").predicate(UDFS.settingValue).notNull(),valueType:string$2("valueType").predicate(UDFS.settingType).notNull().default("string"),category:string$2("category").predicate(DCTerms.type).notNull(),label:string$2("label").predicate(DCTerms.title),description:text("description").predicate(DCTerms.description),owner:string$2("owner").predicate(DCTerms.creator).notNull(),isSensitive:boolean$2("isSensitive").predicate(UDFS.status).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),modifiedAt:timestamp("modifiedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:SCHEMA.PropertyValue,namespace:UDFS});const agentResource=podTable("agent",{id:id("id").default("{key}/"),name:string$2("name").predicate(FOAF.name).notNull(),description:text("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),root:uri("root").predicate(UDFS.root),identity:uri("identity").predicate(UDFS.webId),hasSkill:uri("hasSkill").array().predicate(UDFS.hasSkill),instructions:text("instructions").predicate(UDFS.systemMessage),provider:string$2("provider").predicate(UDFS.provider),model:string$2("model").predicate(UDFS.model),backend:string$2("backend").predicate(UDFS.backend),runtime:string$2("runtime").predicate(UDFS.runtime),transport:string$2("transport").predicate(UDFS.transport),endpoint:uri("endpoint").predicate(UDFS.endpoint),credentialSource:string$2("credentialSource").predicate(UDFS.credentialSource),temperature:real("temperature").predicate(UDFS.temperature).default(.7),tools:text("tools").array().predicate(UDFS.tools),contextRound:integer$1("contextRound").predicate(UDFS.contextRound).default(4),authorityPolicy:object$1("authorityPolicy").predicate(UDFS.authorityPolicy),toolPolicy:object$1("toolPolicy").predicate(UDFS.toolPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),ttsModel:string$2("ttsModel").predicate(UDFS.ttsModel),videoModel:string$2("videoModel").predicate(UDFS.videoModel),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:FOAF.Agent,namespace:UDFS});definePodRepository({namespace:"agent",resource:agentResource,searchableFields:["name","description","instructions"]});podTable("skill",{id:id("id").default("{agent.key}/skills/{key}/"),agent:uri("agent").predicate(UDFS.agent).notNull().link(agentResource),root:uri("root").predicate(UDFS.root),name:string$2("name").predicate(UDFS.name).notNull(),displayName:string$2("displayName").predicate(UDFS.displayName),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),version:string$2("version").predicate(UDFS.version),source:string$2("source").predicate(UDFS.source),checksum:string$2("checksum").predicate(UDFS.checksum),loadPolicy:string$2("loadPolicy").predicate(UDFS.loadPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:UDFS.Skill,namespace:UDFS});const sessionResource=podTable("session",{id:id("id").default("{yyyy}/{MM}/{dd}/{key}.ttl"),owner:uri("owner").predicate(UDFS.actor).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),status:string$2("status").predicate(UDFS.sessionStatus).notNull().default("active"),tool:string$2("tool").predicate(UDFS.sessionTool),tokenUsage:integer$1("tokenUsage").predicate(UDFS.tokenUsage).default(0),messages:uri("messages").predicate(UDFS.message).array(),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),archivedAt:timestamp("archivedAt").predicate(UDFS.archivedAt)},{base:"/.data/sessions/",sparqlEndpoint:"/.data/sessions/-/sparql",type:UDFS.term("Session"),namespace:UDFS});definePodRepository({namespace:"session",resource:sessionResource,searchableFields:["chat","thread","status","tool"],defaultSort:{field:"updatedAt",direction:"desc"}});podTable("audit",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),action:string$2("action").predicate(UDFS.action).notNull(),actor:uri("actor").predicate(UDFS.actor).notNull(),actorRole:string$2("actorRole").predicate(UDFS.actorRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),session:uri("session").predicate(UDFS.session),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),entry:uri("entry").predicate(UDFS.entry),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),toolName:string$2("toolName").predicate(UDFS.toolName),approval:uri("approval").predicate(UDFS.approval),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/audits/",sparqlEndpoint:"/.data/audits/-/sparql",type:UDFS.AuditEntry,namespace:UDFS});podTable("grant",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AutonomyGrant]),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),title:string$2("title").predicate(DCTerms.title),summary:text("summary").predicate(DCTerms.abstract),description:text("description").predicate(DCTerms.description),schema:uri("schema").predicate(DCTerms.conformsTo),pageKind:string$2("pageKind").predicate(UDFS.pageKind),wikiStatus:string$2("wikiStatus").predicate(UDFS.status),tags:text("tags").predicate(UDFS.tags),source:string$2("source").predicate(UDFS.sourceKind),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),compiledAt:timestamp("compiledAt").predicate(UDFS.compiledAt),compiledFrom:uri("compiledFrom").array().predicate(UDFS.compiledFrom),related:uri("related").array().predicate(DCTerms.relation),effect:string$2("effect").predicate(UDFS.effect).notNull(),riskCeiling:string$2("riskCeiling").predicate(UDFS.riskCeiling),policy:text("policy").predicate(UDFS.policy),context:text("context").predicate(UDFS.context),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy).notNull(),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/settings/autonomy/grants/",sparqlEndpoint:"/settings/autonomy/grants/-/sparql",type:ODRL.Policy,namespace:ODRL});podTable("inbox_notification",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([AS.Announce]),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object).notNull(),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/inbox/",sparqlEndpoint:"/inbox/-/sparql",type:AS.Activity,namespace:AS});var util;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const o={};for(const l of s)o[l]=l;return o},n.getValidEnumValues=s=>{const o=n.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),l={};for(const u of o)l[u]=s[u];return n.objectValues(l)},n.objectValues=s=>n.objectKeys(s).map(function(o){return s[o]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&o.push(l);return o},n.find=(s,o)=>{for(const l of s)if(o(l))return l},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function i(s,o=" | "){return s.map(l=>typeof l=="string"?`'${l}'`:l).join(o)}n.joinValues=i,n.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(util||(util={}));var objectUtil;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=n=>{switch(typeof n){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(n)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(n)?ZodParsedType.array:n===null?ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?ZodParsedType.map:typeof Set<"u"&&n instanceof Set?ZodParsedType.set:typeof Date<"u"&&n instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(o){return o.message},i={_errors:[]},s=o=>{for(const l of o.issues)if(l.code==="invalid_union")l.unionErrors.map(s);else if(l.code==="invalid_return_type")s(l.returnTypeError);else if(l.code==="invalid_arguments")s(l.argumentsError);else if(l.path.length===0)i._errors.push(t(l));else{let u=i,h=0;for(;h<l.path.length;){const d=l.path[h];h===l.path.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(l))):u[d]=u[d]||{_errors:[]},u=u[d],h++}}};return s(this),i}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)if(s.path.length>0){const o=s.path[0];t[o]=t[o]||[],t[o].push(e(s))}else i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=n=>new ZodError(n);const errorMap=(n,e)=>{let t;switch(n.code){case ZodIssueCode.invalid_type:n.received===ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${util.joinValues(n.keys,", ")}`;break;case ZodIssueCode.invalid_union:t="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${util.joinValues(n.options)}`;break;case ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${util.joinValues(n.options)}, received '${n.received}'`;break;case ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ZodIssueCode.invalid_date:t="Invalid date";break;case ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case ZodIssueCode.custom:t="Invalid input";break;case ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,util.assertNever(n)}return{message:t}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=n=>{const{data:e,path:t,errorMaps:i,issueData:s}=n,o=[...t,...s.path||[]],l={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let u="";const h=i.filter(d=>!!d).slice().reverse();for(const d of h)u=d(l,{data:e,defaultError:u}).message;return{...s,path:o,message:u}};function addIssueToContext(n,e){const t=getErrorMap(),i=makeIssue({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===errorMap?void 0:errorMap].filter(s=>!!s)});n.common.issues.push(i)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const s of t){if(s.status==="aborted")return INVALID;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const o=await s.key,l=await s.value;i.push({key:o,value:l})}return ParseStatus.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:o,value:l}=s;if(o.status==="aborted"||l.status==="aborted")return INVALID;o.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof l.value<"u"||s.alwaysSet)&&(i[o.value]=l.value)}return{status:e.value,value:i}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=n=>({status:"dirty",value:n}),OK=n=>({status:"valid",value:n}),isAborted=n=>n.status==="aborted",isDirty=n=>n.status==="dirty",isValid=n=>n.status==="valid",isAsync=n=>typeof Promise<"u"&&n instanceof Promise;var errorUtil;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(n,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(n.common.issues);return this._error=t,this._error}}};function processCreateParams(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(l,u)=>{const{message:h}=n;return l.code==="invalid_enum_value"?{message:h??u.defaultError}:typeof u.data>"u"?{message:h??i??u.defaultError}:l.code!=="invalid_type"?{message:u.defaultError}:{message:h??t??u.defaultError}},description:s}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parseSync({data:e,path:i.path,parent:i});return handleResult(i,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return isValid(i)?{value:i.value}:{issues:t.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>isValid(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parse({data:e,path:i.path,parent:i}),o=await(isAsync(s)?s:Promise.resolve(s));return handleResult(i,o)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,o)=>{const l=e(s),u=()=>o.addIssue({code:ZodIssueCode.custom,...i(s)});return typeof Promise<"u"&&l instanceof Promise?l.then(h=>h?!0:(u(),!1)):l?!0:(u(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function timeRegex(n){return new RegExp(`^${timeRegexSource(n)}$`)}function datetimeRegex(n){let e=`${dateRegexSource}T${timeRegexSource(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(n,e){return!!((e==="v4"||!e)&&ipv4Regex.test(n)||(e==="v6"||!e)&&ipv6Regex.test(n))}function isValidJWT(n,e){if(!jwtRegex.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function isValidCidr(n,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(n)||(e==="v6"||!e)&&ipv6CidrRegex.test(n))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:o.parsedType}),INVALID}const i=new ParseStatus;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),i.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),i.dirty());else if(o.kind==="length"){const l=e.data.length>o.value,u=e.data.length<o.value;(l||u)&&(s=this._getOrReturnCtx(e,s),l?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):u&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),i.dirty())}else if(o.kind==="email")emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="uuid")uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="nanoid")nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="cuid")cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="cuid2")cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="ulid")ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),i.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),i.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),i.dirty()):o.kind==="datetime"?datetimeRegex(o).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),i.dirty()):o.kind==="date"?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),i.dirty()):o.kind==="time"?timeRegex(o).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),i.dirty()):o.kind==="duration"?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="ip"?isValidIP(e.data,o.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="jwt"?isValidJWT(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="cidr"?isValidCidr(e.data,o.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="base64"?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="base64url"?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(i)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodString.create=n=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:n?.coerce??!1,...processCreateParams(n)});function floatSafeRemainder(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,o=Number.parseInt(n.toFixed(s).replace(".","")),l=Number.parseInt(e.toFixed(s).replace(".",""));return o%l/10**s}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:o.parsedType}),INVALID}let i;const s=new ParseStatus;for(const o of this._def.checks)o.kind==="int"?util.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?floatSafeRemainder(e.data,o.value)!==0&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_finite,message:o.message}),s.dirty()):util.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=n=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let i;const s=new ParseStatus;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):util.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=n=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:n?.coerce??!1,...processCreateParams(n)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:i.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=n=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:o.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_date}),INVALID}const i=new ParseStatus;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),i.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),i.dirty()):util.assertNever(o);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ZodDate.create=n=>new ZodDate({checks:[],coerce:n?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(n)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:i.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=n=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(n)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:i.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=n=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(n)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:i.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=n=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(n)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=n=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(n)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=n=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(n)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=n=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(n)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:i.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=n=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(n)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(s.exactLength!==null){const l=t.data.length>s.exactLength.value,u=t.data.length<s.exactLength.value;(l||u)&&(addIssueToContext(t,{code:l?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:u?s.exactLength.value:void 0,maximum:l?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,u)=>s.type._parseAsync(new ParseInputLazyPath(t,l,t.path,u)))).then(l=>ParseStatus.mergeArray(i,l));const o=[...t.data].map((l,u)=>s.type._parseSync(new ParseInputLazyPath(t,l,t.path,u)));return ParseStatus.mergeArray(i,o)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(n,e)=>new ZodArray({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(n){if(n instanceof ZodObject){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=ZodOptional.create(deepPartialify(i))}return new ZodObject({...n._def,shape:()=>e})}else return n instanceof ZodArray?new ZodArray({...n._def,type:deepPartialify(n.element)}):n instanceof ZodOptional?ZodOptional.create(deepPartialify(n.unwrap())):n instanceof ZodNullable?ZodNullable.create(deepPartialify(n.unwrap())):n instanceof ZodTuple?ZodTuple.create(n.items.map(e=>deepPartialify(e))):n}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const d=this._getOrReturnCtx(e);return addIssueToContext(d,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:d.parsedType}),INVALID}const{status:i,ctx:s}=this._processInputParams(e),{shape:o,keys:l}=this._getCached(),u=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const d in s.data)l.includes(d)||u.push(d);const h=[];for(const d of l){const p=o[d],g=s.data[d];h.push({key:{status:"valid",value:d},value:p._parse(new ParseInputLazyPath(s,g,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof ZodNever){const d=this._def.unknownKeys;if(d==="passthrough")for(const p of u)h.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")u.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:u}),i.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const p of u){const g=s.data[p];h.push({key:{status:"valid",value:p},value:d._parse(new ParseInputLazyPath(s,g,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const p of h){const g=await p.key,m=await p.value;d.push({key:g,value:m,alwaysSet:p.alwaysSet})}return d}).then(d=>ParseStatus.mergeObjectSync(i,d)):ParseStatus.mergeObjectSync(i,h)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{const s=this._def.errorMap?.(t,i).message??i.defaultError;return t.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};for(const i of util.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const i of util.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const i of util.objectKeys(this.shape)){const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const i of util.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let o=this.shape[i];for(;o instanceof ZodOptional;)o=o._def.innerType;t[i]=o}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.strictCreate=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.lazycreate=(n,e)=>new ZodObject({shape:n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(o){for(const u of o)if(u.result.status==="valid")return u.result;for(const u of o)if(u.result.status==="dirty")return t.common.issues.push(...u.ctx.common.issues),u.result;const l=o.map(u=>new ZodError(u.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:l}),INVALID}if(t.common.async)return Promise.all(i.map(async o=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(s);{let o;const l=[];for(const h of i){const d={...t,common:{...t.common,issues:[]},parent:null},p=h._parseSync({data:t.data,path:t.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!o&&(o={result:p,ctx:d}),d.common.issues.length&&l.push(d.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const u=l.map(h=>new ZodError(h));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:u}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(n,e)=>new ZodUnion({options:n,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(n,e){const t=getParsedType(n),i=getParsedType(e);if(n===e)return{valid:!0,data:n};if(t===ZodParsedType.object&&i===ZodParsedType.object){const s=util.objectKeys(e),o=util.objectKeys(n).filter(u=>s.indexOf(u)!==-1),l={...n,...e};for(const u of o){const h=mergeValues(n[u],e[u]);if(!h.valid)return{valid:!1};l[u]=h.data}return{valid:!0,data:l}}else if(t===ZodParsedType.array&&i===ZodParsedType.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<n.length;o++){const l=n[o],u=e[o],h=mergeValues(l,u);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return t===ZodParsedType.date&&i===ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(o,l)=>{if(isAborted(o)||isAborted(l))return INVALID;const u=mergeValues(o.value,l.value);return u.valid?((isDirty(o)||isDirty(l))&&t.dirty(),{status:t.value,value:u.data}):(addIssueToContext(i,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([o,l])=>s(o,l)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ZodIntersection.create=(n,e,t)=>new ZodIntersection({left:n,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(t)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.array)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:i.parsedType}),INVALID;if(i.data.length<this._def.items.length)return addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&i.data.length>this._def.items.length&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...i.data].map((l,u)=>{const h=this._def.items[u]||this._def.rest;return h?h._parse(new ParseInputLazyPath(i,l,i.path,u)):null}).filter(l=>!!l);return i.common.async?Promise.all(o).then(l=>ParseStatus.mergeArray(t,l)):ParseStatus.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:n,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.object)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:i.parsedType}),INVALID;const s=[],o=this._def.keyType,l=this._def.valueType;for(const u in i.data)s.push({key:o._parse(new ParseInputLazyPath(i,u,i.path,u)),value:l._parse(new ParseInputLazyPath(i,i.data[u],i.path,u)),alwaysSet:u in i.data});return i.common.async?ParseStatus.mergeObjectAsync(t,s):ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(i)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.map)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:i.parsedType}),INVALID;const s=this._def.keyType,o=this._def.valueType,l=[...i.data.entries()].map(([u,h],d)=>({key:s._parse(new ParseInputLazyPath(i,u,i.path,[d,"key"])),value:o._parse(new ParseInputLazyPath(i,h,i.path,[d,"value"]))}));if(i.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const h of l){const d=await h.key,p=await h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}})}else{const u=new Map;for(const h of l){const d=h.key,p=h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}}}}ZodMap.create=(n,e,t)=>new ZodMap({valueType:e,keyType:n,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(t)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.set)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:i.parsedType}),INVALID;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const o=this._def.valueType;function l(h){const d=new Set;for(const p of h){if(p.status==="aborted")return INVALID;p.status==="dirty"&&t.dirty(),d.add(p.value)}return{status:t.value,value:d}}const u=[...i.data.values()].map((h,d)=>o._parse(new ParseInputLazyPath(i,h,i.path,d)));return i.common.async?Promise.all(u).then(h=>l(h)):l(u)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(n,e)=>new ZodSet({valueType:n,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(n,e)=>new ZodLazy({getter:n,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(n,e)=>new ZodLiteral({value:n,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(n,e){return new ZodEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{expected:util.joinValues(i),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==ZodParsedType.string&&i.parsedType!==ZodParsedType.number){const s=util.objectValues(t);return addIssueToContext(i,{expected:util.joinValues(s),received:i.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=util.objectValues(t);return addIssueToContext(i,{received:i.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(n,e)=>new ZodNativeEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&t.common.async===!1)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const i=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ZodPromise.create=(n,e)=>new ZodPromise({type:n,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:l=>{addIssueToContext(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const l=s.transform(i.data,o);if(i.common.async)return Promise.resolve(l).then(async u=>{if(t.value==="aborted")return INVALID;const h=await this._def.schema._parseAsync({data:u,path:i.path,parent:i});return h.status==="aborted"?INVALID:h.status==="dirty"||t.value==="dirty"?DIRTY(h.value):h});{if(t.value==="aborted")return INVALID;const u=this._def.schema._parseSync({data:l,path:i.path,parent:i});return u.status==="aborted"?INVALID:u.status==="dirty"||t.value==="dirty"?DIRTY(u.value):u}}if(s.type==="refinement"){const l=u=>{const h=s.refinement(u,o);if(i.common.async)return Promise.resolve(h);if(h instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(i.common.async===!1){const u=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value),{status:t.value,value:u.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(u=>u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value).then(()=>({status:t.value,value:u.value}))))}if(s.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!isValid(l))return INVALID;const u=s.transform(l.value,o);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:u}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>isValid(l)?Promise.resolve(s.transform(l.value,o)).then(u=>({status:t.value,value:u})):INVALID);util.assertNever(s)}}ZodEffects.create=(n,e,t)=>new ZodEffects({schema:n,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(t)});ZodEffects.createWithPreprocess=(n,e,t)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:n},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(t)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(n,e)=>new ZodOptional({innerType:n,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(n,e)=>new ZodNullable({innerType:n,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===ZodParsedType.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(n,e)=>new ZodDefault({innerType:n,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return isAsync(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(n,e)=>new ZodCatch({innerType:n,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:i.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=n=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(n)});class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?INVALID:o.status==="dirty"?(t.dirty(),DIRTY(o.value)):this._def.out._parseAsync({data:o.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),i=s=>(isValid(s)&&(s.value=Object.freeze(s.value)),s);return isAsync(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}ZodReadonly.create=(n,e)=>new ZodReadonly({innerType:n,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create;ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const RiskLevelSchema=enumType(["low","medium","high"]),DecisionRoleSchema=enumType(["human","secretary","system"]),ToolCallStatusSchema=enumType(["calling","waiting_approval","approved","rejected","running","done","error"]),IsoDatetimeSchema=stringType().datetime(),ApprovalOptionSchema=objectType({optionId:stringType(),label:stringType(),kind:stringType().optional(),description:stringType().optional()}).strict(),ToolCallEventV1Schema=objectType({type:literalType("tool.call"),version:literalType(1).optional(),sessionId:stringType(),toolCallId:stringType(),toolName:stringType(),risk:RiskLevelSchema.optional(),status:ToolCallStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),expiresAt:IsoDatetimeSchema.optional(),target:stringType().optional(),action:stringType().optional(),arguments:recordType(unknownType()).optional(),result:unknownType().optional(),error:stringType().optional(),duration:numberType().int().nonnegative().optional(),inboxItemId:stringType().optional(),decisionBy:stringType().optional(),decisionRole:DecisionRoleSchema.optional(),onBehalfOf:stringType().optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolCallEventSchema=ToolCallEventV1Schema,SessionToolSchema=enumType(["claude-code","cursor","windsurf"]),SessionStatusSchema=enumType(["active","paused","completed","error"]),SessionStateEventV1Schema=objectType({type:literalType("session.state"),version:literalType(1).optional(),sessionId:stringType(),chat:stringType(),policy:stringType().optional(),policyVersion:stringType().optional(),status:SessionStatusSchema,previousStatus:stringType(),tool:SessionToolSchema,tokenUsage:numberType().int().nonnegative(),timestamp:IsoDatetimeSchema}).strict(),SessionStateEventSchema=SessionStateEventV1Schema,ToolControlCommandNameSchema=enumType(["approve","reject","pause","resume","stop","inject_message","approve_pattern"]),ToolControlCommandV1Schema=objectType({commandId:stringType().optional(),type:literalType("tool.control"),version:literalType(1).optional(),command:ToolControlCommandNameSchema,sessionId:stringType(),toolCallId:stringType().optional(),message:stringType().optional(),pattern:stringType().optional(),inboxItemId:stringType().optional(),actor:objectType({actorWebId:stringType(),actorRole:DecisionRoleSchema,onBehalfOf:stringType().optional()}).optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolControlCommandSchema=ToolControlCommandV1Schema,InboxApprovalStatusSchema=enumType(["pending","approved","rejected","expired"]),InboxApprovalEventV1Schema=objectType({type:literalType("inbox.approval"),version:literalType(1).optional(),inboxItemId:stringType(),sessionId:stringType(),toolCallId:stringType(),target:stringType().optional(),action:stringType().optional(),policy:stringType().optional(),policyVersion:stringType().optional(),risk:RiskLevelSchema,status:InboxApprovalStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),assignedTo:stringType().optional(),createdAt:IsoDatetimeSchema,expiresAt:IsoDatetimeSchema.optional(),resolvedAt:IsoDatetimeSchema.optional()}).strict(),InboxApprovalEventSchema=InboxApprovalEventV1Schema;unionType([ToolCallEventSchema,SessionStateEventSchema,ToolControlCommandSchema,InboxApprovalEventSchema]);const aiProviderResource=podTable("aiProvider",{id:id("id").default("{key}.ttl"),displayName:string$2("displayName").predicate(UDFS.displayName),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),homepage:string$2("homepage").predicate(UDFS.homepage),apiKeyUrl:string$2("apiKeyUrl").predicate(UDFS.apiKeyUrl),connectMode:string$2("connectMode").predicate(UDFS.connectMode),hasModel:uri("hasModel").predicate(UDFS.hasModel).array().link("aiModel"),defaultModel:uri("defaultModel").predicate(UDFS.defaultModel).link("aiModel"),supportsBackend:string$2("supportsBackend").predicate(UDFS.supportsBackend),capabilities:string$2("capabilities").array().predicate(UDFS.capability),rotationPolicy:string$2("rotationPolicy").predicate(UDFS.rotationPolicy)},{base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql",type:UDFS.Provider,namespace:UDFS}),MODEL_STORAGE={base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql"},aiModelSchema=solidSchema({id:id("id").default("{isProvidedBy.doc}#{key}"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AIModel]),displayName:string$2("displayName").predicate(UDFS.displayName),isProvidedBy:uri("isProvidedBy").predicate(UDFS.isProvidedBy).link(aiProviderResource),inputModalities:text("inputModalities").array().predicate(UDFS.inputModality),outputModalities:text("outputModalities").array().predicate(UDFS.outputModality),runtimeCapabilities:string$2("runtimeCapabilities").array().predicate(UDFS.capability),capabilities:uri("capabilities").array().predicate(UDFS.hasCapability),pricingInput:real("pricingInput").predicate(UDFS.pricingInput),pricingOutput:real("pricingOutput").predicate(UDFS.pricingOutput),status:string$2("status").predicate(UDFS.status).default("active"),createdAt:timestamp("createdAt").predicate(UDFS.createdAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt).notNull().defaultNow()},{type:UDFS.AIModel,subClassOf:UDFS.Model,namespace:UDFS}),chatModelSchema=aiModelSchema.extend({contextLength:integer$1("contextLength").predicate(UDFS.contextLength),maxOutputTokens:integer$1("maxOutputTokens").predicate(UDFS.maxOutputTokens)},{type:UDFS.ChatModel,namespace:UDFS}),embeddingModelSchema=aiModelSchema.extend({dimension:integer$1("dimension").predicate(UDFS.dimension)},{type:UDFS.EmbeddingModel,namespace:UDFS}),documentUnderstandingModelSchema=aiModelSchema.extend({},{type:UDFS.DocumentUnderstandingModel,namespace:UDFS}),rerankingModelSchema=aiModelSchema.extend({},{type:UDFS.RerankingModel,namespace:UDFS}),imageGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.ImageGenerationModel,namespace:UDFS}),speechRecognitionModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechRecognitionModel,namespace:UDFS}),speechSynthesisModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechSynthesisModel,namespace:UDFS}),videoGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.VideoGenerationModel,namespace:UDFS}),aiModelResource=aiModelSchema.table("aiModel",MODEL_STORAGE);chatModelSchema.table("chatModel",MODEL_STORAGE);embeddingModelSchema.table("embeddingModel",MODEL_STORAGE);documentUnderstandingModelSchema.table("documentUnderstandingModel",MODEL_STORAGE);rerankingModelSchema.table("rerankingModel",MODEL_STORAGE);imageGenerationModelSchema.table("imageGenerationModel",MODEL_STORAGE);speechRecognitionModelSchema.table("speechRecognitionModel",MODEL_STORAGE);speechSynthesisModelSchema.table("speechSynthesisModel",MODEL_STORAGE);videoGenerationModelSchema.table("videoGenerationModel",MODEL_STORAGE);const AI_MODEL_MODALITIES=["text","image","audio","video","pdf"],AI_MODEL_CAPABILITIES=["chat","embedding","reranking","tool_call","reasoning","web","vision","ocr","document_understanding","structured_output","indexing","image_generation","speech_recognition","speech_synthesis","video_generation"],AI_MODEL_CAPABILITY={chat:UDFS.ChatCapability,embedding:UDFS.EmbeddingCapability,reranking:UDFS.RerankingCapability,tool_call:UDFS.ToolCallCapability,reasoning:UDFS.ReasoningCapability,web:UDFS.WebCapability,vision:UDFS.VisionCapability,ocr:UDFS.OCRCapability,document_understanding:UDFS.DocumentUnderstandingCapability,structured_output:UDFS.StructuredOutputCapability,indexing:UDFS.IndexingCapability,image_generation:UDFS.ImageGenerationCapability,speech_recognition:UDFS.SpeechRecognitionCapability,speech_synthesis:UDFS.SpeechSynthesisCapability,video_generation:UDFS.VideoGenerationCapability},AI_MODEL_CLASS={chat:UDFS.ChatModel,embedding:UDFS.EmbeddingModel,document_understanding:UDFS.DocumentUnderstandingModel,reranking:UDFS.RerankingModel,image_generation:UDFS.ImageGenerationModel,speech_recognition:UDFS.SpeechRecognitionModel,speech_synthesis:UDFS.SpeechSynthesisModel,video_generation:UDFS.VideoGenerationModel};new Set(AI_MODEL_MODALITIES);new Set(AI_MODEL_CAPABILITIES);new Set(Object.values(AI_MODEL_CAPABILITY));new Map(Object.entries(AI_MODEL_CAPABILITY).map(([n,e])=>[e,n]));new Map(Object.entries(AI_MODEL_CLASS).map(([n,e])=>[e,n]));podTable("aiConfig",{id:id("id").default("config.ttl#{key}"),chatModel:uri("chatModel").predicate(UDFS.chatModel).link(aiModelResource),ocrModel:uri("ocrModel").predicate(UDFS.ocrModel).link(aiModelResource),readerModel:uri("readerModel").predicate(UDFS.readerModel).link(aiModelResource),embeddingModel:uri("embeddingModel").predicate(UDFS.embeddingModel).link(aiModelResource),indexerModel:uri("indexerModel").predicate(UDFS.indexerModel).link(aiModelResource),rerankerModel:uri("rerankerModel").predicate(UDFS.rerankerModel).link(aiModelResource),ocrEnabled:boolean$2("ocrEnabled").predicate(UDFS.ocrEnabled).default(!0),automaticOcr:boolean$2("automaticOcr").predicate(UDFS.automaticOcr).default(!0),imageRecognition:boolean$2("imageRecognition").predicate(UDFS.imageRecognition).default(!0),pdfRecognition:boolean$2("pdfRecognition").predicate(UDFS.pdfRecognition).default(!0),tableRecognition:boolean$2("tableRecognition").predicate(UDFS.tableRecognition).default(!1),processingMode:string$2("processingMode").predicate(UDFS.processingMode).default("auto"),readerPolicy:string$2("readerPolicy").predicate(UDFS.readerPolicy).default("auto"),readerPriority:string$2("readerPriority").predicate(UDFS.readerPriority).default("structure-first"),maxFileSizeMb:integer$1("maxFileSizeMb").predicate(UDFS.maxFileSizeMb).default(64),maxPages:integer$1("maxPages").predicate(UDFS.maxPages).default(500),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AIConfig,namespace:UDFS});podTable("vectorStore",{id:id("id").default("vector-stores.ttl#{key}"),name:string$2("name").predicate(UDFS.name),container:uri("container").predicate(UDFS.container),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.VectorStore,namespace:UDFS});podTable("indexedFile",{id:id("id").default("indexed-files.ttl#{key}"),fileUrl:uri("fileUrl").predicate(UDFS.fileUrl),vectorId:integer$1("vectorId").predicate(UDFS.vectorId),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),usageBytes:integer$1("usageBytes").predicate(UDFS.usageBytes),lastError:string$2("lastError").predicate(UDFS.lastError),indexedAt:timestamp("indexedAt").predicate(UDFS.indexedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.IndexedFile,namespace:UDFS});podTable("agentStatus",{id:id("id").default("agent-status.ttl#{key}"),agent:uri("agent").predicate(UDFS.agent).link(agentResource),status:string$2("status").predicate(UDFS.status),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),lastActivityAt:timestamp("lastActivityAt").predicate(UDFS.lastActivityAt),currentTask:uri("currentTask").predicate(UDFS.task).link(taskResource),errorMessage:string$2("errorMessage").predicate(UDFS.errorMessage)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AgentStatus,namespace:UDFS});const GatewayAccessKeyDeployment={local:"local",cloud:"cloud"},QuotaSnapshotStatus={available:"available",unsupported:"unsupported",error:"error"},gatewayAccessKeyResource=podTable("gatewayAccessKey",{id:id("id").default("ai/gateway/access-keys.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),secretHash:string$2("secretHash").predicate(UDFS.secretHash),name:string$2("name").predicate(UDFS.name),deployment:string$2("deployment").predicate(UDFS.deployment),scopes:text("scopes").array().predicate(UDFS.scopes),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),disabledAt:timestamp("disabledAt").predicate(UDFS.disabledAt),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/",type:UDFS.GatewayAccessKey,namespace:UDFS}),quotaSnapshotResource=podTable("quotaSnapshot",{id:id("id").default("ai/gateway/quota.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),deployment:string$2("deployment").predicate(UDFS.deployment),provider:string$2("provider").predicate(UDFS.provider),credential:uri("credential").predicate(UDFS.credential).link(credentialResource),status:string$2("status").predicate(UDFS.status),balance:integer$1("balance").predicate(UDFS.balance),windows:text("windows").predicate(UDFS.windows),observedAt:timestamp("observedAt").predicate(UDFS.observedAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),source:string$2("source").predicate(UDFS.source)},{base:"/.data/",type:UDFS.QuotaSnapshot,namespace:UDFS});ensureResourceIntrospectionColumns(gatewayAccessKeyResource);ensureResourceIntrospectionColumns(quotaSnapshotResource);function ensureResourceIntrospectionColumns(n){const e=n;e._&&e.columns&&e._.columns!==e.columns&&(e._.columns=e.columns);const t=e.columns;for(const i of Object.values(t??{}))typeof i.options?.predicate=="string"&&(i.getPredicate=()=>i.options?.predicate)}new Set(Object.values(GatewayAccessKeyDeployment));new Set(Object.values(QuotaSnapshotStatus));const AIConfigRuntimeCapability={chatCompletions:"chat_completions",responses:"responses",responsesWebSearch:"responses_web_search",imageInput:"image_input",imageGeneration:"image_generation",imageEditing:"image_editing",toolCalls:"tool_calls"};new Set(Object.values(AIConfigRuntimeCapability));const AI_CONFIG_PROVIDER_CATALOG=[{id:"dashscope",displayName:"DashScope",aliases:["qwen","alibaba","dashscope-cn"],defaultBaseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModels:["text-embedding-v4"],defaultModelType:"embedding"},{id:"openai",displayName:"OpenAI",aliases:["codex"],defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",displayName:"Anthropic",aliases:["claude"],defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",displayName:"Google",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta"},{id:"deepseek",displayName:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com/v1"},{id:"ollama",displayName:"Ollama",defaultBaseUrl:"http://localhost:11434/v1"},{id:"x-ai",displayName:"xAI",aliases:["xai"],defaultBaseUrl:"https://api.x.ai/v1"},{id:"openrouter",displayName:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1"},{id:"minimax",displayName:"MiniMax",defaultBaseUrl:"https://api.minimax.chat/v1"},{id:"mistral",displayName:"Mistral",defaultBaseUrl:"https://api.mistral.ai/v1"},{id:"groq",displayName:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1"},{id:"moonshot",displayName:"Moonshot",defaultBaseUrl:"https://api.moonshot.cn/v1"},{id:"zhipu",displayName:"ZhiPu",defaultBaseUrl:"https://open.bigmodel.cn/api/paas/v4"},{id:"codebuddy",displayName:"CodeBuddy",defaultBaseUrl:"https://api.codebuddy.ai/v1"},{id:"paddleocr",displayName:"PaddleOCR",aliases:["paddle"],defaultBaseUrl:"https://paddleocr.aistudio-app.com/api/v2/ocr/jobs",defaultModels:["PP-OCRv6"],defaultModelType:"document_understanding"}];new Map(AI_CONFIG_PROVIDER_CATALOG.map(n=>[n.id,n]));const ABSOLUTE_IRI=/^[a-zA-Z][a-zA-Z\d+.-]*:/;function normalizeText(n){return n.trim().toLowerCase()}function normalizeAIConfigResourceId(n){if(!n)return"";const e=n.trim();if(!e)return"";if(e.includes("#"))return e.split("#").pop()||e;if(!ABSOLUTE_IRI.test(e)&&!e.endsWith(".ttl"))return e;const t=e.replace(/\/$/,""),i=t.split("/").pop()||t;return i.endsWith(".ttl")?i.slice(0,-4):i}function aiConfigResourceRefToModelId(n,e){return normalizeAIConfigModelId(n,e)}function normalizeAIConfigModelId(n,e){const t=normalizeAIConfigResourceId(n);if(!t.includes("/"))return t;const[i,...s]=t.split("/");return s.length===0||!e?t:normalizeAIConfigProviderId(i)===normalizeAIConfigProviderId(e)?s.join("/"):t}function normalizeAIConfigProviderId(n){const e=normalizeText(normalizeAIConfigResourceId(n));if(!e)return"";for(const t of AI_CONFIG_PROVIDER_CATALOG)if(t.id===e||(t.aliases??[]).includes(e))return t.id;return e}function normalizeAIConfigModelStorageId(n,e){return aiConfigResourceRefToModelId(n,e)}function buildAIConfigModelStorageId(n,e){return aiModelResource.buildId({id:e,isProvidedBy:aiConfigProviderRef(n)})}function aiConfigProviderRef(n){const e=normalizeAIConfigProviderId(n);return e&&`settings/providers/${aiProviderResource.buildId({id:e})}`}function aiConfigModelRef(n,e){if(e===void 0)return normalizeAIConfigResourceId(n);const t=normalizeAIConfigProviderId(n),i=normalizeAIConfigModelStorageId(e,t);return t&&i?`settings/providers/${buildAIConfigModelStorageId(t,i)}`:i}const credentialDescriptor={uri:UDFS.Credential,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Credential,resourceKind:"credential",description:"Generic credential material required by runtimes, tools, MCP servers, and providers.",storage:{base:"/settings/credentials.ttl",resourceIdPattern:"#{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Local credential id."},service:{type:"string",predicate:UDFS.service,required:!0,description:"Credential service grouping, for example ai or infra."},providerId:{type:"string",predicate:UDFS.provider,required:!0,description:"Provider identifier such as openai or cloudflare."},secretType:{type:"string",predicate:UDFS.secretType,required:!0,description:"Provider-specific secret kind such as api-key or tunnel-token."},label:{type:"string",predicate:UDFS.label,description:"User-facing credential label."},apiKey:{type:"string",predicate:UDFS.apiKey,secret:!0,description:"Secret token or API key material."},authMode:{type:"string",predicate:UDFS.authMode,description:"Authentication mode such as apiKey, oauth, deviceCode, or console."},storageMode:{type:"string",predicate:UDFS.storageMode,description:"Credential storage format, for example plaintext-v1 or secret-cell-v1."},secretPayload:{type:"string",predicate:UDFS.secretPayload,secret:!0,description:"Storage-mode-specific credential payload. plaintext-v1 stores a JSON payload here."},encryptedSecret:{type:"string",predicate:UDFS.encryptedSecret,secret:!0,description:"Encrypted credential payload stored in the Pod."},wrappedDataKey:{type:"string",predicate:UDFS.wrappedDataKey,secret:!0,description:"Wrapped data-encryption key for encrypted credential payloads."},encryptionAlgorithm:{type:"string",predicate:UDFS.encryptionAlgorithm,description:"Credential encryption algorithm identifier."},keyVersion:{type:"string",predicate:UDFS.keyVersion,description:"Key-management version used to encrypt the credential."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Credential scopes granted by the provider."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Credential expiry timestamp."},accountLabel:{type:"string",predicate:UDFS.accountLabel,description:"Provider account label associated with the credential."},lastRefreshAt:{type:"timestamp",predicate:UDFS.lastRefreshAt,description:"Last successful credential refresh timestamp."},reauthRequired:{type:"boolean",predicate:UDFS.reauthRequired,description:"Whether this credential requires user reauthentication."},status:{type:"string",predicate:UDFS.status,description:"Credential health status."}},uniqueBy:["service","providerId","secretType"],writableFields:["label","apiKey","authMode","storageMode","secretPayload","encryptedSecret","wrappedDataKey","encryptionAlgorithm","keyVersion","scopes","expiresAt","accountLabel","lastRefreshAt","reauthRequired","status"],mergePolicy:"upsert",examples:[{request:"保存 Cloudflare tunnel token",match:{service:"infra",providerId:"cloudflare",secretType:"tunnel-token"}},{request:"保存 OpenAI API key",match:{service:"ai",providerId:"openai",secretType:"api-key"}}]},gatewayAccessKeyDescriptor={uri:UDFS.GatewayAccessKey,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.GatewayAccessKey,resourceKind:"gateway-access-key",description:"Control-primary Pod AI Gateway access key. The key owner is a semantic WebID/URI relation, while the secret itself is represented only by a hash.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/access-keys.ttl#key_1."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID or principal URI that owns this Gateway access key."},secretHash:{type:"string",predicate:UDFS.secretHash,required:!0,secret:!0,description:"Hash of the Gateway secret. Raw access key material must not be stored here."},name:{type:"string",predicate:UDFS.name,description:"User-visible label for distinguishing this Gateway access key."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment target: local or cloud."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Gateway scopes granted to this key."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Key expiry timestamp."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful Gateway use timestamp."},disabledAt:{type:"timestamp",predicate:UDFS.disabledAt,description:"Temporary disable timestamp. Clear it to enable the key again."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp. Presence means the key is no longer valid."}},uniqueBy:["id"],writableFields:["owner","secretHash","name","deployment","scopes","createdAt","expiresAt","lastUsedAt","revokedAt","disabledAt"],mergePolicy:"upsert",examples:[{request:"Create a local Gateway access key for a user",match:{id:"ai/gateway/access-keys.ttl#key_1"}}]},quotaSnapshotDescriptor={uri:UDFS.QuotaSnapshot,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.QuotaSnapshot,resourceKind:"quota-snapshot",description:"Observed Pod AI Gateway quota state for a provider credential. The credential field is a semantic URI relation, and normalized windows are stored as a serialized literal.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/quota.ttl#quota_1."},credential:{type:"uri",predicate:UDFS.credential,required:!0,description:"Credential resource URI this quota snapshot describes."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID that owns the credential and quota snapshot."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment scope: local or cloud."},provider:{type:"string",predicate:UDFS.provider,required:!0,description:"Normalized provider id for the quota snapshot."},status:{type:"string",predicate:UDFS.status,required:!0,description:"Quota availability status: available, unsupported, or error."},balance:{type:"number",predicate:UDFS.balance,description:"Normalized remaining quota balance when the provider exposes one."},windows:{type:"text",predicate:UDFS.windows,description:"Serialized normalized quota windows literal, for example JSON produced by Gateway normalization."},observedAt:{type:"timestamp",predicate:UDFS.observedAt,description:"Observation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Snapshot freshness expiry timestamp."},source:{type:"string",predicate:UDFS.source,description:"Observation source such as provider, gateway-cache, or manual."}},uniqueBy:["id"],writableFields:["credential","status","balance","windows","observedAt","expiresAt","source"],mergePolicy:"upsert",examples:[{request:"Record a fresh quota snapshot for a provider credential",match:{id:"ai/gateway/quota.ttl#quota_1"}}]},approvalDescriptor={uri:UDFS.ApprovalRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ApprovalRequest,resourceKind:"approval",description:"Durable approval request control item. Solid inbox notifications may point at this resource, but lifecycle and claim state live here.",storage:{base:"/.data/approvals/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Approval request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource that requested approval."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},toolCallId:{type:"string",predicate:UDFS.toolCallId,required:!0,description:"Opaque runtime tool-call identifier; not an RDF resource link."},toolName:{type:"string",predicate:UDFS.toolName,required:!0,description:"Runtime tool name that requires approval."},target:{type:"uri",predicate:ODRL.target,required:!0,description:"Target resource for the requested action. Schema field uses ODRL target in the executable resource."},action:{type:"uri",predicate:ODRL.action,required:!0,description:"Requested action URI. Schema field uses ODRL action in the executable resource."},risk:{type:"string",predicate:UDFS.risk,required:!0,description:"Risk level assigned by the runtime or policy layer."},status:{type:"string",predicate:UDFS.status,description:"Approval lifecycle status such as pending, handling, approved, rejected, resolved, or expired."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/approval handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to decide the request."},decisionBy:{type:"uri",predicate:UDFS.decisionBy,description:"WebID or agent resource that made the decision."},decisionRole:{type:"string",predicate:UDFS.decisionRole,description:"Role of the decision maker, for example human or secretary."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the decision applies."},reason:{type:"text",predicate:UDFS.reason,description:"Decision reason or policy explanation."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},approvalOptions:{type:"text",predicate:UDFS.approvalOptions,description:"Serialized approval options offered by the runtime."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version used to create or resolve this approval."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Decision timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","toolCallId","toolName","target","action","risk","status","leaseOwner","leaseExpiresAt","assignedTo","decisionBy","decisionRole","onBehalfOf","reason","context","approvalOptions","policyVersion","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending approval from Inbox subscription",match:{id:"2026/06/12.ttl#approval_1"}}]},inputRequestDescriptor={uri:UDFS.InputRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.InputRequest,resourceKind:"input-request",description:"Durable input request control item. It asks for missing information or a choice; approval/authority decisions remain ApprovalRequest.",storage:{base:"/.data/input-requests/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Input request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource waiting for input."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},run:{type:"uri",predicate:UDFS.run,description:"Run waiting for input."},task:{type:"uri",predicate:UDFS.task,description:"Task whose execution requires input."},requester:{type:"uri",predicate:UDFS.requester,description:"Runtime, worker, or Secretary resource that requested input."},requestKind:{type:"string",predicate:UDFS.requestKind,required:!0,description:"Input request category such as user-input, clarification, binding, or selection."},prompt:{type:"text",predicate:UDFS.prompt,required:!0,description:"Question or missing-information prompt."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},inputOptions:{type:"text",predicate:UDFS.inputOptions,description:"Serialized options offered for the input request."},status:{type:"string",predicate:UDFS.status,description:"Input request lifecycle status such as pending, handling, resolved, expired, or cancelled."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/input handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to answer the request."},response:{type:"text",predicate:UDFS.response,description:"Answer, selected option, or input supplied to unblock the run."},answeredBy:{type:"uri",predicate:UDFS.answeredBy,description:"WebID or agent resource that supplied the response."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the response applies."},reason:{type:"text",predicate:UDFS.reason,description:"Reason or explanation for the response."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque protocol-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Resolution timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","run","task","requester","requestKind","prompt","context","inputOptions","status","leaseOwner","leaseExpiresAt","assignedTo","response","answeredBy","onBehalfOf","reason","metadata","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending input request from Inbox subscription",match:{id:"2026/06/12.ttl#input_1"}}]};function exactIdStorage(n="/.data/"){return{base:n,resourceIdPattern:"{id}"}}const idField={type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id. For exact-id descriptors this includes the full document path and optional fragment."},captureCandidateDescriptor={uri:UDFS.CaptureCandidate,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureCandidate,resourceKind:"capture-candidate",description:"Temporary capture suggestion created from observed or ambiguous content. It is not formal memory until promoted through the appropriate typed resource and control flow.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource being considered."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Concise statement of what might be worth saving."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Proposed formal resource class such as Idea, Evidence, Note, Decision, Preference, Link, or ContactInfo."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Proposed folder, collection, project, task, issue, chat, or other scope."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence: high, medium, or low."},reason:{type:"text",predicate:UDFS.reason,description:"Short rationale for why this source might be worth capturing."},status:{type:"string",predicate:UDFS.status,description:"Candidate lifecycle status such as candidate, promoted, rejected, duplicate, ignored, or superseded."},sourceHash:{type:"string",predicate:UDFS.sourceHash,description:"Optional source digest for duplicate detection."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that created the candidate."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["source","summary","suggestedType","suggestedTarget","confidence","reason","status","sourceHash","chat","thread","task","run","actor","metadata","updatedAt"],mergePolicy:"upsert",examples:[{request:"Create a capture candidate from an observed chat message",match:{id:"candidates/2026/06/16.ttl#candidate_1"}}]},captureEventDescriptor={uri:UDFS.CaptureEvent,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureEvent,resourceKind:"capture-event",description:"Append-only capture decision ledger. It records direct commits, optimistic commits, candidate creation, promotion, rejection, correction, rollback, duplicate detection, and ignored decisions.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource considered by capture."},captureCandidate:{type:"uri",predicate:UDFS.captureCandidate,description:"Candidate resource involved in this event, when applicable."},targetResource:{type:"uri",predicate:UDFS.targetResource,description:"Formal resource affected by this capture decision."},decision:{type:"string",predicate:UDFS.captureDecision,required:!0,description:"Decision such as direct_commit, optimistic_commit, candidate_created, promoted, rejected, corrected, rollback, duplicate, or ignored."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Type suggested at decision time."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Target suggested at decision time."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence at decision time."},reason:{type:"text",predicate:UDFS.reason,description:"Explanation for the capture decision."},userCorrection:{type:"text",predicate:UDFS.userCorrection,description:"User correction to type, target, title, summary, or content."},approval:{type:"uri",predicate:UDFS.approval,description:"ApprovalRequest controlling an authority gate, if any."},inputRequest:{type:"uri",predicate:UDFS.inputRequest,description:"InputRequest controlling missing information, if any."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that made or recorded the decision."},about:{type:"uri",predicate:SCHEMA.about,description:"Control object or semantic subject the event is about."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."}},uniqueBy:["id"],writableFields:["source","captureCandidate","targetResource","decision","suggestedType","suggestedTarget","confidence","reason","userCorrection","approval","inputRequest","chat","thread","task","run","actor","about","metadata"],mergePolicy:"append",examples:[{request:"Record that a chat message became a capture candidate",match:{id:"events/2026/06/16.ttl#event_1"}}]},contactDescriptor={uri:UDFS.Contact,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:VCARD.Individual,resourceKind:"contact",description:"Unified address-book projection for Solid users, external users, groups, and AI agents.",storage:exactIdStorage("/.data/contacts/"),fields:{id:idField,name:{type:"string",predicate:VCARD.fn,required:!0,description:"Display name."},avatarUrl:{type:"uri",predicate:VCARD.hasPhoto,description:"Avatar image URI."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Person, Agent, Chat, or external resource this contact card is about."},rdfType:{type:"uri",predicate:RDF$1.type,required:!0,description:"Semantic classifier for the represented resource."},contactType:{type:"string",predicate:UDFS.contactType,required:!0,description:"Runtime/source hint for handler selection."},isPublic:{type:"boolean",predicate:AS.audience,description:"Whether the contact is public."},externalPlatform:{type:"string",predicate:UDFS.externalPlatform,description:"External platform namespace."},externalId:{type:"string",predicate:UDFS.externalId,description:"Opaque external platform id; not a resource relation."},alias:{type:"string",predicate:UDFS.alias,description:"Private display alias."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},note:{type:"text",predicate:VCARD.note,description:"Private note."},sortKey:{type:"string",predicate:UDFS.sortKey,description:"Stable sort key."},gender:{type:"string",predicate:VCARD.hasGender,description:"Demographic hint."},province:{type:"string",predicate:VCARD.region,description:"Region."},city:{type:"string",predicate:VCARD.locality,description:"Locality."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."},lastSyncedAt:{type:"timestamp",predicate:UDFS.lastSyncedAt,description:"Last sync timestamp."}},uniqueBy:["id"],writableFields:["name","avatarUrl","about","rdfType","contactType","isPublic","externalPlatform","externalId","alias","starred","note","sortKey","gender","province","city","deletedAt","lastSyncedAt"],mergePolicy:"upsert",examples:[{request:"Create an AI agent contact projection",match:{id:"agent-secretary.ttl"}}]},chatDescriptor={uri:MEETING.LongChat,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.LongChat,resourceKind:"chat",description:"Interactive command surface/counterpart: who or what the user is talking with.",storage:exactIdStorage("/.data/chat/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Chat title."},description:{type:"string",predicate:DCTerms.description,description:"Chat description."},avatarUrl:{type:"uri",predicate:SCHEMA.image,description:"Avatar image URI."},author:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},status:{type:"string",predicate:UDFS.status,description:"Chat lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},muted:{type:"boolean",predicate:UDFS.muted,description:"Muted flag."},unreadCount:{type:"number",predicate:UDFS.unreadCount,description:"Unread message count."},contact:{type:"uri",predicate:UDFS.hasContact,description:"Optional counterpart/contact represented by this channel."},participants:{type:"uri",predicate:WF.participant,array:!0,description:"Participant resource URIs."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},lastActiveAt:{type:"timestamp",predicate:UDFS.lastActiveAt,description:"Last activity timestamp."},lastMessage:{type:"uri",predicate:UDFS.lastMessage,description:"Latest message pointer."},lastMessagePreview:{type:"text",predicate:SCHEMA.text,description:"Latest message preview."}},uniqueBy:["id"],writableFields:["title","description","avatarUrl","author","status","starred","muted","unreadCount","contact","participants","metadata","lastActiveAt","lastMessage","lastMessagePreview"],mergePolicy:"upsert",examples:[{request:"Create a team chat surface",match:{id:"team/index.ttl#this"}}]},threadDescriptor={uri:SIOC.Thread,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:SIOC.Thread,resourceKind:"thread",description:"Concrete timeline/place under one parent command surface. Ownership is thread.parent via sioc:has_parent.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container."},title:{type:"string",predicate:DCTerms.title,description:"Thread title."},status:{type:"string",predicate:UDFS.status,description:"Thread lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},workspace:{type:"uri",predicate:UDFS.workspace,description:"Storage-layer workspace/container URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."}},uniqueBy:["id"],writableFields:["parent","title","status","starred","workspace","metadata"],mergePolicy:"upsert",examples:[{request:"Create a thread under a chat surface",match:{id:"chat/team/index.ttl#thread"}}]},messageDescriptor={uri:MEETING.Message,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.Message,resourceKind:"message",description:"Human/runtime communication item under one parent command surface and optionally a concrete thread timeline.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container URI."},chat:{type:"uri",predicate:WF.message,description:"Solid Chat compatibility containment relation."},thread:{type:"uri",predicate:SIOC.has_member,description:"Thread containment relation."},maker:{type:"uri",predicate:FOAF.maker,description:"Author resource IRI."},role:{type:"string",predicate:UDFS.messageType,description:"Message role."},content:{type:"text",predicate:SIOC.content,required:!0,description:"Plain text content."},richContent:{type:"text",predicate:SIOC.richContent,description:"Structured/rich content payload."},status:{type:"string",predicate:UDFS.messageStatus,description:"Message lifecycle status."},toolName:{type:"string",predicate:UDFS.toolName,description:"Tool name for tool messages."},toolCallId:{type:"string",predicate:UDFS.toolCallId,description:"Opaque tool call id; not a resource relation."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},replacedBy:{type:"string",predicate:DCTerms.isReplacedBy,description:"Replacement message reference."},deletedAt:{type:"timestamp",predicate:SCHEMA.dateDeleted,description:"Deletion timestamp."},senderName:{type:"string",predicate:UDFS.senderName,description:"Display sender name."},senderAvatarUrl:{type:"uri",predicate:UDFS.senderAvatarUrl,description:"Display sender avatar."},mentions:{type:"uri",predicate:UDFS.mentions,array:!0,description:"Mentioned resource URIs."},replyTo:{type:"uri",predicate:UDFS.replyTo,description:"Original message URI."},routedBy:{type:"uri",predicate:UDFS.routedBy,description:"Routing agent URI."},routeTargetAgent:{type:"uri",predicate:UDFS.routeTargetAgent,description:"Target agent URI."},coordinationId:{type:"string",predicate:UDFS.coordinationId,description:"Opaque multi-agent coordination id."}},uniqueBy:["id"],writableFields:["parent","chat","thread","maker","role","content","richContent","status","toolName","toolCallId","metadata","replacedBy","deletedAt","senderName","senderAvatarUrl","mentions","replyTo","routedBy","routeTargetAgent","coordinationId"],mergePolicy:"append",examples:[{request:"Append a message under a team chat",match:{id:"chat/team/2026/06/14/messages.ttl#msg_1"}}]},chatProjectContextDescriptor={uri:UDFS.ChatProjectContext,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ChatProjectContext,resourceKind:"chat-project-context",description:"Workspace-scoped instructions and explicit memory-use preference shared by related chat threads.",storage:exactIdStorage("/.data/chat-projects/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this context."},instructions:{type:"text",predicate:UDFS.systemMessage,description:"User-maintained project instructions."},memoryEnabled:{type:"boolean",predicate:UDFS.memoryEnabled,description:"Whether explicit project memories may be injected into model context."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","instructions","memoryEnabled","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Save shared instructions for a workspace",match:{id:"workspace-key.ttl"}}]},chatProjectMemoryDescriptor={uri:UDFS.ProjectMemory,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ProjectMemory,resourceKind:"chat-project-memory",description:"One user-approved, workspace-scoped memory entry with optional message provenance.",storage:exactIdStorage("/.data/chat-project-memories/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this memory."},text:{type:"text",predicate:SCHEMA.text,required:!0,description:"Explicit memory text."},sourceMessage:{type:"uri",predicate:UDFS.sourceMessage,description:"Optional source message URI."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","text","sourceMessage","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Remember an explicit project fact",match:{id:"memory-id.ttl"}}]},conversationShareDescriptor={uri:UDFS.ConversationShare,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ConversationShare,resourceKind:"conversation-share",description:"Revocable metadata record for a sanitized, read-only conversation export.",storage:exactIdStorage("/.data/chat-shares/"),fields:{id:idField,thread:{type:"uri",predicate:UDFS.targetThread,required:!0,description:"Shared thread URI."},resourceUrl:{type:"uri",predicate:SCHEMA.url,required:!0,description:"Public read-only HTML resource URL."},includeToolDetails:{type:"boolean",predicate:UDFS.includeToolDetails,description:"Whether sanitized tool details were included."},excludedMessageIds:{type:"string",predicate:UDFS.excludedMessage,array:!0,description:"Messages excluded by the user before sharing."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp."}},uniqueBy:["id"],writableFields:["thread","resourceUrl","includeToolDetails","excludedMessageIds","createdAt","revokedAt"],mergePolicy:"upsert",examples:[{request:"Record a read-only conversation share",match:{id:"share-id.ttl"}}]},ideaDescriptor={uri:UDFS.Idea,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Idea,resourceKind:"idea",description:"File-primary candidate extracted from conversation before it is promoted to committed work. The document owns human-readable content; meta owns status and routing facts.",storage:exactIdStorage("/.data/ideas/"),fields:{id:idField,summary:{type:"string",predicate:DCTerms.abstract,required:!0,description:"Short summary of the idea."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the idea body."},input:{type:"text",predicate:DCTerms.description,description:"Original or synthesized input text."},status:{type:"string",predicate:UDFS.status,description:"Idea lifecycle status."},commitment:{type:"string",predicate:UDFS.commitment,description:"Commitment level such as thought, direction, tentative_decision, or committed."},affectedArea:{type:"string",predicate:UDFS.affectedArea,description:"System or product area the idea may affect."},currentUnderstanding:{type:"text",predicate:UDFS.currentUnderstanding,description:"Current synthesized understanding."},openQuestions:{type:"text",predicate:UDFS.openQuestions,array:!0,description:"Open questions before promotion."},related:{type:"uri",predicate:DCTerms.relation,array:!0,description:"Related control records or resources."},conflicts:{type:"text",predicate:UDFS.conflicts,array:!0,description:"Potential semantic conflicts."},nextStep:{type:"text",predicate:UDFS.nextStep,description:"Suggested next action."},promotedTo:{type:"uri",predicate:UDFS.promotedTo,description:"Committed resource created from the idea."},chat:{type:"uri",predicate:UDFS.conversation,description:"Source chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Source thread."},sourceMessages:{type:"uri",predicate:DCTerms.source,array:!0,description:"Source messages."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["summary","document","input","status","commitment","affectedArea","currentUnderstanding","openQuestions","related","conflicts","nextStep","promotedTo","chat","thread","sourceMessages","createdBy","metadata"],mergePolicy:"upsert",examples:[{request:"Capture a fragmented product idea for later triage",match:{id:"2026/05/28.ttl#idea_symphony_quality_metrics"}}]},issueDescriptor={uri:UDFS.Issue,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Issue,resourceKind:"issue",description:"File-primary user-facing work item for a requirement, bug, support item, investigation, or feature request. The document owns human-readable content; meta owns status and routing facts.",storage:{base:"/.data/issues/",resourceIdPattern:"{id}"},fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Compact issue label for list/search surfaces; the file owns the full title/body."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the issue body."},description:{type:"text",predicate:DCTerms.description,description:"Issue description."},status:{type:"string",predicate:UDFS.status,description:"Issue lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Issue priority."},labels:{type:"text",predicate:UDFS.tags,array:!0,description:"Tags or labels."},chat:{type:"uri",predicate:UDFS.conversation,description:"Owning or source chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Owning or source thread."},parentIssue:{type:"uri",predicate:UDFS.parentIssue,description:"Parent issue."},tasks:{type:"uri",predicate:UDFS.task,array:!0,description:"Executable task slices."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},closedAt:{type:"timestamp",predicate:UDFS.closedAt,description:"Closure timestamp."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."}},uniqueBy:["id"],writableFields:["title","document","description","status","priority","labels","chat","thread","parentIssue","tasks","createdBy","assignedTo","closedAt","deletedAt"],mergePolicy:"upsert",examples:[{request:"Create a Symphony issue for a delegated implementation slice",match:{id:"issue_symphony_runtime_projection.ttl"}}]},taskDescriptor={uri:UDFS.Task,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Task,resourceKind:"task",description:"Durable executable work unit. Scheduling, runner selection, and concrete attempts live outside Task.",storage:exactIdStorage("/.data/task/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,description:"Task title."},instruction:{type:"text",predicate:UDFS.instruction,required:!0,description:"Executable instruction."},prompt:{type:"text",predicate:UDFS.prompt,description:"Runtime prompt projection."},issue:{type:"uri",predicate:UDFS.issue,description:"Originating issue."},message:{type:"uri",predicate:UDFS.message,description:"Message that produced this task."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Task lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Priority."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["title","instruction","prompt","issue","message","workspace","status","priority","assignedTo","source","metadata"],mergePolicy:"upsert",examples:[{request:"Create an executable task under an issue",match:{id:"task_symphony_worker_projection"}}]},scheduleDescriptor={uri:UDFS.Schedule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Schedule,resourceKind:"schedule",description:"Time-based trigger configuration for a Task.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,required:!0,description:"Scheduled task."},status:{type:"string",predicate:UDFS.status,description:"Schedule lifecycle status."},scheduleKind:{type:"string",predicate:UDFS.scheduleKind,description:"Schedule kind: once, interval, or cron."},cron:{type:"string",predicate:UDFS.cron,description:"Cron expression."},intervalSeconds:{type:"number",predicate:UDFS.intervalSeconds,description:"Interval in seconds."},timezone:{type:"string",predicate:UDFS.timezone,description:"Timezone."},startsAt:{type:"timestamp",predicate:UDFS.startsAt,description:"Start timestamp."},nextRunAt:{type:"timestamp",predicate:UDFS.nextRunAt,description:"Next run timestamp."},lastRunAt:{type:"timestamp",predicate:UDFS.lastRunAt,description:"Last run timestamp."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["task","status","scheduleKind","cron","intervalSeconds","timezone","startsAt","nextRunAt","lastRunAt","metadata"],mergePolicy:"upsert",examples:[{request:"Create a time trigger for a task",match:{id:"schedules/schedule_1.ttl"}}]},automationRuleDescriptor={uri:UDFS.AutomationRule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AutomationRule,resourceKind:"automation_rule",description:"Policy, condition, and action wiring that can dispatch tasks or scheduled work.",storage:exactIdStorage(),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Rule title."},description:{type:"text",predicate:DCTerms.description,description:"Rule description."},status:{type:"string",predicate:UDFS.status,description:"Rule lifecycle status."},ruleKind:{type:"string",predicate:UDFS.ruleKind,description:"Rule kind: event, schedule, or manual."},task:{type:"uri",predicate:UDFS.task,description:"Task dispatched by this rule."},schedule:{type:"uri",predicate:UDFS.schedule,description:"Schedule that triggers this rule."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},condition:{type:"json",predicate:UDFS.condition,description:"Structured condition."},actions:{type:"json",predicate:UDFS.actions,description:"Structured actions."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},lastTriggeredAt:{type:"timestamp",predicate:UDFS.lastTriggeredAt,description:"Last trigger timestamp."},lastRunStatus:{type:"string",predicate:UDFS.lastRunStatus,description:"Last run status."}},uniqueBy:["id"],writableFields:["title","description","status","ruleKind","task","schedule","source","target","condition","actions","metadata","lastTriggeredAt","lastRunStatus"],mergePolicy:"upsert",examples:[{request:"Create an automation rule that dispatches a task",match:{id:"automation/rule_1.ttl"}}]},deliveryDescriptor={uri:UDFS.Delivery,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Delivery,resourceKind:"delivery",description:"Internal handoff envelope between threads, sessions, agents, and runtimes.",storage:exactIdStorage(),fields:{id:idField,kind:{type:"string",predicate:UDFS.deliveryKind,description:"Delivery kind."},status:{type:"string",predicate:UDFS.status,description:"Delivery lifecycle status."},task:{type:"uri",predicate:UDFS.task,description:"Task being delivered."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Source thread."},targetThread:{type:"uri",predicate:UDFS.targetThread,description:"Target thread."},targetSession:{type:"uri",predicate:UDFS.targetSession,description:"Target session."},actor:{type:"uri",predicate:AS.actor,description:"Actor."},object:{type:"uri",predicate:AS.object,description:"Object resource."},objective:{type:"text",predicate:UDFS.objective,description:"Short objective."},payload:{type:"json",predicate:UDFS.payload,description:"Structured payload."},projection:{type:"json",predicate:UDFS.projection,description:"Runtime projection."},projectedRole:{type:"string",predicate:UDFS.projectedRole,description:"Projected runtime role."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},error:{type:"text",predicate:UDFS.error,description:"Failure detail."},dispatchedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Dispatch timestamp."},consumedAt:{type:"timestamp",predicate:UDFS.consumedAt,description:"Consumption timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["kind","status","task","source","target","chat","thread","targetThread","targetSession","actor","object","objective","payload","projection","projectedRole","metadata","error","dispatchedAt","consumedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Create a worker delivery package",match:{id:"task/symphony/2026/05/28/deliveries.ttl#delivery_1"}}]},runDescriptor={uri:UDFS.Run,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Run,resourceKind:"run",description:"One concrete execution attempt by an agent runtime.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,description:"Task being executed."},delivery:{type:"uri",predicate:UDFS.delivery,description:"Delivery that caused or carries this run."},trigger:{type:"uri",predicate:UDFS.trigger,description:"Resource that triggered the run."},input:{type:"uri",predicate:UDFS.input,description:"Concrete input/context projection resource."},thread:{type:"uri",predicate:UDFS.inThread,required:!0,description:"Runtime thread."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Run lifecycle status."},runner:{type:"string",predicate:UDFS.runner,required:!0,description:"Runtime implementation."},prompt:{type:"string",predicate:UDFS.prompt,description:"Prompt or prompt version."},externalRunId:{type:"string",predicate:UDFS.externalRunId,description:"Opaque external runtime id; not a resource relation."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Lease owner."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Lease expiration timestamp."},heartbeatAt:{type:"timestamp",predicate:UDFS.heartbeatAt,description:"Heartbeat timestamp."},cancelRequestedAt:{type:"timestamp",predicate:UDFS.cancelRequestedAt,description:"Cancel request timestamp."},error:{type:"string",predicate:UDFS.error,description:"Failure detail."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},startedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Start timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["task","delivery","trigger","input","thread","workspace","status","runner","prompt","externalRunId","leaseOwner","leaseExpiresAt","heartbeatAt","cancelRequestedAt","error","metadata","startedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Record a runtime execution attempt",match:{id:"task/symphony/2026/05/28/runs.ttl#run_1"}}]},runStepDescriptor={uri:UDFS.RunStep,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.RunStep,resourceKind:"run_step",description:"Append-only execution fact emitted while a run executes.",storage:exactIdStorage(),fields:{id:idField,run:{type:"uri",predicate:UDFS.run,required:!0,description:"Run this step belongs to."},stepType:{type:"string",predicate:UDFS.stepType,required:!0,description:"RunStep event type."},message:{type:"string",predicate:DCTerms.description,description:"Human-readable step message."},payload:{type:"json",predicate:UDFS.payload,description:"Structured step payload."}},uniqueBy:["id"],writableFields:["run","stepType","message","payload"],mergePolicy:"append",examples:[{request:"Append a runtime tool call step",match:{id:"task/symphony/2026/05/28/runs.ttl#run-step_1"}}]},evidenceDescriptor={uri:UDFS.Evidence,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Evidence,resourceKind:"evidence",description:"Append-only proof or finding for a workflow control object.",storage:exactIdStorage(),fields:{id:idField,evidenceKind:{type:"string",predicate:UDFS.evidenceKind,required:!0,description:"Evidence kind."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object this evidence supports."},issue:{type:"uri",predicate:UDFS.issue,description:"Related issue."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related thread."},summary:{type:"text",predicate:DCTerms.abstract,description:"Evidence summary."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the evidence."},outcome:{type:"string",predicate:UDFS.outcome,description:"Evidence outcome."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["evidenceKind","about","issue","task","delivery","run","thread","summary","source","actor","outcome","metadata"],mergePolicy:"append",examples:[{request:"Record test evidence for a task",match:{id:"task/symphony/2026/05/28/evidence.ttl#evidence_1"}}]},reportDescriptor={uri:UDFS.Report,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Report,resourceKind:"report",description:"Closure, review, handoff, status, or quality summary for a control object.",storage:exactIdStorage(),fields:{id:idField,reportKind:{type:"string",predicate:UDFS.reportKind,required:!0,description:"Report kind."},status:{type:"string",predicate:UDFS.status,description:"Report lifecycle status."},outcome:{type:"string",predicate:UDFS.outcome,description:"Reported outcome."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object being summarized."},issue:{type:"uri",predicate:UDFS.issue,description:"Related issue."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related thread."},evidence:{type:"uri",predicate:UDFS.evidence,array:!0,description:"Evidence summarized by this report."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Report summary."},reviewer:{type:"uri",predicate:SCHEMA.reviewedBy,description:"Reviewer."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the report."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},metricFacts:{type:"json",predicate:UDFS.metricFacts,description:"Structured metric facts."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},publishedAt:{type:"timestamp",predicate:DCTerms.issued,description:"Publication timestamp."}},uniqueBy:["id"],writableFields:["reportKind","status","outcome","about","issue","task","delivery","run","thread","evidence","summary","reviewer","actor","source","metricFacts","metadata","publishedAt"],mergePolicy:"upsert",examples:[{request:"Publish a worker handoff report",match:{id:"task/symphony/2026/05/28/reports.ttl#report_1"}}]},sessionDescriptor={uri:UDFS.term("Session"),version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.term("Session"),resourceKind:"session",description:"Runtime or collaboration session lifecycle projection for a concrete thread.",storage:exactIdStorage("/.data/sessions/"),fields:{id:idField,owner:{type:"uri",predicate:UDFS.actor,required:!0,description:"Session owner."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related thread."},status:{type:"string",predicate:UDFS.sessionStatus,description:"Session lifecycle status."},tool:{type:"string",predicate:UDFS.sessionTool,description:"Runtime tool or backend."},tokenUsage:{type:"number",predicate:UDFS.tokenUsage,description:"Token usage."},messages:{type:"uri",predicate:UDFS.message,array:!0,description:"Messages in this session."},policy:{type:"uri",predicate:UDFS.policy,description:"Policy resource."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},archivedAt:{type:"timestamp",predicate:UDFS.archivedAt,description:"Archive timestamp."}},uniqueBy:["id"],writableFields:["owner","chat","thread","status","tool","tokenUsage","messages","policy","policyVersion","metadata","archivedAt"],mergePolicy:"upsert",examples:[{request:"Record a worker runtime session",match:{id:"2026/05/28/sess_1.ttl"}}]},officialPodModelDescriptors=[credentialDescriptor,gatewayAccessKeyDescriptor,quotaSnapshotDescriptor,contactDescriptor,chatDescriptor,threadDescriptor,messageDescriptor,chatProjectContextDescriptor,chatProjectMemoryDescriptor,conversationShareDescriptor,ideaDescriptor,issueDescriptor,taskDescriptor,scheduleDescriptor,automationRuleDescriptor,deliveryDescriptor,runDescriptor,runStepDescriptor,evidenceDescriptor,reportDescriptor,captureCandidateDescriptor,captureEventDescriptor,sessionDescriptor,approvalDescriptor,inputRequestDescriptor];function createPodModelDescriptorRegistry(n=officialPodModelDescriptors){const e=new Map(n.map(t=>[t.uri,t]));return{list(t={}){return n.filter(i=>!(t.source&&i.source!==t.source||t.resourceKind&&i.resourceKind!==t.resourceKind))},describe(t){return e.get(t)??null}}}createPodSchema();function createPodSchema(n=createPodModelDescriptorRegistry()){const e=(t={})=>{const i=t.uri??t.schemaUri;if(!i)return n.list();const s=n.describe(i);return s?[s]:[]};return{list:n.list,describe(t){const i=typeof t=="string"?t:"uri"in t?t.uri:t.schemaUri;return n.describe(i)},classes(t={}){return e(t).map(i=>({schemaUri:i.uri,resourceKind:i.resourceKind,class:i.class,namespace:i.namespace,source:i.source,trustLevel:i.trustLevel,description:i.description}))},search(t){const i=normalizeSearchTerms(t.query);return i.length===0?[]:n.list({source:t.source,resourceKind:t.resourceKind}).map(s=>scoreDescriptorSearch(s,i)).filter(s=>s!==null).sort((s,o)=>o.score-s.score||s.uri.localeCompare(o.uri)).slice(0,Math.max(1,t.limit??10))},predicates(t={}){return e(t).flatMap(i=>Object.entries(i.fields).filter(([s])=>!t.field||s===t.field).map(([s,o])=>({schemaUri:i.uri,field:s,predicate:o.predicate,type:o.type,required:!!o.required,secret:!!o.secret,array:!!o.array,description:o.description})))}}}function normalizeSearchTerms(n){return n.toLowerCase().split(/[\s,;:/#._-]+/u).map(e=>e.trim()).filter(Boolean)}function scoreDescriptorSearch(n,e){const t=new Set;let i=0;const s=(o,l,u)=>{if(!l)return;const h=l.toLowerCase();for(const d of e)h.includes(d)&&(t.add(o),i+=u)};s("uri",n.uri,10),s("class",n.class,10),s("namespace",n.namespace,4),s("resourceKind",n.resourceKind,8),s("description",n.description,4),s("storage",`${n.storage.base}${n.storage.resourceIdPattern}`,3);for(const[o,l]of Object.entries(n.fields))s(`field:${o}`,o,6),s(`predicate:${o}`,l.predicate,6),s(`description:${o}`,l.description,3);for(const o of n.examples){s("example",o.request,3);for(const[l,u]of Object.entries(o.match))s(`example:${l}`,String(u),3)}return i<=0?null:{uri:n.uri,resourceKind:n.resourceKind,class:n.class,namespace:n.namespace,source:n.source,trustLevel:n.trustLevel,description:n.description,score:i,matchedFields:[...t].sort()}}const CLOUD_PROVISIONING_UNAVAILABLE="Cloud storage is not ready. Please wait for Xpod to reconnect and try again.",localProvisionResolvers=new WeakMap;function isManagedLocalProvisionHost(){return typeof window<"u"&&localProvisionResolvers.has(window)}function unregisterLocalProvisionResolver(){typeof window<"u"&&localProvisionResolvers.delete(window)}function registerLocalProvisionResolver(n){typeof window<"u"&&localProvisionResolvers.set(window,n)}function readStoredProvisionCodeRaw(){try{const n=sessionStorage.getItem("provisionCode")?.trim();return n||void 0}catch{return}}function isProvisionCodeCurrent(n){const e=n.split(".")[0];if(!e)return!0;try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return!0;const s=JSON.parse(globalThis.atob(i));return typeof s.exp=="number"?s.exp>Math.floor(Date.now()/1e3):!0}catch{return!0}}function normalizeProvisionCode(n){const e=n?.trim();if(e)return isProvisionCodeCurrent(e)?e:void 0}function getStoredProvisionCode(){return normalizeProvisionCode(readStoredProvisionCodeRaw())}function setStoredProvisionCode(n){try{sessionStorage.setItem("provisionCode",n)}catch{}}function clearStoredProvisionCode(){try{sessionStorage.removeItem("provisionCode")}catch{}}function buildPodCreatePayload(n,e=getStoredProvisionCode(),t){const i={name:n.trim()};return e&&(i.settings={provisionCode:e,...t?{provisionReceipt:t}:{}}),i}async function resolveProvisionCodeForCurrentScope(n){const e=await resolveCurrentProvisionTargetState(n);if(e.activeProvisionCode)return e.activeProvisionCode;if(e.hasProvisionOperation)throw new Error(CLOUD_PROVISIONING_UNAVAILABLE)}async function resolveCurrentProvisionTargetState(n){const e=typeof window<"u"?window.__XPOD__:void 0;if(e?.authenticating===!0){const l=typeof e.provisionCode=="string"?e.provisionCode.trim():void 0,u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):(clearStoredProvisionCode(),l?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}:{hasProvisionOperation:!1})}const t=n?.trim()||(typeof e?.provisionCode=="string"?e.provisionCode.trim():void 0),i=typeof window<"u"?localProvisionResolvers.get(window):void 0;if(!t&&i){const l=await i(),u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}}const s=t||readStoredProvisionCodeRaw(),o=normalizeProvisionCode(s);return o?{activeProvisionCode:o,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(o)?.storageRoot}:s?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(s)?.storageRoot}:{hasProvisionOperation:!1}}async function resolveProvisionCodeForPodCreate(n){return resolveProvisionCodeForCurrentScope(n)}function decodeProvisionScopePayload(n){const e=parseProvisionScopePayload(n);if(!e)return;const t=typeof e.serviceAccessToken=="string"?e.serviceAccessToken:typeof e.serviceToken=="string"?e.serviceToken:void 0;if(!(typeof e.spUrl!="string"||!t)&&!(typeof e.exp=="number"&&e.exp<Math.floor(Date.now()/1e3))&&!(typeof e.serviceAccessTokenExp=="number"&&e.serviceAccessTokenExp<Math.floor(Date.now()/1e3)))return{spUrl:ensureTrailingSlash(e.spUrl),serviceToken:t,serviceAccessToken:typeof e.serviceAccessToken=="string"?e.serviceAccessToken:void 0,serviceAccessTokenExp:typeof e.serviceAccessTokenExp=="number"?e.serviceAccessTokenExp:void 0,spDomain:typeof e.spDomain=="string"?e.spDomain:void 0,exp:typeof e.exp=="number"?e.exp:void 0}}function parseProvisionScopePayload(n){if(!n)return;const e=n.split(".")[0];if(e)try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return;const s=Uint8Array.from(globalThis.atob(i),o=>o.charCodeAt(0));return JSON.parse(new TextDecoder().decode(s))}catch{return}}function resolveProvisionScope(n){const e=decodeProvisionScopePayload(n);if(!e)return;const t=e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl);return{lookupUrl:t,storageRoot:t,serviceToken:e.serviceToken}}function resolveProvisionStorageTarget(n){const e=parseProvisionScopePayload(n);if(typeof e?.spUrl=="string")return{storageRoot:e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl)}}async function prepareProvisionedPod(n,e,t){const i=resolveProvisionScope(t);if(!i||!t)return t?{provisionCode:t}:void 0;const s=await n(new URL("/provision/pods",resolveProvisionApiBaseUrl(i)).toString(),{method:"POST",headers:{Authorization:`Bearer ${i.serviceToken}`,"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({podName:e})});if(!s.ok)throw new Error(await readResponseMessage(s)??"Failed to prepare Local Pod");const o=await s.json().catch(()=>{}),l=typeof o?.provisionReceipt=="string"?o.provisionReceipt:void 0;if(!l)throw new Error("Local Pod preparation did not return a provision receipt");return{provisionCode:t,provisionReceipt:l}}function resolveProvisionApiBaseUrl(n){return(isManagedLocalProvisionHost()?currentLoopbackLookupUrl():void 0)??n.lookupUrl}function currentLoopbackLookupUrl(){if(!(typeof window>"u"))try{const n=new URL(window.location.href);return isLoopbackHostname$2(n.hostname)?ensureTrailingSlash(n.origin):void 0}catch{return}}function isLoopbackHostname$2(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}async function readResponseMessage(n){const e=await n.text?.().catch(()=>{});if(e)try{const t=JSON.parse(e);return typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:e}catch{return e}}function storageUrlBelongsToRoot(n,e){const t=normalizeStorageUrl(n),i=normalizeStorageRoot$1(e);return!!(t&&i&&t.startsWith(i))}function normalizeStorageRoot$1(n){if(n)try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}const SOLID_STORAGE_KEYS=new Set(["solid:storage","http://www.w3.org/ns/solid/terms#storage","pim:storage","http://www.w3.org/ns/pim/space#storage"]);async function fetchProfileStorageUrls(n,e){const t=await n(e,{headers:{Accept:"text/turtle, application/ld+json, application/json"},credentials:"include"}).catch(()=>{});if(!t?.ok)return[];const i=t.headers?.get?.("content-type")??"",s=await t.text().catch(()=>"");if(!s)return[];if(i.includes("json"))try{return uniqueNormalizedStorageUrls(extractStorageUrlsFromJson(JSON.parse(s)))}catch{return[]}return uniqueNormalizedStorageUrls(extractStorageUrlsFromTurtle(s))}function extractStorageUrlsFromTurtle(n){return Array.from(n.matchAll(/(?:solid:storage|pim:storage|<http:\/\/www\.w3\.org\/ns\/solid\/terms#storage>|<http:\/\/www\.w3\.org\/ns\/pim\/space#storage>)\s+<([^>]+)>/giu)).map(e=>e[1]).filter(e=>typeof e=="string"&&e.length>0)}function extractStorageUrlsFromJson(n){const e=new Set,t=new WeakSet,i=(s,o=!1)=>{if(typeof s=="string"){o&&e.add(s);return}if(!(!s||typeof s!="object")&&!t.has(s)){if(t.add(s),Array.isArray(s)){for(const l of s)i(l,o);return}for(const[l,u]of Object.entries(s)){const h=SOLID_STORAGE_KEYS.has(l);if(o&&l==="@id"){i(u,!0);continue}i(u,o||h)}}};return i(n),Array.from(e)}function normalizeStorageUrl(n){try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}function uniqueNormalizedStorageUrls(n){const e=new Set;for(const t of n){const i=normalizeStorageUrl(t);i&&e.add(i)}return Array.from(e)}function ensureTrailingSlash(n){return n.replace(/\/+$/u,"")+"/"}const XPOD_RETURN_PATH_PREFIXES=["/dashboard","/status","/network","/settings","/ai-config","/ai-connections"];function normalizeXpodReturnPath(n){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const e=n.trim(),t=decodeForValidation(e),i=t.split(/[?#]/,1)[0];if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||t.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(t)||t.startsWith("//")||i.split("/").some(s=>s==="..")||!XPOD_RETURN_PATH_PREFIXES.some(s=>i===s||i.startsWith(`${s}/`)))throw new TypeError("returnTo must be a safe path within the application allow-list");return e}function decodeForValidation(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}const XPOD_LOGIN_ROUTE_ID="xpod-current-origin";function createXpodLoginRoute(n=typeof window>"u"?"http://localhost":window.location){const e=toLocation(n),t=e.origin;if(!t||t==="null")throw new TypeError("Xpod login requires a same-origin browser URL");return{id:XPOD_LOGIN_ROUTE_ID,label:"Xpod",identityProvider:{url:t,label:e.host||t},storageProvider:{url:t,label:e.host||t},availability:"ready"}}function normalizeXpodReturnTo(n){return normalizeXpodReturnPath(n)}function assertXpodLoginRoute(n,e){const t=normalizeWebIdLoginRoute(n),i=new URL(e).origin,s=new URL(t.identityProvider.url).origin,o=t.storageProvider?new URL(t.storageProvider.url).origin:void 0;if(t.id!==XPOD_LOGIN_ROUTE_ID||s!==i||o!==i||t.identityProvider.url!==t.storageProvider?.url)throw new TypeError("Xpod login route must use the current origin for identity and storage");return{...t,identityProvider:{...t.identityProvider,url:i},storageProvider:t.storageProvider?{...t.storageProvider,url:i}:void 0}}function toLocation(n){if(typeof n=="string"){const e=new URL(n,typeof window>"u"?void 0:window.location.href);return{origin:e.origin,host:e.host,href:e.href}}return n instanceof URL?{origin:n.origin,host:n.host,href:n.href}:{origin:n.origin,host:n.host,href:n.href}}const XPOD_LAST_OIDC_ISSUER_STORAGE_KEY="xpod.solid.lastOidcIssuer",XPOD_INRUPT_STORAGE_KEY_PREFIX="xpod.inrupt.",XpodSolidRuntimeContext=reactExports.createContext(null);function snapshotToState(n,e,t){return n.status==="initializing"?{status:"loading",issuer:t}:n.status==="anonymous"?{status:"anonymous",issuer:t}:n.status==="expired"?{status:"expired",webId:n.webId,issuer:t}:n.status==="error"?{status:"error",webId:n.webId,error:n.error,podUrl:e?.podUrl,issuer:t}:{status:"authenticated",webId:n.webId,podUrl:e?.podUrl,issuer:t}}async function discoverPodUrlFromWebId({webId:n,fetch:e}){const t=await fetchProfileStorageUrls(e,n);if(t.length!==1)throw new Error(t.length===0?"WebID profile does not declare a Solid storage URL":"WebID profile declares multiple Solid storage URLs; choose an explicit storage");return ensureTrailingSlash(new URL(t.at(0)).toString())}function createXpodSolidRuntimeValue(n={}){const e=createXpodSolidRuntimeStoragePolicy(n.storage);let t=[];const i=createSolidLocalRouteFetch({fetch:globalThis.fetch,routes:()=>t}),s=n.sessionFactory?.({fetch:i})??createInruptSession(e.oidcSession,i);let o=readStoredOidcIssuer(e.issuer);const l=createSolidSessionRuntime({session:s}),u=createPodRuntime({adapter:{discoverPod:discoverPodUrlFromWebId,openDatabase:({podUrl:h,fetch:d})=>drizzle({get info(){return s.info},fetch:d},{podUrl:h,schema:{aiProvider:aiProviderResource,credential:credentialResource},resourcePreparation:"off"}),hydrateCollections:()=>{}}});return{session:l,pod:u,storage:e,getIssuer:()=>readIssuerFromSessionInfo(s.info)??o??readStoredOidcIssuer(e.issuer),getExpectedIssuer:()=>o??expectedSameOriginIssuer(readIssuerFromSessionInfo(s.info)),setIssuer:h=>{const d=normalizeXpodOidcIssuer(h);o=d,d&&writeStoredOidcIssuer(d,e.issuer)},setLocalPodRoute:h=>{t=h?[h,...["/api/","/v1/","/.notifications/"].map(d=>({canonicalBaseUrl:new URL(d,h.canonicalBaseUrl).href,localBaseUrl:new URL(d,h.localBaseUrl).href}))]:[]},resolveLocalUrl:h=>resolveSolidLocalRouteUrl(h,t)?.href??h}}function createInruptSession(n=getOptionalPersistentStorage$1(),e=globalThis.fetch){return new Session({fetch:e,...n?{secureStorage:new InMemoryStorage,insecureStorage:toInruptStorage(n,"insecure")}:{}})}function toInruptStorage(n,e){const t=i=>inruptStorageKey(e,i);return{get:async i=>n.getItem(t(i))??void 0,set:async(i,s)=>{n.setItem(t(i),s)},delete:async i=>{n.removeItem(t(i))}}}function inruptStorageKey(n,e){return`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${n}:${e}`}let defaultRuntime;function getXpodSolidRuntimeValue(){return defaultRuntime??=createXpodSolidRuntimeValue(),defaultRuntime}function withXpodProvisionScope(n,e){const t=new URL(n);return e?.trim()&&t.searchParams.set("provisionCode",e.trim()),t.toString()}async function resolveXpodLoginContext(n,e){const t=await e("/provision/status",{headers:{Accept:"application/json"},credentials:"include"}).catch(()=>{});if(t?.status===404)return{oidcIssuer:normalizeXpodOidcIssuer(n)};const i=t?.ok?await t.json().catch(()=>{}):void 0,s=normalizeXpodOidcIssuer(i?.oidcIssuer);if(i?.managed===!1)return{oidcIssuer:s??normalizeXpodOidcIssuer(n)};const o=typeof i?.provisionCode=="string"&&i.provisionCode.trim()?i.provisionCode.trim():void 0;if(!s||i?.managed===!0&&!o)throw new Error("暂时无法确认本机登录信息,请稍后重试。");return{oidcIssuer:s,provisionCode:o}}function safeAuthError(n){if(n.name==="SolidSessionPendingError"){const e=new Error("上次登录尚未结束,请刷新页面后重新登录。");return e.name=n.name,e}return n.message==="Solid session expired"?n:new Error("Solid login failed. Please reconnect your Pod.")}function normalizeXpodLoginTransaction(n,e=typeof window>"u"?"http://localhost":window.location.origin){if(!n||typeof n!="object")throw new TypeError("Xpod login requires a validated WebID transaction");const t=normalizeWebIdLoginTransaction(n),i=assertXpodLoginRoute(t.route,e),s=normalizeXpodReturnTo(t.returnTo);return{...t,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}function useXpodSolidRuntimeContext(){const n=reactExports.useContext(XpodSolidRuntimeContext);if(!n)throw new Error("useXpodSolidRuntime must be used within XpodSolidRuntimeProvider");return n}function readIssuerFromSessionInfo(n){const e=n.issuer??n.oidcIssuer;return normalizeXpodOidcIssuer(e)}function normalizeXpodOidcIssuer(n){if(!(typeof n!="string"||!n.trim()))try{const e=new URL(n.trim());return e.protocol!=="https:"&&e.protocol!=="http:"||e.username||e.password||e.search||e.hash?void 0:e.toString()}catch{return}}function isCurrentXpodSessionSnapshot(n,e,t){if(n.status!=="authenticated")return!0;const i=normalizeXpodOidcIssuer(e),s=normalizeXpodOidcIssuer(t);return!i||!s||i!==s?!1:isHttpResourceUrl(n.webId)}function expectedSameOriginIssuer(n,e=typeof window>"u"?"http://localhost":window.location.origin){const t=normalizeXpodOidcIssuer(n);return t&&hasOrigin(t,e)?t:void 0}function hasOrigin(n,e){try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function isHttpResourceUrl(n){try{const e=new URL(n);return(e.protocol==="https:"||e.protocol==="http:")&&!e.username&&!e.password}catch{return!1}}function readStoredOidcIssuer(n=getOptionalPersistentStorage$1()){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$1()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalSessionStorage$1()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY)}catch{}}function writeStoredOidcIssuer(n,e=getOptionalPersistentStorage$1()){try{e?.setItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY,n)}catch{}}function createXpodSolidRuntimeStoragePolicy(n={}){const e=getOptionalPersistentStorage$1();return{oidcSession:n.oidcSession??e,issuer:n.issuer??e,selectedStorage:n.selectedStorage??e}}function getOptionalPersistentStorage$1(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getOptionalSessionStorage$1(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}const useXpodSolidRuntime=useXpodSolidRuntimeContext;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";function optionalPersistentStorage(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function readRememberedXpodLogin(n={}){const e=n.storage??optionalPersistentStorage();if(e)try{const t=e.getItem(XPOD_REMEMBERED_LOGIN_KEY);if(!t)return;const i=normalizeRememberedXpodLogin(JSON.parse(t),n.origin??currentOrigin());return i||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),i}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(n,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const i=normalizeRememberedXpodLogin(n,e.origin??currentOrigin());if(i)try{return t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(i)),t.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function clearRememberedXpodLogin(n=optionalPersistentStorage()){try{n?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(n,e){if(!n||!e.webId||!e.selectedStorage)return!1;const t=validatedWebId(n.webId),i=validatedWebId(n.storageBinding.webId),s=normalizedUrl(n.storageBinding.storageUrl,!0),o=validatedWebId(e.webId),l=validatedWebId(e.selectedStorage.webId),u=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!i||!s||!o||!l||!u||t!==i||o!==l||t!==o||s!==u?!1:rememberedXpodAccountMatchesActive(n,e)}function rememberedXpodAccountMatchesActive(n,e){return n?matchingOptionalEmail(n.account.email,e.accountEmail):!1}function rememberPendingXpodAccountEmail(n,e=optionalPersistentStorage(),t){const i=normalizedEmail(n);if(!(!e||!i))try{return e.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,i),t?e.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,normalizedIssuer(t)):e.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function readPendingXpodAccountEmail(n=optionalPersistentStorage(),e){if(n)try{const t=normalizedEmail(n.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const i=n.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!i||i!==normalizedIssuer(e)){n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}}return t||n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t}catch{return}}function normalizedIssuer(n){try{const e=currentOrigin();return e?new URL(n,e).origin:new URL(n).origin}catch{return n.trim()}}function normalizeRememberedXpodLogin(n,e){if(!n||typeof n!="object")return;const t=n;if(t.routeId!==XPOD_LOGIN_ROUTE_ID||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const i=t.account,s=t.storageBinding,o=normalizedEmail(i.email),l=validatedWebId(t.webId),u=validatedWebId(s.webId),h=normalizedUrl(s.storageUrl,!0);if(i.email!==void 0&&!o||!l||!u||!h||l!==u)return;const d=normalizedAvatarUrl(i.avatarUrl,[l,h,e]);return{account:{...o?{email:o}:{},...normalizedText(i.id)?{id:normalizedText(i.id)}:{},...normalizedText(i.username)?{username:normalizedText(i.username)}:{},...normalizedText(i.displayName)?{displayName:normalizedText(i.displayName)}:{},...d?{avatarUrl:d}:{}},webId:l,storageBinding:{webId:l,storageUrl:h},routeId:XPOD_LOGIN_ROUTE_ID}}function normalizedEmail(n){if(typeof n!="string")return;const e=n.trim();return e&&e.length<=320&&e.includes("@")?e:void 0}function normalizedText(n){if(typeof n!="string")return;const e=n.replace(/\s+/g," ").trim();return e?Array.from(e).slice(0,160).join(""):void 0}function validatedWebId(n){return typeof n=="string"&&!hasInvalidWebIdWhitespace(n)&&normalizedUrl(n)?n:void 0}function normalizedUrl(n,e=!1){if(!(typeof n!="string"||n.length>2048))try{const t=new URL(n);return t.username||t.password||t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(e&&(t.hash="",t.pathname.endsWith("/")||(t.pathname+="/")),t.href)}catch{return}}function normalizedAvatarUrl(n,e){const t=normalizedUrl(n);if(!t)return;const i=new URL(t).origin;return e.some(s=>{const o=normalizedUrl(s);return o&&new URL(o).origin===i})?t:void 0}function matchingOptionalEmail(n,e){const t=normalizedEmail(n)?.toLowerCase(),i=normalizedEmail(e)?.toLowerCase();return!t||!i||t===i}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}function XpodRememberedLoginBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.selectedStorage,i=useXpodProfileCardIdentity({accountIdentity:n.identity,runtime:e}),s=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,o=readRememberedXpodLogin(),l=readPendingXpodAccountEmail(),u=l??o?.account.email;return reactExports.useEffect(()=>{!s||!t||!e.currentPod||t.webId===s&&(e.currentPod.webId!==s||e.currentPod.podUrl!==t.storageUrl||o&&!rememberedXpodLoginMatchesActive(o,{accountIdentity:n.identity,accountEmail:l,webId:s,selectedStorage:t})||rememberXpodLogin({account:{...u?{email:u}:{},...n.identity??{},displayName:i.displayName,...i.username?{username:i.username}:{},...i.avatarSourceUrl??o?.account.avatarUrl?{avatarUrl:i.avatarSourceUrl??o?.account.avatarUrl}:{}},webId:s,storageBinding:t,routeId:XPOD_LOGIN_ROUTE_ID}))},[n.identity,u,l,i.displayName,i.avatarSourceUrl,i.username,o,e.currentPod,t,s]),null}function accountInteractionBase(n=typeof window>"u"?"/.account/":window.location.pathname){return/^\/\.account\/interaction\/[^/]+(?=\/|$)/u.exec(n)?.[0]??"/.account"}function scopeAccountUrl(n,e=typeof window>"u"?void 0:window.location){const t=String(n);if(!e)return t;const i=accountInteractionBase(e.pathname);if(i==="/.account")return t;const s=new URL(t,e.href);return s.origin!==e.origin||!s.pathname.startsWith("/.account/")||s.pathname.startsWith("/.account/interaction/")?t:(s.pathname=`${i}${s.pathname.slice(9)}`,t.startsWith("/")&&!t.startsWith("//")?`${s.pathname}${s.search}${s.hash}`:s.href)}const CSS_ACCOUNT_COOKIE_NAME="css-account",CSS_ACCOUNT_TOKEN_STORAGE_KEY="xpod.cssAccountToken",CSS_ACCOUNT_AUTHORITY_STORAGE_KEY="xpod.cssAccountAuthority",CSS_ACCOUNT_AUTH_SCHEME="CSS-Account-Token";function isBrowser(){return typeof window<"u"&&typeof document<"u"}function readCssAccountCookie(){if(!isBrowser())return;const n=document.cookie.split(";");for(const e of n){const[t,...i]=e.trim().split("=");if(t===CSS_ACCOUNT_COOKIE_NAME){const s=i.join("=");try{return s?decodeURIComponent(s):void 0}catch{return}}}}function writeCssAccountCookie(n){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=${encodeURIComponent(n)}; Path=/; SameSite=Lax`)}function clearCssAccountCookie(){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=; Path=/; SameSite=Lax; Max-Age=0`)}function clearLegacyStoredToken(){if(!(typeof window>"u")){try{window.localStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}try{window.sessionStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}}}function bindAccountSessionAuthority(n){if(!isBrowser())return!1;const e=normalizeAccountAuthority(n),t=window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY),i=t!==null?t!==e:new URL(e).origin!==window.location.origin;return window.localStorage.setItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY,e),i&&clearAccountSessionToken(),i}function normalizeAccountAuthority(n){const e=new URL(n,window.location.origin);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.pathname!=="/.account/"||e.search||e.hash)throw new Error("Invalid Account authority");return e.href}function storeAccountSessionToken(n){!n||readCssAccountCookie()===n||writeCssAccountCookie(n)}function clearAccountSessionToken(){clearLegacyStoredToken(),clearCssAccountCookie()}function getAccountSessionToken(){return readCssAccountCookie()}function accountTokenHeaders(n,e={Accept:"application/json"}){const t={...e};return n&&!hasHeader(t,"Authorization")&&(t.Authorization=`${CSS_ACCOUNT_AUTH_SCHEME} ${n}`),t}function storedAccountTokenHeaders(n={Accept:"application/json"},e){if(e)try{if(window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY)!==normalizeAccountAuthority(e))return{...n}}catch{return{...n}}return accountTokenHeaders(getAccountSessionToken(),n)}function hasHeader(n,e){const t=e.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===t)}let cachedRoute,cachedRouteOrigin;function resolveSameOriginAccountControlUrl(n){if(typeof window>"u"||typeof n!="string"||!n.trim())return;const e=n.trim();try{const t=new URL(e,window.location.origin);return t.origin!==window.location.origin||!["http:","https:"].includes(t.protocol)||t.username||t.password?void 0:scopeAccountUrl(t)}catch{return}}async function resolveHostedAccountControlUrl(n,e=fetch,t){if(typeof window>"u"||typeof n!="string"||!n.trim())return;if(t)try{const d=new URL(t,window.location.origin),p=new URL(n.trim(),d);if(p.origin===d.origin&&d.pathname.startsWith("/.account/")&&p.pathname.startsWith("/.account/")&&["http:","https:"].includes(p.protocol)&&!p.username&&!p.password)return scopeAccountUrl(p)}catch{}const i=resolveSameOriginAccountControlUrl(n);if(i)return i;let s;try{s=new URL(n)}catch{return}if(!["http:","https:"].includes(s.protocol)||s.username||s.password||!s.pathname.startsWith("/.account/"))return;if(cachedRoute&&cachedRouteOrigin===window.location.origin){const d=resolveSolidLocalRouteUrl(s,[cachedRoute]);if(d)return scopeAccountUrl(d)}const o={localBaseUrl:`${window.location.origin}/`,statusUrl:new URL("/provision/status",window.location.origin).href},l=await Promise.resolve(e.call(globalThis,o.statusUrl,{credentials:"include",headers:{accept:"application/json"}})).catch(()=>{}),u=l?await discoverSolidLocalRoute({...o,fetch:async()=>l.clone()}):void 0;u&&(cachedRoute=u,cachedRouteOrigin=window.location.origin);const h=u?resolveSolidLocalRouteUrl(s,[u]):void 0;return h?scopeAccountUrl(h):void 0}const LOCAL_ACCOUNT_INDEX$1="/.account/";function isProvisionStatusResponse(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}async function resolveXpodAccountIndex(n=fetch){if(typeof window>"u")return LOCAL_ACCOUNT_INDEX$1;if(!isLoopbackHostname$1(window.location.hostname)){const i=window.__XPOD__?.idpIndex;if(i!==void 0){try{const s=new URL(i,window.location.origin);if(typeof i=="string"&&i.trim()&&["http:","https:"].includes(s.protocol)&&s.pathname===LOCAL_ACCOUNT_INDEX$1&&!s.username&&!s.password&&!s.search&&!s.hash)return unregisterLocalProvisionResolver(),s.href}catch{}throw new Error("Server bootstrap did not expose a valid Account index")}}const e=await n(new URL("/provision/status",window.location.origin),{credentials:"include",headers:{accept:"application/json"}});if(e.status===404)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(!e.ok)throw new Error(`Local provisioning status request failed (${e.status})`);let t;try{t=await e.json()}catch{throw new Error("Local provisioning status response was not valid JSON")}if(!isProvisionStatusResponse(t)||typeof t.managed!="boolean")throw new Error("Local provisioning status response was not valid");if(t.managed===!1)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(typeof t.oidcIssuer=="string")try{const i=new URL(t.oidcIssuer);if(["http:","https:"].includes(i.protocol)&&!i.username&&!i.password)return installLocalProvisionResolver(n),typeof t.provisionCode=="string"&&setStoredProvisionCode(t.provisionCode),new URL(LOCAL_ACCOUNT_INDEX$1,i).href}catch{}throw new Error("Local provisioning status did not expose a valid OIDC issuer")}function installLocalProvisionResolver(n){const e=new URL("/provision/status",window.location.origin);registerLocalProvisionResolver(async()=>{const t=await n(e,{credentials:"include",headers:{accept:"application/json"}}),i=t.ok?await t.json().catch(()=>{}):void 0;if(i?.managed!==!0||i?.registered!==!0||typeof i?.provisionCode!="string")throw new Error(CLOUD_PROVISIONING_UNAVAILABLE);return i.provisionCode})}function isLoopbackHostname$1(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}const LOCAL_ACCOUNT_INDEX="/.account/",ACCOUNT_ERROR_MESSAGE="Xpod 登录服务暂时不可用,请稍后重试。",ACCOUNT_CONTROLS_RETRY_DELAYS_MS=[250,750,1500],ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS=300,OIDC_PENDING_PROBE_TIMEOUT_MS=3e3;function isAccountSpaPath(){if(typeof window>"u")return!1;const n=window.location.pathname;return n==="/.account"||n.startsWith("/.account/")}function accountIdentityFromControls(n){const e=n?.account;if(!e)return;const t={...typeof e.id=="string"?{id:e.id}:{},...typeof e.username=="string"?{username:e.username}:{},...typeof e.displayName=="string"?{displayName:e.displayName}:{}};return Object.keys(t).length>0?t:void 0}function accountStateForControls(n){return n?.account?.logout?{status:"authenticated"}:{status:"anonymous",mode:"login"}}function isTransientAccountControlsStatus(n){return n===502||n===503||n===504}function transientAccountState(n){return n?{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}:{status:"initializing"}}function wait(n){return new Promise(e=>setTimeout(e,n))}function AuthProvider({children:n}){const[e,t]=reactExports.useState(),[i,s]=reactExports.useState(null),[o,l]=reactExports.useState(!0),[u,h]=reactExports.useState(null),[d,p]=reactExports.useState(!1),[g,m]=reactExports.useState({status:"initializing"}),v=reactExports.useRef(0),S=reactExports.useRef(!0),E=reactExports.useRef(0),x=reactExports.useRef(void 0),A=reactExports.useRef(null),C=reactExports.useRef(void 0),T=reactExports.useRef(0),F=reactExports.useRef(0),P=reactExports.useRef(!1),q=reactExports.useCallback(()=>{const te=A.current?.account;return te?.logout?JSON.stringify([x.current,te.id,te.logout,te.clientCredentials]):void 0},[]),O=reactExports.useCallback(()=>{T.current+=1,P.current=!0},[]),G=reactExports.useCallback((te,Te)=>{const je=q(),He=C.current;A.current=te,C.current=Te,(je!==q()||He!==Te)&&O(),P.current=!q()},[q,O]),fe=reactExports.useCallback(()=>{const te=q(),Te=T.current,je=getAccountSessionToken();let He=!!te&&je===C.current&&!P.current&&F.current===0;return()=>{if(!He||!S.current||P.current||F.current>0||Te!==T.current||te!==q()||je!==getAccountSessionToken())throw He=!1,new Error("Account 登录状态已改变,请重新打开客户端凭据操作。")}},[q]),M=g.status==="authenticated",ee=o||g.status==="submitting",Se=reactExports.useRef(!1),re=reactExports.useCallback(te=>{(bindAccountSessionAuthority(te)||x.current&&x.current!==te)&&(E.current+=1,v.current+=1,Se.current=!1,G(null),s(null),p(!1),m({status:"initializing"})),x.current=te,t(te)},[G]),Ae=reactExports.useCallback(async()=>{l(!0),h(null),m(te=>te.status==="authenticated"?te:{status:"initializing"});try{const te=await resolveXpodAccountIndex();return S.current?(re(te),te):void 0}catch{if(!S.current)return;G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1);return}},[re,G]);reactExports.useEffect(()=>{let te=!0;return resolveXpodAccountIndex().then(Te=>{te&&S.current&&re(Te)}).catch(()=>{!te||!S.current||(G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1))}),()=>{te=!1}},[re,G]),reactExports.useEffect(()=>(S.current=!0,()=>{S.current=!1,O(),E.current+=1}),[O]);const ke=reactExports.useCallback(te=>S.current&&te===E.current,[]),he=reactExports.useCallback(async()=>{const te=new AbortController,Te=setTimeout(()=>te.abort(),OIDC_PENDING_PROBE_TIMEOUT_MS);try{const je=x.current;if(!je)return!1;const He=await fetch(scopeAccountUrl(new URL("oidc/consent/",je)),{headers:storedAccountTokenHeaders(void 0,je),credentials:"include",signal:te.signal});return He.ok?!!(await He.json()).client:!1}catch{return!1}finally{clearTimeout(Te)}},[]),Oe=reactExports.useCallback(async({exposeTransientError:te,generation:Te,confirmUnauthenticated:je})=>{const He=x.current;if(!He)return"stale";const We=getAccountSessionToken(),me=()=>We===getAccountSessionToken()?!0:(O(),!1);try{const ge=await fetch(scopeAccountUrl(He),{headers:storedAccountTokenHeaders(void 0,He),credentials:"include"});if(!ke(Te))return"stale";if(!me())return"transient-error";if(ge.ok){const Be=await ge.json();if(!ke(Te))return"stale";if(!me())return"transient-error";if(!Be?.controls||typeof Be.controls!="object"||Array.isArray(Be.controls))throw new Error("Invalid CSS Account controls response");const ie=Be.controls,B=++v.current;p(!1),G(ie,We),s(ie),h(null);const N=accountStateForControls(ie);return Se.current=N.status==="anonymous",m(N),ie.account?.logout&&isAccountSpaPath()&&he().then(k=>{ke(Te)&&B===v.current&&p(k)}),"ok"}else{if(ge.status===401||ge.status===403)return je?(v.current+=1,clearAccountSessionToken(),Se.current=!0,p(!1),G({}),s({}),m({status:"anonymous",mode:"login"}),h(null),"ok"):"unauthenticated";if(v.current+=1,p(!1),isTransientAccountControlsStatus(ge.status))return h(null),m(ie=>ie.status==="authenticated"?ie:transientAccountState(te)),"transient-error";O();const Be=`Failed to load account controls (Status: ${ge.status})`;return h(Be),m({status:"error",mode:"login",message:Be}),"terminal-error"}}catch{return ke(Te)?(v.current+=1,p(!1),h(null),m(ge=>ge.status==="authenticated"?ge:transientAccountState(te)),"transient-error"):"stale"}},[G,he,ke,O]),ce=reactExports.useCallback(async()=>{const te=++E.current;for(let Te=0;Te<=ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length;Te+=1){const je=Te===ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length,He=await Oe({exposeTransientError:je,generation:te});if(He==="unauthenticated")return!ke(te)||(await wait(ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS),!ke(te))?"stale":Oe({exposeTransientError:!0,generation:te,confirmUnauthenticated:!0});if(He!=="transient-error")return He;if(!ke(te)||!je&&(m(We=>We.status==="authenticated"?We:{status:"initializing"}),await wait(ACCOUNT_CONTROLS_RETRY_DELAYS_MS[Te]),!ke(te)))return"stale"}return"transient-error"},[Oe,ke]);reactExports.useEffect(()=>{if(!e)return;let te=!0;return(async()=>(await ce(),te&&S.current&&l(!1)))(),()=>{te=!1}},[ce,e]);const Ue=reactExports.useCallback(async()=>{const te=await Ae();if(te&&te===e){const Te=await ce();if(S.current&&l(!1),Te==="ok")return accountStateForControls(A.current)}return{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}},[ce,e,Ae]),$=reactExports.useCallback(async()=>{await Ue()},[Ue]),W=reactExports.useCallback(async()=>{F.current+=1;try{O(),E.current+=1,v.current+=1,A.current?.account?.logout||(Se.current=!1,(x.current??await Ae())&&await ce());const te=x.current,Te=A.current?.account?.logout,je=await resolveHostedAccountControlUrl(Te,fetch,te);let He=!je&&(!!Te||!Se.current);if(je)try{const We=await fetch(scopeAccountUrl(je),{method:"POST",headers:storedAccountTokenHeaders(void 0,te),credentials:"include"});He=!We.ok&&We.status!==401&&We.status!==403}catch{He=!0}if(He){m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE});return}E.current+=1,v.current+=1,Se.current=!0,l(!1),clearAccountSessionToken(),p(!1),G({}),s({}),h(null),m({status:"anonymous",mode:"login"})}finally{F.current-=1}},[G,ce,Ae,O]),de=reactExports.useMemo(()=>accountIdentityFromControls(i),[i]);return jsxRuntimeExports.jsx(AuthContext.Provider,{value:{controls:i,isInitializing:o,initError:u,idpIndex:e??LOCAL_ACCOUNT_INDEX,isLoggedIn:M,isAnonymous:()=>Se.current,bindAccountCapability:fe,authenticating:ee,hasOidcPending:d,refetchControls:Ue,retry:$,logout:W,accountState:g,identity:de},children:n})}const MAX_LABEL_CODE_POINTS=80,MAX_IDENTITY_URL_LENGTH=2048;function XpodDesktopIdentityBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,i=e.state.status==="authenticated"?e.currentPod?.podUrl??e.podUrl??e.state.podUrl:void 0,s=reactExports.useMemo(()=>projectDesktopIdentity({isLoggedIn:n.isLoggedIn,displayName:n.identity?.displayName,username:n.identity?.username,webId:t,podUrl:i}),[n.identity?.displayName,n.identity?.username,n.isLoggedIn,i,t]);return reactExports.useEffect(()=>{globalThis.xpodDesktop?.setIdentity(s)},[s]),reactExports.useEffect(()=>()=>{globalThis.xpodDesktop?.setIdentity(null)},[]),null}function projectDesktopIdentity({isLoggedIn:n,displayName:e,username:t,webId:i,podUrl:s}){if(!n)return null;const o=sanitizeLabel(e)??sanitizeLabel(t)??"Xpod Account",l=sanitizeCurrentXpodUrl(i),u=sanitizeCurrentXpodUrl(s);return{label:o,...l?{webId:l}:{},...u?{podUrl:u}:{}}}function sanitizeLabel(n){if(!n)return;const t=Array.from(n,i=>{const s=i.codePointAt(0);return isUnsafeLabelCodePoint(s)?" ":i}).join("").replace(/\s+/g," ").trim();if(t)return Array.from(t).slice(0,MAX_LABEL_CODE_POINTS).join("").trim()}function isUnsafeLabelCodePoint(n){return n<32||n>=127&&n<=159||n>=8234&&n<=8238||n>=8294&&n<=8297}function sanitizeCurrentXpodUrl(n){if(!(!n||n.length>MAX_IDENTITY_URL_LENGTH))try{const e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password||!isCurrentXpodOrigin(e)?void 0:e.toString()}catch{return}}function isCurrentXpodOrigin(n){const e=globalThis.window?.location;return e?n.origin===e.origin?!0:n.protocol===e.protocol&&n.port===e.port&&isLoopbackHostname(n.hostname)&&isLoopbackHostname(e.hostname):!1}function isLoopbackHostname(n){const e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}function XpodServiceAvailability({children:n}){const[e,t]=reactExports.useState(!1),i=reactExports.useRef(()=>{}),s=reactExports.useRef(null);return reactExports.useEffect(()=>{if(!e)return;const o=document.activeElement;return s.current?.focus(),()=>{o instanceof HTMLElement&&o.isConnected&&o.focus()}},[e]),reactExports.useEffect(()=>{let o=!1,l,u,h=0;async function d(){if(o||l)return;clearTimeout(u);const g=new AbortController;l=g;const m=setTimeout(()=>g.abort(),5e3);let v=!0;try{const S=await fetch("/service/status",{cache:"no-store",signal:g.signal});if(v=S.status<500,S.ok){const E=await S.json().catch(()=>null);Array.isArray(E)&&(v=!E.some(x=>x&&["css","api"].includes(x.name)&&typeof x.status=="string"&&x.status!=="running")),g.signal.aborted&&(v=!1)}else await S.body?.cancel()}catch{v=!1}finally{clearTimeout(m),l=void 0}o||(h=v?0:h+1,t(!v),u=setTimeout(()=>{document.visibilityState!=="hidden"&&d()},v?1e4:Math.min(2e3*2**Math.min(h-1,4),3e4)))}const p=()=>{document.visibilityState!=="hidden"&&d()};return i.current=()=>{d()},window.addEventListener("online",p),window.addEventListener("focus",p),document.addEventListener("visibilitychange",p),d(),()=>{o=!0,clearTimeout(u),l?.abort(),i.current=()=>{},window.removeEventListener("online",p),window.removeEventListener("focus",p),document.removeEventListener("visibilitychange",p)}},[]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{style:{display:"contents"},inert:e||void 0,children:n}),e&&jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center bg-background/70 p-6 backdrop-blur-sm",children:jsxRuntimeExports.jsxs("section",{role:"alertdialog","aria-modal":"true","aria-labelledby":"xpod-connection-title","aria-describedby":"xpod-connection-description",className:"w-full max-w-sm rounded-2xl border bg-background p-6 shadow-lg",children:[jsxRuntimeExports.jsx("h2",{id:"xpod-connection-title",className:"text-lg font-semibold",children:"Xpod 连接中断"}),jsxRuntimeExports.jsx("p",{id:"xpod-connection-description",className:"mt-3 text-sm text-muted-foreground",children:"暂时无法连接 Xpod,正在自动重连。登录状态和当前页面已保留,恢复后即可继续。"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"刚才未完成的操作不会自动重试,请在连接恢复后确认结果。"}),jsxRuntimeExports.jsx("button",{ref:s,type:"button",onKeyDown:o=>{o.key==="Tab"&&o.preventDefault()},onClick:()=>i.current(),className:"mt-5 w-full rounded-lg bg-primary px-4 py-2 text-primary-foreground",children:"立即重试"})]})})]})}function XpodDesktopNavigationBridge(){const n=useNavigate();return reactExports.useEffect(()=>globalThis.xpodDesktop?.onNavigate?.(e=>{const t=new URL(e,window.location.origin);t.origin===window.location.origin&&n(`${t.pathname}${t.search}${t.hash}`)}),[n]),null}const XPOD_DEFAULT_RETURN_PATH="/ai-connections",LEGACY_DEFAULT_RETURN_PATH="/dashboard/overview",canonicalRoutes={status:"/status/overview",network:"/network",aiConnections:"/ai-connections",aiConfig:"/ai-config/model-assignments",settings:"/settings/pod"},legacyProductRedirects={"/dashboard":canonicalRoutes.status,[LEGACY_DEFAULT_RETURN_PATH]:canonicalRoutes.status,"/dashboard/network":canonicalRoutes.network,"/dashboard/models":canonicalRoutes.aiConnections,"/dashboard/pod":canonicalRoutes.settings,"/dashboard/services":canonicalRoutes.status,"/dashboard/settings":canonicalRoutes.settings,"/settings/models":canonicalRoutes.aiConnections,"/settings/ai-connections":canonicalRoutes.aiConnections,"/settings/ai-config":canonicalRoutes.aiConfig,"/settings/pod":canonicalRoutes.settings,"/settings/network":canonicalRoutes.network,"/settings/services":canonicalRoutes.status,"/settings/system":canonicalRoutes.settings};function canonicalProductPathname(n){return legacyProductRedirects[n]??n}const client_id="https://id.undefineds.co/app/xpod-desktop-client.json",desktopClient={client_id},XPOD_LOGIN_TRANSACTION_VERSION=1,XPOD_LOGIN_TRANSACTION_PREFIX="xpod.auth.transaction.v1",XPOD_LOGIN_TRANSACTION_TTL_MS=600*1e3,XPOD_SELECTED_STORAGE_BINDING_VERSION=1,XPOD_SELECTED_STORAGE_BINDING_KEY="xpod.auth.selected-storage.v1";class XpodLoginTransactionError extends Error{code;constructor(e,t){super(t),this.name="XpodLoginTransactionError",this.code=e}}function readXpodSelectedStorage(n={}){return n.storage?readXpodSelectedStorageFrom(n.storage,n):readXpodSelectedStorageFrom(getOptionalPersistentStorage(),n)??readXpodSelectedStorageFrom(getOptionalSessionStorage(),n)}function readXpodSelectedStorageFrom(n,e){if(!n)return;const t=n.getItem(XPOD_SELECTED_STORAGE_BINDING_KEY);if(!t)return;const i=()=>n.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);let s;try{s=JSON.parse(t)}catch{i();return}if(!isStoredSelectedStorageBinding(s)){i();return}const o=e.now??(()=>Date.now());if(s.expiresAt<=o()){i();return}let l;try{l=normalizeSelectedStorageBinding(s.binding,s.storageRoot??new URL(e.origin??getWindowOrigin()).origin,s.storageRoot===void 0)}catch{i();return}if(e.webId!==void 0&&l.webId!==e.webId){i();return}return l}function clearXpodSelectedStorage(n={}){n.storage?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);try{getOptionalPersistentStorage()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY),getOptionalSessionStorage()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY)}catch{}}function createOpaqueTransactionId(){const n=globalThis.crypto;if(typeof n?.randomUUID=="function")return n.randomUUID();if(typeof n?.getRandomValues=="function"){const e=new Uint8Array(24);return n.getRandomValues(e),`xpod-${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}throw new XpodLoginTransactionError("storage_unavailable","Secure transaction id generation is unavailable")}function createXpodLoginTransactionStore(n={}){const e=n.storage??getSessionStorage(),t=new URL(n.origin??getWindowOrigin()).origin,i=n.now??(()=>Date.now()),s=n.ttlMs??XPOD_LOGIN_TRANSACTION_TTL_MS,o=n.prefix??XPOD_LOGIN_TRANSACTION_PREFIX,l=`${o}.active`,u=m=>`${o}.record.${m}`,h=m=>`${o}.consumed.${m}`,d=m=>{e.getItem(l)===m&&e.removeItem(l),e.removeItem(u(m))},p=(m,v=!0)=>{if(!isSafeTransactionId(m))throw new XpodLoginTransactionError("malformed","Transaction id is malformed");if(e.getItem(h(m))==="1")throw new XpodLoginTransactionError("consumed","Transaction has already been consumed");if(v&&e.getItem(l)!==m)throw new XpodLoginTransactionError("unknown","Transaction is not the active Xpod login transaction");const S=e.getItem(u(m));if(!S)throw v&&e.getItem(l)===m&&e.removeItem(l),new XpodLoginTransactionError("unknown","Xpod login transaction was not found");let E;try{E=JSON.parse(S)}catch{throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}if(!isStoredTransaction(E)||E.transaction.id!==m)throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed");if(E.expiresAt<=i())throw d(m),new XpodLoginTransactionError("expired","Xpod login transaction has expired");try{const x=normalizePublicTransaction({...E.transaction,authorizationSurface:"redirect",discovery:"strict"},t);return E.transaction={id:x.id,route:x.route,...x.returnTo===void 0?{}:{returnTo:x.returnTo},...x.prompt===void 0?{}:{prompt:x.prompt},...x.selectedStorage===void 0?{}:{selectedStorage:x.selectedStorage}},E}catch(x){throw d(m),x instanceof XpodLoginTransactionError?x:new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}};return{begin:m=>{const v=e.getItem(l);if(v){try{p(v)}catch(T){if(!(T instanceof XpodLoginTransactionError&&(T.code==="expired"||T.code==="malformed"||T.code==="unknown")))throw T}if(e.getItem(l)===v)throw new XpodLoginTransactionError("already_active","An Xpod login transaction is already pending in this tab")}const S=isSafeTransactionId(m.id)?m.id:createOpaqueTransactionId(),E=normalizePublicTransaction({...m,id:S},t),x=i(),A=x+s,C={version:XPOD_LOGIN_TRANSACTION_VERSION,createdAt:x,expiresAt:A,transaction:{id:E.id,route:E.route,...E.returnTo===void 0?{}:{returnTo:E.returnTo},...E.prompt===void 0?{}:{prompt:E.prompt},...E.selectedStorage===void 0?{}:{selectedStorage:E.selectedStorage}}};return e.setItem(u(E.id),JSON.stringify(C)),e.setItem(l,E.id),E},readSinglePending(){const m=e.getItem(l);if(m)return materialize(p(m).transaction)},updateSelectedStorage(m,v){const S=p(m),E=materialize(S.transaction),x=normalizeBinding(v,t,E.route.storageProvider?.url),A={...S,transaction:{...S.transaction,selectedStorage:x}};e.setItem(u(m),JSON.stringify(A))},consume(m){const v=p(m),S=materialize(v.transaction);return e.removeItem(l),e.removeItem(u(m)),e.setItem(h(m),"1"),S},cancel(m){p(m),e.removeItem(l),e.removeItem(u(m)),e.setItem(h(m),"1")}}}function normalizePublicTransaction(n,e){let t;try{t=normalizeWebIdLoginTransaction(n)}catch(o){throw new XpodLoginTransactionError("malformed",o instanceof Error?o.message:"Transaction is malformed")}let i;try{i=assertXpodLoginRoute(t.route,e)}catch(o){throw new XpodLoginTransactionError("cross_origin",o instanceof Error?o.message:"Transaction route is not local")}let s;try{s=normalizeXpodReturnTo(t.returnTo)}catch(o){throw new XpodLoginTransactionError("mismatch",o instanceof Error?o.message:"Transaction return path is unsafe")}if(t.selectedStorage!==void 0)try{const o=normalizeBinding(t.selectedStorage,e,i.storageProvider?.url);return{id:t.id,route:i,selectedStorage:o,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}catch(o){throw o instanceof XpodLoginTransactionError?o:new XpodLoginTransactionError("mismatch","Selected storage binding is invalid")}return{id:t.id,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}function normalizeBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(i.origin!==e||s.origin!==e||t&&i.origin!==new URL(t).origin)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");if(i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("malformed","Selected storage binding contains unsafe URL data");return{storageUrl:i.href,webId:n.webId,...n.label===void 0?{}:{label:n.label}}}function materialize(n){return{id:n.id,route:n.route,authorizationSurface:"redirect",discovery:"strict",...n.returnTo===void 0?{}:{returnTo:n.returnTo},...n.prompt===void 0?{}:{prompt:n.prompt},...n.selectedStorage===void 0?{}:{selectedStorage:n.selectedStorage}}}function normalizeSelectedStorageBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(!urlBelongsToRoot(i,e)||t&&s.origin!==new URL(e).origin||i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");return{storageUrl:i.href,webId:n.webId}}function normalizeStorageRoot(n){const e=new URL(n);return e.hash="",e.search="",e.pathname.endsWith("/")||(e.pathname+="/"),e.href}function urlBelongsToRoot(n,e){const t=new URL(normalizeStorageRoot(e));if(n.origin!==t.origin)return!1;const i=t.pathname;return n.pathname===i.slice(0,-1)||n.pathname.startsWith(i)}function isSafeTransactionId(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{16,128}$/.test(n)}function isStoredTransaction(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_LOGIN_TRANSACTION_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.transaction&&typeof e.transaction=="object")}function isStoredSelectedStorageBinding(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_SELECTED_STORAGE_BINDING_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.binding&&typeof e.binding=="object")}function getSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}throw new XpodLoginTransactionError("storage_unavailable","Session storage is unavailable")}function getOptionalSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}function getOptionalPersistentStorage(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getWindowOrigin(){return typeof window<"u"&&window.location.origin!=="null"?window.location.origin:"http://localhost"}async function currentHostLocalPodRoute(n,e){if(typeof window>"u")return;const t=desktopLocalPodRoute(n);if(t)return t;if(storageUrlUsesCurrentOrigin(n))return;const i=await fetchCurrentProvisionRouteStatus(e);return currentProvisionLocalPodRoute(n,i)}function currentProvisionLocalPodRoute(n,e){if(!(typeof window>"u")&&!(e.managed!==!0||typeof e.storageRoot!="string")&&managedPublicRouteCoversStorage(n,e.storageRoot))return podScopedLocalRoute(n)}function desktopLocalPodRoute(n){if(!(typeof window>"u"||!window.xpodDesktop))return podScopedLocalRoute(n)}async function fetchCurrentProvisionRouteStatus(n){let e;try{e=await n(new URL("/provision/status",window.location.origin).href,{credentials:"include",headers:{accept:"application/json"}})}catch{return{}}if(!e.ok||!e.headers.get("content-type")?.includes("application/json"))return await e.arrayBuffer().catch(()=>{}),{};const t=await e.json().catch(()=>{});return{managed:t?.managed===!0,storageRoot:typeof t?.publicUrl=="string"?t.publicUrl:void 0}}function podScopedLocalRoute(n){try{const e=new URL(n),t=new URL(e.pathname,window.location.origin);return!["http:","https:"].includes(e.protocol)||e.username||e.password?void 0:(e.search="",e.hash="",t.search="",t.hash="",{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:t.href.endsWith("/")?t.href:`${t.href}/`})}catch{return}}function managedPublicRouteCoversStorage(n,e){try{const t=new URL(e),i=new URL(t.pathname,window.location.origin);return resolveSolidLocalRouteUrl(n,[{canonicalBaseUrl:t.href,localBaseUrl:i.href}])!==void 0}catch{return!1}}function storageUrlUsesCurrentOrigin(n){try{return new URL(n).origin===window.location.origin}catch{return!1}}function XpodSolidRuntimeProvider({children:n,value:e}){const t=e??getXpodSolidRuntimeValue(),i=reactExports.useMemo(()=>t.storage??{},[t]),s=reactExports.useMemo(()=>currentProviderSession(t),[t]),[o,l]=reactExports.useState(s.snapshot),[u,h]=reactExports.useState(s.issuer),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),[v,S]=reactExports.useState(),[E,x]=reactExports.useState(0),[A,C]=reactExports.useState(),T=reactExports.useRef(o),F=reactExports.useRef(s.rejected),P=reactExports.useRef(void 0),q=reactExports.useCallback(async(Ae,ke)=>F.current?Promise.reject(REJECTED_SESSION_FETCH_ERROR):ke===void 0?t.session.fetch(Ae):t.session.fetch(Ae,ke),[t.session]),O=reactExports.useMemo(()=>o.status==="authenticated"?t.session.createAuthenticatedFetch(o.webId):void 0,[t.session,o]),G=reactExports.useCallback(async(Ae,ke)=>{if(!O||F.current)throw REJECTED_SESSION_FETCH_ERROR;return ke===void 0?O(Ae):O(Ae,ke)},[O]),fe=reactExports.useCallback(()=>{if(P.current)return P.current;const Ae=(async()=>{try{await t.session.logout();const ke=t.session.getSnapshot();(ke.status!=="authenticated"||isCurrentXpodSessionSnapshot(ke,t.getIssuer(),t.getExpectedIssuer?.()??window.location.origin))&&(F.current=!1)}catch{}finally{const ke={status:"anonymous"};t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),t.setIssuer(void 0),T.current=ke,l(ke),h(void 0),p(void 0),m(void 0),S(void 0),C(void 0)}})().finally(()=>{P.current===Ae&&(P.current=void 0)});return P.current=Ae,Ae},[t,i.issuer,i.selectedStorage]),M=reactExports.useMemo(()=>({...t.session,fetch:q,getSnapshot:()=>T.current}),[q,t.session]);reactExports.useEffect(()=>{const Ae=he=>{const Oe=t.getIssuer();if(!isCurrentXpodSessionSnapshot(he,Oe,t.getExpectedIssuer?.()??window.location.origin)){F.current=!0,fe();return}he.status==="authenticated"&&(F.current=!1);const ce=T.current;T.current=he,l(he),h(Oe),he.status!=="authenticated"?(t.setLocalPodRoute?.(void 0),p(void 0),he.status!=="expired"&&m(void 0),S(void 0),C(void 0),t.pod.clear()):ce!==he&&(p(void 0),m(void 0),S(void 0),C(void 0),t.pod.clear(ce.status==="authenticated"?{webId:ce.webId}:void 0))},ke=t.session.subscribe(Ae);return Ae(t.session.getSnapshot()),ke},[fe,t,i]),reactExports.useEffect(()=>{F.current&&fe()},[fe]),reactExports.useEffect(()=>{if(o.status!=="authenticated")return;let Ae=!1;const ke=readXpodSelectedStorage({storage:i.selectedStorage,origin:typeof window>"u"?void 0:window.location.origin,webId:o.webId}),he={webId:o.webId,...ke?{podUrl:ke.storageUrl}:{},fetch:G};return(async()=>{try{const Oe=await t.pod.open(he),ce=await currentHostLocalPodRoute(Oe.podUrl,fetch);if(Ae)return;if(t.setLocalPodRoute?.(ce),!Ae){if(ke&&(Oe.webId!==ke.webId||!sameUrl$2(Oe.podUrl,ke.storageUrl))){clearXpodSelectedStorage({storage:i.selectedStorage}),p(void 0),m(void 0),S({webId:o.webId,error:new Error("Selected Pod binding mismatch")});return}p(Oe),m(ke??{webId:Oe.webId,storageUrl:Oe.podUrl}),S(void 0)}}catch(Oe){Ae||S({webId:o.webId,error:Oe instanceof Error?Oe:new Error(String(Oe))})}})(),()=>{Ae=!0}},[G,E,t,i.selectedStorage,o]);const ee=reactExports.useCallback(()=>{S(void 0),x(Ae=>Ae+1)},[]),Se=o.status==="authenticated"?o.webId:void 0;reactExports.useEffect(()=>{if(!Se)return;let Ae=!1;return discoverAiClientConfigurationCapability(G).then(ke=>{!Ae&&t.session.getSnapshot().status==="authenticated"&&t.session.getSnapshot().webId===Se&&C(ke)}),()=>{Ae=!0}},[G,Se,t]);const re=reactExports.useMemo(()=>{const Ae=u??t.getIssuer(),ke=o.status==="authenticated"&&v?.webId===o.webId?v:void 0,he=snapshotToState(o,d,Ae);return{session:M,pod:t.pod,fetch:G,state:he.status==="error"?{...he,error:safeAuthError(he.error)}:he,webId:he.webId,podUrl:he.podUrl,issuer:he.issuer,currentPod:d,selectedStorage:g,...ke?{podError:ke}:{},retryPodOpen:ee,aiClientConfiguration:A,resolveLocalUrl:Oe=>t.resolveLocalUrl(Oe),login:async Oe=>{const ce=normalizeXpodLoginTransaction(Oe),Ue=await resolveXpodLoginContext(ce.route.identityProvider.url,fetch),$=Ue.oidcIssuer;if(!$)throw new TypeError("Xpod login route has no valid issuer");const W=new URL("/auth/callback",window.location.origin),de=globalThis.xpodDesktop?desktopClient.client_id:void 0;try{await t.session.login({...de?{clientId:de}:{},oidcIssuer:$,redirectUrl:W.toString(),handleRedirect:te=>{t.setIssuer($),h($);const Te=new URL(te);ce.prompt?Te.searchParams.set("prompt",ce.prompt):de&&Te.searchParams.get("prompt")==="consent"&&Te.searchParams.delete("prompt"),window.location.assign(Ue.provisionCode?withXpodProvisionScope(Te.href,Ue.provisionCode):Te.href)}}),t.setIssuer($),h($)}catch(te){throw console.error("[XpodSolidRuntimeProvider] WebID login failed",te,te instanceof Error?te.cause:void 0),te}},logout:async()=>{await t.session.logout(),t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),p(void 0),m(void 0),C(void 0)}}},[A,G,d,M,u,v,ee,t,i,g,o]);return jsxRuntimeExports.jsx(SolidRuntimeProvider,{value:{session:M,pod:t.pod,currentPod:d},children:jsxRuntimeExports.jsx(XpodSolidRuntimeContext.Provider,{value:re,children:n})})}const ANONYMOUS_SNAPSHOT={status:"anonymous"},REJECTED_SESSION_FETCH_ERROR=new Error("Xpod session is unavailable");function currentProviderSession(n){const e=n.session.getSnapshot(),t=n.getIssuer();return isCurrentXpodSessionSnapshot(e,t,n.getExpectedIssuer?.()??window.location.origin)?{snapshot:e,issuer:t,rejected:!1}:{snapshot:ANONYMOUS_SNAPSHOT,issuer:void 0,rejected:!0}}function sameUrl$2(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}async function discoverAiClientConfigurationCapability(n){try{const e=new URL("/api/ai/client-configuration/capability",window.location.href).toString(),t=await n(e,{method:"GET",credentials:"include",headers:{accept:"application/json"}});if(!t.ok||!t.headers.get("content-type")?.includes("application/json"))return await t.arrayBuffer().catch(()=>{}),manualAiClientConfigurationCapability();const i=await t.json();if(isRecord(i)&&i.available===!0&&i.authority==="local-filesystem")return{available:!0,authority:"local-filesystem",manualInstructions:typeof i.manualInstructions=="string"?i.manualInstructions:manualAiClientConfigurationCapability().manualInstructions}}catch{}return manualAiClientConfigurationCapability()}function manualAiClientConfigurationCapability(){return{available:!1,manualInstructions:"manual client setup is available"}}function isRecord(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}const XPOD_THEME_STORAGE_KEY="xpod.theme",XPOD_THEME_MEDIA_QUERY="(prefers-color-scheme: dark)";function readXpodThemePreference(n=optionalLocalStorage()){try{const e=n?.getItem(XPOD_THEME_STORAGE_KEY);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function resolveXpodTheme(n,e=systemThemeMedia()){return n!=="system"?n:e?.matches?"dark":"light"}function applyXpodTheme(n,e=typeof document>"u"?void 0:document.documentElement){e&&(e.classList.toggle("light",n==="light"),e.classList.toggle("dark",n==="dark"),e.dataset.theme=n,e.style.colorScheme=n)}function initializeXpodTheme(){const n=readXpodThemePreference(),e=resolveXpodTheme(n);return applyXpodTheme(e),{preference:n,resolvedTheme:e}}function systemThemeMedia(){return typeof window>"u"||typeof window.matchMedia!="function"?void 0:window.matchMedia(XPOD_THEME_MEDIA_QUERY)}function optionalLocalStorage(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}const XpodThemeContext=reactExports.createContext(null);function XpodThemeProvider({children:n}){const[e,t]=reactExports.useState(()=>readXpodThemePreference()),[i,s]=reactExports.useState(()=>resolveXpodTheme("system")),o=e==="system"?i:e;reactExports.useEffect(()=>{const u=systemThemeMedia();if(!u)return;const h=d=>{s(d.matches?"dark":"light")};return typeof u.addEventListener=="function"?(u.addEventListener("change",h),()=>u.removeEventListener("change",h)):(u.addListener?.(h),()=>u.removeListener?.(h))},[]),reactExports.useEffect(()=>{applyXpodTheme(o)},[o]);const l=reactExports.useMemo(()=>({preference:e,resolvedTheme:o,setPreference(u){t(u);try{u==="system"?optionalLocalStorage()?.removeItem(XPOD_THEME_STORAGE_KEY):optionalLocalStorage()?.setItem(XPOD_THEME_STORAGE_KEY,u)}catch{}}}),[e,o]);return jsxRuntimeExports.jsx(XpodThemeContext.Provider,{value:l,children:n})}function XpodThemeRoot({children:n}){return reactExports.useContext(XpodThemeContext)?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(XpodThemeProvider,{children:n})}function DesktopLoginReturnAction(){const[n,e]=reactExports.useState(!1),[t,i]=reactExports.useState(!1),s=reactExports.useRef(!1);if(!window.xpodDesktop?.cancelLogin)return null;const o=async()=>{const l=window.xpodDesktop;if(!(s.current||!l?.cancelLogin)){s.current=!0,e(!0),i(!1);try{await l.cancelLogin()}catch{i(!0)}finally{s.current=!1,e(!1)}}};return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[t&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"返回应用未完成,请重试。"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",className:"w-full",disabled:n,"aria-busy":n,onClick:()=>{o()},children:n?"正在返回…":"返回应用"})]})}const xpodAccountCredentialsCopy={productName:"Xpod 账号",loginTitle:"登录",registerTitle:"创建账号",usernameLabel:"Pod 名称",usernamePlaceholder:"选择 Pod 名称",emailLabel:"邮箱",emailPlaceholder:"you@example.com",passwordLabel:"密码",passwordPlaceholder:"输入密码",confirmationLabel:"确认密码",confirmationPlaceholder:"再次输入密码",loginAction:"登录",registerAction:"创建账号",switchToRegister:"切换用户",switchToLogin:"返回登录",usernameChecking:"正在检查 Pod 名称…",usernameAvailable:"Pod 名称可用",usernameUnavailable:"Pod 名称不可用",suggestionsLabel:"可用建议",mismatchError:"两次输入的密码不一致"},xpodAccountPageCopy={forgotPassword:"忘记密码?"},xpodRegistrationCopy={usernameRequired:"请填写 Pod 名称",usernameLength:"Pod 名称需为 3-63 个字符",usernameCharset:"Pod 名称只能包含小写字母、数字和连字符",usernameHyphen:"Pod 名称不能以连字符开头或结尾",emailAlreadyRegisteredPasswordMismatch:"该邮箱已注册,但密码不正确,请登录或重置密码。",podNameTaken:"Pod 名称已被占用,请换一个。"};function safeXpodLoginMessage(n){return n===401||n===403?"邮箱或密码不正确。":n===429?"尝试次数过多,请稍后再试。":"登录失败,请重试。"}class RegistrationError extends Error{code;constructor(e,t){super(e),this.name="RegistrationError",this.code=t}}async function readErrorMessage(n){const e=await n.json().catch(()=>{});return e?.message||e?.error}async function loginAccountPassword(n){const t=await(n.fetchImpl??fetch)(scopeAccountUrl(n.loginUrl),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({email:n.email,password:n.password,...n.remember===void 0?{}:{remember:n.remember}})});if(!t.ok){const o=await readErrorMessage(t);throw n.duplicateEmailRecovery?new RegistrationError(xpodRegistrationCopy.emailAlreadyRegisteredPasswordMismatch,"EMAIL_ALREADY_REGISTERED"):new Error(o||"Auto-login failed")}const i=await t.json().catch(()=>({})),s=typeof i.authorization=="string"?i.authorization:"";if(!s)throw new Error("Account token not returned after login");return{accountToken:s}}class PasswordLoginStatusError extends Error{status;constructor(e){super(`Password login failed with status ${e}`),this.name="PasswordLoginStatusError",this.status=e}}function XpodAccountCredentials({surface:n,onAuthenticated:e,initialEmail:t}){const{controls:i,idpIndex:s,refetchControls:o}=useAuth(),[l,u]=reactExports.useState({email:t!==void 0?t:readPendingXpodAccountEmail(void 0,s)??"",password:""}),[h,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),[m,v]=reactExports.useState(!0),S=reactExports.useRef(!1),E=async C=>{if(!S.current){S.current=!0,g(!0),d(void 0);try{const T=await resolveHostedAccountControlUrl(i?.password?.login,fetch,s)??scopeAccountUrl("/.account/login/password/"),F=await loginAccountPassword({email:C.email?.trim()??"",password:C.password,loginUrl:T,remember:m,fetchImpl:async(q,O)=>{const G=await fetch(typeof q=="string"||q instanceof URL?scopeAccountUrl(q):q,O);if(!G.ok)throw new PasswordLoginStatusError(G.status);return G}});storeAccountSessionToken(F.accountToken),rememberPendingXpodAccountEmail(C.email?.trim()??"",void 0,s);const P=await o();if(P?.status!=="authenticated"){P?.status==="anonymous"&&clearAccountSessionToken(),d("登录失败,请重试。");return}await e?.()}catch(T){d(T instanceof PasswordLoginStatusError?safeXpodLoginMessage(T.status):safeXpodLoginMessage(500))}finally{S.current=!1,g(!1)}}},x=C=>{u(C),h&&d(void 0)},A={surface:"page",surfaceTitle:"登录 Xpod",copy:xpodAccountCredentialsCopy,footer:n==="embedded"?void 0:jsxRuntimeExports.jsx(AccountEntryLinks,{}),mode:"login",values:l,onChange:x,onSubmit:E,pending:p,rememberAccount:m,onRememberAccountChange:v,errors:h?{form:h}:void 0};return n==="embedded"?jsxRuntimeExports.jsx(AccountCredentialsView,{...A,presentation:"compact",frame:"bare",showHeader:!1}):jsxRuntimeExports.jsx(XpodBlockingAccountCredentialsSurface,{...A})}function AccountEntryLinks(){let n="";try{const e=normalizeXpodReturnTo(`${window.location.pathname}${window.location.search}`);e&&(n=`?${new URLSearchParams({returnTo:e})}`)}catch{}return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-center gap-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/register/${n}`),children:"创建账号"})}),jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"text-border",children:"·"}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/forgot/${n}`),children:xpodAccountPageCopy.forgotPassword})})]})}function AccountWorkspaceBoundary({children:n}){return useXpodSolidRuntimeContext().state.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(AccountAuthBoundary,{children:n})}function AccountAuthBoundary({children:n,accountState:e,retry:t,surface:i="page"}){const s=useAuth(),o=e??s.accountState,l=t??s.retry;return o.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):o.status==="submitting"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在登录…"]})}):o.status==="initializing"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在加载账号"]})}):o.status==="error"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:o.message}),jsxRuntimeExports.jsx(Button,{className:"w-full",type:"button",onClick:()=>{l()},children:"重试"}),jsxRuntimeExports.jsx(DesktopLoginReturnAction,{})]})}):i==="embedded"?jsxRuntimeExports.jsxs(LoginSurface,{surface:i,children:[jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"embedded"}),jsxRuntimeExports.jsx("div",{className:"mt-6 space-y-3 border-t pt-5",children:jsxRuntimeExports.jsx(AccountEntryLinks,{})})]}):jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"page"})}function LoginSurface({children:n,surface:e}){return e==="embedded"?jsxRuntimeExports.jsx(WebAccountLayout,{title:"登录 Xpod",presentation:"compact",children:n}):jsxRuntimeExports.jsx(XpodAccountPageSurface,{title:"登录 Xpod",presentation:"compact",children:n})}function AppLayout({navigation:n,children:e,className:t}){return jsxRuntimeExports.jsxs("section",{className:cn("grid h-screen min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_64px] bg-background sm:grid-cols-[60px_minmax(0,1fr)] sm:grid-rows-[minmax(0,1fr)]",t),"data-app-layout":"workspace",children:[jsxRuntimeExports.jsx("aside",{className:"row-start-2 min-h-0 overflow-x-auto overflow-y-hidden border-t border-border/50 bg-layout-sidebar sm:col-start-1 sm:row-start-1 sm:overflow-hidden sm:border-r sm:border-t-0","data-app-layout-navigation":!0,children:n}),jsxRuntimeExports.jsx("div",{className:"col-start-1 row-start-1 min-h-0 min-w-0 overflow-hidden bg-layout-content sm:col-start-2","data-app-layout-content":!0,children:e})]})}const globalNavigationItems=[{id:"ai-connections",label:"AI Connections",href:canonicalRoutes.aiConnections,activePaths:["/ai-connections"],placement:"primary",icon:Sparkles},{id:"ai-config",label:"AI Config",href:canonicalRoutes.aiConfig,activePaths:["/ai-config"],placement:"primary",icon:BrainCircuit},{id:"network",label:"Network",href:canonicalRoutes.network,activePaths:["/network"],placement:"bottom",icon:Globe},{id:"status",label:"Status",href:canonicalRoutes.status,activePaths:["/status"],placement:"bottom",icon:Gauge},{id:"settings",label:"Settings",href:canonicalRoutes.settings,activePaths:["/settings"],placement:"bottom",icon:Settings}];function isGlobalNavigationItemActive(n,e){const t=e.replace(/\/+$/,"")||"/";return n.activePaths.some(i=>t===i||t.startsWith(`${i}/`))}function accountCardPosition(n,e,t){const l=e>=640,u=Math.min(360,e-16);if(l){const d=Math.max(8,Math.min(n.top,t-240-8));return{left:Math.max(8,Math.min(n.right+12,e-u-8)),top:d,width:u,maxHeight:Math.max(240,t-d-8)}}const h=Math.max(72,t-n.top+12);return{left:8,bottom:h,width:u,maxHeight:Math.max(240,t-h-8)}}function XpodUserCard(){const n=useAuth(),e=reactExports.useContext(XpodSolidRuntimeContext),t=n.isLoggedIn&&n.accountState.status==="authenticated",i=e?.state.status==="authenticated"&&!!(e.webId??e.state.webId),s=t||i,[o,l]=reactExports.useState(accountCardRequestedByUrl(s)),[u,h]=reactExports.useState(),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),v=reactExports.useRef(null),S=reactExports.useRef(null),E=reactExports.useRef(void 0),x=reactExports.useId(),A=n.identity,C=readPendingXpodAccountEmail(),T=readRememberedXpodLogin()?.account,F=t?accountCardIdentityFallback(A,C,T):void 0,P=useXpodProfileCardIdentity({accountIdentity:F,runtime:i?e:void 0}),q=P.displayName,O=initialsFor(P.displayName),G=e?.webId??(e?.state.status==="authenticated"?e.state.webId:void 0),fe=accountHandle(P.username,i?void 0:F?.id,G),M=e?.selectedStorage?.storageUrl??e?.podUrl,ee=e?.selectedStorage,Se=e?.currentPod,re=reactExports.useMemo(()=>M?podNameFromUrl(M):void 0,[M]),Ae=e?.state.status==="authenticated"&&!!(G&&M&&ee&&Se)&&ee?.webId===G&&sameUrl$1(ee?.storageUrl??"",M??"")&&Se?.webId===G&&sameUrl$1(Se?.podUrl??"",M??""),ke=s,he=o&&ke,Oe=reactExports.useCallback(W=>{l(W),W||(m(void 0),clearAccountCardRequest())},[]);reactExports.useLayoutEffect(()=>{if(!he)return;const W=()=>{const de=S.current;de&&m(accountCardPosition(de.getBoundingClientRect(),window.innerWidth,window.innerHeight))};return W(),window.addEventListener("resize",W),window.addEventListener("scroll",W,!0),window.visualViewport?.addEventListener("resize",W),()=>{window.removeEventListener("resize",W),window.removeEventListener("scroll",W,!0),window.visualViewport?.removeEventListener("resize",W)}},[he]),reactExports.useEffect(()=>{if(!ke){clearAccountCardRequest();return}if(!he)return;const W=te=>{const Te=te.target;Te instanceof Node&&(v.current?.contains(Te)||S.current?.contains(Te)||Oe(!1))},de=te=>{te.key==="Escape"&&(Oe(!1),S.current?.focus())};return document.addEventListener("pointerdown",W),document.addEventListener("keydown",de),()=>{document.removeEventListener("pointerdown",W),document.removeEventListener("keydown",de)}},[ke,he,Oe]),reactExports.useEffect(()=>{!he||!g||v.current?.focus({preventScroll:!0})},[he,g]),reactExports.useEffect(()=>()=>{E.current!==void 0&&window.clearTimeout(E.current)},[]);const ce=async()=>{h("logout"),Oe(!1);try{await logoutXpodProduct(n,e),(n.isAnonymous?.()??!0)&&Oe(!1)}catch{}finally{h(void 0)}},Ue=async()=>{h("switch"),Oe(!1);try{await logoutXpodProduct(n,e,{onComplete:()=>{clearRememberedXpodLogin();const W=new URL(XPOD_DEFAULT_RETURN_PATH,window.location.origin);W.searchParams.set("xpod-login","switch"),window.location.assign(W)}}),Oe(!1)}catch{}finally{h(void 0)}},$=async()=>{const W=P.webId??fe;try{await navigator.clipboard.writeText(W),p("Copied")}catch{p("Copy failed")}E.current!==void 0&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>p(void 0),1800)};return ke?jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("button",{ref:S,type:"button","aria-label":s?`Open account menu for ${q}`:"Open account menu","aria-expanded":he,"aria-controls":he?x:void 0,"data-testid":"xpod-user-card-trigger","data-pod-ready":Ae?"true":"false",className:"flex h-9 w-9 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus:ring-0 focus-visible:bg-accent",onClick:()=>Oe(!he),children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:q}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-md bg-muted text-xs text-muted-foreground",children:O})]}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s?q:"Not signed in"})]}),he&&typeof document<"u"?reactDomExports.createPortal(jsxRuntimeExports.jsx("section",{ref:v,id:x,role:"region",tabIndex:-1,"aria-label":s?q:"Xpod account","data-avatar-card":"true","data-selected-pod-url":M,style:g,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${g?"":"invisible"}`,children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-5 px-6 pb-5 pt-6",children:[jsxRuntimeExports.jsxs(Avatar,{"data-testid":"xpod-profile-avatar",className:"h-20 w-20 shrink-0 rounded-2xl border border-border/50 bg-primary/10 shadow-sm",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:q}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-2xl bg-primary/10 text-2xl font-bold text-primary",children:O})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 py-0.5",children:[jsxRuntimeExports.jsx("h2",{className:"truncate text-xl font-bold text-foreground",children:q}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"shrink-0 opacity-70",children:"Xpod ID"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono font-medium",children:fe}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground","aria-label":"Copy Xpod ID",onClick:()=>{$()},children:jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3","aria-hidden":"true"})}),d?jsxRuntimeExports.jsx("span",{role:"status",className:"shrink-0 text-xs text-primary",children:d}):null]}),jsxRuntimeExports.jsxs("div",{className:"mt-2.5 inline-flex items-center gap-1.5 rounded-full bg-emerald-500/10 px-2 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-300",children:[jsxRuntimeExports.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Ae?"bg-emerald-500":"bg-muted-foreground/50"}`,"aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{children:Ae?"Pod connected":i?"WebID connected":"Account connected"})]})]})]}),P.note||P.region?jsxRuntimeExports.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[P.note?jsxRuntimeExports.jsx("p",{className:"line-clamp-2 text-foreground/85",children:P.note}):null,P.region?jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:P.region}):null]}):null,jsxRuntimeExports.jsx("div",{className:"border-t border-border/40 p-2",children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto min-h-14 w-full justify-start gap-3 px-3 py-2.5 font-normal",children:jsxRuntimeExports.jsxs("a",{href:"/settings/pod","aria-label":"Pod settings",children:[jsxRuntimeExports.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:jsxRuntimeExports.jsx(Database,{className:"h-4 w-4","aria-hidden":"true"})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[jsxRuntimeExports.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:podDisplayName(re)}),jsxRuntimeExports.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:["Personal Pod · ",podHost(M)]})]}),Ae?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-emerald-500","aria-label":"Pod ready"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})})}),jsxRuntimeExports.jsx(Separator,{}),jsxRuntimeExports.jsxs("div",{className:"p-2",children:[jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal",onClick:()=>{Ue()},disabled:u!==void 0,children:[u==="switch"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Switch account"]}),jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal text-destructive hover:text-destructive",onClick:()=>{ce()},disabled:u!==void 0,children:[u==="logout"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Sign out"]})]})]})}),document.body):null]}):null}function accountCardIdentityFallback(n,e,t){if(n?.displayName||n?.username||n?.id||n?.webId)return n;const i=e||(t&&"email"in t&&typeof t.email=="string"?t.email:void 0);if(!i&&!t)return n;const s=t?.username||usernameFromEmail(i);return{...t??{},...s?{username:s}:{},...t?.displayName?{displayName:t.displayName}:{displayName:s||i||"Xpod account"}}}function usernameFromEmail(n){if(n)return n.split("@")[0]?.trim()||void 0}function accountHandle(n,e,t){const i=n||e||usernameFromWebId(t);return i?i.startsWith("@")?i:`@${i}`:"Xpod member"}function initialsFor(n){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>=2?`${e[0][0]}${e.at(-1)[0]}`.toUpperCase():n.slice(0,2).toUpperCase()||"XP"}function podNameFromUrl(n){try{return new URL(n).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function podDisplayName(n){return n?`${n} Pod`:"My Pod"}function podHost(n){if(!n)return"No Pod connected";try{return new URL(n).host}catch{return"Pod storage"}}function usernameFromWebId(n){if(n)try{return new URL(n).pathname.split("/").filter(Boolean).at(0)}catch{return}}function sameUrl$1(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function accountCardRequestedByUrl(n){return n?typeof window<"u"&&new URLSearchParams(window.location.search).get("account")==="open":!1}function clearAccountCardRequest(){if(typeof window>"u")return;const n=new URL(window.location.href);n.searchParams.get("account")==="open"&&(n.searchParams.delete("account"),window.history.replaceState(window.history.state,"",`${n.pathname}${n.search}${n.hash}`))}function handleListNavigationKeyDown(n){if(!["ArrowDown","ArrowUp","Home","End"].includes(n.key))return;const e=n.currentTarget.closest("[data-list-navigation]")??n.currentTarget.closest("nav");if(!e)return;const t=[...e.querySelectorAll('a[href]:not([aria-disabled="true"])')],i=t.indexOf(n.currentTarget);if(i<0||t.length===0)return;n.preventDefault();const s=n.key==="Home"?0:n.key==="End"?t.length-1:n.key==="ArrowDown"?(i+1)%t.length:(i-1+t.length)%t.length;t[s]?.focus()}const navItemBaseClass="rounded-lg transition-colors",navItemInteractiveClass="text-foreground hover:bg-accent/60",navItemFocusClass="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function getRailNavItemClass(n){return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":`text-foreground ${navItemInteractiveClass}`,"h-9 w-9 rounded-lg p-0",n?"":"mx-2","flex items-center justify-center"].join(" ")}function getListNavItemClass(n,e){const t=e?.compact===!0;return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":"",t?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",n?"font-medium":`${navItemInteractiveClass} text-foreground`].join(" ")}function ProductNavLinks({items:n,label:e}){const i=useLocation().pathname;return jsxRuntimeExports.jsx("nav",{"aria-label":e,className:"flex flex-row items-center gap-3 sm:flex-col sm:gap-4",children:n.map(s=>{const o=s.icon,l=s.href??s.path??"/",u=s.activePaths?isGlobalNavigationItemActive(s,i):i===s.path||i.startsWith(`${s.path}/`);return jsxRuntimeExports.jsxs(Link,{to:l,"aria-label":s.label,"aria-current":u?"page":void 0,"data-list-item":"true",title:s.label,onKeyDown:handleListNavigationKeyDown,className:clsx(getRailNavItemClass(u),"text-sm"),children:[jsxRuntimeExports.jsx(o,{className:"h-6 w-6","aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s.label})]},s.id)})})}function XpodProductLayout({product:n}){const e=globalNavigationItems.filter(i=>i.placement==="primary"),t=globalNavigationItems.filter(i=>i.placement==="bottom");return jsxRuntimeExports.jsx(AppLayout,{className:`xpod-${n}-shell`,navigation:jsxRuntimeExports.jsxs("div",{className:"flex h-full w-full flex-row items-center px-2 sm:min-h-full sm:flex-col sm:px-0 sm:py-4","data-list-navigation":!0,children:[jsxRuntimeExports.jsx("div",{className:"mr-1 shrink-0 sm:mr-0 sm:ml-2 sm:mb-2",children:jsxRuntimeExports.jsx(XpodUserCard,{})}),jsxRuntimeExports.jsx("div",{className:"flex min-w-0 flex-1 flex-row items-center justify-center sm:mt-5 sm:flex-none sm:flex-col sm:justify-start",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:e,label:"Primary Xpod workspaces"})}),jsxRuntimeExports.jsx("div",{className:"flex shrink-0 flex-row items-center gap-3 sm:mt-auto sm:flex-col sm:gap-0",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:t,label:"Xpod settings"})})]}),children:jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 flex-col bg-background",children:jsxRuntimeExports.jsx(Outlet,{})})})}function XpodDashboardLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"dashboard"})}function RouteLoadingBoundary({children:n}){return jsxRuntimeExports.jsx(RouteChunkErrorBoundary,{children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"正在打开…"}),children:n})})}class RouteChunkErrorBoundary extends reactExports.Component{state={};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("Route module failed to load",e,t.componentStack)}render(){if(!this.state.error)return this.props.children;const e=/Failed to fetch dynamically imported module|Importing a module script failed|Loading chunk .* failed/i.test(this.state.error.message);return jsxRuntimeExports.jsxs("div",{className:"mx-auto flex min-h-64 max-w-md flex-col items-start justify-center gap-3 p-6",children:[jsxRuntimeExports.jsx("div",{className:"text-base font-medium",children:e?"页面已更新":"页面暂时无法打开"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:e?"当前窗口仍在使用旧版页面资源,请重新载入。":"页面加载遇到了问题,请重试。这不表示登录已失效。"}),!1,jsxRuntimeExports.jsx("button",{type:"button",className:"rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground",onClick:()=>window.location.reload(),children:"重新载入"})]})}}const LogsPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DBO_Vq0P.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.LogsPage}))),RdfPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DBO_Vq0P.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.RdfPage}))),StatusPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DBO_Vq0P.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.StatusPage}))),NetworkPage=reactExports.lazy(()=>__vitePreload(()=>import("./NetworkPage-C8OA9Mtp.js"),__vite__mapDeps([7,8,9,2,10,3,11,12,5]))),StatusWorkspace=reactExports.lazy(()=>__vitePreload(()=>import("./StatusWorkspace-CoMFRXoV.js"),__vite__mapDeps([13,2,9,8,10]))),ServiceStatusPanel=reactExports.lazy(()=>__vitePreload(()=>import("./StatusSubjectPanel-BuLml7qn.js"),__vite__mapDeps([14,1,3])).then(n=>({default:n.ServiceStatusPanel}))),IndexSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexSubjectPanel-BgbI9c-a.js"),__vite__mapDeps([15,1,16])));function lazyRoute$1(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}const statusContentRoutes=[{path:"overview",element:lazyRoute$1(jsxRuntimeExports.jsx(StatusPage,{}))},{path:"services/gateway",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"gateway",title:"Gateway"}))},{path:"services/solid-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"css",title:"Solid Server"}))},{path:"services/api-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"api",title:"API Server"}))},{path:"logs",element:lazyRoute$1(jsxRuntimeExports.jsx(LogsPage,{}))},{path:"index",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"overview"}))},{path:"index/rdf",element:lazyRoute$1(jsxRuntimeExports.jsx(RdfPage,{}))},{path:"index/fts",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"fts"}))},{path:"index/vector",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"vector"}))},{path:"index/retrieval-points",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"retrieval-points"}))},{path:"index/cache",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"cache"}))},{path:"index/slow-queries",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"slow-queries"}))},{path:"index/benchmark",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"benchmark"}))}];function statusWorkspaceRoute(n){return{element:lazyRoute$1(jsxRuntimeExports.jsx(StatusWorkspace,{})),children:n}}const dashboardRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},statusWorkspaceRoute(statusContentRoutes),{path:"runtime",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"rdf",element:jsxRuntimeExports.jsx(Navigate,{to:"index/rdf",replace:!0})},{path:"network/*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"status",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"../overview",replace:!0})}]}]}],statusSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[statusWorkspaceRoute([{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},...statusContentRoutes,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})}])]}]}],networkSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))}]}];function XpodSettingsLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"settings"})}function XpodLocalLoginPreflight({onReady:n}){const e=reactExports.useContext(AuthContext),t=reactExports.useRef(!1),i=e?.isInitializing===!0;return reactExports.useEffect(()=>{!i&&!t.current&&(t.current=!0,n())},[i,n]),jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在准备登录…"})}const RETURN_TO_KEY="xpod:returnTo";function consumeReturnTo(){try{const n=sessionStorage.getItem(RETURN_TO_KEY);return n&&sessionStorage.removeItem(RETURN_TO_KEY),n}catch{return null}}const CANCELLED_LOGIN_KEY="xpod.auth.login-cancelled";function setXpodLoginCancelled(n){try{n?window.localStorage.setItem(CANCELLED_LOGIN_KEY,"1"):window.localStorage.removeItem(CANCELLED_LOGIN_KEY)}catch{}}function consumeXpodLoginIntent(n){const e=new URL(window.location.href);return e.searchParams.get("xpod-login")!==n?!1:(setXpodLoginCancelled(!0),consumeReturnTo(),e.searchParams.delete("xpod-login"),window.history.replaceState(window.history.state,"",`${e.pathname}${e.search}${e.hash}`),!0)}function readXpodAccountSwitch(){return new URL(window.location.href).searchParams.get("xpod-login")==="switch"}function consumeXpodAccountSwitch(){return consumeXpodLoginIntent("switch")}function readXpodLoginCancelled(){if(consumeXpodLoginIntent("cancelled"))return!0;try{return window.localStorage.getItem(CANCELLED_LOGIN_KEY)==="1"}catch{return!1}}function createXpodLoginController(n){const e=n.location??(typeof window>"u"?"http://localhost/":window.location),i=[createXpodLoginRoute(e)],s=toOrigin(e),o=n.transactionStore??createXpodLoginTransactionStore({origin:s}),l=p=>{if(p!==void 0)return normalizeXpodReturnTo(p);const g=new URL(toHref(e)),m=`${g.pathname}${g.search}`;try{return normalizeXpodReturnTo(m)}catch{return}};let u=!1;const h=p=>{try{return o.begin(p)}catch(g){if(u||!(g instanceof XpodLoginTransactionError)||g.code!=="already_active")throw g;try{const m=o.readSinglePending();m&&o.cancel(m.id)}catch{}return o.begin(p)}},d=async(p,g,m)=>{const v=l(p),S={id:createOpaqueTransactionId(),route:i[0],authorizationSurface:"redirect",discovery:"strict",...m?{prompt:m}:{},...v===void 0?{}:{returnTo:v},...g===void 0?{}:{selectedStorage:g}},E=h(S);u=!0;try{await n.runtime.login(E)}catch(x){try{o.cancel(E.id)}catch{}throw x}finally{u=!1}return E};return{routes:i,startLogin:d,retryLogin:d,cancelLogin(){const p=o.readSinglePending();p&&o.cancel(p.id)},readPending:()=>o.readSinglePending(),callbackUrl(){return`${s}/auth/callback`}}}function toOrigin(n){return new URL(toHref(n)).origin}function toHref(n){return typeof n=="string"?n:n.href}function XpodLoginBrand({compact:n=!1,showSubtitle:e=!n,subtitle:t="使用 WebID 登录"}){const i=n&&e;return jsxRuntimeExports.jsxs("div",{"data-testid":"xpod-login-brand","data-presentation":n?"compact":"standard",className:i?"flex flex-col items-center justify-center gap-1 text-center":n?"flex items-center justify-center gap-2 text-center":"flex flex-col items-center gap-3 text-center",children:[jsxRuntimeExports.jsx("img",{src:xpodIconUrl,alt:"",className:n?i?"h-16 w-16":"h-7 w-7":"h-11 w-11"}),jsxRuntimeExports.jsxs("div",{className:i?"space-y-1 text-center":n?"text-left":"space-y-1",children:[jsxRuntimeExports.jsx("h1",{className:n?"text-base font-semibold leading-none text-foreground":"text-lg font-semibold text-foreground",children:"Xpod"}),e?jsxRuntimeExports.jsx("p",{className:"text-xs text-primary/80",children:t}):null]})]})}const rememberedCopy={restoringLabel:"正在恢复 Xpod 会话…",continueLabel:n=>`使用 ${n} 登录`,reauthenticateLabel:n=>`重新登录 ${n}`,switchAccountLabel:"切换账号",expiredTitle:"会话已过期",connectingTitle:"正在登录…",connectingDetail:"请在授权页面完成登录。",cancelLabel:"取消"},podFailureMessage="无法打开选中的 Pod,请重试。",actionFailureMessage="操作未完成,请重试。";function WebIdAuthBoundary(n){return jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(WebIdAuthBoundaryContent,{...n})})}function WebIdAuthBoundaryContent({children:n,autoStart:e=!1}){const t=useXpodSolidRuntime(),i=reactExports.useContext(AuthContext),s=reactExports.useSyncExternalStore(subscribeXpodProductLogout,isXpodAutomaticLoginBlocked,()=>!1),o=reactExports.useMemo(()=>createXpodLoginController({runtime:t}),[t]),[l]=reactExports.useState(readXpodAccountSwitch),[u,h]=reactExports.useState(()=>l||readXpodLoginCancelled());reactExports.useLayoutEffect(()=>{l&&consumeXpodAccountSwitch()},[l]),reactExports.useEffect(()=>{if(u)try{o.cancelLogin()}catch{}},[u,o]);const d=runtimeState(t.state),p=storageSelectionState(t,d),g=d.status==="authenticated"&&p?.status==="ready",[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1),[x,A]=reactExports.useState(l?{prompt:"login"}:void 0),C=reactExports.useRef(0),[T,F]=reactExports.useState(!1),P=reactExports.useRef(!1),q=reactExports.useRef(!1),O=reactExports.useCallback($=>{console.error("[WebIdAuthBoundary] authentication action failed",$),v(actionFailureMessage)},[]),G=reactExports.useCallback($=>{const W=++C.current;v(void 0),E(!0),$().catch(de=>{W===C.current&&O(de)}).finally(()=>{W===C.current&&E(!1)})},[O]),fe=reactExports.useCallback(()=>{setXpodLoginCancelled(!1),h(!1),v(void 0),A({})},[]),M=reactExports.useCallback(()=>{if(!x)return;const $=x.prompt;setXpodLoginCancelled(!1),h(!1),A(void 0),G(async()=>{l&&await t.session.initialize({restorePreviousSession:!1}),await o.startLogin(void 0,void 0,$)})},[o,x,G,t.session,l]),ee=()=>{if(T){re();return}d.status==="authenticated"?t.retryPodOpen?.():fe()},Se=()=>{if(!T){try{o.cancelLogin()}catch{}setXpodLoginCancelled(!0),h(!0),A(void 0),C.current+=1,E(!1),v(void 0)}},re=()=>G(async()=>{F(!0);const $=()=>{setXpodLoginCancelled(!1),h(!1),clearRememberedXpodLogin(),v(void 0),A({prompt:"login"}),F(!1)};i?await logoutXpodProduct(i,t,{onComplete:$}):(await t.logout(),$())});if(reactExports.useEffect(()=>{t.state.status!=="loading"||P.current||(P.current=!0,t.session.initialize({restorePreviousSession:!u}).catch(O))},[u,O,t.session,t.state.status]),reactExports.useEffect(()=>{u||x||s||S||T||!e||q.current||d.status!=="anonymous"||(q.current=!0,fe())},[u,s,e,S,x,fe,d.status,T]),g&&!S&&!m)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});if(x)return jsxRuntimeExports.jsx(XpodLocalLoginPreflight,{onReady:M});const Ae="remembered"in d?d.remembered:void 0,ke=d.status==="restoring",he=S||e&&!u&&!s&&d.status==="anonymous"&&!m,Oe=jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0});let ce,Ue;return!u&&t.state.status==="error"&&t.state.error.name==="SolidSessionPendingError"?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:"上次登录尚未结束,请刷新页面后重新登录。",primaryLabel:"刷新页面",onPrimary:()=>window.location.reload(),secondaryLabel:"返回登录",onSecondary:Se}):m?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:m,primaryLabel:"重试",onPrimary:ee,secondaryLabel:T?void 0:"返回登录",onSecondary:T?void 0:Se}):ke?(Ue=Ae?void 0:Oe,ce=jsxRuntimeExports.jsx(LoginRestoringView,{accountName:Ae?.displayName,avatarUrl:Ae?.avatarUrl,label:rememberedCopy.restoringLabel})):he?ce=T?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在切换账号…"}):jsxRuntimeExports.jsx(LoginConnectingView,{title:rememberedCopy.connectingTitle,detail:rememberedCopy.connectingDetail,cancelLabel:rememberedCopy.cancelLabel,onCancel:Se}):d.status==="authenticated"?ce=p?.status==="conflict"||p?.status==="error"?jsxRuntimeExports.jsx(LoginFailureView,{title:p.status==="conflict"?"存储绑定冲突":"暂时无法打开 Pod",description:p.message,primaryLabel:"重试",onPrimary:ee,secondaryLabel:"切换账号",onSecondary:re}):jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在打开选中的 Pod。"}):Ae&&!u?ce=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[d.status==="error"&&jsxRuntimeExports.jsx("p",{role:"alert",className:"mb-3 text-center text-xs text-muted-foreground",children:d.message}),jsxRuntimeExports.jsx(LoginAccountView,{name:Ae.displayName,avatarUrl:Ae.avatarUrl,bindingLabel:"Xpod",expired:d.status==="expired"||d.status==="error",expiredTitle:d.status==="error"?"会话恢复未完成":rememberedCopy.expiredTitle,enterLabel:d.status==="expired"||d.status==="error"?rememberedCopy.reauthenticateLabel(Ae.displayName):rememberedCopy.continueLabel(Ae.displayName),switchLabel:rememberedCopy.switchAccountLabel,onEnter:fe,onReauthenticate:ee,onSwitchAccount:re})]}):!u&&(d.status==="error"||d.status==="expired")?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:d.status==="expired"?rememberedCopy.expiredTitle:"无法登录 Xpod",description:d.status==="error"?d.message:"请重新登录后继续。",primaryLabel:"重试",onPrimary:ee,secondaryLabel:"返回登录",onSecondary:Se}):ce=jsxRuntimeExports.jsx(WebIdLoginEntryView,{copy:{title:"",startLabel:"登录",pendingLabel:rememberedCopy.connectingTitle},logo:Oe,onStart:fe}),jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"登录 Xpod",lead:Ue,children:ce})}function storageSelectionState(n,e){if(e.status!=="authenticated")return;if(n.podError?.webId===e.webId)return{status:"error",message:podFailureMessage};if(n.currentPod===void 0)return{status:"waiting_for_binding"};const t=n.selectedStorage??{webId:n.currentPod.webId,storageUrl:n.currentPod.podUrl},i=n.state.status==="authenticated"?n.state.podUrl:void 0;return n.currentPod.webId===e.webId&&t.webId===n.currentPod.webId&&sameUrl(t.storageUrl,n.currentPod.podUrl)&&(i===void 0||sameUrl(n.currentPod.podUrl,i))?{status:"ready",selected:t}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function sameUrl(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function rememberedWebIdLogin(n){const e=readRememberedXpodLogin();if(e&&!(n&&n!==e.webId))return{displayName:e.account.displayName??e.account.username??e.account.email??"Xpod",...e.account.avatarUrl?{avatarUrl:e.account.avatarUrl}:{},webId:e.webId,routeId:e.routeId}}function withRemembered(n,e){const t=rememberedWebIdLogin(e);return t?{...n,remembered:t}:n}function runtimeState(n){switch(n.status){case"loading":return withRemembered({status:"restoring"});case"anonymous":return withRemembered({status:"anonymous"});case"expired":return withRemembered({status:"expired"},n.webId);case"authenticated":return{status:"authenticated",webId:n.webId};case"error":{const e=rememberedWebIdLogin(n.webId);return{status:"error",message:n.error.message,retryRouteId:"xpod-current-origin",...e?{remembered:e}:{}}}}}const ModelsPage=reactExports.lazy(()=>__vitePreload(()=>import("./ModelsPage-CU-YQ8_7.js"),__vite__mapDeps([17,18,10,4,11,19]))),AiConfigPage=reactExports.lazy(()=>__vitePreload(()=>import("./AiConfigPage-Bs1EE3Ei.js"),__vite__mapDeps([20,8,21,18,10]))),ModelAssignmentsPanel=reactExports.lazy(()=>__vitePreload(()=>import("./ModelAssignmentsPanel-C0BE7nbk.js").then(n=>n.M),__vite__mapDeps([22,21,18])).then(n=>({default:n.ModelAssignmentsPanel}))),DocumentProcessingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./DocumentProcessingPanel-CSFfdOXS.js"),__vite__mapDeps([23,22,21,18])).then(n=>({default:n.DocumentProcessingPanel}))),SearchIndexingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SearchIndexingPanel-Bdd46mIV.js"),__vite__mapDeps([24,22,21,18])).then(n=>({default:n.SearchIndexingPanel}))),IndexLifecyclePanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexLifecyclePanel-BR9Su49B.js"),__vite__mapDeps([25,22,21,18])).then(n=>({default:n.IndexLifecyclePanel}))),SystemSettingsPage=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsPage-DlzmaWV-.js"),__vite__mapDeps([26,6,1,27,8,10]))),PodSettingsSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsSubjectPanel-DExjDo_v.js"),__vite__mapDeps([28,1,27,18,12,16,3])).then(n=>({default:n.PodSettingsSubjectPanel})));function lazyRoute(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}function systemSettingsPage(n){return{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(SystemSettingsPage,{})),children:n}]}}const aiConnectionsSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{index:!0,element:lazyRoute(jsxRuntimeExports.jsx(ModelsPage,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:".",replace:!0})}]}],aiConfigSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(AiConfigPage,{})),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})},{path:"model-assignments",element:lazyRoute(jsxRuntimeExports.jsx(ModelAssignmentsPanel,{}))},{path:"document-processing",element:lazyRoute(jsxRuntimeExports.jsx(DocumentProcessingPanel,{}))},{path:"search-indexing",element:lazyRoute(jsxRuntimeExports.jsx(SearchIndexingPanel,{}))},{path:"index-lifecycle",element:lazyRoute(jsxRuntimeExports.jsx(IndexLifecyclePanel,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})}]}]}],systemSettingsSurfaceRoutes=[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})},{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"pod",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"pod"}))}])]},{element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"identity-access",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"identity-access"}))}])]},systemSettingsPage([{path:"storage",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"storage"}))},{path:"runtime",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"runtime"}))},{path:"cloud",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"cloud"}))},{path:"advanced",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"advanced"}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})}])],xpodShellRoutes=[{path:"status",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:statusSurfaceRoutes},{path:"network",children:networkSurfaceRoutes},{path:"ai-connections",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConnectionsSurfaceRoutes},{path:"ai-config",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConfigSurfaceRoutes},{path:"settings",children:systemSettingsSurfaceRoutes},{path:"dashboard",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:dashboardRoutes},{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})}];function XpodShellRoutes(){const n=useLocation(),e=useRoutes(xpodShellRoutes);return reactExports.useEffect(()=>{document.title=n.pathname.startsWith("/status")?"Xpod Dashboard":"Xpod Settings"},[n.pathname]),e}function XpodShellApp({runtime:n,initialPathname:e}={}){const[t]=reactExports.useState(()=>initializeProductLocation(e));return jsxRuntimeExports.jsx(XpodThemeRoot,{children:jsxRuntimeExports.jsx(AuthProvider,{children:jsxRuntimeExports.jsxs(XpodSolidRuntimeProvider,{value:n,children:[jsxRuntimeExports.jsx(XpodDesktopIdentityBridge,{}),jsxRuntimeExports.jsx(XpodRememberedLoginBridge,{}),jsxRuntimeExports.jsxs(BrowserRouter,{children:[jsxRuntimeExports.jsx(XpodDesktopNavigationBridge,{}),jsxRuntimeExports.jsx(XpodServiceAvailability,{children:jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(XpodShellRoutes,{})})}),jsxRuntimeExports.jsx(Toaster,{})]},t)]})})})}function initializeProductLocation(n){const t=`${canonicalProductPathname(n??globalThis.location?.pathname??XPOD_DEFAULT_RETURN_PATH)}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==t&&globalThis.history?.replaceState(null,"",t),t}initializeXpodTheme();clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(reactExports.StrictMode,{children:jsxRuntimeExports.jsx(XpodThemeProvider,{children:jsxRuntimeExports.jsx(XpodShellApp,{})})}));export{createSlottable as $,prepareProvisionedPod as A,Button as B,Card as C,Database as D,useAuth as E,resolveProvisionCodeForCurrentScope as F,Gauge as G,toast as H,Copy as I,useLayoutEffect2 as J,React4 as K,useComposedRefs as L,useCallbackRef as M,NavLink as N,Outlet as O,Primitive as P,dispatchDiscreteCustomEvent as Q,RefreshCw as R,Sparkles as S,reactDomExports as T,createContextScope as U,clsx as V,Link as W,createSlot as X,getDefaultExportFromCjs as Y,createLucideIcon$1 as Z,X as _,CardHeader as a,getLinkedResourceUrlAll as a0,acp as a1,internal_cloneResource as a2,getSolidDataset as a3,freeze as a4,getSourceUrl as a5,getResourceInfo as a6,getSourceIri as a7,getThingAll as a8,getIriAll as a9,dismissToast as aA,controlFocusClass as aB,Toaster as aC,credentialResource as aD,aiProviderResource as aE,aiModelResource as aF,configureSparqlEngine as aG,AuthContext as aH,createXpodLoginController as aI,requireBuffer as aJ,requireLink as aK,getAugmentedNamespace as aL,requireBrowser$2 as aM,requireSparql as aN,requireEvents as aO,requireBrowser$3 as aP,requireString_decoder as aQ,bufferExports as aR,commonjsGlobal as aS,rdf$3 as aa,acl as ab,setThing as ac,setIri as ad,removeIri as ae,removeAll as af,createThing as ag,addIri as ah,removeThing as ai,subjectToRdfJsQuads as aj,DataFactory$1 as ak,getIri as al,saveSolidDatasetAt as am,createSolidDataset as an,foaf as ao,getThing as ap,getUrlAll as aq,buildThing as ar,Avatar as as,AvatarImage as at,AvatarFallback as au,LoaderCircle$1 as av,Input as aw,LoginFailureView as ax,LoginConnectingView as ay,Label as az,CardTitle as b,createLucideIcon as c,CardDescription as d,CardContent as e,cn as f,cva as g,aiConfigModelRef as h,interactiveFocusClass as i,jsxRuntimeExports as j,useLocation as k,handleListNavigationKeyDown as l,getListNavItemClass as m,resolveHostedAccountControlUrl as n,hasInvalidWebIdWhitespace as o,resolveProvisionCodeForPodCreate as p,scopeAccountUrl as q,reactExports as r,storedAccountTokenHeaders as s,buildPodCreatePayload as t,useXpodSolidRuntime as u,getAccountSessionToken as v,accountTokenHeaders as w,xpodRegistrationCopy as x,resolveProvisionScope as y,storageUrlBelongsToRoot as z};
306
+ `)},i.hextoposhex=Pr,i.intarystrtohex=function(b){b=(b=(b=b.replace(/^\s*\[\s*/,"")).replace(/\s*\]\s*$/,"")).replace(/\s*/g,"");try{return b.split(/,/).map((function(w,I,L){var Q=parseInt(w);if(Q<0||255<Q)throw"integer not in range 0-255";return("00"+Q.toString(16)).slice(-2)})).join("")}catch(w){throw"malformed integer array string: "+w}},i.strdiffidx=function(b,w){var I=b.length;b.length>w.length&&(I=w.length);for(var L=0;L<I;L++)if(b.charCodeAt(L)!=w.charCodeAt(L))return L;return b.length!=w.length?I:-1},i.KJUR=j;var En=j.crypto;i.crypto=En;var gn=j.asn1;i.asn1=gn;var Rn=j.jws;i.jws=Rn;var ws=j.lang;i.lang=ws}).call(this,s(28).Buffer)},function(t,i,s){(function(o){var l=s(30),u=s(31),h=s(32);function d(){return g.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function p(ie,B){if(d()<B)throw new RangeError("Invalid typed array length");return g.TYPED_ARRAY_SUPPORT?(ie=new Uint8Array(B)).__proto__=g.prototype:(ie===null&&(ie=new g(B)),ie.length=B),ie}function g(ie,B,N){if(!(g.TYPED_ARRAY_SUPPORT||this instanceof g))return new g(ie,B,N);if(typeof ie=="number"){if(typeof B=="string")throw new Error("If encoding is specified then the first argument must be a string");return S(this,ie)}return m(this,ie,B,N)}function m(ie,B,N,k){if(typeof B=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&B instanceof ArrayBuffer?(function(ne,le,Ee,J){if(le.byteLength,Ee<0||le.byteLength<Ee)throw new RangeError("'offset' is out of bounds");if(le.byteLength<Ee+(J||0))throw new RangeError("'length' is out of bounds");return le=Ee===void 0&&J===void 0?new Uint8Array(le):J===void 0?new Uint8Array(le,Ee):new Uint8Array(le,Ee,J),g.TYPED_ARRAY_SUPPORT?(ne=le).__proto__=g.prototype:ne=E(ne,le),ne})(ie,B,N,k):typeof B=="string"?(function(ne,le,Ee){if(typeof Ee=="string"&&Ee!==""||(Ee="utf8"),!g.isEncoding(Ee))throw new TypeError('"encoding" must be a valid string encoding');var J=0|A(le,Ee),_e=(ne=p(ne,J)).write(le,Ee);return _e!==J&&(ne=ne.slice(0,_e)),ne})(ie,B,N):(function(ne,le){if(g.isBuffer(le)){var Ee=0|x(le.length);return(ne=p(ne,Ee)).length===0||le.copy(ne,0,0,Ee),ne}if(le){if(typeof ArrayBuffer<"u"&&le.buffer instanceof ArrayBuffer||"length"in le)return typeof le.length!="number"||(function(_e){return _e!=_e})(le.length)?p(ne,0):E(ne,le);if(le.type==="Buffer"&&h(le.data))return E(ne,le.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(ie,B)}function v(ie){if(typeof ie!="number")throw new TypeError('"size" argument must be a number');if(ie<0)throw new RangeError('"size" argument must not be negative')}function S(ie,B){if(v(B),ie=p(ie,B<0?0:0|x(B)),!g.TYPED_ARRAY_SUPPORT)for(var N=0;N<B;++N)ie[N]=0;return ie}function E(ie,B){var N=B.length<0?0:0|x(B.length);ie=p(ie,N);for(var k=0;k<N;k+=1)ie[k]=255&B[k];return ie}function x(ie){if(ie>=d())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+d().toString(16)+" bytes");return 0|ie}function A(ie,B){if(g.isBuffer(ie))return ie.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(ie)||ie instanceof ArrayBuffer))return ie.byteLength;typeof ie!="string"&&(ie=""+ie);var N=ie.length;if(N===0)return 0;for(var k=!1;;)switch(B){case"ascii":case"latin1":case"binary":return N;case"utf8":case"utf-8":case void 0:return me(ie).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*N;case"hex":return N>>>1;case"base64":return ge(ie).length;default:if(k)return me(ie).length;B=(""+B).toLowerCase(),k=!0}}function C(ie,B,N){var k=!1;if((B===void 0||B<0)&&(B=0),B>this.length||((N===void 0||N>this.length)&&(N=this.length),N<=0)||(N>>>=0)<=(B>>>=0))return"";for(ie||(ie="utf8");;)switch(ie){case"hex":return Oe(this,B,N);case"utf8":case"utf-8":return re(this,B,N);case"ascii":return ke(this,B,N);case"latin1":case"binary":return he(this,B,N);case"base64":return Se(this,B,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ce(this,B,N);default:if(k)throw new TypeError("Unknown encoding: "+ie);ie=(ie+"").toLowerCase(),k=!0}}function T(ie,B,N){var k=ie[B];ie[B]=ie[N],ie[N]=k}function F(ie,B,N,k,H){if(ie.length===0)return-1;if(typeof N=="string"?(k=N,N=0):N>2147483647?N=2147483647:N<-2147483648&&(N=-2147483648),N=+N,isNaN(N)&&(N=H?0:ie.length-1),N<0&&(N=ie.length+N),N>=ie.length){if(H)return-1;N=ie.length-1}else if(N<0){if(!H)return-1;N=0}if(typeof B=="string"&&(B=g.from(B,k)),g.isBuffer(B))return B.length===0?-1:P(ie,B,N,k,H);if(typeof B=="number")return B&=255,g.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?H?Uint8Array.prototype.indexOf.call(ie,B,N):Uint8Array.prototype.lastIndexOf.call(ie,B,N):P(ie,[B],N,k,H);throw new TypeError("val must be string, number or Buffer")}function P(ie,B,N,k,H){var ne,le=1,Ee=ie.length,J=B.length;if(k!==void 0&&((k=String(k).toLowerCase())==="ucs2"||k==="ucs-2"||k==="utf16le"||k==="utf-16le")){if(ie.length<2||B.length<2)return-1;le=2,Ee/=2,J/=2,N/=2}function _e(ht,Je){return le===1?ht[Je]:ht.readUInt16BE(Je*le)}if(H){var Ie=-1;for(ne=N;ne<Ee;ne++)if(_e(ie,ne)===_e(B,Ie===-1?0:ne-Ie)){if(Ie===-1&&(Ie=ne),ne-Ie+1===J)return Ie*le}else Ie!==-1&&(ne-=ne-Ie),Ie=-1}else for(N+J>Ee&&(N=Ee-J),ne=N;ne>=0;ne--){for(var ye=!0,at=0;at<J;at++)if(_e(ie,ne+at)!==_e(B,at)){ye=!1;break}if(ye)return ne}return-1}function q(ie,B,N,k){N=Number(N)||0;var H=ie.length-N;k?(k=Number(k))>H&&(k=H):k=H;var ne=B.length;if(ne%2!=0)throw new TypeError("Invalid hex string");k>ne/2&&(k=ne/2);for(var le=0;le<k;++le){var Ee=parseInt(B.substr(2*le,2),16);if(isNaN(Ee))return le;ie[N+le]=Ee}return le}function O(ie,B,N,k){return Be(me(B,ie.length-N),ie,N,k)}function G(ie,B,N,k){return Be((function(ne){for(var le=[],Ee=0;Ee<ne.length;++Ee)le.push(255&ne.charCodeAt(Ee));return le})(B),ie,N,k)}function fe(ie,B,N,k){return G(ie,B,N,k)}function M(ie,B,N,k){return Be(ge(B),ie,N,k)}function ee(ie,B,N,k){return Be((function(ne,le){for(var Ee,J,_e,Ie=[],ye=0;ye<ne.length&&!((le-=2)<0);++ye)J=(Ee=ne.charCodeAt(ye))>>8,_e=Ee%256,Ie.push(_e),Ie.push(J);return Ie})(B,ie.length-N),ie,N,k)}function Se(ie,B,N){return B===0&&N===ie.length?l.fromByteArray(ie):l.fromByteArray(ie.slice(B,N))}function re(ie,B,N){N=Math.min(ie.length,N);for(var k=[],H=B;H<N;){var ne,le,Ee,J,_e=ie[H],Ie=null,ye=_e>239?4:_e>223?3:_e>191?2:1;if(H+ye<=N)switch(ye){case 1:_e<128&&(Ie=_e);break;case 2:(192&(ne=ie[H+1]))==128&&(J=(31&_e)<<6|63&ne)>127&&(Ie=J);break;case 3:ne=ie[H+1],le=ie[H+2],(192&ne)==128&&(192&le)==128&&(J=(15&_e)<<12|(63&ne)<<6|63&le)>2047&&(J<55296||J>57343)&&(Ie=J);break;case 4:ne=ie[H+1],le=ie[H+2],Ee=ie[H+3],(192&ne)==128&&(192&le)==128&&(192&Ee)==128&&(J=(15&_e)<<18|(63&ne)<<12|(63&le)<<6|63&Ee)>65535&&J<1114112&&(Ie=J)}Ie===null?(Ie=65533,ye=1):Ie>65535&&(Ie-=65536,k.push(Ie>>>10&1023|55296),Ie=56320|1023&Ie),k.push(Ie),H+=ye}return(function(ht){var Je=ht.length;if(Je<=Ae)return String.fromCharCode.apply(String,ht);for(var gt="",Y=0;Y<Je;)gt+=String.fromCharCode.apply(String,ht.slice(Y,Y+=Ae));return gt})(k)}i.Buffer=g,i.SlowBuffer=function(B){return+B!=B&&(B=0),g.alloc(+B)},i.INSPECT_MAX_BYTES=50,g.TYPED_ARRAY_SUPPORT=o.TYPED_ARRAY_SUPPORT!==void 0?o.TYPED_ARRAY_SUPPORT:(function(){try{var B=new Uint8Array(1);return B.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},B.foo()===42&&typeof B.subarray=="function"&&B.subarray(1,1).byteLength===0}catch{return!1}})(),i.kMaxLength=d(),g.poolSize=8192,g._augment=function(ie){return ie.__proto__=g.prototype,ie},g.from=function(ie,B,N){return m(null,ie,B,N)},g.TYPED_ARRAY_SUPPORT&&(g.prototype.__proto__=Uint8Array.prototype,g.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&g[Symbol.species]===g&&Object.defineProperty(g,Symbol.species,{value:null,configurable:!0})),g.alloc=function(ie,B,N){return(function(H,ne,le,Ee){return v(ne),ne<=0?p(H,ne):le!==void 0?typeof Ee=="string"?p(H,ne).fill(le,Ee):p(H,ne).fill(le):p(H,ne)})(null,ie,B,N)},g.allocUnsafe=function(ie){return S(null,ie)},g.allocUnsafeSlow=function(ie){return S(null,ie)},g.isBuffer=function(B){return!(B==null||!B._isBuffer)},g.compare=function(B,N){if(!g.isBuffer(B)||!g.isBuffer(N))throw new TypeError("Arguments must be Buffers");if(B===N)return 0;for(var k=B.length,H=N.length,ne=0,le=Math.min(k,H);ne<le;++ne)if(B[ne]!==N[ne]){k=B[ne],H=N[ne];break}return k<H?-1:H<k?1:0},g.isEncoding=function(B){switch(String(B).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},g.concat=function(B,N){if(!h(B))throw new TypeError('"list" argument must be an Array of Buffers');if(B.length===0)return g.alloc(0);var k;if(N===void 0)for(N=0,k=0;k<B.length;++k)N+=B[k].length;var H=g.allocUnsafe(N),ne=0;for(k=0;k<B.length;++k){var le=B[k];if(!g.isBuffer(le))throw new TypeError('"list" argument must be an Array of Buffers');le.copy(H,ne),ne+=le.length}return H},g.byteLength=A,g.prototype._isBuffer=!0,g.prototype.swap16=function(){var B=this.length;if(B%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var N=0;N<B;N+=2)T(this,N,N+1);return this},g.prototype.swap32=function(){var B=this.length;if(B%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var N=0;N<B;N+=4)T(this,N,N+3),T(this,N+1,N+2);return this},g.prototype.swap64=function(){var B=this.length;if(B%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var N=0;N<B;N+=8)T(this,N,N+7),T(this,N+1,N+6),T(this,N+2,N+5),T(this,N+3,N+4);return this},g.prototype.toString=function(){var B=0|this.length;return B===0?"":arguments.length===0?re(this,0,B):C.apply(this,arguments)},g.prototype.equals=function(B){if(!g.isBuffer(B))throw new TypeError("Argument must be a Buffer");return this===B||g.compare(this,B)===0},g.prototype.inspect=function(){var B="",N=i.INSPECT_MAX_BYTES;return this.length>0&&(B=this.toString("hex",0,N).match(/.{2}/g).join(" "),this.length>N&&(B+=" ... ")),"<Buffer "+B+">"},g.prototype.compare=function(B,N,k,H,ne){if(!g.isBuffer(B))throw new TypeError("Argument must be a Buffer");if(N===void 0&&(N=0),k===void 0&&(k=B?B.length:0),H===void 0&&(H=0),ne===void 0&&(ne=this.length),N<0||k>B.length||H<0||ne>this.length)throw new RangeError("out of range index");if(H>=ne&&N>=k)return 0;if(H>=ne)return-1;if(N>=k)return 1;if(this===B)return 0;for(var le=(ne>>>=0)-(H>>>=0),Ee=(k>>>=0)-(N>>>=0),J=Math.min(le,Ee),_e=this.slice(H,ne),Ie=B.slice(N,k),ye=0;ye<J;++ye)if(_e[ye]!==Ie[ye]){le=_e[ye],Ee=Ie[ye];break}return le<Ee?-1:Ee<le?1:0},g.prototype.includes=function(B,N,k){return this.indexOf(B,N,k)!==-1},g.prototype.indexOf=function(B,N,k){return F(this,B,N,k,!0)},g.prototype.lastIndexOf=function(B,N,k){return F(this,B,N,k,!1)},g.prototype.write=function(B,N,k,H){if(N===void 0)H="utf8",k=this.length,N=0;else if(k===void 0&&typeof N=="string")H=N,k=this.length,N=0;else{if(!isFinite(N))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");N|=0,isFinite(k)?(k|=0,H===void 0&&(H="utf8")):(H=k,k=void 0)}var ne=this.length-N;if((k===void 0||k>ne)&&(k=ne),B.length>0&&(k<0||N<0)||N>this.length)throw new RangeError("Attempt to write outside buffer bounds");H||(H="utf8");for(var le=!1;;)switch(H){case"hex":return q(this,B,N,k);case"utf8":case"utf-8":return O(this,B,N,k);case"ascii":return G(this,B,N,k);case"latin1":case"binary":return fe(this,B,N,k);case"base64":return M(this,B,N,k);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ee(this,B,N,k);default:if(le)throw new TypeError("Unknown encoding: "+H);H=(""+H).toLowerCase(),le=!0}},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ae=4096;function ke(ie,B,N){var k="";N=Math.min(ie.length,N);for(var H=B;H<N;++H)k+=String.fromCharCode(127&ie[H]);return k}function he(ie,B,N){var k="";N=Math.min(ie.length,N);for(var H=B;H<N;++H)k+=String.fromCharCode(ie[H]);return k}function Oe(ie,B,N){var k=ie.length;(!B||B<0)&&(B=0),(!N||N<0||N>k)&&(N=k);for(var H="",ne=B;ne<N;++ne)H+=We(ie[ne]);return H}function ce(ie,B,N){for(var k=ie.slice(B,N),H="",ne=0;ne<k.length;ne+=2)H+=String.fromCharCode(k[ne]+256*k[ne+1]);return H}function Ue(ie,B,N){if(ie%1!=0||ie<0)throw new RangeError("offset is not uint");if(ie+B>N)throw new RangeError("Trying to access beyond buffer length")}function $(ie,B,N,k,H,ne){if(!g.isBuffer(ie))throw new TypeError('"buffer" argument must be a Buffer instance');if(B>H||B<ne)throw new RangeError('"value" argument is out of bounds');if(N+k>ie.length)throw new RangeError("Index out of range")}function W(ie,B,N,k){B<0&&(B=65535+B+1);for(var H=0,ne=Math.min(ie.length-N,2);H<ne;++H)ie[N+H]=(B&255<<8*(k?H:1-H))>>>8*(k?H:1-H)}function de(ie,B,N,k){B<0&&(B=4294967295+B+1);for(var H=0,ne=Math.min(ie.length-N,4);H<ne;++H)ie[N+H]=B>>>8*(k?H:3-H)&255}function te(ie,B,N,k,H,ne){if(N+k>ie.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("Index out of range")}function Te(ie,B,N,k,H){return H||te(ie,0,N,4),u.write(ie,B,N,k,23,4),N+4}function je(ie,B,N,k,H){return H||te(ie,0,N,8),u.write(ie,B,N,k,52,8),N+8}g.prototype.slice=function(B,N){var k,H=this.length;if((B=~~B)<0?(B+=H)<0&&(B=0):B>H&&(B=H),(N=N===void 0?H:~~N)<0?(N+=H)<0&&(N=0):N>H&&(N=H),N<B&&(N=B),g.TYPED_ARRAY_SUPPORT)(k=this.subarray(B,N)).__proto__=g.prototype;else{var ne=N-B;k=new g(ne,void 0);for(var le=0;le<ne;++le)k[le]=this[le+B]}return k},g.prototype.readUIntLE=function(B,N,k){B|=0,N|=0,k||Ue(B,N,this.length);for(var H=this[B],ne=1,le=0;++le<N&&(ne*=256);)H+=this[B+le]*ne;return H},g.prototype.readUIntBE=function(B,N,k){B|=0,N|=0,k||Ue(B,N,this.length);for(var H=this[B+--N],ne=1;N>0&&(ne*=256);)H+=this[B+--N]*ne;return H},g.prototype.readUInt8=function(B,N){return N||Ue(B,1,this.length),this[B]},g.prototype.readUInt16LE=function(B,N){return N||Ue(B,2,this.length),this[B]|this[B+1]<<8},g.prototype.readUInt16BE=function(B,N){return N||Ue(B,2,this.length),this[B]<<8|this[B+1]},g.prototype.readUInt32LE=function(B,N){return N||Ue(B,4,this.length),(this[B]|this[B+1]<<8|this[B+2]<<16)+16777216*this[B+3]},g.prototype.readUInt32BE=function(B,N){return N||Ue(B,4,this.length),16777216*this[B]+(this[B+1]<<16|this[B+2]<<8|this[B+3])},g.prototype.readIntLE=function(B,N,k){B|=0,N|=0,k||Ue(B,N,this.length);for(var H=this[B],ne=1,le=0;++le<N&&(ne*=256);)H+=this[B+le]*ne;return H>=(ne*=128)&&(H-=Math.pow(2,8*N)),H},g.prototype.readIntBE=function(B,N,k){B|=0,N|=0,k||Ue(B,N,this.length);for(var H=N,ne=1,le=this[B+--H];H>0&&(ne*=256);)le+=this[B+--H]*ne;return le>=(ne*=128)&&(le-=Math.pow(2,8*N)),le},g.prototype.readInt8=function(B,N){return N||Ue(B,1,this.length),128&this[B]?-1*(255-this[B]+1):this[B]},g.prototype.readInt16LE=function(B,N){N||Ue(B,2,this.length);var k=this[B]|this[B+1]<<8;return 32768&k?4294901760|k:k},g.prototype.readInt16BE=function(B,N){N||Ue(B,2,this.length);var k=this[B+1]|this[B]<<8;return 32768&k?4294901760|k:k},g.prototype.readInt32LE=function(B,N){return N||Ue(B,4,this.length),this[B]|this[B+1]<<8|this[B+2]<<16|this[B+3]<<24},g.prototype.readInt32BE=function(B,N){return N||Ue(B,4,this.length),this[B]<<24|this[B+1]<<16|this[B+2]<<8|this[B+3]},g.prototype.readFloatLE=function(B,N){return N||Ue(B,4,this.length),u.read(this,B,!0,23,4)},g.prototype.readFloatBE=function(B,N){return N||Ue(B,4,this.length),u.read(this,B,!1,23,4)},g.prototype.readDoubleLE=function(B,N){return N||Ue(B,8,this.length),u.read(this,B,!0,52,8)},g.prototype.readDoubleBE=function(B,N){return N||Ue(B,8,this.length),u.read(this,B,!1,52,8)},g.prototype.writeUIntLE=function(B,N,k,H){B=+B,N|=0,k|=0,H||$(this,B,N,k,Math.pow(2,8*k)-1,0);var ne=1,le=0;for(this[N]=255&B;++le<k&&(ne*=256);)this[N+le]=B/ne&255;return N+k},g.prototype.writeUIntBE=function(B,N,k,H){B=+B,N|=0,k|=0,H||$(this,B,N,k,Math.pow(2,8*k)-1,0);var ne=k-1,le=1;for(this[N+ne]=255&B;--ne>=0&&(le*=256);)this[N+ne]=B/le&255;return N+k},g.prototype.writeUInt8=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,1,255,0),g.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),this[N]=255&B,N+1},g.prototype.writeUInt16LE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8):W(this,B,N,!0),N+2},g.prototype.writeUInt16BE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>8,this[N+1]=255&B):W(this,B,N,!1),N+2},g.prototype.writeUInt32LE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N+3]=B>>>24,this[N+2]=B>>>16,this[N+1]=B>>>8,this[N]=255&B):de(this,B,N,!0),N+4},g.prototype.writeUInt32BE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>24,this[N+1]=B>>>16,this[N+2]=B>>>8,this[N+3]=255&B):de(this,B,N,!1),N+4},g.prototype.writeIntLE=function(B,N,k,H){if(B=+B,N|=0,!H){var ne=Math.pow(2,8*k-1);$(this,B,N,k,ne-1,-ne)}var le=0,Ee=1,J=0;for(this[N]=255&B;++le<k&&(Ee*=256);)B<0&&J===0&&this[N+le-1]!==0&&(J=1),this[N+le]=(B/Ee>>0)-J&255;return N+k},g.prototype.writeIntBE=function(B,N,k,H){if(B=+B,N|=0,!H){var ne=Math.pow(2,8*k-1);$(this,B,N,k,ne-1,-ne)}var le=k-1,Ee=1,J=0;for(this[N+le]=255&B;--le>=0&&(Ee*=256);)B<0&&J===0&&this[N+le+1]!==0&&(J=1),this[N+le]=(B/Ee>>0)-J&255;return N+k},g.prototype.writeInt8=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,1,127,-128),g.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),B<0&&(B=255+B+1),this[N]=255&B,N+1},g.prototype.writeInt16LE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8):W(this,B,N,!0),N+2},g.prototype.writeInt16BE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>8,this[N+1]=255&B):W(this,B,N,!1),N+2},g.prototype.writeInt32LE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,4,2147483647,-2147483648),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8,this[N+2]=B>>>16,this[N+3]=B>>>24):de(this,B,N,!0),N+4},g.prototype.writeInt32BE=function(B,N,k){return B=+B,N|=0,k||$(this,B,N,4,2147483647,-2147483648),B<0&&(B=4294967295+B+1),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>24,this[N+1]=B>>>16,this[N+2]=B>>>8,this[N+3]=255&B):de(this,B,N,!1),N+4},g.prototype.writeFloatLE=function(B,N,k){return Te(this,B,N,!0,k)},g.prototype.writeFloatBE=function(B,N,k){return Te(this,B,N,!1,k)},g.prototype.writeDoubleLE=function(B,N,k){return je(this,B,N,!0,k)},g.prototype.writeDoubleBE=function(B,N,k){return je(this,B,N,!1,k)},g.prototype.copy=function(B,N,k,H){if(k||(k=0),H||H===0||(H=this.length),N>=B.length&&(N=B.length),N||(N=0),H>0&&H<k&&(H=k),H===k||B.length===0||this.length===0)return 0;if(N<0)throw new RangeError("targetStart out of bounds");if(k<0||k>=this.length)throw new RangeError("sourceStart out of bounds");if(H<0)throw new RangeError("sourceEnd out of bounds");H>this.length&&(H=this.length),B.length-N<H-k&&(H=B.length-N+k);var ne,le=H-k;if(this===B&&k<N&&N<H)for(ne=le-1;ne>=0;--ne)B[ne+N]=this[ne+k];else if(le<1e3||!g.TYPED_ARRAY_SUPPORT)for(ne=0;ne<le;++ne)B[ne+N]=this[ne+k];else Uint8Array.prototype.set.call(B,this.subarray(k,k+le),N);return le},g.prototype.fill=function(B,N,k,H){if(typeof B=="string"){if(typeof N=="string"?(H=N,N=0,k=this.length):typeof k=="string"&&(H=k,k=this.length),B.length===1){var ne=B.charCodeAt(0);ne<256&&(B=ne)}if(H!==void 0&&typeof H!="string")throw new TypeError("encoding must be a string");if(typeof H=="string"&&!g.isEncoding(H))throw new TypeError("Unknown encoding: "+H)}else typeof B=="number"&&(B&=255);if(N<0||this.length<N||this.length<k)throw new RangeError("Out of range index");if(k<=N)return this;var le;if(N>>>=0,k=k===void 0?this.length:k>>>0,B||(B=0),typeof B=="number")for(le=N;le<k;++le)this[le]=B;else{var Ee=g.isBuffer(B)?B:me(new g(B,H).toString()),J=Ee.length;for(le=0;le<k-N;++le)this[le+N]=Ee[le%J]}return this};var He=/[^+\/0-9A-Za-z-_]/g;function We(ie){return ie<16?"0"+ie.toString(16):ie.toString(16)}function me(ie,B){var N;B=B||1/0;for(var k=ie.length,H=null,ne=[],le=0;le<k;++le){if((N=ie.charCodeAt(le))>55295&&N<57344){if(!H){if(N>56319){(B-=3)>-1&&ne.push(239,191,189);continue}if(le+1===k){(B-=3)>-1&&ne.push(239,191,189);continue}H=N;continue}if(N<56320){(B-=3)>-1&&ne.push(239,191,189),H=N;continue}N=65536+(H-55296<<10|N-56320)}else H&&(B-=3)>-1&&ne.push(239,191,189);if(H=null,N<128){if((B-=1)<0)break;ne.push(N)}else if(N<2048){if((B-=2)<0)break;ne.push(N>>6|192,63&N|128)}else if(N<65536){if((B-=3)<0)break;ne.push(N>>12|224,N>>6&63|128,63&N|128)}else{if(!(N<1114112))throw new Error("Invalid code point");if((B-=4)<0)break;ne.push(N>>18|240,N>>12&63|128,N>>6&63|128,63&N|128)}}return ne}function ge(ie){return l.toByteArray((function(N){if((N=(function(H){return H.trim?H.trim():H.replace(/^\s+|\s+$/g,"")})(N).replace(He,"")).length<2)return"";for(;N.length%4!=0;)N+="=";return N})(ie))}function Be(ie,B,N,k){for(var H=0;H<k&&!(H+N>=B.length||H>=ie.length);++H)B[H+N]=ie[H];return H}}).call(this,s(29))},function(t,i){var s;s=(function(){return this})();try{s=s||new Function("return this")()}catch{typeof window=="object"&&(s=window)}t.exports=s},function(t,i,s){i.byteLength=function(S){var E=g(S),x=E[0],A=E[1];return 3*(x+A)/4-A},i.toByteArray=function(S){var E,x,A=g(S),C=A[0],T=A[1],F=new u((function(G,fe,M){return 3*(fe+M)/4-M})(0,C,T)),P=0,q=T>0?C-4:C;for(x=0;x<q;x+=4)E=l[S.charCodeAt(x)]<<18|l[S.charCodeAt(x+1)]<<12|l[S.charCodeAt(x+2)]<<6|l[S.charCodeAt(x+3)],F[P++]=E>>16&255,F[P++]=E>>8&255,F[P++]=255&E;return T===2&&(E=l[S.charCodeAt(x)]<<2|l[S.charCodeAt(x+1)]>>4,F[P++]=255&E),T===1&&(E=l[S.charCodeAt(x)]<<10|l[S.charCodeAt(x+1)]<<4|l[S.charCodeAt(x+2)]>>2,F[P++]=E>>8&255,F[P++]=255&E),F},i.fromByteArray=function(S){for(var E,x=S.length,A=x%3,C=[],T=16383,F=0,P=x-A;F<P;F+=T)C.push(m(S,F,F+T>P?P:F+T));return A===1?(E=S[x-1],C.push(o[E>>2]+o[E<<4&63]+"==")):A===2&&(E=(S[x-2]<<8)+S[x-1],C.push(o[E>>10]+o[E>>4&63]+o[E<<2&63]+"=")),C.join("")};for(var o=[],l=[],u=typeof Uint8Array<"u"?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=h.length;d<p;++d)o[d]=h[d],l[h.charCodeAt(d)]=d;function g(v){var S=v.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var E=v.indexOf("=");return E===-1&&(E=S),[E,E===S?0:4-E%4]}function m(v,S,E){for(var x,A,C=[],T=S;T<E;T+=3)x=(v[T]<<16&16711680)+(v[T+1]<<8&65280)+(255&v[T+2]),C.push(o[(A=x)>>18&63]+o[A>>12&63]+o[A>>6&63]+o[63&A]);return C.join("")}l[45]=62,l[95]=63},function(t,i){i.read=function(s,o,l,u,h){var d,p,g=8*h-u-1,m=(1<<g)-1,v=m>>1,S=-7,E=l?h-1:0,x=l?-1:1,A=s[o+E];for(E+=x,d=A&(1<<-S)-1,A>>=-S,S+=g;S>0;d=256*d+s[o+E],E+=x,S-=8);for(p=d&(1<<-S)-1,d>>=-S,S+=u;S>0;p=256*p+s[o+E],E+=x,S-=8);if(d===0)d=1-v;else{if(d===m)return p?NaN:1/0*(A?-1:1);p+=Math.pow(2,u),d-=v}return(A?-1:1)*p*Math.pow(2,d-u)},i.write=function(s,o,l,u,h,d){var p,g,m,v=8*d-h-1,S=(1<<v)-1,E=S>>1,x=h===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=u?0:d-1,C=u?1:-1,T=o<0||o===0&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(g=isNaN(o)?1:0,p=S):(p=Math.floor(Math.log(o)/Math.LN2),o*(m=Math.pow(2,-p))<1&&(p--,m*=2),(o+=p+E>=1?x/m:x*Math.pow(2,1-E))*m>=2&&(p++,m/=2),p+E>=S?(g=0,p=S):p+E>=1?(g=(o*m-1)*Math.pow(2,h),p+=E):(g=o*Math.pow(2,E-1)*Math.pow(2,h),p=0));h>=8;s[l+A]=255&g,A+=C,g/=256,h-=8);for(p=p<<h|g,v+=h;v>0;s[l+A]=255&p,A+=C,p/=256,v-=8);s[l+A-C]|=128*T}},function(t,i){var s={}.toString;t.exports=Array.isArray||function(o){return s.call(o)=="[object Array]"}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.default=function(u){var h=u.jws,d=u.KeyUtil,p=u.X509,g=u.crypto,m=u.hextob64u,v=u.b64tohex,S=u.AllowedSigningAlgs;return(function(){function E(){(function(A,C){if(!(A instanceof C))throw new TypeError("Cannot call a class as a function")})(this,E)}return E.parseJwt=function(A){o.Log.debug("JoseUtil.parseJwt");try{var C=h.JWS.parse(A);return{header:C.headerObj,payload:C.payloadObj}}catch(T){o.Log.error(T)}},E.validateJwt=function(A,C,T,F,P,q,O){o.Log.debug("JoseUtil.validateJwt");try{if(C.kty==="RSA")if(C.e&&C.n)C=d.getKey(C);else{if(!C.x5c||!C.x5c.length)return o.Log.error("JoseUtil.validateJwt: RSA key missing key material",C),Promise.reject(new Error("RSA key missing key material"));var G=v(C.x5c[0]);C=p.getPublicKeyFromCertHex(G)}else{if(C.kty!=="EC")return o.Log.error("JoseUtil.validateJwt: Unsupported key type",C&&C.kty),Promise.reject(new Error(C.kty));if(!(C.crv&&C.x&&C.y))return o.Log.error("JoseUtil.validateJwt: EC key missing key material",C),Promise.reject(new Error("EC key missing key material"));C=d.getKey(C)}return E._validateJwt(A,C,T,F,P,q,O)}catch(fe){return o.Log.error(fe&&fe.message||fe),Promise.reject("JWT validation failed")}},E.validateJwtAttributes=function(A,C,T,F,P,q){F||(F=0),P||(P=parseInt(Date.now()/1e3));var O=E.parseJwt(A).payload;if(!O.iss)return o.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(O.iss!==C)return o.Log.error("JoseUtil._validateJwt: Invalid issuer in token",O.iss),Promise.reject(new Error("Invalid issuer in token: "+O.iss));if(!O.aud)return o.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(O.aud===T||Array.isArray(O.aud)&&O.aud.indexOf(T)>=0))return o.Log.error("JoseUtil._validateJwt: Invalid audience in token",O.aud),Promise.reject(new Error("Invalid audience in token: "+O.aud));if(O.azp&&O.azp!==T)return o.Log.error("JoseUtil._validateJwt: Invalid azp in token",O.azp),Promise.reject(new Error("Invalid azp in token: "+O.azp));if(!q){var G=P+F,fe=P-F;if(!O.iat)return o.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(G<O.iat)return o.Log.error("JoseUtil._validateJwt: iat is in the future",O.iat),Promise.reject(new Error("iat is in the future: "+O.iat));if(O.nbf&&G<O.nbf)return o.Log.error("JoseUtil._validateJwt: nbf is in the future",O.nbf),Promise.reject(new Error("nbf is in the future: "+O.nbf));if(!O.exp)return o.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if(O.exp<fe)return o.Log.error("JoseUtil._validateJwt: exp is in the past",O.exp),Promise.reject(new Error("exp is in the past:"+O.exp))}return Promise.resolve(O)},E._validateJwt=function(A,C,T,F,P,q,O){return E.validateJwtAttributes(A,T,F,P,q,O).then((function(G){try{return h.JWS.verify(A,C,S)?G:(o.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(fe){return o.Log.error(fe&&fe.message||fe),Promise.reject(new Error("signature validation failed"))}}))},E.hashString=function(A,C){try{return g.Util.hashString(A,C)}catch(T){o.Log.error(T)}},E.hexToBase64Url=function(A){try{return m(A)}catch(C){o.Log.error(C)}},E})()};var o=s(0);t.exports=i.default},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SigninResponse=void 0;var o=(function(){function h(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(3);function u(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")}i.SigninResponse=(function(){function h(d){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#";u(this,h);var g=l.UrlUtility.parseUrlFragment(d,p);this.error=g.error,this.error_description=g.error_description,this.error_uri=g.error_uri,this.code=g.code,this.state=g.state,this.id_token=g.id_token,this.session_state=g.session_state,this.access_token=g.access_token,this.token_type=g.token_type,this.scope=g.scope,this.profile=void 0,this.expires_in=g.expires_in}return o(h,[{key:"expires_in",get:function(){if(this.expires_at){var p=parseInt(Date.now()/1e3);return this.expires_at-p}},set:function(p){var g=parseInt(p);if(typeof g=="number"&&g>0){var m=parseInt(Date.now()/1e3);this.expires_at=m+g}}},{key:"expired",get:function(){var p=this.expires_in;if(p!==void 0)return p<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutRequest=void 0;var o=s(0),l=s(3),u=s(9);i.SignoutRequest=function h(d){var p=d.url,g=d.id_token_hint,m=d.post_logout_redirect_uri,v=d.data,S=d.extraQueryParams,E=d.request_type;if((function(C,T){if(!(C instanceof T))throw new TypeError("Cannot call a class as a function")})(this,h),!p)throw o.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var x in g&&(p=l.UrlUtility.addQueryParam(p,"id_token_hint",g)),m&&(p=l.UrlUtility.addQueryParam(p,"post_logout_redirect_uri",m),v&&(this.state=new u.State({data:v,request_type:E}),p=l.UrlUtility.addQueryParam(p,"state",this.state.id))),S)p=l.UrlUtility.addQueryParam(p,x,S[x]);this.url=p}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutResponse=void 0;var o=s(3);i.SignoutResponse=function l(u){(function(p,g){if(!(p instanceof g))throw new TypeError("Cannot call a class as a function")})(this,l);var h=o.UrlUtility.parseUrlFragment(u,"?");this.error=h.error,this.error_description=h.error_description,this.error_uri=h.error_uri,this.state=h.state}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.InMemoryWebStorage=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.InMemoryWebStorage=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u),this._data={}}return u.prototype.getItem=function(d){return l.Log.debug("InMemoryWebStorage.getItem",d),this._data[d]},u.prototype.setItem=function(d,p){l.Log.debug("InMemoryWebStorage.setItem",d),this._data[d]=p},u.prototype.removeItem=function(d){l.Log.debug("InMemoryWebStorage.removeItem",d),delete this._data[d]},u.prototype.key=function(d){return Object.getOwnPropertyNames(this._data)[d]},o(u,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManager=void 0;var o=(function(){function T(F,P){for(var q=0;q<P.length;q++){var O=P[q];O.enumerable=O.enumerable||!1,O.configurable=!0,"value"in O&&(O.writable=!0),Object.defineProperty(F,O.key,O)}}return function(F,P,q){return P&&T(F.prototype,P),q&&T(F,q),F}})(),l=s(0),u=s(10),h=s(39),d=s(15),p=s(45),g=s(47),m=s(18),v=s(8),S=s(20),E=s(11),x=s(4);function A(T,F){if(!(T instanceof F))throw new TypeError("Cannot call a class as a function")}function C(T,F){if(!T)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!F||typeof F!="object"&&typeof F!="function"?T:F}i.UserManager=(function(T){function F(){var P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:g.SilentRenewService,O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:m.SessionMonitor,G=arguments.length>3&&arguments[3]!==void 0?arguments[3]:S.TokenRevocationClient,fe=arguments.length>4&&arguments[4]!==void 0?arguments[4]:E.TokenClient,M=arguments.length>5&&arguments[5]!==void 0?arguments[5]:x.JoseUtil;A(this,F),P instanceof h.UserManagerSettings||(P=new h.UserManagerSettings(P));var ee=C(this,T.call(this,P));return ee._events=new p.UserManagerEvents(P),ee._silentRenewService=new q(ee),ee.settings.automaticSilentRenew&&(l.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),ee.startSilentRenew()),ee.settings.monitorSession&&(l.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),ee._sessionMonitor=new O(ee)),ee._tokenRevocationClient=new G(ee._settings),ee._tokenClient=new fe(ee._settings),ee._joseUtil=M,ee}return(function(q,O){if(typeof O!="function"&&O!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof O);q.prototype=Object.create(O&&O.prototype,{constructor:{value:q,enumerable:!1,writable:!0,configurable:!0}}),O&&(Object.setPrototypeOf?Object.setPrototypeOf(q,O):q.__proto__=O)})(F,T),F.prototype.getUser=function(){var q=this;return this._loadUser().then((function(O){return O?(l.Log.info("UserManager.getUser: user loaded"),q._events.load(O,!1),O):(l.Log.info("UserManager.getUser: user not found in storage"),null)}))},F.prototype.removeUser=function(){var q=this;return this.storeUser(null).then((function(){l.Log.info("UserManager.removeUser: user removed from storage"),q._events.unload()}))},F.prototype.signinRedirect=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(q=Object.assign({},q)).request_type="si:r";var O={useReplaceToNavigate:q.useReplaceToNavigate};return this._signinStart(q,this._redirectNavigator,O).then((function(){l.Log.info("UserManager.signinRedirect: successful")}))},F.prototype.signinRedirectCallback=function(q){return this._signinEnd(q||this._redirectNavigator.url).then((function(O){return O.profile&&O.profile.sub?l.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinRedirectCallback: no sub"),O}))},F.prototype.signinPopup=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(q=Object.assign({},q)).request_type="si:p";var O=q.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return O?(q.redirect_uri=O,q.display="popup",this._signin(q,this._popupNavigator,{startUrl:O,popupWindowFeatures:q.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:q.popupWindowTarget||this.settings.popupWindowTarget}).then((function(G){return G&&(G.profile&&G.profile.sub?l.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",G.profile.sub):l.Log.info("UserManager.signinPopup: no sub")),G}))):(l.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},F.prototype.signinPopupCallback=function(q){return this._signinCallback(q,this._popupNavigator).then((function(O){return O&&(O.profile&&O.profile.sub?l.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinPopupCallback: no sub")),O})).catch((function(O){l.Log.error(O.message)}))},F.prototype.signinSilent=function(){var q=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return O=Object.assign({},O),this._loadUser().then((function(G){return G&&G.refresh_token?(O.refresh_token=G.refresh_token,q._useRefreshToken(O)):(O.request_type="si:s",O.id_token_hint=O.id_token_hint||q.settings.includeIdTokenInSilentRenew&&G&&G.id_token,G&&q._settings.validateSubOnSilentRenew&&(l.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",G.profile.sub),O.current_sub=G.profile.sub),q._signinSilentIframe(O))}))},F.prototype._useRefreshToken=function(){var q=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(O).then((function(G){return G?G.access_token?q._loadUser().then((function(fe){if(fe){var M=Promise.resolve();return G.id_token&&(M=q._validateIdTokenFromTokenRefreshToken(fe.profile,G.id_token)),M.then((function(){return l.Log.debug("UserManager._useRefreshToken: refresh token response success"),fe.id_token=G.id_token||fe.id_token,fe.access_token=G.access_token,fe.refresh_token=G.refresh_token||fe.refresh_token,fe.expires_in=G.expires_in,q.storeUser(fe).then((function(){return q._events.load(fe),fe}))}))}return null})):(l.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(l.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},F.prototype._validateIdTokenFromTokenRefreshToken=function(q,O){var G=this;return this._metadataService.getIssuer().then((function(fe){return G.settings.getEpochTime().then((function(M){return G._joseUtil.validateJwtAttributes(O,fe,G._settings.client_id,G._settings.clockSkew,M).then((function(ee){return ee?ee.sub!==q.sub?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: sub in id_token does not match current sub"),Promise.reject(new Error("sub in id_token does not match current sub"))):ee.auth_time&&ee.auth_time!==q.auth_time?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: auth_time in id_token does not match original auth_time"),Promise.reject(new Error("auth_time in id_token does not match original auth_time"))):ee.azp&&ee.azp!==q.azp?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp in id_token does not match original azp"),Promise.reject(new Error("azp in id_token does not match original azp"))):!ee.azp&&q.azp?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp not in id_token, but present in original id_token"),Promise.reject(new Error("azp not in id_token, but present in original id_token"))):void 0:(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},F.prototype._signinSilentIframe=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},O=q.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return O?(q.redirect_uri=O,q.prompt=q.prompt||"none",this._signin(q,this._iframeNavigator,{startUrl:O,silentRequestTimeout:q.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(G){return G&&(G.profile&&G.profile.sub?l.Log.info("UserManager.signinSilent: successful, signed in sub: ",G.profile.sub):l.Log.info("UserManager.signinSilent: no sub")),G}))):(l.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype.signinSilentCallback=function(q){return this._signinCallback(q,this._iframeNavigator).then((function(O){return O&&(O.profile&&O.profile.sub?l.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinSilentCallback: no sub")),O}))},F.prototype.signinCallback=function(q){var O=this;return this.readSigninResponseState(q).then((function(G){var fe=G.state;return G.response,fe.request_type==="si:r"?O.signinRedirectCallback(q):fe.request_type==="si:p"?O.signinPopupCallback(q):fe.request_type==="si:s"?O.signinSilentCallback(q):Promise.reject(new Error("invalid response_type in state"))}))},F.prototype.signoutCallback=function(q,O){var G=this;return this.readSignoutResponseState(q).then((function(fe){var M=fe.state,ee=fe.response;return M?M.request_type==="so:r"?G.signoutRedirectCallback(q):M.request_type==="so:p"?G.signoutPopupCallback(q,O):Promise.reject(new Error("invalid response_type in state")):ee}))},F.prototype.querySessionStatus=function(){var q=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(O=Object.assign({},O)).request_type="si:s";var G=O.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return G?(O.redirect_uri=G,O.prompt="none",O.response_type=O.response_type||this.settings.query_status_response_type,O.scope=O.scope||"openid",O.skipUserInfo=!0,this._signinStart(O,this._iframeNavigator,{startUrl:G,silentRequestTimeout:O.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(fe){return q.processSigninResponse(fe.url).then((function(M){if(l.Log.debug("UserManager.querySessionStatus: got signin response"),M.session_state&&M.profile.sub)return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",M.profile.sub),{session_state:M.session_state,sub:M.profile.sub,sid:M.profile.sid};l.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(M){if(M.session_state&&q.settings.monitorAnonymousSession&&(M.message=="login_required"||M.message=="consent_required"||M.message=="interaction_required"||M.message=="account_selection_required"))return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:M.session_state};throw M}))}))):(l.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype._signin=function(q,O){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signinStart(q,O,fe).then((function(M){return G._signinEnd(M.url,q)}))},F.prototype._signinStart=function(q,O){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return O.prepare(fe).then((function(M){return l.Log.debug("UserManager._signinStart: got navigator window handle"),G.createSigninRequest(q).then((function(ee){return l.Log.debug("UserManager._signinStart: got signin request"),fe.url=ee.url,fe.id=ee.state.id,M.navigate(fe)})).catch((function(ee){throw M.close&&(l.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),M.close()),ee}))}))},F.prototype._signinEnd=function(q){var O=this,G=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.processSigninResponse(q).then((function(fe){l.Log.debug("UserManager._signinEnd: got signin response");var M=new d.User(fe);if(G.current_sub){if(G.current_sub!==M.profile.sub)return l.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",M.profile.sub),Promise.reject(new Error("login_required"));l.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return O.storeUser(M).then((function(){return l.Log.debug("UserManager._signinEnd: user stored"),O._events.load(M),M}))}))},F.prototype._signinCallback=function(q,O){l.Log.debug("UserManager._signinCallback");var G=this._settings.response_mode==="query"||!this._settings.response_mode&&v.SigninRequest.isCode(this._settings.response_type)?"?":"#";return O.callback(q,void 0,G)},F.prototype.signoutRedirect=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(q=Object.assign({},q)).request_type="so:r";var O=q.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;O&&(q.post_logout_redirect_uri=O);var G={useReplaceToNavigate:q.useReplaceToNavigate};return this._signoutStart(q,this._redirectNavigator,G).then((function(){l.Log.info("UserManager.signoutRedirect: successful")}))},F.prototype.signoutRedirectCallback=function(q){return this._signoutEnd(q||this._redirectNavigator.url).then((function(O){return l.Log.info("UserManager.signoutRedirectCallback: successful"),O}))},F.prototype.signoutPopup=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(q=Object.assign({},q)).request_type="so:p";var O=q.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return q.post_logout_redirect_uri=O,q.display="popup",q.post_logout_redirect_uri&&(q.state=q.state||{}),this._signout(q,this._popupNavigator,{startUrl:O,popupWindowFeatures:q.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:q.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){l.Log.info("UserManager.signoutPopup: successful")}))},F.prototype.signoutPopupCallback=function(q,O){return O===void 0&&typeof q=="boolean"&&(O=q,q=null),this._popupNavigator.callback(q,O,"?").then((function(){l.Log.info("UserManager.signoutPopupCallback: successful")}))},F.prototype._signout=function(q,O){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signoutStart(q,O,fe).then((function(M){return G._signoutEnd(M.url)}))},F.prototype._signoutStart=function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},O=this,G=arguments[1],fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return G.prepare(fe).then((function(M){return l.Log.debug("UserManager._signoutStart: got navigator window handle"),O._loadUser().then((function(ee){return l.Log.debug("UserManager._signoutStart: loaded current user from storage"),(O._settings.revokeAccessTokenOnSignout?O._revokeInternal(ee):Promise.resolve()).then((function(){var Se=q.id_token_hint||ee&&ee.id_token;return Se&&(l.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),q.id_token_hint=Se),O.removeUser().then((function(){return l.Log.debug("UserManager._signoutStart: user removed, creating signout request"),O.createSignoutRequest(q).then((function(re){return l.Log.debug("UserManager._signoutStart: got signout request"),fe.url=re.url,re.state&&(fe.id=re.state.id),M.navigate(fe)}))}))}))})).catch((function(ee){throw M.close&&(l.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),M.close()),ee}))}))},F.prototype._signoutEnd=function(q){return this.processSignoutResponse(q).then((function(O){return l.Log.debug("UserManager._signoutEnd: got signout response"),O}))},F.prototype.revokeAccessToken=function(){var q=this;return this._loadUser().then((function(O){return q._revokeInternal(O,!0).then((function(G){if(G)return l.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),O.access_token=null,O.refresh_token=null,O.expires_at=null,O.token_type=null,q.storeUser(O).then((function(){l.Log.debug("UserManager.revokeAccessToken: user stored"),q._events.load(O)}))}))})).then((function(){l.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},F.prototype._revokeInternal=function(q,O){var G=this;if(q){var fe=q.access_token,M=q.refresh_token;return this._revokeAccessTokenInternal(fe,O).then((function(ee){return G._revokeRefreshTokenInternal(M,O).then((function(Se){return ee||Se||l.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),ee||Se}))}))}return Promise.resolve(!1)},F.prototype._revokeAccessTokenInternal=function(q,O){return!q||q.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(q,O).then((function(){return!0}))},F.prototype._revokeRefreshTokenInternal=function(q,O){return q?this._tokenRevocationClient.revoke(q,O,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},F.prototype.startSilentRenew=function(){this._silentRenewService.start()},F.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},F.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(q){return q?(l.Log.debug("UserManager._loadUser: user storageString loaded"),d.User.fromStorageString(q)):(l.Log.debug("UserManager._loadUser: no user storageString"),null)}))},F.prototype.storeUser=function(q){if(q){l.Log.debug("UserManager.storeUser: storing user");var O=q.toStorageString();return this._userStore.set(this._userStoreKey,O)}return l.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},o(F,[{key:"_redirectNavigator",get:function(){return this.settings.redirectNavigator}},{key:"_popupNavigator",get:function(){return this.settings.popupNavigator}},{key:"_iframeNavigator",get:function(){return this.settings.iframeNavigator}},{key:"_userStore",get:function(){return this.settings.userStore}},{key:"events",get:function(){return this._events}},{key:"_userStoreKey",get:function(){return"user:"+this.settings.authority+":"+this.settings.client_id}}]),F})(u.OidcClient)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerSettings=void 0;var o=(function(){function E(x,A){for(var C=0;C<A.length;C++){var T=A[C];T.enumerable=T.enumerable||!1,T.configurable=!0,"value"in T&&(T.writable=!0),Object.defineProperty(x,T.key,T)}}return function(x,A,C){return A&&E(x.prototype,A),C&&E(x,C),x}})(),l=(s(0),s(5)),u=s(40),h=s(41),d=s(43),p=s(6),g=s(1),m=s(8);function v(E,x){if(!(E instanceof x))throw new TypeError("Cannot call a class as a function")}function S(E,x){if(!E)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!x||typeof x!="object"&&typeof x!="function"?E:x}i.UserManagerSettings=(function(E){function x(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},C=A.popup_redirect_uri,T=A.popup_post_logout_redirect_uri,F=A.popupWindowFeatures,P=A.popupWindowTarget,q=A.silent_redirect_uri,O=A.silentRequestTimeout,G=A.automaticSilentRenew,fe=G!==void 0&&G,M=A.validateSubOnSilentRenew,ee=M!==void 0&&M,Se=A.includeIdTokenInSilentRenew,re=Se===void 0||Se,Ae=A.monitorSession,ke=Ae===void 0||Ae,he=A.monitorAnonymousSession,Oe=he!==void 0&&he,ce=A.checkSessionInterval,Ue=ce===void 0?2e3:ce,$=A.stopCheckSessionOnError,W=$===void 0||$,de=A.query_status_response_type,te=A.revokeAccessTokenOnSignout,Te=te!==void 0&&te,je=A.accessTokenExpiringNotificationTime,He=je===void 0?60:je,We=A.redirectNavigator,me=We===void 0?new u.RedirectNavigator:We,ge=A.popupNavigator,Be=ge===void 0?new h.PopupNavigator:ge,ie=A.iframeNavigator,B=ie===void 0?new d.IFrameNavigator:ie,N=A.userStore,k=N===void 0?new p.WebStorageStateStore({store:g.Global.sessionStorage}):N;v(this,x);var H=S(this,E.call(this,arguments[0]));return H._popup_redirect_uri=C,H._popup_post_logout_redirect_uri=T,H._popupWindowFeatures=F,H._popupWindowTarget=P,H._silent_redirect_uri=q,H._silentRequestTimeout=O,H._automaticSilentRenew=fe,H._validateSubOnSilentRenew=ee,H._includeIdTokenInSilentRenew=re,H._accessTokenExpiringNotificationTime=He,H._monitorSession=ke,H._monitorAnonymousSession=Oe,H._checkSessionInterval=Ue,H._stopCheckSessionOnError=W,de?H._query_status_response_type=de:arguments[0]&&arguments[0].response_type?H._query_status_response_type=m.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":H._query_status_response_type="id_token",H._revokeAccessTokenOnSignout=Te,H._redirectNavigator=me,H._popupNavigator=Be,H._iframeNavigator=B,H._userStore=k,H}return(function(C,T){if(typeof T!="function"&&T!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof T);C.prototype=Object.create(T&&T.prototype,{constructor:{value:C,enumerable:!1,writable:!0,configurable:!0}}),T&&(Object.setPrototypeOf?Object.setPrototypeOf(C,T):C.__proto__=T)})(x,E),o(x,[{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}}]),x})(l.OidcClientSettings)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.RedirectNavigator=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.RedirectNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(){return Promise.resolve(this)},u.prototype.navigate=function(d){return d&&d.url?(d.useReplaceToNavigate?window.location.replace(d.url):window.location=d.url,Promise.resolve()):(l.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},o(u,[{key:"url",get:function(){return window.location.href}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupNavigator=void 0;var o=s(0),l=s(42);i.PopupNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.PopupWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d,p,g){o.Log.debug("PopupNavigator.callback");try{return l.PopupWindow.notifyOpener(d,p,g),Promise.resolve()}catch(m){return Promise.reject(m)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupWindow=void 0;var o=(function(){function h(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(0),u=s(3);i.PopupWindow=(function(){function h(d){var p=this;(function(S,E){if(!(S instanceof E))throw new TypeError("Cannot call a class as a function")})(this,h),this._promise=new Promise((function(v,S){p._resolve=v,p._reject=S}));var g=d.popupWindowTarget||"_blank",m=d.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",g,m),this._popup&&(l.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return h.prototype.navigate=function(p){return this._popup?p&&p.url?(l.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=p.id,this._id&&(window["popupCallback_"+p.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=p.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},h.prototype._success=function(p){l.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(p)},h.prototype._error=function(p){l.Log.error("PopupWindow.error: ",p),this._cleanup(),this._reject(new Error(p))},h.prototype.close=function(){this._cleanup(!1)},h.prototype._cleanup=function(p){l.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!p&&this._popup.close(),this._popup=null},h.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},h.prototype._callback=function(p,g){this._cleanup(g),p?(l.Log.debug("PopupWindow.callback success"),this._success({url:p})):(l.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},h.notifyOpener=function(p,g,m){if(window.opener){if(p=p||window.location.href){var v=u.UrlUtility.parseUrlFragment(p,m);if(v.state){var S="popupCallback_"+v.state,E=window.opener[S];E?(l.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),E(p,g)):l.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else l.Log.warn("PopupWindow.notifyOpener: no state found in response url")}}else l.Log.warn("PopupWindow.notifyOpener: no window.opener. Can't complete notification.")},o(h,[{key:"promise",get:function(){return this._promise}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameNavigator=void 0;var o=s(0),l=s(44);i.IFrameNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.IFrameWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d){o.Log.debug("IFrameNavigator.callback");try{return l.IFrameWindow.notifyParent(d),Promise.resolve()}catch(p){return Promise.reject(p)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameWindow=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.IFrameWindow=(function(){function u(h){var d=this;(function(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")})(this,u),this._promise=new Promise((function(p,g){d._resolve=p,d._reject=g})),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.width=0,this._frame.height=0,window.document.body.appendChild(this._frame)}return u.prototype.navigate=function(d){if(d&&d.url){var p=d.silentRequestTimeout||1e4;l.Log.debug("IFrameWindow.navigate: Using timeout of:",p),this._timer=window.setTimeout(this._timeout.bind(this),p),this._frame.src=d.url}else this._error("No url provided");return this.promise},u.prototype._success=function(d){this._cleanup(),l.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(d)},u.prototype._error=function(d){this._cleanup(),l.Log.error(d),this._reject(new Error(d))},u.prototype.close=function(){this._cleanup()},u.prototype._cleanup=function(){this._frame&&(l.Log.debug("IFrameWindow: cleanup"),window.removeEventListener("message",this._boundMessageEvent,!1),window.clearTimeout(this._timer),window.document.body.removeChild(this._frame),this._timer=null,this._frame=null,this._boundMessageEvent=null)},u.prototype._timeout=function(){l.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},u.prototype._message=function(d){if(l.Log.debug("IFrameWindow.message"),this._timer&&d.origin===this._origin&&d.source===this._frame.contentWindow&&typeof d.data=="string"&&(d.data.startsWith("http://")||d.data.startsWith("https://"))){var p=d.data;p?this._success({url:p}):this._error("Invalid response from frame")}},u.notifyParent=function(d){l.Log.debug("IFrameWindow.notifyParent"),(d=d||window.location.href)&&(l.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(d,location.protocol+"//"+location.host))},o(u,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerEvents=void 0;var o=s(0),l=s(16),u=s(17);i.UserManagerEvents=(function(h){function d(p){(function(v,S){if(!(v instanceof S))throw new TypeError("Cannot call a class as a function")})(this,d);var g=(function(v,S){if(!v)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!S||typeof S!="object"&&typeof S!="function"?v:S})(this,h.call(this,p));return g._userLoaded=new u.Event("User loaded"),g._userUnloaded=new u.Event("User unloaded"),g._silentRenewError=new u.Event("Silent renew error"),g._userSignedIn=new u.Event("User signed in"),g._userSignedOut=new u.Event("User signed out"),g._userSessionChanged=new u.Event("User session changed"),g}return(function(g,m){if(typeof m!="function"&&m!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof m);g.prototype=Object.create(m&&m.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),m&&(Object.setPrototypeOf?Object.setPrototypeOf(g,m):g.__proto__=m)})(d,h),d.prototype.load=function(g){var m=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];o.Log.debug("UserManagerEvents.load"),h.prototype.load.call(this,g),m&&this._userLoaded.raise(g)},d.prototype.unload=function(){o.Log.debug("UserManagerEvents.unload"),h.prototype.unload.call(this),this._userUnloaded.raise()},d.prototype.addUserLoaded=function(g){this._userLoaded.addHandler(g)},d.prototype.removeUserLoaded=function(g){this._userLoaded.removeHandler(g)},d.prototype.addUserUnloaded=function(g){this._userUnloaded.addHandler(g)},d.prototype.removeUserUnloaded=function(g){this._userUnloaded.removeHandler(g)},d.prototype.addSilentRenewError=function(g){this._silentRenewError.addHandler(g)},d.prototype.removeSilentRenewError=function(g){this._silentRenewError.removeHandler(g)},d.prototype._raiseSilentRenewError=function(g){o.Log.debug("UserManagerEvents._raiseSilentRenewError",g.message),this._silentRenewError.raise(g)},d.prototype.addUserSignedIn=function(g){this._userSignedIn.addHandler(g)},d.prototype.removeUserSignedIn=function(g){this._userSignedIn.removeHandler(g)},d.prototype._raiseUserSignedIn=function(){o.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},d.prototype.addUserSignedOut=function(g){this._userSignedOut.addHandler(g)},d.prototype.removeUserSignedOut=function(g){this._userSignedOut.removeHandler(g)},d.prototype._raiseUserSignedOut=function(){o.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},d.prototype.addUserSessionChanged=function(g){this._userSessionChanged.addHandler(g)},d.prototype.removeUserSessionChanged=function(g){this._userSessionChanged.removeHandler(g)},d.prototype._raiseUserSessionChanged=function(){o.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},d})(l.AccessTokenEvents)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Timer=void 0;var o=(function(){function g(m,v){for(var S=0;S<v.length;S++){var E=v[S];E.enumerable=E.enumerable||!1,E.configurable=!0,"value"in E&&(E.writable=!0),Object.defineProperty(m,E.key,E)}}return function(m,v,S){return v&&g(m.prototype,v),S&&g(m,S),m}})(),l=s(0),u=s(1),h=s(17);function d(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")}function p(g,m){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!m||typeof m!="object"&&typeof m!="function"?g:m}i.Timer=(function(g){function m(v){var S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u.Global.timer,E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;d(this,m);var x=p(this,g.call(this,v));return x._timer=S,x._nowFunc=E||function(){return Date.now()/1e3},x}return(function(S,E){if(typeof E!="function"&&E!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof E);S.prototype=Object.create(E&&E.prototype,{constructor:{value:S,enumerable:!1,writable:!0,configurable:!0}}),E&&(Object.setPrototypeOf?Object.setPrototypeOf(S,E):S.__proto__=E)})(m,g),m.prototype.init=function(S){S<=0&&(S=1),S=parseInt(S);var E=this.now+S;if(this.expiration===E&&this._timerHandle)l.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),l.Log.debug("Timer.init timer "+this._name+" for duration:",S),this._expiration=E;var x=5;S<x&&(x=S),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*x)}},m.prototype.cancel=function(){this._timerHandle&&(l.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},m.prototype._callback=function(){var S=this._expiration-this.now;l.Log.debug("Timer.callback; "+this._name+" timer expires in:",S),this._expiration<=this.now&&(this.cancel(),g.prototype.raise.call(this))},o(m,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),m})(h.Event)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SilentRenewService=void 0;var o=s(0);i.SilentRenewService=(function(){function l(u){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,l),this._userManager=u}return l.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then((function(h){})).catch((function(h){o.Log.error("SilentRenewService.start: Error from getUser:",h.message)})))},l.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},l.prototype._tokenExpiring=function(){var h=this;this._userManager.signinSilent().then((function(d){o.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")}),(function(d){o.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",d.message),h._userManager.events._raiseSilentRenewError(d)}))},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaPopupNavigator=void 0;var o=s(21);i.CordovaPopupNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){var d=new o.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaIFrameNavigator=void 0;var o=s(21);i.CordovaIFrameNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){h.popupWindowFeatures="hidden=yes";var d=new o.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Version="1.11.6"}])}))})(oidcClient_min$1)),oidcClient_min$1.exports}var oidcClient_minExports=requireOidcClient_min();function processErrorResponse(n,e){throw n.error==="invalid_redirect_uri"?new Error(`Dynamic client registration failed: the provided redirect uri [${e.redirectUrl?.toString()}] is invalid - ${n.error_description??""}`):n.error==="invalid_client_metadata"?new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(e)} is invalid - ${n.error_description??""}`):new Error(`Dynamic client registration failed: ${n.error} - ${n.error_description??""}`)}function hasClientId(n){return typeof n.client_id=="string"}function hasRedirectUri(n){return Array.isArray(n.redirect_uris)&&n.redirect_uris.every(e=>typeof e=="string")}function validateRegistrationResponse(n,e){if(!hasClientId(n))throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(n)}`);if(e.redirectUrl&&hasRedirectUri(n)&&n.redirect_uris[0]!==e.redirectUrl.toString())throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(n.redirect_uris)} don't match the provided ${JSON.stringify([e.redirectUrl.toString()])}`);return!0}async function registerClient(n,e){if(!e.registrationEndpoint)throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");if(!Array.isArray(e.idTokenSigningAlgValuesSupported))throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");const t=determineSigningAlg(e.idTokenSigningAlgValuesSupported,PREFERRED_SIGNING_ALG),i={client_name:n.clientName,application_type:"web",redirect_uris:[n.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:t,grant_types:["authorization_code","refresh_token"]},s={"Content-Type":"application/json"},o=await fetch(e.registrationEndpoint.toString(),{method:"POST",headers:s,body:JSON.stringify(i)});if(o.ok){const l=await o.json();return validateRegistrationResponse(l,n),{clientId:l.client_id,clientSecret:l.client_secret,expiresAt:l.client_secret_expires_at,idTokenSignedResponseAlg:l.id_token_signed_response_alg,clientType:"dynamic"}}throw o.status===400&&processErrorResponse(await o.json(),n),new Error(`Dynamic client registration failed: the server returned ${o.status} ${o.statusText} - ${await o.text()}`)}function hasError(n){return n.error!==void 0&&typeof n.error=="string"}function hasErrorDescription(n){return n.error_description!==void 0&&typeof n.error_description=="string"}function hasErrorUri(n){return n.error_uri!==void 0&&typeof n.error_uri=="string"}function hasAccessToken(n){return n.access_token!==void 0&&typeof n.access_token=="string"}function hasIdToken(n){return n.id_token!==void 0&&typeof n.id_token=="string"}function hasRefreshToken(n){return n.refresh_token!==void 0&&typeof n.refresh_token=="string"}function hasTokenType(n){return n.token_type!==void 0&&typeof n.token_type=="string"}function hasExpiresIn(n){return n.expires_in===void 0||typeof n.expires_in=="number"}function validatePreconditions(n,e){if(e.grantType&&(!n.grantTypesSupported||!n.grantTypesSupported.includes(e.grantType)))throw new Error(`The issuer [${n.issuer}] does not support the [${e.grantType}] grant`);if(!n.tokenEndpoint)throw new Error(`This issuer [${n.issuer}] does not have a token endpoint`)}function validateTokenEndpointResponse(n,e){if(hasError(n))throw new OidcProviderError(`Token endpoint returned error [${n.error}]${hasErrorDescription(n)?`: ${n.error_description}`:""}${hasErrorUri(n)?` (see ${n.error_uri})`:""}`,n.error,hasErrorDescription(n)?n.error_description:void 0);if(!hasAccessToken(n))throw new InvalidResponseError(["access_token"]);if(!hasIdToken(n))throw new InvalidResponseError(["id_token"]);if(!hasTokenType(n))throw new InvalidResponseError(["token_type"]);if(!hasExpiresIn(n))throw new InvalidResponseError(["expires_in"]);if(!e&&n.token_type.toLowerCase()!=="bearer")throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${n.token_type}].`);return n}async function getTokens(n,e,t,i){validatePreconditions(n,t);const s={"content-type":"application/x-www-form-urlencoded"};let o;i&&(o=await generateDpopKeyPair(),s.DPoP=await createDpopHeader(n.tokenEndpoint,"POST",o)),e.clientSecret&&(s.Authorization=`Basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`);const l={grant_type:t.grantType,redirect_uri:t.redirectUrl,code:t.code,code_verifier:t.codeVerifier,client_id:e.clientId},u={method:"POST",headers:s,body:new URLSearchParams(l).toString()},d=await(await fetch(n.tokenEndpoint,u)).json(),p=validateTokenEndpointResponse(d,i),{webId:g,clientId:m}=await getWebidFromTokenPayload(p.id_token,n.jwksUri,n.issuer,e.clientId);return{accessToken:p.access_token,idToken:p.id_token,refreshToken:hasRefreshToken(p)?p.refresh_token:void 0,webId:g,clientId:m,dpopKey:o,expiresIn:p.expires_in}}const isValidUrl=n=>{try{return new URL(n),!0}catch{return!1}};async function refresh(n,e,t,i){if(t.clientId===void 0)throw new Error("No client ID available when trying to refresh the access token.");const s={grant_type:"refresh_token",refresh_token:n};let o={};i!==void 0&&(o={DPoP:await createDpopHeader(e.tokenEndpoint,"POST",i)});let l={};t.clientSecret!==void 0?l={Authorization:`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`}:isValidUrl(t.clientId)&&(s.client_id=t.clientId);const u=await fetch(e.tokenEndpoint,{method:"POST",body:new URLSearchParams(s).toString(),headers:{...o,...l,"Content-Type":"application/x-www-form-urlencoded"}});let h;try{h=await u.json()}catch{throw new Error(`The token endpoint of issuer ${e.issuer} returned a malformed response.`)}const d=validateTokenEndpointResponse(h,i!==void 0),{webId:p}=await getWebidFromTokenPayload(d.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:d.access_token,idToken:d.id_token,refreshToken:typeof d.refresh_token=="string"?d.refresh_token:void 0,webId:p,dpopKey:i,expiresIn:d.expires_in}}function normalizeCallbackUrl(n){const e=removeOpenIdParams(n);return e.hash="",n.includes(`${e.origin}/`)?e.href:`${e.origin}${e.href.substring(e.origin.length+1)}`}async function clearOidcPersistentStorage(){await new oidcClient_minExports.OidcClient({response_mode:"query"}).clearStaleState(new oidcClient_minExports.WebStorageStateStore({}));const e=window.localStorage,t=[];for(let i=0;i<=e.length;i+=1){const s=e.key(i);s&&(s.match(/^oidc\..+$/)||s.match(/^solidClientAuthenticationUser:.+$/))&&t.push(s)}t.forEach(i=>e.removeItem(i))}class StorageUtilityBrowser extends StorageUtility{constructor(e,t){super(e,t)}}class ClientAuthentication extends ClientAuthentication$1{login=async(e,t)=>{e.prompt!=="none"&&await this.sessionInfoManager.clear(e.sessionId);const i=e.redirectUrl??normalizeCallbackUrl(window.location.href);if(!isValidRedirectUrl(i))throw new Error(`${i} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);await this.loginHandler.handle({...e,redirectUrl:i,clientName:e.clientName??e.clientId,eventEmitter:t})};validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return t===void 0||t.clientAppId===void 0||t.issuer===void 0?null:t};handleIncomingRedirect=async(e,t)=>{try{const i=await this.redirectHandler.handle(e,t,void 0);return this.fetch=i.fetch.bind(window),this.boundLogout=i.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:i.isLoggedIn,webId:i.webId,sessionId:i.sessionId,expirationDate:i.expirationDate,clientAppId:i.clientAppId}}catch(i){await this.cleanUrlAfterRedirect(e),t.emit(EVENTS.ERROR,"redirect",i);return}};async cleanUrlAfterRedirect(e){const t=removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(i=>{setTimeout(()=>i(),1)})}}function hasIssuer(n){return typeof n.oidcIssuer=="string"}function hasRedirectUrl(n){return typeof n.redirectUrl=="string"}class OidcLoginHandler{storageUtility;oidcHandler;issuerConfigFetcher;clientRegistrar;constructor(e,t,i,s){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s}async canHandle(e){return hasIssuer(e)&&hasRedirectUrl(e)}async handle(e){if(!hasIssuer(e))throw new ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!hasRedirectUrl(e))throw new ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),i=await handleRegistration(e,t,this.storageUtility,this.clientRegistrar),s={issuer:t.issuer,dpop:e.tokenType.toLowerCase()==="dpop",...e,issuerConfiguration:t,client:i,scopes:normalizeScopes(e.customScopes)};return this.oidcHandler.handle(s)}}class AuthorizationCodeWithPkceOidcHandler extends AuthorizationCodeWithPkceOidcHandlerBase{async handle(e){const t={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:e.prompt??"consent"},i=new oidcClient_minExports.OidcClient(t);try{const s=await i.createSigninRequest();return await this.setupRedirectHandler({oidcLoginOptions:e,state:s.state._id,codeVerifier:s.state._code_verifier,targetUrl:s.url.toString()})}catch(s){console.error(s)}}}const WELL_KNOWN_OPENID_CONFIG=".well-known/openid-configuration",issuerConfigKeyMap={issuer:{toKey:"issuer",convertToUrl:!0},authorization_endpoint:{toKey:"authorizationEndpoint",convertToUrl:!0},token_endpoint:{toKey:"tokenEndpoint",convertToUrl:!0},userinfo_endpoint:{toKey:"userinfoEndpoint",convertToUrl:!0},jwks_uri:{toKey:"jwksUri",convertToUrl:!0},registration_endpoint:{toKey:"registrationEndpoint",convertToUrl:!0},end_session_endpoint:{toKey:"endSessionEndpoint",convertToUrl:!0},scopes_supported:{toKey:"scopesSupported"},response_types_supported:{toKey:"responseTypesSupported"},response_modes_supported:{toKey:"responseModesSupported"},grant_types_supported:{toKey:"grantTypesSupported"},acr_values_supported:{toKey:"acrValuesSupported"},subject_types_supported:{toKey:"subjectTypesSupported"},id_token_signing_alg_values_supported:{toKey:"idTokenSigningAlgValuesSupported"},id_token_encryption_alg_values_supported:{toKey:"idTokenEncryptionAlgValuesSupported"},id_token_encryption_enc_values_supported:{toKey:"idTokenEncryptionEncValuesSupported"},userinfo_signing_alg_values_supported:{toKey:"userinfoSigningAlgValuesSupported"},userinfo_encryption_alg_values_supported:{toKey:"userinfoEncryptionAlgValuesSupported"},userinfo_encryption_enc_values_supported:{toKey:"userinfoEncryptionEncValuesSupported"},request_object_signing_alg_values_supported:{toKey:"requestObjectSigningAlgValuesSupported"},request_object_encryption_alg_values_supported:{toKey:"requestObjectEncryptionAlgValuesSupported"},request_object_encryption_enc_values_supported:{toKey:"requestObjectEncryptionEncValuesSupported"},token_endpoint_auth_methods_supported:{toKey:"tokenEndpointAuthMethodsSupported"},token_endpoint_auth_signing_alg_values_supported:{toKey:"tokenEndpointAuthSigningAlgValuesSupported"},display_values_supported:{toKey:"displayValuesSupported"},claim_types_supported:{toKey:"claimTypesSupported"},claims_supported:{toKey:"claimsSupported"},service_documentation:{toKey:"serviceDocumentation"},claims_locales_supported:{toKey:"claimsLocalesSupported"},ui_locales_supported:{toKey:"uiLocalesSupported"},claims_parameter_supported:{toKey:"claimsParameterSupported"},request_parameter_supported:{toKey:"requestParameterSupported"},request_uri_parameter_supported:{toKey:"requestUriParameterSupported"},require_request_uri_registration:{toKey:"requireRequestUriRegistration"},op_policy_uri:{toKey:"opPolicyUri",convertToUrl:!0},op_tos_uri:{toKey:"opTosUri",convertToUrl:!0}};function processConfig(n){const e={};return Object.keys(n).forEach(t=>{issuerConfigKeyMap[t]&&(e[issuerConfigKeyMap[t].toKey]=n[t])}),Array.isArray(e.scopesSupported)||(e.scopesSupported=["openid"]),e}class IssuerConfigFetcher{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}static getLocalStorageKey(e){return`issuerConfig:${e}`}async fetchConfig(e){let t;const i=new URL(WELL_KNOWN_OPENID_CONFIG,e.endsWith("/")?e:`${e}/`).href,s=await fetch(i);try{t=processConfig(await s.json())}catch(o){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${o.message}`)}return await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t}}async function clear(n,e){await clear$1(n,e),await clearOidcPersistentStorage()}class SessionInfoManager extends SessionInfoManagerBase{async get(e){const[t,i,s,o,l,u,h,d]=await Promise.all([this.storageUtility.getForUser(e,"isLoggedIn",{secure:!0}),this.storageUtility.getForUser(e,"webId",{secure:!0}),this.storageUtility.getForUser(e,"clientId",{secure:!1}),this.storageUtility.getForUser(e,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e,"redirectUrl",{secure:!1}),this.storageUtility.getForUser(e,"refreshToken",{secure:!0}),this.storageUtility.getForUser(e,"issuer",{secure:!1}),this.storageUtility.getForUser(e,"tokenType",{secure:!1})]);if(typeof l=="string"&&!isValidRedirectUrl(l)){await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})]);return}if(d!==void 0&&!isSupportedTokenType(d))throw new Error(`Tokens of type [${d}] are not supported.`);if(!(s===void 0&&t===void 0&&i===void 0&&u===void 0))return{sessionId:e,webId:i,isLoggedIn:t==="true",redirectUrl:l,refreshToken:u,issuer:h,clientAppId:s,clientAppSecret:o,tokenType:d??"DPoP"}}async clear(e){return clear(e,this.storageUtility)}}class FallbackRedirectHandler{async canHandle(e){try{return new URL(e),!0}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e){return getUnauthenticatedSession()}}class AuthCodeRedirectHandler{storageUtility;sessionInfoManager;issuerConfigFetcher;clientRegistrar;tokerRefresher;fetch;constructor(e,t,i,s,o,l){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=o,this.fetch=l,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=o}async canHandle(e){try{const t=new URL(e);return t.searchParams.get("code")!==null&&t.searchParams.get("state")!==null}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(!await this.canHandle(e))throw new Error(`AuthCodeRedirectHandler cannot handle [${e}]: it is missing one of [code, state].`);const i=new URL(e),s=i.searchParams.get("state"),o=await this.storageUtility.getForUser(s,"sessionId",{errorIfNull:!0}),{issuerConfig:l,codeVerifier:u,redirectUrl:h,dpop:d}=await loadOidcContextFromStorage(o,this.storageUtility,this.issuerConfigFetcher),p=i.searchParams.get("iss");if(typeof p=="string"&&p!==l.issuer)throw new Error(`The value of the iss parameter (${p}) does not match the issuer identifier of the authorization server (${l.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(u===void 0)throw new Error(`The code verifier for session ${o} is missing from storage.`);if(h===void 0)throw new Error(`The redirect URL for session ${o} is missing from storage.`);const g=await this.clientRegistrar.getClient({sessionId:o},l),m=Date.now(),v=await getTokens(l,g,{grantType:"authorization_code",code:i.searchParams.get("code"),codeVerifier:u,redirectUrl:h},d);window.localStorage.removeItem(`oidc.${s}`);let S;v.refreshToken!==void 0&&(S={sessionId:o,refreshToken:v.refreshToken,tokenRefresher:this.tokerRefresher});const E=buildAuthenticatedFetch(v.accessToken,{dpopKey:v.dpopKey,refreshOptions:S,eventEmitter:t,expiresIn:v.expiresIn,fetch:this.fetch});await saveSessionInfoToStorage(this.storageUtility,o,v.webId,v.clientId,"true",void 0,!0);const x=await this.sessionInfoManager.get(o);if(!x)throw new Error(`Could not retrieve session: [${o}].`);return Object.assign(x,{fetch:E,getLogoutUrl:maybeBuildRpInitiatedLogout({idTokenHint:v.idToken,endSessionEndpoint:l.endSessionEndpoint}),expirationDate:typeof v.expiresIn=="number"?m+v.expiresIn*1e3:void 0})}}class AggregateRedirectHandler extends AggregateHandler{constructor(e){super(e)}}class BrowserStorage{get storage(){return window.localStorage}async get(e){return this.storage.getItem(e)||void 0}async set(e,t){this.storage.setItem(e,t)}async delete(e){this.storage.removeItem(e)}}class Redirector{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class ClientRegistrar{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[i,s,o,l,u]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"expiresAt",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]),h=o!==void 0?Number.parseInt(o,10):-1,d=s!==void 0&&h!==0&&Math.floor(Date.now()/1e3)>h;if(i&&isKnownClientType(u)&&!d)return s!==void 0?{clientId:i,clientSecret:s,clientName:l,clientType:"dynamic",expiresAt:h}:{clientId:i,clientName:l,clientType:u};try{const p=await registerClient(e,t),g={clientId:p.clientId,clientType:"dynamic"};return p.clientSecret!==void 0&&(g.clientSecret=p.clientSecret,g.expiresAt=String(p.expiresAt)),p.idTokenSignedResponseAlg&&(g.idTokenSignedResponseAlg=p.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,g,{secure:!1}),p}catch(p){throw new Error("Client registration failed.",{cause:p})}}}class ErrorOidcHandler{async canHandle(e){try{return new URL(e).searchParams.has("error")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(t!==void 0){const i=new URL(e),s=i.searchParams.get("error"),o=i.searchParams.get("error_description");t.emit(EVENTS.ERROR,s,o)}return getUnauthenticatedSession()}}class TokenRefresher{storageUtility;issuerConfigFetcher;clientRegistrar;constructor(e,t,i){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i}async refresh(e,t,i,s){const o=await loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),l=await this.clientRegistrar.getClient({sessionId:e},o.issuerConfig);if(t===void 0)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(o.dpop&&i===void 0)throw new Error(`For session [${e}], the key bound to the DPoP access token must be provided to refresh said access token.`);const u=await refresh(t,o.issuerConfig,l,i);return u.refreshToken!==void 0&&s?.emit(EVENTS.NEW_REFRESH_TOKEN,u.refreshToken),u}}function getClientAuthenticationWithDependencies(n){const e=new InMemoryStorage,t=n.secureStorage||e,i=n.insecureStorage||new BrowserStorage,s=new StorageUtilityBrowser(t,i),o=new IssuerConfigFetcher(s),l=new ClientRegistrar(s),u=new SessionInfoManager(s),h=new TokenRefresher(s,o,l),d=new Redirector,p=new OidcLoginHandler(s,new AuthorizationCodeWithPkceOidcHandler(s,d),o,l),g=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(s,u,o,l,h,n.fetch),new FallbackRedirectHandler]);return new ClientAuthentication(p,g,new IWaterfallLogoutHandler(u,d),u,o)}const KEY_CURRENT_SESSION=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`,KEY_CURRENT_URL=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;async function silentlyAuthenticate(n,e,t){const i=await e.validateCurrentSession(n);return i!==null?(window.localStorage.setItem(KEY_CURRENT_URL,window.location.href),await e.login({sessionId:n,prompt:"none",oidcIssuer:i.issuer,redirectUrl:i.redirectUrl,clientId:i.clientAppId,clientSecret:i.clientAppSecret,tokenType:i.tokenType??"DPoP"},t.events),!0):!1}function isLoggedIn(n){return!!n?.isLoggedIn}class Session{info;events;clientAuthentication;tokenRequestInProgress=!1;xpodErrorLogout=Promise.resolve();constructor(e={},t=void 0){this.events=new EventEmitter,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=getClientAuthenticationWithDependencies({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage,fetch:e.fetch}):this.clientAuthentication=getClientAuthenticationWithDependencies({fetch:e.fetch}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??v4(),isLoggedIn:!1},this.events.on(EVENTS.LOGIN,()=>window.localStorage.setItem(KEY_CURRENT_SESSION,this.info.sessionId)),this.events.on(EVENTS.SESSION_EXPIRED,()=>this.internalLogout(!1)),this.events.on(EVENTS.ERROR,()=>{this.xpodErrorLogout=this.xpodErrorLogout.then(()=>this.internalLogout(!1),()=>this.internalLogout(!1)),this.xpodErrorLogout.catch(()=>{})})}login=async e=>(await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:e.tokenType??"DPoP"},this.events),new Promise(()=>{}));fetch=(e,t)=>this.clientAuthentication.fetch(e,t);internalLogout=async(e,t)=>{window.localStorage.removeItem(KEY_CURRENT_SESSION),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(EVENTS.LOGOUT)};logout=async e=>this.internalLogout(!0,e);handleIncomingRedirect=async(e={})=>{if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const t=typeof e=="string"?{url:e}:e,i=t.url??window.location.href;this.tokenRequestInProgress=!0;const s=await this.clientAuthentication.handleIncomingRedirect(i,this.events);try{await this.xpodErrorLogout}catch(o){throw this.tokenRequestInProgress=!1,o}if(isLoggedIn(s)){this.setSessionInfo(s);const o=window.localStorage.getItem(KEY_CURRENT_URL);o===null?this.events.emit(EVENTS.LOGIN):(window.localStorage.removeItem(KEY_CURRENT_URL),this.events.emit(EVENTS.SESSION_RESTORED,o))}else if(t.restorePreviousSession===!0){const o=window.localStorage.getItem(KEY_CURRENT_SESSION);if(o!==null&&await silentlyAuthenticate(o,this.clientAuthentication,this))return new Promise(()=>{})}return this.tokenRequestInProgress=!1,s};setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.clientAppId=e.clientAppId,this.info.expirationDate=e.expirationDate,this.events.on(EVENTS.SESSION_EXTENDED,t=>{this.info.expirationDate=Date.now()+t*1e3})}}function snapshotFromSessionInfo(n){return n?.isLoggedIn&&n.webId?{status:"authenticated",webId:n.webId}:{status:"anonymous"}}function normalizeError(n){return n instanceof Error?n:new Error(String(n))}function snapshotFromSessionError(n,e){return{status:"error",webId:e.webId,error:normalizeError(n)}}function snapshotFromSessionExpired(n){return{status:"expired",...n.webId===void 0?{}:{webId:n.webId}}}function areSnapshotsEqual(n,e){return!n||n.status!==e.status||n.webId!==e.webId?!1:n.status==="error"&&e.status==="error"?n.error===e.error:!0}function createSolidSessionRuntime(n={}){const e=n.session??new Session,t=new Set;let i={status:"initializing"},s,o,l=!1,u=!1,h,d=!1,p=0,g=!1,m=0,v=0,S;const E=()=>{p+=1,g=!0},x=q=>{if(d||((q.status!=="authenticated"||i.status!=="authenticated"||i.webId!==q.webId)&&E(),q.status==="authenticated"&&(g=!1),i=q,areSnapshotsEqual(s,i)))return i;s=i;for(const O of t)O(i);return i},A=()=>{if(S){if(S.generation!==v||S.eventWebId&&S.eventWebId!==e.info.webId)return i;S.eventWebId=e.info.webId}return E(),s=void 0,x(snapshotFromSessionInfo(e.info))},C=()=>(v+=1,x({status:"anonymous"})),T=()=>(v+=1,x(snapshotFromSessionExpired(e.info))),F=(q,O)=>{v+=1;const G=snapshotFromSessionError(O??q??"Solid session error",e.info);u&&(h=G),x(G)};e.events.on(EVENTS.LOGIN,A),e.events.on(EVENTS.SESSION_RESTORED,A),e.events.on(EVENTS.LOGOUT,C),e.events.on(EVENTS.SESSION_EXPIRED,T);const P=e.events;return P.on(EVENTS.ERROR,F),{fetch:e.fetch,createAuthenticatedFetch(q){const O=p,G=()=>{if(d||m>0||g||O!==p||i.status!=="authenticated"||i.webId!==q||!e.info.isLoggedIn||e.info.webId!==q){const fe=new Error("Authenticated session is no longer current");throw fe.name="AbortError",fe}};return async(fe,M)=>{G();const ee=await(M===void 0?e.fetch(fe):e.fetch(fe,M));try{G()}catch(Se){throw ee.body?.cancel().catch(()=>{}),Se}return ee}},getSnapshot(){return i},initialize(q={}){if(o)return o;if(l||d)return Promise.resolve(i);const O={generation:++v,eventWebId:void 0};S=O;const G=M=>!d&&O.generation===v&&(!M?.isLoggedIn||!O.eventWebId||O.eventWebId===M.webId);u=!0,h=void 0,x({status:"initializing"});const fe=e.handleIncomingRedirect({restorePreviousSession:q.restorePreviousSession??!0}).then(M=>{if(!G(M??e.info))return i;const ee=snapshotFromSessionInfo(M??e.info);return ee.status==="anonymous"&&h?.status==="error"?h:(l=!0,x(ee))}).catch(M=>G()?x(snapshotFromSessionError(M,e.info)):i).finally(()=>{o===fe&&(S===O&&(S=void 0),o=void 0,u=!1,h=void 0)});return o=fe,o},handleIncomingRedirect(q){if(o)return o;if(d)return Promise.resolve(i);const O={generation:++v,eventWebId:void 0};S=O;const G=M=>!d&&O.generation===v&&(!M?.isLoggedIn||!O.eventWebId||O.eventWebId===M.webId);u=!0,h=void 0,x({status:"initializing"});const fe=e.handleIncomingRedirect(q).then(M=>{if(!G(M??e.info))return i;const ee=snapshotFromSessionInfo(M??e.info);return ee.status==="anonymous"&&h?.status==="error"?h:(l=!0,x(ee))}).catch(M=>G()?x(snapshotFromSessionError(M,e.info)):i).finally(()=>{o===fe&&(S===O&&(S=void 0),o=void 0,u=!1,h=void 0)});return o=fe,fe},async login(q){v+=1,E(),m+=1;try{if(o){const O=new Error("Previous login is still completing. Reload before reconnecting.");throw O.name="SolidSessionPendingError",O}if(d)throw new Error("Solid session runtime is disposed");await e.login(q)}catch(O){throw x(snapshotFromSessionError(O,e.info)),O}finally{m-=1}},async logout(q){v+=1,E(),m+=1;try{await e.logout(q),x({status:"anonymous"})}catch(O){throw x(snapshotFromSessionError(O,e.info)),O}finally{m-=1}},subscribe(q){return t.add(q),()=>{t.delete(q)}},dispose(){v+=1,E(),d=!0,t.clear(),e.events.off(EVENTS.LOGIN,A),e.events.off(EVENTS.SESSION_RESTORED,A),e.events.off(EVENTS.LOGOUT,C),e.events.off(EVENTS.SESSION_EXPIRED,T),P.off(EVENTS.ERROR,F)}}}const ENDPOINT_PROTOCOLS=new Set(["http:","https:"]),RESERVED_AUTHORIZATION_PARAMETERS=new Set(["state","redirect_uri","client_id","response_type","code_challenge","code_challenge_method"]);function normalizeEndpoint(n,e){if(!n||typeof n.url!="string"||n.url.trim()==="")throw new TypeError(`${e}.url must be a non-empty absolute URL`);if(typeof n.label!="string")throw new TypeError(`${e}.label must be a string`);let t;try{t=new URL(n.url.trim())}catch{throw new TypeError(`${e}.url must be a valid absolute URL`)}if(!ENDPOINT_PROTOCOLS.has(t.protocol))throw new TypeError(`${e}.url must use http or https`);if(t.username||t.password)throw new TypeError(`${e}.url must not contain credentials`);if(t.hash)throw new TypeError(`${e}.url must not contain a fragment`);return{url:t.href,label:n.label}}function validateWebId(n){if(typeof n!="string"||n===""||/[\s\u0000-\u001f\u007f-\u009f]/u.test(n))throw new TypeError("webId must be a non-empty identifier without whitespace or control characters");return n}function normalizeStorageBinding(n){if(!n||typeof n.storageUrl!="string"||n.storageUrl.trim()==="")throw new TypeError("selectedStorage.storageUrl must be a non-empty absolute URL");validateWebId(n.webId);let e;try{e=new URL(n.storageUrl.trim())}catch{throw new TypeError("selectedStorage.storageUrl must be a valid absolute URL")}if(!ENDPOINT_PROTOCOLS.has(e.protocol))throw new TypeError("selectedStorage.storageUrl must use http or https");if(e.username||e.password)throw new TypeError("selectedStorage.storageUrl must not contain credentials");if(e.hash)throw new TypeError("selectedStorage.storageUrl must not contain a fragment");return{storageUrl:e.href,webId:n.webId,...n.label===void 0?{}:{label:n.label}}}function ensureEnum(n,e,t){if(!e.includes(n))throw new TypeError(`${t} has an unsupported value`);return n}function normalizeWebIdLoginRoute(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("route.id must be a non-empty opaque identifier");if(typeof n.label!="string")throw new TypeError("route.label must be a string");return{id:n.id.trim(),label:n.label,...n.description===void 0?{}:{description:n.description},...n.badge===void 0?{}:{badge:{label:n.badge.label,tone:ensureEnum(n.badge.tone,["neutral","primary","success","warning","danger"],"route.badge.tone")}},identityProvider:normalizeEndpoint(n.identityProvider,"route.identityProvider"),...n.storageProvider===void 0?{}:{storageProvider:normalizeEndpoint(n.storageProvider,"route.storageProvider")},availability:ensureEnum(n.availability,["ready","starting","unavailable"],"route.availability"),...n.unavailableReason===void 0?{}:{unavailableReason:n.unavailableReason}}}function decodeForValidation$1(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}function matchesAllowedPrefix(n,e){return e.some(t=>{if(t==="/")return n.startsWith("/");const i=t.endsWith("/")?t.slice(0,-1):t;return n===i||n.startsWith(`${i}/`)})}function normalizeApplicationReturnTo(n,e){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const t=n.trim(),i=decodeForValidation$1(t),s=i.split(/[?#]/,1)[0];if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||i.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(i)||i.startsWith("//")||s.split("/").some(o=>o==="..")||!matchesAllowedPrefix(s,e))throw new TypeError("returnTo must be a safe path within the application allow-list");return t}function normalizeWebIdLoginTransaction(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("transaction.id must be a non-empty opaque identifier");const e=n.authorizationParameters===void 0?void 0:{...n.authorizationParameters};if(e){for(const i of Object.keys(e))if(RESERVED_AUTHORIZATION_PARAMETERS.has(i.toLowerCase()))throw new TypeError(`authorizationParameters cannot override ${i}`)}const t=n.prompt===void 0?void 0:ensureEnum(n.prompt,["login","consent","select_account"],"transaction.prompt");return{id:n.id,route:normalizeWebIdLoginRoute(n.route),...n.selectedStorage===void 0?{}:{selectedStorage:normalizeStorageBinding(n.selectedStorage)},authorizationSurface:ensureEnum(n.authorizationSurface,["redirect","popup","embedded","external"],"transaction.authorizationSurface"),...t===void 0?{}:{prompt:t},discovery:ensureEnum(n.discovery,["standard","strict"],"transaction.discovery"),...e===void 0?{}:{authorizationParameters:e},...n.returnTo===void 0?{}:{returnTo:normalizeApplicationReturnTo(n.returnTo,["/"])}}}const KEY_SEPARATOR="\0";function normalizePodUrl(n){if(typeof n!="string"||n.trim()==="")throw new TypeError("podUrl must be a non-empty absolute URL");let e;try{e=new URL(n.trim())}catch{throw new TypeError("podUrl must be a valid absolute URL")}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("podUrl must use http or https");if(e.username||e.password||e.hash)throw new TypeError("podUrl must not contain credentials or a fragment");return e.href}function compositeKey(n,e){return`${n}${KEY_SEPARATOR}${e}`}function nextGeneration(n,e){const t=(n.get(e)??0)+1;return n.set(e,t),t}function createAbortedOpenError(){const n=new Error("Pod open aborted because the runtime identity changed");return n.name="AbortError",n}function createPodRuntime(n){const{adapter:e}=n,t=new Map,i=new Map,s=new Map,o=new Map,l=new Map,u=new Map,h=(g,m)=>{const v=validateWebId(g);if(m!==void 0){const x=normalizePodUrl(m),A=compositeKey(g,x);nextGeneration(u,A),o.get(A)?.controller.abort(),o.delete(A),i.delete(A);const C=t.get(v);C&&compositeKey(C.webId,C.podUrl)===A&&t.delete(v);return}nextGeneration(l,v),s.get(v)?.controller.abort(),s.delete(v);const S=t.get(v);S&&i.delete(compositeKey(S.webId,S.podUrl)),t.delete(v);const E=`${v}${KEY_SEPARATOR}`;for(const x of[...i.keys()])x.startsWith(E)&&i.delete(x);for(const[x,A]of[...o.entries()])x.startsWith(E)&&(nextGeneration(u,x),A.controller.abort(),o.delete(x))},d=g=>{if(g===void 0){t.clear(),i.clear();for(const m of s.values())m.controller.abort();for(const m of o.values())m.controller.abort();s.clear(),o.clear();for(const m of l.keys())nextGeneration(l,m);for(const m of u.keys())nextGeneration(u,m);return}if(typeof g=="string"){h(g);return}h(g.webId,g.podUrl)};return{open(g){const m=validateWebId(g.webId),v=g.podUrl===void 0?void 0:normalizePodUrl(g.podUrl);if(v!==void 0){const q=compositeKey(g.webId,v),O=i.get(q);if(O)return Promise.resolve(O);const G=o.get(q);if(G)return G.promise;const fe=u.get(q)??0;u.set(q,fe);const M=new AbortController,ee=()=>!M.signal.aborted&&(u.get(q)??0)===fe,Se=()=>{if(!ee())throw createAbortedOpenError()},re=p({webId:g.webId,podUrl:v,fetch:g.fetch,signal:M.signal,isCurrent:ee,assertCurrent:Se});o.set(q,{generation:fe,promise:re,controller:M});const Ae=()=>{const ke=o.get(q);ke?.generation===fe&&ke.promise===re&&o.delete(q)};return re.then(Ae,Ae),re}const S=t.get(m);if(S)return Promise.resolve(S);const E=s.get(m);if(E)return E.promise;const x=l.get(m)??0;l.set(m,x);const A=new AbortController,C=()=>!A.signal.aborted&&(l.get(m)??0)===x,T=()=>{if(!C())throw createAbortedOpenError()},F=(async()=>{const q=await e.discoverPod({webId:g.webId,fetch:g.fetch,signal:A.signal,isCurrent:C});return T(),p({webId:g.webId,podUrl:normalizePodUrl(q),fetch:g.fetch,signal:A.signal,isCurrent:C,assertCurrent:T,generation:x,webIdKey:m,discovered:!0})})();s.set(m,{generation:x,promise:F,controller:A});const P=()=>{const q=s.get(m);q?.generation===x&&q.promise===F&&s.delete(m)};return F.then(P,P),F},clear:d,dispose(){d()}};async function p(g){const m=compositeKey(g.webId,g.podUrl),v=i.get(m);if(v)return g.discovered&&g.webIdKey&&g.isCurrent()&&t.set(g.webIdKey,v),v;const S=await e.openDatabase({webId:g.webId,podUrl:g.podUrl,fetch:g.fetch,signal:g.signal,isCurrent:g.isCurrent});g.assertCurrent(),await e.hydrateCollections({webId:g.webId,podUrl:g.podUrl,database:S,signal:g.signal,isCurrent:g.isCurrent}),g.assertCurrent();const E={webId:g.webId,podUrl:g.podUrl,database:S,collections:"ready"};return g.isCurrent()&&(i.set(m,E),g.discovered&&g.webIdKey&&t.set(g.webIdKey,E)),E}}const SolidRuntimeContext=reactExports.createContext(null);function SolidRuntimeProvider({value:n,children:e}){return reactExports.createElement(SolidRuntimeContext.Provider,{value:n},e)}const SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER="x-xpod-canonical-url",SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER="x-xpod-canonical-origin",SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER="x-xpod-canonical-host",SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER="x-xpod-local-route-url";async function discoverSolidLocalRoute(n){let e;try{e=await n.fetch.call(globalThis,n.statusUrl??"/provision/status",{credentials:"include",headers:{accept:"application/json"}})}catch{return}if(!e?.ok)return;const t=await e.json().catch(()=>{});if(typeof t?.publicUrl=="string")try{return normalizeRoute({canonicalBaseUrl:t.publicUrl,localBaseUrl:n.localBaseUrl})}catch{return}}function resolveSolidLocalRouteUrl(n,e){let t;try{t=n instanceof URL?new URL(n.href):new URL(n)}catch{return}const i=e.map(normalizeRoute).filter(s=>isInsideBase(t,s.canonicalBaseUrl)).sort((s,o)=>o.canonicalBaseUrl.length-s.canonicalBaseUrl.length)[0];return i?replaceBase(t,i):void 0}function createSolidLocalRouteFetch(n){return async(e,t)=>{const i=requestUrl(e);if(!i)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const s=n.routes(),o=resolveSolidLocalRouteUrl(i,s);if(!o)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const l=routedHeaders(e,t,i,o);let u;if(e instanceof Request){const d=new Request(new Request(o,e),{headers:l});u=t===void 0?await n.fetch.call(globalThis,d):await n.fetch.call(globalThis,d,{...t,headers:l})}else u=await n.fetch.call(globalThis,o,{...t,headers:l});const h=resolveSolidLocalRouteUrl(u.url,s.map(d=>({canonicalBaseUrl:d.localBaseUrl,localBaseUrl:d.canonicalBaseUrl})));return h?withResponseUrl(u,h.href):u}}function withResponseUrl(n,e){const t=n.clone.bind(n);return Object.defineProperties(n,{url:{value:e,configurable:!0},clone:{value:()=>withResponseUrl(t(),e),configurable:!0}}),n}function requestUrl(n){if(n instanceof Request)return new URL(n.url);try{return new URL(String(n))}catch{return}}function normalizeRoute(n){return{canonicalBaseUrl:normalizeBaseUrl(n.canonicalBaseUrl),localBaseUrl:normalizeBaseUrl(n.localBaseUrl)}}function normalizeBaseUrl(n){const e=new URL(n);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("Solid local routes must use http or https");return e.search="",e.hash="",e.href.endsWith("/")?e.href:`${e.href}/`}function isInsideBase(n,e){const t=new URL(e);return n.origin===t.origin&&n.pathname.startsWith(t.pathname)}function replaceBase(n,e){const t=new URL(e.canonicalBaseUrl),i=new URL(e.localBaseUrl),s=n.pathname.slice(t.pathname.length),o=new URL(s,i);return o.search=n.search,o.hash=n.hash,o}function routedHeaders(n,e,t,i){const s=n instanceof Request?n:void 0,o=new Headers(s?.headers??void 0);return new Headers(e?.headers??void 0).forEach((l,u)=>o.set(u,l)),o.set(SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER,t.toString()),o.set(SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER,t.origin),o.set(SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER,t.host),o.set(SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER,i.toString()),o}SCHEMA.image,UDFS.hasContact,WF.participant,UDFS.metadata,UDFS.favorite,UDFS.muted,UDFS.unreadCount,UDFS.lastActiveAt,UDFS.lastMessage,SCHEMA.text;SIOC.has_parent,SIOC.has_member,WF.message,UDFS.messageType,SIOC.content,SIOC.richContent,UDFS.messageStatus,SCHEMA.dateDeleted,UDFS.senderName,UDFS.senderAvatarUrl,UDFS.mentions,UDFS.replyTo,UDFS.routedBy,UDFS.routeTargetAgent,UDFS.coordinationId;SCHEMA.about,UDFS.contactType,AS.audience,UDFS.externalPlatform,UDFS.externalId,UDFS.alias,UDFS.favorite,UDFS.sortKey,UDFS.deletedAt,UDFS.lastSyncedAt;SIOC.has_parent,UDFS.favorite,UDFS.metadata,UDFS.workspace,SIOC.Thread;UDFS.actor,UDFS.conversation,UDFS.inThread,UDFS.sessionStatus,UDFS.sessionTool,UDFS.tokenUsage,UDFS.message,UDFS.policy,UDFS.policyVersion,UDFS.metadata,UDFS.archivedAt;UDFS.instruction,UDFS.prompt,UDFS.issue,UDFS.message,UDFS.workspace,UDFS.status,UDFS.priority,UDFS.assignedTo,UDFS.source,UDFS.metadata;UDFS.task,UDFS.status,UDFS.scheduleKind,UDFS.cron,UDFS.intervalSeconds,UDFS.timezone,UDFS.startsAt,UDFS.nextRunAt,UDFS.lastRunAt,UDFS.metadata;UDFS.status,UDFS.ruleKind,UDFS.task,UDFS.schedule,UDFS.source,UDFS.target,UDFS.condition,UDFS.actions,UDFS.metadata,UDFS.lastTriggeredAt,UDFS.lastRunStatus;UDFS.deliveryKind,UDFS.status,UDFS.task,UDFS.source,AS.target,UDFS.conversation,UDFS.inThread,UDFS.targetThread,UDFS.targetSession,AS.actor,AS.object,UDFS.objective,UDFS.payload,UDFS.projection,UDFS.projectedRole,UDFS.metadata,UDFS.error,UDFS.startedAt,UDFS.consumedAt,UDFS.completedAt;UDFS.task,UDFS.delivery,UDFS.trigger,UDFS.input,UDFS.inThread,UDFS.workspace,UDFS.status,UDFS.runner,UDFS.prompt,UDFS.externalRunId,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.heartbeatAt,UDFS.cancelRequestedAt,UDFS.error,UDFS.metadata,UDFS.startedAt,UDFS.completedAt;UDFS.evidenceKind,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.outcome,UDFS.metadata;UDFS.reportKind,UDFS.status,UDFS.outcome,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.evidence,SCHEMA.reviewedBy,UDFS.metricFacts,UDFS.metadata;UDFS.run,UDFS.stepType,UDFS.payload;UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.status,UDFS.sourceHash,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,UDFS.metadata;UDFS.captureCandidate,UDFS.targetResource,UDFS.captureDecision,UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.userCorrection,UDFS.approval,UDFS.inputRequest,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,SCHEMA.about,UDFS.metadata;UDFS.session,UDFS.toolCallId,UDFS.toolName,ODRL.target,ODRL.action,UDFS.risk,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.reason,UDFS.context,UDFS.approvalOptions,UDFS.policyVersion,UDFS.expiresAt,UDFS.resolvedAt;UDFS.session,UDFS.conversation,UDFS.inThread,UDFS.run,UDFS.task,UDFS.requester,UDFS.requestKind,UDFS.prompt,UDFS.context,UDFS.inputOptions,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.response,UDFS.answeredBy,UDFS.onBehalfOf,UDFS.reason,UDFS.metadata,UDFS.expiresAt,UDFS.resolvedAt;UDFS.action,UDFS.actor,UDFS.actorRole,UDFS.onBehalfOf,UDFS.session,UDFS.entry,UDFS.toolCallId,UDFS.toolName,UDFS.approval,UDFS.policy,UDFS.policyVersion;ODRL.target,ODRL.action,UDFS.pageKind,UDFS.status,UDFS.tags,UDFS.sourceKind,UDFS.sourceHash,UDFS.compiledAt,UDFS.compiledFrom,UDFS.effect,UDFS.riskCeiling,UDFS.policy,UDFS.context,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.revokedAt,UDFS.disabledAt;UDFS.summary,UDFS.body,UDFS.source,UDFS.related;AS.actor,AS.object;UDFS.Note,SIOC.about,UDFS.noteKind,UDFS.sourceKey,UDFS.fingerprint,UDFS.readerEngine,UDFS.readerVersion,UDFS.generatedWithModel,UDFS.sourceHash,UDFS.readerOptionsHash,UDFS.representationHash,UDFS.representationMediaType,UDFS.coverageUnit,UDFS.coveredRange,UDFS.readUnits,UDFS.totalUnits,UDFS.status;const ContactClass={PERSON:UDFS.PersonContact,AGENT:UDFS.AgentContact,GROUP:UDFS.GroupContact},contactResource=podTable("contact",{id:id("id").default("{key}.ttl"),name:string$2("name").predicate(VCARD.fn).notNull(),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),about:uri("about").predicate(SCHEMA.about).notNull(),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([ContactClass.PERSON]),contactType:string$2("contactType").predicate(UDFS.contactType).notNull(),isPublic:boolean$2("isPublic").predicate(AS.audience).default(!1),externalPlatform:string$2("externalPlatform").predicate(UDFS.externalPlatform),externalId:string$2("externalId").predicate(UDFS.externalId),alias:string$2("alias").predicate(UDFS.alias),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),note:text("note").predicate(VCARD.note),sortKey:string$2("sortKey").predicate(UDFS.sortKey),gender:string$2("gender").predicate(VCARD.hasGender),province:string$2("province").predicate(VCARD.region),city:string$2("city").predicate(VCARD.locality),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt),lastSyncedAt:timestamp("lastSyncedAt").predicate(UDFS.lastSyncedAt)},{base:"/.data/contacts/",sparqlEndpoint:"/.data/contacts/-/sparql",type:VCARD.Individual,namespace:UDFS});definePodRepository({namespace:"contact",resource:contactResource,searchableFields:["name","alias","note"],defaultSort:{field:"name",direction:"asc"}});const ChatStatus={ACTIVE:"active"},chatResource=podTable("chats",{id:id("id").default("{key}/index.ttl#this"),title:string$2("title").predicate(DCTerms.title).notNull(),description:string$2("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(SCHEMA.image),author:uri("author").predicate(DCTerms.creator),status:string$2("status").predicate(UDFS.status).notNull().default(ChatStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),muted:boolean$2("muted").predicate(UDFS.muted).default(!1),unreadCount:integer$1("unreadCount").predicate(UDFS.unreadCount).default(0),contact:uri("contact").predicate(UDFS.hasContact).link(contactResource),participants:uri("participants").array().predicate(WF.participant),metadata:object$1("metadata").predicate(UDFS.metadata),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt),lastMessage:uri("lastMessage").predicate(UDFS.lastMessage),lastMessagePreview:text("lastMessagePreview").predicate(SCHEMA.text),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat/",sparqlEndpoint:"/.data/chat/-/sparql",type:MEETING.LongChat,namespace:UDFS});definePodRepository({namespace:"chat",resource:chatResource,searchableFields:["title","description"],defaultSort:{field:"lastActiveAt",direction:"desc"}});const ProviderAuthMode={apiKey:"apiKey"},credentialResource=podTable("credential",{id:id("id").default("credentials.ttl#{key}"),provider:uri("provider").predicate(UDFS.provider).link("aiProvider"),authMode:string$2("authMode").predicate(UDFS.authMode).default(ProviderAuthMode.apiKey),offeringId:string$2("offeringId").predicate(UDFS.offeringId),service:string$2("service").predicate(UDFS.service).notNull().default("ai"),status:string$2("status").predicate(UDFS.status).notNull().default("active"),apiKey:string$2("apiKey").predicate(UDFS.apiKey),storageMode:string$2("storageMode").predicate(UDFS.storageMode),secretPayload:string$2("secretPayload").predicate(UDFS.secretPayload),encryptedSecret:string$2("encryptedSecret").predicate(UDFS.encryptedSecret),wrappedDataKey:string$2("wrappedDataKey").predicate(UDFS.wrappedDataKey),encryptionAlgorithm:string$2("encryptionAlgorithm").predicate(UDFS.encryptionAlgorithm),keyVersion:string$2("keyVersion").predicate(UDFS.keyVersion),scopes:text("scopes").array().predicate(UDFS.scopes),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),accountLabel:string$2("accountLabel").predicate(UDFS.accountLabel),lastRefreshAt:timestamp("lastRefreshAt").predicate(UDFS.lastRefreshAt),reauthRequired:boolean$2("reauthRequired").predicate(UDFS.reauthRequired).default(!1),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),label:string$2("label").predicate(UDFS.label),isDefault:boolean$2("isDefault").predicate(UDFS.isDefault).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).defaultNow(),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),clientCredentialId:string$2("clientCredentialId").predicate(UDFS.clientCredentialId),appliedTo:string$2("appliedTo").predicate(UDFS.appliedTo),appliedOn:string$2("appliedOn").predicate(UDFS.appliedOn),appliedAt:timestamp("appliedAt").predicate(UDFS.appliedAt),failCount:integer$1("failCount").predicate(UDFS.failCount).default(0),rateLimitResetAt:timestamp("rateLimitResetAt").predicate(UDFS.rateLimitResetAt),oauthRefreshToken:string$2("oauthRefreshToken").predicate(UDFS.oauthRefreshToken),oauthAccessToken:string$2("oauthAccessToken").predicate(UDFS.oauthAccessToken),oauthExpiresAt:timestamp("oauthExpiresAt").predicate(UDFS.oauthExpiresAt),projectId:string$2("projectId").predicate(UDFS.projectId),organizationId:string$2("organizationId").predicate(UDFS.organizationId),metadata:json("metadata").predicate(UDFS.metadata)},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:UDFS.Credential,namespace:UDFS});function resourceKey(n,e){return n&&n.length>0?n:`${e}_${Math.random().toString(36).slice(2,12)}`}function workflowOwnerDir(n){return taskDir(n)??runDir(n)??deliveryDir(n)??issueDir(n)??threadDir(n)??chatDir(n)??aboutDir(n)}function chatDir(n){const e=typeof n?.chat=="string"?n.chat:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^chat\/(.+)\/index\.ttl#this$/);return i?.[1]?`chat/${i[1]}`:null}function threadDir(n){const e=typeof n?.thread=="string"?n.thread:void 0;return e?normalizePodDataResourceId(e).match(/^((?:chat|task)\/.+)\/index\.ttl#[^#/]+$/)?.[1]??null:null}function taskDir(n){const e=typeof n?.task=="string"?n.task:void 0;if(!e)return null;const t=normalizePodDataResourceId(e);if(t==="task/index.ttl#this")return"task";const i=t.match(/^task\/index\.ttl#([^#/]+)$/);if(i?.[1])return`task/${i[1]}`;const s=t.match(/^task\/(.+)\.ttl(?:#[^#/]+)?$/);return s?.[1]?`task/${s[1]}`:null}function issueDir(n){const e=typeof n?.issue=="string"?n.issue:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^issues\/(.+)\.ttl(?:#[^#/]+)?$/);return i?.[1]?`issues/${i[1]}`:null}function deliveryDir(n){const e=typeof n?.delivery=="string"?n.delivery:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/deliveries\.ttl#[^#/]+$/)?.[1]??null:null}function runDir(n){const e=typeof n?.run=="string"?n.run:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/runs\.ttl#[^#/]+$/)?.[1]??null:null}function aboutDir(n){const e=typeof n?.about=="string"?n.about:void 0;return e?runDir({run:e})??deliveryDir({delivery:e})??taskDir({task:e})??issueDir({issue:e})??threadDir({thread:e})??chatDir({chat:e}):null}const ThreadStatus={ACTIVE:"active"},threadResource=podTable("thread",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/index.ttl#{key}",{key:resourceKey(n,"thread"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),title:string$2("title").predicate(DCTerms.title),status:string$2("status").predicate(UDFS.status).notNull().default(ThreadStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),workspace:uri("workspace").predicate(UDFS.workspace),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:SIOC.Thread,namespace:UDFS});definePodRepository({namespace:"thread",resource:threadResource,searchableFields:["title"],defaultSort:{field:"updatedAt",direction:"desc"}});const MessageRole={USER:"user"},MessageStatus={COMPLETED:"completed"},messageResource=podTable("chat_message",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/{yyyy}/{MM}/{dd}/messages.ttl#{key}",{key:resourceKey(n,"msg"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),chat:uri("chat").predicate(WF.message).inverse().link(chatResource),thread:uri("thread").predicate(SIOC.has_member).inverse().link(threadResource),maker:uri("maker").predicate(FOAF.maker),role:string$2("role").predicate(UDFS.messageType).notNull().default(MessageRole.USER),content:text("content").predicate(SIOC.content).notNull(),richContent:text("richContent").predicate(SIOC.richContent),status:string$2("status").predicate(UDFS.messageStatus).notNull().default(MessageStatus.COMPLETED),toolName:string$2("toolName").predicate(UDFS.toolName),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),metadata:object$1("metadata").predicate(UDFS.metadata),replacedBy:string$2("replacedBy").predicate(DCTerms.isReplacedBy),deletedAt:timestamp("deletedAt").predicate(SCHEMA.dateDeleted),senderName:string$2("senderName").predicate(UDFS.senderName),senderAvatarUrl:uri("senderAvatarUrl").predicate(UDFS.senderAvatarUrl),mentions:uri("mentions").array().predicate(UDFS.mentions),replyTo:uri("replyTo").predicate(UDFS.replyTo),routedBy:uri("routedBy").predicate(UDFS.routedBy),routeTargetAgent:uri("routeTargetAgent").predicate(UDFS.routeTargetAgent),coordinationId:string$2("coordinationId").predicate(UDFS.coordinationId),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:MEETING.Message,namespace:UDFS}),exactFilterColumns={parent:messageResource.parent,chat:messageResource.chat,thread:messageResource.thread,maker:messageResource.maker,role:messageResource.role,status:messageResource.status,toolName:messageResource.toolName,toolCallId:messageResource.toolCallId,coordinationId:messageResource.coordinationId};function exactFilter$1(n,e){return e===void 0?void 0:eq(exactFilterColumns[n],e)}function messageListFilter(n){if(!n)return;const e=[exactFilter$1("parent",n.parent),exactFilter$1("chat",n.chat),exactFilter$1("thread",n.thread),exactFilter$1("maker",n.maker),exactFilter$1("role",n.role),exactFilter$1("status",n.status),exactFilter$1("toolName",n.toolName),exactFilter$1("toolCallId",n.toolCallId),exactFilter$1("coordinationId",n.coordinationId)].filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}definePodRepository({namespace:"message",resource:messageResource,searchableFields:["content"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>messageListFilter(n)});function chatProjectMemoryResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const chatProjectContextResource=podTable("chatProjectContext",{id:id("id"),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),instructions:text("instructions").predicate(UDFS.systemMessage),memoryEnabled:boolean$2("memoryEnabled").predicate(UDFS.memoryEnabled).notNull().default(!0),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-projects/",sparqlEndpoint:"/.data/chat-projects/-/sparql",type:UDFS.ChatProjectContext,namespace:UDFS}),chatProjectMemoryResource=podTable("chatProjectMemory",{id:id("id").default(n=>n?chatProjectMemoryResourceId(n):""),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),text:text("text").predicate(SCHEMA.text).notNull(),sourceMessage:uri("sourceMessage").predicate(UDFS.sourceMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-project-memories/",sparqlEndpoint:"/.data/chat-project-memories/-/sparql",type:UDFS.ProjectMemory,namespace:UDFS});definePodRepository({namespace:"chat-project-context",resource:chatProjectContextResource,defaultSort:{field:"updatedAt",direction:"desc"},filter:({filters:n})=>n?.workspace?eq(chatProjectContextResource.workspace,n.workspace):void 0});definePodRepository({namespace:"chat-project-memory",resource:chatProjectMemoryResource,searchableFields:["text"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>n?.workspace?eq(chatProjectMemoryResource.workspace,n.workspace):void 0});function conversationShareResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const conversationShareResource=podTable("conversationShare",{id:id("id").default(n=>n?conversationShareResourceId(n):""),thread:uri("thread").predicate(UDFS.targetThread).notNull(),resourceUrl:uri("resourceUrl").predicate(SCHEMA.url).notNull(),includeToolDetails:boolean$2("includeToolDetails").predicate(UDFS.includeToolDetails).notNull().default(!1),excludedMessageIds:string$2("excludedMessageIds").array().predicate(UDFS.excludedMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/chat-shares/",sparqlEndpoint:"/.data/chat-shares/-/sparql",type:UDFS.ConversationShare,namespace:UDFS});definePodRepository({namespace:"conversation-share",resource:conversationShareResource,defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>n?.thread?eq(conversationShareResource.thread,n.thread):void 0});const TaskStatus={OPEN:"open"},taskResource=podTable("task",{id:id("id").default("index.ttl#{key}"),title:string$2("title").predicate(DCTerms.title),instruction:text("instruction").predicate(UDFS.instruction).notNull(),prompt:text("prompt").predicate(UDFS.prompt),issue:uri("issue").predicate(UDFS.issue).link("issue"),message:uri("message").predicate(UDFS.message),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(TaskStatus.OPEN),priority:string$2("priority").predicate(UDFS.priority),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),source:uri("source").predicate(DCTerms.source),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/task/",sparqlEndpoint:"/.data/task/-/sparql",type:UDFS.Task,namespace:UDFS}),ScheduleStatus={ACTIVE:"active"},ScheduleKind={ONCE:"once"},scheduleResource=podTable("schedule",{id:id("id"),task:uri("task").predicate(UDFS.task).notNull().link(taskResource),status:string$2("status").predicate(UDFS.status).notNull().default(ScheduleStatus.ACTIVE),scheduleKind:string$2("scheduleKind").predicate(UDFS.scheduleKind).notNull().default(ScheduleKind.ONCE),cron:string$2("cron").predicate(UDFS.cron),intervalSeconds:integer$1("intervalSeconds").predicate(UDFS.intervalSeconds),timezone:string$2("timezone").predicate(UDFS.timezone),startsAt:timestamp("startsAt").predicate(UDFS.startsAt),nextRunAt:timestamp("nextRunAt").predicate(UDFS.nextRunAt),lastRunAt:timestamp("lastRunAt").predicate(UDFS.lastRunAt),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Schedule,namespace:UDFS}),AutomationRuleStatus={ACTIVE:"active"},AutomationRuleKind={EVENT:"event"};podTable("automation_rule",{id:id("id"),title:string$2("title").predicate(DCTerms.title).notNull(),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default(AutomationRuleStatus.ACTIVE),ruleKind:string$2("ruleKind").predicate(UDFS.ruleKind).notNull().default(AutomationRuleKind.EVENT),task:uri("task").predicate(UDFS.task).link(taskResource),schedule:uri("schedule").predicate(UDFS.schedule).link(scheduleResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),condition:object$1("condition").predicate(UDFS.condition),actions:object$1("actions").predicate(UDFS.actions),metadata:object$1("metadata").predicate(UDFS.metadata),lastTriggeredAt:timestamp("lastTriggeredAt").predicate(UDFS.lastTriggeredAt),lastRunStatus:string$2("lastRunStatus").predicate(UDFS.lastRunStatus),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.AutomationRule,namespace:UDFS});const DeliveryStatus={PENDING:"pending"},DeliveryKind={TASK_DISPATCH:"task_dispatch"},deliveryResource=podTable("delivery",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/deliveries.ttl#{key}"),kind:string$2("kind").predicate(UDFS.deliveryKind).notNull().default(DeliveryKind.TASK_DISPATCH),status:string$2("status").predicate(UDFS.status).notNull().default(DeliveryStatus.PENDING),task:uri("task").predicate(UDFS.task).link(taskResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),targetThread:uri("targetThread").predicate(UDFS.targetThread).link(threadResource),targetSession:uri("targetSession").predicate(UDFS.targetSession),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object),objective:text("objective").predicate(UDFS.objective),payload:object$1("payload").predicate(UDFS.payload),projection:object$1("projection").predicate(UDFS.projection),projectedRole:string$2("projectedRole").predicate(UDFS.projectedRole),metadata:object$1("metadata").predicate(UDFS.metadata),error:text("error").predicate(UDFS.error),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),dispatchedAt:timestamp("dispatchedAt").predicate(UDFS.startedAt),consumedAt:timestamp("consumedAt").predicate(UDFS.consumedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Delivery,namespace:UDFS}),issueResource=podTable("issue",{id:id("id").default("{key}.ttl"),title:string$2("title").predicate(DCTerms.title).notNull(),document:uri("document").predicate(DCTerms.source),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("open"),priority:string$2("priority").predicate(UDFS.priority).default("medium"),labels:text("labels").array().predicate(UDFS.tags),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),parentIssue:uri("parentIssue").predicate(UDFS.parentIssue).link("issue"),tasks:uri("tasks").predicate(UDFS.task).array(),createdBy:uri("createdBy").predicate(DCTerms.creator),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),closedAt:timestamp("closedAt").predicate(UDFS.closedAt),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/.data/issues/",sparqlEndpoint:"/.data/issues/-/sparql",type:UDFS.Issue,namespace:UDFS}),RunStatus={QUEUED:"queued"},runResource=podTable("run",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/runs.ttl#{key}"),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),trigger:uri("trigger").predicate(UDFS.trigger),input:uri("input").predicate(UDFS.input),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(RunStatus.QUEUED),runner:string$2("runner").predicate(UDFS.runner).notNull(),prompt:string$2("prompt").predicate(UDFS.prompt),externalRunId:string$2("externalRunId").predicate(UDFS.externalRunId),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),heartbeatAt:timestamp("heartbeatAt").predicate(UDFS.heartbeatAt),cancelRequestedAt:timestamp("cancelRequestedAt").predicate(UDFS.cancelRequestedAt),error:string$2("error").predicate(UDFS.error),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Run,namespace:UDFS});podTable("run_step",{id:id("id").default("{run.doc}#{key}"),run:uri("run").predicate(UDFS.run).notNull().link(runResource),stepType:string$2("stepType").predicate(UDFS.stepType).notNull(),message:string$2("message").predicate(DCTerms.description),payload:object$1("payload").predicate(UDFS.payload),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.RunStep,namespace:UDFS});const evidenceResource=podTable("evidence",{id:id("id").default("evidence/{yyyy}/{MM}/{dd}.ttl#{key}"),evidenceKind:string$2("evidenceKind").predicate(UDFS.evidenceKind).notNull(),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),summary:text("summary").predicate(DCTerms.abstract),source:uri("source").predicate(DCTerms.source),actor:uri("actor").predicate(DCTerms.creator),outcome:string$2("outcome").predicate(UDFS.outcome),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Evidence,namespace:UDFS}),ReportStatus={DRAFT:"draft"};podTable("report",{id:id("id").default((n,e)=>{const t=resourceKey(n,"report"),i=workflowOwnerDir(e)??"reports";return renderDefaultIdTemplate(`${i}/{yyyy}/{MM}/{dd}/reports.ttl#{key}`,{key:t,row:e})}),reportKind:string$2("reportKind").predicate(UDFS.reportKind).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(ReportStatus.DRAFT),outcome:string$2("outcome").predicate(UDFS.outcome),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),evidence:uri("evidence").predicate(UDFS.evidence).array().link(evidenceResource),summary:text("summary").predicate(DCTerms.abstract).notNull(),reviewer:uri("reviewer").predicate(SCHEMA.reviewedBy),actor:uri("actor").predicate(DCTerms.creator),source:uri("source").predicate(DCTerms.source),metricFacts:object$1("metricFacts").predicate(UDFS.metricFacts),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),publishedAt:timestamp("publishedAt").predicate(DCTerms.issued),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Report,namespace:UDFS});podTable("idea",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),summary:string$2("summary").predicate(DCTerms.abstract).notNull(),document:uri("document").predicate(DCTerms.source),input:text("input").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("captured"),commitment:string$2("commitment").predicate(UDFS.commitment).notNull().default("thought"),affectedArea:string$2("affectedArea").predicate(UDFS.affectedArea),currentUnderstanding:text("currentUnderstanding").predicate(UDFS.currentUnderstanding),openQuestions:text("openQuestions").array().predicate(UDFS.openQuestions),related:uri("related").array().predicate(DCTerms.relation),conflicts:text("conflicts").array().predicate(UDFS.conflicts),nextStep:text("nextStep").predicate(UDFS.nextStep),promotedTo:uri("promotedTo").predicate(UDFS.promotedTo),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),sourceMessages:uri("sourceMessages").array().predicate(DCTerms.source),createdBy:uri("createdBy").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/ideas/",sparqlEndpoint:"/.data/ideas/-/sparql",type:UDFS.Idea,namespace:UDFS});definePodRepository({namespace:"issue",resource:issueResource,searchableFields:["title","description"],defaultSort:{field:"updatedAt",direction:"desc"}});var MessageBlockType;(function(n){n.UNKNOWN="unknown",n.MAIN_TEXT="main_text",n.THINKING="thinking",n.IMAGE="image",n.CODE="code",n.TOOL="tool",n.TOOL_APPROVAL="tool_approval",n.TASK_PROGRESS="task_progress",n.FILE="file",n.ERROR="error",n.CITATION="citation"})(MessageBlockType||(MessageBlockType={}));var MessageBlockStatus;(function(n){n.PENDING="pending",n.PROCESSING="processing",n.STREAMING="streaming",n.SUCCESS="success",n.ERROR="error",n.PAUSED="paused"})(MessageBlockStatus||(MessageBlockStatus={}));const fixtureToolCallBlock={type:"tool",toolCallId:"toolcall-1",toolName:"write_file",arguments:{path:"README.md",content:"hello"},status:"waiting_approval",duration:123},fixtureToolApprovalBlock={type:"tool_approval",toolCallId:"toolcall-1",toolName:"write_file",toolDescription:"Write a file in the workspace",arguments:{path:"README.md",content:"hello"},risk:"medium",status:"pending",decisionRole:"human"},fixtureTaskProgressBlock={type:"task_progress",task:"https://pod.example/.data/task/index.ttl#task-1",title:"CP0 contract baseline",steps:[{id:"s1",label:"Freeze contracts",status:"done",duration:10},{id:"s2",label:"Add namespaces",status:"running"}],currentStep:2,totalSteps:2};JSON.stringify({blocks:[fixtureToolCallBlock,fixtureToolApprovalBlock,fixtureTaskProgressBlock]});const favoriteResource=podTable("favorite",{id:id("id"),targetType:uri("targetType").predicate(RDF$1.type).notNull(),target:uri("target").predicate(UDFS.favoriteTarget).notNull(),title:string$2("title").predicate(DCTerms.title).notNull(),snapshotContent:text("snapshotContent").predicate(SCHEMA.text),snapshotAuthor:string$2("snapshotAuthor").predicate(SCHEMA.author),sourceModule:string$2("sourceModule").predicate(UDFS.sourceModule),searchText:text("searchText").predicate(UDFS.searchText),snapshotMeta:text("snapshotMeta").predicate(UDFS.snapshotMeta),favoredAt:timestamp("favoredAt").predicate(UDFS.favoredAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/favorites/",sparqlEndpoint:"/.data/favorites/-/sparql",type:SCHEMA.CreativeWork,namespace:UDFS});async function createFavorite(n,e,t){const{rdfType:i,sourceModule:s,extractor:o}=e,l=t["@id"]||t.id;if(!l){console.warn("[StarredSync] Cannot create favorite: missing target URI");return}const u=o.getTitle(t),h={id:crypto.randomUUID(),targetType:i,target:l,title:u,snapshotContent:o.getContent?.(t),snapshotAuthor:o.getAuthor?.(t),sourceModule:s,searchText:o.getSearchText?.(t)??u,snapshotMeta:o.getSnapshotMeta?.(t),favoredAt:new Date,updatedAt:new Date};try{getDbInstance()||console.warn("[StarredSync] No db instance registered")}catch(d){console.error("[StarredSync] Failed to create favorite:",d)}}async function deleteFavorite(n,e){if(e)try{const t=getDbInstance()}catch(t){console.error("[StarredSync] Failed to delete favorite:",t)}}function createStarredSyncHook(n){return{afterUpdate:async(e,t,i)=>{if(!("starred"in i))return;const s=t.starred,o=t["@id"]||t.id;s?await createFavorite(e,n,t):await deleteFavorite(e,o)}}}let dbInstance=null;function getDbInstance(){return dbInstance}const chatSnapshotExtractor={getTitle:n=>n.title||"未命名对话",getContent:n=>n.lastMessagePreview},threadSnapshotExtractor={getTitle:n=>n.title||"未命名话题"};createStarredSyncHook({rdfType:MEETING.LongChat,sourceModule:"chat",extractor:chatSnapshotExtractor});createStarredSyncHook({rdfType:SIOC.Thread,sourceModule:"thread",extractor:threadSnapshotExtractor});const approvalResource=podTable("approval",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId).notNull(),toolName:string$2("toolName").predicate(UDFS.toolName).notNull(),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),risk:string$2("risk").predicate(UDFS.risk).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default("pending"),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),context:text("context").predicate(UDFS.context),approvalOptions:text("approvalOptions").predicate(UDFS.approvalOptions),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/approvals/",sparqlEndpoint:"/.data/approvals/-/sparql",type:UDFS.ApprovalRequest,namespace:UDFS}),InputRequestStatus={PENDING:"pending"},inputRequestResource=podTable("input_request",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),run:uri("run").predicate(UDFS.run).link(runResource),task:uri("task").predicate(UDFS.task).link(taskResource),requester:uri("requester").predicate(UDFS.requester),requestKind:string$2("requestKind").predicate(UDFS.requestKind).notNull().default("user-input"),prompt:text("prompt").predicate(UDFS.prompt).notNull(),context:text("context").predicate(UDFS.context),inputOptions:text("inputOptions").predicate(UDFS.inputOptions),status:string$2("status").predicate(UDFS.status).notNull().default(InputRequestStatus.PENDING),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),response:text("response").predicate(UDFS.response),answeredBy:uri("answeredBy").predicate(UDFS.answeredBy),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/input-requests/",sparqlEndpoint:"/.data/input-requests/-/sparql",type:UDFS.InputRequest,namespace:UDFS}),CaptureCandidateStatus={CANDIDATE:"candidate"},captureCandidateResource=podTable("capture_candidate",{id:id("id").default("candidates/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),summary:text("summary").predicate(DCTerms.abstract).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence).notNull().default("medium"),reason:text("reason").predicate(UDFS.reason),status:string$2("status").predicate(UDFS.status).notNull().default(CaptureCandidateStatus.CANDIDATE),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureCandidate,namespace:UDFS}),captureEventResource=podTable("capture_event",{id:id("id").default("events/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),captureCandidate:uri("captureCandidate").predicate(UDFS.captureCandidate).link(captureCandidateResource),targetResource:uri("targetResource").predicate(UDFS.targetResource),decision:string$2("decision").predicate(UDFS.captureDecision).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence),reason:text("reason").predicate(UDFS.reason),userCorrection:text("userCorrection").predicate(UDFS.userCorrection),approval:uri("approval").predicate(UDFS.approval).link(approvalResource),inputRequest:uri("inputRequest").predicate(UDFS.inputRequest).link(inputRequestResource),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),about:uri("about").predicate(SCHEMA.about),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureEvent,namespace:UDFS}),candidateExactFilterColumns={source:captureCandidateResource.source,suggestedType:captureCandidateResource.suggestedType,suggestedTarget:captureCandidateResource.suggestedTarget,status:captureCandidateResource.status,chat:captureCandidateResource.chat,thread:captureCandidateResource.thread,task:captureCandidateResource.task,run:captureCandidateResource.run},eventExactFilterColumns={source:captureEventResource.source,captureCandidate:captureEventResource.captureCandidate,targetResource:captureEventResource.targetResource,decision:captureEventResource.decision,approval:captureEventResource.approval,inputRequest:captureEventResource.inputRequest,chat:captureEventResource.chat,thread:captureEventResource.thread,task:captureEventResource.task,run:captureEventResource.run};function exactFilter(n,e,t){return t===void 0?void 0:eq(n[e],t)}function combineFilters(n){const e=n.filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}function captureCandidateListFilter(n){if(n)return combineFilters([exactFilter(candidateExactFilterColumns,"source",n.source),exactFilter(candidateExactFilterColumns,"suggestedType",n.suggestedType),exactFilter(candidateExactFilterColumns,"suggestedTarget",n.suggestedTarget),exactFilter(candidateExactFilterColumns,"status",n.status),exactFilter(candidateExactFilterColumns,"chat",n.chat),exactFilter(candidateExactFilterColumns,"thread",n.thread),exactFilter(candidateExactFilterColumns,"task",n.task),exactFilter(candidateExactFilterColumns,"run",n.run)])}function captureEventListFilter(n){if(n)return combineFilters([exactFilter(eventExactFilterColumns,"source",n.source),exactFilter(eventExactFilterColumns,"captureCandidate",n.captureCandidate),exactFilter(eventExactFilterColumns,"targetResource",n.targetResource),exactFilter(eventExactFilterColumns,"decision",n.decision),exactFilter(eventExactFilterColumns,"approval",n.approval),exactFilter(eventExactFilterColumns,"inputRequest",n.inputRequest),exactFilter(eventExactFilterColumns,"chat",n.chat),exactFilter(eventExactFilterColumns,"thread",n.thread),exactFilter(eventExactFilterColumns,"task",n.task),exactFilter(eventExactFilterColumns,"run",n.run)])}definePodRepository({namespace:"capture-candidate",resource:captureCandidateResource,searchableFields:["summary","reason"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureCandidateListFilter(n)});definePodRepository({namespace:"capture-event",resource:captureEventResource,searchableFields:["reason","userCorrection"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureEventListFilter(n)});podTable("settings",{id:id("id").default((n,e)=>{const t=typeof e?.key=="string"?e.key:n;return t?`${encodeURIComponent(t)}.ttl`:""}),key:string$2("key").predicate(UDFS.settingKey).notNull(),value:text("value").predicate(UDFS.settingValue).notNull(),valueType:string$2("valueType").predicate(UDFS.settingType).notNull().default("string"),category:string$2("category").predicate(DCTerms.type).notNull(),label:string$2("label").predicate(DCTerms.title),description:text("description").predicate(DCTerms.description),owner:string$2("owner").predicate(DCTerms.creator).notNull(),isSensitive:boolean$2("isSensitive").predicate(UDFS.status).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),modifiedAt:timestamp("modifiedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:SCHEMA.PropertyValue,namespace:UDFS});const agentResource=podTable("agent",{id:id("id").default("{key}/"),name:string$2("name").predicate(FOAF.name).notNull(),description:text("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),root:uri("root").predicate(UDFS.root),identity:uri("identity").predicate(UDFS.webId),hasSkill:uri("hasSkill").array().predicate(UDFS.hasSkill),instructions:text("instructions").predicate(UDFS.systemMessage),provider:string$2("provider").predicate(UDFS.provider),model:string$2("model").predicate(UDFS.model),backend:string$2("backend").predicate(UDFS.backend),runtime:string$2("runtime").predicate(UDFS.runtime),transport:string$2("transport").predicate(UDFS.transport),endpoint:uri("endpoint").predicate(UDFS.endpoint),credentialSource:string$2("credentialSource").predicate(UDFS.credentialSource),temperature:real("temperature").predicate(UDFS.temperature).default(.7),tools:text("tools").array().predicate(UDFS.tools),contextRound:integer$1("contextRound").predicate(UDFS.contextRound).default(4),authorityPolicy:object$1("authorityPolicy").predicate(UDFS.authorityPolicy),toolPolicy:object$1("toolPolicy").predicate(UDFS.toolPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),ttsModel:string$2("ttsModel").predicate(UDFS.ttsModel),videoModel:string$2("videoModel").predicate(UDFS.videoModel),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:FOAF.Agent,namespace:UDFS});definePodRepository({namespace:"agent",resource:agentResource,searchableFields:["name","description","instructions"]});podTable("skill",{id:id("id").default("{agent.key}/skills/{key}/"),agent:uri("agent").predicate(UDFS.agent).notNull().link(agentResource),root:uri("root").predicate(UDFS.root),name:string$2("name").predicate(UDFS.name).notNull(),displayName:string$2("displayName").predicate(UDFS.displayName),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),version:string$2("version").predicate(UDFS.version),source:string$2("source").predicate(UDFS.source),checksum:string$2("checksum").predicate(UDFS.checksum),loadPolicy:string$2("loadPolicy").predicate(UDFS.loadPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:UDFS.Skill,namespace:UDFS});const sessionResource=podTable("session",{id:id("id").default("{yyyy}/{MM}/{dd}/{key}.ttl"),owner:uri("owner").predicate(UDFS.actor).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),status:string$2("status").predicate(UDFS.sessionStatus).notNull().default("active"),tool:string$2("tool").predicate(UDFS.sessionTool),tokenUsage:integer$1("tokenUsage").predicate(UDFS.tokenUsage).default(0),messages:uri("messages").predicate(UDFS.message).array(),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),archivedAt:timestamp("archivedAt").predicate(UDFS.archivedAt)},{base:"/.data/sessions/",sparqlEndpoint:"/.data/sessions/-/sparql",type:UDFS.term("Session"),namespace:UDFS});definePodRepository({namespace:"session",resource:sessionResource,searchableFields:["chat","thread","status","tool"],defaultSort:{field:"updatedAt",direction:"desc"}});podTable("audit",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),action:string$2("action").predicate(UDFS.action).notNull(),actor:uri("actor").predicate(UDFS.actor).notNull(),actorRole:string$2("actorRole").predicate(UDFS.actorRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),session:uri("session").predicate(UDFS.session),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),entry:uri("entry").predicate(UDFS.entry),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),toolName:string$2("toolName").predicate(UDFS.toolName),approval:uri("approval").predicate(UDFS.approval),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/audits/",sparqlEndpoint:"/.data/audits/-/sparql",type:UDFS.AuditEntry,namespace:UDFS});podTable("grant",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AutonomyGrant]),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),title:string$2("title").predicate(DCTerms.title),summary:text("summary").predicate(DCTerms.abstract),description:text("description").predicate(DCTerms.description),schema:uri("schema").predicate(DCTerms.conformsTo),pageKind:string$2("pageKind").predicate(UDFS.pageKind),wikiStatus:string$2("wikiStatus").predicate(UDFS.status),tags:text("tags").predicate(UDFS.tags),source:string$2("source").predicate(UDFS.sourceKind),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),compiledAt:timestamp("compiledAt").predicate(UDFS.compiledAt),compiledFrom:uri("compiledFrom").array().predicate(UDFS.compiledFrom),related:uri("related").array().predicate(DCTerms.relation),effect:string$2("effect").predicate(UDFS.effect).notNull(),riskCeiling:string$2("riskCeiling").predicate(UDFS.riskCeiling),policy:text("policy").predicate(UDFS.policy),context:text("context").predicate(UDFS.context),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy).notNull(),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/settings/autonomy/grants/",sparqlEndpoint:"/settings/autonomy/grants/-/sparql",type:ODRL.Policy,namespace:ODRL});podTable("inbox_notification",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([AS.Announce]),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object).notNull(),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/inbox/",sparqlEndpoint:"/inbox/-/sparql",type:AS.Activity,namespace:AS});var util;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const o={};for(const l of s)o[l]=l;return o},n.getValidEnumValues=s=>{const o=n.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),l={};for(const u of o)l[u]=s[u];return n.objectValues(l)},n.objectValues=s=>n.objectKeys(s).map(function(o){return s[o]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&o.push(l);return o},n.find=(s,o)=>{for(const l of s)if(o(l))return l},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function i(s,o=" | "){return s.map(l=>typeof l=="string"?`'${l}'`:l).join(o)}n.joinValues=i,n.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(util||(util={}));var objectUtil;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=n=>{switch(typeof n){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(n)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(n)?ZodParsedType.array:n===null?ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?ZodParsedType.map:typeof Set<"u"&&n instanceof Set?ZodParsedType.set:typeof Date<"u"&&n instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(o){return o.message},i={_errors:[]},s=o=>{for(const l of o.issues)if(l.code==="invalid_union")l.unionErrors.map(s);else if(l.code==="invalid_return_type")s(l.returnTypeError);else if(l.code==="invalid_arguments")s(l.argumentsError);else if(l.path.length===0)i._errors.push(t(l));else{let u=i,h=0;for(;h<l.path.length;){const d=l.path[h];h===l.path.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(l))):u[d]=u[d]||{_errors:[]},u=u[d],h++}}};return s(this),i}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)if(s.path.length>0){const o=s.path[0];t[o]=t[o]||[],t[o].push(e(s))}else i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=n=>new ZodError(n);const errorMap=(n,e)=>{let t;switch(n.code){case ZodIssueCode.invalid_type:n.received===ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${util.joinValues(n.keys,", ")}`;break;case ZodIssueCode.invalid_union:t="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${util.joinValues(n.options)}`;break;case ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${util.joinValues(n.options)}, received '${n.received}'`;break;case ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ZodIssueCode.invalid_date:t="Invalid date";break;case ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case ZodIssueCode.custom:t="Invalid input";break;case ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,util.assertNever(n)}return{message:t}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=n=>{const{data:e,path:t,errorMaps:i,issueData:s}=n,o=[...t,...s.path||[]],l={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let u="";const h=i.filter(d=>!!d).slice().reverse();for(const d of h)u=d(l,{data:e,defaultError:u}).message;return{...s,path:o,message:u}};function addIssueToContext(n,e){const t=getErrorMap(),i=makeIssue({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===errorMap?void 0:errorMap].filter(s=>!!s)});n.common.issues.push(i)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const s of t){if(s.status==="aborted")return INVALID;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const o=await s.key,l=await s.value;i.push({key:o,value:l})}return ParseStatus.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:o,value:l}=s;if(o.status==="aborted"||l.status==="aborted")return INVALID;o.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof l.value<"u"||s.alwaysSet)&&(i[o.value]=l.value)}return{status:e.value,value:i}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=n=>({status:"dirty",value:n}),OK=n=>({status:"valid",value:n}),isAborted=n=>n.status==="aborted",isDirty=n=>n.status==="dirty",isValid=n=>n.status==="valid",isAsync=n=>typeof Promise<"u"&&n instanceof Promise;var errorUtil;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(n,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(n.common.issues);return this._error=t,this._error}}};function processCreateParams(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(l,u)=>{const{message:h}=n;return l.code==="invalid_enum_value"?{message:h??u.defaultError}:typeof u.data>"u"?{message:h??i??u.defaultError}:l.code!=="invalid_type"?{message:u.defaultError}:{message:h??t??u.defaultError}},description:s}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parseSync({data:e,path:i.path,parent:i});return handleResult(i,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return isValid(i)?{value:i.value}:{issues:t.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>isValid(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parse({data:e,path:i.path,parent:i}),o=await(isAsync(s)?s:Promise.resolve(s));return handleResult(i,o)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,o)=>{const l=e(s),u=()=>o.addIssue({code:ZodIssueCode.custom,...i(s)});return typeof Promise<"u"&&l instanceof Promise?l.then(h=>h?!0:(u(),!1)):l?!0:(u(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function timeRegex(n){return new RegExp(`^${timeRegexSource(n)}$`)}function datetimeRegex(n){let e=`${dateRegexSource}T${timeRegexSource(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(n,e){return!!((e==="v4"||!e)&&ipv4Regex.test(n)||(e==="v6"||!e)&&ipv6Regex.test(n))}function isValidJWT(n,e){if(!jwtRegex.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function isValidCidr(n,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(n)||(e==="v6"||!e)&&ipv6CidrRegex.test(n))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:o.parsedType}),INVALID}const i=new ParseStatus;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),i.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),i.dirty());else if(o.kind==="length"){const l=e.data.length>o.value,u=e.data.length<o.value;(l||u)&&(s=this._getOrReturnCtx(e,s),l?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):u&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),i.dirty())}else if(o.kind==="email")emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="uuid")uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="nanoid")nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="cuid")cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="cuid2")cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="ulid")ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),i.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),i.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),i.dirty()):o.kind==="datetime"?datetimeRegex(o).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),i.dirty()):o.kind==="date"?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),i.dirty()):o.kind==="time"?timeRegex(o).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),i.dirty()):o.kind==="duration"?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="ip"?isValidIP(e.data,o.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="jwt"?isValidJWT(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="cidr"?isValidCidr(e.data,o.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="base64"?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="base64url"?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(i)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodString.create=n=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:n?.coerce??!1,...processCreateParams(n)});function floatSafeRemainder(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,o=Number.parseInt(n.toFixed(s).replace(".","")),l=Number.parseInt(e.toFixed(s).replace(".",""));return o%l/10**s}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:o.parsedType}),INVALID}let i;const s=new ParseStatus;for(const o of this._def.checks)o.kind==="int"?util.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?floatSafeRemainder(e.data,o.value)!==0&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_finite,message:o.message}),s.dirty()):util.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=n=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let i;const s=new ParseStatus;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):util.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=n=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:n?.coerce??!1,...processCreateParams(n)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:i.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=n=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:o.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_date}),INVALID}const i=new ParseStatus;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),i.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),i.dirty()):util.assertNever(o);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ZodDate.create=n=>new ZodDate({checks:[],coerce:n?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(n)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:i.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=n=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(n)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:i.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=n=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(n)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:i.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=n=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(n)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=n=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(n)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=n=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(n)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=n=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(n)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:i.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=n=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(n)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(s.exactLength!==null){const l=t.data.length>s.exactLength.value,u=t.data.length<s.exactLength.value;(l||u)&&(addIssueToContext(t,{code:l?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:u?s.exactLength.value:void 0,maximum:l?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,u)=>s.type._parseAsync(new ParseInputLazyPath(t,l,t.path,u)))).then(l=>ParseStatus.mergeArray(i,l));const o=[...t.data].map((l,u)=>s.type._parseSync(new ParseInputLazyPath(t,l,t.path,u)));return ParseStatus.mergeArray(i,o)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(n,e)=>new ZodArray({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(n){if(n instanceof ZodObject){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=ZodOptional.create(deepPartialify(i))}return new ZodObject({...n._def,shape:()=>e})}else return n instanceof ZodArray?new ZodArray({...n._def,type:deepPartialify(n.element)}):n instanceof ZodOptional?ZodOptional.create(deepPartialify(n.unwrap())):n instanceof ZodNullable?ZodNullable.create(deepPartialify(n.unwrap())):n instanceof ZodTuple?ZodTuple.create(n.items.map(e=>deepPartialify(e))):n}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const d=this._getOrReturnCtx(e);return addIssueToContext(d,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:d.parsedType}),INVALID}const{status:i,ctx:s}=this._processInputParams(e),{shape:o,keys:l}=this._getCached(),u=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const d in s.data)l.includes(d)||u.push(d);const h=[];for(const d of l){const p=o[d],g=s.data[d];h.push({key:{status:"valid",value:d},value:p._parse(new ParseInputLazyPath(s,g,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof ZodNever){const d=this._def.unknownKeys;if(d==="passthrough")for(const p of u)h.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")u.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:u}),i.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const p of u){const g=s.data[p];h.push({key:{status:"valid",value:p},value:d._parse(new ParseInputLazyPath(s,g,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const p of h){const g=await p.key,m=await p.value;d.push({key:g,value:m,alwaysSet:p.alwaysSet})}return d}).then(d=>ParseStatus.mergeObjectSync(i,d)):ParseStatus.mergeObjectSync(i,h)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{const s=this._def.errorMap?.(t,i).message??i.defaultError;return t.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};for(const i of util.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const i of util.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const i of util.objectKeys(this.shape)){const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const i of util.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let o=this.shape[i];for(;o instanceof ZodOptional;)o=o._def.innerType;t[i]=o}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.strictCreate=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.lazycreate=(n,e)=>new ZodObject({shape:n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(o){for(const u of o)if(u.result.status==="valid")return u.result;for(const u of o)if(u.result.status==="dirty")return t.common.issues.push(...u.ctx.common.issues),u.result;const l=o.map(u=>new ZodError(u.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:l}),INVALID}if(t.common.async)return Promise.all(i.map(async o=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(s);{let o;const l=[];for(const h of i){const d={...t,common:{...t.common,issues:[]},parent:null},p=h._parseSync({data:t.data,path:t.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!o&&(o={result:p,ctx:d}),d.common.issues.length&&l.push(d.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const u=l.map(h=>new ZodError(h));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:u}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(n,e)=>new ZodUnion({options:n,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(n,e){const t=getParsedType(n),i=getParsedType(e);if(n===e)return{valid:!0,data:n};if(t===ZodParsedType.object&&i===ZodParsedType.object){const s=util.objectKeys(e),o=util.objectKeys(n).filter(u=>s.indexOf(u)!==-1),l={...n,...e};for(const u of o){const h=mergeValues(n[u],e[u]);if(!h.valid)return{valid:!1};l[u]=h.data}return{valid:!0,data:l}}else if(t===ZodParsedType.array&&i===ZodParsedType.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<n.length;o++){const l=n[o],u=e[o],h=mergeValues(l,u);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return t===ZodParsedType.date&&i===ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(o,l)=>{if(isAborted(o)||isAborted(l))return INVALID;const u=mergeValues(o.value,l.value);return u.valid?((isDirty(o)||isDirty(l))&&t.dirty(),{status:t.value,value:u.data}):(addIssueToContext(i,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([o,l])=>s(o,l)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ZodIntersection.create=(n,e,t)=>new ZodIntersection({left:n,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(t)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.array)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:i.parsedType}),INVALID;if(i.data.length<this._def.items.length)return addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&i.data.length>this._def.items.length&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...i.data].map((l,u)=>{const h=this._def.items[u]||this._def.rest;return h?h._parse(new ParseInputLazyPath(i,l,i.path,u)):null}).filter(l=>!!l);return i.common.async?Promise.all(o).then(l=>ParseStatus.mergeArray(t,l)):ParseStatus.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:n,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.object)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:i.parsedType}),INVALID;const s=[],o=this._def.keyType,l=this._def.valueType;for(const u in i.data)s.push({key:o._parse(new ParseInputLazyPath(i,u,i.path,u)),value:l._parse(new ParseInputLazyPath(i,i.data[u],i.path,u)),alwaysSet:u in i.data});return i.common.async?ParseStatus.mergeObjectAsync(t,s):ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(i)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.map)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:i.parsedType}),INVALID;const s=this._def.keyType,o=this._def.valueType,l=[...i.data.entries()].map(([u,h],d)=>({key:s._parse(new ParseInputLazyPath(i,u,i.path,[d,"key"])),value:o._parse(new ParseInputLazyPath(i,h,i.path,[d,"value"]))}));if(i.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const h of l){const d=await h.key,p=await h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}})}else{const u=new Map;for(const h of l){const d=h.key,p=h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}}}}ZodMap.create=(n,e,t)=>new ZodMap({valueType:e,keyType:n,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(t)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.set)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:i.parsedType}),INVALID;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const o=this._def.valueType;function l(h){const d=new Set;for(const p of h){if(p.status==="aborted")return INVALID;p.status==="dirty"&&t.dirty(),d.add(p.value)}return{status:t.value,value:d}}const u=[...i.data.values()].map((h,d)=>o._parse(new ParseInputLazyPath(i,h,i.path,d)));return i.common.async?Promise.all(u).then(h=>l(h)):l(u)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(n,e)=>new ZodSet({valueType:n,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(n,e)=>new ZodLazy({getter:n,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(n,e)=>new ZodLiteral({value:n,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(n,e){return new ZodEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{expected:util.joinValues(i),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==ZodParsedType.string&&i.parsedType!==ZodParsedType.number){const s=util.objectValues(t);return addIssueToContext(i,{expected:util.joinValues(s),received:i.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=util.objectValues(t);return addIssueToContext(i,{received:i.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(n,e)=>new ZodNativeEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&t.common.async===!1)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const i=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ZodPromise.create=(n,e)=>new ZodPromise({type:n,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:l=>{addIssueToContext(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const l=s.transform(i.data,o);if(i.common.async)return Promise.resolve(l).then(async u=>{if(t.value==="aborted")return INVALID;const h=await this._def.schema._parseAsync({data:u,path:i.path,parent:i});return h.status==="aborted"?INVALID:h.status==="dirty"||t.value==="dirty"?DIRTY(h.value):h});{if(t.value==="aborted")return INVALID;const u=this._def.schema._parseSync({data:l,path:i.path,parent:i});return u.status==="aborted"?INVALID:u.status==="dirty"||t.value==="dirty"?DIRTY(u.value):u}}if(s.type==="refinement"){const l=u=>{const h=s.refinement(u,o);if(i.common.async)return Promise.resolve(h);if(h instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(i.common.async===!1){const u=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value),{status:t.value,value:u.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(u=>u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value).then(()=>({status:t.value,value:u.value}))))}if(s.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!isValid(l))return INVALID;const u=s.transform(l.value,o);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:u}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>isValid(l)?Promise.resolve(s.transform(l.value,o)).then(u=>({status:t.value,value:u})):INVALID);util.assertNever(s)}}ZodEffects.create=(n,e,t)=>new ZodEffects({schema:n,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(t)});ZodEffects.createWithPreprocess=(n,e,t)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:n},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(t)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(n,e)=>new ZodOptional({innerType:n,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(n,e)=>new ZodNullable({innerType:n,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===ZodParsedType.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(n,e)=>new ZodDefault({innerType:n,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return isAsync(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(n,e)=>new ZodCatch({innerType:n,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:i.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=n=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(n)});class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?INVALID:o.status==="dirty"?(t.dirty(),DIRTY(o.value)):this._def.out._parseAsync({data:o.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),i=s=>(isValid(s)&&(s.value=Object.freeze(s.value)),s);return isAsync(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}ZodReadonly.create=(n,e)=>new ZodReadonly({innerType:n,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create;ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const RiskLevelSchema=enumType(["low","medium","high"]),DecisionRoleSchema=enumType(["human","secretary","system"]),ToolCallStatusSchema=enumType(["calling","waiting_approval","approved","rejected","running","done","error"]),IsoDatetimeSchema=stringType().datetime(),ApprovalOptionSchema=objectType({optionId:stringType(),label:stringType(),kind:stringType().optional(),description:stringType().optional()}).strict(),ToolCallEventV1Schema=objectType({type:literalType("tool.call"),version:literalType(1).optional(),sessionId:stringType(),toolCallId:stringType(),toolName:stringType(),risk:RiskLevelSchema.optional(),status:ToolCallStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),expiresAt:IsoDatetimeSchema.optional(),target:stringType().optional(),action:stringType().optional(),arguments:recordType(unknownType()).optional(),result:unknownType().optional(),error:stringType().optional(),duration:numberType().int().nonnegative().optional(),inboxItemId:stringType().optional(),decisionBy:stringType().optional(),decisionRole:DecisionRoleSchema.optional(),onBehalfOf:stringType().optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolCallEventSchema=ToolCallEventV1Schema,SessionToolSchema=enumType(["claude-code","cursor","windsurf"]),SessionStatusSchema=enumType(["active","paused","completed","error"]),SessionStateEventV1Schema=objectType({type:literalType("session.state"),version:literalType(1).optional(),sessionId:stringType(),chat:stringType(),policy:stringType().optional(),policyVersion:stringType().optional(),status:SessionStatusSchema,previousStatus:stringType(),tool:SessionToolSchema,tokenUsage:numberType().int().nonnegative(),timestamp:IsoDatetimeSchema}).strict(),SessionStateEventSchema=SessionStateEventV1Schema,ToolControlCommandNameSchema=enumType(["approve","reject","pause","resume","stop","inject_message","approve_pattern"]),ToolControlCommandV1Schema=objectType({commandId:stringType().optional(),type:literalType("tool.control"),version:literalType(1).optional(),command:ToolControlCommandNameSchema,sessionId:stringType(),toolCallId:stringType().optional(),message:stringType().optional(),pattern:stringType().optional(),inboxItemId:stringType().optional(),actor:objectType({actorWebId:stringType(),actorRole:DecisionRoleSchema,onBehalfOf:stringType().optional()}).optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolControlCommandSchema=ToolControlCommandV1Schema,InboxApprovalStatusSchema=enumType(["pending","approved","rejected","expired"]),InboxApprovalEventV1Schema=objectType({type:literalType("inbox.approval"),version:literalType(1).optional(),inboxItemId:stringType(),sessionId:stringType(),toolCallId:stringType(),target:stringType().optional(),action:stringType().optional(),policy:stringType().optional(),policyVersion:stringType().optional(),risk:RiskLevelSchema,status:InboxApprovalStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),assignedTo:stringType().optional(),createdAt:IsoDatetimeSchema,expiresAt:IsoDatetimeSchema.optional(),resolvedAt:IsoDatetimeSchema.optional()}).strict(),InboxApprovalEventSchema=InboxApprovalEventV1Schema;unionType([ToolCallEventSchema,SessionStateEventSchema,ToolControlCommandSchema,InboxApprovalEventSchema]);const aiProviderResource=podTable("aiProvider",{id:id("id").default("{key}.ttl"),displayName:string$2("displayName").predicate(UDFS.displayName),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),homepage:string$2("homepage").predicate(UDFS.homepage),apiKeyUrl:string$2("apiKeyUrl").predicate(UDFS.apiKeyUrl),connectMode:string$2("connectMode").predicate(UDFS.connectMode),hasModel:uri("hasModel").predicate(UDFS.hasModel).array().link("aiModel"),defaultModel:uri("defaultModel").predicate(UDFS.defaultModel).link("aiModel"),supportsBackend:string$2("supportsBackend").predicate(UDFS.supportsBackend),capabilities:string$2("capabilities").array().predicate(UDFS.capability),rotationPolicy:string$2("rotationPolicy").predicate(UDFS.rotationPolicy)},{base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql",type:UDFS.Provider,namespace:UDFS}),MODEL_STORAGE={base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql"},aiModelSchema=solidSchema({id:id("id").default("{isProvidedBy.doc}#{key}"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AIModel]),displayName:string$2("displayName").predicate(UDFS.displayName),isProvidedBy:uri("isProvidedBy").predicate(UDFS.isProvidedBy).link(aiProviderResource),inputModalities:text("inputModalities").array().predicate(UDFS.inputModality),outputModalities:text("outputModalities").array().predicate(UDFS.outputModality),runtimeCapabilities:string$2("runtimeCapabilities").array().predicate(UDFS.capability),capabilities:uri("capabilities").array().predicate(UDFS.hasCapability),pricingInput:real("pricingInput").predicate(UDFS.pricingInput),pricingOutput:real("pricingOutput").predicate(UDFS.pricingOutput),status:string$2("status").predicate(UDFS.status).default("active"),createdAt:timestamp("createdAt").predicate(UDFS.createdAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt).notNull().defaultNow()},{type:UDFS.AIModel,subClassOf:UDFS.Model,namespace:UDFS}),chatModelSchema=aiModelSchema.extend({contextLength:integer$1("contextLength").predicate(UDFS.contextLength),maxOutputTokens:integer$1("maxOutputTokens").predicate(UDFS.maxOutputTokens)},{type:UDFS.ChatModel,namespace:UDFS}),embeddingModelSchema=aiModelSchema.extend({dimension:integer$1("dimension").predicate(UDFS.dimension)},{type:UDFS.EmbeddingModel,namespace:UDFS}),documentUnderstandingModelSchema=aiModelSchema.extend({},{type:UDFS.DocumentUnderstandingModel,namespace:UDFS}),rerankingModelSchema=aiModelSchema.extend({},{type:UDFS.RerankingModel,namespace:UDFS}),imageGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.ImageGenerationModel,namespace:UDFS}),speechRecognitionModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechRecognitionModel,namespace:UDFS}),speechSynthesisModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechSynthesisModel,namespace:UDFS}),videoGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.VideoGenerationModel,namespace:UDFS}),aiModelResource=aiModelSchema.table("aiModel",MODEL_STORAGE);chatModelSchema.table("chatModel",MODEL_STORAGE);embeddingModelSchema.table("embeddingModel",MODEL_STORAGE);documentUnderstandingModelSchema.table("documentUnderstandingModel",MODEL_STORAGE);rerankingModelSchema.table("rerankingModel",MODEL_STORAGE);imageGenerationModelSchema.table("imageGenerationModel",MODEL_STORAGE);speechRecognitionModelSchema.table("speechRecognitionModel",MODEL_STORAGE);speechSynthesisModelSchema.table("speechSynthesisModel",MODEL_STORAGE);videoGenerationModelSchema.table("videoGenerationModel",MODEL_STORAGE);const AI_MODEL_MODALITIES=["text","image","audio","video","pdf"],AI_MODEL_CAPABILITIES=["chat","embedding","reranking","tool_call","reasoning","web","vision","ocr","document_understanding","structured_output","indexing","image_generation","speech_recognition","speech_synthesis","video_generation"],AI_MODEL_CAPABILITY={chat:UDFS.ChatCapability,embedding:UDFS.EmbeddingCapability,reranking:UDFS.RerankingCapability,tool_call:UDFS.ToolCallCapability,reasoning:UDFS.ReasoningCapability,web:UDFS.WebCapability,vision:UDFS.VisionCapability,ocr:UDFS.OCRCapability,document_understanding:UDFS.DocumentUnderstandingCapability,structured_output:UDFS.StructuredOutputCapability,indexing:UDFS.IndexingCapability,image_generation:UDFS.ImageGenerationCapability,speech_recognition:UDFS.SpeechRecognitionCapability,speech_synthesis:UDFS.SpeechSynthesisCapability,video_generation:UDFS.VideoGenerationCapability},AI_MODEL_CLASS={chat:UDFS.ChatModel,embedding:UDFS.EmbeddingModel,document_understanding:UDFS.DocumentUnderstandingModel,reranking:UDFS.RerankingModel,image_generation:UDFS.ImageGenerationModel,speech_recognition:UDFS.SpeechRecognitionModel,speech_synthesis:UDFS.SpeechSynthesisModel,video_generation:UDFS.VideoGenerationModel};new Set(AI_MODEL_MODALITIES);new Set(AI_MODEL_CAPABILITIES);new Set(Object.values(AI_MODEL_CAPABILITY));new Map(Object.entries(AI_MODEL_CAPABILITY).map(([n,e])=>[e,n]));new Map(Object.entries(AI_MODEL_CLASS).map(([n,e])=>[e,n]));podTable("aiConfig",{id:id("id").default("config.ttl#{key}"),chatModel:uri("chatModel").predicate(UDFS.chatModel).link(aiModelResource),ocrModel:uri("ocrModel").predicate(UDFS.ocrModel).link(aiModelResource),readerModel:uri("readerModel").predicate(UDFS.readerModel).link(aiModelResource),embeddingModel:uri("embeddingModel").predicate(UDFS.embeddingModel).link(aiModelResource),indexerModel:uri("indexerModel").predicate(UDFS.indexerModel).link(aiModelResource),rerankerModel:uri("rerankerModel").predicate(UDFS.rerankerModel).link(aiModelResource),ocrEnabled:boolean$2("ocrEnabled").predicate(UDFS.ocrEnabled).default(!0),automaticOcr:boolean$2("automaticOcr").predicate(UDFS.automaticOcr).default(!0),imageRecognition:boolean$2("imageRecognition").predicate(UDFS.imageRecognition).default(!0),pdfRecognition:boolean$2("pdfRecognition").predicate(UDFS.pdfRecognition).default(!0),tableRecognition:boolean$2("tableRecognition").predicate(UDFS.tableRecognition).default(!1),processingMode:string$2("processingMode").predicate(UDFS.processingMode).default("auto"),readerPolicy:string$2("readerPolicy").predicate(UDFS.readerPolicy).default("auto"),readerPriority:string$2("readerPriority").predicate(UDFS.readerPriority).default("structure-first"),maxFileSizeMb:integer$1("maxFileSizeMb").predicate(UDFS.maxFileSizeMb).default(64),maxPages:integer$1("maxPages").predicate(UDFS.maxPages).default(500),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AIConfig,namespace:UDFS});podTable("vectorStore",{id:id("id").default("vector-stores.ttl#{key}"),name:string$2("name").predicate(UDFS.name),container:uri("container").predicate(UDFS.container),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.VectorStore,namespace:UDFS});podTable("indexedFile",{id:id("id").default("indexed-files.ttl#{key}"),fileUrl:uri("fileUrl").predicate(UDFS.fileUrl),vectorId:integer$1("vectorId").predicate(UDFS.vectorId),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),usageBytes:integer$1("usageBytes").predicate(UDFS.usageBytes),lastError:string$2("lastError").predicate(UDFS.lastError),indexedAt:timestamp("indexedAt").predicate(UDFS.indexedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.IndexedFile,namespace:UDFS});podTable("agentStatus",{id:id("id").default("agent-status.ttl#{key}"),agent:uri("agent").predicate(UDFS.agent).link(agentResource),status:string$2("status").predicate(UDFS.status),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),lastActivityAt:timestamp("lastActivityAt").predicate(UDFS.lastActivityAt),currentTask:uri("currentTask").predicate(UDFS.task).link(taskResource),errorMessage:string$2("errorMessage").predicate(UDFS.errorMessage)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AgentStatus,namespace:UDFS});const GatewayAccessKeyDeployment={local:"local",cloud:"cloud"},QuotaSnapshotStatus={available:"available",unsupported:"unsupported",error:"error"},gatewayAccessKeyResource=podTable("gatewayAccessKey",{id:id("id").default("ai/gateway/access-keys.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),secretHash:string$2("secretHash").predicate(UDFS.secretHash),name:string$2("name").predicate(UDFS.name),deployment:string$2("deployment").predicate(UDFS.deployment),scopes:text("scopes").array().predicate(UDFS.scopes),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),disabledAt:timestamp("disabledAt").predicate(UDFS.disabledAt),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/",type:UDFS.GatewayAccessKey,namespace:UDFS}),quotaSnapshotResource=podTable("quotaSnapshot",{id:id("id").default("ai/gateway/quota.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),deployment:string$2("deployment").predicate(UDFS.deployment),provider:string$2("provider").predicate(UDFS.provider),credential:uri("credential").predicate(UDFS.credential).link(credentialResource),status:string$2("status").predicate(UDFS.status),balance:integer$1("balance").predicate(UDFS.balance),windows:text("windows").predicate(UDFS.windows),observedAt:timestamp("observedAt").predicate(UDFS.observedAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),source:string$2("source").predicate(UDFS.source)},{base:"/.data/",type:UDFS.QuotaSnapshot,namespace:UDFS});ensureResourceIntrospectionColumns(gatewayAccessKeyResource);ensureResourceIntrospectionColumns(quotaSnapshotResource);function ensureResourceIntrospectionColumns(n){const e=n;e._&&e.columns&&e._.columns!==e.columns&&(e._.columns=e.columns);const t=e.columns;for(const i of Object.values(t??{}))typeof i.options?.predicate=="string"&&(i.getPredicate=()=>i.options?.predicate)}new Set(Object.values(GatewayAccessKeyDeployment));new Set(Object.values(QuotaSnapshotStatus));const AIConfigRuntimeCapability={chatCompletions:"chat_completions",responses:"responses",responsesWebSearch:"responses_web_search",imageInput:"image_input",imageGeneration:"image_generation",imageEditing:"image_editing",toolCalls:"tool_calls"};new Set(Object.values(AIConfigRuntimeCapability));const AI_CONFIG_PROVIDER_CATALOG=[{id:"dashscope",displayName:"DashScope",aliases:["qwen","alibaba","dashscope-cn"],defaultBaseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModels:["text-embedding-v4"],defaultModelType:"embedding"},{id:"openai",displayName:"OpenAI",aliases:["codex"],defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",displayName:"Anthropic",aliases:["claude"],defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",displayName:"Google",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta"},{id:"deepseek",displayName:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com/v1"},{id:"ollama",displayName:"Ollama",defaultBaseUrl:"http://localhost:11434/v1"},{id:"x-ai",displayName:"xAI",aliases:["xai"],defaultBaseUrl:"https://api.x.ai/v1"},{id:"openrouter",displayName:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1"},{id:"minimax",displayName:"MiniMax",defaultBaseUrl:"https://api.minimax.chat/v1"},{id:"mistral",displayName:"Mistral",defaultBaseUrl:"https://api.mistral.ai/v1"},{id:"groq",displayName:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1"},{id:"moonshot",displayName:"Moonshot",defaultBaseUrl:"https://api.moonshot.cn/v1"},{id:"zhipu",displayName:"ZhiPu",defaultBaseUrl:"https://open.bigmodel.cn/api/paas/v4"},{id:"codebuddy",displayName:"CodeBuddy",defaultBaseUrl:"https://api.codebuddy.ai/v1"},{id:"paddleocr",displayName:"PaddleOCR",aliases:["paddle"],defaultBaseUrl:"https://paddleocr.aistudio-app.com/api/v2/ocr/jobs",defaultModels:["PP-OCRv6"],defaultModelType:"document_understanding"}];new Map(AI_CONFIG_PROVIDER_CATALOG.map(n=>[n.id,n]));const ABSOLUTE_IRI=/^[a-zA-Z][a-zA-Z\d+.-]*:/;function normalizeText(n){return n.trim().toLowerCase()}function normalizeAIConfigResourceId(n){if(!n)return"";const e=n.trim();if(!e)return"";if(e.includes("#"))return e.split("#").pop()||e;if(!ABSOLUTE_IRI.test(e)&&!e.endsWith(".ttl"))return e;const t=e.replace(/\/$/,""),i=t.split("/").pop()||t;return i.endsWith(".ttl")?i.slice(0,-4):i}function aiConfigResourceRefToModelId(n,e){return normalizeAIConfigModelId(n,e)}function normalizeAIConfigModelId(n,e){const t=normalizeAIConfigResourceId(n);if(!t.includes("/"))return t;const[i,...s]=t.split("/");return s.length===0||!e?t:normalizeAIConfigProviderId(i)===normalizeAIConfigProviderId(e)?s.join("/"):t}function normalizeAIConfigProviderId(n){const e=normalizeText(normalizeAIConfigResourceId(n));if(!e)return"";for(const t of AI_CONFIG_PROVIDER_CATALOG)if(t.id===e||(t.aliases??[]).includes(e))return t.id;return e}function normalizeAIConfigModelStorageId(n,e){return aiConfigResourceRefToModelId(n,e)}function buildAIConfigModelStorageId(n,e){return aiModelResource.buildId({id:e,isProvidedBy:aiConfigProviderRef(n)})}function aiConfigProviderRef(n){const e=normalizeAIConfigProviderId(n);return e&&`settings/providers/${aiProviderResource.buildId({id:e})}`}function aiConfigModelRef(n,e){if(e===void 0)return normalizeAIConfigResourceId(n);const t=normalizeAIConfigProviderId(n),i=normalizeAIConfigModelStorageId(e,t);return t&&i?`settings/providers/${buildAIConfigModelStorageId(t,i)}`:i}function definePodModelDescriptor(n){return n}const credentialDescriptor={uri:UDFS.Credential,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Credential,resourceKind:"credential",description:"Generic credential material required by runtimes, tools, MCP servers, and providers.",storage:{base:"/settings/credentials.ttl",resourceIdPattern:"#{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative credential row id. Every credential in a provider pool keeps its own id."},provider:{type:"uri",predicate:UDFS.provider,references:{resource:"provider",key:"id"},description:"Provider resource URI this credential connects through, as a URI relation to the provider row."},authMode:{type:"string",predicate:UDFS.authMode,description:"Authentication mode such as apiKey, oauth, deviceCode, or console."},offeringId:{type:"string",predicate:UDFS.offeringId,description:"Offering id this credential connects through. Offerings are catalog content, so this stays a plain attribute, not a relation."},service:{type:"string",predicate:UDFS.service,required:!0,description:"Credential service grouping, for example ai or infra."},status:{type:"string",predicate:UDFS.status,description:"Credential health status."},apiKey:{type:"string",predicate:UDFS.apiKey,secret:!0,description:"Secret token or API key material."},storageMode:{type:"string",predicate:UDFS.storageMode,description:"Credential storage format, for example plaintext-v1 or secret-cell-v1."},secretPayload:{type:"string",predicate:UDFS.secretPayload,secret:!0,description:"Storage-mode-specific credential payload. plaintext-v1 stores a JSON payload here."},encryptedSecret:{type:"string",predicate:UDFS.encryptedSecret,secret:!0,description:"Encrypted credential payload stored in the Pod."},wrappedDataKey:{type:"string",predicate:UDFS.wrappedDataKey,secret:!0,description:"Wrapped data-encryption key for encrypted credential payloads."},encryptionAlgorithm:{type:"string",predicate:UDFS.encryptionAlgorithm,description:"Credential encryption algorithm identifier."},keyVersion:{type:"string",predicate:UDFS.keyVersion,description:"Key-management version used to encrypt the credential."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Credential scopes granted by the provider."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Credential expiry timestamp."},accountLabel:{type:"string",predicate:UDFS.accountLabel,description:"Provider account label associated with the credential."},lastRefreshAt:{type:"timestamp",predicate:UDFS.lastRefreshAt,description:"Last successful credential refresh timestamp."},reauthRequired:{type:"boolean",predicate:UDFS.reauthRequired,description:"Whether this credential requires user reauthentication."},baseUrl:{type:"string",predicate:UDFS.baseUrl,description:"Provider API base URL recorded on the credential."},proxyUrl:{type:"string",predicate:UDFS.proxyUrl,description:"Proxy URL used for requests made with this credential."},label:{type:"string",predicate:UDFS.label,description:"User-facing credential label."},isDefault:{type:"boolean",predicate:UDFS.isDefault,description:"Whether this credential is the default credential for its provider."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp, set by the store."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful use timestamp."},clientCredentialId:{type:"string",predicate:UDFS.clientCredentialId,description:"Client the issued credential belongs to. An external runtime identifier, not an RDF link."},appliedTo:{type:"string",predicate:UDFS.appliedTo,description:"Client application id the credential is in effect for. A runtime identifier, not an RDF link."},appliedOn:{type:"string",predicate:UDFS.appliedOn,description:"Device id that wrote the applied configuration. A runtime identifier, not an RDF link."},appliedAt:{type:"timestamp",predicate:UDFS.appliedAt,description:"Timestamp when the credential was applied."},failCount:{type:"number",predicate:UDFS.failCount,description:"Failed use count recorded for the credential."},rateLimitResetAt:{type:"timestamp",predicate:UDFS.rateLimitResetAt,description:"Timestamp when the provider rate limit is expected to reset."},oauthRefreshToken:{type:"string",predicate:UDFS.oauthRefreshToken,secret:!0,description:"OAuth refresh token."},oauthAccessToken:{type:"string",predicate:UDFS.oauthAccessToken,secret:!0,description:"OAuth access token."},oauthExpiresAt:{type:"timestamp",predicate:UDFS.oauthExpiresAt,description:"OAuth access token expiry timestamp."},projectId:{type:"string",predicate:UDFS.projectId,description:"Provider project identifier recorded for the credential."},organizationId:{type:"string",predicate:UDFS.organizationId,description:"Provider organization identifier recorded for the credential."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata bag; shared relations must be explicit fields."}},uniqueBy:["id"],writableFields:["provider","authMode","offeringId","service","status","apiKey","storageMode","secretPayload","encryptedSecret","wrappedDataKey","encryptionAlgorithm","keyVersion","scopes","expiresAt","accountLabel","lastRefreshAt","reauthRequired","baseUrl","proxyUrl","label","isDefault","lastUsedAt","clientCredentialId","appliedTo","appliedOn","appliedAt","failCount","rateLimitResetAt","oauthRefreshToken","oauthAccessToken","oauthExpiresAt","projectId","organizationId","metadata"],mergePolicy:"upsert",examples:[{request:"保存 Cloudflare tunnel token",match:{id:"cloudflare-5f2c9a1e"}},{request:"保存 OpenAI API key",match:{id:"openai-2b7d4e10"}}]},gatewayAccessKeyDescriptor={uri:UDFS.GatewayAccessKey,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.GatewayAccessKey,resourceKind:"gateway-access-key",description:"Control-primary Pod AI Gateway access key. The key owner is a semantic WebID/URI relation, while the secret itself is represented only by a hash.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/access-keys.ttl#key_1."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID or principal URI that owns this Gateway access key."},secretHash:{type:"string",predicate:UDFS.secretHash,required:!0,secret:!0,description:"Hash of the Gateway secret. Raw access key material must not be stored here."},name:{type:"string",predicate:UDFS.name,description:"User-visible label for distinguishing this Gateway access key."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment target: local or cloud."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Gateway scopes granted to this key."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Key expiry timestamp."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful Gateway use timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp. Presence means the key is no longer valid."},disabledAt:{type:"timestamp",predicate:UDFS.disabledAt,description:"Temporary disable timestamp. Clear it to enable the key again."}},uniqueBy:["id"],writableFields:["owner","secretHash","name","deployment","scopes","createdAt","expiresAt","lastUsedAt","revokedAt","disabledAt"],mergePolicy:"upsert",examples:[{request:"Create a local Gateway access key for a user",match:{id:"ai/gateway/access-keys.ttl#key_1"}}]},quotaSnapshotDescriptor={uri:UDFS.QuotaSnapshot,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.QuotaSnapshot,resourceKind:"quota-snapshot",description:"Observed Pod AI Gateway quota state for a provider credential. The credential field is a semantic URI relation, and normalized windows are stored as a serialized literal.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/quota.ttl#quota_1."},credential:{type:"uri",predicate:UDFS.credential,references:{resource:"credential",key:"id"},required:!0,description:"Credential resource URI this quota snapshot describes."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID that owns the credential and quota snapshot."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment scope: local or cloud."},provider:{type:"string",predicate:UDFS.provider,required:!0,description:"Normalized provider id for the quota snapshot."},status:{type:"string",predicate:UDFS.status,required:!0,description:"Quota availability status: available, unsupported, or error."},balance:{type:"number",predicate:UDFS.balance,description:"Normalized remaining quota balance when the provider exposes one."},windows:{type:"text",predicate:UDFS.windows,description:"Serialized normalized quota windows literal, for example JSON produced by Gateway normalization."},observedAt:{type:"timestamp",predicate:UDFS.observedAt,description:"Observation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Snapshot freshness expiry timestamp."},source:{type:"string",predicate:UDFS.source,description:"Observation source such as provider, gateway-cache, or manual."}},uniqueBy:["id"],writableFields:["credential","status","balance","windows","observedAt","expiresAt","source"],mergePolicy:"upsert",examples:[{request:"Record a fresh quota snapshot for a provider credential",match:{id:"ai/gateway/quota.ttl#quota_1"}}]},aiProviderDescriptor={uri:UDFS.Provider,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Provider,resourceKind:"provider",description:"AI provider endpoint configured in the Pod: endpoint, proxy, console entry, backend support, and the models it exposes. Its model rows live in the same provider document and are linked from here through hasModel.",storage:{base:"/settings/providers/",resourceIdPattern:"{key}.ttl"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative provider row id, for example openai.ttl."},displayName:{type:"string",predicate:UDFS.displayName,description:"Provider display name stored on the provider row."},baseUrl:{type:"string",predicate:UDFS.baseUrl,description:"Provider API base URL."},proxyUrl:{type:"string",predicate:UDFS.proxyUrl,description:"Proxy URL used for provider requests."},homepage:{type:"string",predicate:UDFS.homepage,description:"Provider homepage URL."},apiKeyUrl:{type:"string",predicate:UDFS.apiKeyUrl,description:"URL where a user creates an API key for this provider."},connectMode:{type:"string",predicate:UDFS.connectMode,description:"Connection mode recorded for the provider authorization method."},hasModel:{type:"uri",predicate:UDFS.hasModel,references:{resource:"ai-model",key:"id"},array:!0,description:"Model rows this provider exposes, as subjects inside the provider document."},defaultModel:{type:"uri",predicate:UDFS.defaultModel,references:{resource:"ai-model",key:"id"},description:"Default model for this provider when a request does not select one."},supportsBackend:{type:"string",predicate:UDFS.supportsBackend,description:"Backends this provider can serve, read as a backend list by the AI config selector."},capabilities:{type:"string",predicate:UDFS.capability,array:!0,description:"Provider capability tags."},rotationPolicy:{type:"string",predicate:UDFS.rotationPolicy,description:"Credential rotation policy recorded for the provider."}},uniqueBy:["id"],writableFields:["displayName","baseUrl","proxyUrl","homepage","apiKeyUrl","connectMode","hasModel","defaultModel","supportsBackend","capabilities","rotationPolicy"],mergePolicy:"upsert",examples:[{request:"Describe the provider document a Pod AI connection writes",match:{id:"openai.ttl"}}]},aiModelDescriptor={uri:UDFS.AIModel,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AIModel,resourceKind:"ai-model",description:"AI model exposed by a provider, stored as a subject inside that provider document. The provider relation and model capabilities are URI facts, while pricing and modality facts stay literals.",storage:{base:"/settings/providers/",resourceIdPattern:"{isProvidedBy.doc}#{key}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative model row id: provider document plus model key, for example openai.ttl#gpt-4o."},rdfType:{type:"uri",predicate:RDF$1.type,array:!0,description:"RDF class of the model row. The base table defaults to AIModel, and subclass tables narrow it."},displayName:{type:"string",predicate:UDFS.displayName,description:"Model display name stored on the model row."},isProvidedBy:{type:"uri",predicate:UDFS.isProvidedBy,references:{resource:"provider",key:"id"},description:"Provider document this model row belongs to, as a URI relation to the provider row."},inputModalities:{type:"text",predicate:UDFS.inputModality,array:!0,description:"Input modalities the model accepts."},outputModalities:{type:"text",predicate:UDFS.outputModality,array:!0,description:"Output modalities the model produces."},runtimeCapabilities:{type:"string",predicate:UDFS.capability,array:!0,description:"Adapter/runtime endpoint capabilities, kept separate from semantic model capabilities."},capabilities:{type:"uri",predicate:UDFS.hasCapability,array:!0,description:"Semantic capabilities of the model, as URIs."},pricingInput:{type:"number",predicate:UDFS.pricingInput,description:"Input token price recorded for the model."},pricingOutput:{type:"number",predicate:UDFS.pricingOutput,description:"Output token price recorded for the model."},status:{type:"string",predicate:UDFS.status,description:"Model availability status."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp, set by the store."},updatedAt:{type:"timestamp",predicate:UDFS.updatedAt,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["displayName","isProvidedBy","inputModalities","outputModalities","runtimeCapabilities","capabilities","pricingInput","pricingOutput","status","updatedAt"],mergePolicy:"upsert",examples:[{request:"Describe a model row inside a provider document",match:{id:"openai.ttl#gpt-4o"}}]},approvalDescriptor={uri:UDFS.ApprovalRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ApprovalRequest,resourceKind:"approval",description:"Durable approval request control item. Solid inbox notifications may point at this resource, but lifecycle and claim state live here.",storage:{base:"/.data/approvals/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Approval request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource that requested approval."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},toolCallId:{type:"string",predicate:UDFS.toolCallId,required:!0,description:"Opaque runtime tool-call identifier; not an RDF resource link."},toolName:{type:"string",predicate:UDFS.toolName,required:!0,description:"Runtime tool name that requires approval."},target:{type:"uri",predicate:ODRL.target,required:!0,description:"Target resource for the requested action. Schema field uses ODRL target in the executable resource."},action:{type:"uri",predicate:ODRL.action,required:!0,description:"Requested action URI. Schema field uses ODRL action in the executable resource."},risk:{type:"string",predicate:UDFS.risk,required:!0,description:"Risk level assigned by the runtime or policy layer."},status:{type:"string",predicate:UDFS.status,description:"Approval lifecycle status such as pending, handling, approved, rejected, resolved, or expired."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/approval handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to decide the request."},decisionBy:{type:"uri",predicate:UDFS.decisionBy,description:"WebID or agent resource that made the decision."},decisionRole:{type:"string",predicate:UDFS.decisionRole,description:"Role of the decision maker, for example human or secretary."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the decision applies."},reason:{type:"text",predicate:UDFS.reason,description:"Decision reason or policy explanation."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},approvalOptions:{type:"text",predicate:UDFS.approvalOptions,description:"Serialized approval options offered by the runtime."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version used to create or resolve this approval."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Decision timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","toolCallId","toolName","target","action","risk","status","leaseOwner","leaseExpiresAt","assignedTo","decisionBy","decisionRole","onBehalfOf","reason","context","approvalOptions","policyVersion","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending approval from Inbox subscription",match:{id:"2026/06/12.ttl#approval_1"}}]},inputRequestDescriptor={uri:UDFS.InputRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.InputRequest,resourceKind:"input-request",description:"Durable input request control item. It asks for missing information or a choice; approval/authority decisions remain ApprovalRequest.",storage:{base:"/.data/input-requests/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Input request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource waiting for input."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Run waiting for input."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task whose execution requires input."},requester:{type:"uri",predicate:UDFS.requester,description:"Runtime, worker, or Secretary resource that requested input."},requestKind:{type:"string",predicate:UDFS.requestKind,required:!0,description:"Input request category such as user-input, clarification, binding, or selection."},prompt:{type:"text",predicate:UDFS.prompt,required:!0,description:"Question or missing-information prompt."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},inputOptions:{type:"text",predicate:UDFS.inputOptions,description:"Serialized options offered for the input request."},status:{type:"string",predicate:UDFS.status,description:"Input request lifecycle status such as pending, handling, resolved, expired, or cancelled."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/input handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to answer the request."},response:{type:"text",predicate:UDFS.response,description:"Answer, selected option, or input supplied to unblock the run."},answeredBy:{type:"uri",predicate:UDFS.answeredBy,description:"WebID or agent resource that supplied the response."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the response applies."},reason:{type:"text",predicate:UDFS.reason,description:"Reason or explanation for the response."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque protocol-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Resolution timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","run","task","requester","requestKind","prompt","context","inputOptions","status","leaseOwner","leaseExpiresAt","assignedTo","response","answeredBy","onBehalfOf","reason","metadata","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending input request from Inbox subscription",match:{id:"2026/06/12.ttl#input_1"}}]};function exactIdStorage(n="/.data/"){return{base:n,resourceIdPattern:"{id}"}}const idField={type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id. For exact-id descriptors this includes the full document path and optional fragment."},captureCandidateDescriptor={uri:UDFS.CaptureCandidate,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureCandidate,resourceKind:"capture-candidate",description:"Temporary capture suggestion created from observed or ambiguous content. It is not formal memory until promoted through the appropriate typed resource and control flow.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource being considered."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Concise statement of what might be worth saving."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Proposed formal resource class such as Idea, Evidence, Note, Decision, Preference, Link, or ContactInfo."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Proposed folder, collection, project, task, issue, chat, or other scope."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence: high, medium, or low."},reason:{type:"text",predicate:UDFS.reason,description:"Short rationale for why this source might be worth capturing."},status:{type:"string",predicate:UDFS.status,description:"Candidate lifecycle status such as candidate, promoted, rejected, duplicate, ignored, or superseded."},sourceHash:{type:"string",predicate:UDFS.sourceHash,description:"Optional source digest for duplicate detection."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that created the candidate."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["source","summary","suggestedType","suggestedTarget","confidence","reason","status","sourceHash","chat","thread","task","run","actor","metadata","updatedAt"],mergePolicy:"upsert",examples:[{request:"Create a capture candidate from an observed chat message",match:{id:"candidates/2026/06/16.ttl#candidate_1"}}]},captureEventDescriptor={uri:UDFS.CaptureEvent,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureEvent,resourceKind:"capture-event",description:"Append-only capture decision ledger. It records direct commits, optimistic commits, candidate creation, promotion, rejection, correction, rollback, duplicate detection, and ignored decisions.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource considered by capture."},captureCandidate:{type:"uri",predicate:UDFS.captureCandidate,references:{resource:"capture-candidate",key:"id"},description:"Candidate resource involved in this event, when applicable."},targetResource:{type:"uri",predicate:UDFS.targetResource,description:"Formal resource affected by this capture decision."},decision:{type:"string",predicate:UDFS.captureDecision,required:!0,description:"Decision such as direct_commit, optimistic_commit, candidate_created, promoted, rejected, corrected, rollback, duplicate, or ignored."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Type suggested at decision time."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Target suggested at decision time."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence at decision time."},reason:{type:"text",predicate:UDFS.reason,description:"Explanation for the capture decision."},userCorrection:{type:"text",predicate:UDFS.userCorrection,description:"User correction to type, target, title, summary, or content."},approval:{type:"uri",predicate:UDFS.approval,references:{resource:"approval",key:"id"},description:"ApprovalRequest controlling an authority gate, if any."},inputRequest:{type:"uri",predicate:UDFS.inputRequest,references:{resource:"input-request",key:"id"},description:"InputRequest controlling missing information, if any."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that made or recorded the decision."},about:{type:"uri",predicate:SCHEMA.about,description:"Control object or semantic subject the event is about."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."}},uniqueBy:["id"],writableFields:["source","captureCandidate","targetResource","decision","suggestedType","suggestedTarget","confidence","reason","userCorrection","approval","inputRequest","chat","thread","task","run","actor","about","metadata"],mergePolicy:"append",examples:[{request:"Record that a chat message became a capture candidate",match:{id:"events/2026/06/16.ttl#event_1"}}]},contactDescriptor={uri:UDFS.Contact,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:VCARD.Individual,resourceKind:"contact",description:"Unified address-book projection for Solid users, external users, groups, and AI agents.",storage:exactIdStorage("/.data/contacts/"),fields:{id:idField,name:{type:"string",predicate:VCARD.fn,required:!0,description:"Display name."},avatarUrl:{type:"uri",predicate:VCARD.hasPhoto,description:"Avatar image URI."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Person, Agent, Chat, or external resource this contact card is about."},rdfType:{type:"uri",predicate:RDF$1.type,required:!0,description:"Semantic classifier for the represented resource."},contactType:{type:"string",predicate:UDFS.contactType,required:!0,description:"Runtime/source hint for handler selection."},isPublic:{type:"boolean",predicate:AS.audience,description:"Whether the contact is public."},externalPlatform:{type:"string",predicate:UDFS.externalPlatform,description:"External platform namespace."},externalId:{type:"string",predicate:UDFS.externalId,description:"Opaque external platform id; not a resource relation."},alias:{type:"string",predicate:UDFS.alias,description:"Private display alias."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},note:{type:"text",predicate:VCARD.note,description:"Private note."},sortKey:{type:"string",predicate:UDFS.sortKey,description:"Stable sort key."},gender:{type:"string",predicate:VCARD.hasGender,description:"Demographic hint."},province:{type:"string",predicate:VCARD.region,description:"Region."},city:{type:"string",predicate:VCARD.locality,description:"Locality."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."},lastSyncedAt:{type:"timestamp",predicate:UDFS.lastSyncedAt,description:"Last sync timestamp."}},uniqueBy:["id"],writableFields:["name","avatarUrl","about","rdfType","contactType","isPublic","externalPlatform","externalId","alias","starred","note","sortKey","gender","province","city","deletedAt","lastSyncedAt"],mergePolicy:"upsert",examples:[{request:"Create an AI agent contact projection",match:{id:"agent-secretary.ttl"}}]},chatDescriptor={uri:MEETING.LongChat,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.LongChat,resourceKind:"chat",description:"Interactive command surface/counterpart: who or what the user is talking with.",storage:exactIdStorage("/.data/chat/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Chat title."},description:{type:"string",predicate:DCTerms.description,description:"Chat description."},avatarUrl:{type:"uri",predicate:SCHEMA.image,description:"Avatar image URI."},author:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},status:{type:"string",predicate:UDFS.status,description:"Chat lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},muted:{type:"boolean",predicate:UDFS.muted,description:"Muted flag."},unreadCount:{type:"number",predicate:UDFS.unreadCount,description:"Unread message count."},contact:{type:"uri",predicate:UDFS.hasContact,references:{resource:"contact",key:"id"},description:"Optional counterpart/contact represented by this channel."},participants:{type:"uri",predicate:WF.participant,array:!0,description:"Participant resource URIs."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},lastActiveAt:{type:"timestamp",predicate:UDFS.lastActiveAt,description:"Last activity timestamp."},lastMessage:{type:"uri",predicate:UDFS.lastMessage,description:"Latest message pointer."},lastMessagePreview:{type:"text",predicate:SCHEMA.text,description:"Latest message preview."}},uniqueBy:["id"],writableFields:["title","description","avatarUrl","author","status","starred","muted","unreadCount","contact","participants","metadata","lastActiveAt","lastMessage","lastMessagePreview"],mergePolicy:"upsert",examples:[{request:"Create a team chat surface",match:{id:"team/index.ttl#this"}}]},threadDescriptor={uri:SIOC.Thread,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:SIOC.Thread,resourceKind:"thread",description:"Concrete timeline/place under one parent command surface. Ownership is thread.parent via sioc:has_parent.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container."},title:{type:"string",predicate:DCTerms.title,description:"Thread title."},status:{type:"string",predicate:UDFS.status,description:"Thread lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},workspace:{type:"uri",predicate:UDFS.workspace,description:"Storage-layer workspace/container URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."}},uniqueBy:["id"],writableFields:["parent","title","status","starred","workspace","metadata"],mergePolicy:"upsert",examples:[{request:"Create a thread under a chat surface",match:{id:"chat/team/index.ttl#thread"}}]},messageDescriptor={uri:MEETING.Message,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.Message,resourceKind:"message",description:"Human/runtime communication item under one parent command surface and optionally a concrete thread timeline.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container URI."},chat:{type:"uri",predicate:WF.message,references:{resource:"chat",key:"id"},description:"Solid Chat compatibility containment relation."},thread:{type:"uri",predicate:SIOC.has_member,references:{resource:"thread",key:"id"},description:"Thread containment relation."},maker:{type:"uri",predicate:FOAF.maker,description:"Author resource IRI."},role:{type:"string",predicate:UDFS.messageType,description:"Message role."},content:{type:"text",predicate:SIOC.content,required:!0,description:"Plain text content."},richContent:{type:"text",predicate:SIOC.richContent,description:"Structured/rich content payload."},status:{type:"string",predicate:UDFS.messageStatus,description:"Message lifecycle status."},toolName:{type:"string",predicate:UDFS.toolName,description:"Tool name for tool messages."},toolCallId:{type:"string",predicate:UDFS.toolCallId,description:"Opaque tool call id; not a resource relation."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},replacedBy:{type:"string",predicate:DCTerms.isReplacedBy,description:"Replacement message reference."},deletedAt:{type:"timestamp",predicate:SCHEMA.dateDeleted,description:"Deletion timestamp."},senderName:{type:"string",predicate:UDFS.senderName,description:"Display sender name."},senderAvatarUrl:{type:"uri",predicate:UDFS.senderAvatarUrl,description:"Display sender avatar."},mentions:{type:"uri",predicate:UDFS.mentions,array:!0,description:"Mentioned resource URIs."},replyTo:{type:"uri",predicate:UDFS.replyTo,description:"Original message URI."},routedBy:{type:"uri",predicate:UDFS.routedBy,description:"Routing agent URI."},routeTargetAgent:{type:"uri",predicate:UDFS.routeTargetAgent,description:"Target agent URI."},coordinationId:{type:"string",predicate:UDFS.coordinationId,description:"Opaque multi-agent coordination id."}},uniqueBy:["id"],writableFields:["parent","chat","thread","maker","role","content","richContent","status","toolName","toolCallId","metadata","replacedBy","deletedAt","senderName","senderAvatarUrl","mentions","replyTo","routedBy","routeTargetAgent","coordinationId"],mergePolicy:"append",examples:[{request:"Append a message under a team chat",match:{id:"chat/team/2026/06/14/messages.ttl#msg_1"}}]},chatProjectContextDescriptor={uri:UDFS.ChatProjectContext,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ChatProjectContext,resourceKind:"chat-project-context",description:"Workspace-scoped instructions and explicit memory-use preference shared by related chat threads.",storage:exactIdStorage("/.data/chat-projects/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this context."},instructions:{type:"text",predicate:UDFS.systemMessage,description:"User-maintained project instructions."},memoryEnabled:{type:"boolean",predicate:UDFS.memoryEnabled,description:"Whether explicit project memories may be injected into model context."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","instructions","memoryEnabled","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Save shared instructions for a workspace",match:{id:"workspace-key.ttl"}}]},chatProjectMemoryDescriptor={uri:UDFS.ProjectMemory,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ProjectMemory,resourceKind:"chat-project-memory",description:"One user-approved, workspace-scoped memory entry with optional message provenance.",storage:exactIdStorage("/.data/chat-project-memories/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this memory."},text:{type:"text",predicate:SCHEMA.text,required:!0,description:"Explicit memory text."},sourceMessage:{type:"uri",predicate:UDFS.sourceMessage,description:"Optional source message URI."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","text","sourceMessage","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Remember an explicit project fact",match:{id:"memory-id.ttl"}}]},conversationShareDescriptor={uri:UDFS.ConversationShare,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ConversationShare,resourceKind:"conversation-share",description:"Revocable metadata record for a sanitized, read-only conversation export.",storage:exactIdStorage("/.data/chat-shares/"),fields:{id:idField,thread:{type:"uri",predicate:UDFS.targetThread,required:!0,description:"Shared thread URI."},resourceUrl:{type:"uri",predicate:SCHEMA.url,required:!0,description:"Public read-only HTML resource URL."},includeToolDetails:{type:"boolean",predicate:UDFS.includeToolDetails,description:"Whether sanitized tool details were included."},excludedMessageIds:{type:"string",predicate:UDFS.excludedMessage,array:!0,description:"Messages excluded by the user before sharing."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp."}},uniqueBy:["id"],writableFields:["thread","resourceUrl","includeToolDetails","excludedMessageIds","createdAt","revokedAt"],mergePolicy:"upsert",examples:[{request:"Record a read-only conversation share",match:{id:"share-id.ttl"}}]},ideaDescriptor={uri:UDFS.Idea,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Idea,resourceKind:"idea",description:"File-primary candidate extracted from conversation before it is promoted to committed work. The document owns human-readable content; meta owns status and routing facts.",storage:exactIdStorage("/.data/ideas/"),fields:{id:idField,summary:{type:"string",predicate:DCTerms.abstract,required:!0,description:"Short summary of the idea."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the idea body."},input:{type:"text",predicate:DCTerms.description,description:"Original or synthesized input text."},status:{type:"string",predicate:UDFS.status,description:"Idea lifecycle status."},commitment:{type:"string",predicate:UDFS.commitment,description:"Commitment level such as thought, direction, tentative_decision, or committed."},affectedArea:{type:"string",predicate:UDFS.affectedArea,description:"System or product area the idea may affect."},currentUnderstanding:{type:"text",predicate:UDFS.currentUnderstanding,description:"Current synthesized understanding."},openQuestions:{type:"text",predicate:UDFS.openQuestions,array:!0,description:"Open questions before promotion."},related:{type:"uri",predicate:DCTerms.relation,array:!0,description:"Related control records or resources."},conflicts:{type:"text",predicate:UDFS.conflicts,array:!0,description:"Potential semantic conflicts."},nextStep:{type:"text",predicate:UDFS.nextStep,description:"Suggested next action."},promotedTo:{type:"uri",predicate:UDFS.promotedTo,description:"Committed resource created from the idea."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Source chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Source thread."},sourceMessages:{type:"uri",predicate:DCTerms.source,array:!0,description:"Source messages."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["summary","document","input","status","commitment","affectedArea","currentUnderstanding","openQuestions","related","conflicts","nextStep","promotedTo","chat","thread","sourceMessages","createdBy","metadata"],mergePolicy:"upsert",examples:[{request:"Capture a fragmented product idea for later triage",match:{id:"2026/05/28.ttl#idea_symphony_quality_metrics"}}]},issueDescriptor={uri:UDFS.Issue,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Issue,resourceKind:"issue",description:"File-primary user-facing work item for a requirement, bug, support item, investigation, or feature request. The document owns human-readable content; meta owns status and routing facts.",storage:{base:"/.data/issues/",resourceIdPattern:"{id}"},fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Compact issue label for list/search surfaces; the file owns the full title/body."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the issue body."},description:{type:"text",predicate:DCTerms.description,description:"Issue description."},status:{type:"string",predicate:UDFS.status,description:"Issue lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Issue priority."},labels:{type:"text",predicate:UDFS.tags,array:!0,description:"Tags or labels."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Owning or source chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Owning or source thread."},parentIssue:{type:"uri",predicate:UDFS.parentIssue,references:{resource:"issue",key:"id"},description:"Parent issue."},tasks:{type:"uri",predicate:UDFS.task,array:!0,description:"Executable task slices."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},closedAt:{type:"timestamp",predicate:UDFS.closedAt,description:"Closure timestamp."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."}},uniqueBy:["id"],writableFields:["title","document","description","status","priority","labels","chat","thread","parentIssue","tasks","createdBy","assignedTo","closedAt","deletedAt"],mergePolicy:"upsert",examples:[{request:"Create a Symphony issue for a delegated implementation slice",match:{id:"issue_symphony_runtime_projection.ttl"}}]},taskDescriptor={uri:UDFS.Task,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Task,resourceKind:"task",description:"Durable executable work unit. Scheduling, runner selection, and concrete attempts live outside Task.",storage:exactIdStorage("/.data/task/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,description:"Task title."},instruction:{type:"text",predicate:UDFS.instruction,required:!0,description:"Executable instruction."},prompt:{type:"text",predicate:UDFS.prompt,description:"Runtime prompt projection."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Originating issue."},message:{type:"uri",predicate:UDFS.message,description:"Message that produced this task."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Task lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Priority."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["title","instruction","prompt","issue","message","workspace","status","priority","assignedTo","source","metadata"],mergePolicy:"upsert",examples:[{request:"Create an executable task under an issue",match:{id:"task_symphony_worker_projection"}}]},scheduleDescriptor={uri:UDFS.Schedule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Schedule,resourceKind:"schedule",description:"Time-based trigger configuration for a Task.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},required:!0,description:"Scheduled task."},status:{type:"string",predicate:UDFS.status,description:"Schedule lifecycle status."},scheduleKind:{type:"string",predicate:UDFS.scheduleKind,description:"Schedule kind: once, interval, or cron."},cron:{type:"string",predicate:UDFS.cron,description:"Cron expression."},intervalSeconds:{type:"number",predicate:UDFS.intervalSeconds,description:"Interval in seconds."},timezone:{type:"string",predicate:UDFS.timezone,description:"Timezone."},startsAt:{type:"timestamp",predicate:UDFS.startsAt,description:"Start timestamp."},nextRunAt:{type:"timestamp",predicate:UDFS.nextRunAt,description:"Next run timestamp."},lastRunAt:{type:"timestamp",predicate:UDFS.lastRunAt,description:"Last run timestamp."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["task","status","scheduleKind","cron","intervalSeconds","timezone","startsAt","nextRunAt","lastRunAt","metadata"],mergePolicy:"upsert",examples:[{request:"Create a time trigger for a task",match:{id:"schedules/schedule_1.ttl"}}]},automationRuleDescriptor={uri:UDFS.AutomationRule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AutomationRule,resourceKind:"automation_rule",description:"Policy, condition, and action wiring that can dispatch tasks or scheduled work.",storage:exactIdStorage(),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Rule title."},description:{type:"text",predicate:DCTerms.description,description:"Rule description."},status:{type:"string",predicate:UDFS.status,description:"Rule lifecycle status."},ruleKind:{type:"string",predicate:UDFS.ruleKind,description:"Rule kind: event, schedule, or manual."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task dispatched by this rule."},schedule:{type:"uri",predicate:UDFS.schedule,references:{resource:"schedule",key:"id"},description:"Schedule that triggers this rule."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},condition:{type:"json",predicate:UDFS.condition,description:"Structured condition."},actions:{type:"json",predicate:UDFS.actions,description:"Structured actions."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},lastTriggeredAt:{type:"timestamp",predicate:UDFS.lastTriggeredAt,description:"Last trigger timestamp."},lastRunStatus:{type:"string",predicate:UDFS.lastRunStatus,description:"Last run status."}},uniqueBy:["id"],writableFields:["title","description","status","ruleKind","task","schedule","source","target","condition","actions","metadata","lastTriggeredAt","lastRunStatus"],mergePolicy:"upsert",examples:[{request:"Create an automation rule that dispatches a task",match:{id:"automation/rule_1.ttl"}}]},deliveryDescriptor={uri:UDFS.Delivery,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Delivery,resourceKind:"delivery",description:"Internal handoff envelope between threads, sessions, agents, and runtimes.",storage:exactIdStorage(),fields:{id:idField,kind:{type:"string",predicate:UDFS.deliveryKind,description:"Delivery kind."},status:{type:"string",predicate:UDFS.status,description:"Delivery lifecycle status."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task being delivered."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Source thread."},targetThread:{type:"uri",predicate:UDFS.targetThread,references:{resource:"thread",key:"id"},description:"Target thread."},targetSession:{type:"uri",predicate:UDFS.targetSession,description:"Target session."},actor:{type:"uri",predicate:AS.actor,description:"Actor."},object:{type:"uri",predicate:AS.object,description:"Object resource."},objective:{type:"text",predicate:UDFS.objective,description:"Short objective."},payload:{type:"json",predicate:UDFS.payload,description:"Structured payload."},projection:{type:"json",predicate:UDFS.projection,description:"Runtime projection."},projectedRole:{type:"string",predicate:UDFS.projectedRole,description:"Projected runtime role."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},error:{type:"text",predicate:UDFS.error,description:"Failure detail."},dispatchedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Dispatch timestamp."},consumedAt:{type:"timestamp",predicate:UDFS.consumedAt,description:"Consumption timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["kind","status","task","source","target","chat","thread","targetThread","targetSession","actor","object","objective","payload","projection","projectedRole","metadata","error","dispatchedAt","consumedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Create a worker delivery package",match:{id:"task/symphony/2026/05/28/deliveries.ttl#delivery_1"}}]},runDescriptor={uri:UDFS.Run,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Run,resourceKind:"run",description:"One concrete execution attempt by an agent runtime.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task being executed."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Delivery that caused or carries this run."},trigger:{type:"uri",predicate:UDFS.trigger,description:"Resource that triggered the run."},input:{type:"uri",predicate:UDFS.input,description:"Concrete input/context projection resource."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},required:!0,description:"Runtime thread."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Run lifecycle status."},runner:{type:"string",predicate:UDFS.runner,required:!0,description:"Runtime implementation."},prompt:{type:"string",predicate:UDFS.prompt,description:"Prompt or prompt version."},externalRunId:{type:"string",predicate:UDFS.externalRunId,description:"Opaque external runtime id; not a resource relation."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Lease owner."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Lease expiration timestamp."},heartbeatAt:{type:"timestamp",predicate:UDFS.heartbeatAt,description:"Heartbeat timestamp."},cancelRequestedAt:{type:"timestamp",predicate:UDFS.cancelRequestedAt,description:"Cancel request timestamp."},error:{type:"string",predicate:UDFS.error,description:"Failure detail."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},startedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Start timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["task","delivery","trigger","input","thread","workspace","status","runner","prompt","externalRunId","leaseOwner","leaseExpiresAt","heartbeatAt","cancelRequestedAt","error","metadata","startedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Record a runtime execution attempt",match:{id:"task/symphony/2026/05/28/runs.ttl#run_1"}}]},runStepDescriptor={uri:UDFS.RunStep,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.RunStep,resourceKind:"run_step",description:"Append-only execution fact emitted while a run executes.",storage:exactIdStorage(),fields:{id:idField,run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},required:!0,description:"Run this step belongs to."},stepType:{type:"string",predicate:UDFS.stepType,required:!0,description:"RunStep event type."},message:{type:"string",predicate:DCTerms.description,description:"Human-readable step message."},payload:{type:"json",predicate:UDFS.payload,description:"Structured step payload."}},uniqueBy:["id"],writableFields:["run","stepType","message","payload"],mergePolicy:"append",examples:[{request:"Append a runtime tool call step",match:{id:"task/symphony/2026/05/28/runs.ttl#run-step_1"}}]},evidenceDescriptor={uri:UDFS.Evidence,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Evidence,resourceKind:"evidence",description:"Append-only proof or finding for a workflow control object.",storage:exactIdStorage(),fields:{id:idField,evidenceKind:{type:"string",predicate:UDFS.evidenceKind,required:!0,description:"Evidence kind."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object this evidence supports."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Related issue."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},summary:{type:"text",predicate:DCTerms.abstract,description:"Evidence summary."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the evidence."},outcome:{type:"string",predicate:UDFS.outcome,description:"Evidence outcome."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["evidenceKind","about","issue","task","delivery","run","thread","summary","source","actor","outcome","metadata"],mergePolicy:"append",examples:[{request:"Record test evidence for a task",match:{id:"task/symphony/2026/05/28/evidence.ttl#evidence_1"}}]},reportDescriptor={uri:UDFS.Report,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Report,resourceKind:"report",description:"Closure, review, handoff, status, or quality summary for a control object.",storage:exactIdStorage(),fields:{id:idField,reportKind:{type:"string",predicate:UDFS.reportKind,required:!0,description:"Report kind."},status:{type:"string",predicate:UDFS.status,description:"Report lifecycle status."},outcome:{type:"string",predicate:UDFS.outcome,description:"Reported outcome."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object being summarized."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Related issue."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},evidence:{type:"uri",predicate:UDFS.evidence,references:{resource:"evidence",key:"id"},array:!0,description:"Evidence summarized by this report."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Report summary."},reviewer:{type:"uri",predicate:SCHEMA.reviewedBy,description:"Reviewer."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the report."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},metricFacts:{type:"json",predicate:UDFS.metricFacts,description:"Structured metric facts."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},publishedAt:{type:"timestamp",predicate:DCTerms.issued,description:"Publication timestamp."}},uniqueBy:["id"],writableFields:["reportKind","status","outcome","about","issue","task","delivery","run","thread","evidence","summary","reviewer","actor","source","metricFacts","metadata","publishedAt"],mergePolicy:"upsert",examples:[{request:"Publish a worker handoff report",match:{id:"task/symphony/2026/05/28/reports.ttl#report_1"}}]},sessionDescriptor={uri:UDFS.term("Session"),version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.term("Session"),resourceKind:"session",description:"Runtime or collaboration session lifecycle projection for a concrete thread.",storage:exactIdStorage("/.data/sessions/"),fields:{id:idField,owner:{type:"uri",predicate:UDFS.actor,required:!0,description:"Session owner."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},status:{type:"string",predicate:UDFS.sessionStatus,description:"Session lifecycle status."},tool:{type:"string",predicate:UDFS.sessionTool,description:"Runtime tool or backend."},tokenUsage:{type:"number",predicate:UDFS.tokenUsage,description:"Token usage."},messages:{type:"uri",predicate:UDFS.message,array:!0,description:"Messages in this session."},policy:{type:"uri",predicate:UDFS.policy,description:"Policy resource."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},archivedAt:{type:"timestamp",predicate:UDFS.archivedAt,description:"Archive timestamp."}},uniqueBy:["id"],writableFields:["owner","chat","thread","status","tool","tokenUsage","messages","policy","policyVersion","metadata","archivedAt"],mergePolicy:"upsert",examples:[{request:"Record a worker runtime session",match:{id:"2026/05/28/sess_1.ttl"}}]},officialPodModelDescriptors=[credentialDescriptor,gatewayAccessKeyDescriptor,quotaSnapshotDescriptor,aiProviderDescriptor,aiModelDescriptor,contactDescriptor,chatDescriptor,threadDescriptor,messageDescriptor,chatProjectContextDescriptor,chatProjectMemoryDescriptor,conversationShareDescriptor,ideaDescriptor,issueDescriptor,taskDescriptor,scheduleDescriptor,automationRuleDescriptor,deliveryDescriptor,runDescriptor,runStepDescriptor,evidenceDescriptor,reportDescriptor,captureCandidateDescriptor,captureEventDescriptor,sessionDescriptor,approvalDescriptor,inputRequestDescriptor];function createPodModelDescriptorRegistry(n=officialPodModelDescriptors){const e=new Map(n.map(t=>[t.uri,t]));return{list(t={}){return n.filter(i=>!(t.source&&i.source!==t.source||t.resourceKind&&i.resourceKind!==t.resourceKind))},describe(t){return e.get(t)??null}}}createPodSchema();function createPodSchema(n=createPodModelDescriptorRegistry()){const e=(t={})=>{const i=t.uri??t.schemaUri;if(!i)return n.list();const s=n.describe(i);return s?[s]:[]};return{list:n.list,describe(t){const i=typeof t=="string"?t:"uri"in t?t.uri:t.schemaUri;return n.describe(i)},classes(t={}){return e(t).map(i=>({schemaUri:i.uri,resourceKind:i.resourceKind,class:i.class,namespace:i.namespace,source:i.source,trustLevel:i.trustLevel,description:i.description}))},search(t){const i=normalizeSearchTerms(t.query);return i.length===0?[]:n.list({source:t.source,resourceKind:t.resourceKind}).map(s=>scoreDescriptorSearch(s,i)).filter(s=>s!==null).sort((s,o)=>o.score-s.score||s.uri.localeCompare(o.uri)).slice(0,Math.max(1,t.limit??10))},predicates(t={}){return e(t).flatMap(i=>Object.entries(i.fields).filter(([s])=>!t.field||s===t.field).map(([s,o])=>({schemaUri:i.uri,field:s,predicate:o.predicate,type:o.type,required:!!o.required,secret:!!o.secret,array:!!o.array,description:o.description})))}}}function normalizeSearchTerms(n){return n.toLowerCase().split(/[\s,;:/#._-]+/u).map(e=>e.trim()).filter(Boolean)}function scoreDescriptorSearch(n,e){const t=new Set;let i=0;const s=(o,l,u)=>{if(!l)return;const h=l.toLowerCase();for(const d of e)h.includes(d)&&(t.add(o),i+=u)};s("uri",n.uri,10),s("class",n.class,10),s("namespace",n.namespace,4),s("resourceKind",n.resourceKind,8),s("description",n.description,4),s("storage",`${n.storage.base}${n.storage.resourceIdPattern}`,3);for(const[o,l]of Object.entries(n.fields))s(`field:${o}`,o,6),s(`predicate:${o}`,l.predicate,6),s(`description:${o}`,l.description,3);for(const o of n.examples){s("example",o.request,3);for(const[l,u]of Object.entries(o.match))s(`example:${l}`,String(u),3)}return i<=0?null:{uri:n.uri,resourceKind:n.resourceKind,class:n.class,namespace:n.namespace,source:n.source,trustLevel:n.trustLevel,description:n.description,score:i,matchedFields:[...t].sort()}}const CLOUD_PROVISIONING_UNAVAILABLE="Cloud storage is not ready. Please wait for Xpod to reconnect and try again.",localProvisionResolvers=new WeakMap;function isManagedLocalProvisionHost(){return typeof window<"u"&&localProvisionResolvers.has(window)}function unregisterLocalProvisionResolver(){typeof window<"u"&&localProvisionResolvers.delete(window)}function registerLocalProvisionResolver(n){typeof window<"u"&&localProvisionResolvers.set(window,n)}function readStoredProvisionCodeRaw(){try{const n=sessionStorage.getItem("provisionCode")?.trim();return n||void 0}catch{return}}function isProvisionCodeCurrent(n){const e=n.split(".")[0];if(!e)return!0;try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return!0;const s=JSON.parse(globalThis.atob(i));return typeof s.exp=="number"?s.exp>Math.floor(Date.now()/1e3):!0}catch{return!0}}function normalizeProvisionCode(n){const e=n?.trim();if(e)return isProvisionCodeCurrent(e)?e:void 0}function getStoredProvisionCode(){return normalizeProvisionCode(readStoredProvisionCodeRaw())}function setStoredProvisionCode(n){try{sessionStorage.setItem("provisionCode",n)}catch{}}function clearStoredProvisionCode(){try{sessionStorage.removeItem("provisionCode")}catch{}}function buildPodCreatePayload(n,e=getStoredProvisionCode(),t){const i={name:n.trim()};return e&&(i.settings={provisionCode:e,...t?{provisionReceipt:t}:{}}),i}async function resolveProvisionCodeForCurrentScope(n){const e=await resolveCurrentProvisionTargetState(n);if(e.activeProvisionCode)return e.activeProvisionCode;if(e.hasProvisionOperation)throw new Error(CLOUD_PROVISIONING_UNAVAILABLE)}async function resolveCurrentProvisionTargetState(n){const e=typeof window<"u"?window.__XPOD__:void 0;if(e?.authenticating===!0){const l=typeof e.provisionCode=="string"?e.provisionCode.trim():void 0,u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):(clearStoredProvisionCode(),l?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}:{hasProvisionOperation:!1})}const t=n?.trim()||(typeof e?.provisionCode=="string"?e.provisionCode.trim():void 0),i=typeof window<"u"?localProvisionResolvers.get(window):void 0;if(!t&&i){const l=await i(),u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}}const s=t||readStoredProvisionCodeRaw(),o=normalizeProvisionCode(s);return o?{activeProvisionCode:o,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(o)?.storageRoot}:s?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(s)?.storageRoot}:{hasProvisionOperation:!1}}async function resolveProvisionCodeForPodCreate(n){return resolveProvisionCodeForCurrentScope(n)}function decodeProvisionScopePayload(n){const e=parseProvisionScopePayload(n);if(!e)return;const t=typeof e.serviceAccessToken=="string"?e.serviceAccessToken:typeof e.serviceToken=="string"?e.serviceToken:void 0;if(!(typeof e.spUrl!="string"||!t)&&!(typeof e.exp=="number"&&e.exp<Math.floor(Date.now()/1e3))&&!(typeof e.serviceAccessTokenExp=="number"&&e.serviceAccessTokenExp<Math.floor(Date.now()/1e3)))return{spUrl:ensureTrailingSlash(e.spUrl),serviceToken:t,serviceAccessToken:typeof e.serviceAccessToken=="string"?e.serviceAccessToken:void 0,serviceAccessTokenExp:typeof e.serviceAccessTokenExp=="number"?e.serviceAccessTokenExp:void 0,spDomain:typeof e.spDomain=="string"?e.spDomain:void 0,exp:typeof e.exp=="number"?e.exp:void 0}}function parseProvisionScopePayload(n){if(!n)return;const e=n.split(".")[0];if(e)try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return;const s=Uint8Array.from(globalThis.atob(i),o=>o.charCodeAt(0));return JSON.parse(new TextDecoder().decode(s))}catch{return}}function resolveProvisionScope(n){const e=decodeProvisionScopePayload(n);if(!e)return;const t=e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl);return{lookupUrl:t,storageRoot:t,serviceToken:e.serviceToken}}function resolveProvisionStorageTarget(n){const e=parseProvisionScopePayload(n);if(typeof e?.spUrl=="string")return{storageRoot:e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl)}}async function prepareProvisionedPod(n,e,t){const i=resolveProvisionScope(t);if(!i||!t)return t?{provisionCode:t}:void 0;const s=await n(new URL("/provision/pods",resolveProvisionApiBaseUrl(i)).toString(),{method:"POST",headers:{Authorization:`Bearer ${i.serviceToken}`,"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({podName:e})});if(!s.ok)throw new Error(await readResponseMessage(s)??"Failed to prepare Local Pod");const o=await s.json().catch(()=>{}),l=typeof o?.provisionReceipt=="string"?o.provisionReceipt:void 0;if(!l)throw new Error("Local Pod preparation did not return a provision receipt");return{provisionCode:t,provisionReceipt:l}}function resolveProvisionApiBaseUrl(n){return(isManagedLocalProvisionHost()?currentLoopbackLookupUrl():void 0)??n.lookupUrl}function currentLoopbackLookupUrl(){if(!(typeof window>"u"))try{const n=new URL(window.location.href);return isLoopbackHostname$2(n.hostname)?ensureTrailingSlash(n.origin):void 0}catch{return}}function isLoopbackHostname$2(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}async function readResponseMessage(n){const e=await n.text?.().catch(()=>{});if(e)try{const t=JSON.parse(e);return typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:e}catch{return e}}function storageUrlBelongsToRoot(n,e){const t=normalizeStorageUrl(n),i=normalizeStorageRoot$1(e);return!!(t&&i&&t.startsWith(i))}function normalizeStorageRoot$1(n){if(n)try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}const SOLID_STORAGE_KEYS=new Set(["solid:storage","http://www.w3.org/ns/solid/terms#storage","pim:storage","http://www.w3.org/ns/pim/space#storage"]);async function fetchProfileStorageUrls(n,e){const t=await n(e,{headers:{Accept:"text/turtle, application/ld+json, application/json"},credentials:"include"}).catch(()=>{});if(!t?.ok)return[];const i=t.headers?.get?.("content-type")??"",s=await t.text().catch(()=>"");if(!s)return[];if(i.includes("json"))try{return uniqueNormalizedStorageUrls(extractStorageUrlsFromJson(JSON.parse(s)))}catch{return[]}return uniqueNormalizedStorageUrls(extractStorageUrlsFromTurtle(s))}function extractStorageUrlsFromTurtle(n){return Array.from(n.matchAll(/(?:solid:storage|pim:storage|<http:\/\/www\.w3\.org\/ns\/solid\/terms#storage>|<http:\/\/www\.w3\.org\/ns\/pim\/space#storage>)\s+<([^>]+)>/giu)).map(e=>e[1]).filter(e=>typeof e=="string"&&e.length>0)}function extractStorageUrlsFromJson(n){const e=new Set,t=new WeakSet,i=(s,o=!1)=>{if(typeof s=="string"){o&&e.add(s);return}if(!(!s||typeof s!="object")&&!t.has(s)){if(t.add(s),Array.isArray(s)){for(const l of s)i(l,o);return}for(const[l,u]of Object.entries(s)){const h=SOLID_STORAGE_KEYS.has(l);if(o&&l==="@id"){i(u,!0);continue}i(u,o||h)}}};return i(n),Array.from(e)}function normalizeStorageUrl(n){try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}function uniqueNormalizedStorageUrls(n){const e=new Set;for(const t of n){const i=normalizeStorageUrl(t);i&&e.add(i)}return Array.from(e)}function ensureTrailingSlash(n){return n.replace(/\/+$/u,"")+"/"}const XPOD_RETURN_PATH_PREFIXES=["/dashboard","/status","/network","/settings","/ai-config","/ai-connections"];function normalizeXpodReturnPath(n){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const e=n.trim(),t=decodeForValidation(e),i=t.split(/[?#]/,1)[0];if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||t.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(t)||t.startsWith("//")||i.split("/").some(s=>s==="..")||!XPOD_RETURN_PATH_PREFIXES.some(s=>i===s||i.startsWith(`${s}/`)))throw new TypeError("returnTo must be a safe path within the application allow-list");return e}function decodeForValidation(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}const XPOD_LOGIN_ROUTE_ID="xpod-current-origin";function createXpodLoginRoute(n=typeof window>"u"?"http://localhost":window.location){const e=toLocation(n),t=e.origin;if(!t||t==="null")throw new TypeError("Xpod login requires a same-origin browser URL");return{id:XPOD_LOGIN_ROUTE_ID,label:"Xpod",identityProvider:{url:t,label:e.host||t},storageProvider:{url:t,label:e.host||t},availability:"ready"}}function normalizeXpodReturnTo(n){return normalizeXpodReturnPath(n)}function assertXpodLoginRoute(n,e){const t=normalizeWebIdLoginRoute(n),i=new URL(e).origin,s=new URL(t.identityProvider.url).origin,o=t.storageProvider?new URL(t.storageProvider.url).origin:void 0;if(t.id!==XPOD_LOGIN_ROUTE_ID||s!==i||o!==i||t.identityProvider.url!==t.storageProvider?.url)throw new TypeError("Xpod login route must use the current origin for identity and storage");return{...t,identityProvider:{...t.identityProvider,url:i},storageProvider:t.storageProvider?{...t.storageProvider,url:i}:void 0}}function toLocation(n){if(typeof n=="string"){const e=new URL(n,typeof window>"u"?void 0:window.location.href);return{origin:e.origin,host:e.host,href:e.href}}return n instanceof URL?{origin:n.origin,host:n.host,href:n.href}:{origin:n.origin,host:n.host,href:n.href}}const XPOD_LAST_OIDC_ISSUER_STORAGE_KEY="xpod.solid.lastOidcIssuer",XPOD_INRUPT_STORAGE_KEY_PREFIX="xpod.inrupt.",XpodSolidRuntimeContext=reactExports.createContext(null);function snapshotToState(n,e,t){return n.status==="initializing"?{status:"loading",issuer:t}:n.status==="anonymous"?{status:"anonymous",issuer:t}:n.status==="expired"?{status:"expired",webId:n.webId,issuer:t}:n.status==="error"?{status:"error",webId:n.webId,error:n.error,podUrl:e?.podUrl,issuer:t}:{status:"authenticated",webId:n.webId,podUrl:e?.podUrl,issuer:t}}async function discoverPodUrlFromWebId({webId:n,fetch:e}){const t=await fetchProfileStorageUrls(e,n);if(t.length!==1)throw new Error(t.length===0?"WebID profile does not declare a Solid storage URL":"WebID profile declares multiple Solid storage URLs; choose an explicit storage");return ensureTrailingSlash(new URL(t.at(0)).toString())}function createXpodSolidRuntimeValue(n={}){const e=createXpodSolidRuntimeStoragePolicy(n.storage);let t=[];const i=createSolidLocalRouteFetch({fetch:globalThis.fetch,routes:()=>t}),s=n.sessionFactory?.({fetch:i})??createInruptSession(e.oidcSession,i);let o=readStoredOidcIssuer(e.issuer);const l=createSolidSessionRuntime({session:s}),u=createPodRuntime({adapter:{discoverPod:discoverPodUrlFromWebId,openDatabase:({podUrl:h,fetch:d})=>drizzle({get info(){return s.info},fetch:d},{podUrl:h,schema:{aiProvider:aiProviderResource,credential:credentialResource},resourcePreparation:"off"}),hydrateCollections:()=>{}}});return{session:l,pod:u,storage:e,getIssuer:()=>readIssuerFromSessionInfo(s.info)??o??readStoredOidcIssuer(e.issuer),getExpectedIssuer:()=>o??expectedSameOriginIssuer(readIssuerFromSessionInfo(s.info)),setIssuer:h=>{const d=normalizeXpodOidcIssuer(h);o=d,d&&writeStoredOidcIssuer(d,e.issuer)},setLocalPodRoute:h=>{t=h?[h,...["/api/","/v1/","/.notifications/"].map(d=>({canonicalBaseUrl:new URL(d,h.canonicalBaseUrl).href,localBaseUrl:new URL(d,h.localBaseUrl).href}))]:[]},resolveLocalUrl:h=>resolveSolidLocalRouteUrl(h,t)?.href??h}}function createInruptSession(n=getOptionalPersistentStorage$1(),e=globalThis.fetch){return new Session({fetch:e,...n?{secureStorage:new InMemoryStorage,insecureStorage:toInruptStorage(n,"insecure")}:{}})}function toInruptStorage(n,e){const t=i=>inruptStorageKey(e,i);return{get:async i=>n.getItem(t(i))??void 0,set:async(i,s)=>{n.setItem(t(i),s)},delete:async i=>{n.removeItem(t(i))}}}function inruptStorageKey(n,e){return`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${n}:${e}`}let defaultRuntime;function getXpodSolidRuntimeValue(){return defaultRuntime??=createXpodSolidRuntimeValue(),defaultRuntime}function withXpodProvisionScope(n,e){const t=new URL(n);return e?.trim()&&t.searchParams.set("provisionCode",e.trim()),t.toString()}async function resolveXpodLoginContext(n,e){const t=await e("/provision/status",{headers:{Accept:"application/json"},credentials:"include"}).catch(()=>{});if(t?.status===404)return{oidcIssuer:normalizeXpodOidcIssuer(n)};const i=t?.ok?await t.json().catch(()=>{}):void 0,s=normalizeXpodOidcIssuer(i?.oidcIssuer);if(i?.managed===!1)return{oidcIssuer:s??normalizeXpodOidcIssuer(n)};const o=typeof i?.provisionCode=="string"&&i.provisionCode.trim()?i.provisionCode.trim():void 0;if(!s||i?.managed===!0&&!o)throw new Error("暂时无法确认本机登录信息,请稍后重试。");return{oidcIssuer:s,provisionCode:o}}function safeAuthError(n){if(n.name==="SolidSessionPendingError"){const e=new Error("上次登录尚未结束,请刷新页面后重新登录。");return e.name=n.name,e}return n.message==="Solid session expired"?n:new Error("Solid login failed. Please reconnect your Pod.")}function normalizeXpodLoginTransaction(n,e=typeof window>"u"?"http://localhost":window.location.origin){if(!n||typeof n!="object")throw new TypeError("Xpod login requires a validated WebID transaction");const t=normalizeWebIdLoginTransaction(n),i=assertXpodLoginRoute(t.route,e),s=normalizeXpodReturnTo(t.returnTo);return{...t,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}function useXpodSolidRuntimeContext(){const n=reactExports.useContext(XpodSolidRuntimeContext);if(!n)throw new Error("useXpodSolidRuntime must be used within XpodSolidRuntimeProvider");return n}function readIssuerFromSessionInfo(n){const e=n.issuer??n.oidcIssuer;return normalizeXpodOidcIssuer(e)}function normalizeXpodOidcIssuer(n){if(!(typeof n!="string"||!n.trim()))try{const e=new URL(n.trim());return e.protocol!=="https:"&&e.protocol!=="http:"||e.username||e.password||e.search||e.hash?void 0:e.toString()}catch{return}}function isCurrentXpodSessionSnapshot(n,e,t){if(n.status!=="authenticated")return!0;const i=normalizeXpodOidcIssuer(e),s=normalizeXpodOidcIssuer(t);return!i||!s||i!==s?!1:isHttpResourceUrl(n.webId)}function expectedSameOriginIssuer(n,e=typeof window>"u"?"http://localhost":window.location.origin){const t=normalizeXpodOidcIssuer(n);return t&&hasOrigin(t,e)?t:void 0}function hasOrigin(n,e){try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function isHttpResourceUrl(n){try{const e=new URL(n);return(e.protocol==="https:"||e.protocol==="http:")&&!e.username&&!e.password}catch{return!1}}function readStoredOidcIssuer(n=getOptionalPersistentStorage$1()){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$1()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalSessionStorage$1()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY)}catch{}}function writeStoredOidcIssuer(n,e=getOptionalPersistentStorage$1()){try{e?.setItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY,n)}catch{}}function createXpodSolidRuntimeStoragePolicy(n={}){const e=getOptionalPersistentStorage$1();return{oidcSession:n.oidcSession??e,issuer:n.issuer??e,selectedStorage:n.selectedStorage??e}}function getOptionalPersistentStorage$1(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getOptionalSessionStorage$1(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}const useXpodSolidRuntime=useXpodSolidRuntimeContext;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";function optionalPersistentStorage(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function readRememberedXpodLogin(n={}){const e=n.storage??optionalPersistentStorage();if(e)try{const t=e.getItem(XPOD_REMEMBERED_LOGIN_KEY);if(!t)return;const i=normalizeRememberedXpodLogin(JSON.parse(t),n.origin??currentOrigin());return i||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),i}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(n,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const i=normalizeRememberedXpodLogin(n,e.origin??currentOrigin());if(i)try{return t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(i)),t.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function clearRememberedXpodLogin(n=optionalPersistentStorage()){try{n?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(n,e){if(!n||!e.webId||!e.selectedStorage)return!1;const t=validatedWebId(n.webId),i=validatedWebId(n.storageBinding.webId),s=normalizedUrl(n.storageBinding.storageUrl,!0),o=validatedWebId(e.webId),l=validatedWebId(e.selectedStorage.webId),u=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!i||!s||!o||!l||!u||t!==i||o!==l||t!==o||s!==u?!1:rememberedXpodAccountMatchesActive(n,e)}function rememberedXpodAccountMatchesActive(n,e){return n?matchingOptionalEmail(n.account.email,e.accountEmail):!1}function rememberPendingXpodAccountEmail(n,e=optionalPersistentStorage(),t){const i=normalizedEmail(n);if(!(!e||!i))try{return e.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,i),t?e.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,normalizedIssuer(t)):e.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function readPendingXpodAccountEmail(n=optionalPersistentStorage(),e){if(n)try{const t=normalizedEmail(n.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const i=n.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!i||i!==normalizedIssuer(e)){n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}}return t||n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t}catch{return}}function normalizedIssuer(n){try{const e=currentOrigin();return e?new URL(n,e).origin:new URL(n).origin}catch{return n.trim()}}function normalizeRememberedXpodLogin(n,e){if(!n||typeof n!="object")return;const t=n;if(t.routeId!==XPOD_LOGIN_ROUTE_ID||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const i=t.account,s=t.storageBinding,o=normalizedEmail(i.email),l=validatedWebId(t.webId),u=validatedWebId(s.webId),h=normalizedUrl(s.storageUrl,!0);if(i.email!==void 0&&!o||!l||!u||!h||l!==u)return;const d=normalizedAvatarUrl(i.avatarUrl,[l,h,e]);return{account:{...o?{email:o}:{},...normalizedText(i.id)?{id:normalizedText(i.id)}:{},...normalizedText(i.username)?{username:normalizedText(i.username)}:{},...normalizedText(i.displayName)?{displayName:normalizedText(i.displayName)}:{},...d?{avatarUrl:d}:{}},webId:l,storageBinding:{webId:l,storageUrl:h},routeId:XPOD_LOGIN_ROUTE_ID}}function normalizedEmail(n){if(typeof n!="string")return;const e=n.trim();return e&&e.length<=320&&e.includes("@")?e:void 0}function normalizedText(n){if(typeof n!="string")return;const e=n.replace(/\s+/g," ").trim();return e?Array.from(e).slice(0,160).join(""):void 0}function validatedWebId(n){return typeof n=="string"&&!hasInvalidWebIdWhitespace(n)&&normalizedUrl(n)?n:void 0}function normalizedUrl(n,e=!1){if(!(typeof n!="string"||n.length>2048))try{const t=new URL(n);return t.username||t.password||t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(e&&(t.hash="",t.pathname.endsWith("/")||(t.pathname+="/")),t.href)}catch{return}}function normalizedAvatarUrl(n,e){const t=normalizedUrl(n);if(!t)return;const i=new URL(t).origin;return e.some(s=>{const o=normalizedUrl(s);return o&&new URL(o).origin===i})?t:void 0}function matchingOptionalEmail(n,e){const t=normalizedEmail(n)?.toLowerCase(),i=normalizedEmail(e)?.toLowerCase();return!t||!i||t===i}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}function XpodRememberedLoginBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.selectedStorage,i=useXpodProfileCardIdentity({accountIdentity:n.identity,runtime:e}),s=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,o=readRememberedXpodLogin(),l=readPendingXpodAccountEmail(),u=l??o?.account.email;return reactExports.useEffect(()=>{!s||!t||!e.currentPod||t.webId===s&&(e.currentPod.webId!==s||e.currentPod.podUrl!==t.storageUrl||o&&!rememberedXpodLoginMatchesActive(o,{accountIdentity:n.identity,accountEmail:l,webId:s,selectedStorage:t})||rememberXpodLogin({account:{...u?{email:u}:{},...n.identity??{},displayName:i.displayName,...i.username?{username:i.username}:{},...i.avatarSourceUrl??o?.account.avatarUrl?{avatarUrl:i.avatarSourceUrl??o?.account.avatarUrl}:{}},webId:s,storageBinding:t,routeId:XPOD_LOGIN_ROUTE_ID}))},[n.identity,u,l,i.displayName,i.avatarSourceUrl,i.username,o,e.currentPod,t,s]),null}function accountInteractionBase(n=typeof window>"u"?"/.account/":window.location.pathname){return/^\/\.account\/interaction\/[^/]+(?=\/|$)/u.exec(n)?.[0]??"/.account"}function scopeAccountUrl(n,e=typeof window>"u"?void 0:window.location){const t=String(n);if(!e)return t;const i=accountInteractionBase(e.pathname);if(i==="/.account")return t;const s=new URL(t,e.href);return s.origin!==e.origin||!s.pathname.startsWith("/.account/")||s.pathname.startsWith("/.account/interaction/")?t:(s.pathname=`${i}${s.pathname.slice(9)}`,t.startsWith("/")&&!t.startsWith("//")?`${s.pathname}${s.search}${s.hash}`:s.href)}const CSS_ACCOUNT_COOKIE_NAME="css-account",CSS_ACCOUNT_TOKEN_STORAGE_KEY="xpod.cssAccountToken",CSS_ACCOUNT_AUTHORITY_STORAGE_KEY="xpod.cssAccountAuthority",CSS_ACCOUNT_AUTH_SCHEME="CSS-Account-Token";function isBrowser(){return typeof window<"u"&&typeof document<"u"}function readCssAccountCookie(){if(!isBrowser())return;const n=document.cookie.split(";");for(const e of n){const[t,...i]=e.trim().split("=");if(t===CSS_ACCOUNT_COOKIE_NAME){const s=i.join("=");try{return s?decodeURIComponent(s):void 0}catch{return}}}}function writeCssAccountCookie(n){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=${encodeURIComponent(n)}; Path=/; SameSite=Lax`)}function clearCssAccountCookie(){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=; Path=/; SameSite=Lax; Max-Age=0`)}function clearLegacyStoredToken(){if(!(typeof window>"u")){try{window.localStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}try{window.sessionStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}}}function bindAccountSessionAuthority(n){if(!isBrowser())return!1;const e=normalizeAccountAuthority(n),t=window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY),i=t!==null?t!==e:new URL(e).origin!==window.location.origin;return window.localStorage.setItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY,e),i&&clearAccountSessionToken(),i}function normalizeAccountAuthority(n){const e=new URL(n,window.location.origin);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.pathname!=="/.account/"||e.search||e.hash)throw new Error("Invalid Account authority");return e.href}function storeAccountSessionToken(n){!n||readCssAccountCookie()===n||writeCssAccountCookie(n)}function clearAccountSessionToken(){clearLegacyStoredToken(),clearCssAccountCookie()}function getAccountSessionToken(){return readCssAccountCookie()}function accountTokenHeaders(n,e={Accept:"application/json"}){const t={...e};return n&&!hasHeader(t,"Authorization")&&(t.Authorization=`${CSS_ACCOUNT_AUTH_SCHEME} ${n}`),t}function storedAccountTokenHeaders(n={Accept:"application/json"},e){if(e)try{if(window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY)!==normalizeAccountAuthority(e))return{...n}}catch{return{...n}}return accountTokenHeaders(getAccountSessionToken(),n)}function hasHeader(n,e){const t=e.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===t)}let cachedRoute,cachedRouteOrigin;function resolveSameOriginAccountControlUrl(n){if(typeof window>"u"||typeof n!="string"||!n.trim())return;const e=n.trim();try{const t=new URL(e,window.location.origin);return t.origin!==window.location.origin||!["http:","https:"].includes(t.protocol)||t.username||t.password?void 0:scopeAccountUrl(t)}catch{return}}async function resolveHostedAccountControlUrl(n,e=fetch,t){if(typeof window>"u"||typeof n!="string"||!n.trim())return;if(t)try{const d=new URL(t,window.location.origin),p=new URL(n.trim(),d);if(p.origin===d.origin&&d.pathname.startsWith("/.account/")&&p.pathname.startsWith("/.account/")&&["http:","https:"].includes(p.protocol)&&!p.username&&!p.password)return scopeAccountUrl(p)}catch{}const i=resolveSameOriginAccountControlUrl(n);if(i)return i;let s;try{s=new URL(n)}catch{return}if(!["http:","https:"].includes(s.protocol)||s.username||s.password||!s.pathname.startsWith("/.account/"))return;if(cachedRoute&&cachedRouteOrigin===window.location.origin){const d=resolveSolidLocalRouteUrl(s,[cachedRoute]);if(d)return scopeAccountUrl(d)}const o={localBaseUrl:`${window.location.origin}/`,statusUrl:new URL("/provision/status",window.location.origin).href},l=await Promise.resolve(e.call(globalThis,o.statusUrl,{credentials:"include",headers:{accept:"application/json"}})).catch(()=>{}),u=l?await discoverSolidLocalRoute({...o,fetch:async()=>l.clone()}):void 0;u&&(cachedRoute=u,cachedRouteOrigin=window.location.origin);const h=u?resolveSolidLocalRouteUrl(s,[u]):void 0;return h?scopeAccountUrl(h):void 0}const LOCAL_ACCOUNT_INDEX$1="/.account/";function isProvisionStatusResponse(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}async function resolveXpodAccountIndex(n=fetch){if(typeof window>"u")return LOCAL_ACCOUNT_INDEX$1;if(!isLoopbackHostname$1(window.location.hostname)){const i=window.__XPOD__?.idpIndex;if(i!==void 0){try{const s=new URL(i,window.location.origin);if(typeof i=="string"&&i.trim()&&["http:","https:"].includes(s.protocol)&&s.pathname===LOCAL_ACCOUNT_INDEX$1&&!s.username&&!s.password&&!s.search&&!s.hash)return unregisterLocalProvisionResolver(),s.href}catch{}throw new Error("Server bootstrap did not expose a valid Account index")}}const e=await n(new URL("/provision/status",window.location.origin),{credentials:"include",headers:{accept:"application/json"}});if(e.status===404)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(!e.ok)throw new Error(`Local provisioning status request failed (${e.status})`);let t;try{t=await e.json()}catch{throw new Error("Local provisioning status response was not valid JSON")}if(!isProvisionStatusResponse(t)||typeof t.managed!="boolean")throw new Error("Local provisioning status response was not valid");if(t.managed===!1)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(typeof t.oidcIssuer=="string")try{const i=new URL(t.oidcIssuer);if(["http:","https:"].includes(i.protocol)&&!i.username&&!i.password)return installLocalProvisionResolver(n),typeof t.provisionCode=="string"&&setStoredProvisionCode(t.provisionCode),new URL(LOCAL_ACCOUNT_INDEX$1,i).href}catch{}throw new Error("Local provisioning status did not expose a valid OIDC issuer")}function installLocalProvisionResolver(n){const e=new URL("/provision/status",window.location.origin);registerLocalProvisionResolver(async()=>{const t=await n(e,{credentials:"include",headers:{accept:"application/json"}}),i=t.ok?await t.json().catch(()=>{}):void 0;if(i?.managed!==!0||i?.registered!==!0||typeof i?.provisionCode!="string")throw new Error(CLOUD_PROVISIONING_UNAVAILABLE);return i.provisionCode})}function isLoopbackHostname$1(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}const LOCAL_ACCOUNT_INDEX="/.account/",ACCOUNT_ERROR_MESSAGE="Xpod 登录服务暂时不可用,请稍后重试。",ACCOUNT_CONTROLS_RETRY_DELAYS_MS=[250,750,1500],ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS=300,OIDC_PENDING_PROBE_TIMEOUT_MS=3e3;function isAccountSpaPath(){if(typeof window>"u")return!1;const n=window.location.pathname;return n==="/.account"||n.startsWith("/.account/")}function accountIdentityFromControls(n){const e=n?.account;if(!e)return;const t={...typeof e.id=="string"?{id:e.id}:{},...typeof e.username=="string"?{username:e.username}:{},...typeof e.displayName=="string"?{displayName:e.displayName}:{}};return Object.keys(t).length>0?t:void 0}function accountStateForControls(n){return n?.account?.logout?{status:"authenticated"}:{status:"anonymous",mode:"login"}}function isTransientAccountControlsStatus(n){return n===502||n===503||n===504}function transientAccountState(n){return n?{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}:{status:"initializing"}}function wait(n){return new Promise(e=>setTimeout(e,n))}function AuthProvider({children:n}){const[e,t]=reactExports.useState(),[i,s]=reactExports.useState(null),[o,l]=reactExports.useState(!0),[u,h]=reactExports.useState(null),[d,p]=reactExports.useState(!1),[g,m]=reactExports.useState({status:"initializing"}),v=reactExports.useRef(0),S=reactExports.useRef(!0),E=reactExports.useRef(0),x=reactExports.useRef(void 0),A=reactExports.useRef(null),C=reactExports.useRef(void 0),T=reactExports.useRef(0),F=reactExports.useRef(0),P=reactExports.useRef(!1),q=reactExports.useCallback(()=>{const te=A.current?.account;return te?.logout?JSON.stringify([x.current,te.id,te.logout,te.clientCredentials]):void 0},[]),O=reactExports.useCallback(()=>{T.current+=1,P.current=!0},[]),G=reactExports.useCallback((te,Te)=>{const je=q(),He=C.current;A.current=te,C.current=Te,(je!==q()||He!==Te)&&O(),P.current=!q()},[q,O]),fe=reactExports.useCallback(()=>{const te=q(),Te=T.current,je=getAccountSessionToken();let He=!!te&&je===C.current&&!P.current&&F.current===0;return()=>{if(!He||!S.current||P.current||F.current>0||Te!==T.current||te!==q()||je!==getAccountSessionToken())throw He=!1,new Error("Account 登录状态已改变,请重新打开客户端凭据操作。")}},[q]),M=g.status==="authenticated",ee=o||g.status==="submitting",Se=reactExports.useRef(!1),re=reactExports.useCallback(te=>{(bindAccountSessionAuthority(te)||x.current&&x.current!==te)&&(E.current+=1,v.current+=1,Se.current=!1,G(null),s(null),p(!1),m({status:"initializing"})),x.current=te,t(te)},[G]),Ae=reactExports.useCallback(async()=>{l(!0),h(null),m(te=>te.status==="authenticated"?te:{status:"initializing"});try{const te=await resolveXpodAccountIndex();return S.current?(re(te),te):void 0}catch{if(!S.current)return;G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1);return}},[re,G]);reactExports.useEffect(()=>{let te=!0;return resolveXpodAccountIndex().then(Te=>{te&&S.current&&re(Te)}).catch(()=>{!te||!S.current||(G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1))}),()=>{te=!1}},[re,G]),reactExports.useEffect(()=>(S.current=!0,()=>{S.current=!1,O(),E.current+=1}),[O]);const ke=reactExports.useCallback(te=>S.current&&te===E.current,[]),he=reactExports.useCallback(async()=>{const te=new AbortController,Te=setTimeout(()=>te.abort(),OIDC_PENDING_PROBE_TIMEOUT_MS);try{const je=x.current;if(!je)return!1;const He=await fetch(scopeAccountUrl(new URL("oidc/consent/",je)),{headers:storedAccountTokenHeaders(void 0,je),credentials:"include",signal:te.signal});return He.ok?!!(await He.json()).client:!1}catch{return!1}finally{clearTimeout(Te)}},[]),Oe=reactExports.useCallback(async({exposeTransientError:te,generation:Te,confirmUnauthenticated:je})=>{const He=x.current;if(!He)return"stale";const We=getAccountSessionToken(),me=()=>We===getAccountSessionToken()?!0:(O(),!1);try{const ge=await fetch(scopeAccountUrl(He),{headers:storedAccountTokenHeaders(void 0,He),credentials:"include"});if(!ke(Te))return"stale";if(!me())return"transient-error";if(ge.ok){const Be=await ge.json();if(!ke(Te))return"stale";if(!me())return"transient-error";if(!Be?.controls||typeof Be.controls!="object"||Array.isArray(Be.controls))throw new Error("Invalid CSS Account controls response");const ie=Be.controls,B=++v.current;p(!1),G(ie,We),s(ie),h(null);const N=accountStateForControls(ie);return Se.current=N.status==="anonymous",m(N),ie.account?.logout&&isAccountSpaPath()&&he().then(k=>{ke(Te)&&B===v.current&&p(k)}),"ok"}else{if(ge.status===401||ge.status===403)return je?(v.current+=1,clearAccountSessionToken(),Se.current=!0,p(!1),G({}),s({}),m({status:"anonymous",mode:"login"}),h(null),"ok"):"unauthenticated";if(v.current+=1,p(!1),isTransientAccountControlsStatus(ge.status))return h(null),m(ie=>ie.status==="authenticated"?ie:transientAccountState(te)),"transient-error";O();const Be=`Failed to load account controls (Status: ${ge.status})`;return h(Be),m({status:"error",mode:"login",message:Be}),"terminal-error"}}catch{return ke(Te)?(v.current+=1,p(!1),h(null),m(ge=>ge.status==="authenticated"?ge:transientAccountState(te)),"transient-error"):"stale"}},[G,he,ke,O]),ce=reactExports.useCallback(async()=>{const te=++E.current;for(let Te=0;Te<=ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length;Te+=1){const je=Te===ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length,He=await Oe({exposeTransientError:je,generation:te});if(He==="unauthenticated")return!ke(te)||(await wait(ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS),!ke(te))?"stale":Oe({exposeTransientError:!0,generation:te,confirmUnauthenticated:!0});if(He!=="transient-error")return He;if(!ke(te)||!je&&(m(We=>We.status==="authenticated"?We:{status:"initializing"}),await wait(ACCOUNT_CONTROLS_RETRY_DELAYS_MS[Te]),!ke(te)))return"stale"}return"transient-error"},[Oe,ke]);reactExports.useEffect(()=>{if(!e)return;let te=!0;return(async()=>(await ce(),te&&S.current&&l(!1)))(),()=>{te=!1}},[ce,e]);const Ue=reactExports.useCallback(async()=>{const te=await Ae();if(te&&te===e){const Te=await ce();if(S.current&&l(!1),Te==="ok")return accountStateForControls(A.current)}return{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}},[ce,e,Ae]),$=reactExports.useCallback(async()=>{await Ue()},[Ue]),W=reactExports.useCallback(async()=>{F.current+=1;try{O(),E.current+=1,v.current+=1,A.current?.account?.logout||(Se.current=!1,(x.current??await Ae())&&await ce());const te=x.current,Te=A.current?.account?.logout,je=await resolveHostedAccountControlUrl(Te,fetch,te);let He=!je&&(!!Te||!Se.current);if(je)try{const We=await fetch(scopeAccountUrl(je),{method:"POST",headers:storedAccountTokenHeaders(void 0,te),credentials:"include"});He=!We.ok&&We.status!==401&&We.status!==403}catch{He=!0}if(He){m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE});return}E.current+=1,v.current+=1,Se.current=!0,l(!1),clearAccountSessionToken(),p(!1),G({}),s({}),h(null),m({status:"anonymous",mode:"login"})}finally{F.current-=1}},[G,ce,Ae,O]),de=reactExports.useMemo(()=>accountIdentityFromControls(i),[i]);return jsxRuntimeExports.jsx(AuthContext.Provider,{value:{controls:i,isInitializing:o,initError:u,idpIndex:e??LOCAL_ACCOUNT_INDEX,isLoggedIn:M,isAnonymous:()=>Se.current,bindAccountCapability:fe,authenticating:ee,hasOidcPending:d,refetchControls:Ue,retry:$,logout:W,accountState:g,identity:de},children:n})}const MAX_LABEL_CODE_POINTS=80,MAX_IDENTITY_URL_LENGTH=2048;function XpodDesktopIdentityBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,i=e.state.status==="authenticated"?e.currentPod?.podUrl??e.podUrl??e.state.podUrl:void 0,s=reactExports.useMemo(()=>projectDesktopIdentity({isLoggedIn:n.isLoggedIn,displayName:n.identity?.displayName,username:n.identity?.username,webId:t,podUrl:i}),[n.identity?.displayName,n.identity?.username,n.isLoggedIn,i,t]);return reactExports.useEffect(()=>{globalThis.xpodDesktop?.setIdentity(s)},[s]),reactExports.useEffect(()=>()=>{globalThis.xpodDesktop?.setIdentity(null)},[]),null}function projectDesktopIdentity({isLoggedIn:n,displayName:e,username:t,webId:i,podUrl:s}){if(!n)return null;const o=sanitizeLabel(e)??sanitizeLabel(t)??"Xpod Account",l=sanitizeCurrentXpodUrl(i),u=sanitizeCurrentXpodUrl(s);return{label:o,...l?{webId:l}:{},...u?{podUrl:u}:{}}}function sanitizeLabel(n){if(!n)return;const t=Array.from(n,i=>{const s=i.codePointAt(0);return isUnsafeLabelCodePoint(s)?" ":i}).join("").replace(/\s+/g," ").trim();if(t)return Array.from(t).slice(0,MAX_LABEL_CODE_POINTS).join("").trim()}function isUnsafeLabelCodePoint(n){return n<32||n>=127&&n<=159||n>=8234&&n<=8238||n>=8294&&n<=8297}function sanitizeCurrentXpodUrl(n){if(!(!n||n.length>MAX_IDENTITY_URL_LENGTH))try{const e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password||!isCurrentXpodOrigin(e)?void 0:e.toString()}catch{return}}function isCurrentXpodOrigin(n){const e=globalThis.window?.location;return e?n.origin===e.origin?!0:n.protocol===e.protocol&&n.port===e.port&&isLoopbackHostname(n.hostname)&&isLoopbackHostname(e.hostname):!1}function isLoopbackHostname(n){const e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}function XpodServiceAvailability({children:n}){const[e,t]=reactExports.useState(!1),i=reactExports.useRef(()=>{}),s=reactExports.useRef(null);return reactExports.useEffect(()=>{if(!e)return;const o=document.activeElement;return s.current?.focus(),()=>{o instanceof HTMLElement&&o.isConnected&&o.focus()}},[e]),reactExports.useEffect(()=>{let o=!1,l,u,h=0;async function d(){if(o||l)return;clearTimeout(u);const g=new AbortController;l=g;const m=setTimeout(()=>g.abort(),5e3);let v=!0;try{const S=await fetch("/service/status",{cache:"no-store",signal:g.signal});if(v=S.status<500,S.ok){const E=await S.json().catch(()=>null);Array.isArray(E)&&(v=!E.some(x=>x&&["css","api"].includes(x.name)&&typeof x.status=="string"&&x.status!=="running")),g.signal.aborted&&(v=!1)}else await S.body?.cancel()}catch{v=!1}finally{clearTimeout(m),l=void 0}o||(h=v?0:h+1,t(!v),u=setTimeout(()=>{document.visibilityState!=="hidden"&&d()},v?1e4:Math.min(2e3*2**Math.min(h-1,4),3e4)))}const p=()=>{document.visibilityState!=="hidden"&&d()};return i.current=()=>{d()},window.addEventListener("online",p),window.addEventListener("focus",p),document.addEventListener("visibilitychange",p),d(),()=>{o=!0,clearTimeout(u),l?.abort(),i.current=()=>{},window.removeEventListener("online",p),window.removeEventListener("focus",p),document.removeEventListener("visibilitychange",p)}},[]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{style:{display:"contents"},inert:e||void 0,children:n}),e&&jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center bg-background/70 p-6 backdrop-blur-sm",children:jsxRuntimeExports.jsxs("section",{role:"alertdialog","aria-modal":"true","aria-labelledby":"xpod-connection-title","aria-describedby":"xpod-connection-description",className:"w-full max-w-sm rounded-2xl border bg-background p-6 shadow-lg",children:[jsxRuntimeExports.jsx("h2",{id:"xpod-connection-title",className:"text-lg font-semibold",children:"Xpod 连接中断"}),jsxRuntimeExports.jsx("p",{id:"xpod-connection-description",className:"mt-3 text-sm text-muted-foreground",children:"暂时无法连接 Xpod,正在自动重连。登录状态和当前页面已保留,恢复后即可继续。"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"刚才未完成的操作不会自动重试,请在连接恢复后确认结果。"}),jsxRuntimeExports.jsx("button",{ref:s,type:"button",onKeyDown:o=>{o.key==="Tab"&&o.preventDefault()},onClick:()=>i.current(),className:"mt-5 w-full rounded-lg bg-primary px-4 py-2 text-primary-foreground",children:"立即重试"})]})})]})}function XpodDesktopNavigationBridge(){const n=useNavigate();return reactExports.useEffect(()=>globalThis.xpodDesktop?.onNavigate?.(e=>{const t=new URL(e,window.location.origin);t.origin===window.location.origin&&n(`${t.pathname}${t.search}${t.hash}`)}),[n]),null}const XPOD_DEFAULT_RETURN_PATH="/ai-connections",LEGACY_DEFAULT_RETURN_PATH="/dashboard/overview",canonicalRoutes={status:"/status/overview",network:"/network",aiConnections:"/ai-connections",aiConfig:"/ai-config/model-assignments",settings:"/settings/pod"},legacyProductRedirects={"/dashboard":canonicalRoutes.status,[LEGACY_DEFAULT_RETURN_PATH]:canonicalRoutes.status,"/dashboard/network":canonicalRoutes.network,"/dashboard/models":canonicalRoutes.aiConnections,"/dashboard/pod":canonicalRoutes.settings,"/dashboard/services":canonicalRoutes.status,"/dashboard/settings":canonicalRoutes.settings,"/settings/models":canonicalRoutes.aiConnections,"/settings/ai-connections":canonicalRoutes.aiConnections,"/settings/ai-config":canonicalRoutes.aiConfig,"/settings/pod":canonicalRoutes.settings,"/settings/network":canonicalRoutes.network,"/settings/services":canonicalRoutes.status,"/settings/system":canonicalRoutes.settings};function canonicalProductPathname(n){return legacyProductRedirects[n]??n}const client_id="https://id.undefineds.co/app/xpod-desktop-client.json",desktopClient={client_id},XPOD_LOGIN_TRANSACTION_VERSION=1,XPOD_LOGIN_TRANSACTION_PREFIX="xpod.auth.transaction.v1",XPOD_LOGIN_TRANSACTION_TTL_MS=600*1e3,XPOD_SELECTED_STORAGE_BINDING_VERSION=1,XPOD_SELECTED_STORAGE_BINDING_KEY="xpod.auth.selected-storage.v1";class XpodLoginTransactionError extends Error{code;constructor(e,t){super(t),this.name="XpodLoginTransactionError",this.code=e}}function readXpodSelectedStorage(n={}){return n.storage?readXpodSelectedStorageFrom(n.storage,n):readXpodSelectedStorageFrom(getOptionalPersistentStorage(),n)??readXpodSelectedStorageFrom(getOptionalSessionStorage(),n)}function readXpodSelectedStorageFrom(n,e){if(!n)return;const t=n.getItem(XPOD_SELECTED_STORAGE_BINDING_KEY);if(!t)return;const i=()=>n.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);let s;try{s=JSON.parse(t)}catch{i();return}if(!isStoredSelectedStorageBinding(s)){i();return}const o=e.now??(()=>Date.now());if(s.expiresAt<=o()){i();return}let l;try{l=normalizeSelectedStorageBinding(s.binding,s.storageRoot??new URL(e.origin??getWindowOrigin()).origin,s.storageRoot===void 0)}catch{i();return}if(e.webId!==void 0&&l.webId!==e.webId){i();return}return l}function clearXpodSelectedStorage(n={}){n.storage?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);try{getOptionalPersistentStorage()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY),getOptionalSessionStorage()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY)}catch{}}function createOpaqueTransactionId(){const n=globalThis.crypto;if(typeof n?.randomUUID=="function")return n.randomUUID();if(typeof n?.getRandomValues=="function"){const e=new Uint8Array(24);return n.getRandomValues(e),`xpod-${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}throw new XpodLoginTransactionError("storage_unavailable","Secure transaction id generation is unavailable")}function createXpodLoginTransactionStore(n={}){const e=n.storage??getSessionStorage(),t=new URL(n.origin??getWindowOrigin()).origin,i=n.now??(()=>Date.now()),s=n.ttlMs??XPOD_LOGIN_TRANSACTION_TTL_MS,o=n.prefix??XPOD_LOGIN_TRANSACTION_PREFIX,l=`${o}.active`,u=m=>`${o}.record.${m}`,h=m=>`${o}.consumed.${m}`,d=m=>{e.getItem(l)===m&&e.removeItem(l),e.removeItem(u(m))},p=(m,v=!0)=>{if(!isSafeTransactionId(m))throw new XpodLoginTransactionError("malformed","Transaction id is malformed");if(e.getItem(h(m))==="1")throw new XpodLoginTransactionError("consumed","Transaction has already been consumed");if(v&&e.getItem(l)!==m)throw new XpodLoginTransactionError("unknown","Transaction is not the active Xpod login transaction");const S=e.getItem(u(m));if(!S)throw v&&e.getItem(l)===m&&e.removeItem(l),new XpodLoginTransactionError("unknown","Xpod login transaction was not found");let E;try{E=JSON.parse(S)}catch{throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}if(!isStoredTransaction(E)||E.transaction.id!==m)throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed");if(E.expiresAt<=i())throw d(m),new XpodLoginTransactionError("expired","Xpod login transaction has expired");try{const x=normalizePublicTransaction({...E.transaction,authorizationSurface:"redirect",discovery:"strict"},t);return E.transaction={id:x.id,route:x.route,...x.returnTo===void 0?{}:{returnTo:x.returnTo},...x.prompt===void 0?{}:{prompt:x.prompt},...x.selectedStorage===void 0?{}:{selectedStorage:x.selectedStorage}},E}catch(x){throw d(m),x instanceof XpodLoginTransactionError?x:new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}};return{begin:m=>{const v=e.getItem(l);if(v){try{p(v)}catch(T){if(!(T instanceof XpodLoginTransactionError&&(T.code==="expired"||T.code==="malformed"||T.code==="unknown")))throw T}if(e.getItem(l)===v)throw new XpodLoginTransactionError("already_active","An Xpod login transaction is already pending in this tab")}const S=isSafeTransactionId(m.id)?m.id:createOpaqueTransactionId(),E=normalizePublicTransaction({...m,id:S},t),x=i(),A=x+s,C={version:XPOD_LOGIN_TRANSACTION_VERSION,createdAt:x,expiresAt:A,transaction:{id:E.id,route:E.route,...E.returnTo===void 0?{}:{returnTo:E.returnTo},...E.prompt===void 0?{}:{prompt:E.prompt},...E.selectedStorage===void 0?{}:{selectedStorage:E.selectedStorage}}};return e.setItem(u(E.id),JSON.stringify(C)),e.setItem(l,E.id),E},readSinglePending(){const m=e.getItem(l);if(m)return materialize(p(m).transaction)},updateSelectedStorage(m,v){const S=p(m),E=materialize(S.transaction),x=normalizeBinding(v,t,E.route.storageProvider?.url),A={...S,transaction:{...S.transaction,selectedStorage:x}};e.setItem(u(m),JSON.stringify(A))},consume(m){const v=p(m),S=materialize(v.transaction);return e.removeItem(l),e.removeItem(u(m)),e.setItem(h(m),"1"),S},cancel(m){p(m),e.removeItem(l),e.removeItem(u(m)),e.setItem(h(m),"1")}}}function normalizePublicTransaction(n,e){let t;try{t=normalizeWebIdLoginTransaction(n)}catch(o){throw new XpodLoginTransactionError("malformed",o instanceof Error?o.message:"Transaction is malformed")}let i;try{i=assertXpodLoginRoute(t.route,e)}catch(o){throw new XpodLoginTransactionError("cross_origin",o instanceof Error?o.message:"Transaction route is not local")}let s;try{s=normalizeXpodReturnTo(t.returnTo)}catch(o){throw new XpodLoginTransactionError("mismatch",o instanceof Error?o.message:"Transaction return path is unsafe")}if(t.selectedStorage!==void 0)try{const o=normalizeBinding(t.selectedStorage,e,i.storageProvider?.url);return{id:t.id,route:i,selectedStorage:o,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}catch(o){throw o instanceof XpodLoginTransactionError?o:new XpodLoginTransactionError("mismatch","Selected storage binding is invalid")}return{id:t.id,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}function normalizeBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(i.origin!==e||s.origin!==e||t&&i.origin!==new URL(t).origin)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");if(i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("malformed","Selected storage binding contains unsafe URL data");return{storageUrl:i.href,webId:n.webId,...n.label===void 0?{}:{label:n.label}}}function materialize(n){return{id:n.id,route:n.route,authorizationSurface:"redirect",discovery:"strict",...n.returnTo===void 0?{}:{returnTo:n.returnTo},...n.prompt===void 0?{}:{prompt:n.prompt},...n.selectedStorage===void 0?{}:{selectedStorage:n.selectedStorage}}}function normalizeSelectedStorageBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(!urlBelongsToRoot(i,e)||t&&s.origin!==new URL(e).origin||i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");return{storageUrl:i.href,webId:n.webId}}function normalizeStorageRoot(n){const e=new URL(n);return e.hash="",e.search="",e.pathname.endsWith("/")||(e.pathname+="/"),e.href}function urlBelongsToRoot(n,e){const t=new URL(normalizeStorageRoot(e));if(n.origin!==t.origin)return!1;const i=t.pathname;return n.pathname===i.slice(0,-1)||n.pathname.startsWith(i)}function isSafeTransactionId(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{16,128}$/.test(n)}function isStoredTransaction(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_LOGIN_TRANSACTION_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.transaction&&typeof e.transaction=="object")}function isStoredSelectedStorageBinding(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_SELECTED_STORAGE_BINDING_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.binding&&typeof e.binding=="object")}function getSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}throw new XpodLoginTransactionError("storage_unavailable","Session storage is unavailable")}function getOptionalSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}function getOptionalPersistentStorage(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getWindowOrigin(){return typeof window<"u"&&window.location.origin!=="null"?window.location.origin:"http://localhost"}async function currentHostLocalPodRoute(n,e){if(typeof window>"u")return;const t=desktopLocalPodRoute(n);if(t)return t;if(storageUrlUsesCurrentOrigin(n))return;const i=await fetchCurrentProvisionRouteStatus(e);return currentProvisionLocalPodRoute(n,i)}function currentProvisionLocalPodRoute(n,e){if(!(typeof window>"u")&&!(e.managed!==!0||typeof e.storageRoot!="string")&&managedPublicRouteCoversStorage(n,e.storageRoot))return podScopedLocalRoute(n)}function desktopLocalPodRoute(n){if(!(typeof window>"u"||!window.xpodDesktop))return podScopedLocalRoute(n)}async function fetchCurrentProvisionRouteStatus(n){let e;try{e=await n(new URL("/provision/status",window.location.origin).href,{credentials:"include",headers:{accept:"application/json"}})}catch{return{}}if(!e.ok||!e.headers.get("content-type")?.includes("application/json"))return await e.arrayBuffer().catch(()=>{}),{};const t=await e.json().catch(()=>{});return{managed:t?.managed===!0,storageRoot:typeof t?.publicUrl=="string"?t.publicUrl:void 0}}function podScopedLocalRoute(n){try{const e=new URL(n),t=new URL(e.pathname,window.location.origin);return!["http:","https:"].includes(e.protocol)||e.username||e.password?void 0:(e.search="",e.hash="",t.search="",t.hash="",{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:t.href.endsWith("/")?t.href:`${t.href}/`})}catch{return}}function managedPublicRouteCoversStorage(n,e){try{const t=new URL(e),i=new URL(t.pathname,window.location.origin);return resolveSolidLocalRouteUrl(n,[{canonicalBaseUrl:t.href,localBaseUrl:i.href}])!==void 0}catch{return!1}}function storageUrlUsesCurrentOrigin(n){try{return new URL(n).origin===window.location.origin}catch{return!1}}function XpodSolidRuntimeProvider({children:n,value:e}){const t=e??getXpodSolidRuntimeValue(),i=reactExports.useMemo(()=>t.storage??{},[t]),s=reactExports.useMemo(()=>currentProviderSession(t),[t]),[o,l]=reactExports.useState(s.snapshot),[u,h]=reactExports.useState(s.issuer),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),[v,S]=reactExports.useState(),[E,x]=reactExports.useState(0),[A,C]=reactExports.useState(),T=reactExports.useRef(o),F=reactExports.useRef(s.rejected),P=reactExports.useRef(void 0),q=reactExports.useCallback(async(Ae,ke)=>F.current?Promise.reject(REJECTED_SESSION_FETCH_ERROR):ke===void 0?t.session.fetch(Ae):t.session.fetch(Ae,ke),[t.session]),O=reactExports.useMemo(()=>o.status==="authenticated"?t.session.createAuthenticatedFetch(o.webId):void 0,[t.session,o]),G=reactExports.useCallback(async(Ae,ke)=>{if(!O||F.current)throw REJECTED_SESSION_FETCH_ERROR;return ke===void 0?O(Ae):O(Ae,ke)},[O]),fe=reactExports.useCallback(()=>{if(P.current)return P.current;const Ae=(async()=>{try{await t.session.logout();const ke=t.session.getSnapshot();(ke.status!=="authenticated"||isCurrentXpodSessionSnapshot(ke,t.getIssuer(),t.getExpectedIssuer?.()??window.location.origin))&&(F.current=!1)}catch{}finally{const ke={status:"anonymous"};t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),t.setIssuer(void 0),T.current=ke,l(ke),h(void 0),p(void 0),m(void 0),S(void 0),C(void 0)}})().finally(()=>{P.current===Ae&&(P.current=void 0)});return P.current=Ae,Ae},[t,i.issuer,i.selectedStorage]),M=reactExports.useMemo(()=>({...t.session,fetch:q,getSnapshot:()=>T.current}),[q,t.session]);reactExports.useEffect(()=>{const Ae=he=>{const Oe=t.getIssuer();if(!isCurrentXpodSessionSnapshot(he,Oe,t.getExpectedIssuer?.()??window.location.origin)){F.current=!0,fe();return}he.status==="authenticated"&&(F.current=!1);const ce=T.current;T.current=he,l(he),h(Oe),he.status!=="authenticated"?(t.setLocalPodRoute?.(void 0),p(void 0),he.status!=="expired"&&m(void 0),S(void 0),C(void 0),t.pod.clear()):ce!==he&&(p(void 0),m(void 0),S(void 0),C(void 0),t.pod.clear(ce.status==="authenticated"?{webId:ce.webId}:void 0))},ke=t.session.subscribe(Ae);return Ae(t.session.getSnapshot()),ke},[fe,t,i]),reactExports.useEffect(()=>{F.current&&fe()},[fe]),reactExports.useEffect(()=>{if(o.status!=="authenticated")return;let Ae=!1;const ke=readXpodSelectedStorage({storage:i.selectedStorage,origin:typeof window>"u"?void 0:window.location.origin,webId:o.webId}),he={webId:o.webId,...ke?{podUrl:ke.storageUrl}:{},fetch:G};return(async()=>{try{const Oe=await t.pod.open(he),ce=await currentHostLocalPodRoute(Oe.podUrl,fetch);if(Ae)return;if(t.setLocalPodRoute?.(ce),!Ae){if(ke&&(Oe.webId!==ke.webId||!sameUrl$2(Oe.podUrl,ke.storageUrl))){clearXpodSelectedStorage({storage:i.selectedStorage}),p(void 0),m(void 0),S({webId:o.webId,error:new Error("Selected Pod binding mismatch")});return}p(Oe),m(ke??{webId:Oe.webId,storageUrl:Oe.podUrl}),S(void 0)}}catch(Oe){Ae||S({webId:o.webId,error:Oe instanceof Error?Oe:new Error(String(Oe))})}})(),()=>{Ae=!0}},[G,E,t,i.selectedStorage,o]);const ee=reactExports.useCallback(()=>{S(void 0),x(Ae=>Ae+1)},[]),Se=o.status==="authenticated"?o.webId:void 0;reactExports.useEffect(()=>{if(!Se)return;let Ae=!1;return discoverAiClientConfigurationCapability(G).then(ke=>{!Ae&&t.session.getSnapshot().status==="authenticated"&&t.session.getSnapshot().webId===Se&&C(ke)}),()=>{Ae=!0}},[G,Se,t]);const re=reactExports.useMemo(()=>{const Ae=u??t.getIssuer(),ke=o.status==="authenticated"&&v?.webId===o.webId?v:void 0,he=snapshotToState(o,d,Ae);return{session:M,pod:t.pod,fetch:G,state:he.status==="error"?{...he,error:safeAuthError(he.error)}:he,webId:he.webId,podUrl:he.podUrl,issuer:he.issuer,currentPod:d,selectedStorage:g,...ke?{podError:ke}:{},retryPodOpen:ee,aiClientConfiguration:A,resolveLocalUrl:Oe=>t.resolveLocalUrl(Oe),login:async Oe=>{const ce=normalizeXpodLoginTransaction(Oe),Ue=await resolveXpodLoginContext(ce.route.identityProvider.url,fetch),$=Ue.oidcIssuer;if(!$)throw new TypeError("Xpod login route has no valid issuer");const W=new URL("/auth/callback",window.location.origin),de=globalThis.xpodDesktop?desktopClient.client_id:void 0;try{await t.session.login({...de?{clientId:de}:{},oidcIssuer:$,redirectUrl:W.toString(),handleRedirect:te=>{t.setIssuer($),h($);const Te=new URL(te);ce.prompt?Te.searchParams.set("prompt",ce.prompt):de&&Te.searchParams.get("prompt")==="consent"&&Te.searchParams.delete("prompt"),window.location.assign(Ue.provisionCode?withXpodProvisionScope(Te.href,Ue.provisionCode):Te.href)}}),t.setIssuer($),h($)}catch(te){throw console.error("[XpodSolidRuntimeProvider] WebID login failed",te,te instanceof Error?te.cause:void 0),te}},logout:async()=>{await t.session.logout(),t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),p(void 0),m(void 0),C(void 0)}}},[A,G,d,M,u,v,ee,t,i,g,o]);return jsxRuntimeExports.jsx(SolidRuntimeProvider,{value:{session:M,pod:t.pod,currentPod:d},children:jsxRuntimeExports.jsx(XpodSolidRuntimeContext.Provider,{value:re,children:n})})}const ANONYMOUS_SNAPSHOT={status:"anonymous"},REJECTED_SESSION_FETCH_ERROR=new Error("Xpod session is unavailable");function currentProviderSession(n){const e=n.session.getSnapshot(),t=n.getIssuer();return isCurrentXpodSessionSnapshot(e,t,n.getExpectedIssuer?.()??window.location.origin)?{snapshot:e,issuer:t,rejected:!1}:{snapshot:ANONYMOUS_SNAPSHOT,issuer:void 0,rejected:!0}}function sameUrl$2(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}async function discoverAiClientConfigurationCapability(n){try{const e=new URL("/api/ai/client-configuration/capability",window.location.href).toString(),t=await n(e,{method:"GET",credentials:"include",headers:{accept:"application/json"}});if(!t.ok||!t.headers.get("content-type")?.includes("application/json"))return await t.arrayBuffer().catch(()=>{}),manualAiClientConfigurationCapability();const i=await t.json();if(isRecord(i)&&i.available===!0&&i.authority==="local-filesystem")return{available:!0,authority:"local-filesystem",manualInstructions:typeof i.manualInstructions=="string"?i.manualInstructions:manualAiClientConfigurationCapability().manualInstructions}}catch{}return manualAiClientConfigurationCapability()}function manualAiClientConfigurationCapability(){return{available:!1,manualInstructions:"manual client setup is available"}}function isRecord(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}const XPOD_THEME_STORAGE_KEY="xpod.theme",XPOD_THEME_MEDIA_QUERY="(prefers-color-scheme: dark)";function readXpodThemePreference(n=optionalLocalStorage()){try{const e=n?.getItem(XPOD_THEME_STORAGE_KEY);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function resolveXpodTheme(n,e=systemThemeMedia()){return n!=="system"?n:e?.matches?"dark":"light"}function applyXpodTheme(n,e=typeof document>"u"?void 0:document.documentElement){e&&(e.classList.toggle("light",n==="light"),e.classList.toggle("dark",n==="dark"),e.dataset.theme=n,e.style.colorScheme=n)}function initializeXpodTheme(){const n=readXpodThemePreference(),e=resolveXpodTheme(n);return applyXpodTheme(e),{preference:n,resolvedTheme:e}}function systemThemeMedia(){return typeof window>"u"||typeof window.matchMedia!="function"?void 0:window.matchMedia(XPOD_THEME_MEDIA_QUERY)}function optionalLocalStorage(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}const XpodThemeContext=reactExports.createContext(null);function XpodThemeProvider({children:n}){const[e,t]=reactExports.useState(()=>readXpodThemePreference()),[i,s]=reactExports.useState(()=>resolveXpodTheme("system")),o=e==="system"?i:e;reactExports.useEffect(()=>{const u=systemThemeMedia();if(!u)return;const h=d=>{s(d.matches?"dark":"light")};return typeof u.addEventListener=="function"?(u.addEventListener("change",h),()=>u.removeEventListener("change",h)):(u.addListener?.(h),()=>u.removeListener?.(h))},[]),reactExports.useEffect(()=>{applyXpodTheme(o)},[o]);const l=reactExports.useMemo(()=>({preference:e,resolvedTheme:o,setPreference(u){t(u);try{u==="system"?optionalLocalStorage()?.removeItem(XPOD_THEME_STORAGE_KEY):optionalLocalStorage()?.setItem(XPOD_THEME_STORAGE_KEY,u)}catch{}}}),[e,o]);return jsxRuntimeExports.jsx(XpodThemeContext.Provider,{value:l,children:n})}function XpodThemeRoot({children:n}){return reactExports.useContext(XpodThemeContext)?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(XpodThemeProvider,{children:n})}function DesktopLoginReturnAction(){const[n,e]=reactExports.useState(!1),[t,i]=reactExports.useState(!1),s=reactExports.useRef(!1);if(!window.xpodDesktop?.cancelLogin)return null;const o=async()=>{const l=window.xpodDesktop;if(!(s.current||!l?.cancelLogin)){s.current=!0,e(!0),i(!1);try{await l.cancelLogin()}catch{i(!0)}finally{s.current=!1,e(!1)}}};return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[t&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"返回应用未完成,请重试。"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",className:"w-full",disabled:n,"aria-busy":n,onClick:()=>{o()},children:n?"正在返回…":"返回应用"})]})}const xpodAccountCredentialsCopy={productName:"Xpod 账号",loginTitle:"登录",registerTitle:"创建账号",usernameLabel:"Pod 名称",usernamePlaceholder:"选择 Pod 名称",emailLabel:"邮箱",emailPlaceholder:"you@example.com",passwordLabel:"密码",passwordPlaceholder:"输入密码",confirmationLabel:"确认密码",confirmationPlaceholder:"再次输入密码",loginAction:"登录",registerAction:"创建账号",switchToRegister:"切换用户",switchToLogin:"返回登录",usernameChecking:"正在检查 Pod 名称…",usernameAvailable:"Pod 名称可用",usernameUnavailable:"Pod 名称不可用",suggestionsLabel:"可用建议",mismatchError:"两次输入的密码不一致"},xpodAccountPageCopy={forgotPassword:"忘记密码?"},xpodRegistrationCopy={usernameRequired:"请填写 Pod 名称",usernameLength:"Pod 名称需为 3-63 个字符",usernameCharset:"Pod 名称只能包含小写字母、数字和连字符",usernameHyphen:"Pod 名称不能以连字符开头或结尾",emailAlreadyRegisteredPasswordMismatch:"该邮箱已注册,但密码不正确,请登录或重置密码。",podNameTaken:"Pod 名称已被占用,请换一个。"};function safeXpodLoginMessage(n){return n===401||n===403?"邮箱或密码不正确。":n===429?"尝试次数过多,请稍后再试。":"登录失败,请重试。"}class RegistrationError extends Error{code;constructor(e,t){super(e),this.name="RegistrationError",this.code=t}}async function readErrorMessage(n){const e=await n.json().catch(()=>{});return e?.message||e?.error}async function loginAccountPassword(n){const t=await(n.fetchImpl??fetch)(scopeAccountUrl(n.loginUrl),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({email:n.email,password:n.password,...n.remember===void 0?{}:{remember:n.remember}})});if(!t.ok){const o=await readErrorMessage(t);throw n.duplicateEmailRecovery?new RegistrationError(xpodRegistrationCopy.emailAlreadyRegisteredPasswordMismatch,"EMAIL_ALREADY_REGISTERED"):new Error(o||"Auto-login failed")}const i=await t.json().catch(()=>({})),s=typeof i.authorization=="string"?i.authorization:"";if(!s)throw new Error("Account token not returned after login");return{accountToken:s}}class PasswordLoginStatusError extends Error{status;constructor(e){super(`Password login failed with status ${e}`),this.name="PasswordLoginStatusError",this.status=e}}function XpodAccountCredentials({surface:n,onAuthenticated:e,initialEmail:t}){const{controls:i,idpIndex:s,refetchControls:o}=useAuth(),[l,u]=reactExports.useState({email:t!==void 0?t:readPendingXpodAccountEmail(void 0,s)??"",password:""}),[h,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),[m,v]=reactExports.useState(!0),S=reactExports.useRef(!1),E=async C=>{if(!S.current){S.current=!0,g(!0),d(void 0);try{const T=await resolveHostedAccountControlUrl(i?.password?.login,fetch,s)??scopeAccountUrl("/.account/login/password/"),F=await loginAccountPassword({email:C.email?.trim()??"",password:C.password,loginUrl:T,remember:m,fetchImpl:async(q,O)=>{const G=await fetch(typeof q=="string"||q instanceof URL?scopeAccountUrl(q):q,O);if(!G.ok)throw new PasswordLoginStatusError(G.status);return G}});storeAccountSessionToken(F.accountToken),rememberPendingXpodAccountEmail(C.email?.trim()??"",void 0,s);const P=await o();if(P?.status!=="authenticated"){P?.status==="anonymous"&&clearAccountSessionToken(),d("登录失败,请重试。");return}await e?.()}catch(T){d(T instanceof PasswordLoginStatusError?safeXpodLoginMessage(T.status):safeXpodLoginMessage(500))}finally{S.current=!1,g(!1)}}},x=C=>{u(C),h&&d(void 0)},A={surface:"page",surfaceTitle:"登录 Xpod",copy:xpodAccountCredentialsCopy,footer:n==="embedded"?void 0:jsxRuntimeExports.jsx(AccountEntryLinks,{}),mode:"login",values:l,onChange:x,onSubmit:E,pending:p,rememberAccount:m,onRememberAccountChange:v,errors:h?{form:h}:void 0};return n==="embedded"?jsxRuntimeExports.jsx(AccountCredentialsView,{...A,presentation:"compact",frame:"bare",showHeader:!1}):jsxRuntimeExports.jsx(XpodBlockingAccountCredentialsSurface,{...A})}function AccountEntryLinks(){let n="";try{const e=normalizeXpodReturnTo(`${window.location.pathname}${window.location.search}`);e&&(n=`?${new URLSearchParams({returnTo:e})}`)}catch{}return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-center gap-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/register/${n}`),children:"创建账号"})}),jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"text-border",children:"·"}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/forgot/${n}`),children:xpodAccountPageCopy.forgotPassword})})]})}function AccountWorkspaceBoundary({children:n}){return useXpodSolidRuntimeContext().state.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(AccountAuthBoundary,{children:n})}function AccountAuthBoundary({children:n,accountState:e,retry:t,surface:i="page"}){const s=useAuth(),o=e??s.accountState,l=t??s.retry;return o.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):o.status==="submitting"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在登录…"]})}):o.status==="initializing"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在加载账号"]})}):o.status==="error"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:o.message}),jsxRuntimeExports.jsx(Button,{className:"w-full",type:"button",onClick:()=>{l()},children:"重试"}),jsxRuntimeExports.jsx(DesktopLoginReturnAction,{})]})}):i==="embedded"?jsxRuntimeExports.jsxs(LoginSurface,{surface:i,children:[jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"embedded"}),jsxRuntimeExports.jsx("div",{className:"mt-6 space-y-3 border-t pt-5",children:jsxRuntimeExports.jsx(AccountEntryLinks,{})})]}):jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"page"})}function LoginSurface({children:n,surface:e}){return e==="embedded"?jsxRuntimeExports.jsx(WebAccountLayout,{title:"登录 Xpod",presentation:"compact",children:n}):jsxRuntimeExports.jsx(XpodAccountPageSurface,{title:"登录 Xpod",presentation:"compact",children:n})}function AppLayout({navigation:n,children:e,className:t}){return jsxRuntimeExports.jsxs("section",{className:cn("grid h-screen min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_64px] bg-background sm:grid-cols-[60px_minmax(0,1fr)] sm:grid-rows-[minmax(0,1fr)]",t),"data-app-layout":"workspace",children:[jsxRuntimeExports.jsx("aside",{className:"row-start-2 min-h-0 overflow-x-auto overflow-y-hidden border-t border-border/50 bg-layout-sidebar sm:col-start-1 sm:row-start-1 sm:overflow-hidden sm:border-r sm:border-t-0","data-app-layout-navigation":!0,children:n}),jsxRuntimeExports.jsx("div",{className:"col-start-1 row-start-1 min-h-0 min-w-0 overflow-hidden bg-layout-content sm:col-start-2","data-app-layout-content":!0,children:e})]})}const globalNavigationItems=[{id:"ai-connections",label:"AI Connections",href:canonicalRoutes.aiConnections,activePaths:["/ai-connections"],placement:"primary",icon:Sparkles},{id:"ai-config",label:"AI Config",href:canonicalRoutes.aiConfig,activePaths:["/ai-config"],placement:"primary",icon:BrainCircuit},{id:"network",label:"Network",href:canonicalRoutes.network,activePaths:["/network"],placement:"bottom",icon:Globe},{id:"status",label:"Status",href:canonicalRoutes.status,activePaths:["/status"],placement:"bottom",icon:Gauge},{id:"settings",label:"Settings",href:canonicalRoutes.settings,activePaths:["/settings"],placement:"bottom",icon:Settings}];function isGlobalNavigationItemActive(n,e){const t=e.replace(/\/+$/,"")||"/";return n.activePaths.some(i=>t===i||t.startsWith(`${i}/`))}function accountCardPosition(n,e,t){const l=e>=640,u=Math.min(360,e-16);if(l){const d=Math.max(8,Math.min(n.top,t-240-8));return{left:Math.max(8,Math.min(n.right+12,e-u-8)),top:d,width:u,maxHeight:Math.max(240,t-d-8)}}const h=Math.max(72,t-n.top+12);return{left:8,bottom:h,width:u,maxHeight:Math.max(240,t-h-8)}}function XpodUserCard(){const n=useAuth(),e=reactExports.useContext(XpodSolidRuntimeContext),t=n.isLoggedIn&&n.accountState.status==="authenticated",i=e?.state.status==="authenticated"&&!!(e.webId??e.state.webId),s=t||i,[o,l]=reactExports.useState(accountCardRequestedByUrl(s)),[u,h]=reactExports.useState(),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),v=reactExports.useRef(null),S=reactExports.useRef(null),E=reactExports.useRef(void 0),x=reactExports.useId(),A=n.identity,C=readPendingXpodAccountEmail(),T=readRememberedXpodLogin()?.account,F=t?accountCardIdentityFallback(A,C,T):void 0,P=useXpodProfileCardIdentity({accountIdentity:F,runtime:i?e:void 0}),q=P.displayName,O=initialsFor(P.displayName),G=e?.webId??(e?.state.status==="authenticated"?e.state.webId:void 0),fe=accountHandle(P.username,i?void 0:F?.id,G),M=e?.selectedStorage?.storageUrl??e?.podUrl,ee=e?.selectedStorage,Se=e?.currentPod,re=reactExports.useMemo(()=>M?podNameFromUrl(M):void 0,[M]),Ae=e?.state.status==="authenticated"&&!!(G&&M&&ee&&Se)&&ee?.webId===G&&sameUrl$1(ee?.storageUrl??"",M??"")&&Se?.webId===G&&sameUrl$1(Se?.podUrl??"",M??""),ke=s,he=o&&ke,Oe=reactExports.useCallback(W=>{l(W),W||(m(void 0),clearAccountCardRequest())},[]);reactExports.useLayoutEffect(()=>{if(!he)return;const W=()=>{const de=S.current;de&&m(accountCardPosition(de.getBoundingClientRect(),window.innerWidth,window.innerHeight))};return W(),window.addEventListener("resize",W),window.addEventListener("scroll",W,!0),window.visualViewport?.addEventListener("resize",W),()=>{window.removeEventListener("resize",W),window.removeEventListener("scroll",W,!0),window.visualViewport?.removeEventListener("resize",W)}},[he]),reactExports.useEffect(()=>{if(!ke){clearAccountCardRequest();return}if(!he)return;const W=te=>{const Te=te.target;Te instanceof Node&&(v.current?.contains(Te)||S.current?.contains(Te)||Oe(!1))},de=te=>{te.key==="Escape"&&(Oe(!1),S.current?.focus())};return document.addEventListener("pointerdown",W),document.addEventListener("keydown",de),()=>{document.removeEventListener("pointerdown",W),document.removeEventListener("keydown",de)}},[ke,he,Oe]),reactExports.useEffect(()=>{!he||!g||v.current?.focus({preventScroll:!0})},[he,g]),reactExports.useEffect(()=>()=>{E.current!==void 0&&window.clearTimeout(E.current)},[]);const ce=async()=>{h("logout"),Oe(!1);try{await logoutXpodProduct(n,e),(n.isAnonymous?.()??!0)&&Oe(!1)}catch{}finally{h(void 0)}},Ue=async()=>{h("switch"),Oe(!1);try{await logoutXpodProduct(n,e,{onComplete:()=>{clearRememberedXpodLogin();const W=new URL(XPOD_DEFAULT_RETURN_PATH,window.location.origin);W.searchParams.set("xpod-login","switch"),window.location.assign(W)}}),Oe(!1)}catch{}finally{h(void 0)}},$=async()=>{const W=P.webId??fe;try{await navigator.clipboard.writeText(W),p("Copied")}catch{p("Copy failed")}E.current!==void 0&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>p(void 0),1800)};return ke?jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("button",{ref:S,type:"button","aria-label":s?`Open account menu for ${q}`:"Open account menu","aria-expanded":he,"aria-controls":he?x:void 0,"data-testid":"xpod-user-card-trigger","data-pod-ready":Ae?"true":"false",className:"flex h-9 w-9 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus:ring-0 focus-visible:bg-accent",onClick:()=>Oe(!he),children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:q}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-md bg-muted text-xs text-muted-foreground",children:O})]}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s?q:"Not signed in"})]}),he&&typeof document<"u"?reactDomExports.createPortal(jsxRuntimeExports.jsx("section",{ref:v,id:x,role:"region",tabIndex:-1,"aria-label":s?q:"Xpod account","data-avatar-card":"true","data-selected-pod-url":M,style:g,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${g?"":"invisible"}`,children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-5 px-6 pb-5 pt-6",children:[jsxRuntimeExports.jsxs(Avatar,{"data-testid":"xpod-profile-avatar",className:"h-20 w-20 shrink-0 rounded-2xl border border-border/50 bg-primary/10 shadow-sm",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:q}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-2xl bg-primary/10 text-2xl font-bold text-primary",children:O})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 py-0.5",children:[jsxRuntimeExports.jsx("h2",{className:"truncate text-xl font-bold text-foreground",children:q}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"shrink-0 opacity-70",children:"Xpod ID"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono font-medium",children:fe}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground","aria-label":"Copy Xpod ID",onClick:()=>{$()},children:jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3","aria-hidden":"true"})}),d?jsxRuntimeExports.jsx("span",{role:"status",className:"shrink-0 text-xs text-primary",children:d}):null]}),jsxRuntimeExports.jsxs("div",{className:"mt-2.5 inline-flex items-center gap-1.5 rounded-full bg-emerald-500/10 px-2 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-300",children:[jsxRuntimeExports.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Ae?"bg-emerald-500":"bg-muted-foreground/50"}`,"aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{children:Ae?"Pod connected":i?"WebID connected":"Account connected"})]})]})]}),P.note||P.region?jsxRuntimeExports.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[P.note?jsxRuntimeExports.jsx("p",{className:"line-clamp-2 text-foreground/85",children:P.note}):null,P.region?jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:P.region}):null]}):null,jsxRuntimeExports.jsx("div",{className:"border-t border-border/40 p-2",children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto min-h-14 w-full justify-start gap-3 px-3 py-2.5 font-normal",children:jsxRuntimeExports.jsxs("a",{href:"/settings/pod","aria-label":"Pod settings",children:[jsxRuntimeExports.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:jsxRuntimeExports.jsx(Database,{className:"h-4 w-4","aria-hidden":"true"})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[jsxRuntimeExports.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:podDisplayName(re)}),jsxRuntimeExports.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:["Personal Pod · ",podHost(M)]})]}),Ae?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-emerald-500","aria-label":"Pod ready"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})})}),jsxRuntimeExports.jsx(Separator,{}),jsxRuntimeExports.jsxs("div",{className:"p-2",children:[jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal",onClick:()=>{Ue()},disabled:u!==void 0,children:[u==="switch"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Switch account"]}),jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal text-destructive hover:text-destructive",onClick:()=>{ce()},disabled:u!==void 0,children:[u==="logout"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Sign out"]})]})]})}),document.body):null]}):null}function accountCardIdentityFallback(n,e,t){if(n?.displayName||n?.username||n?.id||n?.webId)return n;const i=e||(t&&"email"in t&&typeof t.email=="string"?t.email:void 0);if(!i&&!t)return n;const s=t?.username||usernameFromEmail(i);return{...t??{},...s?{username:s}:{},...t?.displayName?{displayName:t.displayName}:{displayName:s||i||"Xpod account"}}}function usernameFromEmail(n){if(n)return n.split("@")[0]?.trim()||void 0}function accountHandle(n,e,t){const i=n||e||usernameFromWebId(t);return i?i.startsWith("@")?i:`@${i}`:"Xpod member"}function initialsFor(n){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>=2?`${e[0][0]}${e.at(-1)[0]}`.toUpperCase():n.slice(0,2).toUpperCase()||"XP"}function podNameFromUrl(n){try{return new URL(n).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function podDisplayName(n){return n?`${n} Pod`:"My Pod"}function podHost(n){if(!n)return"No Pod connected";try{return new URL(n).host}catch{return"Pod storage"}}function usernameFromWebId(n){if(n)try{return new URL(n).pathname.split("/").filter(Boolean).at(0)}catch{return}}function sameUrl$1(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function accountCardRequestedByUrl(n){return n?typeof window<"u"&&new URLSearchParams(window.location.search).get("account")==="open":!1}function clearAccountCardRequest(){if(typeof window>"u")return;const n=new URL(window.location.href);n.searchParams.get("account")==="open"&&(n.searchParams.delete("account"),window.history.replaceState(window.history.state,"",`${n.pathname}${n.search}${n.hash}`))}function handleListNavigationKeyDown(n){if(!["ArrowDown","ArrowUp","Home","End"].includes(n.key))return;const e=n.currentTarget.closest("[data-list-navigation]")??n.currentTarget.closest("nav");if(!e)return;const t=[...e.querySelectorAll('a[href]:not([aria-disabled="true"])')],i=t.indexOf(n.currentTarget);if(i<0||t.length===0)return;n.preventDefault();const s=n.key==="Home"?0:n.key==="End"?t.length-1:n.key==="ArrowDown"?(i+1)%t.length:(i-1+t.length)%t.length;t[s]?.focus()}const navItemBaseClass="rounded-lg transition-colors",navItemInteractiveClass="text-foreground hover:bg-accent/60",navItemFocusClass="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function getRailNavItemClass(n){return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":`text-foreground ${navItemInteractiveClass}`,"h-9 w-9 rounded-lg p-0",n?"":"mx-2","flex items-center justify-center"].join(" ")}function getListNavItemClass(n,e){const t=e?.compact===!0;return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":"",t?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",n?"font-medium":`${navItemInteractiveClass} text-foreground`].join(" ")}function ProductNavLinks({items:n,label:e}){const i=useLocation().pathname;return jsxRuntimeExports.jsx("nav",{"aria-label":e,className:"flex flex-row items-center gap-3 sm:flex-col sm:gap-4",children:n.map(s=>{const o=s.icon,l=s.href??s.path??"/",u=s.activePaths?isGlobalNavigationItemActive(s,i):i===s.path||i.startsWith(`${s.path}/`);return jsxRuntimeExports.jsxs(Link,{to:l,"aria-label":s.label,"aria-current":u?"page":void 0,"data-list-item":"true",title:s.label,onKeyDown:handleListNavigationKeyDown,className:clsx(getRailNavItemClass(u),"text-sm"),children:[jsxRuntimeExports.jsx(o,{className:"h-6 w-6","aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s.label})]},s.id)})})}function XpodProductLayout({product:n}){const e=globalNavigationItems.filter(i=>i.placement==="primary"),t=globalNavigationItems.filter(i=>i.placement==="bottom");return jsxRuntimeExports.jsx(AppLayout,{className:`xpod-${n}-shell`,navigation:jsxRuntimeExports.jsxs("div",{className:"flex h-full w-full flex-row items-center px-2 sm:min-h-full sm:flex-col sm:px-0 sm:py-4","data-list-navigation":!0,children:[jsxRuntimeExports.jsx("div",{className:"mr-1 shrink-0 sm:mr-0 sm:ml-2 sm:mb-2",children:jsxRuntimeExports.jsx(XpodUserCard,{})}),jsxRuntimeExports.jsx("div",{className:"flex min-w-0 flex-1 flex-row items-center justify-center sm:mt-5 sm:flex-none sm:flex-col sm:justify-start",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:e,label:"Primary Xpod workspaces"})}),jsxRuntimeExports.jsx("div",{className:"flex shrink-0 flex-row items-center gap-3 sm:mt-auto sm:flex-col sm:gap-0",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:t,label:"Xpod settings"})})]}),children:jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 flex-col bg-background",children:jsxRuntimeExports.jsx(Outlet,{})})})}function XpodDashboardLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"dashboard"})}function RouteLoadingBoundary({children:n}){return jsxRuntimeExports.jsx(RouteChunkErrorBoundary,{children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"正在打开…"}),children:n})})}class RouteChunkErrorBoundary extends reactExports.Component{state={};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("Route module failed to load",e,t.componentStack)}render(){if(!this.state.error)return this.props.children;const e=/Failed to fetch dynamically imported module|Importing a module script failed|Loading chunk .* failed/i.test(this.state.error.message);return jsxRuntimeExports.jsxs("div",{className:"mx-auto flex min-h-64 max-w-md flex-col items-start justify-center gap-3 p-6",children:[jsxRuntimeExports.jsx("div",{className:"text-base font-medium",children:e?"页面已更新":"页面暂时无法打开"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:e?"当前窗口仍在使用旧版页面资源,请重新载入。":"页面加载遇到了问题,请重试。这不表示登录已失效。"}),!1,jsxRuntimeExports.jsx("button",{type:"button",className:"rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground",onClick:()=>window.location.reload(),children:"重新载入"})]})}}const LogsPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-B0mQa59b.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.LogsPage}))),RdfPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-B0mQa59b.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.RdfPage}))),StatusPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-B0mQa59b.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.StatusPage}))),NetworkPage=reactExports.lazy(()=>__vitePreload(()=>import("./NetworkPage-BKymvsQc.js"),__vite__mapDeps([8,9,10,2,11,3,12,13,6]))),StatusWorkspace=reactExports.lazy(()=>__vitePreload(()=>import("./StatusWorkspace-B0NzrP--.js"),__vite__mapDeps([14,2,10,9,11]))),ServiceStatusPanel=reactExports.lazy(()=>__vitePreload(()=>import("./StatusSubjectPanel-Bvl6K4mx.js"),__vite__mapDeps([15,1,3])).then(n=>({default:n.ServiceStatusPanel}))),IndexSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexSubjectPanel-CFd0ay-r.js"),__vite__mapDeps([16,1,17])));function lazyRoute$1(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}const statusContentRoutes=[{path:"overview",element:lazyRoute$1(jsxRuntimeExports.jsx(StatusPage,{}))},{path:"services/gateway",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"gateway",title:"Gateway"}))},{path:"services/solid-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"css",title:"Solid Server"}))},{path:"services/api-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"api",title:"API Server"}))},{path:"logs",element:lazyRoute$1(jsxRuntimeExports.jsx(LogsPage,{}))},{path:"index",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"overview"}))},{path:"index/rdf",element:lazyRoute$1(jsxRuntimeExports.jsx(RdfPage,{}))},{path:"index/fts",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"fts"}))},{path:"index/vector",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"vector"}))},{path:"index/retrieval-points",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"retrieval-points"}))},{path:"index/cache",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"cache"}))},{path:"index/slow-queries",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"slow-queries"}))},{path:"index/benchmark",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"benchmark"}))}];function statusWorkspaceRoute(n){return{element:lazyRoute$1(jsxRuntimeExports.jsx(StatusWorkspace,{})),children:n}}const dashboardRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},statusWorkspaceRoute(statusContentRoutes),{path:"runtime",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"rdf",element:jsxRuntimeExports.jsx(Navigate,{to:"index/rdf",replace:!0})},{path:"network/*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"status",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"../overview",replace:!0})}]}]}],statusSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[statusWorkspaceRoute([{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},...statusContentRoutes,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})}])]}]}],networkSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))}]}];function XpodSettingsLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"settings"})}function XpodLocalLoginPreflight({onReady:n}){const e=reactExports.useContext(AuthContext),t=reactExports.useRef(!1),i=e?.isInitializing===!0;return reactExports.useEffect(()=>{!i&&!t.current&&(t.current=!0,n())},[i,n]),jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在准备登录…"})}const RETURN_TO_KEY="xpod:returnTo";function consumeReturnTo(){try{const n=sessionStorage.getItem(RETURN_TO_KEY);return n&&sessionStorage.removeItem(RETURN_TO_KEY),n}catch{return null}}const CANCELLED_LOGIN_KEY="xpod.auth.login-cancelled";function setXpodLoginCancelled(n){try{n?window.localStorage.setItem(CANCELLED_LOGIN_KEY,"1"):window.localStorage.removeItem(CANCELLED_LOGIN_KEY)}catch{}}function consumeXpodLoginIntent(n){const e=new URL(window.location.href);return e.searchParams.get("xpod-login")!==n?!1:(setXpodLoginCancelled(!0),consumeReturnTo(),e.searchParams.delete("xpod-login"),window.history.replaceState(window.history.state,"",`${e.pathname}${e.search}${e.hash}`),!0)}function readXpodAccountSwitch(){return new URL(window.location.href).searchParams.get("xpod-login")==="switch"}function consumeXpodAccountSwitch(){return consumeXpodLoginIntent("switch")}function readXpodLoginCancelled(){if(consumeXpodLoginIntent("cancelled"))return!0;try{return window.localStorage.getItem(CANCELLED_LOGIN_KEY)==="1"}catch{return!1}}function createXpodLoginController(n){const e=n.location??(typeof window>"u"?"http://localhost/":window.location),i=[createXpodLoginRoute(e)],s=toOrigin(e),o=n.transactionStore??createXpodLoginTransactionStore({origin:s}),l=p=>{if(p!==void 0)return normalizeXpodReturnTo(p);const g=new URL(toHref(e)),m=`${g.pathname}${g.search}`;try{return normalizeXpodReturnTo(m)}catch{return}};let u=!1;const h=p=>{try{return o.begin(p)}catch(g){if(u||!(g instanceof XpodLoginTransactionError)||g.code!=="already_active")throw g;try{const m=o.readSinglePending();m&&o.cancel(m.id)}catch{}return o.begin(p)}},d=async(p,g,m)=>{const v=l(p),S={id:createOpaqueTransactionId(),route:i[0],authorizationSurface:"redirect",discovery:"strict",...m?{prompt:m}:{},...v===void 0?{}:{returnTo:v},...g===void 0?{}:{selectedStorage:g}},E=h(S);u=!0;try{await n.runtime.login(E)}catch(x){try{o.cancel(E.id)}catch{}throw x}finally{u=!1}return E};return{routes:i,startLogin:d,retryLogin:d,cancelLogin(){const p=o.readSinglePending();p&&o.cancel(p.id)},readPending:()=>o.readSinglePending(),callbackUrl(){return`${s}/auth/callback`}}}function toOrigin(n){return new URL(toHref(n)).origin}function toHref(n){return typeof n=="string"?n:n.href}function XpodLoginBrand({compact:n=!1,showSubtitle:e=!n,subtitle:t="使用 WebID 登录"}){const i=n&&e;return jsxRuntimeExports.jsxs("div",{"data-testid":"xpod-login-brand","data-presentation":n?"compact":"standard",className:i?"flex flex-col items-center justify-center gap-1 text-center":n?"flex items-center justify-center gap-2 text-center":"flex flex-col items-center gap-3 text-center",children:[jsxRuntimeExports.jsx("img",{src:xpodIconUrl,alt:"",className:n?i?"h-16 w-16":"h-7 w-7":"h-11 w-11"}),jsxRuntimeExports.jsxs("div",{className:i?"space-y-1 text-center":n?"text-left":"space-y-1",children:[jsxRuntimeExports.jsx("h1",{className:n?"text-base font-semibold leading-none text-foreground":"text-lg font-semibold text-foreground",children:"Xpod"}),e?jsxRuntimeExports.jsx("p",{className:"text-xs text-primary/80",children:t}):null]})]})}const rememberedCopy={restoringLabel:"正在恢复 Xpod 会话…",continueLabel:n=>`使用 ${n} 登录`,reauthenticateLabel:n=>`重新登录 ${n}`,switchAccountLabel:"切换账号",expiredTitle:"会话已过期",connectingTitle:"正在登录…",connectingDetail:"请在授权页面完成登录。",cancelLabel:"取消"},podFailureMessage="无法打开选中的 Pod,请重试。",actionFailureMessage="操作未完成,请重试。";function WebIdAuthBoundary(n){return jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(WebIdAuthBoundaryContent,{...n})})}function WebIdAuthBoundaryContent({children:n,autoStart:e=!1}){const t=useXpodSolidRuntime(),i=reactExports.useContext(AuthContext),s=reactExports.useSyncExternalStore(subscribeXpodProductLogout,isXpodAutomaticLoginBlocked,()=>!1),o=reactExports.useMemo(()=>createXpodLoginController({runtime:t}),[t]),[l]=reactExports.useState(readXpodAccountSwitch),[u,h]=reactExports.useState(()=>l||readXpodLoginCancelled());reactExports.useLayoutEffect(()=>{l&&consumeXpodAccountSwitch()},[l]),reactExports.useEffect(()=>{if(u)try{o.cancelLogin()}catch{}},[u,o]);const d=runtimeState(t.state),p=storageSelectionState(t,d),g=d.status==="authenticated"&&p?.status==="ready",[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1),[x,A]=reactExports.useState(l?{prompt:"login"}:void 0),C=reactExports.useRef(0),[T,F]=reactExports.useState(!1),P=reactExports.useRef(!1),q=reactExports.useRef(!1),O=reactExports.useCallback($=>{console.error("[WebIdAuthBoundary] authentication action failed",$),v(actionFailureMessage)},[]),G=reactExports.useCallback($=>{const W=++C.current;v(void 0),E(!0),$().catch(de=>{W===C.current&&O(de)}).finally(()=>{W===C.current&&E(!1)})},[O]),fe=reactExports.useCallback(()=>{setXpodLoginCancelled(!1),h(!1),v(void 0),A({})},[]),M=reactExports.useCallback(()=>{if(!x)return;const $=x.prompt;setXpodLoginCancelled(!1),h(!1),A(void 0),G(async()=>{l&&await t.session.initialize({restorePreviousSession:!1}),await o.startLogin(void 0,void 0,$)})},[o,x,G,t.session,l]),ee=()=>{if(T){re();return}d.status==="authenticated"?t.retryPodOpen?.():fe()},Se=()=>{if(!T){try{o.cancelLogin()}catch{}setXpodLoginCancelled(!0),h(!0),A(void 0),C.current+=1,E(!1),v(void 0)}},re=()=>G(async()=>{F(!0);const $=()=>{setXpodLoginCancelled(!1),h(!1),clearRememberedXpodLogin(),v(void 0),A({prompt:"login"}),F(!1)};i?await logoutXpodProduct(i,t,{onComplete:$}):(await t.logout(),$())});if(reactExports.useEffect(()=>{t.state.status!=="loading"||P.current||(P.current=!0,t.session.initialize({restorePreviousSession:!u}).catch(O))},[u,O,t.session,t.state.status]),reactExports.useEffect(()=>{u||x||s||S||T||!e||q.current||d.status!=="anonymous"||(q.current=!0,fe())},[u,s,e,S,x,fe,d.status,T]),g&&!S&&!m)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});if(x)return jsxRuntimeExports.jsx(XpodLocalLoginPreflight,{onReady:M});const Ae="remembered"in d?d.remembered:void 0,ke=d.status==="restoring",he=S||e&&!u&&!s&&d.status==="anonymous"&&!m,Oe=jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0});let ce,Ue;return!u&&t.state.status==="error"&&t.state.error.name==="SolidSessionPendingError"?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:"上次登录尚未结束,请刷新页面后重新登录。",primaryLabel:"刷新页面",onPrimary:()=>window.location.reload(),secondaryLabel:"返回登录",onSecondary:Se}):m?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:m,primaryLabel:"重试",onPrimary:ee,secondaryLabel:T?void 0:"返回登录",onSecondary:T?void 0:Se}):ke?(Ue=Ae?void 0:Oe,ce=jsxRuntimeExports.jsx(LoginRestoringView,{accountName:Ae?.displayName,avatarUrl:Ae?.avatarUrl,label:rememberedCopy.restoringLabel})):he?ce=T?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在切换账号…"}):jsxRuntimeExports.jsx(LoginConnectingView,{title:rememberedCopy.connectingTitle,detail:rememberedCopy.connectingDetail,cancelLabel:rememberedCopy.cancelLabel,onCancel:Se}):d.status==="authenticated"?ce=p?.status==="conflict"||p?.status==="error"?jsxRuntimeExports.jsx(LoginFailureView,{title:p.status==="conflict"?"存储绑定冲突":"暂时无法打开 Pod",description:p.message,primaryLabel:"重试",onPrimary:ee,secondaryLabel:"切换账号",onSecondary:re}):jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在打开选中的 Pod。"}):Ae&&!u?ce=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[d.status==="error"&&jsxRuntimeExports.jsx("p",{role:"alert",className:"mb-3 text-center text-xs text-muted-foreground",children:d.message}),jsxRuntimeExports.jsx(LoginAccountView,{name:Ae.displayName,avatarUrl:Ae.avatarUrl,bindingLabel:"Xpod",expired:d.status==="expired"||d.status==="error",expiredTitle:d.status==="error"?"会话恢复未完成":rememberedCopy.expiredTitle,enterLabel:d.status==="expired"||d.status==="error"?rememberedCopy.reauthenticateLabel(Ae.displayName):rememberedCopy.continueLabel(Ae.displayName),switchLabel:rememberedCopy.switchAccountLabel,onEnter:fe,onReauthenticate:ee,onSwitchAccount:re})]}):!u&&(d.status==="error"||d.status==="expired")?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:d.status==="expired"?rememberedCopy.expiredTitle:"无法登录 Xpod",description:d.status==="error"?d.message:"请重新登录后继续。",primaryLabel:"重试",onPrimary:ee,secondaryLabel:"返回登录",onSecondary:Se}):ce=jsxRuntimeExports.jsx(WebIdLoginEntryView,{copy:{title:"",startLabel:"登录",pendingLabel:rememberedCopy.connectingTitle},logo:Oe,onStart:fe}),jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"登录 Xpod",lead:Ue,children:ce})}function storageSelectionState(n,e){if(e.status!=="authenticated")return;if(n.podError?.webId===e.webId)return{status:"error",message:podFailureMessage};if(n.currentPod===void 0)return{status:"waiting_for_binding"};const t=n.selectedStorage??{webId:n.currentPod.webId,storageUrl:n.currentPod.podUrl},i=n.state.status==="authenticated"?n.state.podUrl:void 0;return n.currentPod.webId===e.webId&&t.webId===n.currentPod.webId&&sameUrl(t.storageUrl,n.currentPod.podUrl)&&(i===void 0||sameUrl(n.currentPod.podUrl,i))?{status:"ready",selected:t}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function sameUrl(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function rememberedWebIdLogin(n){const e=readRememberedXpodLogin();if(e&&!(n&&n!==e.webId))return{displayName:e.account.displayName??e.account.username??e.account.email??"Xpod",...e.account.avatarUrl?{avatarUrl:e.account.avatarUrl}:{},webId:e.webId,routeId:e.routeId}}function withRemembered(n,e){const t=rememberedWebIdLogin(e);return t?{...n,remembered:t}:n}function runtimeState(n){switch(n.status){case"loading":return withRemembered({status:"restoring"});case"anonymous":return withRemembered({status:"anonymous"});case"expired":return withRemembered({status:"expired"},n.webId);case"authenticated":return{status:"authenticated",webId:n.webId};case"error":{const e=rememberedWebIdLogin(n.webId);return{status:"error",message:n.error.message,retryRouteId:"xpod-current-origin",...e?{remembered:e}:{}}}}}const ModelsPage=reactExports.lazy(()=>__vitePreload(()=>import("./ModelsPage-BQwCwLHU.js").then(n=>n.M),__vite__mapDeps([18,19,20,21,11,4,5,22,12]))),AiConfigPage=reactExports.lazy(()=>__vitePreload(()=>import("./AiConfigPage-DGSXUkLs.js"),__vite__mapDeps([23,9,24,19,20,21,11]))),ModelAssignmentsPanel=reactExports.lazy(()=>__vitePreload(()=>import("./ModelAssignmentsPanel-CSAryvWJ.js").then(n=>n.M),__vite__mapDeps([25,24,19,20,21,22,4])).then(n=>({default:n.ModelAssignmentsPanel}))),DocumentProcessingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./DocumentProcessingPanel-Da2Re6Rg.js"),__vite__mapDeps([26,25,24,19,20,21,22,4])).then(n=>({default:n.DocumentProcessingPanel}))),SearchIndexingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SearchIndexingPanel-MjKL5QLU.js"),__vite__mapDeps([27,25,24,19,20,21,22,4])).then(n=>({default:n.SearchIndexingPanel}))),IndexLifecyclePanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexLifecyclePanel-BSZuIzgr.js"),__vite__mapDeps([28,25,24,19,20,21,22,4])).then(n=>({default:n.IndexLifecyclePanel}))),SystemSettingsPage=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsPage-D2z6Z4FE.js"),__vite__mapDeps([29,7,1,30,9,11]))),PodSettingsSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsSubjectPanel-4sxma4X4.js"),__vite__mapDeps([31,1,30,19,13,17,3])).then(n=>({default:n.PodSettingsSubjectPanel})));function lazyRoute(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}function systemSettingsPage(n){return{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(SystemSettingsPage,{})),children:n}]}}const aiConnectionsSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{index:!0,element:lazyRoute(jsxRuntimeExports.jsx(ModelsPage,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:".",replace:!0})}]}],aiConfigSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(AiConfigPage,{})),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})},{path:"model-assignments",element:lazyRoute(jsxRuntimeExports.jsx(ModelAssignmentsPanel,{}))},{path:"document-processing",element:lazyRoute(jsxRuntimeExports.jsx(DocumentProcessingPanel,{}))},{path:"search-indexing",element:lazyRoute(jsxRuntimeExports.jsx(SearchIndexingPanel,{}))},{path:"index-lifecycle",element:lazyRoute(jsxRuntimeExports.jsx(IndexLifecyclePanel,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})}]}]}],systemSettingsSurfaceRoutes=[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})},{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"pod",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"pod"}))}])]},{element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"identity-access",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"identity-access"}))}])]},systemSettingsPage([{path:"storage",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"storage"}))},{path:"runtime",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"runtime"}))},{path:"cloud",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"cloud"}))},{path:"advanced",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"advanced"}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})}])],xpodShellRoutes=[{path:"status",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:statusSurfaceRoutes},{path:"network",children:networkSurfaceRoutes},{path:"ai-connections",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConnectionsSurfaceRoutes},{path:"ai-config",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConfigSurfaceRoutes},{path:"settings",children:systemSettingsSurfaceRoutes},{path:"dashboard",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:dashboardRoutes},{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})}];function XpodShellRoutes(){const n=useLocation(),e=useRoutes(xpodShellRoutes);return reactExports.useEffect(()=>{document.title=n.pathname.startsWith("/status")?"Xpod Dashboard":"Xpod Settings"},[n.pathname]),e}function XpodShellApp({runtime:n,initialPathname:e}={}){const[t]=reactExports.useState(()=>initializeProductLocation(e));return jsxRuntimeExports.jsx(XpodThemeRoot,{children:jsxRuntimeExports.jsx(AuthProvider,{children:jsxRuntimeExports.jsxs(XpodSolidRuntimeProvider,{value:n,children:[jsxRuntimeExports.jsx(XpodDesktopIdentityBridge,{}),jsxRuntimeExports.jsx(XpodRememberedLoginBridge,{}),jsxRuntimeExports.jsxs(BrowserRouter,{children:[jsxRuntimeExports.jsx(XpodDesktopNavigationBridge,{}),jsxRuntimeExports.jsx(XpodServiceAvailability,{children:jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(XpodShellRoutes,{})})}),jsxRuntimeExports.jsx(Toaster,{})]},t)]})})})}function initializeProductLocation(n){const t=`${canonicalProductPathname(n??globalThis.location?.pathname??XPOD_DEFAULT_RETURN_PATH)}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==t&&globalThis.history?.replaceState(null,"",t),t}initializeXpodTheme();clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(reactExports.StrictMode,{children:jsxRuntimeExports.jsx(XpodThemeProvider,{children:jsxRuntimeExports.jsx(XpodShellApp,{})})}));export{dispatchDiscreteCustomEvent as $,hasInvalidWebIdWhitespace as A,Button as B,Card as C,Database as D,xpodRegistrationCopy as E,resolveProvisionCodeForPodCreate as F,scopeAccountUrl as G,buildPodCreatePayload as H,getAccountSessionToken as I,accountTokenHeaders as J,resolveProvisionScope as K,storageUrlBelongsToRoot as L,prepareProvisionedPod as M,NavLink as N,Outlet as O,Primitive as P,useAuth as Q,RefreshCw as R,resolveProvisionCodeForCurrentScope as S,Sparkles as T,Gauge as U,reactDomExports as V,useCallbackRef as W,X,toast as Y,Copy as Z,React4 as _,CardHeader as a,clsx as a0,Link as a1,getDefaultExportFromCjs as a2,createLucideIcon$1 as a3,createSlottable as a4,getLinkedResourceUrlAll as a5,acp as a6,internal_cloneResource as a7,getSolidDataset as a8,freeze as a9,AvatarFallback as aA,LoaderCircle$1 as aB,Input as aC,LoginFailureView as aD,LoginConnectingView as aE,Label as aF,dismissToast as aG,controlFocusClass as aH,Toaster as aI,AuthContext as aJ,createXpodLoginController as aK,requireBuffer as aL,requireLink as aM,getAugmentedNamespace as aN,requireBrowser$2 as aO,requireSparql as aP,requireEvents as aQ,requireBrowser$3 as aR,requireString_decoder as aS,bufferExports as aT,commonjsGlobal as aU,getSourceUrl as aa,getResourceInfo as ab,getSourceIri as ac,getThingAll as ad,getIriAll as ae,rdf$3 as af,acl as ag,setThing as ah,setIri as ai,removeIri as aj,removeAll as ak,createThing as al,addIri as am,removeThing as an,subjectToRdfJsQuads as ao,DataFactory$1 as ap,getIri as aq,saveSolidDatasetAt as ar,createSolidDataset as as,foaf as at,getThing as au,getUrlAll as av,buildThing as aw,__vitePreload as ax,Avatar as ay,AvatarImage as az,CardTitle as b,createLucideIcon as c,CardDescription as d,CardContent as e,cn as f,cva as g,credentialDescriptor as h,interactiveFocusClass as i,jsxRuntimeExports as j,credentialResource as k,useLayoutEffect2 as l,useComposedRefs as m,createContextScope as n,createSlot as o,aiConfigModelRef as p,aiProviderResource as q,reactExports as r,aiModelResource as s,configureSparqlEngine as t,useXpodSolidRuntime as u,useLocation as v,handleListNavigationKeyDown as w,getListNavItemClass as x,resolveHostedAccountControlUrl as y,storedAccountTokenHeaders as z};