@devries-cameron20 / composio-1 / commits / 24151cbe1
Fork 0

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

fix(cli): make source-map enrichment best-effort end to end (#3963)

This PR: - fixes #3925 - treats source maps as best-effort metadata end to end: a missing, malformed, invalid, consumer-rejected, or unreadable map — and a valid map pointing at an original source that was never shipped — all fall back to the raw stack location instead of aborting error capture - decodes untrusted source-map JSON with Effect Schema and wraps `source-map-js` exceptions in a typed `SourceMapResolutionError` - splits the fallible work into `enrichFromMapFile` and recovers from it with `orElseSucceed`, so `getSourcesFromMapFile`, `getErrorRelatedSources`, `maybeMapSourcemaps` and `captureErrors` all end up with a `never` error channel - models mapped diagnostic variants with `Data.TaggedEnum`, using its constructors and `$is` refinements instead of hand-written tagged records - removes the unchecked generic JSON cast, and drops a redundant `node_modules` filter that interpolated an unescaped working directory into a `RegExp` - adds regression coverage for invalid JSON, invalid shapes, invalid mappings, nullable optional keys, missing original sources, unreadable maps, valid enrichment, and end-to-end diagnostic preservation - records the user-visible fix in the CLI changelog without adding a Changeset ## Context `captureErrors` runs inside the top-level `Effect.catchAll` in `cli-main.ts`, so any failure while enriching a diagnostic was the CLI's error reporter crashing while reporting an error. #3925 reported one trigger (malformed `.map` JSON), but three more paths had the same effect and are fixed here: - a **valid map whose original source was never shipped** — the common shape for a compiled binary — failed on the `PlatformError` from reading that source - an **unreadable map**, e.g. a directory sitting at the `.map` path, failed with `EISDIR` - a **`.ts` stack frame** skips source maps entirely and reads the file directly, with the same unguarded read The Effect Schema decoder also has to be no stricter than `source-map-js` itself, or valid maps silently lose enrichment. `file` and `sourceRoot` are now `NullOr`: bundlers that emit no output filename write `"file": null` rather than omitting the key, and the consumer accepts it. Two incidental correctness fixes come along with the rewrite: original source paths are resolved with the platform path separator instead of a hardcoded `/`, and the `node_modules` filter no longer mistakes directories such as `node_modules_local` for real dependency paths. Both matter on Windows. ## Verification - `pnpm --filter @composio/cli exec vitest run test/src/effect-errors` — 32 tests passed - `pnpm --filter @composio/cli exec vitest run` — 973 passed, 1 skipped, 109 files - every new behavioural test was confirmed to fail against `next`, with the source tree reverted underneath them - `pnpm typecheck` — 14 tasks passed across 19 TypeScript packages - `pnpm --filter @composio/cli build` — passed - boundary validation (46 registered disables, none added), targeted ESLint, and Prettier — passed

Alberto Schiabel committed Jul 28, 2026 at 15:12 UTC 24151cbe14979671903efae6901991d1574ccd68
12 files changed +533 -149
ts/packages/cli/CHANGELOG.md
+2
@@ -15,6 +15,8 @@
15
16 ### Patch Changes
17
18 +- Preserve the original CLI diagnostic when an adjacent source map is malformed or unusable instead of letting optional source-map enrichment abort error capture. Source-map enrichment is now best-effort end to end: a malformed, invalid, or unreadable `.map`, and a valid map pointing at an original source that was never shipped, all degrade to the raw stack location. `captureErrors` can no longer fail.
19 +- Fix source-map resolution on Windows: original source paths are now resolved with the platform path separator instead of a hardcoded `/`, and the `node_modules` filter no longer mistakes directories such as `node_modules_local` for real dependency paths.
20 - Make `composio version --check` report `checkStatus: "unknown"` when GitHub cannot confirm the latest stable release, preserve the last successful cache on failed refreshes, and avoid racing the command with the startup update check.
21 - Make multi-account selection a stable CLI feature: `execute`, `listen`, and `link --alias` no longer honor the old experimental toggle; `proxy` now accepts `--account <alias|word_id|connected-account-id>`; and duplicate-alias link errors explain how to select the existing account.
22 - 8467efd: Fix `composio whoami` reporting the API key's home organization after `composio orgs switch`. Session info requests now forward the selected global organization.
ts/packages/cli/src/effect-errors/capture-errors.ts
+1 -3
@@ -1,10 +1,8 @@
1 -import type { PlatformError } from '@effect/platform/Error';
1 import type { FileSystem } from '@effect/platform/FileSystem';
2 import type { Path } from '@effect/platform/Path';
3 import { Effect } from 'effect';
4 import { type Cause, isInterruptedOnly } from 'effect/Cause';
5
7 -import type { JsonParsingError } from 'effect-errors/dependencies/fs';
6 import { captureErrorsFrom } from 'effect-errors/logic/errors';
7 import {
8 type ErrorLocation,
@@ -37,7 +35,7 @@ export const captureErrors = <E>(
35 options: CaptureErrorsOptions = {
36 stripCwd: true,
37 }
40 -): Effect.Effect<CapturedErrors, PlatformError | JsonParsingError, FileSystem | Path> =>
38 +): Effect.Effect<CapturedErrors, never, FileSystem | Path> =>
39 Effect.gen(function* () {
40 if (isInterruptedOnly(cause)) {
41 return {
ts/packages/cli/src/effect-errors/dependencies/fs/read-json/read-json.ts
+2 -2
@@ -3,7 +3,7 @@ import { Effect, pipe } from 'effect';
3
4 import { parseJsonRecord } from 'src/utils/parse-json';
5
6 -export const readJsonEffect = <TJson>(filePath: string) =>
6 +export const readJsonEffect = (filePath: string) =>
7 pipe(
8 Effect.gen(function* () {
9 const { readFileString } = yield* FileSystem;
@@ -15,7 +15,7 @@ export const readJsonEffect = <TJson>(filePath: string) =>
15
16 const json = yield* parseJsonRecord(data);
17
18 - return json as TJson;
18 + return json;
19 }),
20 Effect.withSpan('read-json', { attributes: { filePath } })
21 );
ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
+26 -23
@@ -1,26 +1,16 @@
1 -import type { PlatformError } from '@effect/platform/Error';
2 -import type { FileSystem } from '@effect/platform/FileSystem';
3 -import type { Path } from '@effect/platform/Path';
1 +import { FileSystem } from '@effect/platform/FileSystem';
2 +import { Path } from '@effect/platform/Path';
3 import { Effect } from 'effect';
4
6 -import type { JsonParsingError } from 'effect-errors/dependencies/fs';
7 -
5 import { getErrorLocationFrom } from './get-error-location-from-file-path';
6 import { getSourceCode } from './get-source-code';
10 -import {
11 - type ErrorRelatedSources,
12 - getSourcesFromMapFile,
13 - type RawErrorLocation,
14 -} from './get-sources-from-map-file';
7 +import { getSourcesFromMapFile } from './get-sources-from-map-file';
8 +import { type ErrorRelatedSources, MappedSources, type RawErrorLocation } from './mapped-sources';
9
10 export const getErrorRelatedSources = (
11 name: string,
12 sourceFile: string
19 -): Effect.Effect<
20 - ErrorRelatedSources | RawErrorLocation | undefined,
21 - PlatformError | JsonParsingError,
22 - FileSystem | Path
23 -> =>
13 +): Effect.Effect<ErrorRelatedSources | RawErrorLocation | undefined, never, FileSystem | Path> =>
14 Effect.gen(function* () {
15 const location = getErrorLocationFrom(sourceFile);
16 if (location === undefined) {
@@ -31,15 +21,28 @@ export const getErrorRelatedSources = (
21
22 const isTypescriptFile = filePath.endsWith('.ts') || filePath.endsWith('.tsx');
23 if (isTypescriptFile) {
34 - const source = yield* getSourceCode(location);
24 + const path = yield* Path;
25 + const workingDirectory = path.resolve('.');
26
36 - return {
37 - _tag: 'sources' as const,
38 - name,
39 - runPath: `${filePath}:${line}:${column}`,
40 - sourcesPath: undefined,
41 - source,
42 - };
27 + // Reading the source is best-effort enrichment, exactly as it is for the
28 + // source-map branch below: an unreadable file falls back to the location.
29 + return yield* getSourceCode(location).pipe(
30 + Effect.map(source =>
31 + MappedSources.sources({
32 + name,
33 + runPath: `${filePath}:${line}:${column}`,
34 + sourcesPath: undefined,
35 + source,
36 + })
37 + ),
38 + Effect.orElseSucceed(() =>
39 + MappedSources.location({
40 + name,
41 + ...location,
42 + filePath: filePath.replace(workingDirectory, ''),
43 + })
44 + )
45 + );
46 }
47
48 return yield* getSourcesFromMapFile(name, location);
ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
+135 -65
@@ -1,88 +1,158 @@
1 import type { PlatformError } from '@effect/platform/Error';
2 import { FileSystem } from '@effect/platform/FileSystem';
3 import { Path } from '@effect/platform/Path';
4 -import { Effect, pipe } from 'effect';
5 -import { type RawSourceMap, SourceMapConsumer } from 'source-map-js';
4 +import { Data, Effect, Option, Schema, pipe } from 'effect';
5 +import { SourceMapConsumer } from 'source-map-js';
6
7 -import { type JsonParsingError, readJsonEffect } from 'effect-errors/dependencies/fs';
7 +import { readJsonEffect } from 'effect-errors/dependencies/fs';
8
9 import type { ErrorLocation } from './get-error-location-from-file-path';
10 -import { getSourceCode, type SourceCode } from './get-source-code';
10 +import { getSourceCode } from './get-source-code';
11 +import { type ErrorRelatedSources, MappedSources, type RawErrorLocation } from './mapped-sources';
12
12 -export interface ErrorRelatedSources {
13 - _tag: 'sources';
14 - name: string;
15 - source: SourceCode[];
16 - runPath: string;
17 - sourcesPath: string | undefined;
18 -}
13 +/**
14 + * Structural subset of the Source Map v3 spec that `originalPositionFor` needs.
15 + *
16 + * `file` and `sourceRoot` are nullable, not merely absent: bundlers emitting a
17 + * map with no output file name write `"file": null` rather than omitting the
18 + * key, and `source-map-js` accepts both. Rejecting them here would silently
19 + * downgrade a perfectly usable map to an unenriched location.
20 + */
21 +const SourceMapSchema = Schema.Struct({
22 + version: Schema.Literal(3, '3'),
23 + sources: Schema.Array(Schema.String),
24 + names: Schema.optionalWith(Schema.Array(Schema.String), { default: () => [] }),
25 + mappings: Schema.String,
26 + file: Schema.optional(Schema.NullOr(Schema.String)),
27 + sourceRoot: Schema.optional(Schema.NullOr(Schema.String)),
28 +});
29 +const decodeSourceMap = Schema.decodeUnknownOption(SourceMapSchema);
30
20 -export interface RawErrorLocation extends ErrorLocation {
21 - _tag: 'location';
22 - name: string;
31 +class SourceMapResolutionError extends Data.TaggedError('SourceMapResolutionError')<{
32 + readonly filePath: string;
33 + readonly cause: unknown;
34 +}> {
35 + override get message(): string {
36 + return `Could not resolve source-map location for ${this.filePath}`;
37 + }
38 }
39
25 -export const getSourcesFromMapFile = (
40 +const rawErrorLocation = (
41 name: string,
27 - location: ErrorLocation
42 + location: ErrorLocation,
43 + workingDirectory: string
44 +): RawErrorLocation =>
45 + MappedSources.location({
46 + name,
47 + ...location,
48 + filePath: location.filePath.replace(workingDirectory, ''),
49 + });
50 +
51 +const resolveOriginalPosition = (sourceMap: typeof SourceMapSchema.Type, location: ErrorLocation) =>
52 + Effect.try({
53 + try: () =>
54 + new SourceMapConsumer({
55 + version: String(sourceMap.version),
56 + sources: [...sourceMap.sources],
57 + names: [...sourceMap.names],
58 + mappings: sourceMap.mappings,
59 + file: sourceMap.file ?? undefined,
60 + sourceRoot: sourceMap.sourceRoot ?? undefined,
61 + }).originalPositionFor({
62 + column: location.column,
63 + line: location.line,
64 + }),
65 + catch: cause => new SourceMapResolutionError({ filePath: location.filePath, cause }),
66 + }).pipe(
67 + Effect.map(Option.some),
68 + Effect.catchTag('SourceMapResolutionError', () => Effect.succeed(Option.none()))
69 + );
70 +
71 +/**
72 + * Enriches `location` with the original source it maps to.
73 + *
74 + * Fails with a `PlatformError` when the map file, or the original source it
75 + * points at, cannot be read; `getSourcesFromMapFile` turns that into the raw
76 + * location.
77 + */
78 +const enrichFromMapFile = (
79 + name: string,
80 + location: ErrorLocation,
81 + workingDirectory: string
82 ): Effect.Effect<
83 ErrorRelatedSources | RawErrorLocation | undefined,
30 - PlatformError | JsonParsingError,
84 + PlatformError,
85 FileSystem | Path
86 > =>
87 + Effect.gen(function* () {
88 + const fs = yield* FileSystem;
89 + const path = yield* Path;
90 + const fileExists = yield* fs.exists(`${location.filePath}.map`);
91 + if (!fileExists) {
92 + return rawErrorLocation(name, location, workingDirectory);
93 + }
94 +
95 + const sourceMap = yield* readJsonEffect(`${location.filePath}.map`).pipe(
96 + Effect.map(Option.fromNullable),
97 + Effect.map(Option.flatMap(decodeSourceMap)),
98 + Effect.catchTag('JsonParsingError', () => Effect.succeed(Option.none()))
99 + );
100 + if (Option.isNone(sourceMap)) {
101 + return rawErrorLocation(name, location, workingDirectory);
102 + }
103 +
104 + const maybeSources = yield* resolveOriginalPosition(sourceMap.value, location);
105 + if (Option.isNone(maybeSources)) {
106 + return rawErrorLocation(name, location, workingDirectory);
107 + }
108 +
109 + const sources = maybeSources.value;
110 + if (sources.source === null || sources.line === null || sources.column === null) {
111 + return;
112 + }
113 +
114 + const absolutePath = path.resolve(path.dirname(location.filePath), sources.source);
115 + const isNodeModules = absolutePath.startsWith(
116 + `${path.join(workingDirectory, 'node_modules')}${path.sep}`
117 + );
118 + if (isNodeModules) {
119 + return;
120 + }
121 + const source = yield* getSourceCode(
122 + {
123 + filePath: absolutePath,
124 + line: sources.line,
125 + column: sources.column,
126 + },
127 + true
128 + );
129 +
130 + return MappedSources.sources({
131 + name,
132 + runPath: `${location.filePath}:${location.line}:${location.column}`,
133 + sourcesPath: `${absolutePath}:${sources.line}:${sources.column + 1}`,
134 + source,
135 + });
136 + });
137 +
138 +/**
139 + * Source maps are best-effort metadata. A missing, malformed, invalid, or
140 + * unreadable map — or a map pointing at an original source that was never
141 + * shipped — degrades to the raw stack location, and never destroys the
142 + * diagnostic the user actually asked for. Hence the `never` error channel.
143 + */
144 +export const getSourcesFromMapFile = (
145 + name: string,
146 + location: ErrorLocation
147 +): Effect.Effect<ErrorRelatedSources | RawErrorLocation | undefined, never, FileSystem | Path> =>
148 pipe(
149 Effect.gen(function* () {
35 - const fs = yield* FileSystem;
150 const path = yield* Path;
37 - const fileExists = yield* fs.exists(`${location.filePath}.map`);
38 - if (!fileExists) {
39 - return {
40 - _tag: 'location' as const,
41 - name,
42 - ...location,
43 - filePath: location.filePath.replace(process.cwd(), ''),
44 - };
45 - }
151 + const workingDirectory = path.resolve('.');
152
47 - const data = yield* readJsonEffect<RawSourceMap>(`${location.filePath}.map`);
48 - const hasNoData = data?.version === undefined || data?.sources === undefined;
49 - if (hasNoData) {
50 - return;
51 - }
52 -
53 - const consumer = new SourceMapConsumer(data);
54 - const sources = consumer.originalPositionFor({
55 - column: location.column,
56 - line: location.line,
57 - });
58 - if (sources.source === null || sources.line === null || sources.column === null) {
59 - return;
60 - }
61 -
62 - const absolutePath = path.resolve(
63 - location.filePath.substring(0, location.filePath.lastIndexOf('/')),
64 - sources.source
65 - );
66 - const isNodeModules = absolutePath.startsWith(`${process.cwd()}/node_modules`);
67 - if (isNodeModules) {
68 - return;
69 - }
70 - const source = yield* getSourceCode(
71 - {
72 - filePath: absolutePath,
73 - line: sources.line,
74 - column: sources.column,
75 - },
76 - true
153 + return yield* enrichFromMapFile(name, location, workingDirectory).pipe(
154 + Effect.orElseSucceed(() => rawErrorLocation(name, location, workingDirectory))
155 );
78 -
79 - return {
80 - _tag: 'sources' as const,
81 - name,
82 - runPath: `${location.filePath}:${location.line}:${location.column}`,
83 - sourcesPath: `${absolutePath}:${sources.line}:${sources.column + 1}`,
84 - source,
85 - };
156 }),
157 Effect.withSpan('get-sources-from-map-file', {
158 attributes: { location: JSON.stringify(location) },
ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts
+4 -3
@@ -3,12 +3,13 @@ import type { AnySpan, Span } from 'effect/Tracer';
3
4 import { splitSpansAttributesByTypes } from 'effect-errors/logic/spans';
5
6 -import type { ErrorRelatedSources, RawErrorLocation } from './get-sources-from-map-file';
6 import {
7 + type ErrorRelatedSources,
8 isErrorRelatedSources,
9 isRawErrorLocation,
10 - maybeMapSourcemaps,
11 -} from './maybe-map-sourcemaps';
10 + type RawErrorLocation,
11 +} from './mapped-sources';
12 +import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
13
14 export const getSourcesFromSpan = ({
15 span,
ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts
+2 -5
@@ -2,11 +2,8 @@ import { Effect, pipe } from 'effect';
2
3 import { removeNodeModulesEntriesFromStack } from 'effect-errors/logic/spans';
4
5 -import {
6 - isErrorRelatedSources,
7 - isRawErrorLocation,
8 - maybeMapSourcemaps,
9 -} from './maybe-map-sourcemaps';
5 +import { isErrorRelatedSources, isRawErrorLocation } from './mapped-sources';
6 +import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
7
8 export const getSourcesFromStack = (maybeStack: string | undefined) =>
9 pipe(
ts/packages/cli/src/effect-errors/sourcemaps/index.ts
+1
@@ -1,4 +1,5 @@
1 export * from './get-error-location-from-file-path';
2 export * from './get-source-code';
3 export * from './get-sources-from-map-file';
4 +export * from './mapped-sources';
5 export * from './transform-raw-error';
ts/packages/cli/src/effect-errors/sourcemaps/mapped-sources.ts new
+28
@@ -0,0 +1,28 @@
1 +import { Data } from 'effect';
2 +
3 +import type { ErrorLocation } from './get-error-location-from-file-path';
4 +import type { SourceCode } from './get-source-code';
5 +
6 +export type MaybeMappedSources = Data.TaggedEnum<{
7 + sources: {
8 + readonly name: string;
9 + readonly source: SourceCode[];
10 + readonly runPath: string;
11 + readonly sourcesPath: string | undefined;
12 + };
13 + location: ErrorLocation & {
14 + readonly name: string;
15 + };
16 + 'stack-entry': {
17 + readonly runPath: string;
18 + };
19 +}>;
20 +
21 +export const MappedSources = Data.taggedEnum<MaybeMappedSources>();
22 +
23 +export type ErrorRelatedSources = Data.TaggedEnum.Value<MaybeMappedSources, 'sources'>;
24 +export type RawErrorLocation = Data.TaggedEnum.Value<MaybeMappedSources, 'location'>;
25 +export type StackEntry = Data.TaggedEnum.Value<MaybeMappedSources, 'stack-entry'>;
26 +
27 +export const isErrorRelatedSources = MappedSources.$is('sources');
28 +export const isRawErrorLocation = MappedSources.$is('location');
ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
+21 -45
@@ -1,56 +1,32 @@
1 -import type { PlatformError } from '@effect/platform/Error';
1 import type { FileSystem } from '@effect/platform/FileSystem';
2 import type { Path } from '@effect/platform/Path';
4 -import { Effect, Predicate, pipe } from 'effect';
3 +import { Effect } from 'effect';
4
6 -import type { JsonParsingError } from 'effect-errors/dependencies/fs';
5 import { stackAtRegex } from 'effect-errors/logic/stack';
6
7 import { getErrorRelatedSources } from './get-error-related-sources';
10 -import type { ErrorRelatedSources, RawErrorLocation } from './get-sources-from-map-file';
11 -
12 -export type StackEntry = {
13 - _tag: 'stack-entry';
14 - runPath: string;
15 -};
16 -
17 -export type MaybeMappedSources = ErrorRelatedSources | RawErrorLocation | StackEntry;
18 -
19 -export const isErrorRelatedSources = (value: MaybeMappedSources): value is ErrorRelatedSources =>
20 - Predicate.isTagged(value, 'sources');
21 -
22 -export const isRawErrorLocation = (value: MaybeMappedSources): value is RawErrorLocation =>
23 - Predicate.isTagged(value, 'location');
8 +import { MappedSources, type MaybeMappedSources } from './mapped-sources';
9
10 export const maybeMapSourcemaps = (
11 name: string,
12 stacktrace: string[]
28 -): Effect.Effect<MaybeMappedSources[], PlatformError | JsonParsingError, FileSystem | Path> =>
29 - pipe(
30 - Effect.forEach(stacktrace, stackLine =>
31 - Effect.gen(function* () {
32 - const chunks = stackLine.trimStart().split(' ');
33 - const mapFileReportedPath =
34 - chunks.length === 2 ? chunks[1] : chunks[chunks.length - 1].slice(1, -1);
35 -
36 - const details = yield* getErrorRelatedSources(name, mapFileReportedPath);
37 - if (details === undefined) {
38 - return {
39 - _tag: 'stack-entry' as const,
40 - runPath: stackLine.replaceAll(stackAtRegex, 'at '),
41 - };
42 - }
43 - if (isRawErrorLocation(details)) {
44 - return details;
45 - }
46 -
47 - const regex = new RegExp(`${process.cwd()}/node_modules/`);
48 - if (details.sourcesPath?.match(regex)) {
49 - return undefined;
50 - }
51 -
52 - return details;
53 - })
54 - ),
55 - Effect.map(array => array.filter(maybeSources => maybeSources !== undefined))
13 +): Effect.Effect<MaybeMappedSources[], never, FileSystem | Path> =>
14 + Effect.forEach(stacktrace, stackLine =>
15 + Effect.gen(function* () {
16 + const chunks = stackLine.trimStart().split(' ');
17 + const mapFileReportedPath =
18 + chunks.length === 2 ? chunks[1] : chunks[chunks.length - 1].slice(1, -1);
19 +
20 + const details = yield* getErrorRelatedSources(name, mapFileReportedPath);
21 + if (details === undefined) {
22 + return MappedSources['stack-entry']({
23 + runPath: stackLine.replaceAll(stackAtRegex, 'at '),
24 + });
25 + }
26 +
27 + // `node_modules` frames are already dropped by `getSourcesFromMapFile`,
28 + // which compares resolved paths through the `Path` service instead of
29 + // interpolating the working directory into an unescaped `RegExp`.
30 + return details;
31 + })
32 );
ts/packages/cli/src/effect-errors/sourcemaps/transform-raw-error.ts
+7 -3
@@ -1,4 +1,4 @@
1 -import { Effect, pipe } from 'effect';
1 +import { Effect, Struct, pipe } from 'effect';
2
3 import { stripCwdPath } from 'effect-errors/logic/path';
4 import { stackAtRegex } from 'effect-errors/logic/stack';
@@ -8,6 +8,8 @@ import type { PrettyError } from '../types/pretty-error.type';
8 import { getSourcesFromSpan } from './get-sources-from-span';
9 import { getSourcesFromStack } from './get-sources-from-stack';
10
11 +const dropTag = Struct.omit('_tag');
12 +
13 export const transformRawError =
14 ({ stripCwd }: CaptureErrorsOptions) =>
15 ({ message, stack: maybeStack, span, errorType, isPlainString }: PrettyError) =>
@@ -28,8 +30,10 @@ export const transformRawError =
30 errorType,
31 message,
32 stack: stack?.replaceAll(stackAtRegex, 'at ').split('\r\n'),
31 - sources: sources.length > 0 ? sources.map(({ _tag, ...data }) => data) : undefined,
32 - location: location.length > 0 ? location.map(({ _tag, ...data }) => data) : undefined,
33 + // `Struct.omit` returns a plain object, dropping the `Data` prototype
34 + // along with the tag: these values leave the source-map layer here.
35 + sources: sources.length > 0 ? sources.map(dropTag) : undefined,
36 + location: location.length > 0 ? location.map(dropTag) : undefined,
37 spans,
38 isPlainString,
39 };
ts/packages/cli/test/src/effect-errors/get-sources-from-map-file.test.ts new
+304
@@ -0,0 +1,304 @@
1 +import { FileSystem, Path } from '@effect/platform';
2 +import { BunFileSystem, BunPath } from '@effect/platform-bun';
3 +import { describe, expect, it } from '@effect/vitest';
4 +import { Cause, Effect, Layer, Scope } from 'effect';
5 +import { type RawSourceMap, SourceMapConsumer } from 'source-map-js';
6 +
7 +import { captureErrors } from 'src/effect-errors/capture-errors';
8 +import { getSourcesFromMapFile } from 'src/effect-errors/sourcemaps/get-sources-from-map-file';
9 +
10 +const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
11 +const locationFor = (filePath: string) => ({ filePath, line: 1, column: 0 });
12 +
13 +const makeSourceMapFixture = (
14 + mapContents: string,
15 + options: { readonly directory?: string; readonly sourceContents?: string } = {}
16 +) =>
17 + Effect.gen(function* () {
18 + const fs = yield* FileSystem.FileSystem;
19 + const path = yield* Path.Path;
20 + const directory = yield* fs.makeTempDirectoryScoped({
21 + directory: options.directory,
22 + prefix: 'composio-sourcemap-',
23 + });
24 + const generatedFile = path.join(directory, 'app.js');
25 +
26 + yield* fs.writeFileString(`${generatedFile}.map`, mapContents);
27 + if (options.sourceContents !== undefined) {
28 + yield* fs.writeFileString(path.join(directory, 'app.ts'), options.sourceContents);
29 + }
30 +
31 + return { directory, generatedFile };
32 + });
33 +
34 +const run = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | Scope.Scope>) =>
35 + effect.pipe(Effect.provide(TestPlatform));
36 +
37 +describe('getSourcesFromMapFile', () => {
38 + it.scoped('falls back to the full raw location when source-map JSON is malformed', () =>
39 + run(
40 + Effect.gen(function* () {
41 + const { generatedFile } = yield* makeSourceMapFixture('{ this is not valid JSON');
42 + const location = locationFor(generatedFile);
43 +
44 + expect(yield* getSourcesFromMapFile('app.js', location)).toStrictEqual({
45 + _tag: 'location',
46 + name: 'app.js',
47 + ...location,
48 + });
49 + })
50 + )
51 + );
52 +
53 + it.scoped('falls back when valid JSON is not a usable source map', () =>
54 + run(
55 + Effect.gen(function* () {
56 + const invalidSourceMap = JSON.stringify({
57 + version: 2,
58 + sources: [],
59 + names: [],
60 + mappings: '',
61 + });
62 + const { generatedFile } = yield* makeSourceMapFixture(invalidSourceMap);
63 + const location = locationFor(generatedFile);
64 +
65 + expect(yield* getSourcesFromMapFile('app.js', location)).toStrictEqual({
66 + _tag: 'location',
67 + name: 'app.js',
68 + ...location,
69 + });
70 + })
71 + )
72 + );
73 +
74 + it.scoped('falls back when source-map resolution rejects schema-valid data', () =>
75 + run(
76 + Effect.gen(function* () {
77 + const invalidSourceMap = {
78 + version: '3',
79 + sources: ['app.ts'],
80 + names: [],
81 + mappings: '!',
82 + } satisfies RawSourceMap;
83 + expect(() =>
84 + new SourceMapConsumer(invalidSourceMap).originalPositionFor({
85 + line: 1,
86 + column: 0,
87 + })
88 + ).toThrow('Invalid base64 digit');
89 +
90 + const { generatedFile } = yield* makeSourceMapFixture(JSON.stringify(invalidSourceMap));
91 + const location = locationFor(generatedFile);
92 +
93 + expect(yield* getSourcesFromMapFile('app.js', location)).toStrictEqual({
94 + _tag: 'location',
95 + name: 'app.js',
96 + ...location,
97 + });
98 + })
99 + )
100 + );
101 +
102 + it.scoped('falls back when the map points at a source file that was never shipped', () =>
103 + run(
104 + Effect.gen(function* () {
105 + const validSourceMap = JSON.stringify({
106 + version: 3,
107 + file: 'app.js',
108 + sources: ['app.ts'],
109 + names: [],
110 + mappings: 'AAAA',
111 + });
112 + // No `sourceContents`, so `app.ts` does not exist next to the map.
113 + const { generatedFile } = yield* makeSourceMapFixture(validSourceMap);
114 + const location = locationFor(generatedFile);
115 +
116 + expect(yield* getSourcesFromMapFile('app.js', location)).toStrictEqual({
117 + _tag: 'location',
118 + name: 'app.js',
119 + ...location,
120 + });
121 + })
122 + )
123 + );
124 +
125 + it.scoped('falls back when the .map path is a directory rather than a file', () =>
126 + run(
127 + Effect.gen(function* () {
128 + const fs = yield* FileSystem.FileSystem;
129 + const path = yield* Path.Path;
130 + const directory = yield* fs.makeTempDirectoryScoped({ prefix: 'composio-sourcemap-' });
131 + const generatedFile = path.join(directory, 'app.js');
132 + yield* fs.makeDirectory(`${generatedFile}.map`);
133 + const location = locationFor(generatedFile);
134 +
135 + expect(yield* getSourcesFromMapFile('app.js', location)).toStrictEqual({
136 + _tag: 'location',
137 + name: 'app.js',
138 + ...location,
139 + });
140 + })
141 + )
142 + );
143 +
144 + it.scoped('enriches maps that use null for the optional file and sourceRoot keys', () =>
145 + run(
146 + Effect.gen(function* () {
147 + const sourceContents = "throw new Error('primary diagnostic');\n";
148 + // `source-map-js` accepts both; rejecting them would silently drop
149 + // enrichment for maps emitted without an output file name.
150 + const nullableSourceMap = JSON.stringify({
151 + version: 3,
152 + file: null,
153 + sourceRoot: null,
154 + sources: ['app.ts'],
155 + names: [],
156 + mappings: 'AAAA',
157 + });
158 + const { directory, generatedFile } = yield* makeSourceMapFixture(nullableSourceMap, {
159 + sourceContents,
160 + });
161 + const path = yield* Path.Path;
162 +
163 + expect(yield* getSourcesFromMapFile('app.js', locationFor(generatedFile))).toMatchObject({
164 + _tag: 'sources',
165 + sourcesPath: `${path.join(directory, 'app.ts')}:1:1`,
166 + });
167 + })
168 + )
169 + );
170 +
171 + it.scoped('still enriches locations from valid source maps', () =>
172 + run(
173 + Effect.gen(function* () {
174 + const sourceContents = "throw new Error('primary diagnostic');\n";
175 + const validSourceMap = JSON.stringify({
176 + version: 3,
177 + file: 'app.js',
178 + sources: ['app.ts'],
179 + names: [],
180 + mappings: 'AAAA',
181 + });
182 + const { directory, generatedFile } = yield* makeSourceMapFixture(validSourceMap, {
183 + sourceContents,
184 + });
185 + const path = yield* Path.Path;
186 +
187 + expect(yield* getSourcesFromMapFile('app.js', locationFor(generatedFile))).toStrictEqual({
188 + _tag: 'sources',
189 + name: 'app.js',
190 + runPath: `${generatedFile}:1:0`,
191 + sourcesPath: `${path.join(directory, 'app.ts')}:1:1`,
192 + source: [
193 + { line: 1, code: "throw new Error('primary diagnostic');", column: 1 },
194 + { line: 2, code: '', column: undefined },
195 + ],
196 + });
197 + })
198 + )
199 + );
200 +
201 + it.scoped('preserves the primary diagnostic through captureErrors', () =>
202 + run(
203 + Effect.gen(function* () {
204 + const path = yield* Path.Path;
205 + const workingDirectory = path.resolve('.');
206 + const { generatedFile } = yield* makeSourceMapFixture('{ malformed', {
207 + directory: workingDirectory,
208 + });
209 + const primary = new Error('primary diagnostic');
210 + primary.stack = `Error: primary diagnostic\n at ${generatedFile}:1:0`;
211 +
212 + const captured = yield* captureErrors(Cause.die(primary));
213 +
214 + expect(captured.errors).toHaveLength(1);
215 + expect(captured.errors[0]).toMatchObject({
216 + errorType: 'Error',
217 + message: ['primary diagnostic'],
218 + location: [
219 + {
220 + name: '',
221 + filePath: generatedFile.replace(workingDirectory, ''),
222 + line: 1,
223 + column: 0,
224 + },
225 + ],
226 + });
227 + })
228 + )
229 + );
230 +
231 + it.scoped('preserves the primary diagnostic when the original source is missing', () =>
232 + run(
233 + Effect.gen(function* () {
234 + const path = yield* Path.Path;
235 + const workingDirectory = path.resolve('.');
236 + const validSourceMap = JSON.stringify({
237 + version: 3,
238 + file: 'app.js',
239 + sources: ['app.ts'],
240 + names: [],
241 + mappings: 'AAAA',
242 + });
243 + // A valid map whose original source was never shipped — the common
244 + // shape for a compiled binary — must not abort error capture either.
245 + const { generatedFile } = yield* makeSourceMapFixture(validSourceMap, {
246 + directory: workingDirectory,
247 + });
248 + const primary = new Error('primary diagnostic');
249 + primary.stack = `Error: primary diagnostic\n at ${generatedFile}:1:0`;
250 +
251 + const captured = yield* captureErrors(Cause.die(primary));
252 +
253 + expect(captured.errors).toHaveLength(1);
254 + expect(captured.errors[0]).toMatchObject({
255 + errorType: 'Error',
256 + message: ['primary diagnostic'],
257 + location: [
258 + {
259 + name: '',
260 + filePath: generatedFile.replace(workingDirectory, ''),
261 + line: 1,
262 + column: 0,
263 + },
264 + ],
265 + });
266 + })
267 + )
268 + );
269 +
270 + it.scoped('preserves the primary diagnostic when a .ts frame is unreadable', () =>
271 + run(
272 + Effect.gen(function* () {
273 + const path = yield* Path.Path;
274 + const fs = yield* FileSystem.FileSystem;
275 + const workingDirectory = path.resolve('.');
276 + const directory = yield* fs.makeTempDirectoryScoped({
277 + directory: workingDirectory,
278 + prefix: 'composio-sourcemap-',
279 + });
280 + // TypeScript frames skip source maps entirely and read the file
281 + // directly; a deleted file must degrade rather than abort.
282 + const missingSource = path.join(directory, 'missing.ts');
283 + const primary = new Error('primary diagnostic');
284 + primary.stack = `Error: primary diagnostic\n at ${missingSource}:1:0`;
285 +
286 + const captured = yield* captureErrors(Cause.die(primary));
287 +
288 + expect(captured.errors).toHaveLength(1);
289 + expect(captured.errors[0]).toMatchObject({
290 + errorType: 'Error',
291 + message: ['primary diagnostic'],
292 + location: [
293 + {
294 + name: '',
295 + filePath: missingSource.replace(workingDirectory, ''),
296 + line: 1,
297 + column: 0,
298 + },
299 + ],
300 + });
301 + })
302 + )
303 + );
304 +});