beddel 0.1.0

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 (236) hide show
  1. package/README.md +297 -0
  2. package/dist/agents/agentRegistry.d.ts +68 -0
  3. package/dist/agents/agentRegistry.d.ts.map +1 -0
  4. package/dist/agents/agentRegistry.js +222 -0
  5. package/dist/agents/agentRegistry.js.map +1 -0
  6. package/dist/agents/formatter-agent.d.ts +10 -0
  7. package/dist/agents/formatter-agent.d.ts.map +1 -0
  8. package/dist/agents/formatter-agent.js +49 -0
  9. package/dist/agents/formatter-agent.js.map +1 -0
  10. package/dist/agents/genkit-agent.d.ts +12 -0
  11. package/dist/agents/genkit-agent.d.ts.map +1 -0
  12. package/dist/agents/genkit-agent.js +119 -0
  13. package/dist/agents/genkit-agent.js.map +1 -0
  14. package/dist/agents/i18n-messages.d.ts +17 -0
  15. package/dist/agents/i18n-messages.d.ts.map +1 -0
  16. package/dist/agents/i18n-messages.js +92 -0
  17. package/dist/agents/i18n-messages.js.map +1 -0
  18. package/dist/agents/index.d.ts +10 -0
  19. package/dist/agents/index.d.ts.map +1 -0
  20. package/dist/agents/index.js +26 -0
  21. package/dist/agents/index.js.map +1 -0
  22. package/dist/agents/pipeline.d.ts +15 -0
  23. package/dist/agents/pipeline.d.ts.map +1 -0
  24. package/dist/agents/pipeline.js +45 -0
  25. package/dist/agents/pipeline.js.map +1 -0
  26. package/dist/agents/schema-factory.d.ts +40 -0
  27. package/dist/agents/schema-factory.d.ts.map +1 -0
  28. package/dist/agents/schema-factory.js +121 -0
  29. package/dist/agents/schema-factory.js.map +1 -0
  30. package/dist/agents/translation-validators.d.ts +26 -0
  31. package/dist/agents/translation-validators.d.ts.map +1 -0
  32. package/dist/agents/translation-validators.js +77 -0
  33. package/dist/agents/translation-validators.js.map +1 -0
  34. package/dist/agents/translator-agents.d.ts +184 -0
  35. package/dist/agents/translator-agents.d.ts.map +1 -0
  36. package/dist/agents/translator-agents.js +613 -0
  37. package/dist/agents/translator-agents.js.map +1 -0
  38. package/dist/agents/types/translation.types.d.ts +100 -0
  39. package/dist/agents/types/translation.types.d.ts.map +1 -0
  40. package/dist/agents/types/translation.types.js +3 -0
  41. package/dist/agents/types/translation.types.js.map +1 -0
  42. package/dist/agents/validator-agent.d.ts +42 -0
  43. package/dist/agents/validator-agent.d.ts.map +1 -0
  44. package/dist/agents/validator-agent.js +122 -0
  45. package/dist/agents/validator-agent.js.map +1 -0
  46. package/dist/audit/auditTrail.d.ts +55 -0
  47. package/dist/audit/auditTrail.d.ts.map +1 -0
  48. package/dist/audit/auditTrail.js +93 -0
  49. package/dist/audit/auditTrail.js.map +1 -0
  50. package/dist/compliance/gdprEngine.d.ts +44 -0
  51. package/dist/compliance/gdprEngine.d.ts.map +1 -0
  52. package/dist/compliance/gdprEngine.js +178 -0
  53. package/dist/compliance/gdprEngine.js.map +1 -0
  54. package/dist/compliance/lgpdEngine.d.ts +51 -0
  55. package/dist/compliance/lgpdEngine.d.ts.map +1 -0
  56. package/dist/compliance/lgpdEngine.js +221 -0
  57. package/dist/compliance/lgpdEngine.js.map +1 -0
  58. package/dist/config.d.ts +78 -0
  59. package/dist/config.d.ts.map +1 -0
  60. package/dist/config.js +77 -0
  61. package/dist/config.js.map +1 -0
  62. package/dist/errors.d.ts +17 -0
  63. package/dist/errors.d.ts.map +1 -0
  64. package/dist/errors.js +40 -0
  65. package/dist/errors.js.map +1 -0
  66. package/dist/firebase/tenantManager.d.ts +84 -0
  67. package/dist/firebase/tenantManager.d.ts.map +1 -0
  68. package/dist/firebase/tenantManager.js +378 -0
  69. package/dist/firebase/tenantManager.js.map +1 -0
  70. package/dist/index.d.ts +36 -0
  71. package/dist/index.d.ts.map +1 -0
  72. package/dist/index.js +118 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/integration/secure-yaml-runtime.d.ts +68 -0
  75. package/dist/integration/secure-yaml-runtime.d.ts.map +1 -0
  76. package/dist/integration/secure-yaml-runtime.js +245 -0
  77. package/dist/integration/secure-yaml-runtime.js.map +1 -0
  78. package/dist/parser/secure-yaml-parser.d.ts +62 -0
  79. package/dist/parser/secure-yaml-parser.d.ts.map +1 -0
  80. package/dist/parser/secure-yaml-parser.js +234 -0
  81. package/dist/parser/secure-yaml-parser.js.map +1 -0
  82. package/dist/performance/autoscaling.d.ts +100 -0
  83. package/dist/performance/autoscaling.d.ts.map +1 -0
  84. package/dist/performance/autoscaling.js +339 -0
  85. package/dist/performance/autoscaling.js.map +1 -0
  86. package/dist/performance/benchmark.d.ts +104 -0
  87. package/dist/performance/benchmark.d.ts.map +1 -0
  88. package/dist/performance/benchmark.js +514 -0
  89. package/dist/performance/benchmark.js.map +1 -0
  90. package/dist/performance/index.d.ts +14 -0
  91. package/dist/performance/index.d.ts.map +1 -0
  92. package/dist/performance/index.js +35 -0
  93. package/dist/performance/index.js.map +1 -0
  94. package/dist/performance/monitor.d.ts +126 -0
  95. package/dist/performance/monitor.d.ts.map +1 -0
  96. package/dist/performance/monitor.js +324 -0
  97. package/dist/performance/monitor.js.map +1 -0
  98. package/dist/performance/streaming.d.ts +82 -0
  99. package/dist/performance/streaming.d.ts.map +1 -0
  100. package/dist/performance/streaming.js +287 -0
  101. package/dist/performance/streaming.js.map +1 -0
  102. package/dist/runtime/audit.d.ts +240 -0
  103. package/dist/runtime/audit.d.ts.map +1 -0
  104. package/dist/runtime/audit.js +641 -0
  105. package/dist/runtime/audit.js.map +1 -0
  106. package/dist/runtime/declarativeAgentRuntime.d.ts +123 -0
  107. package/dist/runtime/declarativeAgentRuntime.d.ts.map +1 -0
  108. package/dist/runtime/declarativeAgentRuntime.js +576 -0
  109. package/dist/runtime/declarativeAgentRuntime.js.map +1 -0
  110. package/dist/runtime/isolatedRuntime.d.ts +119 -0
  111. package/dist/runtime/isolatedRuntime.d.ts.map +1 -0
  112. package/dist/runtime/isolatedRuntime.js +425 -0
  113. package/dist/runtime/isolatedRuntime.js.map +1 -0
  114. package/dist/runtime/schemaCompiler.d.ts +35 -0
  115. package/dist/runtime/schemaCompiler.d.ts.map +1 -0
  116. package/dist/runtime/schemaCompiler.js +151 -0
  117. package/dist/runtime/schemaCompiler.js.map +1 -0
  118. package/dist/runtime/simpleRuntime.d.ts +57 -0
  119. package/dist/runtime/simpleRuntime.d.ts.map +1 -0
  120. package/dist/runtime/simpleRuntime.js +187 -0
  121. package/dist/runtime/simpleRuntime.js.map +1 -0
  122. package/dist/security/dashboard.d.ts +89 -0
  123. package/dist/security/dashboard.d.ts.map +1 -0
  124. package/dist/security/dashboard.js +300 -0
  125. package/dist/security/dashboard.js.map +1 -0
  126. package/dist/security/hardening.d.ts +130 -0
  127. package/dist/security/hardening.d.ts.map +1 -0
  128. package/dist/security/hardening.js +414 -0
  129. package/dist/security/hardening.js.map +1 -0
  130. package/dist/security/index.d.ts +128 -0
  131. package/dist/security/index.d.ts.map +1 -0
  132. package/dist/security/index.js +353 -0
  133. package/dist/security/index.js.map +1 -0
  134. package/dist/security/monitor.d.ts +88 -0
  135. package/dist/security/monitor.d.ts.map +1 -0
  136. package/dist/security/monitor.js +356 -0
  137. package/dist/security/monitor.js.map +1 -0
  138. package/dist/security/scanner.d.ts +104 -0
  139. package/dist/security/scanner.d.ts.map +1 -0
  140. package/dist/security/scanner.js +298 -0
  141. package/dist/security/scanner.js.map +1 -0
  142. package/dist/security/score.d.ts +150 -0
  143. package/dist/security/score.d.ts.map +1 -0
  144. package/dist/security/score.js +983 -0
  145. package/dist/security/score.js.map +1 -0
  146. package/dist/security/test-security.d.ts +22 -0
  147. package/dist/security/test-security.d.ts.map +1 -0
  148. package/dist/security/test-security.js +154 -0
  149. package/dist/security/test-security.js.map +1 -0
  150. package/dist/security/threatDetector.d.ts +39 -0
  151. package/dist/security/threatDetector.d.ts.map +1 -0
  152. package/dist/security/threatDetector.js +354 -0
  153. package/dist/security/threatDetector.js.map +1 -0
  154. package/dist/security/validation.d.ts +69 -0
  155. package/dist/security/validation.d.ts.map +1 -0
  156. package/dist/security/validation.js +286 -0
  157. package/dist/security/validation.js.map +1 -0
  158. package/dist/server/api/clientsRoute.d.ts +9 -0
  159. package/dist/server/api/clientsRoute.d.ts.map +1 -0
  160. package/dist/server/api/clientsRoute.js +71 -0
  161. package/dist/server/api/clientsRoute.js.map +1 -0
  162. package/dist/server/api/endpointsRoute.d.ts +8 -0
  163. package/dist/server/api/endpointsRoute.d.ts.map +1 -0
  164. package/dist/server/api/endpointsRoute.js +76 -0
  165. package/dist/server/api/endpointsRoute.js.map +1 -0
  166. package/dist/server/api/graphql.d.ts +9 -0
  167. package/dist/server/api/graphql.d.ts.map +1 -0
  168. package/dist/server/api/graphql.js +180 -0
  169. package/dist/server/api/graphql.js.map +1 -0
  170. package/dist/server/errors.d.ts +19 -0
  171. package/dist/server/errors.d.ts.map +1 -0
  172. package/dist/server/errors.js +42 -0
  173. package/dist/server/errors.js.map +1 -0
  174. package/dist/server/index.d.ts +7 -0
  175. package/dist/server/index.d.ts.map +1 -0
  176. package/dist/server/index.js +24 -0
  177. package/dist/server/index.js.map +1 -0
  178. package/dist/server/kvStore.d.ts +27 -0
  179. package/dist/server/kvStore.d.ts.map +1 -0
  180. package/dist/server/kvStore.js +128 -0
  181. package/dist/server/kvStore.js.map +1 -0
  182. package/dist/server/runtimeSecurity.d.ts +28 -0
  183. package/dist/server/runtimeSecurity.d.ts.map +1 -0
  184. package/dist/server/runtimeSecurity.js +85 -0
  185. package/dist/server/runtimeSecurity.js.map +1 -0
  186. package/dist/server/types.d.ts +53 -0
  187. package/dist/server/types.d.ts.map +1 -0
  188. package/dist/server/types.js +8 -0
  189. package/dist/server/types.js.map +1 -0
  190. package/dist/types/executionContext.d.ts +16 -0
  191. package/dist/types/executionContext.d.ts.map +1 -0
  192. package/dist/types/executionContext.js +3 -0
  193. package/dist/types/executionContext.js.map +1 -0
  194. package/package.json +77 -0
  195. package/src/agents/agentRegistry.ts +272 -0
  196. package/src/agents/image-agent.yaml +86 -0
  197. package/src/agents/joker-agent.yaml +47 -0
  198. package/src/agents/translator-agent.yaml +80 -0
  199. package/src/audit/auditTrail.ts +134 -0
  200. package/src/compliance/gdprEngine.ts +209 -0
  201. package/src/compliance/lgpdEngine.ts +268 -0
  202. package/src/config.ts +179 -0
  203. package/src/errors.ts +35 -0
  204. package/src/firebase/tenantManager.ts +443 -0
  205. package/src/index.ts +125 -0
  206. package/src/integration/secure-yaml-runtime.ts +341 -0
  207. package/src/parser/secure-yaml-parser.ts +273 -0
  208. package/src/performance/autoscaling.ts +495 -0
  209. package/src/performance/benchmark.ts +644 -0
  210. package/src/performance/index.ts +34 -0
  211. package/src/performance/monitor.ts +469 -0
  212. package/src/performance/streaming.ts +317 -0
  213. package/src/runtime/audit.ts +907 -0
  214. package/src/runtime/declarativeAgentRuntime.ts +836 -0
  215. package/src/runtime/isolatedRuntime.ts +572 -0
  216. package/src/runtime/schemaCompiler.ts +228 -0
  217. package/src/runtime/simpleRuntime.ts +201 -0
  218. package/src/security/dashboard.ts +462 -0
  219. package/src/security/hardening.ts +560 -0
  220. package/src/security/index.ts +439 -0
  221. package/src/security/monitor.ts +490 -0
  222. package/src/security/scanner.ts +368 -0
  223. package/src/security/score.ts +1138 -0
  224. package/src/security/threatDetector.ts +481 -0
  225. package/src/security/validation.ts +365 -0
  226. package/src/server/api/clientsRoute.ts +92 -0
  227. package/src/server/api/endpointsRoute.ts +97 -0
  228. package/src/server/api/graphql.ts +249 -0
  229. package/src/server/errors.ts +38 -0
  230. package/src/server/index.ts +6 -0
  231. package/src/server/kvStore.ts +152 -0
  232. package/src/server/runtimeSecurity.ts +102 -0
  233. package/src/server/types.ts +60 -0
  234. package/src/types/executionContext.ts +16 -0
  235. package/tools/seed.ts +365 -0
  236. package/tools/test-endpoints.ts +174 -0
package/tools/seed.ts ADDED
@@ -0,0 +1,365 @@
1
+ // centralized seed file to update existing methods using Upstash KV
2
+ //
3
+ // how to run:
4
+ // 1. make sure your environment variables for KV_REST_API_URL and KV_REST_API_TOKEN are set
5
+ // 2. run the following command from the root of the project:
6
+ // npx dotenv-cli -- npx tsx packages/beddel/tools/seed.ts
7
+
8
+ import { Redis } from "@upstash/redis";
9
+
10
+ // --- Code block for: summarize-text ---
11
+ const summarizeTextCode = `async function execute(input, props, context) {
12
+ try {
13
+ context.log("Starting text summarization...");
14
+ const { generateText } = await import("ai");
15
+ const { createGoogleGenerativeAI } = await import("@ai-sdk/google");
16
+
17
+ if (!input.text) {
18
+ return context.setError("Missing required parameter: text");
19
+ }
20
+
21
+ if (!props.gemini_api_key) {
22
+ return context.setError("Missing required prop: gemini_api_key");
23
+ }
24
+
25
+ const google = createGoogleGenerativeAI({
26
+ apiKey: props.gemini_api_key,
27
+ });
28
+
29
+ const { text } = await generateText({
30
+ model: google("models/gemini-flash-latest"),
31
+ prompt: "Summarize the following text into concise bullet points:\\n\\n" + input.text,
32
+ });
33
+
34
+ if (typeof text !== "string") {
35
+ return context.setError("AI service did not return a valid text response.");
36
+ }
37
+
38
+ context.log("Successfully generated summary.");
39
+ context.setOutput({ summary: text });
40
+
41
+ } catch (e) {
42
+ context.log("An unexpected error occurred: " + e.message);
43
+ context.setError(e.message || "An unknown error occurred during summarization.");
44
+ }
45
+ }`;
46
+
47
+ // --- Code block for: extract-entities ---
48
+ const extractEntitiesCode = `async function execute(input, props, context) {
49
+ try {
50
+ context.log("Starting entity extraction...");
51
+ const { generateText } = await import("ai");
52
+ const { createGoogleGenerativeAI } = await import("@ai-sdk/google");
53
+
54
+ if (!input.text) {
55
+ return context.setError("Missing required parameter: text");
56
+ }
57
+
58
+ if (!props.gemini_api_key) {
59
+ return context.setError("Missing required prop: gemini_api_key");
60
+ }
61
+
62
+ const google = createGoogleGenerativeAI({
63
+ apiKey: props.gemini_api_key,
64
+ });
65
+
66
+ const { text } = await generateText({
67
+ model: google("models/gemini-flash-latest"),
68
+ prompt: "Extract all named entities from the following text and categorize them as PERSON, PLACE, ORGANIZATION, or OTHER. Return as a valid JSON object string:\\n\\n" + input.text,
69
+ });
70
+
71
+ if (typeof text !== "string") {
72
+ return context.setError("AI service did not return a valid text response.");
73
+ }
74
+
75
+ context.log("Successfully extracted entities.");
76
+ context.setOutput({ entities: text });
77
+
78
+ } catch (e) {
79
+ context.log("An unexpected error occurred: " + e.message);
80
+ context.setError(e.message || "An unknown error occurred during entity extraction.");
81
+ }
82
+ }`;
83
+
84
+ // --- Code block for: generate-automation-ideas ---
85
+ const generateIdeasCode = `async function execute(input, props, context) {
86
+ try {
87
+ context.log("Starting automation idea generation...");
88
+ const { generateText } = await import("ai");
89
+ const { createGoogleGenerativeAI } = await import("@ai-sdk/google");
90
+
91
+ if (!input.problem) {
92
+ return context.setError("Missing required parameter: problem");
93
+ }
94
+
95
+ if (!props.gemini_api_key) {
96
+ return context.setError("Missing required prop: gemini_api_key");
97
+ }
98
+
99
+ const google = createGoogleGenerativeAI({
100
+ apiKey: props.gemini_api_key,
101
+ });
102
+
103
+ const { text } = await generateText({
104
+ model: google("models/gemini-flash-latest"),
105
+ prompt: "Given this business problem: "" + input.problem + ""\\n\\nGenerate 5 creative automation workflow ideas that could solve or improve this situation. For each idea, include: 1) Workflow name, 2) Description, 3) Key steps, 4) Expected benefits.",
106
+ });
107
+
108
+ if (typeof text !== "string") {
109
+ return context.setError("AI service did not return a valid text response.");
110
+ }
111
+
112
+ context.log("Successfully generated ideas.");
113
+ context.setOutput({ ideas: text });
114
+
115
+ } catch (e) {
116
+ context.log("An unexpected error occurred: " + e.message);
117
+ context.setError(e.message || "An unknown error occurred during idea generation.");
118
+ }
119
+ }`;
120
+
121
+ // --- Code block for: validate-json-schema ---
122
+ const validateJsonCode = `async function execute(input, props, context) {
123
+ try {
124
+ context.log("Starting JSON validation...");
125
+ const { generateText } = await import("ai");
126
+ const { createGoogleGenerativeAI } = await import("@ai-sdk/google");
127
+
128
+ if (!input.json || !input.schema) {
129
+ return context.setError("Missing required parameters: json, schema");
130
+ }
131
+
132
+ if (!props.gemini_api_key) {
133
+ return context.setError("Missing required prop: gemini_api_key");
134
+ }
135
+
136
+ const google = createGoogleGenerativeAI({
137
+ apiKey: props.gemini_api_key,
138
+ });
139
+
140
+ const { text } = await generateText({
141
+ model: google("models/gemini-flash-latest"),
142
+ prompt: "Validate this JSON data against the schema and provide detailed feedback:\\n\\nJSON Data:\\n" + input.json + "\\n\\nSchema:\\n" + input.schema + "\\n\\nProvide: 1) Is it valid? 2) List of errors if any, 3) Suggested fixes",
143
+ });
144
+
145
+ if (typeof text !== "string") {
146
+ return context.setError("AI service did not return a valid text response.");
147
+ }
148
+
149
+ context.log("Successfully validated JSON.");
150
+ context.setOutput({ validation: text });
151
+
152
+ } catch (e) {
153
+ context.log("An unexpected error occurred: " + e.message);
154
+ context.setError(e.message || "An unknown error occurred during JSON validation.");
155
+ }
156
+ }`;
157
+
158
+ // --- Code block for: create-endpoint-from-description ---
159
+ const createEndpointFromDescriptionCode = `async function execute(input, props, context) {
160
+ const { generateText } = await import("ai");
161
+ const { createGoogleGenerativeAI } = await import("@ai-sdk/google");
162
+ const { Redis } = await import("@upstash/redis");
163
+
164
+ try {
165
+ context.log("Starting endpoint generation from description...");
166
+
167
+ // 1. Validate input and props
168
+ if (!input.description) {
169
+ return context.setError("Missing required parameter: description");
170
+ }
171
+ const requiredPropsList = ["gemini_api_key", "kv_rest_api_url", "kv_rest_api_token"];
172
+ for (const prop of requiredPropsList) {
173
+ if (!props[prop]) {
174
+ return context.setError("Missing required prop: " + prop);
175
+ }
176
+ }
177
+
178
+ // 1.5. Fetch existing endpoints to inform AI
179
+ const redis = new Redis({
180
+ url: props.kv_rest_api_url,
181
+ token: props.kv_rest_api_token,
182
+ });
183
+
184
+ context.log("Fetching existing endpoints to inform AI...");
185
+ const existingEndpointIds = (await redis.get("endpoints:list")) || [];
186
+ const existingEndpoints = [];
187
+ for (const id of existingEndpointIds) {
188
+ const endpoint = await redis.get("endpoint:" + id);
189
+ if (endpoint) {
190
+ existingEndpoints.push({
191
+ id: endpoint.id,
192
+ name: endpoint.name,
193
+ description: endpoint.description,
194
+ requiredProps: endpoint.requiredProps,
195
+ });
196
+ }
197
+ }
198
+ const existingEndpointsString = JSON.stringify(existingEndpoints, null, 2);
199
+ context.log("Found " + existingEndpoints.length + " existing endpoints.");
200
+
201
+ // 2. Prepare the prompt for the AI
202
+ const generationPrompt = "# PROMPT PARA GERAร‡รƒO DE ENDPOINT DINร‚MICO COM IA\\n\\n" +
203
+ "## Persona\\nVocรช รฉ um Engenheiro de Software Sรชnior especialista em criar funรงรตes serverless seguras, eficientes e robustas em JavaScript.\\n\\n" +
204
+ "## Contexto da Aplicaรงรฃo\\nVocรช estรก trabalhing in um sistema que executa dinamicamente endpoints de cรณdigo a partir de uma base de dados Upstash KV. Cada endpoint รฉ uma funรงรฃo \\"execute\\" que recebe \\"input\\", \\"props\\", e \\"context\\".\\n- \\"context.setOutput(output)\\" para sucesso.\\n- \\"context.setError(error)\\" para falha.\\n\\n" +
205
+ "## Exemplo de Implementaรงรฃo Correta\\n**Descriรงรฃo:** \"Resumir texto com Gemini.\"\\n**Saรญda JSON Esperada:**\\n" +
206
+ "{\\n \"name\": \"summarize-text\",\\n \"description\": \"Summarize long text into concise bullet points using Gemini AI\",\\n \"requiredProps\": [\"gemini_api_key\"],\\n \"code\": \"async function execute(input, props, context) { try { context.log(\\"Starting text summarization...\\"); const { generateText } = await import(\\"ai\\"); const { createGoogleGenerativeAI } = await import(\\"/@ai-sdk/google\\"); if (!input.text) { return context.setError(\\"Missing required parameter: text\\"); } if (!props.gemini_api_key) { return context.setError(\\"Missing required prop: gemini_api_key\\"); } const google = createGoogleGenerativeAI({ apiKey: props.gemini_api_key }); const { text } = await generateText({ model: google(\\"models/gemini-flash-latest\\"), prompt: \\"Summarize the following text into concise bullet points:\\\\\\\\n\\\\\\\\n\\" + input.text }); if (typeof text !== \\"string\\") { return context.setError(\\"AI service did not return a valid text response.\\"); } context.log(\\"Successfully generated summary.\\"); context.setOutput({ summary: text }); } catch (e) { context.log(\\"An unexpected error occurred: \\" + e.message); context.setError(e.message || \\"An unknown error occurred during summarization.\\"); } }"\\n}" +
207
+ "\\n\\n## Endpoints Existentes (para referรชncia e reutilizaรงรฃo de padrรตes)\\n\\`\\`\\`json\\n" + existingEndpointsString + "\\n\\`\\`\\`\\n\\n" +
208
+ "## Regras\\n1. **Seguranรงa:** Valide \\"input\\" e \\"props\\".\\n2. **Saรญda JSON:** Sua resposta DEVE ser um รบnico objeto JSON vรกlido. O campo \\"code\\" deve ser uma string com quebras de linha escapadas como \\"\\\\n\\".\\n3. **Bibliotecas Permitidas:** \\"ai\\", \\"@ai-sdk/google\\", \\"@upstash/redis\\".\\n4. **Nome do Endpoint:** O \\"name\\" deve ser um slug em \\"kebab-case\\".\\n5. **Reutilizaรงรฃo:** Se um endpoint similar jรก existe, o novo endpoint DEVE tentar reutilizar lรณgica ou ao menos seguir o mesmo padrรฃo de design e validaรงรฃo.\\n\\n" +
209
+ '## Sua Tarefa\\nGere o objeto JSON para o novo endpoint.\\n**Descriรงรฃo do Usuรกrio:** "" + input.description + """;
210
+
211
+ // 3. Call the AI to generate the endpoint details
212
+ context.log('Generating endpoint code with AI...');
213
+ const google = createGoogleGenerativeAI({ apiKey: props.gemini_api_key });
214
+ const { text } = await generateText({
215
+ model: google('models/gemini-flash-latest'),
216
+ prompt: generationPrompt,
217
+ });
218
+
219
+ let newEndpoint;
220
+ try {
221
+ newEndpoint = JSON.parse(text);
222
+ } catch (e) {
223
+ context.log('AI returned invalid JSON: ' + text);
224
+ return context.setError('Failed to parse AI response. The generated content was not valid JSON.');
225
+ }
226
+
227
+ // 4. Connect to Upstash KV and save the new endpoint
228
+ context.log('Connecting to Upstash KV to save \"' + newEndpoint.name + '\"...');
229
+
230
+ const endpointId = 'endpoint_' + newEndpoint.name.replace(/-/g, '_') + '_' + Date.now();
231
+ const endpointData = {
232
+ id: endpointId,
233
+ name: newEndpoint.name,
234
+ description: newEndpoint.description,
235
+ code: newEndpoint.code,
236
+ requiredProps: newEndpoint.requiredProps || [],
237
+ isPublic: false,
238
+ createdAt: new Date().toISOString(),
239
+ updatedAt: new Date().toISOString(),
240
+ };
241
+
242
+ await redis.set('endpoint:' + endpointId, JSON.stringify(endpointData));
243
+ context.log('Successfully saved new endpoint.');
244
+
245
+ // 5. Update the main endpoint list
246
+ const endpointList = (await redis.get('endpoints:list')) || [];
247
+ if (!Array.isArray(endpointList)) {
248
+ await redis.set('endpoints:list', [endpointId]);
249
+ } else {
250
+ endpointList.push(endpointId);
251
+ await redis.set('endpoints:list', endpointList);
252
+ }
253
+
254
+ context.log('Successfully updated endpoints list.');
255
+
256
+ context.setOutput({
257
+ message: 'Endpoint created successfully!',
258
+ endpointId: endpointId,
259
+ name: newEndpoint.name
260
+ });
261
+
262
+ } catch (e) {
263
+ context.log('An unexpected error occurred: ' + e.message);
264
+ context.setError(e.message || 'An unknown error occurred during endpoint creation.');
265
+ }
266
+ }`;
267
+
268
+ // The list of methods to be updated with the correct code pattern.
269
+ const methodsToUpdate = [
270
+ {
271
+ id: "endpoint_summarize_001",
272
+ name: "summarize-text",
273
+ description: "Summarize long text into concise bullet points using Gemini AI",
274
+ isPublic: true,
275
+ requiredProps: ["gemini_api_key"],
276
+ code: summarizeTextCode,
277
+ },
278
+ {
279
+ id: "endpoint_extract_entities_002",
280
+ name: "extract-entities",
281
+ description: "Extract named entities (people, places, organizations) from text",
282
+ isPublic: true,
283
+ requiredProps: ["gemini_api_key"],
284
+ code: extractEntitiesCode,
285
+ },
286
+ {
287
+ id: "endpoint_generate_ideas_003",
288
+ name: "generate-automation-ideas",
289
+ description: "Generate automation workflow ideas based on a business problem",
290
+ isPublic: true,
291
+ requiredProps: ["gemini_api_key"],
292
+ code: generateIdeasCode,
293
+ },
294
+ {
295
+ id: "endpoint_validate_json_004",
296
+ name: "validate-json-schema",
297
+ description: "Validate JSON data against a schema and suggest fixes",
298
+ isPublic: true,
299
+ requiredProps: ["gemini_api_key"],
300
+ code: validateJsonCode,
301
+ },
302
+ {
303
+ id: "endpoint_create_from_description_005",
304
+ name: "create-endpoint-from-description",
305
+ description: "Create a new dynamic endpoint from a natural language description using AI",
306
+ isPublic: false,
307
+ requiredProps: ["gemini_api_key", "kv_rest_api_url", "kv_rest_api_token"],
308
+ code: createEndpointFromDescriptionCode,
309
+ },
310
+ ];
311
+
312
+ async function seedUpdatedMethods() {
313
+ console.log("[v1] Starting endpoint update seed...");
314
+
315
+ if (!process.env.KV_REST_API_URL || !process.env.KV_REST_API_TOKEN) {
316
+ console.error("[v1] โŒ Missing Upstash KV environment variables. Please set KV_REST_API_URL and KV_REST_API_TOKEN.");
317
+ process.exit(1);
318
+ }
319
+
320
+ console.log("[v1] Connecting to Upstash KV...");
321
+ const redis = new Redis({
322
+ url: process.env.KV_REST_API_URL as string,
323
+ token: process.env.KV_REST_API_TOKEN as string,
324
+ });
325
+
326
+ try {
327
+ const allEndpointIds = [];
328
+ for (const method of methodsToUpdate) {
329
+ console.log(`[v1] Updating endpoint: ${method.name} (${method.id})`);
330
+
331
+ const oldRecord = await redis.get<any>(`endpoint:${method.id}`);
332
+ const createdAt = oldRecord?.createdAt || new Date().toISOString();
333
+
334
+ const updatedMethod = {
335
+ ...oldRecord,
336
+ ...method,
337
+ createdAt: createdAt,
338
+ updatedAt: new Date().toISOString(),
339
+ };
340
+
341
+ await redis.set(`endpoint:${method.id}`, JSON.stringify(updatedMethod));
342
+ console.log(`[v1] โœ“ Successfully updated ${method.name}`);
343
+ allEndpointIds.push(method.id);
344
+ }
345
+
346
+ // Check for endpoints that are in the list but not in methodsToUpdate
347
+ const existingEndpointIds = (await redis.get<string[]>("endpoints:list")) || [];
348
+ for(const existingId of existingEndpointIds) {
349
+ if(!allEndpointIds.includes(existingId)) {
350
+ allEndpointIds.push(existingId)
351
+ }
352
+ }
353
+
354
+ await redis.set("endpoints:list", allEndpointIds);
355
+ console.log("[v1] โœ“ Successfully created/updated the endpoints list index.");
356
+
357
+ console.log("\\n[v1] โœ… Endpoint update seed completed successfully!");
358
+
359
+ } catch (error) {
360
+ console.error("\\n[v1] โŒ Error updating endpoints:", error);
361
+ throw error;
362
+ }
363
+ }
364
+
365
+ seedUpdatedMethods();
@@ -0,0 +1,174 @@
1
+
2
+ import { Redis } from '@upstash/redis';
3
+ import assert from 'assert';
4
+
5
+ // Centralized test data for each endpoint
6
+ const testData = {
7
+ "endpoint_summarize_001": {
8
+ success: { input: { text: "This is a long text to summarize into bullet points." } },
9
+ failure: { input: {} } // Missing 'text'
10
+ },
11
+ "endpoint_extract_entities_002": {
12
+ success: { input: { text: "John Doe works at Google in New York." } },
13
+ failure: { input: {} } // Missing 'text'
14
+ },
15
+ "endpoint_generate_ideas_003": {
16
+ success: { input: { problem: "Our customer support team is overwhelmed with tickets." } },
17
+ failure: { input: {} } // Missing 'problem'
18
+ },
19
+ "endpoint_validate_json_004": {
20
+ success: {
21
+ input: {
22
+ json: '{ \"name\": \"John\", \"age\": 30 }',
23
+ schema: '{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"number\" } } }'
24
+ }
25
+ },
26
+ failure: { input: { json: '{ \"name\": \"John\" }' } } // Missing 'schema'
27
+ },
28
+ "endpoint_translate_005": {
29
+ success: { input: { text: "Hello, world!", targetLanguage: "Spanish" } },
30
+ failure: { input: { text: "Hello, world!" } } // Missing 'targetLanguage'
31
+ }
32
+ };
33
+
34
+ // Expected output keys for each endpoint\'s success case
35
+ const expectedOutputKeys = {
36
+ endpoint_summarize_001: 'summary',
37
+ endpoint_extract_entities_002: 'entities',
38
+ endpoint_generate_ideas_003: 'ideas',
39
+ endpoint_validate_json_004: 'validation',
40
+ endpoint_translate_005: 'translation'
41
+ };
42
+
43
+
44
+ // Mock context object to capture test results
45
+ function createMockContext() {
46
+ let output: any = null;
47
+ let error: string | null = null;
48
+ const logs: string[] = [];
49
+ return {
50
+ log: (message: string) => logs.push(message),
51
+ setOutput: (data: any) => { output = data; },
52
+ setError: (message: string) => { error = message; },
53
+ getOutput: () => output,
54
+ getError: () => error,
55
+ getLogs: () => logs,
56
+ reset: () => { output = null; error = null; logs.length = 0; },
57
+ };
58
+ }
59
+
60
+ // Runs the endpoint code in a sandboxed environment
61
+ async function runCode(code: string, input: any, props: any, context: any) {
62
+ // Create a dynamic function to execute the user-provided code string
63
+ const execute = new Function('input', 'props', 'context', 'require', `
64
+ const userCode = ${code};
65
+ return userCode(input, props, context);
66
+ `);
67
+
68
+ // Execute the code, allowing it to use the real 'require' function
69
+ await execute(input, props, context, require);
70
+ }
71
+
72
+ async function testEndpoints() {
73
+ console.log("[TEST] Starting TRUE integration test...");
74
+
75
+ // Check for all required environment variables
76
+ if (!process.env.KV_REST_API_URL || !process.env.KV_REST_API_TOKEN || !process.env.GEMINI_API_KEY) {
77
+ console.error("[TEST] โŒ Missing required environment variables (KV_REST_API_URL, KV_REST_API_TOKEN, GEMINI_API_KEY).");
78
+ process.exit(1);
79
+ }
80
+
81
+ const redis = new Redis({
82
+ url: process.env.KV_REST_API_URL as string,
83
+ token: process.env.KV_REST_API_TOKEN as string,
84
+ });
85
+
86
+ const mockContext = createMockContext();
87
+ const endpointIdToTest = process.argv[2];
88
+ let endpointIds: string[] = [];
89
+
90
+ if (endpointIdToTest) {
91
+ console.log(`[TEST] ๐ŸŽฏ Targeting single endpoint: ${endpointIdToTest}`);
92
+ endpointIds = [endpointIdToTest];
93
+ } else {
94
+ console.log("[TEST] ๐ŸŽฏ Targeting all endpoints from master list...");
95
+ const idList = await redis.get<string[]>('endpoints:list');
96
+ if (!idList) {
97
+ console.error("[TEST] โŒ Master list 'endpoints:list' not found in Redis.");
98
+ process.exit(1);
99
+ }
100
+ endpointIds = idList;
101
+ }
102
+
103
+ if (endpointIds.length === 0) {
104
+ console.warn("[TEST] โš ๏ธ No endpoints found to test.");
105
+ return;
106
+ }
107
+
108
+ let passed = 0;
109
+ let failed = 0;
110
+
111
+ for (const endpointId of endpointIds) {
112
+ const key = `endpoint:${endpointId}`;
113
+ const endpoint = await redis.get<any>(key);
114
+
115
+ if (!endpoint || !endpoint.code || !endpoint.id) {
116
+ console.warn(`[TEST] โš ๏ธ Skipping invalid record for ID: ${endpointId} (key: ${key})`);
117
+ continue;
118
+ }
119
+
120
+ const specificTestData = testData[endpointId as keyof typeof testData];
121
+ const expectedKey = expectedOutputKeys[endpointId as keyof typeof expectedOutputKeys];
122
+
123
+ if (!specificTestData || !expectedKey) {
124
+ console.warn(`[TEST] โš ๏ธ No test data or expected output key for ${endpointId}. Skipping.`);
125
+ continue;
126
+ }
127
+
128
+ console.log(`\n[TEST] ๐Ÿงช Testing endpoint: ${endpoint.name} (${endpointId})`);
129
+ mockContext.reset();
130
+
131
+ try {
132
+ const realProps = { gemini_api_key: process.env.GEMINI_API_KEY };
133
+
134
+ // Test Case 1: Success (Real API Call)
135
+ console.log(" -> Running success case (REAL API call)...");
136
+ await runCode(endpoint.code, specificTestData.success.input, realProps, mockContext);
137
+ const output = mockContext.getOutput();
138
+ assert.strictEqual(mockContext.getError(), null, "Success case should not produce an error.");
139
+ assert.ok(output, "Output should not be null or undefined.");
140
+ assert.ok(output[expectedKey], `Output should have the key '${expectedKey}'.`);
141
+ assert.strictEqual(typeof output[expectedKey], 'string', `Value of '${expectedKey}' should be a string.`);
142
+ console.log(` โœ… Success (Received: "${output[expectedKey].substring(0, 50)}...")`);
143
+
144
+ // Test Case 2: Failure (missing input)
145
+ console.log(" -> Running failure case (missing input)...");
146
+ mockContext.reset();
147
+ await runCode(endpoint.code, specificTestData.failure.input, realProps, mockContext);
148
+ assert.notStrictEqual(mockContext.getError(), null, "Failure case (missing input) should produce an error.");
149
+ console.log(" โœ… Success (Correctly caught error)");
150
+
151
+ // Test Case 3: Failure (missing prop)
152
+ console.log(" -> Running failure case (missing prop)...");
153
+ mockContext.reset();
154
+ await runCode(endpoint.code, specificTestData.success.input, {}, mockContext);
155
+ assert.notStrictEqual(mockContext.getError(), null, "Failure case (missing prop) 2should produce an error.");
156
+ console.log(" โœ… Success (Correctly caught error)");
157
+
158
+ passed++;
159
+ } catch (e: any) {
160
+ console.error(`[TEST] โŒ FAILED: ${endpoint.name}`);
161
+ console.error(` Assertion Error: ${e.message}`);
162
+ failed++;
163
+ }
164
+ }
165
+
166
+ console.log(`\n[TEST] โœจ Test run complete.`);
167
+ console.log(`[TEST] Passed: ${passed}, Failed: ${failed}`);
168
+
169
+ if (failed > 0) {
170
+ process.exit(1);
171
+ }
172
+ }
173
+
174
+ testEndpoints();