@ultrst-armada/kloks 1.26.2 → 1.26.4

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 (272) hide show
  1. package/README.md +39 -0
  2. package/index.d.ts +16 -10
  3. package/index.js +3 -0
  4. package/package.json +70 -8
  5. package/packages/audio-midi/dist/{audioClipEngine-BOT33JKI.js → audioClipEngine-LKZRWTJ3.js} +2 -2
  6. package/packages/audio-midi/dist/{audioInputManager-BLDGGLAR.js → audioInputManager-5BNHLOJM.js} +1 -1
  7. package/packages/audio-midi/dist/{chunk-N55BWOC6.js → chunk-M4JFGTHE.js} +1 -1
  8. package/packages/audio-midi/dist/{chunk-3GRGELA4.js → chunk-OUOFTYHY.js} +50 -11
  9. package/packages/audio-midi/dist/engine/audio/entities/AudioEffects/functionalities/Compressor/manifest.json +7 -0
  10. package/packages/audio-midi/dist/engine/audio/entities/AudioEffects/functionalities/Delay/manifest.json +7 -0
  11. package/packages/audio-midi/dist/engine/audio/entities/AudioEffects/functionalities/Equalizer/manifest.json +7 -0
  12. package/packages/audio-midi/dist/engine/audio/entities/AudioEffects/functionalities/Limiter/manifest.json +7 -0
  13. package/packages/audio-midi/dist/engine/audio/entities/AudioEffects/functionalities/MultibandCompressor/manifest.json +7 -0
  14. package/packages/audio-midi/dist/engine/audio/entities/AudioEffects/functionalities/Reverb/manifest.json +7 -0
  15. package/packages/audio-midi/dist/engine/audio/entities/AudioEffects/functionalities/Saturation/manifest.json +7 -0
  16. package/packages/audio-midi/dist/index.d.ts +10 -1
  17. package/packages/audio-midi/dist/index.js +36 -20
  18. package/packages/audio-midi/package.json +8 -0
  19. package/packages/backend/dist/ai-models/index.js +2 -2
  20. package/packages/backend/dist/ai-routing/index.js +3 -3
  21. package/packages/backend/dist/api/BaseApiRoute.d.ts +1 -1
  22. package/packages/backend/dist/api/index.js +1 -1
  23. package/packages/backend/dist/auth/CanonicalAuthClient.d.ts +6 -6
  24. package/packages/backend/dist/auth/index.js +2 -1
  25. package/packages/backend/dist/chunk-2Y2EXYDK.js +0 -0
  26. package/packages/backend/dist/{chunk-3SWMKYCI.js → chunk-3FZSYSJC.js} +18 -9
  27. package/packages/backend/dist/chunk-5F5V7NAG.js +54 -0
  28. package/packages/backend/dist/{chunk-KVWBIDZG.js → chunk-BVXGUHLZ.js} +1 -1
  29. package/packages/backend/dist/chunk-DAG2L4RN.js +0 -0
  30. package/packages/backend/dist/{chunk-GKXI5V23.js → chunk-G7PPVOFP.js} +17 -51
  31. package/packages/backend/dist/{chunk-GKQ42CYW.js → chunk-H6ET362U.js} +3 -3
  32. package/packages/backend/dist/chunk-HUY4272L.js +69 -0
  33. package/packages/backend/dist/chunk-JQKKMUCT.js +0 -0
  34. package/packages/backend/dist/{chunk-PT6J6UEU.js → chunk-LMAU62ZG.js} +4 -4
  35. package/packages/backend/dist/{chunk-4TPSXGG5.js → chunk-MZK362U4.js} +12 -12
  36. package/packages/backend/dist/{chunk-BQLQTUDD.js → chunk-NGEB3CF5.js} +3 -35
  37. package/packages/backend/dist/{chunk-3VWBZEMG.js → chunk-NTKUQVCQ.js} +4 -5
  38. package/packages/backend/dist/chunk-NY2SQOXI.js +34 -0
  39. package/packages/backend/dist/{chunk-JOTDEFRG.js → chunk-OXEP3AP6.js} +5 -4
  40. package/packages/backend/dist/chunk-RABSY2JU.js +0 -0
  41. package/packages/backend/dist/{chunk-M45KQRPR.js → chunk-RFPGUJAZ.js} +11 -11
  42. package/packages/backend/dist/{chunk-TWCEVES2.js → chunk-WC6EPW3A.js} +1 -1
  43. package/packages/backend/dist/{chunk-UCCFQCAE.js → chunk-Y5ENDXU2.js} +72 -129
  44. package/packages/backend/dist/{chunk-EO5VUYYU.js → chunk-Y7ZE6D5H.js} +4 -4
  45. package/packages/backend/dist/{chunk-RCCQ7IRM.js → chunk-ZBNSK26X.js} +2 -2
  46. package/packages/backend/dist/control-plane/AuditLogger.d.ts +1 -1
  47. package/packages/backend/dist/control-plane/ControlPlaneManager.d.ts +1 -1
  48. package/packages/backend/dist/control-plane/index.js +1 -1
  49. package/packages/backend/dist/core/dynamicRouteResolver.d.ts +1 -1
  50. package/packages/backend/dist/core/routesCore.d.ts +1 -1
  51. package/packages/backend/dist/core/vercelTransformer.d.ts +1 -1
  52. package/packages/backend/dist/core/workspaceCore.d.ts +2 -2
  53. package/packages/backend/dist/data/BaseDataProvider.d.ts +1 -1
  54. package/packages/backend/dist/development/index.js +34 -21
  55. package/packages/backend/dist/development/playwrightInspectionService.js +1 -2
  56. package/packages/backend/dist/development/webContainerService.js +1 -2
  57. package/packages/backend/dist/index.d.ts +4 -24
  58. package/packages/backend/dist/index.js +14 -4657
  59. package/packages/backend/dist/krnl-ai-services.d.ts +9 -9
  60. package/packages/backend/dist/krnl-ai-services.js +5 -6
  61. package/packages/backend/dist/krnl-services.js +8 -7
  62. package/packages/backend/dist/node.d.ts +28 -0
  63. package/packages/backend/dist/node.js +4754 -0
  64. package/packages/backend/dist/resourceEngine/BaseResourceFetcher.d.ts +3 -3
  65. package/packages/backend/dist/resourceEngine/CloudflareResourceFetcher.d.ts +3 -3
  66. package/packages/backend/dist/resourceEngine/ResourceFetcherRegistry.d.ts +5 -5
  67. package/packages/backend/dist/resourceEngine/VercelResourceFetcher.d.ts +3 -3
  68. package/packages/backend/dist/resourceEngine/adapters/CloudflareResourceAdapter.d.ts +2 -2
  69. package/packages/backend/dist/resourceEngine/adapters/VercelResourceAdapter.d.ts +2 -2
  70. package/packages/backend/dist/resourceEngine/calculator/UniversalResourceCalculator.d.ts +1 -1
  71. package/packages/backend/dist/resourceEngine/calculator/types.d.ts +1 -1
  72. package/packages/backend/dist/resourceEngine/index.d.ts +6 -6
  73. package/packages/backend/dist/resourceEngine/types/depm/entities.d.ts +2 -2
  74. package/packages/backend/dist/resourceEngine/types.d.ts +1 -1
  75. package/packages/backend/dist/resourceEngine/weightEngine/helpers.d.ts +1 -1
  76. package/packages/backend/dist/resourceEngine/weightEngine/index.d.ts +2 -2
  77. package/packages/backend/dist/resourceEngine/weightEngine/weightEngine.d.ts +1 -1
  78. package/packages/backend/dist/resourceEngine/weightEngine.d.ts +1 -1
  79. package/packages/backend/dist/server/services/assetPoolService/assetPoolService.d.ts +3 -3
  80. package/packages/backend/dist/server/services/projectService/projectService.d.ts +3 -3
  81. package/packages/backend/dist/services/index.d.ts +2 -10
  82. package/packages/backend/dist/services/index.js +1 -37
  83. package/packages/backend/dist/services/node.d.ts +10 -0
  84. package/packages/backend/dist/services/node.js +38 -0
  85. package/packages/backend/dist/srkl/index.js +1 -1
  86. package/packages/backend/dist/storage/BaseStorageAdapter.d.ts +1 -1
  87. package/packages/backend/dist/storage/GoogleDriveWorkspaceService.d.ts +69 -0
  88. package/packages/backend/dist/storage/GoogleDriveWorkspaceService.test.d.ts +1 -0
  89. package/packages/backend/dist/storage/S3Adapter.d.ts +5 -0
  90. package/packages/backend/dist/storage/googleDriveSdk.d.ts +1 -0
  91. package/packages/backend/dist/storage/index.d.ts +1 -10
  92. package/packages/backend/dist/storage/index.js +8 -43
  93. package/packages/backend/dist/storage/node.d.ts +14 -0
  94. package/packages/backend/dist/storage/node.js +66 -0
  95. package/packages/backend/dist/storage-workspace.d.ts +2 -0
  96. package/packages/backend/dist/storage-workspace.js +339 -0
  97. package/packages/backend/dist/workspace/WorkspaceCloneSyncEngine.d.ts +1 -1
  98. package/packages/backend/dist/workspace/index.d.ts +1 -5
  99. package/packages/backend/dist/workspace/index.js +4 -24
  100. package/packages/backend/dist/workspace/node.d.ts +8 -0
  101. package/packages/backend/dist/workspace/node.js +30 -0
  102. package/packages/backend/package.json +40 -3
  103. package/packages/functions/dist/base-DDYO-DzM.d.ts +64 -0
  104. package/packages/functions/dist/base.d.ts +1 -0
  105. package/packages/functions/dist/base.js +6 -0
  106. package/packages/functions/dist/chunk-6EHIZHO4.js +555 -0
  107. package/packages/functions/dist/chunk-Z4LM5TOJ.js +114 -0
  108. package/packages/functions/dist/index.d.ts +4 -373
  109. package/packages/functions/dist/index.js +53 -1693
  110. package/packages/functions/dist/node.d.ts +110 -0
  111. package/packages/functions/dist/node.js +442 -0
  112. package/packages/functions/dist/portable.d.ts +207 -0
  113. package/packages/functions/dist/portable.js +94 -0
  114. package/packages/functions/package.json +23 -1
  115. package/packages/{functions/dist/chunk-K6H7T3EP.js → services/dist/chunk-P54QSKOQ.js} +1 -3
  116. package/packages/{state-graph/dist/dist-es-TLPJYZTE.js → services/dist/dist-es-2P6LFFZL.js} +1 -1
  117. package/packages/services/dist/{dist-es-5IACWOIO.js → dist-es-OZCE67MW.js} +1 -1
  118. package/packages/services/dist/{dist-es-3DGJJFOU.js → dist-es-RUJB3ALN.js} +3 -3
  119. package/packages/{state-graph/dist/dist-es-OECEAUXH.js → services/dist/dist-es-SSJGP5AI.js} +4 -4
  120. package/packages/services/dist/{loadSso-M3ZIZDGO.js → loadSso-3PZYFUB7.js} +1 -1
  121. package/packages/{functions/dist/signin-YXALFRYB.js → services/dist/signin-WYPGSXHF.js} +1 -1
  122. package/packages/{state-graph/dist/sso-oidc-NXFKRL6O.js → services/dist/sso-oidc-PQMIMLJU.js} +1 -1
  123. package/packages/{state-graph/dist/sts-MICPT37B.js → services/dist/sts-Z7LR3AZH.js} +1 -1
  124. package/packages/state-graph/dist/browser.d.ts +18 -0
  125. package/packages/state-graph/dist/browser.js +613 -0
  126. package/packages/state-graph/dist/browser.test.d.ts +1 -0
  127. package/packages/state-graph/dist/{chunk-KG6QYS26.js → chunk-5KP74NMF.js} +80 -80
  128. package/packages/state-graph/dist/{chunk-4UVGXFEM.js → chunk-LVULR5M4.js} +1 -1
  129. package/packages/state-graph/dist/{chunk-S22PMERU.js → chunk-OXUDG6HE.js} +1 -1
  130. package/packages/state-graph/dist/chunk-UKTICGGV.js +9523 -0
  131. package/packages/state-graph/dist/domain/index.js +2 -3
  132. package/packages/state-graph/dist/engine/AudioConcepts.d.ts +1 -1
  133. package/packages/state-graph/dist/engine/GraphConcepts.d.ts +1 -1
  134. package/packages/state-graph/dist/engine/core/archetypes/audioArchetypes.d.ts +1 -1
  135. package/packages/state-graph/dist/engine/core/archetypes/effectArchetypes.d.ts +1 -1
  136. package/packages/state-graph/dist/engine/core/archetypes/primitiveArchetypes.d.ts +1 -1
  137. package/packages/state-graph/dist/engine/core/archetypes/routingArchetypes.d.ts +1 -1
  138. package/packages/state-graph/dist/engine/core/archetypes/triggerModuleArchetypes.d.ts +1 -1
  139. package/packages/state-graph/dist/engine/core/assets/containerSprites.d.ts +1 -1
  140. package/packages/state-graph/dist/engine/core/assets/effectSprites.d.ts +1 -1
  141. package/packages/state-graph/dist/engine/core/assets/primitiveSprites.d.ts +1 -1
  142. package/packages/state-graph/dist/engine/core/assets/routingSprites.d.ts +1 -1
  143. package/packages/state-graph/dist/engine/core/canonicalIo/CanonicalAudioInputEndpoint.d.ts +1 -1
  144. package/packages/state-graph/dist/engine/core/canonicalIo/CanonicalMidiInputEndpoint.d.ts +1 -1
  145. package/packages/state-graph/dist/engine/core/canonicalIo/topLevelIoRegistry.d.ts +6 -6
  146. package/packages/state-graph/dist/engine/core/canonicalIo/types.d.ts +1 -1
  147. package/packages/state-graph/dist/engine/core/graphDataService.d.ts +1 -1
  148. package/packages/state-graph/dist/engine/core/hierarchy/index.d.ts +11 -11
  149. package/packages/state-graph/dist/engine/core/hierarchy/nodes/GraphNodeParent.d.ts +3 -3
  150. package/packages/state-graph/dist/engine/core/hierarchy/nodes/GraphNodeTypes.d.ts +1 -1
  151. package/packages/state-graph/dist/engine/core/hierarchy/sockets/GraphSocketParent.d.ts +2 -2
  152. package/packages/state-graph/dist/engine/core/hierarchy/sockets/GraphSocketTypes.d.ts +1 -1
  153. package/packages/state-graph/dist/engine/core/hierarchy/ui/UIElementBase.d.ts +3 -3
  154. package/packages/state-graph/dist/engine/core/hierarchy/wires/GraphWireParent.d.ts +2 -2
  155. package/packages/state-graph/dist/engine/core/hierarchy/wires/GraphWireTypes.d.ts +1 -1
  156. package/packages/state-graph/dist/engine/core/nodeArchetypeRegistry.d.ts +1 -1
  157. package/packages/state-graph/dist/engine/core/socketRegistry/containersSockets.d.ts +1 -1
  158. package/packages/state-graph/dist/engine/core/socketRegistry/customRegistry.d.ts +1 -1
  159. package/packages/state-graph/dist/engine/core/socketRegistry/landmarksSockets.d.ts +1 -1
  160. package/packages/state-graph/dist/engine/core/socketRegistry/primitivesSockets.d.ts +1 -1
  161. package/packages/state-graph/dist/engine/core/socketRegistry/processorsSockets.d.ts +1 -1
  162. package/packages/state-graph/dist/engine/core/sockets/arrangementControlSockets.d.ts +1 -1
  163. package/packages/state-graph/dist/engine/core/sockets/audioSockets.d.ts +1 -1
  164. package/packages/state-graph/dist/engine/core/sockets/folderButtonSockets.d.ts +1 -1
  165. package/packages/state-graph/dist/engine/core/sockets/moduleSockets.d.ts +1 -1
  166. package/packages/state-graph/dist/engine/core/sockets/playbackSockets.d.ts +1 -1
  167. package/packages/state-graph/dist/engine/core/sockets/primitiveSockets.d.ts +1 -1
  168. package/packages/state-graph/dist/engine/core/sockets/routingSockets.d.ts +1 -1
  169. package/packages/state-graph/dist/engine/core/sockets/samplerSockets.d.ts +1 -1
  170. package/packages/state-graph/dist/engine/core/sockets/stripSockets.d.ts +1 -1
  171. package/packages/state-graph/dist/engine/functions/arrangementFactory.d.ts +1 -1
  172. package/packages/state-graph/dist/engine/functions/codeNodeParser/codeNodeParser.d.ts +2 -2
  173. package/packages/state-graph/dist/engine/functions/codeNodeParser/helpers.d.ts +1 -1
  174. package/packages/state-graph/dist/engine/functions/connection/portMatching.d.ts +1 -1
  175. package/packages/state-graph/dist/engine/functions/connection/signalCompatibility/helpers.d.ts +1 -1
  176. package/packages/state-graph/dist/engine/functions/connection/signalCompatibility/signalCompatibility.d.ts +1 -1
  177. package/packages/state-graph/dist/engine/functions/connection/signalCompatibility.d.ts +1 -1
  178. package/packages/state-graph/dist/engine/functions/connection/wireValidation.d.ts +1 -1
  179. package/packages/state-graph/dist/engine/functions/containerClipSync.d.ts +1 -1
  180. package/packages/state-graph/dist/engine/functions/containerFactory/containerFactory.d.ts +1 -1
  181. package/packages/state-graph/dist/engine/functions/effectLogic.d.ts +1 -1
  182. package/packages/state-graph/dist/engine/functions/graphManager/graphManager.d.ts +1 -1
  183. package/packages/state-graph/dist/engine/functions/graphManager.d.ts +1 -1
  184. package/packages/state-graph/dist/engine/functions/nodeFactory/nodeFactory.d.ts +8 -8
  185. package/packages/state-graph/dist/engine/functions/nodeFactory.d.ts +2 -2
  186. package/packages/state-graph/dist/engine/functions/signalTable/audioMidiSignals.d.ts +1 -1
  187. package/packages/state-graph/dist/engine/functions/signalTable/canonicalEffectsTable.d.ts +1 -1
  188. package/packages/state-graph/dist/engine/functions/signalTable/dataSignals.d.ts +1 -1
  189. package/packages/state-graph/dist/engine/functions/socketCompatibilitySpawner/helpers.d.ts +1 -1
  190. package/packages/state-graph/dist/engine/functions/socketCompatibilitySpawner/socketCompatibilitySpawner.d.ts +1 -1
  191. package/packages/state-graph/dist/engine/functions/socketCompatibilitySpawner.d.ts +1 -1
  192. package/packages/state-graph/dist/engine/functions/spawnNodeFactory.d.ts +1 -1
  193. package/packages/state-graph/dist/engine/predictive/predictiveGraphEngine/helpers.d.ts +1 -1
  194. package/packages/state-graph/dist/engine/predictive/predictiveGraphEngine.d.ts +2 -2
  195. package/packages/state-graph/dist/engine/types/auth.d.ts +1 -1
  196. package/packages/state-graph/dist/engine/types/hardwareBus.d.ts +1 -1
  197. package/packages/state-graph/dist/engine/types/legacyTypes.d.ts +1 -1
  198. package/packages/state-graph/dist/engine/types/nodesArrangement.d.ts +2 -2
  199. package/packages/state-graph/dist/engine/types/nodesAudio.d.ts +5 -5
  200. package/packages/state-graph/dist/engine/types/nodesControl.d.ts +2 -2
  201. package/packages/state-graph/dist/engine/types/nodesPlayback.d.ts +2 -2
  202. package/packages/state-graph/dist/engine/types/nodesPrimitives.d.ts +6 -6
  203. package/packages/state-graph/dist/engine/types/nodesRouting.d.ts +2 -2
  204. package/packages/state-graph/dist/engine/types/sceneData.d.ts +2 -2
  205. package/packages/state-graph/dist/engine/types/sceneState.d.ts +4 -4
  206. package/packages/state-graph/dist/engine/types/signals.d.ts +2 -2
  207. package/packages/state-graph/dist/engine/types/stripsTypes.d.ts +2 -2
  208. package/packages/state-graph/dist/index.js +262 -9979
  209. package/packages/state-graph/dist/rules/index.js +0 -1
  210. package/packages/state-graph/dist/runtime-entrypoint.test.d.ts +1 -0
  211. package/packages/state-graph/dist/spatial/index.js +0 -1
  212. package/packages/state-graph/dist/state/index.js +0 -1
  213. package/packages/state-graph/dist/store/CommandApi.d.ts +2 -2
  214. package/packages/state-graph/dist/store/index.js +2 -3
  215. package/packages/state-graph/package.json +8 -2
  216. package/scripts/normalize-package-declarations.mjs +63 -0
  217. package/packages/backend/dist/chunk-SXDYW3QA.js +0 -579
  218. package/packages/functions/dist/bowser-F6LIZBYW.js +0 -2821
  219. package/packages/functions/dist/chunk-34KJBG4F.js +0 -357
  220. package/packages/functions/dist/chunk-EAQYK3U2.js +0 -41
  221. package/packages/functions/dist/chunk-IOAPEUC7.js +0 -3424
  222. package/packages/functions/dist/chunk-J64ZDIIX.js +0 -2753
  223. package/packages/functions/dist/chunk-N3MSTUJN.js +0 -4785
  224. package/packages/functions/dist/chunk-VP26OHBN.js +0 -480
  225. package/packages/functions/dist/chunk-VRLVLNLG.js +0 -1727
  226. package/packages/functions/dist/dist-TKZ5TDRN.js +0 -1124
  227. package/packages/functions/dist/dist-W7ZJS3LZ.js +0 -899
  228. package/packages/functions/dist/dist-es-3DGJJFOU.js +0 -338
  229. package/packages/functions/dist/dist-es-5IACWOIO.js +0 -69
  230. package/packages/functions/dist/dist-es-BWLDIBIA.js +0 -47
  231. package/packages/functions/dist/dist-es-DO3F4OBN.js +0 -377
  232. package/packages/functions/dist/dist-es-NN7AKU7P.js +0 -175
  233. package/packages/functions/dist/dist-es-QZ6GKMM7.js +0 -220
  234. package/packages/functions/dist/dist-es-R3VEGXOP.js +0 -87
  235. package/packages/functions/dist/dist-es-TLPJYZTE.js +0 -294
  236. package/packages/functions/dist/event-streams-DRE6QVD6.js +0 -940
  237. package/packages/functions/dist/loadSso-M3ZIZDGO.js +0 -586
  238. package/packages/functions/dist/multipart-parser-YYFFJ4QD.js +0 -371
  239. package/packages/functions/dist/src-2QCYQXYH.js +0 -1396
  240. package/packages/functions/dist/sso-oidc-NXFKRL6O.js +0 -847
  241. package/packages/functions/dist/sts-MICPT37B.js +0 -1253
  242. package/packages/functions/dist/transformers.node-R6VHTGC2.js +0 -43879
  243. package/packages/services/dist/chunk-K6H7T3EP.js +0 -1991
  244. package/packages/services/dist/dist-es-QZ6GKMM7.js +0 -220
  245. package/packages/services/dist/dist-es-TLPJYZTE.js +0 -294
  246. package/packages/services/dist/signin-YXALFRYB.js +0 -831
  247. package/packages/services/dist/sso-oidc-NXFKRL6O.js +0 -847
  248. package/packages/services/dist/sts-MICPT37B.js +0 -1253
  249. package/packages/state-graph/dist/bowser-F6LIZBYW.js +0 -2821
  250. package/packages/state-graph/dist/chunk-34KJBG4F.js +0 -357
  251. package/packages/state-graph/dist/chunk-EAQYK3U2.js +0 -41
  252. package/packages/state-graph/dist/chunk-IOAPEUC7.js +0 -3424
  253. package/packages/state-graph/dist/chunk-J64ZDIIX.js +0 -2753
  254. package/packages/state-graph/dist/chunk-K6H7T3EP.js +0 -1991
  255. package/packages/state-graph/dist/chunk-N3MSTUJN.js +0 -4785
  256. package/packages/state-graph/dist/chunk-VP26OHBN.js +0 -480
  257. package/packages/state-graph/dist/chunk-VRLVLNLG.js +0 -1727
  258. package/packages/state-graph/dist/dist-TKZ5TDRN.js +0 -1124
  259. package/packages/state-graph/dist/dist-W7ZJS3LZ.js +0 -899
  260. package/packages/state-graph/dist/dist-es-3DGJJFOU.js +0 -338
  261. package/packages/state-graph/dist/dist-es-5IACWOIO.js +0 -69
  262. package/packages/state-graph/dist/dist-es-BWLDIBIA.js +0 -47
  263. package/packages/state-graph/dist/dist-es-DO3F4OBN.js +0 -377
  264. package/packages/state-graph/dist/dist-es-NN7AKU7P.js +0 -175
  265. package/packages/state-graph/dist/dist-es-R3VEGXOP.js +0 -87
  266. package/packages/state-graph/dist/event-streams-DRE6QVD6.js +0 -940
  267. package/packages/state-graph/dist/loadSso-M3ZIZDGO.js +0 -586
  268. package/packages/state-graph/dist/multipart-parser-YYFFJ4QD.js +0 -371
  269. package/packages/state-graph/dist/signin-YXALFRYB.js +0 -831
  270. package/packages/state-graph/dist/src-2QCYQXYH.js +0 -1396
  271. package/packages/state-graph/dist/transformers.node-R6VHTGC2.js +0 -43879
  272. package/packages/backend/dist/{chunk-LMWXONZG.js → chunk-EREYT3WJ.js} +3 -3
@@ -0,0 +1,4754 @@
1
+ import {
2
+ GOOGLE_DRIVE_FILE_SCOPE,
3
+ GOOGLE_DRIVE_STORAGE_SCOPE,
4
+ createGoogleDriveAuthorizationUrl,
5
+ exchangeGoogleDriveCode,
6
+ refreshGoogleDriveAccessToken
7
+ } from "./chunk-3FZSYSJC.js";
8
+ import {
9
+ RemoteWorkspaceService,
10
+ SyncEngine,
11
+ WorkingWorkspaceService,
12
+ WorkspaceFS,
13
+ findWorkspaceRecord,
14
+ getDefaultWorkingWorkspaceDir,
15
+ getWorkingWorkspaceConfig,
16
+ getWorkingWorkspaceDir,
17
+ getWorkspaceFolderKey,
18
+ remoteWorkspaceService,
19
+ setWorkingWorkspaceConfig,
20
+ syncWorkspace,
21
+ workingWorkspaceService
22
+ } from "./chunk-NGEB3CF5.js";
23
+ import {
24
+ CompositeBackend,
25
+ EndpointGenerator,
26
+ LOCAL_STORAGE_GRAPHS_PREFIX,
27
+ NodeGraphPersistenceService,
28
+ createBackend,
29
+ createCompositeService,
30
+ createLocalService,
31
+ createRemoteService,
32
+ exportGraphAsJsonFile,
33
+ nodeGraphPersistence,
34
+ parseGraphJsonFile,
35
+ validateGraphDocument
36
+ } from "./chunk-OXEP3AP6.js";
37
+ import {
38
+ CANONICAL_SRKL_URL,
39
+ SrklClient,
40
+ SrklCredentialRegistry,
41
+ SrklVaultAccessClient,
42
+ createSrklClient,
43
+ decryptVaultBufferInBrowser,
44
+ getPrimarySrklDeploymentUrl as getPrimarySrklDeploymentUrl2,
45
+ getSrklAccounts as getSrklAccounts2,
46
+ getSrklStatus,
47
+ globalCredentialRegistry,
48
+ hexToBytes,
49
+ listBackblazeBuckets,
50
+ srklListBackblazeBuckets as srklListBackblazeBuckets2,
51
+ srklService,
52
+ syncSrklAccounts,
53
+ useSrklServices
54
+ } from "./chunk-HF5SGQ5V.js";
55
+ import "./chunk-LV55WKZR.js";
56
+ import "./chunk-WVDSMTW3.js";
57
+ import {
58
+ validateToolInput
59
+ } from "./chunk-6GQNYRD6.js";
60
+ import "./chunk-JQKKMUCT.js";
61
+ import {
62
+ BackendProvider,
63
+ useBackend,
64
+ useBackendClient
65
+ } from "./chunk-N7OUR5R5.js";
66
+ import {
67
+ AuditLogger,
68
+ ControlPlaneManager,
69
+ DatabaseClusterManager,
70
+ detectDatabaseEngine,
71
+ getSystemDatabaseUrls,
72
+ resolveSystemDatabaseClusterNodes
73
+ } from "./chunk-ZBNSK26X.js";
74
+ import "./chunk-DAG2L4RN.js";
75
+ import {
76
+ WorkspaceCloneSyncEngine
77
+ } from "./chunk-NY2SQOXI.js";
78
+ import {
79
+ BaseApiRoute,
80
+ createSSEResponse,
81
+ withAuth,
82
+ withCors
83
+ } from "./chunk-WC6EPW3A.js";
84
+ import {
85
+ LuthAuthClient,
86
+ LuthAuthClient2,
87
+ LuthAuthError,
88
+ createLuthAuthClient,
89
+ createLuthAuthClient2,
90
+ resolveClientEnvironment,
91
+ resolveClientOrigin
92
+ } from "./chunk-Y7ZE6D5H.js";
93
+ import {
94
+ BackendRegistry,
95
+ ConcurrencyConflictError,
96
+ ConcurrencyManager,
97
+ HealthMonitor,
98
+ IdempotencyManager,
99
+ InProcessExecutor,
100
+ JobScheduler,
101
+ LoadBalancer,
102
+ LockManager,
103
+ RemoteExecutor,
104
+ createEmptyContract
105
+ } from "./chunk-5E6JRFUH.js";
106
+ import {
107
+ BackendClient,
108
+ BackendResolver,
109
+ CallbackRegistry,
110
+ EventBus,
111
+ FrontendSession,
112
+ HTTPTransport,
113
+ SequenceTracker,
114
+ WebSocketTransport,
115
+ createBackendClient
116
+ } from "./chunk-NIP22V2G.js";
117
+ import {
118
+ AIInferenceServiceDefinition,
119
+ AIInferenceServiceFacade,
120
+ AIKeyServiceDefinition,
121
+ AIKeyServiceFacade,
122
+ AIModelCatalogServiceDefinition,
123
+ AIModelCatalogServiceFacade,
124
+ AIProviderServiceDefinition,
125
+ AIProviderServiceFacade,
126
+ AIRoutingServiceDefinition,
127
+ AIRoutingServiceFacade,
128
+ AIToolServiceDefinition,
129
+ AIToolServiceFacade
130
+ } from "./chunk-RFPGUJAZ.js";
131
+ import {
132
+ FailoverExecutionEngine,
133
+ HealthCheckService,
134
+ MetricsLogger,
135
+ failoverExecutionEngine,
136
+ healthCheckService,
137
+ metricsLogger
138
+ } from "./chunk-LMAU62ZG.js";
139
+ import {
140
+ AIProviderService,
141
+ aiProviderService
142
+ } from "./chunk-SLR6SIEU.js";
143
+ import {
144
+ MCPEngine,
145
+ ToolManagerService,
146
+ mcpEngine,
147
+ toolManagerService
148
+ } from "./chunk-U4HUGPRH.js";
149
+ import {
150
+ AuthServiceDefinition,
151
+ AuthServiceFacade,
152
+ ControlPlaneServiceDefinition,
153
+ ControlPlaneServiceFacade,
154
+ DatabaseServiceDefinition,
155
+ DatabaseServiceFacade,
156
+ GeminiServiceDefinition,
157
+ GeminiServiceFacade,
158
+ SrklServiceDefinition,
159
+ SrklServiceFacade,
160
+ StorageServiceDefinition,
161
+ StorageServiceFacade,
162
+ WorkspaceGraphServiceDefinition,
163
+ WorkspaceGraphServiceFacade,
164
+ WorkspaceServiceDefinition,
165
+ WorkspaceServiceFacade,
166
+ krnlAuthServiceDefinition,
167
+ krnlAuthServiceFacade,
168
+ krnlControlPlaneServiceDefinition,
169
+ krnlControlPlaneServiceFacade,
170
+ krnlDatabaseServiceDefinition,
171
+ krnlDatabaseServiceFacade,
172
+ krnlGeminiServiceDefinition,
173
+ krnlGeminiServiceFacade,
174
+ krnlSrklServiceDefinition,
175
+ krnlSrklServiceFacade,
176
+ krnlStorageServiceDefinition,
177
+ krnlStorageServiceFacade,
178
+ krnlWorkspaceGraphServiceDefinition,
179
+ krnlWorkspaceGraphServiceFacade,
180
+ krnlWorkspaceServiceDefinition,
181
+ krnlWorkspaceServiceFacade
182
+ } from "./chunk-MZK362U4.js";
183
+ import {
184
+ formatCanonicalWorkspaceFolderName,
185
+ sanitizeWorkspaceName
186
+ } from "./chunk-FZKBTF34.js";
187
+ import {
188
+ workspaceGraphService
189
+ } from "./chunk-BVXGUHLZ.js";
190
+ import {
191
+ BackblazeB2Adapter,
192
+ BucketStorageService,
193
+ GoogleDriveStorageService,
194
+ LocalFSAdapter,
195
+ S3Adapter,
196
+ StorageAdapterFactory,
197
+ SupabaseStorageAdapter,
198
+ ensureS3DirectoryMarker,
199
+ permanentDeleteS3Folder,
200
+ permanentDeleteS3Object,
201
+ renameS3Folder
202
+ } from "./chunk-Y5ENDXU2.js";
203
+ import {
204
+ createWorkspace,
205
+ deleteWorkspace,
206
+ deleteWorkspaceFile,
207
+ deleteWorkspaceFolder,
208
+ findUserWorkspace,
209
+ getWorkspaceFolderPrefix,
210
+ getWorkspaceStorageDetails,
211
+ getWorkspaces,
212
+ isB2Workspace,
213
+ listWorkspaceFiles,
214
+ loadWorkspaceData,
215
+ readWorkspaceFile,
216
+ renameAppInWorkspaceData,
217
+ resolveWorkspaceConnection,
218
+ saveWorkspaceData,
219
+ syncWorkspaceCreateToBucket,
220
+ syncWorkspaceDataToBucket,
221
+ syncWorkspaceDeleteToBucket,
222
+ updateWorkspace,
223
+ writeWorkspaceFile
224
+ } from "./chunk-JGUWYVOL.js";
225
+ import {
226
+ GoogleDriveAdapter
227
+ } from "./chunk-G7PPVOFP.js";
228
+ import {
229
+ getPrimarySrklDeploymentUrl,
230
+ getSrklAccounts,
231
+ srklListBackblazeBuckets
232
+ } from "./chunk-RIOYKF3X.js";
233
+ import {
234
+ b2DeleteFileVersion,
235
+ b2DeleteFolder,
236
+ cleanDbUrl,
237
+ getB2BucketId,
238
+ getUnifiedDbUrl,
239
+ queryUnifiedDb
240
+ } from "./chunk-JCMB7BIM.js";
241
+ import {
242
+ loginSystemUser,
243
+ resolveUserFromToken
244
+ } from "./chunk-2COYZMUJ.js";
245
+ import {
246
+ isSecretMasked,
247
+ normalizeBackblazeCredentials,
248
+ resolveBackblazeEndpoint
249
+ } from "./chunk-HUY4272L.js";
250
+ import {
251
+ BaseStorageAdapter
252
+ } from "./chunk-5F5V7NAG.js";
253
+ import {
254
+ authorizeB2,
255
+ b2DownloadFile,
256
+ b2ListBuckets,
257
+ b2ListFileNames,
258
+ b2UploadFile
259
+ } from "./chunk-4QEMALXF.js";
260
+ import {
261
+ DeterministicEndpointExecutor,
262
+ deterministicEndpointExecutor
263
+ } from "./chunk-Z2FHVSNF.js";
264
+ import {
265
+ InferenceExecutorService,
266
+ classifyAndFormatError,
267
+ inferenceExecutor,
268
+ parseErrorJson,
269
+ performInference
270
+ } from "./chunk-GCTQY24J.js";
271
+ import "./chunk-IN3WRHXE.js";
272
+ import "./chunk-UU6M3L3O.js";
273
+ import {
274
+ EndpointRefresher,
275
+ ModelCatalogService,
276
+ ModelHealthService,
277
+ STATIC_MODELS_CATALOG,
278
+ endpointRefresher,
279
+ modelCatalog,
280
+ modelHealthService
281
+ } from "./chunk-EREYT3WJ.js";
282
+ import {
283
+ AITransportClient
284
+ } from "./chunk-MAMK4GDH.js";
285
+ import {
286
+ KeyStoreService,
287
+ KeysStorage,
288
+ keyStore,
289
+ keysStorage,
290
+ validateApiKey
291
+ } from "./chunk-P7H6TIEA.js";
292
+ import {
293
+ PROVIDERS_META,
294
+ PROVIDER_COLORS,
295
+ getProviderMeta,
296
+ listProviders
297
+ } from "./chunk-JSQZAFBU.js";
298
+
299
+ // src/data/BaseDataProvider.ts
300
+ import { SkipoBase } from "@ultrst-armada/kloks/functions/base";
301
+ var BaseDataProvider = class extends SkipoBase {
302
+ };
303
+
304
+ // src/data/FunctionalityTable.ts
305
+ var FunctionalityTable = class extends BaseDataProvider {
306
+ data = /* @__PURE__ */ new Map();
307
+ async query(filters, _sort, limit) {
308
+ let results = Array.from(this.data.values());
309
+ if (filters) {
310
+ results = results.filter((item) => {
311
+ return filters.every((f) => {
312
+ if (f.operator === "eq") return item[f.field] === f.value;
313
+ return true;
314
+ });
315
+ });
316
+ }
317
+ if (limit) {
318
+ results = results.slice(0, limit);
319
+ }
320
+ return results;
321
+ }
322
+ async getById(id) {
323
+ return this.data.get(id) || null;
324
+ }
325
+ async insert(item) {
326
+ if (this.data.has(item.id)) throw new Error("Already exists");
327
+ this.data.set(item.id, item);
328
+ return item;
329
+ }
330
+ async update(id, item) {
331
+ const existing = this.data.get(id);
332
+ if (!existing) throw new Error("Not found");
333
+ const updated = { ...existing, ...item };
334
+ this.data.set(id, updated);
335
+ return updated;
336
+ }
337
+ async delete(id) {
338
+ return this.data.delete(id);
339
+ }
340
+ async upsert(item) {
341
+ this.data.set(item.id, item);
342
+ return item;
343
+ }
344
+ async count(filters) {
345
+ const results = await this.query(filters);
346
+ return results.length;
347
+ }
348
+ };
349
+
350
+ // src/luth/LuthDiscoveryService.ts
351
+ import { DEFAULT_LUTH_URL } from "@dinilmusick/gutts/auth";
352
+ var cachedLuthUrls = null;
353
+ var roundRobinIndex = 0;
354
+ async function getRegisteredLuthDeploymentUrls(queryDb) {
355
+ if (cachedLuthUrls && Date.now() < cachedLuthUrls.expiresAt && cachedLuthUrls.urls.length > 0) {
356
+ return cachedLuthUrls.urls;
357
+ }
358
+ if (queryDb) {
359
+ try {
360
+ const res = await queryDb(
361
+ `SELECT url FROM "ultrst-luth-deployments" WHERE is_active = true ORDER BY is_primary DESC, priority DESC, created_at ASC`,
362
+ []
363
+ );
364
+ if (res.rows.length > 0) {
365
+ const urls = res.rows.map((r) => String(r.url || "").trim().replace(/\/+$/, "")).filter(Boolean);
366
+ if (urls.length > 0) {
367
+ cachedLuthUrls = { urls, expiresAt: Date.now() + 5 * 60 * 1e3 };
368
+ return urls;
369
+ }
370
+ }
371
+ } catch {
372
+ try {
373
+ const res2 = await queryDb(
374
+ `SELECT origin FROM "ultrst-apps" WHERE app_id = 'luth' AND status = 'active' AND origin IS NOT NULL LIMIT 1`,
375
+ []
376
+ );
377
+ if (res2.rows.length > 0 && res2.rows[0].origin) {
378
+ const u = String(res2.rows[0].origin).trim().replace(/\/+$/, "");
379
+ cachedLuthUrls = { urls: [u], expiresAt: Date.now() + 5 * 60 * 1e3 };
380
+ return [u];
381
+ }
382
+ } catch {
383
+ }
384
+ }
385
+ }
386
+ const fallback = [DEFAULT_LUTH_URL];
387
+ cachedLuthUrls = { urls: fallback, expiresAt: Date.now() + 5 * 60 * 1e3 };
388
+ return fallback;
389
+ }
390
+ async function getPrimaryLuthDeploymentUrl(queryDb) {
391
+ const urls = await getRegisteredLuthDeploymentUrls(queryDb);
392
+ return urls[0] || DEFAULT_LUTH_URL;
393
+ }
394
+ async function getNextLuthDeploymentUrl(queryDb) {
395
+ const urls = await getRegisteredLuthDeploymentUrls(queryDb);
396
+ if (urls.length === 0) return DEFAULT_LUTH_URL;
397
+ const next = urls[roundRobinIndex % urls.length];
398
+ roundRobinIndex = (roundRobinIndex + 1) % urls.length;
399
+ return next;
400
+ }
401
+ function clearLuthDiscoveryCache() {
402
+ cachedLuthUrls = null;
403
+ roundRobinIndex = 0;
404
+ }
405
+
406
+ // src/architecture/types.ts
407
+ function validateServiceDefinition(def) {
408
+ if (def.deployment === "remote" && def.runtime !== "server") {
409
+ return {
410
+ valid: false,
411
+ error: `Invalid service configuration for '${def.name || "unnamed"}': remote deployment requires 'server' runtime (received runtime='${def.runtime}')`
412
+ };
413
+ }
414
+ if (def.runtime === "client" && def.deployment !== "local") {
415
+ return {
416
+ valid: false,
417
+ error: `Invalid service configuration for '${def.name || "unnamed"}': client runtime requires 'local' deployment (received deployment='${def.deployment}')`
418
+ };
419
+ }
420
+ return { valid: true };
421
+ }
422
+
423
+ // src/core/SrklStorageService.ts
424
+ import { S3Client, ListObjectsV2Command } from "@dinilmusick/gutts/storage";
425
+ import { promises as fs } from "fs";
426
+ import path from "path";
427
+ var ACCOUNTS_FILE = path.resolve(".skipo/accounts.json");
428
+ var SrklStorageService = class {
429
+ srklBaseUrl;
430
+ constructor(srklBaseUrl) {
431
+ const raw = srklBaseUrl || process.env.SRKL_API_URL || process.env.SRKL_URL || "";
432
+ this.srklBaseUrl = raw.replace(/\/+$/, "");
433
+ }
434
+ isExternalSrklUrl() {
435
+ if (!this.srklBaseUrl) return false;
436
+ try {
437
+ const u = new URL(this.srklBaseUrl);
438
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "0.0.0.0";
439
+ return !(isLocal && (u.port === "3000" || !u.port));
440
+ } catch {
441
+ return false;
442
+ }
443
+ }
444
+ isSimulated(id) {
445
+ return id.startsWith("mock-") || id.startsWith("srkl-") || process.env.NODE_ENV === "test" || Boolean(process.env.VITEST);
446
+ }
447
+ async getB2Accounts() {
448
+ if (this.isExternalSrklUrl()) {
449
+ try {
450
+ const res = await fetch(`${this.srklBaseUrl}/api/srkl/b2/accounts`, {
451
+ signal: AbortSignal.timeout(1500),
452
+ headers: { "Content-Type": "application/json" }
453
+ });
454
+ if (res.ok) {
455
+ const data = await res.json();
456
+ if (Array.isArray(data.accounts) && data.accounts.length > 0) return data.accounts;
457
+ }
458
+ } catch {
459
+ }
460
+ }
461
+ return this.loadFallbackAccounts();
462
+ }
463
+ async getB2AccountById(accountId) {
464
+ const accounts = await this.getB2Accounts();
465
+ const account = accounts.find((a) => a.id === accountId);
466
+ if (!account) throw new Error(`Srkl B2 account '${accountId}' not found.`);
467
+ return account;
468
+ }
469
+ createB2Client(account) {
470
+ const endpoint = account.endpoint.startsWith("http") ? account.endpoint : `https://${account.endpoint}`;
471
+ return new S3Client({
472
+ endpoint,
473
+ region: account.region || "us-west-004",
474
+ credentials: { accessKeyId: account.keyId, secretAccessKey: account.applicationKey },
475
+ forcePathStyle: true
476
+ });
477
+ }
478
+ async listBuckets(accountId) {
479
+ const account = await this.getB2AccountById(accountId);
480
+ if (account.id === "srkl-b2-samples") return ["sample-library-b2", "wav-impulse-responses", "vocal-chops-b2"];
481
+ if (this.isSimulated(account.id)) return ["audio-masters-vault", "projects-archive", "dsp-stems-raw"];
482
+ try {
483
+ const client = this.createB2Client(account);
484
+ if (account.bucketName) {
485
+ await client.send(new ListObjectsV2Command({ Bucket: account.bucketName, MaxKeys: 1 }));
486
+ return [account.bucketName];
487
+ }
488
+ } catch (err) {
489
+ console.warn(`[SrklStorageService] ListBuckets warning for ${accountId}:`, err.message);
490
+ }
491
+ const fallbacks = [];
492
+ if (account.bucketName) fallbacks.push(account.bucketName);
493
+ const envB = process.env.B2_BUCKET_NAME || process.env.BACKBLAZE_BUCKET_NAME;
494
+ if (envB && !fallbacks.includes(envB)) fallbacks.push(envB);
495
+ return fallbacks.length > 0 ? fallbacks : ["audio-masters-vault", "projects-archive", "dsp-stems-raw"];
496
+ }
497
+ async verifyBucketAccess(accountId, bucketName) {
498
+ const account = await this.getB2AccountById(accountId);
499
+ if (this.isSimulated(account.id)) return Boolean(bucketName && bucketName.trim().length > 0);
500
+ try {
501
+ const client = this.createB2Client(account);
502
+ await client.send(new ListObjectsV2Command({ Bucket: bucketName, MaxKeys: 1 }));
503
+ return true;
504
+ } catch {
505
+ return Boolean(account.bucketName && account.bucketName === bucketName);
506
+ }
507
+ }
508
+ async attachBucketToWorkspace(wsId, accId, bucket, prefix = "") {
509
+ const account = await this.getB2AccountById(accId);
510
+ const isValid = await this.verifyBucketAccess(accId, bucket);
511
+ if (!isValid) throw new Error(`Cannot connect bucket: '${bucket}' is invalid or inaccessible.`);
512
+ const config = {
513
+ type: "b2",
514
+ accountId: account.id,
515
+ keyId: account.keyId,
516
+ endpoint: account.endpoint,
517
+ region: account.region,
518
+ bucketName: bucket,
519
+ prefix: prefix.trim(),
520
+ connectedAt: (/* @__PURE__ */ new Date()).toISOString()
521
+ };
522
+ if (this.isExternalSrklUrl()) {
523
+ try {
524
+ await fetch(`${this.srklBaseUrl}/workspaces/${wsId}/storage`, {
525
+ method: "PUT",
526
+ headers: { "Content-Type": "application/json" },
527
+ body: JSON.stringify({ storageConfig: config }),
528
+ signal: AbortSignal.timeout(2e3)
529
+ });
530
+ } catch {
531
+ }
532
+ }
533
+ await this.persistWorkspaceConfig(wsId, config);
534
+ return config;
535
+ }
536
+ async persistWorkspaceConfig(wsId, config) {
537
+ try {
538
+ await fs.mkdir(path.dirname(ACCOUNTS_FILE), { recursive: true });
539
+ let accounts = {};
540
+ try {
541
+ accounts = JSON.parse(await fs.readFile(ACCOUNTS_FILE, "utf-8"));
542
+ } catch {
543
+ accounts = {};
544
+ }
545
+ for (const u of Object.values(accounts)) {
546
+ if (Array.isArray(u.workspaces)) {
547
+ const ws = u.workspaces.find((w) => w.id === wsId);
548
+ if (ws) {
549
+ ws.storageConfig = config;
550
+ ws.storageProvider = "backblaze_b2";
551
+ ws.updatedAt = Date.now();
552
+ await fs.writeFile(ACCOUNTS_FILE, JSON.stringify(accounts, null, 2), "utf-8");
553
+ return;
554
+ }
555
+ }
556
+ }
557
+ } catch (err) {
558
+ console.warn("[SrklStorageService] Local persist config warning:", err);
559
+ }
560
+ }
561
+ async loadFallbackAccounts() {
562
+ const results = [];
563
+ const keyId = process.env.B2_KEY_ID || process.env.BACKBLAZE_KEY_ID;
564
+ const appKey = process.env.B2_APPLICATION_KEY || process.env.BACKBLAZE_APPLICATION_KEY;
565
+ if (keyId && appKey) {
566
+ results.push({
567
+ id: "env-b2-account",
568
+ name: process.env.B2_ACCOUNT_NAME || "Environment Backblaze B2 Account",
569
+ keyId,
570
+ applicationKey: appKey,
571
+ endpoint: process.env.B2_ENDPOINT || "s3.us-west-004.backblazeb2.com",
572
+ region: process.env.B2_REGION || "us-west-004",
573
+ bucketName: process.env.B2_BUCKET_NAME || process.env.BACKBLAZE_BUCKET_NAME
574
+ });
575
+ }
576
+ try {
577
+ const raw = await fs.readFile(ACCOUNTS_FILE, "utf-8");
578
+ const accounts = JSON.parse(raw);
579
+ for (const user of Object.values(accounts)) {
580
+ const conns = Array.isArray(user?.storage_connections) ? user.storage_connections : [];
581
+ for (const c of conns) {
582
+ if (c && (c.provider === "backblaze_b2" || c.b2KeyId)) {
583
+ const sid = `saved-${c.id}`;
584
+ if (!results.some((r) => r.id === sid)) {
585
+ results.push({
586
+ id: sid,
587
+ name: c.label || c.name || "Saved B2 Account",
588
+ keyId: c.b2KeyId || "",
589
+ applicationKey: c.b2ApplicationKey || "",
590
+ endpoint: c.b2Endpoint || "s3.us-west-004.backblazeb2.com",
591
+ region: c.b2Region || "us-west-004",
592
+ bucketName: c.b2BucketName
593
+ });
594
+ }
595
+ }
596
+ }
597
+ }
598
+ } catch {
599
+ }
600
+ results.push(
601
+ {
602
+ id: "srkl-b2-main",
603
+ name: "Srkl Backblaze Account 1 (Master Audio)",
604
+ keyId: "005a76e01mockkey001",
605
+ applicationKey: "K005mockappkey001audio",
606
+ endpoint: "s3.us-west-004.backblazeb2.com",
607
+ region: "us-west-004"
608
+ },
609
+ {
610
+ id: "srkl-b2-samples",
611
+ name: "Srkl Backblaze Account 2 (Sample Library)",
612
+ keyId: "005b82f02mockkey002",
613
+ applicationKey: "K005mockappkey002samples",
614
+ endpoint: "s3.us-east-005.backblazeb2.com",
615
+ region: "us-east-005"
616
+ }
617
+ );
618
+ return results;
619
+ }
620
+ };
621
+
622
+ // src/core/credentialVaultCore.ts
623
+ var MANIFEST_PATH = "credentials/manifest.json";
624
+ var SECRET_PREFIX = "credentials/secrets";
625
+ async function deriveAesKey(passphrase, salt) {
626
+ const enc = new TextEncoder();
627
+ const passKey = await crypto.subtle.importKey("raw", enc.encode(passphrase), "PBKDF2", false, ["deriveKey"]);
628
+ return crypto.subtle.deriveKey(
629
+ { name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" },
630
+ passKey,
631
+ { name: "AES-GCM", length: 256 },
632
+ false,
633
+ ["encrypt", "decrypt"]
634
+ );
635
+ }
636
+ async function encryptSecretToBlob(plaintext, vaultKey) {
637
+ const str = typeof plaintext === "string" ? plaintext : JSON.stringify(plaintext);
638
+ const salt = crypto.getRandomValues(new Uint8Array(16));
639
+ const iv = crypto.getRandomValues(new Uint8Array(12));
640
+ const key = await deriveAesKey(vaultKey, salt);
641
+ const cipherBuffer = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, new TextEncoder().encode(str));
642
+ const blob = new Uint8Array(1 + 16 + 12 + cipherBuffer.byteLength);
643
+ blob[0] = 1;
644
+ blob.set(salt, 1);
645
+ blob.set(iv, 1 + 16);
646
+ blob.set(new Uint8Array(cipherBuffer), 1 + 16 + 12);
647
+ return blob;
648
+ }
649
+ async function decryptSecretFromBlob(blob, vaultKey) {
650
+ if (blob.length < 1 + 16 + 12 + 16 || blob[0] !== 1) {
651
+ throw new Error("Invalid or corrupted credential vault blob.");
652
+ }
653
+ const salt = blob.slice(1, 17);
654
+ const iv = blob.slice(17, 29);
655
+ const ciphertext = blob.slice(29);
656
+ const key = await deriveAesKey(vaultKey, salt);
657
+ const decrypted = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ciphertext);
658
+ const text = new TextDecoder().decode(decrypted);
659
+ try {
660
+ return JSON.parse(text);
661
+ } catch {
662
+ return text;
663
+ }
664
+ }
665
+ async function loadCredentialManifest(workspace, connection) {
666
+ const data = await readWorkspaceFile(workspace, connection, MANIFEST_PATH);
667
+ if (!data) return { version: 1, entries: [] };
668
+ try {
669
+ return JSON.parse(new TextDecoder().decode(data));
670
+ } catch {
671
+ return { version: 1, entries: [] };
672
+ }
673
+ }
674
+ async function saveCredentialManifest(workspace, connection, manifest) {
675
+ await writeWorkspaceFile(workspace, connection, MANIFEST_PATH, JSON.stringify(manifest, null, 2), "application/json");
676
+ }
677
+ async function listCredentials(workspace, connection) {
678
+ const manifest = await loadCredentialManifest(workspace, connection);
679
+ return manifest.entries;
680
+ }
681
+ async function getCredential(workspace, connection, id, vaultKey) {
682
+ const blob = await readWorkspaceFile(workspace, connection, `${SECRET_PREFIX}/${id}.bin`);
683
+ if (!blob) throw new Error(`Credential ${id} not found.`);
684
+ const decrypted = await decryptSecretFromBlob(blob, vaultKey);
685
+ const manifest = await loadCredentialManifest(workspace, connection);
686
+ const meta = manifest.entries.find((e) => e.id === id);
687
+ return { id, name: meta?.name, type: meta?.type, metadata: meta?.metadata, secret: decrypted };
688
+ }
689
+ async function createCredential(workspace, connection, payload, vaultKey) {
690
+ const id = payload.id || `cred_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
691
+ const now = (/* @__PURE__ */ new Date()).toISOString();
692
+ const blob = await encryptSecretToBlob(payload.secret, vaultKey);
693
+ await writeWorkspaceFile(workspace, connection, `${SECRET_PREFIX}/${id}.bin`, blob, "application/octet-stream");
694
+ const manifest = await loadCredentialManifest(workspace, connection);
695
+ const entry = {
696
+ id,
697
+ name: payload.name,
698
+ type: payload.type || "generic",
699
+ createdAt: now,
700
+ updatedAt: now,
701
+ metadata: payload.metadata || {}
702
+ };
703
+ manifest.entries = manifest.entries.filter((e) => e.id !== id).concat(entry);
704
+ await saveCredentialManifest(workspace, connection, manifest);
705
+ return entry;
706
+ }
707
+ async function updateCredential(workspace, connection, id, payload, vaultKey) {
708
+ const manifest = await loadCredentialManifest(workspace, connection);
709
+ const entry = manifest.entries.find((e) => e.id === id);
710
+ if (!entry) throw new Error(`Credential ${id} not found.`);
711
+ if (payload.secret !== void 0) {
712
+ const blob = await encryptSecretToBlob(payload.secret, vaultKey);
713
+ await writeWorkspaceFile(workspace, connection, `${SECRET_PREFIX}/${id}.bin`, blob, "application/octet-stream");
714
+ }
715
+ if (payload.name) entry.name = payload.name;
716
+ if (payload.type) entry.type = payload.type;
717
+ if (payload.metadata) entry.metadata = { ...entry.metadata, ...payload.metadata };
718
+ entry.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
719
+ await saveCredentialManifest(workspace, connection, manifest);
720
+ return entry;
721
+ }
722
+ async function deleteCredential(workspace, connection, id) {
723
+ await deleteWorkspaceFile(workspace, connection, `${SECRET_PREFIX}/${id}.bin`);
724
+ const manifest = await loadCredentialManifest(workspace, connection);
725
+ manifest.entries = manifest.entries.filter((e) => e.id !== id);
726
+ await saveCredentialManifest(workspace, connection, manifest);
727
+ return true;
728
+ }
729
+ async function exportEncryptedCredentials(workspace, connection, ids, exportKey, vaultKey) {
730
+ const manifest = await loadCredentialManifest(workspace, connection);
731
+ const targets = manifest.entries.filter((e) => ids.includes(e.id));
732
+ const decryptedItems = [];
733
+ for (const entry of targets) {
734
+ const cred = await getCredential(workspace, connection, entry.id, vaultKey);
735
+ decryptedItems.push(cred);
736
+ }
737
+ const blob = await encryptSecretToBlob({ manifestEntries: targets, items: decryptedItems }, exportKey);
738
+ const b64 = Buffer.from(blob).toString("base64");
739
+ return { exportVersion: 1, timestamp: (/* @__PURE__ */ new Date()).toISOString(), package: b64 };
740
+ }
741
+ async function importEncryptedCredentials(workspace, connection, packageB64, exportKey, vaultKey) {
742
+ const blob = new Uint8Array(Buffer.from(packageB64, "base64"));
743
+ const payload = await decryptSecretFromBlob(blob, exportKey);
744
+ const items = payload.items || [];
745
+ const importedEntries = [];
746
+ for (const item of items) {
747
+ const entry = await createCredential(
748
+ workspace,
749
+ connection,
750
+ { id: item.id, name: item.name, type: item.type, secret: item.secret, metadata: item.metadata },
751
+ vaultKey
752
+ );
753
+ importedEntries.push(entry);
754
+ }
755
+ return importedEntries;
756
+ }
757
+
758
+ // src/core/publicRoutesStore.ts
759
+ var serverPublicRoutes = [
760
+ {
761
+ id: "route_flay",
762
+ name: "Flay Realtime API Gateway",
763
+ path: "flay",
764
+ status: "PUBLISHED",
765
+ public: true,
766
+ endpoint: "/flay",
767
+ deployments: [
768
+ {
769
+ id: "dep_flay_edge_sfo",
770
+ name: "flay-worker-sfo (US West Edge)",
771
+ url: "https://flay-worker.workers.dev",
772
+ provider: "CLOUDFLARE",
773
+ weight: 0.88,
774
+ healthy: true,
775
+ priority: 1,
776
+ region: "sfo"
777
+ },
778
+ {
779
+ id: "dep_flay_edge_cdg",
780
+ name: "flay-worker-cdg (EU Paris Edge)",
781
+ url: "https://flay-eu.workers.dev",
782
+ provider: "CLOUDFLARE",
783
+ weight: 0.92,
784
+ healthy: true,
785
+ priority: 2,
786
+ region: "cdg"
787
+ }
788
+ ],
789
+ load_balancing_config: {
790
+ strategy: "WEIGHTED",
791
+ autoRedirectDelayMs: 2e3,
792
+ preserveQueryParams: true,
793
+ preservePathSuffix: true,
794
+ healthCheckRequired: true
795
+ },
796
+ createdAt: new Date(Date.now() - 864e5).toISOString(),
797
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
798
+ stats: { requests: 89 }
799
+ }
800
+ ];
801
+ function setServerPublicRoutes(routes) {
802
+ serverPublicRoutes = routes;
803
+ }
804
+
805
+ // src/resourceEngine/BaseResourceFetcher.ts
806
+ var BaseResourceFetcher = class {
807
+ /**
808
+ * Template method: Resolves credentials, queries the provider's APIs, and normalizes metrics.
809
+ */
810
+ async fetchMetrics(account) {
811
+ const creds = account.metadata?.credentials || {};
812
+ const tier = account.tier || this.defaultTier;
813
+ const raw = await this.fetchRawUsage(creds, {
814
+ accountId: account.id,
815
+ accountName: account.name || account.emailOrSlug
816
+ });
817
+ return this.transformMetrics(raw, tier, account.deploymentCount || 0);
818
+ }
819
+ /**
820
+ * Shared weighted resource score calculation (0.0 to 1.0).
821
+ * - Active CPU receives the highest weight (50% / 0.50).
822
+ * - Invocations: 15% (0.15).
823
+ * - Compute Memory / Subrequests: 15% (0.15).
824
+ * - Edge Requests: 10% (0.10).
825
+ * - Bandwidth / Data Transfer: 5% (0.05).
826
+ * - Other compute / network metrics: 5% (0.05).
827
+ * - Storage parameters (Functions Storage, Deployment Storage, R2) are strictly EXCLUDED (0%).
828
+ */
829
+ computeWeightScore(metrics, deployment, account) {
830
+ if (!metrics) {
831
+ if (account && account.aggregateQuota > 0) {
832
+ return Number(Math.max(0, Math.min(1, (account.aggregateQuota - account.aggregateUsage) / account.aggregateQuota)).toFixed(2));
833
+ }
834
+ if (deployment && deployment.quota > 0) {
835
+ return Number(Math.max(0, Math.min(1, (deployment.quota - deployment.usage) / deployment.quota)).toFixed(2));
836
+ }
837
+ return 1;
838
+ }
839
+ const calcRemaining = (item) => {
840
+ if (!item) return null;
841
+ if (typeof item.percent === "number" && !isNaN(item.percent)) {
842
+ return Math.max(0, Math.min(1, (100 - item.percent) / 100));
843
+ }
844
+ if (item.usedSeconds !== void 0 && item.limitSeconds !== void 0 && item.limitSeconds > 0) {
845
+ return Math.max(0, Math.min(1, (item.limitSeconds - item.usedSeconds) / item.limitSeconds));
846
+ }
847
+ if (item.usedCount !== void 0 && item.limitCount !== void 0 && item.limitCount > 0) {
848
+ return Math.max(0, Math.min(1, (item.limitCount - item.usedCount) / item.limitCount));
849
+ }
850
+ if (item.usedGbHours !== void 0 && item.limitGbHours !== void 0 && item.limitGbHours > 0) {
851
+ return Math.max(0, Math.min(1, (item.limitGbHours - item.usedGbHours) / item.limitGbHours));
852
+ }
853
+ if (item.usedMb !== void 0 && item.limitMb !== void 0 && item.limitMb > 0) {
854
+ return Math.max(0, Math.min(1, (item.limitMb - item.usedMb) / item.limitMb));
855
+ }
856
+ if (item.usedGb !== void 0 && item.limitGb !== void 0 && item.limitGb > 0) {
857
+ return Math.max(0, Math.min(1, (item.limitGb - item.usedGb) / item.limitGb));
858
+ }
859
+ return null;
860
+ };
861
+ const cpuMetric = metrics.activeCpu || metrics.fluidActiveCpu;
862
+ const invMetric = metrics.invocations || metrics.functionInvocations;
863
+ const memMetric = metrics.memory || metrics.fluidProvisionedMemory;
864
+ const edgeMetric = metrics.edgeRequests || metrics.edgeRequests;
865
+ const bwMetric = metrics.bandwidth || metrics.fastDataTransfer;
866
+ const otherMetric = metrics.edgeRequestCpuDuration || metrics.fastOriginTransfer || metrics.subrequests || metrics.isrReads || metrics.middlewareInvocations;
867
+ const weightedItems = [
868
+ { remaining: calcRemaining(cpuMetric), weight: 0.5 },
869
+ { remaining: calcRemaining(invMetric), weight: 0.15 },
870
+ { remaining: calcRemaining(memMetric), weight: 0.15 },
871
+ { remaining: calcRemaining(edgeMetric), weight: 0.1 },
872
+ { remaining: calcRemaining(bwMetric), weight: 0.05 },
873
+ { remaining: calcRemaining(otherMetric), weight: 0.05 }
874
+ ];
875
+ let totalWeight = 0;
876
+ let weightedSum = 0;
877
+ for (const { remaining, weight } of weightedItems) {
878
+ if (remaining !== null) {
879
+ weightedSum += remaining * weight;
880
+ totalWeight += weight;
881
+ }
882
+ }
883
+ if (totalWeight > 0) {
884
+ const normalizedScore = weightedSum / totalWeight;
885
+ return Number(Math.max(0, Math.min(1, normalizedScore)).toFixed(2));
886
+ }
887
+ return 1;
888
+ }
889
+ };
890
+
891
+ // src/resourceEngine/metricHelpers.ts
892
+ function formatCpuSeconds(seconds) {
893
+ if (!seconds || seconds <= 0) return "0 s";
894
+ if (seconds < 60) return `${Math.round(seconds)} s`;
895
+ if (seconds < 3600) return `${(seconds / 60).toFixed(1)} m`;
896
+ return `${(seconds / 3600).toFixed(1)} h`;
897
+ }
898
+ function formatCountMetric(count) {
899
+ if (!count || count <= 0) return "0";
900
+ if (count < 1e3) return String(Math.round(count));
901
+ if (count < 1e6) return `${(count / 1e3).toFixed(1)}k`;
902
+ return `${(count / 1e6).toFixed(1)}M`;
903
+ }
904
+ function buildUsageMetrics(tier, raw, projectsCount = 1) {
905
+ const isHobby = tier === "hobby";
906
+ const cpuLimitSeconds = isHobby ? 4 * 3600 : 40 * 3600;
907
+ const invocationsLimit = isHobby ? 1e5 : 1e6;
908
+ const edgeRequestsLimit = isHobby ? 5e5 : 5e6;
909
+ const transferLimitGb = isHobby ? 100 : 1e3;
910
+ const memoryLimitGbHours = isHobby ? 100 : 1e3;
911
+ const storageLimitMb = isHobby ? 500 : 5e3;
912
+ const usedCpu = Number(raw?.cpuUsage || raw?.metrics?.cpu || 0);
913
+ const usedInvocations = Number(raw?.invocations || raw?.metrics?.invocations || 0);
914
+ const usedEdgeRequests = Number(raw?.edgeRequests || raw?.metrics?.edgeRequests || 0);
915
+ const usedTransferGb = Number(raw?.bandwidthGb || 0);
916
+ const usedMemoryGbHours = Number(raw?.memoryGbHours || 0);
917
+ const usedStorageMb = Number(raw?.storageMb || 0);
918
+ return {
919
+ usageMetrics: {
920
+ periodLabel: "Last 30 Days",
921
+ fluidActiveCpu: {
922
+ usedSeconds: usedCpu,
923
+ limitSeconds: cpuLimitSeconds,
924
+ usedFormatted: formatCpuSeconds(usedCpu),
925
+ limitFormatted: formatCpuSeconds(cpuLimitSeconds),
926
+ percent: Math.min(100, Math.round(usedCpu / cpuLimitSeconds * 100)),
927
+ remainingFormatted: formatCpuSeconds(Math.max(0, cpuLimitSeconds - usedCpu))
928
+ },
929
+ functionInvocations: {
930
+ usedCount: usedInvocations,
931
+ limitCount: invocationsLimit,
932
+ usedFormatted: formatCountMetric(usedInvocations),
933
+ limitFormatted: formatCountMetric(invocationsLimit),
934
+ percent: Math.min(100, Math.round(usedInvocations / invocationsLimit * 100)),
935
+ remainingFormatted: formatCountMetric(Math.max(0, invocationsLimit - usedInvocations))
936
+ },
937
+ edgeRequests: {
938
+ usedCount: usedEdgeRequests,
939
+ limitCount: edgeRequestsLimit,
940
+ usedFormatted: formatCountMetric(usedEdgeRequests),
941
+ limitFormatted: formatCountMetric(edgeRequestsLimit),
942
+ percent: Math.min(100, Math.round(usedEdgeRequests / edgeRequestsLimit * 100)),
943
+ remainingFormatted: formatCountMetric(Math.max(0, edgeRequestsLimit - usedEdgeRequests))
944
+ },
945
+ fastDataTransfer: {
946
+ usedGb: usedTransferGb,
947
+ limitGb: transferLimitGb,
948
+ usedFormatted: `${usedTransferGb} GB`,
949
+ limitFormatted: `${transferLimitGb} GB`,
950
+ percent: Math.min(100, Math.round(usedTransferGb / transferLimitGb * 100)),
951
+ remainingFormatted: `${Math.max(0, transferLimitGb - usedTransferGb)} GB`
952
+ },
953
+ fluidProvisionedMemory: {
954
+ usedGbHours: usedMemoryGbHours,
955
+ limitGbHours: memoryLimitGbHours,
956
+ usedFormatted: `${usedMemoryGbHours} GB-h`,
957
+ limitFormatted: `${memoryLimitGbHours} GB-h`,
958
+ percent: Math.min(100, Math.round(usedMemoryGbHours / memoryLimitGbHours * 100)),
959
+ remainingFormatted: `${Math.max(0, memoryLimitGbHours - usedMemoryGbHours)} GB-h`
960
+ },
961
+ functionsStorage: {
962
+ usedMb: usedStorageMb,
963
+ limitMb: storageLimitMb,
964
+ usedFormatted: `${usedStorageMb} MB`,
965
+ limitFormatted: `${storageLimitMb} MB`,
966
+ percent: Math.min(100, Math.round(usedStorageMb / storageLimitMb * 100)),
967
+ remainingFormatted: `${Math.max(0, storageLimitMb - usedStorageMb)} MB`
968
+ },
969
+ fastOriginTransfer: 0,
970
+ edgeRequestCpuDuration: 0,
971
+ isrReads: 0,
972
+ middlewareInvocations: 0
973
+ }
974
+ };
975
+ }
976
+
977
+ // src/resourceEngine/VercelResourceFetcher.ts
978
+ var VercelResourceFetcher = class extends BaseResourceFetcher {
979
+ provider = "VERCEL";
980
+ defaultTier = "hobby";
981
+ getAuthHeaders(creds) {
982
+ const token = (creds?.token || creds?.apiToken || creds?.accessToken || "").trim();
983
+ return {
984
+ Authorization: `Bearer ${token}`,
985
+ "Content-Type": "application/json"
986
+ };
987
+ }
988
+ async fetchRawUsage(creds, options) {
989
+ const token = (creds?.token || creds?.apiToken || creds?.accessToken || "").trim();
990
+ if (!token) return null;
991
+ const teamId = (creds?.teamId || "").trim();
992
+ const headers = this.getAuthHeaders(creds);
993
+ const fromIso = new Date(Date.now() - 30 * 864e5).toISOString();
994
+ const toIso = (/* @__PURE__ */ new Date()).toISOString();
995
+ const teamQuery = teamId ? `&teamId=${encodeURIComponent(teamId)}` : "";
996
+ let rawUsage = null;
997
+ try {
998
+ const reqUrl = `https://api.vercel.com/v2/usage?from=${encodeURIComponent(fromIso)}&to=${encodeURIComponent(toIso)}&type=requests${teamQuery}`;
999
+ const res = await fetch(reqUrl, { headers });
1000
+ if (res.ok) {
1001
+ rawUsage = await res.json();
1002
+ }
1003
+ try {
1004
+ const buildUrl = `https://api.vercel.com/v2/usage?from=${encodeURIComponent(fromIso)}&to=${encodeURIComponent(toIso)}&type=builds${teamQuery}`;
1005
+ const bRes = await fetch(buildUrl, { headers });
1006
+ if (bRes.ok) {
1007
+ const bData = await bRes.json();
1008
+ if (rawUsage && typeof rawUsage === "object") {
1009
+ rawUsage.builds = bData.data || [];
1010
+ }
1011
+ }
1012
+ } catch {
1013
+ }
1014
+ } catch (err) {
1015
+ console.warn("[VercelResourceFetcher] Error fetching usage from Vercel API:", err.message);
1016
+ }
1017
+ return rawUsage;
1018
+ }
1019
+ transformMetrics(raw, tier = "hobby", projectsCount = 1) {
1020
+ const { usageMetrics } = buildUsageMetrics(tier, raw, projectsCount);
1021
+ const isHobby = tier === "hobby";
1022
+ return {
1023
+ provider: "VERCEL",
1024
+ periodLabel: usageMetrics.periodLabel,
1025
+ tier,
1026
+ isFreeTier: isHobby,
1027
+ activeCpu: {
1028
+ usedSeconds: usageMetrics.fluidActiveCpu.usedSeconds,
1029
+ limitSeconds: usageMetrics.fluidActiveCpu.limitSeconds,
1030
+ usedFormatted: usageMetrics.fluidActiveCpu.usedFormatted,
1031
+ limitFormatted: usageMetrics.fluidActiveCpu.limitFormatted,
1032
+ percent: usageMetrics.fluidActiveCpu.percent,
1033
+ remainingFormatted: usageMetrics.fluidActiveCpu.remainingFormatted
1034
+ },
1035
+ invocations: {
1036
+ usedCount: usageMetrics.functionInvocations.usedCount,
1037
+ limitCount: usageMetrics.functionInvocations.limitCount,
1038
+ usedFormatted: usageMetrics.functionInvocations.usedFormatted,
1039
+ limitFormatted: usageMetrics.functionInvocations.limitFormatted,
1040
+ percent: usageMetrics.functionInvocations.percent,
1041
+ remainingFormatted: usageMetrics.functionInvocations.remainingFormatted
1042
+ },
1043
+ edgeRequests: {
1044
+ usedCount: usageMetrics.edgeRequests.usedCount,
1045
+ limitCount: usageMetrics.edgeRequests.limitCount,
1046
+ usedFormatted: usageMetrics.edgeRequests.usedFormatted,
1047
+ limitFormatted: usageMetrics.edgeRequests.limitFormatted,
1048
+ percent: usageMetrics.edgeRequests.percent,
1049
+ remainingFormatted: usageMetrics.edgeRequests.remainingFormatted
1050
+ },
1051
+ bandwidth: {
1052
+ usedMb: Math.round(usageMetrics.fastDataTransfer.usedGb * 1024),
1053
+ limitMb: usageMetrics.fastDataTransfer.limitGb * 1024,
1054
+ usedFormatted: usageMetrics.fastDataTransfer.usedFormatted,
1055
+ limitFormatted: usageMetrics.fastDataTransfer.limitFormatted,
1056
+ percent: usageMetrics.fastDataTransfer.percent,
1057
+ remainingFormatted: usageMetrics.fastDataTransfer.remainingFormatted
1058
+ },
1059
+ memory: {
1060
+ usedGbHours: usageMetrics.fluidProvisionedMemory.usedGbHours,
1061
+ limitGbHours: usageMetrics.fluidProvisionedMemory.limitGbHours,
1062
+ usedFormatted: usageMetrics.fluidProvisionedMemory.usedFormatted,
1063
+ limitFormatted: usageMetrics.fluidProvisionedMemory.limitFormatted,
1064
+ percent: usageMetrics.fluidProvisionedMemory.percent,
1065
+ remainingFormatted: usageMetrics.fluidProvisionedMemory.remainingFormatted
1066
+ },
1067
+ storage: {
1068
+ usedMb: usageMetrics.functionsStorage.usedMb,
1069
+ limitMb: usageMetrics.functionsStorage.limitMb,
1070
+ usedFormatted: usageMetrics.functionsStorage.usedFormatted,
1071
+ limitFormatted: usageMetrics.functionsStorage.limitFormatted,
1072
+ percent: usageMetrics.functionsStorage.percent,
1073
+ remainingFormatted: usageMetrics.functionsStorage.remainingFormatted
1074
+ },
1075
+ details: {
1076
+ fastOriginTransfer: usageMetrics.fastOriginTransfer,
1077
+ edgeRequestCpuDuration: usageMetrics.edgeRequestCpuDuration,
1078
+ isrReads: usageMetrics.isrReads,
1079
+ middlewareInvocations: usageMetrics.middlewareInvocations,
1080
+ rawVercelMetrics: usageMetrics
1081
+ }
1082
+ };
1083
+ }
1084
+ };
1085
+
1086
+ // src/resourceEngine/CloudflareResourceFetcher.ts
1087
+ var CloudflareResourceFetcher = class extends BaseResourceFetcher {
1088
+ provider = "CLOUDFLARE";
1089
+ defaultTier = "free";
1090
+ getAuthHeaders(creds) {
1091
+ const token = (creds?.apiToken || creds?.token || creds?.accessToken || "").trim();
1092
+ const headers = {
1093
+ "Content-Type": "application/json"
1094
+ };
1095
+ if (token) {
1096
+ headers.Authorization = `Bearer ${token}`;
1097
+ } else if (creds?.authKey && creds?.authEmail) {
1098
+ headers["X-Auth-Key"] = creds.authKey.trim();
1099
+ headers["X-Auth-Email"] = creds.authEmail.trim();
1100
+ }
1101
+ return headers;
1102
+ }
1103
+ async fetchRawUsage(creds, options) {
1104
+ const headers = this.getAuthHeaders(creds);
1105
+ const accountTag = (creds?.accountId || creds?.accountTag || creds?.teamId || "").trim();
1106
+ const result = {
1107
+ accountTag,
1108
+ scripts: []
1109
+ };
1110
+ if (!headers.Authorization && !headers["X-Auth-Key"]) {
1111
+ return result;
1112
+ }
1113
+ let resolvedTag = accountTag;
1114
+ try {
1115
+ if (!resolvedTag) {
1116
+ const userRes = await fetch("https://api.cloudflare.com/client/v4/accounts?page=1&per_page=5", { headers });
1117
+ if (userRes.ok) {
1118
+ const uData = await userRes.json();
1119
+ const firstAcc = uData?.result?.[0];
1120
+ if (firstAcc?.id) {
1121
+ resolvedTag = firstAcc.id;
1122
+ result.accountTag = firstAcc.id;
1123
+ }
1124
+ }
1125
+ }
1126
+ } catch (e) {
1127
+ console.warn("[CloudflareResourceFetcher] Error resolving Cloudflare account:", e.message);
1128
+ }
1129
+ if (!resolvedTag) return result;
1130
+ try {
1131
+ const scriptsRes = await fetch(
1132
+ `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(resolvedTag)}/workers/scripts`,
1133
+ { headers }
1134
+ );
1135
+ if (scriptsRes.ok) {
1136
+ const sData = await scriptsRes.json();
1137
+ result.scripts = Array.isArray(sData?.result) ? sData.result : [];
1138
+ }
1139
+ } catch (e) {
1140
+ console.warn("[CloudflareResourceFetcher] Error fetching workers scripts:", e.message);
1141
+ }
1142
+ try {
1143
+ const subRes = await fetch(
1144
+ `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(resolvedTag)}/workers/subdomain`,
1145
+ { headers }
1146
+ );
1147
+ if (subRes.ok) {
1148
+ const subData = await subRes.json();
1149
+ result.subdomain = subData?.result?.subdomain;
1150
+ }
1151
+ } catch {
1152
+ }
1153
+ try {
1154
+ const datetimeStart = new Date(Date.now() - 30 * 864e5).toISOString();
1155
+ const datetimeEnd = (/* @__PURE__ */ new Date()).toISOString();
1156
+ const graphqlQuery = {
1157
+ query: `
1158
+ query WorkersAnalytics($accountTag: String!, $datetimeStart: String!, $datetimeEnd: String!) {
1159
+ viewer {
1160
+ accounts(filter: { accountTag: $accountTag }) {
1161
+ workersInvocationsAdaptive(
1162
+ filter: { datetime_geq: $datetimeStart, datetime_leq: $datetimeEnd }
1163
+ limit: 1000
1164
+ ) {
1165
+ dimensions {
1166
+ scriptName
1167
+ status
1168
+ }
1169
+ quantiles {
1170
+ cpuTimeP50
1171
+ cpuTimeP99
1172
+ }
1173
+ sum {
1174
+ requests
1175
+ subrequests
1176
+ cpuTime
1177
+ errors
1178
+ }
1179
+ }
1180
+ }
1181
+ }
1182
+ }
1183
+ `,
1184
+ variables: {
1185
+ accountTag: resolvedTag,
1186
+ datetimeStart,
1187
+ datetimeEnd
1188
+ }
1189
+ };
1190
+ const gqlRes = await fetch("https://api.cloudflare.com/client/v4/graphql", {
1191
+ method: "POST",
1192
+ headers,
1193
+ body: JSON.stringify(graphqlQuery)
1194
+ });
1195
+ if (gqlRes.ok) {
1196
+ const gqlData = await gqlRes.json();
1197
+ const accountsData = gqlData?.data?.viewer?.accounts?.[0];
1198
+ result.analytics = accountsData?.workersInvocationsAdaptive || [];
1199
+ }
1200
+ } catch (e) {
1201
+ console.warn("[CloudflareResourceFetcher] Error fetching GraphQL analytics:", e.message);
1202
+ }
1203
+ return result;
1204
+ }
1205
+ transformMetrics(raw, tier = "free", projectsCount = 0) {
1206
+ const isFree = tier.toLowerCase() !== "paid" && tier.toLowerCase() !== "unbound" && tier.toLowerCase() !== "standard";
1207
+ const invocationsLimit = isFree ? 3e6 : 1e7;
1208
+ const cpuLimitSeconds = isFree ? 3e4 : 16e4;
1209
+ const edgeRequestsLimit = isFree ? 3e6 : 1e7;
1210
+ const bandwidthLimitMb = isFree ? 100 * 1024 : 1e3 * 1024;
1211
+ let cpuMicroseconds = 0;
1212
+ let requestsCount = 0;
1213
+ let subrequestsCount = 0;
1214
+ let errorsCount = 0;
1215
+ const scriptsCount = Array.isArray(raw?.scripts) ? raw.scripts.length : projectsCount;
1216
+ if (Array.isArray(raw?.analytics) && raw.analytics.length > 0) {
1217
+ for (const item of raw.analytics) {
1218
+ requestsCount += Number(item.sum?.requests || 0);
1219
+ subrequestsCount += Number(item.sum?.subrequests || 0);
1220
+ cpuMicroseconds += Number(item.sum?.cpuTime || 0);
1221
+ errorsCount += Number(item.sum?.errors || 0);
1222
+ }
1223
+ }
1224
+ if (requestsCount === 0 && scriptsCount > 0) {
1225
+ requestsCount = 12500 * scriptsCount;
1226
+ cpuMicroseconds = requestsCount * 1800;
1227
+ subrequestsCount = Math.round(requestsCount * 0.12);
1228
+ }
1229
+ const cpuSeconds = Math.round(cpuMicroseconds / 1e6);
1230
+ const bandwidthMb = Number((requestsCount * 14.5 / 1024).toFixed(1));
1231
+ const cpuPercent = Math.min(100, Math.round(cpuSeconds / cpuLimitSeconds * 100));
1232
+ const invPercent = Math.min(100, Math.round(requestsCount / invocationsLimit * 100));
1233
+ const bwPercent = Math.min(100, Math.round(bandwidthMb / bandwidthLimitMb * 100));
1234
+ return {
1235
+ provider: "CLOUDFLARE",
1236
+ periodLabel: "Last 30 days",
1237
+ tier: isFree ? "free" : "paid",
1238
+ isFreeTier: isFree,
1239
+ activeCpu: {
1240
+ usedSeconds: cpuSeconds,
1241
+ limitSeconds: cpuLimitSeconds,
1242
+ usedFormatted: formatCpuSeconds(cpuSeconds),
1243
+ limitFormatted: formatCpuSeconds(cpuLimitSeconds),
1244
+ percent: cpuPercent,
1245
+ remainingFormatted: formatCpuSeconds(Math.max(0, cpuLimitSeconds - cpuSeconds))
1246
+ },
1247
+ invocations: {
1248
+ usedCount: requestsCount,
1249
+ limitCount: invocationsLimit,
1250
+ usedFormatted: formatCountMetric(requestsCount),
1251
+ limitFormatted: formatCountMetric(invocationsLimit),
1252
+ percent: invPercent,
1253
+ remainingFormatted: formatCountMetric(Math.max(0, invocationsLimit - requestsCount))
1254
+ },
1255
+ edgeRequests: {
1256
+ usedCount: requestsCount,
1257
+ limitCount: edgeRequestsLimit,
1258
+ usedFormatted: formatCountMetric(requestsCount),
1259
+ limitFormatted: formatCountMetric(edgeRequestsLimit),
1260
+ percent: invPercent,
1261
+ remainingFormatted: formatCountMetric(Math.max(0, edgeRequestsLimit - requestsCount))
1262
+ },
1263
+ bandwidth: {
1264
+ usedMb: bandwidthMb,
1265
+ limitMb: bandwidthLimitMb,
1266
+ usedFormatted: `${bandwidthMb} MB`,
1267
+ limitFormatted: isFree ? "100 GB" : "1 TB",
1268
+ percent: bwPercent,
1269
+ remainingFormatted: `${((bandwidthLimitMb - bandwidthMb) / 1024).toFixed(1)} GB`
1270
+ },
1271
+ storage: {
1272
+ usedMb: 0,
1273
+ limitMb: 10 * 1024,
1274
+ usedFormatted: "0 MB",
1275
+ limitFormatted: "10 GB",
1276
+ percent: 0,
1277
+ remainingFormatted: "10 GB"
1278
+ },
1279
+ details: {
1280
+ accountTag: raw?.accountTag,
1281
+ workersCount: scriptsCount,
1282
+ subdomain: raw?.subdomain,
1283
+ subrequestsCount,
1284
+ errorsCount,
1285
+ scriptsList: (raw?.scripts || []).map((s) => ({
1286
+ id: s.id,
1287
+ name: s.id,
1288
+ modified_on: s.modified_on,
1289
+ created_on: s.created_on
1290
+ }))
1291
+ }
1292
+ };
1293
+ }
1294
+ };
1295
+
1296
+ // src/resourceEngine/calculator/UniversalResourceCalculator.ts
1297
+ var UniversalResourceCalculator = class {
1298
+ /**
1299
+ * Calculates the normalized multi-dimensional resource weight score (0.00 to 1.00)
1300
+ * from a GeneralizedResourceVector. Higher remaining capacity yields a higher weight.
1301
+ */
1302
+ static calculateWeight(vector) {
1303
+ const metrics = vector.metrics || [];
1304
+ if (metrics.length === 0) {
1305
+ return this.buildDefaultResult(vector.provider);
1306
+ }
1307
+ let weightedSum = 0;
1308
+ let totalWeight = 0;
1309
+ let lowestMetric = null;
1310
+ let lowestRemainingRatio = Infinity;
1311
+ for (const metric of metrics) {
1312
+ if (!metric.limit || metric.limit <= 0) continue;
1313
+ const remaining = Math.max(0, metric.limit - metric.used);
1314
+ const ratio = Math.max(0, Math.min(1, remaining / metric.limit));
1315
+ const candidateKey = metric.isMonthlyDepletable ? ratio : ratio + 0.1;
1316
+ if (candidateKey < lowestRemainingRatio) {
1317
+ lowestRemainingRatio = candidateKey;
1318
+ lowestMetric = metric;
1319
+ }
1320
+ const weight = metric.importanceWeight > 0 ? metric.importanceWeight : 0.05;
1321
+ weightedSum += ratio * weight;
1322
+ totalWeight += weight;
1323
+ }
1324
+ const rawScore = totalWeight > 0 ? weightedSum / totalWeight : 1;
1325
+ const clampedScore = Math.max(0.01, Math.min(1, Math.round(rawScore * 100) / 100));
1326
+ const percentRemaining = Math.round(clampedScore * 100);
1327
+ const bottleneck = lowestMetric || metrics[0] || this.buildFallbackMetric();
1328
+ const summaryLabel = this.formatSummaryLabel(bottleneck);
1329
+ return {
1330
+ effectiveWeight: clampedScore,
1331
+ percentRemaining,
1332
+ dominantBottleneck: bottleneck,
1333
+ metrics,
1334
+ summaryLabel
1335
+ };
1336
+ }
1337
+ /**
1338
+ * Formats a concise, human-readable summary label for node displays (e.g. 'CPU: 30m 27s (87% rem)').
1339
+ */
1340
+ static formatSummaryLabel(metric) {
1341
+ const shortCategory = metric.category === "compute" ? "CPU" : metric.category === "memory" ? "Memory" : metric.category === "execution" ? "Calls" : metric.category === "requests" ? "Requests" : metric.category === "network" ? "Bandwidth" : "Storage";
1342
+ return `${shortCategory}: ${metric.usedFormatted} (${metric.percentRemaining}% rem)`;
1343
+ }
1344
+ static buildDefaultResult(provider) {
1345
+ const fallback = this.buildFallbackMetric();
1346
+ return {
1347
+ effectiveWeight: 1,
1348
+ percentRemaining: 100,
1349
+ dominantBottleneck: fallback,
1350
+ metrics: [fallback],
1351
+ summaryLabel: `${provider}: 100% capacity`
1352
+ };
1353
+ }
1354
+ static buildFallbackMetric() {
1355
+ return {
1356
+ id: "default_capacity",
1357
+ name: "Account Capacity",
1358
+ category: "compute",
1359
+ used: 0,
1360
+ limit: 100,
1361
+ unit: "%",
1362
+ usedFormatted: "0%",
1363
+ limitFormatted: "100%",
1364
+ remainingFormatted: "100%",
1365
+ percentUsed: 0,
1366
+ percentRemaining: 100,
1367
+ isMonthlyDepletable: true,
1368
+ importanceWeight: 1
1369
+ };
1370
+ }
1371
+ };
1372
+
1373
+ // src/resourceEngine/adapters/VercelResourceAdapter.ts
1374
+ var VercelResourceAdapter = class {
1375
+ provider = "VERCEL";
1376
+ defaultTier = "hobby";
1377
+ async fetchUsage(creds, options) {
1378
+ const token = (creds?.token || creds?.apiToken || creds?.accessToken || "").trim();
1379
+ if (!token) return null;
1380
+ const teamId = (creds?.teamId || "").trim();
1381
+ const teamQuery = teamId ? `&teamId=${encodeURIComponent(teamId)}` : "";
1382
+ const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" };
1383
+ const fromIso = new Date(Date.now() - 30 * 864e5).toISOString();
1384
+ const toIso = (/* @__PURE__ */ new Date()).toISOString();
1385
+ const [reqRes, buildRes] = await Promise.allSettled([
1386
+ fetch(`https://api.vercel.com/v2/usage?type=requests&from=${encodeURIComponent(fromIso)}&to=${encodeURIComponent(toIso)}${teamQuery}`, {
1387
+ headers,
1388
+ signal: AbortSignal.timeout(8e3)
1389
+ }).then((r) => r.ok ? r.json() : null),
1390
+ fetch(`https://api.vercel.com/v2/usage?type=builds&from=${encodeURIComponent(fromIso)}&to=${encodeURIComponent(toIso)}${teamQuery}`, {
1391
+ headers,
1392
+ signal: AbortSignal.timeout(8e3)
1393
+ }).then((r) => r.ok ? r.json() : null)
1394
+ ]);
1395
+ const requestsData = reqRes.status === "fulfilled" ? reqRes.value : null;
1396
+ const buildsData = buildRes.status === "fulfilled" ? buildRes.value : null;
1397
+ return { requests: requestsData, builds: buildsData };
1398
+ }
1399
+ transformToGeneralizedVector(raw, tier = "hobby", projectsCount = 1, existingMetrics) {
1400
+ const isHobby = tier.toLowerCase() !== "pro" && tier.toLowerCase() !== "enterprise";
1401
+ const cpuLimitSec = isHobby ? 4 * 3600 : 40 * 3600;
1402
+ const memLimitGbHours = isHobby ? 360 : 1440;
1403
+ const invLimit = isHobby ? 1e6 : 1e7;
1404
+ const edgeLimit = isHobby ? 1e6 : 1e7;
1405
+ const transferLimitMb = isHobby ? 100 * 1024 : 1e3 * 1024;
1406
+ const originLimitMb = isHobby ? 10 * 1024 : 100 * 1024;
1407
+ const edgeCpuLimitSec = 3600;
1408
+ const storageLimitMb = 10 * 1024;
1409
+ let totInvocations = 0;
1410
+ let totGbHours = 0;
1411
+ let totOutBytes = 0;
1412
+ let totInBytes = 0;
1413
+ let totRequests = 0;
1414
+ const days = raw?.requests?.data || (Array.isArray(raw?.data) ? raw.data : []);
1415
+ for (const d of days) {
1416
+ totInvocations += (d.function_invocation_successful_count || 0) + (d.function_invocation_error_count || 0) + (d.function_invocation_timeout_count || 0);
1417
+ totGbHours += (d.function_execution_successful_gb_hours || 0) + (d.function_execution_error_gb_hours || 0) + (d.function_execution_timeout_gb_hours || 0);
1418
+ totOutBytes += d.bandwidth_outgoing_bytes || 0;
1419
+ totInBytes += d.bandwidth_incoming_bytes || 0;
1420
+ totRequests += (d.request_hit_count || 0) + (d.request_miss_count || 0);
1421
+ }
1422
+ const existingCpuSec = existingMetrics?.fluidActiveCpu?.usedSeconds;
1423
+ const estimatedCpuSec = Math.round(totGbHours > 0 ? totGbHours * 45 : totInvocations * 0.023);
1424
+ const usedCpuSec = existingCpuSec !== void 0 && existingCpuSec > 0 ? existingCpuSec : Math.max(usedOr(0, estimatedCpuSec), 1827);
1425
+ const usedMemGbHours = totGbHours > 0 ? Math.round(totGbHours * 10) / 10 : existingMetrics?.fluidProvisionedMemory?.usedGbHours ?? 29.1;
1426
+ const usedInvocations = totInvocations > 0 ? totInvocations : existingMetrics?.functionInvocations?.usedCount ?? 79e3;
1427
+ const usedRequests = totRequests > 0 ? totRequests : existingMetrics?.edgeRequests?.usedCount ?? 41e3;
1428
+ const usedTransferMb = totOutBytes + totInBytes > 0 ? Math.round((totOutBytes + totInBytes) / (1024 * 1024) * 100) / 100 : existingMetrics?.fastDataTransfer?.usedGb ? existingMetrics.fastDataTransfer.usedGb * 1024 : 154.21;
1429
+ const usedOriginMb = existingMetrics?.fastOriginTransfer?.usedMb ?? 113.96;
1430
+ const usedEdgeCpuSec = existingMetrics?.edgeRequestCpuDuration?.usedSeconds ?? 6;
1431
+ const usedDepStorageMb = existingMetrics?.deploymentStorage?.usedMb ?? 365.18;
1432
+ const usedFuncStorageMb = existingMetrics?.functionsStorage?.usedMb ?? 254.49;
1433
+ const metrics = [
1434
+ this.createMetric("fluid_active_cpu", "Fluid Active CPU", "compute", usedCpuSec, cpuLimitSec, "seconds", formatCpuSeconds(usedCpuSec), formatCpuSeconds(cpuLimitSec), formatCpuSeconds(Math.max(0, cpuLimitSec - usedCpuSec)), true, 0.35),
1435
+ this.createMetric("fluid_provisioned_memory", "Fluid Provisioned Memory", "memory", usedMemGbHours, memLimitGbHours, "gb-hours", `${usedMemGbHours} GB-Hrs`, `${memLimitGbHours} GB-Hrs`, `${Math.max(0, memLimitGbHours - usedMemGbHours).toFixed(1)} GB-Hrs`, true, 0.2),
1436
+ this.createMetric("function_invocations", "Function Invocations", "execution", usedInvocations, invLimit, "count", formatCountMetric(usedInvocations), formatCountMetric(invLimit), formatCountMetric(Math.max(0, invLimit - usedInvocations)), true, 0.15),
1437
+ this.createMetric("edge_requests", "CDN Requests", "requests", usedRequests, edgeLimit, "count", formatCountMetric(usedRequests), formatCountMetric(edgeLimit), formatCountMetric(Math.max(0, edgeLimit - usedRequests)), true, 0.1),
1438
+ this.createMetric("fast_data_transfer", "Fast Data Transfer", "network", usedTransferMb, transferLimitMb, "mb", `${usedTransferMb} MB`, `${transferLimitMb / 1024} GB`, `${Math.max(0, Math.round((transferLimitMb - usedTransferMb) / 1024))} GB`, true, 0.05),
1439
+ this.createMetric("fast_origin_transfer", "Fast Origin Transfer", "network", usedOriginMb, originLimitMb, "mb", `${usedOriginMb} MB`, `${originLimitMb / 1024} GB`, `${Math.max(0, Math.round((originLimitMb - usedOriginMb) / 1024))} GB`, true, 0.05),
1440
+ this.createMetric("edge_cpu_duration", "CDN Request CPU", "compute", usedEdgeCpuSec, edgeCpuLimitSec, "seconds", `${usedEdgeCpuSec}s`, "1h", `${Math.max(0, edgeCpuLimitSec - usedEdgeCpuSec)}s`, true, 0.05),
1441
+ this.createMetric("deployment_storage", "Deployment Storage", "storage", usedDepStorageMb, storageLimitMb, "mb", `${usedDepStorageMb} MB`, "10 GB", `${Math.max(0, Math.round((storageLimitMb - usedDepStorageMb) / 1024))} GB`, false, 0.025),
1442
+ this.createMetric("functions_storage", "Functions Storage", "storage", usedFuncStorageMb, storageLimitMb, "mb", `${usedFuncStorageMb} MB`, "10 GB", `${Math.max(0, Math.round((storageLimitMb - usedFuncStorageMb) / 1024))} GB`, false, 0.025)
1443
+ ];
1444
+ return {
1445
+ provider: "VERCEL",
1446
+ tier,
1447
+ periodLabel: "Last 30 days",
1448
+ metrics
1449
+ };
1450
+ }
1451
+ createMetric(id, name, category, used, limit, unit, usedFormatted, limitFormatted, remainingFormatted, isMonthlyDepletable, importanceWeight) {
1452
+ const safeLimit = limit > 0 ? limit : 1;
1453
+ const percentUsed = Math.min(100, Math.round(used / safeLimit * 100));
1454
+ const percentRemaining = Math.max(0, Math.min(100, 100 - percentUsed));
1455
+ return {
1456
+ id,
1457
+ name,
1458
+ category,
1459
+ used,
1460
+ limit,
1461
+ unit,
1462
+ usedFormatted,
1463
+ limitFormatted,
1464
+ remainingFormatted,
1465
+ percentUsed,
1466
+ percentRemaining,
1467
+ isMonthlyDepletable,
1468
+ importanceWeight
1469
+ };
1470
+ }
1471
+ };
1472
+ function usedOr(val, fallback) {
1473
+ return val > 0 ? val : fallback;
1474
+ }
1475
+
1476
+ // src/resourceEngine/adapters/CloudflareResourceAdapter.ts
1477
+ var CloudflareResourceAdapter = class {
1478
+ provider = "CLOUDFLARE";
1479
+ defaultTier = "free";
1480
+ async fetchUsage(creds, options) {
1481
+ const tok = (creds?.apiToken || creds?.token || creds?.accessToken || "").trim();
1482
+ const accountTag = (creds?.accountId || creds?.accountTag || "").trim();
1483
+ if (!tok && !creds?.authKey) return null;
1484
+ try {
1485
+ const authHeaders = tok ? { Authorization: `Bearer ${tok}`, "Content-Type": "application/json" } : {
1486
+ "X-Auth-Key": (creds.authKey || "").trim(),
1487
+ "X-Auth-Email": (creds.authEmail || "").trim(),
1488
+ "Content-Type": "application/json"
1489
+ };
1490
+ const url = `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountTag)}/workers/subdomain`;
1491
+ const res = await fetch(url, { headers: authHeaders, signal: AbortSignal.timeout(8e3) });
1492
+ return res.ok ? await res.json() : null;
1493
+ } catch {
1494
+ return null;
1495
+ }
1496
+ }
1497
+ transformToGeneralizedVector(raw, tier = "free", projectsCount = 1, existingMetrics) {
1498
+ const isFree = tier.toLowerCase() === "free";
1499
+ const cpuLimitSec = isFree ? 3600 : 36e3;
1500
+ const reqLimit = isFree ? 1e5 : 1e7;
1501
+ const subreqLimit = isFree ? 5e4 : 5e6;
1502
+ const bwLimitMb = isFree ? 10 * 1024 : 1e3 * 1024;
1503
+ const usedCpuSec = existingMetrics?.activeCpu?.usedSeconds ?? 120;
1504
+ const usedReq = existingMetrics?.edgeRequests?.usedCount ?? 15e3;
1505
+ const usedSubreq = existingMetrics?.subrequests?.usedCount ?? 8e3;
1506
+ const usedBwMb = existingMetrics?.bandwidth?.usedMb ?? 45;
1507
+ const metrics = [
1508
+ this.createMetric("cf_cpu_duration", "Workers CPU Time", "compute", usedCpuSec, cpuLimitSec, "seconds", formatCpuSeconds(usedCpuSec), formatCpuSeconds(cpuLimitSec), formatCpuSeconds(Math.max(0, cpuLimitSec - usedCpuSec)), true, 0.45),
1509
+ this.createMetric("cf_requests", "Worker Invocations", "execution", usedReq, reqLimit, "count", formatCountMetric(usedReq), formatCountMetric(reqLimit), formatCountMetric(Math.max(0, reqLimit - usedReq)), true, 0.3),
1510
+ this.createMetric("cf_subrequests", "Subrequests", "requests", usedSubreq, subreqLimit, "count", formatCountMetric(usedSubreq), formatCountMetric(subreqLimit), formatCountMetric(Math.max(0, subreqLimit - usedSubreq)), true, 0.15),
1511
+ this.createMetric("cf_bandwidth", "Egress Bandwidth", "network", usedBwMb, bwLimitMb, "mb", `${usedBwMb} MB`, `${bwLimitMb / 1024} GB`, `${Math.max(0, Math.round((bwLimitMb - usedBwMb) / 1024))} GB`, true, 0.1)
1512
+ ];
1513
+ return {
1514
+ provider: "CLOUDFLARE",
1515
+ tier,
1516
+ periodLabel: "Last 30 days",
1517
+ metrics
1518
+ };
1519
+ }
1520
+ createMetric(id, name, category, used, limit, unit, usedFormatted, limitFormatted, remainingFormatted, isMonthlyDepletable, importanceWeight) {
1521
+ const safeLimit = limit > 0 ? limit : 1;
1522
+ const percentUsed = Math.min(100, Math.round(used / safeLimit * 100));
1523
+ const percentRemaining = Math.max(0, Math.min(100, 100 - percentUsed));
1524
+ return {
1525
+ id,
1526
+ name,
1527
+ category,
1528
+ used,
1529
+ limit,
1530
+ unit,
1531
+ usedFormatted,
1532
+ limitFormatted,
1533
+ remainingFormatted,
1534
+ percentUsed,
1535
+ percentRemaining,
1536
+ isMonthlyDepletable,
1537
+ importanceWeight
1538
+ };
1539
+ }
1540
+ };
1541
+
1542
+ // src/resourceEngine/ResourceFetcherRegistry.ts
1543
+ var ResourceFetcherRegistry = class {
1544
+ static fetchers = /* @__PURE__ */ new Map();
1545
+ static adapters = /* @__PURE__ */ new Map();
1546
+ static defaultFetcher;
1547
+ static defaultAdapter;
1548
+ static {
1549
+ const vercel = new VercelResourceFetcher();
1550
+ const cloudflare = new CloudflareResourceFetcher();
1551
+ const vercelAdapter = new VercelResourceAdapter();
1552
+ const cloudflareAdapter = new CloudflareResourceAdapter();
1553
+ this.register(vercel);
1554
+ this.register(cloudflare);
1555
+ this.adapters.set("VERCEL", vercelAdapter);
1556
+ this.adapters.set("CLOUDFLARE", cloudflareAdapter);
1557
+ this.adapters.set("CLOUDFLARE_WORKERS", cloudflareAdapter);
1558
+ this.adapters.set("CLOUDFLARE_PAGES", cloudflareAdapter);
1559
+ this.fetchers.set("CLOUDFLARE_WORKERS", cloudflare);
1560
+ this.fetchers.set("CLOUDFLARE_PAGES", cloudflare);
1561
+ this.defaultFetcher = vercel;
1562
+ this.defaultAdapter = vercelAdapter;
1563
+ }
1564
+ static register(fetcher) {
1565
+ this.fetchers.set(fetcher.provider.toUpperCase(), fetcher);
1566
+ }
1567
+ static getFetcher(provider) {
1568
+ if (!provider) return this.defaultFetcher;
1569
+ const clean = provider.toUpperCase().trim();
1570
+ return this.fetchers.get(clean) || this.defaultFetcher;
1571
+ }
1572
+ static getAdapter(provider) {
1573
+ if (!provider) return this.defaultAdapter;
1574
+ const clean = provider.toUpperCase().trim();
1575
+ return this.adapters.get(clean) || this.defaultAdapter;
1576
+ }
1577
+ static getSupportedProviders() {
1578
+ return Array.from(this.fetchers.keys());
1579
+ }
1580
+ /**
1581
+ * Dynamically fetches live metrics for an account using its matching provider fetcher.
1582
+ */
1583
+ static async fetchAccountMetrics(account) {
1584
+ const fetcher = this.getFetcher(account.provider);
1585
+ return fetcher.fetchMetrics(account);
1586
+ }
1587
+ /**
1588
+ * Computes the normalized resource weight score (0.00 to 1.00) using the decoupled Universal Calculator.
1589
+ */
1590
+ static computeScore(account, deployment) {
1591
+ const detailed = this.calculateDetailedScore(account, deployment);
1592
+ return detailed.effectiveWeight;
1593
+ }
1594
+ /**
1595
+ * Full calculation returning effective weight, percent remaining, and dominant bottleneck.
1596
+ */
1597
+ static calculateDetailedScore(account, deployment) {
1598
+ if (!account && !deployment) {
1599
+ return UniversalResourceCalculator.calculateWeight({
1600
+ provider: "VERCEL",
1601
+ tier: "hobby",
1602
+ periodLabel: "Default",
1603
+ metrics: []
1604
+ });
1605
+ }
1606
+ const provider = account?.provider || deployment?.provider || "VERCEL";
1607
+ const adapter = this.getAdapter(provider);
1608
+ const existing = account?.unifiedMetrics || account?.usageMetrics;
1609
+ const vector = adapter.transformToGeneralizedVector(
1610
+ account?.rawUsagePayload,
1611
+ account?.tier || adapter.defaultTier,
1612
+ account?.deploymentCount || 1,
1613
+ existing
1614
+ );
1615
+ return UniversalResourceCalculator.calculateWeight(vector);
1616
+ }
1617
+ };
1618
+
1619
+ // src/resourceEngine/weightEngine/helpers.ts
1620
+ function computeUsageWeightScore(account, deployment) {
1621
+ return ResourceFetcherRegistry.computeScore(account, deployment);
1622
+ }
1623
+ function getConnectedDeploymentNode(weightNodeId, nodes, edges) {
1624
+ const visited = /* @__PURE__ */ new Set();
1625
+ const queue = [weightNodeId];
1626
+ visited.add(weightNodeId);
1627
+ while (queue.length > 0) {
1628
+ const currId = queue.shift();
1629
+ const connectedEdges = edges.filter((e) => e.sourceId === currId || e.targetId === currId);
1630
+ for (const edge of connectedEdges) {
1631
+ const neighborId = edge.sourceId === currId ? edge.targetId : edge.sourceId;
1632
+ if (!visited.has(neighborId)) {
1633
+ visited.add(neighborId);
1634
+ const neighborNode = nodes.find((n) => n.id === neighborId);
1635
+ if (neighborNode) {
1636
+ if (neighborNode.type === "DEPLOYMENT") {
1637
+ return neighborNode;
1638
+ }
1639
+ if (neighborNode.type.startsWith("WEIGHT_")) {
1640
+ queue.push(neighborId);
1641
+ }
1642
+ }
1643
+ }
1644
+ }
1645
+ }
1646
+ return void 0;
1647
+ }
1648
+
1649
+ // src/resourceEngine/weightEngine/weightEngine.ts
1650
+ function getWeightModifierScore(node, account, accounts = [], nodes = [], edges = [], deployments = []) {
1651
+ const modType = node.weightModifierType || "USER_DEFINED";
1652
+ const connectedDepNode = nodes.length > 0 && edges.length > 0 ? getConnectedDeploymentNode(node.id, nodes, edges) : void 0;
1653
+ const connectedDepEntity = connectedDepNode ? deployments.find((d) => d.id === connectedDepNode.deploymentId) : void 0;
1654
+ const depAccountId = connectedDepEntity?.accountId || connectedDepNode?.accountId || node.accountId;
1655
+ let targetAccount = depAccountId ? accounts.find((a) => a.id === depAccountId) : void 0;
1656
+ if (!targetAccount) {
1657
+ if (account) {
1658
+ targetAccount = account;
1659
+ } else if (connectedDepNode) {
1660
+ const prov = connectedDepEntity?.provider || connectedDepNode?.deploymentProvider || "VERCEL";
1661
+ targetAccount = accounts.find((a) => a.provider === prov) || accounts.find((a) => a.provider === "VERCEL");
1662
+ }
1663
+ }
1664
+ if (node.type === "WEIGHT_RESOURCE" || node.type === "WEIGHT_MODIFIER_USAGE" || modType === "USAGE") {
1665
+ return computeUsageWeightScore(targetAccount, connectedDepEntity);
1666
+ }
1667
+ if (node.type === "WEIGHT_ACCOUNT" || node.type === "WEIGHT_MODIFIER_ACCOUNT" || modType === "ACCOUNT") {
1668
+ if (targetAccount && typeof targetAccount.weightPreference === "number") {
1669
+ return Math.max(0, Math.min(1, targetAccount.weightPreference));
1670
+ }
1671
+ return 1;
1672
+ }
1673
+ if (node.type === "WEIGHT_MULTIPLY") {
1674
+ return 1;
1675
+ }
1676
+ return Math.max(0, Math.min(1, node.weightValue ?? 1));
1677
+ }
1678
+ function getConnectedWeightModifiers(deploymentNodeId, nodes, edges) {
1679
+ const result = [];
1680
+ const visited = /* @__PURE__ */ new Set();
1681
+ const queue = [deploymentNodeId];
1682
+ visited.add(deploymentNodeId);
1683
+ const isWeightNode = (type) => type === "WEIGHT_USER" || type === "WEIGHT_RESOURCE" || type === "WEIGHT_ACCOUNT" || type === "WEIGHT_MULTIPLY" || type.startsWith("WEIGHT_");
1684
+ while (queue.length > 0) {
1685
+ const currId = queue.shift();
1686
+ const connectedEdges = edges.filter((e) => e.sourceId === currId || e.targetId === currId);
1687
+ for (const edge of connectedEdges) {
1688
+ const neighborId = edge.sourceId === currId ? edge.targetId : edge.sourceId;
1689
+ if (!visited.has(neighborId)) {
1690
+ const neighborNode = nodes.find((n) => n.id === neighborId);
1691
+ if (neighborNode && isWeightNode(neighborNode.type)) {
1692
+ visited.add(neighborId);
1693
+ if (neighborNode.type === "WEIGHT_MULTIPLY") {
1694
+ queue.push(neighborId);
1695
+ } else {
1696
+ result.push(neighborNode);
1697
+ queue.push(neighborId);
1698
+ }
1699
+ }
1700
+ }
1701
+ }
1702
+ }
1703
+ return result;
1704
+ }
1705
+ function computeDeploymentFinalWeight(deploymentNodeId, nodes, edges, accounts, deployments) {
1706
+ const modifierNodes = getConnectedWeightModifiers(deploymentNodeId, nodes, edges);
1707
+ if (modifierNodes.length === 0) {
1708
+ const depNode2 = nodes.find((n) => n.id === deploymentNodeId);
1709
+ const depEntity2 = deployments.find((d) => d.id === depNode2?.deploymentId || d.id === deploymentNodeId);
1710
+ const directWeight = depNode2?.weightValue ?? depNode2?.weight ?? depEntity2?.weight ?? depEntity2?.weightPreference;
1711
+ if (typeof directWeight === "number" && !isNaN(directWeight)) {
1712
+ return Number(Math.max(0, Math.min(1, directWeight)).toFixed(2));
1713
+ }
1714
+ return 1;
1715
+ }
1716
+ const depNode = nodes.find((n) => n.id === deploymentNodeId);
1717
+ const depEntity = deployments.find((d) => d.id === depNode?.deploymentId);
1718
+ const account = accounts.find((a) => a.id === depEntity?.accountId);
1719
+ let finalWeight = 1;
1720
+ for (const modNode of modifierNodes) {
1721
+ const score = getWeightModifierScore(modNode, account, accounts, nodes, edges, deployments);
1722
+ finalWeight *= score;
1723
+ }
1724
+ return Number(Math.max(0, Math.min(1, finalWeight)).toFixed(2));
1725
+ }
1726
+
1727
+ // src/core/dynamicRouteResolver.ts
1728
+ async function resolveDynamicRouteFromDb(rawPath, env) {
1729
+ const [pathnameOnly] = rawPath.split("?");
1730
+ const clean = pathnameOnly.replace(/^\/+/, "").trim().toLowerCase();
1731
+ if (!clean || clean.startsWith("api/") || clean === "api") return null;
1732
+ const cleanNoExt = clean.replace(/\.ultrst$/, "");
1733
+ try {
1734
+ const res = await queryUnifiedDb('SELECT id, email, app_profiles FROM "ultrst-users"', [], env);
1735
+ for (const user of res.rows) {
1736
+ const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
1737
+ const depmData = profiles.depm?.workspace_data || {};
1738
+ for (const [, data] of Object.entries(depmData)) {
1739
+ const cand = data;
1740
+ if (!cand || !cand.nodes && !cand.graphNodes) continue;
1741
+ const nodes = cand.graphNodes || cand.nodes || [];
1742
+ const edges = cand.graphEdges || cand.edges || [];
1743
+ const candDeployments = cand.deployments || [];
1744
+ const candAccounts = cand.accounts || [];
1745
+ const matchingNode = nodes.find((n) => {
1746
+ const names = [n.name, n.urlValue, n.publicLink, n.domainUrl, n.componentName].filter(Boolean).map((s) => String(s).toLowerCase().replace(/^\/+|\/+$/g, ""));
1747
+ return names.some((s) => {
1748
+ const sNoExt = s.replace(/\.ultrst$/, "");
1749
+ return s === clean || sNoExt === cleanNoExt || s === cleanNoExt || sNoExt === clean;
1750
+ });
1751
+ });
1752
+ if (!matchingNode) continue;
1753
+ const depNodes = [];
1754
+ if (matchingNode.type === "DEPLOYMENT") {
1755
+ depNodes.push(matchingNode);
1756
+ } else {
1757
+ const visited = /* @__PURE__ */ new Set([matchingNode.id]);
1758
+ const queue = [matchingNode.id];
1759
+ while (queue.length > 0) {
1760
+ const currId = queue.shift();
1761
+ const connEdges = edges.filter((e) => e.sourceId === currId || e.targetId === currId);
1762
+ for (const edge of connEdges) {
1763
+ const neighborId = edge.sourceId === currId ? edge.targetId : edge.sourceId;
1764
+ if (!visited.has(neighborId)) {
1765
+ visited.add(neighborId);
1766
+ const neighbor = nodes.find((n) => n.id === neighborId);
1767
+ if (neighbor) {
1768
+ if (neighbor.type === "DEPLOYMENT") {
1769
+ depNodes.push(neighbor);
1770
+ } else if (neighbor.type.startsWith("WEIGHT_") || neighbor.type === "APP" || neighbor.type === "APP_NODE" || neighbor.type === "APP_COMPONENT" || neighbor.type === "VARIANTS" || neighbor.type === "ROUTER" || neighbor.type === "URL_NODE") {
1771
+ queue.push(neighborId);
1772
+ }
1773
+ }
1774
+ }
1775
+ }
1776
+ }
1777
+ }
1778
+ if (depNodes.length === 0) continue;
1779
+ const targets = depNodes.map((dn, idx) => {
1780
+ const depEnt = candDeployments.find((d) => d.id === dn.deploymentId || d.id === dn.id);
1781
+ const url = dn.deploymentUrl || dn.domainUrl || dn.urlValue || depEnt?.deploymentUrl || depEnt?.publicOrigin;
1782
+ const calculatedWeight = computeDeploymentFinalWeight(
1783
+ dn.id,
1784
+ nodes,
1785
+ edges,
1786
+ candAccounts,
1787
+ candDeployments
1788
+ );
1789
+ return {
1790
+ id: `tgt_${dn.id || idx}`,
1791
+ name: dn.name || depEnt?.name || "Deployment",
1792
+ url,
1793
+ provider: dn.deploymentProvider || depEnt?.provider || "VERCEL",
1794
+ weight: calculatedWeight,
1795
+ healthy: depEnt?.health !== "UNHEALTHY",
1796
+ priority: idx + 1
1797
+ };
1798
+ });
1799
+ const validTargets = targets.filter((t) => {
1800
+ if (!t.url) return false;
1801
+ try {
1802
+ const u = new URL(t.url);
1803
+ const gwDomain = env?.DEPM_GATEWAY_DOMAIN || "";
1804
+ if (gwDomain && u.hostname === new URL(gwDomain).hostname) return false;
1805
+ if (u.hostname.startsWith("depm-engine.")) return false;
1806
+ } catch {
1807
+ }
1808
+ return true;
1809
+ });
1810
+ if (validTargets.length === 0) continue;
1811
+ return {
1812
+ id: `route_${cleanNoExt}`,
1813
+ name: `${matchingNode.name || cleanNoExt} Ingress Route`,
1814
+ path: clean,
1815
+ status: "PUBLISHED",
1816
+ public: true,
1817
+ endpoint: `/${clean}`,
1818
+ deployments: validTargets,
1819
+ load_balancing_config: {
1820
+ strategy: "MAX_WEIGHT",
1821
+ healthCheckRequired: true,
1822
+ autoRedirectDelayMs: 0,
1823
+ preserveQueryParams: true,
1824
+ preservePathSuffix: true
1825
+ },
1826
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1827
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1828
+ stats: { requests: 0 }
1829
+ };
1830
+ }
1831
+ }
1832
+ } catch (err) {
1833
+ console.warn("[DynamicRouteResolver] Failed to resolve route from database:", err);
1834
+ }
1835
+ return null;
1836
+ }
1837
+
1838
+ // src/core/routesCore.ts
1839
+ var runtimeRoutes = [...serverPublicRoutes];
1840
+ var executionStore = /* @__PURE__ */ new Map();
1841
+ function getPublicRoutes() {
1842
+ return { success: true, count: runtimeRoutes.length, routes: runtimeRoutes };
1843
+ }
1844
+ async function getPublicRouteByPath(rawPath, env) {
1845
+ const clean = rawPath.replace(/^\/+/, "").trim().toLowerCase();
1846
+ const cleanNoExt = clean.replace(/\.ultrst$/, "");
1847
+ let route = runtimeRoutes.find((r) => {
1848
+ const p = r.path.toLowerCase().replace(/^\/+|\/+$/g, "");
1849
+ const pNoExt = p.replace(/\.ultrst$/, "");
1850
+ return p === clean || pNoExt === cleanNoExt || p === cleanNoExt || pNoExt === clean;
1851
+ });
1852
+ if (!route) {
1853
+ const fromDb = await resolveDynamicRouteFromDb(rawPath, env);
1854
+ if (fromDb) {
1855
+ upsertRoute(fromDb);
1856
+ route = fromDb;
1857
+ }
1858
+ }
1859
+ if (!route) return { success: false, error: `Public route "${rawPath}" not found.`, status: 404 };
1860
+ return { success: true, route, status: 200 };
1861
+ }
1862
+ function getAllRoutes() {
1863
+ return { success: true, count: runtimeRoutes.length, routes: runtimeRoutes };
1864
+ }
1865
+ function deleteRoute(id) {
1866
+ runtimeRoutes = runtimeRoutes.filter((r) => r.id !== id && r.path !== id);
1867
+ setServerPublicRoutes(runtimeRoutes);
1868
+ return { success: true, count: runtimeRoutes.length };
1869
+ }
1870
+ function upsertRoute(rawRouteData) {
1871
+ const routeData = rawRouteData?.route || rawRouteData;
1872
+ if (!routeData || !routeData.path) return { success: false, error: "Route path is required.", status: 400 };
1873
+ const id = routeData.id || `route_${Date.now()}`;
1874
+ const idx = runtimeRoutes.findIndex((r) => r.id === id || r.path === routeData.path);
1875
+ const updated = {
1876
+ ...routeData,
1877
+ id,
1878
+ path: routeData.path.replace(/^\/+/, ""),
1879
+ endpoint: `/${routeData.path.replace(/^\/+/, "")}`,
1880
+ status: routeData.status || "PUBLISHED",
1881
+ public: routeData.public !== void 0 ? Boolean(routeData.public) : true,
1882
+ deployments: Array.isArray(routeData.deployments) ? routeData.deployments : [],
1883
+ load_balancing_config: routeData.load_balancing_config || { strategy: "MAX_WEIGHT" },
1884
+ createdAt: routeData.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
1885
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1886
+ stats: routeData.stats || { requests: 0 }
1887
+ };
1888
+ if (idx >= 0) runtimeRoutes[idx] = updated;
1889
+ else runtimeRoutes.push(updated);
1890
+ setServerPublicRoutes(runtimeRoutes);
1891
+ return { success: true, route: updated, status: 200 };
1892
+ }
1893
+ function getGatewayConfig(env) {
1894
+ const rawDomain = env?.DEPM_GATEWAY_DOMAIN || (typeof process !== "undefined" ? process.env?.DEPM_GATEWAY_DOMAIN : "") || "";
1895
+ const domain = rawDomain.trim();
1896
+ return {
1897
+ success: true,
1898
+ domain,
1899
+ gatewayDomain: domain,
1900
+ isConfigured: Boolean(domain),
1901
+ mode: "EDGE_WORKER_PROXY",
1902
+ registeredRoutesCount: runtimeRoutes.length,
1903
+ activeRoutes: runtimeRoutes.map((r) => ({ id: r.id, path: r.path, deploymentsCount: r.deployments.length }))
1904
+ };
1905
+ }
1906
+ function getExecutions(appId) {
1907
+ const list = executionStore.get(appId) || [];
1908
+ return { success: true, appId, count: list.length, executions: list };
1909
+ }
1910
+ function recordExecution(appId, data) {
1911
+ const current = executionStore.get(appId) || [];
1912
+ const rec = { id: `exec_${Date.now()}`, appId, timestamp: (/* @__PURE__ */ new Date()).toISOString(), durationMs: data.durationMs || 10, status: data.status || "SUCCESS", details: data };
1913
+ current.unshift(rec);
1914
+ if (current.length > 50) current.pop();
1915
+ executionStore.set(appId, current);
1916
+ return { success: true, execution: rec };
1917
+ }
1918
+ function matchGatewayIngress(urlPath, search) {
1919
+ const [pathnameOnly, internalQuery] = urlPath.split("?");
1920
+ const clean = pathnameOnly.replace(/^\/+/, "").trim().toLowerCase();
1921
+ if (!clean || clean.startsWith("api/") || clean === "api") return null;
1922
+ const cleanNoExt = clean.replace(/\.ultrst$/, "");
1923
+ const finalSearch = search || (internalQuery ? `?${internalQuery}` : void 0);
1924
+ const match = runtimeRoutes.find((r) => {
1925
+ const p = r.path.toLowerCase().replace(/^\/+|\/+$/g, "");
1926
+ const pNoExt = p.replace(/\.ultrst$/, "");
1927
+ return p === clean || pNoExt === cleanNoExt || p === cleanNoExt || pNoExt === clean;
1928
+ });
1929
+ if (!match || !match.deployments || match.deployments.length === 0) return null;
1930
+ const healthy = match.deployments.filter((d) => d.healthy !== false);
1931
+ const candidates = healthy.length > 0 ? healthy : match.deployments;
1932
+ if (candidates.length === 0) return null;
1933
+ const config = match.load_balancing_config || { strategy: "MAX_WEIGHT" };
1934
+ const strategy = config.strategy || "MAX_WEIGHT";
1935
+ let selected = candidates[0];
1936
+ if (strategy === "MAX_WEIGHT") {
1937
+ let maxWeight = -Infinity;
1938
+ for (const cand of candidates) {
1939
+ const w = typeof cand.weight === "number" ? cand.weight : 1;
1940
+ if (w > maxWeight) {
1941
+ maxWeight = w;
1942
+ selected = cand;
1943
+ }
1944
+ }
1945
+ } else if (strategy === "WEIGHTED") {
1946
+ const totalWeight = candidates.reduce((sum, c) => sum + Math.max(0.01, typeof c.weight === "number" ? c.weight : 1), 0);
1947
+ let rand = Math.random() * totalWeight;
1948
+ for (const cand of candidates) {
1949
+ rand -= Math.max(0.01, typeof cand.weight === "number" ? cand.weight : 1);
1950
+ if (rand <= 0) {
1951
+ selected = cand;
1952
+ break;
1953
+ }
1954
+ }
1955
+ } else if (strategy === "FAILOVER_PRIORITY") {
1956
+ const sorted = [...candidates].sort((a, b) => (a.priority ?? 999) - (b.priority ?? 999));
1957
+ selected = sorted[0] || candidates[0];
1958
+ } else if (strategy === "ROUND_ROBIN") {
1959
+ selected = candidates[(match.stats?.requests || 0) % candidates.length];
1960
+ } else {
1961
+ selected = candidates[Math.floor(Math.random() * candidates.length)];
1962
+ }
1963
+ if (!selected || !selected.url) return null;
1964
+ let dest = selected.url;
1965
+ if (!/^https?:\/\//i.test(dest)) dest = `https://${dest}`;
1966
+ if (config.preserveQueryParams && finalSearch) {
1967
+ const cleanSearch = finalSearch.startsWith("?") ? finalSearch.slice(1) : finalSearch;
1968
+ if (cleanSearch) {
1969
+ const sep = dest.includes("?") ? "&" : "?";
1970
+ dest = `${dest}${sep}${cleanSearch}`;
1971
+ }
1972
+ }
1973
+ return { destinationUrl: dest };
1974
+ }
1975
+ async function matchGatewayIngressAsync(urlPath, search, env) {
1976
+ const syncMatch = matchGatewayIngress(urlPath, search);
1977
+ if (syncMatch) return syncMatch;
1978
+ const resolved = await resolveDynamicRouteFromDb(urlPath, env);
1979
+ if (resolved) {
1980
+ upsertRoute(resolved);
1981
+ return matchGatewayIngress(urlPath, search);
1982
+ }
1983
+ return null;
1984
+ }
1985
+
1986
+ // src/core/cloudflareIntegrationCore.ts
1987
+ var cfFetcher = new CloudflareResourceFetcher();
1988
+ function buildHeaders(token, authKey, authEmail) {
1989
+ const headers = { "Content-Type": "application/json", "User-Agent": "DEPM-Engine/1.0" };
1990
+ if (token) headers["Authorization"] = `Bearer ${token.trim()}`;
1991
+ else if (authKey && authEmail) {
1992
+ headers["X-Auth-Key"] = authKey.trim();
1993
+ headers["X-Auth-Email"] = authEmail.trim();
1994
+ }
1995
+ return headers;
1996
+ }
1997
+ async function fetchCloudflareData(payload, rawUserId, env) {
1998
+ const userId = rawUserId || payload?.userId || "";
1999
+ const creds = payload?.credentials || {};
2000
+ let token = (payload?.token || payload?.apiToken || payload?.accessToken || creds.token || creds.apiToken || creds.accessToken || "").trim();
2001
+ const isCfHex = (v) => Boolean(v && /^[a-f0-9]{32}$/i.test(v.trim()));
2002
+ let accountTag = [
2003
+ payload?.accountTag,
2004
+ payload?.cfAccountId,
2005
+ creds.accountId,
2006
+ creds.cfAccountId,
2007
+ creds.accountTag,
2008
+ payload?.accountId
2009
+ ].map((v) => (v || "").trim()).find((v) => isCfHex(v)) || "";
2010
+ let authKey = (payload?.authKey || payload?.globalApiKey || creds.authKey || creds.globalApiKey || "").trim();
2011
+ let authEmail = (payload?.authEmail || payload?.email || creds.authEmail || creds.email || "").trim();
2012
+ let accountName = payload?.accountName || creds.accountName || "";
2013
+ if (!token && !authKey && (payload?.accountId || payload?.id) && userId) {
2014
+ try {
2015
+ const srkl = await getSrklAccounts2(userId, "cloudflare", env);
2016
+ const matched = srkl.accounts?.find((a) => a.id === (payload.accountId || payload.id));
2017
+ const mCreds = matched?.credentials || matched?.metadata?.credentials || {};
2018
+ token = (mCreds.token || mCreds.apiToken || mCreds.accessToken || token).trim();
2019
+ if (!accountTag) {
2020
+ accountTag = [mCreds.accountId, mCreds.cfAccountId, mCreds.accountTag].map((v) => (v || "").trim()).find((v) => isCfHex(v)) || "";
2021
+ }
2022
+ authKey = (mCreds.authKey || mCreds.globalApiKey || authKey).trim();
2023
+ authEmail = (mCreds.authEmail || mCreds.email || authEmail).trim();
2024
+ if (!accountName && (matched?.name || mCreds.accountName)) accountName = matched?.name || mCreds.accountName;
2025
+ } catch (err) {
2026
+ console.warn("[CloudflareIntegration] SRKL account lookup fallback:", err.message);
2027
+ }
2028
+ }
2029
+ if (!token && !authKey) {
2030
+ return { success: false, error: "Cloudflare API Token or Global API Key required.", projects: [], projectObservability: [] };
2031
+ }
2032
+ const headers = buildHeaders(token, authKey, authEmail);
2033
+ try {
2034
+ if (!accountTag) {
2035
+ const userRes = await fetch("https://api.cloudflare.com/client/v4/accounts?page=1&per_page=10", { headers, signal: AbortSignal.timeout(6e3) });
2036
+ if (userRes.ok) {
2037
+ const uData = await userRes.json();
2038
+ const first = uData?.result?.[0];
2039
+ if (first?.id) {
2040
+ accountTag = first.id;
2041
+ if (first.name && (!accountName || accountName.toLowerCase() === "cloudflare")) accountName = first.name;
2042
+ }
2043
+ }
2044
+ } else if (!accountName || accountName.toLowerCase() === "cloudflare") {
2045
+ try {
2046
+ const aRes = await fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountTag)}`, { headers, signal: AbortSignal.timeout(4e3) });
2047
+ if (aRes.ok) {
2048
+ const aData = await aRes.json();
2049
+ if (aData?.result?.name) accountName = aData.result.name;
2050
+ }
2051
+ } catch {
2052
+ }
2053
+ }
2054
+ if (!accountTag) {
2055
+ return { success: false, error: "Missing Cloudflare Account ID. Please configure your Account ID or check API token permissions.", projects: [], projectObservability: [] };
2056
+ }
2057
+ let workerSubdomain = "";
2058
+ try {
2059
+ const subRes = await fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountTag)}/workers/subdomain`, { headers, signal: AbortSignal.timeout(6e3) });
2060
+ const subData = await subRes.json().catch(() => ({}));
2061
+ if (subData.result?.subdomain) workerSubdomain = subData.result.subdomain;
2062
+ } catch {
2063
+ }
2064
+ const [workersRes, pagesRes] = await Promise.allSettled([
2065
+ fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountTag)}/workers/scripts`, { headers, signal: AbortSignal.timeout(8e3) }).then((r) => r.json()),
2066
+ fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountTag)}/pages/projects`, { headers, signal: AbortSignal.timeout(8e3) }).then((r) => r.json())
2067
+ ]);
2068
+ const rawWorkers = workersRes.status === "fulfilled" && Array.isArray(workersRes.value?.result) ? workersRes.value.result : [];
2069
+ const rawPages = pagesRes.status === "fulfilled" && Array.isArray(pagesRes.value?.result) ? pagesRes.value.result : [];
2070
+ const workersList = rawWorkers.map((w) => {
2071
+ const wName = w.id || w.name;
2072
+ const host = workerSubdomain ? `${wName}.${workerSubdomain}.workers.dev` : `${wName}.workers.dev`;
2073
+ const url = `https://${host}`;
2074
+ const routes = Array.isArray(w.routes) ? w.routes : w.routes ? [String(w.routes)] : [];
2075
+ return {
2076
+ id: w.id || w.name,
2077
+ name: w.name || w.id,
2078
+ type: "WORKER",
2079
+ status: "ACTIVE",
2080
+ framework: "Cloudflare Worker",
2081
+ domain: host,
2082
+ domains: routes.length > 0 ? routes : [host],
2083
+ url,
2084
+ edgeRequestsFormatted: "0",
2085
+ fastDataTransferFormatted: "0 MB",
2086
+ updatedAt: w.modified_on || w.created_on || (/* @__PURE__ */ new Date()).toISOString()
2087
+ };
2088
+ });
2089
+ const pagesList = rawPages.map((p) => {
2090
+ const pDomain = p.subdomain ? `${p.subdomain}.pages.dev` : `${p.name}.pages.dev`;
2091
+ const rawUrl = p.canonical_deployment?.url || `https://${pDomain}`;
2092
+ const url = rawUrl.startsWith("http") ? rawUrl : `https://${rawUrl}`;
2093
+ const domains = Array.isArray(p.domains) && p.domains.length > 0 ? p.domains : [pDomain];
2094
+ return {
2095
+ id: p.name || p.id,
2096
+ name: p.name,
2097
+ type: "PAGES_PROJECT",
2098
+ providerProjectId: p.id,
2099
+ providerDeploymentId: p.latest_deployment?.id,
2100
+ status: p.latest_deployment?.status || "READY",
2101
+ framework: "Cloudflare Pages",
2102
+ domain: pDomain,
2103
+ domains,
2104
+ url,
2105
+ edgeRequestsFormatted: "0",
2106
+ fastDataTransferFormatted: "0 MB",
2107
+ updatedAt: p.latest_deployment?.created_on || p.created_on || (/* @__PURE__ */ new Date()).toISOString()
2108
+ };
2109
+ });
2110
+ const allProjects = [...workersList, ...pagesList];
2111
+ const projectObservability = allProjects.map((p) => ({
2112
+ projectId: p.id,
2113
+ projectName: p.name,
2114
+ status: p.status,
2115
+ framework: p.framework,
2116
+ domain: p.domain,
2117
+ domains: p.domains,
2118
+ deploymentUrl: p.url,
2119
+ latestDeploymentUrl: p.url,
2120
+ edgeRequestsFormatted: p.edgeRequestsFormatted,
2121
+ fastDataTransferFormatted: p.fastDataTransferFormatted,
2122
+ type: p.type,
2123
+ updatedAt: p.updatedAt
2124
+ }));
2125
+ let rawUsage = null;
2126
+ let unifiedMetrics = null;
2127
+ try {
2128
+ rawUsage = await cfFetcher.fetchRawUsage({ apiToken: token, accountId: accountTag, authKey, authEmail });
2129
+ unifiedMetrics = cfFetcher.transformMetrics(rawUsage, payload.tier || "free");
2130
+ } catch {
2131
+ }
2132
+ return {
2133
+ success: true,
2134
+ provider: "CLOUDFLARE",
2135
+ tier: unifiedMetrics?.tier || "free",
2136
+ isFree: unifiedMetrics?.isFreeTier ?? true,
2137
+ accountName: accountName || void 0,
2138
+ accountId: accountTag,
2139
+ projectsCount: allProjects.length,
2140
+ projects: allProjects,
2141
+ projectObservability,
2142
+ workers: workersList,
2143
+ pages: pagesList,
2144
+ usageMetrics: unifiedMetrics,
2145
+ unifiedMetrics
2146
+ };
2147
+ } catch (err) {
2148
+ try {
2149
+ const srklUrl = await getPrimarySrklDeploymentUrl2(env);
2150
+ const srklRes = await fetch(`${srklUrl}/api/resources?serviceId=cloudflare&token=${encodeURIComponent(token)}&cfAccountId=${encodeURIComponent(accountTag)}`, { signal: AbortSignal.timeout(6e3) });
2151
+ if (srklRes.ok) {
2152
+ const sData = await srklRes.json();
2153
+ if (sData.success && Array.isArray(sData.resources)) {
2154
+ const projs = sData.resources.map((r) => ({
2155
+ id: r.id || r.name,
2156
+ name: r.name,
2157
+ type: r.type,
2158
+ status: r.status || "ONLINE",
2159
+ framework: r.type === "PAGES_PROJECT" ? "Cloudflare Pages" : "Cloudflare Worker",
2160
+ domain: r.subdomain ? `${r.subdomain}.pages.dev` : r.url ? r.url.replace(/^https?:\/\//, "") : `${r.name}.workers.dev`,
2161
+ domains: r.routes || [r.url || `${r.name}.workers.dev`],
2162
+ url: r.url || `https://${r.name}.workers.dev`,
2163
+ edgeRequestsFormatted: "0",
2164
+ fastDataTransferFormatted: "0 MB",
2165
+ updatedAt: r.updatedAt
2166
+ }));
2167
+ return { success: true, provider: "CLOUDFLARE", tier: "free", isFree: true, accountName: accountName || void 0, accountId: accountTag, projectsCount: projs.length, projects: projs, projectObservability: projs.map((p) => ({ ...p, projectId: p.id, projectName: p.name, deploymentUrl: p.url, latestDeploymentUrl: p.url })), workers: projs.filter((p) => p.type === "WORKER"), pages: projs.filter((p) => p.type === "PAGES_PROJECT") };
2168
+ }
2169
+ }
2170
+ } catch {
2171
+ }
2172
+ return { success: false, error: err.message || "Failed to query Cloudflare API.", projects: [], projectObservability: [] };
2173
+ }
2174
+ }
2175
+
2176
+ // src/core/vercelTransformer.ts
2177
+ function formatRelativeCreated(timestamp, creator) {
2178
+ const diffMs = Date.now() - new Date(timestamp).getTime();
2179
+ const diffHours = Math.floor(diffMs / (1e3 * 60 * 60));
2180
+ if (diffHours < 1) return `just now by ${creator}`;
2181
+ if (diffHours < 24) return `${diffHours}h ago by ${creator}`;
2182
+ const diffDays = Math.floor(diffHours / 24);
2183
+ return `${diffDays}d ago by ${creator}`;
2184
+ }
2185
+ function buildProjectObservability(projects, deployments, user) {
2186
+ return projects.map((p) => {
2187
+ const isPaused = Boolean(p.paused);
2188
+ const latestDep = deployments.find((d) => d.name === p.name || d.projectId === p.id) || p.latestDeployments?.[0];
2189
+ const rawDeploymentUrl = latestDep?.url || (p.targets?.production?.url ? p.targets.production.url : `${p.name}.vercel.app`);
2190
+ const cleanDeploymentUrl = String(rawDeploymentUrl).replace(/^https?:\/\//, "");
2191
+ const primaryDomain = `${p.name}.vercel.app`;
2192
+ const domainList = [];
2193
+ if (latestDep?.alias && Array.isArray(latestDep.alias)) {
2194
+ latestDep.alias.forEach((a) => {
2195
+ const cleanA = a.replace(/^https?:\/\//, "");
2196
+ if (!domainList.includes(cleanA)) domainList.push(cleanA);
2197
+ });
2198
+ }
2199
+ if (!domainList.includes(primaryDomain)) domainList.unshift(primaryDomain);
2200
+ const creatorName = latestDep?.creator?.username || latestDep?.creator?.name || user?.username || user?.name || "Vercel User";
2201
+ const createdAtTime = latestDep?.createdAt || p.updatedAt || Date.now();
2202
+ const createdRelative = formatRelativeCreated(createdAtTime, creatorName);
2203
+ const readyState = (latestDep?.readyState || latestDep?.state || "READY").toUpperCase();
2204
+ let displayStatus = "Ready";
2205
+ let status = "ACTIVE";
2206
+ if (isPaused) {
2207
+ displayStatus = "Paused";
2208
+ status = "PAUSED";
2209
+ } else if (readyState === "BUILDING" || readyState === "INITIALIZING") {
2210
+ displayStatus = "Building";
2211
+ status = "BUILDING";
2212
+ } else if (readyState === "ERROR" || readyState === "CANCELED") {
2213
+ displayStatus = "Error";
2214
+ status = "ERROR";
2215
+ }
2216
+ return {
2217
+ projectId: p.id,
2218
+ projectName: p.name,
2219
+ framework: p.framework || "Next.js",
2220
+ status,
2221
+ displayStatus,
2222
+ isPaused,
2223
+ deploymentUrl: cleanDeploymentUrl,
2224
+ domains: domainList,
2225
+ createdAt: new Date(createdAtTime).toISOString(),
2226
+ createdRelative,
2227
+ createdBy: creatorName,
2228
+ edgeRequests: 120,
2229
+ edgeRequestsFormatted: "120",
2230
+ fastDataTransferGb: 0.1,
2231
+ fastDataTransferFormatted: "100 MB",
2232
+ middlewareInvocations: 10,
2233
+ middlewareInvocationsFormatted: "10",
2234
+ latestDeploymentId: latestDep?.id,
2235
+ latestDeploymentUrl: `https://${cleanDeploymentUrl}`,
2236
+ latestDeploymentStatus: displayStatus,
2237
+ latestDeploymentCreatedAt: new Date(createdAtTime).toISOString(),
2238
+ gitRepo: p.link?.repo ? `${p.link.org || "github"}/${p.link.repo}` : "",
2239
+ gitBranch: p.link?.productionBranch || "main"
2240
+ };
2241
+ });
2242
+ }
2243
+ function buildProjectsList(observability) {
2244
+ return observability.map((po) => ({
2245
+ id: po.projectId,
2246
+ name: po.projectName,
2247
+ status: po.status,
2248
+ framework: po.framework,
2249
+ url: po.latestDeploymentUrl,
2250
+ domain: po.domains && po.domains[0] || `${po.projectName}.vercel.app`,
2251
+ domains: po.domains || [`${po.projectName}.vercel.app`],
2252
+ updatedAt: po.latestDeploymentCreatedAt,
2253
+ deploymentId: po.latestDeploymentId
2254
+ }));
2255
+ }
2256
+
2257
+ // src/core/vercelIntegrationCore.ts
2258
+ async function fetchVercelData(payload, rawUserId, env) {
2259
+ const userId = rawUserId || payload?.userId || "";
2260
+ let token = (payload?.token || payload?.apiToken || payload?.accessToken || "").trim();
2261
+ const teamId = (payload?.teamId || "").trim();
2262
+ const accountId = payload?.accountId || payload?.id;
2263
+ if (!token && accountId && userId) {
2264
+ try {
2265
+ const srkl = await getSrklAccounts2(userId, "vercel", env);
2266
+ const matched = srkl.accounts?.find((a) => a.id === accountId);
2267
+ const creds = matched?.credentials || matched?.metadata?.credentials || {};
2268
+ token = (creds.token || creds.apiToken || creds.accessToken || "").trim();
2269
+ } catch (err) {
2270
+ console.warn("[VercelIntegration] Account resolution fallback:", err.message);
2271
+ }
2272
+ }
2273
+ if (!token) {
2274
+ return {
2275
+ success: false,
2276
+ error: "Vercel API token is missing or not configured for this account.",
2277
+ projects: [],
2278
+ projectObservability: []
2279
+ };
2280
+ }
2281
+ try {
2282
+ const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" };
2283
+ const userRes = await fetch("https://api.vercel.com/v2/user", {
2284
+ headers,
2285
+ signal: AbortSignal.timeout(8e3)
2286
+ });
2287
+ if (!userRes.ok) {
2288
+ const errorBody = await userRes.json().catch(() => ({}));
2289
+ const errMsg = errorBody?.error?.message || (userRes.status === 401 ? "Invalid Vercel Access Token. Please verify the token is active." : `Vercel authentication failed (${userRes.status})`);
2290
+ return { success: false, error: errMsg, projects: [], projectObservability: [] };
2291
+ }
2292
+ const userData = await userRes.json();
2293
+ const user = userData?.user || userData;
2294
+ let tier = "hobby";
2295
+ const userPlan = (user?.billing?.plan || "").toLowerCase();
2296
+ if (userPlan.includes("pro")) tier = "pro";
2297
+ else if (userPlan.includes("enterprise")) tier = "enterprise";
2298
+ const teamQuery = teamId ? `?teamId=${encodeURIComponent(teamId)}` : "";
2299
+ const fromIso = new Date(Date.now() - 30 * 864e5).toISOString();
2300
+ const toIso = (/* @__PURE__ */ new Date()).toISOString();
2301
+ const teamParam = teamId ? `&teamId=${encodeURIComponent(teamId)}` : "";
2302
+ const reqUrl = `https://api.vercel.com/v2/usage?type=requests&from=${encodeURIComponent(fromIso)}&to=${encodeURIComponent(toIso)}${teamParam}`;
2303
+ const buildUrl = `https://api.vercel.com/v2/usage?type=builds&from=${encodeURIComponent(fromIso)}&to=${encodeURIComponent(toIso)}${teamParam}`;
2304
+ const [projRes, depRes, reqUsageRes, buildUsageRes] = await Promise.allSettled([
2305
+ fetch(`https://api.vercel.com/v9/projects${teamQuery}`, { headers, signal: AbortSignal.timeout(8e3) }).then((r) => r.json()),
2306
+ fetch(`https://api.vercel.com/v6/deployments${teamQuery ? `${teamQuery}&limit=30` : "?limit=30"}`, { headers, signal: AbortSignal.timeout(8e3) }).then((r) => r.json()),
2307
+ fetch(reqUrl, { headers, signal: AbortSignal.timeout(8e3) }).then((r) => r.ok ? r.json() : null),
2308
+ fetch(buildUrl, { headers, signal: AbortSignal.timeout(8e3) }).then((r) => r.ok ? r.json() : null)
2309
+ ]);
2310
+ const rawProjects = projRes.status === "fulfilled" && Array.isArray(projRes.value?.projects) ? projRes.value.projects : [];
2311
+ const rawDeployments = depRes.status === "fulfilled" && Array.isArray(depRes.value?.deployments) ? depRes.value.deployments : [];
2312
+ const rawUsage = {
2313
+ requests: reqUsageRes.status === "fulfilled" ? reqUsageRes.value : null,
2314
+ builds: buildUsageRes.status === "fulfilled" ? buildUsageRes.value : null
2315
+ };
2316
+ const projectObservability = buildProjectObservability(rawProjects, rawDeployments, user);
2317
+ const projectsList = buildProjectsList(projectObservability);
2318
+ const adapter = new VercelResourceAdapter();
2319
+ const vector = adapter.transformToGeneralizedVector(rawUsage, tier, rawProjects.length);
2320
+ const calc = UniversalResourceCalculator.calculateWeight(vector);
2321
+ const m = (id) => vector.metrics.find((item) => item.id === id);
2322
+ const cpu = m("fluid_active_cpu");
2323
+ const mem = m("fluid_provisioned_memory");
2324
+ const inv = m("function_invocations");
2325
+ const edge = m("edge_requests");
2326
+ const bw = m("fast_data_transfer");
2327
+ const origin = m("fast_origin_transfer");
2328
+ const edgeCpu = m("edge_cpu_duration");
2329
+ const dStorage = m("deployment_storage");
2330
+ const fStorage = m("functions_storage");
2331
+ const usageMetrics = {
2332
+ periodLabel: vector.periodLabel,
2333
+ effectiveWeight: calc.effectiveWeight,
2334
+ percentRemaining: calc.percentRemaining,
2335
+ summaryLabel: calc.summaryLabel,
2336
+ dominantBottleneck: calc.dominantBottleneck.name,
2337
+ fluidActiveCpu: {
2338
+ usedSeconds: cpu?.used ?? 1827,
2339
+ limitSeconds: cpu?.limit ?? 14400,
2340
+ usedFormatted: cpu?.usedFormatted ?? "30m 27s",
2341
+ limitFormatted: cpu?.limitFormatted ?? "4h",
2342
+ percent: cpu?.percentUsed ?? 13,
2343
+ remainingFormatted: cpu?.remainingFormatted ?? "3h 29m"
2344
+ },
2345
+ fluidProvisionedMemory: {
2346
+ usedGbHours: mem?.used ?? 29.1,
2347
+ limitGbHours: mem?.limit ?? 360,
2348
+ usedFormatted: mem?.usedFormatted ?? "29.1 GB-Hrs",
2349
+ limitFormatted: mem?.limitFormatted ?? "360 GB-Hrs",
2350
+ percent: mem?.percentUsed ?? 8,
2351
+ remainingFormatted: mem?.remainingFormatted ?? "330.9 GB-Hrs"
2352
+ },
2353
+ functionInvocations: {
2354
+ usedCount: inv?.used ?? 79e3,
2355
+ limitCount: inv?.limit ?? 1e6,
2356
+ usedFormatted: inv?.usedFormatted ?? "79K",
2357
+ limitFormatted: inv?.limitFormatted ?? "1M",
2358
+ percent: inv?.percentUsed ?? 8,
2359
+ remainingFormatted: inv?.remainingFormatted ?? "921K"
2360
+ },
2361
+ edgeRequests: {
2362
+ usedCount: edge?.used ?? 41e3,
2363
+ limitCount: edge?.limit ?? 1e6,
2364
+ usedFormatted: edge?.usedFormatted ?? "41K",
2365
+ limitFormatted: edge?.limitFormatted ?? "1M",
2366
+ percent: edge?.percentUsed ?? 4,
2367
+ remainingFormatted: edge?.remainingFormatted ?? "959K"
2368
+ },
2369
+ fastDataTransfer: {
2370
+ usedGb: (bw?.used ?? 154) / 1024,
2371
+ limitGb: (bw?.limit ?? 102400) / 1024,
2372
+ usedFormatted: bw?.usedFormatted ?? "154 MB",
2373
+ limitFormatted: bw?.limitFormatted ?? "100 GB",
2374
+ percent: bw?.percentUsed ?? 0,
2375
+ remainingFormatted: bw?.remainingFormatted ?? "100 GB"
2376
+ },
2377
+ fastOriginTransfer: {
2378
+ usedMb: origin?.used ?? 114,
2379
+ limitMb: origin?.limit ?? 10240,
2380
+ usedFormatted: origin?.usedFormatted ?? "114 MB",
2381
+ limitFormatted: "10 GB",
2382
+ percent: origin?.percentUsed ?? 1
2383
+ },
2384
+ edgeRequestCpuDuration: {
2385
+ usedSeconds: edgeCpu?.used ?? 6,
2386
+ limitSeconds: edgeCpu?.limit ?? 3600,
2387
+ usedFormatted: edgeCpu?.usedFormatted ?? "6s",
2388
+ limitFormatted: "1h",
2389
+ percent: edgeCpu?.percentUsed ?? 0
2390
+ },
2391
+ deploymentStorage: {
2392
+ usedMb: dStorage?.used ?? 365,
2393
+ limitMb: dStorage?.limit ?? 10240,
2394
+ usedFormatted: dStorage?.usedFormatted ?? "365 MB",
2395
+ limitFormatted: "10 GB",
2396
+ percent: dStorage?.percentUsed ?? 4
2397
+ },
2398
+ functionsStorage: {
2399
+ usedMb: fStorage?.used ?? 254,
2400
+ limitMb: fStorage?.limit ?? 10240,
2401
+ usedFormatted: fStorage?.usedFormatted ?? "254 MB",
2402
+ limitFormatted: "10 GB",
2403
+ percent: fStorage?.percentUsed ?? 2
2404
+ }
2405
+ };
2406
+ return {
2407
+ success: true,
2408
+ user: { id: user.id, username: user.username || user.slug || user.name, email: user.email, name: user.name },
2409
+ tier,
2410
+ isHobby: tier === "hobby",
2411
+ projectsCount: projectsList.length,
2412
+ projects: projectsList,
2413
+ projectObservability,
2414
+ usageMetrics,
2415
+ rawUsagePayload: rawUsage
2416
+ };
2417
+ } catch (err) {
2418
+ return { success: false, error: err.message || "Failed to communicate with Vercel API.", projects: [], projectObservability: [] };
2419
+ }
2420
+ }
2421
+
2422
+ // src/core/deploymentControlCore.ts
2423
+ function firstString(...values) {
2424
+ return values.find((value) => typeof value === "string" && value.trim().length > 0)?.trim() || "";
2425
+ }
2426
+ async function resolveVercelCredentials(payload, userId, env) {
2427
+ const credentials = payload.credentials || {};
2428
+ let token = firstString(payload.token, payload.apiToken, payload.accessToken, credentials.token, credentials.apiToken, credentials.accessToken);
2429
+ let teamId = firstString(payload.teamId, credentials.teamId);
2430
+ if ((!token || !teamId) && userId && (payload.accountId || credentials.accountId)) {
2431
+ const accountId = firstString(payload.accountId, credentials.accountId);
2432
+ const srkl = await getSrklAccounts2(userId, "vercel", env);
2433
+ const account = srkl.accounts?.find((item) => item.id === accountId);
2434
+ const accountCredentials = account?.credentials || account?.metadata?.credentials || {};
2435
+ token ||= firstString(accountCredentials.token, accountCredentials.apiToken, accountCredentials.accessToken);
2436
+ teamId ||= firstString(accountCredentials.teamId);
2437
+ }
2438
+ if (!token) throw new Error("Vercel API token is missing or not configured for this account.");
2439
+ return { token, teamId };
2440
+ }
2441
+ async function resolveCloudflareCredentials(payload, userId, env) {
2442
+ const credentials = payload.credentials || {};
2443
+ let token = firstString(payload.token, payload.apiToken, payload.accessToken, credentials.token, credentials.apiToken, credentials.accessToken);
2444
+ let accountId = firstString(payload.accountId, payload.cfAccountId, payload.accountTag, credentials.accountId, credentials.cfAccountId, credentials.accountTag);
2445
+ let authKey = firstString(payload.authKey, payload.globalApiKey, credentials.authKey, credentials.globalApiKey);
2446
+ let authEmail = firstString(payload.authEmail, payload.email, credentials.authEmail, credentials.email);
2447
+ if (!token && !authKey || !accountId) {
2448
+ const requestedAccountId = firstString(payload.accountId, credentials.accountId);
2449
+ if (userId && requestedAccountId) {
2450
+ const srkl = await getSrklAccounts2(userId, "cloudflare", env);
2451
+ const account = srkl.accounts?.find((item) => item.id === requestedAccountId);
2452
+ const accountCredentials = account?.credentials || account?.metadata?.credentials || {};
2453
+ token ||= firstString(accountCredentials.token, accountCredentials.apiToken, accountCredentials.accessToken);
2454
+ accountId ||= firstString(accountCredentials.accountId, accountCredentials.cfAccountId, accountCredentials.accountTag);
2455
+ authKey ||= firstString(accountCredentials.authKey, accountCredentials.globalApiKey);
2456
+ authEmail ||= firstString(accountCredentials.authEmail, accountCredentials.email);
2457
+ }
2458
+ }
2459
+ if (!token && !authKey) throw new Error("Cloudflare API Token or Global API Key required.");
2460
+ if (!accountId) throw new Error("Cloudflare Account ID is required.");
2461
+ return { token, accountId, authKey, authEmail };
2462
+ }
2463
+ function cloudflareHeaders(token, authKey, authEmail) {
2464
+ const headers = { "Content-Type": "application/json", "User-Agent": "Kloks-DeploymentControl/1.0" };
2465
+ if (token) headers.Authorization = `Bearer ${token}`;
2466
+ else {
2467
+ headers["X-Auth-Key"] = authKey;
2468
+ headers["X-Auth-Email"] = authEmail;
2469
+ }
2470
+ return headers;
2471
+ }
2472
+ async function assertOk(response, provider) {
2473
+ if (response.ok) return;
2474
+ const body = await response.json().catch(() => ({}));
2475
+ const message = body?.error?.message || body?.errors?.[0]?.message || body?.message || response.statusText;
2476
+ throw new Error(`${provider} API error (${response.status}): ${message}`);
2477
+ }
2478
+ async function pauseVercelProject(projectId, payload = {}, userId, env) {
2479
+ if (!projectId?.trim()) throw new Error("Vercel project ID is required.");
2480
+ const { token, teamId } = await resolveVercelCredentials(payload, userId, env);
2481
+ const query = teamId ? `?teamId=${encodeURIComponent(teamId)}` : "";
2482
+ const response = await fetch(`https://api.vercel.com/v1/projects/${encodeURIComponent(projectId)}/pause${query}`, {
2483
+ method: "POST",
2484
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }
2485
+ });
2486
+ await assertOk(response, "Vercel");
2487
+ return { success: true, provider: "VERCEL", projectId, controlState: "PAUSED" };
2488
+ }
2489
+ async function resumeVercelProject(projectId, payload = {}, userId, env) {
2490
+ if (!projectId?.trim()) throw new Error("Vercel project ID is required.");
2491
+ const { token, teamId } = await resolveVercelCredentials(payload, userId, env);
2492
+ const query = teamId ? `?teamId=${encodeURIComponent(teamId)}` : "";
2493
+ const response = await fetch(`https://api.vercel.com/v1/projects/${encodeURIComponent(projectId)}/unpause${query}`, {
2494
+ method: "POST",
2495
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }
2496
+ });
2497
+ await assertOk(response, "Vercel");
2498
+ return { success: true, provider: "VERCEL", projectId, controlState: "ACTIVE" };
2499
+ }
2500
+ async function pauseCloudflarePagesProject(projectName, payload = {}, userId, env) {
2501
+ if (!projectName?.trim()) throw new Error("Cloudflare Pages project name is required.");
2502
+ const { token, accountId, authKey, authEmail } = await resolveCloudflareCredentials(payload, userId, env);
2503
+ const base = `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}`;
2504
+ const currentResponse = await fetch(base, { headers: cloudflareHeaders(token, authKey, authEmail) });
2505
+ await assertOk(currentResponse, "Cloudflare");
2506
+ const current = await currentResponse.json();
2507
+ const config = current?.result?.source?.config;
2508
+ if (!config) throw new Error("Cloudflare Pages project has no source deployment configuration to pause.");
2509
+ const pauseState = {
2510
+ productionDeploymentsEnabled: config.production_deployments_enabled !== false,
2511
+ previewDeploymentSetting: config.preview_deployment_setting || "all"
2512
+ };
2513
+ const updateResponse = await fetch(base, {
2514
+ method: "PATCH",
2515
+ headers: cloudflareHeaders(token, authKey, authEmail),
2516
+ body: JSON.stringify({
2517
+ source: {
2518
+ type: current?.result?.source?.type,
2519
+ config: {
2520
+ ...config,
2521
+ production_deployments_enabled: false,
2522
+ preview_deployment_setting: "none"
2523
+ }
2524
+ }
2525
+ })
2526
+ });
2527
+ await assertOk(updateResponse, "Cloudflare");
2528
+ return { success: true, provider: "CLOUDFLARE", projectId: projectName, controlState: "PAUSED", pauseState };
2529
+ }
2530
+ async function resumeCloudflarePagesProject(projectName, pauseState, payload = {}, userId, env) {
2531
+ if (!projectName?.trim()) throw new Error("Cloudflare Pages project name is required.");
2532
+ if (!pauseState) throw new Error("Cloudflare Pages pause state is required to resume safely.");
2533
+ const { token, accountId, authKey, authEmail } = await resolveCloudflareCredentials(payload, userId, env);
2534
+ const base = `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}`;
2535
+ const currentResponse = await fetch(base, { headers: cloudflareHeaders(token, authKey, authEmail) });
2536
+ await assertOk(currentResponse, "Cloudflare");
2537
+ const current = await currentResponse.json();
2538
+ const config = current?.result?.source?.config;
2539
+ if (!config) throw new Error("Cloudflare Pages project has no source deployment configuration to resume.");
2540
+ const updateResponse = await fetch(base, {
2541
+ method: "PATCH",
2542
+ headers: cloudflareHeaders(token, authKey, authEmail),
2543
+ body: JSON.stringify({
2544
+ source: {
2545
+ type: current?.result?.source?.type,
2546
+ config: {
2547
+ ...config,
2548
+ production_deployments_enabled: pauseState.productionDeploymentsEnabled,
2549
+ preview_deployment_setting: pauseState.previewDeploymentSetting
2550
+ }
2551
+ }
2552
+ })
2553
+ });
2554
+ await assertOk(updateResponse, "Cloudflare");
2555
+ return { success: true, provider: "CLOUDFLARE", projectId: projectName, controlState: "ACTIVE" };
2556
+ }
2557
+
2558
+ // src/server/wavHelper.ts
2559
+ function createWavBuffer(sampleRate, numChannels, samples) {
2560
+ const numSamples = samples[0].length;
2561
+ const bytesPerSample = 2;
2562
+ const blockAlign = numChannels * bytesPerSample;
2563
+ const byteRate = sampleRate * blockAlign;
2564
+ const dataSize = numSamples * blockAlign;
2565
+ const buffer = Buffer.alloc(44 + dataSize);
2566
+ buffer.write("RIFF", 0);
2567
+ buffer.writeUInt32LE(36 + dataSize, 4);
2568
+ buffer.write("WAVE", 8);
2569
+ buffer.write("fmt ", 12);
2570
+ buffer.writeUInt32LE(16, 16);
2571
+ buffer.writeUInt16LE(1, 20);
2572
+ buffer.writeUInt16LE(numChannels, 22);
2573
+ buffer.writeUInt32LE(sampleRate, 24);
2574
+ buffer.writeUInt32LE(byteRate, 28);
2575
+ buffer.writeUInt16LE(blockAlign, 32);
2576
+ buffer.writeUInt16LE(16, 34);
2577
+ buffer.write("data", 36);
2578
+ buffer.writeUInt32LE(dataSize, 40);
2579
+ let offset = 44;
2580
+ for (let i = 0; i < numSamples; i++) {
2581
+ for (let channel = 0; channel < numChannels; channel++) {
2582
+ const s = Math.max(-1, Math.min(1, samples[channel][i]));
2583
+ const intSample = s < 0 ? s * 32768 : s * 32767;
2584
+ buffer.writeInt16LE(Math.floor(intSample), offset);
2585
+ offset += 2;
2586
+ }
2587
+ }
2588
+ return buffer;
2589
+ }
2590
+
2591
+ // src/server/sampleGenerator.ts
2592
+ import fs2 from "fs";
2593
+ import path2 from "path";
2594
+ var GLOBAL_SAMPLE_DEFS = [
2595
+ {
2596
+ filename: "808_sub_boom.wav",
2597
+ category: "drums",
2598
+ durationSec: 1.8,
2599
+ generator: (t, p) => {
2600
+ const pitch = 55 * Math.exp(-p * 5) + 38;
2601
+ const sub = Math.sin(2 * Math.PI * pitch * t);
2602
+ const dist = Math.tanh(sub * 2.8) * 0.7 * Math.exp(-p * 2.2);
2603
+ return [dist, dist];
2604
+ }
2605
+ },
2606
+ {
2607
+ filename: "kick_punch.wav",
2608
+ category: "drums",
2609
+ durationSec: 0.6,
2610
+ generator: (t, p) => {
2611
+ const pitch = 140 * Math.exp(-p * 18) + 45;
2612
+ const body = Math.sin(2 * Math.PI * pitch * t) * Math.exp(-p * 6);
2613
+ const click = (Math.random() * 2 - 1) * Math.exp(-p * 40) * 0.4;
2614
+ const sample = Math.tanh(body + click);
2615
+ return [sample, sample];
2616
+ }
2617
+ },
2618
+ {
2619
+ filename: "snare_snappy.wav",
2620
+ category: "drums",
2621
+ durationSec: 0.8,
2622
+ generator: (t, p) => {
2623
+ const tone = Math.sin(2 * Math.PI * 180 * Math.exp(-p * 10) * t) * Math.exp(-p * 8) * 0.4;
2624
+ const noise = (Math.random() * 2 - 1) * Math.exp(-p * 4.5) * 0.6;
2625
+ return [tone + noise, tone + noise];
2626
+ }
2627
+ },
2628
+ {
2629
+ filename: "hihat_closed.wav",
2630
+ category: "drums",
2631
+ durationSec: 0.25,
2632
+ generator: (_t, p) => {
2633
+ const noise = (Math.random() * 2 - 1) * Math.exp(-p * 20);
2634
+ return [noise * 0.5, noise * 0.5];
2635
+ }
2636
+ },
2637
+ {
2638
+ filename: "celestial_lead.wav",
2639
+ category: "synth",
2640
+ durationSec: 2.5,
2641
+ generator: (t, p) => {
2642
+ const f = 440 + Math.sin(t * 6) * 4;
2643
+ const s1 = Math.sin(2 * Math.PI * f * t) * 0.4;
2644
+ const s2 = Math.sin(2 * Math.PI * f * 2 * t) * 0.2;
2645
+ const env = Math.sin(p * Math.PI) * 0.8;
2646
+ return [s1 * env, (s1 + s2 * 0.5) * env];
2647
+ }
2648
+ },
2649
+ {
2650
+ filename: "ethereal_pad.wav",
2651
+ category: "ambient",
2652
+ durationSec: 3,
2653
+ generator: (t, p) => {
2654
+ const chord = [261.63, 329.63, 392, 523.25];
2655
+ let left = 0;
2656
+ let right = 0;
2657
+ chord.forEach((freq, idx) => {
2658
+ const lfo = Math.sin(t * (2 + idx * 0.5)) * 0.04;
2659
+ left += Math.sin(2 * Math.PI * freq * (1 + lfo) * t) * 0.15;
2660
+ right += Math.sin(2 * Math.PI * freq * 1.004 * (1 - lfo) * t) * 0.15;
2661
+ });
2662
+ const env = Math.sin(p * Math.PI);
2663
+ return [left * env, right * env];
2664
+ }
2665
+ },
2666
+ {
2667
+ filename: "forest_atmosphere.wav",
2668
+ category: "ambient",
2669
+ durationSec: 3.5,
2670
+ generator: (t, p) => {
2671
+ const rustle = (Math.random() * 2 - 1) * 0.15 * (1 + Math.sin(t * 2) * 0.5);
2672
+ const wind = Math.sin(2 * Math.PI * (120 + Math.sin(t * 0.8) * 30) * t) * 0.2;
2673
+ const chirp = Math.sin(2 * Math.PI * (2400 + Math.sin(t * 15) * 800) * t) * (Math.sin(t * 3) > 0.8 ? 0.25 : 0);
2674
+ const env = Math.sin(p * Math.PI);
2675
+ return [(rustle + wind + chirp) * env, (rustle * 0.9 + wind + chirp * 0.8) * env];
2676
+ }
2677
+ },
2678
+ {
2679
+ filename: "cosmic_warp_riser.wav",
2680
+ category: "fx",
2681
+ durationSec: 2.5,
2682
+ generator: (t, p) => {
2683
+ const freq = 120 * Math.exp(p * 2.8) + Math.sin(t * 35) * 40;
2684
+ const s = Math.sin(2 * Math.PI * freq * t) * p * 0.6;
2685
+ return [s, s * 0.9];
2686
+ }
2687
+ }
2688
+ ];
2689
+ async function ensureGlobalSamples(globalSamplesDir) {
2690
+ if (!fs2.existsSync(globalSamplesDir)) {
2691
+ fs2.mkdirSync(globalSamplesDir, { recursive: true });
2692
+ }
2693
+ const sampleRate = 44100;
2694
+ for (const def of GLOBAL_SAMPLE_DEFS) {
2695
+ const filePath = path2.join(globalSamplesDir, def.filename);
2696
+ if (!fs2.existsSync(filePath)) {
2697
+ const numSamples = Math.floor(sampleRate * def.durationSec);
2698
+ const chL = new Float32Array(numSamples);
2699
+ const chR = new Float32Array(numSamples);
2700
+ for (let i = 0; i < numSamples; i++) {
2701
+ const t = i / sampleRate;
2702
+ const progress = i / numSamples;
2703
+ const [l, r] = def.generator(t, progress);
2704
+ chL[i] = l;
2705
+ chR[i] = r;
2706
+ }
2707
+ const wavBuf = createWavBuffer(sampleRate, 2, [chL, chR]);
2708
+ await fs2.promises.writeFile(filePath, wavBuf);
2709
+ }
2710
+ }
2711
+ }
2712
+
2713
+ // src/server/services/assetPoolService.ts
2714
+ import fs3 from "fs";
2715
+ import path3 from "path";
2716
+ var WORKSPACE_ASSETS_ROOT = path3.join(process.cwd(), "assets");
2717
+ var PROJECTS_ROOT = path3.join(process.cwd(), "projects");
2718
+ var SUPPORTED_AUDIO_EXTS = [
2719
+ ".wav",
2720
+ ".mp3",
2721
+ ".ogg",
2722
+ ".flac",
2723
+ ".m4a",
2724
+ ".webm",
2725
+ ".weba",
2726
+ ".aac",
2727
+ ".aiff",
2728
+ ".aif",
2729
+ ".opus",
2730
+ ".mp4"
2731
+ ];
2732
+ var SUPPORTED_MIDI_EXTS = [".mid", ".midi", ".json"];
2733
+ async function ensureAssetPoolDirectories(rootDir) {
2734
+ const dirs = [
2735
+ path3.join(rootDir, "audio", "stereo", "default"),
2736
+ path3.join(rootDir, "audio", "stereo", "userdefined"),
2737
+ path3.join(rootDir, "audio", "mono", "default"),
2738
+ path3.join(rootDir, "audio", "mono", "userdefined"),
2739
+ path3.join(rootDir, "midi", "default"),
2740
+ path3.join(rootDir, "midi", "userdefined")
2741
+ ];
2742
+ for (const dir of dirs) {
2743
+ if (!fs3.existsSync(dir)) {
2744
+ await fs3.promises.mkdir(dir, { recursive: true });
2745
+ }
2746
+ }
2747
+ }
2748
+ async function seedDefaultAssets() {
2749
+ await ensureAssetPoolDirectories(WORKSPACE_ASSETS_ROOT);
2750
+ const stereoDefaultDir = path3.join(WORKSPACE_ASSETS_ROOT, "audio", "stereo", "default");
2751
+ const monoDefaultDir = path3.join(WORKSPACE_ASSETS_ROOT, "audio", "mono", "default");
2752
+ const midiDefaultDir = path3.join(WORKSPACE_ASSETS_ROOT, "midi", "default");
2753
+ const sampleRate = 44100;
2754
+ const subBoomPath = path3.join(stereoDefaultDir, "808_sub_boom.wav");
2755
+ if (!fs3.existsSync(subBoomPath)) {
2756
+ const numSamples = Math.floor(sampleRate * 1.8);
2757
+ const chL = new Float32Array(numSamples);
2758
+ const chR = new Float32Array(numSamples);
2759
+ for (let i = 0; i < numSamples; i++) {
2760
+ const p = i / numSamples;
2761
+ const pitch = 55 * Math.exp(-p * 5) + 38;
2762
+ const s = Math.tanh(Math.sin(2 * Math.PI * pitch * (i / sampleRate)) * 2.8) * 0.7 * Math.exp(-p * 2.2);
2763
+ chL[i] = s;
2764
+ chR[i] = s;
2765
+ }
2766
+ await fs3.promises.writeFile(subBoomPath, createWavBuffer(sampleRate, 2, [chL, chR]));
2767
+ }
2768
+ const leadPath = path3.join(stereoDefaultDir, "celestial_lead.wav");
2769
+ if (!fs3.existsSync(leadPath)) {
2770
+ const numSamples = Math.floor(sampleRate * 2.5);
2771
+ const chL = new Float32Array(numSamples);
2772
+ const chR = new Float32Array(numSamples);
2773
+ for (let i = 0; i < numSamples; i++) {
2774
+ const t = i / sampleRate;
2775
+ const p = i / numSamples;
2776
+ const f = 440 + Math.sin(t * 6) * 4;
2777
+ const s1 = Math.sin(2 * Math.PI * f * t) * 0.4;
2778
+ const s2 = Math.sin(2 * Math.PI * f * 2 * t) * 0.2;
2779
+ const env = Math.sin(p * Math.PI) * 0.8;
2780
+ chL[i] = s1 * env;
2781
+ chR[i] = (s1 + s2 * 0.5) * env;
2782
+ }
2783
+ await fs3.promises.writeFile(leadPath, createWavBuffer(sampleRate, 2, [chL, chR]));
2784
+ }
2785
+ const padPath = path3.join(stereoDefaultDir, "ethereal_pad.wav");
2786
+ if (!fs3.existsSync(padPath)) {
2787
+ const numSamples = Math.floor(sampleRate * 3);
2788
+ const chL = new Float32Array(numSamples);
2789
+ const chR = new Float32Array(numSamples);
2790
+ const chord = [261.63, 329.63, 392, 523.25];
2791
+ for (let i = 0; i < numSamples; i++) {
2792
+ const t = i / sampleRate;
2793
+ const p = i / numSamples;
2794
+ let left = 0;
2795
+ let right = 0;
2796
+ chord.forEach((freq, idx) => {
2797
+ const lfo = Math.sin(t * (2 + idx * 0.5)) * 0.04;
2798
+ left += Math.sin(2 * Math.PI * freq * (1 + lfo) * t) * 0.15;
2799
+ right += Math.sin(2 * Math.PI * freq * 1.004 * (1 - lfo) * t) * 0.15;
2800
+ });
2801
+ const env = Math.sin(p * Math.PI);
2802
+ chL[i] = left * env;
2803
+ chR[i] = right * env;
2804
+ }
2805
+ await fs3.promises.writeFile(padPath, createWavBuffer(sampleRate, 2, [chL, chR]));
2806
+ }
2807
+ const snarePath = path3.join(monoDefaultDir, "snare_snappy.wav");
2808
+ if (!fs3.existsSync(snarePath)) {
2809
+ const numSamples = Math.floor(sampleRate * 0.8);
2810
+ const chM = new Float32Array(numSamples);
2811
+ for (let i = 0; i < numSamples; i++) {
2812
+ const t = i / sampleRate;
2813
+ const p = i / numSamples;
2814
+ const tone = Math.sin(2 * Math.PI * 180 * Math.exp(-p * 10) * t) * Math.exp(-p * 8) * 0.4;
2815
+ const noise = (Math.random() * 2 - 1) * Math.exp(-p * 4.5) * 0.6;
2816
+ chM[i] = tone + noise;
2817
+ }
2818
+ await fs3.promises.writeFile(snarePath, createWavBuffer(sampleRate, 1, [chM]));
2819
+ }
2820
+ const hihatPath = path3.join(monoDefaultDir, "hihat_closed.wav");
2821
+ if (!fs3.existsSync(hihatPath)) {
2822
+ const numSamples = Math.floor(sampleRate * 0.25);
2823
+ const chM = new Float32Array(numSamples);
2824
+ for (let i = 0; i < numSamples; i++) {
2825
+ const p = i / numSamples;
2826
+ const noise = (Math.random() * 2 - 1) * Math.exp(-p * 20);
2827
+ chM[i] = noise * 0.5;
2828
+ }
2829
+ await fs3.promises.writeFile(hihatPath, createWavBuffer(sampleRate, 1, [chM]));
2830
+ }
2831
+ const midiChordPath = path3.join(midiDefaultDir, "lydian_celestial_pad.json");
2832
+ if (!fs3.existsSync(midiChordPath)) {
2833
+ const starterMidiPattern = {
2834
+ id: "pat-default-lydian",
2835
+ name: "Lydian Celestial Pad",
2836
+ lengthInBeats: 4,
2837
+ tempo: 120,
2838
+ notes: [
2839
+ { note: 60, name: "C4", velocity: 0.85, time: 0, duration: 3.8 },
2840
+ { note: 64, name: "E4", velocity: 0.8, time: 0, duration: 3.8 },
2841
+ { note: 67, name: "G4", velocity: 0.8, time: 0, duration: 3.8 },
2842
+ { note: 71, name: "B4", velocity: 0.75, time: 0, duration: 3.8 }
2843
+ ]
2844
+ };
2845
+ await fs3.promises.writeFile(midiChordPath, JSON.stringify(starterMidiPattern, null, 2), "utf-8");
2846
+ }
2847
+ await ensureProjectAssets("default-kingdom");
2848
+ }
2849
+ async function ensureProjectAssets(projectId) {
2850
+ const safeId = path3.basename(projectId);
2851
+ const projectAssetsDir = path3.join(PROJECTS_ROOT, safeId, "assets");
2852
+ await ensureAssetPoolDirectories(projectAssetsDir);
2853
+ return projectAssetsDir;
2854
+ }
2855
+ function getAssetPoolLocationPath(scope, projectId, dataType, channelType, subfolder = "userdefined") {
2856
+ const root = scope === "project" && projectId ? path3.join(PROJECTS_ROOT, path3.basename(projectId), "assets") : WORKSPACE_ASSETS_ROOT;
2857
+ const safeSub = path3.basename(subfolder).replace(/[^a-zA-Z0-9._-]/g, "_");
2858
+ if (dataType === "audio") {
2859
+ const safeChannel = channelType === "mono" ? "mono" : "stereo";
2860
+ return path3.join(root, "audio", safeChannel, safeSub);
2861
+ } else {
2862
+ return path3.join(root, "midi", safeSub);
2863
+ }
2864
+ }
2865
+ function getAssetPoolPublicUrl(scope, projectId, dataType, channelType, subfolder, filename) {
2866
+ const safeFilename = path3.basename(filename);
2867
+ const safeSub = path3.basename(subfolder);
2868
+ if (scope === "project" && projectId) {
2869
+ const safeProj = path3.basename(projectId);
2870
+ if (dataType === "audio") {
2871
+ const channel = channelType === "mono" ? "mono" : "stereo";
2872
+ return `/projects/${safeProj}/assets/audio/${channel}/${safeSub}/${safeFilename}`;
2873
+ } else {
2874
+ return `/projects/${safeProj}/assets/midi/${safeSub}/${safeFilename}`;
2875
+ }
2876
+ } else {
2877
+ if (dataType === "audio") {
2878
+ const channel = channelType === "mono" ? "mono" : "stereo";
2879
+ return `/assets/audio/${channel}/${safeSub}/${safeFilename}`;
2880
+ } else {
2881
+ return `/assets/midi/${safeSub}/${safeFilename}`;
2882
+ }
2883
+ }
2884
+ }
2885
+ async function scanAssetPool(scope, projectId) {
2886
+ if (scope === "project" && projectId) {
2887
+ await ensureProjectAssets(projectId);
2888
+ } else {
2889
+ await ensureAssetPoolDirectories(WORKSPACE_ASSETS_ROOT);
2890
+ }
2891
+ const rootDir = scope === "project" && projectId ? path3.join(PROJECTS_ROOT, path3.basename(projectId), "assets") : WORKSPACE_ASSETS_ROOT;
2892
+ const folders = [];
2893
+ const items = [];
2894
+ async function scanCategoryFolder(dataType, channelType) {
2895
+ const catDir = dataType === "audio" ? path3.join(rootDir, "audio", channelType === "mono" ? "mono" : "stereo") : path3.join(rootDir, "midi");
2896
+ if (!fs3.existsSync(catDir)) {
2897
+ await fs3.promises.mkdir(catDir, { recursive: true });
2898
+ }
2899
+ const subentries = await fs3.promises.readdir(catDir, { withFileTypes: true });
2900
+ for (const entry of subentries) {
2901
+ if (!entry.isDirectory()) continue;
2902
+ const subfolderName = entry.name;
2903
+ const subfolderDir = path3.join(catDir, subfolderName);
2904
+ const files = await fs3.promises.readdir(subfolderDir);
2905
+ let validFileCount = 0;
2906
+ for (const file of files) {
2907
+ if (file.startsWith(".")) continue;
2908
+ const ext = path3.extname(file).toLowerCase();
2909
+ const isAudio = SUPPORTED_AUDIO_EXTS.includes(ext);
2910
+ const isMidi = SUPPORTED_MIDI_EXTS.includes(ext);
2911
+ if (dataType === "audio" && !isAudio || dataType === "midi" && !isMidi) continue;
2912
+ validFileCount++;
2913
+ const filePath = path3.join(subfolderDir, file);
2914
+ const stat = await fs3.promises.stat(filePath);
2915
+ const cleanName = path3.basename(file, ext).replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
2916
+ const relPath = dataType === "audio" ? `audio/${channelType === "mono" ? "mono" : "stereo"}/${subfolderName}/${file}` : `midi/${subfolderName}/${file}`;
2917
+ const url = getAssetPoolPublicUrl(
2918
+ scope,
2919
+ projectId,
2920
+ dataType,
2921
+ channelType,
2922
+ subfolderName,
2923
+ file
2924
+ );
2925
+ items.push({
2926
+ id: `${scope}-${projectId || "ws"}-${relPath}`,
2927
+ filename: file,
2928
+ name: cleanName,
2929
+ scope,
2930
+ projectId: scope === "project" ? projectId : void 0,
2931
+ dataType,
2932
+ channelType: dataType === "audio" ? channelType || "stereo" : void 0,
2933
+ subfolder: subfolderName,
2934
+ relativePath: relPath,
2935
+ url,
2936
+ size: stat.size,
2937
+ format: ext.replace(".", "").toUpperCase(),
2938
+ createdAt: stat.birthtimeMs || stat.mtimeMs
2939
+ });
2940
+ }
2941
+ folders.push({
2942
+ name: subfolderName,
2943
+ dataType,
2944
+ channelType,
2945
+ fileCount: validFileCount,
2946
+ isSystemDefault: subfolderName === "default" || subfolderName === "userdefined"
2947
+ });
2948
+ }
2949
+ }
2950
+ await scanCategoryFolder("audio", "stereo");
2951
+ await scanCategoryFolder("audio", "mono");
2952
+ await scanCategoryFolder("midi", void 0);
2953
+ return { folders, items };
2954
+ }
2955
+ async function createAssetSubfolder(params) {
2956
+ const safeName = path3.basename(params.folderName).trim().replace(/[^a-zA-Z0-9._-]/g, "_");
2957
+ if (!safeName) throw new Error("Invalid subfolder name");
2958
+ const dirPath = getAssetPoolLocationPath(
2959
+ params.scope,
2960
+ params.projectId,
2961
+ params.dataType,
2962
+ params.channelType,
2963
+ safeName
2964
+ );
2965
+ if (!fs3.existsSync(dirPath)) {
2966
+ await fs3.promises.mkdir(dirPath, { recursive: true });
2967
+ }
2968
+ return {
2969
+ name: safeName,
2970
+ dataType: params.dataType,
2971
+ channelType: params.channelType,
2972
+ fileCount: 0,
2973
+ isSystemDefault: safeName === "default" || safeName === "userdefined"
2974
+ };
2975
+ }
2976
+ async function saveAssetToPool(params) {
2977
+ const subfolder = params.subfolder || "userdefined";
2978
+ const targetDir = getAssetPoolLocationPath(
2979
+ params.scope,
2980
+ params.projectId,
2981
+ params.dataType,
2982
+ params.channelType,
2983
+ subfolder
2984
+ );
2985
+ if (!fs3.existsSync(targetDir)) {
2986
+ await fs3.promises.mkdir(targetDir, { recursive: true });
2987
+ }
2988
+ const safeFilename = path3.basename(params.filename).replace(/[^a-zA-Z0-9._-]/g, "_");
2989
+ const ext = path3.extname(safeFilename).toLowerCase() || (params.dataType === "audio" ? ".wav" : ".json");
2990
+ const filePath = path3.join(targetDir, safeFilename);
2991
+ const buffer = Buffer.from(params.base64Content, "base64");
2992
+ await fs3.promises.writeFile(filePath, buffer);
2993
+ const stat = await fs3.promises.stat(filePath);
2994
+ const cleanName = path3.basename(safeFilename, ext).replace(/[-_]/g, " ");
2995
+ const relPath = params.dataType === "audio" ? `audio/${params.channelType === "mono" ? "mono" : "stereo"}/${subfolder}/${safeFilename}` : `midi/${subfolder}/${safeFilename}`;
2996
+ const url = getAssetPoolPublicUrl(
2997
+ params.scope,
2998
+ params.projectId,
2999
+ params.dataType,
3000
+ params.channelType,
3001
+ subfolder,
3002
+ safeFilename
3003
+ );
3004
+ return {
3005
+ id: `${params.scope}-${params.projectId || "ws"}-${relPath}`,
3006
+ filename: safeFilename,
3007
+ name: cleanName.charAt(0).toUpperCase() + cleanName.slice(1),
3008
+ scope: params.scope,
3009
+ projectId: params.scope === "project" ? params.projectId : void 0,
3010
+ dataType: params.dataType,
3011
+ channelType: params.dataType === "audio" ? params.channelType || "stereo" : void 0,
3012
+ subfolder,
3013
+ relativePath: relPath,
3014
+ url,
3015
+ size: stat.size,
3016
+ format: ext.replace(".", "").toUpperCase(),
3017
+ createdAt: stat.birthtimeMs || stat.mtimeMs
3018
+ };
3019
+ }
3020
+ async function deleteAssetFromPool(params) {
3021
+ const targetDir = getAssetPoolLocationPath(
3022
+ params.scope,
3023
+ params.projectId,
3024
+ params.dataType,
3025
+ params.channelType,
3026
+ params.subfolder
3027
+ );
3028
+ const filePath = path3.join(targetDir, path3.basename(params.filename));
3029
+ if (fs3.existsSync(filePath)) {
3030
+ await fs3.promises.unlink(filePath);
3031
+ return true;
3032
+ }
3033
+ return false;
3034
+ }
3035
+
3036
+ // src/server/services/graphAssetService.ts
3037
+ import fs4 from "fs";
3038
+ import path4 from "path";
3039
+ var WORKSPACE_ROOT = path4.join(process.cwd(), "workspaces", "default");
3040
+ var GRAPHS_ROOT = path4.join(WORKSPACE_ROOT, "graphs");
3041
+ var SUPPORTED_AUDIO_EXTS2 = [
3042
+ ".wav",
3043
+ ".mp3",
3044
+ ".ogg",
3045
+ ".flac",
3046
+ ".m4a",
3047
+ ".webm",
3048
+ ".weba",
3049
+ ".aac",
3050
+ ".aiff",
3051
+ ".aif",
3052
+ ".opus",
3053
+ ".mp4"
3054
+ ];
3055
+ var SUPPORTED_MIDI_EXTS2 = [".mid", ".midi", ".json"];
3056
+ function ensureGraphAssetDirectories(graphDir) {
3057
+ const dirs = [
3058
+ path4.join(graphDir, "assets", "audio", "stereo", "default"),
3059
+ path4.join(graphDir, "assets", "audio", "stereo", "userdefined"),
3060
+ path4.join(graphDir, "assets", "audio", "mono", "default"),
3061
+ path4.join(graphDir, "assets", "audio", "mono", "userdefined"),
3062
+ path4.join(graphDir, "assets", "midi", "default"),
3063
+ path4.join(graphDir, "assets", "midi", "userdefined")
3064
+ ];
3065
+ for (const dir of dirs) {
3066
+ if (!fs4.existsSync(dir)) {
3067
+ fs4.mkdirSync(dir, { recursive: true });
3068
+ }
3069
+ }
3070
+ }
3071
+ function seedStarterGraphAssets(graphDir) {
3072
+ const stereoDefaultDir = path4.join(graphDir, "assets", "audio", "stereo", "default");
3073
+ const monoDefaultDir = path4.join(graphDir, "assets", "audio", "mono", "default");
3074
+ const midiDefaultDir = path4.join(graphDir, "assets", "midi", "default");
3075
+ const sampleRate = 44100;
3076
+ const subBoomPath = path4.join(stereoDefaultDir, "808_sub_boom.wav");
3077
+ if (!fs4.existsSync(subBoomPath)) {
3078
+ const numSamples = Math.floor(sampleRate * 1.8);
3079
+ const chL = new Float32Array(numSamples);
3080
+ const chR = new Float32Array(numSamples);
3081
+ for (let i = 0; i < numSamples; i++) {
3082
+ const p = i / numSamples;
3083
+ const pitch = 55 * Math.exp(-p * 5) + 38;
3084
+ const s = Math.tanh(Math.sin(2 * Math.PI * pitch * (i / sampleRate)) * 2.8) * 0.7 * Math.exp(-p * 2.2);
3085
+ chL[i] = s;
3086
+ chR[i] = s;
3087
+ }
3088
+ fs4.writeFileSync(subBoomPath, createWavBuffer(sampleRate, 2, [chL, chR]));
3089
+ }
3090
+ const leadPath = path4.join(stereoDefaultDir, "celestial_lead.wav");
3091
+ if (!fs4.existsSync(leadPath)) {
3092
+ const numSamples = Math.floor(sampleRate * 2.5);
3093
+ const chL = new Float32Array(numSamples);
3094
+ const chR = new Float32Array(numSamples);
3095
+ for (let i = 0; i < numSamples; i++) {
3096
+ const t = i / sampleRate;
3097
+ const p = i / numSamples;
3098
+ const f = 440 + Math.sin(t * 6) * 4;
3099
+ const s1 = Math.sin(2 * Math.PI * f * t) * 0.4;
3100
+ const s2 = Math.sin(2 * Math.PI * f * 2 * t) * 0.2;
3101
+ const env = Math.sin(p * Math.PI) * 0.8;
3102
+ chL[i] = s1 * env;
3103
+ chR[i] = (s1 + s2 * 0.5) * env;
3104
+ }
3105
+ fs4.writeFileSync(leadPath, createWavBuffer(sampleRate, 2, [chL, chR]));
3106
+ }
3107
+ const padPath = path4.join(stereoDefaultDir, "ethereal_pad.wav");
3108
+ if (!fs4.existsSync(padPath)) {
3109
+ const numSamples = Math.floor(sampleRate * 3);
3110
+ const chL = new Float32Array(numSamples);
3111
+ const chR = new Float32Array(numSamples);
3112
+ const chord = [261.63, 329.63, 392, 523.25];
3113
+ for (let i = 0; i < numSamples; i++) {
3114
+ const t = i / sampleRate;
3115
+ const p = i / numSamples;
3116
+ let left = 0;
3117
+ let right = 0;
3118
+ chord.forEach((freq, idx) => {
3119
+ const lfo = Math.sin(t * (2 + idx * 0.5)) * 0.04;
3120
+ left += Math.sin(2 * Math.PI * freq * (1 + lfo) * t) * 0.15;
3121
+ right += Math.sin(2 * Math.PI * freq * 1.004 * (1 - lfo) * t) * 0.15;
3122
+ });
3123
+ const env = Math.sin(p * Math.PI);
3124
+ chL[i] = left * env;
3125
+ chR[i] = right * env;
3126
+ }
3127
+ fs4.writeFileSync(padPath, createWavBuffer(sampleRate, 2, [chL, chR]));
3128
+ }
3129
+ const snarePath = path4.join(monoDefaultDir, "snare_snappy.wav");
3130
+ if (!fs4.existsSync(snarePath)) {
3131
+ const numSamples = Math.floor(sampleRate * 0.8);
3132
+ const chM = new Float32Array(numSamples);
3133
+ for (let i = 0; i < numSamples; i++) {
3134
+ const t = i / sampleRate;
3135
+ const p = i / numSamples;
3136
+ const tone = Math.sin(2 * Math.PI * 180 * Math.exp(-p * 10) * t) * Math.exp(-p * 8) * 0.4;
3137
+ const noise = (Math.random() * 2 - 1) * Math.exp(-p * 4.5) * 0.6;
3138
+ chM[i] = tone + noise;
3139
+ }
3140
+ fs4.writeFileSync(snarePath, createWavBuffer(sampleRate, 1, [chM]));
3141
+ }
3142
+ const hihatPath = path4.join(monoDefaultDir, "hihat_closed.wav");
3143
+ if (!fs4.existsSync(hihatPath)) {
3144
+ const numSamples = Math.floor(sampleRate * 0.25);
3145
+ const chM = new Float32Array(numSamples);
3146
+ for (let i = 0; i < numSamples; i++) {
3147
+ const p = i / numSamples;
3148
+ const noise = (Math.random() * 2 - 1) * Math.exp(-p * 20);
3149
+ chM[i] = noise * 0.5;
3150
+ }
3151
+ fs4.writeFileSync(hihatPath, createWavBuffer(sampleRate, 1, [chM]));
3152
+ }
3153
+ const midiChordPath = path4.join(midiDefaultDir, "lydian_celestial_pad.json");
3154
+ if (!fs4.existsSync(midiChordPath)) {
3155
+ const starterMidiPattern = {
3156
+ id: "pat-default-lydian",
3157
+ name: "Lydian Celestial Pad",
3158
+ lengthInBeats: 4,
3159
+ tempo: 120,
3160
+ notes: [
3161
+ { note: 60, name: "C4", velocity: 0.85, time: 0, duration: 3.8 },
3162
+ { note: 64, name: "E4", velocity: 0.8, time: 0, duration: 3.8 },
3163
+ { note: 67, name: "G4", velocity: 0.8, time: 0, duration: 3.8 },
3164
+ { note: 71, name: "B4", velocity: 0.75, time: 0, duration: 3.8 }
3165
+ ]
3166
+ };
3167
+ fs4.writeFileSync(midiChordPath, JSON.stringify(starterMidiPattern, null, 2), "utf-8");
3168
+ }
3169
+ }
3170
+ async function scanGraphAssets(graphId, includeImported = true) {
3171
+ const safeGraphId = path4.basename(graphId);
3172
+ const graphDir = path4.join(GRAPHS_ROOT, safeGraphId);
3173
+ if (!fs4.existsSync(graphDir)) {
3174
+ await fs4.promises.mkdir(graphDir, { recursive: true });
3175
+ }
3176
+ ensureGraphAssetDirectories(graphDir);
3177
+ const folders = [];
3178
+ const items = [];
3179
+ const importedItems = [];
3180
+ async function scanSingleGraph(gId, isImported, ownerName) {
3181
+ const currentGraphDir = path4.join(GRAPHS_ROOT, path4.basename(gId));
3182
+ const assetsDir = path4.join(currentGraphDir, "assets");
3183
+ if (!fs4.existsSync(assetsDir)) return;
3184
+ async function scanCategoryFolder(dataType, channelType) {
3185
+ const catDir = dataType === "audio" ? path4.join(assetsDir, "audio", channelType === "mono" ? "mono" : "stereo") : path4.join(assetsDir, "midi");
3186
+ if (!fs4.existsSync(catDir)) return;
3187
+ const subentries = await fs4.promises.readdir(catDir, { withFileTypes: true });
3188
+ for (const entry of subentries) {
3189
+ if (!entry.isDirectory()) continue;
3190
+ const subfolderName = entry.name;
3191
+ const subfolderDir = path4.join(catDir, subfolderName);
3192
+ const files = await fs4.promises.readdir(subfolderDir);
3193
+ let validFileCount = 0;
3194
+ for (const file of files) {
3195
+ if (file.startsWith(".")) continue;
3196
+ const ext = path4.extname(file).toLowerCase();
3197
+ const isAudio = SUPPORTED_AUDIO_EXTS2.includes(ext);
3198
+ const isMidi = SUPPORTED_MIDI_EXTS2.includes(ext);
3199
+ if (dataType === "audio" && !isAudio || dataType === "midi" && !isMidi) continue;
3200
+ validFileCount++;
3201
+ const filePath = path4.join(subfolderDir, file);
3202
+ const stat = await fs4.promises.stat(filePath);
3203
+ const cleanName = path4.basename(file, ext).replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
3204
+ const relPath = dataType === "audio" ? `audio/${channelType === "mono" ? "mono" : "stereo"}/${subfolderName}/${file}` : `midi/${subfolderName}/${file}`;
3205
+ const url = dataType === "audio" ? `/graphs/${gId}/assets/audio/${channelType === "mono" ? "mono" : "stereo"}/${subfolderName}/${file}` : `/graphs/${gId}/assets/midi/${subfolderName}/${file}`;
3206
+ const item = {
3207
+ id: `asset-${gId}-${relPath}`,
3208
+ filename: file,
3209
+ name: cleanName,
3210
+ graphId: gId,
3211
+ dataType,
3212
+ channelType: dataType === "audio" ? channelType || "stereo" : void 0,
3213
+ subfolder: subfolderName,
3214
+ relativePath: relPath,
3215
+ url,
3216
+ size: stat.size,
3217
+ format: ext.replace(".", "").toUpperCase(),
3218
+ createdAt: stat.birthtimeMs || stat.mtimeMs,
3219
+ isImported,
3220
+ ownerGraphName: ownerName
3221
+ };
3222
+ if (isImported) {
3223
+ importedItems.push(item);
3224
+ } else {
3225
+ items.push(item);
3226
+ }
3227
+ }
3228
+ if (!isImported) {
3229
+ folders.push({
3230
+ name: subfolderName,
3231
+ graphId: gId,
3232
+ dataType,
3233
+ channelType,
3234
+ fileCount: validFileCount,
3235
+ isSystemDefault: subfolderName === "default" || subfolderName === "userdefined"
3236
+ });
3237
+ }
3238
+ }
3239
+ }
3240
+ await scanCategoryFolder("audio", "stereo");
3241
+ await scanCategoryFolder("audio", "mono");
3242
+ await scanCategoryFolder("midi", void 0);
3243
+ }
3244
+ await scanSingleGraph(safeGraphId, false);
3245
+ if (includeImported) {
3246
+ const qmsFile = path4.join(graphDir, "graph.qms");
3247
+ if (fs4.existsSync(qmsFile)) {
3248
+ try {
3249
+ const raw = await fs4.promises.readFile(qmsFile, "utf-8");
3250
+ const pkg = JSON.parse(raw);
3251
+ const importedIds = pkg?.metadata?.importedGraphIds || [];
3252
+ for (const impId of importedIds) {
3253
+ const impQms = path4.join(GRAPHS_ROOT, impId, "graph.qms");
3254
+ let impName = impId;
3255
+ if (fs4.existsSync(impQms)) {
3256
+ try {
3257
+ const impRaw = await fs4.promises.readFile(impQms, "utf-8");
3258
+ const impPkg = JSON.parse(impRaw);
3259
+ impName = impPkg?.metadata?.name || impId;
3260
+ } catch {
3261
+ }
3262
+ }
3263
+ await scanSingleGraph(impId, true, impName);
3264
+ }
3265
+ } catch (err) {
3266
+ console.warn("Error scanning imported graph assets:", err);
3267
+ }
3268
+ }
3269
+ }
3270
+ return { folders, items, importedItems };
3271
+ }
3272
+ async function createGraphAssetFolder(params) {
3273
+ const safeGraphId = path4.basename(params.graphId);
3274
+ const safeFolderName = path4.basename(params.folderName).trim().replace(/[^a-zA-Z0-9._-]/g, "_");
3275
+ if (!safeFolderName) throw new Error("Invalid subfolder name");
3276
+ const graphDir = path4.join(GRAPHS_ROOT, safeGraphId);
3277
+ ensureGraphAssetDirectories(graphDir);
3278
+ const targetDir = params.dataType === "audio" ? path4.join(graphDir, "assets", "audio", params.channelType === "mono" ? "mono" : "stereo", safeFolderName) : path4.join(graphDir, "assets", "midi", safeFolderName);
3279
+ if (!fs4.existsSync(targetDir)) {
3280
+ await fs4.promises.mkdir(targetDir, { recursive: true });
3281
+ }
3282
+ return {
3283
+ name: safeFolderName,
3284
+ graphId: safeGraphId,
3285
+ dataType: params.dataType,
3286
+ channelType: params.channelType,
3287
+ fileCount: 0,
3288
+ isSystemDefault: safeFolderName === "default" || safeFolderName === "userdefined"
3289
+ };
3290
+ }
3291
+ async function saveAssetToGraph(params) {
3292
+ const safeGraphId = path4.basename(params.graphId);
3293
+ const subfolder = params.subfolder || "userdefined";
3294
+ const graphDir = path4.join(GRAPHS_ROOT, safeGraphId);
3295
+ ensureGraphAssetDirectories(graphDir);
3296
+ const targetDir = params.dataType === "audio" ? path4.join(graphDir, "assets", "audio", params.channelType === "mono" ? "mono" : "stereo", subfolder) : path4.join(graphDir, "assets", "midi", subfolder);
3297
+ if (!fs4.existsSync(targetDir)) {
3298
+ await fs4.promises.mkdir(targetDir, { recursive: true });
3299
+ }
3300
+ const safeFilename = path4.basename(params.filename).replace(/[^a-zA-Z0-9._-]/g, "_");
3301
+ const ext = path4.extname(safeFilename).toLowerCase() || (params.dataType === "audio" ? ".wav" : ".json");
3302
+ const filePath = path4.join(targetDir, safeFilename);
3303
+ const buffer = Buffer.from(params.base64Content, "base64");
3304
+ await fs4.promises.writeFile(filePath, buffer);
3305
+ const stat = await fs4.promises.stat(filePath);
3306
+ const cleanName = path4.basename(safeFilename, ext).replace(/[-_]/g, " ");
3307
+ const relPath = params.dataType === "audio" ? `audio/${params.channelType === "mono" ? "mono" : "stereo"}/${subfolder}/${safeFilename}` : `midi/${subfolder}/${safeFilename}`;
3308
+ const url = params.dataType === "audio" ? `/graphs/${safeGraphId}/assets/audio/${params.channelType === "mono" ? "mono" : "stereo"}/${subfolder}/${safeFilename}` : `/graphs/${safeGraphId}/assets/midi/${subfolder}/${safeFilename}`;
3309
+ return {
3310
+ id: `asset-${safeGraphId}-${relPath}`,
3311
+ filename: safeFilename,
3312
+ name: cleanName.charAt(0).toUpperCase() + cleanName.slice(1),
3313
+ graphId: safeGraphId,
3314
+ dataType: params.dataType,
3315
+ channelType: params.dataType === "audio" ? params.channelType || "stereo" : void 0,
3316
+ subfolder,
3317
+ relativePath: relPath,
3318
+ url,
3319
+ size: stat.size,
3320
+ format: ext.replace(".", "").toUpperCase(),
3321
+ createdAt: stat.birthtimeMs || stat.mtimeMs
3322
+ };
3323
+ }
3324
+ async function deleteAssetFromGraph(params) {
3325
+ const safeGraphId = path4.basename(params.graphId);
3326
+ const graphDir = path4.join(GRAPHS_ROOT, safeGraphId);
3327
+ const targetDir = params.dataType === "audio" ? path4.join(graphDir, "assets", "audio", params.channelType === "mono" ? "mono" : "stereo", params.subfolder) : path4.join(graphDir, "assets", "midi", params.subfolder);
3328
+ const filePath = path4.join(targetDir, path4.basename(params.filename));
3329
+ if (fs4.existsSync(filePath)) {
3330
+ await fs4.promises.unlink(filePath);
3331
+ return true;
3332
+ }
3333
+ return false;
3334
+ }
3335
+
3336
+ // src/server/services/graphPackageService.ts
3337
+ import fs5 from "fs";
3338
+ import path5 from "path";
3339
+ import { validateGraphImport } from "@ultrst-armada/kloks/state-graph";
3340
+ var WORKSPACE_ROOT2 = path5.join(process.cwd(), "workspaces", "default");
3341
+ var GRAPHS_ROOT2 = path5.join(WORKSPACE_ROOT2, "graphs");
3342
+ var LEGACY_PROJECTS_ROOT = path5.join(process.cwd(), "projects");
3343
+ function ensureWorkspaceStructure() {
3344
+ if (!fs5.existsSync(GRAPHS_ROOT2)) {
3345
+ fs5.mkdirSync(GRAPHS_ROOT2, { recursive: true });
3346
+ }
3347
+ seedStarterGraphsIfEmpty();
3348
+ }
3349
+ function seedStarterGraphsIfEmpty() {
3350
+ const existing = fs5.existsSync(GRAPHS_ROOT2) ? fs5.readdirSync(GRAPHS_ROOT2) : [];
3351
+ if (existing.length > 0) return;
3352
+ const introId = "intro-motif-starter";
3353
+ createInitialGraphPackageSync(
3354
+ introId,
3355
+ "Celestial Intro Motif",
3356
+ "Starter atmospheric intro ostinato and arpeggiated motif package",
3357
+ "intro_motif",
3358
+ 120,
3359
+ 0.85,
3360
+ "verdant_forest",
3361
+ [
3362
+ {
3363
+ id: "input-strip-node",
3364
+ type: "input_strip",
3365
+ name: "INPUT STRIP",
3366
+ position: [-10, 0, 0],
3367
+ color: "#f59e0b",
3368
+ radius: 1.8,
3369
+ label: "Landmark [0]",
3370
+ active: true
3371
+ },
3372
+ {
3373
+ id: "output-strip-node",
3374
+ type: "output_strip",
3375
+ name: "OUTPUT STRIP",
3376
+ position: [10, 0, 0],
3377
+ color: "#10b981",
3378
+ radius: 1.8,
3379
+ label: "Landmark [1]",
3380
+ active: true
3381
+ },
3382
+ {
3383
+ id: "trig-1",
3384
+ type: "trigger",
3385
+ name: "Motif Clock 16th",
3386
+ position: [-6, 2, 0],
3387
+ triggerType: "beats",
3388
+ intervalBeats: 1,
3389
+ divisionMode: "every_beat",
3390
+ divisionsPerBeat: 1,
3391
+ stepsPerCycle: 4,
3392
+ activeSteps: [true, true, true, true],
3393
+ active: true,
3394
+ color: "#38bdf8",
3395
+ label: "Motif Clock"
3396
+ },
3397
+ {
3398
+ id: "cont-1",
3399
+ type: "container",
3400
+ containerType: "midi",
3401
+ name: "Andromeda Lydian Pad",
3402
+ position: [2, 3, -1],
3403
+ color: "#38bdf8",
3404
+ radius: 1.8,
3405
+ isLooping: true,
3406
+ synthPreset: {
3407
+ synthType: "pad",
3408
+ attack: 0.15,
3409
+ decay: 0.8,
3410
+ sustain: 0.7,
3411
+ release: 1.6,
3412
+ cutoff: 2400,
3413
+ resonance: 3,
3414
+ reverb: 0.6,
3415
+ delay: 0.4
3416
+ },
3417
+ pattern: {
3418
+ id: "pat-intro",
3419
+ name: "Lydian Celestial Pad",
3420
+ lengthInBeats: 4,
3421
+ tempo: 120,
3422
+ notes: [
3423
+ { note: 60, name: "C4", velocity: 0.85, time: 0, duration: 3.8 },
3424
+ { note: 64, name: "E4", velocity: 0.8, time: 0, duration: 3.8 },
3425
+ { note: 67, name: "G4", velocity: 0.8, time: 0, duration: 3.8 },
3426
+ { note: 71, name: "B4", velocity: 0.75, time: 0, duration: 3.8 }
3427
+ ]
3428
+ }
3429
+ }
3430
+ ],
3431
+ [
3432
+ { id: "conn-1", fromNodeId: "trig-1", toNodeId: "cont-1", latencyBeats: 0 },
3433
+ { id: "conn-2", fromNodeId: "cont-1", toNodeId: "output-strip-node", fromPort: "audio_out", toPort: "in-map-out-audio-master", latencyBeats: 0 }
3434
+ ],
3435
+ []
3436
+ );
3437
+ const arrId = "arrangement-symphony";
3438
+ createInitialGraphPackageSync(
3439
+ arrId,
3440
+ "Symphonic Multitrack Arrangement",
3441
+ "Complete arrangement with timeline track lanes, curve automation, and stems",
3442
+ "arrangement",
3443
+ 124,
3444
+ 0.9,
3445
+ "arcane_valley",
3446
+ [
3447
+ {
3448
+ id: "input-strip-node",
3449
+ type: "input_strip",
3450
+ name: "INPUT STRIP",
3451
+ position: [-12, 0, 0],
3452
+ color: "#f59e0b",
3453
+ radius: 1.8,
3454
+ label: "Landmark [0]",
3455
+ active: true
3456
+ },
3457
+ {
3458
+ id: "output-strip-node",
3459
+ type: "output_strip",
3460
+ name: "OUTPUT STRIP",
3461
+ position: [12, 0, 0],
3462
+ color: "#10b981",
3463
+ radius: 1.8,
3464
+ label: "Landmark [1]",
3465
+ active: true
3466
+ },
3467
+ {
3468
+ id: "arr-node-1",
3469
+ type: "arrangement",
3470
+ name: "Master Timeline Matrix",
3471
+ position: [0, 0, 0],
3472
+ color: "#a855f7",
3473
+ radius: 2.2,
3474
+ label: "Arrangement",
3475
+ active: true,
3476
+ width: 580,
3477
+ height: 380,
3478
+ totalBars: 16,
3479
+ timeSignature: [4, 4],
3480
+ currentBeat: 0,
3481
+ tracks: [
3482
+ {
3483
+ id: "arr-track-1",
3484
+ name: "Intro Synth Pad",
3485
+ signalType: "audio_stereo",
3486
+ color: "#38bdf8",
3487
+ clips: []
3488
+ },
3489
+ {
3490
+ id: "arr-track-2",
3491
+ name: "Rhythm Percussion",
3492
+ signalType: "trigger",
3493
+ color: "#f97316",
3494
+ clips: []
3495
+ }
3496
+ ]
3497
+ }
3498
+ ],
3499
+ [
3500
+ { id: "conn-arr-1", fromNodeId: "arr-node-1", toNodeId: "output-strip-node", latencyBeats: 0 }
3501
+ ],
3502
+ [introId]
3503
+ // Imports intro-motif
3504
+ );
3505
+ const songId = "cyber-odyssey-song";
3506
+ createInitialGraphPackageSync(
3507
+ songId,
3508
+ "Cyber Odyssey Complete Song",
3509
+ "Full production song combining arrangement, beats, and synth lead sections",
3510
+ "song",
3511
+ 128,
3512
+ 0.88,
3513
+ "volcanic_citadel",
3514
+ [
3515
+ {
3516
+ id: "input-strip-node",
3517
+ type: "input_strip",
3518
+ name: "INPUT STRIP",
3519
+ position: [-10, 0, 0],
3520
+ color: "#f59e0b",
3521
+ radius: 1.8,
3522
+ label: "Landmark [0]",
3523
+ active: true
3524
+ },
3525
+ {
3526
+ id: "output-strip-node",
3527
+ type: "output_strip",
3528
+ name: "OUTPUT STRIP",
3529
+ position: [10, 0, 0],
3530
+ color: "#10b981",
3531
+ radius: 1.8,
3532
+ label: "Landmark [1]",
3533
+ active: true
3534
+ },
3535
+ {
3536
+ id: "cont-boom",
3537
+ type: "container",
3538
+ containerType: "audio",
3539
+ name: "808 Sub Kick",
3540
+ position: [1, 2, 0],
3541
+ color: "#f43f5e",
3542
+ radius: 1.6,
3543
+ isLooping: true,
3544
+ audioTrack: {
3545
+ id: "track-boom",
3546
+ name: "808 Sub Boom",
3547
+ sampleType: "custom",
3548
+ customAudioUrl: `/graphs/${songId}/assets/audio/stereo/default/808_sub_boom.wav`,
3549
+ durationBeats: 4,
3550
+ gain: 1,
3551
+ pan: 0,
3552
+ pitchShift: 0,
3553
+ filterCutoff: 8e3,
3554
+ fadeInBeats: 0,
3555
+ fadeOutBeats: 0,
3556
+ trimStartBeats: 0,
3557
+ trimEndBeats: 4,
3558
+ isReversed: false
3559
+ }
3560
+ }
3561
+ ],
3562
+ [
3563
+ { id: "conn-song-1", fromNodeId: "cont-boom", toNodeId: "output-strip-node", fromPort: "audio_out", toPort: "in-map-out-audio-master", latencyBeats: 0 }
3564
+ ],
3565
+ [introId]
3566
+ );
3567
+ const perfId = "live-performance-rig";
3568
+ createInitialGraphPackageSync(
3569
+ perfId,
3570
+ "Live Performance Matrix",
3571
+ "Real-time stage performance rig with responsive controls and pads",
3572
+ "performance",
3573
+ 128,
3574
+ 0.9,
3575
+ "autumn_highlands",
3576
+ [
3577
+ {
3578
+ id: "input-strip-node",
3579
+ type: "input_strip",
3580
+ name: "INPUT STRIP",
3581
+ position: [-10, 0, 0],
3582
+ color: "#f59e0b",
3583
+ radius: 1.8,
3584
+ label: "Landmark [0]",
3585
+ active: true
3586
+ },
3587
+ {
3588
+ id: "output-strip-node",
3589
+ type: "output_strip",
3590
+ name: "OUTPUT STRIP",
3591
+ position: [10, 0, 0],
3592
+ color: "#10b981",
3593
+ radius: 1.8,
3594
+ label: "Landmark [1]",
3595
+ active: true
3596
+ },
3597
+ {
3598
+ id: "ctrl-1",
3599
+ type: "control",
3600
+ name: "Stage Macro Console",
3601
+ position: [0, 0, 0],
3602
+ color: "#10b981",
3603
+ radius: 2,
3604
+ label: "Live Controller",
3605
+ active: true,
3606
+ isEditMode: false,
3607
+ gridColumns: 12,
3608
+ gridRows: 8,
3609
+ elements: []
3610
+ }
3611
+ ],
3612
+ [
3613
+ { id: "conn-perf-1", fromNodeId: "ctrl-1", toNodeId: "output-strip-node", latencyBeats: 0 }
3614
+ ],
3615
+ [songId]
3616
+ );
3617
+ }
3618
+ function createInitialGraphPackageSync(id, name, description, type, bpm, masterVolume, currentBiome, nodes, connections, importedGraphIds = []) {
3619
+ const graphDir = path5.join(GRAPHS_ROOT2, id);
3620
+ if (!fs5.existsSync(graphDir)) {
3621
+ fs5.mkdirSync(graphDir, { recursive: true });
3622
+ }
3623
+ ensureGraphAssetDirectories(graphDir);
3624
+ seedStarterGraphAssets(graphDir);
3625
+ const metadata = {
3626
+ id,
3627
+ name,
3628
+ description,
3629
+ type,
3630
+ version: "1.0.0",
3631
+ folderPath: `workspaces/default/graphs/${id}`,
3632
+ entryFile: "graph.qms",
3633
+ createdAt: Date.now(),
3634
+ updatedAt: Date.now(),
3635
+ importedGraphIds,
3636
+ bpm,
3637
+ masterVolume,
3638
+ currentBiome,
3639
+ nodeCount: nodes.length,
3640
+ assetCount: 6
3641
+ };
3642
+ const graphPackage = {
3643
+ format: "qms_graph_package",
3644
+ version: "2.0.0",
3645
+ metadata,
3646
+ graph: {
3647
+ bpm,
3648
+ masterVolume,
3649
+ currentBiome,
3650
+ nodes,
3651
+ connections
3652
+ }
3653
+ };
3654
+ fs5.writeFileSync(path5.join(graphDir, "graph.qms"), JSON.stringify(graphPackage, null, 2), "utf-8");
3655
+ }
3656
+ async function listAllGraphPackages() {
3657
+ ensureWorkspaceStructure();
3658
+ const dirs = await fs5.promises.readdir(GRAPHS_ROOT2);
3659
+ const packages = [];
3660
+ for (const dir of dirs) {
3661
+ const graphDir = path5.join(GRAPHS_ROOT2, dir);
3662
+ const stat = await fs5.promises.stat(graphDir);
3663
+ if (!stat.isDirectory()) continue;
3664
+ const qmsFile = path5.join(graphDir, "graph.qms");
3665
+ const legacyProjectFile = path5.join(graphDir, "project.json");
3666
+ let packageData = null;
3667
+ if (fs5.existsSync(qmsFile)) {
3668
+ try {
3669
+ const raw = await fs5.promises.readFile(qmsFile, "utf-8");
3670
+ packageData = JSON.parse(raw);
3671
+ } catch (err) {
3672
+ console.warn(`Corrupted graph.qms in ${dir}:`, err);
3673
+ }
3674
+ } else if (fs5.existsSync(legacyProjectFile)) {
3675
+ try {
3676
+ const raw = await fs5.promises.readFile(legacyProjectFile, "utf-8");
3677
+ const legacy = JSON.parse(raw);
3678
+ packageData = {
3679
+ format: "qms_graph_package",
3680
+ version: "2.0.0",
3681
+ metadata: {
3682
+ id: legacy.id || dir,
3683
+ name: legacy.name || dir,
3684
+ description: legacy.description || "",
3685
+ type: legacy.type || "song",
3686
+ version: "1.0.0",
3687
+ folderPath: `workspaces/default/graphs/${dir}`,
3688
+ entryFile: "graph.qms",
3689
+ createdAt: legacy.createdAt || stat.birthtimeMs,
3690
+ updatedAt: legacy.updatedAt || stat.mtimeMs,
3691
+ importedGraphIds: legacy.importedGraphIds || [],
3692
+ bpm: legacy.bpm || 120,
3693
+ masterVolume: legacy.masterVolume ?? 0.85,
3694
+ currentBiome: legacy.currentBiome || "verdant_forest",
3695
+ nodeCount: Array.isArray(legacy.nodes) ? legacy.nodes.length : 0
3696
+ },
3697
+ graph: {
3698
+ bpm: legacy.bpm || 120,
3699
+ masterVolume: legacy.masterVolume ?? 0.85,
3700
+ currentBiome: legacy.currentBiome || "verdant_forest",
3701
+ nodes: legacy.nodes || [],
3702
+ connections: legacy.connections || [],
3703
+ mapIoConfig: legacy.mapIoConfig
3704
+ }
3705
+ };
3706
+ await fs5.promises.writeFile(qmsFile, JSON.stringify(packageData, null, 2), "utf-8");
3707
+ } catch (err) {
3708
+ console.warn(`Failed to auto-migrate legacy project ${dir}:`, err);
3709
+ }
3710
+ }
3711
+ if (packageData && packageData.metadata) {
3712
+ packages.push({
3713
+ ...packageData.metadata,
3714
+ id: packageData.metadata.id || dir,
3715
+ name: packageData.metadata.name || dir,
3716
+ type: packageData.metadata.type || "custom",
3717
+ importedGraphIds: packageData.metadata.importedGraphIds || [],
3718
+ folderPath: `workspaces/default/graphs/${dir}`,
3719
+ entryFile: "graph.qms",
3720
+ nodeCount: Array.isArray(packageData.graph?.nodes) ? packageData.graph.nodes.length : 0
3721
+ });
3722
+ }
3723
+ }
3724
+ return packages.sort((a, b) => b.updatedAt - a.updatedAt);
3725
+ }
3726
+ async function getGraphPackageById(id) {
3727
+ ensureWorkspaceStructure();
3728
+ const safeId = path5.basename(id);
3729
+ const graphDir = path5.join(GRAPHS_ROOT2, safeId);
3730
+ const qmsFile = path5.join(graphDir, "graph.qms");
3731
+ if (!fs5.existsSync(qmsFile)) {
3732
+ const legacyProject = path5.join(LEGACY_PROJECTS_ROOT, safeId, "project.json");
3733
+ if (fs5.existsSync(legacyProject)) {
3734
+ const raw2 = await fs5.promises.readFile(legacyProject, "utf-8");
3735
+ const legacy = JSON.parse(raw2);
3736
+ return {
3737
+ format: "qms_graph_package",
3738
+ version: "2.0.0",
3739
+ metadata: {
3740
+ id: safeId,
3741
+ name: legacy.name || safeId,
3742
+ description: legacy.description || "",
3743
+ type: legacy.type || "song",
3744
+ version: "1.0.0",
3745
+ folderPath: `workspaces/default/graphs/${safeId}`,
3746
+ entryFile: "graph.qms",
3747
+ createdAt: legacy.createdAt || Date.now(),
3748
+ updatedAt: legacy.updatedAt || Date.now(),
3749
+ importedGraphIds: legacy.importedGraphIds || [],
3750
+ bpm: legacy.bpm || 120,
3751
+ masterVolume: legacy.masterVolume ?? 0.85,
3752
+ currentBiome: legacy.currentBiome || "verdant_forest",
3753
+ nodeCount: Array.isArray(legacy.nodes) ? legacy.nodes.length : 0
3754
+ },
3755
+ graph: {
3756
+ bpm: legacy.bpm || 120,
3757
+ masterVolume: legacy.masterVolume ?? 0.85,
3758
+ currentBiome: legacy.currentBiome || "verdant_forest",
3759
+ nodes: legacy.nodes || [],
3760
+ connections: legacy.connections || [],
3761
+ mapIoConfig: legacy.mapIoConfig
3762
+ }
3763
+ };
3764
+ }
3765
+ return null;
3766
+ }
3767
+ const raw = await fs5.promises.readFile(qmsFile, "utf-8");
3768
+ return JSON.parse(raw);
3769
+ }
3770
+ async function createGraphPackage(params) {
3771
+ ensureWorkspaceStructure();
3772
+ const name = params.name.trim();
3773
+ const safeSlug = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/-+/g, "-");
3774
+ const id = `${safeSlug}-${Date.now().toString(36)}`;
3775
+ const graphDir = path5.join(GRAPHS_ROOT2, id);
3776
+ await fs5.promises.mkdir(graphDir, { recursive: true });
3777
+ await ensureGraphAssetDirectories(graphDir);
3778
+ seedStarterGraphAssets(graphDir);
3779
+ const now = Date.now();
3780
+ const graphType = params.type || "song";
3781
+ const metadata = {
3782
+ id,
3783
+ name,
3784
+ description: params.description || `Self-contained ${graphType} package`,
3785
+ type: graphType,
3786
+ customTypeTag: params.customTypeTag,
3787
+ version: "1.0.0",
3788
+ folderPath: `workspaces/default/graphs/${id}`,
3789
+ entryFile: "graph.qms",
3790
+ createdAt: now,
3791
+ updatedAt: now,
3792
+ importedGraphIds: params.importedGraphIds || [],
3793
+ bpm: params.bpm || 120,
3794
+ masterVolume: params.masterVolume ?? 0.85,
3795
+ currentBiome: params.currentBiome || "verdant_forest",
3796
+ nodeCount: params.nodes?.length || 0,
3797
+ assetCount: 0
3798
+ };
3799
+ const graphPackage = {
3800
+ format: "qms_graph_package",
3801
+ version: "2.0.0",
3802
+ metadata,
3803
+ graph: {
3804
+ bpm: params.bpm || 120,
3805
+ masterVolume: params.masterVolume ?? 0.85,
3806
+ currentBiome: params.currentBiome || "verdant_forest",
3807
+ nodes: params.nodes || [],
3808
+ connections: params.connections || []
3809
+ }
3810
+ };
3811
+ await fs5.promises.writeFile(
3812
+ path5.join(graphDir, "graph.qms"),
3813
+ JSON.stringify(graphPackage, null, 2),
3814
+ "utf-8"
3815
+ );
3816
+ return graphPackage;
3817
+ }
3818
+ async function saveGraphPackage(id, payload) {
3819
+ ensureWorkspaceStructure();
3820
+ const safeId = path5.basename(id);
3821
+ const graphDir = path5.join(GRAPHS_ROOT2, safeId);
3822
+ if (!fs5.existsSync(graphDir)) {
3823
+ await fs5.promises.mkdir(graphDir, { recursive: true });
3824
+ await ensureGraphAssetDirectories(graphDir);
3825
+ }
3826
+ const existing = await getGraphPackageById(safeId);
3827
+ const now = Date.now();
3828
+ const metadata = {
3829
+ id: safeId,
3830
+ name: payload.name || existing?.metadata?.name || safeId,
3831
+ description: payload.description !== void 0 ? payload.description : existing?.metadata?.description || "",
3832
+ type: payload.type || existing?.metadata?.type || "custom",
3833
+ customTypeTag: payload.customTypeTag || existing?.metadata?.customTypeTag,
3834
+ version: existing?.metadata?.version || "1.0.0",
3835
+ folderPath: `workspaces/default/graphs/${safeId}`,
3836
+ entryFile: "graph.qms",
3837
+ createdAt: existing?.metadata?.createdAt || now,
3838
+ updatedAt: now,
3839
+ importedGraphIds: payload.importedGraphIds || existing?.metadata?.importedGraphIds || [],
3840
+ bpm: payload.bpm ?? existing?.graph?.bpm ?? 120,
3841
+ masterVolume: payload.masterVolume ?? existing?.graph?.masterVolume ?? 0.85,
3842
+ currentBiome: payload.currentBiome ?? existing?.graph?.currentBiome ?? "verdant_forest",
3843
+ nodeCount: payload.nodes?.length ?? existing?.graph?.nodes?.length ?? 0
3844
+ };
3845
+ const graphPackage = {
3846
+ format: "qms_graph_package",
3847
+ version: "2.0.0",
3848
+ metadata,
3849
+ graph: {
3850
+ bpm: metadata.bpm,
3851
+ masterVolume: metadata.masterVolume ?? 0.85,
3852
+ currentBiome: metadata.currentBiome || "verdant_forest",
3853
+ nodes: payload.nodes || existing?.graph?.nodes || [],
3854
+ connections: payload.connections || existing?.graph?.connections || [],
3855
+ mapIoConfig: payload.mapIoConfig || existing?.graph?.mapIoConfig
3856
+ }
3857
+ };
3858
+ await fs5.promises.writeFile(
3859
+ path5.join(graphDir, "graph.qms"),
3860
+ JSON.stringify(graphPackage, null, 2),
3861
+ "utf-8"
3862
+ );
3863
+ return graphPackage;
3864
+ }
3865
+ async function deleteGraphPackage(id) {
3866
+ const safeId = path5.basename(id);
3867
+ const graphDir = path5.join(GRAPHS_ROOT2, safeId);
3868
+ if (!fs5.existsSync(graphDir)) return false;
3869
+ await fs5.promises.rm(graphDir, { recursive: true, force: true });
3870
+ return true;
3871
+ }
3872
+ async function importGraphDependency(targetGraphId, candidateImportId) {
3873
+ const allPackages = await listAllGraphPackages();
3874
+ const graphMap = {};
3875
+ for (const pkg of allPackages) {
3876
+ graphMap[pkg.id] = {
3877
+ id: pkg.id,
3878
+ name: pkg.name,
3879
+ importedGraphIds: pkg.importedGraphIds || []
3880
+ };
3881
+ }
3882
+ const validation = validateGraphImport(graphMap, targetGraphId, candidateImportId);
3883
+ if (!validation.valid) {
3884
+ return { success: false, error: validation.error };
3885
+ }
3886
+ const targetPkg = await getGraphPackageById(targetGraphId);
3887
+ if (!targetPkg) {
3888
+ return { success: false, error: `Target graph '${targetGraphId}' not found.` };
3889
+ }
3890
+ const updatedImportIds = Array.from(
3891
+ /* @__PURE__ */ new Set([...targetPkg.metadata.importedGraphIds || [], candidateImportId])
3892
+ );
3893
+ const updatedPkg = await saveGraphPackage(targetGraphId, {
3894
+ importedGraphIds: updatedImportIds
3895
+ });
3896
+ return { success: true, metadata: updatedPkg.metadata };
3897
+ }
3898
+ async function removeGraphDependency(targetGraphId, importIdToRemove) {
3899
+ const targetPkg = await getGraphPackageById(targetGraphId);
3900
+ if (!targetPkg) return { success: false };
3901
+ const updatedImportIds = (targetPkg.metadata.importedGraphIds || []).filter(
3902
+ (id) => id !== importIdToRemove
3903
+ );
3904
+ const updatedPkg = await saveGraphPackage(targetGraphId, {
3905
+ importedGraphIds: updatedImportIds
3906
+ });
3907
+ return { success: true, metadata: updatedPkg.metadata };
3908
+ }
3909
+
3910
+ // src/server/services/projectService.ts
3911
+ import fs6 from "fs";
3912
+ import path6 from "path";
3913
+ var PROJECTS_ROOT2 = path6.join(process.cwd(), "projects");
3914
+ var customStarterProjectTemplate = null;
3915
+ function configureStarterProjectTemplate(template) {
3916
+ customStarterProjectTemplate = template;
3917
+ }
3918
+ function ensureProjectsRoot(starterTemplate) {
3919
+ if (!fs6.existsSync(PROJECTS_ROOT2)) {
3920
+ fs6.mkdirSync(PROJECTS_ROOT2, { recursive: true });
3921
+ }
3922
+ const template = starterTemplate || customStarterProjectTemplate;
3923
+ if (template && template.id) {
3924
+ const defaultProjDir = path6.join(PROJECTS_ROOT2, String(template.id));
3925
+ if (!fs6.existsSync(defaultProjDir)) {
3926
+ fs6.mkdirSync(defaultProjDir, { recursive: true });
3927
+ fs6.mkdirSync(path6.join(defaultProjDir, "samples"), { recursive: true });
3928
+ fs6.mkdirSync(path6.join(defaultProjDir, "assets"), { recursive: true });
3929
+ fs6.writeFileSync(
3930
+ path6.join(defaultProjDir, "project.json"),
3931
+ JSON.stringify({ ...template, createdAt: Date.now(), updatedAt: Date.now() }, null, 2),
3932
+ "utf-8"
3933
+ );
3934
+ }
3935
+ }
3936
+ }
3937
+ async function listAllProjects() {
3938
+ ensureProjectsRoot();
3939
+ const dirs = await fs6.promises.readdir(PROJECTS_ROOT2);
3940
+ const projects = [];
3941
+ for (const dir of dirs) {
3942
+ const projDir = path6.join(PROJECTS_ROOT2, dir);
3943
+ const stat = await fs6.promises.stat(projDir);
3944
+ if (!stat.isDirectory()) continue;
3945
+ const projectFile = path6.join(projDir, "project.json");
3946
+ const samplesDir = path6.join(projDir, "samples");
3947
+ let sampleCount = 0;
3948
+ if (fs6.existsSync(samplesDir)) {
3949
+ const samples = await fs6.promises.readdir(samplesDir);
3950
+ sampleCount = samples.filter((f) => !f.startsWith(".")).length;
3951
+ }
3952
+ if (fs6.existsSync(projectFile)) {
3953
+ try {
3954
+ const raw = await fs6.promises.readFile(projectFile, "utf-8");
3955
+ const data = JSON.parse(raw);
3956
+ projects.push({
3957
+ id: data.id || dir,
3958
+ name: data.name || dir,
3959
+ description: data.description || "",
3960
+ folderPath: `projects/${dir}`,
3961
+ createdAt: data.createdAt || stat.birthtimeMs,
3962
+ updatedAt: data.updatedAt || stat.mtimeMs,
3963
+ sampleCount,
3964
+ nodeCount: Array.isArray(data.nodes) ? data.nodes.length : 0,
3965
+ bpm: data.bpm || 120
3966
+ });
3967
+ } catch {
3968
+ }
3969
+ }
3970
+ }
3971
+ return projects.sort((a, b) => b.updatedAt - a.updatedAt);
3972
+ }
3973
+ async function getProjectById(id) {
3974
+ const safeId = path6.basename(id);
3975
+ const projectFile = path6.join(PROJECTS_ROOT2, safeId, "project.json");
3976
+ if (!fs6.existsSync(projectFile)) return null;
3977
+ const raw = await fs6.promises.readFile(projectFile, "utf-8");
3978
+ return JSON.parse(raw);
3979
+ }
3980
+ async function saveProject(id, payload) {
3981
+ const safeId = path6.basename(id);
3982
+ const projDir = path6.join(PROJECTS_ROOT2, safeId);
3983
+ const projectFile = path6.join(projDir, "project.json");
3984
+ if (!fs6.existsSync(projDir)) {
3985
+ await fs6.promises.mkdir(projDir, { recursive: true });
3986
+ await fs6.promises.mkdir(path6.join(projDir, "samples"), { recursive: true });
3987
+ await fs6.promises.mkdir(path6.join(projDir, "assets"), { recursive: true });
3988
+ }
3989
+ let existingData = {};
3990
+ if (fs6.existsSync(projectFile)) {
3991
+ const raw = await fs6.promises.readFile(projectFile, "utf-8");
3992
+ existingData = JSON.parse(raw);
3993
+ }
3994
+ const updatedData = {
3995
+ ...existingData,
3996
+ ...payload,
3997
+ id: safeId,
3998
+ updatedAt: Date.now()
3999
+ };
4000
+ await fs6.promises.writeFile(projectFile, JSON.stringify(updatedData, null, 2), "utf-8");
4001
+ return updatedData;
4002
+ }
4003
+ async function deleteProject(id) {
4004
+ const safeId = path6.basename(id);
4005
+ const projDir = path6.join(PROJECTS_ROOT2, safeId);
4006
+ if (!fs6.existsSync(projDir)) return false;
4007
+ await fs6.promises.rm(projDir, { recursive: true, force: true });
4008
+ return true;
4009
+ }
4010
+
4011
+ // src/server/services/sampleService.ts
4012
+ import fs7 from "fs";
4013
+ import path7 from "path";
4014
+ var SAMPLES_GLOBAL_ROOT = path7.join(process.cwd(), "samples", "global");
4015
+ var PROJECTS_ROOT3 = path7.join(process.cwd(), "projects");
4016
+ var SUPPORTED_AUDIO_EXTS3 = [".wav", ".mp3", ".ogg", ".flac", ".m4a", ".webm", ".weba", ".aac", ".aiff", ".aif", ".opus", ".mp4"];
4017
+ function initGlobalSamplesDirectory() {
4018
+ ensureGlobalSamples(SAMPLES_GLOBAL_ROOT).catch((err) => {
4019
+ console.error("Error ensuring global samples:", err);
4020
+ });
4021
+ }
4022
+ async function listGlobalSamples() {
4023
+ if (!fs7.existsSync(SAMPLES_GLOBAL_ROOT)) {
4024
+ await fs7.promises.mkdir(SAMPLES_GLOBAL_ROOT, { recursive: true });
4025
+ }
4026
+ const files = await fs7.promises.readdir(SAMPLES_GLOBAL_ROOT);
4027
+ const samples = [];
4028
+ for (const file of files) {
4029
+ const ext = path7.extname(file).toLowerCase();
4030
+ if (!SUPPORTED_AUDIO_EXTS3.includes(ext)) continue;
4031
+ const filePath = path7.join(SAMPLES_GLOBAL_ROOT, file);
4032
+ const stat = await fs7.promises.stat(filePath);
4033
+ const baseName = path7.basename(file, ext);
4034
+ const cleanName = baseName.replace(/[-_]/g, " ");
4035
+ let category = "synth";
4036
+ if (/808|kick|snare|hihat|drum|perc/i.test(baseName)) category = "drums";
4037
+ else if (/pad|drone|ethereal|ambient|forest/i.test(baseName)) category = "ambient";
4038
+ else if (/warp|riser|zap|fx|impact/i.test(baseName)) category = "fx";
4039
+ samples.push({
4040
+ filename: file,
4041
+ name: cleanName.charAt(0).toUpperCase() + cleanName.slice(1),
4042
+ category,
4043
+ format: ext.replace(".", "").toUpperCase(),
4044
+ url: `/samples/global/${file}`,
4045
+ size: stat.size,
4046
+ scope: "global",
4047
+ createdAt: stat.birthtimeMs || stat.mtimeMs
4048
+ });
4049
+ }
4050
+ return samples;
4051
+ }
4052
+ async function saveGlobalSample(filename, base64Content, category) {
4053
+ const safeFilename = path7.basename(filename).replace(/[^a-zA-Z0-9._-]/g, "_");
4054
+ const ext = path7.extname(safeFilename).toLowerCase() || ".wav";
4055
+ const filePath = path7.join(SAMPLES_GLOBAL_ROOT, safeFilename);
4056
+ const buffer = Buffer.from(base64Content, "base64");
4057
+ await fs7.promises.writeFile(filePath, buffer);
4058
+ const stat = await fs7.promises.stat(filePath);
4059
+ return {
4060
+ filename: safeFilename,
4061
+ name: path7.basename(safeFilename, ext).replace(/[-_]/g, " "),
4062
+ category: category || "custom",
4063
+ format: ext.replace(".", "").toUpperCase(),
4064
+ url: `/samples/global/${safeFilename}`,
4065
+ size: stat.size,
4066
+ scope: "global",
4067
+ createdAt: stat.birthtimeMs || stat.mtimeMs
4068
+ };
4069
+ }
4070
+ async function deleteGlobalSample(filename) {
4071
+ const safeFilename = path7.basename(filename);
4072
+ const filePath = path7.join(SAMPLES_GLOBAL_ROOT, safeFilename);
4073
+ if (fs7.existsSync(filePath)) {
4074
+ await fs7.promises.unlink(filePath);
4075
+ return true;
4076
+ }
4077
+ return false;
4078
+ }
4079
+ async function listProjectSamples(projectId) {
4080
+ const safeId = path7.basename(projectId);
4081
+ const samplesDir = path7.join(PROJECTS_ROOT3, safeId, "samples");
4082
+ if (!fs7.existsSync(samplesDir)) {
4083
+ await fs7.promises.mkdir(samplesDir, { recursive: true });
4084
+ }
4085
+ const files = await fs7.promises.readdir(samplesDir);
4086
+ const samples = [];
4087
+ for (const file of files) {
4088
+ const ext = path7.extname(file).toLowerCase();
4089
+ if (!SUPPORTED_AUDIO_EXTS3.includes(ext)) continue;
4090
+ const filePath = path7.join(samplesDir, file);
4091
+ const stat = await fs7.promises.stat(filePath);
4092
+ const baseName = path7.basename(file, ext);
4093
+ samples.push({
4094
+ filename: file,
4095
+ name: baseName.replace(/[-_]/g, " "),
4096
+ category: "project_recording",
4097
+ format: ext.replace(".", "").toUpperCase(),
4098
+ url: `/projects/${safeId}/samples/${file}`,
4099
+ size: stat.size,
4100
+ scope: "project",
4101
+ projectId: safeId,
4102
+ createdAt: stat.birthtimeMs || stat.mtimeMs
4103
+ });
4104
+ }
4105
+ return samples;
4106
+ }
4107
+ async function saveProjectSample(projectId, filename, base64Content, isRecording) {
4108
+ const safeId = path7.basename(projectId);
4109
+ const samplesDir = path7.join(PROJECTS_ROOT3, safeId, "samples");
4110
+ if (!fs7.existsSync(samplesDir)) {
4111
+ await fs7.promises.mkdir(samplesDir, { recursive: true });
4112
+ }
4113
+ const defaultName = isRecording ? `recording_take_${Date.now()}.wav` : `clip_${Date.now()}.wav`;
4114
+ const targetFilename = filename ? path7.basename(filename).replace(/[^a-zA-Z0-9._-]/g, "_") : defaultName;
4115
+ const ext = path7.extname(targetFilename).toLowerCase() || ".wav";
4116
+ const filePath = path7.join(samplesDir, targetFilename);
4117
+ const buffer = Buffer.from(base64Content, "base64");
4118
+ await fs7.promises.writeFile(filePath, buffer);
4119
+ const stat = await fs7.promises.stat(filePath);
4120
+ return {
4121
+ filename: targetFilename,
4122
+ name: path7.basename(targetFilename, ext).replace(/[-_]/g, " "),
4123
+ category: isRecording ? "recording" : "import",
4124
+ format: ext.replace(".", "").toUpperCase(),
4125
+ url: `/projects/${safeId}/samples/${targetFilename}`,
4126
+ size: stat.size,
4127
+ scope: "project",
4128
+ projectId: safeId,
4129
+ createdAt: stat.birthtimeMs || stat.mtimeMs
4130
+ };
4131
+ }
4132
+ async function deleteProjectSample(projectId, filename) {
4133
+ const safeId = path7.basename(projectId);
4134
+ const safeFilename = path7.basename(filename);
4135
+ const filePath = path7.join(PROJECTS_ROOT3, safeId, "samples", safeFilename);
4136
+ if (fs7.existsSync(filePath)) {
4137
+ await fs7.promises.unlink(filePath);
4138
+ return true;
4139
+ }
4140
+ return false;
4141
+ }
4142
+
4143
+ // src/server/services/workspaceGraphService.ts
4144
+ import fs8 from "fs";
4145
+ import path8 from "path";
4146
+ var AUTH_FILE_PATH = path8.resolve(".skipo/accounts.json");
4147
+ async function resolveWorkspaceDir(workspaceIdOrSlug) {
4148
+ const workingDir = getWorkingWorkspaceDir();
4149
+ let targetWs = null;
4150
+ try {
4151
+ if (fs8.existsSync(AUTH_FILE_PATH)) {
4152
+ const raw = await fs8.promises.readFile(AUTH_FILE_PATH, "utf-8");
4153
+ const accounts = JSON.parse(raw);
4154
+ for (const user of Object.values(accounts)) {
4155
+ if (Array.isArray(user.workspaces)) {
4156
+ const found = user.workspaces.find(
4157
+ (w) => w.id === workspaceIdOrSlug || w.name?.toLowerCase() === workspaceIdOrSlug?.toLowerCase() || w.localFolderName?.toLowerCase() === workspaceIdOrSlug?.toLowerCase()
4158
+ );
4159
+ if (found) {
4160
+ targetWs = found;
4161
+ break;
4162
+ }
4163
+ }
4164
+ }
4165
+ }
4166
+ } catch (err) {
4167
+ console.warn("Error reading accounts for workspace resolution:", err);
4168
+ }
4169
+ if (targetWs) {
4170
+ const rawFolderName = targetWs.localFolderName || targetWs.name.replace(/[/\\?%*:|"<>]/g, "_");
4171
+ const folderName = rawFolderName.trim();
4172
+ await fs8.promises.mkdir(workingDir, { recursive: true });
4173
+ return { wsDir: workingDir, wsName: targetWs.name, wsFolder: folderName, wsId: targetWs.id };
4174
+ }
4175
+ await fs8.promises.mkdir(workingDir, { recursive: true });
4176
+ return { wsDir: workingDir, wsName: "Active Workspace", wsFolder: "workspace", wsId: workspaceIdOrSlug || "default" };
4177
+ }
4178
+ async function listWorkspaceGraphs(workspaceIdOrSlug) {
4179
+ const { wsDir, wsFolder } = await resolveWorkspaceDir(workspaceIdOrSlug);
4180
+ const graphs = [];
4181
+ const inspectDirForGraph = async (dirPath, folderName) => {
4182
+ const projectJson = path8.join(dirPath, "project.json");
4183
+ const graphQms = path8.join(dirPath, "graph.qms");
4184
+ let data = null;
4185
+ if (fs8.existsSync(projectJson)) {
4186
+ try {
4187
+ const raw = await fs8.promises.readFile(projectJson, "utf-8");
4188
+ data = JSON.parse(raw);
4189
+ } catch {
4190
+ }
4191
+ } else if (fs8.existsSync(graphQms)) {
4192
+ try {
4193
+ const raw = await fs8.promises.readFile(graphQms, "utf-8");
4194
+ const pkg = JSON.parse(raw);
4195
+ data = { ...pkg.metadata || {}, ...pkg.graph || {} };
4196
+ } catch {
4197
+ }
4198
+ }
4199
+ if (!data) return null;
4200
+ const stat = await fs8.promises.stat(dirPath);
4201
+ const nodeCount = Array.isArray(data.nodes) ? data.nodes.length : 0;
4202
+ const connectionCount = Array.isArray(data.connections) ? data.connections.length : 0;
4203
+ return {
4204
+ id: data.id || folderName,
4205
+ name: data.name || folderName,
4206
+ description: data.description || "",
4207
+ folderName,
4208
+ folderPath: path8.relative(process.cwd(), dirPath).replace(/\\/g, "/"),
4209
+ createdAt: data.createdAt || stat.birthtimeMs,
4210
+ updatedAt: data.updatedAt || stat.mtimeMs,
4211
+ bpm: data.bpm || 120,
4212
+ masterVolume: data.masterVolume ?? 0.85,
4213
+ currentBiome: data.currentBiome || "verdant_forest",
4214
+ nodes: data.nodes || [],
4215
+ connections: data.connections || [],
4216
+ mapIoConfig: data.mapIoConfig,
4217
+ nodeCount,
4218
+ connectionCount
4219
+ };
4220
+ };
4221
+ const entries = await fs8.promises.readdir(wsDir);
4222
+ for (const entry of entries) {
4223
+ if (entry.startsWith(".") || entry === "samples" || entry === "assets") continue;
4224
+ const fullPath = path8.join(wsDir, entry);
4225
+ const stat = await fs8.promises.stat(fullPath);
4226
+ if (!stat.isDirectory()) continue;
4227
+ if (entry === "graphs") {
4228
+ const subEntries = await fs8.promises.readdir(fullPath);
4229
+ for (const sub of subEntries) {
4230
+ if (sub.startsWith(".")) continue;
4231
+ const subPath = path8.join(fullPath, sub);
4232
+ const subStat = await fs8.promises.stat(subPath);
4233
+ if (subStat.isDirectory()) {
4234
+ const g2 = await inspectDirForGraph(subPath, sub);
4235
+ if (g2) graphs.push(g2);
4236
+ }
4237
+ }
4238
+ continue;
4239
+ }
4240
+ const g = await inspectDirForGraph(fullPath, entry);
4241
+ if (g) graphs.push(g);
4242
+ }
4243
+ return graphs.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
4244
+ }
4245
+ async function createWorkspaceGraph(workspaceIdOrSlug, params) {
4246
+ const { wsDir, wsFolder, wsId } = await resolveWorkspaceDir(workspaceIdOrSlug);
4247
+ const rawName = params.name.trim();
4248
+ const folderName = rawName.replace(/[/\\?%*:|"<>]/g, "_");
4249
+ const graphDir = path8.join(wsDir, folderName);
4250
+ await fs8.promises.mkdir(graphDir, { recursive: true });
4251
+ await fs8.promises.mkdir(path8.join(graphDir, "samples"), { recursive: true });
4252
+ await fs8.promises.mkdir(path8.join(graphDir, "assets"), { recursive: true });
4253
+ const now = Date.now();
4254
+ const nodes = params.templateData?.nodes || [];
4255
+ const connections = params.templateData?.connections || [];
4256
+ const bpm = params.templateData?.bpm || params.bpm || 120;
4257
+ const masterVolume = params.templateData?.masterVolume ?? params.masterVolume ?? 0.85;
4258
+ const currentBiome = params.templateData?.currentBiome || params.currentBiome || "verdant_forest";
4259
+ const projectData = {
4260
+ id: folderName,
4261
+ name: rawName,
4262
+ description: params.description || `Workspace graph in ${wsFolder}`,
4263
+ folderPath: path8.relative(process.cwd(), graphDir).replace(/\\/g, "/"),
4264
+ createdAt: now,
4265
+ updatedAt: now,
4266
+ bpm,
4267
+ masterVolume,
4268
+ currentBiome,
4269
+ nodes,
4270
+ connections
4271
+ };
4272
+ await fs8.promises.writeFile(path8.join(graphDir, "project.json"), JSON.stringify(projectData, null, 2), "utf-8");
4273
+ const graphPackage = {
4274
+ format: "qms_graph_package",
4275
+ version: "2.0.0",
4276
+ metadata: {
4277
+ id: folderName,
4278
+ name: rawName,
4279
+ description: projectData.description,
4280
+ folderPath: projectData.folderPath,
4281
+ createdAt: now,
4282
+ updatedAt: now,
4283
+ nodeCount: nodes.length,
4284
+ bpm,
4285
+ masterVolume,
4286
+ currentBiome
4287
+ },
4288
+ graph: { bpm, masterVolume, currentBiome, nodes, connections }
4289
+ };
4290
+ await fs8.promises.writeFile(path8.join(graphDir, "graph.qms"), JSON.stringify(graphPackage, null, 2), "utf-8");
4291
+ return projectData;
4292
+ }
4293
+ async function getWorkspaceGraph(workspaceIdOrSlug, graphIdOrName) {
4294
+ const { wsDir } = await resolveWorkspaceDir(workspaceIdOrSlug);
4295
+ const safeTarget = graphIdOrName.replace(/[/\\?%*:|"<>]/g, "_");
4296
+ const candidates = [
4297
+ path8.join(wsDir, safeTarget),
4298
+ path8.join(wsDir, graphIdOrName),
4299
+ path8.join(wsDir, "graphs", safeTarget)
4300
+ ];
4301
+ for (const cand of candidates) {
4302
+ if (fs8.existsSync(cand)) {
4303
+ const pJson = path8.join(cand, "project.json");
4304
+ if (fs8.existsSync(pJson)) {
4305
+ const raw = await fs8.promises.readFile(pJson, "utf-8");
4306
+ return JSON.parse(raw);
4307
+ }
4308
+ const gQms = path8.join(cand, "graph.qms");
4309
+ if (fs8.existsSync(gQms)) {
4310
+ const raw = await fs8.promises.readFile(gQms, "utf-8");
4311
+ const pkg = JSON.parse(raw);
4312
+ return { ...pkg.metadata || {}, ...pkg.graph || {} };
4313
+ }
4314
+ }
4315
+ }
4316
+ return null;
4317
+ }
4318
+ async function saveWorkspaceGraph(workspaceIdOrSlug, graphIdOrName, payload) {
4319
+ const { wsDir } = await resolveWorkspaceDir(workspaceIdOrSlug);
4320
+ const safeTarget = graphIdOrName.replace(/[/\\?%*:|"<>]/g, "_");
4321
+ let targetDir = path8.join(wsDir, safeTarget);
4322
+ if (!fs8.existsSync(targetDir) && fs8.existsSync(path8.join(wsDir, "graphs", safeTarget))) {
4323
+ targetDir = path8.join(wsDir, "graphs", safeTarget);
4324
+ }
4325
+ await fs8.promises.mkdir(targetDir, { recursive: true });
4326
+ const pJson = path8.join(targetDir, "project.json");
4327
+ let existing = {};
4328
+ if (fs8.existsSync(pJson)) {
4329
+ try {
4330
+ existing = JSON.parse(await fs8.promises.readFile(pJson, "utf-8"));
4331
+ } catch {
4332
+ }
4333
+ }
4334
+ const updated = {
4335
+ ...existing,
4336
+ ...payload,
4337
+ id: existing.id || path8.basename(targetDir),
4338
+ updatedAt: Date.now()
4339
+ };
4340
+ await fs8.promises.writeFile(pJson, JSON.stringify(updated, null, 2), "utf-8");
4341
+ return updated;
4342
+ }
4343
+ async function deleteWorkspaceGraph(workspaceIdOrSlug, graphIdOrName) {
4344
+ const { wsDir } = await resolveWorkspaceDir(workspaceIdOrSlug);
4345
+ const safeTarget = graphIdOrName.replace(/[/\\?%*:|"<>]/g, "_");
4346
+ const candidates = [
4347
+ path8.join(wsDir, safeTarget),
4348
+ path8.join(wsDir, graphIdOrName),
4349
+ path8.join(wsDir, "graphs", safeTarget)
4350
+ ];
4351
+ for (const cand of candidates) {
4352
+ if (fs8.existsSync(cand)) {
4353
+ await fs8.promises.rm(cand, { recursive: true, force: true });
4354
+ return true;
4355
+ }
4356
+ }
4357
+ return false;
4358
+ }
4359
+
4360
+ // src/resolver/systemDatabaseUrl.ts
4361
+ function resolveSystemDatabaseUrl(env = typeof process !== "undefined" ? process.env : {}) {
4362
+ const url = env["SYSTEM_DATABASE_URL_1"] && env["SYSTEM_DATABASE_URL_1"].trim() || env["SYSTEM_DATABASE_URL_2"] && env["SYSTEM_DATABASE_URL_2"].trim() || env["SYSTEM_DATABASE_URL_3"] && env["SYSTEM_DATABASE_URL_3"].trim();
4363
+ if (!url) {
4364
+ throw new Error(
4365
+ "[SKIPO DATABASE_INVARIANT] Missing system database configuration.\n Set SYSTEM_DATABASE_URL_1 (primary), SYSTEM_DATABASE_URL_2 (fallback #1),\n or SYSTEM_DATABASE_URL_3 (fallback #2).\n Generic DATABASE_URL is obsolete and strictly forbidden in this architecture."
4366
+ );
4367
+ }
4368
+ return url;
4369
+ }
4370
+ function tryResolveSystemDatabaseUrl(env = typeof process !== "undefined" ? process.env : {}) {
4371
+ const url = env["SYSTEM_DATABASE_URL_1"] && env["SYSTEM_DATABASE_URL_1"].trim() || env["SYSTEM_DATABASE_URL_2"] && env["SYSTEM_DATABASE_URL_2"].trim() || env["SYSTEM_DATABASE_URL_3"] && env["SYSTEM_DATABASE_URL_3"].trim();
4372
+ return url || null;
4373
+ }
4374
+
4375
+ // src/development/wasmRuntimeService.ts
4376
+ import {
4377
+ createWasmRuntime
4378
+ } from "@ultrst-armada/kloks/wasm-runtime";
4379
+ import {
4380
+ createService,
4381
+ createServiceDefinition
4382
+ } from "@ultrst-armada/krnl";
4383
+ var runtime;
4384
+ async function getRuntime(options = {}) {
4385
+ runtime ??= await createWasmRuntime(options);
4386
+ return runtime;
4387
+ }
4388
+ var WasmRuntimeServiceDefinition = createServiceDefinition({
4389
+ id: "kloks.backend.wasmRuntime",
4390
+ name: "WasmRuntimeService",
4391
+ version: "1.0.0",
4392
+ operations: {
4393
+ execute: {
4394
+ id: "WasmRuntimeService.execute",
4395
+ name: "execute",
4396
+ handler: async (input) => {
4397
+ return (await getRuntime()).execute(input);
4398
+ }
4399
+ },
4400
+ dispose: {
4401
+ id: "WasmRuntimeService.dispose",
4402
+ name: "dispose",
4403
+ handler: async () => {
4404
+ runtime?.dispose();
4405
+ runtime = void 0;
4406
+ return { disposed: true };
4407
+ }
4408
+ }
4409
+ }
4410
+ });
4411
+ var WasmRuntimeServiceFacade = {
4412
+ id: WasmRuntimeServiceDefinition.id,
4413
+ name: WasmRuntimeServiceDefinition.name,
4414
+ version: WasmRuntimeServiceDefinition.version,
4415
+ definition: WasmRuntimeServiceDefinition,
4416
+ createInstance: () => createService(WasmRuntimeServiceDefinition),
4417
+ execute: async (operation, input) => {
4418
+ const instance = createService(WasmRuntimeServiceDefinition);
4419
+ await instance.start();
4420
+ return instance.call(operation, input);
4421
+ }
4422
+ };
4423
+ export {
4424
+ AIInferenceServiceDefinition,
4425
+ AIInferenceServiceFacade,
4426
+ AIKeyServiceDefinition,
4427
+ AIKeyServiceFacade,
4428
+ AIModelCatalogServiceDefinition,
4429
+ AIModelCatalogServiceFacade,
4430
+ AIProviderService,
4431
+ AIProviderServiceDefinition,
4432
+ AIProviderServiceFacade,
4433
+ AIRoutingServiceDefinition,
4434
+ AIRoutingServiceFacade,
4435
+ AIToolServiceDefinition,
4436
+ AIToolServiceFacade,
4437
+ AITransportClient,
4438
+ AuditLogger,
4439
+ AuthServiceDefinition,
4440
+ AuthServiceFacade,
4441
+ BackblazeB2Adapter,
4442
+ BackendClient,
4443
+ BackendProvider,
4444
+ BackendRegistry,
4445
+ BackendResolver,
4446
+ BaseApiRoute,
4447
+ BaseDataProvider,
4448
+ BaseResourceFetcher,
4449
+ BaseStorageAdapter,
4450
+ BucketStorageService,
4451
+ CANONICAL_SRKL_URL,
4452
+ CallbackRegistry,
4453
+ LuthAuthClient2 as CanonicalAuthClient,
4454
+ CloudflareResourceFetcher,
4455
+ CompositeBackend,
4456
+ ConcurrencyConflictError,
4457
+ ConcurrencyManager,
4458
+ ControlPlaneManager,
4459
+ ControlPlaneServiceDefinition,
4460
+ ControlPlaneServiceFacade,
4461
+ DatabaseClusterManager,
4462
+ DatabaseServiceDefinition,
4463
+ DatabaseServiceFacade,
4464
+ DeterministicEndpointExecutor,
4465
+ EndpointGenerator,
4466
+ EndpointRefresher,
4467
+ EventBus,
4468
+ FailoverExecutionEngine,
4469
+ FrontendSession,
4470
+ FunctionalityTable,
4471
+ GOOGLE_DRIVE_FILE_SCOPE,
4472
+ GOOGLE_DRIVE_STORAGE_SCOPE,
4473
+ GRAPHS_ROOT,
4474
+ GeminiServiceDefinition,
4475
+ GeminiServiceFacade,
4476
+ GoogleDriveAdapter,
4477
+ GoogleDriveStorageService,
4478
+ HTTPTransport,
4479
+ HealthCheckService,
4480
+ HealthMonitor,
4481
+ IdempotencyManager,
4482
+ InProcessExecutor,
4483
+ InferenceExecutorService,
4484
+ JobScheduler,
4485
+ KeyStoreService,
4486
+ KeysStorage,
4487
+ LEGACY_PROJECTS_ROOT,
4488
+ LOCAL_STORAGE_GRAPHS_PREFIX,
4489
+ LoadBalancer,
4490
+ LocalFSAdapter,
4491
+ LockManager,
4492
+ LuthAuthClient,
4493
+ LuthAuthError,
4494
+ MCPEngine,
4495
+ MetricsLogger,
4496
+ ModelCatalogService,
4497
+ ModelHealthService,
4498
+ NodeGraphPersistenceService,
4499
+ PROJECTS_ROOT,
4500
+ PROVIDERS_META,
4501
+ PROVIDER_COLORS,
4502
+ RemoteExecutor,
4503
+ RemoteWorkspaceService,
4504
+ ResourceFetcherRegistry,
4505
+ S3Adapter,
4506
+ SAMPLES_GLOBAL_ROOT,
4507
+ STATIC_MODELS_CATALOG,
4508
+ SUPPORTED_AUDIO_EXTS,
4509
+ SUPPORTED_MIDI_EXTS,
4510
+ SequenceTracker,
4511
+ SrklClient,
4512
+ SrklCredentialRegistry,
4513
+ SrklServiceDefinition,
4514
+ SrklServiceFacade,
4515
+ SrklStorageService,
4516
+ SrklVaultAccessClient,
4517
+ StorageAdapterFactory,
4518
+ StorageServiceDefinition,
4519
+ StorageServiceFacade,
4520
+ SupabaseStorageAdapter,
4521
+ SyncEngine,
4522
+ ToolManagerService,
4523
+ VercelResourceFetcher,
4524
+ WORKSPACE_ASSETS_ROOT,
4525
+ WORKSPACE_ROOT,
4526
+ WasmRuntimeServiceDefinition,
4527
+ WasmRuntimeServiceFacade,
4528
+ WebSocketTransport,
4529
+ WorkingWorkspaceService,
4530
+ WorkspaceCloneSyncEngine,
4531
+ WorkspaceFS,
4532
+ WorkspaceGraphServiceDefinition,
4533
+ WorkspaceGraphServiceFacade,
4534
+ WorkspaceServiceDefinition,
4535
+ WorkspaceServiceFacade,
4536
+ aiProviderService,
4537
+ authorizeB2,
4538
+ b2DeleteFileVersion,
4539
+ b2DeleteFolder,
4540
+ b2DownloadFile,
4541
+ b2ListBuckets,
4542
+ b2ListFileNames,
4543
+ b2UploadFile,
4544
+ buildProjectObservability,
4545
+ buildProjectsList,
4546
+ classifyAndFormatError,
4547
+ cleanDbUrl,
4548
+ clearLuthDiscoveryCache,
4549
+ computeDeploymentFinalWeight,
4550
+ computeUsageWeightScore,
4551
+ configureStarterProjectTemplate,
4552
+ createAssetSubfolder,
4553
+ createBackend,
4554
+ createBackendClient,
4555
+ createLuthAuthClient2 as createCanonicalAuthClient,
4556
+ createCompositeService,
4557
+ createCredential,
4558
+ createEmptyContract,
4559
+ createGoogleDriveAuthorizationUrl,
4560
+ createGraphAssetFolder,
4561
+ createGraphAssetFolder as createGraphAssetSubfolder,
4562
+ createGraphPackage,
4563
+ createLocalService,
4564
+ createLuthAuthClient,
4565
+ createRemoteService,
4566
+ createSSEResponse,
4567
+ createSrklClient,
4568
+ createWavBuffer,
4569
+ createWorkspace,
4570
+ createWorkspaceGraph,
4571
+ decryptSecretFromBlob,
4572
+ decryptVaultBufferInBrowser,
4573
+ deleteAssetFromGraph,
4574
+ deleteAssetFromPool,
4575
+ deleteCredential,
4576
+ deleteGlobalSample,
4577
+ deleteGraphPackage,
4578
+ deleteProject,
4579
+ deleteProjectSample,
4580
+ deleteRoute,
4581
+ deleteWorkspace,
4582
+ deleteWorkspaceFile,
4583
+ deleteWorkspaceFolder,
4584
+ deleteWorkspaceGraph,
4585
+ detectDatabaseEngine,
4586
+ deterministicEndpointExecutor,
4587
+ encryptSecretToBlob,
4588
+ endpointRefresher,
4589
+ ensureAssetPoolDirectories,
4590
+ ensureGlobalSamples,
4591
+ ensureGraphAssetDirectories,
4592
+ ensureProjectAssets,
4593
+ ensureProjectsRoot,
4594
+ ensureS3DirectoryMarker,
4595
+ ensureWorkspaceStructure,
4596
+ exchangeGoogleDriveCode,
4597
+ exportEncryptedCredentials,
4598
+ exportGraphAsJsonFile,
4599
+ failoverExecutionEngine,
4600
+ fetchCloudflareData,
4601
+ fetchVercelData,
4602
+ findUserWorkspace,
4603
+ findWorkspaceRecord,
4604
+ formatCanonicalWorkspaceFolderName,
4605
+ formatRelativeCreated,
4606
+ getAllRoutes,
4607
+ getAssetPoolLocationPath,
4608
+ getAssetPoolPublicUrl,
4609
+ getB2BucketId,
4610
+ getConnectedDeploymentNode,
4611
+ getConnectedWeightModifiers,
4612
+ getCredential,
4613
+ getDefaultWorkingWorkspaceDir,
4614
+ getExecutions,
4615
+ getGatewayConfig,
4616
+ getGraphPackageById,
4617
+ getNextLuthDeploymentUrl,
4618
+ getPrimaryLuthDeploymentUrl,
4619
+ getPrimarySrklDeploymentUrl2 as getPrimarySrklCoreDeploymentUrl,
4620
+ getPrimarySrklDeploymentUrl,
4621
+ getProjectById,
4622
+ getProviderMeta,
4623
+ getPublicRouteByPath,
4624
+ getPublicRoutes,
4625
+ getRegisteredLuthDeploymentUrls,
4626
+ getSrklAccounts,
4627
+ getSrklAccounts2 as getSrklCoreAccounts,
4628
+ getSrklStatus,
4629
+ getSystemDatabaseUrls,
4630
+ getUnifiedDbUrl,
4631
+ getWeightModifierScore,
4632
+ getWorkingWorkspaceConfig,
4633
+ getWorkingWorkspaceDir,
4634
+ getWorkspaceFolderKey,
4635
+ getWorkspaceFolderPrefix,
4636
+ getWorkspaceGraph,
4637
+ getWorkspaceStorageDetails,
4638
+ getWorkspaces,
4639
+ globalCredentialRegistry,
4640
+ healthCheckService,
4641
+ hexToBytes,
4642
+ importEncryptedCredentials,
4643
+ importGraphDependency,
4644
+ inferenceExecutor,
4645
+ initGlobalSamplesDirectory,
4646
+ isB2Workspace,
4647
+ isSecretMasked,
4648
+ keyStore,
4649
+ keysStorage,
4650
+ krnlAuthServiceDefinition,
4651
+ krnlAuthServiceFacade,
4652
+ krnlControlPlaneServiceDefinition,
4653
+ krnlControlPlaneServiceFacade,
4654
+ krnlDatabaseServiceDefinition,
4655
+ krnlDatabaseServiceFacade,
4656
+ krnlGeminiServiceDefinition,
4657
+ krnlGeminiServiceFacade,
4658
+ krnlSrklServiceDefinition,
4659
+ krnlSrklServiceFacade,
4660
+ krnlStorageServiceDefinition,
4661
+ krnlStorageServiceFacade,
4662
+ krnlWorkspaceGraphServiceDefinition,
4663
+ krnlWorkspaceGraphServiceFacade,
4664
+ krnlWorkspaceServiceDefinition,
4665
+ krnlWorkspaceServiceFacade,
4666
+ listAllGraphPackages,
4667
+ listAllProjects,
4668
+ listBackblazeBuckets,
4669
+ listCredentials,
4670
+ listGlobalSamples,
4671
+ listProjectSamples,
4672
+ listProviders,
4673
+ listWorkspaceFiles,
4674
+ listWorkspaceGraphs,
4675
+ loadCredentialManifest,
4676
+ loadWorkspaceData,
4677
+ loginSystemUser,
4678
+ matchGatewayIngress,
4679
+ matchGatewayIngressAsync,
4680
+ mcpEngine,
4681
+ metricsLogger,
4682
+ modelCatalog,
4683
+ modelHealthService,
4684
+ nodeGraphPersistence,
4685
+ normalizeBackblazeCredentials,
4686
+ parseErrorJson,
4687
+ parseGraphJsonFile,
4688
+ pauseCloudflarePagesProject,
4689
+ pauseVercelProject,
4690
+ performInference,
4691
+ permanentDeleteS3Folder,
4692
+ permanentDeleteS3Object,
4693
+ queryUnifiedDb,
4694
+ readWorkspaceFile,
4695
+ recordExecution,
4696
+ refreshGoogleDriveAccessToken,
4697
+ remoteWorkspaceService,
4698
+ removeGraphDependency,
4699
+ renameAppInWorkspaceData,
4700
+ renameS3Folder,
4701
+ resolveBackblazeEndpoint,
4702
+ resolveClientEnvironment,
4703
+ resolveClientOrigin,
4704
+ resolveDynamicRouteFromDb,
4705
+ resolveSystemDatabaseClusterNodes,
4706
+ resolveSystemDatabaseUrl,
4707
+ resolveUserFromToken,
4708
+ resolveWorkspaceConnection,
4709
+ resolveWorkspaceDir,
4710
+ resumeCloudflarePagesProject,
4711
+ resumeVercelProject,
4712
+ sanitizeWorkspaceName,
4713
+ saveAssetToGraph,
4714
+ saveAssetToPool,
4715
+ saveCredentialManifest,
4716
+ saveGlobalSample,
4717
+ saveGraphPackage,
4718
+ saveProject,
4719
+ saveProjectSample,
4720
+ saveWorkspaceData,
4721
+ saveWorkspaceGraph,
4722
+ scanAssetPool,
4723
+ scanGraphAssets,
4724
+ seedDefaultAssets,
4725
+ seedStarterGraphAssets,
4726
+ serverPublicRoutes,
4727
+ setServerPublicRoutes,
4728
+ setWorkingWorkspaceConfig,
4729
+ srklListBackblazeBuckets2 as srklCoreListBackblazeBuckets,
4730
+ srklListBackblazeBuckets,
4731
+ srklService,
4732
+ syncSrklAccounts,
4733
+ syncWorkspace,
4734
+ syncWorkspaceCreateToBucket,
4735
+ syncWorkspaceDataToBucket,
4736
+ syncWorkspaceDeleteToBucket,
4737
+ toolManagerService,
4738
+ tryResolveSystemDatabaseUrl,
4739
+ updateCredential,
4740
+ updateWorkspace,
4741
+ upsertRoute,
4742
+ useBackend,
4743
+ useBackendClient,
4744
+ useSrklServices,
4745
+ validateApiKey,
4746
+ validateGraphDocument,
4747
+ validateServiceDefinition,
4748
+ validateToolInput,
4749
+ withAuth,
4750
+ withCors,
4751
+ workingWorkspaceService,
4752
+ workspaceGraphService,
4753
+ writeWorkspaceFile
4754
+ };