Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex d7849fa702 refactor(connection): preserve persistence failure causes
Co-authored-by: codex <[email protected]>
2026-06-20 18:10:46 -07:00
51 changed files with 773 additions and 3111 deletions

No files matched your search

+2 -1
View File
@@ -18,7 +18,8 @@ export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
detail: `Could not ${operation} the local connection catalog.`,
cause,
});
}
+58 -49
View File
@@ -58,23 +58,8 @@ const LegacyStoredShellSnapshot = Schema.Struct({
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function shellPersistenceError(
operation:
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
detail: `Could not ${operation} the local connection catalog.`,
cause,
});
}
@@ -100,7 +85,7 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
}
return directory;
},
catch: (cause) => shellPersistenceError(operation, cause),
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
});
},
);
@@ -117,16 +102,6 @@ const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFil
);
});
function targetPersistenceError(
operation: "list-targets" | "register-connection" | "remove-connection",
error: ConnectionTransientError,
) {
return new ConnectionPersistenceError({
operation,
message: error.message,
});
}
const secureCatalogStorage: SecureCatalogStorage = {
getItem: (key) =>
Effect.tryPromise({
@@ -163,7 +138,7 @@ const shellSnapshotFileInDirectory = Effect.fn(
directory.create({ idempotent: true, intermediates: true });
return new File(directory, shellSnapshotFileName(environmentId));
},
catch: (cause) => shellPersistenceError(operation, cause),
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
});
});
@@ -184,18 +159,29 @@ export const connectionStorageLayer = Layer.effectContext(
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
Effect.map((document) => document.targets),
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
catalog
.update((document) => registerConnectionInCatalog(document, registration))
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
.pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({ operation: "register-connection", cause }),
),
),
remove: (target) =>
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
.pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
),
),
});
const profileStore = ProfileStore.make({
get: (connectionId) =>
@@ -283,15 +269,19 @@ export const connectionStorageLayer = Layer.effectContext(
if (file.exists) {
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
);
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
@@ -303,15 +293,19 @@ export const connectionStorageLayer = Layer.effectContext(
}
const legacyRaw = yield* Effect.tryPromise({
try: () => legacyFile.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const legacyParsed = yield* Effect.try({
try: () => JSON.parse(legacyRaw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
);
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
: Option.none();
@@ -326,7 +320,11 @@ export const connectionStorageLayer = Layer.effectContext(
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
),
);
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -334,7 +332,7 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
});
}),
loadThread: (environmentId, threadId) =>
@@ -345,15 +343,19 @@ export const connectionStorageLayer = Layer.effectContext(
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-thread", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
),
);
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
@@ -368,7 +370,11 @@ export const connectionStorageLayer = Layer.effectContext(
threadId: thread.id,
thread,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
),
);
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -376,7 +382,7 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-thread", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
});
}),
removeThread: (environmentId, threadId) =>
@@ -389,7 +395,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: shellPersistenceError("remove-thread", cause),
: new ConnectionPersistenceError({ operation: "remove-thread", cause }),
),
),
clear: (environmentId) =>
@@ -398,14 +404,16 @@ export const connectionStorageLayer = Layer.effectContext(
if (file.exists) {
yield* Effect.try({
try: () => file.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
});
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
if (legacyFile.exists) {
yield* Effect.try({
try: () => legacyFile.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
@@ -415,7 +423,8 @@ export const connectionStorageLayer = Layer.effectContext(
if (threadDirectory.exists) {
yield* Effect.try({
try: () => threadDirectory.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
});
}
}),
+4 -9
View File
@@ -2,11 +2,7 @@ import { assert, it } from "@effect/vitest";
import { EnvironmentInternalError } from "@t3tools/contracts";
import {
ProjectLiveServerDeclaredResponseError,
ProjectLiveServerRequestError,
projectCommandErrorFromLiveServerRequest,
} from "./project.ts";
import { ProjectCommandError } from "./project.ts";
it("maps declared server failures into structural project command errors", () => {
const cause = new EnvironmentInternalError({
@@ -15,9 +11,8 @@ it("maps declared server failures into structural project command errors", () =>
traceId: "trace-123",
});
const error = projectCommandErrorFromLiveServerRequest(cause);
const error = ProjectCommandError.fromLiveServerRequest(cause);
assert.instanceOf(error, ProjectLiveServerDeclaredResponseError);
assert.strictEqual(error.operation, "callLiveServer");
assert.strictEqual(error.code, "internal_error");
assert.strictEqual(error.traceId, "trace-123");
@@ -28,10 +23,10 @@ it("maps declared server failures into structural project command errors", () =>
it("preserves unexpected server failures without deriving the message from them", () => {
const cause = new Error("credential abc123 was rejected");
const error = projectCommandErrorFromLiveServerRequest(cause);
const error = ProjectCommandError.fromLiveServerRequest(cause);
assert.instanceOf(error, ProjectLiveServerRequestError);
assert.strictEqual(error.operation, "callLiveServer");
assert.strictEqual(error.detail, "Failed to call the running server.");
assert.strictEqual(error.message, "Failed to call the running server.");
assert.strictEqual(error.cause, cause);
});
+49 -138
View File
@@ -51,148 +51,62 @@ type ProjectCliDispatchCommand = Extract<
>;
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
const ProjectCommandOperation = Schema.Literals([
"generateProjectCommandId",
"callLiveServer",
"validateProjectTitle",
"resolveProjectTarget",
"addProject",
]);
export class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(
"ProjectCommandIdGenerationError",
export class ProjectCommandError extends Schema.TaggedErrorClass<ProjectCommandError>()(
"ProjectCommandError",
{
operation: Schema.Literal("generateProjectCommandId"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to generate a project command identifier.";
}
}
export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedErrorClass<ProjectLiveServerDeclaredResponseError>()(
"ProjectLiveServerDeclaredResponseError",
{
operation: Schema.Literal("callLiveServer"),
code: Schema.String,
traceId: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Server request failed (${this.code}, trace ${this.traceId}).`;
}
}
export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedErrorClass<ProjectLiveServerUndeclaredStatusError>()(
"ProjectLiveServerUndeclaredStatusError",
{
operation: Schema.Literal("callLiveServer"),
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Server request failed with undeclared status ${this.status}.`;
}
}
export class ProjectLiveServerRequestError extends Schema.TaggedErrorClass<ProjectLiveServerRequestError>()(
"ProjectLiveServerRequestError",
{
operation: Schema.Literal("callLiveServer"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to call the running server.";
}
}
export class ProjectTitleEmptyError extends Schema.TaggedErrorClass<ProjectTitleEmptyError>()(
"ProjectTitleEmptyError",
{
operation: Schema.Literal("validateProjectTitle"),
title: Schema.String,
},
) {
override get message(): string {
return "Project title cannot be empty.";
}
}
export class ProjectIdentifierEmptyError extends Schema.TaggedErrorClass<ProjectIdentifierEmptyError>()(
"ProjectIdentifierEmptyError",
{
operation: Schema.Literal("resolveProjectTarget"),
identifier: Schema.String,
},
) {
override get message(): string {
return "Project identifier cannot be empty.";
}
}
export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
"ProjectNotFoundError",
{
operation: Schema.Literal("resolveProjectTarget"),
identifier: Schema.String,
normalizedWorkspaceRoot: Schema.optional(Schema.String),
activeProjectCount: Schema.Number,
operation: ProjectCommandOperation,
detail: Schema.String,
code: Schema.optional(Schema.String),
traceId: Schema.optional(Schema.String),
status: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `No active project found for '${this.identifier}'.`;
}
}
export class ProjectAlreadyExistsError extends Schema.TaggedErrorClass<ProjectAlreadyExistsError>()(
"ProjectAlreadyExistsError",
{
operation: Schema.Literal("addProject"),
projectId: ProjectId,
workspaceRoot: Schema.String,
},
) {
override get message(): string {
return `An active project already exists for '${this.workspaceRoot}'.`;
}
}
export const ProjectCommandError = Schema.Union([
ProjectCommandIdGenerationError,
ProjectLiveServerDeclaredResponseError,
ProjectLiveServerUndeclaredStatusError,
ProjectLiveServerRequestError,
ProjectTitleEmptyError,
ProjectIdentifierEmptyError,
ProjectNotFoundError,
ProjectAlreadyExistsError,
]);
export type ProjectCommandError = typeof ProjectCommandError.Type;
export function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
if (isEnvironmentHttpCommonError(cause)) {
return new ProjectLiveServerDeclaredResponseError({
static fromLiveServerRequest(cause: unknown): ProjectCommandError {
if (isEnvironmentHttpCommonError(cause)) {
return new ProjectCommandError({
operation: "callLiveServer",
detail: `Server request failed (${cause.code}, trace ${cause.traceId}).`,
code: cause.code,
traceId: cause.traceId,
cause,
});
}
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
return new ProjectCommandError({
operation: "callLiveServer",
detail: `Server request failed with undeclared status ${cause.response.status}.`,
status: cause.response.status,
cause,
});
}
return new ProjectCommandError({
operation: "callLiveServer",
code: cause.code,
traceId: cause.traceId,
cause,
});
}
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
return new ProjectLiveServerUndeclaredStatusError({
operation: "callLiveServer",
status: cause.response.status,
detail: "Failed to call the running server.",
cause,
});
}
return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
override get message(): string {
return this.detail;
}
}
const projectCommandUuid = Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.mapError(
(cause) =>
new ProjectCommandIdGenerationError({
new ProjectCommandError({
operation: "generateProjectCommandId",
detail: "Failed to generate a project command identifier.",
cause,
}),
),
@@ -244,9 +158,9 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
if (trimmed.length > 0) {
return trimmed;
}
return yield* new ProjectTitleEmptyError({
return yield* new ProjectCommandError({
operation: "validateProjectTitle",
title: explicitTitle,
detail: "Project title cannot be empty.",
});
}
@@ -261,9 +175,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
}) {
const trimmedIdentifier = input.identifier.trim();
if (trimmedIdentifier.length === 0) {
return yield* new ProjectIdentifierEmptyError({
return yield* new ProjectCommandError({
operation: "resolveProjectTarget",
identifier: input.identifier,
detail: "Project identifier cannot be empty.",
});
}
@@ -290,11 +204,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
const resolved = exactWorkspaceMatch;
if (!resolved) {
return yield* new ProjectNotFoundError({
return yield* new ProjectCommandError({
operation: "resolveProjectTarget",
identifier: trimmedIdentifier,
activeProjectCount: activeProjects.length,
...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
detail: `No active project found for '${trimmedIdentifier}'.`,
...(normalizedWorkspaceRootResult._tag === "Failure"
? { cause: normalizedWorkspaceRootResult.failure }
: {}),
@@ -316,7 +228,7 @@ const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
});
}).pipe(
withProjectCliLiveServerTimeout,
Effect.mapError(projectCommandErrorFromLiveServerRequest),
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
);
const dispatchLiveOrchestrationCommand = (
@@ -332,7 +244,7 @@ const dispatchLiveOrchestrationCommand = (
} as Parameters<typeof client.orchestration.dispatch>[0]);
}).pipe(
withProjectCliLiveServerTimeout,
Effect.mapError(projectCommandErrorFromLiveServerRequest),
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
);
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
@@ -464,10 +376,9 @@ const projectAddCommand = Command.make("add", {
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
);
if (existingProject) {
return yield* new ProjectAlreadyExistsError({
return yield* new ProjectCommandError({
operation: "addProject",
projectId: existingProject.id,
workspaceRoot,
detail: `An active project already exists for '${workspaceRoot}'.`,
});
}
+39 -17
View File
@@ -171,8 +171,20 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
if (result.status === 0) {
return;
}
throw new Error(
`Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
throw new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd,
detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
});
}
function isGitHubCliError(error: unknown): error is GitHubCli.GitHubCliError {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
(error as { _tag?: unknown })._tag === "GitHubCliError"
);
}
@@ -466,12 +478,16 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
return fakeGhOutput("");
},
catch: (error) =>
GitHubCli.isGitHubCliError(error)
isGitHubCliError(error)
? error
: new GitHubCli.GitHubCliCommandError({
: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: input.cwd,
cause: error,
detail:
error instanceof Error
? `Failed to simulate gh checkout: ${error.message}`
: "Failed to simulate gh checkout.",
}),
});
}
@@ -482,10 +498,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
const cloneUrls = scenario.repositoryCloneUrls?.[repository];
if (!cloneUrls) {
return Effect.fail(
new GitHubCli.GitHubCliCommandError({
new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: input.cwd,
cause: new Error(`Unexpected repository lookup: ${repository}`),
detail: `Unexpected repository lookup: ${repository}`,
}),
);
}
@@ -503,10 +520,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}
return Effect.fail(
new GitHubCli.GitHubCliCommandError({
new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: input.cwd,
cause: new Error(`Unexpected gh command: ${args.join(" ")}`),
detail: `Unexpected gh command: ${args.join(" ")}`,
}),
);
};
@@ -583,10 +601,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
createRepository: (input) =>
Effect.fail(
new GitHubCli.GitHubCliCommandError({
new GitHubCli.GitHubCliError({
operation: "createRepository",
command: "gh",
cwd: input.cwd,
cause: new Error(`Unexpected repository create: ${input.repository}`),
detail: `Unexpected repository create: ${input.repository}`,
}),
),
checkoutPullRequest: (input) =>
@@ -1322,10 +1341,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliUnavailableError({
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: repoDir,
cause: new Error("gh is not available on PATH"),
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
},
});
@@ -2463,10 +2483,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliUnavailableError({
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: repoDir,
cause: new Error("gh is not available on PATH"),
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
},
});
@@ -2493,10 +2514,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliAuthenticationError({
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: repoDir,
cause: new Error("gh is not authenticated"),
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
}),
},
});
@@ -1,39 +0,0 @@
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
PreviewAutomationUnavailableError,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as McpInvocationContext from "./McpInvocationContext.ts";
it.effect("reports the scoped credential context when preview capability is unavailable", () => {
const invocation: McpInvocationContext.McpInvocationScope = {
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
providerSessionId: "provider-session-1",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(),
issuedAt: 1,
expiresAt: 2,
};
return Effect.gen(function* () {
const error = yield* McpInvocationContext.requireMcpCapability("preview").pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.flip,
);
expect(error).toBeInstanceOf(PreviewAutomationUnavailableError);
expect(error).toMatchObject({
capability: "preview",
environmentId: invocation.environmentId,
threadId: invocation.threadId,
providerSessionId: invocation.providerSessionId,
providerInstanceId: invocation.providerInstanceId,
});
expect(error.message).toBe("MCP credential does not grant the preview capability.");
});
});
+3 -11
View File
@@ -1,9 +1,5 @@
import {
type EnvironmentId,
PreviewAutomationUnavailableError,
type ProviderInstanceId,
type ThreadId,
} from "@t3tools/contracts";
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { PreviewAutomationUnavailableError } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -30,11 +26,7 @@ export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function*
const invocation = yield* McpInvocationContext;
if (!invocation.capabilities.has(capability)) {
return yield* new PreviewAutomationUnavailableError({
capability,
environmentId: invocation.environmentId,
threadId: invocation.threadId,
providerSessionId: invocation.providerSessionId,
providerInstanceId: invocation.providerInstanceId,
message: `MCP credential does not grant the ${capability} capability.`,
});
}
return invocation;
@@ -4,9 +4,8 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
import { VcsProcessExitError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
@@ -346,63 +345,11 @@ describe("AzureDevOpsCli.layer", () => {
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
assert.strictEqual(error.operation, "execute");
assert.strictEqual(error.command, "az");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.argumentCount, 2);
assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
assert.strictEqual(error.cause, cause);
assert.equal(error.message.includes("sensitive-upstream-detail"), false);
}).pipe(Effect.provide(layer)),
);
it.effect("does not report a missing working directory as a missing Azure CLI", () =>
Effect.gen(function* () {
const cwd = "/missing/repo";
const platformCause = PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
syscall: "chdir",
pathOrDescriptor: cwd,
});
const cause = new VcsProcessSpawnError({
operation: "AzureDevOpsCli.execute",
command: "az",
cwd,
argumentCount: 2,
cause: platformCause,
});
mockRun.mockReturnValueOnce(Effect.fail(cause));
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.execute({ cwd, args: ["repos", "list"] }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
assert.strictEqual(error.cwd, cwd);
assert.strictEqual(error.cause, cause);
}).pipe(Effect.provide(layer)),
);
it.effect("keeps invalid pull request output diagnostics structured", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("not-json")));
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.getPullRequest({ cwd: "/repo", reference: "42" }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsPullRequestDecodeError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.command, "az");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.outputLength, 8);
assert.strictEqual(error.detail, "Azure DevOps CLI returned invalid pull request JSON.");
assert.exists(error.cause);
assert.strictEqual(
error.message,
"Azure DevOps CLI failed in getPullRequest: Azure DevOps CLI returned invalid pull request JSON.",
);
}).pipe(Effect.provide(layer)),
);
});
+83 -166
View File
@@ -1,11 +1,9 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import {
NonNegativeInt,
TrimmedNonEmptyString,
type SourceControlRepositoryVisibility,
type VcsError,
@@ -21,61 +19,16 @@ import * as SourceControlProvider from "./SourceControlProvider.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const azureDevOpsCommandErrorFields = {
operation: Schema.Literal("execute"),
command: Schema.Literal("az"),
cwd: Schema.String,
argumentCount: NonNegativeInt,
cause: Schema.Defect(),
};
export class AzureDevOpsCliUnavailableError extends Schema.TaggedErrorClass<AzureDevOpsCliUnavailableError>()(
"AzureDevOpsCliUnavailableError",
azureDevOpsCommandErrorFields,
export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliError>()(
"AzureDevOpsCliError",
{
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
get detail(): string {
return "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsCliAuthenticationError extends Schema.TaggedErrorClass<AzureDevOpsCliAuthenticationError>()(
"AzureDevOpsCliAuthenticationError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestNotFoundError>()(
"AzureDevOpsPullRequestNotFoundError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Pull request not found. Check the PR number or URL and try again.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<AzureDevOpsCommandFailedError>()(
"AzureDevOpsCommandFailedError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Azure DevOps CLI command failed.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
@@ -85,109 +38,53 @@ export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<Azure
readonly operation: "execute";
readonly command: "az";
readonly cwd: string;
readonly argumentCount: number;
},
cause: VcsError,
error: VcsError | unknown,
): AzureDevOpsCliError {
const fields = { ...context, cause };
const lower = errorText(error).toLowerCase();
if (lower.includes("command not found: az") || lower.includes("enoent")) {
return new AzureDevOpsCliError({
...context,
detail:
"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
cause: error,
});
}
if (
cause._tag === "VcsProcessSpawnError" &&
cause.cause instanceof PlatformError.PlatformError &&
cause.cause.reason._tag === "NotFound" &&
cause.cause.reason.pathOrDescriptor !== context.cwd &&
cause.cause.reason.syscall !== "chdir"
lower.includes("az devops login") ||
lower.includes("please run az login") ||
lower.includes("not logged in") ||
lower.includes("authentication failed") ||
lower.includes("unauthorized")
) {
return new AzureDevOpsCliUnavailableError(fields);
return new AzureDevOpsCliError({
...context,
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
cause: error,
});
}
if (cause._tag === "VcsProcessExitError") {
if (cause.failureKind === "authentication") {
return new AzureDevOpsCliAuthenticationError(fields);
}
if (cause.failureKind === "not-found") {
return new AzureDevOpsPullRequestNotFoundError(fields);
}
if (
lower.includes("pull request") &&
(lower.includes("not found") || lower.includes("does not exist"))
) {
return new AzureDevOpsCliError({
...context,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
}
return new AzureDevOpsCommandFailedError(fields);
return new AzureDevOpsCliError({
...context,
detail: "Azure DevOps CLI command failed.",
cause: error,
});
}
}
const azureDevOpsDecodeErrorFields = {
command: Schema.Literal("az"),
cwd: Schema.String,
outputLength: NonNegativeInt,
cause: Schema.Defect(),
};
export class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestListDecodeError>()(
"AzureDevOpsPullRequestListDecodeError",
{
operation: Schema.Literal("listPullRequests"),
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid PR list JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsPullRequestDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestDecodeError>()(
"AzureDevOpsPullRequestDecodeError",
{
operation: Schema.Literal("getPullRequest"),
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid pull request JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
const AzureDevOpsRepositoryDecodeOperation = Schema.Literals([
"getRepositoryCloneUrls",
"getDefaultBranch",
"createRepository",
]);
export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedErrorClass<AzureDevOpsRepositoryDecodeError>()(
"AzureDevOpsRepositoryDecodeError",
{
operation: AzureDevOpsRepositoryDecodeOperation,
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid repository JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export const AzureDevOpsCliError = Schema.Union([
AzureDevOpsCliUnavailableError,
AzureDevOpsCliAuthenticationError,
AzureDevOpsPullRequestNotFoundError,
AzureDevOpsCommandFailedError,
AzureDevOpsPullRequestListDecodeError,
AzureDevOpsPullRequestDecodeError,
AzureDevOpsRepositoryDecodeError,
]);
export type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type;
export const isAzureDevOpsCliError = Schema.is(AzureDevOpsCliError);
export interface AzureDevOpsRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
@@ -249,6 +146,17 @@ export class AzureDevOpsCli extends Context.Service<
}
>()("t3/sourceControl/AzureDevOpsCli") {}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
function normalizeChangeRequestId(reference: string): string {
const trimmed = reference.trim().replace(/^#/, "");
const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
@@ -317,18 +225,19 @@ function parseRepositorySpecifier(repository: string): {
function decodeAzureDevOpsJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
invalidDetail: string,
cwd: string,
): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(cause) =>
new AzureDevOpsRepositoryDecodeError({
(error) =>
new AzureDevOpsCliError({
operation,
command: "az",
cwd,
outputLength: raw.length,
cause,
detail: invalidDetail,
cause: error,
}),
),
);
@@ -348,13 +257,8 @@ export const make = Effect.gen(function* () {
})
.pipe(
Effect.mapError((error) =>
AzureDevOpsCommandFailedError.fromVcsError(
{
operation: "execute",
command: "az",
cwd: input.cwd,
argumentCount: input.args.length,
},
AzureDevOpsCliError.fromVcsError(
{ operation: "execute", command: "az", cwd: input.cwd },
error,
),
),
@@ -393,11 +297,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new AzureDevOpsPullRequestListDecodeError({
new AzureDevOpsCliError({
operation: "listPullRequests",
command: "az",
cwd: input.cwd,
outputLength: raw.length,
detail: "Azure DevOps CLI returned invalid PR list JSON.",
cause: decoded.failure,
}),
);
@@ -427,11 +331,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new AzureDevOpsPullRequestDecodeError({
new AzureDevOpsCliError({
operation: "getPullRequest",
command: "az",
cwd: input.cwd,
outputLength: raw.length,
detail: "Azure DevOps CLI returned invalid pull request JSON.",
cause: decoded.failure,
}),
);
@@ -453,6 +357,7 @@ export const make = Effect.gen(function* () {
raw,
RawAzureDevOpsRepositorySchema,
"getRepositoryCloneUrls",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
),
@@ -478,7 +383,13 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
decodeAzureDevOpsJson(
raw,
RawAzureDevOpsRepositorySchema,
"createRepository",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
);
@@ -510,7 +421,13 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
decodeAzureDevOpsJson(
raw,
RawAzureDevOpsRepositorySchema,
"getDefaultBranch",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
),
@@ -48,11 +48,11 @@ it.effect("maps Azure DevOps PR summaries into provider-neutral change requests"
it.effect("adds change-request context while retaining Azure CLI causes", () =>
Effect.gen(function* () {
const cause = new AzureDevOpsCli.AzureDevOpsCommandFailedError({
const cause = new AzureDevOpsCli.AzureDevOpsCliError({
operation: "execute",
command: "az",
cwd: "/repo",
argumentCount: 2,
detail: "Azure DevOps CLI command failed.",
cause: new Error("raw upstream detail that should remain in the cause"),
});
const provider = yield* makeProvider({
@@ -533,8 +533,8 @@ it.effect("preserves the HTTP client failure without deriving the domain message
}),
);
assert.instanceOf(error, BitbucketApi.BitbucketRequestError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.detail, "Failed to send the Bitbucket request.");
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Failed to send the Bitbucket request.",
@@ -544,61 +544,6 @@ it.effect("preserves the HTTP client failure without deriving the domain message
}).pipe(Effect.provide(layer));
});
it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => {
const responseBody = '{"error":{"message":"credential=secret-value"}}';
const { layer } = makeLayer({
response: () => new Response(responseBody, { status: 403 }),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const error = yield* bitbucket
.checkoutPullRequest({ cwd: "/repo", reference: "42" })
.pipe(Effect.flip);
assert.instanceOf(error, BitbucketApi.BitbucketResponseError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.status, 403);
assert.strictEqual(error.responseBodyLength, responseBody.length);
assert.notProperty(error, "responseBody");
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 403.",
);
assert.notInclude(error.message, "secret-value");
}).pipe(Effect.provide(layer));
});
it.effect("preserves Bitbucket response body read failures as their immediate cause", () => {
const cause = new Error("response stream failed");
const { layer } = makeLayer({
response: () =>
new Response(
new ReadableStream<Uint8Array>({
start: (controller) => controller.error(cause),
}),
{ status: 502 },
),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const error = yield* bitbucket
.getPullRequest({ cwd: "/repo", reference: "42" })
.pipe(Effect.flip);
assert.instanceOf(error, BitbucketApi.BitbucketResponseBodyReadError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.status, 502);
assert.instanceOf(error.cause, HttpClientError.HttpClientError);
assert.strictEqual(error.cause.cause, cause);
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 502.",
);
}).pipe(Effect.provide(layer));
});
it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => {
const { git, layer } = makeLayer({
response: () =>
@@ -685,9 +630,8 @@ it.effect("preserves Git checkout failures without deriving the domain message f
}),
);
assert.instanceOf(error, BitbucketApi.BitbucketCheckoutError);
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.reference, "42");
assert.strictEqual(error.operation, "checkoutPullRequest");
assert.strictEqual(error.detail, "Failed to check out the Bitbucket pull request.");
assert.strictEqual(
error.message,
"Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.",
+41 -176
View File
@@ -6,7 +6,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
NonNegativeInt,
TrimmedNonEmptyString,
type SourceControlProviderAuth,
type SourceControlRepositoryCloneUrls,
@@ -37,156 +36,20 @@ const BitbucketApiEnvConfig = Config.all({
apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
});
const BitbucketApiOperation = Schema.Literals([
"resolveRepository",
"getRepository",
"getBranchingModel",
"getPullRequest",
"listPullRequests",
"createRepository",
"createPullRequest",
"probeAuth",
"checkoutPullRequest",
]);
type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
export class BitbucketRepositoryLocatorError extends Schema.TaggedErrorClass<BitbucketRepositoryLocatorError>()(
"BitbucketRepositoryLocatorError",
export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError>()(
"BitbucketApiError",
{
repository: Schema.String,
operation: Schema.String,
detail: Schema.String,
status: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return "Bitbucket API failed in createRepository: Bitbucket repositories must be specified as workspace/repository.";
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
}
}
export class BitbucketRequestError extends Schema.TaggedErrorClass<BitbucketRequestError>()(
"BitbucketRequestError",
{
operation: BitbucketApiOperation,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Failed to send the Bitbucket request.`;
}
}
export class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketResponseError>()(
"BitbucketResponseError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
responseBodyLength: NonNegativeInt,
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
}
}
export class BitbucketResponseBodyReadError extends Schema.TaggedErrorClass<BitbucketResponseBodyReadError>()(
"BitbucketResponseBodyReadError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
}
}
export class BitbucketResponseDecodeError extends Schema.TaggedErrorClass<BitbucketResponseDecodeError>()(
"BitbucketResponseDecodeError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned invalid JSON for the requested resource.`;
}
}
export class BitbucketRepositoryVcsResolveError extends Schema.TaggedErrorClass<BitbucketRepositoryVcsResolveError>()(
"BitbucketRepositoryVcsResolveError",
{
cwd: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: Failed to resolve VCS repository for ${this.cwd}.`;
}
}
export class BitbucketRepositoryRemotesListError extends Schema.TaggedErrorClass<BitbucketRepositoryRemotesListError>()(
"BitbucketRepositoryRemotesListError",
{
cwd: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: Failed to list remotes for ${this.cwd}.`;
}
}
export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedErrorClass<BitbucketRepositoryRemoteNotFoundError>()(
"BitbucketRepositoryRemoteNotFoundError",
{
cwd: Schema.String,
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: No Bitbucket repository remote was detected for ${this.cwd}.`;
}
}
export class BitbucketPullRequestBodyReadError extends Schema.TaggedErrorClass<BitbucketPullRequestBodyReadError>()(
"BitbucketPullRequestBodyReadError",
{
cwd: Schema.String,
bodyFile: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in createPullRequest: Failed to read pull request body file ${this.bodyFile}.`;
}
}
export class BitbucketCheckoutError extends Schema.TaggedErrorClass<BitbucketCheckoutError>()(
"BitbucketCheckoutError",
{
cwd: Schema.String,
reference: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.";
}
}
export const BitbucketApiError = Schema.Union([
BitbucketRepositoryLocatorError,
BitbucketRequestError,
BitbucketResponseError,
BitbucketResponseBodyReadError,
BitbucketResponseDecodeError,
BitbucketRepositoryVcsResolveError,
BitbucketRepositoryRemotesListError,
BitbucketRepositoryRemoteNotFoundError,
BitbucketPullRequestBodyReadError,
BitbucketCheckoutError,
]);
export type BitbucketApiError = typeof BitbucketApiError.Type;
export const isBitbucketApiError = Schema.is(BitbucketApiError);
const isBitbucketApiError = Schema.is(BitbucketApiError);
const RawBitbucketRepositorySchema = Schema.Struct({
full_name: TrimmedNonEmptyString,
@@ -346,14 +209,16 @@ function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator
}
function requireRepositoryLocator(
operation: string,
repository: string,
): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
const locator = parseBitbucketRepositorySlug(repository);
return locator
? Effect.succeed(locator)
: Effect.fail(
new BitbucketRepositoryLocatorError({
repository,
new BitbucketApiError({
operation,
detail: "Bitbucket repositories must be specified as workspace/repository.",
}),
);
}
@@ -474,24 +339,20 @@ function authFromConfig(
}
function responseError(
operation: BitbucketApiOperation,
operation: string,
response: HttpClientResponse.HttpClientResponse,
): Effect.Effect<never, BitbucketApiError> {
return response.text.pipe(
Effect.mapError(
(cause) =>
new BitbucketResponseBodyReadError({
operation,
status: response.status,
cause,
}),
),
Effect.orElseSucceed(() => ""),
Effect.flatMap((body) =>
Effect.fail(
new BitbucketResponseError({
new BitbucketApiError({
operation,
status: response.status,
responseBodyLength: body.length,
detail:
body.trim().length > 0
? `Bitbucket returned HTTP ${response.status}: ${body.trim()}`
: `Bitbucket returned HTTP ${response.status}.`,
}),
),
),
@@ -518,7 +379,7 @@ export const make = Effect.gen(function* () {
};
const decodeResponse = <S extends Schema.Top>(
operation: BitbucketApiOperation,
operation: string,
schema: S,
response: HttpClientResponse.HttpClientResponse,
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
@@ -527,9 +388,9 @@ export const make = Effect.gen(function* () {
HttpClientResponse.schemaBodyJson(schema)(success).pipe(
Effect.mapError(
(cause) =>
new BitbucketResponseDecodeError({
new BitbucketApiError({
operation,
status: success.status,
detail: "Bitbucket returned invalid JSON for the requested resource.",
cause,
}),
),
@@ -538,15 +399,16 @@ export const make = Effect.gen(function* () {
})(response);
const executeJson = <S extends Schema.Top>(
operation: BitbucketApiOperation,
operation: string,
request: HttpClientRequest.HttpClientRequest,
schema: S,
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
Effect.mapError(
(cause) =>
new BitbucketRequestError({
new BitbucketApiError({
operation,
detail: "Failed to send the Bitbucket request.",
cause,
}),
),
@@ -571,8 +433,9 @@ export const make = Effect.gen(function* () {
const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
Effect.mapError(
(cause) =>
new BitbucketRepositoryVcsResolveError({
cwd: input.cwd,
new BitbucketApiError({
operation: "resolveRepository",
detail: `Failed to resolve VCS repository for ${input.cwd}.`,
cause,
}),
),
@@ -580,8 +443,9 @@ export const make = Effect.gen(function* () {
const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
Effect.mapError(
(cause) =>
new BitbucketRepositoryRemotesListError({
cwd: input.cwd,
new BitbucketApiError({
operation: "resolveRepository",
detail: `Failed to list remotes for ${input.cwd}.`,
cause,
}),
),
@@ -593,8 +457,9 @@ export const make = Effect.gen(function* () {
if (parsed) return parsed;
}
return yield* new BitbucketRepositoryRemoteNotFoundError({
cwd: input.cwd,
return yield* new BitbucketApiError({
operation: "resolveRepository",
detail: `No Bitbucket repository remote was detected for ${input.cwd}.`,
});
});
@@ -735,7 +600,7 @@ export const make = Effect.gen(function* () {
getRepositoryCloneUrls: (input) =>
getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
createRepository: (input) =>
requireRepositoryLocator(input.repository).pipe(
requireRepositoryLocator("createRepository", input.repository).pipe(
Effect.flatMap((repository) =>
executeJson(
"createRepository",
@@ -760,9 +625,9 @@ export const make = Effect.gen(function* () {
const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
Effect.mapError(
(cause) =>
new BitbucketPullRequestBodyReadError({
cwd: input.cwd,
bodyFile: input.bodyFile,
new BitbucketApiError({
operation: "createPullRequest",
detail: `Failed to read pull request body file ${input.bodyFile}.`,
cause,
}),
),
@@ -878,9 +743,9 @@ export const make = Effect.gen(function* () {
Effect.mapError((cause) =>
isBitbucketApiError(cause)
? cause
: new BitbucketCheckoutError({
cwd: input.cwd,
reference: input.reference,
: new BitbucketApiError({
operation: "checkoutPullRequest",
detail: "Failed to check out the Bitbucket pull request.",
cause,
}),
),
@@ -53,10 +53,11 @@ it.effect("maps Bitbucket PR summaries into provider-neutral change requests", (
it.effect("adds repository context while retaining Bitbucket API causes", () =>
Effect.gen(function* () {
const upstreamCause = new Error("raw upstream failure");
const cause = new BitbucketApi.BitbucketRequestError({
const cause = new BitbucketApi.BitbucketApiError({
operation: "getRepository",
cause: upstreamCause,
detail: "upstream detail that should remain in the cause",
status: 503,
cause: new Error("raw upstream failure"),
});
const provider = yield* makeProvider({
getRepositoryCloneUrls: () => Effect.fail(cause),
@@ -85,7 +86,7 @@ it.effect("adds repository context while retaining Bitbucket API causes", () =>
},
);
assert.strictEqual(error.cause, cause);
assert.equal(error.message.includes(upstreamCause.message), false);
assert.equal(error.message.includes(cause.detail), false);
}),
);
@@ -1,9 +1,8 @@
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
import { VcsProcessExitError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubCli from "./GitHubCli.ts";
@@ -31,27 +30,6 @@ afterEach(() => {
});
describe("GitHubCli.layer", () => {
it("does not classify a missing cwd as an unavailable gh executable", () => {
const context = { command: "gh", cwd: "/repo" } as const;
const missingCwd = new VcsProcessSpawnError({
operation: "GitHubCli.execute",
command: "gh",
cwd: context.cwd,
cause: PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "access",
pathOrDescriptor: context.cwd,
}),
});
const commandFailure = GitHubCli.fromVcsError(context, missingCwd);
assert.equal(commandFailure._tag, "GitHubCliCommandError");
assert.strictEqual(commandFailure.cause, missingCwd);
assert.notProperty(commandFailure, "operation");
});
it.effect("parses pull request view output", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
@@ -296,7 +274,6 @@ describe("GitHubCli.layer", () => {
command: "gh pr view",
cwd: "/repo",
exitCode: 1,
failureKind: "not-found",
detail:
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
});
@@ -311,7 +288,6 @@ describe("GitHubCli.layer", () => {
.pipe(Effect.flip);
assert.equal(error.message.includes("Pull request not found"), true);
assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
assert.strictEqual(error.command, "gh");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.cause, cause);
+106 -166
View File
@@ -1,7 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
@@ -19,163 +18,67 @@ import {
const DEFAULT_TIMEOUT_MS = 30_000;
const gitHubCliFailureFields = {
command: Schema.Literal("gh"),
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
cause: Schema.Defect(),
} as const;
export class GitHubCliUnavailableError extends Schema.TaggedErrorClass<GitHubCliUnavailableError>()(
"GitHubCliUnavailableError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI (`gh`) is required but not available on PATH.";
}
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
export class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHubCliAuthenticationError>()(
"GitHubCliAuthenticationError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI is not authenticated. Run `gh auth login` and retry.";
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
static fromVcsError(
context: {
readonly operation: "execute";
readonly command: "gh";
readonly cwd: string;
},
error: VcsError | unknown,
): GitHubCliError {
const lower = errorText(error).toLowerCase();
export class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
"GitHubPullRequestNotFoundError",
gitHubCliFailureFields,
) {
get detail(): string {
return "Pull request not found. Check the PR number or URL and try again.";
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
export class GitHubCliCommandError extends Schema.TaggedErrorClass<GitHubCliCommandError>()(
"GitHubCliCommandError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI command failed.";
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
const gitHubCliDecodeFields = {
command: Schema.Literal("gh"),
cwd: Schema.String,
cause: Schema.Defect(),
} as const;
export class GitHubPullRequestListDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestListDecodeError>()(
"GitHubPullRequestListDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid PR list JSON.";
}
override get message(): string {
return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
}
}
export class GitHubChangeRequestListDecodeError extends Schema.TaggedErrorClass<GitHubChangeRequestListDecodeError>()(
"GitHubChangeRequestListDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid change request JSON.";
}
override get message(): string {
return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
}
}
export class GitHubPullRequestDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestDecodeError>()(
"GitHubPullRequestDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid pull request JSON.";
}
override get message(): string {
return `GitHub CLI failed in getPullRequest: ${this.detail}`;
}
}
export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubRepositoryDecodeError>()(
"GitHubRepositoryDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid repository JSON.";
}
override get message(): string {
return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
}
}
export const GitHubCliError = Schema.Union([
GitHubCliUnavailableError,
GitHubCliAuthenticationError,
GitHubPullRequestNotFoundError,
GitHubCliCommandError,
GitHubPullRequestListDecodeError,
GitHubChangeRequestListDecodeError,
GitHubPullRequestDecodeError,
GitHubRepositoryDecodeError,
]);
export type GitHubCliError = typeof GitHubCliError.Type;
export const isGitHubCliError = Schema.is(GitHubCliError);
export function fromVcsError(
context: {
readonly command: "gh";
readonly cwd: string;
},
error: VcsError,
): GitHubCliError {
if (
error._tag === "VcsProcessSpawnError" &&
error.cause instanceof PlatformError.PlatformError &&
error.cause.reason._tag === "NotFound" &&
error.cause.reason.module === "ChildProcess" &&
error.cause.reason.method === "spawn"
) {
return new GitHubCliUnavailableError({ ...context, cause: error });
}
if (error._tag === "VcsProcessExitError") {
if (error.failureKind === "authentication") {
return new GitHubCliAuthenticationError({ ...context, cause: error });
if (lower.includes("command not found: gh") || lower.includes("enoent")) {
return new GitHubCliError({
...context,
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: error,
});
}
if (error.failureKind === "not-found") {
return new GitHubPullRequestNotFoundError({ ...context, cause: error });
}
}
return new GitHubCliCommandError({ ...context, cause: error });
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("gh auth login") ||
lower.includes("no oauth token")
) {
return new GitHubCliError({
...context,
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
cause: error,
});
}
if (
lower.includes("could not resolve to a pullrequest") ||
lower.includes("repository.pullrequest") ||
lower.includes("no pull requests found for branch") ||
lower.includes("pull request not found")
) {
return new GitHubCliError({
...context,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
}
return new GitHubCliError({
...context,
detail: "GitHub CLI command failed.",
cause: error,
});
}
}
export interface GitHubPullRequestSummary {
@@ -247,14 +150,22 @@ export class GitHubCli extends Context.Service<
}
>()("t3/sourceControl/GitHubCli") {}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
nameWithOwner: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
sshUrl: TrimmedNonEmptyString,
});
const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
);
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
@@ -303,6 +214,27 @@ function deriveRepositoryCloneUrlsFromCreateOutput(
};
}
function decodeGitHubJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
invalidDetail: string,
cwd: string,
): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitHubCliError({
operation,
command: "gh",
cwd,
detail: invalidDetail,
cause: error,
}),
),
);
}
export const make = Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
@@ -315,7 +247,14 @@ export const make = Effect.gen(function* () {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
})
.pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
.pipe(
Effect.mapError((error) =>
GitHubCliError.fromVcsError(
{ operation: "execute", command: "gh", cwd: input.cwd },
error,
),
),
);
return GitHubCli.of({
execute,
@@ -343,9 +282,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestListDecodeError({
new GitHubCliError({
operation: "listOpenPullRequests",
command: "gh",
cwd: input.cwd,
detail: "GitHub CLI returned invalid PR list JSON.",
cause: decoded.failure,
}),
);
@@ -375,9 +316,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestDecodeError({
new GitHubCliError({
operation: "getPullRequest",
command: "gh",
cwd: input.cwd,
detail: "GitHub CLI returned invalid pull request JSON.",
cause: decoded.failure,
}),
);
@@ -397,15 +340,12 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeRawGitHubRepositoryCloneUrls(raw).pipe(
Effect.mapError(
(cause) =>
new GitHubRepositoryDecodeError({
command: "gh",
cwd: input.cwd,
cause,
}),
),
decodeGitHubJson(
raw,
RawGitHubRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitHub CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
@@ -70,9 +70,11 @@ it.effect("maps GitHub PR summaries into provider-neutral change requests", () =
it.effect("adds safe request context while retaining GitHub CLI causes", () =>
Effect.gen(function* () {
const cause = new GitHubCli.GitHubPullRequestNotFoundError({
const cause = new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: "/repo",
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: new Error("raw upstream detail that should remain in the cause"),
});
const provider = yield* makeProvider({
@@ -158,17 +158,23 @@ export const make = Effect.gen(function* () {
})),
)
: Effect.fail(
new GitHubCli.GitHubChangeRequestListDecodeError({
new SourceControlProviderError({
provider: "github",
operation: "listChangeRequests",
command: "gh",
cwd: input.cwd,
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
input.headSelector,
),
detail: "GitHub CLI returned invalid change request JSON.",
cause: decoded.failure,
}),
),
),
);
}),
Effect.mapError(
(error) =>
Effect.catchTags({
GitHubCliError: (error) =>
new SourceControlProviderError({
provider: "github",
operation: "listChangeRequests",
@@ -180,7 +186,7 @@ export const make = Effect.gen(function* () {
detail: error.detail,
cause: error,
}),
),
}),
);
};
@@ -315,11 +315,10 @@ layer("GitLabCli.layer", (it) => {
Effect.gen(function* () {
const cause = new VcsProcessExitError({
operation: "GitLabCli.execute",
command: "glab",
command: "glab mr view 4888",
cwd: "/repo",
exitCode: 1,
detail: "GET 404 merge request not found",
failureKind: "not-found",
});
mockedRun.mockReturnValueOnce(Effect.fail(cause));
@@ -331,37 +330,11 @@ layer("GitLabCli.layer", (it) => {
});
}).pipe(Effect.flip);
assert.equal(error.message.includes("Merge request 4888 was not found"), true);
assert.strictEqual(error._tag, "GitLabMergeRequestNotFoundError");
assert.equal(error.message.includes("Merge request not found"), true);
assert.strictEqual(error.command, "glab");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.cause, cause);
assert.equal(error.message.includes(cause.detail), false);
}),
);
it.effect("keeps non-merge-request not-found failures generic", () =>
Effect.gen(function* () {
const cause = new VcsProcessExitError({
operation: "GitLabCli.execute",
command: "glab",
cwd: "/repo",
exitCode: 1,
detail: "GET 404 project not found",
failureKind: "not-found",
});
mockedRun.mockReturnValueOnce(Effect.fail(cause));
const error = yield* Effect.gen(function* () {
const glab = yield* GitLabCli.GitLabCli;
return yield* glab.getRepositoryCloneUrls({
cwd: "/repo",
repository: "missing/project",
});
}).pipe(Effect.flip);
assert.strictEqual(error._tag, "GitLabCliCommandError");
assert.strictEqual(error.cause, cause);
}),
);
});
+122 -267
View File
@@ -1,7 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Match from "effect/Match";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
@@ -22,56 +21,13 @@ import type * as SourceControlProvider from "./SourceControlProvider.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const gitLabCliExecutionErrorContext = {
operation: Schema.Literal("execute"),
command: Schema.Literal("glab"),
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
cause: Schema.Defect(),
};
const gitLabCliDecodeErrorContext = {
command: Schema.Literal("glab"),
cwd: Schema.String,
cause: Schema.Defect(),
};
export class GitLabCliUnavailableError extends Schema.TaggedErrorClass<GitLabCliUnavailableError>()(
"GitLabCliUnavailableError",
gitLabCliExecutionErrorContext,
) {
get detail(): string {
return "GitLab CLI (`glab`) is required but not available on PATH.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabCliAuthenticationError extends Schema.TaggedErrorClass<GitLabCliAuthenticationError>()(
"GitLabCliAuthenticationError",
gitLabCliExecutionErrorContext,
) {
get detail(): string {
return "GitLab CLI is not authenticated. Run `glab auth login` and retry.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<GitLabMergeRequestNotFoundError>()(
"GitLabMergeRequestNotFoundError",
{
...gitLabCliExecutionErrorContext,
reference: Schema.String,
},
) {
get detail(): string {
return `Merge request ${this.reference} was not found. Check the MR number or URL and try again.`;
}
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
@@ -81,145 +37,52 @@ export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<Git
readonly operation: "execute";
readonly command: "glab";
readonly cwd: string;
readonly reference: string;
},
error: VcsError,
error: VcsError | unknown,
): GitLabCliError {
if (error._tag === "VcsProcessExitError" && error.failureKind === "not-found") {
return new GitLabMergeRequestNotFoundError({ ...context, cause: error });
const lower = errorText(error).toLowerCase();
if (lower.includes("command not found: glab") || isVcsProcessSpawnError(error)) {
return new GitLabCliError({
...context,
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
cause: error,
});
}
return GitLabCliCommandError.fromVcsError(
{
operation: context.operation,
command: context.command,
cwd: context.cwd,
},
error,
);
}
}
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("glab auth login") ||
lower.includes("token")
) {
return new GitLabCliError({
...context,
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
cause: error,
});
}
export class GitLabCliCommandError extends Schema.TaggedErrorClass<GitLabCliCommandError>()(
"GitLabCliCommandError",
gitLabCliExecutionErrorContext,
) {
get detail(): string {
return "GitLab CLI command failed.";
}
if (
lower.includes("merge request not found") ||
lower.includes("not found") ||
lower.includes("404")
) {
return new GitLabCliError({
...context,
detail: "Merge request not found. Check the MR number or URL and try again.",
cause: error,
});
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
static fromVcsError(
context: {
readonly operation: "execute";
readonly command: "glab";
readonly cwd: string;
},
error: VcsError,
): GitLabCliError {
return Match.valueTags(error, {
VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }),
VcsProcessExitError: (cause) => {
switch (cause.failureKind) {
case "authentication":
return new GitLabCliAuthenticationError({ ...context, cause });
case "not-found":
case "command-failed":
case undefined:
return new GitLabCliCommandError({ ...context, cause });
}
},
VcsProcessTimeoutError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsOutputDecodeError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsRepositoryDetectionError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),
return new GitLabCliError({
...context,
detail: "GitLab CLI command failed.",
cause: error,
});
}
}
export class GitLabMergeRequestListDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestListDecodeError>()(
"GitLabMergeRequestListDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literal("listMergeRequests"),
},
) {
get detail(): string {
return "GitLab CLI returned invalid MR list JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabMergeRequestDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestDecodeError>()(
"GitLabMergeRequestDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literal("getMergeRequest"),
reference: Schema.String,
},
) {
get detail(): string {
return "GitLab CLI returned invalid merge request JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabRepositoryDecodeError extends Schema.TaggedErrorClass<GitLabRepositoryDecodeError>()(
"GitLabRepositoryDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literals(["getRepositoryCloneUrls", "createRepository", "getDefaultBranch"]),
repository: Schema.optional(Schema.String),
},
) {
get detail(): string {
return "GitLab CLI returned invalid repository JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabNamespaceDecodeError extends Schema.TaggedErrorClass<GitLabNamespaceDecodeError>()(
"GitLabNamespaceDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literal("createRepository"),
namespacePath: Schema.String,
},
) {
get detail(): string {
return "GitLab CLI returned invalid namespace JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export const GitLabCliError = Schema.Union([
GitLabCliUnavailableError,
GitLabCliAuthenticationError,
GitLabMergeRequestNotFoundError,
GitLabCliCommandError,
GitLabMergeRequestListDecodeError,
GitLabMergeRequestDecodeError,
GitLabRepositoryDecodeError,
GitLabNamespaceDecodeError,
]);
export type GitLabCliError = typeof GitLabCliError.Type;
export const isGitLabCliError = Schema.is(GitLabCliError);
export interface GitLabMergeRequestSummary {
readonly number: number;
readonly title: string;
@@ -239,6 +102,17 @@ export interface GitLabRepositoryCloneUrls {
readonly sshUrl: string;
}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
export class GitLabCli extends Context.Service<
GitLabCli,
{
@@ -294,6 +168,15 @@ export class GitLabCli extends Context.Service<
}
>()("t3/sourceControl/GitLabCli") {}
function isVcsProcessSpawnError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
error._tag === "VcsProcessSpawnError"
);
}
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
path_with_namespace: TrimmedNonEmptyString,
web_url: TrimmedNonEmptyString,
@@ -309,14 +192,6 @@ const RawGitLabNamespaceSchema = Schema.Struct({
id: Schema.Number,
});
const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
);
const decodeGitLabDefaultBranch = Schema.decodeEffect(
Schema.fromJsonString(RawGitLabDefaultBranchSchema),
);
const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
): GitLabRepositoryCloneUrls {
@@ -327,6 +202,27 @@ function normalizeRepositoryCloneUrls(
};
}
function decodeGitLabJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
invalidDetail: string,
cwd: string,
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitLabCliError({
operation,
command: "glab",
cwd,
detail: invalidDetail,
cause: error,
}),
),
);
}
function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
switch (state) {
case "open":
@@ -387,10 +283,7 @@ function parseRepositoryPath(repository: string): {
export const make = Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
const run = (
input: Parameters<GitLabCli["Service"]["execute"]>[0],
mapError: (error: VcsError) => GitLabCliError,
) =>
const execute: GitLabCli["Service"]["execute"] = (input) =>
process
.run({
operation: "GitLabCli.execute",
@@ -399,32 +292,14 @@ export const make = Effect.gen(function* () {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
})
.pipe(Effect.mapError(mapError));
const execute: GitLabCli["Service"]["execute"] = (input) =>
run(input, (error) =>
GitLabCliCommandError.fromVcsError(
{ operation: "execute", command: "glab", cwd: input.cwd },
error,
),
);
const executeMergeRequest = (input: {
readonly cwd: string;
readonly reference: string;
readonly args: ReadonlyArray<string>;
}) =>
run(input, (error) =>
GitLabMergeRequestNotFoundError.fromVcsError(
{
operation: "execute",
command: "glab",
cwd: input.cwd,
reference: input.reference,
},
error,
),
);
.pipe(
Effect.mapError((error) =>
GitLabCliError.fromVcsError(
{ operation: "execute", command: "glab", cwd: input.cwd },
error,
),
),
);
return GitLabCli.of({
execute,
@@ -451,10 +326,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestListDecodeError({
new GitLabCliError({
operation: "listMergeRequests",
command: "glab",
cwd: input.cwd,
detail: "GitLab CLI returned invalid MR list JSON.",
cause: decoded.failure,
}),
);
@@ -466,9 +342,8 @@ export const make = Effect.gen(function* () {
),
),
getMergeRequest: (input) =>
executeMergeRequest({
execute({
cwd: input.cwd,
reference: input.reference,
args: ["mr", "view", input.reference, "--output", "json"],
}).pipe(
Effect.map((result) => result.stdout.trim()),
@@ -477,11 +352,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestDecodeError({
new GitLabCliError({
operation: "getMergeRequest",
command: "glab",
cwd: input.cwd,
reference: input.reference,
detail: "GitLab CLI returned invalid merge request JSON.",
cause: decoded.failure,
}),
);
@@ -499,17 +374,12 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabRepositoryCloneUrls(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabRepositoryDecodeError({
operation: "getRepositoryCloneUrls",
command: "glab",
cwd: input.cwd,
repository: input.repository,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitLab CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
@@ -523,17 +393,12 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabNamespace(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabNamespaceDecodeError({
operation: "createRepository",
command: "glab",
cwd: input.cwd,
namespacePath,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabNamespaceSchema,
"createRepository",
"GitLab CLI returned invalid namespace JSON.",
input.cwd,
),
),
Effect.map((namespace) => namespace.id),
@@ -563,17 +428,12 @@ export const make = Effect.gen(function* () {
),
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabRepositoryCloneUrls(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabRepositoryDecodeError({
operation: "createRepository",
command: "glab",
cwd: input.cwd,
repository: input.repository,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabRepositoryCloneUrlsSchema,
"createRepository",
"GitLab CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
@@ -607,24 +467,19 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabDefaultBranch(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabRepositoryDecodeError({
operation: "getDefaultBranch",
command: "glab",
cwd: input.cwd,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabDefaultBranchSchema,
"getDefaultBranch",
"GitLab CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map((value) => value.default_branch ?? null),
),
checkoutMergeRequest: (input) =>
executeMergeRequest({
execute({
cwd: input.cwd,
reference: input.reference,
args: ["mr", "checkout", input.reference],
}).pipe(Effect.asVoid),
});
@@ -54,10 +54,11 @@ it.effect("maps GitLab MR summaries into provider-neutral change requests", () =
it.effect("adds repository context while retaining GitLab CLI causes", () =>
Effect.gen(function* () {
const cause = new GitLabCli.GitLabCliCommandError({
const cause = new GitLabCli.GitLabCliError({
operation: "execute",
command: "glab",
cwd: "/repo",
detail: "GitLab CLI command failed.",
cause: new Error("raw upstream detail that should remain in the cause"),
});
const provider = yield* makeProvider({
+9 -18
View File
@@ -151,29 +151,20 @@ export const make = Effect.gen(function* () {
if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, normalizedCwd))) {
return;
}
const recoverRefreshFailure = (
cause:
| WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
| WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
| WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
) =>
Effect.gen(function* () {
yield* Effect.logWarning("Failed to refresh workspace search index", {
cwd,
cause,
});
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
});
yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
yield* searchIndex.refresh();
}).pipe(
Effect.provide(workspaceSearchIndexes.get(normalizedCwd)),
Effect.catchTags({
WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
}),
Effect.catch((cause) =>
Effect.gen(function* () {
yield* Effect.logWarning("Failed to refresh workspace search index", {
cwd,
cause,
});
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
}),
),
);
},
);
@@ -1,8 +1,6 @@
import { FileFinder } from "@ff-labs/fff-node";
import { afterEach, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import { vi } from "vite-plus/test";
import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
@@ -51,35 +49,6 @@ it.effect("keeps returned FileFinder creation diagnostics out of the cause chain
}),
);
it.effect("preserves FileFinder destroy failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("native destroy failed");
const finder = {
destroy: vi.fn(() => {
throw cause;
}),
isScanning: vi.fn(() => false),
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
const exit = yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")).pipe(
Effect.exit,
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasDies(exit.cause)).toBe(true);
const error = Cause.squash(exit.cause);
expect(error).toBeInstanceOf(WorkspaceSearchIndex.WorkspaceSearchIndexDestroyFailed);
expect(error).toMatchObject({
_tag: "WorkspaceSearchIndexDestroyFailed",
cwd: "/workspace/project",
cause,
});
}
}),
);
it.effect("preserves search and refresh failures with operation context", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -71,18 +71,6 @@ export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedErrorClass<W
}
}
export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexDestroyFailed>()(
"WorkspaceSearchIndexDestroyFailed",
{
cwd: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to destroy the workspace search index for '${this.cwd}'.`;
}
}
export type WorkspaceSearchIndexError =
| WorkspaceSearchIndexCreateFailed
| WorkspaceSearchIndexScanTimedOut
@@ -213,10 +201,7 @@ const waitForScan = <E>(cwd: string, finder: FileFinder, onFailure: (cause: unkn
export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: string) {
const finder = yield* Effect.acquireRelease(createFinder(cwd), (finder) =>
Effect.try({
try: () => finder.destroy(),
catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
}).pipe(Effect.orDie),
Effect.sync(() => finder.destroy()),
);
yield* waitForScan(
cwd,
+4 -1
View File
@@ -70,7 +70,10 @@ describe("makeCatalogBackend", () => {
const error = yield* backend.write("{}").pipe(Effect.flip);
expect(error).toBeInstanceOf(ConnectionTransientError);
expect(error.message).toContain("Desktop secure storage is unavailable");
expect(error.message).toBe("Could not save the local connection catalog.");
expect(error.cause).toEqual(
new Error("Desktop secure storage is unavailable in this system context."),
);
expect(setConnectionCatalog).toHaveBeenCalledWith("{}");
}),
);
+47 -34
View File
@@ -63,26 +63,8 @@ const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshotJson)
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function persistenceError(
operation:
| "list-targets"
| "register-connection"
| "remove-connection"
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
detail: `Could not ${operation} the local connection catalog.`,
cause,
});
}
@@ -233,7 +215,7 @@ export function makeCatalogBackend(database: IDBDatabase): CatalogBackend {
: Effect.fail(
catalogError(
"save",
"Desktop secure storage is unavailable in this system context.",
new Error("Desktop secure storage is unavailable in this system context."),
),
),
),
@@ -330,18 +312,29 @@ export const connectionStorageLayer = Layer.effectContext(
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
Effect.map((document) => document.targets),
Effect.mapError((cause) => persistenceError("list-targets", cause)),
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
catalog
.update((document) => registerConnectionInCatalog(document, registration))
.pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),
.pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({ operation: "register-connection", cause }),
),
),
remove: (target) =>
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
.pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
),
),
});
const profileStore = ProfileStore.make({
get: (connectionId) =>
@@ -430,7 +423,9 @@ export const connectionStorageLayer = Layer.effectContext(
return Effect.succeed(Option.none());
}
return decodeStoredShellSnapshot(raw).pipe(
Effect.mapError((cause) => persistenceError("load-shell", cause)),
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
Effect.map((stored) =>
stored.environmentId === environmentId
? Option.some(stored.snapshot)
@@ -441,7 +436,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("load-shell", cause),
: new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
),
saveShell: (environmentId, snapshot) =>
@@ -450,13 +445,17 @@ export const connectionStorageLayer = Layer.effectContext(
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
}).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
),
);
yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
}).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("save-shell", cause),
: new ConnectionPersistenceError({ operation: "save-shell", cause }),
),
),
loadThread: (environmentId, threadId) =>
@@ -470,7 +469,9 @@ export const connectionStorageLayer = Layer.effectContext(
return Effect.succeed(Option.none());
}
return decodeStoredThreadSnapshot(raw).pipe(
Effect.mapError((cause) => persistenceError("load-thread", cause)),
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
),
Effect.map((stored) =>
stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
@@ -481,7 +482,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("load-thread", cause),
: new ConnectionPersistenceError({ operation: "load-thread", cause }),
),
),
saveThread: (environmentId, thread) =>
@@ -491,7 +492,11 @@ export const connectionStorageLayer = Layer.effectContext(
environmentId,
threadId: thread.id,
thread,
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
}).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
),
);
yield* writeDatabaseValue(
database,
THREAD_STORE_NAME,
@@ -502,7 +507,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: persistenceError("save-thread", cause),
: new ConnectionPersistenceError({ operation: "save-thread", cause }),
),
),
removeThread: (environmentId, threadId) =>
@@ -510,7 +515,11 @@ export const connectionStorageLayer = Layer.effectContext(
database,
THREAD_STORE_NAME,
threadCacheKey(environmentId, threadId),
).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause))),
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "remove-thread", cause }),
),
),
clear: (environmentId) =>
Effect.all(
[
@@ -522,7 +531,11 @@ export const connectionStorageLayer = Layer.effectContext(
),
],
{ concurrency: "unbounded", discard: true },
).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))),
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "clear-environment", cause }),
),
),
});
return Context.make(ConnectionTargetStore, targetStore).pipe(
-193
View File
@@ -1,193 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
function createStorage(overrides: Partial<Storage> = {}): Storage {
const store = new Map<string, string>();
return {
clear: () => store.clear(),
getItem: (key) => store.get(key) ?? null,
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
removeItem: (key) => {
store.delete(key);
},
setItem: (key, value) => {
store.set(key, value);
},
...overrides,
};
}
afterEach(() => {
vi.doUnmock("react");
vi.resetModules();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
describe("theme failure handling", () => {
it("preserves exact storage causes and operation context", async () => {
const readCause = new Error("storage read blocked");
const writeCause = new Error("storage quota exceeded");
vi.stubGlobal("window", {
localStorage: createStorage({
getItem: () => {
throw readCause;
},
setItem: () => {
throw writeCause;
},
}),
});
const { readThemePreference, ThemeStorageError, writeThemePreference } =
await import("./useTheme");
try {
readThemePreference();
expect.unreachable("expected the theme read to fail");
} catch (error) {
expect(error).toBeInstanceOf(ThemeStorageError);
expect(error).toMatchObject({
operation: "read",
storageKey: "t3code:theme",
cause: readCause,
});
}
try {
writeThemePreference("dark");
expect.unreachable("expected the theme write to fail");
} catch (error) {
expect(error).toBeInstanceOf(ThemeStorageError);
expect(error).toMatchObject({
operation: "write",
storageKey: "t3code:theme",
theme: "dark",
cause: writeCause,
});
}
});
it("falls back during initial theme application and logs only safe attributes", async () => {
const cause = new Error("private browsing storage failure");
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
vi.stubGlobal("window", {
localStorage: createStorage({
getItem: () => {
throw cause;
},
}),
matchMedia: () => ({ matches: false }),
});
vi.stubGlobal("document", {
documentElement: {
classList: { toggle: vi.fn() },
},
});
await expect(import("./useTheme")).resolves.toBeDefined();
expect(errorLog).toHaveBeenCalledWith(
"Failed to read theme preference for t3code:theme.",
expect.objectContaining({
operation: "read",
storageKey: "t3code:theme",
errorTag: "ThemeStorageError",
}),
);
const attributes = errorLog.mock.calls[0]?.[1];
expect(attributes).not.toHaveProperty("cause");
expect(JSON.stringify(attributes)).not.toContain(cause.message);
});
it("retries a failed storage read only after a relevant storage event", async () => {
const cause = new Error("persistent storage failure");
const getItem = vi.fn(() => {
throw cause;
});
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
let readSnapshot: (() => unknown) | undefined;
let subscribeToTheme: ((listener: () => void) => () => void) | undefined;
let storageHandler: ((event: StorageEvent) => void) | undefined;
vi.doMock("react", () => ({
useCallback: <A>(callback: A) => callback,
useEffect: () => undefined,
useSyncExternalStore: (
subscribe: (listener: () => void) => () => void,
getSnapshot: () => unknown,
) => {
subscribeToTheme = subscribe;
readSnapshot = getSnapshot;
return getSnapshot();
},
}));
vi.stubGlobal("window", {
addEventListener: (type: string, listener: (event: StorageEvent) => void) => {
if (type === "storage") storageHandler = listener;
},
localStorage: createStorage({ getItem }),
matchMedia: () => ({
matches: false,
addEventListener: () => undefined,
removeEventListener: () => undefined,
}),
removeEventListener: () => undefined,
});
const { useTheme } = await import("./useTheme");
useTheme();
readSnapshot?.();
readSnapshot?.();
expect(getItem).toHaveBeenCalledTimes(1);
expect(errorLog).toHaveBeenCalledTimes(1);
const unsubscribe = subscribeToTheme?.(() => undefined);
storageHandler?.({ key: "t3code:theme" } as StorageEvent);
readSnapshot?.();
expect(getItem).toHaveBeenCalledTimes(2);
expect(errorLog).toHaveBeenCalledTimes(2);
unsubscribe?.();
});
it("preserves desktop sync causes and retries after a failed cosmetic sync", async () => {
const cause = new Error("desktop IPC unavailable");
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
const setTheme = vi.fn().mockRejectedValue(cause);
vi.stubGlobal("window", { desktopBridge: { setTheme } });
const { DesktopThemeSyncError, syncDesktopTheme, syncDesktopThemePreference } =
await import("./useTheme");
const error = await syncDesktopThemePreference({ setTheme }, "dark").then(
() => undefined,
(failure: unknown) => failure,
);
expect(error).toBeInstanceOf(DesktopThemeSyncError);
expect(error).toMatchObject({ theme: "dark", cause });
setTheme.mockClear();
syncDesktopTheme("dark");
await Promise.resolve();
await Promise.resolve();
syncDesktopTheme("dark");
await Promise.resolve();
await Promise.resolve();
expect(setTheme).toHaveBeenCalledTimes(2);
expect(errorLog).toHaveBeenCalledWith(
"Failed to sync the dark theme to the desktop shell.",
expect.objectContaining({
theme: "dark",
errorTag: "DesktopThemeSyncError",
}),
);
for (const [, attributes] of errorLog.mock.calls) {
expect(attributes).not.toHaveProperty("cause");
expect(JSON.stringify(attributes)).not.toContain(cause.message);
}
});
});
+14 -132
View File
@@ -1,17 +1,11 @@
import type { DesktopBridge } from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import * as Schema from "effect/Schema";
import { useCallback, useEffect, useSyncExternalStore } from "react";
const ThemePreference = Schema.Literals(["light", "dark", "system"]);
type Theme = typeof ThemePreference.Type;
type Theme = "light" | "dark" | "system";
type ThemeSnapshot = {
theme: Theme;
systemDark: boolean;
};
type DesktopThemeBridge = Pick<DesktopBridge, "setTheme">;
const STORAGE_KEY = "t3code:theme";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
@@ -21,46 +15,19 @@ const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
const THEME_COLOR_META_NAME = "theme-color";
const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
export class ThemeStorageError extends Schema.TaggedErrorClass<ThemeStorageError>()(
"ThemeStorageError",
{
operation: Schema.Literals(["read", "write"]),
storageKey: Schema.String,
theme: Schema.optional(ThemePreference),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} theme preference for ${this.storageKey}.`;
}
}
export const isThemeStorageError = Schema.is(ThemeStorageError);
export class DesktopThemeSyncError extends Schema.TaggedErrorClass<DesktopThemeSyncError>()(
"DesktopThemeSyncError",
{
theme: ThemePreference,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to sync the ${this.theme} theme to the desktop shell.`;
}
}
export const isDesktopThemeSyncError = Schema.is(DesktopThemeSyncError);
let listeners: Array<() => void> = [];
let lastSnapshot: ThemeSnapshot | null = null;
let lastDesktopTheme: Theme | null = null;
let lastAppliedTheme: ThemeSnapshot | null = null;
let themeStorageReadFailure: ThemeStorageError | null = null;
function emitChange() {
for (const listener of listeners) listener();
}
function hasThemeStorage() {
return typeof window !== "undefined" && typeof localStorage !== "undefined";
}
function getSystemDark() {
return (
typeof window !== "undefined" &&
@@ -69,61 +36,13 @@ function getSystemDark() {
);
}
export function readThemePreference(): Theme {
if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT.theme;
let raw: string | null;
try {
raw = window.localStorage.getItem(STORAGE_KEY);
} catch (cause) {
throw new ThemeStorageError({
operation: "read",
storageKey: STORAGE_KEY,
cause,
});
}
function getStored(): Theme {
if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT.theme;
const raw = localStorage.getItem(STORAGE_KEY);
if (raw === "light" || raw === "dark" || raw === "system") return raw;
return DEFAULT_THEME_SNAPSHOT.theme;
}
export function writeThemePreference(theme: Theme): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(STORAGE_KEY, theme);
themeStorageReadFailure = null;
} catch (cause) {
throw new ThemeStorageError({
operation: "write",
storageKey: STORAGE_KEY,
theme,
cause,
});
}
}
function getStored(): Theme {
if (themeStorageReadFailure !== null) {
return DEFAULT_THEME_SNAPSHOT.theme;
}
try {
return readThemePreference();
} catch (cause) {
const error = isThemeStorageError(cause)
? cause
: new ThemeStorageError({
operation: "read",
storageKey: STORAGE_KEY,
cause,
});
themeStorageReadFailure = error;
console.error(error.message, {
operation: error.operation,
storageKey: error.storageKey,
...safeErrorLogAttributes(error),
});
return DEFAULT_THEME_SNAPSHOT.theme;
}
}
function ensureThemeColorMetaTag(): HTMLMetaElement {
let element = document.querySelector<HTMLMetaElement>(DYNAMIC_THEME_COLOR_SELECTOR);
if (element) {
@@ -199,18 +118,7 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
}
}
export async function syncDesktopThemePreference(
bridge: DesktopThemeBridge,
theme: Theme,
): Promise<void> {
try {
await bridge.setTheme(theme);
} catch (cause) {
throw new DesktopThemeSyncError({ theme, cause });
}
}
export function syncDesktopTheme(theme: Theme) {
function syncDesktopTheme(theme: Theme) {
if (typeof window === "undefined") return;
const bridge = window.desktopBridge;
if (!bridge || typeof bridge.setTheme !== "function" || lastDesktopTheme === theme) {
@@ -218,14 +126,7 @@ export function syncDesktopTheme(theme: Theme) {
}
lastDesktopTheme = theme;
void syncDesktopThemePreference(bridge, theme).catch((cause: unknown) => {
const error = isDesktopThemeSyncError(cause)
? cause
: new DesktopThemeSyncError({ theme, cause });
console.error(error.message, {
theme: error.theme,
...safeErrorLogAttributes(error),
});
void bridge.setTheme(theme).catch(() => {
if (lastDesktopTheme === theme) {
lastDesktopTheme = null;
}
@@ -233,12 +134,12 @@ export function syncDesktopTheme(theme: Theme) {
}
// Apply immediately on module load to prevent flash
if (typeof document !== "undefined" && typeof window !== "undefined") {
if (typeof document !== "undefined" && hasThemeStorage()) {
applyTheme(getStored());
}
function getSnapshot(): ThemeSnapshot {
if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT;
if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT;
const theme = getStored();
const systemDark = theme === "system" ? getSystemDark() : false;
@@ -269,7 +170,6 @@ function subscribe(listener: () => void): () => void {
// Listen for storage changes from other tabs
const handleStorage = (e: StorageEvent) => {
if (e.key === STORAGE_KEY) {
themeStorageReadFailure = null;
applyTheme(getStored(), true);
emitChange();
}
@@ -291,26 +191,8 @@ export function useTheme() {
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
const setTheme = useCallback((next: Theme) => {
if (typeof window === "undefined") return;
try {
writeThemePreference(next);
} catch (cause) {
const error = isThemeStorageError(cause)
? cause
: new ThemeStorageError({
operation: "write",
storageKey: STORAGE_KEY,
theme: next,
cause,
});
console.error(error.message, {
operation: error.operation,
storageKey: error.storageKey,
theme: next,
...safeErrorLogAttributes(error),
});
return;
}
if (!hasThemeStorage()) return;
localStorage.setItem(STORAGE_KEY, next);
applyTheme(next, true);
emitChange();
}, []);
@@ -81,6 +81,7 @@ export class ConnectionTransientError extends Schema.TaggedErrorClass<Connection
reason: ConnectionTransientReason,
detail: Schema.String,
traceId: Schema.optionalKey(Schema.String),
cause: Schema.optionalKey(Schema.Defect()),
},
) {
override get message(): string {
@@ -689,12 +689,13 @@ describe("EnvironmentRegistry", () => {
it.effect("keeps the runtime registered when durable removal fails", () =>
Effect.gen(function* () {
const persistenceCause = new Error("Storage is unavailable.");
const harness = yield* makeHarness([RELAY_TARGET], [], [], {
beforeRegistrationRemove: () =>
Effect.fail(
new Persistence.ConnectionPersistenceError({
operation: "remove-connection",
message: "Storage is unavailable.",
cause: persistenceCause,
}),
),
});
@@ -711,6 +712,8 @@ describe("EnvironmentRegistry", () => {
const error = yield* Effect.flip(registry.removeRelayEnvironments());
expect(error._tag).toBe("ConnectionPersistenceError");
expect(error.message).toBe("Could not remove connection.");
expect(error.cause).toBe(persistenceCause);
expect(yield* Ref.get(harness.releasedSessions)).toBe(0);
expect((yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId)).toBe(
true,
@@ -26,9 +26,13 @@ export class ConnectionPersistenceError extends Schema.TaggedErrorClass<Connecti
"remove-thread",
"clear-environment",
]),
message: Schema.String,
cause: Schema.Defect(),
},
) {}
) {
override get message(): string {
return `Could not ${this.operation.replaceAll("-", " ")}.`;
}
}
export class ConnectionTargetStore extends Context.Service<
ConnectionTargetStore,
+2 -12
View File
@@ -453,18 +453,8 @@ export type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;
export class PreviewAutomationUnavailableError extends Schema.TaggedErrorClass<PreviewAutomationUnavailableError>()(
"PreviewAutomationUnavailableError",
{
capability: Schema.Literal("preview"),
environmentId: EnvironmentId,
threadId: ThreadId,
providerSessionId: TrimmedNonEmptyString,
providerInstanceId: ProviderInstanceId,
},
) {
override get message(): string {
return `MCP credential does not grant the ${this.capability} capability.`;
}
}
{ message: Schema.String },
) {}
const PreviewAutomationScopeErrorFields = {
operation: PreviewAutomationOperation,
@@ -1,45 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as AcpError from "../errors.ts";
import { makeTerminationError } from "./stdio.ts";
describe("ACP child process termination", () => {
it.effect("retains the process identifier with the exit code", () =>
Effect.gen(function* () {
const error = yield* makeTerminationError({
pid: ChildProcessSpawner.ProcessId(41),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(7)),
});
assert.instanceOf(error, AcpError.AcpProcessExitedError);
assert.equal(error.pid, 41);
assert.equal(error.code, 7);
assert.equal(error.message, "ACP process exited with code 7");
}),
);
it.effect("retains the process identifier and exact exit-status cause", () =>
Effect.gen(function* () {
const rootCause = new Error("private process diagnostics");
const cause = PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: "exitCode",
cause: rootCause,
});
const error = yield* makeTerminationError({
pid: ChildProcessSpawner.ProcessId(42),
exitCode: Effect.fail(cause),
});
assert.instanceOf(error, AcpError.AcpTransportError);
assert.equal(error.pid, 42);
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "ACP transport operation read-process-exit-status failed.");
assert.notInclude(error.message, rootCause.message);
}),
);
});
+2 -8
View File
@@ -44,20 +44,14 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
};
});
type ChildProcessTerminationHandle = Pick<
ChildProcessSpawner.ChildProcessHandle,
"exitCode" | "pid"
>;
export const makeTerminationError = (
handle: ChildProcessTerminationHandle,
handle: ChildProcessSpawner.ChildProcessHandle,
): Effect.Effect<AcpError.AcpError> =>
Effect.match(handle.exitCode, {
onFailure: (cause) =>
new AcpError.AcpTransportError({
operation: "read-process-exit-status",
pid: handle.pid,
cause,
}),
onSuccess: (code) => new AcpError.AcpProcessExitedError({ code, pid: handle.pid }),
onSuccess: (code) => new AcpError.AcpProcessExitedError({ code }),
});
-2
View File
@@ -91,7 +91,6 @@ export class AcpProcessExitedError extends Schema.TaggedErrorClass<AcpProcessExi
"AcpProcessExitedError",
{
code: Schema.optional(Schema.Number),
pid: Schema.optionalKey(Schema.Int),
cause: Schema.optional(Schema.Defect()),
},
) {
@@ -161,7 +160,6 @@ export class AcpTransportError extends Schema.TaggedErrorClass<AcpTransportError
),
method: Schema.optional(Schema.String),
detail: Schema.optional(Schema.String),
pid: Schema.optionalKey(Schema.Int),
cause: Schema.Defect(),
},
) {
@@ -1,48 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexError from "../errors.ts";
import { makeTerminationError } from "./stdio.ts";
describe("Codex App Server child process termination", () => {
it.effect("retains the process identifier with the exit code", () =>
Effect.gen(function* () {
const error = yield* makeTerminationError({
pid: ChildProcessSpawner.ProcessId(51),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(9)),
});
assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);
assert.equal(error.pid, 51);
assert.equal(error.code, 9);
assert.equal(error.message, "Codex App Server process exited with code 9");
}),
);
it.effect("retains the process identifier and exact exit-status cause", () =>
Effect.gen(function* () {
const rootCause = new Error("private process diagnostics");
const cause = PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: "exitCode",
cause: rootCause,
});
const error = yield* makeTerminationError({
pid: ChildProcessSpawner.ProcessId(52),
exitCode: Effect.fail(cause),
});
assert.instanceOf(error, CodexError.CodexAppServerTransportError);
assert.equal(error.pid, 52);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
"Codex App Server transport operation 'read-process-exit-status' failed.",
);
assert.notInclude(error.message, rootCause.message);
}),
);
});
@@ -44,20 +44,14 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
};
});
type ChildProcessTerminationHandle = Pick<
ChildProcessSpawner.ChildProcessHandle,
"exitCode" | "pid"
>;
export const makeTerminationError = (
handle: ChildProcessTerminationHandle,
handle: ChildProcessSpawner.ChildProcessHandle,
): Effect.Effect<CodexError.CodexAppServerError> =>
Effect.match(handle.exitCode, {
onFailure: (cause) =>
new CodexError.CodexAppServerTransportError({
operation: "read-process-exit-status",
pid: handle.pid,
cause,
}),
onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code, pid: handle.pid }),
onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code }),
});
+1 -34
View File
@@ -82,11 +82,6 @@ const payloadKind = (payload: unknown): CodexAppServerPayloadKind => {
return typeof payload;
};
const protocolMessageFields = ["id", "method", "params", "result", "error"] as const;
export const CodexAppServerProtocolMessageField = Schema.Literals(protocolMessageFields);
export type CodexAppServerProtocolMessageField = typeof CodexAppServerProtocolMessageField.Type;
export interface CodexAppServerRequestDiagnostics {
readonly method?: string;
readonly requestId?: string;
@@ -146,7 +141,6 @@ export class CodexAppServerProcessExitedError extends Schema.TaggedErrorClass<Co
"CodexAppServerProcessExitedError",
{
code: Schema.optional(Schema.Number),
pid: Schema.optionalKey(Schema.Int),
cause: Schema.optional(Schema.Defect()),
},
) {
@@ -163,8 +157,7 @@ export class CodexAppServerProtocolParseError extends Schema.TaggedErrorClass<Co
operation: CodexAppServerProtocolParseOperation,
method: Schema.optionalKey(Schema.String),
requestId: Schema.optionalKey(Schema.String),
payloadKind: Schema.optionalKey(CodexAppServerPayloadKind),
presentFields: Schema.optionalKey(Schema.Array(CodexAppServerProtocolMessageField)),
detail: Schema.optionalKey(Schema.String),
issueCount: Schema.optionalKey(Schema.Number),
issueKinds: Schema.optionalKey(Schema.Array(CodexAppServerSchemaIssueKind)),
maximumPathDepth: Schema.optionalKey(Schema.Number),
@@ -203,38 +196,12 @@ export class CodexAppServerProtocolParseError extends Schema.TaggedErrorClass<Co
cause,
});
}
static fromUnroutableMessage(message: unknown) {
const diagnostics = { payloadKind: payloadKind(message) };
if (typeof message !== "object" || message === null || Array.isArray(message)) {
return new CodexAppServerProtocolParseError({
operation: "route-wire-message",
...diagnostics,
});
}
const presentFields = protocolMessageFields.filter((field) => field in message);
const method =
"method" in message && typeof message.method === "string" ? message.method : undefined;
const requestId =
"id" in message && (typeof message.id === "string" || typeof message.id === "number")
? String(message.id)
: undefined;
return new CodexAppServerProtocolParseError({
operation: "route-wire-message",
...diagnostics,
presentFields,
...(method === undefined ? {} : { method }),
...(requestId === undefined ? {} : { requestId }),
});
}
}
export class CodexAppServerTransportError extends Schema.TaggedErrorClass<CodexAppServerTransportError>()(
"CodexAppServerTransportError",
{
operation: CodexAppServerTransportOperation,
pid: Schema.optionalKey(Schema.Int),
cause: Schema.Defect(),
},
) {
@@ -311,36 +311,6 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
}),
);
it.effect("describes unroutable messages with safe structural diagnostics", () =>
Effect.gen(function* () {
const secret = "codex-unroutable-secret-sentinel";
const { stdio, input } = yield* makeInMemoryStdio();
const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
});
yield* Queue.offer(
input,
encodeJsonl({ id: true, method: "thread/start", params: { token: secret } }),
);
const error = yield* Deferred.await(termination);
assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
assert.deepInclude(error, {
operation: "route-wire-message",
method: "thread/start",
payloadKind: "object",
presentFields: ["id", "method", "params"],
});
assert.isUndefined(error.requestId);
assert.notProperty(error, "detail");
assert.notProperty(error, "cause");
assert.notInclude(error.message, secret);
}),
);
it.effect("classifies an input stream ending without inventing a cause", () =>
Effect.gen(function* () {
const { stdio, input } = yield* makeInMemoryStdio();
@@ -310,7 +310,10 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
return handleResponse(message);
}
return Effect.fail(
CodexError.CodexAppServerProtocolParseError.fromUnroutableMessage(message),
new CodexError.CodexAppServerProtocolParseError({
detail: "Received protocol message in an unknown shape",
operation: "route-wire-message",
}),
);
};
+2 -7
View File
@@ -108,15 +108,10 @@ describe("tailscale", () => {
it.effect("preserves status decoding failures without exposing cause text", () =>
Effect.gen(function* () {
const malformedStatus = "{not-json";
const error = yield* parseTailscaleStatus(malformedStatus).pipe(Effect.flip);
const error = yield* parseTailscaleStatus("{not-json").pipe(Effect.flip);
assert.instanceOf(error, TailscaleStatusParseError);
assert.equal(error.inputLength, malformedStatus.length);
assert.equal(
error.message,
`Failed to decode ${malformedStatus.length}-character tailscale status JSON.`,
);
assert.equal(error.message, "Failed to decode tailscale status JSON.");
assert.isDefined(error.cause);
assert.notInclude(error.message, String(error.cause));
}),
+4 -11
View File
@@ -84,13 +84,10 @@ export type TailscaleCommandError = typeof TailscaleCommandError.Type;
export class TailscaleStatusParseError extends Schema.TaggedErrorClass<TailscaleStatusParseError>()(
"TailscaleStatusParseError",
{
inputLength: Schema.Number,
cause: Schema.Defect(),
},
{ cause: Schema.Defect() },
) {
override get message(): string {
return `Failed to decode ${this.inputLength}-character tailscale status JSON.`;
return "Failed to decode tailscale status JSON.";
}
}
@@ -138,9 +135,7 @@ export const parseTailscaleMagicDnsName = (
rawStatusJson: string,
): Effect.Effect<string | null, TailscaleStatusParseError> =>
decodeTailscaleStatusJson(rawStatusJson).pipe(
Effect.mapError(
(cause) => new TailscaleStatusParseError({ inputLength: rawStatusJson.length, cause }),
),
Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
Effect.map(normalizeMagicDnsName),
);
@@ -166,9 +161,7 @@ export const parseTailscaleStatus = (
rawStatusJson: string,
): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>
decodeTailscaleStatusJson(rawStatusJson).pipe(
Effect.mapError(
(cause) => new TailscaleStatusParseError({ inputLength: rawStatusJson.length, cause }),
),
Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
Effect.map((parsed) => {
const rawIps = parsed.Self?.TailscaleIPs;
const tailnetIpv4Addresses: Array<string> = [];
+8 -37
View File
@@ -9,17 +9,15 @@ import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
BuildCommandFailedError,
BuildScriptError,
createStageWorkspaceConfig,
createStagePnpmConfig,
createBuildConfig,
DESKTOP_ASAR_UNPACK,
InvalidMacPasskeyRpDomainError,
InvalidMacPasskeyPublishableKeyError,
InvalidMockUpdateServerPortError,
isMacPasskeySigningConfigurationError,
LinuxIconResizeError,
MacPasskeySigningConfigurationResolutionError,
MissingMacPasskeyProvisioningProfileError,
renderMacPasskeyEntitlements,
resolveClerkPasskeyNativeArtifacts,
@@ -251,16 +249,10 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
const aggregateCause = error.cause as AggregateError;
assert.lengthOf(aggregateCause.errors, 2);
assert.strictEqual(aggregateCause.cause, aggregateCause.errors[0]);
assert.instanceOf(aggregateCause.errors[0], BuildCommandFailedError);
assert.instanceOf(aggregateCause.errors[1], BuildCommandFailedError);
const primaryError = aggregateCause.errors[0] as BuildCommandFailedError;
const fallbackError = aggregateCause.errors[1] as BuildCommandFailedError;
assert.equal(primaryError.command, "magick linux icon 512x512");
assert.equal(primaryError.exitCode, 1);
assert.include(primaryError.message, "magick linux icon");
assert.equal(fallbackError.command, "convert linux icon 512x512");
assert.equal(fallbackError.exitCode, 2);
assert.include(fallbackError.message, "convert linux icon");
assert.instanceOf(aggregateCause.errors[0], BuildScriptError);
assert.instanceOf(aggregateCause.errors[1], BuildScriptError);
assert.include((aggregateCause.errors[0] as BuildScriptError).message, "magick linux icon");
assert.include((aggregateCause.errors[1] as BuildScriptError).message, "convert linux icon");
assert.deepStrictEqual(
commands.map(({ command }) => command),
["magick", "convert"],
@@ -364,7 +356,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
it("preserves known passkey signing configuration errors at the build boundary", () => {
const decodingCause = new Error("publishable-key-decode-failed");
const knownError = new InvalidMacPasskeyPublishableKeyError({ cause: decodingCause });
const error = MacPasskeySigningConfigurationResolutionError.fromCause(knownError);
const error = BuildScriptError.fromMacPasskeySigningConfiguration(knownError);
assert.strictEqual(error, knownError);
assert.instanceOf(error, InvalidMacPasskeyPublishableKeyError);
@@ -375,9 +367,9 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
it("wraps unknown passkey signing configuration defects without copying cause text", () => {
const secret = "pk_test_do-not-retain";
const cause = new Error(secret);
const error = MacPasskeySigningConfigurationResolutionError.fromCause(cause);
const error = BuildScriptError.fromMacPasskeySigningConfiguration(cause);
assert.instanceOf(error, MacPasskeySigningConfigurationResolutionError);
assert.instanceOf(error, BuildScriptError);
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "Failed to resolve macOS passkey signing configuration.");
assert.notInclude(error.message, secret);
@@ -461,27 +453,6 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
}),
);
it("classifies invalid configured ports with the decoder's number grammar", () => {
const cause = new Error("invalid configured port");
assert.equal(
InvalidMockUpdateServerPortError.fromConfigValue("0x10", cause).reason,
"not-numeric",
);
assert.equal(
InvalidMockUpdateServerPortError.fromConfigValue("12.5", cause).reason,
"not-integer",
);
assert.equal(
InvalidMockUpdateServerPortError.fromConfigValue("65536", cause).reason,
"out-of-range",
);
assert.strictEqual(
InvalidMockUpdateServerPortError.fromConfigValue("0x10", cause).cause,
cause,
);
});
it.effect("resolves default platform and architecture from host references", () =>
Effect.gen(function* () {
const resolved = yield* resolveBuildOptions({
+67 -312
View File
@@ -18,6 +18,7 @@ import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Config from "effect/Config";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -125,238 +126,19 @@ const getDefaultArch = Effect.fn("getDefaultArch")(function* (platform: typeof B
return yield* getDefaultBuildArch(platform, config);
});
export class MacPasskeySigningConfigurationResolutionError extends Schema.TaggedErrorClass<MacPasskeySigningConfigurationResolutionError>()(
"MacPasskeySigningConfigurationResolutionError",
{
cause: Schema.Defect(),
},
) {
static fromCause(
export class BuildScriptError extends Data.TaggedError("BuildScriptError")<{
readonly message: string;
readonly cause?: unknown;
}> {
static fromMacPasskeySigningConfiguration(
cause: unknown,
): MacPasskeySigningConfigurationError | MacPasskeySigningConfigurationResolutionError {
): MacPasskeySigningConfigurationError | BuildScriptError {
return isMacPasskeySigningConfigurationError(cause)
? cause
: new MacPasskeySigningConfigurationResolutionError({ cause });
}
override get message(): string {
return "Failed to resolve macOS passkey signing configuration.";
}
}
export class ClerkPasskeyNativePackageMissingError extends Schema.TaggedErrorClass<ClerkPasskeyNativePackageMissingError>()(
"ClerkPasskeyNativePackageMissingError",
{
packageName: Schema.String,
binaryFileName: Schema.String,
packageEntryPath: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Clerk passkey native package is missing: ${this.packageName}`;
}
}
export class UnsupportedHostBuildPlatformError extends Schema.TaggedErrorClass<UnsupportedHostBuildPlatformError>()(
"UnsupportedHostBuildPlatformError",
{
hostPlatform: Schema.String,
},
) {
override get message(): string {
return `Unsupported host platform '${this.hostPlatform}'.`;
}
}
const InvalidMockUpdateServerPortReason = Schema.Literals([
"not-numeric",
"not-integer",
"out-of-range",
]);
export class InvalidMockUpdateServerPortError extends Schema.TaggedErrorClass<InvalidMockUpdateServerPortError>()(
"InvalidMockUpdateServerPortError",
{
reason: InvalidMockUpdateServerPortReason,
inputLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Invalid mock update server port.";
}
static fromConfigValue(configuredPort: string, cause: unknown) {
return new InvalidMockUpdateServerPortError({
reason: invalidMockUpdateServerPortReason(configuredPort),
inputLength: configuredPort.length,
cause,
});
}
}
export class BuildCommandFailedError extends Schema.TaggedErrorClass<BuildCommandFailedError>()(
"BuildCommandFailedError",
{
command: Schema.String,
exitCode: Schema.Int,
stdoutTail: Schema.optionalKey(Schema.String),
stderrTail: Schema.optionalKey(Schema.String),
},
) {
override get message(): string {
const outputSections = [
`Command: ${this.command}`,
formatOutputSection("stdout", this.stdoutTail ?? ""),
formatOutputSection("stderr", this.stderrTail ?? ""),
].filter((section): section is string => section !== undefined);
const outputSuffix = outputSections.length > 0 ? `\n\n${outputSections.join("\n\n")}` : "";
return `Command exited with non-zero exit code (${this.exitCode})${outputSuffix}`;
}
}
const desktopIconPlatformNames = {
mac: "macOS",
linux: "Linux",
win: "Windows",
} satisfies Record<typeof BuildPlatform.Type, string>;
export class DesktopIconSourceMissingError extends Schema.TaggedErrorClass<DesktopIconSourceMissingError>()(
"DesktopIconSourceMissingError",
{
platform: BuildPlatform,
sourcePath: Schema.String,
},
) {
override get message(): string {
return `Desktop ${desktopIconPlatformNames[this.platform]} icon source is missing at ${this.sourcePath}`;
}
}
export class BundledClientAssetsMissingError extends Schema.TaggedErrorClass<BundledClientAssetsMissingError>()(
"BundledClientAssetsMissingError",
{
indexPath: Schema.String,
missingFiles: Schema.Array(Schema.String),
},
) {
override get message(): string {
const preview = this.missingFiles.slice(0, 6).join(", ");
const suffix = this.missingFiles.length > 6 ? ` (+${this.missingFiles.length - 6} more)` : "";
return `Bundled client references missing files in ${this.indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`;
}
}
export class UnsupportedDesktopBuildPlatformError extends Schema.TaggedErrorClass<UnsupportedDesktopBuildPlatformError>()(
"UnsupportedDesktopBuildPlatformError",
{
platform: Schema.String,
},
) {
override get message(): string {
return `Unsupported platform '${this.platform}'.`;
}
}
const dependencyResolutionDescriptions = {
"server-production": "production dependencies",
"workspace-overrides": "overrides",
"desktop-runtime": "desktop runtime dependencies",
} as const;
const DependencyResolutionKind = Schema.Literals([
"server-production",
"workspace-overrides",
"desktop-runtime",
]);
export class DesktopBuildDependencyResolutionError extends Schema.TaggedErrorClass<DesktopBuildDependencyResolutionError>()(
"DesktopBuildDependencyResolutionError",
{
kind: DependencyResolutionKind,
manifestPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Could not resolve ${dependencyResolutionDescriptions[this.kind]} from ${this.manifestPath}.`;
}
}
export class MissingServerProductionDependenciesError extends Schema.TaggedErrorClass<MissingServerProductionDependenciesError>()(
"MissingServerProductionDependenciesError",
{
manifestPath: Schema.String,
},
) {
override get message(): string {
return `Could not resolve production dependencies from ${this.manifestPath}.`;
}
}
const DesktopBuildInputArtifact = Schema.Literals([
"desktop-dist",
"desktop-resources",
"server-dist",
"bundled-server-client",
]);
type DesktopBuildInputArtifact = typeof DesktopBuildInputArtifact.Type;
const desktopBuildInputArtifactNames = {
"desktop-dist": "desktopDist",
"desktop-resources": "desktopResources",
"server-dist": "serverDist",
"bundled-server-client": "bundled server client",
} satisfies Record<DesktopBuildInputArtifact, string>;
export class MissingDesktopBuildInputError extends Schema.TaggedErrorClass<MissingDesktopBuildInputError>()(
"MissingDesktopBuildInputError",
{
artifact: DesktopBuildInputArtifact,
artifactPath: Schema.String,
buildCommand: Schema.Literal("vp run build:desktop"),
},
) {
override get message(): string {
return `Missing ${desktopBuildInputArtifactNames[this.artifact]} at ${this.artifactPath}. Run '${this.buildCommand}' first.`;
}
}
export class MacProvisioningProfileNotFoundError extends Schema.TaggedErrorClass<MacProvisioningProfileNotFoundError>()(
"MacProvisioningProfileNotFoundError",
{
provisioningProfilePath: Schema.String,
},
) {
override get message(): string {
return `macOS provisioning profile not found: ${this.provisioningProfilePath}`;
}
}
export class DesktopBuildDistDirectoryMissingError extends Schema.TaggedErrorClass<DesktopBuildDistDirectoryMissingError>()(
"DesktopBuildDistDirectoryMissingError",
{
distPath: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
},
) {
override get message(): string {
return `Build completed but dist directory was not found at ${this.distPath}`;
}
}
export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedErrorClass<DesktopBuildNoArtifactsProducedError>()(
"DesktopBuildNoArtifactsProducedError",
{
distPath: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
},
) {
override get message(): string {
return `Build completed but no files were produced in ${this.distPath}`;
: new BuildScriptError({
message: "Failed to resolve macOS passkey signing configuration.",
cause,
});
}
}
@@ -834,12 +616,8 @@ const stageClerkPasskeyNativeBinaries = Effect.fn("stageClerkPasskeyNativeBinari
const sourcePath = yield* Effect.try({
try: () => packageRequire.resolve(artifact.packageName),
catch: (cause) =>
new ClerkPasskeyNativePackageMissingError({
packageName: artifact.packageName,
binaryFileName: artifact.binaryFileName,
packageEntryPath,
platform,
arch,
new BuildScriptError({
message: `Clerk passkey native package is missing: ${artifact.packageName}`,
cause,
}),
});
@@ -913,18 +691,6 @@ const MockUpdateServerPortSchema = Schema.NumberFromString.check(
);
const decodeMockUpdateServerPort = Schema.decodeUnknownEffect(MockUpdateServerPortSchema);
function invalidMockUpdateServerPortReason(
configuredPort: string,
): typeof InvalidMockUpdateServerPortReason.Type {
const parsed = Number(configuredPort);
if (!Number.isFinite(parsed)) return "not-numeric";
if (!Number.isInteger(parsed)) return "not-integer";
if (parsed < 1 || parsed > 65535) return "out-of-range";
// This mapper is only called after schema decoding failed. An otherwise
// valid integer therefore used a representation the decoder did not accept.
return "not-numeric";
}
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
Option.getOrElse(flag, () => envValue);
const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
@@ -956,7 +722,9 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
);
if (!platform) {
return yield* new UnsupportedHostBuildPlatformError({ hostPlatform });
return yield* new BuildScriptError({
message: `Unsupported host platform '${hostPlatform}'.`,
});
}
const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget);
@@ -977,16 +745,17 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
const verbose = resolveBooleanFlag(input.verbose, env.verbose);
const mockUpdates = resolveBooleanFlag(input.mockUpdates, env.mockUpdates);
const configuredMockUpdateServerPort = Option.getOrUndefined(env.mockUpdateServerPort);
const mockUpdateServerPort =
Option.getOrUndefined(input.mockUpdateServerPort) ??
(configuredMockUpdateServerPort === undefined
? undefined
: yield* resolveMockUpdateServerPort(configuredMockUpdateServerPort).pipe(
Effect.mapError((cause) =>
InvalidMockUpdateServerPortError.fromConfigValue(configuredMockUpdateServerPort, cause),
),
));
(yield* resolveMockUpdateServerPort(Option.getOrUndefined(env.mockUpdateServerPort)).pipe(
Effect.mapError(
(cause) =>
new BuildScriptError({
message: "Invalid mock update server port.",
cause,
}),
),
));
return {
platform,
@@ -1006,7 +775,7 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
const runCommand = Effect.fn("runCommand")(function* (
command: ChildProcess.Command,
options: {
readonly label: string;
readonly label?: string;
readonly verbose: boolean;
},
) {
@@ -1022,11 +791,14 @@ const runCommand = Effect.fn("runCommand")(function* (
);
if (exitCode !== 0) {
return yield* new BuildCommandFailedError({
command: options.label,
exitCode,
...(stdout.trim() ? { stdoutTail: stdout } : {}),
...(stderr.trim() ? { stderrTail: stderr } : {}),
const outputSections = [
options.label ? `Command: ${options.label}` : undefined,
formatOutputSection("stdout", stdout),
formatOutputSection("stderr", stderr),
].filter((section): section is string => section !== undefined);
const outputSuffix = outputSections.length > 0 ? `\n\n${outputSections.join("\n\n")}` : "";
return yield* new BuildScriptError({
message: `Command exited with non-zero exit code (${exitCode})${outputSuffix}`,
});
}
});
@@ -1073,9 +845,8 @@ function stageMacIcons(stageResourcesDir: string, sourcePng: string, verbose: bo
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
if (!(yield* fs.exists(sourcePng))) {
return yield* new DesktopIconSourceMissingError({
platform: "mac",
sourcePath: sourcePng,
return yield* new BuildScriptError({
message: `Desktop macOS icon source is missing at ${sourcePng}`,
});
}
@@ -1100,9 +871,8 @@ function stageLinuxIcons(stageResourcesDir: string, sourcePng: string, verbose:
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
if (!(yield* fs.exists(sourcePng))) {
return yield* new DesktopIconSourceMissingError({
platform: "linux",
sourcePath: sourcePng,
return yield* new BuildScriptError({
message: `Desktop Linux icon source is missing at ${sourcePng}`,
});
}
@@ -1161,9 +931,8 @@ function stageWindowsIcons(stageResourcesDir: string, sourceIco: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
if (!(yield* fs.exists(sourceIco))) {
return yield* new DesktopIconSourceMissingError({
platform: "win",
sourcePath: sourceIco,
return yield* new BuildScriptError({
message: `Desktop Windows icon source is missing at ${sourceIco}`,
});
}
@@ -1200,9 +969,10 @@ function validateBundledClientAssets(clientDir: string) {
}
if (missing.length > 0) {
return yield* new BundledClientAssetsMissingError({
indexPath,
missingFiles: missing,
const preview = missing.slice(0, 6).join(", ");
const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
return yield* new BuildScriptError({
message: `Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
});
}
});
@@ -1404,8 +1174,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const platformConfig = PLATFORM_CONFIG[options.platform];
if (!platformConfig) {
return yield* new UnsupportedDesktopBuildPlatformError({
platform: options.platform,
return yield* new BuildScriptError({
message: `Unsupported platform '${options.platform}'.`,
});
}
@@ -1413,17 +1183,16 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const serverDependencies = serverPackageJson.dependencies;
if (!serverDependencies || Object.keys(serverDependencies).length === 0) {
return yield* new MissingServerProductionDependenciesError({
manifestPath: "apps/server/package.json",
return yield* new BuildScriptError({
message: "Could not resolve production dependencies from apps/server/package.json.",
});
}
const resolvedOverrides = yield* Effect.try({
try: () => resolveCatalogDependencies(workspaceOverrides, workspaceCatalog, "apps/desktop"),
catch: (cause) =>
new DesktopBuildDependencyResolutionError({
kind: "workspace-overrides",
manifestPath: "pnpm-workspace.yaml",
new BuildScriptError({
message: "Could not resolve overrides from pnpm-workspace.yaml.",
cause,
}),
});
@@ -1431,18 +1200,16 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const resolvedServerDependencies = yield* Effect.try({
try: () => resolveCatalogDependencies(serverDependencies, workspaceCatalog, "apps/server"),
catch: (cause) =>
new DesktopBuildDependencyResolutionError({
kind: "server-production",
manifestPath: "apps/server/package.json",
new BuildScriptError({
message: "Could not resolve production dependencies from apps/server/package.json.",
cause,
}),
});
const resolvedDesktopRuntimeDependencies = yield* Effect.try({
try: () => resolveDesktopRuntimeDependencies(desktopPackageJson.dependencies, workspaceCatalog),
catch: (cause) =>
new DesktopBuildDependencyResolutionError({
kind: "desktop-runtime",
manifestPath: "apps/desktop/package.json",
new BuildScriptError({
message: "Could not resolve desktop runtime dependencies from apps/desktop/package.json.",
cause,
}),
});
@@ -1476,25 +1243,17 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
);
}
const requiredBuildInputs = [
{ artifact: "desktop-dist", artifactPath: distDirs.desktopDist },
{ artifact: "desktop-resources", artifactPath: distDirs.desktopResources },
{ artifact: "server-dist", artifactPath: distDirs.serverDist },
] as const;
for (const input of requiredBuildInputs) {
if (!(yield* fs.exists(input.artifactPath))) {
return yield* new MissingDesktopBuildInputError({
...input,
buildCommand: "vp run build:desktop",
for (const [label, dir] of Object.entries(distDirs)) {
if (!(yield* fs.exists(dir))) {
return yield* new BuildScriptError({
message: `Missing ${label} at ${dir}. Run 'vp run build:desktop' first.`,
});
}
}
if (!(yield* fs.exists(bundledClientEntry))) {
return yield* new MissingDesktopBuildInputError({
artifact: "bundled-server-client",
artifactPath: bundledClientEntry,
buildCommand: "vp run build:desktop",
return yield* new BuildScriptError({
message: `Missing bundled server client at ${bundledClientEntry}. Run 'vp run build:desktop' first.`,
});
}
@@ -1526,7 +1285,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
options.platform === "mac" && options.signed
? yield* Effect.try({
try: () => resolveMacPasskeySigningConfiguration(loadRepoEnv({ repoRoot })),
catch: MacPasskeySigningConfigurationResolutionError.fromCause,
catch: BuildScriptError.fromMacPasskeySigningConfiguration,
})
: undefined;
const macPasskeySigning = configuredMacPasskeySigning
@@ -1543,8 +1302,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
: undefined;
if (macPasskeySigning && macEntitlementsPath) {
if (!(yield* fs.exists(macPasskeySigning.provisioningProfilePath))) {
return yield* new MacProvisioningProfileNotFoundError({
provisioningProfilePath: macPasskeySigning.provisioningProfilePath,
return yield* new BuildScriptError({
message: `macOS provisioning profile not found: ${macPasskeySigning.provisioningProfilePath}`,
});
}
yield* fs.writeFileString(macEntitlementsPath, renderMacPasskeyEntitlements(macPasskeySigning));
@@ -1683,10 +1442,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const stageDistDir = path.join(stageAppDir, "dist");
if (!(yield* fs.exists(stageDistDir))) {
return yield* new DesktopBuildDistDirectoryMissingError({
distPath: stageDistDir,
platform: options.platform,
arch: options.arch,
return yield* new BuildScriptError({
message: `Build completed but dist directory was not found at ${stageDistDir}`,
});
}
@@ -1705,10 +1462,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
}
if (copiedArtifacts.length === 0) {
return yield* new DesktopBuildNoArtifactsProducedError({
distPath: stageDistDir,
platform: options.platform,
arch: options.arch,
return yield* new BuildScriptError({
message: `Build completed but no files were produced in ${stageDistDir}`,
});
}
+12 -136
View File
@@ -1,142 +1,18 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as HostProcess from "@t3tools/shared/hostProcess";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import { collectSources, runCommand } from "./mobile-native-static-check.ts";
import { NativeStaticCheckCommandError } from "./mobile-native-static-check.ts";
const processHandle = (
exitCode: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
) =>
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode,
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
it("describes failed native static-analysis commands structurally", () => {
const error = new NativeStaticCheckCommandError({
command: "swiftlint",
args: ["lint", "--strict"],
cwd: "/repo/apps/mobile",
exitCode: 2,
});
const provideSpawner = (spawn: ChildProcessSpawner.ChildProcessSpawner["Service"]["spawn"]) =>
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(spawn));
const runSwiftLint = runCommand("swiftlint", ["lint", "--strict"], "/repo/apps/mobile").pipe(
Effect.provideService(HostProcess.HostProcessPlatform, "linux"),
);
it.layer(NodeServices.layer)("mobile native source discovery", (it) => {
it.effect("preserves the failed discovery operation, path, and exact cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "mobile-native-static-check-" });
const missingDirectory = path.join(root, "missing");
const error = yield* collectSources(missingDirectory, root).pipe(Effect.flip);
assert.equal(error._tag, "NativeStaticCheckSourceDiscoveryError");
assert.equal(error.operation, "read-directory");
assert.equal(error.path, missingDirectory);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal(error.message, "Native source discovery operation 'read-directory' failed.");
}),
);
assert.equal(error.command, "swiftlint");
assert.deepStrictEqual(error.args, ["lint", "--strict"]);
assert.equal(error.cwd, "/repo/apps/mobile");
assert.equal(error.exitCode, 2);
assert.equal(error.message, "Native static check command 'swiftlint' exited with code 2.");
});
it.effect("preserves process spawn context and the exact cause", () => {
const cause = PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description: "swiftlint was not found",
});
return Effect.gen(function* () {
const error = yield* runSwiftLint.pipe(
Effect.provide(provideSpawner(() => Effect.fail(cause))),
Effect.flip,
);
if (error._tag !== "NativeStaticCheckProcessError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "spawn");
assert.equal(error.command, "swiftlint");
assert.equal(error.argumentCount, 2);
assert.equal(error.cwd, "/repo/apps/mobile");
assert.equal(error.shell, false);
assert.equal(error.cause, cause);
assert.equal(
error.message,
"Native static check process operation 'spawn' failed for command 'swiftlint'.",
);
assert.notProperty(error, "args");
});
});
it.effect("preserves process wait context and the exact cause", () => {
const cause = PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: "exitCode",
description: "status unavailable",
});
return Effect.gen(function* () {
const error = yield* runSwiftLint.pipe(
Effect.provide(provideSpawner(() => Effect.succeed(processHandle(Effect.fail(cause))))),
Effect.flip,
);
if (error._tag !== "NativeStaticCheckProcessError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "wait-for-exit");
assert.equal(error.command, "swiftlint");
assert.equal(error.argumentCount, 2);
assert.equal(error.cwd, "/repo/apps/mobile");
assert.equal(error.shell, false);
assert.equal(error.cause, cause);
assert.equal(
error.message,
"Native static check process operation 'wait-for-exit' failed for command 'swiftlint'.",
);
assert.notProperty(error, "args");
});
});
it.effect("reports non-zero exits without manufacturing a cause", () =>
Effect.gen(function* () {
const error = yield* runSwiftLint.pipe(
Effect.provide(
provideSpawner(() =>
Effect.succeed(processHandle(Effect.succeed(ChildProcessSpawner.ExitCode(2)))),
),
),
Effect.flip,
);
if (error._tag !== "NativeStaticCheckCommandError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.command, "swiftlint");
assert.equal(error.argumentCount, 2);
assert.equal(error.cwd, "/repo/apps/mobile");
assert.equal(error.shell, false);
assert.equal(error.exitCode, 2);
assert.notProperty(error, "cause");
assert.notProperty(error, "args");
}),
);
+18 -102
View File
@@ -8,6 +8,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Logger from "effect/Logger";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { Command } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -17,44 +18,12 @@ interface NativeStaticTool {
readonly installHint: string;
}
const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
export class NativeStaticCheckSourceDiscoveryError extends Schema.TaggedErrorClass<NativeStaticCheckSourceDiscoveryError>()(
"NativeStaticCheckSourceDiscoveryError",
{
operation: Schema.Literals(["resolve-root", "read-directory", "stat-entry"]),
path: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Native source discovery operation '${this.operation}' failed.`;
}
}
export class NativeStaticCheckProcessError extends Schema.TaggedErrorClass<NativeStaticCheckProcessError>()(
"NativeStaticCheckProcessError",
{
operation: Schema.Literals(["spawn", "wait-for-exit"]),
command: Schema.String,
argumentCount: NonNegativeInt,
cwd: Schema.String,
shell: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Native static check process operation '${this.operation}' failed for command '${this.command}'.`;
}
}
export class NativeStaticCheckCommandError extends Schema.TaggedErrorClass<NativeStaticCheckCommandError>()(
"NativeStaticCheckCommandError",
{
command: Schema.String,
argumentCount: NonNegativeInt,
args: Schema.Array(Schema.String),
cwd: Schema.String,
shell: Schema.Boolean,
exitCode: Schema.Int,
},
) {
@@ -90,17 +59,8 @@ const excludedDirectories = new Set([
]);
const generatedNativeProjectDirectories = new Set(["android", "ios"]);
const mobileAppRootUrl = new URL("../apps/mobile", import.meta.url);
const appRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(mobileAppRootUrl)),
Effect.mapError(
(cause) =>
new NativeStaticCheckSourceDiscoveryError({
operation: "resolve-root",
path: mobileAppRootUrl.pathname,
cause,
}),
),
Effect.flatMap((path) => path.fromFileUrl(new URL("../apps/mobile", import.meta.url))),
);
const commandOutputOptions = {
@@ -117,7 +77,7 @@ const warnMissingTool = (tool: NativeStaticTool, checkName: string) =>
`${tool.command} is not installed; skipping ${checkName}. Install it with '${tool.installHint}' or run 'brew bundle install --file apps/mobile/Brewfile'.`,
);
export const runCommand = Effect.fn("runCommand")(function* (
const runCommand = Effect.fn("runCommand")(function* (
command: string,
args: ReadonlyArray<string>,
cwd: string,
@@ -125,86 +85,42 @@ export const runCommand = Effect.fn("runCommand")(function* (
yield* Console.log(`$ ${[command, ...args].join(" ")}`);
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const spawnCommand = yield* resolveSpawnCommand(command, args);
const processContext = {
command,
argumentCount: spawnCommand.args.length,
cwd,
shell: spawnCommand.shell,
} as const;
const child = yield* spawner
.spawn(
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
cwd,
...commandOutputOptions,
shell: spawnCommand.shell,
}),
)
.pipe(
Effect.mapError(
(cause) =>
new NativeStaticCheckProcessError({
...processContext,
operation: "spawn",
cause,
}),
),
);
const exitCode = Number(
yield* child.exitCode.pipe(
Effect.mapError(
(cause) =>
new NativeStaticCheckProcessError({
...processContext,
operation: "wait-for-exit",
cause,
}),
),
),
const child = yield* spawner.spawn(
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
cwd,
...commandOutputOptions,
shell: spawnCommand.shell,
}),
);
const exitCode = Number(yield* child.exitCode);
if (exitCode !== 0) {
return yield* new NativeStaticCheckCommandError({
...processContext,
command,
args,
cwd,
exitCode,
});
}
});
export function collectSources(
function collectSources(
directory: string,
root: string,
): Effect.Effect<
ReadonlyArray<string>,
NativeStaticCheckSourceDiscoveryError,
PlatformError.PlatformError,
FileSystem.FileSystem | Path.Path
> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const entries = yield* fs.readDirectory(directory).pipe(
Effect.mapError(
(cause) =>
new NativeStaticCheckSourceDiscoveryError({
operation: "read-directory",
path: directory,
cause,
}),
),
);
const entries = yield* fs.readDirectory(directory);
const sources: Array<string> = [];
for (const entry of entries) {
const entryPath = path.join(directory, entry);
const stat = yield* fs.stat(entryPath).pipe(
Effect.mapError(
(cause) =>
new NativeStaticCheckSourceDiscoveryError({
operation: "stat-entry",
path: entryPath,
cause,
}),
),
);
const stat = yield* fs.stat(entryPath);
if (stat.type === "Directory") {
const isGeneratedNativeProjectDirectory =
-77
View File
@@ -1,18 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import {
readDesktopBaseVersion,
resolveNightlyBaseVersion,
resolveNightlyReleaseMetadata,
resolveNightlyTargetVersion,
writeNightlyReleaseOutput,
} from "./resolve-nightly-release.ts";
it("strips prerelease and build metadata when deriving the nightly base version", () => {
@@ -51,72 +43,3 @@ it("derives nightly metadata including the short commit sha in the release name"
},
);
});
it.effect("preserves the GITHUB_OUTPUT configuration cause", () => {
const metadata = resolveNightlyReleaseMetadata("1.2.4", "20260620", 42, "abcdef1234567890");
const configCause = new ConfigProvider.SourceError({ message: "environment unavailable" });
return Effect.gen(function* () {
const configError = yield* writeNightlyReleaseOutput(metadata, true).pipe(
Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.make(() => Effect.fail(configCause)),
),
Effect.flip,
);
if (configError._tag !== "NightlyReleaseGitHubOutputConfigError") {
return assert.fail(`Unexpected error: ${configError._tag}`);
}
assert.instanceOf(configError.cause, Config.ConfigError);
assert.strictEqual(configError.cause.cause, configCause);
assert.notInclude(configError.message, configCause.message);
});
});
it.layer(NodeServices.layer)("readDesktopBaseVersion", (it) => {
it.effect("preserves desktop package read context and its platform cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const rootDir = yield* fs.makeTempDirectoryScoped({
prefix: "resolve-nightly-release-read-",
});
const packageJsonPath = path.join(rootDir, "apps/desktop/package.json");
const error = yield* readDesktopBaseVersion(rootDir).pipe(Effect.flip);
if (error._tag !== "NightlyReleaseDesktopPackageError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "read");
assert.equal(error.packageJsonPath, packageJsonPath);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.notInclude(error.message, String((error.cause as Error).message));
}),
);
it.effect("preserves desktop package decode context and its schema cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const rootDir = yield* fs.makeTempDirectoryScoped({
prefix: "resolve-nightly-release-decode-",
});
const packageJsonPath = path.join(rootDir, "apps/desktop/package.json");
yield* fs.makeDirectory(path.dirname(packageJsonPath), { recursive: true });
yield* fs.writeFileString(packageJsonPath, "{");
const error = yield* readDesktopBaseVersion(rootDir).pipe(Effect.flip);
if (error._tag !== "NightlyReleaseDesktopPackageError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "decode");
assert.equal(error.packageJsonPath, packageJsonPath);
assert.ok(error.cause !== undefined);
assert.notInclude(error.message, String((error.cause as Error).message));
}),
);
});
+9 -77
View File
@@ -11,7 +11,7 @@ import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { Command, Flag } from "effect/unstable/cli";
export interface NightlyReleaseMetadata {
interface NightlyReleaseMetadata {
readonly baseVersion: string;
readonly version: string;
readonly tag: string;
@@ -40,42 +40,6 @@ export class InvalidDesktopPackageVersionError extends Schema.TaggedErrorClass<I
}
}
export class NightlyReleaseDesktopPackageError extends Schema.TaggedErrorClass<NightlyReleaseDesktopPackageError>()(
"NightlyReleaseDesktopPackageError",
{
operation: Schema.Literals(["read", "decode"]),
packageJsonPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} desktop package metadata at ${this.packageJsonPath}.`;
}
}
export class NightlyReleaseGitHubOutputConfigError extends Schema.TaggedErrorClass<NightlyReleaseGitHubOutputConfigError>()(
"NightlyReleaseGitHubOutputConfigError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to resolve the GITHUB_OUTPUT path for nightly release metadata.";
}
}
export class NightlyReleaseGitHubOutputAppendError extends Schema.TaggedErrorClass<NightlyReleaseGitHubOutputAppendError>()(
"NightlyReleaseGitHubOutputAppendError",
{
outputPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to append nightly release metadata to ${this.outputPath}.`;
}
}
const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
);
@@ -113,37 +77,20 @@ export const resolveNightlyReleaseMetadata = (
};
};
export const readDesktopBaseVersion = Effect.fn("readDesktopBaseVersion")(function* (
const readDesktopBaseVersion = Effect.fn("readDesktopBaseVersion")(function* (
rootDir: string | undefined,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspaceRoot = rootDir ? path.resolve(rootDir) : yield* RepoRoot;
const packageJsonPath = path.join(workspaceRoot, "apps/desktop/package.json");
const packageJsonSource = yield* fs.readFileString(packageJsonPath).pipe(
Effect.mapError(
(cause) =>
new NightlyReleaseDesktopPackageError({
operation: "read",
packageJsonPath,
cause,
}),
),
);
const packageJson = yield* decodeDesktopPackageJson(packageJsonSource).pipe(
Effect.mapError(
(cause) =>
new NightlyReleaseDesktopPackageError({
operation: "decode",
packageJsonPath,
cause,
}),
),
);
const packageJson = yield* fs
.readFileString(packageJsonPath)
.pipe(Effect.flatMap(decodeDesktopPackageJson));
return yield* resolveNightlyTargetVersion(packageJson.version);
});
export const writeNightlyReleaseOutput = Effect.fn("writeNightlyReleaseOutput")(function* (
const writeOutput = Effect.fn("writeOutput")(function* (
metadata: NightlyReleaseMetadata,
writeGithubOutput: boolean,
) {
@@ -158,24 +105,9 @@ export const writeNightlyReleaseOutput = Effect.fn("writeNightlyReleaseOutput")(
] as const;
if (writeGithubOutput) {
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT").pipe(
Effect.mapError(
(cause) =>
new NightlyReleaseGitHubOutputConfigError({
cause,
}),
),
);
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");
const serialized = entries.map(([key, value]) => `${key}=${value}\n`).join("");
yield* fs.writeFileString(githubOutputPath, serialized, { flag: "a" }).pipe(
Effect.mapError(
(cause) =>
new NightlyReleaseGitHubOutputAppendError({
outputPath: githubOutputPath,
cause,
}),
),
);
yield* fs.writeFileString(githubOutputPath, serialized, { flag: "a" });
} else {
for (const [key, value] of entries) {
yield* Console.log(`${key}=${value}`);
@@ -210,7 +142,7 @@ const command = Command.make(
({ date, runNumber, sha, githubOutput, root }) =>
readDesktopBaseVersion(Option.getOrUndefined(root)).pipe(
Effect.map((baseVersion) => resolveNightlyReleaseMetadata(baseVersion, date, runNumber, sha)),
Effect.flatMap((metadata) => writeNightlyReleaseOutput(metadata, githubOutput)),
Effect.flatMap((metadata) => writeOutput(metadata, githubOutput)),
),
).pipe(Command.withDescription("Resolve nightly release version metadata."));
+1 -175
View File
@@ -1,45 +1,7 @@
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
listGitTags,
resolvePreviousReleaseTag,
writePreviousReleaseTagOutput,
} from "./resolve-previous-release-tag.ts";
const encoder = new TextEncoder();
function mockHandle(options: {
readonly exitCode: number;
readonly stdout?: string;
readonly stderr?: string;
readonly stdoutError?: PlatformError.PlatformError;
readonly stderrError?: PlatformError.PlatformError;
}) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(options.exitCode)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: options.stdoutError
? Stream.fail(options.stdoutError)
: Stream.make(encoder.encode(options.stdout ?? "")),
stderr: options.stderrError
? Stream.fail(options.stderrError)
: Stream.make(encoder.encode(options.stderr ?? "")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
import { resolvePreviousReleaseTag } from "./resolve-previous-release-tag.ts";
it.effect("selects the latest earlier stable tag and ignores nightlies", () =>
Effect.gen(function* () {
@@ -75,139 +37,3 @@ it.effect("reports the invalid tag with its release channel", () =>
assert.equal(error.message, "Invalid nightly release tag 'v1.2.0'.");
}),
);
it.effect("preserves git tag spawn context and the exact platform cause", () => {
const cause = PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description: "git was not found",
});
return Effect.gen(function* () {
const error = yield* listGitTags("/repo").pipe(
Effect.scoped,
Effect.provideService(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.fail(cause)),
),
Effect.flip,
);
if (error._tag !== "ReleaseTagListProcessError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "spawn");
assert.equal(error.executable, "git");
assert.equal(error.argumentCount, 2);
assert.equal(error.cwd, "/repo");
assert.strictEqual(error.cause, cause);
assert.notProperty(error, "args");
assert.notInclude(error.message, cause.message);
});
});
it.effect("distinguishes stdout and stderr read failures", () =>
Effect.gen(function* () {
for (const [stream, operation] of [
["stdout", "read-stdout"],
["stderr", "read-stderr"],
] as const) {
const cause = PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: stream,
description: `${stream} unavailable`,
});
const error = yield* listGitTags("/repo").pipe(
Effect.scoped,
Effect.provideService(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
exitCode: 0,
...(stream === "stdout" ? { stdoutError: cause } : { stderrError: cause }),
}),
),
),
),
Effect.flip,
);
if (error._tag !== "ReleaseTagListProcessError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, operation);
assert.strictEqual(error.cause, cause);
}
}),
);
it.effect("reports git tag non-zero exits without manufacturing a cause", () =>
Effect.gen(function* () {
const error = yield* listGitTags("/repo").pipe(
Effect.scoped,
Effect.provideService(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
exitCode: 17,
stdout: "v1.2.3\n",
stderr: "fatal: repository unavailable\n",
}),
),
),
),
Effect.flip,
);
if (error._tag !== "ReleaseTagListProcessExitError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.executable, "git");
assert.equal(error.argumentCount, 2);
assert.equal(error.cwd, "/repo");
assert.equal(error.exitCode, 17);
assert.equal(error.stdoutLength, 7);
assert.equal(error.stderrLength, 30);
assert.notProperty(error, "cause");
assert.notProperty(error, "stdout");
assert.notProperty(error, "stderr");
}),
);
it.effect("preserves the GITHUB_OUTPUT append path and exact cause", () => {
const outputPath = "/tmp/previous-tag-github-output";
const appendCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFileString",
pathOrDescriptor: outputPath,
});
return Effect.gen(function* () {
const appendError = yield* writePreviousReleaseTagOutput("v1.2.3", true).pipe(
Effect.provideService(
FileSystem.FileSystem,
FileSystem.makeNoop({
writeFileString: () => Effect.fail(appendCause),
}),
),
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.fromEnv({ env: { GITHUB_OUTPUT: outputPath } }),
),
Effect.flip,
);
if (appendError._tag !== "PreviousReleaseTagGitHubOutputAppendError") {
return assert.fail(`Unexpected error: ${appendError._tag}`);
}
assert.equal(appendError.outputPath, outputPath);
assert.strictEqual(appendError.cause, appendCause);
assert.notProperty(appendError, "contents");
assert.notInclude(appendError.message, appendCause.message);
});
});
+13 -145
View File
@@ -2,6 +2,7 @@
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Array from "effect/Array";
import * as Config from "effect/Config";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -26,64 +27,6 @@ export class InvalidReleaseTagError extends Schema.TaggedErrorClass<InvalidRelea
}
}
const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
const releaseTagListProcessContext = {
executable: Schema.Literal("git"),
argumentCount: NonNegativeInt,
cwd: Schema.String,
};
export class ReleaseTagListProcessError extends Schema.TaggedErrorClass<ReleaseTagListProcessError>()(
"ReleaseTagListProcessError",
{
...releaseTagListProcessContext,
operation: Schema.Literals(["spawn", "read-stdout", "read-stderr", "wait-for-exit"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to list release tags during process operation "${this.operation}".`;
}
}
export class ReleaseTagListProcessExitError extends Schema.TaggedErrorClass<ReleaseTagListProcessExitError>()(
"ReleaseTagListProcessExitError",
{
...releaseTagListProcessContext,
exitCode: Schema.Number,
stdoutLength: NonNegativeInt,
stderrLength: NonNegativeInt,
},
) {
override get message(): string {
return `Release tag listing exited with code ${this.exitCode}.`;
}
}
export class PreviousReleaseTagGitHubOutputConfigError extends Schema.TaggedErrorClass<PreviousReleaseTagGitHubOutputConfigError>()(
"PreviousReleaseTagGitHubOutputConfigError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to resolve the GITHUB_OUTPUT path for the previous release tag.";
}
}
export class PreviousReleaseTagGitHubOutputAppendError extends Schema.TaggedErrorClass<PreviousReleaseTagGitHubOutputAppendError>()(
"PreviousReleaseTagGitHubOutputAppendError",
{
outputPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to append the previous release tag to ${this.outputPath}.`;
}
}
interface StableVersion {
readonly major: number;
readonly minor: number;
@@ -229,83 +172,23 @@ export const resolvePreviousReleaseTag = (
return candidates[0]?.tag;
});
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(
const listGitTags = Effect.fn("listGitTags")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(ChildProcess.make("git", ["tag", "--list"]));
const tags = yield* child.stdout.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
Effect.map(String.split(/\r?\n/)),
Effect.map(Array.map(String.trim)),
Effect.map(Array.filter(String.isNonEmpty)),
);
export const listGitTags = Effect.fn("listGitTags")(function* (cwd = process.cwd()) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const args = ["tag", "--list"] as const;
const context = {
executable: "git",
argumentCount: args.length,
cwd,
} as const;
const child = yield* spawner.spawn(ChildProcess.make("git", args, { cwd })).pipe(
Effect.mapError(
(cause) =>
new ReleaseTagListProcessError({
...context,
operation: "spawn",
cause,
}),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout).pipe(
Effect.mapError(
(cause) =>
new ReleaseTagListProcessError({
...context,
operation: "read-stdout",
cause,
}),
),
),
collectStreamAsString(child.stderr).pipe(
Effect.mapError(
(cause) =>
new ReleaseTagListProcessError({
...context,
operation: "read-stderr",
cause,
}),
),
),
child.exitCode.pipe(
Effect.map(Number),
Effect.mapError(
(cause) =>
new ReleaseTagListProcessError({
...context,
operation: "wait-for-exit",
cause,
}),
),
),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
return yield* new ReleaseTagListProcessExitError({
...context,
exitCode,
stdoutLength: stdout.length,
stderrLength: stderr.length,
});
}
return stdout.split(/\r?\n/).map(String.trim).filter(String.isNonEmpty);
return tags;
});
export const writePreviousReleaseTagOutput = Effect.fn("writePreviousReleaseTagOutput")(function* (
const writeOutput = Effect.fn("writeOutput")(function* (
previousTag: string | undefined,
writeGithubOutput: boolean,
) {
@@ -313,23 +196,8 @@ export const writePreviousReleaseTagOutput = Effect.fn("writePreviousReleaseTagO
if (writeGithubOutput) {
const fs = yield* FileSystem.FileSystem;
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT").pipe(
Effect.mapError(
(cause) =>
new PreviousReleaseTagGitHubOutputConfigError({
cause,
}),
),
);
yield* fs.writeFileString(githubOutputPath, entry, { flag: "a" }).pipe(
Effect.mapError(
(cause) =>
new PreviousReleaseTagGitHubOutputAppendError({
outputPath: githubOutputPath,
cause,
}),
),
);
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");
yield* fs.writeFileString(githubOutputPath, entry, { flag: "a" });
return;
}
@@ -353,7 +221,7 @@ const command = Command.make(
({ channel, currentTag, githubOutput }) =>
listGitTags().pipe(
Effect.flatMap((tags) => resolvePreviousReleaseTag(channel, currentTag, tags)),
Effect.flatMap((previousTag) => writePreviousReleaseTagOutput(previousTag, githubOutput)),
Effect.flatMap((previousTag) => writeOutput(previousTag, githubOutput)),
),
).pipe(Command.withDescription("Resolve the previous release tag for a stable or nightly series."));
+1 -107
View File
@@ -1,21 +1,16 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { Command, CliError } from "effect/unstable/cli";
import * as TestConsole from "effect/testing/TestConsole";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import {
ReleaseGitHubOutputConfigurationError,
ReleaseGitHubOutputWriteError,
ReleasePackageManifestError,
releasePackageFiles,
updateReleasePackageVersions,
updateReleasePackageVersionsCommand,
@@ -108,73 +103,6 @@ it.layer(ScriptTestLayer)("update-release-package-versions", (it) => {
}),
);
it.effect("preserves manifest read context and the filesystem cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-read-error-",
});
const filePath = path.join(baseDir, releasePackageFiles[0]);
const error = yield* updateReleasePackageVersions("1.2.3", {
rootDir: baseDir,
}).pipe(Effect.flip);
assert.instanceOf(error, ReleasePackageManifestError);
assert.equal(error.operation, "read");
assert.equal(error.filePath, filePath);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal(error.message, `Failed to read release package manifest '${filePath}'.`);
}),
);
it.effect("preserves manifest decode context and the schema cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-decode-error-",
});
const filePath = path.join(baseDir, releasePackageFiles[0]);
yield* writePackageJsonFixtures(baseDir, "0.0.1");
yield* fs.writeFileString(filePath, "not json");
const error = yield* updateReleasePackageVersions("1.2.3", {
rootDir: baseDir,
}).pipe(Effect.flip);
assert.equal(error.operation, "decode");
assert.equal(error.filePath, filePath);
assert.isTrue(Schema.isSchemaError(error.cause));
assert.equal(error.message, `Failed to decode release package manifest '${filePath}'.`);
}),
);
it.effect("preserves manifest write context and the filesystem cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-write-error-",
});
const filePath = path.join(baseDir, releasePackageFiles[0]);
yield* writePackageJsonFixtures(baseDir, "0.0.1");
yield* fs.chmod(filePath, 0o400);
const error = yield* updateReleasePackageVersions("1.2.3", {
rootDir: baseDir,
}).pipe(Effect.flip, Effect.ensuring(fs.chmod(filePath, 0o600).pipe(Effect.orDie)));
assert.equal(error.operation, "write");
assert.equal(error.filePath, filePath);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal(error.message, `Failed to write release package manifest '${filePath}'.`);
}),
);
it.effect("accepts flags before the version positional and appends changed output", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -236,43 +164,9 @@ it.layer(ScriptTestLayer)("update-release-package-versions", (it) => {
Effect.flip,
);
assert.instanceOf(error, ReleaseGitHubOutputConfigurationError);
assert.instanceOf(error.cause, Config.ConfigError);
assert.equal(
error.message,
"Failed to resolve GITHUB_OUTPUT for release package version output.",
);
}),
);
it.effect("preserves GITHUB_OUTPUT write context and the filesystem cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-cli-output-error-",
});
yield* writePackageJsonFixtures(baseDir, "0.0.1");
const error = yield* runCli(["4.0.0", "--root", baseDir, "--github-output"]).pipe(
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
GITHUB_OUTPUT: baseDir,
},
}),
),
),
Effect.flip,
);
assert.instanceOf(error, ReleaseGitHubOutputWriteError);
assert.equal(error.filePath, baseDir);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal(
error.message,
`Failed to append release package version output to '${baseDir}'.`,
'SchemaError(Expected string, got undefined\n at ["GITHUB_OUTPUT"])',
);
}),
);
+5 -91
View File
@@ -12,40 +12,6 @@ import * as Schema from "effect/Schema";
import { Argument, Command, Flag } from "effect/unstable/cli";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
export class ReleasePackageManifestError extends Schema.TaggedErrorClass<ReleasePackageManifestError>()(
"ReleasePackageManifestError",
{
operation: Schema.Literals(["read", "decode", "encode", "write"]),
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} release package manifest '${this.filePath}'.`;
}
}
export class ReleaseGitHubOutputConfigurationError extends Schema.TaggedErrorClass<ReleaseGitHubOutputConfigurationError>()(
"ReleaseGitHubOutputConfigurationError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to resolve GITHUB_OUTPUT for release package version output.";
}
}
export class ReleaseGitHubOutputWriteError extends Schema.TaggedErrorClass<ReleaseGitHubOutputWriteError>()(
"ReleaseGitHubOutputWriteError",
{
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to append release package version output to '${this.filePath}'.`;
}
}
export const releasePackageFiles = [
"apps/server/package.json",
"apps/desktop/package.json",
@@ -73,50 +39,13 @@ export const updateReleasePackageVersions = Effect.fn("updateReleasePackageVersi
for (const relativePath of releasePackageFiles) {
const filePath = path.join(rootDir, relativePath);
const packageJsonText = yield* fs.readFileString(filePath).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "read",
filePath,
cause,
}),
),
);
const packageJson = yield* decodePackageJson(packageJsonText).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "decode",
filePath,
cause,
}),
),
);
const packageJson = yield* fs.readFileString(filePath).pipe(Effect.flatMap(decodePackageJson));
if (packageJson.version === version) {
continue;
}
const packageJsonString = yield* encodePackageJson({ ...packageJson, version }).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "encode",
filePath,
cause,
}),
),
);
yield* fs.writeFileString(filePath, `${packageJsonString}\n`).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "write",
filePath,
cause,
}),
),
);
const packageJsonString = yield* encodePackageJson({ ...packageJson, version });
yield* fs.writeFileString(filePath, `${packageJsonString}\n`);
changed = true;
}
@@ -125,23 +54,8 @@ export const updateReleasePackageVersions = Effect.fn("updateReleasePackageVersi
const writeGithubOutput = Effect.fn("writeGithubOutput")(function* (changed: boolean) {
const fs = yield* FileSystem.FileSystem;
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT").pipe(
Effect.mapError(
(cause) =>
new ReleaseGitHubOutputConfigurationError({
cause,
}),
),
);
yield* fs.writeFileString(githubOutputPath, `changed=${changed}\n`, { flag: "a" }).pipe(
Effect.mapError(
(cause) =>
new ReleaseGitHubOutputWriteError({
filePath: githubOutputPath,
cause,
}),
),
);
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");
yield* fs.writeFileString(githubOutputPath, `changed=${changed}\n`, { flag: "a" });
});
export const updateReleasePackageVersionsCommand = Command.make(