Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Schedule from "effect/Schedule";
4import * as Schema from "effect/Schema";
5import { SourceControlProviderError, SourceControlProviderKind } from "@t3tools/contracts";
6import { CURSOR_ORIGIN_WEB_BASE_URL } from "../shared/definition.ts";
7import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
8import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
9import {
10 probeSourceControlProvider,
11 providerAuth,
12 type SourceControlCliDiscoverySpec,
13 type SourceControlManagedCliDiscoverySpec,
14} from "@t3tools/source-control-core/server/discovery";
15
16import * as OriginCli from "./OriginCli.ts";
17import {
18 OriginPullRequestListSchema,
19 OriginPullRequestSchema,
20 OriginRepositorySchema,
21 pullReference,
22 toOriginChangeRequest,
23 type OriginRepository,
24} from "./originPullRequests.ts";
25
26const isOriginCliError = Schema.is(OriginCli.OriginCliError);
27
28const discovery = {
29 type: "cli",
30 kind: SourceControlProviderKind.make("cursor-origin"),
31 label: "Cursor Origin",
32 executable: OriginCli.ORIGIN_COMMAND,
33 versionArgs: ["--version"],
34 authArgs: ["auth", "status", "--json"],
35 parseAuth: (input) => {
36 const status = OriginCli.parseOriginAuthStatus(input.stdout);
37 const account = OriginCli.originAccount(status);
38 if (status === null) return providerAuth({ status: "unknown" });
39 return status.authenticated && status.tokenValid !== false
40 ? providerAuth({
41 status: "authenticated",
42 account: account ?? undefined,
43 host: "origin.cursor.com",
44 })
45 : providerAuth({
46 status: "unauthenticated",
47 detail: "Run `origin auth login` to sign in to Cursor Origin.",
48 });
49 },
50 installHint:
51 "Install the Origin CLI with `curl -fsSL https://downloads.cursor.com/origin/install.sh | sh`, then run `origin auth login`.",
52} satisfies SourceControlCliDiscoverySpec;
53
54/**
55 * Discovery names the account by its namespace slug, which is what owns its repositories (and so
56 * what Publish fills in), rather than the email `origin auth status` reports.
57 */
58export const makeDiscovery = Effect.gen(function* () {
59 const cli = yield* OriginCli.OriginCli;
60 const { process } = yield* SourceControlHost.SourceControlHost;
61 return {
62 type: "managed-cli",
63 kind: discovery.kind,
64 label: discovery.label,
65 installHint: discovery.installHint,
66 probe: Effect.fn("OriginSourceControlProvider.discovery")(function* (cwd: string) {
67 const item = yield* probeSourceControlProvider({ cwd, process, spec: discovery });
68 if (item.status !== "available" || item.auth.status !== "authenticated") return item;
69 const namespace = yield* cli.personalNamespace(cwd).pipe(Effect.option);
70 return { ...item, auth: { ...item.auth, account: namespace } };
71 }),
72 // `origin.cursor.com` is recognised from the remote alone, so there is nothing to refine.
73 refineUnknownRemote: () => Effect.succeed(null),
74 } satisfies SourceControlManagedCliDiscoverySpec;
75});
76
77const cloneUrls = (repository: OriginRepository, fallbackName: string) => {
78 const nameWithOwner =
79 repository.fullName ??
80 (repository.owner ? `${repository.owner.slug}/${repository.name}` : fallbackName);
81 const url = repository.cloneUrl ?? `https://origin.cursor.com/${nameWithOwner}.git`;
82 // Origin documents no SSH clone URL, and `origin auth login` already configures git's HTTPS
83 // credential helper, so HTTPS stands in for both.
84 return { nameWithOwner, url, sshUrl: url };
85};
86
87export const make = Effect.gen(function* () {
88 const cli = yield* OriginCli.OriginCli;
89 const fs = yield* FileSystem.FileSystem;
90 const { git } = yield* SourceControlHost.SourceControlHost;
91
92 const mapError = (
93 operation: string,
94 cwd: string,
95 extra?: { readonly repository?: string; readonly reference?: string },
96 ) =>
97 Effect.mapError(
98 (cause: unknown) =>
99 new SourceControlProviderError({
100 provider: SourceControlProviderKind.make("cursor-origin"),
101 operation,
102 cwd,
103 command: OriginCli.ORIGIN_COMMAND,
104 ...(extra?.repository
105 ? {
106 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
107 extra.repository,
108 ),
109 }
110 : {}),
111 ...(extra?.reference
112 ? {
113 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
114 extra.reference,
115 ),
116 }
117 : {}),
118 detail: isOriginCliError(cause) ? cause.detail : "Cursor Origin operation failed.",
119 cause,
120 }),
121 );
122
123 const getRepository = (cwd: string, repository: string, operation: string) =>
124 cli.api(
125 { cwd, operation, path: OriginCli.originRepositoryPath(repository) },
126 OriginRepositorySchema,
127 );
128
129 return SourceControlProvider.SourceControlProvider.of({
130 kind: SourceControlProviderKind.make("cursor-origin"),
131
132 /** Origin's browser pages live on cursor.com, not on the git host the remote names. */
133 refineRepositoryIdentity: Effect.fn("OriginSourceControlProvider.refineRepositoryIdentity")(
134 ({ identity }) => {
135 const path = SourceControlProvider.repositoryPathFromRemoteUrl(identity.locator.remoteUrl);
136 return Effect.succeed(
137 identity.provider === "cursor-origin" && path
138 ? { ...identity, webUrl: `${CURSOR_ORIGIN_WEB_BASE_URL}/${path}` }
139 : identity,
140 );
141 },
142 ),
143
144 listChangeRequests: Effect.fn("OriginSourceControlProvider.listChangeRequests")(
145 function* (input) {
146 const repository = yield* cli.resolveRepository(input);
147 const head = SourceControlProvider.sourceBranch(input);
148 const limit = Math.min(Math.max(input.limit ?? 20, 1), 100);
149 const query = new URLSearchParams({
150 head,
151 state: input.state,
152 pageSize: String(limit),
153 sortBy: "updated",
154 });
155 const page = yield* cli.api(
156 {
157 cwd: input.cwd,
158 operation: "listChangeRequests",
159 path: `${OriginCli.originRepositoryPath(repository)}/pulls?${query}`,
160 },
161 OriginPullRequestListSchema,
162 );
163 return (page.pullRequests ?? []).map(toOriginChangeRequest);
164 },
165 (effect, input) =>
166 effect.pipe(mapError("listChangeRequests", input.cwd, { reference: input.headSelector })),
167 ),
168
169 getChangeRequest: Effect.fn("OriginSourceControlProvider.getChangeRequest")(
170 function* (input) {
171 const reference = pullReference(input.reference);
172 const repository = reference.repository ?? (yield* cli.resolveRepository(input));
173 const number = reference.number;
174 if (number === null)
175 return yield* new OriginCli.OriginCliError({
176 operation: "getChangeRequest",
177 cwd: input.cwd,
178 reason: "not-found",
179 detail: "Specify a pull request number or Cursor Origin pull request URL.",
180 });
181 return toOriginChangeRequest(
182 yield* cli.api(
183 {
184 cwd: input.cwd,
185 operation: "getChangeRequest",
186 path: `${OriginCli.originRepositoryPath(repository)}/pulls/${number}`,
187 },
188 OriginPullRequestSchema,
189 ),
190 );
191 },
192 (effect, input) =>
193 effect.pipe(mapError("getChangeRequest", input.cwd, { reference: input.reference })),
194 ),
195
196 createChangeRequest: Effect.fn("OriginSourceControlProvider.createChangeRequest")(
197 function* (input) {
198 const repository = input.target?.repository ?? (yield* cli.resolveRepository(input));
199 // Origin creates drafts unless told otherwise; T3 asks for draft explicitly elsewhere.
200 yield* cli.api(
201 {
202 cwd: input.cwd,
203 operation: "createChangeRequest",
204 method: "POST",
205 path: `${OriginCli.originRepositoryPath(repository)}/pulls`,
206 body: {
207 title: input.title,
208 body: yield* fs.readFileString(input.bodyFile),
209 head: SourceControlProvider.sourceBranch(input),
210 base: input.target?.refName ?? input.baseRefName,
211 draft: false,
212 },
213 },
214 Schema.Unknown,
215 );
216 },
217 (effect, input) =>
218 effect.pipe(mapError("createChangeRequest", input.cwd, { reference: input.headSelector })),
219 ),
220
221 getRepositoryCloneUrls: Effect.fn("OriginSourceControlProvider.getRepositoryCloneUrls")(
222 function* (input) {
223 const repository = yield* getRepository(
224 input.cwd,
225 input.repository,
226 "getRepositoryCloneUrls",
227 );
228 return cloneUrls(repository, input.repository);
229 },
230 (effect, input) =>
231 effect.pipe(
232 mapError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),
233 ),
234 ),
235
236 createRepository: Effect.fn("OriginSourceControlProvider.createRepository")(
237 function* (input) {
238 if (input.visibility === "public")
239 return yield* new OriginCli.OriginCliError({
240 operation: "createRepository",
241 cwd: input.cwd,
242 reason: "failed",
243 detail: "Cursor Origin repositories are private. Choose private visibility.",
244 });
245 const parts = input.repository.split("/");
246 if (parts.length > 2 || parts.some((part) => part.trim().length === 0))
247 return yield* new OriginCli.OriginCliError({
248 operation: "createRepository",
249 cwd: input.cwd,
250 reason: "failed",
251 detail: "Specify an Origin repository as owner/name or name.",
252 });
253 const [owner, name] =
254 parts.length === 2 ? parts : [yield* cli.personalNamespace(input.cwd), input.repository];
255 yield* cli.api(
256 {
257 cwd: input.cwd,
258 operation: "createRepository",
259 method: "POST",
260 path: `/v1/origin/repos/${encodeURIComponent(owner ?? "")}`,
261 body: { name },
262 },
263 OriginRepositorySchema,
264 );
265 // Origin creates repositories internal (visible to the whole team) and only takes a
266 // visibility on update, so the repository is made private straight after.
267 const madePrivate = yield* cli
268 .api(
269 {
270 cwd: input.cwd,
271 operation: "createRepository",
272 method: "PATCH",
273 path: OriginCli.originRepositoryPath(`${owner}/${name}`),
274 body: { visibility: "private" },
275 },
276 OriginRepositorySchema,
277 )
278 .pipe(
279 Effect.retry({
280 times: 2,
281 schedule: Schedule.spaced("1 second"),
282 while: (error) =>
283 error.reason !== "rate-limited" && error.reason !== "unauthenticated",
284 }),
285 Effect.mapError(
286 (cause) =>
287 new OriginCli.OriginCliError({
288 operation: "createRepository",
289 cwd: input.cwd,
290 reason: cause.reason,
291 ...(cause.retryAt === undefined ? {} : { retryAt: cause.retryAt }),
292 detail: `Created ${owner}/${name}, but could not make it private, so your Cursor team can still see it. Set it to private on cursor.com.`,
293 cause,
294 }),
295 ),
296 );
297 return cloneUrls(madePrivate, `${owner}/${name}`);
298 },
299 (effect, input) =>
300 effect.pipe(mapError("createRepository", input.cwd, { repository: input.repository })),
301 ),
302
303 getDefaultBranch: Effect.fn("OriginSourceControlProvider.getDefaultBranch")(
304 function* (input) {
305 const repository = yield* cli.resolveRepository(input);
306 return (
307 (yield* getRepository(input.cwd, repository, "getDefaultBranch")).defaultBranch ?? null
308 );
309 },
310 (effect, input) => effect.pipe(mapError("getDefaultBranch", input.cwd)),
311 ),
312
313 checkoutChangeRequest: Effect.fn("OriginSourceControlProvider.checkoutChangeRequest")(
314 function* (input) {
315 const repository = yield* cli.resolveRepository(input);
316 const { repository: linked, number } = pullReference(input.reference);
317 const reference = input.reference.trim();
318 // The CLI reads a leading dash as a flag and ignores a target after `--`; no branch starts
319 // with one.
320 if (number === null && reference.startsWith("-"))
321 return yield* new OriginCli.OriginCliError({
322 operation: "checkoutChangeRequest",
323 cwd: input.cwd,
324 reason: "not-found",
325 detail: "Specify a pull request number, branch, or Cursor Origin pull request URL.",
326 });
327 if (linked !== null && linked !== repository.toLowerCase())
328 return yield* new OriginCli.OriginCliError({
329 operation: "checkoutChangeRequest",
330 cwd: input.cwd,
331 reason: "not-found",
332 detail: `That pull request is in ${linked}, not this checkout's ${repository}.`,
333 });
334 yield* cli.execute({
335 cwd: input.cwd,
336 operation: "checkoutChangeRequest",
337 args: [
338 "pr",
339 "checkout",
340 "-R",
341 repository,
342 "--remote",
343 input.context?.remoteName ?? (yield* git.resolvePrimaryRemoteName(input.cwd)),
344 ...(input.force ? ["--force"] : []),
345 number === null ? reference : String(number),
346 ],
347 });
348 },
349 (effect, input) =>
350 effect.pipe(mapError("checkoutChangeRequest", input.cwd, { reference: input.reference })),
351 ),
352 });
353});