@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,151 @@
1
+ // Test support: a fake Backend behind the pl-client classes that pl-cli uses.
2
+ // Not part of the build: only test files import it.
3
+ import { vi } from "vitest";
4
+
5
+ export interface FakeLoginMethod {
6
+ kind: "basic" | "token" | "sso";
7
+ id: string;
8
+ title: string;
9
+ description: string;
10
+ /** SSO methods only. */
11
+ issuer?: string;
12
+ }
13
+
14
+ /** State of the fake Backend at one address. */
15
+ export interface FakeBackend {
16
+ instanceId: string;
17
+ requireAuth: boolean;
18
+ authV2: boolean;
19
+ methods: FakeLoginMethod[];
20
+ /** Accepted passwords by login. */
21
+ passwords: Record<string, string>;
22
+ /** Tokens that the Backend refuses. */
23
+ refused: Set<string>;
24
+ /** Calls, for assertions. */
25
+ calls: string[];
26
+ /** Instance ID that the full connection reports, when it differs from the ping answer. */
27
+ instanceIdAfterInit?: string;
28
+ /** Issuer to write into the tokens that this Backend issues. Default: its instance ID.
29
+ * `null`: no issuer (a Backend older than v3.6.0). */
30
+ tokenIssuer?: string | null;
31
+ }
32
+
33
+ /** Makes an unsigned JWT with the claims that the Backend writes. */
34
+ export function fakeToken(
35
+ login: string,
36
+ /** `undefined`: no `iss` claim, as Backends older than v3.6.0 issue. */
37
+ iss: string | undefined,
38
+ opts: { iat?: number; exp?: number } = {},
39
+ ): string {
40
+ const now = Math.floor(Date.now() / 1000);
41
+ const iat = opts.iat ?? now;
42
+ const exp = opts.exp ?? now + 3600;
43
+ const enc = (v: object) => Buffer.from(JSON.stringify(v)).toString("base64url");
44
+ return `${enc({ alg: "none" })}.${enc({ sub: login, iss, iat, exp, user: { login } })}.sig`;
45
+ }
46
+
47
+ export function newFakeBackend(instanceId: string, over: Partial<FakeBackend> = {}): FakeBackend {
48
+ return {
49
+ instanceId,
50
+ requireAuth: true,
51
+ authV2: true,
52
+ methods: [{ kind: "basic", id: "htpasswd", title: "Password", description: "" }],
53
+ passwords: { alice: "secret" },
54
+ refused: new Set(),
55
+ calls: [],
56
+ ...over,
57
+ };
58
+ }
59
+
60
+ /** Fake Backends by address. Tests fill it; the mocked pl-client reads it. */
61
+ export const backends = new Map<string, FakeBackend>();
62
+
63
+ /** Auth information that `PlClient.init` received, by call. */
64
+ export const initCalls: {
65
+ address: string;
66
+ jwtToken?: string;
67
+ onUpdate?: (info: { jwtToken?: string }) => void;
68
+ }[] = [];
69
+
70
+ function backendAt(address: string): FakeBackend {
71
+ const b = backends.get(address);
72
+ if (b === undefined) throw new Error(`no fake Backend at ${address}`);
73
+ return b;
74
+ }
75
+
76
+ function issue(b: FakeBackend, login: string): { jwtToken: string } {
77
+ const iss = b.tokenIssuer === null ? undefined : (b.tokenIssuer ?? b.instanceId);
78
+ return { jwtToken: fakeToken(login, iss) };
79
+ }
80
+
81
+ /** Module factory for `vi.mock("@milaboratories/pl-client", ...)`. */
82
+ export async function mockPlClient(
83
+ importOriginal: () => Promise<Record<string, unknown>>,
84
+ ): Promise<Record<string, unknown>> {
85
+ const actual = await importOriginal();
86
+ // The real error class, so that `isUnauthenticated` of pl-client recognizes the errors.
87
+ const RealUnauthenticatedError = actual.UnauthenticatedError;
88
+ if (typeof RealUnauthenticatedError !== "function")
89
+ throw new Error("pl-client exports no UnauthenticatedError");
90
+ const unauthenticated = (message: string): Error =>
91
+ Reflect.construct(RealUnauthenticatedError, [message]);
92
+ // Tests use addresses without a scheme, so the config keeps them as `hostAndPort`.
93
+ const build = async (config: { hostAndPort?: string } | string) => {
94
+ const address = typeof config === "string" ? config : (config.hostAndPort ?? "");
95
+ const b = backendAt(address);
96
+ b.calls.push("ping");
97
+ return {
98
+ ll: { serverInfo: { instanceId: b.instanceId }, close: vi.fn(async () => {}) },
99
+ requireAuth: async () => b.requireAuth,
100
+ hasCapability: (c: string) => c === "auth:v2" && b.authV2,
101
+ loginMethods: () => b.methods,
102
+ get supportedAuthSchemes() {
103
+ return {
104
+ basic: b.methods.some((m) => m.kind === "basic"),
105
+ token: b.methods.some((m) => m.kind === "token"),
106
+ };
107
+ },
108
+ login: async (user: string, password: string, idP?: string) => {
109
+ b.calls.push(`login:${user}:${idP ?? ""}`);
110
+ if (b.passwords[user] !== password) throw unauthenticated("bad password");
111
+ return issue(b, user);
112
+ },
113
+ refreshToken: async (token: string) => {
114
+ b.calls.push("refresh");
115
+ if (b.refused.has(token)) throw unauthenticated("refused");
116
+ const login = JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString()).sub;
117
+ return issue(b, login);
118
+ },
119
+ beginSSOLogin: async (idP?: string) => {
120
+ b.calls.push(`beginSSO:${idP ?? ""}`);
121
+ return { flow: "public_pkce", nonce: "n-1", expiresAt: new Date(), clientSecret: "cs" };
122
+ },
123
+ loginSSO: async (p: { tokenResponse: Uint8Array; idP?: string }) => {
124
+ b.calls.push(`loginSSO:${Buffer.from(p.tokenResponse).toString()}:${p.idP ?? ""}`);
125
+ return issue(b, "sso-user");
126
+ },
127
+ };
128
+ };
129
+ return {
130
+ ...actual,
131
+ UnauthenticatedPlClient: { build },
132
+ PlClient: {
133
+ init: async (
134
+ config: { hostAndPort?: string },
135
+ auth: {
136
+ authInformation: { jwtToken?: string };
137
+ onUpdate?: (info: { jwtToken?: string }) => void;
138
+ },
139
+ ) => {
140
+ const address = config.hostAndPort ?? "";
141
+ const b = backendAt(address);
142
+ const jwtToken = auth.authInformation.jwtToken;
143
+ initCalls.push({ address, jwtToken, onUpdate: auth.onUpdate });
144
+ if (jwtToken !== undefined && b.refused.has(jwtToken)) throw unauthenticated("refused");
145
+ // `instanceIdAfterInit` simulates another Backend that answers between probe and init.
146
+ const instanceId = b.instanceIdAfterInit ?? b.instanceId;
147
+ return { close: async () => {}, serverInfo: { instanceId } };
148
+ },
149
+ },
150
+ };
151
+ }
@@ -1,229 +0,0 @@
1
- import { PlClient as e, UnauthenticatedPlClient as t, field as n, isNotFoundError as r, isNullSignedResourceId as i, plAddressToConfig as a, resourceIdToString as o } from "@milaboratories/pl-client";
2
- import { randomUUID as s } from "node:crypto";
3
- import { ProjectCreatedTimestamp as c, ProjectLastModifiedTimestamp as l, ProjectMetaKey as u, ProjectStructureKey as d, ProjectsField as f, ProjectsResourceType as p, SchemaVersionKey as m, duplicateProject as h } from "@milaboratories/pl-middle-layer";
4
- // src/connection.ts
5
- async function g(n) {
6
- let r = a(n.address);
7
- n.user !== void 0 && (r.user = n.user), n.password !== void 0 && (r.password = n.password);
8
- let i = await t.build(r), o;
9
- if (await i.requireAuth()) {
10
- if (r.user === void 0 || r.password === void 0) throw Error("Server requires authentication but no credentials provided. Use --user/--password flags or PL_USER/PL_PASSWORD env vars.");
11
- o = await i.login(r.user, r.password);
12
- } else o = {};
13
- return await e.init(r, { authInformation: o });
14
- }
15
- async function _(n) {
16
- let r = a(n.address), i = await (await t.build(r)).login(n.adminUser, n.adminPassword);
17
- return await e.init(r, { authInformation: i });
18
- }
19
- // src/project_ops.ts
20
- async function v(e, t) {
21
- return await e.withReadTx("listProjects", async (e) => {
22
- let n = await e.getResourceData(t, !0), r = [];
23
- for (let t of n.fields) {
24
- if (i(t.value)) continue;
25
- let [n, a, s] = await Promise.all([
26
- e.getKValueStringIfExists(t.value, u),
27
- e.getKValueStringIfExists(t.value, c),
28
- e.getKValueStringIfExists(t.value, l)
29
- ]), d = n ? JSON.parse(n) : { label: "(unknown)" }, f = o(t.value);
30
- r.push({
31
- id: f,
32
- rid: t.value,
33
- label: d.label,
34
- created: a ? new Date(Number(a)) : /* @__PURE__ */ new Date(0),
35
- lastModified: s ? new Date(Number(s)) : /* @__PURE__ */ new Date(0)
36
- });
37
- }
38
- return r.sort((e, t) => t.lastModified.getTime() - e.lastModified.getTime()), r;
39
- });
40
- }
41
- async function y(e, t) {
42
- return await e.withReadTx("listProjectIdentities", async (e) => await b(e, t));
43
- }
44
- async function b(e, t) {
45
- let n = await e.getResourceData(t, !0), r = [];
46
- for (let t of n.fields) {
47
- if (i(t.value)) continue;
48
- let n = await e.getKValueStringIfExists(t.value, u), a = n ? JSON.parse(n) : { label: "(unknown)" };
49
- r.push({
50
- id: o(t.value),
51
- rid: t.value,
52
- fieldName: t.name,
53
- label: a.label
54
- });
55
- }
56
- return r;
57
- }
58
- async function x(e, t, n) {
59
- return await e.withReadTx("getProjectInfo", async (e) => {
60
- let r = await e.listKeyValuesString(n), i = r.find((e) => e.key === u), a = r.find((e) => e.key === c), o = r.find((e) => e.key === l), s = r.find((e) => e.key === m), f = r.find((e) => e.key === d), p = i ? JSON.parse(i.value) : { label: "(unknown)" }, h = s ? JSON.parse(s.value) : void 0, g = [];
61
- if (f) {
62
- let e = JSON.parse(f.value);
63
- for (let t of e.groups ?? []) for (let e of t.blocks ?? []) g.push(e.id);
64
- }
65
- return {
66
- id: t,
67
- rid: n,
68
- label: p.label,
69
- created: a ? new Date(Number(a.value)) : /* @__PURE__ */ new Date(0),
70
- lastModified: o ? new Date(Number(o.value)) : /* @__PURE__ */ new Date(0),
71
- schemaVersion: h,
72
- blockCount: g.length,
73
- blockIds: g
74
- };
75
- });
76
- }
77
- async function S(e, t, n) {
78
- return await e.withReadTx("resolveProject", async (e) => {
79
- let r = await e.getResourceData(t, !0);
80
- for (let e of r.fields) {
81
- if (i(e.value)) continue;
82
- let t = o(e.value);
83
- if (t === n) return {
84
- id: t,
85
- rid: e.value,
86
- fieldName: e.name
87
- };
88
- }
89
- for (let t of r.fields) {
90
- if (i(t.value)) continue;
91
- let r = await e.getKValueStringIfExists(t.value, u);
92
- if (r && JSON.parse(r).label === n) return {
93
- id: o(t.value),
94
- rid: t.value,
95
- fieldName: t.name
96
- };
97
- }
98
- throw Error(`Project "${n}" not found (searched by id and label).`);
99
- });
100
- }
101
- async function C(e, t) {
102
- let n = await e.getResourceData(t, !0), r = [];
103
- for (let t of n.fields) {
104
- if (i(t.value)) continue;
105
- let n = await e.getKValueStringIfExists(t.value, u);
106
- if (n) {
107
- let e = JSON.parse(n);
108
- r.push(e.label);
109
- }
110
- }
111
- return r;
112
- }
113
- function w(e, t) {
114
- let n = `${e} (Copy)`, r = 2;
115
- for (; t.includes(n);) n = `${e} (Copy ${r})`, r++;
116
- return n;
117
- }
118
- async function T(e, t, n) {
119
- await e.withWriteTx("renameProject", async (e) => {
120
- let r = await e.getKValueString(t, u), i = {
121
- ...JSON.parse(r),
122
- label: n
123
- };
124
- e.setKValue(t, u, JSON.stringify(i)), e.setKValue(t, l, String(Date.now())), await e.commit();
125
- });
126
- }
127
- async function E(e, t, r) {
128
- await e.withWriteTx("deleteProject", async (e) => {
129
- e.removeField(n(t, r)), await e.commit();
130
- });
131
- }
132
- async function D(e, t, r) {
133
- return await e.withWriteTx("moveProjects", async (e) => {
134
- let i = await b(e, t);
135
- if (i.length === 0) return [];
136
- let a = await C(e, r), o = [];
137
- for (let c of i) {
138
- let i = await e.getKValueString(c.rid, u), d = JSON.parse(i), f = d.label, p = f;
139
- a.includes(p) && (p = w(f, a), e.setKValue(c.rid, u, JSON.stringify({
140
- ...d,
141
- label: p
142
- })), e.setKValue(c.rid, l, String(Date.now()))), a.push(p), e.createField(n(r, s()), "Dynamic", c.rid), e.removeField(n(t, c.fieldName)), o.push({
143
- id: c.id,
144
- sourceLabel: f,
145
- targetLabel: p
146
- });
147
- }
148
- return await e.commit(), o;
149
- });
150
- }
151
- async function O(e) {
152
- return await e.withReadTx("getProjectList", async (e) => {
153
- let t = await e.getField({
154
- resourceId: e.clientRoot,
155
- fieldName: f
156
- });
157
- if (i(t.value)) throw Error("No project list found for this user.");
158
- return t.value;
159
- });
160
- }
161
- async function k(e, t) {
162
- let a;
163
- try {
164
- a = await e.getUserRoot({ login: t });
165
- } catch (e) {
166
- throw r(e) ? Error(`User "${t}" not found on this server.`) : e;
167
- }
168
- if (a === void 0) throw Error(`User "${t}" not found on this server (no root resource).`);
169
- return await e.withReadTx("openUserRoot", async (e) => {
170
- let t = await e.getFieldIfExists(n(a, f));
171
- return t === void 0 || i(t.value) ? {
172
- userRoot: a,
173
- projectListRid: void 0
174
- } : {
175
- userRoot: a,
176
- projectListRid: t.value
177
- };
178
- });
179
- }
180
- async function A(e, t) {
181
- return await e.withWriteTx("ensureUserProjectList", async (e) => {
182
- let r = n(t, f);
183
- e.createField(r, "Dynamic");
184
- let a = await e.getField(r);
185
- if (!i(a.value)) return await e.commit(), a.value;
186
- let o = e.createEphemeral(p);
187
- return e.lock(o), e.setField(r, o), await e.commit(), await o.globalId;
188
- });
189
- }
190
- async function j(e, t) {
191
- let n;
192
- if (n = await e.getUserRoot({ login: t }), n === void 0) throw Error(`User "${t}" not found on this server (no root resource).`);
193
- return await e.withReadTx("navigateToUserProjects", async (e) => {
194
- let r = await e.getField({
195
- resourceId: n,
196
- fieldName: f
197
- });
198
- if (i(r.value)) throw Error(`User "${t}" has no project list.`);
199
- return {
200
- userRoot: n,
201
- projectListRid: r.value
202
- };
203
- });
204
- }
205
- // src/output.ts
206
- function M(e) {
207
- console.log(e);
208
- }
209
- function N(e) {
210
- console.log(JSON.stringify(e, null, 2));
211
- }
212
- function P(e, t) {
213
- let n = (e) => /[",\r\n]/.test(e) ? `"${e.replace(/"/g, "\"\"")}"` : e, r = [e, ...t].map((e) => e.map(n).join(","));
214
- console.log(r.join("\n"));
215
- }
216
- function F(e, t) {
217
- let n = e.map((e, n) => Math.max(e.length, ...t.map((e) => (e[n] ?? "").length))), r = n.map((e) => "-".repeat(e)).join(" ");
218
- return [
219
- e.map((e, t) => e.padEnd(n[t])).join(" "),
220
- r,
221
- ...t.map((e) => e.map((e, t) => (e ?? "").padEnd(n[t])).join(" "))
222
- ].join("\n");
223
- }
224
- function I(e) {
225
- return e.getTime() === 0 ? "(unknown)" : e.toISOString().replace("T", " ").replace(/\.\d+Z$/, "Z");
226
- }
227
- export { k as _, M as a, _ as b, h as c, x as d, O as f, j as g, D as h, N as i, A as l, v as m, F as n, w as o, y as p, P as r, E as s, I as t, C as u, T as v, g as x, S as y };
228
-
229
- //# sourceMappingURL=output-D41Wn0wM.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"output-D41Wn0wM.js","names":["createPlConnection","config","plAddressToConfig","opts","unauth","UnauthenticatedPlClient","authInformation","PlClient","createAdminPlConnection","listProjects","pl","data","tx","projectListRid","entries","f","isNullSignedResourceId","metaStr","createdStr","modifiedStr","ProjectMetaKey","ProjectCreatedTimestamp","ProjectLastModifiedTimestamp","meta","projectId","resourceIdToString","b","a","listProjectIdentities","listProjectIdentitiesInTx","projects","getProjectInfo","kvs","rid","metaKV","kv","createdKV","modifiedKV","schemaKV","SchemaVersionKey","structureKV","ProjectStructureKey","schemaVersion","blockIds","structure","group","block","resolveProject","identifier","getExistingLabelsInTx","labels","deduplicateName","candidate","baseName","i","existingLabels","renameProject","projectRid","updated","newLabel","deleteProject","field","fieldName","moveProjects","sourceProjectListRid","takenLabels","targetProjectListRid","moved","project","sourceLabel","targetLabel","randomUUID","getProjectListRid","fieldData","ProjectsField","openUserRoot","userRoot","username","isNotFoundError","projectsField","ensureUserProjectList","list","ProjectsResourceType","navigateToUserRoot","userRootRid","projectsFieldData","outputText","message","outputJson","outputCsv","esc","v","lines","headers","rows","r","formatTable","colWidths","h","sep","w","row","cell","formatDate","d","duplicateProject"],"sources":["../src/connection.ts","../src/project_ops.ts","../src/output.ts"],"sourcesContent":["import {\n PlClient,\n UnauthenticatedPlClient,\n plAddressToConfig,\n type AuthInformation,\n type PlClientConfig,\n} from \"@milaboratories/pl-client\";\n\nexport interface PlConnectionOptions {\n address: string;\n user?: string;\n password?: string;\n}\n\nexport interface AdminConnectionOptions {\n address: string;\n adminUser: string;\n adminPassword: string;\n}\n\n/** Creates an authenticated PlClient from address + credentials. */\nexport async function createPlConnection(opts: PlConnectionOptions): Promise<PlClient> {\n const config: PlClientConfig = plAddressToConfig(opts.address);\n\n if (opts.user !== undefined) config.user = opts.user;\n if (opts.password !== undefined) config.password = opts.password;\n\n const unauth = await UnauthenticatedPlClient.build(config);\n let authInformation: AuthInformation;\n\n if (await unauth.requireAuth()) {\n if (config.user === undefined || config.password === undefined) {\n throw new Error(\n \"Server requires authentication but no credentials provided. \" +\n \"Use --user/--password flags or PL_USER/PL_PASSWORD env vars.\",\n );\n }\n authInformation = await unauth.login(config.user, config.password);\n } else {\n authInformation = {};\n }\n\n return await PlClient.init(config, { authInformation });\n}\n\n/** Creates a PlClient with admin/controller credentials. */\nexport async function createAdminPlConnection(opts: AdminConnectionOptions): Promise<PlClient> {\n const config: PlClientConfig = plAddressToConfig(opts.address);\n\n const unauth = await UnauthenticatedPlClient.build(config);\n const authInformation: AuthInformation = await unauth.login(opts.adminUser, opts.adminPassword);\n\n return await PlClient.init(config, { authInformation });\n}\n","import type { PlClient, SignedResourceId, PlTransaction } from \"@milaboratories/pl-client\";\nimport {\n field,\n isNotFoundError,\n isNullSignedResourceId,\n resourceIdToString,\n} from \"@milaboratories/pl-client\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n ProjectMetaKey,\n ProjectCreatedTimestamp,\n ProjectLastModifiedTimestamp,\n SchemaVersionKey,\n ProjectStructureKey,\n ProjectsField,\n ProjectsResourceType,\n duplicateProject,\n} from \"@milaboratories/pl-middle-layer\";\nimport type { ProjectMeta } from \"@milaboratories/pl-middle-layer\";\n\nexport interface ProjectEntry {\n id: string;\n rid: SignedResourceId;\n label: string;\n created: Date;\n lastModified: Date;\n}\n\nexport interface ProjectIdentity {\n /** Project ID (resourceIdToString of resource ID) */\n id: string;\n /** Signed resource ID for use in transactions */\n rid: SignedResourceId;\n /** UUID field name in the project list resource */\n fieldName: string;\n}\n\nexport interface ProjectInfo extends ProjectEntry {\n schemaVersion: string | undefined;\n blockCount: number;\n blockIds: string[];\n}\n\n/** List all projects from a project list resource. */\nexport async function listProjects(\n pl: PlClient,\n projectListRid: SignedResourceId,\n): Promise<ProjectEntry[]> {\n return await pl.withReadTx(\"listProjects\", async (tx) => {\n const data = await tx.getResourceData(projectListRid, true);\n const entries: ProjectEntry[] = [];\n\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n\n const [metaStr, createdStr, modifiedStr] = await Promise.all([\n tx.getKValueStringIfExists(f.value, ProjectMetaKey),\n tx.getKValueStringIfExists(f.value, ProjectCreatedTimestamp),\n tx.getKValueStringIfExists(f.value, ProjectLastModifiedTimestamp),\n ]);\n\n const meta: ProjectMeta = metaStr ? JSON.parse(metaStr) : { label: \"(unknown)\" };\n\n const projectId = resourceIdToString(f.value);\n entries.push({\n id: projectId,\n rid: f.value,\n label: meta.label,\n created: createdStr ? new Date(Number(createdStr)) : new Date(0),\n lastModified: modifiedStr ? new Date(Number(modifiedStr)) : new Date(0),\n });\n }\n\n entries.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());\n return entries;\n });\n}\n\n/** A project's identity plus its label — what a whole-root operation needs per project. */\nexport interface ProjectIdentityWithLabel extends ProjectIdentity {\n label: string;\n}\n\n/**\n * Lists every project in a project list with the field name holding it, which\n * {@link listProjects} omits. Whole-root operations (moving a user's projects out before the\n * account is deleted) need that field name to detach each project from its old owner.\n */\nexport async function listProjectIdentities(\n pl: PlClient,\n projectListRid: SignedResourceId,\n): Promise<ProjectIdentityWithLabel[]> {\n return await pl.withReadTx(\"listProjectIdentities\", async (tx) => {\n return await listProjectIdentitiesInTx(tx, projectListRid);\n });\n}\n\n/**\n * {@link listProjectIdentities} against a transaction the caller already holds, so a write that\n * acts on the list can read it in the same transaction rather than trusting an earlier snapshot.\n */\nexport async function listProjectIdentitiesInTx(\n tx: PlTransaction,\n projectListRid: SignedResourceId,\n): Promise<ProjectIdentityWithLabel[]> {\n const data = await tx.getResourceData(projectListRid, true);\n const projects: ProjectIdentityWithLabel[] = [];\n\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n\n const metaStr = await tx.getKValueStringIfExists(f.value, ProjectMetaKey);\n const meta: ProjectMeta = metaStr ? JSON.parse(metaStr) : { label: \"(unknown)\" };\n\n projects.push({\n id: resourceIdToString(f.value),\n rid: f.value,\n fieldName: f.name,\n label: meta.label,\n });\n }\n\n return projects;\n}\n\n/** Get detailed info about a project. */\nexport async function getProjectInfo(\n pl: PlClient,\n projectId: string,\n rid: SignedResourceId,\n): Promise<ProjectInfo> {\n return await pl.withReadTx(\"getProjectInfo\", async (tx) => {\n const kvs = await tx.listKeyValuesString(rid);\n\n const metaKV = kvs.find((kv: { key: string }) => kv.key === ProjectMetaKey);\n const createdKV = kvs.find((kv: { key: string }) => kv.key === ProjectCreatedTimestamp);\n const modifiedKV = kvs.find((kv: { key: string }) => kv.key === ProjectLastModifiedTimestamp);\n const schemaKV = kvs.find((kv: { key: string }) => kv.key === SchemaVersionKey);\n const structureKV = kvs.find((kv: { key: string }) => kv.key === ProjectStructureKey);\n\n const meta: ProjectMeta = metaKV ? JSON.parse(metaKV.value) : { label: \"(unknown)\" };\n const schemaVersion = schemaKV ? JSON.parse(schemaKV.value) : undefined;\n\n const blockIds: string[] = [];\n if (structureKV) {\n const structure = JSON.parse(structureKV.value);\n for (const group of structure.groups ?? []) {\n for (const block of group.blocks ?? []) {\n blockIds.push(block.id);\n }\n }\n }\n\n return {\n id: projectId,\n rid: rid,\n label: meta.label,\n created: createdKV ? new Date(Number(createdKV.value)) : new Date(0),\n lastModified: modifiedKV ? new Date(Number(modifiedKV.value)) : new Date(0),\n schemaVersion,\n blockCount: blockIds.length,\n blockIds,\n };\n });\n}\n\n/** Resolve a project identifier (id or label) to its project ID, ResourceId and field name. */\nexport async function resolveProject(\n pl: PlClient,\n projectListRid: SignedResourceId,\n identifier: string,\n): Promise<ProjectIdentity> {\n return await pl.withReadTx(\"resolveProject\", async (tx) => {\n const data = await tx.getResourceData(projectListRid, true);\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const projectId = resourceIdToString(f.value);\n if (projectId === identifier) {\n return { id: projectId, rid: f.value, fieldName: f.name };\n }\n }\n // Fallback: match by label\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const metaStr = await tx.getKValueStringIfExists(f.value, ProjectMetaKey);\n if (metaStr) {\n const meta: ProjectMeta = JSON.parse(metaStr);\n if (meta.label === identifier) {\n return { id: resourceIdToString(f.value), rid: f.value, fieldName: f.name };\n }\n }\n }\n\n throw new Error(`Project \"${identifier}\" not found (searched by id and label).`);\n });\n}\n\n/** Read all project labels within an existing transaction. */\nexport async function getExistingLabelsInTx(\n tx: PlTransaction,\n projectListRid: SignedResourceId,\n): Promise<string[]> {\n const data = await tx.getResourceData(projectListRid, true);\n const labels: string[] = [];\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const metaStr = await tx.getKValueStringIfExists(f.value, ProjectMetaKey);\n if (metaStr) {\n const meta: ProjectMeta = JSON.parse(metaStr);\n labels.push(meta.label);\n }\n }\n return labels;\n}\n\n/** Get all project labels from a project list. */\nexport async function getProjectLabels(\n pl: PlClient,\n projectListRid: SignedResourceId,\n): Promise<string[]> {\n return await pl.withReadTx(\"getProjectLabels\", async (tx) => {\n return getExistingLabelsInTx(tx, projectListRid);\n });\n}\n\n/**\n * Deduplicates a project name against existing labels.\n * \"X\" → \"X (Copy)\" → \"X (Copy 2)\" → ...\n */\nexport function deduplicateName(baseName: string, existingLabels: string[]): string {\n let candidate = `${baseName} (Copy)`;\n let i = 2;\n while (existingLabels.includes(candidate)) {\n candidate = `${baseName} (Copy ${i})`;\n i++;\n }\n return candidate;\n}\n\n/** Rename a project (update its label). */\nexport async function renameProject(\n pl: PlClient,\n projectRid: SignedResourceId,\n newLabel: string,\n): Promise<void> {\n await pl.withWriteTx(\"renameProject\", async (tx) => {\n const metaStr = await tx.getKValueString(projectRid, ProjectMetaKey);\n const meta: ProjectMeta = JSON.parse(metaStr);\n const updated: ProjectMeta = { ...meta, label: newLabel };\n tx.setKValue(projectRid, ProjectMetaKey, JSON.stringify(updated));\n tx.setKValue(projectRid, ProjectLastModifiedTimestamp, String(Date.now()));\n await tx.commit();\n });\n}\n\n/** Delete a project from the project list. */\nexport async function deleteProject(\n pl: PlClient,\n projectListRid: SignedResourceId,\n fieldName: string,\n): Promise<void> {\n await pl.withWriteTx(\"deleteProject\", async (tx) => {\n tx.removeField(field(projectListRid, fieldName));\n await tx.commit();\n });\n}\n\n/** One project moved by {@link moveProjects}, as it ended up in the target root. */\nexport interface MovedProject {\n id: string;\n /** Label the project had in the source root. */\n sourceLabel: string;\n /** Label it carries in the target root — differs when the name collided and was deduplicated. */\n targetLabel: string;\n}\n\n/**\n * Re-attaches projects from one user's project list to another's, keeping the same project\n * resources — no copy is made, so nothing is duplicated and no data is rewritten.\n *\n * This works across roots because the backend permits a reference between differently coloured\n * resources when the caller holds write access to both, which admin credentials do. Names that\n * collide in the target are deduplicated the way {@link duplicateProject} callers deduplicate\n * theirs, so a move never silently shadows a project the target user already has.\n *\n * The whole batch is one transaction: either every project lands in the target root, or none\n * moves and both roots are untouched.\n */\nexport async function moveProjects(\n pl: PlClient,\n sourceProjectListRid: SignedResourceId,\n targetProjectListRid: SignedResourceId,\n): Promise<MovedProject[]> {\n return await pl.withWriteTx(\"moveProjects\", async (tx) => {\n // Read here rather than taken from the caller: a list read before an operator answered a\n // confirmation prompt describes the account as it was minutes ago, and a project attached\n // since then would be left on the source root — where the account deletion that follows\n // destroys it. Moving what this transaction sees narrows that to the transaction itself.\n const projects = await listProjectIdentitiesInTx(tx, sourceProjectListRid);\n if (projects.length === 0) return [];\n\n const takenLabels = await getExistingLabelsInTx(tx, targetProjectListRid);\n const moved: MovedProject[] = [];\n\n for (const project of projects) {\n const metaStr = await tx.getKValueString(project.rid, ProjectMetaKey);\n const meta: ProjectMeta = JSON.parse(metaStr);\n const sourceLabel = meta.label;\n\n let targetLabel = sourceLabel;\n if (takenLabels.includes(targetLabel)) {\n targetLabel = deduplicateName(sourceLabel, takenLabels);\n tx.setKValue(project.rid, ProjectMetaKey, JSON.stringify({ ...meta, label: targetLabel }));\n tx.setKValue(project.rid, ProjectLastModifiedTimestamp, String(Date.now()));\n }\n // Reserved even when the label was free, so two source projects with the same name do not\n // both keep it.\n takenLabels.push(targetLabel);\n\n // Attached to the target before being detached from the source: the project keeps a\n // reference throughout, so it is never momentarily unreferenced.\n tx.createField(field(targetProjectListRid, randomUUID()), \"Dynamic\", project.rid);\n tx.removeField(field(sourceProjectListRid, project.fieldName));\n\n moved.push({ id: project.id, sourceLabel, targetLabel });\n }\n\n await tx.commit();\n return moved;\n });\n}\n\n/** Get the project list ResourceId for the connected user. */\nexport async function getProjectListRid(pl: PlClient): Promise<SignedResourceId> {\n return await pl.withReadTx(\"getProjectList\", async (tx) => {\n const fieldData = await tx.getField({\n resourceId: tx.clientRoot,\n fieldName: ProjectsField,\n });\n if (isNullSignedResourceId(fieldData.value)) {\n throw new Error(\"No project list found for this user.\");\n }\n return fieldData.value;\n });\n}\n\n/**\n * Resolves a user's root and, if they have one, their project list.\n *\n * Unlike {@link navigateToUserRoot} a missing project list is not an error here: a user who has\n * never opened the app has a root and no list, and that account is still a legitimate target for\n * whole-account operations. Callers that need a list to write into use\n * {@link ensureUserProjectList}.\n */\nexport async function openUserRoot(\n pl: PlClient,\n username: string,\n): Promise<{ userRoot: SignedResourceId; projectListRid: SignedResourceId | undefined }> {\n let userRoot: SignedResourceId | undefined;\n try {\n userRoot = await pl.getUserRoot({ login: username });\n } catch (e) {\n // The backend reports an unknown login as NOT_FOUND on the root, which reads as a missing\n // resource rather than a missing user. Name the actual problem.\n if (isNotFoundError(e)) {\n throw new Error(`User \"${username}\" not found on this server.`);\n }\n throw e;\n }\n if (userRoot === undefined) {\n throw new Error(`User \"${username}\" not found on this server (no root resource).`);\n }\n\n return await pl.withReadTx(\"openUserRoot\", async (tx) => {\n const projectsField = await tx.getFieldIfExists(field(userRoot, ProjectsField));\n if (projectsField === undefined || isNullSignedResourceId(projectsField.value)) {\n return { userRoot, projectListRid: undefined };\n }\n return { userRoot, projectListRid: projectsField.value };\n });\n}\n\n/**\n * Returns a user's project list, creating an empty one when the root has none — the same lazy\n * creation the middle layer performs for the signed-in user, but against an impersonated root, so\n * projects can be re-homed to a user who has never opened the app.\n */\nexport async function ensureUserProjectList(\n pl: PlClient,\n userRoot: SignedResourceId,\n): Promise<SignedResourceId> {\n return await pl.withWriteTx(\"ensureUserProjectList\", async (tx) => {\n const projectsField = field(userRoot, ProjectsField);\n tx.createField(projectsField, \"Dynamic\");\n const fieldData = await tx.getField(projectsField);\n if (!isNullSignedResourceId(fieldData.value)) {\n await tx.commit();\n return fieldData.value;\n }\n\n const list = tx.createEphemeral(ProjectsResourceType);\n tx.lock(list);\n tx.setField(projectsField, list);\n await tx.commit();\n return await list.globalId;\n });\n}\n\n/**\n * Navigates to a specific user's project list resource ID.\n * Tries ListUserResources first (new backend), falls back to SHA256 named resource lookup.\n */\nexport async function navigateToUserRoot(\n pl: PlClient,\n username: string,\n): Promise<{ userRoot: SignedResourceId; projectListRid: SignedResourceId }> {\n let userRootRid: SignedResourceId | undefined;\n\n userRootRid = await pl.getUserRoot({ login: username });\n if (userRootRid === undefined) {\n throw new Error(`User \"${username}\" not found on this server (no root resource).`);\n }\n\n // Read the projects field from the resolved user root\n return await pl.withReadTx(\"navigateToUserProjects\", async (tx) => {\n const projectsFieldData = await tx.getField({\n resourceId: userRootRid,\n fieldName: ProjectsField,\n });\n\n if (isNullSignedResourceId(projectsFieldData.value)) {\n throw new Error(`User \"${username}\" has no project list.`);\n }\n\n return { userRoot: userRootRid, projectListRid: projectsFieldData.value };\n });\n}\n\n// Re-export duplicateProject from pl-middle-layer for use in commands\nexport { duplicateProject };\n","export type OutputFormat = \"text\" | \"json\" | \"csv\";\n\n/** Outputs a line of text to stdout. */\nexport function outputText(message: string): void {\n console.log(message);\n}\n\n/** Outputs data as formatted JSON to stdout. */\nexport function outputJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2));\n}\n\n/** Outputs a header row + data rows as RFC-4180-ish CSV to stdout. */\nexport function outputCsv(headers: string[], rows: string[][]): void {\n const esc = (v: string) => (/[\",\\r\\n]/.test(v) ? `\"${v.replace(/\"/g, '\"\"')}\"` : v);\n const lines = [headers, ...rows].map((r) => r.map(esc).join(\",\"));\n console.log(lines.join(\"\\n\"));\n}\n\n/** Formats a table as aligned text columns. */\nexport function formatTable(headers: string[], rows: string[][]): string {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)),\n );\n\n const sep = colWidths.map((w) => \"-\".repeat(w)).join(\" \");\n const headerLine = headers.map((h, i) => h.padEnd(colWidths[i])).join(\" \");\n const dataLines = rows.map((row) =>\n row.map((cell, i) => (cell ?? \"\").padEnd(colWidths[i])).join(\" \"),\n );\n\n return [headerLine, sep, ...dataLines].join(\"\\n\");\n}\n\n/** Formats a Date as a short human-readable string. */\nexport function formatDate(d: Date): string {\n if (d.getTime() === 0) return \"(unknown)\";\n return d\n .toISOString()\n .replace(\"T\", \" \")\n .replace(/\\.\\d+Z$/, \"Z\");\n}\n"],"mappings":";;;;AAqBA,eAAsBA,EAAmB,GAA8C;CACrF,IAAMC,IAAyBC,EAAkBC,EAAK,OAAO;CAG7D,AADIA,EAAK,SAAS,KAAA,MAAW,EAAO,OAAOA,EAAK,OAC5CA,EAAK,aAAa,KAAA,MAAW,EAAO,WAAWA,EAAK;CAExD,IAAMC,IAAS,MAAMC,EAAwB,MAAMJ,CAAM,GACrDK;CAEJ,IAAI,MAAMF,EAAO,YAAY,GAAG;EAC9B,IAAIH,EAAO,SAAS,KAAA,KAAaA,EAAO,aAAa,KAAA,GACnD,MAAU,MACR,0HAEF;EAEF,IAAkB,MAAMG,EAAO,MAAMH,EAAO,MAAMA,EAAO,QAAQ;CACnE,OACE,IAAkB,CAAC;CAGrB,OAAO,MAAMM,EAAS,KAAKN,GAAQ,EAAE,mBAAgB,CAAC;AACxD;AAGA,eAAsBO,EAAwB,GAAiD;CAC7F,IAAMP,IAAyBC,EAAkBC,EAAK,OAAO,GAGvDG,IAAmC,OAAM,MAD1BD,EAAwB,MAAMJ,CAAM,EAAA,CACH,MAAME,EAAK,WAAWA,EAAK,aAAa;CAE9F,OAAO,MAAMI,EAAS,KAAKN,GAAQ,EAAE,mBAAgB,CAAC;AAC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