@platforma-sdk/pl-cli 0.13.6 → 0.14.1

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 (45) hide show
  1. package/README.md +208 -0
  2. package/dist/address.d.ts +6 -0
  3. package/dist/base_command.d.ts +10 -3
  4. package/dist/cli.js +649 -230
  5. package/dist/cli.js.map +1 -1
  6. package/dist/cmd/login.d.ts +21 -0
  7. package/dist/cmd/logout.d.ts +7 -0
  8. package/dist/cmd/session/list.d.ts +6 -0
  9. package/dist/cmd/session/remove.d.ts +7 -0
  10. package/dist/cmd/session/select.d.ts +9 -0
  11. package/dist/cmd-opts.d.ts +8 -3
  12. package/dist/connection.d.ts +59 -3
  13. package/dist/index.js +1 -1
  14. package/dist/instance.d.ts +7 -0
  15. package/dist/jwt.d.ts +12 -0
  16. package/dist/lib.d.ts +2 -1
  17. package/dist/project_ops-CHhJu5k5.js +524 -0
  18. package/dist/project_ops-CHhJu5k5.js.map +1 -0
  19. package/dist/prompt.d.ts +5 -0
  20. package/dist/session_store.d.ts +112 -0
  21. package/dist/sso.d.ts +30 -0
  22. package/package.json +3 -3
  23. package/src/address.ts +15 -0
  24. package/src/base_command.ts +24 -6
  25. package/src/cli.ts +74 -3
  26. package/src/cmd/admin/delete-user.ts +7 -0
  27. package/src/cmd/login.ts +262 -0
  28. package/src/cmd/logout.ts +55 -0
  29. package/src/cmd/session/list.ts +71 -0
  30. package/src/cmd/session/remove.ts +29 -0
  31. package/src/cmd/session/select.ts +36 -0
  32. package/src/cmd-opts.ts +24 -15
  33. package/src/commands.test.ts +637 -0
  34. package/src/connection.ts +275 -15
  35. package/src/instance.ts +19 -0
  36. package/src/jwt.ts +36 -0
  37. package/src/lib.ts +12 -0
  38. package/src/prompt.ts +54 -0
  39. package/src/session_store.test.ts +237 -0
  40. package/src/session_store.ts +315 -0
  41. package/src/sso.test.ts +269 -0
  42. package/src/sso.ts +336 -0
  43. package/src/test_backend.ts +151 -0
  44. package/dist/output-D41Wn0wM.js +0 -229
  45. package/dist/output-D41Wn0wM.js.map +0 -1
@@ -0,0 +1,7 @@
1
+ /** Returns the instance ID of the Backend at `address`, from its ping answer. */
2
+ export declare function instanceIdOf(address: string): Promise<string>;
3
+ /** Returns `instance` when given, else the instance ID of the Backend at `address`. */
4
+ export declare function resolveInstance(flags: {
5
+ instance?: string;
6
+ address?: string;
7
+ }): Promise<string>;
package/dist/jwt.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ /** Claims of a Platforma token that pl-cli reads. The Backend verifies the token; pl-cli only
2
+ * reads the claims to name the login and to know the expiry time. */
3
+ export interface PlTokenClaims {
4
+ /** The login of the user. */
5
+ login: string;
6
+ /** The instance ID of the Backend that issued the token. */
7
+ issuer?: string;
8
+ /** Expiry time, ms since epoch. */
9
+ expiresAt?: number;
10
+ }
11
+ /** Reads the claims of a Platforma JWT without verifying its signature. */
12
+ export declare function parsePlToken(token: string): PlTokenClaims;
package/dist/lib.d.ts CHANGED
@@ -1,3 +1,4 @@
1
- export { createPlConnection, createAdminPlConnection, type PlConnectionOptions, type AdminConnectionOptions, } from './connection';
1
+ export { createPlConnection, createAdminPlConnection, type PlConnectionOptions, type AdminConnectionOptions, type UsedSession, SessionRequiredError, authenticatedLogin, } from './connection';
2
+ export { SessionStore, defaultSessionsPath, SessionsFileEnv, type StoredSession, type SessionsFileData, type SessionListEntry, type SessionLoginKind, } from './session_store';
2
3
  export { listProjects, getProjectInfo, getProjectListRid, getExistingLabelsInTx, resolveProject, renameProject, deleteProject, deduplicateName, navigateToUserRoot, duplicateProject, type ProjectEntry, type ProjectInfo, } from './project_ops';
3
4
  export { type OutputFormat, outputText, outputJson, formatTable, formatDate } from './output';
@@ -0,0 +1,524 @@
1
+ import { PlClient as e, UnauthenticatedPlClient as t, field as n, inferAuthRefreshTime as r, isNotFoundError as i, isNullSignedResourceId as a, isPermissionDenied as o, isUnauthenticated as s, plAddressToConfig as c, resourceIdToString as l } from "@milaboratories/pl-client";
2
+ import { randomBytes as u, randomUUID as d } from "node:crypto";
3
+ import { chmodSync as f, closeSync as p, existsSync as m, mkdirSync as h, openSync as g, readFileSync as _, renameSync as ee, rmSync as v, statSync as y, writeFileSync as te } from "node:fs";
4
+ import { homedir as ne } from "node:os";
5
+ import { dirname as b, join as x } from "node:path";
6
+ import { ProjectCreatedTimestamp as S, ProjectLastModifiedTimestamp as C, ProjectMetaKey as w, ProjectStructureKey as re, ProjectsField as T, ProjectsResourceType as ie, SchemaVersionKey as E, duplicateProject as D } from "@milaboratories/pl-middle-layer";
7
+ // src/address.ts
8
+ function O(e) {
9
+ if (e.indexOf("://") === -1) return e;
10
+ let t;
11
+ try {
12
+ t = new URL(e);
13
+ } catch {
14
+ return "(address that is not a valid URL)";
15
+ }
16
+ return `${t.protocol}//${t.host}`;
17
+ }
18
+ // src/jwt.ts
19
+ function k(e) {
20
+ let t = e.split(".")[1];
21
+ if (t === void 0) throw Error("The Backend returned a token that is not a JWT.");
22
+ let n;
23
+ try {
24
+ n = JSON.parse(Buffer.from(t, "base64url").toString("utf8"));
25
+ } catch (e) {
26
+ throw Error("The Backend returned a token that is not a JWT.", { cause: e });
27
+ }
28
+ let r = typeof n.user?.login == "string" && n.user.login !== "" ? n.user.login : typeof n.sub == "string" && n.sub !== "" ? n.sub : void 0;
29
+ if (r === void 0) throw Error("The token from the Backend has no login.");
30
+ return {
31
+ login: r,
32
+ issuer: typeof n.iss == "string" ? n.iss : void 0,
33
+ expiresAt: typeof n.exp == "number" ? n.exp * 1e3 : void 0
34
+ };
35
+ }
36
+ // src/session_store.ts
37
+ var A = "PL_CLI_SESSIONS_FILE";
38
+ function j() {
39
+ let e = process.env[A];
40
+ return e !== void 0 && e !== "" ? e : x(ne(), ".platforma", "pl-cli.sessions");
41
+ }
42
+ var M = process.platform !== "win32", N = class {
43
+ path;
44
+ constructor(e = j()) {
45
+ this.path = e;
46
+ }
47
+ read() {
48
+ if (!m(this.path)) return {
49
+ version: 1,
50
+ instances: Object.create(null)
51
+ };
52
+ this.tightenFileMode();
53
+ let e;
54
+ try {
55
+ e = JSON.parse(_(this.path, "utf8"));
56
+ } catch (e) {
57
+ throw Error(`The sessions file ${this.path} is not valid JSON. Remove it and sign in again.`, { cause: e });
58
+ }
59
+ let t = e;
60
+ if (t?.version !== 1 || typeof t.instances != "object" || t.instances === null) throw Error(`The sessions file ${this.path} has an unknown format. Remove it and sign in again.`);
61
+ let n = Object.create(null);
62
+ for (let [e, r] of Object.entries(t.instances)) {
63
+ let t = Object.create(null);
64
+ for (let [e, n] of Object.entries(r.sessions ?? {})) t[e] = n;
65
+ n[e] = r.current === void 0 ? { sessions: t } : {
66
+ current: r.current,
67
+ sessions: t
68
+ };
69
+ }
70
+ let r = t.default, i = typeof r == "object" && r && "instanceId" in r && "login" in r && typeof r.instanceId == "string" && typeof r.login == "string" && Object.hasOwn(n, r.instanceId) && Object.hasOwn(n[r.instanceId].sessions, r.login) ? {
71
+ instanceId: r.instanceId,
72
+ login: r.login
73
+ } : void 0;
74
+ return i === void 0 ? {
75
+ version: 1,
76
+ instances: n
77
+ } : {
78
+ version: 1,
79
+ default: i,
80
+ instances: n
81
+ };
82
+ }
83
+ getDefault() {
84
+ let e = this.read();
85
+ if (e.default === void 0) return;
86
+ let { instanceId: t, login: n } = e.default;
87
+ return {
88
+ instanceId: t,
89
+ session: e.instances[t].sessions[n]
90
+ };
91
+ }
92
+ get(e, t) {
93
+ let n = this.read().instances[e];
94
+ if (n === void 0) return;
95
+ let r = t ?? n.current;
96
+ return r === void 0 ? void 0 : n.sessions[r];
97
+ }
98
+ logins(e) {
99
+ return Object.keys(this.read().instances[e]?.sessions ?? {}).sort();
100
+ }
101
+ list() {
102
+ let e = this.read(), t = [];
103
+ for (let n of Object.keys(e.instances).sort()) {
104
+ let r = e.instances[n];
105
+ for (let i of Object.keys(r.sessions).sort()) t.push({
106
+ instanceId: n,
107
+ current: r.current === i,
108
+ default: e.default?.instanceId === n && e.default.login === i,
109
+ session: r.sessions[i]
110
+ });
111
+ }
112
+ return t;
113
+ }
114
+ put(e, t) {
115
+ this.update((n) => {
116
+ let r = n.instances[e] ??= { sessions: Object.create(null) };
117
+ r.sessions[t.login] = t, r.current = t.login, n.default = {
118
+ instanceId: e,
119
+ login: t.login
120
+ };
121
+ });
122
+ }
123
+ updateToken(e, t, n) {
124
+ this.update((r) => {
125
+ let i = r.instances[e]?.sessions[t];
126
+ i !== void 0 && (i.token = n, i.updatedAt = (/* @__PURE__ */ new Date()).toISOString());
127
+ });
128
+ }
129
+ select(e, t) {
130
+ this.update((n) => {
131
+ let r = n.instances[e];
132
+ if (r?.sessions[t] === void 0) throw Error(`No stored session for login "${t}" on instance ${e}.`);
133
+ r.current = t, n.default = {
134
+ instanceId: e,
135
+ login: t
136
+ };
137
+ });
138
+ }
139
+ remove(e, t) {
140
+ let n;
141
+ return this.update((r) => {
142
+ let i = r.instances[e];
143
+ if (i === void 0) return;
144
+ let a = t ?? i.current;
145
+ a !== void 0 && (n = i.sessions[a], n !== void 0 && (delete i.sessions[a], i.current === a && delete i.current, r.default?.instanceId === e && r.default.login === a && delete r.default, Object.keys(i.sessions).length === 0 && delete r.instances[e]));
146
+ }), n;
147
+ }
148
+ update(e) {
149
+ this.prepareDir();
150
+ let t = this.lock();
151
+ try {
152
+ let t = this.read();
153
+ e(t), this.write(t);
154
+ } finally {
155
+ t();
156
+ }
157
+ }
158
+ prepareDir() {
159
+ let e = b(this.path);
160
+ m(e) ? M && y(e).mode & 18 && console.error(`warning: the directory ${e} is writable by other users; they can replace the sessions file. Run: chmod go-w ` + e) : h(e, {
161
+ recursive: !0,
162
+ mode: 448
163
+ });
164
+ }
165
+ lock() {
166
+ let e = `${this.path}.lock`, t = Date.now() + 5e3;
167
+ for (;;) {
168
+ try {
169
+ return p(g(e, "wx", 384)), () => v(e, { force: !0 });
170
+ } catch (e) {
171
+ if (!(e instanceof Error && "code" in e && e.code === "EEXIST")) throw e;
172
+ }
173
+ try {
174
+ Date.now() - y(e).mtimeMs > 3e4 && v(e, { force: !0 });
175
+ } catch {}
176
+ if (Date.now() > t) throw Error(`The sessions file is locked by another pl-cli process. If no other pl-cli runs, remove ${e}.`);
177
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
178
+ }
179
+ }
180
+ write(e) {
181
+ let t = `${this.path}.${u(8).toString("hex")}.tmp`;
182
+ try {
183
+ te(t, JSON.stringify(e, null, 2) + "\n", {
184
+ mode: 384,
185
+ flag: "wx"
186
+ }), ee(t, this.path);
187
+ } catch (e) {
188
+ throw v(t, { force: !0 }), e;
189
+ }
190
+ }
191
+ tightenFileMode() {
192
+ if (!M) return;
193
+ let e = y(this.path).mode & 511;
194
+ e & 63 && (f(this.path, 384), console.error(`warning: the sessions file ${this.path} had mode ${e.toString(8)}; changed it to 600.`));
195
+ }
196
+ }, P = class extends Error {
197
+ name = "SessionRequiredError";
198
+ }, F = /* @__PURE__ */ new WeakMap();
199
+ function I(e) {
200
+ return F.get(e);
201
+ }
202
+ var L;
203
+ function R() {
204
+ return L;
205
+ }
206
+ function z() {
207
+ L = void 0;
208
+ }
209
+ async function B(e) {
210
+ let n = await t.build(e), r = n.ll.serverInfo.instanceId;
211
+ return {
212
+ unauth: n,
213
+ instanceId: r === "" ? void 0 : r
214
+ };
215
+ }
216
+ function V(e) {
217
+ if (e === void 0) throw new P(G);
218
+ return e;
219
+ }
220
+ async function H(e) {
221
+ let t = e.address, n;
222
+ if (t === void 0) {
223
+ if (e.sessionStore === null) throw Error("Give the Backend address: --address or PL_ADDRESS.");
224
+ let r = (e.sessionStore ?? new N()).getDefault();
225
+ if (r === void 0) throw new P("No Backend address and no default session. Give --address (or PL_ADDRESS), sign in with \"pl-cli login -a <address> --method <id>\", or select a stored session with \"pl-cli session select <login> -a <address>\" (see \"pl-cli session list\").");
226
+ t = r.session.address, n = {
227
+ instanceId: r.instanceId,
228
+ login: r.session.login
229
+ };
230
+ }
231
+ let r = c(t), { unauth: i, instanceId: a } = await B(r);
232
+ if (n !== void 0 && a !== n.instanceId) throw await i.ll.close(), new P(`The default session of "${n.login}" is for instance ${n.instanceId}, but the Backend at ${O(t)} is instance ${a ?? "(no instance ID)"}. No token was sent. Give --address of the Backend, or select another session with "pl-cli session select".`);
233
+ let o = e.password ?? r.password, s = e.user ?? r.user ?? (o === void 0 ? n?.login : void 0), l, u, d, f;
234
+ try {
235
+ if (!await i.requireAuth()) l = {};
236
+ else if (s !== void 0 && o !== void 0) l = await i.login(s, o), u = s;
237
+ else if (o !== void 0) throw Error("--password needs --user (or PL_USER).");
238
+ else if (e.sessionStore === null) throw Error("Server requires authentication but no credentials provided. Use --user/--password flags or PL_USER/PL_PASSWORD env vars.");
239
+ else {
240
+ let n = V(a);
241
+ f = e.sessionStore ?? new N();
242
+ let o = q(f, n, O(t), s);
243
+ l = { jwtToken: await J(i, f, n, o, r) }, u = o.login, d = {
244
+ instanceId: n,
245
+ login: u
246
+ };
247
+ }
248
+ } finally {
249
+ await i.ll.close();
250
+ }
251
+ let p = await Y(r, l, d, f);
252
+ return u !== void 0 && F.set(p, u), p;
253
+ }
254
+ async function U(n) {
255
+ let r = c(n.address), i = await t.build(r), a;
256
+ try {
257
+ a = await i.login(n.adminUser, n.adminPassword);
258
+ } finally {
259
+ await i.ll.close();
260
+ }
261
+ let o = await e.init(r, { authInformation: a });
262
+ return F.set(o, n.adminUser), o;
263
+ }
264
+ var W = "3.6.0", G = `This Backend is older than v${W}; pl-cli login and stored sessions need v${W} or newer; use --user/--password per command.`;
265
+ function K(e, t) {
266
+ return `${t === "expired" ? `The stored session of "${e.login}" on instance ${e.instanceId} has expired.` : `The Backend refused the stored session of "${e.login}" on instance ${e.instanceId}.`} Run "pl-cli login" to sign in again.`;
267
+ }
268
+ function q(e, t, n, r) {
269
+ let i = e.get(t, r);
270
+ if (i !== void 0) {
271
+ let { issuer: e } = k(i.token);
272
+ if (e === void 0) throw new P(G);
273
+ if (e !== t) throw new P(`The stored session of "${i.login}" holds a token of instance ${e}, not of instance ${t}. It was not sent. Run "pl-cli login" to sign in again.`);
274
+ return i;
275
+ }
276
+ let a = e.logins(t);
277
+ throw r === void 0 ? a.length > 0 ? new P(`The Backend at ${n} (instance ${t}) has no current session. Stored logins: ${a.join(", ")}. Run "pl-cli session select <login>" or "pl-cli login".`) : new P(`The Backend at ${n} requires authentication and there is no stored session for its instance ${t}. Run "pl-cli login", or give credentials with --user/--password (PL_USER/PL_PASSWORD).`) : new P(`No stored session for "${r}" on the Backend at ${n} (instance ${t}). Run "pl-cli login --user ${r}", or give a password with --password or PL_PASSWORD.`);
278
+ }
279
+ async function J(e, t, n, i, a) {
280
+ let c = {
281
+ instanceId: n,
282
+ login: i.login
283
+ }, { expiresAt: l } = k(i.token);
284
+ if (l !== void 0 && l <= Date.now()) throw new P(K(c, "expired"));
285
+ let u = r({ jwtToken: i.token }, a.authMaxRefreshSeconds);
286
+ if (u === void 0 || Date.now() < u || !e.hasCapability("auth:v2")) return i.token;
287
+ try {
288
+ let { jwtToken: r } = await e.refreshToken(i.token);
289
+ return r === void 0 ? i.token : (t.updateToken(n, i.login, r), r);
290
+ } catch (e) {
291
+ if (s(e)) throw new P(K(c, "refused"), { cause: e });
292
+ return o(e) || console.error(`warning: cannot renew the stored session: ${String(e)}`), i.token;
293
+ }
294
+ }
295
+ async function Y(e, t, n, r) {
296
+ let i = await ae(e, t, n, r);
297
+ if (n !== void 0 && i.serverInfo.instanceId !== n.instanceId) throw await i.close(), new P(`The Backend instance at the address changed from ${n.instanceId} to ${i.serverInfo.instanceId} during the connection. Run the command again.`);
298
+ return i;
299
+ }
300
+ async function ae(t, n, r, i) {
301
+ L = r;
302
+ let a = r === void 0 ? void 0 : (e) => {
303
+ e.jwtToken !== void 0 && i !== void 0 && i.updateToken(r.instanceId, r.login, e.jwtToken);
304
+ };
305
+ try {
306
+ return await e.init(t, {
307
+ authInformation: n,
308
+ onUpdate: a
309
+ });
310
+ } catch (e) {
311
+ throw r !== void 0 && s(e) ? new P(K(r, "refused"), { cause: e }) : e;
312
+ }
313
+ }
314
+ // src/output.ts
315
+ function oe(e) {
316
+ console.log(e);
317
+ }
318
+ function se(e) {
319
+ console.log(JSON.stringify(e, null, 2));
320
+ }
321
+ function ce(e, t) {
322
+ let n = (e) => /[",\r\n]/.test(e) ? `"${e.replace(/"/g, "\"\"")}"` : e, r = [e, ...t].map((e) => e.map(n).join(","));
323
+ console.log(r.join("\n"));
324
+ }
325
+ function le(e, t) {
326
+ let n = e.map((e, n) => Math.max(e.length, ...t.map((e) => (e[n] ?? "").length))), r = n.map((e) => "-".repeat(e)).join(" ");
327
+ return [
328
+ e.map((e, t) => e.padEnd(n[t])).join(" "),
329
+ r,
330
+ ...t.map((e) => e.map((e, t) => (e ?? "").padEnd(n[t])).join(" "))
331
+ ].join("\n");
332
+ }
333
+ function ue(e) {
334
+ return e.getTime() === 0 ? "(unknown)" : e.toISOString().replace("T", " ").replace(/\.\d+Z$/, "Z");
335
+ }
336
+ // src/project_ops.ts
337
+ async function de(e, t) {
338
+ return await e.withReadTx("listProjects", async (e) => {
339
+ let n = await e.getResourceData(t, !0), r = [];
340
+ for (let t of n.fields) {
341
+ if (a(t.value)) continue;
342
+ let [n, i, o] = await Promise.all([
343
+ e.getKValueStringIfExists(t.value, w),
344
+ e.getKValueStringIfExists(t.value, S),
345
+ e.getKValueStringIfExists(t.value, C)
346
+ ]), s = n ? JSON.parse(n) : { label: "(unknown)" }, c = l(t.value);
347
+ r.push({
348
+ id: c,
349
+ rid: t.value,
350
+ label: s.label,
351
+ created: i ? new Date(Number(i)) : /* @__PURE__ */ new Date(0),
352
+ lastModified: o ? new Date(Number(o)) : /* @__PURE__ */ new Date(0)
353
+ });
354
+ }
355
+ return r.sort((e, t) => t.lastModified.getTime() - e.lastModified.getTime()), r;
356
+ });
357
+ }
358
+ async function fe(e, t) {
359
+ return await e.withReadTx("listProjectIdentities", async (e) => await X(e, t));
360
+ }
361
+ async function X(e, t) {
362
+ let n = await e.getResourceData(t, !0), r = [];
363
+ for (let t of n.fields) {
364
+ if (a(t.value)) continue;
365
+ let n = await e.getKValueStringIfExists(t.value, w), i = n ? JSON.parse(n) : { label: "(unknown)" };
366
+ r.push({
367
+ id: l(t.value),
368
+ rid: t.value,
369
+ fieldName: t.name,
370
+ label: i.label
371
+ });
372
+ }
373
+ return r;
374
+ }
375
+ async function Z(e, t, n) {
376
+ return await e.withReadTx("getProjectInfo", async (e) => {
377
+ let r = await e.listKeyValuesString(n), i = r.find((e) => e.key === w), a = r.find((e) => e.key === S), o = r.find((e) => e.key === C), s = r.find((e) => e.key === E), c = r.find((e) => e.key === re), l = i ? JSON.parse(i.value) : { label: "(unknown)" }, u = s ? JSON.parse(s.value) : void 0, d = [];
378
+ if (c) {
379
+ let e = JSON.parse(c.value);
380
+ for (let t of e.groups ?? []) for (let e of t.blocks ?? []) d.push(e.id);
381
+ }
382
+ return {
383
+ id: t,
384
+ rid: n,
385
+ label: l.label,
386
+ created: a ? new Date(Number(a.value)) : /* @__PURE__ */ new Date(0),
387
+ lastModified: o ? new Date(Number(o.value)) : /* @__PURE__ */ new Date(0),
388
+ schemaVersion: u,
389
+ blockCount: d.length,
390
+ blockIds: d
391
+ };
392
+ });
393
+ }
394
+ async function pe(e, t, n) {
395
+ return await e.withReadTx("resolveProject", async (e) => {
396
+ let r = await e.getResourceData(t, !0);
397
+ for (let e of r.fields) {
398
+ if (a(e.value)) continue;
399
+ let t = l(e.value);
400
+ if (t === n) return {
401
+ id: t,
402
+ rid: e.value,
403
+ fieldName: e.name
404
+ };
405
+ }
406
+ for (let t of r.fields) {
407
+ if (a(t.value)) continue;
408
+ let r = await e.getKValueStringIfExists(t.value, w);
409
+ if (r && JSON.parse(r).label === n) return {
410
+ id: l(t.value),
411
+ rid: t.value,
412
+ fieldName: t.name
413
+ };
414
+ }
415
+ throw Error(`Project "${n}" not found (searched by id and label).`);
416
+ });
417
+ }
418
+ async function Q(e, t) {
419
+ let n = await e.getResourceData(t, !0), r = [];
420
+ for (let t of n.fields) {
421
+ if (a(t.value)) continue;
422
+ let n = await e.getKValueStringIfExists(t.value, w);
423
+ if (n) {
424
+ let e = JSON.parse(n);
425
+ r.push(e.label);
426
+ }
427
+ }
428
+ return r;
429
+ }
430
+ function $(e, t) {
431
+ let n = `${e} (Copy)`, r = 2;
432
+ for (; t.includes(n);) n = `${e} (Copy ${r})`, r++;
433
+ return n;
434
+ }
435
+ async function me(e, t, n) {
436
+ await e.withWriteTx("renameProject", async (e) => {
437
+ let r = await e.getKValueString(t, w), i = {
438
+ ...JSON.parse(r),
439
+ label: n
440
+ };
441
+ e.setKValue(t, w, JSON.stringify(i)), e.setKValue(t, C, String(Date.now())), await e.commit();
442
+ });
443
+ }
444
+ async function he(e, t, r) {
445
+ await e.withWriteTx("deleteProject", async (e) => {
446
+ e.removeField(n(t, r)), await e.commit();
447
+ });
448
+ }
449
+ async function ge(e, t, r) {
450
+ return await e.withWriteTx("moveProjects", async (e) => {
451
+ let i = await X(e, t);
452
+ if (i.length === 0) return [];
453
+ let a = await Q(e, r), o = [];
454
+ for (let s of i) {
455
+ let i = await e.getKValueString(s.rid, w), c = JSON.parse(i), l = c.label, u = l;
456
+ a.includes(u) && (u = $(l, a), e.setKValue(s.rid, w, JSON.stringify({
457
+ ...c,
458
+ label: u
459
+ })), e.setKValue(s.rid, C, String(Date.now()))), a.push(u), e.createField(n(r, d()), "Dynamic", s.rid), e.removeField(n(t, s.fieldName)), o.push({
460
+ id: s.id,
461
+ sourceLabel: l,
462
+ targetLabel: u
463
+ });
464
+ }
465
+ return await e.commit(), o;
466
+ });
467
+ }
468
+ async function _e(e) {
469
+ return await e.withReadTx("getProjectList", async (e) => {
470
+ let t = await e.getField({
471
+ resourceId: e.clientRoot,
472
+ fieldName: T
473
+ });
474
+ if (a(t.value)) throw Error("No project list found for this user.");
475
+ return t.value;
476
+ });
477
+ }
478
+ async function ve(e, t) {
479
+ let r;
480
+ try {
481
+ r = await e.getUserRoot({ login: t });
482
+ } catch (e) {
483
+ throw i(e) ? Error(`User "${t}" not found on this server.`) : e;
484
+ }
485
+ if (r === void 0) throw Error(`User "${t}" not found on this server (no root resource).`);
486
+ return await e.withReadTx("openUserRoot", async (e) => {
487
+ let t = await e.getFieldIfExists(n(r, T));
488
+ return t === void 0 || a(t.value) ? {
489
+ userRoot: r,
490
+ projectListRid: void 0
491
+ } : {
492
+ userRoot: r,
493
+ projectListRid: t.value
494
+ };
495
+ });
496
+ }
497
+ async function ye(e, t) {
498
+ return await e.withWriteTx("ensureUserProjectList", async (e) => {
499
+ let r = n(t, T);
500
+ e.createField(r, "Dynamic");
501
+ let i = await e.getField(r);
502
+ if (!a(i.value)) return await e.commit(), i.value;
503
+ let o = e.createEphemeral(ie);
504
+ return e.lock(o), e.setField(r, o), await e.commit(), await o.globalId;
505
+ });
506
+ }
507
+ async function be(e, t) {
508
+ let n;
509
+ if (n = await e.getUserRoot({ login: t }), n === void 0) throw Error(`User "${t}" not found on this server (no root resource).`);
510
+ return await e.withReadTx("navigateToUserProjects", async (e) => {
511
+ let r = await e.getField({
512
+ resourceId: n,
513
+ fieldName: T
514
+ });
515
+ if (a(r.value)) throw Error(`User "${t}" has no project list.`);
516
+ return {
517
+ userRoot: n,
518
+ projectListRid: r.value
519
+ };
520
+ });
521
+ }
522
+ export { R as A, I as C, V as D, B as E, O as F, A as M, j as N, z as O, k as P, P as S, H as T, ce as _, Q as a, W as b, fe as c, be as d, ve as f, le as g, ue as h, ye as i, N as j, K as k, de as l, pe as m, he as n, Z as o, me as p, D as r, _e as s, $ as t, ge as u, se as v, U as w, G as x, oe as y };
523
+
524
+ //# sourceMappingURL=project_ops-CHhJu5k5.js.map