-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestScriptsApi.js
More file actions
429 lines (377 loc) · 14.7 KB
/
testScriptsApi.js
File metadata and controls
429 lines (377 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import BosBase from "bosbase";
import { EventSource as EventSourcePolyfill } from "eventsource";
const baseUrl = process.env.BOSBASE_BASE_URL ?? "https://try.bosbase.com";
const authEmail =
process.env.BOSBASE_EMAIL ??
process.env.BOSBASE_SUPERUSER_EMAIL ??
"try@bosbase.com";
const authPassword =
process.env.BOSBASE_PASSWORD ??
process.env.BOSBASE_SUPERUSER_PASSWORD ??
"bosbasepass";
async function main() {
try {
if (typeof EventSource === "undefined") {
global.EventSource = EventSourcePolyfill;
}
console.log("[INFO] SCRIPTS_API.md doc test starting...");
const pb = new BosBase(baseUrl);
await pb.collection("_superusers").authWithPassword(authEmail, authPassword);
console.log("[SUCCESS] Authenticated as superuser");
if (!pb.scripts) {
throw new Error("pb.scripts is not available. Ensure the JS SDK includes the Scripts API.");
}
const scriptName = `doc_script_${Date.now()}`;
const initialContent = `
def main(*args):
args_str = " ".join(args) if args else "no-args"
return "doc execution success " + args_str
def custom_function():
return "custom function called"
def process_args(a, b):
return f"processed {a} and {b}"
# For backward compatibility with old execution method
if __name__ == "__main__":
import sys
args = sys.argv[1:] if len(sys.argv) > 1 else []
result = main(*args)
print(result)
`.trim();
// Clean up in case a previous run left residue
try {
await pb.scripts.delete(scriptName);
} catch (_) {
/* ignore */
}
const created = await pb.scripts.create({
name: scriptName,
content: initialContent,
description: "Doc test script",
});
console.log("[SUCCESS] Created script:", created);
if (!created.id) {
throw new Error("Created script is missing an id");
}
const fetched = await pb.scripts.get(scriptName);
if (fetched.version !== 1) {
throw new Error(`Expected version 1 after create, got ${fetched.version}`);
}
if (fetched.id !== created.id) {
throw new Error("Fetched script id does not match the created id");
}
console.log("[INFO] Fetched script:", fetched);
const updated = await pb.scripts.update(scriptName, {
description: "Updated description",
content: `
def main(*args):
args_str = " ".join(args) if args else "no-args"
return "doc execution success updated " + args_str
def custom_function():
return "custom function called updated"
def process_args(a, b):
return f"processed {a} and {b} updated"
# For backward compatibility with old execution method
if __name__ == "__main__":
import sys
args = sys.argv[1:] if len(sys.argv) > 1 else []
result = main(*args)
print(result)
`.trim(),
});
if (updated.version !== fetched.version + 1) {
throw new Error(`Version did not increment on update (expected ${fetched.version + 1}, got ${updated.version})`);
}
console.log("[SUCCESS] Updated script:", updated);
const listed = await pb.scripts.list();
const found = listed.find((s) => s.name === scriptName);
if (!found) {
throw new Error("Created script not found in list()");
}
if (found.id !== created.id) {
throw new Error("Listed script id does not match the created id");
}
console.log("[INFO] List contains script. Total scripts:", listed.length);
const cmd = await pb.scripts.command("echo command-ok");
if (!cmd?.output?.includes("command-ok")) {
throw new Error(`Command output missing expected text: ${cmd.output}`);
}
console.log("[SUCCESS] Command output:", cmd.output);
const uploadName = `doc_upload_${Date.now()}.sh`;
const uploadContent = `#!/bin/sh
echo "upload-success"
`;
const uploadFile = new Blob([uploadContent], {
type: "text/x-shellscript",
});
try {
const uploadResult = await pb.scripts.upload({
file: uploadFile,
path: uploadName,
});
if (!uploadResult?.output) {
throw new Error("Upload result is missing output");
}
console.log("[SUCCESS] Upload result:", uploadResult);
const runUploaded = await pb.scripts.command(`./${uploadName}`);
if (!runUploaded?.output?.includes("upload-success")) {
throw new Error(
`Uploaded file did not execute as expected: ${runUploaded.output}`,
);
}
console.log("[SUCCESS] Executed uploaded file:", runUploaded.output);
} finally {
try {
await pb.scripts.command(`rm -f ${uploadName}`);
await pb.scripts.command("rm -f wasmedge");
} catch (_) {
/* ignore cleanup issues */
}
}
// Script permissions: allow anonymous execution, then read/update/delete
const perm = await pb.scriptsPermissions.create({
scriptName: scriptName,
content: "anonymous",
});
console.log("[SUCCESS] Created execution permission:", perm);
const permFetched = await pb.scriptsPermissions.get(scriptName);
if (permFetched.content !== "anonymous") {
throw new Error(`Fetched permission mismatch: ${permFetched.content}`);
}
console.log("[INFO] Fetched execution permission:", permFetched);
const permUpdated = await pb.scriptsPermissions.update(scriptName, { content: "user" });
if (permUpdated.content !== "user") {
throw new Error(`Updated permission mismatch: ${permUpdated.content}`);
}
console.log("[SUCCESS] Updated execution permission:", permUpdated);
// Test execution with arguments (old way, backward compatible)
const executed = await pb.scripts.execute(scriptName, ["10", "20"]);
if (!executed?.output?.includes("doc execution success updated 10 20")) {
throw new Error(`Execute output missing expected text with args: ${executed.output}`);
}
console.log("[SUCCESS] Executed script with arguments:", executed.output);
// Test execution with function_name only
const executedWithFunction = await pb.scripts.execute(scriptName, {
function_name: "custom_function",
});
if (!executedWithFunction?.output?.includes("custom function called updated")) {
throw new Error(
`Execute with function_name missing expected text: ${executedWithFunction.output}`,
);
}
console.log("[SUCCESS] Executed script with function_name:", executedWithFunction.output);
// Test execution with both function_name and arguments
const executedWithBoth = await pb.scripts.execute(scriptName, {
function_name: "process_args",
arguments: ["arg1", "arg2"],
});
if (!executedWithBoth?.output?.includes("processed arg1 and arg2 updated")) {
throw new Error(
`Execute with function_name and arguments missing expected text: ${executedWithBoth.output}`,
);
}
console.log("[SUCCESS] Executed script with function_name and arguments:", executedWithBoth.output);
if (typeof pb.scripts.executeAsync !== "function") {
throw new Error("pb.scripts.executeAsync is not available. Ensure the JS SDK includes async script execution.");
}
if (typeof pb.scripts.executeAsyncStatus !== "function") {
throw new Error("pb.scripts.executeAsyncStatus is not available. Ensure the JS SDK includes async script execution status.");
}
const startedAsync = await pb.scripts.executeAsync(scriptName, {
arguments: ["10", "20"],
function_name: "main",
});
if (!startedAsync?.id) {
throw new Error("executeAsync did not return a job id");
}
console.log("[SUCCESS] Started async execution:", startedAsync);
const asyncTimeoutMs = 30000;
const asyncPollIntervalMs = 500;
const asyncStart = Date.now();
let asyncJob;
while (true) {
asyncJob = await pb.scripts.executeAsyncStatus(startedAsync.id);
if (!asyncJob?.status) {
throw new Error("executeAsyncStatus did not return a valid job status");
}
if (asyncJob.status !== "running") {
break;
}
if (Date.now() - asyncStart > asyncTimeoutMs) {
throw new Error(`Async execution did not finish within ${asyncTimeoutMs}ms`);
}
await new Promise((resolve) => setTimeout(resolve, asyncPollIntervalMs));
}
if (asyncJob.status !== "done") {
throw new Error(`Async execution failed: ${asyncJob.error || asyncJob.status}`);
}
if (!asyncJob?.output?.includes("doc execution success updated 10 20")) {
throw new Error(`Async execution output missing expected text: ${asyncJob.output}`);
}
console.log("[SUCCESS] Async execution completed:", asyncJob.output);
// Test execution without function_name (should default to "main")
const executedDefault = await pb.scripts.execute(scriptName, {});
if (!executedDefault?.output?.includes("doc execution success updated no-args")) {
throw new Error(
`Execute without function_name (default to main) missing expected text: ${executedDefault.output}`,
);
}
console.log("[SUCCESS] Executed script without function_name (defaults to main):", executedDefault.output);
// Loosen permissions for streaming tests (allow anonymous)
await pb.scriptsPermissions.update(scriptName, { content: "anonymous" });
console.log("[INFO] Set execution permission to anonymous for streaming tests");
// Test SSE execution (skip if EventSource is not available in this runtime)
if (typeof EventSource === "undefined") {
console.log("[INFO] EventSource is not available in this environment; skipping SSE test.");
} else {
const ssePayload = await new Promise((resolve, reject) => {
const es = pb.scripts.executeSSE(
scriptName,
{ arguments: ["sse-arg"] },
{ eventSourceInit: { withCredentials: true } },
);
const timeout = setTimeout(() => {
es.close();
reject(new Error("SSE execution timed out"));
}, 10000);
es.addEventListener("message", (ev) => {
clearTimeout(timeout);
es.close();
try {
resolve(JSON.parse(ev.data));
} catch (err) {
reject(err);
}
});
es.addEventListener("error", (err) => {
clearTimeout(timeout);
es.close();
reject(err instanceof Error ? err : new Error("SSE error"));
});
});
if (!ssePayload?.output?.includes("sse-arg")) {
throw new Error(`SSE execution output missing expected text: ${ssePayload?.output}`);
}
console.log("[SUCCESS] SSE execution output:", ssePayload.output);
}
// Test WebSocket execution (skip if WebSocket is not available in this runtime)
if (typeof WebSocket === "undefined") {
console.log("[INFO] WebSocket is not available in this environment; skipping WebSocket test.");
} else {
try {
const wsPayload = await new Promise((resolve, reject) => {
let settled = false;
const ws = pb.scripts.executeWebSocket(
scriptName,
{ arguments: ["ws-arg"] },
{
headers: { Authorization: pb.authStore.token },
query: { token: pb.authStore.token },
},
);
const timeout = setTimeout(() => {
if (settled) return;
settled = true;
ws.close();
reject(new Error("WebSocket execution timed out"));
}, 10000);
ws.onmessage = (event) => {
if (settled) return;
clearTimeout(timeout);
settled = true;
ws.onmessage = null;
ws.onerror = null;
ws.close();
try {
const raw =
typeof event.data === "string"
? event.data
: event.data?.toString?.() ?? "";
resolve(JSON.parse(raw));
} catch (err) {
reject(err);
}
};
ws.onerror = (err) => {
if (settled) return;
clearTimeout(timeout);
settled = true;
ws.onmessage = null;
ws.onerror = null;
try {
ws.close();
} catch (_) {}
resolve({ _error: err instanceof Error ? err : new Error("WebSocket error") });
};
});
if (wsPayload?._error) {
throw wsPayload._error;
}
if (!wsPayload?.output?.includes("ws-arg")) {
throw new Error(`WebSocket execution output missing expected text: ${wsPayload?.output}`);
}
console.log("[SUCCESS] WebSocket execution output:", wsPayload.output);
} catch (err) {
console.log("[INFO] WebSocket execution skipped (non-critical):", err?.message || err);
}
}
await pb.scriptsPermissions.delete(scriptName);
console.log("[SUCCESS] Deleted execution permission");
await pb.scripts.delete(scriptName);
console.log("[SUCCESS] Deleted script");
const mathOperationsScriptName = "math_operation" + Date.now();
const mathOperationsScriptNameContent = `
import math
def add(a: float, b: float) -> float:
"""Add two numbers"""
# Convert to float (handles both strings and numbers)
a, b = float(a), float(b)
return a + b
def multiply(a: float, b: float) -> float:
"""Multiply two numbers"""
# Convert to float (handles both strings and numbers)
a, b = float(a), float(b)
return a * b
def factorial(n: int) -> int:
"""Calculate factorial"""
# Convert to int (handles both strings and numbers)
n = int(n)
if n < 0:
raise ValueError("Factorial not defined for negative numbers")
return math.factorial(n)
def fibonacci(n: int) -> int:
"""Calculate nth Fibonacci number"""
# Convert to int (handles both strings and numbers)
n = int(n)
if n <= 0:
return 0
elif n == 1:
return 1
else:
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
`;
const createdMathOperationsScript = await pb.scripts.create({
name: mathOperationsScriptName,
content: mathOperationsScriptNameContent,
});
console.log("[SUCCESS] Created math operations script:", createdMathOperationsScript);
const executedMultiply = await pb.scripts.execute(mathOperationsScriptName, {function_name: "multiply", arguments: [12, 20]});
console.log("[SUCCESS] Executed script with arguments:", executedMultiply.output);
console.log("\n========== SCRIPTS_API.md doc test completed ==========");
} catch (error) {
console.error("[ERROR] SCRIPTS_API.md doc test failed:");
if (error?.response) {
console.error("Status:", error.response.status);
console.error("Data:", JSON.stringify(error.response.data, null, 2));
if (error.response.data?.message) {
console.error("Message:", error.response.data.message);
}
} else {
console.error(error);
}
process.exit(1);
}
}
main();