@neurocode-ai/codemode 1.18.8
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.
- package/AGENTS.md +23 -0
- package/README.md +369 -0
- package/codemode.md +176 -0
- package/package.json +25 -0
- package/src/codemode.ts +159 -0
- package/src/index.ts +4 -0
- package/src/interpreter/model.ts +201 -0
- package/src/interpreter/runtime.ts +3465 -0
- package/src/openapi/TODO.md +19 -0
- package/src/openapi/index.ts +130 -0
- package/src/openapi/runtime.ts +326 -0
- package/src/openapi/spec.ts +511 -0
- package/src/openapi/types.ts +112 -0
- package/src/stdlib/collections.ts +51 -0
- package/src/stdlib/console.ts +4 -0
- package/src/stdlib/date.ts +94 -0
- package/src/stdlib/json.ts +42 -0
- package/src/stdlib/math.ts +65 -0
- package/src/stdlib/number.ts +66 -0
- package/src/stdlib/object.ts +77 -0
- package/src/stdlib/promise.ts +6 -0
- package/src/stdlib/regexp.ts +74 -0
- package/src/stdlib/string.ts +52 -0
- package/src/stdlib/url.ts +90 -0
- package/src/stdlib/value.ts +86 -0
- package/src/tool-error.ts +11 -0
- package/src/tool-runtime.ts +806 -0
- package/src/tool-schema.ts +301 -0
- package/src/tool.ts +96 -0
- package/src/values.ts +49 -0
- package/sst-env.d.ts +10 -0
- package/test/codemode.test.ts +1163 -0
- package/test/enumeration.test.ts +159 -0
- package/test/fixtures/openapi-happy-path.json +230 -0
- package/test/fixtures/opencode-v2-openapi.json +23730 -0
- package/test/openapi.test.ts +964 -0
- package/test/parity.test.ts +425 -0
- package/test/promise.test.ts +456 -0
- package/test/signature.test.ts +449 -0
- package/test/stdlib.test.ts +715 -0
- package/tsconfig.json +7 -0
|
@@ -0,0 +1,715 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test"
|
|
2
|
+
import { Effect, Schema } from "effect"
|
|
3
|
+
import { CodeMode, Tool } from "../src/index.js"
|
|
4
|
+
|
|
5
|
+
// Standard-library value types: Date, RegExp, Map, Set. Programs use them as ordinary JS;
|
|
6
|
+
// intra-sandbox checkpoints (Object.* helpers, spread, coercion inputs) preserve the live
|
|
7
|
+
// values, while at the host boundary (final result, tool arguments, JSON.stringify) they
|
|
8
|
+
// serialize exactly as JSON.stringify would: Date -> ISO string (invalid -> null),
|
|
9
|
+
// URL -> href, and RegExp/Map/Set/URLSearchParams -> {}.
|
|
10
|
+
const run = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} }))
|
|
11
|
+
const value = async (code: string) => {
|
|
12
|
+
const result = await run(code)
|
|
13
|
+
if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`)
|
|
14
|
+
return result.value
|
|
15
|
+
}
|
|
16
|
+
const error = async (code: string) => {
|
|
17
|
+
const result = await run(code)
|
|
18
|
+
if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`)
|
|
19
|
+
return result.error
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
describe("Date", () => {
|
|
23
|
+
test("Date.now() returns a number", async () => {
|
|
24
|
+
expect(await value(`return typeof Date.now()`)).toBe("number")
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
test("epoch construction and ISO rendering", async () => {
|
|
28
|
+
expect(await value(`return new Date(0).toISOString()`)).toBe("1970-01-01T00:00:00.000Z")
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
test("string parsing round-trips", async () => {
|
|
32
|
+
expect(await value(`return new Date("2024-01-02T03:04:05.000Z").getTime()`)).toBe(1704164645000)
|
|
33
|
+
expect(await value(`return Date.parse("2024-01-02T03:04:05.000Z")`)).toBe(1704164645000)
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
test("date arithmetic and comparison use the time value", async () => {
|
|
37
|
+
expect(await value(`const a = new Date(1000); const b = new Date(3000); return b - a`)).toBe(2000)
|
|
38
|
+
expect(await value(`const a = new Date(1000); const b = new Date(3000); return a < b`)).toBe(true)
|
|
39
|
+
expect(await value(`return +new Date(42)`)).toBe(42)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
test("UTC getters read calendar components", async () => {
|
|
43
|
+
expect(
|
|
44
|
+
await value(
|
|
45
|
+
`const d = new Date("2024-03-05T06:07:08.009Z"); return [d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()]`,
|
|
46
|
+
),
|
|
47
|
+
).toEqual([2024, 2, 5, 6, 7, 8, 9])
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
test("invalid dates yield NaN times, guardable in-sandbox", async () => {
|
|
51
|
+
expect(await value(`return Number.isNaN(new Date("garbage").getTime())`)).toBe(true)
|
|
52
|
+
expect(await value(`return new Date("garbage").toJSON()`)).toBeNull()
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
test("toISOString on an invalid date is a catchable error", async () => {
|
|
56
|
+
expect(await value(`try { new Date("garbage").toISOString(); return "no" } catch { return "caught" }`)).toBe(
|
|
57
|
+
"caught",
|
|
58
|
+
)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
test("template interpolation renders the ISO form", async () => {
|
|
62
|
+
expect(await value("return `at ${new Date(0)}`")).toBe("at 1970-01-01T00:00:00.000Z")
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
test("dates serialize to ISO strings at the boundary, direct and nested", async () => {
|
|
66
|
+
expect(await value(`return new Date(0)`)).toBe("1970-01-01T00:00:00.000Z")
|
|
67
|
+
expect(await value(`return { when: new Date(0), tags: [new Date(1000)] }`)).toEqual({
|
|
68
|
+
when: "1970-01-01T00:00:00.000Z",
|
|
69
|
+
tags: ["1970-01-01T00:00:01.000Z"],
|
|
70
|
+
})
|
|
71
|
+
expect(await value(`return JSON.stringify({ d: new Date(0) })`)).toBe('{"d":"1970-01-01T00:00:00.000Z"}')
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
test("coercions: Number is the time, String is ISO, Boolean is true", async () => {
|
|
75
|
+
expect(await value(`return Number(new Date(5))`)).toBe(5)
|
|
76
|
+
expect(await value(`return String(new Date(0))`)).toBe("1970-01-01T00:00:00.000Z")
|
|
77
|
+
expect(await value(`return Boolean(new Date(0))`)).toBe(true)
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
test("sorting dates with a numeric comparator", async () => {
|
|
81
|
+
expect(
|
|
82
|
+
await value(`
|
|
83
|
+
const dates = [new Date(3000), new Date(1000), new Date(2000)]
|
|
84
|
+
return dates.sort((a, b) => a - b).map((d) => d.getTime())
|
|
85
|
+
`),
|
|
86
|
+
).toEqual([1000, 2000, 3000])
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
test("new Date(year, month, day) accepts component form", async () => {
|
|
90
|
+
expect(await value(`const d = new Date(2024, 0, 2); return [d.getFullYear(), d.getMonth(), d.getDate()]`)).toEqual([
|
|
91
|
+
2024, 0, 2,
|
|
92
|
+
])
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
test("typeof and unknown properties are forgiving", async () => {
|
|
96
|
+
expect(await value(`return typeof new Date(0)`)).toBe("object")
|
|
97
|
+
expect(await value(`return new Date(0).nope === undefined`)).toBe(true)
|
|
98
|
+
})
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
describe("RegExp", () => {
|
|
102
|
+
test("literal test", async () => {
|
|
103
|
+
expect(await value(`return /ab+c/.test("xabbbc")`)).toBe(true)
|
|
104
|
+
expect(await value(`return /ab+c/.test("nope")`)).toBe(false)
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
test("exec exposes captures and index", async () => {
|
|
108
|
+
expect(await value(`const m = /a(b+)/.exec("xxabbc"); return { full: m[0], group: m[1], index: m.index }`)).toEqual(
|
|
109
|
+
{
|
|
110
|
+
full: "abb",
|
|
111
|
+
group: "bb",
|
|
112
|
+
index: 2,
|
|
113
|
+
},
|
|
114
|
+
)
|
|
115
|
+
expect(await value(`return /a/.exec("zzz")`)).toBeNull()
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
test("named groups read through", async () => {
|
|
119
|
+
expect(
|
|
120
|
+
await value(`const m = /(?<word>[a-z]+)-(?<num>\\d+)/.exec("id ab-42"); return m.groups.word + m.groups.num`),
|
|
121
|
+
).toBe("ab42")
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
test("global exec advances lastIndex across calls", async () => {
|
|
125
|
+
expect(
|
|
126
|
+
await value(`
|
|
127
|
+
const r = /\\d+/g
|
|
128
|
+
const first = r.exec("a1b22c")
|
|
129
|
+
const second = r.exec("a1b22c")
|
|
130
|
+
return [first[0], second[0]]
|
|
131
|
+
`),
|
|
132
|
+
).toEqual(["1", "22"])
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
test("string match: non-global carries index, global lists all matches", async () => {
|
|
136
|
+
expect(await value(`const m = "a1b22".match(/\\d+/); return [m[0], m.index]`)).toEqual(["1", 1])
|
|
137
|
+
expect(await value(`return "a1b22".match(/\\d+/g)`)).toEqual(["1", "22"])
|
|
138
|
+
expect(await value(`return "abc".match(/\\d/)`)).toBeNull()
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
test("matchAll materializes match arrays with captures", async () => {
|
|
142
|
+
expect(await value(`return "a1b22".matchAll(/(\\d+)/g).map((m) => m[1])`)).toEqual(["1", "22"])
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
test("replace and replaceAll with patterns and $1 substitution", async () => {
|
|
146
|
+
expect(await value(`return "a1b2".replace(/\\d/, "#")`)).toBe("a#b2")
|
|
147
|
+
expect(await value(`return "a1b2".replace(/\\d/g, "#")`)).toBe("a#b#")
|
|
148
|
+
expect(await value(`return "a1b2".replaceAll(/\\d/g, "#")`)).toBe("a#b#")
|
|
149
|
+
expect(await value(`return "hi bob".replace(/b(o)b/, "[$1]")`)).toBe("hi [o]")
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
test("function replacers receive captures, offsets, input, and named groups", async () => {
|
|
153
|
+
expect(
|
|
154
|
+
await value(`
|
|
155
|
+
const seen = []
|
|
156
|
+
const output = "a1b22".replace(/(\\d)(\\d)?/g, (match, first, second, offset, input) => {
|
|
157
|
+
seen.push([match, first, second === undefined, offset, input])
|
|
158
|
+
return Number(match) * 2
|
|
159
|
+
})
|
|
160
|
+
return { output, seen }
|
|
161
|
+
`),
|
|
162
|
+
).toEqual({
|
|
163
|
+
output: "a2b44",
|
|
164
|
+
seen: [
|
|
165
|
+
["1", "1", true, 1, "a1b22"],
|
|
166
|
+
["22", "2", false, 3, "a1b22"],
|
|
167
|
+
],
|
|
168
|
+
})
|
|
169
|
+
expect(
|
|
170
|
+
await value(`
|
|
171
|
+
return "red-blue".replace(
|
|
172
|
+
/(?<left>[a-z]+)-(?<right>[a-z]+)/,
|
|
173
|
+
(match, left, right, offset, input, groups) => groups.right + ":" + groups.left,
|
|
174
|
+
)
|
|
175
|
+
`),
|
|
176
|
+
).toBe("blue:red")
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
test("function replacers support string searches, zero-length matches, and result coercion", async () => {
|
|
180
|
+
expect(await value(`return "banana".replace("na", (match, offset, input) => "[" + offset + "]")`)).toBe("ba[2]na")
|
|
181
|
+
expect(await value(`return "ab".replaceAll("", (match, offset) => offset)`)).toBe("0a1b2")
|
|
182
|
+
expect(await value(`return "😀".replaceAll(/(?:)/gu, (match, offset) => "[" + offset + "]")`)).toBe("[0]😀[2]")
|
|
183
|
+
expect(
|
|
184
|
+
await value(`return "123".replace(/\\d/g, (match) => match === "1" ? 7 : match === "2" ? null : { n: 3 })`),
|
|
185
|
+
).toBe("7null[object Object]")
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
test("function replacers can await effectful tool calls", async () => {
|
|
189
|
+
const decorate = Tool.make({
|
|
190
|
+
description: "Decorate a string",
|
|
191
|
+
input: Schema.String,
|
|
192
|
+
output: Schema.String,
|
|
193
|
+
run: (input) => Effect.succeed(`[${input}]`),
|
|
194
|
+
})
|
|
195
|
+
const result = await Effect.runPromise(
|
|
196
|
+
CodeMode.execute({
|
|
197
|
+
tools: { host: { decorate } },
|
|
198
|
+
code: `return "a1b22".replace(/\\d+/g, async (match) => await tools.host.decorate(match))`,
|
|
199
|
+
}),
|
|
200
|
+
)
|
|
201
|
+
expect(result.ok && result.value).toBe("a[1]b[22]")
|
|
202
|
+
|
|
203
|
+
const missingAwait = await Effect.runPromise(
|
|
204
|
+
CodeMode.execute({
|
|
205
|
+
tools: { host: { decorate } },
|
|
206
|
+
code: `return "a1".replace(/\\d/, (match) => tools.host.decorate(match))`,
|
|
207
|
+
}),
|
|
208
|
+
)
|
|
209
|
+
expect(!missingAwait.ok && missingAwait.error.kind).toBe("InvalidDataValue")
|
|
210
|
+
expect(!missingAwait.ok && missingAwait.error.message).toContain("un-awaited Promise")
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
test("replaceAll without the g flag is a catchable error", async () => {
|
|
214
|
+
expect(await value(`try { "a".replaceAll(/a/, "b"); return "no" } catch { return "caught" }`)).toBe("caught")
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
test("split and search accept patterns", async () => {
|
|
218
|
+
expect(await value(`return "a1b22c".split(/\\d+/)`)).toEqual(["a", "b", "c"])
|
|
219
|
+
expect(await value(`return "ab42".search(/\\d/)`)).toBe(2)
|
|
220
|
+
expect(await value(`return "ab".search(/\\d/)`)).toBe(-1)
|
|
221
|
+
})
|
|
222
|
+
|
|
223
|
+
test("new RegExp constructs from strings; invalid patterns are catchable", async () => {
|
|
224
|
+
expect(await value(`return new RegExp("a+", "i").test("AAA")`)).toBe(true)
|
|
225
|
+
expect(await value(`try { new RegExp("("); return "no" } catch { return "caught" }`)).toBe("caught")
|
|
226
|
+
expect(await value(`return [/a/ instanceof RegExp, /a/.source]`)).toEqual([true, "a"])
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
test("invalid patterns fail with actionable messages", async () => {
|
|
230
|
+
const fromString = await error(`return "abc".match("(")`)
|
|
231
|
+
expect(fromString.message).toContain('String.match received the string "("')
|
|
232
|
+
expect(fromString.message).toContain("escape them with a backslash")
|
|
233
|
+
|
|
234
|
+
const fromConstructor = await error(`return new RegExp("(")`)
|
|
235
|
+
expect(fromConstructor.message).toContain('new RegExp(...) received "("')
|
|
236
|
+
expect(fromConstructor.message).toContain("escape them with a backslash")
|
|
237
|
+
|
|
238
|
+
const fromFlags = await error(`return new RegExp("a", "xz")`)
|
|
239
|
+
expect(fromFlags.message).toContain('invalid flags "xz"')
|
|
240
|
+
expect(fromFlags.message).toContain("Valid flags are")
|
|
241
|
+
})
|
|
242
|
+
|
|
243
|
+
test("missing g-flag errors say how to fix the call", async () => {
|
|
244
|
+
expect((await error(`return "aa".replaceAll(/a/, "b")`)).message).toContain("write /a/g, or use String.replace")
|
|
245
|
+
expect((await error(`return "aa".matchAll(/a/)`)).message).toContain("write /a/g, or use String.match")
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
test("a non-pattern argument names the expected shapes", async () => {
|
|
249
|
+
const err = await error(`return "abc".match(42)`)
|
|
250
|
+
expect(err.message).toContain("expects a regular expression")
|
|
251
|
+
expect(err.message).toContain("not number")
|
|
252
|
+
})
|
|
253
|
+
|
|
254
|
+
test("source and flags properties read through", async () => {
|
|
255
|
+
expect(await value(`const r = /ab/gi; return { source: r.source, flags: r.flags, global: r.global }`)).toEqual({
|
|
256
|
+
source: "ab",
|
|
257
|
+
flags: "gi",
|
|
258
|
+
global: true,
|
|
259
|
+
})
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
test("regexes serialize to {} at the boundary, like JSON", async () => {
|
|
263
|
+
expect(await value(`return /a/`)).toEqual({})
|
|
264
|
+
expect(await value(`return JSON.stringify({ r: /a/g })`)).toBe('{"r":{}}')
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
test("template interpolation renders the literal form", async () => {
|
|
268
|
+
expect(await value("return `${/ab/g}`")).toBe("/ab/g")
|
|
269
|
+
})
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
describe("URL and URI helpers", () => {
|
|
273
|
+
test("encodes and decodes complete URIs and URI components", async () => {
|
|
274
|
+
expect(
|
|
275
|
+
await value(`
|
|
276
|
+
return [
|
|
277
|
+
encodeURI("https://example.test/a b?q=a/b"),
|
|
278
|
+
encodeURIComponent("a b/c?"),
|
|
279
|
+
decodeURI("https://example.test/a%20b?q=a/b"),
|
|
280
|
+
decodeURIComponent("a%20b%2Fc%3F"),
|
|
281
|
+
["a b", "c/d"].map(encodeURIComponent),
|
|
282
|
+
]
|
|
283
|
+
`),
|
|
284
|
+
).toEqual([
|
|
285
|
+
"https://example.test/a%20b?q=a/b",
|
|
286
|
+
"a%20b%2Fc%3F",
|
|
287
|
+
"https://example.test/a b?q=a/b",
|
|
288
|
+
"a b/c?",
|
|
289
|
+
["a%20b", "c%2Fd"],
|
|
290
|
+
])
|
|
291
|
+
expect(
|
|
292
|
+
await value(`try { decodeURIComponent("%zz"); return false } catch (error) { return error instanceof URIError }`),
|
|
293
|
+
).toBe(true)
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
test("resolves and mutates URLs with linked search parameters", async () => {
|
|
297
|
+
expect(
|
|
298
|
+
await value(`
|
|
299
|
+
const url = new URL("../users?id=old#top", "https://user:pass@example.com:8443/api/v1/")
|
|
300
|
+
url.pathname = "/items/a b"
|
|
301
|
+
url.searchParams.set("id", "a b")
|
|
302
|
+
url.searchParams.append("tag", "x/y")
|
|
303
|
+
url.hash = "part 1"
|
|
304
|
+
return {
|
|
305
|
+
href: url.href,
|
|
306
|
+
origin: url.origin,
|
|
307
|
+
host: url.host,
|
|
308
|
+
pathname: url.pathname,
|
|
309
|
+
search: url.search,
|
|
310
|
+
id: url.searchParams.get("id"),
|
|
311
|
+
string: String(url),
|
|
312
|
+
json: url.toJSON(),
|
|
313
|
+
instances: [
|
|
314
|
+
url instanceof URL,
|
|
315
|
+
url.searchParams instanceof URLSearchParams,
|
|
316
|
+
url.searchParams === url.searchParams,
|
|
317
|
+
],
|
|
318
|
+
}
|
|
319
|
+
`),
|
|
320
|
+
).toEqual({
|
|
321
|
+
href: "https://user:pass@example.com:8443/items/a%20b?id=a+b&tag=x%2Fy#part%201",
|
|
322
|
+
origin: "https://example.com:8443",
|
|
323
|
+
host: "example.com:8443",
|
|
324
|
+
pathname: "/items/a%20b",
|
|
325
|
+
search: "?id=a+b&tag=x%2Fy",
|
|
326
|
+
id: "a b",
|
|
327
|
+
string: "https://user:pass@example.com:8443/items/a%20b?id=a+b&tag=x%2Fy#part%201",
|
|
328
|
+
json: "https://user:pass@example.com:8443/items/a%20b?id=a+b&tag=x%2Fy#part%201",
|
|
329
|
+
instances: [true, true, true],
|
|
330
|
+
})
|
|
331
|
+
})
|
|
332
|
+
|
|
333
|
+
test("URLSearchParams supports records, pairs, mutation, callbacks, and materialization", async () => {
|
|
334
|
+
expect(
|
|
335
|
+
await value(`
|
|
336
|
+
const params = new URLSearchParams([["tag", "b"], ["tag", "a"], ["q", "a b"]])
|
|
337
|
+
const seen = []
|
|
338
|
+
params.forEach((value, key) => seen.push(key + "=" + value))
|
|
339
|
+
params.delete("tag", "b")
|
|
340
|
+
params.append("tag", "c")
|
|
341
|
+
params.sort()
|
|
342
|
+
return {
|
|
343
|
+
text: params.toString(),
|
|
344
|
+
size: params.size,
|
|
345
|
+
tags: params.getAll("tag"),
|
|
346
|
+
has: params.has("tag", "c"),
|
|
347
|
+
entries: Array.from(params),
|
|
348
|
+
object: Object.fromEntries(params),
|
|
349
|
+
record: new URLSearchParams({ page: 2, filter: "open" }).toString(),
|
|
350
|
+
seen,
|
|
351
|
+
}
|
|
352
|
+
`),
|
|
353
|
+
).toEqual({
|
|
354
|
+
text: "q=a+b&tag=a&tag=c",
|
|
355
|
+
size: 3,
|
|
356
|
+
tags: ["a", "c"],
|
|
357
|
+
has: true,
|
|
358
|
+
entries: [
|
|
359
|
+
["q", "a b"],
|
|
360
|
+
["tag", "a"],
|
|
361
|
+
["tag", "c"],
|
|
362
|
+
],
|
|
363
|
+
object: { q: "a b", tag: "c" },
|
|
364
|
+
record: "page=2&filter=open",
|
|
365
|
+
seen: ["tag=b", "tag=a", "q=a b"],
|
|
366
|
+
})
|
|
367
|
+
})
|
|
368
|
+
|
|
369
|
+
test("URL parsing failures are catchable and values use native JSON forms", async () => {
|
|
370
|
+
expect(
|
|
371
|
+
await value(`
|
|
372
|
+
const parsed = URL.parse("/users", "https://example.test/api/")
|
|
373
|
+
let invalidIsTypeError = false
|
|
374
|
+
try { new URL("not relative without a base") } catch (error) { invalidIsTypeError = error instanceof TypeError }
|
|
375
|
+
return {
|
|
376
|
+
canParse: URL.canParse("/users", "https://example.test/api/"),
|
|
377
|
+
cannotParse: URL.canParse("not relative without a base"),
|
|
378
|
+
parsed: parsed.href,
|
|
379
|
+
invalidIsTypeError,
|
|
380
|
+
boundary: [new URL("https://example.test/a"), new URLSearchParams("q=one")],
|
|
381
|
+
json: JSON.stringify({ url: new URL("https://example.test/a"), params: new URLSearchParams("q=one") }),
|
|
382
|
+
}
|
|
383
|
+
`),
|
|
384
|
+
).toEqual({
|
|
385
|
+
canParse: true,
|
|
386
|
+
cannotParse: false,
|
|
387
|
+
parsed: "https://example.test/users",
|
|
388
|
+
invalidIsTypeError: true,
|
|
389
|
+
boundary: ["https://example.test/a", {}],
|
|
390
|
+
json: '{"url":"https://example.test/a","params":{}}',
|
|
391
|
+
})
|
|
392
|
+
})
|
|
393
|
+
|
|
394
|
+
test("distinguishes omitted URL arguments from explicit undefined", async () => {
|
|
395
|
+
expect(
|
|
396
|
+
await value(`
|
|
397
|
+
function throwsTypeError(run) {
|
|
398
|
+
try { run(); return false } catch (error) { return error instanceof TypeError }
|
|
399
|
+
}
|
|
400
|
+
const params = new URLSearchParams()
|
|
401
|
+
const required = [
|
|
402
|
+
() => params.append(),
|
|
403
|
+
() => params.delete(),
|
|
404
|
+
() => params.get(),
|
|
405
|
+
() => params.getAll(),
|
|
406
|
+
() => params.has(),
|
|
407
|
+
() => params.set(),
|
|
408
|
+
() => params.forEach(),
|
|
409
|
+
].map(throwsTypeError)
|
|
410
|
+
params.append(undefined, undefined)
|
|
411
|
+
return {
|
|
412
|
+
construct: throwsTypeError(() => new URL()),
|
|
413
|
+
canParse: throwsTypeError(() => URL.canParse()),
|
|
414
|
+
parse: throwsTypeError(() => URL.parse()),
|
|
415
|
+
explicitUndefined: new URL(undefined, "https://example.test/base/").href,
|
|
416
|
+
params: params.toString(),
|
|
417
|
+
required,
|
|
418
|
+
}
|
|
419
|
+
`),
|
|
420
|
+
).toEqual({
|
|
421
|
+
construct: true,
|
|
422
|
+
canParse: true,
|
|
423
|
+
parse: true,
|
|
424
|
+
explicitUndefined: "https://example.test/base/undefined",
|
|
425
|
+
params: "undefined=undefined",
|
|
426
|
+
required: [true, true, true, true, true, true, true],
|
|
427
|
+
})
|
|
428
|
+
})
|
|
429
|
+
})
|
|
430
|
+
|
|
431
|
+
describe("Map", () => {
|
|
432
|
+
test("get/set/has/size with chaining", async () => {
|
|
433
|
+
expect(
|
|
434
|
+
await value(`
|
|
435
|
+
const m = new Map()
|
|
436
|
+
m.set("a", 1).set("b", 2)
|
|
437
|
+
return { a: m.get("a"), b: m.get("b"), has: m.has("a"), miss: m.get("zz") === undefined, size: m.size }
|
|
438
|
+
`),
|
|
439
|
+
).toEqual({ a: 1, b: 2, has: true, miss: true, size: 5 - 3 })
|
|
440
|
+
})
|
|
441
|
+
|
|
442
|
+
test("object keys use identity", async () => {
|
|
443
|
+
expect(
|
|
444
|
+
await value(`
|
|
445
|
+
const key = { id: 1 }
|
|
446
|
+
const m = new Map()
|
|
447
|
+
m.set(key, "hit")
|
|
448
|
+
return [m.get(key), m.get({ id: 1 }) === undefined]
|
|
449
|
+
`),
|
|
450
|
+
).toEqual(["hit", true])
|
|
451
|
+
})
|
|
452
|
+
|
|
453
|
+
test("construction from entry pairs and another Map", async () => {
|
|
454
|
+
expect(await value(`const m = new Map([["a", 1], ["b", 2]]); return m.get("b")`)).toBe(2)
|
|
455
|
+
expect(
|
|
456
|
+
await value(
|
|
457
|
+
`const m = new Map([["a", 1]]); const n = new Map(m); n.set("b", 2); return [n.get("a"), n.get("b"), m.has("b")]`,
|
|
458
|
+
),
|
|
459
|
+
).toEqual([1, 2, false])
|
|
460
|
+
expect((await error(`return new Map("nope")`)).message).toMatch(/\[key, value\] pairs/)
|
|
461
|
+
expect((await error(`return new Map(["flat"])`)).message).toMatch(/\[key, value\] pairs/)
|
|
462
|
+
})
|
|
463
|
+
|
|
464
|
+
test("keys/values/entries return arrays", async () => {
|
|
465
|
+
expect(
|
|
466
|
+
await value(`
|
|
467
|
+
const m = new Map([["a", 1], ["b", 2]])
|
|
468
|
+
return { keys: m.keys(), values: m.values(), entries: m.entries() }
|
|
469
|
+
`),
|
|
470
|
+
).toEqual({
|
|
471
|
+
keys: ["a", "b"],
|
|
472
|
+
values: [1, 2],
|
|
473
|
+
entries: [
|
|
474
|
+
["a", 1],
|
|
475
|
+
["b", 2],
|
|
476
|
+
],
|
|
477
|
+
})
|
|
478
|
+
})
|
|
479
|
+
|
|
480
|
+
test("Object.fromEntries(map) and Array.from(map)", async () => {
|
|
481
|
+
expect(await value(`return Object.fromEntries(new Map([["a", 1], ["b", 2]]))`)).toEqual({ a: 1, b: 2 })
|
|
482
|
+
expect(await value(`return Array.from(new Map([["a", 1]]))`)).toEqual([["a", 1]])
|
|
483
|
+
})
|
|
484
|
+
|
|
485
|
+
test("for...of iterates [key, value] pairs with destructuring", async () => {
|
|
486
|
+
expect(
|
|
487
|
+
await value(`
|
|
488
|
+
const m = new Map([["a", 1], ["b", 2]])
|
|
489
|
+
let total = 0
|
|
490
|
+
let names = ""
|
|
491
|
+
for (const [key, count] of m) { names += key; total += count }
|
|
492
|
+
return names + total
|
|
493
|
+
`),
|
|
494
|
+
).toBe("ab3")
|
|
495
|
+
})
|
|
496
|
+
|
|
497
|
+
test("spread produces entry pairs", async () => {
|
|
498
|
+
expect(await value(`return [...new Map([["a", 1]])]`)).toEqual([["a", 1]])
|
|
499
|
+
})
|
|
500
|
+
|
|
501
|
+
test("forEach passes (value, key)", async () => {
|
|
502
|
+
expect(
|
|
503
|
+
await value(`
|
|
504
|
+
const m = new Map([["a", 1], ["b", 2]])
|
|
505
|
+
const seen = []
|
|
506
|
+
m.forEach((count, key) => seen.push(key + count))
|
|
507
|
+
return seen
|
|
508
|
+
`),
|
|
509
|
+
).toEqual(["a1", "b2"])
|
|
510
|
+
})
|
|
511
|
+
|
|
512
|
+
test("delete and clear", async () => {
|
|
513
|
+
expect(
|
|
514
|
+
await value(`
|
|
515
|
+
const m = new Map([["a", 1], ["b", 2]])
|
|
516
|
+
const removed = m.delete("a")
|
|
517
|
+
const missed = m.delete("zz")
|
|
518
|
+
const sizeAfterDelete = m.size
|
|
519
|
+
m.clear()
|
|
520
|
+
return [removed, missed, sizeAfterDelete, m.size]
|
|
521
|
+
`),
|
|
522
|
+
).toEqual([true, false, 1, 0])
|
|
523
|
+
})
|
|
524
|
+
|
|
525
|
+
test("counting idiom: grouped tallies", async () => {
|
|
526
|
+
expect(
|
|
527
|
+
await value(`
|
|
528
|
+
const words = ["a", "b", "a", "c", "a"]
|
|
529
|
+
const counts = new Map()
|
|
530
|
+
for (const word of words) counts.set(word, (counts.get(word) ?? 0) + 1)
|
|
531
|
+
return Object.fromEntries(counts)
|
|
532
|
+
`),
|
|
533
|
+
).toEqual({ a: 3, b: 1, c: 1 })
|
|
534
|
+
})
|
|
535
|
+
|
|
536
|
+
test("maps serialize to {} at the boundary, like JSON", async () => {
|
|
537
|
+
expect(await value(`return new Map([["a", 1]])`)).toEqual({})
|
|
538
|
+
expect(await value(`return JSON.stringify(new Map([["a", 1]]))`)).toBe("{}")
|
|
539
|
+
})
|
|
540
|
+
|
|
541
|
+
test("console.log renders map contents for debugging", async () => {
|
|
542
|
+
const result = await run(`console.log(new Map([["a", 1]])); return null`)
|
|
543
|
+
expect(result.ok).toBe(true)
|
|
544
|
+
expect(result.logs?.[0]).toBe(`Map(1) [["a",1]]`)
|
|
545
|
+
})
|
|
546
|
+
})
|
|
547
|
+
|
|
548
|
+
describe("Set", () => {
|
|
549
|
+
test("add/has/delete/size with chaining", async () => {
|
|
550
|
+
expect(
|
|
551
|
+
await value(`
|
|
552
|
+
const s = new Set()
|
|
553
|
+
s.add(1).add(2).add(1)
|
|
554
|
+
const removed = s.delete(2)
|
|
555
|
+
return [s.size, s.has(1), s.has(2), removed]
|
|
556
|
+
`),
|
|
557
|
+
).toEqual([1, true, false, true])
|
|
558
|
+
})
|
|
559
|
+
|
|
560
|
+
test("dedupe idiom: [...new Set(items)]", async () => {
|
|
561
|
+
expect(await value(`return [...new Set([1, 2, 2, 3, 1])]`)).toEqual([1, 2, 3])
|
|
562
|
+
})
|
|
563
|
+
|
|
564
|
+
test("construction from strings and other Sets", async () => {
|
|
565
|
+
expect(await value(`return [...new Set("aba")]`)).toEqual(["a", "b"])
|
|
566
|
+
expect(await value(`return Array.from(new Set(new Set([1, 2])))`)).toEqual([1, 2])
|
|
567
|
+
})
|
|
568
|
+
|
|
569
|
+
test("SameValueZero: NaN is findable", async () => {
|
|
570
|
+
expect(await value(`const s = new Set([NaN]); return s.has(NaN)`)).toBe(true)
|
|
571
|
+
})
|
|
572
|
+
|
|
573
|
+
test("for...of iterates values", async () => {
|
|
574
|
+
expect(
|
|
575
|
+
await value(`
|
|
576
|
+
let total = 0
|
|
577
|
+
for (const n of new Set([1, 2, 3])) total += n
|
|
578
|
+
return total
|
|
579
|
+
`),
|
|
580
|
+
).toBe(6)
|
|
581
|
+
})
|
|
582
|
+
|
|
583
|
+
test("sets serialize to {} at the boundary, like JSON", async () => {
|
|
584
|
+
expect(await value(`return { s: new Set([1]) }`)).toEqual({ s: {} })
|
|
585
|
+
})
|
|
586
|
+
})
|
|
587
|
+
|
|
588
|
+
describe("stdlib integration", () => {
|
|
589
|
+
test("typeof reports constructors as functions and never throws", async () => {
|
|
590
|
+
expect(await value(`return typeof Map`)).toBe("function")
|
|
591
|
+
expect(await value(`return typeof ((x) => x)`)).toBe("function")
|
|
592
|
+
expect(await value(`return typeof Math`)).toBe("object")
|
|
593
|
+
expect(await value(`return typeof tools`)).toBe("object")
|
|
594
|
+
})
|
|
595
|
+
|
|
596
|
+
test("negation works on any value", async () => {
|
|
597
|
+
expect(await value(`return !new Map()`)).toBe(false)
|
|
598
|
+
expect(await value(`const fn = () => 1; return !fn`)).toBe(false)
|
|
599
|
+
})
|
|
600
|
+
|
|
601
|
+
test("object spread of sandbox values is a no-op, like JS", async () => {
|
|
602
|
+
expect(await value(`return { ...new Map([["a", 1]]), kept: true }`)).toEqual({ kept: true })
|
|
603
|
+
})
|
|
604
|
+
|
|
605
|
+
test("dates inside Map values survive in-sandbox reads", async () => {
|
|
606
|
+
expect(
|
|
607
|
+
await value(`
|
|
608
|
+
const m = new Map([["start", new Date(1000)]])
|
|
609
|
+
return m.get("start").getTime()
|
|
610
|
+
`),
|
|
611
|
+
).toBe(1000)
|
|
612
|
+
})
|
|
613
|
+
|
|
614
|
+
test("instanceof recognizes the stdlib value types", async () => {
|
|
615
|
+
expect(
|
|
616
|
+
await value(
|
|
617
|
+
`return [new Date(0) instanceof Date, /a/ instanceof RegExp, new Map() instanceof Map, new Set() instanceof Set]`,
|
|
618
|
+
),
|
|
619
|
+
).toEqual([true, true, true, true])
|
|
620
|
+
expect(
|
|
621
|
+
await value(`return [[1] instanceof Array, [1] instanceof Object, ({}) instanceof Object, 5 instanceof Object]`),
|
|
622
|
+
).toEqual([true, true, true, false])
|
|
623
|
+
expect(await value(`return [new Map() instanceof Set, "s" instanceof Date]`)).toEqual([false, false])
|
|
624
|
+
expect(
|
|
625
|
+
await value(`const p = Promise.resolve(1); const isPromise = p instanceof Promise; await p; return isPromise`),
|
|
626
|
+
).toBe(true)
|
|
627
|
+
})
|
|
628
|
+
|
|
629
|
+
test("realistic pipeline: parse, extract with regex, dedupe, count by day", async () => {
|
|
630
|
+
expect(
|
|
631
|
+
await value(`
|
|
632
|
+
const raw = '[{"at":"2024-01-01T05:00:00Z","tag":"a b"},{"at":"2024-01-01T09:00:00Z","tag":"b c"},{"at":"2024-01-02T01:00:00Z","tag":"a"}]'
|
|
633
|
+
const rows = JSON.parse(raw)
|
|
634
|
+
const tags = new Set()
|
|
635
|
+
const byDay = new Map()
|
|
636
|
+
for (const row of rows) {
|
|
637
|
+
for (const m of row.tag.matchAll(/[a-z]+/g)) tags.add(m[0])
|
|
638
|
+
const day = new Date(row.at).toISOString().slice(0, 10)
|
|
639
|
+
byDay.set(day, (byDay.get(day) ?? 0) + 1)
|
|
640
|
+
}
|
|
641
|
+
return { tags: [...tags].sort((a, b) => (a < b ? -1 : 1)), byDay: Object.fromEntries(byDay) }
|
|
642
|
+
`),
|
|
643
|
+
).toEqual({ tags: ["a", "b", "c"], byDay: { "2024-01-01": 2, "2024-01-02": 1 } })
|
|
644
|
+
})
|
|
645
|
+
})
|
|
646
|
+
|
|
647
|
+
describe("sandbox values at intra-sandbox checkpoints", () => {
|
|
648
|
+
test("Object.values/entries keep Dates usable", async () => {
|
|
649
|
+
expect(await value(`return Object.values({ d: new Date(0) })[0].getTime()`)).toBe(0)
|
|
650
|
+
expect(await value(`const [key, d] = Object.entries({ d: new Date(0) })[0]; return key + ":" + d.getTime()`)).toBe(
|
|
651
|
+
"d:0",
|
|
652
|
+
)
|
|
653
|
+
})
|
|
654
|
+
|
|
655
|
+
test("Object.assign keeps Maps usable", async () => {
|
|
656
|
+
expect(await value(`const merged = Object.assign({}, { m: new Map([["a", 1]]) }); return merged.m.get("a")`)).toBe(
|
|
657
|
+
1,
|
|
658
|
+
)
|
|
659
|
+
})
|
|
660
|
+
|
|
661
|
+
test("object and array spread keep sandbox values usable", async () => {
|
|
662
|
+
expect(
|
|
663
|
+
await value(`
|
|
664
|
+
const src = { m: new Map([["a", 1]]) }
|
|
665
|
+
const copy = { ...src }
|
|
666
|
+
copy.m.set("b", 2)
|
|
667
|
+
return [copy.m.get("a"), src.m.get("b")]
|
|
668
|
+
`),
|
|
669
|
+
).toEqual([1, 2])
|
|
670
|
+
expect(await value(`const list = [new Date(1000)]; const copy = [...list]; return copy[0].getTime()`)).toBe(1000)
|
|
671
|
+
})
|
|
672
|
+
|
|
673
|
+
test("Array.from over arrays keeps nested sandbox values usable", async () => {
|
|
674
|
+
expect(await value(`return Array.from([new Date(5)])[0].getTime()`)).toBe(5)
|
|
675
|
+
})
|
|
676
|
+
|
|
677
|
+
test("regexes stay callable through Object.values", async () => {
|
|
678
|
+
expect(await value(`return Object.values({ r: /ab+/ })[0].test("abb")`)).toBe(true)
|
|
679
|
+
})
|
|
680
|
+
|
|
681
|
+
test("Object.* helpers see sandbox values as empty objects, never internals", async () => {
|
|
682
|
+
expect(await value(`return Object.keys(new Map([["a", 1]]))`)).toEqual([])
|
|
683
|
+
expect(await value(`return Object.values(new Date(0))`)).toEqual([])
|
|
684
|
+
expect(await value(`return Object.entries(new Set([1]))`)).toEqual([])
|
|
685
|
+
expect(await value(`return Object.assign({}, new Map([["a", 1]]))`)).toEqual({})
|
|
686
|
+
expect(await value(`return Object.hasOwn(new Date(0), "time")`)).toBe(false)
|
|
687
|
+
})
|
|
688
|
+
|
|
689
|
+
test("the host boundary still serializes JSON forms: results, JSON.stringify, and tool arguments", async () => {
|
|
690
|
+
expect(await value(`return { d: new Date(0), m: new Map([["a", 1]]) }`)).toEqual({
|
|
691
|
+
d: "1970-01-01T00:00:00.000Z",
|
|
692
|
+
m: {},
|
|
693
|
+
})
|
|
694
|
+
expect(await value(`return JSON.stringify({ d: new Date(0) })`)).toBe('{"d":"1970-01-01T00:00:00.000Z"}')
|
|
695
|
+
|
|
696
|
+
const observed: Array<unknown> = []
|
|
697
|
+
const capture = Tool.make({
|
|
698
|
+
description: "Capture the exact input the host receives",
|
|
699
|
+
input: { type: "object" },
|
|
700
|
+
run: (input) =>
|
|
701
|
+
Effect.sync(() => {
|
|
702
|
+
observed.push(input)
|
|
703
|
+
return "ok"
|
|
704
|
+
}),
|
|
705
|
+
})
|
|
706
|
+
const result = await Effect.runPromise(
|
|
707
|
+
CodeMode.execute({
|
|
708
|
+
tools: { host: { capture } },
|
|
709
|
+
code: `return await tools.host.capture({ when: new Date(0), tags: new Map([["a", 1]]) })`,
|
|
710
|
+
}),
|
|
711
|
+
)
|
|
712
|
+
expect(result.ok).toBe(true)
|
|
713
|
+
expect(observed).toStrictEqual([{ when: "1970-01-01T00:00:00.000Z", tags: {} }])
|
|
714
|
+
})
|
|
715
|
+
})
|