@remixhq/core 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +15 -0
  3. package/dist/api.d.ts +494 -0
  4. package/dist/api.js +7 -0
  5. package/dist/auth.d.ts +27 -0
  6. package/dist/auth.js +15 -0
  7. package/dist/binding.d.ts +16 -0
  8. package/dist/binding.js +11 -0
  9. package/dist/chunk-2WGZS7CD.js +0 -0
  10. package/dist/chunk-34WDQCPF.js +242 -0
  11. package/dist/chunk-4OCNZHHR.js +0 -0
  12. package/dist/chunk-54CBEP2W.js +570 -0
  13. package/dist/chunk-55K5GHAZ.js +252 -0
  14. package/dist/chunk-5H5CZKGN.js +691 -0
  15. package/dist/chunk-5NTOJXEZ.js +223 -0
  16. package/dist/chunk-7WUKH3ZD.js +221 -0
  17. package/dist/chunk-AE2HPMUZ.js +80 -0
  18. package/dist/chunk-AEAOYVIL.js +200 -0
  19. package/dist/chunk-BJFCN2C3.js +46 -0
  20. package/dist/chunk-DCU3646I.js +12 -0
  21. package/dist/chunk-DEWAIK5X.js +11 -0
  22. package/dist/chunk-DRD6EVTT.js +447 -0
  23. package/dist/chunk-E4KAGBU7.js +134 -0
  24. package/dist/chunk-EF3677RE.js +93 -0
  25. package/dist/chunk-EVWDYCBL.js +223 -0
  26. package/dist/chunk-FAZUMWBS.js +93 -0
  27. package/dist/chunk-GC2MOT3U.js +12 -0
  28. package/dist/chunk-GFOBGYW4.js +252 -0
  29. package/dist/chunk-INDDXWAH.js +92 -0
  30. package/dist/chunk-K57ZFDGC.js +15 -0
  31. package/dist/chunk-NDA7EJJA.js +286 -0
  32. package/dist/chunk-NK2DA4X6.js +357 -0
  33. package/dist/chunk-OJMTW22J.js +286 -0
  34. package/dist/chunk-OMUDRPUI.js +195 -0
  35. package/dist/chunk-ONKKRS2C.js +239 -0
  36. package/dist/chunk-OWFBBWU7.js +196 -0
  37. package/dist/chunk-P7EM3N73.js +46 -0
  38. package/dist/chunk-PR5QKMHM.js +46 -0
  39. package/dist/chunk-RIP2MIZL.js +710 -0
  40. package/dist/chunk-TQHLFQY4.js +448 -0
  41. package/dist/chunk-TY3SSQQK.js +688 -0
  42. package/dist/chunk-UGKPOCN5.js +710 -0
  43. package/dist/chunk-VM3CGCNX.js +46 -0
  44. package/dist/chunk-XOQIADCH.js +223 -0
  45. package/dist/chunk-YZ34ICNN.js +17 -0
  46. package/dist/chunk-ZBMOGUSJ.js +17 -0
  47. package/dist/collab.d.ts +680 -0
  48. package/dist/collab.js +1917 -0
  49. package/dist/config.d.ts +22 -0
  50. package/dist/config.js +9 -0
  51. package/dist/errors.d.ts +21 -0
  52. package/dist/errors.js +12 -0
  53. package/dist/index.cjs +1269 -0
  54. package/dist/index.d.cts +482 -0
  55. package/dist/index.d.ts +6 -0
  56. package/dist/index.js +34 -0
  57. package/dist/repo.d.ts +66 -0
  58. package/dist/repo.js +62 -0
  59. package/dist/tokenProvider-BWTusyj4.d.ts +63 -0
  60. package/package.json +72 -0
@@ -0,0 +1,223 @@
1
+ import {
2
+ RemixError
3
+ } from "./chunk-YZ34ICNN.js";
4
+
5
+ // src/auth/session.ts
6
+ import { z } from "zod";
7
+ var storedSessionSchema = z.object({
8
+ access_token: z.string().min(1),
9
+ refresh_token: z.string().min(1),
10
+ expires_at: z.number().int().positive(),
11
+ token_type: z.string().min(1).optional(),
12
+ user: z.object({
13
+ id: z.string().min(1),
14
+ email: z.string().email().optional().nullable()
15
+ }).optional()
16
+ });
17
+
18
+ // src/auth/localSessionStore.ts
19
+ import fs from "fs/promises";
20
+ import os from "os";
21
+ import path from "path";
22
+ function xdgConfigHome() {
23
+ const value = process.env.XDG_CONFIG_HOME;
24
+ if (typeof value === "string" && value.trim()) return value;
25
+ return path.join(os.homedir(), ".config");
26
+ }
27
+ async function maybeLoadKeytar() {
28
+ try {
29
+ const mod = await new Function("return import('keytar')")();
30
+ const candidates = [mod, mod?.default].filter(Boolean);
31
+ for (const candidate of candidates) {
32
+ const value = candidate;
33
+ if (typeof value.getPassword === "function" && typeof value.setPassword === "function") {
34
+ return value;
35
+ }
36
+ }
37
+ } catch {
38
+ return null;
39
+ }
40
+ return null;
41
+ }
42
+ async function ensurePathPermissions(filePath) {
43
+ const dir = path.dirname(filePath);
44
+ await fs.mkdir(dir, { recursive: true });
45
+ try {
46
+ await fs.chmod(dir, 448);
47
+ } catch {
48
+ }
49
+ try {
50
+ await fs.chmod(filePath, 384);
51
+ } catch {
52
+ }
53
+ }
54
+ async function writeJsonAtomic(filePath, value) {
55
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
56
+ const tmpPath = `${filePath}.tmp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
57
+ await fs.writeFile(tmpPath, JSON.stringify(value, null, 2) + "\n", "utf8");
58
+ await fs.rename(tmpPath, filePath);
59
+ }
60
+ async function writeSessionFileFallback(filePath, session) {
61
+ await writeJsonAtomic(filePath, session);
62
+ await ensurePathPermissions(filePath);
63
+ }
64
+ function createLocalSessionStore(params) {
65
+ const service = params?.service?.trim() || "remix-cli";
66
+ const account = params?.account?.trim() || "default";
67
+ const filePath = params?.filePath?.trim() || path.join(xdgConfigHome(), "remix", "session.json");
68
+ return {
69
+ async getSession() {
70
+ const keytar = await maybeLoadKeytar();
71
+ if (keytar) {
72
+ const raw2 = await keytar.getPassword(service, account);
73
+ if (!raw2) return null;
74
+ try {
75
+ const parsed = storedSessionSchema.safeParse(JSON.parse(raw2));
76
+ return parsed.success ? parsed.data : null;
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+ const raw = await fs.readFile(filePath, "utf8").catch(() => null);
82
+ if (!raw) return null;
83
+ try {
84
+ const parsed = storedSessionSchema.safeParse(JSON.parse(raw));
85
+ if (!parsed.success) return null;
86
+ await ensurePathPermissions(filePath);
87
+ return parsed.data;
88
+ } catch {
89
+ return null;
90
+ }
91
+ },
92
+ async setSession(session) {
93
+ const parsed = storedSessionSchema.safeParse(session);
94
+ if (!parsed.success) {
95
+ throw new Error("Session data is invalid and was not stored.");
96
+ }
97
+ const keytar = await maybeLoadKeytar();
98
+ if (keytar) {
99
+ await keytar.setPassword(service, account, JSON.stringify(parsed.data));
100
+ }
101
+ await writeSessionFileFallback(filePath, parsed.data);
102
+ }
103
+ };
104
+ }
105
+
106
+ // src/auth/tokenProvider.ts
107
+ function shouldRefreshSoon(session, skewSeconds = 60) {
108
+ const nowSec = Math.floor(Date.now() / 1e3);
109
+ return session.expires_at <= nowSec + skewSeconds;
110
+ }
111
+ function createStoredSessionTokenProvider(params) {
112
+ return async (opts) => {
113
+ const forceRefresh = Boolean(opts?.forceRefresh);
114
+ const envToken = process.env.COMERGE_ACCESS_TOKEN;
115
+ if (typeof envToken === "string" && envToken.trim().length > 0) {
116
+ return { token: envToken.trim(), session: null, fromEnv: true };
117
+ }
118
+ let session = await params.sessionStore.getSession();
119
+ if (!session) {
120
+ throw new RemixError("Not signed in.", {
121
+ exitCode: 2,
122
+ hint: "Run `remix login`, or set COMERGE_ACCESS_TOKEN for CI."
123
+ });
124
+ }
125
+ if (forceRefresh || shouldRefreshSoon(session)) {
126
+ try {
127
+ session = await params.refreshStoredSession({ config: params.config, session });
128
+ await params.sessionStore.setSession(session);
129
+ } catch (err) {
130
+ void err;
131
+ }
132
+ }
133
+ return { token: session.access_token, session, fromEnv: false };
134
+ };
135
+ }
136
+
137
+ // src/auth/supabase.ts
138
+ import { createClient } from "@supabase/supabase-js";
139
+ function createInMemoryStorage() {
140
+ const map = /* @__PURE__ */ new Map();
141
+ return {
142
+ getItem: (k) => map.get(k) ?? null,
143
+ setItem: (k, v) => {
144
+ map.set(k, v);
145
+ },
146
+ removeItem: (k) => {
147
+ map.delete(k);
148
+ }
149
+ };
150
+ }
151
+ function createSupabaseClient(config, storage) {
152
+ return createClient(config.supabaseUrl, config.supabaseAnonKey, {
153
+ auth: {
154
+ flowType: "pkce",
155
+ persistSession: false,
156
+ autoRefreshToken: false,
157
+ detectSessionInUrl: false,
158
+ storage
159
+ },
160
+ global: {
161
+ headers: {
162
+ "X-Requested-By": "comerge-cli"
163
+ }
164
+ }
165
+ });
166
+ }
167
+ function toStoredSession(session) {
168
+ if (!session.access_token || !session.refresh_token || !session.expires_at) {
169
+ throw new RemixError("Supabase session is missing required fields.", { exitCode: 1 });
170
+ }
171
+ return {
172
+ access_token: session.access_token,
173
+ refresh_token: session.refresh_token,
174
+ expires_at: session.expires_at,
175
+ token_type: session.token_type ?? void 0,
176
+ user: session.user ? { id: session.user.id, email: session.user.email ?? null } : void 0
177
+ };
178
+ }
179
+ function createSupabaseAuthHelpers(config) {
180
+ const storage = createInMemoryStorage();
181
+ const supabase = createSupabaseClient(config, storage);
182
+ return {
183
+ async startGoogleLogin(params) {
184
+ const { data, error } = await supabase.auth.signInWithOAuth({
185
+ provider: "google",
186
+ options: {
187
+ redirectTo: params.redirectTo,
188
+ skipBrowserRedirect: true,
189
+ queryParams: {
190
+ access_type: "offline",
191
+ prompt: "consent"
192
+ }
193
+ }
194
+ });
195
+ if (error) throw error;
196
+ if (!data?.url) throw new RemixError("Supabase did not return an OAuth URL.", { exitCode: 1 });
197
+ return { url: data.url };
198
+ },
199
+ async exchangeCode(params) {
200
+ const { data, error } = await supabase.auth.exchangeCodeForSession(params.code);
201
+ if (error) throw error;
202
+ if (!data?.session) throw new RemixError("Supabase did not return a session.", { exitCode: 1 });
203
+ return toStoredSession(data.session);
204
+ },
205
+ async refreshWithStoredSession(params) {
206
+ const { data, error } = await supabase.auth.setSession({
207
+ access_token: params.session.access_token,
208
+ refresh_token: params.session.refresh_token
209
+ });
210
+ if (error) throw error;
211
+ if (!data?.session) throw new RemixError("No session returned after refresh.", { exitCode: 1 });
212
+ return toStoredSession(data.session);
213
+ }
214
+ };
215
+ }
216
+
217
+ export {
218
+ storedSessionSchema,
219
+ createLocalSessionStore,
220
+ shouldRefreshSoon,
221
+ createStoredSessionTokenProvider,
222
+ createSupabaseAuthHelpers
223
+ };
@@ -0,0 +1,93 @@
1
+ import {
2
+ RemixError
3
+ } from "./chunk-YZ34ICNN.js";
4
+
5
+ // src/infrastructure/binding/collabBindingStore.ts
6
+ import fs2 from "fs/promises";
7
+ import path2 from "path";
8
+
9
+ // src/shared/fs.ts
10
+ import fs from "fs/promises";
11
+ import path from "path";
12
+ async function reserveDirectory(targetDir) {
13
+ try {
14
+ await fs.mkdir(targetDir);
15
+ return targetDir;
16
+ } catch (error) {
17
+ if (error?.code === "EEXIST") {
18
+ throw new RemixError("Output directory already exists.", {
19
+ exitCode: 2,
20
+ hint: `Choose an empty destination path: ${targetDir}`
21
+ });
22
+ }
23
+ throw error;
24
+ }
25
+ }
26
+ async function reserveAvailableDirPath(preferredDir) {
27
+ const parent = path.dirname(preferredDir);
28
+ const base = path.basename(preferredDir);
29
+ for (let i = 1; i <= 1e3; i += 1) {
30
+ const candidate = i === 1 ? preferredDir : path.join(parent, `${base}-${i}`);
31
+ try {
32
+ await fs.mkdir(candidate);
33
+ return candidate;
34
+ } catch (error) {
35
+ if (error?.code === "EEXIST") continue;
36
+ throw error;
37
+ }
38
+ }
39
+ throw new RemixError("No available output directory name.", {
40
+ exitCode: 2,
41
+ hint: `Tried ${base} through ${base}-1000 under ${parent}.`
42
+ });
43
+ }
44
+ async function writeJsonAtomic(filePath, value) {
45
+ const dir = path.dirname(filePath);
46
+ await fs.mkdir(dir, { recursive: true });
47
+ const tmp = `${filePath}.tmp-${Date.now()}`;
48
+ await fs.writeFile(tmp, `${JSON.stringify(value, null, 2)}
49
+ `, "utf8");
50
+ await fs.rename(tmp, filePath);
51
+ }
52
+
53
+ // src/infrastructure/binding/collabBindingStore.ts
54
+ function getCollabBindingPath(repoRoot) {
55
+ return path2.join(repoRoot, ".remix", "config.json");
56
+ }
57
+ async function readCollabBinding(repoRoot) {
58
+ try {
59
+ const raw = await fs2.readFile(getCollabBindingPath(repoRoot), "utf8");
60
+ const parsed = JSON.parse(raw);
61
+ if (parsed?.schemaVersion !== 1) return null;
62
+ if (!parsed.projectId || !parsed.currentAppId || !parsed.upstreamAppId) return null;
63
+ return {
64
+ schemaVersion: 1,
65
+ projectId: parsed.projectId,
66
+ currentAppId: parsed.currentAppId,
67
+ upstreamAppId: parsed.upstreamAppId,
68
+ threadId: parsed.threadId ?? null,
69
+ repoFingerprint: parsed.repoFingerprint ?? null,
70
+ remoteUrl: parsed.remoteUrl ?? null,
71
+ defaultBranch: parsed.defaultBranch ?? null,
72
+ preferredBranch: parsed.preferredBranch ?? parsed.defaultBranch ?? null
73
+ };
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+ async function writeCollabBinding(repoRoot, binding) {
79
+ const filePath = getCollabBindingPath(repoRoot);
80
+ await writeJsonAtomic(filePath, {
81
+ schemaVersion: 1,
82
+ ...binding
83
+ });
84
+ return filePath;
85
+ }
86
+
87
+ export {
88
+ reserveDirectory,
89
+ reserveAvailableDirPath,
90
+ getCollabBindingPath,
91
+ readCollabBinding,
92
+ writeCollabBinding
93
+ };
@@ -0,0 +1,12 @@
1
+ // src/errors/errorCodes.ts
2
+ var REMIX_ERROR_CODES = {
3
+ REPO_LOCK_HELD: "REPO_LOCK_HELD",
4
+ REPO_LOCK_TIMEOUT: "REPO_LOCK_TIMEOUT",
5
+ REPO_LOCK_STALE_RECOVERED: "REPO_LOCK_STALE_RECOVERED",
6
+ REPO_STATE_CHANGED_DURING_OPERATION: "REPO_STATE_CHANGED_DURING_OPERATION",
7
+ PREFERRED_BRANCH_MISMATCH: "PREFERRED_BRANCH_MISMATCH"
8
+ };
9
+
10
+ export {
11
+ REMIX_ERROR_CODES
12
+ };
@@ -0,0 +1,252 @@
1
+ import {
2
+ ComergeError
3
+ } from "./chunk-K57ZFDGC.js";
4
+
5
+ // src/api/client.ts
6
+ async function readJsonSafe(res) {
7
+ const ct = res.headers.get("content-type") ?? "";
8
+ if (!ct.toLowerCase().includes("application/json")) return null;
9
+ try {
10
+ return await res.json();
11
+ } catch {
12
+ return null;
13
+ }
14
+ }
15
+ function createApiClient(config, opts) {
16
+ const apiKey = (opts?.apiKey ?? "").trim();
17
+ const tokenProvider = opts?.tokenProvider;
18
+ const CLIENT_KEY_HEADER = "x-comerge-api-key";
19
+ async function request(path, init) {
20
+ if (!tokenProvider) {
21
+ throw new ComergeError("API client is missing a token provider.", {
22
+ exitCode: 1,
23
+ hint: "Configure auth before creating the Comerge API client."
24
+ });
25
+ }
26
+ const auth = await tokenProvider();
27
+ const url = new URL(path, config.apiUrl).toString();
28
+ const doFetch = async (bearer) => fetch(url, {
29
+ ...init,
30
+ headers: {
31
+ Accept: "application/json",
32
+ "Content-Type": "application/json",
33
+ ...init?.headers ?? {},
34
+ Authorization: `Bearer ${bearer}`,
35
+ ...apiKey ? { [CLIENT_KEY_HEADER]: apiKey } : {}
36
+ }
37
+ });
38
+ let res = await doFetch(auth.token);
39
+ if (res.status === 401 && !auth.fromEnv && auth.session?.refresh_token) {
40
+ const refreshed = await tokenProvider({ forceRefresh: true });
41
+ res = await doFetch(refreshed.token);
42
+ }
43
+ if (!res.ok) {
44
+ const body = await readJsonSafe(res);
45
+ const msg = (body && typeof body === "object" && body && "message" in body && typeof body.message === "string" ? body.message : null) ?? `Request failed (status ${res.status})`;
46
+ throw new ComergeError(msg, { exitCode: 1, hint: body ? JSON.stringify(body, null, 2) : null });
47
+ }
48
+ const json = await readJsonSafe(res);
49
+ return json ?? null;
50
+ }
51
+ async function requestBinary(path, init) {
52
+ if (!tokenProvider) {
53
+ throw new ComergeError("API client is missing a token provider.", {
54
+ exitCode: 1,
55
+ hint: "Configure auth before creating the Comerge API client."
56
+ });
57
+ }
58
+ const auth = await tokenProvider();
59
+ const url = new URL(path, config.apiUrl).toString();
60
+ const doFetch = async (bearer) => fetch(url, {
61
+ ...init,
62
+ headers: {
63
+ Accept: "*/*",
64
+ ...init?.headers ?? {},
65
+ Authorization: `Bearer ${bearer}`,
66
+ ...apiKey ? { [CLIENT_KEY_HEADER]: apiKey } : {}
67
+ }
68
+ });
69
+ let res = await doFetch(auth.token);
70
+ if (res.status === 401 && !auth.fromEnv && auth.session?.refresh_token) {
71
+ const refreshed = await tokenProvider({ forceRefresh: true });
72
+ res = await doFetch(refreshed.token);
73
+ }
74
+ if (!res.ok) {
75
+ const body = await readJsonSafe(res);
76
+ const msg = (body && typeof body === "object" && body && "message" in body && typeof body.message === "string" ? body.message : null) ?? `Request failed (status ${res.status})`;
77
+ throw new ComergeError(msg, { exitCode: 1, hint: body ? JSON.stringify(body, null, 2) : null });
78
+ }
79
+ const contentDisposition = res.headers.get("content-disposition") ?? "";
80
+ const fileNameMatch = contentDisposition.match(/filename=\"([^\"]+)\"/i);
81
+ return {
82
+ data: Buffer.from(await res.arrayBuffer()),
83
+ fileName: fileNameMatch?.[1] ?? null,
84
+ contentType: res.headers.get("content-type")
85
+ };
86
+ }
87
+ return {
88
+ getMe: () => request("/v1/me", { method: "GET" }),
89
+ listOrganizations: () => request("/v1/organizations", { method: "GET" }),
90
+ listProjects: (params) => {
91
+ const qs = new URLSearchParams();
92
+ if (params?.organizationId) qs.set("organizationId", params.organizationId);
93
+ if (params?.clientAppId) qs.set("clientAppId", params.clientAppId);
94
+ const suffix = qs.toString() ? `?${qs.toString()}` : "";
95
+ return request(`/v1/projects${suffix}`, { method: "GET" });
96
+ },
97
+ resolveProjectBinding: (params) => {
98
+ const qs = new URLSearchParams();
99
+ if (params.repoFingerprint) qs.set("repoFingerprint", params.repoFingerprint);
100
+ if (params.remoteUrl) qs.set("remoteUrl", params.remoteUrl);
101
+ return request(`/v1/projects/bindings/resolve?${qs.toString()}`, { method: "GET" });
102
+ },
103
+ autoEnableDeveloper: () => request("/v1/developer/auto-enable", { method: "POST" }),
104
+ listClientApps: (params) => {
105
+ const qs = params?.orgId ? `?orgId=${encodeURIComponent(params.orgId)}` : "";
106
+ return request(`/v1/developer/client-apps${qs}`, { method: "GET" });
107
+ },
108
+ createClientApp: (payload) => request("/v1/developer/client-apps", { method: "POST", body: JSON.stringify(payload) }),
109
+ createClientAppKey: (clientAppId, payload) => request(`/v1/developer/client-apps/${encodeURIComponent(clientAppId)}/keys`, {
110
+ method: "POST",
111
+ body: JSON.stringify(payload ?? {})
112
+ }),
113
+ listApps: (params) => {
114
+ const qs = new URLSearchParams();
115
+ if (params?.projectId) qs.set("projectId", params.projectId);
116
+ if (params?.organizationId) qs.set("organizationId", params.organizationId);
117
+ if (params?.forked) qs.set("forked", params.forked);
118
+ const suffix = qs.toString() ? `?${qs.toString()}` : "";
119
+ return request(`/v1/apps${suffix}`, { method: "GET" });
120
+ },
121
+ getApp: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}`, { method: "GET" }),
122
+ getMergeRequest: (mrId) => request(`/v1/merge-requests/${encodeURIComponent(mrId)}`, { method: "GET" }),
123
+ presignImportUpload: (payload) => request("/v1/apps/import/upload/presign", { method: "POST", body: JSON.stringify(payload) }),
124
+ importFromUpload: (payload) => request("/v1/apps/import/upload", { method: "POST", body: JSON.stringify(payload) }),
125
+ presignImportUploadFirstParty: (payload) => request("/v1/apps/import/upload/presign/first-party", { method: "POST", body: JSON.stringify(payload) }),
126
+ importFromUploadFirstParty: (payload) => request("/v1/apps/import/upload/first-party", { method: "POST", body: JSON.stringify(payload) }),
127
+ importFromGithubFirstParty: (payload) => request("/v1/apps/import/github/first-party", { method: "POST", body: JSON.stringify(payload) }),
128
+ forkApp: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/fork`, { method: "POST", body: JSON.stringify(payload ?? {}) }),
129
+ downloadAppBundle: (appId) => requestBinary(`/v1/apps/${encodeURIComponent(appId)}/download.bundle`, { method: "GET" }),
130
+ createChangeStep: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps`, {
131
+ method: "POST",
132
+ body: JSON.stringify(payload)
133
+ }),
134
+ createCollabTurn: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/collab-turns`, {
135
+ method: "POST",
136
+ body: JSON.stringify(payload)
137
+ }),
138
+ listCollabTurns: (appId, params) => {
139
+ const qs = new URLSearchParams();
140
+ if (params?.limit !== void 0) qs.set("limit", String(params.limit));
141
+ if (params?.offset !== void 0) qs.set("offset", String(params.offset));
142
+ if (params?.changeStepId) qs.set("changeStepId", params.changeStepId);
143
+ if (params?.threadId) qs.set("threadId", params.threadId);
144
+ if (params?.createdAfter) qs.set("createdAfter", params.createdAfter);
145
+ if (params?.createdBefore) qs.set("createdBefore", params.createdBefore);
146
+ const suffix = qs.toString() ? `?${qs.toString()}` : "";
147
+ return request(`/v1/apps/${encodeURIComponent(appId)}/collab-turns${suffix}`, { method: "GET" });
148
+ },
149
+ getCollabTurn: (appId, collabTurnId) => request(`/v1/apps/${encodeURIComponent(appId)}/collab-turns/${encodeURIComponent(collabTurnId)}`, {
150
+ method: "GET"
151
+ }),
152
+ getAgentMemorySummary: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/agent-memory/summary`, { method: "GET" }),
153
+ listAgentMemoryTimeline: (appId, params) => {
154
+ const qs = new URLSearchParams();
155
+ if (params?.limit !== void 0) qs.set("limit", String(params.limit));
156
+ if (params?.offset !== void 0) qs.set("offset", String(params.offset));
157
+ if (params?.createdAfter) qs.set("createdAfter", params.createdAfter);
158
+ if (params?.createdBefore) qs.set("createdBefore", params.createdBefore);
159
+ if (params?.kinds?.length) {
160
+ for (const kind of params.kinds) qs.append("kinds", kind);
161
+ }
162
+ const suffix = qs.toString() ? `?${qs.toString()}` : "";
163
+ return request(`/v1/apps/${encodeURIComponent(appId)}/agent-memory/timeline${suffix}`, { method: "GET" });
164
+ },
165
+ searchAgentMemory: (appId, params) => {
166
+ const qs = new URLSearchParams();
167
+ qs.set("q", params.q);
168
+ if (params.limit !== void 0) qs.set("limit", String(params.limit));
169
+ if (params.offset !== void 0) qs.set("offset", String(params.offset));
170
+ if (params.createdAfter) qs.set("createdAfter", params.createdAfter);
171
+ if (params.createdBefore) qs.set("createdBefore", params.createdBefore);
172
+ if (params.kinds?.length) {
173
+ for (const kind of params.kinds) qs.append("kinds", kind);
174
+ }
175
+ return request(`/v1/apps/${encodeURIComponent(appId)}/agent-memory/search?${qs.toString()}`, { method: "GET" });
176
+ },
177
+ getChangeStep: (appId, changeStepId) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps/${encodeURIComponent(changeStepId)}`, { method: "GET" }),
178
+ getChangeStepDiff: (appId, changeStepId) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps/${encodeURIComponent(changeStepId)}/diff`, {
179
+ method: "GET"
180
+ }),
181
+ startChangeStepReplay: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps/replays`, {
182
+ method: "POST",
183
+ body: JSON.stringify(payload)
184
+ }),
185
+ getChangeStepReplay: (appId, replayId) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps/replays/${encodeURIComponent(replayId)}`, {
186
+ method: "GET"
187
+ }),
188
+ getChangeStepReplayDiff: (appId, replayId) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps/replays/${encodeURIComponent(replayId)}/diff`, {
189
+ method: "GET"
190
+ }),
191
+ listMergeRequests: (params) => {
192
+ const qs = new URLSearchParams();
193
+ if (params?.sourceAppId) qs.set("sourceAppId", params.sourceAppId);
194
+ if (params?.targetAppId) qs.set("targetAppId", params.targetAppId);
195
+ if (Array.isArray(params?.status)) {
196
+ for (const status of params.status) qs.append("status", status);
197
+ } else if (typeof params?.status === "string") {
198
+ qs.set("status", params.status);
199
+ }
200
+ if (params?.kind) qs.set("kind", params.kind);
201
+ const suffix = qs.toString() ? `?${qs.toString()}` : "";
202
+ return request(`/v1/merge-requests${suffix}`, { method: "GET" });
203
+ },
204
+ openMergeRequest: (sourceAppId) => request("/v1/merge-requests", { method: "POST", body: JSON.stringify({ sourceAppId }) }),
205
+ getMergeRequestReview: (mrId) => request(`/v1/merge-requests/${encodeURIComponent(mrId)}/review`, { method: "GET" }),
206
+ updateMergeRequest: (mrId, payload) => request(`/v1/merge-requests/${encodeURIComponent(mrId)}`, { method: "PATCH", body: JSON.stringify(payload) }),
207
+ createProjectInvite: (projectId, payload) => request(`/v1/projects/${encodeURIComponent(projectId)}/invitations`, {
208
+ method: "POST",
209
+ body: JSON.stringify(payload)
210
+ }),
211
+ syncUpstreamApp: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/sync-upstream`, {
212
+ method: "POST",
213
+ body: JSON.stringify({})
214
+ }),
215
+ preflightAppReconcile: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/reconcile/preflight`, {
216
+ method: "POST",
217
+ body: JSON.stringify(payload)
218
+ }),
219
+ startAppReconcile: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/reconcile/start`, {
220
+ method: "POST",
221
+ body: JSON.stringify(payload)
222
+ }),
223
+ getAppReconcile: (appId, reconcileId) => request(`/v1/apps/${encodeURIComponent(appId)}/reconcile/${encodeURIComponent(reconcileId)}`, { method: "GET" }),
224
+ downloadAppReconcileBundle: (appId, reconcileId) => requestBinary(`/v1/apps/${encodeURIComponent(appId)}/reconcile/${encodeURIComponent(reconcileId)}/download.bundle`, {
225
+ method: "GET"
226
+ }),
227
+ syncLocalApp: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/sync-local`, {
228
+ method: "POST",
229
+ body: JSON.stringify(payload)
230
+ }),
231
+ initiateBundle: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/bundles`, { method: "POST", body: JSON.stringify(payload) }),
232
+ getBundle: (appId, bundleId) => request(`/v1/apps/${encodeURIComponent(appId)}/bundles/${encodeURIComponent(bundleId)}`, { method: "GET" }),
233
+ getBundleDownloadUrl: (appId, bundleId, options) => request(
234
+ `/v1/apps/${encodeURIComponent(appId)}/bundles/${encodeURIComponent(bundleId)}/download?redirect=${options?.redirect ?? false}`,
235
+ { method: "GET" }
236
+ ),
237
+ getBundleAssetsDownloadUrl: (appId, bundleId, options) => {
238
+ const qs = new URLSearchParams({
239
+ redirect: String(options?.redirect ?? false),
240
+ kind: options?.kind ?? "metro-assets"
241
+ });
242
+ return request(
243
+ `/v1/apps/${encodeURIComponent(appId)}/bundles/${encodeURIComponent(bundleId)}/assets/download?${qs.toString()}`,
244
+ { method: "GET" }
245
+ );
246
+ }
247
+ };
248
+ }
249
+
250
+ export {
251
+ createApiClient
252
+ };
@@ -0,0 +1,92 @@
1
+ import {
2
+ ComergeError
3
+ } from "./chunk-ZBMOGUSJ.js";
4
+
5
+ // src/infrastructure/binding/collabBindingStore.ts
6
+ import fs2 from "fs/promises";
7
+ import path2 from "path";
8
+
9
+ // src/shared/fs.ts
10
+ import fs from "fs/promises";
11
+ import path from "path";
12
+ async function reserveDirectory(targetDir) {
13
+ try {
14
+ await fs.mkdir(targetDir);
15
+ return targetDir;
16
+ } catch (error) {
17
+ if (error?.code === "EEXIST") {
18
+ throw new ComergeError("Output directory already exists.", {
19
+ exitCode: 2,
20
+ hint: `Choose an empty destination path: ${targetDir}`
21
+ });
22
+ }
23
+ throw error;
24
+ }
25
+ }
26
+ async function reserveAvailableDirPath(preferredDir) {
27
+ const parent = path.dirname(preferredDir);
28
+ const base = path.basename(preferredDir);
29
+ for (let i = 1; i <= 1e3; i += 1) {
30
+ const candidate = i === 1 ? preferredDir : path.join(parent, `${base}-${i}`);
31
+ try {
32
+ await fs.mkdir(candidate);
33
+ return candidate;
34
+ } catch (error) {
35
+ if (error?.code === "EEXIST") continue;
36
+ throw error;
37
+ }
38
+ }
39
+ throw new ComergeError("No available output directory name.", {
40
+ exitCode: 2,
41
+ hint: `Tried ${base} through ${base}-1000 under ${parent}.`
42
+ });
43
+ }
44
+ async function writeJsonAtomic(filePath, value) {
45
+ const dir = path.dirname(filePath);
46
+ await fs.mkdir(dir, { recursive: true });
47
+ const tmp = `${filePath}.tmp-${Date.now()}`;
48
+ await fs.writeFile(tmp, `${JSON.stringify(value, null, 2)}
49
+ `, "utf8");
50
+ await fs.rename(tmp, filePath);
51
+ }
52
+
53
+ // src/infrastructure/binding/collabBindingStore.ts
54
+ function getCollabBindingPath(repoRoot) {
55
+ return path2.join(repoRoot, ".comerge", "config.json");
56
+ }
57
+ async function readCollabBinding(repoRoot) {
58
+ try {
59
+ const raw = await fs2.readFile(getCollabBindingPath(repoRoot), "utf8");
60
+ const parsed = JSON.parse(raw);
61
+ if (parsed?.schemaVersion !== 1) return null;
62
+ if (!parsed.projectId || !parsed.currentAppId || !parsed.upstreamAppId) return null;
63
+ return {
64
+ schemaVersion: 1,
65
+ projectId: parsed.projectId,
66
+ currentAppId: parsed.currentAppId,
67
+ upstreamAppId: parsed.upstreamAppId,
68
+ threadId: parsed.threadId ?? null,
69
+ repoFingerprint: parsed.repoFingerprint ?? null,
70
+ remoteUrl: parsed.remoteUrl ?? null,
71
+ defaultBranch: parsed.defaultBranch ?? null
72
+ };
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+ async function writeCollabBinding(repoRoot, binding) {
78
+ const filePath = getCollabBindingPath(repoRoot);
79
+ await writeJsonAtomic(filePath, {
80
+ schemaVersion: 1,
81
+ ...binding
82
+ });
83
+ return filePath;
84
+ }
85
+
86
+ export {
87
+ reserveDirectory,
88
+ reserveAvailableDirPath,
89
+ getCollabBindingPath,
90
+ readCollabBinding,
91
+ writeCollabBinding
92
+ };
@@ -0,0 +1,15 @@
1
+ // src/errors/cliError.ts
2
+ var ComergeError = class extends Error {
3
+ exitCode;
4
+ hint;
5
+ constructor(message, opts) {
6
+ super(message);
7
+ this.name = "ComergeError";
8
+ this.exitCode = opts?.exitCode ?? 1;
9
+ this.hint = opts?.hint ?? null;
10
+ }
11
+ };
12
+
13
+ export {
14
+ ComergeError
15
+ };