@platforma-sdk/pl-cli 0.12.17 → 0.13.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.
package/dist/cli.js CHANGED
@@ -1,52 +1,52 @@
1
- import { _ as e, a as t, b as n, c as r, d as i, f as a, g as o, h as s, i as c, l, m as u, n as d, o as f, p, r as m, s as ee, t as h, u as g, v as te, x as _, y as v } from "./output-D41Wn0wM.js";
2
- import { Command as y, InvalidArgumentError as b, Option as x } from "commander";
3
- import { anyResourceIdToBigint as S, asSignedResourceId as ne, createSignedResourceId as re, field as C, isLocalResourceId as w, isNotNullSignedResourceId as T, isPermissionDenied as ie, listRegisteredControllers as E, resourceIdFromString as ae, resourceIdToString as D, resourceType as oe, resourceTypeToString as se } from "@milaboratories/pl-client";
4
- import { randomUUID as O } from "node:crypto";
5
- import { InstanceStatsContextTypeName as k, ProjectMetaKey as A, parseInstanceStats as ce } from "@milaboratories/pl-middle-layer";
6
- import { createInterface as j } from "node:readline";
7
- import { once as le } from "node:events";
1
+ import { _ as e, a as t, b as n, c as r, d as i, f as a, g as o, h as s, i as c, l, m as u, n as d, o as f, p, r as m, s as h, t as g, u as _, v, x as y, y as b } from "./output-D41Wn0wM.js";
2
+ import { Command as x, InvalidArgumentError as S, Option as C } from "commander";
3
+ import { asSignedResourceId as w, createSignedResourceId as T, field as E, isLocalResourceId as D, isNotNullSignedResourceId as O, isPermissionDenied as ee, resourceIdFromString as k, resourceIdToString as A, resourceType as te, resourceTypeToString as j } from "@milaboratories/pl-client";
4
+ import { randomUUID as M } from "node:crypto";
5
+ import { InstanceStatsContextTypeName as ne, ProjectMetaKey as N, parseInstanceStats as re } from "@milaboratories/pl-middle-layer";
6
+ import { createInterface as P } from "node:readline";
7
+ import { once as ie } from "node:events";
8
8
  // src/base_command.ts
9
- async function M(e) {
9
+ async function F(e) {
10
10
  return e.adminUser && e.adminPassword ? n({
11
11
  address: e.address,
12
12
  adminUser: e.adminUser,
13
13
  adminPassword: e.adminPassword
14
- }) : _({
14
+ }) : y({
15
15
  address: e.address,
16
16
  user: e.user,
17
17
  password: e.password
18
18
  });
19
19
  }
20
- async function N(e) {
20
+ async function I(e) {
21
21
  let t = !!e.adminUser, n = !!e.adminPassword, r = !!e.targetUser;
22
22
  if (r && !(t && n)) throw Error("--target-user requires --admin-user and --admin-password");
23
23
  if ((t || n) && !r) throw Error("--admin-user/--admin-password require --target-user for project commands");
24
- let i = await M(e), s;
24
+ let i = await F(e), s;
25
25
  return s = r ? (await o(i, e.targetUser)).projectListRid : await a(i), {
26
26
  pl: i,
27
27
  projectListRid: s
28
28
  };
29
29
  }
30
30
  // src/cmd-opts.ts
31
- function P(e, ...t) {
31
+ function L(e, ...t) {
32
32
  for (let n of t) for (let t of n) e.addOption(t);
33
33
  return e;
34
34
  }
35
- var F = () => [new x("-a, --address <url>", "Platforma server address").env("PL_ADDRESS").makeOptionMandatory()], I = (e = "text", t = ["text", "json"]) => [...F(), new x("-f, --format <format>", "Output format").choices(t).default(e)], L = () => [new x("-u, --user <user>", "Username for authentication").env("PL_USER"), new x("-p, --password <password>", "Password for authentication").env("PL_PASSWORD")], R = () => [new x("--admin-user <user>", "Admin/controller username").env("PL_ADMIN_USER").makeOptionMandatory(), new x("--admin-password <password>", "Admin/controller password").env("PL_ADMIN_PASSWORD").makeOptionMandatory()], z = () => [
36
- new x("--admin-user <user>", "Admin/controller username (enables admin mode)").env("PL_ADMIN_USER"),
37
- new x("--admin-password <password>", "Admin/controller password").env("PL_ADMIN_PASSWORD"),
38
- new x("--target-user <user>", "Operate on this user's data (requires admin credentials)").env("PL_TARGET_USER")
35
+ var R = () => [new C("-a, --address <url>", "Platforma server address").env("PL_ADDRESS").makeOptionMandatory()], z = (e = "text", t = ["text", "json"]) => [...R(), new C("-f, --format <format>", "Output format").choices(t).default(e)], B = () => [new C("-u, --user <user>", "Username for authentication").env("PL_USER"), new C("-p, --password <password>", "Password for authentication").env("PL_PASSWORD")], V = () => [new C("--admin-user <user>", "Admin/controller username").env("PL_ADMIN_USER").makeOptionMandatory(), new C("--admin-password <password>", "Admin/controller password").env("PL_ADMIN_PASSWORD").makeOptionMandatory()], H = () => [
36
+ new C("--admin-user <user>", "Admin/controller username (enables admin mode)").env("PL_ADMIN_USER"),
37
+ new C("--admin-password <password>", "Admin/controller password").env("PL_ADMIN_PASSWORD"),
38
+ new C("--target-user <user>", "Operate on this user's data (requires admin credentials)").env("PL_TARGET_USER")
39
39
  ];
40
40
  // src/cmd/project/list.ts
41
- function B() {
42
- let e = new y("list").description("List all projects for the authenticated user.");
43
- return P(e, I(), L(), z()), e.action(async (e) => {
44
- let { pl: n, projectListRid: r } = await N(e);
41
+ function U() {
42
+ let e = new x("list").description("List all projects for the authenticated user.");
43
+ return L(e, z(), B(), H()), e.action(async (e) => {
44
+ let { pl: n, projectListRid: r } = await I(e);
45
45
  try {
46
46
  let i = await u(n, r);
47
47
  if (e.format === "json") c(i.map((e) => ({
48
48
  id: e.id,
49
- rid: D(e.rid),
49
+ rid: A(e.rid),
50
50
  label: e.label,
51
51
  created: e.created.toISOString(),
52
52
  lastModified: e.lastModified.toISOString()
@@ -64,10 +64,10 @@ function B() {
64
64
  "LAST MODIFIED"
65
65
  ], i.map((e) => [
66
66
  e.id,
67
- D(e.rid),
67
+ A(e.rid),
68
68
  e.label,
69
- h(e.created),
70
- h(e.lastModified)
69
+ g(e.created),
70
+ g(e.lastModified)
71
71
  ]))), t(`\n${i.length} project(s)`);
72
72
  }
73
73
  } finally {
@@ -76,15 +76,15 @@ function B() {
76
76
  }), e;
77
77
  }
78
78
  // src/cmd/project/info.ts
79
- function V() {
80
- let e = new y("info").description("Show detailed information about a project.");
81
- return e.argument("<project>", "Project ID or label"), P(e, I(), L(), z()), e.action(async (e, n) => {
82
- let { pl: r, projectListRid: a } = await N(n);
79
+ function W() {
80
+ let e = new x("info").description("Show detailed information about a project.");
81
+ return e.argument("<project>", "Project ID or label"), L(e, z(), B(), H()), e.action(async (e, n) => {
82
+ let { pl: r, projectListRid: a } = await I(n);
83
83
  try {
84
- let { id: o, rid: s } = await v(r, a, e), l = await i(r, o, s);
84
+ let { id: o, rid: s } = await b(r, a, e), l = await i(r, o, s);
85
85
  if (n.format === "json") c({
86
86
  id: l.id,
87
- rid: D(l.rid),
87
+ rid: A(l.rid),
88
88
  label: l.label,
89
89
  schemaVersion: l.schemaVersion,
90
90
  blockCount: l.blockCount,
@@ -93,8 +93,8 @@ function V() {
93
93
  lastModified: l.lastModified.toISOString()
94
94
  });
95
95
  else {
96
- if (t(`Project: ${l.label}`), t(`ID: ${l.id}`), t(`RID: ${D(l.rid)}`), t(`Schema: ${l.schemaVersion ?? "(unknown)"}`), t(`Blocks: ${l.blockCount}`), l.blockIds.length > 0) for (let e of l.blockIds) t(` - ${e}`);
97
- t(`Created: ${h(l.created)}`), t(`Last Modified: ${h(l.lastModified)}`);
96
+ if (t(`Project: ${l.label}`), t(`ID: ${l.id}`), t(`RID: ${A(l.rid)}`), t(`Schema: ${l.schemaVersion ?? "(unknown)"}`), t(`Blocks: ${l.blockCount}`), l.blockIds.length > 0) for (let e of l.blockIds) t(` - ${e}`);
97
+ t(`Created: ${g(l.created)}`), t(`Last Modified: ${g(l.lastModified)}`);
98
98
  }
99
99
  } finally {
100
100
  await r.close();
@@ -102,29 +102,29 @@ function V() {
102
102
  }), e;
103
103
  }
104
104
  // src/cmd/project/duplicate.ts
105
- function H() {
106
- let e = new y("duplicate").description("Duplicate a project within the same user. Auto-renames on collision by default.");
107
- return e.argument("<project>", "Project ID or label"), P(e, I(), L(), z()), e.option("-n, --name <name>", "Name for the duplicate"), e.addOption(new x("--auto-rename", "Auto-rename on collision (default: true)").default(!0)), e.option("--no-auto-rename", "Fail on name collision instead of auto-renaming"), e.action(async (e, n) => {
108
- let { pl: i, projectListRid: a } = await N(n);
105
+ function G() {
106
+ let e = new x("duplicate").description("Duplicate a project within the same user. Auto-renames on collision by default.");
107
+ return e.argument("<project>", "Project ID or label"), L(e, z(), B(), H()), e.option("-n, --name <name>", "Name for the duplicate"), e.addOption(new C("--auto-rename", "Auto-rename on collision (default: true)").default(!0)), e.option("--no-auto-rename", "Fail on name collision instead of auto-renaming"), e.action(async (e, n) => {
108
+ let { pl: i, projectListRid: a } = await I(n);
109
109
  try {
110
- let { rid: o } = await v(i, a, e), s = O(), l = await i.withWriteTx("duplicateProject", async (e) => {
111
- let t = await e.getKValueString(o, A), i = JSON.parse(t).label, c = await g(e, a), l;
110
+ let { rid: o } = await b(i, a, e), s = M(), l = await i.withWriteTx("duplicateProject", async (e) => {
111
+ let t = await e.getKValueString(o, N), i = JSON.parse(t).label, c = await _(e, a), l;
112
112
  if (n.name) {
113
113
  if (!n.autoRename && c.includes(n.name)) throw Error(`Project name "${n.name}" already exists.`);
114
114
  l = c.includes(n.name) ? f(n.name, c) : n.name;
115
115
  } else l = f(i, c);
116
116
  let u = await r(e, o, { label: l });
117
- e.createField(C(a, s), "Dynamic", u), await e.commit();
117
+ e.createField(E(a, s), "Dynamic", u), await e.commit();
118
118
  let d = await u.globalId;
119
119
  return {
120
- id: D(d),
120
+ id: A(d),
121
121
  rid: d,
122
122
  label: l
123
123
  };
124
124
  });
125
125
  n.format === "json" ? c({
126
126
  id: l.id,
127
- rid: D(l.rid),
127
+ rid: A(l.rid),
128
128
  label: l.label
129
129
  }) : t(`Duplicated project as "${l.label}" (id: ${l.id})`);
130
130
  } finally {
@@ -133,15 +133,15 @@ function H() {
133
133
  }), e;
134
134
  }
135
135
  // src/cmd/project/rename.ts
136
- function U() {
137
- let e = new y("rename").description("Rename a project.");
138
- return e.argument("<project>", "Project ID or label"), P(e, I(), L(), z()), e.addOption(new x("-n, --name <name>", "New name for the project").makeOptionMandatory()), e.action(async (e, n) => {
139
- let { pl: r, projectListRid: i } = await N(n);
136
+ function K() {
137
+ let e = new x("rename").description("Rename a project.");
138
+ return e.argument("<project>", "Project ID or label"), L(e, z(), B(), H()), e.addOption(new C("-n, --name <name>", "New name for the project").makeOptionMandatory()), e.action(async (e, n) => {
139
+ let { pl: r, projectListRid: i } = await I(n);
140
140
  try {
141
- let { id: a, rid: o } = await v(r, i, e);
142
- await te(r, o, n.name), n.format === "json" ? c({
141
+ let { id: a, rid: o } = await b(r, i, e);
142
+ await v(r, o, n.name), n.format === "json" ? c({
143
143
  id: a,
144
- rid: D(o),
144
+ rid: A(o),
145
145
  label: n.name
146
146
  }) : t(`Renamed project to "${n.name}"`);
147
147
  } finally {
@@ -150,14 +150,14 @@ function U() {
150
150
  }), e;
151
151
  }
152
152
  // src/cmd/project/delete.ts
153
- function W() {
154
- let e = new y("delete").description("Delete a project. This permanently destroys all project data.");
155
- return e.argument("<project>", "Project ID or label"), P(e, I(), L(), z()), e.option("--force", "Skip confirmation", !1), e.action(async (e, n) => {
156
- let { pl: r, projectListRid: a } = await N(n);
153
+ function q() {
154
+ let e = new x("delete").description("Delete a project. This permanently destroys all project data.");
155
+ return e.argument("<project>", "Project ID or label"), L(e, z(), B(), H()), e.option("--force", "Skip confirmation", !1), e.action(async (e, n) => {
156
+ let { pl: r, projectListRid: a } = await I(n);
157
157
  try {
158
- let { id: o, rid: s, fieldName: l } = await v(r, a, e), u = await i(r, o, s);
158
+ let { id: o, rid: s, fieldName: l } = await b(r, a, e), u = await i(r, o, s);
159
159
  if (!n.force) {
160
- let e = j({
160
+ let e = P({
161
161
  input: process.stdin,
162
162
  output: process.stderr
163
163
  });
@@ -172,7 +172,7 @@ function W() {
172
172
  e.close();
173
173
  }
174
174
  }
175
- await ee(r, a, l), n.format === "json" ? c({
175
+ await h(r, a, l), n.format === "json" ? c({
176
176
  deleted: !0,
177
177
  id: o,
178
178
  label: u.label
@@ -183,53 +183,53 @@ function W() {
183
183
  }), e;
184
184
  }
185
185
  // src/cmd/admin/copy-project.ts
186
- function ue() {
187
- let e = new y("copy-project").description("Copy a project from one user to another. Requires admin/controller credentials.");
188
- return P(e, I(), R()), e.addOption(new x("--source-user <user>", "Username of the source project owner").makeOptionMandatory()), e.addOption(new x("--source-project <project>", "Source project ID or label").makeOptionMandatory()), e.option("--target-user <user>", "Username of the target user (defaults to source-user for same-user copy)"), e.option("-n, --name <name>", "Name for the copied project"), e.addOption(new x("--auto-rename", "Auto-rename on collision (default: true)").default(!0)), e.option("--no-auto-rename", "Fail on name collision instead of auto-renaming"), e.action(async (e) => {
189
- let n = await M(e);
186
+ function J() {
187
+ let e = new x("copy-project").description("Copy a project from one user to another. Requires admin/controller credentials.");
188
+ return L(e, z(), V()), e.addOption(new C("--source-user <user>", "Username of the source project owner").makeOptionMandatory()), e.addOption(new C("--source-project <project>", "Source project ID or label").makeOptionMandatory()), e.option("--target-user <user>", "Username of the target user (defaults to source-user for same-user copy)"), e.option("-n, --name <name>", "Name for the copied project"), e.addOption(new C("--auto-rename", "Auto-rename on collision (default: true)").default(!0)), e.option("--no-auto-rename", "Fail on name collision instead of auto-renaming"), e.action(async (e) => {
189
+ let n = await F(e);
190
190
  try {
191
- let i = e.targetUser ?? e.sourceUser, a = await o(n, e.sourceUser), { rid: s } = await v(n, a.projectListRid, e.sourceProject), l = i === e.sourceUser ? a : await o(n, i), u = O(), d = await n.withWriteTx("adminCopyProject", async (t) => {
192
- let n = await t.getKValueString(s, A), i = JSON.parse(n).label, a = await g(t, l.projectListRid), o = e.name ?? i;
191
+ let i = e.targetUser ?? e.sourceUser, a = await o(n, e.sourceUser), { rid: s } = await b(n, a.projectListRid, e.sourceProject), l = i === e.sourceUser ? a : await o(n, i), u = M(), d = await n.withWriteTx("adminCopyProject", async (t) => {
192
+ let n = await t.getKValueString(s, N), i = JSON.parse(n).label, a = await _(t, l.projectListRid), o = e.name ?? i;
193
193
  if (a.includes(o)) {
194
194
  if (!e.autoRename) throw Error(`Project name "${o}" already exists for target user.`);
195
195
  o = f(e.name ?? i, a);
196
196
  }
197
197
  let c = await r(t, s, { label: o });
198
- t.createField(C(l.projectListRid, u), "Dynamic", c), await t.commit();
198
+ t.createField(E(l.projectListRid, u), "Dynamic", c), await t.commit();
199
199
  let d = await c.globalId;
200
200
  return {
201
- id: D(d),
201
+ id: A(d),
202
202
  rid: d,
203
203
  label: o
204
204
  };
205
205
  });
206
206
  e.format === "json" ? c({
207
207
  id: d.id,
208
- rid: D(d.rid),
208
+ rid: A(d.rid),
209
209
  label: d.label,
210
210
  sourceUser: e.sourceUser,
211
211
  targetUser: i
212
- }) : t(`Copied project from ${e.sourceUser} to ${i} as "${d.label}" (id: ${d.id}, rid: ${D(d.rid)})`);
212
+ }) : t(`Copied project from ${e.sourceUser} to ${i} as "${d.label}" (id: ${d.id}, rid: ${A(d.rid)})`);
213
213
  } finally {
214
214
  await n.close();
215
215
  }
216
216
  }), e;
217
217
  }
218
218
  // src/cmd/admin/user-list.ts
219
- function de() {
220
- let e = new y("user-list").description("List all known users' logins from a live server. Requires admin/controller credentials.");
221
- return P(e, I("csv", [
219
+ function Y() {
220
+ let e = new x("user-list").description("List all known users' logins from a live server. Requires admin/controller credentials.");
221
+ return L(e, z("csv", [
222
222
  "text",
223
223
  "json",
224
224
  "csv"
225
- ]), R()), e.action(async (e) => {
226
- let n = await M(e);
225
+ ]), V()), e.action(async (e) => {
226
+ let n = await F(e);
227
227
  try {
228
228
  let r;
229
229
  try {
230
230
  r = await n.listUsers();
231
231
  } catch (e) {
232
- throw ie(e) ? Error("The server does not let this user list users. Check the server option '--show-user-list-to' and the role of the user.", { cause: e }) : e;
232
+ throw ee(e) ? Error("The server does not let this user list users. Check the server option '--show-user-list-to' and the role of the user.", { cause: e }) : e;
233
233
  }
234
234
  let i = r.map((e) => e.login).sort();
235
235
  e.format === "json" ? c(i) : e.format === "text" ? t(i.join("\n")) : m(["login"], i.map((e) => [e]));
@@ -239,17 +239,17 @@ function de() {
239
239
  }), e;
240
240
  }
241
241
  // src/cmd/admin/delete-user.ts
242
- function fe() {
243
- let n = new y("delete-user").description("Delete a user account. Optionally re-homes the user's projects to another user first. Requires admin/controller credentials.");
244
- return n.argument("<user>", "Username of the account to delete"), P(n, I(), R()), n.addOption(new x("--move-projects-to <user>", "Re-home the deleted user's projects to this user before deleting the account")), n.addOption(new x("--delete-projects", "Delete the user's projects along with the account, losing their data")), n.option("--force", "Skip confirmation", !1), n.action(async (n, r) => {
242
+ function ae() {
243
+ let n = new x("delete-user").description("Delete a user account. Optionally re-homes the user's projects to another user first. Requires admin/controller credentials.");
244
+ return n.argument("<user>", "Username of the account to delete"), L(n, z(), V()), n.addOption(new C("--move-projects-to <user>", "Re-home the deleted user's projects to this user before deleting the account")), n.addOption(new C("--delete-projects", "Delete the user's projects along with the account, losing their data")), n.option("--force", "Skip confirmation", !1), n.action(async (n, r) => {
245
245
  if (r.moveProjectsTo && r.deleteProjects) throw Error("--move-projects-to and --delete-projects are mutually exclusive");
246
246
  if (r.moveProjectsTo === n) throw Error("--move-projects-to must name a different user than the one being deleted");
247
247
  if (r.adminUser === n) throw Error(`Refusing to delete "${n}" — it is the account these credentials authenticate as.`);
248
- let i = await M(r);
248
+ let i = await F(r);
249
249
  try {
250
250
  let a = await e(i, n), o = a.projectListRid === void 0 ? [] : await p(i, a.projectListRid);
251
251
  if (o.length > 0 && !r.moveProjectsTo && !r.deleteProjects) throw Error(`User "${n}" owns ${o.length} project(s). Pass --move-projects-to <user> to re-home them, or --delete-projects to delete them with the account.`);
252
- if (!await me(n, o, r)) {
252
+ if (!await se(n, o, r)) {
253
253
  t("Aborted.");
254
254
  return;
255
255
  }
@@ -259,7 +259,7 @@ function fe() {
259
259
  u = await s(i, a.projectListRid, n);
260
260
  }
261
261
  let d = a.projectListRid === void 0 ? [] : await p(i, a.projectListRid);
262
- pe(n, r, o, d);
262
+ oe(n, r, o, d);
263
263
  let f = await i.deleteUser(n);
264
264
  r.format === "json" ? c({
265
265
  deleted: !0,
@@ -271,13 +271,13 @@ function fe() {
271
271
  userRootDeleted: f.userRootDeleted,
272
272
  revokedGrants: f.revokedGrants,
273
273
  removedIdentityIndexEntries: f.removedIdentityIndexEntries
274
- }) : t(he(n, r.moveProjectsTo, u, d));
274
+ }) : t(ce(n, r.moveProjectsTo, u, d));
275
275
  } finally {
276
276
  await i.close();
277
277
  }
278
278
  }), n;
279
279
  }
280
- function pe(e, t, n, r) {
280
+ function oe(e, t, n, r) {
281
281
  if (t.moveProjectsTo) {
282
282
  if (r.length === 0) return;
283
283
  throw Error(`User "${e}" still owns ${r.length} project(s) after the move: ${r.map((e) => e.label).join(", ")}. The account was NOT deleted — the projects were attached while the move ran. Re-run the command to move them too.`);
@@ -285,11 +285,11 @@ function pe(e, t, n, r) {
285
285
  let i = new Set(n.map((e) => e.id)), a = r.filter((e) => !i.has(e.id));
286
286
  if (a.length !== 0) throw Error(`User "${e}" gained ${a.length} project(s) since the list you confirmed: ${a.map((e) => e.label).join(", ")}. The account was NOT deleted — deleting it now would destroy them unreviewed. Re-run the command to see the current list.`);
287
287
  }
288
- async function me(e, t, n) {
288
+ async function se(e, t, n) {
289
289
  if (n.force) return !0;
290
290
  let r = n.moveProjectsTo ? `${t.length} project(s) will move to "${n.moveProjectsTo}"` : t.length > 0 ? `${t.length} project(s) will be PERMANENTLY DELETED` : "the account owns no projects";
291
291
  process.stderr.write(`Delete user "${e}"? ${r}.\n`), t.length > 0 && process.stderr.write(t.map((e) => ` - ${e.label}`).join("\n") + "\n");
292
- let i = j({
292
+ let i = P({
293
293
  input: process.stdin,
294
294
  output: process.stderr
295
295
  });
@@ -301,7 +301,7 @@ async function me(e, t, n) {
301
301
  i.close();
302
302
  }
303
303
  }
304
- function he(e, t, n, r) {
304
+ function ce(e, t, n, r) {
305
305
  let i = [];
306
306
  return t ? n.length > 0 ? (i.push(`Moved ${n.length} project(s) from ${e} to ${t}:`), i.push(d([
307
307
  "id",
@@ -314,33 +314,33 @@ function he(e, t, n, r) {
314
314
  ])))) : i.push(`User ${e} had no projects to move.`) : r.length > 0 && (i.push(`Deleted ${r.length} project(s) belonging to ${e}:`), i.push(r.map((e) => ` - ${e.label}`).join("\n"))), i.push(`Deleted user "${e}".`), i.join("\n");
315
315
  }
316
316
  // src/cmd/admin/instance-stats.ts
317
- function G() {
318
- let e = new y("instance-stats").description("Show the instance statistics as JSON.");
319
- return P(e, I(), R()), e.action(async (e) => {
320
- let t = await M(e);
317
+ function le() {
318
+ let e = new x("instance-stats").description("Show the instance statistics as JSON.");
319
+ return L(e, z(), V()), e.action(async (e) => {
320
+ let t = await F(e);
321
321
  try {
322
- let [e] = await t.listSharedResourcesByType(k);
322
+ let [e] = await t.listSharedResourcesByType(ne);
323
323
  if (e === void 0) throw Error("The instance has no instance statistics.");
324
324
  let n = await t.withReadTx("instanceStats", (t) => t.listKeyValuesString(e));
325
- c(ce(n));
325
+ c(re(n));
326
326
  } finally {
327
327
  await t.close();
328
328
  }
329
329
  }), e;
330
330
  }
331
331
  // src/resource_id.ts
332
- function K(e) {
332
+ function X(e) {
333
333
  let t = e.trim();
334
- if (t.includes("|")) return ne(t);
335
- let n = ae(t);
336
- if (n === void 0 && /^\d+$/.test(t) && (n = BigInt(t)), n === void 0 || n === 0n || w(n)) throw Error(`not a global resource ID: ${e}`);
337
- return re(n);
334
+ if (t.includes("|")) return w(t);
335
+ let n = k(t);
336
+ if (n === void 0 && /^\d+$/.test(t) && (n = BigInt(t)), n === void 0 || n === 0n || D(n)) throw Error(`not a global resource ID: ${e}`);
337
+ return T(n);
338
338
  }
339
339
  // src/cmd/maintenance/list-resources.ts
340
- function ge() {
341
- let e = new y("list-resources").description("List resources of one type as JSON lines, in ascending order of resource ID. Resource data and key-value values are printed as JSON when they are valid JSON, as text when they are valid UTF-8, and as {\"base64\": ...} in other cases. Requires admin/controller credentials.");
342
- return P(e, F(), R()), e.addOption(new x("--type <name:version>", "Resource type to list (e.g. 'Blob/work:1')").argParser(ye).makeOptionMandatory()), e.addOption(new x("--limit <n>", "Maximum number of resources to list. 0 lists all resources").argParser(be).default(0)), e.addOption(new x("--after <resource-id>", "List only resources with IDs greater than this ID. To get the next page, give the ID of the last resource of the previous page").argParser(K)), e.option("--load-fields", "Load the fields and the error of each resource ('fields' and 'error' keys)", !1), e.option("--load-kv", "Load the key-value entries of each resource ('kv' key)", !1), e.action(async (e) => {
343
- let t = await M(e);
340
+ function ue() {
341
+ let e = new x("list-resources").description("List resources of one type as JSON lines, in ascending order of resource ID. Resource data and key-value values are printed as JSON when they are valid JSON, as text when they are valid UTF-8, and as {\"base64\": ...} in other cases. Requires admin/controller credentials.");
342
+ return L(e, R(), V()), e.addOption(new C("--type <name:version>", "Resource type to list (e.g. 'Blob/work:1')").argParser(pe).makeOptionMandatory()), e.addOption(new C("--limit <n>", "Maximum number of resources to list. 0 lists all resources").argParser(me).default(0)), e.addOption(new C("--after <resource-id>", "List only resources with IDs greater than this ID. To get the next page, give the ID of the last resource of the previous page").argParser(X)), e.option("--load-fields", "Load the fields and the error of each resource ('fields' and 'error' keys)", !1), e.option("--load-kv", "Load the key-value entries of each resource ('kv' key)", !1), e.action(async (e) => {
343
+ let t = await F(e);
344
344
  try {
345
345
  let n = await t.withReadTx("listResources", async (t) => {
346
346
  let n = await t.listResourcesByType(e.type, {
@@ -354,46 +354,46 @@ function ge() {
354
354
  })));
355
355
  });
356
356
  for (let { resource: t, kv: r } of n) {
357
- let n = JSON.stringify(_e(t, e.loadFields, r)) + "\n";
358
- process.stdout.write(n) || await le(process.stdout, "drain");
357
+ let n = JSON.stringify(de(t, e.loadFields, r)) + "\n";
358
+ process.stdout.write(n) || await ie(process.stdout, "drain");
359
359
  }
360
360
  } finally {
361
361
  await t.close();
362
362
  }
363
363
  }), e;
364
364
  }
365
- function _e(e, t, n) {
365
+ function de(e, t, n) {
366
366
  return {
367
- id: D(e.id),
368
- type: se(e.type),
367
+ id: A(e.id),
368
+ type: j(e.type),
369
369
  kind: e.kind,
370
- originalId: q(e.originalResourceId),
370
+ originalId: Z(e.originalResourceId),
371
371
  inputsLocked: e.inputsLocked,
372
372
  outputsLocked: e.outputsLocked,
373
373
  ready: e.resourceReady,
374
374
  final: e.final,
375
- data: e.data === void 0 || e.data.length === 0 ? null : J(e.data),
375
+ data: e.data === void 0 || e.data.length === 0 ? null : Q(e.data),
376
376
  ...t ? {
377
- error: q(e.error),
378
- fields: e.fields.map(ve)
377
+ error: Z(e.error),
378
+ fields: e.fields.map(fe)
379
379
  } : {},
380
- ...n === void 0 ? {} : { kv: Object.fromEntries(n.map((e) => [e.key, J(e.value)])) }
380
+ ...n === void 0 ? {} : { kv: Object.fromEntries(n.map((e) => [e.key, Q(e.value)])) }
381
381
  };
382
382
  }
383
- function ve(e) {
383
+ function fe(e) {
384
384
  return {
385
385
  name: e.name,
386
386
  type: e.type,
387
387
  status: e.status,
388
- value: q(e.value),
389
- error: q(e.error),
388
+ value: Z(e.value),
389
+ error: Z(e.error),
390
390
  valueIsFinal: e.valueIsFinal
391
391
  };
392
392
  }
393
- function q(e) {
394
- return T(e) ? D(e) : null;
393
+ function Z(e) {
394
+ return O(e) ? A(e) : null;
395
395
  }
396
- function J(e) {
396
+ function Q(e) {
397
397
  let t;
398
398
  try {
399
399
  t = new TextDecoder("utf-8", { fatal: !0 }).decode(e);
@@ -406,28 +406,28 @@ function J(e) {
406
406
  return t;
407
407
  }
408
408
  }
409
- function ye(e) {
409
+ function pe(e) {
410
410
  let t = e.lastIndexOf(":");
411
- if (t <= 0 || t === e.length - 1) throw new b(`expected <name>:<version>, e.g. 'Blob/work:1': ${e}`);
412
- return oe(e.slice(0, t), e.slice(t + 1));
411
+ if (t <= 0 || t === e.length - 1) throw new S(`expected <name>:<version>, e.g. 'Blob/work:1': ${e}`);
412
+ return te(e.slice(0, t), e.slice(t + 1));
413
413
  }
414
- function be(e) {
414
+ function me(e) {
415
415
  let t = Number(e);
416
- if (!Number.isInteger(t) || t < 0) throw new b(`not a non-negative integer: ${e}`);
416
+ if (!Number.isInteger(t) || t < 0) throw new S(`not a non-negative integer: ${e}`);
417
417
  return t;
418
418
  }
419
419
  // src/cmd/maintenance/set-resource-error.ts
420
- var xe = "Manual error set by administrator to trigger blocks re-run. Run block once again to get rid of it.";
421
- function Se() {
422
- let e = new y("set-resource-error").description("Put an error on one or more resources in a single transaction. Resources that already have an error are skipped. Requires admin/controller credentials.");
423
- return e.argument("<resource-id...>", "Resource IDs: as printed by the server (NG:0x1A2B), as decimal numbers, or as signed IDs (<decimal ID>|<signature hex>)"), P(e, F(), R()), e.addOption(new x("-m, --error-message <message>", "Error message to put on the resources").default(xe)), e.option("--skip-missing", "Skip resources that do not exist instead of failing the whole transaction", !1), e.action(async (e, n) => {
424
- let r = e.map(K), i = await M(n);
420
+ var he = "Manual error set by administrator to trigger blocks re-run. Run block once again to get rid of it.";
421
+ function ge() {
422
+ let e = new x("set-resource-error").description("Put an error on one or more resources in a single transaction. Resources that already have an error are skipped. Requires admin/controller credentials.");
423
+ return e.argument("<resource-id...>", "Resource IDs: as printed by the server (NG:0x1A2B), as decimal numbers, or as signed IDs (<decimal ID>|<signature hex>)"), L(e, R(), V()), e.addOption(new C("-m, --error-message <message>", "Error message to put on the resources").default(he)), e.option("--skip-missing", "Skip resources that do not exist instead of failing the whole transaction", !1), e.action(async (e, n) => {
424
+ let r = e.map(X), i = await F(n);
425
425
  try {
426
426
  let e = await i.withWriteTx("setResourceError", async (e) => {
427
427
  let t = await Promise.all(r.map(async (t) => ({
428
428
  id: t,
429
429
  data: n.skipMissing ? await e.getResourceDataIfExists(t, !0) : await e.getResourceData(t, !0, !0)
430
- }))), i = t.filter((e) => e.data === void 0).map((e) => e.id), a = t.flatMap((e) => e.data === void 0 ? [] : [e.data]), o = a.filter((e) => !T(e.error)), s = a.filter((e) => T(e.error));
430
+ }))), i = t.filter((e) => e.data === void 0).map((e) => e.id), a = t.flatMap((e) => e.data === void 0 ? [] : [e.data]), o = a.filter((e) => !O(e.error)), s = a.filter((e) => O(e.error));
431
431
  if (o.length > 0) {
432
432
  let t = e.createError(n.errorMessage);
433
433
  for (let n of o) e.setResourceError(n.id, t);
@@ -439,111 +439,28 @@ function Se() {
439
439
  missing: i
440
440
  };
441
441
  });
442
- for (let n of e.missing) t(`skipped ${D(n)}: resource does not exist`);
443
- for (let n of e.skipped) t(`skipped ${D(n.id)}: resource already has an error`);
444
- for (let n of e.targets) t(`error set ${D(n.id)}`);
442
+ for (let n of e.missing) t(`skipped ${A(n)}: resource does not exist`);
443
+ for (let n of e.skipped) t(`skipped ${A(n.id)}: resource already has an error`);
444
+ for (let n of e.targets) t(`error set ${A(n.id)}`);
445
445
  } finally {
446
446
  await i.close();
447
447
  }
448
448
  }), e;
449
449
  }
450
- // src/cmd/maintenance/controller/fixup_level.ts
451
- var Y = "ctl/ctlsdk/resourcesFixupLevel", X = 4;
452
- async function Z(e, t) {
453
- let n = await e.getControllerKValueIfExists(t, Y);
454
- return n === void 0 ? "not set" : n.length === X ? String(Buffer.from(n).readUInt32BE(0)) : `invalid (${n.length} bytes)`;
455
- }
456
- function Ce(e, t) {
457
- e.setControllerKValue(t, Y, new Uint8Array(X));
458
- }
459
- // src/cmd/maintenance/controller/list.ts
460
- function we() {
461
- let e = new y("list").description("List the controllers registered in the backend, with their IDs and resources fixup levels. Requires admin/controller credentials.");
462
- return P(e, I("text", [
463
- "text",
464
- "json",
465
- "csv"
466
- ]), R()), e.action(async (e) => {
467
- let n = await M(e);
468
- try {
469
- let r = await n.withReadTx("listControllers", async (e) => {
470
- let t = await E(e);
471
- return await Promise.all(t.map(async (t) => ({
472
- id: D(t.id),
473
- type: t.type,
474
- fixupLevel: await Z(e, t.type)
475
- })));
476
- }), i = [
477
- "id",
478
- "type",
479
- "fixup level"
480
- ], a = r.map((e) => [
481
- e.id,
482
- e.type,
483
- e.fixupLevel
484
- ]);
485
- e.format === "json" ? c(r) : e.format === "csv" ? m(i, a) : t(d(i, a));
486
- } finally {
487
- await n.close();
488
- }
489
- }), e;
490
- }
491
- // src/cmd/maintenance/controller/rerun-fixups.ts
492
- function Q(e) {
493
- return (t, n) => [...n ?? [], e(t)];
494
- }
495
- function Te() {
496
- let e = new y("rerun-fixups").description("Set the resources fixup level of the selected controllers to 0 in a single transaction. On its next start, each controller applies all its one-time resources fixups again. Use this after a rollback to a backend version without resources fixups. Select controllers with --controller-name and --controller-id (see 'maintenance controller list'). Requires admin/controller credentials.");
497
- return P(e, F(), R()), e.addOption(new x("--controller-name <type>", "Controller type, as the controller registers it (for example \"File/Manager\"). Repeat the option to select more controllers").argParser(Q((e) => e))), e.addOption(new x("--controller-id <resource-id>", "Controller ID, as 'maintenance controller list' prints it. Repeat the option to select more controllers").argParser(Q(K))), e.action(async (e) => {
498
- let n = e.controllerName ?? [], r = e.controllerId ?? [];
499
- if (n.length === 0 && r.length === 0) throw Error("select at least one controller with --controller-name or --controller-id");
500
- let i = await M(e);
501
- try {
502
- let e = await i.withWriteTx("rerunControllerFixups", async (e) => {
503
- let t = await Ee(e, n, r), i = await Promise.all(t.map(async (t) => ({
504
- controller: t,
505
- level: await Z(e, t.type)
506
- })));
507
- for (let n of t) Ce(e, n.type);
508
- return await e.commit(), i;
509
- });
510
- for (let { controller: n, level: r } of e) t(`${n.type} (${D(n.id)}): resources fixup level ${r} -> 0`);
511
- t("Restart the backend to apply the resources fixups.");
512
- } finally {
513
- await i.close();
514
- }
515
- }), e;
516
- }
517
- async function Ee(e, t, n) {
518
- let r = await E(e), i = /* @__PURE__ */ new Map();
519
- for (let e of t) {
520
- let t = r.find((t) => t.type === e);
521
- if (t === void 0) throw Error(`controller "${e}" is not registered`);
522
- i.set(t.type, t);
523
- }
524
- for (let e of n) {
525
- let t = S(e), n = r.find((e) => S(e.id) === t);
526
- if (n === void 0) throw Error(`no registered controller has ID ${D(e)}`);
527
- i.set(n.type, n);
528
- }
529
- return [...i.values()];
530
- }
531
450
  // src/cli.ts
532
451
  function $() {
533
- let e = new y();
452
+ let e = new x();
534
453
  e.name("pl-cli").description("Platforma command-line client");
535
- let t = new y("project").description("Manage projects");
536
- t.addCommand(B()), t.addCommand(V()), t.addCommand(H()), t.addCommand(U()), t.addCommand(W()), e.addCommand(t);
537
- let n = new y("admin").description("Admin operations (requires controller credentials)");
538
- n.addCommand(ue()), n.addCommand(de()), n.addCommand(fe()), n.addCommand(G()), e.addCommand(n);
539
- let r = new y("maintenance").description("Low-level server state repair (requires admin/controller credentials)");
540
- r.addCommand(ge()), r.addCommand(Se());
541
- let i = new y("controller").description("Inspect registered controllers and their resources fixups");
542
- return i.addCommand(we()), i.addCommand(Te()), r.addCommand(i), e.addCommand(r), e;
543
- }
544
- async function De(e = process.argv) {
454
+ let t = new x("project").description("Manage projects");
455
+ t.addCommand(U()), t.addCommand(W()), t.addCommand(G()), t.addCommand(K()), t.addCommand(q()), e.addCommand(t);
456
+ let n = new x("admin").description("Admin operations (requires controller credentials)");
457
+ n.addCommand(J()), n.addCommand(Y()), n.addCommand(ae()), n.addCommand(le()), e.addCommand(n);
458
+ let r = new x("maintenance").description("Low-level server state repair (requires admin/controller credentials)");
459
+ return r.addCommand(ue()), r.addCommand(ge()), e.addCommand(r), e;
460
+ }
461
+ async function _e(e = process.argv) {
545
462
  await $().parseAsync(e);
546
463
  }
547
- export { $ as buildProgram, De as run };
464
+ export { $ as buildProgram, _e as run };
548
465
 
549
466
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":["openUserRoot","outputText","createAdminPlConnection","duplicateProject","getProjectInfo","getProjectListRid","navigateToUserRoot","moveProjects","outputJson","listProjects","formatTable","deduplicateName","outputCsv","deleteProject","formatDate","getExistingLabelsInTx","renameProject","createPlConnection","resolveProject","connectClient","flags","connect","hasAdminUser","hasAdminPassword","hasTarget","pl","projectListRid","addOptions","optionGroups","group","opt","cmd","AddressOptions","Option","GlobalOptions","allowedFormats","formatDefault","UserAuthOptions","AdminAuthOptions","AdminTargetOptions","projectListCommand","Command","projects","p","resourceIdToString","projectInfoCommand","project","info","id","rid","bid","projectDuplicateCommand","sourceRid","newId","randomUUID","result","sourceMetaStr","tx","ProjectMetaKey","sourceLabel","existingLabels","newLabel","newPrj","field","projectResourceId","projectRenameCommand","projectDeleteCommand","rl","createInterface","resolve","fieldName","adminCopyProjectCommand","targetUser","source","target","prjResourceId","adminUserListCommand","users","err","isPermissionDenied","logins","u","l","adminDeleteUserCommand","user","listProjectIdentities","confirmDeletion","moved","targetList","ensureUserProjectList","remaining","report","renderResult","assertProjectsAccountedFor","approvedIds","approved","unapproved","fate","lines","movedTo","adminInstanceStatsCommand","context","InstanceStatsContextTypeName","kvs","parseInstanceStats","parseResourceId","str","raw","asSignedResourceId","resourceIdFromString","isLocalResourceId","createSignedResourceId","maintenanceListResourcesCommand","parseResourceTypeArg","parseNonNegativeInt","resources","list","resource","line","toJson","kv","once","r","resourceTypeToString","optionalIdToString","decodeBytes","withFields","fieldToJson","f","isNotNullSignedResourceId","text","bytes","sep","value","InvalidArgumentError","resourceType","n","DefaultErrorMessage","maintenanceSetResourceErrorCommand","ids","rawIds","found","missing","targets","skipped","error","ResourcesFixupLevelKey","ResourcesFixupLevelSize","readFixupLevel","controllerType","resetFixupLevel","maintenanceControllerListCommand","controllers","listRegisteredControllers","c","headers","rows","collect","previous","parse","maintenanceControllerRerunFixupsCommand","names","reset","selected","selectControllers","levels","controller","level","registered","byType","name","wanted","anyResourceIdToBigint","buildProgram","program","admin","maintenance","run","argv"],"sources":["../src/base_command.ts","../src/cmd-opts.ts","../src/cmd/project/list.ts","../src/cmd/project/info.ts","../src/cmd/project/duplicate.ts","../src/cmd/project/rename.ts","../src/cmd/project/delete.ts","../src/cmd/admin/copy-project.ts","../src/cmd/admin/user-list.ts","../src/cmd/admin/delete-user.ts","../src/cmd/admin/instance-stats.ts","../src/resource_id.ts","../src/cmd/maintenance/list-resources.ts","../src/cmd/maintenance/set-resource-error.ts","../src/cmd/maintenance/controller/fixup_level.ts","../src/cmd/maintenance/controller/list.ts","../src/cmd/maintenance/controller/rerun-fixups.ts","../src/cli.ts"],"sourcesContent":["import type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { createPlConnection, createAdminPlConnection } from \"./connection\";\nimport { getProjectListRid, navigateToUserRoot } from \"./project_ops\";\n\n/**\n * Low-level: get an authenticated PlClient without resolving a project list.\n * Use this for commands that navigate to multiple users (e.g. admin copy-project).\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connectClient(flags: {\n address: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n}): Promise<PlClient> {\n if (flags.adminUser && flags.adminPassword) {\n return createAdminPlConnection({\n address: flags.address,\n adminUser: flags.adminUser,\n adminPassword: flags.adminPassword,\n });\n }\n return createPlConnection({\n address: flags.address,\n user: flags.user,\n password: flags.password,\n });\n}\n\n/**\n * Connect and resolve the project list for a single user.\n * In admin mode (--admin-user + --admin-password + --target-user), operates on the target user's data.\n * In user mode, operates on the authenticated user's own data.\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connect(flags: {\n address: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n targetUser?: string;\n}): Promise<{ pl: PlClient; projectListRid: SignedResourceId }> {\n const hasAdminUser = !!flags.adminUser;\n const hasAdminPassword = !!flags.adminPassword;\n const hasTarget = !!flags.targetUser;\n\n // Validate flag combinations\n if (hasTarget && !(hasAdminUser && hasAdminPassword)) {\n throw new Error(\"--target-user requires --admin-user and --admin-password\");\n }\n if ((hasAdminUser || hasAdminPassword) && !hasTarget) {\n throw new Error(\"--admin-user/--admin-password require --target-user for project commands\");\n }\n\n const pl = await connectClient(flags);\n\n let projectListRid: SignedResourceId;\n if (hasTarget) {\n const nav = await navigateToUserRoot(pl, flags.targetUser!);\n projectListRid = nav.projectListRid;\n } else {\n projectListRid = await getProjectListRid(pl);\n }\n\n return { pl, projectListRid };\n}\n","import { Command, Option } from \"commander\";\nimport type { OutputFormat } from \"./output\";\n\n/** Add one or more groups of options to a command, preserving group order. */\nexport function addOptions(cmd: Command, ...optionGroups: Option[][]): Command {\n for (const group of optionGroups) {\n for (const opt of group) cmd.addOption(opt);\n }\n return cmd;\n}\n\n/** Server address only (for commands with a fixed output format). */\nexport const AddressOptions = (): Option[] => [\n new Option(\"-a, --address <url>\", \"Platforma server address\")\n .env(\"PL_ADDRESS\")\n .makeOptionMandatory(),\n];\n\nexport const GlobalOptions = (\n formatDefault: OutputFormat = \"text\",\n allowedFormats: OutputFormat[] = [\"text\", \"json\"],\n): Option[] => [\n ...AddressOptions(),\n new Option(\"-f, --format <format>\", \"Output format\")\n .choices(allowedFormats)\n .default(formatDefault),\n];\n\nexport const UserAuthOptions = (): Option[] => [\n new Option(\"-u, --user <user>\", \"Username for authentication\").env(\"PL_USER\"),\n new Option(\"-p, --password <password>\", \"Password for authentication\").env(\"PL_PASSWORD\"),\n];\n\n/** Admin credentials only (for purely admin commands like copy-project). */\nexport const AdminAuthOptions = (): Option[] => [\n new Option(\"--admin-user <user>\", \"Admin/controller username\")\n .env(\"PL_ADMIN_USER\")\n .makeOptionMandatory(),\n new Option(\"--admin-password <password>\", \"Admin/controller password\")\n .env(\"PL_ADMIN_PASSWORD\")\n .makeOptionMandatory(),\n];\n\n/** Admin credentials + target user (for regular commands that can optionally operate on another user). */\nexport const AdminTargetOptions = (): Option[] => [\n new Option(\"--admin-user <user>\", \"Admin/controller username (enables admin mode)\").env(\n \"PL_ADMIN_USER\",\n ),\n new Option(\"--admin-password <password>\", \"Admin/controller password\").env(\"PL_ADMIN_PASSWORD\"),\n new Option(\n \"--target-user <user>\",\n \"Operate on this user's data (requires admin credentials)\",\n ).env(\"PL_TARGET_USER\"),\n];\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { listProjects } from \"../../project_ops\";\nimport { formatTable, formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectListCommand(): Command {\n const cmd = new Command(\"list\").description(\"List all projects for the authenticated user.\");\n\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const projects = await listProjects(pl, projectListRid);\n\n if (flags.format === \"json\") {\n outputJson(\n projects.map((p) => ({\n id: p.id,\n rid: resourceIdToString(p.rid),\n label: p.label,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n } else {\n if (projects.length === 0) {\n outputText(\"No projects found.\");\n return;\n }\n\n outputText(\n formatTable(\n [\"ID\", \"RID\", \"LABEL\", \"CREATED\", \"LAST MODIFIED\"],\n projects.map((p) => [\n p.id,\n resourceIdToString(p.rid),\n p.label,\n formatDate(p.created),\n formatDate(p.lastModified),\n ]),\n ),\n );\n outputText(`\\n${projects.length} project(s)`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, getProjectInfo } from \"../../project_ops\";\nimport { formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectInfoCommand(): Command {\n const cmd = new Command(\"info\").description(\"Show detailed information about a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n const info = await getProjectInfo(pl, id, rid);\n\n if (flags.format === \"json\") {\n outputJson({\n id: info.id,\n rid: resourceIdToString(info.rid),\n label: info.label,\n schemaVersion: info.schemaVersion,\n blockCount: info.blockCount,\n blockIds: info.blockIds,\n created: info.created.toISOString(),\n lastModified: info.lastModified.toISOString(),\n });\n } else {\n outputText(`Project: ${info.label}`);\n outputText(`ID: ${info.id}`);\n outputText(`RID: ${resourceIdToString(info.rid)}`);\n outputText(`Schema: ${info.schemaVersion ?? \"(unknown)\"}`);\n outputText(`Blocks: ${info.blockCount}`);\n if (info.blockIds.length > 0) {\n for (const bid of info.blockIds) {\n outputText(` - ${bid}`);\n }\n }\n outputText(`Created: ${formatDate(info.created)}`);\n outputText(`Last Modified: ${formatDate(info.lastModified)}`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDuplicateCommand(): Command {\n const cmd = new Command(\"duplicate\").description(\n \"Duplicate a project within the same user. Auto-renames on collision by default.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"-n, --name <name>\", \"Name for the duplicate\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { rid: sourceRid } = await resolveProject(pl, projectListRid, project);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"duplicateProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, projectListRid);\n\n // Compute new label\n let newLabel: string;\n if (flags.name) {\n if (!flags.autoRename && existingLabels.includes(flags.name)) {\n throw new Error(`Project name \"${flags.name}\" already exists.`);\n }\n newLabel = existingLabels.includes(flags.name)\n ? deduplicateName(flags.name, existingLabels)\n : flags.name;\n } else {\n newLabel = deduplicateName(sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const projectResourceId = await newPrj.globalId;\n const projectId = resourceIdToString(projectResourceId);\n return { id: projectId, rid: projectResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({ id: result.id, rid: resourceIdToString(result.rid), label: result.label });\n } else {\n outputText(`Duplicated project as \"${result.label}\" (id: ${result.id})`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, renameProject } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectRenameCommand(): Command {\n const cmd = new Command(\"rename\").description(\"Rename a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.addOption(new Option(\"-n, --name <name>\", \"New name for the project\").makeOptionMandatory());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n\n await renameProject(pl, rid, flags.name);\n\n if (flags.format === \"json\") {\n outputJson({ id, rid: resourceIdToString(rid), label: flags.name });\n } else {\n outputText(`Renamed project to \"${flags.name}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, deleteProject, getProjectInfo } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDeleteCommand(): Command {\n const cmd = new Command(\"delete\").description(\n \"Delete a project. This permanently destroys all project data.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid, fieldName } = await resolveProject(pl, projectListRid, project);\n\n const info = await getProjectInfo(pl, id, rid);\n\n if (!flags.force) {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\n `Delete project \"${info.label}\" (${info.blockCount} blocks)? [y/N] `,\n resolve,\n );\n });\n if (answer.toLowerCase() !== \"y\") {\n outputText(\"Aborted.\");\n return;\n }\n } finally {\n rl.close();\n }\n }\n\n await deleteProject(pl, projectListRid, fieldName);\n\n if (flags.format === \"json\") {\n outputJson({ deleted: true, id, label: info.label });\n } else {\n outputText(`Deleted project \"${info.label}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n navigateToUserRoot,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function adminCopyProjectCommand(): Command {\n const cmd = new Command(\"copy-project\").description(\n \"Copy a project from one user to another. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--source-user <user>\",\n \"Username of the source project owner\",\n ).makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--source-project <project>\", \"Source project ID or label\").makeOptionMandatory(),\n );\n cmd.option(\n \"--target-user <user>\",\n \"Username of the target user (defaults to source-user for same-user copy)\",\n );\n cmd.option(\"-n, --name <name>\", \"Name for the copied project\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const targetUser = flags.targetUser ?? flags.sourceUser;\n\n const source = await navigateToUserRoot(pl, flags.sourceUser);\n const { rid: sourceRid } = await resolveProject(\n pl,\n source.projectListRid,\n flags.sourceProject,\n );\n\n const target =\n targetUser === flags.sourceUser ? source : await navigateToUserRoot(pl, targetUser);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"adminCopyProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, target.projectListRid);\n\n let newLabel: string = flags.name ?? sourceLabel;\n\n if (existingLabels.includes(newLabel)) {\n if (!flags.autoRename) {\n throw new Error(`Project name \"${newLabel}\" already exists for target user.`);\n }\n newLabel = deduplicateName(flags.name ?? sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(target.projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const prjResourceId = await newPrj.globalId;\n const prjId = resourceIdToString(prjResourceId);\n return { id: prjId, rid: prjResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({\n id: result.id,\n rid: resourceIdToString(result.rid),\n label: result.label,\n sourceUser: flags.sourceUser,\n targetUser,\n });\n } else {\n outputText(\n `Copied project from ${flags.sourceUser} to ${targetUser} as \"${result.label}\" (id: ${result.id}, rid: ${resourceIdToString(result.rid)})`,\n );\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { isPermissionDenied } from \"@milaboratories/pl-client\";\nimport { Command } from \"commander\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson, outputText, outputCsv } from \"../../output\";\n\nexport default function adminUserListCommand(): Command {\n const cmd = new Command(\"user-list\").description(\n \"List all known users' logins from a live server. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(\"csv\", [\"text\", \"json\", \"csv\"]), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n let users;\n try {\n users = await pl.listUsers();\n } catch (err) {\n if (isPermissionDenied(err))\n throw new Error(\n \"The server does not let this user list users. \" +\n \"Check the server option '--show-user-list-to' and the role of the user.\",\n { cause: err },\n );\n throw err;\n }\n const logins = users.map((u) => u.login).sort();\n if (flags.format === \"json\") outputJson(logins);\n else if (flags.format === \"text\") outputText(logins.join(\"\\n\"));\n else\n outputCsv(\n [\"login\"],\n logins.map((l) => [l]),\n );\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n ensureUserProjectList,\n listProjectIdentities,\n moveProjects,\n openUserRoot,\n} from \"../../project_ops\";\nimport type { MovedProject, ProjectIdentityWithLabel } from \"../../project_ops\";\nimport { formatTable, outputJson, outputText } from \"../../output\";\n\nexport default function adminDeleteUserCommand(): Command {\n const cmd = new Command(\"delete-user\").description(\n \"Delete a user account. Optionally re-homes the user's projects to another user first. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\"<user>\", \"Username of the account to delete\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--move-projects-to <user>\",\n \"Re-home the deleted user's projects to this user before deleting the account\",\n ),\n );\n cmd.addOption(\n new Option(\n \"--delete-projects\",\n \"Delete the user's projects along with the account, losing their data\",\n ),\n );\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (user: string, flags) => {\n // The two modes are alternatives, not a combination: one keeps the projects, the other\n // destroys them, and a request for both says nothing about which was meant.\n if (flags.moveProjectsTo && flags.deleteProjects) {\n throw new Error(\"--move-projects-to and --delete-projects are mutually exclusive\");\n }\n if (flags.moveProjectsTo === user) {\n throw new Error(\"--move-projects-to must name a different user than the one being deleted\");\n }\n // Caught here as well as server-side, where it is authoritative: the operator gets the reason\n // instead of a failure from whichever lookup happens to run first.\n if (flags.adminUser === user) {\n throw new Error(\n `Refusing to delete \"${user}\" — it is the account these credentials authenticate as.`,\n );\n }\n\n const pl = await connectClient(flags);\n try {\n const source = await openUserRoot(pl, user);\n // No project list means the account never opened the app, so it owns nothing — a state to\n // delete straight through, not to fail on.\n const projects =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n\n // Neither mode given while the account still owns projects: refuse rather than pick. Both\n // defaults are wrong to assume — one silently destroys data, the other silently hands it to\n // someone. An account with no projects has nothing to decide about, so it just proceeds.\n if (projects.length > 0 && !flags.moveProjectsTo && !flags.deleteProjects) {\n throw new Error(\n `User \"${user}\" owns ${projects.length} project(s). Pass --move-projects-to <user> to ` +\n \"re-home them, or --delete-projects to delete them with the account.\",\n );\n }\n\n const confirmed = await confirmDeletion(user, projects, flags);\n if (!confirmed) {\n outputText(\"Aborted.\");\n return;\n }\n\n let moved: MovedProject[] = [];\n if (flags.moveProjectsTo && projects.length > 0) {\n const target = await openUserRoot(pl, flags.moveProjectsTo);\n // Created if the target has none, so re-homing to a user who has never opened the app\n // works rather than failing halfway with the account still present.\n const targetList = await ensureUserProjectList(pl, target.userRoot);\n moved = await moveProjects(pl, source.projectListRid!, targetList);\n }\n\n // deleteUser takes the root and everything still attached to it. The listing, the prompt and\n // the move each ran in an earlier transaction, so re-read: a project attached since then would\n // be destroyed without ever being reviewed.\n const remaining =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n assertProjectsAccountedFor(user, flags, projects, remaining);\n\n const report = await pl.deleteUser(user);\n\n if (flags.format === \"json\") {\n outputJson({\n deleted: true,\n user,\n movedTo: flags.moveProjectsTo ?? null,\n movedProjects: moved,\n deletedProjects: flags.moveProjectsTo ? [] : remaining.map((p) => p.label),\n userRootId: report.userRootId === undefined ? null : report.userRootId.toString(),\n userRootDeleted: report.userRootDeleted,\n revokedGrants: report.revokedGrants,\n removedIdentityIndexEntries: report.removedIdentityIndexEntries,\n });\n } else {\n outputText(renderResult(user, flags.moveProjectsTo, moved, remaining));\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\n/**\n * Refuses while the root holds a project the operator never agreed to lose — attached after the\n * listing, or left behind by the move.\n *\n * A last read, not a lock: it closes the prompt-sized window, not the round trip that follows.\n */\nfunction assertProjectsAccountedFor(\n user: string,\n flags: { moveProjectsTo?: string },\n approved: ProjectIdentityWithLabel[],\n remaining: ProjectIdentityWithLabel[],\n): void {\n if (flags.moveProjectsTo) {\n if (remaining.length === 0) return;\n throw new Error(\n `User \"${user}\" still owns ${remaining.length} project(s) after the move: ` +\n `${remaining.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"the projects were attached while the move ran. Re-run the command to move them too.\",\n );\n }\n\n const approvedIds = new Set(approved.map((p) => p.id));\n const unapproved = remaining.filter((p) => !approvedIds.has(p.id));\n if (unapproved.length === 0) return;\n throw new Error(\n `User \"${user}\" gained ${unapproved.length} project(s) since the list you confirmed: ` +\n `${unapproved.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"deleting it now would destroy them unreviewed. Re-run the command to see the current list.\",\n );\n}\n\n/** Asks the operator to confirm, naming the affected projects and their fate. */\nasync function confirmDeletion(\n user: string,\n projects: ProjectIdentityWithLabel[],\n flags: { moveProjectsTo?: string; force?: boolean },\n): Promise<boolean> {\n if (flags.force) return true;\n\n const fate = flags.moveProjectsTo\n ? `${projects.length} project(s) will move to \"${flags.moveProjectsTo}\"`\n : projects.length > 0\n ? `${projects.length} project(s) will be PERMANENTLY DELETED`\n : \"the account owns no projects\";\n\n process.stderr.write(`Delete user \"${user}\"? ${fate}.\\n`);\n if (projects.length > 0) {\n process.stderr.write(projects.map((p) => ` - ${p.label}`).join(\"\\n\") + \"\\n\");\n }\n\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\"Proceed? [y/N] \", resolve);\n });\n return answer.toLowerCase() === \"y\";\n } finally {\n rl.close();\n }\n}\n\nfunction renderResult(\n user: string,\n movedTo: string | undefined,\n moved: MovedProject[],\n projects: ProjectIdentityWithLabel[],\n): string {\n const lines: string[] = [];\n\n if (movedTo) {\n if (moved.length > 0) {\n lines.push(`Moved ${moved.length} project(s) from ${user} to ${movedTo}:`);\n lines.push(\n formatTable(\n [\"id\", \"name\", \"name in target\"],\n moved.map((p) => [p.id, p.sourceLabel, p.targetLabel]),\n ),\n );\n } else {\n lines.push(`User ${user} had no projects to move.`);\n }\n } else if (projects.length > 0) {\n lines.push(`Deleted ${projects.length} project(s) belonging to ${user}:`);\n lines.push(projects.map((p) => ` - ${p.label}`).join(\"\\n\"));\n }\n\n lines.push(`Deleted user \"${user}\".`);\n return lines.join(\"\\n\");\n}\n","import { Command } from \"commander\";\nimport { InstanceStatsContextTypeName, parseInstanceStats } from \"@milaboratories/pl-middle-layer\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson } from \"../../output\";\n\nexport default function adminInstanceStatsCommand(): Command {\n const cmd = new Command(\"instance-stats\").description(\"Show the instance statistics as JSON.\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const [context] = await pl.listSharedResourcesByType(InstanceStatsContextTypeName);\n if (context === undefined) throw new Error(\"The instance has no instance statistics.\");\n const kvs = await pl.withReadTx(\"instanceStats\", (tx) => tx.listKeyValuesString(context));\n outputJson(parseInstanceStats(kvs));\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import {\n asSignedResourceId,\n createSignedResourceId,\n isLocalResourceId,\n resourceIdFromString,\n type SignedResourceId,\n} from \"@milaboratories/pl-client\";\n\n/**\n * Admin and controller roles do not need resource signatures: an ID without a signature\n * is accepted by the backend for these roles.\n */\nexport function parseResourceId(raw: string): SignedResourceId {\n const str = raw.trim();\n if (str.includes(\"|\")) return asSignedResourceId(str);\n\n let id: bigint | undefined = resourceIdFromString(str);\n if (id === undefined && /^\\d+$/.test(str)) id = BigInt(str);\n if (id === undefined || id === 0n || isLocalResourceId(id))\n throw new Error(`not a global resource ID: ${raw}`);\n\n return createSignedResourceId(id);\n}\n","import { once } from \"node:events\";\nimport { Command, InvalidArgumentError, Option } from \"commander\";\nimport {\n isNotNullSignedResourceId,\n resourceIdToString,\n resourceType,\n resourceTypeToString,\n type FieldData,\n type KeyValue,\n type OptionalSignedResourceId,\n type ResourceData,\n type ResourceType,\n} from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { parseResourceId } from \"../../resource_id\";\n\nexport default function maintenanceListResourcesCommand(): Command {\n const cmd = new Command(\"list-resources\").description(\n \"List resources of one type as JSON lines, in ascending order of resource ID. \" +\n \"Resource data and key-value values are printed as JSON when they are valid JSON, \" +\n 'as text when they are valid UTF-8, and as {\"base64\": ...} in other cases. ' +\n \"Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"--type <name:version>\", \"Resource type to list (e.g. 'Blob/work:1')\")\n .argParser(parseResourceTypeArg)\n .makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--limit <n>\", \"Maximum number of resources to list. 0 lists all resources\")\n .argParser(parseNonNegativeInt)\n .default(0),\n );\n cmd.addOption(\n new Option(\n \"--after <resource-id>\",\n \"List only resources with IDs greater than this ID. \" +\n \"To get the next page, give the ID of the last resource of the previous page\",\n ).argParser(parseResourceId),\n );\n cmd.option(\n \"--load-fields\",\n \"Load the fields and the error of each resource ('fields' and 'error' keys)\",\n false,\n );\n cmd.option(\"--load-kv\", \"Load the key-value entries of each resource ('kv' key)\", false);\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const resources = await pl.withReadTx(\"listResources\", async (tx) => {\n const list = await tx.listResourcesByType(flags.type, {\n limit: flags.limit,\n after: flags.after,\n loadFields: flags.loadFields,\n });\n return await Promise.all(\n list.map(async (resource) => ({\n resource,\n kv: flags.loadKv ? await tx.listKeyValues(resource.id) : undefined,\n })),\n );\n });\n\n for (const { resource, kv } of resources) {\n const line = JSON.stringify(toJson(resource, flags.loadFields, kv)) + \"\\n\";\n // Wait for a slow reader: else the output collects in memory a second time.\n if (!process.stdout.write(line)) await once(process.stdout, \"drain\");\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\nfunction toJson(\n r: ResourceData,\n withFields: boolean,\n kv: KeyValue[] | undefined,\n): Record<string, unknown> {\n return {\n id: resourceIdToString(r.id),\n type: resourceTypeToString(r.type),\n kind: r.kind,\n originalId: optionalIdToString(r.originalResourceId),\n inputsLocked: r.inputsLocked,\n outputsLocked: r.outputsLocked,\n ready: r.resourceReady,\n final: r.final,\n data: r.data === undefined || r.data.length === 0 ? null : decodeBytes(r.data),\n // The backend sends the resource error as a field: without fields it is not known.\n ...(withFields\n ? { error: optionalIdToString(r.error), fields: r.fields.map(fieldToJson) }\n : {}),\n ...(kv === undefined\n ? {}\n : { kv: Object.fromEntries(kv.map((e) => [e.key, decodeBytes(e.value)])) }),\n };\n}\n\nfunction fieldToJson(f: FieldData): Record<string, unknown> {\n return {\n name: f.name,\n type: f.type,\n status: f.status,\n value: optionalIdToString(f.value),\n error: optionalIdToString(f.error),\n valueIsFinal: f.valueIsFinal,\n };\n}\n\nfunction optionalIdToString(id: OptionalSignedResourceId): string | null {\n return isNotNullSignedResourceId(id) ? resourceIdToString(id) : null;\n}\n\n/** JSON value when the bytes are valid JSON, text when valid UTF-8, {\"base64\": ...} otherwise. */\nfunction decodeBytes(bytes: Uint8Array): unknown {\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n return { base64: Buffer.from(bytes).toString(\"base64\") };\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction parseResourceTypeArg(value: string): ResourceType {\n const sep = value.lastIndexOf(\":\");\n if (sep <= 0 || sep === value.length - 1)\n throw new InvalidArgumentError(`expected <name>:<version>, e.g. 'Blob/work:1': ${value}`);\n return resourceType(value.slice(0, sep), value.slice(sep + 1));\n}\n\nfunction parseNonNegativeInt(value: string): number {\n const n = Number(value);\n if (!Number.isInteger(n) || n < 0)\n throw new InvalidArgumentError(`not a non-negative integer: ${value}`);\n return n;\n}\n","import { Command, Option } from \"commander\";\nimport { isNotNullSignedResourceId, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputText } from \"../../output\";\nimport { parseResourceId } from \"../../resource_id\";\n\nconst DefaultErrorMessage =\n \"Manual error set by administrator to trigger blocks re-run. \" +\n \"Run block once again to get rid of it.\";\n\nexport default function maintenanceSetResourceErrorCommand(): Command {\n const cmd = new Command(\"set-resource-error\").description(\n \"Put an error on one or more resources in a single transaction. \" +\n \"Resources that already have an error are skipped. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\n \"<resource-id...>\",\n \"Resource IDs: as printed by the server (NG:0x1A2B), as decimal numbers, \" +\n \"or as signed IDs (<decimal ID>|<signature hex>)\",\n );\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"-m, --error-message <message>\", \"Error message to put on the resources\").default(\n DefaultErrorMessage,\n ),\n );\n cmd.option(\n \"--skip-missing\",\n \"Skip resources that do not exist instead of failing the whole transaction\",\n false,\n );\n\n cmd.action(async (rawIds: string[], flags) => {\n // Parse all IDs before the connection, so that a typo does not leave a half-done job.\n const ids = rawIds.map(parseResourceId);\n\n const pl = await connectClient(flags);\n try {\n const result = await pl.withWriteTx(\"setResourceError\", async (tx) => {\n const found = await Promise.all(\n ids.map(async (id) => ({\n id,\n data: flags.skipMissing\n ? await tx.getResourceDataIfExists(id, true)\n : await tx.getResourceData(id, true, true),\n })),\n );\n\n const missing = found.filter((r) => r.data === undefined).map((r) => r.id);\n const resources = found.flatMap((r) => (r.data === undefined ? [] : [r.data]));\n const targets = resources.filter((r) => !isNotNullSignedResourceId(r.error));\n const skipped = resources.filter((r) => isNotNullSignedResourceId(r.error));\n\n if (targets.length > 0) {\n // One error resource for all targets: the backend links it to each target separately.\n const error = tx.createError(flags.errorMessage);\n for (const r of targets) tx.setResourceError(r.id, error);\n await tx.commit();\n }\n\n return { targets, skipped, missing };\n });\n\n for (const id of result.missing)\n outputText(`skipped ${resourceIdToString(id)}: resource does not exist`);\n for (const r of result.skipped)\n outputText(`skipped ${resourceIdToString(r.id)}: resource already has an error`);\n for (const r of result.targets) outputText(`error set ${resourceIdToString(r.id)}`);\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import type { PlTransaction } from \"@milaboratories/pl-client\";\n\n/**\n * Key of the resources fixup level in the key-value store of a controller.\n * Must match MetadataResourcesFixupLevel in the backend (controllers/shared/ctlsdk/resources_fixup.go).\n */\nexport const ResourcesFixupLevelKey = \"ctl/ctlsdk/resourcesFixupLevel\";\n\n/** The backend keeps the level as a big-endian uint32. */\nconst ResourcesFixupLevelSize = 4;\n\n/** Reads the resources fixup level of the controller as text: a number, \"not set\" or \"invalid\". */\nexport async function readFixupLevel(tx: PlTransaction, controllerType: string): Promise<string> {\n const value = await tx.getControllerKValueIfExists(controllerType, ResourcesFixupLevelKey);\n if (value === undefined) return \"not set\";\n if (value.length !== ResourcesFixupLevelSize) return `invalid (${value.length} bytes)`;\n return String(Buffer.from(value).readUInt32BE(0));\n}\n\n/** Sets the resources fixup level of the controller to 0. The transaction must be writable. */\nexport function resetFixupLevel(tx: PlTransaction, controllerType: string): void {\n tx.setControllerKValue(\n controllerType,\n ResourcesFixupLevelKey,\n new Uint8Array(ResourcesFixupLevelSize),\n );\n}\n","import { Command } from \"commander\";\nimport { listRegisteredControllers, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../../base_command\";\nimport { addOptions, AdminAuthOptions, GlobalOptions } from \"../../../cmd-opts\";\nimport { formatTable, outputCsv, outputJson, outputText } from \"../../../output\";\nimport { readFixupLevel } from \"./fixup_level\";\n\nexport default function maintenanceControllerListCommand(): Command {\n const cmd = new Command(\"list\").description(\n \"List the controllers registered in the backend, with their IDs and resources fixup levels. \" +\n \"Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(\"text\", [\"text\", \"json\", \"csv\"]), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const controllers = await pl.withReadTx(\"listControllers\", async (tx) => {\n const list = await listRegisteredControllers(tx);\n return await Promise.all(\n list.map(async (c) => ({\n id: resourceIdToString(c.id),\n type: c.type,\n fixupLevel: await readFixupLevel(tx, c.type),\n })),\n );\n });\n\n const headers = [\"id\", \"type\", \"fixup level\"];\n const rows = controllers.map((c) => [c.id, c.type, c.fixupLevel]);\n if (flags.format === \"json\") outputJson(controllers);\n else if (flags.format === \"csv\") outputCsv(headers, rows);\n else outputText(formatTable(headers, rows));\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport {\n anyResourceIdToBigint,\n listRegisteredControllers,\n resourceIdToString,\n type PlTransaction,\n type RegisteredController,\n type SignedResourceId,\n} from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../../cmd-opts\";\nimport { outputText } from \"../../../output\";\nimport { parseResourceId } from \"../../../resource_id\";\nimport { readFixupLevel, resetFixupLevel } from \"./fixup_level\";\n\nfunction collect<T>(parse: (raw: string) => T) {\n return (raw: string, previous: T[] | undefined): T[] => [...(previous ?? []), parse(raw)];\n}\n\nexport default function maintenanceControllerRerunFixupsCommand(): Command {\n const cmd = new Command(\"rerun-fixups\").description(\n \"Set the resources fixup level of the selected controllers to 0 in a single transaction. \" +\n \"On its next start, each controller applies all its one-time resources fixups again. \" +\n \"Use this after a rollback to a backend version without resources fixups. \" +\n \"Select controllers with --controller-name and --controller-id \" +\n \"(see 'maintenance controller list'). Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--controller-name <type>\",\n 'Controller type, as the controller registers it (for example \"File/Manager\"). ' +\n \"Repeat the option to select more controllers\",\n ).argParser(collect((raw) => raw)),\n );\n cmd.addOption(\n new Option(\n \"--controller-id <resource-id>\",\n \"Controller ID, as 'maintenance controller list' prints it. \" +\n \"Repeat the option to select more controllers\",\n ).argParser(collect(parseResourceId)),\n );\n\n cmd.action(async (flags) => {\n const names: string[] = flags.controllerName ?? [];\n const ids: SignedResourceId[] = flags.controllerId ?? [];\n if (names.length === 0 && ids.length === 0)\n throw new Error(\"select at least one controller with --controller-name or --controller-id\");\n\n const pl = await connectClient(flags);\n try {\n const reset = await pl.withWriteTx(\"rerunControllerFixups\", async (tx) => {\n const selected = await selectControllers(tx, names, ids);\n const levels = await Promise.all(\n selected.map(async (c) => ({ controller: c, level: await readFixupLevel(tx, c.type) })),\n );\n\n for (const c of selected) resetFixupLevel(tx, c.type);\n await tx.commit();\n\n return levels;\n });\n\n for (const { controller, level } of reset)\n outputText(\n `${controller.type} (${resourceIdToString(controller.id)}): ` +\n `resources fixup level ${level} -> 0`,\n );\n outputText(\"Restart the backend to apply the resources fixups.\");\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\n/** Resolves the selected controllers. Throws when a name or an ID matches no registered controller. */\nasync function selectControllers(\n tx: PlTransaction,\n names: string[],\n ids: SignedResourceId[],\n): Promise<RegisteredController[]> {\n const registered = await listRegisteredControllers(tx);\n const byType = new Map<string, RegisteredController>();\n\n for (const name of names) {\n const controller = registered.find((c) => c.type === name);\n if (controller === undefined) throw new Error(`controller \"${name}\" is not registered`);\n byType.set(controller.type, controller);\n }\n\n for (const id of ids) {\n const wanted = anyResourceIdToBigint(id);\n const controller = registered.find((c) => anyResourceIdToBigint(c.id) === wanted);\n if (controller === undefined)\n throw new Error(`no registered controller has ID ${resourceIdToString(id)}`);\n byType.set(controller.type, controller);\n }\n\n return [...byType.values()];\n}\n","import { Command } from \"commander\";\nimport projectListCommand from \"./cmd/project/list\";\nimport projectInfoCommand from \"./cmd/project/info\";\nimport projectDuplicateCommand from \"./cmd/project/duplicate\";\nimport projectRenameCommand from \"./cmd/project/rename\";\nimport projectDeleteCommand from \"./cmd/project/delete\";\nimport adminCopyProjectCommand from \"./cmd/admin/copy-project\";\nimport adminUserListCommand from \"./cmd/admin/user-list\";\nimport adminDeleteUserCommand from \"./cmd/admin/delete-user\";\nimport adminInstanceStatsCommand from \"./cmd/admin/instance-stats\";\nimport maintenanceListResourcesCommand from \"./cmd/maintenance/list-resources\";\nimport maintenanceSetResourceErrorCommand from \"./cmd/maintenance/set-resource-error\";\nimport maintenanceControllerListCommand from \"./cmd/maintenance/controller/list\";\nimport maintenanceControllerRerunFixupsCommand from \"./cmd/maintenance/controller/rerun-fixups\";\n\nexport function buildProgram(): Command {\n const program = new Command();\n program.name(\"pl-cli\").description(\"Platforma command-line client\");\n\n const project = new Command(\"project\").description(\"Manage projects\");\n project.addCommand(projectListCommand());\n project.addCommand(projectInfoCommand());\n project.addCommand(projectDuplicateCommand());\n project.addCommand(projectRenameCommand());\n project.addCommand(projectDeleteCommand());\n program.addCommand(project);\n\n const admin = new Command(\"admin\").description(\n \"Admin operations (requires controller credentials)\",\n );\n admin.addCommand(adminCopyProjectCommand());\n admin.addCommand(adminUserListCommand());\n admin.addCommand(adminDeleteUserCommand());\n admin.addCommand(adminInstanceStatsCommand());\n program.addCommand(admin);\n\n const maintenance = new Command(\"maintenance\").description(\n \"Low-level server state repair (requires admin/controller credentials)\",\n );\n maintenance.addCommand(maintenanceListResourcesCommand());\n maintenance.addCommand(maintenanceSetResourceErrorCommand());\n const controller = new Command(\"controller\").description(\n \"Inspect registered controllers and their resources fixups\",\n );\n controller.addCommand(maintenanceControllerListCommand());\n controller.addCommand(maintenanceControllerRerunFixupsCommand());\n maintenance.addCommand(controller);\n program.addCommand(maintenance);\n\n return program;\n}\n\nexport async function run(argv: string[] = process.argv): Promise<void> {\n await buildProgram().parseAsync(argv);\n}\n"],"mappings":";;;;;;;;AAUA,eAAsBmB,EAAc,GAMd;CAQpB,OAPIC,EAAM,aAAaA,EAAM,gBACpBlB,EAAwB;EAC7B,SAASkB,EAAM;EACf,WAAWA,EAAM;EACjB,eAAeA,EAAM;CACvB,CAAC,IAEIH,EAAmB;EACxB,SAASG,EAAM;EACf,MAAMA,EAAM;EACZ,UAAUA,EAAM;CAClB,CAAC;AACH;AASA,eAAsBC,EAAQ,GAOkC;CAC9D,IAAMC,IAAe,CAAC,CAACF,EAAM,WACvBG,IAAmB,CAAC,CAACH,EAAM,eAC3BI,IAAY,CAAC,CAACJ,EAAM;CAG1B,IAAII,KAAa,EAAEF,KAAgBC,IACjC,MAAU,MAAM,0DAA0D;CAE5E,KAAKD,KAAgBC,MAAqB,CAACC,GACzC,MAAU,MAAM,0EAA0E;CAG5F,IAAMC,IAAK,MAAMN,EAAcC,CAAK,GAEhCM;CAQJ,OAPA,AAIEA,IAJEF,KAEe,MADClB,EAAmBmB,GAAIL,EAAM,UAAW,EAAA,CACrC,iBAEJ,MAAMf,EAAkBoB,CAAE,GAGtC;EAAE;EAAI;CAAe;AAC9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1
+ {"version":3,"file":"cli.js","names":["openUserRoot","outputText","createAdminPlConnection","duplicateProject","getProjectInfo","getProjectListRid","navigateToUserRoot","moveProjects","outputJson","listProjects","formatTable","deduplicateName","outputCsv","deleteProject","formatDate","getExistingLabelsInTx","createPlConnection","resolveProject","connectClient","flags","connect","hasAdminUser","hasAdminPassword","hasTarget","pl","projectListRid","addOptions","optionGroups","group","opt","cmd","AddressOptions","Option","GlobalOptions","allowedFormats","formatDefault","UserAuthOptions","AdminAuthOptions","AdminTargetOptions","projectListCommand","Command","projects","p","resourceIdToString","projectInfoCommand","project","info","id","rid","bid","projectDuplicateCommand","sourceRid","newId","randomUUID","result","sourceMetaStr","tx","ProjectMetaKey","sourceLabel","existingLabels","newLabel","newPrj","field","projectResourceId","projectRenameCommand","renameProject","projectDeleteCommand","rl","createInterface","resolve","fieldName","adminCopyProjectCommand","targetUser","source","target","prjResourceId","adminUserListCommand","users","err","isPermissionDenied","logins","u","l","adminDeleteUserCommand","user","listProjectIdentities","confirmDeletion","moved","targetList","ensureUserProjectList","remaining","report","renderResult","assertProjectsAccountedFor","approvedIds","approved","unapproved","fate","lines","movedTo","adminInstanceStatsCommand","context","InstanceStatsContextTypeName","kvs","parseInstanceStats","parseResourceId","str","raw","asSignedResourceId","resourceIdFromString","isLocalResourceId","createSignedResourceId","maintenanceListResourcesCommand","parseResourceTypeArg","parseNonNegativeInt","resources","list","resource","line","toJson","kv","once","r","resourceTypeToString","optionalIdToString","decodeBytes","withFields","fieldToJson","f","isNotNullSignedResourceId","text","bytes","sep","value","InvalidArgumentError","resourceType","n","DefaultErrorMessage","maintenanceSetResourceErrorCommand","ids","rawIds","found","missing","targets","skipped","error","buildProgram","program","admin","maintenance","run","argv"],"sources":["../src/base_command.ts","../src/cmd-opts.ts","../src/cmd/project/list.ts","../src/cmd/project/info.ts","../src/cmd/project/duplicate.ts","../src/cmd/project/rename.ts","../src/cmd/project/delete.ts","../src/cmd/admin/copy-project.ts","../src/cmd/admin/user-list.ts","../src/cmd/admin/delete-user.ts","../src/cmd/admin/instance-stats.ts","../src/resource_id.ts","../src/cmd/maintenance/list-resources.ts","../src/cmd/maintenance/set-resource-error.ts","../src/cli.ts"],"sourcesContent":["import type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { createPlConnection, createAdminPlConnection } from \"./connection\";\nimport { getProjectListRid, navigateToUserRoot } from \"./project_ops\";\n\n/**\n * Low-level: get an authenticated PlClient without resolving a project list.\n * Use this for commands that navigate to multiple users (e.g. admin copy-project).\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connectClient(flags: {\n address: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n}): Promise<PlClient> {\n if (flags.adminUser && flags.adminPassword) {\n return createAdminPlConnection({\n address: flags.address,\n adminUser: flags.adminUser,\n adminPassword: flags.adminPassword,\n });\n }\n return createPlConnection({\n address: flags.address,\n user: flags.user,\n password: flags.password,\n });\n}\n\n/**\n * Connect and resolve the project list for a single user.\n * In admin mode (--admin-user + --admin-password + --target-user), operates on the target user's data.\n * In user mode, operates on the authenticated user's own data.\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connect(flags: {\n address: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n targetUser?: string;\n}): Promise<{ pl: PlClient; projectListRid: SignedResourceId }> {\n const hasAdminUser = !!flags.adminUser;\n const hasAdminPassword = !!flags.adminPassword;\n const hasTarget = !!flags.targetUser;\n\n // Validate flag combinations\n if (hasTarget && !(hasAdminUser && hasAdminPassword)) {\n throw new Error(\"--target-user requires --admin-user and --admin-password\");\n }\n if ((hasAdminUser || hasAdminPassword) && !hasTarget) {\n throw new Error(\"--admin-user/--admin-password require --target-user for project commands\");\n }\n\n const pl = await connectClient(flags);\n\n let projectListRid: SignedResourceId;\n if (hasTarget) {\n const nav = await navigateToUserRoot(pl, flags.targetUser!);\n projectListRid = nav.projectListRid;\n } else {\n projectListRid = await getProjectListRid(pl);\n }\n\n return { pl, projectListRid };\n}\n","import { Command, Option } from \"commander\";\nimport type { OutputFormat } from \"./output\";\n\n/** Add one or more groups of options to a command, preserving group order. */\nexport function addOptions(cmd: Command, ...optionGroups: Option[][]): Command {\n for (const group of optionGroups) {\n for (const opt of group) cmd.addOption(opt);\n }\n return cmd;\n}\n\n/** Server address only (for commands with a fixed output format). */\nexport const AddressOptions = (): Option[] => [\n new Option(\"-a, --address <url>\", \"Platforma server address\")\n .env(\"PL_ADDRESS\")\n .makeOptionMandatory(),\n];\n\nexport const GlobalOptions = (\n formatDefault: OutputFormat = \"text\",\n allowedFormats: OutputFormat[] = [\"text\", \"json\"],\n): Option[] => [\n ...AddressOptions(),\n new Option(\"-f, --format <format>\", \"Output format\")\n .choices(allowedFormats)\n .default(formatDefault),\n];\n\nexport const UserAuthOptions = (): Option[] => [\n new Option(\"-u, --user <user>\", \"Username for authentication\").env(\"PL_USER\"),\n new Option(\"-p, --password <password>\", \"Password for authentication\").env(\"PL_PASSWORD\"),\n];\n\n/** Admin credentials only (for purely admin commands like copy-project). */\nexport const AdminAuthOptions = (): Option[] => [\n new Option(\"--admin-user <user>\", \"Admin/controller username\")\n .env(\"PL_ADMIN_USER\")\n .makeOptionMandatory(),\n new Option(\"--admin-password <password>\", \"Admin/controller password\")\n .env(\"PL_ADMIN_PASSWORD\")\n .makeOptionMandatory(),\n];\n\n/** Admin credentials + target user (for regular commands that can optionally operate on another user). */\nexport const AdminTargetOptions = (): Option[] => [\n new Option(\"--admin-user <user>\", \"Admin/controller username (enables admin mode)\").env(\n \"PL_ADMIN_USER\",\n ),\n new Option(\"--admin-password <password>\", \"Admin/controller password\").env(\"PL_ADMIN_PASSWORD\"),\n new Option(\n \"--target-user <user>\",\n \"Operate on this user's data (requires admin credentials)\",\n ).env(\"PL_TARGET_USER\"),\n];\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { listProjects } from \"../../project_ops\";\nimport { formatTable, formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectListCommand(): Command {\n const cmd = new Command(\"list\").description(\"List all projects for the authenticated user.\");\n\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const projects = await listProjects(pl, projectListRid);\n\n if (flags.format === \"json\") {\n outputJson(\n projects.map((p) => ({\n id: p.id,\n rid: resourceIdToString(p.rid),\n label: p.label,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n } else {\n if (projects.length === 0) {\n outputText(\"No projects found.\");\n return;\n }\n\n outputText(\n formatTable(\n [\"ID\", \"RID\", \"LABEL\", \"CREATED\", \"LAST MODIFIED\"],\n projects.map((p) => [\n p.id,\n resourceIdToString(p.rid),\n p.label,\n formatDate(p.created),\n formatDate(p.lastModified),\n ]),\n ),\n );\n outputText(`\\n${projects.length} project(s)`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, getProjectInfo } from \"../../project_ops\";\nimport { formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectInfoCommand(): Command {\n const cmd = new Command(\"info\").description(\"Show detailed information about a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n const info = await getProjectInfo(pl, id, rid);\n\n if (flags.format === \"json\") {\n outputJson({\n id: info.id,\n rid: resourceIdToString(info.rid),\n label: info.label,\n schemaVersion: info.schemaVersion,\n blockCount: info.blockCount,\n blockIds: info.blockIds,\n created: info.created.toISOString(),\n lastModified: info.lastModified.toISOString(),\n });\n } else {\n outputText(`Project: ${info.label}`);\n outputText(`ID: ${info.id}`);\n outputText(`RID: ${resourceIdToString(info.rid)}`);\n outputText(`Schema: ${info.schemaVersion ?? \"(unknown)\"}`);\n outputText(`Blocks: ${info.blockCount}`);\n if (info.blockIds.length > 0) {\n for (const bid of info.blockIds) {\n outputText(` - ${bid}`);\n }\n }\n outputText(`Created: ${formatDate(info.created)}`);\n outputText(`Last Modified: ${formatDate(info.lastModified)}`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDuplicateCommand(): Command {\n const cmd = new Command(\"duplicate\").description(\n \"Duplicate a project within the same user. Auto-renames on collision by default.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"-n, --name <name>\", \"Name for the duplicate\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { rid: sourceRid } = await resolveProject(pl, projectListRid, project);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"duplicateProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, projectListRid);\n\n // Compute new label\n let newLabel: string;\n if (flags.name) {\n if (!flags.autoRename && existingLabels.includes(flags.name)) {\n throw new Error(`Project name \"${flags.name}\" already exists.`);\n }\n newLabel = existingLabels.includes(flags.name)\n ? deduplicateName(flags.name, existingLabels)\n : flags.name;\n } else {\n newLabel = deduplicateName(sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const projectResourceId = await newPrj.globalId;\n const projectId = resourceIdToString(projectResourceId);\n return { id: projectId, rid: projectResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({ id: result.id, rid: resourceIdToString(result.rid), label: result.label });\n } else {\n outputText(`Duplicated project as \"${result.label}\" (id: ${result.id})`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, renameProject } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectRenameCommand(): Command {\n const cmd = new Command(\"rename\").description(\"Rename a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.addOption(new Option(\"-n, --name <name>\", \"New name for the project\").makeOptionMandatory());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n\n await renameProject(pl, rid, flags.name);\n\n if (flags.format === \"json\") {\n outputJson({ id, rid: resourceIdToString(rid), label: flags.name });\n } else {\n outputText(`Renamed project to \"${flags.name}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, deleteProject, getProjectInfo } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDeleteCommand(): Command {\n const cmd = new Command(\"delete\").description(\n \"Delete a project. This permanently destroys all project data.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid, fieldName } = await resolveProject(pl, projectListRid, project);\n\n const info = await getProjectInfo(pl, id, rid);\n\n if (!flags.force) {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\n `Delete project \"${info.label}\" (${info.blockCount} blocks)? [y/N] `,\n resolve,\n );\n });\n if (answer.toLowerCase() !== \"y\") {\n outputText(\"Aborted.\");\n return;\n }\n } finally {\n rl.close();\n }\n }\n\n await deleteProject(pl, projectListRid, fieldName);\n\n if (flags.format === \"json\") {\n outputJson({ deleted: true, id, label: info.label });\n } else {\n outputText(`Deleted project \"${info.label}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n navigateToUserRoot,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function adminCopyProjectCommand(): Command {\n const cmd = new Command(\"copy-project\").description(\n \"Copy a project from one user to another. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--source-user <user>\",\n \"Username of the source project owner\",\n ).makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--source-project <project>\", \"Source project ID or label\").makeOptionMandatory(),\n );\n cmd.option(\n \"--target-user <user>\",\n \"Username of the target user (defaults to source-user for same-user copy)\",\n );\n cmd.option(\"-n, --name <name>\", \"Name for the copied project\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const targetUser = flags.targetUser ?? flags.sourceUser;\n\n const source = await navigateToUserRoot(pl, flags.sourceUser);\n const { rid: sourceRid } = await resolveProject(\n pl,\n source.projectListRid,\n flags.sourceProject,\n );\n\n const target =\n targetUser === flags.sourceUser ? source : await navigateToUserRoot(pl, targetUser);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"adminCopyProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, target.projectListRid);\n\n let newLabel: string = flags.name ?? sourceLabel;\n\n if (existingLabels.includes(newLabel)) {\n if (!flags.autoRename) {\n throw new Error(`Project name \"${newLabel}\" already exists for target user.`);\n }\n newLabel = deduplicateName(flags.name ?? sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(target.projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const prjResourceId = await newPrj.globalId;\n const prjId = resourceIdToString(prjResourceId);\n return { id: prjId, rid: prjResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({\n id: result.id,\n rid: resourceIdToString(result.rid),\n label: result.label,\n sourceUser: flags.sourceUser,\n targetUser,\n });\n } else {\n outputText(\n `Copied project from ${flags.sourceUser} to ${targetUser} as \"${result.label}\" (id: ${result.id}, rid: ${resourceIdToString(result.rid)})`,\n );\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { isPermissionDenied } from \"@milaboratories/pl-client\";\nimport { Command } from \"commander\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson, outputText, outputCsv } from \"../../output\";\n\nexport default function adminUserListCommand(): Command {\n const cmd = new Command(\"user-list\").description(\n \"List all known users' logins from a live server. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(\"csv\", [\"text\", \"json\", \"csv\"]), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n let users;\n try {\n users = await pl.listUsers();\n } catch (err) {\n if (isPermissionDenied(err))\n throw new Error(\n \"The server does not let this user list users. \" +\n \"Check the server option '--show-user-list-to' and the role of the user.\",\n { cause: err },\n );\n throw err;\n }\n const logins = users.map((u) => u.login).sort();\n if (flags.format === \"json\") outputJson(logins);\n else if (flags.format === \"text\") outputText(logins.join(\"\\n\"));\n else\n outputCsv(\n [\"login\"],\n logins.map((l) => [l]),\n );\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n ensureUserProjectList,\n listProjectIdentities,\n moveProjects,\n openUserRoot,\n} from \"../../project_ops\";\nimport type { MovedProject, ProjectIdentityWithLabel } from \"../../project_ops\";\nimport { formatTable, outputJson, outputText } from \"../../output\";\n\nexport default function adminDeleteUserCommand(): Command {\n const cmd = new Command(\"delete-user\").description(\n \"Delete a user account. Optionally re-homes the user's projects to another user first. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\"<user>\", \"Username of the account to delete\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--move-projects-to <user>\",\n \"Re-home the deleted user's projects to this user before deleting the account\",\n ),\n );\n cmd.addOption(\n new Option(\n \"--delete-projects\",\n \"Delete the user's projects along with the account, losing their data\",\n ),\n );\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (user: string, flags) => {\n // The two modes are alternatives, not a combination: one keeps the projects, the other\n // destroys them, and a request for both says nothing about which was meant.\n if (flags.moveProjectsTo && flags.deleteProjects) {\n throw new Error(\"--move-projects-to and --delete-projects are mutually exclusive\");\n }\n if (flags.moveProjectsTo === user) {\n throw new Error(\"--move-projects-to must name a different user than the one being deleted\");\n }\n // Caught here as well as server-side, where it is authoritative: the operator gets the reason\n // instead of a failure from whichever lookup happens to run first.\n if (flags.adminUser === user) {\n throw new Error(\n `Refusing to delete \"${user}\" — it is the account these credentials authenticate as.`,\n );\n }\n\n const pl = await connectClient(flags);\n try {\n const source = await openUserRoot(pl, user);\n // No project list means the account never opened the app, so it owns nothing — a state to\n // delete straight through, not to fail on.\n const projects =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n\n // Neither mode given while the account still owns projects: refuse rather than pick. Both\n // defaults are wrong to assume — one silently destroys data, the other silently hands it to\n // someone. An account with no projects has nothing to decide about, so it just proceeds.\n if (projects.length > 0 && !flags.moveProjectsTo && !flags.deleteProjects) {\n throw new Error(\n `User \"${user}\" owns ${projects.length} project(s). Pass --move-projects-to <user> to ` +\n \"re-home them, or --delete-projects to delete them with the account.\",\n );\n }\n\n const confirmed = await confirmDeletion(user, projects, flags);\n if (!confirmed) {\n outputText(\"Aborted.\");\n return;\n }\n\n let moved: MovedProject[] = [];\n if (flags.moveProjectsTo && projects.length > 0) {\n const target = await openUserRoot(pl, flags.moveProjectsTo);\n // Created if the target has none, so re-homing to a user who has never opened the app\n // works rather than failing halfway with the account still present.\n const targetList = await ensureUserProjectList(pl, target.userRoot);\n moved = await moveProjects(pl, source.projectListRid!, targetList);\n }\n\n // deleteUser takes the root and everything still attached to it. The listing, the prompt and\n // the move each ran in an earlier transaction, so re-read: a project attached since then would\n // be destroyed without ever being reviewed.\n const remaining =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n assertProjectsAccountedFor(user, flags, projects, remaining);\n\n const report = await pl.deleteUser(user);\n\n if (flags.format === \"json\") {\n outputJson({\n deleted: true,\n user,\n movedTo: flags.moveProjectsTo ?? null,\n movedProjects: moved,\n deletedProjects: flags.moveProjectsTo ? [] : remaining.map((p) => p.label),\n userRootId: report.userRootId === undefined ? null : report.userRootId.toString(),\n userRootDeleted: report.userRootDeleted,\n revokedGrants: report.revokedGrants,\n removedIdentityIndexEntries: report.removedIdentityIndexEntries,\n });\n } else {\n outputText(renderResult(user, flags.moveProjectsTo, moved, remaining));\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\n/**\n * Refuses while the root holds a project the operator never agreed to lose — attached after the\n * listing, or left behind by the move.\n *\n * A last read, not a lock: it closes the prompt-sized window, not the round trip that follows.\n */\nfunction assertProjectsAccountedFor(\n user: string,\n flags: { moveProjectsTo?: string },\n approved: ProjectIdentityWithLabel[],\n remaining: ProjectIdentityWithLabel[],\n): void {\n if (flags.moveProjectsTo) {\n if (remaining.length === 0) return;\n throw new Error(\n `User \"${user}\" still owns ${remaining.length} project(s) after the move: ` +\n `${remaining.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"the projects were attached while the move ran. Re-run the command to move them too.\",\n );\n }\n\n const approvedIds = new Set(approved.map((p) => p.id));\n const unapproved = remaining.filter((p) => !approvedIds.has(p.id));\n if (unapproved.length === 0) return;\n throw new Error(\n `User \"${user}\" gained ${unapproved.length} project(s) since the list you confirmed: ` +\n `${unapproved.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"deleting it now would destroy them unreviewed. Re-run the command to see the current list.\",\n );\n}\n\n/** Asks the operator to confirm, naming the affected projects and their fate. */\nasync function confirmDeletion(\n user: string,\n projects: ProjectIdentityWithLabel[],\n flags: { moveProjectsTo?: string; force?: boolean },\n): Promise<boolean> {\n if (flags.force) return true;\n\n const fate = flags.moveProjectsTo\n ? `${projects.length} project(s) will move to \"${flags.moveProjectsTo}\"`\n : projects.length > 0\n ? `${projects.length} project(s) will be PERMANENTLY DELETED`\n : \"the account owns no projects\";\n\n process.stderr.write(`Delete user \"${user}\"? ${fate}.\\n`);\n if (projects.length > 0) {\n process.stderr.write(projects.map((p) => ` - ${p.label}`).join(\"\\n\") + \"\\n\");\n }\n\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\"Proceed? [y/N] \", resolve);\n });\n return answer.toLowerCase() === \"y\";\n } finally {\n rl.close();\n }\n}\n\nfunction renderResult(\n user: string,\n movedTo: string | undefined,\n moved: MovedProject[],\n projects: ProjectIdentityWithLabel[],\n): string {\n const lines: string[] = [];\n\n if (movedTo) {\n if (moved.length > 0) {\n lines.push(`Moved ${moved.length} project(s) from ${user} to ${movedTo}:`);\n lines.push(\n formatTable(\n [\"id\", \"name\", \"name in target\"],\n moved.map((p) => [p.id, p.sourceLabel, p.targetLabel]),\n ),\n );\n } else {\n lines.push(`User ${user} had no projects to move.`);\n }\n } else if (projects.length > 0) {\n lines.push(`Deleted ${projects.length} project(s) belonging to ${user}:`);\n lines.push(projects.map((p) => ` - ${p.label}`).join(\"\\n\"));\n }\n\n lines.push(`Deleted user \"${user}\".`);\n return lines.join(\"\\n\");\n}\n","import { Command } from \"commander\";\nimport { InstanceStatsContextTypeName, parseInstanceStats } from \"@milaboratories/pl-middle-layer\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson } from \"../../output\";\n\nexport default function adminInstanceStatsCommand(): Command {\n const cmd = new Command(\"instance-stats\").description(\"Show the instance statistics as JSON.\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const [context] = await pl.listSharedResourcesByType(InstanceStatsContextTypeName);\n if (context === undefined) throw new Error(\"The instance has no instance statistics.\");\n const kvs = await pl.withReadTx(\"instanceStats\", (tx) => tx.listKeyValuesString(context));\n outputJson(parseInstanceStats(kvs));\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import {\n asSignedResourceId,\n createSignedResourceId,\n isLocalResourceId,\n resourceIdFromString,\n type SignedResourceId,\n} from \"@milaboratories/pl-client\";\n\n/**\n * Admin and controller roles do not need resource signatures: an ID without a signature\n * is accepted by the backend for these roles.\n */\nexport function parseResourceId(raw: string): SignedResourceId {\n const str = raw.trim();\n if (str.includes(\"|\")) return asSignedResourceId(str);\n\n let id: bigint | undefined = resourceIdFromString(str);\n if (id === undefined && /^\\d+$/.test(str)) id = BigInt(str);\n if (id === undefined || id === 0n || isLocalResourceId(id))\n throw new Error(`not a global resource ID: ${raw}`);\n\n return createSignedResourceId(id);\n}\n","import { once } from \"node:events\";\nimport { Command, InvalidArgumentError, Option } from \"commander\";\nimport {\n isNotNullSignedResourceId,\n resourceIdToString,\n resourceType,\n resourceTypeToString,\n type FieldData,\n type KeyValue,\n type OptionalSignedResourceId,\n type ResourceData,\n type ResourceType,\n} from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { parseResourceId } from \"../../resource_id\";\n\nexport default function maintenanceListResourcesCommand(): Command {\n const cmd = new Command(\"list-resources\").description(\n \"List resources of one type as JSON lines, in ascending order of resource ID. \" +\n \"Resource data and key-value values are printed as JSON when they are valid JSON, \" +\n 'as text when they are valid UTF-8, and as {\"base64\": ...} in other cases. ' +\n \"Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"--type <name:version>\", \"Resource type to list (e.g. 'Blob/work:1')\")\n .argParser(parseResourceTypeArg)\n .makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--limit <n>\", \"Maximum number of resources to list. 0 lists all resources\")\n .argParser(parseNonNegativeInt)\n .default(0),\n );\n cmd.addOption(\n new Option(\n \"--after <resource-id>\",\n \"List only resources with IDs greater than this ID. \" +\n \"To get the next page, give the ID of the last resource of the previous page\",\n ).argParser(parseResourceId),\n );\n cmd.option(\n \"--load-fields\",\n \"Load the fields and the error of each resource ('fields' and 'error' keys)\",\n false,\n );\n cmd.option(\"--load-kv\", \"Load the key-value entries of each resource ('kv' key)\", false);\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const resources = await pl.withReadTx(\"listResources\", async (tx) => {\n const list = await tx.listResourcesByType(flags.type, {\n limit: flags.limit,\n after: flags.after,\n loadFields: flags.loadFields,\n });\n return await Promise.all(\n list.map(async (resource) => ({\n resource,\n kv: flags.loadKv ? await tx.listKeyValues(resource.id) : undefined,\n })),\n );\n });\n\n for (const { resource, kv } of resources) {\n const line = JSON.stringify(toJson(resource, flags.loadFields, kv)) + \"\\n\";\n // Wait for a slow reader: else the output collects in memory a second time.\n if (!process.stdout.write(line)) await once(process.stdout, \"drain\");\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\nfunction toJson(\n r: ResourceData,\n withFields: boolean,\n kv: KeyValue[] | undefined,\n): Record<string, unknown> {\n return {\n id: resourceIdToString(r.id),\n type: resourceTypeToString(r.type),\n kind: r.kind,\n originalId: optionalIdToString(r.originalResourceId),\n inputsLocked: r.inputsLocked,\n outputsLocked: r.outputsLocked,\n ready: r.resourceReady,\n final: r.final,\n data: r.data === undefined || r.data.length === 0 ? null : decodeBytes(r.data),\n // The backend sends the resource error as a field: without fields it is not known.\n ...(withFields\n ? { error: optionalIdToString(r.error), fields: r.fields.map(fieldToJson) }\n : {}),\n ...(kv === undefined\n ? {}\n : { kv: Object.fromEntries(kv.map((e) => [e.key, decodeBytes(e.value)])) }),\n };\n}\n\nfunction fieldToJson(f: FieldData): Record<string, unknown> {\n return {\n name: f.name,\n type: f.type,\n status: f.status,\n value: optionalIdToString(f.value),\n error: optionalIdToString(f.error),\n valueIsFinal: f.valueIsFinal,\n };\n}\n\nfunction optionalIdToString(id: OptionalSignedResourceId): string | null {\n return isNotNullSignedResourceId(id) ? resourceIdToString(id) : null;\n}\n\n/** JSON value when the bytes are valid JSON, text when valid UTF-8, {\"base64\": ...} otherwise. */\nfunction decodeBytes(bytes: Uint8Array): unknown {\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n return { base64: Buffer.from(bytes).toString(\"base64\") };\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction parseResourceTypeArg(value: string): ResourceType {\n const sep = value.lastIndexOf(\":\");\n if (sep <= 0 || sep === value.length - 1)\n throw new InvalidArgumentError(`expected <name>:<version>, e.g. 'Blob/work:1': ${value}`);\n return resourceType(value.slice(0, sep), value.slice(sep + 1));\n}\n\nfunction parseNonNegativeInt(value: string): number {\n const n = Number(value);\n if (!Number.isInteger(n) || n < 0)\n throw new InvalidArgumentError(`not a non-negative integer: ${value}`);\n return n;\n}\n","import { Command, Option } from \"commander\";\nimport { isNotNullSignedResourceId, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputText } from \"../../output\";\nimport { parseResourceId } from \"../../resource_id\";\n\nconst DefaultErrorMessage =\n \"Manual error set by administrator to trigger blocks re-run. \" +\n \"Run block once again to get rid of it.\";\n\nexport default function maintenanceSetResourceErrorCommand(): Command {\n const cmd = new Command(\"set-resource-error\").description(\n \"Put an error on one or more resources in a single transaction. \" +\n \"Resources that already have an error are skipped. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\n \"<resource-id...>\",\n \"Resource IDs: as printed by the server (NG:0x1A2B), as decimal numbers, \" +\n \"or as signed IDs (<decimal ID>|<signature hex>)\",\n );\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"-m, --error-message <message>\", \"Error message to put on the resources\").default(\n DefaultErrorMessage,\n ),\n );\n cmd.option(\n \"--skip-missing\",\n \"Skip resources that do not exist instead of failing the whole transaction\",\n false,\n );\n\n cmd.action(async (rawIds: string[], flags) => {\n // Parse all IDs before the connection, so that a typo does not leave a half-done job.\n const ids = rawIds.map(parseResourceId);\n\n const pl = await connectClient(flags);\n try {\n const result = await pl.withWriteTx(\"setResourceError\", async (tx) => {\n const found = await Promise.all(\n ids.map(async (id) => ({\n id,\n data: flags.skipMissing\n ? await tx.getResourceDataIfExists(id, true)\n : await tx.getResourceData(id, true, true),\n })),\n );\n\n const missing = found.filter((r) => r.data === undefined).map((r) => r.id);\n const resources = found.flatMap((r) => (r.data === undefined ? [] : [r.data]));\n const targets = resources.filter((r) => !isNotNullSignedResourceId(r.error));\n const skipped = resources.filter((r) => isNotNullSignedResourceId(r.error));\n\n if (targets.length > 0) {\n // One error resource for all targets: the backend links it to each target separately.\n const error = tx.createError(flags.errorMessage);\n for (const r of targets) tx.setResourceError(r.id, error);\n await tx.commit();\n }\n\n return { targets, skipped, missing };\n });\n\n for (const id of result.missing)\n outputText(`skipped ${resourceIdToString(id)}: resource does not exist`);\n for (const r of result.skipped)\n outputText(`skipped ${resourceIdToString(r.id)}: resource already has an error`);\n for (const r of result.targets) outputText(`error set ${resourceIdToString(r.id)}`);\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport projectListCommand from \"./cmd/project/list\";\nimport projectInfoCommand from \"./cmd/project/info\";\nimport projectDuplicateCommand from \"./cmd/project/duplicate\";\nimport projectRenameCommand from \"./cmd/project/rename\";\nimport projectDeleteCommand from \"./cmd/project/delete\";\nimport adminCopyProjectCommand from \"./cmd/admin/copy-project\";\nimport adminUserListCommand from \"./cmd/admin/user-list\";\nimport adminDeleteUserCommand from \"./cmd/admin/delete-user\";\nimport adminInstanceStatsCommand from \"./cmd/admin/instance-stats\";\nimport maintenanceListResourcesCommand from \"./cmd/maintenance/list-resources\";\nimport maintenanceSetResourceErrorCommand from \"./cmd/maintenance/set-resource-error\";\n\nexport function buildProgram(): Command {\n const program = new Command();\n program.name(\"pl-cli\").description(\"Platforma command-line client\");\n\n const project = new Command(\"project\").description(\"Manage projects\");\n project.addCommand(projectListCommand());\n project.addCommand(projectInfoCommand());\n project.addCommand(projectDuplicateCommand());\n project.addCommand(projectRenameCommand());\n project.addCommand(projectDeleteCommand());\n program.addCommand(project);\n\n const admin = new Command(\"admin\").description(\n \"Admin operations (requires controller credentials)\",\n );\n admin.addCommand(adminCopyProjectCommand());\n admin.addCommand(adminUserListCommand());\n admin.addCommand(adminDeleteUserCommand());\n admin.addCommand(adminInstanceStatsCommand());\n program.addCommand(admin);\n\n const maintenance = new Command(\"maintenance\").description(\n \"Low-level server state repair (requires admin/controller credentials)\",\n );\n maintenance.addCommand(maintenanceListResourcesCommand());\n maintenance.addCommand(maintenanceSetResourceErrorCommand());\n program.addCommand(maintenance);\n\n return program;\n}\n\nexport async function run(argv: string[] = process.argv): Promise<void> {\n await buildProgram().parseAsync(argv);\n}\n"],"mappings":";;;;;;;;AAUA,eAAsBkB,EAAc,GAMd;CAQpB,OAPIC,EAAM,aAAaA,EAAM,gBACpBjB,EAAwB;EAC7B,SAASiB,EAAM;EACf,WAAWA,EAAM;EACjB,eAAeA,EAAM;CACvB,CAAC,IAEIH,EAAmB;EACxB,SAASG,EAAM;EACf,MAAMA,EAAM;EACZ,UAAUA,EAAM;CAClB,CAAC;AACH;AASA,eAAsBC,EAAQ,GAOkC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;CAMpE,AALAK,EAAQ,WAAWN,EAAmB,CAAC,GACvCM,EAAQ,WAAWD,EAAmB,CAAC,GACvCC,EAAQ,WAAWK,EAAwB,CAAC,GAC5CL,EAAQ,WAAWmB,EAAqB,CAAC,GACzCnB,EAAQ,WAAWqB,EAAqB,CAAC,GACzCiF,EAAQ,WAAWtG,CAAO;CAE1B,IAAMuG,IAAQ,IAAI5G,EAAQ,OAAO,CAAC,CAAC,YACjC,oDACF;CAKA,AAJA4G,EAAM,WAAW7E,EAAwB,CAAC,GAC1C6E,EAAM,WAAWxE,EAAqB,CAAC,GACvCwE,EAAM,WAAWjE,GAAuB,CAAC,GACzCiE,EAAM,WAAWhD,GAA0B,CAAC,GAC5C+C,EAAQ,WAAWC,CAAK;CAExB,IAAMC,IAAc,IAAI7G,EAAQ,aAAa,CAAC,CAAC,YAC7C,uEACF;CAKA,OAJA6G,EAAY,WAAWrC,GAAgC,CAAC,GACxDqC,EAAY,WAAWX,GAAmC,CAAC,GAC3DS,EAAQ,WAAWE,CAAW,GAEvBF;AACT;AAEA,eAAsBG,GAAI,IAAiB,QAAQ,MAAqB;CACtE,MAAMJ,EAAa,CAAC,CAAC,WAAWK,CAAI;AACtC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@platforma-sdk/pl-cli",
3
- "version": "0.12.17",
3
+ "version": "0.13.0",
4
4
  "description": "CLI for Platforma server state manipulation",
5
5
  "license": "UNLICENSED",
6
6
  "bin": {
package/src/cli.ts CHANGED
@@ -10,8 +10,6 @@ import adminDeleteUserCommand from "./cmd/admin/delete-user";
10
10
  import adminInstanceStatsCommand from "./cmd/admin/instance-stats";
11
11
  import maintenanceListResourcesCommand from "./cmd/maintenance/list-resources";
12
12
  import maintenanceSetResourceErrorCommand from "./cmd/maintenance/set-resource-error";
13
- import maintenanceControllerListCommand from "./cmd/maintenance/controller/list";
14
- import maintenanceControllerRerunFixupsCommand from "./cmd/maintenance/controller/rerun-fixups";
15
13
 
16
14
  export function buildProgram(): Command {
17
15
  const program = new Command();
@@ -39,12 +37,6 @@ export function buildProgram(): Command {
39
37
  );
40
38
  maintenance.addCommand(maintenanceListResourcesCommand());
41
39
  maintenance.addCommand(maintenanceSetResourceErrorCommand());
42
- const controller = new Command("controller").description(
43
- "Inspect registered controllers and their resources fixups",
44
- );
45
- controller.addCommand(maintenanceControllerListCommand());
46
- controller.addCommand(maintenanceControllerRerunFixupsCommand());
47
- maintenance.addCommand(controller);
48
40
  program.addCommand(maintenance);
49
41
 
50
42
  return program;
@@ -1,10 +0,0 @@
1
- import { PlTransaction } from '@milaboratories/pl-client';
2
- /**
3
- * Key of the resources fixup level in the key-value store of a controller.
4
- * Must match MetadataResourcesFixupLevel in the backend (controllers/shared/ctlsdk/resources_fixup.go).
5
- */
6
- export declare const ResourcesFixupLevelKey = "ctl/ctlsdk/resourcesFixupLevel";
7
- /** Reads the resources fixup level of the controller as text: a number, "not set" or "invalid". */
8
- export declare function readFixupLevel(tx: PlTransaction, controllerType: string): Promise<string>;
9
- /** Sets the resources fixup level of the controller to 0. The transaction must be writable. */
10
- export declare function resetFixupLevel(tx: PlTransaction, controllerType: string): void;
@@ -1,2 +0,0 @@
1
- import { Command } from 'commander';
2
- export default function maintenanceControllerListCommand(): Command;
@@ -1,2 +0,0 @@
1
- import { Command } from 'commander';
2
- export default function maintenanceControllerRerunFixupsCommand(): Command;
@@ -1,27 +0,0 @@
1
- import type { PlTransaction } from "@milaboratories/pl-client";
2
-
3
- /**
4
- * Key of the resources fixup level in the key-value store of a controller.
5
- * Must match MetadataResourcesFixupLevel in the backend (controllers/shared/ctlsdk/resources_fixup.go).
6
- */
7
- export const ResourcesFixupLevelKey = "ctl/ctlsdk/resourcesFixupLevel";
8
-
9
- /** The backend keeps the level as a big-endian uint32. */
10
- const ResourcesFixupLevelSize = 4;
11
-
12
- /** Reads the resources fixup level of the controller as text: a number, "not set" or "invalid". */
13
- export async function readFixupLevel(tx: PlTransaction, controllerType: string): Promise<string> {
14
- const value = await tx.getControllerKValueIfExists(controllerType, ResourcesFixupLevelKey);
15
- if (value === undefined) return "not set";
16
- if (value.length !== ResourcesFixupLevelSize) return `invalid (${value.length} bytes)`;
17
- return String(Buffer.from(value).readUInt32BE(0));
18
- }
19
-
20
- /** Sets the resources fixup level of the controller to 0. The transaction must be writable. */
21
- export function resetFixupLevel(tx: PlTransaction, controllerType: string): void {
22
- tx.setControllerKValue(
23
- controllerType,
24
- ResourcesFixupLevelKey,
25
- new Uint8Array(ResourcesFixupLevelSize),
26
- );
27
- }
@@ -1,41 +0,0 @@
1
- import { Command } from "commander";
2
- import { listRegisteredControllers, resourceIdToString } from "@milaboratories/pl-client";
3
- import { connectClient } from "../../../base_command";
4
- import { addOptions, AdminAuthOptions, GlobalOptions } from "../../../cmd-opts";
5
- import { formatTable, outputCsv, outputJson, outputText } from "../../../output";
6
- import { readFixupLevel } from "./fixup_level";
7
-
8
- export default function maintenanceControllerListCommand(): Command {
9
- const cmd = new Command("list").description(
10
- "List the controllers registered in the backend, with their IDs and resources fixup levels. " +
11
- "Requires admin/controller credentials.",
12
- );
13
-
14
- addOptions(cmd, GlobalOptions("text", ["text", "json", "csv"]), AdminAuthOptions());
15
-
16
- cmd.action(async (flags) => {
17
- const pl = await connectClient(flags);
18
- try {
19
- const controllers = await pl.withReadTx("listControllers", async (tx) => {
20
- const list = await listRegisteredControllers(tx);
21
- return await Promise.all(
22
- list.map(async (c) => ({
23
- id: resourceIdToString(c.id),
24
- type: c.type,
25
- fixupLevel: await readFixupLevel(tx, c.type),
26
- })),
27
- );
28
- });
29
-
30
- const headers = ["id", "type", "fixup level"];
31
- const rows = controllers.map((c) => [c.id, c.type, c.fixupLevel]);
32
- if (flags.format === "json") outputJson(controllers);
33
- else if (flags.format === "csv") outputCsv(headers, rows);
34
- else outputText(formatTable(headers, rows));
35
- } finally {
36
- await pl.close();
37
- }
38
- });
39
-
40
- return cmd;
41
- }
@@ -1,103 +0,0 @@
1
- import { Command, Option } from "commander";
2
- import {
3
- anyResourceIdToBigint,
4
- listRegisteredControllers,
5
- resourceIdToString,
6
- type PlTransaction,
7
- type RegisteredController,
8
- type SignedResourceId,
9
- } from "@milaboratories/pl-client";
10
- import { connectClient } from "../../../base_command";
11
- import { addOptions, AddressOptions, AdminAuthOptions } from "../../../cmd-opts";
12
- import { outputText } from "../../../output";
13
- import { parseResourceId } from "../../../resource_id";
14
- import { readFixupLevel, resetFixupLevel } from "./fixup_level";
15
-
16
- function collect<T>(parse: (raw: string) => T) {
17
- return (raw: string, previous: T[] | undefined): T[] => [...(previous ?? []), parse(raw)];
18
- }
19
-
20
- export default function maintenanceControllerRerunFixupsCommand(): Command {
21
- const cmd = new Command("rerun-fixups").description(
22
- "Set the resources fixup level of the selected controllers to 0 in a single transaction. " +
23
- "On its next start, each controller applies all its one-time resources fixups again. " +
24
- "Use this after a rollback to a backend version without resources fixups. " +
25
- "Select controllers with --controller-name and --controller-id " +
26
- "(see 'maintenance controller list'). Requires admin/controller credentials.",
27
- );
28
-
29
- addOptions(cmd, AddressOptions(), AdminAuthOptions());
30
- cmd.addOption(
31
- new Option(
32
- "--controller-name <type>",
33
- 'Controller type, as the controller registers it (for example "File/Manager"). ' +
34
- "Repeat the option to select more controllers",
35
- ).argParser(collect((raw) => raw)),
36
- );
37
- cmd.addOption(
38
- new Option(
39
- "--controller-id <resource-id>",
40
- "Controller ID, as 'maintenance controller list' prints it. " +
41
- "Repeat the option to select more controllers",
42
- ).argParser(collect(parseResourceId)),
43
- );
44
-
45
- cmd.action(async (flags) => {
46
- const names: string[] = flags.controllerName ?? [];
47
- const ids: SignedResourceId[] = flags.controllerId ?? [];
48
- if (names.length === 0 && ids.length === 0)
49
- throw new Error("select at least one controller with --controller-name or --controller-id");
50
-
51
- const pl = await connectClient(flags);
52
- try {
53
- const reset = await pl.withWriteTx("rerunControllerFixups", async (tx) => {
54
- const selected = await selectControllers(tx, names, ids);
55
- const levels = await Promise.all(
56
- selected.map(async (c) => ({ controller: c, level: await readFixupLevel(tx, c.type) })),
57
- );
58
-
59
- for (const c of selected) resetFixupLevel(tx, c.type);
60
- await tx.commit();
61
-
62
- return levels;
63
- });
64
-
65
- for (const { controller, level } of reset)
66
- outputText(
67
- `${controller.type} (${resourceIdToString(controller.id)}): ` +
68
- `resources fixup level ${level} -> 0`,
69
- );
70
- outputText("Restart the backend to apply the resources fixups.");
71
- } finally {
72
- await pl.close();
73
- }
74
- });
75
-
76
- return cmd;
77
- }
78
-
79
- /** Resolves the selected controllers. Throws when a name or an ID matches no registered controller. */
80
- async function selectControllers(
81
- tx: PlTransaction,
82
- names: string[],
83
- ids: SignedResourceId[],
84
- ): Promise<RegisteredController[]> {
85
- const registered = await listRegisteredControllers(tx);
86
- const byType = new Map<string, RegisteredController>();
87
-
88
- for (const name of names) {
89
- const controller = registered.find((c) => c.type === name);
90
- if (controller === undefined) throw new Error(`controller "${name}" is not registered`);
91
- byType.set(controller.type, controller);
92
- }
93
-
94
- for (const id of ids) {
95
- const wanted = anyResourceIdToBigint(id);
96
- const controller = registered.find((c) => anyResourceIdToBigint(c.id) === wanted);
97
- if (controller === undefined)
98
- throw new Error(`no registered controller has ID ${resourceIdToString(id)}`);
99
- byType.set(controller.type, controller);
100
- }
101
-
102
- return [...byType.values()];
103
- }