From bdca9489adab9736c47575006c63c6b0389fbc12 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:41:25 +0000 Subject: [PATCH 1/2] Update Effect to v4.0.6 --- bun.lock | 14 +++++++------- package.json | 6 +++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/bun.lock b/bun.lock index a4b4d431..b9a8d673 100644 --- a/bun.lock +++ b/bun.lock @@ -5,13 +5,13 @@ "": { "name": "@timmo001/workflows-actions", "dependencies": { - "@effect/platform-node": "4.0.5", + "@effect/platform-node": "4.0.6", "@timmo001/effect-gh": "0.7.0", - "effect": "4.0.5", + "effect": "4.0.6", }, "devDependencies": { "@effect/tsgo": "0.56.0", - "@effect/vitest": "4.0.5", + "@effect/vitest": "4.0.6", "@oxlint/plugins": "1.89.0", "@timmo001/oxlint-rules": "0.6.3", "@types/bun": "1.4.3", @@ -24,9 +24,9 @@ }, }, "packages": { - "@effect/platform-node": ["@effect/platform-node@4.0.5", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.5", "undici": "^8.11.2" }, "peerDependencies": { "effect": "^4.0.5", "redis": ">=5.0.0 <7.0.0" } }, "sha512-v4KD5fWvEUa4QmWFpZFbBsRhmfnTP6ETCME2r9ifyXVDPjhfpxpTZl41prjgQFMqZBHdWWCl7YC5ImbXv5ui5g=="], + "@effect/platform-node": ["@effect/platform-node@4.0.6", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.6", "undici": "^8.12.2" }, "peerDependencies": { "effect": "^4.0.6", "redis": ">=5.0.0 <7.0.0" } }, "sha512-gXvGHAy0/8PZbWvMMguloDUyeSP+rzYEo3FSEqUuGduxo9ORcGioDxPI+GOLCIFfam7VuNkmSUxBOiRMIrMrBw=="], - "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.5", "", { "dependencies": { "@types/ws": "^8.18.2", "ws": "^8.22.0" }, "peerDependencies": { "effect": "^4.0.5" } }, "sha512-a8rCdEkfZBGe9C6bsIjxVZuRp73svIyK5IHwHdDAVsvZXjrbkxusfI+rZ8WlX31RP1mKizwI/E72GQTNfdMWHw=="], + "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.6", "", { "dependencies": { "@types/ws": "^8.18.2", "ws": "^8.22.0" }, "peerDependencies": { "effect": "^4.0.6" } }, "sha512-0PhyC4uG30xGtsajnxjkcBWfTjNRzUh4ZKl1Kvo/MNyCTb+W2O+fBzf7wCRCoqt+nLudiq4V7vX40Q8XIBuMaQ=="], "@effect/tsgo": ["@effect/tsgo@0.56.0", "", { "optionalDependencies": { "@effect/tsgo-darwin-arm64": "0.56.0", "@effect/tsgo-darwin-x64": "0.56.0", "@effect/tsgo-linux-arm": "0.56.0", "@effect/tsgo-linux-arm64": "0.56.0", "@effect/tsgo-linux-x64": "0.56.0", "@effect/tsgo-win32-arm64": "0.56.0", "@effect/tsgo-win32-x64": "0.56.0" }, "bin": { "effect-tsgo": "dist/effect-tsgo.cjs" } }, "sha512-/S5G8RJjtaVjE/RhwFNTvWQwFAQyDGc+3Ig4Oynvlo3gJu8le4MUgM/DBjoiwkwBsQ+BhufGDCBpwojplerGlw=="], @@ -44,7 +44,7 @@ "@effect/tsgo-win32-x64": ["@effect/tsgo-win32-x64@0.56.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Cf6SDixFTkp7Aoeg2eRwJps/2BG9lvx2m+iVRjUzxdqkTbCCNKmmOAIyDslNZm2sMwaDUw/iN/BPGqxx7xMxww=="], - "@effect/vitest": ["@effect/vitest@4.0.5", "", { "peerDependencies": { "effect": "^4.0.5", "vitest": ">=5.0.0 <6.0.0" } }, "sha512-q64paZ/i4V2NiRhTyqCmT2KiDbFjlxc2EZrZca8GGt+Nf8844946HyJM5bPk/q+YeRkFSxIrlCs+J+LSfky/wA=="], + "@effect/vitest": ["@effect/vitest@4.0.6", "", { "peerDependencies": { "effect": "^4.0.6", "vitest": ">=5.0.0 <6.0.0" } }, "sha512-oKNbtyUHK5+0o730CXwojULEu7f3+c235pYFD4U5T//o+hHrJbYbZU4bRkcv936tPr5IOnmujeyQiC/LuJJjHw=="], "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], @@ -216,7 +216,7 @@ "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - "effect": ["effect@4.0.5", "", {}, "sha512-BY4/28NlpOd99yzmV741xbVGmp+1U7tks4oB7F/Png64bTa5tm5eCA6W0RiXsnuLDDoJpjfVSo4Dnq4BZb/89Q=="], + "effect": ["effect@4.0.6", "", {}, "sha512-Tc3mkzuLR6t6P9dhLt0D2GrxYtmU5td4XEJEiXCmILz53IRIfJyHsKZWjTA3xEjiwpNTtXBgI4iqYPxMztBDrw=="], "es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], diff --git a/package.json b/package.json index 7ba0c5c2..cb12d8f4 100644 --- a/package.json +++ b/package.json @@ -14,13 +14,13 @@ "prepare": "effect-tsgo patch --force=false" }, "dependencies": { - "@effect/platform-node": "4.0.5", + "@effect/platform-node": "4.0.6", "@timmo001/effect-gh": "0.7.0", - "effect": "4.0.5" + "effect": "4.0.6" }, "devDependencies": { "@effect/tsgo": "0.56.0", - "@effect/vitest": "4.0.5", + "@effect/vitest": "4.0.6", "@oxlint/plugins": "1.89.0", "@timmo001/oxlint-rules": "0.6.3", "@types/bun": "1.4.3", From 1d5cf64091a0d31bdfbd859be56ce5ea4d48e671 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:41:49 +0000 Subject: [PATCH 2/2] Rebuild action bundles --- .../arch-source-deployment/dist/index.js | 841 +++++++++------- .../actions/build-arch-package/dist/index.js | 824 ++++++++------- .../build-python-pypi-release/dist/index.js | 920 ++++++++--------- .../actions/foundation-smoke/dist/index.js | 935 ++++++++---------- .../actions/prepare-arch-bin/dist/index.js | 839 +++++++++------- .github/actions/publish-aur/dist/index.js | 920 ++++++++--------- .github/actions/release-bun-cli/dist/index.js | 839 +++++++++------- .../validate-agent-skills/dist/index.js | 935 ++++++++---------- .../actions/validate-js-package/dist/index.js | 920 ++++++++--------- .github/actions/validate-json/dist/index.js | 935 ++++++++---------- 10 files changed, 4497 insertions(+), 4411 deletions(-) diff --git a/.github/actions/arch-source-deployment/dist/index.js b/.github/actions/arch-source-deployment/dist/index.js index 5c8ad252..f114ca88 100644 --- a/.github/actions/arch-source-deployment/dist/index.js +++ b/.github/actions/arch-source-deployment/dist/index.js @@ -788,6 +788,10 @@ function assignProperty(self, key, value) { } } function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } for (const key of Reflect.ownKeys(source)) { if (Object.prototype.propertyIsEnumerable.call(source, key)) { assignProperty(self, key, source[key]); @@ -878,7 +882,7 @@ class CauseImpl { toJSON() { return { _id: "Cause", - failures: this.reasons.map((f) => f.toJSON()) + reasons: this.reasons.map((f) => f.toJSON()) }; } toString() { @@ -1661,9 +1665,21 @@ var bigint2 = /* @__PURE__ */ BigInt(2); var bigint10 = /* @__PURE__ */ BigInt(10); var bigint1e3 = /* @__PURE__ */ BigInt(1000); var bigint1e6 = /* @__PURE__ */ BigInt(1e6); +var bigint1e9 = /* @__PURE__ */ BigInt(1e9); +var bigintNanosPerMinute = /* @__PURE__ */ BigInt(60000000000); +var bigintNanosPerHour = /* @__PURE__ */ BigInt(3600000000000); +var bigintNanosPerDay = /* @__PURE__ */ BigInt(86400000000000); +var bigintNanosPerWeek = /* @__PURE__ */ BigInt(604800000000000); var roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input))); var roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6); var fromNanosNumber = (nanos) => make3(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos); +var nanosToUnit = (nanos, divisor) => { + const value = Number(nanos); + if (Number.isFinite(value)) + return value / divisor; + const scale = BigInt(divisor); + return Number(nanos / scale) + Number(nanos % scale) / divisor; +}; var parseNanos = (input, scale) => { const decimalIndex = input.indexOf("."); if (decimalIndex === -1) @@ -1679,6 +1695,13 @@ var divideTiesAwayFromZero = (numerator, denominator) => { const rounded = absolute / denominator + (absolute % denominator * bigint2 >= denominator ? bigint1 : bigint0); return numerator < bigint0 ? -rounded : rounded; }; +var fromMillisString = (input, scale) => { + const millis = Number(input) * scale; + if (!Number.isFinite(millis)) + return make3(millis); + const nanos = parseNanos(input, BigInt(scale) * bigint1e6); + return make3(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos); +}; var DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; var fromInputUnsafe = (input) => { switch (typeof input) { @@ -1703,26 +1726,25 @@ var fromInputUnsafe = (input) => { if (unit === "micro" || unit === "micros") { return nanos(parseNanos(valueStr, bigint1e3)); } - const value = Number(valueStr); switch (unit) { case "milli": case "millis": - return millis(value); + return fromMillisString(valueStr, 1); case "second": case "seconds": - return seconds(value); + return fromMillisString(valueStr, 1000); case "minute": case "minutes": - return minutes(value); + return fromMillisString(valueStr, 60000); case "hour": case "hours": - return hours(value); + return fromMillisString(valueStr, 3600000); case "day": case "days": - return days(value); + return fromMillisString(valueStr, 86400000); case "week": case "weeks": - return weeks(value); + return fromMillisString(valueStr, 604800000); } break; } @@ -1744,7 +1766,8 @@ var fromInputUnsafe = (input) => { if (input[0] === Infinity || input[1] === Infinity) { return infinity; } - return fromNanosNumber(input[0] * 1e9 + input[1]); + const nanos = input[0] * 1e9 + input[1]; + return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make3(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos); } const obj = input; let millis = 0; @@ -1760,13 +1783,42 @@ var fromInputUnsafe = (input) => { millis += obj.seconds * 1000; if (obj.milliseconds) millis += obj.milliseconds; - if (!obj.microseconds && !obj.nanoseconds) - return make3(millis); - return fromNanosNumber(millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0)); + if (!obj.microseconds && !obj.nanoseconds) { + if (!Number.isFinite(millis)) + return make3(millis); + const exact = sumObjectNanos(obj); + return exact === undefined || BigInt(millis) * bigint1e6 === exact ? make3(millis) : make3(exact); + } + const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0); + const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : undefined; + return exact === undefined ? fromNanosNumber(nanos) : make3(exact); } } return invalid(input); }; +var isIntegerOrUnset = (n) => !n || Number.isInteger(n); +var sumObjectNanos = (obj) => { + if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds)) + return; + let nanos = bigint0; + if (obj.weeks) + nanos += BigInt(obj.weeks) * bigintNanosPerWeek; + if (obj.days) + nanos += BigInt(obj.days) * bigintNanosPerDay; + if (obj.hours) + nanos += BigInt(obj.hours) * bigintNanosPerHour; + if (obj.minutes) + nanos += BigInt(obj.minutes) * bigintNanosPerMinute; + if (obj.seconds) + nanos += BigInt(obj.seconds) * bigint1e9; + if (obj.milliseconds) + nanos += BigInt(obj.milliseconds) * bigint1e6; + if (obj.microseconds) + nanos += BigInt(obj.microseconds) * bigint1e3; + if (obj.nanoseconds) + nanos += BigInt(obj.nanoseconds); + return nanos; +}; var invalid = (input) => { throw new Error(`Invalid Input: ${input}`); }; @@ -1875,14 +1927,9 @@ var infinity = /* @__PURE__ */ make3(Infinity); var negativeInfinity = /* @__PURE__ */ make3(-Infinity); var nanos = (nanos) => make3(nanos); var millis = (millis) => make3(millis); -var seconds = (seconds) => make3(seconds * 1000); -var minutes = (minutes) => make3(minutes * 60000); -var hours = (hours) => make3(hours * 3600000); -var days = (days) => make3(days * 86400000); -var weeks = (weeks) => make3(weeks * 604800000); var toMillis = (self) => match3(fromInputUnsafe(self), { onMillis: identity, - onNanos: (nanos) => Number(nanos) / 1e6, + onNanos: (nanos) => nanosToUnit(nanos, 1e6), onInfinity: () => Infinity, onNegativeInfinity: () => -Infinity }); @@ -1964,7 +2011,7 @@ var setTimer = "setImmediate" in globalThis ? (f) => { const timer = setTimeout(f, 0); return () => clearTimeout(timer); }; -var setImmediate = (f) => { +var setImmediate2 = (f) => { try { return setTimer(f); } catch { @@ -2004,7 +2051,7 @@ class MixedScheduler { setImmediate; constructor(executionMode = "async", setImmediateFn) { this.executionMode = executionMode; - this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate2); } shouldYield(fiber) { return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; @@ -2018,7 +2065,7 @@ class MixedSchedulerDispatcher { tasks = /* @__PURE__ */ new PriorityBuckets; running = undefined; setImmediate; - constructor(setImmediateFn = setImmediate) { + constructor(setImmediateFn = setImmediate2) { this.setImmediate = setImmediateFn; } scheduleTask(task, priority) { @@ -2262,10 +2309,7 @@ class Interrupt extends ReasonBase { } } var causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); -var findFail = (self) => { - const reason = self.reasons.find(isFailReason); - return reason ? succeed2(reason) : fail2(self); -}; +var hasFails = (self) => self.reasons.some(isFailReason); var findError = (self) => { for (let i = 0;i < self.reasons.length; i++) { const reason = self.reasons[i]; @@ -2275,6 +2319,9 @@ var findError = (self) => { } return fail2(self); }; +var hasDies = (self) => self.reasons.some(isDieReason); +var causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +var findRecoverableError = (self) => hasDies(self) ? fail2(causeElectDefects(self)) : findError(self); var hasInterrupts = (self) => self.reasons.some(isInterruptReason); var hasInterruptsOnly = (self) => self.reasons.length > 0 && self.reasons.every(isInterruptReason); var reasonAnnotations = (self) => makeUnsafe(self.annotations); @@ -2336,12 +2383,14 @@ var causePrettyErrors = (self, options) => { } return errors; }; -var causePrettyError = (original, annotations, options) => { +var causePrettyError = (original, annotations, options, seen = new Set) => { const kind = typeof original; let error; if (original && kind === "object") { + seen.add(original); + const cause = original.cause; error = new globalThis.Error(causePrettyMessage(original), { - cause: original.cause ? causePrettyError(original.cause) : undefined + cause: cause !== undefined && !seen.has(cause) ? causePrettyError(cause, undefined, undefined, seen) : undefined }); if (typeof original.name === "string") { error.name = original.name; @@ -2552,7 +2601,11 @@ class FiberImpl { } else if (this._asyncContext !== undefined) { const asyncContext = this._asyncContext; this._asyncContext = undefined; - return asyncContext.runInAsyncScope(this.evaluate, this, effect); + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } } else if (this._yielded !== undefined) { const yielded = this._yielded; this._yielded = undefined; @@ -2857,7 +2910,6 @@ var tryPromise = (options) => { } }, f.length !== 0); }; -var withFiberId = (f) => withFiber((fiber) => f(fiber.id)); var callbackOptions = /* @__PURE__ */ function() { const Proto = /* @__PURE__ */ makePrimitiveProto({ op: "Async", @@ -2878,9 +2930,9 @@ var callbackOptions = /* @__PURE__ */ function() { if (yielded !== false) return yielded; yielded = true; - fiber._yielded = () => { + fiber.yieldWith(() => { resumed = true; - }; + }); if (controller === undefined && onCancel === undefined) { return Yield; } @@ -3159,9 +3211,9 @@ var catchEager = /* @__PURE__ */ dual(2, (self, f) => { if (effectIsExit(self)) { if (self._tag === "Success") return self; - const error = findError(self.cause); + const error = findRecoverableError(self.cause); if (isFailure2(error)) - return self; + return exitFailCause(error.failure); return f(error.success); } return catch_(self, f); @@ -3175,10 +3227,7 @@ var exitMap = /* @__PURE__ */ dual(2, (self, f) => self._tag === "Success" ? exi var exitMapError = /* @__PURE__ */ dual(2, (self, f) => { if (self._tag === "Success") return self; - const error = findError(self.cause); - if (isFailure2(error)) - return self; - return exitFail(f(error.success)); + return exitFailCause(causeMap(self.cause, f)); }); var exitZipRight = /* @__PURE__ */ dual(2, (self, that) => exitIsSuccess(self) ? that : self); var exitAsVoidAll = (exits) => { @@ -3242,10 +3291,10 @@ var catchCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(s const eb = filter(cause); return isFailure2(eb) ? failCause(eb.failure) : f(eb.success, cause); })); -var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findError, (e) => f(e))); +var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findRecoverableError, (e) => f(e))); var tapCause = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => andThen(f(cause), failCause(cause)))); var catchIf = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, predicate, f, orElse) => catchCause(self, (cause) => { - const error = findError(cause); + const error = findRecoverableError(cause); if (isFailure2(error)) return failCause(error.failure); if (!predicate(error.success)) { @@ -3257,7 +3306,7 @@ var catchTag = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, k, f, or const pred = Array.isArray(k) ? (e) => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); return catchIf(self, pred, f, orElse); }); -var mapError = /* @__PURE__ */ dual(2, (self, f) => catch_(self, (error) => failSync(() => f(error)))); +var mapError = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => failCause(causeMap(cause, f)))); var orDie = (self) => catch_(self, die); var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { if (!options?.log) { @@ -3269,12 +3318,25 @@ var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) = const logEffect = logWithLevel(options.log === true ? undefined : options.log); return matchCauseEffect(self, { onFailure(cause) { - const failure = findFail(cause); - return isFailure2(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); }, onSuccess: (_) => void_ }); }); +var ignoreCause = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { + if (!options?.log) { + return matchCauseEffect(self, { + onFailure: (_) => void_, + onSuccess: (_) => void_ + }); + } + const logEffect = logWithLevel(options.log === true ? undefined : options.log); + return matchCauseEffect(self, { + onFailure: (cause) => options.message === undefined ? logEffect(cause) : logEffect(options.message, cause), + onSuccess: (_) => void_ + }); +}); var result = (self) => matchEager(self, { onFailure: fail2, onSuccess: succeed2 @@ -3309,16 +3371,16 @@ var makeMatch = (op, onFailure) => { return MatchImpl; }; var MatchImpl = /* @__PURE__ */ makeMatch("Match", function(cause, fiber) { - const fail = cause.reasons.find(isFailReason); - if (fail === undefined) - return failCause(cause); + const error = findRecoverableError(cause); + if (isFailure2(error)) + return failCause(error.failure); const handlers = this.payload; - return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(fail.error) : internalCall(() => handlers.onFailure(fail.error))); + return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))); }); var matchEffect = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, { onFailure: (cause) => { - const fail = cause.reasons.find(isFailReason); - return fail ? options.onFailure(fail.error) : failCause(cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.onFailure(error.success); }, onSuccess: options.onSuccess })); @@ -3327,9 +3389,9 @@ var matchEager = /* @__PURE__ */ dual(2, (self, options) => { if (effectIsExit(self)) { if (self._tag === "Success") return exitSucceed(options.onSuccess(self.value)); - const error = findError(self.cause); + const error = findRecoverableError(self.cause); if (isFailure2(error)) - return self; + return exitFailCause(error.failure); return exitSucceed(options.onFailure(error.success)); } return match4(self, options); @@ -3386,17 +3448,17 @@ var runFinalizer = (finalizer, exit_) => { return exitDie(defect); } }; -var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeCombine(exit_.cause, cause))); +var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); var scopeCloseFinalizers = /* @__PURE__ */ fnUntraced(function* (self, finalizers, exit_) { let exits = []; const fibers = []; - const arr = Array.from(finalizers.values()); + const arr = Array.from(finalizers); const parent = getCurrentFiber(); for (let i = arr.length - 1;i >= 0; i--) { - const finalizer = arr[i]; + const [key, finalizer] = arr[i]; if (self.strategy === "sequential") { exits.push(yield* exit(runFinalizer(finalizer, exit_))); - } else { + } else if (key !== parent) { fibers.push(forkUnsafe(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); } } @@ -3589,15 +3651,9 @@ var all = (arg, options) => { } else if (options?.discard) { return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options); } - return suspend(() => { - const out = {}; - return as(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => { - assignProperty(out, key, value); - }), { - discard: true, - concurrency: options?.concurrency - }), out); - }); + return suspend(() => map3(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => [key, value]), { + concurrency: options?.concurrency + }), Object.fromEntries)); }; var whileLoop = /* @__PURE__ */ makePrimitive({ op: "While", @@ -3736,7 +3792,7 @@ var iterateConcurrentImpl = (options) => { const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); if (reasons.length > 0) { const cause = causeFromReasons(reasons); - terminal = exitFailCause(terminal._tag === "Failure" ? causeCombine(terminal.cause, cause) : cause); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); } } } else { @@ -3818,14 +3874,13 @@ var forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterrupt } return child; }; +var fiberScopeFinalizer = (fiber) => () => withFiber((current) => current === fiber ? void_ : fiberInterrupt(fiber)); var forkIn = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, scope, options) => withFiber((parent) => { - const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + const fiber = scope.state._tag === "Closed" ? new FiberImpl(parent.context) : forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); if (!fiber._exit) { if (scope.state._tag !== "Closed") { - const key = {}; - const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); - scopeAddFinalizerUnsafe(scope, key, finalizer); - fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + scopeAddFinalizerUnsafe(scope, fiber, fiberScopeFinalizer(fiber)); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, fiber)); } else { fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); } @@ -3862,7 +3917,7 @@ var fiberRunIn = /* @__PURE__ */ dual(2, (self, scope) => { return self; } scopeRemoveFinalizerUnsafe(scope, self); - scopeAddFinalizerUnsafe(scope, self, () => fiberInterrupt(self)); + scopeAddFinalizerUnsafe(scope, self, fiberScopeFinalizer(self)); self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, self)); return self; }); @@ -4317,7 +4372,6 @@ var makeDieReason = (defect) => new Die(defect); var hasInterruptsOnly2 = hasInterruptsOnly; var map4 = causeMap; var squash = causeSquash; -var findError2 = findError; var isDone2 = isDone; var Done2 = Done; var done2 = done; @@ -4328,6 +4382,7 @@ var reasonAnnotations2 = reasonAnnotations; var succeed4 = exitSucceed; var failCause2 = exitFailCause; var fail5 = exitFail; +var interrupt2 = exitInterrupt; var void_2 = exitVoid; var isSuccess3 = exitIsSuccess; var isFailure3 = exitIsFailure; @@ -4512,8 +4567,8 @@ var mergeAllEffect = (layers, memoMap, scope) => { concurrency: layers.length }).pipe(map3((context) => mergeAll(...context))); }; -var mergeAll2 = (...layers) => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); -var provideWith = (self, that, f) => fromBuild((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); +var mergeAll2 = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +var provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); var provide2 = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, identity)); var provideMerge = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, (self, that) => merge(that, self))); @@ -4715,11 +4770,10 @@ var provideLayer = (self, layer, options) => scopedWith((scope) => flatMap2(opti var provide3 = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll2(...source) : source, options)); // node_modules/effect/dist/internal/schedule.js -var findErrorOnly = (cause) => cause.reasons.every(isFailReason) ? findError(cause) : fail2(cause); var retryOrElse = /* @__PURE__ */ dual(3, (self, policy, orElse) => flatMap2(toStepWithMetadata(policy), (step) => { let meta = CurrentMetadata.defaultValue(); let lastError; - const loop = catchCauseFilter(suspend(() => provideService(self, CurrentMetadata, meta)), findErrorOnly, (error) => { + const loop = catchCauseFilter(suspend(() => provideService(self, CurrentMetadata, meta)), findRecoverableError, (error) => { lastError = error; return flatMap2(step(error), (meta_) => { meta = meta_; @@ -4773,6 +4827,7 @@ var callback2 = callback; var never2 = never; var gen2 = gen; var fail6 = fail3; +var failSync2 = failSync; var failCause3 = failCause; var failCauseSync2 = failCauseSync; var die3 = die; @@ -4794,6 +4849,7 @@ var orDie2 = orDie; var tapCause2 = tapCause; var retry2 = retry; var ignore2 = ignore; +var ignoreCause2 = ignoreCause; var timeoutOrElse2 = timeoutOrElse; var sleep2 = sleep; var raceFirst2 = raceFirst; @@ -4811,7 +4867,7 @@ var ensuring2 = ensuring; var onError2 = onError; var onExitPrimitive2 = onExitPrimitive; var onExit2 = onExit; -var interrupt2 = interrupt; +var interrupt3 = interrupt; var uninterruptible2 = uninterruptible; var uninterruptibleMask2 = uninterruptibleMask; var forever3 = forever; @@ -4826,16 +4882,23 @@ var fn2 = fn; var clockWith2 = clockWith; var logError = /* @__PURE__ */ logWithLevel("Error"); var effectify = (fn, onError, onSyncError) => (...args) => callback2((resume) => { + let synchronous = true; + let pending; try { fn(...args, (err, result) => { - if (err) { - resume(onError ? suspend2(() => fail6(onError(err, args))) : fail6(err)); + const effect = err ? onError ? suspend2(() => fail6(onError(err, args))) : fail6(err) : succeed6(result); + if (synchronous) { + pending ??= effect; } else { - resume(succeed6(result)); + resume(effect); } }); } catch (err) { - resume(onSyncError ? fail6(onSyncError(err, args)) : die3(err)); + pending = onSyncError ? fail6(onSyncError(err, args)) : die3(err); + } + synchronous = false; + if (pending) { + resume(pending); } }); var mapEager2 = mapEager; @@ -5247,7 +5310,7 @@ var defaultLeafHook = (issue) => { } } }; -var defaultCheckHook = (issue) => findMessage(issue.issue) ?? findMessage(issue); +var defaultCheckHook = (issue) => findMessage(issue) ?? findMessage(issue.issue); function formatInput(issue) { return hasInput(issue) ? format(issue.input) : undefined; } @@ -5259,6 +5322,13 @@ function getExpectedMessage(expected, issue) { const input = formatInput(issue); return input === undefined ? `Expected ${expected}` : `Expected ${expected}, got ${input}`; } +function getFilterMessage(issue, checkHook) { + const message = checkHook(issue); + if (message !== undefined || issue.issue._tag !== "InvalidValue") + return message; + const expected = findExpected(issue.issue); + return expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); +} function formatCheck(check) { const expected = check.annotations?.expected; if (typeof expected === "string") @@ -5274,44 +5344,33 @@ function makeFormatterDefault() { return (issue) => formatIssue(issue, ""); } var defaultFormatter = /* @__PURE__ */ makeFormatterDefault(); -function formatIssue(issue, path) { +function formatIssue(issue, path, messageOverride) { let message; switch (issue._tag) { - case "Filter": { - const annotated = defaultCheckHook(issue); - if (annotated !== undefined) { - message = annotated; - } else { - if (issue.issue._tag !== "InvalidValue") { - return formatIssue(issue.issue, path); - } - const expected = findExpected(issue.issue); - message = expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); - } - break; - } + case "Filter": + return formatIssue(issue.issue, path, messageOverride ?? getFilterMessage(issue, defaultCheckHook)); case "Encoding": - return formatIssue(issue.issue, path); + return formatIssue(issue.issue, path, messageOverride); case "Pointer": - return formatIssue(issue.issue, path + formatPath(issue.path)); + return formatIssue(issue.issue, path + formatPath(issue.path), messageOverride); case "Composite": case "AnyOf": { if (issue._tag === "Composite" || issue.issues.length > 0) { - return issue.issues.map((issue) => formatIssue(issue, path)).join(` + return issue.issues.map((issue) => formatIssue(issue, path, messageOverride)).join(` `); } - message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); + message = messageOverride ?? findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); break; } default: - message = defaultLeafHook(issue); + message = messageOverride ?? defaultLeafHook(issue); break; } return path ? `${message} at ${path}` : message; } function findMessage(issue) { - if (issue._tag === "Pointer") + if (issue._tag === "Pointer" || issue._tag === "Composite") return; if (issue._tag === "Encoding") return findMessage(issue.issue); @@ -5569,7 +5628,12 @@ var Declaration = class extends ASTNodeImpl { return (input, options) => { if (input === missing) return missingExit; - return (run ??= this.run(this.typeParameters))(input, this, options); + run ??= this.run(this.typeParameters); + try { + return run(input, this, options); + } catch (error) { + return die3(error); + } }; } _rebuild(recur, checks, encodingChecks, run, encodingRun) { @@ -5778,7 +5842,7 @@ var Arrays = class extends ASTNodeImpl { input, len, tailThreshold: Math.max(elementLen, len - tailLen), - output: new globalThis.Array(len), + output: [], issues: undefined, options }; @@ -5887,7 +5951,7 @@ var wrapPropertyKeyIssue = (s, ast, key, exit) => { return fail5(new Composite(ast, [pointer], s.input, s.options)); } }; -var FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?"; +var FINITE_PATTERN = "[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?"; function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) { let stringKeys; let symbolKeys; @@ -6126,9 +6190,15 @@ var Objects = class extends ASTNodeImpl { if (indexCount) return makeFallback(); let fallback; - const resume = (state, index, pending) => { + const resume = (snapshot, index, pending) => { const property = properties[index]; return flatMap3(exit2(pending), (exit) => { + const state = { + ...snapshot, + out: { + ...snapshot.out + } + }; const terminal = stepProperty(state, property, exit); if (terminal) return terminal; @@ -6258,9 +6328,6 @@ function struct(fields, checks, annotations) { function getAST(self) { return self.ast; } -function tuple(elements, checks = undefined) { - return new Arrays(false, elements.map((e) => e.ast), [], undefined, checks); -} function union(members, options, checks) { return new Union(members.map(getAST), options, undefined, checks); } @@ -7191,6 +7258,16 @@ var unknownToStringTree = /* @__PURE__ */ new Link(StringTree, /* @__PURE__ */ p // node_modules/effect/dist/internal/schema/interpreter.js var flatMapTransformation = (result, current, f) => result === sameExit ? f(current) : flatMapEager2(result, f); function compileTransformation(transformation) { + const apply = compileTransformationUnsafe(transformation); + return (result, current, options) => { + try { + return apply(result, current, options); + } catch (error) { + return die3(error); + } + }; +} +function compileTransformationUnsafe(transformation) { if (transformation._tag === "Middleware") { return (result, current, options) => { const transformed = result === sameExit ? transformation.decode(succeed7(toOption(current)), options) : transformation.decode(mapEager2(result, toOption), options); @@ -7266,53 +7343,57 @@ function compile(ast, compile, compileField, base, specialize) { let encodingParsers; const parseChecks = (input, options) => { let result = parser(input, options); - if (encodingChecks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const output = result === sameExit ? input : result[args]; - if (input !== missing && output !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, input, options)); + try { + if (encodingChecks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const output = result === sameExit ? input : result[args]; + if (input !== missing && output !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + result = fail6(new Composite(ast, issues, input, options)); + } } } - } - } else { - result = flatMap3(result, (value) => { - if (input !== missing && value !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - return fail6(new Composite(ast, issues, input, options)); + } else { + result = flatMap3(result, (value) => { + if (input !== missing && value !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, input, options)); + } } - } - return succeed6(value); - }); - } - } - if (checks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const value = result === sameExit ? input : result[args]; - if (value === missing) - return result; - const issues = collectIssues(checks, value, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, value, options)); - } + return succeed6(value); + }); } - } else { - result = flatMap3(result, (value) => { - if (value !== missing) { + } + if (checks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const value = result === sameExit ? input : result[args]; + if (value === missing) + return result; const issues = collectIssues(checks, value, undefined, ast, options); if (issues) { - return fail6(new Composite(ast, issues, value, options)); + result = fail6(new Composite(ast, issues, value, options)); } } - return succeed6(value); - }); + } else { + result = flatMap3(result, (value) => { + if (value !== missing) { + const issues = collectIssues(checks, value, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, value, options)); + } + } + return succeed6(value); + }); + } } + return result; + } catch (error) { + return die3(error); } - return result; }; const parseLocal = specialize === undefined ? parseChecks : specialize(parseChecks); if (!links) { @@ -7890,18 +7971,6 @@ function Record(key, value) { value }); } -function makeTuple(ast, elements) { - return make8(ast, { - elements, - mapElements(f, options) { - const elements = f(this.elements); - return makeTuple(tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements); - } - }); -} -function Tuple(elements) { - return makeTuple(tuple(elements), elements); -} var ArraySchema = /* @__PURE__ */ lambda((schema) => make8(new Arrays(false, [], [schema.ast]), { value: schema })); @@ -8078,16 +8147,23 @@ function isPattern2(regExp, annotations) { }); } function isBase64(annotations) { - const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - return isPattern2(regExp, { + const pattern = "^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"; + const regExp = /^[0-9a-zA-Z+/]*={0,2}$/; + return makeFilter2((s) => s.length % 4 === 0 && regExp.test(s), { expected: "a base64 encoded string", representation: { id: "effect/schema/isBase64", payload: null }, toJsonSchema: () => ({ - pattern: regExp.source + pattern }), + arbitraryConstraint: { + patterns: [{ + source: pattern, + flags: "" + }] + }, toCode: () => ({ runtime: "Schema.isBase64()" }), @@ -8275,47 +8351,6 @@ var File = /* @__PURE__ */ instanceOf(globalThis.File, { }) })) }); -var FormData2 = /* @__PURE__ */ instanceOf(globalThis.FormData, { - representation: { - id: "effect/schema/FormData", - payload: null - }, - toCode: () => ({ - runtime: `Schema.FormData`, - Type: `globalThis.FormData` - }), - expected: "FormData", - toCodecJson: () => link()(ArraySchema(Tuple([String4, Union2([Struct({ - _tag: tag("String"), - value: String4 - }), Struct({ - _tag: tag("File"), - value: File - })])])), transformEffect2({ - decode: (e) => { - const out = new globalThis.FormData; - for (const [key, entry] of e) { - out.append(key, entry.value); - } - return succeed6(out); - }, - encode: (formData) => { - return succeed6(globalThis.Array.from(formData.entries()).map(([key, value]) => { - if (typeof value === "string") { - return [key, { - _tag: "String", - value - }]; - } else { - return [key, { - _tag: "File", - value - }]; - } - })); - } - })) -}); var URLSearchParams2 = /* @__PURE__ */ instanceOf(globalThis.URLSearchParams, { representation: { id: "effect/schema/URLSearchParams", @@ -8431,13 +8466,16 @@ function makeClass(Inherited, identifier, struct2, annotations, proto) { } return out; } -function getClassTransformation(self) { - return new Transformation(transform((input) => new self(input, { +function makeClassTrusted(self, fields) { + return new self(fields, { "~payload": { token: payloadToken, - value: input + value: fields } - })), passthrough2()); + }); +} +function getClassTransformation(self) { + return new Transformation(transform((input) => makeClassTrusted(self, input)), passthrough2()); } function getClassTypeId(identifier) { return `~effect/Schema/Class/${identifier}`; @@ -8506,7 +8544,7 @@ function nominal() { } // node_modules/effect/dist/Fiber.js var join = fiberJoin; -var interrupt3 = fiberInterrupt; +var interrupt4 = fiberInterrupt; var getCurrent = getCurrentFiber; var runIn = fiberRunIn; @@ -9035,7 +9073,9 @@ var toTransform = (channel) => channel.transform; var asyncQueue = (scope, f, options) => make12({ capacity: options?.bufferSize, strategy: options?.strategy -}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope)))); +}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope, { + startImmediately: true +})))); var callbackArray = (f, options) => fromTransform((_, scope) => map5(asyncQueue(scope, f, options), takeAll2)); var suspend3 = (evaluate) => fromTransform((upstream, scope) => suspend2(() => toTransform(evaluate())(upstream, scope))); var fromIterator = (iterator) => fromPull(sync3(() => { @@ -9047,8 +9087,8 @@ var fromIterator = (iterator) => fromPull(sync3(() => { })); var succeed8 = (value) => fromEffect(succeed6(value)); var empty3 = /* @__PURE__ */ fromPull(/* @__PURE__ */ succeed6(/* @__PURE__ */ done2())); -var fail7 = (error) => fromPull(succeed6(fail6(error))); var failCause5 = (cause) => fromPull(failCause3(cause)); +var die4 = (defect) => failCause5(die2(defect)); var fromEffect = (effect) => fromPull(sync3(() => { let done = false; return suspend2(() => { @@ -9160,29 +9200,7 @@ var mapAccum = /* @__PURE__ */ dual((args) => isChannel(args[0]), (self, initial }); return pump; }))); -var catchCause3 = /* @__PURE__ */ dual(2, (self, f) => fromTransform((upstream, scope) => { - let forkedScope = forkUnsafe2(scope); - return map5(toTransform(self)(upstream, forkedScope), (pull) => { - let currentPull = pull.pipe(catchCause2((cause) => { - if (isDoneCause(cause)) { - return failCause3(cause); - } - const toClose = forkedScope; - forkedScope = forkUnsafe2(scope); - return close(toClose, failCause2(cause)).pipe(andThen2(toTransform(f(cause))(upstream, forkedScope)), flatMap3((childPull) => { - currentPull = childPull; - return childPull; - })); - })); - return suspend2(() => currentPull); - }); -})); -var catchCauseFilter2 = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause3(self, (cause) => { - const result = filter(cause); - return isFailure2(result) ? failCause5(result.failure) : f(result.success, cause); -})); -var catch_3 = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter2(self, findError2, (e) => f(e))); -var mapError4 = /* @__PURE__ */ dual(2, (self, f) => catch_3(self, (err) => fail7(f(err)))); +var mapError4 = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => succeed6(mapError2(pull, (err) => isDone2(err) ? err : f(err))))); var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { bufferSize = 16, concurrency, @@ -9191,7 +9209,7 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { const concurrencyN = concurrency === "unbounded" ? Number.MAX_SAFE_INTEGER : Math.max(1, concurrency); const semaphore = switch_ ? undefined : makeUnsafe5(concurrencyN); const doneLatch = yield* make9(true); - const fibers = new Set; + const fibers = new Map; const queue = yield* bounded(bufferSize); yield* addFinalizer2(forkedScope, shutdown(queue)); const pull = yield* toTransform(channels)(upstream, scope); @@ -9210,11 +9228,12 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { const childScope = forkUnsafe2(forkedScope); const childPull = yield* toTransform(channel)(upstream, childScope); while (fibers.size >= concurrencyN) { - const fiber = headUnsafe(fibers); + const [fiber, fiberScope] = headUnsafe(fibers); fibers.delete(fiber); if (fibers.size === 0) yield* doneLatch.open; - yield* interrupt3(fiber); + yield* interrupt4(fiber); + yield* ignoreCause2(close(fiberScope, interrupt2())); } const fiber = yield* childPull.pipe(tap2(() => yieldNow2), flatMap3((value) => offer(queue, value)), forever3({ disableYield: true @@ -9233,7 +9252,7 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { yield* doneLatch.open; })), forkChild2); doneLatch.closeUnsafe(); - fibers.add(fiber); + fibers.set(fiber, childScope); } }).pipe(catchCause2((cause) => { const halt = filterDone(cause); @@ -9357,6 +9376,18 @@ var splitLines = () => fromTransform((upstream, _scope) => sync3(() => { } return pullOrFlush; })); +var decodeText = (encoding, options) => fromTransform((upstream, _scope) => sync3(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + let pull = upstream.pipe(map5(map2((bytes) => decoder.decode(bytes, streamOptions))), catchDone((leftover) => { + pull = done2(leftover); + const last = decoder.decode(); + return last.length > 0 ? succeed6(of(last)) : pull; + })); + return suspend2(() => pull); +})); var pipeTo = /* @__PURE__ */ dual(2, (self, that) => fromTransform((upstream, scope) => flatMap3(toTransform(self)(upstream, scope), (upstream) => toTransform(that)(upstream, scope)))); var unwrap = (channel) => fromTransform((upstream, scope) => { let pull; @@ -9516,19 +9547,19 @@ var make13 = (options) => withFiber2((fiber) => { if (state._tag === "Acquired") return close(state.scope, void_2); if (state._tag === "Acquiring") - return interrupt3(state.fiber); + return interrupt4(state.fiber); return void_3; }), ref); }); var getState = (self, restore) => { switch (self.state._tag) { case "Closed": { - return interrupt2; + return interrupt3; } case "Acquired": { const state = self.state; state.refCount++; - return state.fiber ? as2(interrupt3(state.fiber), state) : succeed6(state); + return state.fiber ? as2(interrupt4(state.fiber), state) : succeed6(state); } case "Acquiring": { const state = self.state; @@ -9546,7 +9577,7 @@ var getState = (self, restore) => { const scope = makeUnsafe3(); const acquire = provideContext2(self.acquire, add(self.context, Scope, scope)).pipe(flatMap3((value) => { if (self.state !== acquiring) { - return interrupt2; + return interrupt3; } const state = { _tag: "Acquired", @@ -9579,7 +9610,7 @@ var awaitAcquiring = (self, acquiring, restore) => onExit2(restore(join(acquirin if (--acquiring.awaiters > 0 || self.state !== acquiring) return void_3; self.state = stateEmpty; - return interrupt3(acquiring.fiber); + return interrupt4(acquiring.fiber); }); var get2 = (self_) => { const self = self_; @@ -9626,7 +9657,13 @@ var toChannel2 = (stream) => stream.channel; var callback3 = (f, options) => fromChannel3(callbackArray(f, options)); var empty4 = /* @__PURE__ */ fromChannel3(empty3); var succeed9 = (value) => fromChannel3(succeed8(of(value))); -var suspend4 = (stream) => fromChannel3(suspend3(() => stream().channel)); +var suspend4 = (stream) => { + const suspended = fromChannel3(suspend3(() => stream().channel)); + suspendedStreams.set(suspended, stream); + return suspended; +}; +var suspendedStreams = /* @__PURE__ */ new WeakMap; +var die6 = (defect) => fromChannel3(die4(defect)); var unwrap3 = (effect) => fromChannel3(unwrap(map5(effect, toChannel2))); var map8 = /* @__PURE__ */ dual(2, (self, f) => suspend4(() => { let i = 0; @@ -9644,10 +9681,21 @@ function* concatChannels(self, that) { while (stack.length > 0) { const stream = stack.pop(); const parts = concatParts.get(stream); - if (parts === undefined) - yield stream.channel; - else + if (parts !== undefined) { stack.push(parts[1], parts[0]); + continue; + } + const evaluate = suspendedStreams.get(stream); + if (evaluate === undefined) { + yield stream.channel; + continue; + } + try { + stack.push(evaluate()); + } catch (defect) { + stack.push(die6(defect)); + } + yield empty3; } } var merge3 = /* @__PURE__ */ dual((args) => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel3(merge2(toChannel2(self), toChannel2(that), options))); @@ -9680,12 +9728,7 @@ var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (up }); return suspend2(() => done ? done : pull); }))); -var decodeText = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => suspend4(() => { - const decoder = new TextDecoder(options?.encoding); - return map8(self, (chunk) => decoder.decode(chunk, { - stream: true - })); -})); +var decodeText2 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => self.channel.pipe(pipeTo(decodeText(options?.encoding)), fromChannel3)); var splitLines2 = (self) => self.channel.pipe(pipeTo(splitLines()), fromChannel3); var run2 = /* @__PURE__ */ dual(2, (self, sink) => scopedWith2((scope) => toPullScoped(self.channel, scope).pipe(flatMap3((upstream) => sink.transform(upstream, scope)), map5(([a]) => a)))); var runCollect = (self) => runFold(self.channel, () => [], (acc, chunk) => { @@ -9967,7 +10010,6 @@ var toConfigCursorAST = /* @__PURE__ */ memoize((root) => { seen.add(ast); switch (ast._tag) { case "Objects": { - const matchesIndex = ast.indexSignatures.map((is) => _is(is.parameter)); const materialize = fnUntraced2(function* (cursor) { if (cursor.node?._tag !== "Record") { return; @@ -9978,10 +10020,16 @@ var toConfigCursorAST = /* @__PURE__ */ memoize((root) => { if (typeof property.name === "string") keys.add(property.name); } - if (matchesIndex.length > 0) { + if (ast.indexSignatures.length > 0) { + const input = {}; for (const key of node.keys) { - if (matchesIndex.some((matches) => matches(key))) - keys.add(key); + assignProperty(input, key, undefined); + } + for (const is of ast.indexSignatures) { + for (const key of getIndexSignatureKeys(input, is.parameter)) { + if (typeof key === "string") + keys.add(key); + } } } const out = {}; @@ -10073,10 +10121,14 @@ var ulidString = (timestampMillis, bytes) => { }; // node_modules/effect/dist/internal/uuid.js -var hex = (byte) => byte.toString(16).padStart(2, "0"); +var hex = /* @__PURE__ */ Array.from({ + length: 256 +}, (_, byte) => byte.toString(16).padStart(2, "0")); var stringify = (bytes) => { - const segments = [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)]; - return segments.map((segment) => Array.from(segment, hex).join("")).join("-"); + if (bytes.length < 16) { + return [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)].map((segment) => Array.from(segment, (byte) => hex[byte]).join("")).join("-"); + } + return hex[bytes[0]] + hex[bytes[1]] + hex[bytes[2]] + hex[bytes[3]] + "-" + hex[bytes[4]] + hex[bytes[5]] + "-" + hex[bytes[6]] + hex[bytes[7]] + "-" + hex[bytes[8]] + hex[bytes[9]] + "-" + hex[bytes[10]] + hex[bytes[11]] + hex[bytes[12]] + hex[bytes[13]] + hex[bytes[14]] + hex[bytes[15]]; }; var randomBytes = () => globalThis.crypto.getRandomValues(new Uint8Array(16)); function v4Bytes(bytes = randomBytes()) { @@ -10369,23 +10421,26 @@ var defaultTeardown = (exit, onExit) => { return onExit(getErrorExitCode(squash(exit.cause))); }; var makeRunMain = (f) => dual((args) => isEffect2(args[0]), (effect, options) => { - const fiber = options?.disableErrorReporting === true ? runFork2(effect) : runFork2(tapCause2(effect, (cause) => { + const main = options?.disableErrorReporting === true ? effect : tapCause2(effect, (cause) => { if (hasInterruptsOnly2(cause)) return void_3; const isReported = getErrorReported(squash(cause)); return isReported ? logError(cause) : void_3; - })); - try { - const keepAlive = globalThis.setInterval(constVoid, 2147483647); - fiber.addObserver(() => { - clearInterval(keepAlive); - }); - } catch {} - const teardown = options?.teardown ?? defaultTeardown; - return f({ - fiber, - teardown }); + const teardown = options?.teardown ?? defaultTeardown; + runFork2(withFiber2((fiber) => { + try { + const keepAlive = globalThis.setInterval(constVoid, 2147483647); + fiber.addObserver(() => { + clearInterval(keepAlive); + }); + } catch {} + f({ + fiber, + teardown + }); + return main; + })); }); var errorExitCode = "~effect/Runtime/errorExitCode"; var getErrorExitCode = (u) => { @@ -10449,7 +10504,7 @@ var makeHandle = (params) => Object.setPrototypeOf({ ...params }, HandleProto); var make23 = (spawn) => { - const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); + const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText2(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); const streamLines = (command, options) => splitLines2(streamString(command, options)); return ChildProcessSpawner.of({ spawn, @@ -10697,11 +10752,11 @@ var layer = (defaults = {}) => effect(Gh, gen2(function* () { let stdoutTruncated = false; let stderr = ""; let stderrTruncated = false; - const output = merge3(handle.stdout.pipe(decodeText(), map8((text) => { + const output = merge3(handle.stdout.pipe(decodeText2(), map8((text) => { stdoutTruncated ||= stdout.length + text.length > outputLimit; stdout = (stdout + text).slice(-outputLimit); return GhChunk.cases.Stdout.make({ text }); - })), handle.stderr.pipe(decodeText(), map8((text) => { + })), handle.stderr.pipe(decodeText2(), map8((text) => { stderrTruncated ||= stderr.length + text.length > outputLimit; stderr = (stderr + text).slice(-outputLimit); return GhChunk.cases.Stderr.make({ text }); @@ -10948,6 +11003,7 @@ var handleErrnoException = (module, method) => (err, [path]) => { reason = "NotFound"; break; case "EACCES": + case "EPERM": reason = "PermissionDenied"; break; case "EEXIST": @@ -10976,66 +11032,149 @@ var handleErrnoException = (module, method) => (err, [path]) => { }); }; +// node_modules/@effect/platform-node-shared/dist/NodeSink.js +import { finished } from "node:stream"; + +// node_modules/@effect/platform-node-shared/dist/internal/stream.js +var destroyStream = (stream, cleanup, onDestroyed) => { + if (!("closed" in stream)) { + cleanup(); + onDestroyed?.(); + return; + } + const onDone = () => { + clearImmediate(immediate); + stream.off("error", onDone); + stream.off("close", onDone); + onDestroyed?.(); + }; + const onClosed = () => { + if (stream.closed) { + onDone(); + } else { + immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + } + }; + let immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + stream.once("error", onDone); + stream.once("close", onDone); + cleanup(); + if (!stream.closed) { + stream.destroy(); + } +}; + // node_modules/@effect/platform-node-shared/dist/NodeSink.js var fromWritable = (options) => fromChannel2(mapDone(fromWritableChannel(options), (_) => [_])); var fromWritableChannel = (options) => fromTransform((pull) => { const writable = options.evaluate(); - return succeed6(pullIntoWritable({ + const write = pullIntoWritable({ ...options, writable, pull - })); -}); -var pullIntoWritable = (options) => options.pull.pipe(flatMap3((chunk) => { - let i = 0; - return callback2((resume) => { - let cancelled = false; - const loop = () => { - for (;i < chunk.length; ) { - if (cancelled) { - return; - } - const success = options.writable.write(chunk[i++], options.encoding); - if (!success) { - if (!cancelled) { - options.writable.once("drain", loop); + }); + return succeed6(options.endOnDone === false ? write : onError2(write, (cause) => isDoneCause(cause) ? void_3 : releaseWritable(writable))); +}); +var releaseWritable = (writable) => callback2((resume) => { + const onDestroyed = () => resume(void_3); + if (writable.closed) { + const cleanup = finished(writable, { + readable: false + }, () => { + cleanup(); + onDestroyed(); + }); + } else { + destroyStream(writable, constVoid, onDestroyed); + } +}); +var pullIntoWritable = (options) => withFiber2((fiber) => { + const dispatcher = fiber.currentDispatcher; + const completion = makeUnsafe2(); + const failure = makeUnsafe2(); + const onError = (error) => doneUnsafe(failure, failSync2(() => options.onError(error))); + let errorEmitted = false; + const onStreamError = (error) => { + errorEmitted = true; + onError(error); + }; + options.writable.on("error", onStreamError); + const cleanup = finished(options.writable, { + readable: false + }, (error) => { + if (error) { + onError(error); + } else { + doneUnsafe(completion, void_3); + } + }); + return options.pull.pipe(flatMap3((chunk) => { + let i = 0; + return callback2((resume) => { + let cancelled = false; + const onFinish = () => dispatcher.scheduleTask(loop, 0); + const loop = () => { + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + for (;i < chunk.length; ) { + if (cancelled) { + return; + } + const success = options.writable.write(chunk[i++], options.encoding, (error) => { + if (!error) + return; + if (options.writable.closed) { + onError(error); + } else { + dispatcher.scheduleTask(() => onError(error), 0); + } + }); + if (!success) { + if (!cancelled) { + options.writable.once("drain", loop); + options.writable.once("finish", onFinish); + } + return; } - return; } - } - if (!cancelled) { - resume(void_3); - } - }; - loop(); - return sync3(() => { - cancelled = true; - options.writable.off("drain", loop); + if (!cancelled) { + resume(void_3); + } + }; + loop(); + return sync3(() => { + cancelled = true; + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + }); }); - }); -}), forever3({ - disableYield: true -}), options.endOnDone !== false ? catchDone((_) => { - if ("closed" in options.writable && options.writable.closed) { - return done2(_); - } - return callback2((resume) => { - const onFinish = () => resume(done2(_)); - options.writable.once("finish", onFinish); + }), forever3({ + disableYield: true + }), options.endOnDone !== false ? catchDone((_) => { options.writable.end(); - return sync3(() => { - options.writable.off("finish", onFinish); - }); - }); -}) : identity, raceFirst2(callback2((resume) => { - const onError = (error) => resume(fail6(options.onError(error))); - options.writable.once("error", onError); - return sync3(() => { - options.writable.off("error", onError); - }); -}))); + return andThen2(_await(completion), done2(_)); + }) : identity, raceFirst2(_await(failure)), ensuring2(sync3(() => { + cleanup(); + const removeErrorListener = () => { + options.writable.off("error", onStreamError); + options.writable.off("error", removeErrorListener); + options.writable.off("close", removeErrorListener); + }; + if (options.writable.errored && !options.writable.closed && !errorEmitted) { + options.writable.once("error", removeErrorListener); + options.writable.once("close", removeErrorListener); + } else { + removeErrorListener(); + } + }))); +}); // node_modules/@effect/platform-node-shared/dist/NodeStream.js +import { finished as finished2, Readable } from "node:stream"; var fromReadable = (options) => fromChannel3(fromReadableChannel(options)); var fromReadableChannel = (options) => fromTransform((_, scope) => readableToPullUnsafe({ scope, @@ -11052,17 +11191,14 @@ var readableToPullUnsafe = (options) => { function onReadable() { latch.openUnsafe(); } - function onError(error) { - exit.current = fail5(options.onError(error)); - latch.openUnsafe(); - } - function onEnd() { - exit.current = fail5(Done2()); - latch.openUnsafe(); - } readable.on("readable", onReadable); - readable.once("error", onError); - readable.once("end", onEnd); + const cleanup = finished2(readable, { + readable: true, + writable: false + }, (error) => { + exit.current ??= fail5(error ? options.onError(error) : Done2()); + latch.openUnsafe(); + }); const pull = suspend2(function loop() { let item = options.readable.read(options.chunkSize); if (item === null) { @@ -11086,10 +11222,10 @@ var readableToPullUnsafe = (options) => { }); return as2(addFinalizer2(options.scope, sync3(() => { readable.off("readable", onReadable); - readable.off("error", onError); - readable.off("end", onEnd); - if (closeOnDone && "closed" in options.readable && !options.readable.closed) { - options.readable.destroy(); + if (closeOnDone) { + destroyStream(readable, cleanup); + } else { + cleanup(); } })), pull); }; @@ -11414,6 +11550,7 @@ var make25 = /* @__PURE__ */ gen2(function* () { const signalGroup = (signal) => killProcessGroup(command, childProcess, signal).pipe(catch_2(() => killProcess(command, childProcess, signal))); yield* signalGroup(options?.killSignal ?? "SIGTERM"); if (isUndefined(options?.forceKillAfter)) { + yield* _await(exitSignal); yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis); } else { yield* awaitProcessExit(childProcess, exitSignal, toMillis(options.forceKillAfter)); @@ -12007,14 +12144,14 @@ var readLink = /* @__PURE__ */ (() => { return (path) => nodeReadLink(path); })(); var realPath = /* @__PURE__ */ (() => { - const nodeRealPath = /* @__PURE__ */ effectify(NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); + const nodeRealPath = /* @__PURE__ */ effectify(process.platform === "win32" ? NFS.realpath.native : NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); return (path) => nodeRealPath(path); })(); var rename2 = /* @__PURE__ */ (() => { const nodeRename = /* @__PURE__ */ effectify(NFS.rename, /* @__PURE__ */ handleErrnoException("FileSystem", "rename"), /* @__PURE__ */ handleBadArgument("rename")); return (oldPath, newPath) => nodeRename(oldPath, newPath); })(); -var makeFileInfo = (stat) => try_2({ +var makeFileInfo = (stat, method = "stat") => try_2({ try: () => ({ type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown", mtime: fromNullishOr(stat.mtime), @@ -12031,14 +12168,16 @@ var makeFileInfo = (stat) => try_2({ blksize: stat.blksize !== undefined ? some2(bytes(stat.blksize)) : none2(), blocks: fromNullishOr(stat.blocks) }), - catch: handleBadArgument("stat") + catch: handleBadArgument(method) }); -var stat2 = /* @__PURE__ */ (() => { - const nodeStat = /* @__PURE__ */ effectify(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat")); +var statFactory = (method, nodeStatFn) => { + const nodeStat = effectify(nodeStatFn, handleErrnoException("FileSystem", method), handleBadArgument(method)); return (path) => flatMap3(nodeStat(path, { bigint: true - }), makeFileInfo); -})(); + }), (stat) => makeFileInfo(stat, method)); +}; +var stat2 = /* @__PURE__ */ statFactory("stat", NFS.stat); +var lstat2 = /* @__PURE__ */ statFactory("lstat", NFS.lstat); var symlink2 = /* @__PURE__ */ (() => { const nodeSymlink = /* @__PURE__ */ effectify(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink")); return (target, path) => nodeSymlink(target, path); @@ -12121,6 +12260,7 @@ var makeFileSystem = /* @__PURE__ */ map5(/* @__PURE__ */ serviceOption2(WatchBa copyFile: copyFile2, glob: glob2, link: link3, + lstat: lstat2, makeDirectory, makeTempDirectory, makeTempDirectoryScoped, @@ -12260,9 +12400,6 @@ var make27 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readline.emitKeypressEvents(stdin, rl); rl.on("line", onLine); rl.once("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(true); - } return { rl, onClose, @@ -12276,9 +12413,6 @@ var make27 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readlineActive = false; rl.off("line", onLine); rl.off("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(false); - } rl.close(); if (inputEnded) { endUnsafe(lines); @@ -12286,6 +12420,14 @@ var make27 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu })), idleTimeToLive: "10 millis" }); + const setRawMode = (enabled) => sync3(() => { + if (stdin.isTTY) + stdin.setRawMode(enabled); + }); + const rawModeRef = yield* make14({ + acquire: acquireRelease2(setRawMode(true), () => setRawMode(false)), + idleTimeToLive: "10 millis" + }); const columns = sync3(() => stdout.columns ?? 0); const rows = sync3(() => stdout.rows ?? 0); const readInput = gen2(function* () { @@ -12320,6 +12462,7 @@ var make27 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu handleEnd(); } else { yield* get3(rlRef); + yield* get3(rawModeRef); stdin.once("end", handleEnd); } return queue; @@ -12439,7 +12582,7 @@ class CommandError extends TaggedError3()("CommandError", { }) { } var error = (command, cause) => new CommandError({ command, exitCode: -1, stderr: String(cause) }); -var collectText = (stream) => stream.pipe(decodeText(), runFold2(() => "", (all, chunk) => all + chunk)); +var collectText = (stream) => stream.pipe(decodeText2(), runFold2(() => "", (all, chunk) => all + chunk)); var retainedStderrLength = 16 * 1024; class Service3 extends Service()("@timmo001/workflows/CommandExecutor") { @@ -12492,8 +12635,8 @@ var layer15 = effect(Service3, gen2(function* () { stdin: "inherit" })); let stderrTail = ""; - const stdout = handle.stdout.pipe(decodeText(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); - const stderr = handle.stderr.pipe(decodeText(), runForEach2((chunk) => sync3(() => { + const stdout = handle.stdout.pipe(decodeText2(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); + const stderr = handle.stderr.pipe(decodeText2(), runForEach2((chunk) => sync3(() => { process.stderr.write(chunk); stderrTail = `${stderrTail}${chunk}`.slice(-retainedStderrLength); }))); diff --git a/.github/actions/build-arch-package/dist/index.js b/.github/actions/build-arch-package/dist/index.js index 2061198c..fad5cf9c 100644 --- a/.github/actions/build-arch-package/dist/index.js +++ b/.github/actions/build-arch-package/dist/index.js @@ -788,6 +788,10 @@ function assignProperty(self, key, value) { } } function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } for (const key of Reflect.ownKeys(source)) { if (Object.prototype.propertyIsEnumerable.call(source, key)) { assignProperty(self, key, source[key]); @@ -878,7 +882,7 @@ class CauseImpl { toJSON() { return { _id: "Cause", - failures: this.reasons.map((f) => f.toJSON()) + reasons: this.reasons.map((f) => f.toJSON()) }; } toString() { @@ -1657,9 +1661,21 @@ var bigint2 = /* @__PURE__ */ BigInt(2); var bigint10 = /* @__PURE__ */ BigInt(10); var bigint1e3 = /* @__PURE__ */ BigInt(1000); var bigint1e6 = /* @__PURE__ */ BigInt(1e6); +var bigint1e9 = /* @__PURE__ */ BigInt(1e9); +var bigintNanosPerMinute = /* @__PURE__ */ BigInt(60000000000); +var bigintNanosPerHour = /* @__PURE__ */ BigInt(3600000000000); +var bigintNanosPerDay = /* @__PURE__ */ BigInt(86400000000000); +var bigintNanosPerWeek = /* @__PURE__ */ BigInt(604800000000000); var roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input))); var roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6); var fromNanosNumber = (nanos) => make3(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos); +var nanosToUnit = (nanos, divisor) => { + const value = Number(nanos); + if (Number.isFinite(value)) + return value / divisor; + const scale = BigInt(divisor); + return Number(nanos / scale) + Number(nanos % scale) / divisor; +}; var parseNanos = (input, scale) => { const decimalIndex = input.indexOf("."); if (decimalIndex === -1) @@ -1675,6 +1691,13 @@ var divideTiesAwayFromZero = (numerator, denominator) => { const rounded = absolute / denominator + (absolute % denominator * bigint2 >= denominator ? bigint1 : bigint0); return numerator < bigint0 ? -rounded : rounded; }; +var fromMillisString = (input, scale) => { + const millis = Number(input) * scale; + if (!Number.isFinite(millis)) + return make3(millis); + const nanos = parseNanos(input, BigInt(scale) * bigint1e6); + return make3(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos); +}; var DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; var fromInputUnsafe = (input) => { switch (typeof input) { @@ -1699,26 +1722,25 @@ var fromInputUnsafe = (input) => { if (unit === "micro" || unit === "micros") { return nanos(parseNanos(valueStr, bigint1e3)); } - const value = Number(valueStr); switch (unit) { case "milli": case "millis": - return millis(value); + return fromMillisString(valueStr, 1); case "second": case "seconds": - return seconds(value); + return fromMillisString(valueStr, 1000); case "minute": case "minutes": - return minutes(value); + return fromMillisString(valueStr, 60000); case "hour": case "hours": - return hours(value); + return fromMillisString(valueStr, 3600000); case "day": case "days": - return days(value); + return fromMillisString(valueStr, 86400000); case "week": case "weeks": - return weeks(value); + return fromMillisString(valueStr, 604800000); } break; } @@ -1740,7 +1762,8 @@ var fromInputUnsafe = (input) => { if (input[0] === Infinity || input[1] === Infinity) { return infinity; } - return fromNanosNumber(input[0] * 1e9 + input[1]); + const nanos = input[0] * 1e9 + input[1]; + return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make3(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos); } const obj = input; let millis = 0; @@ -1756,13 +1779,42 @@ var fromInputUnsafe = (input) => { millis += obj.seconds * 1000; if (obj.milliseconds) millis += obj.milliseconds; - if (!obj.microseconds && !obj.nanoseconds) - return make3(millis); - return fromNanosNumber(millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0)); + if (!obj.microseconds && !obj.nanoseconds) { + if (!Number.isFinite(millis)) + return make3(millis); + const exact = sumObjectNanos(obj); + return exact === undefined || BigInt(millis) * bigint1e6 === exact ? make3(millis) : make3(exact); + } + const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0); + const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : undefined; + return exact === undefined ? fromNanosNumber(nanos) : make3(exact); } } return invalid(input); }; +var isIntegerOrUnset = (n) => !n || Number.isInteger(n); +var sumObjectNanos = (obj) => { + if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds)) + return; + let nanos = bigint0; + if (obj.weeks) + nanos += BigInt(obj.weeks) * bigintNanosPerWeek; + if (obj.days) + nanos += BigInt(obj.days) * bigintNanosPerDay; + if (obj.hours) + nanos += BigInt(obj.hours) * bigintNanosPerHour; + if (obj.minutes) + nanos += BigInt(obj.minutes) * bigintNanosPerMinute; + if (obj.seconds) + nanos += BigInt(obj.seconds) * bigint1e9; + if (obj.milliseconds) + nanos += BigInt(obj.milliseconds) * bigint1e6; + if (obj.microseconds) + nanos += BigInt(obj.microseconds) * bigint1e3; + if (obj.nanoseconds) + nanos += BigInt(obj.nanoseconds); + return nanos; +}; var invalid = (input) => { throw new Error(`Invalid Input: ${input}`); }; @@ -1871,14 +1923,9 @@ var infinity = /* @__PURE__ */ make3(Infinity); var negativeInfinity = /* @__PURE__ */ make3(-Infinity); var nanos = (nanos) => make3(nanos); var millis = (millis) => make3(millis); -var seconds = (seconds) => make3(seconds * 1000); -var minutes = (minutes) => make3(minutes * 60000); -var hours = (hours) => make3(hours * 3600000); -var days = (days) => make3(days * 86400000); -var weeks = (weeks) => make3(weeks * 604800000); var toMillis = (self) => match3(fromInputUnsafe(self), { onMillis: identity, - onNanos: (nanos) => Number(nanos) / 1e6, + onNanos: (nanos) => nanosToUnit(nanos, 1e6), onInfinity: () => Infinity, onNegativeInfinity: () => -Infinity }); @@ -1960,7 +2007,7 @@ var setTimer = "setImmediate" in globalThis ? (f) => { const timer = setTimeout(f, 0); return () => clearTimeout(timer); }; -var setImmediate = (f) => { +var setImmediate2 = (f) => { try { return setTimer(f); } catch { @@ -2000,7 +2047,7 @@ class MixedScheduler { setImmediate; constructor(executionMode = "async", setImmediateFn) { this.executionMode = executionMode; - this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate2); } shouldYield(fiber) { return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; @@ -2014,7 +2061,7 @@ class MixedSchedulerDispatcher { tasks = /* @__PURE__ */ new PriorityBuckets; running = undefined; setImmediate; - constructor(setImmediateFn = setImmediate) { + constructor(setImmediateFn = setImmediate2) { this.setImmediate = setImmediateFn; } scheduleTask(task, priority) { @@ -2258,10 +2305,7 @@ class Interrupt extends ReasonBase { } } var causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); -var findFail = (self) => { - const reason = self.reasons.find(isFailReason); - return reason ? succeed2(reason) : fail2(self); -}; +var hasFails = (self) => self.reasons.some(isFailReason); var findError = (self) => { for (let i = 0;i < self.reasons.length; i++) { const reason = self.reasons[i]; @@ -2271,6 +2315,9 @@ var findError = (self) => { } return fail2(self); }; +var hasDies = (self) => self.reasons.some(isDieReason); +var causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +var findRecoverableError = (self) => hasDies(self) ? fail2(causeElectDefects(self)) : findError(self); var hasInterrupts = (self) => self.reasons.some(isInterruptReason); var hasInterruptsOnly = (self) => self.reasons.length > 0 && self.reasons.every(isInterruptReason); var causeMap = /* @__PURE__ */ dual(2, (self, f) => { @@ -2331,12 +2378,14 @@ var causePrettyErrors = (self, options) => { } return errors; }; -var causePrettyError = (original, annotations, options) => { +var causePrettyError = (original, annotations, options, seen = new Set) => { const kind = typeof original; let error; if (original && kind === "object") { + seen.add(original); + const cause = original.cause; error = new globalThis.Error(causePrettyMessage(original), { - cause: original.cause ? causePrettyError(original.cause) : undefined + cause: cause !== undefined && !seen.has(cause) ? causePrettyError(cause, undefined, undefined, seen) : undefined }); if (typeof original.name === "string") { error.name = original.name; @@ -2547,7 +2596,11 @@ class FiberImpl { } else if (this._asyncContext !== undefined) { const asyncContext = this._asyncContext; this._asyncContext = undefined; - return asyncContext.runInAsyncScope(this.evaluate, this, effect); + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } } else if (this._yielded !== undefined) { const yielded = this._yielded; this._yielded = undefined; @@ -2852,7 +2905,6 @@ var tryPromise = (options) => { } }, f.length !== 0); }; -var withFiberId = (f) => withFiber((fiber) => f(fiber.id)); var callbackOptions = /* @__PURE__ */ function() { const Proto = /* @__PURE__ */ makePrimitiveProto({ op: "Async", @@ -2873,9 +2925,9 @@ var callbackOptions = /* @__PURE__ */ function() { if (yielded !== false) return yielded; yielded = true; - fiber._yielded = () => { + fiber.yieldWith(() => { resumed = true; - }; + }); if (controller === undefined && onCancel === undefined) { return Yield; } @@ -3159,10 +3211,7 @@ var exitMap = /* @__PURE__ */ dual(2, (self, f) => self._tag === "Success" ? exi var exitMapError = /* @__PURE__ */ dual(2, (self, f) => { if (self._tag === "Success") return self; - const error = findError(self.cause); - if (isFailure2(error)) - return self; - return exitFail(f(error.success)); + return exitFailCause(causeMap(self.cause, f)); }); var exitZipRight = /* @__PURE__ */ dual(2, (self, that) => exitIsSuccess(self) ? that : self); var exitAsVoidAll = (exits) => { @@ -3226,7 +3275,7 @@ var catchCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(s const eb = filter(cause); return isFailure2(eb) ? failCause(eb.failure) : f(eb.success, cause); })); -var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findError, (e) => f(e))); +var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findRecoverableError, (e) => f(e))); var tapCause = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => andThen(f(cause), failCause(cause)))); var tapCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(self, (cause) => { const result = filter(cause); @@ -3237,7 +3286,7 @@ var tapCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(sel })); var tapError = /* @__PURE__ */ dual(2, (self, f) => tapCauseFilter(self, findError, (e) => f(e))); var catchIf = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, predicate, f, orElse) => catchCause(self, (cause) => { - const error = findError(cause); + const error = findRecoverableError(cause); if (isFailure2(error)) return failCause(error.failure); if (!predicate(error.success)) { @@ -3249,7 +3298,7 @@ var catchTag = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, k, f, or const pred = Array.isArray(k) ? (e) => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); return catchIf(self, pred, f, orElse); }); -var mapError = /* @__PURE__ */ dual(2, (self, f) => catch_(self, (error) => failSync(() => f(error)))); +var mapError = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => failCause(causeMap(cause, f)))); var orDie = (self) => catch_(self, die); var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { if (!options?.log) { @@ -3261,12 +3310,25 @@ var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) = const logEffect = logWithLevel(options.log === true ? undefined : options.log); return matchCauseEffect(self, { onFailure(cause) { - const failure = findFail(cause); - return isFailure2(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); }, onSuccess: (_) => void_ }); }); +var ignoreCause = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { + if (!options?.log) { + return matchCauseEffect(self, { + onFailure: (_) => void_, + onSuccess: (_) => void_ + }); + } + const logEffect = logWithLevel(options.log === true ? undefined : options.log); + return matchCauseEffect(self, { + onFailure: (cause) => options.message === undefined ? logEffect(cause) : logEffect(options.message, cause), + onSuccess: (_) => void_ + }); +}); var result = (self) => matchEager(self, { onFailure: fail2, onSuccess: succeed2 @@ -3301,16 +3363,16 @@ var makeMatch = (op, onFailure) => { return MatchImpl; }; var MatchImpl = /* @__PURE__ */ makeMatch("Match", function(cause, fiber) { - const fail = cause.reasons.find(isFailReason); - if (fail === undefined) - return failCause(cause); + const error = findRecoverableError(cause); + if (isFailure2(error)) + return failCause(error.failure); const handlers = this.payload; - return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(fail.error) : internalCall(() => handlers.onFailure(fail.error))); + return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))); }); var matchEffect = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, { onFailure: (cause) => { - const fail = cause.reasons.find(isFailReason); - return fail ? options.onFailure(fail.error) : failCause(cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.onFailure(error.success); }, onSuccess: options.onSuccess })); @@ -3319,9 +3381,9 @@ var matchEager = /* @__PURE__ */ dual(2, (self, options) => { if (effectIsExit(self)) { if (self._tag === "Success") return exitSucceed(options.onSuccess(self.value)); - const error = findError(self.cause); + const error = findRecoverableError(self.cause); if (isFailure2(error)) - return self; + return exitFailCause(error.failure); return exitSucceed(options.onFailure(error.success)); } return match4(self, options); @@ -3378,17 +3440,17 @@ var runFinalizer = (finalizer, exit_) => { return exitDie(defect); } }; -var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeCombine(exit_.cause, cause))); +var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); var scopeCloseFinalizers = /* @__PURE__ */ fnUntraced(function* (self, finalizers, exit_) { let exits = []; const fibers = []; - const arr = Array.from(finalizers.values()); + const arr = Array.from(finalizers); const parent = getCurrentFiber(); for (let i = arr.length - 1;i >= 0; i--) { - const finalizer = arr[i]; + const [key, finalizer] = arr[i]; if (self.strategy === "sequential") { exits.push(yield* exit(runFinalizer(finalizer, exit_))); - } else { + } else if (key !== parent) { fibers.push(forkUnsafe(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); } } @@ -3581,15 +3643,9 @@ var all = (arg, options) => { } else if (options?.discard) { return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options); } - return suspend(() => { - const out = {}; - return as(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => { - assignProperty(out, key, value); - }), { - discard: true, - concurrency: options?.concurrency - }), out); - }); + return suspend(() => map3(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => [key, value]), { + concurrency: options?.concurrency + }), Object.fromEntries)); }; var whileLoop = /* @__PURE__ */ makePrimitive({ op: "While", @@ -3728,7 +3784,7 @@ var iterateConcurrentImpl = (options) => { const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); if (reasons.length > 0) { const cause = causeFromReasons(reasons); - terminal = exitFailCause(terminal._tag === "Failure" ? causeCombine(terminal.cause, cause) : cause); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); } } } else { @@ -3810,14 +3866,13 @@ var forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterrupt } return child; }; +var fiberScopeFinalizer = (fiber) => () => withFiber((current) => current === fiber ? void_ : fiberInterrupt(fiber)); var forkIn = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, scope, options) => withFiber((parent) => { - const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + const fiber = scope.state._tag === "Closed" ? new FiberImpl(parent.context) : forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); if (!fiber._exit) { if (scope.state._tag !== "Closed") { - const key = {}; - const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); - scopeAddFinalizerUnsafe(scope, key, finalizer); - fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + scopeAddFinalizerUnsafe(scope, fiber, fiberScopeFinalizer(fiber)); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, fiber)); } else { fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); } @@ -3854,7 +3909,7 @@ var fiberRunIn = /* @__PURE__ */ dual(2, (self, scope) => { return self; } scopeRemoveFinalizerUnsafe(scope, self); - scopeAddFinalizerUnsafe(scope, self, () => fiberInterrupt(self)); + scopeAddFinalizerUnsafe(scope, self, fiberScopeFinalizer(self)); self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, self)); return self; }); @@ -4306,7 +4361,6 @@ var die2 = causeDie; var hasInterruptsOnly2 = hasInterruptsOnly; var map4 = causeMap; var squash = causeSquash; -var findError2 = findError; var isDone2 = isDone; var Done2 = Done; var done2 = done; @@ -4316,6 +4370,7 @@ var UnknownError2 = UnknownError; var succeed4 = exitSucceed; var failCause2 = exitFailCause; var fail5 = exitFail; +var interrupt2 = exitInterrupt; var void_2 = exitVoid; var isSuccess3 = exitIsSuccess; var isFailure3 = exitIsFailure; @@ -4500,8 +4555,8 @@ var mergeAllEffect = (layers, memoMap, scope) => { concurrency: layers.length }).pipe(map3((context) => mergeAll(...context))); }; -var mergeAll2 = (...layers) => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); -var provideWith = (self, that, f) => fromBuild((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); +var mergeAll2 = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +var provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); var provide2 = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, identity)); var provideMerge = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, (self, that) => merge(that, self))); @@ -4703,11 +4758,10 @@ var provideLayer = (self, layer, options) => scopedWith((scope) => flatMap2(opti var provide3 = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll2(...source) : source, options)); // node_modules/effect/dist/internal/schedule.js -var findErrorOnly = (cause) => cause.reasons.every(isFailReason) ? findError(cause) : fail2(cause); var retryOrElse = /* @__PURE__ */ dual(3, (self, policy, orElse) => flatMap2(toStepWithMetadata(policy), (step) => { let meta = CurrentMetadata.defaultValue(); let lastError; - const loop = catchCauseFilter(suspend(() => provideService(self, CurrentMetadata, meta)), findErrorOnly, (error) => { + const loop = catchCauseFilter(suspend(() => provideService(self, CurrentMetadata, meta)), findRecoverableError, (error) => { lastError = error; return flatMap2(step(error), (meta_) => { meta = meta_; @@ -4761,6 +4815,7 @@ var callback2 = callback; var never2 = never; var gen2 = gen; var fail6 = fail3; +var failSync2 = failSync; var failCause3 = failCause; var failCauseSync2 = failCauseSync; var die3 = die; @@ -4783,6 +4838,7 @@ var tapError2 = tapError; var tapCause2 = tapCause; var retry2 = retry; var ignore2 = ignore; +var ignoreCause2 = ignoreCause; var timeoutOrElse2 = timeoutOrElse; var sleep2 = sleep; var raceFirst2 = raceFirst; @@ -4800,7 +4856,7 @@ var ensuring2 = ensuring; var onError2 = onError; var onExitPrimitive2 = onExitPrimitive; var onExit2 = onExit; -var interrupt2 = interrupt; +var interrupt3 = interrupt; var uninterruptible2 = uninterruptible; var uninterruptibleMask2 = uninterruptibleMask; var forever3 = forever; @@ -4815,16 +4871,23 @@ var fn2 = fn; var clockWith2 = clockWith; var logError = /* @__PURE__ */ logWithLevel("Error"); var effectify = (fn, onError, onSyncError) => (...args) => callback2((resume) => { + let synchronous = true; + let pending; try { fn(...args, (err, result) => { - if (err) { - resume(onError ? suspend2(() => fail6(onError(err, args))) : fail6(err)); + const effect = err ? onError ? suspend2(() => fail6(onError(err, args))) : fail6(err) : succeed6(result); + if (synchronous) { + pending ??= effect; } else { - resume(succeed6(result)); + resume(effect); } }); } catch (err) { - resume(onSyncError ? fail6(onSyncError(err, args)) : die3(err)); + pending = onSyncError ? fail6(onSyncError(err, args)) : die3(err); + } + synchronous = false; + if (pending) { + resume(pending); } }); var mapEager2 = mapEager; @@ -5235,7 +5298,7 @@ var defaultLeafHook = (issue) => { } } }; -var defaultCheckHook = (issue) => findMessage(issue.issue) ?? findMessage(issue); +var defaultCheckHook = (issue) => findMessage(issue) ?? findMessage(issue.issue); function formatInput(issue) { return hasInput(issue) ? format(issue.input) : undefined; } @@ -5247,6 +5310,13 @@ function getExpectedMessage(expected, issue) { const input = formatInput(issue); return input === undefined ? `Expected ${expected}` : `Expected ${expected}, got ${input}`; } +function getFilterMessage(issue, checkHook) { + const message = checkHook(issue); + if (message !== undefined || issue.issue._tag !== "InvalidValue") + return message; + const expected = findExpected(issue.issue); + return expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); +} function formatCheck(check) { const expected = check.annotations?.expected; if (typeof expected === "string") @@ -5262,44 +5332,33 @@ function makeFormatterDefault() { return (issue) => formatIssue(issue, ""); } var defaultFormatter = /* @__PURE__ */ makeFormatterDefault(); -function formatIssue(issue, path) { +function formatIssue(issue, path, messageOverride) { let message; switch (issue._tag) { - case "Filter": { - const annotated = defaultCheckHook(issue); - if (annotated !== undefined) { - message = annotated; - } else { - if (issue.issue._tag !== "InvalidValue") { - return formatIssue(issue.issue, path); - } - const expected = findExpected(issue.issue); - message = expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); - } - break; - } + case "Filter": + return formatIssue(issue.issue, path, messageOverride ?? getFilterMessage(issue, defaultCheckHook)); case "Encoding": - return formatIssue(issue.issue, path); + return formatIssue(issue.issue, path, messageOverride); case "Pointer": - return formatIssue(issue.issue, path + formatPath(issue.path)); + return formatIssue(issue.issue, path + formatPath(issue.path), messageOverride); case "Composite": case "AnyOf": { if (issue._tag === "Composite" || issue.issues.length > 0) { - return issue.issues.map((issue) => formatIssue(issue, path)).join(` + return issue.issues.map((issue) => formatIssue(issue, path, messageOverride)).join(` `); } - message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); + message = messageOverride ?? findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); break; } default: - message = defaultLeafHook(issue); + message = messageOverride ?? defaultLeafHook(issue); break; } return path ? `${message} at ${path}` : message; } function findMessage(issue) { - if (issue._tag === "Pointer") + if (issue._tag === "Pointer" || issue._tag === "Composite") return; if (issue._tag === "Encoding") return findMessage(issue.issue); @@ -5557,7 +5616,12 @@ var Declaration = class extends ASTNodeImpl { return (input, options) => { if (input === missing) return missingExit; - return (run ??= this.run(this.typeParameters))(input, this, options); + run ??= this.run(this.typeParameters); + try { + return run(input, this, options); + } catch (error) { + return die3(error); + } }; } _rebuild(recur, checks, encodingChecks, run, encodingRun) { @@ -5766,7 +5830,7 @@ var Arrays = class extends ASTNodeImpl { input, len, tailThreshold: Math.max(elementLen, len - tailLen), - output: new globalThis.Array(len), + output: [], issues: undefined, options }; @@ -5875,7 +5939,7 @@ var wrapPropertyKeyIssue = (s, ast, key, exit) => { return fail5(new Composite(ast, [pointer], s.input, s.options)); } }; -var FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?"; +var FINITE_PATTERN = "[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?"; function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) { let stringKeys; let symbolKeys; @@ -6114,9 +6178,15 @@ var Objects = class extends ASTNodeImpl { if (indexCount) return makeFallback(); let fallback; - const resume = (state, index, pending) => { + const resume = (snapshot, index, pending) => { const property = properties[index]; return flatMap3(exit2(pending), (exit) => { + const state = { + ...snapshot, + out: { + ...snapshot.out + } + }; const terminal = stepProperty(state, property, exit); if (terminal) return terminal; @@ -6246,9 +6316,6 @@ function struct(fields, checks, annotations) { function getAST(self) { return self.ast; } -function tuple(elements, checks = undefined) { - return new Arrays(false, elements.map((e) => e.ast), [], undefined, checks); -} function union(members, options, checks) { return new Union(members.map(getAST), options, undefined, checks); } @@ -7159,6 +7226,16 @@ var unknownToStringTree = /* @__PURE__ */ new Link(StringTree, /* @__PURE__ */ p // node_modules/effect/dist/internal/schema/interpreter.js var flatMapTransformation = (result, current, f) => result === sameExit ? f(current) : flatMapEager2(result, f); function compileTransformation(transformation) { + const apply = compileTransformationUnsafe(transformation); + return (result, current, options) => { + try { + return apply(result, current, options); + } catch (error) { + return die3(error); + } + }; +} +function compileTransformationUnsafe(transformation) { if (transformation._tag === "Middleware") { return (result, current, options) => { const transformed = result === sameExit ? transformation.decode(succeed7(toOption(current)), options) : transformation.decode(mapEager2(result, toOption), options); @@ -7234,53 +7311,57 @@ function compile(ast, compile, compileField, base, specialize) { let encodingParsers; const parseChecks = (input, options) => { let result = parser(input, options); - if (encodingChecks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const output = result === sameExit ? input : result[args]; - if (input !== missing && output !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, input, options)); + try { + if (encodingChecks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const output = result === sameExit ? input : result[args]; + if (input !== missing && output !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + result = fail6(new Composite(ast, issues, input, options)); + } } } - } - } else { - result = flatMap3(result, (value) => { - if (input !== missing && value !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - return fail6(new Composite(ast, issues, input, options)); + } else { + result = flatMap3(result, (value) => { + if (input !== missing && value !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, input, options)); + } } - } - return succeed6(value); - }); - } - } - if (checks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const value = result === sameExit ? input : result[args]; - if (value === missing) - return result; - const issues = collectIssues(checks, value, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, value, options)); - } + return succeed6(value); + }); } - } else { - result = flatMap3(result, (value) => { - if (value !== missing) { + } + if (checks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const value = result === sameExit ? input : result[args]; + if (value === missing) + return result; const issues = collectIssues(checks, value, undefined, ast, options); if (issues) { - return fail6(new Composite(ast, issues, value, options)); + result = fail6(new Composite(ast, issues, value, options)); } } - return succeed6(value); - }); + } else { + result = flatMap3(result, (value) => { + if (value !== missing) { + const issues = collectIssues(checks, value, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, value, options)); + } + } + return succeed6(value); + }); + } } + return result; + } catch (error) { + return die3(error); } - return result; }; const parseLocal = specialize === undefined ? parseChecks : specialize(parseChecks); if (!links) { @@ -7754,18 +7835,6 @@ function Record(key, value) { value }); } -function makeTuple(ast, elements) { - return make8(ast, { - elements, - mapElements(f, options) { - const elements = f(this.elements); - return makeTuple(tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements); - } - }); -} -function Tuple(elements) { - return makeTuple(tuple(elements), elements); -} var ArraySchema = /* @__PURE__ */ lambda((schema) => make8(new Arrays(false, [], [schema.ast]), { value: schema })); @@ -7942,16 +8011,23 @@ function isPattern2(regExp, annotations) { }); } function isBase64(annotations) { - const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - return isPattern2(regExp, { + const pattern = "^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"; + const regExp = /^[0-9a-zA-Z+/]*={0,2}$/; + return makeFilter2((s) => s.length % 4 === 0 && regExp.test(s), { expected: "a base64 encoded string", representation: { id: "effect/schema/isBase64", payload: null }, toJsonSchema: () => ({ - pattern: regExp.source + pattern }), + arbitraryConstraint: { + patterns: [{ + source: pattern, + flags: "" + }] + }, toCode: () => ({ runtime: "Schema.isBase64()" }), @@ -8139,47 +8215,6 @@ var File = /* @__PURE__ */ instanceOf(globalThis.File, { }) })) }); -var FormData2 = /* @__PURE__ */ instanceOf(globalThis.FormData, { - representation: { - id: "effect/schema/FormData", - payload: null - }, - toCode: () => ({ - runtime: `Schema.FormData`, - Type: `globalThis.FormData` - }), - expected: "FormData", - toCodecJson: () => link()(ArraySchema(Tuple([String4, Union2([Struct({ - _tag: tag("String"), - value: String4 - }), Struct({ - _tag: tag("File"), - value: File - })])])), transformEffect2({ - decode: (e) => { - const out = new globalThis.FormData; - for (const [key, entry] of e) { - out.append(key, entry.value); - } - return succeed6(out); - }, - encode: (formData) => { - return succeed6(globalThis.Array.from(formData.entries()).map(([key, value]) => { - if (typeof value === "string") { - return [key, { - _tag: "String", - value - }]; - } else { - return [key, { - _tag: "File", - value - }]; - } - })); - } - })) -}); var URLSearchParams2 = /* @__PURE__ */ instanceOf(globalThis.URLSearchParams, { representation: { id: "effect/schema/URLSearchParams", @@ -8295,13 +8330,16 @@ function makeClass(Inherited, identifier, struct2, annotations, proto) { } return out; } -function getClassTransformation(self) { - return new Transformation(transform((input) => new self(input, { +function makeClassTrusted(self, fields) { + return new self(fields, { "~payload": { token: payloadToken, - value: input + value: fields } - })), passthrough2()); + }); +} +function getClassTransformation(self) { + return new Transformation(transform((input) => makeClassTrusted(self, input)), passthrough2()); } function getClassTypeId(identifier) { return `~effect/Schema/Class/${identifier}`; @@ -8369,7 +8407,7 @@ function nominal() { } // node_modules/effect/dist/Fiber.js var join = fiberJoin; -var interrupt3 = fiberInterrupt; +var interrupt4 = fiberInterrupt; var getCurrent = getCurrentFiber; var runIn = fiberRunIn; @@ -8898,7 +8936,9 @@ var toTransform = (channel) => channel.transform; var asyncQueue = (scope, f, options) => make12({ capacity: options?.bufferSize, strategy: options?.strategy -}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope)))); +}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope, { + startImmediately: true +})))); var callbackArray = (f, options) => fromTransform((_, scope) => map5(asyncQueue(scope, f, options), takeAll2)); var suspend3 = (evaluate) => fromTransform((upstream, scope) => suspend2(() => toTransform(evaluate())(upstream, scope))); var fromIterator = (iterator) => fromPull(sync3(() => { @@ -8910,8 +8950,8 @@ var fromIterator = (iterator) => fromPull(sync3(() => { })); var succeed8 = (value) => fromEffect(succeed6(value)); var empty3 = /* @__PURE__ */ fromPull(/* @__PURE__ */ succeed6(/* @__PURE__ */ done2())); -var fail7 = (error) => fromPull(succeed6(fail6(error))); var failCause5 = (cause) => fromPull(failCause3(cause)); +var die4 = (defect) => failCause5(die2(defect)); var fromEffect = (effect) => fromPull(sync3(() => { let done = false; return suspend2(() => { @@ -9023,29 +9063,7 @@ var mapAccum = /* @__PURE__ */ dual((args) => isChannel(args[0]), (self, initial }); return pump; }))); -var catchCause3 = /* @__PURE__ */ dual(2, (self, f) => fromTransform((upstream, scope) => { - let forkedScope = forkUnsafe2(scope); - return map5(toTransform(self)(upstream, forkedScope), (pull) => { - let currentPull = pull.pipe(catchCause2((cause) => { - if (isDoneCause(cause)) { - return failCause3(cause); - } - const toClose = forkedScope; - forkedScope = forkUnsafe2(scope); - return close(toClose, failCause2(cause)).pipe(andThen2(toTransform(f(cause))(upstream, forkedScope)), flatMap3((childPull) => { - currentPull = childPull; - return childPull; - })); - })); - return suspend2(() => currentPull); - }); -})); -var catchCauseFilter2 = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause3(self, (cause) => { - const result = filter(cause); - return isFailure2(result) ? failCause5(result.failure) : f(result.success, cause); -})); -var catch_3 = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter2(self, findError2, (e) => f(e))); -var mapError4 = /* @__PURE__ */ dual(2, (self, f) => catch_3(self, (err) => fail7(f(err)))); +var mapError4 = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => succeed6(mapError2(pull, (err) => isDone2(err) ? err : f(err))))); var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { bufferSize = 16, concurrency, @@ -9054,7 +9072,7 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { const concurrencyN = concurrency === "unbounded" ? Number.MAX_SAFE_INTEGER : Math.max(1, concurrency); const semaphore = switch_ ? undefined : makeUnsafe5(concurrencyN); const doneLatch = yield* make9(true); - const fibers = new Set; + const fibers = new Map; const queue = yield* bounded(bufferSize); yield* addFinalizer2(forkedScope, shutdown(queue)); const pull = yield* toTransform(channels)(upstream, scope); @@ -9073,11 +9091,12 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { const childScope = forkUnsafe2(forkedScope); const childPull = yield* toTransform(channel)(upstream, childScope); while (fibers.size >= concurrencyN) { - const fiber = headUnsafe(fibers); + const [fiber, fiberScope] = headUnsafe(fibers); fibers.delete(fiber); if (fibers.size === 0) yield* doneLatch.open; - yield* interrupt3(fiber); + yield* interrupt4(fiber); + yield* ignoreCause2(close(fiberScope, interrupt2())); } const fiber = yield* childPull.pipe(tap2(() => yieldNow2), flatMap3((value) => offer(queue, value)), forever3({ disableYield: true @@ -9096,7 +9115,7 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { yield* doneLatch.open; })), forkChild2); doneLatch.closeUnsafe(); - fibers.add(fiber); + fibers.set(fiber, childScope); } }).pipe(catchCause2((cause) => { const halt = filterDone(cause); @@ -9220,6 +9239,18 @@ var splitLines = () => fromTransform((upstream, _scope) => sync3(() => { } return pullOrFlush; })); +var decodeText = (encoding, options) => fromTransform((upstream, _scope) => sync3(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + let pull = upstream.pipe(map5(map2((bytes) => decoder.decode(bytes, streamOptions))), catchDone((leftover) => { + pull = done2(leftover); + const last = decoder.decode(); + return last.length > 0 ? succeed6(of(last)) : pull; + })); + return suspend2(() => pull); +})); var pipeTo = /* @__PURE__ */ dual(2, (self, that) => fromTransform((upstream, scope) => flatMap3(toTransform(self)(upstream, scope), (upstream) => toTransform(that)(upstream, scope)))); var unwrap = (channel) => fromTransform((upstream, scope) => { let pull; @@ -9379,19 +9410,19 @@ var make13 = (options) => withFiber2((fiber) => { if (state._tag === "Acquired") return close(state.scope, void_2); if (state._tag === "Acquiring") - return interrupt3(state.fiber); + return interrupt4(state.fiber); return void_3; }), ref); }); var getState = (self, restore) => { switch (self.state._tag) { case "Closed": { - return interrupt2; + return interrupt3; } case "Acquired": { const state = self.state; state.refCount++; - return state.fiber ? as2(interrupt3(state.fiber), state) : succeed6(state); + return state.fiber ? as2(interrupt4(state.fiber), state) : succeed6(state); } case "Acquiring": { const state = self.state; @@ -9409,7 +9440,7 @@ var getState = (self, restore) => { const scope = makeUnsafe3(); const acquire = provideContext2(self.acquire, add(self.context, Scope, scope)).pipe(flatMap3((value) => { if (self.state !== acquiring) { - return interrupt2; + return interrupt3; } const state = { _tag: "Acquired", @@ -9442,7 +9473,7 @@ var awaitAcquiring = (self, acquiring, restore) => onExit2(restore(join(acquirin if (--acquiring.awaiters > 0 || self.state !== acquiring) return void_3; self.state = stateEmpty; - return interrupt3(acquiring.fiber); + return interrupt4(acquiring.fiber); }); var get2 = (self_) => { const self = self_; @@ -9489,7 +9520,13 @@ var toChannel2 = (stream) => stream.channel; var callback3 = (f, options) => fromChannel3(callbackArray(f, options)); var empty4 = /* @__PURE__ */ fromChannel3(empty3); var succeed9 = (value) => fromChannel3(succeed8(of(value))); -var suspend4 = (stream) => fromChannel3(suspend3(() => stream().channel)); +var suspend4 = (stream) => { + const suspended = fromChannel3(suspend3(() => stream().channel)); + suspendedStreams.set(suspended, stream); + return suspended; +}; +var suspendedStreams = /* @__PURE__ */ new WeakMap; +var die6 = (defect) => fromChannel3(die4(defect)); var unwrap3 = (effect) => fromChannel3(unwrap(map5(effect, toChannel2))); var map8 = /* @__PURE__ */ dual(2, (self, f) => suspend4(() => { let i = 0; @@ -9507,10 +9544,21 @@ function* concatChannels(self, that) { while (stack.length > 0) { const stream = stack.pop(); const parts = concatParts.get(stream); - if (parts === undefined) - yield stream.channel; - else + if (parts !== undefined) { stack.push(parts[1], parts[0]); + continue; + } + const evaluate = suspendedStreams.get(stream); + if (evaluate === undefined) { + yield stream.channel; + continue; + } + try { + stack.push(evaluate()); + } catch (defect) { + stack.push(die6(defect)); + } + yield empty3; } } var merge3 = /* @__PURE__ */ dual((args) => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel3(merge2(toChannel2(self), toChannel2(that), options))); @@ -9543,12 +9591,7 @@ var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (up }); return suspend2(() => done ? done : pull); }))); -var decodeText = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => suspend4(() => { - const decoder = new TextDecoder(options?.encoding); - return map8(self, (chunk) => decoder.decode(chunk, { - stream: true - })); -})); +var decodeText2 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => self.channel.pipe(pipeTo(decodeText(options?.encoding)), fromChannel3)); var splitLines2 = (self) => self.channel.pipe(pipeTo(splitLines()), fromChannel3); var run2 = /* @__PURE__ */ dual(2, (self, sink) => scopedWith2((scope) => toPullScoped(self.channel, scope).pipe(flatMap3((upstream) => sink.transform(upstream, scope)), map5(([a]) => a)))); var runCollect = (self) => runFold(self.channel, () => [], (acc, chunk) => { @@ -9674,10 +9717,14 @@ var ulidString = (timestampMillis, bytes) => { }; // node_modules/effect/dist/internal/uuid.js -var hex = (byte) => byte.toString(16).padStart(2, "0"); +var hex = /* @__PURE__ */ Array.from({ + length: 256 +}, (_, byte) => byte.toString(16).padStart(2, "0")); var stringify = (bytes) => { - const segments = [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)]; - return segments.map((segment) => Array.from(segment, hex).join("")).join("-"); + if (bytes.length < 16) { + return [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)].map((segment) => Array.from(segment, (byte) => hex[byte]).join("")).join("-"); + } + return hex[bytes[0]] + hex[bytes[1]] + hex[bytes[2]] + hex[bytes[3]] + "-" + hex[bytes[4]] + hex[bytes[5]] + "-" + hex[bytes[6]] + hex[bytes[7]] + "-" + hex[bytes[8]] + hex[bytes[9]] + "-" + hex[bytes[10]] + hex[bytes[11]] + hex[bytes[12]] + hex[bytes[13]] + hex[bytes[14]] + hex[bytes[15]]; }; var randomBytes = () => globalThis.crypto.getRandomValues(new Uint8Array(16)); function v4Bytes(bytes = randomBytes()) { @@ -9933,23 +9980,26 @@ var defaultTeardown = (exit, onExit) => { return onExit(getErrorExitCode(squash(exit.cause))); }; var makeRunMain = (f) => dual((args) => isEffect2(args[0]), (effect, options) => { - const fiber = options?.disableErrorReporting === true ? runFork2(effect) : runFork2(tapCause2(effect, (cause) => { + const main = options?.disableErrorReporting === true ? effect : tapCause2(effect, (cause) => { if (hasInterruptsOnly2(cause)) return void_3; const isReported = getErrorReported(squash(cause)); return isReported ? logError(cause) : void_3; - })); - try { - const keepAlive = globalThis.setInterval(constVoid, 2147483647); - fiber.addObserver(() => { - clearInterval(keepAlive); - }); - } catch {} - const teardown = options?.teardown ?? defaultTeardown; - return f({ - fiber, - teardown }); + const teardown = options?.teardown ?? defaultTeardown; + runFork2(withFiber2((fiber) => { + try { + const keepAlive = globalThis.setInterval(constVoid, 2147483647); + fiber.addObserver(() => { + clearInterval(keepAlive); + }); + } catch {} + f({ + fiber, + teardown + }); + return main; + })); }); var errorExitCode = "~effect/Runtime/errorExitCode"; var getErrorExitCode = (u) => { @@ -10013,7 +10063,7 @@ var makeHandle = (params) => Object.setPrototypeOf({ ...params }, HandleProto); var make21 = (spawn) => { - const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); + const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText2(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); const streamLines = (command, options) => splitLines2(streamString(command, options)); return ChildProcessSpawner.of({ spawn, @@ -10261,11 +10311,11 @@ var layer = (defaults = {}) => effect(Gh, gen2(function* () { let stdoutTruncated = false; let stderr = ""; let stderrTruncated = false; - const output = merge3(handle.stdout.pipe(decodeText(), map8((text) => { + const output = merge3(handle.stdout.pipe(decodeText2(), map8((text) => { stdoutTruncated ||= stdout.length + text.length > outputLimit; stdout = (stdout + text).slice(-outputLimit); return GhChunk.cases.Stdout.make({ text }); - })), handle.stderr.pipe(decodeText(), map8((text) => { + })), handle.stderr.pipe(decodeText2(), map8((text) => { stderrTruncated ||= stderr.length + text.length > outputLimit; stderr = (stderr + text).slice(-outputLimit); return GhChunk.cases.Stderr.make({ text }); @@ -10512,6 +10562,7 @@ var handleErrnoException = (module, method) => (err, [path]) => { reason = "NotFound"; break; case "EACCES": + case "EPERM": reason = "PermissionDenied"; break; case "EEXIST": @@ -10540,66 +10591,149 @@ var handleErrnoException = (module, method) => (err, [path]) => { }); }; +// node_modules/@effect/platform-node-shared/dist/NodeSink.js +import { finished } from "node:stream"; + +// node_modules/@effect/platform-node-shared/dist/internal/stream.js +var destroyStream = (stream, cleanup, onDestroyed) => { + if (!("closed" in stream)) { + cleanup(); + onDestroyed?.(); + return; + } + const onDone = () => { + clearImmediate(immediate); + stream.off("error", onDone); + stream.off("close", onDone); + onDestroyed?.(); + }; + const onClosed = () => { + if (stream.closed) { + onDone(); + } else { + immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + } + }; + let immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + stream.once("error", onDone); + stream.once("close", onDone); + cleanup(); + if (!stream.closed) { + stream.destroy(); + } +}; + // node_modules/@effect/platform-node-shared/dist/NodeSink.js var fromWritable = (options) => fromChannel2(mapDone(fromWritableChannel(options), (_) => [_])); var fromWritableChannel = (options) => fromTransform((pull) => { const writable = options.evaluate(); - return succeed6(pullIntoWritable({ + const write = pullIntoWritable({ ...options, writable, pull - })); -}); -var pullIntoWritable = (options) => options.pull.pipe(flatMap3((chunk) => { - let i = 0; - return callback2((resume) => { - let cancelled = false; - const loop = () => { - for (;i < chunk.length; ) { - if (cancelled) { - return; - } - const success = options.writable.write(chunk[i++], options.encoding); - if (!success) { - if (!cancelled) { - options.writable.once("drain", loop); + }); + return succeed6(options.endOnDone === false ? write : onError2(write, (cause) => isDoneCause(cause) ? void_3 : releaseWritable(writable))); +}); +var releaseWritable = (writable) => callback2((resume) => { + const onDestroyed = () => resume(void_3); + if (writable.closed) { + const cleanup = finished(writable, { + readable: false + }, () => { + cleanup(); + onDestroyed(); + }); + } else { + destroyStream(writable, constVoid, onDestroyed); + } +}); +var pullIntoWritable = (options) => withFiber2((fiber) => { + const dispatcher = fiber.currentDispatcher; + const completion = makeUnsafe2(); + const failure = makeUnsafe2(); + const onError = (error) => doneUnsafe(failure, failSync2(() => options.onError(error))); + let errorEmitted = false; + const onStreamError = (error) => { + errorEmitted = true; + onError(error); + }; + options.writable.on("error", onStreamError); + const cleanup = finished(options.writable, { + readable: false + }, (error) => { + if (error) { + onError(error); + } else { + doneUnsafe(completion, void_3); + } + }); + return options.pull.pipe(flatMap3((chunk) => { + let i = 0; + return callback2((resume) => { + let cancelled = false; + const onFinish = () => dispatcher.scheduleTask(loop, 0); + const loop = () => { + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + for (;i < chunk.length; ) { + if (cancelled) { + return; + } + const success = options.writable.write(chunk[i++], options.encoding, (error) => { + if (!error) + return; + if (options.writable.closed) { + onError(error); + } else { + dispatcher.scheduleTask(() => onError(error), 0); + } + }); + if (!success) { + if (!cancelled) { + options.writable.once("drain", loop); + options.writable.once("finish", onFinish); + } + return; } - return; } - } - if (!cancelled) { - resume(void_3); - } - }; - loop(); - return sync3(() => { - cancelled = true; - options.writable.off("drain", loop); + if (!cancelled) { + resume(void_3); + } + }; + loop(); + return sync3(() => { + cancelled = true; + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + }); }); - }); -}), forever3({ - disableYield: true -}), options.endOnDone !== false ? catchDone((_) => { - if ("closed" in options.writable && options.writable.closed) { - return done2(_); - } - return callback2((resume) => { - const onFinish = () => resume(done2(_)); - options.writable.once("finish", onFinish); + }), forever3({ + disableYield: true + }), options.endOnDone !== false ? catchDone((_) => { options.writable.end(); - return sync3(() => { - options.writable.off("finish", onFinish); - }); - }); -}) : identity, raceFirst2(callback2((resume) => { - const onError = (error) => resume(fail6(options.onError(error))); - options.writable.once("error", onError); - return sync3(() => { - options.writable.off("error", onError); - }); -}))); + return andThen2(_await(completion), done2(_)); + }) : identity, raceFirst2(_await(failure)), ensuring2(sync3(() => { + cleanup(); + const removeErrorListener = () => { + options.writable.off("error", onStreamError); + options.writable.off("error", removeErrorListener); + options.writable.off("close", removeErrorListener); + }; + if (options.writable.errored && !options.writable.closed && !errorEmitted) { + options.writable.once("error", removeErrorListener); + options.writable.once("close", removeErrorListener); + } else { + removeErrorListener(); + } + }))); +}); // node_modules/@effect/platform-node-shared/dist/NodeStream.js +import { finished as finished2, Readable } from "node:stream"; var fromReadable = (options) => fromChannel3(fromReadableChannel(options)); var fromReadableChannel = (options) => fromTransform((_, scope) => readableToPullUnsafe({ scope, @@ -10616,17 +10750,14 @@ var readableToPullUnsafe = (options) => { function onReadable() { latch.openUnsafe(); } - function onError(error) { - exit.current = fail5(options.onError(error)); - latch.openUnsafe(); - } - function onEnd() { - exit.current = fail5(Done2()); - latch.openUnsafe(); - } readable.on("readable", onReadable); - readable.once("error", onError); - readable.once("end", onEnd); + const cleanup = finished2(readable, { + readable: true, + writable: false + }, (error) => { + exit.current ??= fail5(error ? options.onError(error) : Done2()); + latch.openUnsafe(); + }); const pull = suspend2(function loop() { let item = options.readable.read(options.chunkSize); if (item === null) { @@ -10650,10 +10781,10 @@ var readableToPullUnsafe = (options) => { }); return as2(addFinalizer2(options.scope, sync3(() => { readable.off("readable", onReadable); - readable.off("error", onError); - readable.off("end", onEnd); - if (closeOnDone && "closed" in options.readable && !options.readable.closed) { - options.readable.destroy(); + if (closeOnDone) { + destroyStream(readable, cleanup); + } else { + cleanup(); } })), pull); }; @@ -10978,6 +11109,7 @@ var make23 = /* @__PURE__ */ gen2(function* () { const signalGroup = (signal) => killProcessGroup(command, childProcess, signal).pipe(catch_2(() => killProcess(command, childProcess, signal))); yield* signalGroup(options?.killSignal ?? "SIGTERM"); if (isUndefined(options?.forceKillAfter)) { + yield* _await(exitSignal); yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis); } else { yield* awaitProcessExit(childProcess, exitSignal, toMillis(options.forceKillAfter)); @@ -11571,14 +11703,14 @@ var readLink = /* @__PURE__ */ (() => { return (path) => nodeReadLink(path); })(); var realPath = /* @__PURE__ */ (() => { - const nodeRealPath = /* @__PURE__ */ effectify(NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); + const nodeRealPath = /* @__PURE__ */ effectify(process.platform === "win32" ? NFS.realpath.native : NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); return (path) => nodeRealPath(path); })(); var rename2 = /* @__PURE__ */ (() => { const nodeRename = /* @__PURE__ */ effectify(NFS.rename, /* @__PURE__ */ handleErrnoException("FileSystem", "rename"), /* @__PURE__ */ handleBadArgument("rename")); return (oldPath, newPath) => nodeRename(oldPath, newPath); })(); -var makeFileInfo = (stat) => try_2({ +var makeFileInfo = (stat, method = "stat") => try_2({ try: () => ({ type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown", mtime: fromNullishOr(stat.mtime), @@ -11595,14 +11727,16 @@ var makeFileInfo = (stat) => try_2({ blksize: stat.blksize !== undefined ? some2(bytes(stat.blksize)) : none2(), blocks: fromNullishOr(stat.blocks) }), - catch: handleBadArgument("stat") + catch: handleBadArgument(method) }); -var stat2 = /* @__PURE__ */ (() => { - const nodeStat = /* @__PURE__ */ effectify(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat")); +var statFactory = (method, nodeStatFn) => { + const nodeStat = effectify(nodeStatFn, handleErrnoException("FileSystem", method), handleBadArgument(method)); return (path) => flatMap3(nodeStat(path, { bigint: true - }), makeFileInfo); -})(); + }), (stat) => makeFileInfo(stat, method)); +}; +var stat2 = /* @__PURE__ */ statFactory("stat", NFS.stat); +var lstat2 = /* @__PURE__ */ statFactory("lstat", NFS.lstat); var symlink2 = /* @__PURE__ */ (() => { const nodeSymlink = /* @__PURE__ */ effectify(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink")); return (target, path) => nodeSymlink(target, path); @@ -11685,6 +11819,7 @@ var makeFileSystem = /* @__PURE__ */ map5(/* @__PURE__ */ serviceOption2(WatchBa copyFile: copyFile2, glob: glob2, link: link3, + lstat: lstat2, makeDirectory, makeTempDirectory, makeTempDirectoryScoped, @@ -11824,9 +11959,6 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readline.emitKeypressEvents(stdin, rl); rl.on("line", onLine); rl.once("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(true); - } return { rl, onClose, @@ -11840,9 +11972,6 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readlineActive = false; rl.off("line", onLine); rl.off("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(false); - } rl.close(); if (inputEnded) { endUnsafe(lines); @@ -11850,6 +11979,14 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu })), idleTimeToLive: "10 millis" }); + const setRawMode = (enabled) => sync3(() => { + if (stdin.isTTY) + stdin.setRawMode(enabled); + }); + const rawModeRef = yield* make14({ + acquire: acquireRelease2(setRawMode(true), () => setRawMode(false)), + idleTimeToLive: "10 millis" + }); const columns = sync3(() => stdout.columns ?? 0); const rows = sync3(() => stdout.rows ?? 0); const readInput = gen2(function* () { @@ -11884,6 +12021,7 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu handleEnd(); } else { yield* get3(rlRef); + yield* get3(rawModeRef); stdin.once("end", handleEnd); } return queue; @@ -12003,7 +12141,7 @@ class CommandError extends TaggedError3()("CommandError", { }) { } var error = (command, cause) => new CommandError({ command, exitCode: -1, stderr: String(cause) }); -var collectText = (stream) => stream.pipe(decodeText(), runFold2(() => "", (all, chunk) => all + chunk)); +var collectText = (stream) => stream.pipe(decodeText2(), runFold2(() => "", (all, chunk) => all + chunk)); var retainedStderrLength = 16 * 1024; class Service3 extends Service()("@timmo001/workflows/CommandExecutor") { @@ -12056,8 +12194,8 @@ var layer15 = effect(Service3, gen2(function* () { stdin: "inherit" })); let stderrTail = ""; - const stdout = handle.stdout.pipe(decodeText(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); - const stderr = handle.stderr.pipe(decodeText(), runForEach2((chunk) => sync3(() => { + const stdout = handle.stdout.pipe(decodeText2(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); + const stderr = handle.stderr.pipe(decodeText2(), runForEach2((chunk) => sync3(() => { process.stderr.write(chunk); stderrTail = `${stderrTail}${chunk}`.slice(-retainedStderrLength); }))); diff --git a/.github/actions/build-python-pypi-release/dist/index.js b/.github/actions/build-python-pypi-release/dist/index.js index 85676e92..14017c1f 100644 --- a/.github/actions/build-python-pypi-release/dist/index.js +++ b/.github/actions/build-python-pypi-release/dist/index.js @@ -769,6 +769,10 @@ function assignProperty(self, key, value) { } } function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } for (const key of Reflect.ownKeys(source)) { if (Object.prototype.propertyIsEnumerable.call(source, key)) { assignProperty(self, key, source[key]); @@ -859,7 +863,7 @@ class CauseImpl { toJSON() { return { _id: "Cause", - failures: this.reasons.map((f) => f.toJSON()) + reasons: this.reasons.map((f) => f.toJSON()) }; } toString() { @@ -1610,9 +1614,21 @@ var bigint2 = /* @__PURE__ */ BigInt(2); var bigint10 = /* @__PURE__ */ BigInt(10); var bigint1e3 = /* @__PURE__ */ BigInt(1000); var bigint1e6 = /* @__PURE__ */ BigInt(1e6); +var bigint1e9 = /* @__PURE__ */ BigInt(1e9); +var bigintNanosPerMinute = /* @__PURE__ */ BigInt(60000000000); +var bigintNanosPerHour = /* @__PURE__ */ BigInt(3600000000000); +var bigintNanosPerDay = /* @__PURE__ */ BigInt(86400000000000); +var bigintNanosPerWeek = /* @__PURE__ */ BigInt(604800000000000); var roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input))); var roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6); var fromNanosNumber = (nanos) => make3(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos); +var nanosToUnit = (nanos, divisor) => { + const value = Number(nanos); + if (Number.isFinite(value)) + return value / divisor; + const scale = BigInt(divisor); + return Number(nanos / scale) + Number(nanos % scale) / divisor; +}; var parseNanos = (input, scale) => { const decimalIndex = input.indexOf("."); if (decimalIndex === -1) @@ -1628,6 +1644,13 @@ var divideTiesAwayFromZero = (numerator, denominator) => { const rounded = absolute / denominator + (absolute % denominator * bigint2 >= denominator ? bigint1 : bigint0); return numerator < bigint0 ? -rounded : rounded; }; +var fromMillisString = (input, scale) => { + const millis = Number(input) * scale; + if (!Number.isFinite(millis)) + return make3(millis); + const nanos = parseNanos(input, BigInt(scale) * bigint1e6); + return make3(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos); +}; var DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; var fromInputUnsafe = (input) => { switch (typeof input) { @@ -1652,26 +1675,25 @@ var fromInputUnsafe = (input) => { if (unit === "micro" || unit === "micros") { return nanos(parseNanos(valueStr, bigint1e3)); } - const value = Number(valueStr); switch (unit) { case "milli": case "millis": - return millis(value); + return fromMillisString(valueStr, 1); case "second": case "seconds": - return seconds(value); + return fromMillisString(valueStr, 1000); case "minute": case "minutes": - return minutes(value); + return fromMillisString(valueStr, 60000); case "hour": case "hours": - return hours(value); + return fromMillisString(valueStr, 3600000); case "day": case "days": - return days(value); + return fromMillisString(valueStr, 86400000); case "week": case "weeks": - return weeks(value); + return fromMillisString(valueStr, 604800000); } break; } @@ -1693,7 +1715,8 @@ var fromInputUnsafe = (input) => { if (input[0] === Infinity || input[1] === Infinity) { return infinity; } - return fromNanosNumber(input[0] * 1e9 + input[1]); + const nanos = input[0] * 1e9 + input[1]; + return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make3(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos); } const obj = input; let millis = 0; @@ -1709,13 +1732,42 @@ var fromInputUnsafe = (input) => { millis += obj.seconds * 1000; if (obj.milliseconds) millis += obj.milliseconds; - if (!obj.microseconds && !obj.nanoseconds) - return make3(millis); - return fromNanosNumber(millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0)); + if (!obj.microseconds && !obj.nanoseconds) { + if (!Number.isFinite(millis)) + return make3(millis); + const exact = sumObjectNanos(obj); + return exact === undefined || BigInt(millis) * bigint1e6 === exact ? make3(millis) : make3(exact); + } + const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0); + const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : undefined; + return exact === undefined ? fromNanosNumber(nanos) : make3(exact); } } return invalid(input); }; +var isIntegerOrUnset = (n) => !n || Number.isInteger(n); +var sumObjectNanos = (obj) => { + if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds)) + return; + let nanos = bigint0; + if (obj.weeks) + nanos += BigInt(obj.weeks) * bigintNanosPerWeek; + if (obj.days) + nanos += BigInt(obj.days) * bigintNanosPerDay; + if (obj.hours) + nanos += BigInt(obj.hours) * bigintNanosPerHour; + if (obj.minutes) + nanos += BigInt(obj.minutes) * bigintNanosPerMinute; + if (obj.seconds) + nanos += BigInt(obj.seconds) * bigint1e9; + if (obj.milliseconds) + nanos += BigInt(obj.milliseconds) * bigint1e6; + if (obj.microseconds) + nanos += BigInt(obj.microseconds) * bigint1e3; + if (obj.nanoseconds) + nanos += BigInt(obj.nanoseconds); + return nanos; +}; var invalid = (input) => { throw new Error(`Invalid Input: ${input}`); }; @@ -1824,14 +1876,9 @@ var infinity = /* @__PURE__ */ make3(Infinity); var negativeInfinity = /* @__PURE__ */ make3(-Infinity); var nanos = (nanos) => make3(nanos); var millis = (millis) => make3(millis); -var seconds = (seconds) => make3(seconds * 1000); -var minutes = (minutes) => make3(minutes * 60000); -var hours = (hours) => make3(hours * 3600000); -var days = (days) => make3(days * 86400000); -var weeks = (weeks) => make3(weeks * 604800000); var toMillis = (self) => match3(fromInputUnsafe(self), { onMillis: identity, - onNanos: (nanos) => Number(nanos) / 1e6, + onNanos: (nanos) => nanosToUnit(nanos, 1e6), onInfinity: () => Infinity, onNegativeInfinity: () => -Infinity }); @@ -1897,7 +1944,7 @@ var setTimer = "setImmediate" in globalThis ? (f) => { const timer = setTimeout(f, 0); return () => clearTimeout(timer); }; -var setImmediate = (f) => { +var setImmediate2 = (f) => { try { return setTimer(f); } catch { @@ -1937,7 +1984,7 @@ class MixedScheduler { setImmediate; constructor(executionMode = "async", setImmediateFn) { this.executionMode = executionMode; - this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate2); } shouldYield(fiber) { return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; @@ -1951,7 +1998,7 @@ class MixedSchedulerDispatcher { tasks = /* @__PURE__ */ new PriorityBuckets; running = undefined; setImmediate; - constructor(setImmediateFn = setImmediate) { + constructor(setImmediateFn = setImmediate2) { this.setImmediate = setImmediateFn; } scheduleTask(task, priority) { @@ -2195,10 +2242,7 @@ class Interrupt extends ReasonBase { } } var causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); -var findFail = (self) => { - const reason = self.reasons.find(isFailReason); - return reason ? succeed2(reason) : fail2(self); -}; +var hasFails = (self) => self.reasons.some(isFailReason); var findError = (self) => { for (let i = 0;i < self.reasons.length; i++) { const reason = self.reasons[i]; @@ -2208,6 +2252,9 @@ var findError = (self) => { } return fail2(self); }; +var hasDies = (self) => self.reasons.some(isDieReason); +var causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +var findRecoverableError = (self) => hasDies(self) ? fail2(causeElectDefects(self)) : findError(self); var hasInterrupts = (self) => self.reasons.some(isInterruptReason); var hasInterruptsOnly = (self) => self.reasons.length > 0 && self.reasons.every(isInterruptReason); var causeMap = /* @__PURE__ */ dual(2, (self, f) => { @@ -2268,12 +2315,14 @@ var causePrettyErrors = (self, options) => { } return errors; }; -var causePrettyError = (original, annotations, options) => { +var causePrettyError = (original, annotations, options, seen = new Set) => { const kind = typeof original; let error; if (original && kind === "object") { + seen.add(original); + const cause = original.cause; error = new globalThis.Error(causePrettyMessage(original), { - cause: original.cause ? causePrettyError(original.cause) : undefined + cause: cause !== undefined && !seen.has(cause) ? causePrettyError(cause, undefined, undefined, seen) : undefined }); if (typeof original.name === "string") { error.name = original.name; @@ -2484,7 +2533,11 @@ class FiberImpl { } else if (this._asyncContext !== undefined) { const asyncContext = this._asyncContext; this._asyncContext = undefined; - return asyncContext.runInAsyncScope(this.evaluate, this, effect); + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } } else if (this._yielded !== undefined) { const yielded = this._yielded; this._yielded = undefined; @@ -2782,7 +2835,6 @@ var tryPromise = (options) => { } }, f.length !== 0); }; -var withFiberId = (f) => withFiber((fiber) => f(fiber.id)); var callbackOptions = /* @__PURE__ */ function() { const Proto = /* @__PURE__ */ makePrimitiveProto({ op: "Async", @@ -2803,9 +2855,9 @@ var callbackOptions = /* @__PURE__ */ function() { if (yielded !== false) return yielded; yielded = true; - fiber._yielded = () => { + fiber.yieldWith(() => { resumed = true; - }; + }); if (controller === undefined && onCancel === undefined) { return Yield; } @@ -3088,10 +3140,7 @@ var exitMap = /* @__PURE__ */ dual(2, (self, f) => self._tag === "Success" ? exi var exitMapError = /* @__PURE__ */ dual(2, (self, f) => { if (self._tag === "Success") return self; - const error = findError(self.cause); - if (isFailure2(error)) - return self; - return exitFail(f(error.success)); + return exitFailCause(causeMap(self.cause, f)); }); var exitZipRight = /* @__PURE__ */ dual(2, (self, that) => exitIsSuccess(self) ? that : self); var exitAsVoidAll = (exits) => { @@ -3155,10 +3204,10 @@ var catchCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(s const eb = filter(cause); return isFailure2(eb) ? failCause(eb.failure) : f(eb.success, cause); })); -var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findError, (e) => f(e))); +var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findRecoverableError, (e) => f(e))); var tapCause = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => andThen(f(cause), failCause(cause)))); var catchIf = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, predicate, f, orElse) => catchCause(self, (cause) => { - const error = findError(cause); + const error = findRecoverableError(cause); if (isFailure2(error)) return failCause(error.failure); if (!predicate(error.success)) { @@ -3170,7 +3219,7 @@ var catchTag = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, k, f, or const pred = Array.isArray(k) ? (e) => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); return catchIf(self, pred, f, orElse); }); -var mapError = /* @__PURE__ */ dual(2, (self, f) => catch_(self, (error) => failSync(() => f(error)))); +var mapError = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => failCause(causeMap(cause, f)))); var orDie = (self) => catch_(self, die); var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { if (!options?.log) { @@ -3182,8 +3231,8 @@ var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) = const logEffect = logWithLevel(options.log === true ? undefined : options.log); return matchCauseEffect(self, { onFailure(cause) { - const failure = findFail(cause); - return isFailure2(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); }, onSuccess: (_) => void_ }); @@ -3222,16 +3271,16 @@ var makeMatch = (op, onFailure) => { return MatchImpl; }; var MatchImpl = /* @__PURE__ */ makeMatch("Match", function(cause, fiber) { - const fail = cause.reasons.find(isFailReason); - if (fail === undefined) - return failCause(cause); + const error = findRecoverableError(cause); + if (isFailure2(error)) + return failCause(error.failure); const handlers = this.payload; - return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(fail.error) : internalCall(() => handlers.onFailure(fail.error))); + return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))); }); var matchEffect = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, { onFailure: (cause) => { - const fail = cause.reasons.find(isFailReason); - return fail ? options.onFailure(fail.error) : failCause(cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.onFailure(error.success); }, onSuccess: options.onSuccess })); @@ -3240,9 +3289,9 @@ var matchEager = /* @__PURE__ */ dual(2, (self, options) => { if (effectIsExit(self)) { if (self._tag === "Success") return exitSucceed(options.onSuccess(self.value)); - const error = findError(self.cause); + const error = findRecoverableError(self.cause); if (isFailure2(error)) - return self; + return exitFailCause(error.failure); return exitSucceed(options.onFailure(error.success)); } return match4(self, options); @@ -3297,17 +3346,17 @@ var runFinalizer = (finalizer, exit_) => { return exitDie(defect); } }; -var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeCombine(exit_.cause, cause))); +var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); var scopeCloseFinalizers = /* @__PURE__ */ fnUntraced(function* (self, finalizers, exit_) { let exits = []; const fibers = []; - const arr = Array.from(finalizers.values()); + const arr = Array.from(finalizers); const parent = getCurrentFiber(); for (let i = arr.length - 1;i >= 0; i--) { - const finalizer = arr[i]; + const [key, finalizer] = arr[i]; if (self.strategy === "sequential") { exits.push(yield* exit(runFinalizer(finalizer, exit_))); - } else { + } else if (key !== parent) { fibers.push(forkUnsafe(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); } } @@ -3500,15 +3549,9 @@ var all = (arg, options) => { } else if (options?.discard) { return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options); } - return suspend(() => { - const out = {}; - return as(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => { - assignProperty(out, key, value); - }), { - discard: true, - concurrency: options?.concurrency - }), out); - }); + return suspend(() => map3(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => [key, value]), { + concurrency: options?.concurrency + }), Object.fromEntries)); }; var whileLoop = /* @__PURE__ */ makePrimitive({ op: "While", @@ -3647,7 +3690,7 @@ var iterateConcurrentImpl = (options) => { const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); if (reasons.length > 0) { const cause = causeFromReasons(reasons); - terminal = exitFailCause(terminal._tag === "Failure" ? causeCombine(terminal.cause, cause) : cause); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); } } } else { @@ -3725,14 +3768,13 @@ var forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterrupt } return child; }; +var fiberScopeFinalizer = (fiber) => () => withFiber((current) => current === fiber ? void_ : fiberInterrupt(fiber)); var forkIn = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, scope, options) => withFiber((parent) => { - const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + const fiber = scope.state._tag === "Closed" ? new FiberImpl(parent.context) : forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); if (!fiber._exit) { if (scope.state._tag !== "Closed") { - const key = {}; - const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); - scopeAddFinalizerUnsafe(scope, key, finalizer); - fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + scopeAddFinalizerUnsafe(scope, fiber, fiberScopeFinalizer(fiber)); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, fiber)); } else { fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); } @@ -3769,7 +3811,7 @@ var fiberRunIn = /* @__PURE__ */ dual(2, (self, scope) => { return self; } scopeRemoveFinalizerUnsafe(scope, self); - scopeAddFinalizerUnsafe(scope, self, () => fiberInterrupt(self)); + scopeAddFinalizerUnsafe(scope, self, fiberScopeFinalizer(self)); self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, self)); return self; }); @@ -4408,8 +4450,8 @@ var mergeAllEffect = (layers, memoMap, scope) => { concurrency: layers.length }).pipe(map3((context) => mergeAll(...context))); }; -var mergeAll2 = (...layers) => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); -var provideWith = (self, that, f) => fromBuild((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); +var mergeAll2 = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +var provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); var provide2 = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, identity)); var provideMerge = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, (self, that) => merge(that, self))); @@ -4480,6 +4522,7 @@ var void_3 = void_; var callback2 = callback; var gen2 = gen; var fail6 = fail3; +var failSync2 = failSync; var failCause3 = failCause; var failCauseSync2 = failCauseSync; var die3 = die; @@ -4529,16 +4572,23 @@ var fn2 = fn; var clockWith2 = clockWith; var logError = /* @__PURE__ */ logWithLevel("Error"); var effectify = (fn, onError, onSyncError) => (...args) => callback2((resume) => { + let synchronous = true; + let pending; try { fn(...args, (err, result) => { - if (err) { - resume(onError ? suspend2(() => fail6(onError(err, args))) : fail6(err)); + const effect = err ? onError ? suspend2(() => fail6(onError(err, args))) : fail6(err) : succeed6(result); + if (synchronous) { + pending ??= effect; } else { - resume(succeed6(result)); + resume(effect); } }); } catch (err) { - resume(onSyncError ? fail6(onSyncError(err, args)) : die3(err)); + pending = onSyncError ? fail6(onSyncError(err, args)) : die3(err); + } + synchronous = false; + if (pending) { + resume(pending); } }); var mapEager2 = mapEager; @@ -4949,7 +4999,7 @@ var defaultLeafHook = (issue) => { } } }; -var defaultCheckHook = (issue) => findMessage(issue.issue) ?? findMessage(issue); +var defaultCheckHook = (issue) => findMessage(issue) ?? findMessage(issue.issue); function formatInput(issue) { return hasInput(issue) ? format(issue.input) : undefined; } @@ -4961,6 +5011,13 @@ function getExpectedMessage(expected, issue) { const input = formatInput(issue); return input === undefined ? `Expected ${expected}` : `Expected ${expected}, got ${input}`; } +function getFilterMessage(issue, checkHook) { + const message = checkHook(issue); + if (message !== undefined || issue.issue._tag !== "InvalidValue") + return message; + const expected = findExpected(issue.issue); + return expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); +} function formatCheck(check) { const expected = check.annotations?.expected; if (typeof expected === "string") @@ -4976,44 +5033,33 @@ function makeFormatterDefault() { return (issue) => formatIssue(issue, ""); } var defaultFormatter = /* @__PURE__ */ makeFormatterDefault(); -function formatIssue(issue, path) { +function formatIssue(issue, path, messageOverride) { let message; switch (issue._tag) { - case "Filter": { - const annotated = defaultCheckHook(issue); - if (annotated !== undefined) { - message = annotated; - } else { - if (issue.issue._tag !== "InvalidValue") { - return formatIssue(issue.issue, path); - } - const expected = findExpected(issue.issue); - message = expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); - } - break; - } + case "Filter": + return formatIssue(issue.issue, path, messageOverride ?? getFilterMessage(issue, defaultCheckHook)); case "Encoding": - return formatIssue(issue.issue, path); + return formatIssue(issue.issue, path, messageOverride); case "Pointer": - return formatIssue(issue.issue, path + formatPath(issue.path)); + return formatIssue(issue.issue, path + formatPath(issue.path), messageOverride); case "Composite": case "AnyOf": { if (issue._tag === "Composite" || issue.issues.length > 0) { - return issue.issues.map((issue) => formatIssue(issue, path)).join(` + return issue.issues.map((issue) => formatIssue(issue, path, messageOverride)).join(` `); } - message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); + message = messageOverride ?? findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); break; } default: - message = defaultLeafHook(issue); + message = messageOverride ?? defaultLeafHook(issue); break; } return path ? `${message} at ${path}` : message; } function findMessage(issue) { - if (issue._tag === "Pointer") + if (issue._tag === "Pointer" || issue._tag === "Composite") return; if (issue._tag === "Encoding") return findMessage(issue.issue); @@ -5191,7 +5237,12 @@ var Declaration = class extends ASTNodeImpl { return (input, options) => { if (input === missing) return missingExit; - return (run ??= this.run(this.typeParameters))(input, this, options); + run ??= this.run(this.typeParameters); + try { + return run(input, this, options); + } catch (error) { + return die3(error); + } }; } _rebuild(recur, checks, encodingChecks, run, encodingRun) { @@ -5304,173 +5355,6 @@ function hasCheck(checks, id) { return checks.some((check) => check.annotations?.representation?.id === id || check._tag === "FilterGroup" && hasCheck(check.checks, id)); } var number2 = /* @__PURE__ */ new Number4; -var Arrays = class extends ASTNodeImpl { - _tag = "Arrays"; - isMutable; - elements; - rest; - encodingChecks; - constructor(isMutable, elements, rest, annotations, checks, encoding, context, encodingChecks) { - super(annotations, checks, encoding, context); - this.isMutable = isMutable; - this.elements = elements; - this.rest = rest; - this.encodingChecks = encodingChecks; - let hasOptional = false; - for (let i = 0;i < elements.length; i++) { - if (isOptional(elements[i])) { - hasOptional = true; - } else if (hasOptional) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - } - if (hasOptional && rest.length > 1) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - for (let i = 1;i < rest.length; i++) { - if (isOptional(rest[i])) { - throw new Error("An optional element cannot follow a rest element. ts(1266)"); - } - } - } - getParser(compile, compileField = compile) { - const ast = this; - let elements; - let rest; - const elementLen = ast.elements.length; - const tailLen = Math.max(0, ast.rest.length - 1); - function getParser(tailThreshold, index) { - if (index < elementLen) { - return elements[index]; - } else if (index >= tailThreshold) { - return rest[index - tailThreshold + 1]; - } - return rest[0]; - } - const finish = (state) => { - const { - input, - len, - options - } = state; - if (ast.rest.length === 0 && len > elementLen) { - for (let i = elementLen;i < len; i++) { - const unexpected = new UnexpectedKey(ast, input[i], options); - const issue = new Pointer([i], unexpected); - if (options.errors === "all") { - if (state.issues) - state.issues.push(issue); - else - state.issues = [issue]; - } else { - return fail6(new Composite(ast, [issue], input, options)); - } - } - } - if (state.issues) { - return fail6(new Composite(ast, state.issues, input, options)); - } - return succeed7(state.output); - }; - const parse = (input, options) => { - const len = input.length; - const state = { - ast, - getParser, - input, - len, - tailThreshold: Math.max(elementLen, len - tailLen), - output: new globalThis.Array(len), - issues: undefined, - options - }; - const end = ast.rest.length === 0 ? elementLen : Math.max(len, elementLen + tailLen); - const concurrency = options.concurrency === undefined ? 1 : resolveConcurrency(options.concurrency); - const eff = concurrency === 1 ? parseArray(state, input, 0, end) : parseArrayConcurrent(state, input, { - concurrency, - end - }); - if (!eff) - return finish(state); - if (effectIsExit(eff)) - return flatMapEager2(eff, () => finish(state)); - let first = true; - return suspend2(() => { - if (!first) - return parse(input, options); - first = false; - return flatMap3(eff, () => finish(state)); - }); - }; - return (input, options) => { - if (input === missing) - return missingExit; - try { - if (!Array.isArray(input)) { - return fail6(new InvalidType(ast, input, options)); - } - if (!elements) { - elements = ast.elements.map((ast) => ({ - ast, - parser: compileField(ast) - })); - rest = ast.rest.map((ast) => ({ - ast, - parser: compileField(ast) - })); - } - return parse(input, options); - } catch (error) { - return die3(error); - } - }; - } - _rebuild(recur, checks, encodingChecks) { - const elements = mapOrSame(this.elements, recur); - const rest = mapOrSame(this.rest, recur); - return elements === this.elements && rest === this.rest && checks === this.checks && encodingChecks === this.encodingChecks ? this : new Arrays(this.isMutable, elements, rest, this.annotations, checks, undefined, this.context, encodingChecks); - } - recur(recur) { - return this._rebuild(recur, this.checks, this.encodingChecks); - } - flip(recur) { - return this._rebuild(recur, this.encodingChecks, this.checks); - } - getExpected() { - return "array"; - } -}; -function stepArray(s, item, exit, i) { - if (exit._tag === "Failure") { - return wrapPropertyKeyIssue(s, s.ast, i, exit); - } - const value = exit === sameExit ? item : exit[args]; - if (value !== missing) { - s.output[i] = value; - } else { - const p = s.getParser(s.tailThreshold, i); - if (isOptional(p.ast)) - return; - const issue = new Pointer([i], new MissingKey(p.ast.context?.annotations)); - if (s.options.errors === "all") { - if (s.issues) - s.issues.push(issue); - else - s.issues = [issue]; - } else { - return fail5(new Composite(s.ast, [issue], s.input, s.options)); - } - } -} -var parseArrayOptions = { - onItem(s, item, i) { - const value = i < s.len ? item : missing; - return s.getParser(s.tailThreshold, i).parser(value, s.options); - }, - step: stepArray -}; -var parseArray = /* @__PURE__ */ iterateEager()(parseArrayOptions); -var parseArrayConcurrent = /* @__PURE__ */ iterateConcurrent()(parseArrayOptions); var wrapPropertyKeyIssue = (s, ast, key, exit) => { if (exit.cause.reasons.length === 0) { return exit; @@ -5489,7 +5373,7 @@ var wrapPropertyKeyIssue = (s, ast, key, exit) => { return fail5(new Composite(ast, [pointer], s.input, s.options)); } }; -var FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?"; +var FINITE_PATTERN = "[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?"; function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) { let stringKeys; let symbolKeys; @@ -5728,9 +5612,15 @@ var Objects = class extends ASTNodeImpl { if (indexCount) return makeFallback(); let fallback; - const resume = (state, index, pending) => { + const resume = (snapshot, index, pending) => { const property = properties[index]; return flatMap3(exit2(pending), (exit) => { + const state = { + ...snapshot, + out: { + ...snapshot.out + } + }; const terminal = stepProperty(state, property, exit); if (terminal) return terminal; @@ -5860,9 +5750,6 @@ function struct(fields, checks, annotations) { function getAST(self) { return self.ast; } -function tuple(elements, checks = undefined) { - return new Arrays(false, elements.map((e) => e.ast), [], undefined, checks); -} function union(members, options, checks) { return new Union(members.map(getAST), options, undefined, checks); } @@ -6655,6 +6542,16 @@ function getConstructorDescriptor(ast) { // node_modules/effect/dist/internal/schema/interpreter.js var flatMapTransformation = (result, current, f) => result === sameExit ? f(current) : flatMapEager2(result, f); function compileTransformation(transformation) { + const apply = compileTransformationUnsafe(transformation); + return (result, current, options) => { + try { + return apply(result, current, options); + } catch (error) { + return die3(error); + } + }; +} +function compileTransformationUnsafe(transformation) { if (transformation._tag === "Middleware") { return (result, current, options) => { const transformed = result === sameExit ? transformation.decode(succeed7(toOption(current)), options) : transformation.decode(mapEager2(result, toOption), options); @@ -6730,53 +6627,57 @@ function compile(ast, compile, compileField, base, specialize) { let encodingParsers; const parseChecks = (input, options) => { let result = parser(input, options); - if (encodingChecks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const output = result === sameExit ? input : result[args]; - if (input !== missing && output !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, input, options)); + try { + if (encodingChecks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const output = result === sameExit ? input : result[args]; + if (input !== missing && output !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + result = fail6(new Composite(ast, issues, input, options)); + } } } - } - } else { - result = flatMap3(result, (value) => { - if (input !== missing && value !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - return fail6(new Composite(ast, issues, input, options)); + } else { + result = flatMap3(result, (value) => { + if (input !== missing && value !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, input, options)); + } } - } - return succeed6(value); - }); - } - } - if (checks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const value = result === sameExit ? input : result[args]; - if (value === missing) - return result; - const issues = collectIssues(checks, value, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, value, options)); - } + return succeed6(value); + }); } - } else { - result = flatMap3(result, (value) => { - if (value !== missing) { + } + if (checks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const value = result === sameExit ? input : result[args]; + if (value === missing) + return result; const issues = collectIssues(checks, value, undefined, ast, options); if (issues) { - return fail6(new Composite(ast, issues, value, options)); + result = fail6(new Composite(ast, issues, value, options)); } } - return succeed6(value); - }); + } else { + result = flatMap3(result, (value) => { + if (value !== missing) { + const issues = collectIssues(checks, value, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, value, options)); + } + } + return succeed6(value); + }); + } } + return result; + } catch (error) { + return die3(error); } - return result; }; const parseLocal = specialize === undefined ? parseChecks : specialize(parseChecks); if (!links) { @@ -7178,21 +7079,6 @@ function makeStruct(ast, fields) { function Struct(fields) { return makeStruct(struct(fields, undefined), fields); } -function makeTuple(ast, elements) { - return make8(ast, { - elements, - mapElements(f, options) { - const elements = f(this.elements); - return makeTuple(tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements); - } - }); -} -function Tuple(elements) { - return makeTuple(tuple(elements), elements); -} -var ArraySchema = /* @__PURE__ */ lambda((schema) => make8(new Arrays(false, [], [schema.ast]), { - value: schema -})); function makeUnion(ast, members) { return make8(ast, { members, @@ -7252,32 +7138,24 @@ function link() { }; } var makeFilter2 = makeFilter; -function isPattern2(regExp, annotations) { - const source = regExp.source; - const flags = regExp.flags; - const canExport = /^[dg]*uy?$/.test(flags); - const runtimeRegExp = flags === "" ? `new RegExp(${format(source)})` : `new RegExp(${format(source)}, ${format(flags)})`; - return isPattern(regExp, { - toJsonSchema: () => canExport ? { - pattern: flags.endsWith("y") ? `^(?:${source})` : source - } : [{}, true], - toCode: () => ({ - runtime: `Schema.isPattern(${runtimeRegExp})` - }), - ...annotations - }); -} function isBase64(annotations) { - const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - return isPattern2(regExp, { + const pattern = "^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"; + const regExp = /^[0-9a-zA-Z+/]*={0,2}$/; + return makeFilter2((s) => s.length % 4 === 0 && regExp.test(s), { expected: "a base64 encoded string", representation: { id: "effect/schema/isBase64", payload: null }, toJsonSchema: () => ({ - pattern: regExp.source + pattern }), + arbitraryConstraint: { + patterns: [{ + source: pattern, + flags: "" + }] + }, toCode: () => ({ runtime: "Schema.isBase64()" }), @@ -7391,47 +7269,6 @@ var File = /* @__PURE__ */ instanceOf(globalThis.File, { }) })) }); -var FormData2 = /* @__PURE__ */ instanceOf(globalThis.FormData, { - representation: { - id: "effect/schema/FormData", - payload: null - }, - toCode: () => ({ - runtime: `Schema.FormData`, - Type: `globalThis.FormData` - }), - expected: "FormData", - toCodecJson: () => link()(ArraySchema(Tuple([String4, Union2([Struct({ - _tag: tag("String"), - value: String4 - }), Struct({ - _tag: tag("File"), - value: File - })])])), transformEffect2({ - decode: (e) => { - const out = new globalThis.FormData; - for (const [key, entry] of e) { - out.append(key, entry.value); - } - return succeed6(out); - }, - encode: (formData) => { - return succeed6(globalThis.Array.from(formData.entries()).map(([key, value]) => { - if (typeof value === "string") { - return [key, { - _tag: "String", - value - }]; - } else { - return [key, { - _tag: "File", - value - }]; - } - })); - } - })) -}); var URLSearchParams2 = /* @__PURE__ */ instanceOf(globalThis.URLSearchParams, { representation: { id: "effect/schema/URLSearchParams", @@ -7547,13 +7384,16 @@ function makeClass(Inherited, identifier, struct2, annotations, proto) { } return out; } -function getClassTransformation(self) { - return new Transformation(transform((input) => new self(input, { +function makeClassTrusted(self, fields) { + return new self(fields, { "~payload": { token: payloadToken, - value: input + value: fields } - })), passthrough()); + }); +} +function getClassTransformation(self) { + return new Transformation(transform((input) => makeClassTrusted(self, input)), passthrough()); } function getClassTypeId(identifier) { return `~effect/Schema/Class/${identifier}`; @@ -8040,14 +7880,11 @@ var toTransform = (channel) => channel.transform; var asyncQueue = (scope, f, options) => make11({ capacity: options?.bufferSize, strategy: options?.strategy -}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope)))); +}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope, { + startImmediately: true +})))); var callbackArray = (f, options) => fromTransform((_, scope) => map5(asyncQueue(scope, f, options), takeAll2)); -var suspend3 = (evaluate) => fromTransform((upstream, scope) => suspend2(() => toTransform(evaluate())(upstream, scope))); var empty3 = /* @__PURE__ */ fromPull(/* @__PURE__ */ succeed6(/* @__PURE__ */ done2())); -var map7 = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => sync3(() => { - let i = 0; - return map5(pull, (o) => f(o, i++)); -}))); var mapDone = /* @__PURE__ */ dual(2, (self, f) => mapDoneEffect(self, (o) => succeed6(f(o)))); var mapDoneEffect = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => succeed6(catchDone(pull, (done) => flatMap3(f(done), done2))))); var merge2 = /* @__PURE__ */ dual((args) => isChannel(args[0]) && isChannel(args[1]), (left, right, options) => fromTransformBracket(fnUntraced2(function* (upstream, _scope, forkedScope) { @@ -8160,6 +7997,18 @@ var splitLines = () => fromTransform((upstream, _scope) => sync3(() => { } return pullOrFlush; })); +var decodeText = (encoding, options) => fromTransform((upstream, _scope) => sync3(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + let pull = upstream.pipe(map5(map2((bytes) => decoder.decode(bytes, streamOptions))), catchDone((leftover) => { + pull = done2(leftover); + const last = decoder.decode(); + return last.length > 0 ? succeed6(of(last)) : pull; + })); + return suspend2(() => pull); +})); var pipeTo = /* @__PURE__ */ dual(2, (self, that) => fromTransform((upstream, scope) => flatMap3(toTransform(self)(upstream, scope), (upstream) => toTransform(that)(upstream, scope)))); var unwrap = (channel) => fromTransform((upstream, scope) => { let pull; @@ -8427,12 +8276,7 @@ var transformPull2 = (self, f) => fromChannel3(fromTransform((_, scope) => flatM var toChannel2 = (stream) => stream.channel; var callback3 = (f, options) => fromChannel3(callbackArray(f, options)); var empty4 = /* @__PURE__ */ fromChannel3(empty3); -var suspend4 = (stream) => fromChannel3(suspend3(() => stream().channel)); var unwrap3 = (effect) => fromChannel3(unwrap(map5(effect, toChannel2))); -var map8 = /* @__PURE__ */ dual(2, (self, f) => suspend4(() => { - let i = 0; - return fromChannel3(map7(self.channel, map2((o) => f(o, i++)))); -})); var merge3 = /* @__PURE__ */ dual((args) => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel3(merge2(toChannel2(self), toChannel2(that), options))); var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (upstream, scope) => sync3(() => { let done; @@ -8454,12 +8298,7 @@ var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (up }); return suspend2(() => done ? done : pull); }))); -var decodeText = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => suspend4(() => { - const decoder = new TextDecoder(options?.encoding); - return map8(self, (chunk) => decoder.decode(chunk, { - stream: true - })); -})); +var decodeText2 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => self.channel.pipe(pipeTo(decodeText(options?.encoding)), fromChannel3)); var splitLines2 = (self) => self.channel.pipe(pipeTo(splitLines()), fromChannel3); var run2 = /* @__PURE__ */ dual(2, (self, sink) => scopedWith2((scope) => toPullScoped(self.channel, scope).pipe(flatMap3((upstream) => sink.transform(upstream, scope)), map5(([a]) => a)))); var runCollect = (self) => runFold(self.channel, () => [], (acc, chunk) => { @@ -8585,10 +8424,14 @@ var ulidString = (timestampMillis, bytes) => { }; // node_modules/effect/dist/internal/uuid.js -var hex = (byte) => byte.toString(16).padStart(2, "0"); +var hex = /* @__PURE__ */ Array.from({ + length: 256 +}, (_, byte) => byte.toString(16).padStart(2, "0")); var stringify = (bytes) => { - const segments = [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)]; - return segments.map((segment) => Array.from(segment, hex).join("")).join("-"); + if (bytes.length < 16) { + return [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)].map((segment) => Array.from(segment, (byte) => hex[byte]).join("")).join("-"); + } + return hex[bytes[0]] + hex[bytes[1]] + hex[bytes[2]] + hex[bytes[3]] + "-" + hex[bytes[4]] + hex[bytes[5]] + "-" + hex[bytes[6]] + hex[bytes[7]] + "-" + hex[bytes[8]] + hex[bytes[9]] + "-" + hex[bytes[10]] + hex[bytes[11]] + hex[bytes[12]] + hex[bytes[13]] + hex[bytes[14]] + hex[bytes[15]]; }; var randomBytes = () => globalThis.crypto.getRandomValues(new Uint8Array(16)); function v4Bytes(bytes = randomBytes()) { @@ -8707,23 +8550,26 @@ var defaultTeardown = (exit, onExit) => { return onExit(getErrorExitCode(squash(exit.cause))); }; var makeRunMain = (f) => dual((args) => isEffect2(args[0]), (effect, options) => { - const fiber = options?.disableErrorReporting === true ? runFork2(effect) : runFork2(tapCause2(effect, (cause) => { + const main = options?.disableErrorReporting === true ? effect : tapCause2(effect, (cause) => { if (hasInterruptsOnly2(cause)) return void_3; const isReported = getErrorReported(squash(cause)); return isReported ? logError(cause) : void_3; - })); - try { - const keepAlive = globalThis.setInterval(constVoid, 2147483647); - fiber.addObserver(() => { - clearInterval(keepAlive); - }); - } catch {} - const teardown = options?.teardown ?? defaultTeardown; - return f({ - fiber, - teardown }); + const teardown = options?.teardown ?? defaultTeardown; + runFork2(withFiber2((fiber) => { + try { + const keepAlive = globalThis.setInterval(constVoid, 2147483647); + fiber.addObserver(() => { + clearInterval(keepAlive); + }); + } catch {} + f({ + fiber, + teardown + }); + return main; + })); }); var errorExitCode = "~effect/Runtime/errorExitCode"; var getErrorExitCode = (u) => { @@ -8828,7 +8674,7 @@ var makeHandle = (params) => Object.setPrototypeOf({ ...params }, HandleProto); var make20 = (spawn) => { - const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); + const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText2(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); const streamLines = (command, options) => splitLines2(streamString(command, options)); return ChildProcessSpawner.of({ spawn, @@ -8997,6 +8843,7 @@ var handleErrnoException = (module, method) => (err, [path]) => { reason = "NotFound"; break; case "EACCES": + case "EPERM": reason = "PermissionDenied"; break; case "EEXIST": @@ -9025,66 +8872,149 @@ var handleErrnoException = (module, method) => (err, [path]) => { }); }; +// node_modules/@effect/platform-node-shared/dist/NodeSink.js +import { finished } from "node:stream"; + +// node_modules/@effect/platform-node-shared/dist/internal/stream.js +var destroyStream = (stream, cleanup, onDestroyed) => { + if (!("closed" in stream)) { + cleanup(); + onDestroyed?.(); + return; + } + const onDone = () => { + clearImmediate(immediate); + stream.off("error", onDone); + stream.off("close", onDone); + onDestroyed?.(); + }; + const onClosed = () => { + if (stream.closed) { + onDone(); + } else { + immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + } + }; + let immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + stream.once("error", onDone); + stream.once("close", onDone); + cleanup(); + if (!stream.closed) { + stream.destroy(); + } +}; + // node_modules/@effect/platform-node-shared/dist/NodeSink.js var fromWritable = (options) => fromChannel2(mapDone(fromWritableChannel(options), (_) => [_])); var fromWritableChannel = (options) => fromTransform((pull) => { const writable = options.evaluate(); - return succeed6(pullIntoWritable({ + const write = pullIntoWritable({ ...options, writable, pull - })); -}); -var pullIntoWritable = (options) => options.pull.pipe(flatMap3((chunk) => { - let i = 0; - return callback2((resume) => { - let cancelled = false; - const loop = () => { - for (;i < chunk.length; ) { - if (cancelled) { - return; - } - const success = options.writable.write(chunk[i++], options.encoding); - if (!success) { - if (!cancelled) { - options.writable.once("drain", loop); + }); + return succeed6(options.endOnDone === false ? write : onError2(write, (cause) => isDoneCause(cause) ? void_3 : releaseWritable(writable))); +}); +var releaseWritable = (writable) => callback2((resume) => { + const onDestroyed = () => resume(void_3); + if (writable.closed) { + const cleanup = finished(writable, { + readable: false + }, () => { + cleanup(); + onDestroyed(); + }); + } else { + destroyStream(writable, constVoid, onDestroyed); + } +}); +var pullIntoWritable = (options) => withFiber2((fiber) => { + const dispatcher = fiber.currentDispatcher; + const completion = makeUnsafe2(); + const failure = makeUnsafe2(); + const onError = (error) => doneUnsafe(failure, failSync2(() => options.onError(error))); + let errorEmitted = false; + const onStreamError = (error) => { + errorEmitted = true; + onError(error); + }; + options.writable.on("error", onStreamError); + const cleanup = finished(options.writable, { + readable: false + }, (error) => { + if (error) { + onError(error); + } else { + doneUnsafe(completion, void_3); + } + }); + return options.pull.pipe(flatMap3((chunk) => { + let i = 0; + return callback2((resume) => { + let cancelled = false; + const onFinish = () => dispatcher.scheduleTask(loop, 0); + const loop = () => { + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + for (;i < chunk.length; ) { + if (cancelled) { + return; + } + const success = options.writable.write(chunk[i++], options.encoding, (error) => { + if (!error) + return; + if (options.writable.closed) { + onError(error); + } else { + dispatcher.scheduleTask(() => onError(error), 0); + } + }); + if (!success) { + if (!cancelled) { + options.writable.once("drain", loop); + options.writable.once("finish", onFinish); + } + return; } - return; } - } - if (!cancelled) { - resume(void_3); - } - }; - loop(); - return sync3(() => { - cancelled = true; - options.writable.off("drain", loop); + if (!cancelled) { + resume(void_3); + } + }; + loop(); + return sync3(() => { + cancelled = true; + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + }); }); - }); -}), forever2({ - disableYield: true -}), options.endOnDone !== false ? catchDone((_) => { - if ("closed" in options.writable && options.writable.closed) { - return done2(_); - } - return callback2((resume) => { - const onFinish = () => resume(done2(_)); - options.writable.once("finish", onFinish); + }), forever2({ + disableYield: true + }), options.endOnDone !== false ? catchDone((_) => { options.writable.end(); - return sync3(() => { - options.writable.off("finish", onFinish); - }); - }); -}) : identity, raceFirst2(callback2((resume) => { - const onError = (error) => resume(fail6(options.onError(error))); - options.writable.once("error", onError); - return sync3(() => { - options.writable.off("error", onError); - }); -}))); + return andThen2(_await(completion), done2(_)); + }) : identity, raceFirst2(_await(failure)), ensuring2(sync3(() => { + cleanup(); + const removeErrorListener = () => { + options.writable.off("error", onStreamError); + options.writable.off("error", removeErrorListener); + options.writable.off("close", removeErrorListener); + }; + if (options.writable.errored && !options.writable.closed && !errorEmitted) { + options.writable.once("error", removeErrorListener); + options.writable.once("close", removeErrorListener); + } else { + removeErrorListener(); + } + }))); +}); // node_modules/@effect/platform-node-shared/dist/NodeStream.js +import { finished as finished2, Readable } from "node:stream"; var fromReadable = (options) => fromChannel3(fromReadableChannel(options)); var fromReadableChannel = (options) => fromTransform((_, scope) => readableToPullUnsafe({ scope, @@ -9101,17 +9031,14 @@ var readableToPullUnsafe = (options) => { function onReadable() { latch.openUnsafe(); } - function onError(error) { - exit.current = fail5(options.onError(error)); - latch.openUnsafe(); - } - function onEnd() { - exit.current = fail5(Done2()); - latch.openUnsafe(); - } readable.on("readable", onReadable); - readable.once("error", onError); - readable.once("end", onEnd); + const cleanup = finished2(readable, { + readable: true, + writable: false + }, (error) => { + exit.current ??= fail5(error ? options.onError(error) : Done2()); + latch.openUnsafe(); + }); const pull = suspend2(function loop() { let item = options.readable.read(options.chunkSize); if (item === null) { @@ -9135,10 +9062,10 @@ var readableToPullUnsafe = (options) => { }); return as2(addFinalizer2(options.scope, sync3(() => { readable.off("readable", onReadable); - readable.off("error", onError); - readable.off("end", onEnd); - if (closeOnDone && "closed" in options.readable && !options.readable.closed) { - options.readable.destroy(); + if (closeOnDone) { + destroyStream(readable, cleanup); + } else { + cleanup(); } })), pull); }; @@ -9463,6 +9390,7 @@ var make22 = /* @__PURE__ */ gen2(function* () { const signalGroup = (signal) => killProcessGroup(command, childProcess, signal).pipe(catch_2(() => killProcess(command, childProcess, signal))); yield* signalGroup(options?.killSignal ?? "SIGTERM"); if (isUndefined(options?.forceKillAfter)) { + yield* _await(exitSignal); yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis); } else { yield* awaitProcessExit(childProcess, exitSignal, toMillis(options.forceKillAfter)); @@ -10056,14 +9984,14 @@ var readLink = /* @__PURE__ */ (() => { return (path) => nodeReadLink(path); })(); var realPath = /* @__PURE__ */ (() => { - const nodeRealPath = /* @__PURE__ */ effectify(NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); + const nodeRealPath = /* @__PURE__ */ effectify(process.platform === "win32" ? NFS.realpath.native : NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); return (path) => nodeRealPath(path); })(); var rename2 = /* @__PURE__ */ (() => { const nodeRename = /* @__PURE__ */ effectify(NFS.rename, /* @__PURE__ */ handleErrnoException("FileSystem", "rename"), /* @__PURE__ */ handleBadArgument("rename")); return (oldPath, newPath) => nodeRename(oldPath, newPath); })(); -var makeFileInfo = (stat) => try_2({ +var makeFileInfo = (stat, method = "stat") => try_2({ try: () => ({ type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown", mtime: fromNullishOr(stat.mtime), @@ -10080,14 +10008,16 @@ var makeFileInfo = (stat) => try_2({ blksize: stat.blksize !== undefined ? some2(bytes(stat.blksize)) : none2(), blocks: fromNullishOr(stat.blocks) }), - catch: handleBadArgument("stat") + catch: handleBadArgument(method) }); -var stat2 = /* @__PURE__ */ (() => { - const nodeStat = /* @__PURE__ */ effectify(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat")); +var statFactory = (method, nodeStatFn) => { + const nodeStat = effectify(nodeStatFn, handleErrnoException("FileSystem", method), handleBadArgument(method)); return (path) => flatMap3(nodeStat(path, { bigint: true - }), makeFileInfo); -})(); + }), (stat) => makeFileInfo(stat, method)); +}; +var stat2 = /* @__PURE__ */ statFactory("stat", NFS.stat); +var lstat2 = /* @__PURE__ */ statFactory("lstat", NFS.lstat); var symlink2 = /* @__PURE__ */ (() => { const nodeSymlink = /* @__PURE__ */ effectify(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink")); return (target, path) => nodeSymlink(target, path); @@ -10170,6 +10100,7 @@ var makeFileSystem = /* @__PURE__ */ map5(/* @__PURE__ */ serviceOption2(WatchBa copyFile: copyFile2, glob: glob2, link: link3, + lstat: lstat2, makeDirectory, makeTempDirectory, makeTempDirectoryScoped, @@ -10309,9 +10240,6 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readline.emitKeypressEvents(stdin, rl); rl.on("line", onLine); rl.once("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(true); - } return { rl, onClose, @@ -10325,9 +10253,6 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readlineActive = false; rl.off("line", onLine); rl.off("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(false); - } rl.close(); if (inputEnded) { endUnsafe(lines); @@ -10335,6 +10260,14 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu })), idleTimeToLive: "10 millis" }); + const setRawMode = (enabled) => sync3(() => { + if (stdin.isTTY) + stdin.setRawMode(enabled); + }); + const rawModeRef = yield* make13({ + acquire: acquireRelease2(setRawMode(true), () => setRawMode(false)), + idleTimeToLive: "10 millis" + }); const columns = sync3(() => stdout.columns ?? 0); const rows = sync3(() => stdout.rows ?? 0); const readInput = gen2(function* () { @@ -10369,6 +10302,7 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu handleEnd(); } else { yield* get3(rlRef); + yield* get3(rawModeRef); stdin.once("end", handleEnd); } return queue; @@ -10487,7 +10421,7 @@ class CommandError extends TaggedError3()("CommandError", { }) { } var error = (command, cause) => new CommandError({ command, exitCode: -1, stderr: String(cause) }); -var collectText = (stream) => stream.pipe(decodeText(), runFold2(() => "", (all, chunk) => all + chunk)); +var collectText = (stream) => stream.pipe(decodeText2(), runFold2(() => "", (all, chunk) => all + chunk)); var retainedStderrLength = 16 * 1024; class Service3 extends Service()("@timmo001/workflows/CommandExecutor") { @@ -10540,8 +10474,8 @@ var layer14 = effect(Service3, gen2(function* () { stdin: "inherit" })); let stderrTail = ""; - const stdout = handle.stdout.pipe(decodeText(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); - const stderr = handle.stderr.pipe(decodeText(), runForEach2((chunk) => sync3(() => { + const stdout = handle.stdout.pipe(decodeText2(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); + const stderr = handle.stderr.pipe(decodeText2(), runForEach2((chunk) => sync3(() => { process.stderr.write(chunk); stderrTail = `${stderrTail}${chunk}`.slice(-retainedStderrLength); }))); diff --git a/.github/actions/foundation-smoke/dist/index.js b/.github/actions/foundation-smoke/dist/index.js index e55575b3..b0d55c23 100644 --- a/.github/actions/foundation-smoke/dist/index.js +++ b/.github/actions/foundation-smoke/dist/index.js @@ -769,6 +769,10 @@ function assignProperty(self, key, value) { } } function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } for (const key of Reflect.ownKeys(source)) { if (Object.prototype.propertyIsEnumerable.call(source, key)) { assignProperty(self, key, source[key]); @@ -859,7 +863,7 @@ class CauseImpl { toJSON() { return { _id: "Cause", - failures: this.reasons.map((f) => f.toJSON()) + reasons: this.reasons.map((f) => f.toJSON()) }; } toString() { @@ -1610,9 +1614,21 @@ var bigint2 = /* @__PURE__ */ BigInt(2); var bigint10 = /* @__PURE__ */ BigInt(10); var bigint1e3 = /* @__PURE__ */ BigInt(1000); var bigint1e6 = /* @__PURE__ */ BigInt(1e6); +var bigint1e9 = /* @__PURE__ */ BigInt(1e9); +var bigintNanosPerMinute = /* @__PURE__ */ BigInt(60000000000); +var bigintNanosPerHour = /* @__PURE__ */ BigInt(3600000000000); +var bigintNanosPerDay = /* @__PURE__ */ BigInt(86400000000000); +var bigintNanosPerWeek = /* @__PURE__ */ BigInt(604800000000000); var roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input))); var roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6); var fromNanosNumber = (nanos) => make3(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos); +var nanosToUnit = (nanos, divisor) => { + const value = Number(nanos); + if (Number.isFinite(value)) + return value / divisor; + const scale = BigInt(divisor); + return Number(nanos / scale) + Number(nanos % scale) / divisor; +}; var parseNanos = (input, scale) => { const decimalIndex = input.indexOf("."); if (decimalIndex === -1) @@ -1628,6 +1644,13 @@ var divideTiesAwayFromZero = (numerator, denominator) => { const rounded = absolute / denominator + (absolute % denominator * bigint2 >= denominator ? bigint1 : bigint0); return numerator < bigint0 ? -rounded : rounded; }; +var fromMillisString = (input, scale) => { + const millis = Number(input) * scale; + if (!Number.isFinite(millis)) + return make3(millis); + const nanos = parseNanos(input, BigInt(scale) * bigint1e6); + return make3(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos); +}; var DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; var fromInputUnsafe = (input) => { switch (typeof input) { @@ -1652,26 +1675,25 @@ var fromInputUnsafe = (input) => { if (unit === "micro" || unit === "micros") { return nanos(parseNanos(valueStr, bigint1e3)); } - const value = Number(valueStr); switch (unit) { case "milli": case "millis": - return millis(value); + return fromMillisString(valueStr, 1); case "second": case "seconds": - return seconds(value); + return fromMillisString(valueStr, 1000); case "minute": case "minutes": - return minutes(value); + return fromMillisString(valueStr, 60000); case "hour": case "hours": - return hours(value); + return fromMillisString(valueStr, 3600000); case "day": case "days": - return days(value); + return fromMillisString(valueStr, 86400000); case "week": case "weeks": - return weeks(value); + return fromMillisString(valueStr, 604800000); } break; } @@ -1693,7 +1715,8 @@ var fromInputUnsafe = (input) => { if (input[0] === Infinity || input[1] === Infinity) { return infinity; } - return fromNanosNumber(input[0] * 1e9 + input[1]); + const nanos = input[0] * 1e9 + input[1]; + return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make3(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos); } const obj = input; let millis = 0; @@ -1709,13 +1732,42 @@ var fromInputUnsafe = (input) => { millis += obj.seconds * 1000; if (obj.milliseconds) millis += obj.milliseconds; - if (!obj.microseconds && !obj.nanoseconds) - return make3(millis); - return fromNanosNumber(millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0)); + if (!obj.microseconds && !obj.nanoseconds) { + if (!Number.isFinite(millis)) + return make3(millis); + const exact = sumObjectNanos(obj); + return exact === undefined || BigInt(millis) * bigint1e6 === exact ? make3(millis) : make3(exact); + } + const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0); + const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : undefined; + return exact === undefined ? fromNanosNumber(nanos) : make3(exact); } } return invalid(input); }; +var isIntegerOrUnset = (n) => !n || Number.isInteger(n); +var sumObjectNanos = (obj) => { + if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds)) + return; + let nanos = bigint0; + if (obj.weeks) + nanos += BigInt(obj.weeks) * bigintNanosPerWeek; + if (obj.days) + nanos += BigInt(obj.days) * bigintNanosPerDay; + if (obj.hours) + nanos += BigInt(obj.hours) * bigintNanosPerHour; + if (obj.minutes) + nanos += BigInt(obj.minutes) * bigintNanosPerMinute; + if (obj.seconds) + nanos += BigInt(obj.seconds) * bigint1e9; + if (obj.milliseconds) + nanos += BigInt(obj.milliseconds) * bigint1e6; + if (obj.microseconds) + nanos += BigInt(obj.microseconds) * bigint1e3; + if (obj.nanoseconds) + nanos += BigInt(obj.nanoseconds); + return nanos; +}; var invalid = (input) => { throw new Error(`Invalid Input: ${input}`); }; @@ -1824,14 +1876,9 @@ var infinity = /* @__PURE__ */ make3(Infinity); var negativeInfinity = /* @__PURE__ */ make3(-Infinity); var nanos = (nanos) => make3(nanos); var millis = (millis) => make3(millis); -var seconds = (seconds) => make3(seconds * 1000); -var minutes = (minutes) => make3(minutes * 60000); -var hours = (hours) => make3(hours * 3600000); -var days = (days) => make3(days * 86400000); -var weeks = (weeks) => make3(weeks * 604800000); var toMillis = (self) => match3(fromInputUnsafe(self), { onMillis: identity, - onNanos: (nanos) => Number(nanos) / 1e6, + onNanos: (nanos) => nanosToUnit(nanos, 1e6), onInfinity: () => Infinity, onNegativeInfinity: () => -Infinity }); @@ -1897,7 +1944,7 @@ var setTimer = "setImmediate" in globalThis ? (f) => { const timer = setTimeout(f, 0); return () => clearTimeout(timer); }; -var setImmediate = (f) => { +var setImmediate2 = (f) => { try { return setTimer(f); } catch { @@ -1937,7 +1984,7 @@ class MixedScheduler { setImmediate; constructor(executionMode = "async", setImmediateFn) { this.executionMode = executionMode; - this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate2); } shouldYield(fiber) { return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; @@ -1951,7 +1998,7 @@ class MixedSchedulerDispatcher { tasks = /* @__PURE__ */ new PriorityBuckets; running = undefined; setImmediate; - constructor(setImmediateFn = setImmediate) { + constructor(setImmediateFn = setImmediate2) { this.setImmediate = setImmediateFn; } scheduleTask(task, priority) { @@ -2195,10 +2242,7 @@ class Interrupt extends ReasonBase { } } var causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); -var findFail = (self) => { - const reason = self.reasons.find(isFailReason); - return reason ? succeed2(reason) : fail2(self); -}; +var hasFails = (self) => self.reasons.some(isFailReason); var findError = (self) => { for (let i = 0;i < self.reasons.length; i++) { const reason = self.reasons[i]; @@ -2208,6 +2252,9 @@ var findError = (self) => { } return fail2(self); }; +var hasDies = (self) => self.reasons.some(isDieReason); +var causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +var findRecoverableError = (self) => hasDies(self) ? fail2(causeElectDefects(self)) : findError(self); var hasInterrupts = (self) => self.reasons.some(isInterruptReason); var hasInterruptsOnly = (self) => self.reasons.length > 0 && self.reasons.every(isInterruptReason); var causeMap = /* @__PURE__ */ dual(2, (self, f) => { @@ -2268,12 +2315,14 @@ var causePrettyErrors = (self, options) => { } return errors; }; -var causePrettyError = (original, annotations, options) => { +var causePrettyError = (original, annotations, options, seen = new Set) => { const kind = typeof original; let error; if (original && kind === "object") { + seen.add(original); + const cause = original.cause; error = new globalThis.Error(causePrettyMessage(original), { - cause: original.cause ? causePrettyError(original.cause) : undefined + cause: cause !== undefined && !seen.has(cause) ? causePrettyError(cause, undefined, undefined, seen) : undefined }); if (typeof original.name === "string") { error.name = original.name; @@ -2484,7 +2533,11 @@ class FiberImpl { } else if (this._asyncContext !== undefined) { const asyncContext = this._asyncContext; this._asyncContext = undefined; - return asyncContext.runInAsyncScope(this.evaluate, this, effect); + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } } else if (this._yielded !== undefined) { const yielded = this._yielded; this._yielded = undefined; @@ -2782,7 +2835,6 @@ var tryPromise = (options) => { } }, f.length !== 0); }; -var withFiberId = (f) => withFiber((fiber) => f(fiber.id)); var callbackOptions = /* @__PURE__ */ function() { const Proto = /* @__PURE__ */ makePrimitiveProto({ op: "Async", @@ -2803,9 +2855,9 @@ var callbackOptions = /* @__PURE__ */ function() { if (yielded !== false) return yielded; yielded = true; - fiber._yielded = () => { + fiber.yieldWith(() => { resumed = true; - }; + }); if (controller === undefined && onCancel === undefined) { return Yield; } @@ -3088,10 +3140,7 @@ var exitMap = /* @__PURE__ */ dual(2, (self, f) => self._tag === "Success" ? exi var exitMapError = /* @__PURE__ */ dual(2, (self, f) => { if (self._tag === "Success") return self; - const error = findError(self.cause); - if (isFailure2(error)) - return self; - return exitFail(f(error.success)); + return exitFailCause(causeMap(self.cause, f)); }); var exitZipRight = /* @__PURE__ */ dual(2, (self, that) => exitIsSuccess(self) ? that : self); var exitAsVoidAll = (exits) => { @@ -3155,10 +3204,10 @@ var catchCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(s const eb = filter(cause); return isFailure2(eb) ? failCause(eb.failure) : f(eb.success, cause); })); -var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findError, (e) => f(e))); +var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findRecoverableError, (e) => f(e))); var tapCause = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => andThen(f(cause), failCause(cause)))); var catchIf = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, predicate, f, orElse) => catchCause(self, (cause) => { - const error = findError(cause); + const error = findRecoverableError(cause); if (isFailure2(error)) return failCause(error.failure); if (!predicate(error.success)) { @@ -3170,7 +3219,7 @@ var catchTag = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, k, f, or const pred = Array.isArray(k) ? (e) => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); return catchIf(self, pred, f, orElse); }); -var mapError = /* @__PURE__ */ dual(2, (self, f) => catch_(self, (error) => failSync(() => f(error)))); +var mapError = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => failCause(causeMap(cause, f)))); var orDie = (self) => catch_(self, die); var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { if (!options?.log) { @@ -3182,8 +3231,8 @@ var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) = const logEffect = logWithLevel(options.log === true ? undefined : options.log); return matchCauseEffect(self, { onFailure(cause) { - const failure = findFail(cause); - return isFailure2(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); }, onSuccess: (_) => void_ }); @@ -3222,16 +3271,16 @@ var makeMatch = (op, onFailure) => { return MatchImpl; }; var MatchImpl = /* @__PURE__ */ makeMatch("Match", function(cause, fiber) { - const fail = cause.reasons.find(isFailReason); - if (fail === undefined) - return failCause(cause); + const error = findRecoverableError(cause); + if (isFailure2(error)) + return failCause(error.failure); const handlers = this.payload; - return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(fail.error) : internalCall(() => handlers.onFailure(fail.error))); + return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))); }); var matchEffect = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, { onFailure: (cause) => { - const fail = cause.reasons.find(isFailReason); - return fail ? options.onFailure(fail.error) : failCause(cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.onFailure(error.success); }, onSuccess: options.onSuccess })); @@ -3240,9 +3289,9 @@ var matchEager = /* @__PURE__ */ dual(2, (self, options) => { if (effectIsExit(self)) { if (self._tag === "Success") return exitSucceed(options.onSuccess(self.value)); - const error = findError(self.cause); + const error = findRecoverableError(self.cause); if (isFailure2(error)) - return self; + return exitFailCause(error.failure); return exitSucceed(options.onFailure(error.success)); } return match4(self, options); @@ -3297,17 +3346,17 @@ var runFinalizer = (finalizer, exit_) => { return exitDie(defect); } }; -var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeCombine(exit_.cause, cause))); +var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); var scopeCloseFinalizers = /* @__PURE__ */ fnUntraced(function* (self, finalizers, exit_) { let exits = []; const fibers = []; - const arr = Array.from(finalizers.values()); + const arr = Array.from(finalizers); const parent = getCurrentFiber(); for (let i = arr.length - 1;i >= 0; i--) { - const finalizer = arr[i]; + const [key, finalizer] = arr[i]; if (self.strategy === "sequential") { exits.push(yield* exit(runFinalizer(finalizer, exit_))); - } else { + } else if (key !== parent) { fibers.push(forkUnsafe(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); } } @@ -3500,15 +3549,9 @@ var all = (arg, options) => { } else if (options?.discard) { return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options); } - return suspend(() => { - const out = {}; - return as(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => { - assignProperty(out, key, value); - }), { - discard: true, - concurrency: options?.concurrency - }), out); - }); + return suspend(() => map3(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => [key, value]), { + concurrency: options?.concurrency + }), Object.fromEntries)); }; var whileLoop = /* @__PURE__ */ makePrimitive({ op: "While", @@ -3647,7 +3690,7 @@ var iterateConcurrentImpl = (options) => { const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); if (reasons.length > 0) { const cause = causeFromReasons(reasons); - terminal = exitFailCause(terminal._tag === "Failure" ? causeCombine(terminal.cause, cause) : cause); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); } } } else { @@ -3725,14 +3768,13 @@ var forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterrupt } return child; }; +var fiberScopeFinalizer = (fiber) => () => withFiber((current) => current === fiber ? void_ : fiberInterrupt(fiber)); var forkIn = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, scope, options) => withFiber((parent) => { - const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + const fiber = scope.state._tag === "Closed" ? new FiberImpl(parent.context) : forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); if (!fiber._exit) { if (scope.state._tag !== "Closed") { - const key = {}; - const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); - scopeAddFinalizerUnsafe(scope, key, finalizer); - fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + scopeAddFinalizerUnsafe(scope, fiber, fiberScopeFinalizer(fiber)); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, fiber)); } else { fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); } @@ -3769,7 +3811,7 @@ var fiberRunIn = /* @__PURE__ */ dual(2, (self, scope) => { return self; } scopeRemoveFinalizerUnsafe(scope, self); - scopeAddFinalizerUnsafe(scope, self, () => fiberInterrupt(self)); + scopeAddFinalizerUnsafe(scope, self, fiberScopeFinalizer(self)); self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, self)); return self; }); @@ -4408,8 +4450,8 @@ var mergeAllEffect = (layers, memoMap, scope) => { concurrency: layers.length }).pipe(map3((context) => mergeAll(...context))); }; -var mergeAll2 = (...layers) => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); -var provideWith = (self, that, f) => fromBuild((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); +var mergeAll2 = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +var provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); var provide2 = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, identity)); var provideMerge = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, (self, that) => merge(that, self))); @@ -4480,6 +4522,7 @@ var void_3 = void_; var callback2 = callback; var gen2 = gen; var fail6 = fail3; +var failSync2 = failSync; var failCause3 = failCause; var failCauseSync2 = failCauseSync; var die3 = die; @@ -4529,16 +4572,23 @@ var fn2 = fn; var clockWith2 = clockWith; var logError = /* @__PURE__ */ logWithLevel("Error"); var effectify = (fn, onError, onSyncError) => (...args) => callback2((resume) => { + let synchronous = true; + let pending; try { fn(...args, (err, result) => { - if (err) { - resume(onError ? suspend2(() => fail6(onError(err, args))) : fail6(err)); + const effect = err ? onError ? suspend2(() => fail6(onError(err, args))) : fail6(err) : succeed6(result); + if (synchronous) { + pending ??= effect; } else { - resume(succeed6(result)); + resume(effect); } }); } catch (err) { - resume(onSyncError ? fail6(onSyncError(err, args)) : die3(err)); + pending = onSyncError ? fail6(onSyncError(err, args)) : die3(err); + } + synchronous = false; + if (pending) { + resume(pending); } }); var mapEager2 = mapEager; @@ -4949,7 +4999,7 @@ var defaultLeafHook = (issue) => { } } }; -var defaultCheckHook = (issue) => findMessage(issue.issue) ?? findMessage(issue); +var defaultCheckHook = (issue) => findMessage(issue) ?? findMessage(issue.issue); function formatInput(issue) { return hasInput(issue) ? format(issue.input) : undefined; } @@ -4961,6 +5011,13 @@ function getExpectedMessage(expected, issue) { const input = formatInput(issue); return input === undefined ? `Expected ${expected}` : `Expected ${expected}, got ${input}`; } +function getFilterMessage(issue, checkHook) { + const message = checkHook(issue); + if (message !== undefined || issue.issue._tag !== "InvalidValue") + return message; + const expected = findExpected(issue.issue); + return expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); +} function formatCheck(check) { const expected = check.annotations?.expected; if (typeof expected === "string") @@ -4976,44 +5033,33 @@ function makeFormatterDefault() { return (issue) => formatIssue(issue, ""); } var defaultFormatter = /* @__PURE__ */ makeFormatterDefault(); -function formatIssue(issue, path) { +function formatIssue(issue, path, messageOverride) { let message; switch (issue._tag) { - case "Filter": { - const annotated = defaultCheckHook(issue); - if (annotated !== undefined) { - message = annotated; - } else { - if (issue.issue._tag !== "InvalidValue") { - return formatIssue(issue.issue, path); - } - const expected = findExpected(issue.issue); - message = expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); - } - break; - } + case "Filter": + return formatIssue(issue.issue, path, messageOverride ?? getFilterMessage(issue, defaultCheckHook)); case "Encoding": - return formatIssue(issue.issue, path); + return formatIssue(issue.issue, path, messageOverride); case "Pointer": - return formatIssue(issue.issue, path + formatPath(issue.path)); + return formatIssue(issue.issue, path + formatPath(issue.path), messageOverride); case "Composite": case "AnyOf": { if (issue._tag === "Composite" || issue.issues.length > 0) { - return issue.issues.map((issue) => formatIssue(issue, path)).join(` + return issue.issues.map((issue) => formatIssue(issue, path, messageOverride)).join(` `); } - message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); + message = messageOverride ?? findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); break; } default: - message = defaultLeafHook(issue); + message = messageOverride ?? defaultLeafHook(issue); break; } return path ? `${message} at ${path}` : message; } function findMessage(issue) { - if (issue._tag === "Pointer") + if (issue._tag === "Pointer" || issue._tag === "Composite") return; if (issue._tag === "Encoding") return findMessage(issue.issue); @@ -5191,7 +5237,12 @@ var Declaration = class extends ASTNodeImpl { return (input, options) => { if (input === missing) return missingExit; - return (run ??= this.run(this.typeParameters))(input, this, options); + run ??= this.run(this.typeParameters); + try { + return run(input, this, options); + } catch (error) { + return die3(error); + } }; } _rebuild(recur, checks, encodingChecks, run, encodingRun) { @@ -5304,173 +5355,6 @@ function hasCheck(checks, id) { return checks.some((check) => check.annotations?.representation?.id === id || check._tag === "FilterGroup" && hasCheck(check.checks, id)); } var number2 = /* @__PURE__ */ new Number4; -var Arrays = class extends ASTNodeImpl { - _tag = "Arrays"; - isMutable; - elements; - rest; - encodingChecks; - constructor(isMutable, elements, rest, annotations, checks, encoding, context, encodingChecks) { - super(annotations, checks, encoding, context); - this.isMutable = isMutable; - this.elements = elements; - this.rest = rest; - this.encodingChecks = encodingChecks; - let hasOptional = false; - for (let i = 0;i < elements.length; i++) { - if (isOptional(elements[i])) { - hasOptional = true; - } else if (hasOptional) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - } - if (hasOptional && rest.length > 1) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - for (let i = 1;i < rest.length; i++) { - if (isOptional(rest[i])) { - throw new Error("An optional element cannot follow a rest element. ts(1266)"); - } - } - } - getParser(compile, compileField = compile) { - const ast = this; - let elements; - let rest; - const elementLen = ast.elements.length; - const tailLen = Math.max(0, ast.rest.length - 1); - function getParser(tailThreshold, index) { - if (index < elementLen) { - return elements[index]; - } else if (index >= tailThreshold) { - return rest[index - tailThreshold + 1]; - } - return rest[0]; - } - const finish = (state) => { - const { - input, - len, - options - } = state; - if (ast.rest.length === 0 && len > elementLen) { - for (let i = elementLen;i < len; i++) { - const unexpected = new UnexpectedKey(ast, input[i], options); - const issue = new Pointer([i], unexpected); - if (options.errors === "all") { - if (state.issues) - state.issues.push(issue); - else - state.issues = [issue]; - } else { - return fail6(new Composite(ast, [issue], input, options)); - } - } - } - if (state.issues) { - return fail6(new Composite(ast, state.issues, input, options)); - } - return succeed7(state.output); - }; - const parse = (input, options) => { - const len = input.length; - const state = { - ast, - getParser, - input, - len, - tailThreshold: Math.max(elementLen, len - tailLen), - output: new globalThis.Array(len), - issues: undefined, - options - }; - const end = ast.rest.length === 0 ? elementLen : Math.max(len, elementLen + tailLen); - const concurrency = options.concurrency === undefined ? 1 : resolveConcurrency(options.concurrency); - const eff = concurrency === 1 ? parseArray(state, input, 0, end) : parseArrayConcurrent(state, input, { - concurrency, - end - }); - if (!eff) - return finish(state); - if (effectIsExit(eff)) - return flatMapEager2(eff, () => finish(state)); - let first = true; - return suspend2(() => { - if (!first) - return parse(input, options); - first = false; - return flatMap3(eff, () => finish(state)); - }); - }; - return (input, options) => { - if (input === missing) - return missingExit; - try { - if (!Array.isArray(input)) { - return fail6(new InvalidType(ast, input, options)); - } - if (!elements) { - elements = ast.elements.map((ast) => ({ - ast, - parser: compileField(ast) - })); - rest = ast.rest.map((ast) => ({ - ast, - parser: compileField(ast) - })); - } - return parse(input, options); - } catch (error) { - return die3(error); - } - }; - } - _rebuild(recur, checks, encodingChecks) { - const elements = mapOrSame(this.elements, recur); - const rest = mapOrSame(this.rest, recur); - return elements === this.elements && rest === this.rest && checks === this.checks && encodingChecks === this.encodingChecks ? this : new Arrays(this.isMutable, elements, rest, this.annotations, checks, undefined, this.context, encodingChecks); - } - recur(recur) { - return this._rebuild(recur, this.checks, this.encodingChecks); - } - flip(recur) { - return this._rebuild(recur, this.encodingChecks, this.checks); - } - getExpected() { - return "array"; - } -}; -function stepArray(s, item, exit, i) { - if (exit._tag === "Failure") { - return wrapPropertyKeyIssue(s, s.ast, i, exit); - } - const value = exit === sameExit ? item : exit[args]; - if (value !== missing) { - s.output[i] = value; - } else { - const p = s.getParser(s.tailThreshold, i); - if (isOptional(p.ast)) - return; - const issue = new Pointer([i], new MissingKey(p.ast.context?.annotations)); - if (s.options.errors === "all") { - if (s.issues) - s.issues.push(issue); - else - s.issues = [issue]; - } else { - return fail5(new Composite(s.ast, [issue], s.input, s.options)); - } - } -} -var parseArrayOptions = { - onItem(s, item, i) { - const value = i < s.len ? item : missing; - return s.getParser(s.tailThreshold, i).parser(value, s.options); - }, - step: stepArray -}; -var parseArray = /* @__PURE__ */ iterateEager()(parseArrayOptions); -var parseArrayConcurrent = /* @__PURE__ */ iterateConcurrent()(parseArrayOptions); var wrapPropertyKeyIssue = (s, ast, key, exit) => { if (exit.cause.reasons.length === 0) { return exit; @@ -5489,7 +5373,7 @@ var wrapPropertyKeyIssue = (s, ast, key, exit) => { return fail5(new Composite(ast, [pointer], s.input, s.options)); } }; -var FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?"; +var FINITE_PATTERN = "[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?"; function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) { let stringKeys; let symbolKeys; @@ -5728,9 +5612,15 @@ var Objects = class extends ASTNodeImpl { if (indexCount) return makeFallback(); let fallback; - const resume = (state, index, pending) => { + const resume = (snapshot, index, pending) => { const property = properties[index]; return flatMap3(exit2(pending), (exit) => { + const state = { + ...snapshot, + out: { + ...snapshot.out + } + }; const terminal = stepProperty(state, property, exit); if (terminal) return terminal; @@ -5860,12 +5750,6 @@ function struct(fields, checks, annotations) { function getAST(self) { return self.ast; } -function tuple(elements, checks = undefined) { - return new Arrays(false, elements.map((e) => e.ast), [], undefined, checks); -} -function union(members, options, checks) { - return new Union(members.map(getAST), options, undefined, checks); -} var toCandidate = /* @__PURE__ */ memoizeIdempotent((ast) => { while (true) { if (isSuspend(ast)) @@ -6655,6 +6539,16 @@ function getConstructorDescriptor(ast) { // node_modules/effect/dist/internal/schema/interpreter.js var flatMapTransformation = (result, current, f) => result === sameExit ? f(current) : flatMapEager2(result, f); function compileTransformation(transformation) { + const apply = compileTransformationUnsafe(transformation); + return (result, current, options) => { + try { + return apply(result, current, options); + } catch (error) { + return die3(error); + } + }; +} +function compileTransformationUnsafe(transformation) { if (transformation._tag === "Middleware") { return (result, current, options) => { const transformed = result === sameExit ? transformation.decode(succeed7(toOption(current)), options) : transformation.decode(mapEager2(result, toOption), options); @@ -6730,53 +6624,57 @@ function compile(ast, compile, compileField, base, specialize) { let encodingParsers; const parseChecks = (input, options) => { let result = parser(input, options); - if (encodingChecks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const output = result === sameExit ? input : result[args]; - if (input !== missing && output !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, input, options)); + try { + if (encodingChecks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const output = result === sameExit ? input : result[args]; + if (input !== missing && output !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + result = fail6(new Composite(ast, issues, input, options)); + } } } - } - } else { - result = flatMap3(result, (value) => { - if (input !== missing && value !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - return fail6(new Composite(ast, issues, input, options)); + } else { + result = flatMap3(result, (value) => { + if (input !== missing && value !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, input, options)); + } } - } - return succeed6(value); - }); - } - } - if (checks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const value = result === sameExit ? input : result[args]; - if (value === missing) - return result; - const issues = collectIssues(checks, value, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, value, options)); - } + return succeed6(value); + }); } - } else { - result = flatMap3(result, (value) => { - if (value !== missing) { + } + if (checks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const value = result === sameExit ? input : result[args]; + if (value === missing) + return result; const issues = collectIssues(checks, value, undefined, ast, options); if (issues) { - return fail6(new Composite(ast, issues, value, options)); + result = fail6(new Composite(ast, issues, value, options)); } } - return succeed6(value); - }); + } else { + result = flatMap3(result, (value) => { + if (value !== missing) { + const issues = collectIssues(checks, value, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, value, options)); + } + } + return succeed6(value); + }); + } } + return result; + } catch (error) { + return die3(error); } - return result; }; const parseLocal = specialize === undefined ? parseChecks : specialize(parseChecks); if (!links) { @@ -7178,33 +7076,6 @@ function makeStruct(ast, fields) { function Struct(fields) { return makeStruct(struct(fields, undefined), fields); } -function makeTuple(ast, elements) { - return make8(ast, { - elements, - mapElements(f, options) { - const elements = f(this.elements); - return makeTuple(tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements); - } - }); -} -function Tuple(elements) { - return makeTuple(tuple(elements), elements); -} -var ArraySchema = /* @__PURE__ */ lambda((schema) => make8(new Arrays(false, [], [schema.ast]), { - value: schema -})); -function makeUnion(ast, members) { - return make8(ast, { - members, - mapMembers(f, options) { - const members = f(this.members); - return makeUnion(union(members, this.ast.options, options?.unsafePreserveChecks ? this.ast.checks : undefined), members); - } - }); -} -function Union2(members, options) { - return makeUnion(union(members, options, undefined), members); -} function decodeTo2(to, transformation) { return (from) => { return make8(decodeTo(from.ast, to.ast, transformation ? makeTransformation(transformation) : passthrough2()), { @@ -7236,32 +7107,24 @@ function link() { }; } var makeFilter2 = makeFilter; -function isPattern2(regExp, annotations) { - const source = regExp.source; - const flags = regExp.flags; - const canExport = /^[dg]*uy?$/.test(flags); - const runtimeRegExp = flags === "" ? `new RegExp(${format(source)})` : `new RegExp(${format(source)}, ${format(flags)})`; - return isPattern(regExp, { - toJsonSchema: () => canExport ? { - pattern: flags.endsWith("y") ? `^(?:${source})` : source - } : [{}, true], - toCode: () => ({ - runtime: `Schema.isPattern(${runtimeRegExp})` - }), - ...annotations - }); -} function isBase64(annotations) { - const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - return isPattern2(regExp, { + const pattern = "^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"; + const regExp = /^[0-9a-zA-Z+/]*={0,2}$/; + return makeFilter2((s) => s.length % 4 === 0 && regExp.test(s), { expected: "a base64 encoded string", representation: { id: "effect/schema/isBase64", payload: null }, toJsonSchema: () => ({ - pattern: regExp.source + pattern }), + arbitraryConstraint: { + patterns: [{ + source: pattern, + flags: "" + }] + }, toCode: () => ({ runtime: "Schema.isBase64()" }), @@ -7375,47 +7238,6 @@ var File = /* @__PURE__ */ instanceOf(globalThis.File, { }) })) }); -var FormData2 = /* @__PURE__ */ instanceOf(globalThis.FormData, { - representation: { - id: "effect/schema/FormData", - payload: null - }, - toCode: () => ({ - runtime: `Schema.FormData`, - Type: `globalThis.FormData` - }), - expected: "FormData", - toCodecJson: () => link()(ArraySchema(Tuple([String4, Union2([Struct({ - _tag: tag("String"), - value: String4 - }), Struct({ - _tag: tag("File"), - value: File - })])])), transformEffect2({ - decode: (e) => { - const out = new globalThis.FormData; - for (const [key, entry] of e) { - out.append(key, entry.value); - } - return succeed6(out); - }, - encode: (formData) => { - return succeed6(globalThis.Array.from(formData.entries()).map(([key, value]) => { - if (typeof value === "string") { - return [key, { - _tag: "String", - value - }]; - } else { - return [key, { - _tag: "File", - value - }]; - } - })); - } - })) -}); var URLSearchParams2 = /* @__PURE__ */ instanceOf(globalThis.URLSearchParams, { representation: { id: "effect/schema/URLSearchParams", @@ -7531,13 +7353,16 @@ function makeClass(Inherited, identifier, struct2, annotations, proto) { } return out; } -function getClassTransformation(self) { - return new Transformation(transform((input) => new self(input, { +function makeClassTrusted(self, fields) { + return new self(fields, { "~payload": { token: payloadToken, - value: input + value: fields } - })), passthrough()); + }); +} +function getClassTransformation(self) { + return new Transformation(transform((input) => makeClassTrusted(self, input)), passthrough()); } function getClassTypeId(identifier) { return `~effect/Schema/Class/${identifier}`; @@ -8024,14 +7849,11 @@ var toTransform = (channel) => channel.transform; var asyncQueue = (scope, f, options) => make11({ capacity: options?.bufferSize, strategy: options?.strategy -}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope)))); +}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope, { + startImmediately: true +})))); var callbackArray = (f, options) => fromTransform((_, scope) => map5(asyncQueue(scope, f, options), takeAll2)); -var suspend3 = (evaluate) => fromTransform((upstream, scope) => suspend2(() => toTransform(evaluate())(upstream, scope))); var empty3 = /* @__PURE__ */ fromPull(/* @__PURE__ */ succeed6(/* @__PURE__ */ done2())); -var map7 = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => sync3(() => { - let i = 0; - return map5(pull, (o) => f(o, i++)); -}))); var mapDone = /* @__PURE__ */ dual(2, (self, f) => mapDoneEffect(self, (o) => succeed6(f(o)))); var mapDoneEffect = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => succeed6(catchDone(pull, (done) => flatMap3(f(done), done2))))); var merge2 = /* @__PURE__ */ dual((args) => isChannel(args[0]) && isChannel(args[1]), (left, right, options) => fromTransformBracket(fnUntraced2(function* (upstream, _scope, forkedScope) { @@ -8144,6 +7966,18 @@ var splitLines = () => fromTransform((upstream, _scope) => sync3(() => { } return pullOrFlush; })); +var decodeText = (encoding, options) => fromTransform((upstream, _scope) => sync3(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + let pull = upstream.pipe(map5(map2((bytes) => decoder.decode(bytes, streamOptions))), catchDone((leftover) => { + pull = done2(leftover); + const last = decoder.decode(); + return last.length > 0 ? succeed6(of(last)) : pull; + })); + return suspend2(() => pull); +})); var pipeTo = /* @__PURE__ */ dual(2, (self, that) => fromTransform((upstream, scope) => flatMap3(toTransform(self)(upstream, scope), (upstream) => toTransform(that)(upstream, scope)))); var unwrap = (channel) => fromTransform((upstream, scope) => { let pull; @@ -8411,12 +8245,7 @@ var transformPull2 = (self, f) => fromChannel3(fromTransform((_, scope) => flatM var toChannel2 = (stream) => stream.channel; var callback3 = (f, options) => fromChannel3(callbackArray(f, options)); var empty4 = /* @__PURE__ */ fromChannel3(empty3); -var suspend4 = (stream) => fromChannel3(suspend3(() => stream().channel)); var unwrap3 = (effect) => fromChannel3(unwrap(map5(effect, toChannel2))); -var map8 = /* @__PURE__ */ dual(2, (self, f) => suspend4(() => { - let i = 0; - return fromChannel3(map7(self.channel, map2((o) => f(o, i++)))); -})); var merge3 = /* @__PURE__ */ dual((args) => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel3(merge2(toChannel2(self), toChannel2(that), options))); var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (upstream, scope) => sync3(() => { let done; @@ -8438,12 +8267,7 @@ var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (up }); return suspend2(() => done ? done : pull); }))); -var decodeText = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => suspend4(() => { - const decoder = new TextDecoder(options?.encoding); - return map8(self, (chunk) => decoder.decode(chunk, { - stream: true - })); -})); +var decodeText2 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => self.channel.pipe(pipeTo(decodeText(options?.encoding)), fromChannel3)); var splitLines2 = (self) => self.channel.pipe(pipeTo(splitLines()), fromChannel3); var run2 = /* @__PURE__ */ dual(2, (self, sink) => scopedWith2((scope) => toPullScoped(self.channel, scope).pipe(flatMap3((upstream) => sink.transform(upstream, scope)), map5(([a]) => a)))); var runCollect = (self) => runFold(self.channel, () => [], (acc, chunk) => { @@ -8569,10 +8393,14 @@ var ulidString = (timestampMillis, bytes) => { }; // node_modules/effect/dist/internal/uuid.js -var hex = (byte) => byte.toString(16).padStart(2, "0"); +var hex = /* @__PURE__ */ Array.from({ + length: 256 +}, (_, byte) => byte.toString(16).padStart(2, "0")); var stringify = (bytes) => { - const segments = [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)]; - return segments.map((segment) => Array.from(segment, hex).join("")).join("-"); + if (bytes.length < 16) { + return [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)].map((segment) => Array.from(segment, (byte) => hex[byte]).join("")).join("-"); + } + return hex[bytes[0]] + hex[bytes[1]] + hex[bytes[2]] + hex[bytes[3]] + "-" + hex[bytes[4]] + hex[bytes[5]] + "-" + hex[bytes[6]] + hex[bytes[7]] + "-" + hex[bytes[8]] + hex[bytes[9]] + "-" + hex[bytes[10]] + hex[bytes[11]] + hex[bytes[12]] + hex[bytes[13]] + hex[bytes[14]] + hex[bytes[15]]; }; var randomBytes = () => globalThis.crypto.getRandomValues(new Uint8Array(16)); function v4Bytes(bytes = randomBytes()) { @@ -8691,23 +8519,26 @@ var defaultTeardown = (exit, onExit) => { return onExit(getErrorExitCode(squash(exit.cause))); }; var makeRunMain = (f) => dual((args) => isEffect2(args[0]), (effect, options) => { - const fiber = options?.disableErrorReporting === true ? runFork2(effect) : runFork2(tapCause2(effect, (cause) => { + const main = options?.disableErrorReporting === true ? effect : tapCause2(effect, (cause) => { if (hasInterruptsOnly2(cause)) return void_3; const isReported = getErrorReported(squash(cause)); return isReported ? logError(cause) : void_3; - })); - try { - const keepAlive = globalThis.setInterval(constVoid, 2147483647); - fiber.addObserver(() => { - clearInterval(keepAlive); - }); - } catch {} - const teardown = options?.teardown ?? defaultTeardown; - return f({ - fiber, - teardown }); + const teardown = options?.teardown ?? defaultTeardown; + runFork2(withFiber2((fiber) => { + try { + const keepAlive = globalThis.setInterval(constVoid, 2147483647); + fiber.addObserver(() => { + clearInterval(keepAlive); + }); + } catch {} + f({ + fiber, + teardown + }); + return main; + })); }); var errorExitCode = "~effect/Runtime/errorExitCode"; var getErrorExitCode = (u) => { @@ -8834,7 +8665,7 @@ var makeHandle = (params) => Object.setPrototypeOf({ ...params }, HandleProto); var make20 = (spawn) => { - const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); + const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText2(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); const streamLines = (command, options) => splitLines2(streamString(command, options)); return ChildProcessSpawner.of({ spawn, @@ -9003,6 +8834,7 @@ var handleErrnoException = (module, method) => (err, [path]) => { reason = "NotFound"; break; case "EACCES": + case "EPERM": reason = "PermissionDenied"; break; case "EEXIST": @@ -9031,66 +8863,149 @@ var handleErrnoException = (module, method) => (err, [path]) => { }); }; +// node_modules/@effect/platform-node-shared/dist/NodeSink.js +import { finished } from "node:stream"; + +// node_modules/@effect/platform-node-shared/dist/internal/stream.js +var destroyStream = (stream, cleanup, onDestroyed) => { + if (!("closed" in stream)) { + cleanup(); + onDestroyed?.(); + return; + } + const onDone = () => { + clearImmediate(immediate); + stream.off("error", onDone); + stream.off("close", onDone); + onDestroyed?.(); + }; + const onClosed = () => { + if (stream.closed) { + onDone(); + } else { + immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + } + }; + let immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + stream.once("error", onDone); + stream.once("close", onDone); + cleanup(); + if (!stream.closed) { + stream.destroy(); + } +}; + // node_modules/@effect/platform-node-shared/dist/NodeSink.js var fromWritable = (options) => fromChannel2(mapDone(fromWritableChannel(options), (_) => [_])); var fromWritableChannel = (options) => fromTransform((pull) => { const writable = options.evaluate(); - return succeed6(pullIntoWritable({ + const write = pullIntoWritable({ ...options, writable, pull - })); -}); -var pullIntoWritable = (options) => options.pull.pipe(flatMap3((chunk) => { - let i = 0; - return callback2((resume) => { - let cancelled = false; - const loop = () => { - for (;i < chunk.length; ) { - if (cancelled) { - return; - } - const success = options.writable.write(chunk[i++], options.encoding); - if (!success) { - if (!cancelled) { - options.writable.once("drain", loop); + }); + return succeed6(options.endOnDone === false ? write : onError2(write, (cause) => isDoneCause(cause) ? void_3 : releaseWritable(writable))); +}); +var releaseWritable = (writable) => callback2((resume) => { + const onDestroyed = () => resume(void_3); + if (writable.closed) { + const cleanup = finished(writable, { + readable: false + }, () => { + cleanup(); + onDestroyed(); + }); + } else { + destroyStream(writable, constVoid, onDestroyed); + } +}); +var pullIntoWritable = (options) => withFiber2((fiber) => { + const dispatcher = fiber.currentDispatcher; + const completion = makeUnsafe2(); + const failure = makeUnsafe2(); + const onError = (error) => doneUnsafe(failure, failSync2(() => options.onError(error))); + let errorEmitted = false; + const onStreamError = (error) => { + errorEmitted = true; + onError(error); + }; + options.writable.on("error", onStreamError); + const cleanup = finished(options.writable, { + readable: false + }, (error) => { + if (error) { + onError(error); + } else { + doneUnsafe(completion, void_3); + } + }); + return options.pull.pipe(flatMap3((chunk) => { + let i = 0; + return callback2((resume) => { + let cancelled = false; + const onFinish = () => dispatcher.scheduleTask(loop, 0); + const loop = () => { + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + for (;i < chunk.length; ) { + if (cancelled) { + return; + } + const success = options.writable.write(chunk[i++], options.encoding, (error) => { + if (!error) + return; + if (options.writable.closed) { + onError(error); + } else { + dispatcher.scheduleTask(() => onError(error), 0); + } + }); + if (!success) { + if (!cancelled) { + options.writable.once("drain", loop); + options.writable.once("finish", onFinish); + } + return; } - return; } - } - if (!cancelled) { - resume(void_3); - } - }; - loop(); - return sync3(() => { - cancelled = true; - options.writable.off("drain", loop); + if (!cancelled) { + resume(void_3); + } + }; + loop(); + return sync3(() => { + cancelled = true; + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + }); }); - }); -}), forever2({ - disableYield: true -}), options.endOnDone !== false ? catchDone((_) => { - if ("closed" in options.writable && options.writable.closed) { - return done2(_); - } - return callback2((resume) => { - const onFinish = () => resume(done2(_)); - options.writable.once("finish", onFinish); + }), forever2({ + disableYield: true + }), options.endOnDone !== false ? catchDone((_) => { options.writable.end(); - return sync3(() => { - options.writable.off("finish", onFinish); - }); - }); -}) : identity, raceFirst2(callback2((resume) => { - const onError = (error) => resume(fail6(options.onError(error))); - options.writable.once("error", onError); - return sync3(() => { - options.writable.off("error", onError); - }); -}))); + return andThen2(_await(completion), done2(_)); + }) : identity, raceFirst2(_await(failure)), ensuring2(sync3(() => { + cleanup(); + const removeErrorListener = () => { + options.writable.off("error", onStreamError); + options.writable.off("error", removeErrorListener); + options.writable.off("close", removeErrorListener); + }; + if (options.writable.errored && !options.writable.closed && !errorEmitted) { + options.writable.once("error", removeErrorListener); + options.writable.once("close", removeErrorListener); + } else { + removeErrorListener(); + } + }))); +}); // node_modules/@effect/platform-node-shared/dist/NodeStream.js +import { finished as finished2, Readable } from "node:stream"; var fromReadable = (options) => fromChannel3(fromReadableChannel(options)); var fromReadableChannel = (options) => fromTransform((_, scope) => readableToPullUnsafe({ scope, @@ -9107,17 +9022,14 @@ var readableToPullUnsafe = (options) => { function onReadable() { latch.openUnsafe(); } - function onError(error) { - exit.current = fail5(options.onError(error)); - latch.openUnsafe(); - } - function onEnd() { - exit.current = fail5(Done2()); - latch.openUnsafe(); - } readable.on("readable", onReadable); - readable.once("error", onError); - readable.once("end", onEnd); + const cleanup = finished2(readable, { + readable: true, + writable: false + }, (error) => { + exit.current ??= fail5(error ? options.onError(error) : Done2()); + latch.openUnsafe(); + }); const pull = suspend2(function loop() { let item = options.readable.read(options.chunkSize); if (item === null) { @@ -9141,10 +9053,10 @@ var readableToPullUnsafe = (options) => { }); return as2(addFinalizer2(options.scope, sync3(() => { readable.off("readable", onReadable); - readable.off("error", onError); - readable.off("end", onEnd); - if (closeOnDone && "closed" in options.readable && !options.readable.closed) { - options.readable.destroy(); + if (closeOnDone) { + destroyStream(readable, cleanup); + } else { + cleanup(); } })), pull); }; @@ -9469,6 +9381,7 @@ var make22 = /* @__PURE__ */ gen2(function* () { const signalGroup = (signal) => killProcessGroup(command, childProcess, signal).pipe(catch_2(() => killProcess(command, childProcess, signal))); yield* signalGroup(options?.killSignal ?? "SIGTERM"); if (isUndefined(options?.forceKillAfter)) { + yield* _await(exitSignal); yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis); } else { yield* awaitProcessExit(childProcess, exitSignal, toMillis(options.forceKillAfter)); @@ -10062,14 +9975,14 @@ var readLink = /* @__PURE__ */ (() => { return (path) => nodeReadLink(path); })(); var realPath = /* @__PURE__ */ (() => { - const nodeRealPath = /* @__PURE__ */ effectify(NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); + const nodeRealPath = /* @__PURE__ */ effectify(process.platform === "win32" ? NFS.realpath.native : NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); return (path) => nodeRealPath(path); })(); var rename2 = /* @__PURE__ */ (() => { const nodeRename = /* @__PURE__ */ effectify(NFS.rename, /* @__PURE__ */ handleErrnoException("FileSystem", "rename"), /* @__PURE__ */ handleBadArgument("rename")); return (oldPath, newPath) => nodeRename(oldPath, newPath); })(); -var makeFileInfo = (stat) => try_2({ +var makeFileInfo = (stat, method = "stat") => try_2({ try: () => ({ type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown", mtime: fromNullishOr(stat.mtime), @@ -10086,14 +9999,16 @@ var makeFileInfo = (stat) => try_2({ blksize: stat.blksize !== undefined ? some2(bytes(stat.blksize)) : none2(), blocks: fromNullishOr(stat.blocks) }), - catch: handleBadArgument("stat") + catch: handleBadArgument(method) }); -var stat2 = /* @__PURE__ */ (() => { - const nodeStat = /* @__PURE__ */ effectify(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat")); +var statFactory = (method, nodeStatFn) => { + const nodeStat = effectify(nodeStatFn, handleErrnoException("FileSystem", method), handleBadArgument(method)); return (path) => flatMap3(nodeStat(path, { bigint: true - }), makeFileInfo); -})(); + }), (stat) => makeFileInfo(stat, method)); +}; +var stat2 = /* @__PURE__ */ statFactory("stat", NFS.stat); +var lstat2 = /* @__PURE__ */ statFactory("lstat", NFS.lstat); var symlink2 = /* @__PURE__ */ (() => { const nodeSymlink = /* @__PURE__ */ effectify(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink")); return (target, path) => nodeSymlink(target, path); @@ -10176,6 +10091,7 @@ var makeFileSystem = /* @__PURE__ */ map5(/* @__PURE__ */ serviceOption2(WatchBa copyFile: copyFile2, glob: glob2, link: link3, + lstat: lstat2, makeDirectory, makeTempDirectory, makeTempDirectoryScoped, @@ -10315,9 +10231,6 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readline.emitKeypressEvents(stdin, rl); rl.on("line", onLine); rl.once("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(true); - } return { rl, onClose, @@ -10331,9 +10244,6 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readlineActive = false; rl.off("line", onLine); rl.off("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(false); - } rl.close(); if (inputEnded) { endUnsafe(lines); @@ -10341,6 +10251,14 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu })), idleTimeToLive: "10 millis" }); + const setRawMode = (enabled) => sync3(() => { + if (stdin.isTTY) + stdin.setRawMode(enabled); + }); + const rawModeRef = yield* make13({ + acquire: acquireRelease2(setRawMode(true), () => setRawMode(false)), + idleTimeToLive: "10 millis" + }); const columns = sync3(() => stdout.columns ?? 0); const rows = sync3(() => stdout.rows ?? 0); const readInput = gen2(function* () { @@ -10375,6 +10293,7 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu handleEnd(); } else { yield* get3(rlRef); + yield* get3(rawModeRef); stdin.once("end", handleEnd); } return queue; @@ -10493,7 +10412,7 @@ class CommandError extends TaggedError3()("CommandError", { }) { } var error = (command, cause) => new CommandError({ command, exitCode: -1, stderr: String(cause) }); -var collectText = (stream) => stream.pipe(decodeText(), runFold2(() => "", (all, chunk) => all + chunk)); +var collectText = (stream) => stream.pipe(decodeText2(), runFold2(() => "", (all, chunk) => all + chunk)); var retainedStderrLength = 16 * 1024; class Service3 extends Service()("@timmo001/workflows/CommandExecutor") { @@ -10546,8 +10465,8 @@ var layer14 = effect(Service3, gen2(function* () { stdin: "inherit" })); let stderrTail = ""; - const stdout = handle.stdout.pipe(decodeText(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); - const stderr = handle.stderr.pipe(decodeText(), runForEach2((chunk) => sync3(() => { + const stdout = handle.stdout.pipe(decodeText2(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); + const stderr = handle.stderr.pipe(decodeText2(), runForEach2((chunk) => sync3(() => { process.stderr.write(chunk); stderrTail = `${stderrTail}${chunk}`.slice(-retainedStderrLength); }))); diff --git a/.github/actions/prepare-arch-bin/dist/index.js b/.github/actions/prepare-arch-bin/dist/index.js index 91a52944..1ee430e8 100644 --- a/.github/actions/prepare-arch-bin/dist/index.js +++ b/.github/actions/prepare-arch-bin/dist/index.js @@ -785,6 +785,10 @@ function assignProperty(self, key, value) { } } function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } for (const key of Reflect.ownKeys(source)) { if (Object.prototype.propertyIsEnumerable.call(source, key)) { assignProperty(self, key, source[key]); @@ -875,7 +879,7 @@ class CauseImpl { toJSON() { return { _id: "Cause", - failures: this.reasons.map((f) => f.toJSON()) + reasons: this.reasons.map((f) => f.toJSON()) }; } toString() { @@ -1654,9 +1658,21 @@ var bigint2 = /* @__PURE__ */ BigInt(2); var bigint10 = /* @__PURE__ */ BigInt(10); var bigint1e3 = /* @__PURE__ */ BigInt(1000); var bigint1e6 = /* @__PURE__ */ BigInt(1e6); +var bigint1e9 = /* @__PURE__ */ BigInt(1e9); +var bigintNanosPerMinute = /* @__PURE__ */ BigInt(60000000000); +var bigintNanosPerHour = /* @__PURE__ */ BigInt(3600000000000); +var bigintNanosPerDay = /* @__PURE__ */ BigInt(86400000000000); +var bigintNanosPerWeek = /* @__PURE__ */ BigInt(604800000000000); var roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input))); var roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6); var fromNanosNumber = (nanos) => make3(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos); +var nanosToUnit = (nanos, divisor) => { + const value = Number(nanos); + if (Number.isFinite(value)) + return value / divisor; + const scale = BigInt(divisor); + return Number(nanos / scale) + Number(nanos % scale) / divisor; +}; var parseNanos = (input, scale) => { const decimalIndex = input.indexOf("."); if (decimalIndex === -1) @@ -1672,6 +1688,13 @@ var divideTiesAwayFromZero = (numerator, denominator) => { const rounded = absolute / denominator + (absolute % denominator * bigint2 >= denominator ? bigint1 : bigint0); return numerator < bigint0 ? -rounded : rounded; }; +var fromMillisString = (input, scale) => { + const millis = Number(input) * scale; + if (!Number.isFinite(millis)) + return make3(millis); + const nanos = parseNanos(input, BigInt(scale) * bigint1e6); + return make3(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos); +}; var DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; var fromInputUnsafe = (input) => { switch (typeof input) { @@ -1696,26 +1719,25 @@ var fromInputUnsafe = (input) => { if (unit === "micro" || unit === "micros") { return nanos(parseNanos(valueStr, bigint1e3)); } - const value = Number(valueStr); switch (unit) { case "milli": case "millis": - return millis(value); + return fromMillisString(valueStr, 1); case "second": case "seconds": - return seconds(value); + return fromMillisString(valueStr, 1000); case "minute": case "minutes": - return minutes(value); + return fromMillisString(valueStr, 60000); case "hour": case "hours": - return hours(value); + return fromMillisString(valueStr, 3600000); case "day": case "days": - return days(value); + return fromMillisString(valueStr, 86400000); case "week": case "weeks": - return weeks(value); + return fromMillisString(valueStr, 604800000); } break; } @@ -1737,7 +1759,8 @@ var fromInputUnsafe = (input) => { if (input[0] === Infinity || input[1] === Infinity) { return infinity; } - return fromNanosNumber(input[0] * 1e9 + input[1]); + const nanos = input[0] * 1e9 + input[1]; + return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make3(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos); } const obj = input; let millis = 0; @@ -1753,13 +1776,42 @@ var fromInputUnsafe = (input) => { millis += obj.seconds * 1000; if (obj.milliseconds) millis += obj.milliseconds; - if (!obj.microseconds && !obj.nanoseconds) - return make3(millis); - return fromNanosNumber(millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0)); + if (!obj.microseconds && !obj.nanoseconds) { + if (!Number.isFinite(millis)) + return make3(millis); + const exact = sumObjectNanos(obj); + return exact === undefined || BigInt(millis) * bigint1e6 === exact ? make3(millis) : make3(exact); + } + const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0); + const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : undefined; + return exact === undefined ? fromNanosNumber(nanos) : make3(exact); } } return invalid(input); }; +var isIntegerOrUnset = (n) => !n || Number.isInteger(n); +var sumObjectNanos = (obj) => { + if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds)) + return; + let nanos = bigint0; + if (obj.weeks) + nanos += BigInt(obj.weeks) * bigintNanosPerWeek; + if (obj.days) + nanos += BigInt(obj.days) * bigintNanosPerDay; + if (obj.hours) + nanos += BigInt(obj.hours) * bigintNanosPerHour; + if (obj.minutes) + nanos += BigInt(obj.minutes) * bigintNanosPerMinute; + if (obj.seconds) + nanos += BigInt(obj.seconds) * bigint1e9; + if (obj.milliseconds) + nanos += BigInt(obj.milliseconds) * bigint1e6; + if (obj.microseconds) + nanos += BigInt(obj.microseconds) * bigint1e3; + if (obj.nanoseconds) + nanos += BigInt(obj.nanoseconds); + return nanos; +}; var invalid = (input) => { throw new Error(`Invalid Input: ${input}`); }; @@ -1868,14 +1920,9 @@ var infinity = /* @__PURE__ */ make3(Infinity); var negativeInfinity = /* @__PURE__ */ make3(-Infinity); var nanos = (nanos) => make3(nanos); var millis = (millis) => make3(millis); -var seconds = (seconds) => make3(seconds * 1000); -var minutes = (minutes) => make3(minutes * 60000); -var hours = (hours) => make3(hours * 3600000); -var days = (days) => make3(days * 86400000); -var weeks = (weeks) => make3(weeks * 604800000); var toMillis = (self) => match3(fromInputUnsafe(self), { onMillis: identity, - onNanos: (nanos) => Number(nanos) / 1e6, + onNanos: (nanos) => nanosToUnit(nanos, 1e6), onInfinity: () => Infinity, onNegativeInfinity: () => -Infinity }); @@ -1957,7 +2004,7 @@ var setTimer = "setImmediate" in globalThis ? (f) => { const timer = setTimeout(f, 0); return () => clearTimeout(timer); }; -var setImmediate = (f) => { +var setImmediate2 = (f) => { try { return setTimer(f); } catch { @@ -1997,7 +2044,7 @@ class MixedScheduler { setImmediate; constructor(executionMode = "async", setImmediateFn) { this.executionMode = executionMode; - this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate2); } shouldYield(fiber) { return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; @@ -2011,7 +2058,7 @@ class MixedSchedulerDispatcher { tasks = /* @__PURE__ */ new PriorityBuckets; running = undefined; setImmediate; - constructor(setImmediateFn = setImmediate) { + constructor(setImmediateFn = setImmediate2) { this.setImmediate = setImmediateFn; } scheduleTask(task, priority) { @@ -2255,10 +2302,7 @@ class Interrupt extends ReasonBase { } } var causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); -var findFail = (self) => { - const reason = self.reasons.find(isFailReason); - return reason ? succeed2(reason) : fail2(self); -}; +var hasFails = (self) => self.reasons.some(isFailReason); var findError = (self) => { for (let i = 0;i < self.reasons.length; i++) { const reason = self.reasons[i]; @@ -2268,6 +2312,9 @@ var findError = (self) => { } return fail2(self); }; +var hasDies = (self) => self.reasons.some(isDieReason); +var causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +var findRecoverableError = (self) => hasDies(self) ? fail2(causeElectDefects(self)) : findError(self); var hasInterrupts = (self) => self.reasons.some(isInterruptReason); var hasInterruptsOnly = (self) => self.reasons.length > 0 && self.reasons.every(isInterruptReason); var causeMap = /* @__PURE__ */ dual(2, (self, f) => { @@ -2328,12 +2375,14 @@ var causePrettyErrors = (self, options) => { } return errors; }; -var causePrettyError = (original, annotations, options) => { +var causePrettyError = (original, annotations, options, seen = new Set) => { const kind = typeof original; let error; if (original && kind === "object") { + seen.add(original); + const cause = original.cause; error = new globalThis.Error(causePrettyMessage(original), { - cause: original.cause ? causePrettyError(original.cause) : undefined + cause: cause !== undefined && !seen.has(cause) ? causePrettyError(cause, undefined, undefined, seen) : undefined }); if (typeof original.name === "string") { error.name = original.name; @@ -2544,7 +2593,11 @@ class FiberImpl { } else if (this._asyncContext !== undefined) { const asyncContext = this._asyncContext; this._asyncContext = undefined; - return asyncContext.runInAsyncScope(this.evaluate, this, effect); + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } } else if (this._yielded !== undefined) { const yielded = this._yielded; this._yielded = undefined; @@ -2849,7 +2902,6 @@ var tryPromise = (options) => { } }, f.length !== 0); }; -var withFiberId = (f) => withFiber((fiber) => f(fiber.id)); var callbackOptions = /* @__PURE__ */ function() { const Proto = /* @__PURE__ */ makePrimitiveProto({ op: "Async", @@ -2870,9 +2922,9 @@ var callbackOptions = /* @__PURE__ */ function() { if (yielded !== false) return yielded; yielded = true; - fiber._yielded = () => { + fiber.yieldWith(() => { resumed = true; - }; + }); if (controller === undefined && onCancel === undefined) { return Yield; } @@ -3156,10 +3208,7 @@ var exitMap = /* @__PURE__ */ dual(2, (self, f) => self._tag === "Success" ? exi var exitMapError = /* @__PURE__ */ dual(2, (self, f) => { if (self._tag === "Success") return self; - const error = findError(self.cause); - if (isFailure2(error)) - return self; - return exitFail(f(error.success)); + return exitFailCause(causeMap(self.cause, f)); }); var exitZipRight = /* @__PURE__ */ dual(2, (self, that) => exitIsSuccess(self) ? that : self); var exitAsVoidAll = (exits) => { @@ -3223,7 +3272,7 @@ var catchCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(s const eb = filter(cause); return isFailure2(eb) ? failCause(eb.failure) : f(eb.success, cause); })); -var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findError, (e) => f(e))); +var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findRecoverableError, (e) => f(e))); var tapCause = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => andThen(f(cause), failCause(cause)))); var tapCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(self, (cause) => { const result = filter(cause); @@ -3234,7 +3283,7 @@ var tapCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(sel })); var tapError = /* @__PURE__ */ dual(2, (self, f) => tapCauseFilter(self, findError, (e) => f(e))); var catchIf = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, predicate, f, orElse) => catchCause(self, (cause) => { - const error = findError(cause); + const error = findRecoverableError(cause); if (isFailure2(error)) return failCause(error.failure); if (!predicate(error.success)) { @@ -3246,7 +3295,7 @@ var catchTag = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, k, f, or const pred = Array.isArray(k) ? (e) => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); return catchIf(self, pred, f, orElse); }); -var mapError = /* @__PURE__ */ dual(2, (self, f) => catch_(self, (error) => failSync(() => f(error)))); +var mapError = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => failCause(causeMap(cause, f)))); var orDie = (self) => catch_(self, die); var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { if (!options?.log) { @@ -3258,12 +3307,25 @@ var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) = const logEffect = logWithLevel(options.log === true ? undefined : options.log); return matchCauseEffect(self, { onFailure(cause) { - const failure = findFail(cause); - return isFailure2(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); }, onSuccess: (_) => void_ }); }); +var ignoreCause = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { + if (!options?.log) { + return matchCauseEffect(self, { + onFailure: (_) => void_, + onSuccess: (_) => void_ + }); + } + const logEffect = logWithLevel(options.log === true ? undefined : options.log); + return matchCauseEffect(self, { + onFailure: (cause) => options.message === undefined ? logEffect(cause) : logEffect(options.message, cause), + onSuccess: (_) => void_ + }); +}); var result = (self) => matchEager(self, { onFailure: fail2, onSuccess: succeed2 @@ -3298,16 +3360,16 @@ var makeMatch = (op, onFailure) => { return MatchImpl; }; var MatchImpl = /* @__PURE__ */ makeMatch("Match", function(cause, fiber) { - const fail = cause.reasons.find(isFailReason); - if (fail === undefined) - return failCause(cause); + const error = findRecoverableError(cause); + if (isFailure2(error)) + return failCause(error.failure); const handlers = this.payload; - return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(fail.error) : internalCall(() => handlers.onFailure(fail.error))); + return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))); }); var matchEffect = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, { onFailure: (cause) => { - const fail = cause.reasons.find(isFailReason); - return fail ? options.onFailure(fail.error) : failCause(cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.onFailure(error.success); }, onSuccess: options.onSuccess })); @@ -3316,9 +3378,9 @@ var matchEager = /* @__PURE__ */ dual(2, (self, options) => { if (effectIsExit(self)) { if (self._tag === "Success") return exitSucceed(options.onSuccess(self.value)); - const error = findError(self.cause); + const error = findRecoverableError(self.cause); if (isFailure2(error)) - return self; + return exitFailCause(error.failure); return exitSucceed(options.onFailure(error.success)); } return match4(self, options); @@ -3375,17 +3437,17 @@ var runFinalizer = (finalizer, exit_) => { return exitDie(defect); } }; -var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeCombine(exit_.cause, cause))); +var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); var scopeCloseFinalizers = /* @__PURE__ */ fnUntraced(function* (self, finalizers, exit_) { let exits = []; const fibers = []; - const arr = Array.from(finalizers.values()); + const arr = Array.from(finalizers); const parent = getCurrentFiber(); for (let i = arr.length - 1;i >= 0; i--) { - const finalizer = arr[i]; + const [key, finalizer] = arr[i]; if (self.strategy === "sequential") { exits.push(yield* exit(runFinalizer(finalizer, exit_))); - } else { + } else if (key !== parent) { fibers.push(forkUnsafe(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); } } @@ -3578,15 +3640,9 @@ var all = (arg, options) => { } else if (options?.discard) { return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options); } - return suspend(() => { - const out = {}; - return as(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => { - assignProperty(out, key, value); - }), { - discard: true, - concurrency: options?.concurrency - }), out); - }); + return suspend(() => map3(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => [key, value]), { + concurrency: options?.concurrency + }), Object.fromEntries)); }; var whileLoop = /* @__PURE__ */ makePrimitive({ op: "While", @@ -3725,7 +3781,7 @@ var iterateConcurrentImpl = (options) => { const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); if (reasons.length > 0) { const cause = causeFromReasons(reasons); - terminal = exitFailCause(terminal._tag === "Failure" ? causeCombine(terminal.cause, cause) : cause); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); } } } else { @@ -3807,14 +3863,13 @@ var forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterrupt } return child; }; +var fiberScopeFinalizer = (fiber) => () => withFiber((current) => current === fiber ? void_ : fiberInterrupt(fiber)); var forkIn = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, scope, options) => withFiber((parent) => { - const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + const fiber = scope.state._tag === "Closed" ? new FiberImpl(parent.context) : forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); if (!fiber._exit) { if (scope.state._tag !== "Closed") { - const key = {}; - const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); - scopeAddFinalizerUnsafe(scope, key, finalizer); - fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + scopeAddFinalizerUnsafe(scope, fiber, fiberScopeFinalizer(fiber)); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, fiber)); } else { fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); } @@ -3851,7 +3906,7 @@ var fiberRunIn = /* @__PURE__ */ dual(2, (self, scope) => { return self; } scopeRemoveFinalizerUnsafe(scope, self); - scopeAddFinalizerUnsafe(scope, self, () => fiberInterrupt(self)); + scopeAddFinalizerUnsafe(scope, self, fiberScopeFinalizer(self)); self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, self)); return self; }); @@ -4303,7 +4358,6 @@ var die2 = causeDie; var hasInterruptsOnly2 = hasInterruptsOnly; var map4 = causeMap; var squash = causeSquash; -var findError2 = findError; var isDone2 = isDone; var Done2 = Done; var done2 = done; @@ -4313,6 +4367,7 @@ var UnknownError2 = UnknownError; var succeed4 = exitSucceed; var failCause2 = exitFailCause; var fail5 = exitFail; +var interrupt2 = exitInterrupt; var void_2 = exitVoid; var isSuccess3 = exitIsSuccess; var isFailure3 = exitIsFailure; @@ -4497,8 +4552,8 @@ var mergeAllEffect = (layers, memoMap, scope) => { concurrency: layers.length }).pipe(map3((context) => mergeAll(...context))); }; -var mergeAll2 = (...layers) => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); -var provideWith = (self, that, f) => fromBuild((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); +var mergeAll2 = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +var provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); var provide2 = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, identity)); var provideMerge = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, (self, that) => merge(that, self))); @@ -4700,11 +4755,10 @@ var provideLayer = (self, layer, options) => scopedWith((scope) => flatMap2(opti var provide3 = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll2(...source) : source, options)); // node_modules/effect/dist/internal/schedule.js -var findErrorOnly = (cause) => cause.reasons.every(isFailReason) ? findError(cause) : fail2(cause); var retryOrElse = /* @__PURE__ */ dual(3, (self, policy, orElse) => flatMap2(toStepWithMetadata(policy), (step) => { let meta = CurrentMetadata.defaultValue(); let lastError; - const loop = catchCauseFilter(suspend(() => provideService(self, CurrentMetadata, meta)), findErrorOnly, (error) => { + const loop = catchCauseFilter(suspend(() => provideService(self, CurrentMetadata, meta)), findRecoverableError, (error) => { lastError = error; return flatMap2(step(error), (meta_) => { meta = meta_; @@ -4758,6 +4812,7 @@ var callback2 = callback; var never2 = never; var gen2 = gen; var fail6 = fail3; +var failSync2 = failSync; var failCause3 = failCause; var failCauseSync2 = failCauseSync; var die3 = die; @@ -4780,6 +4835,7 @@ var tapError2 = tapError; var tapCause2 = tapCause; var retry2 = retry; var ignore2 = ignore; +var ignoreCause2 = ignoreCause; var timeoutOrElse2 = timeoutOrElse; var sleep2 = sleep; var raceFirst2 = raceFirst; @@ -4797,7 +4853,7 @@ var ensuring2 = ensuring; var onError2 = onError; var onExitPrimitive2 = onExitPrimitive; var onExit2 = onExit; -var interrupt2 = interrupt; +var interrupt3 = interrupt; var uninterruptible2 = uninterruptible; var uninterruptibleMask2 = uninterruptibleMask; var forever3 = forever; @@ -4812,16 +4868,23 @@ var fn2 = fn; var clockWith2 = clockWith; var logError = /* @__PURE__ */ logWithLevel("Error"); var effectify = (fn, onError, onSyncError) => (...args) => callback2((resume) => { + let synchronous = true; + let pending; try { fn(...args, (err, result) => { - if (err) { - resume(onError ? suspend2(() => fail6(onError(err, args))) : fail6(err)); + const effect = err ? onError ? suspend2(() => fail6(onError(err, args))) : fail6(err) : succeed6(result); + if (synchronous) { + pending ??= effect; } else { - resume(succeed6(result)); + resume(effect); } }); } catch (err) { - resume(onSyncError ? fail6(onSyncError(err, args)) : die3(err)); + pending = onSyncError ? fail6(onSyncError(err, args)) : die3(err); + } + synchronous = false; + if (pending) { + resume(pending); } }); var mapEager2 = mapEager; @@ -5232,7 +5295,7 @@ var defaultLeafHook = (issue) => { } } }; -var defaultCheckHook = (issue) => findMessage(issue.issue) ?? findMessage(issue); +var defaultCheckHook = (issue) => findMessage(issue) ?? findMessage(issue.issue); function formatInput(issue) { return hasInput(issue) ? format(issue.input) : undefined; } @@ -5244,6 +5307,13 @@ function getExpectedMessage(expected, issue) { const input = formatInput(issue); return input === undefined ? `Expected ${expected}` : `Expected ${expected}, got ${input}`; } +function getFilterMessage(issue, checkHook) { + const message = checkHook(issue); + if (message !== undefined || issue.issue._tag !== "InvalidValue") + return message; + const expected = findExpected(issue.issue); + return expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); +} function formatCheck(check) { const expected = check.annotations?.expected; if (typeof expected === "string") @@ -5259,44 +5329,33 @@ function makeFormatterDefault() { return (issue) => formatIssue(issue, ""); } var defaultFormatter = /* @__PURE__ */ makeFormatterDefault(); -function formatIssue(issue, path) { +function formatIssue(issue, path, messageOverride) { let message; switch (issue._tag) { - case "Filter": { - const annotated = defaultCheckHook(issue); - if (annotated !== undefined) { - message = annotated; - } else { - if (issue.issue._tag !== "InvalidValue") { - return formatIssue(issue.issue, path); - } - const expected = findExpected(issue.issue); - message = expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); - } - break; - } + case "Filter": + return formatIssue(issue.issue, path, messageOverride ?? getFilterMessage(issue, defaultCheckHook)); case "Encoding": - return formatIssue(issue.issue, path); + return formatIssue(issue.issue, path, messageOverride); case "Pointer": - return formatIssue(issue.issue, path + formatPath(issue.path)); + return formatIssue(issue.issue, path + formatPath(issue.path), messageOverride); case "Composite": case "AnyOf": { if (issue._tag === "Composite" || issue.issues.length > 0) { - return issue.issues.map((issue) => formatIssue(issue, path)).join(` + return issue.issues.map((issue) => formatIssue(issue, path, messageOverride)).join(` `); } - message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); + message = messageOverride ?? findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); break; } default: - message = defaultLeafHook(issue); + message = messageOverride ?? defaultLeafHook(issue); break; } return path ? `${message} at ${path}` : message; } function findMessage(issue) { - if (issue._tag === "Pointer") + if (issue._tag === "Pointer" || issue._tag === "Composite") return; if (issue._tag === "Encoding") return findMessage(issue.issue); @@ -5554,7 +5613,12 @@ var Declaration = class extends ASTNodeImpl { return (input, options) => { if (input === missing) return missingExit; - return (run ??= this.run(this.typeParameters))(input, this, options); + run ??= this.run(this.typeParameters); + try { + return run(input, this, options); + } catch (error) { + return die3(error); + } }; } _rebuild(recur, checks, encodingChecks, run, encodingRun) { @@ -5763,7 +5827,7 @@ var Arrays = class extends ASTNodeImpl { input, len, tailThreshold: Math.max(elementLen, len - tailLen), - output: new globalThis.Array(len), + output: [], issues: undefined, options }; @@ -5872,7 +5936,7 @@ var wrapPropertyKeyIssue = (s, ast, key, exit) => { return fail5(new Composite(ast, [pointer], s.input, s.options)); } }; -var FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?"; +var FINITE_PATTERN = "[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?"; function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) { let stringKeys; let symbolKeys; @@ -6111,9 +6175,15 @@ var Objects = class extends ASTNodeImpl { if (indexCount) return makeFallback(); let fallback; - const resume = (state, index, pending) => { + const resume = (snapshot, index, pending) => { const property = properties[index]; return flatMap3(exit2(pending), (exit) => { + const state = { + ...snapshot, + out: { + ...snapshot.out + } + }; const terminal = stepProperty(state, property, exit); if (terminal) return terminal; @@ -6243,9 +6313,6 @@ function struct(fields, checks, annotations) { function getAST(self) { return self.ast; } -function tuple(elements, checks = undefined) { - return new Arrays(false, elements.map((e) => e.ast), [], undefined, checks); -} function union(members, options, checks) { return new Union(members.map(getAST), options, undefined, checks); } @@ -7117,6 +7184,16 @@ var unknownToStringTree = /* @__PURE__ */ new Link(StringTree, /* @__PURE__ */ p // node_modules/effect/dist/internal/schema/interpreter.js var flatMapTransformation = (result, current, f) => result === sameExit ? f(current) : flatMapEager2(result, f); function compileTransformation(transformation) { + const apply = compileTransformationUnsafe(transformation); + return (result, current, options) => { + try { + return apply(result, current, options); + } catch (error) { + return die3(error); + } + }; +} +function compileTransformationUnsafe(transformation) { if (transformation._tag === "Middleware") { return (result, current, options) => { const transformed = result === sameExit ? transformation.decode(succeed7(toOption(current)), options) : transformation.decode(mapEager2(result, toOption), options); @@ -7192,53 +7269,57 @@ function compile(ast, compile, compileField, base, specialize) { let encodingParsers; const parseChecks = (input, options) => { let result = parser(input, options); - if (encodingChecks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const output = result === sameExit ? input : result[args]; - if (input !== missing && output !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, input, options)); + try { + if (encodingChecks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const output = result === sameExit ? input : result[args]; + if (input !== missing && output !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + result = fail6(new Composite(ast, issues, input, options)); + } } } - } - } else { - result = flatMap3(result, (value) => { - if (input !== missing && value !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - return fail6(new Composite(ast, issues, input, options)); + } else { + result = flatMap3(result, (value) => { + if (input !== missing && value !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, input, options)); + } } - } - return succeed6(value); - }); - } - } - if (checks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const value = result === sameExit ? input : result[args]; - if (value === missing) - return result; - const issues = collectIssues(checks, value, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, value, options)); - } + return succeed6(value); + }); } - } else { - result = flatMap3(result, (value) => { - if (value !== missing) { + } + if (checks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const value = result === sameExit ? input : result[args]; + if (value === missing) + return result; const issues = collectIssues(checks, value, undefined, ast, options); if (issues) { - return fail6(new Composite(ast, issues, value, options)); + result = fail6(new Composite(ast, issues, value, options)); } } - return succeed6(value); - }); + } else { + result = flatMap3(result, (value) => { + if (value !== missing) { + const issues = collectIssues(checks, value, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, value, options)); + } + } + return succeed6(value); + }); + } } + return result; + } catch (error) { + return die3(error); } - return result; }; const parseLocal = specialize === undefined ? parseChecks : specialize(parseChecks); if (!links) { @@ -7714,18 +7795,6 @@ function makeStruct(ast, fields) { function Struct(fields) { return makeStruct(struct(fields, undefined), fields); } -function makeTuple(ast, elements) { - return make8(ast, { - elements, - mapElements(f, options) { - const elements = f(this.elements); - return makeTuple(tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements); - } - }); -} -function Tuple(elements) { - return makeTuple(tuple(elements), elements); -} var ArraySchema = /* @__PURE__ */ lambda((schema) => make8(new Arrays(false, [], [schema.ast]), { value: schema })); @@ -7887,32 +7956,24 @@ function link() { }; } var makeFilter2 = makeFilter; -function isPattern2(regExp, annotations) { - const source = regExp.source; - const flags = regExp.flags; - const canExport = /^[dg]*uy?$/.test(flags); - const runtimeRegExp = flags === "" ? `new RegExp(${format(source)})` : `new RegExp(${format(source)}, ${format(flags)})`; - return isPattern(regExp, { - toJsonSchema: () => canExport ? { - pattern: flags.endsWith("y") ? `^(?:${source})` : source - } : [{}, true], - toCode: () => ({ - runtime: `Schema.isPattern(${runtimeRegExp})` - }), - ...annotations - }); -} function isBase64(annotations) { - const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - return isPattern2(regExp, { + const pattern = "^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"; + const regExp = /^[0-9a-zA-Z+/]*={0,2}$/; + return makeFilter2((s) => s.length % 4 === 0 && regExp.test(s), { expected: "a base64 encoded string", representation: { id: "effect/schema/isBase64", payload: null }, toJsonSchema: () => ({ - pattern: regExp.source + pattern }), + arbitraryConstraint: { + patterns: [{ + source: pattern, + flags: "" + }] + }, toCode: () => ({ runtime: "Schema.isBase64()" }), @@ -8065,47 +8126,6 @@ var File = /* @__PURE__ */ instanceOf(globalThis.File, { }) })) }); -var FormData2 = /* @__PURE__ */ instanceOf(globalThis.FormData, { - representation: { - id: "effect/schema/FormData", - payload: null - }, - toCode: () => ({ - runtime: `Schema.FormData`, - Type: `globalThis.FormData` - }), - expected: "FormData", - toCodecJson: () => link()(ArraySchema(Tuple([String4, Union2([Struct({ - _tag: tag("String"), - value: String4 - }), Struct({ - _tag: tag("File"), - value: File - })])])), transformEffect2({ - decode: (e) => { - const out = new globalThis.FormData; - for (const [key, entry] of e) { - out.append(key, entry.value); - } - return succeed6(out); - }, - encode: (formData) => { - return succeed6(globalThis.Array.from(formData.entries()).map(([key, value]) => { - if (typeof value === "string") { - return [key, { - _tag: "String", - value - }]; - } else { - return [key, { - _tag: "File", - value - }]; - } - })); - } - })) -}); var URLSearchParams2 = /* @__PURE__ */ instanceOf(globalThis.URLSearchParams, { representation: { id: "effect/schema/URLSearchParams", @@ -8221,13 +8241,16 @@ function makeClass(Inherited, identifier, struct2, annotations, proto) { } return out; } -function getClassTransformation(self) { - return new Transformation(transform((input) => new self(input, { +function makeClassTrusted(self, fields) { + return new self(fields, { "~payload": { token: payloadToken, - value: input + value: fields } - })), passthrough2()); + }); +} +function getClassTransformation(self) { + return new Transformation(transform((input) => makeClassTrusted(self, input)), passthrough2()); } function getClassTypeId(identifier) { return `~effect/Schema/Class/${identifier}`; @@ -8295,7 +8318,7 @@ function nominal() { } // node_modules/effect/dist/Fiber.js var join = fiberJoin; -var interrupt3 = fiberInterrupt; +var interrupt4 = fiberInterrupt; var getCurrent = getCurrentFiber; var runIn = fiberRunIn; @@ -8824,7 +8847,9 @@ var toTransform = (channel) => channel.transform; var asyncQueue = (scope, f, options) => make12({ capacity: options?.bufferSize, strategy: options?.strategy -}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope)))); +}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope, { + startImmediately: true +})))); var callbackArray = (f, options) => fromTransform((_, scope) => map5(asyncQueue(scope, f, options), takeAll2)); var suspend3 = (evaluate) => fromTransform((upstream, scope) => suspend2(() => toTransform(evaluate())(upstream, scope))); var fromIterator = (iterator) => fromPull(sync3(() => { @@ -8836,8 +8861,8 @@ var fromIterator = (iterator) => fromPull(sync3(() => { })); var succeed8 = (value) => fromEffect(succeed6(value)); var empty3 = /* @__PURE__ */ fromPull(/* @__PURE__ */ succeed6(/* @__PURE__ */ done2())); -var fail7 = (error) => fromPull(succeed6(fail6(error))); var failCause5 = (cause) => fromPull(failCause3(cause)); +var die4 = (defect) => failCause5(die2(defect)); var fromEffect = (effect) => fromPull(sync3(() => { let done = false; return suspend2(() => { @@ -8949,29 +8974,7 @@ var mapAccum = /* @__PURE__ */ dual((args) => isChannel(args[0]), (self, initial }); return pump; }))); -var catchCause3 = /* @__PURE__ */ dual(2, (self, f) => fromTransform((upstream, scope) => { - let forkedScope = forkUnsafe2(scope); - return map5(toTransform(self)(upstream, forkedScope), (pull) => { - let currentPull = pull.pipe(catchCause2((cause) => { - if (isDoneCause(cause)) { - return failCause3(cause); - } - const toClose = forkedScope; - forkedScope = forkUnsafe2(scope); - return close(toClose, failCause2(cause)).pipe(andThen2(toTransform(f(cause))(upstream, forkedScope)), flatMap3((childPull) => { - currentPull = childPull; - return childPull; - })); - })); - return suspend2(() => currentPull); - }); -})); -var catchCauseFilter2 = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause3(self, (cause) => { - const result = filter(cause); - return isFailure2(result) ? failCause5(result.failure) : f(result.success, cause); -})); -var catch_3 = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter2(self, findError2, (e) => f(e))); -var mapError4 = /* @__PURE__ */ dual(2, (self, f) => catch_3(self, (err) => fail7(f(err)))); +var mapError4 = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => succeed6(mapError2(pull, (err) => isDone2(err) ? err : f(err))))); var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { bufferSize = 16, concurrency, @@ -8980,7 +8983,7 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { const concurrencyN = concurrency === "unbounded" ? Number.MAX_SAFE_INTEGER : Math.max(1, concurrency); const semaphore = switch_ ? undefined : makeUnsafe5(concurrencyN); const doneLatch = yield* make9(true); - const fibers = new Set; + const fibers = new Map; const queue = yield* bounded(bufferSize); yield* addFinalizer2(forkedScope, shutdown(queue)); const pull = yield* toTransform(channels)(upstream, scope); @@ -8999,11 +9002,12 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { const childScope = forkUnsafe2(forkedScope); const childPull = yield* toTransform(channel)(upstream, childScope); while (fibers.size >= concurrencyN) { - const fiber = headUnsafe(fibers); + const [fiber, fiberScope] = headUnsafe(fibers); fibers.delete(fiber); if (fibers.size === 0) yield* doneLatch.open; - yield* interrupt3(fiber); + yield* interrupt4(fiber); + yield* ignoreCause2(close(fiberScope, interrupt2())); } const fiber = yield* childPull.pipe(tap2(() => yieldNow2), flatMap3((value) => offer(queue, value)), forever3({ disableYield: true @@ -9022,7 +9026,7 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { yield* doneLatch.open; })), forkChild2); doneLatch.closeUnsafe(); - fibers.add(fiber); + fibers.set(fiber, childScope); } }).pipe(catchCause2((cause) => { const halt = filterDone(cause); @@ -9146,6 +9150,18 @@ var splitLines = () => fromTransform((upstream, _scope) => sync3(() => { } return pullOrFlush; })); +var decodeText = (encoding, options) => fromTransform((upstream, _scope) => sync3(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + let pull = upstream.pipe(map5(map2((bytes) => decoder.decode(bytes, streamOptions))), catchDone((leftover) => { + pull = done2(leftover); + const last = decoder.decode(); + return last.length > 0 ? succeed6(of(last)) : pull; + })); + return suspend2(() => pull); +})); var pipeTo = /* @__PURE__ */ dual(2, (self, that) => fromTransform((upstream, scope) => flatMap3(toTransform(self)(upstream, scope), (upstream) => toTransform(that)(upstream, scope)))); var unwrap = (channel) => fromTransform((upstream, scope) => { let pull; @@ -9305,19 +9321,19 @@ var make13 = (options) => withFiber2((fiber) => { if (state._tag === "Acquired") return close(state.scope, void_2); if (state._tag === "Acquiring") - return interrupt3(state.fiber); + return interrupt4(state.fiber); return void_3; }), ref); }); var getState = (self, restore) => { switch (self.state._tag) { case "Closed": { - return interrupt2; + return interrupt3; } case "Acquired": { const state = self.state; state.refCount++; - return state.fiber ? as2(interrupt3(state.fiber), state) : succeed6(state); + return state.fiber ? as2(interrupt4(state.fiber), state) : succeed6(state); } case "Acquiring": { const state = self.state; @@ -9335,7 +9351,7 @@ var getState = (self, restore) => { const scope = makeUnsafe3(); const acquire = provideContext2(self.acquire, add(self.context, Scope, scope)).pipe(flatMap3((value) => { if (self.state !== acquiring) { - return interrupt2; + return interrupt3; } const state = { _tag: "Acquired", @@ -9368,7 +9384,7 @@ var awaitAcquiring = (self, acquiring, restore) => onExit2(restore(join(acquirin if (--acquiring.awaiters > 0 || self.state !== acquiring) return void_3; self.state = stateEmpty; - return interrupt3(acquiring.fiber); + return interrupt4(acquiring.fiber); }); var get2 = (self_) => { const self = self_; @@ -9415,7 +9431,13 @@ var toChannel2 = (stream) => stream.channel; var callback3 = (f, options) => fromChannel3(callbackArray(f, options)); var empty4 = /* @__PURE__ */ fromChannel3(empty3); var succeed9 = (value) => fromChannel3(succeed8(of(value))); -var suspend4 = (stream) => fromChannel3(suspend3(() => stream().channel)); +var suspend4 = (stream) => { + const suspended = fromChannel3(suspend3(() => stream().channel)); + suspendedStreams.set(suspended, stream); + return suspended; +}; +var suspendedStreams = /* @__PURE__ */ new WeakMap; +var die6 = (defect) => fromChannel3(die4(defect)); var unwrap3 = (effect) => fromChannel3(unwrap(map5(effect, toChannel2))); var map8 = /* @__PURE__ */ dual(2, (self, f) => suspend4(() => { let i = 0; @@ -9433,10 +9455,21 @@ function* concatChannels(self, that) { while (stack.length > 0) { const stream = stack.pop(); const parts = concatParts.get(stream); - if (parts === undefined) - yield stream.channel; - else + if (parts !== undefined) { stack.push(parts[1], parts[0]); + continue; + } + const evaluate = suspendedStreams.get(stream); + if (evaluate === undefined) { + yield stream.channel; + continue; + } + try { + stack.push(evaluate()); + } catch (defect) { + stack.push(die6(defect)); + } + yield empty3; } } var merge3 = /* @__PURE__ */ dual((args) => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel3(merge2(toChannel2(self), toChannel2(that), options))); @@ -9469,12 +9502,7 @@ var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (up }); return suspend2(() => done ? done : pull); }))); -var decodeText = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => suspend4(() => { - const decoder = new TextDecoder(options?.encoding); - return map8(self, (chunk) => decoder.decode(chunk, { - stream: true - })); -})); +var decodeText2 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => self.channel.pipe(pipeTo(decodeText(options?.encoding)), fromChannel3)); var splitLines2 = (self) => self.channel.pipe(pipeTo(splitLines()), fromChannel3); var run2 = /* @__PURE__ */ dual(2, (self, sink) => scopedWith2((scope) => toPullScoped(self.channel, scope).pipe(flatMap3((upstream) => sink.transform(upstream, scope)), map5(([a]) => a)))); var runCollect = (self) => runFold(self.channel, () => [], (acc, chunk) => { @@ -9600,10 +9628,14 @@ var ulidString = (timestampMillis, bytes) => { }; // node_modules/effect/dist/internal/uuid.js -var hex = (byte) => byte.toString(16).padStart(2, "0"); +var hex = /* @__PURE__ */ Array.from({ + length: 256 +}, (_, byte) => byte.toString(16).padStart(2, "0")); var stringify = (bytes) => { - const segments = [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)]; - return segments.map((segment) => Array.from(segment, hex).join("")).join("-"); + if (bytes.length < 16) { + return [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)].map((segment) => Array.from(segment, (byte) => hex[byte]).join("")).join("-"); + } + return hex[bytes[0]] + hex[bytes[1]] + hex[bytes[2]] + hex[bytes[3]] + "-" + hex[bytes[4]] + hex[bytes[5]] + "-" + hex[bytes[6]] + hex[bytes[7]] + "-" + hex[bytes[8]] + hex[bytes[9]] + "-" + hex[bytes[10]] + hex[bytes[11]] + hex[bytes[12]] + hex[bytes[13]] + hex[bytes[14]] + hex[bytes[15]]; }; var randomBytes = () => globalThis.crypto.getRandomValues(new Uint8Array(16)); function v4Bytes(bytes = randomBytes()) { @@ -9859,23 +9891,26 @@ var defaultTeardown = (exit, onExit) => { return onExit(getErrorExitCode(squash(exit.cause))); }; var makeRunMain = (f) => dual((args) => isEffect2(args[0]), (effect, options) => { - const fiber = options?.disableErrorReporting === true ? runFork2(effect) : runFork2(tapCause2(effect, (cause) => { + const main = options?.disableErrorReporting === true ? effect : tapCause2(effect, (cause) => { if (hasInterruptsOnly2(cause)) return void_3; const isReported = getErrorReported(squash(cause)); return isReported ? logError(cause) : void_3; - })); - try { - const keepAlive = globalThis.setInterval(constVoid, 2147483647); - fiber.addObserver(() => { - clearInterval(keepAlive); - }); - } catch {} - const teardown = options?.teardown ?? defaultTeardown; - return f({ - fiber, - teardown }); + const teardown = options?.teardown ?? defaultTeardown; + runFork2(withFiber2((fiber) => { + try { + const keepAlive = globalThis.setInterval(constVoid, 2147483647); + fiber.addObserver(() => { + clearInterval(keepAlive); + }); + } catch {} + f({ + fiber, + teardown + }); + return main; + })); }); var errorExitCode = "~effect/Runtime/errorExitCode"; var getErrorExitCode = (u) => { @@ -9939,7 +9974,7 @@ var makeHandle = (params) => Object.setPrototypeOf({ ...params }, HandleProto); var make21 = (spawn) => { - const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); + const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText2(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); const streamLines = (command, options) => splitLines2(streamString(command, options)); return ChildProcessSpawner.of({ spawn, @@ -10187,11 +10222,11 @@ var layer = (defaults = {}) => effect(Gh, gen2(function* () { let stdoutTruncated = false; let stderr = ""; let stderrTruncated = false; - const output = merge3(handle.stdout.pipe(decodeText(), map8((text) => { + const output = merge3(handle.stdout.pipe(decodeText2(), map8((text) => { stdoutTruncated ||= stdout.length + text.length > outputLimit; stdout = (stdout + text).slice(-outputLimit); return GhChunk.cases.Stdout.make({ text }); - })), handle.stderr.pipe(decodeText(), map8((text) => { + })), handle.stderr.pipe(decodeText2(), map8((text) => { stderrTruncated ||= stderr.length + text.length > outputLimit; stderr = (stderr + text).slice(-outputLimit); return GhChunk.cases.Stderr.make({ text }); @@ -10427,6 +10462,7 @@ var handleErrnoException = (module, method) => (err, [path]) => { reason = "NotFound"; break; case "EACCES": + case "EPERM": reason = "PermissionDenied"; break; case "EEXIST": @@ -10455,66 +10491,149 @@ var handleErrnoException = (module, method) => (err, [path]) => { }); }; +// node_modules/@effect/platform-node-shared/dist/NodeSink.js +import { finished } from "node:stream"; + +// node_modules/@effect/platform-node-shared/dist/internal/stream.js +var destroyStream = (stream, cleanup, onDestroyed) => { + if (!("closed" in stream)) { + cleanup(); + onDestroyed?.(); + return; + } + const onDone = () => { + clearImmediate(immediate); + stream.off("error", onDone); + stream.off("close", onDone); + onDestroyed?.(); + }; + const onClosed = () => { + if (stream.closed) { + onDone(); + } else { + immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + } + }; + let immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + stream.once("error", onDone); + stream.once("close", onDone); + cleanup(); + if (!stream.closed) { + stream.destroy(); + } +}; + // node_modules/@effect/platform-node-shared/dist/NodeSink.js var fromWritable = (options) => fromChannel2(mapDone(fromWritableChannel(options), (_) => [_])); var fromWritableChannel = (options) => fromTransform((pull) => { const writable = options.evaluate(); - return succeed6(pullIntoWritable({ + const write = pullIntoWritable({ ...options, writable, pull - })); -}); -var pullIntoWritable = (options) => options.pull.pipe(flatMap3((chunk) => { - let i = 0; - return callback2((resume) => { - let cancelled = false; - const loop = () => { - for (;i < chunk.length; ) { - if (cancelled) { - return; - } - const success = options.writable.write(chunk[i++], options.encoding); - if (!success) { - if (!cancelled) { - options.writable.once("drain", loop); + }); + return succeed6(options.endOnDone === false ? write : onError2(write, (cause) => isDoneCause(cause) ? void_3 : releaseWritable(writable))); +}); +var releaseWritable = (writable) => callback2((resume) => { + const onDestroyed = () => resume(void_3); + if (writable.closed) { + const cleanup = finished(writable, { + readable: false + }, () => { + cleanup(); + onDestroyed(); + }); + } else { + destroyStream(writable, constVoid, onDestroyed); + } +}); +var pullIntoWritable = (options) => withFiber2((fiber) => { + const dispatcher = fiber.currentDispatcher; + const completion = makeUnsafe2(); + const failure = makeUnsafe2(); + const onError = (error) => doneUnsafe(failure, failSync2(() => options.onError(error))); + let errorEmitted = false; + const onStreamError = (error) => { + errorEmitted = true; + onError(error); + }; + options.writable.on("error", onStreamError); + const cleanup = finished(options.writable, { + readable: false + }, (error) => { + if (error) { + onError(error); + } else { + doneUnsafe(completion, void_3); + } + }); + return options.pull.pipe(flatMap3((chunk) => { + let i = 0; + return callback2((resume) => { + let cancelled = false; + const onFinish = () => dispatcher.scheduleTask(loop, 0); + const loop = () => { + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + for (;i < chunk.length; ) { + if (cancelled) { + return; + } + const success = options.writable.write(chunk[i++], options.encoding, (error) => { + if (!error) + return; + if (options.writable.closed) { + onError(error); + } else { + dispatcher.scheduleTask(() => onError(error), 0); + } + }); + if (!success) { + if (!cancelled) { + options.writable.once("drain", loop); + options.writable.once("finish", onFinish); + } + return; } - return; } - } - if (!cancelled) { - resume(void_3); - } - }; - loop(); - return sync3(() => { - cancelled = true; - options.writable.off("drain", loop); + if (!cancelled) { + resume(void_3); + } + }; + loop(); + return sync3(() => { + cancelled = true; + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + }); }); - }); -}), forever3({ - disableYield: true -}), options.endOnDone !== false ? catchDone((_) => { - if ("closed" in options.writable && options.writable.closed) { - return done2(_); - } - return callback2((resume) => { - const onFinish = () => resume(done2(_)); - options.writable.once("finish", onFinish); + }), forever3({ + disableYield: true + }), options.endOnDone !== false ? catchDone((_) => { options.writable.end(); - return sync3(() => { - options.writable.off("finish", onFinish); - }); - }); -}) : identity, raceFirst2(callback2((resume) => { - const onError = (error) => resume(fail6(options.onError(error))); - options.writable.once("error", onError); - return sync3(() => { - options.writable.off("error", onError); - }); -}))); + return andThen2(_await(completion), done2(_)); + }) : identity, raceFirst2(_await(failure)), ensuring2(sync3(() => { + cleanup(); + const removeErrorListener = () => { + options.writable.off("error", onStreamError); + options.writable.off("error", removeErrorListener); + options.writable.off("close", removeErrorListener); + }; + if (options.writable.errored && !options.writable.closed && !errorEmitted) { + options.writable.once("error", removeErrorListener); + options.writable.once("close", removeErrorListener); + } else { + removeErrorListener(); + } + }))); +}); // node_modules/@effect/platform-node-shared/dist/NodeStream.js +import { finished as finished2, Readable } from "node:stream"; var fromReadable = (options) => fromChannel3(fromReadableChannel(options)); var fromReadableChannel = (options) => fromTransform((_, scope) => readableToPullUnsafe({ scope, @@ -10531,17 +10650,14 @@ var readableToPullUnsafe = (options) => { function onReadable() { latch.openUnsafe(); } - function onError(error) { - exit.current = fail5(options.onError(error)); - latch.openUnsafe(); - } - function onEnd() { - exit.current = fail5(Done2()); - latch.openUnsafe(); - } readable.on("readable", onReadable); - readable.once("error", onError); - readable.once("end", onEnd); + const cleanup = finished2(readable, { + readable: true, + writable: false + }, (error) => { + exit.current ??= fail5(error ? options.onError(error) : Done2()); + latch.openUnsafe(); + }); const pull = suspend2(function loop() { let item = options.readable.read(options.chunkSize); if (item === null) { @@ -10565,10 +10681,10 @@ var readableToPullUnsafe = (options) => { }); return as2(addFinalizer2(options.scope, sync3(() => { readable.off("readable", onReadable); - readable.off("error", onError); - readable.off("end", onEnd); - if (closeOnDone && "closed" in options.readable && !options.readable.closed) { - options.readable.destroy(); + if (closeOnDone) { + destroyStream(readable, cleanup); + } else { + cleanup(); } })), pull); }; @@ -10893,6 +11009,7 @@ var make23 = /* @__PURE__ */ gen2(function* () { const signalGroup = (signal) => killProcessGroup(command, childProcess, signal).pipe(catch_2(() => killProcess(command, childProcess, signal))); yield* signalGroup(options?.killSignal ?? "SIGTERM"); if (isUndefined(options?.forceKillAfter)) { + yield* _await(exitSignal); yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis); } else { yield* awaitProcessExit(childProcess, exitSignal, toMillis(options.forceKillAfter)); @@ -11486,14 +11603,14 @@ var readLink = /* @__PURE__ */ (() => { return (path) => nodeReadLink(path); })(); var realPath = /* @__PURE__ */ (() => { - const nodeRealPath = /* @__PURE__ */ effectify(NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); + const nodeRealPath = /* @__PURE__ */ effectify(process.platform === "win32" ? NFS.realpath.native : NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); return (path) => nodeRealPath(path); })(); var rename2 = /* @__PURE__ */ (() => { const nodeRename = /* @__PURE__ */ effectify(NFS.rename, /* @__PURE__ */ handleErrnoException("FileSystem", "rename"), /* @__PURE__ */ handleBadArgument("rename")); return (oldPath, newPath) => nodeRename(oldPath, newPath); })(); -var makeFileInfo = (stat) => try_2({ +var makeFileInfo = (stat, method = "stat") => try_2({ try: () => ({ type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown", mtime: fromNullishOr(stat.mtime), @@ -11510,14 +11627,16 @@ var makeFileInfo = (stat) => try_2({ blksize: stat.blksize !== undefined ? some2(bytes(stat.blksize)) : none2(), blocks: fromNullishOr(stat.blocks) }), - catch: handleBadArgument("stat") + catch: handleBadArgument(method) }); -var stat2 = /* @__PURE__ */ (() => { - const nodeStat = /* @__PURE__ */ effectify(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat")); +var statFactory = (method, nodeStatFn) => { + const nodeStat = effectify(nodeStatFn, handleErrnoException("FileSystem", method), handleBadArgument(method)); return (path) => flatMap3(nodeStat(path, { bigint: true - }), makeFileInfo); -})(); + }), (stat) => makeFileInfo(stat, method)); +}; +var stat2 = /* @__PURE__ */ statFactory("stat", NFS.stat); +var lstat2 = /* @__PURE__ */ statFactory("lstat", NFS.lstat); var symlink2 = /* @__PURE__ */ (() => { const nodeSymlink = /* @__PURE__ */ effectify(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink")); return (target, path) => nodeSymlink(target, path); @@ -11600,6 +11719,7 @@ var makeFileSystem = /* @__PURE__ */ map5(/* @__PURE__ */ serviceOption2(WatchBa copyFile: copyFile2, glob: glob2, link: link3, + lstat: lstat2, makeDirectory, makeTempDirectory, makeTempDirectoryScoped, @@ -11739,9 +11859,6 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readline.emitKeypressEvents(stdin, rl); rl.on("line", onLine); rl.once("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(true); - } return { rl, onClose, @@ -11755,9 +11872,6 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readlineActive = false; rl.off("line", onLine); rl.off("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(false); - } rl.close(); if (inputEnded) { endUnsafe(lines); @@ -11765,6 +11879,14 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu })), idleTimeToLive: "10 millis" }); + const setRawMode = (enabled) => sync3(() => { + if (stdin.isTTY) + stdin.setRawMode(enabled); + }); + const rawModeRef = yield* make14({ + acquire: acquireRelease2(setRawMode(true), () => setRawMode(false)), + idleTimeToLive: "10 millis" + }); const columns = sync3(() => stdout.columns ?? 0); const rows = sync3(() => stdout.rows ?? 0); const readInput = gen2(function* () { @@ -11799,6 +11921,7 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu handleEnd(); } else { yield* get3(rlRef); + yield* get3(rawModeRef); stdin.once("end", handleEnd); } return queue; @@ -11918,7 +12041,7 @@ class CommandError extends TaggedError3()("CommandError", { }) { } var error = (command, cause) => new CommandError({ command, exitCode: -1, stderr: String(cause) }); -var collectText = (stream) => stream.pipe(decodeText(), runFold2(() => "", (all, chunk) => all + chunk)); +var collectText = (stream) => stream.pipe(decodeText2(), runFold2(() => "", (all, chunk) => all + chunk)); var retainedStderrLength = 16 * 1024; class Service3 extends Service()("@timmo001/workflows/CommandExecutor") { @@ -11971,8 +12094,8 @@ var layer15 = effect(Service3, gen2(function* () { stdin: "inherit" })); let stderrTail = ""; - const stdout = handle.stdout.pipe(decodeText(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); - const stderr = handle.stderr.pipe(decodeText(), runForEach2((chunk) => sync3(() => { + const stdout = handle.stdout.pipe(decodeText2(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); + const stderr = handle.stderr.pipe(decodeText2(), runForEach2((chunk) => sync3(() => { process.stderr.write(chunk); stderrTail = `${stderrTail}${chunk}`.slice(-retainedStderrLength); }))); diff --git a/.github/actions/publish-aur/dist/index.js b/.github/actions/publish-aur/dist/index.js index aff8b1d0..7288cc7e 100644 --- a/.github/actions/publish-aur/dist/index.js +++ b/.github/actions/publish-aur/dist/index.js @@ -769,6 +769,10 @@ function assignProperty(self, key, value) { } } function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } for (const key of Reflect.ownKeys(source)) { if (Object.prototype.propertyIsEnumerable.call(source, key)) { assignProperty(self, key, source[key]); @@ -859,7 +863,7 @@ class CauseImpl { toJSON() { return { _id: "Cause", - failures: this.reasons.map((f) => f.toJSON()) + reasons: this.reasons.map((f) => f.toJSON()) }; } toString() { @@ -1610,9 +1614,21 @@ var bigint2 = /* @__PURE__ */ BigInt(2); var bigint10 = /* @__PURE__ */ BigInt(10); var bigint1e3 = /* @__PURE__ */ BigInt(1000); var bigint1e6 = /* @__PURE__ */ BigInt(1e6); +var bigint1e9 = /* @__PURE__ */ BigInt(1e9); +var bigintNanosPerMinute = /* @__PURE__ */ BigInt(60000000000); +var bigintNanosPerHour = /* @__PURE__ */ BigInt(3600000000000); +var bigintNanosPerDay = /* @__PURE__ */ BigInt(86400000000000); +var bigintNanosPerWeek = /* @__PURE__ */ BigInt(604800000000000); var roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input))); var roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6); var fromNanosNumber = (nanos) => make3(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos); +var nanosToUnit = (nanos, divisor) => { + const value = Number(nanos); + if (Number.isFinite(value)) + return value / divisor; + const scale = BigInt(divisor); + return Number(nanos / scale) + Number(nanos % scale) / divisor; +}; var parseNanos = (input, scale) => { const decimalIndex = input.indexOf("."); if (decimalIndex === -1) @@ -1628,6 +1644,13 @@ var divideTiesAwayFromZero = (numerator, denominator) => { const rounded = absolute / denominator + (absolute % denominator * bigint2 >= denominator ? bigint1 : bigint0); return numerator < bigint0 ? -rounded : rounded; }; +var fromMillisString = (input, scale) => { + const millis = Number(input) * scale; + if (!Number.isFinite(millis)) + return make3(millis); + const nanos = parseNanos(input, BigInt(scale) * bigint1e6); + return make3(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos); +}; var DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; var fromInputUnsafe = (input) => { switch (typeof input) { @@ -1652,26 +1675,25 @@ var fromInputUnsafe = (input) => { if (unit === "micro" || unit === "micros") { return nanos(parseNanos(valueStr, bigint1e3)); } - const value = Number(valueStr); switch (unit) { case "milli": case "millis": - return millis(value); + return fromMillisString(valueStr, 1); case "second": case "seconds": - return seconds(value); + return fromMillisString(valueStr, 1000); case "minute": case "minutes": - return minutes(value); + return fromMillisString(valueStr, 60000); case "hour": case "hours": - return hours(value); + return fromMillisString(valueStr, 3600000); case "day": case "days": - return days(value); + return fromMillisString(valueStr, 86400000); case "week": case "weeks": - return weeks(value); + return fromMillisString(valueStr, 604800000); } break; } @@ -1693,7 +1715,8 @@ var fromInputUnsafe = (input) => { if (input[0] === Infinity || input[1] === Infinity) { return infinity; } - return fromNanosNumber(input[0] * 1e9 + input[1]); + const nanos = input[0] * 1e9 + input[1]; + return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make3(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos); } const obj = input; let millis = 0; @@ -1709,13 +1732,42 @@ var fromInputUnsafe = (input) => { millis += obj.seconds * 1000; if (obj.milliseconds) millis += obj.milliseconds; - if (!obj.microseconds && !obj.nanoseconds) - return make3(millis); - return fromNanosNumber(millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0)); + if (!obj.microseconds && !obj.nanoseconds) { + if (!Number.isFinite(millis)) + return make3(millis); + const exact = sumObjectNanos(obj); + return exact === undefined || BigInt(millis) * bigint1e6 === exact ? make3(millis) : make3(exact); + } + const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0); + const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : undefined; + return exact === undefined ? fromNanosNumber(nanos) : make3(exact); } } return invalid(input); }; +var isIntegerOrUnset = (n) => !n || Number.isInteger(n); +var sumObjectNanos = (obj) => { + if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds)) + return; + let nanos = bigint0; + if (obj.weeks) + nanos += BigInt(obj.weeks) * bigintNanosPerWeek; + if (obj.days) + nanos += BigInt(obj.days) * bigintNanosPerDay; + if (obj.hours) + nanos += BigInt(obj.hours) * bigintNanosPerHour; + if (obj.minutes) + nanos += BigInt(obj.minutes) * bigintNanosPerMinute; + if (obj.seconds) + nanos += BigInt(obj.seconds) * bigint1e9; + if (obj.milliseconds) + nanos += BigInt(obj.milliseconds) * bigint1e6; + if (obj.microseconds) + nanos += BigInt(obj.microseconds) * bigint1e3; + if (obj.nanoseconds) + nanos += BigInt(obj.nanoseconds); + return nanos; +}; var invalid = (input) => { throw new Error(`Invalid Input: ${input}`); }; @@ -1824,14 +1876,9 @@ var infinity = /* @__PURE__ */ make3(Infinity); var negativeInfinity = /* @__PURE__ */ make3(-Infinity); var nanos = (nanos) => make3(nanos); var millis = (millis) => make3(millis); -var seconds = (seconds) => make3(seconds * 1000); -var minutes = (minutes) => make3(minutes * 60000); -var hours = (hours) => make3(hours * 3600000); -var days = (days) => make3(days * 86400000); -var weeks = (weeks) => make3(weeks * 604800000); var toMillis = (self) => match3(fromInputUnsafe(self), { onMillis: identity, - onNanos: (nanos) => Number(nanos) / 1e6, + onNanos: (nanos) => nanosToUnit(nanos, 1e6), onInfinity: () => Infinity, onNegativeInfinity: () => -Infinity }); @@ -1897,7 +1944,7 @@ var setTimer = "setImmediate" in globalThis ? (f) => { const timer = setTimeout(f, 0); return () => clearTimeout(timer); }; -var setImmediate = (f) => { +var setImmediate2 = (f) => { try { return setTimer(f); } catch { @@ -1937,7 +1984,7 @@ class MixedScheduler { setImmediate; constructor(executionMode = "async", setImmediateFn) { this.executionMode = executionMode; - this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate2); } shouldYield(fiber) { return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; @@ -1951,7 +1998,7 @@ class MixedSchedulerDispatcher { tasks = /* @__PURE__ */ new PriorityBuckets; running = undefined; setImmediate; - constructor(setImmediateFn = setImmediate) { + constructor(setImmediateFn = setImmediate2) { this.setImmediate = setImmediateFn; } scheduleTask(task, priority) { @@ -2195,10 +2242,7 @@ class Interrupt extends ReasonBase { } } var causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); -var findFail = (self) => { - const reason = self.reasons.find(isFailReason); - return reason ? succeed2(reason) : fail2(self); -}; +var hasFails = (self) => self.reasons.some(isFailReason); var findError = (self) => { for (let i = 0;i < self.reasons.length; i++) { const reason = self.reasons[i]; @@ -2208,6 +2252,9 @@ var findError = (self) => { } return fail2(self); }; +var hasDies = (self) => self.reasons.some(isDieReason); +var causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +var findRecoverableError = (self) => hasDies(self) ? fail2(causeElectDefects(self)) : findError(self); var hasInterrupts = (self) => self.reasons.some(isInterruptReason); var hasInterruptsOnly = (self) => self.reasons.length > 0 && self.reasons.every(isInterruptReason); var causeMap = /* @__PURE__ */ dual(2, (self, f) => { @@ -2268,12 +2315,14 @@ var causePrettyErrors = (self, options) => { } return errors; }; -var causePrettyError = (original, annotations, options) => { +var causePrettyError = (original, annotations, options, seen = new Set) => { const kind = typeof original; let error; if (original && kind === "object") { + seen.add(original); + const cause = original.cause; error = new globalThis.Error(causePrettyMessage(original), { - cause: original.cause ? causePrettyError(original.cause) : undefined + cause: cause !== undefined && !seen.has(cause) ? causePrettyError(cause, undefined, undefined, seen) : undefined }); if (typeof original.name === "string") { error.name = original.name; @@ -2484,7 +2533,11 @@ class FiberImpl { } else if (this._asyncContext !== undefined) { const asyncContext = this._asyncContext; this._asyncContext = undefined; - return asyncContext.runInAsyncScope(this.evaluate, this, effect); + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } } else if (this._yielded !== undefined) { const yielded = this._yielded; this._yielded = undefined; @@ -2782,7 +2835,6 @@ var tryPromise = (options) => { } }, f.length !== 0); }; -var withFiberId = (f) => withFiber((fiber) => f(fiber.id)); var callbackOptions = /* @__PURE__ */ function() { const Proto = /* @__PURE__ */ makePrimitiveProto({ op: "Async", @@ -2803,9 +2855,9 @@ var callbackOptions = /* @__PURE__ */ function() { if (yielded !== false) return yielded; yielded = true; - fiber._yielded = () => { + fiber.yieldWith(() => { resumed = true; - }; + }); if (controller === undefined && onCancel === undefined) { return Yield; } @@ -3088,10 +3140,7 @@ var exitMap = /* @__PURE__ */ dual(2, (self, f) => self._tag === "Success" ? exi var exitMapError = /* @__PURE__ */ dual(2, (self, f) => { if (self._tag === "Success") return self; - const error = findError(self.cause); - if (isFailure2(error)) - return self; - return exitFail(f(error.success)); + return exitFailCause(causeMap(self.cause, f)); }); var exitZipRight = /* @__PURE__ */ dual(2, (self, that) => exitIsSuccess(self) ? that : self); var exitAsVoidAll = (exits) => { @@ -3155,10 +3204,10 @@ var catchCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(s const eb = filter(cause); return isFailure2(eb) ? failCause(eb.failure) : f(eb.success, cause); })); -var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findError, (e) => f(e))); +var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findRecoverableError, (e) => f(e))); var tapCause = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => andThen(f(cause), failCause(cause)))); var catchIf = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, predicate, f, orElse) => catchCause(self, (cause) => { - const error = findError(cause); + const error = findRecoverableError(cause); if (isFailure2(error)) return failCause(error.failure); if (!predicate(error.success)) { @@ -3170,7 +3219,7 @@ var catchTag = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, k, f, or const pred = Array.isArray(k) ? (e) => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); return catchIf(self, pred, f, orElse); }); -var mapError = /* @__PURE__ */ dual(2, (self, f) => catch_(self, (error) => failSync(() => f(error)))); +var mapError = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => failCause(causeMap(cause, f)))); var orDie = (self) => catch_(self, die); var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { if (!options?.log) { @@ -3182,8 +3231,8 @@ var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) = const logEffect = logWithLevel(options.log === true ? undefined : options.log); return matchCauseEffect(self, { onFailure(cause) { - const failure = findFail(cause); - return isFailure2(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); }, onSuccess: (_) => void_ }); @@ -3222,16 +3271,16 @@ var makeMatch = (op, onFailure) => { return MatchImpl; }; var MatchImpl = /* @__PURE__ */ makeMatch("Match", function(cause, fiber) { - const fail = cause.reasons.find(isFailReason); - if (fail === undefined) - return failCause(cause); + const error = findRecoverableError(cause); + if (isFailure2(error)) + return failCause(error.failure); const handlers = this.payload; - return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(fail.error) : internalCall(() => handlers.onFailure(fail.error))); + return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))); }); var matchEffect = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, { onFailure: (cause) => { - const fail = cause.reasons.find(isFailReason); - return fail ? options.onFailure(fail.error) : failCause(cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.onFailure(error.success); }, onSuccess: options.onSuccess })); @@ -3240,9 +3289,9 @@ var matchEager = /* @__PURE__ */ dual(2, (self, options) => { if (effectIsExit(self)) { if (self._tag === "Success") return exitSucceed(options.onSuccess(self.value)); - const error = findError(self.cause); + const error = findRecoverableError(self.cause); if (isFailure2(error)) - return self; + return exitFailCause(error.failure); return exitSucceed(options.onFailure(error.success)); } return match4(self, options); @@ -3297,17 +3346,17 @@ var runFinalizer = (finalizer, exit_) => { return exitDie(defect); } }; -var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeCombine(exit_.cause, cause))); +var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); var scopeCloseFinalizers = /* @__PURE__ */ fnUntraced(function* (self, finalizers, exit_) { let exits = []; const fibers = []; - const arr = Array.from(finalizers.values()); + const arr = Array.from(finalizers); const parent = getCurrentFiber(); for (let i = arr.length - 1;i >= 0; i--) { - const finalizer = arr[i]; + const [key, finalizer] = arr[i]; if (self.strategy === "sequential") { exits.push(yield* exit(runFinalizer(finalizer, exit_))); - } else { + } else if (key !== parent) { fibers.push(forkUnsafe(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); } } @@ -3500,15 +3549,9 @@ var all = (arg, options) => { } else if (options?.discard) { return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options); } - return suspend(() => { - const out = {}; - return as(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => { - assignProperty(out, key, value); - }), { - discard: true, - concurrency: options?.concurrency - }), out); - }); + return suspend(() => map3(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => [key, value]), { + concurrency: options?.concurrency + }), Object.fromEntries)); }; var whileLoop = /* @__PURE__ */ makePrimitive({ op: "While", @@ -3647,7 +3690,7 @@ var iterateConcurrentImpl = (options) => { const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); if (reasons.length > 0) { const cause = causeFromReasons(reasons); - terminal = exitFailCause(terminal._tag === "Failure" ? causeCombine(terminal.cause, cause) : cause); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); } } } else { @@ -3725,14 +3768,13 @@ var forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterrupt } return child; }; +var fiberScopeFinalizer = (fiber) => () => withFiber((current) => current === fiber ? void_ : fiberInterrupt(fiber)); var forkIn = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, scope, options) => withFiber((parent) => { - const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + const fiber = scope.state._tag === "Closed" ? new FiberImpl(parent.context) : forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); if (!fiber._exit) { if (scope.state._tag !== "Closed") { - const key = {}; - const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); - scopeAddFinalizerUnsafe(scope, key, finalizer); - fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + scopeAddFinalizerUnsafe(scope, fiber, fiberScopeFinalizer(fiber)); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, fiber)); } else { fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); } @@ -3769,7 +3811,7 @@ var fiberRunIn = /* @__PURE__ */ dual(2, (self, scope) => { return self; } scopeRemoveFinalizerUnsafe(scope, self); - scopeAddFinalizerUnsafe(scope, self, () => fiberInterrupt(self)); + scopeAddFinalizerUnsafe(scope, self, fiberScopeFinalizer(self)); self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, self)); return self; }); @@ -4408,8 +4450,8 @@ var mergeAllEffect = (layers, memoMap, scope) => { concurrency: layers.length }).pipe(map3((context) => mergeAll(...context))); }; -var mergeAll2 = (...layers) => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); -var provideWith = (self, that, f) => fromBuild((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); +var mergeAll2 = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +var provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); var provide2 = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, identity)); var provideMerge = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, (self, that) => merge(that, self))); @@ -4480,6 +4522,7 @@ var void_3 = void_; var callback2 = callback; var gen2 = gen; var fail6 = fail3; +var failSync2 = failSync; var failCause3 = failCause; var failCauseSync2 = failCauseSync; var die3 = die; @@ -4529,16 +4572,23 @@ var fn2 = fn; var clockWith2 = clockWith; var logError = /* @__PURE__ */ logWithLevel("Error"); var effectify = (fn, onError, onSyncError) => (...args) => callback2((resume) => { + let synchronous = true; + let pending; try { fn(...args, (err, result) => { - if (err) { - resume(onError ? suspend2(() => fail6(onError(err, args))) : fail6(err)); + const effect = err ? onError ? suspend2(() => fail6(onError(err, args))) : fail6(err) : succeed6(result); + if (synchronous) { + pending ??= effect; } else { - resume(succeed6(result)); + resume(effect); } }); } catch (err) { - resume(onSyncError ? fail6(onSyncError(err, args)) : die3(err)); + pending = onSyncError ? fail6(onSyncError(err, args)) : die3(err); + } + synchronous = false; + if (pending) { + resume(pending); } }); var mapEager2 = mapEager; @@ -4949,7 +4999,7 @@ var defaultLeafHook = (issue) => { } } }; -var defaultCheckHook = (issue) => findMessage(issue.issue) ?? findMessage(issue); +var defaultCheckHook = (issue) => findMessage(issue) ?? findMessage(issue.issue); function formatInput(issue) { return hasInput(issue) ? format(issue.input) : undefined; } @@ -4961,6 +5011,13 @@ function getExpectedMessage(expected, issue) { const input = formatInput(issue); return input === undefined ? `Expected ${expected}` : `Expected ${expected}, got ${input}`; } +function getFilterMessage(issue, checkHook) { + const message = checkHook(issue); + if (message !== undefined || issue.issue._tag !== "InvalidValue") + return message; + const expected = findExpected(issue.issue); + return expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); +} function formatCheck(check) { const expected = check.annotations?.expected; if (typeof expected === "string") @@ -4976,44 +5033,33 @@ function makeFormatterDefault() { return (issue) => formatIssue(issue, ""); } var defaultFormatter = /* @__PURE__ */ makeFormatterDefault(); -function formatIssue(issue, path) { +function formatIssue(issue, path, messageOverride) { let message; switch (issue._tag) { - case "Filter": { - const annotated = defaultCheckHook(issue); - if (annotated !== undefined) { - message = annotated; - } else { - if (issue.issue._tag !== "InvalidValue") { - return formatIssue(issue.issue, path); - } - const expected = findExpected(issue.issue); - message = expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); - } - break; - } + case "Filter": + return formatIssue(issue.issue, path, messageOverride ?? getFilterMessage(issue, defaultCheckHook)); case "Encoding": - return formatIssue(issue.issue, path); + return formatIssue(issue.issue, path, messageOverride); case "Pointer": - return formatIssue(issue.issue, path + formatPath(issue.path)); + return formatIssue(issue.issue, path + formatPath(issue.path), messageOverride); case "Composite": case "AnyOf": { if (issue._tag === "Composite" || issue.issues.length > 0) { - return issue.issues.map((issue) => formatIssue(issue, path)).join(` + return issue.issues.map((issue) => formatIssue(issue, path, messageOverride)).join(` `); } - message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); + message = messageOverride ?? findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); break; } default: - message = defaultLeafHook(issue); + message = messageOverride ?? defaultLeafHook(issue); break; } return path ? `${message} at ${path}` : message; } function findMessage(issue) { - if (issue._tag === "Pointer") + if (issue._tag === "Pointer" || issue._tag === "Composite") return; if (issue._tag === "Encoding") return findMessage(issue.issue); @@ -5191,7 +5237,12 @@ var Declaration = class extends ASTNodeImpl { return (input, options) => { if (input === missing) return missingExit; - return (run ??= this.run(this.typeParameters))(input, this, options); + run ??= this.run(this.typeParameters); + try { + return run(input, this, options); + } catch (error) { + return die3(error); + } }; } _rebuild(recur, checks, encodingChecks, run, encodingRun) { @@ -5304,173 +5355,6 @@ function hasCheck(checks, id) { return checks.some((check) => check.annotations?.representation?.id === id || check._tag === "FilterGroup" && hasCheck(check.checks, id)); } var number2 = /* @__PURE__ */ new Number4; -var Arrays = class extends ASTNodeImpl { - _tag = "Arrays"; - isMutable; - elements; - rest; - encodingChecks; - constructor(isMutable, elements, rest, annotations, checks, encoding, context, encodingChecks) { - super(annotations, checks, encoding, context); - this.isMutable = isMutable; - this.elements = elements; - this.rest = rest; - this.encodingChecks = encodingChecks; - let hasOptional = false; - for (let i = 0;i < elements.length; i++) { - if (isOptional(elements[i])) { - hasOptional = true; - } else if (hasOptional) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - } - if (hasOptional && rest.length > 1) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - for (let i = 1;i < rest.length; i++) { - if (isOptional(rest[i])) { - throw new Error("An optional element cannot follow a rest element. ts(1266)"); - } - } - } - getParser(compile, compileField = compile) { - const ast = this; - let elements; - let rest; - const elementLen = ast.elements.length; - const tailLen = Math.max(0, ast.rest.length - 1); - function getParser(tailThreshold, index) { - if (index < elementLen) { - return elements[index]; - } else if (index >= tailThreshold) { - return rest[index - tailThreshold + 1]; - } - return rest[0]; - } - const finish = (state) => { - const { - input, - len, - options - } = state; - if (ast.rest.length === 0 && len > elementLen) { - for (let i = elementLen;i < len; i++) { - const unexpected = new UnexpectedKey(ast, input[i], options); - const issue = new Pointer([i], unexpected); - if (options.errors === "all") { - if (state.issues) - state.issues.push(issue); - else - state.issues = [issue]; - } else { - return fail6(new Composite(ast, [issue], input, options)); - } - } - } - if (state.issues) { - return fail6(new Composite(ast, state.issues, input, options)); - } - return succeed7(state.output); - }; - const parse = (input, options) => { - const len = input.length; - const state = { - ast, - getParser, - input, - len, - tailThreshold: Math.max(elementLen, len - tailLen), - output: new globalThis.Array(len), - issues: undefined, - options - }; - const end = ast.rest.length === 0 ? elementLen : Math.max(len, elementLen + tailLen); - const concurrency = options.concurrency === undefined ? 1 : resolveConcurrency(options.concurrency); - const eff = concurrency === 1 ? parseArray(state, input, 0, end) : parseArrayConcurrent(state, input, { - concurrency, - end - }); - if (!eff) - return finish(state); - if (effectIsExit(eff)) - return flatMapEager2(eff, () => finish(state)); - let first = true; - return suspend2(() => { - if (!first) - return parse(input, options); - first = false; - return flatMap3(eff, () => finish(state)); - }); - }; - return (input, options) => { - if (input === missing) - return missingExit; - try { - if (!Array.isArray(input)) { - return fail6(new InvalidType(ast, input, options)); - } - if (!elements) { - elements = ast.elements.map((ast) => ({ - ast, - parser: compileField(ast) - })); - rest = ast.rest.map((ast) => ({ - ast, - parser: compileField(ast) - })); - } - return parse(input, options); - } catch (error) { - return die3(error); - } - }; - } - _rebuild(recur, checks, encodingChecks) { - const elements = mapOrSame(this.elements, recur); - const rest = mapOrSame(this.rest, recur); - return elements === this.elements && rest === this.rest && checks === this.checks && encodingChecks === this.encodingChecks ? this : new Arrays(this.isMutable, elements, rest, this.annotations, checks, undefined, this.context, encodingChecks); - } - recur(recur) { - return this._rebuild(recur, this.checks, this.encodingChecks); - } - flip(recur) { - return this._rebuild(recur, this.encodingChecks, this.checks); - } - getExpected() { - return "array"; - } -}; -function stepArray(s, item, exit, i) { - if (exit._tag === "Failure") { - return wrapPropertyKeyIssue(s, s.ast, i, exit); - } - const value = exit === sameExit ? item : exit[args]; - if (value !== missing) { - s.output[i] = value; - } else { - const p = s.getParser(s.tailThreshold, i); - if (isOptional(p.ast)) - return; - const issue = new Pointer([i], new MissingKey(p.ast.context?.annotations)); - if (s.options.errors === "all") { - if (s.issues) - s.issues.push(issue); - else - s.issues = [issue]; - } else { - return fail5(new Composite(s.ast, [issue], s.input, s.options)); - } - } -} -var parseArrayOptions = { - onItem(s, item, i) { - const value = i < s.len ? item : missing; - return s.getParser(s.tailThreshold, i).parser(value, s.options); - }, - step: stepArray -}; -var parseArray = /* @__PURE__ */ iterateEager()(parseArrayOptions); -var parseArrayConcurrent = /* @__PURE__ */ iterateConcurrent()(parseArrayOptions); var wrapPropertyKeyIssue = (s, ast, key, exit) => { if (exit.cause.reasons.length === 0) { return exit; @@ -5489,7 +5373,7 @@ var wrapPropertyKeyIssue = (s, ast, key, exit) => { return fail5(new Composite(ast, [pointer], s.input, s.options)); } }; -var FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?"; +var FINITE_PATTERN = "[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?"; function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) { let stringKeys; let symbolKeys; @@ -5728,9 +5612,15 @@ var Objects = class extends ASTNodeImpl { if (indexCount) return makeFallback(); let fallback; - const resume = (state, index, pending) => { + const resume = (snapshot, index, pending) => { const property = properties[index]; return flatMap3(exit2(pending), (exit) => { + const state = { + ...snapshot, + out: { + ...snapshot.out + } + }; const terminal = stepProperty(state, property, exit); if (terminal) return terminal; @@ -5860,9 +5750,6 @@ function struct(fields, checks, annotations) { function getAST(self) { return self.ast; } -function tuple(elements, checks = undefined) { - return new Arrays(false, elements.map((e) => e.ast), [], undefined, checks); -} function union(members, options, checks) { return new Union(members.map(getAST), options, undefined, checks); } @@ -6655,6 +6542,16 @@ function getConstructorDescriptor(ast) { // node_modules/effect/dist/internal/schema/interpreter.js var flatMapTransformation = (result, current, f) => result === sameExit ? f(current) : flatMapEager2(result, f); function compileTransformation(transformation) { + const apply = compileTransformationUnsafe(transformation); + return (result, current, options) => { + try { + return apply(result, current, options); + } catch (error) { + return die3(error); + } + }; +} +function compileTransformationUnsafe(transformation) { if (transformation._tag === "Middleware") { return (result, current, options) => { const transformed = result === sameExit ? transformation.decode(succeed7(toOption(current)), options) : transformation.decode(mapEager2(result, toOption), options); @@ -6730,53 +6627,57 @@ function compile(ast, compile, compileField, base, specialize) { let encodingParsers; const parseChecks = (input, options) => { let result = parser(input, options); - if (encodingChecks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const output = result === sameExit ? input : result[args]; - if (input !== missing && output !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, input, options)); + try { + if (encodingChecks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const output = result === sameExit ? input : result[args]; + if (input !== missing && output !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + result = fail6(new Composite(ast, issues, input, options)); + } } } - } - } else { - result = flatMap3(result, (value) => { - if (input !== missing && value !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - return fail6(new Composite(ast, issues, input, options)); + } else { + result = flatMap3(result, (value) => { + if (input !== missing && value !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, input, options)); + } } - } - return succeed6(value); - }); - } - } - if (checks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const value = result === sameExit ? input : result[args]; - if (value === missing) - return result; - const issues = collectIssues(checks, value, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, value, options)); - } + return succeed6(value); + }); } - } else { - result = flatMap3(result, (value) => { - if (value !== missing) { + } + if (checks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const value = result === sameExit ? input : result[args]; + if (value === missing) + return result; const issues = collectIssues(checks, value, undefined, ast, options); if (issues) { - return fail6(new Composite(ast, issues, value, options)); + result = fail6(new Composite(ast, issues, value, options)); } } - return succeed6(value); - }); + } else { + result = flatMap3(result, (value) => { + if (value !== missing) { + const issues = collectIssues(checks, value, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, value, options)); + } + } + return succeed6(value); + }); + } } + return result; + } catch (error) { + return die3(error); } - return result; }; const parseLocal = specialize === undefined ? parseChecks : specialize(parseChecks); if (!links) { @@ -7178,21 +7079,6 @@ function makeStruct(ast, fields) { function Struct(fields) { return makeStruct(struct(fields, undefined), fields); } -function makeTuple(ast, elements) { - return make8(ast, { - elements, - mapElements(f, options) { - const elements = f(this.elements); - return makeTuple(tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements); - } - }); -} -function Tuple(elements) { - return makeTuple(tuple(elements), elements); -} -var ArraySchema = /* @__PURE__ */ lambda((schema) => make8(new Arrays(false, [], [schema.ast]), { - value: schema -})); function makeUnion(ast, members) { return make8(ast, { members, @@ -7252,32 +7138,24 @@ function link() { }; } var makeFilter2 = makeFilter; -function isPattern2(regExp, annotations) { - const source = regExp.source; - const flags = regExp.flags; - const canExport = /^[dg]*uy?$/.test(flags); - const runtimeRegExp = flags === "" ? `new RegExp(${format(source)})` : `new RegExp(${format(source)}, ${format(flags)})`; - return isPattern(regExp, { - toJsonSchema: () => canExport ? { - pattern: flags.endsWith("y") ? `^(?:${source})` : source - } : [{}, true], - toCode: () => ({ - runtime: `Schema.isPattern(${runtimeRegExp})` - }), - ...annotations - }); -} function isBase64(annotations) { - const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - return isPattern2(regExp, { + const pattern = "^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"; + const regExp = /^[0-9a-zA-Z+/]*={0,2}$/; + return makeFilter2((s) => s.length % 4 === 0 && regExp.test(s), { expected: "a base64 encoded string", representation: { id: "effect/schema/isBase64", payload: null }, toJsonSchema: () => ({ - pattern: regExp.source + pattern }), + arbitraryConstraint: { + patterns: [{ + source: pattern, + flags: "" + }] + }, toCode: () => ({ runtime: "Schema.isBase64()" }), @@ -7391,47 +7269,6 @@ var File = /* @__PURE__ */ instanceOf(globalThis.File, { }) })) }); -var FormData2 = /* @__PURE__ */ instanceOf(globalThis.FormData, { - representation: { - id: "effect/schema/FormData", - payload: null - }, - toCode: () => ({ - runtime: `Schema.FormData`, - Type: `globalThis.FormData` - }), - expected: "FormData", - toCodecJson: () => link()(ArraySchema(Tuple([String4, Union2([Struct({ - _tag: tag("String"), - value: String4 - }), Struct({ - _tag: tag("File"), - value: File - })])])), transformEffect2({ - decode: (e) => { - const out = new globalThis.FormData; - for (const [key, entry] of e) { - out.append(key, entry.value); - } - return succeed6(out); - }, - encode: (formData) => { - return succeed6(globalThis.Array.from(formData.entries()).map(([key, value]) => { - if (typeof value === "string") { - return [key, { - _tag: "String", - value - }]; - } else { - return [key, { - _tag: "File", - value - }]; - } - })); - } - })) -}); var URLSearchParams2 = /* @__PURE__ */ instanceOf(globalThis.URLSearchParams, { representation: { id: "effect/schema/URLSearchParams", @@ -7547,13 +7384,16 @@ function makeClass(Inherited, identifier, struct2, annotations, proto) { } return out; } -function getClassTransformation(self) { - return new Transformation(transform((input) => new self(input, { +function makeClassTrusted(self, fields) { + return new self(fields, { "~payload": { token: payloadToken, - value: input + value: fields } - })), passthrough()); + }); +} +function getClassTransformation(self) { + return new Transformation(transform((input) => makeClassTrusted(self, input)), passthrough()); } function getClassTypeId(identifier) { return `~effect/Schema/Class/${identifier}`; @@ -8040,14 +7880,11 @@ var toTransform = (channel) => channel.transform; var asyncQueue = (scope, f, options) => make11({ capacity: options?.bufferSize, strategy: options?.strategy -}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope)))); +}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope, { + startImmediately: true +})))); var callbackArray = (f, options) => fromTransform((_, scope) => map5(asyncQueue(scope, f, options), takeAll2)); -var suspend3 = (evaluate) => fromTransform((upstream, scope) => suspend2(() => toTransform(evaluate())(upstream, scope))); var empty3 = /* @__PURE__ */ fromPull(/* @__PURE__ */ succeed6(/* @__PURE__ */ done2())); -var map7 = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => sync3(() => { - let i = 0; - return map5(pull, (o) => f(o, i++)); -}))); var mapDone = /* @__PURE__ */ dual(2, (self, f) => mapDoneEffect(self, (o) => succeed6(f(o)))); var mapDoneEffect = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => succeed6(catchDone(pull, (done) => flatMap3(f(done), done2))))); var merge2 = /* @__PURE__ */ dual((args) => isChannel(args[0]) && isChannel(args[1]), (left, right, options) => fromTransformBracket(fnUntraced2(function* (upstream, _scope, forkedScope) { @@ -8160,6 +7997,18 @@ var splitLines = () => fromTransform((upstream, _scope) => sync3(() => { } return pullOrFlush; })); +var decodeText = (encoding, options) => fromTransform((upstream, _scope) => sync3(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + let pull = upstream.pipe(map5(map2((bytes) => decoder.decode(bytes, streamOptions))), catchDone((leftover) => { + pull = done2(leftover); + const last = decoder.decode(); + return last.length > 0 ? succeed6(of(last)) : pull; + })); + return suspend2(() => pull); +})); var pipeTo = /* @__PURE__ */ dual(2, (self, that) => fromTransform((upstream, scope) => flatMap3(toTransform(self)(upstream, scope), (upstream) => toTransform(that)(upstream, scope)))); var unwrap = (channel) => fromTransform((upstream, scope) => { let pull; @@ -8427,12 +8276,7 @@ var transformPull2 = (self, f) => fromChannel3(fromTransform((_, scope) => flatM var toChannel2 = (stream) => stream.channel; var callback3 = (f, options) => fromChannel3(callbackArray(f, options)); var empty4 = /* @__PURE__ */ fromChannel3(empty3); -var suspend4 = (stream) => fromChannel3(suspend3(() => stream().channel)); var unwrap3 = (effect) => fromChannel3(unwrap(map5(effect, toChannel2))); -var map8 = /* @__PURE__ */ dual(2, (self, f) => suspend4(() => { - let i = 0; - return fromChannel3(map7(self.channel, map2((o) => f(o, i++)))); -})); var merge3 = /* @__PURE__ */ dual((args) => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel3(merge2(toChannel2(self), toChannel2(that), options))); var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (upstream, scope) => sync3(() => { let done; @@ -8454,12 +8298,7 @@ var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (up }); return suspend2(() => done ? done : pull); }))); -var decodeText = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => suspend4(() => { - const decoder = new TextDecoder(options?.encoding); - return map8(self, (chunk) => decoder.decode(chunk, { - stream: true - })); -})); +var decodeText2 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => self.channel.pipe(pipeTo(decodeText(options?.encoding)), fromChannel3)); var splitLines2 = (self) => self.channel.pipe(pipeTo(splitLines()), fromChannel3); var run2 = /* @__PURE__ */ dual(2, (self, sink) => scopedWith2((scope) => toPullScoped(self.channel, scope).pipe(flatMap3((upstream) => sink.transform(upstream, scope)), map5(([a]) => a)))); var runCollect = (self) => runFold(self.channel, () => [], (acc, chunk) => { @@ -8585,10 +8424,14 @@ var ulidString = (timestampMillis, bytes) => { }; // node_modules/effect/dist/internal/uuid.js -var hex = (byte) => byte.toString(16).padStart(2, "0"); +var hex = /* @__PURE__ */ Array.from({ + length: 256 +}, (_, byte) => byte.toString(16).padStart(2, "0")); var stringify = (bytes) => { - const segments = [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)]; - return segments.map((segment) => Array.from(segment, hex).join("")).join("-"); + if (bytes.length < 16) { + return [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)].map((segment) => Array.from(segment, (byte) => hex[byte]).join("")).join("-"); + } + return hex[bytes[0]] + hex[bytes[1]] + hex[bytes[2]] + hex[bytes[3]] + "-" + hex[bytes[4]] + hex[bytes[5]] + "-" + hex[bytes[6]] + hex[bytes[7]] + "-" + hex[bytes[8]] + hex[bytes[9]] + "-" + hex[bytes[10]] + hex[bytes[11]] + hex[bytes[12]] + hex[bytes[13]] + hex[bytes[14]] + hex[bytes[15]]; }; var randomBytes = () => globalThis.crypto.getRandomValues(new Uint8Array(16)); function v4Bytes(bytes = randomBytes()) { @@ -8707,23 +8550,26 @@ var defaultTeardown = (exit, onExit) => { return onExit(getErrorExitCode(squash(exit.cause))); }; var makeRunMain = (f) => dual((args) => isEffect2(args[0]), (effect, options) => { - const fiber = options?.disableErrorReporting === true ? runFork2(effect) : runFork2(tapCause2(effect, (cause) => { + const main = options?.disableErrorReporting === true ? effect : tapCause2(effect, (cause) => { if (hasInterruptsOnly2(cause)) return void_3; const isReported = getErrorReported(squash(cause)); return isReported ? logError(cause) : void_3; - })); - try { - const keepAlive = globalThis.setInterval(constVoid, 2147483647); - fiber.addObserver(() => { - clearInterval(keepAlive); - }); - } catch {} - const teardown = options?.teardown ?? defaultTeardown; - return f({ - fiber, - teardown }); + const teardown = options?.teardown ?? defaultTeardown; + runFork2(withFiber2((fiber) => { + try { + const keepAlive = globalThis.setInterval(constVoid, 2147483647); + fiber.addObserver(() => { + clearInterval(keepAlive); + }); + } catch {} + f({ + fiber, + teardown + }); + return main; + })); }); var errorExitCode = "~effect/Runtime/errorExitCode"; var getErrorExitCode = (u) => { @@ -8828,7 +8674,7 @@ var makeHandle = (params) => Object.setPrototypeOf({ ...params }, HandleProto); var make20 = (spawn) => { - const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); + const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText2(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); const streamLines = (command, options) => splitLines2(streamString(command, options)); return ChildProcessSpawner.of({ spawn, @@ -8997,6 +8843,7 @@ var handleErrnoException = (module, method) => (err, [path]) => { reason = "NotFound"; break; case "EACCES": + case "EPERM": reason = "PermissionDenied"; break; case "EEXIST": @@ -9025,66 +8872,149 @@ var handleErrnoException = (module, method) => (err, [path]) => { }); }; +// node_modules/@effect/platform-node-shared/dist/NodeSink.js +import { finished } from "node:stream"; + +// node_modules/@effect/platform-node-shared/dist/internal/stream.js +var destroyStream = (stream, cleanup, onDestroyed) => { + if (!("closed" in stream)) { + cleanup(); + onDestroyed?.(); + return; + } + const onDone = () => { + clearImmediate(immediate); + stream.off("error", onDone); + stream.off("close", onDone); + onDestroyed?.(); + }; + const onClosed = () => { + if (stream.closed) { + onDone(); + } else { + immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + } + }; + let immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + stream.once("error", onDone); + stream.once("close", onDone); + cleanup(); + if (!stream.closed) { + stream.destroy(); + } +}; + // node_modules/@effect/platform-node-shared/dist/NodeSink.js var fromWritable = (options) => fromChannel2(mapDone(fromWritableChannel(options), (_) => [_])); var fromWritableChannel = (options) => fromTransform((pull) => { const writable = options.evaluate(); - return succeed6(pullIntoWritable({ + const write = pullIntoWritable({ ...options, writable, pull - })); -}); -var pullIntoWritable = (options) => options.pull.pipe(flatMap3((chunk) => { - let i = 0; - return callback2((resume) => { - let cancelled = false; - const loop = () => { - for (;i < chunk.length; ) { - if (cancelled) { - return; - } - const success = options.writable.write(chunk[i++], options.encoding); - if (!success) { - if (!cancelled) { - options.writable.once("drain", loop); + }); + return succeed6(options.endOnDone === false ? write : onError2(write, (cause) => isDoneCause(cause) ? void_3 : releaseWritable(writable))); +}); +var releaseWritable = (writable) => callback2((resume) => { + const onDestroyed = () => resume(void_3); + if (writable.closed) { + const cleanup = finished(writable, { + readable: false + }, () => { + cleanup(); + onDestroyed(); + }); + } else { + destroyStream(writable, constVoid, onDestroyed); + } +}); +var pullIntoWritable = (options) => withFiber2((fiber) => { + const dispatcher = fiber.currentDispatcher; + const completion = makeUnsafe2(); + const failure = makeUnsafe2(); + const onError = (error) => doneUnsafe(failure, failSync2(() => options.onError(error))); + let errorEmitted = false; + const onStreamError = (error) => { + errorEmitted = true; + onError(error); + }; + options.writable.on("error", onStreamError); + const cleanup = finished(options.writable, { + readable: false + }, (error) => { + if (error) { + onError(error); + } else { + doneUnsafe(completion, void_3); + } + }); + return options.pull.pipe(flatMap3((chunk) => { + let i = 0; + return callback2((resume) => { + let cancelled = false; + const onFinish = () => dispatcher.scheduleTask(loop, 0); + const loop = () => { + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + for (;i < chunk.length; ) { + if (cancelled) { + return; + } + const success = options.writable.write(chunk[i++], options.encoding, (error) => { + if (!error) + return; + if (options.writable.closed) { + onError(error); + } else { + dispatcher.scheduleTask(() => onError(error), 0); + } + }); + if (!success) { + if (!cancelled) { + options.writable.once("drain", loop); + options.writable.once("finish", onFinish); + } + return; } - return; } - } - if (!cancelled) { - resume(void_3); - } - }; - loop(); - return sync3(() => { - cancelled = true; - options.writable.off("drain", loop); + if (!cancelled) { + resume(void_3); + } + }; + loop(); + return sync3(() => { + cancelled = true; + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + }); }); - }); -}), forever2({ - disableYield: true -}), options.endOnDone !== false ? catchDone((_) => { - if ("closed" in options.writable && options.writable.closed) { - return done2(_); - } - return callback2((resume) => { - const onFinish = () => resume(done2(_)); - options.writable.once("finish", onFinish); + }), forever2({ + disableYield: true + }), options.endOnDone !== false ? catchDone((_) => { options.writable.end(); - return sync3(() => { - options.writable.off("finish", onFinish); - }); - }); -}) : identity, raceFirst2(callback2((resume) => { - const onError = (error) => resume(fail6(options.onError(error))); - options.writable.once("error", onError); - return sync3(() => { - options.writable.off("error", onError); - }); -}))); + return andThen2(_await(completion), done2(_)); + }) : identity, raceFirst2(_await(failure)), ensuring2(sync3(() => { + cleanup(); + const removeErrorListener = () => { + options.writable.off("error", onStreamError); + options.writable.off("error", removeErrorListener); + options.writable.off("close", removeErrorListener); + }; + if (options.writable.errored && !options.writable.closed && !errorEmitted) { + options.writable.once("error", removeErrorListener); + options.writable.once("close", removeErrorListener); + } else { + removeErrorListener(); + } + }))); +}); // node_modules/@effect/platform-node-shared/dist/NodeStream.js +import { finished as finished2, Readable } from "node:stream"; var fromReadable = (options) => fromChannel3(fromReadableChannel(options)); var fromReadableChannel = (options) => fromTransform((_, scope) => readableToPullUnsafe({ scope, @@ -9101,17 +9031,14 @@ var readableToPullUnsafe = (options) => { function onReadable() { latch.openUnsafe(); } - function onError(error) { - exit.current = fail5(options.onError(error)); - latch.openUnsafe(); - } - function onEnd() { - exit.current = fail5(Done2()); - latch.openUnsafe(); - } readable.on("readable", onReadable); - readable.once("error", onError); - readable.once("end", onEnd); + const cleanup = finished2(readable, { + readable: true, + writable: false + }, (error) => { + exit.current ??= fail5(error ? options.onError(error) : Done2()); + latch.openUnsafe(); + }); const pull = suspend2(function loop() { let item = options.readable.read(options.chunkSize); if (item === null) { @@ -9135,10 +9062,10 @@ var readableToPullUnsafe = (options) => { }); return as2(addFinalizer2(options.scope, sync3(() => { readable.off("readable", onReadable); - readable.off("error", onError); - readable.off("end", onEnd); - if (closeOnDone && "closed" in options.readable && !options.readable.closed) { - options.readable.destroy(); + if (closeOnDone) { + destroyStream(readable, cleanup); + } else { + cleanup(); } })), pull); }; @@ -9463,6 +9390,7 @@ var make22 = /* @__PURE__ */ gen2(function* () { const signalGroup = (signal) => killProcessGroup(command, childProcess, signal).pipe(catch_2(() => killProcess(command, childProcess, signal))); yield* signalGroup(options?.killSignal ?? "SIGTERM"); if (isUndefined(options?.forceKillAfter)) { + yield* _await(exitSignal); yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis); } else { yield* awaitProcessExit(childProcess, exitSignal, toMillis(options.forceKillAfter)); @@ -10056,14 +9984,14 @@ var readLink = /* @__PURE__ */ (() => { return (path) => nodeReadLink(path); })(); var realPath = /* @__PURE__ */ (() => { - const nodeRealPath = /* @__PURE__ */ effectify(NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); + const nodeRealPath = /* @__PURE__ */ effectify(process.platform === "win32" ? NFS.realpath.native : NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); return (path) => nodeRealPath(path); })(); var rename2 = /* @__PURE__ */ (() => { const nodeRename = /* @__PURE__ */ effectify(NFS.rename, /* @__PURE__ */ handleErrnoException("FileSystem", "rename"), /* @__PURE__ */ handleBadArgument("rename")); return (oldPath, newPath) => nodeRename(oldPath, newPath); })(); -var makeFileInfo = (stat) => try_2({ +var makeFileInfo = (stat, method = "stat") => try_2({ try: () => ({ type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown", mtime: fromNullishOr(stat.mtime), @@ -10080,14 +10008,16 @@ var makeFileInfo = (stat) => try_2({ blksize: stat.blksize !== undefined ? some2(bytes(stat.blksize)) : none2(), blocks: fromNullishOr(stat.blocks) }), - catch: handleBadArgument("stat") + catch: handleBadArgument(method) }); -var stat2 = /* @__PURE__ */ (() => { - const nodeStat = /* @__PURE__ */ effectify(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat")); +var statFactory = (method, nodeStatFn) => { + const nodeStat = effectify(nodeStatFn, handleErrnoException("FileSystem", method), handleBadArgument(method)); return (path) => flatMap3(nodeStat(path, { bigint: true - }), makeFileInfo); -})(); + }), (stat) => makeFileInfo(stat, method)); +}; +var stat2 = /* @__PURE__ */ statFactory("stat", NFS.stat); +var lstat2 = /* @__PURE__ */ statFactory("lstat", NFS.lstat); var symlink2 = /* @__PURE__ */ (() => { const nodeSymlink = /* @__PURE__ */ effectify(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink")); return (target, path) => nodeSymlink(target, path); @@ -10170,6 +10100,7 @@ var makeFileSystem = /* @__PURE__ */ map5(/* @__PURE__ */ serviceOption2(WatchBa copyFile: copyFile2, glob: glob2, link: link3, + lstat: lstat2, makeDirectory, makeTempDirectory, makeTempDirectoryScoped, @@ -10309,9 +10240,6 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readline.emitKeypressEvents(stdin, rl); rl.on("line", onLine); rl.once("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(true); - } return { rl, onClose, @@ -10325,9 +10253,6 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readlineActive = false; rl.off("line", onLine); rl.off("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(false); - } rl.close(); if (inputEnded) { endUnsafe(lines); @@ -10335,6 +10260,14 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu })), idleTimeToLive: "10 millis" }); + const setRawMode = (enabled) => sync3(() => { + if (stdin.isTTY) + stdin.setRawMode(enabled); + }); + const rawModeRef = yield* make13({ + acquire: acquireRelease2(setRawMode(true), () => setRawMode(false)), + idleTimeToLive: "10 millis" + }); const columns = sync3(() => stdout.columns ?? 0); const rows = sync3(() => stdout.rows ?? 0); const readInput = gen2(function* () { @@ -10369,6 +10302,7 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu handleEnd(); } else { yield* get3(rlRef); + yield* get3(rawModeRef); stdin.once("end", handleEnd); } return queue; @@ -10487,7 +10421,7 @@ class CommandError extends TaggedError3()("CommandError", { }) { } var error = (command, cause) => new CommandError({ command, exitCode: -1, stderr: String(cause) }); -var collectText = (stream) => stream.pipe(decodeText(), runFold2(() => "", (all, chunk) => all + chunk)); +var collectText = (stream) => stream.pipe(decodeText2(), runFold2(() => "", (all, chunk) => all + chunk)); var retainedStderrLength = 16 * 1024; class Service3 extends Service()("@timmo001/workflows/CommandExecutor") { @@ -10540,8 +10474,8 @@ var layer14 = effect(Service3, gen2(function* () { stdin: "inherit" })); let stderrTail = ""; - const stdout = handle.stdout.pipe(decodeText(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); - const stderr = handle.stderr.pipe(decodeText(), runForEach2((chunk) => sync3(() => { + const stdout = handle.stdout.pipe(decodeText2(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); + const stderr = handle.stderr.pipe(decodeText2(), runForEach2((chunk) => sync3(() => { process.stderr.write(chunk); stderrTail = `${stderrTail}${chunk}`.slice(-retainedStderrLength); }))); diff --git a/.github/actions/release-bun-cli/dist/index.js b/.github/actions/release-bun-cli/dist/index.js index 7730c9d3..b27dcf41 100644 --- a/.github/actions/release-bun-cli/dist/index.js +++ b/.github/actions/release-bun-cli/dist/index.js @@ -785,6 +785,10 @@ function assignProperty(self, key, value) { } } function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } for (const key of Reflect.ownKeys(source)) { if (Object.prototype.propertyIsEnumerable.call(source, key)) { assignProperty(self, key, source[key]); @@ -875,7 +879,7 @@ class CauseImpl { toJSON() { return { _id: "Cause", - failures: this.reasons.map((f) => f.toJSON()) + reasons: this.reasons.map((f) => f.toJSON()) }; } toString() { @@ -1654,9 +1658,21 @@ var bigint2 = /* @__PURE__ */ BigInt(2); var bigint10 = /* @__PURE__ */ BigInt(10); var bigint1e3 = /* @__PURE__ */ BigInt(1000); var bigint1e6 = /* @__PURE__ */ BigInt(1e6); +var bigint1e9 = /* @__PURE__ */ BigInt(1e9); +var bigintNanosPerMinute = /* @__PURE__ */ BigInt(60000000000); +var bigintNanosPerHour = /* @__PURE__ */ BigInt(3600000000000); +var bigintNanosPerDay = /* @__PURE__ */ BigInt(86400000000000); +var bigintNanosPerWeek = /* @__PURE__ */ BigInt(604800000000000); var roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input))); var roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6); var fromNanosNumber = (nanos) => make3(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos); +var nanosToUnit = (nanos, divisor) => { + const value = Number(nanos); + if (Number.isFinite(value)) + return value / divisor; + const scale = BigInt(divisor); + return Number(nanos / scale) + Number(nanos % scale) / divisor; +}; var parseNanos = (input, scale) => { const decimalIndex = input.indexOf("."); if (decimalIndex === -1) @@ -1672,6 +1688,13 @@ var divideTiesAwayFromZero = (numerator, denominator) => { const rounded = absolute / denominator + (absolute % denominator * bigint2 >= denominator ? bigint1 : bigint0); return numerator < bigint0 ? -rounded : rounded; }; +var fromMillisString = (input, scale) => { + const millis = Number(input) * scale; + if (!Number.isFinite(millis)) + return make3(millis); + const nanos = parseNanos(input, BigInt(scale) * bigint1e6); + return make3(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos); +}; var DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; var fromInputUnsafe = (input) => { switch (typeof input) { @@ -1696,26 +1719,25 @@ var fromInputUnsafe = (input) => { if (unit === "micro" || unit === "micros") { return nanos(parseNanos(valueStr, bigint1e3)); } - const value = Number(valueStr); switch (unit) { case "milli": case "millis": - return millis(value); + return fromMillisString(valueStr, 1); case "second": case "seconds": - return seconds(value); + return fromMillisString(valueStr, 1000); case "minute": case "minutes": - return minutes(value); + return fromMillisString(valueStr, 60000); case "hour": case "hours": - return hours(value); + return fromMillisString(valueStr, 3600000); case "day": case "days": - return days(value); + return fromMillisString(valueStr, 86400000); case "week": case "weeks": - return weeks(value); + return fromMillisString(valueStr, 604800000); } break; } @@ -1737,7 +1759,8 @@ var fromInputUnsafe = (input) => { if (input[0] === Infinity || input[1] === Infinity) { return infinity; } - return fromNanosNumber(input[0] * 1e9 + input[1]); + const nanos = input[0] * 1e9 + input[1]; + return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make3(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos); } const obj = input; let millis = 0; @@ -1753,13 +1776,42 @@ var fromInputUnsafe = (input) => { millis += obj.seconds * 1000; if (obj.milliseconds) millis += obj.milliseconds; - if (!obj.microseconds && !obj.nanoseconds) - return make3(millis); - return fromNanosNumber(millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0)); + if (!obj.microseconds && !obj.nanoseconds) { + if (!Number.isFinite(millis)) + return make3(millis); + const exact = sumObjectNanos(obj); + return exact === undefined || BigInt(millis) * bigint1e6 === exact ? make3(millis) : make3(exact); + } + const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0); + const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : undefined; + return exact === undefined ? fromNanosNumber(nanos) : make3(exact); } } return invalid(input); }; +var isIntegerOrUnset = (n) => !n || Number.isInteger(n); +var sumObjectNanos = (obj) => { + if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds)) + return; + let nanos = bigint0; + if (obj.weeks) + nanos += BigInt(obj.weeks) * bigintNanosPerWeek; + if (obj.days) + nanos += BigInt(obj.days) * bigintNanosPerDay; + if (obj.hours) + nanos += BigInt(obj.hours) * bigintNanosPerHour; + if (obj.minutes) + nanos += BigInt(obj.minutes) * bigintNanosPerMinute; + if (obj.seconds) + nanos += BigInt(obj.seconds) * bigint1e9; + if (obj.milliseconds) + nanos += BigInt(obj.milliseconds) * bigint1e6; + if (obj.microseconds) + nanos += BigInt(obj.microseconds) * bigint1e3; + if (obj.nanoseconds) + nanos += BigInt(obj.nanoseconds); + return nanos; +}; var invalid = (input) => { throw new Error(`Invalid Input: ${input}`); }; @@ -1868,14 +1920,9 @@ var infinity = /* @__PURE__ */ make3(Infinity); var negativeInfinity = /* @__PURE__ */ make3(-Infinity); var nanos = (nanos) => make3(nanos); var millis = (millis) => make3(millis); -var seconds = (seconds) => make3(seconds * 1000); -var minutes = (minutes) => make3(minutes * 60000); -var hours = (hours) => make3(hours * 3600000); -var days = (days) => make3(days * 86400000); -var weeks = (weeks) => make3(weeks * 604800000); var toMillis = (self) => match3(fromInputUnsafe(self), { onMillis: identity, - onNanos: (nanos) => Number(nanos) / 1e6, + onNanos: (nanos) => nanosToUnit(nanos, 1e6), onInfinity: () => Infinity, onNegativeInfinity: () => -Infinity }); @@ -1957,7 +2004,7 @@ var setTimer = "setImmediate" in globalThis ? (f) => { const timer = setTimeout(f, 0); return () => clearTimeout(timer); }; -var setImmediate = (f) => { +var setImmediate2 = (f) => { try { return setTimer(f); } catch { @@ -1997,7 +2044,7 @@ class MixedScheduler { setImmediate; constructor(executionMode = "async", setImmediateFn) { this.executionMode = executionMode; - this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate2); } shouldYield(fiber) { return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; @@ -2011,7 +2058,7 @@ class MixedSchedulerDispatcher { tasks = /* @__PURE__ */ new PriorityBuckets; running = undefined; setImmediate; - constructor(setImmediateFn = setImmediate) { + constructor(setImmediateFn = setImmediate2) { this.setImmediate = setImmediateFn; } scheduleTask(task, priority) { @@ -2255,10 +2302,7 @@ class Interrupt extends ReasonBase { } } var causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); -var findFail = (self) => { - const reason = self.reasons.find(isFailReason); - return reason ? succeed2(reason) : fail2(self); -}; +var hasFails = (self) => self.reasons.some(isFailReason); var findError = (self) => { for (let i = 0;i < self.reasons.length; i++) { const reason = self.reasons[i]; @@ -2268,6 +2312,9 @@ var findError = (self) => { } return fail2(self); }; +var hasDies = (self) => self.reasons.some(isDieReason); +var causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +var findRecoverableError = (self) => hasDies(self) ? fail2(causeElectDefects(self)) : findError(self); var hasInterrupts = (self) => self.reasons.some(isInterruptReason); var hasInterruptsOnly = (self) => self.reasons.length > 0 && self.reasons.every(isInterruptReason); var causeMap = /* @__PURE__ */ dual(2, (self, f) => { @@ -2328,12 +2375,14 @@ var causePrettyErrors = (self, options) => { } return errors; }; -var causePrettyError = (original, annotations, options) => { +var causePrettyError = (original, annotations, options, seen = new Set) => { const kind = typeof original; let error; if (original && kind === "object") { + seen.add(original); + const cause = original.cause; error = new globalThis.Error(causePrettyMessage(original), { - cause: original.cause ? causePrettyError(original.cause) : undefined + cause: cause !== undefined && !seen.has(cause) ? causePrettyError(cause, undefined, undefined, seen) : undefined }); if (typeof original.name === "string") { error.name = original.name; @@ -2544,7 +2593,11 @@ class FiberImpl { } else if (this._asyncContext !== undefined) { const asyncContext = this._asyncContext; this._asyncContext = undefined; - return asyncContext.runInAsyncScope(this.evaluate, this, effect); + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } } else if (this._yielded !== undefined) { const yielded = this._yielded; this._yielded = undefined; @@ -2849,7 +2902,6 @@ var tryPromise = (options) => { } }, f.length !== 0); }; -var withFiberId = (f) => withFiber((fiber) => f(fiber.id)); var callbackOptions = /* @__PURE__ */ function() { const Proto = /* @__PURE__ */ makePrimitiveProto({ op: "Async", @@ -2870,9 +2922,9 @@ var callbackOptions = /* @__PURE__ */ function() { if (yielded !== false) return yielded; yielded = true; - fiber._yielded = () => { + fiber.yieldWith(() => { resumed = true; - }; + }); if (controller === undefined && onCancel === undefined) { return Yield; } @@ -3156,10 +3208,7 @@ var exitMap = /* @__PURE__ */ dual(2, (self, f) => self._tag === "Success" ? exi var exitMapError = /* @__PURE__ */ dual(2, (self, f) => { if (self._tag === "Success") return self; - const error = findError(self.cause); - if (isFailure2(error)) - return self; - return exitFail(f(error.success)); + return exitFailCause(causeMap(self.cause, f)); }); var exitZipRight = /* @__PURE__ */ dual(2, (self, that) => exitIsSuccess(self) ? that : self); var exitAsVoidAll = (exits) => { @@ -3223,7 +3272,7 @@ var catchCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(s const eb = filter(cause); return isFailure2(eb) ? failCause(eb.failure) : f(eb.success, cause); })); -var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findError, (e) => f(e))); +var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findRecoverableError, (e) => f(e))); var tapCause = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => andThen(f(cause), failCause(cause)))); var tapCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(self, (cause) => { const result = filter(cause); @@ -3234,7 +3283,7 @@ var tapCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(sel })); var tapError = /* @__PURE__ */ dual(2, (self, f) => tapCauseFilter(self, findError, (e) => f(e))); var catchIf = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, predicate, f, orElse) => catchCause(self, (cause) => { - const error = findError(cause); + const error = findRecoverableError(cause); if (isFailure2(error)) return failCause(error.failure); if (!predicate(error.success)) { @@ -3246,7 +3295,7 @@ var catchTag = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, k, f, or const pred = Array.isArray(k) ? (e) => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); return catchIf(self, pred, f, orElse); }); -var mapError = /* @__PURE__ */ dual(2, (self, f) => catch_(self, (error) => failSync(() => f(error)))); +var mapError = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => failCause(causeMap(cause, f)))); var orDie = (self) => catch_(self, die); var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { if (!options?.log) { @@ -3258,12 +3307,25 @@ var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) = const logEffect = logWithLevel(options.log === true ? undefined : options.log); return matchCauseEffect(self, { onFailure(cause) { - const failure = findFail(cause); - return isFailure2(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); }, onSuccess: (_) => void_ }); }); +var ignoreCause = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { + if (!options?.log) { + return matchCauseEffect(self, { + onFailure: (_) => void_, + onSuccess: (_) => void_ + }); + } + const logEffect = logWithLevel(options.log === true ? undefined : options.log); + return matchCauseEffect(self, { + onFailure: (cause) => options.message === undefined ? logEffect(cause) : logEffect(options.message, cause), + onSuccess: (_) => void_ + }); +}); var result = (self) => matchEager(self, { onFailure: fail2, onSuccess: succeed2 @@ -3298,16 +3360,16 @@ var makeMatch = (op, onFailure) => { return MatchImpl; }; var MatchImpl = /* @__PURE__ */ makeMatch("Match", function(cause, fiber) { - const fail = cause.reasons.find(isFailReason); - if (fail === undefined) - return failCause(cause); + const error = findRecoverableError(cause); + if (isFailure2(error)) + return failCause(error.failure); const handlers = this.payload; - return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(fail.error) : internalCall(() => handlers.onFailure(fail.error))); + return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))); }); var matchEffect = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, { onFailure: (cause) => { - const fail = cause.reasons.find(isFailReason); - return fail ? options.onFailure(fail.error) : failCause(cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.onFailure(error.success); }, onSuccess: options.onSuccess })); @@ -3316,9 +3378,9 @@ var matchEager = /* @__PURE__ */ dual(2, (self, options) => { if (effectIsExit(self)) { if (self._tag === "Success") return exitSucceed(options.onSuccess(self.value)); - const error = findError(self.cause); + const error = findRecoverableError(self.cause); if (isFailure2(error)) - return self; + return exitFailCause(error.failure); return exitSucceed(options.onFailure(error.success)); } return match4(self, options); @@ -3375,17 +3437,17 @@ var runFinalizer = (finalizer, exit_) => { return exitDie(defect); } }; -var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeCombine(exit_.cause, cause))); +var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); var scopeCloseFinalizers = /* @__PURE__ */ fnUntraced(function* (self, finalizers, exit_) { let exits = []; const fibers = []; - const arr = Array.from(finalizers.values()); + const arr = Array.from(finalizers); const parent = getCurrentFiber(); for (let i = arr.length - 1;i >= 0; i--) { - const finalizer = arr[i]; + const [key, finalizer] = arr[i]; if (self.strategy === "sequential") { exits.push(yield* exit(runFinalizer(finalizer, exit_))); - } else { + } else if (key !== parent) { fibers.push(forkUnsafe(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); } } @@ -3578,15 +3640,9 @@ var all = (arg, options) => { } else if (options?.discard) { return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options); } - return suspend(() => { - const out = {}; - return as(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => { - assignProperty(out, key, value); - }), { - discard: true, - concurrency: options?.concurrency - }), out); - }); + return suspend(() => map3(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => [key, value]), { + concurrency: options?.concurrency + }), Object.fromEntries)); }; var whileLoop = /* @__PURE__ */ makePrimitive({ op: "While", @@ -3725,7 +3781,7 @@ var iterateConcurrentImpl = (options) => { const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); if (reasons.length > 0) { const cause = causeFromReasons(reasons); - terminal = exitFailCause(terminal._tag === "Failure" ? causeCombine(terminal.cause, cause) : cause); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); } } } else { @@ -3807,14 +3863,13 @@ var forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterrupt } return child; }; +var fiberScopeFinalizer = (fiber) => () => withFiber((current) => current === fiber ? void_ : fiberInterrupt(fiber)); var forkIn = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, scope, options) => withFiber((parent) => { - const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + const fiber = scope.state._tag === "Closed" ? new FiberImpl(parent.context) : forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); if (!fiber._exit) { if (scope.state._tag !== "Closed") { - const key = {}; - const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); - scopeAddFinalizerUnsafe(scope, key, finalizer); - fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + scopeAddFinalizerUnsafe(scope, fiber, fiberScopeFinalizer(fiber)); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, fiber)); } else { fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); } @@ -3851,7 +3906,7 @@ var fiberRunIn = /* @__PURE__ */ dual(2, (self, scope) => { return self; } scopeRemoveFinalizerUnsafe(scope, self); - scopeAddFinalizerUnsafe(scope, self, () => fiberInterrupt(self)); + scopeAddFinalizerUnsafe(scope, self, fiberScopeFinalizer(self)); self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, self)); return self; }); @@ -4303,7 +4358,6 @@ var die2 = causeDie; var hasInterruptsOnly2 = hasInterruptsOnly; var map4 = causeMap; var squash = causeSquash; -var findError2 = findError; var isDone2 = isDone; var Done2 = Done; var done2 = done; @@ -4313,6 +4367,7 @@ var UnknownError2 = UnknownError; var succeed4 = exitSucceed; var failCause2 = exitFailCause; var fail5 = exitFail; +var interrupt2 = exitInterrupt; var void_2 = exitVoid; var isSuccess3 = exitIsSuccess; var isFailure3 = exitIsFailure; @@ -4497,8 +4552,8 @@ var mergeAllEffect = (layers, memoMap, scope) => { concurrency: layers.length }).pipe(map3((context) => mergeAll(...context))); }; -var mergeAll2 = (...layers) => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); -var provideWith = (self, that, f) => fromBuild((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); +var mergeAll2 = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +var provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); var provide2 = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, identity)); var provideMerge = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, (self, that) => merge(that, self))); @@ -4700,11 +4755,10 @@ var provideLayer = (self, layer, options) => scopedWith((scope) => flatMap2(opti var provide3 = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll2(...source) : source, options)); // node_modules/effect/dist/internal/schedule.js -var findErrorOnly = (cause) => cause.reasons.every(isFailReason) ? findError(cause) : fail2(cause); var retryOrElse = /* @__PURE__ */ dual(3, (self, policy, orElse) => flatMap2(toStepWithMetadata(policy), (step) => { let meta = CurrentMetadata.defaultValue(); let lastError; - const loop = catchCauseFilter(suspend(() => provideService(self, CurrentMetadata, meta)), findErrorOnly, (error) => { + const loop = catchCauseFilter(suspend(() => provideService(self, CurrentMetadata, meta)), findRecoverableError, (error) => { lastError = error; return flatMap2(step(error), (meta_) => { meta = meta_; @@ -4758,6 +4812,7 @@ var callback2 = callback; var never2 = never; var gen2 = gen; var fail6 = fail3; +var failSync2 = failSync; var failCause3 = failCause; var failCauseSync2 = failCauseSync; var die3 = die; @@ -4780,6 +4835,7 @@ var tapError2 = tapError; var tapCause2 = tapCause; var retry2 = retry; var ignore2 = ignore; +var ignoreCause2 = ignoreCause; var timeoutOrElse2 = timeoutOrElse; var sleep2 = sleep; var raceFirst2 = raceFirst; @@ -4797,7 +4853,7 @@ var ensuring2 = ensuring; var onError2 = onError; var onExitPrimitive2 = onExitPrimitive; var onExit2 = onExit; -var interrupt2 = interrupt; +var interrupt3 = interrupt; var uninterruptible2 = uninterruptible; var uninterruptibleMask2 = uninterruptibleMask; var forever3 = forever; @@ -4812,16 +4868,23 @@ var fn2 = fn; var clockWith2 = clockWith; var logError = /* @__PURE__ */ logWithLevel("Error"); var effectify = (fn, onError, onSyncError) => (...args) => callback2((resume) => { + let synchronous = true; + let pending; try { fn(...args, (err, result) => { - if (err) { - resume(onError ? suspend2(() => fail6(onError(err, args))) : fail6(err)); + const effect = err ? onError ? suspend2(() => fail6(onError(err, args))) : fail6(err) : succeed6(result); + if (synchronous) { + pending ??= effect; } else { - resume(succeed6(result)); + resume(effect); } }); } catch (err) { - resume(onSyncError ? fail6(onSyncError(err, args)) : die3(err)); + pending = onSyncError ? fail6(onSyncError(err, args)) : die3(err); + } + synchronous = false; + if (pending) { + resume(pending); } }); var mapEager2 = mapEager; @@ -5232,7 +5295,7 @@ var defaultLeafHook = (issue) => { } } }; -var defaultCheckHook = (issue) => findMessage(issue.issue) ?? findMessage(issue); +var defaultCheckHook = (issue) => findMessage(issue) ?? findMessage(issue.issue); function formatInput(issue) { return hasInput(issue) ? format(issue.input) : undefined; } @@ -5244,6 +5307,13 @@ function getExpectedMessage(expected, issue) { const input = formatInput(issue); return input === undefined ? `Expected ${expected}` : `Expected ${expected}, got ${input}`; } +function getFilterMessage(issue, checkHook) { + const message = checkHook(issue); + if (message !== undefined || issue.issue._tag !== "InvalidValue") + return message; + const expected = findExpected(issue.issue); + return expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); +} function formatCheck(check) { const expected = check.annotations?.expected; if (typeof expected === "string") @@ -5259,44 +5329,33 @@ function makeFormatterDefault() { return (issue) => formatIssue(issue, ""); } var defaultFormatter = /* @__PURE__ */ makeFormatterDefault(); -function formatIssue(issue, path) { +function formatIssue(issue, path, messageOverride) { let message; switch (issue._tag) { - case "Filter": { - const annotated = defaultCheckHook(issue); - if (annotated !== undefined) { - message = annotated; - } else { - if (issue.issue._tag !== "InvalidValue") { - return formatIssue(issue.issue, path); - } - const expected = findExpected(issue.issue); - message = expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); - } - break; - } + case "Filter": + return formatIssue(issue.issue, path, messageOverride ?? getFilterMessage(issue, defaultCheckHook)); case "Encoding": - return formatIssue(issue.issue, path); + return formatIssue(issue.issue, path, messageOverride); case "Pointer": - return formatIssue(issue.issue, path + formatPath(issue.path)); + return formatIssue(issue.issue, path + formatPath(issue.path), messageOverride); case "Composite": case "AnyOf": { if (issue._tag === "Composite" || issue.issues.length > 0) { - return issue.issues.map((issue) => formatIssue(issue, path)).join(` + return issue.issues.map((issue) => formatIssue(issue, path, messageOverride)).join(` `); } - message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); + message = messageOverride ?? findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); break; } default: - message = defaultLeafHook(issue); + message = messageOverride ?? defaultLeafHook(issue); break; } return path ? `${message} at ${path}` : message; } function findMessage(issue) { - if (issue._tag === "Pointer") + if (issue._tag === "Pointer" || issue._tag === "Composite") return; if (issue._tag === "Encoding") return findMessage(issue.issue); @@ -5554,7 +5613,12 @@ var Declaration = class extends ASTNodeImpl { return (input, options) => { if (input === missing) return missingExit; - return (run ??= this.run(this.typeParameters))(input, this, options); + run ??= this.run(this.typeParameters); + try { + return run(input, this, options); + } catch (error) { + return die3(error); + } }; } _rebuild(recur, checks, encodingChecks, run, encodingRun) { @@ -5763,7 +5827,7 @@ var Arrays = class extends ASTNodeImpl { input, len, tailThreshold: Math.max(elementLen, len - tailLen), - output: new globalThis.Array(len), + output: [], issues: undefined, options }; @@ -5872,7 +5936,7 @@ var wrapPropertyKeyIssue = (s, ast, key, exit) => { return fail5(new Composite(ast, [pointer], s.input, s.options)); } }; -var FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?"; +var FINITE_PATTERN = "[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?"; function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) { let stringKeys; let symbolKeys; @@ -6111,9 +6175,15 @@ var Objects = class extends ASTNodeImpl { if (indexCount) return makeFallback(); let fallback; - const resume = (state, index, pending) => { + const resume = (snapshot, index, pending) => { const property = properties[index]; return flatMap3(exit2(pending), (exit) => { + const state = { + ...snapshot, + out: { + ...snapshot.out + } + }; const terminal = stepProperty(state, property, exit); if (terminal) return terminal; @@ -6243,9 +6313,6 @@ function struct(fields, checks, annotations) { function getAST(self) { return self.ast; } -function tuple(elements, checks = undefined) { - return new Arrays(false, elements.map((e) => e.ast), [], undefined, checks); -} function union(members, options, checks) { return new Union(members.map(getAST), options, undefined, checks); } @@ -7117,6 +7184,16 @@ var unknownToStringTree = /* @__PURE__ */ new Link(StringTree, /* @__PURE__ */ p // node_modules/effect/dist/internal/schema/interpreter.js var flatMapTransformation = (result, current, f) => result === sameExit ? f(current) : flatMapEager2(result, f); function compileTransformation(transformation) { + const apply = compileTransformationUnsafe(transformation); + return (result, current, options) => { + try { + return apply(result, current, options); + } catch (error) { + return die3(error); + } + }; +} +function compileTransformationUnsafe(transformation) { if (transformation._tag === "Middleware") { return (result, current, options) => { const transformed = result === sameExit ? transformation.decode(succeed7(toOption(current)), options) : transformation.decode(mapEager2(result, toOption), options); @@ -7192,53 +7269,57 @@ function compile(ast, compile, compileField, base, specialize) { let encodingParsers; const parseChecks = (input, options) => { let result = parser(input, options); - if (encodingChecks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const output = result === sameExit ? input : result[args]; - if (input !== missing && output !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, input, options)); + try { + if (encodingChecks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const output = result === sameExit ? input : result[args]; + if (input !== missing && output !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + result = fail6(new Composite(ast, issues, input, options)); + } } } - } - } else { - result = flatMap3(result, (value) => { - if (input !== missing && value !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - return fail6(new Composite(ast, issues, input, options)); + } else { + result = flatMap3(result, (value) => { + if (input !== missing && value !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, input, options)); + } } - } - return succeed6(value); - }); - } - } - if (checks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const value = result === sameExit ? input : result[args]; - if (value === missing) - return result; - const issues = collectIssues(checks, value, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, value, options)); - } + return succeed6(value); + }); } - } else { - result = flatMap3(result, (value) => { - if (value !== missing) { + } + if (checks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const value = result === sameExit ? input : result[args]; + if (value === missing) + return result; const issues = collectIssues(checks, value, undefined, ast, options); if (issues) { - return fail6(new Composite(ast, issues, value, options)); + result = fail6(new Composite(ast, issues, value, options)); } } - return succeed6(value); - }); + } else { + result = flatMap3(result, (value) => { + if (value !== missing) { + const issues = collectIssues(checks, value, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, value, options)); + } + } + return succeed6(value); + }); + } } + return result; + } catch (error) { + return die3(error); } - return result; }; const parseLocal = specialize === undefined ? parseChecks : specialize(parseChecks); if (!links) { @@ -7714,18 +7795,6 @@ function makeStruct(ast, fields) { function Struct(fields) { return makeStruct(struct(fields, undefined), fields); } -function makeTuple(ast, elements) { - return make8(ast, { - elements, - mapElements(f, options) { - const elements = f(this.elements); - return makeTuple(tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements); - } - }); -} -function Tuple(elements) { - return makeTuple(tuple(elements), elements); -} var ArraySchema = /* @__PURE__ */ lambda((schema) => make8(new Arrays(false, [], [schema.ast]), { value: schema })); @@ -7887,32 +7956,24 @@ function link() { }; } var makeFilter2 = makeFilter; -function isPattern2(regExp, annotations) { - const source = regExp.source; - const flags = regExp.flags; - const canExport = /^[dg]*uy?$/.test(flags); - const runtimeRegExp = flags === "" ? `new RegExp(${format(source)})` : `new RegExp(${format(source)}, ${format(flags)})`; - return isPattern(regExp, { - toJsonSchema: () => canExport ? { - pattern: flags.endsWith("y") ? `^(?:${source})` : source - } : [{}, true], - toCode: () => ({ - runtime: `Schema.isPattern(${runtimeRegExp})` - }), - ...annotations - }); -} function isBase64(annotations) { - const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - return isPattern2(regExp, { + const pattern = "^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"; + const regExp = /^[0-9a-zA-Z+/]*={0,2}$/; + return makeFilter2((s) => s.length % 4 === 0 && regExp.test(s), { expected: "a base64 encoded string", representation: { id: "effect/schema/isBase64", payload: null }, toJsonSchema: () => ({ - pattern: regExp.source + pattern }), + arbitraryConstraint: { + patterns: [{ + source: pattern, + flags: "" + }] + }, toCode: () => ({ runtime: "Schema.isBase64()" }), @@ -8065,47 +8126,6 @@ var File = /* @__PURE__ */ instanceOf(globalThis.File, { }) })) }); -var FormData2 = /* @__PURE__ */ instanceOf(globalThis.FormData, { - representation: { - id: "effect/schema/FormData", - payload: null - }, - toCode: () => ({ - runtime: `Schema.FormData`, - Type: `globalThis.FormData` - }), - expected: "FormData", - toCodecJson: () => link()(ArraySchema(Tuple([String4, Union2([Struct({ - _tag: tag("String"), - value: String4 - }), Struct({ - _tag: tag("File"), - value: File - })])])), transformEffect2({ - decode: (e) => { - const out = new globalThis.FormData; - for (const [key, entry] of e) { - out.append(key, entry.value); - } - return succeed6(out); - }, - encode: (formData) => { - return succeed6(globalThis.Array.from(formData.entries()).map(([key, value]) => { - if (typeof value === "string") { - return [key, { - _tag: "String", - value - }]; - } else { - return [key, { - _tag: "File", - value - }]; - } - })); - } - })) -}); var URLSearchParams2 = /* @__PURE__ */ instanceOf(globalThis.URLSearchParams, { representation: { id: "effect/schema/URLSearchParams", @@ -8221,13 +8241,16 @@ function makeClass(Inherited, identifier, struct2, annotations, proto) { } return out; } -function getClassTransformation(self) { - return new Transformation(transform((input) => new self(input, { +function makeClassTrusted(self, fields) { + return new self(fields, { "~payload": { token: payloadToken, - value: input + value: fields } - })), passthrough2()); + }); +} +function getClassTransformation(self) { + return new Transformation(transform((input) => makeClassTrusted(self, input)), passthrough2()); } function getClassTypeId(identifier) { return `~effect/Schema/Class/${identifier}`; @@ -8295,7 +8318,7 @@ function nominal() { } // node_modules/effect/dist/Fiber.js var join = fiberJoin; -var interrupt3 = fiberInterrupt; +var interrupt4 = fiberInterrupt; var getCurrent = getCurrentFiber; var runIn = fiberRunIn; @@ -8824,7 +8847,9 @@ var toTransform = (channel) => channel.transform; var asyncQueue = (scope, f, options) => make12({ capacity: options?.bufferSize, strategy: options?.strategy -}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope)))); +}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope, { + startImmediately: true +})))); var callbackArray = (f, options) => fromTransform((_, scope) => map5(asyncQueue(scope, f, options), takeAll2)); var suspend3 = (evaluate) => fromTransform((upstream, scope) => suspend2(() => toTransform(evaluate())(upstream, scope))); var fromIterator = (iterator) => fromPull(sync3(() => { @@ -8836,8 +8861,8 @@ var fromIterator = (iterator) => fromPull(sync3(() => { })); var succeed8 = (value) => fromEffect(succeed6(value)); var empty3 = /* @__PURE__ */ fromPull(/* @__PURE__ */ succeed6(/* @__PURE__ */ done2())); -var fail7 = (error) => fromPull(succeed6(fail6(error))); var failCause5 = (cause) => fromPull(failCause3(cause)); +var die4 = (defect) => failCause5(die2(defect)); var fromEffect = (effect) => fromPull(sync3(() => { let done = false; return suspend2(() => { @@ -8949,29 +8974,7 @@ var mapAccum = /* @__PURE__ */ dual((args) => isChannel(args[0]), (self, initial }); return pump; }))); -var catchCause3 = /* @__PURE__ */ dual(2, (self, f) => fromTransform((upstream, scope) => { - let forkedScope = forkUnsafe2(scope); - return map5(toTransform(self)(upstream, forkedScope), (pull) => { - let currentPull = pull.pipe(catchCause2((cause) => { - if (isDoneCause(cause)) { - return failCause3(cause); - } - const toClose = forkedScope; - forkedScope = forkUnsafe2(scope); - return close(toClose, failCause2(cause)).pipe(andThen2(toTransform(f(cause))(upstream, forkedScope)), flatMap3((childPull) => { - currentPull = childPull; - return childPull; - })); - })); - return suspend2(() => currentPull); - }); -})); -var catchCauseFilter2 = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause3(self, (cause) => { - const result = filter(cause); - return isFailure2(result) ? failCause5(result.failure) : f(result.success, cause); -})); -var catch_3 = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter2(self, findError2, (e) => f(e))); -var mapError4 = /* @__PURE__ */ dual(2, (self, f) => catch_3(self, (err) => fail7(f(err)))); +var mapError4 = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => succeed6(mapError2(pull, (err) => isDone2(err) ? err : f(err))))); var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { bufferSize = 16, concurrency, @@ -8980,7 +8983,7 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { const concurrencyN = concurrency === "unbounded" ? Number.MAX_SAFE_INTEGER : Math.max(1, concurrency); const semaphore = switch_ ? undefined : makeUnsafe5(concurrencyN); const doneLatch = yield* make9(true); - const fibers = new Set; + const fibers = new Map; const queue = yield* bounded(bufferSize); yield* addFinalizer2(forkedScope, shutdown(queue)); const pull = yield* toTransform(channels)(upstream, scope); @@ -8999,11 +9002,12 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { const childScope = forkUnsafe2(forkedScope); const childPull = yield* toTransform(channel)(upstream, childScope); while (fibers.size >= concurrencyN) { - const fiber = headUnsafe(fibers); + const [fiber, fiberScope] = headUnsafe(fibers); fibers.delete(fiber); if (fibers.size === 0) yield* doneLatch.open; - yield* interrupt3(fiber); + yield* interrupt4(fiber); + yield* ignoreCause2(close(fiberScope, interrupt2())); } const fiber = yield* childPull.pipe(tap2(() => yieldNow2), flatMap3((value) => offer(queue, value)), forever3({ disableYield: true @@ -9022,7 +9026,7 @@ var mergeAll3 = /* @__PURE__ */ dual(2, (channels, { yield* doneLatch.open; })), forkChild2); doneLatch.closeUnsafe(); - fibers.add(fiber); + fibers.set(fiber, childScope); } }).pipe(catchCause2((cause) => { const halt = filterDone(cause); @@ -9146,6 +9150,18 @@ var splitLines = () => fromTransform((upstream, _scope) => sync3(() => { } return pullOrFlush; })); +var decodeText = (encoding, options) => fromTransform((upstream, _scope) => sync3(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + let pull = upstream.pipe(map5(map2((bytes) => decoder.decode(bytes, streamOptions))), catchDone((leftover) => { + pull = done2(leftover); + const last = decoder.decode(); + return last.length > 0 ? succeed6(of(last)) : pull; + })); + return suspend2(() => pull); +})); var pipeTo = /* @__PURE__ */ dual(2, (self, that) => fromTransform((upstream, scope) => flatMap3(toTransform(self)(upstream, scope), (upstream) => toTransform(that)(upstream, scope)))); var unwrap = (channel) => fromTransform((upstream, scope) => { let pull; @@ -9305,19 +9321,19 @@ var make13 = (options) => withFiber2((fiber) => { if (state._tag === "Acquired") return close(state.scope, void_2); if (state._tag === "Acquiring") - return interrupt3(state.fiber); + return interrupt4(state.fiber); return void_3; }), ref); }); var getState = (self, restore) => { switch (self.state._tag) { case "Closed": { - return interrupt2; + return interrupt3; } case "Acquired": { const state = self.state; state.refCount++; - return state.fiber ? as2(interrupt3(state.fiber), state) : succeed6(state); + return state.fiber ? as2(interrupt4(state.fiber), state) : succeed6(state); } case "Acquiring": { const state = self.state; @@ -9335,7 +9351,7 @@ var getState = (self, restore) => { const scope = makeUnsafe3(); const acquire = provideContext2(self.acquire, add(self.context, Scope, scope)).pipe(flatMap3((value) => { if (self.state !== acquiring) { - return interrupt2; + return interrupt3; } const state = { _tag: "Acquired", @@ -9368,7 +9384,7 @@ var awaitAcquiring = (self, acquiring, restore) => onExit2(restore(join(acquirin if (--acquiring.awaiters > 0 || self.state !== acquiring) return void_3; self.state = stateEmpty; - return interrupt3(acquiring.fiber); + return interrupt4(acquiring.fiber); }); var get2 = (self_) => { const self = self_; @@ -9415,7 +9431,13 @@ var toChannel2 = (stream) => stream.channel; var callback3 = (f, options) => fromChannel3(callbackArray(f, options)); var empty4 = /* @__PURE__ */ fromChannel3(empty3); var succeed9 = (value) => fromChannel3(succeed8(of(value))); -var suspend4 = (stream) => fromChannel3(suspend3(() => stream().channel)); +var suspend4 = (stream) => { + const suspended = fromChannel3(suspend3(() => stream().channel)); + suspendedStreams.set(suspended, stream); + return suspended; +}; +var suspendedStreams = /* @__PURE__ */ new WeakMap; +var die6 = (defect) => fromChannel3(die4(defect)); var unwrap3 = (effect) => fromChannel3(unwrap(map5(effect, toChannel2))); var map8 = /* @__PURE__ */ dual(2, (self, f) => suspend4(() => { let i = 0; @@ -9433,10 +9455,21 @@ function* concatChannels(self, that) { while (stack.length > 0) { const stream = stack.pop(); const parts = concatParts.get(stream); - if (parts === undefined) - yield stream.channel; - else + if (parts !== undefined) { stack.push(parts[1], parts[0]); + continue; + } + const evaluate = suspendedStreams.get(stream); + if (evaluate === undefined) { + yield stream.channel; + continue; + } + try { + stack.push(evaluate()); + } catch (defect) { + stack.push(die6(defect)); + } + yield empty3; } } var merge3 = /* @__PURE__ */ dual((args) => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel3(merge2(toChannel2(self), toChannel2(that), options))); @@ -9469,12 +9502,7 @@ var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (up }); return suspend2(() => done ? done : pull); }))); -var decodeText = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => suspend4(() => { - const decoder = new TextDecoder(options?.encoding); - return map8(self, (chunk) => decoder.decode(chunk, { - stream: true - })); -})); +var decodeText2 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => self.channel.pipe(pipeTo(decodeText(options?.encoding)), fromChannel3)); var splitLines2 = (self) => self.channel.pipe(pipeTo(splitLines()), fromChannel3); var run2 = /* @__PURE__ */ dual(2, (self, sink) => scopedWith2((scope) => toPullScoped(self.channel, scope).pipe(flatMap3((upstream) => sink.transform(upstream, scope)), map5(([a]) => a)))); var runCollect = (self) => runFold(self.channel, () => [], (acc, chunk) => { @@ -9600,10 +9628,14 @@ var ulidString = (timestampMillis, bytes) => { }; // node_modules/effect/dist/internal/uuid.js -var hex = (byte) => byte.toString(16).padStart(2, "0"); +var hex = /* @__PURE__ */ Array.from({ + length: 256 +}, (_, byte) => byte.toString(16).padStart(2, "0")); var stringify = (bytes) => { - const segments = [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)]; - return segments.map((segment) => Array.from(segment, hex).join("")).join("-"); + if (bytes.length < 16) { + return [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)].map((segment) => Array.from(segment, (byte) => hex[byte]).join("")).join("-"); + } + return hex[bytes[0]] + hex[bytes[1]] + hex[bytes[2]] + hex[bytes[3]] + "-" + hex[bytes[4]] + hex[bytes[5]] + "-" + hex[bytes[6]] + hex[bytes[7]] + "-" + hex[bytes[8]] + hex[bytes[9]] + "-" + hex[bytes[10]] + hex[bytes[11]] + hex[bytes[12]] + hex[bytes[13]] + hex[bytes[14]] + hex[bytes[15]]; }; var randomBytes = () => globalThis.crypto.getRandomValues(new Uint8Array(16)); function v4Bytes(bytes = randomBytes()) { @@ -9859,23 +9891,26 @@ var defaultTeardown = (exit, onExit) => { return onExit(getErrorExitCode(squash(exit.cause))); }; var makeRunMain = (f) => dual((args) => isEffect2(args[0]), (effect, options) => { - const fiber = options?.disableErrorReporting === true ? runFork2(effect) : runFork2(tapCause2(effect, (cause) => { + const main = options?.disableErrorReporting === true ? effect : tapCause2(effect, (cause) => { if (hasInterruptsOnly2(cause)) return void_3; const isReported = getErrorReported(squash(cause)); return isReported ? logError(cause) : void_3; - })); - try { - const keepAlive = globalThis.setInterval(constVoid, 2147483647); - fiber.addObserver(() => { - clearInterval(keepAlive); - }); - } catch {} - const teardown = options?.teardown ?? defaultTeardown; - return f({ - fiber, - teardown }); + const teardown = options?.teardown ?? defaultTeardown; + runFork2(withFiber2((fiber) => { + try { + const keepAlive = globalThis.setInterval(constVoid, 2147483647); + fiber.addObserver(() => { + clearInterval(keepAlive); + }); + } catch {} + f({ + fiber, + teardown + }); + return main; + })); }); var errorExitCode = "~effect/Runtime/errorExitCode"; var getErrorExitCode = (u) => { @@ -9939,7 +9974,7 @@ var makeHandle = (params) => Object.setPrototypeOf({ ...params }, HandleProto); var make21 = (spawn) => { - const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); + const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText2(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); const streamLines = (command, options) => splitLines2(streamString(command, options)); return ChildProcessSpawner.of({ spawn, @@ -10187,11 +10222,11 @@ var layer = (defaults = {}) => effect(Gh, gen2(function* () { let stdoutTruncated = false; let stderr = ""; let stderrTruncated = false; - const output = merge3(handle.stdout.pipe(decodeText(), map8((text) => { + const output = merge3(handle.stdout.pipe(decodeText2(), map8((text) => { stdoutTruncated ||= stdout.length + text.length > outputLimit; stdout = (stdout + text).slice(-outputLimit); return GhChunk.cases.Stdout.make({ text }); - })), handle.stderr.pipe(decodeText(), map8((text) => { + })), handle.stderr.pipe(decodeText2(), map8((text) => { stderrTruncated ||= stderr.length + text.length > outputLimit; stderr = (stderr + text).slice(-outputLimit); return GhChunk.cases.Stderr.make({ text }); @@ -10427,6 +10462,7 @@ var handleErrnoException = (module, method) => (err, [path]) => { reason = "NotFound"; break; case "EACCES": + case "EPERM": reason = "PermissionDenied"; break; case "EEXIST": @@ -10455,66 +10491,149 @@ var handleErrnoException = (module, method) => (err, [path]) => { }); }; +// node_modules/@effect/platform-node-shared/dist/NodeSink.js +import { finished } from "node:stream"; + +// node_modules/@effect/platform-node-shared/dist/internal/stream.js +var destroyStream = (stream, cleanup, onDestroyed) => { + if (!("closed" in stream)) { + cleanup(); + onDestroyed?.(); + return; + } + const onDone = () => { + clearImmediate(immediate); + stream.off("error", onDone); + stream.off("close", onDone); + onDestroyed?.(); + }; + const onClosed = () => { + if (stream.closed) { + onDone(); + } else { + immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + } + }; + let immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + stream.once("error", onDone); + stream.once("close", onDone); + cleanup(); + if (!stream.closed) { + stream.destroy(); + } +}; + // node_modules/@effect/platform-node-shared/dist/NodeSink.js var fromWritable = (options) => fromChannel2(mapDone(fromWritableChannel(options), (_) => [_])); var fromWritableChannel = (options) => fromTransform((pull) => { const writable = options.evaluate(); - return succeed6(pullIntoWritable({ + const write = pullIntoWritable({ ...options, writable, pull - })); -}); -var pullIntoWritable = (options) => options.pull.pipe(flatMap3((chunk) => { - let i = 0; - return callback2((resume) => { - let cancelled = false; - const loop = () => { - for (;i < chunk.length; ) { - if (cancelled) { - return; - } - const success = options.writable.write(chunk[i++], options.encoding); - if (!success) { - if (!cancelled) { - options.writable.once("drain", loop); + }); + return succeed6(options.endOnDone === false ? write : onError2(write, (cause) => isDoneCause(cause) ? void_3 : releaseWritable(writable))); +}); +var releaseWritable = (writable) => callback2((resume) => { + const onDestroyed = () => resume(void_3); + if (writable.closed) { + const cleanup = finished(writable, { + readable: false + }, () => { + cleanup(); + onDestroyed(); + }); + } else { + destroyStream(writable, constVoid, onDestroyed); + } +}); +var pullIntoWritable = (options) => withFiber2((fiber) => { + const dispatcher = fiber.currentDispatcher; + const completion = makeUnsafe2(); + const failure = makeUnsafe2(); + const onError = (error) => doneUnsafe(failure, failSync2(() => options.onError(error))); + let errorEmitted = false; + const onStreamError = (error) => { + errorEmitted = true; + onError(error); + }; + options.writable.on("error", onStreamError); + const cleanup = finished(options.writable, { + readable: false + }, (error) => { + if (error) { + onError(error); + } else { + doneUnsafe(completion, void_3); + } + }); + return options.pull.pipe(flatMap3((chunk) => { + let i = 0; + return callback2((resume) => { + let cancelled = false; + const onFinish = () => dispatcher.scheduleTask(loop, 0); + const loop = () => { + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + for (;i < chunk.length; ) { + if (cancelled) { + return; + } + const success = options.writable.write(chunk[i++], options.encoding, (error) => { + if (!error) + return; + if (options.writable.closed) { + onError(error); + } else { + dispatcher.scheduleTask(() => onError(error), 0); + } + }); + if (!success) { + if (!cancelled) { + options.writable.once("drain", loop); + options.writable.once("finish", onFinish); + } + return; } - return; } - } - if (!cancelled) { - resume(void_3); - } - }; - loop(); - return sync3(() => { - cancelled = true; - options.writable.off("drain", loop); + if (!cancelled) { + resume(void_3); + } + }; + loop(); + return sync3(() => { + cancelled = true; + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + }); }); - }); -}), forever3({ - disableYield: true -}), options.endOnDone !== false ? catchDone((_) => { - if ("closed" in options.writable && options.writable.closed) { - return done2(_); - } - return callback2((resume) => { - const onFinish = () => resume(done2(_)); - options.writable.once("finish", onFinish); + }), forever3({ + disableYield: true + }), options.endOnDone !== false ? catchDone((_) => { options.writable.end(); - return sync3(() => { - options.writable.off("finish", onFinish); - }); - }); -}) : identity, raceFirst2(callback2((resume) => { - const onError = (error) => resume(fail6(options.onError(error))); - options.writable.once("error", onError); - return sync3(() => { - options.writable.off("error", onError); - }); -}))); + return andThen2(_await(completion), done2(_)); + }) : identity, raceFirst2(_await(failure)), ensuring2(sync3(() => { + cleanup(); + const removeErrorListener = () => { + options.writable.off("error", onStreamError); + options.writable.off("error", removeErrorListener); + options.writable.off("close", removeErrorListener); + }; + if (options.writable.errored && !options.writable.closed && !errorEmitted) { + options.writable.once("error", removeErrorListener); + options.writable.once("close", removeErrorListener); + } else { + removeErrorListener(); + } + }))); +}); // node_modules/@effect/platform-node-shared/dist/NodeStream.js +import { finished as finished2, Readable } from "node:stream"; var fromReadable = (options) => fromChannel3(fromReadableChannel(options)); var fromReadableChannel = (options) => fromTransform((_, scope) => readableToPullUnsafe({ scope, @@ -10531,17 +10650,14 @@ var readableToPullUnsafe = (options) => { function onReadable() { latch.openUnsafe(); } - function onError(error) { - exit.current = fail5(options.onError(error)); - latch.openUnsafe(); - } - function onEnd() { - exit.current = fail5(Done2()); - latch.openUnsafe(); - } readable.on("readable", onReadable); - readable.once("error", onError); - readable.once("end", onEnd); + const cleanup = finished2(readable, { + readable: true, + writable: false + }, (error) => { + exit.current ??= fail5(error ? options.onError(error) : Done2()); + latch.openUnsafe(); + }); const pull = suspend2(function loop() { let item = options.readable.read(options.chunkSize); if (item === null) { @@ -10565,10 +10681,10 @@ var readableToPullUnsafe = (options) => { }); return as2(addFinalizer2(options.scope, sync3(() => { readable.off("readable", onReadable); - readable.off("error", onError); - readable.off("end", onEnd); - if (closeOnDone && "closed" in options.readable && !options.readable.closed) { - options.readable.destroy(); + if (closeOnDone) { + destroyStream(readable, cleanup); + } else { + cleanup(); } })), pull); }; @@ -10893,6 +11009,7 @@ var make23 = /* @__PURE__ */ gen2(function* () { const signalGroup = (signal) => killProcessGroup(command, childProcess, signal).pipe(catch_2(() => killProcess(command, childProcess, signal))); yield* signalGroup(options?.killSignal ?? "SIGTERM"); if (isUndefined(options?.forceKillAfter)) { + yield* _await(exitSignal); yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis); } else { yield* awaitProcessExit(childProcess, exitSignal, toMillis(options.forceKillAfter)); @@ -11486,14 +11603,14 @@ var readLink = /* @__PURE__ */ (() => { return (path) => nodeReadLink(path); })(); var realPath = /* @__PURE__ */ (() => { - const nodeRealPath = /* @__PURE__ */ effectify(NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); + const nodeRealPath = /* @__PURE__ */ effectify(process.platform === "win32" ? NFS.realpath.native : NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); return (path) => nodeRealPath(path); })(); var rename2 = /* @__PURE__ */ (() => { const nodeRename = /* @__PURE__ */ effectify(NFS.rename, /* @__PURE__ */ handleErrnoException("FileSystem", "rename"), /* @__PURE__ */ handleBadArgument("rename")); return (oldPath, newPath) => nodeRename(oldPath, newPath); })(); -var makeFileInfo = (stat) => try_2({ +var makeFileInfo = (stat, method = "stat") => try_2({ try: () => ({ type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown", mtime: fromNullishOr(stat.mtime), @@ -11510,14 +11627,16 @@ var makeFileInfo = (stat) => try_2({ blksize: stat.blksize !== undefined ? some2(bytes(stat.blksize)) : none2(), blocks: fromNullishOr(stat.blocks) }), - catch: handleBadArgument("stat") + catch: handleBadArgument(method) }); -var stat2 = /* @__PURE__ */ (() => { - const nodeStat = /* @__PURE__ */ effectify(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat")); +var statFactory = (method, nodeStatFn) => { + const nodeStat = effectify(nodeStatFn, handleErrnoException("FileSystem", method), handleBadArgument(method)); return (path) => flatMap3(nodeStat(path, { bigint: true - }), makeFileInfo); -})(); + }), (stat) => makeFileInfo(stat, method)); +}; +var stat2 = /* @__PURE__ */ statFactory("stat", NFS.stat); +var lstat2 = /* @__PURE__ */ statFactory("lstat", NFS.lstat); var symlink2 = /* @__PURE__ */ (() => { const nodeSymlink = /* @__PURE__ */ effectify(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink")); return (target, path) => nodeSymlink(target, path); @@ -11600,6 +11719,7 @@ var makeFileSystem = /* @__PURE__ */ map5(/* @__PURE__ */ serviceOption2(WatchBa copyFile: copyFile2, glob: glob2, link: link3, + lstat: lstat2, makeDirectory, makeTempDirectory, makeTempDirectoryScoped, @@ -11739,9 +11859,6 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readline.emitKeypressEvents(stdin, rl); rl.on("line", onLine); rl.once("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(true); - } return { rl, onClose, @@ -11755,9 +11872,6 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readlineActive = false; rl.off("line", onLine); rl.off("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(false); - } rl.close(); if (inputEnded) { endUnsafe(lines); @@ -11765,6 +11879,14 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu })), idleTimeToLive: "10 millis" }); + const setRawMode = (enabled) => sync3(() => { + if (stdin.isTTY) + stdin.setRawMode(enabled); + }); + const rawModeRef = yield* make14({ + acquire: acquireRelease2(setRawMode(true), () => setRawMode(false)), + idleTimeToLive: "10 millis" + }); const columns = sync3(() => stdout.columns ?? 0); const rows = sync3(() => stdout.rows ?? 0); const readInput = gen2(function* () { @@ -11799,6 +11921,7 @@ var make25 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu handleEnd(); } else { yield* get3(rlRef); + yield* get3(rawModeRef); stdin.once("end", handleEnd); } return queue; @@ -11918,7 +12041,7 @@ class CommandError extends TaggedError3()("CommandError", { }) { } var error = (command, cause) => new CommandError({ command, exitCode: -1, stderr: String(cause) }); -var collectText = (stream) => stream.pipe(decodeText(), runFold2(() => "", (all, chunk) => all + chunk)); +var collectText = (stream) => stream.pipe(decodeText2(), runFold2(() => "", (all, chunk) => all + chunk)); var retainedStderrLength = 16 * 1024; class Service3 extends Service()("@timmo001/workflows/CommandExecutor") { @@ -11971,8 +12094,8 @@ var layer15 = effect(Service3, gen2(function* () { stdin: "inherit" })); let stderrTail = ""; - const stdout = handle.stdout.pipe(decodeText(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); - const stderr = handle.stderr.pipe(decodeText(), runForEach2((chunk) => sync3(() => { + const stdout = handle.stdout.pipe(decodeText2(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); + const stderr = handle.stderr.pipe(decodeText2(), runForEach2((chunk) => sync3(() => { process.stderr.write(chunk); stderrTail = `${stderrTail}${chunk}`.slice(-retainedStderrLength); }))); diff --git a/.github/actions/validate-agent-skills/dist/index.js b/.github/actions/validate-agent-skills/dist/index.js index 5258e963..1271298d 100644 --- a/.github/actions/validate-agent-skills/dist/index.js +++ b/.github/actions/validate-agent-skills/dist/index.js @@ -772,6 +772,10 @@ function assignProperty(self, key, value) { } } function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } for (const key of Reflect.ownKeys(source)) { if (Object.prototype.propertyIsEnumerable.call(source, key)) { assignProperty(self, key, source[key]); @@ -862,7 +866,7 @@ class CauseImpl { toJSON() { return { _id: "Cause", - failures: this.reasons.map((f) => f.toJSON()) + reasons: this.reasons.map((f) => f.toJSON()) }; } toString() { @@ -1614,9 +1618,21 @@ var bigint2 = /* @__PURE__ */ BigInt(2); var bigint10 = /* @__PURE__ */ BigInt(10); var bigint1e3 = /* @__PURE__ */ BigInt(1000); var bigint1e6 = /* @__PURE__ */ BigInt(1e6); +var bigint1e9 = /* @__PURE__ */ BigInt(1e9); +var bigintNanosPerMinute = /* @__PURE__ */ BigInt(60000000000); +var bigintNanosPerHour = /* @__PURE__ */ BigInt(3600000000000); +var bigintNanosPerDay = /* @__PURE__ */ BigInt(86400000000000); +var bigintNanosPerWeek = /* @__PURE__ */ BigInt(604800000000000); var roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input))); var roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6); var fromNanosNumber = (nanos) => make3(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos); +var nanosToUnit = (nanos, divisor) => { + const value = Number(nanos); + if (Number.isFinite(value)) + return value / divisor; + const scale = BigInt(divisor); + return Number(nanos / scale) + Number(nanos % scale) / divisor; +}; var parseNanos = (input, scale) => { const decimalIndex = input.indexOf("."); if (decimalIndex === -1) @@ -1632,6 +1648,13 @@ var divideTiesAwayFromZero = (numerator, denominator) => { const rounded = absolute / denominator + (absolute % denominator * bigint2 >= denominator ? bigint1 : bigint0); return numerator < bigint0 ? -rounded : rounded; }; +var fromMillisString = (input, scale) => { + const millis = Number(input) * scale; + if (!Number.isFinite(millis)) + return make3(millis); + const nanos = parseNanos(input, BigInt(scale) * bigint1e6); + return make3(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos); +}; var DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; var fromInputUnsafe = (input) => { switch (typeof input) { @@ -1656,26 +1679,25 @@ var fromInputUnsafe = (input) => { if (unit === "micro" || unit === "micros") { return nanos(parseNanos(valueStr, bigint1e3)); } - const value = Number(valueStr); switch (unit) { case "milli": case "millis": - return millis(value); + return fromMillisString(valueStr, 1); case "second": case "seconds": - return seconds(value); + return fromMillisString(valueStr, 1000); case "minute": case "minutes": - return minutes(value); + return fromMillisString(valueStr, 60000); case "hour": case "hours": - return hours(value); + return fromMillisString(valueStr, 3600000); case "day": case "days": - return days(value); + return fromMillisString(valueStr, 86400000); case "week": case "weeks": - return weeks(value); + return fromMillisString(valueStr, 604800000); } break; } @@ -1697,7 +1719,8 @@ var fromInputUnsafe = (input) => { if (input[0] === Infinity || input[1] === Infinity) { return infinity; } - return fromNanosNumber(input[0] * 1e9 + input[1]); + const nanos = input[0] * 1e9 + input[1]; + return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make3(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos); } const obj = input; let millis = 0; @@ -1713,13 +1736,42 @@ var fromInputUnsafe = (input) => { millis += obj.seconds * 1000; if (obj.milliseconds) millis += obj.milliseconds; - if (!obj.microseconds && !obj.nanoseconds) - return make3(millis); - return fromNanosNumber(millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0)); + if (!obj.microseconds && !obj.nanoseconds) { + if (!Number.isFinite(millis)) + return make3(millis); + const exact = sumObjectNanos(obj); + return exact === undefined || BigInt(millis) * bigint1e6 === exact ? make3(millis) : make3(exact); + } + const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0); + const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : undefined; + return exact === undefined ? fromNanosNumber(nanos) : make3(exact); } } return invalid(input); }; +var isIntegerOrUnset = (n) => !n || Number.isInteger(n); +var sumObjectNanos = (obj) => { + if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds)) + return; + let nanos = bigint0; + if (obj.weeks) + nanos += BigInt(obj.weeks) * bigintNanosPerWeek; + if (obj.days) + nanos += BigInt(obj.days) * bigintNanosPerDay; + if (obj.hours) + nanos += BigInt(obj.hours) * bigintNanosPerHour; + if (obj.minutes) + nanos += BigInt(obj.minutes) * bigintNanosPerMinute; + if (obj.seconds) + nanos += BigInt(obj.seconds) * bigint1e9; + if (obj.milliseconds) + nanos += BigInt(obj.milliseconds) * bigint1e6; + if (obj.microseconds) + nanos += BigInt(obj.microseconds) * bigint1e3; + if (obj.nanoseconds) + nanos += BigInt(obj.nanoseconds); + return nanos; +}; var invalid = (input) => { throw new Error(`Invalid Input: ${input}`); }; @@ -1828,14 +1880,9 @@ var infinity = /* @__PURE__ */ make3(Infinity); var negativeInfinity = /* @__PURE__ */ make3(-Infinity); var nanos = (nanos) => make3(nanos); var millis = (millis) => make3(millis); -var seconds = (seconds) => make3(seconds * 1000); -var minutes = (minutes) => make3(minutes * 60000); -var hours = (hours) => make3(hours * 3600000); -var days = (days) => make3(days * 86400000); -var weeks = (weeks) => make3(weeks * 604800000); var toMillis = (self) => match3(fromInputUnsafe(self), { onMillis: identity, - onNanos: (nanos) => Number(nanos) / 1e6, + onNanos: (nanos) => nanosToUnit(nanos, 1e6), onInfinity: () => Infinity, onNegativeInfinity: () => -Infinity }); @@ -1901,7 +1948,7 @@ var setTimer = "setImmediate" in globalThis ? (f) => { const timer = setTimeout(f, 0); return () => clearTimeout(timer); }; -var setImmediate = (f) => { +var setImmediate2 = (f) => { try { return setTimer(f); } catch { @@ -1941,7 +1988,7 @@ class MixedScheduler { setImmediate; constructor(executionMode = "async", setImmediateFn) { this.executionMode = executionMode; - this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate2); } shouldYield(fiber) { return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; @@ -1955,7 +2002,7 @@ class MixedSchedulerDispatcher { tasks = /* @__PURE__ */ new PriorityBuckets; running = undefined; setImmediate; - constructor(setImmediateFn = setImmediate) { + constructor(setImmediateFn = setImmediate2) { this.setImmediate = setImmediateFn; } scheduleTask(task, priority) { @@ -2223,10 +2270,7 @@ class Interrupt extends ReasonBase { } } var causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); -var findFail = (self) => { - const reason = self.reasons.find(isFailReason); - return reason ? succeed2(reason) : fail2(self); -}; +var hasFails = (self) => self.reasons.some(isFailReason); var findError = (self) => { for (let i = 0;i < self.reasons.length; i++) { const reason = self.reasons[i]; @@ -2236,6 +2280,9 @@ var findError = (self) => { } return fail2(self); }; +var hasDies = (self) => self.reasons.some(isDieReason); +var causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +var findRecoverableError = (self) => hasDies(self) ? fail2(causeElectDefects(self)) : findError(self); var hasInterrupts = (self) => self.reasons.some(isInterruptReason); var hasInterruptsOnly = (self) => self.reasons.length > 0 && self.reasons.every(isInterruptReason); var causeMap = /* @__PURE__ */ dual(2, (self, f) => { @@ -2296,12 +2343,14 @@ var causePrettyErrors = (self, options) => { } return errors; }; -var causePrettyError = (original, annotations, options) => { +var causePrettyError = (original, annotations, options, seen = new Set) => { const kind = typeof original; let error; if (original && kind === "object") { + seen.add(original); + const cause = original.cause; error = new globalThis.Error(causePrettyMessage(original), { - cause: original.cause ? causePrettyError(original.cause) : undefined + cause: cause !== undefined && !seen.has(cause) ? causePrettyError(cause, undefined, undefined, seen) : undefined }); if (typeof original.name === "string") { error.name = original.name; @@ -2512,7 +2561,11 @@ class FiberImpl { } else if (this._asyncContext !== undefined) { const asyncContext = this._asyncContext; this._asyncContext = undefined; - return asyncContext.runInAsyncScope(this.evaluate, this, effect); + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } } else if (this._yielded !== undefined) { const yielded = this._yielded; this._yielded = undefined; @@ -2810,7 +2863,6 @@ var tryPromise = (options) => { } }, f.length !== 0); }; -var withFiberId = (f) => withFiber((fiber) => f(fiber.id)); var callbackOptions = /* @__PURE__ */ function() { const Proto = /* @__PURE__ */ makePrimitiveProto({ op: "Async", @@ -2831,9 +2883,9 @@ var callbackOptions = /* @__PURE__ */ function() { if (yielded !== false) return yielded; yielded = true; - fiber._yielded = () => { + fiber.yieldWith(() => { resumed = true; - }; + }); if (controller === undefined && onCancel === undefined) { return Yield; } @@ -3116,10 +3168,7 @@ var exitMap = /* @__PURE__ */ dual(2, (self, f) => self._tag === "Success" ? exi var exitMapError = /* @__PURE__ */ dual(2, (self, f) => { if (self._tag === "Success") return self; - const error = findError(self.cause); - if (isFailure2(error)) - return self; - return exitFail(f(error.success)); + return exitFailCause(causeMap(self.cause, f)); }); var exitZipRight = /* @__PURE__ */ dual(2, (self, that) => exitIsSuccess(self) ? that : self); var exitAsVoidAll = (exits) => { @@ -3183,10 +3232,10 @@ var catchCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(s const eb = filter(cause); return isFailure2(eb) ? failCause(eb.failure) : f(eb.success, cause); })); -var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findError, (e) => f(e))); +var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findRecoverableError, (e) => f(e))); var tapCause = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => andThen(f(cause), failCause(cause)))); var catchIf = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, predicate, f, orElse) => catchCause(self, (cause) => { - const error = findError(cause); + const error = findRecoverableError(cause); if (isFailure2(error)) return failCause(error.failure); if (!predicate(error.success)) { @@ -3198,7 +3247,7 @@ var catchTag = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, k, f, or const pred = Array.isArray(k) ? (e) => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); return catchIf(self, pred, f, orElse); }); -var mapError = /* @__PURE__ */ dual(2, (self, f) => catch_(self, (error) => failSync(() => f(error)))); +var mapError = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => failCause(causeMap(cause, f)))); var orDie = (self) => catch_(self, die); var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { if (!options?.log) { @@ -3210,8 +3259,8 @@ var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) = const logEffect = logWithLevel(options.log === true ? undefined : options.log); return matchCauseEffect(self, { onFailure(cause) { - const failure = findFail(cause); - return isFailure2(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); }, onSuccess: (_) => void_ }); @@ -3250,16 +3299,16 @@ var makeMatch = (op, onFailure) => { return MatchImpl; }; var MatchImpl = /* @__PURE__ */ makeMatch("Match", function(cause, fiber) { - const fail = cause.reasons.find(isFailReason); - if (fail === undefined) - return failCause(cause); + const error = findRecoverableError(cause); + if (isFailure2(error)) + return failCause(error.failure); const handlers = this.payload; - return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(fail.error) : internalCall(() => handlers.onFailure(fail.error))); + return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))); }); var matchEffect = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, { onFailure: (cause) => { - const fail = cause.reasons.find(isFailReason); - return fail ? options.onFailure(fail.error) : failCause(cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.onFailure(error.success); }, onSuccess: options.onSuccess })); @@ -3268,9 +3317,9 @@ var matchEager = /* @__PURE__ */ dual(2, (self, options) => { if (effectIsExit(self)) { if (self._tag === "Success") return exitSucceed(options.onSuccess(self.value)); - const error = findError(self.cause); + const error = findRecoverableError(self.cause); if (isFailure2(error)) - return self; + return exitFailCause(error.failure); return exitSucceed(options.onFailure(error.success)); } return match4(self, options); @@ -3325,17 +3374,17 @@ var runFinalizer = (finalizer, exit_) => { return exitDie(defect); } }; -var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeCombine(exit_.cause, cause))); +var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); var scopeCloseFinalizers = /* @__PURE__ */ fnUntraced(function* (self, finalizers, exit_) { let exits = []; const fibers = []; - const arr = Array.from(finalizers.values()); + const arr = Array.from(finalizers); const parent = getCurrentFiber(); for (let i = arr.length - 1;i >= 0; i--) { - const finalizer = arr[i]; + const [key, finalizer] = arr[i]; if (self.strategy === "sequential") { exits.push(yield* exit(runFinalizer(finalizer, exit_))); - } else { + } else if (key !== parent) { fibers.push(forkUnsafe(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); } } @@ -3528,15 +3577,9 @@ var all = (arg, options) => { } else if (options?.discard) { return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options); } - return suspend(() => { - const out = {}; - return as(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => { - assignProperty(out, key, value); - }), { - discard: true, - concurrency: options?.concurrency - }), out); - }); + return suspend(() => map3(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => [key, value]), { + concurrency: options?.concurrency + }), Object.fromEntries)); }; var whileLoop = /* @__PURE__ */ makePrimitive({ op: "While", @@ -3675,7 +3718,7 @@ var iterateConcurrentImpl = (options) => { const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); if (reasons.length > 0) { const cause = causeFromReasons(reasons); - terminal = exitFailCause(terminal._tag === "Failure" ? causeCombine(terminal.cause, cause) : cause); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); } } } else { @@ -3753,14 +3796,13 @@ var forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterrupt } return child; }; +var fiberScopeFinalizer = (fiber) => () => withFiber((current) => current === fiber ? void_ : fiberInterrupt(fiber)); var forkIn = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, scope, options) => withFiber((parent) => { - const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + const fiber = scope.state._tag === "Closed" ? new FiberImpl(parent.context) : forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); if (!fiber._exit) { if (scope.state._tag !== "Closed") { - const key = {}; - const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); - scopeAddFinalizerUnsafe(scope, key, finalizer); - fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + scopeAddFinalizerUnsafe(scope, fiber, fiberScopeFinalizer(fiber)); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, fiber)); } else { fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); } @@ -3797,7 +3839,7 @@ var fiberRunIn = /* @__PURE__ */ dual(2, (self, scope) => { return self; } scopeRemoveFinalizerUnsafe(scope, self); - scopeAddFinalizerUnsafe(scope, self, () => fiberInterrupt(self)); + scopeAddFinalizerUnsafe(scope, self, fiberScopeFinalizer(self)); self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, self)); return self; }); @@ -4436,8 +4478,8 @@ var mergeAllEffect = (layers, memoMap, scope) => { concurrency: layers.length }).pipe(map3((context) => mergeAll(...context))); }; -var mergeAll2 = (...layers) => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); -var provideWith = (self, that, f) => fromBuild((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); +var mergeAll2 = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +var provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); var provide2 = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, identity)); var provideMerge = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, (self, that) => merge(that, self))); @@ -4508,6 +4550,7 @@ var void_3 = void_; var callback2 = callback; var gen2 = gen; var fail6 = fail3; +var failSync2 = failSync; var failCause3 = failCause; var failCauseSync2 = failCauseSync; var die3 = die; @@ -4557,16 +4600,23 @@ var fn2 = fn; var clockWith2 = clockWith; var logError = /* @__PURE__ */ logWithLevel("Error"); var effectify = (fn, onError, onSyncError) => (...args) => callback2((resume) => { + let synchronous = true; + let pending; try { fn(...args, (err, result) => { - if (err) { - resume(onError ? suspend2(() => fail6(onError(err, args))) : fail6(err)); + const effect = err ? onError ? suspend2(() => fail6(onError(err, args))) : fail6(err) : succeed6(result); + if (synchronous) { + pending ??= effect; } else { - resume(succeed6(result)); + resume(effect); } }); } catch (err) { - resume(onSyncError ? fail6(onSyncError(err, args)) : die3(err)); + pending = onSyncError ? fail6(onSyncError(err, args)) : die3(err); + } + synchronous = false; + if (pending) { + resume(pending); } }); var mapEager2 = mapEager; @@ -4977,7 +5027,7 @@ var defaultLeafHook = (issue) => { } } }; -var defaultCheckHook = (issue) => findMessage(issue.issue) ?? findMessage(issue); +var defaultCheckHook = (issue) => findMessage(issue) ?? findMessage(issue.issue); function formatInput(issue) { return hasInput(issue) ? format(issue.input) : undefined; } @@ -4989,6 +5039,13 @@ function getExpectedMessage(expected, issue) { const input = formatInput(issue); return input === undefined ? `Expected ${expected}` : `Expected ${expected}, got ${input}`; } +function getFilterMessage(issue, checkHook) { + const message = checkHook(issue); + if (message !== undefined || issue.issue._tag !== "InvalidValue") + return message; + const expected = findExpected(issue.issue); + return expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); +} function formatCheck(check) { const expected = check.annotations?.expected; if (typeof expected === "string") @@ -5004,44 +5061,33 @@ function makeFormatterDefault() { return (issue) => formatIssue(issue, ""); } var defaultFormatter = /* @__PURE__ */ makeFormatterDefault(); -function formatIssue(issue, path) { +function formatIssue(issue, path, messageOverride) { let message; switch (issue._tag) { - case "Filter": { - const annotated = defaultCheckHook(issue); - if (annotated !== undefined) { - message = annotated; - } else { - if (issue.issue._tag !== "InvalidValue") { - return formatIssue(issue.issue, path); - } - const expected = findExpected(issue.issue); - message = expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); - } - break; - } + case "Filter": + return formatIssue(issue.issue, path, messageOverride ?? getFilterMessage(issue, defaultCheckHook)); case "Encoding": - return formatIssue(issue.issue, path); + return formatIssue(issue.issue, path, messageOverride); case "Pointer": - return formatIssue(issue.issue, path + formatPath(issue.path)); + return formatIssue(issue.issue, path + formatPath(issue.path), messageOverride); case "Composite": case "AnyOf": { if (issue._tag === "Composite" || issue.issues.length > 0) { - return issue.issues.map((issue) => formatIssue(issue, path)).join(` + return issue.issues.map((issue) => formatIssue(issue, path, messageOverride)).join(` `); } - message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); + message = messageOverride ?? findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); break; } default: - message = defaultLeafHook(issue); + message = messageOverride ?? defaultLeafHook(issue); break; } return path ? `${message} at ${path}` : message; } function findMessage(issue) { - if (issue._tag === "Pointer") + if (issue._tag === "Pointer" || issue._tag === "Composite") return; if (issue._tag === "Encoding") return findMessage(issue.issue); @@ -5219,7 +5265,12 @@ var Declaration = class extends ASTNodeImpl { return (input, options) => { if (input === missing) return missingExit; - return (run ??= this.run(this.typeParameters))(input, this, options); + run ??= this.run(this.typeParameters); + try { + return run(input, this, options); + } catch (error) { + return die3(error); + } }; } _rebuild(recur, checks, encodingChecks, run, encodingRun) { @@ -5332,173 +5383,6 @@ function hasCheck(checks, id) { return checks.some((check) => check.annotations?.representation?.id === id || check._tag === "FilterGroup" && hasCheck(check.checks, id)); } var number2 = /* @__PURE__ */ new Number4; -var Arrays = class extends ASTNodeImpl { - _tag = "Arrays"; - isMutable; - elements; - rest; - encodingChecks; - constructor(isMutable, elements, rest, annotations, checks, encoding, context, encodingChecks) { - super(annotations, checks, encoding, context); - this.isMutable = isMutable; - this.elements = elements; - this.rest = rest; - this.encodingChecks = encodingChecks; - let hasOptional = false; - for (let i = 0;i < elements.length; i++) { - if (isOptional(elements[i])) { - hasOptional = true; - } else if (hasOptional) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - } - if (hasOptional && rest.length > 1) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - for (let i = 1;i < rest.length; i++) { - if (isOptional(rest[i])) { - throw new Error("An optional element cannot follow a rest element. ts(1266)"); - } - } - } - getParser(compile, compileField = compile) { - const ast = this; - let elements; - let rest; - const elementLen = ast.elements.length; - const tailLen = Math.max(0, ast.rest.length - 1); - function getParser(tailThreshold, index) { - if (index < elementLen) { - return elements[index]; - } else if (index >= tailThreshold) { - return rest[index - tailThreshold + 1]; - } - return rest[0]; - } - const finish = (state) => { - const { - input, - len, - options - } = state; - if (ast.rest.length === 0 && len > elementLen) { - for (let i = elementLen;i < len; i++) { - const unexpected = new UnexpectedKey(ast, input[i], options); - const issue = new Pointer([i], unexpected); - if (options.errors === "all") { - if (state.issues) - state.issues.push(issue); - else - state.issues = [issue]; - } else { - return fail6(new Composite(ast, [issue], input, options)); - } - } - } - if (state.issues) { - return fail6(new Composite(ast, state.issues, input, options)); - } - return succeed7(state.output); - }; - const parse = (input, options) => { - const len = input.length; - const state = { - ast, - getParser, - input, - len, - tailThreshold: Math.max(elementLen, len - tailLen), - output: new globalThis.Array(len), - issues: undefined, - options - }; - const end = ast.rest.length === 0 ? elementLen : Math.max(len, elementLen + tailLen); - const concurrency = options.concurrency === undefined ? 1 : resolveConcurrency(options.concurrency); - const eff = concurrency === 1 ? parseArray(state, input, 0, end) : parseArrayConcurrent(state, input, { - concurrency, - end - }); - if (!eff) - return finish(state); - if (effectIsExit(eff)) - return flatMapEager2(eff, () => finish(state)); - let first = true; - return suspend2(() => { - if (!first) - return parse(input, options); - first = false; - return flatMap3(eff, () => finish(state)); - }); - }; - return (input, options) => { - if (input === missing) - return missingExit; - try { - if (!Array.isArray(input)) { - return fail6(new InvalidType(ast, input, options)); - } - if (!elements) { - elements = ast.elements.map((ast) => ({ - ast, - parser: compileField(ast) - })); - rest = ast.rest.map((ast) => ({ - ast, - parser: compileField(ast) - })); - } - return parse(input, options); - } catch (error) { - return die3(error); - } - }; - } - _rebuild(recur, checks, encodingChecks) { - const elements = mapOrSame(this.elements, recur); - const rest = mapOrSame(this.rest, recur); - return elements === this.elements && rest === this.rest && checks === this.checks && encodingChecks === this.encodingChecks ? this : new Arrays(this.isMutable, elements, rest, this.annotations, checks, undefined, this.context, encodingChecks); - } - recur(recur) { - return this._rebuild(recur, this.checks, this.encodingChecks); - } - flip(recur) { - return this._rebuild(recur, this.encodingChecks, this.checks); - } - getExpected() { - return "array"; - } -}; -function stepArray(s, item, exit, i) { - if (exit._tag === "Failure") { - return wrapPropertyKeyIssue(s, s.ast, i, exit); - } - const value = exit === sameExit ? item : exit[args]; - if (value !== missing) { - s.output[i] = value; - } else { - const p = s.getParser(s.tailThreshold, i); - if (isOptional(p.ast)) - return; - const issue = new Pointer([i], new MissingKey(p.ast.context?.annotations)); - if (s.options.errors === "all") { - if (s.issues) - s.issues.push(issue); - else - s.issues = [issue]; - } else { - return fail5(new Composite(s.ast, [issue], s.input, s.options)); - } - } -} -var parseArrayOptions = { - onItem(s, item, i) { - const value = i < s.len ? item : missing; - return s.getParser(s.tailThreshold, i).parser(value, s.options); - }, - step: stepArray -}; -var parseArray = /* @__PURE__ */ iterateEager()(parseArrayOptions); -var parseArrayConcurrent = /* @__PURE__ */ iterateConcurrent()(parseArrayOptions); var wrapPropertyKeyIssue = (s, ast, key, exit) => { if (exit.cause.reasons.length === 0) { return exit; @@ -5517,7 +5401,7 @@ var wrapPropertyKeyIssue = (s, ast, key, exit) => { return fail5(new Composite(ast, [pointer], s.input, s.options)); } }; -var FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?"; +var FINITE_PATTERN = "[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?"; function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) { let stringKeys; let symbolKeys; @@ -5756,9 +5640,15 @@ var Objects = class extends ASTNodeImpl { if (indexCount) return makeFallback(); let fallback; - const resume = (state, index, pending) => { + const resume = (snapshot, index, pending) => { const property = properties[index]; return flatMap3(exit2(pending), (exit) => { + const state = { + ...snapshot, + out: { + ...snapshot.out + } + }; const terminal = stepProperty(state, property, exit); if (terminal) return terminal; @@ -5888,12 +5778,6 @@ function struct(fields, checks, annotations) { function getAST(self) { return self.ast; } -function tuple(elements, checks = undefined) { - return new Arrays(false, elements.map((e) => e.ast), [], undefined, checks); -} -function union(members, options, checks) { - return new Union(members.map(getAST), options, undefined, checks); -} var toCandidate = /* @__PURE__ */ memoizeIdempotent((ast) => { while (true) { if (isSuspend(ast)) @@ -6683,6 +6567,16 @@ function getConstructorDescriptor(ast) { // node_modules/effect/dist/internal/schema/interpreter.js var flatMapTransformation = (result, current, f) => result === sameExit ? f(current) : flatMapEager2(result, f); function compileTransformation(transformation) { + const apply = compileTransformationUnsafe(transformation); + return (result, current, options) => { + try { + return apply(result, current, options); + } catch (error) { + return die3(error); + } + }; +} +function compileTransformationUnsafe(transformation) { if (transformation._tag === "Middleware") { return (result, current, options) => { const transformed = result === sameExit ? transformation.decode(succeed7(toOption(current)), options) : transformation.decode(mapEager2(result, toOption), options); @@ -6758,53 +6652,57 @@ function compile(ast, compile, compileField, base, specialize) { let encodingParsers; const parseChecks = (input, options) => { let result = parser(input, options); - if (encodingChecks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const output = result === sameExit ? input : result[args]; - if (input !== missing && output !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, input, options)); + try { + if (encodingChecks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const output = result === sameExit ? input : result[args]; + if (input !== missing && output !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + result = fail6(new Composite(ast, issues, input, options)); + } } } - } - } else { - result = flatMap3(result, (value) => { - if (input !== missing && value !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - return fail6(new Composite(ast, issues, input, options)); + } else { + result = flatMap3(result, (value) => { + if (input !== missing && value !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, input, options)); + } } - } - return succeed6(value); - }); - } - } - if (checks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const value = result === sameExit ? input : result[args]; - if (value === missing) - return result; - const issues = collectIssues(checks, value, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, value, options)); - } + return succeed6(value); + }); } - } else { - result = flatMap3(result, (value) => { - if (value !== missing) { + } + if (checks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const value = result === sameExit ? input : result[args]; + if (value === missing) + return result; const issues = collectIssues(checks, value, undefined, ast, options); if (issues) { - return fail6(new Composite(ast, issues, value, options)); + result = fail6(new Composite(ast, issues, value, options)); } } - return succeed6(value); - }); + } else { + result = flatMap3(result, (value) => { + if (value !== missing) { + const issues = collectIssues(checks, value, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, value, options)); + } + } + return succeed6(value); + }); + } } + return result; + } catch (error) { + return die3(error); } - return result; }; const parseLocal = specialize === undefined ? parseChecks : specialize(parseChecks); if (!links) { @@ -7206,33 +7104,6 @@ function makeStruct(ast, fields) { function Struct(fields) { return makeStruct(struct(fields, undefined), fields); } -function makeTuple(ast, elements) { - return make8(ast, { - elements, - mapElements(f, options) { - const elements = f(this.elements); - return makeTuple(tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements); - } - }); -} -function Tuple(elements) { - return makeTuple(tuple(elements), elements); -} -var ArraySchema = /* @__PURE__ */ lambda((schema) => make8(new Arrays(false, [], [schema.ast]), { - value: schema -})); -function makeUnion(ast, members) { - return make8(ast, { - members, - mapMembers(f, options) { - const members = f(this.members); - return makeUnion(union(members, this.ast.options, options?.unsafePreserveChecks ? this.ast.checks : undefined), members); - } - }); -} -function Union2(members, options) { - return makeUnion(union(members, options, undefined), members); -} function decodeTo2(to, transformation) { return (from) => { return make8(decodeTo(from.ast, to.ast, transformation ? makeTransformation(transformation) : passthrough2()), { @@ -7264,32 +7135,24 @@ function link() { }; } var makeFilter2 = makeFilter; -function isPattern2(regExp, annotations) { - const source = regExp.source; - const flags = regExp.flags; - const canExport = /^[dg]*uy?$/.test(flags); - const runtimeRegExp = flags === "" ? `new RegExp(${format(source)})` : `new RegExp(${format(source)}, ${format(flags)})`; - return isPattern(regExp, { - toJsonSchema: () => canExport ? { - pattern: flags.endsWith("y") ? `^(?:${source})` : source - } : [{}, true], - toCode: () => ({ - runtime: `Schema.isPattern(${runtimeRegExp})` - }), - ...annotations - }); -} function isBase64(annotations) { - const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - return isPattern2(regExp, { + const pattern = "^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"; + const regExp = /^[0-9a-zA-Z+/]*={0,2}$/; + return makeFilter2((s) => s.length % 4 === 0 && regExp.test(s), { expected: "a base64 encoded string", representation: { id: "effect/schema/isBase64", payload: null }, toJsonSchema: () => ({ - pattern: regExp.source + pattern }), + arbitraryConstraint: { + patterns: [{ + source: pattern, + flags: "" + }] + }, toCode: () => ({ runtime: "Schema.isBase64()" }), @@ -7403,47 +7266,6 @@ var File = /* @__PURE__ */ instanceOf(globalThis.File, { }) })) }); -var FormData2 = /* @__PURE__ */ instanceOf(globalThis.FormData, { - representation: { - id: "effect/schema/FormData", - payload: null - }, - toCode: () => ({ - runtime: `Schema.FormData`, - Type: `globalThis.FormData` - }), - expected: "FormData", - toCodecJson: () => link()(ArraySchema(Tuple([String5, Union2([Struct({ - _tag: tag("String"), - value: String5 - }), Struct({ - _tag: tag("File"), - value: File - })])])), transformEffect2({ - decode: (e) => { - const out = new globalThis.FormData; - for (const [key, entry] of e) { - out.append(key, entry.value); - } - return succeed6(out); - }, - encode: (formData) => { - return succeed6(globalThis.Array.from(formData.entries()).map(([key, value]) => { - if (typeof value === "string") { - return [key, { - _tag: "String", - value - }]; - } else { - return [key, { - _tag: "File", - value - }]; - } - })); - } - })) -}); var URLSearchParams2 = /* @__PURE__ */ instanceOf(globalThis.URLSearchParams, { representation: { id: "effect/schema/URLSearchParams", @@ -7559,13 +7381,16 @@ function makeClass(Inherited, identifier, struct2, annotations, proto) { } return out; } -function getClassTransformation(self) { - return new Transformation(transform((input) => new self(input, { +function makeClassTrusted(self, fields) { + return new self(fields, { "~payload": { token: payloadToken, - value: input + value: fields } - })), passthrough()); + }); +} +function getClassTransformation(self) { + return new Transformation(transform((input) => makeClassTrusted(self, input)), passthrough()); } function getClassTypeId(identifier) { return `~effect/Schema/Class/${identifier}`; @@ -8052,14 +7877,11 @@ var toTransform = (channel) => channel.transform; var asyncQueue = (scope, f, options) => make11({ capacity: options?.bufferSize, strategy: options?.strategy -}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope)))); +}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope, { + startImmediately: true +})))); var callbackArray = (f, options) => fromTransform((_, scope) => map5(asyncQueue(scope, f, options), takeAll2)); -var suspend3 = (evaluate) => fromTransform((upstream, scope) => suspend2(() => toTransform(evaluate())(upstream, scope))); var empty3 = /* @__PURE__ */ fromPull(/* @__PURE__ */ succeed6(/* @__PURE__ */ done2())); -var map7 = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => sync3(() => { - let i = 0; - return map5(pull, (o) => f(o, i++)); -}))); var mapDone = /* @__PURE__ */ dual(2, (self, f) => mapDoneEffect(self, (o) => succeed6(f(o)))); var mapDoneEffect = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => succeed6(catchDone(pull, (done) => flatMap3(f(done), done2))))); var merge2 = /* @__PURE__ */ dual((args) => isChannel(args[0]) && isChannel(args[1]), (left, right, options) => fromTransformBracket(fnUntraced2(function* (upstream, _scope, forkedScope) { @@ -8172,6 +7994,18 @@ var splitLines = () => fromTransform((upstream, _scope) => sync3(() => { } return pullOrFlush; })); +var decodeText = (encoding, options) => fromTransform((upstream, _scope) => sync3(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + let pull = upstream.pipe(map5(map2((bytes) => decoder.decode(bytes, streamOptions))), catchDone((leftover) => { + pull = done2(leftover); + const last = decoder.decode(); + return last.length > 0 ? succeed6(of(last)) : pull; + })); + return suspend2(() => pull); +})); var pipeTo = /* @__PURE__ */ dual(2, (self, that) => fromTransform((upstream, scope) => flatMap3(toTransform(self)(upstream, scope), (upstream) => toTransform(that)(upstream, scope)))); var unwrap = (channel) => fromTransform((upstream, scope) => { let pull; @@ -8439,12 +8273,7 @@ var transformPull2 = (self, f) => fromChannel3(fromTransform((_, scope) => flatM var toChannel2 = (stream) => stream.channel; var callback3 = (f, options) => fromChannel3(callbackArray(f, options)); var empty4 = /* @__PURE__ */ fromChannel3(empty3); -var suspend4 = (stream) => fromChannel3(suspend3(() => stream().channel)); var unwrap3 = (effect) => fromChannel3(unwrap(map5(effect, toChannel2))); -var map8 = /* @__PURE__ */ dual(2, (self, f) => suspend4(() => { - let i = 0; - return fromChannel3(map7(self.channel, map2((o) => f(o, i++)))); -})); var merge3 = /* @__PURE__ */ dual((args) => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel3(merge2(toChannel2(self), toChannel2(that), options))); var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (upstream, scope) => sync3(() => { let done; @@ -8466,12 +8295,7 @@ var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (up }); return suspend2(() => done ? done : pull); }))); -var decodeText = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => suspend4(() => { - const decoder = new TextDecoder(options?.encoding); - return map8(self, (chunk) => decoder.decode(chunk, { - stream: true - })); -})); +var decodeText2 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => self.channel.pipe(pipeTo(decodeText(options?.encoding)), fromChannel3)); var splitLines2 = (self) => self.channel.pipe(pipeTo(splitLines()), fromChannel3); var run2 = /* @__PURE__ */ dual(2, (self, sink) => scopedWith2((scope) => toPullScoped(self.channel, scope).pipe(flatMap3((upstream) => sink.transform(upstream, scope)), map5(([a]) => a)))); var runCollect = (self) => runFold(self.channel, () => [], (acc, chunk) => { @@ -8597,10 +8421,14 @@ var ulidString = (timestampMillis, bytes) => { }; // node_modules/effect/dist/internal/uuid.js -var hex = (byte) => byte.toString(16).padStart(2, "0"); +var hex = /* @__PURE__ */ Array.from({ + length: 256 +}, (_, byte) => byte.toString(16).padStart(2, "0")); var stringify = (bytes) => { - const segments = [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)]; - return segments.map((segment) => Array.from(segment, hex).join("")).join("-"); + if (bytes.length < 16) { + return [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)].map((segment) => Array.from(segment, (byte) => hex[byte]).join("")).join("-"); + } + return hex[bytes[0]] + hex[bytes[1]] + hex[bytes[2]] + hex[bytes[3]] + "-" + hex[bytes[4]] + hex[bytes[5]] + "-" + hex[bytes[6]] + hex[bytes[7]] + "-" + hex[bytes[8]] + hex[bytes[9]] + "-" + hex[bytes[10]] + hex[bytes[11]] + hex[bytes[12]] + hex[bytes[13]] + hex[bytes[14]] + hex[bytes[15]]; }; var randomBytes = () => globalThis.crypto.getRandomValues(new Uint8Array(16)); function v4Bytes(bytes = randomBytes()) { @@ -8719,23 +8547,26 @@ var defaultTeardown = (exit, onExit) => { return onExit(getErrorExitCode(squash(exit.cause))); }; var makeRunMain = (f) => dual((args) => isEffect2(args[0]), (effect, options) => { - const fiber = options?.disableErrorReporting === true ? runFork2(effect) : runFork2(tapCause2(effect, (cause) => { + const main = options?.disableErrorReporting === true ? effect : tapCause2(effect, (cause) => { if (hasInterruptsOnly2(cause)) return void_3; const isReported = getErrorReported(squash(cause)); return isReported ? logError(cause) : void_3; - })); - try { - const keepAlive = globalThis.setInterval(constVoid, 2147483647); - fiber.addObserver(() => { - clearInterval(keepAlive); - }); - } catch {} - const teardown = options?.teardown ?? defaultTeardown; - return f({ - fiber, - teardown }); + const teardown = options?.teardown ?? defaultTeardown; + runFork2(withFiber2((fiber) => { + try { + const keepAlive = globalThis.setInterval(constVoid, 2147483647); + fiber.addObserver(() => { + clearInterval(keepAlive); + }); + } catch {} + f({ + fiber, + teardown + }); + return main; + })); }); var errorExitCode = "~effect/Runtime/errorExitCode"; var getErrorExitCode = (u) => { @@ -8840,7 +8671,7 @@ var makeHandle = (params) => Object.setPrototypeOf({ ...params }, HandleProto); var make20 = (spawn) => { - const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); + const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText2(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); const streamLines = (command, options) => splitLines2(streamString(command, options)); return ChildProcessSpawner.of({ spawn, @@ -9009,6 +8840,7 @@ var handleErrnoException = (module, method) => (err, [path]) => { reason = "NotFound"; break; case "EACCES": + case "EPERM": reason = "PermissionDenied"; break; case "EEXIST": @@ -9037,66 +8869,149 @@ var handleErrnoException = (module, method) => (err, [path]) => { }); }; +// node_modules/@effect/platform-node-shared/dist/NodeSink.js +import { finished } from "node:stream"; + +// node_modules/@effect/platform-node-shared/dist/internal/stream.js +var destroyStream = (stream, cleanup, onDestroyed) => { + if (!("closed" in stream)) { + cleanup(); + onDestroyed?.(); + return; + } + const onDone = () => { + clearImmediate(immediate); + stream.off("error", onDone); + stream.off("close", onDone); + onDestroyed?.(); + }; + const onClosed = () => { + if (stream.closed) { + onDone(); + } else { + immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + } + }; + let immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + stream.once("error", onDone); + stream.once("close", onDone); + cleanup(); + if (!stream.closed) { + stream.destroy(); + } +}; + // node_modules/@effect/platform-node-shared/dist/NodeSink.js var fromWritable = (options) => fromChannel2(mapDone(fromWritableChannel(options), (_) => [_])); var fromWritableChannel = (options) => fromTransform((pull) => { const writable = options.evaluate(); - return succeed6(pullIntoWritable({ + const write = pullIntoWritable({ ...options, writable, pull - })); -}); -var pullIntoWritable = (options) => options.pull.pipe(flatMap3((chunk) => { - let i = 0; - return callback2((resume) => { - let cancelled = false; - const loop = () => { - for (;i < chunk.length; ) { - if (cancelled) { - return; - } - const success = options.writable.write(chunk[i++], options.encoding); - if (!success) { - if (!cancelled) { - options.writable.once("drain", loop); + }); + return succeed6(options.endOnDone === false ? write : onError2(write, (cause) => isDoneCause(cause) ? void_3 : releaseWritable(writable))); +}); +var releaseWritable = (writable) => callback2((resume) => { + const onDestroyed = () => resume(void_3); + if (writable.closed) { + const cleanup = finished(writable, { + readable: false + }, () => { + cleanup(); + onDestroyed(); + }); + } else { + destroyStream(writable, constVoid, onDestroyed); + } +}); +var pullIntoWritable = (options) => withFiber2((fiber) => { + const dispatcher = fiber.currentDispatcher; + const completion = makeUnsafe2(); + const failure = makeUnsafe2(); + const onError = (error) => doneUnsafe(failure, failSync2(() => options.onError(error))); + let errorEmitted = false; + const onStreamError = (error) => { + errorEmitted = true; + onError(error); + }; + options.writable.on("error", onStreamError); + const cleanup = finished(options.writable, { + readable: false + }, (error) => { + if (error) { + onError(error); + } else { + doneUnsafe(completion, void_3); + } + }); + return options.pull.pipe(flatMap3((chunk) => { + let i = 0; + return callback2((resume) => { + let cancelled = false; + const onFinish = () => dispatcher.scheduleTask(loop, 0); + const loop = () => { + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + for (;i < chunk.length; ) { + if (cancelled) { + return; + } + const success = options.writable.write(chunk[i++], options.encoding, (error) => { + if (!error) + return; + if (options.writable.closed) { + onError(error); + } else { + dispatcher.scheduleTask(() => onError(error), 0); + } + }); + if (!success) { + if (!cancelled) { + options.writable.once("drain", loop); + options.writable.once("finish", onFinish); + } + return; } - return; } - } - if (!cancelled) { - resume(void_3); - } - }; - loop(); - return sync3(() => { - cancelled = true; - options.writable.off("drain", loop); + if (!cancelled) { + resume(void_3); + } + }; + loop(); + return sync3(() => { + cancelled = true; + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + }); }); - }); -}), forever2({ - disableYield: true -}), options.endOnDone !== false ? catchDone((_) => { - if ("closed" in options.writable && options.writable.closed) { - return done2(_); - } - return callback2((resume) => { - const onFinish = () => resume(done2(_)); - options.writable.once("finish", onFinish); + }), forever2({ + disableYield: true + }), options.endOnDone !== false ? catchDone((_) => { options.writable.end(); - return sync3(() => { - options.writable.off("finish", onFinish); - }); - }); -}) : identity, raceFirst2(callback2((resume) => { - const onError = (error) => resume(fail6(options.onError(error))); - options.writable.once("error", onError); - return sync3(() => { - options.writable.off("error", onError); - }); -}))); + return andThen2(_await(completion), done2(_)); + }) : identity, raceFirst2(_await(failure)), ensuring2(sync3(() => { + cleanup(); + const removeErrorListener = () => { + options.writable.off("error", onStreamError); + options.writable.off("error", removeErrorListener); + options.writable.off("close", removeErrorListener); + }; + if (options.writable.errored && !options.writable.closed && !errorEmitted) { + options.writable.once("error", removeErrorListener); + options.writable.once("close", removeErrorListener); + } else { + removeErrorListener(); + } + }))); +}); // node_modules/@effect/platform-node-shared/dist/NodeStream.js +import { finished as finished2, Readable } from "node:stream"; var fromReadable = (options) => fromChannel3(fromReadableChannel(options)); var fromReadableChannel = (options) => fromTransform((_, scope) => readableToPullUnsafe({ scope, @@ -9113,17 +9028,14 @@ var readableToPullUnsafe = (options) => { function onReadable() { latch.openUnsafe(); } - function onError(error) { - exit.current = fail5(options.onError(error)); - latch.openUnsafe(); - } - function onEnd() { - exit.current = fail5(Done2()); - latch.openUnsafe(); - } readable.on("readable", onReadable); - readable.once("error", onError); - readable.once("end", onEnd); + const cleanup = finished2(readable, { + readable: true, + writable: false + }, (error) => { + exit.current ??= fail5(error ? options.onError(error) : Done2()); + latch.openUnsafe(); + }); const pull = suspend2(function loop() { let item = options.readable.read(options.chunkSize); if (item === null) { @@ -9147,10 +9059,10 @@ var readableToPullUnsafe = (options) => { }); return as2(addFinalizer2(options.scope, sync3(() => { readable.off("readable", onReadable); - readable.off("error", onError); - readable.off("end", onEnd); - if (closeOnDone && "closed" in options.readable && !options.readable.closed) { - options.readable.destroy(); + if (closeOnDone) { + destroyStream(readable, cleanup); + } else { + cleanup(); } })), pull); }; @@ -9475,6 +9387,7 @@ var make22 = /* @__PURE__ */ gen2(function* () { const signalGroup = (signal) => killProcessGroup(command, childProcess, signal).pipe(catch_2(() => killProcess(command, childProcess, signal))); yield* signalGroup(options?.killSignal ?? "SIGTERM"); if (isUndefined(options?.forceKillAfter)) { + yield* _await(exitSignal); yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis); } else { yield* awaitProcessExit(childProcess, exitSignal, toMillis(options.forceKillAfter)); @@ -10068,14 +9981,14 @@ var readLink = /* @__PURE__ */ (() => { return (path) => nodeReadLink(path); })(); var realPath = /* @__PURE__ */ (() => { - const nodeRealPath = /* @__PURE__ */ effectify(NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); + const nodeRealPath = /* @__PURE__ */ effectify(process.platform === "win32" ? NFS.realpath.native : NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); return (path) => nodeRealPath(path); })(); var rename2 = /* @__PURE__ */ (() => { const nodeRename = /* @__PURE__ */ effectify(NFS.rename, /* @__PURE__ */ handleErrnoException("FileSystem", "rename"), /* @__PURE__ */ handleBadArgument("rename")); return (oldPath, newPath) => nodeRename(oldPath, newPath); })(); -var makeFileInfo = (stat) => try_2({ +var makeFileInfo = (stat, method = "stat") => try_2({ try: () => ({ type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown", mtime: fromNullishOr(stat.mtime), @@ -10092,14 +10005,16 @@ var makeFileInfo = (stat) => try_2({ blksize: stat.blksize !== undefined ? some2(bytes(stat.blksize)) : none2(), blocks: fromNullishOr(stat.blocks) }), - catch: handleBadArgument("stat") + catch: handleBadArgument(method) }); -var stat2 = /* @__PURE__ */ (() => { - const nodeStat = /* @__PURE__ */ effectify(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat")); +var statFactory = (method, nodeStatFn) => { + const nodeStat = effectify(nodeStatFn, handleErrnoException("FileSystem", method), handleBadArgument(method)); return (path) => flatMap3(nodeStat(path, { bigint: true - }), makeFileInfo); -})(); + }), (stat) => makeFileInfo(stat, method)); +}; +var stat2 = /* @__PURE__ */ statFactory("stat", NFS.stat); +var lstat2 = /* @__PURE__ */ statFactory("lstat", NFS.lstat); var symlink2 = /* @__PURE__ */ (() => { const nodeSymlink = /* @__PURE__ */ effectify(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink")); return (target, path) => nodeSymlink(target, path); @@ -10182,6 +10097,7 @@ var makeFileSystem = /* @__PURE__ */ map5(/* @__PURE__ */ serviceOption2(WatchBa copyFile: copyFile2, glob: glob2, link: link3, + lstat: lstat2, makeDirectory, makeTempDirectory, makeTempDirectoryScoped, @@ -10321,9 +10237,6 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readline.emitKeypressEvents(stdin, rl); rl.on("line", onLine); rl.once("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(true); - } return { rl, onClose, @@ -10337,9 +10250,6 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readlineActive = false; rl.off("line", onLine); rl.off("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(false); - } rl.close(); if (inputEnded) { endUnsafe(lines); @@ -10347,6 +10257,14 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu })), idleTimeToLive: "10 millis" }); + const setRawMode = (enabled) => sync3(() => { + if (stdin.isTTY) + stdin.setRawMode(enabled); + }); + const rawModeRef = yield* make13({ + acquire: acquireRelease2(setRawMode(true), () => setRawMode(false)), + idleTimeToLive: "10 millis" + }); const columns = sync3(() => stdout.columns ?? 0); const rows = sync3(() => stdout.rows ?? 0); const readInput = gen2(function* () { @@ -10381,6 +10299,7 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu handleEnd(); } else { yield* get3(rlRef); + yield* get3(rawModeRef); stdin.once("end", handleEnd); } return queue; @@ -10499,7 +10418,7 @@ class CommandError extends TaggedError3()("CommandError", { }) { } var error = (command, cause) => new CommandError({ command, exitCode: -1, stderr: String(cause) }); -var collectText = (stream) => stream.pipe(decodeText(), runFold2(() => "", (all, chunk) => all + chunk)); +var collectText = (stream) => stream.pipe(decodeText2(), runFold2(() => "", (all, chunk) => all + chunk)); var retainedStderrLength = 16 * 1024; class Service3 extends Service()("@timmo001/workflows/CommandExecutor") { @@ -10552,8 +10471,8 @@ var layer14 = effect(Service3, gen2(function* () { stdin: "inherit" })); let stderrTail = ""; - const stdout = handle.stdout.pipe(decodeText(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); - const stderr = handle.stderr.pipe(decodeText(), runForEach2((chunk) => sync3(() => { + const stdout = handle.stdout.pipe(decodeText2(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); + const stderr = handle.stderr.pipe(decodeText2(), runForEach2((chunk) => sync3(() => { process.stderr.write(chunk); stderrTail = `${stderrTail}${chunk}`.slice(-retainedStderrLength); }))); diff --git a/.github/actions/validate-js-package/dist/index.js b/.github/actions/validate-js-package/dist/index.js index f36f6c4e..f85c3a00 100644 --- a/.github/actions/validate-js-package/dist/index.js +++ b/.github/actions/validate-js-package/dist/index.js @@ -769,6 +769,10 @@ function assignProperty(self, key, value) { } } function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } for (const key of Reflect.ownKeys(source)) { if (Object.prototype.propertyIsEnumerable.call(source, key)) { assignProperty(self, key, source[key]); @@ -859,7 +863,7 @@ class CauseImpl { toJSON() { return { _id: "Cause", - failures: this.reasons.map((f) => f.toJSON()) + reasons: this.reasons.map((f) => f.toJSON()) }; } toString() { @@ -1610,9 +1614,21 @@ var bigint2 = /* @__PURE__ */ BigInt(2); var bigint10 = /* @__PURE__ */ BigInt(10); var bigint1e3 = /* @__PURE__ */ BigInt(1000); var bigint1e6 = /* @__PURE__ */ BigInt(1e6); +var bigint1e9 = /* @__PURE__ */ BigInt(1e9); +var bigintNanosPerMinute = /* @__PURE__ */ BigInt(60000000000); +var bigintNanosPerHour = /* @__PURE__ */ BigInt(3600000000000); +var bigintNanosPerDay = /* @__PURE__ */ BigInt(86400000000000); +var bigintNanosPerWeek = /* @__PURE__ */ BigInt(604800000000000); var roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input))); var roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6); var fromNanosNumber = (nanos) => make3(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos); +var nanosToUnit = (nanos, divisor) => { + const value = Number(nanos); + if (Number.isFinite(value)) + return value / divisor; + const scale = BigInt(divisor); + return Number(nanos / scale) + Number(nanos % scale) / divisor; +}; var parseNanos = (input, scale) => { const decimalIndex = input.indexOf("."); if (decimalIndex === -1) @@ -1628,6 +1644,13 @@ var divideTiesAwayFromZero = (numerator, denominator) => { const rounded = absolute / denominator + (absolute % denominator * bigint2 >= denominator ? bigint1 : bigint0); return numerator < bigint0 ? -rounded : rounded; }; +var fromMillisString = (input, scale) => { + const millis = Number(input) * scale; + if (!Number.isFinite(millis)) + return make3(millis); + const nanos = parseNanos(input, BigInt(scale) * bigint1e6); + return make3(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos); +}; var DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; var fromInputUnsafe = (input) => { switch (typeof input) { @@ -1652,26 +1675,25 @@ var fromInputUnsafe = (input) => { if (unit === "micro" || unit === "micros") { return nanos(parseNanos(valueStr, bigint1e3)); } - const value = Number(valueStr); switch (unit) { case "milli": case "millis": - return millis(value); + return fromMillisString(valueStr, 1); case "second": case "seconds": - return seconds(value); + return fromMillisString(valueStr, 1000); case "minute": case "minutes": - return minutes(value); + return fromMillisString(valueStr, 60000); case "hour": case "hours": - return hours(value); + return fromMillisString(valueStr, 3600000); case "day": case "days": - return days(value); + return fromMillisString(valueStr, 86400000); case "week": case "weeks": - return weeks(value); + return fromMillisString(valueStr, 604800000); } break; } @@ -1693,7 +1715,8 @@ var fromInputUnsafe = (input) => { if (input[0] === Infinity || input[1] === Infinity) { return infinity; } - return fromNanosNumber(input[0] * 1e9 + input[1]); + const nanos = input[0] * 1e9 + input[1]; + return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make3(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos); } const obj = input; let millis = 0; @@ -1709,13 +1732,42 @@ var fromInputUnsafe = (input) => { millis += obj.seconds * 1000; if (obj.milliseconds) millis += obj.milliseconds; - if (!obj.microseconds && !obj.nanoseconds) - return make3(millis); - return fromNanosNumber(millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0)); + if (!obj.microseconds && !obj.nanoseconds) { + if (!Number.isFinite(millis)) + return make3(millis); + const exact = sumObjectNanos(obj); + return exact === undefined || BigInt(millis) * bigint1e6 === exact ? make3(millis) : make3(exact); + } + const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0); + const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : undefined; + return exact === undefined ? fromNanosNumber(nanos) : make3(exact); } } return invalid(input); }; +var isIntegerOrUnset = (n) => !n || Number.isInteger(n); +var sumObjectNanos = (obj) => { + if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds)) + return; + let nanos = bigint0; + if (obj.weeks) + nanos += BigInt(obj.weeks) * bigintNanosPerWeek; + if (obj.days) + nanos += BigInt(obj.days) * bigintNanosPerDay; + if (obj.hours) + nanos += BigInt(obj.hours) * bigintNanosPerHour; + if (obj.minutes) + nanos += BigInt(obj.minutes) * bigintNanosPerMinute; + if (obj.seconds) + nanos += BigInt(obj.seconds) * bigint1e9; + if (obj.milliseconds) + nanos += BigInt(obj.milliseconds) * bigint1e6; + if (obj.microseconds) + nanos += BigInt(obj.microseconds) * bigint1e3; + if (obj.nanoseconds) + nanos += BigInt(obj.nanoseconds); + return nanos; +}; var invalid = (input) => { throw new Error(`Invalid Input: ${input}`); }; @@ -1824,14 +1876,9 @@ var infinity = /* @__PURE__ */ make3(Infinity); var negativeInfinity = /* @__PURE__ */ make3(-Infinity); var nanos = (nanos) => make3(nanos); var millis = (millis) => make3(millis); -var seconds = (seconds) => make3(seconds * 1000); -var minutes = (minutes) => make3(minutes * 60000); -var hours = (hours) => make3(hours * 3600000); -var days = (days) => make3(days * 86400000); -var weeks = (weeks) => make3(weeks * 604800000); var toMillis = (self) => match3(fromInputUnsafe(self), { onMillis: identity, - onNanos: (nanos) => Number(nanos) / 1e6, + onNanos: (nanos) => nanosToUnit(nanos, 1e6), onInfinity: () => Infinity, onNegativeInfinity: () => -Infinity }); @@ -1897,7 +1944,7 @@ var setTimer = "setImmediate" in globalThis ? (f) => { const timer = setTimeout(f, 0); return () => clearTimeout(timer); }; -var setImmediate = (f) => { +var setImmediate2 = (f) => { try { return setTimer(f); } catch { @@ -1937,7 +1984,7 @@ class MixedScheduler { setImmediate; constructor(executionMode = "async", setImmediateFn) { this.executionMode = executionMode; - this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate2); } shouldYield(fiber) { return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; @@ -1951,7 +1998,7 @@ class MixedSchedulerDispatcher { tasks = /* @__PURE__ */ new PriorityBuckets; running = undefined; setImmediate; - constructor(setImmediateFn = setImmediate) { + constructor(setImmediateFn = setImmediate2) { this.setImmediate = setImmediateFn; } scheduleTask(task, priority) { @@ -2195,10 +2242,7 @@ class Interrupt extends ReasonBase { } } var causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); -var findFail = (self) => { - const reason = self.reasons.find(isFailReason); - return reason ? succeed2(reason) : fail2(self); -}; +var hasFails = (self) => self.reasons.some(isFailReason); var findError = (self) => { for (let i = 0;i < self.reasons.length; i++) { const reason = self.reasons[i]; @@ -2208,6 +2252,9 @@ var findError = (self) => { } return fail2(self); }; +var hasDies = (self) => self.reasons.some(isDieReason); +var causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +var findRecoverableError = (self) => hasDies(self) ? fail2(causeElectDefects(self)) : findError(self); var hasInterrupts = (self) => self.reasons.some(isInterruptReason); var hasInterruptsOnly = (self) => self.reasons.length > 0 && self.reasons.every(isInterruptReason); var causeMap = /* @__PURE__ */ dual(2, (self, f) => { @@ -2268,12 +2315,14 @@ var causePrettyErrors = (self, options) => { } return errors; }; -var causePrettyError = (original, annotations, options) => { +var causePrettyError = (original, annotations, options, seen = new Set) => { const kind = typeof original; let error; if (original && kind === "object") { + seen.add(original); + const cause = original.cause; error = new globalThis.Error(causePrettyMessage(original), { - cause: original.cause ? causePrettyError(original.cause) : undefined + cause: cause !== undefined && !seen.has(cause) ? causePrettyError(cause, undefined, undefined, seen) : undefined }); if (typeof original.name === "string") { error.name = original.name; @@ -2484,7 +2533,11 @@ class FiberImpl { } else if (this._asyncContext !== undefined) { const asyncContext = this._asyncContext; this._asyncContext = undefined; - return asyncContext.runInAsyncScope(this.evaluate, this, effect); + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } } else if (this._yielded !== undefined) { const yielded = this._yielded; this._yielded = undefined; @@ -2782,7 +2835,6 @@ var tryPromise = (options) => { } }, f.length !== 0); }; -var withFiberId = (f) => withFiber((fiber) => f(fiber.id)); var callbackOptions = /* @__PURE__ */ function() { const Proto = /* @__PURE__ */ makePrimitiveProto({ op: "Async", @@ -2803,9 +2855,9 @@ var callbackOptions = /* @__PURE__ */ function() { if (yielded !== false) return yielded; yielded = true; - fiber._yielded = () => { + fiber.yieldWith(() => { resumed = true; - }; + }); if (controller === undefined && onCancel === undefined) { return Yield; } @@ -3088,10 +3140,7 @@ var exitMap = /* @__PURE__ */ dual(2, (self, f) => self._tag === "Success" ? exi var exitMapError = /* @__PURE__ */ dual(2, (self, f) => { if (self._tag === "Success") return self; - const error = findError(self.cause); - if (isFailure2(error)) - return self; - return exitFail(f(error.success)); + return exitFailCause(causeMap(self.cause, f)); }); var exitZipRight = /* @__PURE__ */ dual(2, (self, that) => exitIsSuccess(self) ? that : self); var exitAsVoidAll = (exits) => { @@ -3155,10 +3204,10 @@ var catchCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(s const eb = filter(cause); return isFailure2(eb) ? failCause(eb.failure) : f(eb.success, cause); })); -var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findError, (e) => f(e))); +var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findRecoverableError, (e) => f(e))); var tapCause = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => andThen(f(cause), failCause(cause)))); var catchIf = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, predicate, f, orElse) => catchCause(self, (cause) => { - const error = findError(cause); + const error = findRecoverableError(cause); if (isFailure2(error)) return failCause(error.failure); if (!predicate(error.success)) { @@ -3170,7 +3219,7 @@ var catchTag = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, k, f, or const pred = Array.isArray(k) ? (e) => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); return catchIf(self, pred, f, orElse); }); -var mapError = /* @__PURE__ */ dual(2, (self, f) => catch_(self, (error) => failSync(() => f(error)))); +var mapError = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => failCause(causeMap(cause, f)))); var orDie = (self) => catch_(self, die); var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { if (!options?.log) { @@ -3182,8 +3231,8 @@ var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) = const logEffect = logWithLevel(options.log === true ? undefined : options.log); return matchCauseEffect(self, { onFailure(cause) { - const failure = findFail(cause); - return isFailure2(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); }, onSuccess: (_) => void_ }); @@ -3222,16 +3271,16 @@ var makeMatch = (op, onFailure) => { return MatchImpl; }; var MatchImpl = /* @__PURE__ */ makeMatch("Match", function(cause, fiber) { - const fail = cause.reasons.find(isFailReason); - if (fail === undefined) - return failCause(cause); + const error = findRecoverableError(cause); + if (isFailure2(error)) + return failCause(error.failure); const handlers = this.payload; - return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(fail.error) : internalCall(() => handlers.onFailure(fail.error))); + return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))); }); var matchEffect = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, { onFailure: (cause) => { - const fail = cause.reasons.find(isFailReason); - return fail ? options.onFailure(fail.error) : failCause(cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.onFailure(error.success); }, onSuccess: options.onSuccess })); @@ -3240,9 +3289,9 @@ var matchEager = /* @__PURE__ */ dual(2, (self, options) => { if (effectIsExit(self)) { if (self._tag === "Success") return exitSucceed(options.onSuccess(self.value)); - const error = findError(self.cause); + const error = findRecoverableError(self.cause); if (isFailure2(error)) - return self; + return exitFailCause(error.failure); return exitSucceed(options.onFailure(error.success)); } return match4(self, options); @@ -3297,17 +3346,17 @@ var runFinalizer = (finalizer, exit_) => { return exitDie(defect); } }; -var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeCombine(exit_.cause, cause))); +var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); var scopeCloseFinalizers = /* @__PURE__ */ fnUntraced(function* (self, finalizers, exit_) { let exits = []; const fibers = []; - const arr = Array.from(finalizers.values()); + const arr = Array.from(finalizers); const parent = getCurrentFiber(); for (let i = arr.length - 1;i >= 0; i--) { - const finalizer = arr[i]; + const [key, finalizer] = arr[i]; if (self.strategy === "sequential") { exits.push(yield* exit(runFinalizer(finalizer, exit_))); - } else { + } else if (key !== parent) { fibers.push(forkUnsafe(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); } } @@ -3500,15 +3549,9 @@ var all = (arg, options) => { } else if (options?.discard) { return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options); } - return suspend(() => { - const out = {}; - return as(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => { - assignProperty(out, key, value); - }), { - discard: true, - concurrency: options?.concurrency - }), out); - }); + return suspend(() => map3(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => [key, value]), { + concurrency: options?.concurrency + }), Object.fromEntries)); }; var whileLoop = /* @__PURE__ */ makePrimitive({ op: "While", @@ -3647,7 +3690,7 @@ var iterateConcurrentImpl = (options) => { const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); if (reasons.length > 0) { const cause = causeFromReasons(reasons); - terminal = exitFailCause(terminal._tag === "Failure" ? causeCombine(terminal.cause, cause) : cause); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); } } } else { @@ -3725,14 +3768,13 @@ var forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterrupt } return child; }; +var fiberScopeFinalizer = (fiber) => () => withFiber((current) => current === fiber ? void_ : fiberInterrupt(fiber)); var forkIn = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, scope, options) => withFiber((parent) => { - const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + const fiber = scope.state._tag === "Closed" ? new FiberImpl(parent.context) : forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); if (!fiber._exit) { if (scope.state._tag !== "Closed") { - const key = {}; - const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); - scopeAddFinalizerUnsafe(scope, key, finalizer); - fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + scopeAddFinalizerUnsafe(scope, fiber, fiberScopeFinalizer(fiber)); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, fiber)); } else { fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); } @@ -3769,7 +3811,7 @@ var fiberRunIn = /* @__PURE__ */ dual(2, (self, scope) => { return self; } scopeRemoveFinalizerUnsafe(scope, self); - scopeAddFinalizerUnsafe(scope, self, () => fiberInterrupt(self)); + scopeAddFinalizerUnsafe(scope, self, fiberScopeFinalizer(self)); self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, self)); return self; }); @@ -4408,8 +4450,8 @@ var mergeAllEffect = (layers, memoMap, scope) => { concurrency: layers.length }).pipe(map3((context) => mergeAll(...context))); }; -var mergeAll2 = (...layers) => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); -var provideWith = (self, that, f) => fromBuild((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); +var mergeAll2 = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +var provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); var provide2 = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, identity)); var provideMerge = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, (self, that) => merge(that, self))); @@ -4480,6 +4522,7 @@ var void_3 = void_; var callback2 = callback; var gen2 = gen; var fail6 = fail3; +var failSync2 = failSync; var failCause3 = failCause; var failCauseSync2 = failCauseSync; var die3 = die; @@ -4529,16 +4572,23 @@ var fn2 = fn; var clockWith2 = clockWith; var logError = /* @__PURE__ */ logWithLevel("Error"); var effectify = (fn, onError, onSyncError) => (...args) => callback2((resume) => { + let synchronous = true; + let pending; try { fn(...args, (err, result) => { - if (err) { - resume(onError ? suspend2(() => fail6(onError(err, args))) : fail6(err)); + const effect = err ? onError ? suspend2(() => fail6(onError(err, args))) : fail6(err) : succeed6(result); + if (synchronous) { + pending ??= effect; } else { - resume(succeed6(result)); + resume(effect); } }); } catch (err) { - resume(onSyncError ? fail6(onSyncError(err, args)) : die3(err)); + pending = onSyncError ? fail6(onSyncError(err, args)) : die3(err); + } + synchronous = false; + if (pending) { + resume(pending); } }); var mapEager2 = mapEager; @@ -4949,7 +4999,7 @@ var defaultLeafHook = (issue) => { } } }; -var defaultCheckHook = (issue) => findMessage(issue.issue) ?? findMessage(issue); +var defaultCheckHook = (issue) => findMessage(issue) ?? findMessage(issue.issue); function formatInput(issue) { return hasInput(issue) ? format(issue.input) : undefined; } @@ -4961,6 +5011,13 @@ function getExpectedMessage(expected, issue) { const input = formatInput(issue); return input === undefined ? `Expected ${expected}` : `Expected ${expected}, got ${input}`; } +function getFilterMessage(issue, checkHook) { + const message = checkHook(issue); + if (message !== undefined || issue.issue._tag !== "InvalidValue") + return message; + const expected = findExpected(issue.issue); + return expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); +} function formatCheck(check) { const expected = check.annotations?.expected; if (typeof expected === "string") @@ -4976,44 +5033,33 @@ function makeFormatterDefault() { return (issue) => formatIssue(issue, ""); } var defaultFormatter = /* @__PURE__ */ makeFormatterDefault(); -function formatIssue(issue, path) { +function formatIssue(issue, path, messageOverride) { let message; switch (issue._tag) { - case "Filter": { - const annotated = defaultCheckHook(issue); - if (annotated !== undefined) { - message = annotated; - } else { - if (issue.issue._tag !== "InvalidValue") { - return formatIssue(issue.issue, path); - } - const expected = findExpected(issue.issue); - message = expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); - } - break; - } + case "Filter": + return formatIssue(issue.issue, path, messageOverride ?? getFilterMessage(issue, defaultCheckHook)); case "Encoding": - return formatIssue(issue.issue, path); + return formatIssue(issue.issue, path, messageOverride); case "Pointer": - return formatIssue(issue.issue, path + formatPath(issue.path)); + return formatIssue(issue.issue, path + formatPath(issue.path), messageOverride); case "Composite": case "AnyOf": { if (issue._tag === "Composite" || issue.issues.length > 0) { - return issue.issues.map((issue) => formatIssue(issue, path)).join(` + return issue.issues.map((issue) => formatIssue(issue, path, messageOverride)).join(` `); } - message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); + message = messageOverride ?? findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); break; } default: - message = defaultLeafHook(issue); + message = messageOverride ?? defaultLeafHook(issue); break; } return path ? `${message} at ${path}` : message; } function findMessage(issue) { - if (issue._tag === "Pointer") + if (issue._tag === "Pointer" || issue._tag === "Composite") return; if (issue._tag === "Encoding") return findMessage(issue.issue); @@ -5216,7 +5262,12 @@ var Declaration = class extends ASTNodeImpl { return (input, options) => { if (input === missing) return missingExit; - return (run ??= this.run(this.typeParameters))(input, this, options); + run ??= this.run(this.typeParameters); + try { + return run(input, this, options); + } catch (error) { + return die3(error); + } }; } _rebuild(recur, checks, encodingChecks, run, encodingRun) { @@ -5329,173 +5380,6 @@ function hasCheck(checks, id) { return checks.some((check) => check.annotations?.representation?.id === id || check._tag === "FilterGroup" && hasCheck(check.checks, id)); } var number2 = /* @__PURE__ */ new Number4; -var Arrays = class extends ASTNodeImpl { - _tag = "Arrays"; - isMutable; - elements; - rest; - encodingChecks; - constructor(isMutable, elements, rest, annotations, checks, encoding, context, encodingChecks) { - super(annotations, checks, encoding, context); - this.isMutable = isMutable; - this.elements = elements; - this.rest = rest; - this.encodingChecks = encodingChecks; - let hasOptional = false; - for (let i = 0;i < elements.length; i++) { - if (isOptional(elements[i])) { - hasOptional = true; - } else if (hasOptional) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - } - if (hasOptional && rest.length > 1) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - for (let i = 1;i < rest.length; i++) { - if (isOptional(rest[i])) { - throw new Error("An optional element cannot follow a rest element. ts(1266)"); - } - } - } - getParser(compile, compileField = compile) { - const ast = this; - let elements; - let rest; - const elementLen = ast.elements.length; - const tailLen = Math.max(0, ast.rest.length - 1); - function getParser(tailThreshold, index) { - if (index < elementLen) { - return elements[index]; - } else if (index >= tailThreshold) { - return rest[index - tailThreshold + 1]; - } - return rest[0]; - } - const finish = (state) => { - const { - input, - len, - options - } = state; - if (ast.rest.length === 0 && len > elementLen) { - for (let i = elementLen;i < len; i++) { - const unexpected = new UnexpectedKey(ast, input[i], options); - const issue = new Pointer([i], unexpected); - if (options.errors === "all") { - if (state.issues) - state.issues.push(issue); - else - state.issues = [issue]; - } else { - return fail6(new Composite(ast, [issue], input, options)); - } - } - } - if (state.issues) { - return fail6(new Composite(ast, state.issues, input, options)); - } - return succeed7(state.output); - }; - const parse = (input, options) => { - const len = input.length; - const state = { - ast, - getParser, - input, - len, - tailThreshold: Math.max(elementLen, len - tailLen), - output: new globalThis.Array(len), - issues: undefined, - options - }; - const end = ast.rest.length === 0 ? elementLen : Math.max(len, elementLen + tailLen); - const concurrency = options.concurrency === undefined ? 1 : resolveConcurrency(options.concurrency); - const eff = concurrency === 1 ? parseArray(state, input, 0, end) : parseArrayConcurrent(state, input, { - concurrency, - end - }); - if (!eff) - return finish(state); - if (effectIsExit(eff)) - return flatMapEager2(eff, () => finish(state)); - let first = true; - return suspend2(() => { - if (!first) - return parse(input, options); - first = false; - return flatMap3(eff, () => finish(state)); - }); - }; - return (input, options) => { - if (input === missing) - return missingExit; - try { - if (!Array.isArray(input)) { - return fail6(new InvalidType(ast, input, options)); - } - if (!elements) { - elements = ast.elements.map((ast) => ({ - ast, - parser: compileField(ast) - })); - rest = ast.rest.map((ast) => ({ - ast, - parser: compileField(ast) - })); - } - return parse(input, options); - } catch (error) { - return die3(error); - } - }; - } - _rebuild(recur, checks, encodingChecks) { - const elements = mapOrSame(this.elements, recur); - const rest = mapOrSame(this.rest, recur); - return elements === this.elements && rest === this.rest && checks === this.checks && encodingChecks === this.encodingChecks ? this : new Arrays(this.isMutable, elements, rest, this.annotations, checks, undefined, this.context, encodingChecks); - } - recur(recur) { - return this._rebuild(recur, this.checks, this.encodingChecks); - } - flip(recur) { - return this._rebuild(recur, this.encodingChecks, this.checks); - } - getExpected() { - return "array"; - } -}; -function stepArray(s, item, exit, i) { - if (exit._tag === "Failure") { - return wrapPropertyKeyIssue(s, s.ast, i, exit); - } - const value = exit === sameExit ? item : exit[args]; - if (value !== missing) { - s.output[i] = value; - } else { - const p = s.getParser(s.tailThreshold, i); - if (isOptional(p.ast)) - return; - const issue = new Pointer([i], new MissingKey(p.ast.context?.annotations)); - if (s.options.errors === "all") { - if (s.issues) - s.issues.push(issue); - else - s.issues = [issue]; - } else { - return fail5(new Composite(s.ast, [issue], s.input, s.options)); - } - } -} -var parseArrayOptions = { - onItem(s, item, i) { - const value = i < s.len ? item : missing; - return s.getParser(s.tailThreshold, i).parser(value, s.options); - }, - step: stepArray -}; -var parseArray = /* @__PURE__ */ iterateEager()(parseArrayOptions); -var parseArrayConcurrent = /* @__PURE__ */ iterateConcurrent()(parseArrayOptions); var wrapPropertyKeyIssue = (s, ast, key, exit) => { if (exit.cause.reasons.length === 0) { return exit; @@ -5514,7 +5398,7 @@ var wrapPropertyKeyIssue = (s, ast, key, exit) => { return fail5(new Composite(ast, [pointer], s.input, s.options)); } }; -var FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?"; +var FINITE_PATTERN = "[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?"; function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) { let stringKeys; let symbolKeys; @@ -5753,9 +5637,15 @@ var Objects = class extends ASTNodeImpl { if (indexCount) return makeFallback(); let fallback; - const resume = (state, index, pending) => { + const resume = (snapshot, index, pending) => { const property = properties[index]; return flatMap3(exit2(pending), (exit) => { + const state = { + ...snapshot, + out: { + ...snapshot.out + } + }; const terminal = stepProperty(state, property, exit); if (terminal) return terminal; @@ -5885,9 +5775,6 @@ function struct(fields, checks, annotations) { function getAST(self) { return self.ast; } -function tuple(elements, checks = undefined) { - return new Arrays(false, elements.map((e) => e.ast), [], undefined, checks); -} function union(members, options, checks) { return new Union(members.map(getAST), options, undefined, checks); } @@ -6680,6 +6567,16 @@ function getConstructorDescriptor(ast) { // node_modules/effect/dist/internal/schema/interpreter.js var flatMapTransformation = (result, current, f) => result === sameExit ? f(current) : flatMapEager2(result, f); function compileTransformation(transformation) { + const apply = compileTransformationUnsafe(transformation); + return (result, current, options) => { + try { + return apply(result, current, options); + } catch (error) { + return die3(error); + } + }; +} +function compileTransformationUnsafe(transformation) { if (transformation._tag === "Middleware") { return (result, current, options) => { const transformed = result === sameExit ? transformation.decode(succeed7(toOption(current)), options) : transformation.decode(mapEager2(result, toOption), options); @@ -6755,53 +6652,57 @@ function compile(ast, compile, compileField, base, specialize) { let encodingParsers; const parseChecks = (input, options) => { let result = parser(input, options); - if (encodingChecks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const output = result === sameExit ? input : result[args]; - if (input !== missing && output !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, input, options)); + try { + if (encodingChecks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const output = result === sameExit ? input : result[args]; + if (input !== missing && output !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + result = fail6(new Composite(ast, issues, input, options)); + } } } - } - } else { - result = flatMap3(result, (value) => { - if (input !== missing && value !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - return fail6(new Composite(ast, issues, input, options)); + } else { + result = flatMap3(result, (value) => { + if (input !== missing && value !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, input, options)); + } } - } - return succeed6(value); - }); - } - } - if (checks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const value = result === sameExit ? input : result[args]; - if (value === missing) - return result; - const issues = collectIssues(checks, value, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, value, options)); - } + return succeed6(value); + }); } - } else { - result = flatMap3(result, (value) => { - if (value !== missing) { + } + if (checks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const value = result === sameExit ? input : result[args]; + if (value === missing) + return result; const issues = collectIssues(checks, value, undefined, ast, options); if (issues) { - return fail6(new Composite(ast, issues, value, options)); + result = fail6(new Composite(ast, issues, value, options)); } } - return succeed6(value); - }); + } else { + result = flatMap3(result, (value) => { + if (value !== missing) { + const issues = collectIssues(checks, value, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, value, options)); + } + } + return succeed6(value); + }); + } } + return result; + } catch (error) { + return die3(error); } - return result; }; const parseLocal = specialize === undefined ? parseChecks : specialize(parseChecks); if (!links) { @@ -7203,21 +7104,6 @@ function makeStruct(ast, fields) { function Struct(fields) { return makeStruct(struct(fields, undefined), fields); } -function makeTuple(ast, elements) { - return make8(ast, { - elements, - mapElements(f, options) { - const elements = f(this.elements); - return makeTuple(tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements); - } - }); -} -function Tuple(elements) { - return makeTuple(tuple(elements), elements); -} -var ArraySchema = /* @__PURE__ */ lambda((schema) => make8(new Arrays(false, [], [schema.ast]), { - value: schema -})); function makeUnion(ast, members) { return make8(ast, { members, @@ -7277,32 +7163,24 @@ function link() { }; } var makeFilter2 = makeFilter; -function isPattern2(regExp, annotations) { - const source = regExp.source; - const flags = regExp.flags; - const canExport = /^[dg]*uy?$/.test(flags); - const runtimeRegExp = flags === "" ? `new RegExp(${format(source)})` : `new RegExp(${format(source)}, ${format(flags)})`; - return isPattern(regExp, { - toJsonSchema: () => canExport ? { - pattern: flags.endsWith("y") ? `^(?:${source})` : source - } : [{}, true], - toCode: () => ({ - runtime: `Schema.isPattern(${runtimeRegExp})` - }), - ...annotations - }); -} function isBase64(annotations) { - const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - return isPattern2(regExp, { + const pattern = "^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"; + const regExp = /^[0-9a-zA-Z+/]*={0,2}$/; + return makeFilter2((s) => s.length % 4 === 0 && regExp.test(s), { expected: "a base64 encoded string", representation: { id: "effect/schema/isBase64", payload: null }, toJsonSchema: () => ({ - pattern: regExp.source + pattern }), + arbitraryConstraint: { + patterns: [{ + source: pattern, + flags: "" + }] + }, toCode: () => ({ runtime: "Schema.isBase64()" }), @@ -7423,47 +7301,6 @@ var File = /* @__PURE__ */ instanceOf(globalThis.File, { }) })) }); -var FormData2 = /* @__PURE__ */ instanceOf(globalThis.FormData, { - representation: { - id: "effect/schema/FormData", - payload: null - }, - toCode: () => ({ - runtime: `Schema.FormData`, - Type: `globalThis.FormData` - }), - expected: "FormData", - toCodecJson: () => link()(ArraySchema(Tuple([String4, Union2([Struct({ - _tag: tag("String"), - value: String4 - }), Struct({ - _tag: tag("File"), - value: File - })])])), transformEffect2({ - decode: (e) => { - const out = new globalThis.FormData; - for (const [key, entry] of e) { - out.append(key, entry.value); - } - return succeed6(out); - }, - encode: (formData) => { - return succeed6(globalThis.Array.from(formData.entries()).map(([key, value]) => { - if (typeof value === "string") { - return [key, { - _tag: "String", - value - }]; - } else { - return [key, { - _tag: "File", - value - }]; - } - })); - } - })) -}); var URLSearchParams2 = /* @__PURE__ */ instanceOf(globalThis.URLSearchParams, { representation: { id: "effect/schema/URLSearchParams", @@ -7579,13 +7416,16 @@ function makeClass(Inherited, identifier, struct2, annotations, proto) { } return out; } -function getClassTransformation(self) { - return new Transformation(transform((input) => new self(input, { +function makeClassTrusted(self, fields) { + return new self(fields, { "~payload": { token: payloadToken, - value: input + value: fields } - })), passthrough()); + }); +} +function getClassTransformation(self) { + return new Transformation(transform((input) => makeClassTrusted(self, input)), passthrough()); } function getClassTypeId(identifier) { return `~effect/Schema/Class/${identifier}`; @@ -8072,14 +7912,11 @@ var toTransform = (channel) => channel.transform; var asyncQueue = (scope, f, options) => make11({ capacity: options?.bufferSize, strategy: options?.strategy -}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope)))); +}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope, { + startImmediately: true +})))); var callbackArray = (f, options) => fromTransform((_, scope) => map5(asyncQueue(scope, f, options), takeAll2)); -var suspend3 = (evaluate) => fromTransform((upstream, scope) => suspend2(() => toTransform(evaluate())(upstream, scope))); var empty3 = /* @__PURE__ */ fromPull(/* @__PURE__ */ succeed6(/* @__PURE__ */ done2())); -var map7 = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => sync3(() => { - let i = 0; - return map5(pull, (o) => f(o, i++)); -}))); var mapDone = /* @__PURE__ */ dual(2, (self, f) => mapDoneEffect(self, (o) => succeed6(f(o)))); var mapDoneEffect = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => succeed6(catchDone(pull, (done) => flatMap3(f(done), done2))))); var merge2 = /* @__PURE__ */ dual((args) => isChannel(args[0]) && isChannel(args[1]), (left, right, options) => fromTransformBracket(fnUntraced2(function* (upstream, _scope, forkedScope) { @@ -8192,6 +8029,18 @@ var splitLines = () => fromTransform((upstream, _scope) => sync3(() => { } return pullOrFlush; })); +var decodeText = (encoding, options) => fromTransform((upstream, _scope) => sync3(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + let pull = upstream.pipe(map5(map2((bytes) => decoder.decode(bytes, streamOptions))), catchDone((leftover) => { + pull = done2(leftover); + const last = decoder.decode(); + return last.length > 0 ? succeed6(of(last)) : pull; + })); + return suspend2(() => pull); +})); var pipeTo = /* @__PURE__ */ dual(2, (self, that) => fromTransform((upstream, scope) => flatMap3(toTransform(self)(upstream, scope), (upstream) => toTransform(that)(upstream, scope)))); var unwrap = (channel) => fromTransform((upstream, scope) => { let pull; @@ -8459,12 +8308,7 @@ var transformPull2 = (self, f) => fromChannel3(fromTransform((_, scope) => flatM var toChannel2 = (stream) => stream.channel; var callback3 = (f, options) => fromChannel3(callbackArray(f, options)); var empty4 = /* @__PURE__ */ fromChannel3(empty3); -var suspend4 = (stream) => fromChannel3(suspend3(() => stream().channel)); var unwrap3 = (effect) => fromChannel3(unwrap(map5(effect, toChannel2))); -var map8 = /* @__PURE__ */ dual(2, (self, f) => suspend4(() => { - let i = 0; - return fromChannel3(map7(self.channel, map2((o) => f(o, i++)))); -})); var merge3 = /* @__PURE__ */ dual((args) => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel3(merge2(toChannel2(self), toChannel2(that), options))); var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (upstream, scope) => sync3(() => { let done; @@ -8486,12 +8330,7 @@ var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (up }); return suspend2(() => done ? done : pull); }))); -var decodeText = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => suspend4(() => { - const decoder = new TextDecoder(options?.encoding); - return map8(self, (chunk) => decoder.decode(chunk, { - stream: true - })); -})); +var decodeText2 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => self.channel.pipe(pipeTo(decodeText(options?.encoding)), fromChannel3)); var splitLines2 = (self) => self.channel.pipe(pipeTo(splitLines()), fromChannel3); var run2 = /* @__PURE__ */ dual(2, (self, sink) => scopedWith2((scope) => toPullScoped(self.channel, scope).pipe(flatMap3((upstream) => sink.transform(upstream, scope)), map5(([a]) => a)))); var runCollect = (self) => runFold(self.channel, () => [], (acc, chunk) => { @@ -8617,10 +8456,14 @@ var ulidString = (timestampMillis, bytes) => { }; // node_modules/effect/dist/internal/uuid.js -var hex = (byte) => byte.toString(16).padStart(2, "0"); +var hex = /* @__PURE__ */ Array.from({ + length: 256 +}, (_, byte) => byte.toString(16).padStart(2, "0")); var stringify = (bytes) => { - const segments = [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)]; - return segments.map((segment) => Array.from(segment, hex).join("")).join("-"); + if (bytes.length < 16) { + return [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)].map((segment) => Array.from(segment, (byte) => hex[byte]).join("")).join("-"); + } + return hex[bytes[0]] + hex[bytes[1]] + hex[bytes[2]] + hex[bytes[3]] + "-" + hex[bytes[4]] + hex[bytes[5]] + "-" + hex[bytes[6]] + hex[bytes[7]] + "-" + hex[bytes[8]] + hex[bytes[9]] + "-" + hex[bytes[10]] + hex[bytes[11]] + hex[bytes[12]] + hex[bytes[13]] + hex[bytes[14]] + hex[bytes[15]]; }; var randomBytes = () => globalThis.crypto.getRandomValues(new Uint8Array(16)); function v4Bytes(bytes = randomBytes()) { @@ -8739,23 +8582,26 @@ var defaultTeardown = (exit, onExit) => { return onExit(getErrorExitCode(squash(exit.cause))); }; var makeRunMain = (f) => dual((args) => isEffect2(args[0]), (effect, options) => { - const fiber = options?.disableErrorReporting === true ? runFork2(effect) : runFork2(tapCause2(effect, (cause) => { + const main = options?.disableErrorReporting === true ? effect : tapCause2(effect, (cause) => { if (hasInterruptsOnly2(cause)) return void_3; const isReported = getErrorReported(squash(cause)); return isReported ? logError(cause) : void_3; - })); - try { - const keepAlive = globalThis.setInterval(constVoid, 2147483647); - fiber.addObserver(() => { - clearInterval(keepAlive); - }); - } catch {} - const teardown = options?.teardown ?? defaultTeardown; - return f({ - fiber, - teardown }); + const teardown = options?.teardown ?? defaultTeardown; + runFork2(withFiber2((fiber) => { + try { + const keepAlive = globalThis.setInterval(constVoid, 2147483647); + fiber.addObserver(() => { + clearInterval(keepAlive); + }); + } catch {} + f({ + fiber, + teardown + }); + return main; + })); }); var errorExitCode = "~effect/Runtime/errorExitCode"; var getErrorExitCode = (u) => { @@ -8860,7 +8706,7 @@ var makeHandle = (params) => Object.setPrototypeOf({ ...params }, HandleProto); var make20 = (spawn) => { - const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); + const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText2(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); const streamLines = (command, options) => splitLines2(streamString(command, options)); return ChildProcessSpawner.of({ spawn, @@ -9029,6 +8875,7 @@ var handleErrnoException = (module, method) => (err, [path]) => { reason = "NotFound"; break; case "EACCES": + case "EPERM": reason = "PermissionDenied"; break; case "EEXIST": @@ -9057,66 +8904,149 @@ var handleErrnoException = (module, method) => (err, [path]) => { }); }; +// node_modules/@effect/platform-node-shared/dist/NodeSink.js +import { finished } from "node:stream"; + +// node_modules/@effect/platform-node-shared/dist/internal/stream.js +var destroyStream = (stream, cleanup, onDestroyed) => { + if (!("closed" in stream)) { + cleanup(); + onDestroyed?.(); + return; + } + const onDone = () => { + clearImmediate(immediate); + stream.off("error", onDone); + stream.off("close", onDone); + onDestroyed?.(); + }; + const onClosed = () => { + if (stream.closed) { + onDone(); + } else { + immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + } + }; + let immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + stream.once("error", onDone); + stream.once("close", onDone); + cleanup(); + if (!stream.closed) { + stream.destroy(); + } +}; + // node_modules/@effect/platform-node-shared/dist/NodeSink.js var fromWritable = (options) => fromChannel2(mapDone(fromWritableChannel(options), (_) => [_])); var fromWritableChannel = (options) => fromTransform((pull) => { const writable = options.evaluate(); - return succeed6(pullIntoWritable({ + const write = pullIntoWritable({ ...options, writable, pull - })); -}); -var pullIntoWritable = (options) => options.pull.pipe(flatMap3((chunk) => { - let i = 0; - return callback2((resume) => { - let cancelled = false; - const loop = () => { - for (;i < chunk.length; ) { - if (cancelled) { - return; - } - const success = options.writable.write(chunk[i++], options.encoding); - if (!success) { - if (!cancelled) { - options.writable.once("drain", loop); + }); + return succeed6(options.endOnDone === false ? write : onError2(write, (cause) => isDoneCause(cause) ? void_3 : releaseWritable(writable))); +}); +var releaseWritable = (writable) => callback2((resume) => { + const onDestroyed = () => resume(void_3); + if (writable.closed) { + const cleanup = finished(writable, { + readable: false + }, () => { + cleanup(); + onDestroyed(); + }); + } else { + destroyStream(writable, constVoid, onDestroyed); + } +}); +var pullIntoWritable = (options) => withFiber2((fiber) => { + const dispatcher = fiber.currentDispatcher; + const completion = makeUnsafe2(); + const failure = makeUnsafe2(); + const onError = (error) => doneUnsafe(failure, failSync2(() => options.onError(error))); + let errorEmitted = false; + const onStreamError = (error) => { + errorEmitted = true; + onError(error); + }; + options.writable.on("error", onStreamError); + const cleanup = finished(options.writable, { + readable: false + }, (error) => { + if (error) { + onError(error); + } else { + doneUnsafe(completion, void_3); + } + }); + return options.pull.pipe(flatMap3((chunk) => { + let i = 0; + return callback2((resume) => { + let cancelled = false; + const onFinish = () => dispatcher.scheduleTask(loop, 0); + const loop = () => { + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + for (;i < chunk.length; ) { + if (cancelled) { + return; + } + const success = options.writable.write(chunk[i++], options.encoding, (error) => { + if (!error) + return; + if (options.writable.closed) { + onError(error); + } else { + dispatcher.scheduleTask(() => onError(error), 0); + } + }); + if (!success) { + if (!cancelled) { + options.writable.once("drain", loop); + options.writable.once("finish", onFinish); + } + return; } - return; } - } - if (!cancelled) { - resume(void_3); - } - }; - loop(); - return sync3(() => { - cancelled = true; - options.writable.off("drain", loop); + if (!cancelled) { + resume(void_3); + } + }; + loop(); + return sync3(() => { + cancelled = true; + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + }); }); - }); -}), forever2({ - disableYield: true -}), options.endOnDone !== false ? catchDone((_) => { - if ("closed" in options.writable && options.writable.closed) { - return done2(_); - } - return callback2((resume) => { - const onFinish = () => resume(done2(_)); - options.writable.once("finish", onFinish); + }), forever2({ + disableYield: true + }), options.endOnDone !== false ? catchDone((_) => { options.writable.end(); - return sync3(() => { - options.writable.off("finish", onFinish); - }); - }); -}) : identity, raceFirst2(callback2((resume) => { - const onError = (error) => resume(fail6(options.onError(error))); - options.writable.once("error", onError); - return sync3(() => { - options.writable.off("error", onError); - }); -}))); + return andThen2(_await(completion), done2(_)); + }) : identity, raceFirst2(_await(failure)), ensuring2(sync3(() => { + cleanup(); + const removeErrorListener = () => { + options.writable.off("error", onStreamError); + options.writable.off("error", removeErrorListener); + options.writable.off("close", removeErrorListener); + }; + if (options.writable.errored && !options.writable.closed && !errorEmitted) { + options.writable.once("error", removeErrorListener); + options.writable.once("close", removeErrorListener); + } else { + removeErrorListener(); + } + }))); +}); // node_modules/@effect/platform-node-shared/dist/NodeStream.js +import { finished as finished2, Readable } from "node:stream"; var fromReadable = (options) => fromChannel3(fromReadableChannel(options)); var fromReadableChannel = (options) => fromTransform((_, scope) => readableToPullUnsafe({ scope, @@ -9133,17 +9063,14 @@ var readableToPullUnsafe = (options) => { function onReadable() { latch.openUnsafe(); } - function onError(error) { - exit.current = fail5(options.onError(error)); - latch.openUnsafe(); - } - function onEnd() { - exit.current = fail5(Done2()); - latch.openUnsafe(); - } readable.on("readable", onReadable); - readable.once("error", onError); - readable.once("end", onEnd); + const cleanup = finished2(readable, { + readable: true, + writable: false + }, (error) => { + exit.current ??= fail5(error ? options.onError(error) : Done2()); + latch.openUnsafe(); + }); const pull = suspend2(function loop() { let item = options.readable.read(options.chunkSize); if (item === null) { @@ -9167,10 +9094,10 @@ var readableToPullUnsafe = (options) => { }); return as2(addFinalizer2(options.scope, sync3(() => { readable.off("readable", onReadable); - readable.off("error", onError); - readable.off("end", onEnd); - if (closeOnDone && "closed" in options.readable && !options.readable.closed) { - options.readable.destroy(); + if (closeOnDone) { + destroyStream(readable, cleanup); + } else { + cleanup(); } })), pull); }; @@ -9495,6 +9422,7 @@ var make22 = /* @__PURE__ */ gen2(function* () { const signalGroup = (signal) => killProcessGroup(command, childProcess, signal).pipe(catch_2(() => killProcess(command, childProcess, signal))); yield* signalGroup(options?.killSignal ?? "SIGTERM"); if (isUndefined(options?.forceKillAfter)) { + yield* _await(exitSignal); yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis); } else { yield* awaitProcessExit(childProcess, exitSignal, toMillis(options.forceKillAfter)); @@ -10088,14 +10016,14 @@ var readLink = /* @__PURE__ */ (() => { return (path) => nodeReadLink(path); })(); var realPath = /* @__PURE__ */ (() => { - const nodeRealPath = /* @__PURE__ */ effectify(NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); + const nodeRealPath = /* @__PURE__ */ effectify(process.platform === "win32" ? NFS.realpath.native : NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); return (path) => nodeRealPath(path); })(); var rename2 = /* @__PURE__ */ (() => { const nodeRename = /* @__PURE__ */ effectify(NFS.rename, /* @__PURE__ */ handleErrnoException("FileSystem", "rename"), /* @__PURE__ */ handleBadArgument("rename")); return (oldPath, newPath) => nodeRename(oldPath, newPath); })(); -var makeFileInfo = (stat) => try_2({ +var makeFileInfo = (stat, method = "stat") => try_2({ try: () => ({ type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown", mtime: fromNullishOr(stat.mtime), @@ -10112,14 +10040,16 @@ var makeFileInfo = (stat) => try_2({ blksize: stat.blksize !== undefined ? some2(bytes(stat.blksize)) : none2(), blocks: fromNullishOr(stat.blocks) }), - catch: handleBadArgument("stat") + catch: handleBadArgument(method) }); -var stat2 = /* @__PURE__ */ (() => { - const nodeStat = /* @__PURE__ */ effectify(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat")); +var statFactory = (method, nodeStatFn) => { + const nodeStat = effectify(nodeStatFn, handleErrnoException("FileSystem", method), handleBadArgument(method)); return (path) => flatMap3(nodeStat(path, { bigint: true - }), makeFileInfo); -})(); + }), (stat) => makeFileInfo(stat, method)); +}; +var stat2 = /* @__PURE__ */ statFactory("stat", NFS.stat); +var lstat2 = /* @__PURE__ */ statFactory("lstat", NFS.lstat); var symlink2 = /* @__PURE__ */ (() => { const nodeSymlink = /* @__PURE__ */ effectify(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink")); return (target, path) => nodeSymlink(target, path); @@ -10202,6 +10132,7 @@ var makeFileSystem = /* @__PURE__ */ map5(/* @__PURE__ */ serviceOption2(WatchBa copyFile: copyFile2, glob: glob2, link: link3, + lstat: lstat2, makeDirectory, makeTempDirectory, makeTempDirectoryScoped, @@ -10341,9 +10272,6 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readline.emitKeypressEvents(stdin, rl); rl.on("line", onLine); rl.once("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(true); - } return { rl, onClose, @@ -10357,9 +10285,6 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readlineActive = false; rl.off("line", onLine); rl.off("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(false); - } rl.close(); if (inputEnded) { endUnsafe(lines); @@ -10367,6 +10292,14 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu })), idleTimeToLive: "10 millis" }); + const setRawMode = (enabled) => sync3(() => { + if (stdin.isTTY) + stdin.setRawMode(enabled); + }); + const rawModeRef = yield* make13({ + acquire: acquireRelease2(setRawMode(true), () => setRawMode(false)), + idleTimeToLive: "10 millis" + }); const columns = sync3(() => stdout.columns ?? 0); const rows = sync3(() => stdout.rows ?? 0); const readInput = gen2(function* () { @@ -10401,6 +10334,7 @@ var make24 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu handleEnd(); } else { yield* get3(rlRef); + yield* get3(rawModeRef); stdin.once("end", handleEnd); } return queue; @@ -10519,7 +10453,7 @@ class CommandError extends TaggedError3()("CommandError", { }) { } var error = (command, cause) => new CommandError({ command, exitCode: -1, stderr: String(cause) }); -var collectText = (stream) => stream.pipe(decodeText(), runFold2(() => "", (all, chunk) => all + chunk)); +var collectText = (stream) => stream.pipe(decodeText2(), runFold2(() => "", (all, chunk) => all + chunk)); var retainedStderrLength = 16 * 1024; class Service3 extends Service()("@timmo001/workflows/CommandExecutor") { @@ -10572,8 +10506,8 @@ var layer14 = effect(Service3, gen2(function* () { stdin: "inherit" })); let stderrTail = ""; - const stdout = handle.stdout.pipe(decodeText(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); - const stderr = handle.stderr.pipe(decodeText(), runForEach2((chunk) => sync3(() => { + const stdout = handle.stdout.pipe(decodeText2(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); + const stderr = handle.stderr.pipe(decodeText2(), runForEach2((chunk) => sync3(() => { process.stderr.write(chunk); stderrTail = `${stderrTail}${chunk}`.slice(-retainedStderrLength); }))); diff --git a/.github/actions/validate-json/dist/index.js b/.github/actions/validate-json/dist/index.js index f3f6f530..99d03731 100644 --- a/.github/actions/validate-json/dist/index.js +++ b/.github/actions/validate-json/dist/index.js @@ -769,6 +769,10 @@ function assignProperty(self, key, value) { } } function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } for (const key of Reflect.ownKeys(source)) { if (Object.prototype.propertyIsEnumerable.call(source, key)) { assignProperty(self, key, source[key]); @@ -859,7 +863,7 @@ class CauseImpl { toJSON() { return { _id: "Cause", - failures: this.reasons.map((f) => f.toJSON()) + reasons: this.reasons.map((f) => f.toJSON()) }; } toString() { @@ -1610,9 +1614,21 @@ var bigint2 = /* @__PURE__ */ BigInt(2); var bigint10 = /* @__PURE__ */ BigInt(10); var bigint1e3 = /* @__PURE__ */ BigInt(1000); var bigint1e6 = /* @__PURE__ */ BigInt(1e6); +var bigint1e9 = /* @__PURE__ */ BigInt(1e9); +var bigintNanosPerMinute = /* @__PURE__ */ BigInt(60000000000); +var bigintNanosPerHour = /* @__PURE__ */ BigInt(3600000000000); +var bigintNanosPerDay = /* @__PURE__ */ BigInt(86400000000000); +var bigintNanosPerWeek = /* @__PURE__ */ BigInt(604800000000000); var roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input))); var roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6); var fromNanosNumber = (nanos) => make3(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos); +var nanosToUnit = (nanos, divisor) => { + const value = Number(nanos); + if (Number.isFinite(value)) + return value / divisor; + const scale = BigInt(divisor); + return Number(nanos / scale) + Number(nanos % scale) / divisor; +}; var parseNanos = (input, scale) => { const decimalIndex = input.indexOf("."); if (decimalIndex === -1) @@ -1628,6 +1644,13 @@ var divideTiesAwayFromZero = (numerator, denominator) => { const rounded = absolute / denominator + (absolute % denominator * bigint2 >= denominator ? bigint1 : bigint0); return numerator < bigint0 ? -rounded : rounded; }; +var fromMillisString = (input, scale) => { + const millis = Number(input) * scale; + if (!Number.isFinite(millis)) + return make3(millis); + const nanos = parseNanos(input, BigInt(scale) * bigint1e6); + return make3(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos); +}; var DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; var fromInputUnsafe = (input) => { switch (typeof input) { @@ -1652,26 +1675,25 @@ var fromInputUnsafe = (input) => { if (unit === "micro" || unit === "micros") { return nanos(parseNanos(valueStr, bigint1e3)); } - const value = Number(valueStr); switch (unit) { case "milli": case "millis": - return millis(value); + return fromMillisString(valueStr, 1); case "second": case "seconds": - return seconds(value); + return fromMillisString(valueStr, 1000); case "minute": case "minutes": - return minutes(value); + return fromMillisString(valueStr, 60000); case "hour": case "hours": - return hours(value); + return fromMillisString(valueStr, 3600000); case "day": case "days": - return days(value); + return fromMillisString(valueStr, 86400000); case "week": case "weeks": - return weeks(value); + return fromMillisString(valueStr, 604800000); } break; } @@ -1693,7 +1715,8 @@ var fromInputUnsafe = (input) => { if (input[0] === Infinity || input[1] === Infinity) { return infinity; } - return fromNanosNumber(input[0] * 1e9 + input[1]); + const nanos = input[0] * 1e9 + input[1]; + return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make3(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos); } const obj = input; let millis = 0; @@ -1709,13 +1732,42 @@ var fromInputUnsafe = (input) => { millis += obj.seconds * 1000; if (obj.milliseconds) millis += obj.milliseconds; - if (!obj.microseconds && !obj.nanoseconds) - return make3(millis); - return fromNanosNumber(millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0)); + if (!obj.microseconds && !obj.nanoseconds) { + if (!Number.isFinite(millis)) + return make3(millis); + const exact = sumObjectNanos(obj); + return exact === undefined || BigInt(millis) * bigint1e6 === exact ? make3(millis) : make3(exact); + } + const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0); + const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : undefined; + return exact === undefined ? fromNanosNumber(nanos) : make3(exact); } } return invalid(input); }; +var isIntegerOrUnset = (n) => !n || Number.isInteger(n); +var sumObjectNanos = (obj) => { + if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds)) + return; + let nanos = bigint0; + if (obj.weeks) + nanos += BigInt(obj.weeks) * bigintNanosPerWeek; + if (obj.days) + nanos += BigInt(obj.days) * bigintNanosPerDay; + if (obj.hours) + nanos += BigInt(obj.hours) * bigintNanosPerHour; + if (obj.minutes) + nanos += BigInt(obj.minutes) * bigintNanosPerMinute; + if (obj.seconds) + nanos += BigInt(obj.seconds) * bigint1e9; + if (obj.milliseconds) + nanos += BigInt(obj.milliseconds) * bigint1e6; + if (obj.microseconds) + nanos += BigInt(obj.microseconds) * bigint1e3; + if (obj.nanoseconds) + nanos += BigInt(obj.nanoseconds); + return nanos; +}; var invalid = (input) => { throw new Error(`Invalid Input: ${input}`); }; @@ -1824,14 +1876,9 @@ var infinity = /* @__PURE__ */ make3(Infinity); var negativeInfinity = /* @__PURE__ */ make3(-Infinity); var nanos = (nanos) => make3(nanos); var millis = (millis) => make3(millis); -var seconds = (seconds) => make3(seconds * 1000); -var minutes = (minutes) => make3(minutes * 60000); -var hours = (hours) => make3(hours * 3600000); -var days = (days) => make3(days * 86400000); -var weeks = (weeks) => make3(weeks * 604800000); var toMillis = (self) => match3(fromInputUnsafe(self), { onMillis: identity, - onNanos: (nanos) => Number(nanos) / 1e6, + onNanos: (nanos) => nanosToUnit(nanos, 1e6), onInfinity: () => Infinity, onNegativeInfinity: () => -Infinity }); @@ -1897,7 +1944,7 @@ var setTimer = "setImmediate" in globalThis ? (f) => { const timer = setTimeout(f, 0); return () => clearTimeout(timer); }; -var setImmediate = (f) => { +var setImmediate2 = (f) => { try { return setTimer(f); } catch { @@ -1937,7 +1984,7 @@ class MixedScheduler { setImmediate; constructor(executionMode = "async", setImmediateFn) { this.executionMode = executionMode; - this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate2); } shouldYield(fiber) { return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; @@ -1951,7 +1998,7 @@ class MixedSchedulerDispatcher { tasks = /* @__PURE__ */ new PriorityBuckets; running = undefined; setImmediate; - constructor(setImmediateFn = setImmediate) { + constructor(setImmediateFn = setImmediate2) { this.setImmediate = setImmediateFn; } scheduleTask(task, priority) { @@ -2219,10 +2266,7 @@ class Interrupt extends ReasonBase { } } var causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); -var findFail = (self) => { - const reason = self.reasons.find(isFailReason); - return reason ? succeed2(reason) : fail2(self); -}; +var hasFails = (self) => self.reasons.some(isFailReason); var findError = (self) => { for (let i = 0;i < self.reasons.length; i++) { const reason = self.reasons[i]; @@ -2232,6 +2276,9 @@ var findError = (self) => { } return fail2(self); }; +var hasDies = (self) => self.reasons.some(isDieReason); +var causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +var findRecoverableError = (self) => hasDies(self) ? fail2(causeElectDefects(self)) : findError(self); var hasInterrupts = (self) => self.reasons.some(isInterruptReason); var hasInterruptsOnly = (self) => self.reasons.length > 0 && self.reasons.every(isInterruptReason); var causeMap = /* @__PURE__ */ dual(2, (self, f) => { @@ -2292,12 +2339,14 @@ var causePrettyErrors = (self, options) => { } return errors; }; -var causePrettyError = (original, annotations, options) => { +var causePrettyError = (original, annotations, options, seen = new Set) => { const kind = typeof original; let error; if (original && kind === "object") { + seen.add(original); + const cause = original.cause; error = new globalThis.Error(causePrettyMessage(original), { - cause: original.cause ? causePrettyError(original.cause) : undefined + cause: cause !== undefined && !seen.has(cause) ? causePrettyError(cause, undefined, undefined, seen) : undefined }); if (typeof original.name === "string") { error.name = original.name; @@ -2508,7 +2557,11 @@ class FiberImpl { } else if (this._asyncContext !== undefined) { const asyncContext = this._asyncContext; this._asyncContext = undefined; - return asyncContext.runInAsyncScope(this.evaluate, this, effect); + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } } else if (this._yielded !== undefined) { const yielded = this._yielded; this._yielded = undefined; @@ -2806,7 +2859,6 @@ var tryPromise = (options) => { } }, f.length !== 0); }; -var withFiberId = (f) => withFiber((fiber) => f(fiber.id)); var callbackOptions = /* @__PURE__ */ function() { const Proto = /* @__PURE__ */ makePrimitiveProto({ op: "Async", @@ -2827,9 +2879,9 @@ var callbackOptions = /* @__PURE__ */ function() { if (yielded !== false) return yielded; yielded = true; - fiber._yielded = () => { + fiber.yieldWith(() => { resumed = true; - }; + }); if (controller === undefined && onCancel === undefined) { return Yield; } @@ -3112,10 +3164,7 @@ var exitMap = /* @__PURE__ */ dual(2, (self, f) => self._tag === "Success" ? exi var exitMapError = /* @__PURE__ */ dual(2, (self, f) => { if (self._tag === "Success") return self; - const error = findError(self.cause); - if (isFailure2(error)) - return self; - return exitFail(f(error.success)); + return exitFailCause(causeMap(self.cause, f)); }); var exitZipRight = /* @__PURE__ */ dual(2, (self, that) => exitIsSuccess(self) ? that : self); var exitAsVoidAll = (exits) => { @@ -3179,10 +3228,10 @@ var catchCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(s const eb = filter(cause); return isFailure2(eb) ? failCause(eb.failure) : f(eb.success, cause); })); -var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findError, (e) => f(e))); +var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findRecoverableError, (e) => f(e))); var tapCause = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => andThen(f(cause), failCause(cause)))); var catchIf = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, predicate, f, orElse) => catchCause(self, (cause) => { - const error = findError(cause); + const error = findRecoverableError(cause); if (isFailure2(error)) return failCause(error.failure); if (!predicate(error.success)) { @@ -3194,7 +3243,7 @@ var catchTag = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, k, f, or const pred = Array.isArray(k) ? (e) => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); return catchIf(self, pred, f, orElse); }); -var mapError = /* @__PURE__ */ dual(2, (self, f) => catch_(self, (error) => failSync(() => f(error)))); +var mapError = /* @__PURE__ */ dual(2, (self, f) => catchCause(self, (cause) => failCause(causeMap(cause, f)))); var orDie = (self) => catch_(self, die); var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => { if (!options?.log) { @@ -3206,8 +3255,8 @@ var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) = const logEffect = logWithLevel(options.log === true ? undefined : options.log); return matchCauseEffect(self, { onFailure(cause) { - const failure = findFail(cause); - return isFailure2(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); }, onSuccess: (_) => void_ }); @@ -3246,16 +3295,16 @@ var makeMatch = (op, onFailure) => { return MatchImpl; }; var MatchImpl = /* @__PURE__ */ makeMatch("Match", function(cause, fiber) { - const fail = cause.reasons.find(isFailReason); - if (fail === undefined) - return failCause(cause); + const error = findRecoverableError(cause); + if (isFailure2(error)) + return failCause(error.failure); const handlers = this.payload; - return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(fail.error) : internalCall(() => handlers.onFailure(fail.error))); + return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))); }); var matchEffect = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, { onFailure: (cause) => { - const fail = cause.reasons.find(isFailReason); - return fail ? options.onFailure(fail.error) : failCause(cause); + const error = findRecoverableError(cause); + return isFailure2(error) ? failCause(error.failure) : options.onFailure(error.success); }, onSuccess: options.onSuccess })); @@ -3264,9 +3313,9 @@ var matchEager = /* @__PURE__ */ dual(2, (self, options) => { if (effectIsExit(self)) { if (self._tag === "Success") return exitSucceed(options.onSuccess(self.value)); - const error = findError(self.cause); + const error = findRecoverableError(self.cause); if (isFailure2(error)) - return self; + return exitFailCause(error.failure); return exitSucceed(options.onFailure(error.success)); } return match4(self, options); @@ -3321,17 +3370,17 @@ var runFinalizer = (finalizer, exit_) => { return exitDie(defect); } }; -var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeCombine(exit_.cause, cause))); +var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); var scopeCloseFinalizers = /* @__PURE__ */ fnUntraced(function* (self, finalizers, exit_) { let exits = []; const fibers = []; - const arr = Array.from(finalizers.values()); + const arr = Array.from(finalizers); const parent = getCurrentFiber(); for (let i = arr.length - 1;i >= 0; i--) { - const finalizer = arr[i]; + const [key, finalizer] = arr[i]; if (self.strategy === "sequential") { exits.push(yield* exit(runFinalizer(finalizer, exit_))); - } else { + } else if (key !== parent) { fibers.push(forkUnsafe(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); } } @@ -3524,15 +3573,9 @@ var all = (arg, options) => { } else if (options?.discard) { return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options); } - return suspend(() => { - const out = {}; - return as(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => { - assignProperty(out, key, value); - }), { - discard: true, - concurrency: options?.concurrency - }), out); - }); + return suspend(() => map3(forEach(Object.entries(arg), ([key, effect]) => map3(options?.mode === "result" ? result(effect) : effect, (value) => [key, value]), { + concurrency: options?.concurrency + }), Object.fromEntries)); }; var whileLoop = /* @__PURE__ */ makePrimitive({ op: "While", @@ -3671,7 +3714,7 @@ var iterateConcurrentImpl = (options) => { const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); if (reasons.length > 0) { const cause = causeFromReasons(reasons); - terminal = exitFailCause(terminal._tag === "Failure" ? causeCombine(terminal.cause, cause) : cause); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); } } } else { @@ -3749,14 +3792,13 @@ var forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterrupt } return child; }; +var fiberScopeFinalizer = (fiber) => () => withFiber((current) => current === fiber ? void_ : fiberInterrupt(fiber)); var forkIn = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, scope, options) => withFiber((parent) => { - const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + const fiber = scope.state._tag === "Closed" ? new FiberImpl(parent.context) : forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); if (!fiber._exit) { if (scope.state._tag !== "Closed") { - const key = {}; - const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); - scopeAddFinalizerUnsafe(scope, key, finalizer); - fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + scopeAddFinalizerUnsafe(scope, fiber, fiberScopeFinalizer(fiber)); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, fiber)); } else { fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); } @@ -3793,7 +3835,7 @@ var fiberRunIn = /* @__PURE__ */ dual(2, (self, scope) => { return self; } scopeRemoveFinalizerUnsafe(scope, self); - scopeAddFinalizerUnsafe(scope, self, () => fiberInterrupt(self)); + scopeAddFinalizerUnsafe(scope, self, fiberScopeFinalizer(self)); self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, self)); return self; }); @@ -4432,8 +4474,8 @@ var mergeAllEffect = (layers, memoMap, scope) => { concurrency: layers.length }).pipe(map3((context) => mergeAll(...context))); }; -var mergeAll2 = (...layers) => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); -var provideWith = (self, that, f) => fromBuild((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); +var mergeAll2 = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +var provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap2(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map3((merged) => f(merged, context))))); var provide2 = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, identity)); var provideMerge = /* @__PURE__ */ dual(2, (self, that) => provideWith(self, that, (self, that) => merge(that, self))); @@ -4504,6 +4546,7 @@ var void_3 = void_; var callback2 = callback; var gen2 = gen; var fail6 = fail3; +var failSync2 = failSync; var failCause3 = failCause; var failCauseSync2 = failCauseSync; var die3 = die; @@ -4553,16 +4596,23 @@ var fn2 = fn; var clockWith2 = clockWith; var logError = /* @__PURE__ */ logWithLevel("Error"); var effectify = (fn, onError, onSyncError) => (...args) => callback2((resume) => { + let synchronous = true; + let pending; try { fn(...args, (err, result) => { - if (err) { - resume(onError ? suspend2(() => fail6(onError(err, args))) : fail6(err)); + const effect = err ? onError ? suspend2(() => fail6(onError(err, args))) : fail6(err) : succeed6(result); + if (synchronous) { + pending ??= effect; } else { - resume(succeed6(result)); + resume(effect); } }); } catch (err) { - resume(onSyncError ? fail6(onSyncError(err, args)) : die3(err)); + pending = onSyncError ? fail6(onSyncError(err, args)) : die3(err); + } + synchronous = false; + if (pending) { + resume(pending); } }); var mapEager2 = mapEager; @@ -4579,23 +4629,26 @@ var defaultTeardown = (exit, onExit) => { return onExit(getErrorExitCode(squash(exit.cause))); }; var makeRunMain = (f) => dual((args) => isEffect2(args[0]), (effect, options) => { - const fiber = options?.disableErrorReporting === true ? runFork2(effect) : runFork2(tapCause2(effect, (cause) => { + const main = options?.disableErrorReporting === true ? effect : tapCause2(effect, (cause) => { if (hasInterruptsOnly2(cause)) return void_3; const isReported = getErrorReported(squash(cause)); return isReported ? logError(cause) : void_3; - })); - try { - const keepAlive = globalThis.setInterval(constVoid, 2147483647); - fiber.addObserver(() => { - clearInterval(keepAlive); - }); - } catch {} - const teardown = options?.teardown ?? defaultTeardown; - return f({ - fiber, - teardown }); + const teardown = options?.teardown ?? defaultTeardown; + runFork2(withFiber2((fiber) => { + try { + const keepAlive = globalThis.setInterval(constVoid, 2147483647); + fiber.addObserver(() => { + clearInterval(keepAlive); + }); + } catch {} + f({ + fiber, + teardown + }); + return main; + })); }); var errorExitCode = "~effect/Runtime/errorExitCode"; var getErrorExitCode = (u) => { @@ -5240,14 +5293,11 @@ var toTransform = (channel) => channel.transform; var asyncQueue = (scope, f, options) => make8({ capacity: options?.bufferSize, strategy: options?.strategy -}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope)))); +}).pipe(tap2((queue) => addFinalizer2(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause4(queue, cause)), forkIn2(scope, { + startImmediately: true +})))); var callbackArray = (f, options) => fromTransform((_, scope) => map5(asyncQueue(scope, f, options), takeAll2)); -var suspend3 = (evaluate) => fromTransform((upstream, scope) => suspend2(() => toTransform(evaluate())(upstream, scope))); var empty3 = /* @__PURE__ */ fromPull(/* @__PURE__ */ succeed6(/* @__PURE__ */ done2())); -var map6 = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => sync3(() => { - let i = 0; - return map5(pull, (o) => f(o, i++)); -}))); var mapDone = /* @__PURE__ */ dual(2, (self, f) => mapDoneEffect(self, (o) => succeed6(f(o)))); var mapDoneEffect = /* @__PURE__ */ dual(2, (self, f) => transformPull(self, (pull) => succeed6(catchDone(pull, (done) => flatMap3(f(done), done2))))); var merge2 = /* @__PURE__ */ dual((args) => isChannel(args[0]) && isChannel(args[1]), (left, right, options) => fromTransformBracket(fnUntraced2(function* (upstream, _scope, forkedScope) { @@ -5360,6 +5410,18 @@ var splitLines = () => fromTransform((upstream, _scope) => sync3(() => { } return pullOrFlush; })); +var decodeText = (encoding, options) => fromTransform((upstream, _scope) => sync3(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + let pull = upstream.pipe(map5(map2((bytes) => decoder.decode(bytes, streamOptions))), catchDone((leftover) => { + pull = done2(leftover); + const last = decoder.decode(); + return last.length > 0 ? succeed6(of(last)) : pull; + })); + return suspend2(() => pull); +})); var pipeTo = /* @__PURE__ */ dual(2, (self, that) => fromTransform((upstream, scope) => flatMap3(toTransform(self)(upstream, scope), (upstream) => toTransform(that)(upstream, scope)))); var unwrap = (channel) => fromTransform((upstream, scope) => { let pull; @@ -5592,12 +5654,7 @@ var transformPull2 = (self, f) => fromChannel3(fromTransform((_, scope) => flatM var toChannel2 = (stream) => stream.channel; var callback3 = (f, options) => fromChannel3(callbackArray(f, options)); var empty4 = /* @__PURE__ */ fromChannel3(empty3); -var suspend4 = (stream) => fromChannel3(suspend3(() => stream().channel)); var unwrap3 = (effect) => fromChannel3(unwrap(map5(effect, toChannel2))); -var map7 = /* @__PURE__ */ dual(2, (self, f) => suspend4(() => { - let i = 0; - return fromChannel3(map6(self.channel, map2((o) => f(o, i++)))); -})); var merge3 = /* @__PURE__ */ dual((args) => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel3(merge2(toChannel2(self), toChannel2(that), options))); var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (upstream, scope) => sync3(() => { let done; @@ -5619,12 +5676,7 @@ var transduce = /* @__PURE__ */ dual(2, (self, sink) => transformPull2(self, (up }); return suspend2(() => done ? done : pull); }))); -var decodeText = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => suspend4(() => { - const decoder = new TextDecoder(options?.encoding); - return map7(self, (chunk) => decoder.decode(chunk, { - stream: true - })); -})); +var decodeText2 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, options) => self.channel.pipe(pipeTo(decodeText(options?.encoding)), fromChannel3)); var splitLines2 = (self) => self.channel.pipe(pipeTo(splitLines()), fromChannel3); var run = /* @__PURE__ */ dual(2, (self, sink) => scopedWith2((scope) => toPullScoped(self.channel, scope).pipe(flatMap3((upstream) => sink.transform(upstream, scope)), map5(([a]) => a)))); var runCollect = (self) => runFold(self.channel, () => [], (acc, chunk) => { @@ -5915,7 +5967,7 @@ var defaultLeafHook = (issue) => { } } }; -var defaultCheckHook = (issue) => findMessage(issue.issue) ?? findMessage(issue); +var defaultCheckHook = (issue) => findMessage(issue) ?? findMessage(issue.issue); function formatInput(issue) { return hasInput(issue) ? format(issue.input) : undefined; } @@ -5927,6 +5979,13 @@ function getExpectedMessage(expected, issue) { const input = formatInput(issue); return input === undefined ? `Expected ${expected}` : `Expected ${expected}, got ${input}`; } +function getFilterMessage(issue, checkHook) { + const message = checkHook(issue); + if (message !== undefined || issue.issue._tag !== "InvalidValue") + return message; + const expected = findExpected(issue.issue); + return expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); +} function formatCheck(check) { const expected = check.annotations?.expected; if (typeof expected === "string") @@ -5942,44 +6001,33 @@ function makeFormatterDefault() { return (issue) => formatIssue(issue, ""); } var defaultFormatter = /* @__PURE__ */ makeFormatterDefault(); -function formatIssue(issue, path) { +function formatIssue(issue, path, messageOverride) { let message; switch (issue._tag) { - case "Filter": { - const annotated = defaultCheckHook(issue); - if (annotated !== undefined) { - message = annotated; - } else { - if (issue.issue._tag !== "InvalidValue") { - return formatIssue(issue.issue, path); - } - const expected = findExpected(issue.issue); - message = expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue); - } - break; - } + case "Filter": + return formatIssue(issue.issue, path, messageOverride ?? getFilterMessage(issue, defaultCheckHook)); case "Encoding": - return formatIssue(issue.issue, path); + return formatIssue(issue.issue, path, messageOverride); case "Pointer": - return formatIssue(issue.issue, path + formatPath(issue.path)); + return formatIssue(issue.issue, path + formatPath(issue.path), messageOverride); case "Composite": case "AnyOf": { if (issue._tag === "Composite" || issue.issues.length > 0) { - return issue.issues.map((issue) => formatIssue(issue, path)).join(` + return issue.issues.map((issue) => formatIssue(issue, path, messageOverride)).join(` `); } - message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); + message = messageOverride ?? findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue); break; } default: - message = defaultLeafHook(issue); + message = messageOverride ?? defaultLeafHook(issue); break; } return path ? `${message} at ${path}` : message; } function findMessage(issue) { - if (issue._tag === "Pointer") + if (issue._tag === "Pointer" || issue._tag === "Composite") return; if (issue._tag === "Encoding") return findMessage(issue.issue); @@ -6260,7 +6308,12 @@ var Declaration = class extends ASTNodeImpl { return (input, options) => { if (input === missing) return missingExit; - return (run ??= this.run(this.typeParameters))(input, this, options); + run ??= this.run(this.typeParameters); + try { + return run(input, this, options); + } catch (error) { + return die3(error); + } }; } _rebuild(recur, checks, encodingChecks, run, encodingRun) { @@ -6373,173 +6426,6 @@ function hasCheck(checks, id) { return checks.some((check) => check.annotations?.representation?.id === id || check._tag === "FilterGroup" && hasCheck(check.checks, id)); } var number2 = /* @__PURE__ */ new Number4; -var Arrays = class extends ASTNodeImpl { - _tag = "Arrays"; - isMutable; - elements; - rest; - encodingChecks; - constructor(isMutable, elements, rest, annotations, checks, encoding, context, encodingChecks) { - super(annotations, checks, encoding, context); - this.isMutable = isMutable; - this.elements = elements; - this.rest = rest; - this.encodingChecks = encodingChecks; - let hasOptional = false; - for (let i = 0;i < elements.length; i++) { - if (isOptional(elements[i])) { - hasOptional = true; - } else if (hasOptional) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - } - if (hasOptional && rest.length > 1) { - throw new Error("A required element cannot follow an optional element. ts(1257)"); - } - for (let i = 1;i < rest.length; i++) { - if (isOptional(rest[i])) { - throw new Error("An optional element cannot follow a rest element. ts(1266)"); - } - } - } - getParser(compile, compileField = compile) { - const ast = this; - let elements; - let rest; - const elementLen = ast.elements.length; - const tailLen = Math.max(0, ast.rest.length - 1); - function getParser(tailThreshold, index) { - if (index < elementLen) { - return elements[index]; - } else if (index >= tailThreshold) { - return rest[index - tailThreshold + 1]; - } - return rest[0]; - } - const finish = (state) => { - const { - input, - len, - options - } = state; - if (ast.rest.length === 0 && len > elementLen) { - for (let i = elementLen;i < len; i++) { - const unexpected = new UnexpectedKey(ast, input[i], options); - const issue = new Pointer([i], unexpected); - if (options.errors === "all") { - if (state.issues) - state.issues.push(issue); - else - state.issues = [issue]; - } else { - return fail6(new Composite(ast, [issue], input, options)); - } - } - } - if (state.issues) { - return fail6(new Composite(ast, state.issues, input, options)); - } - return succeed8(state.output); - }; - const parse = (input, options) => { - const len = input.length; - const state = { - ast, - getParser, - input, - len, - tailThreshold: Math.max(elementLen, len - tailLen), - output: new globalThis.Array(len), - issues: undefined, - options - }; - const end = ast.rest.length === 0 ? elementLen : Math.max(len, elementLen + tailLen); - const concurrency = options.concurrency === undefined ? 1 : resolveConcurrency(options.concurrency); - const eff = concurrency === 1 ? parseArray(state, input, 0, end) : parseArrayConcurrent(state, input, { - concurrency, - end - }); - if (!eff) - return finish(state); - if (effectIsExit(eff)) - return flatMapEager2(eff, () => finish(state)); - let first = true; - return suspend2(() => { - if (!first) - return parse(input, options); - first = false; - return flatMap3(eff, () => finish(state)); - }); - }; - return (input, options) => { - if (input === missing) - return missingExit; - try { - if (!Array.isArray(input)) { - return fail6(new InvalidType(ast, input, options)); - } - if (!elements) { - elements = ast.elements.map((ast) => ({ - ast, - parser: compileField(ast) - })); - rest = ast.rest.map((ast) => ({ - ast, - parser: compileField(ast) - })); - } - return parse(input, options); - } catch (error) { - return die3(error); - } - }; - } - _rebuild(recur, checks, encodingChecks) { - const elements = mapOrSame(this.elements, recur); - const rest = mapOrSame(this.rest, recur); - return elements === this.elements && rest === this.rest && checks === this.checks && encodingChecks === this.encodingChecks ? this : new Arrays(this.isMutable, elements, rest, this.annotations, checks, undefined, this.context, encodingChecks); - } - recur(recur) { - return this._rebuild(recur, this.checks, this.encodingChecks); - } - flip(recur) { - return this._rebuild(recur, this.encodingChecks, this.checks); - } - getExpected() { - return "array"; - } -}; -function stepArray(s, item, exit, i) { - if (exit._tag === "Failure") { - return wrapPropertyKeyIssue(s, s.ast, i, exit); - } - const value = exit === sameExit ? item : exit[args]; - if (value !== missing) { - s.output[i] = value; - } else { - const p = s.getParser(s.tailThreshold, i); - if (isOptional(p.ast)) - return; - const issue = new Pointer([i], new MissingKey(p.ast.context?.annotations)); - if (s.options.errors === "all") { - if (s.issues) - s.issues.push(issue); - else - s.issues = [issue]; - } else { - return fail5(new Composite(s.ast, [issue], s.input, s.options)); - } - } -} -var parseArrayOptions = { - onItem(s, item, i) { - const value = i < s.len ? item : missing; - return s.getParser(s.tailThreshold, i).parser(value, s.options); - }, - step: stepArray -}; -var parseArray = /* @__PURE__ */ iterateEager()(parseArrayOptions); -var parseArrayConcurrent = /* @__PURE__ */ iterateConcurrent()(parseArrayOptions); var wrapPropertyKeyIssue = (s, ast, key, exit) => { if (exit.cause.reasons.length === 0) { return exit; @@ -6558,7 +6444,7 @@ var wrapPropertyKeyIssue = (s, ast, key, exit) => { return fail5(new Composite(ast, [pointer], s.input, s.options)); } }; -var FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?"; +var FINITE_PATTERN = "[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?"; function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) { let stringKeys; let symbolKeys; @@ -6797,9 +6683,15 @@ var Objects = class extends ASTNodeImpl { if (indexCount) return makeFallback(); let fallback; - const resume = (state, index, pending) => { + const resume = (snapshot, index, pending) => { const property = properties[index]; return flatMap3(exit2(pending), (exit) => { + const state = { + ...snapshot, + out: { + ...snapshot.out + } + }; const terminal = stepProperty(state, property, exit); if (terminal) return terminal; @@ -6929,12 +6821,6 @@ function struct(fields, checks, annotations) { function getAST(self) { return self.ast; } -function tuple(elements, checks = undefined) { - return new Arrays(false, elements.map((e) => e.ast), [], undefined, checks); -} -function union(members, options, checks) { - return new Union(members.map(getAST), options, undefined, checks); -} var toCandidate = /* @__PURE__ */ memoizeIdempotent((ast) => { while (true) { if (isSuspend(ast)) @@ -7748,7 +7634,7 @@ var makeHandle = (params) => Object.setPrototypeOf({ ...params }, HandleProto); var make13 = (spawn) => { - const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); + const streamString = (command, options) => spawn(command).pipe(map5((handle) => decodeText2(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap3); const streamLines = (command, options) => splitLines2(streamString(command, options)); return ChildProcessSpawner.of({ spawn, @@ -7917,6 +7803,7 @@ var handleErrnoException = (module, method) => (err, [path]) => { reason = "NotFound"; break; case "EACCES": + case "EPERM": reason = "PermissionDenied"; break; case "EEXIST": @@ -7945,66 +7832,149 @@ var handleErrnoException = (module, method) => (err, [path]) => { }); }; +// node_modules/@effect/platform-node-shared/dist/NodeSink.js +import { finished } from "node:stream"; + +// node_modules/@effect/platform-node-shared/dist/internal/stream.js +var destroyStream = (stream, cleanup, onDestroyed) => { + if (!("closed" in stream)) { + cleanup(); + onDestroyed?.(); + return; + } + const onDone = () => { + clearImmediate(immediate); + stream.off("error", onDone); + stream.off("close", onDone); + onDestroyed?.(); + }; + const onClosed = () => { + if (stream.closed) { + onDone(); + } else { + immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + } + }; + let immediate = setImmediate(onClosed); + if (!onDestroyed) + immediate.unref(); + stream.once("error", onDone); + stream.once("close", onDone); + cleanup(); + if (!stream.closed) { + stream.destroy(); + } +}; + // node_modules/@effect/platform-node-shared/dist/NodeSink.js var fromWritable = (options) => fromChannel2(mapDone(fromWritableChannel(options), (_) => [_])); var fromWritableChannel = (options) => fromTransform((pull) => { const writable = options.evaluate(); - return succeed6(pullIntoWritable({ + const write = pullIntoWritable({ ...options, writable, pull - })); -}); -var pullIntoWritable = (options) => options.pull.pipe(flatMap3((chunk) => { - let i = 0; - return callback2((resume) => { - let cancelled = false; - const loop = () => { - for (;i < chunk.length; ) { - if (cancelled) { - return; - } - const success = options.writable.write(chunk[i++], options.encoding); - if (!success) { - if (!cancelled) { - options.writable.once("drain", loop); + }); + return succeed6(options.endOnDone === false ? write : onError2(write, (cause) => isDoneCause(cause) ? void_3 : releaseWritable(writable))); +}); +var releaseWritable = (writable) => callback2((resume) => { + const onDestroyed = () => resume(void_3); + if (writable.closed) { + const cleanup = finished(writable, { + readable: false + }, () => { + cleanup(); + onDestroyed(); + }); + } else { + destroyStream(writable, constVoid, onDestroyed); + } +}); +var pullIntoWritable = (options) => withFiber2((fiber) => { + const dispatcher = fiber.currentDispatcher; + const completion = makeUnsafe2(); + const failure = makeUnsafe2(); + const onError = (error) => doneUnsafe(failure, failSync2(() => options.onError(error))); + let errorEmitted = false; + const onStreamError = (error) => { + errorEmitted = true; + onError(error); + }; + options.writable.on("error", onStreamError); + const cleanup = finished(options.writable, { + readable: false + }, (error) => { + if (error) { + onError(error); + } else { + doneUnsafe(completion, void_3); + } + }); + return options.pull.pipe(flatMap3((chunk) => { + let i = 0; + return callback2((resume) => { + let cancelled = false; + const onFinish = () => dispatcher.scheduleTask(loop, 0); + const loop = () => { + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + for (;i < chunk.length; ) { + if (cancelled) { + return; + } + const success = options.writable.write(chunk[i++], options.encoding, (error) => { + if (!error) + return; + if (options.writable.closed) { + onError(error); + } else { + dispatcher.scheduleTask(() => onError(error), 0); + } + }); + if (!success) { + if (!cancelled) { + options.writable.once("drain", loop); + options.writable.once("finish", onFinish); + } + return; } - return; } - } - if (!cancelled) { - resume(void_3); - } - }; - loop(); - return sync3(() => { - cancelled = true; - options.writable.off("drain", loop); + if (!cancelled) { + resume(void_3); + } + }; + loop(); + return sync3(() => { + cancelled = true; + options.writable.off("drain", loop); + options.writable.off("finish", onFinish); + }); }); - }); -}), forever2({ - disableYield: true -}), options.endOnDone !== false ? catchDone((_) => { - if ("closed" in options.writable && options.writable.closed) { - return done2(_); - } - return callback2((resume) => { - const onFinish = () => resume(done2(_)); - options.writable.once("finish", onFinish); + }), forever2({ + disableYield: true + }), options.endOnDone !== false ? catchDone((_) => { options.writable.end(); - return sync3(() => { - options.writable.off("finish", onFinish); - }); - }); -}) : identity, raceFirst2(callback2((resume) => { - const onError = (error) => resume(fail6(options.onError(error))); - options.writable.once("error", onError); - return sync3(() => { - options.writable.off("error", onError); - }); -}))); + return andThen2(_await(completion), done2(_)); + }) : identity, raceFirst2(_await(failure)), ensuring2(sync3(() => { + cleanup(); + const removeErrorListener = () => { + options.writable.off("error", onStreamError); + options.writable.off("error", removeErrorListener); + options.writable.off("close", removeErrorListener); + }; + if (options.writable.errored && !options.writable.closed && !errorEmitted) { + options.writable.once("error", removeErrorListener); + options.writable.once("close", removeErrorListener); + } else { + removeErrorListener(); + } + }))); +}); // node_modules/@effect/platform-node-shared/dist/NodeStream.js +import { finished as finished2, Readable } from "node:stream"; var fromReadable = (options) => fromChannel3(fromReadableChannel(options)); var fromReadableChannel = (options) => fromTransform((_, scope) => readableToPullUnsafe({ scope, @@ -8021,17 +7991,14 @@ var readableToPullUnsafe = (options) => { function onReadable() { latch.openUnsafe(); } - function onError(error) { - exit.current = fail5(options.onError(error)); - latch.openUnsafe(); - } - function onEnd() { - exit.current = fail5(Done2()); - latch.openUnsafe(); - } readable.on("readable", onReadable); - readable.once("error", onError); - readable.once("end", onEnd); + const cleanup = finished2(readable, { + readable: true, + writable: false + }, (error) => { + exit.current ??= fail5(error ? options.onError(error) : Done2()); + latch.openUnsafe(); + }); const pull = suspend2(function loop() { let item = options.readable.read(options.chunkSize); if (item === null) { @@ -8055,10 +8022,10 @@ var readableToPullUnsafe = (options) => { }); return as2(addFinalizer2(options.scope, sync3(() => { readable.off("readable", onReadable); - readable.off("error", onError); - readable.off("end", onEnd); - if (closeOnDone && "closed" in options.readable && !options.readable.closed) { - options.readable.destroy(); + if (closeOnDone) { + destroyStream(readable, cleanup); + } else { + cleanup(); } })), pull); }; @@ -8383,6 +8350,7 @@ var make15 = /* @__PURE__ */ gen2(function* () { const signalGroup = (signal) => killProcessGroup(command, childProcess, signal).pipe(catch_2(() => killProcess(command, childProcess, signal))); yield* signalGroup(options?.killSignal ?? "SIGTERM"); if (isUndefined(options?.forceKillAfter)) { + yield* _await(exitSignal); yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis); } else { yield* awaitProcessExit(childProcess, exitSignal, toMillis(options.forceKillAfter)); @@ -8629,10 +8597,14 @@ var ulidString = (timestampMillis, bytes) => { }; // node_modules/effect/dist/internal/uuid.js -var hex = (byte) => byte.toString(16).padStart(2, "0"); +var hex = /* @__PURE__ */ Array.from({ + length: 256 +}, (_, byte) => byte.toString(16).padStart(2, "0")); var stringify = (bytes) => { - const segments = [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)]; - return segments.map((segment) => Array.from(segment, hex).join("")).join("-"); + if (bytes.length < 16) { + return [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)].map((segment) => Array.from(segment, (byte) => hex[byte]).join("")).join("-"); + } + return hex[bytes[0]] + hex[bytes[1]] + hex[bytes[2]] + hex[bytes[3]] + "-" + hex[bytes[4]] + hex[bytes[5]] + "-" + hex[bytes[6]] + hex[bytes[7]] + "-" + hex[bytes[8]] + hex[bytes[9]] + "-" + hex[bytes[10]] + hex[bytes[11]] + hex[bytes[12]] + hex[bytes[13]] + hex[bytes[14]] + hex[bytes[15]]; }; var randomBytes = () => globalThis.crypto.getRandomValues(new Uint8Array(16)); function v4Bytes(bytes = randomBytes()) { @@ -9093,14 +9065,14 @@ var readLink = /* @__PURE__ */ (() => { return (path) => nodeReadLink(path); })(); var realPath = /* @__PURE__ */ (() => { - const nodeRealPath = /* @__PURE__ */ effectify(NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); + const nodeRealPath = /* @__PURE__ */ effectify(process.platform === "win32" ? NFS.realpath.native : NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath")); return (path) => nodeRealPath(path); })(); var rename2 = /* @__PURE__ */ (() => { const nodeRename = /* @__PURE__ */ effectify(NFS.rename, /* @__PURE__ */ handleErrnoException("FileSystem", "rename"), /* @__PURE__ */ handleBadArgument("rename")); return (oldPath, newPath) => nodeRename(oldPath, newPath); })(); -var makeFileInfo = (stat) => try_2({ +var makeFileInfo = (stat, method = "stat") => try_2({ try: () => ({ type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown", mtime: fromNullishOr(stat.mtime), @@ -9117,14 +9089,16 @@ var makeFileInfo = (stat) => try_2({ blksize: stat.blksize !== undefined ? some2(bytes(stat.blksize)) : none2(), blocks: fromNullishOr(stat.blocks) }), - catch: handleBadArgument("stat") + catch: handleBadArgument(method) }); -var stat2 = /* @__PURE__ */ (() => { - const nodeStat = /* @__PURE__ */ effectify(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat")); +var statFactory = (method, nodeStatFn) => { + const nodeStat = effectify(nodeStatFn, handleErrnoException("FileSystem", method), handleBadArgument(method)); return (path) => flatMap3(nodeStat(path, { bigint: true - }), makeFileInfo); -})(); + }), (stat) => makeFileInfo(stat, method)); +}; +var stat2 = /* @__PURE__ */ statFactory("stat", NFS.stat); +var lstat2 = /* @__PURE__ */ statFactory("lstat", NFS.lstat); var symlink2 = /* @__PURE__ */ (() => { const nodeSymlink = /* @__PURE__ */ effectify(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink")); return (target, path) => nodeSymlink(target, path); @@ -9207,6 +9181,7 @@ var makeFileSystem = /* @__PURE__ */ map5(/* @__PURE__ */ serviceOption2(WatchBa copyFile: copyFile2, glob: glob2, link: link2, + lstat: lstat2, makeDirectory, makeTempDirectory, makeTempDirectoryScoped, @@ -9329,6 +9304,16 @@ var layer9 = layer8; // node_modules/effect/dist/internal/schema/interpreter.js var flatMapTransformation = (result, current, f) => result === sameExit ? f(current) : flatMapEager2(result, f); function compileTransformation(transformation) { + const apply = compileTransformationUnsafe(transformation); + return (result, current, options) => { + try { + return apply(result, current, options); + } catch (error) { + return die3(error); + } + }; +} +function compileTransformationUnsafe(transformation) { if (transformation._tag === "Middleware") { return (result, current, options) => { const transformed = result === sameExit ? transformation.decode(succeed8(toOption(current)), options) : transformation.decode(mapEager2(result, toOption), options); @@ -9404,53 +9389,57 @@ function compile(ast, compile, compileField, base, specialize) { let encodingParsers; const parseChecks = (input, options) => { let result = parser(input, options); - if (encodingChecks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const output = result === sameExit ? input : result[args]; - if (input !== missing && output !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, input, options)); + try { + if (encodingChecks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const output = result === sameExit ? input : result[args]; + if (input !== missing && output !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + result = fail6(new Composite(ast, issues, input, options)); + } } } - } - } else { - result = flatMap3(result, (value) => { - if (input !== missing && value !== missing) { - const issues = collectIssues(encodingChecks, input, undefined, ast, options); - if (issues) { - return fail6(new Composite(ast, issues, input, options)); + } else { + result = flatMap3(result, (value) => { + if (input !== missing && value !== missing) { + const issues = collectIssues(encodingChecks, input, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, input, options)); + } } - } - return succeed6(value); - }); - } - } - if (checks && !options.disableChecks) { - if (effectIsExit(result)) { - if (result._tag === "Success") { - const value = result === sameExit ? input : result[args]; - if (value === missing) - return result; - const issues = collectIssues(checks, value, undefined, ast, options); - if (issues) { - result = fail6(new Composite(ast, issues, value, options)); - } + return succeed6(value); + }); } - } else { - result = flatMap3(result, (value) => { - if (value !== missing) { + } + if (checks && !options.disableChecks) { + if (effectIsExit(result)) { + if (result._tag === "Success") { + const value = result === sameExit ? input : result[args]; + if (value === missing) + return result; const issues = collectIssues(checks, value, undefined, ast, options); if (issues) { - return fail6(new Composite(ast, issues, value, options)); + result = fail6(new Composite(ast, issues, value, options)); } } - return succeed6(value); - }); + } else { + result = flatMap3(result, (value) => { + if (value !== missing) { + const issues = collectIssues(checks, value, undefined, ast, options); + if (issues) { + return fail6(new Composite(ast, issues, value, options)); + } + } + return succeed6(value); + }); + } } + return result; + } catch (error) { + return die3(error); } - return result; }; const parseLocal = specialize === undefined ? parseChecks : specialize(parseChecks); if (!links) { @@ -9847,33 +9836,6 @@ function makeStruct(ast, fields) { function Struct(fields) { return makeStruct(struct(fields, undefined), fields); } -function makeTuple(ast, elements) { - return make21(ast, { - elements, - mapElements(f, options) { - const elements = f(this.elements); - return makeTuple(tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements); - } - }); -} -function Tuple(elements) { - return makeTuple(tuple(elements), elements); -} -var ArraySchema = /* @__PURE__ */ lambda((schema) => make21(new Arrays(false, [], [schema.ast]), { - value: schema -})); -function makeUnion(ast, members) { - return make21(ast, { - members, - mapMembers(f, options) { - const members = f(this.members); - return makeUnion(union(members, this.ast.options, options?.unsafePreserveChecks ? this.ast.checks : undefined), members); - } - }); -} -function Union2(members, options) { - return makeUnion(union(members, options, undefined), members); -} function decodeTo2(to, transformation) { return (from) => { return make21(decodeTo(from.ast, to.ast, transformation ? makeTransformation(transformation) : passthrough2()), { @@ -9905,32 +9867,24 @@ function link3() { }; } var makeFilter2 = makeFilter; -function isPattern2(regExp, annotations) { - const source = regExp.source; - const flags = regExp.flags; - const canExport = /^[dg]*uy?$/.test(flags); - const runtimeRegExp = flags === "" ? `new RegExp(${format(source)})` : `new RegExp(${format(source)}, ${format(flags)})`; - return isPattern(regExp, { - toJsonSchema: () => canExport ? { - pattern: flags.endsWith("y") ? `^(?:${source})` : source - } : [{}, true], - toCode: () => ({ - runtime: `Schema.isPattern(${runtimeRegExp})` - }), - ...annotations - }); -} function isBase64(annotations) { - const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - return isPattern2(regExp, { + const pattern = "^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"; + const regExp = /^[0-9a-zA-Z+/]*={0,2}$/; + return makeFilter2((s) => s.length % 4 === 0 && regExp.test(s), { expected: "a base64 encoded string", representation: { id: "effect/schema/isBase64", payload: null }, toJsonSchema: () => ({ - pattern: regExp.source + pattern }), + arbitraryConstraint: { + patterns: [{ + source: pattern, + flags: "" + }] + }, toCode: () => ({ runtime: "Schema.isBase64()" }), @@ -10044,47 +9998,6 @@ var File = /* @__PURE__ */ instanceOf(globalThis.File, { }) })) }); -var FormData2 = /* @__PURE__ */ instanceOf(globalThis.FormData, { - representation: { - id: "effect/schema/FormData", - payload: null - }, - toCode: () => ({ - runtime: `Schema.FormData`, - Type: `globalThis.FormData` - }), - expected: "FormData", - toCodecJson: () => link3()(ArraySchema(Tuple([String4, Union2([Struct({ - _tag: tag("String"), - value: String4 - }), Struct({ - _tag: tag("File"), - value: File - })])])), transformEffect2({ - decode: (e) => { - const out = new globalThis.FormData; - for (const [key, entry] of e) { - out.append(key, entry.value); - } - return succeed6(out); - }, - encode: (formData) => { - return succeed6(globalThis.Array.from(formData.entries()).map(([key, value]) => { - if (typeof value === "string") { - return [key, { - _tag: "String", - value - }]; - } else { - return [key, { - _tag: "File", - value - }]; - } - })); - } - })) -}); var URLSearchParams2 = /* @__PURE__ */ instanceOf(globalThis.URLSearchParams, { representation: { id: "effect/schema/URLSearchParams", @@ -10200,13 +10113,16 @@ function makeClass(Inherited, identifier, struct2, annotations, proto) { } return out; } -function getClassTransformation(self) { - return new Transformation(transform((input) => new self(input, { +function makeClassTrusted(self, fields) { + return new self(fields, { "~payload": { token: payloadToken, - value: input + value: fields } - })), passthrough()); + }); +} +function getClassTransformation(self) { + return new Transformation(transform((input) => makeClassTrusted(self, input)), passthrough()); } function getClassTypeId(identifier) { return `~effect/Schema/Class/${identifier}`; @@ -10305,9 +10221,6 @@ var make23 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readline.emitKeypressEvents(stdin, rl); rl.on("line", onLine); rl.once("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(true); - } return { rl, onClose, @@ -10321,9 +10234,6 @@ var make23 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu readlineActive = false; rl.off("line", onLine); rl.off("close", onClose); - if (stdin.isTTY) { - stdin.setRawMode(false); - } rl.close(); if (inputEnded) { endUnsafe(lines); @@ -10331,6 +10241,14 @@ var make23 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu })), idleTimeToLive: "10 millis" }); + const setRawMode = (enabled) => sync3(() => { + if (stdin.isTTY) + stdin.setRawMode(enabled); + }); + const rawModeRef = yield* make10({ + acquire: acquireRelease2(setRawMode(true), () => setRawMode(false)), + idleTimeToLive: "10 millis" + }); const columns = sync3(() => stdout.columns ?? 0); const rows = sync3(() => stdout.rows ?? 0); const readInput = gen2(function* () { @@ -10365,6 +10283,7 @@ var make23 = /* @__PURE__ */ fnUntraced2(function* (shouldQuit = defaultShouldQu handleEnd(); } else { yield* get3(rlRef); + yield* get3(rawModeRef); stdin.once("end", handleEnd); } return queue; @@ -10507,7 +10426,7 @@ class CommandError extends TaggedError3()("CommandError", { }) { } var error = (command, cause) => new CommandError({ command, exitCode: -1, stderr: String(cause) }); -var collectText = (stream) => stream.pipe(decodeText(), runFold2(() => "", (all, chunk) => all + chunk)); +var collectText = (stream) => stream.pipe(decodeText2(), runFold2(() => "", (all, chunk) => all + chunk)); var retainedStderrLength = 16 * 1024; class Service3 extends Service()("@timmo001/workflows/CommandExecutor") { @@ -10560,8 +10479,8 @@ var layer14 = effect(Service3, gen2(function* () { stdin: "inherit" })); let stderrTail = ""; - const stdout = handle.stdout.pipe(decodeText(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); - const stderr = handle.stderr.pipe(decodeText(), runForEach2((chunk) => sync3(() => { + const stdout = handle.stdout.pipe(decodeText2(), runForEach2((chunk) => sync3(() => process.stdout.write(chunk)))); + const stderr = handle.stderr.pipe(decodeText2(), runForEach2((chunk) => sync3(() => { process.stderr.write(chunk); stderrTail = `${stderrTail}${chunk}`.slice(-retainedStderrLength); })));