The best way to control Claude Code, Codex and more from any computer or phone

main
ts 205 lines 6.57 KB
Raw
1 import { describe, expect, it } from "@alchemy.run/test";
2 import * as Redacted from "effect/Redacted";
3 import { packEnvValue, unpackEnvValue } from "@/RuntimeContext.ts";
4
5 describe("unpackEnvValue compatibility", { tags: ["unit", "local"] }, () => {
6 it("returns obvious non-JSON strings unchanged without attempting JSON.parse", () => {
7 const values = [
8 "",
9 " \t\r\n",
10 "alchemy-worker",
11 "https://example.com/api",
12 "queue-name",
13 " bucket-name\t",
14 "Infinity",
15 "NaN",
16 "+1",
17 ".5",
18 "\ufefftrue",
19 "\u00a0null",
20 ];
21 const parse = JSON.parse;
22 let calls = 0;
23 const results: unknown[] = [];
24 // This synchronous probe cannot overlap another test's JavaScript. Restore
25 // before assertions, and even if the function under test throws.
26 try {
27 JSON.parse = (...args: Parameters<typeof JSON.parse>) => {
28 calls++;
29 return parse(...args);
30 };
31 for (const value of values) results.push(unpackEnvValue(value));
32 } finally {
33 JSON.parse = parse;
34 }
35 expect(results).toEqual(values);
36 expect(calls).toBe(0);
37 });
38
39 it("skips JSON.parse only for strings JSON.parse rejects (every first character)", () => {
40 // A JSON text is `ws value ws`; only these characters start a value. Sweep
41 // every UTF-16 code unit behind each JSON-whitespace prefix, followed by
42 // suffixes that complete any value form, and require that every string
43 // the guard returns raw also fails JSON.parse — and decodes as before.
44 const parses = (raw: string) => {
45 try {
46 JSON.parse(raw);
47 return true;
48 } catch {
49 return false;
50 }
51 };
52 const starts = new Set<string>();
53 const falsePositives: string[] = [];
54 for (let code = 0; code <= 0xffff; code++) {
55 const c = String.fromCharCode(code);
56 for (const prefix of ["", " \t\r\n"]) {
57 for (const suffix of ["", "1", '"', "]", "}", "rue", "alse", "ull"]) {
58 const raw = prefix + c + suffix;
59 if (!parses(raw)) continue;
60 starts.add(c);
61 // A parseable string never decodes to its own raw text.
62 if (unpackEnvValue(raw) === raw) {
63 falsePositives.push(raw);
64 }
65 }
66 }
67 }
68 expect(falsePositives).toEqual([]);
69 expect([...starts].sort().join("")).toBe(
70 ["\t", "\n", "\r", " ", ...'"-0123456789[fnt{'].sort().join(""),
71 );
72 });
73
74 it("decodes every JSON primitive form, including negative zero and escaped strings", () => {
75 const cases: ReadonlyArray<readonly [string, unknown]> = [
76 ["null", null],
77 ["true", true],
78 ["false", false],
79 ["0", 0],
80 ["-0", -0],
81 ["123", 123],
82 ["-4.5", -4.5],
83 ["1e3", 1000],
84 ["1E-3", 0.001],
85 ["1e400", Infinity],
86 ['""', ""],
87 ['"line\\nbreak\\t\\u263a"', "line\nbreak\t☺"],
88 ];
89 for (const [raw, expected] of cases) {
90 expect(Object.is(unpackEnvValue(raw), expected)).toBe(true);
91 }
92 });
93
94 it("decodes arrays and objects", () => {
95 expect(unpackEnvValue("[]")).toEqual([]);
96 expect(unpackEnvValue("{}")).toEqual({});
97 expect(unpackEnvValue('{"nested":[1,true,null,{"name":"alice"}]}')).toEqual({
98 nested: [1, true, null, { name: "alice" }],
99 });
100 });
101
102 it("accepts only JSON whitespace around JSON values", () => {
103 for (const whitespace of [" ", "\t", "\r", "\n", " \t\r\n"]) {
104 expect(unpackEnvValue(`${whitespace}true${whitespace}`)).toBe(true);
105 expect(unpackEnvValue(`${whitespace}[1]${whitespace}`)).toEqual([1]);
106 expect(unpackEnvValue(`${whitespace}{"a":2}${whitespace}`)).toEqual({ a: 2 });
107 }
108 });
109
110 it("preserves non-JSON whitespace and BOM verbatim", () => {
111 for (const whitespace of [
112 "\v",
113 "\f",
114 "\u00a0",
115 "\u1680",
116 "\u2000",
117 "\u2028",
118 "\u2029",
119 "\u202f",
120 "\u205f",
121 "\u3000",
122 "\ufeff",
123 ]) {
124 for (const raw of [`${whitespace}null`, `null${whitespace}`, ` \t${whitespace}[1]`]) {
125 expect(unpackEnvValue(raw)).toBe(raw);
126 }
127 }
128 });
129
130 it("falls back to the exact raw string for malformed JSON candidates", () => {
131 for (const raw of [
132 "{",
133 "{not json",
134 "[1,]",
135 "[undefined]",
136 '"unterminated',
137 '"\\x20"',
138 "01",
139 "-",
140 "1e",
141 "trueish",
142 "false null",
143 "nullish",
144 " \t{bad}\r\n",
145 ]) {
146 expect(unpackEnvValue(raw)).toBe(raw);
147 }
148 });
149
150 it("returns a fresh decoded object on every evaluation", () => {
151 const raw = '{"items":[{"value":1}]}';
152 const first = unpackEnvValue<{ items: Array<{ value: number }> }>(raw)!;
153 first.items[0]!.value = 99;
154 const second = unpackEnvValue<{ items: Array<{ value: number }> }>(raw)!;
155 expect(second).toEqual({ items: [{ value: 1 }] });
156 expect(first === second).toBe(false);
157 expect(first.items === second.items).toBe(false);
158 });
159
160 it("reconstructs fresh Redacted values, including whitespace-prefixed markers", () => {
161 const raw = ` \t\r\n${packEnvValue(Redacted.make({ token: "secret" }))}\n`;
162 const first = unpackEnvValue<Redacted.Redacted<{ token: string }>>(raw)!;
163 const second = unpackEnvValue<Redacted.Redacted<{ token: string }>>(raw)!;
164 expect(Redacted.isRedacted(first)).toBe(true);
165 expect(Redacted.value(first)).toEqual({ token: "secret" });
166 expect(first === second).toBe(false);
167 expect(Redacted.value(first) === Redacted.value(second)).toBe(false);
168 expect(unpackEnvValue('{"_tag":"Redacted"}')).toEqual({ _tag: "Redacted" });
169 expect(unpackEnvValue('{"_tag":"Other","value":1}')).toEqual({
170 _tag: "Other",
171 value: 1,
172 });
173 });
174
175 it("preserves undefined", () => {
176 expect(unpackEnvValue(undefined)).toBeUndefined();
177 });
178
179 it("preserves existing non-string coercion and fallback behavior", () => {
180 // The public type accepts strings, but runtime env objects can reach this
181 // boundary untyped. The guard must leave JSON.parse's coercion unchanged.
182 const unpack = (raw: unknown) => unpackEnvValue(raw as string);
183 expect(unpack(null)).toBeNull();
184 expect(unpack(true)).toBe(true);
185 expect(unpack(123)).toBe(123);
186 expect(unpack(7n)).toBe(7);
187 expect(unpack([1])).toBe(1);
188 expect(unpack(new String('{"a":1}'))).toEqual({ a: 1 });
189 expect(unpack({ toString: () => '["coerced"]' })).toEqual(["coerced"]);
190 for (const raw of [
191 [],
192 [1, 2],
193 {},
194 Object.create(null),
195 Symbol("env"),
196 {
197 [Symbol.toPrimitive]: () => {
198 throw new Error("coercion failed");
199 },
200 },
201 ]) {
202 expect(unpack(raw)).toBe(raw);
203 }
204 });
205 });