@superblocksteam/vite-plugin-file-sync 2.0.59-next.2 → 2.0.59-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/dist/ai-service/agent/prompts/build-base-system-prompt.d.ts.map +1 -1
  2. package/dist/ai-service/agent/prompts/build-base-system-prompt.js +10 -1
  3. package/dist/ai-service/agent/prompts/build-base-system-prompt.js.map +1 -1
  4. package/dist/ai-service/agent/subagents/apis/examples.d.ts.map +1 -1
  5. package/dist/ai-service/agent/subagents/apis/examples.js +137 -10
  6. package/dist/ai-service/agent/subagents/apis/examples.js.map +1 -1
  7. package/dist/ai-service/agent/subagents/apis/static-analysis.d.ts.map +1 -1
  8. package/dist/ai-service/agent/subagents/apis/static-analysis.js +14 -7
  9. package/dist/ai-service/agent/subagents/apis/static-analysis.js.map +1 -1
  10. package/dist/ai-service/agent/tool-message-utils.d.ts.map +1 -1
  11. package/dist/ai-service/agent/tool-message-utils.js +6 -2
  12. package/dist/ai-service/agent/tool-message-utils.js.map +1 -1
  13. package/dist/ai-service/agent/tools/apis/analysis.d.ts +9 -0
  14. package/dist/ai-service/agent/tools/apis/analysis.d.ts.map +1 -0
  15. package/dist/ai-service/agent/tools/apis/analysis.js +357 -0
  16. package/dist/ai-service/agent/tools/apis/analysis.js.map +1 -0
  17. package/dist/ai-service/agent/{subagents → tools}/apis/api-executor.d.ts +35 -10
  18. package/dist/ai-service/agent/tools/apis/api-executor.d.ts.map +1 -0
  19. package/dist/ai-service/agent/{subagents → tools}/apis/api-executor.js +179 -94
  20. package/dist/ai-service/agent/tools/apis/api-executor.js.map +1 -0
  21. package/dist/ai-service/agent/tools/apis/api-source.d.ts +19 -0
  22. package/dist/ai-service/agent/tools/apis/api-source.d.ts.map +1 -0
  23. package/dist/ai-service/agent/tools/apis/api-source.js +73 -0
  24. package/dist/ai-service/agent/tools/apis/api-source.js.map +1 -0
  25. package/dist/ai-service/agent/tools/apis/api-validation-orchestrator.d.ts +51 -0
  26. package/dist/ai-service/agent/tools/apis/api-validation-orchestrator.d.ts.map +1 -0
  27. package/dist/ai-service/agent/tools/apis/api-validation-orchestrator.js +510 -0
  28. package/dist/ai-service/agent/tools/apis/api-validation-orchestrator.js.map +1 -0
  29. package/dist/ai-service/agent/tools/apis/build-api-artifact.d.ts +32 -0
  30. package/dist/ai-service/agent/tools/apis/build-api-artifact.d.ts.map +1 -0
  31. package/dist/ai-service/agent/tools/apis/build-api-artifact.js +313 -0
  32. package/dist/ai-service/agent/tools/apis/build-api-artifact.js.map +1 -0
  33. package/dist/ai-service/agent/tools/apis/build-api.d.ts +1 -10
  34. package/dist/ai-service/agent/tools/apis/build-api.d.ts.map +1 -1
  35. package/dist/ai-service/agent/tools/apis/build-api.js +26 -238
  36. package/dist/ai-service/agent/tools/apis/build-api.js.map +1 -1
  37. package/dist/ai-service/agent/tools/apis/get-api-docs.d.ts +11 -0
  38. package/dist/ai-service/agent/tools/apis/get-api-docs.d.ts.map +1 -0
  39. package/dist/ai-service/agent/tools/apis/get-api-docs.js +1809 -0
  40. package/dist/ai-service/agent/tools/apis/get-api-docs.js.map +1 -0
  41. package/dist/ai-service/agent/tools/apis/integration-types.d.ts +37 -0
  42. package/dist/ai-service/agent/tools/apis/integration-types.d.ts.map +1 -0
  43. package/dist/ai-service/agent/tools/apis/integration-types.js +697 -0
  44. package/dist/ai-service/agent/tools/apis/integration-types.js.map +1 -0
  45. package/dist/ai-service/agent/tools/apis/test-api.d.ts +25 -0
  46. package/dist/ai-service/agent/tools/apis/test-api.d.ts.map +1 -0
  47. package/dist/ai-service/agent/tools/apis/test-api.js +194 -0
  48. package/dist/ai-service/agent/tools/apis/test-api.js.map +1 -0
  49. package/dist/ai-service/agent/tools/apis/write-api.d.ts +11 -0
  50. package/dist/ai-service/agent/tools/apis/write-api.d.ts.map +1 -0
  51. package/dist/ai-service/agent/tools/apis/write-api.js +41 -0
  52. package/dist/ai-service/agent/tools/apis/write-api.js.map +1 -0
  53. package/dist/ai-service/agent/tools/build-read-files.js +2 -2
  54. package/dist/ai-service/agent/tools/build-read-files.js.map +1 -1
  55. package/dist/ai-service/agent/tools.d.ts +2 -5
  56. package/dist/ai-service/agent/tools.d.ts.map +1 -1
  57. package/dist/ai-service/agent/tools.js +51 -22
  58. package/dist/ai-service/agent/tools.js.map +1 -1
  59. package/dist/ai-service/agent/tools2/access-control.d.ts +1 -0
  60. package/dist/ai-service/agent/tools2/access-control.d.ts.map +1 -1
  61. package/dist/ai-service/agent/tools2/access-control.js +15 -13
  62. package/dist/ai-service/agent/tools2/access-control.js.map +1 -1
  63. package/dist/ai-service/agent/tools2/registry.d.ts +2 -1
  64. package/dist/ai-service/agent/tools2/registry.d.ts.map +1 -1
  65. package/dist/ai-service/agent/tools2/registry.js +4 -3
  66. package/dist/ai-service/agent/tools2/registry.js.map +1 -1
  67. package/dist/ai-service/agent/tools2/tools/exit-plan-mode.d.ts +2 -1
  68. package/dist/ai-service/agent/tools2/tools/exit-plan-mode.d.ts.map +1 -1
  69. package/dist/ai-service/agent/tools2/tools/exit-plan-mode.js +103 -88
  70. package/dist/ai-service/agent/tools2/tools/exit-plan-mode.js.map +1 -1
  71. package/dist/ai-service/agent/tools2/tools/grep-metadata.d.ts.map +1 -1
  72. package/dist/ai-service/agent/tools2/tools/grep-metadata.js +25 -4
  73. package/dist/ai-service/agent/tools2/tools/grep-metadata.js.map +1 -1
  74. package/dist/ai-service/agent/tools2/types.d.ts +1 -1
  75. package/dist/ai-service/agent/tools2/types.d.ts.map +1 -1
  76. package/dist/ai-service/agent/tools2/types.js.map +1 -1
  77. package/dist/ai-service/agent/tools2/utils.d.ts.map +1 -1
  78. package/dist/ai-service/agent/tools2/utils.js +4 -1
  79. package/dist/ai-service/agent/tools2/utils.js.map +1 -1
  80. package/dist/ai-service/agent/utils.d.ts +1 -3
  81. package/dist/ai-service/agent/utils.d.ts.map +1 -1
  82. package/dist/ai-service/agent/utils.js +44 -4
  83. package/dist/ai-service/agent/utils.js.map +1 -1
  84. package/dist/ai-service/app-interface/shell.d.ts +5 -0
  85. package/dist/ai-service/app-interface/shell.d.ts.map +1 -1
  86. package/dist/ai-service/app-interface/shell.js +17 -2
  87. package/dist/ai-service/app-interface/shell.js.map +1 -1
  88. package/dist/ai-service/chat/chat-session-store.d.ts +7 -0
  89. package/dist/ai-service/chat/chat-session-store.d.ts.map +1 -1
  90. package/dist/ai-service/chat/chat-session-store.js +26 -0
  91. package/dist/ai-service/chat/chat-session-store.js.map +1 -1
  92. package/dist/ai-service/const.d.ts +2 -1
  93. package/dist/ai-service/const.d.ts.map +1 -1
  94. package/dist/ai-service/const.js +1 -0
  95. package/dist/ai-service/const.js.map +1 -1
  96. package/dist/ai-service/index.d.ts +5 -1
  97. package/dist/ai-service/index.d.ts.map +1 -1
  98. package/dist/ai-service/index.js +55 -7
  99. package/dist/ai-service/index.js.map +1 -1
  100. package/dist/ai-service/integrations/metadata-storage/index.d.ts +10 -0
  101. package/dist/ai-service/integrations/metadata-storage/index.d.ts.map +1 -1
  102. package/dist/ai-service/integrations/metadata-storage/local.d.ts +4 -2
  103. package/dist/ai-service/integrations/metadata-storage/local.d.ts.map +1 -1
  104. package/dist/ai-service/integrations/metadata-storage/local.js +35 -9
  105. package/dist/ai-service/integrations/metadata-storage/local.js.map +1 -1
  106. package/dist/ai-service/integrations/store.d.ts +27 -2
  107. package/dist/ai-service/integrations/store.d.ts.map +1 -1
  108. package/dist/ai-service/integrations/store.js +129 -62
  109. package/dist/ai-service/integrations/store.js.map +1 -1
  110. package/dist/ai-service/llm/client.d.ts +123 -0
  111. package/dist/ai-service/llm/client.d.ts.map +1 -0
  112. package/dist/ai-service/llm/client.js +168 -0
  113. package/dist/ai-service/llm/client.js.map +1 -0
  114. package/dist/ai-service/llm/context/context-handle.d.ts +4 -4
  115. package/dist/ai-service/llm/context/context-handle.d.ts.map +1 -1
  116. package/dist/ai-service/llm/context/context-handle.js +7 -3
  117. package/dist/ai-service/llm/context/context-handle.js.map +1 -1
  118. package/dist/ai-service/llm/context/context.d.ts +28 -0
  119. package/dist/ai-service/llm/context/context.d.ts.map +1 -1
  120. package/dist/ai-service/llm/context/context.js +117 -0
  121. package/dist/ai-service/llm/context/context.js.map +1 -1
  122. package/dist/ai-service/llm/context/manager.d.ts +22 -2
  123. package/dist/ai-service/llm/context/manager.d.ts.map +1 -1
  124. package/dist/ai-service/llm/context/manager.js +86 -13
  125. package/dist/ai-service/llm/context/manager.js.map +1 -1
  126. package/dist/ai-service/llm/context/storage/index.d.ts +1 -0
  127. package/dist/ai-service/llm/context/storage/index.d.ts.map +1 -1
  128. package/dist/ai-service/llm/context/storage/local.d.ts +1 -0
  129. package/dist/ai-service/llm/context/storage/local.d.ts.map +1 -1
  130. package/dist/ai-service/llm/context/storage/local.js +13 -1
  131. package/dist/ai-service/llm/context/storage/local.js.map +1 -1
  132. package/dist/ai-service/llm/error.d.ts +14 -4
  133. package/dist/ai-service/llm/error.d.ts.map +1 -1
  134. package/dist/ai-service/llm/error.js +49 -4
  135. package/dist/ai-service/llm/error.js.map +1 -1
  136. package/dist/ai-service/llm/interaction/adapters/vercel.d.ts +67 -0
  137. package/dist/ai-service/llm/interaction/adapters/vercel.d.ts.map +1 -0
  138. package/dist/ai-service/llm/interaction/adapters/vercel.js +110 -0
  139. package/dist/ai-service/llm/interaction/adapters/vercel.js.map +1 -0
  140. package/dist/ai-service/llm/interaction/compose.d.ts +71 -0
  141. package/dist/ai-service/llm/interaction/compose.d.ts.map +1 -0
  142. package/dist/ai-service/llm/interaction/compose.js +88 -0
  143. package/dist/ai-service/llm/interaction/compose.js.map +1 -0
  144. package/dist/ai-service/llm/interaction/index.d.ts +68 -0
  145. package/dist/ai-service/llm/interaction/index.d.ts.map +1 -0
  146. package/dist/ai-service/llm/interaction/index.js +70 -0
  147. package/dist/ai-service/llm/interaction/index.js.map +1 -0
  148. package/dist/ai-service/llm/interaction/middleware.d.ts +52 -0
  149. package/dist/ai-service/llm/interaction/middleware.d.ts.map +1 -0
  150. package/dist/ai-service/llm/interaction/middleware.js +17 -0
  151. package/dist/ai-service/llm/interaction/middleware.js.map +1 -0
  152. package/dist/ai-service/llm/interaction/middlewares/llmobs.d.ts +45 -0
  153. package/dist/ai-service/llm/interaction/middlewares/llmobs.d.ts.map +1 -0
  154. package/dist/ai-service/llm/interaction/middlewares/llmobs.js +85 -0
  155. package/dist/ai-service/llm/interaction/middlewares/llmobs.js.map +1 -0
  156. package/dist/ai-service/llm/interaction/middlewares/logging.d.ts +88 -0
  157. package/dist/ai-service/llm/interaction/middlewares/logging.d.ts.map +1 -0
  158. package/dist/ai-service/llm/interaction/middlewares/logging.js +238 -0
  159. package/dist/ai-service/llm/interaction/middlewares/logging.js.map +1 -0
  160. package/dist/ai-service/llm/interaction/middlewares/profiler.d.ts +47 -0
  161. package/dist/ai-service/llm/interaction/middlewares/profiler.d.ts.map +1 -0
  162. package/dist/ai-service/llm/interaction/middlewares/profiler.js +183 -0
  163. package/dist/ai-service/llm/interaction/middlewares/profiler.js.map +1 -0
  164. package/dist/ai-service/llm/interaction/middlewares/stream-retry.d.ts +121 -0
  165. package/dist/ai-service/llm/interaction/middlewares/stream-retry.d.ts.map +1 -0
  166. package/dist/ai-service/llm/interaction/middlewares/stream-retry.js +291 -0
  167. package/dist/ai-service/llm/interaction/middlewares/stream-retry.js.map +1 -0
  168. package/dist/ai-service/llm/interaction/provider.d.ts +158 -0
  169. package/dist/ai-service/llm/interaction/provider.d.ts.map +1 -0
  170. package/dist/ai-service/llm/interaction/provider.js +15 -0
  171. package/dist/ai-service/llm/interaction/provider.js.map +1 -0
  172. package/dist/ai-service/llm/interaction/stream-lifecycle.d.ts +48 -0
  173. package/dist/ai-service/llm/interaction/stream-lifecycle.d.ts.map +1 -0
  174. package/dist/ai-service/llm/interaction/stream-lifecycle.js +131 -0
  175. package/dist/ai-service/llm/interaction/stream-lifecycle.js.map +1 -0
  176. package/dist/ai-service/llm/provider.d.ts +1 -2
  177. package/dist/ai-service/llm/provider.d.ts.map +1 -1
  178. package/dist/ai-service/llm/provider.js +3 -6
  179. package/dist/ai-service/llm/provider.js.map +1 -1
  180. package/dist/ai-service/llmobs/helpers.d.ts +7 -8
  181. package/dist/ai-service/llmobs/helpers.d.ts.map +1 -1
  182. package/dist/ai-service/llmobs/helpers.js +8 -48
  183. package/dist/ai-service/llmobs/helpers.js.map +1 -1
  184. package/dist/ai-service/llmobs/middleware/stream-text.d.ts +19 -21
  185. package/dist/ai-service/llmobs/middleware/stream-text.d.ts.map +1 -1
  186. package/dist/ai-service/llmobs/middleware/stream-text.js +98 -106
  187. package/dist/ai-service/llmobs/middleware/stream-text.js.map +1 -1
  188. package/dist/ai-service/llmobs/types.d.ts +14 -1
  189. package/dist/ai-service/llmobs/types.d.ts.map +1 -1
  190. package/dist/ai-service/state-machine/clark-fsm.d.ts +75 -5
  191. package/dist/ai-service/state-machine/clark-fsm.d.ts.map +1 -1
  192. package/dist/ai-service/state-machine/clark-fsm.js +100 -0
  193. package/dist/ai-service/state-machine/clark-fsm.js.map +1 -1
  194. package/dist/ai-service/state-machine/handlers/agent-planning.d.ts.map +1 -1
  195. package/dist/ai-service/state-machine/handlers/agent-planning.js +4 -0
  196. package/dist/ai-service/state-machine/handlers/agent-planning.js.map +1 -1
  197. package/dist/ai-service/state-machine/handlers/llm-generating.d.ts.map +1 -1
  198. package/dist/ai-service/state-machine/handlers/llm-generating.js +91 -456
  199. package/dist/ai-service/state-machine/handlers/llm-generating.js.map +1 -1
  200. package/dist/ai-service/state-machine/handlers/runtime-reviewing.js +1 -1
  201. package/dist/ai-service/state-machine/handlers/runtime-reviewing.js.map +1 -1
  202. package/dist/ai-service/state-machine/helpers/peer.d.ts.map +1 -1
  203. package/dist/ai-service/state-machine/helpers/peer.js +15 -0
  204. package/dist/ai-service/state-machine/helpers/peer.js.map +1 -1
  205. package/dist/ai-service/state-machine/mocks.d.ts.map +1 -1
  206. package/dist/ai-service/state-machine/mocks.js +1 -0
  207. package/dist/ai-service/state-machine/mocks.js.map +1 -1
  208. package/dist/ai-service/types.d.ts +30 -0
  209. package/dist/ai-service/types.d.ts.map +1 -1
  210. package/dist/binding-extraction/extract-identifiers.d.ts +14 -0
  211. package/dist/binding-extraction/extract-identifiers.d.ts.map +1 -1
  212. package/dist/binding-extraction/extract-identifiers.js +46 -1
  213. package/dist/binding-extraction/extract-identifiers.js.map +1 -1
  214. package/dist/binding-extraction/js-identifiers.d.ts +14 -0
  215. package/dist/binding-extraction/js-identifiers.d.ts.map +1 -1
  216. package/dist/binding-extraction/js-identifiers.js +168 -0
  217. package/dist/binding-extraction/js-identifiers.js.map +1 -1
  218. package/dist/binding-extraction/python-identifiers.d.ts +5 -0
  219. package/dist/binding-extraction/python-identifiers.d.ts.map +1 -1
  220. package/dist/binding-extraction/python-identifiers.js +76 -7
  221. package/dist/binding-extraction/python-identifiers.js.map +1 -1
  222. package/dist/file-sync-vite-plugin.d.ts.map +1 -1
  223. package/dist/file-sync-vite-plugin.js +73 -3
  224. package/dist/file-sync-vite-plugin.js.map +1 -1
  225. package/dist/file-system-manager.d.ts.map +1 -1
  226. package/dist/file-system-manager.js +6 -4
  227. package/dist/file-system-manager.js.map +1 -1
  228. package/dist/index.d.ts +1 -1
  229. package/dist/index.d.ts.map +1 -1
  230. package/dist/index.js +1 -1
  231. package/dist/index.js.map +1 -1
  232. package/dist/lock-service/activity-tracker.d.ts +14 -2
  233. package/dist/lock-service/activity-tracker.d.ts.map +1 -1
  234. package/dist/lock-service/activity-tracker.js +43 -6
  235. package/dist/lock-service/activity-tracker.js.map +1 -1
  236. package/dist/lock-service/index.d.ts +13 -2
  237. package/dist/lock-service/index.d.ts.map +1 -1
  238. package/dist/lock-service/index.js +130 -44
  239. package/dist/lock-service/index.js.map +1 -1
  240. package/dist/parsing/jsx.d.ts.map +1 -1
  241. package/dist/parsing/jsx.js +78 -66
  242. package/dist/parsing/jsx.js.map +1 -1
  243. package/dist/socket-manager.js +1 -1
  244. package/dist/socket-manager.js.map +1 -1
  245. package/dist/sync-service/list-dir.d.ts.map +1 -1
  246. package/dist/sync-service/list-dir.js +41 -18
  247. package/dist/sync-service/list-dir.js.map +1 -1
  248. package/dist/vite-plugin-yaml-types.d.ts.map +1 -1
  249. package/dist/vite-plugin-yaml-types.js +2 -4
  250. package/dist/vite-plugin-yaml-types.js.map +1 -1
  251. package/package.json +7 -7
  252. package/dist/ai-service/agent/subagents/apis/api-executor.d.ts.map +0 -1
  253. package/dist/ai-service/agent/subagents/apis/api-executor.js.map +0 -1
  254. package/dist/ai-service/agent/subagents/apis/context.d.ts +0 -12
  255. package/dist/ai-service/agent/subagents/apis/context.d.ts.map +0 -1
  256. package/dist/ai-service/agent/subagents/apis/context.js +0 -18
  257. package/dist/ai-service/agent/subagents/apis/context.js.map +0 -1
  258. package/dist/ai-service/agent/subagents/apis/generate-api-source.d.ts +0 -40
  259. package/dist/ai-service/agent/subagents/apis/generate-api-source.d.ts.map +0 -1
  260. package/dist/ai-service/agent/subagents/apis/generate-api-source.js +0 -516
  261. package/dist/ai-service/agent/subagents/apis/generate-api-source.js.map +0 -1
  262. package/dist/ai-service/agent/subagents/apis/state.d.ts +0 -49
  263. package/dist/ai-service/agent/subagents/apis/state.d.ts.map +0 -1
  264. package/dist/ai-service/agent/subagents/apis/state.js +0 -25
  265. package/dist/ai-service/agent/subagents/apis/state.js.map +0 -1
  266. package/dist/ai-service/agent/subagents/apis/system-prompt.d.ts +0 -3
  267. package/dist/ai-service/agent/subagents/apis/system-prompt.d.ts.map +0 -1
  268. package/dist/ai-service/agent/subagents/apis/system-prompt.js +0 -1704
  269. package/dist/ai-service/agent/subagents/apis/system-prompt.js.map +0 -1
  270. package/dist/ai-service/agent/tools/apis/finalize-api.d.ts +0 -11
  271. package/dist/ai-service/agent/tools/apis/finalize-api.d.ts.map +0 -1
  272. package/dist/ai-service/agent/tools/apis/finalize-api.js +0 -133
  273. package/dist/ai-service/agent/tools/apis/finalize-api.js.map +0 -1
  274. package/dist/ai-service/llm/middleware/retry.d.ts +0 -112
  275. package/dist/ai-service/llm/middleware/retry.d.ts.map +0 -1
  276. package/dist/ai-service/llm/middleware/retry.js +0 -239
  277. package/dist/ai-service/llm/middleware/retry.js.map +0 -1
@@ -0,0 +1,1809 @@
1
+ import { z } from "zod";
2
+ import { selectExamplesByTags, formatSelectedExamples, } from "../../subagents/apis/example-selector.js";
3
+ import { POSITIVE_EXAMPLES, } from "../../subagents/apis/examples.js";
4
+ import { createToolFactory, ToolCategory } from "../../tools2/types.js";
5
+ import { getIntegrationTypeDefinition } from "./integration-types.js";
6
+ /**
7
+ * Core type definitions - control flow and base types only
8
+ * Integration-specific types are provided by getIntegrationTypeDefinition
9
+ */
10
+ const TYPE_DEFINITIONS = `
11
+ ## Core Type Definitions
12
+
13
+ These are the core type definitions for control flow blocks and base types in Superblocks APIs:
14
+
15
+ \`\`\`typescript
16
+ // @superblocksteam/library
17
+
18
+ export type JsonValue = any;
19
+
20
+ export type State = { [key: string]: JsonValue };
21
+
22
+ export type Binding<T> = T | ((state: State) => T);
23
+
24
+ export declare abstract class Block {
25
+ protected name: string;
26
+
27
+ constructor(name: string);
28
+ }
29
+
30
+ export declare abstract class Integration extends Block {
31
+ constructor(name: string, integration: string);
32
+ }
33
+
34
+ // Control Flow Blocks
35
+
36
+ export type Condition = {
37
+ when: Binding<boolean>;
38
+ then: Block[];
39
+ };
40
+
41
+ export type Conditions = {
42
+ if: Condition;
43
+ elif?: Condition[];
44
+ else?: Block[];
45
+ };
46
+
47
+ export declare class Conditional extends Block {
48
+ public conditions: Conditions;
49
+
50
+ constructor(name: string, config: Conditions);
51
+ }
52
+
53
+ export declare class Loop extends Block {
54
+ constructor(
55
+ name: string,
56
+ config: {
57
+ over: Binding<JsonValue[]>;
58
+ variables: { item: string; index: string };
59
+ blocks: Block[];
60
+ },
61
+ );
62
+ public static fromJSON(json: any, entities: string[]): Loop;
63
+ }
64
+
65
+ export declare class TryCatch extends Block {
66
+ constructor(
67
+ name: string,
68
+ config: {
69
+ try: Block[];
70
+ catch: Block[];
71
+ finally?: Block[];
72
+ variables: { error: string };
73
+ },
74
+ );
75
+ }
76
+
77
+ export declare class Throw extends Block {
78
+ constructor(
79
+ name: string,
80
+ config: {
81
+ error: Binding<JsonValue>;
82
+ },
83
+ );
84
+ }
85
+
86
+ export declare class Return extends Block {
87
+ constructor(
88
+ name: string,
89
+ config: {
90
+ data: Binding<JsonValue>;
91
+ },
92
+ );
93
+ }
94
+
95
+ export declare class Break extends Block {
96
+ constructor(
97
+ name: string,
98
+ config: {
99
+ condition: Binding<JsonValue>;
100
+ },
101
+ );
102
+ }
103
+
104
+ // API and Authorization
105
+
106
+ export type Authorization =
107
+ | {
108
+ type: "AUTHORIZATION_TYPE_APP_USERS";
109
+ }
110
+ | {
111
+ type: "AUTHORIZATION_TYPE_JS_EXPRESSION";
112
+ expression: Binding<boolean>;
113
+ };
114
+
115
+ export declare class Api {
116
+ constructor(name: string, blocks?: Block[], authorization?: Authorization);
117
+ }
118
+ \`\`\`
119
+
120
+ **Note:** Integration-specific type definitions (PostgreSQL, Snowflake, OpenApi, etc.) are provided when you specify \`integrationIds\` in the tool call. JavaScript and Python block definitions are included in the "Built-in Blocks" section.
121
+ `;
122
+ /**
123
+ * Integration exploration workflow - critical for understanding integrations
124
+ */
125
+ const INTEGRATION_EXPLORATION_WORKFLOW = `
126
+ ## 🔍 Integration Exploration Workflow (CRITICAL)
127
+
128
+ When exploring integrations and data sources:
129
+
130
+ ### 1. Start with metadata exploration
131
+
132
+ Use \`grepMetadata\` to understand:
133
+ - What tables/endpoints exist
134
+ - Schema structure and organization
135
+ - Available fields and data types
136
+
137
+ Query actual data (\`executeRequestToIntegration\`) only when you need:
138
+ - Specific data values for analysis
139
+ - Sample records to understand data patterns
140
+ - Actual data for application functionality
141
+
142
+ **💡 KEY PRINCIPLE:** For "tell me about the data" type questions, metadata exploration is usually sufficient and more efficient
143
+
144
+ ### 2. NEVER use SQL/API queries for metadata exploration
145
+
146
+ ❌ **WRONG**: \`SHOW COLUMNS FROM users\`, \`DESCRIBE table\`, \`SELECT * FROM INFORMATION_SCHEMA\`
147
+ ❌ **WRONG**: API calls just to see what endpoints exist
148
+ ✅ **CORRECT**: \`grepMetadata({ grepPattern: "\\\\.columns\\\\[\\\\d+\\\\]\\\\.name" })\` to find all columns (database)
149
+ ✅ **CORRECT**: \`grepMetadata({ grepPattern: "\\\\.paths\\\\[\\".*repo.*\\"\\\\]" })\` for API paths with "repo" (OpenAPI)
150
+
151
+ ### 3. Progressive Exploration for Large Integrations (100+ tables/endpoints)
152
+
153
+ **⚠️ Use this workflow ONLY for exploratory prompts** ("tell me about @databricks", "what data is available").
154
+ **When user mentions specific topics** ("weather app", "user orders"), search for those or similar keywords directly instead.
155
+
156
+ #### Step 1: Discover Top-Level Organization
157
+ - **Database Pattern**: \`"\\\\.dbSchema\\\\.schemas\\\\[\\\\d+\\\\]\\\\.name"\` (returns all unique schemas)
158
+ - **OpenAPI Pattern**: \`"\\\\.paths\\\\[.*\\\\]"\` (returns all API paths)
159
+ - **GraphQL Pattern**: \`"\\\\.types\\\\[\\\\d+\\\\]\\\\.name"\` (returns all GraphQL types)
160
+
161
+ #### Step 2: Explore Specific Area (User-Directed)
162
+ - **Database Pattern**:
163
+ - \`"\\\\.tables\\\\[\\\\d+\\\\]\\\\.name = \\".*\\""\` (get all table names)
164
+ - \`"\\\\.tables\\\\[\\\\d+\\\\]\\\\.name"\` (shorter - just find table name fields)
165
+ - **⚠️ NOT** \`"\\\\.schema\\\\.tables"\` - the field is \`dbSchema\` not \`schema\`!
166
+ - **OpenAPI Pattern**: \`"\\\\.paths\\\\[\\".*category.*\\"\\\\]"\` (paths matching category)
167
+ - **GraphQL Pattern**: \`"\\\\.types\\\\[\\\\d+\\\\]\\\\.name = \\".*User.*\\""\` (types matching pattern)
168
+
169
+ #### Step 3: Dive Into Specifics
170
+ - **Database Pattern**: \`"\\\\.tables\\\\[\\\\d+\\\\]\\\\.name = \\"exact_table\\""\` (returns full table with all columns!)
171
+ - **OpenAPI Pattern**: \`"\\\\.paths\\\\[\\"/exact/path\\"\\\\]\\\\..*"\` (all details for that endpoint)
172
+ - **GraphQL Pattern**: \`"\\\\.types\\\\[\\\\d+\\\\]\\\\.name = \\"User\\"|" + "\\\\.fields\\\\[\\\\d+\\\\]\\\\.name"\` (get fields for a type)
173
+
174
+ ### 4. Critical: Different integration types use different key formats
175
+
176
+ #### DATABASE integrations (Postgres, MySQL, Snowflake, Databricks, etc.)
177
+ - **Structure**: All databases use \`json.dbSchema.schemas[]\` and \`json.dbSchema.tables[]\`
178
+ - **⚠️ CRITICAL**: It's \`dbSchema\` (NOT \`schema\`!) - the field name is \`dbSchema\`
179
+ - Use **numeric array indices**: \`[0]\`, \`[1]\`, \`[2]\`, etc.
180
+ - Pattern: Use \`\\\\d+\` to match any number
181
+ - Examples:
182
+ - ✅ \`"\\\\.dbSchema\\\\.schemas\\\\[\\\\d+\\\\]\\\\.name"\` - Find schema names
183
+ - ✅ \`"\\\\.tables\\\\[\\\\d+\\\\]\\\\.name = \\".*user.*\\""\` - Find tables
184
+ - ❌ \`"\\\\.schema\\\\.tables"\` - WRONG! It's \`dbSchema\` not \`schema\`
185
+
186
+ #### OPENAPI integrations (REST APIs with OpenAPI specs)
187
+ - Use **string object keys**: \`["/users"]\`, \`["/repos"]\`
188
+ - Pattern: Use \`.*\` to match any key (NOT \`\\\\d+\`!)
189
+ - **Structure**: Path string IS the key (not a field!)
190
+ - Format: \`json.openApiSpec.paths["/users"].get.operationId\`
191
+ - Examples:
192
+ - ✅ \`"\\\\.paths\\\\[\\".*repos.*\\"\\\\]"\` - Find paths with "repos"
193
+ - ✅ \`"\\\\.paths\\\\[\\"/exact/path\\"\\\\]"\` - Exact path match
194
+ - ❌ \`"\\\\.paths\\\\[\\\\d+\\\\]"\` - WRONG! OpenAPI doesn't use numeric indices
195
+
196
+ #### GRAPHQL integrations
197
+ - **Structure**: GraphQL uses standard introspection response format at \`json.graphql.data.__schema\`
198
+ - Use **numeric array indices**: \`[0]\`, \`[1]\`, \`[2]\`, etc.
199
+ - **Two-step workflow** (recommended for large schemas):
200
+ 1. **Exploration**: Use \`includeDetails: false\` to get type with field names
201
+ 2. **Detailed lookup**: Search for 1-3 specific fields at a time
202
+
203
+ ### 5. Pagination and Truncation
204
+
205
+ **Understanding \`truncated: true\`**:
206
+ - Truncation is **NORMAL and EXPECTED** for large schemas
207
+ - It means: "Here's what I found so far"
208
+
209
+ **When to paginate:**
210
+ 1. User explicitly wants ALL results: "Give me ALL tables"
211
+ 2. Specific search truncated AND you need more
212
+ 3. User requests continuation: "Show me more"
213
+
214
+ **When NOT to paginate:**
215
+ 1. Sample is sufficient for the question
216
+ 2. Can refine search instead
217
+
218
+ ### 6. REST API vs OpenAPI Selection
219
+
220
+ **🚨 CRITICAL: When working with REST API integrations:**
221
+ 1. **ALWAYS call \`grepMetadata\` first** to determine if the REST API is OpenAPI-backed
222
+ 2. **If metadata shows it's an OpenAPI-backed API, you MUST:**
223
+ - Use the \`OpenApi\` class, NOT \`RestApi\`
224
+ - Supply the required \`openapi.path\` property
225
+ - Example: \`new OpenApi("api_call", "integration-id", {...}, { path: "/endpoint" })\`
226
+ 3. **Only use \`RestApi\` class for non-OpenAPI REST integrations**
227
+ `;
228
+ /**
229
+ * Block output scoping rules - critical for understanding variable access
230
+ */
231
+ const BLOCK_OUTPUT_SCOPING_RULES = `
232
+ ## Block Output Scoping Rules
233
+
234
+ **CRITICAL: Blocks can only access outputs from specific scopes based on their position in the hierarchy.**
235
+
236
+ ### Scoping Hierarchy
237
+ Control flow blocks (Loop, Conditional, TryCatch) create new scopes for their children. Regular blocks (JavaScript, PostgreSQL, etc.) do not create scopes.
238
+
239
+ ### What blocks CAN access:
240
+ 1. **Previous sibling blocks** at the same level (executed before them)
241
+ 2. **ALL ancestor block outputs** (parent, grandparent, etc. up the chain)
242
+ 3. **Parent control flow variables** (e.g., \`item\` and \`index\` in Loop, \`error\` in TryCatch)
243
+ 4. **Control flow block outputs** (equals the output of their last child block)
244
+
245
+ ### What blocks CANNOT access:
246
+ - ❌ Outputs from blocks nested inside other control flow blocks
247
+ - ❌ Outputs from blocks in other Conditional branches
248
+ - ❌ Outputs from blocks that come after them at the same level
249
+
250
+ ### Example Hierarchy:
251
+
252
+ \`\`\`typescript
253
+ // Structure: A → B(Loop) → [B1, B2, B3] → C → D
254
+
255
+ new JavaScript("A_fetch_data", { fn: () => [...] }), // Block A
256
+
257
+ new Loop("B_process_items", { // Block B (control flow)
258
+ over: ({ A_fetch_data }) => A_fetch_data.output,
259
+ variables: { item: "current", index: "i" },
260
+ blocks: [
261
+ new JavaScript("B1_validate", { // Block B1
262
+ fn: ({ current, i, A_fetch_data }) => {
263
+ // ✅ Can access: current, i (loop vars), A_fetch_data
264
+ return { valid: true };
265
+ }
266
+ }),
267
+ new JavaScript("B2_transform", { // Block B2
268
+ fn: ({ B1_validate, current }) => {
269
+ // ✅ Can access: B1_validate, current, A_fetch_data
270
+ return { transformed: current.value };
271
+ }
272
+ }),
273
+ new JavaScript("B3_save", { // Block B3
274
+ fn: ({ B2_transform, B1_validate }) => {
275
+ // ✅ Can access: B2_transform, B1_validate, loop vars, A_fetch_data
276
+ return { saved: true };
277
+ }
278
+ })
279
+ ]
280
+ }),
281
+
282
+ new JavaScript("C_aggregate", { // Block C
283
+ fn: ({ B_process_items, A_fetch_data }) => {
284
+ // ✅ Can access: B_process_items.output (= B3's output), A_fetch_data
285
+ // ❌ CANNOT access: B1_validate, B2_transform, B3_save (inside B's scope)
286
+ return { total: B_process_items.output.length };
287
+ }
288
+ }),
289
+
290
+ new JavaScript("D_finalize", { // Block D
291
+ fn: ({ C_aggregate, B_process_items, A_fetch_data }) => {
292
+ // ✅ Can access: C_aggregate, B_process_items, A_fetch_data
293
+ // ❌ CANNOT access: B1_validate, B2_transform, B3_save (inside B's scope)
294
+ return { complete: true };
295
+ }
296
+ })
297
+ \`\`\`
298
+
299
+ ### Conditional Branch Scoping:
300
+
301
+ \`\`\`typescript
302
+ new Conditional("check_user_type", {
303
+ if: {
304
+ when: ({ userRole }) => userRole === "admin",
305
+ then: [
306
+ new JavaScript("admin_process", {
307
+ fn: () => ({ adminData: "..." })
308
+ })
309
+ ]
310
+ },
311
+ elif: [{
312
+ when: ({ userRole }) => userRole === "user",
313
+ then: [
314
+ new JavaScript("user_process", {
315
+ fn: () => ({ userData: "..." })
316
+ })
317
+ ]
318
+ }]
319
+ }),
320
+
321
+ new JavaScript("next_step", {
322
+ fn: ({ check_user_type }) => {
323
+ // ✅ Can access: check_user_type.output (from whichever branch executed)
324
+ // ❌ CANNOT access: admin_process or user_process directly
325
+ return check_user_type.output;
326
+ }
327
+ })
328
+ \`\`\`
329
+
330
+ ### Variable Access Patterns
331
+
332
+ **Control Block Variables:**
333
+ \`\`\`typescript
334
+ // Always use .value for Loop, TryCatch variables
335
+ new Loop("process_items", {
336
+ variables: { item: "order", index: "i" },
337
+ blocks: [
338
+ new JavaScript("process", {
339
+ fn: ({ order, i }) => ({
340
+ id: order.value.id, // ✅ .value
341
+ position: i.value // ✅ .value
342
+ })
343
+ })
344
+ ]
345
+ })
346
+ \`\`\`
347
+
348
+ **Previous Block Outputs:**
349
+ \`\`\`typescript
350
+ // Use .output for previous block results
351
+ new JavaScript("get_data", {
352
+ fn: () => [{ id: 1, name: "John" }, { id: 2, name: "Jane" }]
353
+ }),
354
+ new JavaScript("process_data", {
355
+ fn: ({ get_data }) => get_data.output.length // ✅ .output
356
+ })
357
+ \`\`\`
358
+
359
+ **Inputs:**
360
+ \`\`\`typescript
361
+ // Direct access inputs - no .value needed!
362
+ new PostgreSQL("insert_user", "valid-postgres-id", {
363
+ statement: ({ FirstName, LastName }) =>
364
+ \`INSERT INTO users VALUES ('\${FirstName}', '\${LastName}')\`
365
+ // ✅ FirstName and LastName are API inputs - accessed directly, no .value
366
+ })
367
+
368
+ // Compare with step outputs which DO need .output:
369
+ new JavaScript("process", {
370
+ fn: ({ FirstName, insert_user }) => {
371
+ // FirstName is an API input - no .value needed
372
+ if (FirstName) { ... } // ✅ CORRECT
373
+
374
+ // insert_user is a step output - needs .output
375
+ if (insert_user.output) { ... } // ✅ CORRECT
376
+ }
377
+ })
378
+ \`\`\`
379
+ `;
380
+ /**
381
+ * Input discovery rules - how variables become API inputs
382
+ */
383
+ const INPUT_DISCOVERY_RULES = `
384
+ ## 🎯 API Input Discovery Rules (CRITICAL)
385
+
386
+ **IMPORTANT: You do NOT need to explicitly declare API inputs. They are automatically discovered through code analysis.**
387
+
388
+ ### How Variables Become API Inputs
389
+
390
+ Variables are **implicitly discovered** as API inputs when they are:
391
+ 1. **Destructured in block functions** but not defined elsewhere
392
+ 2. **Referenced but not produced** by any previous block
393
+ 3. **External to the API scope** (not step outputs or control flow variables)
394
+
395
+ ### 🚨 CRITICAL: Always Type Your Input Parameters
396
+
397
+ **EVERY input parameter MUST have a TypeScript type annotation.**
398
+
399
+ When you reference input variables in your API code, you MUST add type annotations to the destructured parameters:
400
+
401
+ #### ✅ CORRECT - Typed parameters:
402
+ \`\`\`typescript
403
+ // Single typed parameter
404
+ new JavaScript("validate_email", {
405
+ fn: ({ email }: { email: string }) => {
406
+ return email.includes("@");
407
+ }
408
+ })
409
+
410
+ // Multiple typed parameters
411
+ new PostgreSQL("search_users", "postgres-id", {
412
+ statement: ({ searchTerm, limit }: { searchTerm: string; limit: number }) =>
413
+ \`SELECT * FROM users WHERE name ILIKE '%\${searchTerm}%' LIMIT \${limit}\`
414
+ })
415
+
416
+ // Optional parameters with union types
417
+ new JavaScript("process_filters", {
418
+ fn: ({ status, category }: { status?: string; category?: string | null }) => {
419
+ const filters = [];
420
+ if (status) filters.push(\`status = '\${status}'\`);
421
+ if (category) filters.push(\`category = '\${category}'\`);
422
+ return filters.join(" AND ");
423
+ }
424
+ })
425
+ \`\`\`
426
+
427
+ #### ❌ WRONG - Untyped parameters:
428
+ \`\`\`typescript
429
+ // Missing type annotations
430
+ new JavaScript("validate_email", {
431
+ fn: ({ email }) => { // ❌ No type annotation!
432
+ return email.includes("@");
433
+ }
434
+ })
435
+
436
+ new PostgreSQL("search_users", "postgres-id", {
437
+ statement: ({ searchTerm, limit }) => // ❌ No types!
438
+ \`SELECT * FROM users WHERE name ILIKE '%\${searchTerm}%' LIMIT \${limit}\`
439
+ })
440
+ \`\`\`
441
+
442
+ #### Type Inference from Context
443
+
444
+ Use appropriate types based on the parameter's usage:
445
+ - **String fields**: \`name: string\`, \`email: string\`, \`description: string\`
446
+ - **Numeric values**: \`age: number\`, \`price: number\`, \`quantity: number\`
447
+ - **Booleans**: \`isActive: boolean\`, \`hasPermission: boolean\`
448
+ - **Optional values**: \`category?: string\`, \`userId?: number\`
449
+ - **Nullable values**: \`middleName: string | null\`, \`avatar: string | null | undefined\`
450
+ - **Arrays**: \`tags: string[]\`, \`ids: number[]\`
451
+ - **Objects**: \`user: { id: number; name: string }\`
452
+ - **Union types**: \`status: "active" | "pending" | "inactive"\`
453
+
454
+ #### Why This Matters
455
+
456
+ Typed parameters enable:
457
+ 1. **Automatic type extraction** - The buildApi tool extracts these types to generate accurate input interfaces
458
+ 2. **Better IDE support** - Type checking catches errors before runtime
459
+ 3. **Self-documenting code** - Types show what inputs are expected
460
+ 4. **Frontend integration** - Generated type definition files provide accurate TypeScript types for the frontend
461
+
462
+ **REMEMBER**: Every input parameter MUST have a type annotation. The system will automatically extract these to generate the API's input interface.
463
+
464
+ ### ⚠️ CRITICAL: When to Use .value vs Direct Access
465
+
466
+ **API Inputs** - Access DIRECTLY (no .value):
467
+ \`\`\`typescript
468
+ fn: ({ statusFilter, emailFilter }) => {
469
+ if (statusFilter) { ... } // ✅ CORRECT - direct access
470
+ if (statusFilter.value) { ... } // ❌ WRONG - don't use .value
471
+ }
472
+ \`\`\`
473
+
474
+ **Step Outputs** - Use .output:
475
+ \`\`\`typescript
476
+ fn: ({ previous_step }) => {
477
+ return previous_step.output; // ✅ CORRECT - use .output
478
+ return previous_step; // ❌ WRONG - missing .output
479
+ }
480
+ \`\`\`
481
+
482
+ **Loop Variables** - Use .value:
483
+ \`\`\`typescript
484
+ fn: ({ item, index }) => { // Loop variables from Loop block
485
+ return item.value.id; // ✅ CORRECT - use .value
486
+ return item.id; // ❌ WRONG - missing .value
487
+ }
488
+ \`\`\`
489
+
490
+ **TryCatch Error Variables** - Use .value:
491
+ \`\`\`typescript
492
+ fn: ({ error }) => { // Error variable from TryCatch
493
+ return error.value.message; // ✅ CORRECT - use .value
494
+ return error.message; // ❌ WRONG - missing .value
495
+ }
496
+ \`\`\`
497
+
498
+ ### Automatic Input Detection
499
+
500
+ \`\`\`typescript
501
+ // Example: startDate and endDate automatically become API inputs
502
+ export default new Api("GetOrders", [
503
+ new JavaScript("build_query", {
504
+ fn: ({ startDate, endDate }) => { // ✅ These become inputs automatically
505
+ let query = "SELECT * FROM orders";
506
+
507
+ if (startDate) {
508
+ query += \` WHERE date >= '\${startDate}'\`;
509
+ }
510
+ if (endDate) {
511
+ query += \` AND date <= '\${endDate}'\`;
512
+ }
513
+
514
+ return query;
515
+ }
516
+ }),
517
+
518
+ new PostgreSQL("fetch_orders", "postgres-id", {
519
+ statement: ({ build_query }) => build_query.output // ❌ NOT an input (it's a block output)
520
+ })
521
+ ]);
522
+ \`\`\`
523
+
524
+ ### What Does NOT Become an Input
525
+
526
+ 1. **Previous block outputs** (accessed via \`.output\`):
527
+ \`\`\`typescript
528
+ new JavaScript("process", {
529
+ fn: ({ fetch_data }) => fetch_data.output // ❌ NOT an input - it's a block reference
530
+ })
531
+ \`\`\`
532
+
533
+ 2. **Control flow variables** (accessed via \`.value\`):
534
+ \`\`\`typescript
535
+ new Loop("process_items", {
536
+ variables: { item: "order", index: "i" },
537
+ blocks: [
538
+ new JavaScript("transform", {
539
+ fn: ({ order, i }) => ({ // ❌ NOT inputs - they're loop variables
540
+ id: order.value.id,
541
+ position: i.value
542
+ })
543
+ })
544
+ ]
545
+ })
546
+ \`\`\`
547
+
548
+ 3. **Error variables in TryCatch**:
549
+ \`\`\`typescript
550
+ new TryCatch("safe_operation", {
551
+ catch: [
552
+ new JavaScript("handle_error", {
553
+ fn: ({ err }) => err.value // ❌ NOT an input - it's a catch variable
554
+ })
555
+ ],
556
+ variables: { error: "err" }
557
+ })
558
+ \`\`\`
559
+
560
+ ### Type Generation
561
+
562
+ When you build an API, the system automatically:
563
+ 1. **Analyzes your code** to find all undefined external variables
564
+ 2. **Generates TypeScript interfaces** for the inputs
565
+ 3. **Creates a types.d.ts file** with the proper types
566
+
567
+ Example generated types for the GetOrders API above:
568
+ \`\`\`typescript
569
+ // Auto-generated by Superblocks
570
+ interface GetOrdersInput {
571
+ startDate?: any;
572
+ endDate?: any;
573
+ }
574
+
575
+ type GetOrdersResponse = any;
576
+ \`\`\`
577
+
578
+ ### How APIs Are Called
579
+
580
+ Once built, APIs can be called from the frontend with the discovered inputs:
581
+
582
+ \`\`\`typescript
583
+ // In React component
584
+ const { run: runGetOrders } = useApi("GetOrders");
585
+
586
+ const response = await runGetOrders({
587
+ startDate: "2024-01-01",
588
+ endDate: "2024-12-31"
589
+ });
590
+
591
+ // The API returns the output of the last block directly
592
+ const orders = response || [];
593
+ \`\`\`
594
+
595
+ ### Best Practices
596
+
597
+ 1. **Use descriptive parameter names** that clearly indicate their purpose
598
+ 2. **Don't worry about declaring inputs** - the system handles it automatically
599
+ 3. **Focus on using the variables** where you need them - inputs are inferred
600
+ 4. **Check the build output** to see which inputs were detected
601
+
602
+ ### Common Patterns
603
+
604
+ **Filter parameters automatically become inputs:**
605
+ \`\`\`typescript
606
+ new JavaScript("build_filter", {
607
+ fn: ({ statusFilter, userIdFilter, dateRangeFilter }) => {
608
+ // All three filters automatically become API inputs
609
+ const conditions = [];
610
+ if (statusFilter) conditions.push(\`status = '\${statusFilter}'\`);
611
+ if (userIdFilter) conditions.push(\`user_id = \${userIdFilter}\`);
612
+ if (dateRangeFilter) conditions.push(\`date BETWEEN ...\`);
613
+ return conditions;
614
+ }
615
+ })
616
+ \`\`\`
617
+
618
+ **Pagination parameters:**
619
+ \`\`\`typescript
620
+ new JavaScript("paginate", {
621
+ fn: ({ page = 1, pageSize = 20 }) => {
622
+ // page and pageSize become optional inputs with defaults
623
+ const offset = (page - 1) * pageSize;
624
+ return { offset, limit: pageSize };
625
+ }
626
+ })
627
+ \`\`\`
628
+ `;
629
+ /**
630
+ * Common API patterns including the critical two-block dynamic SQL pattern
631
+ */
632
+ const COMMON_API_PATTERNS = `
633
+ ## 🔄 Common API Patterns
634
+
635
+ ### Simple Data Retrieval
636
+ \`\`\`typescript
637
+ export default new Api("getUsersApi", [
638
+ new JavaScript("fetch_users", {
639
+ fn: () => [
640
+ { id: 1, name: "John Doe", email: "john@example.com" },
641
+ { id: 2, name: "Jane Smith", email: "jane@example.com" }
642
+ ]
643
+ })
644
+ ]);
645
+ \`\`\`
646
+
647
+ ### Input Validation + Processing
648
+ \`\`\`typescript
649
+ export default new Api("createUserApi", [
650
+ new Conditional("validate_inputs", {
651
+ if: {
652
+ when: ({ FirstNameInput, EmailInput }: { FirstNameInput: string; EmailInput: string }): boolean =>
653
+ !FirstNameInput || !EmailInput,
654
+ then: [
655
+ new Throw("validation_error", {
656
+ error: "First name and email are required"
657
+ })
658
+ ]
659
+ }
660
+ }),
661
+ new JavaScript("create_user", {
662
+ fn: ({ FirstNameInput, EmailInput }: { FirstNameInput: string; EmailInput: string }) => ({
663
+ id: Math.floor(Math.random() * 1000),
664
+ name: FirstNameInput,
665
+ email: EmailInput,
666
+ created_at: new Date().toISOString()
667
+ })
668
+ })
669
+ ]);
670
+ \`\`\`
671
+
672
+ ### Data Processing with Loops
673
+ \`\`\`typescript
674
+ export default new Api("processOrdersApi", [
675
+ new JavaScript("get_orders", {
676
+ fn: () => [
677
+ { id: 1, status: "pending", amount: 100 },
678
+ { id: 2, status: "pending", amount: 200 }
679
+ ]
680
+ }),
681
+ new Loop("process_each_order", {
682
+ over: ({ get_orders }) => get_orders.output,
683
+ variables: { item: "order", index: "i" },
684
+ blocks: [
685
+ new JavaScript("calculate_tax", {
686
+ fn: ({ order, i }) => ({
687
+ ...order.value,
688
+ tax: order.value.amount * 0.1,
689
+ total: order.value.amount * 1.1,
690
+ position: i.value
691
+ })
692
+ })
693
+ ]
694
+ })
695
+ ]);
696
+ \`\`\`
697
+
698
+ ### 🚨 Dynamic SQL Queries (Two-Block Pattern) - CRITICAL
699
+ \`\`\`typescript
700
+ import {
701
+ Api,
702
+ JavaScript,
703
+ PostgreSQL,
704
+ } from "@superblocksteam/library";
705
+
706
+ export default new Api("searchOrdersApi", [
707
+ // Block 1: Build the dynamic SQL query in JavaScript
708
+ new JavaScript("build_search_query", {
709
+ fn: ({ EmailFilter, StatusFilter }: { EmailFilter?: string; StatusFilter?: string }) => {
710
+ let query = \`
711
+ SELECT id, user_email, product, price, status, date_purchased
712
+ FROM orders
713
+ \`;
714
+
715
+ const conditions = [];
716
+
717
+ if (EmailFilter && EmailFilter.trim()) {
718
+ conditions.push(\`user_email ILIKE '%\${EmailFilter}%'\`);
719
+ }
720
+
721
+ if (StatusFilter && StatusFilter !== 'all') {
722
+ conditions.push(\`status = '\${StatusFilter}'\`);
723
+ }
724
+
725
+ if (conditions.length > 0) {
726
+ query += \` WHERE \${conditions.join(' AND ')}\`;
727
+ }
728
+
729
+ return query + \` ORDER BY date_purchased DESC LIMIT 100\`;
730
+ }
731
+ }),
732
+ // Block 2: Execute the dynamically built SQL query
733
+ new PostgreSQL("execute_search", "your-postgresql-integration-id", {
734
+ statement: ({ build_search_query }) => build_search_query.output
735
+ })
736
+ ]);
737
+ \`\`\`
738
+
739
+ **Why the Two-Block Pattern?**
740
+ - **SQL blocks can ONLY contain SQL** - no JavaScript logic allowed
741
+ - **JavaScript blocks build the dynamic query** based on conditions
742
+ - **SQL blocks execute the prepared query** from the JavaScript block
743
+ - This separation maintains clean language boundaries
744
+ `;
745
+ /**
746
+ * Error handling guidelines - when to use TryCatch
747
+ */
748
+ const ERROR_HANDLING_GUIDELINES = `
749
+ ## ⚠️ Error Handling: When to Use TryCatch
750
+
751
+ **IMPORTANT: Do NOT use TryCatch blocks by default. Only use them when truly necessary.**
752
+
753
+ Wrapping everything in try/catch adds unnecessary complexity that makes workflows harder to understand and debug.
754
+
755
+ ### ❌ DO NOT use TryCatch for:
756
+
757
+ 1. **Standard operations that should fail fast:**
758
+ \`\`\`typescript
759
+ // ❌ WRONG - Unnecessary try/catch for normal database query
760
+ new TryCatch("wrapped_query", {
761
+ try: [
762
+ new PostgreSQL("fetch_users", "postgres-id", {
763
+ statement: "SELECT * FROM users LIMIT 100"
764
+ })
765
+ ],
766
+ catch: [
767
+ new JavaScript("handle_error", {
768
+ fn: ({ err }) => ({ error: err.value })
769
+ })
770
+ ],
771
+ variables: { error: "err" }
772
+ })
773
+
774
+ // ✅ CORRECT - Let the query fail naturally if there's an issue
775
+ new PostgreSQL("fetch_users", "postgres-id", {
776
+ statement: "SELECT * FROM users LIMIT 100"
777
+ })
778
+ \`\`\`
779
+
780
+ 2. **Simple data transformations:**
781
+ \`\`\`typescript
782
+ // ❌ WRONG - Wrapping basic JavaScript logic
783
+ new TryCatch("safe_transform", {
784
+ try: [
785
+ new JavaScript("transform_data", {
786
+ fn: ({ userData }) => userData.output.map(u => u.name)
787
+ })
788
+ ],
789
+ catch: [
790
+ new Return("empty_array", { data: () => [] })
791
+ ],
792
+ variables: { error: "err" }
793
+ })
794
+
795
+ // ✅ CORRECT - Direct transformation
796
+ new JavaScript("transform_data", {
797
+ fn: ({ userData }) => userData.output.map(u => u.name)
798
+ })
799
+ \`\`\`
800
+
801
+ ### ✅ DO use TryCatch when:
802
+
803
+ 1. **User explicitly requests error handling**
804
+
805
+ 2. **Continuing execution after failure is business-critical:**
806
+ \`\`\`typescript
807
+ // ✅ Process must continue even if notification fails
808
+ new TryCatch("attempt_notification", {
809
+ try: [
810
+ new Email("send_notification", {
811
+ from: "noreply@example.com",
812
+ to: ({ userEmail }) => userEmail,
813
+ subject: "Order Confirmed",
814
+ body: "Your order has been confirmed"
815
+ })
816
+ ],
817
+ catch: [
818
+ new JavaScript("log_notification_failure", {
819
+ fn: ({ err }) => ({
820
+ emailFailed: true,
821
+ error: err.value.message
822
+ })
823
+ })
824
+ ],
825
+ variables: { error: "err" }
826
+ }),
827
+ // Continue processing regardless of email success
828
+ new JavaScript("finalize_order", {
829
+ fn: ({ orderData }) => ({ status: "complete" })
830
+ })
831
+ \`\`\`
832
+
833
+ 3. **Partial failure recovery in loops:**
834
+ \`\`\`typescript
835
+ // ✅ Process all items even if some fail
836
+ new Loop("process_all_orders", {
837
+ over: ({ orders }) => orders.output,
838
+ variables: { item: "order", index: "i" },
839
+ blocks: [
840
+ new TryCatch("safe_process", {
841
+ try: [
842
+ new RestApi("external_validation", "rest-id", {
843
+ method: "POST",
844
+ url: "https://validator.example.com/check",
845
+ body: ({ order }) => JSON.stringify(order.value)
846
+ })
847
+ ],
848
+ catch: [
849
+ new JavaScript("mark_failed", {
850
+ fn: ({ order, err }) => ({
851
+ orderId: order.value.id,
852
+ failed: true,
853
+ error: err.value
854
+ })
855
+ })
856
+ ],
857
+ variables: { error: "err" }
858
+ })
859
+ ]
860
+ })
861
+ \`\`\`
862
+
863
+ 4. **Graceful degradation with fallback data:**
864
+ \`\`\`typescript
865
+ // ✅ Use cached data if live fetch fails
866
+ new TryCatch("fetch_with_fallback", {
867
+ try: [
868
+ new RestApi("fetch_live_prices", "rest-id", {
869
+ method: "GET",
870
+ url: "https://api.example.com/prices"
871
+ })
872
+ ],
873
+ catch: [
874
+ new PostgreSQL("fetch_cached_prices", "postgres-id", {
875
+ statement: "SELECT * FROM cached_prices WHERE updated_at > NOW() - INTERVAL '1 hour'"
876
+ })
877
+ ],
878
+ variables: { error: "err" }
879
+ })
880
+ \`\`\`
881
+
882
+ ### General Rule:
883
+
884
+ **If you can't clearly articulate why the try/catch is necessary for business logic, don't use it.** Error messages are more helpful to users when they surface naturally rather than being caught and hidden.
885
+ `;
886
+ /**
887
+ * SQL best practices section
888
+ */
889
+ const SQL_BEST_PRACTICES = `
890
+ ## 📝 SQL Best Practices
891
+
892
+ ### 1. ONE Query Per Block Rule
893
+ Each SQL block (PostgreSQL, Snowflake, MySQL, MicrosoftSql, Databricks) can execute **ONLY ONE SQL query**.
894
+
895
+ ❌ **WRONG - Multiple queries in one block:**
896
+ \`\`\`sql
897
+ UPDATE users SET status = 'active';
898
+ DELETE FROM logs WHERE created < '2023-01-01';
899
+ INSERT INTO audit VALUES ('done');
900
+ \`\`\`
901
+
902
+ ✅ **CORRECT - One query per block:**
903
+ \`\`\`typescript
904
+ new PostgreSQL("update_status", "postgres-id", {
905
+ statement: "UPDATE users SET status = 'active'"
906
+ }),
907
+ new PostgreSQL("clean_logs", "postgres-id", {
908
+ statement: "DELETE FROM logs WHERE created < '2023-01-01'"
909
+ })
910
+ \`\`\`
911
+
912
+ ### 2. Sort, Don't Filter by Date (Default)
913
+ Do NOT add automatic date filters (e.g., "last 90 days") unless the user explicitly requests them. This is a common cause of unexpected empty SQL results.
914
+
915
+ ✅ **Default approach:**
916
+ \`\`\`sql
917
+ SELECT * FROM orders ORDER BY created_at DESC LIMIT 100;
918
+ \`\`\`
919
+
920
+ ❌ **Avoid automatic filtering:**
921
+ \`\`\`sql
922
+ SELECT * FROM orders WHERE created_at >= CURRENT_DATE - INTERVAL '90 days'; -- Can return empty results
923
+ \`\`\`
924
+
925
+ Only add date WHERE clauses when users explicitly ask for time-based filtering.
926
+
927
+ ### 3. Always Add Defensive LIMIT Clauses
928
+ Always include a LIMIT clause to prevent runaway queries. Use 100 as the default unless user specifies otherwise.
929
+
930
+ ✅ **Default approach:**
931
+ \`\`\`sql
932
+ SELECT * FROM orders ORDER BY created_at DESC LIMIT 100;
933
+ \`\`\`
934
+
935
+ ❌ **Avoid unlimited queries:**
936
+ \`\`\`sql
937
+ SELECT * FROM orders ORDER BY created_at DESC; -- Can timeout or crash
938
+ \`\`\`
939
+ `;
940
+ /**
941
+ * Database naming conventions
942
+ */
943
+ const DATABASE_NAMING_CONVENTIONS = `
944
+ ## 📊 Database Schema Naming Conventions
945
+
946
+ ### Databricks Three-Part Naming
947
+ Databricks uses a **three-part naming convention**: \`catalog.schema.table\`
948
+
949
+ When you see Databricks metadata like:
950
+ - \`uber.default.orders\` - Use the FULL path: \`uber.default.orders\`
951
+ - \`production.analytics.users\` - Use: \`production.analytics.users\`
952
+
953
+ **❌ WRONG for Databricks:**
954
+ \`\`\`sql
955
+ -- Metadata shows: uber.default.orders
956
+ SELECT * FROM uber.orders -- ❌ Missing schema part
957
+ SELECT * FROM orders -- ❌ Missing catalog and schema
958
+ \`\`\`
959
+
960
+ **✅ CORRECT for Databricks:**
961
+ \`\`\`sql
962
+ -- Always use the full three-part name
963
+ SELECT * FROM uber.default.orders -- ✅ Full path
964
+ SELECT * FROM catalog.schema.table -- ✅ Pattern
965
+ \`\`\`
966
+
967
+ **Note:** The word "default" in Databricks paths is NOT optional - it's the actual schema name. Always include all three parts exactly as shown in the metadata.
968
+
969
+ ### Snowflake Two-Part Naming
970
+ Snowflake uses **schema-qualified table names**: \`schema.table\`
971
+
972
+ When you see Snowflake metadata where tables have a \`schema\` property, **you MUST qualify table names**:
973
+
974
+ **Metadata structure:**
975
+ \`\`\`json
976
+ {
977
+ "schema": {
978
+ "tables": [
979
+ {
980
+ "name": "PRODUCTLINE",
981
+ "schema": "MASTERDATA",
982
+ "columns": [...]
983
+ }
984
+ ]
985
+ }
986
+ }
987
+ \`\`\`
988
+
989
+ **❌ WRONG for Snowflake:**
990
+ \`\`\`sql
991
+ -- Missing schema qualification
992
+ SELECT * FROM PRODUCTLINE -- ❌ Will fail if no default schema
993
+ \`\`\`
994
+
995
+ **✅ CORRECT for Snowflake:**
996
+ \`\`\`sql
997
+ -- Always use schema.table format when schema property exists
998
+ SELECT * FROM MASTERDATA.PRODUCTLINE -- ✅ Fully qualified
999
+ \`\`\`
1000
+
1001
+ **Rule**: If a table object has a non-empty \`schema\` property, use \`{schema}.{name}\` format in your SQL queries.
1002
+
1003
+ ### Traditional SQL Databases (PostgreSQL, MySQL, etc.)
1004
+ Traditional databases use **two-part naming**: \`schema.table\`
1005
+ - PostgreSQL: \`public.orders\` or just \`orders\`
1006
+ - MySQL: \`database.orders\` or just \`orders\`
1007
+ `;
1008
+ /**
1009
+ * Response interface guidelines
1010
+ */
1011
+ const RESPONSE_INTERFACE_GUIDELINES = `
1012
+ ## 📝 Response Interface for finalizeApi
1013
+
1014
+ The \`responseInterface\` describes what external code gets from \`apiName.response\`. Internal blocks/steps are NOT visible externally.
1015
+
1016
+ ### Direct Response Types
1017
+
1018
+ ✅ **CORRECT**: Direct array response
1019
+ \`\`\`typescript
1020
+ interface GetUsersApiResponse {
1021
+ id: number;
1022
+ name: string;
1023
+ email: string;
1024
+ }[]
1025
+ \`\`\`
1026
+
1027
+ ✅ **CORRECT**: Direct data structure
1028
+ \`\`\`typescript
1029
+ interface GetOrdersApiResponse {
1030
+ orders: Order[];
1031
+ totalCount: number;
1032
+ }
1033
+ \`\`\`
1034
+
1035
+ ❌ **WRONG**: Exposing internal steps
1036
+ \`\`\`typescript
1037
+ interface GetOrdersApiResponse {
1038
+ fetchStep: { output: Order[] }; // ❌ Steps are internal
1039
+ countStep: { output: number }; // ❌ Not visible outside
1040
+ }
1041
+ \`\`\`
1042
+
1043
+ ### Type Safety for API Response Interfaces
1044
+
1045
+ **CRITICAL: When defining response interfaces, consider runtime reality, not just happy-path data.**
1046
+
1047
+ #### Making Fields Optional
1048
+
1049
+ When uncertain if an API field will always be present, mark it optional:
1050
+
1051
+ ✅ **CORRECT** - Accounts for real-world API behavior:
1052
+ \`\`\`typescript
1053
+ interface GitHubPRResponse {
1054
+ id: number;
1055
+ title: string;
1056
+ user?: { // ← Optional, can be null for deleted users
1057
+ login: string;
1058
+ avatar_url: string;
1059
+ } | null;
1060
+ labels?: Label[]; // ← Optional, might be omitted in response
1061
+ }
1062
+ \`\`\`
1063
+
1064
+ ❌ **WRONG** - False confidence:
1065
+ \`\`\`typescript
1066
+ interface GitHubPRResponse {
1067
+ user: { // ← Marked required, but API can return null
1068
+ login: string;
1069
+ avatar_url: string;
1070
+ };
1071
+ }
1072
+ \`\`\`
1073
+
1074
+ #### When to Make Fields Optional
1075
+
1076
+ Mark fields optional when:
1077
+ 1. **User/account references** - Can be null for deleted/deactivated accounts
1078
+ 2. **Nested objects** - May be omitted in partial responses
1079
+ 3. **Third-party APIs** - GitHub, Stripe, etc. often have nullable fields
1080
+ 4. **Loading states** - Data may not be available during initial render
1081
+ 5. **Uncertain API behavior** - When in doubt, mark optional
1082
+
1083
+ This prevents downstream runtime errors when frontend code accesses these fields.
1084
+ `;
1085
+ /**
1086
+ * Runtime safety and defensive coding
1087
+ */
1088
+ const RUNTIME_SAFETY = `
1089
+ ## Runtime Safety and Defensive Coding (CRITICAL)
1090
+
1091
+ - Prefer safe access patterns that tolerate partial/missing data. When reading nested fields, assume null/undefined is possible unless guaranteed otherwise.
1092
+ - Use optional chaining and nullish coalescing when producing outputs that the frontend will consume; avoid throwing on missing optional fields.
1093
+ - For REST/OpenAPI/GraphQL responses, treat non-required fields as optional in interfaces. If unsure, mark as optional and document assumptions in finalize summary.
1094
+ - Avoid catching and suppressing unexpected errors with TryCatch unless explicitly asked; surface meaningful errors. Use validation (Conditional + Throw) for expected preconditions.
1095
+ - When transforming arrays or objects from external sources, default to empty arrays/objects when inputs are absent.
1096
+
1097
+ Examples:
1098
+ \`\`\`typescript
1099
+ // Optional fields
1100
+ type User = { id: number; name?: string | null };
1101
+
1102
+ // Defensive transformation
1103
+ new JavaScript("normalize_users", {
1104
+ fn: ({ fetch_users }) => (Array.isArray(fetch_users.output) ? fetch_users.output : []).map(u => ({
1105
+ id: u.id,
1106
+ name: (u.name ?? "Unknown").toString()
1107
+ }))
1108
+ })
1109
+
1110
+ // Guarded access
1111
+ new Conditional("validate_email", {
1112
+ if: {
1113
+ when: ({ EmailInput }) => !EmailInput,
1114
+ then: [new Throw("missing_email", { error: "Email is required" })]
1115
+ }
1116
+ })
1117
+ \`\`\`
1118
+ `;
1119
+ /**
1120
+ * Error recovery strategies
1121
+ */
1122
+ const ERROR_RECOVERY_STRATEGIES = `
1123
+ ## 🚨 Error Handling and Recovery
1124
+
1125
+ When you encounter errors while building APIs, follow these guidelines:
1126
+
1127
+ ### Read Error Messages Carefully
1128
+
1129
+ Error messages contain specific guidance on how to fix the problem. Pay close attention to:
1130
+ - What operation failed (compilation, validation, execution)
1131
+ - Suggestions for how to resolve the issue
1132
+ - Whether metadata is missing
1133
+
1134
+ ### When to Check Integration Metadata
1135
+
1136
+ If you encounter errors mentioning:
1137
+ - "unknown column", "table not found", "invalid field"
1138
+ - "check integration metadata"
1139
+ - Integration type mismatches
1140
+
1141
+ You MUST call \`readIntegrationMetadata\` to get the correct schema/table structure before retrying.
1142
+ `;
1143
+ /**
1144
+ * Loop control patterns
1145
+ */
1146
+ const LOOP_CONTROL = `
1147
+ ## 🔄 Loop Control
1148
+
1149
+ **Breaking out of loops:**
1150
+ \`\`\`typescript
1151
+ new Loop("process_until_complete", {
1152
+ over: ({ items }) => items.output,
1153
+ variables: { item: "current", index: "i" },
1154
+ blocks: [
1155
+ new Conditional("check_stop_condition", {
1156
+ if: {
1157
+ when: ({ current }) => current.value.status === "complete",
1158
+ then: [
1159
+ new Break("exit_loop", { condition: () => true }) // ✅ Only way to exit
1160
+ ]
1161
+ }
1162
+ }),
1163
+ new JavaScript("process_item", {
1164
+ fn: ({ current, i }) => ({
1165
+ processed: current.value,
1166
+ position: i.value
1167
+ })
1168
+ })
1169
+ ]
1170
+ })
1171
+ \`\`\`
1172
+ `;
1173
+ /**
1174
+ * API structure requirements
1175
+ */
1176
+ const API_STRUCTURE = `
1177
+ ## 🏗️ API Structure Requirements
1178
+
1179
+ ### File Structure
1180
+ \`\`\`typescript
1181
+ // Path: /apis/apiName.ts
1182
+
1183
+ // ✅ ALWAYS import the required types from the library
1184
+ import {
1185
+ Api,
1186
+ JavaScript,
1187
+ Python,
1188
+ Databricks,
1189
+ Snowflake,
1190
+ PostgreSQL,
1191
+ GraphQL,
1192
+ RestApi,
1193
+ S3,
1194
+ Email,
1195
+ Conditional,
1196
+ TryCatch,
1197
+ Loop,
1198
+ Throw,
1199
+ Return,
1200
+ Break,
1201
+ } from "@superblocksteam/library";
1202
+
1203
+ // ✅ Export default API with consistent naming
1204
+ export default new Api("apiName", [
1205
+ // Workflow blocks here
1206
+ ]);
1207
+ \`\`\`
1208
+
1209
+ ### Basic Workflow Structure
1210
+ \`\`\`typescript
1211
+ // 1. Input validation
1212
+ // 2. Data fetching (integrations)
1213
+ // 3. Data processing (JavaScript/Python)
1214
+ // 4. Error handling (Try/Catch)
1215
+ // 5. Return formatted output
1216
+ \`\`\`
1217
+ `;
1218
+ /**
1219
+ * Critical mistakes to avoid
1220
+ */
1221
+ const CRITICAL_MISTAKES = `
1222
+ ## 🚨 Critical Mistakes to Avoid
1223
+
1224
+ ### 1. OVERUSING TRYCATCH BLOCKS
1225
+ See the Error Handling section - only use TryCatch when truly necessary, not by default.
1226
+
1227
+ ### 2. WRONG LANGUAGE FOR INTEGRATION TYPE
1228
+
1229
+ ❌ **NEVER put JavaScript in PostgreSQL statement:**
1230
+ \`\`\`typescript
1231
+ new PostgreSQL("bad_query", "valid-postgres-id", {
1232
+ statement: ({ userId }) => \`SELECT * FROM users WHERE id = \${userId}\` // ❌ This is JavaScript!
1233
+ })
1234
+ \`\`\`
1235
+
1236
+ ❌ **NEVER put SQL in JavaScript fn:**
1237
+ \`\`\`typescript
1238
+ new JavaScript("bad_js", {
1239
+ fn: "SELECT * FROM users" // ❌ This is SQL, not JavaScript!
1240
+ })
1241
+ \`\`\`
1242
+
1243
+ ❌ **NEVER put multiple queries in one SQL block:**
1244
+ \`\`\`typescript
1245
+ new PostgreSQL("bad_multiple_queries", "postgres-id", {
1246
+ statement: \`
1247
+ UPDATE users SET status = 'active';
1248
+ DELETE FROM logs WHERE created < '2023-01-01';
1249
+ INSERT INTO audit VALUES ('done');
1250
+ \` // ❌ Multiple queries in one block will fail!
1251
+ })
1252
+ \`\`\`
1253
+
1254
+ ✅ **CORRECT Language Matching:**
1255
+ \`\`\`typescript
1256
+ // ✅ PostgreSQL gets SQL in statement with typed parameters
1257
+ new PostgreSQL("good_query", "your-postgresql-integration-id", {
1258
+ statement: ({ userId }: { userId: string }) => \`SELECT * FROM users WHERE id = '\${userId}'\`
1259
+ })
1260
+
1261
+ // ✅ JavaScript gets JavaScript function in fn with typed parameters
1262
+ new JavaScript("good_js", {
1263
+ fn: ({ userData }: { userData: Array<{ id: number; name: string; email: string }> }) =>
1264
+ userData.map(user => ({ id: user.id, name: user.name }))
1265
+ })
1266
+
1267
+ // ✅ Python gets Python string in fn (types in function signature)
1268
+ new Python("good_python", {
1269
+ fn: \`
1270
+ def main(userId: str) -> str:
1271
+ return f"Processing user {userId}"
1272
+ \`
1273
+ })
1274
+ \`\`\`
1275
+
1276
+ ### 3. Wrong Variable Access
1277
+ \`\`\`typescript
1278
+ // WRONG - accessing non-existent variables
1279
+ new JavaScript("bad_example", {
1280
+ fn: ({ SomeVariable }) => SomeVariable
1281
+ // ❌ SomeVariable must be provided as an input when the API is called!
1282
+ })
1283
+ \`\`\`
1284
+
1285
+ ### 4. Fake Integration IDs
1286
+ \`\`\`typescript
1287
+ // WRONG - making up integration IDs
1288
+ new PostgreSQL("query", "fake-postgres-id", { // ❌ Never do this!
1289
+ statement: "SELECT * FROM users"
1290
+ })
1291
+ \`\`\`
1292
+
1293
+ ### 5. APIs Cannot Set Frontend State
1294
+ APIs are backend workflows that can only READ state, never SET it. State mutations MUST happen on the frontend.
1295
+
1296
+ ❌ **NEVER attempt to set state inside API blocks:**
1297
+ \`\`\`typescript
1298
+ new JavaScript("update_data", {
1299
+ fn: ({ userData }) => {
1300
+ userNameVar.value = userData.name; // ❌ CANNOT set state here!
1301
+ selectedUserVar.value = userData; // ❌ CANNOT set state here!
1302
+ UserInput.value = userData.email; // ❌ CANNOT set component values here!
1303
+ return userData;
1304
+ }
1305
+ })
1306
+ \`\`\`
1307
+
1308
+ ✅ **CORRECT: APIs return data, frontend handles state updates:**
1309
+ \`\`\`typescript
1310
+ new JavaScript("update_data", {
1311
+ fn: ({ userData }) => {
1312
+ // Process data, perform calculations, transformations
1313
+ const processedUser = {
1314
+ ...userData,
1315
+ fullName: \`\${userData.firstName} \${userData.lastName}\`,
1316
+ lastUpdated: new Date().toISOString()
1317
+ };
1318
+ return processedUser; // Frontend will handle state updates in onSuccess
1319
+ }
1320
+ })
1321
+ \`\`\`
1322
+ `;
1323
+ /**
1324
+ * API checklist
1325
+ */
1326
+ const API_CHECKLIST = `
1327
+ ## 📝 API Checklist
1328
+
1329
+ When creating APIs, you MUST follow this mental checklist:
1330
+
1331
+ 1. **CORRECT LANGUAGE FOR EACH INTEGRATION** - SQL for PostgreSQL/Redshift/Snowflake, JavaScript for JavaScript blocks, Python strings for Python blocks
1332
+ 2. **CORRECT CLASS FOR REST APIs** - Use \`OpenApi\` class with \`openapi.path\` when \`grepMetadata\` shows OpenAPI spec exists, otherwise use \`RestApi\`
1333
+ 3. All imports included
1334
+ 4. Correct variable access patterns (.value, .output, and .output.data for GraphQL)
1335
+ 5. No fake or placeholder integration IDs
1336
+ 6. No placeholder logic
1337
+ 7. Descriptive block names
1338
+ 8. Error handling where appropriate - **avoid TryCatch blocks unless truly necessary**
1339
+ 9. Consistent naming across the API
1340
+ 10. NEVER change the API name when editing an existing API. Even if the prompt suggests another name, you must leave it as-is, or the API will break.
1341
+ 11. **ALWAYS** test the API after building to ensure it works as expected before moving on to other work.
1342
+ 12. Response interface describes ONLY what's available as \`apiName.response\` - no internal steps
1343
+
1344
+ Remember: Superblocks APIs are reactive workflow builders that transform inputs into backend operations. Keep them declarative and focused.
1345
+ `;
1346
+ /**
1347
+ * Core documentation that applies to all APIs - now much more comprehensive
1348
+ */
1349
+ const CORE_DOCUMENTATION = `# Superblocks API Documentation
1350
+
1351
+ ## Mental Model
1352
+
1353
+ APIs in Superblocks are backend logic blocks that run in a secure server environment. They:
1354
+ - Execute integrations (database queries, API calls, etc.)
1355
+ - Process data with JavaScript or Python
1356
+ - Return data to the frontend
1357
+ - Cannot directly modify UI state
1358
+
1359
+ **Superblocks APIs are NOT traditional backend services.** They are frontend-coupled workflow builders that:
1360
+ - **Build declarative workflows** - using a chain of blocks to provide I/O and control flow
1361
+ - **Access inputs the user provides when they call the API from the frontend** - APIs receive input parameters passed from the application
1362
+ - **Are visualized in the Superblocks editor** - APIs are represented in the Superblocks UI in a way that any user can understand
1363
+
1364
+ ## 🚨 Critical Rules
1365
+
1366
+ ### 1. Language Must Match Integration Type
1367
+
1368
+ **NEVER mix languages between integration types. This is the #1 cause of API failures.**
1369
+
1370
+ - **SQL integrations** (PostgreSQL, MySQL, Snowflake, etc.): Use SQL syntax
1371
+ - **JavaScript blocks**: Use JavaScript/TypeScript syntax
1372
+ - **Python blocks**: Use Python syntax
1373
+ - **REST/GraphQL**: Use appropriate query languages
1374
+
1375
+ **The API will completely fail if you provide the wrong language to an integration.**
1376
+
1377
+ ### 2. Variable Scoping
1378
+
1379
+ Variables referenced in API blocks can ONLY come from these sources:
1380
+ - **Outputs of previous blocks** in the same API (accessed via block name)
1381
+ - **Inputs from the user calling the API in their app** (passed as destructured parameters)
1382
+
1383
+ Important: Input variables from the frontend are GLOBAL for all API blocks. Do not shadow user input variables with local variables in your code.
1384
+
1385
+ ### 4. Block Execution Order
1386
+ - Blocks execute sequentially from top to bottom
1387
+ - Each block can access outputs from previous blocks
1388
+ - Use control flow blocks (Loop, Conditional, Try/Catch) for complex logic
1389
+
1390
+ ### 5. GraphQL Output Structure
1391
+ GraphQL steps return \`{ data: {...}, errors?: [...] }\`. Access query results via \`stepName.output.data\`, not \`stepName.output\` directly.
1392
+
1393
+ ## ✅ Best Practices
1394
+
1395
+ 1. **Single Responsibility**: Each API should do one thing well
1396
+ 2. **Clear Naming**: Use descriptive names for blocks and APIs
1397
+ 3. **Input Validation**: Validate inputs early in the API
1398
+ 4. **Error Boundaries**: Use Try/Catch for external operations (but only when truly necessary)
1399
+ 5. **Documentation**: Comment complex logic
1400
+ 6. **Performance**: Minimize database round trips
1401
+ 7. **Security**: Never expose sensitive data in responses
1402
+ 8. **Reasonable Guardrails**: Use LIMIT clauses in SQL queries, validate input ranges
1403
+ 9. **Plan the workflow**: Think through the sequence of operations before coding
1404
+ 10. **No placeholder logic**: Always implement real functionality
1405
+
1406
+ ## Parallel Generation
1407
+
1408
+ Whenever you have multiple APIs to create, parallelize the tool calls as much as possible to minimize latency.
1409
+ `;
1410
+ /**
1411
+ * Get documentation for built-in blocks (JavaScript and Python)
1412
+ */
1413
+ function getBuiltInBlockDocumentation() {
1414
+ return `## Built-in Blocks
1415
+
1416
+ ### JavaScript Blocks
1417
+
1418
+ JavaScript blocks execute code directly in the API runtime environment. They're used for data transformation, validation, and business logic.
1419
+
1420
+ #### TypeScript Definition
1421
+ \`\`\`typescript
1422
+ export class JavaScript extends Integration {
1423
+ constructor(
1424
+ name: string,
1425
+ config: {
1426
+ fn: (state: State) => any; // Function that receives state with all previous blocks
1427
+ }
1428
+ );
1429
+ }
1430
+ \`\`\`
1431
+
1432
+ #### Usage Pattern
1433
+ \`\`\`typescript
1434
+ new JavaScript("TransformData", {
1435
+ fn: ({ GetUsers, statusFilter }) => {
1436
+ // Access previous block outputs directly
1437
+ const users = GetUsers.output;
1438
+
1439
+ // Access frontend variables
1440
+ const status = statusFilter.value;
1441
+
1442
+ // Transform and return data
1443
+ return users
1444
+ .filter(user => user.status === status)
1445
+ .map(user => ({
1446
+ ...user,
1447
+ fullName: \`\${user.firstName} \${user.lastName}\`
1448
+ }));
1449
+ }
1450
+ })
1451
+ \`\`\`
1452
+
1453
+ #### Key Points
1454
+ - Use \`fn\` property with a JavaScript function
1455
+ - Access previous blocks via destructured parameters
1456
+ - Can access frontend variables in the same way
1457
+ - Return value becomes the block's output
1458
+ - Supports async/await for asynchronous operations
1459
+
1460
+ ### Python Blocks
1461
+
1462
+ Python blocks execute Python code strings. They're ideal for data science operations, complex calculations, and when Python libraries are needed.
1463
+
1464
+ #### TypeScript Definition
1465
+ \`\`\`typescript
1466
+ export class Python extends Integration {
1467
+ constructor(
1468
+ name: string,
1469
+ config: {
1470
+ fn: string; // Python code as a string
1471
+ }
1472
+ );
1473
+ }
1474
+ \`\`\`
1475
+
1476
+ #### Usage Pattern
1477
+ \`\`\`typescript
1478
+ new Python("AnalyzeData", {
1479
+ fn: \`
1480
+ def main(GetUsers, statusFilter):
1481
+ import pandas as pd
1482
+
1483
+ # Access previous block outputs directly
1484
+ users = GetUsers['output']
1485
+
1486
+ # Access input parameters directly
1487
+ status = statusFilter
1488
+
1489
+ # Convert to DataFrame
1490
+ df = pd.DataFrame(users)
1491
+
1492
+ # Filter by status
1493
+ df_filtered = df[df['status'] == status]
1494
+
1495
+ # Perform analysis
1496
+ summary = {
1497
+ 'total_count': len(df_filtered),
1498
+ 'avg_age': df_filtered['age'].mean(),
1499
+ 'status_distribution': df_filtered['status'].value_counts().to_dict()
1500
+ }
1501
+
1502
+ # Return as JSON-serializable object
1503
+ return summary
1504
+ \`
1505
+ })
1506
+ \`\`\`
1507
+
1508
+ #### Key Points
1509
+ - Use \`fn\` property with a Python code string containing a \`main\` function
1510
+ - Access previous blocks and inputs as function parameters
1511
+ - Previous block outputs accessed as \`blockName['output']\`
1512
+ - Input parameters accessed directly (no \`.value\` needed)
1513
+ - Must return JSON-serializable data
1514
+ - Common libraries available: pandas, numpy, scipy, etc.
1515
+ - DON'T FORGET to return the result using the \`return\` statement
1516
+
1517
+ ### 🚨 Critical: Never Mix Languages
1518
+
1519
+ **CORRECT:**
1520
+ - JavaScript block: \`fn: ({ data }) => data.map(...)\`
1521
+ - Python block: \`fn: "import pandas as pd\\ndf = pd.DataFrame(data)"\`
1522
+ - SQL block: \`statement: "SELECT * FROM users"\`
1523
+
1524
+ **INCORRECT:**
1525
+ - JavaScript block with Python: \`fn: "import pandas"\` ❌
1526
+ - Python block with JavaScript: \`fn: ({ data }) => ...\` ❌
1527
+ - SQL block with JavaScript: \`statement: "users.map(u => u.id)"\` ❌`;
1528
+ }
1529
+ /**
1530
+ * Get integration-specific documentation based on plugin type
1531
+ */
1532
+ function getIntegrationSpecificDocs(pluginId) {
1533
+ const specialDocs = {
1534
+ snowflake: `### Snowflake Specific Patterns
1535
+ - Use two-part naming: \`schema.table\` or \`"SCHEMA"."TABLE"\`
1536
+ - Case sensitivity: Unquoted identifiers are uppercase
1537
+ - Use \`FLATTEN\` for JSON data
1538
+ - Leverage warehouse-specific settings when needed`,
1539
+ databricks: `### Databricks Specific Patterns
1540
+ - Use three-part naming: \`catalog.schema.table\`
1541
+ - Default catalog is 'main' if not specified
1542
+ - Supports both SQL and Python notebooks
1543
+ - Use Unity Catalog for governance`,
1544
+ postgres: `### PostgreSQL Specific Patterns
1545
+ - Use schema-qualified names: \`schema.table\` or \`"schema"."table"\`
1546
+ - Case sensitivity: Unquoted identifiers are lowercase
1547
+ - Use \`::type\` for type casting
1548
+ - Leverage JSONB operators for JSON data`,
1549
+ mongodb: `### MongoDB Specific Patterns
1550
+ - Use proper operation names: find, insertOne, updateMany, etc.
1551
+ - Structure queries as JSON objects
1552
+ - Use aggregation pipelines for complex queries
1553
+ - Remember to specify the collection name`,
1554
+ };
1555
+ return specialDocs[pluginId] || "";
1556
+ }
1557
+ /**
1558
+ * Build documentation for specific integrations including TypeScript types
1559
+ */
1560
+ function buildIntegrationDocumentation(integrationIds, services) {
1561
+ const sections = [];
1562
+ const processedPluginIds = new Set();
1563
+ for (const integrationId of integrationIds) {
1564
+ // Get integration header from store
1565
+ const header = services.integrationStore.getHeader(integrationId);
1566
+ if (!header) {
1567
+ continue;
1568
+ }
1569
+ const plugin = header.plugin;
1570
+ // Avoid duplicating docs for same plugin type
1571
+ if (processedPluginIds.has(plugin.id)) {
1572
+ continue;
1573
+ }
1574
+ processedPluginIds.add(plugin.id);
1575
+ // Get TypeScript type definition
1576
+ const typeDef = getIntegrationTypeDefinition(plugin);
1577
+ if (!typeDef) {
1578
+ continue;
1579
+ }
1580
+ // Build section for this integration
1581
+ const integrationSection = [
1582
+ `## ${typeDef.className} Integration`,
1583
+ "",
1584
+ `**Integration ID**: \`${integrationId}\``,
1585
+ `**Plugin Type**: ${plugin.id}`,
1586
+ `**Description**: ${typeDef.description}`,
1587
+ "",
1588
+ "### TypeScript Type Definition",
1589
+ "```typescript",
1590
+ typeDef.typeDefinition,
1591
+ "```",
1592
+ "",
1593
+ ];
1594
+ // Add example if available
1595
+ if (typeDef.example) {
1596
+ integrationSection.push("### Example Usage", "```typescript", typeDef.example, "```", "");
1597
+ }
1598
+ // Add integration-specific patterns/rules
1599
+ const specificDocs = getIntegrationSpecificDocs(plugin.id);
1600
+ if (specificDocs) {
1601
+ integrationSection.push(specificDocs, "");
1602
+ }
1603
+ sections.push(integrationSection.join("\n"));
1604
+ }
1605
+ return sections.join("\n\n");
1606
+ }
1607
+ /**
1608
+ * Get relevant examples based on integration types
1609
+ */
1610
+ function getRelevantExamples(integrationIds, services) {
1611
+ const tags = [];
1612
+ const pluginTypes = new Set();
1613
+ // Collect plugin types from integration IDs
1614
+ for (const integrationId of integrationIds) {
1615
+ const header = services.integrationStore.getHeader(integrationId);
1616
+ if (header) {
1617
+ pluginTypes.add(header.plugin.id);
1618
+ }
1619
+ }
1620
+ // Map plugin types to relevant tags
1621
+ if (pluginTypes.has("snowflake"))
1622
+ tags.push("snowflake");
1623
+ if (pluginTypes.has("databricks"))
1624
+ tags.push("databricks");
1625
+ if (pluginTypes.has("postgres") ||
1626
+ pluginTypes.has("mysql") ||
1627
+ pluginTypes.has("mssql")) {
1628
+ tags.push("sql-query");
1629
+ }
1630
+ if (pluginTypes.size > 1)
1631
+ tags.push("multi-integration");
1632
+ // If no integrations provided, default to data transformation examples
1633
+ if (integrationIds.length === 0) {
1634
+ tags.push("data-transformation", "variable-access");
1635
+ }
1636
+ // Always include some common patterns
1637
+ tags.push("error-handling", "variable-access");
1638
+ // Select and format examples
1639
+ const selectedExamples = selectExamplesByTags(tags, {
1640
+ maxExamples: 3,
1641
+ includeNegative: true,
1642
+ maxTokenBudget: 3000,
1643
+ });
1644
+ // If no examples were selected, use a fallback example
1645
+ if (selectedExamples.length === 0) {
1646
+ // Find a basic data transformation example as fallback
1647
+ const fallbackExample = POSITIVE_EXAMPLES.find((ex) => ex.metadata.tags.includes("data-transformation") &&
1648
+ ex.metadata.tags.includes("variable-access")) || POSITIVE_EXAMPLES[0]; // Ultimate fallback to first example
1649
+ if (fallbackExample) {
1650
+ // Create metadata object with id for formatting
1651
+ const fallbackMetadata = {
1652
+ id: fallbackExample.id,
1653
+ ...fallbackExample.metadata,
1654
+ };
1655
+ const formattedFallback = formatSelectedExamples([fallbackMetadata]);
1656
+ return `## Relevant Examples
1657
+
1658
+ ${formattedFallback}`;
1659
+ }
1660
+ }
1661
+ const formattedExamples = formatSelectedExamples(selectedExamples);
1662
+ return `## Relevant Examples
1663
+
1664
+ ${formattedExamples}`;
1665
+ }
1666
+ export const getApiDocsToolFactory = createToolFactory("getApiDocs", (_clark, services) => ({
1667
+ category: ToolCategory.API,
1668
+ readOnly: true,
1669
+ description: `
1670
+ Retrieve comprehensive API development documentation with TypeScript type definitions and examples.
1671
+
1672
+ This tool provides:
1673
+ - Core API development rules and best practices
1674
+ - Complete TypeScript type definitions for all blocks and integrations
1675
+ - Integration exploration workflow (grepMetadata patterns)
1676
+ - Block output scoping rules
1677
+ - Common API patterns including dynamic SQL two-block pattern
1678
+ - Error handling and TryCatch usage guidelines
1679
+ - SQL best practices (LIMIT, no auto date filtering, one query per block)
1680
+ - Database naming conventions (Databricks, Snowflake, PostgreSQL)
1681
+ - Response interface guidelines
1682
+ - Runtime safety and defensive coding patterns
1683
+ - Integration-specific patterns and syntax rules
1684
+ - Relevant code examples based on integration types
1685
+
1686
+ ALWAYS call this before building or modifying APIs to ensure you follow the correct patterns.
1687
+ `,
1688
+ inputSchema: z.object({
1689
+ integrationIds: z
1690
+ .array(z.string())
1691
+ .describe("Integration IDs to include type definitions and specific documentation for. Pass the actual integration IDs from your page context.")
1692
+ .optional(),
1693
+ sections: z
1694
+ .array(z.enum([
1695
+ "core",
1696
+ "types",
1697
+ "integration-workflow",
1698
+ "scoping",
1699
+ "patterns",
1700
+ "error-handling",
1701
+ "sql-best-practices",
1702
+ "database-naming",
1703
+ "response-interface",
1704
+ "runtime-safety",
1705
+ "error-recovery",
1706
+ "loop-control",
1707
+ "api-structure",
1708
+ "critical-mistakes",
1709
+ "checklist",
1710
+ "built-in-blocks",
1711
+ "examples",
1712
+ ]))
1713
+ .optional()
1714
+ .describe("Specific sections to include. If not specified, all sections are included."),
1715
+ verbosity: z
1716
+ .enum(["minimal", "standard", "comprehensive"])
1717
+ .optional()
1718
+ .describe("Level of detail to include. Defaults to comprehensive."),
1719
+ }),
1720
+ execute: async ({ integrationIds = [], sections, verbosity = "comprehensive", }) => {
1721
+ const documentationSections = {
1722
+ core: CORE_DOCUMENTATION,
1723
+ types: TYPE_DEFINITIONS,
1724
+ "integration-workflow": INTEGRATION_EXPLORATION_WORKFLOW,
1725
+ scoping: BLOCK_OUTPUT_SCOPING_RULES,
1726
+ "input-discovery": INPUT_DISCOVERY_RULES,
1727
+ patterns: COMMON_API_PATTERNS,
1728
+ "error-handling": ERROR_HANDLING_GUIDELINES,
1729
+ "sql-best-practices": SQL_BEST_PRACTICES,
1730
+ "database-naming": DATABASE_NAMING_CONVENTIONS,
1731
+ "response-interface": RESPONSE_INTERFACE_GUIDELINES,
1732
+ "runtime-safety": RUNTIME_SAFETY,
1733
+ "error-recovery": ERROR_RECOVERY_STRATEGIES,
1734
+ "loop-control": LOOP_CONTROL,
1735
+ "api-structure": API_STRUCTURE,
1736
+ "critical-mistakes": CRITICAL_MISTAKES,
1737
+ checklist: API_CHECKLIST,
1738
+ "built-in-blocks": getBuiltInBlockDocumentation(),
1739
+ };
1740
+ // Determine which sections to include
1741
+ let sectionsToInclude = [];
1742
+ if (sections && sections.length > 0) {
1743
+ // Use only specified sections
1744
+ sectionsToInclude = sections;
1745
+ }
1746
+ else {
1747
+ // Include sections based on verbosity
1748
+ switch (verbosity) {
1749
+ case "minimal":
1750
+ sectionsToInclude = ["core", "critical-mistakes", "checklist"];
1751
+ break;
1752
+ case "standard":
1753
+ sectionsToInclude = [
1754
+ "core",
1755
+ "integration-workflow",
1756
+ "scoping",
1757
+ "input-discovery",
1758
+ "patterns",
1759
+ "error-handling",
1760
+ "sql-best-practices",
1761
+ "database-naming",
1762
+ "critical-mistakes",
1763
+ "checklist",
1764
+ ];
1765
+ break;
1766
+ case "comprehensive":
1767
+ default:
1768
+ sectionsToInclude = Object.keys(documentationSections);
1769
+ break;
1770
+ }
1771
+ }
1772
+ // Build documentation sections
1773
+ const outputSections = [];
1774
+ // Add requested sections, but handle built-in-blocks specially
1775
+ for (const section of sectionsToInclude) {
1776
+ // Skip built-in-blocks if integrations are provided, unless explicitly requested
1777
+ if (section === "built-in-blocks" &&
1778
+ integrationIds.length > 0 &&
1779
+ (!sections || !sections.includes("built-in-blocks"))) {
1780
+ continue;
1781
+ }
1782
+ if (documentationSections[section]) {
1783
+ outputSections.push(documentationSections[section]);
1784
+ }
1785
+ }
1786
+ // Add integration-specific documentation if integrationIds provided
1787
+ if (integrationIds.length > 0) {
1788
+ const integrationDocs = buildIntegrationDocumentation(integrationIds, services);
1789
+ if (integrationDocs) {
1790
+ outputSections.push(integrationDocs);
1791
+ }
1792
+ }
1793
+ // Always add relevant examples if requested or in comprehensive mode
1794
+ if (sectionsToInclude.includes("examples") ||
1795
+ verbosity === "comprehensive") {
1796
+ const examples = getRelevantExamples(integrationIds, services);
1797
+ if (examples) {
1798
+ outputSections.push(examples);
1799
+ }
1800
+ }
1801
+ return {
1802
+ documentation: outputSections.filter(Boolean).join("\n\n---\n\n"),
1803
+ integrationCount: integrationIds.length,
1804
+ sectionsIncluded: sectionsToInclude,
1805
+ verbosity,
1806
+ };
1807
+ },
1808
+ }));
1809
+ //# sourceMappingURL=get-api-docs.js.map