Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion typescript/src/ts/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ export function createModuleTextFromProgram(jsonObject: object): Result<string>
return `[${arrayToString(obj)}]`;
}
else {
return `{ ${Object.keys(obj).map(key => `${JSON.stringify(key)}: ${exprToString(obj[key])}`).join(", ")} }`;
return `{ ${Object.keys(obj).map(key => `${key === "__proto__" ? '["__proto__"]' : JSON.stringify(key)}: ${exprToString(obj[key])}`).join(", ")} }`;
}
hasError = true;
return "";
Expand Down
4 changes: 2 additions & 2 deletions typescript/src/typechat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,14 +206,14 @@ export function createJsonTranslator<T extends object>(model: TypeChatLanguageMo
function stripNulls(obj: any) {
let keysToDelete: string[] | undefined;
for (const k in obj) {
const value = obj[k];
let value = obj[k];
if (value === null) {
(keysToDelete ??= []).push(k);
}
else {
if (Array.isArray(value)) {
if (value.some(x => x === null)) {
obj[k] = value.filter(x => x !== null);
value = obj[k] = value.filter(x => x !== null);
}
}
if (typeof value === "object") {
Expand Down
47 changes: 47 additions & 0 deletions typescript/test/failure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,53 @@ describe("translation failure context", () => {
});
});

describe("stripNulls array normalization", () => {
for (const { groups, expected } of [
{ groups: [null, [null, 1]], expected: [[1]] },
{ groups: [[null, 1], null, [null, null]], expected: [[1], []] }
]) {
it(`strips nulls from nested arrays ${JSON.stringify(groups)}`, async () => {
const validator = createTypeScriptJsonValidator<{ groups: number[][] }>(
"export interface Groups { groups: number[][]; }", "Groups"
);
try {
const model: TypeChatLanguageModel = {
complete: async () => success(JSON.stringify({ groups }))
};
const translator = createJsonTranslator(model, validator);
translator.stripNulls = true;
translator.attemptRepair = false;
const result = await translator.translate("request");
assert.ok(result.success);
assert.deepEqual(result.data, { groups: expected });
}
finally {
validator.close();
}
});
}

it("strips nulls from flat arrays", async () => {
const validator = createTypeScriptJsonValidator<{ items: number[] }>(
"export interface Items { items: number[]; }", "Items"
);
try {
const model: TypeChatLanguageModel = {
complete: async () => success('{"items":[null,1,null,2]}')
};
const translator = createJsonTranslator(model, validator);
translator.stripNulls = true;
translator.attemptRepair = false;
const result = await translator.translate("request");
assert.ok(result.success);
assert.deepEqual(result.data, { items: [1, 2] });
}
finally {
validator.close();
}
});
});

describe("repair failure context", () => {
it("preserves a successful repair and the existing repair prompt", async () => {
const first = '{"value":"invalid"}';
Expand Down
30 changes: 30 additions & 0 deletions typescript/test/program.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { stripTypeScriptTypes } from "node:module";
import { runInNewContext } from "node:vm";
import {
createModuleTextFromProgram,
createProgramTranslator,
Expand Down Expand Up @@ -186,6 +188,34 @@ describe("hasOwnProperty shadowing in parsed programs", () => {
});
});

describe("literal __proto__ property preservation in generated modules", () => {
for (const value of ["kept", { label: "kept" }, null]) {
it(`preserves an own __proto__ data property with value ${JSON.stringify(value)}`, async () => {
const input = JSON.parse(`{"__proto__": ${JSON.stringify(value)}, "value": 7}`);
const program: Program = { "@steps": [{ "@func": "identity", "@args": [input] }] };
const moduleResult = createModuleTextFromProgram(program);
assert.ok(moduleResult.success);
assert.match(moduleResult.data, /\["__proto__"\]: /);
assert.doesNotMatch(moduleResult.data, /(?<!\[)"__proto__": /);
assert.match(moduleResult.data, /"value": 7/);

const executableSource = stripTypeScriptTypes(moduleResult.data.replace(/^import[^\n]*\n/, ""));
const generatedProgram = runInNewContext(`${executableSource}\nprogram`) as
(api: { identity: (arg: unknown) => unknown }) => unknown;
const generatedResult = generatedProgram({ identity: arg => arg });

assert.ok(typeof generatedResult === "object" && generatedResult !== null);
assert.ok(Object.prototype.hasOwnProperty.call(generatedResult, "__proto__"));
assert.equal(JSON.stringify(generatedResult), JSON.stringify(input));

const interpretedResult = await evaluateJsonProgram(program, async (_func, args) => args[0]);
assert.ok(typeof interpretedResult === "object" && interpretedResult !== null);
assert.ok(Object.prototype.hasOwnProperty.call(interpretedResult, "__proto__"));
assert.equal(JSON.stringify(generatedResult), JSON.stringify(interpretedResult));
});
}
});

describe("@func name validation", () => {
const maliciousProgram: Program = {
"@steps": [
Expand Down