functype-react 1.7.0 → 1.8.0

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/README.md CHANGED
@@ -213,7 +213,7 @@ Both read only the fields they project. For **queries** that matters: React Quer
213
213
  Two behaviours worth knowing before you rely on the ADT:
214
214
 
215
215
  - **A failed background refetch projects to `Failure` even though React Query still holds the last successful `data`.** `TaskState` has no "loaded but stale" variant. This is the deliberate default — it never silently hides a failure — but it does mean a transient refetch error flips a loaded view to the error branch. To keep rendering stale data, read `query.data` alongside the projection or branch on `query.isRefetchError` before projecting.
216
- - **If your effect factory throws synchronously** (before an `IO` is produced), the rejection is still boxed, but with `defect: true` and `.error` holding the raw thrown value rather than an `E`. Check `defect` before matching on `_tag` if that's reachable in your code.
216
+ - **`defect: true` means `.error` is not an `E`** — check it before matching on `_tag`. It is set when the effect factory throws before an `IO` is produced, when the effect produces a defect (`Exit.Die`: a throwing `IO.sync` thunk, a throwing `map`/`flatMap`/`mapError` callback, or `IO.die`), or when the effect is interrupted. Conversely `defect: false` genuinely means `.error` is an `E` — the bridge reads `runExit()`, so it can see the difference. (It previously read `run()`, whose `Either` could not, so a defect arrived indistinguishable from a typed failure and the flag read `false`.)
217
217
 
218
218
  Mutations mirror the shape (React Query supplies no `AbortSignal` to mutations, so the callback takes only the variables):
219
219
 
@@ -250,7 +250,7 @@ useInfiniteQuery({
250
250
  })
251
251
  ```
252
252
 
253
- Both the hooks and the primitives are generic over any `IO<never, E, A>` — nothing here is HTTP-specific. `Error.message` is derived structurally (`formatIOError`); pass `formatError` to override it.
253
+ Both the hooks and the primitives are generic over any `IO<never, E, A>` — nothing here is HTTP-specific. `Error.message` is derived structurally (`formatIOError`); pass `formatError` to override it. The derivation prefers, in order: a raw `Error`'s `.message`, the HTTP shape (`HTTP 403 Forbidden — /api/x`) for anything carrying a numeric `status`, a tagged error's own `message`, then the bare `_tag`, then JSON.
254
254
 
255
255
  ## Compatibility
256
256
 
@@ -29,16 +29,25 @@ declare class IOQueryError<E> extends Error {
29
29
  /**
30
30
  * The raw functype error channel value — discriminable via its own `_tag`.
31
31
  *
32
- * When {@link defect} is `true` this is **not** an `E`: it is whatever the effect
33
- * factory threw before an `IO` was ever produced. Check `defect` before matching
34
- * on `_tag` if your factory can throw synchronously.
32
+ * When {@link defect} is `true` this is **not** an `E`. Check `defect` before
33
+ * matching on `_tag`.
35
34
  */
36
35
  readonly error: E;
37
36
  /**
38
- * `true` when this wraps an unexpected throw rather than a value from the effect's
39
- * typed error channel — i.e. the effect factory itself threw. Kept as an explicit
40
- * flag rather than widening `E` to `unknown`, which would force every consumer to
41
- * handle a case that should never occur.
37
+ * `true` when {@link error} is *not* a value from the effect's typed error channel.
38
+ * Three things set it:
39
+ *
40
+ * - the effect factory threw before an `IO` was ever produced
41
+ * - the effect produced a defect (`Exit.Die`) — a throwing `IO.sync` thunk, a
42
+ * throwing `map` / `flatMap` / `mapError` callback, or `IO.die`
43
+ * - the effect was interrupted, so `error` is an `InterruptedError`
44
+ *
45
+ * Kept as an explicit flag rather than widening `E` to `unknown`, which would force
46
+ * every consumer to handle a case that should never occur.
47
+ *
48
+ * `defect: false` genuinely means `error` is an `E`. Before 1.8.0 it did not: a
49
+ * defect reached the adapter as an ordinary `Left` and was indistinguishable from a
50
+ * typed failure, so the documented guard didn't guard anything (#259).
42
51
  */
43
52
  readonly defect: boolean;
44
53
  constructor(error: E, message?: string, defect?: boolean);
@@ -1,2 +1,2 @@
1
- import{Try as e}from"functype";const t=e=>typeof e==`object`&&!!e&&`_tag`in e&&typeof e._tag==`string`,n=n=>{if(n instanceof Error)return n.message;if(t(n)){let e=typeof n.url==`string`?` — ${n.url}`:``;if(typeof n.status==`number`){let t=typeof n.statusText==`string`&&n.statusText.length>0?` ${n.statusText}`:``;return`HTTP ${n.status}${t}${e}`}return`${n._tag}${e}`}return typeof n==`object`&&n?e(()=>JSON.stringify(n)).orElse(String(n)):String(n)};var r=class extends Error{constructor(e,t,r=!1){super(t??n(e),{cause:e}),this.name=`IOQueryError`,this.error=e,this.defect=r}};const i=e=>e instanceof r;export{r as IOQueryError,n as formatIOError,i as isIOQueryError};
1
+ import{Try as e}from"functype";const t=e=>typeof e==`object`&&!!e&&`_tag`in e&&typeof e._tag==`string`,n=n=>{if(n instanceof Error)return n.message;if(t(n)){let e=typeof n.url==`string`?` — ${n.url}`:``;if(typeof n.status==`number`){let t=typeof n.statusText==`string`&&n.statusText.length>0?` ${n.statusText}`:``;return`HTTP ${n.status}${t}${e}`}return typeof n.message==`string`&&n.message.length>0?n.message:`${n._tag}${e}`}return typeof n==`object`&&n?e(()=>JSON.stringify(n)).orElse(String(n)):String(n)};var r=class extends Error{constructor(e,t,r=!1){super(t??n(e),{cause:e}),this.name=`IOQueryError`,this.error=e,this.defect=r}};const i=e=>e instanceof r;export{r as IOQueryError,n as formatIOError,i as isIOQueryError};
2
2
  //# sourceMappingURL=IOQueryError.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"IOQueryError.js","names":[],"sources":["../../src/query/IOQueryError.ts"],"sourcesContent":["/**\n * Error boxing for the React Query bridge.\n *\n * `IO`'s own terminals don't fit React Query's contract: `.run()` returns\n * `Promise<Either<E, A>>` and never throws (so RQ never sees a failure), while\n * `.runOrThrow()` throws the *raw* tagged error object — `{ _tag: \"NetworkError\", ... }`\n * is not an `Error` instance, so the ubiquitous\n * `error instanceof Error ? error.message : fallback` handler silently degrades.\n *\n * `IOQueryError` boxes the typed error so both worlds work: `instanceof Error` and\n * `.message` behave as any React Query consumer expects, while `.error` preserves the\n * fully discriminable functype `E`.\n */\nimport { Try } from \"functype\"\n\n/** Structural view of a tagged functype error (e.g. any `HttpError` variant). */\ntype TaggedError = {\n readonly _tag: string\n readonly url?: unknown\n readonly status?: unknown\n readonly statusText?: unknown\n}\n\nconst isTaggedError = (e: unknown): e is TaggedError =>\n typeof e === \"object\" && e !== null && \"_tag\" in e && typeof (e as { _tag: unknown })._tag === \"string\"\n\n/**\n * Derives a human-readable message from an arbitrary error channel value.\n *\n * Deliberately *structural* — this module does not import `functype/fetch`, so the\n * query bridge stays generic over any `IO<never, E, A>` rather than being HTTP-specific.\n * An `HttpStatusError` is recognized by its shape, not its type.\n *\n * Pass `formatError` to any of the query entry points to override this entirely.\n */\nexport const formatIOError = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message\n }\n\n if (isTaggedError(error)) {\n const where = typeof error.url === \"string\" ? ` — ${error.url}` : \"\"\n\n if (typeof error.status === \"number\") {\n const statusText =\n typeof error.statusText === \"string\" && error.statusText.length > 0 ? ` ${error.statusText}` : \"\"\n return `HTTP ${error.status}${statusText}${where}`\n }\n\n return `${error._tag}${where}`\n }\n\n // `String({})` is \"[object Object]\", which tells a reader nothing. Prefer a JSON\n // rendering for plain objects, falling back to String() for cycles and symbols.\n if (typeof error === \"object\" && error !== null) {\n return Try(() => JSON.stringify(error)).orElse(String(error))\n }\n\n return String(error)\n}\n\n/**\n * An `Error` subclass carrying the typed functype error channel.\n *\n * ```ts\n * const { error } = useIOQuery([\"limits\", userId], ({ signal }) => Http.get(url, { signal }))\n *\n * error instanceof Error // true\n * error.message // \"HTTP 403 Forbidden — /api/limits\"\n *\n * HttpErrors.match(error.error, {\n * NetworkError: (e) => retryBanner(e),\n * HttpStatusError: (e) => (e.status === 403 ? upgradePrompt() : genericFailure(e)),\n * DecodeError: (e) => reportSchemaDrift(e),\n * })\n * ```\n */\nexport class IOQueryError<E> extends Error {\n /**\n * The raw functype error channel value — discriminable via its own `_tag`.\n *\n * When {@link defect} is `true` this is **not** an `E`: it is whatever the effect\n * factory threw before an `IO` was ever produced. Check `defect` before matching\n * on `_tag` if your factory can throw synchronously.\n */\n readonly error: E\n\n /**\n * `true` when this wraps an unexpected throw rather than a value from the effect's\n * typed error channel — i.e. the effect factory itself threw. Kept as an explicit\n * flag rather than widening `E` to `unknown`, which would force every consumer to\n * handle a case that should never occur.\n */\n readonly defect: boolean\n\n constructor(error: E, message?: string, defect = false) {\n super(message ?? formatIOError(error), { cause: error })\n this.name = \"IOQueryError\"\n this.error = error\n this.defect = defect\n }\n}\n\n/** Runtime guard for {@link IOQueryError}. */\nexport const isIOQueryError = <E = unknown>(error: unknown): error is IOQueryError<E> => error instanceof IOQueryError\n"],"mappings":"+BAuBA,MAAM,EAAiB,GACrB,OAAO,GAAM,YAAY,GAAc,SAAU,GAAK,OAAQ,EAAwB,MAAS,SAWpF,EAAiB,GAA2B,CACvD,GAAI,aAAiB,MACnB,OAAO,EAAM,QAGf,GAAI,EAAc,CAAK,EAAG,CACxB,IAAM,EAAQ,OAAO,EAAM,KAAQ,SAAW,MAAM,EAAM,MAAQ,GAElE,GAAI,OAAO,EAAM,QAAW,SAAU,CACpC,IAAM,EACJ,OAAO,EAAM,YAAe,UAAY,EAAM,WAAW,OAAS,EAAI,IAAI,EAAM,aAAe,GACjG,MAAO,QAAQ,EAAM,SAAS,IAAa,GAC7C,CAEA,MAAO,GAAG,EAAM,OAAO,GACzB,CAQA,OAJI,OAAO,GAAU,UAAY,EACxB,MAAU,KAAK,UAAU,CAAK,CAAC,CAAC,CAAC,OAAO,OAAO,CAAK,CAAC,EAGvD,OAAO,CAAK,CACrB,EAkBA,IAAa,EAAb,cAAqC,KAAM,CAkBzC,YAAY,EAAU,EAAkB,EAAS,GAAO,CACtD,MAAM,GAAW,EAAc,CAAK,EAAG,CAAE,MAAO,CAAM,CAAC,EACvD,KAAK,KAAO,eACZ,KAAK,MAAQ,EACb,KAAK,OAAS,CAChB,CACF,EAGA,MAAa,EAA+B,GAA6C,aAAiB"}
1
+ {"version":3,"file":"IOQueryError.js","names":[],"sources":["../../src/query/IOQueryError.ts"],"sourcesContent":["/**\n * Error boxing for the React Query bridge.\n *\n * `IO`'s own terminals don't fit React Query's contract: `.run()` returns\n * `Promise<Either<E, A>>` and never throws (so RQ never sees a failure), while\n * `.runOrThrow()` throws the *raw* tagged error object — `{ _tag: \"NetworkError\", ... }`\n * is not an `Error` instance, so the ubiquitous\n * `error instanceof Error ? error.message : fallback` handler silently degrades.\n *\n * `IOQueryError` boxes the typed error so both worlds work: `instanceof Error` and\n * `.message` behave as any React Query consumer expects, while `.error` preserves the\n * fully discriminable functype `E`.\n */\nimport { Try } from \"functype\"\n\n/** Structural view of a tagged functype error (e.g. any `HttpError` variant). */\ntype TaggedError = {\n readonly _tag: string\n readonly url?: unknown\n readonly status?: unknown\n readonly statusText?: unknown\n readonly message?: unknown\n}\n\nconst isTaggedError = (e: unknown): e is TaggedError =>\n typeof e === \"object\" && e !== null && \"_tag\" in e && typeof (e as { _tag: unknown })._tag === \"string\"\n\n/**\n * Derives a human-readable message from an arbitrary error channel value.\n *\n * Deliberately *structural* — this module does not import `functype/fetch`, so the\n * query bridge stays generic over any `IO<never, E, A>` rather than being HTTP-specific.\n * An `HttpStatusError` is recognized by its shape, not its type.\n *\n * Pass `formatError` to any of the query entry points to override this entirely.\n */\nexport const formatIOError = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message\n }\n\n if (isTaggedError(error)) {\n const where = typeof error.url === \"string\" ? ` — ${error.url}` : \"\"\n\n if (typeof error.status === \"number\") {\n const statusText =\n typeof error.statusText === \"string\" && error.statusText.length > 0 ? ` ${error.statusText}` : \"\"\n return `HTTP ${error.status}${statusText}${where}`\n }\n\n // A tagged error carrying its own `message` is the normal shape for a domain error\n // in the `IO` channel, and that message is what the author wrote for a human to\n // read. Falling back to the bare tag was the one case where information already\n // present got discarded — a raw `Error` gets `.message`, an untagged object gets\n // JSON, but a tagged one got neither. None of functype's own `HttpError` variants\n // carry a `message`, so the HTTP renderings above are unaffected.\n if (typeof error.message === \"string\" && error.message.length > 0) {\n return error.message\n }\n\n return `${error._tag}${where}`\n }\n\n // `String({})` is \"[object Object]\", which tells a reader nothing. Prefer a JSON\n // rendering for plain objects, falling back to String() for cycles and symbols.\n if (typeof error === \"object\" && error !== null) {\n return Try(() => JSON.stringify(error)).orElse(String(error))\n }\n\n return String(error)\n}\n\n/**\n * An `Error` subclass carrying the typed functype error channel.\n *\n * ```ts\n * const { error } = useIOQuery([\"limits\", userId], ({ signal }) => Http.get(url, { signal }))\n *\n * error instanceof Error // true\n * error.message // \"HTTP 403 Forbidden — /api/limits\"\n *\n * HttpErrors.match(error.error, {\n * NetworkError: (e) => retryBanner(e),\n * HttpStatusError: (e) => (e.status === 403 ? upgradePrompt() : genericFailure(e)),\n * DecodeError: (e) => reportSchemaDrift(e),\n * })\n * ```\n */\nexport class IOQueryError<E> extends Error {\n /**\n * The raw functype error channel value — discriminable via its own `_tag`.\n *\n * When {@link defect} is `true` this is **not** an `E`. Check `defect` before\n * matching on `_tag`.\n */\n readonly error: E\n\n /**\n * `true` when {@link error} is *not* a value from the effect's typed error channel.\n * Three things set it:\n *\n * - the effect factory threw before an `IO` was ever produced\n * - the effect produced a defect (`Exit.Die`) — a throwing `IO.sync` thunk, a\n * throwing `map` / `flatMap` / `mapError` callback, or `IO.die`\n * - the effect was interrupted, so `error` is an `InterruptedError`\n *\n * Kept as an explicit flag rather than widening `E` to `unknown`, which would force\n * every consumer to handle a case that should never occur.\n *\n * `defect: false` genuinely means `error` is an `E`. Before 1.8.0 it did not: a\n * defect reached the adapter as an ordinary `Left` and was indistinguishable from a\n * typed failure, so the documented guard didn't guard anything (#259).\n */\n readonly defect: boolean\n\n constructor(error: E, message?: string, defect = false) {\n super(message ?? formatIOError(error), { cause: error })\n this.name = \"IOQueryError\"\n this.error = error\n this.defect = defect\n }\n}\n\n/** Runtime guard for {@link IOQueryError}. */\nexport const isIOQueryError = <E = unknown>(error: unknown): error is IOQueryError<E> => error instanceof IOQueryError\n"],"mappings":"+BAwBA,MAAM,EAAiB,GACrB,OAAO,GAAM,YAAY,GAAc,SAAU,GAAK,OAAQ,EAAwB,MAAS,SAWpF,EAAiB,GAA2B,CACvD,GAAI,aAAiB,MACnB,OAAO,EAAM,QAGf,GAAI,EAAc,CAAK,EAAG,CACxB,IAAM,EAAQ,OAAO,EAAM,KAAQ,SAAW,MAAM,EAAM,MAAQ,GAElE,GAAI,OAAO,EAAM,QAAW,SAAU,CACpC,IAAM,EACJ,OAAO,EAAM,YAAe,UAAY,EAAM,WAAW,OAAS,EAAI,IAAI,EAAM,aAAe,GACjG,MAAO,QAAQ,EAAM,SAAS,IAAa,GAC7C,CAYA,OAJI,OAAO,EAAM,SAAY,UAAY,EAAM,QAAQ,OAAS,EACvD,EAAM,QAGR,GAAG,EAAM,OAAO,GACzB,CAQA,OAJI,OAAO,GAAU,UAAY,EACxB,MAAU,KAAK,UAAU,CAAK,CAAC,CAAC,CAAC,OAAO,OAAO,CAAK,CAAC,EAGvD,OAAO,CAAK,CACrB,EAkBA,IAAa,EAAb,cAAqC,KAAM,CA2BzC,YAAY,EAAU,EAAkB,EAAS,GAAO,CACtD,MAAM,GAAW,EAAc,CAAK,EAAG,CAAE,MAAO,CAAM,CAAC,EACvD,KAAK,KAAO,eACZ,KAAK,MAAQ,EACb,KAAK,OAAS,CAChB,CACF,EAGA,MAAa,EAA+B,GAA6C,aAAiB"}
@@ -1,2 +1,2 @@
1
- import{IOQueryError as e}from"./IOQueryError.js";import{Try as t}from"functype";const n=async(n,r)=>{let i=await t(()=>n()).fold(t=>{throw new e(t,void 0,!0)},e=>e.run());if(i.isLeft())throw new e(i.value,r?.formatError?.(i.value));return i.value},r=(e,t)=>r=>n(()=>e(r),t),i=(e,t)=>r=>n(()=>e(r),t);export{i as ioMutationFn,r as ioQueryFn};
1
+ import{IOQueryError as e}from"./IOQueryError.js";import{Try as t}from"functype";import{InterruptedError as n}from"functype/io";const r=async(r,i)=>{let a=await t(()=>r()).fold(t=>{throw new e(t,void 0,!0)},e=>e.runExit());if(a.isFailure()){let{error:t}=a.toValue();throw new e(t,i?.formatError?.(t))}if(a.isDie())throw new e(a.toValue().defect,void 0,!0);if(a.isInterrupted())throw new e(new n,void 0,!0);return a.orThrow()},i=(e,t)=>n=>r(()=>e(n),t),a=(e,t)=>n=>r(()=>e(n),t);export{a as ioMutationFn,i as ioQueryFn};
2
2
  //# sourceMappingURL=ioQueryFn.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ioQueryFn.js","names":[],"sources":["../../src/query/ioQueryFn.ts"],"sourcesContent":["/* eslint-disable functype/prefer-either -- This module IS the Either→rejection bridge.\n * React Query signals failure exclusively by promise rejection: `isError`, `onError`,\n * and retry all key off a rejected queryFn. Returning an `Either` here would be\n * indistinguishable from success to React Query — the very bug (see #239) that makes\n * `.run()` unusable as a `queryFn`. The throw is the contract, and it is confined to\n * `runBoxed` so no caller ever has to write it. Scoped to the file rather than to each\n * `throw` because the rule also fires on the enclosing function: three scattered\n * suppressions would read as incidental exceptions rather than one deliberate design. */\nimport { Try } from \"functype\"\nimport type { IO } from \"functype/io\"\n\nimport { IOQueryError } from \"./IOQueryError\"\n\n/**\n * Minimal structural view of React Query's `QueryFunctionContext` — the floor that\n * every context satisfies, and the default when nothing wider is inferred.\n *\n * Typed structurally on purpose, so these primitives carry **no**\n * `@tanstack/react-query` type dependency. `ioQueryFn` is generic over the context, so\n * a richer one flows through unchanged: annotate the callback parameter (e.g. with\n * `QueryFunctionContext<QueryKey, number>` for an infinite query) and `pageParam`,\n * `queryKey`, and `meta` are all readable inside the effect factory.\n */\nexport type IOQueryFnContext = {\n readonly signal: AbortSignal\n}\n\nexport type IOBridgeOptions<E> = {\n /** Override the derived `Error.message`. Defaults to a structural formatter. */\n readonly formatError?: (error: E) => string\n}\n\n/**\n * Runs an effect and returns its value, or throws a boxed {@link IOQueryError}.\n *\n * Two failure paths converge here:\n * - the effect's typed error channel (`Left`) → boxed with `defect: false`\n * - the factory throwing before an `IO` exists → boxed with `defect: true`\n *\n * The second matters because `.run()` itself never throws (defects raised *inside*\n * the effect are folded into `Left` by the interpreter), but `io(input)` is ordinary\n * user code that can throw while building the effect. Without this, that throw would\n * escape unboxed and `error.error` would be `undefined` despite the declared type.\n */\nconst runBoxed = async <E, A>(effect: () => IO<never, E, A>, options?: IOBridgeOptions<E>): Promise<A> => {\n const result = await Try(() => effect()).fold(\n (thrown) => {\n throw new IOQueryError(thrown as E, undefined, true)\n },\n (io) => io.run(),\n )\n\n if (result.isLeft()) {\n throw new IOQueryError(result.value, options?.formatError?.(result.value))\n }\n\n return result.value\n}\n\n/**\n * Adapts an `IO<never, E, A>` into a React Query `queryFn`.\n *\n * `Right` resolves with the value; `Left` rejects with an {@link IOQueryError} that\n * carries the typed error on `.error`. Wire cancellation by closing over the supplied\n * `signal`:\n *\n * ```ts\n * useQuery({\n * queryKey: [\"connector-limits\", userId],\n * queryFn: ioQueryFn(({ signal }) => Http.get<Limits>(url, { headers, signal })),\n * enabled: !!userId,\n * })\n * ```\n */\nexport const ioQueryFn =\n <E, A, TContext extends IOQueryFnContext = IOQueryFnContext>(\n io: (context: TContext) => IO<never, E, A>,\n options?: IOBridgeOptions<E>,\n ) =>\n (context: TContext): Promise<A> =>\n runBoxed(() => io(context), options)\n\n/**\n * Adapts a variables-taking `IO<never, E, A>` into a React Query `mutationFn`.\n *\n * React Query does not supply an `AbortSignal` to mutations, so the callback receives\n * only the mutation variables.\n *\n * ```ts\n * useMutation({\n * mutationFn: ioMutationFn((body: CreateTokenInput) => Http.post<Token>(url, { body })),\n * })\n * ```\n */\nexport const ioMutationFn =\n <E, A, V = void>(io: (variables: V) => IO<never, E, A>, options?: IOBridgeOptions<E>) =>\n (variables: V): Promise<A> =>\n runBoxed(() => io(variables), options)\n"],"mappings":"gFA4CA,MAAM,EAAW,MAAa,EAA+B,IAA6C,CACxG,IAAM,EAAS,MAAM,MAAU,EAAO,CAAC,CAAC,CAAC,KACtC,GAAW,CACV,MAAM,IAAI,EAAa,EAAa,IAAA,GAAW,EAAI,CACrD,EACC,GAAO,EAAG,IAAI,CACjB,EAEA,GAAI,EAAO,OAAO,EAChB,MAAM,IAAI,EAAa,EAAO,MAAO,GAAS,cAAc,EAAO,KAAK,CAAC,EAG3E,OAAO,EAAO,KAChB,EAiBa,GAET,EACA,IAED,GACC,MAAe,EAAG,CAAO,EAAG,CAAO,EAc1B,GACM,EAAuC,IACvD,GACC,MAAe,EAAG,CAAS,EAAG,CAAO"}
1
+ {"version":3,"file":"ioQueryFn.js","names":[],"sources":["../../src/query/ioQueryFn.ts"],"sourcesContent":["/* eslint-disable functype/prefer-either -- This module IS the Either→rejection bridge.\n * React Query signals failure exclusively by promise rejection: `isError`, `onError`,\n * and retry all key off a rejected queryFn. Returning an `Either` here would be\n * indistinguishable from success to React Query — the very bug (see #239) that makes\n * `.run()` unusable as a `queryFn`. The throw is the contract, and it is confined to\n * `runBoxed` so no caller ever has to write it. Scoped to the file rather than to each\n * `throw` because the rule also fires on the enclosing function: three scattered\n * suppressions would read as incidental exceptions rather than one deliberate design. */\nimport { Try } from \"functype\"\nimport { InterruptedError, type IO } from \"functype/io\"\n\nimport { IOQueryError } from \"./IOQueryError\"\n\n/**\n * Minimal structural view of React Query's `QueryFunctionContext` — the floor that\n * every context satisfies, and the default when nothing wider is inferred.\n *\n * Typed structurally on purpose, so these primitives carry **no**\n * `@tanstack/react-query` type dependency. `ioQueryFn` is generic over the context, so\n * a richer one flows through unchanged: annotate the callback parameter (e.g. with\n * `QueryFunctionContext<QueryKey, number>` for an infinite query) and `pageParam`,\n * `queryKey`, and `meta` are all readable inside the effect factory.\n */\nexport type IOQueryFnContext = {\n readonly signal: AbortSignal\n}\n\nexport type IOBridgeOptions<E> = {\n /** Override the derived `Error.message`. Defaults to a structural formatter. */\n readonly formatError?: (error: E) => string\n}\n\n/**\n * Runs an effect and returns its value, or throws a boxed {@link IOQueryError}.\n *\n * Three failure paths converge here:\n * - the effect's typed error channel (`Failure`) → boxed with `defect: false`\n * - a defect raised *inside* the effect (`Die`) → boxed with `defect: true`\n * - the factory throwing before an `IO` exists → boxed with `defect: true`\n *\n * The third matters because running an effect never throws, but `io(input)` is\n * ordinary user code that can throw while building the effect. Without this, that\n * throw would escape unboxed and `error.error` would be `undefined` despite the\n * declared type.\n *\n * The second is why this uses `runExit()` rather than `run()`. `run()` returns\n * `Either<E, A>`, which has nowhere to put a defect — a throwing `mapError` handler or\n * `IO.sync` thunk arrived as `Left` and was indistinguishable from a genuine `E`, so\n * `defect` read `false` while `.error` held something that was not an `E` at all\n * (#259). `Exit` keeps the two apart, so the flag can be accurate.\n */\nconst runBoxed = async <E, A>(effect: () => IO<never, E, A>, options?: IOBridgeOptions<E>): Promise<A> => {\n const exit = await Try(() => effect()).fold(\n (thrown) => {\n throw new IOQueryError(thrown as E, undefined, true)\n },\n (io) => io.runExit(),\n )\n\n if (exit.isFailure()) {\n const { error } = exit.toValue() as { error: E }\n throw new IOQueryError(error, options?.formatError?.(error))\n }\n\n if (exit.isDie()) {\n throw new IOQueryError((exit.toValue() as { defect: unknown }).defect as E, undefined, true)\n }\n\n if (exit.isInterrupted()) {\n // An `InterruptedError` is no more an `E` than a defect is, so it carries the same\n // flag. `run()` put it in the `Left` with `defect: false`, which had the same problem\n // the rest of this fix is about.\n throw new IOQueryError(new InterruptedError() as E, undefined, true)\n }\n\n return exit.orThrow()\n}\n\n/**\n * Adapts an `IO<never, E, A>` into a React Query `queryFn`.\n *\n * `Right` resolves with the value; `Left` rejects with an {@link IOQueryError} that\n * carries the typed error on `.error`. Wire cancellation by closing over the supplied\n * `signal`:\n *\n * ```ts\n * useQuery({\n * queryKey: [\"connector-limits\", userId],\n * queryFn: ioQueryFn(({ signal }) => Http.get<Limits>(url, { headers, signal })),\n * enabled: !!userId,\n * })\n * ```\n */\nexport const ioQueryFn =\n <E, A, TContext extends IOQueryFnContext = IOQueryFnContext>(\n io: (context: TContext) => IO<never, E, A>,\n options?: IOBridgeOptions<E>,\n ) =>\n (context: TContext): Promise<A> =>\n runBoxed(() => io(context), options)\n\n/**\n * Adapts a variables-taking `IO<never, E, A>` into a React Query `mutationFn`.\n *\n * React Query does not supply an `AbortSignal` to mutations, so the callback receives\n * only the mutation variables.\n *\n * ```ts\n * useMutation({\n * mutationFn: ioMutationFn((body: CreateTokenInput) => Http.post<Token>(url, { body })),\n * })\n * ```\n */\nexport const ioMutationFn =\n <E, A, V = void>(io: (variables: V) => IO<never, E, A>, options?: IOBridgeOptions<E>) =>\n (variables: V): Promise<A> =>\n runBoxed(() => io(variables), options)\n"],"mappings":"+HAmDA,MAAM,EAAW,MAAa,EAA+B,IAA6C,CACxG,IAAM,EAAO,MAAM,MAAU,EAAO,CAAC,CAAC,CAAC,KACpC,GAAW,CACV,MAAM,IAAI,EAAa,EAAa,IAAA,GAAW,EAAI,CACrD,EACC,GAAO,EAAG,QAAQ,CACrB,EAEA,GAAI,EAAK,UAAU,EAAG,CACpB,GAAM,CAAE,SAAU,EAAK,QAAQ,EAC/B,MAAM,IAAI,EAAa,EAAO,GAAS,cAAc,CAAK,CAAC,CAC7D,CAEA,GAAI,EAAK,MAAM,EACb,MAAM,IAAI,EAAc,EAAK,QAAQ,CAAC,CAAyB,OAAa,IAAA,GAAW,EAAI,EAG7F,GAAI,EAAK,cAAc,EAIrB,MAAM,IAAI,EAAa,IAAI,EAAyB,IAAA,GAAW,EAAI,EAGrE,OAAO,EAAK,QAAQ,CACtB,EAiBa,GAET,EACA,IAED,GACC,MAAe,EAAG,CAAO,EAAG,CAAO,EAc1B,GACM,EAAuC,IACvD,GACC,MAAe,EAAG,CAAS,EAAG,CAAO"}
@@ -1,6 +1,6 @@
1
1
  import { IOQueryError } from "./IOQueryError.js";
2
- import { UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
3
2
  import { IO } from "functype/io";
3
+ import { UseMutationOptions, UseMutationResult } from "@tanstack/react-query";
4
4
  //#region src/query/useIOMutation.d.ts
5
5
  type UseIOMutationOptions<A, E, V, TContext> = Omit<UseMutationOptions<A, IOQueryError<E>, V, TContext>, "mutationFn"> & {
6
6
  /** Override the derived `Error.message` on failure. */
@@ -1,8 +1,8 @@
1
1
  import { t as TaskState } from "../TaskState-DWxGWqXf.js";
2
2
  import { IOQueryError } from "./IOQueryError.js";
3
3
  import { UseIOMutationOptions } from "./useIOMutation.js";
4
- import { UseMutationResult } from "@tanstack/react-query";
5
4
  import { IO } from "functype/io";
5
+ import { UseMutationResult } from "@tanstack/react-query";
6
6
  //#region src/query/useIOMutationState.d.ts
7
7
  /**
8
8
  * `TaskState` plus the flags and the trigger functions. Unlike a query, a mutation is
@@ -1,6 +1,6 @@
1
1
  import { IOQueryError } from "./IOQueryError.js";
2
- import { QueryFunctionContext, QueryKey, UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
3
2
  import { IO } from "functype/io";
3
+ import { QueryFunctionContext, QueryKey, UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
4
4
  //#region src/query/useIOQuery.d.ts
5
5
  type UseIOQueryOptions<A, E, TData, TQueryKey extends QueryKey> = Omit<UseQueryOptions<A, IOQueryError<E>, TData, TQueryKey>, "queryKey" | "queryFn"> & {
6
6
  /** Override the derived `Error.message` on failure. */
@@ -1,8 +1,8 @@
1
1
  import { t as TaskState } from "../TaskState-DWxGWqXf.js";
2
2
  import { IOQueryError } from "./IOQueryError.js";
3
3
  import { UseIOQueryOptions } from "./useIOQuery.js";
4
- import { QueryFunctionContext, QueryKey, UseQueryResult } from "@tanstack/react-query";
5
4
  import { IO } from "functype/io";
5
+ import { QueryFunctionContext, QueryKey, UseQueryResult } from "@tanstack/react-query";
6
6
  //#region src/query/useIOQueryState.d.ts
7
7
  /**
8
8
  * `TaskState` plus the convenience flags and refetch trigger, mirroring
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "functype-react",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "React bindings for functype — ADT-aware hooks and exhaustive pattern matching components",
5
5
  "keywords": [
6
6
  "functype",
@@ -53,7 +53,7 @@
53
53
  "react-dom": "^19.2.8",
54
54
  "ts-builds": "^3.2.3",
55
55
  "tsdown": "^0.22.14",
56
- "functype": "^1.7.0"
56
+ "functype": "^1.8.0"
57
57
  },
58
58
  "type": "module",
59
59
  "main": "./dist/index.js",