effect-browser 0.3.0-beta.22 → 0.3.0-beta.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Browser.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { i as make, r as Suspension, t as Browser } from "./Browser-Cq2K1FEA.mjs";
1
+ import { i as make, r as Suspension, t as Browser } from "./Browser-BKPAbyys.mjs";
2
2
  export { Browser, Suspension, make };
@@ -1,6 +1,6 @@
1
1
  import { quoted } from "./Url.mjs";
2
2
  import { InvalidRequest, Timeout, reasonOf, undispatched } from "./BrowserError.mjs";
3
- import { i as make$1, t as Browser } from "./Browser-Cq2K1FEA.mjs";
3
+ import { i as make$1, t as Browser } from "./Browser-BKPAbyys.mjs";
4
4
  import { Effect, Layer, Redacted } from "effect";
5
5
  //#region src/providers/connection.ts
6
6
  /**
@@ -65,4 +65,4 @@ const make = (defaultConnect) => {
65
65
  //#endregion
66
66
  export { make as t };
67
67
 
68
- //# sourceMappingURL=connection-BTeO0Hiz.mjs.map
68
+ //# sourceMappingURL=connection-CK83pvqP.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"connection-BTeO0Hiz.mjs","names":["Errors.InvalidRequest","Url.quoted","Errors.Timeout","Browser.make","Browser.Browser"],"sources":["../src/providers/connection.ts"],"sourcesContent":["/**\n * A browser reached over the Chrome DevTools Protocol: a Chrome started with\n * `--remote-debugging-port`, or any provider that hands out a CDP WebSocket URL.\n *\n * Closing the scope disconnects. It does not close the remote browser; its owner does that.\n *\n * @since 0.3.0\n */\nimport { type DateTime, Effect, Layer, Redacted } from \"effect\";\nimport type { Browser as PlaywrightBrowser } from \"playwright-core\";\n\nimport * as Browser from \"../Browser.ts\";\nimport * as Errors from \"../BrowserError.ts\";\nimport { reasonOf, undispatched } from \"../BrowserError.ts\";\nimport * as Url from \"../Url.ts\";\n\n/** The runtime connector receives the bound and cancellation signal owned by the opening scope. */\nexport interface ConnectOptions {\n readonly timeout: number;\n readonly headers?: Readonly<Record<string, string>> | undefined;\n readonly signal: AbortSignal;\n}\n\n/**\n * Return a real Playwright CDP browser whose `close()` disconnects without ending the remote\n * browser. Honor `signal` to cancel work; a browser returned after cancellation is disconnected.\n * The endpoint and headers may contain credentials and must not be logged.\n */\nexport type Connector = (endpoint: string, options: ConnectOptions) => Promise<PlaywrightBrowser>;\n\nexport interface Options extends Browser.Options, Pick<ConnectOptions, \"headers\"> {\n /**\n * `ws://`, `wss://` or `http://` DevTools endpoint. Often a credential, so it may be redacted;\n * connect failures never include its userinfo, path or query.\n */\n readonly endpoint: string | Redacted.Redacted<string>;\n /** Runtime-supplied Playwright connection. Required by the `workerd` entry. */\n readonly connect?: Connector | undefined;\n /** Identifies the session in `Browser.id`. Defaults to `\"cdp\"`. */\n readonly id?: string | undefined;\n readonly provider?: string | undefined;\n /** Bound on connecting. Defaults to 30 seconds. */\n readonly connectTimeoutMillis?: number | undefined;\n /** When the provider ends the session on its own, as a hosted session's timeout does. */\n readonly expiresAt?: DateTime.Utc | undefined;\n /**\n * A connection apart from this one for the pages' screencasts, as a hosted provider supplies.\n * Without one, each page's capture runs on its own session.\n */\n readonly capture?: Browser.CaptureSource | undefined;\n}\n\n/** Runtime facades supply the default transport; the shared lifetime imports no Node transport. */\nexport const make = (defaultConnect?: Connector) => {\n const open = Effect.fn(\"Cdp.open\")(function* (options: Options) {\n const endpoint = Redacted.isRedacted(options.endpoint)\n ? Redacted.value(options.endpoint)\n : options.endpoint;\n\n const timeout = options.connectTimeoutMillis ?? 30_000;\n const connector = options.connect ?? defaultConnect;\n const headers = options.headers === undefined ? undefined : { ...options.headers };\n\n const invalid = (detail: string) =>\n undispatched(\"connect\", new Errors.InvalidRequest({ detail }));\n\n if (!Number.isFinite(timeout) || timeout <= 0)\n return yield* invalid(\"connectTimeoutMillis must be finite and greater than zero\");\n if (connector === undefined)\n return yield* invalid(\"This runtime requires a CDP connect callback\");\n\n // Inspect before URL normalization or truncation. Withhold an echoed diagnostic entirely so\n // overlapping header values cannot leave fragments; other URLs keep only their scheme and host.\n const redact = (message: string) => {\n if (Object.values(headers ?? {}).some((value) => value !== \"\" && message.includes(value)))\n return \"CDP diagnostic withheld\";\n\n const origins = message.replace(Url.quoted, (url) => {\n const parsed = URL.parse(url);\n\n return parsed?.host ? `${parsed.protocol}//${parsed.host}` : \"<url>\";\n });\n\n return endpoint === \"\" ? origins : origins.replaceAll(endpoint, \"<endpoint>\");\n };\n\n const failed = (cause: unknown, timeoutMillis?: number) =>\n undispatched(\"connect\", reasonOf(cause, timeoutMillis, \"connection\", redact));\n\n // The endpoint is often a credential, so the connect span names no part of it.\n const connected = yield* Effect.acquireRelease(\n Effect.tryPromise({\n try: (signal) =>\n connector(endpoint, {\n timeout,\n signal,\n ...(headers === undefined ? {} : { headers: { ...headers } }),\n }).then(async (browser) => {\n // Cancellation can precede a connector that ignores its signal. Its late browser still\n // belongs to this acquisition, so disconnect it before dropping the promise result.\n if (signal.aborted) await browser.close().catch(() => undefined);\n\n return browser;\n }),\n catch: (cause) => failed(cause, timeout),\n }).pipe(\n Effect.timeoutOrElse({\n duration: timeout,\n orElse: () =>\n Effect.fail(undispatched(\"connect\", new Errors.Timeout({ millis: timeout }))),\n }),\n Effect.withSpan(\"Cdp.connect\", {}, { captureStackTrace: false }),\n ),\n (browser) => Effect.tryPromise(() => browser.close()).pipe(Effect.ignore),\n { interruptible: true },\n );\n\n const context =\n connected.contexts()[0] ??\n (yield* Effect.tryPromise({\n try: () => connected.newContext(),\n catch: (cause) => failed(cause),\n }));\n\n const { id = \"cdp\", provider = \"cdp\", expiresAt, capture } = options;\n\n return yield* Browser.make(context, { id, provider, expiresAt, capture }, options);\n });\n\n const layer = (options: Options): Layer.Layer<Browser.Browser, Errors.BrowserError> =>\n Layer.effect(Browser.Browser, open(options));\n\n return { open, layer };\n};\n"],"mappings":";;;;;;;;;;;;;;AAqDA,MAAa,QAAQ,mBAA+B;CAClD,MAAM,OAAO,OAAO,GAAG,UAAU,CA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GACH,QAAQ,UAAU,OAAO,OAAO,OAAO;EACzC,CAAC,CAAC,CAAC,KACD,OAAO,cAAc;GACnB,UAAU;GACV,cACE,OAAO,KAAK,aAAa,WAAW,IAAIC,QAAe,EAAE,QAAQ,QAAQ,CAAC,CAAC,CAAC;EAChF,CAAC,GACD,OAAO,SAAS,eAAe,CAAC,GAAG,EAAE,mBAAmB,MAAM,CAAC,CACjE,IACC,YAAY,OAAO,iBAAiB,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM,GACxE,EAAE,eAAe,KAAK,CACxB;EAEA,MAAM,UACJ,UAAU,SAAS,CAAC,CAAC,OACpB,OAAO,OAAO,WAAW;GACxB,WAAW,UAAU,WAAW;GAChC,QAAQ,UAAU,OAAO,KAAK;EAChC,CAAC;EAEH,MAAM,EAAE,KAAK,OAAO,WAAW,OAAO,WAAW,YAAY;EAE7D,OAAO,OAAOC,OAAa,SAAS;GAAE;GAAI;GAAU;GAAW;EAAQ,GAAG,OAAO;CACnF,CAAC;CAED,MAAM,SAAS,YACb,MAAM,OAAOC,SAAiB,KAAK,OAAO,CAAC;CAE7C,OAAO;EAAE;EAAM;CAAM;AACvB"}
1
+ {"version":3,"file":"connection-CK83pvqP.mjs","names":["Errors.InvalidRequest","Url.quoted","Errors.Timeout","Browser.make","Browser.Browser"],"sources":["../src/providers/connection.ts"],"sourcesContent":["/**\n * A browser reached over the Chrome DevTools Protocol: a Chrome started with\n * `--remote-debugging-port`, or any provider that hands out a CDP WebSocket URL.\n *\n * Closing the scope disconnects. It does not close the remote browser; its owner does that.\n *\n * @since 0.3.0\n */\nimport { type DateTime, Effect, Layer, Redacted } from \"effect\";\nimport type { Browser as PlaywrightBrowser } from \"playwright-core\";\n\nimport * as Browser from \"../Browser.ts\";\nimport * as Errors from \"../BrowserError.ts\";\nimport { reasonOf, undispatched } from \"../BrowserError.ts\";\nimport * as Url from \"../Url.ts\";\n\n/** The runtime connector receives the bound and cancellation signal owned by the opening scope. */\nexport interface ConnectOptions {\n readonly timeout: number;\n readonly headers?: Readonly<Record<string, string>> | undefined;\n readonly signal: AbortSignal;\n}\n\n/**\n * Return a real Playwright CDP browser whose `close()` disconnects without ending the remote\n * browser. Honor `signal` to cancel work; a browser returned after cancellation is disconnected.\n * The endpoint and headers may contain credentials and must not be logged.\n */\nexport type Connector = (endpoint: string, options: ConnectOptions) => Promise<PlaywrightBrowser>;\n\nexport interface Options extends Browser.Options, Pick<ConnectOptions, \"headers\"> {\n /**\n * `ws://`, `wss://` or `http://` DevTools endpoint. Often a credential, so it may be redacted;\n * connect failures never include its userinfo, path or query.\n */\n readonly endpoint: string | Redacted.Redacted<string>;\n /** Runtime-supplied Playwright connection. Required by the `workerd` entry. */\n readonly connect?: Connector | undefined;\n /** Identifies the session in `Browser.id`. Defaults to `\"cdp\"`. */\n readonly id?: string | undefined;\n readonly provider?: string | undefined;\n /** Bound on connecting. Defaults to 30 seconds. */\n readonly connectTimeoutMillis?: number | undefined;\n /** When the provider ends the session on its own, as a hosted session's timeout does. */\n readonly expiresAt?: DateTime.Utc | undefined;\n /**\n * A connection apart from this one for the pages' screencasts, as a hosted provider supplies.\n * Without one, each page's capture runs on its own session.\n */\n readonly capture?: Browser.CaptureSource | undefined;\n}\n\n/** Runtime facades supply the default transport; the shared lifetime imports no Node transport. */\nexport const make = (defaultConnect?: Connector) => {\n const open = Effect.fn(\"Cdp.open\")(function* (options: Options) {\n const endpoint = Redacted.isRedacted(options.endpoint)\n ? Redacted.value(options.endpoint)\n : options.endpoint;\n\n const timeout = options.connectTimeoutMillis ?? 30_000;\n const connector = options.connect ?? defaultConnect;\n const headers = options.headers === undefined ? undefined : { ...options.headers };\n\n const invalid = (detail: string) =>\n undispatched(\"connect\", new Errors.InvalidRequest({ detail }));\n\n if (!Number.isFinite(timeout) || timeout <= 0)\n return yield* invalid(\"connectTimeoutMillis must be finite and greater than zero\");\n if (connector === undefined)\n return yield* invalid(\"This runtime requires a CDP connect callback\");\n\n // Inspect before URL normalization or truncation. Withhold an echoed diagnostic entirely so\n // overlapping header values cannot leave fragments; other URLs keep only their scheme and host.\n const redact = (message: string) => {\n if (Object.values(headers ?? {}).some((value) => value !== \"\" && message.includes(value)))\n return \"CDP diagnostic withheld\";\n\n const origins = message.replace(Url.quoted, (url) => {\n const parsed = URL.parse(url);\n\n return parsed?.host ? `${parsed.protocol}//${parsed.host}` : \"<url>\";\n });\n\n return endpoint === \"\" ? origins : origins.replaceAll(endpoint, \"<endpoint>\");\n };\n\n const failed = (cause: unknown, timeoutMillis?: number) =>\n undispatched(\"connect\", reasonOf(cause, timeoutMillis, \"connection\", redact));\n\n // The endpoint is often a credential, so the connect span names no part of it.\n const connected = yield* Effect.acquireRelease(\n Effect.tryPromise({\n try: (signal) =>\n connector(endpoint, {\n timeout,\n signal,\n ...(headers === undefined ? {} : { headers: { ...headers } }),\n }).then(async (browser) => {\n // Cancellation can precede a connector that ignores its signal. Its late browser still\n // belongs to this acquisition, so disconnect it before dropping the promise result.\n if (signal.aborted) await browser.close().catch(() => undefined);\n\n return browser;\n }),\n catch: (cause) => failed(cause, timeout),\n }).pipe(\n Effect.timeoutOrElse({\n duration: timeout,\n orElse: () =>\n Effect.fail(undispatched(\"connect\", new Errors.Timeout({ millis: timeout }))),\n }),\n Effect.withSpan(\"Cdp.connect\", {}, { captureStackTrace: false }),\n ),\n (browser) => Effect.tryPromise(() => browser.close()).pipe(Effect.ignore),\n { interruptible: true },\n );\n\n const context =\n connected.contexts()[0] ??\n (yield* Effect.tryPromise({\n try: () => connected.newContext(),\n catch: (cause) => failed(cause),\n }));\n\n const { id = \"cdp\", provider = \"cdp\", expiresAt, capture } = options;\n\n return yield* Browser.make(context, { id, provider, expiresAt, capture }, options);\n });\n\n const layer = (options: Options): Layer.Layer<Browser.Browser, Errors.BrowserError> =>\n Layer.effect(Browser.Browser, open(options));\n\n return { open, layer };\n};\n"],"mappings":";;;;;;;;;;;;;;AAqDA,MAAa,QAAQ,mBAA+B;CAClD,MAAM,O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;IAE/D,OAAO;GACT,CAAC;GACH,QAAQ,UAAU,OAAO,OAAO,OAAO;EACzC,CAAC,CAAC,CAAC,KACD,OAAO,cAAc;GACnB,UAAU;GACV,cACE,OAAO,KAAK,aAAa,WAAW,IAAIC,QAAe,EAAE,QAAQ,QAAQ,CAAC,CAAC,CAAC;EAChF,CAAC,GACD,OAAO,SAAS,eAAe,CAAC,GAAG,EAAE,mBAAmB,MAAM,CAAC,CACjE,IACC,YAAY,OAAO,iBAAiB,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM,GACxE,EAAE,eAAe,KAAK,CACxB;EAEA,MAAM,UACJ,UAAU,SAAS,CAAC,CAAC,OACpB,OAAO,OAAO,WAAW;GACxB,WAAW,UAAU,WAAW;GAChC,QAAQ,UAAU,OAAO,KAAK;EAChC,CAAC;EAEH,MAAM,EAAE,KAAK,OAAO,WAAW,OAAO,WAAW,YAAY;EAE7D,OAAO,OAAOC,OAAa,SAAS;GAAE;GAAI;GAAU;GAAW;EAAQ,GAAG,OAAO;CACnF,CAAC;CAED,MAAM,SAAS,YACb,MAAM,OAAOC,SAAiB,KAAK,OAAO,CAAC;CAE7C,OAAO;EAAE;EAAM;CAAM;AACvB"}
package/dist/index.mjs CHANGED
@@ -8,7 +8,7 @@ import { a as Page_exports } from "./Page-BF5izr8R.mjs";
8
8
  import { t as Snapshot_exports } from "./Snapshot.mjs";
9
9
  import { t as ActionPort_exports } from "./ActionPort.mjs";
10
10
  import { t as Clock_exports } from "./Clock.mjs";
11
- import { n as Browser_exports } from "./Browser-Cq2K1FEA.mjs";
11
+ import { n as Browser_exports } from "./Browser-BKPAbyys.mjs";
12
12
  import { n as Style_exports } from "./Style-AO4V7Czt.mjs";
13
13
  import { t as Change_exports } from "./Change.mjs";
14
14
  import { t as Window_exports } from "./Window.mjs";
@@ -1,4 +1,4 @@
1
- import { t as make } from "../connection-BTeO0Hiz.mjs";
1
+ import { t as make } from "../connection-CK83pvqP.mjs";
2
2
  import { chromium } from "playwright-core";
3
3
  //#region src/providers/Cdp.ts
4
4
  /**
@@ -1,5 +1,5 @@
1
1
  import { Failed, reasonOf, undispatched } from "../BrowserError.mjs";
2
- import { i as make, t as Browser$1 } from "../Browser-Cq2K1FEA.mjs";
2
+ import { i as make, t as Browser$1 } from "../Browser-BKPAbyys.mjs";
3
3
  import { Effect, Layer } from "effect";
4
4
  import { chromium } from "playwright-core";
5
5
  //#region src/providers/Chromium.ts
@@ -299,6 +299,7 @@ const describe = (cause) => Cause.prettyErrors(cause).map((error) => error.messa
299
299
  const opening = (options, context, own, retiring, apply, links) => (number) => {
300
300
  let attempt = 0;
301
301
  let began = false;
302
+ let failed = Option.none();
302
303
  const once = Effect.uninterruptible(Effect.gen(function* () {
303
304
  attempt += 1;
304
305
  if ((yield* apply({
@@ -332,6 +333,7 @@ const opening = (options, context, own, retiring, apply, links) => (number) => {
332
333
  const closed = yield* Effect.exit(Scope.close(scope, exit));
333
334
  const cause = Exit.isFailure(closed) ? Cause.combine(exit.cause, closed.cause) : exit.cause;
334
335
  const error = Cause.findErrorOption(cause);
336
+ failed = error;
335
337
  if (Option.isSome(error)) yield* apply({
336
338
  _tag: "Failed",
337
339
  number,
@@ -346,7 +348,7 @@ const opening = (options, context, own, retiring, apply, links) => (number) => {
346
348
  })), Effect.as(Deferred.await(retiring), void 0)).pipe(Effect.flatMap((exit) => exit !== void 0 && Exit.isSuccess(exit) && exit.value ? Effect.void : exit !== void 0 && Exit.isFailure(exit) ? apply({
347
349
  _tag: "GaveUp",
348
350
  number,
349
- error: Option.getOrUndefined(Cause.findErrorOption(exit.cause)),
351
+ error: Option.getOrUndefined(failed),
350
352
  detail: describe(exit.cause)
351
353
  }) : apply({
352
354
  _tag: "Stopped",
@@ -1 +1 @@
1
- {"version":3,"file":"Supervisor.mjs","names":["Lifecycle.resolve","Lifecycle.start","Lifecycle.transition"],"sources":["../../src/supervisor/contract.ts","../../src/supervisor/lifecycle.ts","../../src/supervisor/runtime.ts","../../src/supervisor/Supervisor.ts"],"sourcesContent":["/** Resource generations, typed acquisition failures and the public supervision contract. */\nimport {\n type Cause,\n Data,\n type Duration,\n type Effect,\n Schema,\n type Schedule,\n type Scope,\n type Stream,\n} from \"effect\";\n\nimport type { Released } from \"../providers/Released.ts\";\n\n/** Why a generation stopped serving. */\nexport const Why = Schema.Literals([\"lost\", \"rotated\", \"retired\"]);\nexport type Why = typeof Why.Type;\n\n/** A resource acquired in the generation's scope. The core never inspects its value. */\nexport interface Opened<A> {\n readonly value: A;\n /** Watched until the generation's scope closes, after its release. */\n readonly lost?: Effect.Effect<string> | undefined;\n /** Without a release hook, closing the generation's scope ends the resource. */\n readonly release?: ((why: Why) => Effect.Effect<Released>) | undefined;\n}\n\nexport interface Options<A, E, R> {\n /** Each try receives its generation number and owns resources in the supplied Scope. */\n readonly open: (number: number) => Effect.Effect<Opened<A>, E, R>;\n /** Defaults to exponential from one second, for five minutes. */\n readonly reopen?: Schedule.Schedule<unknown, E> | undefined;\n readonly definite?: ((error: E) => boolean) | undefined;\n /** Each generation waits until every earlier release has completed. */\n readonly exclusive?: boolean | undefined;\n}\n\n/** Every failed try retains its own typed error, including any provider cleanup evidence. */\nexport type State<E> =\n | { readonly _tag: \"Opening\"; readonly attempt: number }\n | { readonly _tag: \"Failed\"; readonly attempt: number; readonly error: E }\n | { readonly _tag: \"Down\"; readonly error: E | undefined; readonly detail: string }\n | { readonly _tag: \"Open\" }\n | { readonly _tag: \"Ending\"; readonly why: Why; readonly detail?: string | undefined }\n | { readonly _tag: \"Closed\"; readonly released?: Released | undefined };\n\nexport interface Generation<E = unknown> {\n readonly number: number;\n /** Epoch milliseconds on the owning Effect clock. */\n readonly at: number;\n /** Monotonic milliseconds on the same clock. */\n readonly hostTime: number;\n readonly state: State<E>;\n}\n\n/** No generation serves because opening failed permanently or the supervisor retired. */\nexport class Unavailable<E = unknown> extends Data.TaggedError(\"Unavailable\")<{\n readonly reason: \"down\" | \"retired\";\n readonly error?: E | undefined;\n readonly detail: string;\n}> {\n override get message() {\n return `no resource: ${this.detail}`;\n }\n}\n\n/** Revoked work still uses its input receipt to determine whether input reached the site. */\nexport class Superseded extends Schema.TaggedError<Superseded>()(\"Superseded\", {\n generation: Schema.Int,\n reason: Why,\n}) {}\n\nexport interface Lease<A> {\n readonly generation: number;\n readonly value: A;\n readonly ending: Effect.Effect<Why>;\n /** Stale declarations do nothing. */\n readonly lose: (detail: string) => Effect.Effect<void>;\n}\n\n/** A public admission budget must be finite and nonnegative. */\nexport class InvalidWait extends Data.TaggedError(\"InvalidWait\")<{ readonly detail: string }> {}\n\nexport interface UseOptions {\n /** Finite nonnegative admission budget on the owner's clock. Zero peeks; absent waits. */\n readonly wait?: Duration.Input | undefined;\n}\n\nexport interface Supervisor<A, E = unknown> {\n /** Ending interrupts the work and awaits its scoped cleanup before releasing the resource. */\n readonly use: <B, E2, R>(\n work: (lease: Lease<A>) => Effect.Effect<B, E2, R>,\n options?: UseOptions,\n ) => Effect.Effect<\n B,\n E2 | Unavailable<E> | Superseded | Cause.TimeoutError | InvalidWait,\n Exclude<R, Scope.Scope>\n >;\n /** Replays the latest 64 changes; ends only after every try and release has finished. */\n readonly states: Stream.Stream<Generation<E>>;\n /** Replace the current generation. A stale `from` does nothing. */\n readonly rotate: (from?: number) => Effect.Effect<void, Unavailable<E>>;\n /** The stop runs on its own fiber; abandoning this wait never abandons retirement. */\n readonly retire: Effect.Effect<void>;\n}\n","/** The resource supervisor's pure lifecycle: one state, one transition, explicit commands. */\nimport type { Released } from \"../providers/Released.ts\";\nimport type { State, Why } from \"./contract.ts\";\n\n/** A generation that opened, with the holds on it. */\nexport interface Live<V, H> {\n readonly number: number;\n readonly value: V;\n readonly holds: ReadonlySet<H>;\n}\n\n/** A generation that stopped serving and is not yet released. */\nexport interface Ended<V, H> {\n readonly live: Live<V, H>;\n readonly why: Why;\n readonly releasing: boolean;\n}\n\nexport type Core<V, H, E> = (\n | {\n readonly _tag: \"Opening\";\n readonly number: number;\n /** False while an exclusive generation waits for earlier releases. */\n readonly started: boolean;\n /** The one it replaces, serving until it opens. Never under `exclusive`. */\n readonly serving: Live<V, H> | undefined;\n }\n | { readonly _tag: \"Open\"; readonly serving: Live<V, H> }\n | {\n readonly _tag: \"Down\";\n readonly number: number;\n readonly error: E | undefined;\n readonly detail: string;\n readonly serving: Live<V, H> | undefined;\n }\n /** `opening`: a generation whose open is finishing the try it began before retiring. */\n | { readonly _tag: \"Retired\"; readonly opening: number | undefined }\n) & { readonly ended: ReadonlyMap<number, Ended<V, H>> };\n\nexport type Input<V, H, E> =\n | { readonly _tag: \"Try\"; readonly number: number; readonly attempt: number }\n | {\n readonly _tag: \"Failed\";\n readonly number: number;\n readonly attempt: number;\n readonly error: E;\n }\n | { readonly _tag: \"Opened\"; readonly number: number; readonly value: V }\n | {\n readonly _tag: \"GaveUp\";\n readonly number: number;\n readonly error: E | undefined;\n readonly detail: string;\n }\n | { readonly _tag: \"Stopped\"; readonly number: number; readonly began: boolean }\n | { readonly _tag: \"Lost\"; readonly number: number; readonly detail: string }\n | { readonly _tag: \"Rotate\"; readonly from?: number | undefined }\n | { readonly _tag: \"Retire\" }\n | { readonly _tag: \"Hold\"; readonly hold: H }\n | { readonly _tag: \"Let\"; readonly number: number; readonly hold: H }\n | { readonly _tag: \"Released\"; readonly number: number; readonly released: Released };\n\nexport type Command<V, H> =\n | { readonly _tag: \"Open\"; readonly number: number }\n | { readonly _tag: \"Watch\"; readonly live: Live<V, H> }\n | { readonly _tag: \"End\"; readonly live: Live<V, H>; readonly why: Why }\n | { readonly _tag: \"Release\"; readonly live: Live<V, H>; readonly why: Why }\n | { readonly _tag: \"Stop\" };\n\nexport interface Step<V, H, E> {\n readonly state: Core<V, H, E>;\n readonly events: ReadonlyArray<readonly [number, State<E>]>;\n readonly commands: ReadonlyArray<Command<V, H>>;\n /** `Try`: the attempt may start. `Rotate`: the generation that replaces the serving one. */\n readonly reply?: number | undefined;\n /** `Hold`: the generation the hold was admitted on. */\n readonly borrowed?: Live<V, H> | undefined;\n}\n\nexport const start = <V, H, E>(): Step<V, H, E> => ({\n state: { _tag: \"Opening\", number: 1, started: true, serving: undefined, ended: new Map() },\n events: [],\n commands: [{ _tag: \"Open\", number: 1 }],\n});\n\nexport const servingOf = <V, H, E>(state: Core<V, H, E>) =>\n state._tag === \"Retired\" ? undefined : state.serving;\n\nconst without = <H>(holds: ReadonlySet<H>, hold: H) => {\n const rest = new Set(holds);\n\n rest.delete(hold);\n\n return rest;\n};\n\nexport const transition = <V, H, E>(\n state: Core<V, H, E>,\n input: Input<V, H, E>,\n exclusive: boolean,\n): Step<V, H, E> => {\n let next = state;\n const events: Array<readonly [number, State<E>]> = [];\n const commands: Array<Command<V, H>> = [];\n let reply: number | undefined;\n let borrowed: Live<V, H> | undefined;\n\n // Stop `live` serving: its work hears why, and its release starts once that work has let go.\n const end = (live: Live<V, H>, why: Why, detail?: string) => {\n const releasing = live.holds.size === 0;\n\n next = { ...next, ended: new Map(next.ended).set(live.number, { live, why, releasing }) };\n events.push([live.number, { _tag: \"Ending\", why, detail }]);\n commands.push({ _tag: \"End\", live, why });\n if (releasing) commands.push({ _tag: \"Release\", live, why });\n };\n\n // Open `number`, `serving` serving until it opens. An exclusive one starts once none is ending.\n const open = (number: number, serving: Live<V, H> | undefined) => {\n const started = !exclusive || next.ended.size === 0;\n\n next = { _tag: \"Opening\", number, started, serving, ended: next.ended };\n if (started) commands.push({ _tag: \"Open\", number });\n };\n\n switch (input._tag) {\n case \"Try\":\n if (state._tag === \"Opening\" && state.started && state.number === input.number) {\n reply = input.attempt;\n events.push([input.number, { _tag: \"Opening\", attempt: input.attempt }]);\n }\n break;\n case \"Failed\":\n events.push([input.number, { _tag: \"Failed\", attempt: input.attempt, error: input.error }]);\n break;\n case \"GaveUp\": {\n const { number, error, detail } = input;\n\n events.push([number, { _tag: \"Down\", error, detail }]);\n if (state._tag === \"Opening\" && state.number === number)\n next = { _tag: \"Down\", number, error, detail, serving: state.serving, ended: state.ended };\n else if (state._tag === \"Retired\" && state.opening === number)\n next = { ...state, opening: undefined };\n break;\n }\n case \"Stopped\":\n if (state._tag === \"Retired\" && state.opening === input.number) {\n next = { ...state, opening: undefined };\n if (input.began) events.push([input.number, { _tag: \"Closed\" }]);\n }\n break;\n case \"Opened\": {\n const live: Live<V, H> = { number: input.number, value: input.value, holds: new Set() };\n\n events.push([live.number, { _tag: \"Open\" }]);\n commands.push({ _tag: \"Watch\", live });\n if (state._tag === \"Opening\" && state.number === live.number) {\n next = { _tag: \"Open\", serving: live, ended: state.ended };\n if (state.serving !== undefined) end(state.serving, \"rotated\");\n } else {\n // Retired while its try ran: it ends as it opens.\n if (state._tag === \"Retired\") next = { ...state, opening: undefined };\n end(live, \"retired\");\n }\n break;\n }\n case \"Lost\": {\n const serving = servingOf(state);\n\n if (state._tag === \"Retired\" || serving === undefined || serving.number !== input.number)\n break;\n if (state._tag === \"Opening\") next = { ...state, serving: undefined };\n end(serving, \"lost\", input.detail);\n if (state._tag !== \"Opening\")\n open((state._tag === \"Open\" ? serving.number : state.number) + 1, undefined);\n break;\n }\n case \"Rotate\": {\n if (state._tag === \"Retired\") break;\n const serving = state.serving;\n\n if (input.from !== undefined && serving?.number !== input.from) break;\n if (state._tag === \"Opening\") {\n reply = state.number;\n break;\n }\n reply = (state._tag === \"Open\" ? state.serving.number : state.number) + 1;\n if (exclusive && serving !== undefined) end(serving, \"rotated\");\n open(reply, exclusive ? undefined : serving);\n break;\n }\n case \"Retire\": {\n if (state._tag === \"Retired\") break;\n const serving = state.serving;\n\n next = {\n _tag: \"Retired\",\n opening: state._tag === \"Opening\" && state.started ? state.number : undefined,\n ended: state.ended,\n };\n if (serving !== undefined) end(serving, \"retired\");\n commands.push({ _tag: \"Stop\" });\n break;\n }\n case \"Hold\": {\n if (state._tag === \"Retired\" || state.serving === undefined) break;\n const live = { ...state.serving, holds: new Set(state.serving.holds).add(input.hold) };\n\n next = { ...state, serving: live };\n borrowed = live;\n break;\n }\n case \"Let\": {\n const serving = servingOf(state);\n\n if (state._tag !== \"Retired\" && serving?.number === input.number) {\n if (serving.holds.has(input.hold))\n next = { ...state, serving: { ...serving, holds: without(serving.holds, input.hold) } };\n break;\n }\n const ended = state.ended.get(input.number);\n\n if (ended === undefined || !ended.live.holds.has(input.hold)) break;\n const live = { ...ended.live, holds: without(ended.live.holds, input.hold) };\n const releasing = live.holds.size === 0;\n\n next = {\n ...state,\n ended: new Map(state.ended).set(input.number, { ...ended, live, releasing }),\n };\n if (releasing) commands.push({ _tag: \"Release\", live, why: ended.why });\n break;\n }\n case \"Released\": {\n const ended = state.ended.get(input.number);\n\n if (ended === undefined || !ended.releasing) break;\n const rest = new Map(state.ended);\n\n rest.delete(input.number);\n next = { ...state, ended: rest };\n events.push([input.number, { _tag: \"Closed\", released: input.released }]);\n if (next._tag === \"Opening\" && !next.started && rest.size === 0) {\n next = { ...next, started: true };\n commands.push({ _tag: \"Open\", number: next.number });\n }\n break;\n }\n }\n\n return { state: next, events, commands, reply, borrowed };\n};\n\n/** What a caller waiting for a generation gets now: nothing yet while one opens. */\nexport const resolve = <V, H, E>(state: Core<V, H, E>) =>\n state._tag === \"Retired\"\n ? {\n _tag: \"Unavailable\" as const,\n reason: \"retired\" as const,\n error: undefined,\n detail: \"retired\",\n }\n : state.serving !== undefined\n ? { _tag: \"Serve\" as const }\n : state._tag === \"Down\"\n ? {\n _tag: \"Unavailable\" as const,\n reason: \"down\" as const,\n error: state.error,\n detail: state.detail,\n }\n : undefined;\n","/** Scoped acquisition, release and borrowing for the pure resource supervisor lifecycle. */\nimport {\n Cause,\n Clock,\n type Context,\n Deferred,\n Duration,\n Effect,\n Exit,\n Option,\n Schedule,\n Scope,\n Stream,\n SubscriptionRef,\n type Tracer,\n} from \"effect\";\n\nimport { Settled, Unconfirmed } from \"../providers/Released.ts\";\nimport {\n InvalidWait,\n type Lease,\n type Opened,\n type Options,\n type Supervisor,\n Superseded,\n Unavailable,\n type Why,\n} from \"./contract.ts\";\nimport * as Lifecycle from \"./lifecycle.ts\";\n\nexport interface Runtime<A> {\n readonly opened: Opened<A>;\n readonly scope: Scope.Closeable;\n readonly ending: Deferred.Deferred<Why>;\n}\n\nexport type Hold = object;\nexport type State<A, E> = Lifecycle.Core<Runtime<A>, Hold, E>;\n\nexport type Apply<A, E> = (\n input: Lifecycle.Input<Runtime<A>, Hold, E>,\n) => Effect.Effect<Lifecycle.Step<Runtime<A>, Hold, E>>;\n\nexport const describe = (cause: Cause.Cause<unknown>) =>\n Cause.prettyErrors(cause)\n .map((error) => error.message)\n .join(\"; \");\n\nexport const opening =\n <A, E, R>(\n options: Options<A, E, R>,\n context: Context.Context<Exclude<Exclude<R, Scope.Scope>, Tracer.ParentSpan>>,\n own: Scope.Closeable,\n retiring: Deferred.Deferred<void>,\n apply: Apply<A, E>,\n links: ReadonlyArray<Tracer.SpanLink>,\n ) =>\n (number: number) => {\n let attempt = 0;\n let began = false;\n\n const once: Effect.Effect<boolean, E> = Effect.uninterruptible(\n Effect.gen(function* () {\n attempt += 1;\n const admitted = yield* apply({ _tag: \"Try\", number, attempt });\n\n if (admitted.reply === undefined) return false;\n began = true;\n const scope = yield* Scope.fork(own);\n\n const exit = yield* Effect.exit(\n options.open(number).pipe(\n Scope.provide(scope),\n Effect.withSpan(\"Supervisor.open\", {\n root: true,\n links,\n attributes: { generation: number, attempt },\n }),\n Effect.provideContext(context),\n ),\n );\n\n if (Exit.isSuccess(exit)) {\n const ending = Deferred.makeUnsafe<Why>();\n\n yield* apply({ _tag: \"Opened\", number, value: { opened: exit.value, scope, ending } });\n\n return true;\n }\n const closed = yield* Effect.exit(Scope.close(scope, exit));\n\n const cause = Exit.isFailure(closed) ? Cause.combine(exit.cause, closed.cause) : exit.cause;\n const error = Cause.findErrorOption(cause);\n\n if (Option.isSome(error))\n yield* apply({ _tag: \"Failed\", number, attempt, error: error.value });\n\n return yield* Effect.failCause(cause);\n }),\n );\n\n return Effect.raceFirst(\n Effect.exit(\n Effect.retry(once, {\n schedule:\n options.reopen ??\n Schedule.exponential(\"1 second\").pipe(Schedule.upTo({ duration: \"5 minutes\" })),\n while: (error) => options.definite?.(error) !== true,\n }),\n ),\n Effect.as(Deferred.await(retiring), undefined),\n ).pipe(\n Effect.flatMap((exit) =>\n exit !== undefined && Exit.isSuccess(exit) && exit.value\n ? Effect.void\n : exit !== undefined && Exit.isFailure(exit)\n ? apply({\n _tag: \"GaveUp\",\n number,\n error: Option.getOrUndefined(Cause.findErrorOption(exit.cause)),\n detail: describe(exit.cause),\n })\n : apply({ _tag: \"Stopped\", number, began }),\n ),\n Effect.asVoid,\n );\n };\n\n/** A provider failure or a failed scope close always leaves an Unconfirmed outcome. */\nexport const releasing = <A, E>(apply: Apply<A, E>, links: ReadonlyArray<Tracer.SpanLink>) =>\n Effect.fnUntraced(\n function* (live: Lifecycle.Live<Runtime<A>, Hold>, why: Why) {\n const { opened, scope } = live.value;\n\n const outcome = yield* Effect.suspend(\n () => opened.release?.(why) ?? Effect.succeed(new Settled()),\n ).pipe(\n Effect.catchCause((cause) =>\n Effect.succeed(new Unconfirmed({ detail: `the release failed: ${describe(cause)}` })),\n ),\n );\n\n const closed = yield* Effect.exit(Scope.close(scope, Exit.void));\n\n const released =\n Exit.isSuccess(closed) || outcome._tag !== \"Settled\"\n ? outcome\n : new Unconfirmed({ detail: `its scope failed to close: ${describe(closed.cause)}` });\n\n yield* apply({ _tag: \"Released\", number: live.number, released });\n },\n Effect.uninterruptible,\n Effect.withSpan(\"Supervisor.release\", { root: true, links }),\n );\n\nconst bounded = (input: Duration.Input) =>\n Effect.suspend(() => {\n const duration = Duration.fromInput(input);\n\n return Option.isSome(duration) &&\n Duration.isFinite(duration.value) &&\n !Duration.isNegative(duration.value)\n ? Effect.succeed(duration.value)\n : Effect.fail(new InvalidWait({ detail: \"wait must be a finite nonnegative duration\" }));\n });\n\nexport const leasing =\n <A, E>(\n state: SubscriptionRef.SubscriptionRef<State<A, E>>,\n apply: Apply<A, E>,\n clock: Clock.Clock,\n ): Supervisor<A, E>[\"use\"] =>\n (work, options = {}) =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const hold: Hold = {};\n const wait = options.wait === undefined ? undefined : yield* bounded(options.wait);\n const now = () => Number(clock.monotonicTimeNanosUnsafe()) / 1e6;\n const until = wait === undefined ? undefined : now() + Duration.toMillis(wait);\n let live: Lifecycle.Live<Runtime<A>, Hold> | undefined;\n\n while (live === undefined) {\n const step = yield* apply({ _tag: \"Hold\", hold });\n const resolved = Lifecycle.resolve(step.state);\n\n live = step.borrowed;\n if (live !== undefined) break;\n if (resolved?._tag === \"Unavailable\") return yield* new Unavailable<E>(resolved);\n const remaining = until === undefined ? undefined : Math.max(0, until - now());\n\n if (remaining === 0) return yield* new Cause.TimeoutError();\n\n const changed = SubscriptionRef.changes(state).pipe(\n Stream.filter((s) => Lifecycle.resolve(s) !== undefined),\n Stream.runHead,\n );\n\n yield* restore(\n (remaining === undefined ? changed : Effect.timeout(changed, remaining)).pipe(\n Effect.provideService(Clock.Clock, clock),\n ),\n );\n if (until !== undefined && now() >= until) return yield* new Cause.TimeoutError();\n }\n const { number } = live;\n const { ending, opened } = live.value;\n\n const superseded = Effect.flatMap(Deferred.await(ending), (reason) =>\n Effect.fail(new Superseded({ generation: number, reason })),\n );\n\n const lease: Lease<A> = {\n generation: number,\n value: opened.value,\n ending: Deferred.await(ending),\n lose: (detail) => Effect.asVoid(apply({ _tag: \"Lost\", number, detail })),\n };\n\n return yield* restore(\n Effect.scoped(\n Effect.raceFirst(\n Effect.tap(\n Effect.suspend(() => work(lease)),\n () =>\n Effect.flatMap(Deferred.isDone(ending), (done) =>\n done ? superseded : Effect.void,\n ),\n ),\n superseded,\n ),\n ),\n ).pipe(Effect.ensuring(apply({ _tag: \"Let\", number, hold })));\n }),\n );\n","/**\n * A resource kept serving through typed acquisition failures, loss and rotation.\n * `make` adds its finalizer directly to its caller's scope. Each generation has its own scope;\n * its loss signal remains watched until that scope closes, after release. Optional policies\n * compose by wrapping `open`, `release` and the public generation stream.\n */\nimport {\n Clock,\n Context,\n Deferred,\n Effect,\n Exit,\n FiberSet,\n Option,\n PubSub,\n Scope,\n Semaphore,\n Stream,\n SubscriptionRef,\n type Take,\n Tracer,\n} from \"effect\";\n\nimport { type Generation, type Options, type Supervisor, Unavailable } from \"./contract.ts\";\nimport * as Lifecycle from \"./lifecycle.ts\";\nimport { type Apply, type Hold, type Runtime, leasing, opening, releasing } from \"./runtime.ts\";\n\nexport {\n type Generation,\n InvalidWait,\n type Lease,\n type Opened,\n type Options,\n type State,\n type Supervisor,\n Superseded,\n Unavailable,\n type UseOptions,\n Why,\n} from \"./contract.ts\";\n\nexport const make = Effect.fn(\"Supervisor.make\")(function* <A, E, R>(\n options: Options<A, E, R>,\n): Effect.fn.Return<Supervisor<A, E>, never, Scope.Scope | Exclude<R, Scope.Scope>> {\n const clock = yield* Clock.Clock;\n // The caller span survives as a link, never as the parent of a later generation.\n const context = Context.omit(Tracer.ParentSpan)(yield* Effect.context<Exclude<R, Scope.Scope>>());\n const parent = yield* Effect.serviceOption(Tracer.ParentSpan);\n const links = Option.isSome(parent) ? [{ span: parent.value, attributes: {} }] : [];\n // A parallel caller scope must not close workers alongside retirement.\n const own = yield* Scope.make();\n const started = Lifecycle.start<Runtime<A>, Hold, E>();\n const state = yield* SubscriptionRef.make(started.state);\n const permit = yield* Semaphore.make(1);\n const events = yield* PubSub.unbounded<Take.Take<Generation<E>>>({ replay: 64 });\n const fibers = yield* FiberSet.make().pipe(Scope.provide(own));\n\n const run = yield* FiberSet.runtime(fibers)<never>().pipe(\n Effect.updateContext<never, never>(() => context),\n );\n\n const retiring = Deferred.makeUnsafe<void>();\n const stopped = Deferred.makeUnsafe<void>();\n\n const apply: Apply<A, E> = (input) =>\n permit.withPermit(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const step = Lifecycle.transition(state.value, input, options.exclusive ?? false);\n\n // SubscriptionRef.set wakes retirement's waiter immediately; publish its last outcome first.\n for (const [number, change] of step.events)\n PubSub.publishUnsafe(events, [\n {\n number,\n state: change,\n at: clock.currentTimeMillisUnsafe(),\n hostTime: Number(clock.monotonicTimeNanosUnsafe()) / 1e6,\n },\n ]);\n if (step.state !== state.value) yield* SubscriptionRef.set(state, step.state);\n for (const command of step.commands) yield* perform(command);\n\n return step;\n }),\n ),\n );\n\n const openGeneration = opening<A, E, R>(options, context, own, retiring, apply, links);\n const releaseGeneration = releasing(apply, links);\n\n const perform = (command: Lifecycle.Command<Runtime<A>, Hold>): Effect.Effect<void> => {\n switch (command._tag) {\n case \"Open\":\n return Effect.sync(() => void run(openGeneration(command.number)));\n case \"Watch\": {\n const { number, value } = command.live;\n const { lost } = value.opened;\n\n return lost === undefined\n ? Effect.void\n : Effect.asVoid(\n Effect.forkIn(\n Effect.flatMap(lost, (detail) => apply({ _tag: \"Lost\", number, detail })),\n value.scope,\n ),\n );\n }\n case \"End\":\n return Effect.asVoid(Deferred.succeed(command.live.value.ending, command.why));\n case \"Release\":\n return Effect.sync(() => void run(releaseGeneration(command.live, command.why)));\n case \"Stop\":\n return Deferred.succeed(retiring, undefined).pipe(\n Effect.andThen(Effect.sync(() => void run(stop))),\n );\n }\n };\n\n const rotate = Effect.fnUntraced(function* (from?: number) {\n const step = yield* apply({ _tag: \"Rotate\", from });\n const target = step.reply;\n\n if (target === undefined)\n return step.state._tag === \"Retired\"\n ? yield* new Unavailable<E>({ reason: \"retired\", detail: \"retired\" })\n : undefined;\n\n const reached = (s: typeof step.state) =>\n s._tag === \"Retired\"\n ? new Unavailable<E>({ reason: \"retired\", detail: \"retired\" })\n : s._tag === \"Down\" && s.number >= target\n ? new Unavailable<E>({ reason: \"down\", error: s.error, detail: s.detail })\n : s._tag === \"Open\" && s.serving.number >= target\n ? (\"served\" as const)\n : undefined;\n\n const outcome = yield* Stream.runHead(\n Stream.filter(Stream.map(SubscriptionRef.changes(state), reached), (r) => r !== undefined),\n );\n\n if (Option.isSome(outcome) && outcome.value !== \"served\") return yield* outcome.value;\n });\n\n const stop = Effect.gen(function* () {\n yield* Stream.runHead(\n Stream.filter(\n SubscriptionRef.changes(state),\n (s) => s._tag === \"Retired\" && s.opening === undefined && s.ended.size === 0,\n ),\n );\n yield* PubSub.publish(events, Exit.void);\n }).pipe(Effect.ensuring(Deferred.succeed(stopped, undefined)));\n\n // Commit the transition even if its caller is interrupted while waiting for the state lock.\n const retire = apply({ _tag: \"Retire\" }).pipe(\n Effect.uninterruptible,\n Effect.andThen(Deferred.await(stopped)),\n );\n\n yield* Effect.addFinalizer((exit) => retire.pipe(Effect.ensuring(Scope.close(own, exit))));\n yield* Effect.forEach(started.commands, perform, { discard: true });\n\n return {\n use: leasing(state, apply, clock),\n states: Stream.fromPubSubTake(events),\n rotate,\n retire,\n };\n});\n"],"mappings":";;;;;AAeA,MAAa,MAAM,OAAO,SAAS;CAAC;CAAQ;CAAW;AAAS,CAAC;;AAyCjE,IAAa,cAAb,cAA8C,KAAK,YAAY,aAAa,CAAC,CAI1E;CACD,IAAa,UAAU;EACrB,OAAO,gBAAgB,KAAK;CAC9B;AACF;;AAGA,IAAa,aAAb,cAAgC,OAAO,YAAwB,CAAC,CAAC,cAAc;CAC7E,YAAY,OAAO;CACnB,QAAQ;AACV,CAAC,CAAC,CAAC,CAAC;;AAWJ,IAAa,cAAb,cAAiC,KAAK,YAAY,aAAa,CAAC,CAA8B,CAAC;;;ACF/F,MAAa,eAAuC;CAClD,OAAO;EAAE,MAAM;EAAW,QAAQ;EAAG,SAAS;EAAM,SAAS,KAAA;EAAW,uBAAO,IAAI,IAAI;CAAE;CACzF,QAAQ,CAAC;CACT,UAAU,CAAC;EAAE,MAAM;EAAQ,QAAQ;CAAE,CAAC;AACxC;AAEA,MAAa,aAAsB,UACjC,MAAM,SAAS,YAAY,KAAA,IAAY,MAAM;AAE/C,MAAM,WAAc,OAAuB,SAAY;CACrD,MAAM,OAAO,IAAI,IAAI,KAAK;CAE1B,KAAK,OAAO,IAAI;CAEhB,OAAO;AACT;AAEA,MAAa,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,IAAI,aAAa;EACnC,OAAO,OAAO,QACZ,OAAO,OACL,gBAAgB,QAAQ,KAAK,IAC5B,MAAM,EAAE,SAAS,aAAa,EAAE,YAAY,KAAA,KAAa,EAAE,MAAM,SAAS,CAC7E,CACF;EACA,OAAO,OAAO,QAAQ,QAAQ,KAAK,IAAI;CACzC,CAAC,CAAC,CAAC,KAAK,OAAO,SAAS,SAAS,QAAQ,SAAS,KAAA,CAAS,CAAC,CAAC;CAG7D,MAAM,SAAS,MAAM,EAAE,MAAM,SAAS,CAAC,CAAC,CAAC,KACvC,OAAO,iBACP,OAAO,QAAQ,SAAS,MAAM,OAAO,CAAC,CACxC;CAEA,OAAO,OAAO,cAAc,SAAS,OAAO,KAAK,OAAO,SAAS,MAAM,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC;CACzF,OAAO,OAAO,QAAQ,QAAQ,UAAU,SAAS,EAAE,SAAS,KAAK,CAAC;CAElE,OAAO;EACL,KAAK,QAAQ,OAAO,OAAO,KAAK;EAChC,QAAQ,OAAO,eAAe,MAAM;EACpC;EACA;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"Supervisor.mjs","names":["Lifecycle.resolve","Lifecycle.start","Lifecycle.transition"],"sources":["../../src/supervisor/contract.ts","../../src/supervisor/lifecycle.ts","../../src/supervisor/runtime.ts","../../src/supervisor/Supervisor.ts"],"sourcesContent":["/** Resource generations, typed acquisition failures and the public supervision contract. */\nimport {\n type Cause,\n Data,\n type Duration,\n type Effect,\n Schema,\n type Schedule,\n type Scope,\n type Stream,\n} from \"effect\";\n\nimport type { Released } from \"../providers/Released.ts\";\n\n/** Why a generation stopped serving. */\nexport const Why = Schema.Literals([\"lost\", \"rotated\", \"retired\"]);\nexport type Why = typeof Why.Type;\n\n/** A resource acquired in the generation's scope. The core never inspects its value. */\nexport interface Opened<A> {\n readonly value: A;\n /** Watched until the generation's scope closes, after its release. */\n readonly lost?: Effect.Effect<string> | undefined;\n /** Without a release hook, closing the generation's scope ends the resource. */\n readonly release?: ((why: Why) => Effect.Effect<Released>) | undefined;\n}\n\nexport interface Options<A, E, R> {\n /** Each try receives its generation number and owns resources in the supplied Scope. */\n readonly open: (number: number) => Effect.Effect<Opened<A>, E, R>;\n /** Defaults to exponential from one second, for five minutes. */\n readonly reopen?: Schedule.Schedule<unknown, E> | undefined;\n readonly definite?: ((error: E) => boolean) | undefined;\n /** Each generation waits until every earlier release has completed. */\n readonly exclusive?: boolean | undefined;\n}\n\n/** Every failed try retains its own typed error, including any provider cleanup evidence. */\nexport type State<E> =\n | { readonly _tag: \"Opening\"; readonly attempt: number }\n | { readonly _tag: \"Failed\"; readonly attempt: number; readonly error: E }\n | { readonly _tag: \"Down\"; readonly error: E | undefined; readonly detail: string }\n | { readonly _tag: \"Open\" }\n | { readonly _tag: \"Ending\"; readonly why: Why; readonly detail?: string | undefined }\n | { readonly _tag: \"Closed\"; readonly released?: Released | undefined };\n\nexport interface Generation<E = unknown> {\n readonly number: number;\n /** Epoch milliseconds on the owning Effect clock. */\n readonly at: number;\n /** Monotonic milliseconds on the same clock. */\n readonly hostTime: number;\n readonly state: State<E>;\n}\n\n/** No generation serves because opening failed permanently or the supervisor retired. */\nexport class Unavailable<E = unknown> extends Data.TaggedError(\"Unavailable\")<{\n readonly reason: \"down\" | \"retired\";\n readonly error?: E | undefined;\n readonly detail: string;\n}> {\n override get message() {\n return `no resource: ${this.detail}`;\n }\n}\n\n/** Revoked work still uses its input receipt to determine whether input reached the site. */\nexport class Superseded extends Schema.TaggedError<Superseded>()(\"Superseded\", {\n generation: Schema.Int,\n reason: Why,\n}) {}\n\nexport interface Lease<A> {\n readonly generation: number;\n readonly value: A;\n readonly ending: Effect.Effect<Why>;\n /** Stale declarations do nothing. */\n readonly lose: (detail: string) => Effect.Effect<void>;\n}\n\n/** A public admission budget must be finite and nonnegative. */\nexport class InvalidWait extends Data.TaggedError(\"InvalidWait\")<{ readonly detail: string }> {}\n\nexport interface UseOptions {\n /** Finite nonnegative admission budget on the owner's clock. Zero peeks; absent waits. */\n readonly wait?: Duration.Input | undefined;\n}\n\nexport interface Supervisor<A, E = unknown> {\n /** Ending interrupts the work and awaits its scoped cleanup before releasing the resource. */\n readonly use: <B, E2, R>(\n work: (lease: Lease<A>) => Effect.Effect<B, E2, R>,\n options?: UseOptions,\n ) => Effect.Effect<\n B,\n E2 | Unavailable<E> | Superseded | Cause.TimeoutError | InvalidWait,\n Exclude<R, Scope.Scope>\n >;\n /** Replays the latest 64 changes; ends only after every try and release has finished. */\n readonly states: Stream.Stream<Generation<E>>;\n /** Replace the current generation. A stale `from` does nothing. */\n readonly rotate: (from?: number) => Effect.Effect<void, Unavailable<E>>;\n /** The stop runs on its own fiber; abandoning this wait never abandons retirement. */\n readonly retire: Effect.Effect<void>;\n}\n","/** The resource supervisor's pure lifecycle: one state, one transition, explicit commands. */\nimport type { Released } from \"../providers/Released.ts\";\nimport type { State, Why } from \"./contract.ts\";\n\n/** A generation that opened, with the holds on it. */\nexport interface Live<V, H> {\n readonly number: number;\n readonly value: V;\n readonly holds: ReadonlySet<H>;\n}\n\n/** A generation that stopped serving and is not yet released. */\nexport interface Ended<V, H> {\n readonly live: Live<V, H>;\n readonly why: Why;\n readonly releasing: boolean;\n}\n\nexport type Core<V, H, E> = (\n | {\n readonly _tag: \"Opening\";\n readonly number: number;\n /** False while an exclusive generation waits for earlier releases. */\n readonly started: boolean;\n /** The one it replaces, serving until it opens. Never under `exclusive`. */\n readonly serving: Live<V, H> | undefined;\n }\n | { readonly _tag: \"Open\"; readonly serving: Live<V, H> }\n | {\n readonly _tag: \"Down\";\n readonly number: number;\n readonly error: E | undefined;\n readonly detail: string;\n readonly serving: Live<V, H> | undefined;\n }\n /** `opening`: a generation whose open is finishing the try it began before retiring. */\n | { readonly _tag: \"Retired\"; readonly opening: number | undefined }\n) & { readonly ended: ReadonlyMap<number, Ended<V, H>> };\n\nexport type Input<V, H, E> =\n | { readonly _tag: \"Try\"; readonly number: number; readonly attempt: number }\n | {\n readonly _tag: \"Failed\";\n readonly number: number;\n readonly attempt: number;\n readonly error: E;\n }\n | { readonly _tag: \"Opened\"; readonly number: number; readonly value: V }\n | {\n readonly _tag: \"GaveUp\";\n readonly number: number;\n readonly error: E | undefined;\n readonly detail: string;\n }\n | { readonly _tag: \"Stopped\"; readonly number: number; readonly began: boolean }\n | { readonly _tag: \"Lost\"; readonly number: number; readonly detail: string }\n | { readonly _tag: \"Rotate\"; readonly from?: number | undefined }\n | { readonly _tag: \"Retire\" }\n | { readonly _tag: \"Hold\"; readonly hold: H }\n | { readonly _tag: \"Let\"; readonly number: number; readonly hold: H }\n | { readonly _tag: \"Released\"; readonly number: number; readonly released: Released };\n\nexport type Command<V, H> =\n | { readonly _tag: \"Open\"; readonly number: number }\n | { readonly _tag: \"Watch\"; readonly live: Live<V, H> }\n | { readonly _tag: \"End\"; readonly live: Live<V, H>; readonly why: Why }\n | { readonly _tag: \"Release\"; readonly live: Live<V, H>; readonly why: Why }\n | { readonly _tag: \"Stop\" };\n\nexport interface Step<V, H, E> {\n readonly state: Core<V, H, E>;\n readonly events: ReadonlyArray<readonly [number, State<E>]>;\n readonly commands: ReadonlyArray<Command<V, H>>;\n /** `Try`: the attempt may start. `Rotate`: the generation that replaces the serving one. */\n readonly reply?: number | undefined;\n /** `Hold`: the generation the hold was admitted on. */\n readonly borrowed?: Live<V, H> | undefined;\n}\n\nexport const start = <V, H, E>(): Step<V, H, E> => ({\n state: { _tag: \"Opening\", number: 1, started: true, serving: undefined, ended: new Map() },\n events: [],\n commands: [{ _tag: \"Open\", number: 1 }],\n});\n\nexport const servingOf = <V, H, E>(state: Core<V, H, E>) =>\n state._tag === \"Retired\" ? undefined : state.serving;\n\nconst without = <H>(holds: ReadonlySet<H>, hold: H) => {\n const rest = new Set(holds);\n\n rest.delete(hold);\n\n return rest;\n};\n\nexport const transition = <V, H, E>(\n state: Core<V, H, E>,\n input: Input<V, H, E>,\n exclusive: boolean,\n): Step<V, H, E> => {\n let next = state;\n const events: Array<readonly [number, State<E>]> = [];\n const commands: Array<Command<V, H>> = [];\n let reply: number | undefined;\n let borrowed: Live<V, H> | undefined;\n\n // Stop `live` serving: its work hears why, and its release starts once that work has let go.\n const end = (live: Live<V, H>, why: Why, detail?: string) => {\n const releasing = live.holds.size === 0;\n\n next = { ...next, ended: new Map(next.ended).set(live.number, { live, why, releasing }) };\n events.push([live.number, { _tag: \"Ending\", why, detail }]);\n commands.push({ _tag: \"End\", live, why });\n if (releasing) commands.push({ _tag: \"Release\", live, why });\n };\n\n // Open `number`, `serving` serving until it opens. An exclusive one starts once none is ending.\n const open = (number: number, serving: Live<V, H> | undefined) => {\n const started = !exclusive || next.ended.size === 0;\n\n next = { _tag: \"Opening\", number, started, serving, ended: next.ended };\n if (started) commands.push({ _tag: \"Open\", number });\n };\n\n switch (input._tag) {\n case \"Try\":\n if (state._tag === \"Opening\" && state.started && state.number === input.number) {\n reply = input.attempt;\n events.push([input.number, { _tag: \"Opening\", attempt: input.attempt }]);\n }\n break;\n case \"Failed\":\n events.push([input.number, { _tag: \"Failed\", attempt: input.attempt, error: input.error }]);\n break;\n case \"GaveUp\": {\n const { number, error, detail } = input;\n\n events.push([number, { _tag: \"Down\", error, detail }]);\n if (state._tag === \"Opening\" && state.number === number)\n next = { _tag: \"Down\", number, error, detail, serving: state.serving, ended: state.ended };\n else if (state._tag === \"Retired\" && state.opening === number)\n next = { ...state, opening: undefined };\n break;\n }\n case \"Stopped\":\n if (state._tag === \"Retired\" && state.opening === input.number) {\n next = { ...state, opening: undefined };\n if (input.began) events.push([input.number, { _tag: \"Closed\" }]);\n }\n break;\n case \"Opened\": {\n const live: Live<V, H> = { number: input.number, value: input.value, holds: new Set() };\n\n events.push([live.number, { _tag: \"Open\" }]);\n commands.push({ _tag: \"Watch\", live });\n if (state._tag === \"Opening\" && state.number === live.number) {\n next = { _tag: \"Open\", serving: live, ended: state.ended };\n if (state.serving !== undefined) end(state.serving, \"rotated\");\n } else {\n // Retired while its try ran: it ends as it opens.\n if (state._tag === \"Retired\") next = { ...state, opening: undefined };\n end(live, \"retired\");\n }\n break;\n }\n case \"Lost\": {\n const serving = servingOf(state);\n\n if (state._tag === \"Retired\" || serving === undefined || serving.number !== input.number)\n break;\n if (state._tag === \"Opening\") next = { ...state, serving: undefined };\n end(serving, \"lost\", input.detail);\n if (state._tag !== \"Opening\")\n open((state._tag === \"Open\" ? serving.number : state.number) + 1, undefined);\n break;\n }\n case \"Rotate\": {\n if (state._tag === \"Retired\") break;\n const serving = state.serving;\n\n if (input.from !== undefined && serving?.number !== input.from) break;\n if (state._tag === \"Opening\") {\n reply = state.number;\n break;\n }\n reply = (state._tag === \"Open\" ? state.serving.number : state.number) + 1;\n if (exclusive && serving !== undefined) end(serving, \"rotated\");\n open(reply, exclusive ? undefined : serving);\n break;\n }\n case \"Retire\": {\n if (state._tag === \"Retired\") break;\n const serving = state.serving;\n\n next = {\n _tag: \"Retired\",\n opening: state._tag === \"Opening\" && state.started ? state.number : undefined,\n ended: state.ended,\n };\n if (serving !== undefined) end(serving, \"retired\");\n commands.push({ _tag: \"Stop\" });\n break;\n }\n case \"Hold\": {\n if (state._tag === \"Retired\" || state.serving === undefined) break;\n const live = { ...state.serving, holds: new Set(state.serving.holds).add(input.hold) };\n\n next = { ...state, serving: live };\n borrowed = live;\n break;\n }\n case \"Let\": {\n const serving = servingOf(state);\n\n if (state._tag !== \"Retired\" && serving?.number === input.number) {\n if (serving.holds.has(input.hold))\n next = { ...state, serving: { ...serving, holds: without(serving.holds, input.hold) } };\n break;\n }\n const ended = state.ended.get(input.number);\n\n if (ended === undefined || !ended.live.holds.has(input.hold)) break;\n const live = { ...ended.live, holds: without(ended.live.holds, input.hold) };\n const releasing = live.holds.size === 0;\n\n next = {\n ...state,\n ended: new Map(state.ended).set(input.number, { ...ended, live, releasing }),\n };\n if (releasing) commands.push({ _tag: \"Release\", live, why: ended.why });\n break;\n }\n case \"Released\": {\n const ended = state.ended.get(input.number);\n\n if (ended === undefined || !ended.releasing) break;\n const rest = new Map(state.ended);\n\n rest.delete(input.number);\n next = { ...state, ended: rest };\n events.push([input.number, { _tag: \"Closed\", released: input.released }]);\n if (next._tag === \"Opening\" && !next.started && rest.size === 0) {\n next = { ...next, started: true };\n commands.push({ _tag: \"Open\", number: next.number });\n }\n break;\n }\n }\n\n return { state: next, events, commands, reply, borrowed };\n};\n\n/** What a caller waiting for a generation gets now: nothing yet while one opens. */\nexport const resolve = <V, H, E>(state: Core<V, H, E>) =>\n state._tag === \"Retired\"\n ? {\n _tag: \"Unavailable\" as const,\n reason: \"retired\" as const,\n error: undefined,\n detail: \"retired\",\n }\n : state.serving !== undefined\n ? { _tag: \"Serve\" as const }\n : state._tag === \"Down\"\n ? {\n _tag: \"Unavailable\" as const,\n reason: \"down\" as const,\n error: state.error,\n detail: state.detail,\n }\n : undefined;\n","/** Scoped acquisition, release and borrowing for the pure resource supervisor lifecycle. */\nimport {\n Cause,\n Clock,\n type Context,\n Deferred,\n Duration,\n Effect,\n Exit,\n Option,\n Schedule,\n Scope,\n Stream,\n SubscriptionRef,\n type Tracer,\n} from \"effect\";\n\nimport { Settled, Unconfirmed } from \"../providers/Released.ts\";\nimport {\n InvalidWait,\n type Lease,\n type Opened,\n type Options,\n type Supervisor,\n Superseded,\n Unavailable,\n type Why,\n} from \"./contract.ts\";\nimport * as Lifecycle from \"./lifecycle.ts\";\n\nexport interface Runtime<A> {\n readonly opened: Opened<A>;\n readonly scope: Scope.Closeable;\n readonly ending: Deferred.Deferred<Why>;\n}\n\nexport type Hold = object;\nexport type State<A, E> = Lifecycle.Core<Runtime<A>, Hold, E>;\n\nexport type Apply<A, E> = (\n input: Lifecycle.Input<Runtime<A>, Hold, E>,\n) => Effect.Effect<Lifecycle.Step<Runtime<A>, Hold, E>>;\n\nexport const describe = (cause: Cause.Cause<unknown>) =>\n Cause.prettyErrors(cause)\n .map((error) => error.message)\n .join(\"; \");\n\nexport const opening =\n <A, E, R>(\n options: Options<A, E, R>,\n context: Context.Context<Exclude<Exclude<R, Scope.Scope>, Tracer.ParentSpan>>,\n own: Scope.Closeable,\n retiring: Deferred.Deferred<void>,\n apply: Apply<A, E>,\n links: ReadonlyArray<Tracer.SpanLink>,\n ) =>\n (number: number) => {\n let attempt = 0;\n let began = false;\n // The last attempt's typed failure. Since Effect 4.0.6, `Effect.retry` rethrows a cause that\n // also holds a defect with its failures made defects, so its exit no longer carries it.\n let failed: Option.Option<E> = Option.none();\n\n const once: Effect.Effect<boolean, E> = Effect.uninterruptible(\n Effect.gen(function* () {\n attempt += 1;\n const admitted = yield* apply({ _tag: \"Try\", number, attempt });\n\n if (admitted.reply === undefined) return false;\n began = true;\n const scope = yield* Scope.fork(own);\n\n const exit = yield* Effect.exit(\n options.open(number).pipe(\n Scope.provide(scope),\n Effect.withSpan(\"Supervisor.open\", {\n root: true,\n links,\n attributes: { generation: number, attempt },\n }),\n Effect.provideContext(context),\n ),\n );\n\n if (Exit.isSuccess(exit)) {\n const ending = Deferred.makeUnsafe<Why>();\n\n yield* apply({ _tag: \"Opened\", number, value: { opened: exit.value, scope, ending } });\n\n return true;\n }\n const closed = yield* Effect.exit(Scope.close(scope, exit));\n\n const cause = Exit.isFailure(closed) ? Cause.combine(exit.cause, closed.cause) : exit.cause;\n const error = Cause.findErrorOption(cause);\n\n failed = error;\n if (Option.isSome(error))\n yield* apply({ _tag: \"Failed\", number, attempt, error: error.value });\n\n return yield* Effect.failCause(cause);\n }),\n );\n\n return Effect.raceFirst(\n Effect.exit(\n Effect.retry(once, {\n schedule:\n options.reopen ??\n Schedule.exponential(\"1 second\").pipe(Schedule.upTo({ duration: \"5 minutes\" })),\n while: (error) => options.definite?.(error) !== true,\n }),\n ),\n Effect.as(Deferred.await(retiring), undefined),\n ).pipe(\n Effect.flatMap((exit) =>\n exit !== undefined && Exit.isSuccess(exit) && exit.value\n ? Effect.void\n : exit !== undefined && Exit.isFailure(exit)\n ? apply({\n _tag: \"GaveUp\",\n number,\n error: Option.getOrUndefined(failed),\n detail: describe(exit.cause),\n })\n : apply({ _tag: \"Stopped\", number, began }),\n ),\n Effect.asVoid,\n );\n };\n\n/** A provider failure or a failed scope close always leaves an Unconfirmed outcome. */\nexport const releasing = <A, E>(apply: Apply<A, E>, links: ReadonlyArray<Tracer.SpanLink>) =>\n Effect.fnUntraced(\n function* (live: Lifecycle.Live<Runtime<A>, Hold>, why: Why) {\n const { opened, scope } = live.value;\n\n const outcome = yield* Effect.suspend(\n () => opened.release?.(why) ?? Effect.succeed(new Settled()),\n ).pipe(\n Effect.catchCause((cause) =>\n Effect.succeed(new Unconfirmed({ detail: `the release failed: ${describe(cause)}` })),\n ),\n );\n\n const closed = yield* Effect.exit(Scope.close(scope, Exit.void));\n\n const released =\n Exit.isSuccess(closed) || outcome._tag !== \"Settled\"\n ? outcome\n : new Unconfirmed({ detail: `its scope failed to close: ${describe(closed.cause)}` });\n\n yield* apply({ _tag: \"Released\", number: live.number, released });\n },\n Effect.uninterruptible,\n Effect.withSpan(\"Supervisor.release\", { root: true, links }),\n );\n\nconst bounded = (input: Duration.Input) =>\n Effect.suspend(() => {\n const duration = Duration.fromInput(input);\n\n return Option.isSome(duration) &&\n Duration.isFinite(duration.value) &&\n !Duration.isNegative(duration.value)\n ? Effect.succeed(duration.value)\n : Effect.fail(new InvalidWait({ detail: \"wait must be a finite nonnegative duration\" }));\n });\n\nexport const leasing =\n <A, E>(\n state: SubscriptionRef.SubscriptionRef<State<A, E>>,\n apply: Apply<A, E>,\n clock: Clock.Clock,\n ): Supervisor<A, E>[\"use\"] =>\n (work, options = {}) =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const hold: Hold = {};\n const wait = options.wait === undefined ? undefined : yield* bounded(options.wait);\n const now = () => Number(clock.monotonicTimeNanosUnsafe()) / 1e6;\n const until = wait === undefined ? undefined : now() + Duration.toMillis(wait);\n let live: Lifecycle.Live<Runtime<A>, Hold> | undefined;\n\n while (live === undefined) {\n const step = yield* apply({ _tag: \"Hold\", hold });\n const resolved = Lifecycle.resolve(step.state);\n\n live = step.borrowed;\n if (live !== undefined) break;\n if (resolved?._tag === \"Unavailable\") return yield* new Unavailable<E>(resolved);\n const remaining = until === undefined ? undefined : Math.max(0, until - now());\n\n if (remaining === 0) return yield* new Cause.TimeoutError();\n\n const changed = SubscriptionRef.changes(state).pipe(\n Stream.filter((s) => Lifecycle.resolve(s) !== undefined),\n Stream.runHead,\n );\n\n yield* restore(\n (remaining === undefined ? changed : Effect.timeout(changed, remaining)).pipe(\n Effect.provideService(Clock.Clock, clock),\n ),\n );\n if (until !== undefined && now() >= until) return yield* new Cause.TimeoutError();\n }\n const { number } = live;\n const { ending, opened } = live.value;\n\n const superseded = Effect.flatMap(Deferred.await(ending), (reason) =>\n Effect.fail(new Superseded({ generation: number, reason })),\n );\n\n const lease: Lease<A> = {\n generation: number,\n value: opened.value,\n ending: Deferred.await(ending),\n lose: (detail) => Effect.asVoid(apply({ _tag: \"Lost\", number, detail })),\n };\n\n return yield* restore(\n Effect.scoped(\n Effect.raceFirst(\n Effect.tap(\n Effect.suspend(() => work(lease)),\n () =>\n Effect.flatMap(Deferred.isDone(ending), (done) =>\n done ? superseded : Effect.void,\n ),\n ),\n superseded,\n ),\n ),\n ).pipe(Effect.ensuring(apply({ _tag: \"Let\", number, hold })));\n }),\n );\n","/**\n * A resource kept serving through typed acquisition failures, loss and rotation.\n * `make` adds its finalizer directly to its caller's scope. Each generation has its own scope;\n * its loss signal remains watched until that scope closes, after release. Optional policies\n * compose by wrapping `open`, `release` and the public generation stream.\n */\nimport {\n Clock,\n Context,\n Deferred,\n Effect,\n Exit,\n FiberSet,\n Option,\n PubSub,\n Scope,\n Semaphore,\n Stream,\n SubscriptionRef,\n type Take,\n Tracer,\n} from \"effect\";\n\nimport { type Generation, type Options, type Supervisor, Unavailable } from \"./contract.ts\";\nimport * as Lifecycle from \"./lifecycle.ts\";\nimport { type Apply, type Hold, type Runtime, leasing, opening, releasing } from \"./runtime.ts\";\n\nexport {\n type Generation,\n InvalidWait,\n type Lease,\n type Opened,\n type Options,\n type State,\n type Supervisor,\n Superseded,\n Unavailable,\n type UseOptions,\n Why,\n} from \"./contract.ts\";\n\nexport const make = Effect.fn(\"Supervisor.make\")(function* <A, E, R>(\n options: Options<A, E, R>,\n): Effect.fn.Return<Supervisor<A, E>, never, Scope.Scope | Exclude<R, Scope.Scope>> {\n const clock = yield* Clock.Clock;\n // The caller span survives as a link, never as the parent of a later generation.\n const context = Context.omit(Tracer.ParentSpan)(yield* Effect.context<Exclude<R, Scope.Scope>>());\n const parent = yield* Effect.serviceOption(Tracer.ParentSpan);\n const links = Option.isSome(parent) ? [{ span: parent.value, attributes: {} }] : [];\n // A parallel caller scope must not close workers alongside retirement.\n const own = yield* Scope.make();\n const started = Lifecycle.start<Runtime<A>, Hold, E>();\n const state = yield* SubscriptionRef.make(started.state);\n const permit = yield* Semaphore.make(1);\n const events = yield* PubSub.unbounded<Take.Take<Generation<E>>>({ replay: 64 });\n const fibers = yield* FiberSet.make().pipe(Scope.provide(own));\n\n const run = yield* FiberSet.runtime(fibers)<never>().pipe(\n Effect.updateContext<never, never>(() => context),\n );\n\n const retiring = Deferred.makeUnsafe<void>();\n const stopped = Deferred.makeUnsafe<void>();\n\n const apply: Apply<A, E> = (input) =>\n permit.withPermit(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const step = Lifecycle.transition(state.value, input, options.exclusive ?? false);\n\n // SubscriptionRef.set wakes retirement's waiter immediately; publish its last outcome first.\n for (const [number, change] of step.events)\n PubSub.publishUnsafe(events, [\n {\n number,\n state: change,\n at: clock.currentTimeMillisUnsafe(),\n hostTime: Number(clock.monotonicTimeNanosUnsafe()) / 1e6,\n },\n ]);\n if (step.state !== state.value) yield* SubscriptionRef.set(state, step.state);\n for (const command of step.commands) yield* perform(command);\n\n return step;\n }),\n ),\n );\n\n const openGeneration = opening<A, E, R>(options, context, own, retiring, apply, links);\n const releaseGeneration = releasing(apply, links);\n\n const perform = (command: Lifecycle.Command<Runtime<A>, Hold>): Effect.Effect<void> => {\n switch (command._tag) {\n case \"Open\":\n return Effect.sync(() => void run(openGeneration(command.number)));\n case \"Watch\": {\n const { number, value } = command.live;\n const { lost } = value.opened;\n\n return lost === undefined\n ? Effect.void\n : Effect.asVoid(\n Effect.forkIn(\n Effect.flatMap(lost, (detail) => apply({ _tag: \"Lost\", number, detail })),\n value.scope,\n ),\n );\n }\n case \"End\":\n return Effect.asVoid(Deferred.succeed(command.live.value.ending, command.why));\n case \"Release\":\n return Effect.sync(() => void run(releaseGeneration(command.live, command.why)));\n case \"Stop\":\n return Deferred.succeed(retiring, undefined).pipe(\n Effect.andThen(Effect.sync(() => void run(stop))),\n );\n }\n };\n\n const rotate = Effect.fnUntraced(function* (from?: number) {\n const step = yield* apply({ _tag: \"Rotate\", from });\n const target = step.reply;\n\n if (target === undefined)\n return step.state._tag === \"Retired\"\n ? yield* new Unavailable<E>({ reason: \"retired\", detail: \"retired\" })\n : undefined;\n\n const reached = (s: typeof step.state) =>\n s._tag === \"Retired\"\n ? new Unavailable<E>({ reason: \"retired\", detail: \"retired\" })\n : s._tag === \"Down\" && s.number >= target\n ? new Unavailable<E>({ reason: \"down\", error: s.error, detail: s.detail })\n : s._tag === \"Open\" && s.serving.number >= target\n ? (\"served\" as const)\n : undefined;\n\n const outcome = yield* Stream.runHead(\n Stream.filter(Stream.map(SubscriptionRef.changes(state), reached), (r) => r !== undefined),\n );\n\n if (Option.isSome(outcome) && outcome.value !== \"served\") return yield* outcome.value;\n });\n\n const stop = Effect.gen(function* () {\n yield* Stream.runHead(\n Stream.filter(\n SubscriptionRef.changes(state),\n (s) => s._tag === \"Retired\" && s.opening === undefined && s.ended.size === 0,\n ),\n );\n yield* PubSub.publish(events, Exit.void);\n }).pipe(Effect.ensuring(Deferred.succeed(stopped, undefined)));\n\n // Commit the transition even if its caller is interrupted while waiting for the state lock.\n const retire = apply({ _tag: \"Retire\" }).pipe(\n Effect.uninterruptible,\n Effect.andThen(Deferred.await(stopped)),\n );\n\n yield* Effect.addFinalizer((exit) => retire.pipe(Effect.ensuring(Scope.close(own, exit))));\n yield* Effect.forEach(started.commands, perform, { discard: true });\n\n return {\n use: leasing(state, apply, clock),\n states: Stream.fromPubSubTake(events),\n rotate,\n retire,\n };\n});\n"],"mappings":";;;;;AAeA,MAAa,MAAM,OAAO,SAAS;CAAC;CAAQ;CAAW;AAAS,CAAC;;AAyCjE,IAAa,cAAb,cAA8C,KAAK,YAAY,aAAa,CAAC,CAI1E;CACD,IAAa,UAAU;EACrB,OAAO,gBAAgB,KAAK;CAC9B;AACF;;AAGA,IAAa,aAAb,cAAgC,OAAO,YAAwB,CAAC,CAAC,cAAc;CAC7E,YAAY,OAAO;CACnB,QAAQ;AACV,CAAC,CAAC,CAAC,CAAC;;AAWJ,IAAa,cAAb,cAAiC,KAAK,YAAY,aAAa,CAAC,CAA8B,CAAC;;;ACF/F,MAAa,eAAuC;CAClD,OAAO;EAAE,MAAM;EAAW,QAAQ;EAAG,SAAS;EAAM,SAAS,KAAA;EAAW,uBAAO,IAAI,IAAI;CAAE;CACzF,QAAQ,CAAC;CACT,UAAU,CAAC;EAAE,MAAM;EAAQ,QAAQ;CAAE,CAAC;AACxC;AAEA,MAAa,aAAsB,UACjC,MAAM,SAAS,YAAY,KAAA,IAAY,MAAM;AAE/C,MAAM,WAAc,OAAuB,SAAY;CACrD,MAAM,OAAO,IAAI,IAAI,KAAK;CAE1B,KAAK,OAAO,IAAI;CAEhB,OAAO;AACT;AAEA,MAAa,cACX,OACA,OACA,cACkB;CAClB,IAAI,OAAO;CACX,MAAM,SAA6C,CAAC;CACpD,MAAM,WAAiC,CAAC;CACxC,IAAI;CACJ,IAAI;CAGJ,MAAM,OAAO,MAAkB,KAAU,WAAoB;EAC3D,MAAM,YAAY,KAAK,MAAM,SAAS;EAEtC,OAAO;GAAE,GAAG;GAAM,OAAO,IAAI,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,KAAK,QAAQ;IAAE;IAAM;IAAK;GAAU,CAAC;EA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SAAS,MAAM,EAAE,MAAM,SAAS,CAAC,CAAC,CAAC,KACvC,OAAO,iBACP,OAAO,QAAQ,SAAS,MAAM,OAAO,CAAC,CACxC;CAEA,OAAO,OAAO,cAAc,SAAS,OAAO,KAAK,OAAO,SAAS,MAAM,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC;CACzF,OAAO,OAAO,QAAQ,QAAQ,UAAU,SAAS,EAAE,SAAS,KAAK,CAAC;CAElE,OAAO;EACL,KAAK,QAAQ,OAAO,OAAO,KAAK;EAChC,QAAQ,OAAO,eAAe,MAAM;EACpC;EACA;CACF;AACF,CAAC"}
@@ -8,7 +8,7 @@ import { c as State, g as make$4, l as Text, r as Found, s as ResolvedTarget } f
8
8
  import { Control, Snapshot } from "../Snapshot.mjs";
9
9
  import { checked, methods } from "../ActionPort.mjs";
10
10
  import { monotonicMillis } from "../Clock.mjs";
11
- import { a as make$5, o as fold, r as Suspension, s as make$6 } from "../Browser-Cq2K1FEA.mjs";
11
+ import { a as make$5, o as fold, r as Suspension, s as make$6 } from "../Browser-BKPAbyys.mjs";
12
12
  import { match, request } from "../Matching.mjs";
13
13
  import { Change, Changes } from "../Change.mjs";
14
14
  import { Clock, Deferred, Duration, Effect, Exit, Option, PubSub, Scope, Semaphore, Stream } from "effect";
@@ -1,4 +1,4 @@
1
- import { t as make } from "../connection-BTeO0Hiz.mjs";
1
+ import { t as make } from "../connection-CK83pvqP.mjs";
2
2
  //#region src/workerd/Cdp.ts
3
3
  /**
4
4
  * CDP lifetime for Workers. The consumer supplies a runtime-compatible Playwright connector;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-browser",
3
- "version": "0.3.0-beta.22",
3
+ "version": "0.3.0-beta.23",
4
4
  "description": "Effect browser sessions, page control, screencast and moments over Playwright and CDP.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -175,9 +175,9 @@
175
175
  "test": "vp test --run"
176
176
  },
177
177
  "devDependencies": {
178
- "@effect/vitest": "4.0.3",
178
+ "@effect/vitest": "4.1.2",
179
179
  "@types/node": "26.1.2",
180
- "effect": "4.0.3",
180
+ "effect": "4.1.2",
181
181
  "esbuild": "0.28.2",
182
182
  "playwright-core": "1.63.0",
183
183
  "typescript": "7.0.2",
@@ -186,7 +186,7 @@
186
186
  "vitest": "5.0.3"
187
187
  },
188
188
  "peerDependencies": {
189
- "effect": "~4.0.3",
189
+ "effect": "~4.1.2",
190
190
  "playwright-core": "^1.63.0"
191
191
  },
192
192
  "engines": {
@@ -1,5 +1,6 @@
1
- /** Connection identity uses the supplied Crypto service, or the host's Web Crypto on Node/Bun. */
2
- import { Crypto, Effect, Option } from "effect";
1
+ /** Connection identity uses the supplied SecureRandom service, or the host's Web Crypto on Node/Bun. */
2
+ import { Effect, Option } from "effect";
3
+ import { SecureRandom } from "effect/crypto";
3
4
 
4
5
  import { Failed } from "../../BrowserError.ts";
5
6
  import { undispatched } from "./context.ts";
@@ -7,10 +8,10 @@ import { undispatched } from "./context.ts";
7
8
  const failed = () => undispatched("make", new Failed({ detail: "Could not name connection" }));
8
9
 
9
10
  export const make = Effect.gen(function* () {
10
- const supplied = yield* Effect.serviceOption(Crypto.Crypto);
11
+ const supplied = yield* Effect.serviceOption(SecureRandom.SecureRandom);
11
12
 
12
13
  return yield* Option.isSome(supplied)
13
- ? supplied.value.randomUUIDv4().pipe(Effect.mapError(failed))
14
- : // oxlint-disable-next-line no-restricted-properties -- this host fallback runs only when the captured Effect Crypto service is absent
14
+ ? supplied.value.uuidV4()
15
+ : // oxlint-disable-next-line no-restricted-properties -- this host fallback runs only when the captured SecureRandom service is absent
15
16
  Effect.try({ try: () => globalThis.crypto.randomUUID(), catch: failed });
16
17
  });
@@ -58,6 +58,9 @@ export const opening =
58
58
  (number: number) => {
59
59
  let attempt = 0;
60
60
  let began = false;
61
+ // The last attempt's typed failure. Since Effect 4.0.6, `Effect.retry` rethrows a cause that
62
+ // also holds a defect with its failures made defects, so its exit no longer carries it.
63
+ let failed: Option.Option<E> = Option.none();
61
64
 
62
65
  const once: Effect.Effect<boolean, E> = Effect.uninterruptible(
63
66
  Effect.gen(function* () {
@@ -92,6 +95,7 @@ export const opening =
92
95
  const cause = Exit.isFailure(closed) ? Cause.combine(exit.cause, closed.cause) : exit.cause;
93
96
  const error = Cause.findErrorOption(cause);
94
97
 
98
+ failed = error;
95
99
  if (Option.isSome(error))
96
100
  yield* apply({ _tag: "Failed", number, attempt, error: error.value });
97
101
 
@@ -117,7 +121,7 @@ export const opening =
117
121
  ? apply({
118
122
  _tag: "GaveUp",
119
123
  number,
120
- error: Option.getOrUndefined(Cause.findErrorOption(exit.cause)),
124
+ error: Option.getOrUndefined(failed),
121
125
  detail: describe(exit.cause),
122
126
  })
123
127
  : apply({ _tag: "Stopped", number, began }),