54 lines
1.5 KiB
TypeScript
54 lines
1.5 KiB
TypeScript
type TProcessFunction = (input: string) => Promise<string>;
|
|
|
|
interface ISmartAiOptions {
|
|
processFunction: TProcessFunction;
|
|
}
|
|
|
|
class SmartAi {
|
|
private processFunction: TProcessFunction;
|
|
private inputStreamWriter: WritableStreamDefaultWriter<string> | null = null;
|
|
private outputStreamController: ReadableStreamDefaultController<string> | null = null;
|
|
|
|
constructor(options: ISmartAiOptions) {
|
|
this.processFunction = options.processFunction;
|
|
}
|
|
|
|
private setupOutputStream(): ReadableStream<string> {
|
|
return new ReadableStream<string>({
|
|
start: (controller) => {
|
|
this.outputStreamController = controller;
|
|
}
|
|
});
|
|
}
|
|
|
|
private setupInputStream(): WritableStream<string> {
|
|
return new WritableStream<string>({
|
|
write: async (chunk) => {
|
|
const processedData = await this.processFunction(chunk);
|
|
if (this.outputStreamController) {
|
|
this.outputStreamController.enqueue(processedData);
|
|
}
|
|
},
|
|
close: () => {
|
|
this.outputStreamController?.close();
|
|
},
|
|
abort: (err) => {
|
|
console.error('Stream aborted', err);
|
|
this.outputStreamController?.error(err);
|
|
}
|
|
});
|
|
}
|
|
|
|
public getInputStreamWriter(): WritableStreamDefaultWriter<string> {
|
|
if (!this.inputStreamWriter) {
|
|
const inputStream = this.setupInputStream();
|
|
this.inputStreamWriter = inputStream.getWriter();
|
|
}
|
|
return this.inputStreamWriter;
|
|
}
|
|
|
|
public getOutputStream(): ReadableStream<string> {
|
|
return this.setupOutputStream();
|
|
}
|
|
}
|