UNPKG

inngest

Version:

Official SDK for Inngest.com. Inngest is the reliability layer for modern applications. Inngest combines durable execution, events, and queues into a zero-infra platform with built-in observability.

59 lines 2.69 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createStream = void 0; const strings_js_1 = require("./strings.js"); /** * Creates a {@link ReadableStream} that sends a `value` every `interval` * milliseconds as a heartbeat, intended to keep a stream open. * * Returns the `stream` itself and a `finalize` function that can be used to * close the stream and send a final value. */ const createStream = (opts) => { var _a, _b; /** * We need to resolve this promise with both the stream and the `finalize` * function, but having them both instantiated synchronously is difficult, as * we need access to the stream's internals too. * * We create this cheeky deferred promise to grab the internal `finalize` * value. Be warned that simpler solutions may appear to compile, but fail at * runtime due to variables not being assigned; make sure to test your code! */ let passFinalize; const finalizeP = new Promise((resolve) => { passFinalize = resolve; }); const interval = (_a = opts === null || opts === void 0 ? void 0 : opts.interval) !== null && _a !== void 0 ? _a : 3000; const value = (_b = opts === null || opts === void 0 ? void 0 : opts.value) !== null && _b !== void 0 ? _b : " "; // eslint-disable-next-line @typescript-eslint/no-misused-promises, no-async-promise-executor return new Promise(async (resolve, reject) => { try { const stream = new ReadableStream({ start(controller) { const encoder = new TextEncoder(); const heartbeat = setInterval(() => { controller.enqueue(encoder.encode(value)); }, interval); const finalize = (data) => { clearInterval(heartbeat); // `data` may be a `Promise`. If it is, we need to wait for it to // resolve before sending it. To support this elegantly we'll always // assume it's a promise and handle that case. void Promise.resolve(data).then((resolvedData) => { controller.enqueue(encoder.encode((0, strings_js_1.stringify)(resolvedData))); controller.close(); }); }; passFinalize(finalize); }, }); resolve({ stream, finalize: await finalizeP }); } catch (err) { reject(err); } }); }; exports.createStream = createStream; //# sourceMappingURL=stream.js.map