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