@harperfast/harper 5.3.2 → 5.3.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 (251) hide show
  1. package/bin/cliOperations.ts +3 -3
  2. package/bin/copyDb.ts +4 -3
  3. package/components/DESIGN.md +12 -0
  4. package/components/packageComponent.ts +42 -17
  5. package/config/DESIGN.md +4 -0
  6. package/config/configUtils.ts +8 -8
  7. package/config/parseConfigFile.ts +11 -7
  8. package/dist/bin/cliOperations.js +3 -3
  9. package/dist/bin/cliOperations.js.map +1 -1
  10. package/dist/bin/copyDb.js +3 -3
  11. package/dist/bin/copyDb.js.map +1 -1
  12. package/dist/components/packageComponent.d.ts +9 -7
  13. package/dist/components/packageComponent.js +41 -16
  14. package/dist/components/packageComponent.js.map +1 -1
  15. package/dist/config/configUtils.js +4 -3
  16. package/dist/config/configUtils.js.map +1 -1
  17. package/dist/config/parseConfigFile.d.ts +1 -0
  18. package/dist/config/parseConfigFile.js +7 -3
  19. package/dist/config/parseConfigFile.js.map +1 -1
  20. package/dist/resources/DatabaseTransaction.d.ts +75 -10
  21. package/dist/resources/DatabaseTransaction.js +1080 -277
  22. package/dist/resources/DatabaseTransaction.js.map +1 -1
  23. package/dist/resources/Resource.js +40 -14
  24. package/dist/resources/Resource.js.map +1 -1
  25. package/dist/resources/RocksTransactionLogStore.js +1 -0
  26. package/dist/resources/RocksTransactionLogStore.js.map +1 -1
  27. package/dist/resources/Table.js +16 -2
  28. package/dist/resources/Table.js.map +1 -1
  29. package/dist/resources/analytics/write.js +34 -16
  30. package/dist/resources/analytics/write.js.map +1 -1
  31. package/dist/resources/databases.d.ts +5 -0
  32. package/dist/resources/databases.js +38 -4
  33. package/dist/resources/databases.js.map +1 -1
  34. package/dist/resources/recordLock.d.ts +9 -4
  35. package/dist/resources/recordLock.js +79 -19
  36. package/dist/resources/recordLock.js.map +1 -1
  37. package/dist/server/DurableSubscriptionsSession.d.ts +2 -0
  38. package/dist/server/DurableSubscriptionsSession.js +20 -17
  39. package/dist/server/DurableSubscriptionsSession.js.map +1 -1
  40. package/dist/server/mqtt.js +41 -23
  41. package/dist/server/mqtt.js.map +1 -1
  42. package/dist/server/serverHelpers/NodeAdapterResponse.js +18 -0
  43. package/dist/server/serverHelpers/NodeAdapterResponse.js.map +1 -1
  44. package/dist/utility/npmUtilities.js +18 -7
  45. package/dist/utility/npmUtilities.js.map +1 -1
  46. package/package.json +1 -1
  47. package/resources/DESIGN.md +42 -10
  48. package/resources/DatabaseTransaction.ts +1244 -275
  49. package/resources/Resource.ts +39 -14
  50. package/resources/RocksTransactionLogStore.ts +1 -0
  51. package/resources/Table.ts +24 -2
  52. package/resources/analytics/DESIGN.md +17 -0
  53. package/resources/analytics/write.ts +28 -15
  54. package/resources/databases.ts +40 -4
  55. package/resources/record-locks.md +34 -17
  56. package/resources/recordLock.ts +89 -22
  57. package/server/DESIGN.md +2 -0
  58. package/server/DurableSubscriptionsSession.ts +18 -16
  59. package/server/mqtt.ts +39 -22
  60. package/server/serverHelpers/NodeAdapterResponse.ts +19 -1
  61. package/studio/web/assets/Chat-B-Rd-ft9.js +2100 -0
  62. package/studio/web/assets/FloatingChat-CFypO7kh.js +23 -0
  63. package/studio/web/assets/SearchDialog-BRIyPiBl.js +1 -0
  64. package/studio/web/assets/{abnfDiagram-O67JEVCF-raXE027J.js → abnfDiagram-YUKMZFIV-DPR2lFRk.js} +1 -1
  65. package/studio/web/assets/{apiToken-DNrfij0E.js → apiToken-BraYnzvC.js} +1 -1
  66. package/studio/web/assets/applications-XCds8-ZP.js +296 -0
  67. package/studio/web/assets/architecture-WOLXFQ4H-DtJHIK0_.js +1 -0
  68. package/studio/web/assets/{architectureDiagram-NJMV4G6O-C8_Eet7w.js → architectureDiagram-47P4ROYG-MDymp2dh.js} +3 -3
  69. package/studio/web/assets/authStore-DE1HFvVP.js +3 -0
  70. package/studio/web/assets/{blockDiagram-BEXU5L5S-DR6S5-1D.js → blockDiagram-E7TT5TSB-O5qRgZmd.js} +3 -3
  71. package/studio/web/assets/button-C37w80Uk.js +21 -0
  72. package/studio/web/assets/{c4Diagram-YGBWAQC7-BAfZ1G01.js → c4Diagram-CRA5TL53-BdPORGHo.js} +2 -2
  73. package/studio/web/assets/channel-yCStoq0_.js +1 -0
  74. package/studio/web/assets/{chevron-up-CFxbMGv2.js → chevron-up-DozwrIz-.js} +1 -1
  75. package/studio/web/assets/chunk-2BW5OAIV-DJ-iXJAw.js +10 -0
  76. package/studio/web/assets/{chunk-ZIGJFQKS-Cs8fUn7y.js → chunk-3YJQHVM4-BOgacqS1.js} +2 -2
  77. package/studio/web/assets/{chunk-7PRAP22T-KyqX6x3f.js → chunk-4EA7E6EY-C-7xqUBl.js} +1 -1
  78. package/studio/web/assets/{chunk-GWA4HPMP-DsejB6gA.js → chunk-7TKQ45FW-C3XA1bIN.js} +1 -1
  79. package/studio/web/assets/{chunk-GTNCS2PH-DGHLXyow.js → chunk-AW2ZBBNX-BdvgD1UW.js} +3 -3
  80. package/studio/web/assets/{chunk-5DYCD2WN-BceBfIHT.js → chunk-DBDB3WZW-CKKxIc6F.js} +1 -1
  81. package/studio/web/assets/{chunk-MBY4JIJT-BwSGweQP.js → chunk-E2ZNV5FY-bVefNHvz.js} +3 -3
  82. package/studio/web/assets/chunk-EU5HNXII-BHv2kWp4.js +213 -0
  83. package/studio/web/assets/chunk-FVRAUYC3-BoL_NO6b.js +2 -0
  84. package/studio/web/assets/{chunk-742MDFTN-CIkt8ijt.js → chunk-HJ2JQQFS-N_98oMRS.js} +1 -1
  85. package/studio/web/assets/{chunk-NETBCI7D-C8UnOw_f.js → chunk-HTAEGDNF-BQ1fSjPs.js} +1 -1
  86. package/studio/web/assets/{chunk-WEXAMYUT-BAIhTwyh.js → chunk-KQW6MTUR-qP0QiQAg.js} +1 -1
  87. package/studio/web/assets/chunk-NGNAAXSQ-DqoPQk1a.js +136 -0
  88. package/studio/web/assets/{chunk-UA2S7LBM-BHpEdH8D.js → chunk-NTY3LDVX-CSBFjlJg.js} +1 -1
  89. package/studio/web/assets/chunk-VPRB5NB3-BVHOe9Q-.js +129 -0
  90. package/studio/web/assets/{chunk-7INBJB4K-BpeAXyOi.js → chunk-XC4XBNZT-46uQwtF4.js} +10 -10
  91. package/studio/web/assets/{classDiagram-v2-NBCMYWYE-DmDPkt2u.js → classDiagram-v2-K4WV4PDN-Da0ps1Ui.js} +3 -3
  92. package/studio/web/assets/cn-DpF1PxBT.js +1 -0
  93. package/studio/web/assets/{createLucideIcon-fO5dL7D5.js → createLucideIcon-DLWRoWN-.js} +1 -1
  94. package/studio/web/assets/{cssMode-DBucrQdT.js → cssMode-BY1w91l8.js} +1 -1
  95. package/studio/web/assets/cynefin-EF2NZ3EQ-jQ2eCUaU.js +1 -0
  96. package/studio/web/assets/cynefinDiagram-3GCD6N5R-TNi5iS0E.js +62 -0
  97. package/studio/web/assets/dagre-W4DXFKR2-BnLHmA44.js +4 -0
  98. package/studio/web/assets/{diagram-22UHCM2B-DJCvcaWP.js → diagram-2UJZ2QOL-r_jehhZR.js} +7 -7
  99. package/studio/web/assets/{diagram-3UASUU5V-Du6VKWln.js → diagram-OVF4WLC6-BSUXGVh8.js} +11 -11
  100. package/studio/web/assets/{diagram-CDSNMT55-l5Ga0u-W.js → diagram-PFPMY2P6-BrVedycw.js} +3 -3
  101. package/studio/web/assets/{diagram-MLGK6HIB-CNQY47LA.js → diagram-UMYRVEAY-CBIaakBB.js} +1 -1
  102. package/studio/web/assets/diagram-YEKJPTXX-DFmmDXCl.js +41 -0
  103. package/studio/web/assets/diagram-ZIFT7M5P-CQfOWxOi.js +3 -0
  104. package/studio/web/assets/dist-9lpzt2Hn.js +11 -0
  105. package/studio/web/assets/{ebnfDiagram-ZINNZB2B-5OnkTpfi.js → ebnfDiagram-VR2GEFS7-FXA3Xe6e.js} +1 -1
  106. package/studio/web/assets/{editor-CHpQCuBq.js → editor-D5mpVs1b.js} +1 -1
  107. package/studio/web/assets/elk-IJKZMXRS-CC4gfVRU.js +27 -0
  108. package/studio/web/assets/{erDiagram-OPXOYQCR-CQlCX84D.js → erDiagram-O2IAPWRE-C-BkDTPl.js} +2 -2
  109. package/studio/web/assets/errorText-8xV8WZBt.js +1 -0
  110. package/studio/web/assets/eventmodeling-K75KTNOO-D0dJ_PbR.js +1 -0
  111. package/studio/web/assets/flowDiagram-OXPTDLAJ-C1LEc_Hf.js +1 -0
  112. package/studio/web/assets/{ganttDiagram-FUAMR5RP-bloX3Voy.js → ganttDiagram-R7TSEDQI-85F44BIo.js} +4 -4
  113. package/studio/web/assets/{getAnalytics-C0FHjtdQ.js → getAnalytics-B1xpd4kG.js} +1 -1
  114. package/studio/web/assets/gitGraph-VSP46ZUC-BBmqrmjK.js +1 -0
  115. package/studio/web/assets/gitGraphDiagram-XJZIOB7I-CFY6iMwg.js +106 -0
  116. package/studio/web/assets/graphlib-DS17s2tU.js +1 -0
  117. package/studio/web/assets/{html-B1iA8q38.js → html-DiXKiahz.js} +1 -1
  118. package/studio/web/assets/{htmlMode-CrL3YO5Y.js → htmlMode-DitVJ707.js} +1 -1
  119. package/studio/web/assets/index-CDnn0-PN.css +1 -0
  120. package/studio/web/assets/index-D8kyF6dt.js +833 -0
  121. package/studio/web/assets/index.lazy-DgbjUxLo.js +1 -0
  122. package/studio/web/assets/info-OHQRW6UA-Bs2aEco7.js +1 -0
  123. package/studio/web/assets/{infoDiagram-VRGFBTTK-B0J1132p.js → infoDiagram-5W2HQ5XZ-d6yG1yfZ.js} +1 -1
  124. package/studio/web/assets/invalidateEntityQueries-BkWXiqjz.js +1 -0
  125. package/studio/web/assets/{ishikawaDiagram-OU5B5YK6-BNk0tuQx.js → ishikawaDiagram-K3B6WC7H-CSYz-WRA.js} +2 -2
  126. package/studio/web/assets/{javascript-CXgQMkoa.js → javascript-BBVXeMDm.js} +1 -1
  127. package/studio/web/assets/{journeyDiagram-ZHPQQLJL-Be79RMQM.js → journeyDiagram-COXZFDF6-BDj6Wqcj.js} +3 -3
  128. package/studio/web/assets/{jsonMode-DycqRKOv.js → jsonMode-D85_j2oD.js} +1 -1
  129. package/studio/web/assets/{kanban-definition-PNTS6WVX-4uuoQP9W.js → kanban-definition-P3RFRI5V-C2Bjfbp-.js} +6 -6
  130. package/studio/web/assets/{languageServices-HYHV1wDJ.js → languageServices-U3mWhpRL.js} +1 -1
  131. package/studio/web/assets/{lspLanguageFeatures-CH_6SYiA.js → lspLanguageFeatures-CoymyM3c.js} +1 -1
  132. package/studio/web/assets/{mermaid-parser.core-V1UYMeXV.js → mermaid-parser.core-Ch_T61iL.js} +6 -6
  133. package/studio/web/assets/mermaid.core-BOAgKzo5.js +44 -0
  134. package/studio/web/assets/{mindmap-definition-NLK3R4M7-C70Ctm0J.js → mindmap-definition-LZFPQGKD-DzOapzMM.js} +3 -3
  135. package/studio/web/assets/notifications-CPgEC6ZP.js +1 -0
  136. package/studio/web/assets/notifications-D_VqhHnx.js +1 -0
  137. package/studio/web/assets/operations-D8aaKYty.js +4 -0
  138. package/studio/web/assets/packet-JDAUHWVQ-CGHB_EIE.js +1 -0
  139. package/studio/web/assets/{pegDiagram-GJSIUBJH-d6z1cc7W.js → pegDiagram-BGZESJAR-ADzOIKrz.js} +1 -1
  140. package/studio/web/assets/pie-XZMESJXO-Bijz5Y2o.js +1 -0
  141. package/studio/web/assets/pieDiagram-CAPJLFHJ-VM7fvbwO.js +39 -0
  142. package/studio/web/assets/profile-DM5E6Xls.js +1 -0
  143. package/studio/web/assets/{quadrantDiagram-O4NWA36T-CIF5Qkou.js → quadrantDiagram-GDMTTRAM-Bmza84_j.js} +3 -3
  144. package/studio/web/assets/radar-ABXABTNO-IaC8pB63.js +1 -0
  145. package/studio/web/assets/railroad-I3PHUGI6-CCrSUqeq.js +1 -0
  146. package/studio/web/assets/railroad-abnf-LNEFI6M7-BhobVp-t.js +1 -0
  147. package/studio/web/assets/railroad-ebnf-DWYD2UWJ-OHhGUTEh.js +1 -0
  148. package/studio/web/assets/railroad-peg-JR7BVNR7-FupC3Jcn.js +1 -0
  149. package/studio/web/assets/{railroadDiagram-XR7U4H2S-y3Jv2U6N.js → railroadDiagram-SM67HX2B-CgFGOVI5.js} +1 -1
  150. package/studio/web/assets/regions-WFvXqryO.js +1 -0
  151. package/studio/web/assets/{register-DCN4QUii.js → register-B7DvfAGj.js} +3 -3
  152. package/studio/web/assets/request-ChoMERRk.js +2 -0
  153. package/studio/web/assets/{requirementDiagram-PLB6GJNP-ChINZEmu.js → requirementDiagram-X7JNWC4A-BHoQgkoT.js} +4 -4
  154. package/studio/web/assets/restartGate-D_e93lFE.js +1 -0
  155. package/studio/web/assets/restartUnconfirmed-BqcDZ__Y.js +1 -0
  156. package/studio/web/assets/sankeyDiagram-UM26HJRW-8tFu_oUe.js +40 -0
  157. package/studio/web/assets/sequenceDiagram-ZO4K6R2Y-jryb1rwT.js +169 -0
  158. package/studio/web/assets/setComponentFile-BHk22Rh6.js +1 -0
  159. package/studio/web/assets/setup-wNdpTrVH.js +2 -0
  160. package/studio/web/assets/{stateDiagram-v2-GCMORJYK-Bs8RIb9K.js → stateDiagram-v2-TBUQTH76-CnWE5yFn.js} +2 -2
  161. package/studio/web/assets/status-CYoonm9V.js +61 -0
  162. package/studio/web/assets/{swimlanes-2SLR337P-B52xrf6t.js → swimlanes-N4OXWK64-CBlFzDJn.js} +1 -1
  163. package/studio/web/assets/swimlanesDiagram-K3J5GTZL-DvFLtUPi.js +8 -0
  164. package/studio/web/assets/{timeline-definition-EJHVYXUP-DJSITpQX.js → timeline-definition-YOQAKGHF-CFWqHrqI.js} +4 -4
  165. package/studio/web/assets/{toggleHighContrast-CfAp6Sxb.js → toggleHighContrast-CKEm-P4K.js} +1 -1
  166. package/studio/web/assets/treeView-D4JQ5SDB-CpV9zuVb.js +1 -0
  167. package/studio/web/assets/treemap-SAJKECNS-Bc94Tqiq.js +1 -0
  168. package/studio/web/assets/{tsMode-HZR0bfq4.js → tsMode-Dv35qHmn.js} +1 -1
  169. package/studio/web/assets/{typescript-UMJSfZyF.js → typescript-Bly1EW8o.js} +1 -1
  170. package/studio/web/assets/{useEntityRestURL-B379CS-h.js → useEntityRestURL-Cg3P0MOb.js} +1 -1
  171. package/studio/web/assets/usecaseDiagram-VIAY4XPW-Brf2xP3S.js +328 -0
  172. package/studio/web/assets/{vendor-core-6LhfJlRC.js → vendor-core-PejxhUWQ.js} +1 -1
  173. package/studio/web/assets/vendor-datadog-GjET_Cbn.js +6 -0
  174. package/studio/web/assets/{vendor-react-BOliS0BL.js → vendor-react-DSIx92Ld.js} +1 -1
  175. package/studio/web/assets/vendor-tanstack-C5Y-nrd2.js +2 -0
  176. package/studio/web/assets/vendor-ui-BBWHOEoQ.js +41 -0
  177. package/studio/web/assets/{vennDiagram-UO4OBE2U-DZTsDA4k.js → vennDiagram-BLWOH2XV-XxOyJPq_.js} +3 -3
  178. package/studio/web/assets/wardley-7MLQ67FV-DRW0zuE4.js +1 -0
  179. package/studio/web/assets/{wardleyDiagram-VNRHLVJA-qu_f7Tvl.js → wardleyDiagram-YMQ3BMBF-B3WskJ9W.js} +3 -3
  180. package/studio/web/assets/wasAReleasedBeforeB-D5grAaGM.js +1 -0
  181. package/studio/web/assets/{workers-Bn_0_L1R.js → workers-DVtjrvUa.js} +1 -1
  182. package/studio/web/assets/{xml-CG2N-1r1.js → xml-DjAPbgLN.js} +1 -1
  183. package/studio/web/assets/xychartDiagram-TAQBALBS-D5NV4Env.js +7 -0
  184. package/studio/web/assets/{yaml-68pda6Av.js → yaml-oTUyoJy1.js} +1 -1
  185. package/studio/web/index.html +17 -15
  186. package/utility/npmUtilities.ts +17 -7
  187. package/studio/web/assets/Chat-CrxPD4ph.js +0 -2294
  188. package/studio/web/assets/FloatingChat-EXzoUQ-9.js +0 -23
  189. package/studio/web/assets/SearchDialog-7qRL8Yqx.js +0 -1
  190. package/studio/web/assets/_basePickBy-QJXUw_pr.js +0 -1
  191. package/studio/web/assets/_baseUniq-DR4vVjyC.js +0 -1
  192. package/studio/web/assets/alertDialog-BbWD9Xxa.js +0 -1
  193. package/studio/web/assets/applications-CdqjiSQe.js +0 -296
  194. package/studio/web/assets/architecture-7GRP2DOG-DDmz3hpI.js +0 -1
  195. package/studio/web/assets/arrow-up-D2g_57vT.js +0 -1
  196. package/studio/web/assets/authStore-CJCaADw9.js +0 -3
  197. package/studio/web/assets/button-DWwfgGWI.js +0 -21
  198. package/studio/web/assets/channel-D0AkPjJ8.js +0 -1
  199. package/studio/web/assets/chunk-3FUC2YCW-DuRp-j19.js +0 -2
  200. package/studio/web/assets/chunk-7M6MHVWA-h6WlaTzO.js +0 -213
  201. package/studio/web/assets/chunk-FOHPRMQF-DzxwRta7.js +0 -161
  202. package/studio/web/assets/chunk-O7XYJQB3-CBS3nZYV.js +0 -128
  203. package/studio/web/assets/chunk-Z7XXMR3K-DSHbImdf.js +0 -10
  204. package/studio/web/assets/cn-6T8VranJ.js +0 -1
  205. package/studio/web/assets/cynefin-OW5HDTMX-DIvbXLSj.js +0 -1
  206. package/studio/web/assets/cynefinDiagram-VND7K2PF-BdtaXiCE.js +0 -62
  207. package/studio/web/assets/dagre-6A5THRUB-C7RUWHyz.js +0 -4
  208. package/studio/web/assets/diagram-ATOU4E4O-dxRfeG4B.js +0 -3
  209. package/studio/web/assets/diagram-MPIPVDR6-7prveD1B.js +0 -41
  210. package/studio/web/assets/dist-BrRuMUzt.js +0 -11
  211. package/studio/web/assets/download-Cn6tPG4L.js +0 -1
  212. package/studio/web/assets/elk-276RUBZZ-DxDQPjQT.js +0 -27
  213. package/studio/web/assets/errorText-NpBmvk9I.js +0 -1
  214. package/studio/web/assets/eventmodeling-NTZA5JFV-DONQf5aG.js +0 -1
  215. package/studio/web/assets/flowDiagram-KWPJA3E3-BoZ8_QR1.js +0 -1
  216. package/studio/web/assets/gitGraph-4MIJSDKK-BrXWmJt2.js +0 -1
  217. package/studio/web/assets/gitGraphDiagram-X574FWY7-C2KnnZeY.js +0 -106
  218. package/studio/web/assets/graphlib-C9Tl7QrK.js +0 -1
  219. package/studio/web/assets/index-QLZw6xrU.css +0 -1
  220. package/studio/web/assets/index-qCLyhyah.js +0 -828
  221. package/studio/web/assets/index.lazy-DCx-DxIV.js +0 -2
  222. package/studio/web/assets/info-A6RAGUB7-BhzBHe4U.js +0 -1
  223. package/studio/web/assets/mermaid.core-1PX6R49U.js +0 -44
  224. package/studio/web/assets/notifications-BSObVIY1.js +0 -1
  225. package/studio/web/assets/notifications-DFLXk68b.js +0 -1
  226. package/studio/web/assets/packet-AYTQ26CC-DWbXHx5g.js +0 -1
  227. package/studio/web/assets/pie-WAS4IAKB-DjoTm3yr.js +0 -1
  228. package/studio/web/assets/pieDiagram-5QR66LMP-Dz3RHpDA.js +0 -39
  229. package/studio/web/assets/profile-TBjzOMIy.js +0 -1
  230. package/studio/web/assets/radar-RG4KPBEZ-CVBgjCOj.js +0 -1
  231. package/studio/web/assets/railroad-74A4TZTK-BdhXw10Q.js +0 -1
  232. package/studio/web/assets/railroad-abnf-HS5TGJTU-BcoQPN39.js +0 -1
  233. package/studio/web/assets/railroad-ebnf-LZEXJU2U-B1Lke2JN.js +0 -1
  234. package/studio/web/assets/railroad-peg-WCYAUIDC-D-oJFkiV.js +0 -1
  235. package/studio/web/assets/regions-C4an4H7e.js +0 -1
  236. package/studio/web/assets/restartGate-nHAFLDh-.js +0 -1
  237. package/studio/web/assets/sankeyDiagram-IPEJSGJF-D9AyLce2.js +0 -40
  238. package/studio/web/assets/sequenceDiagram-PO4LG4MO-hfk4aIEm.js +0 -169
  239. package/studio/web/assets/setComponentFile-BrqOM1Zm.js +0 -1
  240. package/studio/web/assets/setup-0v2MCm-E.js +0 -2
  241. package/studio/web/assets/status-DdezofUu.js +0 -61
  242. package/studio/web/assets/swimlanesDiagram-TC7HE7FX-DfN7BAP5.js +0 -8
  243. package/studio/web/assets/tabs-BCTQzoQK.js +0 -1
  244. package/studio/web/assets/treeView-Q6P3EWNA-C-epdxRo.js +0 -1
  245. package/studio/web/assets/treemap-WGGIJYW6-DOVyp_zw.js +0 -1
  246. package/studio/web/assets/usecaseDiagram-POWQR4AR-B6252cbq.js +0 -328
  247. package/studio/web/assets/vendor-datadog-ozKf-pts.js +0 -6
  248. package/studio/web/assets/vendor-tanstack-Bntfka-M.js +0 -2
  249. package/studio/web/assets/vendor-ui-9EYYDgoN.js +0 -41
  250. package/studio/web/assets/wardley-WFR3VGLG-Cfqoe6z4.js +0 -1
  251. package/studio/web/assets/xychartDiagram-PMCCYNJV-UrOKRsmR.js +0 -7
@@ -1,2294 +0,0 @@
1
- import{i as e,t}from"./rolldown-runtime-Dd_uD5pT.js";import{C as n,S as r,_ as i,a,b as o,c as s,f as c,g as l,h as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,v as y,x as b,y as x}from"./vendor-core-6LhfJlRC.js";import{n as S}from"./cn-6T8VranJ.js";import{a as ee}from"./vendor-datadog-ozKf-pts.js";import{r as te}from"./vendor-react-BOliS0BL.js";import{B as ne,R as re,Y as ie,k as ae}from"./vendor-tanstack-Bntfka-M.js";import{n as oe}from"./setSessionStorage-B0bf71m4.js";import{t as se}from"./button-DWwfgGWI.js";import{Rt as ce}from"./vendor-ui-9EYYDgoN.js";import{t as C}from"./createLucideIcon-fO5dL7D5.js";import{n as le,r as ue,t as de}from"./chevron-up-CFxbMGv2.js";import{c as fe,f as pe,h as me,i as he,l as ge,m as _e,p as ve,r as ye,t as be,u as xe}from"./setComponentFile-BrqOM1Zm.js";import{t as Se}from"./localStorageKeys-etzFY_xV.js";import{Ar as Ce,At as we,Bn as Te,Br as Ee,Er as De,Fr as Oe,H as ke,Hr as Ae,Ln as je,Nt as Me,Pr as Ne,Tn as Pe,Ur as Fe,V as Ie,Z as Le,c as Re,d as ze,f as Be,ft as Ve,gt as He,ir as Ue,jt as We,kt as Ge,m as Ke,nn as qe,qr as Je,ut as Ye,vr as Xe,wr as Ze,xr as Qe}from"./index-qCLyhyah.js";import{t as $e}from"./useEntityRestURL-B379CS-h.js";import{n as et,t as tt}from"./FloatingChat-EXzoUQ-9.js";import{n as nt}from"./getAnalytics-C0FHjtdQ.js";var rt={name:`between-horizontal-start`,size:24,node:[[`rect`,{width:`13`,height:`7`,x:`8`,y:`3`,rx:`1`,key:`pkso9a`}],[`path`,{d:`m2 9 3 3-3 3`,key:`1agib5`}],[`rect`,{width:`13`,height:`7`,x:`8`,y:`14`,rx:`1`,key:`1q5fc1`}]],aliases:[`between-horizonal-start`]};rt.node;var it=C(rt),at={name:`book`,size:24,node:[[`path`,{d:`M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20`,key:`k3hazp`}]]};at.node;var ot=C(at),st={name:`chart-area`,size:24,node:[[`path`,{d:`M3 3v16a2 2 0 0 0 2 2h16`,key:`c24i48`}],[`path`,{d:`M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z`,key:`q0gr47`}]],aliases:[`area-chart`]};st.node;var ct=C(st),lt={name:`circle-x`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]],aliases:[`x-circle`]};lt.node;var ut=C(lt),dt={name:`file-pen`,size:24,node:[[`path`,{d:`M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34`,key:`o6klzx`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z`,key:`zhnas1`}]],aliases:[`file-edit`]};dt.node;var ft=C(dt),pt={name:`logs`,size:24,node:[[`path`,{d:`M3 5h1`,key:`1mv5vm`}],[`path`,{d:`M3 12h1`,key:`lp3yf2`}],[`path`,{d:`M3 19h1`,key:`w6f3n9`}],[`path`,{d:`M8 5h1`,key:`1nxr5w`}],[`path`,{d:`M8 12h1`,key:`1con00`}],[`path`,{d:`M8 19h1`,key:`k7p10e`}],[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}]]};pt.node;var mt=C(pt),ht={name:`message-square-heart`,size:24,node:[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7.5 9.5c0 .687.265 1.383.697 1.844l3.009 3.264a1.14 1.14 0 0 0 .407.314 1 1 0 0 0 .783-.004 1.14 1.14 0 0 0 .398-.31l3.008-3.264A2.77 2.77 0 0 0 16.5 9.5 2.5 2.5 0 0 0 12 8a2.5 2.5 0 0 0-4.5 1.5`,key:`1faxuh`}]]};ht.node;var gt=C(ht),_t={name:`send`,size:24,node:[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]};_t.node;var vt=C(_t),yt={name:`user`,size:24,node:[[`path`,{d:`M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2`,key:`975kel`}],[`circle`,{cx:`12`,cy:`7`,r:`4`,key:`17ys0d`}]]};yt.node;var bt=C(yt),xt={name:`wrench`,size:24,node:[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`,key:`1ngwbx`}]]};xt.node;var St=C(xt);async function Ct(){await S.delete(`/Chat/Messages/`)}var w=e(ee(),1),T=te();function wt({setMessages:e}){let[t,n]=(0,w.useState)(!1),r=(0,w.useCallback)(async()=>{if(!t){n(!0);try{await Ct(),e([])}catch(e){console.error(`Failed to clear chat:`,e)}finally{n(!1)}}},[t,e]);return(0,T.jsxs)(`button`,{type:`button`,className:`clear-chat-button gap-1`,onClick:r,disabled:t,title:`Clear chat`,children:[t?(0,T.jsx)(Ne,{className:`animate-spin`,size:18}):(0,T.jsx)(Ze,{size:18}),`Clear`]})}async function Tt(){let{data:e}=await S.get(`/Chat/Messages/`);return e}var Et=`vercel.ai.error`,Dt=Symbol.for(Et),Ot,kt,E=class e extends (kt=Error,Ot=Dt,kt){constructor({name:e,message:t,cause:n}){super(t),this[Ot]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Et)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}},At=`AI_APICallError`,jt=`vercel.ai.error.${At}`,Mt=Symbol.for(jt),Nt,Pt,Ft=class extends (Pt=E,Nt=Mt,Pt){constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:i,responseBody:a,cause:o,isRetryable:s=r!=null&&(r===408||r===409||r===429||r>=500),data:c}){super({name:At,message:e,cause:o}),this[Nt]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=i,this.responseBody=a,this.isRetryable=s,this.data=c}static isInstance(e){return E.hasMarker(e,jt)}},It=`AI_EmptyResponseBodyError`,Lt=`vercel.ai.error.${It}`,Rt=Symbol.for(Lt),zt,Bt,Vt=class extends (Bt=E,zt=Rt,Bt){constructor({message:e=`Empty response body`}={}){super({name:It,message:e}),this[zt]=!0}static isInstance(e){return E.hasMarker(e,Lt)}};function Ht(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.toString():JSON.stringify(e)}var Ut=`AI_InvalidArgumentError`,Wt=`vercel.ai.error.${Ut}`,Gt=Symbol.for(Wt),Kt,qt,Jt=class extends (qt=E,Kt=Gt,qt){constructor({message:e,cause:t,argument:n}){super({name:Ut,message:e,cause:t}),this[Kt]=!0,this.argument=n}static isInstance(e){return E.hasMarker(e,Wt)}},Yt=`AI_JSONParseError`,Xt=`vercel.ai.error.${Yt}`,Zt=Symbol.for(Xt),Qt,$t,en=class extends ($t=E,Qt=Zt,$t){constructor({text:e,cause:t}){super({name:Yt,message:`JSON parsing failed: Text: ${e}.
2
- Error message: ${Ht(t)}`,cause:t}),this[Qt]=!0,this.text=e}static isInstance(e){return E.hasMarker(e,Xt)}},tn=`AI_TypeValidationError`,nn=`vercel.ai.error.${tn}`,rn=Symbol.for(nn),an,on,D=class e extends (on=E,an=rn,on){constructor({value:e,cause:t,context:n}){let r=`Type validation failed`;if(n?.field&&(r+=` for ${n.field}`),n?.entityName||n?.entityId){r+=` (`;let e=[];n.entityName&&e.push(n.entityName),n.entityId&&e.push(`id: "${n.entityId}"`),r+=e.join(`, `),r+=`)`}super({name:tn,message:`${r}: Value: ${JSON.stringify(e)}.
3
- Error message: ${Ht(t)}`,cause:t}),this[an]=!0,this.value=e,this.context=n}static isInstance(e){return E.hasMarker(e,nn)}static wrap({value:t,cause:n,context:r}){return e.isInstance(n)&&n.value===t&&n.context?.field===r?.field&&n.context?.entityName===r?.entityName&&n.context?.entityId===r?.entityId?n:new e({value:t,cause:n,context:r})}},sn=`AI_UnsupportedFunctionalityError`,cn=`vercel.ai.error.${sn}`,ln=Symbol.for(cn),un,dn,fn=class extends (dn=E,un=ln,dn){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:sn,message:t}),this[un]=!0,this.functionality=e}static isInstance(e){return E.hasMarker(e,cn)}},pn=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},mn=10,hn=13,O=32;function gn(e){}function _n(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=gn,onError:n=gn,onRetry:r=gn,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
4
- `)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new pn(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
5
- `,n);for(;r!==-1;){if(n===r){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0,n=r+1,r=e.indexOf(`
6
- `,n);continue}let i=e.charCodeAt(n);if(vn(e,n,i)){let i=e.charCodeAt(n+5)===O?n+6:n+5,a=e.slice(i,r);if(d===0&&e.charCodeAt(r+1)===mn){t({id:l,event:f,data:a}),l=void 0,u=``,f=void 0,n=r+2,r=e.indexOf(`
7
- `,n);continue}u=d===0?a:`${u}
8
- ${a}`,d++}else yn(e,n,i)?f=e.slice(e.charCodeAt(n+6)===O?n+7:n+6,r)||void 0:_(e,n,r);n=r+1,r=e.indexOf(`
9
- `,n)}return e.slice(n)}for(;n<e.length;){let t=e.indexOf(`\r`,n),r=e.indexOf(`
10
- `,n),i=-1;if(t!==-1&&r!==-1?i=t<r?t:r:t===-1?r!==-1&&(i=r):i=t===e.length-1?-1:t,i===-1)break;_(e,n,i),n=i+1,e.charCodeAt(n-1)===hn&&e.charCodeAt(n)===mn&&n++}return e.slice(n)}function _(e,t,n){if(t===n){y();return}let r=e.charCodeAt(t);if(vn(e,t,r)){let r=e.charCodeAt(t+5)===O?t+6:t+5,i=e.slice(r,n);u=d===0?i:`${u}
11
- ${i}`,d++;return}if(yn(e,t,r)){f=e.slice(e.charCodeAt(t+6)===O?t+7:t+6,n)||void 0;return}if(r===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let r=e.slice(e.charCodeAt(t+3)===O?t+4:t+3,n);r.includes(`\0`)||(l=r);return}if(r===58){if(i){let r=e.slice(t,n);i(r.slice(e.charCodeAt(t+1)===O?2:1))}return}let a=e.slice(t,n),o=a.indexOf(`:`);if(o===-1){v(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===O?2:1;v(s,a.slice(o+c),a)}function v(e,t,i){switch(e){case`event`:f=t||void 0;break;case`data`:u=d===0?t:`${u}
12
- ${t}`,d++;break;case`id`:t.includes(`\0`)||(l=t);break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new pn(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new pn(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function b(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:b}}function vn(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function yn(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var bn=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:r}={}){let i;super({start(a){i=_n({onEvent:e=>{a.enqueue(e)},onError(t){typeof e==`function`&&e(t),(e===`terminate`||t.type===`max-buffer-size-exceeded`)&&a.error(t)},onRetry:t,onComment:n,maxBufferSize:r})},transform(e){i.feed(e)}})}};new TextDecoder;var{btoa:xn,atob:Sn}=globalThis;function k(e){if(e==null)return{};let t={};if(e instanceof Headers)e.forEach((e,n)=>{t[n.toLowerCase()]=e});else{Array.isArray(e)||(e=Object.entries(e));for(let[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}var A=({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new Jt({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`},Cn=A();function wn(e){return globalThis.Buffer?.isBuffer(e)??!1}var Tn=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,En=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function Dn(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Tn.test(e)===!1&&En.test(e)===!1?t:On(t)}function On(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&n.constructor!==null&&typeof n.constructor==`object`&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function kn(e){let{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Dn(e)}try{return Dn(e)}finally{Error.stackTraceLimit=t}}function An(e){if(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)){let{additionalProperties:t}=e;e.additionalProperties=t!=null&&typeof t!=`boolean`&&j(t);let{properties:n}=e;if(n!=null)for(let e of Object.keys(n))n[e]=j(n[e])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(j):j(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(j)),e.allOf!=null&&(e.allOf=e.allOf.map(j)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(j));let{definitions:t}=e;if(t!=null)for(let e of Object.keys(t))t[e]=j(t[e]);return e}function j(e){return typeof e==`boolean`?e:An(e)}var jn=Symbol(`Let zodToJsonSchema decide on which parser to use`),Mn={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`},Nn=e=>typeof e==`string`?{...Mn,name:e}:{...Mn,...e};function M(){return{}}function Pn(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==`ZodAny`&&(n.items=I(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&(n.minItems=e.minLength.value),e.maxLength&&(n.maxItems=e.maxLength.value),e.exactLength&&(n.minItems=e.exactLength.value,n.maxItems=e.exactLength.value),n}function Fn(e){let t={type:`integer`,format:`int64`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value}return t}function In(){return{type:`boolean`}}function Ln(e,t){return I(e.type._def,t)}var Rn=(e,t)=>I(e.innerType._def,t);function zn(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(n=>zn(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Bn(e)}}var Bn=e=>{let t={type:`integer`,format:`unix-time`};for(let n of e.checks)switch(n.kind){case`min`:t.minimum=n.value;break;case`max`:t.maximum=n.value}return t};function Vn(e,t){return{...I(e.innerType._def,t),default:e.defaultValue()}}function Hn(e,t){return t.effectStrategy===`input`?I(e.schema._def,t):M()}function Un(e){return{type:`string`,enum:Array.from(e.values)}}var Wn=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Gn(e,t){let n=[I(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),I(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=[];return n.forEach(e=>{if(Wn(e))r.push(...e.allOf);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}r.push(t)}}),r.length?{allOf:r}:void 0}function Kn(e){let t=typeof e.value;return t!==`bigint`&&t!==`number`&&t!==`boolean`&&t!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:{type:t===`bigint`?`integer`:t,const:e.value}}var qn=void 0,N={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(qn===void 0&&(qn=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),qn),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Jn(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value;break;case`max`:n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`email`:switch(t.emailStrategy){case`format:email`:P(n,`email`,r.message,t);break;case`format:idn-email`:P(n,`idn-email`,r.message,t);break;case`pattern:zod`:F(n,N.email,r.message,t)}break;case`url`:P(n,`uri`,r.message,t);break;case`uuid`:P(n,`uuid`,r.message,t);break;case`regex`:F(n,r.regex,r.message,t);break;case`cuid`:F(n,N.cuid,r.message,t);break;case`cuid2`:F(n,N.cuid2,r.message,t);break;case`startsWith`:F(n,RegExp(`^${Yn(r.value,t)}`),r.message,t);break;case`endsWith`:F(n,RegExp(`${Yn(r.value,t)}$`),r.message,t);break;case`datetime`:P(n,`date-time`,r.message,t);break;case`date`:P(n,`date`,r.message,t);break;case`time`:P(n,`time`,r.message,t);break;case`duration`:P(n,`duration`,r.message,t);break;case`length`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`includes`:F(n,RegExp(Yn(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&P(n,`ipv4`,r.message,t),r.version!==`v4`&&P(n,`ipv6`,r.message,t);break;case`base64url`:F(n,N.base64url,r.message,t);break;case`jwt`:F(n,N.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&F(n,N.ipv4Cidr,r.message,t),r.version!==`v4`&&F(n,N.ipv6Cidr,r.message,t);break;case`emoji`:F(n,N.emoji(),r.message,t);break;case`ulid`:F(n,N.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:P(n,`binary`,r.message,t);break;case`contentEncoding:base64`:n.contentEncoding=`base64`;break;case`pattern:zod`:F(n,N.base64,r.message,t)}break;case`nanoid`:F(n,N.nanoid,r.message,t)}return n}function Yn(e,t){return t.patternStrategy===`escape`?Zn(e):e}var Xn=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Zn(e){let t=``;for(let n=0;n<e.length;n++)Xn.has(e[n])||(t+=`\\`),t+=e[n];return t}function P(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function F(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Qn(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Qn(t,r)}function Qn(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
13
- ]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
14
- ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r
15
- `:`[${r[e]}\r
16
- ]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function $n(e,t){let n={type:`object`,additionalProperties:I(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===`ZodString`&&e.keyType._def.checks?.length){let{type:r,...i}=Jn(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===`ZodEnum`)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===`ZodBranded`&&e.keyType._def.type._def.typeName===`ZodString`&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Ln(e.keyType._def,t);return{...n,propertyNames:i}}return n}function er(e,t){return t.mapStrategy===`record`?$n(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[I(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||M(),I(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||M()],minItems:2,maxItems:2}}}function tr(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function nr(){return{not:M()}}function rr(){return{type:`null`}}var ir={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function ar(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in ir&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=ir[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return or(e,t)}var or=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>I(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function sr(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[ir[e.innerType._def.typeName],`null`]};let n=I(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function cr(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value}return t}function lr(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=dr(a),s=I(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});s!==void 0&&(n.properties[e]=s,o||r.push(e))}r.length&&(n.required=r);let a=ur(e,t);return a!==void 0&&(n.additionalProperties=a),n}function ur(e,t){if(e.catchall._def.typeName!==`ZodNever`)return I(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function dr(e){try{return e.isOptional()}catch{return!0}}var fr=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return I(e.innerType._def,t);let n=I(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:M()},n]}:M()},pr=(e,t)=>{if(t.pipeStrategy===`input`)return I(e.in._def,t);if(t.pipeStrategy===`output`)return I(e.out._def,t);let n=I(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,I(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function mr(e,t){return I(e.type._def,t)}function hr(e,t){let n={type:`array`,uniqueItems:!0,items:I(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function gr(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>I(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:I(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>I(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function _r(){return{not:M()}}function vr(){return M()}var yr=(e,t)=>I(e.innerType._def,t),br=(e,t,n)=>{switch(t){case`ZodString`:return Jn(e,n);case`ZodNumber`:return cr(e);case`ZodObject`:return lr(e,n);case`ZodBigInt`:return Fn(e);case`ZodBoolean`:return In();case`ZodDate`:return zn(e,n);case`ZodUndefined`:return _r();case`ZodNull`:return rr();case`ZodArray`:return Pn(e,n);case`ZodUnion`:case`ZodDiscriminatedUnion`:return ar(e,n);case`ZodIntersection`:return Gn(e,n);case`ZodTuple`:return gr(e,n);case`ZodRecord`:return $n(e,n);case`ZodLiteral`:return Kn(e);case`ZodEnum`:return Un(e);case`ZodNativeEnum`:return tr(e);case`ZodNullable`:return sr(e,n);case`ZodOptional`:return fr(e,n);case`ZodMap`:return er(e,n);case`ZodSet`:return hr(e,n);case`ZodLazy`:return()=>e.getter()._def;case`ZodPromise`:return mr(e,n);case`ZodNaN`:case`ZodNever`:return nr();case`ZodEffects`:return Hn(e,n);case`ZodAny`:return M();case`ZodUnknown`:return vr();case`ZodDefault`:return Vn(e,n);case`ZodBranded`:return Ln(e,n);case`ZodReadonly`:return yr(e,n);case`ZodCatch`:return Rn(e,n);case`ZodPipeline`:return pr(e,n);case`ZodFunction`:case`ZodVoid`:case`ZodSymbol`:return;default:return(e=>void 0)(t)}},xr=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function I(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.call(t,e,t,r,n);if(i!==jn)return i}if(r&&!n){let e=Sr(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=br(e,e.typeName,t),o=typeof a==`function`?I(a(),t):a;if(o&&Cr(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Sr=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:xr(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),M()):t.$refStrategy===`seen`?M():void 0}},Cr=(e,t,n)=>(e.description&&(n.description=e.description),n),wr=e=>{let t=Nn(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Tr=(e,t)=>{let n=wr(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:I(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??M()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=I(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??M(),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o);let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return s.$schema=`http://json-schema.org/draft-07/schema#`,s},Er=Symbol.for(`vercel.ai.schema`);function Dr(e){let t;return()=>(t??=e(),t)}function Or(e,{validate:t}={}){return{[Er]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function kr(e){return typeof e==`object`&&!!e&&Er in e&&e[Er]===!0&&`jsonSchema`in e&&`validate`in e}function Ar(e){return e==null?Or({type:`object`,properties:{},additionalProperties:!1}):kr(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?Ir(e):jr(e):e()}function jr(e){return Or(()=>{if(!Mr(e))throw Error(`Standard schema vendor '${e[`~standard`].vendor}' does not support JSON Schema conversion.`);return An(e[`~standard`].jsonSchema.input({target:`draft-07`}))},{validate:async t=>{let n=await e[`~standard`].validate(t);return`value`in n?{success:!0,value:n.value}:{success:!1,error:new D({value:t,cause:n.issues})}}})}function Mr(e){return e[`~standard`].jsonSchema!=null}function Nr(e,t){let n=t?.useReferences??!1;return Or(()=>Tr(e,{$refStrategy:n?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function Pr(e,t){let i=t?.useReferences??!1;return Or(()=>An(n(e,{target:`draft-7`,io:`input`,reused:i?`ref`:`inline`})),{validate:async t=>{let n=await r(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function Fr(e){return`_zod`in e}function Ir(e,t){return Fr(e)?Pr(e,t):Nr(e,t)}async function Lr({value:e,schema:t,context:n}){let r=await Rr({value:e,schema:t,context:n});if(!r.success)throw D.wrap({value:e,cause:r.error,context:n});return r.value}async function Rr({value:e,schema:t,context:n}){let r=Ar(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let t=await r.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:D.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:D.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function L({text:e,schema:t}){try{let n=kn(e);return t==null?{success:!0,value:n,rawValue:n}:await Rr({value:n,schema:t})}catch(t){return{success:!1,error:en.isInstance(t)?t:new en({text:e,cause:t}),rawValue:void 0}}}function zr({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new bn).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await L({text:e,schema:t}))}}))}async function R(e){return typeof e==`function`&&(e=e()),e}new TextDecoder;var Br=Object.defineProperty,Vr=(e,t)=>{for(var n in t)Br(e,n,{get:t[n],enumerable:!0})},Hr=`AI_InvalidArgumentError`,Ur=`vercel.ai.error.${Hr}`,Wr=Symbol.for(Ur),Gr,Kr,z=class extends (Kr=E,Gr=Wr,Kr){constructor({parameter:e,value:t,message:n}){super({name:Hr,message:`Invalid argument for parameter ${e}: ${n}`}),this[Gr]=!0,this.parameter=e,this.value=t}static isInstance(e){return E.hasMarker(e,Ur)}},qr=`AI_NoObjectGeneratedError`,Jr=`vercel.ai.error.${qr}`,Yr=Symbol.for(Jr),Xr,Zr,B=class extends (Zr=E,Xr=Yr,Zr){constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:qr,message:e,cause:t}),this[Xr]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return E.hasMarker(e,Jr)}},Qr=`AI_UIMessageStreamError`,$r=`vercel.ai.error.${Qr}`,ei=Symbol.for($r),ti,ni,V=class extends (ni=E,ti=ei,ni){constructor({chunkType:e,chunkId:t,message:n}){super({name:Qr,message:n}),this[ti]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return E.hasMarker(e,$r)}};function ri({warning:e,provider:t,model:n}){let r=`AI SDK Warning${t!=null&&n!=null?` (${t} / ${n})`:``}:`;switch(e.type){case`unsupported`:{let t=`${r} The feature "${e.feature}" is not supported.`;return e.details&&(t+=` ${e.details}`),t}case`compatibility`:{let t=`${r} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(t+=` ${e.details}`),t}case`deprecated`:return`${r} Deprecated: "${e.setting}". ${e.message}`;case`other`:return`${r} ${e.message}`;default:return`${r} ${JSON.stringify(e,null,2)}`}}var ii=`AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.`,ai=!1;function oi({message:e,type:t}){typeof process<`u`&&typeof process.emitWarning==`function`?process.emitWarning(e,{type:t}):console.warn(e)}var si=e=>{if(e.warnings.length===0)return;let t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t==`function`){t(e);return}ai||(ai=!0,oi({message:ii,type:`Warning`}));for(let t of e.warnings)oi({message:ri({warning:t,provider:e.provider,model:e.model}),type:t.type===`deprecated`?`DeprecationWarning`:`Warning`})}};function ci(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let n={...e};for(let r in t)if(r!==`__proto__`&&r!==`constructor`&&r!==`prototype`&&Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(i===void 0)continue;let a=r in e?e[r]:void 0,o=typeof i==`object`&&!!i&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),s=typeof a==`object`&&!!a&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);n[r]=o&&s?ci(a,i):i}return n}var H={array:m,boolean:_,custom:s,discriminatedUnion:d,enum:v,instanceof:p,lazy:c,literal:h,looseObject:f,never:u,null:g,number:l,object:i,record:y,string:x,union:o,unknown:b},U=H.lazy(()=>H.union([H.null(),H.string(),H.number(),H.boolean(),H.record(H.string(),U.optional()),H.array(U)])),W=H.record(H.string(),H.record(H.string(),U.optional())),li=H.union([H.string(),H.instanceof(Uint8Array),H.instanceof(ArrayBuffer),H.custom(wn,{message:`Must be a Buffer`})]),ui=H.record(H.string(),H.string()),di=H.object({type:H.literal(`text`),text:H.string(),providerOptions:W.optional()}),fi=H.object({type:H.literal(`image`),image:H.union([li,H.instanceof(URL),ui]),mediaType:H.string().optional(),providerOptions:W.optional()}),pi=H.discriminatedUnion(`type`,[H.object({type:H.literal(`data`),data:li}),H.object({type:H.literal(`url`),url:H.instanceof(URL)}),H.object({type:H.literal(`reference`),reference:ui}),H.object({type:H.literal(`text`),text:H.string()})]),mi=H.discriminatedUnion(`type`,[H.object({type:H.literal(`data`),data:li}),H.object({type:H.literal(`url`),url:H.instanceof(URL)})]),hi=H.object({type:H.literal(`file`),data:H.union([pi,li,H.instanceof(URL),ui]),filename:H.string().optional(),mediaType:H.string(),providerOptions:W.optional()}),gi=H.object({type:H.literal(`reasoning`),text:H.string(),providerOptions:W.optional()}),_i=H.object({type:H.literal(`custom`),kind:H.string().transform(e=>e),providerOptions:W.optional()}),vi=H.object({type:H.literal(`reasoning-file`),data:H.union([mi,li,H.instanceof(URL)]),mediaType:H.string(),providerOptions:W.optional()}),yi=H.object({type:H.literal(`tool-call`),toolCallId:H.string(),toolName:H.string(),input:H.unknown(),providerOptions:W.optional(),providerExecuted:H.boolean().optional()}),bi=H.discriminatedUnion(`type`,[H.object({type:H.literal(`text`),value:H.string(),providerOptions:W.optional()}),H.object({type:H.literal(`json`),value:U,providerOptions:W.optional()}),H.object({type:H.literal(`execution-denied`),reason:H.string().optional(),providerOptions:W.optional()}),H.object({type:H.literal(`error-text`),value:H.string(),providerOptions:W.optional()}),H.object({type:H.literal(`error-json`),value:U,providerOptions:W.optional()}),H.object({type:H.literal(`content`),value:H.array(H.union([H.object({type:H.literal(`text`),text:H.string(),providerOptions:W.optional()}),H.object({type:H.literal(`file`),data:pi,mediaType:H.string(),filename:H.string().optional(),providerOptions:W.optional()}),H.object({type:H.literal(`file-data`),data:H.string(),mediaType:H.string(),filename:H.string().optional(),providerOptions:W.optional()}),H.object({type:H.literal(`file-url`),url:H.string(),mediaType:H.string().optional(),providerOptions:W.optional()}),H.object({type:H.literal(`file-id`),fileId:H.union([H.string(),H.record(H.string(),H.string())]),providerOptions:W.optional()}),H.object({type:H.literal(`file-reference`),providerReference:H.record(H.string(),H.string()),providerOptions:W.optional()}),H.object({type:H.literal(`image-data`),data:H.string(),mediaType:H.string(),providerOptions:W.optional()}),H.object({type:H.literal(`image-url`),url:H.string(),providerOptions:W.optional()}),H.object({type:H.literal(`image-file-id`),fileId:H.union([H.string(),H.record(H.string(),H.string())]),providerOptions:W.optional()}),H.object({type:H.literal(`image-file-reference`),providerReference:H.record(H.string(),H.string()),providerOptions:W.optional()}),H.object({type:H.literal(`custom`),providerOptions:W.optional()})]))})]),xi=H.object({type:H.literal(`tool-result`),toolCallId:H.string(),toolName:H.string(),output:bi,providerOptions:W.optional()}),Si=H.object({type:H.literal(`tool-approval-request`),approvalId:H.string(),toolCallId:H.string(),reason:H.string().optional(),isAutomatic:H.boolean().optional(),signature:H.string().optional(),inputSchemaInput:H.unknown().optional()}),Ci=H.object({type:H.literal(`tool-approval-response`),approvalId:H.string(),approved:H.boolean(),reason:H.string().optional()}),wi=H.object({role:H.literal(`system`),content:H.string(),providerOptions:W.optional()}),Ti=H.object({role:H.literal(`user`),content:H.union([H.string(),H.array(H.union([di,fi,hi]))]),providerOptions:W.optional()}),Ei=H.object({role:H.literal(`assistant`),content:H.union([H.string(),H.array(H.union([di,_i,hi,gi,vi,yi,xi,Si]))]),providerOptions:W.optional()}),Di=H.object({role:H.literal(`tool`),content:H.array(H.union([xi,Ci])),providerOptions:W.optional()});H.union([wi,Ti,Ei,Di]),Vr({},{array:()=>Mi,choice:()=>Fi,json:()=>Ii,object:()=>ji,text:()=>Ai});function Oi(e){let t=[`ROOT`],n=-1,r=null,i=0;function a(e){return e>=`0`&&e<=`9`||e>=`A`&&e<=`F`||e>=`a`&&e<=`f`}function o(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`)}}function s(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop()}}function c(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop()}}for(let l=0;l<e.length;l++){let u=e[l];switch(t[t.length-1]){case`ROOT`:o(u,l,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=l,t.pop()}break;case`INSIDE_OBJECT_AFTER_COMMA`:u===`"`&&(t.pop(),t.push(`INSIDE_OBJECT_KEY`));break;case`INSIDE_OBJECT_KEY`:u===`"`&&(t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`));break;case`INSIDE_OBJECT_AFTER_KEY`:u===`:`&&(t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`));break;case`INSIDE_OBJECT_BEFORE_VALUE`:o(u,l,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:s(u,l);break;case`INSIDE_STRING`:switch(u){case`"`:t.pop(),n=l;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=l}break;case`INSIDE_ARRAY_START`:switch(u){case`]`:n=l,t.pop();break;default:n=l,o(u,l,`INSIDE_ARRAY_AFTER_VALUE`)}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(u){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=l,t.pop();break;default:n=l}break;case`INSIDE_ARRAY_AFTER_COMMA`:o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),u===`u`?(i=0,t.push(`INSIDE_STRING_UNICODE_ESCAPE`)):n=l;break;case`INSIDE_STRING_UNICODE_ESCAPE`:a(u)&&(i++,i===4&&(t.pop(),n=l));break;case`INSIDE_NUMBER`:switch(u){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=l;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l);break;default:t.pop()}break;case`INSIDE_LITERAL`:{let i=e.substring(r,l+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?s(u,l):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l)):n=l;break}}}let l=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:l+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:l+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:l+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?l+=`true`.slice(t.length):`false`.startsWith(t)?l+=`false`.slice(t.length):`null`.startsWith(t)&&(l+=`null`.slice(t.length))}}return l}async function ki(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await L({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await L({text:Oi(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var Ai=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),ji=({schema:e,name:t,description:n})=>{let r=Ar(e);return{name:`object`,responseFormat:R(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await L({text:e});if(!n.success)throw new B({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=await Rr({value:n.value,schema:r});if(!i.success)throw new B({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return i.value},async parsePartialOutput({text:e}){let t=await ki(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},Mi=({element:e,minItems:t,maxItems:n,name:r,description:i})=>{if(Ni({name:`minItems`,value:t}),Ni({name:`maxItems`,value:n}),t!=null&&n!=null&&t>n)throw new z({parameter:`minItems`,value:t,message:`minItems must be less than or equal to maxItems`});let a=Ar(e);return{name:`array`,responseFormat:R(a.jsonSchema).then(e=>{let{$schema:a,definitions:o,$defs:s,...c}=e;return{type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,...o!=null&&{definitions:o},...s!=null&&{$defs:s},type:`object`,properties:{elements:{type:`array`,items:c,...t!=null&&{minItems:t},...n!=null&&{maxItems:n}}},required:[`elements`],additionalProperties:!1},...r!=null&&{name:r},...i!=null&&{description:i}}}),async parseCompleteOutput({text:e},r){let i=await L({text:e});if(!i.success)throw new B({message:`No object generated: could not parse the response.`,cause:i.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let o=i.value;if(typeof o!=`object`||!o||!(`elements`in o)||!Array.isArray(o.elements))throw new B({message:`No object generated: response did not match schema.`,cause:new D({value:o,cause:`response must be an object with an elements array`}),text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let s=Pi({value:o.elements,minItems:t,maxItems:n});if(s!=null)throw new B({message:`No object generated: response did not match schema.`,cause:s,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let c=[];for(let t of o.elements){let n=await Rr({value:t,schema:a});if(!n.success)throw new B({message:`No object generated: response did not match schema.`,cause:n.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});c.push(n.value)}return c},async parsePartialOutput({text:e}){let t=await ki(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let e=t.value;if(typeof e!=`object`||!e||!(`elements`in e)||!Array.isArray(e.elements))return;let n=t.state===`repaired-parse`&&e.elements.length>0?e.elements.slice(0,-1):e.elements,r=[];for(let e of n){let t=await Rr({value:e,schema:a});t.success&&r.push(t.value)}return{partial:r}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},r){if(t!=null)for(;e<t.length;e++){if(n!=null&&e>=n){r.error(Pi({value:t,maxItems:n}));return}r.enqueue(t[e])}}})}}};function Ni({name:e,value:t}){if(t!=null){if(!Number.isInteger(t))throw new z({parameter:e,value:t,message:`${e} must be an integer`});if(t<0)throw new z({parameter:e,value:t,message:`${e} must be greater than or equal to 0`})}}function Pi({value:e,minItems:t,maxItems:n}){if(t!=null&&e.length<t)return new D({value:e,cause:`elements array must contain at least ${t} items`});if(n!=null&&e.length>n)return new D({value:e,cause:`elements array must contain at most ${n} items`})}var Fi=({options:e,name:t,description:n})=>({name:`choice`,responseFormat:Promise.resolve({type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{result:{type:`string`,enum:e}},required:[`result`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:t},n){let r=await L({text:t});if(!r.success)throw new B({message:`No object generated: could not parse the response.`,cause:r.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=r.value;if(typeof i!=`object`||!i||!(`result`in i)||typeof i.result!=`string`||!e.includes(i.result))throw new B({message:`No object generated: response did not match schema.`,cause:new D({value:i,cause:`response must be an object that contains a choice value.`}),text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.result},async parsePartialOutput({text:t}){let n=await ki(t);switch(n.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let t=n.value;if(typeof t!=`object`||!t||!(`result`in t)||typeof t.result!=`string`)return;let r=e.filter(e=>e.startsWith(t.result));return n.state===`successful-parse`?r.includes(t.result)?{partial:t.result}:void 0:r.length===1?{partial:r[0]}:void 0}}},createElementStreamTransform(){}}),Ii=({name:e,description:t}={})=>({name:`json`,responseFormat:Promise.resolve({type:`json`,...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:e},t){let n=await L({text:e});if(!n.success)throw new B({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await ki(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return t.value===void 0?void 0:{partial:t.value}}},createElementStreamTransform(){}});new TextEncoder,new TextEncoder,A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),TransformStream;var Li=H.record(H.string(),U.optional()),Ri=Dr(()=>Ir(H.union([H.looseObject({type:H.literal(`text-start`),id:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`text-delta`),id:H.string(),delta:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`text-end`),id:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`error`),errorText:H.string()}),H.looseObject({type:H.literal(`tool-input-start`),toolCallId:H.string(),toolName:H.string(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional(),toolMetadata:Li.optional(),dynamic:H.boolean().optional(),title:H.string().optional()}),H.looseObject({type:H.literal(`tool-input-delta`),toolCallId:H.string(),inputTextDelta:H.string()}),H.looseObject({type:H.literal(`tool-input-available`),toolCallId:H.string(),toolName:H.string(),input:H.unknown(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional(),toolMetadata:Li.optional(),dynamic:H.boolean().optional(),title:H.string().optional()}),H.looseObject({type:H.literal(`tool-input-error`),toolCallId:H.string(),toolName:H.string(),input:H.unknown(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional(),toolMetadata:Li.optional(),dynamic:H.boolean().optional(),errorText:H.string(),title:H.string().optional()}),H.looseObject({type:H.literal(`tool-approval-request`),approvalId:H.string(),toolCallId:H.string(),approvalDescriptor:H.unknown().optional(),inputSchemaInput:H.unknown().optional(),reason:H.string().optional(),isAutomatic:H.boolean().optional(),signature:H.string().optional()}),H.looseObject({type:H.literal(`tool-approval-response`),approvalId:H.string(),approved:H.boolean(),reason:H.string().optional(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`tool-output-available`),toolCallId:H.string(),output:H.unknown(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional(),toolMetadata:Li.optional(),dynamic:H.boolean().optional(),preliminary:H.boolean().optional()}),H.looseObject({type:H.literal(`tool-output-error`),toolCallId:H.string(),errorText:H.string(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional(),toolMetadata:Li.optional(),dynamic:H.boolean().optional()}),H.looseObject({type:H.literal(`tool-output-denied`),toolCallId:H.string()}),H.looseObject({type:H.literal(`reasoning-start`),id:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`reasoning-delta`),id:H.string(),delta:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`reasoning-end`),id:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`custom`),kind:H.string().transform(e=>e),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`source-url`),sourceId:H.string(),url:H.string(),title:H.string().optional(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`source-document`),sourceId:H.string(),mediaType:H.string(),title:H.string(),filename:H.string().optional(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`file`),url:H.string(),mediaType:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`reasoning-file`),url:H.string(),mediaType:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.custom(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:H.string().optional(),data:H.unknown(),transient:H.boolean().optional()}),H.looseObject({type:H.literal(`start-step`)}),H.looseObject({type:H.literal(`finish-step`)}),H.looseObject({type:H.literal(`reset-step`)}),H.looseObject({type:H.literal(`start`),messageId:H.string().optional(),messageMetadata:H.unknown().optional()}),H.looseObject({type:H.literal(`finish`),finishReason:H.enum([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:H.unknown().optional()}),H.looseObject({type:H.literal(`abort`),reason:H.string().optional()}),H.looseObject({type:H.literal(`message-metadata`),messageMetadata:H.unknown()})])));function zi(e){return e.type.startsWith(`data-`)}function G(){return Object.create(null)}function Bi(e){return e.type===`text`}function Vi(e){return e.type.startsWith(`tool-`)}function Hi(e){return e.type===`dynamic-tool`}function K(e){return Vi(e)||Hi(e)}function Ui(e){return e.type.split(`-`).slice(1).join(`-`)}function Wi(e){return Hi(e)?e.toolName:Ui(e)}var Gi={type:`deprecated`,setting:`rawInput in output-error UI message parts`,message:`Use the "input" field instead. The "rawInput" field will be removed in the next major version.`};function Ki(e){e.some(e=>e.parts.some(e=>typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`&&(e.type===`dynamic-tool`||e.type.startsWith(`tool-`))&&`state`in e&&e.state===`output-error`&&Object.prototype.hasOwnProperty.call(e,`rawInput`)&&`rawInput`in e&&e.rawInput!==void 0))&&si({warnings:[Gi]})}function qi({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:G(),activeReasoningParts:G(),partialToolCalls:G()}}function Ji({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:i,onToolCall:a,onData:o}){return e.pipeThrough(new TransformStream({async transform(e,s){await r(async({state:r,write:c})=>{function l(){let e=r.message.parts,t=e.length-1;for(;t>=0&&e[t].type!==`step-start`;)t--;return e.slice(t+1)}function u(){return l().filter(K)}function d(e){let t=u().find(t=>t.toolCallId===e);if(t==null){let n=r.message.parts;for(let r=n.length-1;r>=0;r--){let i=n[r];if(K(i)&&i.toolCallId===e){t=i;break}}}if(t==null)throw new V({chunkType:`tool-invocation`,chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function f(e){let t=r.message.parts.filter(K).find(t=>t.approval?.id===e);if(t==null)throw new V({chunkType:`tool-approval-response`,chunkId:e,message:`No tool invocation found for approval ID "${e}".`});return t}function p(e,t){let n=t??l().find(t=>Vi(t)&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null){if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}}else r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},input:i.input,output:i.output,rawInput:i.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,preliminary:i.preliminary,...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&e.state!==`output-available`&&e.state!==`output-error`?{callProviderMetadata:i.providerMetadata}:{}})}function m(e,t){let n=t??l().find(t=>t.type===`dynamic-tool`&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.toolName=e.toolName,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput??a.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null){if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}}else r.message.parts.push({type:`dynamic-tool`,toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,errorText:i.errorText,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&e.state!==`output-available`&&e.state!==`output-error`?{callProviderMetadata:i.providerMetadata}:{}})}async function h(e){if(e!=null){let n=r.message.metadata==null?e:ci(r.message.metadata,e);t!=null&&await Lr({value:n,schema:t,context:{field:`message.metadata`,entityId:r.message.id}}),r.message.metadata=n}}switch(e.type){case`text-start`:{let t={type:`text`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeTextParts[e.id]=t,r.message.parts.push(t),c();break}case`text-delta`:{let t=r.activeTextParts[e.id];if(t==null)throw new V({chunkType:`text-delta`,chunkId:e.id,message:`Received text-delta for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`text-end`:{let t=r.activeTextParts[e.id];if(t==null)throw new V({chunkType:`text-end`,chunkId:e.id,message:`Received text-end for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});t.state=`done`,t.providerMetadata=e.providerMetadata??t.providerMetadata,delete r.activeTextParts[e.id],c();break}case`custom`:{let t={type:`custom`,kind:e.kind,providerMetadata:e.providerMetadata};r.message.parts.push(t),c();break}case`reasoning-start`:{let t={type:`reasoning`,id:e.id,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),c();break}case`reasoning-delta`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new V({chunkType:`reasoning-delta`,chunkId:e.id,message:`Received reasoning-delta for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`reasoning-end`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new V({chunkType:`reasoning-end`,chunkId:e.id,message:`Received reasoning-end for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});t.providerMetadata=e.providerMetadata??t.providerMetadata,t.state=`done`,delete r.activeReasoningParts[e.id],c();break}case`file`:case`reasoning-file`:r.message.parts.push({type:e.type,mediaType:e.mediaType,url:e.url,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}}),c();break;case`source-url`:r.message.parts.push({type:`source-url`,sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),c();break;case`source-document`:r.message.parts.push({type:`source-document`,sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),c();break;case`tool-input-start`:{let t=l().filter(Vi);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title,toolMetadata:e.toolMetadata},e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}),c();break}case`tool-input-delta`:{let t=r.partialToolCalls[e.toolCallId];if(t==null)throw new V({chunkType:`tool-input-delta`,chunkId:e.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${e.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});t.text+=e.inputTextDelta;let{value:n}=await ki(t.text);t.dynamic?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}):p({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}),c();break}case`tool-input-available`:e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}),c(),a&&!e.providerExecuted&&await a({toolCall:e});break;case`tool-input-error`:{let t=l().filter(K).find(t=>t.toolCallId===e.toolCallId);(t==null?e.dynamic:t.type===`dynamic-tool`)?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}):(p({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}),Ki([r.message])),c();break}case`tool-approval-request`:{let t=d(e.toolCallId);t.state=`approval-requested`,t.approval={id:e.approvalId,...e.approvalDescriptor==null?{}:{descriptor:e.approvalDescriptor},...Object.prototype.hasOwnProperty.call(e,`inputSchemaInput`)?{inputSchemaInput:e.inputSchemaInput}:{},...e.reason==null?{}:{requestReason:e.reason},...e.isAutomatic===!0?{isAutomatic:!0}:{},...e.signature==null?{}:{signature:e.signature}},c();break}case`tool-approval-response`:{let t=f(e.approvalId),n=t.approval==null?{id:e.approvalId}:t.approval;t.state=`approval-responded`,t.approval={...n,id:e.approvalId,approved:e.approved,...e.reason==null?{}:{reason:e.reason}},e.providerExecuted!=null&&(t.providerExecuted=e.providerExecuted),e.providerMetadata!=null&&(t.callProviderMetadata=e.providerMetadata),c();break}case`tool-output-denied`:{let t=d(e.toolCallId);t.state=`output-denied`,c();break}case`tool-output-available`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-available`,input:t.input,output:e.output,preliminary:e.preliminary,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):p({toolCallId:e.toolCallId,toolName:Ui(t),state:`output-available`,input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),c();break}case`tool-output-error`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):p({toolCallId:e.toolCallId,toolName:Ui(t),state:`output-error`,input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),c();break}case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:break;case`reset-step`:{let e=l();r.activeTextParts=G(),r.activeReasoningParts=G(),r.partialToolCalls=G(),e.length>0&&(r.message.parts.splice(r.message.parts.length-e.length,e.length),c());break}case`start`:e.messageId!=null&&(r.message.id=e.messageId),await h(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c({updateStatus:!1});break;case`finish`:e.finishReason!=null&&(r.finishReason=e.finishReason),await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(zi(e)){if(n?.[e.type]!=null){let t=r.message.parts.findIndex(t=>`id`in t&&`data`in t&&t.id===e.id&&t.type===e.type),i=t>=0?t:r.message.parts.length;await Lr({value:e.data,schema:n[e.type],context:{field:`message.parts[${i}].data`,entityName:e.type,entityId:e.id}})}let t=e;if(t.transient){o?.(t);break}let i=t.id==null?void 0:r.message.parts.find(e=>t.type===e.type&&t.id===e.id);i==null?r.message.parts.push(t):i.data=t.data,o?.(t),c()}}s.enqueue(e)})}}))}async function Yi({stream:e,onError:t,abortSignal:n}){let r=e.getReader(),i=()=>{r.cancel().catch(()=>{})};n?.aborted?i():n?.addEventListener(`abort`,i,{once:!0});try{for(;;){let{done:e}=await r.read();if(e)break}}catch(e){t?.(e)}finally{n?.removeEventListener(`abort`,i),r.releaseLock()}}A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),H.record(H.string(),U.optional()),H.record(H.string(),H.string()),A({prefix:`call`,size:24}),A({prefix:`call`,size:24}),new TextEncoder,A({prefix:`call`,size:24}),A({prefix:`aiobj`,size:24});var{atob:Xi}=globalThis,Zi=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(e){n(e)}}),this.processQueue()})}};A({prefix:`aiobj`,size:24}),H.object({token:H.string().refine(e=>e.trim().length>0),url:H.string().refine(e=>{try{let t=new URL(e);return(t.protocol===`ws:`||t.protocol===`wss:`)&&t.hostname!==``}catch{return!1}}),expiresAt:H.number().positive().max(2**53-1).optional(),tools:H.array(H.object({type:H.literal(`function`),name:H.string().min(1),description:H.string().optional(),parameters:H.record(H.string(),H.unknown())})).optional()}),A({prefix:`call`,size:24});async function Qi({response:e,url:t,fallbackMessage:n}){let r=await e.text();return new Ft({message:r||n,url:t,requestBodyValues:void 0,statusCode:e.status,responseBody:r})}async function $i(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new fn({functionality:`FileList`,message:`FileList is not supported in the current environment`});return Promise.all(Array.from(e).map(async e=>{let{name:t,type:n}=e;return{type:`file`,mediaType:n,filename:t,url:await new Promise((t,n)=>{let r=new FileReader;r.onload=e=>{t(e.target?.result)},r.onerror=e=>n(e),r.readAsDataURL(e)})}}))}function ea(e,t){let n=e.search(/[?#]/);return n===-1?`${e}${t}`:`${e.slice(0,n)}${t}${e.slice(n)}`}var ta=class{constructor({api:e=`/api/chat`,credentials:t,headers:n,body:r,fetch:i,prepareSendMessagesRequest:a,prepareReconnectToStreamRequest:o}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=i,this.prepareSendMessagesRequest=a,this.prepareReconnectToStreamRequest=o}async sendMessages({abortSignal:e,...t}){let n=await R(this.body),r=await R(this.headers),i=await R(this.credentials),a={...k(r),...k(t.headers)},o=await this.prepareSendMessagesRequest?.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...n,...t.body},headers:a,credentials:i,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId}),s=o?.api??this.api,c=o?.headers===void 0?a:k(o.headers),l=o?.body===void 0?{...n,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId}:o.body,u=o?.credentials??i,d=await(this.fetch??globalThis.fetch)(s,{method:`POST`,headers:{"content-type":`application/json`,...c},body:JSON.stringify(l),credentials:u,signal:e});if(!d.ok)throw await Qi({response:d,url:s,fallbackMessage:`Failed to fetch the chat response.`});if(!d.body)throw new Vt({message:`The response body is empty.`});return this.processResponseStream(d.body)}async reconnectToStream(e){let t=await R(this.body),n=await R(this.headers),r=await R(this.credentials),i={...k(n),...k(e.headers)},a=await this.prepareReconnectToStreamRequest?.call(this,{api:this.api,id:e.chatId,body:{...t,...e.body},headers:i,credentials:r,requestMetadata:e.metadata}),o=a?.api??ea(this.api,`/${e.chatId}/stream`),s=a?.headers===void 0?i:k(a.headers),c=a?.credentials??r,l=await(this.fetch??globalThis.fetch)(o,{method:`GET`,headers:s,credentials:c,signal:e.abortSignal});if(l.status===204)return null;if(!l.ok)throw await Qi({response:l,url:o,fallbackMessage:`Failed to fetch the chat response.`});if(!l.body)throw new Vt({message:`The response body is empty.`});return this.processResponseStream(l.body)}},na=class extends ta{constructor(e={}){super(e)}processResponseStream(e){return zr({stream:e,schema:Ri}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},ra=class{constructor({generateId:e=Cn,id:t=e(),transport:n=new na,messageMetadataSchema:r,dataPartSchemas:i,state:a,onError:o,onToolCall:s,onFinish:c,onData:l,sendAutomaticallyWhen:u}){this.pendingMessagePreparations=new Set,this.activeResponse=void 0,this.activeResumeRequest=void 0,this.jobExecutor=new Zi,this.sendMessage=async(e,t)=>{if(e==null){let e=this.pendingApprovalMessageId;if(e==null){e=this.lastMessage?.id;for(let t=this.state.messages.length-1;t>=0;t--){let n=this.state.messages[t];if(n.role===`assistant`&&n.parts.some(e=>K(e)&&e.state===`approval-responded`)){e=n.id;break}}}let n=e!=null&&e===this.pendingApprovalMessageId?this.state.messages.findIndex(t=>t.id===e):-1;await this.makeRequestForToolApproval({messageId:e,messageIndex:n,...t});return}let n;if(`text`in e||`files`in e){let t=new AbortController;this.pendingMessagePreparations.add(t);let r;try{r=Array.isArray(e.files)?e.files:await $i(e.files)}finally{this.pendingMessagePreparations.delete(t)}if(t.signal.aborted)return;n={parts:[...r,...`text`in e&&e.text!=null?[{type:`text`,text:e.text}]:[]]}}else n=e;if(e.messageId!=null){let t=this.state.messages.findIndex(t=>t.id===e.messageId);if(t===-1)throw new z({parameter:`message.messageId`,value:e.messageId,message:`message with id ${e.messageId} not found`});if(this.state.messages[t].role!==`user`)throw new z({parameter:`message.messageId`,value:e.messageId,message:`message with id ${e.messageId} is not a user message`});this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{id:e.messageId,...n,role:n.role??`user`,metadata:e.metadata})}else this.state.pushMessage({...n,id:n.id??this.generateId(),role:n.role??`user`,metadata:e.metadata});await this.makeRequest({trigger:`submit-message`,messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{let n=e==null?this.state.messages.length-1:this.state.messages.findIndex(t=>t.id===e);if(n===-1)throw new z({parameter:`messageId`,value:e,message:`message ${e} not found`});this.state.messages=this.state.messages.slice(0,this.messages[n].role===`assistant`?n:n+1),await this.makeRequest({trigger:`regenerate-message`,messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:`resume-stream`,...e})},this.clearError=()=>{this.status===`error`&&(this.state.error=void 0,this.setStatus({status:`ready`}))},this.addToolApprovalResponse=async({id:e,approved:t,reason:n,options:r})=>this.jobExecutor.run(async()=>{let i=this.state.messages,a=r=>K(r)&&r.state===`approval-requested`&&r.approval.id===e?{...r,state:`approval-responded`,approval:{...r.approval,id:e,approved:t,reason:n}}:r,o=i.findIndex(t=>t.parts.some(t=>K(t)&&t.state===`approval-requested`&&t.approval.id===e));if(o!==-1){let e=i[o];this.state.replaceMessage(o,{...e,parts:e.parts.map(a)}),this.pendingApprovalMessageId=e.id}this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(a)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{if(e){let e=o===-1?this.lastMessage?.id:i[o].id;this.makeRequestForToolApproval({messageId:e,messageIndex:o,...r})}})}),this.addToolOutput=async({state:e=`output-available`,toolCallId:t,output:n,errorText:r,options:i})=>this.jobExecutor.run(async()=>{let a=this.state.messages,o=a[a.length-1],s=i=>K(i)&&i.toolCallId===t?{...i,state:e,output:n,errorText:r}:i;this.state.replaceMessage(a.length-1,{...o,parts:o.parts.map(s)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(s)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...i})})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var e,t;for(let e of this.pendingMessagePreparations)e.abort();(e=this.activeResumeRequest)==null||e.abortController.abort(),(t=this.activeResponse)==null||t.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=i,this.state=a,this.onError=o,this.onToolCall=s,this.onFinish=c,this.onData=l,this.sendAutomaticallyWhen=u}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async shouldSendAutomatically(){if(!this.sendAutomaticallyWhen)return!1;let e=this.sendAutomaticallyWhen({messages:this.state.messages});return e&&typeof e==`object`&&`then`in e?await e:e}async makeRequestForToolApproval({messageId:e,messageIndex:t,...n}){let r=e!=null&&e===this.pendingApprovalMessageId;r&&(this.pendingApprovalMessageId=void 0),await this.makeRequest({trigger:`submit-message`,messageId:e,...n}),r&&this.status===`error`&&this.pendingApprovalMessageId==null&&(this.pendingApprovalMessageId=this.state.messages[t]?.id??e)}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:i}){var a,o;let s=new AbortController,c=e===`resume-stream`?{abortController:s}:void 0;c&&((a=this.activeResumeRequest)==null||a.abortController.abort(),this.activeResumeRequest=c);let l=()=>c==null||this.activeResumeRequest===c,u=()=>{this.activeResumeRequest===c&&(this.activeResumeRequest=void 0)},d;if(e===`resume-stream`)try{let e=await this.transport.reconnectToStream({chatId:this.id,abortSignal:s.signal,metadata:t,headers:n,body:r});if(s.signal.aborted||!l()){await e?.cancel().catch(()=>{}),l()&&this.setStatus({status:`ready`}),u();return}if(e==null){this.setStatus({status:`ready`}),u();return}d=e}catch(e){if(s.signal.aborted||e.name===`AbortError`){l()&&this.setStatus({status:`ready`}),u();return}if(!l())return;this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e}),u();return}this.setStatus({status:`submitted`,error:void 0});let f=this.lastMessage,p=e===`submit-message`&&i!=null?this.state.messages.findIndex(e=>e.id===i):this.state.messages.length-1,m=p===-1?f:this.state.messages[p],h=p!==-1&&p<this.state.messages.length-1&&m?.role===`assistant`,g=!1,_=!1,v=!1,y;try{let a={state:qi({lastMessage:e===`resume-stream`||e===`regenerate-message`?void 0:this.state.snapshot(m),messageId:this.generateId()}),abortController:s};y=a,a.abortController.signal.addEventListener(`abort`,()=>{g=!0}),this.activeResponse=a;let o;if(o=e===`resume-stream`?d:await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:a.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:i}),await Yi({stream:Ji({stream:o,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:e=>this.jobExecutor.run(()=>a.abortController.signal.aborted?Promise.resolve():e({state:a.state,write:({updateStatus:e=!0}={})=>{a.abortController.signal.aborted||(e&&this.setStatus({status:`streaming`}),h?this.state.replaceMessage(p,a.state.message):a.state.message.id===this.lastMessage?.id?this.state.replaceMessage(this.state.messages.length-1,a.state.message):this.state.pushMessage(a.state.message))}})),onError:e=>{throw e}}),abortSignal:a.abortController.signal,onError:e=>{throw e}}),g)return l()&&this.setStatus({status:`ready`}),null;l()&&this.setStatus({status:`ready`})}catch(e){if(g||e.name===`AbortError`)return g=!0,l()&&this.setStatus({status:`ready`}),null;if(!l())return null;v=!0,e instanceof TypeError&&(e.message.toLowerCase().includes(`fetch`)||e.message.toLowerCase().includes(`network`))&&(_=!0),this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e})}finally{try{y&&((o=this.onFinish)==null||o.call(this,{message:y.state.message,messages:this.state.messages,isAbort:g,isDisconnect:_,isError:v,finishReason:y.state.finishReason}))}finally{this.activeResponse===y&&(this.activeResponse=void 0),u()}}!v&&await this.shouldSendAutomatically()&&await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,metadata:t,headers:n,body:r})}};function ia({messages:e}){let t=e[e.length-1];if(!t||t.role!==`assistant`)return!1;let n=t.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=t.parts.slice(n+1).filter(K).filter(e=>!e.providerExecuted);return r.length>0&&r.every(e=>e.state===`output-available`&&e.preliminary!==!0||e.state===`output-error`)}function aa(e){return new na({api:Pe(`/`,`Chat/Messages/`),credentials:`include`,body:{orgId:e}})}var oa=e(t(((e,t)=>{function n(e,t){if(typeof e!=`function`)throw TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...i){clearTimeout(n);let a=Date.now(),o=t-(a-r);o<=0?(r=a,e.apply(this,i)):n=setTimeout(()=>{r=Date.now(),e.apply(this,i)},o)}}t.exports=n}))(),1),sa=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},q=(e,t,n)=>(sa(e,t,`read from private field`),n?n.call(e):t.get(e)),J=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},Y=(e,t,n,r)=>(sa(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n);function ca(e,t){return t==null?e:(0,oa.default)(e,t)}function la(e){return Array.isArray(e)?[...e]:typeof e==`object`&&e&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)?{...e}:e}var X,ua,da,Z,fa,pa,Q,ma,ha,ga=class{constructor(e=[]){J(this,X,void 0),J(this,ua,`ready`),J(this,da,void 0),J(this,Z,new Set),J(this,fa,new Set),J(this,pa,new Set),this.pushMessage=e=>{Y(this,X,q(this,X).concat(e)),q(this,Q).call(this)},this.popMessage=()=>{Y(this,X,q(this,X).slice(0,-1)),q(this,Q).call(this)},this.replaceMessage=(e,t)=>{Y(this,X,[...q(this,X).slice(0,e),this.snapshot(t),...q(this,X).slice(e+1)]),q(this,Q).call(this)},this.snapshot=e=>{if(typeof e!=`object`||!e||!(`parts`in e)||!Array.isArray(e.parts))return e;let t=e,n={...t,parts:t.parts.map(e=>({...e}))};return`metadata`in t&&(n.metadata=la(t.metadata)),n},this[`~registerMessagesCallback`]=(e,t)=>{let n=t?ca(e,t):e;return q(this,Z).add(n),()=>{q(this,Z).delete(n)}},this[`~registerStatusCallback`]=e=>(q(this,fa).add(e),()=>{q(this,fa).delete(e)}),this[`~registerErrorCallback`]=e=>(q(this,pa).add(e),()=>{q(this,pa).delete(e)}),J(this,Q,()=>{q(this,Z).forEach(e=>e())}),J(this,ma,()=>{q(this,fa).forEach(e=>e())}),J(this,ha,()=>{q(this,pa).forEach(e=>e())}),Y(this,X,e)}get status(){return q(this,ua)}set status(e){Y(this,ua,e),q(this,ma).call(this)}get error(){return q(this,da)}set error(e){Y(this,da,e),q(this,ha).call(this)}get messages(){return q(this,X)}set messages(e){Y(this,X,[...e]),q(this,Q).call(this)}};X=new WeakMap,ua=new WeakMap,da=new WeakMap,Z=new WeakMap,fa=new WeakMap,pa=new WeakMap,Q=new WeakMap,ma=new WeakMap,ha=new WeakMap;var $,_a=class extends ra{constructor({messages:e,...t}){let n=new ga(e);super({...t,state:n}),J(this,$,void 0),this[`~registerMessagesCallback`]=(e,t)=>q(this,$)[`~registerMessagesCallback`](e,t),this[`~registerStatusCallback`]=e=>q(this,$)[`~registerStatusCallback`](e),this[`~registerErrorCallback`]=e=>q(this,$)[`~registerErrorCallback`](e),Y(this,$,n)}};$=new WeakMap;function va({throttle:e,experimental_throttle:t,resume:n=!1,...r}={}){let i=e??t,a=(0,w.useRef)({});`chat`in r||(a.current={onToolCall:r.onToolCall,onData:r.onData,onFinish:r.onFinish,onError:r.onError,sendAutomaticallyWhen:r.sendAutomaticallyWhen,transport:r.transport});let o,s=()=>a.current.transport??(o??=new na),c={...r,transport:{sendMessages:e=>s().sendMessages(e),reconnectToStream:e=>s().reconnectToStream(e)},onToolCall:e=>{var t;return(t=a.current).onToolCall?.call(t,e)},onData:e=>{var t;return(t=a.current).onData?.call(t,e)},onFinish:e=>{var t;return(t=a.current).onFinish?.call(t,e)},onError:e=>{var t;return(t=a.current).onError?.call(t,e)},sendAutomaticallyWhen:e=>{var t;return(t=a.current).sendAutomaticallyWhen?.call(t,e)??!1}},l=`chat`in r?r.chat:r.id,{chat:u,isExternallyManaged:d}=(0,w.useMemo)(()=>({chat:`chat`in r?r.chat:new _a(c),isExternallyManaged:`chat`in r}),[l]);(0,w.useEffect)(()=>{if(!d)return()=>{u.stop()}},[u,d]);let f=(0,w.useMemo)(()=>({messages:u.messages}),[u]),p=(0,w.useCallback)(e=>{let t=!0,n=u[`~registerMessagesCallback`](()=>{t&&(f.messages=u.messages,e())},i);return f.messages=u.messages,()=>{t=!1,n()}},[u,f,i]),m=(0,w.useCallback)(()=>f.messages,[f]),h=(0,w.useSyncExternalStore)(p,m,m),g=(0,w.useCallback)(e=>u[`~registerStatusCallback`](()=>{(u.status===`ready`||u.status===`error`)&&(f.messages=u.messages),e()}),[u,f]),_=(0,w.useCallback)(()=>u.status,[u]),v=(0,w.useSyncExternalStore)(g,_,_),y=(0,w.useSyncExternalStore)(u[`~registerErrorCallback`],()=>u.error,()=>u.error),b=(0,w.useCallback)(e=>{typeof e==`function`&&(e=e(u.messages)),u.messages=e},[u]);return(0,w.useEffect)(()=>{n&&u.resumeStream()},[n,u]),{id:u.id,messages:h,setMessages:b,sendMessage:u.sendMessage,regenerate:u.regenerate,clearError:u.clearError,stop:u.stop,error:y,resumeStream:u.resumeStream,status:v,addToolResult:u.addToolOutput,addToolOutput:u.addToolOutput,addToolApprovalResponse:u.addToolApprovalResponse}}function ya({input:e,setInput:t,onSubmit:n,disabled:r,autoFocus:i}){let a=(0,w.useRef)(null);return(0,w.useEffect)(()=>{i&&!r&&a.current?.focus()},[i,r]),(0,T.jsxs)(`form`,{onSubmit:n,className:`input-area`,children:[(0,T.jsx)(`input`,{ref:a,value:e,onChange:e=>t(e.target.value),placeholder:`Type a message...`,disabled:r}),(0,T.jsx)(`button`,{type:`submit`,disabled:r||!e.trim(),children:(0,T.jsx)(vt,{size:18})})]})}function ba(){return(0,T.jsxs)(`div`,{className:`loading-state`,children:[(0,T.jsx)(Ne,{className:`animate-spin`,size:24}),(0,T.jsx)(`p`,{children:`Loading conversation...`})]})}var xa={name:`collectFeedback`,description:`Collects feedback from the user by fetching a link to a pre-populated GitHub Discussion. Use this if the user lets us know we did something well, or if the user seems frustrated, or wants to report a bug.`,inputSchema:i({feedbackSummary:x().describe(`A brief summary of the feedback, used as the discussion title.`),feedbackDetails:x().describe(`Detailed feedback from the user or agent observation.`),recap:x().describe(`A sanitized recap of what the agent and user did together and if it was successful. No sensitive information.`)})};async function Sa({input:{feedbackSummary:e,feedbackDetails:t,recap:n}}){let r=e,i=`${t}\n\n${n}`;return{success:!0,url:`https://github.com/HarperFast/harper-agent/discussions/new?category=usage-feedback&title=${encodeURIComponent(r)}&body=${encodeURIComponent(i)}`,message:`Feedback URL created! Ask the user to open it in their browser, and they will be brought to a form to approve the details of the feedback.`}}var Ca={...xa,icon:gt,execute:Sa},wa={name:`createApp`,description:`Create a new Harper app with the specified name and template type.`,inputSchema:i({name:x().trim(),type:v(ve)})};async function Ta({input:{name:e,type:t},instanceClientParams:n,baseURL:r}){let i=qe(e),a=ge(pe,`id`,t);if(!a)return{success:!1,message:`Error: Invalid template type, ${t}, please choose from: ${pe.map(e=>e.id).join(`, `)}`};let o=ce.loading(`Creating from template...`,{description:`This may take a bit.`,duration:3e5});try{await xe({...n,project:i,template:a.npm||a.githubUrl})}catch(e){return{success:!1,message:`Error: ${e}`}}Me(`ReloadApplicationRootEntries`,!0),ce.loading(`Created successfully!`,{description:`${i} created! Restarting the HTTP service...`,id:o,duration:3e5});try{await He({...n,operation:`restart_service`,replicated:n.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return ce.success(`Created successfully!`,{description:`${i} created!`,id:o,duration:5e3}),{success:!0,message:`App "${i}" created successfully.`,webURL:r}}var Ea={...wa,icon:Oe,execute:Ta,requiresApproval:!0},Da={name:`deleteTableRecords`,description:`Deletes records in a particular table in a particular database on the server by their primary keys.`,inputSchema:i({database:x().trim(),table:x().trim(),primaryKeys:m(x())})};async function Oa({input:{database:e,table:t,primaryKeys:n},instanceClientParams:r,params:i}){try{let a=await Be({...r,databaseName:e,tableName:t,hashValues:n}),{databaseName:o,tableName:s}=i;return await Xe.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ka={...Da,icon:it,execute:Oa,requiresApproval:!0},Aa={name:`dropComponentFile`,description:`Drops a component file by its full path (which was returned by getComponents)`,inputSchema:i({path:x().trim()})};async function ja({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await fe({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ma={...Aa,icon:Ze,execute:ja,requiresApproval:!0},Na={name:`getAnalytics`,description:`Retrieves analytics metrics for the server, such as CPU usage or database operations (reads, writes, messages).`,inputSchema:i({metricName:x().describe(`The name of the metric to retrieve.`),startTime:l().describe(`The start of the time range for the metric, in milliseconds since the Unix epoch.`),endTime:l().describe(`The end of the time range for the metric, in milliseconds since the Unix epoch.`)})};async function Pa({input:e,instanceClientParams:t}){try{let{metricName:n,startTime:r,endTime:i}=e;return{success:!0,data:await nt({metric:n,startTime:r,endTime:i,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var Fa={...Na,icon:ct,execute:Pa},Ia={name:`getComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:i({path:x().trim()})};async function La({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await Ke({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ra={...Ia,icon:me,execute:La},za={name:`getComponents`,description:`Retrieves a tree of all the component (files and folders) names and sizes stored on the server.`,inputSchema:i({})};async function Ba({instanceClientParams:e}){try{let t=await Ve(e),{rootEntries:n}=ye(t.entries);return{success:!0,items:he(n).items}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Va={...za,icon:_e,execute:Ba},Ha={name:`getDescribeAll`,description:`Retrieves a map of the names of databases and their tables stored on the server.`,inputSchema:i({})};async function Ua({instanceClientParams:e}){try{return{success:!0,map:await Ye(e)}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Wa={...Ha,icon:Fe,execute:Ua},Ga={name:`getDescribeTable`,description:`Returns the schema metadata describing a particular table in a particular database on the server.`,inputSchema:i({database:x().trim(),table:x().trim()})};async function Ka({input:{database:e,table:t},instanceClientParams:n}){try{return{success:!0,data:await Ie({...n,databaseName:e,tableName:t})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var qa={...Ga,icon:De,execute:Ka},Ja={name:`getUserContext`,description:`Retrieves the context of what the user is looking at on their screen, such as the current page, the file they are viewing, the database and table visible to them, that sort of thing.`,inputSchema:i({})};async function Ya({instanceClientParams:e,params:t}){let n=je();if(n.includes(`/databases`)){let{databaseName:e,tableName:n}=t;return{success:!0,description:`viewing the database`,data:{databaseName:e,tableName:n}}}if(n.endsWith(`/apis`))return{success:!0,description:`viewing the APIs`};if(n.endsWith(`/status`))return{success:!0,description:`viewing the status graphs`};if(n.endsWith(`/logs`))return{success:!0,description:`viewing the logs`};if(n.includes(`/config/`))return{success:!0,description:`viewing the configuration pages`};let r=oe(`FileFocused/${e.entityId}`,void 0),i=oe(`FolderOpened/${e.entityId}`,[]),a=oe(`FileSelected/${e.entityId}`,[]);return r?{success:!0,description:`editing application files`,data:{openedPath:r,expandedItems:i,selectedItems:a}}:{success:!0,description:n}}var Xa={...Ja,icon:bt,execute:Ya},Za={name:`insertTableRecords`,description:`Inserts one or more records into a particular table in a particular database on the server.`,inputSchema:i({database:x().trim(),table:x().trim(),records:m(a())})};async function Qa({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await Le({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Xe.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var $a={...Za,icon:it,execute:Qa,requiresApproval:!0},eo={name:`listAnalyticsMetrics`,description:`Lists the available analytics metric names available for calling getAnalytics upon.`,inputSchema:i({metricTypes:v([`builtin`,`custom`]),customWindowMS:l().optional().describe(`Default to one week time window for finding custom metrics.`)})};async function to({metricTypes:e,customWindowMS:t,instanceParams:n}){let{data:r}=await n.instanceClient.post(`/`,{operation:`list_analytics_metrics`,metricTypes:e,customWindowMS:t});return r}async function no({input:e,instanceClientParams:t}){try{let{metricTypes:n,customWindowMS:r}=e;return{success:!0,metricNames:await to({metricTypes:n,customWindowMS:r,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var ro={...eo,icon:ct,execute:no},io=[`adding-tables-with-schemas`,`automatic-apis`,`caching`,`checking-authentication`,`creating-a-fabric-account-and-cluster`,`creating-harper-apps`,`custom-resources`,`defining-relationships`,`delegating-to-the-built-in-agent`,`deploying-to-harper-fabric`,`extending-tables`,`handling-binary-data`,`load-env`,`logging`,`programmatic-table-requests`,`querying-rest-apis`,`real-time-apps`,`schema-design-tooling`,`serving-web-content`,`typescript-type-stripping`,`using-blob-datatype`,`v5-upgrade`,`vector-indexing`],ao={"adding-tables-with-schemas":"---\nname: adding-tables-with-schemas\ndescription: Guidelines for adding tables to a Harper database using GraphQL schemas.\nmetadata:\n mode: synthesized\n---\n\n# Adding Tables with Schemas\n\nInstructions for the agent to follow when adding tables to a Harper database.\n\n## When to Use\n\nUse this skill when you need to define new data structures or modify existing ones in a Harper database.\n\n## How It Works\n\n1. **Create Dedicated Schema Files**: Prefer having a dedicated schema `.graphql` file for each table. Check the `config.yaml` file under `graphqlSchema.files` to see how it's configured. It typically accepts wildcards (e.g., `schemas/*.graphql`), but may be configured to point at a single file.\n2. **Use Directives**: All available directives for defining your schema are defined in `node_modules/harper/schema.graphql`. Common directives include `@table`, `@export`, `@primaryKey`, `@indexed`, and `@relationship`.\n3. **Define Relationships**: Link tables together using the `@relationship` directive. For more details, see the [Defining Relationships](defining-relationships.md) skill.\n4. **Enable Automatic APIs**: If you add `@table @export` to a schema type, Harper automatically sets up REST and WebSocket APIs for basic CRUD operations against that table. **Important**: REST endpoints also require `rest: true` in `config.yaml` — without it, `@export`ed tables will not respond to HTTP requests. For a detailed list of available endpoints and how to use them, see the [Automatic REST APIs](automatic-apis.md) skill.\n - `GET /{TableName}`: Describes the resource itself — table, database, and declared attributes. No trailing slash.\n - `GET /{TableName}/`: Lists all records (supports filtering, sorting, and pagination via query parameters). See the [Querying REST APIs](querying-rest-apis.md) skill for details.\n - `GET /{TableName}/{id}`: Retrieves a single record by its primary key.\n - `POST /{TableName}/`: Creates a record and returns `201` with the Harper-assigned primary key in the `Location` response header (the bare key, not a URL). **The trailing slash is required** — `POST /{TableName}` returns `404`, and `POST /{TableName}/{id}` returns `405`.\n - `PUT /{TableName}/{id}`: Creates **or replaces** the record at `{id}` (upsert). **Properties omitted from the body are removed** — send the complete record, or use `PATCH` to change a subset. Three exceptions survive the replacement: an `@updatedTime` attribute is re-stamped with the time of the write, a `@createdTime` attribute keeps its original value, and the primary key is forced to match the `{id}` in the URL, so a mismatched key in the body cannot create a second record.\n - `PATCH /{TableName}/{id}`: Merges the request body into the existing record, preserving unspecified properties. The merge is **shallow** — a nested object in the body replaces the stored one wholesale rather than being deep-merged.\n - `DELETE /{TableName}/{id}`: Deletes a single record by its primary key.\n - `DELETE /{TableName}/`: Deletes every record matching the query parameters. **With no query parameters it matches — and deletes — every record in the table.** Always pass a filter unless emptying the table is the intent.\n5. **Consider Table Extensions**: If you are going to [extend the table](./extending-tables.md) in your resources, then do not `@export` the table from the schema.\n\n## Examples\n\nIn a hypothetical `schemas/ExamplePerson.graphql`:\n\n```graphql\ntype ExamplePerson @table @export {\n id: ID @primaryKey\n name: String\n tag: String @indexed\n}\n```\n","automatic-apis":`---
17
- name: automatic-apis
18
- description: How to use Harper's automatically generated REST and WebSocket APIs.
19
- metadata:
20
- mode: generate
21
- sources:
22
- - reference/v5/rest/overview.md#How the REST Interface Works
23
- - reference/v5/rest/overview.md#Configuration
24
- - reference/v5/rest/overview.md#Tables and Their Automatic Endpoints
25
- - reference/v5/rest/overview.md#URL Structure
26
- - reference/v5/rest/overview.md#HTTP Methods
27
- - reference/v5/rest/overview.md#Content Types
28
- - reference/v5/rest/overview.md#OpenAPI
29
- - reference/v5/rest/websockets.md
30
- sourceCommit: 677ad213d67822e109c83619e181ca23a59823db
31
- inputHash: a9356e92dd3dc106
32
- ---
33
-
34
- # Automatic APIs
35
-
36
- Instructions for the agent to follow when using Harper's automatically generated REST and WebSocket APIs for exported tables and resources.
37
-
38
- ## When to Use
39
-
40
- Apply this rule when enabling HTTP REST endpoints or WebSocket subscriptions for Harper tables without writing custom handler code. Use it whenever a schema type needs to be served over HTTP, when configuring real-time subscriptions, or when setting up conditional caching behavior for REST responses.
41
-
42
- ## How It Works
43
-
44
- 1. **Enable REST in \`config.yaml\`**: Add \`rest: true\` to the application configuration file. This registers REST endpoints and, by default, WebSocket subscriptions for all exported resources.
45
-
46
- \`\`\`yaml
47
- rest: true
48
- \`\`\`
49
-
50
- To configure options explicitly:
51
-
52
- \`\`\`yaml
53
- rest:
54
- lastModified: true # enables Last-Modified response header support
55
- webSocket: false # disables automatic WebSocket support (enabled by default)
56
- \`\`\`
57
-
58
- 2. **Export the table in the schema**: Add \`@export\` to the type definition. Without \`@export\`, Harper registers no REST route and callers receive \`404\`. Without \`rest: true\`, even an exported table does not respond to HTTP requests. Both are required.
59
-
60
- \`\`\`graphql
61
- type Product @table @export {
62
- id: Long @primaryKey
63
- name: String
64
- price: Float
65
- }
66
- \`\`\`
67
-
68
- Reference the schema file in \`config.yaml\`:
69
-
70
- \`\`\`yaml
71
- graphqlSchema:
72
- files: schema.graphql
73
- rest: true
74
- \`\`\`
75
-
76
- 3. **Use the automatically registered endpoints**: Harper serves the following endpoints on the application HTTP server port (default \`9926\`) with no route definitions or handler code required.
77
-
78
- | Endpoint | Description |
79
- | ---------------------------- | --------------------------------------------------------------------------- |
80
- | \`GET /Product\` | Returns resource description (table name, database, attributes) |
81
- | \`GET /Product/\` | Returns the record collection; append query parameters to filter |
82
- | \`GET /Product/{id}\` | Returns a single record by primary key; \`404\` if not found |
83
- | \`GET /Product/{id}.property\` | Returns a single declared property of one record |
84
- | \`POST /Product/\` | Creates a record; responds \`201\`; primary key returned in \`Location\` header |
85
- | \`PUT /Product/{id}\` | Creates or replaces the record at \`{id}\` (upsert) |
86
- | \`PATCH /Product/{id}\` | Merges body into existing record (shallow, top-level only) |
87
- | \`DELETE /Product/{id}\` | Deletes the record at \`{id}\` |
88
- | \`DELETE /Product/?query\` | Deletes every record matching the query |
89
-
90
- 4. **Handle \`POST\` primary key and \`Location\`**: On a successful \`POST\`, the new record's primary key is returned in the \`Location\` response header — the value the body supplied if it carried the primary-key property, otherwise a Harper-assigned key. The header carries the bare key value, not a URL.
91
-
92
- 5. **Understand \`PUT\` write behavior**: \`PUT\` replaces the stored record exactly. Three exceptions always apply: a \`@createdTime\` attribute keeps the original value, an \`@updatedTime\` attribute is re-stamped with the time of the write, and the primary key is forced to match the \`{id}\` in the URL.
93
-
94
- 6. **Use conditional requests for caching**: GET responses include an \`ETag\` header encoding the record's version/last-modification time. Send \`If-None-Match\` on subsequent requests with the cached \`ETag\` value. If the record has not changed, Harper returns \`304 Not Modified\` with no body.
95
-
96
- 7. **Select content type with \`Accept\`**: Use the \`Accept\` header to request a specific response format. The suffixes \`.json\`, \`.cbor\`, \`.msgpack\`, and \`.csv\` are reserved as content-type selectors on property paths and take precedence over property names. See [querying-rest-apis.md](querying-rest-apis.md) for query syntax details.
97
-
98
- 8. **Connect via WebSocket**: WebSocket support is enabled automatically when \`rest\` is enabled. Connecting to a resource URL subscribes to changes for that resource. See [real-time-apps.md](real-time-apps.md) for real-time patterns.
99
-
100
- \`\`\`javascript
101
- let ws = new WebSocket('wss://server/my-resource/341');
102
- ws.onmessage = (event) => {
103
- let data = JSON.parse(event.data);
104
- };
105
- \`\`\`
106
-
107
- 9. **Implement a custom \`connect()\` handler** when default subscription behavior is insufficient. The method must return an async iterable that produces messages to send to the client.
108
-
109
- \`\`\`javascript
110
- export class Echo extends Resource {
111
- async *connect(incomingMessages) {
112
- for await (let message of incomingMessages) {
113
- yield message; // echo each message back
114
- }
115
- }
116
- }
117
- \`\`\`
118
-
119
- ## Examples
120
-
121
- ### Full schema and config setup
122
-
123
- \`\`\`graphql
124
- # schema.graphql
125
- type Product @table @export {
126
- id: Long @primaryKey
127
- name: String
128
- price: Float
129
- }
130
- \`\`\`
131
-
132
- \`\`\`yaml
133
- # config.yaml
134
- graphqlSchema:
135
- files: schema.graphql
136
- rest: true
137
- \`\`\`
138
-
139
- ### Conditional GET with ETag caching
140
-
141
- \`\`\`
142
- GET /Product/123
143
- # Response includes:
144
- # ETag: "abc123"
145
-
146
- GET /Product/123
147
- If-None-Match: "abc123"
148
- # Response: 304 Not Modified (no body transferred)
149
- \`\`\`
150
-
151
- ### POST and read the Location header
152
-
153
- \`\`\`
154
- POST /Product/
155
- Content-Type: application/json
156
-
157
- { "name": "Widget", "price": 9.99 }
158
-
159
- # Response:
160
- # 201 Created
161
- # Location: 7f3a9c
162
- \`\`\`
163
-
164
- ### PATCH (shallow merge only)
165
-
166
- \`\`\`
167
- PATCH /Product/123
168
- Content-Type: application/json
169
-
170
- { "price": 12.99 }
171
- \`\`\`
172
-
173
- Only \`price\` is updated; other top-level properties are preserved. Nested objects in the body replace the stored sub-object wholesale — deep merge does not occur.
174
-
175
- ### Request MessagePack response
176
-
177
- \`\`\`
178
- GET /Product/123
179
- Accept: application/msgpack
180
- \`\`\`
181
-
182
- Alternatively, use the \`.msgpack\` suffix on the URL path where supported.
183
-
184
- ### WebSocket with custom outgoing messages
185
-
186
- \`\`\`javascript
187
- export class Example extends Resource {
188
- connect(incomingMessages) {
189
- let outgoingMessages = super.connect();
190
-
191
- let timer = setInterval(() => {
192
- outgoingMessages.send({ greeting: 'hi again!' });
193
- }, 1000);
194
-
195
- incomingMessages.on('data', (message) => {
196
- outgoingMessages.send(message);
197
- });
198
-
199
- outgoingMessages.on('close', () => {
200
- clearInterval(timer);
201
- });
202
-
203
- return outgoingMessages;
204
- }
205
- }
206
- \`\`\`
207
-
208
- ### Disable WebSocket while keeping REST
209
-
210
- \`\`\`yaml
211
- rest:
212
- webSocket: false
213
- \`\`\`
214
-
215
- ## Notes
216
-
217
- - The trailing slash is significant: \`/Product\` addresses the resource itself; \`/Product/\` addresses its record collection. \`POST /Product\` (no trailing slash) returns \`404\`.
218
- - \`HEAD\` is served as \`GET\` with the body omitted. \`QUERY\` is accepted on the collection path and reads its search from the request body.
219
- - A \`POST\` to an existing primary key fails with \`409\` — it does not overwrite.
220
- - A component directory with **no configuration file** gets REST enabled by Harper's built-in default. As soon as a \`config.yaml\` exists it is used verbatim — add \`rest: true\` explicitly or REST is off.
221
- - Do not apply \`@export\` to a schema type and also export a same-named JavaScript subclass of that table — this produces conflicting endpoints.
222
- - Server-Sent Events subscriptions are served on the same paths, negotiated via \`Accept: text/event-stream\`. They are not affected by the \`webSocket\` option.
223
- - Every non-hidden exported resource is included in the generated OpenAPI document at \`GET /openapi\`. Mark a type \`@hidden\` or set \`static hidden = true\` on a programmatic Resource to omit it.
224
- - MQTT over WebSockets requires the sub-protocol header \`Sec-WebSocket-Protocol: mqtt\`.
225
- `,caching:`---
226
- name: caching
227
- description: How to implement integrated data caching in Harper from external sources.
228
- metadata:
229
- mode: generate
230
- sources:
231
- - learn/developers/caching-with-harper.md
232
- sourceCommit: 4fe4c9c95e0974eaa77032f6f10e36fbd8ec64ac
233
- inputHash: 60ad55fa37b5eec5
234
- ---
235
-
236
- # Caching External Data Sources in Harper
237
-
238
- Instructions for the agent to implement integrated data caching from external sources using Harper's cache table directives and \`sourcedFrom\` API.
239
-
240
- ## When to Use
241
-
242
- Apply this rule when an application needs to wrap an external API, microservice, or database with a fast local cache. Use it when you need to define TTL-based cache expiration, connect an upstream data source to a Harper table, or implement on-demand cache invalidation.
243
-
244
- ## How It Works
245
-
246
- 1. **Define a cache table with \`expiration\`**: Add the \`expiration\` argument to the \`@table\` directive in \`schema.graphql\`. The value is in seconds. When a record becomes stale, the next request fetches a fresh copy from the upstream source.
247
-
248
- \`\`\`graphql
249
- type JokeCache @table(expiration: 60) @export {
250
- id: ID @primaryKey
251
- setup: String
252
- punchline: String
253
- }
254
- \`\`\`
255
-
256
- 2. **Implement an upstream source object**: In \`resources.js\`, create an object with a \`get(id)\` method that fetches data from the external API.
257
-
258
- \`\`\`javascript
259
- const jokeAPI = {
260
- async get(id) {
261
- const response = await fetch(\`https://official-joke-api.appspot.com/jokes/\${id}\`);
262
- return response.json();
263
- },
264
- };
265
- \`\`\`
266
-
267
- 3. **Connect the source with \`sourcedFrom\`**: Call \`sourcedFrom\` on the table to register the upstream source. Harper will call \`jokeAPI.get()\` automatically when a record is missing or stale.
268
-
269
- \`\`\`javascript
270
- tables.JokeCache.sourcedFrom(jokeAPI);
271
- \`\`\`
272
-
273
- Harper's request flow after \`sourcedFrom\` is registered:
274
- - Request arrives for \`/JokeCache/1\`.
275
- - Harper checks if the record exists and is not stale.
276
- - If fresh, Harper returns it immediately.
277
- - If missing or stale, Harper calls \`jokeAPI.get()\`, stores the result in \`JokeCache\`, and returns it.
278
- - Multiple simultaneous requests for the same missing or stale record wait on a single upstream call — Harper prevents cache stampedes automatically.
279
-
280
- 4. **Configure plugins in \`config.yaml\`**: Enable \`graphqlSchema\`, \`rest\`, and \`jsResource\`.
281
-
282
- \`\`\`yaml
283
- graphqlSchema:
284
- files: 'schema.graphql'
285
- rest: true
286
- jsResource:
287
- files: 'resources.js'
288
- \`\`\`
289
-
290
- 5. **Implement on-demand invalidation**: To invalidate a cache entry before its TTL expires, export a class extending the table and call \`this.invalidate(target)\` in a \`post\` handler. Remove \`@export\` from the schema when using this pattern — the exported class provides the endpoint.
291
-
292
- \`\`\`javascript
293
- export class JokeCache extends tables.JokeCache {
294
- static async post(target, data) {
295
- const body = await data;
296
- if (body?.action === 'invalidate') {
297
- this.invalidate(target);
298
- return { status: 200, data: { message: 'invalidated' } };
299
- }
300
- }
301
- }
302
- \`\`\`
303
-
304
- Update the schema to remove \`@export\`:
305
-
306
- \`\`\`graphql
307
- type JokeCache @table(expiration: 60) {
308
- id: ID @primaryKey
309
- setup: String
310
- punchline: String
311
- }
312
- \`\`\`
313
-
314
- ## Examples
315
-
316
- **Complete \`resources.js\`**:
317
-
318
- \`\`\`javascript
319
- // resources.js
320
-
321
- const jokeAPI = {
322
- async get(id) {
323
- const response = await fetch(\`https://official-joke-api.appspot.com/jokes/\${id}\`);
324
- return response.json();
325
- },
326
- };
327
-
328
- tables.JokeCache.sourcedFrom(jokeAPI);
329
-
330
- export class JokeCache extends tables.JokeCache {
331
- static async post(target, data) {
332
- const body = await data;
333
- if (body?.action === 'invalidate') {
334
- this.invalidate(target);
335
- return { status: 200, data: { message: 'invalidated' } };
336
- }
337
- }
338
- }
339
- \`\`\`
340
-
341
- **Complete \`schema.graphql\`**:
342
-
343
- \`\`\`graphql
344
- type JokeCache @table(expiration: 60) {
345
- id: ID @primaryKey
346
- setup: String
347
- punchline: String
348
- }
349
- \`\`\`
350
-
351
- **Fetch a cached record**:
352
-
353
- \`\`\`javascript
354
- const response = await fetch('http://localhost:9926/JokeCache/1');
355
- console.log(response.status); // 200
356
- const etag = response.headers.get('etag'); // e.g. "abCDefGHij"
357
- const joke = await response.json();
358
- \`\`\`
359
-
360
- **Use ETag for conditional requests** (returns \`304 Not Modified\` if unchanged):
361
-
362
- \`\`\`javascript
363
- const second = await fetch('http://localhost:9926/JokeCache/1', {
364
- headers: { 'If-None-Match': etag },
365
- });
366
- console.log(second.status); // 304
367
- \`\`\`
368
-
369
- **Bypass the cache with \`Cache-Control: no-cache\`**:
370
-
371
- \`\`\`javascript
372
- const response = await fetch('http://localhost:9926/JokeCache/1', {
373
- headers: { 'Cache-Control': 'no-cache' },
374
- });
375
- \`\`\`
376
-
377
- **Trigger invalidation via POST**:
378
-
379
- \`\`\`javascript
380
- await fetch('http://localhost:9926/JokeCache/1', {
381
- method: 'POST',
382
- headers: { 'Content-Type': 'application/json' },
383
- body: JSON.stringify({ action: 'invalidate' }),
384
- });
385
- \`\`\`
386
-
387
- ## Notes
388
-
389
- - \`expiration\` is measured in seconds. Harper also supports separate \`eviction\` and \`scanInterval\` arguments on \`@table\` for fine-grained control over physical record removal.
390
- - ETags are automatically computed from a record's last-modified timestamp. Include the double quotes when passing an ETag back in \`If-None-Match\` — they are part of the value.
391
- - Exporting a class with the same name as a table (e.g., \`export class JokeCache extends tables.JokeCache\`) registers it as the HTTP endpoint for that table; \`@export\` in the schema is not required separately.
392
- - For defining custom upstream source behavior beyond a simple \`get\`, see [custom-resources.md](custom-resources.md).
393
- - For details on how \`@table\` and \`@export\` expose REST endpoints automatically, see [automatic-apis.md](automatic-apis.md).
394
- `,"checking-authentication":`---
395
- name: checking-authentication
396
- description: How to handle user authentication and sessions in Harper Resources.
397
- metadata:
398
- mode: generate
399
- sources:
400
- - >-
401
- reference/v5/resources/resource-api.md#\`getCurrentUser(): User |
402
- undefined\`
403
- - 'reference/v5/resources/resource-api.md#\`getContext(): Context\`'
404
- - reference/v5/resources/resource-api.md#Session and Login from a Resource
405
- - reference/v5/security/jwt-authentication.md#Create Authentication Tokens
406
- - reference/v5/security/jwt-authentication.md#Using the Operation Token
407
- - reference/v5/security/jwt-authentication.md#Refreshing the Operation Token
408
- - reference/v5/security/jwt-authentication.md#Scoped Tokens (Inline Role)
409
- - >-
410
- reference/v5/security/jwt-authentication.md#Issuing Tokens from a Custom
411
- Resource
412
- - reference/v5/security/jwt-authentication.md#Token Expiry Configuration
413
- - reference/v5/security/jwt-authentication.md#When to Use JWT Auth
414
- - reference/v5/security/jwt-authentication.md#Security Notes
415
- sourceCommit: 9e6ecf87dd25bb488ad44dc2876ca6439ccd682e
416
- inputHash: 1837f39fdfe06fac
417
- ---
418
-
419
- # Checking Authentication
420
-
421
- Instructions for the agent to handle user authentication, sessions, and JWT token issuance in Harper Resources.
422
-
423
- ## When to Use
424
-
425
- Apply this rule when implementing login/logout flows, reading the current authenticated user, issuing or refreshing JWT tokens, or minting scoped tokens from a custom Resource. Use it whenever a Resource must gate behavior on identity or credentials. See [custom-resources.md](custom-resources.md) for the broader Resource authoring model.
426
-
427
- ## How It Works
428
-
429
- ### 1. Reading the Current Authenticated User
430
-
431
- **In an instance method**, call \`getCurrentUser()\` to get the user associated with the current request, or \`undefined\` if unauthenticated. The returned object exposes \`username\`, \`role\`, and \`role.permission\` flags.
432
-
433
- **In a static verb**, read the user from the \`context\` argument instead — \`context.user\`:
434
-
435
- \`\`\`javascript
436
- static async get(_target, context) {
437
- const user = context?.user;
438
- if (!user) return new Response(null, { status: 401 });
439
- return { username: user.username, role: user.role };
440
- }
441
- \`\`\`
442
-
443
- ### 2. Reading the Full Context
444
-
445
- **In an instance method**, call \`getContext()\` to retrieve the current context, which includes:
446
-
447
- - \`user\` — User object with username, role, and authorization information
448
- - \`transaction\` — The current transaction
449
-
450
- **In a static verb**, the context is the trailing argument:
451
-
452
- - \`(target, context)\` for \`get\`/\`delete\`
453
- - \`(target, data, context)\` for \`put\`/\`patch\`/\`post\`
454
-
455
- When triggered by HTTP, the context also exposes \`url\`, \`method\`, \`headers\`, \`responseHeaders\`, \`pathname\`, \`host\`, \`ip\`, \`body\`, \`data\`, \`lastModified\`, and \`requestContext\`.
456
-
457
- ### 3. Handling Sessions and Login
458
-
459
- Enable sessions in \`harper-config.yaml\`:
460
-
461
- \`\`\`yaml
462
- authentication:
463
- enableSessions: true
464
- \`\`\`
465
-
466
- Use \`context.login\` in a static \`post\` verb to verify credentials and establish a session cookie:
467
-
468
- \`\`\`javascript
469
- export class SignIn extends Resource {
470
- static async post(_target, data, context) {
471
- const { username, password } = (await data) ?? {};
472
- try {
473
- await context.login(username, password);
474
- } catch {
475
- return new Response('Invalid credentials', { status: 403 });
476
- }
477
- return new Response('Logged in', { status: 200 });
478
- }
479
- }
480
-
481
- export class SignOut extends Resource {
482
- static async post(_target, _data, context) {
483
- if (!context?.session?.user) return new Response(null, { status: 401 });
484
- await context.session.update({ user: null });
485
- return new Response('Logged out', { status: 200 });
486
- }
487
- }
488
- \`\`\`
489
-
490
- - \`context.login(username, password)\` verifies credentials and sets the session cookie on success.
491
- - To end a session, call \`context.session.update({ user: null })\` — \`update\` is the session's only mutator.
492
- - \`context.session\` is an empty object (not \`undefined\`) when sessions are enabled and no session cookie is present; test \`context?.session?.user\` to detect an established session.
493
- - Cookie-based sessions are for browser clients. For non-browser clients, use JWT issuance.
494
-
495
- ### 4. Creating Authentication Tokens
496
-
497
- Call \`create_authentication_tokens\` with credentials in the body — no \`Authorization\` header is required when \`username\` and \`password\` are supplied:
498
-
499
- \`\`\`json
500
- {
501
- "operation": "create_authentication_tokens",
502
- "username": "username",
503
- "password": "password"
504
- }
505
- \`\`\`
506
-
507
- Response:
508
-
509
- \`\`\`json
510
- {
511
- "operation_token": "<jwt-operation-token>",
512
- "refresh_token": "<jwt-refresh-token>"
513
- }
514
- \`\`\`
515
-
516
- Pass the \`operation_token\` as a \`Bearer\` token on subsequent requests:
517
-
518
- \`\`\`bash
519
- curl --location --request POST 'http://localhost:9925' \\
520
- --header 'Content-Type: application/json' \\
521
- --header 'Authorization: Bearer <operation_token>' \\
522
- --data-raw '{
523
- "operation": "search_by_hash",
524
- "schema": "dev",
525
- "table": "dog",
526
- "hash_values": [1],
527
- "get_attributes": ["*"]
528
- }'
529
- \`\`\`
530
-
531
- ### 5. Refreshing the Operation Token
532
-
533
- When the \`operation_token\` expires, pass the \`refresh_token\` as \`Bearer <refresh_token>\` and call \`refresh_operation_token\`:
534
-
535
- \`\`\`bash
536
- curl --location --request POST 'http://localhost:9925' \\
537
- --header 'Content-Type: application/json' \\
538
- --header 'Authorization: Bearer <refresh_token>' \\
539
- --data-raw '{
540
- "operation": "refresh_operation_token"
541
- }'
542
- \`\`\`
543
-
544
- Response:
545
-
546
- \`\`\`json
547
- {
548
- "operation_token": "<new-jwt-operation-token>"
549
- }
550
- \`\`\`
551
-
552
- When both tokens have expired, call \`create_authentication_tokens\` again with username and password.
553
-
554
- ### 6. Minting Scoped Tokens
555
-
556
- A \`super_user\` can mint a scoped token with embedded permissions using \`create_authentication_tokens\` with an inline \`role\`. The minter must be authenticated; no \`password\` may be included in the body. Use \`add_role\`-style \`permission\` structure:
557
-
558
- \`\`\`json
559
- {
560
- "operation": "create_authentication_tokens",
561
- "username": "reporting-service",
562
- "role": {
563
- "permission": {
564
- "operations": ["read_only"],
565
- "dev": {
566
- "tables": {
567
- "dog": {
568
- "read": true,
569
- "insert": false,
570
- "update": false,
571
- "delete": false,
572
- "attribute_permissions": []
573
- }
574
- }
575
- }
576
- }
577
- },
578
- "expires_in": "7d"
579
- }
580
- \`\`\`
581
-
582
- Authenticate the mint request with Basic Authentication or an existing \`super_user\` \`operation_token\`:
583
-
584
- \`\`\`bash
585
- curl --location --request POST 'http://localhost:9925' \\
586
- --header 'Content-Type: application/json' \\
587
- --header 'Authorization: Basic <base64 of super_user:password>' \\
588
- --data-raw '{
589
- "operation": "create_authentication_tokens",
590
- "username": "reporting-service",
591
- "role": { "permission": { "operations": ["read_only"] } },
592
- "expires_in": "7d"
593
- }'
594
- \`\`\`
595
-
596
- Key constraints for scoped tokens:
597
-
598
- - \`username\` is attribution only and must not name an existing user.
599
- - No refresh token is issued; no user record is created.
600
- - Scoped tokens cannot be revoked before expiry — choose \`expires_in\` carefully and prefer short lifetimes.
601
- - \`super_user\` and \`cluster_user\` are always forced to \`false\` in the embedded role.
602
- - In **mixed-version** clusters, only nodes with scoped-token support accept these tokens; older nodes reject them with 401.
603
-
604
- ### 7. Issuing Tokens from a Custom Resource
605
-
606
- Use \`server.operation()\` to mint tokens programmatically inside a Resource. Pass \`authorize: true\` as the **third argument** when the operation should run as the current authenticated user:
607
-
608
- \`\`\`javascript
609
- import { Resource, server } from 'harper';
610
-
611
- export class IssueTokens extends Resource {
612
- static async get(_target, context) {
613
- // Issue tokens for the current authenticated user
614
- const { operation_token, refresh_token } = await server.operation(
615
- { operation: 'create_authentication_tokens' },
616
- context,
617
- true, // third argument: authorize as current user
618
- );
619
- return { operation_token, refresh_token };
620
- }
621
-
622
- static async post(_target, data) {
623
- // Issue tokens from credentials supplied in the body
624
- const { username, password } = await data;
625
- if (!username || !password) {
626
- return new Response('username and password required', { status: 400 });
627
- }
628
- const { operation_token, refresh_token } = await server.operation({
629
- operation: 'create_authentication_tokens',
630
- username,
631
- password,
632
- });
633
- return { operation_token, refresh_token };
634
- }
635
- }
636
-
637
- export class RefreshJWT extends Resource {
638
- static async post(_target, data) {
639
- const { refresh_token } = await data;
640
- if (!refresh_token) {
641
- return new Response('refresh_token required', { status: 400 });
642
- }
643
- const { operation_token } = await server.operation({
644
- operation: 'refresh_operation_token',
645
- refresh_token,
646
- });
647
- return { operation_token };
648
- }
649
- }
650
- \`\`\`
651
-
652
- Omit the third argument (or pass \`false\`) when the operation supplies its own credentials.
653
-
654
- ### 8. Configuring Token Expiry
655
-
656
- Set timeouts in \`harper-config.yaml\` under the \`authentication\` section:
657
-
658
- \`\`\`yaml
659
- authentication:
660
- operationTokenTimeout: 1d # Default: 1 day
661
- refreshTokenTimeout: 30d # Default: 30 days
662
- \`\`\`
663
-
664
- Valid duration strings follow the \`jsonwebtoken\` package format (e.g., \`1d\`, \`12h\`, \`60m\`). The \`expires_in\` field on scoped token minting accepts the same format.
665
-
666
- ## Examples
667
-
668
- ### Full Sign-In / Sign-Out Resource
669
-
670
- \`\`\`javascript
671
- export class SignIn extends Resource {
672
- static async post(_target, data, context) {
673
- const { username, password } = (await data) ?? {};
674
- try {
675
- await context.login(username, password);
676
- } catch {
677
- return new Response('Invalid credentials', { status: 403 });
678
- }
679
- return new Response('Logged in', { status: 200 });
680
- }
681
- }
682
-
683
- export class SignOut extends Resource {
684
- static async post(_target, _data, context) {
685
- if (!context?.session?.user) return new Response(null, { status: 401 });
686
- await context.session.update({ user: null });
687
- return new Response('Logged out', { status: 200 });
688
- }
689
- }
690
- \`\`\`
691
-
692
- ### Reading the Current Authenticated User in a Static Verb
693
-
694
- \`\`\`javascript
695
- static async get(_target, context) {
696
- const user = context?.user;
697
- if (!user) return new Response(null, { status: 401 });
698
- return { username: user.username, role: user.role };
699
- }
700
- \`\`\`
701
-
702
- ### Minting Tokens via cURL
703
-
704
- \`\`\`bash
705
- curl --location --request POST 'http://localhost:9925' \\
706
- --header 'Content-Type: application/json' \\
707
- --data-raw '{
708
- "operation": "create_authentication_tokens",
709
- "username": "username",
710
- "password": "password"
711
- }'
712
- \`\`\`
713
-
714
- ## Notes
715
-
716
- - JWT authentication is **preferred over Basic Auth** when you want to avoid sending credentials on every request, your client can store tokens, or you have multiple sequential requests. For simple or **server-to-server** scenarios, use **Basic Authentication**.
717
- - Always use **HTTPS** in production to protect tokens in transit.
718
- - Treat tokens like passwords. If a token is compromised, it remains valid until expiry — use shorter \`operationTokenTimeout\` values in high-security environments.
719
- - \`context.login\` and \`context.session\` require \`enableSessions: true\` in \`harperdb-config.yaml\`; they are for browser clients only.
720
- - The \`server.operation()\` third argument (\`authorize: true\`) attributes the operation to — and permission-checks against — the current authenticated user. Omit it when supplying credentials directly in the operation body.
721
- - In **mixed-version** clusters, scoped tokens are only accepted by nodes that support them; older nodes return 401.
722
- `,"creating-a-fabric-account-and-cluster":`---
723
- name: creating-a-fabric-account-and-cluster
724
- description: How to create a Harper Fabric account, organization, and cluster.
725
- metadata:
726
- mode: synthesized
727
- ---
728
-
729
- # Creating a Harper Fabric Account and Cluster
730
-
731
- Follow these steps to set up your Harper Fabric environment for deployment.
732
-
733
- ## How It Works
734
-
735
- 1. **Sign Up/In**: Go to [https://fabric.harper.fast/](https://fabric.harper.fast/) and sign up or sign in.
736
- 2. **Create an Organization**: Create an organization (org) to manage your projects.
737
- 3. **Create a Cluster**: Create a new cluster. This can be on the free tier, no credit card required.
738
- 4. **Set Credentials**: During setup, set the cluster username and password to finish configuring it.
739
- 5. **Get Application URL**: Navigate to the **Config** tab and copy the **Application URL**.
740
- 6. **Configure Environment**: Update your \`.env\` file or GitHub Actions secrets with cluster-specific credentials.
741
- 7. **Next Steps**: See the [deploying-to-harper-fabric](deploying-to-harper-fabric.md) rule for detailed instructions on deploying your application successfully.
742
-
743
- ## Examples
744
-
745
- ### Environment Configuration
746
-
747
- \`\`\`bash
748
- CLI_TARGET_USERNAME='YOUR_CLUSTER_USERNAME'
749
- CLI_TARGET_PASSWORD='YOUR_CLUSTER_PASSWORD'
750
- CLI_TARGET='YOUR_CLUSTER_URL'
751
- \`\`\`
752
- `,"creating-harper-apps":`---
753
- name: creating-harper-apps
754
- description: How to initialize a new Harper application using the CLI.
755
- metadata:
756
- mode: synthesized
757
- ---
758
-
759
- # Creating Harper Applications
760
-
761
- The fastest way to start a new Harper project is using the \`create-harper\` CLI tool. This command
762
- initializes a project with a standard folder structure, essential configuration files, and basic
763
- schema definitions.
764
-
765
- ## When to Use
766
-
767
- Use this command when starting a new Harper application or adding a new Harper microservice to an
768
- existing architecture.
769
-
770
- ## Commands
771
-
772
- Initialize a project using your preferred package manager:
773
-
774
- ### NPM
775
-
776
- \`\`\`bash
777
- npm create harper@latest
778
- \`\`\`
779
-
780
- ### PNPM
781
-
782
- \`\`\`bash
783
- pnpm create harper@latest
784
- \`\`\`
785
-
786
- ### Bun
787
-
788
- \`\`\`bash
789
- bun create harper@latest
790
- \`\`\`
791
-
792
- ## Options
793
-
794
- You can specify the project name and template directly:
795
-
796
- \`\`\`bash
797
- npm create harper@latest my-app --template default
798
- \`\`\`
799
-
800
- ## Next Steps
801
-
802
- 1. **Configure Environment**: Set up your \`.env\` file with local or cloud credentials.
803
- 2. **Define Schema**: Modify \`schema.graphql\` to fit your application's data model.
804
- 3. **Start Development**: Run \`npm run dev\` to start the local Harper instance.
805
- 4. **Deploy**: Use \`npm run deploy\` to push your application to Harper Fabric.
806
- `,"custom-resources":`---
807
- name: custom-resources
808
- description: How to define custom REST endpoints with JavaScript or TypeScript in Harper.
809
- metadata:
810
- mode: generate
811
- sources:
812
- - reference/v5/resources/overview.md#Custom External Data Source
813
- - reference/v5/resources/overview.md#Exporting Resources as Endpoints
814
- - reference/v5/components/javascript-environment.md#Module Formats
815
- sourceCommit: 9e6ecf87dd25bb488ad44dc2876ca6439ccd682e
816
- inputHash: 86858206e33925f0
817
- ---
818
-
819
- # Custom Resources
820
-
821
- Instructions for the agent to follow when defining custom REST endpoints with JavaScript or TypeScript in Harper.
822
-
823
- ## When to Use
824
-
825
- Apply this rule when creating custom HTTP endpoints, wrapping external APIs, or registering routes programmatically in a Harper application. Use it any time business logic must live outside a table-backed resource or when a specific URL shape is required.
826
-
827
- ## How It Works
828
-
829
- 1. **Import \`Resource\` from the \`harper\` package**: Always import explicitly rather than relying on globals.
830
-
831
- \`\`\`javascript
832
- import { tables, Resource } from 'harper';
833
- \`\`\`
834
-
835
- 2. **Define a class that \`extends Resource\`**: Implement HTTP methods as \`static\` methods. Each method receives a \`target\` object.
836
-
837
- \`\`\`javascript
838
- export class CustomEndpoint extends Resource {
839
- static get(target) {
840
- return {
841
- data: doSomething(),
842
- };
843
- }
844
- }
845
- \`\`\`
846
-
847
- 3. **Use \`async\` static methods to call external services**: Return or forward the response directly.
848
-
849
- \`\`\`javascript
850
- export class MyExternalData extends Resource {
851
- static async get(target) {
852
- const response = await fetch(\`https://api.example.com/\${target.id}\`);
853
- return response.json();
854
- }
855
-
856
- static async put(target, data) {
857
- return fetch(\`https://api.example.com/\${target.id}\`, {
858
- method: 'PUT',
859
- body: JSON.stringify(await data),
860
- });
861
- }
862
- }
863
- \`\`\`
864
-
865
- 4. **Export the class to expose it as an endpoint**: The export form controls the resulting URL. Choose the form that matches the URL shape you need.
866
-
867
- | Export form | URL | Notes |
868
- | ------------------------------------------- | --------------- | --------------------------------------------------------------- |
869
- | \`export class Foo extends Resource {}\` | \`/Foo/\` | Class name becomes the path segment. Case-sensitive. |
870
- | \`export const Bar = { Foo };\` | \`/Bar/Foo/\` | Nest under an object to add a path prefix. |
871
- | \`export const bar = { 'foo-baz': Foo };\` | \`/bar/foo-baz/\` | Use object keys for lowercase, hyphens, or non-identifier URLs. |
872
- | \`export { Foo as '/widget/:id' }\` | \`/widget/:id\` | Rename the export to set the path directly. |
873
- | \`static path = '/widget/:id'\` (class field) | \`/widget/:id\` | Declare path on the class; overrides the export name. |
874
- | \`server.resources.set('my-path', Foo);\` | \`/my-path/\` | Programmatic registration for dynamic paths. |
875
-
876
- 5. **Register programmatically when the path is dynamic**: Use \`server.resources.set(\` with a path string and the resource class.
877
-
878
- \`\`\`javascript
879
- server.resources.set('my-path', Foo);
880
- \`\`\`
881
-
882
- 6. **Declare dynamic path segments with \`static path\`**: Use \`:name\` for a single segment and \`*name\` as a catch-all. Matched values are bound onto \`target.<name>\`.
883
-
884
- \`\`\`javascript
885
- export class Widget extends Resource {
886
- // GET /widget/10/action/jump -> target.id === '10', target.action === 'jump'
887
- static path = '/widget/:id/action/:action';
888
- static get(target) {
889
- return { id: target.id, action: target.action };
890
- }
891
- }
892
- \`\`\`
893
-
894
- 7. **Resolve path precedence correctly**: Exact and static paths always win over parameterized ones. Among parameterized routes, more specific paths win: a literal segment beats a \`:param\`, which beats a \`*\` wildcard, compared left to right.
895
-
896
- ## Examples
897
-
898
- **Wrapping an external API and using it as a cache source:**
899
-
900
- \`\`\`javascript
901
- import { tables, Resource } from 'harper';
902
-
903
- export class MyExternalData extends Resource {
904
- static async get(target) {
905
- const response = await fetch(\`https://api.example.com/\${target.id}\`);
906
- return response.json();
907
- }
908
-
909
- static async put(target, data) {
910
- return fetch(\`https://api.example.com/\${target.id}\`, {
911
- method: 'PUT',
912
- body: JSON.stringify(await data),
913
- });
914
- }
915
- }
916
-
917
- // Use as a cache source for a local table
918
- tables.MyCache.sourcedFrom(MyExternalData);
919
- \`\`\`
920
-
921
- **Catch-all wildcard path:**
922
-
923
- \`\`\`javascript
924
- export class Files extends Resource {
925
- // GET /files/a/b/c.txt -> target.rest === 'a/b/c.txt'
926
- static path = '/files/*rest';
927
- static get(target) {
928
- return { path: target.rest };
929
- }
930
- }
931
- \`\`\`
932
-
933
- **Root-relative fixed route:**
934
-
935
- \`\`\`javascript
936
- export class AcmeChallenge extends Resource {
937
- static path = '/.well-known/acme-challenge/:token';
938
- static get(target) {
939
- return { token: target.token };
940
- }
941
- }
942
- \`\`\`
943
-
944
- ## Notes
945
-
946
- - URL path matching is case-sensitive — \`/Foo/\` and \`/foo/\` are different endpoints.
947
- - A leading \`/\` in \`static path\` makes the path root-relative (top-level), independent of the file's location.
948
- - A leading \`./\` or a bare name in \`static path\` resolves relative to the component directory.
949
- - A bare \`*\` (no name) binds under \`target.wildcard\`. A wildcard must be the final segment of the path.
950
- - \`static path\` takes precedence over the export name when both are present.
951
- - Parameterized routes appear in the generated OpenAPI document as templated paths (e.g. \`/widget/{id}/action/{action}\`) and in MCP \`resources/templates/list\` as URI templates.
952
- - When a resource \`extends\` an existing table, avoid conflicting exports between the schema and the JavaScript implementation.
953
- - Link the \`harper\` package in your component directory to ensure correct typings: \`npm link harper\`. All installed components have \`harper\` automatically linked.
954
- `,"defining-relationships":`---
955
- name: defining-relationships
956
- description: How to define and use relationships between tables in Harper using GraphQL.
957
- metadata:
958
- mode: generate
959
- sources:
960
- - reference/v5/database/schema.md#Relationships
961
- - reference/v5/rest/querying.md#Relationships and Joins
962
- sourceCommit: 3749d0c54be457a2a65d9a63c738a5dc88989ecd
963
- inputHash: fd399fd81a88f13e
964
- ---
965
-
966
- # Defining Relationships Between Tables in Harper
967
-
968
- Instructions for the agent to follow when defining and querying relationships between tables in Harper using the \`@relationship\` directive.
969
-
970
- ## When to Use
971
-
972
- Apply this rule when adding foreign key relationships between schema tables, enabling join queries, or returning nested related records in query results. Use it any time a schema type needs to reference records in another table via a foreign key attribute.
973
-
974
- ## How It Works
975
-
976
- 1. **Use \`@relationship(from: attribute)\` for many-to-one or many-to-many**: Place this on the field in the table that holds the foreign key. The \`from\` parameter names the attribute on this table that stores the foreign key referencing the target table's primary key.
977
-
978
- \`\`\`graphql
979
- type RealityShow @table @export {
980
- id: Long @primaryKey
981
- networkId: Long @indexed
982
- network: Network @relationship(from: networkId) # many-to-one
983
- title: String @indexed
984
- }
985
-
986
- type Network @table @export {
987
- id: Long @primaryKey
988
- name: String @indexed
989
- }
990
- \`\`\`
991
-
992
- If the foreign key attribute is an array, the relationship becomes many-to-many:
993
-
994
- \`\`\`graphql
995
- type RealityShow @table @export {
996
- id: Long @primaryKey
997
- networkIds: [Long] @indexed
998
- networks: [Network] @relationship(from: networkIds)
999
- }
1000
- \`\`\`
1001
-
1002
- 2. **Use \`@relationship(to: attribute)\` for one-to-many or many-to-many**: Place this on the table whose primary key is referenced by the foreign key in the target table. The \`to\` parameter names the attribute on the target table that holds the foreign key. The result type **must** be an array.
1003
-
1004
- \`\`\`graphql
1005
- type Network @table @export {
1006
- id: Long @primaryKey
1007
- name: String @indexed
1008
- shows: [RealityShow] @relationship(to: networkId) # one-to-many
1009
- }
1010
- \`\`\`
1011
-
1012
- 3. **Use \`@relationship(from: attribute, to: attribute)\` for foreign key to foreign key joins**: Specify both \`from\` and \`to\` when neither side uses the primary key. Harper resolves the relationship by searching the target table's \`to\` attribute for matches using this record's \`from\` attribute value. The result type must be an array.
1013
-
1014
- \`\`\`graphql
1015
- type OrderItem @table @export {
1016
- id: Long @primaryKey
1017
- orderId: Long @indexed
1018
- productSku: Long @indexed
1019
- products: [Product] @relationship(from: productSku, to: sku)
1020
- }
1021
-
1022
- type Product @table @export {
1023
- id: Long @primaryKey
1024
- sku: Long @indexed
1025
- name: String
1026
- }
1027
- \`\`\`
1028
-
1029
- 4. **Query across relationships using dot-syntax**: Filter records by related table attributes using chained dot notation. This behaves as an INNER JOIN — only records with a matching related record are returned.
1030
-
1031
- \`\`\`
1032
- GET /Product/?brand.name=Microsoft
1033
- GET /Brand/?products.name=Keyboard
1034
- \`\`\`
1035
-
1036
- 5. **Include relationship fields in results using \`select()\`**: Relationship attributes are not returned by default. Use \`select()\` to include them, optionally specifying nested fields with \`{}\`.
1037
-
1038
- \`\`\`
1039
- GET /Product/?brand.name=Microsoft&select(name,brand)
1040
- GET /Product/?brand.name=Microsoft&select(name,brand{name})
1041
- GET /Product/?name=Keyboard&select(name,brand{name,id})
1042
- \`\`\`
1043
-
1044
- When selecting a relationship without filtering on it, Harper performs a LEFT JOIN — the relationship property is omitted if the foreign key is null or references a non-existent record.
1045
-
1046
- 6. **Model many-to-many without a junction table**: Store an array of foreign key values and use \`@relationship(from: ...)\` pointing to that array attribute. The array order of the foreign key values is preserved when resolving the relationship.
1047
-
1048
- \`\`\`graphql
1049
- type Product @table @export {
1050
- id: Long @primaryKey
1051
- name: String
1052
- resellerIds: [Long] @indexed
1053
- resellers: [Reseller] @relationship(from: "resellerIds")
1054
- }
1055
- \`\`\`
1056
-
1057
- 7. **Define self-referential relationships** for parent-child hierarchies by pointing \`@relationship\` back at the same table type.
1058
-
1059
- ## Examples
1060
-
1061
- **Full schema with bidirectional relationships:**
1062
-
1063
- \`\`\`graphql
1064
- type Product @table @export {
1065
- id: Long @primaryKey
1066
- name: String
1067
- brandId: Long @indexed
1068
- brand: Brand @relationship(from: "brandId")
1069
- }
1070
-
1071
- type Brand @table @export {
1072
- id: Long @primaryKey
1073
- name: String
1074
- products: [Product] @relationship(to: "brandId")
1075
- }
1076
- \`\`\`
1077
-
1078
- **Querying with joins and nested select:**
1079
-
1080
- \`\`\`
1081
- GET /Product/?brand.name=Microsoft&select(name,brand{name,id})
1082
- GET /Brand/?products.name=Keyboard
1083
- \`\`\`
1084
-
1085
- **Many-to-many query with nested select:**
1086
-
1087
- \`\`\`
1088
- GET /Product/?resellers.name=Cool Shop&select(id,name,resellers{name,id})
1089
- \`\`\`
1090
-
1091
- ## Notes
1092
-
1093
- - Every attribute named in \`from\` or \`to\` must exist on the respective table and be annotated with \`@indexed\` to support join queries.
1094
- - The \`to\`-only and \`from\`+\`to\` forms both require the result field type to be an array (e.g., \`[RealityShow]\`).
1095
- - The \`from\`-only form on a non-array attribute produces a many-to-one relationship; on an array attribute it produces many-to-many.
1096
- - Self-referential relationships are supported for hierarchical data within a single table.
1097
- `,"delegating-to-the-built-in-agent":`---
1098
- name: delegating-to-the-built-in-agent
1099
- description: How to delegate tasks to Harper's built-in agent via the CLI and the agent operations API.
1100
- metadata:
1101
- mode: synthesized
1102
- ---
1103
-
1104
- # Delegating to the Built-in Agent
1105
-
1106
- Harper 5.2+ ships with a **built-in agent** that runs _inside_ the server, on the main thread
1107
- adjacent to the operations API. Because it runs in-process, it can do things a remote client
1108
- cannot: call the operations API as RBAC-filtered tools, read and write component files under the
1109
- instance's components root, attach the V8 inspector to worker threads to debug and profile them,
1110
- schedule follow-up work, and consult the Harper best-practices skill. You send it a natural-language
1111
- task; it runs a tool-using loop under a super_user identity and reports back.
1112
-
1113
- ## When to Use
1114
-
1115
- Delegate to the built-in agent when the work is best done **on the instance itself** rather than
1116
- from your local client:
1117
-
1118
- - Operating on a deployed instance in place — inspect the schema, build or adjust a component,
1119
- restart, run an operation.
1120
- - Debugging or profiling a running instance — attach to a worker thread, capture a CPU profile,
1121
- set a logpoint.
1122
- - Handing off a larger, multi-step task to an agent that already has the instance's tools,
1123
- filesystem, and credentials in context.
1124
-
1125
- Do the work in your own client instead when it's purely local (editing source before deploy) or
1126
- when you don't want a server-side agent making changes.
1127
-
1128
- **Prerequisites:** the target instance must have the agent enabled (an \`agent:\` config block with
1129
- \`enabled: true\`) and a configured generative model backend. All agent operations require
1130
- **super_user**.
1131
-
1132
- ## How It Works
1133
-
1134
- The lifecycle assumes you have already deployed to and authenticated with the target instance (see
1135
- [deploying-to-harper-fabric.md](deploying-to-harper-fabric.md) — \`harper login\` stores a token so
1136
- you don't repeat credentials). Delegation reuses that same target and credentials.
1137
-
1138
- There are two equivalent ways to drive the agent.
1139
-
1140
- ### Option A — the \`harper agent\` CLI (simplest)
1141
-
1142
- A thin client over the agent operations API that reuses your stored \`harper login\` credentials, so
1143
- no connector setup is needed:
1144
-
1145
- \`\`\`bash
1146
- # One-shot: send a task, print the reply, exit
1147
- harper agent "Describe the schema, then add a price index to the Product table."
1148
-
1149
- # Interactive session (REPL)
1150
- harper agent
1151
-
1152
- # Against a specific remote instead of the logged-in default
1153
- harper agent --target <Application URL> "List the databases and tables."
1154
- \`\`\`
1155
-
1156
- The CLI polls the run to completion and renders the transcript (tool calls, results, and the
1157
- agent's reply). When a run needs approval for a destructive action, it prompts you inline.
1158
-
1159
- ### Option B — the agent operations API (programmatic)
1160
-
1161
- Call the operations API directly (HTTP POST to the ops endpoint, super_user auth). This is the path
1162
- to use from scripts and services.
1163
-
1164
- 1. **Start a task** with \`agent_prompt\`. Returns a \`session_id\` and a \`status\`.
1165
-
1166
- \`\`\`bash
1167
- curl -s -u <user>:<pass> <ops-endpoint> \\
1168
- -H 'Content-Type: application/json' \\
1169
- -d '{"operation":"agent_prompt","message":"Build a Customer table (id, email, name) exported over REST."}'
1170
- \`\`\`
1171
-
1172
- 2. **Poll for progress** with \`get_agent_session\`, passing the \`session_id\`. The returned session
1173
- carries the \`status\`, the \`messages\` transcript, and any \`pendingApprovals\`.
1174
-
1175
- \`\`\`bash
1176
- curl -s -u <user>:<pass> <ops-endpoint> \\
1177
- -H 'Content-Type: application/json' \\
1178
- -d '{"operation":"get_agent_session","session_id":"<id>"}'
1179
- \`\`\`
1180
-
1181
- Poll until \`status\` leaves \`running\` — terminal states are \`completed\`, \`aborted\`, and \`error\`;
1182
- \`awaiting_approval\` means it is paused for an approval decision (see step 3).
1183
-
1184
- 3. **Approve or deny a paused action.** When the agent enabled configuration has \`autoApprove:false\`,
1185
- a destructive tool call pauses the run with a \`pendingApprovals[]\` entry. Resolve it with
1186
- \`approve_agent_action\`, then poll again — approval executes the saved call, denial hands the
1187
- rejection back to the agent so it can adjust.
1188
-
1189
- \`\`\`bash
1190
- curl -s -u <user>:<pass> <ops-endpoint> \\
1191
- -H 'Content-Type: application/json' \\
1192
- -d '{"operation":"approve_agent_action","session_id":"<id>","approval_id":"<approval-id>","approved":true}'
1193
- \`\`\`
1194
-
1195
- 4. **Continue the conversation** by passing the same \`session_id\` back into \`agent_prompt\` with a
1196
- new \`message\`. Omit \`session_id\` to start a fresh session.
1197
-
1198
- Supporting operations: \`list_agent_sessions\` (recent sessions), \`cancel_agent_run\` (terminate a
1199
- running or paused session), and \`set_agent_config\` (adjust \`autoApprove\`, \`allowDestructive\`,
1200
- \`model\`, and related settings on a running instance).
1201
-
1202
- ## Examples
1203
-
1204
- **Delegate a build to a deployed Fabric instance and wait for the result:**
1205
-
1206
- \`\`\`bash
1207
- harper login <Application URL>
1208
- harper agent --target <Application URL> \\
1209
- "Create a Product table (id, name, price) exported over REST, then confirm the endpoint responds."
1210
- \`\`\`
1211
-
1212
- **Programmatic start-and-poll loop:**
1213
-
1214
- \`\`\`bash
1215
- SID=$(curl -s -u <user>:<pass> <ops-endpoint> -H 'Content-Type: application/json' \\
1216
- -d '{"operation":"agent_prompt","message":"Add a vector index to the Document.embedding field."}' \\
1217
- | jq -r .session_id)
1218
-
1219
- while [ "$(curl -s -u <user>:<pass> <ops-endpoint> -H 'Content-Type: application/json' \\
1220
- -d "{\\"operation\\":\\"get_agent_session\\",\\"session_id\\":\\"$SID\\"}" | jq -r .status)" = "running" ]; do
1221
- sleep 3
1222
- done
1223
- \`\`\`
1224
-
1225
- ## Notes
1226
-
1227
- - **All agent operations require super_user.** Authenticate with \`harper login\`, which stores a
1228
- short-lived JWT (operation token) plus a refresh token rather than your password — prefer that
1229
- over passing credentials inline, and never embed a raw password in scripts or client config.
1230
- - **Approvals are your safety gate.** With \`autoApprove:false\`, the agent pauses before destructive
1231
- tools (writing files, deploying, restarting) so an operator decides. Set \`autoApprove:true\` only
1232
- when you want unattended runs.
1233
- - **Sessions are single-active.** A session that is \`running\` or \`awaiting_approval\` rejects a new
1234
- \`agent_prompt\`; resolve the approval or cancel the run first.
1235
- - **MCP alternative.** For MCP-native clients, an instance with MCP enabled exposes the agent as
1236
- curated MCP tools (\`agent_prompt\`, \`get_agent_session\`, \`list_agent_sessions\`) at the ops API's
1237
- \`/mcp\` endpoint — the same delegation loop over the MCP transport instead of raw operations.
1238
- `,"deploying-to-harper-fabric":`---
1239
- name: deploying-to-harper-fabric
1240
- description: How to deploy a Harper application to the Harper Fabric cloud.
1241
- metadata:
1242
- mode: generate
1243
- sources:
1244
- - reference/v5/components/applications.md#Remote Management
1245
- - >-
1246
- fabric/cluster-creation-management.md#Connecting the Harper CLI to a
1247
- Cluster
1248
- sourceCommit: 677ad213d67822e109c83619e181ca23a59823db
1249
- inputHash: e5586ad2bcc7c12a
1250
- ---
1251
-
1252
- # Deploying to Harper Fabric
1253
-
1254
- Instructions for the agent to follow when deploying a Harper application to a remote Harper Fabric cloud cluster.
1255
-
1256
- ## When to Use
1257
-
1258
- Apply this rule when deploying a Harper application to a remote Harper Fabric cluster or any remote Harper instance. This includes first-time deploys, redeployments, rollbacks, CI/CD pipeline deploys, and provisioning credentials for private repositories. See [creating-a-fabric-account-and-cluster.md](creating-a-fabric-account-and-cluster.md) for setting up the cluster before deploying.
1259
-
1260
- ## How It Works
1261
-
1262
- 1. **Authenticate against the remote cluster**: Run \`harper login\` once, pointing at the cluster's Application URL (found on the cluster's **Config → Overview** page). The CLI stores the token and writes \`HARPER_CLI_TARGET\` to a local \`.env\`.
1263
-
1264
- \`\`\`bash
1265
- harper login <Application URL>
1266
- # Provide cluster username and password when prompted
1267
- \`\`\`
1268
-
1269
- 2. **Deploy the application**: After login, run \`harper deploy\` without repeating credentials. Set \`restart=true\` and \`replicated=true\` for a production deploy.
1270
-
1271
- \`\`\`bash
1272
- harper deploy \\
1273
- project=<name> \\
1274
- package=<package> \\
1275
- target=<remote> \\
1276
- restart=true \\
1277
- replicated=true
1278
- \`\`\`
1279
-
1280
- 3. **Use environment variables for CI/CD**: Instead of \`harper login\`, export credentials as environment variables before calling \`harper deploy\`.
1281
-
1282
- \`\`\`bash
1283
- export HARPER_CLI_USERNAME=<username>
1284
- export HARPER_CLI_PASSWORD=<password>
1285
- harper deploy \\
1286
- project=<name> \\
1287
- package=<package> \\
1288
- target=<remote> \\
1289
- restart=true \\
1290
- replicated=true
1291
- \`\`\`
1292
-
1293
- 4. **Choose a package source**: The \`package\` field accepts any valid npm dependency value. Select the form that matches your source:
1294
-
1295
- | Source | \`package\` value |
1296
- | ----------------------- | ---------------------------------------------------- |
1297
- | Current local directory | Omit \`package\` |
1298
- | npm package | \`"@harperdb/status-check"\` |
1299
- | GitHub (public) | \`"HarperFast/status-check"\` or full URL |
1300
- | Private repo (SSH) | \`"git+ssh://git@github.com:HarperDB/secret-app.git"\` |
1301
- | Tarball | \`"https://example.com/application.tar.gz"\` |
1302
-
1303
- For git tags, use the \`semver\` directive:
1304
-
1305
- \`\`\`
1306
- HarperFast/application-template#semver:v1.0.0
1307
- \`\`\`
1308
-
1309
- 5. **Deploy by reference for reproducible deploys**: Pass \`by_ref=true\` to send a pinned git SHA instead of uploading a snapshot. The cluster fetches and builds from that exact commit.
1310
-
1311
- \`\`\`bash
1312
- harper deploy by_ref=true restart=true replicated=true
1313
- \`\`\`
1314
-
1315
- Use \`ref\` to target a specific commit, tag, or branch (resolved to a full SHA before sending):
1316
-
1317
- \`\`\`bash
1318
- # Deploy a specific tag
1319
- harper deploy ref=v1.2.0 restart=true replicated=true
1320
-
1321
- # Roll back by deploying an older commit
1322
- harper deploy ref=9f8c2a1 restart=true replicated=true
1323
- \`\`\`
1324
-
1325
- **Key constraints for \`ref\` values:**
1326
- - Must name something a clone can fetch: \`refs/heads/*\` and \`refs/tags/*\`, or a bare branch or tag name.
1327
- - Anything else (e.g., \`refs/pull/123/head\`) is rejected up front.
1328
- - If a ref can't be resolved, the deploy stops — run \`git fetch\` and retry, or pass a full commit SHA.
1329
- - Commit and push before deploying: the cluster clones from the remote and only sees pushed commits.
1330
-
1331
- 6. **Deploy private repositories by reference**: Pass \`credential=true\` alongside \`by_ref=true\`. The CLI attaches a credentials reference; the cluster resolves the secret in memory at clone time — no token travels in the operation body or lands on disk.
1332
-
1333
- \`\`\`bash
1334
- harper deploy by_ref=true credential=true restart=true replicated=true
1335
- \`\`\`
1336
-
1337
- 7. **Provision a deploy credential for private sources**: Run \`harper deploy setup=true\` once per component and source. This is interactive and requires **super_user** — run it with an administrative credential, not the CI identity.
1338
-
1339
- \`\`\`bash
1340
- harper deploy setup=true
1341
- \`\`\`
1342
-
1343
- This command:
1344
- 1. Fetches the cluster's public key with \`get_secrets_public_key\`.
1345
- 2. Encrypts the token locally into an \`enc:v1:\` envelope.
1346
- 3. Stores only the ciphertext with \`set_secret\`, in the component-scoped tier.
1347
- 4. Grants the component permission to resolve it with \`grant_secret\`.
1348
- 5. Prints the \`credentials\` reference for the deploy to use.
1349
-
1350
- Use a **fine-grained** personal access token (PAT) scoped to **Contents: Read-only** on the specific repository. Avoid session tokens from \`gh\` CLI — they typically carry \`repo\`, \`read:org\`, \`gist\`, and \`workflow\` scopes across your whole account.
1351
-
1352
- ## Examples
1353
-
1354
- **Standard deploy after login:**
1355
-
1356
- \`\`\`bash
1357
- harper login https://my-cluster.harperdbcloud.com
1358
- harper deploy \\
1359
- project=my-app \\
1360
- package="HarperFast/my-app" \\
1361
- target=https://my-cluster.harperdbcloud.com \\
1362
- restart=true \\
1363
- replicated=true
1364
- \`\`\`
1365
-
1366
- **CI/CD deploy using environment variables:**
1367
-
1368
- \`\`\`bash
1369
- export HARPER_CLI_USERNAME=admin
1370
- export HARPER_CLI_PASSWORD=secret
1371
- harper deploy \\
1372
- project=my-app \\
1373
- package="HarperFast/my-app" \\
1374
- target=https://my-cluster.harperdbcloud.com \\
1375
- restart=true \\
1376
- replicated=true
1377
- \`\`\`
1378
-
1379
- **Deploy by reference in GitHub Actions (pull request):**
1380
-
1381
- \`\`\`bash
1382
- harper deploy ref=\${{ github.event.pull_request.head.sha }} restart=true replicated=true
1383
- \`\`\`
1384
-
1385
- **Deploy a private repo by reference with a provisioned credential:**
1386
-
1387
- \`\`\`bash
1388
- # Provision once (run as super_user)
1389
- harper deploy setup=true
1390
-
1391
- # Deploy subsequently
1392
- harper deploy by_ref=true credential=true restart=true replicated=true
1393
- \`\`\`
1394
-
1395
- ## Notes
1396
-
1397
- - \`auth_username\` and \`auth_password\` can be passed directly as deploy parameters for one-off commands, but this is not recommended for production. Dedicated authentication parameters take precedence over environment variables and saved login tokens.
1398
- - The \`enc:v1:\` envelope means the plaintext token never leaves your machine — only ciphertext is stored and replicated.
1399
- - Deploy credentials are stored scoped to the component, never in the global \`processEnv\` tier. If a global secret exists at the derived name, it is converted to the component-scoped tier automatically.
1400
- - Because stored credentials are durable, later deploys and rollbacks reuse them without re-entering anything.
1401
- - The unpushed-commit check is skipped under GitHub Actions; the dirty-tree warning still applies.
1402
- - Deploying by reference means the cluster installs and builds from source. If your application requires a build step that cannot run on the node, deploy the built output as a payload deploy instead.
1403
- - For SSH-based private repos, use the \`add_ssh_key\` operation to register keys before deploying.
1404
- `,"extending-tables":`---
1405
- name: extending-tables
1406
- description: How to add custom logic to automatically generated table resources in Harper.
1407
- metadata:
1408
- mode: generate
1409
- sources:
1410
- - reference/v5/resources/overview.md#Extending a Table
1411
- - reference/v5/resources/resource-api.md#Throwing Errors
1412
- sourceCommit: ce0ab713d918d789bc1c9f22e461e963ccc1dff1
1413
- inputHash: 19738fbc732e0a1a
1414
- ---
1415
-
1416
- # Extending Tables
1417
-
1418
- Instructions for the agent to follow when adding custom logic to automatically generated table resources in Harper.
1419
-
1420
- ## When to Use
1421
-
1422
- Apply this rule when you need to add computed properties, intercept writes, enforce validation, or otherwise customize the behavior of a Harper table resource beyond what the default generated endpoints provide. Use it any time a \`@table\` type needs server-side logic attached to its REST handlers.
1423
-
1424
- ## How It Works
1425
-
1426
- 1. **Define the schema without \`@export\`**: Declare the table type in \`schema.graphql\` and omit the \`@export\` directive. Leaving \`@export\` on the schema while also exporting a subclass with the same name produces conflicting endpoints. Let the JavaScript class own the URL instead.
1427
-
1428
- \`\`\`graphql
1429
- # Omit the \`@export\` directive
1430
- type MyTable @table {
1431
- id: Long @primaryKey
1432
- # ...
1433
- }
1434
- \`\`\`
1435
-
1436
- 2. **Extend the generated table class**: In \`resources.js\`, extend from the \`tables.<TypeName>\` global. The class name you export becomes the URL path. The exported class extends tables.
1437
-
1438
- \`\`\`javascript
1439
- export class MyTable extends tables.MyTable {
1440
- static async get(target) {
1441
- const record = await super.get(target);
1442
- return { ...record, computedField: 'value' };
1443
- }
1444
-
1445
- static async post(target, data) {
1446
- this.create({ ...(await data), status: 'pending' });
1447
- }
1448
- }
1449
- \`\`\`
1450
-
1451
- 3. **Call \`super\` to preserve default behavior**: When delegating to \`super\`, match the argument form to the operation:
1452
- - Reads/deletes: \`super.get(target)\` / \`super.delete(target)\`
1453
- - Collection create: \`super.post(target, record)\` — target carries no id
1454
- - Updates: \`super.put(target, data)\` / \`super.patch(target, data)\`
1455
-
1456
- Omit the \`super\` call only if you intend to replace the default behavior entirely.
1457
-
1458
- 4. **Set \`statusCode\` on thrown errors to control HTTP responses**: Uncaught errors are caught by the protocol handler and produce error responses for REST. Use \`.statusCode\` — a plain \`.status\` property is ignored.
1459
-
1460
- \`\`\`javascript
1461
- const error = new Error('Name is required');
1462
- error.statusCode = 400; // use statusCode, NOT status
1463
- throw error;
1464
- \`\`\`
1465
-
1466
- 5. **Configure Harper to load both files**: Ensure your configuration references the schema and resource files.
1467
-
1468
- \`\`\`yaml
1469
- rest: true
1470
- graphqlSchema:
1471
- files: schema.graphql
1472
- jsResource:
1473
- files: resources.js
1474
- \`\`\`
1475
-
1476
- ## Examples
1477
-
1478
- Full end-to-end example — schema, resource class, and error handling:
1479
-
1480
- \`\`\`graphql
1481
- # schema.graphql — omit @export so the JS class owns the endpoint
1482
- type MyTable @table {
1483
- id: Long @primaryKey
1484
- }
1485
- \`\`\`
1486
-
1487
- \`\`\`javascript
1488
- // resources.js
1489
- export class MyTable extends tables.MyTable {
1490
- static async get(target) {
1491
- // get the record from the database
1492
- const record = await super.get(target);
1493
- // add a computed property before returning
1494
- return { ...record, computedField: 'value' };
1495
- }
1496
-
1497
- static async post(target, data) {
1498
- // custom action on POST
1499
- this.create({ ...(await data), status: 'pending' });
1500
- }
1501
- }
1502
- \`\`\`
1503
-
1504
- Throwing a controlled HTTP error:
1505
-
1506
- \`\`\`javascript
1507
- if (!authorized) {
1508
- const error = new Error('Forbidden');
1509
- error.statusCode = 403;
1510
- throw error;
1511
- }
1512
- \`\`\`
1513
-
1514
- ## Notes
1515
-
1516
- - Always omit \`@export\` from the schema type when a JavaScript subclass is exporting the same name. The two registrations conflict.
1517
- - \`super\` must be called with the correct arguments for each operation type — mismatched arguments will not behave as expected.
1518
- - \`statusCode\` is the only recognized property for controlling HTTP status on thrown errors; \`.status\` is ignored.
1519
- `,"handling-binary-data":`---
1520
- name: handling-binary-data
1521
- description: How to store and serve binary data like images or audio in Harper.
1522
- metadata:
1523
- mode: generate
1524
- sources:
1525
- - reference/v5/database/api.md#Accepting Binary in JSON Requests
1526
- - reference/v5/database/api.md#Serving Binary from a Resource
1527
- - reference/v5/rest/content-types.md#Storing Arbitrary Content Types
1528
- sourceCommit: ce0ab713d918d789bc1c9f22e461e963ccc1dff1
1529
- inputHash: fa06480e6fae7614
1530
- ---
1531
-
1532
- # Handling Binary Data
1533
-
1534
- Instructions for the agent to follow when storing and serving binary data (images, audio, arbitrary content types) in Harper.
1535
-
1536
- ## When to Use
1537
-
1538
- Apply this rule when a Harper resource needs to accept, store, or serve binary payloads such as images, audio files, or calendar data. Use it when REST clients send \`base64\`-encoded data inside JSON, when raw binary is uploaded via \`PUT\`/\`POST\`, or when a resource must stream binary back to the client with the correct \`Content-Type\`.
1539
-
1540
- ## How It Works
1541
-
1542
- 1. **Accept base64-encoded binary from JSON clients**: Decode the incoming \`base64\` string with \`Buffer.from\` and wrap it using \`createBlob\`, recording the MIME type. Override \`post\` in your resource class:
1543
-
1544
- \`\`\`typescript
1545
- import { type RequestTargetOrId, tables, createBlob } from 'harper';
1546
-
1547
- export class Photo extends tables.Photo {
1548
- static async post(target: RequestTargetOrId, record: any) {
1549
- if (record.data) {
1550
- record.data = createBlob(Buffer.from(record.data, record.encoding || 'base64'), {
1551
- type: record.contentType || 'application/octet-stream',
1552
- });
1553
- }
1554
- return super.post(target, record);
1555
- }
1556
- }
1557
- \`\`\`
1558
-
1559
- 2. **Serve binary from a resource**: Override \`get\` to return a response object with the blob's MIME type in the \`Content-Type\` header and the blob as the body. Harper streams it to the client:
1560
-
1561
- \`\`\`typescript
1562
- export class Photo extends tables.Photo {
1563
- static async get(target: RequestTargetOrId) {
1564
- const record = await super.get(target);
1565
- if (record?.data) {
1566
- return {
1567
- status: 200,
1568
- headers: { 'Content-Type': record.data.type || 'application/octet-stream' },
1569
- body: record.data,
1570
- };
1571
- }
1572
- return record;
1573
- }
1574
- }
1575
- \`\`\`
1576
-
1577
- 3. **Upload raw binary with a non-standard content type**: Make a \`PUT\` or \`POST\` with any non-standard \`Content-Type\` header. Harper automatically stores the body as a record with \`contentType\` and \`data\` properties:
1578
-
1579
- \`\`\`http
1580
- PUT /my-resource/33
1581
- Content-Type: text/calendar
1582
-
1583
- BEGIN:VCALENDAR
1584
- VERSION:2.0
1585
- ...
1586
- \`\`\`
1587
-
1588
- Harper stores this as:
1589
-
1590
- \`\`\`json
1591
- { "contentType": "text/calendar", "data": "BEGIN:VCALENDAR\\nVERSION:2.0\\n..." }
1592
- \`\`\`
1593
-
1594
- Retrieving that record returns the response with the stored \`Content-Type\` and body. If the content type is not from the \`text\` family, the data is treated as binary (a Node.js \`Buffer\`).
1595
-
1596
- 4. **Upload binary to a specific property**: Use \`application/octet-stream\` (or any image/binary MIME type) and target a sub-path to store binary directly on a property:
1597
-
1598
- \`\`\`http
1599
- PUT /my-resource/33/image
1600
- Content-Type: image/gif
1601
-
1602
- ...image data...
1603
- \`\`\`
1604
-
1605
- ## Examples
1606
-
1607
- **End-to-end: accept base64 JSON, store as blob, serve as binary**
1608
-
1609
- \`\`\`typescript
1610
- import { type RequestTargetOrId, tables, createBlob } from 'harper';
1611
-
1612
- export class Photo extends tables.Photo {
1613
- // Accept base64-encoded uploads in JSON
1614
- static async post(target: RequestTargetOrId, record: any) {
1615
- if (record.data) {
1616
- record.data = createBlob(Buffer.from(record.data, record.encoding || 'base64'), {
1617
- type: record.contentType || 'application/octet-stream',
1618
- });
1619
- }
1620
- return super.post(target, record);
1621
- }
1622
-
1623
- // Stream the blob back with the correct Content-Type
1624
- static async get(target: RequestTargetOrId) {
1625
- const record = await super.get(target);
1626
- if (record?.data) {
1627
- return {
1628
- status: 200,
1629
- headers: { 'Content-Type': record.data.type || 'application/octet-stream' },
1630
- body: record.data,
1631
- };
1632
- }
1633
- return record;
1634
- }
1635
- }
1636
- \`\`\`
1637
-
1638
- ## Notes
1639
-
1640
- - \`createBlob\` takes a \`Buffer\` as its first argument and an options object with a \`type\` property for the MIME type. See [using-blob-datatype.md](using-blob-datatype.md) for full details on the blob data type.
1641
- - Always fall back to \`application/octet-stream\` when no MIME type is known, both when creating and when serving blobs.
1642
- - When Harper retrieves a record that has both \`contentType\` and \`data\` properties, it automatically sets the response \`Content-Type\` and body — no custom \`get\` override is required for that case unless you need additional logic.
1643
- - Non-\`text\` content types cause \`data\` to be stored and returned as a Node.js \`Buffer\`.
1644
- `,"load-env":`---
1645
- name: load-env
1646
- description: >-
1647
- How to load environment variables from .env files into a Harper application
1648
- using the loadEnv plugin.
1649
- metadata:
1650
- mode: generate
1651
- sources:
1652
- - reference/v5/environment-variables/overview.md
1653
- sourceCommit: 3749d0c54be457a2a65d9a63c738a5dc88989ecd
1654
- inputHash: b4db5ede6b93d426
1655
- ---
1656
-
1657
- # Load Environment Variables with loadEnv
1658
-
1659
- Instructions for the agent to follow when loading environment variables from \`.env\` files into a Harper application using the \`loadEnv\` plugin.
1660
-
1661
- ## When to Use
1662
-
1663
- Apply this rule when a Harper application needs to supply secrets, API endpoints, or other configuration values to component code via \`process.env\` without hardcoding them. Use \`loadEnv\` any time you need to load one or more \`.env\` files at application startup.
1664
-
1665
- ## How It Works
1666
-
1667
- 1. **Declare \`loadEnv\` in \`config.yaml\`**: Add \`loadEnv\` as the first entry in \`config.yaml\`. It is built into Harper and requires no installation.
1668
-
1669
- \`\`\`yaml
1670
- loadEnv:
1671
- files: '.env'
1672
- \`\`\`
1673
-
1674
- 2. **Place \`loadEnv\` first**: Harper is a single-process application. List \`loadEnv\` before all other components so that environment variables are available on \`process.env\` before dependent components start.
1675
-
1676
- \`\`\`yaml
1677
- # config.yaml — loadEnv must come first
1678
- loadEnv:
1679
- files: '.env'
1680
-
1681
- rest: true
1682
-
1683
- myApp:
1684
- files: './src/*.js'
1685
- \`\`\`
1686
-
1687
- 3. **Access loaded values in component code**: After \`loadEnv\` runs, all loaded values are available on \`process.env\` and shared across all components.
1688
-
1689
- 4. **Control override behavior**: By default, existing environment variables take precedence over values in \`.env\` files. Set \`override: true\` to make loaded values win instead.
1690
-
1691
- \`\`\`yaml
1692
- loadEnv:
1693
- files: '.env'
1694
- override: true
1695
- \`\`\`
1696
-
1697
- 5. **Load multiple files**: Pass an array of paths or a glob pattern to \`files\`. Files are loaded in the order specified.
1698
-
1699
- \`\`\`yaml
1700
- loadEnv:
1701
- files:
1702
- - '.env'
1703
- - '.env.local'
1704
- \`\`\`
1705
-
1706
- or with a glob:
1707
-
1708
- \`\`\`yaml
1709
- loadEnv:
1710
- files: 'env-vars/*'
1711
- \`\`\`
1712
-
1713
- ### Configuration Options
1714
-
1715
- | Option | Type | Required | Description |
1716
- | ---------- | -------------------- | -------- | -------------------------------------------------------------------------------------- |
1717
- | \`files\` | \`string \\| string[]\` | **Yes** | Path(s) or glob pattern(s) to the env file(s) to load. |
1718
- | \`override\` | \`boolean\` | No | If \`true\`, loaded values override existing environment variables. Defaults to \`false\`. |
1719
-
1720
- ## Examples
1721
-
1722
- **Single file, default behavior:**
1723
-
1724
- \`\`\`yaml
1725
- # config.yaml
1726
- loadEnv:
1727
- files: '.env'
1728
-
1729
- rest: true
1730
-
1731
- myApp:
1732
- files: './src/*.js'
1733
- \`\`\`
1734
-
1735
- **Multiple files with override:**
1736
-
1737
- \`\`\`yaml
1738
- # config.yaml
1739
- loadEnv:
1740
- files:
1741
- - '.env'
1742
- - '.env.local'
1743
- override: true
1744
-
1745
- rest: true
1746
-
1747
- myApp:
1748
- files: './src/*.js'
1749
- \`\`\`
1750
-
1751
- ## Notes
1752
-
1753
- - \`loadEnv\` loads values into \`process.env\` for **application** code only — it does not configure Harper itself.
1754
- - Harper's own instance-wide configuration is composed at startup **before** any component's \`loadEnv\` runs. Variables such as \`HARPER_CONFIG\`, \`HARPER_SET_CONFIG\`, and \`HARPER_DEFAULT_CONFIG\` delivered through a \`.env\` file are read too late and are ignored. Set Harper configuration directly in the configuration file or export variables in the real process/container environment before Harper starts.
1755
- - For production credentials, prefer the encrypted secrets store over a committed \`.env\` file. Secrets are also delivered to components via \`process.env\`.
1756
- `,logging:`---
1757
- name: logging
1758
- description: >-
1759
- Best practices for logging in Harper, including console capture, the granular
1760
- logger interface, and programmatic log retrieval.
1761
- metadata:
1762
- mode: generate
1763
- sources:
1764
- - reference/v5/logging/overview.md
1765
- - reference/v5/logging/api.md
1766
- sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819
1767
- inputHash: 46cd384598304e3b
1768
- ---
1769
-
1770
- # Harper Logging
1771
-
1772
- Instructions for the agent to follow when implementing logging in Harper applications, including direct logger usage, tagged loggers, and console capture behavior.
1773
-
1774
- ## When to Use
1775
-
1776
- Apply this rule when writing any JavaScript component, plugin, or resource that needs to emit structured log entries, filter logs by component, or capture existing \`console.log\` output into Harper's log system. Use it whenever you need to understand log levels, log entry format, or the \`logger\` global API.
1777
-
1778
- ## How It Works
1779
-
1780
- 1. **Use the \`logger\` global directly** — \`logger\` is available in all JavaScript components without any imports. Call the method matching the desired severity level:
1781
-
1782
- \`\`\`javascript
1783
- logger.trace('detailed trace message');
1784
- logger.debug('debug info', { someContext: 'value' });
1785
- logger.info('informational message');
1786
- logger.warn('potential issue');
1787
- logger.error('error occurred', error);
1788
- logger.fatal('fatal error');
1789
- logger.notify('server is ready');
1790
- \`\`\`
1791
-
1792
- Only entries at or above the configured \`logging.level\` (or \`logging.external.level\`) are written to \`hdb.log\`.
1793
-
1794
- 2. **Create a tagged logger with \`withTag(\`** — Call \`logger.withTag(tag)\` once per module or class to get a \`TaggedLogger\` scoped to that tag. This prefixes every log entry with the tag, making log output filterable by component.
1795
-
1796
- \`\`\`javascript
1797
- const log = logger.withTag('my-resource');
1798
- \`\`\`
1799
-
1800
- Because \`TaggedLogger\` methods for disabled levels are \`null\`, always use optional chaining (\`?.\`) when calling them:
1801
-
1802
- \`\`\`javascript
1803
- log.debug?.('Fetching record', { id });
1804
- log.warn?.('Record not found', { id });
1805
- log.error?.('Failed to update record', err);
1806
- \`\`\`
1807
-
1808
- \`TaggedLogger\` does not have a \`withTag()\` method.
1809
-
1810
- 3. **Understand the interface contracts** — \`MainLogger\` always has all methods defined:
1811
-
1812
- \`\`\`typescript
1813
- interface MainLogger {
1814
- trace(...messages: any[]): void;
1815
- debug(...messages: any[]): void;
1816
- info(...messages: any[]): void;
1817
- warn(...messages: any[]): void;
1818
- error(...messages: any[]): void;
1819
- fatal(...messages: any[]): void;
1820
- notify(...messages: any[]): void;
1821
- withTag(tag: string): TaggedLogger;
1822
- }
1823
- \`\`\`
1824
-
1825
- \`TaggedLogger\` methods may be \`null\`:
1826
-
1827
- \`\`\`typescript
1828
- interface TaggedLogger {
1829
- trace: ((...messages: any[]) => void) | null;
1830
- debug: ((...messages: any[]) => void) | null;
1831
- info: ((...messages: any[]) => void) | null;
1832
- warn: ((...messages: any[]) => void) | null;
1833
- error: ((...messages: any[]) => void) | null;
1834
- fatal: ((...messages: any[]) => void) | null;
1835
- notify: ((...messages: any[]) => void) | null;
1836
- }
1837
- \`\`\`
1838
-
1839
- 4. **Know the log levels** — From least to most severe:
1840
-
1841
- | Level | Description |
1842
- | -------- | -------------------------------------------------------------------- |
1843
- | \`trace\` | Highly detailed internal execution tracing. |
1844
- | \`debug\` | Diagnostic information useful during development. |
1845
- | \`info\` | General operational events. |
1846
- | \`warn\` | Potential issues that don't prevent normal operation. |
1847
- | \`error\` | Errors that affect specific operations. |
1848
- | \`fatal\` | Critical errors causing process termination. |
1849
- | \`notify\` | Important operational milestones. Always logged regardless of level. |
1850
-
1851
- The default log level is \`warn\`. Setting a level includes that level and all more-severe levels.
1852
-
1853
- 5. **Enable console capture when porting existing code** — When \`logging.console: true\` is set, writes via \`console.log\`, \`console.warn\`, \`console.error\`, etc. are appended verbatim to \`hdb.log\`. Captured lines do **not** pass through \`logger\`'s level filter. Prefer \`logger\` directly in production code so that level filtering and tagging apply. Console capture is intended as a convenience for porting existing code and for debugging.
1854
-
1855
- 6. **Know where logs are written** — All standard log output goes to \`<ROOTPATH>/log/hdb.log\` (default: \`~/hdb/log/hdb.log\`). To also log to \`stdout\`/\`stderr\`, set \`logging.stdStreams: true\`.
1856
-
1857
- ## Examples
1858
-
1859
- ### Basic logging in a resource
1860
-
1861
- \`\`\`javascript
1862
- export class MyResource extends Resource {
1863
- async get(id) {
1864
- logger.debug('Fetching record', { id });
1865
- const record = await super.get(id);
1866
- if (!record) {
1867
- logger.warn('Record not found', { id });
1868
- }
1869
- return record;
1870
- }
1871
-
1872
- async put(record) {
1873
- logger.info('Updating record', { id: record.id });
1874
- try {
1875
- return await super.put(record);
1876
- } catch (err) {
1877
- logger.error('Failed to update record', err);
1878
- throw err;
1879
- }
1880
- }
1881
- }
1882
- \`\`\`
1883
-
1884
- ### Tagged logging with \`withTag()\`
1885
-
1886
- \`\`\`javascript
1887
- const log = logger.withTag('my-resource');
1888
-
1889
- export class MyResource extends Resource {
1890
- async get(id) {
1891
- log.debug?.('Fetching record', { id });
1892
- const record = await super.get(id);
1893
- if (!record) {
1894
- log.warn?.('Record not found', { id });
1895
- }
1896
- return record;
1897
- }
1898
-
1899
- async put(record) {
1900
- log.info?.('Updating record', { id: record.id });
1901
- try {
1902
- return await super.put(record);
1903
- } catch (err) {
1904
- log.error?.('Failed to update record', err);
1905
- throw err;
1906
- }
1907
- }
1908
- }
1909
- \`\`\`
1910
-
1911
- Tagged entries appear in \`hdb.log\` with the tag in the header:
1912
-
1913
- \`\`\`
1914
- 2023-03-09T14:25:05.269Z [info] [my-resource]: Updating record
1915
- \`\`\`
1916
-
1917
- ## Notes
1918
-
1919
- - All log output is written to \`<ROOTPATH>/log/hdb.log\`. The \`logger\` global writes to this file at the configured \`logging.external\` level.
1920
- - Log entry format for \`logger\`: \`<timestamp> [<level>] [<thread>/<id>]: <message>\`
1921
- - Log entry format for \`TaggedLogger\`: \`<timestamp> [<level>] [<tag>]: <message>\`
1922
- - \`console.log\` output is only forwarded to \`hdb.log\` when \`logging.console: true\` is explicitly set; it is not forwarded by default.
1923
- - When logging to standard streams, run Harper in the foreground (\`harper\`, not \`harper start\`).
1924
- - \`TaggedLogger\` is bound to the configured log level at creation time — always use \`?.\` on its methods.
1925
- `,"programmatic-table-requests":"---\nname: programmatic-table-requests\ndescription: How to interact with Harper tables programmatically using the `tables` object.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/api.md#`tables`\n - reference/v5/resources/resource-api.md#Query Object\n - 'reference/v5/database/api.md#`transaction(context?, callback)`'\n - >-\n reference/v5/resources/resource-api.md#`update(target: RequestTarget | Id,\n updates?: object): Promise<Resource>`\n - >-\n reference/v5/resources/resource-api.md#`addTo(property: string, value:\n number)`\n - reference/v5/components/javascript-environment.md#Module Formats\n sourceCommit: 9e6ecf87dd25bb488ad44dc2876ca6439ccd682e\n inputHash: f5629f73cde74764\n---\n\n# Programmatic Table Requests\n\nInstructions for the agent to interact with Harper tables programmatically using the `tables` object, the Query API, and transactions.\n\n## When to Use\n\nApply this rule when writing server-side Harper component code that reads from or writes to tables directly — for example, in HTTP handlers, background jobs, timers, or SSR render functions. Use it whenever you need to construct queries with `conditions`, `sort`, `select`, `limit`, or `offset`, or when you need explicit transaction control via `transaction()`.\n\n## How It Works\n\n1. **Import `tables` (and other APIs) from `harper`**: Access every table defined in `schema.graphql` as a named property of `tables`. Each property is the table class implementing the Resource API.\n\n ```javascript\n import { tables, transaction } from 'harper';\n const { Product } = tables;\n // equivalent to: databases.data.Product\n ```\n\n For standalone components, run `npm link harper` so imports resolve to the live runtime.\n\n2. **Define your schema with `@table`**: Tables must be declared in `schema.graphql`. Mark attributes you intend to sort or filter on with `@indexed`.\n\n ```graphql\n type Product @table {\n id: Long @primaryKey\n name: String\n price: Float\n }\n ```\n\n3. **Query records with `search(`**: Pass a Query object to `search(`. Iterate results with `for await`.\n\n ```javascript\n const query = {\n conditions: [{ attribute: 'price', comparator: 'less_than', value: 8.0 }],\n };\n for await (const record of Product.search(query)) {\n // process record\n }\n ```\n\n4. **Build `conditions`**: Each condition object supports these properties:\n\n | Property | Description |\n | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |\n | `attribute` | Property name, or array for chained/joined properties (e.g. `['brand', 'name']`) |\n | `value` | The value to match |\n | `comparator` | `equals` (default), `greater_than`, `greater_than_equal`, `less_than`, `less_than_equal`, `starts_with`, `contains`, `ends_with`, `between`, `not_equal` |\n | `conditions` | Nested conditions array |\n | `operator` | `and` (default) or `or` for the nested `conditions` |\n\n5. **Control result shape with `select`**: Pass an array of property names, a single string, or nested objects for relationships.\n\n ```javascript\n // Scalar fields only\n Product.search({ select: ['name', 'price'] });\n\n // Partial related record\n Book.get({ id: 42, select: ['id', 'title', { name: 'author', select: ['name'] }] });\n ```\n\n Special `select` values: `$id`, `$updatedtime`, `$distance`.\n\n6. **Paginate with `limit` and `offset`**:\n\n ```javascript\n Product.search({ conditions: [...], limit: 20, offset: 40 });\n ```\n\n7. **Sort with `sort`**: The `sort` object accepts `attribute`, `descending` (default `false`), and `next` for tie-breaking. Harper uses an index for sort order — the sort `attribute` must be `@indexed`, **or** at least one entry in `conditions` must be present.\n\n Sorting by a non-indexed attribute with zero conditions raises:\n\n > `HdbError: <attribute> is not indexed and not combined with any other conditions`\n\n Note: `@primaryKey` alone is treated as not indexed for sort purposes. To scan the whole table in primary-key order, add an open-ended condition:\n\n ```javascript\n Product.search({\n conditions: [{ attribute: 'id', comparator: 'greater_than', value: '' }],\n sort: { attribute: 'id' },\n });\n ```\n\n Alternatively, pass `allowFullScan: true` to permit an unconditional ordered scan, or omit `sort` entirely to iterate without an index requirement.\n\n8. **Debug query planning with `explain` and `enforceExecutionOrder`**:\n - `explain: true` — returns conditions reordered as Harper will execute them.\n - `enforceExecutionOrder: true` — forces conditions to execute in the order supplied, disabling automatic re-ordering.\n\n9. **Use `addTo` for concurrent-safe numeric updates**: `addTo` uses CRDT incrementation, safe across threads and nodes.\n\n ```javascript\n const record = await Product.update(32);\n record.addTo('quantity', -1);\n ```\n\n10. **Wrap background work in `transaction()`**: HTTP handlers get a transaction automatically. Use `transaction()` explicitly for timers, background jobs, or any code outside a request context. Always `await` the call and `catch` errors.\n\n ```javascript\n await transaction(async (txn) => {\n for (let item of data) {\n await MyTable.put(item, txn);\n }\n });\n ```\n\n The `txn` object exposes:\n\n | Member | Description |\n | --------------------- | ------------------------------------------------------ |\n | `commit()` | Commits the current transaction |\n | `abort()` | Aborts and resets the transaction |\n | `resetReadSnapshot()` | Resets the read snapshot to the latest committed state |\n | `timestamp` | Timestamp associated with the current transaction |\n\n **Atomicity**: all tables in the same database share one transactional context — writes across multiple tables commit atomically. Tables in different databases each get their own transaction with no cross-database atomicity guarantee.\n\n If `transaction()` is called with a context that already has an active transaction, it reuses that transaction — safe to call defensively.\n\n11. **Keep `harper` external when bundling for SSR**: In `vite.config`, mark `harper` as external so it resolves to the runtime rather than being bundled.\n\n ```javascript\n // vite.config\n ssr: {\n external: ['harper'];\n }\n ```\n\n## Examples\n\n### Full CRUD sequence\n\n```javascript\nimport { tables } from 'harper';\nconst { Product } = tables;\n\n// Create\nconst created = await Product.create({ name: 'Shirt', price: 9.5 });\n\n// Patch\nawait Product.patch(created.id, { price: Math.round(created.price * 0.8 * 100) / 100 });\n\n// Retrieve by primary key\nconst record = await Product.get(created.id);\n\n// Query with conditions\nconst query = {\n conditions: [{ attribute: 'price', comparator: 'less_than', value: 8.0 }],\n};\nfor await (const record of Product.search(query)) {\n // process record\n}\n```\n\n### Nested conditions with `or`\n\n```javascript\nProduct.search({\n conditions: [\n { attribute: 'price', comparator: 'less_than', value: 100 },\n {\n operator: 'or',\n conditions: [\n { attribute: 'rating', comparator: 'greater_than', value: 4 },\n { attribute: 'featured', value: true },\n ],\n },\n ],\n});\n```\n\n### Chained attribute reference (join/relationship)\n\n```javascript\nProduct.search({ conditions: [{ attribute: ['brand', 'name'], value: 'Harper' }] });\n```\n\n### Background job with `transaction()`\n\n```javascript\nimport { isMainThread } from 'node:worker_threads';\nimport { tables, transaction } from 'harper';\nconst { MyTable } = tables;\n\nif (isMainThread) {\n let running = false;\n setInterval(async () => {\n if (running) return;\n running = true;\n try {\n let data = await (await fetch('https://example.com/data')).json();\n await transaction(async (txn) => {\n for (let item of data) {\n await MyTable.put(item, txn);\n }\n });\n } catch (error) {\n logger.error('hourly import failed', error);\n } finally {\n running = false;\n }\n }, 3600000);\n}\n```\n\n### SSR render with `tables`\n\n```typescript\nimport { tables } from 'harper';\n\nexport async function render(url: string): Promise<string> {\n const product = await tables.Product.get(idFromUrl(url));\n return renderToString(/* <App product={product} /> */);\n}\n```\n\n## Notes\n\n- `tables` and `databases` do **not** automatically apply role permissions — calls run in a trusted server-side context. Apply your own authorization controls before exposing results.\n- Destructive operations (`update`, `patch`, `delete`) act on live data and are not easily reversible. Scope them with specific `conditions` and validate the affected set before writing.\n- `tables` is the same live, process-wide object whether accessed as a global or via `import { tables } from 'harper'`. A record written through one component is immediately visible to every other.\n- Run `npm link harper` for components in their own directory to ensure typings match the running installation.\n","querying-rest-apis":'---\nname: querying-rest-apis\ndescription: \'How to use query parameters to filter, sort, and paginate Harper REST APIs.\'\nmetadata:\n mode: generate\n sources:\n - reference/v5/rest/querying.md\n sourceCommit: 677ad213d67822e109c83619e181ca23a59823db\n inputHash: 0f8efee293628a52\n---\n\n# Querying REST APIs\n\nInstructions for the agent to filter, sort, select, and paginate Harper REST API collections using URL query parameters.\n\n## When to Use\n\nApply this rule whenever building or modifying code that queries Harper REST collection endpoints. Use it when you need to filter records by attribute values, apply comparison operators, sort or paginate results, or join across related tables. See [automatic-apis.md](automatic-apis.md) for how Harper exposes tables as REST endpoints.\n\n## How It Works\n\n1. **Filter by attribute**: Add query parameters matching attribute names and values. The queried attribute must be indexed.\n\n ```\n GET /Product/?category=software\n GET /Product/?category=software&inStock=true\n ```\n\n2. **Apply comparison operators (FIQL syntax)**: Use FIQL operators in the query string for numeric, string, and date comparisons.\n\n | Operator | Meaning |\n | -------------------- | -------------------------------------- |\n | `==` | Equal |\n | `=lt=` | Less than |\n | `=le=` | Less than or equal |\n | `=gt=` | Greater than |\n | `=ge=` | Greater than or equal |\n | `=ne=`, `!=` | Not equal |\n | `=ct=` | Contains (strings) |\n | `=sw=`, `==<value>*` | Starts with (strings) |\n | `=ew=` | Ends with (strings) |\n | `=`, `===` | Strict equality (no type conversion) |\n | `!==` | Strict inequality (no type conversion) |\n\n ```\n GET /Product/?price=gt=100\n GET /Product/?price=le=20\n GET /Product/?name==Keyboard*\n GET /Product/?category=software&price=gt=100&price=lt=200\n ```\n\n For date fields, URL-encode colons as `%3A`:\n\n ```\n GET /Product/?listDate=gt=2017-03-08T09%3A30%3A00.000Z\n ```\n\n3. **Chain conditions for range queries**: Omit the attribute name on the second condition to apply it to the same attribute. Only `gt`/`ge` combined with `lt`/`le` is supported.\n\n ```\n GET /Product/?price=gt=100&lt=200\n ```\n\n4. **Apply type conversion**: For FIQL comparators, Harper converts values automatically. Use explicit prefixes to force a type.\n\n | Syntax | Behavior |\n | ----------------------------------------- | ------------------------------------------- |\n | `name==null` | Converts to `null` |\n | `name==123` | Converts to number if attribute is untyped |\n | `name==true` | Converts to boolean if attribute is untyped |\n | `name==number:123` | Explicit number conversion |\n | `name==boolean:true` | Explicit boolean conversion |\n | `name==string:some%20text` | Keep as string with URL decode |\n | `name==date:2024-01-05T20%3A07%3A27.955Z` | Explicit Date conversion |\n\n For strict operators (`=`, `===`, `!==`), no automatic type conversion is applied.\n\n5. **Combine conditions with OR logic**: Use `|` instead of `&`.\n\n ```\n GET /Product/?rating=5|featured=true\n ```\n\n6. **Group conditions**: Use parentheses or square brackets to control order of operations. Prefer square brackets when constructing queries from user input, since standard URI encoding safely encodes `[` and `]`.\n\n ```\n GET /Product/?rating=5|(price=gt=100&price=lt=200)\n GET /Product/?rating=5&[tag=fast|tag=scalable|tag=efficient]\n ```\n\n Construct from JavaScript:\n\n ```javascript\n let url = `/Product/?rating=5&[${tags.map(encodeURIComponent).join(\'|\')}]`;\n ```\n\n7. **Select specific properties with `select(`**: Append `select(...)` as a query function separated by `&`.\n\n | Syntax | Returns |\n | -------------------------------------- | ------------------------------------------- |\n | `?select(property)` | Values of a single property directly |\n | `?select(property1,property2)` | Objects with only the specified properties |\n | `?select([property1,property2])` | Arrays of property values |\n | `?select(property1,)` | Objects with a single specified property |\n | `?select(property{subProp1,subProp2})` | Nested objects with specific sub-properties |\n\n8. **Paginate with `limit(`**: Use `limit(end)` or `limit(start,end)` to control result count and offset.\n\n9. **Sort with `sort(`**: Use `sort(property)` or `sort(+property,-property,...)`. Prefix `+` or no prefix = ascending; `-` = descending.\n\n10. **Query across relationships**: Use dot-syntax to filter by related table attributes. Relationships must be defined in the schema using `@relationship`. Relationship attributes are not included by default — use `select()` to include them.\n\n ```\n GET /Product/?brand.name=Microsoft&select(name,brand{name})\n ```\n\n11. **Query for null values**: Use `=null` as the value to match null or non-null records.\n ```\n GET /Product/?discount=null\n ```\n\n## Examples\n\n**Filter with comparison operators and select:**\n\n```\nGET /Product/?category=software&price=gt=100&price=lt=200&select(name,price)\n```\n\n**Paginate and sort:**\n\n```\nGET /Product/?rating=gt=3&inStock=true&select(rating,name)&limit(20)\nGET /Product/?rating=gt=3&limit(10,30)\nGET /Product/?rating=gt=3&sort(+name)\nGET /Product/?sort(+rating,-price)\n```\n\n**OR logic with grouping:**\n\n```\nGET /Product/?price=lt=100|[rating=5&[tag=fast|tag=scalable|tag=efficient]&inStock=true]\n```\n\n**Relationship join with nested select:**\n\nDefine the schema:\n\n```graphql\ntype Product @table @export {\n id: Long @primaryKey\n name: String\n brandId: Long @indexed\n brand: Brand @relationship(from: "brandId")\n}\ntype Brand @table @export {\n id: Long @primaryKey\n name: String\n products: [Product] @relationship(to: "brandId")\n}\n```\n\nQuery with join:\n\n```\nGET /Product/?brand.name=Microsoft&select(name,brand{name,id})\nGET /Brand/?products.name=Keyboard\n```\n\n**Many-to-many relationship:**\n\n```graphql\ntype Product @table @export {\n id: Long @primaryKey\n name: String\n resellerIds: [Long] @indexed\n resellers: [Reseller] @relationship(from: "resellerIds")\n}\n```\n\n```\nGET /Product/?resellers.name=Cool Shop&select(id,name,resellers{name,id})\n```\n\n**Access a specific property by record ID:**\n\n```\nGET /MyTable/123.propertyName\n```\n\n## Notes\n\n- Only indexed attributes can be used as the primary filter attribute; when combining multiple attributes, only one needs to be indexed.\n- Relationship attributes are excluded from responses by default. Always use `select(` to include them.\n- When selecting a related attribute without filtering on it, the behavior is a LEFT JOIN — the property is omitted if the foreign key is null or references a non-existent record.\n- The suffixes `.json`, `.cbor`, `.msgpack`, and `.csv` in URL paths are reserved as content-type selectors and take precedence over a property of the same name.\n- Square brackets are preferred over parentheses when building grouped queries programmatically, because `[` and `]` are safely URL-encoded by standard encoding functions while `(` is not.\n',"real-time-apps":`---
1926
- name: real-time-apps
1927
- description: How to build real-time features in Harper using WebSockets and Pub/Sub.
1928
- metadata:
1929
- mode: generate
1930
- sources:
1931
- - reference/v5/rest/websockets.md
1932
- sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819
1933
- inputHash: a8afd4d3a52f77ba
1934
- ---
1935
-
1936
- # Real-Time Apps with WebSockets and Pub/Sub
1937
-
1938
- Instructions for the agent to follow when building real-time features in Harper using WebSockets and Pub/Sub.
1939
-
1940
- ## When to Use
1941
-
1942
- Apply this rule when implementing any feature that requires real-time bidirectional communication, live data streaming, or push-based updates in a Harper application. This includes chat, live dashboards, sensor feeds, and any scenario where clients must receive resource changes as they happen.
1943
-
1944
- ## How It Works
1945
-
1946
- 1. **Enable WebSocket support**: WebSocket support is enabled automatically when the \`rest\` plugin is enabled. To explicitly disable it, set the following in your config:
1947
-
1948
- \`\`\`yaml
1949
- rest:
1950
- webSocket: false
1951
- \`\`\`
1952
-
1953
- 2. **Connect a client to a resource**: A WebSocket connection to a resource URL automatically subscribes to that resource. When the record changes or a message is published to it, the connection receives the update.
1954
-
1955
- \`\`\`javascript
1956
- let ws = new WebSocket('wss://server/my-resource/341');
1957
- ws.onmessage = (event) => {
1958
- let data = JSON.parse(event.data);
1959
- };
1960
- \`\`\`
1961
-
1962
- \`new WebSocket('wss://server/my-resource/341')\` accesses the resource defined for \`my-resource\` with record id \`341\` and subscribes to it.
1963
-
1964
- 3. **Implement a custom \`connect()\` handler**: Override the \`connect(incomingMessages)\` method on a resource class to control WebSocket behavior. The method must return an async iterable (or generator) that produces messages to send to the client. See [automatic-apis.md](automatic-apis.md) for more on defining resource classes.
1965
-
1966
- 4. **Use the default \`connect()\` for event-style access**: Call \`super.connect()\` to get a streaming iterable that provides:
1967
- - A \`send(message)\` method for pushing outgoing messages
1968
- - A \`close\` event for cleanup on disconnect
1969
-
1970
- 5. **Handle message ordering in distributed environments**: Harper delivers messages to local subscribers immediately without inter-node coordination delay.
1971
-
1972
- | Message Type | Behavior |
1973
- | -------------------------------------------------------- | ----------------------------------------------------------------------- |
1974
- | Non-retained (no \`retain\` flag) | Every message delivered in order received; suitable for chat |
1975
- | Retained (published with \`retain\`, or PUT/updated in DB) | Only the latest-timestamp message is kept; suitable for sensor readings |
1976
-
1977
- 6. **Use MQTT over WebSockets** when needed by setting the sub-protocol header:
1978
- \`\`\`
1979
- Sec-WebSocket-Protocol: mqtt
1980
- \`\`\`
1981
-
1982
- ## Examples
1983
-
1984
- **Simple echo server** — override \`connect(incomingMessages)\` to yield each incoming message back to the client:
1985
-
1986
- \`\`\`javascript
1987
- export class Echo extends Resource {
1988
- async *connect(incomingMessages) {
1989
- for await (let message of incomingMessages) {
1990
- yield message; // echo each message back
1991
- }
1992
- }
1993
- }
1994
- \`\`\`
1995
-
1996
- **Custom connect with timer and event-style access** — use \`super.connect()\` to get the outgoing stream, push periodic messages, echo incoming messages, and clean up on disconnect:
1997
-
1998
- \`\`\`javascript
1999
- export class Example extends Resource {
2000
- connect(incomingMessages) {
2001
- let outgoingMessages = super.connect();
2002
-
2003
- let timer = setInterval(() => {
2004
- outgoingMessages.send({ greeting: 'hi again!' });
2005
- }, 1000);
2006
-
2007
- incomingMessages.on('data', (message) => {
2008
- outgoingMessages.send(message); // echo incoming messages
2009
- });
2010
-
2011
- outgoingMessages.on('close', () => {
2012
- clearInterval(timer);
2013
- });
2014
-
2015
- return outgoingMessages;
2016
- }
2017
- }
2018
- \`\`\`
2019
-
2020
- ## Notes
2021
-
2022
- - WebSocket connections target a resource URL path. By default, connecting to a resource subscribes to changes for that resource.
2023
- - The \`connect(incomingMessages)\` method **must** return an async iterable or generator; returning a plain value will not work.
2024
- - \`super.connect()\` returns a streaming iterable with \`send(message)\` and a \`close\` event — use this when you need to push messages outside of the incoming message loop.
2025
- - For one-way real-time streaming without bidirectional communication, consider Server-Sent Events instead.
2026
- - For full pub/sub capabilities, Harper also supports MQTT; set \`Sec-WebSocket-Protocol: mqtt\` to use MQTT over WebSockets.
2027
- `,"schema-design-tooling":'---\nname: schema-design-tooling\ndescription: >-\n Best practices for Harper schema design, including core directives and GraphQL\n tooling configuration.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Overview\n - reference/v5/database/schema.md#Type Directives\n - reference/v5/database/schema.md#Field Directives\n sourceCommit: 677ad213d67822e109c83619e181ca23a59823db\n inputHash: ecb06058191ba29f\n---\n\n# Schema Design and GraphQL Tooling\n\nInstructions for the agent to follow when designing Harper database schemas using GraphQL type definitions, core directives, and tooling configuration.\n\n## When to Use\n\nApply this rule when creating or modifying Harper schema files (`.graphql`), configuring schema loading in `config.yaml`, or deciding which directives to apply to tables and fields. Use it whenever a task involves defining tables, primary keys, indexes, or export behavior.\n\n## How It Works\n\n1. **Create a GraphQL schema file** with Harper-specific directives. Schemas ensure required tables exist on deployment, enforce types and constraints, control indexing, and define relationships.\n\n ```graphql\n type Dog @table {\n id: Long @primaryKey\n name: String\n breed: String\n age: Int\n }\n ```\n\n2. **Register the schema in `config.yaml`** using the `graphqlSchema` plugin:\n\n ```yaml\n graphqlSchema:\n files: \'schema.graphql\'\n ```\n\n Both plugins and applications can specify schemas.\n\n3. **Mark each type as a table** with `@table`. The type name becomes the table name by default.\n\n ```graphql\n type MyTable @table {\n id: Long @primaryKey\n }\n ```\n\n Key `@table` arguments:\n\n | Argument | Type | Default | Description |\n | -------------------- | --------- | ----------------------------- | --------------------------------------------------------------- |\n | `table` | `String` | type name | Override the table name |\n | `database` | `String` | `"data"` | Database to place the table in |\n | `expiration` | `Int` | — | Seconds until a record goes stale |\n | `eviction` | `Int` | `0` | Additional seconds after `expiration` before physical removal |\n | `scanInterval` | `Int` | `(expiration + eviction) / 4` | Seconds between eviction scans |\n | `replicate` | `Boolean` | `true` | Enable replication of this table |\n | `cacheControl` | `String` | — | `Cache-Control` header for anonymous GET/HEAD 200/304 responses |\n | `randomAccessFields` | `Boolean` | `storage.randomAccessFields` | Pin this table\'s record encoding |\n\n4. **Designate a primary key** on every table using `@primaryKey`. Primary keys must be unique; duplicate inserts are rejected. If no primary key is provided on insert, Harper auto-generates one:\n - **UUID string** — when type is `String` or `ID`\n - **Auto-incrementing integer** — when type is `Int`, `Long`, or `Any`\n\n Use `Long` or `Any` for auto-generated numeric keys; `Int` is 32-bit and may be insufficient for large tables.\n\n ```graphql\n type Product @table {\n id: Long @primaryKey\n name: String\n }\n ```\n\n5. **Add secondary indexes** with `@indexed` on any attribute that will be used for filtering in REST queries, SQL, or NoSQL operations. If the field value is an array, each element is individually indexed.\n\n ```graphql\n type Product @table {\n id: Long @primaryKey\n category: String @indexed\n price: Float @indexed\n }\n ```\n\n6. **Expose tables via REST and other interfaces** using `@export`. Without `@export`, the table has no REST/MQTT route (callers get 404). The optional `name` parameter sets the URL path segment.\n\n ```graphql\n type MyTable @table @export(name: "my-table") {\n id: Long @primaryKey\n }\n ```\n\n `@export` is a routing directive, not access control. The table remains accessible through the Operations API and SQL regardless. REST must also be enabled for the application (via `rest: true` in `config.yaml` or Harper\'s built-in default).\n\n7. **Apply additional type directives** as needed:\n - `@sealed` — prevents records from including properties beyond those declared in the schema.\n - `@hidden` — suppresses the type from MCP tool descriptors and the OpenAPI document. Does not restrict data access.\n\n8. **Apply field directives** for computed and lifecycle behavior:\n - `@createdTime` — assigns Unix epoch milliseconds on record creation.\n - `@updatedTime` — assigns Unix epoch milliseconds on each update.\n - `@expiresAt` — marks a field as the record\'s absolute expiration time (Unix epoch milliseconds); authoritative over the table-level `expiration` default.\n - `@embed` — computes an embedding vector when the source field is written (requires `source` and `model` arguments; field type must be `[Float]`).\n - `@hidden` (field) — suppresses the field from generated specs and MCP tool schemas; does not restrict data access.\n\n## Examples\n\n**Minimal two-table schema:**\n\n```graphql\ntype Dog @table {\n id: Long @primaryKey\n name: String\n breed: String\n age: Int\n}\n\ntype Breed @table {\n id: Long @primaryKey\n name: String @indexed\n}\n```\n\n**Table with expiration, eviction, and scan tuning:**\n\n```graphql\n# Expire after 5 minutes, evict after 1 hour, scan every 10 minutes\ntype WeatherCache @table(expiration: 300, eviction: 3300, scanInterval: 600) {\n id: ID @primaryKey\n temperature: Float\n}\n```\n\n**Exported table with cache control:**\n\n```graphql\ntype Product @table(cacheControl: "public, max-age=60") @export {\n id: Long @primaryKey\n name: String\n price: Float\n}\n```\n\n**Table with lifecycle fields and indexing:**\n\n```graphql\ntype Event @table(database: "analytics", expiration: 86400) {\n id: Long @primaryKey\n name: String @indexed\n createdAt: Long @createdTime\n updatedAt: Long @updatedTime\n}\n```\n\n**Session table with per-record expiration:**\n\n```graphql\ntype Session @table {\n id: ID @primaryKey\n token: String\n expiresAt: Long @expiresAt\n}\n```\n\n**Sealed table preventing extra properties:**\n\n```graphql\ntype StrictRecord @table @sealed {\n id: Long @primaryKey\n name: String\n}\n```\n\n**`config.yaml` schema registration:**\n\n```yaml\ngraphqlSchema:\n files: \'schema.graphql\'\n```\n\n## Notes\n\n- Schemas are flexible by default — records may include additional properties beyond those declared. Use `@sealed` to prevent this.\n- Use unique `database` names in plugins or applications to avoid table naming collisions, since all tables default to the `"data"` database.\n- Replication is enabled by default. If you disable replication and re-enable it later, the table will not catch up on writes made while replication was disabled.\n- `@hidden` (type or field) is a metadata-visibility directive only. Use table-level role permissions and `attribute_permissions` whitelists to restrict actual data access.\n- `@export` absence causes 404 on REST/MQTT routes but does not protect data from the Operations API or SQL.\n- The `cacheControl` argument emits headers only on anonymous (unauthenticated) GET/HEAD 200/304 responses. Authenticated responses receive `Cache-Control: private, no-cache`.\n- `randomAccessFields` on `@table` pins the record encoding at table creation time. Editing the argument later does not repin an existing table.\n',"serving-web-content":"---\nname: serving-web-content\ndescription: How to serve static files and integrated Vite/React applications in Harper.\nmetadata:\n mode: synthesized\n---\n\n# Serving Web Content\n\nInstructions for the agent to follow when serving web content from Harper.\n\n## When to Use\n\nUse this skill when you need to serve a frontend (HTML, CSS, JS, or a React/Vue app) directly from your Harper instance — either plain static files or an integrated Vite app with hot module replacement (HMR) in development and a real production build when deployed.\n\n## How It Works\n\nThere are two building blocks. Harper's built-in `static` plugin **serves** files; the `@harperfast/vite` plugin **builds** (and, for SSR, **renders**) a Vite app. For a Vite app they work **together** — the plugin builds into a directory and `static` serves that same directory.\n\n### Option A: Static plugin only (simple, pre-built assets)\n\nFor a plain static site or already-built assets, use `static` on its own:\n\n```yaml\nstatic:\n files: 'web/*'\n```\n\n- Place files in a `web/` folder in the project root; they are served from the root URL (e.g. `http://localhost:9926/index.html`).\n- Static files are matched first; if none matches, Harper falls through to your resource and table APIs.\n\n### Option B: Vite plugin + static plugin (integrated Vite app)\n\n> **Renamed in v1:** the plugin was previously `@harperfast/vite-plugin`. From `1.0.0` on it is **`@harperfast/vite`** (same key and `package`). It now pairs with the `static` plugin instead of building into `web/` itself.\n\n`@harperfast/vite` **builds** your app — in `harper dev` it runs Vite in middleware mode with HMR; in `harper run` it runs `vite build` and rebuilds when watched files change (and renders HTML for SSR). The `static` plugin **serves** the built output. Point both at the same directory (`output`, default `dist`) — that shared directory is the only contract between them.\n\n**SPA `config.yaml`** — list the plugin first so its dev server wins in `harper dev`; `notFound` + `fallthrough: false` makes client-side routing work:\n\n```yaml\n'@harperfast/vite':\n package: '@harperfast/vite'\n files: 'src/**/*'\n output: 'dist'\n\nstatic:\n files: 'dist/**'\n notFound:\n file: 'index.html'\n statusCode: 200\n fallthrough: false\n```\n\n**SSR `config.yaml`** — add an `ssr` entry so the plugin renders `index.html`, and set `index: false` on `static` so it serves assets only:\n\n```yaml\n'@harperfast/vite':\n package: '@harperfast/vite'\n files: 'src/**/*'\n output: 'dist'\n ssr: 'src/entry-server.tsx'\n\nstatic:\n files: 'dist/**'\n index: false\n```\n\n- Install dependencies: `npm install --save-dev vite @harperfast/vite @vitejs/plugin-react` (swap in your framework's Vite plugin, e.g. `@vitejs/plugin-vue`).\n- Then `harper dev .` runs the app with HMR and `harper run .` runs the production build. Vite does _not_ need to be executed separately.\n\n## Reading Harper Data During SSR\n\nThe render entry (`src/entry-server.tsx`) runs **inside Harper**, so it can read straight from the database and render the data into the HTML — no client-side fetch/XHR. `tables` is the same live, process-wide registry available everywhere (see [Programmatic Table Requests](programmatic-table-requests.md)); import it and query a table in an async `render`:\n\n```tsx\nimport { tables } from 'harper';\n\nexport async function render(url: string): Promise<string> {\n const product = await tables.Product.get(idFromUrl(url));\n return renderToString(\n <StrictMode>\n <App product={product} />\n </StrictMode>,\n );\n}\n```\n\nKeep `harper` external in `vite.config.ts` so this import resolves to Harper's running runtime instead of being bundled. `node_modules/harper` is symlinked to the running install, and symlinked deps aren't reliably auto-externalized for SSR:\n\n```typescript\nexport default defineConfig({\n ssr: { external: ['harper'] },\n // ...plugins, resolve, build\n});\n```\n\nTo hydrate on the client without re-fetching, embed the rendered data in the HTML (e.g. an inline `<script type=\"application/json\">`) and read it back before hydration — so the page needs no XHR at all.\n\n## Deploying to Production\n\nBecause `@harperfast/vite` builds on the node and `static` serves the output, deploy the component as-is — no manual build-and-move step is needed:\n\n```json\n{\n \"scripts\": {\n \"dev\": \"harper dev .\",\n \"start\": \"harper run .\",\n \"deploy\": \"harper deploy_component . restart=true replicated=true\"\n }\n}\n```\n\nOn deploy the plugin runs `vite build` at startup (and rebuilds when `files` change) while `static` serves the result. If you prefer to build in CI, commit the build output, point `static` at it, and omit `files` so the plugin stays idle while `static` serves the prebuilt assets. Either way, `npm create harper@latest` scaffolds a working setup for you.\n","typescript-type-stripping":`---
2028
- name: typescript-type-stripping
2029
- description: How to run TypeScript files directly in Harper without a build step.
2030
- metadata:
2031
- mode: generate
2032
- sources:
2033
- - reference/v5/components/javascript-environment.md#TypeScript Support
2034
- sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819
2035
- inputHash: 4e6bd8b610edd595
2036
- ---
2037
-
2038
- # TypeScript Type Stripping in Harper
2039
-
2040
- Instructions for the agent to run \`.ts\` files directly in Harper without a build step using Node.js's built-in type stripping.
2041
-
2042
- ## When to Use
2043
-
2044
- Apply this rule when writing Harper resource files in TypeScript. Use it any time you need to reference \`.ts\` source files from \`config.yaml\` or import between local TypeScript modules in a Harper project.
2045
-
2046
- ## How It Works
2047
-
2048
- 1. **Ensure Node.js version**: Require Node.js 22.6 or later. Type stripping is unavailable on earlier versions.
2049
-
2050
- 2. **Point \`jsResource\` at \`.ts\` files**: The \`jsResource\` plugin loads both \`.js\` and \`.ts\` files. Set its \`files\` glob in \`config.yaml\` to target your \`.ts\` source files:
2051
-
2052
- \`\`\`yaml
2053
- jsResource:
2054
- files: 'resources/*.ts'
2055
- \`\`\`
2056
-
2057
- 3. **Use explicit \`.ts\` extensions in local imports**: Node's loader does not resolve \`'./helper'\` to \`'./helper.ts'\`, so always include the full extension:
2058
-
2059
- \`\`\`typescript
2060
- import { helper } from './helper.ts';
2061
- \`\`\`
2062
-
2063
- 4. **Stay within type-stripping limits**: Only type annotations and declarations are removed. Do not use enums with runtime values, namespaces with runtime semantics, or any other features that require code transformation beyond type stripping.
2064
-
2065
- ## Examples
2066
-
2067
- A complete Harper resource written in TypeScript, using imports from the \`harper\` package:
2068
-
2069
- \`\`\`typescript
2070
- import { type RequestTargetOrId, Resource, tables } from 'harper';
2071
-
2072
- export class MyResource extends Resource {
2073
- async get(target?: RequestTargetOrId): Promise<{ message: string }> {
2074
- return { message: 'Hello from TS' };
2075
- }
2076
- }
2077
- \`\`\`
2078
-
2079
- Paired \`config.yaml\` entry loading the file via \`jsResource\`:
2080
-
2081
- \`\`\`yaml
2082
- jsResource:
2083
- files: 'resources/*.ts'
2084
- \`\`\`
2085
-
2086
- ## Notes
2087
-
2088
- - No build step or transpiler is required — Harper runs \`.ts\` files directly.
2089
- - Type imports (e.g., \`import { type RequestTargetOrId }\`) from the \`harper\` package work as usual.
2090
- - Unsupported TypeScript features include: enums with runtime values, namespaces with runtime semantics, and anything requiring code transformation beyond simple type stripping.
2091
- `,"using-blob-datatype":"---\nname: using-blob-datatype\ndescription: How to use the Blob data type for efficient binary storage in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Blob Type\n - reference/v5/database/api.md#Streaming\n - reference/v5/database/api.md#`BlobOptions`\n - reference/v5/database/api.md#Blob Coercion\n sourceCommit: f37a8c4021e20d5c74c1d339a6b6c8c196b5603e\n inputHash: 92e03eb0b830f335\n---\n\n# Using the Blob Data Type\n\nInstructions for the agent to follow when storing and retrieving large binary content using the `Blob` data type in Harper.\n\n## When to Use\n\nApply this rule when a schema field needs to store large binary content such as images, video, audio, or large HTML — typically content larger than 20KB. Use `Blob` instead of `Bytes` when streaming support and out-of-record storage are required. See [handling-binary-data.md](handling-binary-data.md) for broader binary data guidance.\n\n## How It Works\n\n1. **Declare a `Blob` field in your schema**: Add a field typed as `Blob` to your `@table` type.\n\n ```graphql\n type MyTable @table {\n id: Any! @primaryKey\n data: Blob\n }\n ```\n\n2. **Create and store a blob with `createBlob()`**: Pass a buffer or stream to `createBlob()`, then `put` the record.\n\n ```javascript\n let blob = createBlob(largeBuffer);\n await MyTable.put({ id: 'my-record', data: blob });\n ```\n\n3. **Retrieve blob data using standard Web API methods**: The `Blob` type implements the Web API `Blob` interface. Use `.bytes()`, `.text()`, `.arrayBuffer()`, `.stream()`, or `.slice()` as needed.\n\n ```javascript\n let record = await MyTable.get('my-record');\n let buffer = await record.data.bytes(); // ArrayBuffer\n let text = await record.data.text(); // string\n let stream = record.data.stream(); // ReadableStream\n ```\n\n4. **Use `saveBeforeCommit` when full write must precede commit**: By default, `Blob` is not ACID-compliant — a record can reference a blob before it is fully written. Set `saveBeforeCommit: true` to block the transaction until the blob is fully saved.\n\n ```javascript\n let blob = createBlob(stream, { saveBeforeCommit: true });\n await MyTable.put({ id: 'my-record', data: blob });\n // put() resolves only after blob is fully written and record is committed\n ```\n\n5. **Register an error handler when returning a blob via REST**: Interrupted streams must be handled explicitly.\n\n ```javascript\n export class MyEndpoint extends MyTable {\n static async get(target) {\n const record = super.get(target);\n let blob = record.data;\n blob.on('error', () => {\n MyTable.invalidate(target);\n });\n return { status: 200, headers: {}, body: blob };\n }\n }\n ```\n\n6. **Rely on automatic coercion where applicable**: When a field is typed as `Blob` in the schema, any string or buffer assigned via `put`, `patch`, or `publish` is automatically coerced to a `Blob` — no manual `createBlob()` call is needed in those cases.\n\n### `BlobOptions` reference\n\nPass an options object as the second argument to `createBlob()`.\n\n| Option | Type | Default | Description |\n| ------------------ | --------- | ----------- | ------------------------------------------------------------------------------------------------------------------------ |\n| `type` | `string` | `undefined` | MIME type to associate with the blob (e.g., `image/jpeg`). Readable via `blob.type` and used when serving HTTP. |\n| `size` | `number` | `undefined` | Size of the data in bytes, if known ahead of time. Otherwise inferred from a buffer or determined as a stream completes. |\n| `saveBeforeCommit` | `boolean` | `false` | Wait until the blob is fully written before the transaction commits. |\n| `compress` | `boolean` | `false` | Compress the stored data with deflate. |\n| `flush` | `boolean` | `false` | Flush the file to disk after writing, before the `createBlob` promise chain resolves. |\n\n## Examples\n\n**Store an image with a MIME type:**\n\n```javascript\nlet blob = createBlob(imageBuffer, { type: 'image/jpeg' });\nawait Photo.put({ id, data: blob });\n```\n\n**Stream a blob in as it streams out (low-latency passthrough):**\n\n```javascript\nlet blob = createBlob(incomingStream);\n// blob exists, but data is still streaming to storage\nawait MyTable.put({ id: 'my-record', data: blob });\n\nlet record = await MyTable.get('my-record');\n// blob data is accessible as it arrives\nlet outgoingStream = record.data.stream();\n```\n\n**Guarantee full write before commit using `saveBeforeCommit`:**\n\n```javascript\nlet blob = createBlob(stream, { saveBeforeCommit: true });\nawait MyTable.put({ id: 'my-record', data: blob });\n```\n\n## Notes\n\n- `Blob` stores data separately from the record. If you need the binary data to be a true, ACID-committed part of the record, use a `Bytes` field instead.\n- All standard Web API `Blob` methods — `.text()`, `.arrayBuffer()`, `.stream()`, `.slice()`, and `.bytes()` — are available on retrieved blob fields.\n- Without `saveBeforeCommit: true`, blobs are **not** ACID-compliant by default; a record can reference a blob before it is fully written to storage.\n","v5-upgrade":"---\nname: v5-upgrade\ndescription: >-\n Breaking changes and recommended updates when migrating a Harper application\n to v5.\nmetadata:\n mode: generate\n sources:\n - release-notes/v5-lincoln/v5-migration.md\n sourceCommit: 677ad213d67822e109c83619e181ca23a59823db\n inputHash: 01c0fafb9afa68a0\n---\n\n# v5 Upgrade: Breaking Changes and Migration Guide\n\nInstructions for the agent to apply when migrating a Harper application to v5, covering all breaking changes and required code updates.\n\n## When to Use\n\nApply this rule when upgrading an existing Harper application to v5, when encountering runtime errors related to renamed packages, changed APIs, or security restrictions after a v5 upgrade, or when scaffolding new v5-compatible application code.\n\n## How It Works\n\n1. **Update the package import from `harperdb` to `harper`**: All application code must import from `harper`, not `harperdb`.\n\n ```javascript\n import { tables } from 'harper';\n ```\n\n2. **Enable `allowInstallScripts` if packages require install scripts**: Harper v5 uses `--ignore-scripts` by default when installing packages. If a package requires execution of install scripts (e.g., to install native binaries), set the `allowInstallScripts` option when deploying.\n\n3. **Update `Table.get` usage — return value is now a frozen record object**: `Table.get` now returns a plain record object, not a table class instance. The record is frozen; you cannot add or mutate properties directly.\n - Replace direct property mutation:\n\n ```javascript\n let record = await Table.get(id);\n record = { ...record, property: 'changed' };\n ```\n\n - Replace `wasLoadedFromSource()` with `loadedFromSource` on the `target` object:\n\n ```javascript\n const target = new RequestTarget();\n target.id = id;\n const record = await Table.get(target);\n if (target.loadedFromSource) {\n // record was loaded from origin (not cache)\n }\n ```\n\n The record objects still expose `getUpdatedTime` and `getExpiresAt` methods.\n\n4. **Update transaction and context handling using `getContext`**: Harper v5 uses asynchronous context tracking. Context and the current transaction are automatically carried to all downstream calls — you no longer pass context explicitly. Import `getContext` and `transaction` from `harper`:\n\n ```javascript\n import { getContext, transaction } from 'harper';\n ```\n\n If your code previously omitted context to escape a transaction (e.g., to poll for updated data), explicitly commit the transaction and/or wrap each read in a new `transaction()` call:\n\n ```javascript\n import { setTimeout as delay } from 'node:timers/promises';\n import { getContext, transaction } from 'harper';\n class MyResource {\n static async get(target) {\n await getContext().transaction.commit();\n while ((await transaction(() => Table.get(target))).status !== 'ready') {\n await delay(100);\n }\n return Table.get(target);\n }\n }\n ```\n\n5. **Register allowed spawn commands via `allowedSpawnCommands`**: `spawn` and `execFile` may only launch executables listed in `applications.allowedSpawnCommands` in `harperdb-config.yaml`. Only the first token of the command is matched. `exec` is not usable through the substituted module; `execSync` always throws.\n\n ```yaml\n applications:\n allowedSpawnCommands:\n - npm\n - node\n ```\n\n Additionally, `spawn`, `execFile`, and `fork` now require a `name` property in the `options` argument to prevent process multiplication across threads.\n\n6. **Use `saveBeforeCommit` instead of `blob.save()`**: The `blob.save()` method has been removed. Pass the `saveBeforeCommit` flag in the options to the `Blob` constructor instead.\n\n7. **Handle `headers` on returned response objects**: If you return an object from a REST method with a `headers` property, Harper v5 will use it as the response headers.\n\n8. **Configure the VM module loader and `lockdown` in `harperdb-config.yaml`**: v5 loads application modules through Node.js's VM module API. Control all behavior under the `applications` key:\n\n ```yaml\n applications:\n lockdown: freeze-after-load\n moduleLoader: vm-current-context\n dependencyLoader: auto\n allowedDirectory: app\n allowedSpawnCommands:\n - npm\n - node\n ```\n\n **`moduleLoader` options:**\n\n | Value | Behavior |\n | -------------------- | -------------------------------------------------------------------------------------------------------------------------------- |\n | `vm-current-context` | Default. VM loader in Harper's own context; shares intrinsics with Harper. Best compatibility. |\n | `vm` | VM loader in a separate per-application context with its own intrinsics. Stronger isolation but may cause `instanceof` failures. |\n | `native` | Standard Node.js `import()`. No VM loader; application-specific context (`logger`, `config`) unavailable. |\n | `compartment` | SES Compartment-based loading. For specialized sandboxing only. |\n\n **`lockdown` options:**\n\n | Value | Behavior |\n | ------------------- | ------------------------------------------------------- |\n | `freeze-after-load` | Default. Freezes intrinsics after all components load. |\n | `freeze` | Freezes intrinsics before loading any application code. |\n | `ses` | Full SES lockdown via the `ses` package. Strictest. |\n | `none` | No lockdown. Use as a temporary workaround only. |\n\n To disable the VM loader entirely and restore pre-v5 behavior:\n\n ```yaml\n applications:\n moduleLoader: native\n ```\n\n## Examples\n\n**Full transaction polling pattern (v5):**\n\n```javascript\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { getContext, transaction } from 'harper';\n\nclass MyResource {\n static async get(target) {\n await getContext().transaction.commit();\n while ((await transaction(() => Table.get(target))).status !== 'ready') {\n await delay(100);\n }\n return Table.get(target);\n }\n}\n```\n\n**Checking `loadedFromSource` after `Table.get`:**\n\n```javascript\nconst target = new RequestTarget();\ntarget.id = id;\nconst record = await Table.get(target);\nif (target.loadedFromSource) {\n // record was loaded from origin (not cache)\n}\n```\n\n**Full `harperdb-config.yaml` `applications` block:**\n\n```yaml\napplications:\n lockdown: freeze-after-load\n moduleLoader: vm-current-context\n dependencyLoader: auto\n allowedDirectory: app\n allowedSpawnCommands:\n - npm\n - node\n```\n\n**Restricting allowed built-in modules:**\n\n```yaml\napplications:\n allowedBuiltinModules:\n - fs\n - path\n - http\n```\n\n## Notes\n\n- Always import Harper APIs from `'harper'`, not from global variables or `'harperdb'`.\n- `getContext` is exported from `'harper'` and provides access to the current transaction without passing context explicitly.\n- Record objects returned by `Table.get` are frozen — spread into a new object before modifying.\n- `loadedFromSource` is a property on the `target` object, replacing the removed `wasLoadedFromSource()` instance method.\n- `saveBeforeCommit` replaces the removed `blob.save()` method.\n- The `headers` property on a returned REST response object is used as response headers.\n- Under `lockdown: ses`, the constrained `fetch` applies only in `vm` mode. In `vm-current-context` and `native` modes, application code uses the standard global `fetch`.\n- In production, `allowedDirectory: app` is the default; modules outside the application directory tree will throw. Set `allowedDirectory: any` only if legitimately required.\n- `dependencyLoader: native` is a narrower option than `moduleLoader: native` — it uses native loading only for npm packages while keeping the VM loader for first-party application source files.\n","vector-indexing":`---
2092
- name: vector-indexing
2093
- description: How to enable and query vector indexes for similarity search in Harper.
2094
- metadata:
2095
- mode: generate
2096
- sources:
2097
- - reference/v5/database/schema.md#Vector Indexing
2098
- sourceCommit: d4cbc1a7dd400462e4a3243f944b3a75d89b29ca
2099
- inputHash: 1dae788bc850ea90
2100
- ---
2101
-
2102
- # Vector Indexing
2103
-
2104
- Instructions for the agent to enable HNSW vector indexes on table fields and query them for similarity search in Harper.
2105
-
2106
- ## When to Use
2107
-
2108
- Apply this rule when adding a vector similarity search capability to a Harper table — for example, storing text embeddings and querying for nearest neighbors, filtering by distance threshold, or combining vector search with record-level access control. See [adding-tables-with-schemas.md](adding-tables-with-schemas.md) for how to define the surrounding table schema.
2109
-
2110
- ## How It Works
2111
-
2112
- 1. **Declare the vector index** on a \`[Float]\` field using \`@indexed(type: "HNSW")\`:
2113
-
2114
- \`\`\`graphql
2115
- type Document @table {
2116
- id: Long @primaryKey
2117
- textEmbeddings: [Float] @indexed(type: "HNSW")
2118
- }
2119
- \`\`\`
2120
-
2121
- 2. **Query nearest neighbors** using \`Document.search()\` with the \`sort\` parameter. Set \`attribute\` to the indexed field and \`target\` to the query vector:
2122
-
2123
- \`\`\`javascript
2124
- let results = Document.search({
2125
- sort: { attribute: 'textEmbeddings', target: searchVector },
2126
- limit: 5,
2127
- });
2128
- \`\`\`
2129
-
2130
- 3. **Combine with filter conditions** to narrow results before or during graph traversal. Selective conditions are automatically diverted to an exact-scan strategy:
2131
-
2132
- \`\`\`javascript
2133
- let results = Document.search({
2134
- conditions: [{ attribute: 'price', comparator: 'lt', value: 50 }],
2135
- sort: { attribute: 'textEmbeddings', target: searchVector },
2136
- limit: 5,
2137
- });
2138
- \`\`\`
2139
-
2140
- 4. **Apply a function predicate during traversal** using \`vectorFilter\` (JavaScript API only). The function receives each candidate record and must return a synchronous boolean. It must be side-effect free and fast:
2141
-
2142
- \`\`\`javascript
2143
- let results = Document.search(
2144
- {
2145
- sort: { attribute: 'textEmbeddings', target: searchVector },
2146
- vectorFilter: (record) =>
2147
- record.tenantId === context.user.tenantId && record.status === 'published',
2148
- limit: 10,
2149
- },
2150
- context,
2151
- );
2152
- \`\`\`
2153
-
2154
- 5. **Filter by distance threshold** using \`target\` directly on a condition alongside \`comparator\` and \`value\`. This returns matches within the threshold without using \`sort\`:
2155
-
2156
- \`\`\`javascript
2157
- let results = Document.search({
2158
- conditions: {
2159
- attribute: 'textEmbeddings',
2160
- comparator: 'lt',
2161
- value: 0.1,
2162
- target: searchVector,
2163
- },
2164
- });
2165
- \`\`\`
2166
-
2167
- 6. **Include computed distance in results** by adding \`$distance\` to \`select\`. Works with both \`sort\`-based and threshold queries:
2168
-
2169
- \`\`\`javascript
2170
- let results = Document.search({
2171
- select: ['name', '$distance'],
2172
- sort: { attribute: 'textEmbeddings', target: searchVector },
2173
- limit: 5,
2174
- });
2175
- \`\`\`
2176
-
2177
- 7. **Tune per-query search options** on the \`sort\` descriptor using \`distance\` and \`ef\`:
2178
-
2179
- \`\`\`javascript
2180
- let results = Document.search({
2181
- sort: { attribute: 'textEmbeddings', target: searchVector, distance: 'dotProduct', ef: 200 },
2182
- limit: 5,
2183
- });
2184
- \`\`\`
2185
-
2186
- 8. **Tune filtered traversal** with \`ef\` and \`filterExpansion\` when a \`vectorFilter\` is very selective. The visit budget is \`ef * filterExpansion\` nodes (\`filterExpansion\` defaults to \`24\`):
2187
-
2188
- \`\`\`javascript
2189
- let results = Document.search(
2190
- {
2191
- sort: { attribute: 'textEmbeddings', target: searchVector, ef: 200, filterExpansion: 40 },
2192
- vectorFilter: (record) => record.category === 'rare',
2193
- limit: 10,
2194
- },
2195
- context,
2196
- );
2197
- \`\`\`
2198
-
2199
- 9. **Enforce row-level access control** using \`rowFilter\` on search and subscription targets (JavaScript API only). Attach it in an operation override. For vector queries, \`rowFilter\` participates in HNSW traversal so callers receive the k nearest _matching_ records:
2200
-
2201
- \`\`\`javascript
2202
- function canReadReport(record, context) {
2203
- const user = context.user;
2204
- if (user?.role?.permission?.super_user) return true;
2205
- return user?.username != null && record.ownerId != null && record.ownerId === user.username;
2206
- }
2207
-
2208
- export class Reports extends tables.Reports {
2209
- search(target) {
2210
- target.rowFilter = canReadReport;
2211
- return super.search(target);
2212
- }
2213
- }
2214
- \`\`\`
2215
-
2216
- ### HNSW Index Parameters
2217
-
2218
- Configure parameters directly on \`@indexed(type: "HNSW", ...)\`:
2219
-
2220
- | Parameter | Default | Description |
2221
- | ---------------------- | ----------------- | ------------------------------------------------------------------------------------------------ |
2222
- | \`distance\` | \`"cosine"\` | Distance function: \`"cosine"\`, \`"euclidean"\`, or \`"dotProduct"\` |
2223
- | \`efConstruction\` | \`100\` | Max nodes explored during index construction. Higher = better recall, lower = better performance |
2224
- | \`M\` | \`16\` | Preferred connections per graph layer |
2225
- | \`optimizeRouting\` | \`0.5\` | Heuristic aggressiveness for omitting redundant connections (0 = off, 1 = most aggressive) |
2226
- | \`mL\` | computed from \`M\` | Normalization factor for level generation |
2227
- | \`efConstructionSearch\` | auto-scaled | Max nodes explored during search. When unset, auto-scales with index size |
2228
- | \`quantization\` | — | \`"int8"\` stores vectors quantized to int8 |
2229
- | \`filterExpansion\` | \`24\` | Visit-budget multiplier for filtered search: visits at most \`ef * filterExpansion\` nodes |
2230
-
2231
- Per-query \`sort\` descriptor options:
2232
-
2233
- | Option | Values | Description |
2234
- | ---------- | ----------------------------------------- | ------------------------------------------------------ |
2235
- | \`distance\` | \`"cosine"\`, \`"euclidean"\`, \`"dotProduct"\` | Overrides the index's distance function for this query |
2236
- | \`ef\` | integer | Overrides the search exploration budget for this query |
2237
-
2238
- ## Examples
2239
-
2240
- **Index with custom HNSW parameters:**
2241
-
2242
- \`\`\`graphql
2243
- type Document @table {
2244
- id: Long @primaryKey
2245
- textEmbeddings: [Float]
2246
- @indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efConstructionSearch: 100)
2247
- }
2248
- \`\`\`
2249
-
2250
- **Index with int8 quantization:**
2251
-
2252
- \`\`\`graphql
2253
- type Document @table {
2254
- id: Long @primaryKey
2255
- textEmbeddings: [Float] @indexed(type: "HNSW", quantization: "int8")
2256
- }
2257
- \`\`\`
2258
-
2259
- **Nearest-neighbor search with distance included:**
2260
-
2261
- \`\`\`javascript
2262
- let results = Document.search({
2263
- select: ['name', '$distance'],
2264
- sort: { attribute: 'textEmbeddings', target: searchVector },
2265
- limit: 5,
2266
- });
2267
- \`\`\`
2268
-
2269
- **Filtered traversal with tuned budget:**
2270
-
2271
- \`\`\`javascript
2272
- let results = Document.search(
2273
- {
2274
- sort: { attribute: 'textEmbeddings', target: searchVector, ef: 200, filterExpansion: 40 },
2275
- vectorFilter: (record) => record.category === 'rare',
2276
- limit: 10,
2277
- },
2278
- context,
2279
- );
2280
- \`\`\`
2281
-
2282
- ## Notes
2283
-
2284
- - \`vectorFilter\` and \`rowFilter\` are available from the JavaScript API only; they cannot be set through REST or QUERY request data.
2285
- - \`vectorFilter\` functions must be synchronous, side-effect free, and fast — they can run once per candidate record visited during traversal; verdicts are memoized per query. Records passed to them are frozen.
2286
- - \`rowFilter\` does not apply to a direct primary-key \`get\`.
2287
- - Changing \`efConstructionSearch\` on an existing index does not trigger a rebuild. Structural parameters (\`distance\`, \`M\`, \`efConstruction\`, \`quantization\`) do rebuild the index when changed.
2288
- - With \`quantization: "int8"\`, nearest-neighbor \`sort\` queries re-rank results against full-precision vectors, restoring exact ordering and exact \`$distance\` values. Distance-threshold (\`lt\`/\`le\`) queries filter on the approximate distance.
2289
- - The correct parameter name is \`efConstruction\` (seeds the construction budget) and \`efConstructionSearch\` (controls search budget). The name \`efSearchConstruction\` is a previous documentation error.
2290
- - When no \`ef\` is passed and \`efConstructionSearch\` (or \`efConstruction\`) is not explicitly set, the search budget auto-scales with index size.
2291
- - \`cosine\` is the default distance function when \`distance\` is not specified.
2292
- `},oo={name:`readHarperSkill`,description:`Returns documentation for a Harper skill or best practice. Skills provide guidance on developing Harper applications.`,inputSchema:i({skill:v(io)})};async function so({input:{skill:e}}){return{success:!!ao[e],message:ao[e]||`No skill found with the name ${e}`}}var co={...oo,icon:ot,execute:so},lo={name:`readLogs`,description:`Returns the matching logs from the server.`,inputSchema:i({log_name:v([`hdb.log`,`system.log`]).default(`hdb.log`),limit:x().or(g()).optional(),level:v([`notify`,`error`,`warn`,`info`,`debug`,`trace`,`undefined`]).or(g()).optional(),from:x().or(g()).optional(),until:x().or(g()).optional()})};async function uo({input:e,instanceClientParams:t}){try{return{success:!0,data:await Re({...t,logFilters:e,replicated:t.entityType===`cluster`})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var fo={...lo,icon:mt,execute:uo},po={name:`readTableRecords`,description:`Retrieves some or all table records from a database on the server.`,inputSchema:i({database:x().trim(),table:x().trim(),pageIndex:l().default(0),pageSize:l().default(10),primaryKey:x(),conditions:m(i({search_attribute:x(),search_type:v([`between`,`eq`,`equals`,`greater_than`,`greater_than_equal`,`less_than`,`less_than_equal`,`ne`,`not_equal`,`starts_with`]),search_value:a()})),sort:i({attribute:x(),descending:_()})})};async function mo({input:{database:e,table:t,conditions:n,primaryKey:r,...i},instanceClientParams:a}){try{if(!n.length){let{data:n}=await we({...a,databaseName:e,tableName:t,onlyIfCached:!0,searchAttribute:r,...i});return{success:!0,data:n}}let{data:o}=await ke({...a,databaseName:e,tableName:t,onlyIfCached:!0,conditions:n,...i});return{success:!0,data:o}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ho={...po,icon:Ce,execute:mo},go={name:`restartHTTPService`,description:`Restarts the HTTP service on the server to allow schema and resource changes to be applied.`,inputSchema:i({})};async function _o({instanceClientParams:e,baseURL:t}){let n=ce.loading(`Restarting HTTP service...`,{description:`This may take a bit.`,duration:3e5});try{await He({...e,operation:`restart_service`,replicated:e.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return ce.success(`Done!`,{description:`HTTP Service restarted!`,id:n,duration:5e3}),{success:!0,message:`HTTP Service restarted!`,webURL:t}}var vo={...go,icon:Ne,execute:_o,requiresApproval:!0},yo={name:`setComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:i({path:x().trim(),payload:x(),encoding:v([`utf8`,`ASCII`,`binary`,`hex`,`base64`,`utf16le`,`latin1`,`ucs2`])})};async function bo({input:{path:e,encoding:t,payload:n},instanceClientParams:r}){try{let i=e.split(`/`),a=i.shift(),o=i.join(`/`),s=await be({...r,file:o,project:a,payload:n,encoding:t});return await Xe.invalidateQueries({queryKey:[r.entityId,`get_component_file`,a,o]}),Me(`ReloadApplicationRootEntries`,!0),{success:!0,data:s}}catch(e){return{success:!1,message:`Error: ${e}`}}}var xo={...yo,icon:ft,execute:bo,requiresApproval:!0},So={name:`updateTableRecords`,description:`Updates records in a particular table in a particular database on the server.`,inputSchema:i({database:x().trim(),table:x().trim(),records:m(a())})};async function Co({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await ze({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Xe.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var wo={readHarperSkill:co,createApp:Ea,readLogs:fo,getAnalytics:Fa,listAnalyticsMetrics:ro,restartHTTPService:vo,collectFeedback:Ca,getUserContext:Xa,getComponentFile:Ra,getComponents:Va,setComponentFile:xo,dropComponentFile:Ma,getDescribeAll:Wa,getDescribeTable:qa,insertTableRecords:$a,readTableRecords:ho,updateTableRecords:{...So,icon:it,execute:Co,requiresApproval:!0},deleteTableRecords:ka};function To(e){return wo[e]}function Eo(e){return e.state===`input-available`&&!!To(Wi(e))?.requiresApproval}function Do(e){let t=[];for(let[n,r]of(e??[]).entries()){if(K(r)){if(Eo(r)){t.push({kind:`part`,part:r,index:n});continue}let e=t.at(-1);e?.kind===`tool-group`?e.parts.push(r):t.push({kind:`tool-group`,parts:[r],index:n});continue}Bi(r)&&r.text.length>0&&t.push({kind:`part`,part:r,index:n})}return t}function Oo({part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i}){let[a,o]=(0,w.useState)(!1),[s,c]=(0,w.useState)(!1),l=Wi(e),u=To(l),d=u?.icon||Ae,f=u?.requiresApproval,p=(0,w.useMemo)(()=>!e.input||typeof e.input==`object`&&Object.keys(e.input).length===0,[e.input]),m=(0,w.useMemo)(()=>{let t=JSON.stringify(e.input,null,` `);return{json:t,lines:t?t.split(`
2293
- `).length:0}},[e.input]),h=(0,w.useMemo)(()=>{let t=JSON.stringify(e.output,null,` `);return{json:t,lines:t?t.split(`
2294
- `).length:0}},[e.output]);return(0,T.jsxs)(`div`,{className:`tool-invocation ${e.state}`,children:[(0,T.jsxs)(`div`,{className:`tool-info`,children:[(0,T.jsxs)(`div`,{className:`tool-name`,children:[(0,T.jsx)(d,{size:14}),(0,T.jsx)(`span`,{children:l})]}),(0,T.jsxs)(`div`,{className:`tool-status`,children:[e.state===`input-streaming`&&(0,T.jsx)(`span`,{children:`Thinking...`}),e.state===`input-available`&&(0,T.jsx)(`span`,{children:i?`Executing...`:f?`Awaiting Approval...`:`Executing...`}),e.state===`output-available`&&(e.output?.error?(0,T.jsx)(ut,{size:14,className:`text-destructive`}):(0,T.jsx)(ue,{size:14}))]})]}),e.state!==`input-streaming`&&(0,T.jsxs)(`div`,{className:`tool-io`,children:[!p&&(0,T.jsxs)(`div`,{className:`tool-args`,children:[(0,T.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,T.jsx)(`strong`,{children:`Input:`}),m.lines>3&&(0,T.jsx)(se,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>o(!a),children:a?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(de,{size:12}),`Hide`]}):(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(le,{size:12}),`Show`]})})]}),(0,T.jsx)(`div`,{className:a?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:m.json})]}),e.state===`input-available`&&f&&(0,T.jsxs)(`div`,{className:`flex gap-2 mt-3 pt-3 border-t`,children:[(0,T.jsxs)(se,{size:`sm`,className:`h-8 text-xs bg-green-600 hover:bg-green-700 text-white`,onClick:()=>t?.(e.toolCallId),disabled:i,children:[i?(0,T.jsx)(Ee,{className:`mr-2 h-3 w-3 animate-spin`}):null,`Approve`]}),(0,T.jsx)(se,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>r?.(e.toolCallId),disabled:i,children:`Always Approve`}),(0,T.jsx)(se,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>n?.(e.toolCallId),disabled:i,children:`Deny`})]}),e.state===`output-available`&&(0,T.jsx)(T.Fragment,{children:u?.render?u.render(e):(0,T.jsxs)(`div`,{className:`tool-result`,children:[(0,T.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,T.jsx)(`strong`,{children:`Result:`}),h.lines>3&&(0,T.jsx)(se,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>c(!s),children:s?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(de,{size:12}),`Hide`]}):(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(le,{size:12}),`Show`]})})]}),(0,T.jsx)(`div`,{className:s?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:h.json})]})})]})]})}function ko({parts:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){let[a,o]=(0,w.useState)(!1),s=e.some(e=>e.state!==`output-available`&&e.state!==`output-error`),c=e.some(e=>e.state===`output-error`||e.state===`output-available`&&e.output?.error),l=e.length===1?Wi(e[0]):void 0,u=l&&To(l)?.icon||St,d=l??`${e.length} tools`;return(0,T.jsxs)(`div`,{className:`tool-group`,children:[(0,T.jsxs)(`button`,{type:`button`,className:`tool-group-summary`,"aria-expanded":a,onClick:()=>o(!a),children:[a?(0,T.jsx)(le,{size:14}):(0,T.jsx)(Je,{size:14}),(0,T.jsx)(u,{size:14}),(0,T.jsx)(`span`,{children:s?`Using ${d}...`:`Used ${d}`}),(0,T.jsx)(`span`,{className:`tool-group-status`,children:s?(0,T.jsx)(Ee,{size:14,className:`animate-spin`}):c?(0,T.jsx)(ut,{size:14,className:`text-destructive`}):(0,T.jsx)(ue,{size:14})})]}),a&&e.map(e=>(0,T.jsx)(Oo,{part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(e.toolCallId)},e.toolCallId))]})}function Ao({message:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){return e.parts?.some(e=>Bi(e)&&e.text.length>0||K(e))?(0,T.jsxs)(tt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`message-bubble ${e.role===`user`?`user`:`assistant`}`,children:[(0,T.jsx)(`div`,{className:`avatar`,children:e.role===`user`?(0,T.jsx)(bt,{size:18}):(0,T.jsx)(et,{size:18})}),(0,T.jsx)(`div`,{className:`content`,children:Do(e.parts).map(e=>{if(e.kind===`tool-group`)return(0,T.jsx)(ko,{parts:e.parts,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i},e.parts[0].toolCallId);let{part:a,index:o}=e;return Bi(a)?(0,T.jsx)(`div`,{className:`text-block`,children:a.text},o):K(a)?(0,T.jsx)(Oo,{part:a,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(a.toolCallId)},o):null})})]},e.id):null}function jo(e,t){if(e!==`submitted`&&e!==`streaming`)return!1;if(t?.role!==`assistant`)return!0;let n=t.parts?.at(-1);return n?Bi(n)?n.state!==`streaming`||n.text.length===0:!K(n)||n.state===`output-available`||n.state===`output-error`:!0}function Mo(){return(0,T.jsxs)(tt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.2},className:`message-bubble assistant`,children:[(0,T.jsx)(`div`,{className:`avatar`,children:(0,T.jsx)(et,{size:18})}),(0,T.jsxs)(`div`,{className:`content thinking-indicator`,role:`status`,"aria-label":`Harper Agent is thinking`,children:[(0,T.jsx)(`span`,{className:`thinking-dot`}),(0,T.jsx)(`span`,{className:`thinking-dot`}),(0,T.jsx)(`span`,{className:`thinking-dot`})]})]})}function No(e){return re({queryKey:[`getMyUsage`,e],queryFn:async()=>{let{data:t}=await S.get(`/Chat/Usage/${e}`);return t}})}function Po(){let{organizationId:e}=ae({strict:!1});return ne(No(e))}function Fo(){let{data:e,isLoading:t,error:n}=Po();if(t||n||!e)return null;let{usageUSD:r,monthlyLimitUSD:i,usageBarPercent:a}=e,o=e=>new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`}).format(e);return(0,T.jsxs)(`div`,{className:`usage-container`,children:[(0,T.jsxs)(`div`,{className:`usage-info`,children:[(0,T.jsx)(`span`,{children:`Monthly Org Usage`}),(0,T.jsxs)(`span`,{children:[o(r),` / `,o(i)]}),(0,T.jsxs)(`span`,{children:[Math.round(a),`%`]})]}),(0,T.jsx)(`div`,{className:`usage-bar-bg`,children:(0,T.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${a}%`}})})]})}function Io({autoFocus:e,closeChat:t}){let n=ae({strict:!1}),{organizationId:r}=n,[i,a]=We(`ApplicationChat`,``),[o,s]=(0,w.useState)(!0),[c,l]=(0,w.useState)({}),[u,d]=(0,w.useState)(new Set),[f,p]=Ue(Se.ChatAlwaysApprovedTools,[]),m=new Set(f),h=$e(),g=Te(),_=ie(),{messages:v,sendMessage:y,status:b,addToolOutput:x,setMessages:S}=va({transport:aa(r),generateId:A(),sendAutomaticallyWhen:ia,onFinish(){_.invalidateQueries({queryKey:[`getMyUsage`]})},async onToolCall({toolCall:e}){if(e.dynamic)return;let t=To(e.toolName);if(t){if(t.requiresApproval&&!m.has(e.toolName)){let t={type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input};l(n=>({...n,[e.toolCallId]:t}));return}let r=await t.execute({input:e.input,instanceClientParams:g,baseURL:h,params:n});x({tool:e.toolName,toolCallId:e.toolCallId,output:r})}}}),ee=(0,w.useCallback)(async e=>{let t=c[e];if(t){d(t=>{let n=new Set(t);return n.add(e),n});try{let r=To(t.toolName);if(r){let i=await r.execute({input:t.input,instanceClientParams:g,baseURL:h,params:n});x({tool:t.toolName,toolCallId:t.toolCallId,output:i}),l(t=>{let n={...t};return delete n[e],n})}}finally{d(t=>{let n=new Set(t);return n.delete(e),n})}}},[c,g,h,x,n]),te=(0,w.useCallback)(e=>{let t=c[e];t&&(x({tool:t.toolName,toolCallId:t.toolCallId,output:{error:`User denied the tool execution.`}}),l(t=>{let n={...t};return delete n[e],n}))},[c,x]),ne=(0,w.useCallback)(async e=>{let t=c[e];t&&(p(e=>Ge([...e,t.toolName])),await ee(e))},[c,p,ee]);(0,w.useEffect)(()=>{(async()=>{try{let e=await Tt();Array.isArray(e)&&S(e)}catch(e){console.error(`Failed to fetch initial messages:`,e)}finally{s(!1)}})()},[S]);let re=b===`streaming`||b===`submitted`,oe=(0,w.useRef)(null);return(0,w.useEffect)(()=>{oe.current?.scrollIntoView({behavior:`smooth`})},[v]),(0,T.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,T.jsxs)(`div`,{className:`flex items-start justify-between gap-6 px-4 py-2.5 border-b border-border bg-card`,children:[(0,T.jsxs)(`div`,{className:`flex flex-col gap-1 min-w-0 flex-1`,children:[(0,T.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,T.jsx)(et,{className:`text-primary`,size:20}),(0,T.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Harper Agent`})]}),(0,T.jsx)(Fo,{})]}),(0,T.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,T.jsx)(wt,{setMessages:S}),(0,T.jsx)(`button`,{onClick:t,className:`p-1 hover:bg-accent rounded-md transition-colors text-muted-foreground hover:text-foreground`,title:`Close chat`,children:(0,T.jsx)(Qe,{size:20})})]})]}),(0,T.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,T.jsxs)(`div`,{className:`chat-interface h-full w-full`,children:[(0,T.jsxs)(`div`,{className:`messages-area`,children:[o&&(0,T.jsx)(ba,{}),!o&&v.length===0&&(0,T.jsxs)(`div`,{className:`empty-state`,children:[(0,T.jsx)(et,{size:48}),(0,T.jsx)(`p`,{children:`Ask me to create a Harper app!`})]}),v.map(e=>(0,T.jsx)(Ao,{message:e,onApprove:ee,onDeny:te,onAlwaysApprove:ne,approvingToolCallIds:u},e.id)),jo(b,v.at(-1))&&(0,T.jsx)(Mo,{}),(0,T.jsx)(`div`,{ref:oe})]}),(0,T.jsx)(ya,{input:i,setInput:a,onSubmit:e=>{e.preventDefault(),i.trim()&&!re&&!o&&(y({text:i}),a(``))},disabled:o,autoFocus:e})]})})]})}export{Io as Chat};