MCPcopy Index your code
hub / github.com/microsoft/TypeChat / createModuleTextFromProgram

Function createModuleTextFromProgram

typescript/src/ts/program.ts:86–136  ·  view source on GitHub ↗
(jsonObject: object)

Source from the content-addressed store, hash-verified

84 * couldn't be transformed.
85 */
86export function createModuleTextFromProgram(jsonObject: object): Result<string> {
87 const steps = (jsonObject as Program)["@steps"];
88 if (!(Array.isArray(steps) && steps.every(step => typeof step === "object" && step !== null && step.hasOwnProperty("@func")))) {
89 return error("JSON object is not a valid program");
90 }
91 let hasError = false;
92 let functionBody = "";
93 let currentStep = 0;
94 while (currentStep < steps.length) {
95 functionBody += ` ${currentStep === steps.length - 1 ? `return` : `const step${currentStep + 1} =`} ${exprToString(steps[currentStep])};\n`;
96 currentStep++;
97 }
98 return hasError ?
99 error("JSON program contains an invalid expression") :
100 success(`import { API } from "./schema";\nfunction program(api: API) {\n${functionBody}}`);
101
102 function exprToString(expr: unknown): string {
103 return typeof expr === "object" && expr !== null ?
104 objectToString(expr as Record<string, unknown>) :
105 JSON.stringify(expr);
106 }
107
108 function objectToString(obj: Record<string, unknown>) {
109 if (obj.hasOwnProperty("@ref")) {
110 const index = obj["@ref"];
111 if (typeof index === "number" && index < currentStep && Object.keys(obj).length === 1) {
112 return `step${index + 1}`;
113 }
114 }
115 else if (obj.hasOwnProperty("@func")) {
116 const func = obj["@func"];
117 const hasArgs = obj.hasOwnProperty("@args");
118 const args = hasArgs ? obj["@args"] : [];
119 if (typeof func === "string" && (Array.isArray(args)) && Object.keys(obj).length === (hasArgs ? 2 : 1)) {
120 return `api.${func}(${arrayToString(args)})`;
121 }
122 }
123 else if (Array.isArray(obj)) {
124 return `[${arrayToString(obj)}]`;
125 }
126 else {
127 return `{ ${Object.keys(obj).map(key => `${JSON.stringify(key)}: ${exprToString(obj[key])}`).join(", ")} }`;
128 }
129 hasError = true;
130 return "";
131 }
132
133 function arrayToString(array: unknown[]) {
134 return array.map(exprToString).join(", ");
135 }
136}
137
138/**
139 * Evaluates a JSON program using a simple interpreter. Function calls in the program are passed to the `onCall`

Callers 3

_handleMessageFunction · 0.90
musicAppFunction · 0.90
main.tsFile · 0.90

Calls 3

errorFunction · 0.90
successFunction · 0.90
exprToStringFunction · 0.85

Tested by

no test coverage detected