Repository navigation
Description
1. Goal
Go beyond call-site lint fixes: look at what Effect can do for effect-jsonapi as a whole (data modelling, errors, services and layers, resources, concurrency, streams, platform, observability, testing) and adopt it, including public API changes where they're worth it.
2. Scope and constraints
- docs/CONTRIBUTING.md § Effect: Effect v4 idioms and modules throughout; exceptions are non-Effect APIs adapted at the edge and hot paths where measured performance needs plain code. Absence is
Option; JSON:API wire shapes keep their native optionals andnull, spelled from their schemas. Exports are one PascalCase module per file, re-exported as a namespace. docs/architecture.md: every module derives from one resource definition; a new query family goes in both the flat and the nested struct inQuery.schema.- The JSON:API v1.1 wire format and the documented filter grammar (
docs/filter-grammar.md, e.g. F-NULL-1) must not change without an explicit decision. vp run docgenexecutes every@exampleagainstdist/: changed APIs need complete, runnable examples.- Public API changes are allowed. Each needs a changeset; pre-1.0 a breaking change is a
minor, nevermajor, with migration notes in the changeset text (and in the consumer migration guide, Migration guide: 0.21 → 0.22 (breaking changes for website, gardeneria, preferenceflow, in-the-dark) #620, when the consuming apps are affected). - Lint-level issues listed in §6 are handled separately.
3. Effect version
Catalog and installed: effect@4.1.4 (@effect/vitest 4.1.4), matching the catalogue; the published peer floor is ^4.1.0, so anything adopted must exist in 4.1.0 or the floor rises (a breaking change, checked by typecheck:floor).
v3 → v4 traps that matter here:
- Non-core modules are plain subpaths (
effect/http,effect/http-api,effect/sql,effect/cli,effect/process,effect/encoding,effect/crypto,effect/persistence,effect/testing, …), noteffect/unstable/*; every one is@stability unstable, as are some core exports (check the JSDoc@stabilitybefore calling one settled). - Not present in v4:
Either(→Result),Context.Tag/Effect.Service(→Context.Service),Effect.catchAll(→catch),catchAllCause(→catchCause),catchSome(→catchFilter),Effect.either(→result),Effect.fork/forkDaemon(→forkChild/forkDetach),Effect.async(→callback),Schema.decodeUnknown(→decodeUnknownEffect),FiberRef/Effect.locally(→References.*/provideService),Runtime<R>(→ManagedRuntime/runForkWith),effect/FastCheck(→ Effect's ownArbitrary),TestClockin core (→effect/testing). - Semantics:
OptionandResultare no longer Effects (Effect.fromOption/fromResult); layers are memoised acrossEffect.providecalls (Layer.freshor{ local: true }to opt out);Context.Servicehas no auto-generatedDefaultlayer; defects take precedence over typed errors in mixed causes;Equal.equalsis structural by default (Equal.byReferenceopts out); forked fibers keep the process alive. - Sources for every rename: Effect-TS/effect
mainMIGRATION.mdandmigration/*.md, effect.website/docs/v4/**, and the installednode_modules/effect(AGENTS.md,ai-docs/,dist/*.d.ts).
4. Candidates found in this repository
A starting point, not the full audit. Format: site → current shape → pattern → benefit → API impact.
Errors
src/Lid.ts:63UnknownLidError extends Error, thrown fromresolveRef(:212) → aSchema.TaggedErrorand aResult- orEffect-returning resolver, so Atomic handlers recover withcatchTagrather thaninstanceofinEffect.try. Benefit: typed channel, serialisable. API: yes.src/internal/filter.ts:78-97, 684, 736throwInvalidFilterfrom the literal encoder and operator check →Result-returning encoders. Benefit: no exceptions as control flow inside encoding. API: no (internal).src/Registry.ts:205, 213checkFamilythrowsUnknownFamily/FamilyMismatch→ decide: aResult-returning check (typed) or a documented construction-time defect. API: maybe.src/internal/conformance/semantics.ts:127, 156throwDomainMismatch→Result. API: no.orDie/dieaudit:Assemble.ts:1347,Idempotency.ts:511(digest),Idempotency.ts:876(request.textbody read: an I/O failure, maybe a 400 rather than a defect),Middleware.ts:1234, 1276,ServerErrors.ts:559, 631,internal/conformance/core.ts:1093, 1278, 1321. API: maybe.src/Client.ts:477-478andsrc/Registry.ts:59, 345type effects asEffect<unknown, unknown, unknown>→ precise error unions where the shape is known. API: maybe.
Services, layers and storage
src/Idempotency.ts:680Storeis a plain interface passed tolayer(store)(:866);memoryStore()(:721) keeps entries in aMutableHashMapwith no expiry → aContext.ServiceStorewithlayerMemoryonSynchronizedRef(atomic claim) and a TTL read throughClock; optionally aKeyValueStore-backed layer (effect/persistence, unstable) viatoSchemaStore. Benefit: atomic claim/record, expiry, swappable stores without threading values. API: yes.src/Lid.ts:205-219make()returns a mutable map closed over aMutableHashMap: keep (synchronous, per request) unless the resolver becomes effectful. API: no.
Effect.fn and tracing
- 7
Effect.fn/ 6Effect.fnUntracedsites against roughly 60(x) => Effect.gen(...)wrappers, concentrated insrc/internal/conformance/spec.ts(26),profile.ts(11),relationships.ts(7),sort.ts(5),pagination.ts(4), plusHandlers.ts(2) andAtomic.ts(2) →Effect.fn("Conformance.rule")etc. Benefit: spans per rule and handler. API: no.
Concurrency and batching
src/Handlers.ts:1147-1166builds includebatchesby type by hand, thenEffect.forEach(batches, load, { concurrency });src/ResourceHandlers.ts:949-1048loadRefswith a hard-coded concurrency of 6 →Request+RequestResolver.makeGrouped(grouped by type) withEffect.requestand a per-request cache. Benefit: dedupe and batching across the whole include tree, not per level. API: maybe (loader signature).- Module-level
WeakMapmemo caches keyed by schema identity (ApiError.ts:239,Resource.ts:2756, 2817,internal/sparse.ts:171,Middleware.ts:1025,internal/wireNames.ts:206): hand-written get/set memoisation on the hot path →Function.memoize(a privateWeakMapby object identity, same cost) where the key is the single argument; keep the rest, recorded with the reason. API: no.
Data modelling
src/internal/wireNames.ts:71runs a decode withEffect.runSyncExitWith(noServices)→Schema.decodeUnknownExit/decodeUnknownResult, with no runtime call in library code. API: no.
Streams
src/Client.ts:1465-1538offers page-window arithmetic but no paginated fetch → an additiveClienthelper onStream.paginatethat followslinks.next. API: yes (additive).
Style
- Tacit
src/internal/json.ts:35(flow() andsrc/internal/conformance/profile.ts:490(Effect.map(Arr.of)) → explicit lambdas. API: no.
Observability
src/ServerErrors.ts:639logs an unhandled defect with a bracketed string prefix →Effect.annotateLogs+Cause.pretty, and consider anErrorReporterhook (unstable) so applications can route defects to their tracker. API: maybe (additive).
5. Full checklist
1. Data modelling
-
Schema.Class/TaggedClass/Struct/TaggedStructfor every type that crosses a boundary (replaces aninterfaceplus a hand validator) - Decode at the boundary:
Schema.decodeUnknownEffect/decodeUnknownResult/decodeUnknownOption,decodeUnknownSynconly at edges (replacesJSON.parse(x) as T,ascasts,isFooguards) - Transformations:
Schema.decodeTo+SchemaGetter; built-insNumberFromString,DateTimeUtcFromString,fromJsonString,URLFromString,Uint8ArrayFromBase64,OptionFromNullOr/OptionFromOptionalKey(replacesparseInt,new Date(str), null/undefined shuffles) - Unions:
Schema.Union,TaggedUnion,toTaggedUnion(tag),Literals,Enum(replaces string unions duplicated as arrays) - Checks:
.check(Schema.isMinLength, isPattern, isInt, isBetween, …),Schema.makeFilter,Schema.refine(replaces scatteredif (…) throw) - Brands:
Schema.brand,Brand.nominal/Brand.check,Schema.fromBrand(replaces barestringids and hand-rolled__brandcasts) - Defaults:
withConstructorDefault,withDecodingDefault(Key),optionalKeyvsoptional(replaces?? defaultin every consumer) - Derivation:
toJsonSchemaDocument,toStandardSchemaV1,Arbitrary.schema,toEquivalence,toFormatter,toCodecJson,toDifferJsonPatch,toIso(replaces a second representation kept by hand) - Built-in schemas (
NonEmptyString,Trimmed,Int,Natural,Port,Redacted,DateTimeUtc,Duration,BigDecimal,Json,DomainName,SemVer,TimeZone,Uint8Array,Defect()) over re-declared regexes -
Data.TaggedEnum+Data.taggedEnum<T>()($is,$match),Data.TaggedClassfor internal ADTs (replaces{ kind }unions +switch) -
Equal.equals/Hash/Equal.byReference(replacesJSON.stringifyequality, hand deep-equal; v4 is structural by default) -
Optionfor public absence (fromNullishOr,getOrElse,match,liftThrowable) (replacesT | null | undefinedreturns; wire and framework edges keep native nulls) -
Resultfor pure synchronous fallible code (replacesEither, hand-rolled{ ok }objects, throwing parsers) -
Struct.pick/omit/evolve/renameKeys,Tuple(replaces spread-and-delete)
2. Errors
-
Schema.TaggedError<Self>()(tag, { …, cause: Schema.Defect() })for expected failures,Data.TaggedErrorfor in-process-only ones (replacesthrow new Error,extends Error, string codes,Effect.fail("…")) - Reason errors: one tagged error with a tagged
reason;Effect.catchReason/catchReasons/unwrapReason(replaces an exploding error union) -
Effect.catchTag/catchTags/catch/catchIf/catchFilter/mapError/tapErrorTag/Effect.result/Effect.option(replaces_tagchecks andinstanceof) - Errors vs defects: audit every
orDie/Effect.die; die only on the proven-impossible;catchDefectonly at edges (v4: defects win in mixed causes) -
Cause.pretty/squash/findError/hasInterruptsOnly,Exit.matchat reporting edges (replacesString(err)) -
Effect.try/Effect.tryPromise({ try: (signal) => … })/Effect.callback/Effect.promise, once per non-Effect API (replacestry/catchin generators andnew Promise) - Retries:
Effect.retry(Schedule.exponential(…).pipe(Schedule.jittered, Schedule.upTo(…))),Effect.retry({ times, while }),HttpClient.retryTransient(replaces loops with sleeps) -
ExecutionPlan.make+Effect.withExecutionPlan(unstable) for fallback providers -
ErrorReporter+Effect.withErrorReporting(unstable) for error tracking hooks
3. Services and layers
-
class X extends Context.Service<X, Shape>()("pkg/X") { static readonly layer = Layer.effect(X, …) }; v4 has no auto-generatedDefaultlayer (replaces singletons,Context.Tag/GenericTag, factories passed by hand) - Resolve dependencies when the layer is built, so methods have
R = never -
Context.Reference<T>(id, { defaultValue })for settings with a default (replaces modulelettoggles) - Composition:
Layer.provide/provideMerge/mergeAll/unwrap/effectDiscard/fresh/launch,LayerMap.Service(unstable); v4 memoises layers acrossEffect.provide - Test doubles:
Layer.mock,layerTest/layerMemorysiblings (replacesvi.mock) -
Effect.fn("Mod.fn")for reusable effectful functions,Effect.fnUntracedfor hot internals (replaces(x) => Effect.gen(…)) - Scopes:
Effect.acquireRelease/acquireUseRelease/addFinalizer/scoped/ensuring/onExit/acquireDisposable(replacestry/finally) -
RcMap,RcRef,ScopedRef,Resource,LayerReffor shared, lazily created resources - Edges:
ManagedRuntime,NodeRuntime.runMain,FiberSet.makeRuntimePromise,Effect.runForkWith;Effect.run*in one edge file (replacesrunPromise(… Effect.provide(layer))per call)
5. Concurrency and resources
-
Effect.all/Effect.forEachwith explicitconcurrency,discard,mode: "result";Effect.partition/validate(replacesPromise.all/allSettled) - Fibers:
forkChild/forkScoped/forkDetach/forkIn,FiberSet/FiberMap/FiberHandle(replacesvoid promise,setIntervaljobs) -
Semaphore,PartitionedSemaphore,Latch(replaces "isRunning" flags, p-limit) -
Queue,PubSub,Deferred(replacesEventEmitter, resolve-later promises) -
Ref,SynchronizedRef,SubscriptionRef,Effect.tx+TxRef(replaces mutable closures and module-levelMapstate) -
Pool.make/makeWithTTL(replaces hand-rolled pools) -
Cache.make,ScopedCache,Effect.cached/cachedWithTTL,PersistedCache(replacesMapmemos with manual expiry) -
Request+RequestResolver.make/makeGrouped/batchN/withCache,Effect.request(replaces N+1 loops and hand batching) -
Effect.timeout/timeoutOption/timeoutOrElse/race/raceFirst,Effect.abortSignal(replacesPromise.race,AbortControllerplumbing) -
RateLimiter/CircuitBreaker(effect/persistence, unstable),HttpClient.withRateLimiter
6. Streams
- Sources:
Stream.fromIterable/fromAsyncIterable/fromReadableStream/fromEventListener/callback/paginate/fromQueue/fromPubSub - Operators:
mapEffect(f, { concurrency }),grouped,groupedWithin,rechunk,buffer,throttle,debounce,splitLines,decodeText/encodeText,retry,timeout,haltWhen - Sinks and running:
Sink.fold/forEach/collect,runCollect/runForEach/runDrain/toReadableStream/toAsyncIterable - Codecs:
Stream.pipeThroughChannelwitheffect/encodingNdjson/Sse/Csv/SchemaBinary(unstable) - Replace
for await/getReader()loops and manual batching withsetTimeoutflushes
8. Platform
- HTTP client (
effect/http):HttpClient,FetchHttpClient.layer,HttpClientRequest.*,filterStatusOk,retryTransient,HttpClientResponse.schemaJson/matchStatus(replacesfetch) - HTTP server:
HttpRouter,HttpServerResponse,HttpMiddleware;effect/http-api(HttpApi*,HttpApiClient,OpenApi,HttpApiTest) - FS/OS:
FileSystem,Path,effect/processChildProcess+ChildProcessSpawner,NodeServices.layer(replacesnode:fs,node:path,child_process) - Storage:
effect/persistenceKeyValueStore(layerMemory,layerFileSystem,toSchemaStore),PersistedQueue(unstable) - Encoding/crypto (unstable):
effect/encoding(Base64,Hex,Csv,Xml,Zip, …),effect/crypto(Digest,Mac,SecureRandom, …),effect/jose(replacesbtoa,Buffer, hand-rolled hex,crypto.subtle) - Library code depends on abstract services; applications supply
@effect/platform-node/-browserlayers
9. Observability
- Tracing:
Effect.fnspans,Effect.withSpan,annotateCurrentSpan,Layer.withSpan,Effect.linkSpans - Logging:
Effect.log*,annotateLogs,withLogSpan,Logger.*,References.MinimumLogLevel,Console(replacesconsole.*) - Metrics:
Metric.counter/gauge/histogram/summary/frequency/timer,Effect.track*(replaces counters in module variables)
10. Collections and utilities
-
Array(groupBy,partition,dedupe,sortBy,chunksOf,head,findFirst,filterMap,getSomes;makeBy/rangenever return empty) (replaces lodash,arr[0]!) -
Record(map,filter,collect,get,toEntries),Struct,Tuple,Iterable -
HashMap/HashSet/Chunk/MutableHashMap/Trie/HashRingwhere structural keys or persistence matter (nativeMapis fine otherwise) -
Match.type/Match.valuewithtag,tags(Exhaustive),exhaustive,discriminatorsExhaustive;$match(replaces non-exhaustiveswitch) -
Predicate(isString,isObject,hasProperty,isTagged,isNotNullish,and/or/not) (replaces ownisRecordhelpers) -
Order(mapInput,Struct,combine,flip) andEquivalence(replaces(a, b) => a.x - b.x);BigDecimal,ByteSize,SemVer,JsonPointer,JsonPatch,TextDiff,Glob,Strcase helpers -
Function.dual+Pipeablefor exported helpers (additive API) -
Optic(Lens,Prism,Iso,Schema.toIso) for deep immutable updates
11. Testing
-
@effect/vitest:it.effect/it.live/it.effect.each/it.effect.prop/it.layer/layer(L)/it.flakyTest(replacesEffect.runPromiseinsideit) -
TestClock/TestConsolefromeffect/testing(replacesvi.useFakeTimers, real sleeps) -
Arbitrary.schema(S)for property tests (effect/FastCheckis gone from v4) - In-memory layers and
HttpApiTest/RpcTestinstead ofvi.mock
12. Newer modules (all @stability unstable)
-
effect/http/effect/http-api(in use): check new helpers (HttpApiTest,HttpClient.retryTransientin the conformance runner) against the hand-written equivalents -
effect/persistenceKeyValueStore/PersistedCachefor the idempotency store -
effect/cryptoDigest+effect/encodingHex(tracked in Use effect/crypto Digest and Record helpers instead of hand-rolled code #646) - Not applicable:
effect/sql,effect/rpc,effect/ai,effect/cli,effect/cluster,effect/workflow,effect/reactivity(a library overHttpApi; storage stays behind seams).
Dropped as not applicable: §4 Configuration (the library takes explicit options and reads no environment; a layerConfig is only worth it if a consumer asks) and §7 Time (no clock reads today; requestTimeout already uses Duration; the idempotency TTL above is the one new time use).
Anti-patterns to grep for (pattern → replacement; run against src/ excluding comments and @example blocks):
async function / await / .then( inside Effect code → Effect.gen / Effect.fn; Effect.tryPromise at the edge
try { … } catch around yield* or Effect.run* → Effect.try / catchTag / catch; Exit/Cause at edges
\bthrow new\b in src/ (library code) → Schema.TaggedError + return yield* / Effect.fail; Effect.die for bugs
class \w+Error extends Error → Schema.TaggedError / Data.TaggedError
Effect.fail\("|Effect.fail\(new Error → tagged error with fields
: .*\| null\b|return null;|return undefined; → Option (keep at wire/framework edges)
\bas [A-Z]\w*\b after JSON.parse / .json() / decode → Schema.decodeUnknown*
JSON.parse\( → Schema.fromJsonString(S) / decodeUnknownEffect
for (.*retry|attempt) / while.*attempt / 2 \*\* attempt → Effect.retry(Schedule…) / HttpClient.retryTransient
setTimeout|setInterval|new Promise\(\s*\(?res → Effect.sleep / Schedule / Effect.callback / Deferred
Date\.now\(\)|new Date\(\)|Math\.random\(\) → Clock / DateTime.now / Random (crypto: SecureRandom)
Promise\.all\(|Promise\.allSettled\( → Effect.all / forEach with { concurrency }
Promise\.race\( → Effect.timeout / Effect.race
process\.env\.|import\.meta\.env → Config + ConfigProvider (fromEnv / fromEnvRecord)
apiKey: string|token: string|password: string → Redacted
^let \w+ = |^const \w+ = new (Map|Set)\( at module top → Ref / service state / Cache (and "sideEffects": false)
export const \w+ = new \w+Client\( → Context.Service + Layer
functions taking (deps, …) / ctx: { db, http } → yield* Service in layer construction
Effect.runPromise|runSync|runFork outside one edge file → ManagedRuntime / NodeRuntime.runMain / it.effect
=> Effect.gen\(function\* → Effect.fn("name") / fnUntraced
Effect\.(map|flatMap|tap)\(\w+\) / flow\( → explicit lambdas (avoid tacit style)
yield\* Option\.|yield\* Result\. in Effect.gen → Effect.fromOption / Effect.fromResult (v4: no longer Effects)
repeated Effect.provide(layer) per call → compose once; layers memoise across provides
catchAll|catchAllCause|either\(|fork\(|forkDaemon|Effect\.Tag|Effect\.Service|Context\.Tag|GenericTag|FiberRef|Effect\.locally|Either\. → v4 names
\.orDie\b / Effect\.orDie in library modules → keep typed errors; die only on proven-impossible
switch \((\w+)\.(_tag|type|kind)\) → Match.tags(Exhaustive) / $match / Match.exhaustive
typeof \w+ === "(string|object)"|isRecord|isObject\( → Predicate / Schema
fetch\(|axios → HttpClient + HttpClientResponse.schemaJson
node:fs|node:path|child_process in library src → FileSystem / Path / effect/process
btoa|atob|Buffer\.from\(.*(base64|hex) → effect/encoding Base64 / Hex
console\.(log|error|warn) → Effect.log* / Logger
\bany\b in error position / Effect<.*, unknown → precise tagged unions
for await \(|\.getReader\(\) → Stream.fromAsyncIterable / fromReadableStream
lodash|ramda|date-fns|dayjs|p-limit|p-retry|lru-cache → Array/Record/Order, DateTime, Semaphore, Schedule, Cache
6. Related issues
Covered separately (don't duplicate here):
- Use effect/crypto Digest and Record helpers instead of hand-rolled code #646 Use
effect/cryptoDigestandRecordhelpers instead of hand-rolled code - Remove the last three Function.cast double assertions (Endpoint.resource, Resource.extend, Resource.family) #635 Remove the last three
Function.castdouble assertions - Adopt @effect/vitest (it.effect / layer) for tests; take effect-run-in-body and strict-effect-provide to error #600 Adopt
@effect/vitest(it.effect/layer) for tests - Pay down the type-aware lint findings (tsgolint) #536 Pay down the type-aware lint findings (tsgolint)
- Move every @enfect/oxlint rule to error #533 Move every
@enfect/oxlintrule to error - Migration guide: 0.21 → 0.22 (breaking changes for website, gardeneria, preferenceflow, in-the-dark) #620 Migration guide 0.21 → 0.22 (where consumer-facing breaks are written up)
7. Instructions for the assigned session
- Audit every module against §5, not only the candidates in §4. Record each finding in the PR description as adopt, defer or reject, with a one-line reason.
- Read the installed
node_modules/effect(AGENTS.md,ai-docs/,.d.ts) and the effect.website v4 docs / Effect-TS/effectmain(MIGRATION.md,migration/*.md) rather than guessing APIs. Effect-TS/effect-smol is archived; ignore it. - Make the changes in one PR (the repository's one-PR-per-change rule), in reviewable commits by area. Keep behaviour unless a change is an intended improvement, and call each one out in the PR.
- Benchmark before and after any hot path touched (no bench task exists: measure with a focused script and report the numbers in the PR).
- Run the full gates (
vp run ci,vp run docgen) and the pre-commit Fallow audit; say in the PR body which couldn't run. - Update docs/CONTRIBUTING.md and AGENTS.md (and package
AGENTS.mdfiles) if a convention changes, e.g. a new service or error pattern becomes the house style. - File follow-up issues for anything deferred.
8. Acceptance criteria
- Every §5 checklist item is marked adopted, not applicable, or deferred (with a follow-up issue)
-
vp run ciand the repository's other gates are green; any that couldn't run are named in the PR body - Changesets present for every published-package change, at the right level, with migration notes
- No new lint allowances (no new
warnentries, scoped overrides or inline disables without a recorded reason)
Generated by Claude Code
Activity