functype 1.27.2 → 2.1.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.
Files changed (181) hide show
  1. package/README.md +70 -88
  2. package/dist/_virtual/_rolldown/runtime.js +1 -0
  3. package/dist/branded/ValidatedBrand.d.ts +122 -0
  4. package/dist/branded/ValidatedBrand.js +1 -0
  5. package/dist/branded/index.d.ts +52 -2
  6. package/dist/cli/data.d.ts +37 -0
  7. package/dist/cli/data.js +1 -0
  8. package/dist/cli/exports.d.ts +5 -46
  9. package/dist/cli/exports.js +1 -1
  10. package/dist/cli/formatters.js +4 -0
  11. package/dist/cli/full-interfaces.d.ts +6 -0
  12. package/dist/cli/full-interfaces.js +1150 -0
  13. package/dist/cli/index.js +3 -6
  14. package/dist/cli/interfaces.generated.js +1 -0
  15. package/dist/collections/index.d.ts +13 -0
  16. package/dist/companion/Companion.d.ts +23 -0
  17. package/dist/companion/Companion.js +1 -0
  18. package/dist/companion/CompanionTypes.d.ts +30 -0
  19. package/dist/{CompanionTypes-BVqO7Kc2.js → companion/CompanionTypes.js} +1 -1
  20. package/dist/companion/index.d.ts +2 -1
  21. package/dist/companion/index.js +1 -1
  22. package/dist/conditional/Cond.d.ts +147 -0
  23. package/dist/conditional/Cond.js +1 -0
  24. package/dist/conditional/Match.d.ts +295 -0
  25. package/dist/conditional/Match.js +1 -0
  26. package/dist/conditional/index.d.ts +3 -2
  27. package/dist/conditional/index.js +1 -1
  28. package/dist/core/base/Base.d.ts +12 -0
  29. package/dist/core/base/Base.js +1 -0
  30. package/dist/core/throwable/Throwable.d.ts +38 -0
  31. package/dist/core/throwable/Throwable.js +1 -0
  32. package/dist/decoder/Decoder.d.ts +15 -0
  33. package/dist/decoder/DecoderCompanion.js +1 -0
  34. package/dist/decoder/DecoderError.d.ts +56 -0
  35. package/dist/decoder/DecoderError.js +2 -0
  36. package/dist/decoder/Encoder.d.ts +15 -0
  37. package/dist/decoder/index.d.ts +71 -2
  38. package/dist/decoder/index.js +1 -1
  39. package/dist/decoder/tagged.js +1 -0
  40. package/dist/do/index.d.ts +246 -2
  41. package/dist/do/index.js +1 -1
  42. package/dist/do/protocol.d.ts +29 -0
  43. package/dist/either/index.d.ts +290 -2
  44. package/dist/either/index.js +1 -1
  45. package/dist/error/ErrorChain.d.ts +60 -0
  46. package/dist/error/ErrorChain.js +4 -0
  47. package/dist/error/ErrorFormatter.d.ts +67 -0
  48. package/dist/error/ErrorFormatter.js +6 -0
  49. package/dist/error/ParseError.d.ts +6 -0
  50. package/dist/error/ParseError.js +1 -0
  51. package/dist/error/typed/TypedError.d.ts +146 -0
  52. package/dist/error/typed/TypedError.js +1 -0
  53. package/dist/error/typed/Validation.d.ts +76 -0
  54. package/dist/error/typed/Validation.js +1 -0
  55. package/dist/extractable/Extractable.d.ts +62 -0
  56. package/dist/extractable/Extractable.js +1 -0
  57. package/dist/fetch/Http.d.ts +32 -0
  58. package/dist/fetch/Http.js +1 -0
  59. package/dist/fetch/HttpClient.d.ts +80 -0
  60. package/dist/fetch/HttpClient.js +1 -0
  61. package/dist/fetch/HttpError.d.ts +57 -0
  62. package/dist/fetch/HttpError.js +1 -0
  63. package/dist/fetch/HttpRequest.d.ts +103 -0
  64. package/dist/fetch/index.d.ts +5 -2
  65. package/dist/fetch/index.js +1 -1
  66. package/dist/foldable/Foldable.d.ts +27 -0
  67. package/dist/foldable/index.d.ts +55 -0
  68. package/dist/foldable/index.js +1 -0
  69. package/dist/functype/Functype.d.ts +76 -0
  70. package/dist/functype/FunctypeSum.d.ts +39 -0
  71. package/dist/functype/index.d.ts +4 -2
  72. package/dist/hkt/index.d.ts +68 -0
  73. package/dist/hkt/index.js +1 -0
  74. package/dist/identity/Identity.d.ts +34 -0
  75. package/dist/identity/Identity.js +1 -0
  76. package/dist/index.d.ts +74 -8
  77. package/dist/index.js +1 -1
  78. package/dist/internal/base64.js +1 -0
  79. package/dist/internal/call-alone.js +1 -0
  80. package/dist/internal/concurrency.d.ts +11 -0
  81. package/dist/internal/concurrency.js +1 -0
  82. package/dist/internal/define.js +1 -0
  83. package/dist/internal/mutation-utils.js +1 -0
  84. package/dist/internal/signal.js +1 -0
  85. package/dist/internal/stringify.js +1 -0
  86. package/dist/invariant/index.d.ts +32 -2
  87. package/dist/io/Context.d.ts +112 -0
  88. package/dist/io/Context.js +1 -0
  89. package/dist/io/Exit.d.ts +249 -0
  90. package/dist/io/Exit.js +1 -0
  91. package/dist/io/IO.d.ts +1263 -0
  92. package/dist/io/IO.js +1 -0
  93. package/dist/io/Layer.d.ts +139 -0
  94. package/dist/io/Layer.js +1 -0
  95. package/dist/io/SpanTracer.d.ts +78 -0
  96. package/dist/io/SpanTracer.js +1 -0
  97. package/dist/io/Tag.d.ts +75 -0
  98. package/dist/io/Tag.js +1 -0
  99. package/dist/io/TestClock.d.ts +133 -0
  100. package/dist/io/TestClock.js +1 -0
  101. package/dist/io/index.d.ts +41 -2
  102. package/dist/io/index.js +1 -1
  103. package/dist/lazy/Lazy.d.ts +312 -0
  104. package/dist/lazy/Lazy.js +1 -0
  105. package/dist/lazy/index.d.ts +2 -2
  106. package/dist/lazy/index.js +1 -1
  107. package/dist/list/LazyList.d.ts +182 -0
  108. package/dist/list/LazyList.js +1 -0
  109. package/dist/list/index.d.ts +137 -2
  110. package/dist/list/index.js +1 -1
  111. package/dist/logger/index.d.ts +24 -2
  112. package/dist/map/index.d.ts +95 -2
  113. package/dist/map/index.js +1 -1
  114. package/dist/map/shim.d.ts +13 -0
  115. package/dist/map/shim.js +1 -0
  116. package/dist/matchable/Matchable.d.ts +38 -0
  117. package/dist/matchable/Matchable.js +1 -0
  118. package/dist/obj/Obj.d.ts +212 -0
  119. package/dist/obj/Obj.js +1 -0
  120. package/dist/obj/index.d.ts +2 -2
  121. package/dist/obj/index.js +1 -1
  122. package/dist/option/index.d.ts +304 -2
  123. package/dist/option/index.js +1 -1
  124. package/dist/package.json.js +1 -0
  125. package/dist/pipe/index.d.ts +14 -0
  126. package/dist/ref/Ref.d.ts +77 -0
  127. package/dist/ref/Ref.js +1 -0
  128. package/dist/reshapeable/Reshapeable.d.ts +90 -0
  129. package/dist/serializable/Serializable.d.ts +39 -0
  130. package/dist/serialization/Serialization.d.ts +147 -0
  131. package/dist/serialization/Serialization.js +1 -0
  132. package/dist/serialization/SerializationCompanion.d.ts +125 -0
  133. package/dist/serialization/SerializationCompanion.js +1 -0
  134. package/dist/serialization/error-envelope.d.ts +44 -0
  135. package/dist/serialization/error-envelope.js +1 -0
  136. package/dist/serialization/index.d.ts +4 -2
  137. package/dist/serialization/index.js +1 -1
  138. package/dist/set/index.d.ts +106 -2
  139. package/dist/set/index.js +1 -1
  140. package/dist/stack/Stack.d.ts +120 -0
  141. package/dist/stack/Stack.js +1 -0
  142. package/dist/traced/TraceEvent.d.ts +27 -0
  143. package/dist/traced/TracedOption.d.ts +46 -0
  144. package/dist/traced/TracedOption.js +1 -0
  145. package/dist/traced/Tracer.d.ts +26 -0
  146. package/dist/traversable/KVTraversable.d.ts +14 -0
  147. package/dist/traversable/Traversable.d.ts +30 -0
  148. package/dist/try/index.d.ts +238 -2
  149. package/dist/try/index.js +1 -1
  150. package/dist/tuple/index.d.ts +92 -2
  151. package/dist/tuple/index.js +1 -1
  152. package/dist/typeable/Typeable.d.ts +40 -0
  153. package/dist/typeable/Typeable.js +1 -0
  154. package/dist/typeclass/ContainerOps.d.ts +131 -0
  155. package/dist/typeclass/Functor.d.ts +41 -0
  156. package/dist/typeclass/Promisable.d.ts +33 -0
  157. package/dist/typeclass/index.d.ts +4 -1
  158. package/dist/typeclass/index.js +1 -1
  159. package/dist/typeclass/variance.d.ts +54 -0
  160. package/dist/typeclass/variance.js +1 -0
  161. package/dist/types/index.d.ts +1 -0
  162. package/dist/util/index.d.ts +1 -3
  163. package/dist/valuable/Valuable.d.ts +28 -0
  164. package/dist/valuable/Valuable.js +1 -0
  165. package/dist/wire/index.d.ts +40 -2
  166. package/package.json +8 -13
  167. package/dist/Brand-bfnGXuum.d.ts +0 -54
  168. package/dist/Companion-DiOMBHDG.js +0 -1
  169. package/dist/CompanionTypes-Cc90cQ4P.d.ts +0 -58
  170. package/dist/Invariant-DEan-SxV.d.ts +0 -35
  171. package/dist/Logger-BmprRS8v.d.ts +0 -27
  172. package/dist/Tuple-B8KM-H8Y.d.ts +0 -213
  173. package/dist/Wire-3hvw0Ogg.d.ts +0 -42
  174. package/dist/core/task/index.d.ts +0 -2
  175. package/dist/core/task/index.js +0 -1
  176. package/dist/full-interfaces-BadxJrCt.js +0 -1202
  177. package/dist/index-CLYh2qZu.d.ts +0 -6649
  178. package/dist/rolldown-runtime-DK3Fl9T5.js +0 -1
  179. package/dist/serialization-9_SyrfdG.js +0 -3
  180. package/dist/src-BQPeS6p2.js +0 -10
  181. package/dist/typeclass-C61yDVYd.js +0 -1
@@ -0,0 +1,147 @@
1
+ /**
2
+ * The headline 1.2.0 public API for universal serialization.
3
+ *
4
+ * `Serialization.deserialize` parses a JSON string and walks the result,
5
+ * reconstructing any object carrying a `@functype` marker via the per-type
6
+ * companion's `fromJSON`. Plain JSON values pass through untouched.
7
+ * `Serialization.serialize` is a thin convenience over `JSON.stringify` —
8
+ * functype instances self-stringify via their instance `toJSON()` method
9
+ * (which emits the `@functype`-marked envelope), so the standard
10
+ * `JSON.stringify` protocol does the recursion for free.
11
+ *
12
+ * `Serialization.isFunctypeValue` is a runtime type guard for live values,
13
+ * useful when wrapping this API in a host serializer (e.g. a DBOS
14
+ * `stringify`/`parse` recipe — see docs/archive/proposals/universal-deserialize.md).
15
+ *
16
+ * Strict unknown-marker policy: a JSON value carrying an `@functype` marker
17
+ * that doesn't match any known type returns `Failure` from `deserialize`.
18
+ * No silent pass-through. (Plain JSON values without the marker are NOT
19
+ * "unknown" — they just aren't ours; those walk through unchanged.)
20
+ *
21
+ * See `docs/archive/proposals/universal-deserialize.md` for the design rationale.
22
+ */
23
+ import { Serializable } from "../serializable/Serializable.js";
24
+ import { Try } from "../try/index.js";
25
+ declare namespace Serialization_d_exports {
26
+ export { JSONValue, deserialize, deserializeStrict, fromEnvelope, isFunctypeValue, serialize, toEnvelope };
27
+ }
28
+ /**
29
+ * The canonical JSON value type — anything `JSON.parse` can return and
30
+ * anything `JSON.stringify` can accept as input. Used by `toEnvelope` /
31
+ * `fromEnvelope` to express the contract precisely: the envelope is a
32
+ * structured JSON shape, not opaque `unknown`. Lets consumers wiring this
33
+ * API into another structured serializer (SuperJSON, DBOS custom
34
+ * transformers) slot it in without a cast at the boundary.
35
+ *
36
+ * Added in 1.2.2 — `toEnvelope`/`fromEnvelope` previously typed input/output
37
+ * as `unknown`, which forced a cast at the consumer side.
38
+ */
39
+ export type JSONValue = string | number | boolean | null | JSONValue[] | {
40
+ [key: string]: JSONValue;
41
+ };
42
+ /**
43
+ * Reconstruct any value from a JSON string. Lenient codec: walks the parsed
44
+ * structure and rebuilds any value carrying an `@functype` marker via the
45
+ * dispatch table; plain JSON without the marker walks through unchanged.
46
+ * Returns `Try` so malformed JSON or unknown markers are expressible values
47
+ * rather than thrown — matches the functype convention for expected-failure
48
+ * paths.
49
+ *
50
+ * **Pass-through policy:** valid JSON without an `@functype` marker is
51
+ * returned verbatim as `Success(value)`; only marker-carrying values are
52
+ * reconstructed. Only malformed JSON (or an unknown marker) yields `Failure`.
53
+ * For a strict variant that rejects unmarked input, see `deserializeStrict`.
54
+ *
55
+ * @example
56
+ * const result = Serialization.deserialize('{"@functype":"Either","_tag":"Right","value":5}')
57
+ * result.fold(e => console.error(e), v => console.log(v)) // → Right(5)
58
+ *
59
+ * // Plain (non-functype) values pass through:
60
+ * Serialization.deserialize('{"name":"alice","age":30}') // → Success({name, age})
61
+ *
62
+ * // Embedding in another structured serializer (SuperJSON, DBOS)? See
63
+ * // `fromEnvelope` — taking a string here forces the consumer through a
64
+ * // JSON.stringify shim and SuperJSON re-walks strings character-by-character.
65
+ */
66
+ export declare const deserialize: (json: string) => Try<unknown>;
67
+ /**
68
+ * Strict variant of `deserialize`: returns `Failure` when the parsed JSON
69
+ * doesn't carry an `@functype` marker at the top level. Use this at API,
70
+ * queue, or RPC boundaries where the wire format MUST be a functype value
71
+ * and pass-through silence would be a bug.
72
+ *
73
+ * Implementation note: only the top-level value is checked for the marker.
74
+ * Nested values inside it follow the same lenient pass-through rules as
75
+ * `deserialize` — a `Right` containing a plain object still reconstructs
76
+ * fine, you just can't START with a plain object.
77
+ *
78
+ * @example
79
+ * Serialization.deserializeStrict('{"@functype":"Option","_tag":"Some","value":1}') // → Success(Some(1))
80
+ * Serialization.deserializeStrict('{"_tag":"Some","value":1}') // → Failure
81
+ * Serialization.deserializeStrict('42') // → Failure
82
+ */
83
+ export declare const deserializeStrict: (json: string) => Try<unknown>;
84
+ /**
85
+ * Serialize any value to a JSON string. Lenient codec: thin convenience over
86
+ * `JSON.stringify` — functype instances self-stringify via their instance
87
+ * `toJSON()` method (which emits the `@functype`-marked envelope), and
88
+ * non-functype values pass through as plain JSON. Nested functype values
89
+ * embedded in plain objects/arrays serialize correctly via the standard
90
+ * JSON.stringify protocol with no walker needed.
91
+ *
92
+ * `undefined` is converted to `null` (matching the convention DBOS and
93
+ * SuperJSON use; `JSON.stringify(undefined)` returns the string `"undefined"`
94
+ * which is not valid JSON).
95
+ */
96
+ export declare const serialize: (value: unknown) => string;
97
+ /**
98
+ * Serialize a value to a parsed JSON envelope (object/array/primitive) rather
99
+ * than a string. Use this when nesting functype values inside another
100
+ * **structured** serializer (SuperJSON / DBOS custom transformers / similar)
101
+ * whose custom-transformer hook expects JSON values, not strings — passing a
102
+ * string to such a hook causes the host to re-walk it character-by-character,
103
+ * destroying the round-trip.
104
+ *
105
+ * Equivalent to `JSON.parse(serialize(value))` but exposed as a named entry
106
+ * point so consumers don't carry the parse/stringify shim.
107
+ *
108
+ * Returns `JSONValue` (tightened from `unknown` in 1.2.2) so consumers can
109
+ * drop the result straight into a host serializer's `serialize` hook without
110
+ * a boundary cast.
111
+ *
112
+ * @example
113
+ * // Inside a DBOS custom serialization recipe — zero casts:
114
+ * DBOS.registerSerialization({
115
+ * name: "functype",
116
+ * isApplicable: Serialization.isFunctypeValue,
117
+ * serialize: Serialization.toEnvelope,
118
+ * deserialize: (o) => Serialization.fromEnvelope(o).orThrow(),
119
+ * })
120
+ */
121
+ export declare const toEnvelope: (value: unknown) => JSONValue;
122
+ /**
123
+ * Inverse of `toEnvelope`: reconstruct any value from a parsed JSON envelope
124
+ * (object/array/primitive). Equivalent to `deserialize(JSON.stringify(envelope))`
125
+ * but skips the stringify/parse roundtrip — the same `revive` walker is
126
+ * applied directly. Returns `Try` for the same reasons as `deserialize`.
127
+ *
128
+ * Pass-through policy matches `deserialize`: a parsed value without an
129
+ * `@functype` marker is returned verbatim as `Success(value)`.
130
+ *
131
+ * Input is `unknown` (intentionally permissive — Postel's law). Host
132
+ * serializers typically hand the deserialize callback a JSON-shaped value
133
+ * that they parsed themselves, but their callback typing varies (some are
134
+ * `JSONValue`, some are `unknown`, some are `any`). Accepting `unknown`
135
+ * here means the function slots into any host shape without forcing a
136
+ * cast at the consumer site.
137
+ */
138
+ export declare const fromEnvelope: (envelope: unknown) => Try<unknown>;
139
+ /**
140
+ * Runtime guard: is this a live functype Serializable? Checks for the
141
+ * `serialize()` method plus the `_tag` field that every Serializable instance
142
+ * carries. Use this when wrapping `serialize`/`deserialize` in a host
143
+ * serializer that needs to distinguish functype values from foreign data
144
+ * (e.g. `isApplicable` in a DBOS recipe).
145
+ */
146
+ export declare const isFunctypeValue: (v: unknown) => v is Serializable<unknown>;
147
+ export { Serialization_d_exports };
@@ -0,0 +1 @@
1
+ import{__exportAll as e}from"../_virtual/_rolldown/runtime.js";import{Left as t,Right as n}from"../either/index.js";import{Lazy as r}from"../lazy/Lazy.js";import{LazyList as i}from"../list/LazyList.js";import{List as a}from"../list/index.js";import{Map as o}from"../map/index.js";import{Obj as s}from"../obj/Obj.js";import{None as c,Some as l}from"../option/index.js";import{Set as u}from"../set/index.js";import{Stack as d}from"../stack/Stack.js";import{Try as f}from"../try/index.js";import{Tuple as p}from"../tuple/index.js";import{deserializeError as m}from"./error-envelope.js";import{FUNCTYPE_MARKER as h}from"./SerializationCompanion.js";var g=/* @__PURE__ */ e({deserialize:()=>S,deserializeStrict:()=>C,fromEnvelope:()=>E,isFunctypeValue:()=>D,serialize:()=>w,toEnvelope:()=>T});let _;const v=()=>(_===void 0&&(_={Option:e=>e._tag===`Some`?l(e.value):c(),Either:e=>e._tag===`Right`?n(e.value):t(e.value),Try:e=>{if(e._tag===`Success`)return f.success(e.value);let t=e.error!==void 0&&typeof e.error==`object`?m(e.error):Error(typeof e.error==`string`?e.error:``);return f.failure(t)},List:e=>a(e.value),Set:e=>u(e.value),Map:e=>o(e.value),Obj:e=>s(e.value),Stack:e=>d(e.value),Tuple:e=>p(e.value),LazyList:e=>i(e.value),Lazy:e=>{if(e.error!==void 0){let t=typeof e.error==`object`?m(e.error):Error(e.error);return r.fail(t)}return r.evaluated(e.value)}}),_),y=e=>typeof e==`object`&&!!e&&!Array.isArray(e),b=e=>y(e)&&typeof e[`@functype`]==`string`,x=e=>{if(Array.isArray(e))return e.map(x);if(b(e)){let t=e[h],n=v()[t];if(n===void 0)throw Error(`Serialization.deserialize: unknown @functype marker ${JSON.stringify(t)}`);let r={};for(let t of Object.keys(e))r[t]=x(e[t]);return n(r)}if(y(e)){let t={};for(let n of Object.keys(e))t[n]=x(e[n]);return t}return e},S=e=>f(()=>x(JSON.parse(e))),C=e=>f(()=>{let t=JSON.parse(e);if(!b(t))throw Error(`Serialization.deserializeStrict: input is not a functype envelope (no @functype marker at the top level)`);return x(t)}),w=e=>JSON.stringify(e??null),T=e=>JSON.parse(JSON.stringify(e??null)),E=e=>f(()=>x(e)),D=e=>typeof e==`object`&&!!e&&typeof e.serialize==`function`&&typeof e._tag==`string`;export{g as Serialization_exports,S as deserialize,C as deserializeStrict,E as fromEnvelope,D as isFunctypeValue,w as serialize,T as toEnvelope};
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Serialization result containing methods for different formats
3
+ */
4
+ export interface SerializationResult {
5
+ /** Serializes to JSON string */
6
+ toJSON: () => string;
7
+ /** Serializes to base64-encoded binary string */
8
+ toBinary: () => string;
9
+ }
10
+ /**
11
+ * The namespaced marker stamped on every functype envelope. Defends against
12
+ * `_tag` collisions with Effect/fp-ts (which use identical strings like
13
+ * `"Some"`, `"Left"`, `"Success"`). A value WITHOUT this marker is treated
14
+ * as "not ours" by `Serialization.deserialize`.
15
+ *
16
+ * See `docs/archive/proposals/universal-deserialize-changes.md` Change 0 for the
17
+ * full rationale.
18
+ */
19
+ export declare const FUNCTYPE_MARKER: "@functype";
20
+ /**
21
+ * Shape of every functype JSON envelope. The marker identifies the type,
22
+ * `_tag` (when present) discriminates variants within that type, and the
23
+ * remaining payload fields are type-specific (`value` for canonical cases,
24
+ * `error` for failure branches, etc.).
25
+ */
26
+ export type FunctypeEnvelope = {
27
+ readonly [FUNCTYPE_MARKER]: string;
28
+ readonly _tag?: string;
29
+ readonly [key: string]: unknown;
30
+ };
31
+ /**
32
+ * Build the canonical `{@functype, _tag, value}` envelope OBJECT used by both
33
+ * the instance `toJSON()` (which returns it directly so native JSON.stringify
34
+ * can recurse) and the `serialize().toJSON()` method (which stringifies it).
35
+ *
36
+ * `_tag` is always emitted — variant-less types pass the same string for
37
+ * marker and tag (default behavior when tag is omitted). Keeping `_tag`
38
+ * across the board preserves back-compat for readers that did
39
+ * `if (parsed._tag === "List")` against 1.1.0 envelopes.
40
+ *
41
+ * @param marker - The `@functype` type marker, e.g. `"Either"`, `"Option"`.
42
+ * @param tag - The variant discriminator, e.g. `"Right"`, `"Some"`. Defaults
43
+ * to `marker` for types without variants (List, Map, etc.).
44
+ * @param value - The payload.
45
+ */
46
+ export declare const envelope: (marker: string, tag: string | undefined, value: unknown) => FunctypeEnvelope;
47
+ /**
48
+ * Build a non-canonical envelope where the payload doesn't fit the standard
49
+ * `{value}` shape — e.g. `Try.Failure` carries `{error: SerializedError}`,
50
+ * `Lazy`-with-thrown-thunk carries the same.
51
+ *
52
+ * @param marker - The `@functype` type marker.
53
+ * @param tag - The variant discriminator (may be the same as marker for
54
+ * variant-less types).
55
+ * @param fields - Additional payload fields merged into the envelope.
56
+ */
57
+ export declare const taggedEnvelope: (marker: string, tag: string, fields: Record<string, unknown>) => FunctypeEnvelope;
58
+ /**
59
+ * Creates a serializer for the canonical envelope shape, with the `@functype`
60
+ * marker stamped at the top level (Change 0 of the 1.2.0 universal-deserialize
61
+ * work). Two forms:
62
+ *
63
+ * createSerializer(marker, value) // variant-less types (List, Map, …)
64
+ * createSerializer(marker, tag, value) // variants (Either, Option, …)
65
+ *
66
+ * Variant-less envelopes are `{"@functype": marker, value}`. Variant envelopes
67
+ * are `{"@functype": marker, _tag: tag, value}`.
68
+ */
69
+ export declare function createSerializer(marker: string, value: unknown): SerializationResult;
70
+ export declare function createSerializer(marker: string, tag: string, value: unknown): SerializationResult;
71
+ /**
72
+ * Creates a serializer for non-canonical envelopes whose payload doesn't
73
+ * fit the `{value}` shape — e.g. failure branches that carry a structured
74
+ * `SerializedError`. The envelope still carries the `@functype` marker
75
+ * and `_tag` discriminator.
76
+ *
77
+ * @param marker - The `@functype` type marker.
78
+ * @param tag - The variant discriminator.
79
+ * @param fields - The payload fields (merged after marker + tag).
80
+ */
81
+ export declare const createTaggedSerializer: (marker: string, tag: string, fields: Record<string, unknown>) => SerializationResult;
82
+ /** A parsed envelope, from JSON or binary, before a companion rebuilds its type from it. */
83
+ export type ParsedEnvelope = {
84
+ _tag?: string;
85
+ [key: string]: unknown;
86
+ };
87
+ /**
88
+ * Throws when an envelope carries another type's `@functype` marker. An envelope without a marker
89
+ * passes, because envelopes written before 1.2.0 have none.
90
+ * @param parsed - The parsed envelope
91
+ * @param marker - The marker this companion reads, such as `"List"`
92
+ * @param method - The calling method, named in the error, such as `"fromJSON"`
93
+ */
94
+ export declare const expectMarker: (parsed: ParsedEnvelope, marker: string, method: string) => void;
95
+ /**
96
+ * Generic deserializer from JSON. The `reconstructor` receives the full
97
+ * parsed envelope including any `@functype` marker; per-type companions
98
+ * verify the marker matches their expected value.
99
+ */
100
+ export declare const fromJSON: <T>(json: string, reconstructor: (parsed: {
101
+ _tag?: string;
102
+ [key: string]: unknown;
103
+ }) => T) => T;
104
+ /**
105
+ * Generic deserializer from binary (base64-encoded JSON)
106
+ * @param binary - The base64-encoded binary string
107
+ * @param reconstructor - Function to reconstruct the type from parsed data
108
+ * @returns Reconstructed instance
109
+ */
110
+ export declare const fromBinary: <T>(binary: string, reconstructor: (parsed: {
111
+ _tag?: string;
112
+ [key: string]: unknown;
113
+ }) => T) => T;
114
+ /**
115
+ * Creates companion serialization methods for a type
116
+ * @param reconstructor - Function to reconstruct the type from parsed data
117
+ * @returns Companion methods object with fromJSON and fromBinary
118
+ */
119
+ export declare const createSerializationCompanion: <T>(reconstructor: (parsed: {
120
+ _tag?: string;
121
+ [key: string]: unknown;
122
+ }) => T) => {
123
+ fromJSON: (json: string) => T;
124
+ fromBinary: (binary: string) => T;
125
+ };
@@ -0,0 +1 @@
1
+ import{base64ToUtf8 as e,utf8ToBase64 as t}from"../internal/base64.js";const n=`@functype`,r=(e,t,r)=>({[n]:e,_tag:t??e,value:r}),i=(e,t,r)=>({[n]:e,_tag:t,...r});function a(e,n,i){let a=arguments.length===3,o=r(e,a?n:e,a?i:n);return{toJSON:()=>JSON.stringify(o),toBinary:()=>t(JSON.stringify(o))}}const o=(e,n,r)=>{let a=i(e,n,r);return{toJSON:()=>JSON.stringify(a),toBinary:()=>t(JSON.stringify(a))}},s=(e,t,r)=>{let i=e[n];if(i!==void 0&&i!==t)throw Error(`${t}.${r}: expected @functype="${t}", got ${JSON.stringify(i)}`)},c=(e,t)=>t(JSON.parse(e)),l=(t,n)=>{let r=e(t);return c(r,n)},u=e=>({fromJSON:t=>c(t,e),fromBinary:t=>l(t,e)});export{n as FUNCTYPE_MARKER,u as createSerializationCompanion,a as createSerializer,o as createTaggedSerializer,r as envelope,s as expectMarker,l as fromBinary,c as fromJSON,i as taggedEnvelope};
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Canonical projection of `Error` to JSON, shared by every Serializable type
3
+ * that carries an `Error` in its failure branch (`Try.Failure`, `Lazy` with a
4
+ * thrown thunk).
5
+ *
6
+ * Round-trip guarantees:
7
+ * - `err.name` survives (preserves discriminator: `e.name === "TypeError"` works)
8
+ * - `err.message` survives
9
+ * - `err.stack` survives if present at serialize time
10
+ * - `err.cause` survives recursively (arbitrary nesting depth)
11
+ *
12
+ * What does NOT survive:
13
+ * - `instanceof TypeError` and other subclass identity checks (JSON cannot
14
+ * reconstruct user-defined classes without arbitrary code execution).
15
+ * - Custom Error-subclass fields (e.g. `HttpError.status`). The generic
16
+ * projection doesn't know about them; a future registry mechanism may
17
+ * address this.
18
+ *
19
+ * Use `e.name` for discriminator checks across the serialization boundary,
20
+ * not `e instanceof SomeError`.
21
+ */
22
+ export type SerializedError = {
23
+ readonly name: string;
24
+ readonly message: string;
25
+ readonly stack?: string;
26
+ readonly cause?: SerializedError | string;
27
+ };
28
+ /**
29
+ * Project an arbitrary thrown value to the canonical SerializedError shape.
30
+ * Accepts both `Error` instances and non-Error throwables (strings, plain
31
+ * objects, etc.). Non-Error throwables get `name: "NonErrorThrowable"` and
32
+ * the best textual representation we can produce.
33
+ */
34
+ export declare const serializeError: (err: unknown) => SerializedError;
35
+ /**
36
+ * Reconstruct an Error from a SerializedError. The reconstructed Error has
37
+ * the same `name`, `message`, `stack`, and `cause` chain as the original,
38
+ * but its prototype is always `Error.prototype` — subclass identity does
39
+ * not round-trip.
40
+ *
41
+ * A `string` is accepted as a shorthand for `{name: "Error", message: <string>}`,
42
+ * matching what `serializeCause` emits when a `cause` was a bare string.
43
+ */
44
+ export declare const deserializeError: (s: SerializedError | string) => Error;
@@ -0,0 +1 @@
1
+ import{safeStringify as e}from"../internal/stringify.js";const t=t=>t instanceof Error?n(t):typeof t==`string`?t:e(t)??`<unserializable cause>`,n=n=>{if(n instanceof Error){let e={name:n.name,message:n.message};n.stack!==void 0&&(e.stack=n.stack);let{cause:r}=n;return r!==void 0&&(e.cause=t(r)),e}return{name:`NonErrorThrowable`,message:typeof n==`string`?n:e(n)??`<unserializable>`}},r=e=>{if(typeof e==`string`)return Error(e);let t=Error(e.message);if(e.name&&(t.name=e.name),e.stack!==void 0&&(t.stack=e.stack),e.cause!==void 0){let n=t;n.cause=r(e.cause)}return t};export{r as deserializeError,n as serializeError};
@@ -1,2 +1,4 @@
1
- import { $n as fromBinary, Gn as ParsedEnvelope, Jn as createSerializationCompanion, Kn as SerializationResult, Qn as expectMarker, Un as FUNCTYPE_MARKER, Vn as JSONValue, Wn as FunctypeEnvelope, Xn as createTaggedSerializer, Yn as createSerializer, Zn as envelope, ar as serializeError, er as fromJSON, ir as deserializeError, nr as taggedEnvelope, qn as createCustomSerializer, rr as SerializedError, tr as fromYAML } from "../index-CLYh2qZu.js";
2
- export { FUNCTYPE_MARKER, FunctypeEnvelope, type JSONValue, ParsedEnvelope, SerializationResult, SerializedError, createCustomSerializer, createSerializationCompanion, createSerializer, createTaggedSerializer, deserializeError, envelope, expectMarker, fromBinary, fromJSON, fromYAML, serializeError, taggedEnvelope };
1
+ import { SerializedError, deserializeError, serializeError } from "./error-envelope.js";
2
+ import { FUNCTYPE_MARKER, FunctypeEnvelope, ParsedEnvelope, SerializationResult, createSerializationCompanion, createSerializer, createTaggedSerializer, envelope, expectMarker, fromBinary, fromJSON, taggedEnvelope } from "./SerializationCompanion.js";
3
+ import { JSONValue } from "./Serialization.js";
4
+ export { FUNCTYPE_MARKER, FunctypeEnvelope, type JSONValue, ParsedEnvelope, SerializationResult, SerializedError, createSerializationCompanion, createSerializer, createTaggedSerializer, deserializeError, envelope, expectMarker, fromBinary, fromJSON, serializeError, taggedEnvelope };
@@ -1 +1 @@
1
- import{a as e,c as t,d as n,f as r,i,l as a,n as o,o as s,p as c,r as l,s as u,t as d,u as f}from"../serialization-9_SyrfdG.js";export{d as FUNCTYPE_MARKER,o as createCustomSerializer,l as createSerializationCompanion,i as createSerializer,e as createTaggedSerializer,r as deserializeError,s as envelope,u as expectMarker,t as fromBinary,a as fromJSON,f as fromYAML,c as serializeError,n as taggedEnvelope};
1
+ import{deserializeError as e,serializeError as t}from"./error-envelope.js";import{FUNCTYPE_MARKER as n,createSerializationCompanion as r,createSerializer as i,createTaggedSerializer as a,envelope as o,expectMarker as s,fromBinary as c,fromJSON as l,taggedEnvelope as u}from"./SerializationCompanion.js";export{n as FUNCTYPE_MARKER,r as createSerializationCompanion,i as createSerializer,a as createTaggedSerializer,e as deserializeError,o as envelope,s as expectMarker,c as fromBinary,l as fromJSON,t as serializeError,u as taggedEnvelope};
@@ -1,2 +1,106 @@
1
- import { In as Set } from "../index-CLYh2qZu.js";
2
- export { Set };
1
+ import { Collection } from "../collections/index.js";
2
+ import { FunctypeCollection } from "../functype/Functype.js";
3
+ import { ConcurrencyOptions } from "../internal/concurrency.js";
4
+ import { List } from "../list/index.js";
5
+ import { Flattened } from "../typeclass/ContainerOps.js";
6
+ import { Type } from "../types/index.js";
7
+ /**
8
+ * Immutable Set. Covariant in A (`<out A>`) — while Scala's `Set[A]` is nominally invariant,
9
+ * functype's Set follows the same pragmatic covariance pattern as List: element-query methods
10
+ * (`contains`, `has`, `remove`) accept `unknown`, and additions widen via `<B>(B) => Set<A | B>`.
11
+ * `reduce`/`reduceRight` follow Scala's `reduce[B >: A]` pattern with a default `B = A`.
12
+ */
13
+ export interface Set<out A> extends FunctypeCollection<A, "Set">, Collection<A> {
14
+ add<B>(value: B): Set<A | B>;
15
+ remove(value: unknown): Set<A>;
16
+ has(value: unknown): boolean;
17
+ /**
18
+ * Elements in this set or `other`. `other` can be any iterable: an array, a native Set or a functype Set.
19
+ * Like every Set method, it compares elements as `has` does: by SameValueZero, so objects by identity and
20
+ * `NaN` equal to `NaN`.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * Set([1, 2]).union([2, 3]) // Set([1, 2, 3])
25
+ * ```
26
+ */
27
+ union<B>(other: Iterable<B>): Set<A | B>;
28
+ /** Elements in both this set and `other`, in this set's order (native `intersection` follows the smaller set's). */
29
+ intersection(other: Iterable<unknown>): Set<A>;
30
+ /** Elements in this set and not in `other`. */
31
+ difference(other: Iterable<unknown>): Set<A>;
32
+ /** Elements in exactly one of this set and `other`. */
33
+ symmetricDifference<B>(other: Iterable<B>): Set<A | B>;
34
+ /** True if every element of this set is in `other`. True for an empty set. */
35
+ isSubsetOf(other: Iterable<unknown>): boolean;
36
+ /** True if every element of `other` is in this set. */
37
+ isSupersetOf(other: Iterable<unknown>): boolean;
38
+ /** True if this set and `other` share no element. */
39
+ isDisjointFrom(other: Iterable<unknown>): boolean;
40
+ map<B>(f: (a: A) => B): Set<B>;
41
+ flatMap<B>(f: (a: A) => Iterable<B>): Set<B>;
42
+ /**
43
+ * Async map: awaits `f` for each element and collects the results into a Set, so equal results
44
+ * collapse into one. Runs one call at a time by default; pass `{ concurrency: n }` to allow up to
45
+ * `n` at once, or `"unbounded"`. A rejection rejects the result, and no further calls start.
46
+ */
47
+ mapAsync<B>(f: (a: A) => PromiseLike<B>, options?: ConcurrencyOptions): Promise<Set<B>>;
48
+ filter(p: (a: A) => boolean): Set<A>;
49
+ filterNot(p: (a: A) => boolean): Set<A>;
50
+ /** Keep the first `n` elements. `n` of 0 or less keeps none. */
51
+ take(n: number): Set<A>;
52
+ takeWhile(p: (a: A) => boolean): Set<A>;
53
+ /** Keep the last `n` elements. `n` of 0 or less keeps none. */
54
+ takeRight(n: number): Set<A>;
55
+ /** Drop the first `n` elements. `n` of 0 or less drops nothing. */
56
+ drop(n: number): Set<A>;
57
+ /** Drop the last `n` elements. `n` of 0 or less drops nothing. */
58
+ dropRight(n: number): Set<A>;
59
+ dropWhile(p: (a: A) => boolean): Set<A>;
60
+ tail(): Set<A>;
61
+ init(): Set<A>;
62
+ /**
63
+ * Spread each element that's an array or another non-string iterable into the result, one level deep,
64
+ * keeping other elements, strings included, as they are.
65
+ */
66
+ flatten<B = Flattened<A>>(): Set<B>;
67
+ fold<B>(initial: B, fn: (acc: B, a: A) => B): B;
68
+ toList(): List<A>;
69
+ toSet(): Set<A>;
70
+ toArray<B = A>(): B[];
71
+ toString(): string;
72
+ }
73
+ declare const SetConstructor: <A>(iterable?: Iterable<A>) => Set<A>;
74
+ declare const SetStatics: {
75
+ /**
76
+ * Creates an empty Set
77
+ * Builds a new one each call: a native Set can't be frozen, so a shared empty Set could be
78
+ * changed for every caller through a cast. It costs about 20 ns more than a shared one.
79
+ * @returns An empty Set instance
80
+ */
81
+ empty: <A extends Type>() => Set<A>;
82
+ /**
83
+ * Creates a Set from variadic arguments
84
+ * @param values - Values to create set from
85
+ * @returns A Set containing the unique values
86
+ */
87
+ of: <A extends Type>(...values: A[]) => Set<A>;
88
+ /**
89
+ * Creates a Set from JSON string
90
+ * @param json - The JSON string
91
+ * @returns Set instance
92
+ */
93
+ fromJSON: <A>(json: string) => Set<A>;
94
+ /**
95
+ * Creates a Set from binary string
96
+ * @param binary - The binary string
97
+ * @returns Set instance
98
+ */
99
+ fromBinary: <A>(binary: string) => Set<A>;
100
+ };
101
+ export declare const Set: SetCompanion;
102
+ /** The type of `Set`: its constructor and its statics, named so that errors and hovers print `SetCompanion`. */
103
+ export interface SetCompanion extends SetConstructorType, SetStaticsType {}
104
+ type SetConstructorType = typeof SetConstructor;
105
+ type SetStaticsType = typeof SetStatics;
106
+ export {};
package/dist/set/index.js CHANGED
@@ -1 +1 @@
1
- import{At as e}from"../src-BQPeS6p2.js";export{e as Set};
1
+ import{Companion as e}from"../companion/Companion.js";import{base64ToUtf8 as t}from"../internal/base64.js";import{traverseWithConcurrency as n}from"../internal/concurrency.js";import{define as r}from"../internal/define.js";import{List as i}from"../list/index.js";import{Option as a}from"../option/index.js";import{createSerializer as o,expectMarker as s}from"../serialization/SerializationCompanion.js";import{reduceRightWiden as c,reduceWiden as l}from"../typeclass/variance.js";const u=globalThis.Set,d=r()(`Set`,{[Symbol.toStringTag]:`FunctypeSet`,get size(){return this.value.size},get isEmpty(){return this.value.size===0},[Symbol.iterator](){return this.value[Symbol.iterator]()},head(){return this.value.values().next().value},headOption(){return a(this.value.values().next().value)},last(){return Array.from(this.value).at(-1)},lastOption(){return a(Array.from(this.value).at(-1))},tail(){return f(new u(Array.from(this.value).slice(1)))},init(){return f(new u(Array.from(this.value).slice(0,-1)))},add(e){return f(new u([...this.value,e]))},remove(e){let t=new u(this.value);return t.delete(e),f(t)},contains(e){return this.value.has(e)},has(e){return this.value.has(e)},union(e){return f(new u([...this.value,...e]))},intersection(e){let t=new u(e);return f(new u([...this.value].filter(e=>t.has(e))))},difference(e){let t=new u(e);return f(new u([...this.value].filter(e=>!t.has(e))))},symmetricDifference(e){let t=this.value,n=[...new u(e)],r=new u(n);return f(new u([...[...this.value].filter(e=>!r.has(e)),...n.filter(e=>!t.has(e))]))},isSubsetOf(e){let t=new u(e);return[...this.value].every(e=>t.has(e))},isSupersetOf(e){let t=this.value;for(let n of e)if(!t.has(n))return!1;return!0},isDisjointFrom(e){let t=this.value;for(let n of e)if(t.has(n))return!1;return!0},map(e){return f(new u(Array.from(this.value).map(e)))},ap(e){let t=new u;for(let n of this.value)for(let r of e)t.add(r(n));return f(t)},flatMap(e){let t=new u;for(let n of this.value)for(let r of e(n))t.add(r);return f(t)},async mapAsync(e,t){return f(new u(await n(this.value,e,t?.concurrency??1)))},async flatMapAsync(e,t){let r=await n(this.value,e,t?.concurrency??1);return f(new u(r.flatMap(e=>Array.from(e))))},fold(e,t){let n=e;for(let e of this.value)n=t(n,e);return n},foldLeft(e){return t=>{let n=e;for(let e of this.value)n=t(n,e);return n}},foldRight(e){return t=>Array.from(this.value).reduceRight((e,n)=>t(n,e),e)},reduce(e){let t=Array.from(this.value);if(t.length===0)throw Error(`Cannot reduce empty Set`);return l(t,e)},reduceRight(e){let t=Array.from(this.value);if(t.length===0)throw Error(`Cannot reduceRight empty Set`);return c(t,e)},count(e){let t=0;for(let n of this.value)e(n)&&t++;return t},find(e){for(let t of this.value)if(e(t))return a(t);return a(null)},exists(e){for(let t of this.value)if(e(t))return!0;return!1},every(e){for(let t of this.value)if(!e(t))return!1;return!0},forEach(e){this.value.forEach(e)},filter(e){let t=new u;for(let n of this.value)e(n)&&t.add(n);return f(t)},filterNot(e){let t=new u;for(let n of this.value)e(n)||t.add(n);return f(t)},drop(e){return f(new u(Array.from(this.value).slice(Math.max(0,e))))},dropRight(e){if(!(e>0))return this;let t=Array.from(this.value);return f(new u(t.slice(0,Math.max(0,t.length-Math.trunc(e)))))},dropWhile(e){let t=Array.from(this.value),n=t.findIndex(t=>!e(t));return f(new u(n===-1?[]:t.slice(n)))},flatten(){let e=new u;for(let t of this.value)if(Array.isArray(t))for(let n of t)e.add(n);else if(t&&typeof t==`object`&&Symbol.iterator in t)for(let n of t)e.add(n);else e.add(t);return f(e)},take(e){return f(new u(Array.from(this.value).slice(0,Math.max(0,e))))},takeWhile(e){let t=new u;for(let n of this.value){if(!e(n))break;t.add(n)}return f(t)},takeRight(e){return f(new u(e>0?Array.from(this.value).slice(-e):[]))},toList(){return i(this.value)},toSet(){return this},toArray(){return Array.from(this.value)},toString(){return`Set(${Array.from(this.value).toString()})`},toValue(){return{_tag:`Set`,value:Array.from(this.value)}},toJSON(){return{"@functype":`Set`,_tag:`Set`,value:Array.from(this.value)}},pipe(e){return e(Array.from(this.value))},serialize(){return o(`Set`,Array.from(this.value))}}),f=e=>{let t=Object.create(d);return t._tag=`Set`,t.value=e,Object.freeze(t)},p=e=>f(new u(e)),m=(e,t)=>(s(e,`Set`,t),g(e.value??[])),h={empty:()=>f(new u),of:(...e)=>f(new u(e)),fromJSON:e=>m(JSON.parse(e),`fromJSON`),fromBinary:e=>{let n=t(e);return h.fromJSON(n)}},g=e(p,h);export{g as Set};
@@ -0,0 +1,120 @@
1
+ import { Foldable } from "../foldable/Foldable.js";
2
+ import { List } from "../list/index.js";
3
+ import { Matchable } from "../matchable/Matchable.js";
4
+ import { Option } from "../option/index.js";
5
+ import { Pipe } from "../pipe/index.js";
6
+ import { Serializable } from "../serializable/Serializable.js";
7
+ import { Traversable } from "../traversable/Traversable.js";
8
+ import { Type } from "../types/index.js";
9
+ import { Valuable } from "../valuable/Valuable.js";
10
+ /**
11
+ * Stack data structure - Last In, First Out (LIFO)
12
+ * Implements the Traversable interface for working with ordered collections
13
+ */
14
+ export type Stack<A extends Type> = {
15
+ readonly [Symbol.toStringTag]: string;
16
+ /**
17
+ * Push a value onto the top of the stack. The value may be a wider type;
18
+ * the result widens to `Stack<A | B>` (Scala: `:+[B >: A]`).
19
+ * @param value - The value to push
20
+ * @returns A new Stack with the value added
21
+ */
22
+ push<B extends Type>(value: B): Stack<A | B>;
23
+ /**
24
+ * Remove and return the top value from the stack
25
+ * @returns A tuple containing the new Stack and the value
26
+ */
27
+ pop(): [Stack<A>, Option<A>];
28
+ /**
29
+ * Return the top value without removing it
30
+ * @returns The top value wrapped in an Option
31
+ */
32
+ peek(): Option<A>;
33
+ /**
34
+ * Transforms each element in the stack using the provided function
35
+ * @param f - The mapping function
36
+ * @returns A new Stack with transformed elements
37
+ */
38
+ map<B extends Type>(f: (a: A) => B): Stack<B>;
39
+ /**
40
+ * Maps each element to a Stack and flattens the result
41
+ * @param f - The mapping function returning a Stack
42
+ * @returns A new flattened Stack
43
+ */
44
+ flatMap<B extends Type>(f: (a: A) => Stack<B>): Stack<B>;
45
+ /**
46
+ * Applies a Stack of functions to this Stack
47
+ * @param ff - Stack of functions to apply
48
+ * @returns A new Stack with applied functions
49
+ */
50
+ ap<B extends Type>(ff: Stack<(value: A) => B>): Stack<B>;
51
+ /**
52
+ * Maps each element to an async Stack and flattens the result
53
+ * @param f - The async mapping function returning a Stack
54
+ * @returns A promise of the new flattened Stack
55
+ */
56
+ flatMapAsync<B extends Type>(f: (value: A) => PromiseLike<Stack<B>>): PromiseLike<Stack<B>>;
57
+ /**
58
+ * Convert the stack to a List
59
+ * @returns A List containing all elements
60
+ */
61
+ toList(): List<A>;
62
+ /**
63
+ * Convert the stack to an array
64
+ * @returns An array of all elements
65
+ */
66
+ toArray(): A[];
67
+ /**
68
+ * Returns a string representation of the stack
69
+ * @returns A string representation
70
+ */
71
+ toString(): string;
72
+ /**
73
+ * Left-associative fold over all elements using an initial value and combining function.
74
+ */
75
+ fold<B>(initial: B, fn: (acc: B, a: A) => B): B;
76
+ /**
77
+ * Pattern matches over the Stack, applying a handler function based on whether it's empty
78
+ * @param patterns - Object with handler functions for Empty and NonEmpty variants
79
+ * @returns The result of applying the matching handler function
80
+ */
81
+ match<R>(patterns: {
82
+ Empty: () => R;
83
+ NonEmpty: (values: A[]) => R;
84
+ }): R;
85
+ } & Traversable<A> & Valuable<"Stack", A[]> & Serializable<A> & Pipe<A[]> & Foldable<A> & Matchable<A[], "Empty" | "NonEmpty">;
86
+ /** Copies `values`, so a later change to the caller's array can't reach the Stack. */
87
+ declare const StackConstructor: <A extends Type>(values?: readonly A[]) => Stack<A>;
88
+ declare const StackStatics: {
89
+ /**
90
+ * Creates an empty stack
91
+ * @returns An empty Stack instance
92
+ */
93
+ empty: <A extends Type>() => Stack<A>;
94
+ /**
95
+ * Creates a Stack from values, like `Stack([...values])`
96
+ * @example
97
+ * Stack.of(1, 2, 3) // same as Stack([1, 2, 3])
98
+ * @param values - The values to create the stack with
99
+ * @returns A Stack holding the values
100
+ */
101
+ of: <A extends Type>(...values: A[]) => Stack<A>;
102
+ /**
103
+ * Creates a Stack from JSON string
104
+ * @param json - The JSON string
105
+ * @returns Stack instance
106
+ */
107
+ fromJSON: <A>(json: string) => Stack<A>;
108
+ /**
109
+ * Creates a Stack from binary string
110
+ * @param binary - The binary string
111
+ * @returns Stack instance
112
+ */
113
+ fromBinary: <A>(binary: string) => Stack<A>;
114
+ };
115
+ export declare const Stack: StackCompanion;
116
+ /** The type of `Stack`: its constructor and its statics, named so that errors and hovers print `StackCompanion`. */
117
+ export interface StackCompanion extends StackConstructorType, StackStaticsType {}
118
+ type StackConstructorType = typeof StackConstructor;
119
+ type StackStaticsType = typeof StackStatics;
120
+ export {};
@@ -0,0 +1 @@
1
+ import{Companion as e}from"../companion/Companion.js";import{base64ToUtf8 as t}from"../internal/base64.js";import{define as n}from"../internal/define.js";import{List as r}from"../list/index.js";import{Option as i}from"../option/index.js";import{createSerializer as a,expectMarker as o}from"../serialization/SerializationCompanion.js";import{reduceRightWiden as s,reduceWiden as c}from"../typeclass/variance.js";const l=n()(`Stack`,{[Symbol.toStringTag]:`Stack`,get size(){return this.value.length},get isEmpty(){return this.value.length===0},contains(e){return this.value.includes(e)},reduce(e){if(this.value.length===0)throw Error(`Cannot reduce an empty stack`);return c(this.value,e)},reduceRight(e){if(this.value.length===0)throw Error(`Cannot reduce an empty stack`);return s(this.value,e)},push(e){return u([...this.value,e])},pop(){return this.value.length===0?[this,i(null)]:[u(this.value.slice(0,-1)),i(this.value[this.value.length-1])]},peek(){return i(this.value[this.value.length-1])},map(e){return u(this.value.map(e))},flatMap(e){return u(this.value.flatMap(t=>e(t).toArray()))},ap(e){let t=e.toArray();return u(this.value.flatMap(e=>t.map(t=>t(e))))},async flatMapAsync(e){let t=await Promise.all(this.value.map(async t=>await e(t)));return u(t.flatMap(e=>e.toArray()))},toList(){return r(this.value)},toArray(){return[...this.value]},toString(){return`Stack(${this.value.join(`, `)})`},fold(e,t){return this.value.reduce(t,e)},foldLeft(e){return t=>this.value.reduce(t,e)},foldRight(e){return t=>this.value.reduceRight((e,n)=>t(n,e),e)},match(e){return this.value.length===0?e.Empty():e.NonEmpty([...this.value])},toValue(){return{_tag:`Stack`,value:[...this.value]}},toJSON(){return{"@functype":`Stack`,_tag:`Stack`,value:[...this.value]}},pipe(e){return e([...this.value])},serialize(){return a(`Stack`,this.value)}}),u=e=>{let t=Object.create(l);return t._tag=`Stack`,t.value=e,Object.freeze(t)},d=(e=[])=>u([...e]),f=(e,t)=>(o(e,`Stack`,t),m(e.value??[])),p={empty:()=>u([]),of:(...e)=>u(e),fromJSON:e=>f(JSON.parse(e),`fromJSON`),fromBinary:e=>{let n=t(e);return p.fromJSON(n)}},m=e(d,p);export{m as Stack};
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Identifies which combinator emitted this event.
3
+ * String union is open so callers can extend with custom ops.
4
+ */
5
+ export type TraceOp = "map" | "flatMap" | "filter" | "fold" | "getOrElse" | "unwrap" | (string & {});
6
+ /**
7
+ * One observation emitted by a TracedOption combinator.
8
+ *
9
+ * @field spanId - Groups all events from one chain together. Stable across re-wraps.
10
+ * @field seq - Monotonic 0-based position within the span.
11
+ * @field op - Which combinator fired.
12
+ * @field tag - The container type name (e.g. "Option") from Symbol.toStringTag.
13
+ * @field inTag - Variant entering the op ("Some" | "None" for Option).
14
+ * @field outTag - Variant leaving the op; absent for terminal ops.
15
+ * @field label - Optional caller-supplied code-path name.
16
+ * @field meta - Op-specific detail (e.g. { kept: boolean } for filter).
17
+ */
18
+ export type TraceEvent = {
19
+ readonly spanId: string;
20
+ readonly seq: number;
21
+ readonly op: TraceOp;
22
+ readonly tag: string;
23
+ readonly inTag: string;
24
+ readonly outTag?: string;
25
+ readonly label?: string;
26
+ readonly meta?: Record<string, unknown>;
27
+ };