Adopt Node-native TypeScript for desktop and server (#2098)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-04-16 22:14:35 -07:00
1 parent ed6b7fbf27
commit 8dba2d6484
140 files changed
+2149 -1604

No files matched your search

+83 -28
View File
@@ -1,9 +1,5 @@
#!/usr/bin/env node
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { join } from "node:path";
import rootPackageJson from "../package.json" with { type: "json" };
import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };
import serverPackageJson from "../apps/server/package.json" with { type: "json" };
@@ -14,7 +10,18 @@ import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Config, Data, Effect, FileSystem, Layer, Logger, Option, Path, Schema } from "effect";
import {
Config,
Data,
Effect,
FileSystem,
Layer,
Logger,
Option,
Path,
Schema,
Stream,
} from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -91,12 +98,49 @@ class BuildScriptError extends Data.TaggedError("BuildScriptError")<{
readonly cause?: unknown;
}> {}
function resolveGitCommitHash(repoRoot: string): string {
const result = spawnSync("git", ["rev-parse", "--short=12", "HEAD"], {
cwd: repoRoot,
encoding: "utf8",
});
if (result.status !== 0) {
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
);
const spawnAndCollectOutput = Effect.fn("spawnAndCollectOutput")(function* (
command: ChildProcess.Command,
) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { stdout, stderr, exitCode } as const;
});
const resolveGitCommitHash = Effect.fn("resolveGitCommitHash")(function* (repoRoot: string) {
const result = yield* spawnAndCollectOutput(
ChildProcess.make("git", ["rev-parse", "--short=12", "HEAD"], {
cwd: repoRoot,
}),
).pipe(
Effect.catch(() =>
Effect.succeed({
stdout: "",
stderr: "",
exitCode: 1,
}),
),
);
if (result.exitCode !== 0) {
return "unknown";
}
const hash = result.stdout.trim();
@@ -104,11 +148,13 @@ function resolveGitCommitHash(repoRoot: string): string {
return "unknown";
}
return hash.toLowerCase();
}
});
function resolvePythonForNodeGyp(): string | undefined {
const resolvePythonForNodeGyp = Effect.fn("resolvePythonForNodeGyp")(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const configured = process.env.npm_config_python ?? process.env.PYTHON;
if (configured && existsSync(configured)) {
if (configured && (yield* fs.exists(configured))) {
return configured;
}
@@ -116,28 +162,37 @@ function resolvePythonForNodeGyp(): string | undefined {
const localAppData = process.env.LOCALAPPDATA;
if (localAppData) {
for (const version of ["Python313", "Python312", "Python311", "Python310"]) {
const candidate = join(localAppData, "Programs", "Python", version, "python.exe");
if (existsSync(candidate)) {
const candidate = path.join(localAppData, "Programs", "Python", version, "python.exe");
if (yield* fs.exists(candidate)) {
return candidate;
}
}
}
}
const probe = spawnSync("python", ["-c", "import sys;print(sys.executable)"], {
encoding: "utf8",
});
if (probe.status !== 0) {
const probe = yield* spawnAndCollectOutput(
ChildProcess.make("python", ["-c", "import sys;print(sys.executable)"]),
).pipe(
Effect.catch(() =>
Effect.succeed({
stdout: "",
stderr: "",
exitCode: 1,
}),
),
);
if (probe.exitCode !== 0) {
return undefined;
}
const executable = probe.stdout.trim();
if (!executable || !existsSync(executable)) {
if (!executable || !(yield* fs.exists(executable))) {
return undefined;
}
return executable;
}
});
interface ResolvedBuildOptions {
readonly platform: typeof BuildPlatform.Type;
@@ -654,7 +709,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const appVersion = options.version ?? serverPackageJson.version;
const iconAssets = resolveDesktopBuildIconAssets(appVersion);
const commitHash = resolveGitCommitHash(repoRoot);
const commitHash = yield* resolveGitCommitHash(repoRoot);
const mkdir = options.keepStage ? fs.makeTempDirectory : fs.makeTempDirectoryScoped;
const stageRoot = yield* mkdir({
prefix: `t3code-desktop-${options.platform}-stage-`,
@@ -709,9 +764,9 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
options.platform,
stageResourcesDir,
{
macIconPng: join(repoRoot, iconAssets.macIconPng),
linuxIconPng: join(repoRoot, iconAssets.linuxIconPng),
windowsIconIco: join(repoRoot, iconAssets.windowsIconIco),
macIconPng: path.join(repoRoot, iconAssets.macIconPng),
linuxIconPng: path.join(repoRoot, iconAssets.linuxIconPng),
windowsIconIco: path.join(repoRoot, iconAssets.windowsIconIco),
},
options.verbose,
);
@@ -727,7 +782,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
private: true,
description: "T3 Code desktop build",
author: "T3 Tools",
main: "apps/desktop/dist-electron/main.js",
main: "apps/desktop/dist-electron/main.cjs",
build: yield* createBuildConfig(
options.platform,
options.target,
@@ -777,7 +832,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
}
if (process.platform === "win32") {
const python = resolvePythonForNodeGyp();
const python = yield* resolvePythonForNodeGyp();
if (python) {
buildEnv.PYTHON = python;
buildEnv.npm_config_python = python;
+10 -7
View File
@@ -1,8 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { homedir } from "node:os";
import { resolve } from "node:path";
import * as NodeOS from "node:os";
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import { Effect, Path } from "effect";
import {
checkPortAvailabilityOnHosts,
@@ -49,6 +48,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
describe("createDevRunnerEnv", () => {
it.effect("defaults T3CODE_HOME to ~/.t3 when not provided", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const env = yield* createDevRunnerEnv({
mode: "dev",
baseEnv: {},
@@ -63,12 +63,13 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
devUrl: undefined,
});
assert.equal(env.T3CODE_HOME, resolve(homedir(), ".t3"));
assert.equal(env.T3CODE_HOME, path.resolve(NodeOS.homedir(), ".t3"));
}),
);
it.effect("supports explicit typed overrides", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const env = yield* createDevRunnerEnv({
mode: "dev:server",
baseEnv: {},
@@ -83,7 +84,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
devUrl: new URL("http://localhost:7331"),
});
assert.equal(env.T3CODE_HOME, resolve("/tmp/custom-t3"));
assert.equal(env.T3CODE_HOME, path.resolve("/tmp/custom-t3"));
assert.equal(env.T3CODE_PORT, "4222");
assert.equal(env.VITE_HTTP_URL, "http://localhost:4222");
assert.equal(env.VITE_WS_URL, "ws://localhost:4222");
@@ -142,6 +143,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
it.effect("uses custom t3Home when provided", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const env = yield* createDevRunnerEnv({
mode: "dev",
baseEnv: {},
@@ -156,12 +158,13 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
devUrl: undefined,
});
assert.equal(env.T3CODE_HOME, resolve("/tmp/my-t3"));
assert.equal(env.T3CODE_HOME, path.resolve("/tmp/my-t3"));
}),
);
it.effect("pins desktop dev to a stable backend port and websocket url", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const env = yield* createDevRunnerEnv({
mode: "dev:desktop",
baseEnv: {
@@ -182,7 +185,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
devUrl: undefined,
});
assert.equal(env.T3CODE_HOME, resolve("/tmp/my-t3"));
assert.equal(env.T3CODE_HOME, path.resolve("/tmp/my-t3"));
assert.equal(env.PORT, "5733");
assert.equal(env.VITE_DEV_SERVER_URL, "http://127.0.0.1:5733");
assert.equal(env.HOST, "127.0.0.1");
+7 -8
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env node
import { homedir } from "node:os";
import * as NodeOS from "node:os";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -17,7 +17,7 @@ const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::1", "::"] as const;
export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
path.join(homedir(), ".t3"),
path.join(NodeOS.homedir(), ".t3"),
);
const MODE_ARGS = {
@@ -523,11 +523,10 @@ const cliRuntimeLayer = Layer.mergeAll(
NetService.layer,
);
const runtimeProgram = Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide(cliRuntimeLayer),
);
if (import.meta.main) {
NodeRuntime.runMain(runtimeProgram);
Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide(cliRuntimeLayer),
NodeRuntime.runMain,
);
}
+116
View File
@@ -1,11 +1,17 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { Effect, FileSystem, Path } from "effect";
import { Command, CliError } from "effect/unstable/cli";
import {
mergePlatformUpdateManifests,
mergeUpdateManifestsCommand,
parsePlatformUpdateManifest,
serializePlatformUpdateManifest,
} from "./merge-update-manifests.ts";
const runCli = Command.runWith(mergeUpdateManifestsCommand, { version: "0.0.0" });
describe("merge-update-manifests", () => {
it("merges arm64 and x64 macOS update manifests into one multi-arch manifest", () => {
const arm64 = parsePlatformUpdateManifest(
@@ -188,3 +194,113 @@ releaseDate: '2026-03-07T10:36:07.540Z'
assert.equal(reparsed.version, "1.0");
});
});
it.layer(NodeServices.layer)("merge-update-manifests cli", (it) => {
const arm64MacManifest = `version: 0.0.4
files:
- url: T3-Code-0.0.4-arm64.zip
sha512: arm64zip
size: 125621344
- url: T3-Code-0.0.4-arm64.dmg
sha512: arm64dmg
size: 131754935
path: T3-Code-0.0.4-arm64.zip
sha512: arm64zip
releaseDate: '2026-03-07T10:32:14.587Z'
`;
const x64MacManifest = `version: 0.0.4
files:
- url: T3-Code-0.0.4-x64.zip
sha512: x64zip
size: 132000112
- url: T3-Code-0.0.4-x64.dmg
sha512: x64dmg
size: 138148807
path: T3-Code-0.0.4-x64.zip
sha512: x64zip
releaseDate: '2026-03-07T10:36:07.540Z'
`;
it.effect("writes the merged manifest back to the primary path by default", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "merge-update-manifests-cli-",
});
const primaryPath = path.join(baseDir, "latest-mac.yml");
const secondaryPath = path.join(baseDir, "latest-mac-x64.yml");
yield* fs.writeFileString(primaryPath, arm64MacManifest);
yield* fs.writeFileString(secondaryPath, x64MacManifest);
yield* runCli(["--platform", "mac", primaryPath, secondaryPath]);
const merged = yield* fs.readFileString(primaryPath);
assert.ok(merged.includes("T3-Code-0.0.4-arm64.zip"));
assert.ok(merged.includes("T3-Code-0.0.4-x64.zip"));
assert.ok(!merged.includes("path:"));
}),
);
it.effect("writes the merged manifest to an explicit output path", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "merge-update-manifests-cli-output-",
});
const primaryPath = path.join(baseDir, "latest-win-arm64.yml");
const secondaryPath = path.join(baseDir, "latest-win-x64.yml");
const outputPath = path.join(baseDir, "latest-win.yml");
yield* fs.writeFileString(
primaryPath,
`version: 0.0.4
files:
- url: T3-Code-0.0.4-arm64.exe
sha512: arm64exe
size: 125621344
releaseDate: '2026-03-07T10:32:14.587Z'
`,
);
yield* fs.writeFileString(
secondaryPath,
`version: 0.0.4
files:
- url: T3-Code-0.0.4-x64.exe
sha512: x64exe
size: 132000112
releaseDate: '2026-03-07T10:36:07.540Z'
`,
);
yield* runCli(["--platform", "win", primaryPath, secondaryPath, outputPath]);
const merged = yield* fs.readFileString(outputPath);
assert.ok(merged.includes("T3-Code-0.0.4-arm64.exe"));
assert.ok(merged.includes("T3-Code-0.0.4-x64.exe"));
}),
);
it.effect("rejects invalid platform values during cli parsing", () =>
Effect.gen(function* () {
const error = yield* runCli(["--platform", "linux", "a.yml", "b.yml"]).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
}
const platformError =
error._tag === "ShowHelp" ? (error.errors[0] as CliError.CliError | undefined) : error;
if (!platformError || platformError._tag !== "InvalidValue") {
assert.fail(`Expected InvalidValue, got ${String(platformError?._tag)}`);
}
assert.equal(platformError.option, "platform");
assert.equal(platformError.value, "linux");
}),
);
});
+57 -40
View File
@@ -1,6 +1,9 @@
import { readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, FileSystem, Option, Path, Schema } from "effect";
import { Argument, Command, Flag } from "effect/unstable/cli";
import {
mergeUpdateManifests,
@@ -9,7 +12,8 @@ import {
type UpdateManifest,
} from "./lib/update-manifest.ts";
export type UpdateManifestPlatform = "mac" | "win";
const UpdateManifestPlatform = Schema.Literals(["mac", "win"]);
export type UpdateManifestPlatform = typeof UpdateManifestPlatform.Type;
function getPlatformLabel(platform: UpdateManifestPlatform): string {
return platform === "mac" ? "macOS" : "Windows";
@@ -40,52 +44,65 @@ export function serializePlatformUpdateManifest(
});
}
function parseArgs(args: ReadonlyArray<string>): {
platform: UpdateManifestPlatform;
primaryPath: string;
secondaryPath: string;
outputPath: string;
} {
const [platformFlag, platformValue, primaryPathArg, secondaryPathArg, outputPathArg] = args;
if (platformFlag !== "--platform" || (platformValue !== "mac" && platformValue !== "win")) {
throw new Error(
"Usage: node scripts/merge-update-manifests.ts --platform <mac|win> <primary-path> <secondary-path> [output-path]",
);
}
if (!primaryPathArg || !secondaryPathArg) {
throw new Error(
"Usage: node scripts/merge-update-manifests.ts --platform <mac|win> <primary-path> <secondary-path> [output-path]",
);
}
export const mergeUpdateManifestFiles = Effect.fn("mergeUpdateManifestFiles")(function* (
platform: UpdateManifestPlatform,
primaryPathArg: string,
secondaryPathArg: string,
outputPathArg: string | undefined,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const primaryPath = resolve(primaryPathArg);
const secondaryPath = resolve(secondaryPathArg);
const outputPath = resolve(outputPathArg ?? primaryPathArg);
const primaryPath = path.resolve(primaryPathArg);
const secondaryPath = path.resolve(secondaryPathArg);
const outputPath = path.resolve(outputPathArg ?? primaryPathArg);
return {
platform: platformValue,
primaryPath,
secondaryPath,
outputPath,
};
}
function main(args: ReadonlyArray<string>): void {
const { platform, primaryPath, secondaryPath, outputPath } = parseArgs(args);
const primaryManifest = parsePlatformUpdateManifest(
platform,
readFileSync(primaryPath, "utf8"),
yield* fs.readFileString(primaryPath),
primaryPath,
);
const secondaryManifest = parsePlatformUpdateManifest(
platform,
readFileSync(secondaryPath, "utf8"),
yield* fs.readFileString(secondaryPath),
secondaryPath,
);
const merged = mergePlatformUpdateManifests(platform, primaryManifest, secondaryManifest);
writeFileSync(outputPath, serializePlatformUpdateManifest(platform, merged));
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main(process.argv.slice(2));
yield* fs.writeFileString(outputPath, serializePlatformUpdateManifest(platform, merged));
});
export const mergeUpdateManifestsCommand = Command.make(
"merge-update-manifests",
{
platform: Flag.choice("platform", UpdateManifestPlatform.literals).pipe(
Flag.withDescription("Update manifest platform."),
),
primaryPath: Argument.string("primary-path").pipe(
Argument.withDescription("Primary update manifest path. Defaults to the output path."),
),
secondaryPath: Argument.string("secondary-path").pipe(
Argument.withDescription(
"Secondary update manifest path to merge into the primary manifest.",
),
),
outputPath: Argument.string("output-path").pipe(
Argument.withDescription("Optional output path for the merged manifest."),
Argument.optional,
),
},
({ platform, primaryPath, secondaryPath, outputPath }) =>
mergeUpdateManifestFiles(
platform,
primaryPath,
secondaryPath,
Option.getOrUndefined(outputPath),
),
).pipe(Command.withDescription("Merge two Electron updater manifests into a multi-arch manifest."));
if (import.meta.main) {
Command.run(mergeUpdateManifestsCommand, { version: "0.0.0" }).pipe(
Effect.provide(NodeServices.layer),
NodeRuntime.runMain,
);
}
+104
View File
@@ -0,0 +1,104 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeHttpServer } from "@effect/platform-node";
import { assert, it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { HttpClient, HttpRouter } from "effect/unstable/http";
import { makeMockUpdateRouteLayer } from "./mock-update-server.ts";
const withMockUpdateServer = <A, E, R>(rootRealPath: string, effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.provide(
HttpRouter.serve(makeMockUpdateRouteLayer(rootRealPath), {
disableListenLog: true,
disableLogger: true,
}).pipe(Layer.provideMerge(NodeHttpServer.layerTest)),
),
);
it.layer(NodeServices.layer)("mock-update-server", (it) => {
it.effect("serves files from the configured root", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "mock-update-server-root-",
});
const rootRealPath = yield* fileSystem.realPath(root);
const filePath = path.join(root, "latest.yml");
yield* fileSystem.writeFileString(filePath, "version: 0.0.1\n");
yield* withMockUpdateServer(
rootRealPath,
Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const response = yield* client.get("/latest.yml");
assert.equal(response.status, 200);
assert.equal(response.headers["content-type"], "text/yaml");
assert.equal(yield* response.text, "version: 0.0.1\n");
}),
);
}),
);
it.effect("rejects encoded path traversal outside the configured root", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "mock-update-server-root-",
});
const outside = yield* fileSystem.makeTempDirectoryScoped({
prefix: "mock-update-server-outside-",
});
const rootRealPath = yield* fileSystem.realPath(root);
yield* fileSystem.writeFileString(path.join(outside, "secret.txt"), "nope\n");
yield* withMockUpdateServer(
rootRealPath,
Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const response = yield* client.get("/%2e%2e/secret.txt");
assert.equal(response.status, 404);
assert.equal(yield* response.text, "Not Found");
}),
);
}),
);
it.effect("rejects symlinked files that escape the configured root", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "mock-update-server-root-",
});
const outside = yield* fileSystem.makeTempDirectoryScoped({
prefix: "mock-update-server-outside-",
});
const rootRealPath = yield* fileSystem.realPath(root);
const outsideFile = path.join(outside, "outside.yml");
const linksDir = path.join(root, "links");
const symlinkPath = path.join(linksDir, "outside.yml");
yield* fileSystem.writeFileString(outsideFile, "version: outside\n");
yield* fileSystem.makeDirectory(linksDir, { recursive: true });
yield* fileSystem.symlink(outsideFile, symlinkPath);
yield* withMockUpdateServer(
rootRealPath,
Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const response = yield* client.get("/links/outside.yml");
assert.equal(response.status, 404);
assert.equal(yield* response.text, "Not Found");
}),
);
}),
);
});
+148 -38
View File
@@ -1,44 +1,154 @@
import { resolve, relative } from "node:path";
import { realpathSync } from "node:fs";
import * as NodeHttp from "node:http";
const port = Number(process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000);
const root =
process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_ROOT ??
resolve(import.meta.dirname, "..", "release-mock");
import { NodeHttpServer, NodeRuntime } from "@effect/platform-node";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Config, Effect, FileSystem, Layer, Path } from "effect";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
const mockServerLog = (level: "info" | "warn" | "error" = "info", message: string) => {
console[level](`[mock-update-server] ${message}`);
};
function isWithinRoot(filePath: string): boolean {
try {
return !relative(realpathSync(root), realpathSync(filePath)).startsWith(".");
} catch (error) {
mockServerLog("error", `Error checking if file is within root: ${error}`);
return false;
}
interface MockUpdateServerConfig {
readonly port: number;
readonly rootRealPath: string;
}
Bun.serve({
port,
hostname: "localhost",
fetch: async (request) => {
const url = new URL(request.url);
const path = url.pathname;
mockServerLog("info", `Request received for path: ${path}`);
const filePath = resolve(root, `.${path}`);
if (!isWithinRoot(filePath)) {
mockServerLog("warn", `Attempted to access file outside of root: ${filePath}`);
return new Response("Not Found", { status: 404 });
}
const file = Bun.file(filePath);
if (!(await file.exists())) {
mockServerLog("warn", `Attempted to access non-existent file: ${filePath}`);
return new Response("Not Found", { status: 404 });
}
mockServerLog("info", `Serving file: ${filePath}`);
return new Response(file.stream());
},
const resolveMockUpdateServerConfig = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* Config.all({
port: Config.port("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT").pipe(Config.withDefault(3000)),
root: Config.string("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_ROOT").pipe(
Config.withDefault("../release-mock"),
),
}).asEffect();
const resolvedRoot = path.resolve(import.meta.dirname, config.root);
return {
port: config.port,
rootRealPath: yield* fileSystem.realPath(resolvedRoot),
} satisfies MockUpdateServerConfig;
});
mockServerLog("info", `running on http://localhost:${port}`);
const isOutsideRoot = (rootRealPath: string, filePath: string) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const relativePath = path.relative(rootRealPath, filePath);
return (
relativePath === ".." || relativePath.startsWith("../") || relativePath.startsWith("..\\")
);
});
const isWithinRoot = (rootRealPath: string, filePath: string) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const resolvedFilePath = yield* fileSystem.realPath(filePath).pipe(
Effect.match({
onFailure: () => undefined,
onSuccess: (resolvedPath) => resolvedPath,
}),
);
return (
resolvedFilePath !== undefined && !(yield* isOutsideRoot(rootRealPath, resolvedFilePath))
);
});
const resolveRequestedFilePath = (rootRealPath: string, requestUrl: string | undefined) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const rawPath = (requestUrl ?? "/").split("?", 1)[0] ?? "/";
const decodedPath = yield* Effect.try({
try: () => decodeURIComponent(rawPath),
catch: () => null,
}).pipe(
Effect.match({
onFailure: () => undefined,
onSuccess: (value) => value,
}),
);
if (!decodedPath) {
return undefined;
}
if (decodedPath.includes("\0")) {
return undefined;
}
const filePath = path.resolve(
rootRealPath,
`.${decodedPath.startsWith("/") ? decodedPath : `/${decodedPath}`}`,
);
return (yield* isOutsideRoot(rootRealPath, filePath)) ? undefined : filePath;
});
const isServableFile = (rootRealPath: string, filePath: string) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const stat = yield* fileSystem.stat(filePath).pipe(
Effect.match({
onFailure: () => undefined,
onSuccess: (info) => info,
}),
);
if (stat?.type !== "File") {
return false;
}
return yield* isWithinRoot(rootRealPath, filePath);
});
export const makeMockUpdateRouteLayer = (rootRealPath: string) => {
return HttpRouter.add(
"*",
"*",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const requestPath = (request.url ?? "/").split("?", 1)[0] ?? "/";
yield* Effect.logInfo(`Request received for path: ${requestPath}`);
const filePath = yield* resolveRequestedFilePath(rootRealPath, request.url);
if (!filePath) {
yield* Effect.logWarning(`Attempted to access file outside of root: ${request.url ?? "/"}`);
return HttpServerResponse.text("Not Found", { status: 404 });
}
if (!(yield* isServableFile(rootRealPath, filePath))) {
yield* Effect.logWarning(`Attempted to access invalid file: ${filePath}`);
return HttpServerResponse.text("Not Found", { status: 404 });
}
yield* Effect.logInfo(`Serving file: ${filePath}`);
return yield* HttpServerResponse.file(filePath, { status: 200 });
}).pipe(
Effect.catchCause((cause) =>
Effect.gen(function* () {
yield* Effect.logError(`Unhandled mock update request failure: ${cause}`);
return HttpServerResponse.text("Internal Server Error", { status: 500 });
}),
),
),
);
};
const makeMockUpdateServerLayer = (config: MockUpdateServerConfig) =>
HttpRouter.serve(makeMockUpdateRouteLayer(config.rootRealPath)).pipe(
Layer.provideMerge(
NodeHttpServer.layer(NodeHttp.createServer, {
host: "localhost",
port: config.port,
}),
),
Layer.provideMerge(NodeServices.layer),
);
if (import.meta.main) {
resolveMockUpdateServerConfig.pipe(
Effect.map(makeMockUpdateServerLayer),
Layer.unwrap,
Layer.launch,
Effect.provide(NodeServices.layer),
NodeRuntime.runMain,
);
}
+7 -5
View File
@@ -196,8 +196,10 @@ const command = Command.make(
),
).pipe(Command.withDescription("Resolve the previous release tag for a stable or nightly series."));
Command.run(command, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide(NodeServices.layer),
NodeRuntime.runMain,
);
if (import.meta.main) {
Command.run(command, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide(NodeServices.layer),
NodeRuntime.runMain,
);
}
+2 -4
View File
@@ -2,10 +2,8 @@
"extends": "../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"types": ["node", "bun"],
"lib": ["ES2023", "esnext.disposable"],
"noEmit": true,
"allowImportingTsExtensions": true,
"types": ["node"],
"lib": ["ESNext", "esnext.disposable"],
"plugins": [
{
"name": "@effect/language-service"
+207 -65
View File
@@ -1,71 +1,213 @@
import { describe, expect, it } from "vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { ConfigProvider, Effect, FileSystem, Layer, Path, Schema, SchemaGetter } from "effect";
import { Command, CliError } from "effect/unstable/cli";
import * as TestConsole from "effect/testing/TestConsole";
import { parseArgs } from "./update-release-package-versions.ts";
import {
releasePackageFiles,
updateReleasePackageVersions,
updateReleasePackageVersionsCommand,
} from "./update-release-package-versions.ts";
describe("parseArgs", () => {
it("parses version only", () => {
expect(parseArgs(["1.2.3"])).toEqual({
version: "1.2.3",
rootDir: undefined,
writeGithubOutput: false,
});
});
const ScriptTestLayer = Layer.mergeAll(NodeServices.layer, TestConsole.layer);
const runCli = Command.runWith(updateReleasePackageVersionsCommand, { version: "0.0.0" });
const PackageJsonSchema = Schema.Record(Schema.String, Schema.Unknown);
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
);
const PackageJsonPrettyJson = Schema.fromJsonString(PackageJsonSchema).pipe(
Schema.encode({
decode: PrettyJsonString,
encode: PrettyJsonString,
}),
);
const decodePackageJson = Schema.decodeUnknownEffect(PackageJsonPrettyJson);
const encodePackageJson = Schema.encodeSync(PackageJsonPrettyJson);
it("parses version with --root", () => {
expect(parseArgs(["1.2.3", "--root", "/path"])).toEqual({
version: "1.2.3",
rootDir: "/path",
writeGithubOutput: false,
});
});
const writePackageJsonFixtures = Effect.fn("writePackageJsonFixtures")(function* (
rootDir: string,
version: string,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
it("parses version with --github-output", () => {
expect(parseArgs(["1.2.3", "--github-output"])).toEqual({
version: "1.2.3",
rootDir: undefined,
writeGithubOutput: true,
});
});
it("parses version with --root and --github-output", () => {
expect(parseArgs(["1.2.3", "--root", "/path", "--github-output"])).toEqual({
version: "1.2.3",
rootDir: "/path",
writeGithubOutput: true,
});
});
it("accepts flags before the version positional", () => {
expect(parseArgs(["--github-output", "--root", "/path", "1.2.3"])).toEqual({
version: "1.2.3",
rootDir: "/path",
writeGithubOutput: true,
});
});
it("throws on missing version", () => {
expect(() => parseArgs([])).toThrow("Usage:");
});
it("throws on duplicate version", () => {
expect(() => parseArgs(["1.2.3", "2.0.0"])).toThrow(
"Only one release version can be provided.",
for (const relativePath of releasePackageFiles) {
const filePath = path.join(rootDir, relativePath);
yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
yield* fs.writeFileString(
filePath,
`${encodePackageJson({
name: relativePath,
version,
private: true,
})}\n`,
);
});
it("throws on unknown flag", () => {
expect(() => parseArgs(["1.2.3", "--unknown"])).toThrow("Unknown argument: --unknown");
});
it("throws on --root without value", () => {
expect(() => parseArgs(["1.2.3", "--root"])).toThrow("Missing value for --root.");
});
it("does not consume version as --github-output value", () => {
expect(parseArgs(["--github-output", "1.2.3"])).toEqual({
version: "1.2.3",
rootDir: undefined,
writeGithubOutput: true,
});
});
}
});
const readReleaseVersions = Effect.fn("readReleaseVersions")(function* (rootDir: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const versions = new Map<string, string>();
for (const relativePath of releasePackageFiles) {
const filePath = path.join(rootDir, relativePath);
const packageJson = yield* fs.readFileString(filePath).pipe(Effect.flatMap(decodePackageJson));
versions.set(relativePath, String(packageJson.version));
}
return versions;
});
const captureLogs = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.gen(function* () {
const result = yield* effect;
const logs = (yield* TestConsole.logLines).filter(
(line): line is string => typeof line === "string",
);
return { result, logs };
});
it.layer(ScriptTestLayer)("update-release-package-versions", (it) => {
it.effect("updates all release package versions under the provided root", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-",
});
yield* writePackageJsonFixtures(baseDir, "0.0.1");
const result = yield* updateReleasePackageVersions("1.2.3", { rootDir: baseDir });
const versions = yield* readReleaseVersions(baseDir);
assert.deepStrictEqual(result, { changed: true });
assert.deepStrictEqual(
Array.from(versions.entries()),
releasePackageFiles.map((relativePath) => [relativePath, "1.2.3"]),
);
}),
);
it.effect("returns changed=false when all versions already match", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-unchanged-",
});
yield* writePackageJsonFixtures(baseDir, "1.2.3");
const result = yield* updateReleasePackageVersions("1.2.3", { rootDir: baseDir });
assert.deepStrictEqual(result, { changed: false });
}),
);
it.effect("accepts flags before the version positional and appends changed output", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-cli-",
});
const githubOutputPath = path.join(baseDir, "github-output.txt");
yield* writePackageJsonFixtures(baseDir, "0.0.1");
yield* runCli(["--github-output", "--root", baseDir, "2.0.0"]).pipe(
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
GITHUB_OUTPUT: githubOutputPath,
},
}),
),
),
);
const githubOutput = yield* fs.readFileString(githubOutputPath);
assert.equal(githubOutput, "changed=true\n");
}),
);
it.effect("logs when nothing changed", () =>
captureLogs(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-cli-log-",
});
yield* writePackageJsonFixtures(baseDir, "3.0.0");
yield* runCli(["3.0.0", "--root", baseDir]);
}),
).pipe(
Effect.tap(({ logs }) => {
assert.deepStrictEqual(logs, ["All package.json versions already match release version."]);
return Effect.void;
}),
),
);
it.effect("requires GITHUB_OUTPUT when --github-output is set", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-cli-missing-output-",
});
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: {} }))),
Effect.flip,
);
assert.equal(
error.message,
'SchemaError(Expected string, got undefined\n at ["GITHUB_OUTPUT"])',
);
}),
);
it.effect("rejects unknown flags during cli parsing", () =>
Effect.gen(function* () {
const error = yield* runCli(["1.2.3", "--unknown"]).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
}
const optionError =
error._tag === "ShowHelp" ? (error.errors[0] as CliError.CliError | undefined) : error;
if (!optionError || optionError._tag !== "UnrecognizedOption") {
assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
}
assert.equal(optionError.option, "--unknown");
}),
);
it.effect("rejects a missing version positional during cli parsing", () =>
Effect.gen(function* () {
const error = yield* runCli(["--github-output"]).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
}
const versionError =
error._tag === "ShowHelp" ? (error.errors[0] as CliError.CliError | undefined) : error;
if (!versionError || versionError._tag !== "MissingArgument") {
assert.fail(`Expected MissingArgument, got ${String(versionError?._tag)}`);
}
assert.equal(versionError.argument, "version");
}),
);
});
+63 -68
View File
@@ -1,8 +1,9 @@
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
#!/usr/bin/env node
import { parseCliArgs } from "@t3tools/shared/cliArgs";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Config, Console, Effect, FileSystem, Option, Path, Schema, SchemaGetter } from "effect";
import { Argument, Command, Flag } from "effect/unstable/cli";
export const releasePackageFiles = [
"apps/server/package.json",
@@ -12,88 +13,82 @@ export const releasePackageFiles = [
] as const;
interface UpdateReleasePackageVersionsOptions {
readonly rootDir?: string;
readonly rootDir?: string | undefined;
}
interface MutablePackageJson {
version?: string;
[key: string]: unknown;
}
const PackageJsonSchema = Schema.Record(Schema.String, Schema.Unknown);
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
);
const PackageJsonPrettyJson = Schema.fromJsonString(PackageJsonSchema).pipe(
Schema.encode({
decode: PrettyJsonString,
encode: PrettyJsonString,
}),
);
const decodePackageJson = Schema.decodeUnknownEffect(PackageJsonPrettyJson);
const encodePackageJson = Schema.encodeSync(PackageJsonPrettyJson);
export function updateReleasePackageVersions(
export const updateReleasePackageVersions = Effect.fn("updateReleasePackageVersions")(function* (
version: string,
options: UpdateReleasePackageVersionsOptions = {},
): { changed: boolean } {
const rootDir = resolve(options.rootDir ?? process.cwd());
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const rootDir = path.resolve(options.rootDir ?? process.cwd());
let changed = false;
for (const relativePath of releasePackageFiles) {
const filePath = resolve(rootDir, relativePath);
const packageJson = JSON.parse(readFileSync(filePath, "utf8")) as MutablePackageJson;
const filePath = path.join(rootDir, relativePath);
const packageJson = yield* fs.readFileString(filePath).pipe(Effect.flatMap(decodePackageJson));
if (packageJson.version === version) {
continue;
}
packageJson.version = version;
writeFileSync(filePath, `${JSON.stringify(packageJson, null, 2)}\n`);
yield* fs.writeFileString(filePath, `${encodePackageJson({ ...packageJson, version })}\n`);
changed = true;
}
return { changed };
}
});
export function parseArgs(argv: ReadonlyArray<string>): {
version: string;
rootDir: string | undefined;
writeGithubOutput: boolean;
} {
const { flags, positionals } = parseCliArgs(argv, { booleanFlags: ["github-output"] });
const writeGithubOutput = Effect.fn("writeGithubOutput")(function* (changed: boolean) {
const fs = yield* FileSystem.FileSystem;
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");
yield* fs.writeFileString(githubOutputPath, `changed=${changed}\n`, { flag: "a" });
});
const unknownFlags = Object.keys(flags).filter((k) => k !== "github-output" && k !== "root");
if (unknownFlags.length > 0) {
throw new Error(`Unknown argument: --${unknownFlags[0]}`);
}
export const updateReleasePackageVersionsCommand = Command.make(
"update-release-package-versions",
{
version: Argument.string("version").pipe(
Argument.withDescription("Release version to write into each releasable package.json."),
),
root: Flag.string("root").pipe(
Flag.withDescription("Workspace root used to resolve the release package manifests."),
Flag.optional,
),
githubOutput: Flag.boolean("github-output").pipe(
Flag.withDescription("Append changed=<boolean> to GITHUB_OUTPUT."),
Flag.withDefault(false),
),
},
({ version, root, githubOutput }) =>
updateReleasePackageVersions(version, {
rootDir: Option.getOrUndefined(root),
}).pipe(
Effect.tap(({ changed }) =>
changed
? Effect.void
: Console.log("All package.json versions already match release version."),
),
Effect.tap(({ changed }) => (githubOutput ? writeGithubOutput(changed) : Effect.void)),
),
).pipe(Command.withDescription("Update release package versions across the workspace."));
if ("root" in flags && flags.root === null) {
throw new Error("Missing value for --root.");
}
if (positionals.length > 1) {
throw new Error("Only one release version can be provided.");
}
if (positionals.length !== 1 || !positionals[0]) {
throw new Error(
"Usage: node scripts/update-release-package-versions.ts <version> [--root <path>] [--github-output]",
);
}
return {
version: positionals[0],
rootDir: flags.root ?? undefined,
writeGithubOutput: "github-output" in flags,
};
}
const isMain =
process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isMain) {
const { version, rootDir, writeGithubOutput } = parseArgs(process.argv.slice(2));
const { changed } = updateReleasePackageVersions(
version,
rootDir === undefined ? {} : { rootDir },
if (import.meta.main) {
Command.run(updateReleasePackageVersionsCommand, { version: "0.0.0" }).pipe(
Effect.provide(NodeServices.layer),
NodeRuntime.runMain,
);
if (!changed) {
console.log("All package.json versions already match release version.");
}
if (writeGithubOutput) {
const githubOutputPath = process.env.GITHUB_OUTPUT;
if (!githubOutputPath) {
throw new Error("GITHUB_OUTPUT is required when --github-output is set.");
}
appendFileSync(githubOutputPath, `changed=${changed}\n`);
}
}