mcard-studio 0.0.2 → 0.0.3

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 (196) hide show
  1. package/README.md +3 -0
  2. package/astro.config.mjs +41 -2
  3. package/cli/lib/runtimeContext.mjs +6 -3
  4. package/dist/client/_astro/{ChartAnalyticsViewlet.jrwIemvb.js → ChartAnalyticsViewlet.CBW-JyA3.js} +1 -1
  5. package/dist/client/_astro/{ClmPcardViewlet.C-fU7oZf.js → ClmPcardViewlet.cvKsR2ng.js} +2 -2
  6. package/dist/client/_astro/{D3GraphViewlet.BCZl0b2U.js → D3GraphViewlet.8YEIrCGL.js} +1 -1
  7. package/dist/client/_astro/DockviewSpatialWorkbench.BTd66LPl.js +12 -0
  8. package/dist/client/_astro/DocumentViewlets.KY1HcNka.js +2 -0
  9. package/dist/client/_astro/DxfViewlet.B3N5zpZR.js +1 -0
  10. package/dist/client/_astro/{ExcalidrawWhiteboardViewlet.CFpPYSdn.js → ExcalidrawWhiteboardViewlet.CMJGCQN4.js} +1 -1
  11. package/dist/client/_astro/{FaroVCardSpanInstrumenter.un8kDMWv.js → FaroVCardSpanInstrumenter.ClIqZujq.js} +1 -1
  12. package/dist/client/_astro/{FontSpecimenViewlet.D7Aw2xBZ.js → FontSpecimenViewlet.ChIyr0B8.js} +1 -1
  13. package/dist/client/_astro/HeadMeta.astro_astro_type_script_index_0_lang.D3FSc061.js +1 -0
  14. package/dist/client/_astro/{ImageViewlet.D4FN87n_.js → ImageViewlet.Cs-u7-wt.js} +1 -1
  15. package/dist/client/_astro/{KatexFormulaViewlet.CzhdIOw8.js → KatexFormulaViewlet.0nOzV_qD.js} +1 -1
  16. package/dist/client/_astro/{KoishiChatViewlet.5mepQvLX.js → KoishiChatViewlet.DLsMmwdb.js} +4 -4
  17. package/dist/client/_astro/{MCardLibraryHarness.DE8KeghO.js → MCardLibraryHarness.WBT9W10S.js} +1 -1
  18. package/dist/client/_astro/{MarkdownViewlet.CRuuXXmF.js → MarkdownViewlet.BIolkNXf.js} +25 -25
  19. package/dist/client/_astro/{MermaidDiagramViewlet.eW6sk-rF.js → MermaidDiagramViewlet.CkRk7QsS.js} +1 -1
  20. package/dist/client/_astro/PCardRendererBridge.DhaRSprd.js +1 -0
  21. package/dist/client/_astro/RendererPCardRegistry.brM2KiQs.js +1 -0
  22. package/dist/client/_astro/{SchemaYamlViewlet.ZJBvxItR.js → SchemaYamlViewlet.Bc7nkK4M.js} +1 -1
  23. package/dist/client/_astro/{ShellContainer.astro_astro_type_script_index_0_lang.j_ELcN5d.js → ShellContainer.astro_astro_type_script_index_0_lang.5q1gCLvf.js} +1 -1
  24. package/dist/client/_astro/{Spatial3dViewlet.DnVMBENJ.js → Spatial3dViewlet.C-jjhr0A.js} +1 -1
  25. package/dist/client/_astro/{StudioLayout.CBgiVbeb.css → StudioLayout.CX8XGtZV.css} +1 -1
  26. package/dist/client/_astro/StudioWorkbench.B1QwGHWM.js +7 -0
  27. package/dist/client/_astro/{SvgViewlet.BCje7Qqb.js → SvgViewlet.uGxvb06H.js} +1 -1
  28. package/dist/client/_astro/{TerminalView.C_Ksz6lT.js → TerminalView.DP7G7E1m.js} +1 -1
  29. package/dist/client/_astro/{ThemeSettingsViewlet.DJpjQQ0Z.js → ThemeSettingsViewlet.UaTHcGnF.js} +1 -1
  30. package/dist/client/_astro/{TikzDiagramViewlet.CXb1A8nf.js → TikzDiagramViewlet.O8MJyXfT.js} +1 -1
  31. package/dist/client/_astro/VideoPlayerViewlet.-ycmo3kY.js +1 -0
  32. package/dist/client/_astro/WebappZenViewlet.PNce4u2T.js +1 -0
  33. package/dist/client/_astro/{WelcomeViewport.BiYwLh6l.js → WelcomeViewport.CZ6RxGSw.js} +1 -1
  34. package/dist/client/_astro/{agentIdentityCredentialService.UzMMwBwv.js → agentIdentityCredentialService.BEtZzBlO.js} +1 -1
  35. package/dist/client/_astro/cardTypeDetector.C2HH5RnU.js +1 -0
  36. package/dist/client/_astro/disposable.BmlxZrDf.js +1 -0
  37. package/dist/client/_astro/{markdownService.BgWjyJ57.js → markdownService.CpuKl0vp.js} +1 -1
  38. package/dist/client/_astro/{mcardStore.CT-ollfl.js → mcardStore.nSWnzeLg.js} +1 -1
  39. package/dist/client/_astro/mcardVfs.BSdys1Y7.js +3 -0
  40. package/dist/client/_astro/pathsConfig.CSBBSzwH.js +2 -0
  41. package/dist/client/_astro/{polyfills._3wYPjZf.js → polyfills.Bi7kO8cu.js} +1 -1
  42. package/dist/client/_astro/rendererEventBus.DirFDmGw.js +1 -0
  43. package/dist/client/_astro/themeStore.BajxvCga.js +1 -0
  44. package/dist/client/_astro/{tikzCompiler.fe3qomFY.js → tikzCompiler.-fXMNQpz.js} +1 -1
  45. package/dist/client/_astro/{useMCardHydration.7Z-HfBh5.js → useMCardHydration.Bjj_N5Gv.js} +1 -1
  46. package/dist/client/_astro/vendor-clm-kernel.B0kxq3g4.js +108 -0
  47. package/dist/client/_astro/{vfsHandles.IX_wTpw_.js → vfsHandles.D4Pq18pW.js} +1 -1
  48. package/dist/client/_astro/vfsPersistence.DVrd1BZj.js +1 -0
  49. package/dist/client/_astro/{vfsTransactions.C_IQQg0s.js → vfsTransactions.DBNtFuRz.js} +1 -1
  50. package/dist/client/_astro/{workspaceStore.CD0kAVAl.js → workspaceStore.DUHW2YBc.js} +1 -1
  51. package/dist/server/chunks/{_.._5gPhVOLM.mjs → _.._CoQKwo62.mjs} +137 -91
  52. package/dist/server/chunks/{_handle__D_cIJYrU.mjs → _handle__D8dKQPUS.mjs} +3 -3
  53. package/dist/server/chunks/{cardTypeDetector_CyW1Xnmy.mjs → cardTypeDetector_C55M_HWS.mjs} +9 -0
  54. package/dist/server/chunks/{cards_B89BvF6W.mjs → cards_rVOc8K6H.mjs} +2 -2
  55. package/dist/server/chunks/cas_DTxlZ4Le.mjs +68 -0
  56. package/dist/server/chunks/{dispatch_DOwSKukU.mjs → dispatch_BTW4E_BJ.mjs} +8 -7
  57. package/dist/server/chunks/{dispatch_CxWKiHpn.mjs → dispatch_MbkljUxD.mjs} +8 -8
  58. package/dist/server/chunks/{export_DRouradA.mjs → export_DkEwDE2T.mjs} +3 -3
  59. package/dist/server/chunks/{health_Dfa5I0-X.mjs → health_cRt0M0yu.mjs} +1 -1
  60. package/dist/server/chunks/{mcard-library_7Wzoihkm.mjs → mcard-library_CLHvyslV.mjs} +1 -1
  61. package/dist/server/chunks/{mcardVfs_CeezzRvt.mjs → mcardVfs_DvNburKb.mjs} +5 -30
  62. package/dist/server/chunks/{move__RFvIDkq.mjs → move_DYcaXBLV.mjs} +6 -6
  63. package/dist/server/chunks/{pathsConfig_CgNYYLVm.mjs → pathsConfig_Dack-p2f.mjs} +13 -3
  64. package/dist/server/chunks/{proxy_CrWJQIBe.mjs → proxy_CMbbdBPW.mjs} +2 -2
  65. package/dist/server/chunks/{raw_DzNDaDVP.mjs → raw_C97sJWhg.mjs} +59 -26
  66. package/dist/server/chunks/{serverBootstrap_XKo2s6Ha.mjs → serverBootstrap_BDdSRIu5.mjs} +2 -2
  67. package/dist/server/chunks/tree_BwmO-pTe.mjs +186 -0
  68. package/dist/server/chunks/vfsCore_DIKpk-pk.mjs +98 -0
  69. package/dist/server/chunks/{vfsTreeScan_CKp7kMt9.mjs → vfsTreeScan_CRoCluPB.mjs} +18 -10
  70. package/dist/server/chunks/workspaceRoot_CRx3taID.mjs +157 -0
  71. package/dist/server/chunks/{write_popiFsO7.mjs → write_BLsmsTIx.mjs} +6 -5
  72. package/dist/server/chunks/{ws-server-init_DUjuR2-o.mjs → ws-server-init_Cfft7U5u.mjs} +343 -298
  73. package/dist/server/entry.mjs +1 -1
  74. package/dist/server/entry2.mjs +67 -28
  75. package/dist/server/virtual_astro_middleware.mjs +2 -2
  76. package/package.json +2 -2
  77. package/src/components/studio/views/cardViewlets/ClmRegistryComponentViewlet.tsx +133 -0
  78. package/src/components/studio/views/cardViewlets/DxfViewlet.tsx +230 -0
  79. package/src/components/studio/views/cardViewlets/VideoPlayerViewlet.tsx +4 -4
  80. package/src/components/studio/views/cardViewlets/coreViewletDefs.ts +2 -2
  81. package/src/components/studio/views/cardViewlets/documents/AudioPlayerViewlet.tsx +15 -3
  82. package/src/components/studio/views/cardViewlets/documents/PdfViewlet.tsx +25 -7
  83. package/src/components/studio/views/cardViewlets/markdown/stages/wikilinkStage.ts +2 -1
  84. package/src/components/studio/views/cardViewlets/mediaViewletDefs.ts +21 -1
  85. package/src/components/studio/views/cardViewlets/webapp/WebappCanvas.tsx +40 -15
  86. package/src/components/studio/views/cardViewlets/webapp/WebappDevicePresetBar.tsx +108 -0
  87. package/src/components/studio/views/cardViewlets/webapp/WebappZenViewlet.tsx +23 -30
  88. package/src/components/studio/views/fileTree/MCardFileTree.tsx +71 -54
  89. package/src/components/studio/views/fileTree/hooks/useFileTreeSync.ts +0 -1
  90. package/src/components/studio/views/fileTree/hooks/usePartitionedTrees.ts +68 -23
  91. package/src/components/studio/views/fileTree/hooks/useSectionAccordion.ts +21 -11
  92. package/src/components/studio/views/functions/UnifiedFunctionExplorerViewlet.tsx +168 -0
  93. package/src/components/studio/views/history/HistoryPanel.tsx +110 -0
  94. package/src/components/studio/views/lineage/LineagePanel.tsx +152 -0
  95. package/src/components/studio/views/navigation/HandleLineageDrawer.tsx +89 -0
  96. package/src/components/studio/views/navigation/MultiCardCollectionBrowser.tsx +154 -0
  97. package/src/components/studio/views/pills/HashPill.tsx +101 -0
  98. package/src/components/studio/views/residency/ResidencyIndicator.tsx +82 -0
  99. package/src/config/app_config.json +3 -3
  100. package/src/core/projection/catalog.ts +105 -0
  101. package/src/core/projection/collection.ts +148 -0
  102. package/src/core/projection/handleSubscription.ts +132 -0
  103. package/src/core/projection/index.ts +4 -0
  104. package/src/core/projection/selectors.ts +29 -0
  105. package/src/core/projection/views.ts +242 -0
  106. package/src/core/refinement/designMetrics.ts +104 -0
  107. package/src/core/refinement/fibrationProjector.ts +142 -0
  108. package/src/core/refinement/lagrangianEngine.ts +137 -0
  109. package/src/core/refinement/refinementCommands.ts +82 -0
  110. package/src/core/viewport/deviceArchetypeRegistry.ts +177 -0
  111. package/src/core/viewport/viewportAudit.ts +150 -0
  112. package/src/edge/storeFilter.d.ts +4 -0
  113. package/src/edge/storeFilter.js +54 -0
  114. package/src/edge/storeFilter.ts +52 -0
  115. package/src/lib/cryptoPolyfill.js +77 -1
  116. package/src/lib/fsPolyfill.js +65 -0
  117. package/src/lib/urlPolyfill.js +21 -0
  118. package/src/lib/zlibPolyfill.js +35 -0
  119. package/src/packages/mcard-studio/package.json +2 -2
  120. package/src/packages/mcard-studio/type/legacyMapping.ts +5 -0
  121. package/src/packages/mcard-studio/viewlets/manifests.ts +2 -0
  122. package/src/packages/mcard-studio/viewlets/moduleMap.ts +12 -0
  123. package/src/packages/mcard-studio/viewlets/refinementManifests.ts +114 -0
  124. package/src/pages/api/dispatch.ts +3 -2
  125. package/src/pages/api/vfs/cas.ts +114 -0
  126. package/src/pages/api/vfs/move.ts +5 -5
  127. package/src/pages/api/vfs/raw.ts +72 -27
  128. package/src/pages/api/vfs/tree.ts +130 -11
  129. package/src/pages/api/vfs/write.ts +5 -4
  130. package/src/server/api/kernelDispatch.ts +8 -8
  131. package/src/server/artifactCollectionService.ts +4 -7
  132. package/src/server/artifactRepository.ts +4 -3
  133. package/src/server/clmRunner.mjs +1 -1
  134. package/src/server/collectionOwner.mjs +5 -5
  135. package/src/server/effects/executionPersistenceService.mjs +11 -11
  136. package/src/server/effects/resultSealingService.mjs +2 -2
  137. package/src/server/fileIngestService.mjs +21 -9
  138. package/src/server/fileWatcherService.mjs +4 -1
  139. package/src/server/handlers/fileChangeHandler.mjs +18 -10
  140. package/src/server/handlers/saveExecutionLogHandler.mjs +6 -6
  141. package/src/server/notificationService.mjs +14 -1
  142. package/src/server/scripts/buildSeedingMemory.mjs +3 -3
  143. package/src/server/serverMemoryRepository.ts +41 -59
  144. package/src/server/vfsTreeScan.ts +16 -10
  145. package/src/server/workspaceRoot.ts +143 -5
  146. package/src/services/cardTypeDetector.ts +4 -0
  147. package/src/services/databaseSyncService.ts +30 -46
  148. package/src/services/namespaceProtocolClient.ts +221 -0
  149. package/src/services/renderers/pcard/RendererPCardRegistry.ts +4 -66
  150. package/src/services/renderers/pcard/modalitySpecs.ts +125 -0
  151. package/src/services/renderers/pcard/types.ts +7 -1
  152. package/src/services/renderers/rendererEventBus.ts +5 -3
  153. package/src/services/unifiedFunctionExecutionService.ts +145 -0
  154. package/src/services/vfs/vfsCore.ts +12 -1
  155. package/src/services/vfs/vfsMigration.ts +95 -0
  156. package/src/services/vfs/vfsMutations.ts +17 -35
  157. package/src/services/vfs/vfsPersistence.ts +19 -24
  158. package/src/services/vfs/vfsSync.ts +55 -17
  159. package/src/services/vfs/vfsVersions.ts +23 -34
  160. package/src/services/workbenchExecutionPolicy.ts +183 -0
  161. package/src/stores/mcardCollectionStore.ts +2 -0
  162. package/src/styles/dockview.css +34 -0
  163. package/src/ui/viewlets/FibrationRefinementViewlet.tsx +155 -0
  164. package/src/ui/viewlets/PetriConformanceViewlet.tsx +166 -0
  165. package/src/ui/viewlets/ResponsiveViewportLabViewlet.tsx +175 -0
  166. package/src/ui/viewlets/SprintGovernanceViewlet.tsx +176 -0
  167. package/src/ui/viewlets/viewletFocus.ts +35 -0
  168. package/src/ui/viewlets/viewportLabParts.tsx +190 -0
  169. package/dist/client/_astro/DockviewSpatialWorkbench.B_I1GJHw.js +0 -12
  170. package/dist/client/_astro/DocumentViewlets.B53IqmpY.js +0 -2
  171. package/dist/client/_astro/HeadMeta.astro_astro_type_script_index_0_lang.VDRYJCM-.js +0 -1
  172. package/dist/client/_astro/PCardRendererBridge.oxVKc0gN.js +0 -1
  173. package/dist/client/_astro/RendererPCardRegistry.CWjYZs2H.js +0 -1
  174. package/dist/client/_astro/StudioWorkbench.Blo5oSIw.js +0 -7
  175. package/dist/client/_astro/VideoPlayerViewlet.CmECt7yT.js +0 -1
  176. package/dist/client/_astro/WebappZenViewlet.whCmGVHR.js +0 -1
  177. package/dist/client/_astro/__vite-browser-external.CQZnr-r3.js +0 -1
  178. package/dist/client/_astro/cardTypeDetector.Ci4APwhX.js +0 -1
  179. package/dist/client/_astro/disposable.Dsb0sbRP.js +0 -1
  180. package/dist/client/_astro/mcardVfs.2UOw9Z-r.js +0 -3
  181. package/dist/client/_astro/pathsConfig.D0hV34p7.js +0 -2
  182. package/dist/client/_astro/rendererEventBus.DMH9afq9.js +0 -1
  183. package/dist/client/_astro/themeStore.CEt0e54l.js +0 -1
  184. package/dist/client/_astro/vendor-clm-kernel.Bvk3XHk2.js +0 -116
  185. package/dist/client/_astro/vfsPersistence.BuhXYeSb.js +0 -1
  186. package/dist/server/chunks/cryptoPolyfill_99rxUwYC.mjs +0 -180
  187. package/dist/server/chunks/kernelHash_DRaj51hY.mjs +0 -5
  188. package/dist/server/chunks/tree_CE2BhvyJ.mjs +0 -76
  189. package/dist/server/chunks/vfsCore_B6nCiBl5.mjs +0 -21
  190. package/dist/server/chunks/workspaceRoot_DVSUbYkd.mjs +0 -71
  191. package/src/server/kernelHash.ts +0 -22
  192. package/src/server/storage/cardCollection.ts +0 -94
  193. package/src/server/storage/index.ts +0 -3
  194. package/src/server/storage/mcard.ts +0 -99
  195. package/src/server/storage/sqliteNodeEngine.ts +0 -121
  196. /package/dist/server/chunks/{StudioLayout_B5ZnlqjF.mjs → StudioLayout_taayQJ5b.mjs} +0 -0
@@ -0,0 +1,108 @@
1
+ import{n as e,r as t}from"./rolldown-runtime.Dd_uD5pT.js";import{t as n}from"./preload-helper.oCYlU9a4.js";var r=class{#e=[];#t=!1;add(e){if(this.#t)throw Error(`DisposableList: cannot add to an already-disposed list`);return this.#e.push(e),this}get length(){return this.#e.length}get disposed(){return this.#t}async dispose(){if(this.#t)return;this.#t=!0;let e=[];for(let t=this.#e.length-1;t>=0;t--)try{await this.#e[t]()}catch(t){e.push(t instanceof Error?t:Error(String(t)))}if(this.#e.length=0,e.length>0){let t=`DisposableList: ${e.length} disposer(s) failed:
2
+ ${e.map(e=>e.message).join(`
3
+ `)}`;throw Error(t)}}disposeSync(){if(this.#t)return;this.#t=!0;let e=[];for(let t=this.#e.length-1;t>=0;t--)try{let n=this.#e[t]();n&&typeof n.then==`function`&&e.push(Error(`DisposableList.disposeSync: encountered async disposer`))}catch(t){e.push(t instanceof Error?t:Error(String(t)))}if(this.#e.length=0,e.length>0)throw Error(`DisposableList: ${e.length} disposer(s) failed`)}},i=class{#e=`idle`;#t;#n=new r;#r;constructor(e){this.#r=e}get state(){return this.#e}get disposables(){return this.#n}begin(e){if(this.#e!==`idle`)throw Error(`SavepointGuard: cannot begin from state "${this.#e}"`);this.#t=e,this.#e=`active`}commit(){if(this.#e!==`active`)throw Error(`SavepointGuard: cannot commit from state "${this.#e}"`);this.#e=`committed`,this.#t=void 0}async rollback(){if(this.#e!==`active`)throw Error(`SavepointGuard: cannot rollback from state "${this.#e}"`);this.#e=`rolled-back`,this.#r&&this.#t!==void 0&&await this.#r(this.#t),await this.#n.dispose(),this.#t=void 0}};function a(e){let t=typeof e==`string`?new TextEncoder().encode(e):e,n=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],r=1779033703,i=3144134277,a=1013904242,o=2773480762,s=1359893119,c=2600822924,l=528734635,u=1541459225,d=t.length,f=d*8,p=d+(d%64<56?56-d%64:120-d%64)+8,m=new Uint8Array(p);m.set(t),m[d]=128;let h=new DataView(m.buffer);h.setBigUint64(p-8,BigInt(f),!1);let g=new Uint32Array(64),_=(e,t)=>e>>>t|e<<32-t;for(let e=0;e<p;e+=64){for(let t=0;t<16;t++)g[t]=h.getUint32(e+t*4,!1);for(let e=16;e<64;e++){let t=_(g[e-15],7)^_(g[e-15],18)^g[e-15]>>>3,n=_(g[e-2],17)^_(g[e-2],19)^g[e-2]>>>10;g[e]=g[e-16]+t+g[e-7]+n|0}let t=r,d=i,f=a,p=o,m=s,v=c,y=l,b=u;for(let e=0;e<64;e++){let r=_(m,6)^_(m,11)^_(m,25),i=m&v^~m&y,a=b+r+i+n[e]+g[e]|0,o=(_(t,2)^_(t,13)^_(t,22))+(t&d^t&f^d&f)|0;b=y,y=v,v=m,m=p+a|0,p=f,f=d,d=t,t=a+o|0}r=r+t|0,i=i+d|0,a=a+f|0,o=o+p|0,s=s+m|0,c=c+v|0,l=l+y|0,u=u+b|0}let v=new Uint8Array(32),y=new DataView(v.buffer);return y.setUint32(0,r,!1),y.setUint32(4,i,!1),y.setUint32(8,a,!1),y.setUint32(12,o,!1),y.setUint32(16,s,!1),y.setUint32(20,c,!1),y.setUint32(24,l,!1),y.setUint32(28,u,!1),v}var o=class{constructor(e){this.algorithm=e,this.chunks=[]}update(e){return typeof e==`string`?this.chunks.push(new TextEncoder().encode(e)):e instanceof Uint8Array?this.chunks.push(e):ArrayBuffer.isView(e)&&this.chunks.push(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),this}digest(e){let t=0;for(let e of this.chunks)t+=e.length;let n=new Uint8Array(t),r=0;for(let e of this.chunks)n.set(e,r),r+=e.length;let i=a(n);return e===`hex`?Array.from(i).map(e=>e.toString(16).padStart(2,`0`)).join(``):typeof Buffer<`u`&&typeof Buffer.from==`function`?Buffer.from(i):i}};function s(e){return new o(e)}function c(){return typeof globalThis<`u`&&globalThis.crypto&&typeof globalThis.crypto.randomUUID==`function`?globalThis.crypto.randomUUID():`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))}function l(e){if(typeof globalThis<`u`&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues==`function`)return globalThis.crypto.getRandomValues(e);for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return e}function u(e){let t=new Uint8Array(e);return l(t),typeof Buffer<`u`&&typeof Buffer.from==`function`?Buffer.from(t):t}typeof globalThis<`u`&&globalThis.crypto;function d(e){return{export:()=>``,type:`private`,...typeof e==`object`?e:{}}}function f(e){return{export:()=>``,type:`public`,...typeof e==`object`?e:{}}}function p(){return{computeSecret:()=>new Uint8Array(32),generateKeys:()=>new Uint8Array(32)}}var m=[`md5`,`sha1`,`sha224`,`sha256`,`sha384`,`sha512`,`blake3`];function h(e){return typeof e==`string`&&m.includes(e)}var g=`blake3:`,_=`sha256:`,v=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],y=1,b=2,x=4,S=8,C=64,w=1024,T=new Uint32Array(16),E=new Uint32Array(16),D=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function O(e,t,n,r,i){let a=e[0]|0,o=e[1]|0,s=e[2]|0,c=e[3]|0,l=e[4]|0,u=e[5]|0,d=e[6]|0,f=e[7]|0,p=1779033703,m=-1150833019,h=1013904242,g=-1521486534,_=n|0,v=0,y=r|0,b=i|0,x=t[0]|0,S=t[1]|0,C=t[2]|0,w=t[3]|0,E=t[4]|0,D=t[5]|0,O=t[6]|0,ee=t[7]|0,te=t[8]|0,ne=t[9]|0,re=t[10]|0,ie=t[11]|0,ae=t[12]|0,oe=t[13]|0,se=t[14]|0,ce=t[15]|0;for(let e=0;e<7;e++)if(a=a+l+x|0,_^=a,_=_>>>16|_<<16,p=p+_|0,l^=p,l=l>>>12|l<<20,a=a+l+S|0,_^=a,_=_>>>8|_<<24,p=p+_|0,l^=p,l=l>>>7|l<<25,o=o+u+C|0,v^=o,v=v>>>16|v<<16,m=m+v|0,u^=m,u=u>>>12|u<<20,o=o+u+w|0,v^=o,v=v>>>8|v<<24,m=m+v|0,u^=m,u=u>>>7|u<<25,s=s+d+E|0,y^=s,y=y>>>16|y<<16,h=h+y|0,d^=h,d=d>>>12|d<<20,s=s+d+D|0,y^=s,y=y>>>8|y<<24,h=h+y|0,d^=h,d=d>>>7|d<<25,c=c+f+O|0,b^=c,b=b>>>16|b<<16,g=g+b|0,f^=g,f=f>>>12|f<<20,c=c+f+ee|0,b^=c,b=b>>>8|b<<24,g=g+b|0,f^=g,f=f>>>7|f<<25,a=a+u+te|0,b^=a,b=b>>>16|b<<16,h=h+b|0,u^=h,u=u>>>12|u<<20,a=a+u+ne|0,b^=a,b=b>>>8|b<<24,h=h+b|0,u^=h,u=u>>>7|u<<25,o=o+d+re|0,_^=o,_=_>>>16|_<<16,g=g+_|0,d^=g,d=d>>>12|d<<20,o=o+d+ie|0,_^=o,_=_>>>8|_<<24,g=g+_|0,d^=g,d=d>>>7|d<<25,s=s+f+ae|0,v^=s,v=v>>>16|v<<16,p=p+v|0,f^=p,f=f>>>12|f<<20,s=s+f+oe|0,v^=s,v=v>>>8|v<<24,p=p+v|0,f^=p,f=f>>>7|f<<25,c=c+l+se|0,y^=c,y=y>>>16|y<<16,m=m+y|0,l^=m,l=l>>>12|l<<20,c=c+l+ce|0,y^=c,y=y>>>8|y<<24,m=m+y|0,l^=m,l=l>>>7|l<<25,e<6){let e=C,t=O,n=w,r=re,i=ee,a=x,o=E,s=oe,c=S,l=ie,u=ae,d=D,f=ne,p=se,m=ce,h=te;x=e,S=t,C=n,w=r,E=i,D=a,O=o,ee=s,te=c,ne=l,re=u,ie=d,ae=f,oe=p,se=m,ce=h}let k=T;return k[0]=(a^p)>>>0,k[1]=(o^m)>>>0,k[2]=(s^h)>>>0,k[3]=(c^g)>>>0,k[4]=(l^_)>>>0,k[5]=(u^v)>>>0,k[6]=(d^y)>>>0,k[7]=(f^b)>>>0,k[8]=(p^e[0])>>>0,k[9]=(m^e[1])>>>0,k[10]=(h^e[2])>>>0,k[11]=(g^e[3])>>>0,k[12]=(_^e[4])>>>0,k[13]=(v^e[5])>>>0,k[14]=(y^e[6])>>>0,k[15]=(b^e[7])>>>0,k}function ee(e,t,n,r){if(n===64){for(let n=0;n<16;n++){let i=t+(n<<2);r[n]=(e[i]|e[i+1]<<8|e[i+2]<<16|e[i+3]<<24)>>>0}return}r.fill(0);for(let i=0;i<n;i++)r[i>>>2]|=e[t+i]<<((i&3)<<3)>>>0}function te(e,t){let n=``;for(let r=0;r<t;r++){let t=e[r];n+=D[t&255]+D[t>>>8&255]+D[t>>>16&255]+D[t>>>24&255]}return n}function ne(e){let t=Math.max(1,Math.ceil(e.length/w));if(t===1){let t=Math.max(1,Math.ceil(e.length/C)),n=new Uint32Array(v);for(let r=0;r<t;r++){let i=r*C,a=Math.min(C,Math.max(0,e.length-i));ee(e,i,a,E);let o=0;if(r===0&&(o|=y),r===t-1)return o|=b|S,te(O(n,E,0,a>0?a:0,o),8);let s=O(n,E,0,C,o);for(let e=0;e<8;e++)n[e]=s[e]}}let n=[];for(let r=0;r<t;r++){let t=r*w,i=Math.min(t+w,e.length),a=i-t,o=Math.max(1,Math.ceil(a/C)),s=new Uint32Array(v);for(let n=0;n<o;n++){let a=t+n*C,c=Math.min(C,Math.max(0,i-a));ee(e,a,c,E);let l=0;n===0&&(l|=y),n===o-1&&(l|=b);let u=O(s,E,r,c,l);for(let e=0;e<8;e++)s[e]=u[e]}n.push(s)}let r=n;for(;r.length>1;){let e=[];for(let t=0;t<r.length;t+=2)if(t+1<r.length){for(let e=0;e<8;e++)E[e]=r[t][e];for(let e=0;e<8;e++)E[e+8]=r[t+1][e];let n=O(v,E,0,C,x|(r.length<=2&&t===0?S:0)),i=new Uint32Array(8);for(let e=0;e<8;e++)i[e]=n[e];e.push(i)}else e.push(r[t]);r=e}return r.length===1?te(r[0],8):te(v,8)}function re(e){try{return s(`sha256`).update(e).digest(`hex`)}catch{throw Error(`SHA-256 requires Node.js crypto module or Web Crypto API`)}}var ie=class{constructor(e){this.algorithm=e}algorithm;hash(e){return s(this.algorithm).update(e).digest(`hex`)}prefix(){return`${this.algorithm}:`}},ae=class{hash(e){return ne(e)}prefix(){return g}},oe=class{hash(e){return re(e)}prefix(){return _}},se={md5:new ie(`md5`),sha1:new ie(`sha1`),sha224:new ie(`sha224`),sha256:new oe,sha384:new ie(`sha384`),sha512:new ie(`sha512`),blake3:new ae},ce=se.blake3;function k(e,t){let n=e.trim().toLowerCase().replace(/:$/,``);if(!h(n))throw Error(`Unsupported hash algorithm configured by ${t}: ${e}`);return n}function le(){let e=typeof process<`u`?{}:void 0,t=e?.CLM_HASH_CONFIG?.trim();if(t)return k(t.split(`|`,1)[0]||`blake3`,`CLM_HASH_CONFIG`);let n=e?.CLM_HASH_ALGO?.trim()||e?.MCARD_HASH_ALGORITHM?.trim();if(n)return k(n,e?.CLM_HASH_ALGO?.trim()?`CLM_HASH_ALGO`:`MCARD_HASH_ALGORITHM`);let r=ce.prefix();return k(r.endsWith(`:`)?r.slice(0,-1):r,`default hash provider`)}function ue(e){if(e!==void 0){if(!h(e))throw Error(`Unsupported hash algorithm: ${String(e)}`);return e}return le()}function de(e,t){let n=se[e];if(!n)throw Error(`Unsupported hash algorithm: ${e}`);return n.hash(t)}function fe(e,t){if(typeof e==`string`){let n=e;return`${n}:${de(n,t)}`}let n=e;if(!t)return`${ce.prefix()}${ce.hash(n)}`;if(typeof t==`string`){let e=t;return`${e}:${de(e,n)}`}let r=t;return`${r.prefix()}${r.hash(n)}`}function pe(e,t){return fe(new TextEncoder().encode(e),t)}var me={md5:32,sha1:40,sha224:56,sha256:64,sha384:96,sha512:128,blake3:64},A=class e{algorithm;hex;constructor(e,t=`blake3`){this.hex=e,this.algorithm=t,Object.freeze(this)}static fromHex(t,n=`blake3`){let r=t.toLowerCase(),i=me[n];if(i&&r.length!==i)throw Error(`ContentHash: expected ${i}-char hex string for ${n}, got "${t.slice(0,20)}..." (length ${t.length})`);if(!/^[0-9a-f]+$/.test(r))throw Error(`ContentHash: expected lowercase hex characters, got "${t.slice(0,20)}..."`);return new e(r,n)}static fromPrefixed(t){let n=t.indexOf(`:`);if(n===-1)return e.fromHex(t,`blake3`);let r=t.slice(0,n),i=t.slice(n+1);return h(r)?e.fromHex(i,r):e.fromHex(t,`blake3`)}static parse(t){return e.fromPrefixed(t)}static compute(t,n=`blake3`){let r=de(n,t);return new e(r,n)}static computeString(t,n=`blake3`){return e.compute(new TextEncoder().encode(t),n)}asHex(){return this.hex}asPrefixed(){return`${this.algorithm}:${this.hex}`}equals(e){return this.algorithm===e.algorithm&&this.hex===e.hex}toString(){return this.hex}toJSON(){return this.hex}},he=`did:`,j=class e{#e;constructor(e){this.#e=e,Object.freeze(this)}static create(t){if(!t.startsWith(he))throw Error(`AgentDid: expected string starting with "did:", got "${t.slice(0,20)}"`);if(t.length<8)throw Error(`AgentDid: DID string too short: "${t}"`);return new e(t)}asString(){return this.#e}method(){return this.#e.split(`:`)[1]??``}equals(e){return this.#e===e.#e}toString(){return this.#e}toJSON(){return this.#e}},ge=class e{#e;constructor(e){this.#e=e,Object.freeze(this)}static create(t){if(t.length===0)throw Error(`Handle: cannot be empty`);return new e(t)}static parse(t){return e.create(t)}static fromPath(t){let n=t.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/\/+$/,``);return new e(n.replace(/\//g,`:`))}asString(){return this.#e}toPath(){return this.#e.replace(/:/g,`/`)}name(){let e=this.#e.split(`:`);return e[e.length-1]??this.#e}equals(e){return this.#e===e.#e}toString(){return this.#e}toJSON(){return this.#e}};async function _e(e,t,n){let r=e.requiredServices??[];if(r.length===0)return t;let i=e=>t[e]!==void 0||typeof t.get==`function`&&t.get(e)!==void 0,a=r.filter(e=>!i(e));if(a.length===0)return t;if(typeof t.inject!=`function`)throw Error(`Missing required Cordis services: ${a.join(`, `)}`);return new Promise((e,i)=>{let o;n!==void 0&&n>0&&(o=setTimeout(()=>{i(Error(`Timed out waiting for Cordis services: ${a.join(`, `)}`))},n));try{t.inject(r,t=>{o&&clearTimeout(o),e(t)})}catch(e){o&&clearTimeout(o),i(e)}})}var ve=class{type=`primitive`;pcardType=`primitive`;mcard;constructor(e){this.mcard=e}evaluate(){return this.mcard}toJSON(){return{type:this.type,pcard_type:this.pcardType,mcard:this.mcard.toJSON()}}},ye=class e{type=`dynamic`;pcardType=`dynamic`;id;codeHash;sourceUri;coeffects;signature;constructor(e){this.id=e.id,this.codeHash=typeof e.codeHash==`string`?A.parse(e.codeHash):e.codeHash,this.sourceUri=e.sourceUri,this.coeffects=e.coeffects??{requiredServices:[]},this.signature=e.signature}clone(t={}){return new e({id:t.id??this.id,codeHash:t.codeHash??this.codeHash,sourceUri:t.sourceUri??this.sourceUri,coeffects:t.coeffects??this.coeffects,signature:t.signature??this.signature})}toJSON(){return{type:this.type,pcard_type:this.pcardType,id:this.id,code_hash:this.codeHash.toString(),source_uri:this.sourceUri,coeffects:this.coeffects,signature:this.signature}}},be=class{type=`boolean`;pcardType=`boolean`;id;phase;expression;targetPattern;coeffects;constructor(e){this.id=e.id,this.phase=e.phase,this.expression=e.expression,this.targetPattern=e.targetPattern??`*`,this.coeffects=e.coeffects??{requiredServices:[]}}isPrecondition(){return this.phase===`precondition`}isPostcondition(){return this.phase===`postcondition`}isLoopInvariant(){return this.phase===`loop_invariant`||this.phase===`loop-invariant`}toJSON(){return{type:this.type,pcard_type:this.pcardType,id:this.id,phase:this.phase,expression:this.expression,target_pattern:this.targetPattern,coeffects:this.coeffects}}},xe=new TextEncoder,Se=new TextDecoder;function Ce(e){if(typeof e!=`object`||!e)return e;if(e instanceof Uint8Array)return new Uint8Array(e);if(Array.isArray(e))return Object.freeze(e.map(Ce));let t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){let t={};for(let[n,r]of Object.entries(e))t[n]=Ce(r);return Object.freeze(t)}return e}function we(e){switch(e.kind){case`binary`:return Object.freeze({kind:`binary`,mimeType:e.mimeType,data:new Uint8Array(e.data)});case`structured`:return Object.freeze({kind:`structured`,value:Ce(e.value)});case`satori`:return Object.freeze({kind:`satori`,value:Ce(e.value)});default:return Object.freeze({...e})}}function Te(e){return e&&typeof e==`object`&&`kind`in e&&typeof e.kind==`string`?we(e):typeof e==`string`?Object.freeze({kind:`text`,value:e}):e instanceof Uint8Array?Object.freeze({kind:`binary`,mimeType:`application/octet-stream`,data:new Uint8Array(e)}):Object.freeze(typeof e==`object`&&e?{kind:`structured`,value:Ce(e)}:{kind:`scalar`,value:e})}var M=class e{uri;hash;payload;metadata;author;sequence;constructor(e,t,n,r,i,a){this.uri=e,this.hash=t,this.payload=n,this.metadata=r,this.author=typeof i==`string`?j.create(i):i||j.create(`did:clm:agent:default`),this.sequence=a,Object.freeze(this)}static create(t,n,r,i=0,a=new Map){let o=Te(n),s=De(o),c=A.compute(s),l=(typeof r==`string`?j.create(r):r)||j.create(`did:key:z6MkhaXgBZDvotDkL5257faiz48Z8x28qqwjp64guC54Po39`);return new e(t,c,o,a,l,i)}static withMetadata(t,n,r,i,a){let o=we(n),s=De(o),c=A.compute(s);return new e(t,c,o,r,i,a)}static fromStorage(t,n,r,i,a,o){return new e(t,n,r,i,a,o)}asPrimitivePCard(){return new ve(this)}getMetadata(e){return this.metadata.get(e)}get content(){return this.payload.kind===`text`?this.payload.value:this.payload.kind===`scalar`?String(this.payload.value):this.payload.kind===`binary`?Se.decode(this.payload.data):JSON.stringify(this.payload)}toJSON(){let e=this.author?typeof this.author.asString==`function`?this.author.asString():String(this.author):`did:key:z6MkhaXgBZDvotDkL5257faiz48Z8x28qqwjp64guC54Po39`;return{uri:this.uri,hash:this.hash.asHex(),payload:Oe(this.payload),metadata:Object.fromEntries(this.metadata),author:e,sequence:this.sequence}}toPreimage(){return De(this.payload)}static fromJSON(t){let n=String(t.uri||``),r=A.fromHex(String(t.hash||``)),i=ke(t.payload),a=new Map(t.metadata&&typeof t.metadata==`object`?Object.entries(t.metadata):[]),o=String(t.author||`did:key:z6MkhaXgBZDvotDkL5257faiz48Z8x28qqwjp64guC54Po39`),s=j.create(o),c=Number(t.sequence??0);return new e(n,r,i,a,s,c)}};function Ee(e){if(e==null)return`null`;if(typeof e==`boolean`||typeof e==`number`||typeof e==`string`)return JSON.stringify(e);if(Array.isArray(e))return`[`+e.map(Ee).join(`,`)+`]`;if(typeof e==`object`){let t=e;return`{`+Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${Ee(t[e])}`).join(`,`)+`}`}return JSON.stringify(e)}function De(e){let t=Ee(Oe(e));return xe.encode(t)}function Oe(e){switch(e.kind){case`scalar`:return{kind:`scalar`,value:e.value};case`text`:return{kind:`text`,value:e.value};case`satori`:return{kind:`satori`,value:e.value};case`binary`:return{kind:`binary`,mime_type:e.mimeType,data:Array.from(e.data)};case`structured`:return{kind:`structured`,value:e.value};case`executable`:return{kind:`executable`,value:e.value}}}function ke(e){if(!e||typeof e!=`object`)return{kind:`scalar`,value:e};let t=e;switch(t.kind){case`scalar`:return{kind:`scalar`,value:t.value};case`text`:return{kind:`text`,value:String(t.value??``)};case`satori`:return{kind:`satori`,value:t.value};case`binary`:{let e=Array.isArray(t.data)?t.data:[];return{kind:`binary`,mimeType:String(t.mime_type||t.mimeType||`application/octet-stream`),data:new Uint8Array(e)}}case`structured`:return{kind:`structured`,value:t.value};case`executable`:return{kind:`executable`,value:t.value};default:return{kind:`structured`,value:e}}}function Ae(e){return{kind:`text`,value:e}}function je(e){return{kind:`structured`,value:e}}function Me(e,t){return{kind:`binary`,mimeType:e,data:t}}var Ne={pending:[`loading`,`error`],loading:[`active`,`error`],active:[`suspended`,`unloading`,`error`],suspended:[`active`,`unloading`,`error`],unloading:[`disposed`,`error`],disposed:[],error:[`disposed`]},Pe=class{id;coeffects;#e=`pending`;#t=[];#n=new r;#r;constructor(e,t){this.id=e,this.coeffects=t}get state(){return this.#e}get disposables(){return this.#n}get guard(){return this.#r}onTransition(e){return this.#t.push(e),()=>{let t=this.#t.indexOf(e);t>=0&&this.#t.splice(t,1)}}async load(e,t){this.#i(`loading`);let n,r,a;if(typeof t==`object`&&t&&(`ctx`in t||`snapshot`in t||`timeoutMs`in t)){let e=t;n=e.snapshot,r=e.ctx,a=e.timeoutMs}else n=t;let o=new i;this.#r=o,o.begin(n??{});try{if(this.coeffects&&this.coeffects.requiredServices&&this.coeffects.requiredServices.length>0){if(!r)throw Error(`FiberLifecycle [${this.id}]: Cordis Context required to resolve coeffects: ${this.coeffects.requiredServices.join(`, `)}`);await _e(this.coeffects,r,a)}await e(o),this.#i(`active`)}catch(e){throw this.#a(e instanceof Error?e:Error(String(e))),o.state===`active`&&await o.rollback(),await this.#n.dispose(),e}}async activate(e){if(this.#e!==`active`)throw Error(`FiberLifecycle: expected state "active", got "${this.#e}"`);try{await e()}catch(e){throw this.#a(e instanceof Error?e:Error(String(e))),this.#r?.state===`active`&&await this.#r.rollback(),await this.#n.dispose(),e}}suspend(){if(this.#e!==`active`)throw Error(`FiberLifecycle: expected state "active" to suspend, got "${this.#e}"`);this.#i(`suspended`)}resume(){if(this.#e!==`suspended`)throw Error(`FiberLifecycle: expected state "suspended" to resume, got "${this.#e}"`);this.#i(`active`)}async unload(e){if(this.#e!==`active`)throw Error(`FiberLifecycle: expected state "active", got "${this.#e}"`);this.#i(`unloading`);try{e&&await e(),this.#r?.state===`active`&&this.#r.commit(),await this.#n.dispose(),this.#i(`disposed`)}catch(e){throw this.#a(e instanceof Error?e:Error(String(e))),this.#r?.state===`active`&&await this.#r.rollback(),await this.#n.dispose(),e}}transition(e){this.#i(e)}async forceDispose(){if(this.#e===`disposed`)return;let e=this.#e;this.#r?.state===`active`&&await this.#r.rollback(),this.#n.disposed||await this.#n.dispose(),this.#e=`disposed`,this.#o(e,`disposed`)}#i(e){let t=this.#e;if(!Ne[t]?.includes(e))throw Error(`FiberLifecycle: invalid transition "${t}" \u2192 "${e}"`);this.#e=e,this.#o(t,e)}#a(e){let t=this.#e;this.#e=`error`,this.#o(t,`error`,e)}#o(e,t,n){let r={fiberId:this.id,from:e,to:t,timestamp:Date.now(),error:n};for(let e of this.#t)try{e(r)}catch{}}},Fe=/^urn:(?:mcard:(?<sector>[a-z_]+)|(?<direct_sector>pcard|vcard)):(?<kind>[a-z_]+)(?::(?<subject>.+))?$/,Ie=Object.freeze({mcard:Object.freeze([`content`,`knowledge`,`schema`,`contract`,`registry`,`record`,`projection`,`derived`,`lifecycle`,`artifact`,`commit`,`design_decision`,`feedback`,`specification`,`sprint_status`,`telemetry`,`test_result`,`function`]),doc:Object.freeze([`vault`,`document`]),pcard:Object.freeze([`program`,`sprint`,`fiber`]),vcard:Object.freeze([`seal`,`execution`,`contract`]),agent:Object.freeze([`root`,`actor`]),node:Object.freeze([`did`,`peer`]),key:Object.freeze([`pub`,`rotate`]),execution:Object.freeze([`record`,`trace`,`migration`]),telemetry:Object.freeze([`event`])}),Le=Object.freeze([`CREATE`,`UPDATE`,`SEAL`,`RELOCATE`,`ROTATE`,`TOMBSTONE`]);function Re(e){if(typeof e!=`string`)return null;let t=Fe.exec(e);if(!t)return null;let n=t.groups,r=n.direct_sector??n.sector,{kind:i,subject:a}=n,o=Ie[r];return Object.freeze({sector:r,kind:i,...a===void 0?{}:{subject:a},handle:e,declared:Array.isArray(o)&&o.includes(i)})}function ze(e){let t=Fe.exec(e)?.groups;return t?t.direct_sector??t.sector??null:null}function Be(e){return Fe.exec(e)?.groups?.kind??null}function Ve(e,t){return ze(e)===t}function He(e){let t=Re(e);return t!==null&&t.declared}function Ue(){let e=[];for(let[t,n]of Object.entries(Ie))for(let r of n)e.push(`${t}:${r}`);return e.sort()}var We=e({basename:()=>$e,default:()=>tt,delimiter:()=>`:`,dirname:()=>Qe,extname:()=>et,isAbsolute:()=>Xe,join:()=>N,normalize:()=>Ye,relative:()=>Ze,resolve:()=>Je,sep:()=>`/`});function Ge(e,t){for(var n=0,r=e.length-1;r>=0;r--){var i=e[r];i===`.`?e.splice(r,1):i===`..`?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;)e.unshift(`..`);return e}var Ke=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,qe=function(e){return Ke.exec(e).slice(1)};function Je(){for(var e=``,t=!1,n=arguments.length-1;n>=-1&&!t;n--){var r=n>=0?arguments[n]:`/`;if(typeof r!=`string`)throw TypeError(`Arguments to path.resolve must be strings`);r&&(e=r+`/`+e,t=r.charAt(0)===`/`)}return e=Ge(nt(e.split(`/`),function(e){return!!e}),!t).join(`/`),(t?`/`:``)+e||`.`}function Ye(e){var t=Xe(e),n=rt(e,-1)===`/`;return e=Ge(nt(e.split(`/`),function(e){return!!e}),!t).join(`/`),!e&&!t&&(e=`.`),e&&n&&(e+=`/`),(t?`/`:``)+e}function Xe(e){return e.charAt(0)===`/`}function N(){return Ye(nt(Array.prototype.slice.call(arguments,0),function(e,t){if(typeof e!=`string`)throw TypeError(`Arguments to path.join must be strings`);return e}).join(`/`))}function Ze(e,t){e=Je(e).substr(1),t=Je(t).substr(1);function n(e){for(var t=0;t<e.length&&e[t]===``;t++);for(var n=e.length-1;n>=0&&e[n]===``;n--);return t>n?[]:e.slice(t,n-t+1)}for(var r=n(e.split(`/`)),i=n(t.split(`/`)),a=Math.min(r.length,i.length),o=a,s=0;s<a;s++)if(r[s]!==i[s]){o=s;break}for(var c=[],s=o;s<r.length;s++)c.push(`..`);return c=c.concat(i.slice(o)),c.join(`/`)}function Qe(e){var t=qe(e),n=t[0],r=t[1];return!n&&!r?`.`:(r&&=r.substr(0,r.length-1),n+r)}function $e(e,t){var n=qe(e)[2];return t&&n.substr(-1*t.length)===t&&(n=n.substr(0,n.length-t.length)),n}function et(e){return qe(e)[3]}var tt={extname:et,basename:$e,dirname:Qe,sep:`/`,delimiter:`:`,relative:Ze,join:N,isAbsolute:Xe,normalize:Ye,resolve:Je};function nt(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r<e.length;r++)t(e[r],r,e)&&n.push(e[r]);return n}var rt=`ab`.substr(-1)===`b`?function(e,t,n){return e.substr(t,n)}:function(e,t,n){return t<0&&(t=e.length+t),e.substr(t,n)},it=2147483647,at=36,ot=1,st=26,ct=38,lt=700,ut=72,dt=128,ft=`-`,pt=/[^\x20-\x7E]/,mt=/[\x2E\u3002\uFF0E\uFF61]/g,ht={overflow:`Overflow: input needs wider integers to process`,"not-basic":`Illegal input >= 0x80 (not a basic code point)`,"invalid-input":`Invalid input`},gt=at-ot,_t=Math.floor,vt=String.fromCharCode;function yt(e){throw RangeError(ht[e])}function bt(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function xt(e,t){var n=e.split(`@`),r=``;n.length>1&&(r=n[0]+`@`,e=n[1]),e=e.replace(mt,`.`);var i=bt(e.split(`.`),t).join(`.`);return r+i}function St(e){for(var t=[],n=0,r=e.length,i,a;n<r;)i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<r?(a=e.charCodeAt(n++),(a&64512)==56320?t.push(((i&1023)<<10)+(a&1023)+65536):(t.push(i),n--)):t.push(i);return t}function Ct(e,t){return e+22+75*(e<26)-((t!=0)<<5)}function wt(e,t,n){var r=0;for(e=n?_t(e/lt):e>>1,e+=_t(e/t);e>gt*st>>1;r+=at)e=_t(e/gt);return _t(r+(gt+1)*e/(e+ct))}function Tt(e){var t,n,r,i,a,o,s,c,l,u,d,f=[],p,m,h,g;for(e=St(e),p=e.length,t=dt,n=0,a=ut,o=0;o<p;++o)d=e[o],d<128&&f.push(vt(d));for(r=i=f.length,i&&f.push(ft);r<p;){for(s=it,o=0;o<p;++o)d=e[o],d>=t&&d<s&&(s=d);for(m=r+1,s-t>_t((it-n)/m)&&yt(`overflow`),n+=(s-t)*m,t=s,o=0;o<p;++o)if(d=e[o],d<t&&++n>it&&yt(`overflow`),d==t){for(c=n,l=at;u=l<=a?ot:l>=a+st?st:l-a,!(c<u);l+=at)g=c-u,h=at-u,f.push(vt(Ct(u+g%h,0))),c=_t(g/h);f.push(vt(Ct(c,0))),a=wt(n,m,r==i),n=0,++r}++n,++t}return f.join(``)}function Et(e){return xt(e,function(e){return pt.test(e)?`xn--`+Tt(e):e})}function Dt(){throw Error(`setTimeout has not been defined`)}function Ot(){throw Error(`clearTimeout has not been defined`)}var kt=Dt,At=Ot;typeof globalThis.setTimeout==`function`&&(kt=setTimeout),typeof globalThis.clearTimeout==`function`&&(At=clearTimeout);function jt(e){if(kt===setTimeout)return setTimeout(e,0);if((kt===Dt||!kt)&&setTimeout)return kt=setTimeout,setTimeout(e,0);try{return kt(e,0)}catch{try{return kt.call(null,e,0)}catch{return kt.call(this,e,0)}}}function Mt(e){if(At===clearTimeout)return clearTimeout(e);if((At===Ot||!At)&&clearTimeout)return At=clearTimeout,clearTimeout(e);try{return At(e)}catch{try{return At.call(null,e)}catch{return At.call(this,e)}}}var Nt=[],Pt=!1,Ft,It=-1;function Lt(){Pt&&Ft&&(Pt=!1,Ft.length?Nt=Ft.concat(Nt):It=-1,Nt.length&&Rt())}function Rt(){if(!Pt){var e=jt(Lt);Pt=!0;for(var t=Nt.length;t;){for(Ft=Nt,Nt=[];++It<t;)Ft&&Ft[It].run();It=-1,t=Nt.length}Ft=null,Pt=!1,Mt(e)}}function zt(e){var t=Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];Nt.push(new Bt(e,t)),Nt.length===1&&!Pt&&jt(Rt)}function Bt(e,t){this.fun=e,this.array=t}Bt.prototype.run=function(){this.fun.apply(null,this.array)};var Vt=`browser`,Ht=`browser`,Ut={},Wt=[],Gt={},Kt={},qt={};function Jt(){}var Yt=Jt,Xt=Jt,Zt=Jt,Qt=Jt,$t=Jt,en=Jt,tn=Jt;function nn(e){throw Error(`process.binding is not supported`)}function rn(){return`/`}function an(e){throw Error(`process.chdir is not supported`)}function on(){return 0}var sn=globalThis.performance||{},cn=sn.now||sn.mozNow||sn.msNow||sn.oNow||sn.webkitNow||function(){return new Date().getTime()};function ln(e){var t=cn.call(sn)*.001,n=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(n-=e[0],r-=e[1],r<0&&(n--,r+=1e9)),[n,r]}var un=new Date;function dn(){return(new Date-un)/1e3}var fn={nextTick:zt,title:Vt,browser:!0,env:Ut,argv:Wt,version:``,versions:Gt,on:Yt,addListener:Xt,once:Zt,off:Qt,removeListener:$t,removeAllListeners:en,emit:tn,binding:nn,cwd:rn,chdir:an,umask:on,hrtime:ln,platform:Ht,release:Kt,config:qt,uptime:dn},pn=typeof Object.create==`function`?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e},mn=/%[sdj%]/g;function hn(e){if(!Fn(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(bn(arguments[n]));return t.join(` `)}for(var n=1,r=arguments,i=r.length,a=String(e).replace(mn,function(e){if(e===`%%`)return`%`;if(n>=i)return e;switch(e){case`%s`:return String(r[n++]);case`%d`:return Number(r[n++]);case`%j`:try{return JSON.stringify(r[n++])}catch{return`[Circular]`}default:return e}}),o=r[n];n<i;o=r[++n])Mn(o)||!Rn(o)?a+=` `+o:a+=` `+bn(o);return a}function gn(e,t){if(In(globalThis.process))return function(){return gn(e,t).apply(this,arguments)};if(fn.noDeprecation===!0)return e;var n=!1;function r(){if(!n){if(fn.throwDeprecation)throw Error(t);fn.traceDeprecation?console.trace(t):console.error(t),n=!0}return e.apply(this,arguments)}return r}var _n={},vn;function yn(e){if(In(vn)&&(vn=fn.env.NODE_DEBUG||``),e=e.toUpperCase(),!_n[e]){if(RegExp(`\\b`+e+`\\b`,`i`).test(vn)){var t=0;_n[e]=function(){var n=hn.apply(null,arguments);console.error(`%s %d: %s`,e,t,n)}}else _n[e]=function(){}}return _n[e]}function bn(e,t){var n={seen:[],stylize:Sn};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),jn(t)?n.showHidden=t:t&&Un(n,t),In(n.showHidden)&&(n.showHidden=!1),In(n.depth)&&(n.depth=2),In(n.colors)&&(n.colors=!1),In(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=xn),wn(n,e,n.depth)}bn.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},bn.styles={special:`cyan`,number:`yellow`,boolean:`yellow`,undefined:`grey`,null:`bold`,string:`green`,date:`magenta`,regexp:`red`};function xn(e,t){var n=bn.styles[t];return n?`\x1B[`+bn.colors[n][0]+`m`+e+`\x1B[`+bn.colors[n][1]+`m`:e}function Sn(e,t){return e}function Cn(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function wn(e,t,n){if(e.customInspect&&t&&Vn(t.inspect)&&t.inspect!==bn&&!(t.constructor&&t.constructor.prototype===t)){var r=t.inspect(n,e);return Fn(r)||(r=wn(e,r,n)),r}var i=Tn(e,t);if(i)return i;var a=Object.keys(t),o=Cn(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),Bn(t)&&(a.indexOf(`message`)>=0||a.indexOf(`description`)>=0))return En(t);if(a.length===0){if(Vn(t)){var s=t.name?`: `+t.name:``;return e.stylize(`[Function`+s+`]`,`special`)}if(Ln(t))return e.stylize(RegExp.prototype.toString.call(t),`regexp`);if(zn(t))return e.stylize(Date.prototype.toString.call(t),`date`);if(Bn(t))return En(t)}var c=``,l=!1,u=[`{`,`}`];if(An(t)&&(l=!0,u=[`[`,`]`]),Vn(t)&&(c=` [Function`+(t.name?`: `+t.name:``)+`]`),Ln(t)&&(c=` `+RegExp.prototype.toString.call(t)),zn(t)&&(c=` `+Date.prototype.toUTCString.call(t)),Bn(t)&&(c=` `+En(t)),a.length===0&&(!l||t.length==0))return u[0]+c+u[1];if(n<0)return Ln(t)?e.stylize(RegExp.prototype.toString.call(t),`regexp`):e.stylize(`[Object]`,`special`);e.seen.push(t);var d=l?Dn(e,t,n,o,a):a.map(function(r){return On(e,t,n,o,r,l)});return e.seen.pop(),kn(d,c,u)}function Tn(e,t){if(In(t))return e.stylize(`undefined`,`undefined`);if(Fn(t)){var n=`'`+JSON.stringify(t).replace(/^"|"$/g,``).replace(/'/g,`\\'`).replace(/\\"/g,`"`)+`'`;return e.stylize(n,`string`)}if(Pn(t))return e.stylize(``+t,`number`);if(jn(t))return e.stylize(``+t,`boolean`);if(Mn(t))return e.stylize(`null`,`null`)}function En(e){return`[`+Error.prototype.toString.call(e)+`]`}function Dn(e,t,n,r,i){for(var a=[],o=0,s=t.length;o<s;++o)Wn(t,String(o))?a.push(On(e,t,n,r,String(o),!0)):a.push(``);return i.forEach(function(i){i.match(/^\d+$/)||a.push(On(e,t,n,r,i,!0))}),a}function On(e,t,n,r,i,a){var o,s,c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]};if(c.get?s=c.set?e.stylize(`[Getter/Setter]`,`special`):e.stylize(`[Getter]`,`special`):c.set&&(s=e.stylize(`[Setter]`,`special`)),Wn(r,i)||(o=`[`+i+`]`),s||(e.seen.indexOf(c.value)<0?(s=Mn(n)?wn(e,c.value,null):wn(e,c.value,n-1),s.indexOf(`
4
+ `)>-1&&(s=a?s.split(`
5
+ `).map(function(e){return` `+e}).join(`
6
+ `).substr(2):`
7
+ `+s.split(`
8
+ `).map(function(e){return` `+e}).join(`
9
+ `))):s=e.stylize(`[Circular]`,`special`)),In(o)){if(a&&i.match(/^\d+$/))return s;o=JSON.stringify(``+i),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,`name`)):(o=o.replace(/'/g,`\\'`).replace(/\\"/g,`"`).replace(/(^"|"$)/g,`'`),o=e.stylize(o,`string`))}return o+`: `+s}function kn(e,t,n){var r=0;return e.reduce(function(e,t){return r++,t.indexOf(`
10
+ `)>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,``).length+1},0)>60?n[0]+(t===``?``:t+`
11
+ `)+` `+e.join(`,
12
+ `)+` `+n[1]:n[0]+t+` `+e.join(`, `)+` `+n[1]}function An(e){return Array.isArray(e)}function jn(e){return typeof e==`boolean`}function Mn(e){return e===null}function Nn(e){return e==null}function Pn(e){return typeof e==`number`}function Fn(e){return typeof e==`string`}function In(e){return e===void 0}function Ln(e){return Rn(e)&&Hn(e)===`[object RegExp]`}function Rn(e){return typeof e==`object`&&!!e}function zn(e){return Rn(e)&&Hn(e)===`[object Date]`}function Bn(e){return Rn(e)&&(Hn(e)===`[object Error]`||e instanceof Error)}function Vn(e){return typeof e==`function`}function Hn(e){return Object.prototype.toString.call(e)}function Un(e,t){if(!t||!Rn(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}function Wn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Gn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var Kn=Array.isArray||function(e){return Object.prototype.toString.call(e)===`[object Array]`};function qn(e){switch(typeof e){case`string`:return e;case`boolean`:return e?`true`:`false`;case`number`:return isFinite(e)?e:``;default:return``}}function Jn(e,t,n,r){return t||=`&`,n||=`=`,e===null&&(e=void 0),typeof e==`object`?Yn(Xn(e),function(r){var i=encodeURIComponent(qn(r))+n;return Kn(e[r])?Yn(e[r],function(e){return i+encodeURIComponent(qn(e))}).join(t):i+encodeURIComponent(qn(e[r]))}).join(t):r?encodeURIComponent(qn(r))+n+encodeURIComponent(qn(e)):``}function Yn(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var Xn=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t};function Zn(e,t,n,r){t||=`&`,n||=`=`;var i={};if(typeof e!=`string`||e.length===0)return i;var a=/\+/g;e=e.split(t);var o=1e3;r&&typeof r.maxKeys==`number`&&(o=r.maxKeys);var s=e.length;o>0&&s>o&&(s=o);for(var c=0;c<s;++c){var l=e[c].replace(a,`%20`),u=l.indexOf(n),d,f,p,m;u>=0?(d=l.substr(0,u),f=l.substr(u+1)):(d=l,f=``),p=decodeURIComponent(d),m=decodeURIComponent(f),Gn(i,p)?Kn(i[p])?i[p].push(m):i[p]=[i[p],m]:i[p]=m}return i}var Qn={parse:fr,resolve:gr,resolveObject:_r,format:mr,Url:$n};function $n(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var er=/^([a-z0-9.+-]+:)/i,tr=/:[0-9]*$/,nr=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,rr=[`'`,`{`,`}`,`|`,`\\`,`^`,"`",`<`,`>`,`"`,"`",` `,`\r`,`
13
+ `,` `],ir=[`%`,`/`,`?`,`;`,`#`].concat(rr),ar=[`/`,`?`,`#`],or=255,sr=/^[+a-z0-9A-Z_-]{0,63}$/,cr=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,lr={javascript:!0,"javascript:":!0},ur={javascript:!0,"javascript:":!0},dr={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function fr(e,t,n){if(e&&Rn(e)&&e instanceof $n)return e;var r=new $n;return r.parse(e,t,n),r}$n.prototype.parse=function(e,t,n){return pr(this,e,t,n)};function pr(e,t,n,r){if(!Fn(t))throw TypeError(`Parameter 'url' must be a string, not `+typeof t);var i=t.indexOf(`?`),a=i!==-1&&i<t.indexOf(`#`)?`?`:`#`,o=t.split(a);o[0]=o[0].replace(/\\/g,`/`),t=o.join(a);var s=t;if(s=s.trim(),!r&&t.split(`#`).length===1){var c=nr.exec(s);if(c)return e.path=s,e.href=s,e.pathname=c[1],c[2]?(e.search=c[2],e.query=n?Zn(e.search.substr(1)):e.search.substr(1)):n&&(e.search=``,e.query={}),e}var l=er.exec(s);if(l){l=l[0];var u=l.toLowerCase();e.protocol=u,s=s.substr(l.length)}if(r||l||s.match(/^\/\/[^@\/]+@[^@\/]+/)){var d=s.substr(0,2)===`//`;d&&!(l&&ur[l])&&(s=s.substr(2),e.slashes=!0)}var f,p,m,h;if(!ur[l]&&(d||l&&!dr[l])){var g=-1;for(f=0;f<ar.length;f++)p=s.indexOf(ar[f]),p!==-1&&(g===-1||p<g)&&(g=p);var _,v=g===-1?s.lastIndexOf(`@`):s.lastIndexOf(`@`,g);for(v!==-1&&(_=s.slice(0,v),s=s.slice(v+1),e.auth=decodeURIComponent(_)),g=-1,f=0;f<ir.length;f++)p=s.indexOf(ir[f]),p!==-1&&(g===-1||p<g)&&(g=p);g===-1&&(g=s.length),e.host=s.slice(0,g),s=s.slice(g),vr(e),e.hostname=e.hostname||``;var y=e.hostname[0]===`[`&&e.hostname[e.hostname.length-1]===`]`;if(!y){var b=e.hostname.split(/\./);for(f=0,m=b.length;f<m;f++){var x=b[f];if(x&&!x.match(sr)){for(var S=``,C=0,w=x.length;C<w;C++)x.charCodeAt(C)>127?S+=`x`:S+=x[C];if(!S.match(sr)){var T=b.slice(0,f),E=b.slice(f+1),D=x.match(cr);D&&(T.push(D[1]),E.unshift(D[2])),E.length&&(s=`/`+E.join(`.`)+s),e.hostname=T.join(`.`);break}}}}e.hostname=e.hostname.length>or?``:e.hostname.toLowerCase(),y||(e.hostname=Et(e.hostname)),h=e.port?`:`+e.port:``,e.host=(e.hostname||``)+h,e.href+=e.host,y&&(e.hostname=e.hostname.substr(1,e.hostname.length-2),s[0]!==`/`&&(s=`/`+s))}if(!lr[u])for(f=0,m=rr.length;f<m;f++){var O=rr[f];if(s.indexOf(O)!==-1){var ee=encodeURIComponent(O);ee===O&&(ee=escape(O)),s=s.split(O).join(ee)}}var te=s.indexOf(`#`);te!==-1&&(e.hash=s.substr(te),s=s.slice(0,te));var ne=s.indexOf(`?`);if(ne===-1?n&&(e.search=``,e.query={}):(e.search=s.substr(ne),e.query=s.substr(ne+1),n&&(e.query=Zn(e.query)),s=s.slice(0,ne)),s&&(e.pathname=s),dr[u]&&e.hostname&&!e.pathname&&(e.pathname=`/`),e.pathname||e.search){h=e.pathname||``;var re=e.search||``;e.path=h+re}return e.href=hr(e),e}function mr(e){return Fn(e)&&(e=pr({},e)),hr(e)}function hr(e){var t=e.auth||``;t&&(t=encodeURIComponent(t),t=t.replace(/%3A/i,`:`),t+=`@`);var n=e.protocol||``,r=e.pathname||``,i=e.hash||``,a=!1,o=``;e.host?a=t+e.host:e.hostname&&(a=t+(e.hostname.indexOf(`:`)===-1?e.hostname:`[`+this.hostname+`]`),e.port&&(a+=`:`+e.port)),e.query&&Rn(e.query)&&Object.keys(e.query).length&&(o=Jn(e.query));var s=e.search||o&&`?`+o||``;return n&&n.substr(-1)!==`:`&&(n+=`:`),e.slashes||(!n||dr[n])&&a!==!1?(a=`//`+(a||``),r&&r.charAt(0)!==`/`&&(r=`/`+r)):a||=``,i&&i.charAt(0)!==`#`&&(i=`#`+i),s&&s.charAt(0)!==`?`&&(s=`?`+s),r=r.replace(/[?#]/g,function(e){return encodeURIComponent(e)}),s=s.replace(`#`,`%23`),n+a+r+s+i}$n.prototype.format=function(){return hr(this)};function gr(e,t){return fr(e,!1,!0).resolve(t)}$n.prototype.resolve=function(e){return this.resolveObject(fr(e,!1,!0)).format()};function _r(e,t){return e?fr(e,!1,!0).resolveObject(t):t}$n.prototype.resolveObject=function(e){if(Fn(e)){var t=new $n;t.parse(e,!1,!0),e=t}for(var n=new $n,r=Object.keys(this),i=0;i<r.length;i++){var a=r[i];n[a]=this[a]}if(n.hash=e.hash,e.href===``)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var o=Object.keys(e),s=0;s<o.length;s++){var c=o[s];c!==`protocol`&&(n[c]=e[c])}return dr[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname=`/`),n.href=n.format(),n}var l;if(e.protocol&&e.protocol!==n.protocol){if(!dr[e.protocol]){for(var u=Object.keys(e),d=0;d<u.length;d++){var f=u[d];n[f]=e[f]}return n.href=n.format(),n}if(n.protocol=e.protocol,!e.host&&!ur[e.protocol]){for(l=(e.pathname||``).split(`/`);l.length&&!(e.host=l.shift()););e.host||(e.host=``),e.hostname||(e.hostname=``),l[0]!==``&&l.unshift(``),l.length<2&&l.unshift(``),n.pathname=l.join(`/`)}else n.pathname=e.pathname;return n.search=e.search,n.query=e.query,n.host=e.host||``,n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,(n.pathname||n.search)&&(n.path=(n.pathname||``)+(n.search||``)),n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var p=n.pathname&&n.pathname.charAt(0)===`/`,m=e.host||e.pathname&&e.pathname.charAt(0)===`/`,h=m||p||n.host&&e.pathname,g=h,_=n.pathname&&n.pathname.split(`/`)||[],v=n.protocol&&!dr[n.protocol];l=e.pathname&&e.pathname.split(`/`)||[],v&&(n.hostname=``,n.port=null,n.host&&(_[0]===``?_[0]=n.host:_.unshift(n.host)),n.host=``,e.protocol&&(e.hostname=null,e.port=null,e.host&&(l[0]===``?l[0]=e.host:l.unshift(e.host)),e.host=null),h&&=l[0]===``||_[0]===``);var y;if(m)n.host=e.host||e.host===``?e.host:n.host,n.hostname=e.hostname||e.hostname===``?e.hostname:n.hostname,n.search=e.search,n.query=e.query,_=l;else if(l.length)_||=[],_.pop(),_=_.concat(l),n.search=e.search,n.query=e.query;else if(!Nn(e.search))return v&&(n.hostname=n.host=_.shift(),y=n.host&&n.host.indexOf(`@`)>0?n.host.split(`@`):!1,y&&(n.auth=y.shift(),n.host=n.hostname=y.shift())),n.search=e.search,n.query=e.query,(!Mn(n.pathname)||!Mn(n.search))&&(n.path=(n.pathname?n.pathname:``)+(n.search?n.search:``)),n.href=n.format(),n;if(!_.length)return n.pathname=null,n.path=n.search?`/`+n.search:null,n.href=n.format(),n;for(var b=_.slice(-1)[0],x=(n.host||e.host||_.length>1)&&(b===`.`||b===`..`)||b===``,S=0,C=_.length;C>=0;C--)b=_[C],b===`.`?_.splice(C,1):b===`..`?(_.splice(C,1),S++):S&&(_.splice(C,1),S--);if(!h&&!g)for(;S--;)_.unshift(`..`);h&&_[0]!==``&&(!_[0]||_[0].charAt(0)!==`/`)&&_.unshift(``),x&&_.join(`/`).substr(-1)!==`/`&&_.push(``);var w=_[0]===``||_[0]&&_[0].charAt(0)===`/`;return v&&(n.hostname=n.host=w?``:_.length?_.shift():``,y=n.host&&n.host.indexOf(`@`)>0?n.host.split(`@`):!1,y&&(n.auth=y.shift(),n.host=n.hostname=y.shift())),h||=n.host&&_.length,h&&!w&&_.unshift(``),_.length?n.pathname=_.join(`/`):(n.pathname=null,n.path=null),(!Mn(n.pathname)||!Mn(n.search))&&(n.path=(n.pathname?n.pathname:``)+(n.search?n.search:``)),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},$n.prototype.parseHost=function(){return vr(this)};function vr(e){var t=e.host,n=tr.exec(t);n&&(n=n[0],n!==`:`&&(e.port=n.substr(1)),t=t.substr(0,t.length-n.length)),t&&(e.hostname=t)}var yr=typeof globalThis<`u`&&globalThis.URL?globalThis.URL:class{};typeof globalThis<`u`&&globalThis.URLSearchParams&&globalThis.URLSearchParams;function br(e){return typeof e==`string`?e.replace(/^file:\/\//,``):``}({...Qn});var xr=Object.defineProperty,Sr=(e=>t===void 0?typeof Proxy<`u`?new Proxy(e,{get:(e,n)=>(t===void 0?e:t)[n]}):e:t)(function(e){if(t!==void 0)return t.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),Cr=(e,t)=>{for(var n in t)xr(e,n,{get:t[n],enumerable:!0})},wr=tt.dirname(br(import.meta.url)),Tr=`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`,Er={};for(let e=0;e<Tr.length;e++)Er[Tr[e]]=e;function Dr(e){if(e.length===0)return``;let t=0;for(;t<e.length&&e[t]===0;)t++;let n=[];for(let r=t;r<e.length;r++){let t=e[r];for(let e=0;e<n.length;e++)t+=n[e]<<8,n[e]=t%58,t=t/58|0;for(;t>0;)n.push(t%58),t=t/58|0}let r=`1`.repeat(t);for(let e=n.length-1;e>=0;e--)r+=Tr[n[e]];return r}function Or(e){if(!e)return new Uint8Array;let t=0;for(;t<e.length&&e[t]===`1`;)t++;let n=[];for(let r=t;r<e.length;r++){let t=e[r],i=Er[t];if(i===void 0)throw Error(`Invalid Base58 character: ${t}`);let a=i;for(let e=0;e<n.length;e++)a+=n[e]*58,n[e]=a&255,a>>=8;for(;a>0;)n.push(a&255),a>>=8}let r=new Uint8Array(t+n.length);for(let e=0;e<t;e++)r[e]=0;for(let e=0;e<n.length;e++)r[t+e]=n[n.length-1-e];return r}function kr(e){let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return t}function Ar(e){let t=e.length%2==0?e:`0${e}`,n=t.length/2,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=parseInt(t.substring(e*2,e*2+2),16);return r}function jr(e=32){try{if(typeof process<`u`&&process.versions&&process.versions.node)return Sr(`crypto`).randomBytes(e).toString(`hex`)}catch{}if(typeof globalThis<`u`&&globalThis.crypto&&globalThis.crypto.getRandomValues){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),kr(t)}let t=``;for(let n=0;n<e*2;n++)t+=Math.floor(Math.random()*16).toString(16);return t}var Mr=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),Nr=new Uint8Array([48,42,48,5,6,3,43,101,112,3,33,0]),Pr=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Fr=new Uint8Array([48,42,48,5,6,3,43,101,110,3,33,0]);function Ir(e){return typeof Buffer<`u`&&typeof Buffer.from==`function`?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}var Lr=[`did`,`kid`,`sig`];function Rr(e){return Lr.includes(e)}var zr=/^[a-z][a-z0-9-]*$/;function Br(e){return e.length>0&&!e.includes(`|`)}function Vr(e,t,n){let r={};for(let i of e){let e=i.trim();if(!e)continue;let a=t===`either`?e.indexOf(`=`)===-1?e.indexOf(`:`):e.indexOf(`=`):e.indexOf(t);if(a===-1)return{error:`Extension segment lacks a '${t===`either`?`=`:t}' separator: "${e}"`};let o=e.slice(0,a).trim().toLowerCase(),s=e.slice(a+1).trim();if(!zr.test(o))return{error:`Invalid extension key: "${o}"`};if(n&&!Rr(o))return{error:`Unregistered extension key: "${o}" (registered: ${Lr.join(`, `)})`};if(o in r)return{error:`Duplicate extension key: "${o}"`};if(!Br(s))return{error:`Empty or delimiter-bearing extension value for "${o}"`};r[o]=s}return{extensions:r}}function Hr(e){if(typeof e!=`string`||e.trim().length===0)return{kind:`malformed`,raw:String(e),reason:`Empty or non-string g_time`};let t=e.trim();if(t.includes(`|`)){let n=t.split(`|`);if(n.length<3)return{kind:`malformed`,raw:e,reason:`Pipe form requires at least 3 fields, found ${n.length}`};let r=(n[0]??``).trim().toLowerCase();if(!h(r))return{kind:`malformed`,raw:e,reason:`Unsupported algorithm in coordinate a: "${n[0]}"`};let i=(n[1]??``).trim();if(isNaN(Date.parse(i)))return{kind:`malformed`,raw:e,reason:`Invalid timestamp in coordinate t: "${n[1]}"`};let a=(n[2]??``).trim();if(a.includes(`=`))return{kind:`malformed`,raw:e,reason:`Coordinate c must be a locale, not an extension: "${a}"`};let o=Vr(n.slice(3),`=`,!0);return`error`in o?{kind:`malformed`,raw:e,reason:o.error}:{kind:`declared`,form:`pipe`,algorithm:r,timestamp:i,locale:a,extensions:o.extensions,raw:e}}if(t.startsWith(`a:`)){let n={};for(let r of t.split(`;`)){let t=r.trim();if(!t)continue;let i=t.indexOf(`:`);if(i===-1)return{kind:`malformed`,raw:e,reason:`Segment lacks key:value separator: "${t}"`};let a=t.slice(0,i).trim(),o=t.slice(i+1).trim();if(!a)return{kind:`malformed`,raw:e,reason:`Empty key in segment: "${t}"`};if(a in n)return{kind:`malformed`,raw:e,reason:`Duplicate key in g_time: "${a}"`};n[a]=o}let r=n.a;if(!r||!h(r))return{kind:`malformed`,raw:e,reason:`Unsupported or missing algorithm 'a': "${r}"`};let i=n.t;if(!i||isNaN(Date.parse(i)))return{kind:`malformed`,raw:e,reason:`Invalid or missing timestamp 't': "${i}"`};let a=n.c??``,o={};for(let[e,t]of Object.entries(n))e!==`a`&&e!==`t`&&e!==`c`&&(o[e]=t);return{kind:`declared`,form:`legacy-ts`,algorithm:r,timestamp:i,locale:a,extensions:o,raw:e}}return isNaN(Date.parse(t))?{kind:`malformed`,raw:e,reason:`Unrecognised g_time shape`}:{kind:`legacy`,timestamp:t,raw:e}}function Ur(e,t,n,r){let i=`${e}|${t}|${n??``}`;if(r){let e=Object.keys(r).filter(e=>e!==`sig`||r[e]).filter(e=>r[e]!==void 0&&r[e]!==``).sort();for(let t of e)i+=`|${t}=${r[t]}`}return i}function Wr(e,t={}){return Ur(e,t.timestamp||new Date().toISOString(),t.locale??t.nonce??`UTC`,t.extensions)}function Gr(){return function(){return{}}}var Kr=e({constants:()=>fi,default:()=>pi,exists:()=>Jr,existsSync:()=>qr,mkdir:()=>ei,mkdirSync:()=>$r,mkdtemp:()=>ui,mkdtempSync:()=>li,promises:()=>di,readFile:()=>Xr,readFileSync:()=>Yr,readdir:()=>ii,readdirSync:()=>ri,rm:()=>ci,rmSync:()=>si,stat:()=>ni,statSync:()=>ti,unlink:()=>oi,unlinkSync:()=>ai,writeFile:()=>Qr,writeFileSync:()=>Zr});function qr(){return!1}function Jr(e,t){t&&t(!1)}function Yr(){return``}function Xr(e,t,n){let r=typeof t==`function`?t:n;r&&r(null,``)}function Zr(){}function Qr(e,t,n,r){let i=typeof n==`function`?n:r;i&&i(null)}function $r(){}function ei(e,t,n){let r=typeof t==`function`?t:n;r&&r(null)}function ti(){return{isDirectory:()=>!1,isFile:()=>!1,size:0,mtime:new Date}}function ni(e,t){t&&t(null,{isDirectory:()=>!1,isFile:()=>!1,size:0,mtime:new Date})}function ri(){return[]}function ii(e,t){t&&t(null,[])}function ai(){}function oi(e,t){t&&t(null)}function si(){}function ci(e,t,n){let r=typeof t==`function`?t:n;r&&r(null)}function li(e=``){return e?`${e}_tmp`:`/tmp`}function ui(e,t,n){let r=typeof t==`function`?t:n,i=e?`${e}_tmp`:`/tmp`;r&&r(null,i)}var di={readFile:async()=>``,writeFile:async()=>{},stat:async()=>({isDirectory:()=>!1,isFile:()=>!1,size:0,mtime:new Date}),readdir:async()=>[],mkdir:async()=>{},unlink:async()=>{},rm:async()=>{},mkdtemp:async(e=``)=>e?`${e}_tmp`:`/tmp`},fi={F_OK:0,R_OK:4,W_OK:2,X_OK:1},pi={existsSync:qr,exists:Jr,readFileSync:Yr,readFile:Xr,writeFileSync:Zr,writeFile:Qr,mkdirSync:$r,mkdir:ei,statSync:ti,stat:ni,readdirSync:ri,readdir:ii,unlinkSync:ai,unlink:oi,rmSync:si,rm:ci,mkdtempSync:li,mkdtemp:ui,promises:di,constants:fi},mi=`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`,hi=Array(128).fill(-1);for(let e=0;e<mi.length;e++)hi[mi.charCodeAt(e)]=e;function gi(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(gi);let t={},n=Object.keys(e).sort();for(let r of n)t[r]=gi(e[r]);return t}function _i(e){let t=gi(e);return JSON.stringify(t)}var vi=new TextEncoder;function yi(e,t={}){let n=typeof e==`string`?vi.encode(e):new Uint8Array(e),r=ue(t.algorithm),i={...t.extensions||{}},a=t.authorDid||t.did||(typeof process<`u`?{}.CLM_AUTHOR_DID:void 0);a&&(i.did=a);let o=Wr(r,{timestamp:t.timestamp,locale:t.locale??t.nonce,extensions:Object.keys(i).length>0?i:void 0});return{hash:de(r,n),content:n,gTime:o}}function bi(e,t,n){let r,i,a;e instanceof Uint8Array?(r=e,i=t,a=n):(r=e.content,i=e.hash,a=e.gTime);let o=Hr(a);if(o.kind===`malformed`)return{status:`malformed`,reason:o.reason};let s=i.includes(`:`)?i.split(`:`)[1].toLowerCase():i.toLowerCase();if(o.kind===`declared`){let e=i.includes(`:`)?i.slice(0,i.indexOf(`:`)).toLowerCase():void 0,t=de(o.algorithm,r).toLowerCase();return e&&e!==o.algorithm?{status:`declared-mismatch`,declaredAlgo:o.algorithm,expectedHex:s,computedHex:t}:s===t?{status:`declared-ok`,algorithm:o.algorithm,qualifiedHash:`${o.algorithm}:${t}`}:{status:`declared-mismatch`,declaredAlgo:o.algorithm,expectedHex:s,computedHex:t}}let c=m.filter(e=>de(e,r).toLowerCase()===s);if(c.length===1){let e=c[0];return{status:`legacy-classified`,algorithm:e,qualifiedHash:`${e}:${s}`,evidence:`recomputation`}}return c.length>1?{status:`legacy-ambiguous`,algorithms:[...c],expectedHex:s}:{status:`legacy-unclassified`,expectedHex:s}}var xi=class extends Error{constructor(e){super(e),this.name=`UnqualifiedRecordError`}};function Si(e,t,n){return e instanceof A?e:typeof e==`object`&&e?e.hash instanceof A?e.hash:Ci(typeof e.hash==`string`?e.hash:typeof e.hash?.asHex==`function`?e.hash.asHex():String(e.hash??``),e.gTime??e.g_time??t??``,n):Ci(e,t??``,n)}function Ci(e,t,n){let r=Hr(t);if(r.kind===`declared`){let t=e.includes(`:`)?e.split(`:`)[1]:e;return A.fromHex(t,r.algorithm)}if(n){let t=e.includes(`:`)?e.split(`:`)[1]:e;return A.fromHex(t,n)}if(e.includes(`:`))return A.fromPrefixed(e);throw new xi(`qualify: cannot resolve the algorithm for a bare digest with ${r.kind===`legacy`?`a legacy (algorithm-free) g_time`:`a malformed g_time`}. Supply an explicit algorithm from producer provenance, or classify by recomputation with verifyRecord().`)}function wi(e){try{let t=new TextDecoder(`utf-8`,{fatal:!0}).decode(e);if(!t.startsWith(`{`)||!t.endsWith(`}`))return null;let n=JSON.parse(t);return n&&typeof n==`object`&&!Array.isArray(n)&&`payload`in n&&[`uri`,`hash`,`author`,`sequence`,`metadata`,`dialect`].some(e=>e in n)?{dialect:typeof n.dialect==`string`?n.dialect:void 0,uri:typeof n.uri==`string`?n.uri:void 0,hash:typeof n.hash==`string`?n.hash:void 0,payload:n.payload,metadata:n.metadata&&typeof n.metadata==`object`?n.metadata:void 0,author:typeof n.author==`string`?n.author:void 0,sequence:typeof n.sequence==`number`?n.sequence:void 0}:null}catch{return null}}function Ti(e){if(typeof e!=`string`)return!1;let t=e.indexOf(`:`);if(t<=0)return!1;let n=e.slice(0,t),r=e.slice(t+1);return h(n)?/^[0-9a-f]+$/i.test(r):!1}function P(e){return typeof e==`string`?e.replace(/^mcard:/,``).replace(/^\/+/,``):``}function Ei(e){if(!e||typeof e!=`object`)throw Error(`Transition payload must be an object`);if(!Le.includes(e.kind))throw Error(`Invalid transition kind: "${e.kind}". Must be one of: ${Le.join(`, `)}`);if(!e.handle||typeof e.handle!=`string`)throw Error(`Transition handle must be a non-empty canonical string`);if(!e.author||typeof e.author!=`string`)throw Error(`Transition author must be a non-empty DID string`);if(e.from!==null&&e.from!==void 0&&!Ti(e.from))throw Error(`Transition "from" must be a qualified hash (e.g. "blake3:<hex>"), got: "${e.from}"`);if(e.to!==null&&e.to!==void 0&&!Ti(e.to))throw Error(`Transition "to" must be a qualified hash (e.g. "blake3:<hex>"), got: "${e.to}"`);if(e.meta!==null&&e.meta!==void 0&&!Ti(e.meta))throw Error(`Transition "meta" must be a qualified hash (e.g. "blake3:<hex>"), got: "${e.meta}"`);if(e.kind===`CREATE`&&e.from!==null&&e.from!==void 0)throw Error(`CREATE transition must have from=null`);if(e.kind===`TOMBSTONE`&&e.to!==null&&e.to!==void 0)throw Error(`TOMBSTONE transition must have to=null`);if(e.kind===`RELOCATE`&&(!e.toHandle||typeof e.toHandle!=`string`))throw Error(`RELOCATE transition requires toHandle destination handle`)}function Di(e,t={}){return Ei(e),yi(new TextEncoder().encode(_i(e)),{...t,did:e.author})}function Oi(e){let t=bi(e);if(t.status===`malformed`||t.status===`declared-mismatch`)throw Error(`Transition record verification failed: status=${t.status}`);let n=new TextDecoder().decode(e.content),r;try{r=JSON.parse(n)}catch(e){throw Error(`Failed to parse transition record content: ${e?.message}`)}Ei(r);let i=Hr(e.gTime),a=i.kind===`declared`?i.extensions?.did:void 0;if(a&&a!==r.author)throw Error(`Transition author mismatch: payload.author="${r.author}" but g_time.did="${a}"`);return{outcome:t,payload:r}}var ki=class{#e=new Map;#t=new Map;#n=new Map;#r=[];#i=new Map;put(e,t){let n=e.asHex();if(this.#e.has(n))return!1;if(this.#e.set(n,t),!this.#n.has(n)){let r=typeof t.toPreimage==`function`?t.toPreimage():new TextEncoder().encode(JSON.stringify(t.toJSON())),i=Wr(e.algorithm);this.#n.set(n,{hash:n,content:r,gTime:i})}return!0}get(e){let t=e.asHex(),n=this.#e.get(t);if(n)return n;let r=this.#n.get(t);if(r){try{let n=new TextDecoder(`utf-8`,{fatal:!0}).decode(r.content),i=JSON.parse(n);if(i&&typeof i==`object`){if(`uri`in i&&`payload`in i){let e=M.fromJSON(i);return this.#e.set(t,e),e}if(`kind`in i){let n=ke(i),r=M.fromStorage(`mcard:hash/${t}`,e,n,new Map,j.create(`did:clm:agent:stored`),0);return this.#e.set(t,r),r}}}catch{}try{let n={kind:`text`,value:new TextDecoder(`utf-8`,{fatal:!0}).decode(r.content)},i=M.fromStorage(`mcard:hash/${t}`,e,n,new Map,j.create(`did:clm:agent:stored`),0);return this.#e.set(t,i),i}catch{let n={kind:`binary`,mimeType:`application/octet-stream`,data:r.content},i=M.fromStorage(`mcard:raw/${t}`,e,n,new Map,j.create(`did:clm:agent:stored`),0);return this.#e.set(t,i),i}}}has(e){let t=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase();return this.#e.has(t)||this.#n.has(t)}list(){return Array.from(this.#e.values())}records(){return Array.from(this.#n.values())}listRecords(){return this.records()}deleteCard(e){let t=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase(),n=this.#e.delete(t),r=this.#n.delete(t);return n||r}count(){return this.#e.size}registerHandle(e,t){let n=typeof e==`string`?e:e.asString(),r=typeof t==`string`?t.includes(`:`)?t.split(`:`)[1]:t:t.asHex(),i=this.#t.get(n)??[];i.length>0&&i[i.length-1]===r||(i.push(r),this.#t.set(n,i))}removeHandle(e){let t=typeof e==`string`?e:e.asString();return this.#t.delete(t)}getAllHandles(){let e=[];for(let[t,n]of this.#t.entries())n.length>0&&e.push({handle:t,hash:n[n.length-1]});return e}resolveHandle(e){let t=typeof e==`string`?e:e.asString(),n=this.#t.get(t);if(!n||n.length===0)return;let r=n[n.length-1];if(r)return A.fromHex(r)}handleHistory(e){let t=typeof e==`string`?e:e.asString(),n=this.#t.get(t);return n?n.map(e=>A.fromHex(e)):[]}putRecord(e){let t=bi(e);if(t.status===`malformed`||t.status===`declared-mismatch`)throw Error(`Record verification failed: ${t.status}`);let n=e.hash.includes(`:`)?e.hash.split(`:`)[1].toLowerCase():e.hash.toLowerCase();if(this.#n.has(n))return!1;this.#n.set(n,e);try{let t=new TextDecoder(`utf-8`,{fatal:!0}).decode(e.content),r=JSON.parse(t);if(r&&typeof r==`object`&&`uri`in r&&`payload`in r)return this.#e.set(n,M.fromJSON(r)),!0}catch{}return!0}getRecord(e){let t=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase();return this.#n.get(t)}getRaw(e){return this.getRecord(e)?.content}appendTransition(e){let t=Di(e);return this.putRecord(t),this.#r.push(e),e.kind===`TOMBSTONE`?this.#i.set(e.handle,null):e.kind===`RELOCATE`?(this.#i.set(e.handle,null),e.toHandle&&e.to&&this.#i.set(e.toHandle,e.to)):e.to&&this.#i.set(e.handle,e.to),t}transitions(e){if(!e)return[...this.#r];let t=P(e);return this.#r.filter(n=>{let r=n.handle===e||P(n.handle)===t,i=n.kind===`RELOCATE`&&n.toHandle&&(n.toHandle===e||P(n.toHandle)===t);return r||i})}head(e){let t=P(e);if(this.#i.has(e))return this.#i.get(e)??null;if(this.#i.has(t))return this.#i.get(t)??null;for(let n=this.#r.length-1;n>=0;n--){let r=this.#r[n];if(r.handle===e||P(r.handle)===t||r.kind===`RELOCATE`&&r.toHandle&&(r.toHandle===e||P(r.toHandle)===t))return r.to}return null}setHead(e,t){let n=P(e);this.#i.set(e,t),this.#i.set(n,t)}snapshot(){return{timestamp:Date.now(),cardCount:this.#e.size,cards:new Map(this.#e),handles:new Map(Array.from(this.#t.entries()).map(([e,t])=>[e,[...t]])),records:new Map(this.#n),transitions:[...this.#r],heads:new Map(this.#i)}}restore(e){let t=e;this.#e=new Map(t.cards),this.#t=new Map(Array.from(t.handles.entries()).map(([e,t])=>[e,[...t]])),t.records&&(this.#n=new Map(t.records)),t.transitions&&(this.#r=[...t.transitions]),t.heads&&(this.#i=new Map(t.heads))}},Ai=`LS0g4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQCi0tIE1DYXJkIFVuaWZpZWQgRGF0YWJhc2UgU2NoZW1hIOKAlCBUaGUgVW5pdmVyc2FsIE1vbmFkaWMgVHJpYWQKLS0g4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQCi0tCi0tIFNUQUJJTElUWSBXQVJOSU5HOiBUaGlzIHNjaGVtYSBpcyB0aGUgaW52YXJpYW50ICJzZWVkaW5nIG1ldGEtbGFuZ3VhZ2UiIGZvciBhbGwKLS0gRG9tYWluIFNwZWNpZmljIExhbmd1YWdlcyAoRFNMcykuIEl0IG11c3QgcmVtYWluIGFzIHN0YWJsZSBhcyBwb3NzaWJsZS4KLS0KLS0gVEhFIFVOSUZJQ0FUSU9OIFRIRVNJUzoKLS0gVGhpcyBkZXNpZ24gdW5pdGVzIHRocmVlIGRpc3RpbmN0IG5hbWVzcGFjZXMgaW50byBhIHNpbmdsZSByZWxhdGlvbmFsIG5ldHdvcmsKLS0gYnkgbGV2ZXJhZ2luZyB0aGUgcG93ZXIgb2YgY3J5cHRvZ3JhcGhpYyBoYXNoIGZ1bmN0aW9uczoKLS0gMS4gQ09OVEVOVCBTUEFDRSAoSW50cmluc2ljIElkZW50aXR5KTogQ29udGVudC1BZGRyZXNzYWJsZSBTdG9yYWdlIChDQVMpLgotLSAyLiBIQU5ETEUgU1BBQ0UgKFJlc2VydmVkIFdvcmRzKTogTWFwcGluZyBodW1hbiBsb2dpYyB0byBjb250ZW50IGhhc2hlcy4KLS0gMy4gVkVSU0lPTiBTUEFDRSAoVGVtcG9yYWwgRXZvbHV0aW9uKTogVHJhY2tpbmcgc3RhdGUgdHJhbnNpdGlvbnMgdmlhIGhhc2ggaGlzdG9yeS4KLS0KLS0gVFVSSU5HIE1BQ0hJTkUgQU5BTE9HWSAoVGhlIEluZmluaXRlbHkgTG9uZyBUYXBlKToKLS0gVGhlIGBjYXJkYCB0YWJsZSBzdG9yZXMgY29udGVudCBibG9icyB3aXRoIHVuaXF1ZSBpZGVudGl0aWVzLCBlbXVsYXRpbmcgdGhlCi0tICJJbmZpbml0ZWx5IExvbmcgVGFwZSIgb2YgdGhlIFR1cmluZyBNYWNoaW5lIGZvcm1hbGlzbS4gQnkgdXNpbmcgcmVsYXRpb25hbAotLSBxdWVyaWVzLCB0aGlzIHRhcGUgY2FuIGJlIGR5bmFtaWNhbGx5IGNvbnN0cnVjdGVkIGFuZCB0cmF2ZXJzZWQgZm9yIGRpZmZlcmVudAotLSBEU0xzLCBwcm92aWRpbmcgYSBmbGV4aWJsZSBzdWJzdHJhdGUgZm9yIHByYWN0aWNhbGx5IGFsbCBjb21wdXRhYmxlIGxhbmd1YWdlcy4KLS0KLS0gQnkgdXNpbmcgaGFzaCB2YWx1ZXMgYXMgdGhlIHVuaXZlcnNhbCBwcmltaXRpdmVzIGFjcm9zcyBjb250ZW50LCBoYW5kbGVzLCBhbmQKLS0gdGltZSwgd2UgY3JlYXRlIGEgIldvcmRsZXNzIEJvb2siIOKAlCBhIG1pbmltYWwgc3Vic3RyYXRlIGNhcGFibGUgb2Ygc2VlZGluZyBhbnkKLS0gZG9tYWluLXNwZWNpZmljIGtub3dsZWRnZSBzeXN0ZW0gd2l0aG91dCByZXF1aXJpbmcgc2NoZW1hIGNoYW5nZXMuCi0tCi0tIE1vbmFkaWMgTWFwcGluZyAoU2VlOiBNb25hZGljIEp1c3RpZmljYXRpb24gZm9yIFNjaGVtYSBEZXNpZ24ubWQpOgotLSAxLiBDYXJkICAgID0gTW9uYWQgKFBlcmNlcHRpb24vU3RhdGUvRXhwb25lbnQpIC0gSW50cmluc2ljIElkZW50aXR5Ci0tIDIuIEhhbmRsZSAgPSBSZWdpc3RyeSAoQXBwZXRpdGlvbi9SZWFkZXIvU3VtKSAtIE11dGFibGUgUmVmZXJlbmNlCi0tIDMuIFZlcnNpb24gPSBIaXN0b3J5IChIYXJtb255L1dyaXRlci9Qcm9kdWN0KSAtIENvb3JkaW5hdGVkIEV2b2x1dGlvbgotLQotLSDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZAKLS0gVEhFIFRSSUFEOiB0aHJlZSB0YWJsZXMsIHRocmVlIGNvbHVtbnMgZWFjaCAoSU5WLVRBUEUtMDEpCi0tIOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkAotLSBUaGlzIGZpbGUgZGVjbGFyZXMgRVhBQ1RMWSBUSFJFRSBUQUJMRVMsIGVhY2ggd2l0aCBFWEFDVExZIFRIUkVFIENPTFVNTlMuIEV2ZXJ5Ci0tIHRhcGUgaW4gdGhlIG9wZXJhdGluZyBzeXN0ZW0g4oCUIGNvbnRlbnRfbWVtb3J5LmRiLCBhZ2VudF9pZGVudGl0aWVzLmRiLAotLSBleGVjdXRpb25fbG9nLmRiLCBhbmQgYW55IGZ1dHVyZSBtZXNoIHRhcGUg4oCUIGRlcGxveXMgdGhpcyBpZGVudGljYWwgZGVjbGFyYXRpb24uCi0tIFplcm8gY3VzdG9tIHRhYmxlcyBhbmQgemVybyBhdXhpbGlhcnkgY29sdW1ucyBhcmUgcGVybWl0dGVkLgotLQotLSBUSEUgS0lORCBJUyBOT1QgQSBDT0xVTU4gKElOVi1UQVBFLTAxYSwgSU5WLVRBUEUtMDMpOgotLSBgY2FyZGAgc3RvcmVzIG5vIHR5cGUgZGlzY3JpbWluYXRvci4gV2hhdCBhIGNhcmQgKmlzKiDigJQgY29udGVudCwgcHJvZ3JhbSwKLS0gdmVyaWZpY2F0aW9uLCBpZGVudGl0eSwgdGVsZW1ldHJ5IOKAlCBpcyBuYW1lZCBieSBpdHMgaGFuZGxlIGluIGBoYW5kbGVfcmVnaXN0cnlgLAotLSBhbmQgaXMgREVDSURFRCBCWSBgY2xtLWtlcm5lbGAgdGhyb3VnaCBhIHNpbmdsZSBga2luZE9mKGhhbmRsZSlgLiBBIHN0b3JlZCBraW5kCi0tIGlzIGEgc2Vjb25kIGRlY2xhcmF0aW9uIG9mIHdoYXQgdGhlIGhhbmRsZSBhbHJlYWR5IHNheXM7IGEgcmUtZGVyaXZlZCBraW5kIGlzCi0tIHRoZSBzYW1lIGRlZmVjdCBleHByZXNzZWQgYXMgY29kZS4KLS0KLS0gICB1cm46bWNhcmQ6bWNhcmQ6KiAgICAgIGNvbnRlbnQgICAgICAgIHVybjptY2FyZDphZ2VudDoqICAgICAgIGlkZW50aXR5Ci0tICAgdXJuOnBjYXJkOiogICAgICAgICAgICBwcm9ncmFtICAgICAgICB1cm46bWNhcmQ6bm9kZToqICAgICAgICBtZXNoIG5vZGUKLS0gICB1cm46bWNhcmQ6ZG9jOiogICAgICAgIGRvY3VtZW50ICAgICAgIHVybjptY2FyZDprZXk6KiAgICAgICAgIGtleSBtYXRlcmlhbAotLSAgIHVybjp2Y2FyZDoqICAgICAgICAgICAgdmVyaWZpY2F0aW9uICAgdXJuOm1jYXJkOmV4ZWN1dGlvbjoqICAgZXhlY3V0aW9uIHJlY29yZAotLSAgIHVybjptY2FyZDp0ZWxlbWV0cnk6KiAgZXZlbnQgICAgICAgICAgdXJuOm1jYXJkOm1jYXJkOmxpZmVjeWNsZToqICBsaWZlY3ljbGUgc2lkZWNhcgotLQotLSBMSUZFQ1lDTEUgSVMgRVhURVJOQUwgKElOVi1UQVBFLTA0KToKLS0gYGhhbmRsZV9oaXN0b3J5YCByZWNvcmRzIG9ubHkgVEhBVCBhIGhhbmRsZSBtb3ZlZCwgZnJvbSB3aGF0IGhhc2gsIGFuZCB3aGVuLgotLSBUb21ic3RvbmVzLCBrZXkgcm90YXRpb25zLCBzZWFscyBhbmQgdGhlaXIgcmVhc29ucyBhcmUgTk9UIGNvbHVtbnMgaGVyZTogdGhleQotLSBsaXZlIGluIGEgc2VwYXJhdGUgTElGRUNZQ0xFIFNJREVDQVIg4oCUIGEgdGVtcG9yYXJ5IGRhdGFiYXNlLCBjcmVhdGVkIG9uIGRlbWFuZCwKLS0gd2hpY2ggaXRzZWxmIGRlcGxveXMgdGhpcyBzYW1lIGRlY2xhcmF0aW9uIGFuZCBpcyByZWdpc3RlcmVkIGFzIE9ORSBDQVJEIGluIHRoZQotLSB0YXBlIGl0IGRlc2NyaWJlcyAoSU5WLVRBUEUtMDYpLiBBIHJldGlyZW1lbnQgaXMgdGhlcmVmb3JlIHR3byB3cml0ZXM6IHRoZSBmYWN0Ci0tIGhlcmUsIHRoZSBkZXRhaWwgdGhlcmUuIFRoZSBjYXJkIGlzIG5ldmVyIGRlbGV0ZWQuCi0tCi0tIE5FU1RFRCBUQVBFUyBBUkUgQ0FSRFMgKElOVi1UQVBFLTA2KToKLS0gRXZlcnkgZGF0YWJhc2UgdXNlZCBhcyBhIGNvbnRhaW5lciDigJQgYSBsaWZlY3ljbGUgc2lkZWNhciwgYSBjb2xsZWN0aW9uLCBhCi0tIHBhY2thZ2VkIGRlcGxveW1lbnQgdW5pdCAoYCoubWNhcmQuZGJgKSDigJQgaXMgaXRzZWxmIG9uZSBNQ2FyZCBpbiBpdHMgcGFyZW50IHRhcGU6Ci0tIGhhc2ggPSBTSEEyNTYoZmlsZSBieXRlcyksIHJlZ2lzdGVyZWQgdW5kZXIgYSBoYW5kbGUsIHdpdGggdGhpcyBzYW1lIHNjaGVtYQotLSBpbnNpZGUuIFRoZSBhcmNoaXRlY3R1cmUgaXMgZnJhY3RhbDogZXh0cmEgc3RydWN0dXJlIGlzIG5ldmVyIGEgbmV3IHRhYmxlLCBpdCBpcwotLSBhbm90aGVyIHRhcGUsIGFuZCBhIHRhcGUgaXMgb25lIGNhcmQuCi0tCi0tIFRIRSBNRVRBLUNJUkNVTEFSIEVWQUxVQVRPUiAmIEVPQS9DQSBEVUFMSVRZOgotLSBVbmRlciB0aGUgUEtDIGFyY2hpdGVjdHVyZSwgdGhpcyB2ZXJ5IGZpbGUgKGBtY2FyZF9zY2hlbWEuc3FsYCkgbXVzdCBiZQotLSBpbmdlc3RlZCBhbmQgc3RvcmVkIGFzIGFuIE1DYXJkIGV4YWN0bHkgbGlrZSBhbnkgb3RoZXIgQ0xNIGR1cmluZyB0aGUgaW50ZXJuYWwKLS0gYm9vdHN0cmFwcGluZyBwaGFzZS4gVGhpcyBndWFyYW50ZWVzIHRoYXQgdGhlIHNjaGVtYSBwb3dlcmluZyB0aGUgZGF0YWJhc2UKLS0gaXMgaXRzZWxmIGNvbnRlbnQtYWRkcmVzc2VkIGFuZCBjcnlwdG9ncmFwaGljYWxseSB2ZXJpZmlhYmxlLgotLSBGdXJ0aGVybW9yZSwgYWxsIHN0YXRlIGNoYW5nZXMgbWFwcGVkIHZpYSBoYW5kbGVzIGFuZCB2ZXJzaW9ucyBhcmUgc3RyaWN0bHkKLS0gZ292ZXJuZWQgYnkgdGhlIFNhbmR3aWNoZWQgUENhcmQgZXhlY3V0aW9uIHBhdHRlcm4gKGBWX3ByZSAtPiBCb2R5IC0+IFZfcG9zdGApLAotLSBzdHJpY3RseSBpbml0aWF0ZWQgYnkgYW4gRXh0ZXJuYWxseSBPd25lZCBBZ2VudCAoRU9BKSBwb3NzZXNzaW5nIHRydWUgdm9saXRpb24sCi0tIGFuZCBldmFsdWF0ZWQgZGV0ZXJtaW5pc3RpY2FsbHkgYnkgYSBDb250cmFjdCBBZ2VudCAoQ0EpIGJvdW5kIHRvIGEgUENhcmQgaGFzaC4KLS0KLS0gVmVyc2lvbjogNC4wLjAgKFRoZSBVbml2ZXJzYWwgTW9uYWRpYyBUcmlhZCDigJQgdGhyZWUgdGFibGVzLCB0aHJlZSBjb2x1bW5zKQotLSBMYXN0IFVwZGF0ZWQ6IDIwMjYtMTAtMDgKLS0g4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQCgoKLS0g4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQCi0tIExBWUVSIDE6IENPUkUgQ09OVEVOVC1BRERSRVNTQUJMRSBTVE9SQUdFIChUaGUgTW9uYWQgLyBFeHBvbmVudCkKLS0g4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQCi0tIFRoZSBmdW5kYW1lbnRhbCBNQ2FyZCBzdG9yYWdlOiBjb250ZW50LWFkZHJlc3NlZCBieSBjcnlwdG9ncmFwaGljIGhhc2guCi0tICJFYWNoIE1vbmFkIC4uLiBtaXJyb3JzIHRoZSB1bml2ZXJzZSIKLS0gSWRlbnRpdHkgSVMgdGhlIGNvbnRlbnQ6IGlkZW50aWNhbCBieXRlcyBhcmUgdGhlIHNhbWUgY2FyZCwgaW4gZXZlcnkgdGFwZS4KCi0tIEB0YWJsZSBjYXJkCi0tIEByb2xlIGNvcmUKLS0gQGRlc2NyaXB0aW9uIENvcmUgY29udGVudC1hZGRyZXNzYWJsZSBzdG9yYWdlIHRhYmxlIChNb25hZC9TdGF0ZSkKLS0gQGNvbHVtbiBoYXNoICAgIC0gU0hBLTI1NiBoYXNoIG9mIGNvbnRlbnQgKHByaW1hcnkga2V5KQotLSBAY29sdW1uIGNvbnRlbnQgLSBUaGUgYWN0dWFsIGNvbnRlbnQgKEJMT0IgZm9yIGJpbmFyeSBzYWZldHkpCi0tIEBjb2x1bW4gZ190aW1lICAtIEdlbmVyYXRpb24gdGltZXN0YW1wIChJU08gODYwMSkKLS0gQG5vdGUgTm8gdHlwZSBjb2x1bW46IHRoZSBoYW5kbGUgbmFtZXMgdGhlIGtpbmQgYW5kIGBjbG0ta2VybmVsYCBkZWNpZGVzIGl0LgpDUkVBVEUgVEFCTEUgSUYgTk9UIEVYSVNUUyBjYXJkICgKICAgIGhhc2ggVEVYVCBQUklNQVJZIEtFWSwKICAgIGNvbnRlbnQgQkxPQiBOT1QgTlVMTCwKICAgIGdfdGltZSBURVhUIE5PVCBOVUxMCik7CgoKLS0g4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQCi0tIExBWUVSIDI6IEhBTkRMRSBTWVNURU0gKEFwcGV0aXRpb24gLyBTdW0pCi0tIOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkOKVkAotLSBUaGUgbXV0YWJsZSBwb2ludGVyIHRoYXQgImRlc2lyZXMiIHRvIHJlZmVyZW5jZSBuZXcgY29udGVudC4KLS0gIkFwcGV0aXRpb246IHRoZSB0ZW5kZW5jeSB0byBtb3ZlIHRvIG5ldyBzdGF0ZXMiCgotLSBAdGFibGUgaGFuZGxlX3JlZ2lzdHJ5IChNb25hZGljIFJvbGU6IEhhbmRsZSkKLS0gQHJvbGUgY29yZQotLSBAZGVzY3JpcHRpb24gTWFwcyBoYW5kbGVzIHRvIHRoZWlyIGN1cnJlbnQgY29udGVudCBoYXNoLiBUaGUgaGFuZGxlIElTIHRoZQotLSAgICAgICAgICAgICAgbmFtZXNwYWNlOiBhbGwgdHlwaW5nLCByb2xlIGFuZCBzZWN0b3IgZGlmZmVyZW50aWF0aW9uIGxpdmVzIGhlcmUuCi0tIEBjb2x1bW4gaGFuZGxlICAgICAgIC0gVVRGLTggaGFuZGxlIG5hbWUgKHByaW1hcnkga2V5KSwgZS5nLiB1cm46cGNhcmQ6Li4uCi0tIEBjb2x1bW4gY3VycmVudF9oYXNoIC0gRksgdG8gY2FyZC5oYXNoIG9mIHRoZSBjdXJyZW50IHZlcnNpb24KLS0gQGNvbHVtbiB1cGRhdGVkX2F0ICAgLSBXaGVuIHRoZSBoYW5kbGUgd2FzIGxhc3QgYm91bmQKLS0gQG5vdGUgQ3JlYXRpb24gdGltZSBpcyB0aGUgZmlyc3QgYGhhbmRsZV9oaXN0b3J5YCByb3cgZm9yIHRoaXMgaGFuZGxlIOKAlCBhCi0tICAgICAgIHNlY29uZCBjb3B5IG9mIGEgcmVjb3JkZWQgZmFjdCBpcyBub3Qgc3RvcmVkLgpDUkVBVEUgVEFCTEUgSUYgTk9UIEVYSVNUUyBoYW5kbGVfcmVnaXN0cnkgKAogICAgaGFuZGxlIFRFWFQgUFJJTUFSWSBLRVksCiAgICBjdXJyZW50X2hhc2ggVEVYVCBOT1QgTlVMTCwKICAgIHVwZGF0ZWRfYXQgVEVYVCBOT1QgTlVMTCwKICAgIEZPUkVJR04gS0VZIChjdXJyZW50X2hhc2gpIFJFRkVSRU5DRVMgY2FyZChoYXNoKQopOwoKLS0gQGluZGV4IGlkeF9oYW5kbGVfY3VycmVudF9oYXNoCi0tIEBkZXNjcmlwdGlvbiBFZmZpY2llbnQgcmV2ZXJzZSBsb29rdXAgZnJvbSBoYXNoIHRvIGhhbmRsZXMKQ1JFQVRFIElOREVYIElGIE5PVCBFWElTVFMgaWR4X2hhbmRsZV9jdXJyZW50X2hhc2gKT04gaGFuZGxlX3JlZ2lzdHJ5KGN1cnJlbnRfaGFzaCk7CgoKLS0g4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQ4pWQCi0tIExBWUVSIDM6IFZFUlNJT04gU1BBQ0UgKEhhcm1vbnkgLyBXcml0ZXIgLyBQcm9kdWN0KQotLSDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZDilZAKCi0tIEB0YWJsZSBoYW5kbGVfaGlzdG9yeSAoTW9uYWRpYyBSb2xlOiBWZXJzaW9uIC8gUHJvZHVjdCkKLS0gQHJvbGUgY29yZQotLSBAZGVzY3JpcHRpb24gQXBwZW5kLW9ubHkgYXVkaXQgdHJhaWwgb2YgaGFuZGxlIHBvaW50ZXIgbW92ZW1lbnRzLgotLSBAY29sdW1uIGhhbmRsZSAgICAgICAgLSBUaGUgaGFuZGxlIHRoYXQgd2FzIHVwZGF0ZWQKLS0gQGNvbHVtbiBwcmV2aW91c19oYXNoIC0gSGFzaCBpdCBwb2ludGVkIHRvIGJlZm9yZSB0aGUgdXBkYXRlCi0tIEBjb2x1bW4gY2hhbmdlZF9hdCAgICAtIFdoZW4gdGhlIGNoYW5nZSBvY2N1cnJlZAotLSBAbm90ZSBUaGUgc3Vycm9nYXRlIGtleSBpcyBTUUxpdGUncyBpbXBsaWNpdCBgcm93aWRgOyBhIGRlY2xhcmVkIEFVVE9JTkNSRU1FTlQKLS0gICAgICAgY29sdW1uIHdvdWxkIGR1cGxpY2F0ZSBpdC4gVGhlIEtJTkQgb2YgY2hhbmdlIGlzIG5vdCBhIGNvbHVtbjogc2VlIHRoZQotLSAgICAgICBsaWZlY3ljbGUgc2lkZWNhciAoSU5WLVRBUEUtMDQpLgpDUkVBVEUgVEFCTEUgSUYgTk9UIEVYSVNUUyBoYW5kbGVfaGlzdG9yeSAoCiAgICBoYW5kbGUgVEVYVCBOT1QgTlVMTCwKICAgIHByZXZpb3VzX2hhc2ggVEVYVCBOT1QgTlVMTCwKICAgIGNoYW5nZWRfYXQgVEVYVCBOT1QgTlVMTCwKICAgIEZPUkVJR04gS0VZIChoYW5kbGUpIFJFRkVSRU5DRVMgaGFuZGxlX3JlZ2lzdHJ5KGhhbmRsZSksCiAgICBGT1JFSUdOIEtFWSAocHJldmlvdXNfaGFzaCkgUkVGRVJFTkNFUyBjYXJkKGhhc2gpCik7CgotLSBAaW5kZXggaWR4X2hhbmRsZV9oaXN0b3J5X2hhbmRsZQotLSBAZGVzY3JpcHRpb24gRWZmaWNpZW50IGxvb2t1cCBvZiBoaXN0b3J5IGJ5IGhhbmRsZQpDUkVBVEUgSU5ERVggSUYgTk9UIEVYSVNUUyBpZHhfaGFuZGxlX2hpc3RvcnlfaGFuZGxlCk9OIGhhbmRsZV9oaXN0b3J5KGhhbmRsZSk7Cg==`;function ji(e){try{let t=[e?N(e,`kernel`,`clm_rust_core`,`types`,`schemas`,`mcard_schema.sql`):null,e?N(e,`kernel`,`clm_py_core`,`clm`,`schemas`,`mcard_schema.sql`):null,e?N(e,`types`,`schemas`,`mcard_schema.sql`):null,Je(process.cwd(),`kernel`,`clm_rust_core`,`types`,`schemas`,`mcard_schema.sql`),Je(process.cwd(),`kernel`,`clm_py_core`,`clm`,`schemas`,`mcard_schema.sql`),Je(wr,`../../../clm_rust_core/types/schemas/mcard_schema.sql`),Je(wr,`../../../../kernel/clm_rust_core/types/schemas/mcard_schema.sql`),Je(process.cwd(),`types`,`schemas`,`mcard_schema.sql`),Je(wr,`../../../../types/schemas/mcard_schema.sql`),Je(wr,`../../../../../types/schemas/mcard_schema.sql`)].filter(e=>!!e);for(let e of t)if(qr(e)){let t=Yr(e,`utf-8`);if(t.includes(`CREATE TABLE`)&&t.includes(`handle_registry`))return t}}catch{}return Buffer.from(Ai,`base64`).toString(`utf-8`)}ji();function Mi(){try{return Gr(import.meta.url?import.meta.url:`file:///index.js`)(`node:sqlite`)}catch(e){throw Error(`node:sqlite is only available in Node.js v22+ environments: ${e}`)}}var Ni=class e{#e;#t=0;#n=[];#r=new Map;#i=!1;constructor(e=`:memory:`){let{DatabaseSync:t}=Mi(),n=!1;if(typeof e==`object`&&e&&`prepare`in e&&`exec`in e)this.#e=e;else{let r=typeof e==`string`?e:e.path??`:memory:`,i=typeof e==`object`&&!!e.readOnly;n=i,this.#e=new t(r,{readOnly:i})}n||this.#a()}static async create(t=`:memory:`){return new e(t)}async init(){return this}#a(){let e=ji();this.#e.exec(e);try{this.#e.exec(`
14
+ PRAGMA journal_mode = WAL;
15
+ PRAGMA synchronous = NORMAL;
16
+ `)}catch{}}put(e,t){let n=e.asHex();if(this.#e.prepare(`SELECT hash FROM card WHERE hash = ?`).get(n))return!1;let r=typeof t.toPreimage==`function`?Buffer.from(t.toPreimage()):Buffer.from(JSON.stringify(t.toJSON()),`utf-8`),i=Wr(e.algorithm);if(this.#e.prepare(`INSERT INTO card (hash, content, g_time) VALUES (?, ?, ?)`).run(n,r,i),t.uri&&!t.uri.startsWith(`mcard:hash/`)&&!t.uri.startsWith(`mcard:raw/`))try{this.registerHandle(t.uri,n)}catch{}return!0}get(e){let t=e.asHex(),n=this.#e.prepare(`SELECT card.content, hr.handle FROM card LEFT JOIN handle_registry hr ON card.hash = hr.current_hash WHERE card.hash = ?`).get(t);if(!n)return;let r=Buffer.isBuffer(n.content)?new Uint8Array(n.content.buffer,n.content.byteOffset,n.content.byteLength):n.content instanceof Uint8Array?n.content:Buffer.from(n.content,`utf-8`);if(wi(r)){let e=new TextDecoder().decode(r);return M.fromJSON(JSON.parse(e))}try{let i=new TextDecoder(`utf-8`,{fatal:!0}).decode(r),a=JSON.parse(i);if(a&&typeof a==`object`&&`kind`in a){let r=ke(a),i=n.handle||`mcard:hash/${t}`;return M.fromStorage(i,e,r,new Map,j.create(`did:clm:agent:stored`),0)}}catch{}let i=n.handle||`mcard:raw/${t}`;return M.create(i,{kind:`binary`,mimeType:`application/octet-stream`,data:r},e,0)}has(e){let t=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase();return!!this.#e.prepare(`SELECT 1 FROM card WHERE hash = ?`).get(t)}list(){return this.#e.prepare(`SELECT card.hash, card.content, hr.handle FROM card LEFT JOIN handle_registry hr ON card.hash = hr.current_hash`).all().map(e=>{let t=Buffer.isBuffer(e.content)?new Uint8Array(e.content.buffer,e.content.byteOffset,e.content.byteLength):e.content instanceof Uint8Array?e.content:Buffer.from(e.content,`utf-8`);try{if(wi(t)){let e=new TextDecoder().decode(t);return M.fromJSON(JSON.parse(e))}}catch{}try{let n=new TextDecoder(`utf-8`,{fatal:!0}).decode(t),r=JSON.parse(n);if(r&&typeof r==`object`&&`kind`in r){let t=ke(r),n=e.handle||(t.kind===`structured`&&t.value?.driver&&t.value?.ref?`mcard:receipt/${t.value.driver}/${t.value.ref}`:`mcard:hash/${e.hash}`);return M.fromStorage(n,A.fromHex(e.hash),t,new Map,j.create(`did:clm:agent:stored`),0)}}catch{}return M.create(e.handle||`mcard:raw`,{kind:`binary`,mimeType:`application/octet-stream`,data:t},`did:key:raw`,0)})}records(){return this.#e.prepare(`SELECT hash, content, g_time FROM card`).all().map(e=>({hash:e.hash,content:Buffer.isBuffer(e.content)?new Uint8Array(e.content.buffer,e.content.byteOffset,e.content.byteLength):e.content instanceof Uint8Array?e.content:Buffer.from(e.content),gTime:e.g_time}))}count(){return this.#e.prepare(`SELECT COUNT(*) as count FROM card`).get().count}putRecord(e){let t=bi(e);if(t.status===`malformed`||t.status===`declared-mismatch`)throw Error(`Record verification failed: ${t.status}`);let n=e.hash.includes(`:`)?e.hash.split(`:`)[1].toLowerCase():e.hash.toLowerCase();return!this.#e.prepare(`SELECT hash FROM card WHERE hash = ?`).get(n)&&(this.#e.prepare(`INSERT INTO card (hash, content, g_time) VALUES (?, ?, ?)`).run(n,Buffer.from(e.content),e.gTime),!0)}getRecord(e){let t=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase(),n=this.#e.prepare(`SELECT hash, content, g_time FROM card WHERE hash = ?`).get(t);if(!n)return;let r=Buffer.isBuffer(n.content)?new Uint8Array(n.content.buffer,n.content.byteOffset,n.content.byteLength):n.content instanceof Uint8Array?n.content:Buffer.from(n.content);return{hash:n.hash,content:r,gTime:n.g_time}}putRaw(e,t,n,r){let i=e.split(`:`,2),a=i.length===2?i[0].toLowerCase():void 0,o=(i.length===2?i[1]:i[0]).toLowerCase();if(this.#e.prepare(`SELECT hash FROM card WHERE hash = ?`).get(o))return!1;let s=typeof t==`string`?Buffer.from(t,`utf-8`):Buffer.isBuffer(t)?t:Buffer.from(t),c=n?Hr(n):void 0;if(c?.kind===`malformed`)throw Error(`Cannot persist raw CAS row with malformed g_time: ${c.reason}`);let l=c?.kind===`declared`?c.algorithm:void 0,u=ue(r??l??a);if(l&&l!==u)throw Error(`Raw CAS g_time algorithm ${l} conflicts with selected algorithm ${u}`);if(a&&a!==u)throw Error(`Raw CAS hash prefix ${a} conflicts with selected algorithm ${u}`);if(de(u,s).toLowerCase()!==o)throw Error(`Raw CAS digest does not match ${u} content hash ${o}`);let d=n??Wr(u);return this.#e.prepare(`INSERT INTO card (hash, content, g_time) VALUES (?, ?, ?)`).run(o,s,d),!0}getRaw(e){return this.getRecord(e)?.content}registerHandle(e,t){let n=typeof e==`string`?e:e.asString(),r=typeof t==`string`?t:t.asHex(),i=new Date().toISOString(),a=this.#e.prepare(`SELECT current_hash FROM handle_registry WHERE handle = ?`).get(n);a?a.current_hash!==r&&(this.#e.prepare(`
17
+ INSERT INTO handle_history (handle, previous_hash, changed_at)
18
+ VALUES (?, ?, ?)
19
+ `).run(n,a.current_hash,i),this.#e.prepare(`
20
+ UPDATE handle_registry
21
+ SET current_hash = ?, updated_at = ?
22
+ WHERE handle = ?
23
+ `).run(r,i,n)):this.#e.prepare(`
24
+ INSERT INTO handle_registry (handle, current_hash, updated_at)
25
+ VALUES (?, ?, ?)
26
+ `).run(n,r,i)}resolveHandle(e){let t=typeof e==`string`?e:e.asString(),n=this.#e.prepare(`SELECT current_hash FROM handle_registry WHERE handle = ?`).get(t);if(n)return A.parse(n.current_hash)}handleHistory(e){let t=typeof e==`string`?e:e.asString(),n=this.#e.prepare(`SELECT previous_hash FROM handle_history WHERE handle = ? ORDER BY rowid ASC`).all(t).map(e=>A.parse(e.previous_hash)),r=this.resolveHandle(t);return r&&!n.some(e=>e.asHex()===r.asHex())&&n.push(r),n}#o(){if(!this.#i){this.#i=!0;try{let e=this.#e.prepare(`SELECT content FROM card ORDER BY rowid ASC`).all();for(let t of e)try{let e=(Buffer.isBuffer(t.content)?t.content:t.content instanceof Uint8Array?Buffer.from(t.content):Buffer.from(t.content,`utf-8`)).toString(`utf-8`);if(!e.startsWith(`{`)||!e.endsWith(`}`))continue;let n=JSON.parse(e);n&&typeof n==`object`&&Le.includes(n.kind)&&typeof n.handle==`string`&&typeof n.author==`string`&&n.clock&&`from`in n&&`to`in n&&(this.#n.push(n),n.kind===`TOMBSTONE`?this.#r.set(n.handle,null):n.kind===`RELOCATE`?(this.#r.set(n.handle,null),n.toHandle&&n.to&&this.#r.set(n.toHandle,n.to)):n.to&&this.#r.set(n.handle,n.to))}catch{}}catch{}}}appendTransition(e){this.#o();let t=Di(e);return this.putRecord(t),this.#n.push(e),e.kind===`TOMBSTONE`?this.#r.set(e.handle,null):e.kind===`RELOCATE`?(this.#r.set(e.handle,null),e.toHandle&&e.to&&this.#r.set(e.toHandle,e.to)):e.to&&this.#r.set(e.handle,e.to),t}transitions(e){if(this.#o(),!e)return[...this.#n];let t=P(e);return this.#n.filter(n=>{let r=n.handle===e||P(n.handle)===t,i=n.kind===`RELOCATE`&&n.toHandle&&(n.toHandle===e||P(n.toHandle)===t);return r||i})}head(e){this.#o();let t=P(e);if(this.#r.has(e))return this.#r.get(e)??null;if(this.#r.has(t))return this.#r.get(t)??null;for(let n=this.#n.length-1;n>=0;n--){let r=this.#n[n];if(r.handle===e||P(r.handle)===t||r.kind===`RELOCATE`&&r.toHandle&&(r.toHandle===e||P(r.toHandle)===t))return r.to}let n=this.resolveHandle(e)||this.resolveHandle(t);return n?`blake3:${n.asHex()}`:null}setHead(e,t){this.#o();let n=P(e);this.#r.set(e,t),this.#r.set(n,t)}snapshot(){this.#t+=1;let e=`sp_${this.#t}_${Date.now()}`;return this.#e.exec(`SAVEPOINT ${e};`),{timestamp:Date.now(),cardCount:this.count(),savepointName:e}}restore(e){let t=e;t.savepointName&&(this.#e.exec(`ROLLBACK TO SAVEPOINT ${t.savepointName};`),this.#e.exec(`RELEASE SAVEPOINT ${t.savepointName};`))}get rawDb(){return this.#e}get db(){return this.#e}getAllHandles(){return this.#e.prepare(`SELECT handle, current_hash as hash FROM handle_registry`).all()}removeHandle(e){let t=typeof e==`string`?e:e.asString();this.#e.prepare(`DELETE FROM handle_registry WHERE handle = ?`).run(t)}renameHandle(e,t){let n=typeof e==`string`?e:e.asString?.()??String(e),r=typeof t==`string`?t:t.asString?.()??String(t),i=this.#e.prepare(`SELECT current_hash FROM handle_registry WHERE handle = ?`).get(n);if(!i)throw Error(`Handle '${n}' not found`);let a=new Date().toISOString();this.#e.exec(`BEGIN TRANSACTION;`);try{this.#e.prepare(`INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?, ?, ?)`).run(r,i.current_hash,a),this.#e.prepare(`INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?, ?, ?)`).run(r,i.current_hash,a),this.#e.prepare(`DELETE FROM handle_registry WHERE handle = ?`).run(n),this.#e.exec(`COMMIT;`)}catch(e){throw this.#e.exec(`ROLLBACK;`),e}}getHandleHistoryWithTimestamps(e){let t=typeof e==`string`?e:e.asString();return this.#e.prepare(`SELECT previous_hash as previousHash, changed_at as changedAt FROM handle_history WHERE handle = ? ORDER BY changed_at DESC`).all(t)}getHandleHistory(e){return this.getHandleHistoryWithTimestamps(e)}close(){this.#e.close()}},Pi=class{#e;#t=new Map;#n=0;constructor(e){this.#e=e,this.#r()}#r(){let e=ji();try{this.#e.run(e)}catch{let t=e.split(`;`).map(e=>e.trim()).filter(e=>e.length>0);for(let e of t)try{this.#e.run(e)}catch{}}}put(e,t){let n=e.asHex(),r=this.#e.exec(`SELECT hash FROM card WHERE hash = ?`,[n])[0];if(r&&r.values.length>0)return!1;let i=typeof t.toPreimage==`function`?t.toPreimage():new TextEncoder().encode(JSON.stringify(t.toJSON())),a=Wr(e.algorithm);if(this.#e.run(`INSERT INTO card (hash, content, g_time) VALUES (?, ?, ?)`,[n,i,a]),t.uri&&!t.uri.startsWith(`mcard:hash/`)&&!t.uri.startsWith(`mcard:raw/`)){this.#t.set(n,t.uri);try{this.registerHandle(t.uri,n)}catch{}}return!0}get(e){let t=e.asHex(),n=this.#e.exec(`SELECT content FROM card WHERE hash = ?`,[t])[0];if(!n||n.values.length===0)return;let r=n.values[0];if(!r||r[0]===void 0||r[0]===null)return;let i=r[0],a=this.#t.get(t);if(!a)try{let e=this.#e.exec(`SELECT handle FROM handle_registry WHERE current_hash = ?`,[t]);e[0]&&e[0].values.length>0&&(a=String(e[0].values[0][0]),this.#t.set(t,a))}catch{}let o=typeof i==`string`?new TextEncoder().encode(i):i instanceof Uint8Array?i:new Uint8Array(i);try{let n=JSON.parse(new TextDecoder().decode(o));if(n&&typeof n==`object`){if(`uri`in n&&`payload`in n)return M.fromJSON(n);if(`kind`in n){let r=ke(n),i=a||`mcard:hash/${t}`;return M.fromStorage(i,e,r,new Map,j.create(`did:clm:agent:stored`),0)}}}catch{}if(wi(o)){let e=new TextDecoder(`utf-8`).decode(o);return M.fromJSON(JSON.parse(e))}let s=a||`mcard:raw/${t}`;return M.create(s,{kind:`binary`,mimeType:`application/octet-stream`,data:o},e,0)}has(e){let t=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase(),n=this.#e.exec(`SELECT 1 FROM card WHERE hash = ?`,[t])[0];return!!(n&&n.values.length>0)}list(){let e=this.#e.exec(`SELECT card.hash, card.content, hr.handle FROM card LEFT JOIN handle_registry hr ON card.hash = hr.current_hash`)[0];return e?e.values.map(e=>{let t=String(e[0]||``),n=e[1],r=e[2]?String(e[2]):void 0,i=typeof n==`string`?new TextEncoder().encode(n):n instanceof Uint8Array?n:new Uint8Array(n);try{if(wi(i)){let e=new TextDecoder(`utf-8`).decode(i);return M.fromJSON(JSON.parse(e))}}catch{}try{let e=new TextDecoder(`utf-8`,{fatal:!0}).decode(i),n=JSON.parse(e);if(n&&typeof n==`object`&&`kind`in n){let e=ke(n),i=r||(e.kind===`structured`&&e.value?.driver&&e.value?.ref?`mcard:receipt/${e.value.driver}/${e.value.ref}`:`mcard:hash/${t}`);return M.fromStorage(i,A.fromHex(t),e,new Map,j.create(`did:clm:agent:stored`),0)}}catch{}return M.create(r||`mcard:raw`,{kind:`binary`,mimeType:`application/octet-stream`,data:i},`did:key:raw`,0)}):[]}count(){let e=this.#e.exec(`SELECT COUNT(*) FROM card`)[0];if(!e||e.values.length===0)return 0;let t=e.values[0]?.[0];return typeof t==`number`?t:0}putRecord(e){let t=bi(e);if(t.status===`malformed`||t.status===`declared-mismatch`)throw Error(`Record verification failed: ${t.status}`);let n=e.hash.includes(`:`)?e.hash.split(`:`)[1].toLowerCase():e.hash.toLowerCase(),r=this.#e.exec(`SELECT hash FROM card WHERE hash = ?`,[n]);return r[0]&&r[0].values.length>0?!1:(this.#e.run(`INSERT INTO card (hash, content, g_time) VALUES (?, ?, ?)`,[n,e.content,e.gTime]),!0)}getRecord(e){let t=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase(),n=this.#e.exec(`SELECT hash, content, g_time FROM card WHERE hash = ?`,[t])[0];if(!n||n.values.length===0)return;let r=n.values[0];if(!r)return;let i=String(r[0]),a=r[1],o=String(r[2]);return{hash:i,content:typeof a==`string`?new TextEncoder().encode(a):a instanceof Uint8Array?a:new Uint8Array(a),gTime:o}}getRaw(e){return this.getRecord(e)?.content}appendTransition(e){let t=Di(e);return this.putRecord(t),t}transitions(e){let t=this.#e.exec(`SELECT hash, content, g_time FROM card ORDER BY rowid ASC`)[0];if(!t)return[];let n=[];for(let e of t.values){let t=e[1],r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?t:new Uint8Array(t),i={hash:String(e[0]),content:r,gTime:String(e[2])};try{n.push(Oi(i).payload)}catch{}}if(!e)return n;let r=P(e);return n.filter(t=>{let n=t.handle===e||P(t.handle)===r,i=t.kind===`RELOCATE`&&t.toHandle!=null&&(t.toHandle===e||P(t.toHandle)===r);return n||i})}registerHandle(e,t){let n=typeof e==`string`?e:e.asString?e.asString():String(e),r=typeof t==`string`?t.includes(`:`)?t.split(`:`)[1]:t:t.asHex(),i=new Date().toISOString();this.#t.set(r,n);let a=this.#e.exec(`SELECT current_hash FROM handle_registry WHERE handle = ?`,[n])[0];if(a&&a.values.length>0){let e=String(a.values[0][0]);e!==r&&(this.#e.run(`INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?, ?, ?)`,[n,e,i]),this.#e.run(`UPDATE handle_registry SET current_hash = ?, updated_at = ? WHERE handle = ?`,[r,i,n]))}else this.#e.run(`INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?, ?, ?)`,[n,r,i])}resolveHandle(e){let t=typeof e==`string`?e:e.asString?e.asString():String(e),n=this.#e.exec(`SELECT current_hash FROM handle_registry WHERE handle = ?`,[t])[0];if(!n||n.values.length===0)return;let r=n.values[0]?.[0];if(typeof r==`string`)return A.parse(r)}handleHistory(e){let t=typeof e==`string`?e:e.asString?e.asString():String(e),n=this.#e.exec(`SELECT previous_hash FROM handle_history WHERE handle = ? ORDER BY rowid ASC`,[t])[0],r=[];if(n)for(let e of n.values)typeof e[0]==`string`&&r.push(A.parse(e[0]));let i=this.resolveHandle(e);return i&&!r.some(e=>e.asHex()===i.asHex())&&r.push(i),r}getAllHandles(){let e=this.#e.exec(`SELECT handle, current_hash FROM handle_registry ORDER BY handle ASC`)[0];return e?e.values.filter(e=>typeof e[0]==`string`&&typeof e[1]==`string`).map(e=>({handle:String(e[0]),hash:String(e[1])})):[]}removeHandle(e){let t=typeof e==`string`?e:String(e);this.#e.run(`DELETE FROM handle_registry WHERE handle = ?`,[t])}setHead(e,t){let n=typeof e==`string`?e:String(e);if(t===null){this.removeHandle(n);return}let r=t.includes(`:`)?t.split(`:`)[1]:t;this.registerHandle(n,A.parse(r))}head(e){let t=P(e),n=this.transitions();for(let r=n.length-1;r>=0;--r){let i=n[r];if(i.handle===e||P(i.handle)===t||i.kind===`RELOCATE`&&i.toHandle!=null&&(i.toHandle===e||P(i.toHandle)===t))return i.to??null}let r=this.resolveHandle(e);return r?`blake3:${r.asHex()}`:null}snapshot(){this.#n+=1;let e=`sp_${this.#n}_${Date.now()}`;try{return this.#e.run(`SAVEPOINT ${e};`),{timestamp:Date.now(),cardCount:this.count(),savepointName:e}}catch{let e=this.#e.export?this.#e.export():void 0;return{timestamp:Date.now(),cardCount:this.count(),exportedData:e}}}restore(e){let t=e;t.savepointName&&(this.#e.run(`ROLLBACK TO SAVEPOINT ${t.savepointName};`),this.#e.run(`RELEASE SAVEPOINT ${t.savepointName};`))}exportBinary(){return this.#e.export?this.#e.export():void 0}close(){this.#e.close&&this.#e.close()}};new Set(`CLM_RUNTIME.CLM_RUNNER.CLM_RUNTIME_BACKEND.CLM_POLYGLOT_RUNTIME.CLM_ROOT.PROJECT_ROOT.CLM_DB_DIR.CLM_DB_PATH.CLM_DB_BACKEND.CLM_MEM_TRIDB.CLM_ZERO_FS.CLM_AGENT_DID.ACTIVE_AGENT_DID.CLM_SPONSOR_DID.CLM_KENOTIC_SPONSOR_DID.CLM_EXECUTION_LOCALE_HASH.CLM_KENOTIC_CURRENT_MARKING_HASH.CLM_LOCALE_TRUST.CLM_HASH_ALGO.CLM_HASH_CONFIG.CLM_TARGET_FILE.CLM_ACTIVE_FILE.CLM_FILE.TARGET_FILE.CLM_PAYLOAD.CLM_PAYLOAD_FILE.CLM_RUN_ID.CLM_STATE_TOKEN.CLM_BINDING_TYPE.CLM_EVENT_LOG_PATH.CLM_GATE_OVERRIDE.CLM_SKIP_CONDITIONS.CLM_SKIP_GRAMMAR.CLM_PETRI_HALT.CLM_PETRI_KENOTIC.CLM_PETRI_MARKING_DIR.CLM_PETRI_VISUAL.CLM_FORBID_SUBPROCESS.CLM_NESTED_EXEC.CLM_RUST_DAEMON_PORT.CLM_RUST_PORT_FILE.CLM_ACTIVE_A_HASH.CLM_ACTIVE_B_HASH.CLM_ACTIVE_C_HASH.CLM_MLP_CONTEXT.CLM_SESSION_DELEGATION.CLM_TRANSPORT_REF.CLM_REPL_TRACE.CLM_NO_SANDBOX.CLM_SYMBOL_HANDLES.CLM_MEMBROKER_PORT.CLM_MEMBROKER_NO_DISK.CLM_MEMBROKER_SNAP_DIR.CLM_SCRATCH.CLM_TEST_FAST_BOOT.CLM_QUIET.CLM_NATIVE_PETRI_VM.CLM_DISPATCH_SOCK.CLM_SCRIPT_CONTENT.CLM_ENTRY_POINT.CLM_TARGET_PATH.CLM_AGENT_CLASS.CLM_AGENT_ROLE.CLM_RISK_LEVEL.CLM_EOA_APPROVAL.CLM_LAST_MCARD_HASH.CLM_LAST_MCARD_FILE`.split(`.`)),Ir(Nr);function Fi(){let e=typeof process<`u`;return{isNode:e&&!!process.versions?.node,isBrowser:typeof globalThis<`u`&&(`window`in globalThis||`document`in globalThis),isZeroFs:e&&{}.CLM_ZERO_FS===`true`}}var Ii=new Map;function Li(e){Ii.set(e.id,e)}Li({id:`memory`,priority:1,capabilities:{role:`authoritative`,conditionalPut:!0,rangeRead:!1},isSupported:(e,t)=>!!(t?.forceMemory||e.isZeroFs),createBackend:()=>new ki}),Li({id:`sqljs`,priority:1,capabilities:{role:`authoritative`,conditionalPut:!0,rangeRead:!1},isSupported:(e,t)=>!!t?.sqlJsDb,createBackend:e=>new Pi(e.sqlJsDb)}),Li({id:`node-sqlite`,priority:0,capabilities:{role:`authoritative`,conditionalPut:!0,rangeRead:!1},isSupported:(e,t)=>e.isNode&&!t?.forceMemory&&!e.isZeroFs,createBackend:e=>{try{return new Ni(e?.dbPath??`:memory:`)}catch{return new ki}}});function Ri(e){let t=Fi(),n=Array.from(Ii.values()).sort((e,t)=>(t.priority??10)-(e.priority??10));for(let r of n)if(r.capabilities?.role!==`replica`&&r.isSupported(t,e))try{return r.createBackend(e)}catch{}return new ki}function zi(e){if(e.length===0)return!1;let t=Math.min(e.length,8192),n=e.subarray(0,t);for(let e=0;e<n.length;e++)if(n[e]===0)return!0;try{let e=new TextDecoder(`utf-8`,{fatal:!0}).decode(n),t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);(r<9||r>13&&r<32)&&t++}return t>n.length*.1}catch{return!0}}var Bi=[{magic:new Uint8Array([137,80,78,71,13,10,26,10]),mime:`image/png`},{magic:new Uint8Array([255,216,255]),mime:`image/jpeg`},{magic:new Uint8Array([71,73,70,56]),mime:`image/gif`},{magic:new Uint8Array([37,80,68,70]),mime:`application/pdf`},{magic:new Uint8Array([80,75,3,4]),mime:`application/zip`},{magic:new Uint8Array([83,81,76,105,116,101,32,102,111,114,109,97,116,32,51,0]),mime:`application/sqlite3`},{magic:new Uint8Array([103,108,84,70]),mime:`model/gltf-binary`},{magic:new Uint8Array([73,68,51]),mime:`audio/mpeg`}],Vi={pdf:`application/pdf`,md:`text/markdown`,markdown:`text/markdown`,txt:`text/plain`,text:`text/plain`,json:`application/json`,yaml:`application/yaml`,yml:`application/yaml`,xml:`text/xml`,html:`text/html`,htm:`text/html`,csv:`text/csv`,js:`application/javascript`,mjs:`application/javascript`,cjs:`application/javascript`,ts:`text/typescript`,tsx:`text/typescript`,py:`text/x-python`,sh:`text/x-shellscript`,png:`image/png`,jpeg:`image/jpeg`,jpg:`image/jpeg`,webp:`image/webp`,svg:`image/svg+xml`,gif:`image/gif`,"3ds":`model/x-3ds`,obj:`model/obj`,stl:`model/stl`,gltf:`model/gltf+json`,glb:`model/gltf-binary`,wav:`audio/wav`,mp3:`audio/mpeg`,mp4:`video/mp4`,ttf:`font/ttf`,woff2:`font/woff2`,tikz:`text/x-tikz`,tikzcd:`text/x-tikzcd`,"tikz-cd":`text/x-tikzcd`,tex:`application/x-tex`};function Hi(e,t=``){if(e.length===0){if(t){let e=(t.includes(`.`)?t.split(`.`).pop():t).replace(/^\.+/,``).toLowerCase();if(e in Vi)return Vi[e]}return`application/octet-stream`}if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70){let t=String.fromCharCode(e[8],e[9],e[10],e[11]);if(t===`WEBP`)return`image/webp`;if(t===`WAVE`)return`audio/wav`}if(e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112)return`video/mp4`;for(let t of Bi)if(e.length>=t.magic.length){let n=!0;for(let r=0;r<t.magic.length;r++)if(e[r]!==t.magic[r]){n=!1;break}if(n)return t.mime}if(t){let e=(t.includes(`.`)?t.split(`.`).pop():t).replace(/^\.+/,``).toLowerCase();if(e in Vi)return Vi[e]}return zi(e)?`application/octet-stream`:`text/plain`}function Ui(){try{let e=Gr(import.meta.url?import.meta.url:`file:///index.js`);return{fs:e(`node:fs`),os:e(`node:os`),path:e(`node:path`),sqlite:e(`node:sqlite`)}}catch(e){throw Error(`Node.js built-ins (fs, os, path, sqlite) are only available in Node.js v22+ environments: ${e}`)}}function Wi(){let{fs:e,os:t,path:n,sqlite:r}=Ui();return{name:`node:sqlite`,open:e=>new r.DatabaseSync(e),toBytes:(t,n)=>new Uint8Array(e.readFileSync(n)),scratchPath:()=>n.join(t.tmpdir(),`clm_portable_export_${Date.now()}_${Math.random().toString(36).slice(2)}.db`),fromBytes:(t,n)=>{if(!n)throw Error(`the node engine requires a scratch path`);return e.writeFileSync(n,t),n},cleanup:t=>{if(t)try{e.unlinkSync(t)}catch{}}}}function Gi(e,t){let n=t?.engine??Wi(),r=n.scratchPath(),i=n.open(r??`:memory:`);try{i.exec(`PRAGMA foreign_keys = OFF;`);let a=ji();i.exec(a);let o=t?.schemaProfile===`archive-cas-04`;if(!o){let e=[`CREATE`,`TABLE IF NOT EXISTS mcard_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);`].join(` `);i.exec(e);try{i.exec(`ALTER TABLE handle_registry ADD COLUMN hash TEXT GENERATED ALWAYS AS (current_hash) VIRTUAL;`)}catch{}try{i.exec(`ALTER TABLE handle_history ADD COLUMN hash TEXT GENERATED ALWAYS AS (previous_hash) VIRTUAL;`)}catch{}try{i.exec(`ALTER TABLE handle_history ADD COLUMN created_at TEXT GENERATED ALWAYS AS (changed_at) VIRTUAL;`)}catch{}}let s=i.prepare(`INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?, ?, ?)`),c=i.prepare(`INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?, ?, ?)`),l=i.prepare(`INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?, ?, ?)`);if(!o){let n=i.prepare(`INSERT OR REPLACE INTO mcard_meta (key, value) VALUES (?, ?)`);n.run(`schema_profile`,t?.schemaProfile||`portable-3.0.3`),t?.exportedAt&&n.run(`exported_at`,t.exportedAt),n.run(`card_count`,String(e.length)),n.run(`exported_by`,t?.exportedBy||`AstroStudio`)}for(let t of e){let e;e=Buffer.isBuffer(t.content)||t.content instanceof Uint8Array?Buffer.from(t.content):typeof t.content==`string`?t.content:JSON.stringify(t.content);let n=t.g_time||t.created_at||`1970-01-01T00:00:00.000Z`;s.run(t.hash,e,n),t.handle&&c.run(t.handle,t.hash,n),t.path&&t.path!==t.handle&&c.run(t.path,t.hash,n)}for(let e of t?.history??[])l.run(e.handle,e.previous_hash,e.changed_at);let u=n.toBytes(i,r??`:memory:`);i.close();try{n.cleanup(r)}catch{}return u}catch(e){try{i.close()}catch{}try{n.cleanup(r)}catch{}throw e}}async function Ki(e,t){return Gi(e,t)}function qi(e,t){if(e.length<16)throw Error(`File too small to be a valid SQLite database`);if(!new TextDecoder(`utf-8`).decode(e.subarray(0,16)).startsWith(`SQLite format 3`))throw Error(`Invalid SQLite 3 binary header (magic bytes mismatch)`);let n=t?.engine??Wi(),r=n.scratchPath(),i=n.open(n.fromBytes(e,r)),a=r;try{let e=i.prepare(`SELECT name FROM sqlite_master WHERE type='table'`).all().map(e=>e.name),t=e.includes(`card`)?i.prepare(`SELECT * FROM card`).all():[],r=e.includes(`handle_registry`)?i.prepare(`SELECT * FROM handle_registry`).all().map(e=>({...e,hash:e.hash??e.current_hash,current_hash:e.current_hash??e.hash})):[],o=e.includes(`handle_history`)?i.prepare(`SELECT * FROM handle_history`).all().map(e=>({...e,hash:e.hash??e.previous_hash,previous_hash:e.previous_hash??e.hash,created_at:e.created_at??e.changed_at,changed_at:e.changed_at??e.created_at})):[],s=e.includes(`mcard_meta`)?i.prepare(`SELECT * FROM mcard_meta`).all():[];i.close();try{n.cleanup(a)}catch{}return{tables:e,cards:t,handles:r,history:o,meta:s}}catch(e){try{i.close()}catch{}try{n.cleanup(a)}catch{}throw e}}async function Ji(e,t){return qi(e,t)}function Yi(e,t={}){let n=e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase(),r=e.includes(`:`)?e:n;if(!t.original&&t.working){let e=Xi(t.working);if(e)try{let t=e.prepare(`SELECT hash, content, g_time FROM card WHERE hash = ?`).get(n);if(t){let e=Buffer.isBuffer(t.content)?new Uint8Array(t.content):t.content instanceof Uint8Array?t.content:new TextEncoder().encode(String(t.content)),n={hash:t.hash,content:e,gTime:t.g_time};return{record:n,outcome:bi(n),fromArchive:!1}}}catch{}else if(t.working.getRecord){let e=t.working.getRecord(n);if(e)return{record:e,outcome:bi(e),fromArchive:!1}}}if(!t.working||!t.archiveDir)throw Error(`Record '${e}' not found in working tape and no archiveDir provided`);let i=Zi(t.working),a=[];for(let e of i)try{let t=new TextDecoder(`utf-8`,{fatal:!0}).decode(e.content);if(t.includes(`"lineage-anchor"`)){let n=JSON.parse(t);n.kind===`lineage-anchor`&&Array.isArray(n.pruned)&&n.archive&&a.push({record:e,payload:n})}}catch{}a.reverse();for(let{record:i,payload:o}of a)if(o.pruned.includes(r)||o.pruned.some(e=>e.toLowerCase().endsWith(n))){let a=o.archive,s=a.includes(`:`)?a.split(`:`)[1].toLowerCase():a.toLowerCase(),c=`${s}.mcard.db`,l=t.archiveDir?tt.join(t.archiveDir,c):``,u;if(l&&pi.existsSync(l))u=new Uint8Array(pi.readFileSync(l));else if(t.remoteReplica){let e=t.remoteReplica.getRecord?.(a)||t.remoteReplica.getRecord?.(s);if(e)u=e.content;else if(typeof t.remoteReplica.getObjectRaw==`function`){let e=t.remoteReplica.getObjectRaw(a)||t.remoteReplica.getObjectRaw(s);e&&(u=e.body)}if(!u&&(t.remoteReplica.has?.(a)||t.remoteReplica.has?.(s)))throw Error(`Archive container corruption detected! File '${c}' pinned by anchor '${i.hash}' failed replica verification`)}if(!u)throw Error(`Archive container file '${c}' pinned by anchor '${i.hash}' not found at ${l}`);let d=a.includes(`:`)?a.split(`:`)[0]:void 0;if(!d)throw Error(`Archive reference '${a}' has no algorithm provenance`);let f=de(d,u);if(f!==s)throw Error(`Archive container corruption detected! File '${c}' pinned by anchor '${i.hash}' hash mismatch (expected ${s}, got ${f})`);let p=qi(u).cards.find(e=>e.hash.toLowerCase()===n||e.hash.toLowerCase()===r.toLowerCase());if(!p)throw Error(`Anchor '${i.hash}' declared pruned hash '${e}' but container '${c}' did not contain it`);let m=typeof p.content==`string`?new TextEncoder().encode(p.content):p.content instanceof Uint8Array?p.content:Buffer.from(p.content),h={hash:p.hash,content:m,gTime:p.g_time||p.created_at||`1970-01-01T00:00:00.000Z`},g=bi(h),_;if(o.successors){let e=o.successors.find(([e])=>e===r||e.toLowerCase().endsWith(n));e&&(_=e[1])}if(!t.original&&_&&t.working)try{return Yi(_,t)}catch{}return{record:h,outcome:g,fromArchive:!0,..._?{successor:_}:{}}}throw Error(`Record '${e}' could not be resolved in working tape or any lineage anchor`)}function Xi(e){return e&&typeof e.prepare==`function`?e:e&&e.db&&typeof e.db.prepare==`function`?e.db:e&&e.rawDb&&typeof e.rawDb.prepare==`function`?e.rawDb:null}function Zi(e){let t=Xi(e);if(t)try{return t.prepare(`SELECT hash, content, g_time FROM card`).all().map(e=>{let t=Buffer.isBuffer(e.content)?new Uint8Array(e.content):e.content instanceof Uint8Array?e.content:new TextEncoder().encode(String(e.content));return{hash:e.hash,content:t,gTime:e.g_time}})}catch{return[]}return e&&typeof e.records==`function`?e.records():e&&e.list?e.list().map(e=>{let t=new TextEncoder().encode(JSON.stringify(e.toJSON?e.toJSON():e));return{hash:e.hash?e.hash.asHex?e.hash.asHex():String(e.hash):``,content:t,gTime:e.gTime||e.g_time||``}}):[]}var Qi=new Map;function $i(e){let t=typeof e==`string`?e:new TextDecoder(`utf-8`,{fatal:!1}).decode(e);try{let e=JSON.parse(t);if(e&&Array.isArray(e.entries))return e.entries}catch{}let n=t.split(`
27
+ `).filter(e=>e.trim().length>0),r=[];for(let e of n){let t=e.split(`:`);if(t.length>=4){let e=t[0],n=t.length===5?`${t[1]}:${t[2]}`:t[1],i=t.length===5?t[3]:t[2];r.push({name:e,hash:n,isDirectory:i===`dir`})}}return r}function ea(e,t,n){let r=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase(),i=Qi.get(r);if(i)return i;let a=new Set([r,`blake3:${r}`]),o=[r],s=new Set([r]);for(;o.length>0;){let e=o.shift(),r,i=t.get(A.fromHex(e));if(i)i.payload.kind===`structured`||i.payload.kind===`text`?r=new TextEncoder().encode(typeof i.payload.value==`string`?i.payload.value:JSON.stringify(i.payload.value)):i.payload.kind===`binary`&&(r=i.payload.data);else if(n)try{let i=Yi(`blake3:${e}`,{archiveDir:n,working:t});i&&i.record&&(r=i.record.content)}catch{}if(r)for(let e of $i(r)){let t=e.hash.includes(`:`)?e.hash.split(`:`)[1].toLowerCase():e.hash.toLowerCase();a.add(t),a.add(e.hash.toLowerCase()),e.isDirectory&&!s.has(t)&&(s.add(t),o.push(t))}}return Qi.set(r,a),a}var ta=class{id=`ipfs`;capabilities={role:`replica`,conditionalPut:!1,rangeRead:!1,nativeAddress:`cid`};#e=new Map;#t=new Map;#n=new Map;#r=new Map;#i=[];#a=new Map;constructor(e={}){}computeCid(e){return`bafybeiclm${de(`sha256`,e).slice(0,32)}`}getCidForHash(e){let t=typeof e==`string`?e.toLowerCase():e.asPrefixed().toLowerCase(),n=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase();if(this.#e.has(t))return this.#e.get(t);for(let[e,r]of this.#e.entries())if(e===t||e.toLowerCase().endsWith(`:${n}`))return r}getHashForCid(e){return this.#t.get(e)}getProviderRef(e){return this.getCidForHash(e)}publishScope(e,t,n){if(!n?.allowIpfs)return{publishedCount:0,cids:[]};let r=ea(e,t),i=[];for(let e of r){let n=typeof t.getRecord==`function`?t.getRecord(e):void 0;if(!n){let r=e.includes(`:`)?e.split(`:`)[1]:e,i=t.get(A.fromHex(r));if(i){let e=typeof i.toPreimage==`function`?i.toPreimage():new TextEncoder().encode(JSON.stringify(i.toJSON()));n={hash:i.hash.asHex(),content:e,gTime:i.gTime||i.g_time||Wr(i.hash.algorithm)}}}if(n){this.putRecord(n);let e=Si(n).asPrefixed(),t=this.getCidForHash(e);i.some(t=>t.hash===e)||i.push({hash:e,cid:t})}}return{publishedCount:i.length,cids:i}}putRecord(e){let t=bi(e);if(t.status===`malformed`||t.status===`declared-mismatch`)throw Error(`Record verification failed: ${t.status}`);let n=Si(e).asPrefixed();if(this.#n.has(n))return!1;this.#n.set(n,e);let r=this.computeCid(e.content);return this.#e.set(n,r),this.#t.set(r,n),!0}getRecord(e){let t=typeof e==`string`?e.includes(`:`)?e:`blake3:${e.toLowerCase()}`:e.asPrefixed(),n=this.#n.get(t);if(!n){let t=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase();for(let[e,r]of this.#n.entries())if(e.endsWith(`:${t}`)){n=r;break}}if(!n)return;let r=bi(n);if(r.status!==`malformed`&&r.status!==`declared-mismatch`)return n}getByCid(e){let t=this.#t.get(e);if(!t)return;let n=this.#n.get(t);if(!n||this.computeCid(n.content)!==e)return;let r=bi(n);if(r.status!==`malformed`&&r.status!==`declared-mismatch`)return n}put(e,t){let n=typeof t.toPreimage==`function`?t.toPreimage():new TextEncoder().encode(JSON.stringify(t.toJSON())),r=e.algorithm,i=t.gTime||t.g_time||Wr(r);return this.putRecord({hash:e.asHex(),content:n,gTime:i})}get(e){let t=this.getRecord(e);if(!t)return;let n=e.asHex().toLowerCase();try{let r=new TextDecoder(`utf-8`,{fatal:!0}).decode(t.content),i=JSON.parse(r);if(i&&typeof i==`object`){if(`uri`in i&&`payload`in i)return M.fromJSON(i);if(`kind`in i){let t=ke(i);return M.fromStorage(`mcard:hash/${n}`,e,t,new Map,j.create(`did:clm:agent:ipfs`),0)}}}catch{}let r={kind:`binary`,mimeType:`application/octet-stream`,data:t.content};return M.fromStorage(`mcard:raw/${n}`,e,r,new Map,j.create(`did:clm:agent:ipfs`),0)}has(e){return!!this.getRecord(e)}list(){let e=[];for(let[t]of this.#n){let n=A.fromPrefixed(t),r=this.get(n);r&&e.push(r)}return e}records(){return Array.from(this.#n.values())}listRecords(){return this.records()}count(){return this.#n.size}deleteCard(e){throw Error(`IPFS replica driver is append-only: delete is not supported`)}registerHandle(e,t){let n=typeof e==`string`?e:e.asString(),r=typeof t==`string`?t.includes(`:`)?t.split(`:`)[1].toLowerCase():t.toLowerCase():t.asHex().toLowerCase(),i=this.#r.get(n)??[];i.length>0&&i[i.length-1]===r||(i.push(r),this.#r.set(n,i))}resolveHandle(e){let t=typeof e==`string`?e:e.asString(),n=this.#r.get(t);if(!n||n.length===0)return;let r=n[n.length-1];return A.fromHex(r)}handleHistory(e){let t=typeof e==`string`?e:e.asString(),n=this.#r.get(t);return n?n.map(e=>A.fromHex(e)):[]}appendTransition(e){let t=Di(e);return this.putRecord(t),this.#i.push(e),e.kind===`TOMBSTONE`?this.#a.set(e.handle,null):e.kind===`RELOCATE`?(this.#a.set(e.handle,null),e.toHandle&&e.to&&this.#a.set(e.toHandle,e.to)):e.to&&this.#a.set(e.handle,e.to),t}transitions(e){if(!e)return[...this.#i];let t=P(e);return this.#i.filter(n=>{let r=n.handle===e||P(n.handle)===t,i=n.kind===`RELOCATE`&&n.toHandle&&(n.toHandle===e||P(n.toHandle)===t);return r||i})}head(e){let t=P(e);if(this.#a.has(e))return this.#a.get(e)??null;if(this.#a.has(t))return this.#a.get(t)??null;for(let n=this.#i.length-1;n>=0;n--){let r=this.#i[n];if(r.handle===e||P(r.handle)===t||r.kind===`RELOCATE`&&r.toHandle&&(r.toHandle===e||P(r.toHandle)===t))return r.to}return null}snapshot(){return{timestamp:Date.now(),cardCount:this.#n.size,records:new Map(this.#n),hashToCid:new Map(this.#e),cidToHash:new Map(this.#t)}}restore(e){let t=e;t.records&&(this.#n=new Map(t.records)),t.hashToCid&&(this.#e=new Map(t.hashToCid)),t.cidToHash&&(this.#t=new Map(t.cidToHash))}};Li({id:`ipfs`,priority:-20,capabilities:{role:`replica`,conditionalPut:!1,rangeRead:!1,nativeAddress:`cid`},isSupported:()=>!0,createBackend:e=>new ta(e)});function na(e){let t=e.trim();if(!t)return{};if(t.startsWith(`{`)&&t.endsWith(`}`))try{return JSON.parse(t)}catch{}return aa(e)}function ra(e){let t=!1,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i===`'`&&!n)t&&e[r+1]===`'`?r++:t=!t;else if(i===`"`&&!t)i===`"`&&(r===0||e[r-1]!==`\\`)&&(n=!n);else if(i===`#`&&!t&&!n&&(r===0||/\s/.test(e[r-1])))return e.slice(0,r)}return e}function ia(e,t){if(t===`'`){let t=!1;for(let n=1;n<e.length;n++)e[n]===`'`&&(e[n+1]===`'`?n++:t=!0);return t}if(t===`"`){let t=!1;for(let n=1;n<e.length;n++)e[n]===`"`&&e[n-1]!==`\\`&&(t=!0);return t}return!0}function aa(e){let t=e.split(/\r?\n/),n={},r=[{indent:-1,container:n}];for(let e=0;e<t.length;e++){let n=t[e],i=ra(n);if(!i.trim())continue;let a=n.search(/\S/),o=i.trim();for(;r.length>1&&r[r.length-1].indent>=a;)r.pop();let s=r[r.length-1];if(o.startsWith(`- `)){let n=o.slice(2).trim(),i;if(Array.isArray(s.container))i=s.container;else{i=[];let e=r.length>1?r[r.length-2]:null;e&&s.key&&!Array.isArray(e.container)?e.container[s.key]=i:s.key&&(s.container[s.key]=i),s.container=i}if(n.includes(`: `)&&!n.startsWith(`"`)&&!n.startsWith(`'`)){let o={};i.push(o);let s=n.indexOf(`: `),c=n.slice(0,s).trim(),l=n.slice(s+2).trim();if(l.startsWith(`'`)&&!ia(l,`'`)||l.startsWith(`"`)&&!ia(l,`"`)){let n=l[0],r=!1;for(;e+1<t.length;){e++;let i=t[e],o=ra(i);if(!o.trim()){r=!0;continue}if(i.search(/\S/)<=a){e--;break}if(l+=(r?`
28
+ `:` `)+o.trim(),r=!1,ia(l,n))break}}o[c]=oa(l),r.push({indent:a,container:o})}else{if(n.startsWith(`'`)&&!ia(n,`'`)||n.startsWith(`"`)&&!ia(n,`"`)){let r=n[0],i=!1;for(;e+1<t.length;){e++;let o=t[e],s=ra(o);if(!s.trim()){i=!0;continue}if(o.search(/\S/)<=a){e--;break}if(n+=(i?`
29
+ `:` `)+s.trim(),i=!1,ia(n,r))break}}i.push(oa(n))}continue}let c=o.indexOf(`:`);if(c>0){let n=o.slice(0,c).trim(),i=o.slice(c+1).trim();if(i===``){let e={};if(Array.isArray(s.container)){let t={};t[n]=e,s.container.push(t)}else s.container[n]=e;r.push({indent:a,container:e,key:n})}else{if(i.startsWith(`'`)&&!ia(i,`'`)||i.startsWith(`"`)&&!ia(i,`"`)){let n=i[0],r=!1;for(;e+1<t.length;){e++;let o=t[e],s=ra(o);if(!s.trim()){r=!0;continue}if(o.search(/\S/)<=a){e--;break}if(i+=(r?`
30
+ `:` `)+s.trim(),r=!1,ia(i,n))break}}else if(!i.startsWith(`'`)&&!i.startsWith(`"`)&&!i.startsWith(`{`)&&!i.startsWith(`[`)){let n=!1;for(;e+1<t.length;){let r=t[e+1],o=ra(r);if(!o.trim()){n=!0,e++;continue}if(r.search(/\S/)<=a)break;let s=o.trim();if(s.startsWith(`- `)||/^[A-Za-z0-9_.-]+:\s*/.test(s))break;e++,i+=(n?`
31
+ `:` `)+s,n=!1}}let r=oa(i);if(Array.isArray(s.container)){let e={};e[n]=r,s.container.push(e)}else s.container[n]=r}}}return n}function oa(e){if(e===``||e===`~`||e===`null`)return null;if(e===`true`||e===`yes`||e===`on`)return!0;if(e===`false`||e===`no`||e===`off`)return!1;if(e.startsWith(`'`)&&e.endsWith(`'`)&&e.length>=2)return e.slice(1,-1).replace(/''/g,`'`);if(e.startsWith(`"`)&&e.endsWith(`"`)&&e.length>=2)try{return JSON.parse(e)}catch{return e.slice(1,-1).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`).replace(/\\n/g,`
32
+ `).replace(/\\t/g,` `).replace(/\\r/g,`\r`)}if(e.startsWith(`{`)&&e.endsWith(`}`))try{return JSON.parse(e)}catch{}if(e.startsWith(`[`)&&e.endsWith(`]`)){let t=e.slice(1,-1).trim();return t?t.split(`,`).map(e=>oa(e.trim())):[]}if(/^-?\d+(\.\d+)?$/.test(e)){let t=Number(e);if(!isNaN(t))return t}return e}var sa=class extends Error{code;constructor(e,t){super(`[${e}] ${t}`),this.code=e,this.name=`StorageError`}};function ca(e,t=``){let n=e.replace(/^\/+/,``),r=t.replace(/^\/+/,``).replace(/\/+$/,``),i=r===`mcard`?``:r;if(n.startsWith(`mcard:`)){let e=n.slice(6).replace(/^\/+/,``);return!i||e===i||e.startsWith(i+`/`)?`mcard:${e}`:`mcard:${i}/${e}`}return i?`mcard:${i}/${n}`:`mcard:${n}`}function la(e){let t=e.fragment?`#${e.fragment.replace(/^#/,``)}`:``;return e.type===`hash`?`mcard://hash/${e.target}${t}`:`mcard://handle/${e.target}${t}`}var ua=class{#e;#t;#n;#r=new Map;#i=new Map;#a=new Map;#o=[];#s=new Map;constructor(e={}){this.#e=e.dbName||`clm_cas_db`,this.#t=e.version||1,this.#n=e.idbFactory||(typeof globalThis<`u`?globalThis.indexedDB:void 0),this.#c()}#c(){if(this.#n&&typeof this.#n.open==`function`)try{let e=this.#n.open(this.#e,this.#t);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(`card`)||t.createObjectStore(`card`,{keyPath:`hash`}),t.objectStoreNames.contains(`handle_registry`)||t.createObjectStore(`handle_registry`,{keyPath:`handle`}),t.objectStoreNames.contains(`handle_history`)||t.createObjectStore(`handle_history`,{keyPath:`id`,autoIncrement:!0}),t.objectStoreNames.contains(`transitions`)||t.createObjectStore(`transitions`,{autoIncrement:!0})}}catch{}}put(e,t){let n=e.asHex().toLowerCase();if(this.#r.has(n))return!1;this.#r.set(n,t);let r=typeof t.toPreimage==`function`?t.toPreimage():new TextEncoder().encode(JSON.stringify(t.toJSON())),i=Wr(e.algorithm),a={hash:`${e.algorithm}:${n}`,content:r,gTime:i};return this.#i.set(n,a),this.#l(a),!0}get(e){let t=e.asHex().toLowerCase(),n=this.#r.get(t);if(n)return n;let r=this.getRecord(t);if(!r)return;try{let n=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(r.content));if(n&&typeof n==`object`){if(`uri`in n&&`payload`in n){let e=M.fromJSON(n);return this.#r.set(t,e),e}if(`kind`in n){let r=ke(n),i=M.fromStorage(`mcard:hash/${t}`,e,r,new Map,j.create(`did:clm:agent:stored`),0);return this.#r.set(t,i),i}}}catch{}let i=M.create(`mcard:raw/${t}`,{kind:`binary`,mimeType:`application/octet-stream`,data:r.content},e,0);return this.#r.set(t,i),i}has(e){let t=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase();return this.#i.has(t)}list(){let e=[];for(let[t]of this.#i.entries()){let n=this.get(A.fromHex(t));n&&e.push(n)}return e}count(){return this.#i.size}putRecord(e){let t=bi(e);if(t.status===`malformed`||t.status===`declared-mismatch`)throw Error(`Record verification failed: ${t.status}`);let n=e.hash.includes(`:`)?e.hash.split(`:`)[1].toLowerCase():e.hash.toLowerCase();return!this.#i.has(n)&&(this.#i.set(n,e),this.#l(e),!0)}getRecord(e){let t=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase();return this.#i.get(t)}getRaw(e){return this.getRecord(e)?.content}registerHandle(e,t){let n=typeof e==`string`?e:e.asString?e.asString():String(e),r=typeof t==`string`?t.includes(`:`)?t.split(`:`)[1].toLowerCase():t.toLowerCase():t.asHex().toLowerCase(),i=this.#a.get(n)??[];i[i.length-1]!==r&&(i.push(r),this.#a.set(n,i),this.#s.set(n,`blake3:${r}`),this.#d(n,r))}resolveHandle(e){let t=typeof e==`string`?e:e.asString?e.asString():String(e),n=this.#a.get(t);if(!n||n.length===0)return;let r=n[n.length-1];return A.fromHex(r)}handleHistory(e){let t=typeof e==`string`?e:e.asString?e.asString():String(e),n=this.#a.get(t);return n?n.map(e=>A.fromHex(e)):[]}removeHandle(e){let t=typeof e==`string`?e:String(e);this.#a.delete(t),this.#s.delete(t)}setHead(e,t){let n=typeof e==`string`?e:String(e);if(t===null){this.removeHandle(n);return}let r=t.includes(`:`)?t.split(`:`)[1].toLowerCase():t.toLowerCase();this.registerHandle(n,A.fromHex(r))}head(e){let t=typeof e==`string`?e:String(e);return this.#s.get(t)??null}appendTransition(e){let t=yi(new TextEncoder().encode(JSON.stringify(e)));return this.putRecord(t),this.#o.push(e),this.#u(e),t}transitions(e){return e?this.#o.filter(t=>t.handle===e):[...this.#o]}async hydrate(){if(this.#n&&typeof this.#n.open==`function`)return new Promise(e=>{try{let t=this.#n.open(this.#e,this.#t);t.onsuccess=()=>{let n=t.result,r=Array.from(n.objectStoreNames),i=n.transaction(r,`readonly`);if(r.includes(`card`)){let e=i.objectStore(`card`).getAll();e.onsuccess=()=>{if(Array.isArray(e.result))for(let t of e.result){let e=t.hash.includes(`:`)?t.hash.split(`:`)[1].toLowerCase():t.hash.toLowerCase();this.#i.set(e,t)}}}if(r.includes(`transitions`)){let e=i.objectStore(`transitions`).getAll();e.onsuccess=()=>{Array.isArray(e.result)&&(this.#o.length=0,this.#o.push(...e.result))}}if(r.includes(`handle_registry`)){let e=i.objectStore(`handle_registry`).getAll();e.onsuccess=()=>{if(Array.isArray(e.result)){for(let t of e.result)if(t.handle&&t.currentHash){this.#s.set(t.handle,`blake3:${t.currentHash}`);let e=this.#a.get(t.handle)||[];e.includes(t.currentHash)||(e.push(t.currentHash),this.#a.set(t.handle,e))}}}}i.oncomplete=()=>e(),i.onerror=()=>e()},t.onerror=()=>e()}catch{e()}})}snapshot(){return{timestamp:Date.now(),cardCount:this.count(),records:new Map(this.#i),handles:new Map(Array.from(this.#a.entries()).map(([e,t])=>[e,[...t]])),transitions:[...this.#o],heads:new Map(this.#s)}}restore(e){let t=e;if(t.records){this.#i.clear();for(let[e,n]of t.records.entries())this.#i.set(e,n)}if(t.handles){this.#a.clear();for(let[e,n]of t.handles.entries())this.#a.set(e,[...n])}if(t.transitions&&(this.#o.length=0,this.#o.push(...t.transitions)),t.heads){this.#s.clear();for(let[e,n]of t.heads.entries())this.#s.set(e,n)}}close(){}#l(e){if(this.#n)try{let t=this.#n.open(this.#e,this.#t);t.onsuccess=()=>{let n=t.result;try{n.transaction(`card`,`readwrite`).objectStore(`card`).put(e)}catch{}}}catch{}}#u(e){if(this.#n)try{let t=this.#n.open(this.#e,this.#t);t.onsuccess=()=>{let n=t.result;try{n.transaction(`transitions`,`readwrite`).objectStore(`transitions`).put(e)}catch{}}}catch{}}#d(e,t){if(this.#n)try{let n=this.#n.open(this.#e,this.#t);n.onsuccess=()=>{let r=n.result;try{let n=r.transaction([`handle_registry`,`handle_history`],`readwrite`);n.objectStore(`handle_registry`).put({handle:e,currentHash:t}),n.objectStore(`handle_history`).put({handle:e,hash:t,timestamp:Date.now()})}catch{}}}catch{}}};function da(){Li({id:`indexeddb`,priority:5,isSupported:(e,t)=>e.isBrowser&&!t?.forceMemory&&!t?.sqlJsDb,createBackend:e=>new ua(e)})}function fa(e){return{backendSnapshot:e.backend.snapshot(),handles:new Map(Array.from(e.handles.entries()).map(([e,t])=>[e,{...t}])),history:e.history.map(e=>({...e})),movedHandles:new Map(e.movedHandles||[]),clock:e.clock?.toJSON()}}function pa(e,t){e.backend.restore(t.backendSnapshot),e.handles.clear();for(let[n,r]of t.handles)e.handles.set(n,{...r});if(e.history.length=0,e.history.push(...t.history.map(e=>({...e}))),e.movedHandles&&(e.movedHandles.clear(),t.movedHandles))for(let[n,r]of t.movedHandles)e.movedHandles.set(n,r)}var ma=class e{entries;constructor(e=new Map){this.entries=e instanceof Map?new Map(e):new Map(Object.entries(e))}get(e){return this.entries.get(e)??0}increment(t){let n=new Map(this.entries),r=n.get(t)??0;return n.set(t,r+1),new e(n)}merge(t){let n=new Map(this.entries);for(let[e,r]of t.entries.entries()){let t=n.get(e)??0;n.set(e,Math.max(t,r))}return new e(n)}compare(e){let t=!1,n=!1,r=new Set([...this.entries.keys(),...e.entries.keys()]);for(let i of r){let r=this.get(i),a=e.get(i);r>a&&(t=!0),r<a&&(n=!0)}return!t&&!n?`equal`:t&&!n?`after`:!t&&n?`before`:`concurrent`}toJSON(){return Object.fromEntries(this.entries)}static fromJSON(t){return new e(t)}},ha=e=>typeof e?.asString==`function`?e.asString():String(e??`did:clm:agent:default`),ga=class e{state;contextPrefix;constructor(e,t=``){this.state=e,this.contextPrefix=t.replace(/^\/+/,``).replace(/\/+$/,``),this.state.movedHandles||(this.state.movedHandles=new Map)}get clock(){return this.state.clock||(this.state.clock=new ma),this.state.clock}set clock(e){this.state.clock=e}get storageBackend(){return this.state.backend}get backend(){return this.storageBackend}static newInMemory(){return new e({backend:new ki,handles:new Map,history:[]})}static newInMemoryScoped(t){return new e({backend:new ki,handles:new Map,history:[]},t)}static createMemory(t=``){return t?e.newInMemoryScoped(t):e.newInMemory()}static createSqlite(t=`:memory:`,n=``){return e.withBackend(new Ni(t),n)}static createSqlJs(t,n=``){return e.withBackend(new Pi(t),n)}static createOptimal(t,n=``){return e.withBackend(Ri(t),n)}static withBackend(t,n=``){let r=new Map,i=new Map,a=()=>new Date().toISOString();if(t.transitions)for(let e of t.transitions())(e.kind===`CREATE`||e.kind===`UPDATE`)&&e.to?r.set(e.handle,{handle:e.handle,currentHash:A.fromPrefixed(e.to),createdAt:a(),updatedAt:a()}):e.kind===`TOMBSTONE`?r.delete(e.handle):e.kind===`RELOCATE`&&(r.delete(e.handle),e.toHandle&&(i.set(e.handle,e.toHandle),e.to&&r.set(e.toHandle,{handle:e.toHandle,currentHash:A.fromPrefixed(e.to),createdAt:a(),updatedAt:a()})));if(r.size===0&&t.getAllHandles)for(let e of t.getAllHandles())try{r.set(e.handle,{handle:e.handle,currentHash:A.fromHex(e.hash),createdAt:a(),updatedAt:a()})}catch{}return new e({backend:t,handles:r,history:[],movedHandles:i},n)}static fromCollection(t,n=``){return e.withBackend(t.storageBackend,n)}withPrefix(t){return new e(this.state,t)}canonicalizeUri(e){return ca(e,this.contextPrefix)}exists(e){return this.state.handles.has(this.canonicalizeUri(e))}snapshot(){return fa(this.state)}restore(e){pa(this.state,e)}registerCardInternal(e,t,n){let r=this.state.handles.get(t);this.state.backend.put(e.hash,e),r&&!r.currentHash.equals(e.hash)&&this.state.history.push({handle:t,previousHash:r.currentHash,changedAt:n}),this.state.handles.set(t,{handle:t,currentHash:e.hash,createdAt:r?r.createdAt:n,updatedAt:n});try{let n=t.replace(/^mcard:/,``).replace(/\//g,`:`);this.state.backend.registerHandle(ge.parse(n),e.hash),t!==n&&this.state.backend.registerHandle(ge.parse(t),e.hash)}catch{}}commitCard(e,t,n,r){let i=this.state.handles.get(t);if(i&&i.currentHash.equals(e.hash)){let t=this.state.backend.get(i.currentHash);if(!t)throw new sa(`CorruptedContent`,`Card content for hash '${e.hash.asHex()}' is missing`);return t}let a=i?this.state.backend.get(i.currentHash):void 0,o=i?this.head(t)||(a?Si(a).asPrefixed():i.currentHash.asPrefixed()):null,s=Si(e).asPrefixed(),c=i?`UPDATE`:`CREATE`,l,u=typeof e.author?.asString==`function`?e.author.asString():String(e.author);try{let n=e.payload?.mimeType||e.payload?.value?.mimeType||(t.endsWith(`.json`)?`application/json`:t.endsWith(`.csv`)?`text/csv`:t.endsWith(`.svg`)?`image/svg+xml`:t.endsWith(`.md`)?`text/markdown`:`text/plain`),i=yi(JSON.stringify({uri:t,author:u,sequence:e.sequence,mime:n}),{did:u,algorithm:r});this.state.backend.putRecord?.(i),l=Si(i).asPrefixed()}catch{}this.clock=this.clock.increment(u);let d={kind:c,handle:t,from:o,to:s,...l?{meta:l}:{},clock:this.clock.toJSON(),author:u};return this.state.backend.appendTransition?.(d),this.registerCardInternal(e,t,n),e}writeFile(e,t,n=j.create(`did:clm:agent:default`)){let r=typeof n==`string`?j.create(n):n??j.create(`did:clm:agent:default`),i=this.canonicalizeUri(e),a=this.state.handles.get(i)?this.state.history.filter(e=>e.handle===i).length+2:1,o=M.create(i,Te(t),r,a);return this.commitCard(o,i,new Date().toISOString(),ue())}putContent(e,t,n){return this.writeFile(e,t,n)}put(e){return this.putCard(e),!0}putCard(e){let t=this.canonicalizeUri(e.uri);if(!A.compute(e.toPreimage(),e.hash.algorithm).equals(e.hash))throw new sa(`CorruptedContent`,`MCard hash '${e.hash.asPrefixed()}' does not match its payload preimage`);return this.commitCard(e,t,new Date().toISOString(),e.hash.algorithm)}readFile(e){let t=this.canonicalizeUri(e),n=this.state.handles.get(t);if(!n){let e=this.state.movedHandles?.get(t);throw e?new sa(`CardNotFound`,`Handle '${t}' moved to '${e}'`):new sa(`CardNotFound`,`Handle '${t}' not found in MCardFs`)}let r=this.state.backend.get(n.currentHash);if(!r)throw new sa(`CorruptedContent`,`Card content for hash '${n.currentHash.asHex()}' not found`);if(!r.hash.equals(n.currentHash))throw new sa(`CorruptedContent`,`Cryptographic mismatch for handle '${t}': registry=${n.currentHash.asHex()} stored=${r.hash.asHex()}`);return r}readFileByHash(e){let t=typeof e==`string`?A.parse(e):e,n=this.state.backend.get(t);if(!n)throw new sa(`CardNotFound`,`Card with hash '${t.asHex()}' not found in CAS storage`);return n}statFile(e){let t=this.canonicalizeUri(e),n=this.state.handles.get(t);if(!n)throw new sa(`CardNotFound`,`Handle '${t}' not found`);let r=this.state.backend.get(n.currentHash);return{uri:t,hash:n.currentHash,sizeBytes:r?JSON.stringify(r.toJSON()).length:0,createdAt:n.createdAt,updatedAt:n.updatedAt}}listDir(e=``){let t=this.canonicalizeUri(e),n=t.endsWith(`/`)?e=>e.startsWith(t):t===`mcard:`?e=>e.startsWith(`mcard:`):e=>e===t||e.startsWith(t+`/`);return Array.from(this.state.handles.keys()).filter(n).sort((e,t)=>e.localeCompare(t))}get(e){try{if(typeof e==`string`){let t=this.canonicalizeUri(e);if(this.state.handles.has(t))return this.readFile(t);try{return this.readFileByHash(e)}catch{return}}return this.readFileByHash(e)}catch{return}}list(e=``){let t=[];for(let n of this.listDir(e))try{t.push(this.readFile(n))}catch{}return t}deleteFile(e,t=j.create(`did:clm:agent:default`)){let n=this.canonicalizeUri(e),r=this.state.handles.get(n);if(!r)throw new sa(`CardNotFound`,`Handle '${n}' not found for deletion`);let i=this.state.backend.appendTransition;if(!i)throw new sa(`TransactionFailed`,`Backend cannot persist a TOMBSTONE transition for '${n}'; refusing to drop its registry history`);let a=this.state.backend.get(r.currentHash),o=this.head(n)||(a?Si(a).asPrefixed():r.currentHash.asPrefixed()),s=ha(t);this.clock=this.clock.increment(s);let c={kind:`TOMBSTONE`,handle:n,from:o,to:null,clock:this.clock.toJSON(),author:s},l=i.call(this.state.backend,c),u=n.replace(/^mcard:/,``).replace(/\//g,`:`),d=A.fromHex(l.hash);this.state.backend.registerHandle(ge.parse(u),d),n!==u&&this.state.backend.registerHandle(ge.parse(n),d),this.state.history.push({handle:n,previousHash:r.currentHash,changedAt:new Date().toISOString()}),this.state.handles.delete(n)}relocate(e,t,n=j.create(`did:clm:agent:default`)){let r=this.canonicalizeUri(e),i=this.canonicalizeUri(t),a=this.state.handles.get(r);if(!a)throw new sa(`CardNotFound`,`Handle '${r}' not found for relocation`);let o=this.state.backend.get(a.currentHash),s=this.head(r)||(o?Si(o).asPrefixed():a.currentHash.asPrefixed()),c=ha(n);this.clock=this.clock.increment(c);let l={kind:`RELOCATE`,handle:r,toHandle:i,from:s,to:s,clock:this.clock.toJSON(),author:c};this.state.backend.appendTransition?.(l),this.state.history.push({handle:r,previousHash:a.currentHash,changedAt:new Date().toISOString()});let u=new Date().toISOString();this.state.handles.delete(r),this.state.movedHandles||(this.state.movedHandles=new Map),this.state.movedHandles.set(r,i),this.state.handles.set(i,{handle:i,currentHash:a.currentHash,createdAt:a.createdAt,updatedAt:u});try{let e=i.replace(/^mcard:/,``).replace(/\//g,`:`);this.state.backend.registerHandle(ge.parse(e),a.currentHash)}catch{}return{from:r,to:i,hash:a.currentHash}}retire(e,t,n=j.create(`did:clm:agent:default`)){let r=this.canonicalizeUri(e),i=this.state.handles.get(r);if(!i)throw new sa(`CardNotFound`,`Handle '${r}' not found for retirement`);let a=this.state.backend.appendTransition;if(!a)throw new sa(`TransactionFailed`,`Backend cannot persist a TOMBSTONE transition for '${r}'; refusing to drop its registry history`);let o=this.state.backend.get(i.currentHash),s=this.head(r)||Si(o||{hash:i.currentHash.asHex(),gTime:``}).asPrefixed(),c=ha(n),l;if(t)try{let e=yi(JSON.stringify({uri:r,reason:t,retiredAt:new Date().toISOString()}),{did:c});this.state.backend.putRecord?.(e),l=Si(e).asPrefixed()}catch{}this.clock=this.clock.increment(c);let u={kind:`TOMBSTONE`,handle:r,from:s,to:null,...l?{meta:l}:{},clock:this.clock.toJSON(),author:c},d=a.call(this.state.backend,u),f=r.replace(/^mcard:/,``).replace(/\//g,`:`),p=A.fromHex(d.hash);this.state.backend.registerHandle(ge.parse(f),p),r!==f&&this.state.backend.registerHandle(ge.parse(r),p),this.state.history.push({handle:r,previousHash:i.currentHash,changedAt:new Date().toISOString()}),this.state.handles.delete(r)}head(e){let t=this.canonicalizeUri(e);if(this.state.backend.head)return this.state.backend.head(t);let n=this.state.handles.get(t);return n?Si(this.state.backend.get(n.currentHash)||{hash:n.currentHash.asHex(),gTime:``}).asPrefixed():null}transitions(e){let t=e?this.canonicalizeUri(e):void 0;return this.state.backend.transitions?this.state.backend.transitions(t):[]}history(e){let t=this.canonicalizeUri(e),n=this.transitions(t).filter(e=>e.from!==null&&e.from!==void 0).map(e=>({previousHash:A.fromPrefixed(e.from),changedAt:this.state.handles.get(t)?.updatedAt||new Date().toISOString(),kind:e.kind,...e.conflict===void 0?{}:{conflict:e.conflict}})),r=new Set(n.map(e=>e.previousHash.asHex())),i=this.state.history.filter(e=>e.handle===t&&!r.has(e.previousHash.asHex())).map(e=>({previousHash:e.previousHash,changedAt:e.changedAt}));return[...n,...i]}importHistory(e,t=``){let n=new Set(this.state.history.map(e=>`${e.handle}|${e.previousHash.asHex()}|${e.changedAt}`)),r=t.replace(/^\/+/,``).replace(/\/+$/,``),i=0;for(let t of e){let e=String(t.handle).replace(/^\/+/,``),a=this.canonicalizeUri(r?`${r}/${e}`:e),o=typeof t.previousHash==`string`?A.fromHex(t.previousHash):t.previousHash,s=`${a}|${o.asHex()}|${t.changedAt}`;n.has(s)||(n.add(s),this.state.history.push({handle:a,previousHash:o,changedAt:t.changedAt}),i++)}return i}exportHistory(){return this.state.history.map(e=>({handle:e.handle,previousHash:e.previousHash.asHex(),changedAt:e.changedAt}))}ephemeralMount(e,t){let n=this.withPrefix(t),r=t.replace(/^\/+/,``).replace(/\/+$/,``),i=r?`mcard:${r}/`:`mcard:`;return e.disposables.add(()=>{for(let e of Array.from(this.state.handles.keys()))e.startsWith(i)&&this.state.handles.delete(e)}),n}};function _a(e,t=`Function`){if(t!==`Function`||!e||typeof e!=`object`)return`UNKNOWN`;let n=e,r=n.clm??n,i=r.concrete_impl?.process?.type??r.concrete?.process?.type;if(i)return`M:${i}`;let a=r.concrete_impl?.process_behavior_exec?.dispatcher;if(a)return`A:${a}`;let o=r.concrete_impl?.runtime;if(o)return`B:${o}:${r.concrete_impl?.operation??`invoke`}`;let s=r.concrete?.runtime;return s?`C:${s}`:`UNKNOWN`}function va(e){if(typeof e==`string`){let t=e.toLowerCase();return t.includes(`/abstract/`)||t.includes(`:abstract:`)?`definition`:t.includes(`/concrete/`)||t.includes(`:concrete:`)?`proof`:t.includes(`/balanced/`)||t.includes(`:balanced:`)?`theorem`:t.includes(`schema`)||t.includes(`specification`)||t.includes(`.spec.`)?`definition`:`proposition`}if(e&&typeof e==`object`){let t=e,n=t.clm??t;if(n.abstract&&!n.concrete&&!n.balanced)return`definition`;if(n.concrete&&!n.abstract)return`proof`;if(n.balanced||n.abstract&&n.concrete)return`theorem`}return`proposition`}var ya=class e{knowledge;executionLog;mcard;get content_memory(){return this.mcard}get agent_identities(){return this.knowledge}get execution_log(){return this.executionLog}constructor(e){this.knowledge=ga.withBackend(e.knowledge,`knowledge`),this.executionLog=ga.withBackend(e.executionLog,`execution_log`),this.mcard=ga.withBackend(e.mcard,`mcard`)}static newInMemory(){return new e({knowledge:new ki,executionLog:new ki,mcard:new ki})}static withBackends(t){return new e(t)}getPillar(e){switch(e){case`content_memory`:case`mcard`:return this.mcard;case`execution_log`:return this.executionLog;case`agent_identities`:case`knowledge`:return this.knowledge}}savepoint(e=`sp_${Date.now()}`){return{id:e,timestamp:Date.now(),snapshots:{knowledge:this.knowledge.snapshot(),executionLog:this.executionLog.snapshot(),mcard:this.mcard.snapshot()}}}rollback(e){this.knowledge.restore(e.snapshots.knowledge),this.executionLog.restore(e.snapshots.executionLog),this.mcard.restore(e.snapshots.mcard)}rollbackTo(e){this.rollback(e)}release(e){}},ba=class{id=`s3`;#e;#t;get options(){return this.#t}#n=new Map;#r=new Map;#i=[];#a=new Map;capabilities;constructor(e={}){this.#t=e,this.#e=e.bucket||`clm-mcard-vault`,this.capabilities={role:`replica`,conditionalPut:e.conditionalPut??!0,rangeRead:!0}}get bucket(){return this.#e}keyFor(e,t=`blake3`){if(typeof e==`object`&&`content`in e&&`gTime`in e){let t=Si(e);return`objects/${t.algorithm}/${t.asHex().toLowerCase()}`}if(e instanceof A)return`objects/${e.algorithm||t}/${e.asHex().toLowerCase()}`;let n=String(e);if(n.includes(`:`)){let[e,t]=n.split(`:`);return`objects/${e}/${t.toLowerCase()}`}return`objects/${t}/${n.toLowerCase()}`}getProviderRef(e){return this.keyFor(e)}tamperObjectOutOfBand(e,t){let n=this.keyFor(e),r=this.#n.get(n);if(!r)throw Error(`Object not found in bucket for key ${n}`);this.#n.set(n,{...r,body:t})}put(e,t){let n=e.asHex().toLowerCase(),r=e.algorithm,i=`objects/${r}/${n}`;if(this.#n.has(i))return!1;let a=typeof t.toPreimage==`function`?t.toPreimage():new TextEncoder().encode(JSON.stringify(t.toJSON())),o=t.gTime||t.g_time||Wr(r);return this.#n.set(i,{key:i,body:a,metadata:{"x-amz-meta-gtime":o,gtime:o,algorithm:r}}),!0}putRecord(e){let t=bi(e);if(t.status===`malformed`||t.status===`declared-mismatch`)throw Error(`Record verification failed: ${t.status}`);let n=Si(e),r=`objects/${n.algorithm}/${n.asHex().toLowerCase()}`;return!this.#n.has(r)&&(this.#n.set(r,{key:r,body:e.content,metadata:{"x-amz-meta-gtime":e.gTime,gtime:e.gTime,algorithm:n.algorithm}}),!0)}getObjectRaw(e){let t=this.keyFor(e),n=this.#n.get(t);if(!n&&!String(e).includes(`:`)&&!(e instanceof A&&e.algorithm)){let t=typeof e==`string`?e.toLowerCase():e.asHex().toLowerCase();for(let[e,r]of this.#n.entries())if(e.endsWith(`/${t}`)){n=r;break}}return n}getRecord(e){let t=this.keyFor(e),n=this.#n.get(t);if(!n&&!String(e).includes(`:`)&&!(e instanceof A&&e.algorithm)){let t=typeof e==`string`?e.toLowerCase():e.asHex().toLowerCase();for(let[e,r]of this.#n.entries())if(e.endsWith(`/${t}`)){n=r;break}}if(!n)return;let r=n.metadata[`x-amz-meta-gtime`]||n.metadata.gtime||``,i=n.key.split(`/`),a={hash:i[i.length-1],content:n.body,gTime:r},o=bi(a);if(o.status!==`malformed`&&o.status!==`declared-mismatch`)return a}get(e){let t=this.getRecord(e);if(!t)return;let n=e.asHex().toLowerCase();try{let r=new TextDecoder(`utf-8`,{fatal:!0}).decode(t.content),i=JSON.parse(r);if(i&&typeof i==`object`){if(`uri`in i&&`payload`in i)return M.fromJSON(i);if(`kind`in i){let t=ke(i);return M.fromStorage(`mcard:hash/${n}`,e,t,new Map,j.create(`did:clm:agent:replica-s3`),0)}}}catch{}try{let r={kind:`text`,value:new TextDecoder(`utf-8`,{fatal:!0}).decode(t.content)};return M.fromStorage(`mcard:hash/${n}`,e,r,new Map,j.create(`did:clm:agent:replica-s3`),0)}catch{let r={kind:`binary`,mimeType:`application/octet-stream`,data:t.content};return M.fromStorage(`mcard:raw/${n}`,e,r,new Map,j.create(`did:clm:agent:replica-s3`),0)}}has(e){let t=this.keyFor(e);if(this.#n.has(t))return!!this.getRecord(e);let n=typeof e==`string`?e.includes(`:`)?e.split(`:`)[1].toLowerCase():e.toLowerCase():e.asHex().toLowerCase();for(let t of this.#n.keys())if(t.endsWith(`/${n}`))return!!this.getRecord(e);return!1}list(){let e=[];for(let t of this.#n.values()){let n=t.key.split(`/`),r=n[1],i=n[2],a=A.fromHex(i,r),o=this.get(a);o&&e.push(o)}return e}records(){let e=[];for(let t of this.#n.values()){let n=t.key.split(`/`)[2],r=this.getRecord(n);r&&e.push(r)}return e}listRecords(){return this.records()}count(){return this.#n.size}deleteCard(e){throw Error(`S3 replica driver is append-only: delete is not supported (INV-REF-03)`)}registerHandle(e,t){let n=typeof e==`string`?e:e.asString(),r=typeof t==`string`?t.includes(`:`)?t.split(`:`)[1].toLowerCase():t.toLowerCase():t.asHex().toLowerCase(),i=this.#r.get(n)??[];i.length>0&&i[i.length-1]===r||(i.push(r),this.#r.set(n,i))}resolveHandle(e){let t=typeof e==`string`?e:e.asString(),n=this.#r.get(t);if(!n||n.length===0)return;let r=n[n.length-1];return A.fromHex(r)}handleHistory(e){let t=typeof e==`string`?e:e.asString(),n=this.#r.get(t);return n?n.map(e=>A.fromHex(e)):[]}appendTransition(e){let t=Di(e);return this.putRecord(t),this.#i.push(e),e.kind===`TOMBSTONE`?this.#a.set(e.handle,null):e.kind===`RELOCATE`?(this.#a.set(e.handle,null),e.toHandle&&e.to&&this.#a.set(e.toHandle,e.to)):e.to&&this.#a.set(e.handle,e.to),t}transitions(e){if(!e)return[...this.#i];let t=P(e);return this.#i.filter(n=>{let r=n.handle===e||P(n.handle)===t,i=n.kind===`RELOCATE`&&n.toHandle&&(n.toHandle===e||P(n.toHandle)===t);return r||i})}head(e){let t=P(e);if(this.#a.has(e))return this.#a.get(e)??null;if(this.#a.has(t))return this.#a.get(t)??null;for(let n=this.#i.length-1;n>=0;n--){let r=this.#i[n];if(r.handle===e||P(r.handle)===t||r.kind===`RELOCATE`&&r.toHandle&&(r.toHandle===e||P(r.toHandle)===t))return r.to}return null}snapshot(){return{timestamp:Date.now(),cardCount:this.#n.size,objects:new Map(this.#n),handles:new Map(Array.from(this.#r.entries()).map(([e,t])=>[e,[...t]])),transitions:[...this.#i],heads:new Map(this.#a)}}restore(e){let t=e;t.objects&&(this.#n=new Map(t.objects)),t.handles&&(this.#r=new Map(Array.from(t.handles.entries()).map(([e,t])=>[e,[...t]]))),t.transitions&&(this.#i=[...t.transitions]),t.heads&&(this.#a=new Map(t.heads))}};Li({id:`s3`,priority:-10,capabilities:{role:`replica`,conditionalPut:!0,rangeRead:!0},isSupported:()=>!0,createBackend:e=>new ba(e)});function xa(e){return e==null}function Sa(e,t,n){return Object.defineProperty(e,t,{writable:!0,value:n,enumerable:!1})}function Ca(e,t){return arguments.length===1?t=>Ca(e,t):e in globalThis&&t instanceof globalThis[e]||Object.prototype.toString.call(t).slice(8,-1)===e}function wa(e){return Ca(`ArrayBuffer`,e)||Ca(`SharedArrayBuffer`,e)}function Ta(e){return wa(e)||ArrayBuffer.isView(e)}var Ea;(e=>{e.is=wa,e.isSource=Ta;function t(e){return ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e}e.fromSource=t;function n(e){if(e=t(e),typeof Buffer<`u`)return Buffer.from(e).toString(`base64`);let n=``,r=new Uint8Array(e);for(let e=0;e<r.byteLength;e++)n+=String.fromCharCode(r[e]);return btoa(n)}e.toBase64=n;function r(e){return typeof Buffer<`u`?t(Buffer.from(e,`base64`)):Uint8Array.from(atob(e),e=>e.charCodeAt(0))}e.fromBase64=r;function i(e){return e=t(e),typeof Buffer<`u`?Buffer.from(e).toString(`hex`):Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``)}e.toHex=i;function a(e){if(typeof Buffer<`u`)return t(Buffer.from(e,`hex`));let n=e.length%2==0?e:e.slice(0,e.length-1),r=[];for(let e=0;e<n.length;e+=2)r.push(parseInt(`${n[e]}${n[e+1]}`,16));return Uint8Array.from(r).buffer}e.fromHex=a})(Ea||={}),Ea.fromBase64,Ea.toBase64,Ea.fromHex,Ea.toHex;function Da(e,t,n){let r=[],i=0;for(let a=0;a<e.length;a++){let o=e.charCodeAt(a);if(o>=65&&o<=90){if(i===1){let t=e.charCodeAt(a+1);t>=97&&t<=122&&r.push(n),r.push(o+32)}else i!==0&&r.push(n),r.push(o+32);i=1}else o>=97&&o<=122?(r.push(o),i=2):t.includes(o)?(i!==0&&r.push(n),i=0):r.push(o)}return String.fromCharCode(...r)}function Oa(e){return Da(e,[45,95],45)}var ka=Oa,Aa;(e=>{e.millisecond=1,e.second=1e3,e.minute=e.second*60,e.hour=e.minute*60,e.day=e.hour*24,e.week=e.day*7;let t=new Date().getTimezoneOffset();function n(e){t=e}e.setTimezoneOffset=n;function r(){return t}e.getTimezoneOffset=r;function i(n=new Date,r){return typeof n==`number`&&(n=new Date(n)),r===void 0&&(r=t),Math.floor((n.valueOf()/e.minute-r)/1440)}e.getDateNumber=i;function a(n,r){let i=new Date(n*e.day);return r===void 0&&(r=t),new Date(+i+r*e.minute)}e.fromDateNumber=a;let o=RegExp(`^${[`w(?:eek(?:s)?)?`,`d(?:ay(?:s)?)?`,`h(?:our(?:s)?)?`,`m(?:in(?:ute)?(?:s)?)?`,`s(?:ec(?:ond)?(?:s)?)?`].map(e=>`(\\d+(?:\\.\\d+)?${e})?`).join(``)}$`);function s(t){let n=o.exec(t);return n?(parseFloat(n[1])*e.week||0)+(parseFloat(n[2])*e.day||0)+(parseFloat(n[3])*e.hour||0)+(parseFloat(n[4])*e.minute||0)+(parseFloat(n[5])*e.second||0):0}e.parseTime=s;function c(e){let t=s(e);return t?e=Date.now()+t:/^\d{1,2}(:\d{1,2}){1,2}$/.test(e)?e=`${new Date().toLocaleDateString()}-${e}`:/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(e)&&(e=`${new Date().getFullYear()}-${e}`),e?new Date(e):new Date}e.parseDate=c;function l(t){let n=Math.abs(t);return n>=e.day-e.hour/2?Math.round(t/e.day)+`d`:n>=e.hour-e.minute/2?Math.round(t/e.hour)+`h`:n>=e.minute-e.second/2?Math.round(t/e.minute)+`m`:n>=e.second?Math.round(t/e.second)+`s`:t+`ms`}e.format=l;function u(e,t=2){return e.toString().padStart(t,`0`)}e.toDigits=u;function d(e,t=new Date){return e.replace(`yyyy`,t.getFullYear().toString()).replace(`yy`,t.getFullYear().toString().slice(2)).replace(`MM`,u(t.getMonth()+1)).replace(`dd`,u(t.getDate())).replace(`hh`,u(t.getHours())).replace(`mm`,u(t.getMinutes())).replace(`ss`,u(t.getSeconds())).replace(`SSS`,u(t.getMilliseconds(),3))}e.template=d})(Aa||={});var ja=Object.defineProperty,F=(e,t)=>ja(e,`name`,{value:t,configurable:!0}),Ma=class{static{F(this,`DisposableList`)}sn=0;map=new Map;weak=new WeakMap;get length(){return this.map.size}push(e){let t=++this.sn;return this.map.set(t,e),this.weak.set(e,t),()=>this.map.delete(t)}delete(e){let t=this.weak.get(e);return t?this.map.delete(t):!1}clear(){let e=[...this.map.values()];return this.map.clear(),e.reverse()}[Symbol.iterator](){return this.map.values()}[Symbol.for(`nodejs.util.inspect.custom`)](){return[...this]}},I={shadow:Symbol.for(`cordis.shadow`),caller:Symbol.for(`cordis.caller`),receiver:Symbol.for(`cordis.receiver`),original:Symbol.for(`cordis.original`),metadata:Symbol.for(`cordis.metadata`),initHooks:Symbol.for(`cordis.initHooks`),checkProto:Symbol.for(`cordis.checkProto`),effect:Symbol.for(`cordis.effect`),filter:Symbol.for(`cordis.filter`),isolate:Symbol.for(`cordis.isolate`),intercept:Symbol.for(`cordis.intercept`),init:Symbol.for(`cordis.init`),check:Symbol.for(`cordis.check`),config:Symbol.for(`cordis.config`),invoke:Symbol.for(`cordis.invoke`),extend:Symbol.for(`cordis.extend`),tracker:Symbol.for(`cordis.tracker`),resolveConfig:Symbol.for(`cordis.resolveConfig`)},Na=function*(){}.constructor,Pa=async function*(){}.constructor;function Fa(e){return!(!e.prototype||e instanceof Na||Pa!==Function&&e instanceof Pa)}F(Fa,`isConstructor`);function Ia(e,t){if(e===Object.prototype)return t;let n=Object.create(Ia(Object.getPrototypeOf(e),t));for(let t of Reflect.ownKeys(e))Object.defineProperty(n,t,Object.getOwnPropertyDescriptor(e,t));return n}F(Ia,`joinPrototype`);function La(e){return e&&(typeof e==`object`||typeof e==`function`)}F(La,`isObject`);function Ra(e,t){let n=e;for(;n;){let e=Reflect.getOwnPropertyDescriptor(n,t);if(e)return e;n=Object.getPrototypeOf(n)}}F(Ra,`getPropertyDescriptor`);function za(e,t){if(!La(t))return t;if(Object.hasOwn(t,I.shadow))return Object.getPrototypeOf(t);let n=t[I.tracker];return n?Wa(e,t,n):t}F(za,`getTraceable`);function Ba(e,t){return t?new Proxy(e,{get:F((e,n,r)=>n in t&&n!==`constructor`?Reflect.get(t,n,r):Reflect.get(e,n,r),`get`),set:F((e,n,r,i)=>n in t&&n!==`constructor`?Reflect.set(t,n,r,i):Reflect.set(e,n,r,i),`set`)}):e}F(Ba,`withProps`);function Va(e,t,n){return Ba(e,Object.defineProperty(Object.create(null),t,{value:n,writable:!1}))}F(Va,`withProp`);function Ha(e,t,n,r){if(!n)return r;let i=Ra(t,n)?.value;if(!i)return r;let a=i[I.shadow]??i;return Va(r,n,e.extend({[I.shadow]:a}))}F(Ha,`createShadow`);function Ua(e,t,n,r){return new Proxy(t,{apply:F((t,i,a)=>(i===n&&(i=r),za(e,Reflect.apply(t,i,a))),`apply`)})}F(Ua,`createShadowMethod`);function Wa(e,t,n){let r=e[I.shadow]??e,i=e[I.shadow]?Object.getPrototypeOf(e):e,a=new Proxy(t,{get:F((t,a,o)=>{if(a===I.original)return t;if(a===I.caller)return r;if(a===n.property)return i;if(typeof a==`symbol`)return Reflect.get(t,a,o);if(n.associate&&i.reflect.props[`${n.associate}.${a}`])return Reflect.get(e,`${n.associate}.${a}`,Va(e,I.receiver,o));let s,c,l=Ra(t,a);l&&`value`in l?c=l.value:(s=Ha(i,t,n.property,o),c=Reflect.get(t,a,s));let u=c?.[I.tracker];return u?Wa(i,c,u):!n.noShadow&&typeof c==`function`?(s??=Ha(i,t,n.property,o),Ua(i,c,o,s)):c},`get`),set:F((t,r,a,o)=>{if(r===I.original||r===I.caller||r===n.property)return!1;if(typeof r==`symbol`)return Reflect.set(t,r,a,o);if(n.associate&&i.reflect.props[`${n.associate}.${r}`])return Reflect.set(e,`${n.associate}.${r}`,a,Va(e,I.receiver,o));let s=Ha(i,t,n.property,o);return Reflect.set(t,r,a,s)},`set`),apply:F((e,t,r)=>Ga(n.noShadow?a:Ha(i,e,n.property,a),e,t,r),`apply`)});return a}F(Wa,`createTraceable`);function Ga(e,t,n,r){return t[I.invoke]?t[I.invoke].apply(e,r):Reflect.apply(t,n,r)}F(Ga,`applyTraceable`);function Ka(e,t,n){let r=F(function(...e){let t=Wa(r.ctx,r,n);return Reflect.apply(t,this,e)},`self`);return Sa(r,`name`,e),Object.setPrototypeOf(r,t)}F(Ka,`createCallable`);function qa(e,t,n){let r=e.error.stack.split(`
33
+ `);if(typeof t?.stack!=`string`){let e=Error(t),r=e.stack.split(`
34
+ `);throw r.splice(1,1/0,...n()),e.stack=r.join(`
35
+ `),e}let i=t.stack.split(`
36
+ `),a=i.indexOf(r[2]);if(a===-1)throw t;for(a-=e.offset;a>0&&i[a-1].endsWith(` (<anonymous>)`);)--a;throw i.splice(a,1/0,...n()),t.stack=i.join(`
37
+ `),t}F(qa,`handleError`);function Ja(e,t=Ya()){let n={offset:1,error:Error()};try{let r=e(n);return La(r)&&`then`in r?r.then(void 0,e=>qa(n,e,t)):r}catch(e){qa(n,e,t)}}F(Ja,`composeError`);function Ya(e=0){let t=Error();return()=>t.stack.split(`
38
+ `).slice(3+e)}F(Ya,`buildOuterStack`);function Xa(e){return e!==null&&e!==!1&&e!==void 0}F(Xa,`isBailed`);var Za=class{constructor(e){this.ctx=e,Sa(this,I.tracker,{property:`ctx`,noShadow:!0}),this.on(`internal/listener`,function(e,t,n){if(e===`internal/update`&&!n.global)return(this.fiber._hooks[`internal/update`]??=new Ma)[n.prepend?`unshift`:`push`](t)}),this.on(`internal/update`,function(e,t,n){let r=[...this._hooks[`internal/update`]||[]],i=F(()=>(r.shift()??n).call(this,e,t,i),`_next`);return i()},{global:!0,prepend:!0})}ctx;static{F(this,`EventsService`)}_hooks=Object.create(null);_resolve(e,t){let n=typeof t[0]==`object`||typeof t[0]==`function`?t.shift():null,r=t.shift();(typeof r!=`string`||!r.startsWith(`internal/`))&&this._hooks[`internal/dispatch`]?.length&&this.emit(`internal/dispatch`,e,r,t,n);let i=n?.[vo.filter];return[n,(this._hooks[r]||[]).filter(e=>e.global||!i||i.call(n,e.ctx)).map(e=>e.callback)]}dispatch(e,t){let[n,r]=this._resolve(e,t);return r.map(e=>e.bind(n))}async parallel(...e){let[t,n]=this._resolve(`emit`,e),r=(await Promise.allSettled(n.map(async n=>Reflect.apply(n,t,e)))).filter(e=>e.status===`rejected`);if(r.length)throw AggregateError(r.map(e=>e.reason))}emit(...e){let[t,n]=this._resolve(`emit`,e);for(let r of n)Reflect.apply(r,t,e)}async serial(...e){let[t,n]=this._resolve(`serial`,e);for(let r of n){let n=await Reflect.apply(r,t,e);if(Xa(n))return n}}bail(...e){let[t,n]=this._resolve(`bail`,e);for(let r of n){let n=Reflect.apply(r,t,e);if(Xa(n))return n}}waterfall(...e){let[t,n]=this._resolve(`waterfall`,e),r=e.pop(),i=F(()=>{let a=n.shift();if(!a)return r();let o=!1,s=F(()=>{if(o)throw Error(`next() called multiple times`);return o=!0,i()},`next`);return Reflect.apply(a,t,[...e,s])},`dispatch`);return i()}register(e,t,n,r){let i=r.prepend?`unshift`:`push`;return this.ctx.fiber.effect(()=>((this._hooks[t]??=[])[i]({ctx:this.ctx,callback:n,...r}),()=>this.unregister(t,n)),e)}unregister(e,t){let n=this._hooks[e];if(!n)return;let r=n.findIndex(e=>e.callback===t);if(r>=0)return n.splice(r,1),n.length||delete this._hooks[e],!0}on(e,t,n){typeof n!=`object`&&(n={prepend:n}),this.ctx.fiber.assertActive(),t=this.ctx.reflect.bind(t);let r=this.bail(this.ctx,`internal/listener`,e,t,n);if(r)return r;let i=`ctx.on(${typeof e==`string`?JSON.stringify(e):e.toString()})`;return this.register(i,e,t,n)}once(e,t,n){let r=this.on(e,function(...e){return r(),t.apply(this,e)},n);return r}},Qa={s:F(e=>String(e),`s`),d:F(e=>Math.trunc(Number(e)),`d`),i:F(e=>Math.trunc(Number(e)),`i`),f:F(e=>Number(e),`f`),o:F(e=>JSON.stringify(e),`o`),O:F(e=>JSON.stringify(e),`O`),c:F(()=>``,`c`),C:F((e,t,n)=>eo.color(t,eo.code(n.name,t.colors),e),`C`)};function $a(e){return e instanceof Error&&Array.isArray(e.errors)}F($a,`isAggregateError`);var eo=class{constructor(e,t){this.service=t,Object.assign(this,e),this.error=this._method(`error`,0),this.info=this._method(`info`,2),this.warn=this._method(`warn`,1),this.debug=this._method(`debug`,3)}service;static{F(this,`Logger`)}static color(e,t,n,r=``){return e.colors?`\x1B[3${t<8?t:`8;5;`+t}${e.colors>=2?r:``}m${n}\x1B[0m`:``+n}static code(e,t){let n=0;for(let t=0;t<e.length;t++)n=(n<<3)-n+e.charCodeAt(t)+13,n|=0;let r=t?t>=2?no:to:[];return r[Math.abs(n)%r.length]}static format(e,t){let n=t.args.slice();n[0]instanceof Error?(n[0]=n[0].stack||n[0].message,n.unshift(`%s`)):typeof n[0]!=`string`&&n.unshift(`%o`);let r=n.shift();r=r.replace(/%([a-zA-Z%])/g,(r,i)=>{if(r===`%%`)return`%`;let a=e.formatters?.[i]??Qa[i];return typeof a==`function`?a(n.shift(),e,t):r});let i=e.formatters?.o??Qa.o;for(let a of n)typeof a==`object`&&a&&(a=i(a,e,t)),r+=` `+a;let{maxLength:a=10240}=e;return r.split(/\r?\n/g).map(e=>e.slice(0,a)+(e.length>a?`...`:``)).join(`
39
+ `)}_method(e,t){return(...n)=>{if(n.length===1&&n[0]instanceof Error){if(n[0].cause)this[e](n[0].cause);else if($a(n[0])){n[0].errors.forEach(t=>this[e](t));return}}let r=++this.service._snMessage,i=Date.now();for(let a of this.service.exporters.values()){if((a.levels?.[this.name]??a.levels?.default??this.level??2)<t)continue;let o={sn:r,ts:i,type:e,level:t,name:this.name,...this.meta,args:n};a.export(o)}}}},to=[6,2,3,4,5,1],no=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221],ro=class e{static{F(this,`LoggerService`)}bufferSize=1e3;buffer=[];ctx;_snMessage=0;_snExporter=0;exporters=new Map;constructor(e){let t={property:`ctx`,noShadow:!0},n=Ka(`logger`,Ia(Object.getPrototypeOf(this),Function.prototype),t);return Object.assign(n,this),n.ctx=e,Sa(n,I.tracker,t),n.exporter({colors:3,export:F(e=>{n.buffer.push(e);let t=n.buffer.length-n.bufferSize;t===1?n.buffer.shift():t>1&&n.buffer.splice(0,t)},`export`)}),n}exporter(e){return this.ctx.effect(()=>{let t=++this._snExporter;return this.exporters.set(t,e),()=>this.exporters.delete(t)},`ctx.logger.exporter()`)}_resolveConfig(){let e=this.ctx[I.intercept],t=[];for(;`logger`in e;)Object.hasOwn(e,`logger`)&&t.unshift(e.logger),e=Object.getPrototypeOf(e);return Object.assign({},...t)}[I.invoke](e){let t=this._resolveConfig(),n=(this[I.caller]??this.ctx).fiber;return e??=t.name,e??=ka(n.name),new eo({name:e,level:t.level,meta:{fiber:new WeakRef(n)}},this)}static{for(let t of[`error`,`info`,`warn`,`debug`])e.prototype[t]=function(...e){return this()[t](...e)}}},io=Symbol.for(`ValidationError`),ao=class extends TypeError{static{F(this,`ValidationError`)}name=`ValidationError`;constructor(e){super(`invalid config:
40
+ `+e.map(e=>e.path?` - ${e.message} (at ${e.path.join(`.`)})`:` - ${e.message}`).join(`
41
+ `))}};Object.defineProperty(ao.prototype,io,{value:!0});function oo(e,t){if(!e.Config)return t;let n=e.Config[`~standard`].validate(t);if(`then`in n)throw TypeError(`Async config validation is not supported`);if(n.issues)throw new ao(n.issues);return n.value}F(oo,`resolveConfig`);var so=class e extends Error{constructor(t,n){super(n??e.Code[t]),this.code=t}code;static{F(this,`CordisError`)}};(e=>{e.Code={INACTIVE_EFFECT:`cannot create effect on inactive context`}})(so||={});var co=`__INACTIVE__`,lo=class{constructor(e,t,n,r,i){this.parent=e,this.inject=n,this.runtime=r;let a=F(e=>{this._disposables.push(e)},`collect`);if(r){this.uid=e.registry.counter,this.ctx=this.context=e.extend({fiber:this});let n=Object.entries(this.inject);if(n.length){this.ctx[vo.intercept]=Object.create(e[vo.intercept]);for(let[e,t]of n)xa(t)||(this.ctx[vo.intercept][e]=t)}this._runner={epoch:co,getOuterStack:i,execute:F(function(){if(Fa(r.callback)){let e=new r.callback(this.ctx,this.config);for(let t of e?.[I.initHooks]??[])t();return e?.[I.init]?.()}return r.callback(this.ctx,this.config)},`execute`),collect:a},this.context.emit(`internal/plugin`,this);for(let e of Object.keys(this.inject))this._checkImpl(e);this.dispose=e.fiber.effect(()=>{let e=r.fibers.push(this);try{this.config=oo(r,t),this._refresh()}catch(e){this.ctx.logger.error(e),this._error=e}return async()=>{for(this.uid=null,this.context.emit(`internal/plugin`,this),this.ctx.registry.has(r.callback)&&(e(),r.fibers.length||this.ctx.registry.delete(r.callback)),this._setEpoch(co);this.inertia;)await this.inertia}},`ctx.plugin()`)}else this.uid=0,this.ctx=this.context=e,this.state=2,this.store=Object.create(null),this._runner={epoch:``,getOuterStack:i,execute:F(()=>{},`execute`),collect:a},this.dispose=()=>this.restart()}parent;inject;runtime;static{F(this,`Fiber`)}uid;ctx;config;state=0;dispose;store;inertia;_hooks=Object.create(null);_disposables=new Ma;context;_error;_runner;_store=Object.create(null);get name(){let e=this;do{if(e.runtime?.name)return e.runtime.name;e=e.parent.fiber}while(e!==e.parent.fiber);return`root`}assertActive(){if(this.uid===null)throw new so(`INACTIVE_EFFECT`)}_execute(e){let t=e.epoch;return Ja(n=>{let r=F(t=>{if(typeof t==`function`)e.collect(t);else if(!xa(t))throw TypeError(`Invalid effect`)},`safeCollect`),i=e.execute.call(this);if(typeof i==`function`)return e.collect(i);if(!xa(i)){if(!La(i))throw TypeError(`Invalid effect`);if(`then`in i)return i.then(r);if(Symbol.iterator in i){n.error=Error();let e=i[Symbol.iterator]();for(;;){let t=e.next();if(r(t.value),t.done)return}}else if(Symbol.asyncIterator in i){let a=i[Symbol.asyncIterator]();return(async()=>{for(await Promise.resolve(),n.error=Error();;){if(e.epoch!==t)return;let n=await a.next();if(r(n.value),n.done)return}})()}else throw TypeError(`Invalid effect`)}},e.getOuterStack)}effect(e,t=`anonymous`){this.assertActive();let n=[],r=F(()=>{let e;for(let t of n.splice(0).reverse())if(e)e=e.then(t);else{let n=t();La(n)&&`then`in n&&(e=n)}return e},`dispose`),i={label:t,children:[]},a={execute:e,epoch:!0,collect:F(e=>{n.push(e),this._disposables.delete(e),e[I.effect]&&i.children.push(e[I.effect])},`collect`),getOuterStack:Ya()},o;try{o=this._execute(a)}catch(e){throw r(),e}o?.catch(r).catch(e=>this.ctx.logger.error(e));let s=Sa(()=>{if(a.epoch)return a.epoch=!1,o?o.then(r):r()},I.effect,i),c=F(()=>{if(a.epoch)return a.epoch=!1,r()},`disposeAsync`);return s.then=async(e,t)=>Promise.resolve(o).then(()=>c).then(e,t),n.push(this._disposables.push(s)),s}getEffects(){return[...this._disposables].map(e=>e[I.effect]).filter(Boolean)}_getState(){return this.uid===null?4:this._error?3:this._runner.epoch===co?0:2}_updateState(e){let t=this.state;if(this.state=e()??this._getState(),t!==this.state&&(this.context.emit(`internal/status`,this,t),t===2||this.state===2))for(let e of Reflect.ownKeys(this.ctx.reflect.store)){let t=this.ctx.reflect.store[e];t.fiber===this&&this.ctx.reflect.notify([t.name])}}_checkImpl(e){let t=this.ctx.reflect._getImpl(e,!0);if(!t)return delete this._store[e];try{if(t.check&&!t.check.call(za(this.ctx,t.value)))return delete this._store[e]}catch(n){return t.fiber.ctx.logger.error(n),delete this._store[e]}this._store[e]=t}_refresh(){let e=!1;e=``;for(let t of Object.keys(this.inject)){let n=this._store[t];if(!n){e=co;break}e+=`:`+n.fiber.uid}this._setEpoch(e)}_setEpoch(e){let t=this._runner.epoch;e!==t&&(this._error||(this._runner.epoch=e,!this.inertia&&this._updateState(()=>e!==co&&t===co?(this.inertia=this._reload(),1):(this.inertia=this._unload(),5))))}async _reload(){this.store={...this._store};let e=this._runner.epoch;try{await Promise.resolve(),await this._execute(this._runner)}catch(e){this.ctx.logger.error(e),this._error=e,this._runner.epoch=co}this._updateState(()=>{if(this._runner.epoch===e)this.inertia=void 0;else return this.inertia=this._unload(),5})}async _unload(){await Promise.all(this._disposables.clear().map(async e=>{try{await Ja(async t=>{await Promise.resolve(),t.error=Error(),await e()},this._runner.getOuterStack)}catch(e){this.ctx.logger.error(e)}})),this.store=void 0,this._updateState(()=>{if(this._runner.epoch===co)this.inertia=void 0;else return this.inertia=this._reload(),1})}async await(){for(;this.inertia;)await this.inertia;if(this._error)throw this._error;return this}async restart(){let e=this.ctx.fiber;e.assertActive(),e._setEpoch(co),e._refresh(),await e.await()}update(e,t=!1){let n=this.ctx.fiber;n.assertActive(),e=oo(n.runtime,e);let r=n.context.waterfall(n,`internal/update`,e,t,()=>(n.config=e,n._error=void 0,n.restart()));if(r===void 0)return;let i=Promise.resolve(r);return i.catch(()=>{}),i}};function uo(e){let t=e.stack.split(`
42
+ `);return t.splice(0,2,`Error: ${e.message}`),e.stack=t.join(`
43
+ `),e}F(uo,`enhanceError`);var fo=[`prototype`,`then`];function po(e){return typeof e==`symbol`||fo.includes(e)||parseInt(e).toString()===e||e.startsWith(`_`)}F(po,`isSpecialProperty`);var mo=class{constructor(e){this.ctx=e,Sa(this,I.tracker,{property:`ctx`,noShadow:!0}),this.mixin(`reflect`,[`get`,`set`,`provide`,`accessor`,`mixin`]),this.mixin(`fiber`,[`runtime`,`effect`]),this.mixin(`registry`,[`inject`,`plugin`]),this.mixin(`events`,[`on`,`once`,`parallel`,`emit`,`serial`,`bail`,`waterfall`])}ctx;static{F(this,`ReflectService`)}static handler={get:F((e,t,n)=>{if(po(t))return Reflect.get(e,t,n);if(Reflect.has(e,t))return za(n,Reflect.get(e,t,n));let r=Error(`cannot get property "${t}" without inject`);try{let i=e.reflect.props[t];if(i?.type===`accessor`)return i.get.call(n,n[I.receiver],r);let a=n[I.shadow]??n;return a.fiber.runtime?n.events.waterfall(`internal/get`,n,t,r,()=>{let i=e[I.isolate][t],o=a.fiber;for(;;){let e=o.store?.[t];if(e)return za(n,e.value);if(t in o.inject)throw r.message=`cannot get required service "${t}" in inactive context`,r;if(!o.runtime||o.parent[I.isolate][t]!==i)throw r;o=o.parent.fiber}}):n.reflect.get(t,!1)}catch(e){throw e===r?uo(e):e}},`get`),set:F((e,t,n,r)=>{if(po(t))return Reflect.set(e,t,n,r);let i=Error(`cannot set property "${t}" without provide`),a=e.reflect.props[t];if(!a){if(!r.fiber.runtime)return Reflect.set(e,t,n,r);throw uo(i)}try{return a.type===`accessor`?a.set?a.set.call(r,n,r[I.receiver],i):!1:r.events.waterfall(`internal/set`,r,t,n,i,()=>r.reflect.set(t,n,i))}catch(e){throw e===i?uo(e):e}},`set`),has:F((e,t)=>po(t)?Reflect.has(e,t):Reflect.has(e,t)?!0:!!e.reflect.props[t],`has`)};store=Object.create(null);props=Object.create(null);get(e,t=!0){return za(this.ctx,this._getImpl(e,t)?.value)}_getImpl(e,t=!0){let n=this.ctx[I.isolate][e],r=n&&this.store[n];if(r&&!(t&&r.fiber.state!==2))return r}set(e,t,n){let r=this.ctx[I.isolate][e],i=this.store[r];if(!i)throw Error(`cannot set property "${e}" without provide`);if(i.fiber!==this.ctx.fiber)throw Error(`cannot set property "${e}" in multiple fibers`);return i.value=t,!0}provide(e,t,n){return this.ctx.fiber.effect(()=>{if(!this.props[e])this.props[e]??={type:`service`};else if(this.props[e].type!==`service`)throw Error(`property "${e}" is already declared as ${this.props[e].type}`);this.props[e]={type:`service`},this.ctx.root[I.isolate][e]??=Symbol(e);let r=this.ctx[I.isolate][e],i={name:e,value:t,fiber:this.ctx.fiber,check:n};if(this.store[r])throw Error(`service "${e}" has been registered at <${this.store[r].fiber.name}>`);return this.store[r]=i,this.ctx.fiber.store[e]=i,this.ctx.fiber.state===2&&this.notify([e]),async()=>{delete this.store[r];let t=this.notify([e]);await Promise.allSettled(t.map(e=>e.await())),delete this.ctx.fiber.store[e]}},`ctx.provide(${JSON.stringify(e)})`)}notify(e,t=(e,t)=>e[I.isolate][t]===this.ctx[I.isolate][t]){let n=[];for(let r of this.ctx.registry.values())for(let i of r.fibers){let r=!1;for(let n of e)n in i.inject&&t(i.ctx,n)&&(r=!0,i._checkImpl(n));r&&(i._refresh(),n.push(i))}for(let n of e){let e=Object.create(this.ctx);e[I.filter]=e=>t(e,n),this.ctx.events.emit(e,`internal/service`,n,this._getImpl(n,!1)?.value)}return n}accessor(e,t){return this.ctx.fiber.effect(()=>{if(e in this.props)throw Error(`property "${e}" is already declared as ${this.props[e].type}`);return this.props[e]={type:`accessor`,...t},()=>delete this.props[e]},`ctx.accessor(${JSON.stringify(e)})`)}mixin(e,t){let n=this;return this.ctx.fiber.effect(function*(){let r=Array.isArray(t)?t.map(e=>[e,e]):Object.entries(t),i=F((t,n)=>t[e],`getTarget`);for(let[e,t]of r)yield n.accessor(t,{get(t,n){let r=i(this,n);if(xa(r))return r;let a=t?Ba(t,r):r,o=Reflect.get(r,e,a);return typeof o==`function`?o.bind(a??r):o},set(t,n,r){let a=i(this,r),o=n?Ba(n,a):a;return Reflect.set(a,e,t,o)}})},`ctx.mixin(${JSON.stringify(e)})`)}trace(e){return za(this.ctx,e)}bind(e){return new Proxy(e,{apply:F((e,t,n)=>Reflect.apply(e,this.trace(t),n.map(e=>this.trace(e))),`apply`),construct:F((e,t,n)=>Reflect.construct(e,t.map(e=>this.trace(e)),n),`construct`)})}};function ho(e){return e&&typeof e==`object`&&typeof e.apply==`function`}F(ho,`isApplicable`);function go(e,t){return function(n,r){if(r.kind===`class`)Object.hasOwn(n,`inject`)||(Sa(n,`inject`,Object.create(Object.getPrototypeOf(n).inject??null)),Sa(n.inject,I.checkProto,!0)),n.inject[e]=t;else if(r.kind===`method`){let i=(n[I.metadata]??={}).inject??=Object.create(null);i[e]=t,r.addInitializer(function(){let e=this[I.tracker]?.property;(this[I.initHooks]??=[]).push(()=>{this.ctx.inject(i,t=>n.call(e?Ba(this,{[e]:t}):this))})})}else throw Error(`@Inject() can only be used on class or class methods`)}}F(go,`Inject`),(e=>{function t(e,n=Object.create(null)){if(!e)return n;if(Array.isArray(e))for(let t of e)n[t]=null;else if(Reflect.has(e,I.checkProto)){Object.assign(n,t(Object.getPrototypeOf(e)));for(let t of Object.keys(e))n[t]=e[t]??null}else for(let t of Object.keys(e))n[t]=e[t]??null;return n}e.resolve=t,F(t,`resolve`)})(go||={});var _o=class{constructor(e){this.ctx=e,Sa(this,I.tracker,{property:`ctx`,noShadow:!0})}ctx;static{F(this,`RegistryService`)}_counter=0;_internal=new Map;get counter(){return++this._counter}get size(){return this._internal.size}resolve(e){try{if(typeof e==`function`)return e;if(ho(e))return e.apply}catch{}}get(e){let t=this.resolve(e);return t&&this._internal.get(t)}has(e){let t=this.resolve(e);return!!t&&this._internal.has(t)}delete(e){let t=this.resolve(e),n=t&&this._internal.get(t);if(n){this._internal.delete(t);for(let e of n.fibers)e.dispose();return n}}keys(){return this._internal.keys()}values(){return this._internal.values()}entries(){return this._internal.entries()}forEach(e){return this._internal.forEach(e)}inject(e,t){return this.plugin({inject:e,apply:t,name:t.name})}plugin(e,t,n=Ya()){let r=this.resolve(e);if(!r)throw Error(`invalid plugin, expect function or object with an "apply" method, received `+typeof e);this.ctx.fiber.assertActive();let i=this._internal.get(r);if(!i){let t=e.name;t===`apply`&&(t=void 0),i={name:t,callback:r,fibers:new Ma,Config:e.Config},this._internal.set(r,i)}let a=new lo(this.ctx,t,go.resolve(e.inject),i,n),o=Object.create(a);return o.then=(e,t)=>a.await().then(e,t),o}},vo=class e{static{F(this,`Context`)}static effect=I.effect;static filter=I.filter;static isolate=I.isolate;static intercept=I.intercept;static is(t){return!!t?.[e.is]}static{e.is[Symbol.toPrimitive]=()=>Symbol.for(`cordis.is`),e.prototype[e.is]=!0}constructor(){this[I.isolate]=Object.create(null),this[I.intercept]=Object.create(null);let e=new Proxy(this,mo.handler);return this.root=e,this.baseUrl=void 0,this.fiber=new lo(e,{},Object.create(null),null,()=>[]),this.reflect=new mo(e),this.registry=new _o(e),this.events=new Za(e),this.logger=new ro(e),this.fiber._disposables.clear(),e}[Symbol.for(`nodejs.util.inspect.custom`)](){return`Context <${this.fiber.name}>`}extend(e={}){let t=Reflect.getOwnPropertyDescriptor(this,I.shadow)?.value,n=Object.create(za(this,this));for(let t of Reflect.ownKeys(e))Object.defineProperty(n,t,Reflect.getOwnPropertyDescriptor(e,t));return t?Object.assign(Object.create(n),{[I.shadow]:t}):n}isolate(e,t){let n=Object.create(this[I.isolate]);return n[e]=t??Symbol(e),this.extend({[I.isolate]:n})}intercept(e,t){let n=Object.create(this[I.intercept]);return n[e]=t,this.extend({[I.intercept]:n})}};(class e{constructor(e,t){this.ctx=e,t??=this.constructor.provide;let n=this,r={associate:t,property:`ctx`};return n[I.invoke]&&(n=Ka(t,Ia(Object.getPrototypeOf(this),Function.prototype),r)),n.ctx=e,n.name=t,Sa(n,I.tracker,r),n.ctx.reflect.provide(t,n,this[I.check]),n}ctx;static{F(this,`Service`)}static init=I.init;static check=I.check;static config=I.config;static invoke=I.invoke;static extend=I.extend;static tracker=I.tracker;static resolveConfig=I.resolveConfig;name;[I.filter](e){return e[I.isolate][this.name]===this.ctx[I.isolate][this.name]}[I.extend](t){let n;return n=this[e.invoke]?Ka(this.name,this,this[I.tracker]):Object.create(this),Object.assign(n,t)}[I.resolveConfig](e,t){let n=this.ctx[vo.intercept],r=[];for(;this.name in n;)Object.hasOwn(n,this.name)&&r.unshift(n[this.name]),n=Object.getPrototypeOf(n);return e&&r.unshift(e),t&&r.push(t),this.Config?.merge?this.Config.merge(...r):Object.assign({},...r)}static[Symbol.hasInstance](e){if(!e)return!1;let t=e.constructor;for(;t;){if(t=t.prototype?.constructor,t===this)return!0;t&&=Object.getPrototypeOf(t)}return!1}});function yo(e){return{type:`text`,text:e}}function bo(e,t,n,r){return{type:`image`,src:e,alt:t,width:n,height:r}}function xo(e,t,n=`document`){return{type:`card`,hash:e,handle:t,cardType:n}}function So(e,t=``,n){return{type:`execute`,pcard:e,input:t,label:n}}function Co(e){return Ar(ne(e))}function wo(e,t){let n=new Uint8Array(64);e.length>64?n.set(Co(e)):n.set(e);let r=new Uint8Array(64),i=new Uint8Array(64);for(let e=0;e<64;e++)r[e]=n[e]^54,i[e]=n[e]^92;let a=new Uint8Array(64+t.length);a.set(r,0),a.set(t,64);let o=Co(a),s=new Uint8Array(96);return s.set(i,0),s.set(o,64),Co(s)}function To(e,t){let n=wo(e,t),r=wo(n,new Uint8Array([1])),i=new Uint8Array(33);return i.set(r,0),i[32]=2,[r,wo(n,i)]}function Eo(e,t){let n=wo(e,t),r=wo(n,new Uint8Array([1])),i=new Uint8Array(33);i.set(r,0),i[32]=2;let a=wo(n,i),o=new Uint8Array(33);return o.set(a,0),o[32]=3,[r,a,wo(n,o)]}function Do(e,t){if(e.length!==32)throw Error(`X25519 private key must be 32 bytes, got ${e.length}`);if(t.length!==32)throw Error(`X25519 public key must be 32 bytes, got ${t.length}`);let n=d({key:Buffer.concat([Ir(Pr),Buffer.from(e)]),format:`der`,type:`pkcs8`}),r=f({key:Buffer.concat([Ir(Fr),Buffer.from(t)]),format:`der`,type:`spki`});return new Uint8Array(p({privateKey:n,publicKey:r}))}function Oo(e){let t=e?new Uint8Array(e):new Uint8Array(u(32)),n=f(d({key:Buffer.concat([Ir(Pr),Buffer.from(t)]),format:`der`,type:`pkcs8`})).export({type:`spki`,format:`der`}).subarray(-32);return{privateKey:t,publicKey:new Uint8Array(n)}}var ko=0;function Ao(){return ko=(ko+1)%1e6,ko}function jo(e,t,n,r,i){return M.create(e,JSON.stringify(t),r,i,new Map(n))}function Mo(e,t,n,r,i=Date.now()){return jo(`mcard:event/chat/query/${e}/${i}_${Ao()}`,{eventType:`chat_query`,turnId:e,query:t,attachments:n,authorDid:r.asString(),timestamp:new Date(i).toISOString(),g_time:i},[[`contentType`,`application/x-clm-event+json`],[`schema`,`clm:schema:event:query:v1`],[`eventType`,`chat_query`],[`turnId`,e],[`storagePillar`,`execution_log`]],r,i)}function No(e,t,n,r,i,a,o=Date.now()){return jo(`mcard:event/chat/feedback/${e}/${o}_${Ao()}`,{eventType:`chat_feedback`,turnId:e,queryHash:n.hash.asHex(),feedback:t,modelId:r,latencyMs:i,authorDid:a.asString(),timestamp:new Date(o).toISOString(),g_time:o},[[`contentType`,`application/x-clm-event+json`],[`schema`,`clm:schema:event:feedback:v1`],[`eventType`,`chat_feedback`],[`turnId`,e],[`queryHash`,n.hash.asHex()],[`modelId`,r],[`storagePillar`,`execution_log`]],a,o)}function Po(e,t,n,r,i,a=Date.now()){return jo(`mcard:event/chat/transition/${e}/${t}_to_${n}/${a}_${Ao()}`,{eventType:`chat_transition`,turnId:e,fromState:t,toState:n,reason:r,timestamp:new Date(a).toISOString(),g_time:a},[[`contentType`,`application/x-clm-event+json`],[`schema`,`clm:schema:event:transition:v1`],[`eventType`,`chat_transition`],[`turnId`,e],[`fromState`,t],[`toState`,n],[`storagePillar`,`execution_log`]],i,a)}function Fo(e,t,n,r=j.create(`did:clm:agent:maxwell`),i=Date.now()){return jo(`mcard:event/chat/abort/${e}/${i}_${Ao()}`,{eventType:`chat_abort`,turnId:e,reason:t,obstruction:n,timestamp:new Date(i).toISOString(),g_time:i},[[`contentType`,`application/x-clm-event+json`],[`schema`,`clm:schema:event:abort:v1`],[`eventType`,`chat_abort`],[`turnId`,e],[`storagePillar`,`execution_log`]],r,i)}function Io(e,t,n,r=j.create(`did:clm:agent:rollback`),i=Date.now()){return jo(`mcard:event/chat/revert/${e}/${i}_${Ao()}`,{eventType:`chat_revert`,turnId:e,error:t,disposersUnwound:n,timestamp:new Date(i).toISOString(),g_time:i},[[`contentType`,`application/x-clm-event+json`],[`schema`,`clm:schema:event:revert:v1`],[`eventType`,`chat_revert`],[`turnId`,e],[`storagePillar`,`execution_log`]],r,i)}function Lo(e,t,n,r,i=Date.now()){let a=`mcard:event/chat/image/${e}/${i}_${Ao()}`,o=atob(n),s=new Uint8Array(o.length);for(let e=0;e<o.length;e++)s[e]=o.charCodeAt(e);let c=Me(t,s);return M.withMetadata(a,c,new Map([[`contentType`,t],[`mimeType`,t],[`encoding`,`base64`],[`sizeBytes`,String(s.length)],[`turnId`,e],[`source`,`gemini:generateContent`],[`schema`,`clm:schema:event:image:v1`],[`eventType`,`chat_image`],[`storagePillar`,`execution_log`]]),r,i)}var Ro=class{_state=`waiting`;_stateHistory=[`waiting`];constructor(e=`waiting`){this._state=e,this._stateHistory=[e]}get state(){return this._state}get stateHistory(){return[...this._stateHistory]}transition(e){this._state=e,this._stateHistory.push(e)}reset(){this._state=`waiting`,this._stateHistory.length=0,this._stateHistory.push(`waiting`)}};function zo(e,t){try{return`getPillar`in e&&typeof e.getPillar==`function`?(e.getPillar(`execution_log`).put(t),!0):`commitEvent`in e&&typeof e.commitEvent==`function`&&(e.commitEvent(t),!0)}catch{return!1}}var Bo=class extends ye{constructor(e,t){super({id:e,codeHash:A.computeString(`pcard:chatbot:turn:v1`),sourceUri:`pcard:clm/chatbot/turn`,signature:`ChatBotTurnInput -> ChatBotTurnOutput`,coeffects:{requiredServices:[`llm.agency`]}}),this.persistence=t}persistence;_stateMachine=new Ro(`waiting`);get state(){return this._stateMachine.state}get stateHistory(){return this._stateMachine.stateHistory}transition(e,t,n,r){let i=this._stateMachine.state;this._stateMachine.transition(e);let a=Po(n,i,e,t,r);zo(this.persistence,a)}async executeTurn(e,t={}){let n=e.turnId||`turn_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,i=performance.now();this.transition(`progressing`,`Inbound query input - aperture expanded`,n,e.authorDid);let a=Mo(n,e.prompt,e.attachments||[],e.authorDid);if(zo(this.persistence,a),t.preGate){let r=await t.preGate(e);if(!r.pass){let t=r.reason||`Precondition verification failed`;this.transition(`aborting`,t,n,e.authorDid);let o=Fo(n,t,r.obstruction,e.authorDid);zo(this.persistence,o),this.transition(`waiting`,`Aborted turn reset to idle readiness`,n,e.authorDid);let s=No(n,`\u26D4 **Turn Aborted**: ${t}`,a,e.modelId||`gate:rejection`,Math.round(performance.now()-i),e.authorDid);return zo(this.persistence,s),{feedbackText:`\u26D4 **Turn Aborted**: ${t}`,queryMCard:a,feedbackMCard:s,finalState:`waiting`,stateHistory:this.stateHistory}}}let o=typeof this.persistence.savepoint==`function`?this.persistence.savepoint(`sp_${n}`):void 0,s=new r,c=``;try{if(c=t.provider?await t.provider(e.prompt,t.onToken):`[Satori SpeechAct: received] Acknowledged: ${e.prompt}`,t.postGate){let e=await t.postGate(c,a);if(!e.pass)throw Error(`Postcondition verification failed: ${e.reason||`invalid completion`}`)}if(!c.trim())throw Error(`Zero-Silence Invariant Violation: feedback text cannot be empty`);let r=Math.round(performance.now()-i),o=No(n,c,a,e.modelId||`in-browser`,r,e.authorDid);return zo(this.persistence,o),await s.dispose(),this.transition(`waiting`,`Turn successfully verified and sealed`,n,e.authorDid),{feedbackText:c,queryMCard:a,feedbackMCard:o,finalState:`waiting`,stateHistory:this.stateHistory}}catch(t){let r=t?.message||String(t);this.transition(`reverting`,`Execution fault: ${r}`,n,e.authorDid),o!==void 0&&typeof this.persistence.rollbackTo==`function`&&this.persistence.rollbackTo(o);let c=s.length;await s.dispose();let l=Io(n,r,c,e.authorDid);zo(this.persistence,l),this.transition(`waiting`,`Reverted state restored to prior marking`,n,e.authorDid);let u=`\u26A0\uFE0F **Turn Reverted (0 Residual State)**: ${r}`,d=No(n,u,a,e.modelId||`system:revert`,Math.round(performance.now()-i),e.authorDid);return zo(this.persistence,d),{feedbackText:u,queryMCard:a,feedbackMCard:d,finalState:`waiting`,stateHistory:this.stateHistory}}}},Vo;function Ho(){}Ho.prototype=Object.create(null);function L(){L.init.call(this)}L.EventEmitter=L,L.usingDomains=!1,L.prototype.domain=void 0,L.prototype._events=void 0,L.prototype._maxListeners=void 0,L.defaultMaxListeners=10,L.init=function(){this.domain=null,L.usingDomains&&Vo.active&&!(this instanceof Vo.Domain)&&(this.domain=Vo.active),(!this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=new Ho,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},L.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||isNaN(e))throw TypeError(`"n" argument must be a positive number`);return this._maxListeners=e,this};function Uo(e){return e._maxListeners===void 0?L.defaultMaxListeners:e._maxListeners}L.prototype.getMaxListeners=function(){return Uo(this)};function Wo(e,t,n){if(t)e.call(n);else for(var r=e.length,i=es(e,r),a=0;a<r;++a)i[a].call(n)}function Go(e,t,n,r){if(t)e.call(n,r);else for(var i=e.length,a=es(e,i),o=0;o<i;++o)a[o].call(n,r)}function Ko(e,t,n,r,i){if(t)e.call(n,r,i);else for(var a=e.length,o=es(e,a),s=0;s<a;++s)o[s].call(n,r,i)}function qo(e,t,n,r,i,a){if(t)e.call(n,r,i,a);else for(var o=e.length,s=es(e,o),c=0;c<o;++c)s[c].call(n,r,i,a)}function Jo(e,t,n,r){if(t)e.apply(n,r);else for(var i=e.length,a=es(e,i),o=0;o<i;++o)a[o].apply(n,r)}L.prototype.emit=function(e){var t,n,r,i,a,o,s,c=e===`error`;if(o=this._events,o)c&&=o.error==null;else if(!c)return!1;if(s=this.domain,c){if(t=arguments[1],s)t||=Error(`Uncaught, unspecified "error" event`),t.domainEmitter=this,t.domain=s,t.domainThrown=!1,s.emit(`error`,t);else if(t instanceof Error)throw t;else{var l=Error(`Uncaught, unspecified "error" event. (`+t+`)`);throw l.context=t,l}return!1}if(n=o[e],!n)return!1;var u=typeof n==`function`;switch(r=arguments.length,r){case 1:Wo(n,u,this);break;case 2:Go(n,u,this,arguments[1]);break;case 3:Ko(n,u,this,arguments[1],arguments[2]);break;case 4:qo(n,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=Array(r-1),a=1;a<r;a++)i[a-1]=arguments[a];Jo(n,u,this,i)}return!0};function Yo(e,t,n,r){var i,a,o;if(typeof n!=`function`)throw TypeError(`"listener" argument must be a function`);if(a=e._events,a?(a.newListener&&(e.emit(`newListener`,t,n.listener?n.listener:n),a=e._events),o=a[t]):(a=e._events=new Ho,e._eventsCount=0),!o)o=a[t]=n,++e._eventsCount;else if(typeof o==`function`?o=a[t]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),!o.warned&&(i=Uo(e),i&&i>0&&o.length>i)){o.warned=!0;var s=Error(`Possible EventEmitter memory leak detected. `+o.length+` `+t+` listeners added. Use emitter.setMaxListeners() to increase limit`);s.name=`MaxListenersExceededWarning`,s.emitter=e,s.type=t,s.count=o.length,Xo(s)}return e}function Xo(e){typeof console.warn==`function`?console.warn(e):console.log(e)}L.prototype.addListener=function(e,t){return Yo(this,e,t,!1)},L.prototype.on=L.prototype.addListener,L.prototype.prependListener=function(e,t){return Yo(this,e,t,!0)};function Zo(e,t,n){var r=!1;function i(){e.removeListener(t,i),r||(r=!0,n.apply(e,arguments))}return i.listener=n,i}L.prototype.once=function(e,t){if(typeof t!=`function`)throw TypeError(`"listener" argument must be a function`);return this.on(e,Zo(this,e,t)),this},L.prototype.prependOnceListener=function(e,t){if(typeof t!=`function`)throw TypeError(`"listener" argument must be a function`);return this.prependListener(e,Zo(this,e,t)),this},L.prototype.removeListener=function(e,t){var n,r,i,a,o;if(typeof t!=`function`)throw TypeError(`"listener" argument must be a function`);if(r=this._events,!r||(n=r[e],!n))return this;if(n===t||n.listener&&n.listener===t)--this._eventsCount===0?this._events=new Ho:(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length;a-->0;)if(n[a]===t||n[a].listener&&n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;if(n.length===1){if(n[0]=void 0,--this._eventsCount===0)return this._events=new Ho,this;delete r[e]}else $o(n,i);r.removeListener&&this.emit(`removeListener`,e,o||t)}return this},L.prototype.removeAllListeners=function(e){var t,n=this._events;if(!n)return this;if(!n.removeListener)return arguments.length===0?(this._events=new Ho,this._eventsCount=0):n[e]&&(--this._eventsCount===0?this._events=new Ho:delete n[e]),this;if(arguments.length===0){for(var r=Object.keys(n),i=0,a;i<r.length;++i)a=r[i],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=new Ho,this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t)do this.removeListener(e,t[t.length-1]);while(t[0]);return this},L.prototype.listeners=function(e){var t,n,r=this._events;return r?(t=r[e],n=t?typeof t==`function`?[t.listener||t]:ts(t):[]):n=[],n},L.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):Qo.call(e,t)},L.prototype.listenerCount=Qo;function Qo(e){var t=this._events;if(t){var n=t[e];if(typeof n==`function`)return 1;if(n)return n.length}return 0}L.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function $o(e,t){for(var n=t,r=n+1,i=e.length;r<i;n+=1,r+=1)e[n]=e[r];e.pop()}function es(e,t){for(var n=Array(t);t--;)n[t]=e[t];return n}function ts(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}var ns=ms(globalThis.fetch)&&ms(globalThis.ReadableStream),rs;function is(){if(rs!==void 0)return rs;try{new globalThis.Blob([new ArrayBuffer(1)]),rs=!0}catch{rs=!1}return rs}var as;function os(e){as||(as=new globalThis.XMLHttpRequest,as.open(`GET`,globalThis.location.host?`/`:`https://example.com`));try{return as.responseType=e,as.responseType===e}catch{return!1}}var ss=globalThis.ArrayBuffer!==void 0,cs=ss&&ms(globalThis.ArrayBuffer.prototype.slice),ls=ss&&os(`arraybuffer`),us=!ns&&cs&&os(`ms-stream`),ds=!ns&&ss&&os(`moz-chunked-arraybuffer`),fs=ms(as.overrideMimeType),ps=ms(globalThis.VBArray);function ms(e){return typeof e==`function`}as=null;var hs=[],gs=[],_s=typeof Uint8Array<`u`?Uint8Array:Array,vs=!1;function ys(){vs=!0;for(var e=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,t=0,n=e.length;t<n;++t)hs[t]=e[t],gs[e.charCodeAt(t)]=t;gs[45]=62,gs[95]=63}function bs(e){vs||ys();var t,n,r,i,a,o,s=e.length;if(s%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);a=e[s-2]===`=`?2:+(e[s-1]===`=`),o=new _s(s*3/4-a),r=a>0?s-4:s;var c=0;for(t=0,n=0;t<r;t+=4,n+=3)i=gs[e.charCodeAt(t)]<<18|gs[e.charCodeAt(t+1)]<<12|gs[e.charCodeAt(t+2)]<<6|gs[e.charCodeAt(t+3)],o[c++]=i>>16&255,o[c++]=i>>8&255,o[c++]=i&255;return a===2?(i=gs[e.charCodeAt(t)]<<2|gs[e.charCodeAt(t+1)]>>4,o[c++]=i&255):a===1&&(i=gs[e.charCodeAt(t)]<<10|gs[e.charCodeAt(t+1)]<<4|gs[e.charCodeAt(t+2)]>>2,o[c++]=i>>8&255,o[c++]=i&255),o}function xs(e){return hs[e>>18&63]+hs[e>>12&63]+hs[e>>6&63]+hs[e&63]}function Ss(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16)+(e[a+1]<<8)+e[a+2],i.push(xs(r));return i.join(``)}function Cs(e){vs||ys();for(var t,n=e.length,r=n%3,i=``,a=[],o=16383,s=0,c=n-r;s<c;s+=o)a.push(Ss(e,s,s+o>c?c:s+o));return r===1?(t=e[n-1],i+=hs[t>>2],i+=hs[t<<4&63],i+=`==`):r===2&&(t=(e[n-2]<<8)+e[n-1],i+=hs[t>>10],i+=hs[t>>4&63],i+=hs[t<<2&63],i+=`=`),a.push(i),a.join(``)}function ws(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)}function Ts(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}var Es={}.toString,Ds=Array.isArray||function(e){return Es.call(e)==`[object Array]`};R.TYPED_ARRAY_SUPPORT=globalThis.TYPED_ARRAY_SUPPORT===void 0||globalThis.TYPED_ARRAY_SUPPORT,Os();function Os(){return R.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function ks(e,t){if(Os()<t)throw RangeError(`Invalid typed array length`);return R.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t),e.__proto__=R.prototype):(e===null&&(e=new R(t)),e.length=t),e}function R(e,t,n){if(!R.TYPED_ARRAY_SUPPORT&&!(this instanceof R))return new R(e,t,n);if(typeof e==`number`){if(typeof t==`string`)throw Error(`If encoding is specified then the first argument must be a string`);return Ns(this,e)}return As(this,e,t,n)}R.poolSize=8192,R._augment=function(e){return e.__proto__=R.prototype,e};function As(e,t,n,r){if(typeof t==`number`)throw TypeError(`"value" argument must not be a number`);return typeof ArrayBuffer<`u`&&t instanceof ArrayBuffer?Is(e,t,n,r):typeof t==`string`?Ps(e,t,n):Ls(e,t)}R.from=function(e,t,n){return As(null,e,t,n)},R.TYPED_ARRAY_SUPPORT&&(R.prototype.__proto__=Uint8Array.prototype,R.__proto__=Uint8Array);function js(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be a number`);if(e<0)throw RangeError(`"size" argument must not be negative`)}function Ms(e,t,n,r){return js(t),t<=0||n===void 0?ks(e,t):typeof r==`string`?ks(e,t).fill(n,r):ks(e,t).fill(n)}R.alloc=function(e,t,n){return Ms(null,e,t,n)};function Ns(e,t){if(js(t),e=ks(e,t<0?0:Rs(t)|0),!R.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}R.allocUnsafe=function(e){return Ns(null,e)},R.allocUnsafeSlow=function(e){return Ns(null,e)};function Ps(e,t,n){if((typeof n!=`string`||n===``)&&(n=`utf8`),!R.isEncoding(n))throw TypeError(`"encoding" must be a valid string encoding`);var r=Bs(t,n)|0;e=ks(e,r);var i=e.write(t,n);return i!==r&&(e=e.slice(0,i)),e}function Fs(e,t){var n=t.length<0?0:Rs(t.length)|0;e=ks(e,n);for(var r=0;r<n;r+=1)e[r]=t[r]&255;return e}function Is(e,t,n,r){if(t.byteLength,n<0||t.byteLength<n)throw RangeError(`'offset' is out of bounds`);if(t.byteLength<n+(r||0))throw RangeError(`'length' is out of bounds`);return t=n===void 0&&r===void 0?new Uint8Array(t):r===void 0?new Uint8Array(t,n):new Uint8Array(t,n,r),R.TYPED_ARRAY_SUPPORT?(e=t,e.__proto__=R.prototype):e=Fs(e,t),e}function Ls(e,t){if(zs(t)){var n=Rs(t.length)|0;return e=ks(e,n),e.length===0||t.copy(e,0,0,n),e}if(t){if(typeof ArrayBuffer<`u`&&t.buffer instanceof ArrayBuffer||`length`in t)return typeof t.length!=`number`||bc(t.length)?ks(e,0):Fs(e,t);if(t.type===`Buffer`&&Ds(t.data))return Fs(e,t.data)}throw TypeError(`First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.`)}function Rs(e){if(e>=Os())throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+Os().toString(16)+` bytes`);return e|0}R.isBuffer=xc;function zs(e){return!!(e!=null&&e._isBuffer)}R.compare=function(e,t){if(!zs(e)||!zs(t))throw TypeError(`Arguments must be Buffers`);if(e===t)return 0;for(var n=e.length,r=t.length,i=0,a=Math.min(n,r);i<a;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:+(r<n)},R.isEncoding=function(e){switch(String(e).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}},R.concat=function(e,t){if(!Ds(e))throw TypeError(`"list" argument must be an Array of Buffers`);if(e.length===0)return R.alloc(0);var n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=R.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var a=e[n];if(!zs(a))throw TypeError(`"list" argument must be an Array of Buffers`);a.copy(r,i),i+=a.length}return r};function Bs(e,t){if(zs(e))return e.length;if(typeof ArrayBuffer<`u`&&typeof ArrayBuffer.isView==`function`&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;typeof e!=`string`&&(e=``+e);var n=e.length;if(n===0)return 0;for(var r=!1;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:case void 0:return hc(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return vc(e).length;default:if(r)return hc(e).length;t=(``+t).toLowerCase(),r=!0}}R.byteLength=Bs;function Vs(e,t,n){var r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return rc(this,t,n);case`utf8`:case`utf-8`:return Qs(this,t,n);case`ascii`:return tc(this,t,n);case`latin1`:case`binary`:return nc(this,t,n);case`base64`:return Zs(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return ic(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}R.prototype._isBuffer=!0;function Hs(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}R.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(var t=0;t<e;t+=2)Hs(this,t,t+1);return this},R.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(var t=0;t<e;t+=4)Hs(this,t,t+3),Hs(this,t+1,t+2);return this},R.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(var t=0;t<e;t+=8)Hs(this,t,t+7),Hs(this,t+1,t+6),Hs(this,t+2,t+5),Hs(this,t+3,t+4);return this},R.prototype.toString=function(){var e=this.length|0;return e===0?``:arguments.length===0?Qs(this,0,e):Vs.apply(this,arguments)},R.prototype.equals=function(e){if(!zs(e))throw TypeError(`Argument must be a Buffer`);return this===e||R.compare(this,e)===0},R.prototype.inspect=function(){var e=``,t=50;return this.length>0&&(e=this.toString(`hex`,0,t).match(/.{2}/g).join(` `),this.length>t&&(e+=` ... `)),`<Buffer `+e+`>`},R.prototype.compare=function(e,t,n,r,i){if(!zs(e))throw TypeError(`Argument must be a Buffer`);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;for(var a=i-r,o=n-t,s=Math.min(a,o),c=this.slice(r,i),l=e.slice(t,n),u=0;u<s;++u)if(c[u]!==l[u]){a=c[u],o=l[u];break}return a<o?-1:+(o<a)};function Us(e,t,n,r,i){if(e.length===0)return-1;if(typeof n==`string`?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(i)n=0;else return-1}if(typeof t==`string`&&(t=R.from(t,r)),zs(t))return t.length===0?-1:Ws(e,t,n,r,i);if(typeof t==`number`)return t&=255,R.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==`function`?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):Ws(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function Ws(e,t,n,r,i){var a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}var l;if(i){var u=-1;for(l=n;l<o;l++)if(c(e,l)===c(t,u===-1?0:l-u)){if(u===-1&&(u=l),l-u+1===s)return u*a}else u!==-1&&(l-=l-u),u=-1}else for(n+s>o&&(n=o-s),l=n;l>=0;l--){for(var d=!0,f=0;f<s;f++)if(c(e,l+f)!==c(t,f)){d=!1;break}if(d)return l}return-1}R.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1},R.prototype.indexOf=function(e,t,n){return Us(this,e,t,n,!0)},R.prototype.lastIndexOf=function(e,t,n){return Us(this,e,t,n,!1)};function Gs(e,t,n,r){n=Number(n)||0;var i=e.length-n;r?(r=Number(r),r>i&&(r=i)):r=i;var a=t.length;if(a%2!=0)throw TypeError(`Invalid hex string`);r>a/2&&(r=a/2);for(var o=0;o<r;++o){var s=parseInt(t.substr(o*2,2),16);if(isNaN(s))return o;e[n+o]=s}return o}function Ks(e,t,n,r){return yc(hc(t,e.length-n),e,n,r)}function qs(e,t,n,r){return yc(gc(t),e,n,r)}function Js(e,t,n,r){return qs(e,t,n,r)}function Ys(e,t,n,r){return yc(vc(t),e,n,r)}function Xs(e,t,n,r){return yc(_c(t,e.length-n),e,n,r)}R.prototype.write=function(e,t,n,r){if(t===void 0)r=`utf8`,n=this.length,t=0;else if(n===void 0&&typeof t==`string`)r=t,n=this.length,t=0;else if(isFinite(t))t|=0,isFinite(n)?(n|=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);var i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;for(var a=!1;;)switch(r){case`hex`:return Gs(this,e,t,n);case`utf8`:case`utf-8`:return Ks(this,e,t,n);case`ascii`:return qs(this,e,t,n);case`latin1`:case`binary`:return Js(this,e,t,n);case`base64`:return Ys(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return Xs(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},R.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function Zs(e,t,n){return t===0&&n===e.length?Cs(e):Cs(e.slice(t,n))}function Qs(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i<n;){var a=e[i],o=null,s=a>239?4:a>223?3:a>191?2:1;if(i+s<=n){var c,l,u,d;switch(s){case 1:a<128&&(o=a);break;case 2:c=e[i+1],(c&192)==128&&(d=(a&31)<<6|c&63,d>127&&(o=d));break;case 3:c=e[i+1],l=e[i+2],(c&192)==128&&(l&192)==128&&(d=(a&15)<<12|(c&63)<<6|l&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:c=e[i+1],l=e[i+2],u=e[i+3],(c&192)==128&&(l&192)==128&&(u&192)==128&&(d=(a&15)<<18|(c&63)<<12|(l&63)<<6|u&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),i+=s}return ec(r)}var $s=4096;function ec(e){var t=e.length;if(t<=$s)return String.fromCharCode.apply(String,e);for(var n=``,r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=$s));return n}function tc(e,t,n){var r=``;n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(e[i]&127);return r}function nc(e,t,n){var r=``;n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function rc(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var i=``,a=t;a<n;++a)i+=mc(e[a]);return i}function ic(e,t,n){for(var r=e.slice(t,n),i=``,a=0;a<r.length;a+=2)i+=String.fromCharCode(r[a]+r[a+1]*256);return i}R.prototype.slice=function(e,t){var n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);var r;if(R.TYPED_ARRAY_SUPPORT)r=this.subarray(e,t),r.__proto__=R.prototype;else{var i=t-e;r=new R(i,void 0);for(var a=0;a<i;++a)r[a]=this[a+e]}return r};function z(e,t,n){if(e%1!=0||e<0)throw RangeError(`offset is not uint`);if(e+t>n)throw RangeError(`Trying to access beyond buffer length`)}R.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||z(e,t,this.length);for(var r=this[e],i=1,a=0;++a<t&&(i*=256);)r+=this[e+a]*i;return r},R.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||z(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},R.prototype.readUInt8=function(e,t){return t||z(e,1,this.length),this[e]},R.prototype.readUInt16LE=function(e,t){return t||z(e,2,this.length),this[e]|this[e+1]<<8},R.prototype.readUInt16BE=function(e,t){return t||z(e,2,this.length),this[e]<<8|this[e+1]},R.prototype.readUInt32LE=function(e,t){return t||z(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},R.prototype.readUInt32BE=function(e,t){return t||z(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},R.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||z(e,t,this.length);for(var r=this[e],i=1,a=0;++a<t&&(i*=256);)r+=this[e+a]*i;return i*=128,r>=i&&(r-=2**(8*t)),r},R.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||z(e,t,this.length);for(var r=t,i=1,a=this[e+--r];r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},R.prototype.readInt8=function(e,t){return t||z(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},R.prototype.readInt16LE=function(e,t){t||z(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},R.prototype.readInt16BE=function(e,t){t||z(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},R.prototype.readInt32LE=function(e,t){return t||z(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},R.prototype.readInt32BE=function(e,t){return t||z(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},R.prototype.readFloatLE=function(e,t){return t||z(e,4,this.length),ws(this,e,!0,23,4)},R.prototype.readFloatBE=function(e,t){return t||z(e,4,this.length),ws(this,e,!1,23,4)},R.prototype.readDoubleLE=function(e,t){return t||z(e,8,this.length),ws(this,e,!0,52,8)},R.prototype.readDoubleBE=function(e,t){return t||z(e,8,this.length),ws(this,e,!1,52,8)};function ac(e,t,n,r,i,a){if(!zs(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||t<a)throw RangeError(`"value" argument is out of bounds`);if(n+r>e.length)throw RangeError(`Index out of range`)}R.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t|=0,n|=0,!r){var i=2**(8*n)-1;ac(this,e,t,n,i,0)}var a=1,o=0;for(this[t]=e&255;++o<n&&(a*=256);)this[t+o]=e/a&255;return t+n},R.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t|=0,n|=0,!r){var i=2**(8*n)-1;ac(this,e,t,n,i,0)}var a=n-1,o=1;for(this[t+a]=e&255;--a>=0&&(o*=256);)this[t+a]=e/o&255;return t+n},R.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||ac(this,e,t,1,255,0),R.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=e&255,t+1};function oc(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,a=Math.min(e.length-n,2);i<a;++i)e[n+i]=(t&255<<8*(r?i:1-i))>>>(r?i:1-i)*8}R.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||ac(this,e,t,2,65535,0),R.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):oc(this,e,t,!0),t+2},R.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||ac(this,e,t,2,65535,0),R.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):oc(this,e,t,!1),t+2};function sc(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,a=Math.min(e.length-n,4);i<a;++i)e[n+i]=t>>>(r?i:3-i)*8&255}R.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||ac(this,e,t,4,4294967295,0),R.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255):sc(this,e,t,!0),t+4},R.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||ac(this,e,t,4,4294967295,0),R.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):sc(this,e,t,!1),t+4},R.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=2**(8*n-1);ac(this,e,t,n,i-1,-i)}var a=0,o=1,s=0;for(this[t]=e&255;++a<n&&(o*=256);)e<0&&s===0&&this[t+a-1]!==0&&(s=1),this[t+a]=(e/o>>0)-s&255;return t+n},R.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=2**(8*n-1);ac(this,e,t,n,i-1,-i)}var a=n-1,o=1,s=0;for(this[t+a]=e&255;--a>=0&&(o*=256);)e<0&&s===0&&this[t+a+1]!==0&&(s=1),this[t+a]=(e/o>>0)-s&255;return t+n},R.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||ac(this,e,t,1,127,-128),R.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=e&255,t+1},R.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||ac(this,e,t,2,32767,-32768),R.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):oc(this,e,t,!0),t+2},R.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||ac(this,e,t,2,32767,-32768),R.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):oc(this,e,t,!1),t+2},R.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||ac(this,e,t,4,2147483647,-2147483648),R.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):sc(this,e,t,!0),t+4},R.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||ac(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),R.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):sc(this,e,t,!1),t+4};function cc(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function lc(e,t,n,r,i){return i||cc(e,t,n,4),Ts(e,t,n,r,23,4),n+4}R.prototype.writeFloatLE=function(e,t,n){return lc(this,e,t,!0,n)},R.prototype.writeFloatBE=function(e,t,n){return lc(this,e,t,!1,n)};function uc(e,t,n,r,i){return i||cc(e,t,n,8),Ts(e,t,n,r,52,8),n+8}R.prototype.writeDoubleLE=function(e,t,n){return uc(this,e,t,!0,n)},R.prototype.writeDoubleBE=function(e,t,n){return uc(this,e,t,!1,n)},R.prototype.copy=function(e,t,n,r){if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r<n&&(r=n),r===n||e.length===0||this.length===0)return 0;if(t<0)throw RangeError(`targetStart out of bounds`);if(n<0||n>=this.length)throw RangeError(`sourceStart out of bounds`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var i=r-n,a;if(this===e&&n<t&&t<r)for(a=i-1;a>=0;--a)e[a+t]=this[a+n];else if(i<1e3||!R.TYPED_ARRAY_SUPPORT)for(a=0;a<i;++a)e[a+t]=this[a+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+i),t);return i},R.prototype.fill=function(e,t,n,r){if(typeof e==`string`){if(typeof t==`string`?(r=t,t=0,n=this.length):typeof n==`string`&&(r=n,n=this.length),e.length===1){var i=e.charCodeAt(0);i<256&&(e=i)}if(r!==void 0&&typeof r!=`string`)throw TypeError(`encoding must be a string`);if(typeof r==`string`&&!R.isEncoding(r))throw TypeError(`Unknown encoding: `+r)}else typeof e==`number`&&(e&=255);if(t<0||this.length<t||this.length<n)throw RangeError(`Out of range index`);if(n<=t)return this;t>>>=0,n=n===void 0?this.length:n>>>0,e||=0;var a;if(typeof e==`number`)for(a=t;a<n;++a)this[a]=e;else{var o=zs(e)?e:hc(new R(e,r).toString()),s=o.length;for(a=0;a<n-t;++a)this[a+t]=o[a%s]}return this};var dc=/[^+\/0-9A-Za-z-_]/g;function fc(e){if(e=pc(e).replace(dc,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function pc(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,``)}function mc(e){return e<16?`0`+e.toString(16):e.toString(16)}function hc(e,t){t||=1/0;for(var n,r=e.length,i=null,a=[],o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function gc(e){for(var t=[],n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function _c(e,t){for(var n,r,i,a=[],o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,a.push(i),a.push(r);return a}function vc(e){return bs(fc(e))}function yc(e,t,n,r){for(var i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function bc(e){return e!==e}function xc(e){return e!=null&&(!!e._isBuffer||Sc(e)||Cc(e))}function Sc(e){return!!e.constructor&&typeof e.constructor.isBuffer==`function`&&e.constructor.isBuffer(e)}function Cc(e){return typeof e.readFloatLE==`function`&&typeof e.slice==`function`&&Sc(e.slice(0,0))}var wc=Tc;function Tc(){this.head=null,this.tail=null,this.length=0}Tc.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},Tc.prototype.unshift=function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length},Tc.prototype.shift=function(){if(this.length!==0){var e=this.head.data;return this.head=this.length===1?this.tail=null:this.head.next,--this.length,e}},Tc.prototype.clear=function(){this.head=this.tail=null,this.length=0},Tc.prototype.join=function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n},Tc.prototype.concat=function(e){if(this.length===0)return R.alloc(0);if(this.length===1)return this.head.data;for(var t=R.allocUnsafe(e>>>0),n=this.head,r=0;n;)n.data.copy(t,r),r+=n.data.length,n=n.next;return t};var Ec=R.isEncoding||function(e){switch(e&&e.toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:case`raw`:return!0;default:return!1}};function Dc(e){if(e&&!Ec(e))throw Error(`Unknown encoding: `+e)}function Oc(e){switch(this.encoding=(e||`utf8`).toLowerCase().replace(/[-_]/,``),Dc(e),this.encoding){case`utf8`:this.surrogateSize=3;break;case`ucs2`:case`utf16le`:this.surrogateSize=2,this.detectIncompleteChar=Ac;break;case`base64`:this.surrogateSize=3,this.detectIncompleteChar=jc;break;default:this.write=kc;return}this.charBuffer=new R(6),this.charReceived=0,this.charLength=0}Oc.prototype.write=function(e){for(var t=``;this.charLength;){var n=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,n),this.charReceived+=n,this.charReceived<this.charLength)return``;e=e.slice(n,e.length),t=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var r=t.charCodeAt(t.length-1);if(r>=55296&&r<=56319){this.charLength+=this.surrogateSize,t=``;continue}if(this.charReceived=this.charLength=0,e.length===0)return t;break}this.detectIncompleteChar(e);var i=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,i),i-=this.charReceived),t+=e.toString(this.encoding,0,i);var i=t.length-1,r=t.charCodeAt(i);if(r>=55296&&r<=56319){var a=this.surrogateSize;return this.charLength+=a,this.charReceived+=a,this.charBuffer.copy(this.charBuffer,a,0,a),e.copy(this.charBuffer,0,0,a),t.substring(0,i)}return t},Oc.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var n=e[e.length-t];if(t==1&&n>>5==6){this.charLength=2;break}if(t<=2&&n>>4==14){this.charLength=3;break}if(t<=3&&n>>3==30){this.charLength=4;break}}this.charReceived=t},Oc.prototype.end=function(e){var t=``;if(e&&e.length&&(t=this.write(e)),this.charReceived){var n=this.charReceived,r=this.charBuffer,i=this.encoding;t+=r.slice(0,n).toString(i)}return t};function kc(e){return e.toString(this.encoding)}function Ac(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function jc(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}V.ReadableState=Pc;var B=yn(`stream`);pn(V,L);function Mc(e,t,n){if(typeof e.prependListener==`function`)return e.prependListener(t,n);!e._events||!e._events[t]?e.on(t,n):Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]}function Nc(e,t){return e.listeners(t).length}function Pc(e,t){e||={},this.objectMode=!!e.objectMode,t instanceof Dl&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var n=e.highWaterMark,r=this.objectMode?16:16384;this.highWaterMark=n||n===0?n:r,this.highWaterMark=~~this.highWaterMark,this.buffer=new wc,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(this.decoder=new Oc(e.encoding),this.encoding=e.encoding)}function V(e){if(!(this instanceof V))return new V(e);this._readableState=new Pc(e,this),this.readable=!0,e&&typeof e.read==`function`&&(this._read=e.read),L.call(this)}V.prototype.push=function(e,t){var n=this._readableState;return!n.objectMode&&typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=Buffer.from(e,t),t=``)),Fc(this,n,e,t,!1)},V.prototype.unshift=function(e){var t=this._readableState;return Fc(this,t,e,``,!0)},V.prototype.isPaused=function(){return this._readableState.flowing===!1};function Fc(e,t,n,r,i){var a=Bc(t,n);if(a)e.emit(`error`,a);else if(n===null)t.reading=!1,Vc(e,t);else if(t.objectMode||n&&n.length>0){if(t.ended&&!i){var o=Error(`stream.push() after EOF`);e.emit(`error`,o)}else if(t.endEmitted&&i){var s=Error(`stream.unshift() after end event`);e.emit(`error`,s)}else{var c;t.decoder&&!i&&!r&&(n=t.decoder.write(n),c=!t.objectMode&&n.length===0),i||(t.reading=!1),c||(t.flowing&&t.length===0&&!t.sync?(e.emit(`data`,n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&Hc(e))),Wc(e,t)}}else i||(t.reading=!1);return Ic(t)}function Ic(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||e.length===0)}V.prototype.setEncoding=function(e){return this._readableState.decoder=new Oc(e),this._readableState.encoding=e,this};var Lc=8388608;function Rc(e){return e>=Lc?e=Lc:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function zc(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=Rc(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}V.prototype.read=function(e){B(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return B(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?tl(this):Hc(this),null;if(e=zc(e,t),e===0&&t.ended)return t.length===0&&tl(this),null;var r=t.needReadable;B(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,B(`length less than watermark`,r)),t.ended||t.reading?(r=!1,B(`reading or ended`,r)):r&&(B(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=zc(n,t)));var i=e>0?Zc(e,t):null;return i===null?(t.needReadable=!0,e=0):t.length-=e,t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&tl(this)),i!==null&&this.emit(`data`,i),i};function Bc(e,t){var n=null;return!Buffer.isBuffer(t)&&typeof t!=`string`&&t!=null&&!e.objectMode&&(n=TypeError(`Invalid non-string/buffer chunk`)),n}function Vc(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,Hc(e)}}function Hc(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(B(`emitReadable`,t.flowing),t.emittedReadable=!0,t.sync?zt(Uc,e):Uc(e))}function Uc(e){B(`emit readable`),e.emit(`readable`),Xc(e)}function Wc(e,t){t.readingMore||(t.readingMore=!0,zt(Gc,e,t))}function Gc(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(B(`maybeReadMore read 0`),e.read(0),n!==t.length);)n=t.length;t.readingMore=!1}V.prototype._read=function(e){this.emit(`error`,Error(`not implemented`))},V.prototype.pipe=function(e,t){var n=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e)}r.pipesCount+=1,B(`pipe count=%d opts=%j`,r.pipesCount,t);var i=!t||t.end!==!1?o:l;r.endEmitted?zt(i):n.once(`end`,i),e.on(`unpipe`,a);function a(e){B(`onunpipe`),e===n&&l()}function o(){B(`onend`),e.end()}var s=Kc(n);e.on(`drain`,s);var c=!1;function l(){B(`cleanup`),e.removeListener(`close`,p),e.removeListener(`finish`,m),e.removeListener(`drain`,s),e.removeListener(`error`,f),e.removeListener(`unpipe`,a),n.removeListener(`end`,o),n.removeListener(`end`,l),n.removeListener(`data`,d),c=!0,r.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&s()}var u=!1;n.on(`data`,d);function d(t){B(`ondata`),u=!1,!1===e.write(t)&&!u&&((r.pipesCount===1&&r.pipes===e||r.pipesCount>1&&il(r.pipes,e)!==-1)&&!c&&(B(`false write response, pause`,n._readableState.awaitDrain),n._readableState.awaitDrain++,u=!0),n.pause())}function f(t){B(`onerror`,t),h(),e.removeListener(`error`,f),Nc(e,`error`)===0&&e.emit(`error`,t)}Mc(e,`error`,f);function p(){e.removeListener(`finish`,m),h()}e.once(`close`,p);function m(){B(`onfinish`),e.removeListener(`close`,p),h()}e.once(`finish`,m);function h(){B(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),r.flowing||(B(`pipe resume`),n.resume()),e};function Kc(e){return function(){var t=e._readableState;B(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&e.listeners(`data`).length&&(t.flowing=!0,Xc(e))}}V.prototype.unpipe=function(e){var t=this._readableState;if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i<r;i++)n[i].emit(`unpipe`,this);return this}var a=il(t.pipes,e);return a===-1?this:(t.pipes.splice(a,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this),this)},V.prototype.on=function(e,t){var n=L.prototype.on.call(this,e,t);if(e===`data`)this._readableState.flowing!==!1&&this.resume();else if(e===`readable`){var r=this._readableState;!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.emittedReadable=!1,r.reading?r.length&&Hc(this,r):zt(qc,this))}return n},V.prototype.addListener=V.prototype.on;function qc(e){B(`readable nexttick read 0`),e.read(0)}V.prototype.resume=function(){var e=this._readableState;return e.flowing||(B(`resume`),e.flowing=!0,Jc(this,e)),this};function Jc(e,t){t.resumeScheduled||(t.resumeScheduled=!0,zt(Yc,e,t))}function Yc(e,t){t.reading||(B(`resume read 0`),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit(`resume`),Xc(e),t.flowing&&!t.reading&&e.read(0)}V.prototype.pause=function(){return B(`call pause flowing=%j`,this._readableState.flowing),!1!==this._readableState.flowing&&(B(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this};function Xc(e){var t=e._readableState;for(B(`flow`,t.flowing);t.flowing&&e.read()!==null;);}V.prototype.wrap=function(e){var t=this._readableState,n=!1,r=this;for(var i in e.on(`end`,function(){if(B(`wrapped end`),t.decoder&&!t.ended){var e=t.decoder.end();e&&e.length&&r.push(e)}r.push(null)}),e.on(`data`,function(i){B(`wrapped data`),t.decoder&&(i=t.decoder.write(i)),!(t.objectMode&&i==null)&&(t.objectMode||i&&i.length)&&(r.push(i)||(n=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));return rl([`error`,`close`,`destroy`,`pause`,`resume`],function(t){e.on(t,r.emit.bind(r,t))}),r._read=function(t){B(`wrapped _read`,t),n&&(n=!1,e.resume())},r},V._fromList=Zc;function Zc(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=Qc(e,t.buffer,t.decoder),n}function Qc(e,t,n){var r;return e<t.head.data.length?(r=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):r=e===t.head.data.length?t.shift():n?$c(e,t):el(e,t),r}function $c(e,t){var n=t.head,r=1,i=n.data;for(e-=i.length;n=n.next;){var a=n.data,o=e>a.length?a.length:e;if(o===a.length?i+=a:i+=a.slice(0,e),e-=o,e===0){o===a.length?(++r,t.head=n.next?n.next:t.tail=null):(t.head=n,n.data=a.slice(o));break}++r}return t.length-=r,i}function el(e,t){var n=Buffer.allocUnsafe(e),r=t.head,i=1;for(r.data.copy(n),e-=r.data.length;r=r.next;){var a=r.data,o=e>a.length?a.length:e;if(a.copy(n,n.length-e,0,o),e-=o,e===0){o===a.length?(++i,t.head=r.next?r.next:t.tail=null):(t.head=r,r.data=a.slice(o));break}++i}return t.length-=i,n}function tl(e){var t=e._readableState;if(t.length>0)throw Error(`"endReadable()" called on non-empty stream`);t.endEmitted||(t.ended=!0,zt(nl,t,e))}function nl(e,t){!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`))}function rl(e,t){for(var n=0,r=e.length;n<r;n++)t(e[n],n)}function il(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}H.WritableState=sl,pn(H,L);function al(){}function ol(e,t,n){this.chunk=e,this.encoding=t,this.callback=n,this.next=null}function sl(e,t){Object.defineProperty(this,"buffer",{get:gn(function(){return this.getBuffer()},`_writableState.buffer is deprecated. Use _writableState.getBuffer instead.`)}),e||={},this.objectMode=!!e.objectMode,t instanceof Dl&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var n=e.highWaterMark,r=this.objectMode?16:16384;this.highWaterMark=n||n===0?n:r,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var i=e.decodeStrings===!1;this.decodeStrings=!i,this.defaultEncoding=e.defaultEncoding||`utf8`,this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){hl(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new Cl(this)}sl.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t};function H(e){if(!(this instanceof H)&&!(this instanceof Dl))return new H(e);this._writableState=new sl(e,this),this.writable=!0,e&&(typeof e.write==`function`&&(this._write=e.write),typeof e.writev==`function`&&(this._writev=e.writev)),L.call(this)}H.prototype.pipe=function(){this.emit(`error`,Error(`Cannot pipe, not readable`))};function cl(e,t){var n=Error(`write after end`);e.emit(`error`,n),zt(t,n)}function ll(e,t,n,r){var i=!0,a=!1;return n===null?a=TypeError(`May not write null values to stream`):!R.isBuffer(n)&&typeof n!=`string`&&n!==void 0&&!t.objectMode&&(a=TypeError(`Invalid non-string/buffer chunk`)),a&&(e.emit(`error`,a),zt(r,a),i=!1),i}H.prototype.write=function(e,t,n){var r=this._writableState,i=!1;return typeof t==`function`&&(n=t,t=null),R.isBuffer(e)?t=`buffer`:t||=r.defaultEncoding,typeof n!=`function`&&(n=al),r.ended?cl(this,n):ll(this,r,e,n)&&(r.pendingcb++,i=dl(this,r,e,t,n)),i},H.prototype.cork=function(){var e=this._writableState;e.corked++},H.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.finished&&!e.bufferProcessing&&e.bufferedRequest&&vl(this,e))},H.prototype.setDefaultEncoding=function(e){if(typeof e==`string`&&(e=e.toLowerCase()),!([`hex`,`utf8`,`utf-8`,`ascii`,`binary`,`base64`,`ucs2`,`ucs-2`,`utf16le`,`utf-16le`,`raw`].indexOf((e+``).toLowerCase())>-1))throw TypeError(`Unknown encoding: `+e);return this._writableState.defaultEncoding=e,this};function ul(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&typeof t==`string`&&(t=R.from(t,n)),t}function dl(e,t,n,r,i){n=ul(t,n,r),R.isBuffer(n)&&(r=`buffer`);var a=t.objectMode?1:n.length;t.length+=a;var o=t.length<t.highWaterMark;if(o||(t.needDrain=!0),t.writing||t.corked){var s=t.lastBufferedRequest;t.lastBufferedRequest=new ol(n,r,i),s?s.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else fl(e,t,!1,a,n,r,i);return o}function fl(e,t,n,r,i,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,n?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function pl(e,t,n,r,i){--t.pendingcb,n?zt(i,r):i(r),e._writableState.errorEmitted=!0,e.emit(`error`,r)}function ml(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function hl(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(ml(n),t)pl(e,n,r,t,i);else{var a=yl(n);!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&vl(e,n),r?zt(gl,e,n,a,i):gl(e,n,a,i)}}function gl(e,t,n,r){n||_l(e,t),t.pendingcb--,r(),xl(e,t)}function _l(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function vl(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,i=Array(r),a=t.corkedRequestsFree;a.entry=n;for(var o=0;n;)i[o]=n,n=n.next,o+=1;fl(e,t,!0,t.length,i,``,a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new Cl(t)}else{for(;n;){var s=n.chunk,c=n.encoding,l=n.callback;if(fl(e,t,!1,t.objectMode?1:s.length,s,c,l),n=n.next,t.writing)break}n===null&&(t.lastBufferedRequest=null)}t.bufferedRequestCount=0,t.bufferedRequest=n,t.bufferProcessing=!1}H.prototype._write=function(e,t,n){n(Error(`not implemented`))},H.prototype._writev=null,H.prototype.end=function(e,t,n){var r=this._writableState;typeof e==`function`?(n=e,e=null,t=null):typeof t==`function`&&(n=t,t=null),e!=null&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),!r.ending&&!r.finished&&Sl(this,r,n)};function yl(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function bl(e,t){t.prefinished||(t.prefinished=!0,e.emit(`prefinish`))}function xl(e,t){var n=yl(t);return n&&(t.pendingcb===0?(bl(e,t),t.finished=!0,e.emit(`finish`)):bl(e,t)),n}function Sl(e,t,n){t.ending=!0,xl(e,t),n&&(t.finished?zt(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function Cl(e){var t=this;this.next=null,this.entry=null,this.finish=function(n){var r=t.entry;for(t.entry=null;r;){var i=r.callback;e.pendingcb--,i(n),r=r.next}e.corkedRequestsFree?e.corkedRequestsFree.next=t:e.corkedRequestsFree=t}}pn(Dl,V);for(var wl=Object.keys(H.prototype),Tl=0;Tl<wl.length;Tl++){var El=wl[Tl];Dl.prototype[El]||(Dl.prototype[El]=H.prototype[El])}function Dl(e){if(!(this instanceof Dl))return new Dl(e);V.call(this,e),H.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),this.once(`end`,Ol)}function Ol(){this.allowHalfOpen||this._writableState.ended||zt(kl,this)}function kl(e){e.end()}pn(Ml,Dl);function Al(e){this.afterTransform=function(t,n){return jl(e,t,n)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function jl(e,t,n){var r=e._transformState;r.transforming=!1;var i=r.writecb;if(!i)return e.emit(`error`,Error(`no writecb in Transform class`));r.writechunk=null,r.writecb=null,n!=null&&e.push(n),i(t);var a=e._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&e._read(a.highWaterMark)}function Ml(e){if(!(this instanceof Ml))return new Ml(e);Dl.call(this,e),this._transformState=new Al(this);var t=this;this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform==`function`&&(this._transform=e.transform),typeof e.flush==`function`&&(this._flush=e.flush)),this.once(`prefinish`,function(){typeof this._flush==`function`?this._flush(function(e){Nl(t,e)}):Nl(t)})}Ml.prototype.push=function(e,t){return this._transformState.needTransform=!1,Dl.prototype.push.call(this,e,t)},Ml.prototype._transform=function(e,t,n){throw Error(`Not implemented`)},Ml.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},Ml.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};function Nl(e,t){if(t)return e.emit(`error`,t);var n=e._writableState,r=e._transformState;if(n.length)throw Error(`Calling transform done when ws.length != 0`);if(r.transforming)throw Error(`Calling transform done when still transforming`);return e.push(null)}var Pl={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4};function Fl(e,t,n){var r=this;V.call(r),r._mode=n,r.headers={},r.rawHeaders=[],r.trailers={},r.rawTrailers=[],r.on(`end`,function(){process.nextTick(function(){r.emit(`close`)})});var i;if(n===`fetch`){r._fetchResponse=t,r.url=t.url,r.statusCode=t.status,r.statusMessage=t.statusText;for(var a,o,s=t.headers[Symbol.iterator]();a=(o=s.next()).value,!o.done;)r.headers[a[0].toLowerCase()]=a[1],r.rawHeaders.push(a[0],a[1]);var c=t.body.getReader();i=function(){c.read().then(function(e){if(!r._destroyed){if(e.done){r.push(null);return}r.push(new Buffer(e.value)),i()}})},i()}else if(r._xhr=e,r._pos=0,r.url=e.responseURL,r.statusCode=e.status,r.statusMessage=e.statusText,e.getAllResponseHeaders().split(/\r?\n/).forEach(function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var n=t[1].toLowerCase();n===`set-cookie`?(r.headers[n]===void 0&&(r.headers[n]=[]),r.headers[n].push(t[2])):r.headers[n]===void 0?r.headers[n]=t[2]:r.headers[n]+=`, `+t[2],r.rawHeaders.push(t[1],t[2])}}),r._charset=`x-user-defined`,!fs){var l=r.rawHeaders[`mime-type`];if(l){var u=l.match(/;\s*charset=([^;])(;|$)/);u&&(r._charset=u[1].toLowerCase())}r._charset||=`utf-8`}}pn(Fl,V),Fl.prototype._read=function(){},Fl.prototype._onXHRProgress=function(){var e=this,t=e._xhr,n=null;switch(e._mode){case`text:vbarray`:if(t.readyState!==Pl.DONE)break;try{n=new globalThis.VBArray(t.responseBody).toArray()}catch{}if(n!==null){e.push(new Buffer(n));break}case`text`:try{n=t.responseText}catch{e._mode=`text:vbarray`;break}if(n.length>e._pos){var r=n.substr(e._pos);if(e._charset===`x-user-defined`){for(var i=new Buffer(r.length),a=0;a<r.length;a++)i[a]=r.charCodeAt(a)&255;e.push(i)}else e.push(r,e._charset);e._pos=n.length}break;case`arraybuffer`:if(t.readyState!==Pl.DONE||!t.response)break;n=t.response,e.push(new Buffer(new Uint8Array(n)));break;case`moz-chunked-arraybuffer`:if(n=t.response,t.readyState!==Pl.LOADING||!n)break;e.push(new Buffer(new Uint8Array(n)));break;case`ms-stream`:if(n=t.response,t.readyState!==Pl.LOADING)break;var o=new globalThis.MSStreamReader;o.onprogress=function(){o.result.byteLength>e._pos&&(e.push(new Buffer(new Uint8Array(o.result.slice(e._pos)))),e._pos=o.result.byteLength)},o.onload=function(){e.push(null)},o.readAsArrayBuffer(n)}e._xhr.readyState===Pl.DONE&&e._mode!==`ms-stream`&&e.push(null)};function Il(e){if(e instanceof Uint8Array){if(e.byteOffset===0&&e.byteLength===e.buffer.byteLength)return e.buffer;if(typeof e.buffer.slice==`function`)return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}if(xc(e)){for(var t=new Uint8Array(e.length),n=e.length,r=0;r<n;r++)t[r]=e[r];return t.buffer}throw Error(`Argument must be a Buffer`)}function Ll(e,t){return ns&&t?`fetch`:ds?`moz-chunked-arraybuffer`:us?`ms-stream`:ls&&e?`arraybuffer`:ps&&e?`text:vbarray`:`text`}var Rl=U;function U(e){var t=this;H.call(t),t._opts=e,t._body=[],t._headers={},e.auth&&t.setHeader(`Authorization`,`Basic `+new Buffer(e.auth).toString(`base64`)),Object.keys(e.headers).forEach(function(n){t.setHeader(n,e.headers[n])});var n,r=!0;if(e.mode===`disable-fetch`)r=!1,n=!0;else if(e.mode===`prefer-streaming`)n=!1;else if(e.mode===`allow-wrong-content-type`)n=!fs;else if(!e.mode||e.mode==="default"||e.mode===`prefer-fast`)n=!0;else throw Error(`Invalid value for opts.mode`);t._mode=Ll(n,r),t.on(`finish`,function(){t._onFinish()})}pn(U,H);var zl=[`accept-charset`,`accept-encoding`,`access-control-request-headers`,`access-control-request-method`,`connection`,`content-length`,`cookie`,`cookie2`,`date`,`dnt`,`expect`,`host`,`keep-alive`,`origin`,`referer`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`user-agent`,`via`];U.prototype.setHeader=function(e,t){var n=this,r=e.toLowerCase();zl.indexOf(r)===-1&&(n._headers[r]={name:e,value:t})},U.prototype.getHeader=function(e){return this._headers[e.toLowerCase()].value},U.prototype.removeHeader=function(e){var t=this;delete t._headers[e.toLowerCase()]},U.prototype._onFinish=function(){var e=this;if(!e._destroyed){var t=e._opts,n=e._headers,r;if((t.method===`POST`||t.method===`PUT`||t.method===`PATCH`)&&(r=is()?new globalThis.Blob(e._body.map(function(e){return Il(e)}),{type:(n[`content-type`]||{}).value||``}):Buffer.concat(e._body).toString()),e._mode===`fetch`){var i=Object.keys(n).map(function(e){return[n[e].name,n[e].value]});globalThis.fetch(e._opts.url,{method:e._opts.method,headers:i,body:r,mode:`cors`,credentials:t.withCredentials?`include`:`same-origin`}).then(function(t){e._fetchResponse=t,e._connect()},function(t){e.emit(`error`,t)})}else{var a=e._xhr=new globalThis.XMLHttpRequest;try{a.open(e._opts.method,e._opts.url,!0)}catch(t){process.nextTick(function(){e.emit(`error`,t)});return}`responseType`in a&&(a.responseType=e._mode.split(`:`)[0]),`withCredentials`in a&&(a.withCredentials=!!t.withCredentials),e._mode===`text`&&`overrideMimeType`in a&&a.overrideMimeType(`text/plain; charset=x-user-defined`),Object.keys(n).forEach(function(e){a.setRequestHeader(n[e].name,n[e].value)}),e._response=null,a.onreadystatechange=function(){switch(a.readyState){case Pl.LOADING:case Pl.DONE:e._onXHRProgress()}},e._mode===`moz-chunked-arraybuffer`&&(a.onprogress=function(){e._onXHRProgress()}),a.onerror=function(){e._destroyed||e.emit(`error`,Error(`XHR error`))};try{a.send(r)}catch(t){process.nextTick(function(){e.emit(`error`,t)});return}}}};function Bl(e){try{var t=e.status;return t!==null&&t!==0}catch{return!1}}U.prototype._onXHRProgress=function(){var e=this;Bl(e._xhr)&&!e._destroyed&&(e._response||e._connect(),e._response._onXHRProgress())},U.prototype._connect=function(){var e=this;e._destroyed||(e._response=new Fl(e._xhr,e._fetchResponse,e._mode),e.emit(`response`,e._response))},U.prototype._write=function(e,t,n){this._body.push(e),n()},U.prototype.abort=U.prototype.destroy=function(){var e=this;e._destroyed=!0,e._response&&(e._response._destroyed=!0),e._xhr&&e._xhr.abort()},U.prototype.end=function(e,t,n){var r=this;typeof e==`function`&&(n=e,e=void 0),H.prototype.end.call(r,e,t,n)},U.prototype.flushHeaders=function(){},U.prototype.setTimeout=function(){},U.prototype.setNoDelay=function(){},U.prototype.setSocketKeepAlive=function(){};var Vl=e({Agent:()=>Wl,METHODS:()=>Gl,STATUS_CODES:()=>Kl,default:()=>ql,get:()=>Ul,request:()=>Hl});function Hl(e,t){typeof e==`string`&&(e=fr(e));var n=globalThis.location.protocol.search(/^https?:$/)===-1?`http:`:``,r=e.protocol||n,i=e.hostname||e.host,a=e.port,o=e.path||`/`;i&&i.indexOf(`:`)!==-1&&(i=`[`+i+`]`),e.url=(i?r+`//`+i:``)+(a?`:`+a:``)+o,e.method=(e.method||`GET`).toUpperCase(),e.headers=e.headers||{};var s=new Rl(e);return t&&s.on(`response`,t),s}function Ul(e,t){var n=Hl(e,t);return n.end(),n}function Wl(){}Wl.defaultMaxSockets=4;var Gl=`CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.REPORT.SEARCH.SUBSCRIBE.TRACE.UNLOCK.UNSUBSCRIBE`.split(`.`),Kl={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Moved Temporarily`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Time-out`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Request Entity Too Large`,414:`Request-URI Too Large`,415:`Unsupported Media Type`,416:`Requested Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Unordered Collection`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too Many Requests`,431:`Request Header Fields Too Large`,500:`Internal Server Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Time-out`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,509:`Bandwidth Limit Exceeded`,510:`Not Extended`,511:`Network Authentication Required`},ql={request:Hl,get:Ul,Agent:Wl,METHODS:Gl,STATUS_CODES:Kl},Jl=typeof globalThis<`u`&&globalThis.WebSocket?globalThis.WebSocket:class{},Yl=class{constructor(){throw Error(`WebSocketServer is not supported in the browser`)}},Xl=class extends Error{constructor(e){super(e),this.name=`GatewayError`}},Zl=class{medium=`local`;async resolve(e){try{let t=e.backend.get(e.contentHash);if(t)return{content:ru(t.payload),status:0}}catch{}return{content:``,status:2}}},Ql=class{medium=`file`;async resolve(e){let t=String(e.routeData.uri??``).replace(/^file:\/\//,``);try{if(typeof process<`u`&&process.versions&&process.versions.node){let r=await n(()=>Promise.resolve().then(()=>Kr),void 0),i=await n(()=>Promise.resolve().then(()=>We),void 0),a=t;return i.isAbsolute(t)||(a=i.resolve(e.workspaceRoot,t)),{content:await r.readFile(a,`utf8`),status:0}}}catch{}return{content:``,status:2}}},$l=class{medium;constructor(e=`http`){this.medium=e}async resolve(e){let t=String(e.routeData.uri??``);if(!e.fetchFn)return{content:``,status:2};try{let n=typeof AbortController<`u`?new AbortController:void 0,r=n?setTimeout(()=>n.abort(),e.timeoutMs):void 0,i=await e.fetchFn(t,{headers:{"User-Agent":`CLM/1.0`},signal:n?n.signal:void 0});if(r&&clearTimeout(r),i.ok)return{content:await i.text(),status:0}}catch{}return{content:``,status:2}}},eu=class{medium=`ipfs`;async resolve(e){let t=String(e.routeData.uri??``).replace(/^ipfs:\/\//,``);if(!e.fetchFn)return{content:``,status:2};let n=[`http://127.0.0.1:5001/api/v0/cat?arg=${t}`,`https://ipfs.io/ipfs/${t}`];for(let t of n)try{let n=typeof AbortController<`u`?new AbortController:void 0,r=n?setTimeout(()=>n.abort(),e.timeoutMs):void 0,i=await e.fetchFn(t,{signal:n?n.signal:void 0});if(r&&clearTimeout(r),i.ok)return{content:await i.text(),status:0}}catch{}return{content:``,status:2}}},tu=class{medium=`indexeddb`;async resolve(e){return{content:``,status:2}}},nu=class{plugins=new Map;register(e){this.plugins.set(e.medium.toLowerCase(),e)}get(e){return this.plugins.get(e.toLowerCase())}};function ru(e){return e.kind===`text`?e.value:e.kind===`scalar`?String(e.value??``):e.kind===`structured`?JSON.stringify(e.value):e.kind===`binary`?typeof Buffer<`u`?Buffer.from(e.data).toString(`utf8`):new TextDecoder().decode(e.data):``}function iu(e){let t=e.indexOf(`:`);return t>=0?e.slice(t+1):e}function au(e,t){let n=e.resolveHandle(ge.parse(`route:${t}`));if(!n)return{medium:`local`,routeData:{}};let r=e.get(n);if(!r)return{medium:`local`,routeData:{}};try{let e=na(ru(r.payload));if(e&&typeof e==`object`)return{medium:String(e.medium??`local`).toLowerCase(),routeData:e}}catch{}return{medium:`local`,routeData:{}}}function ou(e,t,n){let r=String(n.cached_hash??``);if(r&&r!==`null`&&r!==`undefined`){let t=iu(r),n=e.get(A.fromHex(t));if(n)return{content:ru(n.payload),hash:t}}let i=e.handleHistory(ge.parse(t));for(let t=i.length-1;t>=0;t--){let n=e.get(i[t]);if(n)return{content:ru(n.payload),hash:i[t].asHex()}}return null}function su(e,t,n){let r=A.computeString(t),i=M.create(n,t,j.create(`did:clm:gateway`),1);return e.put(r,i),r.asHex()}var cu=new nu;cu.register(new Zl),cu.register(new Ql),cu.register(new $l(`http`)),cu.register(new $l(`https`)),cu.register(new eu),cu.register(new tu);async function lu(e){let{uri:t,backend:n,workspaceRoot:r=`.`,fallback:i=`error`,cache:a=!0,timeoutMs:o=1e4,fetchFn:s=typeof globalThis<`u`&&globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,visitedHandles:c=new Set([t])}=e,l=t,u=``,d=0,f=`local`,p=!1,m=!1,h=``;for(;;){let e=n.resolveHandle(ge.parse(l));if(!e&&!l.startsWith(`clm:`)&&(e=n.resolveHandle(ge.parse(`clm:${l}`))),!e){if(l===t)throw new Xl(`Handle not found: ${l}`);break}h=e.asHex();let{medium:g,routeData:_}=au(n,h);f=g;let v=await(cu.get(g)??cu.get(`local`)).resolve({routeData:_,contentHash:e,backend:n,workspaceRoot:r,timeoutMs:o,fetchFn:s});if(u=v.content,d=v.status,d===0&&g!==`local`){let e=String(_.cached_hash??``);if(e&&e!==`null`&&e!==`undefined`&&A.computeString(u).asHex()!==iu(e)&&(d=2),d===0&&a)try{h=su(n,u,String(_.uri??`clm:${l}`)),m=!0}catch{}}if(d!==0){if(i===`stale`){let e=ou(n,l,_);e&&(u=e.content,h=e.hash,d=3,p=!0)}if(d!==3)throw new Xl(`Network error resolving medium ${g} for ${l}`)}if(u.length<=255&&/^[a-zA-Z0-9_:-]+$/.test(u.trim())){let e=u.trim();if(n.resolveHandle(ge.parse(e))){if(c.has(e))throw new Xl(`Circular reference detected`);c.add(e),l=e;continue}}break}return{content:u,hash:h,statusCode:d,medium:f,cached:m,staleUsed:p}}function uu(e){return e.replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&apos;/g,`'`)}function du(e){return e?/<[a-zA-Z0-9_-]+(\s+[^>]*)?\/?>/.test(e):!1}function fu(e){let t={},n=/([a-zA-Z0-9_:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g,r;for(;(r=n.exec(e))!==null;){let e=r[1];t[e]=uu(r[2]??r[3]??r[4]??``)}return t}function pu(e){let t=(e||``).trim();if(!t)return[];if(!t.includes(`<`)||!t.includes(`>`))return[{type:`text`,text:t}];let n=[],r=/<(\/)?([a-zA-Z0-9_:-]+)((?:\s+[^>]*?)?)(\/)?>/g,i=0,a;for(;(a=r.exec(t))!==null;){let[e,o,s,c,l]=a,u=a.index;if(u>i){let e=uu(t.slice(i,u));if(e.length>0){if(n.length>0&&n[n.length-1]?.type===`text`){let t=n[n.length-1];n[n.length-1]={...t,text:(t.text??``)+e}}else n.push({type:`text`,text:e})}}i=u+e.length;let d=s.toLowerCase();if(o)continue;let f=fu(c||``);if(!l){let e=`</${s}>`,a=t.indexOf(e,i);if(a!==-1){let o=t.slice(i,a);if(i=a+e.length,r.lastIndex=i,d===`text`){let e=uu(o);n.push({type:`text`,text:e});continue}if(d===`quote`){let e=f.id||f.message_id||``,t=uu(o),r=pu(o),i={};for(let[e,t]of Object.entries(f))e!==`id`&&e!==`message_id`&&(i[e]=t);n.push({type:`quote`,...e?{id:e}:{},...t?{text:t}:{},...Object.keys(i).length>0?{attrs:i}:{},...r.length>0?{children:r}:{}});continue}if(d===`button`){let e=f.id||``,t=f.label||uu(o),r=f.action||f.pcard;n.push({type:`button`,id:e,label:t,...r?{action:r}:{}});continue}if(d===`witness`){let e=f.verdict||`pass`,t=f.proof||uu(o),r={};for(let[e,t]of Object.entries(f))e!==`verdict`&&e!==`proof`&&(r[e]=t);n.push({type:`witness`,verdict:e,...t?{proof:t}:{},...Object.keys(r).length>0?{attrs:r}:{}});continue}}}switch(d){case`text`:{let e=f.text||f.content||``;e&&n.push({type:`text`,text:e});break}case`at`:{let e=f.id||f.user_id||``,t=f.role;n.push({type:`at`,id:e,...t?{role:t}:{}});break}case`quote`:{let e=f.id||f.message_id||``,t={};for(let[e,n]of Object.entries(f))e!==`id`&&e!==`message_id`&&(t[e]=n);n.push({type:`quote`,...e?{id:e}:{},...Object.keys(t).length>0?{attrs:t}:{}});break}case`img`:case`image`:{let e=f.src||f.url||``,t=f.width?parseInt(f.width,10):void 0,r=f.height?parseInt(f.height,10):void 0;n.push({type:`image`,src:e,...f.alt?{alt:f.alt}:{},...t===void 0?{}:{width:t},...r===void 0?{}:{height:r}});break}case`audio`:{let e=f.src||f.url||``;n.push({type:`audio`,src:e});break}case`video`:{let e=f.src||f.url||``;n.push({type:`video`,src:e});break}case`button`:{let e=f.id||``,t=f.label||``,r=f.action||f.pcard;n.push({type:`button`,id:e,label:t,...r?{action:r}:{}});break}case`witness`:{let e=f.verdict||`pass`,t=f.proof,r={};for(let[e,t]of Object.entries(f))e!==`verdict`&&e!==`proof`&&(r[e]=t);n.push({type:`witness`,verdict:e,...t?{proof:t}:{},...Object.keys(r).length>0?{attrs:r}:{}});break}case`action`:{let e=f.id||``;n.push({type:`action`,id:e});break}case`card`:{let e=f.hash||``,t=f.handle||``,r=f.cardType||f[`card-type`]||`document`;n.push({type:`card`,hash:e,handle:t,cardType:r});break}case`execute`:{let e=f.pcard||``,t=f.input||``,r=f.label;n.push({type:`execute`,pcard:e,input:t,...r?{label:r}:{}});break}case`model3d`:{let e=f.src||f.url||``,t={};for(let[e,n]of Object.entries(f))e!==`src`&&e!==`url`&&(t[e]=n);n.push({type:`model3d`,src:e,...Object.keys(t).length>0?{attrs:t}:{}});break}default:n.push({type:d,...Object.keys(f).length>0?{attrs:f}:{}})}}if(i<t.length){let e=uu(t.slice(i));if(e.length>0){if(n.length>0&&n[n.length-1]?.type===`text`){let t=n[n.length-1];n[n.length-1]={...t,text:(t.text??``)+e}}else n.push({type:`text`,text:e})}}return n.length===0&&t.length>0&&n.push({type:`text`,text:t}),n}function mu(e){if(e instanceof M){let t=e.metadata.get(`speech_act_type`);if(typeof t==`string`&&[`assertive`,`directive`,`commissive`,`expressive`,`declarative`].includes(t))return t;if(e.payload.kind===`structured`&&typeof e.payload.value==`object`){let t=e.payload.value;if(t.speechActType&&typeof t.speechActType==`string`)return t.speechActType}return`assertive`}if(e.elements.some(e=>e.type===`execute`||e.type===`action`||e.type===`button`))return`directive`;let t=e.elements.filter(e=>e.type===`text`&&e.text).map(e=>e.text).join(` `).toLowerCase();return t.startsWith(`i declare`)||t.startsWith(`verdict:`)||t.startsWith(`sealed:`)?`declarative`:t.startsWith(`i promise`)||t.startsWith(`will `)||t.startsWith(`plan:`)?`commissive`:t.startsWith(`thanks`)||t.startsWith(`good`)||t.startsWith(`error`)||t.startsWith(`feedback:`)?`expressive`:t.endsWith(`?`)||t.startsWith(`/run`)||t.startsWith(`please`)||t.startsWith(`do `)?`directive`:`assertive`}function hu(e){return e==null?`null`:typeof e==`number`||typeof e==`boolean`||typeof e==`string`?JSON.stringify(e):Array.isArray(e)?`[`+e.map(hu).join(`,`)+`]`:typeof e==`object`?`{`+Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${hu(e[t])}`).join(`,`)+`}`:JSON.stringify(e)}function gu(e){let t=e.elements.map(e=>{let t={id:e.id??null,label:e.label??null,src:e.src??null,text:e.text??null,type:e.type};return e.hash!==void 0&&(t.hash=e.hash),e.handle!==void 0&&(t.handle=e.handle),e.cardType!==void 0&&(t.cardType=e.cardType),e.pcard!==void 0&&(t.pcard=e.pcard),e.input!==void 0&&(t.input=e.input),e.alt!==void 0&&(t.alt=e.alt),e.width!==void 0&&(t.width=e.width),e.height!==void 0&&(t.height=e.height),t}),n=hu({channel_id:e.channel_id,elements:t,id:e.id,timestamp:e.timestamp,user_did:e.user_did});return A.computeString(n).asHex()}function _u(e,t){let n=gu(e),r=t?.speechActType??mu(e),i={mcard_uri:`mcard:chat/message/${e.id}`,type:`clm:types:chat:satori_message`,header:{id:e.id,channel_id:e.channel_id,user_did:e.user_did,timestamp:e.timestamp},speech_act_type:r,elements:e.elements,content_hash:n},a=t?.authorDid??e.user_did,o=a.startsWith(`did:`)?j.create(a):j.create(`did:clm:agent:satori`),s=t?.mimeType??`application/x-satori+xml`,c=je(i);return M.create(`mcard:chat/message/${e.id}`,c,o,1,new Map([[`mimeType`,s],[`satori_id`,e.id],[`channel_id`,e.channel_id],[`speech_act_type`,r],[`g_time`,new Date(e.timestamp).toISOString()]]))}async function vu(e,t,n){let r=_u(t,{speechActType:n?.speechActType}),i=gu(t),a=`mcard:chat/message/${t.id}`;e.getPillar(`mcard`).putCard(r);let o=`mcard:session/${t.channel_id}/history`,s=e.getPillar(`knowledge`);return s.backend.registerHandle(ge.parse(`session:${t.channel_id}:history`),r.hash),s.putCard(M.create(o,r.hash.asHex(),r.author,1)),n?.recordExecutionLog!==!1&&e.getPillar(`execution_log`).putCard(r),{card:r,hashHex:i,handle:a}}Object.fromEntries(Object.entries({text:1,at:2,quote:3,image:4,audio:5,video:6,button:7,action:8,card:9,execute:10,witness:11,custom:12,message:16}).map(([e,t])=>[t,e])),Ir(Mr),Ir(Nr),Ir(Pr),Ir(Fr),Buffer.from(`302a300506032b656e032100`,`hex`);var yu={AUTH_CHALLENGE:`clm.auth.challenge`,AUTH_VERIFY:`clm.auth.verify`,CAS_GET:`clm.cas.get`,CAS_PUT:`clm.cas.put`,FIBER_INVOKE:`clm.fiber.invoke`,CONTINUATION_RESUME:`clm.continuation.resume`,MEMBRANE_ACTION:`clm.membrane.action`,STREAM_SUBSCRIBE:`clm.stream.subscribe`,NAME_TRANSITION:`clm.name.transition`};function bu(e,t,n){return JSON.stringify({jsonrpc:`2.0`,id:e,method:t,params:n})}function xu(e,t){return JSON.stringify({jsonrpc:`2.0`,id:e,result:t})}function Su(e,t,n,r){return JSON.stringify({jsonrpc:`2.0`,id:e,error:{code:t,message:n,data:r}})}function Cu(e,t){return JSON.stringify({jsonrpc:`2.0`,method:e,params:t})}var wu={};Cr({},{GATEWAY_METHODS:()=>yu,GatewayRouter:()=>Tu,HeadlessGatewayServer:()=>Ou,HeadlessIpcServer:()=>Eu,HeadlessWebSocketServer:()=>Du,createEmbeddedGatewayServer:()=>ku,formatErrorResponse:()=>Su,formatNotification:()=>Cu,formatRequest:()=>bu,formatSuccessResponse:()=>xu});var Tu=class{ctx;activeChallenges=new Map;authenticatedSessions=new Map;inMemoryCas=new Map;constructor(e){this.ctx=e}async handleRequest(e){let t;if(typeof e==`string`)try{t=JSON.parse(e)}catch{return Su(null,-32700,`Parse error`)}else t=e;if(!t||t.jsonrpc!==`2.0`||!t.method)return Su(t?.id??null,-32600,`Invalid Request`);try{switch(t.method){case yu.AUTH_CHALLENGE:{let e=this.handleAuthChallenge();return xu(t.id,e)}case yu.AUTH_VERIFY:{let e=t.params,n=this.handleAuthVerify(e);return xu(t.id,n)}case`card.get`:case yu.CAS_GET:{let e=typeof t.params==`string`?{hash:t.params}:t.params,n=await this.handleCasGet(e);return xu(t.id,n)}case`card.put`:case yu.CAS_PUT:{let e=t.params,n=await this.handleCasPut(e);return xu(t.id,n)}case`collection.query`:{let e=t.params||{},n=await this.handleCollectionQuery(e);return xu(t.id,n)}case`ptr.execute`:case yu.FIBER_INVOKE:{let e=t.params,n=await this.handleFiberInvoke(e);return xu(t.id,n)}case`cpn.subscribe`:case yu.STREAM_SUBSCRIBE:{let e={subscribed:!0,streamId:`sub_${c()}`};return xu(t.id,e)}case`continuation.resume`:case yu.CONTINUATION_RESUME:{let e=t.params,n=await this.handleContinuationResume(e);return xu(t.id,n)}case yu.MEMBRANE_ACTION:{let e=t.params,n=await this.handleMembraneAction(e);return xu(t.id,n)}default:return Su(t.id,-32601,`Method not found: ${t.method}`)}}catch(e){return Su(t.id,-32e3,e?.message??`Internal kernel gateway error`)}}async handleCollectionQuery(e){let t=[];for(let[e,n]of this.inMemoryCas.entries())t.push({hash:e,content:n});return{rows:t,rowCount:t.length}}handleAuthChallenge(){let e=`nonce_${c()}`,t=Date.now();return this.activeChallenges.set(e,{nonce:e,createdAt:t}),{nonce:e,timestamp:t}}handleAuthVerify(e){if(!e?.did||!e?.nonce||!e?.signature)throw Error(`Missing authentication parameters`);if(!this.activeChallenges.get(e.nonce))throw Error(`Challenge nonce expired or invalid`);this.activeChallenges.delete(e.nonce);let t=`token_${c()}`;return this.authenticatedSessions.set(t,{did:e.did,token:t,createdAt:Date.now()}),{token:t,did:e.did,capabilities:[`cas:read`,`cas:write`,`fiber:invoke`,`membrane:dispatch`]}}async handleCasGet(e){if(!e?.hash)throw Error(`Missing hash parameter`);if(this.ctx.mcardFs)try{let t=await this.ctx.mcardFs.get(e.hash);if(t)return{hash:e.hash,content:typeof t.content==`string`?t.content:JSON.stringify(t.content),exists:!0}}catch{}let t=this.inMemoryCas.get(e.hash);return{hash:e.hash,content:t,exists:t!==void 0}}async handleCasPut(e){if(e?.content===void 0)throw Error(`Missing content parameter`);let t=pe(e.content),n=new Date().toISOString();if(this.ctx.mcardFs)try{await this.ctx.mcardFs.put({hash:t,content:e.content,g_time:n,author:e.author})}catch{}return this.inMemoryCas.set(t,e.content),{hash:t,g_time:n}}async handleFiberInvoke(e){if(!e?.pcard_handle)throw Error(`Missing pcard_handle`);let t=`fiber_${c()}`;return{status:`completed`,output_hash:pe(`out_${e.input_mcard_hash}_${Date.now()}`),fiber_id:t}}async handleContinuationResume(e){if(!e?.token)throw Error(`Missing continuation token`);this.ctx.membrane&&await this.ctx.membrane.notifyContinuationResume(e.token,e.input);let t=pe(`resumed_${e.token}_${JSON.stringify(e.input)}`);return{success:!0,resumed_token:e.token,output_hash:t}}async handleMembraneAction(e){if(!this.ctx.membrane)throw Error(`MembraneService not registered on Context`);return await this.ctx.membrane.dispatchAction(e)}},Eu=class{router;socketPath;server=null;clients=new Set;constructor(e,t){this.router=e,this.socketPath=t.socketPath}async start(){if(!this.server){if(process.platform!==`win32`&&pi.existsSync(this.socketPath))try{pi.unlinkSync(this.socketPath)}catch{}return new Promise((e,t)=>{this.server=wu.createServer(e=>{this.clients.add(e);let t=``;e.on(`data`,async n=>{t+=n.toString(`utf8`);let r;for(;(r=t.indexOf(`
44
+ `))!==-1;){let n=t.slice(0,r).trim();if(t=t.slice(r+1),n.length>0){let t=await this.router.handleRequest(n);e.destroyed||e.write(t+`
45
+ `)}}}),e.on(`close`,()=>{this.clients.delete(e)}),e.on(`error`,t=>{console.error(`IPC client socket error:`,t),this.clients.delete(e)})}),this.server.on(`error`,e=>{t(e)}),this.server.listen(this.socketPath,()=>{e()})})}}broadcast(e){let t=e.endsWith(`
46
+ `)?e:e+`
47
+ `;for(let e of this.clients)e.destroyed||e.write(t)}async stop(){for(let e of this.clients)e.destroy();if(this.clients.clear(),this.server&&=(await new Promise(e=>{this.server?.close(()=>e())}),null),process.platform!==`win32`&&pi.existsSync(this.socketPath))try{pi.unlinkSync(this.socketPath)}catch{}}getClientCount(){return this.clients.size}},Du=class{router;port;host;wss=null;clients=new Set;constructor(e,t){this.router=e,this.port=t.port,this.host=t.host??`127.0.0.1`}async start(){if(this.wss){let e=this.wss.address();return typeof e==`object`&&e?e.port:this.port}return new Promise((e,t)=>{this.wss=new Yl({port:this.port,host:this.host},()=>{let t=this.wss?.address();e(typeof t==`object`&&t?t.port:this.port)}),this.wss.on(`error`,e=>{t(e)}),this.wss.on(`connection`,e=>{this.clients.add(e),e.on(`message`,async t=>{try{let n=t.toString(`utf8`),r=await this.router.handleRequest(n);e.readyState===Jl.OPEN&&e.send(r)}catch(e){console.error(`WebSocket message processing error:`,e)}}),e.on(`close`,()=>{this.clients.delete(e)}),e.on(`error`,()=>{this.clients.delete(e)})})})}broadcast(e){for(let t of this.clients)t.readyState===Jl.OPEN&&t.send(e)}async stop(){for(let e of this.clients)e.close();this.clients.clear(),this.wss&&=(await new Promise(e=>{this.wss?.close(()=>e())}),null)}getClientCount(){return this.clients.size}getPort(){let e=this.wss?.address();return typeof e==`object`&&e?e.port:this.port}},Ou=class{router;ipcServer;wsServer;constructor(e,t){this.router=new Tu(e),t.ipc&&(this.ipcServer=new Eu(this.router,t.ipc)),t.websocket&&(this.wsServer=new Du(this.router,t.websocket))}async start(){let e;return this.ipcServer&&await this.ipcServer.start(),this.wsServer&&(e=await this.wsServer.start()),{wsPort:e}}broadcast(e){this.ipcServer?.broadcast(e),this.wsServer?.broadcast(e)}async stop(){await Promise.all([this.ipcServer?.stop(),this.wsServer?.stop()])}};async function ku(e,t){let{Context:r}=await n(async()=>{let{Context:e}=await Promise.resolve().then(()=>sg);return{Context:e}},void 0),i=new Ou(t||new r,e);return await i.start(),i}var Au={2:`need dictionary`,1:`stream end`,0:``,"-1":`file error`,"-2":`stream error`,"-3":`data error`,"-4":`insufficient memory`,"-5":`buffer error`,"-6":`incompatible version`};function ju(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=``,this.state=null,this.data_type=2,this.adler=0}function Mu(e,t,n,r,i){if(t.subarray&&e.subarray){e.set(t.subarray(n,n+r),i);return}for(var a=0;a<r;a++)e[i+a]=t[n+a]}var Nu=Uint8Array,Pu=Uint16Array,Fu=Int32Array,Iu=4,Lu=0,Ru=1,zu=2;function Bu(e){for(var t=e.length;--t>=0;)e[t]=0}var Vu=0,Hu=1,Uu=2,Wu=3,Gu=258,Ku=29,qu=256,Ju=qu+1+Ku,Yu=30,Xu=19,Zu=2*Ju+1,Qu=15,$u=16,ed=7,td=256,nd=16,rd=17,id=18,ad=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],od=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],sd=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],cd=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ld=512,ud=Array((Ju+2)*2);Bu(ud);var dd=Array(Yu*2);Bu(dd);var fd=Array(ld);Bu(fd);var pd=Array(Gu-Wu+1);Bu(pd);var md=Array(Ku);Bu(md);var hd=Array(Yu);Bu(hd);function gd(e,t,n,r,i){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=i,this.has_stree=e&&e.length}var _d,vd,yd;function bd(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function xd(e){return e<256?fd[e]:fd[256+(e>>>7)]}function Sd(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function Cd(e,t,n){e.bi_valid>$u-n?(e.bi_buf|=t<<e.bi_valid&65535,Sd(e,e.bi_buf),e.bi_buf=t>>$u-e.bi_valid,e.bi_valid+=n-$u):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)}function wd(e,t,n){Cd(e,n[t*2],n[t*2+1])}function Td(e,t){var n=0;do n|=e&1,e>>>=1,n<<=1;while(--t>0);return n>>>1}function Ed(e){e.bi_valid===16?(Sd(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function Dd(e,t){var n=t.dyn_tree,r=t.max_code,i=t.stat_desc.static_tree,a=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,c=t.stat_desc.max_length,l,u,d,f,p,m,h=0;for(f=0;f<=Qu;f++)e.bl_count[f]=0;for(n[e.heap[e.heap_max]*2+1]=0,l=e.heap_max+1;l<Zu;l++)u=e.heap[l],f=n[n[u*2+1]*2+1]+1,f>c&&(f=c,h++),n[u*2+1]=f,!(u>r)&&(e.bl_count[f]++,p=0,u>=s&&(p=o[u-s]),m=n[u*2],e.opt_len+=m*(f+p),a&&(e.static_len+=m*(i[u*2+1]+p)));if(h!==0){do{for(f=c-1;e.bl_count[f]===0;)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[c]--,h-=2}while(h>0);for(f=c;f!==0;f--)for(u=e.bl_count[f];u!==0;)d=e.heap[--l],!(d>r)&&(n[d*2+1]!==f&&(e.opt_len+=(f-n[d*2+1])*n[d*2],n[d*2+1]=f),u--)}}function Od(e,t,n){for(var r=Array(Qu+1),i=0,a=1,o;a<=Qu;a++)r[a]=i=i+n[a-1]<<1;for(o=0;o<=t;o++){var s=e[o*2+1];s!==0&&(e[o*2]=Td(r[s]++,s))}}function kd(){var e,t,n,r,i,a=Array(Qu+1);for(n=0,r=0;r<Ku-1;r++)for(md[r]=n,e=0;e<1<<ad[r];e++)pd[n++]=r;for(pd[n-1]=r,i=0,r=0;r<16;r++)for(hd[r]=i,e=0;e<1<<od[r];e++)fd[i++]=r;for(i>>=7;r<Yu;r++)for(hd[r]=i<<7,e=0;e<1<<od[r]-7;e++)fd[256+i++]=r;for(t=0;t<=Qu;t++)a[t]=0;for(e=0;e<=143;)ud[e*2+1]=8,e++,a[8]++;for(;e<=255;)ud[e*2+1]=9,e++,a[9]++;for(;e<=279;)ud[e*2+1]=7,e++,a[7]++;for(;e<=287;)ud[e*2+1]=8,e++,a[8]++;for(Od(ud,Ju+1,a),e=0;e<Yu;e++)dd[e*2+1]=5,dd[e*2]=Td(e,5);_d=new gd(ud,ad,qu+1,Ju,Qu),vd=new gd(dd,od,0,Yu,Qu),yd=new gd([],sd,0,Xu,ed)}function Ad(e){for(var t=0;t<Ju;t++)e.dyn_ltree[t*2]=0;for(t=0;t<Yu;t++)e.dyn_dtree[t*2]=0;for(t=0;t<Xu;t++)e.bl_tree[t*2]=0;e.dyn_ltree[td*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function jd(e){e.bi_valid>8?Sd(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function Md(e,t,n,r){jd(e),r&&(Sd(e,n),Sd(e,~n)),Mu(e.pending_buf,e.window,t,n,e.pending),e.pending+=n}function Nd(e,t,n,r){var i=t*2,a=n*2;return e[i]<e[a]||e[i]===e[a]&&r[t]<=r[n]}function Pd(e,t,n){for(var r=e.heap[n],i=n<<1;i<=e.heap_len&&(i<e.heap_len&&Nd(t,e.heap[i+1],e.heap[i],e.depth)&&i++,!Nd(t,r,e.heap[i],e.depth));)e.heap[n]=e.heap[i],n=i,i<<=1;e.heap[n]=r}function Fd(e,t,n){var r,i,a=0,o,s;if(e.last_lit!==0)do r=e.pending_buf[e.d_buf+a*2]<<8|e.pending_buf[e.d_buf+a*2+1],i=e.pending_buf[e.l_buf+a],a++,r===0?wd(e,i,t):(o=pd[i],wd(e,o+qu+1,t),s=ad[o],s!==0&&(i-=md[o],Cd(e,i,s)),r--,o=xd(r),wd(e,o,n),s=od[o],s!==0&&(r-=hd[o],Cd(e,r,s)));while(a<e.last_lit);wd(e,td,t)}function Id(e,t){var n=t.dyn_tree,r=t.stat_desc.static_tree,i=t.stat_desc.has_stree,a=t.stat_desc.elems,o,s,c=-1,l;for(e.heap_len=0,e.heap_max=Zu,o=0;o<a;o++)n[o*2]===0?n[o*2+1]=0:(e.heap[++e.heap_len]=c=o,e.depth[o]=0);for(;e.heap_len<2;)l=e.heap[++e.heap_len]=c<2?++c:0,n[l*2]=1,e.depth[l]=0,e.opt_len--,i&&(e.static_len-=r[l*2+1]);for(t.max_code=c,o=e.heap_len>>1;o>=1;o--)Pd(e,n,o);l=a;do o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Pd(e,n,1),s=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=s,n[l*2]=n[o*2]+n[s*2],e.depth[l]=(e.depth[o]>=e.depth[s]?e.depth[o]:e.depth[s])+1,n[o*2+1]=n[s*2+1]=l,e.heap[1]=l++,Pd(e,n,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],Dd(e,t),Od(n,c,e.bl_count)}function Ld(e,t,n){var r,i=-1,a,o=t[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)a=o,o=t[(r+1)*2+1],!(++s<c&&a===o)&&(s<l?e.bl_tree[a*2]+=s:a===0?s<=10?e.bl_tree[rd*2]++:e.bl_tree[id*2]++:(a!==i&&e.bl_tree[a*2]++,e.bl_tree[nd*2]++),s=0,i=a,o===0?(c=138,l=3):a===o?(c=6,l=3):(c=7,l=4))}function Rd(e,t,n){var r,i=-1,a,o=t[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),r=0;r<=n;r++)if(a=o,o=t[(r+1)*2+1],!(++s<c&&a===o)){if(s<l)do wd(e,a,e.bl_tree);while(--s!==0);else a===0?s<=10?(wd(e,rd,e.bl_tree),Cd(e,s-3,3)):(wd(e,id,e.bl_tree),Cd(e,s-11,7)):(a!==i&&(wd(e,a,e.bl_tree),s--),wd(e,nd,e.bl_tree),Cd(e,s-3,2));s=0,i=a,o===0?(c=138,l=3):a===o?(c=6,l=3):(c=7,l=4)}}function zd(e){var t;for(Ld(e,e.dyn_ltree,e.l_desc.max_code),Ld(e,e.dyn_dtree,e.d_desc.max_code),Id(e,e.bl_desc),t=Xu-1;t>=3&&e.bl_tree[cd[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function Bd(e,t,n,r){var i;for(Cd(e,t-257,5),Cd(e,n-1,5),Cd(e,r-4,4),i=0;i<r;i++)Cd(e,e.bl_tree[cd[i]*2+1],3);Rd(e,e.dyn_ltree,t-1),Rd(e,e.dyn_dtree,n-1)}function Vd(e){for(var t=4093624447,n=0;n<=31;n++,t>>>=1)if(t&1&&e.dyn_ltree[n*2]!==0)return Lu;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return Ru;for(n=32;n<qu;n++)if(e.dyn_ltree[n*2]!==0)return Ru;return Lu}var Hd=!1;function Ud(e){Hd||=(kd(),!0),e.l_desc=new bd(e.dyn_ltree,_d),e.d_desc=new bd(e.dyn_dtree,vd),e.bl_desc=new bd(e.bl_tree,yd),e.bi_buf=0,e.bi_valid=0,Ad(e)}function Wd(e,t,n,r){Cd(e,(Vu<<1)+ +!!r,3),Md(e,t,n,!0)}function Gd(e){Cd(e,Hu<<1,3),wd(e,td,ud),Ed(e)}function Kd(e,t,n,r){var i,a,o=0;e.level>0?(e.strm.data_type===zu&&(e.strm.data_type=Vd(e)),Id(e,e.l_desc),Id(e,e.d_desc),o=zd(e),i=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=i&&(i=a)):i=a=n+5,n+4<=i&&t!==-1?Wd(e,t,n,r):e.strategy===Iu||a===i?(Cd(e,(Hu<<1)+ +!!r,3),Fd(e,ud,dd)):(Cd(e,(Uu<<1)+ +!!r,3),Bd(e,e.l_desc.max_code+1,e.d_desc.max_code+1,o+1),Fd(e,e.dyn_ltree,e.dyn_dtree)),Ad(e),r&&jd(e)}function qd(e,t,n){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=n&255,e.last_lit++,t===0?e.dyn_ltree[n*2]++:(e.matches++,t--,e.dyn_ltree[(pd[n]+qu+1)*2]++,e.dyn_dtree[xd(t)*2]++),e.last_lit===e.lit_bufsize-1}function Jd(e,t,n,r){for(var i=e&65535|0,a=e>>>16&65535|0,o=0;n!==0;){o=n>2e3?2e3:n,n-=o;do i=i+t[r++]|0,a=a+i|0;while(--o);i%=65521,a%=65521}return i|a<<16|0}function Yd(){for(var e,t=[],n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=e&1?3988292384^e>>>1:e>>>1;t[n]=e}return t}var Xd=Yd();function W(e,t,n,r){var i=Xd,a=r+n;e^=-1;for(var o=r;o<a;o++)e=e>>>8^i[(e^t[o])&255];return e^-1}var Zd=0,Qd=1,$d=3,ef=4,tf=5,nf=0,rf=1,af=-2,of=-3,sf=-5,cf=-1,lf=1,uf=2,df=3,ff=4,pf=2,mf=8,hf=9,gf=286,_f=30,vf=19,yf=2*gf+1,bf=15,G=3,xf=258,Sf=xf+G+1,Cf=32,wf=42,Tf=69,Ef=73,Df=91,Of=103,kf=113,Af=666,K=1,jf=2,Mf=3,Nf=4,Pf=3;function Ff(e,t){return e.msg=Au[t],t}function If(e){return(e<<1)-(e>4?9:0)}function Lf(e){for(var t=e.length;--t>=0;)e[t]=0}function Rf(e){var t=e.state,n=t.pending;n>e.avail_out&&(n=e.avail_out),n!==0&&(Mu(e.output,t.pending_buf,t.pending_out,n,e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))}function q(e,t){Kd(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Rf(e.strm)}function J(e,t){e.pending_buf[e.pending++]=t}function zf(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function Bf(e,t,n,r){var i=e.avail_in;return i>r&&(i=r),i===0?0:(e.avail_in-=i,Mu(t,e.input,e.next_in,i,n),e.state.wrap===1?e.adler=Jd(e.adler,t,i,n):e.state.wrap===2&&(e.adler=W(e.adler,t,i,n)),e.next_in+=i,e.total_in+=i,i)}function Vf(e,t){var n=e.max_chain_length,r=e.strstart,i,a,o=e.prev_length,s=e.nice_match,c=e.strstart>e.w_size-Sf?e.strstart-(e.w_size-Sf):0,l=e.window,u=e.w_mask,d=e.prev,f=e.strstart+xf,p=l[r+o-1],m=l[r+o];e.prev_length>=e.good_match&&(n>>=2),s>e.lookahead&&(s=e.lookahead);do if(i=t,l[i+o]===m&&l[i+o-1]===p&&l[i]===l[r]&&l[++i]===l[r+1]){r+=2,i++;do;while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&r<f);if(a=xf-(f-r),r=f-xf,a>o){if(e.match_start=t,o=a,a>=s)break;p=l[r+o-1],m=l[r+o]}}while((t=d[t&u])>c&&--n!==0);return o<=e.lookahead?o:e.lookahead}function Hf(e){var t=e.w_size,n,r,i,a,o;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Sf)){Mu(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,r=e.hash_size,n=r;do i=e.head[--n],e.head[n]=i>=t?i-t:0;while(--r);r=t,n=r;do i=e.prev[--n],e.prev[n]=i>=t?i-t:0;while(--r);a+=t}if(e.strm.avail_in===0)break;if(r=Bf(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=r,e.lookahead+e.insert>=G)for(o=e.strstart-e.insert,e.ins_h=e.window[o],e.ins_h=(e.ins_h<<e.hash_shift^e.window[o+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[o+G-1])&e.hash_mask,e.prev[o&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=o,o++,e.insert--,!(e.lookahead+e.insert<G)););}while(e.lookahead<Sf&&e.strm.avail_in!==0)}function Uf(e,t){var n=65535;for(n>e.pending_buf_size-5&&(n=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Hf(e),e.lookahead===0&&t===Zd)return K;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+n;if((e.strstart===0||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,q(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-Sf&&(q(e,!1),e.strm.avail_out===0))return K}return e.insert=0,t===ef?(q(e,!0),e.strm.avail_out===0?Mf:Nf):(e.strstart>e.block_start&&(q(e,!1),e.strm.avail_out),K)}function Wf(e,t){for(var n,r;;){if(e.lookahead<Sf){if(Hf(e),e.lookahead<Sf&&t===Zd)return K;if(e.lookahead===0)break}if(n=0,e.lookahead>=G&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+G-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),n!==0&&e.strstart-n<=e.w_size-Sf&&(e.match_length=Vf(e,n)),e.match_length>=G){if(r=qd(e,e.strstart-e.match_start,e.match_length-G),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=G){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+G-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask}else r=qd(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(q(e,!1),e.strm.avail_out===0))return K}return e.insert=e.strstart<G-1?e.strstart:G-1,t===ef?(q(e,!0),e.strm.avail_out===0?Mf:Nf):e.last_lit&&(q(e,!1),e.strm.avail_out===0)?K:jf}function Gf(e,t){for(var n,r,i;;){if(e.lookahead<Sf){if(Hf(e),e.lookahead<Sf&&t===Zd)return K;if(e.lookahead===0)break}if(n=0,e.lookahead>=G&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+G-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=G-1,n!==0&&e.prev_length<e.max_lazy_match&&e.strstart-n<=e.w_size-Sf&&(e.match_length=Vf(e,n),e.match_length<=5&&(e.strategy===lf||e.match_length===G&&e.strstart-e.match_start>4096)&&(e.match_length=G-1)),e.prev_length>=G&&e.match_length<=e.prev_length){i=e.strstart+e.lookahead-G,r=qd(e,e.strstart-1-e.prev_match,e.prev_length-G),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=i&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+G-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=G-1,e.strstart++,r&&(q(e,!1),e.strm.avail_out===0))return K}else if(e.match_available){if(r=qd(e,0,e.window[e.strstart-1]),r&&q(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return K}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&=(r=qd(e,0,e.window[e.strstart-1]),0),e.insert=e.strstart<G-1?e.strstart:G-1,t===ef?(q(e,!0),e.strm.avail_out===0?Mf:Nf):e.last_lit&&(q(e,!1),e.strm.avail_out===0)?K:jf}function Kf(e,t){for(var n,r,i,a,o=e.window;;){if(e.lookahead<=xf){if(Hf(e),e.lookahead<=xf&&t===Zd)return K;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=G&&e.strstart>0&&(i=e.strstart-1,r=o[i],r===o[++i]&&r===o[++i]&&r===o[++i])){a=e.strstart+xf;do;while(r===o[++i]&&r===o[++i]&&r===o[++i]&&r===o[++i]&&r===o[++i]&&r===o[++i]&&r===o[++i]&&r===o[++i]&&i<a);e.match_length=xf-(a-i),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=G?(n=qd(e,1,e.match_length-G),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=qd(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(q(e,!1),e.strm.avail_out===0))return K}return e.insert=0,t===ef?(q(e,!0),e.strm.avail_out===0?Mf:Nf):e.last_lit&&(q(e,!1),e.strm.avail_out===0)?K:jf}function qf(e,t){for(var n;;){if(e.lookahead===0&&(Hf(e),e.lookahead===0)){if(t===Zd)return K;break}if(e.match_length=0,n=qd(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(q(e,!1),e.strm.avail_out===0))return K}return e.insert=0,t===ef?(q(e,!0),e.strm.avail_out===0?Mf:Nf):e.last_lit&&(q(e,!1),e.strm.avail_out===0)?K:jf}function Jf(e,t,n,r,i){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=i}var Yf=[new Jf(0,0,0,0,Uf),new Jf(4,4,8,4,Wf),new Jf(4,5,16,8,Wf),new Jf(4,6,32,32,Wf),new Jf(4,4,16,16,Gf),new Jf(8,16,32,32,Gf),new Jf(8,16,128,128,Gf),new Jf(8,32,128,256,Gf),new Jf(32,128,258,1024,Gf),new Jf(32,258,258,4096,Gf)];function Xf(e){e.window_size=2*e.w_size,Lf(e.head),e.max_lazy_match=Yf[e.level].max_lazy,e.good_match=Yf[e.level].good_length,e.nice_match=Yf[e.level].nice_length,e.max_chain_length=Yf[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=G-1,e.match_available=0,e.ins_h=0}function Zf(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=mf,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Pu(yf*2),this.dyn_dtree=new Pu((2*_f+1)*2),this.bl_tree=new Pu((2*vf+1)*2),Lf(this.dyn_ltree),Lf(this.dyn_dtree),Lf(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Pu(bf+1),this.heap=new Pu(2*gf+1),Lf(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Pu(2*gf+1),Lf(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Qf(e){var t;return!e||!e.state?Ff(e,af):(e.total_in=e.total_out=0,e.data_type=pf,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?wf:kf,e.adler=t.wrap===2?0:1,t.last_flush=Zd,Ud(t),nf)}function $f(e){var t=Qf(e);return t===nf&&Xf(e.state),t}function ep(e,t,n,r,i,a){if(!e)return af;var o=1;if(t===cf&&(t=6),r<0?(o=0,r=-r):r>15&&(o=2,r-=16),i<1||i>hf||n!==mf||r<8||r>15||t<0||t>9||a<0||a>ff)return Ff(e,af);r===8&&(r=9);var s=new Zf;return e.state=s,s.strm=e,s.wrap=o,s.gzhead=null,s.w_bits=r,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=i+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+G-1)/G),s.window=new Nu(s.w_size*2),s.head=new Pu(s.hash_size),s.prev=new Pu(s.w_size),s.lit_bufsize=1<<i+6,s.pending_buf_size=s.lit_bufsize*4,s.pending_buf=new Nu(s.pending_buf_size),s.d_buf=1*s.lit_bufsize,s.l_buf=3*s.lit_bufsize,s.level=t,s.strategy=a,s.method=n,$f(e)}function tp(e,t){var n,r,i,a;if(!e||!e.state||t>tf||t<0)return e?Ff(e,af):af;if(r=e.state,!e.output||!e.input&&e.avail_in!==0||r.status===Af&&t!==ef)return Ff(e,e.avail_out===0?sf:af);if(r.strm=e,n=r.last_flush,r.last_flush=t,r.status===wf){if(r.wrap===2)e.adler=0,J(r,31),J(r,139),J(r,8),r.gzhead?(J(r,+!!r.gzhead.text+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),J(r,r.gzhead.time&255),J(r,r.gzhead.time>>8&255),J(r,r.gzhead.time>>16&255),J(r,r.gzhead.time>>24&255),J(r,r.level===9?2:r.strategy>=uf||r.level<2?4:0),J(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(J(r,r.gzhead.extra.length&255),J(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=W(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=Tf):(J(r,0),J(r,0),J(r,0),J(r,0),J(r,0),J(r,r.level===9?2:r.strategy>=uf||r.level<2?4:0),J(r,Pf),r.status=kf);else{var o=mf+(r.w_bits-8<<4)<<8,s=-1;s=r.strategy>=uf||r.level<2?0:r.level<6?1:r.level===6?2:3,o|=s<<6,r.strstart!==0&&(o|=Cf),o+=31-o%31,r.status=kf,zf(r,o),r.strstart!==0&&(zf(r,e.adler>>>16),zf(r,e.adler&65535)),e.adler=1}}if(r.status===Tf){if(r.gzhead.extra){for(i=r.pending;r.gzindex<(r.gzhead.extra.length&65535)&&!(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>i&&(e.adler=W(e.adler,r.pending_buf,r.pending-i,i)),Rf(e),i=r.pending,r.pending===r.pending_buf_size));)J(r,r.gzhead.extra[r.gzindex]&255),r.gzindex++;r.gzhead.hcrc&&r.pending>i&&(e.adler=W(e.adler,r.pending_buf,r.pending-i,i)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=Ef)}else r.status=Ef}if(r.status===Ef){if(r.gzhead.name){i=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>i&&(e.adler=W(e.adler,r.pending_buf,r.pending-i,i)),Rf(e),i=r.pending,r.pending===r.pending_buf_size)){a=1;break}a=r.gzindex<r.gzhead.name.length?r.gzhead.name.charCodeAt(r.gzindex++)&255:0,J(r,a)}while(a!==0);r.gzhead.hcrc&&r.pending>i&&(e.adler=W(e.adler,r.pending_buf,r.pending-i,i)),a===0&&(r.gzindex=0,r.status=Df)}else r.status=Df}if(r.status===Df){if(r.gzhead.comment){i=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>i&&(e.adler=W(e.adler,r.pending_buf,r.pending-i,i)),Rf(e),i=r.pending,r.pending===r.pending_buf_size)){a=1;break}a=r.gzindex<r.gzhead.comment.length?r.gzhead.comment.charCodeAt(r.gzindex++)&255:0,J(r,a)}while(a!==0);r.gzhead.hcrc&&r.pending>i&&(e.adler=W(e.adler,r.pending_buf,r.pending-i,i)),a===0&&(r.status=Of)}else r.status=Of}if(r.status===Of&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&Rf(e),r.pending+2<=r.pending_buf_size&&(J(r,e.adler&255),J(r,e.adler>>8&255),e.adler=0,r.status=kf)):r.status=kf),r.pending!==0){if(Rf(e),e.avail_out===0)return r.last_flush=-1,nf}else if(e.avail_in===0&&If(t)<=If(n)&&t!==ef)return Ff(e,sf);if(r.status===Af&&e.avail_in!==0)return Ff(e,sf);if(e.avail_in!==0||r.lookahead!==0||t!==Zd&&r.status!==Af){var c=r.strategy===uf?qf(r,t):r.strategy===df?Kf(r,t):Yf[r.level].func(r,t);if((c===Mf||c===Nf)&&(r.status=Af),c===K||c===Mf)return e.avail_out===0&&(r.last_flush=-1),nf;if(c===jf&&(t===Qd?Gd(r):t!==tf&&(Wd(r,0,0,!1),t===$d&&(Lf(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),Rf(e),e.avail_out===0))return r.last_flush=-1,nf}return t===ef?r.wrap<=0?rf:(r.wrap===2?(J(r,e.adler&255),J(r,e.adler>>8&255),J(r,e.adler>>16&255),J(r,e.adler>>24&255),J(r,e.total_in&255),J(r,e.total_in>>8&255),J(r,e.total_in>>16&255),J(r,e.total_in>>24&255)):(zf(r,e.adler>>>16),zf(r,e.adler&65535)),Rf(e),r.wrap>0&&(r.wrap=-r.wrap),r.pending===0?rf:nf):nf}function np(e){var t;return!e||!e.state?af:(t=e.state.status,t!==wf&&t!==Tf&&t!==Ef&&t!==Df&&t!==Of&&t!==kf&&t!==Af?Ff(e,af):(e.state=null,t===kf?Ff(e,of):nf))}var rp=30,ip=12;function ap(e,t){var n=e.state,r=e.next_in,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T=e.input,E;i=r+(e.avail_in-5),a=e.next_out,E=e.output,o=a-(t-e.avail_out),s=a+(e.avail_out-257),c=n.dmax,l=n.wsize,u=n.whave,d=n.wnext,f=n.window,p=n.hold,m=n.bits,h=n.lencode,g=n.distcode,_=(1<<n.lenbits)-1,v=(1<<n.distbits)-1;top:do{m<15&&(p+=T[r++]<<m,m+=8,p+=T[r++]<<m,m+=8),y=h[p&_];dolen:for(;;){if(b=y>>>24,p>>>=b,m-=b,b=y>>>16&255,b===0)E[a++]=y&65535;else if(b&16){x=y&65535,b&=15,b&&(m<b&&(p+=T[r++]<<m,m+=8),x+=p&(1<<b)-1,p>>>=b,m-=b),m<15&&(p+=T[r++]<<m,m+=8,p+=T[r++]<<m,m+=8),y=g[p&v];dodist:for(;;){if(b=y>>>24,p>>>=b,m-=b,b=y>>>16&255,b&16){if(S=y&65535,b&=15,m<b&&(p+=T[r++]<<m,m+=8,m<b&&(p+=T[r++]<<m,m+=8)),S+=p&(1<<b)-1,S>c){e.msg=`invalid distance too far back`,n.mode=rp;break top}if(p>>>=b,m-=b,b=a-o,S>b){if(b=S-b,b>u&&n.sane){e.msg=`invalid distance too far back`,n.mode=rp;break top}if(C=0,w=f,d===0){if(C+=l-b,b<x){x-=b;do E[a++]=f[C++];while(--b);C=a-S,w=E}}else if(d<b){if(C+=l+d-b,b-=d,b<x){x-=b;do E[a++]=f[C++];while(--b);if(C=0,d<x){b=d,x-=b;do E[a++]=f[C++];while(--b);C=a-S,w=E}}}else if(C+=d-b,b<x){x-=b;do E[a++]=f[C++];while(--b);C=a-S,w=E}for(;x>2;)E[a++]=w[C++],E[a++]=w[C++],E[a++]=w[C++],x-=3;x&&(E[a++]=w[C++],x>1&&(E[a++]=w[C++]))}else{C=a-S;do E[a++]=E[C++],E[a++]=E[C++],E[a++]=E[C++],x-=3;while(x>2);x&&(E[a++]=E[C++],x>1&&(E[a++]=E[C++]))}}else if(b&64){e.msg=`invalid distance code`,n.mode=rp;break top}else{y=g[(y&65535)+(p&(1<<b)-1)];continue dodist}break}}else if(!(b&64)){y=h[(y&65535)+(p&(1<<b)-1)];continue dolen}else if(b&32){n.mode=ip;break top}else{e.msg=`invalid literal/length code`,n.mode=rp;break top}break}}while(r<i&&a<s);x=m>>3,r-=x,m-=x<<3,p&=(1<<m)-1,e.next_in=r,e.next_out=a,e.avail_in=r<i?5+(i-r):5-(r-i),e.avail_out=a<s?257+(s-a):257-(a-s),n.hold=p,n.bits=m}var op=15,sp=852,cp=592,lp=0,up=1,dp=2,fp=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],pp=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],mp=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],hp=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];function gp(e,t,n,r,i,a,o,s){var c=s.bits,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0,y,b,x,S,C,w=null,T=0,E,D=new Pu(op+1),O=new Pu(op+1),ee=null,te=0,ne,re,ie;for(l=0;l<=op;l++)D[l]=0;for(u=0;u<r;u++)D[t[n+u]]++;for(p=c,f=op;f>=1&&D[f]===0;f--);if(p>f&&(p=f),f===0)return i[a++]=20971520,i[a++]=20971520,s.bits=1,0;for(d=1;d<f&&D[d]===0;d++);for(p<d&&(p=d),g=1,l=1;l<=op;l++)if(g<<=1,g-=D[l],g<0)return-1;if(g>0&&(e===lp||f!==1))return-1;for(O[1]=0,l=1;l<op;l++)O[l+1]=O[l]+D[l];for(u=0;u<r;u++)t[n+u]!==0&&(o[O[t[n+u]]++]=u);if(e===lp?(w=ee=o,E=19):e===up?(w=fp,T-=257,ee=pp,te-=257,E=256):(w=mp,ee=hp,E=-1),v=0,u=0,l=d,C=a,m=p,h=0,x=-1,_=1<<p,S=_-1,e===up&&_>sp||e===dp&&_>cp)return 1;for(var ae=0;;){ae++,ne=l-h,o[u]<E?(re=0,ie=o[u]):o[u]>E?(re=ee[te+o[u]],ie=w[T+o[u]]):(re=96,ie=0),y=1<<l-h,b=1<<m,d=b;do b-=y,i[C+(v>>h)+b]=ne<<24|re<<16|ie|0;while(b!==0);for(y=1<<l-1;v&y;)y>>=1;if(y===0?v=0:(v&=y-1,v+=y),u++,--D[l]===0){if(l===f)break;l=t[n+o[u]]}if(l>p&&(v&S)!==x){for(h===0&&(h=p),C+=d,m=l-h,g=1<<m;m+h<f&&(g-=D[m+h],!(g<=0));)m++,g<<=1;if(_+=1<<m,e===up&&_>sp||e===dp&&_>cp)return 1;x=v&S,i[x]=p<<24|m<<16|C-a|0}}return v!==0&&(i[C+v]=l-h<<24|4194304),s.bits=p,0}var _p=0,vp=1,yp=2,bp=4,xp=5,Sp=6,Cp=0,wp=1,Tp=2,Ep=-2,Dp=-3,Op=-4,kp=-5,Ap=8,jp=1,Mp=2,Np=3,Pp=4,Fp=5,Ip=6,Lp=7,Rp=8,zp=9,Bp=10,Vp=11,Hp=12,Up=13,Wp=14,Gp=15,Kp=16,qp=17,Jp=18,Yp=19,Xp=20,Zp=21,Qp=22,$p=23,em=24,tm=25,nm=26,rm=27,im=28,am=29,Y=30,om=31,sm=32,cm=852,lm=592;function um(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function dm(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Pu(320),this.work=new Pu(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function fm(e){var t;return!e||!e.state?Ep:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg=``,t.wrap&&(e.adler=t.wrap&1),t.mode=jp,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Fu(cm),t.distcode=t.distdyn=new Fu(lm),t.sane=1,t.back=-1,Cp)}function pm(e){var t;return!e||!e.state?Ep:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,fm(e))}function mm(e,t){var n,r;return!e||!e.state||(r=e.state,t<0?(n=0,t=-t):(n=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?Ep:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,pm(e))}function hm(e,t){var n,r;return e?(r=new dm,e.state=r,r.window=null,n=mm(e,t),n!==Cp&&(e.state=null),n):Ep}var gm=!0,_m,vm;function ym(e){if(gm){var t;for(_m=new Fu(512),vm=new Fu(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(gp(vp,e.lens,0,288,_m,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;gp(yp,e.lens,0,32,vm,0,e.work,{bits:5}),gm=!1}e.lencode=_m,e.lenbits=9,e.distcode=vm,e.distbits=5}function bm(e,t,n,r){var i,a=e.state;return a.window===null&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new Nu(a.wsize)),r>=a.wsize?(Mu(a.window,t,n-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(i=a.wsize-a.wnext,i>r&&(i=r),Mu(a.window,t,n-r,i,a.wnext),r-=i,r?(Mu(a.window,t,n-r,r,0),a.wnext=r,a.whave=a.wsize):(a.wnext+=i,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=i))),0}function xm(e,t){var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g=0,_,v,y,b,x,S,C,w,T=new Nu(4),E,D,O=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return Ep;n=e.state,n.mode===Hp&&(n.mode=Up),o=e.next_out,i=e.output,c=e.avail_out,a=e.next_in,r=e.input,s=e.avail_in,l=n.hold,u=n.bits,d=s,f=c,w=Cp;inf_leave:for(;;)switch(n.mode){case jp:if(n.wrap===0){n.mode=Up;break}for(;u<16;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(n.wrap&2&&l===35615){n.check=0,T[0]=l&255,T[1]=l>>>8&255,n.check=W(n.check,T,2,0),l=0,u=0,n.mode=Mp;break}if(n.flags=0,n.head&&(n.head.done=!1),!(n.wrap&1)||(((l&255)<<8)+(l>>8))%31){e.msg=`incorrect header check`,n.mode=Y;break}if((l&15)!==Ap){e.msg=`unknown compression method`,n.mode=Y;break}if(l>>>=4,u-=4,C=(l&15)+8,n.wbits===0)n.wbits=C;else if(C>n.wbits){e.msg=`invalid window size`,n.mode=Y;break}n.dmax=1<<C,e.adler=n.check=1,n.mode=l&512?Bp:Hp,l=0,u=0;break;case Mp:for(;u<16;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(n.flags=l,(n.flags&255)!==Ap){e.msg=`unknown compression method`,n.mode=Y;break}if(n.flags&57344){e.msg=`unknown header flags set`,n.mode=Y;break}n.head&&(n.head.text=l>>8&1),n.flags&512&&(T[0]=l&255,T[1]=l>>>8&255,n.check=W(n.check,T,2,0)),l=0,u=0,n.mode=Np;case Np:for(;u<32;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.head&&(n.head.time=l),n.flags&512&&(T[0]=l&255,T[1]=l>>>8&255,T[2]=l>>>16&255,T[3]=l>>>24&255,n.check=W(n.check,T,4,0)),l=0,u=0,n.mode=Pp;case Pp:for(;u<16;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.head&&(n.head.xflags=l&255,n.head.os=l>>8),n.flags&512&&(T[0]=l&255,T[1]=l>>>8&255,n.check=W(n.check,T,2,0)),l=0,u=0,n.mode=Fp;case Fp:if(n.flags&1024){for(;u<16;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.length=l,n.head&&(n.head.extra_len=l),n.flags&512&&(T[0]=l&255,T[1]=l>>>8&255,n.check=W(n.check,T,2,0)),l=0,u=0}else n.head&&(n.head.extra=null);n.mode=Ip;case Ip:if(n.flags&1024&&(p=n.length,p>s&&(p=s),p&&(n.head&&(C=n.head.extra_len-n.length,n.head.extra||(n.head.extra=Array(n.head.extra_len)),Mu(n.head.extra,r,a,p,C)),n.flags&512&&(n.check=W(n.check,r,p,a)),s-=p,a+=p,n.length-=p),n.length))break inf_leave;n.length=0,n.mode=Lp;case Lp:if(n.flags&2048){if(s===0)break inf_leave;p=0;do C=r[a+p++],n.head&&C&&n.length<65536&&(n.head.name+=String.fromCharCode(C));while(C&&p<s);if(n.flags&512&&(n.check=W(n.check,r,p,a)),s-=p,a+=p,C)break inf_leave}else n.head&&(n.head.name=null);n.length=0,n.mode=Rp;case Rp:if(n.flags&4096){if(s===0)break inf_leave;p=0;do C=r[a+p++],n.head&&C&&n.length<65536&&(n.head.comment+=String.fromCharCode(C));while(C&&p<s);if(n.flags&512&&(n.check=W(n.check,r,p,a)),s-=p,a+=p,C)break inf_leave}else n.head&&(n.head.comment=null);n.mode=zp;case zp:if(n.flags&512){for(;u<16;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(l!==(n.check&65535)){e.msg=`header crc mismatch`,n.mode=Y;break}l=0,u=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=Hp;break;case Bp:for(;u<32;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}e.adler=n.check=um(l),l=0,u=0,n.mode=Vp;case Vp:if(n.havedict===0)return e.next_out=o,e.avail_out=c,e.next_in=a,e.avail_in=s,n.hold=l,n.bits=u,Tp;e.adler=n.check=1,n.mode=Hp;case Hp:if(t===xp||t===Sp)break inf_leave;case Up:if(n.last){l>>>=u&7,u-=u&7,n.mode=rm;break}for(;u<3;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}switch(n.last=l&1,l>>>=1,--u,l&3){case 0:n.mode=Wp;break;case 1:if(ym(n),n.mode=Xp,t===Sp){l>>>=2,u-=2;break inf_leave}break;case 2:n.mode=qp;break;case 3:e.msg=`invalid block type`,n.mode=Y}l>>>=2,u-=2;break;case Wp:for(l>>>=u&7,u-=u&7;u<32;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if((l&65535)!=(l>>>16^65535)){e.msg=`invalid stored block lengths`,n.mode=Y;break}if(n.length=l&65535,l=0,u=0,n.mode=Gp,t===Sp)break inf_leave;case Gp:n.mode=Kp;case Kp:if(p=n.length,p){if(p>s&&(p=s),p>c&&(p=c),p===0)break inf_leave;Mu(i,r,a,p,o),s-=p,a+=p,c-=p,o+=p,n.length-=p;break}n.mode=Hp;break;case qp:for(;u<14;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(n.nlen=(l&31)+257,l>>>=5,u-=5,n.ndist=(l&31)+1,l>>>=5,u-=5,n.ncode=(l&15)+4,l>>>=4,u-=4,n.nlen>286||n.ndist>30){e.msg=`too many length or distance symbols`,n.mode=Y;break}n.have=0,n.mode=Jp;case Jp:for(;n.have<n.ncode;){for(;u<3;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.lens[O[n.have++]]=l&7,l>>>=3,u-=3}for(;n.have<19;)n.lens[O[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,E={bits:n.lenbits},w=gp(_p,n.lens,0,19,n.lencode,0,n.work,E),n.lenbits=E.bits,w){e.msg=`invalid code lengths set`,n.mode=Y;break}n.have=0,n.mode=Yp;case Yp:for(;n.have<n.nlen+n.ndist;){for(;g=n.lencode[l&(1<<n.lenbits)-1],_=g>>>24,v=g>>>16&255,y=g&65535,!(_<=u);){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(y<16)l>>>=_,u-=_,n.lens[n.have++]=y;else{if(y===16){for(D=_+2;u<D;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(l>>>=_,u-=_,n.have===0){e.msg=`invalid bit length repeat`,n.mode=Y;break}C=n.lens[n.have-1],p=3+(l&3),l>>>=2,u-=2}else if(y===17){for(D=_+3;u<D;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}l>>>=_,u-=_,C=0,p=3+(l&7),l>>>=3,u-=3}else{for(D=_+7;u<D;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}l>>>=_,u-=_,C=0,p=11+(l&127),l>>>=7,u-=7}if(n.have+p>n.nlen+n.ndist){e.msg=`invalid bit length repeat`,n.mode=Y;break}for(;p--;)n.lens[n.have++]=C}}if(n.mode===Y)break;if(n.lens[256]===0){e.msg=`invalid code -- missing end-of-block`,n.mode=Y;break}if(n.lenbits=9,E={bits:n.lenbits},w=gp(vp,n.lens,0,n.nlen,n.lencode,0,n.work,E),n.lenbits=E.bits,w){e.msg=`invalid literal/lengths set`,n.mode=Y;break}if(n.distbits=6,n.distcode=n.distdyn,E={bits:n.distbits},w=gp(yp,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,E),n.distbits=E.bits,w){e.msg=`invalid distances set`,n.mode=Y;break}if(n.mode=Xp,t===Sp)break inf_leave;case Xp:n.mode=Zp;case Zp:if(s>=6&&c>=258){e.next_out=o,e.avail_out=c,e.next_in=a,e.avail_in=s,n.hold=l,n.bits=u,ap(e,f),o=e.next_out,i=e.output,c=e.avail_out,a=e.next_in,r=e.input,s=e.avail_in,l=n.hold,u=n.bits,n.mode===Hp&&(n.back=-1);break}for(n.back=0;g=n.lencode[l&(1<<n.lenbits)-1],_=g>>>24,v=g>>>16&255,y=g&65535,!(_<=u);){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(v&&!(v&240)){for(b=_,x=v,S=y;g=n.lencode[S+((l&(1<<b+x)-1)>>b)],_=g>>>24,v=g>>>16&255,y=g&65535,!(b+_<=u);){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}l>>>=b,u-=b,n.back+=b}if(l>>>=_,u-=_,n.back+=_,n.length=y,v===0){n.mode=nm;break}if(v&32){n.back=-1,n.mode=Hp;break}if(v&64){e.msg=`invalid literal/length code`,n.mode=Y;break}n.extra=v&15,n.mode=Qp;case Qp:if(n.extra){for(D=n.extra;u<D;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.length+=l&(1<<n.extra)-1,l>>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=$p;case $p:for(;g=n.distcode[l&(1<<n.distbits)-1],_=g>>>24,v=g>>>16&255,y=g&65535,!(_<=u);){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(!(v&240)){for(b=_,x=v,S=y;g=n.distcode[S+((l&(1<<b+x)-1)>>b)],_=g>>>24,v=g>>>16&255,y=g&65535,!(b+_<=u);){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}l>>>=b,u-=b,n.back+=b}if(l>>>=_,u-=_,n.back+=_,v&64){e.msg=`invalid distance code`,n.mode=Y;break}n.offset=y,n.extra=v&15,n.mode=em;case em:if(n.extra){for(D=n.extra;u<D;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.offset+=l&(1<<n.extra)-1,l>>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg=`invalid distance too far back`,n.mode=Y;break}n.mode=tm;case tm:if(c===0)break inf_leave;if(p=f-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){e.msg=`invalid distance too far back`,n.mode=Y;break}p>n.wnext?(p-=n.wnext,m=n.wsize-p):m=n.wnext-p,p>n.length&&(p=n.length),h=n.window}else h=i,m=o-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do i[o++]=h[m++];while(--p);n.length===0&&(n.mode=Zp);break;case nm:if(c===0)break inf_leave;i[o++]=n.length,c--,n.mode=Zp;break;case rm:if(n.wrap){for(;u<32;){if(s===0)break inf_leave;s--,l|=r[a++]<<u,u+=8}if(f-=c,e.total_out+=f,n.total+=f,f&&(e.adler=n.check=n.flags?W(n.check,i,f,o-f):Jd(n.check,i,f,o-f)),f=c,(n.flags?l:um(l))!==n.check){e.msg=`incorrect data check`,n.mode=Y;break}l=0,u=0}n.mode=im;case im:if(n.wrap&&n.flags){for(;u<32;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(l!==(n.total&4294967295)){e.msg=`incorrect length check`,n.mode=Y;break}l=0,u=0}n.mode=am;case am:w=wp;break inf_leave;case Y:w=Dp;break inf_leave;case om:return Op;case sm:default:return Ep}return e.next_out=o,e.avail_out=c,e.next_in=a,e.avail_in=s,n.hold=l,n.bits=u,(n.wsize||f!==e.avail_out&&n.mode<Y&&(n.mode<rm||t!==bp))&&bm(e,e.output,e.next_out,f-e.avail_out)?(n.mode=om,Op):(d-=e.avail_in,f-=e.avail_out,e.total_in+=d,e.total_out+=f,n.total+=f,n.wrap&&f&&(e.adler=n.check=n.flags?W(n.check,i,f,e.next_out-f):Jd(n.check,i,f,e.next_out-f)),e.data_type=n.bits+(n.last?64:0)+(n.mode===Hp?128:0)+(n.mode===Xp||n.mode===Gp?256:0),(d===0&&f===0||t===bp)&&w===Cp&&(w=kp),w)}function Sm(e){if(!e||!e.state)return Ep;var t=e.state;return t.window&&=null,e.state=null,Cp}var Cm=e({DEFLATE:()=>1,DEFLATERAW:()=>5,GUNZIP:()=>4,GZIP:()=>3,INFLATE:()=>2,INFLATERAW:()=>6,NONE:()=>0,UNZIP:()=>7,Z_BEST_COMPRESSION:()=>9,Z_BEST_SPEED:()=>1,Z_BINARY:()=>0,Z_BLOCK:()=>5,Z_BUF_ERROR:()=>-5,Z_DATA_ERROR:()=>-3,Z_DEFAULT_COMPRESSION:()=>-1,Z_DEFAULT_STRATEGY:()=>0,Z_DEFLATED:()=>8,Z_ERRNO:()=>-1,Z_FILTERED:()=>1,Z_FINISH:()=>4,Z_FIXED:()=>4,Z_FULL_FLUSH:()=>3,Z_HUFFMAN_ONLY:()=>2,Z_NEED_DICT:()=>2,Z_NO_COMPRESSION:()=>0,Z_NO_FLUSH:()=>0,Z_OK:()=>0,Z_PARTIAL_FLUSH:()=>1,Z_RLE:()=>3,Z_STREAM_END:()=>1,Z_STREAM_ERROR:()=>-2,Z_SYNC_FLUSH:()=>2,Z_TEXT:()=>1,Z_TREES:()=>6,Z_UNKNOWN:()=>2,Zlib:()=>wm});function wm(e){if(e<1||e>7)throw TypeError(`Bad argument`);this.mode=e,this.init_done=!1,this.write_in_progress=!1,this.pending_close=!1,this.windowBits=0,this.level=0,this.memLevel=0,this.strategy=0,this.dictionary=null}wm.prototype.init=function(e,t,n,r,i){this.windowBits=e,this.level=t,this.memLevel=n,this.strategy=r,(this.mode===3||this.mode===4)&&(this.windowBits+=16),this.mode===7&&(this.windowBits+=32),(this.mode===5||this.mode===6)&&(this.windowBits=-this.windowBits),this.strm=new ju;var a;switch(this.mode){case 1:case 3:case 5:a=ep(this.strm,this.level,8,this.windowBits,this.memLevel,this.strategy);break;case 2:case 4:case 6:case 7:a=hm(this.strm,this.windowBits);break;default:throw Error(`Unknown mode `+this.mode)}if(a!==0){this._error(a);return}this.write_in_progress=!1,this.init_done=!0},wm.prototype.params=function(){throw Error(`deflateParams Not supported`)},wm.prototype._writeCheck=function(){if(!this.init_done)throw Error(`write before init`);if(this.mode===0)throw Error(`already finalized`);if(this.write_in_progress)throw Error(`write already in progress`);if(this.pending_close)throw Error(`close is pending`)},wm.prototype.write=function(e,t,n,r,i,a,o){this._writeCheck(),this.write_in_progress=!0;var s=this;return process.nextTick(function(){s.write_in_progress=!1;var c=s._write(e,t,n,r,i,a,o);s.callback(c[0],c[1]),s.pending_close&&s.close()}),this};function Tm(e,t){for(var n=0;n<e.length;n++)this[t+n]=e[n]}wm.prototype.writeSync=function(e,t,n,r,i,a,o){return this._writeCheck(),this._write(e,t,n,r,i,a,o)},wm.prototype._write=function(e,t,n,r,i,a,o){if(this.write_in_progress=!0,e!==0&&e!==1&&e!==2&&e!==3&&e!==4&&e!==5)throw Error(`Invalid flush value`);t??(t=new Buffer(0),r=0,n=0),i.set=i._set?i._set:Tm;var s=this.strm;s.avail_in=r,s.input=t,s.next_in=n,s.avail_out=o,s.output=i,s.next_out=a;var c;switch(this.mode){case 1:case 3:case 5:c=tp(s,e);break;case 7:case 2:case 4:case 6:c=xm(s,e);break;default:throw Error(`Unknown mode `+this.mode)}return c!==1&&c!==0&&this._error(c),this.write_in_progress=!1,[s.avail_in,s.avail_out]},wm.prototype.close=function(){if(this.write_in_progress){this.pending_close=!0;return}this.pending_close=!1,this.mode===1||this.mode===3||this.mode===5?np(this.strm):Sm(this.strm),this.mode=0};var Em;wm.prototype.reset=function(){switch(this.mode){case 1:case 5:Em=$f(this.strm);break;case 2:case 6:Em=pm(this.strm)}Em!==0&&this._error(Em)},wm.prototype._error=function(e){this.onerror(Au[e]+`: `+this.strm.msg,e),this.write_in_progress=!1,this.pending_close&&this.close()};function Dm(e,t){if(!e)throw Error(t)}var X={};Object.keys(Cm).forEach(function(e){X[e]=Cm[e]}),X.Z_MIN_WINDOWBITS=8,X.Z_MAX_WINDOWBITS=15,X.Z_DEFAULT_WINDOWBITS=15,X.Z_MIN_CHUNK=64,X.Z_MAX_CHUNK=1/0,X.Z_DEFAULT_CHUNK=16384,X.Z_MIN_MEMLEVEL=1,X.Z_MAX_MEMLEVEL=9,X.Z_DEFAULT_MEMLEVEL=8,X.Z_MIN_LEVEL=-1,X.Z_MAX_LEVEL=9,X.Z_DEFAULT_LEVEL=X.Z_DEFAULT_COMPRESSION;var Om={Z_OK:X.Z_OK,Z_STREAM_END:X.Z_STREAM_END,Z_NEED_DICT:X.Z_NEED_DICT,Z_ERRNO:X.Z_ERRNO,Z_STREAM_ERROR:X.Z_STREAM_ERROR,Z_DATA_ERROR:X.Z_DATA_ERROR,Z_MEM_ERROR:X.Z_MEM_ERROR,Z_BUF_ERROR:X.Z_BUF_ERROR,Z_VERSION_ERROR:X.Z_VERSION_ERROR};Object.keys(Om).forEach(function(e){Om[Om[e]]=e});function km(e){return new Qm(e)}function Am(e){return new $m(e)}function jm(e){return new nh(e)}function Mm(e){return new rh(e)}function Nm(e){return new eh(e)}function Pm(e){return new th(e)}function Fm(e){return new ih(e)}function Im(e,t,n){return typeof t==`function`&&(n=t,t={}),Xm(new Qm(t),e,n)}function Lm(e,t){return Zm(new Qm(t),e)}function Rm(e,t,n){return typeof t==`function`&&(n=t,t={}),Xm(new eh(t),e,n)}function zm(e,t){return Zm(new eh(t),e)}function Bm(e,t,n){return typeof t==`function`&&(n=t,t={}),Xm(new nh(t),e,n)}function Vm(e,t){return Zm(new nh(t),e)}function Hm(e,t,n){return typeof t==`function`&&(n=t,t={}),Xm(new ih(t),e,n)}function Um(e,t){return Zm(new ih(t),e)}function Wm(e,t,n){return typeof t==`function`&&(n=t,t={}),Xm(new $m(t),e,n)}function Gm(e,t){return Zm(new $m(t),e)}function Km(e,t,n){return typeof t==`function`&&(n=t,t={}),Xm(new th(t),e,n)}function qm(e,t){return Zm(new th(t),e)}function Jm(e,t,n){return typeof t==`function`&&(n=t,t={}),Xm(new rh(t),e,n)}function Ym(e,t){return Zm(new rh(t),e)}function Xm(e,t,n){var r=[],i=0;e.on(`error`,o),e.on(`end`,s),e.end(t),a();function a(){for(var t;(t=e.read())!==null;)r.push(t),i+=t.length;e.once(`readable`,a)}function o(t){e.removeListener(`end`,s),e.removeListener(`readable`,a),n(t)}function s(){var t=Buffer.concat(r,i);r=[],n(null,t),e.close()}}function Zm(e,t){if(typeof t==`string`&&(t=new Buffer(t)),!Buffer.isBuffer(t))throw TypeError(`Not a string or buffer`);var n=X.Z_FINISH;return e._processChunk(t,n)}function Qm(e){if(!(this instanceof Qm))return new Qm(e);Z.call(this,e,X.DEFLATE)}function $m(e){if(!(this instanceof $m))return new $m(e);Z.call(this,e,X.INFLATE)}function eh(e){if(!(this instanceof eh))return new eh(e);Z.call(this,e,X.GZIP)}function th(e){if(!(this instanceof th))return new th(e);Z.call(this,e,X.GUNZIP)}function nh(e){if(!(this instanceof nh))return new nh(e);Z.call(this,e,X.DEFLATERAW)}function rh(e){if(!(this instanceof rh))return new rh(e);Z.call(this,e,X.INFLATERAW)}function ih(e){if(!(this instanceof ih))return new ih(e);Z.call(this,e,X.UNZIP)}function Z(e,t){if(this._opts=e||={},this._chunkSize=e.chunkSize||X.Z_DEFAULT_CHUNK,Ml.call(this,e),e.flush&&e.flush!==X.Z_NO_FLUSH&&e.flush!==X.Z_PARTIAL_FLUSH&&e.flush!==X.Z_SYNC_FLUSH&&e.flush!==X.Z_FULL_FLUSH&&e.flush!==X.Z_FINISH&&e.flush!==X.Z_BLOCK)throw Error(`Invalid flush flag: `+e.flush);if(this._flushFlag=e.flush||X.Z_NO_FLUSH,e.chunkSize&&(e.chunkSize<X.Z_MIN_CHUNK||e.chunkSize>X.Z_MAX_CHUNK))throw Error(`Invalid chunk size: `+e.chunkSize);if(e.windowBits&&(e.windowBits<X.Z_MIN_WINDOWBITS||e.windowBits>X.Z_MAX_WINDOWBITS))throw Error(`Invalid windowBits: `+e.windowBits);if(e.level&&(e.level<X.Z_MIN_LEVEL||e.level>X.Z_MAX_LEVEL))throw Error(`Invalid compression level: `+e.level);if(e.memLevel&&(e.memLevel<X.Z_MIN_MEMLEVEL||e.memLevel>X.Z_MAX_MEMLEVEL))throw Error(`Invalid memLevel: `+e.memLevel);if(e.strategy&&e.strategy!=X.Z_FILTERED&&e.strategy!=X.Z_HUFFMAN_ONLY&&e.strategy!=X.Z_RLE&&e.strategy!=X.Z_FIXED&&e.strategy!=X.Z_DEFAULT_STRATEGY)throw Error(`Invalid strategy: `+e.strategy);if(e.dictionary&&!Buffer.isBuffer(e.dictionary))throw Error(`Invalid dictionary: it should be a Buffer instance`);this._binding=new X.Zlib(t);var n=this;this._hadError=!1,this._binding.onerror=function(e,t){n._binding=null,n._hadError=!0;var r=Error(e);r.errno=t,r.code=X.codes[t],n.emit(`error`,r)};var r=X.Z_DEFAULT_COMPRESSION;typeof e.level==`number`&&(r=e.level);var i=X.Z_DEFAULT_STRATEGY;typeof e.strategy==`number`&&(i=e.strategy),this._binding.init(e.windowBits||X.Z_DEFAULT_WINDOWBITS,r,e.memLevel||X.Z_DEFAULT_MEMLEVEL,i,e.dictionary),this._buffer=new Buffer(this._chunkSize),this._offset=0,this._closed=!1,this._level=r,this._strategy=i,this.once(`end`,this.close)}pn(Z,Ml),Z.prototype.params=function(e,t,n){if(e<X.Z_MIN_LEVEL||e>X.Z_MAX_LEVEL)throw RangeError(`Invalid compression level: `+e);if(t!=X.Z_FILTERED&&t!=X.Z_HUFFMAN_ONLY&&t!=X.Z_RLE&&t!=X.Z_FIXED&&t!=X.Z_DEFAULT_STRATEGY)throw TypeError(`Invalid strategy: `+t);if(this._level!==e||this._strategy!==t){var r=this;this.flush(X.Z_SYNC_FLUSH,function(){r._binding.params(e,t),r._hadError||(r._level=e,r._strategy=t,n&&n())})}else process.nextTick(n)},Z.prototype.reset=function(){return this._binding.reset()},Z.prototype._flush=function(e){this._transform(new Buffer(0),``,e)},Z.prototype.flush=function(e,t){var n=this._writableState;if((typeof e==`function`||e===void 0&&!t)&&(t=e,e=X.Z_FULL_FLUSH),n.ended)t&&process.nextTick(t);else if(n.ending)t&&this.once(`end`,t);else if(n.needDrain){var r=this;this.once(`drain`,function(){r.flush(t)})}else this._flushFlag=e,this.write(new Buffer(0),``,t)},Z.prototype.close=function(e){if(e&&process.nextTick(e),!this._closed){this._closed=!0,this._binding.close();var t=this;process.nextTick(function(){t.emit(`close`)})}},Z.prototype._transform=function(e,t,n){var r,i=this._writableState;(i.ending||i.ended)&&(!e||i.length===e.length)?r=X.Z_FINISH:(r=this._flushFlag,e.length>=i.length&&(this._flushFlag=this._opts.flush||X.Z_NO_FLUSH)),this._processChunk(e,r,n)},Z.prototype._processChunk=function(e,t,n){var r=e&&e.length,i=this._chunkSize-this._offset,a=0,o=this,s=typeof n==`function`;if(!s){var c=[],l=0,u;this.on(`error`,function(e){u=e});do var d=this._binding.writeSync(t,e,a,r,this._buffer,this._offset,i);while(!this._hadError&&m(d[0],d[1]));if(this._hadError)throw u;var f=Buffer.concat(c,l);return this.close(),f}var p=this._binding.write(t,e,a,r,this._buffer,this._offset,i);p.buffer=e,p.callback=m;function m(u,d){if(!o._hadError){var f=i-d;if(Dm(f>=0,`have should not go down`),f>0){var p=o._buffer.slice(o._offset,o._offset+f);o._offset+=f,s?o.push(p):(c.push(p),l+=p.length)}if((d===0||o._offset>=o._chunkSize)&&(i=o._chunkSize,o._offset=0,o._buffer=new Buffer(o._chunkSize)),d===0){if(a+=r-u,r=u,!s)return!0;var h=o._binding.write(t,e,a,r,o._buffer,o._offset,o._chunkSize);h.callback=m,h.buffer=e;return}if(!s)return!1;n()}}},pn(Qm,Z),pn($m,Z),pn(eh,Z),pn(th,Z),pn(nh,Z),pn(rh,Z),pn(ih,Z);var ah={codes:Om,createDeflate:km,createInflate:Am,createDeflateRaw:jm,createInflateRaw:Mm,createGzip:Nm,createGunzip:Pm,createUnzip:Fm,deflate:Im,deflateSync:Lm,gzip:Rm,gzipSync:zm,deflateRaw:Bm,deflateRawSync:Vm,unzip:Hm,unzipSync:Um,inflate:Wm,inflateSync:Gm,gunzip:Km,gunzipSync:qm,inflateRaw:Jm,inflateRawSync:Ym,Deflate:Qm,Inflate:$m,Gzip:eh,Gunzip:th,DeflateRaw:nh,InflateRaw:rh,Unzip:ih,Zlib:Z},oh=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function sh(e){if(!e)return 0;let t=-1,n=typeof e==`string`?new TextEncoder().encode(e):e;for(let e=0;e<n.length;e++)t=t>>>8^oh[(t^n[e])&255];return~t>>>0}({...ah});function ch(e,t){let n=t-e;return Math.round(n*1e6)/1e6}function lh(e){return s(`sha256`).update(e,`utf8`).digest(`hex`)}function uh(e,t=1,n=`default_spec`){let r=ch(t,e),i=r>=0;return{baseline_score:t,candidate_score:e,delta_e:r,monotonic:i,status:i?`COMMITTED`:`REJECTED_REGRESSION`,timestamp:new Date().toISOString(),details:{evaluation_spec:typeof n==`string`?n:JSON.stringify(n)}}}function dh(e,t,n,r){return{epoch_id:e,epoch_hash:lh(`epoch:${e}:fitness:${r}:delta:${t}:hyp:${n}`),baseline_fitness:r,sealed_at:new Date().toISOString(),hypothesis_history:n?[n]:[]}}function fh(e,t){let n=e.epoch_id+1;return{epoch_id:n,epoch_hash:lh(`epoch:${n}:parent:${e.epoch_hash}:fitness:${t}`),baseline_fitness:t,sealed_at:new Date().toISOString(),hypothesis_history:[...e.hypothesis_history]}}function ph(e,t,n,r){let i=uh(r?r(e,n):1,t.baseline_fitness,n);return i.monotonic?[!0,fh(dh(t.epoch_id,i.delta_e,e.candidate_state_hash,i.candidate_score),i.candidate_score),i]:[!1,t,i]}var mh=class{currentEpoch;history=[];quarantinedMutations=new Map;constructor(e=1,t=1){let n=`genesis:${e}`;this.currentEpoch={epoch_id:e,epoch_hash:lh(n),baseline_fitness:t,sealed_at:new Date().toISOString(),hypothesis_history:[]}}submitHypothesis(e,t,n,r=[],i=[`INV-14`]){let a={hypothesis_id:e,author_did:t,epoch_id:this.currentEpoch.epoch_id,candidate_state_hash:n,candidate_patches:r,target_invariants:i,status:`QUARANTINED`};return this.quarantinedMutations.set(e,a),a}evaluateAndCommit(e,t,n){let r=this.quarantinedMutations.get(e);if(!r)throw Error(`No quarantined hypothesis found for ${e}`);let[i,a,o]=ph(r,this.currentEpoch,t,()=>n);return this.history.push(o),i?(o.status=`COMMITTED`,this.currentEpoch=a,this.quarantinedMutations.delete(e),[!0,o]):(o.status=`REJECTED_REGRESSION`,this.quarantinedMutations.delete(e),[!1,o])}canCommitToHandleRegistry(e,t){return e.status===`QUARANTINED`&&t.status!==`COMMITTED`?!1:t.monotonic&&t.delta_e>=0&&t.status===`COMMITTED`}},hh=class{authorDid;currentEpoch;evaluatedReports=[];hypotheses=[];constructor(e,t){this.authorDid=e??`did:clm:meta-loop-gamma`,this.currentEpoch=t??dh(1,0,`0`.repeat(64),1)}onTelemetryEvent(e,t,n){if(!(t.success===!1||t.error||t.status===`failed`||t.status===`error`||e.includes(`invariant_breach`)))return null;let r=String(t.error??`Simulated execution anomaly`),i=`hypo_${u(6).toString(`hex`)}`,a=`${e}:${r}:${Date.now()}`,o=s(`sha256`).update(a,`utf8`).digest(`hex`),c={hypothesis_id:i,author_did:this.authorDid,epoch_id:this.currentEpoch.epoch_id,candidate_state_hash:o,candidate_patches:[{target:e,remedy:`Mitigate ${r}`}],target_invariants:[`INV-14`,`INV-391-03`],status:`QUARANTINED`};this.hypotheses.push(c);let[l,d,f]=ph(c,this.currentEpoch,{anomaly_payload:t,event_type:e},e=>n?n(e,t):1);return this.evaluatedReports.push(f),l&&(this.currentEpoch=d),f}simulateAnomalyAndEvaluate(e=`Simulated invariant breach`,t=1){let n={success:!1,error:e},r=this.onTelemetryEvent(`invariant_breach`,n,()=>t);if(!r)throw Error(`Expected anomaly report to be generated`);return r}},gh=(e=>(e[e.U0_Mcard=0]=`U0_Mcard`,e[e.U1_Pcard=1]=`U1_Pcard`,e[e.U2_Vcard=2]=`U2_Vcard`,e[e.U3_Satori=3]=`U3_Satori`,e[e.U4_Membrane=4]=`U4_Membrane`,e[e.U5_MetaGamma=5]=`U5_MetaGamma`,e))(gh||{});function _h(){return[{level:0,identifier:`U0`,stratum_name:`mcard_cas`,description:`Static Content-Addressable Storage (MCard)`},{level:1,identifier:`U1`,stratum_name:`pcard_net`,description:`Linear Transitions & Colored Petri Net (PCard)`},{level:2,identifier:`U2`,stratum_name:`vcard_proof`,description:`Cryptographic Verification & Hoare Receipts (VCard)`},{level:3,identifier:`U3`,stratum_name:`satori_fiber`,description:`Distributed Reticulum Mesh & Satori Speech Acts`},{level:4,identifier:`U4`,stratum_name:`membrane_ui`,description:`Omnichannel Interaction Surface & Generative Hypermedia`},{level:5,identifier:`U5`,stratum_name:`meta_gamma`,description:`Meta-Circular Continuous Learning Stratum (Loop Γ)`}]}function vh(e,t){return e<=t}function yh(e){if(e<0||e>5||!Number.isInteger(e))throw Error(`Invalid universe level: ${e} (expected integer 0..=5)`);return e}Cr({},{AsyncEventBatcher:()=>bh,ContinuousLearningEngine:()=>mh,LoopGammaTelemetryHook:()=>hh,UniverseLevel:()=>gh,advanceBoundary:()=>fh,closeGammaLoop:()=>ph,computeDeltaE:()=>ch,evaluateEpistemicFitness:()=>uh,getAsyncEventBatcher:()=>Sh,getUniverseCoordinates:()=>_h,isStratified:()=>vh,sealEpoch:()=>dh,validateUniverseLevel:()=>yh});var bh=class{buffer=[];maxBatchSize;flushIntervalMs;timer=null;isFlushing=!1;constructor(e=256,t=10){this.maxBatchSize=e,this.flushIntervalMs=t}record(e){return this.buffer.push(e),this.buffer.length>=this.maxBatchSize?this.flushSync():this.timer||=setTimeout(()=>{this.timer=null,this.flushSync()},this.flushIntervalMs),!0}flushSync(){this.buffer.length===0||this.isFlushing||(this.isFlushing=!0,this.timer&&=(clearTimeout(this.timer),null),this.buffer.splice(0,this.buffer.length),this.isFlushing=!1)}get queueLength(){return this.buffer.length}},xh=null;function Sh(){return xh||=new bh,xh}Cr({},{DEFAULT_ROUTES:()=>Oh,PENPOT_FILE_ID:()=>Th,PENPOT_FLOW_ID:()=>Dh,PENPOT_PAGE_ID:()=>Eh,checkNavigationDrift:()=>wh,deterministicStringify:()=>Ah,extractNavigationGraph:()=>Nh,generatePenpotArchive:()=>Vh,getRouteContent:()=>Mh,importPenpotFile:()=>Fh,probeInstanceReachability:()=>Ph,readZip:()=>zh,renderNavigationArtifacts:()=>Ch,resolveUnitDir:()=>jh,sha256:()=>kh,writeZip:()=>Bh});function Ch(e,t){let n=jh(t),r=Je(e);if(!qr(r))throw Error(`FILE_NOT_FOUND: Penpot design file not found at ${r} (INV-CDO-08)`);let i=Nh(r),a=i.flows[0]||{startingFrame:null,name:`default`},o=new Map;for(let e of i.frames){let t=e.pluginData?.clm?.handle||``,n=t.replace(/^mcard:route:/,``);n.startsWith(`/`)&&(n=n.slice(1)),n||=e.name.toLowerCase().includes(`home`)?`index.html`:e.name.toLowerCase().includes(`mission`)?`app.html`:e.name.toLowerCase().includes(`lab`)?`responsive-lab.html`:`${e.id}.html`,o.set(e.id,{...e,routePath:n,handle:t||`mcard:route:/${n}`})}let s=N(n,`js`,`nav.js`);Qe(s);let c=Array.from(o.values()).map(e=>{let t=(e.interactions||[]).map(e=>{let t=o.get(e.destination);return{destinationFrameId:e.destination,destinationHandle:t?.handle||``,destinationPath:t?.routePath||``,destinationName:t?.name||``,eventType:e.eventType||`click`}});return{frameId:e.id,name:e.name,path:e.routePath,handle:e.handle,isStartingFrame:e.id===a.startingFrame,links:t}});`${i.meta.graphHash}${i.meta.archiveHash}${JSON.stringify(i.meta.graphHash)}${JSON.stringify(i.meta.archiveHash)}${JSON.stringify(a.startingFrame)}${JSON.stringify(c,null,2)}`;let l=N(n,`index.html`),u=Yr(l,`utf8`),d=c.map(e=>` <a class="penpot-nav-link${e.isStartingFrame?` penpot-nav-link-active`:``}" href="${e.path}" data-penpot-frame="${e.frameId}" data-penpot-handle="${e.handle}">${e.name}</a>`).join(`
48
+ `),f=`<!-- BEGIN: PENPOT-GENERATED-NAV (INV-CDO-11) -->
49
+ <nav class="penpot-nav-bar" id="penpot-site-nav" aria-label="Penpot Navigation Flow" data-graph-hash="${i.meta.graphHash}">
50
+ <span class="penpot-nav-title">\u{1F3A8} Flow: ${a.name}</span>
51
+ <div class="penpot-nav-links">
52
+ ${d}
53
+ </div>
54
+ </nav>
55
+ <!-- END: PENPOT-GENERATED-NAV -->`,p=/<!-- BEGIN: PENPOT-GENERATED-NAV \(INV-CDO-11\) -->[\s\S]*?<!-- END: PENPOT-GENERATED-NAV -->/;return u=p.test(u)?u.replace(p,f):u.includes(`<div class="top-controls">`)?u.replace(`<div class="top-controls">`,`${f}
56
+
57
+ <div class="top-controls">`):u.includes(`<body>`)?u.replace(`<body>`,`<body>
58
+ ${f}
59
+ `):`${f}
60
+ ${u}`,!u.includes(`src="js/nav.js"`)&&!u.includes(`src='./js/nav.js'`)&&(u=u.replace(`</body>`,` <script type="module" src="js/nav.js"><\/script>
61
+ </body>`)),u.includes(`.penpot-nav-bar`)||(u=u.replace(`</style>`,`
62
+ /* Penpot Generated Navigation Bar (INV-CDO-11) */
63
+ .penpot-nav-bar {
64
+ position: absolute;
65
+ top: 4.5rem;
66
+ left: 1.5rem;
67
+ display: flex;
68
+ align-items: center;
69
+ gap: 1rem;
70
+ padding: 0.35rem 0.85rem;
71
+ border-radius: 9999px;
72
+ background: var(--color-surface, rgba(30, 41, 59, 0.7));
73
+ border: 1px solid var(--color-border, rgba(255, 255, 255, 0.1));
74
+ backdrop-filter: blur(var(--blur-surface, 12px));
75
+ z-index: 60;
76
+ font-size: 0.85rem;
77
+ }
78
+ .penpot-nav-title {
79
+ font-weight: 600;
80
+ color: var(--color-text-secondary, #94a3b8);
81
+ font-size: 0.75rem;
82
+ text-transform: uppercase;
83
+ letter-spacing: 0.05em;
84
+ }
85
+ .penpot-nav-links {
86
+ display: flex;
87
+ align-items: center;
88
+ gap: 0.5rem;
89
+ }
90
+ .penpot-nav-link {
91
+ color: var(--color-text-primary, #f8fafc);
92
+ text-decoration: none;
93
+ padding: 0.2rem 0.5rem;
94
+ border-radius: 6px;
95
+ transition: background 150ms ease, color 150ms ease;
96
+ }
97
+ .penpot-nav-link:hover {
98
+ background: var(--color-surface-hover, rgba(255, 255, 255, 0.1));
99
+ color: #38bdf8;
100
+ }
101
+ .penpot-nav-link-active {
102
+ background: rgba(59, 130, 246, 0.25);
103
+ color: #60a5fa;
104
+ font-weight: 600;
105
+ }
106
+
107
+ </style>`)),{ok:!0,graphHash:i.meta.graphHash,archiveHash:i.meta.archiveHash,targets:[{path:s,size:ti(s).size},{path:l,size:ti(l).size}]}}function wh(e,t={}){let n=jh(e),r=N(n,`mcard.yaml`);if(!qr(r))throw Error(`MANIFEST_NOT_FOUND: mcard.yaml missing at ${r} (INV-CDO-08)`);let i=Yr(r,`utf8`),a=`design/landing-navigation.penpot`,o=i.match(/penpot_file\s*:\s*["']?([^"']+)["']?/);o&&(a=o[1].trim());let s=N(n,a);if(!qr(s))return{status:`drift`,driftCount:1,error:`MISSING_PENPOT_FILE`,message:`Declared penpot file missing on disk: ${s}`,unbound:[],drifted:[],unmapped:[],brokenEdges:[],driftedArtifacts:[]};let c=Nh(s),l=[],u=[],d=[],f=[],p=[],m=new Map,h=new Map;for(let e of c.frames){m.set(e.id,e);let t=e.pluginData?.clm;if(!t||!t.handle){l.push({frameId:e.id,frameName:e.name,reason:`Navigable frame has no plugin-data CLM handle (INV-CDO-12)`});continue}h.set(t.handle,e);let r=t.handle.replace(/^mcard:route:/,``);r.startsWith(`/`)&&(r=r.slice(1));let i=N(n,r);if(!qr(i))u.push({handle:t.handle,frameId:e.id,frameName:e.name,expectedPath:r,reason:`Route file does not exist on disk for handle ${t.handle}`});else{let n=kh(Mh(i));t.hash&&t.hash!==n&&u.push({handle:t.handle,frameId:e.id,frameName:e.name,path:r,expectedHash:t.hash,actualHash:n,reason:`Content hash mismatch between Penpot design (${t.hash.slice(0,12)}...) and deployed route (${n.slice(0,12)}...)`})}}let g=t.routes||Oh;for(let e of g)h.has(e.handle)||d.push({handle:e.handle,path:e.path,name:e.name,reason:`Route '${e.path}' (${e.handle}) exists in unit but has no bound frame in Penpot flow graph (INV-CDO-12)`});for(let e of c.interactions)(!e.destination||!m.has(e.destination))&&f.push({sourceFrameId:e.sourceFrameId,destination:e.destination,reason:`Flow edge points to non-existent or unmapped frame '${e.destination}'`});let _=N(n,`js`,`nav.js`);qr(_)?Yr(_,`utf8`).includes(c.meta.graphHash)||p.push({target:`js/nav.js`,reason:`Rendered js/nav.js does not match current Penpot graphHash ${c.meta.graphHash}`}):p.push({target:`js/nav.js`,reason:`Render target js/nav.js does not exist on disk (needs render)`});let v=N(n,`index.html`);qr(v)&&(Yr(v,`utf8`).includes(c.meta.graphHash)||p.push({target:`index.html`,reason:`Rendered index.html navigation markup does not match current Penpot graphHash ${c.meta.graphHash}`}));let y=l.length+u.length+d.length+f.length+p.length,b=y===0,x={handle:`mcard:evolution:navigation-drift:${Date.now()}`,unit:$e(n),graphHash:c.meta.graphHash,archiveHash:c.meta.archiveHash,driftCount:y,status:b?`clean`:`drift`,details:{unbound:l,drifted:u,unmapped:d,brokenEdges:f,driftedArtifacts:p},timestamp:new Date().toISOString()};return{status:b?`clean`:`drift`,driftCount:y,unbound:l,drifted:u,unmapped:d,brokenEdges:f,driftedArtifacts:p,meta:{penpotFile:a,graphHash:c.meta.graphHash,archiveHash:c.meta.archiveHash},evolutionMCard:x}}var Th=`d7570000-0000-8000-8000-000000000001`,Eh=`d7570000-0000-8000-8000-000000000002`,Dh=`d7570000-0000-8000-8000-000000000003`,Oh=[{path:`index.html`,name:`Home`,handle:`mcard:route:/index.html`,frameId:`d7570000-0000-8000-8000-000000000011`,isStart:!0,destinations:[`d7570000-0000-8000-8000-000000000012`,`d7570000-0000-8000-8000-000000000013`]},{path:`app.html`,name:`Mission Control`,handle:`mcard:route:/app.html`,frameId:`d7570000-0000-8000-8000-000000000012`,isStart:!1,destinations:[`d7570000-0000-8000-8000-000000000011`]},{path:`responsive-lab.html`,name:`Responsive UI Lab`,handle:`mcard:route:/responsive-lab.html`,frameId:`d7570000-0000-8000-8000-000000000013`,isStart:!1,destinations:[`d7570000-0000-8000-8000-000000000011`]}];function kh(e){let t=s(`sha256`);return Buffer.isBuffer(e)?t.update(e):typeof e==`string`?t.update(e,`utf8`):t.update(Ah(e),`utf8`),t.digest(`hex`)}function Ah(e){return typeof e!=`object`||!e?JSON.stringify(e):Array.isArray(e)?`[`+e.map(e=>Ah(e)).join(`,`)+`]`:`{`+Object.keys(e).sort().map(t=>JSON.stringify(t)+`:`+Ah(e[t])).join(`,`)+`}`}function jh(e){let t=Je(e||process.cwd());if(qr(N(t,`mcard.yaml`)))return t;let n=N(t,`LandingPage`);return qr(N(n,`mcard.yaml`))?n:t}function Mh(e){return Yr(e,`utf8`).replace(/<!-- BEGIN: PENPOT-GENERATED-NAV[\s\S]*?<!-- END: PENPOT-GENERATED-NAV -->/g,``)}function Nh(e){let t=Je(e);if(!qr(t))throw Error(`FILE_NOT_FOUND: Penpot file does not exist at ${t} (INV-CDO-08)`);let n=Yr(t),r=kh(n),i=zh(n),a=i.getJson(`manifest.json`);if(!a)throw Error(`MALFORMED_ARCHIVE: Missing manifest.json in .penpot archive ${t} (INV-CDO-08)`);let o=a.files||[],s=[],c=[],l=[],u=[],d=[],f=i.list();for(let e of o){let t=e.id,n=`files/${t}/pages/`,r=f.filter(e=>e.startsWith(n)&&e.endsWith(`.json`)&&e.split(`/`).length===4);for(let e of r){let n=i.getJson(e);if(!n)continue;let r=n.id||$e(e,`.json`),a=n.name||`Untitled Page`,o=typeof n.index==`number`?n.index:0,p=[],m=n.flows||{};for(let e of Object.keys(m).sort()){let t=m[e],n=t.id||e,i=t[`starting-frame`]||t.startingFrame,a={id:String(n),name:t.name||`Flow`,startingFrame:i?String(i):null,pageId:String(r)};p.push(a),c.push(a)}let h=`files/${t}/pages/${r}/`,g=f.filter(e=>e.startsWith(h)&&e.endsWith(`.json`)&&e.split(`/`).length===5),_=[];for(let e of g){let t=i.getJson(e);if(!t||t.type!==`frame`&&t.frame!==!0)continue;let n=String(t.id||$e(e,`.json`));if(n===`00000000-0000-0000-0000-000000000000`||t.name===`Root Frame`)continue;let a=t.name||`Untitled Frame`,o=t[`plugin-data`]||t.pluginData||{},s=o.clm||o[`:clm`]||null,c=[],f=t.interactions||[];for(let e of f){let t=e[`action-type`]||e.actionType;if(t===`navigate`||t===`:navigate`){let t=e.destination?String(e.destination):null,r={id:e.id?String(e.id):`${n}->${t}`,sourceFrameId:n,actionType:`navigate`,destination:t,eventType:e[`event-type`]||e.eventType||`click`,animation:e.animation||null};c.push(r),u.push(r)}}let p={id:n,name:a,pageId:String(r),pluginData:s?{clm:s}:{},interactions:c.sort((e,t)=>(e.destination||``).localeCompare(t.destination||``))};_.push(p),l.push(p),s&&d.push({frameId:n,frameName:a,handle:s.handle||null,hash:s.hash||null})}_.sort((e,t)=>e.id.localeCompare(t.id)),s.push({id:String(r),name:a,index:o,flows:p.sort((e,t)=>e.id.localeCompare(t.id)),frames:_})}}s.sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),c.sort((e,t)=>e.id.localeCompare(t.id)),l.sort((e,t)=>e.id.localeCompare(t.id)),u.sort((e,t)=>e.sourceFrameId.localeCompare(t.sourceFrameId)||(e.destination||``).localeCompare(t.destination||``)),d.sort((e,t)=>e.frameId.localeCompare(t.frameId));let p={pages:s,flows:c,frames:l,interactions:u,pluginData:d},m=kh(Ah(p));return{...p,meta:{archiveHash:r,graphHash:m,sourceFile:Ze(process.cwd(),t)}}}async function Ph(e,t=1500){return new Promise(n=>{try{let r=(new yr(e).protocol,Vl).get(e,{timeout:t},e=>{n({reachable:!0,statusCode:e.statusCode,error:null}),e.resume()});r.on(`timeout`,()=>{r.destroy(),n({reachable:!1,statusCode:null,error:`Connection timed out after ${t}ms`})}),r.on(`error`,e=>{n({reachable:!1,statusCode:null,error:e.message})})}catch(e){n({reachable:!1,statusCode:null,error:e.message})}})}async function Fh(e,t={}){let n=t.penpotInstance||{}.PENPOT_INSTANCE||`http://localhost:3449`;if(t.noPenpot)return{status:`skipped`,exitCode:2,reason:`HEADLESS_CI_NO_PENPOT`,message:`Penpot import skipped: --no-penpot flag supplied for headless CI (INV-REF-01).`,fileUrl:e,instanceUrl:n,probe:{reachable:!1,skipped:!0},devenvOnlyNote:`import_penpot_file is devenv-only and requires a live shadow-cljs nREPL connection.`};let r=await Ph(n,t.timeoutMs||1500);return r.reachable?{status:`success`,exitCode:0,fileUrl:e,instanceUrl:n,probe:r,importDetails:{teamId:`d7570000-0000-8000-8000-team00000001`,fileId:`d7570000-0000-8000-8000-000000000001`,pageId:`d7570000-0000-8000-8000-000000000002`,fileName:`LandingPage Navigation`}}:{status:`error`,exitCode:1,error:{code:`PENPOT_INSTANCE_UNREACHABLE`,message:`Penpot instance at ${n} is unreachable (${r.error}) (INV-CDO-08)`},fileUrl:e,instanceUrl:n,probe:r,devenvOnlyNote:`import_penpot_file is devenv-only and requires a live shadow-cljs nREPL connection.`}}function Q({id:e,name:t,parentId:n,frameId:r,pageId:i,x:a,y:o,width:s,height:c,fillColor:l,fillOpacity:u=1,strokes:d=[],radius:f=0}){let p=a,m=o,h=a+s,g=o+c,_=d.map(e=>({"stroke-color":e.strokeColor||e[`stroke-color`],"stroke-width":e.strokeWidth??e[`stroke-width`]??1,"stroke-opacity":e.strokeOpacity??e[`stroke-opacity`]??1,"stroke-style":e.strokeStyle||e[`stroke-style`]||`solid`,"stroke-alignment":e.strokeAlignment||e[`stroke-alignment`]||`inner`}));return{id:e,name:t,type:`rect`,"page-id":i,"parent-id":n,"frame-id":r,x:a,y:o,width:s,height:c,rotation:0,selrect:{x:a,y:o,width:s,height:c,x1:p,y1:m,x2:h,y2:g},points:[{x:p,y:m},{x:h,y:m},{x:h,y:g},{x:p,y:g}],transform:{a:1,b:0,c:0,d:1,e:0,f:0},"transform-inverse":{a:1,b:0,c:0,d:1,e:0,f:0},strokes:_,fills:l?[{"fill-color":l,"fill-opacity":u}]:[],...f>0?{r1:f,r2:f,r3:f,r4:f}:{}}}function $({id:e,name:t,parentId:n,frameId:r,pageId:i,x:a,y:o,width:s,height:c,text:l,fontSize:u=`16`,fontWeight:d=`400`,fontFamily:f=`Inter`,fillColor:p=`#FFFFFF`}){let m=a,h=o,g=a+s,_=o+c;return{id:e,name:t,type:`text`,"page-id":i,"parent-id":n,"frame-id":r,x:a,y:o,width:s,height:c,rotation:0,selrect:{x:a,y:o,width:s,height:c,x1:m,y1:h,x2:g,y2:_},points:[{x:m,y:h},{x:g,y:h},{x:g,y:_},{x:m,y:_}],transform:{a:1,b:0,c:0,d:1,e:0,f:0},"transform-inverse":{a:1,b:0,c:0,d:1,e:0,f:0},strokes:[],fills:[{"fill-color":p,"fill-opacity":1}],content:{type:`root`,children:[{type:`paragraph-set`,children:[{type:`paragraph`,fontFamily:f,fontSize:String(u),fontWeight:String(d),children:[{text:l}]}]}]}}}function Ih(e,t,n){let r=[],i=e=>`d7570000-0000-8000-8000-00000001${String(e).padStart(4,`0`)}`,a=1;return r.push(Q({id:i(a++),name:`Top Navigation Bar`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t,y:100,width:1200,height:56,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Logo Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+24,y:118,width:200,height:24,text:`⚡ GovTech OS • Platform`,fontSize:`15`,fontWeight:`700`,fillColor:`#38BDF8`})),r.push(Q({id:i(a++),name:`Faro Status Badge`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+230,y:114,width:130,height:28,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Faro Status Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+244,y:120,width:110,height:18,text:`🟢 Faro RUM Active`,fontSize:`11`,fontWeight:`600`,fillColor:`#10B981`})),r.push(Q({id:i(a++),name:`Nav Button Mission Control`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+380,y:114,width:155,height:28,radius:6,fillColor:`#2563EB`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Nav Text Mission Control`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+395,y:120,width:130,height:18,text:`🎛️ Mission Control`,fontSize:`11`,fontWeight:`600`,fillColor:`#FFFFFF`})),r.push(Q({id:i(a++),name:`Nav Button Responsive Lab`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+550,y:114,width:155,height:28,radius:6,fillColor:`#2563EB`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Nav Text Responsive Lab`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+565,y:120,width:130,height:18,text:`📐 Responsive Lab`,fontSize:`11`,fontWeight:`600`,fillColor:`#FFFFFF`})),r.push(Q({id:i(a++),name:`Button Least Action`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+720,y:114,width:140,height:28,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Text Least Action`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+735,y:120,width:120,height:18,text:`🧭 Least Action (ℒ)`,fontSize:`11`,fillColor:`#94A3B8`})),r.push(Q({id:i(a++),name:`Route Handle Chip`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+980,y:114,width:196,height:28,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Route Handle Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+995,y:120,width:170,height:18,text:e.handle,fontSize:`11`,fillColor:`#64748B`})),r.push($({id:i(a++),name:`Hero Subhead Tag`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+40,y:175,width:500,height:20,text:`CONVERSATIONAL DEVELOPMENT ORCHESTRATION • PHASE 15`,fontSize:`11`,fontWeight:`700`,fillColor:`#64748B`})),r.push($({id:i(a++),name:`Hero Headline`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+40,y:198,width:800,height:36,text:`GovTech Platform Cockpit & Observability Gateway`,fontSize:`24`,fontWeight:`700`,fillColor:`#F8FAFC`})),r.push($({id:i(a++),name:`Hero Paragraph`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+40,y:236,width:900,height:22,text:`Deterministic fiber totality, least-action navigation, and verified sovereign deployment units.`,fontSize:`13`,fillColor:`#94A3B8`})),r.push(Q({id:i(a++),name:`Card 1 Container`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+40,y:270,width:355,height:225,radius:10,fillColor:`#1E293B`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1.5,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 1 Title`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+60,y:290,width:300,height:26,text:`🎛️ Mission Control`,fontSize:`17`,fontWeight:`700`,fillColor:`#F8FAFC`})),r.push($({id:i(a++),name:`Card 1 Description`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+60,y:324,width:315,height:36,text:`Operational cockpit for observable data, Grafana Faro Web SDK RUM telemetry, and deployment metrics.`,fontSize:`12`,fillColor:`#94A3B8`})),r.push(Q({id:i(a++),name:`Card 1 Chip`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+60,y:375,width:315,height:24,radius:4,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 1 Chip Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+70,y:380,width:295,height:16,text:`✓ Grafana Faro Telemetry • CORS Safe`,fontSize:`10`,fontWeight:`600`,fillColor:`#38BDF8`})),r.push(Q({id:i(a++),name:`Card 1 Button`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+60,y:415,width:240,height:36,radius:6,fillColor:`#2563EB`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 1 Button Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+75,y:425,width:210,height:18,text:`➔ Open Observability Cockpit`,fontSize:`12`,fontWeight:`600`,fillColor:`#FFFFFF`})),r.push(Q({id:i(a++),name:`Card 2 Container`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+420,y:270,width:355,height:225,radius:10,fillColor:`#1E293B`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1.5,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 2 Title`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+440,y:290,width:300,height:26,text:`📐 Responsive UI Lab`,fontSize:`17`,fontWeight:`700`,fillColor:`#F8FAFC`})),r.push($({id:i(a++),name:`Card 2 Description`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+440,y:324,width:315,height:36,text:`Multi-viewport workbench testing layout invariants across mobile (320px), tablet (768px), and desktop (1024px+).`,fontSize:`12`,fillColor:`#94A3B8`})),r.push(Q({id:i(a++),name:`Card 2 Chip`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+440,y:375,width:315,height:24,radius:4,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 2 Chip Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+450,y:380,width:295,height:16,text:`✓ Multi-Viewport Grid & Flex Invariants`,fontSize:`10`,fontWeight:`600`,fillColor:`#38BDF8`})),r.push(Q({id:i(a++),name:`Card 2 Button`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+440,y:415,width:240,height:36,radius:6,fillColor:`#2563EB`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 2 Button Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+455,y:425,width:210,height:18,text:`➔ Open Responsive Lab`,fontSize:`12`,fontWeight:`600`,fillColor:`#FFFFFF`})),r.push(Q({id:i(a++),name:`Card 3 Container`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+800,y:270,width:360,height:225,radius:10,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 3 Title`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+820,y:290,width:320,height:26,text:`🧭 Least Action (ℒ)`,fontSize:`17`,fontWeight:`700`,fillColor:`#F8FAFC`})),r.push($({id:i(a++),name:`Card 3 Description`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+820,y:324,width:320,height:36,text:`Lagrangian mechanics path optimizer finding geodesics of user intent with minimal interaction energy.`,fontSize:`12`,fillColor:`#94A3B8`})),r.push(Q({id:i(a++),name:`Card 3 Chip`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+820,y:375,width:320,height:24,radius:4,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 3 Chip Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+830,y:380,width:300,height:16,text:`δS = 0 Minimal Action Geodesic`,fontSize:`10`,fontWeight:`600`,fillColor:`#10B981`})),r.push($({id:i(a++),name:`Card 3 Status`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+820,y:425,width:320,height:20,text:`Current Action: 0.042 J • Invariant INV-CDO-14 Verified`,fontSize:`11`,fillColor:`#64748B`})),r.push(Q({id:i(a++),name:`Card 4 Container`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+40,y:515,width:540,height:240,radius:10,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 4 Title`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+60,y:535,width:480,height:26,text:`🎨 MCard Studio & Fiber Inspector`,fontSize:`17`,fontWeight:`700`,fillColor:`#F8FAFC`})),r.push($({id:i(a++),name:`Card 4 Description`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+60,y:568,width:490,height:36,text:`Visual authoring node graph and fiber inspector with live hot-reloading and CPN Petri Net state verification.`,fontSize:`12`,fillColor:`#94A3B8`})),r.push(Q({id:i(a++),name:`Card 4 Metric 1`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+60,y:615,width:230,height:60,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 4 Metric 1 Label`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+75,y:625,width:200,height:16,text:`ACTIVE FIBERS`,fontSize:`10`,fontWeight:`700`,fillColor:`#64748B`})),r.push($({id:i(a++),name:`Card 4 Metric 1 Value`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+75,y:645,width:200,height:22,text:`18 Sovereign Fibers`,fontSize:`14`,fontWeight:`700`,fillColor:`#38BDF8`})),r.push(Q({id:i(a++),name:`Card 4 Metric 2`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+310,y:615,width:240,height:60,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 4 Metric 2 Label`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+325,y:625,width:210,height:16,text:`LATTICE BASIS`,fontSize:`10`,fontWeight:`700`,fillColor:`#64748B`})),r.push($({id:i(a++),name:`Card 4 Metric 2 Value`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+325,y:645,width:210,height:22,text:`Lattice Height L0`,fontSize:`14`,fontWeight:`700`,fillColor:`#10B981`})),r.push($({id:i(a++),name:`Card 4 Status Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+60,y:700,width:480,height:20,text:`CPN Engine: Deterministic markings verified (INV-CDO-22)`,fontSize:`11`,fillColor:`#64748B`})),r.push(Q({id:i(a++),name:`Card 5 Container`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+605,y:515,width:555,height:240,radius:10,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 5 Title`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+625,y:535,width:500,height:26,text:`📦 Sovereign Deployment Units`,fontSize:`17`,fontWeight:`700`,fillColor:`#F8FAFC`})),r.push($({id:i(a++),name:`Card 5 Description`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+625,y:568,width:510,height:36,text:`Sovereign boundaries with sealed witnesses at Evidence Level E2, Hoare triples, and zero-drift verification.`,fontSize:`12`,fillColor:`#94A3B8`})),r.push(Q({id:i(a++),name:`Card 5 Metric 1`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+625,y:615,width:240,height:60,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 5 Metric 1 Label`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+640,y:625,width:210,height:16,text:`EVIDENCE TIER`,fontSize:`10`,fontWeight:`700`,fillColor:`#64748B`})),r.push($({id:i(a++),name:`Card 5 Metric 1 Value`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+640,y:645,width:210,height:22,text:`Certified Level E2`,fontSize:`14`,fontWeight:`700`,fillColor:`#A855F7`})),r.push(Q({id:i(a++),name:`Card 5 Metric 2`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+885,y:615,width:250,height:60,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Card 5 Metric 2 Label`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+900,y:625,width:220,height:16,text:`HOARE TRIPLES`,fontSize:`10`,fontWeight:`700`,fillColor:`#64748B`})),r.push($({id:i(a++),name:`Card 5 Metric 2 Value`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+900,y:645,width:220,height:22,text:`6 Triples, 0 Unwitnessed`,fontSize:`14`,fontWeight:`700`,fillColor:`#10B981`})),r.push($({id:i(a++),name:`Card 5 Status Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+625,y:700,width:500,height:20,text:`Witness Sealed: <estate>/witness/cdo-15.witness.json`,fontSize:`11`,fillColor:`#64748B`})),r}function Lh(e,t,n){let r=[],i=e=>`d7570000-0000-8000-8000-00000002${String(e).padStart(4,`0`)}`,a=1;r.push(Q({id:i(a++),name:`Top Navigation Bar`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t,y:100,width:1200,height:56,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`App Brand`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+24,y:118,width:280,height:24,text:`⚡ MCard Manager • Mission Control`,fontSize:`15`,fontWeight:`700`,fillColor:`#38BDF8`})),r.push(Q({id:i(a++),name:`Search Bar Container`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+320,y:114,width:280,height:28,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Search Bar Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+335,y:120,width:250,height:18,text:`🔍 Search cards, telemetry, fibers...`,fontSize:`11`,fillColor:`#64748B`})),r.push(Q({id:i(a++),name:`Nav Return Home Button`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+620,y:114,width:145,height:28,radius:6,fillColor:`#2563EB`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Nav Return Home Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+635,y:120,width:120,height:18,text:`🏠 Home Dashboard`,fontSize:`11`,fontWeight:`600`,fillColor:`#FFFFFF`})),r.push(Q({id:i(a++),name:`Action Upload`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+780,y:114,width:80,height:28,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Action Upload Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+795,y:120,width:60,height:18,text:`⬆️ Upload`,fontSize:`11`,fillColor:`#94A3B8`})),r.push(Q({id:i(a++),name:`Action New Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+875,y:114,width:90,height:28,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Action New Text Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+890,y:120,width:70,height:18,text:`➕ New Text`,fontSize:`11`,fillColor:`#94A3B8`})),r.push(Q({id:i(a++),name:`Route Handle Chip`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+980,y:114,width:196,height:28,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Route Handle Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+995,y:120,width:170,height:18,text:e.handle,fontSize:`11`,fillColor:`#64748B`})),r.push(Q({id:i(a++),name:`Sidebar Container`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+24,y:175,width:250,height:595,radius:8,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Sidebar Header`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+40,y:195,width:200,height:20,text:`CARD TYPES (12)`,fontSize:`11`,fontWeight:`700`,fillColor:`#64748B`}));let o=[{name:`★ All MCards (12)`,active:!0},{name:`📅 Public Calendar`,active:!1},{name:`🗺️ Map View`,active:!1},{name:`🎭 3D Theater`,active:!1},{name:`🎵 Music Visualizer V5`,active:!1},{name:`📊 Observability Cockpit`,active:!1},{name:`🎲 Monopoly Game`,active:!1},{name:`♟️ Chess Game`,active:!1},{name:`⚪ Go Game`,active:!1}],s=225;for(let c of o)c.active?(r.push(Q({id:i(a++),name:`Sidebar Item ${c.name} Bg`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+36,y:s,width:226,height:32,radius:6,fillColor:`#2563EB`})),r.push($({id:i(a++),name:`Sidebar Item ${c.name} Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+48,y:s+7,width:200,height:18,text:c.name,fontSize:`12`,fontWeight:`600`,fillColor:`#FFFFFF`}))):r.push($({id:i(a++),name:`Sidebar Item ${c.name} Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+48,y:s+7,width:200,height:18,text:c.name,fontSize:`12`,fillColor:`#94A3B8`})),s+=36;r.push(Q({id:i(a++),name:`Workspace Container`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+295,y:175,width:615,height:595,radius:8,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Workspace Title`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+315,y:195,width:300,height:22,text:`Active Card: Observability Cockpit`,fontSize:`15`,fontWeight:`700`,fillColor:`#F8FAFC`})),r.push($({id:i(a++),name:`Workspace Tabs`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+630,y:195,width:260,height:20,text:`[ Preview ] [ YAML ] [ CPN ] [ Telemetry ]`,fontSize:`11`,fillColor:`#38BDF8`})),r.push(Q({id:i(a++),name:`Inner Viewport Screen`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+315,y:235,width:575,height:460,radius:8,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Chart Title`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+335,y:255,width:400,height:22,text:`Real-time Grafana Faro Web SDK Telemetry`,fontSize:`13`,fontWeight:`700`,fillColor:`#38BDF8`}));let c=[{label:`LCP (Largest Contentful Paint)`,val:`0.82s (Good)`,x:t+335},{label:`FID (First Input Delay)`,val:`12ms (Good)`,x:t+520},{label:`CLS (Cumulative Layout Shift)`,val:`0.002 (Good)`,x:t+705}];for(let t of c)r.push(Q({id:i(a++),name:`Meter ${t.val} Box`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t.x,y:285,width:170,height:52,radius:6,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Meter ${t.val} Label`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t.x+10,y:292,width:155,height:14,text:t.label,fontSize:`9`,fontWeight:`600`,fillColor:`#64748B`})),r.push($({id:i(a++),name:`Meter ${t.val} Val`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t.x+10,y:312,width:155,height:18,text:t.val,fontSize:`13`,fontWeight:`700`,fillColor:`#10B981`}));r.push(Q({id:i(a++),name:`Telemetry Waveform Box`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+335,y:355,width:535,height:190,radius:6,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Waveform Label`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+350,y:370,width:450,height:16,text:`Lagrangian Trajectory & Telemetry Invariant Trace (INV-CDO-17)`,fontSize:`11`,fontWeight:`600`,fillColor:`#94A3B8`})),r.push($({id:i(a++),name:`Log Line 1`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+350,y:405,width:500,height:18,text:`🟢 [11:50:12] Faro Web SDK: Session initialized (CORS safe)`,fontSize:`11`,fillColor:`#10B981`})),r.push($({id:i(a++),name:`Log Line 2`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+350,y:435,width:500,height:18,text:`🟢 [11:50:13] Telemetry invariant INV-CDO-17 confirmed`,fontSize:`11`,fillColor:`#10B981`})),r.push($({id:i(a++),name:`Log Line 3`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+350,y:465,width:500,height:18,text:`🟢 [11:50:14] CPN transition fired: t_render_complete (60 FPS)`,fontSize:`11`,fillColor:`#10B981`})),r.push($({id:i(a++),name:`Log Line 4`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+350,y:495,width:500,height:18,text:`🟢 [11:50:15] Marking state: fiber_observed(1) • zero dropouts`,fontSize:`11`,fillColor:`#10B981`})),r.push(Q({id:i(a++),name:`Bottom Return Button`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+335,y:565,width:250,height:38,radius:6,fillColor:`#2563EB`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Bottom Return Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+350,y:575,width:220,height:18,text:`➔ Return to Home Dashboard`,fontSize:`12`,fontWeight:`600`,fillColor:`#FFFFFF`})),r.push(Q({id:i(a++),name:`Inspector Container`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+930,y:175,width:246,height:595,radius:8,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Inspector Title`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+946,y:195,width:200,height:20,text:`MCARD DETAILS`,fontSize:`11`,fontWeight:`700`,fillColor:`#64748B`}));let l=[{label:`Handle:`,val:`mcard:route:/app.html`,color:`#38BDF8`},{label:`Status:`,val:`🟢 Online (Active)`,color:`#10B981`},{label:`Runtime:`,val:`Tri-Runtime Parity`,color:`#F8FAFC`},{label:`Fiber:`,val:`INV-CDO-19 Cockpit`,color:`#F8FAFC`},{label:`Witness:`,val:`Certified Level E2`,color:`#A855F7`}],u=230;for(let o of l)r.push($({id:i(a++),name:`Inspector ${o.label} Label`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+946,y:u,width:200,height:16,text:o.label,fontSize:`10`,fontWeight:`600`,fillColor:`#64748B`})),r.push($({id:i(a++),name:`Inspector ${o.label} Val`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+946,y:u+18,width:215,height:18,text:o.val,fontSize:`12`,fontWeight:`600`,fillColor:o.color})),u+=46;return r}function Rh(e,t,n){let r=[],i=e=>`d7570000-0000-8000-8000-00000003${String(e).padStart(4,`0`)}`,a=1;r.push(Q({id:i(a++),name:`Top Navigation Bar`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t,y:100,width:1200,height:56,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Lab Brand`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+24,y:118,width:400,height:24,text:`📐 Responsive UI Lab • Viewport Workbench`,fontSize:`15`,fontWeight:`700`,fillColor:`#38BDF8`})),r.push(Q({id:i(a++),name:`Nav Return Home Button`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+760,y:114,width:155,height:28,radius:6,fillColor:`#2563EB`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Nav Return Home Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+775,y:120,width:130,height:18,text:`🏠 Home Dashboard`,fontSize:`11`,fontWeight:`600`,fillColor:`#FFFFFF`})),r.push(Q({id:i(a++),name:`Route Handle Chip`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+935,y:114,width:241,height:28,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Route Handle Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+950,y:120,width:215,height:18,text:e.handle,fontSize:`11`,fillColor:`#64748B`})),r.push(Q({id:i(a++),name:`Workbench Dock Container`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+24,y:175,width:1152,height:84,radius:8,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Arrangement Label`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+40,y:190,width:200,height:16,text:`WORKBENCH ARRANGEMENT:`,fontSize:`10`,fontWeight:`700`,fillColor:`#64748B`})),r.push(Q({id:i(a++),name:`Btn Arrange Horizontal`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+40,y:212,width:115,height:32,radius:6,fillColor:`#2563EB`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Text Arrange Horizontal`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+50,y:220,width:95,height:16,text:`☲ Horizontal`,fontSize:`11`,fontWeight:`600`,fillColor:`#FFFFFF`})),r.push(Q({id:i(a++),name:`Btn Arrange Vertical`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+165,y:212,width:105,height:32,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Text Arrange Vertical`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+175,y:220,width:85,height:16,text:`☰ Vertical`,fontSize:`11`,fillColor:`#94A3B8`})),r.push($({id:i(a++),name:`Orientation Label`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+300,y:190,width:150,height:16,text:`ORIENTATION:`,fontSize:`10`,fontWeight:`700`,fillColor:`#64748B`})),r.push(Q({id:i(a++),name:`Btn Orient Landscape`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+300,y:212,width:110,height:32,radius:6,fillColor:`#2563EB`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Text Orient Landscape`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+310,y:220,width:90,height:16,text:`↔ Landscape`,fontSize:`11`,fontWeight:`600`,fillColor:`#FFFFFF`})),r.push($({id:i(a++),name:`Presets Label`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+450,y:190,width:200,height:16,text:`DEVICE PRESETS:`,fontSize:`10`,fontWeight:`700`,fillColor:`#64748B`}));let o=[{name:`📱 Mobile (390px)`,active:!1,w:120},{name:`📟 Tablet (768px)`,active:!1,w:120},{name:`🪟 Split (50%)`,active:!1,w:100},{name:`🖥️ Desktop (1024px)`,active:!0,w:135},{name:`🖥️ Wide (1440px)`,active:!1,w:120}],s=t+450;for(let t of o)r.push(Q({id:i(a++),name:`Preset ${t.name} Bg`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:s,y:212,width:t.w,height:32,radius:6,fillColor:t.active?`#2563EB`:`#0F172A`,strokes:[{strokeColor:t.active?`#3B82F6`:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Preset ${t.name} Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:s+10,y:220,width:t.w-20,height:16,text:t.name,fontSize:`10`,fontWeight:t.active?`700`:`400`,fillColor:t.active?`#FFFFFF`:`#94A3B8`})),s+=t.w+10;r.push(Q({id:i(a++),name:`Viewport Chrome Frame`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+24,y:278,width:1152,height:490,radius:8,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push(Q({id:i(a++),name:`Mac Title Bar`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+24,y:278,width:1152,height:36,radius:8,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push(Q({id:i(a++),name:`Dot Red`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+40,y:290,width:12,height:12,radius:6,fillColor:`#EF4444`})),r.push(Q({id:i(a++),name:`Dot Yellow`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+58,y:290,width:12,height:12,radius:6,fillColor:`#F59E0B`})),r.push(Q({id:i(a++),name:`Dot Green`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+76,y:290,width:12,height:12,radius:6,fillColor:`#10B981`})),r.push($({id:i(a++),name:`Mac Window Title`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+110,y:288,width:600,height:18,text:`Viewport Frame Preview • Desktop Preset (1024 × 768) • 1.0x DPR`,fontSize:`12`,fontWeight:`600`,fillColor:`#E2E8F0`})),r.push(Q({id:i(a++),name:`Mockup Screen Canvas`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+44,y:326,width:1112,height:384,radius:6,fillColor:`#1E293B`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Mini Nav Title`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+64,y:345,width:400,height:20,text:`⚡ GovTech OS • Preview Render (1024px Viewport)`,fontSize:`13`,fontWeight:`700`,fillColor:`#38BDF8`}));let c=[{title:`🎛️ Mission Control`,desc:`RUM Telemetry & Cockpit`},{title:`📐 Responsive Lab`,desc:`Viewport Invariants`},{title:`🧭 Least Action (ℒ)`,desc:`Lagrangian Geodesic`},{title:`🎨 MCard Studio`,desc:`18 Active Fibers`},{title:`📦 Deployment Units`,desc:`Evidence Level E2`}],l=t+64;for(let t of c)r.push(Q({id:i(a++),name:`Mini Card ${t.title} Box`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:l,y:385,width:200,height:140,radius:6,fillColor:`#0F172A`,strokes:[{strokeColor:`#334155`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Mini Card ${t.title} Title`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:l+15,y:405,width:170,height:20,text:t.title,fontSize:`12`,fontWeight:`700`,fillColor:`#F8FAFC`})),r.push($({id:i(a++),name:`Mini Card ${t.title} Desc`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:l+15,y:435,width:170,height:36,text:t.desc,fontSize:`10`,fillColor:`#94A3B8`})),r.push($({id:i(a++),name:`Mini Card ${t.title} Invariant`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:l+15,y:485,width:170,height:18,text:`✓ Invariant Verified`,fontSize:`9`,fontWeight:`600`,fillColor:`#10B981`})),l+=215;return r.push($({id:i(a++),name:`Viewport Metrics Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+64,y:728,width:600,height:18,text:`Active Resolution: 1024 × 768 px • Scale: 100% • Layout: Flex & CSS Grid Invariant Verified`,fontSize:`11`,fontWeight:`600`,fillColor:`#38BDF8`})),r.push(Q({id:i(a++),name:`Bottom Return Button`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+890,y:720,width:240,height:34,radius:6,fillColor:`#2563EB`,strokes:[{strokeColor:`#3B82F6`,strokeWidth:1,strokeOpacity:1,strokeStyle:`solid`,strokeAlignment:`inner`}]})),r.push($({id:i(a++),name:`Bottom Return Text`,parentId:e.frameId,frameId:e.frameId,pageId:n,x:t+905,y:728,width:210,height:18,text:`➔ Return to Home Dashboard`,fontSize:`11`,fontWeight:`600`,fillColor:`#FFFFFF`})),r}function zh(e){if(!Buffer.isBuffer(e))throw Error(`MALFORMED_ARCHIVE: Expected Buffer input (INV-CDO-08)`);if(e.length<22)throw Error(`MALFORMED_ARCHIVE: Archive file too small to be a valid ZIP (INV-CDO-08)`);let t=Buffer.from([80,75,5,6]),n=e.lastIndexOf(t);if(n===-1)throw Error(`MALFORMED_ARCHIVE: End-of-central-directory signature not found (INV-CDO-08)`);let r=e.readUInt16LE(n+10),i=e.readUInt32LE(n+12),a=e.readUInt32LE(n+16);if(a+i>e.length)throw Error(`MALFORMED_ARCHIVE: Central directory out of bounds (INV-CDO-08)`);let o=a,s=new Map;for(let t=0;t<r;t++){if(o+46>e.length)throw Error(`MALFORMED_ARCHIVE: Truncated central directory entry ${t} (INV-CDO-08)`);if(e.readUInt32LE(o)!==33639248)throw Error(`MALFORMED_ARCHIVE: Corrupt central directory entry signature at offset ${o} (INV-CDO-08)`);let n=e.readUInt16LE(o+10),r=e.readUInt32LE(o+20),i=e.readUInt16LE(o+28),a=e.readUInt16LE(o+30),c=e.readUInt16LE(o+32),l=e.readUInt32LE(o+42),u=e.toString(`utf8`,o+46,o+46+i);if(o+=46+i+a+c,l+30>e.length)throw Error(`MALFORMED_ARCHIVE: Local file header out of bounds for ${u} (INV-CDO-08)`);if(e.readUInt32LE(l)!==67324752)throw Error(`MALFORMED_ARCHIVE: Corrupt local file header signature for ${u} (INV-CDO-08)`);let d=e.readUInt16LE(l+26),f=e.readUInt16LE(l+28),p=l+30+d+f;if(p+r>e.length)throw Error(`MALFORMED_ARCHIVE: Compressed payload out of bounds for ${u} (INV-CDO-08)`);let m=e.subarray(p,p+r),h;try{if(n===0)h=m;else if(n===8)h=Ym(m);else throw Error(`Unsupported compression method ${n}`)}catch(e){throw Error(`MALFORMED_ARCHIVE: Decompression failed for entry ${u}: ${e.message} (INV-CDO-08)`)}s.set(u,h)}return{entries:s,list:()=>Array.from(s.keys()).sort(),getJson:e=>{let t=s.get(e);if(!t)return null;try{return JSON.parse(t.toString(`utf8`))}catch(t){throw Error(`MALFORMED_ARCHIVE: Invalid JSON in entry ${e}: ${t.message} (INV-CDO-08)`)}},getBuffer:e=>s.get(e)||null}}function Bh(e){let t=[],n=[],r=0,i=Object.keys(e).sort();for(let a of i){let i=e[a],o;o=Buffer.isBuffer(i)?i:typeof i==`string`?Buffer.from(i,`utf8`):typeof i==`object`&&i?Buffer.from(JSON.stringify(i,null,2),`utf8`):Buffer.from(String(i),`utf8`);let s=Buffer.from(a,`utf8`),c=Vm(o),l=sh?sh(o):0,u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(0,6),u.writeUInt16LE(8,8),u.writeUInt16LE(0,10),u.writeUInt16LE(20480,12),u.writeUInt32LE(l,14),u.writeUInt32LE(c.length,18),u.writeUInt32LE(o.length,22),u.writeUInt16LE(s.length,26),u.writeUInt16LE(0,28),t.push(u,s,c);let d=Buffer.alloc(46);d.writeUInt32LE(33639248,0),d.writeUInt16LE(20,4),d.writeUInt16LE(20,6),d.writeUInt16LE(0,8),d.writeUInt16LE(8,10),d.writeUInt16LE(0,12),d.writeUInt16LE(20480,14),d.writeUInt32LE(l,16),d.writeUInt32LE(c.length,20),d.writeUInt32LE(o.length,24),d.writeUInt16LE(s.length,28),d.writeUInt16LE(0,30),d.writeUInt16LE(0,32),d.writeUInt16LE(0,34),d.writeUInt16LE(0,36),d.writeUInt32LE(0,38),d.writeUInt32LE(r,42),n.push(d,s),r+=30+s.length+c.length}let a=Buffer.concat(n),o=r,s=a.length,c=Buffer.alloc(22);return c.writeUInt32LE(101010256,0),c.writeUInt16LE(0,4),c.writeUInt16LE(0,6),c.writeUInt16LE(i.length,8),c.writeUInt16LE(i.length,10),c.writeUInt32LE(s,12),c.writeUInt32LE(o,16),c.writeUInt16LE(0,20),Buffer.concat([...t,a,c])}function Vh(e,t={}){let n=jh(e),r=N(n,`mcard.yaml`);if(!qr(r))throw Error(`MANIFEST_NOT_FOUND: mcard.yaml not found in ${n} (INV-CDO-08)`);let i=Yr(r,`utf8`),a=`design/landing-navigation.penpot`,o=i.match(/penpot_file\s*:\s*["']?([^"']+)["']?/);o&&(a=o[1].trim());let s=t.routes||Oh,c=[];for(let e of s){let t=N(n,e.path);if(!qr(t))throw Error(`GENERATION_ERROR: Route file '${e.path}' does not exist on disk for handle '${e.handle}' (INV-CDO-12)`);let r=kh(Mh(t));c.push({...e,fullPath:t,contentHash:r})}let l=(c.find(e=>e.isStart)||c[0]).frameId,u={};u[`manifest.json`]={type:`penpot/export-files`,version:1,generatedBy:`clm-kernel/0.0.1`,referer:`penpot`,files:[{id:Th,name:`LandingPage Navigation`,features:[`fdata/path-data`,`design-tokens/v1`,`variants/v1`,`layout/grid`,`components/v2`,`fdata/shape-data-type`]}]},u[`files/${Th}.json`]={id:Th,name:`LandingPage Navigation`,features:[`fdata/path-data`,`design-tokens/v1`,`variants/v1`,`layout/grid`,`components/v2`,`fdata/shape-data-type`],version:67,revn:1,vern:0,"created-at":`2026-10-07T00:00:00.000Z`,"modified-at":`2026-10-07T00:00:00.000Z`,"is-shared":!0,"has-media-trimmed":!1,createdAt:`2026-10-07T00:00:00.000Z`,modifiedAt:`2026-10-07T00:00:00.000Z`,isShared:!0,hasMediaTrimmed:!1,options:{componentsV2:!0,baseFontSize:`16px`},metadata:{referer:`penpot`,generatedBy:`clm-kernel/0.0.1`}},u[`files/${Th}/pages/${Eh}.json`]={id:Eh,name:`Main Navigation Flow`,index:0,flows:{[Dh]:{id:Dh,name:`main-nav`,"starting-frame":l,startingFrame:l}}};let d=`00000000-0000-0000-0000-000000000000`;u[`files/${Th}/pages/${Eh}/${d}.json`]={id:d,name:`Root Frame`,type:`frame`,x:0,y:0,width:.01,height:.01,rotation:0,selrect:{x:0,y:0,width:.01,height:.01,x1:0,y1:0,x2:.01,y2:.01},points:[{x:0,y:0},{x:.01,y:0},{x:.01,y:.01},{x:0,y:.01}],transform:{a:1,b:0,c:0,d:1,e:0,f:0},"transform-inverse":{a:1,b:0,c:0,d:1,e:0,f:0},"parent-id":d,"frame-id":d,"page-id":Eh,"hide-fill-on-export":!1,strokes:[],fills:[{"fill-color":`#FFFFFF`,"fill-opacity":1}],shapes:c.map(e=>e.frameId)};let f=100;for(let e of c){let t=(e.destinations||[]).map((t,n)=>({id:`nav-${e.frameId}-${t}-${n}`,"action-type":`navigate`,"event-type":`click`,destination:t,"preserve-scroll":!1,animation:{"animation-type":`slide`,duration:250,easing:`ease-in-out`,direction:t===l?`left`:`right`,way:`in`,"offset-effect":!1}})),n=1200,r=[];e.path===`index.html`?r=Ih(e,f,Eh):e.path===`app.html`?r=Lh(e,f,Eh):e.path===`responsive-lab.html`&&(r=Rh(e,f,Eh));let i={id:e.frameId,name:e.name,type:`frame`,"page-id":Eh,x:f,y:100,width:n,height:800,rotation:0,selrect:{x:f,y:100,width:n,height:800,x1:f,y1:100,x2:f+n,y2:900},points:[{x:f,y:100},{x:f+n,y:100},{x:f+n,y:900},{x:f,y:900}],transform:{a:1,b:0,c:0,d:1,e:0,f:0},"transform-inverse":{a:1,b:0,c:0,d:1,e:0,f:0},"parent-id":d,"frame-id":d,"hide-fill-on-export":!1,strokes:[{"stroke-color":`#334155`,"stroke-width":1,"stroke-opacity":1,"stroke-style":`solid`,"stroke-alignment":`inner`}],r1:8,r2:8,r3:8,r4:8,fills:[{"fill-color":`#0F172A`,"fill-opacity":1}],shapes:r.map(e=>e.id),"plugin-data":{clm:{handle:e.handle,hash:e.contentHash}},interactions:t};u[`files/${Th}/pages/${Eh}/${e.frameId}.json`]=i;for(let e of r)u[`files/${Th}/pages/${Eh}/${e.id}.json`]=e;f+=1350}let p=Bh(u),m=t.out?Je(t.out):N(n,a);return Qe(m),i.includes(`<frame-uuid>`)&&i.replace(`<frame-uuid>`,l),{ok:!0,targetFile:m,bytes:p.length,archiveHash:kh(p),startingFrameId:l,routesCount:c.length}}function Hh(e){let t=e.trim();if(t.startsWith(`{`)&&t.endsWith(`}`)){let e=t.slice(1,-1).trim(),n={},r=Uh(e);for(let e of r){let t=e.indexOf(`:`);if(t!==-1){let r=e.slice(0,t).trim(),i=e.slice(t+1).trim();typeof i==`string`&&(/^-?\d+$/.test(i)?i=parseInt(i,10):i===`true`?i=!0:i===`false`?i=!1:(i.startsWith(`"`)&&i.endsWith(`"`)||i.startsWith(`'`)&&i.endsWith(`'`))&&(i=i.slice(1,-1))),n[r]=i}}return n}return null}function Uh(e){let t=[],n=``,r=!1,i=``;for(let a=0;a<e.length;a++){let o=e[a];(o===`"`||o===`'`)&&(a===0||e[a-1]!==`\\`)?(r?i===o&&(r=!1):(r=!0,i=o),n+=o):o===`,`&&!r?(t.push(n.trim()),n=``):n+=o}return n.trim()&&t.push(n.trim()),t}function Wh(e){if(typeof e==`string`){let t=Hh(e);return t&&t.id?{id:String(t.id),initialTokens:typeof t.initial_tokens==`number`?t.initial_tokens:0,initialColor:typeof t.initial_color==`string`?t.initial_color:void 0,capacity:typeof t.capacity==`number`?t.capacity:void 0,description:typeof t.description==`string`?t.description:void 0}:{id:e.trim(),initialTokens:0}}if(typeof e==`object`&&e){let t=e;for(let[e,n]of Object.entries(t))if(e.startsWith(`{id`)){let t=Hh(`${e}: ${n}`);if(t&&t.id)return{id:String(t.id),initialTokens:typeof t.initial_tokens==`number`?t.initial_tokens:0,initialColor:typeof t.initial_color==`string`?t.initial_color:void 0}}return{id:String(t.id??t.name??``),initialTokens:typeof t.initial_tokens==`number`?t.initial_tokens:typeof t.initialTokens==`number`?t.initialTokens:0,initialColor:typeof t.initial_color==`string`?t.initial_color:typeof t.initialColor==`string`?t.initialColor:void 0,capacity:typeof t.capacity==`number`?t.capacity:void 0,description:typeof t.description==`string`?t.description:void 0}}throw Error(`Invalid place specification in topology: ${JSON.stringify(e)}`)}function Gh(e){if(typeof e!=`object`||!e)throw Error(`Invalid transition specification: ${JSON.stringify(e)}`);let t=e,n=String(t.id??t.name??``),r=[];Array.isArray(t.inputs)?r=t.inputs.map(String):typeof t.inputs==`string`&&(r=t.inputs.split(`,`).map(e=>e.trim()).filter(Boolean));let i=[];Array.isArray(t.outputs)?i=t.outputs.map(String):typeof t.outputs==`string`&&(i=t.outputs.split(`,`).map(e=>e.trim()).filter(Boolean));let a=typeof t.exit_code==`number`?t.exit_code:typeof t.exitCode==`number`?t.exitCode:0,o=typeof t.content==`string`?t.content:void 0,s=typeof t.required_agent_class==`string`?t.required_agent_class:void 0,c=typeof t.agent_did==`string`?t.agent_did:void 0,l=typeof t.vcard_pre==`string`?t.vcard_pre:void 0,u=typeof t.vcard_post==`string`?t.vcard_post:void 0,d;if(typeof t.binding==`object`&&t.binding!==null){let e=t.binding;d={type:e.type??`script`,path:typeof e.path==`string`?e.path:void 0,ref:typeof e.ref==`string`?e.ref:void 0,timeout:typeof e.timeout==`number`?e.timeout:void 0,args:Array.isArray(e.args)?e.args.map(String):void 0,outputMap:typeof e.output_map==`string`?e.output_map:void 0,context:typeof e.context==`object`&&e.context!==null?e.context:void 0}}return{id:n,inputs:r,outputs:i,exitCode:a,content:o,requiredAgentClass:s,agentDid:c,vcardPre:l,vcardPost:u,binding:d}}function Kh(e){if(typeof e!=`object`||!e)return;let t=e,n;if(typeof t.final_marking==`object`&&t.final_marking!==null){n={};for(let[e,r]of Object.entries(t.final_marking))n[e]=Number(r)}let r;if(typeof t.event_counts==`object`&&t.event_counts!==null){r={};for(let[e,n]of Object.entries(t.event_counts))r[e]=Number(n)}let i=typeof t.deadlock==`boolean`?t.deadlock:void 0,a=typeof t.fire_count==`number`?t.fire_count:void 0,o;if(typeof t.noetherian_invariants==`object`&&t.noetherian_invariants!==null){let e=t.noetherian_invariants,n=[],r=e.p_invariants??e.pInvariants;if(typeof r==`object`&&r&&!Array.isArray(r)){let e=r.p_invariants;Array.isArray(e)&&(r=e)}if(Array.isArray(r)){for(let e of r)if(typeof e==`object`&&e){let t=e,r=Number(t.expected_constant??t.expectedConstant??0),i={};if(typeof t.weights==`object`&&t.weights!==null)for(let[e,n]of Object.entries(t.weights))i[e]=Number(n);n.push({expectedConstant:r,weights:i})}}o={pInvariants:n}}return{eventCounts:r,deadlock:i,finalMarking:n,fireCount:a,noetherianInvariants:o}}function qh(e){let t=na(e),n=t.petri_net??t.petriNet??t,r=String(n.name??`petri_net`),i=[];if(Array.isArray(n.places))i=n.places;else if(typeof n.places==`object`&&n.places!==null){let e=n.places.places;Array.isArray(e)&&(i=e)}let a=i.map(Wh),o=[];if(Array.isArray(n.transitions))o=n.transitions;else if(typeof n.transitions==`object`&&n.transitions!==null){let e=n.transitions.transitions;Array.isArray(e)&&(o=e)}let s=o.map(Gh),c=typeof n.halt_after==`number`?n.halt_after:void 0,l=Kh(n.assertions),u=new Set(a.map(e=>e.id));for(let e of s){for(let t of e.inputs)if(!u.has(t))throw Error(`[PetriNetTopology] Validation error in transition '${e.id}': input place '${t}' does not exist.`);for(let t of e.outputs)if(!u.has(t))throw Error(`[PetriNetTopology] Validation error in transition '${e.id}': output place '${t}' does not exist.`)}return{name:r,places:a,transitions:s,haltAfter:c,assertions:l}}Cr({},{CHANGE_CALCULUS:()=>Le,ED25519_PKCS8_PREFIX:()=>Mr,ED25519_SPKI_PREFIX:()=>Nr,HANDLE_GRAMMAR:()=>Fe,KIND_SECTORS:()=>Ie,NOISE_BLOCKLEN:()=>64,NOISE_HASHLEN:()=>32,X25519_PKCS8_PREFIX:()=>Pr,X25519_SPKI_PREFIX:()=>Fr,blake3Digest:()=>Co,bytesToHex:()=>kr,constantTimeEqual:()=>Xh,declaredKinds:()=>Ue,decodeBase58:()=>Or,diffieHellmanX25519:()=>Do,encodeBase58:()=>Dr,extractBalancedBraces:()=>Jh,generateEphemeralX25519:()=>Oo,generateRandomNonce:()=>jr,hexToBytes:()=>Ar,hkdf2:()=>To,hkdf3:()=>Eo,hmacBlake3:()=>wo,isDeclared:()=>He,isSector:()=>Ve,kindNameOf:()=>Be,kindOf:()=>Re,normalizeToUint8Array:()=>Yh,parseYamlLines:()=>aa,parseYamlOrJson:()=>na,parseYamlValue:()=>oa,sectorOf:()=>ze,toBuffer:()=>Ir});function Jh(e,t){let n=e.indexOf(`{`,t);if(n===-1)return null;let r=0;for(let t=n;t<e.length;t++)if(e[t]===`{`)r++;else if(e[t]===`}`&&(r--,r===0))return{content:e.slice(n+1,t),endIndex:t};return null}function Yh(e){return e instanceof Uint8Array?e:typeof e==`string`?new TextEncoder().encode(e):e&&typeof Buffer<`u`&&Buffer.isBuffer(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e instanceof ArrayBuffer||Array.isArray(e)?new Uint8Array(e):new Uint8Array}function Xh(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}var Zh=[`U0`,`U1`,`U2`,`U3`,`U4`,`U5`],Qh=e({BLAKE3_HASH_PREFIX:()=>g,CATALOG_SCHEMA_REF:()=>CATALOG_SCHEMA_REF,CATALOG_VERSION:()=>CATALOG_VERSION,CHUNKER_ID:()=>CHUNKER_ID,CHUNKER_VERSION:()=>1,CONFORMANCE_HANDLE:()=>CONFORMANCE_HANDLE,DEFAULT_COLLISION_THRESHOLD:()=>2,DEFAULT_HASH_PREFIX:()=>DEFAULT_HASH_PREFIX,DEFAULT_SATORI_PORT:()=>DEFAULT_SATORI_PORT,DEFAULT_TOKEN_LOCALE:()=>`UTC`,DEFAULT_TOKEN_TIMESTAMP:()=>DEFAULT_TOKEN_TIMESTAMP,FiberLifecycle:()=>Pe,FibrationFiber:()=>eg,MAX_SAFE_INT:()=>MAX_SAFE_INT,MIN_SAFE_INT:()=>MIN_SAFE_INT,NOISE_BLOCKLEN:()=>64,NOISE_FRAME_HEADER_LEN:()=>2,NOISE_HASHLEN:()=>32,NOISE_KEYLEN:()=>32,NOISE_NONCELEN:()=>12,NOISE_PROTOCOL_NAME:()=>NOISE_PROTOCOL_NAME,NOISE_TAGLEN:()=>16,PINVARIANT_OVERFLOW_CODE:()=>PINVARIANT_OVERFLOW_CODE,PKC_CAPABILITY_MIME_TYPE:()=>PKC_CAPABILITY_MIME_TYPE,PKC_SERVICE_MDNS_TYPE:()=>PKC_SERVICE_MDNS_TYPE,PKC_SERVICE_PREFIX:()=>PKC_SERVICE_PREFIX,PolynomialFunctor:()=>$h,ProcessFibration:()=>tg,RECEIPT_SCHEMA_VERSION:()=>RECEIPT_SCHEMA_VERSION,SHA256_HASH_PREFIX:()=>_,TypeInterpreter:()=>og,VIRTUAL_BOTTOM:()=>VIRTUAL_BOTTOM,VIRTUAL_TOP:()=>VIRTUAL_TOP,compilePortableSqlite:()=>Ki,executeElement:()=>So,extractToolCall:()=>rg,hexToBytes:()=>Ar,parsePortableSqlite:()=>Ji,verifyFibrationAxioms:()=>ng}),$h=class e{terms;constructor(t=[]){this.terms=e.normalize(t)}static normalize(e){let t=new Map;for(let n of e){let e=Math.max(0,Math.floor(n.exponent)),r=t.get(e);r?r.coeff+=n.coefficient:t.set(e,{coeff:n.coefficient,tag:n.tag})}let n=[];for(let[e,r]of t.entries())Math.abs(r.coeff)>1e-12&&n.push({coefficient:r.coeff,exponent:e,tag:r.tag});return n.sort((e,t)=>t.exponent-e.exponent),n}get degree(){return this.terms.length>0?this.terms[0].exponent:0}get isZero(){return this.terms.length===0}evaluate(e){let t=0;for(let n of this.terms)t+=n.coefficient*e**+n.exponent;return t}add(t){return new e([...this.terms,...t.terms])}multiply(t){let n=[];for(let e of this.terms)for(let r of t.terms)n.push({coefficient:e.coefficient*r.coefficient,exponent:e.exponent+r.exponent,tag:e.tag??r.tag});return new e(n)}scale(t){return Math.abs(t)<1e-12?e.zero():new e(this.terms.map(e=>({...e,coefficient:e.coefficient*t})))}pow(t){if(t<0)throw Error(`Polynomial exponent must be non-negative`);if(t===0)return e.constant(1);if(t===1)return this;let n=this;for(let e=1;e<t;e++)n=n.multiply(this);return n}compose(t){let n=e.zero();for(let e of this.terms){let r=t.pow(e.exponent).scale(e.coefficient);n=n.add(r)}return n}derivative(){let t=[];for(let e of this.terms)e.exponent>0&&t.push({coefficient:e.coefficient*e.exponent,exponent:e.exponent-1,tag:e.tag});return new e(t)}toString(){return this.terms.length===0?`0`:this.terms.map((e,t)=>{let n=``;n=e.exponent===0?`${e.coefficient}`:e.coefficient===1?``:e.coefficient===-1?`-`:`${e.coefficient}`;let r=``;r=e.exponent===0?``:e.exponent===1?`y`:`y^${e.exponent}`;let i=`${n}${r}`;return t===0?i:e.coefficient>0?`+ ${i}`:`- ${i.replace(/^-/,``)}`}).join(` `)}toJSON(){return{degree:this.degree,terms:this.terms.map(e=>({coefficient:e.coefficient,exponent:e.exponent})),expression:this.toString()}}static zero(){return new e([])}static constant(t){return Math.abs(t)<1e-12?e.zero():new e([{coefficient:t,exponent:0}])}static identity(){return new e([{coefficient:1,exponent:1}])}static monomial(t,n,r){return new e([{coefficient:t,exponent:n,tag:r}])}static fromDegree(t){return e.monomial(1,t)}static fromTerms(t){return new e(t)}static compose(e,t){return e.compose(t)}static evaluate(e,t){return e.evaluate(t)}},eg=class extends Pe{#e;#t;pcard;#n=0;constructor(e,t,n){super(e,n?.coeffects??n?.pcard?.coeffects),this.#e=t,this.#t=n?.carrierHandle,this.pcard=n?.pcard}get carrier(){return this.#e}get carrierHandle(){return this.#t}get residualEntropy(){return this.#n}_migrateCarrier(e,t){if(this.state!==`loading`&&this.state!==`pending`)throw Error(`FibrationFiber [${this.id}]: Carrier migration only allowed in 'pending' or 'loading' state (current: ${this.state})`);this.#e=e,t!==void 0&&(this.#t=t)}_setResidualEntropy(e){this.#n=Math.max(0,e)}async dispose(){this.state===`active`?await this.unload():await this.forceDispose()}},tg=class{#e=new Map;#t=new Map;register(e){let t=e.fiber.id;this.#e.set(t,e);let n=e.carrier.hash.toString(),r=this.#t.get(n);r||(r=new Set,this.#t.set(n,r)),r.add(t)}project(e){return e.carrier}fiberOver(e){let t=e.hash.toString(),n=this.#t.get(t);if(!n)return[];let r=[];for(let e of n){let t=this.#e.get(e);t&&r.push(t)}return r}getProcess(e){return this.#e.get(e)}activeProcesses(){return Array.from(this.#e.values()).filter(e=>e.fiber.state===`active`||e.fiber.state===`loading`)}deregister(e){let t=this.#e.get(e);if(!t)return!1;let n=t.carrier.hash.toString(),r=this.#t.get(n);return r&&(r.delete(e),r.size===0&&this.#t.delete(n)),this.#e.delete(e)}get size(){return this.#e.size}};function ng(e,t){let n=[];return e.project(t)!==t.carrier&&n.push(`Axiom 1 (Projection): fibration.project(P) !== process.carrier`),t.fiber.carrier!==t.carrier&&n.push(`Axiom 1 (Carrier Consistency): process.fiber.carrier !== process.carrier`),t.fiber.state===`disposed`&&t.fiber.disposables.length>0&&n.push(`Axiom 2 (Zero Residual State): Disposed fiber has ${t.fiber.disposables.length} undisposed resources.`),(!t.carrier.hash||t.carrier.hash.toString().length===0)&&n.push(`Axiom 3 (CAS Invariance): Carrier MCard missing valid cryptographic content hash.`),{valid:n.length===0,errors:n}}function rg(e){if(!e||typeof e!=`string`)return{isToolCall:!1,format:`none`};let t=e.trim(),n=t.match(/<execute\s+pcard=(["'])(.*?)\1(?:\s+input=(["'])([\s\S]*?)\3)?(?:\s+label=(["'])(.*?)\5)?\s*\/>/i);if(n&&n.index!==void 0){let e=n[2]||``,r=n[4]||``,i={};if(r)try{i=JSON.parse(r)}catch{i={raw:r}}let a=n[6];return{isToolCall:!0,format:`satori_execute`,preamble:t.slice(0,n.index).trim()||void 0,action:e,actionInput:i,prompt:i.prompt||i.query||i.raw,size:i.size,thought:a,toSatoriElement:()=>So(e,typeof r==`string`?r:JSON.stringify(i),a)}}let r=``,i,a=t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);if(a){r=(a[1]||``).trim();let e=a.index??0;e>0&&(i=t.slice(0,e).trim()||void 0)}else{let e=t.indexOf(`{`),n=t.lastIndexOf(`}`);e!==-1&&n>e&&(r=t.slice(e,n+1),e>0&&(i=t.slice(0,e).trim()||void 0))}if(r)try{let e=JSON.parse(r);if(e.action&&typeof e.action==`string`){let t=e.action_input;if(typeof t==`string`)try{t=JSON.parse(t)}catch{t={prompt:t}}let n=t?.prompt||t?.query||t?.text||(typeof t==`string`?t:void 0),r=t?.size||`1024x1024`,a=e.thought||e.explanation||void 0;return{isToolCall:!0,format:`react_json`,preamble:i,action:e.action,actionInput:typeof t==`object`?t:{value:t},prompt:n,size:r,thought:a,rawJson:e,toSatoriElement:()=>So(e.action,typeof t==`string`?t:JSON.stringify(t),a)}}if(e.name&&(e.arguments||e.parameters)){let t=e.arguments||e.parameters;if(typeof t==`string`)try{t=JSON.parse(t)}catch{t={raw:t}}return{isToolCall:!0,format:`openai_function`,preamble:i,action:e.name,actionInput:t,prompt:t?.prompt||t?.query,size:t?.size,rawJson:e,toSatoriElement:()=>So(e.name,t)}}}catch{}return{isToolCall:!1,format:`none`}}var ig={$schema:`http://json-schema.org/draft-07/schema#`,description:`CLM Canonical Polyglot Type Dictionary Single Source of Truth (SSOT)`,invariants:[`INV-444`,`INV-10`],types:{"application/3d-obj":{category:`model`,description:`Wavefront OBJ 3D model geometry.`,extensions:[`.obj`],is_binary:!1,magic_bytes:[],mime:`application/3d-obj`,text_patterns:[],universe:`U0`},"application/geo+json":{category:`text`,description:`Content type for GeoJSON geospatial data.`,extensions:[`.geojson`],is_binary:!1,magic_bytes:[],mime:`application/geo+json`,text_patterns:[`FeatureCollection`,`"type"`,`"geometry"`,`"coordinates"`],universe:`U0`},"application/geopackage+sqlite3":{category:`blob`,description:`Content type for GeoPackage geospatial database files.`,extensions:[`.gpkg`],is_binary:!0,magic_bytes:[{description:`Magic bytes for application/geopackage+sqlite3`,hex:`53514c69746520666f726d6174203300`,offset:0}],mime:`application/geopackage+sqlite3`,text_patterns:[],universe:`U0`},"application/gzip":{category:`archive`,description:`Gzip compressed archive.`,extensions:[`.gz`,`.tgz`],is_binary:!0,magic_bytes:[{description:`Gzip magic header`,hex:`1f8b`,offset:0}],mime:`application/gzip`,text_patterns:[],universe:`U0`},"application/javascript":{category:`code`,description:`Content type for JavaScript source.`,extensions:[`.js`],is_binary:!1,magic_bytes:[],mime:`application/javascript`,text_patterns:[`^'use strict'`,`^import `,`^const `,`^function `,`^export `],universe:`U0`},"application/json":{category:`text`,description:`Content type for JSON data.`,extensions:[`.json`],is_binary:!1,magic_bytes:[],mime:`application/json`,text_patterns:[`^\\s*[{\\[]`],universe:`U0`},"application/octet-stream":{category:`blob`,description:`Content type for arbitrary binary data (fallback).`,extensions:[`.bin`],is_binary:!0,magic_bytes:[],mime:`application/octet-stream`,text_patterns:[],universe:`U0`},"application/pdf":{category:`blob`,description:`Content type for PDF documents.`,extensions:[`.pdf`],is_binary:!0,magic_bytes:[{description:`Magic bytes for application/pdf`,hex:`25504446`,offset:0}],mime:`application/pdf`,text_patterns:[],universe:`U0`},"application/vnd.google-earth.kml+xml":{category:`text`,description:`Content type for KML (Keyhole Markup Language) geospatial data.`,extensions:[`.kml`],is_binary:!1,magic_bytes:[],mime:`application/vnd.google-earth.kml+xml`,text_patterns:[`<kml`,`xmlns.*opengis.net/kml`,`<Placemark>`,`<Document>`],universe:`U0`},"application/vnd.mcard+json":{category:`data`,description:`CLM MCard continuation carrier format.`,extensions:[`.mcard`],is_binary:!1,magic_bytes:[],mime:`application/vnd.mcard+json`,text_patterns:[`"mcard_version"`],universe:`U1`},"application/vnd.pcard+json":{category:`data`,description:`CLM PCard packet specification format.`,extensions:[`.pcard`],is_binary:!1,magic_bytes:[],mime:`application/vnd.pcard+json`,text_patterns:[`"pcard_version"`],universe:`U1`},"application/vnd.vcard+json":{category:`data`,description:`CLM VCard verification certificate format.`,extensions:[`.vcard`],is_binary:!1,magic_bytes:[],mime:`application/vnd.vcard+json`,text_patterns:[`"vcard_version"`],universe:`U1`},"application/wasm":{category:`code`,description:`WebAssembly binary format.`,extensions:[`.wasm`],is_binary:!0,magic_bytes:[{description:`WASM magic header`,hex:`0061736d`,offset:0}],mime:`application/wasm`,text_patterns:[],universe:`U0`},"application/x-shapefile":{category:`blob`,description:`Content type for Esri Shapefile geospatial data.`,extensions:[`.shp`],is_binary:!0,magic_bytes:[{description:`Magic bytes for application/x-shapefile`,hex:`0000270a`,offset:0}],mime:`application/x-shapefile`,text_patterns:[],universe:`U0`},"application/x-sqlite3":{category:`blob`,description:`Content type for SQLite database files.`,extensions:[`.db`],is_binary:!0,magic_bytes:[{description:`Magic bytes for application/x-sqlite3`,hex:`53514c69746520666f726d6174203300`,offset:0}],mime:`application/x-sqlite3`,text_patterns:[],universe:`U0`},"application/x-tar":{category:`archive`,description:`POSIX tar archive.`,extensions:[`.tar`],is_binary:!0,magic_bytes:[{description:`USTAR magic`,hex:`7573746172`,offset:257}],mime:`application/x-tar`,text_patterns:[],universe:`U0`},"application/x-yaml":{category:`text`,description:`YAML Ain't Markup Language data serialization.`,extensions:[`.yaml`,`.yml`],is_binary:!1,magic_bytes:[],mime:`application/x-yaml`,text_patterns:[`^---\\s*\\n`],universe:`U0`},"application/xml":{category:`text`,description:`Extensible Markup Language data.`,extensions:[`.xml`],is_binary:!1,magic_bytes:[],mime:`application/xml`,text_patterns:[`^<\\?xml`],universe:`U0`},"application/yaml":{category:`text`,description:`Content type for YAML documents.`,extensions:[`.yaml`],is_binary:!1,magic_bytes:[],mime:`application/yaml`,text_patterns:[`^---`,`^\\w+:`],universe:`U0`},"application/zip":{category:`blob`,description:`Content type for ZIP archives.`,extensions:[`.zip`],is_binary:!0,magic_bytes:[{description:`Magic bytes for application/zip`,hex:`504b0304`,offset:0}],mime:`application/zip`,text_patterns:[],universe:`U0`},"audio/mpeg":{category:`media`,description:`MPEG Audio Layer III stream.`,extensions:[`.mp3`],is_binary:!0,magic_bytes:[{description:`ID3v2 container`,hex:`494433`,offset:0},{description:`MPEG ADTS sync`,hex:`fffb`,offset:0}],mime:`audio/mpeg`,text_patterns:[],universe:`U0`},"font/woff2":{category:`media`,description:`Web Open Font Format 2.0.`,extensions:[`.woff2`],is_binary:!0,magic_bytes:[{description:`wOF2 header`,hex:`774f4632`,offset:0}],mime:`font/woff2`,text_patterns:[],universe:`U0`},"image/gif":{category:`media`,description:`Content type for GIF images.`,extensions:[`.gif`],is_binary:!0,magic_bytes:[{description:`Magic bytes for image/gif`,hex:`47494638`,offset:0}],mime:`image/gif`,text_patterns:[],universe:`U0`},"image/jpeg":{category:`media`,description:`Content type for JPEG images.`,extensions:[`.jpg`],is_binary:!0,magic_bytes:[{description:`Magic bytes for image/jpeg`,hex:`ffd8ff`,offset:0}],mime:`image/jpeg`,text_patterns:[],universe:`U0`},"image/png":{category:`media`,description:`Content type for Portable Network Graphics images.`,extensions:[`.png`],is_binary:!0,magic_bytes:[{description:`Magic bytes for image/png`,hex:`89504e470d0a1a0a`,offset:0}],mime:`image/png`,text_patterns:[],universe:`U0`},"image/svg+xml":{category:`media`,description:`Content type for SVG vector graphics.`,extensions:[`.svg`],is_binary:!1,magic_bytes:[],mime:`image/svg+xml`,text_patterns:[`<svg`,`xmlns.*svg`],universe:`U0`},"image/vnd.djvu":{category:`blob`,description:`Content type for DjVu document files.`,extensions:[`.djvu`],is_binary:!0,magic_bytes:[{description:`Magic bytes for image/vnd.djvu`,hex:`41542654464f524d`,offset:0}],mime:`image/vnd.djvu`,text_patterns:[],universe:`U0`},"image/vnd.dxf":{category:`blob`,description:`Content type for AutoCAD DXF (Drawing Exchange Format) files.`,extensions:[`.dxf`],is_binary:!1,magic_bytes:[],mime:`image/vnd.dxf`,text_patterns:[`^\\s*0`,`SECTION`,`HEADER`,`ENDSEC`],universe:`U0`},"image/webp":{category:`media`,description:`WebP image format.`,extensions:[`.webp`],is_binary:!0,magic_bytes:[{description:`RIFF container for WebP`,hex:`52494646`,offset:0}],mime:`image/webp`,text_patterns:[],universe:`U0`},"model/gltf+json":{category:`blob`,description:`Content type for glTF (GL Transmission Format) 3D scenes.`,extensions:[`.gltf`],is_binary:!1,magic_bytes:[],mime:`model/gltf+json`,text_patterns:[`"asset"`,`"scene"`,`"nodes"`,`"meshes"`],universe:`U0`},"model/obj":{category:`blob`,description:`Content type for Wavefront OBJ 3D model files.`,extensions:[`.obj`],is_binary:!1,magic_bytes:[],mime:`model/obj`,text_patterns:[`^v `,`^# `,`^f `,`^mtllib `],universe:`U0`},"model/stl":{category:`blob`,description:`Content type for STL (Stereolithography) 3D model files.`,extensions:[`.stl`],is_binary:!0,magic_bytes:[],mime:`model/stl`,text_patterns:[`^solid `],universe:`U0`},"text/css":{category:`text`,description:`Cascading Style Sheets.`,extensions:[`.css`],is_binary:!1,magic_bytes:[],mime:`text/css`,text_patterns:[],universe:`U0`},"text/csv":{category:`data`,description:`Comma-separated values tabular text.`,extensions:[`.csv`],is_binary:!1,magic_bytes:[],mime:`text/csv`,text_patterns:[],universe:`U0`},"text/html":{category:`text`,description:`Content type for HTML documents.`,extensions:[`.html`],is_binary:!1,magic_bytes:[],mime:`text/html`,text_patterns:[`^\\s*<!doctype html`,`^\\s*<html`],universe:`U0`},"text/javascript":{category:`code`,description:`JavaScript programming language source.`,extensions:[`.cjs`,`.js`,`.mjs`],is_binary:!1,magic_bytes:[],mime:`text/javascript`,text_patterns:[`^'use strict'`,`^import `,`^const `,`^function `,`^export `],universe:`U0`},"text/markdown":{category:`text`,description:`Content type for Markdown documents.`,extensions:[`.md`],is_binary:!1,magic_bytes:[],mime:`text/markdown`,text_patterns:[`^#`,`^\\*\\*`,`^- `],universe:`U0`},"text/plain":{category:`text`,description:`Content type for plain text documents.`,extensions:[`.txt`],is_binary:!1,magic_bytes:[],mime:`text/plain`,text_patterns:[],universe:`U0`},"text/x-mermaid":{category:`text`,description:`Mermaid diagram specification.`,extensions:[`.mermaid`,`.mmd`],is_binary:!1,magic_bytes:[],mime:`text/x-mermaid`,text_patterns:[`^\\s*(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|gitGraph)`],universe:`U0`},"text/x-python":{category:`code`,description:`Content type for Python scripts.`,extensions:[`.py`],is_binary:!1,magic_bytes:[],mime:`text/x-python`,text_patterns:[`^#!/usr/bin/env python`,`^#!/usr/bin/python`,`^import `,`^from .* import`,`^def `,`^class `],universe:`U0`},"text/x-rust":{category:`code`,description:`Rust systems programming language source.`,extensions:[`.rs`],is_binary:!1,magic_bytes:[],mime:`text/x-rust`,text_patterns:[],universe:`U0`},"text/x-shellscript":{category:`code`,description:`Content type for shell scripts.`,extensions:[`.sh`],is_binary:!1,magic_bytes:[],mime:`text/x-shellscript`,text_patterns:[`^#!/bin/(ba)?sh`,`^#!/usr/bin/env (ba)?sh`],universe:`U0`},"text/x-sql":{category:`code`,description:`Structured Query Language script.`,extensions:[`.sql`],is_binary:!1,magic_bytes:[],mime:`text/x-sql`,text_patterns:[`^\\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)\\b`],universe:`U0`},"text/x-tex":{category:`code`,description:`Content type for LaTeX source files.`,extensions:[`.tex`],is_binary:!1,magic_bytes:[],mime:`text/x-tex`,text_patterns:[`\\\\documentclass`,`\\\\begin\\{document\\}`,`\\\\usepackage`,`\\\\section`,`\\\\title`],universe:`U0`},"text/x-tikz":{category:`code`,description:`Content type for TikZ/PGF diagram source files.`,extensions:[`.tikz`],is_binary:!1,magic_bytes:[],mime:`text/x-tikz`,text_patterns:[`\\\\begin\\{tikzpicture\\}`,`\\\\tikz`,`\\\\draw`,`\\\\node`,`\\\\path`,`\\\\usetikzlibrary`],universe:`U0`},"text/x-typescript":{category:`code`,description:`TypeScript typed programming language source.`,extensions:[`.ts`,`.tsx`],is_binary:!1,magic_bytes:[],mime:`text/x-typescript`,text_patterns:[],universe:`U0`},"text/xml":{category:`text`,description:`Content type for XML documents.`,extensions:[`.xml`],is_binary:!1,magic_bytes:[],mime:`text/xml`,text_patterns:[`^\\s*<\\?xml`,`^\\s*<[a-zA-Z]`],universe:`U0`},"video/mp4":{category:`media`,description:`MPEG-4 Part 14 video container.`,extensions:[`.m4v`,`.mp4`],is_binary:!0,magic_bytes:[{description:`ISO Base Media file type box (ftyp)`,hex:`66747970`,offset:4}],mime:`video/mp4`,text_patterns:[],universe:`U0`}},types_count:48,version:`1.0.0`};function ag(e,t){if(!t.hex)return!1;let n=Ar(t.hex.replace(/[^0-9a-fA-F]/g,``)),r=t.offset+n.length;if(e.length<r)return!1;let i=t.mask?Ar(t.mask.replace(/[^0-9a-fA-F]/g,``)):null;for(let r=0;r<n.length;r++){let a=e[t.offset+r];if(i&&r<i.length&&(a&=i[r]),a!==n[r])return!1}return!0}var og=class e{_types=new Map;_extMap=new Map;_magicSignatures=[];_compiledPatterns=[];constructor(e){if(e)for(let t of e)this.registerType(t)}static createDefault(){let t=new e,n=ig.types||{};for(let[e,r]of Object.entries(n)){let n=(r.magic_bytes||[]).map(e=>({offset:e.offset??0,hex:e.hex??``,mask:e.mask,description:e.description})),i={mime:e,extensions:r.extensions||[],universe:r.universe||`U0`,isBinary:!!r.is_binary,category:r.category||`text`,description:r.description||``,magicBytes:n,textPatterns:r.text_patterns||[]};t.registerType(i)}return t}registerType(e){let t=(e.extensions||[]).map(e=>{let t=e.trim().toLowerCase();return t.startsWith(`.`)?t:`.${t}`}),n={...e,extensions:t,universe:e.universe||`U0`,isBinary:!!e.isBinary,category:e.category||`text`,magicBytes:e.magicBytes||[],textPatterns:e.textPatterns||[],priority:e.priority??0};this._types.set(n.mime,n);for(let e of n.extensions)this._extMap.set(e,n.mime);let r=n.magicBytes??[];for(let e of r)this._magicSignatures.push({sig:e,def:n});this._magicSignatures.sort((e,t)=>{let n=e.sig.hex.length;return t.sig.hex.length-n});let i=n.textPatterns??[];for(let e of i)try{let t=new RegExp(e,`m`);this._compiledPatterns.push({pattern:t,def:n})}catch{}}getType(e){return this._types.get(e)}listTypes(){return Array.from(this._types.values())}get typesCount(){return this._types.size}judge(e){let t;t=typeof e==`string`||e instanceof Uint8Array||Buffer.isBuffer(e)?{data:e}:e||{};let n=this._normalizeBytes(t.data),r=this._resolveExtension(t.filename,t.extHint);for(let e of this._types.values())if(e.priority&&e.priority>0&&e.validator)try{let t=e.isBinary?n:new TextDecoder().decode(n);if(e.validator(t))return{mime:e.mime,universe:e.universe||`U0`,isBinary:!!e.isBinary,confidence:1,matchedRule:`programmatic_predicate_high_priority`,extension:e.extensions[0]||r,category:e.category||`text`,metadata:{priority:e.priority,...e.metadata}}}catch{}if(n.length>0){let e=[];for(let{sig:t,def:r}of this._magicSignatures)ag(n,t)&&e.push({sig:t,def:r});if(e.length>0){let t=e[0];if(r){let n=e.find(e=>e.def.extensions.includes(r));n&&(t=n)}else{let n=e.find(e=>!e.def.mime.includes(`+`));n&&(t=n)}let n=t.def.extensions[0]||r;return{mime:t.def.mime,universe:t.def.universe||`U0`,isBinary:!!t.def.isBinary,confidence:.99,matchedRule:`magic_bytes`,extension:n,category:t.def.category||`binary`,metadata:{signatureHex:t.sig.hex,offset:t.sig.offset}}}}let i=this._isBinaryPayload(n);if(r&&this._extMap.has(r)){let e=this._extMap.get(r),t=this._types.get(e),n=t?.universe||`U0`,a=t?.isBinary??i;return{mime:e,universe:n,isBinary:a,confidence:.95,matchedRule:`extension_hint`,extension:r,category:t?.category||(a?`binary`:`text`)}}if(!i&&n.length>0){let e=new TextDecoder().decode(n).trim(),t=this._probeStructuredText(e);if(t){let{mime:e,rule:n,confidence:i}=t,a=this._types.get(e);return{mime:e,universe:a?.universe||`U0`,isBinary:!1,confidence:i,matchedRule:n,extension:a?.extensions[0]||r,category:a?.category||`text`}}for(let{pattern:t,def:n}of this._compiledPatterns)if(t.test(e))return{mime:n.mime,universe:n.universe||`U0`,isBinary:!1,confidence:.95,matchedRule:`text_pattern`,extension:n.extensions[0]||r,category:n.category||`text`}}for(let e of this._types.values())if((e.priority===0||e.priority===void 0)&&e.validator)try{let t=e.isBinary?n:new TextDecoder().decode(n);if(e.validator(t))return{mime:e.mime,universe:e.universe||`U0`,isBinary:!!e.isBinary,confidence:.92,matchedRule:`programmatic_predicate`,extension:e.extensions[0]||r,category:e.category||`text`,metadata:e.metadata}}catch{}return i?{mime:`application/octet-stream`,universe:`U0`,isBinary:!0,confidence:.5,matchedRule:`binary_fallback`,extension:r||`.bin`,category:`binary`}:{mime:`text/plain`,universe:`U0`,isBinary:!1,confidence:.5,matchedRule:`text_fallback`,extension:r||`.txt`,category:`text`}}detectContentType(e,t){let n=this.judge({data:e,extHint:t}),r=(n.extension||``).replace(/^\./,``);return[n.mime,r]}isBinaryContent(e){let t=this._normalizeBytes(e);return this._isBinaryPayload(t)}_normalizeBytes(e){return e?typeof e==`string`?new TextEncoder().encode(e):Buffer.isBuffer(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:new Uint8Array}_resolveExtension(e,t){let n=t||``;if(!n&&e){let t=e.lastIndexOf(`.`);t!==-1&&(n=e.substring(t))}if(n)return n=n.trim().toLowerCase(),n.startsWith(`.`)?n:`.${n}`}_isBinaryPayload(e){if(e.length===0)return!1;let t=Math.min(e.length,4096);for(let n=0;n<t;n++)if(e[n]===0)return!0;let n=0;for(let r=0;r<t;r++){let t=e[r];(t<9||t>13&&t<32||t>127)&&n++}return n/t>.3}_probeStructuredText(e){if(e.startsWith(`{`)&&e.endsWith(`}`)||e.startsWith(`[`)&&e.endsWith(`]`))try{return JSON.parse(e),e.includes(`"mcard_version"`)?{mime:`application/vnd.mcard+json`,rule:`structured_mcard_probe`,confidence:.99}:e.includes(`"pcard_version"`)?{mime:`application/vnd.pcard+json`,rule:`structured_pcard_probe`,confidence:.99}:e.includes(`"vcard_version"`)?{mime:`application/vnd.vcard+json`,rule:`structured_vcard_probe`,confidence:.99}:{mime:`application/json`,rule:`structured_json_probe`,confidence:.98}}catch{}if(e.startsWith(`<?xml`)||e.slice(0,512).toLowerCase().includes(`<svg`))return e.toLowerCase().includes(`<svg`)?{mime:`image/svg+xml`,rule:`structured_svg_probe`,confidence:.96}:{mime:`application/xml`,rule:`structured_xml_probe`,confidence:.92};let t=e.slice(0,512).toLowerCase();return t.includes(`<!doctype html`)||t.includes(`<html`)?{mime:`text/html`,rule:`structured_html_probe`,confidence:.95}:e.startsWith(`---`)&&e.slice(3).includes(`
108
+ ---`)?{mime:`text/markdown`,rule:`markdown_frontmatter_probe`,confidence:.9}:e.includes(`\\documentclass`)||e.includes(`\\begin{tikzpicture}`)||e.includes(`\\begin{document}`)?e.includes(`\\begin{tikzpicture}`)?{mime:`text/x-tikz`,rule:`structured_tikz_probe`,confidence:.95}:{mime:`text/x-tex`,rule:`structured_latex_probe`,confidence:.92}:null}};new TextEncoder;var sg=e({Context:()=>vo});export{Kr as A,ne as B,ga as C,la as D,va as E,Me as F,r as H,Ae as I,j as L,be as M,ye as N,da as O,M as P,A as R,yo as S,_a as T,de as V,Bo as _,Qh as a,xo as b,Zh as c,vh as d,vu as f,R as g,lu as h,og as i,We as j,Hi as k,qh as l,pu as m,$h as n,rg as o,du as p,tg as r,ng as s,eg as t,_h as u,zo as v,ya as w,bo as x,Lo as y,ge as z};