Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
Adopt Node-native TypeScript for desktop and server (#2098)
Julius Marminge8dba2d6484e2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7d2cb7479..e3329b1da 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -71,8 +71,8 @@ jobs:- name: Verify preload bundle outputrun: |- test -f apps/desktop/dist-electron/preload.js- grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js+ test -f apps/desktop/dist-electron/preload.cjs+ grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjsrelease_smoke:name: Release Smokediff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 86e61f182..5fbd3021a 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -2,13 +2,14 @@"name": "@t3tools/desktop","version": "0.0.20","private": true,- "main": "dist-electron/main.js",+ "type": "module",+ "main": "dist-electron/main.cjs","scripts": {"dev": "bun run --parallel dev:bundle dev:electron","dev:bundle": "tsdown --watch",- "dev:electron": "bun run scripts/dev-electron.mjs",+ "dev:electron": "node scripts/dev-electron.mjs","build": "tsdown",- "start": "bun run scripts/start-electron.mjs",+ "start": "node scripts/start-electron.mjs","typecheck": "tsc --noEmit","test": "vitest run --passWithNoTests","smoke-test": "node scripts/smoke-test.mjs"diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjsindex 7c0d55ac9..9a7e68dfb 100644--- a/apps/desktop/scripts/dev-electron.mjs+++ b/apps/desktop/scripts/dev-electron.mjs@@ -17,12 +17,12 @@ if (!Number.isInteger(port) || port <= 0) {}const requiredFiles = [- "dist-electron/main.js",- "dist-electron/preload.js",+ "dist-electron/main.cjs",+ "dist-electron/preload.cjs","../server/dist/bin.mjs",];const watchedDirectories = [- { directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },+ { directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },{ directory: "../server/dist", files: new Set(["bin.mjs"]) },];const forcedShutdownTimeoutMs = 1_500;@@ -69,7 +69,7 @@ function startApp() {const app = spawn(resolveElectronPath(),- [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],+ [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],{cwd: desktopDir,env: childEnv,diff --git a/apps/desktop/scripts/electron-launcher.mjs b/apps/desktop/scripts/electron-launcher.mjsindex 77d9df314..1453cbe66 100644--- a/apps/desktop/scripts/electron-launcher.mjs+++ b/apps/desktop/scripts/electron-launcher.mjs@@ -8,7 +8,6 @@ import {mkdirSync,mkdtempSync,readFileSync,- readdirSync,rmSync,statSync,writeFileSync,@@ -20,7 +19,7 @@ import { fileURLToPath } from "node:url";const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";-const LAUNCHER_VERSION = 1;+const LAUNCHER_VERSION = 2;const __dirname = dirname(fileURLToPath(import.meta.url));export const desktopDir = resolve(__dirname, "..");@@ -121,40 +120,6 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {copyFileSync(iconPath, join(resourcesDir, "electron.icns"));}-function patchHelperBundleInfoPlists(appBundlePath) {- const frameworksDir = join(appBundlePath, "Contents", "Frameworks");- if (!existsSync(frameworksDir)) {- return;- }-- for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {- if (!entry.isDirectory() || !entry.name.endsWith(".app")) {- continue;- }- if (!entry.name.startsWith("Electron Helper")) {- continue;- }-- const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");- if (!existsSync(helperPlistPath)) {- continue;- }-- const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();- const helperName = suffix- ? `${APP_DISPLAY_NAME} Helper ${suffix}`- : `${APP_DISPLAY_NAME} Helper`;- const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-");- const helperBundleId = helperIdSuffix- ? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`- : `${APP_BUNDLE_ID}.helper`;-- setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);- setPlistString(helperPlistPath, "CFBundleName", helperName);- setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);- }-}-function readJson(path) {try {return JSON.parse(readFileSync(path, "utf8"));@@ -192,7 +157,6 @@ function buildMacLauncher(electronBinaryPath) {rmSync(targetAppBundlePath, { recursive: true, force: true });cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });patchMainBundleInfoPlist(targetAppBundlePath, iconPath);- patchHelperBundleInfoPlists(targetAppBundlePath);writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);return targetBinaryPath;@@ -206,5 +170,11 @@ export function resolveElectronPath() {return electronBinaryPath;}+ // Dev launches do not need a renamed app bundle badly enough to risk breaking+ // Electron helper resource lookup on macOS.+ if (isDevelopment) {+ return electronBinaryPath;+ }+return buildMacLauncher(electronBinaryPath);}diff --git a/apps/desktop/scripts/smoke-test.mjs b/apps/desktop/scripts/smoke-test.mjsindex 883da7203..fdbe69b77 100644--- a/apps/desktop/scripts/smoke-test.mjs+++ b/apps/desktop/scripts/smoke-test.mjs@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";const __dirname = dirname(fileURLToPath(import.meta.url));const desktopDir = resolve(__dirname, "..");const electronBin = resolve(desktopDir, "node_modules/.bin/electron");-const mainJs = resolve(desktopDir, "dist-electron/main.js");+const mainJs = resolve(desktopDir, "dist-electron/main.cjs");console.log("\nLaunching Electron smoke test...");diff --git a/apps/desktop/scripts/start-electron.mjs b/apps/desktop/scripts/start-electron.mjsindex bf93adb6b..375dbfe57 100644--- a/apps/desktop/scripts/start-electron.mjs+++ b/apps/desktop/scripts/start-electron.mjs@@ -5,7 +5,7 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";const childEnv = { ...process.env };delete childEnv.ELECTRON_RUN_AS_NODE;-const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {+const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {stdio: "inherit",cwd: desktopDir,env: childEnv,diff --git a/apps/desktop/src/appBranding.test.ts b/apps/desktop/src/appBranding.test.tsindex 93e872fb0..5e3e3a5a1 100644--- a/apps/desktop/src/appBranding.test.ts+++ b/apps/desktop/src/appBranding.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding";+import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding.ts";describe("resolveDesktopAppStageLabel", () => {it("uses Dev in desktop development", () => {diff --git a/apps/desktop/src/appBranding.ts b/apps/desktop/src/appBranding.tsindex 49cbcc678..3cb1539f7 100644--- a/apps/desktop/src/appBranding.ts+++ b/apps/desktop/src/appBranding.ts@@ -1,6 +1,6 @@import type { DesktopAppBranding, DesktopAppStageLabel } from "@t3tools/contracts";-import { isNightlyDesktopVersion } from "./updateChannels";+import { isNightlyDesktopVersion } from "./updateChannels.ts";const APP_BASE_NAME = "T3 Code";diff --git a/apps/desktop/src/backendPort.test.ts b/apps/desktop/src/backendPort.test.tsindex 8f586deb7..774e31b80 100644--- a/apps/desktop/src/backendPort.test.ts+++ b/apps/desktop/src/backendPort.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from "vitest";-import { resolveDesktopBackendPort } from "./backendPort";+import { resolveDesktopBackendPort } from "./backendPort.ts";describe("resolveDesktopBackendPort", () => {it("returns the starting port when it is available", async () => {diff --git a/apps/desktop/src/backendReadiness.test.ts b/apps/desktop/src/backendReadiness.test.tsindex 33a5ef6b7..0d49842ac 100644--- a/apps/desktop/src/backendReadiness.test.ts+++ b/apps/desktop/src/backendReadiness.test.ts@@ -4,7 +4,7 @@ import {BackendReadinessAbortedError,isBackendReadinessAborted,waitForHttpReady,-} from "./backendReadiness";+} from "./backendReadiness.ts";describe("waitForHttpReady", () => {it("returns once the backend serves the requested readiness path", async () => {diff --git a/apps/desktop/src/clientPersistence.test.ts b/apps/desktop/src/clientPersistence.test.tsindex fa263b18f..27f1e1d91 100644--- a/apps/desktop/src/clientPersistence.test.ts+++ b/apps/desktop/src/clientPersistence.test.ts@@ -18,7 +18,7 @@ import {writeSavedEnvironmentRegistry,writeSavedEnvironmentSecret,type DesktopSecretStorage,-} from "./clientPersistence";+} from "./clientPersistence.ts";const tempDirectories: string[] = [];diff --git a/apps/desktop/src/confirmDialog.test.ts b/apps/desktop/src/confirmDialog.test.tsindex 4a4c0ddbe..de1d23eb1 100644--- a/apps/desktop/src/confirmDialog.test.ts+++ b/apps/desktop/src/confirmDialog.test.ts@@ -11,7 +11,7 @@ vi.mock("electron", () => ({},}));-import { showDesktopConfirmDialog } from "./confirmDialog";+import { showDesktopConfirmDialog } from "./confirmDialog.ts";describe("showDesktopConfirmDialog", () => {beforeEach(() => {diff --git a/apps/desktop/src/desktopSettings.test.ts b/apps/desktop/src/desktopSettings.test.tsindex 7c8be53f8..9b467d22c 100644--- a/apps/desktop/src/desktopSettings.test.ts+++ b/apps/desktop/src/desktopSettings.test.ts@@ -11,7 +11,7 @@ import {setDesktopServerExposurePreference,setDesktopUpdateChannelPreference,writeDesktopSettings,-} from "./desktopSettings";+} from "./desktopSettings.ts";const tempDirectories: string[] = [];diff --git a/apps/desktop/src/desktopSettings.ts b/apps/desktop/src/desktopSettings.tsindex cb0829a8b..6ece5189c 100644--- a/apps/desktop/src/desktopSettings.ts+++ b/apps/desktop/src/desktopSettings.ts@@ -2,7 +2,7 @@ import * as FS from "node:fs";import * as Path from "node:path";import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";-import { resolveDefaultDesktopUpdateChannel } from "./updateChannels";+import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";export interface DesktopSettings {readonly serverExposureMode: DesktopServerExposureMode;diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 6bdce564b..3ef80f5c0 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -36,14 +36,14 @@ import { autoUpdater } from "electron-updater";import type { ContextMenuItem } from "@t3tools/contracts";import { RotatingFileSink } from "@t3tools/shared/logging";import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";-import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";+import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";import {DEFAULT_DESKTOP_SETTINGS,readDesktopSettings,setDesktopServerExposurePreference,setDesktopUpdateChannelPreference,writeDesktopSettings,-} from "./desktopSettings";+} from "./desktopSettings.ts";import {readClientSettings,readSavedEnvironmentRegistry,@@ -52,14 +52,14 @@ import {writeClientSettings,writeSavedEnvironmentRegistry,writeSavedEnvironmentSecret,-} from "./clientPersistence";-import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";-import { showDesktopConfirmDialog } from "./confirmDialog";-import { resolveDesktopServerExposure } from "./serverExposure";-import { syncShellEnvironment } from "./syncShellEnvironment";-import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";-import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels";-import { ServerListeningDetector } from "./serverListeningDetector";+} from "./clientPersistence.ts";+import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";+import { showDesktopConfirmDialog } from "./confirmDialog.ts";+import { resolveDesktopServerExposure } from "./serverExposure.ts";+import { syncShellEnvironment } from "./syncShellEnvironment.ts";+import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";+import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels.ts";+import { ServerListeningDetector } from "./serverListeningDetector.ts";import {createInitialDesktopUpdateState,reduceDesktopUpdateStateOnCheckFailure,@@ -71,9 +71,9 @@ import {reduceDesktopUpdateStateOnInstallFailure,reduceDesktopUpdateStateOnNoUpdate,reduceDesktopUpdateStateOnUpdateAvailable,-} from "./updateMachine";-import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";-import { resolveDesktopAppBranding } from "./appBranding";+} from "./updateMachine.ts";+import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";+import { resolveDesktopAppBranding } from "./appBranding.ts";syncShellEnvironment();@@ -1967,7 +1967,7 @@ function createWindow(): BrowserWindow {title: APP_DISPLAY_NAME,...getWindowTitleBarOptions(),webPreferences: {- preload: Path.join(__dirname, "preload.js"),+ preload: Path.join(__dirname, "preload.cjs"),contextIsolation: true,nodeIntegration: false,sandbox: true,diff --git a/apps/desktop/src/runtimeArch.test.ts b/apps/desktop/src/runtimeArch.test.tsindex 258a8fb21..a31735989 100644--- a/apps/desktop/src/runtimeArch.test.ts+++ b/apps/desktop/src/runtimeArch.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";+import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";describe("resolveDesktopRuntimeInfo", () => {it("detects Rosetta-translated Intel builds on Apple Silicon", () => {diff --git a/apps/desktop/src/serverExposure.test.ts b/apps/desktop/src/serverExposure.test.tsindex b1ae4bef4..c83bbc210 100644--- a/apps/desktop/src/serverExposure.test.ts+++ b/apps/desktop/src/serverExposure.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";+import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";describe("resolveLanAdvertisedHost", () => {it("prefers an explicit host override", () => {diff --git a/apps/desktop/src/serverListeningDetector.test.ts b/apps/desktop/src/serverListeningDetector.test.tsindex b7c66b631..fcf9f50ae 100644--- a/apps/desktop/src/serverListeningDetector.test.ts+++ b/apps/desktop/src/serverListeningDetector.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { ServerListeningDetector } from "./serverListeningDetector";+import { ServerListeningDetector } from "./serverListeningDetector.ts";describe("ServerListeningDetector", () => {it("resolves when the server logs the listening line", async () => {diff --git a/apps/desktop/src/syncShellEnvironment.test.ts b/apps/desktop/src/syncShellEnvironment.test.tsindex 7d4578895..abaeeb2b2 100644--- a/apps/desktop/src/syncShellEnvironment.test.ts+++ b/apps/desktop/src/syncShellEnvironment.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from "vitest";-import { syncShellEnvironment } from "./syncShellEnvironment";+import { syncShellEnvironment } from "./syncShellEnvironment.ts";describe("syncShellEnvironment", () => {it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {diff --git a/apps/desktop/src/syncShellEnvironment.ts b/apps/desktop/src/syncShellEnvironment.tsindex 7e031b111..11a9e6930 100644--- a/apps/desktop/src/syncShellEnvironment.ts+++ b/apps/desktop/src/syncShellEnvironment.ts@@ -3,8 +3,8 @@ import {mergePathEntries,readPathFromLaunchctl,readEnvironmentFromLoginShell,- ShellEnvironmentReader,} from "@t3tools/shared/shell";+import type { ShellEnvironmentReader } from "@t3tools/shared/shell";const LOGIN_SHELL_ENV_NAMES = ["PATH",diff --git a/apps/desktop/src/updateChannels.test.ts b/apps/desktop/src/updateChannels.test.tsindex bd1dcc0c7..f815fbd81 100644--- a/apps/desktop/src/updateChannels.test.ts+++ b/apps/desktop/src/updateChannels.test.ts@@ -4,7 +4,7 @@ import {doesVersionMatchDesktopUpdateChannel,isNightlyDesktopVersion,resolveDefaultDesktopUpdateChannel,-} from "./updateChannels";+} from "./updateChannels.ts";describe("isNightlyDesktopVersion", () => {it("detects packaged nightly versions", () => {diff --git a/apps/desktop/src/updateMachine.test.ts b/apps/desktop/src/updateMachine.test.tsindex a6fbcfb5d..e2f0519d3 100644--- a/apps/desktop/src/updateMachine.test.ts+++ b/apps/desktop/src/updateMachine.test.ts@@ -11,7 +11,7 @@ import {reduceDesktopUpdateStateOnInstallFailure,reduceDesktopUpdateStateOnNoUpdate,reduceDesktopUpdateStateOnUpdateAvailable,-} from "./updateMachine";+} from "./updateMachine.ts";const runtimeInfo = {hostArch: "x64",diff --git a/apps/desktop/src/updateMachine.ts b/apps/desktop/src/updateMachine.tsindex c767dfd2f..7d5ed271e 100644--- a/apps/desktop/src/updateMachine.ts+++ b/apps/desktop/src/updateMachine.ts@@ -4,7 +4,7 @@ import type {DesktopUpdateState,} from "@t3tools/contracts";-import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";+import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState.ts";export function createInitialDesktopUpdateState(currentVersion: string,diff --git a/apps/desktop/src/updateState.test.ts b/apps/desktop/src/updateState.test.tsindex 9d7fe5b7a..c2bb4ba12 100644--- a/apps/desktop/src/updateState.test.ts+++ b/apps/desktop/src/updateState.test.ts@@ -6,7 +6,7 @@ import {getAutoUpdateDisabledReason,nextStatusAfterDownloadFailure,shouldBroadcastDownloadProgress,-} from "./updateState";+} from "./updateState.ts";const baseState: DesktopUpdateState = {enabled: true,diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.jsonindex 0ca5bcaa7..ff3e4cd0f 100644--- a/apps/desktop/tsconfig.json+++ b/apps/desktop/tsconfig.json@@ -3,7 +3,7 @@"compilerOptions": {"composite": true,"types": ["node", "electron"],- "lib": ["ES2023", "DOM", "esnext.disposable"]+ "lib": ["ESNext", "DOM", "esnext.disposable"]},"include": ["src", "tsdown.config.ts"]}diff --git a/apps/desktop/tsdown.config.ts b/apps/desktop/tsdown.config.tsindex f3ebc9732..53b003934 100644--- a/apps/desktop/tsdown.config.ts+++ b/apps/desktop/tsdown.config.ts@@ -4,7 +4,7 @@ const shared = {format: "cjs" as const,outDir: "dist-electron",sourcemap: true,- outExtensions: () => ({ js: ".js" }),+ outExtensions: () => ({ js: ".cjs" }),};export default defineConfig([diff --git a/apps/server/package.json b/apps/server/package.jsonindex a5d5d986e..038134bd5 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -15,8 +15,9 @@],"type": "module","scripts": {- "dev": "bun run src/bin.ts",+ "dev": "node --watch src/bin.ts","build": "node scripts/cli.ts build",+ "build:bundle": "tsdown","start": "node dist/bin.mjs","prepare": "effect-language-service patch","typecheck": "tsc --noEmit",diff --git a/apps/server/scripts/cli.ts b/apps/server/scripts/cli.tsindex 299da67fa..efaa2b3b6 100644--- a/apps/server/scripts/cli.ts+++ b/apps/server/scripts/cli.ts@@ -147,13 +147,13 @@ const buildCmd = Command.make(yield* Effect.log("[cli] Running tsdown...");yield* runCommand(- ChildProcess.make({+ ChildProcess.make(process.execPath, ["--run", "build:bundle"], {cwd: serverDir,stdout: config.verbose ? "inherit" : "ignore",stderr: "inherit",- // Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).+ // Windows needs shell mode to resolve `.cmd` shims on PATH.shell: process.platform === "win32",- })`bun tsdown`,+ }),);const webDist = path.join(repoRoot, "apps/web/dist");@@ -203,10 +203,8 @@ const publishCmd = Command.make(}yield* Effect.acquireUseRelease(- // Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts+ // Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scriptsEffect.gen(function* () {- // Resolve catalog dependencies before any file mutations. If this throws,- // acquire fails and no release hook runs, so filesystem must still be untouched.const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);const pkg: PackageJson = {name: serverPackageJson.name,@@ -216,25 +214,22 @@ const publishCmd = Command.make(version,engines: serverPackageJson.engines,files: serverPackageJson.files,- dependencies: serverPackageJson.dependencies,- overrides: rootPackageJson.overrides,+ dependencies: resolveCatalogDependencies(+ serverPackageJson.dependencies,+ rootPackageJson.workspaces.catalog,+ "apps/server",+ ),+ overrides: resolveCatalogDependencies(+ rootPackageJson.overrides,+ rootPackageJson.workspaces.catalog,+ "apps/server",+ ),};- pkg.dependencies = resolveCatalogDependencies(- pkg.dependencies,- rootPackageJson.workspaces.catalog,- "apps/server dependencies",- );- pkg.overrides = resolveCatalogDependencies(- pkg.overrides,- rootPackageJson.workspaces.catalog,- "root overrides",- );-const original = yield* fs.readFileString(packageJsonPath);yield* fs.writeFileString(backupPath, original);yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);- yield* Effect.log("[cli] Resolved package.json for publish");+ yield* Effect.log("[cli] Prepared package.json for publish");const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);return { iconBackups };diff --git a/apps/server/src/auth/Layers/AuthControlPlane.test.ts b/apps/server/src/auth/Layers/AuthControlPlane.test.tsindex 9fc091124..280fbc160 100644--- a/apps/server/src/auth/Layers/AuthControlPlane.test.ts+++ b/apps/server/src/auth/Layers/AuthControlPlane.test.ts@@ -2,7 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import { expect, it } from "@effect/vitest";import { Effect, Layer } from "effect";-import { ServerConfigShape } from "../../config.ts";+import type { ServerConfigShape } from "../../config.ts";import { ServerConfig } from "../../config.ts";import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";import { ServerSecretStoreLive } from "./ServerSecretStore.ts";diff --git a/apps/server/src/auth/Layers/AuthControlPlane.ts b/apps/server/src/auth/Layers/AuthControlPlane.tsindex 98b210780..1bf4909e8 100644--- a/apps/server/src/auth/Layers/AuthControlPlane.ts+++ b/apps/server/src/auth/Layers/AuthControlPlane.ts@@ -10,8 +10,10 @@ import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layimport {AuthControlPlane,AuthControlPlaneError,- AuthControlPlaneShape,DEFAULT_SESSION_SUBJECT,+} from "../Services/AuthControlPlane.ts";+import type {+ AuthControlPlaneShape,IssuedBearerSession,IssuedPairingLink,} from "../Services/AuthControlPlane.ts";diff --git a/apps/server/src/auth/Services/AuthControlPlane.ts b/apps/server/src/auth/Services/AuthControlPlane.tsindex b59e330bc..4b3cf474f 100644--- a/apps/server/src/auth/Services/AuthControlPlane.ts+++ b/apps/server/src/auth/Services/AuthControlPlane.ts@@ -5,7 +5,7 @@ import type {AuthSessionId,} from "@t3tools/contracts";import { Data, DateTime, Duration, Effect, Context } from "effect";-import { SessionRole } from "./SessionCredentialService";+import type { SessionRole } from "./SessionCredentialService.ts";export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";diff --git a/apps/server/src/auth/utils.test.ts b/apps/server/src/auth/utils.test.tsindex a767b77de..e7a540d81 100644--- a/apps/server/src/auth/utils.test.ts+++ b/apps/server/src/auth/utils.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { deriveAuthClientMetadata } from "./utils";+import { deriveAuthClientMetadata } from "./utils.ts";describe("deriveAuthClientMetadata", () => {it("labels Electron user agents as Electron instead of Chrome", () => {diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.tsindex 063d43326..874898d86 100644--- a/apps/server/src/bin.ts+++ b/apps/server/src/bin.ts@@ -5,12 +5,12 @@ import * as Layer from "effect/Layer";import { Command } from "effect/unstable/cli";import { NetService } from "@t3tools/shared/Net";-import { cli } from "./cli";-import { version } from "../package.json" with { type: "json" };+import { cli } from "./cli.ts";+import packageJson from "../package.json" with { type: "json" };const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);-Command.run(cli, { version }).pipe(+Command.run(cli, { version: packageJson.version }).pipe(Effect.scoped,Effect.provide(CliRuntimeLayer),NodeRuntime.runMain,diff --git a/apps/server/src/bootstrap.test.ts b/apps/server/src/bootstrap.test.tsindex 3fce6af9c..e4cdfab1d 100644--- a/apps/server/src/bootstrap.test.ts+++ b/apps/server/src/bootstrap.test.ts@@ -10,7 +10,7 @@ import * as Fiber from "effect/Fiber";import { TestClock } from "effect/testing";import { vi } from "vitest";-import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";+import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap.ts";import { assertNone, assertSome } from "@effect/vitest/utils";const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));diff --git a/apps/server/src/cli-config.test.ts b/apps/server/src/cli-config.test.tsindex 6fa6e0c96..5adece730 100644--- a/apps/server/src/cli-config.test.ts+++ b/apps/server/src/cli-config.test.ts@@ -5,8 +5,8 @@ import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect"import { NetService } from "@t3tools/shared/Net";import * as NodeServices from "@effect/platform-node/NodeServices";-import { deriveServerPaths } from "./config";-import { resolveServerConfig } from "./cli";+import { deriveServerPaths } from "./config.ts";+import { resolveServerConfig } from "./cli.ts";it.layer(NodeServices.layer)("cli config resolution", (it) => {const defaultObservabilityConfig = {diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.tsindex 5f7375092..4fc23a1de 100644--- a/apps/server/src/cli.ts+++ b/apps/server/src/cli.ts@@ -40,30 +40,31 @@ import {RuntimeMode,type ServerConfigShape,type StartupPresentation,-} from "./config";-import { readBootstrapEnvelope } from "./bootstrap";-import { expandHomePath, resolveBaseDir } from "./os-jank";-import { runServer } from "./server";+} from "./config.ts";+import { readBootstrapEnvelope } from "./bootstrap.ts";+import { expandHomePath, resolveBaseDir } from "./os-jank.ts";+import { runServer } from "./server.ts";import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts";import {formatIssuedPairingCredential,formatIssuedSession,formatPairingCredentialList,formatSessionList,-} from "./cliAuthFormat";-import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";+} from "./cliAuthFormat.ts";+import { AuthControlPlane } from "./auth/Services/AuthControlPlane.ts";+import type { AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";-import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";+import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";-import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup";+import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup.ts";import {clearPersistedServerRuntimeState,readPersistedServerRuntimeState,-} from "./serverRuntimeState";-import { WorkspacePaths } from "./workspace/Services/WorkspacePaths";-import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";+} from "./serverRuntimeState.ts";+import { WorkspacePaths } from "./workspace/Services/WorkspacePaths.ts";+import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));diff --git a/apps/server/src/codexAppServerManager.test.ts b/apps/server/src/codexAppServerManager.test.tsindex 919aacf72..84225ef1e 100644--- a/apps/server/src/codexAppServerManager.test.ts+++ b/apps/server/src/codexAppServerManager.test.ts@@ -15,7 +15,7 @@ import {normalizeCodexModelSlug,readCodexAccountSnapshot,resolveCodexModelForAccount,-} from "./codexAppServerManager";+} from "./codexAppServerManager.ts";const asThreadId = (value: string): ThreadId => ThreadId.make(value);diff --git a/apps/server/src/codexAppServerManager.ts b/apps/server/src/codexAppServerManager.tsindex 1e6a7fdb6..6d98264c9 100644--- a/apps/server/src/codexAppServerManager.ts+++ b/apps/server/src/codexAppServerManager.ts@@ -25,16 +25,16 @@ import {formatCodexCliUpgradeMessage,isCodexCliVersionSupported,parseCodexCliVersion,-} from "./provider/codexCliVersion";+} from "./provider/codexCliVersion.ts";import {readCodexAccountSnapshot,resolveCodexModelForAccount,type CodexAccountSnapshot,-} from "./provider/codexAccount";-import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";+} from "./provider/codexAccount.ts";+import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer.ts";-export { buildCodexInitializeParams } from "./provider/codexAppServer";-export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";+export { buildCodexInitializeParams } from "./provider/codexAppServer.ts";+export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount.ts";type PendingRequestKey = string;diff --git a/apps/server/src/environment/Layers/ServerEnvironment.ts b/apps/server/src/environment/Layers/ServerEnvironment.tsindex 506fc45af..9208a6d8e 100644--- a/apps/server/src/environment/Layers/ServerEnvironment.ts+++ b/apps/server/src/environment/Layers/ServerEnvironment.ts@@ -3,7 +3,7 @@ import { Effect, FileSystem, Layer, Path, Random } from "effect";import { ServerConfig } from "../../config.ts";import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";-import { version } from "../../../package.json" with { type: "json" };+import packageJson from "../../../package.json" with { type: "json" };import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {@@ -77,7 +77,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(functionos: platformOs(),arch: platformArch(),},- serverVersion: version,+ serverVersion: packageJson.version,capabilities: {repositoryIdentity: true,},diff --git a/apps/server/src/git/Layers/GitHubCli.test.ts b/apps/server/src/git/Layers/GitHubCli.test.tsindex 0ee4b3f09..5a7b9cb8b 100644--- a/apps/server/src/git/Layers/GitHubCli.test.ts+++ b/apps/server/src/git/Layers/GitHubCli.test.ts@@ -6,7 +6,7 @@ vi.mock("../../processRunner", () => ({runProcess: vi.fn(),}));-import { runProcess } from "../../processRunner";+import { runProcess } from "../../processRunner.ts";import { GitHubCli } from "../Services/GitHubCli.ts";import { GitHubCliLive } from "./GitHubCli.ts";diff --git a/apps/server/src/git/Layers/GitHubCli.ts b/apps/server/src/git/Layers/GitHubCli.tsindex 1a687b0e8..dbacdf632 100644--- a/apps/server/src/git/Layers/GitHubCli.ts+++ b/apps/server/src/git/Layers/GitHubCli.ts@@ -1,7 +1,7 @@import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";import { TrimmedNonEmptyString } from "@t3tools/contracts";-import { runProcess } from "../../processRunner";+import { runProcess } from "../../processRunner.ts";import { GitHubCliError } from "@t3tools/contracts";import {GitHubCli,diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.tsindex a84427a19..dadf2f7e7 100644--- a/apps/server/src/git/Layers/GitManager.ts+++ b/apps/server/src/git/Layers/GitManager.ts@@ -38,7 +38,8 @@ import {type GitManagerShape,type GitRunStackedActionOptions,} from "../Services/GitManager.ts";-import { GitCore, GitStatusDetails } from "../Services/GitCore.ts";+import { GitCore } from "../Services/GitCore.ts";+import type { GitStatusDetails } from "../Services/GitCore.ts";import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";import { TextGeneration } from "../Services/TextGeneration.ts";import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";diff --git a/apps/server/src/git/Services/GitHubCli.ts b/apps/server/src/git/Services/GitHubCli.tsindex 216c24bf7..81a53761a 100644--- a/apps/server/src/git/Services/GitHubCli.ts+++ b/apps/server/src/git/Services/GitHubCli.ts@@ -8,7 +8,7 @@import { Context } from "effect";import type { Effect } from "effect";-import type { ProcessRunResult } from "../../processRunner";+import type { ProcessRunResult } from "../../processRunner.ts";import type { GitHubCliError } from "@t3tools/contracts";export interface GitHubPullRequestSummary {diff --git a/apps/server/src/http.ts b/apps/server/src/http.tsindex 7420156b2..88cc5adae 100644--- a/apps/server/src/http.ts+++ b/apps/server/src/http.ts@@ -15,12 +15,12 @@ import {ATTACHMENTS_ROUTE_PREFIX,normalizeAttachmentRelativePath,resolveAttachmentRelativePath,-} from "./attachmentPaths";-import { resolveAttachmentPathById } from "./attachmentStore";-import { resolveStaticDir, ServerConfig } from "./config";+} from "./attachmentPaths.ts";+import { resolveAttachmentPathById } from "./attachmentStore.ts";+import { resolveStaticDir, ServerConfig } from "./config.ts";import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";-import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";+import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";import { ServerAuth } from "./auth/Services/ServerAuth.ts";import { respondToAuthError } from "./auth/http.ts";import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.tsindex e3f190ff0..15edd4295 100644--- a/apps/server/src/keybindings.test.ts+++ b/apps/server/src/keybindings.test.ts@@ -3,7 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import { assert, it } from "@effect/vitest";import { assertFailure } from "@effect/vitest/utils";import { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";-import { ServerConfig } from "./config";+import { ServerConfig } from "./config.ts";import {DEFAULT_KEYBINDINGS,@@ -13,7 +13,7 @@ import {compileResolvedKeybindingRule,compileResolvedKeybindingsConfig,parseKeybindingShortcut,-} from "./keybindings";+} from "./keybindings.ts";import { KeybindingsConfigError } from "@t3tools/contracts";const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.tsindex b473f77ca..07ae9156c 100644--- a/apps/server/src/keybindings.ts+++ b/apps/server/src/keybindings.ts@@ -19,7 +19,7 @@ import {THREAD_JUMP_KEYBINDING_COMMANDS,type ServerConfigIssue,} from "@t3tools/contracts";-import { Mutable } from "effect/Types";+import type { Mutable } from "effect/Types";import {Array,Cache,@@ -44,7 +44,7 @@ import {Stream,} from "effect";import * as Semaphore from "effect/Semaphore";-import { ServerConfig } from "./config";+import { ServerConfig } from "./config.ts";import { fromLenientJson } from "@t3tools/shared/schemaJson";type WhenToken =diff --git a/apps/server/src/observability/LocalFileTracer.ts b/apps/server/src/observability/LocalFileTracer.tsindex cde5a176e..a3d43ea11 100644--- a/apps/server/src/observability/LocalFileTracer.ts+++ b/apps/server/src/observability/LocalFileTracer.ts@@ -1,7 +1,8 @@import type * as Exit from "effect/Exit";import { Effect, Option, Tracer } from "effect";-import { EffectTraceRecord, spanToTraceRecord } from "./TraceRecord.ts";+import { spanToTraceRecord } from "./TraceRecord.ts";+import type { EffectTraceRecord } from "./TraceRecord.ts";import { makeTraceSink, type TraceSink } from "./TraceSink.ts";export interface LocalFileTracerOptions {@@ -27,12 +28,16 @@ class LocalFileSpan implements Tracer.Span {status: Tracer.SpanStatus;attributes: Map<string, unknown>;events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;+ private readonly delegate: Tracer.Span;+ private readonly push: (record: EffectTraceRecord) => void;constructor(options: Parameters<Tracer.Tracer["span"]>[0],- private readonly delegate: Tracer.Span,- private readonly push: (record: EffectTraceRecord) => void,+ delegate: Tracer.Span,+ push: (record: EffectTraceRecord) => void,) {+ this.delegate = delegate;+ this.push = push;this.name = delegate.name;this.spanId = delegate.spanId;this.traceId = delegate.traceId;diff --git a/apps/server/src/open.test.ts b/apps/server/src/open.test.tsindex 382daab2d..77e85072a 100644--- a/apps/server/src/open.test.ts+++ b/apps/server/src/open.test.ts@@ -8,7 +8,7 @@ import {launchDetached,resolveAvailableEditors,resolveEditorLaunch,-} from "./open";+} from "./open.ts";it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {it.effect("returns commands for command-based editors", () =>diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.tsindex 0b1b203ba..71445b467 100644--- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts@@ -21,8 +21,8 @@ import { ProviderService } from "../../provider/Services/ProviderService.ts";import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";-import { CheckpointStoreError } from "../../checkpointing/Errors.ts";-import { OrchestrationDispatchError } from "../Errors.ts";+import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";+import type { OrchestrationDispatchError } from "../Errors.ts";import { isGitRepository } from "../../git/Utils.ts";import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.tsindex e4e772dc7..db2bd2d43 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts@@ -19,7 +19,8 @@ import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";import { GitCore } from "../../git/Services/GitCore.ts";import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";-import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";+import { ProviderAdapterRequestError } from "../../provider/Errors.ts";+import type { ProviderServiceError } from "../../provider/Errors.ts";import { TextGeneration } from "../../git/Services/TextGeneration.ts";import { ProviderService } from "../../provider/Services/ProviderService.ts";import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";diff --git a/apps/server/src/orchestration/Normalizer.ts b/apps/server/src/orchestration/Normalizer.tsindex 177a23ec0..811d9b8a1 100644--- a/apps/server/src/orchestration/Normalizer.ts+++ b/apps/server/src/orchestration/Normalizer.ts@@ -6,10 +6,10 @@ import {PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,} from "@t3tools/contracts";-import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore";-import { ServerConfig } from "../config";-import { parseBase64DataUrl } from "../imageMime";-import { WorkspacePaths } from "../workspace/Services/WorkspacePaths";+import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";+import { ServerConfig } from "../config.ts";+import { parseBase64DataUrl } from "../imageMime.ts";+import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>Effect.gen(function* () {diff --git a/apps/server/src/os-jank.test.ts b/apps/server/src/os-jank.test.tsindex 89eba62d2..9006644bd 100644--- a/apps/server/src/os-jank.test.ts+++ b/apps/server/src/os-jank.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from "vitest";-import { fixPath } from "./os-jank";+import { fixPath } from "./os-jank.ts";describe("fixPath", () => {it("hydrates PATH on linux using the resolved login shell", () => {diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.tsindex dd909116d..15ad4daf0 100644--- a/apps/server/src/processRunner.test.ts+++ b/apps/server/src/processRunner.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { runProcess } from "./processRunner";+import { runProcess } from "./processRunner.ts";describe("runProcess", () => {it("fails when output exceeds max buffer in default mode", async () => {diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.tsindex b59ac444c..8caeda073 100644--- a/apps/server/src/provider/Layers/ClaudeAdapter.ts+++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts@@ -17,7 +17,7 @@ import {type SDKResultMessage,type SettingSource,type SDKUserMessage,- ModelUsage,+ type ModelUsage,} from "@anthropic-ai/claude-agent-sdk";import { parseCliArgs } from "@t3tools/shared/cliArgs";import {diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.tsindex f76c4250e..c6135fe24 100644--- a/apps/server/src/provider/Layers/ClaudeProvider.ts+++ b/apps/server/src/provider/Layers/ClaudeProvider.ts@@ -25,11 +25,11 @@ import {providerModelsFromSettings,spawnAndCollect,type CommandResult,-} from "../providerSnapshot";-import { compareCliVersions } from "../cliVersion";-import { makeManagedServerProvider } from "../makeManagedServerProvider";-import { ClaudeProvider } from "../Services/ClaudeProvider";-import { ServerSettingsService } from "../../serverSettings";+} from "../providerSnapshot.ts";+import { compareCliVersions } from "../cliVersion.ts";+import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";+import { ClaudeProvider } from "../Services/ClaudeProvider.ts";+import { ServerSettingsService } from "../../serverSettings.ts";import { ServerSettingsError } from "@t3tools/contracts";const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = {diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.tsindex d3f8c742e..de4aceeac 100644--- a/apps/server/src/provider/Layers/CodexProvider.ts+++ b/apps/server/src/provider/Layers/CodexProvider.ts@@ -32,22 +32,22 @@ import {providerModelsFromSettings,spawnAndCollect,type CommandResult,-} from "../providerSnapshot";-import { makeManagedServerProvider } from "../makeManagedServerProvider";+} from "../providerSnapshot.ts";+import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";import {formatCodexCliUpgradeMessage,isCodexCliVersionSupported,parseCodexCliVersion,-} from "../codexCliVersion";+} from "../codexCliVersion.ts";import {adjustCodexModelsForAccount,codexAuthSubLabel,codexAuthSubType,type CodexAccountSnapshot,-} from "../codexAccount";-import { probeCodexDiscovery } from "../codexAppServer";-import { CodexProvider } from "../Services/CodexProvider";-import { ServerSettingsService } from "../../serverSettings";+} from "../codexAccount.ts";+import { probeCodexDiscovery } from "../codexAppServer.ts";+import { CodexProvider } from "../Services/CodexProvider.ts";+import { ServerSettingsService } from "../../serverSettings.ts";import { ServerSettingsError } from "@t3tools/contracts";const DEFAULT_CODEX_MODEL_CAPABILITIES: ModelCapabilities = {diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.tsindex db0293f0f..953a49fe2 100644--- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts+++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts@@ -4,8 +4,10 @@ import { assertFailure } from "@effect/vitest/utils";import { Effect, Layer, Stream } from "effect";-import { ClaudeAdapter, ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";-import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts";+import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";+import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";+import { CodexAdapter } from "../Services/CodexAdapter.ts";+import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";import { ProviderUnsupportedError } from "../Errors.ts";diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.tsindex d03fffe82..170521d2d 100644--- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts+++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts@@ -28,12 +28,12 @@ import {hasCustomModelProvider,parseAuthStatusFromOutput,readCodexConfigModelProvider,-} from "./CodexProvider";-import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider";-import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry";-import { ServerConfig } from "../../config";-import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings";-import { ProviderRegistry } from "../Services/ProviderRegistry";+} from "./CodexProvider.ts";+import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts";+import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry.ts";+import { ServerConfig } from "../../config.ts";+import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";+import { ProviderRegistry } from "../Services/ProviderRegistry.ts";// ── Test helpers ────────────────────────────────────────────────────diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.tsindex 41bb81e74..62207ff07 100644--- a/apps/server/src/provider/Layers/ProviderRegistry.ts+++ b/apps/server/src/provider/Layers/ProviderRegistry.ts@@ -6,14 +6,14 @@import type { ProviderKind, ServerProvider } from "@t3tools/contracts";import { Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";-import { ServerConfig } from "../../config";-import { ClaudeProviderLive } from "./ClaudeProvider";-import { CodexProviderLive } from "./CodexProvider";-import type { ClaudeProviderShape } from "../Services/ClaudeProvider";-import { ClaudeProvider } from "../Services/ClaudeProvider";-import type { CodexProviderShape } from "../Services/CodexProvider";-import { CodexProvider } from "../Services/CodexProvider";-import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry";+import { ServerConfig } from "../../config.ts";+import { ClaudeProviderLive } from "./ClaudeProvider.ts";+import { CodexProviderLive } from "./CodexProvider.ts";+import type { ClaudeProviderShape } from "../Services/ClaudeProvider.ts";+import { ClaudeProvider } from "../Services/ClaudeProvider.ts";+import type { CodexProviderShape } from "../Services/CodexProvider.ts";+import { CodexProvider } from "../Services/CodexProvider.ts";+import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";import {hydrateCachedProvider,PROVIDER_CACHE_IDS,@@ -21,7 +21,7 @@ import {readProviderStatusCache,resolveProviderStatusCachePath,writeProviderStatusCache,-} from "../providerStatusCache";+} from "../providerStatusCache.ts";const loadProviders = (codexProvider: CodexProviderShape,diff --git a/apps/server/src/provider/Services/ClaudeProvider.ts b/apps/server/src/provider/Services/ClaudeProvider.tsindex 7f90c549c..7e21ac56d 100644--- a/apps/server/src/provider/Services/ClaudeProvider.ts+++ b/apps/server/src/provider/Services/ClaudeProvider.ts@@ -1,6 +1,6 @@import { Context } from "effect";-import type { ServerProviderShape } from "./ServerProvider";+import type { ServerProviderShape } from "./ServerProvider.ts";export interface ClaudeProviderShape extends ServerProviderShape {}diff --git a/apps/server/src/provider/Services/CodexProvider.ts b/apps/server/src/provider/Services/CodexProvider.tsindex 6820d4cb4..e116f1a76 100644--- a/apps/server/src/provider/Services/CodexProvider.ts+++ b/apps/server/src/provider/Services/CodexProvider.ts@@ -1,6 +1,6 @@import { Context } from "effect";-import type { ServerProviderShape } from "./ServerProvider";+import type { ServerProviderShape } from "./ServerProvider.ts";export interface CodexProviderShape extends ServerProviderShape {}diff --git a/apps/server/src/provider/cliVersion.test.ts b/apps/server/src/provider/cliVersion.test.tsindex a9c1721c4..ffb42cf5c 100644--- a/apps/server/src/provider/cliVersion.test.ts+++ b/apps/server/src/provider/cliVersion.test.ts@@ -1,6 +1,6 @@import { assert, describe, it } from "@effect/vitest";-import { compareCliVersions, normalizeCliVersion } from "./cliVersion";+import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts";describe("cliVersion", () => {it("normalizes versions with a missing patch segment", () => {diff --git a/apps/server/src/provider/codexAppServer.ts b/apps/server/src/provider/codexAppServer.tsindex 7b3c9eeb7..24a9e29c5 100644--- a/apps/server/src/provider/codexAppServer.ts+++ b/apps/server/src/provider/codexAppServer.ts@@ -1,7 +1,7 @@import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";import readline from "node:readline";import type { ServerProviderSkill } from "@t3tools/contracts";-import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";+import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount.ts";interface JsonRpcProbeResponse {readonly id?: unknown;diff --git a/apps/server/src/provider/codexCliVersion.ts b/apps/server/src/provider/codexCliVersion.tsindex 871948335..33f7cf85d 100644--- a/apps/server/src/provider/codexCliVersion.ts+++ b/apps/server/src/provider/codexCliVersion.ts@@ -1,4 +1,4 @@-import { compareCliVersions, normalizeCliVersion } from "./cliVersion";+import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts";const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/;diff --git a/apps/server/src/provider/makeManagedServerProvider.ts b/apps/server/src/provider/makeManagedServerProvider.tsindex 856594c1f..1d3bf52f4 100644--- a/apps/server/src/provider/makeManagedServerProvider.ts+++ b/apps/server/src/provider/makeManagedServerProvider.ts@@ -2,7 +2,7 @@ import type { ServerProvider } from "@t3tools/contracts";import { Duration, Effect, PubSub, Ref, Scope, Stream } from "effect";import * as Semaphore from "effect/Semaphore";-import type { ServerProviderShape } from "./Services/ServerProvider";+import type { ServerProviderShape } from "./Services/ServerProvider.ts";import { ServerSettingsError } from "@t3tools/contracts";export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <diff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.tsindex 40246563a..068b7c115 100644--- a/apps/server/src/provider/providerSnapshot.ts+++ b/apps/server/src/provider/providerSnapshot.ts@@ -10,7 +10,7 @@ import type {import { Effect, Stream } from "effect";import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";import { normalizeModelSlug } from "@t3tools/shared/model";-import { isWindowsCommandNotFound } from "../processRunner";+import { isWindowsCommandNotFound } from "../processRunner.ts";export const DEFAULT_TIMEOUT_MS = 4_000;diff --git a/apps/server/src/provider/providerStatusCache.test.ts b/apps/server/src/provider/providerStatusCache.test.tsindex 5f0d88322..a82cb4ae5 100644--- a/apps/server/src/provider/providerStatusCache.test.ts+++ b/apps/server/src/provider/providerStatusCache.test.ts@@ -8,7 +8,7 @@ import {readProviderStatusCache,resolveProviderStatusCachePath,writeProviderStatusCache,-} from "./providerStatusCache";+} from "./providerStatusCache.ts";const makeProvider = (provider: ServerProvider["provider"],diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 71d7d8892..50d2d62aa 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -1,7 +1,7 @@import { Effect, Layer } from "effect";import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";-import { ServerConfig } from "./config";+import { ServerConfig } from "./config.ts";import {attachmentsRouteLayer,otlpTracesProxyRouteLayer,@@ -9,46 +9,46 @@ import {serverEnvironmentRouteLayer,staticAndDevRouteLayer,browserApiCorsLayer,-} from "./http";-import { fixPath } from "./os-jank";-import { websocketRpcRouteLayer } from "./ws";-import { OpenLive } from "./open";-import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite";-import { ServerLifecycleEventsLive } from "./serverLifecycleEvents";-import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";-import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger";-import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";-import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime";-import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";-import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";-import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";-import { makeProviderServiceLive } from "./provider/Layers/ProviderService";-import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper";-import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";-import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";-import { GitCoreLive } from "./git/Layers/GitCore";-import { GitHubCliLive } from "./git/Layers/GitHubCli";-import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster";-import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration";-import { TerminalManagerLive } from "./terminal/Layers/Manager";-import { GitManagerLive } from "./git/Layers/GitManager";-import { KeybindingsLive } from "./keybindings";-import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup";-import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor";-import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus";-import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";-import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor";-import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor";-import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry";-import { ServerSettingsLive } from "./serverSettings";-import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver";-import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver";-import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries";-import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem";-import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";-import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner";-import { ObservabilityLive } from "./observability/Layers/Observability";-import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment";+} from "./http.ts";+import { fixPath } from "./os-jank.ts";+import { websocketRpcRouteLayer } from "./ws.ts";+import { OpenLive } from "./open.ts";+import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";+import { ServerLifecycleEventsLive } from "./serverLifecycleEvents.ts";+import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService.ts";+import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger.ts";+import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";+import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime.ts";+import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter.ts";+import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter.ts";+import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";+import { makeProviderServiceLive } from "./provider/Layers/ProviderService.ts";+import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";+import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts";+import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts";+import { GitCoreLive } from "./git/Layers/GitCore.ts";+import { GitHubCliLive } from "./git/Layers/GitHubCli.ts";+import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts";+import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration.ts";+import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";+import { GitManagerLive } from "./git/Layers/GitManager.ts";+import { KeybindingsLive } from "./keybindings.ts";+import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup.ts";+import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor.ts";+import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus.ts";+import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion.ts";+import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts";+import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";+import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";+import { ServerSettingsLive } from "./serverSettings.ts";+import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";+import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";+import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";+import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";+import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";+import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";+import { ObservabilityLive } from "./observability/Layers/Observability.ts";+import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts";import {authBearerBootstrapRouteLayer,authBootstrapRouteLayer,@@ -60,27 +60,27 @@ import {authPairingCredentialRouteLayer,authSessionRouteLayer,authWebSocketTokenRouteLayer,-} from "./auth/http";-import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore";-import { ServerAuthLive } from "./auth/Layers/ServerAuth";-import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";+} from "./auth/http.ts";+import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";+import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";+import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";import {clearPersistedServerRuntimeState,makePersistedServerRuntimeState,persistServerRuntimeState,-} from "./serverRuntimeState";+} from "./serverRuntimeState.ts";import {orchestrationDispatchRouteLayer,orchestrationSnapshotRouteLayer,-} from "./orchestration/http";+} from "./orchestration/http.ts";const PtyAdapterLive = Layer.unwrap(Effect.gen(function* () {if (typeof Bun !== "undefined") {- const BunPTY = yield* Effect.promise(() => import("./terminal/Layers/BunPTY"));+ const BunPTY = yield* Effect.promise(() => import("./terminal/Layers/BunPTY.ts"));return BunPTY.layer;} else {- const NodePTY = yield* Effect.promise(() => import("./terminal/Layers/NodePTY"));+ const NodePTY = yield* Effect.promise(() => import("./terminal/Layers/NodePTY.ts"));return NodePTY.layer;}}),diff --git a/apps/server/src/serverLogger.ts b/apps/server/src/serverLogger.tsindex ea098dcbb..57d51b2a9 100644--- a/apps/server/src/serverLogger.ts+++ b/apps/server/src/serverLogger.ts@@ -1,6 +1,6 @@import { Effect, Logger, References, Layer } from "effect";-import { ServerConfig } from "./config";+import { ServerConfig } from "./config.ts";export const ServerLoggerLive = Effect.gen(function* () {const config = yield* ServerConfig;diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.tsindex 919da67b7..99728f681 100644--- a/apps/server/src/serverRuntimeStartup.ts+++ b/apps/server/src/serverRuntimeStartup.ts@@ -21,24 +21,24 @@ import {Console,} from "effect";-import { ServerConfig } from "./config";-import { Keybindings } from "./keybindings";-import { Open } from "./open";-import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";-import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";-import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";-import { ServerLifecycleEvents } from "./serverLifecycleEvents";-import { ServerSettingsService } from "./serverSettings";-import { ServerEnvironment } from "./environment/Services/ServerEnvironment";-import { AnalyticsService } from "./telemetry/Services/AnalyticsService";-import { ServerAuth } from "./auth/Services/ServerAuth";-import { ProviderSessionReaper } from "./provider/Services/ProviderSessionReaper";+import { ServerConfig } from "./config.ts";+import { Keybindings } from "./keybindings.ts";+import { Open } from "./open.ts";+import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";+import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";+import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor.ts";+import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts";+import { ServerSettingsService } from "./serverSettings.ts";+import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";+import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";+import { ServerAuth } from "./auth/Services/ServerAuth.ts";+import { ProviderSessionReaper } from "./provider/Services/ProviderSessionReaper.ts";import {formatHeadlessServeOutput,formatHostForUrl,isWildcardHost,issueHeadlessServeAccessInfo,-} from "./startupAccess";+} from "./startupAccess.ts";export class ServerRuntimeStartupError extends Data.TaggedError("ServerRuntimeStartupError")<{readonly message: string;diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.tsindex 00c838446..569e4ac11 100644--- a/apps/server/src/serverRuntimeState.ts+++ b/apps/server/src/serverRuntimeState.ts@@ -1,7 +1,7 @@import { Effect, FileSystem, Option, Path, Schema } from "effect";-import { type ServerConfigShape } from "./config";-import { formatHostForUrl, isWildcardHost } from "./startupAccess";+import { type ServerConfigShape } from "./config.ts";+import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts";export const PersistedServerRuntimeState = Schema.Struct({version: Schema.Literal(1),diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.tsindex 26479d61b..406e1e850 100644--- a/apps/server/src/serverSettings.test.ts+++ b/apps/server/src/serverSettings.test.ts@@ -2,8 +2,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import { DEFAULT_SERVER_SETTINGS, ServerSettingsPatch } from "@t3tools/contracts";import { assert, it } from "@effect/vitest";import { Effect, FileSystem, Layer, Schema } from "effect";-import { ServerConfig } from "./config";-import { ServerSettingsLive, ServerSettingsService } from "./serverSettings";+import { ServerConfig } from "./config.ts";+import { ServerSettingsLive, ServerSettingsService } from "./serverSettings.ts";const makeServerSettingsLayer = () =>ServerSettingsLive.pipe(diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.tsindex bdb1d5e0e..d5636d5c0 100644--- a/apps/server/src/serverSettings.ts+++ b/apps/server/src/serverSettings.ts@@ -39,7 +39,7 @@ import {Cause,} from "effect";import * as Semaphore from "effect/Semaphore";-import { ServerConfig } from "./config";+import { ServerConfig } from "./config.ts";import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";import { fromLenientJson } from "@t3tools/shared/schemaJson";import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.tsindex ef6ece31e..03c01170f 100644--- a/apps/server/src/startupAccess.test.ts+++ b/apps/server/src/startupAccess.test.ts@@ -7,7 +7,7 @@ import {resolveHeadlessConnectionHost,resolveHeadlessConnectionString,resolveListeningPort,-} from "./startupAccess";+} from "./startupAccess.ts";it("prefers localhost when no explicit host is configured", () => {expect(resolveHeadlessConnectionHost(undefined)).toBe("localhost");diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.tsindex a350d729d..327919014 100644--- a/apps/server/src/startupAccess.ts+++ b/apps/server/src/startupAccess.ts@@ -4,8 +4,8 @@ import { QrCode } from "@t3tools/shared/qrCode";import { Effect } from "effect";import { HttpServer } from "effect/unstable/http";-import { ServerConfig } from "./config";-import { ServerAuth } from "./auth/Services/ServerAuth";+import { ServerConfig } from "./config.ts";+import { ServerAuth } from "./auth/Services/ServerAuth.ts";export interface HeadlessServeAccessInfo {readonly connectionString: string;diff --git a/apps/server/src/telemetry/Identify.ts b/apps/server/src/telemetry/Identify.tsindex d7784eb88..e81393bbb 100644--- a/apps/server/src/telemetry/Identify.ts+++ b/apps/server/src/telemetry/Identify.ts@@ -1,7 +1,7 @@import { Effect, FileSystem, Path, Random, Schema } from "effect";import * as Crypto from "node:crypto";import { homedir } from "node:os";-import { ServerConfig } from "../config";+import { ServerConfig } from "../config.ts";const CodexAuthJsonSchema = Schema.Struct({tokens: Schema.Struct({diff --git a/apps/server/src/telemetry/Layers/AnalyticsService.ts b/apps/server/src/telemetry/Layers/AnalyticsService.tsindex e933576df..9067b71a5 100644--- a/apps/server/src/telemetry/Layers/AnalyticsService.ts+++ b/apps/server/src/telemetry/Layers/AnalyticsService.ts@@ -13,7 +13,7 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstabimport { ServerConfig } from "../../config.ts";import { AnalyticsService, type AnalyticsServiceShape } from "../Services/AnalyticsService.ts";import { getTelemetryIdentifier } from "../Identify.ts";-import { version } from "../../../package.json" with { type: "json" };+import packageJson from "../../../package.json" with { type: "json" };interface BufferedAnalyticsEvent {readonly event: string;@@ -86,7 +86,7 @@ const makeAnalyticsService = Effect.gen(function* () {platform: process.platform,wsl: process.env.WSL_DISTRO_NAME,arch: process.arch,- t3CodeVersion: version,+ t3CodeVersion: packageJson.version,clientType,},timestamp: event.capturedAt,diff --git a/apps/server/src/terminal/Layers/BunPTY.ts b/apps/server/src/terminal/Layers/BunPTY.tsindex 1fb4bdd63..f0aab813c 100644--- a/apps/server/src/terminal/Layers/BunPTY.ts+++ b/apps/server/src/terminal/Layers/BunPTY.ts@@ -1,13 +1,16 @@import { Effect, Layer } from "effect";-import { PtyAdapter, PtyAdapterShape, PtyExitEvent, PtyProcess } from "../Services/PTY";+import { PtyAdapter } from "../Services/PTY.ts";+import type { PtyAdapterShape, PtyExitEvent, PtyProcess } from "../Services/PTY.ts";class BunPtyProcess implements PtyProcess {private readonly dataListeners = new Set<(data: string) => void>();private readonly exitListeners = new Set<(event: PtyExitEvent) => void>();private readonly decoder = new TextDecoder();+ private readonly process: Bun.Subprocess;private didExit = false;- constructor(private readonly process: Bun.Subprocess) {+ constructor(process: Bun.Subprocess) {+ this.process = process;void this.process.exited.then((exitCode) => {this.emitExit({diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.tsindex 8207861e2..cce0a1627 100644--- a/apps/server/src/terminal/Layers/Manager.test.ts+++ b/apps/server/src/terminal/Layers/Manager.test.ts@@ -24,25 +24,28 @@ import {import { TestClock } from "effect/testing";import { expect } from "vitest";-import type { TerminalManagerShape } from "../Services/Manager";+import type { TerminalManagerShape } from "../Services/Manager.ts";import {type PtyAdapterShape,type PtyExitEvent,type PtyProcess,type PtySpawnInput,PtySpawnError,-} from "../Services/PTY";-import { makeTerminalManagerWithOptions } from "./Manager";+} from "../Services/PTY.ts";+import { makeTerminalManagerWithOptions } from "./Manager.ts";class FakePtyProcess implements PtyProcess {readonly writes: string[] = [];readonly resizeCalls: Array<{ cols: number; rows: number }> = [];readonly killSignals: Array<string | undefined> = [];+ readonly pid: number;private readonly dataListeners = new Set<(data: string) => void>();private readonly exitListeners = new Set<(event: PtyExitEvent) => void>();killed = false;- constructor(readonly pid: number) {}+ constructor(pid: number) {+ this.pid = pid;+ }write(data: string): void {this.writes.push(data);@@ -88,9 +91,12 @@ class FakePtyAdapter implements PtyAdapterShape {readonly spawnInputs: PtySpawnInput[] = [];readonly processes: FakePtyProcess[] = [];readonly spawnFailures: Error[] = [];+ private readonly mode: "sync" | "async";private nextPid = 9000;- constructor(private readonly mode: "sync" | "async" = "sync") {}+ constructor(mode: "sync" | "async" = "sync") {+ this.mode = mode;+ }spawn(input: PtySpawnInput): Effect.Effect<PtyProcess, PtySpawnError> {this.spawnInputs.push(input);diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.tsindex 4bdeba68e..409e4397c 100644--- a/apps/server/src/terminal/Layers/Manager.ts+++ b/apps/server/src/terminal/Layers/Manager.ts@@ -22,13 +22,13 @@ import {SynchronizedRef,} from "effect";-import { ServerConfig } from "../../config";+import { ServerConfig } from "../../config.ts";import {increment,terminalRestartsTotal,terminalSessionsTotal,-} from "../../observability/Metrics";-import { runProcess } from "../../processRunner";+} from "../../observability/Metrics.ts";+import { runProcess } from "../../processRunner.ts";import {TerminalCwdError,TerminalHistoryError,@@ -36,14 +36,14 @@ import {TerminalNotRunningError,TerminalSessionLookupError,type TerminalManagerShape,-} from "../Services/Manager";+} from "../Services/Manager.ts";import {PtyAdapter,PtySpawnError,type PtyAdapterShape,type PtyExitEvent,type PtyProcess,-} from "../Services/PTY";+} from "../Services/PTY.ts";const DEFAULT_HISTORY_LINE_LIMIT = 5_000;const DEFAULT_PERSIST_DEBOUNCE_MS = 40;diff --git a/apps/server/src/terminal/Layers/NodePTY.test.ts b/apps/server/src/terminal/Layers/NodePTY.test.tsindex 58fcc70e4..06f186312 100644--- a/apps/server/src/terminal/Layers/NodePTY.test.ts+++ b/apps/server/src/terminal/Layers/NodePTY.test.ts@@ -1,7 +1,7 @@import { FileSystem, Path, Effect } from "effect";import { assert, it } from "@effect/vitest";-import { ensureNodePtySpawnHelperExecutable } from "./NodePTY";+import { ensureNodePtySpawnHelperExecutable } from "./NodePTY.ts";import * as NodeServices from "@effect/platform-node/NodeServices";it.layer(NodeServices.layer)("ensureNodePtySpawnHelperExecutable", (it) => {diff --git a/apps/server/src/terminal/Layers/NodePTY.ts b/apps/server/src/terminal/Layers/NodePTY.tsindex cf1fdd219..67aecb9fa 100644--- a/apps/server/src/terminal/Layers/NodePTY.ts+++ b/apps/server/src/terminal/Layers/NodePTY.ts@@ -1,7 +1,8 @@import { createRequire } from "node:module";import { Effect, FileSystem, Layer, Path } from "effect";-import { PtyAdapter, PtyAdapterShape, PtyExitEvent, PtyProcess } from "../Services/PTY";+import { PtyAdapter } from "../Services/PTY.ts";+import type { PtyAdapterShape, PtyExitEvent, PtyProcess } from "../Services/PTY.ts";let didEnsureSpawnHelperExecutable = false;@@ -46,7 +47,11 @@ export const ensureNodePtySpawnHelperExecutable = Effect.fn(function* (explicitP});class NodePtyProcess implements PtyProcess {- constructor(private readonly process: import("node-pty").IPty) {}+ private readonly process: import("node-pty").IPty;++ constructor(process: import("node-pty").IPty) {+ this.process = process;+ }get pid(): number {return this.process.pid;diff --git a/apps/server/src/terminal/Services/Manager.ts b/apps/server/src/terminal/Services/Manager.tsindex b59c4721c..fb7a7da7b 100644--- a/apps/server/src/terminal/Services/Manager.ts+++ b/apps/server/src/terminal/Services/Manager.ts@@ -22,7 +22,7 @@ import {TerminalSessionStatus,TerminalWriteInput,} from "@t3tools/contracts";-import { PtyProcess } from "./PTY";+import type { PtyProcess } from "./PTY.ts";import { Effect, Context } from "effect";export {diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex ff9592b5b..aac716cfe 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -27,42 +27,42 @@ import { clamp } from "effect/Number";import { HttpRouter, HttpServerRequest } from "effect/unstable/http";import { RpcSerialization, RpcServer } from "effect/unstable/rpc";-import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";-import { ServerConfig } from "./config";-import { GitCore } from "./git/Services/GitCore";-import { GitManager } from "./git/Services/GitManager";-import { GitStatusBroadcaster } from "./git/Services/GitStatusBroadcaster";-import { Keybindings } from "./keybindings";-import { Open, resolveAvailableEditors } from "./open";-import { normalizeDispatchCommand } from "./orchestration/Normalizer";-import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";-import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";+import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery.ts";+import { ServerConfig } from "./config.ts";+import { GitCore } from "./git/Services/GitCore.ts";+import { GitManager } from "./git/Services/GitManager.ts";+import { GitStatusBroadcaster } from "./git/Services/GitStatusBroadcaster.ts";+import { Keybindings } from "./keybindings.ts";+import { Open, resolveAvailableEditors } from "./open.ts";+import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";+import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";+import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";import {observeRpcEffect,observeRpcStream,observeRpcStreamEffect,-} from "./observability/RpcInstrumentation";-import { ProviderRegistry } from "./provider/Services/ProviderRegistry";-import { ServerLifecycleEvents } from "./serverLifecycleEvents";-import { ServerRuntimeStartup } from "./serverRuntimeStartup";-import { ServerSettingsService } from "./serverSettings";-import { TerminalManager } from "./terminal/Services/Manager";-import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries";-import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem";-import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths";-import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner";-import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver";-import { ServerEnvironment } from "./environment/Services/ServerEnvironment";-import { ServerAuth } from "./auth/Services/ServerAuth";+} from "./observability/RpcInstrumentation.ts";+import { ProviderRegistry } from "./provider/Services/ProviderRegistry.ts";+import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts";+import { ServerRuntimeStartup } from "./serverRuntimeStartup.ts";+import { ServerSettingsService } from "./serverSettings.ts";+import { TerminalManager } from "./terminal/Services/Manager.ts";+import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";+import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";+import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths.ts";+import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts";+import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";+import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";+import { ServerAuth } from "./auth/Services/ServerAuth.ts";import {BootstrapCredentialService,type BootstrapCredentialChange,-} from "./auth/Services/BootstrapCredentialService";+} from "./auth/Services/BootstrapCredentialService.ts";import {SessionCredentialService,type SessionCredentialChange,-} from "./auth/Services/SessionCredentialService";-import { respondToAuthError } from "./auth/http";+} from "./auth/Services/SessionCredentialService.ts";+import { respondToAuthError } from "./auth/http.ts";function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<OrchestrationEvent,diff --git a/apps/server/tsconfig.json b/apps/server/tsconfig.jsonindex 07d52467f..c19bdbf45 100644--- a/apps/server/tsconfig.json+++ b/apps/server/tsconfig.json@@ -3,9 +3,7 @@"compilerOptions": {"composite": true,"types": ["node", "bun"],- "lib": ["ES2023", "esnext.disposable"],- "noEmit": true,- "allowImportingTsExtensions": true,+ "lib": ["ESNext", "esnext.disposable"],"plugins": [{"name": "@effect/language-service",diff --git a/apps/server/vitest.config.ts b/apps/server/vitest.config.tsindex 1c5b2f0d3..660d69423 100644--- a/apps/server/vitest.config.ts+++ b/apps/server/vitest.config.ts@@ -1,6 +1,6 @@import { defineConfig, mergeConfig } from "vitest/config";-import baseConfig from "../../vitest.config";+import baseConfig from "../../vitest.config.ts";export default mergeConfig(baseConfig,diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.jsonindex 178f4bcba..4dd68d721 100644--- a/apps/web/tsconfig.json+++ b/apps/web/tsconfig.json@@ -2,6 +2,10 @@"extends": "../../tsconfig.base.json","compilerOptions": {"composite": true,+ "module": "Preserve",+ "moduleResolution": "Bundler",+ "erasableSyntaxOnly": false,+ "verbatimModuleSyntax": false,"jsx": "react-jsx","lib": ["ES2023", "DOM", "DOM.Iterable"],"types": ["vite/client"],diff --git a/docs/observability.md b/docs/observability.mdindex dde109357..5b98d1163 100644--- a/docs/observability.md+++ b/docs/observability.md@@ -69,11 +69,11 @@ npx t3``````bash-bun dev+node --run dev``````bash-bun dev:desktop+node --run dev:desktop```### Option 2: Run With A Local LGTM Stack@@ -122,13 +122,13 @@ npx t3Monorepo web/server dev:```bash-bun dev+node --run dev```Monorepo desktop dev:```bash-bun dev:desktop+node --run dev:desktop```Packaged desktop app:diff --git a/package.json b/package.jsonindex ade7bcce4..9e412b5ba 100644--- a/package.json+++ b/package.json@@ -33,14 +33,13 @@"start": "turbo run start --filter=t3","start:desktop": "turbo run start --filter=@t3tools/desktop","start:marketing": "turbo run preview --filter=@t3tools/marketing",- "start:mock-update-server": "bun run scripts/mock-update-server.ts",+ "start:mock-update-server": "node scripts/mock-update-server.ts","build": "turbo run build","build:marketing": "turbo run build --filter=@t3tools/marketing","build:desktop": "turbo run build --filter=@t3tools/desktop --filter=t3","typecheck": "turbo run typecheck","lint": "oxlint --report-unused-disable-directives","test": "turbo run test",- "test:process-reaper": "bun run --cwd apps/server test:process-reaper","test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop","fmt": "oxfmt","fmt:check": "oxfmt --check",diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.tsindex 5dd6b9afa..9ca76328a 100644--- a/packages/client-runtime/src/index.ts+++ b/packages/client-runtime/src/index.ts@@ -1,2 +1,2 @@-export * from "./knownEnvironment";-export * from "./scoped";+export * from "./knownEnvironment.ts";+export * from "./scoped.ts";diff --git a/packages/client-runtime/src/knownEnvironment.test.ts b/packages/client-runtime/src/knownEnvironment.test.tsindex dca56c1e6..a40161e9b 100644--- a/packages/client-runtime/src/knownEnvironment.test.ts+++ b/packages/client-runtime/src/knownEnvironment.test.ts@@ -1,7 +1,7 @@import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";import { describe, expect, it } from "vitest";-import { createKnownEnvironment, getKnownEnvironmentHttpBaseUrl } from "./knownEnvironment";+import { createKnownEnvironment, getKnownEnvironmentHttpBaseUrl } from "./knownEnvironment.ts";import {parseScopedProjectKey,parseScopedThreadKey,@@ -10,7 +10,7 @@ import {scopedThreadKey,scopeProjectRef,scopeThreadRef,-} from "./scoped";+} from "./scoped.ts";describe("known environment bootstrap helpers", () => {it("creates known environments from explicit server base urls", () => {diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.tsindex 73327a45a..8110104e1 100644--- a/packages/contracts/src/auth.ts+++ b/packages/contracts/src/auth.ts@@ -1,6 +1,6 @@import { Schema } from "effect";-import { AuthSessionId, TrimmedNonEmptyString } from "./baseSchemas";+import { AuthSessionId, TrimmedNonEmptyString } from "./baseSchemas.ts";/*** Declares the server's overall authentication posture.diff --git a/packages/contracts/src/editor.ts b/packages/contracts/src/editor.tsindex 569f096df..8444e8b10 100644--- a/packages/contracts/src/editor.ts+++ b/packages/contracts/src/editor.ts@@ -1,5 +1,5 @@import { Schema } from "effect";-import { TrimmedNonEmptyString } from "./baseSchemas";+import { TrimmedNonEmptyString } from "./baseSchemas.ts";export const EditorLaunchStyle = Schema.Literals(["direct-path", "goto", "line-column"]);export type EditorLaunchStyle = typeof EditorLaunchStyle.Type;diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 28adbf217..aa34c339a 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -1,6 +1,6 @@import { Effect, Schema } from "effect";-import { EnvironmentId, ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas";+import { EnvironmentId, ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";export const ExecutionEnvironmentPlatformOs = Schema.Literals(["darwin",diff --git a/packages/contracts/src/filesystem.ts b/packages/contracts/src/filesystem.tsindex 41b1eb2b6..a518e2e9a 100644--- a/packages/contracts/src/filesystem.ts+++ b/packages/contracts/src/filesystem.ts@@ -1,5 +1,5 @@import { Schema } from "effect";-import { TrimmedNonEmptyString } from "./baseSchemas";+import { TrimmedNonEmptyString } from "./baseSchemas.ts";const FILESYSTEM_PATH_MAX_LENGTH = 512;diff --git a/packages/contracts/src/git.test.ts b/packages/contracts/src/git.test.tsindex d5b2d7dfd..ebd5324fb 100644--- a/packages/contracts/src/git.test.ts+++ b/packages/contracts/src/git.test.ts@@ -7,7 +7,7 @@ import {GitRunStackedActionResult,GitRunStackedActionInput,GitResolvePullRequestResult,-} from "./git";+} from "./git.ts";const decodeCreateWorktreeInput = Schema.decodeUnknownSync(GitCreateWorktreeInput);const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync(diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.tsindex 345208acf..47d74dc35 100644--- a/packages/contracts/src/git.ts+++ b/packages/contracts/src/git.ts@@ -1,5 +1,5 @@import { Schema } from "effect";-import { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas";+import { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;const GIT_LIST_BRANCHES_MAX_LIMIT = 200;diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.tsindex 0f2327d25..47081d8df 100644--- a/packages/contracts/src/index.ts+++ b/packages/contracts/src/index.ts@@ -1,17 +1,17 @@-export * from "./baseSchemas";-export * from "./auth";-export * from "./environment";-export * from "./ipc";-export * from "./terminal";-export * from "./provider";-export * from "./providerRuntime";-export * from "./model";-export * from "./keybindings";-export * from "./server";-export * from "./settings";-export * from "./git";-export * from "./orchestration";-export * from "./editor";-export * from "./project";-export * from "./filesystem";-export * from "./rpc";+export * from "./baseSchemas.ts";+export * from "./auth.ts";+export * from "./environment.ts";+export * from "./ipc.ts";+export * from "./terminal.ts";+export * from "./provider.ts";+export * from "./providerRuntime.ts";+export * from "./model.ts";+export * from "./keybindings.ts";+export * from "./server.ts";+export * from "./settings.ts";+export * from "./git.ts";+export * from "./orchestration.ts";+export * from "./editor.ts";+export * from "./project.ts";+export * from "./filesystem.ts";+export * from "./rpc.ts";diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex e9cc28736..a1abc0fa4 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -17,19 +17,19 @@ import type {GitStatusInput,GitStatusResult,GitCreateBranchResult,-} from "./git";-import type { FilesystemBrowseInput, FilesystemBrowseResult } from "./filesystem";+} from "./git.ts";+import type { FilesystemBrowseInput, FilesystemBrowseResult } from "./filesystem.ts";import type {ProjectSearchEntriesInput,ProjectSearchEntriesResult,ProjectWriteFileInput,ProjectWriteFileResult,-} from "./project";+} from "./project.ts";import type {ServerConfig,ServerProviderUpdatedPayload,ServerUpsertKeybindingResult,-} from "./server";+} from "./server.ts";import type {TerminalClearInput,TerminalCloseInput,@@ -39,8 +39,8 @@ import type {TerminalRestartInput,TerminalSessionSnapshot,TerminalWriteInput,-} from "./terminal";-import type { ServerUpsertKeybindingInput } from "./server";+} from "./terminal.ts";+import type { ServerUpsertKeybindingInput } from "./server.ts";import type {ClientOrchestrationCommand,OrchestrationGetFullThreadDiffInput,@@ -50,10 +50,10 @@ import type {OrchestrationShellStreamItem,OrchestrationSubscribeThreadInput,OrchestrationThreadStreamItem,-} from "./orchestration";-import type { EnvironmentId } from "./baseSchemas";-import { EditorId } from "./editor";-import { ClientSettings, ServerSettings, ServerSettingsPatch } from "./settings";+} from "./orchestration.ts";+import type { EnvironmentId } from "./baseSchemas.ts";+import { EditorId } from "./editor.ts";+import { ServerSettings, type ClientSettings, type ServerSettingsPatch } from "./settings.ts";export interface ContextMenuItem<T extends string = string> {id: T;diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.tsindex 092d5344f..79c2feb8b 100644--- a/packages/contracts/src/keybindings.test.ts+++ b/packages/contracts/src/keybindings.test.ts@@ -7,7 +7,7 @@ import {KeybindingRule,ResolvedKeybindingRule,ResolvedKeybindingsConfig,-} from "./keybindings";+} from "./keybindings.ts";const decode = <S extends Schema.Top>(schema: S,diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.tsindex 72067eac8..1296e74c1 100644--- a/packages/contracts/src/keybindings.ts+++ b/packages/contracts/src/keybindings.ts@@ -1,5 +1,5 @@import { Schema } from "effect";-import { TrimmedString } from "./baseSchemas";+import { TrimmedString } from "./baseSchemas.ts";export const MAX_KEYBINDING_VALUE_LENGTH = 64;const MAX_KEYBINDING_WHEN_LENGTH = 256;diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.tsindex c87224cf2..8e5301598 100644--- a/packages/contracts/src/model.ts+++ b/packages/contracts/src/model.ts@@ -1,6 +1,6 @@import { Schema } from "effect";-import { TrimmedNonEmptyString } from "./baseSchemas";-import type { ProviderKind } from "./orchestration";+import { TrimmedNonEmptyString } from "./baseSchemas.ts";+import type { ProviderKind } from "./orchestration.ts";export const CodexReasoningEffort = Schema.Literals(["xhigh", "high", "medium", "low"]);export type CodexReasoningEffort = typeof CodexReasoningEffort.Type;diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.tsindex ad46e380a..223efd6d2 100644--- a/packages/contracts/src/orchestration.test.ts+++ b/packages/contracts/src/orchestration.test.ts@@ -19,7 +19,7 @@ import {ThreadCreatedPayload,ThreadTurnDiff,ThreadTurnStartRequestedPayload,-} from "./orchestration";+} from "./orchestration.ts";const decodeTurnDiffInput = Schema.decodeUnknownEffect(OrchestrationGetTurnDiffInput);const decodeThreadTurnDiff = Schema.decodeUnknownEffect(ThreadTurnDiff);diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex 2745cdcdb..6cd63ab17 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -1,6 +1,6 @@import { Effect, Option, Schema, SchemaIssue, Struct } from "effect";-import { ClaudeModelOptions, CodexModelOptions } from "./model";-import { RepositoryIdentity } from "./environment";+import { ClaudeModelOptions, CodexModelOptions } from "./model.ts";+import { RepositoryIdentity } from "./environment.ts";import {ApprovalRequestId,CheckpointRef,@@ -14,7 +14,7 @@ import {ThreadId,TrimmedNonEmptyString,TurnId,-} from "./baseSchemas";+} from "./baseSchemas.ts";export const ORCHESTRATION_WS_METHODS = {dispatchCommand: "orchestration.dispatchCommand",diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.tsindex 2851120d1..d089951bc 100644--- a/packages/contracts/src/project.ts+++ b/packages/contracts/src/project.ts@@ -1,5 +1,5 @@import { Schema } from "effect";-import { PositiveInt, TrimmedNonEmptyString } from "./baseSchemas";+import { PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts";const PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;const PROJECT_WRITE_FILE_PATH_MAX_LENGTH = 512;diff --git a/packages/contracts/src/provider.test.ts b/packages/contracts/src/provider.test.tsindex 37469984d..bd20b7e9b 100644--- a/packages/contracts/src/provider.test.ts+++ b/packages/contracts/src/provider.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { Schema } from "effect";-import { ProviderSendTurnInput, ProviderSessionStartInput } from "./provider";+import { ProviderSendTurnInput, ProviderSessionStartInput } from "./provider.ts";const decodeProviderSessionStartInput = Schema.decodeUnknownSync(ProviderSessionStartInput);const decodeProviderSendTurnInput = Schema.decodeUnknownSync(ProviderSendTurnInput);diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.tsindex 16102920d..e27e3aa7e 100644--- a/packages/contracts/src/provider.ts+++ b/packages/contracts/src/provider.ts@@ -1,5 +1,5 @@import { Schema } from "effect";-import { TrimmedNonEmptyString } from "./baseSchemas";+import { TrimmedNonEmptyString } from "./baseSchemas.ts";import {ApprovalRequestId,EventId,@@ -7,7 +7,7 @@ import {ProviderItemId,ThreadId,TurnId,-} from "./baseSchemas";+} from "./baseSchemas.ts";import {ChatAttachment,ModelSelection,@@ -21,7 +21,7 @@ import {ProviderSandboxMode,ProviderUserInputAnswers,RuntimeMode,-} from "./orchestration";+} from "./orchestration.ts";const ProviderSessionStatus = Schema.Literals(["connecting",diff --git a/packages/contracts/src/providerRuntime.test.ts b/packages/contracts/src/providerRuntime.test.tsindex 9d9c395c3..7b822a286 100644--- a/packages/contracts/src/providerRuntime.test.ts+++ b/packages/contracts/src/providerRuntime.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { Schema } from "effect";-import { ProviderRuntimeEvent } from "./providerRuntime";+import { ProviderRuntimeEvent } from "./providerRuntime.ts";const decodeRuntimeEvent = Schema.decodeUnknownSync(ProviderRuntimeEvent);diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.tsindex 6b03d70d5..5f2673e81 100644--- a/packages/contracts/src/providerRuntime.ts+++ b/packages/contracts/src/providerRuntime.ts@@ -11,8 +11,8 @@ import {ThreadId,TrimmedNonEmptyString,TurnId,-} from "./baseSchemas";-import { ProviderKind } from "./orchestration";+} from "./baseSchemas.ts";+import { ProviderKind } from "./orchestration.ts";const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;const UnknownRecordSchema = Schema.Record(Schema.String, Schema.Unknown);diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex ebdab2c45..5dec716a7 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -2,9 +2,13 @@ import { Schema } from "effect";import * as Rpc from "effect/unstable/rpc/Rpc";import * as RpcGroup from "effect/unstable/rpc/RpcGroup";-import { OpenError, OpenInEditorInput } from "./editor";-import { AuthAccessStreamEvent } from "./auth";-import { FilesystemBrowseInput, FilesystemBrowseResult, FilesystemBrowseError } from "./filesystem";+import { OpenError, OpenInEditorInput } from "./editor.ts";+import { AuthAccessStreamEvent } from "./auth.ts";+import {+ FilesystemBrowseInput,+ FilesystemBrowseResult,+ FilesystemBrowseError,+} from "./filesystem.ts";import {GitActionProgressEvent,GitCheckoutInput,@@ -29,8 +33,8 @@ import {GitStatusInput,GitStatusResult,GitStatusStreamEvent,-} from "./git";-import { KeybindingsConfigError } from "./keybindings";+} from "./git.ts";+import { KeybindingsConfigError } from "./keybindings.ts";import {ClientOrchestrationCommand,ORCHESTRATION_WS_METHODS,@@ -43,7 +47,7 @@ import {OrchestrationReplayEventsError,OrchestrationReplayEventsInput,OrchestrationRpcSchemas,-} from "./orchestration";+} from "./orchestration.ts";import {ProjectSearchEntriesError,ProjectSearchEntriesInput,@@ -51,7 +55,7 @@ import {ProjectWriteFileError,ProjectWriteFileInput,ProjectWriteFileResult,-} from "./project";+} from "./project.ts";import {TerminalClearInput,TerminalCloseInput,@@ -62,7 +66,7 @@ import {TerminalRestartInput,TerminalSessionSnapshot,TerminalWriteInput,-} from "./terminal";+} from "./terminal.ts";import {ServerConfigStreamEvent,ServerConfig,@@ -70,8 +74,8 @@ import {ServerProviderUpdatedPayload,ServerUpsertKeybindingInput,ServerUpsertKeybindingResult,-} from "./server";-import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings";+} from "./server.ts";+import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings.ts";export const WS_METHODS = {// Project registry methodsdiff --git a/packages/contracts/src/server.test.ts b/packages/contracts/src/server.test.tsindex 6e5f70c2e..2603d51d6 100644--- a/packages/contracts/src/server.test.ts+++ b/packages/contracts/src/server.test.ts@@ -1,7 +1,7 @@import { Schema } from "effect";import { describe, expect, it } from "vitest";-import { ServerProvider } from "./server";+import { ServerProvider } from "./server.ts";const decodeServerProvider = Schema.decodeUnknownSync(ServerProvider);diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.tsindex 50db737c6..c08dfa6cd 100644--- a/packages/contracts/src/server.ts+++ b/packages/contracts/src/server.ts@@ -1,18 +1,18 @@import { Effect, Schema } from "effect";-import { ExecutionEnvironmentDescriptor } from "./environment";-import { ServerAuthDescriptor } from "./auth";+import { ExecutionEnvironmentDescriptor } from "./environment.ts";+import { ServerAuthDescriptor } from "./auth.ts";import {IsoDateTime,NonNegativeInt,ProjectId,ThreadId,TrimmedNonEmptyString,-} from "./baseSchemas";-import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";-import { EditorId } from "./editor";-import { ModelCapabilities } from "./model";-import { ProviderKind } from "./orchestration";-import { ServerSettings } from "./settings";+} from "./baseSchemas.ts";+import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings.ts";+import { EditorId } from "./editor.ts";+import { ModelCapabilities } from "./model.ts";+import { ProviderKind } from "./orchestration.ts";+import { ServerSettings } from "./settings.ts";const KeybindingsMalformedConfigIssue = Schema.Struct({kind: Schema.Literal("keybindings.malformed-config"),diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex 28723cf25..fada38eb1 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -1,13 +1,13 @@import { Effect } from "effect";import * as Schema from "effect/Schema";import * as SchemaTransformation from "effect/SchemaTransformation";-import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas";+import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";import {ClaudeModelOptions,CodexModelOptions,DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,-} from "./model";-import { ModelSelection } from "./orchestration";+} from "./model.ts";+import { ModelSelection } from "./orchestration.ts";// ── Client Settings (local-only) ───────────────────────────────diff --git a/packages/contracts/src/terminal.test.ts b/packages/contracts/src/terminal.test.tsindex 1bef8db3a..3feae6749 100644--- a/packages/contracts/src/terminal.test.ts+++ b/packages/contracts/src/terminal.test.ts@@ -11,7 +11,7 @@ import {TerminalSessionSnapshot,TerminalThreadInput,TerminalWriteInput,-} from "./terminal";+} from "./terminal.ts";function decodeSync<S extends Schema.Top>(schema: S, input: unknown): Schema.Schema.Type<S> {return Schema.decodeUnknownSync(schema as never)(input) as Schema.Schema.Type<S>;diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.tsindex 3fe883b44..21bd74a09 100644--- a/packages/contracts/src/terminal.ts+++ b/packages/contracts/src/terminal.ts@@ -1,5 +1,5 @@import { Effect, Schema } from "effect";-import { TrimmedNonEmptyString } from "./baseSchemas";+import { TrimmedNonEmptyString } from "./baseSchemas.ts";export const DEFAULT_TERMINAL_ID = "default";diff --git a/packages/shared/src/DrainableWorker.test.ts b/packages/shared/src/DrainableWorker.test.tsindex 1d7a3a83c..0033038d0 100644--- a/packages/shared/src/DrainableWorker.test.ts+++ b/packages/shared/src/DrainableWorker.test.ts@@ -2,7 +2,7 @@ import { it } from "@effect/vitest";import { describe, expect } from "vitest";import { Deferred, Effect } from "effect";-import { makeDrainableWorker } from "./DrainableWorker";+import { makeDrainableWorker } from "./DrainableWorker.ts";describe("makeDrainableWorker", () => {it.live("waits for work enqueued during active processing before draining", () =>diff --git a/packages/shared/src/KeyedCoalescingWorker.test.ts b/packages/shared/src/KeyedCoalescingWorker.test.tsindex 2226bbd00..78c3a6b91 100644--- a/packages/shared/src/KeyedCoalescingWorker.test.ts+++ b/packages/shared/src/KeyedCoalescingWorker.test.ts@@ -2,7 +2,7 @@ import { it } from "@effect/vitest";import { describe, expect } from "vitest";import { Deferred, Effect } from "effect";-import { makeKeyedCoalescingWorker } from "./KeyedCoalescingWorker";+import { makeKeyedCoalescingWorker } from "./KeyedCoalescingWorker.ts";describe("makeKeyedCoalescingWorker", () => {it.live("waits for latest work enqueued during active processing before draining the key", () =>diff --git a/packages/shared/src/Net.test.ts b/packages/shared/src/Net.test.tsindex 137a9416f..19033a082 100644--- a/packages/shared/src/Net.test.ts+++ b/packages/shared/src/Net.test.ts@@ -3,7 +3,7 @@ import * as Net from "node:net";import { assert, describe, it } from "@effect/vitest";import { Effect } from "effect";-import { NetError, NetService } from "./Net";+import { NetError, NetService } from "./Net.ts";const closeServer = (server: Net.Server) =>Effect.sync(() => {diff --git a/packages/shared/src/String.test.ts b/packages/shared/src/String.test.tsindex d70bfe840..92730cd59 100644--- a/packages/shared/src/String.test.ts+++ b/packages/shared/src/String.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { truncate } from "./String";+import { truncate } from "./String.ts";describe("truncate", () => {it("trims surrounding whitespace", () => {diff --git a/packages/shared/src/cliArgs.test.ts b/packages/shared/src/cliArgs.test.tsindex 02c0b4880..62544c682 100644--- a/packages/shared/src/cliArgs.test.ts+++ b/packages/shared/src/cliArgs.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { parseCliArgs } from "./cliArgs";+import { parseCliArgs } from "./cliArgs.ts";describe("parseCliArgs", () => {it("returns empty result for empty string", () => {diff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.tsindex ba3af6c77..2160c460d 100644--- a/packages/shared/src/git.test.ts+++ b/packages/shared/src/git.test.ts@@ -8,7 +8,7 @@ import {normalizeGitRemoteUrl,parseGitHubRepositoryNameWithOwnerFromRemoteUrl,WORKTREE_BRANCH_PREFIX,-} from "./git";+} from "./git.ts";describe("normalizeGitRemoteUrl", () => {it("canonicalizes equivalent GitHub remotes across protocol variants", () => {diff --git a/packages/shared/src/model.test.ts b/packages/shared/src/model.test.tsindex 62313f360..312ce0433 100644--- a/packages/shared/src/model.test.ts+++ b/packages/shared/src/model.test.ts@@ -18,7 +18,7 @@ import {resolveModelSlugForProvider,resolveSelectableModel,trimOrNull,-} from "./model";+} from "./model.ts";const codexCaps: ModelCapabilities = {reasoningEffortLevels: [diff --git a/packages/shared/src/path.test.ts b/packages/shared/src/path.test.tsindex 912e1e13d..1c74c59a3 100644--- a/packages/shared/src/path.test.ts+++ b/packages/shared/src/path.test.ts@@ -4,7 +4,7 @@ import {isUncPath,isWindowsAbsolutePath,isWindowsDrivePath,-} from "./path";+} from "./path.ts";describe("path helpers", () => {it("detects windows drive paths", () => {diff --git a/packages/shared/src/qrCode.ts b/packages/shared/src/qrCode.tsindex 678d38c11..490e11fa0 100644--- a/packages/shared/src/qrCode.ts+++ b/packages/shared/src/qrCode.ts@@ -1,4 +1,3 @@-// @ts-nocheck/* oxlint-disable eslint/no-useless-escape *//** QR Code generator library (TypeScript)@@ -25,960 +24,962 @@"use strict";-namespace qrcodegen {- type bit = number;- type byte = number;- type int = number;-- /*---- QR Code symbol class ----*/-- /*- * A QR Code symbol, which is a type of two-dimension barcode.- * Invented by Denso Wave and described in the ISO/IEC 18004 standard.- * Instances of this class represent an immutable square grid of dark and light cells.- * The class provides static factory functions to create a QR Code from text or binary data.- * The class covers the QR Code Model 2 specification, supporting all versions (sizes)- * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.- *- * Ways to create a QR Code object:- * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().- * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().- * - Low level: Custom-make the array of data codeword bytes (including- * segment headers and final padding, excluding error correction codewords),- * supply the appropriate version number, and call the QrCode() constructor.- * (Note that all ways require supplying the desired error correction level.)- */- export class QrCode {- /*-- Static factory functions (high level) --*/-- // Returns a QR Code representing the given Unicode text string at the given error correction level.- // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer- // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible- // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the- // ecl argument if it can be done without increasing the version.- public static encodeText(text: string, ecl: QrCode.Ecc): QrCode {- const segs: Array<QrSegment> = qrcodegen.QrSegment.makeSegments(text);- return QrCode.encodeSegments(segs, ecl);- }+type bit = number;+type byte = number;+type int = number;- // Returns a QR Code representing the given binary data at the given error correction level.- // This function always encodes using the binary segment mode, not any text mode. The maximum number of- // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.- // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.- public static encodeBinary(data: Readonly<Array<byte>>, ecl: QrCode.Ecc): QrCode {- const seg: QrSegment = qrcodegen.QrSegment.makeBytes(data);- return QrCode.encodeSegments([seg], ecl);- }+/*---- QR Code symbol class ----*/- /*-- Static factory functions (mid level) --*/-- // Returns a QR Code representing the given segments with the given encoding parameters.- // The smallest possible QR Code version within the given range is automatically- // chosen for the output. Iff boostEcl is true, then the ECC level of the result- // may be higher than the ecl argument if it can be done without increasing the- // version. The mask number is either between 0 to 7 (inclusive) to force that- // mask, or -1 to automatically choose an appropriate mask (which may be slow).- // This function allows the user to create a custom sequence of segments that switches- // between modes (such as alphanumeric and byte) to encode text in less space.- // This is a mid-level API; the high-level API is encodeText() and encodeBinary().- public static encodeSegments(- segs: Readonly<Array<QrSegment>>,- ecl: QrCode.Ecc,- minVersion: int = 1,- maxVersion: int = 40,- mask: int = -1,- boostEcl: boolean = true,- ): QrCode {- if (- !(- QrCode.MIN_VERSION <= minVersion &&- minVersion <= maxVersion &&- maxVersion <= QrCode.MAX_VERSION- ) ||- mask < -1 ||- mask > 7- )- throw new RangeError("Invalid value");-- // Find the minimal version number to use- let version: int;- let dataUsedBits: int;- for (version = minVersion; ; version++) {- const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available- const usedBits: number = QrSegment.getTotalBits(segs, version);- if (usedBits <= dataCapacityBits) {- dataUsedBits = usedBits;- break; // This version number is found to be suitable- }- if (version >= maxVersion)- // All versions in the range could not fit the given data- throw new RangeError("Data too long");- }+/*+ * A QR Code symbol, which is a type of two-dimension barcode.+ * Invented by Denso Wave and described in the ISO/IEC 18004 standard.+ * Instances of this class represent an immutable square grid of dark and light cells.+ * The class provides static factory functions to create a QR Code from text or binary data.+ * The class covers the QR Code Model 2 specification, supporting all versions (sizes)+ * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.+ *+ * Ways to create a QR Code object:+ * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().+ * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().+ * - Low level: Custom-make the array of data codeword bytes (including+ * segment headers and final padding, excluding error correction codewords),+ * supply the appropriate version number, and call the QrCode() constructor.+ * (Note that all ways require supplying the desired error correction level.)+ */+export class QrCode {+ public static Ecc: typeof QrCodeEcc;++ /*-- Static factory functions (high level) --*/++ // Returns a QR Code representing the given Unicode text string at the given error correction level.+ // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer+ // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible+ // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the+ // ecl argument if it can be done without increasing the version.+ public static encodeText(text: string, ecl: QrCodeEcc): QrCode {+ const segs: Array<QrSegment> = QrSegment.makeSegments(text);+ return QrCode.encodeSegments(segs, ecl);+ }- // Increase the error correction level while the data still fits in the current version number- for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) {- // From low to high- if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)- ecl = newEcl;- }+ // Returns a QR Code representing the given binary data at the given error correction level.+ // This function always encodes using the binary segment mode, not any text mode. The maximum number of+ // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.+ // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.+ public static encodeBinary(data: Readonly<Array<byte>>, ecl: QrCodeEcc): QrCode {+ const seg: QrSegment = QrSegment.makeBytes(data);+ return QrCode.encodeSegments([seg], ecl);+ }- // Concatenate all segments to create the data bit string- let bb: Array<bit> = [];- for (const seg of segs) {- appendBits(seg.mode.modeBits, 4, bb);- appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);- for (const b of seg.getData()) bb.push(b);+ /*-- Static factory functions (mid level) --*/++ // Returns a QR Code representing the given segments with the given encoding parameters.+ // The smallest possible QR Code version within the given range is automatically+ // chosen for the output. Iff boostEcl is true, then the ECC level of the result+ // may be higher than the ecl argument if it can be done without increasing the+ // version. The mask number is either between 0 to 7 (inclusive) to force that+ // mask, or -1 to automatically choose an appropriate mask (which may be slow).+ // This function allows the user to create a custom sequence of segments that switches+ // between modes (such as alphanumeric and byte) to encode text in less space.+ // This is a mid-level API; the high-level API is encodeText() and encodeBinary().+ public static encodeSegments(+ segs: Readonly<Array<QrSegment>>,+ ecl: QrCodeEcc,+ minVersion: int = 1,+ maxVersion: int = 40,+ mask: int = -1,+ boostEcl: boolean = true,+ ): QrCode {+ if (+ !(+ QrCode.MIN_VERSION <= minVersion &&+ minVersion <= maxVersion &&+ maxVersion <= QrCode.MAX_VERSION+ ) ||+ mask < -1 ||+ mask > 7+ )+ throw new RangeError("Invalid value");++ // Find the minimal version number to use+ let version: int;+ let dataUsedBits: int;+ for (version = minVersion; ; version++) {+ const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available+ const usedBits: number = QrSegment.getTotalBits(segs, version);+ if (usedBits <= dataCapacityBits) {+ dataUsedBits = usedBits;+ break; // This version number is found to be suitable}- assert(bb.length == dataUsedBits);-- // Add terminator and pad up to a byte if applicable- const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8;- assert(bb.length <= dataCapacityBits);- appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);- appendBits(0, (8 - (bb.length % 8)) % 8, bb);- assert(bb.length % 8 == 0);-- // Pad with alternating bytes until data capacity is reached- for (let padByte = 0xec; bb.length < dataCapacityBits; padByte ^= 0xec ^ 0x11)- appendBits(padByte, 8, bb);-- // Pack bits into bytes in big endian- let dataCodewords: Array<byte> = [];- while (dataCodewords.length * 8 < bb.length) dataCodewords.push(0);- bb.forEach((b: bit, i: int) => (dataCodewords[i >>> 3] |= b << (7 - (i & 7))));-- // Create the QR Code object- return new QrCode(version, ecl, dataCodewords, mask);+ if (version >= maxVersion)+ // All versions in the range could not fit the given data+ throw new RangeError("Data too long");}- /*-- Fields --*/-- // The width and height of this QR Code, measured in modules, between- // 21 and 177 (inclusive). This is equal to version * 4 + 17.- public readonly size: int;-- // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).- // Even if a QR Code is created with automatic masking requested (mask = -1),- // the resulting object still has a mask value between 0 and 7.- public readonly mask: int;-- // The modules of this QR Code (false = light, true = dark).- // Immutable after constructor finishes. Accessed through getModule().- private readonly modules: Array<Array<boolean>> = [];-- // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.- private readonly isFunction: Array<Array<boolean>> = [];-- /*-- Constructor (low level) and fields --*/-- // Creates a new QR Code with the given version number,- // error correction level, data codeword bytes, and mask number.- // This is a low-level API that most users should not use directly.- // A mid-level API is the encodeSegments() function.- public constructor(- // The version number of this QR Code, which is between 1 and 40 (inclusive).- // This determines the size of this barcode.- public readonly version: int,-- // The error correction level used in this QR Code.- public readonly errorCorrectionLevel: QrCode.Ecc,-- dataCodewords: Readonly<Array<byte>>,-- msk: int,- ) {- // Check scalar arguments- if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)- throw new RangeError("Version value out of range");- if (msk < -1 || msk > 7) throw new RangeError("Mask value out of range");- this.size = version * 4 + 17;-- // Initialize both grids to be size*size arrays of Boolean false- let row: Array<boolean> = [];- for (let i = 0; i < this.size; i++) row.push(false);- for (let i = 0; i < this.size; i++) {- this.modules.push(row.slice()); // Initially all light- this.isFunction.push(row.slice());- }-- // Compute ECC, draw modules- this.drawFunctionPatterns();- const allCodewords: Array<byte> = this.addEccAndInterleave(dataCodewords);- this.drawCodewords(allCodewords);-- // Do masking- if (msk == -1) {- // Automatically choose best mask- let minPenalty: int = 1000000000;- for (let i = 0; i < 8; i++) {- this.applyMask(i);- this.drawFormatBits(i);- const penalty: int = this.getPenaltyScore();- if (penalty < minPenalty) {- msk = i;- minPenalty = penalty;- }- this.applyMask(i); // Undoes the mask due to XOR- }- }- assert(0 <= msk && msk <= 7);- this.mask = msk;- this.applyMask(msk); // Apply the final choice of mask- this.drawFormatBits(msk); // Overwrite old format bits+ // Increase the error correction level while the data still fits in the current version number+ for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) {+ // From low to high+ if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8) ecl = newEcl;+ }- this.isFunction = [];+ // Concatenate all segments to create the data bit string+ let bb: Array<bit> = [];+ for (const seg of segs) {+ appendBits(seg.mode.modeBits, 4, bb);+ appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);+ for (const b of seg.getData()) bb.push(b);}+ assert(bb.length == dataUsedBits);- /*-- Accessor methods --*/+ // Add terminator and pad up to a byte if applicable+ const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8;+ assert(bb.length <= dataCapacityBits);+ appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);+ appendBits(0, (8 - (bb.length % 8)) % 8, bb);+ assert(bb.length % 8 == 0);- // Returns the color of the module (pixel) at the given coordinates, which is false- // for light or true for dark. The top left corner has the coordinates (x=0, y=0).- // If the given coordinates are out of bounds, then false (light) is returned.- public getModule(x: int, y: int): boolean {- return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];- }+ // Pad with alternating bytes until data capacity is reached+ for (let padByte = 0xec; bb.length < dataCapacityBits; padByte ^= 0xec ^ 0x11)+ appendBits(padByte, 8, bb);- /*-- Private helper methods for constructor: Drawing function modules --*/+ // Pack bits into bytes in big endian+ let dataCodewords: Array<byte> = [];+ while (dataCodewords.length * 8 < bb.length) dataCodewords.push(0);+ bb.forEach((b: bit, i: int) => (dataCodewords[i >>> 3]! |= b << (7 - (i & 7))));- // Reads this object's version field, and draws and marks all function modules.- private drawFunctionPatterns(): void {- // Draw horizontal and vertical timing patterns- for (let i = 0; i < this.size; i++) {- this.setFunctionModule(6, i, i % 2 == 0);- this.setFunctionModule(i, 6, i % 2 == 0);- }+ // Create the QR Code object+ return new QrCode(version, ecl, dataCodewords, mask);+ }- // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)- this.drawFinderPattern(3, 3);- this.drawFinderPattern(this.size - 4, 3);- this.drawFinderPattern(3, this.size - 4);-- // Draw numerous alignment patterns- const alignPatPos: Array<int> = this.getAlignmentPatternPositions();- const numAlign: int = alignPatPos.length;- for (let i = 0; i < numAlign; i++) {- for (let j = 0; j < numAlign; j++) {- // Don't draw on the three finder corners- if (- !((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))- )- this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);+ /*-- Fields --*/++ // The width and height of this QR Code, measured in modules, between+ // 21 and 177 (inclusive). This is equal to version * 4 + 17.+ public readonly version: int;+ public readonly errorCorrectionLevel: QrCodeEcc;+ public readonly size: int;++ // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).+ // Even if a QR Code is created with automatic masking requested (mask = -1),+ // the resulting object still has a mask value between 0 and 7.+ public readonly mask: int;++ // The modules of this QR Code (false = light, true = dark).+ // Immutable after constructor finishes. Accessed through getModule().+ private readonly modules: Array<Array<boolean>> = [];++ // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.+ private readonly isFunction: Array<Array<boolean>> = [];++ /*-- Constructor (low level) and fields --*/++ // Creates a new QR Code with the given version number,+ // error correction level, data codeword bytes, and mask number.+ // This is a low-level API that most users should not use directly.+ // A mid-level API is the encodeSegments() function.+ public constructor(+ // The version number of this QR Code, which is between 1 and 40 (inclusive).+ // This determines the size of this barcode.+ version: int,++ // The error correction level used in this QR Code.+ errorCorrectionLevel: QrCodeEcc,++ dataCodewords: Readonly<Array<byte>>,++ msk: int,+ ) {+ this.version = version;+ this.errorCorrectionLevel = errorCorrectionLevel;++ // Check scalar arguments+ if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)+ throw new RangeError("Version value out of range");+ if (msk < -1 || msk > 7) throw new RangeError("Mask value out of range");+ this.size = version * 4 + 17;++ // Initialize both grids to be size*size arrays of Boolean false+ let row: Array<boolean> = [];+ for (let i = 0; i < this.size; i++) row.push(false);+ for (let i = 0; i < this.size; i++) {+ this.modules.push(row.slice()); // Initially all light+ this.isFunction.push(row.slice());+ }++ // Compute ECC, draw modules+ this.drawFunctionPatterns();+ const allCodewords: Array<byte> = this.addEccAndInterleave(dataCodewords);+ this.drawCodewords(allCodewords);++ // Do masking+ if (msk == -1) {+ // Automatically choose best mask+ let minPenalty: int = 1000000000;+ for (let i = 0; i < 8; i++) {+ this.applyMask(i);+ this.drawFormatBits(i);+ const penalty: int = this.getPenaltyScore();+ if (penalty < minPenalty) {+ msk = i;+ minPenalty = penalty;}+ this.applyMask(i); // Undoes the mask due to XOR}-- // Draw configuration data- this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor- this.drawVersion();}+ assert(0 <= msk && msk <= 7);+ this.mask = msk;+ this.applyMask(msk); // Apply the final choice of mask+ this.drawFormatBits(msk); // Overwrite old format bits- // Draws two copies of the format bits (with its own error correction code)- // based on the given mask and this object's error correction level field.- private drawFormatBits(mask: int): void {- // Calculate error correction code and pack bits- const data: int = (this.errorCorrectionLevel.formatBits << 3) | mask; // errCorrLvl is uint2, mask is uint3- let rem: int = data;- for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);- const bits = ((data << 10) | rem) ^ 0x5412; // uint15- assert(bits >>> 15 == 0);-- // Draw first copy- for (let i = 0; i <= 5; i++) this.setFunctionModule(8, i, getBit(bits, i));- this.setFunctionModule(8, 7, getBit(bits, 6));- this.setFunctionModule(8, 8, getBit(bits, 7));- this.setFunctionModule(7, 8, getBit(bits, 8));- for (let i = 9; i < 15; i++) this.setFunctionModule(14 - i, 8, getBit(bits, i));-- // Draw second copy- for (let i = 0; i < 8; i++) this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));- for (let i = 8; i < 15; i++) this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));- this.setFunctionModule(8, this.size - 8, true); // Always dark- }+ this.isFunction = [];+ }++ /*-- Accessor methods --*/++ // Returns the color of the module (pixel) at the given coordinates, which is false+ // for light or true for dark. The top left corner has the coordinates (x=0, y=0).+ // If the given coordinates are out of bounds, then false (light) is returned.+ public getModule(x: int, y: int): boolean {+ return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y]![x]!;+ }- // Draws two copies of the version bits (with its own error correction code),- // based on this object's version field, iff 7 <= version <= 40.- private drawVersion(): void {- if (this.version < 7) return;-- // Calculate error correction code and pack bits- let rem: int = this.version; // version is uint6, in the range [7, 40]- for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);- const bits: int = (this.version << 12) | rem; // uint18- assert(bits >>> 18 == 0);-- // Draw two copies- for (let i = 0; i < 18; i++) {- const color: boolean = getBit(bits, i);- const a: int = this.size - 11 + (i % 3);- const b: int = Math.floor(i / 3);- this.setFunctionModule(a, b, color);- this.setFunctionModule(b, a, color);+ /*-- Private helper methods for constructor: Drawing function modules --*/++ // Reads this object's version field, and draws and marks all function modules.+ private drawFunctionPatterns(): void {+ // Draw horizontal and vertical timing patterns+ for (let i = 0; i < this.size; i++) {+ this.setFunctionModule(6, i, i % 2 == 0);+ this.setFunctionModule(i, 6, i % 2 == 0);+ }++ // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)+ this.drawFinderPattern(3, 3);+ this.drawFinderPattern(this.size - 4, 3);+ this.drawFinderPattern(3, this.size - 4);++ // Draw numerous alignment patterns+ const alignPatPos: Array<int> = this.getAlignmentPatternPositions();+ const numAlign: int = alignPatPos.length;+ for (let i = 0; i < numAlign; i++) {+ for (let j = 0; j < numAlign; j++) {+ // Don't draw on the three finder corners+ if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))+ this.drawAlignmentPattern(alignPatPos[i]!, alignPatPos[j]!);}}- // Draws a 9*9 finder pattern including the border separator,- // with the center module at (x, y). Modules can be out of bounds.- private drawFinderPattern(x: int, y: int): void {- for (let dy = -4; dy <= 4; dy++) {- for (let dx = -4; dx <= 4; dx++) {- const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm- const xx: int = x + dx;- const yy: int = y + dy;- if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)- this.setFunctionModule(xx, yy, dist != 2 && dist != 4);- }- }+ // Draw configuration data+ this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor+ this.drawVersion();+ }++ // Draws two copies of the format bits (with its own error correction code)+ // based on the given mask and this object's error correction level field.+ private drawFormatBits(mask: int): void {+ // Calculate error correction code and pack bits+ const data: int = (this.errorCorrectionLevel.formatBits << 3) | mask; // errCorrLvl is uint2, mask is uint3+ let rem: int = data;+ for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);+ const bits = ((data << 10) | rem) ^ 0x5412; // uint15+ assert(bits >>> 15 == 0);++ // Draw first copy+ for (let i = 0; i <= 5; i++) this.setFunctionModule(8, i, getBit(bits, i));+ this.setFunctionModule(8, 7, getBit(bits, 6));+ this.setFunctionModule(8, 8, getBit(bits, 7));+ this.setFunctionModule(7, 8, getBit(bits, 8));+ for (let i = 9; i < 15; i++) this.setFunctionModule(14 - i, 8, getBit(bits, i));++ // Draw second copy+ for (let i = 0; i < 8; i++) this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));+ for (let i = 8; i < 15; i++) this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));+ this.setFunctionModule(8, this.size - 8, true); // Always dark+ }++ // Draws two copies of the version bits (with its own error correction code),+ // based on this object's version field, iff 7 <= version <= 40.+ private drawVersion(): void {+ if (this.version < 7) return;++ // Calculate error correction code and pack bits+ let rem: int = this.version; // version is uint6, in the range [7, 40]+ for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);+ const bits: int = (this.version << 12) | rem; // uint18+ assert(bits >>> 18 == 0);++ // Draw two copies+ for (let i = 0; i < 18; i++) {+ const color: boolean = getBit(bits, i);+ const a: int = this.size - 11 + (i % 3);+ const b: int = Math.floor(i / 3);+ this.setFunctionModule(a, b, color);+ this.setFunctionModule(b, a, color);}+ }- // Draws a 5*5 alignment pattern, with the center module- // at (x, y). All modules must be in bounds.- private drawAlignmentPattern(x: int, y: int): void {- for (let dy = -2; dy <= 2; dy++) {- for (let dx = -2; dx <= 2; dx++)- this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);+ // Draws a 9*9 finder pattern including the border separator,+ // with the center module at (x, y). Modules can be out of bounds.+ private drawFinderPattern(x: int, y: int): void {+ for (let dy = -4; dy <= 4; dy++) {+ for (let dx = -4; dx <= 4; dx++) {+ const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm+ const xx: int = x + dx;+ const yy: int = y + dy;+ if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)+ this.setFunctionModule(xx, yy, dist != 2 && dist != 4);}}+ }- // Sets the color of a module and marks it as a function module.- // Only used by the constructor. Coordinates must be in bounds.- private setFunctionModule(x: int, y: int, isDark: boolean): void {- this.modules[y][x] = isDark;- this.isFunction[y][x] = true;+ // Draws a 5*5 alignment pattern, with the center module+ // at (x, y). All modules must be in bounds.+ private drawAlignmentPattern(x: int, y: int): void {+ for (let dy = -2; dy <= 2; dy++) {+ for (let dx = -2; dx <= 2; dx++)+ this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);}+ }- /*-- Private helper methods for constructor: Codewords and masking --*/-- // Returns a new byte string representing the given data with the appropriate error correction- // codewords appended to it, based on this object's version and error correction level.- private addEccAndInterleave(data: Readonly<Array<byte>>): Array<byte> {- const ver: int = this.version;- const ecl: QrCode.Ecc = this.errorCorrectionLevel;- if (data.length != QrCode.getNumDataCodewords(ver, ecl))- throw new RangeError("Invalid argument");-- // Calculate parameter numbers- const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];- const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];- const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8);- const numShortBlocks: int = numBlocks - (rawCodewords % numBlocks);- const shortBlockLen: int = Math.floor(rawCodewords / numBlocks);-- // Split data into blocks and append ECC to each block- let blocks: Array<Array<byte>> = [];- const rsDiv: Array<byte> = QrCode.reedSolomonComputeDivisor(blockEccLen);- for (let i = 0, k = 0; i < numBlocks; i++) {- let dat: Array<byte> = data.slice(- k,- k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1),- );- k += dat.length;- const ecc: Array<byte> = QrCode.reedSolomonComputeRemainder(dat, rsDiv);- if (i < numShortBlocks) dat.push(0);- blocks.push(dat.concat(ecc));- }+ // Sets the color of a module and marks it as a function module.+ // Only used by the constructor. Coordinates must be in bounds.+ private setFunctionModule(x: int, y: int, isDark: boolean): void {+ this.modules[y]![x] = isDark;+ this.isFunction[y]![x] = true;+ }- // Interleave (not concatenate) the bytes from every block into a single sequence- let result: Array<byte> = [];- for (let i = 0; i < blocks[0].length; i++) {- blocks.forEach((block, j) => {- // Skip the padding byte in short blocks- if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(block[i]);- });- }- assert(result.length == rawCodewords);- return result;- }+ /*-- Private helper methods for constructor: Codewords and masking --*/++ // Returns a new byte string representing the given data with the appropriate error correction+ // codewords appended to it, based on this object's version and error correction level.+ private addEccAndInterleave(data: Readonly<Array<byte>>): Array<byte> {+ const ver: int = this.version;+ const ecl: QrCodeEcc = this.errorCorrectionLevel;+ if (data.length != QrCode.getNumDataCodewords(ver, ecl))+ throw new RangeError("Invalid argument");++ // Calculate parameter numbers+ const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal]![ver]!;+ const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal]![ver]!;+ const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8);+ const numShortBlocks: int = numBlocks - (rawCodewords % numBlocks);+ const shortBlockLen: int = Math.floor(rawCodewords / numBlocks);++ // Split data into blocks and append ECC to each block+ let blocks: Array<Array<byte>> = [];+ const rsDiv: Array<byte> = QrCode.reedSolomonComputeDivisor(blockEccLen);+ for (let i = 0, k = 0; i < numBlocks; i++) {+ let dat: Array<byte> = data.slice(+ k,+ k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1),+ );+ k += dat.length;+ const ecc: Array<byte> = QrCode.reedSolomonComputeRemainder(dat, rsDiv);+ if (i < numShortBlocks) dat.push(0);+ blocks.push(dat.concat(ecc));+ }++ // Interleave (not concatenate) the bytes from every block into a single sequence+ let result: Array<byte> = [];+ for (let i = 0; i < blocks[0]!.length; i++) {+ blocks.forEach((block, j) => {+ // Skip the padding byte in short blocks+ if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(block[i]!);+ });+ }+ assert(result.length == rawCodewords);+ return result;+ }- // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire- // data area of this QR Code. Function modules need to be marked off before this is called.- private drawCodewords(data: Readonly<Array<byte>>): void {- if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))- throw new RangeError("Invalid argument");- let i: int = 0; // Bit index into the data- // Do the funny zigzag scan- for (let right = this.size - 1; right >= 1; right -= 2) {- // Index of right column in each column pair- if (right == 6) right = 5;- for (let vert = 0; vert < this.size; vert++) {- // Vertical counter- for (let j = 0; j < 2; j++) {- const x: int = right - j; // Actual x coordinate- const upward: boolean = ((right + 1) & 2) == 0;- const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate- if (!this.isFunction[y][x] && i < data.length * 8) {- this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));- i++;- }- // If this QR Code has any remainder bits (0 to 7), they were assigned as- // 0/false/light by the constructor and are left unchanged by this method+ // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire+ // data area of this QR Code. Function modules need to be marked off before this is called.+ private drawCodewords(data: Readonly<Array<byte>>): void {+ if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))+ throw new RangeError("Invalid argument");+ let i: int = 0; // Bit index into the data+ // Do the funny zigzag scan+ for (let right = this.size - 1; right >= 1; right -= 2) {+ // Index of right column in each column pair+ if (right == 6) right = 5;+ for (let vert = 0; vert < this.size; vert++) {+ // Vertical counter+ for (let j = 0; j < 2; j++) {+ const x: int = right - j; // Actual x coordinate+ const upward: boolean = ((right + 1) & 2) == 0;+ const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate+ if (!this.isFunction[y]![x]! && i < data.length * 8) {+ this.modules[y]![x] = getBit(data[i >>> 3]!, 7 - (i & 7));+ i++;}+ // If this QR Code has any remainder bits (0 to 7), they were assigned as+ // 0/false/light by the constructor and are left unchanged by this method}}- assert(i == data.length * 8);}+ assert(i == data.length * 8);+ }- // XORs the codeword modules in this QR Code with the given mask pattern.- // The function modules must be marked and the codeword bits must be drawn- // before masking. Due to the arithmetic of XOR, calling applyMask() with- // the same mask value a second time will undo the mask. A final well-formed- // QR Code needs exactly one (not zero, two, etc.) mask applied.- private applyMask(mask: int): void {- if (mask < 0 || mask > 7) throw new RangeError("Mask value out of range");- for (let y = 0; y < this.size; y++) {- for (let x = 0; x < this.size; x++) {- let invert: boolean;- switch (mask) {- case 0:- invert = (x + y) % 2 == 0;- break;- case 1:- invert = y % 2 == 0;- break;- case 2:- invert = x % 3 == 0;- break;- case 3:- invert = (x + y) % 3 == 0;- break;- case 4:- invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;- break;- case 5:- invert = ((x * y) % 2) + ((x * y) % 3) == 0;- break;- case 6:- invert = (((x * y) % 2) + ((x * y) % 3)) % 2 == 0;- break;- case 7:- invert = (((x + y) % 2) + ((x * y) % 3)) % 2 == 0;- break;- default:- throw new Error("Unreachable");- }- if (!this.isFunction[y][x] && invert) this.modules[y][x] = !this.modules[y][x];+ // XORs the codeword modules in this QR Code with the given mask pattern.+ // The function modules must be marked and the codeword bits must be drawn+ // before masking. Due to the arithmetic of XOR, calling applyMask() with+ // the same mask value a second time will undo the mask. A final well-formed+ // QR Code needs exactly one (not zero, two, etc.) mask applied.+ private applyMask(mask: int): void {+ if (mask < 0 || mask > 7) throw new RangeError("Mask value out of range");+ for (let y = 0; y < this.size; y++) {+ for (let x = 0; x < this.size; x++) {+ let invert: boolean;+ switch (mask) {+ case 0:+ invert = (x + y) % 2 == 0;+ break;+ case 1:+ invert = y % 2 == 0;+ break;+ case 2:+ invert = x % 3 == 0;+ break;+ case 3:+ invert = (x + y) % 3 == 0;+ break;+ case 4:+ invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;+ break;+ case 5:+ invert = ((x * y) % 2) + ((x * y) % 3) == 0;+ break;+ case 6:+ invert = (((x * y) % 2) + ((x * y) % 3)) % 2 == 0;+ break;+ case 7:+ invert = (((x + y) % 2) + ((x * y) % 3)) % 2 == 0;+ break;+ default:+ throw new Error("Unreachable");}+ if (!this.isFunction[y]![x]! && invert) this.modules[y]![x] = !this.modules[y]![x]!;}}+ }- // Calculates and returns the penalty score based on state of this QR Code's current modules.- // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.- private getPenaltyScore(): int {- let result: int = 0;+ // Calculates and returns the penalty score based on state of this QR Code's current modules.+ // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.+ private getPenaltyScore(): int {+ let result: int = 0;- // Adjacent modules in row having same color, and finder-like patterns- for (let y = 0; y < this.size; y++) {- let runColor = false;- let runX = 0;- let runHistory = [0, 0, 0, 0, 0, 0, 0];- for (let x = 0; x < this.size; x++) {- if (this.modules[y][x] == runColor) {- runX++;- if (runX == 5) result += QrCode.PENALTY_N1;- else if (runX > 5) result++;- } else {- this.finderPenaltyAddHistory(runX, runHistory);- if (!runColor)- result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;- runColor = this.modules[y][x];- runX = 1;- }- }- result +=- this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;- }- // Adjacent modules in column having same color, and finder-like patterns+ // Adjacent modules in row having same color, and finder-like patterns+ for (let y = 0; y < this.size; y++) {+ let runColor = false;+ let runX = 0;+ let runHistory = [0, 0, 0, 0, 0, 0, 0];for (let x = 0; x < this.size; x++) {- let runColor = false;- let runY = 0;- let runHistory = [0, 0, 0, 0, 0, 0, 0];- for (let y = 0; y < this.size; y++) {- if (this.modules[y][x] == runColor) {- runY++;- if (runY == 5) result += QrCode.PENALTY_N1;- else if (runY > 5) result++;- } else {- this.finderPenaltyAddHistory(runY, runHistory);- if (!runColor)- result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;- runColor = this.modules[y][x];- runY = 1;- }+ if (this.modules[y]![x] === runColor) {+ runX++;+ if (runX == 5) result += QrCode.PENALTY_N1;+ else if (runX > 5) result++;+ } else {+ this.finderPenaltyAddHistory(runX, runHistory);+ if (!runColor) result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;+ runColor = this.modules[y]![x]!;+ runX = 1;}- result +=- this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;}-- // 2*2 blocks of modules having same color- for (let y = 0; y < this.size - 1; y++) {- for (let x = 0; x < this.size - 1; x++) {- const color: boolean = this.modules[y][x];- if (- color == this.modules[y][x + 1] &&- color == this.modules[y + 1][x] &&- color == this.modules[y + 1][x + 1]- )- result += QrCode.PENALTY_N2;+ result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;+ }+ // Adjacent modules in column having same color, and finder-like patterns+ for (let x = 0; x < this.size; x++) {+ let runColor = false;+ let runY = 0;+ let runHistory = [0, 0, 0, 0, 0, 0, 0];+ for (let y = 0; y < this.size; y++) {+ if (this.modules[y]![x] === runColor) {+ runY++;+ if (runY == 5) result += QrCode.PENALTY_N1;+ else if (runY > 5) result++;+ } else {+ this.finderPenaltyAddHistory(runY, runHistory);+ if (!runColor) result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;+ runColor = this.modules[y]![x]!;+ runY = 1;}}-- // Balance of dark and light modules- let dark: int = 0;- for (const row of this.modules)- dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);- const total: int = this.size * this.size; // Note that size is odd, so dark/total != 1/2- // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%- const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;- assert(0 <= k && k <= 9);- result += k * QrCode.PENALTY_N4;- assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4- return result;- }-- /*-- Private helper functions --*/-- // Returns an ascending list of positions of alignment patterns for this version number.- // Each position is in the range [0,177), and are used on both the x and y axes.- // This could be implemented as lookup table of 40 variable-length lists of integers.- private getAlignmentPatternPositions(): Array<int> {- if (this.version == 1) return [];- else {- const numAlign: int = Math.floor(this.version / 7) + 2;- const step: int =- this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;- let result: Array<int> = [6];- for (let pos = this.size - 7; result.length < numAlign; pos -= step)- result.splice(1, 0, pos);- return result;+ result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;+ }++ // 2*2 blocks of modules having same color+ for (let y = 0; y < this.size - 1; y++) {+ for (let x = 0; x < this.size - 1; x++) {+ const color: boolean = this.modules[y]![x]!;+ if (+ color == this.modules[y]![x + 1]! &&+ color == this.modules[y + 1]![x]! &&+ color == this.modules[y + 1]![x + 1]!+ )+ result += QrCode.PENALTY_N2;}}- // Returns the number of data bits that can be stored in a QR Code of the given version number, after- // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.- // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.- private static getNumRawDataModules(ver: int): int {- if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)- throw new RangeError("Version number out of range");- let result: int = (16 * ver + 128) * ver + 64;- if (ver >= 2) {- const numAlign: int = Math.floor(ver / 7) + 2;- result -= (25 * numAlign - 10) * numAlign - 55;- if (ver >= 7) result -= 36;- }- assert(208 <= result && result <= 29648);+ // Balance of dark and light modules+ let dark: int = 0;+ for (const row of this.modules) dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);+ const total: int = this.size * this.size; // Note that size is odd, so dark/total != 1/2+ // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%+ const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;+ assert(0 <= k && k <= 9);+ result += k * QrCode.PENALTY_N4;+ assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4+ return result;+ }++ /*-- Private helper functions --*/++ // Returns an ascending list of positions of alignment patterns for this version number.+ // Each position is in the range [0,177), and are used on both the x and y axes.+ // This could be implemented as lookup table of 40 variable-length lists of integers.+ private getAlignmentPatternPositions(): Array<int> {+ if (this.version == 1) return [];+ else {+ const numAlign: int = Math.floor(this.version / 7) + 2;+ const step: int =+ this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;+ let result: Array<int> = [6];+ for (let pos = this.size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos);return result;}+ }- // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any- // QR Code of the given version number and error correction level, with remainder bits discarded.- // This stateless pure function could be implemented as a (40*4)-cell lookup table.- private static getNumDataCodewords(ver: int, ecl: QrCode.Ecc): int {- return (- Math.floor(QrCode.getNumRawDataModules(ver) / 8) -- QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] *- QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]- );- }+ // Returns the number of data bits that can be stored in a QR Code of the given version number, after+ // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.+ // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.+ private static getNumRawDataModules(ver: int): int {+ if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)+ throw new RangeError("Version number out of range");+ let result: int = (16 * ver + 128) * ver + 64;+ if (ver >= 2) {+ const numAlign: int = Math.floor(ver / 7) + 2;+ result -= (25 * numAlign - 10) * numAlign - 55;+ if (ver >= 7) result -= 36;+ }+ assert(208 <= result && result <= 29648);+ return result;+ }- // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be- // implemented as a lookup table over all possible parameter values, instead of as an algorithm.- private static reedSolomonComputeDivisor(degree: int): Array<byte> {- if (degree < 1 || degree > 255) throw new RangeError("Degree out of range");- // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.- // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].- let result: Array<byte> = [];- for (let i = 0; i < degree - 1; i++) result.push(0);- result.push(1); // Start off with the monomial x^0-- // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),- // and drop the highest monomial term which is always 1x^degree.- // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).- let root = 1;- for (let i = 0; i < degree; i++) {- // Multiply the current product by (x - r^i)- for (let j = 0; j < result.length; j++) {- result[j] = QrCode.reedSolomonMultiply(result[j], root);- if (j + 1 < result.length) result[j] ^= result[j + 1];- }- root = QrCode.reedSolomonMultiply(root, 0x02);- }- return result;- }+ // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any+ // QR Code of the given version number and error correction level, with remainder bits discarded.+ // This stateless pure function could be implemented as a (40*4)-cell lookup table.+ private static getNumDataCodewords(ver: int, ecl: QrCodeEcc): int {+ return (+ Math.floor(QrCode.getNumRawDataModules(ver) / 8) -+ QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal]![ver]! *+ QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal]![ver]!+ );+ }- // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.- private static reedSolomonComputeRemainder(- data: Readonly<Array<byte>>,- divisor: Readonly<Array<byte>>,- ): Array<byte> {- let result: Array<byte> = divisor.map((_) => 0);- for (const b of data) {- // Polynomial division- const factor: byte = b ^ (result.shift() as byte);- result.push(0);- divisor.forEach((coef, i) => (result[i] ^= QrCode.reedSolomonMultiply(coef, factor)));+ // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be+ // implemented as a lookup table over all possible parameter values, instead of as an algorithm.+ private static reedSolomonComputeDivisor(degree: int): Array<byte> {+ if (degree < 1 || degree > 255) throw new RangeError("Degree out of range");+ // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.+ // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].+ let result: Array<byte> = [];+ for (let i = 0; i < degree - 1; i++) result.push(0);+ result.push(1); // Start off with the monomial x^0++ // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),+ // and drop the highest monomial term which is always 1x^degree.+ // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).+ let root = 1;+ for (let i = 0; i < degree; i++) {+ // Multiply the current product by (x - r^i)+ for (let j = 0; j < result.length; j++) {+ result[j] = QrCode.reedSolomonMultiply(result[j]!, root);+ if (j + 1 < result.length) result[j]! ^= result[j + 1]!;}- return result;+ root = QrCode.reedSolomonMultiply(root, 0x02);}+ return result;+ }- // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result- // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.- private static reedSolomonMultiply(x: byte, y: byte): byte {- if (x >>> 8 != 0 || y >>> 8 != 0) throw new RangeError("Byte out of range");- // Russian peasant multiplication- let z: int = 0;- for (let i = 7; i >= 0; i--) {- z = (z << 1) ^ ((z >>> 7) * 0x11d);- z ^= ((y >>> i) & 1) * x;- }- assert(z >>> 8 == 0);- return z as byte;- }+ // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.+ private static reedSolomonComputeRemainder(+ data: Readonly<Array<byte>>,+ divisor: Readonly<Array<byte>>,+ ): Array<byte> {+ let result: Array<byte> = divisor.map((_) => 0);+ for (const b of data) {+ // Polynomial division+ const factor: byte = b ^ (result.shift() as byte);+ result.push(0);+ divisor.forEach((coef, i) => (result[i]! ^= QrCode.reedSolomonMultiply(coef, factor)));+ }+ return result;+ }- // Can only be called immediately after a light run is added, and- // returns either 0, 1, or 2. A helper function for getPenaltyScore().- private finderPenaltyCountPatterns(runHistory: Readonly<Array<int>>): int {- const n: int = runHistory[1];- assert(n <= this.size * 3);- const core: boolean =- n > 0 &&- runHistory[2] == n &&- runHistory[3] == n * 3 &&- runHistory[4] == n &&- runHistory[5] == n;- return (- (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) +- (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0)- );- }+ // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result+ // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.+ private static reedSolomonMultiply(x: byte, y: byte): byte {+ if (x >>> 8 != 0 || y >>> 8 != 0) throw new RangeError("Byte out of range");+ // Russian peasant multiplication+ let z: int = 0;+ for (let i = 7; i >= 0; i--) {+ z = (z << 1) ^ ((z >>> 7) * 0x11d);+ z ^= ((y >>> i) & 1) * x;+ }+ assert(z >>> 8 == 0);+ return z as byte;+ }- // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().- private finderPenaltyTerminateAndCount(- currentRunColor: boolean,- currentRunLength: int,- runHistory: Array<int>,- ): int {- if (currentRunColor) {- // Terminate dark run- this.finderPenaltyAddHistory(currentRunLength, runHistory);- currentRunLength = 0;- }- currentRunLength += this.size; // Add light border to final run+ // Can only be called immediately after a light run is added, and+ // returns either 0, 1, or 2. A helper function for getPenaltyScore().+ private finderPenaltyCountPatterns(runHistory: Readonly<Array<int>>): int {+ const n: int = runHistory[1]!;+ assert(n <= this.size * 3);+ const core: boolean =+ n > 0 &&+ runHistory[2] === n &&+ runHistory[3] === n * 3 &&+ runHistory[4] === n &&+ runHistory[5] === n;+ return (+ (core && runHistory[0]! >= n * 4 && runHistory[6]! >= n ? 1 : 0) ++ (core && runHistory[6]! >= n * 4 && runHistory[0]! >= n ? 1 : 0)+ );+ }++ // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().+ private finderPenaltyTerminateAndCount(+ currentRunColor: boolean,+ currentRunLength: int,+ runHistory: Array<int>,+ ): int {+ if (currentRunColor) {+ // Terminate dark runthis.finderPenaltyAddHistory(currentRunLength, runHistory);- return this.finderPenaltyCountPatterns(runHistory);+ currentRunLength = 0;}+ currentRunLength += this.size; // Add light border to final run+ this.finderPenaltyAddHistory(currentRunLength, runHistory);+ return this.finderPenaltyCountPatterns(runHistory);+ }- // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().- private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array<int>): void {- if (runHistory[0] == 0) currentRunLength += this.size; // Add light border to initial run- runHistory.pop();- runHistory.unshift(currentRunLength);- }+ // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().+ private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array<int>): void {+ if (runHistory[0] === 0) currentRunLength += this.size; // Add light border to initial run+ runHistory.pop();+ runHistory.unshift(currentRunLength);+ }- /*-- Constants and tables --*/-- // The minimum version number supported in the QR Code Model 2 standard.- public static readonly MIN_VERSION: int = 1;- // The maximum version number supported in the QR Code Model 2 standard.- public static readonly MAX_VERSION: int = 40;-- // For use in getPenaltyScore(), when evaluating which mask is best.- private static readonly PENALTY_N1: int = 3;- private static readonly PENALTY_N2: int = 3;- private static readonly PENALTY_N3: int = 40;- private static readonly PENALTY_N4: int = 10;-- private static readonly ECC_CODEWORDS_PER_BLOCK: Array<Array<int>> = [- // Version: (note that index 0 is for padding, and is set to an illegal value)- //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level- [- -1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28,- 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,- ], // Low- [- -1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28,- 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,- ], // Medium- [- -1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30,- 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,- ], // Quartile- [- -1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24,- 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,- ], // High- ];-- private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array<Array<int>> = [- // Version: (note that index 0 is for padding, and is set to an illegal value)- //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level- [- -1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13,- 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25,- ], // Low- [- -1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21,- 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49,- ], // Medium- [- -1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29,- 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68,- ], // Quartile- [- -1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32,- 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81,- ], // High- ];- }-- // Appends the given number of low-order bits of the given value- // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.- function appendBits(val: int, len: int, bb: Array<bit>): void {- if (len < 0 || len > 31 || val >>> len != 0) throw new RangeError("Value out of range");- for (- let i = len - 1;- i >= 0;- i-- // Append bit by bit- )- bb.push((val >>> i) & 1);- }-- // Returns true iff the i'th bit of x is set to 1.- function getBit(x: int, i: int): boolean {- return ((x >>> i) & 1) != 0;- }-- // Throws an exception if the given condition is false.- function assert(cond: boolean): void {- if (!cond) throw new Error("Assertion error");- }-- /*---- Data segment class ----*/-- /*- * A segment of character/binary/control data in a QR Code symbol.- * Instances of this class are immutable.- * The mid-level way to create a segment is to take the payload data- * and call a static factory function such as QrSegment.makeNumeric().- * The low-level way to create a segment is to custom-make the bit buffer- * and call the QrSegment() constructor with appropriate values.- * This segment class imposes no length restrictions, but QR Codes have restrictions.- * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.- * Any segment longer than this is meaningless for the purpose of generating QR Codes.- */- export class QrSegment {- /*-- Static factory functions (mid level) --*/-- // Returns a segment representing the given binary data encoded in- // byte mode. All input byte arrays are acceptable. Any text string- // can be converted to UTF-8 bytes and encoded as a byte mode segment.- public static makeBytes(data: Readonly<Array<byte>>): QrSegment {- let bb: Array<bit> = [];- for (const b of data) appendBits(b, 8, bb);- return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);- }+ /*-- Constants and tables --*/++ // The minimum version number supported in the QR Code Model 2 standard.+ public static readonly MIN_VERSION: int = 1;+ // The maximum version number supported in the QR Code Model 2 standard.+ public static readonly MAX_VERSION: int = 40;++ // For use in getPenaltyScore(), when evaluating which mask is best.+ private static readonly PENALTY_N1: int = 3;+ private static readonly PENALTY_N2: int = 3;+ private static readonly PENALTY_N3: int = 40;+ private static readonly PENALTY_N4: int = 10;++ private static readonly ECC_CODEWORDS_PER_BLOCK: Array<Array<int>> = [+ // Version: (note that index 0 is for padding, and is set to an illegal value)+ //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level+ [+ -1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30,+ 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,+ ], // Low+ [+ -1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28,+ 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,+ ], // Medium+ [+ -1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30,+ 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,+ ], // Quartile+ [+ -1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24,+ 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,+ ], // High+ ];++ private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array<Array<int>> = [+ // Version: (note that index 0 is for padding, and is set to an illegal value)+ //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level+ [+ -1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13,+ 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25,+ ], // Low+ [+ -1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23,+ 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49,+ ], // Medium+ [+ -1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29,+ 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68,+ ], // Quartile+ [+ -1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35,+ 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81,+ ], // High+ ];+}- // Returns a segment representing the given string of decimal digits encoded in numeric mode.- public static makeNumeric(digits: string): QrSegment {- if (!QrSegment.isNumeric(digits))- throw new RangeError("String contains non-numeric characters");- let bb: Array<bit> = [];- for (let i = 0; i < digits.length; ) {- // Consume up to 3 digits per iteration- const n: int = Math.min(digits.length - i, 3);- appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);- i += n;- }- return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);- }+// Appends the given number of low-order bits of the given value+// to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.+function appendBits(val: int, len: int, bb: Array<bit>): void {+ if (len < 0 || len > 31 || val >>> len != 0) throw new RangeError("Value out of range");+ for (+ let i = len - 1;+ i >= 0;+ i-- // Append bit by bit+ )+ bb.push((val >>> i) & 1);+}- // Returns a segment representing the given text string encoded in alphanumeric mode.- // The characters allowed are: 0 to 9, A to Z (uppercase only), space,- // dollar, percent, asterisk, plus, hyphen, period, slash, colon.- public static makeAlphanumeric(text: string): QrSegment {- if (!QrSegment.isAlphanumeric(text))- throw new RangeError("String contains unencodable characters in alphanumeric mode");- let bb: Array<bit> = [];- let i: int;- for (i = 0; i + 2 <= text.length; i += 2) {- // Process groups of 2- let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;- temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));- appendBits(temp, 11, bb);- }- if (i < text.length)- // 1 character remaining- appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);- return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);- }+// Returns true iff the i'th bit of x is set to 1.+function getBit(x: int, i: int): boolean {+ return ((x >>> i) & 1) != 0;+}- // Returns a new mutable list of zero or more segments to represent the given Unicode text string.- // The result may use various segment modes and switch modes to optimize the length of the bit stream.- public static makeSegments(text: string): Array<QrSegment> {- // Select the most efficient segment encoding automatically- if (text == "") return [];- else if (QrSegment.isNumeric(text)) return [QrSegment.makeNumeric(text)];- else if (QrSegment.isAlphanumeric(text)) return [QrSegment.makeAlphanumeric(text)];- else return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];- }+// Throws an exception if the given condition is false.+function assert(cond: boolean): void {+ if (!cond) throw new Error("Assertion error");+}- // Returns a segment representing an Extended Channel Interpretation- // (ECI) designator with the given assignment value.- public static makeEci(assignVal: int): QrSegment {- let bb: Array<bit> = [];- if (assignVal < 0) throw new RangeError("ECI assignment value out of range");- else if (assignVal < 1 << 7) appendBits(assignVal, 8, bb);- else if (assignVal < 1 << 14) {- appendBits(0b10, 2, bb);- appendBits(assignVal, 14, bb);- } else if (assignVal < 1000000) {- appendBits(0b110, 3, bb);- appendBits(assignVal, 21, bb);- } else throw new RangeError("ECI assignment value out of range");- return new QrSegment(QrSegment.Mode.ECI, 0, bb);- }+/*---- Data segment class ----*/- // Tests whether the given string can be encoded as a segment in numeric mode.- // A string is encodable iff each character is in the range 0 to 9.- public static isNumeric(text: string): boolean {- return QrSegment.NUMERIC_REGEX.test(text);- }+/*+ * A segment of character/binary/control data in a QR Code symbol.+ * Instances of this class are immutable.+ * The mid-level way to create a segment is to take the payload data+ * and call a static factory function such as QrSegment.makeNumeric().+ * The low-level way to create a segment is to custom-make the bit buffer+ * and call the QrSegment() constructor with appropriate values.+ * This segment class imposes no length restrictions, but QR Codes have restrictions.+ * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.+ * Any segment longer than this is meaningless for the purpose of generating QR Codes.+ */+export class QrSegment {+ public static Mode: typeof QrSegmentMode;++ /*-- Static factory functions (mid level) --*/++ // Returns a segment representing the given binary data encoded in+ // byte mode. All input byte arrays are acceptable. Any text string+ // can be converted to UTF-8 bytes and encoded as a byte mode segment.+ public static makeBytes(data: Readonly<Array<byte>>): QrSegment {+ let bb: Array<bit> = [];+ for (const b of data) appendBits(b, 8, bb);+ return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);+ }- // Tests whether the given string can be encoded as a segment in alphanumeric mode.- // A string is encodable iff each character is in the following set: 0 to 9, A to Z- // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.- public static isAlphanumeric(text: string): boolean {- return QrSegment.ALPHANUMERIC_REGEX.test(text);- }+ // Returns a segment representing the given string of decimal digits encoded in numeric mode.+ public static makeNumeric(digits: string): QrSegment {+ if (!QrSegment.isNumeric(digits))+ throw new RangeError("String contains non-numeric characters");+ let bb: Array<bit> = [];+ for (let i = 0; i < digits.length; ) {+ // Consume up to 3 digits per iteration+ const n: int = Math.min(digits.length - i, 3);+ appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);+ i += n;+ }+ return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);+ }- /*-- Constructor (low level) and fields --*/-- // Creates a new QR Code segment with the given attributes and data.- // The character count (numChars) must agree with the mode and the bit buffer length,- // but the constraint isn't checked. The given bit buffer is cloned and stored.- public constructor(- // The mode indicator of this segment.- public readonly mode: QrSegment.Mode,-- // The length of this segment's unencoded data. Measured in characters for- // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.- // Always zero or positive. Not the same as the data's bit length.- public readonly numChars: int,-- // The data bits of this segment. Accessed through getData().- private readonly bitData: Array<bit>,- ) {- if (numChars < 0) throw new RangeError("Invalid argument");- this.bitData = bitData.slice(); // Make defensive copy- }+ // Returns a segment representing the given text string encoded in alphanumeric mode.+ // The characters allowed are: 0 to 9, A to Z (uppercase only), space,+ // dollar, percent, asterisk, plus, hyphen, period, slash, colon.+ public static makeAlphanumeric(text: string): QrSegment {+ if (!QrSegment.isAlphanumeric(text))+ throw new RangeError("String contains unencodable characters in alphanumeric mode");+ let bb: Array<bit> = [];+ let i: int;+ for (i = 0; i + 2 <= text.length; i += 2) {+ // Process groups of 2+ let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;+ temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));+ appendBits(temp, 11, bb);+ }+ if (i < text.length)+ // 1 character remaining+ appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);+ return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);+ }- /*-- Methods --*/+ // Returns a new mutable list of zero or more segments to represent the given Unicode text string.+ // The result may use various segment modes and switch modes to optimize the length of the bit stream.+ public static makeSegments(text: string): Array<QrSegment> {+ // Select the most efficient segment encoding automatically+ if (text == "") return [];+ else if (QrSegment.isNumeric(text)) return [QrSegment.makeNumeric(text)];+ else if (QrSegment.isAlphanumeric(text)) return [QrSegment.makeAlphanumeric(text)];+ else return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];+ }- // Returns a new copy of the data bits of this segment.- public getData(): Array<bit> {- return this.bitData.slice(); // Make defensive copy- }+ // Returns a segment representing an Extended Channel Interpretation+ // (ECI) designator with the given assignment value.+ public static makeEci(assignVal: int): QrSegment {+ let bb: Array<bit> = [];+ if (assignVal < 0) throw new RangeError("ECI assignment value out of range");+ else if (assignVal < 1 << 7) appendBits(assignVal, 8, bb);+ else if (assignVal < 1 << 14) {+ appendBits(0b10, 2, bb);+ appendBits(assignVal, 14, bb);+ } else if (assignVal < 1000000) {+ appendBits(0b110, 3, bb);+ appendBits(assignVal, 21, bb);+ } else throw new RangeError("ECI assignment value out of range");+ return new QrSegment(QrSegment.Mode.ECI, 0, bb);+ }- // (Package-private) Calculates and returns the number of bits needed to encode the given segments at- // the given version. The result is infinity if a segment has too many characters to fit its length field.- public static getTotalBits(segs: Readonly<Array<QrSegment>>, version: int): number {- let result: number = 0;- for (const seg of segs) {- const ccbits: int = seg.mode.numCharCountBits(version);- if (seg.numChars >= 1 << ccbits) return Infinity; // The segment's length doesn't fit the field's bit width- result += 4 + ccbits + seg.bitData.length;- }- return result;+ // Tests whether the given string can be encoded as a segment in numeric mode.+ // A string is encodable iff each character is in the range 0 to 9.+ public static isNumeric(text: string): boolean {+ return QrSegment.NUMERIC_REGEX.test(text);+ }++ // Tests whether the given string can be encoded as a segment in alphanumeric mode.+ // A string is encodable iff each character is in the following set: 0 to 9, A to Z+ // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.+ public static isAlphanumeric(text: string): boolean {+ return QrSegment.ALPHANUMERIC_REGEX.test(text);+ }++ /*-- Constructor (low level) and fields --*/++ public readonly mode: QrSegmentMode;+ public readonly numChars: int;+ private readonly bitData: Array<bit>;++ // Creates a new QR Code segment with the given attributes and data.+ // The character count (numChars) must agree with the mode and the bit buffer length,+ // but the constraint isn't checked. The given bit buffer is cloned and stored.+ public constructor(+ // The mode indicator of this segment.+ mode: QrSegmentMode,++ // The length of this segment's unencoded data. Measured in characters for+ // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.+ // Always zero or positive. Not the same as the data's bit length.+ numChars: int,++ // The data bits of this segment. Accessed through getData().+ bitData: Array<bit>,+ ) {+ this.mode = mode;+ this.numChars = numChars;+ if (numChars < 0) throw new RangeError("Invalid argument");+ this.bitData = bitData.slice(); // Make defensive copy+ }++ /*-- Methods --*/++ // Returns a new copy of the data bits of this segment.+ public getData(): Array<bit> {+ return this.bitData.slice(); // Make defensive copy+ }++ // (Package-private) Calculates and returns the number of bits needed to encode the given segments at+ // the given version. The result is infinity if a segment has too many characters to fit its length field.+ public static getTotalBits(segs: Readonly<Array<QrSegment>>, version: int): number {+ let result: number = 0;+ for (const seg of segs) {+ const ccbits: int = seg.mode.numCharCountBits(version);+ if (seg.numChars >= 1 << ccbits) return Infinity; // The segment's length doesn't fit the field's bit width+ result += 4 + ccbits + seg.bitData.length;}+ return result;+ }- // Returns a new array of bytes representing the given string encoded in UTF-8.- private static toUtf8ByteArray(str: string): Array<byte> {- str = encodeURI(str);- let result: Array<byte> = [];- for (let i = 0; i < str.length; i++) {- if (str.charAt(i) != "%") result.push(str.charCodeAt(i));- else {- result.push(parseInt(str.substring(i + 1, i + 3), 16));- i += 2;- }+ // Returns a new array of bytes representing the given string encoded in UTF-8.+ private static toUtf8ByteArray(str: string): Array<byte> {+ str = encodeURI(str);+ let result: Array<byte> = [];+ for (let i = 0; i < str.length; i++) {+ if (str.charAt(i) != "%") result.push(str.charCodeAt(i));+ else {+ result.push(parseInt(str.substring(i + 1, i + 3), 16));+ i += 2;}- return result;}+ return result;+ }- /*-- Constants --*/+ /*-- Constants --*/- // Describes precisely all strings that are encodable in numeric mode.- private static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/;+ // Describes precisely all strings that are encodable in numeric mode.+ private static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/;- // Describes precisely all strings that are encodable in alphanumeric mode.- private static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+.\/:-]*$/;+ // Describes precisely all strings that are encodable in alphanumeric mode.+ private static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+.\/:-]*$/;- // The set of all legal characters in alphanumeric mode,- // where each character value maps to the index in the string.- private static readonly ALPHANUMERIC_CHARSET: string =- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";- }+ // The set of all legal characters in alphanumeric mode,+ // where each character value maps to the index in the string.+ private static readonly ALPHANUMERIC_CHARSET: string =+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";}/*---- Public helper enumeration ----*/-namespace qrcodegen.QrCode {- type int = number;+class QrCodeEcc {+ /*-- Constants --*/- /*- * The error correction level in a QR Code symbol. Immutable.- */- export class Ecc {- /*-- Constants --*/+ public static readonly LOW = new QrCodeEcc(0, 1); // The QR Code can tolerate about 7% erroneous codewords+ public static readonly MEDIUM = new QrCodeEcc(1, 0); // The QR Code can tolerate about 15% erroneous codewords+ public static readonly QUARTILE = new QrCodeEcc(2, 3); // The QR Code can tolerate about 25% erroneous codewords+ public static readonly HIGH = new QrCodeEcc(3, 2); // The QR Code can tolerate about 30% erroneous codewords- public static readonly LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords- public static readonly MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords- public static readonly QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords- public static readonly HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords+ public readonly ordinal: int;+ public readonly formatBits: int;- /*-- Constructor and fields --*/+ /*-- Constructor and fields --*/- private constructor(- // In the range 0 to 3 (unsigned 2-bit integer).- public readonly ordinal: int,- // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).- public readonly formatBits: int,- ) {}+ private constructor(+ // In the range 0 to 3 (unsigned 2-bit integer).+ ordinal: int,+ // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).+ formatBits: int,+ ) {+ this.ordinal = ordinal;+ this.formatBits = formatBits;}}/*---- Public helper enumeration ----*/-namespace qrcodegen.QrSegment {- type int = number;+class QrSegmentMode {+ /*-- Constants --*/- /*- * Describes how a segment's data bits are interpreted. Immutable.- */- export class Mode {- /*-- Constants --*/+ public static readonly NUMERIC = new QrSegmentMode(0x1, [10, 12, 14]);+ public static readonly ALPHANUMERIC = new QrSegmentMode(0x2, [9, 11, 13]);+ public static readonly BYTE = new QrSegmentMode(0x4, [8, 16, 16]);+ public static readonly KANJI = new QrSegmentMode(0x8, [8, 10, 12]);+ public static readonly ECI = new QrSegmentMode(0x7, [0, 0, 0]);- public static readonly NUMERIC = new Mode(0x1, [10, 12, 14]);- public static readonly ALPHANUMERIC = new Mode(0x2, [9, 11, 13]);- public static readonly BYTE = new Mode(0x4, [8, 16, 16]);- public static readonly KANJI = new Mode(0x8, [8, 10, 12]);- public static readonly ECI = new Mode(0x7, [0, 0, 0]);+ public readonly modeBits: int;+ private readonly numBitsCharCount: [int, int, int];- /*-- Constructor and fields --*/+ /*-- Constructor and fields --*/- private constructor(- // The mode indicator bits, which is a uint4 value (range 0 to 15).- public readonly modeBits: int,- // Number of character count bits for three different version ranges.- private readonly numBitsCharCount: [int, int, int],- ) {}+ private constructor(+ // The mode indicator bits, which is a uint4 value (range 0 to 15).+ modeBits: int,+ // Number of character count bits for three different version ranges.+ numBitsCharCount: [int, int, int],+ ) {+ this.modeBits = modeBits;+ this.numBitsCharCount = numBitsCharCount;+ }- /*-- Method --*/+ /*-- Method --*/- // (Package-private) Returns the bit width of the character count field for a segment in- // this mode in a QR Code at the given version number. The result is in the range [0, 16].- public numCharCountBits(ver: int): int {- return this.numBitsCharCount[Math.floor((ver + 7) / 17)];- }+ // (Package-private) Returns the bit width of the character count field for a segment in+ // this mode in a QR Code at the given version number. The result is in the range [0, 16].+ public numCharCountBits(ver: int): int {+ return this.numBitsCharCount[Math.floor((ver + 7) / 17)]!;}}-export const QrCode = qrcodegen.QrCode;-export const QrSegment = qrcodegen.QrSegment;+QrCode.Ecc = QrCodeEcc;+QrSegment.Mode = QrSegmentMode;diff --git a/packages/shared/src/searchRanking.test.ts b/packages/shared/src/searchRanking.test.tsindex d8c4b3d6c..dc43770bd 100644--- a/packages/shared/src/searchRanking.test.ts+++ b/packages/shared/src/searchRanking.test.ts@@ -6,7 +6,7 @@ import {normalizeSearchQuery,scoreQueryMatch,scoreSubsequenceMatch,-} from "./searchRanking";+} from "./searchRanking.ts";describe("normalizeSearchQuery", () => {it("trims and lowercases queries", () => {diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.tsindex 3d4a0da0b..89aa161c6 100644--- a/packages/shared/src/serverSettings.test.ts+++ b/packages/shared/src/serverSettings.test.ts@@ -5,7 +5,7 @@ import {extractPersistedServerObservabilitySettings,normalizePersistedServerSettingString,parsePersistedServerObservabilitySettings,-} from "./serverSettings";+} from "./serverSettings.ts";describe("serverSettings helpers", () => {it("normalizes optional persisted strings", () => {diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.tsindex db9bdcc59..769485ceb 100644--- a/packages/shared/src/serverSettings.ts+++ b/packages/shared/src/serverSettings.ts@@ -1,7 +1,7 @@import { ServerSettings, type ServerSettingsPatch } from "@t3tools/contracts";import { Schema } from "effect";-import { deepMerge } from "./Struct";-import { fromLenientJson } from "./schemaJson";+import { deepMerge } from "./Struct.ts";+import { fromLenientJson } from "./schemaJson.ts";const ServerSettingsJson = fromLenientJson(ServerSettings);diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.tsindex 1c6494a53..1223ad3f0 100644--- a/packages/shared/src/shell.test.ts+++ b/packages/shared/src/shell.test.ts@@ -7,7 +7,7 @@ import {readEnvironmentFromLoginShell,readPathFromLaunchctl,readPathFromLoginShell,-} from "./shell";+} from "./shell.ts";describe("extractPathFromShellOutput", () => {it("extracts the path between capture markers", () => {diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.tsindex 5df46e3a1..110b19a85 100644--- a/scripts/build-desktop-artifact.ts+++ b/scripts/build-desktop-artifact.ts@@ -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;diff --git a/scripts/dev-runner.test.ts b/scripts/dev-runner.test.tsindex b880f1bca..ce4865ece 100644--- a/scripts/dev-runner.test.ts+++ b/scripts/dev-runner.test.ts@@ -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");diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.tsindex 4d34fe389..1621b60da 100644--- a/scripts/dev-runner.ts+++ b/scripts/dev-runner.ts@@ -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,+ );}diff --git a/scripts/merge-update-manifests.test.ts b/scripts/merge-update-manifests.test.tsindex 33ebacfb0..3f2e3b087 100644--- a/scripts/merge-update-manifests.test.ts+++ b/scripts/merge-update-manifests.test.ts@@ -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");+ }),+ );+});diff --git a/scripts/merge-update-manifests.ts b/scripts/merge-update-manifests.tsindex 1ff74d95e..1913cd711 100644--- a/scripts/merge-update-manifests.ts+++ b/scripts/merge-update-manifests.ts@@ -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]",- );- }-- const primaryPath = resolve(primaryPathArg);- const secondaryPath = resolve(secondaryPathArg);- const outputPath = resolve(outputPathArg ?? primaryPathArg);+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;- return {- platform: platformValue,- primaryPath,- secondaryPath,- outputPath,- };-}+ const primaryPath = path.resolve(primaryPathArg);+ const secondaryPath = path.resolve(secondaryPathArg);+ const outputPath = path.resolve(outputPathArg ?? primaryPathArg);-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,+ );}diff --git a/scripts/mock-update-server.test.ts b/scripts/mock-update-server.test.tsnew file mode 100644index 000000000..218dcd224--- /dev/null+++ b/scripts/mock-update-server.test.ts@@ -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");+ }),+ );+ }),+ );+});diff --git a/scripts/mock-update-server.ts b/scripts/mock-update-server.tsindex 57dab49ff..8062f01b1 100644--- a/scripts/mock-update-server.ts+++ b/scripts/mock-update-server.ts@@ -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 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;+});++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;}- 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 });++ if (decodedPath.includes("\0")) {+ return undefined;}- mockServerLog("info", `Serving file: ${filePath}`);- return new Response(file.stream());- },-});-mockServerLog("info", `running on http://localhost:${port}`);+ 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,+ );+}diff --git a/scripts/resolve-previous-release-tag.ts b/scripts/resolve-previous-release-tag.tsindex 22fd4f2e6..93f932821 100644--- a/scripts/resolve-previous-release-tag.ts+++ b/scripts/resolve-previous-release-tag.ts@@ -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,+ );+}diff --git a/scripts/tsconfig.json b/scripts/tsconfig.jsonindex e9ed7c8ae..3b189a767 100644--- a/scripts/tsconfig.json+++ b/scripts/tsconfig.json@@ -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"diff --git a/scripts/update-release-package-versions.test.ts b/scripts/update-release-package-versions.test.tsindex 9e31c7675..df2b194ce 100644--- a/scripts/update-release-package-versions.test.ts+++ b/scripts/update-release-package-versions.test.ts@@ -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,- });- });+ 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("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,- });- });+const readReleaseVersions = Effect.fn("readReleaseVersions")(function* (rootDir: string) {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const versions = new Map<string, string>();- 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,- });- });+ 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));+ }- it("throws on missing version", () => {- expect(() => parseArgs([])).toThrow("Usage:");- });+ return versions;+});- it("throws on duplicate version", () => {- expect(() => parseArgs(["1.2.3", "2.0.0"])).toThrow(- "Only one release version can be provided.",+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("throws on unknown flag", () => {- expect(() => parseArgs(["1.2.3", "--unknown"])).toThrow("Unknown argument: --unknown");- });+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-",+ });- it("throws on --root without value", () => {- expect(() => parseArgs(["1.2.3", "--root"])).toThrow("Missing value for --root.");- });+ yield* writePackageJsonFixtures(baseDir, "0.0.1");- 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 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");+ }),+ );});diff --git a/scripts/update-release-package-versions.ts b/scripts/update-release-package-versions.tsindex cefeef33e..d2baa85a1 100644--- a/scripts/update-release-package-versions.ts+++ b/scripts/update-release-package-versions.ts@@ -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;-}--export function updateReleasePackageVersions(+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 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 unknownFlags = Object.keys(flags).filter((k) => k !== "github-output" && k !== "root");- if (unknownFlags.length > 0) {- throw new Error(`Unknown argument: --${unknownFlags[0]}`);- }-- 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 },+});++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" });+});++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 (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`);- }}diff --git a/tsconfig.base.json b/tsconfig.base.jsonindex 538fa0f0e..8d481cc7f 100644--- a/tsconfig.base.json+++ b/tsconfig.base.json@@ -1,8 +1,13 @@{"compilerOptions": {- "target": "ES2023",- "module": "ESNext",- "moduleResolution": "Bundler",+ "target": "ESNext",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "noEmit": true,+ "allowImportingTsExtensions": true,+ "rewriteRelativeImportExtensions": true,+ "erasableSyntaxOnly": true,+ "verbatimModuleSyntax": true,"strict": true,"noUncheckedIndexedAccess": true,"exactOptionalPropertyTypes": true,