@hyperframes/share 0.9.102 → 0.9.104

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.
package/README.md CHANGED
@@ -21,7 +21,7 @@ bindShareHost({
21
21
  reviewUploadOrigins: ["https://review-bucket.s3.us-east-1.amazonaws.com"],
22
22
  signedInRequest,
23
23
  projectFingerprint,
24
- latestExportFile, // (dir) => { path, fingerprint, id } | null
24
+ latestExportFile, // (dir) => { path, fingerprint, id } | null, or a promise of it
25
25
  ffBinary, // ('ffprobe') => executable path
26
26
  });
27
27
  const client = reviewClient({ access, signedInEmail });
@@ -132,8 +132,16 @@ When the upload ID is known, recovery can check its status directly.
132
132
  A stalled storage PUT stops after 60 seconds without progress and can retry with
133
133
  the same upload identity.
134
134
 
135
- Default state uses `.hyperframes/share-sync.<backend-hash>.json`, with strict
136
- account/backend/realpath binding, private atomic writes, and a process lock.
135
+ The default store uses `source-bindings/` in the local HyperFrames configuration
136
+ directory (`HYPERFRAMES_CONFIG_DIR` or `~/.hyperframes`). Records are keyed by backend
137
+ and project realpath, checked against the signed-in account and written atomically
138
+ under the project lock. Copies and projects with only a legacy in-project record
139
+ start a new composition on the next explicit sync. To keep the history of a moved
140
+ or upgraded folder, run `hyperframes share --reconnect` or choose **Reconnect a
141
+ moved or upgraded project** in Studio before syncing. Confirm the cloud project
142
+ and workspace. When the local files differ from the published version, a separate
143
+ confirmation allows the next sync to publish those local files. Canceling leaves
144
+ the folder unbound. Reconnecting itself only updates the local binding.
137
145
  Hosts can inject a compatible `store` or read-only `existingBinding` resolver.
138
146
  An external Desktop binding is reused only when exact and settled; this adapter
139
147
  never writes Desktop's binding or starts a second upload on its behalf.
package/dist/hosts.d.ts CHANGED
@@ -25,7 +25,13 @@ export interface ShareHost {
25
25
  /** Requests to HeyGen's sign-in host as the signed-in person, traced as the host traces its API calls. */
26
26
  signedInRequest(deps: Omit<SignedInDeps, "trace">): ReturnType<typeof signedInRequest>;
27
27
  /** The newest finished export recorded in the project's renders folder whose file is still there. */
28
- latestExportFile(dir: string): { path: string; fingerprint?: string; id: string } | null;
28
+ /** May answer later, so a host can read its disk off its main thread. */
29
+ latestExportFile(
30
+ dir: string,
31
+ ):
32
+ | { path: string; fingerprint?: string; id: string }
33
+ | null
34
+ | Promise<{ path: string; fingerprint?: string; id: string } | null>;
29
35
  /** Trusted video upload origins configured by the host independently of the review API response. */
30
36
  reviewUploadOrigins?: readonly string[];
31
37
  /** This install's own secret: change-of-space journals are sealed with it; one it did not seal reads as none. */
package/dist/index.d.mts CHANGED
@@ -3,6 +3,7 @@ export { versionSentence } from "./reviewVersionSentences.mjs";
3
3
  export { shareOpenCalls } from "./reviewOpenCalls.mjs";
4
4
  export { bindShareHost } from "./host.mjs";
5
5
  export { SourceIgnoreError } from "./sourceIgnore.mjs";
6
+ export { sourceReconnect } from "./sources/reconnect.mjs";
6
7
  export type ShareHost = import("./hosts.js").ShareHost;
7
8
  export type ReviewClient = import("./reviewClient.mjs").ReviewClient;
8
9
  export type ReviewShare = import("./types/share.js").ReviewShare;
@@ -3,6 +3,10 @@ export function sourceApi({ access, fetchImpl }: {
3
3
  access: import("../signedInRequest.mjs").SignedInAccess;
4
4
  fetchImpl?: typeof fetch;
5
5
  }): {
6
+ /** @param {string} space */
7
+ list: (space: string) => Promise<import("./types.js").Composition[]>;
8
+ /** @param {string} space @param {string} composition */
9
+ get: (space: string, composition: string) => Promise<import("./types.js").Composition>;
6
10
  /** @param {string} space */
7
11
  limits: (space: string) => Promise<{
8
12
  at: "read";
@@ -12,7 +16,16 @@ export function sourceApi({ access, fetchImpl }: {
12
16
  push: import("./types.js").Limits;
13
17
  }>;
14
18
  /** @param {string} space @param {string} composition @param {string} title */
15
- create: (space: string, composition: string, title: string) => Promise<import("./types.js").Composition>;
19
+ create: (space: string, composition: string, title: string) => Promise<{
20
+ created: boolean;
21
+ id: string;
22
+ spaceId: string;
23
+ title: string;
24
+ createdBy: string;
25
+ latestSnapshotId: string | null;
26
+ createdAt: string;
27
+ updatedAt: string;
28
+ }>;
16
29
  /** @param {string} space @param {string} composition @param {string} snapshot */
17
30
  snapshot: (space: string, composition: string, snapshot: string) => Promise<import("./types.js").Snapshot>;
18
31
  /** @param {string} space @param {string} composition @param {import("./types.js").BeginRequest} body */
@@ -26,4 +39,4 @@ export function sourceApi({ access, fetchImpl }: {
26
39
  /** @param {string} space @param {string} composition @param {string} upload */
27
40
  submit: (space: string, composition: string, upload: string) => Promise<import("./types.js").UploadReceipt>;
28
41
  };
29
- export type SourceApi = ReturnType<typeof sourceApi>;
42
+ export type SourceApi = Omit<ReturnType<typeof sourceApi>, "list" | "get">;
@@ -0,0 +1,28 @@
1
+ /** A host keeps one picker per interactive session. Project files cannot nominate a destination.
2
+ * @param {{projectPath:string, access:import("../signedInRequest.mjs").SignedInAccess,
3
+ * workspace:(requested?:string)=>Promise<{id:string,name:string} | null>,
4
+ * store?:import("./adapterTypes.js").SourceStore, fetchImpl?:typeof fetch}} options */
5
+ export function sourceReconnect(options: {
6
+ projectPath: string;
7
+ access: import("../signedInRequest.mjs").SignedInAccess;
8
+ workspace: (requested?: string) => Promise<{
9
+ id: string;
10
+ name: string;
11
+ } | null>;
12
+ store?: import("./adapterTypes.js").SourceStore;
13
+ fetchImpl?: typeof fetch;
14
+ }): {
15
+ available: () => Promise<boolean>;
16
+ list: (requested: string | undefined) => Promise<{
17
+ token: `${string}-${string}-${string}-${string}-${string}`;
18
+ id: string;
19
+ title: string;
20
+ workspace: {
21
+ id: string;
22
+ name: string;
23
+ };
24
+ }[]>;
25
+ confirm: (token: string) => Promise<{
26
+ confirmLocalFiles: `${string}-${string}-${string}-${string}-${string}`;
27
+ } | null>;
28
+ };
@@ -1,3 +1,5 @@
1
- /** Project-local state is excluded by the portable source policy. Account/root mismatches fail closed, including copied folders.
1
+ /** @param {string} path */
2
+ export function directoryIdentity(path: string): Promise<string>;
3
+ /** Default sync destinations belong to this install. Never import a binding from a project.
2
4
  * @returns {import("./adapterTypes.js").SourceStore} */
3
5
  export function createProjectShareSourceStore(): import("./adapterTypes.js").SourceStore;
@@ -299,7 +299,7 @@ export interface InflightUpload {
299
299
 
300
300
  export interface Binding extends BindingKey {
301
301
  version: 1;
302
- /** Client-generated, kept before the first request so a retried create names the same composition. */
302
+ /** Client-generated destination ID, saved after the service confirms creation. */
303
303
  compositionId: string;
304
304
  ownerSpaceId: string;
305
305
  /** The owner workspace as the account's list last named it, so a project whose workspace the account left can
@@ -1,5 +1,5 @@
1
- /** Create metadata folders only inside an existing project. @param {string} root @param {string} rel */
2
- export function mkdirInside(root: string, rel: string): Promise<string>;
1
+ /** Create metadata folders inside an existing root. @param {string} root @param {string} rel @param {number} [mode] */
2
+ export function mkdirInside(root: string, rel: string, mode?: number): Promise<string>;
3
3
  /** @param {string} path @param {unknown} data */
4
4
  export function writeJsonAtomic(path: string, data: unknown): Promise<void>;
5
5
  /** @template T @param {string} path @param {T} fallback @returns {Promise<Record<string, unknown> | Exclude<T, object>>} */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/share",
3
- "version": "0.9.102",
3
+ "version": "0.9.104",
4
4
  "description": "Shared review identity, version upload and sharing state for HyperFrames hosts",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -113,7 +113,7 @@
113
113
  "css-tree": "^3.2.1",
114
114
  "ignore": "^5.3.2",
115
115
  "linkedom": "^0.18.12",
116
- "@hyperframes/parsers": "0.9.102"
116
+ "@hyperframes/parsers": "0.9.104"
117
117
  },
118
118
  "devDependencies": {
119
119
  "@types/css-tree": "^3.2.0",
package/src/hosts.d.ts CHANGED
@@ -25,7 +25,13 @@ export interface ShareHost {
25
25
  /** Requests to HeyGen's sign-in host as the signed-in person, traced as the host traces its API calls. */
26
26
  signedInRequest(deps: Omit<SignedInDeps, "trace">): ReturnType<typeof signedInRequest>;
27
27
  /** The newest finished export recorded in the project's renders folder whose file is still there. */
28
- latestExportFile(dir: string): { path: string; fingerprint?: string; id: string } | null;
28
+ /** May answer later, so a host can read its disk off its main thread. */
29
+ latestExportFile(
30
+ dir: string,
31
+ ):
32
+ | { path: string; fingerprint?: string; id: string }
33
+ | null
34
+ | Promise<{ path: string; fingerprint?: string; id: string } | null>;
29
35
  /** Trusted video upload origins configured by the host independently of the review API response. */
30
36
  reviewUploadOrigins?: readonly string[];
31
37
  /** This install's own secret: change-of-space journals are sealed with it; one it did not seal reads as none. */
package/src/index.mjs CHANGED
@@ -88,3 +88,5 @@ export {
88
88
  } from "./shareSources.mjs";
89
89
 
90
90
  export { SourceIgnoreError } from "./sourceIgnore.mjs";
91
+
92
+ export { sourceReconnect } from "./sources/reconnect.mjs";
@@ -261,15 +261,15 @@ const woken = new Set();
261
261
  const failures = new Map();
262
262
 
263
263
  /** Which export a failure was about: the newest export file and the project as it was rendered. @param {string} dir */
264
- const exportKeyOf = (dir) => {
265
- const latest = latestExportFile(dir);
264
+ const exportKeyOf = async (dir) => {
265
+ const latest = await latestExportFile(dir);
266
266
  return latest ? `${latest.id}\n${latest.path}\n${latest.fingerprint ?? ""}` : "";
267
267
  };
268
268
 
269
269
  /** Whether the newest export can go up now: there is one, it is MP4, and the project has not moved past it.
270
- * @param {string} dir @param {string} now @returns {ReviewVersion["source"]} */
271
- function sourceOf(dir, now) {
272
- const latest = latestExportFile(dir);
270
+ * @param {string} dir @param {string} now @returns {Promise<ReviewVersion["source"]>} */
271
+ async function sourceOf(dir, now) {
272
+ const latest = await latestExportFile(dir);
273
273
  if (!latest) return "none";
274
274
  if (!/\.mp4$/i.test(latest.path)) return "not-mp4";
275
275
  return latest.fingerprint === now ? "ready" : "stale";
@@ -290,13 +290,17 @@ export async function reviewVersion(projectPath, server = {}) {
290
290
  server.latestReadyVersionId === undefined || server.latestReadyVersionId === last?.versionId;
291
291
  const savedFailure = state.failure?.projectId === projectId ? state.failure : null;
292
292
  const failed = savedFailure ?? failures.get(key);
293
+ const [source, exportKey] = await Promise.all([
294
+ sourceOf(projectPath, now),
295
+ exportKeyOf(projectPath),
296
+ ]);
293
297
  return {
294
298
  last: last
295
299
  ? { exportedAt: last.exportedAt, current: last.fingerprint === now && onServer }
296
300
  : null,
297
- source: sourceOf(projectPath, now),
301
+ source,
298
302
  exporting: inFlight.get(key) ?? null,
299
- ...(failed?.exportKey === exportKeyOf(projectPath)
303
+ ...(failed?.exportKey === exportKey
300
304
  ? {
301
305
  failure: failed.sentence,
302
306
  retryable: !failed.final,
@@ -311,8 +315,8 @@ export async function reviewVersion(projectPath, server = {}) {
311
315
  * @param {string} dir @param {string} title @param {(file: string) => Promise<VideoFacts | null>} probe
312
316
  * @param {FilesForRender} filesForExport @param {boolean} requireSource */
313
317
  async function exportSource(dir, title, probe, filesForExport, requireSource) {
314
- const latest = latestExportFile(dir);
315
- if (!latest || sourceOf(dir, await projectFingerprint(dir)) !== "ready")
318
+ const latest = await latestExportFile(dir);
319
+ if (!latest || (await sourceOf(dir, await projectFingerprint(dir))) !== "ready")
316
320
  return { failure: local("Export an MP4 of the project as it is now first.") };
317
321
  const { size } = await stat(latest.path);
318
322
  if (size > MAX_BYTES) return { failure: said(new ReviewFailed(400, "export_too_large")) };
@@ -623,14 +627,14 @@ async function finish(dir, state, pending, id, done, fromReview) {
623
627
  /** @param {string} dir @param {NonNullable<VersionRecord["pending"]>} pending */
624
628
  async function failedExportKey(dir, pending) {
625
629
  if (typeof pending.renderKey === "string") return pending.renderKey;
626
- const latest = latestExportFile(dir);
630
+ const latest = await latestExportFile(dir);
627
631
  if (!latest) return "";
628
632
  const checksum =
629
633
  latest.fingerprint === pending.body.source_fingerprint
630
634
  ? await fileSha256Base64(latest.path).catch(() => null)
631
635
  : null;
632
636
  return checksum === pending.body.local_upload.checksum_sha256
633
- ? exportKeyOf(dir)
637
+ ? await exportKeyOf(dir)
634
638
  : `pending:${pending.body.client_operation_id}`;
635
639
  }
636
640
 
@@ -681,7 +685,7 @@ async function alreadyUploaded(client, id, state, body) {
681
685
  * @param {{file: string, body: ExportRequest}} source @param {string} id @param {VersionRecord} state */
682
686
  async function sendVersion(r, report, source, id, state) {
683
687
  const first = state.last?.projectId !== id;
684
- let pending = bindRenderKey(bodyToSend(state, source.body, id), r.projectPath);
688
+ let pending = await bindRenderKey(bodyToSend(state, source.body, id), r.projectPath);
685
689
  const sourceConflict = pendingSourceConflict(r, pending, source.body);
686
690
  if (sourceConflict) return local(sourceConflict);
687
691
  await writeState(r.projectPath, (state = { ...state, pending, failure: null }));
@@ -788,7 +792,7 @@ export async function addVersion(request) {
788
792
  report({ step: "preparing", sent: 0, total: 0 });
789
793
  const failure = await withProjectShareLock(r.projectPath, "export", () => run(r, report));
790
794
  const kept = failure && (uploaded || !request.projectId);
791
- if (kept) failures.set(key, { ...failure, exportKey: exportKeyOf(r.projectPath) });
795
+ if (kept) failures.set(key, { ...failure, exportKey: await exportKeyOf(r.projectPath) });
792
796
  return failure?.sentence ?? null;
793
797
  } catch (error) {
794
798
  const sentence =
@@ -797,7 +801,7 @@ export async function addVersion(request) {
797
801
  sentence,
798
802
  final: false,
799
803
  exportHelps: false,
800
- exportKey: exportKeyOf(r.projectPath),
804
+ exportKey: await exportKeyOf(r.projectPath),
801
805
  });
802
806
  return sentence;
803
807
  } finally {
@@ -863,7 +867,7 @@ async function settleSavedExport(dir, client, fromReview) {
863
867
  if (done.status === "upload_pending" || going(done)) return;
864
868
  const failure = await finish(dir, state, pending, id, done, fromReview);
865
869
  const key = normalize(dir);
866
- if (failure) failures.set(key, { ...failure, exportKey: exportKeyOf(dir) });
870
+ if (failure) failures.set(key, { ...failure, exportKey: await exportKeyOf(dir) });
867
871
  else failures.delete(key);
868
872
  }
869
873
 
@@ -887,7 +891,7 @@ export async function versionFacts(dir) {
887
891
  const last = state.last?.projectId === projectId ? state.last : null;
888
892
  return {
889
893
  last: last && { ...last, current: last.fingerprint === now },
890
- source: sourceOf(dir, now),
894
+ source: await sourceOf(dir, now),
891
895
  running: inFlight.has(normalize(dir)),
892
896
  };
893
897
  }
@@ -945,8 +949,8 @@ function readyRecord(pending, id, done) {
945
949
  }
946
950
 
947
951
  /** @param {NonNullable<VersionRecord["pending"]>} pending @param {string} dir */
948
- function bindRenderKey(pending, dir) {
952
+ async function bindRenderKey(pending, dir) {
949
953
  return typeof pending.renderKey === "string"
950
954
  ? pending
951
- : { ...pending, renderKey: exportKeyOf(dir) };
955
+ : { ...pending, renderKey: await exportKeyOf(dir) };
952
956
  }
@@ -199,15 +199,24 @@ async function snapshotFor(job, manifest, limits) {
199
199
  if (job.readOnly) return unavailable("source_sync_required");
200
200
  if (!job.own && limits.compositions >= limits.maxCompositions)
201
201
  return unavailable("source_composition_limit");
202
+ binding.composition = await confirmSyncDestination(api, binding);
202
203
  await store.write(binding);
203
- binding.composition = await api.create(
204
+ return uploadSource({ binding, manifest, api, store, signal, ...uploadOptions(options) });
205
+ }
206
+ /** @param {import("./sources/api.mjs").SourceApi} api @param {Binding} binding */
207
+ async function confirmSyncDestination(api, binding) {
208
+ const { created, ...composition } = await api.create(
204
209
  binding.ownerSpaceId,
205
210
  binding.compositionId,
206
211
  basename(binding.projectPath),
207
212
  );
208
- await store.write(binding);
209
- return uploadSource({ binding, manifest, api, store, signal, ...uploadOptions(options) });
213
+ if (composition.id !== binding.compositionId || composition.spaceId !== binding.ownerSpaceId)
214
+ throw new Error("Source sync returned a different composition or workspace.");
215
+ if (created !== true && !binding.composition)
216
+ throw new Error("Source sync requires a new composition. Retry to choose a fresh destination.");
217
+ return composition;
210
218
  }
219
+
211
220
  /** @param {Preparation} job @param {import("./sources/types.js").Manifest} manifest */
212
221
  function recoverEarlierCapture({ readOnly, binding, api, store }, manifest) {
213
222
  const inflight = binding.inflight;
@@ -32,6 +32,28 @@ export function sourceApi({ access, fetchImpl = fetch }) {
32
32
  const path = (space, composition) =>
33
33
  `/v3/hyperframes/workspaces/${encodeURIComponent(space)}/compositions/${encodeURIComponent(composition)}`;
34
34
  return {
35
+ /** @param {string} space */
36
+ list: async (space) => {
37
+ const records = [];
38
+ const cursors = new Set();
39
+ const query = new URLSearchParams({ limit: "100" });
40
+ for (;;) {
41
+ const route = `/v3/hyperframes/workspaces/${encodeURIComponent(space)}/compositions?${query}`;
42
+ const { reply } = await request("GET", route);
43
+ if (!reply.ok) throw await refusalOf(reply);
44
+ const page = objectOf(await reply.json(), "composition list");
45
+ if (!Array.isArray(page.data)) throw new Error("Invalid cloud project list.");
46
+ records.push(...page.data.map(compositionOf));
47
+ if (page.has_more === false) return records;
48
+ const cursor = page.next_token;
49
+ if (page.has_more !== true || typeof cursor !== "string" || !cursor || cursors.has(cursor))
50
+ throw new Error("Invalid cloud project list cursor.");
51
+ cursors.add(cursor);
52
+ query.set("token", cursor);
53
+ }
54
+ },
55
+ /** @param {string} space @param {string} composition */
56
+ get: async (space, composition) => compositionOf(await send("GET", path(space, composition))),
35
57
  /** @param {string} space */
36
58
  limits: async (space) =>
37
59
  syncLimitsOf(
@@ -41,8 +63,12 @@ export function sourceApi({ access, fetchImpl = fetch }) {
41
63
  ),
42
64
  ),
43
65
  /** @param {string} space @param {string} composition @param {string} title */
44
- create: async (space, composition, title) =>
45
- compositionOf(await send("PUT", path(space, composition), { title })),
66
+ create: async (space, composition, title) => {
67
+ const { reply } = await request("PUT", path(space, composition), { title });
68
+ if (!reply.ok) throw await refusalOf(reply);
69
+ const record = compositionOf(objectOf(await reply.json(), "envelope").data);
70
+ return { ...record, created: reply.status === 201 };
71
+ },
46
72
  /** @param {string} space @param {string} composition @param {string} snapshot */
47
73
  snapshot: async (space, composition, snapshot) =>
48
74
  snapshotOf(
@@ -111,4 +137,4 @@ export function sourceApi({ access, fetchImpl = fetch }) {
111
137
  ),
112
138
  };
113
139
  }
114
- /** @typedef {ReturnType<typeof sourceApi>} SourceApi */
140
+ /** @typedef {Omit<ReturnType<typeof sourceApi>, "list" | "get">} SourceApi */
@@ -0,0 +1,147 @@
1
+ // @ts-check
2
+ import { randomUUID } from "node:crypto";
3
+ import { realpath } from "node:fs/promises";
4
+ import { shareSourceFingerprint } from "../shareSources.mjs";
5
+ import { withProjectShareLock } from "../projectLock.mjs";
6
+ import { sourceApi } from "./api.mjs";
7
+ import { createProjectShareSourceStore, directoryIdentity } from "./store.mjs";
8
+
9
+ /** A host keeps one picker per interactive session. Project files cannot nominate a destination.
10
+ * @param {{projectPath:string, access:import("../signedInRequest.mjs").SignedInAccess,
11
+ * workspace:(requested?:string)=>Promise<{id:string,name:string} | null>,
12
+ * store?:import("./adapterTypes.js").SourceStore, fetchImpl?:typeof fetch}} options */
13
+ export function sourceReconnect(options) {
14
+ const store = options.store ?? createProjectShareSourceStore();
15
+ async function bindingKey() {
16
+ const signed = await options.access();
17
+ if (!signed?.owner) throw new Error("Sign in to reconnect a project.");
18
+ return {
19
+ projectPath: await realpath(options.projectPath),
20
+ account: signed.owner,
21
+ backend: signed.heygenApi,
22
+ };
23
+ }
24
+ /** @param {import("./types.js").BindingKey} key */
25
+ async function unboundDirectory(key) {
26
+ if (await store.read(key)) throw new Error("This folder already has a sync destination.");
27
+ return directoryIdentity(key.projectPath);
28
+ }
29
+ /** @param {import("./types.js").BindingKey} key */
30
+ function session(key) {
31
+ const access = async (/** @type {string | undefined} */ refused) => {
32
+ const signed = await options.access(refused);
33
+ if (signed?.owner !== key.account || signed.heygenApi !== key.backend)
34
+ throw new Error("The account or workspace changed. Choose the project again.");
35
+ return signed;
36
+ };
37
+ return {
38
+ check: () => access(undefined),
39
+ api: sourceApi({ access, fetchImpl: options.fetchImpl }),
40
+ };
41
+ }
42
+ /** @typedef {{key:import("./types.js").BindingKey,directory:string,
43
+ * space:{id:string,name:string},project:import("./types.js").Composition, localDigest?:string}} Offer */
44
+ /** @type {Map<string,Offer>} */
45
+ const offers = new Map();
46
+ return {
47
+ available: async () => !(await store.read(await bindingKey())),
48
+ list: async (/** @type {string | undefined} */ requested) => {
49
+ offers.clear();
50
+ const key = await bindingKey();
51
+ const directory = await unboundDirectory(key);
52
+ const space = await options.workspace(requested);
53
+ if (!space || (requested && space.id !== requested))
54
+ throw new Error("Project sync is unavailable in this workspace.");
55
+ const { api } = session(key);
56
+ const projects = await api.list(space.id);
57
+ return projects.map((project) => {
58
+ if (project.spaceId !== space.id) throw new Error("Cloud project workspace mismatch.");
59
+ const token = randomUUID();
60
+ offers.set(token, { key, space, directory, project });
61
+ return { token, id: project.id, title: project.title, workspace: space };
62
+ });
63
+ },
64
+ confirm: async (/** @type {string} */ token) => {
65
+ const offer = offers.get(token);
66
+ offers.clear();
67
+ if (!offer) throw new Error("Choose a cloud project again before reconnecting.");
68
+ const { key, space } = offer;
69
+ const { check, api } = session(key);
70
+ return withProjectShareLock(key.projectPath, "source", async () => {
71
+ await check();
72
+ const current = await options.workspace(space.id);
73
+ if (current?.id !== space.id || current.name !== space.name)
74
+ throw new Error("The workspace changed. Choose the project again.");
75
+ const project = await api.get(space.id, offer.project.id);
76
+ if (!sameProject(project, offer.project))
77
+ throw new Error("The cloud project changed. Review its destination again.");
78
+ const base = await confirmedBase(api, project);
79
+ const divergent = await divergentDigest(key.projectPath, base, offer.localDigest);
80
+ await check();
81
+ if (
82
+ (await realpath(options.projectPath)) !== key.projectPath ||
83
+ (await unboundDirectory(key)) !== offer.directory
84
+ )
85
+ throw new Error("The local folder changed. Choose the project again.");
86
+ if (divergent) {
87
+ const confirmLocalFiles = randomUUID();
88
+ offers.set(confirmLocalFiles, { ...offer, localDigest: divergent });
89
+ return { confirmLocalFiles };
90
+ }
91
+ await store.write({
92
+ ...key,
93
+ version: 1,
94
+ compositionId: project.id,
95
+ ownerSpaceId: space.id,
96
+ composition: project,
97
+ boundAt: Date.now(),
98
+ etag: null,
99
+ inflight: null,
100
+ base,
101
+ });
102
+ return null;
103
+ });
104
+ },
105
+ };
106
+ }
107
+
108
+ /** @param {import("./api.mjs").SourceApi} api @param {import("./types.js").Composition} project */
109
+ async function confirmedBase(api, project) {
110
+ if (!project.latestSnapshotId) return null;
111
+ const snapshot = await api.snapshot(project.spaceId, project.id, project.latestSnapshotId);
112
+ if (
113
+ !snapshot.manifest ||
114
+ snapshot.compositionId !== project.id ||
115
+ snapshot.id !== project.latestSnapshotId ||
116
+ snapshot.publicationOutcome !== "published"
117
+ )
118
+ throw new Error("Could not verify the cloud project's latest version.");
119
+ return {
120
+ snapshotId: snapshot.id,
121
+ manifest: snapshot.manifest.document,
122
+ manifestSha256: snapshot.manifest.sha256,
123
+ };
124
+ }
125
+
126
+ /** @param {import("./types.js").Composition} current @param {import("./types.js").Composition} shown */
127
+ function sameProject(current, shown) {
128
+ return (
129
+ current.id === shown.id &&
130
+ current.spaceId === shown.spaceId &&
131
+ current.title === shown.title &&
132
+ current.latestSnapshotId === shown.latestSnapshotId
133
+ );
134
+ }
135
+
136
+ /** @param {string} path @param {import("./types.js").Binding["base"]} base @param {string | undefined} approved */
137
+ async function divergentDigest(path, base, approved) {
138
+ if (!base) return null;
139
+ const digest = await shareSourceFingerprint(path);
140
+ if (!digest)
141
+ throw new Error(
142
+ "Could not compare this folder with the published version. Finish any edits and retry.",
143
+ );
144
+ if (approved && approved !== digest)
145
+ throw new Error("The local files changed. Choose the project again.");
146
+ return digest === base.manifestSha256 || digest === approved ? null : digest;
147
+ }
@@ -1,8 +1,9 @@
1
1
  // @ts-check
2
2
  import { createHash } from "node:crypto";
3
3
  import { constants } from "node:fs";
4
- import { lstat, open } from "node:fs/promises";
5
- import { join } from "node:path";
4
+ import { lstat, mkdir, open, realpath, stat } from "node:fs/promises";
5
+ import { homedir } from "node:os";
6
+ import { isAbsolute, join, relative, sep } from "node:path";
6
7
  import { errorCode, mkdirInside, writeJsonAtomic } from "../storage.mjs";
7
8
  import { localBaseDigest, readUploadIntent } from "./manifest.mjs";
8
9
 
@@ -41,14 +42,36 @@ function checkSnapshots(raw) {
41
42
  readUploadIntent(raw.inflight);
42
43
  }
43
44
 
44
- /** Project-local state is excluded by the portable source policy. Account/root mismatches fail closed, including copied folders.
45
+ /** @param {string} path */
46
+ export async function directoryIdentity(path) {
47
+ const info = await stat(path, { bigint: true });
48
+ return `${info.dev}:${info.ino}:${info.birthtimeNs}`;
49
+ }
50
+
51
+ /** Default sync destinations belong to this install. Never import a binding from a project.
45
52
  * @returns {import("./adapterTypes.js").SourceStore} */
46
53
  export function createProjectShareSourceStore() {
54
+ const config = process.env.HYPERFRAMES_CONFIG_DIR || join(homedir(), ".hyperframes");
47
55
  /** @param {import("./types.js").BindingKey} key */
48
56
  const location = async (key) => {
49
- const dir = await mkdirInside(key.projectPath, ".hyperframes");
50
- const environment = createHash("sha256").update(key.backend).digest("hex").slice(0, 16);
51
- return join(dir, `share-sync.${environment}.json`);
57
+ if (!isAbsolute(config))
58
+ throw new Error("Source sync requires an absolute configuration directory.");
59
+ await mkdir(config, { recursive: true, mode: 0o700 });
60
+ const root = await realpath(config);
61
+ const relativeConfig = relative(key.projectPath, join(root, "source-bindings"));
62
+ if (
63
+ !(
64
+ relativeConfig === ".." ||
65
+ relativeConfig.startsWith(`..${sep}`) ||
66
+ isAbsolute(relativeConfig)
67
+ )
68
+ )
69
+ throw new Error("The source sync configuration directory must be outside the project.");
70
+ const dir = await mkdirInside(root, "source-bindings", 0o700);
71
+ const id = createHash("sha256")
72
+ .update(JSON.stringify([key.backend, key.projectPath]))
73
+ .digest("hex");
74
+ return join(dir, `${id}.json`);
52
75
  };
53
76
  return {
54
77
  read: async (key) => {
@@ -61,7 +84,10 @@ export function createProjectShareSourceStore() {
61
84
  try {
62
85
  if (!(await handle.stat()).isFile())
63
86
  throw new Error("Source binding must be a regular file.");
64
- return bindingOf(JSON.parse(await handle.readFile("utf8")), key);
87
+ const record = JSON.parse(await handle.readFile("utf8"));
88
+ const { directoryId, ...binding } = record;
89
+ if (directoryId !== (await directoryIdentity(key.projectPath))) return null;
90
+ return bindingOf(binding, key);
65
91
  } finally {
66
92
  await handle.close();
67
93
  }
@@ -73,7 +99,10 @@ export function createProjectShareSourceStore() {
73
99
  throw error;
74
100
  });
75
101
  if (held && !held.isFile()) throw new Error("Source binding must be a regular file.");
76
- await writeJsonAtomic(file, binding);
102
+ await writeJsonAtomic(file, {
103
+ ...binding,
104
+ directoryId: await directoryIdentity(binding.projectPath),
105
+ });
77
106
  },
78
107
  };
79
108
  }
@@ -299,7 +299,7 @@ export interface InflightUpload {
299
299
 
300
300
  export interface Binding extends BindingKey {
301
301
  version: 1;
302
- /** Client-generated, kept before the first request so a retried create names the same composition. */
302
+ /** Client-generated destination ID, saved after the service confirms creation. */
303
303
  compositionId: string;
304
304
  ownerSpaceId: string;
305
305
  /** The owner workspace as the account's list last named it, so a project whose workspace the account left can
package/src/storage.mjs CHANGED
@@ -37,13 +37,13 @@ export const rename = (from, to) => retryBusy(() => renameFile(from, to));
37
37
  /** @param {string} path @param {import("node:fs").RmOptions} [options] */
38
38
  export const rm = (path, options) => retryBusy(() => remove(path, options));
39
39
 
40
- /** Create metadata folders only inside an existing project. @param {string} root @param {string} rel */
41
- export async function mkdirInside(root, rel) {
40
+ /** Create metadata folders inside an existing root. @param {string} root @param {string} rel @param {number} [mode] */
41
+ export async function mkdirInside(root, rel, mode) {
42
42
  let dir = root;
43
43
  for (const part of rel.split(sep).filter(Boolean)) {
44
44
  if (part === ".." || part === ".") throw new Error("Invalid metadata directory.");
45
45
  dir = join(dir, part);
46
- await mkdir(dir).catch((error) => {
46
+ await mkdir(dir, { mode }).catch((error) => {
47
47
  if (errorCode(error) !== "EEXIST") throw error;
48
48
  });
49
49
  if (!(await lstat(dir)).isDirectory())