UNPKG

invoiceddd

Version:

Complete invoice system with domain-driven design - gateway package for easy integration

709 lines (701 loc) 28.3 kB
export { ConcretePDFRenderer, DatabaseLive, DatabaseMigrationError, DrizzleInvoiceNumberRepositoryLive, DrizzleInvoiceRepositoryLive, DrizzleOrderRepositoryLive, StorageService, StorageSubscriber, StorageSubscriberLive, TypedDrizzleService, createTestInfrastructure, invoicesTable, ordersTable, runMigrations, runMigrationsWithPath } from '@invoiceddd/infrastructure'; import * as Channel3 from 'effect/Channel'; import * as Context from 'effect/Context'; import * as Deferred from 'effect/Deferred'; import * as Effect from 'effect/Effect'; import * as ExecutionStrategy from 'effect/ExecutionStrategy'; import * as Exit from 'effect/Exit'; import 'effect/FiberRef'; import * as FiberSet from 'effect/FiberSet'; import { pipe, dual, identity } from 'effect/Function'; import 'effect/GlobalValue'; import * as Layer2 from 'effect/Layer'; import * as Mailbox from 'effect/Mailbox'; import * as Predicate2 from 'effect/Predicate'; import * as Scope from 'effect/Scope'; import * as Data from 'effect/Data'; import * as Schema3 from 'effect/Schema'; import * as Chunk from 'effect/Chunk'; import * as Cause from 'effect/Cause'; import * as Metric2 from 'effect/Metric'; import * as MetricState from 'effect/MetricState'; import * as Schedule from 'effect/Schedule'; import * as Stream from 'effect/Stream'; import * as Tracer from 'effect/Tracer'; import * as Net from 'net'; import { Layer } from 'effect'; var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var TypeId = /* @__PURE__ */ Symbol.for("@effect/platform/Error"); var TypeIdError = /* @__PURE__ */ __name((typeId, tag) => { let Base = class Base extends Data.Error { static { __name(this, "Base"); } _tag = tag; }; Base.prototype[typeId] = typeId; Base.prototype.name = tag; return Base; }, "TypeIdError"); var Module = /* @__PURE__ */ Schema3.Literal("Clipboard", "Command", "FileSystem", "KeyValueStore", "Path", "Stream", "Terminal"); (class extends (/* @__PURE__ */ Schema3.TaggedError("@effect/platform/Error/BadArgument")("BadArgument", { module: Module, method: Schema3.String, description: /* @__PURE__ */ Schema3.optional(Schema3.String), cause: /* @__PURE__ */ Schema3.optional(Schema3.Defect) })) { static { __name(this, "BadArgument"); } /** * @since 1.0.0 */ [TypeId] = TypeId; /** * @since 1.0.0 */ get message() { return `${this.module}.${this.method}${this.description ? `: ${this.description}` : ""}`; } }); var SystemErrorReason = /* @__PURE__ */ Schema3.Literal("AlreadyExists", "BadResource", "Busy", "InvalidData", "NotFound", "PermissionDenied", "TimedOut", "UnexpectedEof", "Unknown", "WouldBlock", "WriteZero"); (class extends (/* @__PURE__ */ Schema3.TaggedError("@effect/platform/Error/SystemError")("SystemError", { reason: SystemErrorReason, module: Module, method: Schema3.String, description: /* @__PURE__ */ Schema3.optional(Schema3.String), syscall: /* @__PURE__ */ Schema3.optional(Schema3.String), pathOrDescriptor: /* @__PURE__ */ Schema3.optional(/* @__PURE__ */ Schema3.Union(Schema3.String, Schema3.Number)), cause: /* @__PURE__ */ Schema3.optional(Schema3.Defect) })) { static { __name(this, "SystemError"); } /** * @since 1.0.0 */ [TypeId] = TypeId; /** * @since 1.0.0 */ get message() { return `${this.reason}: ${this.module}.${this.method}${this.pathOrDescriptor !== void 0 ? ` (${this.pathOrDescriptor})` : ""}${this.description ? `: ${this.description}` : ""}`; } }); // ../../node_modules/@effect/platform/dist/esm/Socket.js var TypeId2 = /* @__PURE__ */ Symbol.for("@effect/platform/Socket"); var isSocket = /* @__PURE__ */ __name((u) => Predicate2.hasProperty(u, TypeId2), "isSocket"); var Socket = /* @__PURE__ */ Context.GenericTag("@effect/platform/Socket"); var CloseEventTypeId = /* @__PURE__ */ Symbol.for("@effect/platform/Socket/CloseEvent"); (class { static { __name(this, "CloseEvent"); } code; reason; /** * @since 1.0.0 */ [CloseEventTypeId]; constructor(code = 1e3, reason) { this.code = code; this.reason = reason; this[CloseEventTypeId] = CloseEventTypeId; } /** * @since 1.0.0 */ toString() { return this.reason ? `${this.code}: ${this.reason}` : `${this.code}`; } }); var isCloseEvent = /* @__PURE__ */ __name((u) => Predicate2.hasProperty(u, CloseEventTypeId), "isCloseEvent"); var SocketErrorTypeId = /* @__PURE__ */ Symbol.for("@effect/platform/Socket/SocketError"); var isSocketError = /* @__PURE__ */ __name((u) => Predicate2.hasProperty(u, SocketErrorTypeId), "isSocketError"); var SocketGenericError = class extends (/* @__PURE__ */ TypeIdError(SocketErrorTypeId, "SocketError")) { static { __name(this, "SocketGenericError"); } get message() { return `An error occurred during ${this.reason}`; } }; var SocketCloseError = class _SocketCloseError extends (/* @__PURE__ */ TypeIdError(SocketErrorTypeId, "SocketError")) { static { __name(this, "SocketCloseError"); } /** * @since 1.0.0 */ static is(u) { return isSocketError(u) && u.reason === "Close"; } /** * @since 1.0.0 */ static isClean(isClean) { return function(u) { return _SocketCloseError.is(u) && isClean(u.code); }; } get message() { if (this.closeReason) { return `${this.reason}: ${this.code}: ${this.closeReason}`; } return `${this.reason}: ${this.code}`; } }; var toChannelMap = /* @__PURE__ */ __name((self, f) => Effect.gen(function* () { const scope2 = yield* Effect.scope; const mailbox = yield* Mailbox.make(); const writeScope = yield* Scope.fork(scope2, ExecutionStrategy.sequential); const write3 = yield* Scope.extend(self.writer, writeScope); function* emit(chunk) { for (const data of chunk) { yield* write3(data); } } __name(emit, "emit"); const input = { awaitRead: /* @__PURE__ */ __name(() => Effect.void, "awaitRead"), emit(chunk) { return Effect.catchAllCause(Effect.gen(() => emit(chunk)), (cause) => mailbox.failCause(cause)); }, error(error) { return Effect.zipRight(Scope.close(writeScope, Exit.void), mailbox.failCause(error)); }, done() { return Scope.close(writeScope, Exit.void); } }; yield* self.runRaw((data) => { mailbox.unsafeOffer(f(data)); }).pipe(Mailbox.into(mailbox), Effect.forkIn(scope2), Effect.interruptible); return Channel3.embedInput(Mailbox.toChannel(mailbox), input); }).pipe(Channel3.unwrapScoped), "toChannelMap"); var toChannel2 = /* @__PURE__ */ __name((self) => { const encoder = new TextEncoder(); return toChannelMap(self, (data) => typeof data === "string" ? encoder.encode(data) : data); }, "toChannel"); var toChannelString = /* @__PURE__ */ dual((args) => isSocket(args[0]), (self, encoding) => { const decoder = new TextDecoder(encoding); return toChannelMap(self, (data) => typeof data === "string" ? data : decoder.decode(data)); }); var toChannelWith = /* @__PURE__ */ __name(() => (self) => toChannel2(self), "toChannelWith"); var defaultCloseCodeIsError = /* @__PURE__ */ __name((code) => code !== 1e3 && code !== 1006, "defaultCloseCodeIsError"); var WebSocket = /* @__PURE__ */ Context.GenericTag("@effect/platform/Socket/WebSocket"); var WebSocketConstructor = /* @__PURE__ */ Context.GenericTag("@effect/platform/Socket/WebSocketConstructor"); var makeWebSocket = /* @__PURE__ */ __name((url, options) => fromWebSocket(Effect.acquireRelease((typeof url === "string" ? Effect.succeed(url) : url).pipe(Effect.flatMap((url2) => Effect.map(WebSocketConstructor, (f) => f(url2, options?.protocols)))), (ws) => Effect.sync(() => ws.close(1e3))), options), "makeWebSocket"); var fromWebSocket = /* @__PURE__ */ __name((acquire, options) => Effect.withFiberRuntime((fiber) => { let currentWS; const latch = Effect.unsafeMakeLatch(false); const acquireContext = fiber.currentContext; const closeCodeIsError = options?.closeCodeIsError ?? defaultCloseCodeIsError; const runRaw = /* @__PURE__ */ __name((handler) => Effect.scopedWith((scope2) => Effect.gen(function* () { const fiberSet = yield* FiberSet.make().pipe(Scope.extend(scope2)); const ws = yield* Scope.extend(acquire, scope2); const run3 = yield* Effect.provideService(FiberSet.runtime(fiberSet)(), WebSocket, ws); let open = false; function onMessage(event) { if (event.data instanceof Blob) { return Effect.promise(() => event.data.arrayBuffer()).pipe(Effect.andThen((buffer) => handler(new Uint8Array(buffer))), run3); } const result = handler(event.data); if (Effect.isEffect(result)) { run3(result); } } __name(onMessage, "onMessage"); function onError(cause) { ws.removeEventListener("message", onMessage); ws.removeEventListener("close", onClose); Deferred.unsafeDone(fiberSet.deferred, Effect.fail(new SocketGenericError({ reason: open ? "Read" : "Open", cause }))); } __name(onError, "onError"); function onClose(event) { ws.removeEventListener("message", onMessage); ws.removeEventListener("error", onError); Deferred.unsafeDone(fiberSet.deferred, Effect.fail(new SocketCloseError({ reason: "Close", code: event.code, closeReason: event.reason }))); } __name(onClose, "onClose"); ws.addEventListener("close", onClose, { once: true }); ws.addEventListener("error", onError, { once: true }); ws.addEventListener("message", onMessage); if (ws.readyState !== 1) { const openDeferred = Deferred.unsafeMake(fiber.id()); ws.addEventListener("open", () => { open = true; Deferred.unsafeDone(openDeferred, Effect.void); }, { once: true }); yield* Deferred.await(openDeferred).pipe(Effect.timeoutFail({ duration: options?.openTimeout ?? 1e4, onTimeout: /* @__PURE__ */ __name(() => new SocketGenericError({ reason: "OpenTimeout", cause: 'timeout waiting for "open"' }), "onTimeout") }), Effect.raceFirst(FiberSet.join(fiberSet))); } open = true; currentWS = ws; yield* latch.open; return yield* FiberSet.join(fiberSet).pipe(Effect.catchIf(SocketCloseError.isClean((_) => !closeCodeIsError(_)), (_) => Effect.void)); })).pipe(Effect.mapInputContext((input) => Context.merge(acquireContext, input)), Effect.ensuring(Effect.sync(() => { latch.unsafeClose(); currentWS = void 0; })), Effect.interruptible), "runRaw"); const encoder = new TextEncoder(); const run2 = /* @__PURE__ */ __name((handler) => runRaw((data) => typeof data === "string" ? handler(encoder.encode(data)) : data instanceof Uint8Array ? handler(data) : handler(new Uint8Array(data))), "run"); const write3 = /* @__PURE__ */ __name((chunk) => latch.whenOpen(Effect.sync(() => { const ws = currentWS; if (isCloseEvent(chunk)) { ws.close(chunk.code, chunk.reason); } else { ws.send(chunk); } })), "write"); const writer = Effect.succeed(write3); return Effect.succeed(Socket.of({ [TypeId2]: TypeId2, run: run2, runRaw, writer })); }), "fromWebSocket"); var layerWebSocket = /* @__PURE__ */ __name((url, options) => Layer2.effect(Socket, makeWebSocket(url, options)), "layerWebSocket"); var encode2 = /* @__PURE__ */ __name((schema) => () => { const encode3 = Schema3.encode(Schema3.ChunkFromSelf(schema)); const loop = Channel3.readWithCause({ onInput: /* @__PURE__ */ __name((input) => Channel3.zipRight(Channel3.flatMap(encode3(input), Channel3.write), loop), "onInput"), onFailure: /* @__PURE__ */ __name((cause) => Channel3.failCause(cause), "onFailure"), onDone: Channel3.succeed }); return loop; }, "encode"); var duplex = /* @__PURE__ */ dual(2, (self, options) => { const decode2 = Schema3.decode(Schema3.ChunkFromSelf(options.outputSchema)); return pipe(encode2(options.inputSchema)(), Channel3.pipeTo(self), Channel3.mapOutEffect(decode2)); }); var duplexUnknown = duplex; // ../../node_modules/@effect/platform/dist/esm/Ndjson.js var ErrorTypeId = /* @__PURE__ */ Symbol.for("@effect/platform/Ndjson/NdjsonError"); var NdjsonError = class extends (/* @__PURE__ */ TypeIdError(ErrorTypeId, "NdjsonError")) { static { __name(this, "NdjsonError"); } get message() { return this.reason; } }; var packString = /* @__PURE__ */ __name(() => { const loop = Channel3.readWithCause({ onInput: /* @__PURE__ */ __name((input) => Channel3.zipRight(Channel3.flatMap(Effect.try({ try: /* @__PURE__ */ __name(() => Chunk.of(Chunk.toReadonlyArray(input).map((_) => JSON.stringify(_)).join("\n") + "\n"), "try"), catch: /* @__PURE__ */ __name((cause) => new NdjsonError({ reason: "Pack", cause }), "catch") }), Channel3.write), loop), "onInput"), onFailure: Channel3.failCause, onDone: Channel3.succeed }); return loop; }, "packString"); var filterEmpty = /* @__PURE__ */ Chunk.filter((line) => line.length > 0); var filterEmptyChannel = /* @__PURE__ */ __name(() => { const loop = Channel3.readWithCause({ onInput(input) { const filtered = filterEmpty(input); return Channel3.zipRight(Chunk.isEmpty(filtered) ? Channel3.void : Channel3.write(filtered), loop); }, onFailure(cause) { return Channel3.failCause(cause); }, onDone(done) { return Channel3.succeed(done); } }); return loop; }, "filterEmptyChannel"); var unpackString = /* @__PURE__ */ __name((options) => { const lines = Channel3.splitLines().pipe(options?.ignoreEmptyLines === true ? Channel3.pipeTo(filterEmptyChannel()) : identity); return Channel3.mapOutEffect(lines, (chunk) => Effect.try({ try: /* @__PURE__ */ __name(() => Chunk.map(chunk, (_) => JSON.parse(_)), "try"), catch: /* @__PURE__ */ __name((cause) => new NdjsonError({ reason: "Unpack", cause }), "catch") })); }, "unpackString"); var duplexString = /* @__PURE__ */ dual((args) => Channel3.isChannel(args[0]), (self, options) => Channel3.pipeTo(Channel3.pipeTo(packString(), self), unpackString(options))); var duplexSchemaString = /* @__PURE__ */ dual(2, (self, options) => duplexUnknown(duplexString(self, options), options)); var SpanStatusStarted = /* @__PURE__ */ Schema3.Struct({ _tag: /* @__PURE__ */ Schema3.Literal("Started"), startTime: Schema3.BigInt }); var SpanStatusEnded = /* @__PURE__ */ Schema3.Struct({ _tag: /* @__PURE__ */ Schema3.Literal("Ended"), startTime: Schema3.BigInt, endTime: Schema3.BigInt }); var SpanStatus = /* @__PURE__ */ Schema3.Union(SpanStatusStarted, SpanStatusEnded); var ExternalSpan = /* @__PURE__ */ Schema3.Struct({ _tag: /* @__PURE__ */ Schema3.Literal("ExternalSpan"), spanId: Schema3.String, traceId: Schema3.String, sampled: Schema3.Boolean }); var Span = /* @__PURE__ */ Schema3.Struct({ _tag: /* @__PURE__ */ Schema3.Literal("Span"), spanId: Schema3.String, traceId: Schema3.String, name: Schema3.String, sampled: Schema3.Boolean, attributes: /* @__PURE__ */ Schema3.ReadonlyMap({ key: Schema3.String, value: Schema3.Unknown }), status: SpanStatus, parent: /* @__PURE__ */ Schema3.Option(/* @__PURE__ */ Schema3.suspend(() => ParentSpan).annotations({ title: "ParentSpan" })) }); var SpanEvent = /* @__PURE__ */ Schema3.Struct({ _tag: /* @__PURE__ */ Schema3.Literal("SpanEvent"), traceId: Schema3.String, spanId: Schema3.String, name: Schema3.String, startTime: Schema3.BigInt, attributes: /* @__PURE__ */ Schema3.Record({ key: Schema3.String, value: Schema3.Unknown }) }); var ParentSpan = /* @__PURE__ */ Schema3.Union(Span, ExternalSpan); var Ping = /* @__PURE__ */ Schema3.Struct({ _tag: /* @__PURE__ */ Schema3.Literal("Ping") }); var Pong = /* @__PURE__ */ Schema3.Struct({ _tag: /* @__PURE__ */ Schema3.Literal("Pong") }); var MetricsRequest = /* @__PURE__ */ Schema3.Struct({ _tag: /* @__PURE__ */ Schema3.Literal("MetricsRequest") }); var MetricLabel = /* @__PURE__ */ Schema3.Struct({ key: Schema3.String, value: Schema3.String }); var metric = /* @__PURE__ */ __name((tag, state) => Schema3.Struct({ _tag: Schema3.Literal(tag), name: Schema3.String, description: Schema3.optionalWith(Schema3.String, { as: "Option" }), tags: Schema3.Array(MetricLabel), state }), "metric"); var Counter = /* @__PURE__ */ metric("Counter", /* @__PURE__ */ Schema3.Struct({ count: /* @__PURE__ */ Schema3.Union(Schema3.Number, Schema3.BigInt) })); var Frequency = /* @__PURE__ */ metric("Frequency", /* @__PURE__ */ Schema3.Struct({ occurrences: /* @__PURE__ */ Schema3.Record({ key: Schema3.String, value: Schema3.Number }) })); var Gauge = /* @__PURE__ */ metric("Gauge", /* @__PURE__ */ Schema3.Struct({ value: /* @__PURE__ */ Schema3.Union(Schema3.Number, Schema3.BigInt) })); var numberOrInfinity = /* @__PURE__ */ Schema3.transform(/* @__PURE__ */ Schema3.Union(Schema3.Number, Schema3.Null), Schema3.Number, { strict: true, decode: /* @__PURE__ */ __name((i) => i === null ? Number.POSITIVE_INFINITY : i, "decode"), encode: /* @__PURE__ */ __name((i) => Number.isFinite(i) ? i : null, "encode") }); var Histogram = /* @__PURE__ */ metric("Histogram", /* @__PURE__ */ Schema3.Struct({ buckets: /* @__PURE__ */ Schema3.Array(/* @__PURE__ */ Schema3.Tuple(numberOrInfinity, Schema3.Number)), count: Schema3.Number, min: Schema3.Number, max: Schema3.Number, sum: Schema3.Number })); var Summary = /* @__PURE__ */ metric("Summary", /* @__PURE__ */ Schema3.Struct({ error: Schema3.Number, quantiles: /* @__PURE__ */ Schema3.Array(/* @__PURE__ */ Schema3.Tuple(Schema3.Number, /* @__PURE__ */ Schema3.Option(Schema3.Number))), count: Schema3.Number, min: Schema3.Number, max: Schema3.Number, sum: Schema3.Number })); var Metric = /* @__PURE__ */ Schema3.Union(Counter, Frequency, Gauge, Histogram, Summary); var MetricsSnapshot = /* @__PURE__ */ Schema3.Struct({ _tag: /* @__PURE__ */ Schema3.Literal("MetricsSnapshot"), metrics: /* @__PURE__ */ Schema3.Array(Metric) }); var Request = /* @__PURE__ */ Schema3.Union(Ping, Span, SpanEvent, MetricsSnapshot); var Response = /* @__PURE__ */ Schema3.Union(Pong, MetricsRequest); // ../../node_modules/@effect/experimental/dist/esm/DevTools/Client.js var Client = /* @__PURE__ */ Context.GenericTag("@effect/experimental/DevTools/Client"); var make6 = /* @__PURE__ */ Effect.gen(function* () { const socket = yield* Socket; const requests = yield* Mailbox.make(); function metricsSnapshot() { const snapshot = Metric2.unsafeSnapshot(); const metrics = []; for (let i = 0, len = snapshot.length; i < len; i++) { const metricPair = snapshot[i]; if (MetricState.isCounterState(metricPair.metricState)) { metrics.push({ _tag: "Counter", name: metricPair.metricKey.name, description: metricPair.metricKey.description, tags: metricPair.metricKey.tags, state: metricPair.metricState }); } else if (MetricState.isGaugeState(metricPair.metricState)) { metrics.push({ _tag: "Gauge", name: metricPair.metricKey.name, description: metricPair.metricKey.description, tags: metricPair.metricKey.tags, state: metricPair.metricState }); } else if (MetricState.isHistogramState(metricPair.metricState)) { metrics.push({ _tag: "Histogram", name: metricPair.metricKey.name, description: metricPair.metricKey.description, tags: metricPair.metricKey.tags, state: metricPair.metricState }); } else if (MetricState.isSummaryState(metricPair.metricState)) { metrics.push({ _tag: "Summary", name: metricPair.metricKey.name, description: metricPair.metricKey.description, tags: metricPair.metricKey.tags, state: metricPair.metricState }); } else if (MetricState.isFrequencyState(metricPair.metricState)) { metrics.push({ _tag: "Frequency", name: metricPair.metricKey.name, description: metricPair.metricKey.description, tags: metricPair.metricKey.tags, state: { occurrences: Object.fromEntries(metricPair.metricState.occurrences.entries()) } }); } } return { _tag: "MetricsSnapshot", metrics }; } __name(metricsSnapshot, "metricsSnapshot"); const connected = yield* Deferred.make(); yield* Mailbox.toStream(requests).pipe(Stream.pipeThroughChannel(duplexSchemaString(toChannelString(socket), { inputSchema: Request, outputSchema: Response })), Stream.runForEach((req) => { Deferred.unsafeDone(connected, Exit.void); switch (req._tag) { case "MetricsRequest": { return requests.offer(metricsSnapshot()); } case "Pong": { return Effect.void; } } }), Effect.tapErrorCause(Effect.logDebug), Effect.retry(Schedule.spaced("1 seconds")), Effect.forkScoped, Effect.uninterruptible); yield* Effect.addFinalizer(() => requests.offer(metricsSnapshot()).pipe(Effect.zipRight(Effect.fiberIdWith((id) => requests.failCause(Cause.interrupt(id)))))); yield* requests.offer({ _tag: "Ping" }).pipe(Effect.delay("3 seconds"), Effect.forever, Effect.forkScoped, Effect.interruptible); yield* Deferred.await(connected).pipe(Effect.timeoutOption("1 second")); return Client.of({ unsafeAddSpan: /* @__PURE__ */ __name((request) => requests.unsafeOffer(request), "unsafeAddSpan") }); }).pipe(/* @__PURE__ */ Effect.annotateLogs({ package: "@effect/experimental", module: "DevTools", service: "Client" })); var layer = /* @__PURE__ */ Layer2.scoped(Client, make6); var makeTracer = /* @__PURE__ */ Effect.gen(function* () { const client = yield* Client; const currentTracer = yield* Effect.tracer; return Tracer.make({ span(name, parent, context, links, startTime, kind) { const span = currentTracer.span(name, parent, context, links, startTime, kind); client.unsafeAddSpan(span); const oldEvent = span.event; span.event = function(name2, startTime2, attributes) { client.unsafeAddSpan({ _tag: "SpanEvent", traceId: span.traceId, spanId: span.spanId, name: name2, startTime: startTime2, attributes: attributes || {} }); return oldEvent.call(this, name2, startTime2, attributes); }; const oldEnd = span.end; span.end = function() { client.unsafeAddSpan(span); return oldEnd.apply(this, arguments); }; return span; }, context: currentTracer.context }); }).pipe(/* @__PURE__ */ Effect.annotateLogs({ package: "@effect/experimental", module: "DevTools", service: "Tracer" })); var layerTracer = /* @__PURE__ */ pipe(makeTracer, /* @__PURE__ */ Effect.map(Layer2.setTracer), Layer2.unwrapEffect, /* @__PURE__ */ Layer2.provide(layer)); // ../../node_modules/@effect/experimental/dist/esm/DevTools.js var layerWebSocket2 = /* @__PURE__ */ __name((url = "ws://localhost:34437") => layerTracer.pipe(Layer2.provide(layerWebSocket(url))), "layerWebSocket"); // ../../node_modules/@effect/platform-bun/dist/esm/BunSocket.js var BunSocket_exports = {}; __export(BunSocket_exports, { NetSocket: () => NetSocket, fromDuplex: () => fromDuplex, layerNet: () => layerNet, layerWebSocket: () => layerWebSocket3, layerWebSocketConstructor: () => layerWebSocketConstructor, makeNet: () => makeNet, makeNetChannel: () => makeNetChannel }); var NetSocket = /* @__PURE__ */ Context.GenericTag("@effect/platform-node/NodeSocket/NetSocket"); var makeNet = /* @__PURE__ */ __name((options) => fromDuplex(Effect.acquireRelease(Effect.async((resume) => { const conn = Net.createConnection(options); conn.on("connect", () => { conn.removeAllListeners(); resume(Effect.succeed(conn)); }); conn.on("error", (cause) => { conn.removeAllListeners(); resume(Effect.fail(new SocketGenericError({ reason: "Open", cause }))); }); return Effect.sync(() => { conn.destroy(); }); }), (conn) => Effect.sync(() => { if (conn.closed === false) { if ("destroySoon" in conn) { conn.destroySoon(); } else { conn.destroy(); } } conn.removeAllListeners(); }))), "makeNet"); var fromDuplex = /* @__PURE__ */ __name((open) => Effect.withFiberRuntime((fiber) => { let currentSocket; const latch = Effect.unsafeMakeLatch(false); const openContext = fiber.currentContext; const run2 = /* @__PURE__ */ __name((handler) => Effect.scopedWith(Effect.fnUntraced(function* (scope2) { const fiberSet = yield* FiberSet.make().pipe(Scope.extend(scope2)); const conn = yield* Scope.extend(open, scope2); const run3 = yield* Effect.provideService(FiberSet.runtime(fiberSet)(), NetSocket, conn); function onData(chunk) { const result = handler(chunk); if (Effect.isEffect(result)) { run3(result); } } __name(onData, "onData"); function onEnd() { Deferred.unsafeDone(fiberSet.deferred, Effect.void); } __name(onEnd, "onEnd"); function onError(cause) { Deferred.unsafeDone(fiberSet.deferred, Effect.fail(new SocketGenericError({ reason: "Read", cause }))); } __name(onError, "onError"); function onClose(hadError) { Deferred.unsafeDone(fiberSet.deferred, Effect.fail(new SocketCloseError({ reason: "Close", code: hadError ? 1006 : 1e3 }))); } __name(onClose, "onClose"); yield* Scope.addFinalizer(scope2, Effect.sync(() => { conn.off("data", onData); conn.off("end", onEnd); conn.off("error", onError); conn.off("close", onClose); })); conn.on("data", onData); conn.on("end", onEnd); conn.on("error", onError); conn.on("close", onClose); currentSocket = conn; yield* latch.open; return yield* FiberSet.join(fiberSet); })).pipe(Effect.mapInputContext((input) => Context.merge(openContext, input)), Effect.ensuring(Effect.sync(() => { latch.unsafeClose(); currentSocket = void 0; })), Effect.interruptible), "run"); const write3 = /* @__PURE__ */ __name((chunk) => latch.whenOpen(Effect.async((resume) => { const conn = currentSocket; if (isCloseEvent(chunk)) { conn.destroy(chunk.code > 1e3 ? new Error(`closed with code ${chunk.code}`) : void 0); return resume(Effect.void); } currentSocket.write(chunk, (cause) => { resume(cause ? Effect.fail(new SocketGenericError({ reason: "Write", cause })) : Effect.void); }); })), "write"); const writer = Effect.acquireRelease(Effect.succeed(write3), () => Effect.sync(() => { if (!currentSocket || currentSocket.writableEnded) return; currentSocket.end(); })); return Effect.succeed(Socket.of({ [TypeId2]: TypeId2, run: run2, runRaw: run2, writer })); }), "fromDuplex"); var makeNetChannel = /* @__PURE__ */ __name((options) => Channel3.unwrapScoped(Effect.map(makeNet(options), toChannelWith())), "makeNetChannel"); var layerNet = /* @__PURE__ */ __name((options) => Layer2.effect(Socket, makeNet(options)), "layerNet"); // ../../node_modules/@effect/platform-bun/dist/esm/BunSocket.js var layerWebSocket3 = /* @__PURE__ */ __name((url, options) => Layer2.scoped(Socket, makeWebSocket(url, options)).pipe(Layer2.provide(layerWebSocketConstructor)), "layerWebSocket"); var layerWebSocketConstructor = /* @__PURE__ */ Layer2.succeed(WebSocketConstructor, (url, protocols) => new globalThis.WebSocket(url, protocols)); function createDevToolsLayer(enableDevTools) { return enableDevTools ? layerWebSocket2().pipe(Layer.provide(BunSocket_exports.layerWebSocketConstructor)) : Layer.empty; } __name(createDevToolsLayer, "createDevToolsLayer"); export { createDevToolsLayer }; //# sourceMappingURL=server.js.map //# sourceMappingURL=server.js.map