Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
}
},
"scripts": {
"build": "tsc -p tsconfig.json",
"build": "tsc -p tsconfig.json && bun scripts/stamp-version.mjs",
"check": "bun run typecheck && bun run lint && bun run test && bun run build",
"typecheck": "tsc -p tsconfig.json --noEmit",
"lint": "bunx oxlint --ignore-path ../../.oxlintignore src vitest.config.ts",
"lint": "bunx oxlint --ignore-path ../../.oxlintignore src scripts vitest.config.ts",
"test": "vitest run --coverage",
"prepack": "bun run build",
"release:preflight": "npm publish --dry-run --access public"
Expand Down
15 changes: 15 additions & 0 deletions packages/sdk/scripts/stamp-version.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Writes this package's version into the compiled build-version module, so built
// and bundled consumers report it without a runtime package.json read.
// Usage: bun scripts/stamp-version.mjs [packageRoot]
import { readFileSync, writeFileSync } from "node:fs"
import path from "node:path"
import { fileURLToPath } from "node:url"

const packageRoot = path.resolve(process.argv[2] ?? path.join(path.dirname(fileURLToPath(import.meta.url)), ".."))
const { version } = JSON.parse(readFileSync(path.join(packageRoot, "package.json"), "utf8"))
if (typeof version !== "string" || !version.trim()) {
throw new Error(`${packageRoot}/package.json has no version`)
}
const target = path.join(packageRoot, "dist", "sdk", "build-version.js")
readFileSync(target) // Fail loudly if tsc did not emit the module first.
writeFileSync(target, `export const BUILD_VERSION = ${JSON.stringify(version.trim())};\n`)
4 changes: 4 additions & 0 deletions packages/sdk/src/sdk/build-version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// `bun run build` overwrites the compiled `dist/sdk/build-version.js` with this
// package's version (scripts/stamp-version.mjs). Source stays unset so dev and
// tests fall back to reading package.json next to `src/`.
export const BUILD_VERSION: string | undefined = undefined
54 changes: 52 additions & 2 deletions packages/sdk/src/sdk/sdk-version.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,39 @@
import { describe, expect, it, vi } from "vitest"
import { execFileSync } from "node:child_process"
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { fileURLToPath, pathToFileURL } from "node:url"
import { afterEach, describe, expect, it, vi } from "vitest"

const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..")
const packageVersion = (JSON.parse(readFileSync(path.join(packageRoot, "package.json"), "utf8")) as { version: string }).version

describe("sdk-version", () => {
it("reads and caches version from package.json", async () => {
afterEach(() => {
vi.doUnmock("node:fs")
vi.doUnmock("./build-version.js")
vi.resetModules()
})

it("reports this package's version from source", async () => {
vi.resetModules()
const { getSdkVersion } = await import("./sdk-version.js")
expect(getSdkVersion()).toBe(packageVersion)
})

it("prefers the build-stamped version without reading package.json", async () => {
vi.resetModules()
const readFileSync = vi.fn(() => JSON.stringify({ version: "9.8.7" }))
vi.doMock("node:fs", () => ({ readFileSync }))
vi.doMock("./build-version.js", () => ({ BUILD_VERSION: "1.2.3" }))

const { getSdkVersion } = await import("./sdk-version.js")
expect(getSdkVersion()).toBe("1.2.3")
expect(getSdkVersion()).toBe("1.2.3")
expect(readFileSync).not.toHaveBeenCalled()
})

it("reads and caches the source package.json version", async () => {
vi.resetModules()
const readFileSync = vi.fn(() => JSON.stringify({ version: "9.8.7" }))
vi.doMock("node:fs", () => ({ readFileSync }))
Expand All @@ -20,4 +52,22 @@ describe("sdk-version", () => {
const { getSdkVersion } = await import("./sdk-version.js")
expect(getSdkVersion()).toBeUndefined()
})

it("stamps the package version into the built module", async () => {
const root = mkdtempSync(path.join(tmpdir(), "inline-sdk-stamp-"))
try {
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: " 4.5.6-alpha.1 " }))
mkdirSync(path.join(root, "dist", "sdk"), { recursive: true })
writeFileSync(path.join(root, "dist", "sdk", "build-version.js"), "export const BUILD_VERSION = undefined;\n")

execFileSync(process.execPath, [path.join(packageRoot, "scripts", "stamp-version.mjs"), root])

const built = (await import(pathToFileURL(path.join(root, "dist", "sdk", "build-version.js")).href)) as {
BUILD_VERSION: unknown
}
expect(built.BUILD_VERSION).toBe("4.5.6-alpha.1")
} finally {
rmSync(root, { recursive: true, force: true })
}
})
})
29 changes: 14 additions & 15 deletions packages/sdk/src/sdk/sdk-version.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,29 @@
import { readFileSync } from "node:fs"
import { BUILD_VERSION } from "./build-version.js"

let cached: string | undefined | null = null

// Best-effort. Used for ConnectionInit.clientVersion.
//
// Built output carries the version as a literal, so the published files and any
// bundle made from them report it without resolving a package.json relative to
// wherever they end up. Only unbuilt source (monorepo dev and tests) reads it.
export const getSdkVersion = (): string | undefined => {
if (cached !== null) return cached
cached = BUILD_VERSION ?? readSourcePackageVersion()
return cached
}

function readSourcePackageVersion(): string | undefined {
try {
// This file compiles to `dist/sdk/sdk-version.js`, so `../../package.json`
// resolves to the published package's root package.json.
const pkgUrl = new URL("../../package.json", import.meta.url)
const raw = readFileSync(pkgUrl, "utf8")
// From `src/sdk/sdk-version.ts`, `../../package.json` is this package's root.
const raw = readFileSync(new URL("../../package.json", import.meta.url), "utf8")
const parsed: unknown = JSON.parse(raw)
if (typeof parsed === "object" && parsed !== null && "version" in parsed && typeof (parsed as any).version === "string") {
const version = ((parsed as any).version as string).trim()
if (!version) {
cached = undefined
return cached
}
cached = version
return version
if (typeof parsed === "object" && parsed !== null && "version" in parsed && typeof parsed.version === "string") {
return parsed.version.trim() || undefined
}
} catch {
// ignore
}

cached = undefined
return cached
return undefined
}
Loading