@venturewild/workspace 0.3.8 → 0.4.0

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.
@@ -0,0 +1,225 @@
1
+ // Workspace registry — the per-install list of LOCAL workspaces (lobby M1).
2
+ //
3
+ // One install can hold many workspaces; this is the list the lobby shows and
4
+ // switches between. Stored in the GLOBAL dir (~/.wild-workspace/workspaces.json),
5
+ // NEVER inside a synced workspace folder (core principle #1: the user's repo
6
+ // folder is sacred — no system state in it).
7
+ //
8
+ // Each entry points at a folder on THIS host. The server re-roots to the chosen
9
+ // workspace per request via the X-Workspace-Id seam (see index.mjs `workspaceFor`).
10
+ // Creating/opening a workspace is a HOST action (the folder lives here); a remote
11
+ // browser only ENTERS existing ones — enforced at the route, not here.
12
+ //
13
+ // Local workspaces only (kind:'local'); shared workspaces arrive from the rails in
14
+ // a later slice. `removeWorkspace` drops a folder from the LIST only — it never
15
+ // deletes files.
16
+
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import os from 'node:os';
20
+ import crypto from 'node:crypto';
21
+ import { globalDir } from './logpaths.mjs';
22
+
23
+ const FILE = 'workspaces.json';
24
+
25
+ function registryPath(env = process.env) {
26
+ return path.join(globalDir(env), FILE);
27
+ }
28
+
29
+ // Where "New workspace" (name-only, no path) creates folders — a visible home so
30
+ // the user always knows where their data lives (design §8.1). Overridable for tests.
31
+ function workspacesHome(env = process.env) {
32
+ return env.WILD_WORKSPACE_HOME || path.join(os.homedir(), 'Workspaces');
33
+ }
34
+
35
+ // A stable id derived from the absolute dir, so re-adding the same folder is
36
+ // idempotent and the id survives a display-name rename. Case-folded on win/mac
37
+ // (case-insensitive filesystems) so one folder maps to exactly one id. Exported
38
+ // so the server can compute the boot/default workspace's id WITHOUT writing the
39
+ // registry file (keeps startup side-effect-free + test-pollution-free).
40
+ export function workspaceIdForDir(dir) {
41
+ const abs = path.resolve(dir);
42
+ const key = process.platform === 'linux' ? abs : abs.toLowerCase();
43
+ return 'ws_' + crypto.createHash('sha256').update(key).digest('hex').slice(0, 12);
44
+ }
45
+ const idForDir = workspaceIdForDir;
46
+
47
+ function nameForDir(dir) {
48
+ return path.basename(path.resolve(dir)) || 'workspace';
49
+ }
50
+
51
+ // folder-name-safe slug of a display name (for the New-workspace folder).
52
+ function folderSlug(name) {
53
+ const s = String(name || '')
54
+ .trim()
55
+ .toLowerCase()
56
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
57
+ .replace(/^-+|-+$/g, '')
58
+ .slice(0, 60);
59
+ return s || 'workspace';
60
+ }
61
+
62
+ function readRaw(env) {
63
+ try {
64
+ const parsed = JSON.parse(fs.readFileSync(registryPath(env), 'utf8'));
65
+ if (Array.isArray(parsed?.workspaces)) {
66
+ return parsed.workspaces.map(sanitize).filter(Boolean);
67
+ }
68
+ } catch {
69
+ /* missing / unreadable / malformed → empty */
70
+ }
71
+ return [];
72
+ }
73
+
74
+ function sanitize(e) {
75
+ if (!e || typeof e !== 'object' || typeof e.dir !== 'string' || !e.dir) return null;
76
+ const dir = path.resolve(e.dir);
77
+ return {
78
+ id: typeof e.id === 'string' && e.id ? e.id : idForDir(dir),
79
+ name: typeof e.name === 'string' && e.name.trim() ? e.name.trim() : nameForDir(dir),
80
+ dir,
81
+ kind: e.kind === 'shared' ? 'shared' : 'local',
82
+ createdAt: Number(e.createdAt) || nowMs(),
83
+ lastOpenedAt: Number(e.lastOpenedAt) || 0,
84
+ };
85
+ }
86
+
87
+ function writeRaw(list, env) {
88
+ const dir = globalDir(env);
89
+ fs.mkdirSync(dir, { recursive: true });
90
+ const tmp = `${registryPath(env)}.tmp`;
91
+ fs.writeFileSync(tmp, JSON.stringify({ workspaces: list }, null, 2), { mode: 0o600 });
92
+ fs.renameSync(tmp, registryPath(env)); // atomic-ish replace
93
+ }
94
+
95
+ function nowMs() {
96
+ return Date.now();
97
+ }
98
+
99
+ // Recency ordering (listWorkspaces) needs strictly-increasing open stamps. Two
100
+ // opens in the same millisecond — easy on a fast machine or CI — would otherwise
101
+ // tie on lastOpenedAt and fall back to the createdAt tiebreak, which does NOT
102
+ // reflect open-order, so the just-touched workspace could fail to sort to the
103
+ // front. Clamp every new open stamp strictly above every existing stamp so the
104
+ // order is deterministic regardless of clock resolution.
105
+ function nextOpenStamp(list) {
106
+ let max = 0;
107
+ for (const w of list) {
108
+ if (w.lastOpenedAt > max) max = w.lastOpenedAt;
109
+ if (w.createdAt > max) max = w.createdAt;
110
+ }
111
+ return Math.max(nowMs(), max + 1);
112
+ }
113
+
114
+ // --- public API ------------------------------------------------------------
115
+
116
+ /** All workspaces, most-recently-opened first (then newest-created). */
117
+ export function listWorkspaces(env = process.env) {
118
+ return readRaw(env).sort(
119
+ (a, b) => b.lastOpenedAt - a.lastOpenedAt || b.createdAt - a.createdAt,
120
+ );
121
+ }
122
+
123
+ /** One workspace by id, or null. */
124
+ export function getWorkspace(id, env = process.env) {
125
+ return readRaw(env).find((w) => w.id === id) || null;
126
+ }
127
+
128
+ /** Find a registered workspace by its directory (idempotency helper), or null. */
129
+ export function findByDir(dir, env = process.env) {
130
+ const want = idForDir(dir);
131
+ return readRaw(env).find((w) => w.id === want) || null;
132
+ }
133
+
134
+ /**
135
+ * Ensure `dir` exists in the registry (idempotent) — used at startup to seed the
136
+ * boot/default workspace so the lobby is never blank for an existing install.
137
+ * Does NOT touch lastOpenedAt. Returns the entry.
138
+ */
139
+ export function seedDefault({ dir, name } = {}, env = process.env) {
140
+ if (!dir) return null;
141
+ const list = readRaw(env);
142
+ const existing = list.find((w) => w.id === idForDir(dir));
143
+ if (existing) return existing;
144
+ const entry = sanitize({
145
+ dir,
146
+ name: name || nameForDir(dir),
147
+ createdAt: nowMs(),
148
+ lastOpenedAt: nowMs(), // the boot workspace is "the one you were just in"
149
+ });
150
+ list.push(entry);
151
+ writeRaw(list, env);
152
+ return entry;
153
+ }
154
+
155
+ /**
156
+ * Create a NEW local workspace. With `dir` → register that existing folder
157
+ * ("Open an existing folder"). With only `name` → make a fresh folder under the
158
+ * Workspaces home ("New workspace"); collisions get a -2/-3 suffix. Idempotent on
159
+ * an already-registered dir (returns it, touched). HOST-only is enforced at the route.
160
+ */
161
+ export function createWorkspace({ name, dir } = {}, env = process.env) {
162
+ let targetDir;
163
+ let isNew = false;
164
+
165
+ if (dir) {
166
+ targetDir = path.resolve(dir);
167
+ if (!fs.existsSync(targetDir)) {
168
+ throw new Error(`folder does not exist: ${targetDir}`);
169
+ }
170
+ if (!fs.statSync(targetDir).isDirectory()) {
171
+ throw new Error(`not a folder: ${targetDir}`);
172
+ }
173
+ } else {
174
+ const home = workspacesHome(env);
175
+ fs.mkdirSync(home, { recursive: true });
176
+ const base = folderSlug(name);
177
+ let candidate = path.join(home, base);
178
+ let n = 2;
179
+ while (fs.existsSync(candidate)) {
180
+ candidate = path.join(home, `${base}-${n}`);
181
+ n += 1;
182
+ }
183
+ fs.mkdirSync(candidate, { recursive: true });
184
+ targetDir = candidate;
185
+ isNew = true;
186
+ }
187
+
188
+ const list = readRaw(env);
189
+ const id = idForDir(targetDir);
190
+ const existing = list.find((w) => w.id === id);
191
+ if (existing) {
192
+ existing.lastOpenedAt = nextOpenStamp(list);
193
+ if (name && isNew) existing.name = name;
194
+ writeRaw(list, env);
195
+ return existing;
196
+ }
197
+ const entry = sanitize({
198
+ dir: targetDir,
199
+ name: name || nameForDir(targetDir),
200
+ createdAt: nowMs(),
201
+ lastOpenedAt: nextOpenStamp(list),
202
+ });
203
+ list.push(entry);
204
+ writeRaw(list, env);
205
+ return entry;
206
+ }
207
+
208
+ /** Mark a workspace opened now (drives the recency sort + pre-select-last). */
209
+ export function touchWorkspace(id, env = process.env) {
210
+ const list = readRaw(env);
211
+ const w = list.find((x) => x.id === id);
212
+ if (!w) return null;
213
+ w.lastOpenedAt = nextOpenStamp(list);
214
+ writeRaw(list, env);
215
+ return w;
216
+ }
217
+
218
+ /** Remove a workspace from the LIST only. NEVER deletes the folder or its files. */
219
+ export function removeWorkspace(id, env = process.env) {
220
+ const list = readRaw(env);
221
+ const next = list.filter((w) => w.id !== id);
222
+ if (next.length === list.length) return false;
223
+ writeRaw(next, env);
224
+ return true;
225
+ }
@@ -0,0 +1,111 @@
1
+ // WorkspaceRails — the shared-workspace membership client (multi-host step 2).
2
+ //
3
+ // A thin client over bmo-sync's POST /api/workspaces/{create,list,members/add,
4
+ // members/remove} (account-token self-authed, exactly like canvas-rails.mjs).
5
+ // The caller (owner/member) is DERIVED server-side from the account token, so a
6
+ // caller can only act as itself.
7
+ //
8
+ // Unlike CanvasRails (which degrades silently to a local cache), these are
9
+ // operator/dev affordances driven by `wild-workspace workspace …`, so the
10
+ // methods SURFACE the rails' error code + message instead of collapsing to a
11
+ // bare false — the human running the command needs to see "slug_taken" /
12
+ // "not_owner" / "no_such_account". Network failures still never throw: they
13
+ // resolve to { ok:false, status:0, code:'unreachable' }.
14
+ //
15
+ // This is the FOUNDATION client — there is no App.jsx / lobby UI yet (that's the
16
+ // lobby's job). The CLI is the only consumer.
17
+
18
+ const DEFAULT_TIMEOUT_MS = 5000;
19
+
20
+ export class WorkspaceRails {
21
+ constructor({
22
+ bmoSyncUrl,
23
+ accountToken,
24
+ timeoutMs = DEFAULT_TIMEOUT_MS,
25
+ fetchImpl = (...a) => globalThis.fetch(...a),
26
+ } = {}) {
27
+ this.bmoSyncUrl = bmoSyncUrl ? bmoSyncUrl.replace(/\/$/, '') : null;
28
+ this.accountToken = accountToken || null;
29
+ this.timeoutMs = timeoutMs;
30
+ this.fetchImpl = fetchImpl;
31
+ // Inert without a token (can't key it) or without a server URL.
32
+ this.capable = Boolean(this.accountToken) && Boolean(this.bmoSyncUrl);
33
+ }
34
+
35
+ /**
36
+ * POST to a workspaces endpoint with the account token folded in.
37
+ * @returns {Promise<{ok:boolean, status:number, data:object|null, code?:string, message?:string}>}
38
+ * ok:true → 2xx; `data` is the parsed body.
39
+ * ok:false → a 4xx/5xx (carries the rails' {code,message}) OR a transport
40
+ * failure (status 0, code 'unreachable' / 'not_configured').
41
+ */
42
+ async _post(path, body) {
43
+ if (!this.capable) {
44
+ return { ok: false, status: 0, data: null, code: 'not_configured', message: 'not logged in / no rails URL' };
45
+ }
46
+ const ctrl = new AbortController();
47
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
48
+ if (timer.unref) timer.unref();
49
+ try {
50
+ const r = await this.fetchImpl(`${this.bmoSyncUrl}${path}`, {
51
+ method: 'POST',
52
+ headers: { 'content-type': 'application/json' },
53
+ body: JSON.stringify({ account_token: this.accountToken, ...body }),
54
+ signal: ctrl.signal,
55
+ });
56
+ const data = await r.json().catch(() => null);
57
+ if (r.ok) return { ok: true, status: r.status, data };
58
+ return {
59
+ ok: false,
60
+ status: r.status,
61
+ data,
62
+ code: data?.code || `http_${r.status}`,
63
+ message: data?.message || `HTTP ${r.status}`,
64
+ };
65
+ } catch (e) {
66
+ return { ok: false, status: 0, data: null, code: 'unreachable', message: String(e?.message || e) };
67
+ } finally {
68
+ clearTimeout(timer);
69
+ }
70
+ }
71
+
72
+ /** Create a shared workspace. `slug` is optional (the rails auto-suggest from name). */
73
+ create(name, slug = null) {
74
+ const body = { name };
75
+ if (slug) body.slug = slug;
76
+ return this._post('/api/workspaces/create', body);
77
+ }
78
+
79
+ /** The shared workspaces this account belongs to. */
80
+ list() {
81
+ return this._post('/api/workspaces/list', {});
82
+ }
83
+
84
+ /** Add a member by email (owner-only; the email must already have an account). */
85
+ addMember(slug, email) {
86
+ return this._post('/api/workspaces/members/add', { slug, member_email: email });
87
+ }
88
+
89
+ /** Remove a member by email or accountId (owner-only; the owner can't be removed). */
90
+ removeMember(slug, ref) {
91
+ const body = { slug };
92
+ if (ref && typeof ref === 'object') {
93
+ if (ref.accountId) body.account_id = ref.accountId;
94
+ else if (ref.email) body.member_email = ref.email;
95
+ } else if (typeof ref === 'string') {
96
+ // Heuristic: an '@' means an email, otherwise treat it as an account id.
97
+ if (ref.includes('@')) body.member_email = ref;
98
+ else body.account_id = ref;
99
+ }
100
+ return this._post('/api/workspaces/members/remove', body);
101
+ }
102
+ }
103
+
104
+ /** Build the client from server config + account (or an inert one when logged out). */
105
+ export function createWorkspaceRails(config, account, fetchImpl) {
106
+ return new WorkspaceRails({
107
+ bmoSyncUrl: config?.bmoSyncServerUrl,
108
+ accountToken: account?.accountToken,
109
+ fetchImpl,
110
+ });
111
+ }