The best way to control Claude Code, Codex and more from any computer or phone

main
ts 274 lines 10.1 KB
Raw
1 import * as Context from "effect/Context"
2 import * as Effect from "effect/Effect"
3 import * as HttpClient from "effect/http/HttpClient"
4 import * as HttpClientRequest from "effect/http/HttpClientRequest"
5 import * as HttpClientResponse from "effect/http/HttpClientResponse"
6 import * as Layer from "effect/Layer"
7 import * as Option from "effect/Option"
8 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"
9 import * as Schedule from "effect/Schedule"
10 import * as Schema from "effect/Schema"
11 import * as Semver from "semver"
12 import { NpmPromoteError, PromotionError, RegistryError } from "./NpmPromoteError.ts"
13 import * as Process from "./Process.ts"
14
15 export { NpmPromoteError, PromotionError, RegistryError } from "./NpmPromoteError.ts"
16
17 /**
18 * A public workspace package and the version it has at HEAD.
19 */
20 export interface ReleasePackage {
21 readonly name: string
22 readonly version: string
23 }
24
25 /**
26 * The `npm` commands the promoter runs.
27 */
28 export class NpmCli extends Context.Service<NpmCli, {
29 readonly addDistTag: (options: {
30 readonly name: string
31 readonly version: string
32 readonly tag: string
33 }) => Effect.Effect<void, NpmPromoteError>
34 }>()("@effect/npm-promote/NpmCli") {
35 /**
36 * Runs `npm dist-tag add`. In the workflow npm authenticates over OIDC with
37 * a trusted publisher configuration that allows dist-tags, which needs npm
38 * 11.21.0 or later. Locally it uses whatever npm login is configured.
39 */
40 static readonly layer = Layer.effect(
41 NpmCli,
42 Effect.gen(function*() {
43 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
44 return NpmCli.of({
45 addDistTag: ({ name, tag, version }) =>
46 Process.run("npm", ["dist-tag", "add", `${name}@${version}`, tag]).pipe(
47 Effect.asVoid,
48 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)
49 )
50 })
51 })
52 )
53 }
54
55 export type PromoteResult =
56 /** At least one target version is missing from the registry metadata. Nothing was promoted. */
57 | {
58 readonly _tag: "NotVisible"
59 readonly pending: ReadonlyArray<ReleasePackage>
60 }
61 /** Every target version is visible. `promoted` lists the packages whose `latest` was moved, in order. */
62 | {
63 readonly _tag: "Promoted"
64 readonly promoted: ReadonlyArray<ReleasePackage>
65 }
66
67 export const registryUrl = "https://registry.npmjs.org"
68
69 const abbreviatedMetadata = "application/vnd.npm.install-v1+json"
70
71 const encodePackageName = (name: string): string => encodeURIComponent(name).replace(/^%40/, "@")
72
73 const PackageMetadata = Schema.Struct({
74 "dist-tags": Schema.Record(Schema.String, Schema.String),
75 versions: Schema.Record(Schema.String, Schema.Unknown)
76 })
77
78 /**
79 * Retries connection failures and transient statuses (408, 429, 5xx) a few
80 * times. Anything that still fails is an error, never "not visible".
81 */
82 const withRetries = (client: HttpClient.HttpClient) =>
83 client.pipe(HttpClient.retryTransient({
84 schedule: Schedule.exponential("1 second"),
85 times: 3
86 }))
87
88 /**
89 * Reads a package's abbreviated metadata document. A 404 means the package has
90 * never been published and yields `None`.
91 */
92 const fetchMetadata = Effect.fnUntraced(function*(name: string) {
93 const client = withRetries(yield* HttpClient.HttpClient)
94 return yield* client.execute(
95 HttpClientRequest.get(`${registryUrl}/${encodePackageName(name)}`).pipe(
96 HttpClientRequest.accept(abbreviatedMetadata)
97 )
98 ).pipe(
99 Effect.flatMap(HttpClientResponse.matchStatus({
100 200: (response) => Effect.map(HttpClientResponse.schemaBodyJson(PackageMetadata)(response), Option.some),
101 404: () => Effect.succeed(Option.none()),
102 orElse: (response) =>
103 Effect.fail(
104 new NpmPromoteError({ message: `Registry returned status ${response.status} for ${name}` })
105 )
106 })),
107 Effect.mapError((cause) =>
108 Schema.is(NpmPromoteError)(cause) ? cause : new NpmPromoteError({
109 message: `Could not read registry metadata for ${name}`,
110 cause
111 })
112 )
113 )
114 })
115
116 /**
117 * Reads the current `latest` tag from the dist-tags endpoint. Unlike the
118 * abbreviated metadata, which the registry CDN caches for minutes, this
119 * endpoint is not cached, so it is the value to trust before a write.
120 */
121 export const liveLatest = Effect.fnUntraced(function*(name: string) {
122 const client = withRetries(yield* HttpClient.HttpClient)
123 return yield* client.execute(
124 HttpClientRequest.get(`${registryUrl}/-/package/${encodePackageName(name)}/dist-tags`).pipe(
125 HttpClientRequest.acceptJson
126 )
127 ).pipe(
128 Effect.flatMap(HttpClientResponse.filterStatusOk),
129 Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Record(Schema.String, Schema.String))),
130 Effect.map((tags): string | undefined => tags.latest),
131 Effect.mapError((cause) => new NpmPromoteError({ message: `Could not read the dist-tags of ${name}`, cause }))
132 )
133 })
134
135 const registryError = (pkg: ReleasePackage, cause: NpmPromoteError, promotionPending: boolean) =>
136 new RegistryError({
137 message: `${cause.message} while promoting ${pkg.name}@${pkg.version}`,
138 pkg,
139 promotionPending,
140 cause
141 })
142
143 /**
144 * Puts `effect` first and keeps the input order for everything else.
145 */
146 const promotionOrder = (packages: ReadonlyArray<ReleasePackage>): ReadonlyArray<ReleasePackage> => [
147 ...packages.filter((pkg) => pkg.name === "effect"),
148 ...packages.filter((pkg) => pkg.name !== "effect")
149 ]
150
151 /**
152 * `latest` needs to move when it is missing or lower than the target. A
153 * `latest` that is not valid semver is an error rather than a guess.
154 */
155 const needsPromotion = (pkg: ReleasePackage, latest: string | undefined): Effect.Effect<boolean, NpmPromoteError> => {
156 if (latest === undefined) {
157 return Effect.succeed(true)
158 }
159 if (Semver.valid(latest) === null) {
160 return Effect.fail(new NpmPromoteError({ message: `${pkg.name} has an invalid latest version: ${latest}` }))
161 }
162 return Effect.succeed(Semver.lt(latest, pkg.version))
163 }
164
165 /**
166 * Moves `latest` to the target version of every package once all target
167 * versions are visible in the registry's abbreviated metadata.
168 *
169 * `effect` is promoted first. Packages whose `latest` already equals the
170 * target, or is higher than it, are left alone. The abbreviated metadata only
171 * decides visibility: it is CDN-cached and can be stale, so each package is
172 * decided from its live `latest`. A failed registry read stops promotion with
173 * a `RegistryError` and a failed write with a `PromotionError`, so no package
174 * moves ahead of the ones before it. With `dryRun` the result is the same plan, but
175 * no dist-tag is changed.
176 */
177 export const promote = Effect.fnUntraced(function*(
178 packages: ReadonlyArray<ReleasePackage>,
179 options?: { readonly dryRun?: boolean | undefined }
180 ): Effect.fn.Return<
181 PromoteResult,
182 NpmPromoteError | PromotionError | RegistryError,
183 HttpClient.HttpClient | NpmCli
184 > {
185 for (const pkg of packages) {
186 if (Semver.valid(pkg.version) === null) {
187 return yield* new NpmPromoteError({ message: `${pkg.name} has an invalid target version: ${pkg.version}` })
188 }
189 }
190
191 const ordered = promotionOrder(packages)
192 const metadata = yield* Effect.forEach(
193 ordered,
194 (pkg) => fetchMetadata(pkg.name).pipe(Effect.mapError((cause) => registryError(pkg, cause, false))),
195 { concurrency: 8 }
196 )
197
198 const pending = ordered.filter((pkg, i) =>
199 Option.match(metadata[i], {
200 onNone: () => true,
201 onSome: (doc) => !Object.hasOwn(doc.versions, pkg.version)
202 })
203 )
204 if (pending.length > 0) {
205 return { _tag: "NotVisible", pending }
206 }
207
208 const npm = yield* NpmCli
209 const promoted: Array<ReleasePackage> = []
210 for (let i = 0; i < ordered.length; i++) {
211 const pkg = ordered[i]
212 const latest = yield* liveLatest(pkg.name).pipe(
213 Effect.mapError((cause) => registryError(pkg, cause, promoted.length > 0))
214 )
215 if (!(yield* needsPromotion(pkg, latest))) {
216 continue
217 }
218 if (options?.dryRun !== true) {
219 yield* npm.addDistTag({ name: pkg.name, version: pkg.version, tag: "latest" }).pipe(
220 Effect.mapError((cause) =>
221 new PromotionError({
222 message: `Could not move latest to ${pkg.name}@${pkg.version}: ${cause.message}`,
223 pkg,
224 reason: cause.message,
225 cause
226 })
227 )
228 )
229 }
230 promoted.push(pkg)
231 }
232 return { _tag: "Promoted", promoted }
233 })
234
235 /**
236 * Why a target version is missing from the abbreviated metadata, according to
237 * the version-specific registry document.
238 *
239 * - `Published`: the version document exists, so the abbreviated metadata is
240 * lagging behind.
241 * - `Missing`: the registry returned 404, so the publish most likely failed.
242 * - `Unknown`: the check itself failed. This is never treated as missing.
243 * - `PromotionFailed`: the version is visible, but moving `latest` to it failed.
244 */
245 export type Diagnosis =
246 | { readonly _tag: "Published"; readonly pkg: ReleasePackage }
247 | { readonly _tag: "Missing"; readonly pkg: ReleasePackage }
248 | { readonly _tag: "Unknown"; readonly pkg: ReleasePackage; readonly reason: string }
249 | { readonly _tag: "PromotionFailed"; readonly pkg: ReleasePackage; readonly reason: string }
250
251 const diagnose = Effect.fnUntraced(function*(pkg: ReleasePackage) {
252 const client = withRetries(yield* HttpClient.HttpClient)
253 return yield* client.execute(
254 HttpClientRequest.get(`${registryUrl}/${encodePackageName(pkg.name)}/${encodeURIComponent(pkg.version)}`).pipe(
255 HttpClientRequest.acceptJson
256 )
257 ).pipe(
258 Effect.map(HttpClientResponse.matchStatus({
259 200: (): Diagnosis => ({ _tag: "Published", pkg }),
260 404: (): Diagnosis => ({ _tag: "Missing", pkg }),
261 orElse: (response): Diagnosis => ({ _tag: "Unknown", pkg, reason: `registry returned status ${response.status}` })
262 })),
263 Effect.catch((error) => Effect.succeed<Diagnosis>({ _tag: "Unknown", pkg, reason: error.message }))
264 )
265 })
266
267 /**
268 * Checks the version-specific registry document of every pending package.
269 * Never fails: transport errors become `Unknown`.
270 */
271 export const diagnosePending = (
272 pending: ReadonlyArray<ReleasePackage>
273 ): Effect.Effect<ReadonlyArray<Diagnosis>, never, HttpClient.HttpClient> =>
274 Effect.forEach(pending, diagnose, { concurrency: 8 })