Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

feat(cli): extract effect-errors into local src

jkomyno333b03c3b688
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fb1728d88..f843f2a1f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -538,15 +538,15 @@ importers:
ansis:
specifier: ^4.1.0
version: 4.1.0
+ comment-json:
+ specifier: ^4.2.5
+ version: 4.2.5
decompress:
specifier: ^4.2.1
version: 4.2.1
effect:
specifier: ^3.16.16
version: 3.16.16
- effect-errors:
- specifier: ^1.10.11
- version: 1.10.11(aea1fe99f240c5dd77146c654a1423dd)
indent-string:
specifier: ^5.0.0
version: 5.0.0
@@ -559,6 +559,9 @@ importers:
semver:
specifier: ^7.7.2
version: 7.7.2
+ source-map-js:
+ specifier: ^1.2.1
+ version: 1.2.1
superjson:
specifier: ^2.2.2
version: 2.2.2
@@ -1240,15 +1243,6 @@ packages:
'@effect/sql': ^0.38.2
effect: ^3.16.8
- '@effect/[email protected]':
- resolution: {integrity: sha512-AImYc+Tg/EF0miKKgORgQEEZ1a6PpdqkH2ZU4wt0ChmWi1XFa1WF/NYzK5qRrtfSKF+ug6Vd/5/psWvZNJTdyw==}
- peerDependencies:
- '@effect/cluster': ^0.39.4
- '@effect/platform': ^0.85.2
- '@effect/rpc': ^0.62.4
- '@effect/sql': ^0.38.2
- effect: ^3.16.8
-
'@effect/[email protected]':
resolution: {integrity: sha512-zIRixbQeO6QniR0k2mwR7DmR2HO1w6+qQlzQ5nb8lyPyPgd1gV9wo/9yBeB6zRC+CGnxiUiYsRMamclVISuxLw==}
peerDependencies:
@@ -3945,17 +3939,6 @@ packages:
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
- resolution: {integrity: sha512-lTktjnqeHfXSGQuhHm4jGWdZFfiWVZQP+szeEOuEmGEa2n4tNAu0FGO3LgS6Vp9nOatINYE3u65dFf28TtxxkQ==}
- engines: {node: '>=20.x'}
- peerDependencies:
- '@effect/cluster': 0.x
- '@effect/platform': 0.x
- '@effect/platform-node': 0.x
- '@effect/rpc': 0.x
- '@effect/sql': 0.x
- effect: 3.x
-
resolution: {integrity: sha512-q8jsuAJykQJJ9jDkR9VaAR1JeHnEDn49g6+LkveIcfW3nIPUJw6BrC9ZPaVCJWmU23vKoVj9XqJmC/EW8kiI8g==}
@@ -6173,10 +6156,6 @@ packages:
resolution: {integrity: sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==}
engines: {node: '>=14.0'}
- resolution: {integrity: sha512-u5otvFBOBZvmdjWLVW+5DAc9Nkq8f24g0O9oY7qw2JVIF1VocIFoyz9JFkuVOS2j41AufeO0xnlweJ2RLT8nGw==}
- engines: {node: '>=20.18.1'}
-
resolution: {integrity: sha512-B06u0wXkEd+o5gOCMl/ZHl5cfpYbDZKAT+HWTL+Hws6jWu7dCiqBBXXXzMFcFVJb8D4ytAnYmxJA83uwOQRSsg==}
@@ -7260,21 +7239,6 @@ snapshots:
- bufferutil
- utf-8-validate
- dependencies:
- '@effect/platform': 0.85.2([email protected])
- '@effect/rpc': 0.62.4(@effect/[email protected]([email protected]))([email protected])
- effect: 3.16.16
- mime: 3.0.0
- undici: 7.10.0
- ws: 8.18.2
- transitivePeerDependencies:
- - bufferutil
- - utf-8-validate
-
dependencies:
effect: 3.16.16
@@ -9619,6 +9583,14 @@ snapshots:
chai: 5.2.0
tinyrainbow: 2.0.0
+ dependencies:
+ '@vitest/spy': 3.2.4
+ estree-walker: 3.0.3
+ magic-string: 0.30.17
+ optionalDependencies:
+
dependencies:
'@vitest/spy': 3.2.4
@@ -9627,6 +9599,14 @@ snapshots:
optionalDependencies:
+ dependencies:
+ '@vitest/spy': 3.2.4
+ estree-walker: 3.0.3
+ magic-string: 0.30.17
+ optionalDependencies:
+
'@vitest/[email protected]':
dependencies:
tinyrainbow: 2.0.0
@@ -9656,7 +9636,7 @@ snapshots:
sirv: 3.0.1
tinyglobby: 0.2.14
tinyrainbow: 2.0.0
'@vitest/[email protected]':
dependencies:
@@ -10245,18 +10225,6 @@ snapshots:
- [email protected](aea1fe99f240c5dd77146c654a1423dd):
- dependencies:
- '@effect/platform': 0.85.2([email protected])
- '@effect/rpc': 0.62.4(@effect/[email protected]([email protected]))([email protected])
- comment-json: 4.2.5
- effect: 3.16.16
- picocolors: 1.1.1
- source-map-js: 1.2.1
-
dependencies:
'@standard-schema/spec': 1.0.0
@@ -12568,8 +12536,6 @@ snapshots:
dependencies:
'@fastify/busboy': 2.1.1
-
dependencies:
defu: 6.1.4
@@ -12720,7 +12686,7 @@ snapshots:
dependencies:
'@types/chai': 5.2.2
'@vitest/expect': 3.2.4
'@vitest/pretty-format': 3.2.4
'@vitest/runner': 3.2.4
'@vitest/snapshot': 3.2.4
@@ -12804,7 +12770,7 @@ snapshots:
dependencies:
'@types/chai': 5.2.2
'@vitest/expect': 3.2.4
'@vitest/pretty-format': 3.2.4
'@vitest/runner': 3.2.4
'@vitest/snapshot': 3.2.4
diff --git a/ts/packages/cli/package.json b/ts/packages/cli/package.json
index 584003580..dccec7a7c 100644
--- a/ts/packages/cli/package.json
+++ b/ts/packages/cli/package.json
@@ -66,13 +66,14 @@
"@effect/platform-bun": "^0.70.4",
"@effect/platform-node-shared": "^0.40.4",
"ansis": "^4.1.0",
+ "comment-json": "^4.2.5",
"decompress": "^4.2.1",
"effect": "^3.16.16",
- "effect-errors": "^1.10.11",
"indent-string": "^5.0.0",
"open": "^10.2.0",
"picocolors": "^1.1.1",
"semver": "^7.7.2",
+ "source-map-js": "^1.2.1",
"superjson": "^2.2.2"
},
"gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064"
diff --git a/ts/packages/cli/src/bin.ts b/ts/packages/cli/src/bin.ts
index 159b3f834..589b1fefa 100644
--- a/ts/packages/cli/src/bin.ts
+++ b/ts/packages/cli/src/bin.ts
@@ -1,6 +1,6 @@
import process from 'node:process';
import { Cause, Console, Effect, Exit, Layer, Logger } from 'effect';
-import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors';
+import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
import { CliConfig } from '@effect/cli';
import { FetchHttpClient } from '@effect/platform';
import { BunContext, BunRuntime, BunFileSystem } from '@effect/platform-bun';
diff --git a/ts/packages/cli/src/effect-errors/README.md b/ts/packages/cli/src/effect-errors/README.md
new file mode 100644
index 000000000..3f87ea3eb
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/README.md
@@ -0,0 +1,4 @@
+The code in this folder is adapter from the `effect-errors` package published at https://github.com/jpb06/effect-errors/tree/d8bedbcb9e0506eabe396449cd16cd247eb55003.
+Compared to the original, it has been modified to work with custom colors.
+
+See the original [MIT License](https://github.com/jpb06/effect-errors/blob/d8bedbcb9e0506eabe396449cd16cd247eb55003/LICENSE).
diff --git a/ts/packages/cli/src/effect-errors/capture-errors.ts b/ts/packages/cli/src/effect-errors/capture-errors.ts
new file mode 100644
index 000000000..d62f8e29f
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/capture-errors.ts
@@ -0,0 +1,55 @@
+import type { PlatformError } from '@effect/platform/Error';
+import type { FileSystem } from '@effect/platform/FileSystem';
+import { Effect } from 'effect';
+import { type Cause, isInterruptedOnly } from 'effect/Cause';
+
+import type { JsonParsingError } from 'effect-errors/dependencies/fs';
+import { captureErrorsFrom } from 'effect-errors/logic/errors';
+import {
+ type ErrorLocation,
+ type ErrorRelatedSources,
+ transformRawError,
+} from 'effect-errors/sourcemaps';
+import type { ErrorSpan } from 'effect-errors/types';
+
+export interface ErrorData {
+ errorType: unknown;
+ message: unknown;
+ stack: string[] | undefined;
+ sources: Omit<ErrorRelatedSources, '_tag'>[] | undefined;
+ location: Omit<ErrorLocation, '_tag'>[] | undefined;
+ spans: ErrorSpan[] | undefined;
+ isPlainString: boolean;
+}
+
+export interface CapturedErrors {
+ interrupted: boolean;
+ errors: ErrorData[];
+}
+
+export interface CaptureErrorsOptions {
+ stripCwd?: boolean;
+}
+
+export const captureErrors = <E>(
+ cause: Cause<E>,
+ options: CaptureErrorsOptions = {
+ stripCwd: true,
+ }
+): Effect.Effect<CapturedErrors, PlatformError | JsonParsingError, FileSystem> =>
+ Effect.gen(function* () {
+ if (isInterruptedOnly(cause)) {
+ return {
+ interrupted: true,
+ errors: [],
+ };
+ }
+
+ const rawErrors = captureErrorsFrom<E>(cause);
+ const errors = yield* Effect.forEach(rawErrors, transformRawError(options));
+
+ return {
+ interrupted: false,
+ errors,
+ };
+ });
diff --git a/ts/packages/cli/src/effect-errors/dependencies/fs/index.ts b/ts/packages/cli/src/effect-errors/dependencies/fs/index.ts
new file mode 100644
index 000000000..8490a1a4e
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/dependencies/fs/index.ts
@@ -0,0 +1 @@
+export * from './read-json/index';
diff --git a/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/index.ts b/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/index.ts
new file mode 100644
index 000000000..eb80f3366
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/index.ts
@@ -0,0 +1,2 @@
+export * from './json-parsing.error';
+export * from './read-json';
diff --git a/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/json-parsing.error.ts b/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/json-parsing.error.ts
new file mode 100644
index 000000000..d5edd79bb
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/json-parsing.error.ts
@@ -0,0 +1,6 @@
+import { TaggedError } from 'effect/Data';
+
+export class JsonParsingError extends TaggedError('json-parsing-error')<{
+ cause?: unknown;
+ message?: string;
+}> {}
diff --git a/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/parse-json.ts b/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/parse-json.ts
new file mode 100644
index 000000000..320fe0a81
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/parse-json.ts
@@ -0,0 +1,21 @@
+import { parse } from 'comment-json';
+import { Effect, pipe } from 'effect';
+
+import { JsonParsingError } from './json-parsing.error';
+
+export const parseJson = (data: string) =>
+ pipe(
+ Effect.sync(() => parse(data, null, true)),
+ Effect.catchAll(e =>
+ Effect.fail(
+ new JsonParsingError({
+ cause: e,
+ })
+ )
+ ),
+ Effect.withSpan('parse-json', {
+ attributes: {
+ data,
+ },
+ })
+ );
diff --git a/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/read-json.ts b/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/read-json.ts
new file mode 100644
index 000000000..f489557d2
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/read-json.ts
@@ -0,0 +1,21 @@
+import { FileSystem } from '@effect/platform/FileSystem';
+import { Effect, pipe } from 'effect';
+
+import { parseJson } from './parse-json';
+
+export const readJsonEffect = <TJson>(filePath: string) =>
+ pipe(
+ Effect.gen(function* () {
+ const { readFileString } = yield* FileSystem;
+ const data = yield* readFileString(filePath, 'utf8');
+
+ if (data.length === 0) {
+ return null;
+ }
+
+ const json = yield* parseJson(data);
+
+ return json as TJson;
+ }),
+ Effect.withSpan('read-json', { attributes: { filePath } })
+ );
diff --git a/ts/packages/cli/src/effect-errors/index.ts b/ts/packages/cli/src/effect-errors/index.ts
new file mode 100644
index 000000000..e8b3671a1
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/index.ts
@@ -0,0 +1,5 @@
+export * from './capture-errors.js';
+export * from './pretty-print-from-captured-errors.js';
+export type { ErrorLocation, ErrorRelatedSources, SourceCode } from './sourcemaps';
+export type { ErrorSpan } from './types/index';
+export * from './types/pretty-print-options.type';
diff --git a/ts/packages/cli/src/effect-errors/logic/errors/capture-errors-from-cause.ts b/ts/packages/cli/src/effect-errors/logic/errors/capture-errors-from-cause.ts
new file mode 100644
index 000000000..e2dd3481f
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/errors/capture-errors-from-cause.ts
@@ -0,0 +1,15 @@
+import { type Cause, reduceWithContext } from 'effect/Cause';
+
+import type { PrettyError } from 'effect-errors/types';
+
+import { parseError } from './parse-error';
+
+export const captureErrorsFrom = <E>(cause: Cause<E>): readonly PrettyError[] =>
+ reduceWithContext(cause, undefined, {
+ emptyCase: (): readonly PrettyError[] => [],
+ dieCase: (_, unknownError) => [parseError(unknownError)],
+ failCase: (_, error) => [parseError(error)],
+ interruptCase: () => [],
+ parallelCase: (_, l, r) => [...l, ...r],
+ sequentialCase: (_, l, r) => [...l, ...r],
+ });
diff --git a/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.test.ts b/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.test.ts
new file mode 100644
index 000000000..29fea00d1
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+
+import { extractErrorDetails } from './extract-error-details';
+
+describe('extractErrorDetails function', () => {
+ it('should handle plain strings', () => {
+ const error = 'Oh no';
+
+ const result = extractErrorDetails(error);
+
+ expect(result).toStrictEqual({ isPlainString: true, message: error });
+ });
+
+ it('should handle errors with cause', () => {
+ const _tag = 'MyError';
+ const message = 'Oh no!';
+ const cause = 'Some cause';
+
+ class MyError extends Error {
+ constructor(message: string, cause: string) {
+ super(message, { cause });
+ }
+
+ public _tag = _tag;
+ }
+ const error = new MyError(message, cause);
+
+ const result = extractErrorDetails(error);
+
+ expect(result).toStrictEqual({
+ isPlainString: false,
+ message: cause,
+ type: _tag,
+ });
+ });
+
+ it('should handle errors with Error ctor', () => {
+ const message = 'Oh no!';
+ const cause = 'Some cause';
+
+ class MyError extends Error {
+ constructor(message: string, cause: string) {
+ super(message, { cause });
+ }
+ }
+ const error = new MyError(message, cause);
+
+ const result = extractErrorDetails(error);
+
+ expect(result).toStrictEqual({
+ isPlainString: false,
+ message: [message],
+ type: 'Error',
+ });
+ });
+
+ it('should handle plain objects with tag attribute', () => {
+ const error = {
+ _tag: 'MyError',
+ message: 'Oh no!',
+ };
+
+ const result = extractErrorDetails(error);
+
+ expect(result).toStrictEqual({
+ isPlainString: false,
+ message: error.message,
+ type: error._tag,
+ });
+ });
+
+ it('should handle plain objects with toString impl', () => {
+ const errorType = 'MyError';
+ const error = {
+ message: 'Oh no!',
+ toString: () => `${errorType}: Oh no!`,
+ };
+
+ const result = extractErrorDetails(error);
+
+ expect(result).toStrictEqual({
+ isPlainString: false,
+ message: [error.message],
+ type: errorType,
+ });
+ });
+
+ it('should handle plain objects with toString impl and underlying type', () => {
+ const errorTypeWithUnderlyingType = 'MyError: Sucks to be you';
+ const error = {
+ message: 'Oh no!',
+ toString: () => `${errorTypeWithUnderlyingType}: Oh no!`,
+ };
+
+ const result = extractErrorDetails(error);
+
+ const [errorType, message] = errorTypeWithUnderlyingType.split(': ');
+
+ expect(result).toStrictEqual({
+ isPlainString: false,
+ message: [message, error.message],
+ type: errorType,
+ });
+ });
+});
diff --git a/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts b/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts
new file mode 100644
index 000000000..7b0edbb1b
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts
@@ -0,0 +1,70 @@
+import { isFunction } from 'effect/Function';
+import { hasProperty } from 'effect/Predicate';
+
+interface ErrorDetails {
+ isPlainString: boolean;
+ type?: unknown;
+ message: unknown;
+}
+
+export const extractErrorDetails = (error: unknown): ErrorDetails => {
+ if (typeof error === 'string') {
+ return {
+ isPlainString: true,
+ message: error,
+ };
+ }
+
+ const isTaggedErrorWithCause =
+ error instanceof Error && hasProperty(error, 'cause') && hasProperty(error, '_tag');
+ if (isTaggedErrorWithCause) {
+ return {
+ isPlainString: false,
+ type: error._tag,
+ message: error.cause,
+ };
+ }
+
+ const isTaggedErrorWithErrorCtor = error instanceof Error && hasProperty(error, 'error');
+ if (isTaggedErrorWithErrorCtor) {
+ return {
+ isPlainString: false,
+ type: error.name,
+ message: error.error,
+ };
+ }
+
+ const isPlainObjectsWithTagAttribute =
+ hasProperty(error, '_tag') && hasProperty(error, 'message');
+ if (isPlainObjectsWithTagAttribute) {
+ return {
+ isPlainString: false,
+ type: error._tag,
+ message: error.message,
+ };
+ }
+
+ const isPlainObjectsWithToStringImpl =
+ hasProperty(error, 'toString') &&
+ isFunction(error.toString) &&
+ error.toString !== Object.prototype.toString &&
+ error.toString !== Array.prototype.toString;
+ if (isPlainObjectsWithToStringImpl) {
+ const message = (error as { toString: () => string }).toString();
+ const maybeWithUnderlyingType = message.split(': ');
+
+ if (maybeWithUnderlyingType.length > 1) {
+ const [type, ...message] = maybeWithUnderlyingType;
+
+ return {
+ isPlainString: false,
+ type,
+ message,
+ };
+ }
+
+ return { message, isPlainString: false };
+ }
+
+ return { message: `Error: ${JSON.stringify(error)}`, isPlainString: false };
+};
diff --git a/ts/packages/cli/src/effect-errors/logic/errors/index.ts b/ts/packages/cli/src/effect-errors/logic/errors/index.ts
new file mode 100644
index 000000000..9d20f2e52
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/errors/index.ts
@@ -0,0 +1,2 @@
+export * from './capture-errors-from-cause';
+export * from './parse-error';
diff --git a/ts/packages/cli/src/effect-errors/logic/errors/parse-error.ts b/ts/packages/cli/src/effect-errors/logic/errors/parse-error.ts
new file mode 100644
index 000000000..ee5f75c52
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/errors/parse-error.ts
@@ -0,0 +1,28 @@
+import { hasProperty } from 'effect/Predicate';
+import type { Span } from 'effect/Tracer';
+
+import { PrettyError } from 'effect-errors/types';
+
+import { extractErrorDetails } from './extract-error-details';
+
+const spanSymbol = Symbol.for('effect/SpanAnnotation');
+
+export const parseError = (error: unknown): PrettyError => {
+ const maybeSpan = hasProperty(error, spanSymbol) ? (error[spanSymbol] as Span) : undefined;
+ const { message, type, isPlainString } = extractErrorDetails(error);
+
+ if (error instanceof Error) {
+ return new PrettyError(
+ message,
+ error.stack
+ ?.split('\n')
+ .filter(el => /at (.*)/.exec(el))
+ .join('\r\n'),
+ maybeSpan,
+ false,
+ type
+ );
+ }
+
+ return new PrettyError(message, undefined, maybeSpan, isPlainString, type);
+};
diff --git a/ts/packages/cli/src/effect-errors/logic/path/index.ts b/ts/packages/cli/src/effect-errors/logic/path/index.ts
new file mode 100644
index 000000000..a890edb6f
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/path/index.ts
@@ -0,0 +1 @@
+export * from './strip-cwd-path';
diff --git a/ts/packages/cli/src/effect-errors/logic/path/strip-cwd-path.ts b/ts/packages/cli/src/effect-errors/logic/path/strip-cwd-path.ts
new file mode 100644
index 000000000..c5c59dda3
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/path/strip-cwd-path.ts
@@ -0,0 +1,4 @@
+const cwdRegex = global.process !== undefined ? new RegExp(global.process.cwd(), 'g') : null;
+
+export const stripCwdPath = (path: string): string =>
+ cwdRegex === null ? path : path.replace(cwdRegex, '.');
diff --git a/ts/packages/cli/src/effect-errors/logic/spans/index.ts b/ts/packages/cli/src/effect-errors/logic/spans/index.ts
new file mode 100644
index 000000000..0c8f60d64
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/spans/index.ts
@@ -0,0 +1,2 @@
+export * from './maybe-add-error-to-spans-stack';
+export * from './split-spans-attributes-by-type';
diff --git a/ts/packages/cli/src/effect-errors/logic/spans/maybe-add-error-to-spans-stack.ts b/ts/packages/cli/src/effect-errors/logic/spans/maybe-add-error-to-spans-stack.ts
new file mode 100644
index 000000000..86fcc964d
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/spans/maybe-add-error-to-spans-stack.ts
@@ -0,0 +1,21 @@
+export const removeNodeModulesEntriesFromStack = (stack: string) => {
+ const lines = stack.split('\r\n');
+
+ return lines.filter(line => line.includes(process.cwd()) && !line.includes('/node_modules/'));
+};
+
+export const maybeAddErrorToSpansStack = (
+ stack: string | undefined,
+ spanAttributesStack: string[] | undefined
+) => {
+ const effectStack: string[] = [];
+
+ if (stack && spanAttributesStack !== undefined) {
+ effectStack.push(...removeNodeModulesEntriesFromStack(stack));
+ }
+ if (spanAttributesStack !== undefined) {
+ effectStack.push(...spanAttributesStack);
+ }
+
+ return effectStack;
+};
diff --git a/ts/packages/cli/src/effect-errors/logic/spans/split-spans-attributes-by-type.ts b/ts/packages/cli/src/effect-errors/logic/spans/split-spans-attributes-by-type.ts
new file mode 100644
index 000000000..5d8b05d1c
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/spans/split-spans-attributes-by-type.ts
@@ -0,0 +1,25 @@
+interface FilteredEffectAttributes {
+ stacktrace: string[];
+ attributes: ReadonlyMap<string, unknown>;
+}
+
+export const splitSpansAttributesByTypes = (attributes: ReadonlyMap<string, unknown>) =>
+ Array.from(attributes.entries()).reduce<FilteredEffectAttributes>(
+ (prev, [key, value]) => {
+ if (key === 'code.stacktrace') {
+ return {
+ attributes: prev.attributes,
+ stacktrace: [...prev.stacktrace, value] as string[],
+ };
+ }
+
+ return {
+ attributes: new Map([...prev.attributes, [key, value]]),
+ stacktrace: prev.stacktrace,
+ };
+ },
+ {
+ stacktrace: [],
+ attributes: new Map(),
+ }
+ );
diff --git a/ts/packages/cli/src/effect-errors/logic/stack/filter-stack.ts b/ts/packages/cli/src/effect-errors/logic/stack/filter-stack.ts
new file mode 100644
index 000000000..514f92f57
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/stack/filter-stack.ts
@@ -0,0 +1,28 @@
+import { Match } from 'effect';
+
+import { stripCwdPath } from 'effect-errors/logic/path';
+
+import { stackAtRegex } from './stack-regex';
+
+const match = Match.type<'node' | 'effect'>().pipe(
+ Match.when('effect', _ => 'at '),
+ Match.when('node', _ => '│ at '),
+ Match.exhaustive
+);
+
+export const filterStack = (stack: string, type: 'node' | 'effect', stripCwd: boolean) => {
+ const lines = stack.split('\r\n');
+ const out: string[] = [];
+
+ for (const line of lines) {
+ out.push(line.replace(/at .*effect_cutpoint.*\((.*)\)/, 'at $1'));
+
+ if (line.includes('effect_cutpoint')) {
+ return out.join('\r\n');
+ }
+ }
+
+ const final = out.join('\r\n').replace(stackAtRegex, match(type));
+
+ return stripCwd ? stripCwdPath(final) : final;
+};
diff --git a/ts/packages/cli/src/effect-errors/logic/stack/index.ts b/ts/packages/cli/src/effect-errors/logic/stack/index.ts
new file mode 100644
index 000000000..47ab9a1b2
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/stack/index.ts
@@ -0,0 +1,2 @@
+export * from './filter-stack';
+export * from './stack-regex';
diff --git a/ts/packages/cli/src/effect-errors/logic/stack/stack-regex.ts b/ts/packages/cli/src/effect-errors/logic/stack/stack-regex.ts
new file mode 100644
index 000000000..5e8161599
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/logic/stack/stack-regex.ts
@@ -0,0 +1,2 @@
+export const stackAtRegex = / {4}at /g;
+export const sourceFileWithMapPointerRegex = /^(file:\/\/)?(.*.([jt])sx?)(\?.*)?:(\d*):(\d*)$/;
diff --git a/ts/packages/cli/src/effect-errors/pretty-print-from-captured-errors.ts b/ts/packages/cli/src/effect-errors/pretty-print-from-captured-errors.ts
new file mode 100644
index 000000000..0ed795f3c
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print-from-captured-errors.ts
@@ -0,0 +1,18 @@
+import { formatCapturedError, formatTitle, interruptedMessage } from 'effect-errors/pretty-print';
+import { type PrettyPrintOptions, prettyPrintOptionsDefault } from 'effect-errors/types';
+
+import type { CapturedErrors } from './capture-errors';
+
+export const prettyPrintFromCapturedErrors = (
+ { errors, interrupted }: CapturedErrors,
+ options: PrettyPrintOptions = prettyPrintOptionsDefault
+) => {
+ if (interrupted) {
+ return interruptedMessage;
+ }
+
+ const title = formatTitle(errors.length);
+ const formattedFailures = errors.map(formatCapturedError(errors.length, options));
+
+ return [...title, ...formattedFailures].join('\r\n');
+};
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/index.ts b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/index.ts
new file mode 100644
index 000000000..e2487bfce
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/index.ts
@@ -0,0 +1,4 @@
+export * from './maybe-advise-spans-usage';
+export * from './maybe-print-node-stacktrace';
+export * from './maybe-print-spans-timeline';
+export * from './print-effect-stacktrace';
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-advice-spans-usage.ts b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-advice-spans-usage.ts
new file mode 100644
index 000000000..9efc4677f
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-advice-spans-usage.ts
@@ -0,0 +1,11 @@
+import color from 'picocolors';
+
+import type { ErrorSpan } from 'effect-errors/types';
+
+export const maybeAdviseSpansUsage = (spans: ErrorSpan[] | undefined): string[] => {
+ if (spans === undefined || spans.length === 0) {
+ return ['', color.gray('ℹ️ Consider using spans to improve errors reporting.')];
+ }
+
+ return [];
+};
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-advise-spans-usage.ts b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-advise-spans-usage.ts
new file mode 100644
index 000000000..9efc4677f
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-advise-spans-usage.ts
@@ -0,0 +1,11 @@
+import color from 'picocolors';
+
+import type { ErrorSpan } from 'effect-errors/types';
+
+export const maybeAdviseSpansUsage = (spans: ErrorSpan[] | undefined): string[] => {
+ if (spans === undefined || spans.length === 0) {
+ return ['', color.gray('ℹ️ Consider using spans to improve errors reporting.')];
+ }
+
+ return [];
+};
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-print-node-stacktrace.ts b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-print-node-stacktrace.ts
new file mode 100644
index 000000000..62358791f
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-print-node-stacktrace.ts
@@ -0,0 +1,37 @@
+import color from 'picocolors';
+
+import { stripCwdPath } from 'effect-errors/logic/path';
+import type { PrettyPrintOptions } from 'effect-errors/types';
+
+export const maybePrintNodeStacktrace = (
+ stack: string[] | undefined,
+ isPlainString: boolean,
+ { stripCwd, hideStackTrace }: PrettyPrintOptions
+): string[] => {
+ if (hideStackTrace) {
+ return [];
+ }
+
+ const stackHasNodes = stack !== undefined && stack.length > 0;
+ if (stackHasNodes) {
+ const nodes = stack.map(el => `│ ${stripCwd ? stripCwdPath(el) : el}`).join('\r\n');
+
+ return [
+ '',
+ `${color.bold(color.red('◯'))} ${color.redBright(color.underline('Node Stacktrace 🚨'))}`,
+ color.red(nodes),
+ color.red('┴'),
+ ];
+ }
+
+ if (!isPlainString) {
+ return [
+ '',
+ color.gray(
+ 'ℹ️ Consider using a yieldable error such as Data.TaggedError and Schema.TaggedError to get a stacktrace.'
+ ),
+ ];
+ }
+
+ return [];
+};
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-print-spans-timeline.ts b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-print-spans-timeline.ts
new file mode 100644
index 000000000..9ed93945c
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-print-spans-timeline.ts
@@ -0,0 +1,40 @@
+import color from 'picocolors';
+
+import { stripCwdPath } from 'effect-errors/logic/path';
+import {
+ formatSpanAttributes,
+ formatSpanDuration,
+ missingSpansWarning,
+ spanStackTrailingChar,
+} from 'effect-errors/pretty-print/common';
+import type { ErrorSpan, PrettyPrintOptions } from 'effect-errors/types';
+
+export const maybePrintSpansTimeline = (
+ spans: ErrorSpan[] | undefined,
+ isPlainString: boolean,
+ { stripCwd }: PrettyPrintOptions
+): string[] => {
+ if (spans === undefined) {
+ return isPlainString === false ? ['', missingSpansWarning, ''] : [];
+ }
+
+ return spans.reduce<string[]>((output, { name, durationInMilliseconds, attributes }, index) => {
+ const isFirstEntry = index === 0;
+ const isLastEntry = index === spans.length - 1;
+
+ const maybeCircle = isFirstEntry ? `\r\n${color.gray('◯')}\r\n` : '';
+ const trailing = spanStackTrailingChar(isLastEntry);
+ const filePath = ` ${stripCwd !== undefined ? color.underline(color.bold(stripCwdPath(name))) : color.underline(name)}`;
+ const duration =
+ durationInMilliseconds !== undefined
+ ? color.gray(formatSpanDuration(durationInMilliseconds, isLastEntry))
+ : '';
+ const formattedAttributes = formatSpanAttributes(attributes, isLastEntry);
+
+ const timelineEntry = color.white(
+ `${maybeCircle}${trailing}${color.gray('─')}${filePath}${duration}${formattedAttributes}`
+ );
+
+ return [...output, timelineEntry];
+ }, []);
+};
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/print-effect-stacktrace.ts b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/print-effect-stacktrace.ts
new file mode 100644
index 000000000..aea2d0a93
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/captured-errors/print-effect-stacktrace.ts
@@ -0,0 +1,30 @@
+import color from 'picocolors';
+
+import { stripCwdPath } from 'effect-errors/logic/path';
+import type { ErrorRelatedSources } from 'effect-errors/sourcemaps';
+import type { ErrorSpan, PrettyPrintOptions } from 'effect-errors/types';
+
+export const printEffectStacktrace = (
+ sources: Omit<ErrorRelatedSources, '_tag'>[] | undefined,
+ spans: ErrorSpan[] | undefined,
+ { stripCwd }: PrettyPrintOptions
+) => {
+ const isEmpty =
+ spans === undefined || spans.length === 0 || sources === undefined || sources.length === 0;
+ if (isEmpty) {
+ return [];
+ }
+
+ const paths = sources.map(({ name, runPath, sourcesPath }) => {
+ const path = sourcesPath ?? runPath;
+ return { path: stripCwd ? stripCwdPath(path) : path, name };
+ });
+
+ return [
+ `${color.bold(color.red('◯'))} ${color.red('Sources')} 🕵️`,
+ ...paths.map(({ path, name }) =>
+ color.red(`│ at ${name.length === 0 ? 'module code' : color.underline(name)} (${path})`)
+ ),
+ color.red('┴'),
+ ];
+};
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/common/constants/interrupted-message.ts b/ts/packages/cli/src/effect-errors/pretty-print/common/constants/interrupted-message.ts
new file mode 100644
index 000000000..1fb152d62
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/common/constants/interrupted-message.ts
@@ -0,0 +1 @@
+export const interruptedMessage = '✅ All fibers interrupted without errors.';
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/common/constants/missing-spans-warning.ts b/ts/packages/cli/src/effect-errors/pretty-print/common/constants/missing-spans-warning.ts
new file mode 100644
index 000000000..bc3b73629
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/common/constants/missing-spans-warning.ts
@@ -0,0 +1,3 @@
+import color from 'picocolors';
+
+export const missingSpansWarning = `\r\n${color.gray('ℹ️ Consider using spans to improve errors reporting.')}`;
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/common/format-error-title.ts b/ts/packages/cli/src/effect-errors/pretty-print/common/format-error-title.ts
new file mode 100644
index 000000000..4cfa2137b
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/common/format-error-title.ts
@@ -0,0 +1,17 @@
+import color from 'picocolors';
+
+export const formatErrorTitle = (
+ errorType: unknown,
+ message: unknown,
+ failuresLength: number,
+ failureIndex: number
+): string[] => {
+ const failuresCount =
+ failuresLength > 1 ? color.bgRed(color.white(` #${failureIndex + 1} -`)) : '';
+ const type = color.bgRed(
+ color.white(` ${(errorType as string | undefined) ?? 'Unknown error'} `)
+ );
+ const formattedMessage = color.bold(color.white(` • ${message as string}`));
+
+ return [`💥 ${failuresCount}${type}${formattedMessage}`];
+};
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/common/format-span-duration.ts b/ts/packages/cli/src/effect-errors/pretty-print/common/format-span-duration.ts
new file mode 100644
index 000000000..044ad588b
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/common/format-span-duration.ts
@@ -0,0 +1,4 @@
+import color from 'picocolors';
+
+export const formatSpanDuration = (durationInMs: number | bigint, isLastEntry: boolean) =>
+ `\r\n${isLastEntry ? ' ' : color.gray('│')} ~ ${durationInMs}ms`;
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/common/format-spans-attribute.ts b/ts/packages/cli/src/effect-errors/pretty-print/common/format-spans-attribute.ts
new file mode 100644
index 000000000..c95375575
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/common/format-spans-attribute.ts
@@ -0,0 +1,17 @@
+import color from 'picocolors';
+
+const maybePrintPipe = (isLastEntry: boolean) => (isLastEntry ? ' ' : color.gray('│'));
+
+export const formatSpanAttributes = (attributes: Record<string, unknown>, isLastEntry: boolean) => {
+ const entries = Object.entries(attributes);
+ if (entries.length === 0) {
+ return [];
+ }
+
+ const lines = Array.from(entries).map(
+ ([key, value]) =>
+ `${maybePrintPipe(isLastEntry)} ${color.blue(key)}${color.gray(':')} ${value}`
+ );
+
+ return `\r\n${lines.join('\r\n')}`;
+};
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/common/format-title.ts b/ts/packages/cli/src/effect-errors/pretty-print/common/format-title.ts
new file mode 100644
index 000000000..235ed4732
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/common/format-title.ts
@@ -0,0 +1,14 @@
+import color from 'picocolors';
+
+export const formatTitle = (errorsCount: number): string[] => {
+ if (errorsCount === 1) {
+ return [''];
+ }
+
+ const libName = color.bold(`${color.underline(color.redBright('effect-errors'))}`);
+ const title = color.bold(
+ color.cyanBright(`${errorsCount} error${errorsCount > 1 ? 's' : ''} occurred`)
+ );
+
+ return ['', `❌ ${libName} ❌ ${title}`, '', ''];
+};
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/common/index.ts b/ts/packages/cli/src/effect-errors/pretty-print/common/index.ts
new file mode 100644
index 000000000..6fcd0dfee
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/common/index.ts
@@ -0,0 +1,7 @@
+export * from './constants/missing-spans-warning';
+export * from './format-error-title';
+export * from './format-span-duration';
+export * from './format-spans-attribute';
+export * from './format-title';
+export * from './maybe-warn-about-plain-strings';
+export * from './spans-stack-trailing-char';
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/common/maybe-warn-about-plain-strings.ts b/ts/packages/cli/src/effect-errors/pretty-print/common/maybe-warn-about-plain-strings.ts
new file mode 100644
index 000000000..5a9f6ae69
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/common/maybe-warn-about-plain-strings.ts
@@ -0,0 +1,14 @@
+import color from 'picocolors';
+
+export const maybeWarnAboutPlainStrings = (isPlainString: boolean): string[] => {
+ if (!isPlainString) {
+ return [];
+ }
+
+ return [
+ '',
+ color.gray(
+ 'ℹ️ You used a plain string to represent a failure in the error channel (E). You should consider using tagged objects (with a _tag field), or yieldable errors such as Data.TaggedError and Schema.TaggedError for better handling experience.'
+ ),
+ ];
+};
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/common/spans-stack-trailing-char.ts b/ts/packages/cli/src/effect-errors/pretty-print/common/spans-stack-trailing-char.ts
new file mode 100644
index 000000000..1ff4aec18
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/common/spans-stack-trailing-char.ts
@@ -0,0 +1,4 @@
+import color from 'picocolors';
+
+export const spanStackTrailingChar = (isLastEntry: boolean) =>
+ isLastEntry ? color.gray('╰') : color.gray('├');
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/format-captured-error.ts b/ts/packages/cli/src/effect-errors/pretty-print/format-captured-error.ts
new file mode 100644
index 000000000..b57c2ac65
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/format-captured-error.ts
@@ -0,0 +1,33 @@
+import { formatErrorTitle, maybeWarnAboutPlainStrings } from 'effect-errors/pretty-print/common';
+import type { PrettyPrintOptions } from 'effect-errors/types';
+
+import type { ErrorData } from '../capture-errors';
+import {
+ maybeAdviseSpansUsage,
+ maybePrintNodeStacktrace,
+ maybePrintSpansTimeline,
+ printEffectStacktrace,
+} from './captured-errors';
+
+export const formatCapturedError =
+ (failuresCount: number, options: PrettyPrintOptions) =>
+ ({ errorType, message, stack, spans, sources, isPlainString }: ErrorData, index: number) => {
+ const title = formatErrorTitle(errorType, message, failuresCount, index);
+ const plainStringWarning = maybeWarnAboutPlainStrings(isPlainString);
+ const spansTimeline = maybePrintSpansTimeline(spans, isPlainString, options);
+ const spansUsageAdvice = maybeAdviseSpansUsage(spans);
+
+ const effectStacktrace = printEffectStacktrace(sources, spans, options);
+ const nodeStacktrace = maybePrintNodeStacktrace(stack, isPlainString, options);
+
+ return [
+ ...title,
+ ...plainStringWarning,
+ ...spansTimeline,
+ ...spansUsageAdvice,
+ '',
+ ...effectStacktrace,
+ ...nodeStacktrace,
+ '',
+ ].join('\r\n');
+ };
diff --git a/ts/packages/cli/src/effect-errors/pretty-print/index.ts b/ts/packages/cli/src/effect-errors/pretty-print/index.ts
new file mode 100644
index 000000000..893e43f64
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/pretty-print/index.ts
@@ -0,0 +1,3 @@
+export * from './common/constants/interrupted-message';
+export * from './common/format-title';
+export * from './format-captured-error';
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-error-location-from-file-path.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-error-location-from-file-path.ts
new file mode 100644
index 000000000..704b3b779
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-error-location-from-file-path.ts
@@ -0,0 +1,20 @@
+import { sourceFileWithMapPointerRegex } from 'effect-errors/logic/stack';
+
+export interface ErrorLocation {
+ filePath: string;
+ line: number;
+ column: number;
+}
+
+export const getErrorLocationFrom = (sourceFile: string): ErrorLocation | undefined => {
+ const regex = sourceFileWithMapPointerRegex.exec(sourceFile);
+ if (regex === null || regex.length !== 7) {
+ return;
+ }
+
+ const filePath = regex[2];
+ const line = +regex[5];
+ const column = +regex[6];
+
+ return { filePath, line, column };
+};
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
new file mode 100644
index 000000000..67d28bb33
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
@@ -0,0 +1,45 @@
+import type { PlatformError } from '@effect/platform/Error';
+import type { FileSystem } from '@effect/platform/FileSystem';
+import { Effect } from 'effect';
+
+import type { JsonParsingError } from 'effect-errors/dependencies/fs';
+
+import { getErrorLocationFrom } from './get-error-location-from-file-path';
+import { getSourceCode } from './get-source-code';
+import {
+ type ErrorRelatedSources,
+ getSourcesFromMapFile,
+ type RawErrorLocation,
+} from './get-sources-from-map-file';
+
+export const getErrorRelatedSources = (
+ name: string,
+ sourceFile: string
+): Effect.Effect<
+ ErrorRelatedSources | RawErrorLocation | undefined,
+ PlatformError | JsonParsingError,
+ FileSystem
+> =>
+ Effect.gen(function* () {
+ const location = getErrorLocationFrom(sourceFile);
+ if (location === undefined) {
+ return;
+ }
+
+ const { filePath, line, column } = location;
+
+ const isTypescriptFile = filePath.endsWith('.ts') || filePath.endsWith('.tsx');
+ if (isTypescriptFile) {
+ const source = yield* getSourceCode(location);
+
+ return {
+ _tag: 'sources' as const,
+ name,
+ runPath: `${filePath}:${line}:${column}`,
+ sourcesPath: undefined,
+ source,
+ };
+ }
+
+ return yield* getSourcesFromMapFile(name, location);
+ });
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-source-code.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-source-code.ts
new file mode 100644
index 000000000..65147aa10
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-source-code.ts
@@ -0,0 +1,39 @@
+import type { PlatformError } from '@effect/platform/Error';
+import { FileSystem } from '@effect/platform/FileSystem';
+import { Effect } from 'effect';
+
+import type { ErrorLocation } from './get-error-location-from-file-path';
+
+export interface SourceCode {
+ line: number;
+ code: string;
+ column: number | undefined;
+}
+
+const numberOflinesToExtract = 7;
+
+export const getSourceCode = (
+ { filePath, line, column }: ErrorLocation,
+ isFromJs = false
+): Effect.Effect<SourceCode[], PlatformError, FileSystem> =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem;
+ const sourceCode = yield* fs.readFileString(filePath, 'utf8');
+
+ const start = line >= 4 ? line - 4 : 0;
+
+ return sourceCode
+ .split('\n')
+ .splice(start, numberOflinesToExtract)
+ .map((currentLine, index) => {
+ const currentLineNumber = index + start + 1;
+
+ const actualColumn = isFromJs ? column + 1 : column;
+
+ return {
+ line: currentLineNumber,
+ code: currentLine,
+ column: currentLineNumber === line ? actualColumn : undefined,
+ };
+ });
+ });
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
new file mode 100644
index 000000000..b4d987f40
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
@@ -0,0 +1,90 @@
+import path from 'node:path';
+
+import type { PlatformError } from '@effect/platform/Error';
+import { FileSystem } from '@effect/platform/FileSystem';
+import { Effect, pipe } from 'effect';
+import { type RawSourceMap, SourceMapConsumer } from 'source-map-js';
+
+import { type JsonParsingError, readJsonEffect } from 'effect-errors/dependencies/fs';
+
+import type { ErrorLocation } from './get-error-location-from-file-path';
+import { getSourceCode, type SourceCode } from './get-source-code';
+
+export interface ErrorRelatedSources {
+ _tag: 'sources';
+ name: string;
+ source: SourceCode[];
+ runPath: string;
+ sourcesPath: string | undefined;
+}
+
+export interface RawErrorLocation extends ErrorLocation {
+ _tag: 'location';
+ name: string;
+}
+
+export const getSourcesFromMapFile = (
+ name: string,
+ location: ErrorLocation
+): Effect.Effect<
+ ErrorRelatedSources | RawErrorLocation | undefined,
+ PlatformError | JsonParsingError,
+ FileSystem
+> =>
+ pipe(
+ Effect.gen(function* () {
+ const fs = yield* FileSystem;
+ const fileExists = yield* fs.exists(`${location.filePath}.map`);
+ if (!fileExists) {
+ return {
+ _tag: 'location' as const,
+ name,
+ ...location,
+ filePath: location.filePath.replace(process.cwd(), ''),
+ };
+ }
+
+ const data = yield* readJsonEffect<RawSourceMap>(`${location.filePath}.map`);
+ const hasNoData = data?.version === undefined || data?.sources === undefined;
+ if (hasNoData) {
+ return;
+ }
+
+ const consumer = new SourceMapConsumer(data);
+ const sources = consumer.originalPositionFor({
+ column: location.column,
+ line: location.line,
+ });
+ if (sources.source === null || sources.line === null || sources.column === null) {
+ return;
+ }
+
+ const absolutePath = path.resolve(
+ location.filePath.substring(0, location.filePath.lastIndexOf('/')),
+ sources.source
+ );
+ const isNodeModules = absolutePath.startsWith(`${process.cwd()}/node_modules`);
+ if (isNodeModules) {
+ return;
+ }
+ const source = yield* getSourceCode(
+ {
+ filePath: absolutePath,
+ line: sources.line,
+ column: sources.column,
+ },
+ true
+ );
+
+ return {
+ _tag: 'sources' as const,
+ name,
+ runPath: `${location.filePath}:${location.line}:${location.column}`,
+ sourcesPath: `${absolutePath}:${sources.line}:${sources.column + 1}`,
+ source,
+ };
+ }),
+ Effect.withSpan('get-sources-from-map-file', {
+ attributes: { location: JSON.stringify(location) },
+ })
+ );
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts
new file mode 100644
index 000000000..037291e89
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts
@@ -0,0 +1,62 @@
+import { Effect, Option, pipe } from 'effect';
+import type { AnySpan, Span } from 'effect/Tracer';
+
+import { splitSpansAttributesByTypes } from 'effect-errors/logic/spans';
+
+import type { ErrorRelatedSources, RawErrorLocation } from './get-sources-from-map-file';
+import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
+
+export const getSourcesFromSpan = ({
+ span,
+ sources,
+ location,
+}: {
+ span: Span | undefined;
+ sources: ErrorRelatedSources[];
+ location: RawErrorLocation[];
+}) =>
+ pipe(
+ Effect.gen(function* () {
+ if (span === undefined) {
+ return {
+ spans: [],
+ sources,
+ location,
+ };
+ }
+
+ const spans = [];
+
+ let current: Span | AnySpan | undefined = span;
+ while (current !== undefined && current._tag === 'Span') {
+ const { name, attributes: allAttributes, status } = current;
+
+ const { attributes, stacktrace } = splitSpansAttributesByTypes(allAttributes);
+
+ const sourcesOrLocation = yield* maybeMapSourcemaps(name, stacktrace);
+ const duration =
+ status._tag === 'Ended'
+ ? +`${(status.endTime - status.startTime) / BigInt(1000000)}`
+ : undefined;
+
+ sources.push(...sourcesOrLocation.filter(el => el._tag === 'sources'));
+ location.push(...sourcesOrLocation.filter(el => el._tag === 'location'));
+ spans.push({
+ name,
+ attributes: Object.fromEntries(attributes),
+ durationInMilliseconds: duration,
+ startTime: status.startTime,
+ endTime: status._tag === 'Ended' ? status.endTime : undefined,
+ });
+
+ current = Option.getOrUndefined(current.parent);
+ }
+
+ return {
+ spans,
+ location,
+ sources,
+ };
+ }),
+ Effect.withSpan('get-sources-from-span')
+ );
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts
new file mode 100644
index 000000000..6c1596e25
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts
@@ -0,0 +1,26 @@
+import { Effect, pipe } from 'effect';
+
+import { removeNodeModulesEntriesFromStack } from 'effect-errors/logic/spans';
+
+import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
+
+export const getSourcesFromStack = (maybeStack: string | undefined) =>
+ pipe(
+ Effect.gen(function* () {
+ if (maybeStack === undefined) {
+ return {
+ sources: [],
+ location: [],
+ };
+ }
+
+ const relevantStackEntries = removeNodeModulesEntriesFromStack(maybeStack);
+ const sourcesOrLocation = yield* maybeMapSourcemaps('', relevantStackEntries);
+
+ return {
+ sources: sourcesOrLocation.filter(el => el._tag === 'sources'),
+ location: sourcesOrLocation.filter(el => el._tag === 'location'),
+ };
+ }),
+ Effect.withSpan('get-sources-from-stack')
+ );
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/index.ts b/ts/packages/cli/src/effect-errors/sourcemaps/index.ts
new file mode 100644
index 000000000..c6c6b9333
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/index.ts
@@ -0,0 +1,4 @@
+export * from './get-error-location-from-file-path';
+export * from './get-source-code';
+export * from './get-sources-from-map-file';
+export * from './transform-raw-error';
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts b/ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
new file mode 100644
index 000000000..525abe1cd
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
@@ -0,0 +1,49 @@
+import type { PlatformError } from '@effect/platform/Error';
+import type { FileSystem } from '@effect/platform/FileSystem';
+import { Effect, pipe } from 'effect';
+
+import type { JsonParsingError } from 'effect-errors/dependencies/fs';
+import { stackAtRegex } from 'effect-errors/logic/stack';
+
+import { getErrorRelatedSources } from './get-error-related-sources';
+import type { ErrorRelatedSources, RawErrorLocation } from './get-sources-from-map-file';
+
+export type StackEntry = {
+ _tag: 'stack-entry';
+ runPath: string;
+};
+
+export type MaybeMappedSources = ErrorRelatedSources | RawErrorLocation | StackEntry;
+
+export const maybeMapSourcemaps = (
+ name: string,
+ stacktrace: string[]
+): Effect.Effect<MaybeMappedSources[], PlatformError | JsonParsingError, FileSystem> =>
+ pipe(
+ Effect.forEach(stacktrace, stackLine =>
+ Effect.gen(function* () {
+ const chunks = stackLine.trimStart().split(' ');
+ const mapFileReportedPath =
+ chunks.length === 2 ? chunks[1] : chunks[chunks.length - 1].slice(1, -1);
+
+ const details = yield* getErrorRelatedSources(name, mapFileReportedPath);
+ if (details === undefined) {
+ return {
+ _tag: 'stack-entry' as const,
+ runPath: stackLine.replaceAll(stackAtRegex, 'at '),
+ };
+ }
+ if (details._tag === 'location') {
+ return details;
+ }
+
+ const regex = new RegExp(`${process.cwd()}/node_modules/`);
+ if (details.sourcesPath?.match(regex)) {
+ return undefined;
+ }
+
+ return details;
+ })
+ ),
+ Effect.map(array => array.filter(maybeSources => maybeSources !== undefined))
+ );
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/transform-raw-error.ts b/ts/packages/cli/src/effect-errors/sourcemaps/transform-raw-error.ts
new file mode 100644
index 000000000..a241072ac
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/transform-raw-error.ts
@@ -0,0 +1,38 @@
+import { Effect, pipe } from 'effect';
+
+import { stripCwdPath } from 'effect-errors/logic/path';
+import { stackAtRegex } from 'effect-errors/logic/stack';
+
+import type { CaptureErrorsOptions } from '../capture-errors';
+import type { PrettyError } from '../types/pretty-error.type';
+import { getSourcesFromSpan } from './get-sources-from-span';
+import { getSourcesFromStack } from './get-sources-from-stack';
+
+export const transformRawError =
+ ({ stripCwd }: CaptureErrorsOptions) =>
+ ({ message, stack: maybeStack, span, errorType, isPlainString }: PrettyError) =>
+ pipe(
+ Effect.gen(function* () {
+ const data = yield* getSourcesFromStack(maybeStack);
+ const { spans, sources, location } = yield* getSourcesFromSpan({
+ span,
+ ...data,
+ });
+
+ let stack: string | undefined;
+ if (maybeStack !== undefined) {
+ stack = stripCwd === true ? stripCwdPath(maybeStack) : maybeStack;
+ }
+
+ return {
+ errorType,
+ message,
+ stack: stack?.replaceAll(stackAtRegex, 'at ').split('\r\n'),
+ sources: sources.length > 0 ? sources.map(({ _tag, ...data }) => data) : undefined,
+ location: location.length > 0 ? location.map(({ _tag, ...data }) => data) : undefined,
+ spans,
+ isPlainString,
+ };
+ }),
+ Effect.withSpan('transform-raw-error')
+ );
diff --git a/ts/packages/cli/src/effect-errors/types/error-span.type.ts b/ts/packages/cli/src/effect-errors/types/error-span.type.ts
new file mode 100644
index 000000000..08eaadc41
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/types/error-span.type.ts
@@ -0,0 +1,7 @@
+export interface ErrorSpan {
+ name: string;
+ attributes: Record<string, unknown>;
+ durationInMilliseconds: number | undefined;
+ startTime: bigint;
+ endTime: bigint | undefined;
+}
diff --git a/ts/packages/cli/src/effect-errors/types/index.ts b/ts/packages/cli/src/effect-errors/types/index.ts
new file mode 100644
index 000000000..8fe74246e
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/types/index.ts
@@ -0,0 +1,3 @@
+export * from './error-span.type';
+export * from './pretty-error.type';
+export * from './pretty-print-options.type';
diff --git a/ts/packages/cli/src/effect-errors/types/pretty-error.type.ts b/ts/packages/cli/src/effect-errors/types/pretty-error.type.ts
new file mode 100644
index 000000000..88c3dd349
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/types/pretty-error.type.ts
@@ -0,0 +1,11 @@
+import type { Span } from 'effect/Tracer';
+
+export class PrettyError {
+ constructor(
+ readonly message: unknown,
+ readonly stack: string | undefined,
+ readonly span: Span | undefined,
+ readonly isPlainString: boolean,
+ readonly errorType?: unknown
+ ) {}
+}
diff --git a/ts/packages/cli/src/effect-errors/types/pretty-print-options.type.ts b/ts/packages/cli/src/effect-errors/types/pretty-print-options.type.ts
new file mode 100644
index 000000000..20425e23c
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/types/pretty-print-options.type.ts
@@ -0,0 +1,11 @@
+export interface PrettyPrintOptions {
+ enabled?: boolean;
+ stripCwd?: boolean | undefined;
+ hideStackTrace?: boolean;
+}
+
+export const prettyPrintOptionsDefault: PrettyPrintOptions = {
+ enabled: true,
+ stripCwd: true,
+ hideStackTrace: true,
+};
diff --git a/ts/packages/cli/src/models/utils/extract-actual.ts b/ts/packages/cli/src/models/utils/extract-actual.ts
index d141a05d4..7ce57863f 100644
--- a/ts/packages/cli/src/models/utils/extract-actual.ts
+++ b/ts/packages/cli/src/models/utils/extract-actual.ts
@@ -1,13 +1,15 @@
import type { ParseIssue } from 'effect/ParseResult';
+import { inspect } from 'node:util';
export function extractActual({ actual }: ParseIssue, cap = 50) {
- // Cap the length of the actual value to 30 characters
- let str = undefined;
+ // Cap the length of the actual value to 50 characters
+ let str: string;
if (typeof actual === 'object') {
- str = JSON.stringify(actual);
+ str = inspect(actual, { depth: 2 });
+ } else {
+ str = String(actual);
}
- str = String(actual);
return str.slice(0, cap) + (str.length > cap ? '...' : '');
}
diff --git a/ts/packages/cli/src/services/utils/pretty-error.ts b/ts/packages/cli/src/services/utils/pretty-error.ts
index cdb89679d..1e0f7b65b 100644
--- a/ts/packages/cli/src/services/utils/pretty-error.ts
+++ b/ts/packages/cli/src/services/utils/pretty-error.ts
@@ -15,18 +15,18 @@ function* renderPrettyErrorGen(
yield '';
} else if (errorLines.length <= 2) {
for (const [key, value] of errorLines) {
- yield `${colors.gray(S_BAR)} ${colors.blueBright(key)}: ${value}`;
+ yield `${colors.inverse(S_BAR)} ${colors.blueBright(key)}: ${value}`;
}
} else if (errorLines.length > 2) {
for (let i = 0; i < errorLines.length; i++) {
const [key, value] = errorLines[i];
if (i === 0) {
- yield `${colors.gray(`${S_CORNER_TOP_LEFT}${S_BAR_H}`)} ${colors.blueBright(key)}: ${value}`;
+ yield `${colors.inverse(`${S_CORNER_TOP_LEFT}${S_BAR_H}`)} ${colors.blueBright(key)}: ${value}`;
} else if (i === errorLines.length - 1) {
- yield `${colors.gray(`${S_CORNER_BOTTOM_LEFT}${S_BAR_H}`)} ${colors.blueBright(key)}: ${value}`;
+ yield `${colors.inverse(`${S_CORNER_BOTTOM_LEFT}${S_BAR_H}`)} ${colors.blueBright(key)}: ${value}`;
} else {
- yield `${colors.gray(S_BAR)} ${colors.blueBright(key)}: ${value}`;
+ yield `${colors.inverse(S_BAR)} ${colors.blueBright(key)}: ${value}`;
}
}
}
diff --git a/ts/packages/cli/tsconfig.json b/ts/packages/cli/tsconfig.json
index 476c325d1..fe8a3fdf0 100644
--- a/ts/packages/cli/tsconfig.json
+++ b/ts/packages/cli/tsconfig.json
@@ -6,7 +6,8 @@
"paths": {
"src/*": ["./src/*"],
"test/*": ["./test/*"],
- "~/*": ["./*"]
+ "~/*": ["./*"],
+ "effect-errors/*": ["./src/effect-errors/*"]
},
"types": ["@types/bun", "vitest/importMeta"]
},
diff --git a/ts/packages/cli/tsconfig.src.json b/ts/packages/cli/tsconfig.src.json
index a12f8d883..9a5ec77ec 100644
--- a/ts/packages/cli/tsconfig.src.json
+++ b/ts/packages/cli/tsconfig.src.json
@@ -9,8 +9,10 @@
"compilerOptions": {
"outDir": "./dist",
"rootDir": ".",
+ "baseUrl": ".",
"paths": {
- "src/*": ["./src/*"]
+ "src/*": ["./src/*"],
+ "effect-errors/*": ["./src/effect-errors/*"]
},
"types": ["@types/bun"]
},
diff --git a/ts/packages/cli/tsconfig.test.json b/ts/packages/cli/tsconfig.test.json
index 06fce3937..ab25ebd34 100644
--- a/ts/packages/cli/tsconfig.test.json
+++ b/ts/packages/cli/tsconfig.test.json
@@ -8,8 +8,10 @@
],
"compilerOptions": {
"rootDir": ".",
+ "baseUrl": ".",
"paths": {
"src/*": ["./src/*"],
+ "effect-errors/*": ["./src/effect-errors/*"],
"test/*": ["./test/*"]
},
"types": ["@types/bun", "vitest/importMeta"]
diff --git a/ts/packages/cli/vitest.config.ts b/ts/packages/cli/vitest.config.ts
index 57ef7edc9..fd9edee4e 100644
--- a/ts/packages/cli/vitest.config.ts
+++ b/ts/packages/cli/vitest.config.ts
@@ -9,6 +9,7 @@ export default defineConfig({
'~': path.resolve(__dirname, './'),
src: path.resolve(__dirname, './src'),
test: path.resolve(__dirname, './test'),
+ 'effect-errors/*': path.resolve(__dirname, './src/effect-errors'),
},
},
test: {