parity.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. import { describe, expect, test } from "bun:test"
  2. import { Effect } from "effect"
  3. import { CodeMode } from "../src/index.js"
  4. import { ToolRuntime } from "../src/tool-runtime.js"
  5. // Runs a CodeMode program with no host tools and returns the CodeMode.Result. These tests pin the
  6. // JS-parity behaviors for the "99% of ordinary defensive JavaScript just works" goal: cases where
  7. // a strict interpreter would throw but idiomatic JS yields undefined / succeeds.
  8. //
  9. // Note on the result boundary: this package normalizes a bare `undefined` result to `null` when
  10. // it crosses out of the sandbox (results are JSON data), so tests asserting an in-sandbox
  11. // `undefined` read check `=== undefined` inside the program and `null` at the boundary.
  12. const run = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} }))
  13. const value = async (code: string) => {
  14. const result = await run(code)
  15. if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`)
  16. return result.value
  17. }
  18. const error = async (code: string) => {
  19. const result = await run(code)
  20. if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`)
  21. return result.error
  22. }
  23. describe("H2: string property access reads as undefined (not a throw)", () => {
  24. test("unknown property on a string is undefined", async () => {
  25. expect(await value(`const s = "hi"; return s.login === undefined`)).toBe(true)
  26. expect(await value(`const s = "hi"; return s.login`)).toBeNull()
  27. })
  28. test("optional chaining + fallback on a string does not throw", async () => {
  29. expect(await value(`const s = "hi"; return s?.login ?? "fallback"`)).toBe("fallback")
  30. })
  31. test("the real MCP pattern: result is a JSON string, defensive read falls through", async () => {
  32. // me.result is a string; me.result?.login is undefined, so we fall back to the raw string.
  33. expect(await value(`const me = { result: '{"login":"x"}' }; return me.result?.login ?? me.result`)).toBe(
  34. '{"login":"x"}',
  35. )
  36. })
  37. test("unknown property on a number is undefined", async () => {
  38. expect(await value(`return (5).foo ?? "n"`)).toBe("n")
  39. })
  40. test("supported string methods still work", async () => {
  41. expect(await value(`return "AB".toLowerCase()`)).toBe("ab")
  42. expect(await value(`return "hello".length`)).toBe(5)
  43. })
  44. })
  45. describe("H3: array property access reads as undefined (not a throw)", () => {
  46. test("unknown property on an array is undefined", async () => {
  47. expect(await value(`return [1,2,3].foo === undefined`)).toBe(true)
  48. expect(await value(`return [1,2,3].foo`)).toBeNull()
  49. })
  50. test("optional chaining on an array does not throw", async () => {
  51. expect(await value(`return [1,2,3]?.foo ?? "fb"`)).toBe("fb")
  52. })
  53. test("unknown property reads stay undefined for methods CodeMode does not implement", async () => {
  54. expect(await value(`return [1,2,3].toSpliced === undefined`)).toBe(true)
  55. })
  56. test("supported array methods and indexing still work", async () => {
  57. expect(await value(`return [1,2,3].map(x => x + 1)`)).toEqual([2, 3, 4])
  58. expect(await value(`return [1,2,3][9] === undefined`)).toBe(true)
  59. expect(await value(`return [1,2,3][9]`)).toBeNull()
  60. })
  61. })
  62. describe("H6: object spread of null/undefined is a no-op", () => {
  63. test("spreading null is a no-op", async () => {
  64. expect(await value(`const o = null; return { ...o, a: 1 }`)).toEqual({ a: 1 })
  65. })
  66. test("spreading an absent argument merges cleanly", async () => {
  67. expect(await value(`function f(opts){ return { ...opts, a: 1 } } return f(undefined)`)).toEqual({ a: 1 })
  68. })
  69. test("spreading a real object still works", async () => {
  70. expect(await value(`const o = { a: 1 }; return { ...o, b: 2 }`)).toEqual({ a: 1, b: 2 })
  71. })
  72. test("spreading an array into an object still errors", async () => {
  73. const err = await error(`return { ...[1,2], a: 1 }`)
  74. expect(err.kind).toBe("InvalidDataValue")
  75. })
  76. })
  77. describe("H4: typeof on an undeclared identifier is 'undefined'", () => {
  78. test("feature-detection guard does not throw", async () => {
  79. expect(await value(`return typeof foo === "undefined" ? "safe" : "no"`)).toBe("safe")
  80. })
  81. test("typeof of a declared binding is unaffected", async () => {
  82. expect(await value(`const x = 5; return typeof x`)).toBe("number")
  83. expect(await value(`const s = "a"; return typeof s`)).toBe("string")
  84. })
  85. test("referencing an undeclared identifier outside typeof still throws", async () => {
  86. const err = await error(`return foo + 1`)
  87. expect(err.message).toContain("foo")
  88. })
  89. })
  90. describe("H1: NaN/Infinity flow as intermediates and normalize to null at the boundary", () => {
  91. test("guards run instead of the program crashing on a transient NaN", async () => {
  92. expect(await value(`return parseInt("abc") || 0`)).toBe(0)
  93. expect(await value(`const x = Number("abc"); return Number.isNaN(x) ? 0 : x`)).toBe(0)
  94. expect(await value(`const o = {}; o.count = (o.count || 0) + 1; return o.count`)).toBe(1)
  95. // average of an empty list, guarded - the classic divide-by-zero that used to throw pre-guard
  96. expect(await value(`const a = []; return a.length ? a.reduce((s,x)=>s+x,0)/a.length : 0`)).toBe(0)
  97. })
  98. test("a non-finite value becomes null when it leaves the sandbox", async () => {
  99. expect(await value(`return 5/0`)).toBeNull()
  100. expect(await value(`return 0/0`)).toBeNull()
  101. expect(await value(`return Math.max()`)).toBeNull()
  102. // nested, too - normalization walks the returned structure
  103. expect(await value(`return { a: Number("x"), b: 2, c: [1/0] }`)).toEqual({ a: null, b: 2, c: [null] })
  104. })
  105. test("NaN and Infinity are usable identifiers and inspectable in-sandbox", async () => {
  106. expect(await value(`return Number.isNaN(NaN)`)).toBe(true)
  107. expect(await value(`return Infinity > 1e9`)).toBe(true)
  108. expect(await value(`return Number.isFinite(1/0)`)).toBe(false)
  109. expect(await value(`return [3,1,2].reduce((a,b)=>Math.max(a,b), -Infinity)`)).toBe(3)
  110. // JSON.stringify inside the sandbox matches JS: non-finite serializes to null
  111. expect(await value(`return JSON.stringify({ x: Number("z") })`)).toBe('{"x":null}')
  112. })
  113. test("copyOut normalizes non-finite numbers to null (the shared return + tool-arg boundary)", () => {
  114. // Tool-call arguments funnel through copyOut too, so this one function pins both boundaries.
  115. expect(ToolRuntime.copyOut(NaN)).toBeNull()
  116. expect(ToolRuntime.copyOut(Infinity)).toBeNull()
  117. expect(ToolRuntime.copyOut(-Infinity)).toBeNull()
  118. expect(ToolRuntime.copyOut(42)).toBe(42)
  119. expect(ToolRuntime.copyOut({ a: NaN, b: [Infinity, 1] })).toEqual({ a: null, b: [null, 1] })
  120. })
  121. })
  122. describe("Error values and instanceof", () => {
  123. test("new Error carries name/message and is instanceof Error", async () => {
  124. expect(await value(`const e = new Error("boom"); return [e instanceof Error, e.name, e.message]`)).toEqual([
  125. true,
  126. "Error",
  127. "boom",
  128. ])
  129. })
  130. test("Error without new behaves like new Error", async () => {
  131. expect(await value(`const e = Error("plain"); return [e instanceof Error, e.name, e.message]`)).toEqual([
  132. true,
  133. "Error",
  134. "plain",
  135. ])
  136. expect(await value(`const e = new Error(); return [e.name, e.message, e instanceof Error]`)).toEqual([
  137. "Error",
  138. "",
  139. true,
  140. ])
  141. })
  142. test("specific error types are instanceof themselves and Error, not each other", async () => {
  143. expect(
  144. await value(
  145. `const e = new TypeError("t"); return [e instanceof TypeError, e instanceof Error, e instanceof RangeError]`,
  146. ),
  147. ).toEqual([true, true, false])
  148. expect(await value(`return new Error("e") instanceof TypeError`)).toBe(false)
  149. })
  150. test("thrown errors keep instanceof through try/catch", async () => {
  151. expect(await value(`try { throw new Error("x") } catch (e) { return [e instanceof Error, e.message] }`)).toEqual([
  152. true,
  153. "x",
  154. ])
  155. })
  156. test("interpreter runtime failures are caught as Error values", async () => {
  157. expect(await value(`try { JSON.parse("nope") } catch (e) { return e instanceof Error }`)).toBe(true)
  158. expect(await value(`try { undeclared() } catch (e) { return e instanceof Error }`)).toBe(true)
  159. })
  160. test("caught failures carry the constructor name the real-JS failure would have", async () => {
  161. // JSON.parse throws SyntaxError: name and specific-instanceof both carry through, and the
  162. // message keeps the engine's position detail.
  163. expect(
  164. await value(`
  165. try { JSON.parse("{oops") } catch (e) {
  166. return [e.name, e instanceof SyntaxError, e instanceof Error, e instanceof TypeError, e.message.includes("JSON")]
  167. }
  168. `),
  169. ).toEqual(["SyntaxError", true, true, false, true])
  170. expect(await value(`try { undeclared() } catch (e) { return [e.name, e instanceof ReferenceError] }`)).toEqual([
  171. "ReferenceError",
  172. true,
  173. ])
  174. expect(await value(`try { const c = 1; c = 2 } catch (e) { return [e.name, e instanceof TypeError] }`)).toEqual([
  175. "TypeError",
  176. true,
  177. ])
  178. expect(await value(`try { "a".normalize("NOPE") } catch (e) { return [e.name, e instanceof RangeError] }`)).toEqual(
  179. ["RangeError", true],
  180. )
  181. expect(await value(`try { "a".match("(") } catch (e) { return [e.name, e instanceof SyntaxError] }`)).toEqual([
  182. "SyntaxError",
  183. true,
  184. ])
  185. expect(await value(`try { new RegExp("(") } catch (e) { return [e.name, e instanceof SyntaxError] }`)).toEqual([
  186. "SyntaxError",
  187. true,
  188. ])
  189. })
  190. test("diagnostics without a specific real-JS analogue are named plain Error", async () => {
  191. expect(await value(`try { JSON.parse(5) } catch (e) { return [e.name, e instanceof Error] }`)).toEqual([
  192. "Error",
  193. true,
  194. ])
  195. })
  196. test("Promise.allSettled rejection reasons are Error values", async () => {
  197. expect(
  198. await value(`
  199. const settled = await Promise.allSettled([Promise.reject(new Error("b"))])
  200. return [settled[0].reason instanceof Error, settled[0].reason.message]
  201. `),
  202. ).toEqual([true, "b"])
  203. })
  204. test("non-error thrown values are not instanceof Error", async () => {
  205. expect(await value(`try { throw "raw" } catch (e) { return e instanceof Error }`)).toBe(false)
  206. expect(await value(`try { throw { message: "shaped" } } catch (e) { return e instanceof Error }`)).toBe(false)
  207. })
  208. test("plain data is never instanceof Error", async () => {
  209. expect(await value(`return [({}) instanceof Error, "s" instanceof Error, null instanceof Error]`)).toEqual([
  210. false,
  211. false,
  212. false,
  213. ])
  214. })
  215. test("error values still serialize as plain { name, message } data", async () => {
  216. expect(await value(`return new Error("m")`)).toEqual({ name: "Error", message: "m" })
  217. expect(await value(`return JSON.stringify(new Error("m"))`)).toBe('{"name":"Error","message":"m"}')
  218. expect(await value(`try { throw new Error("m") } catch (e) { return Object.keys(e) }`)).toEqual(["name", "message"])
  219. })
  220. test("spreading an error loses the brand, like losing the prototype in JS", async () => {
  221. expect(await value(`const e = new Error("m"); return ({ ...e }) instanceof Error`)).toBe(false)
  222. expect(await value(`const e = new Error("m"); return { ...e }`)).toEqual({ name: "Error", message: "m" })
  223. })
  224. test("typeof Error is function; an unknown instanceof right-hand side is a catchable error", async () => {
  225. expect(await value(`return typeof Error`)).toBe("function")
  226. expect(await value(`try { return 1 instanceof 5 } catch (e) { return "caught" }`)).toBe("caught")
  227. const err = await error(`return 1 instanceof 5`)
  228. expect(err.message).toContain("right-hand side of 'instanceof'")
  229. })
  230. })
  231. describe("array methods: splice, fill, copyWithin, keys/values/entries", () => {
  232. test("splice removes in place and returns the removed elements", async () => {
  233. expect(await value(`const a = [1,2,3,4]; const removed = a.splice(1, 2); return { removed, a }`)).toEqual({
  234. removed: [2, 3],
  235. a: [1, 4],
  236. })
  237. })
  238. test("splice inserts new elements at the cut", async () => {
  239. expect(await value(`const a = ["a","d"]; a.splice(1, 0, "b", "c"); return a`)).toEqual(["a", "b", "c", "d"])
  240. expect(await value(`const a = [1,2,3]; const removed = a.splice(1, 1, "x"); return { removed, a }`)).toEqual({
  241. removed: [2],
  242. a: [1, "x", 3],
  243. })
  244. })
  245. test("splice with one argument removes to the end; negative start counts back", async () => {
  246. expect(await value(`const a = [1,2,3]; const removed = a.splice(1); return { removed, a }`)).toEqual({
  247. removed: [2, 3],
  248. a: [1],
  249. })
  250. expect(await value(`const a = [1,2,3]; const removed = a.splice(-1); return { removed, a }`)).toEqual({
  251. removed: [3],
  252. a: [1, 2],
  253. })
  254. })
  255. test("splice rejects inserting a container into itself", async () => {
  256. const err = await error(`const a = [1]; a.splice(0, 0, [a]); return a`)
  257. expect(err.kind).toBe("InvalidDataValue")
  258. expect(err.message).toContain("circular")
  259. })
  260. test("fill overwrites a range and returns the mutated array", async () => {
  261. expect(await value(`const a = [1,2,3,4]; return a.fill(0, 1, 3)`)).toEqual([1, 0, 0, 4])
  262. expect(await value(`return [1,2,3].fill("z")`)).toEqual(["z", "z", "z"])
  263. })
  264. test("copyWithin copies a range in place", async () => {
  265. expect(await value(`return [1,2,3,4,5].copyWithin(0, 3)`)).toEqual([4, 5, 3, 4, 5])
  266. })
  267. test("keys/values/entries return arrays usable with for...of and spread", async () => {
  268. expect(await value(`return [...["x","y","z"].keys()]`)).toEqual([0, 1, 2])
  269. expect(await value(`return ["x","y"].values()`)).toEqual(["x", "y"])
  270. expect(
  271. await value(`
  272. const out = []
  273. for (const [index, item] of ["a","b"].entries()) out.push(index + ":" + item)
  274. return out
  275. `),
  276. ).toEqual(["0:a", "1:b"])
  277. expect(await value(`return [...[7].entries()]`)).toEqual([[0, 7]])
  278. })
  279. })
  280. describe("string methods: localeCompare, normalize, trim aliases", () => {
  281. test("localeCompare orders strings for sorting", async () => {
  282. expect(await value(`return ["b","a","c"].sort((x, y) => x.localeCompare(y))`)).toEqual(["a", "b", "c"])
  283. expect(await value(`return "a".localeCompare("a")`)).toBe(0)
  284. })
  285. test("normalize applies unicode normalization forms", async () => {
  286. expect(await value(`return "\\u0065\\u0301".normalize("NFC").length`)).toBe(1)
  287. expect(await value(`return "\\u00e9".normalize("NFD").length`)).toBe(2)
  288. expect(await value(`return "x".normalize() === "x"`)).toBe(true)
  289. })
  290. test("an invalid normalize form is a clear catchable error", async () => {
  291. expect(await value(`try { "x".normalize("nope"); return "no" } catch (e) { return e.message }`)).toContain('"NFC"')
  292. })
  293. test("trimLeft/trimRight alias trimStart/trimEnd", async () => {
  294. expect(await value(`return " x ".trimLeft()`)).toBe("x ")
  295. expect(await value(`return " x ".trimRight()`)).toBe(" x")
  296. })
  297. })
  298. describe("compound assignment matches its binary operator", () => {
  299. // `x op= y` must behave exactly like `x = x op y`, sharing the binary operator's coercion
  300. // semantics (Dates string-coerce for `+` and use their time value for arithmetic; data
  301. // objects/arrays coerce to their JS string form).
  302. const pair = async (compound: string, expanded: string) => {
  303. const [a, b] = await Promise.all([value(compound), value(expanded)])
  304. expect(a).toEqual(b)
  305. return a
  306. }
  307. test("sandbox Date += concatenates its string form, like d = d + 1", async () => {
  308. const result = await pair(`let d = new Date(1000); d += 1; return d`, `let d = new Date(1000); d = d + 1; return d`)
  309. expect(result).toBe("1970-01-01T00:00:01.000Z1")
  310. })
  311. test("sandbox Date numeric compound ops use its time value", async () => {
  312. expect(
  313. await pair(`let d = new Date(1000); d -= 400; return d`, `let d = new Date(1000); d = d - 400; return d`),
  314. ).toBe(600)
  315. expect(await pair(`let d = new Date(1000); d /= 4; return d`, `let d = new Date(1000); d = d / 4; return d`)).toBe(
  316. 250,
  317. )
  318. })
  319. test("string += object/array matches x = x + obj", async () => {
  320. expect(await pair(`let x = "a"; x += { b: 1 }; return x`, `let x = "a"; x = x + { b: 1 }; return x`)).toBe(
  321. "a[object Object]",
  322. )
  323. expect(await pair(`let x = "a"; x += [1, 2]; return x`, `let x = "a"; x = x + [1, 2]; return x`)).toBe("a1,2")
  324. })
  325. test("compound assignment through a member target coerces the same way", async () => {
  326. expect(
  327. await pair(
  328. `const o = { s: "t" }; o.s += new Date(0); return o.s`,
  329. `const o = { s: "t" }; o.s = o.s + new Date(0); return o.s`,
  330. ),
  331. ).toBe("t1970-01-01T00:00:00.000Z")
  332. })
  333. test("numeric and string compound operators sweep identically to their expansions", async () => {
  334. const cases: Array<[string, number | string]> = [
  335. [`let x = 7; x += 3; return x`, 7 + 3],
  336. [`let x = 7; x -= 3; return x`, 7 - 3],
  337. [`let x = 7; x *= 3; return x`, 7 * 3],
  338. [`let x = 7; x /= 2; return x`, 7 / 2],
  339. [`let x = 7; x %= 3; return x`, 7 % 3],
  340. [`let x = 7; x **= 2; return x`, 7 ** 2],
  341. [`let x = 7; x &= 3; return x`, 7 & 3],
  342. [`let x = 7; x |= 8; return x`, 7 | 8],
  343. [`let x = 7; x ^= 2; return x`, 7 ^ 2],
  344. [`let x = 7; x <<= 2; return x`, 7 << 2],
  345. [`let x = -7; x >>= 1; return x`, -7 >> 1],
  346. [`let x = -7; x >>>= 1; return x`, -7 >>> 1],
  347. [`let x = "a"; x += "b"; return x`, "ab"],
  348. ]
  349. for (const [compound, expected] of cases) {
  350. expect(await value(compound)).toBe(expected)
  351. expect(await value(compound.replace(/x (\S+)= /, (_, op) => `x = x ${op} `))).toBe(expected)
  352. }
  353. })
  354. })
  355. describe("H5: builtin coercion functions work as array callbacks", () => {
  356. test("filter(Boolean) drops falsy values", async () => {
  357. expect(await value(`return [0, 1, "", 2, null, 3].filter(Boolean)`)).toEqual([1, 2, 3])
  358. })
  359. test("map(String) coerces each element", async () => {
  360. expect(await value(`return [1, 2, 3].map(String)`)).toEqual(["1", "2", "3"])
  361. })
  362. test("arrow callbacks still work (no regression)", async () => {
  363. expect(await value(`return [1, 2, 3, 4].filter(x => x % 2 === 0)`)).toEqual([2, 4])
  364. expect(await value(`return [1, 2, 3].reduce((a, b) => a + b, 0)`)).toBe(6)
  365. })
  366. test("a non-callable callback is still rejected", async () => {
  367. const err = await error(`return [1,2,3].map(42)`)
  368. expect(err.message).toContain("callback")
  369. })
  370. })