@tuanhv/op-cli 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,309 @@
1
+ import { OpCliError, refuseCombined, unknownIfUnfinished, writeFailure } from "../core/errors.js";
2
+ import { buildWpFilters, parseSort } from "../core/filters.js";
3
+ import { apiPatchRaw, apiPostRaw } from "../core/http.js";
4
+ import { halRefId } from "../core/hal.js";
5
+ import { parseProjectOverride } from "../context/profile.js";
6
+ import { addFilterFlags, collectOptional, rawListFlags, resolveListFlags, } from "./wp.js";
7
+ import { addQueryScopeOptions, connectQuery, fetchQuery, flattenQueryRecord, QUERIES_COLLECTION, refuseDefault, renderQueryRecord, resolveSavedQuery, } from "./query.js";
8
+ const QUERY_FIELDS = Object.keys(flattenQueryRecord({}));
9
+ const CREATE_WORDING = {
10
+ action: "create",
11
+ unknown: "whether the query was created is unknown",
12
+ check: "run op-cli query list to see whether the query exists before repeating the command.",
13
+ };
14
+ /** What to say when an update may or may not have landed. */
15
+ function updateWording(id) {
16
+ return {
17
+ action: "update",
18
+ unknown: "whether the query was changed is unknown",
19
+ check: `run op-cli query get ${String(id)} to see the stored values before repeating the command.`,
20
+ };
21
+ }
22
+ /** The view flags every write accepts; one spelling for both commands. */
23
+ function addViewOptions(command) {
24
+ return command
25
+ .option("--public [bool]", "visible to everybody: true or false (bare means true)")
26
+ .option("--starred [bool]", "starred for you: true or false (bare means true)")
27
+ .option("--sums [bool]", "show sums: true or false (bare means true)")
28
+ .option("--hierarchies [bool]", "show the work package hierarchy: true or false (bare means true)")
29
+ .option("--sort <field[:asc|desc]>", "sort order; repeat for more fields", collectOptional)
30
+ .option("--columns <list>", "comma-separated column names, in order")
31
+ .option("--group-by <field>", "group results by this field")
32
+ .option("--json", "emit a flat JSON record")
33
+ .option("--fields <list>", "comma-separated fields to show");
34
+ }
35
+ function booleanFlag(raw, flag) {
36
+ if (raw === undefined || raw === true) {
37
+ return raw;
38
+ }
39
+ const lowered = String(raw).trim().toLowerCase();
40
+ if (lowered !== "true" && lowered !== "false") {
41
+ throw new OpCliError("USAGE_ERROR", `--${flag} accepts true or false, not "${String(raw)}".`, `pass --${flag}, --${flag} true, or --${flag} false.`);
42
+ }
43
+ return lowered === "true";
44
+ }
45
+ function viewOf(options, mode) {
46
+ const attributes = {};
47
+ const links = {};
48
+ const flags = [
49
+ ["public", "public", options.public],
50
+ ["starred", "starred", options.starred],
51
+ ["sums", "sums", options.sums],
52
+ ["hierarchies", "showHierarchies", options.hierarchies],
53
+ ];
54
+ for (const [flag, attribute, raw] of flags) {
55
+ const value = booleanFlag(raw, flag);
56
+ if (value !== undefined) {
57
+ attributes[attribute] = value;
58
+ }
59
+ }
60
+ const sort = options.sort;
61
+ if (sort !== undefined) {
62
+ const clears = mode === "update" && sort.length === 1 && sort[0]?.trim() === "";
63
+ links.sortBy = clears
64
+ ? []
65
+ : parseSort(sort).map(([field, direction]) => ({
66
+ href: `${QUERIES_COLLECTION}/sort_bys/${field}-${direction}`,
67
+ }));
68
+ }
69
+ if (options.columns !== undefined) {
70
+ if (options.columns.trim() === "" && mode === "update") {
71
+ links.columns = [];
72
+ }
73
+ else {
74
+ const names = options.columns.split(",").map((name) => name.trim());
75
+ if (names.some((name) => name === "")) {
76
+ throw new OpCliError("USAGE_ERROR", "--columns needs a comma-separated list of column names, none empty.", "pass e.g. --columns id,subject,status.");
77
+ }
78
+ links.columns = names.map((name) => ({
79
+ href: `${QUERIES_COLLECTION}/columns/${name}`,
80
+ }));
81
+ }
82
+ }
83
+ if (options.groupBy !== undefined) {
84
+ const field = options.groupBy.trim();
85
+ if (field === "") {
86
+ if (mode === "create") {
87
+ throw new OpCliError("USAGE_ERROR", "--group-by needs a field name.", "pass e.g. --group-by status; leave the flag out for no grouping.");
88
+ }
89
+ links.groupBy = { href: null };
90
+ }
91
+ else {
92
+ links.groupBy = { href: `${QUERIES_COLLECTION}/group_bys/${field}` };
93
+ }
94
+ }
95
+ return { attributes, links };
96
+ }
97
+ /** The Query filter id a work package filter name goes by. */
98
+ function queryFilterId(name) {
99
+ switch (name) {
100
+ case "assigned_to":
101
+ return "assignee";
102
+ case "created_at":
103
+ return "createdAt";
104
+ case "updated_at":
105
+ return "updatedAt";
106
+ default:
107
+ return name;
108
+ }
109
+ }
110
+ /** Filters whose values are linked resources, by the collection they live in. */
111
+ const LINKED_VALUES = {
112
+ status: "statuses",
113
+ type: "types",
114
+ assignee: "users",
115
+ responsible: "users",
116
+ author: "users",
117
+ watcher: "users",
118
+ version: "versions",
119
+ observedInVersion: "versions",
120
+ category: "categories",
121
+ sprint: "sprints",
122
+ backlogBucket: "backlog_buckets",
123
+ priority: "priorities",
124
+ parent: "work_packages",
125
+ };
126
+ /** One filter clause as a Query filter instance in HAL form. */
127
+ export function queryFilterInstance(clause) {
128
+ const id = queryFilterId(clause.name);
129
+ const links = {
130
+ filter: { href: `${QUERIES_COLLECTION}/filters/${id}` },
131
+ operator: {
132
+ href: `${QUERIES_COLLECTION}/operators/${encodeURIComponent(clause.operator)}`,
133
+ },
134
+ };
135
+ const collection = LINKED_VALUES[id];
136
+ if (collection !== undefined) {
137
+ links.values = clause.values.map((value) => ({ href: `/api/v3/${collection}/${value}` }));
138
+ return { _links: links };
139
+ }
140
+ return {
141
+ values: id === "backlogInbox" ? [true] : [...clause.values],
142
+ _links: links,
143
+ };
144
+ }
145
+ /** The filters the flags name, without the project scope a query keeps elsewhere. */
146
+ function queryFilters(flags) {
147
+ return buildWpFilters({ ...flags, project: undefined, includeSubprojects: undefined }, new Date())
148
+ .filter((clause) => clause.name !== "project" && clause.name !== "subprojectId")
149
+ .map(queryFilterInstance);
150
+ }
151
+ const PROJECT_ONLY_FLAGS = [
152
+ ["version", "--version"],
153
+ ["observedIn", "--observed-in"],
154
+ ["category", "--category"],
155
+ ["sprint", "--sprint"],
156
+ ["bucket", "--bucket"],
157
+ ];
158
+ function requireProjectForNames(options, projectId) {
159
+ if (projectId !== undefined) {
160
+ return;
161
+ }
162
+ for (const [key, flag] of PROJECT_ONLY_FLAGS) {
163
+ const value = options[key];
164
+ if (Array.isArray(value) && value.length > 0) {
165
+ throw new OpCliError("USAGE_ERROR", `${flag} needs a project in context to resolve names.`, "pass --project <name-or-id> or set a default project on the profile.");
166
+ }
167
+ }
168
+ }
169
+ async function resolvedFilters(runtime, profile, options, projectId) {
170
+ requireProjectForNames(options, projectId);
171
+ const resolved = await resolveListFlags({ ...runtime, writeBytes: () => undefined }, projectId === undefined ? { ...profile, project: undefined } : profile, options);
172
+ return queryFilters(resolved);
173
+ }
174
+ function checkFields(fields) {
175
+ if (fields === undefined) {
176
+ return;
177
+ }
178
+ const unknown = fields.split(",").map((name) => name.trim()).find((name) => name !== "" && !QUERY_FIELDS.includes(name));
179
+ if (unknown !== undefined) {
180
+ throw new OpCliError("USAGE_ERROR", `field "${unknown}" is not a column. Valid fields: ${QUERY_FIELDS.join(", ")}.`, "run op-cli query get to list every available field.");
181
+ }
182
+ }
183
+ function checkName(raw, flag) {
184
+ const name = raw.trim();
185
+ if (name === "") {
186
+ throw new OpCliError("USAGE_ERROR", `${flag === "name" ? "the query name" : "--name"} cannot be blank.`, "give the query a name.");
187
+ }
188
+ return name;
189
+ }
190
+ function registerCreate(query, runtime) {
191
+ addViewOptions(addFilterFlags(query
192
+ .command("create")
193
+ .description("Create a saved work package query")
194
+ .argument("<name>", "name of the new query")
195
+ .option("--global", "make a query that belongs to no project"))).action(async (rawName, options) => {
196
+ runtime.setJsonMode(options.json === true);
197
+ const name = checkName(rawName, "name");
198
+ refuseCombined([options.global === true ? "--global" : undefined, options.project === undefined ? undefined : "--project"], "pass only one of --project or --global.");
199
+ const view = viewOf(options, "create");
200
+ // Flag conflicts among the filters are refused here, before any traffic.
201
+ queryFilters(rawListFlags(options));
202
+ const profile = await runtime.resolve({
203
+ profile: options.profile,
204
+ project: parseProjectOverride(options.project),
205
+ });
206
+ const projectId = options.global === true ? undefined : profile.project;
207
+ const filters = await resolvedFilters(runtime, profile, options, projectId);
208
+ const payload = {
209
+ name,
210
+ ...view.attributes,
211
+ ...(options.includeSubprojects === undefined
212
+ ? {}
213
+ : { includeSubprojects: options.includeSubprojects }),
214
+ ...(filters.length > 0 ? { filters } : {}),
215
+ _links: {
216
+ project: projectId === undefined
217
+ ? { href: null }
218
+ : { href: `/api/v3/projects/${String(projectId)}` },
219
+ ...view.links,
220
+ },
221
+ };
222
+ const response = await unknownIfUnfinished(() => apiPostRaw(profile.instanceUrl, profile.apiKey, QUERIES_COLLECTION, payload), CREATE_WORDING);
223
+ if (response.status >= 400) {
224
+ throw writeFailure(response.status, response.body, CREATE_WORDING);
225
+ }
226
+ const record = flattenQueryRecord(response.body);
227
+ renderQueryRecord(runtime, options, record, `query ${String(record.id)} was created`);
228
+ });
229
+ }
230
+ /**
231
+ * The project whose names the filter flags resolve against: none for
232
+ * --global, the one given by --project, otherwise the project of the query
233
+ * being changed when a flag needs one, else the profile's default.
234
+ */
235
+ async function filterProjectOf(connection, ref, options) {
236
+ if (options.global === true) {
237
+ return undefined;
238
+ }
239
+ if (options.project !== undefined) {
240
+ return connection.profile.project;
241
+ }
242
+ const needsProject = PROJECT_ONLY_FLAGS.some(([key]) => {
243
+ const value = options[key];
244
+ return Array.isArray(value) && value.length > 0;
245
+ });
246
+ if (!needsProject) {
247
+ return connection.profile.project;
248
+ }
249
+ const existing = (await fetchQuery(connection, ref));
250
+ const href = existing._links?.project?.href;
251
+ return halRefId(typeof href === "string" ? href : null) ?? undefined;
252
+ }
253
+ function registerUpdate(query, runtime) {
254
+ addQueryScopeOptions(addViewOptions(addFilterFlags(query
255
+ .command("update")
256
+ .description("Change a saved query by id or name; only the flags you pass change")
257
+ .argument("<id-or-name>", "query id or exact name")
258
+ .option("--name <text>", "new name")
259
+ .option("--clear-filters", "remove every filter"), false))).action(async (reference, options) => {
260
+ runtime.setJsonMode(options.json === true);
261
+ refuseDefault(reference);
262
+ const name = options.name === undefined ? undefined : checkName(options.name, "--name");
263
+ checkFields(options.fields);
264
+ const view = viewOf(options, "update");
265
+ const named = queryFilters(rawListFlags(options));
266
+ refuseCombined([options.clearFilters === true ? "--clear-filters" : undefined, named.length > 0 ? "a filter flag" : undefined], "--clear-filters removes every filter; it cannot be combined with filter flags.");
267
+ const touches = name !== undefined
268
+ || options.clearFilters === true
269
+ || named.length > 0
270
+ || options.includeSubprojects !== undefined
271
+ || Object.keys(view.attributes).length > 0
272
+ || Object.keys(view.links).length > 0;
273
+ if (!touches) {
274
+ throw new OpCliError("USAGE_ERROR", "query update needs at least one thing to change.", "pass --name, --clear-filters, a filter flag, or a view flag such as --sort or --public.");
275
+ }
276
+ const connection = await connectQuery(runtime, options);
277
+ const ref = await resolveSavedQuery(connection, reference);
278
+ const wording = updateWording(ref.id);
279
+ const { profile } = connection;
280
+ const filterProject = named.length > 0
281
+ ? await filterProjectOf(connection, ref, options)
282
+ : undefined;
283
+ const filters = named.length > 0
284
+ ? await resolvedFilters(runtime, { ...profile, project: filterProject }, options, filterProject)
285
+ : [];
286
+ const links = view.links;
287
+ const payload = {
288
+ ...(name === undefined ? {} : { name }),
289
+ ...view.attributes,
290
+ ...(options.includeSubprojects === undefined
291
+ ? {}
292
+ : { includeSubprojects: options.includeSubprojects }),
293
+ ...(options.clearFilters === true ? { filters: [] } : {}),
294
+ ...(named.length > 0 ? { filters } : {}),
295
+ ...(Object.keys(links).length > 0 ? { _links: links } : {}),
296
+ };
297
+ const response = await unknownIfUnfinished(() => apiPatchRaw(profile.instanceUrl, profile.apiKey, `${QUERIES_COLLECTION}/${String(ref.id)}`, payload), wording);
298
+ if (response.status >= 400) {
299
+ throw writeFailure(response.status, response.body, wording);
300
+ }
301
+ const record = flattenQueryRecord(response.body);
302
+ renderQueryRecord(runtime, options, record, `query ${String(record.id ?? ref.id)} was updated`);
303
+ });
304
+ }
305
+ export function registerQueryWrite(query, runtime) {
306
+ registerCreate(query, runtime);
307
+ registerUpdate(query, runtime);
308
+ }
309
+ //# sourceMappingURL=query-write.js.map
@@ -0,0 +1,330 @@
1
+ import { formatCell, renderTable } from "../output/table.js";
2
+ import { registerQueryRun } from "./query-run.js";
3
+ import { registerQueryManage } from "./query-manage.js";
4
+ import { OpCliError, refuseCombined } from "../core/errors.js";
5
+ import { filtersQuery } from "../core/filters.js";
6
+ import { emitRows, PAGED_JSON_HELP, rowViewOf, } from "../core/define.js";
7
+ import { flattenHalLink, flattenHalRecord, halRefId } from "../core/hal.js";
8
+ import { apiGet } from "../core/http.js";
9
+ import { DEFAULT_PAGE_SIZE, allPageSize, halElements, parsePageSize, withPageSize, } from "../core/paginate.js";
10
+ import { isIdForm, matchByName, rankByCloseness } from "../context/resolve.js";
11
+ import { parseProjectOverride, } from "../context/profile.js";
12
+ import { registerQueryWrite } from "./query-write.js";
13
+ import { PROJECTS_COLLECTION, withMovedRetry, WORKSPACES_COLLECTION, } from "../context/projectref.js";
14
+ export const QUERIES_COLLECTION = "/api/v3/queries";
15
+ export const QUERY_COLUMNS = [
16
+ { title: "ID", field: "id" },
17
+ { title: "NAME", field: "name" },
18
+ { title: "PROJECT", field: "project" },
19
+ { title: "STARRED", field: "starred" },
20
+ { title: "PUBLIC", field: "public" },
21
+ ];
22
+ /** Declares the scope flags on one command; the single spelling of them. */
23
+ export function addQueryScopeOptions(command) {
24
+ return command
25
+ .option("--profile <name>", "use this profile for this command only")
26
+ .option("--project <name-or-id>", "only queries of this project")
27
+ .option("--global", "only queries that belong to no project")
28
+ .option("--all-projects", "queries of every project, ignoring the default project");
29
+ }
30
+ /** Flag misuse is refused here, before any traffic. */
31
+ export function checkQueryScopeFlags(options) {
32
+ refuseCombined([
33
+ options.global === true ? "--global" : undefined,
34
+ options.allProjects === true ? "--all-projects" : undefined,
35
+ options.project === undefined ? undefined : "--project",
36
+ ], "pass only one of --project, --global, or --all-projects.");
37
+ }
38
+ /** The scope the flags and the profile's default project select. */
39
+ export function queryScopeOf(options, profile) {
40
+ if (options.global === true) {
41
+ return { kind: "global" };
42
+ }
43
+ if (options.allProjects === true || profile.project === undefined) {
44
+ return { kind: "all" };
45
+ }
46
+ return { kind: "project", id: profile.project };
47
+ }
48
+ /** The shared opening: JSON mode, flag checks, the profile, the scope. */
49
+ export async function connectQuery(runtime, options) {
50
+ runtime.setJsonMode(options.json === true);
51
+ checkQueryScopeFlags(options);
52
+ const profile = await runtime.resolve({
53
+ profile: options.profile,
54
+ project: parseProjectOverride(options.project),
55
+ });
56
+ return {
57
+ getPage: (path) => apiGet(profile.instanceUrl, profile.apiKey, path),
58
+ scope: queryScopeOf(options, profile),
59
+ profile,
60
+ };
61
+ }
62
+ /** The collection path of the queries in scope, without pageSize. */
63
+ export function queriesPath(scope) {
64
+ const filters = [];
65
+ if (scope.kind === "project") {
66
+ filters.push({ name: "project", operator: "=", values: [String(scope.id)] });
67
+ }
68
+ else if (scope.kind === "global") {
69
+ filters.push({ name: "project", operator: "!*", values: [] });
70
+ }
71
+ return filters.length === 0
72
+ ? QUERIES_COLLECTION
73
+ : `${QUERIES_COLLECTION}?filters=${filtersQuery(filters)}`;
74
+ }
75
+ /** Where the default query of the scope lives; undefined for the global one. */
76
+ export function defaultQueryPath(scope) {
77
+ return scope.kind === "project"
78
+ ? `${WORKSPACES_COLLECTION}/${String(scope.id)}/queries/default`
79
+ : `${QUERIES_COLLECTION}/default`;
80
+ }
81
+ function defaultQueryFallbackPath(scope) {
82
+ return scope.kind === "project"
83
+ ? `${PROJECTS_COLLECTION}/${String(scope.id)}/queries/default`
84
+ : undefined;
85
+ }
86
+ function refuseDefaultQuery() {
87
+ throw new OpCliError("USAGE_ERROR", "the default query is not a saved query and cannot be modified.", "pass the id or exact name of a saved query; run op-cli query list to see them.");
88
+ }
89
+ /** The default query is a view of the scope, not a stored query. */
90
+ export function refuseDefault(reference) {
91
+ if (reference.trim() === "default") {
92
+ refuseDefaultQuery();
93
+ }
94
+ }
95
+ /** The last path segment of an href, decoded; undefined when there is none. */
96
+ export function lastSegment(href) {
97
+ if (typeof href !== "string") {
98
+ return undefined;
99
+ }
100
+ const tail = href.split("/").filter((part) => part !== "").pop();
101
+ return tail === undefined ? undefined : decodeURIComponent(tail);
102
+ }
103
+ async function walkQueries(connection) {
104
+ const found = [];
105
+ for await (const element of halElements(connection.getPage, withPageSize(queriesPath(connection.scope), DEFAULT_PAGE_SIZE))) {
106
+ if (typeof element.id !== "number" || typeof element.name !== "string") {
107
+ continue;
108
+ }
109
+ const project = flattenHalLink(element._links?.project);
110
+ found.push({
111
+ id: element.id,
112
+ name: element.name,
113
+ owner: project.id === null ? "global" : `project ${project.name ?? String(project.id)}`,
114
+ });
115
+ }
116
+ return found;
117
+ }
118
+ /**
119
+ * A query reference to what it names. A number is an id and a bare
120
+ * "default" is the scope's default query; anything else is an exact name
121
+ * matched live over the queries in scope, because queries are not part of
122
+ * the stored metadata. Ambiguity and a miss fail loudly.
123
+ */
124
+ export async function resolveQueryRef(connection, raw) {
125
+ if (isIdForm(raw)) {
126
+ return { kind: "id", id: Number(raw) };
127
+ }
128
+ if (raw === "default") {
129
+ return { kind: "default" };
130
+ }
131
+ const candidates = await walkQueries(connection);
132
+ const match = matchByName(raw, candidates.map((candidate) => ({
133
+ name: candidate.name,
134
+ owner: candidate.owner,
135
+ value: candidate.id,
136
+ })));
137
+ if (match.kind === "unique") {
138
+ return { kind: "id", id: match.entry.value, name: match.entry.name };
139
+ }
140
+ if (match.kind === "ambiguous") {
141
+ const listed = match.candidates
142
+ .map((candidate) => `${String(candidate.value)} (${candidate.owner})`)
143
+ .join(", ");
144
+ throw new OpCliError("USAGE_ERROR", `query "${raw}" is ambiguous. Candidates: ${listed}.`, "repeat the command with the numeric id of one candidate, or narrow with --project or --global.");
145
+ }
146
+ throw new OpCliError("USAGE_ERROR", candidates.length === 0
147
+ ? `query "${raw}" not found; no query is visible in this scope.`
148
+ : `query "${raw}" not found. Valid values, closest first: `
149
+ + `${rankByCloseness(raw, candidates.map((candidate) => candidate.name)).join(", ")}.`, "run op-cli query list to see the queries you can address.");
150
+ }
151
+ /** Like resolveQueryRef, but a reference to the default query is refused. */
152
+ export async function resolveSavedQuery(connection, raw) {
153
+ const ref = await resolveQueryRef(connection, raw);
154
+ if (ref.kind !== "id") {
155
+ refuseDefaultQuery();
156
+ }
157
+ return ref;
158
+ }
159
+ /** The raw Query resource a reference names. */
160
+ export async function fetchQuery(connection, ref) {
161
+ if (ref.kind === "id") {
162
+ return connection.getPage(`${QUERIES_COLLECTION}/${String(ref.id)}`);
163
+ }
164
+ const fallback = defaultQueryFallbackPath(connection.scope);
165
+ const first = defaultQueryPath(connection.scope);
166
+ return fallback === undefined
167
+ ? connection.getPage(first)
168
+ : withMovedRetry(() => connection.getPage(first), () => connection.getPage(fallback));
169
+ }
170
+ function filterSummary(filter) {
171
+ const body = filter;
172
+ const links = body._links ?? {};
173
+ const linked = Array.isArray(links.values)
174
+ ? links.values.map((value) => {
175
+ const href = value.href;
176
+ return halRefId(typeof href === "string" ? href : null)?.toString() ?? lastSegment(href) ?? "";
177
+ })
178
+ : [];
179
+ const plain = Array.isArray(body.values) ? body.values.map(String) : [];
180
+ return {
181
+ field: lastSegment(links.filter?.href) ?? null,
182
+ operator: lastSegment(links.operator?.href) ?? null,
183
+ values: [...plain, ...linked],
184
+ };
185
+ }
186
+ function linkList(links) {
187
+ return Array.isArray(links) ? links : [];
188
+ }
189
+ function sortSummary(href) {
190
+ const key = lastSegment(href);
191
+ const split = key?.lastIndexOf("-") ?? -1;
192
+ return key === undefined || split < 0
193
+ ? key
194
+ : `${key.slice(0, split)}:${key.slice(split + 1)}`;
195
+ }
196
+ /**
197
+ * One Query resource as a flat record: every attribute the server sent
198
+ * (ADR-0003), with `{ id, name }` for project, user, and group-by, the
199
+ * columns and sort order as plain strings, and the filters as
200
+ * `{ field, operator, values }`. The embedded results are dropped:
201
+ * running a query is its own command.
202
+ */
203
+ export function flattenQueryRecord(element) {
204
+ const query = element;
205
+ // The filters are summarised below; their plain `values` arrays are not
206
+ // resources, which the generic flattening cannot take.
207
+ const withoutFilters = { ...query };
208
+ delete withoutFilters.filters;
209
+ const base = flattenHalRecord(withoutFilters);
210
+ delete base.results;
211
+ const links = query._links ?? {};
212
+ return {
213
+ ...base,
214
+ id: query.id ?? null,
215
+ name: query.name ?? null,
216
+ project: flattenHalLink(links.project),
217
+ user: flattenHalLink(links.user),
218
+ starred: query.starred ?? null,
219
+ public: query.public ?? null,
220
+ sums: query.sums ?? null,
221
+ includeSubprojects: query.includeSubprojects ?? null,
222
+ showHierarchies: query.showHierarchies ?? null,
223
+ groupBy: flattenHalLink(links.groupBy),
224
+ columns: linkList(links.columns)
225
+ .map((link) => lastSegment(link.href))
226
+ .filter((name) => name !== undefined),
227
+ sortBy: linkList(links.sortBy)
228
+ .map((link) => sortSummary(link.href))
229
+ .filter((sort) => sort !== undefined),
230
+ filters: Array.isArray(query.filters) ? query.filters.map(filterSummary) : [],
231
+ createdAt: query.createdAt ?? null,
232
+ updatedAt: query.updatedAt ?? null,
233
+ };
234
+ }
235
+ /** Renders one flat query record as a FIELD/VALUE table or picked JSON. */
236
+ export function renderQueryRecord(runtime, options, record, done) {
237
+ const requested = typeof options.fields === "string"
238
+ ? [
239
+ ...new Set(options.fields.split(",").map((name) => name.trim()).filter((name) => name !== "")),
240
+ ]
241
+ : Object.keys(record);
242
+ const unknown = requested.find((name) => !(name in record));
243
+ if (unknown !== undefined) {
244
+ throw new OpCliError("USAGE_ERROR", `${done === undefined ? "" : `${done}; `}field "${unknown}" is not a column. Valid fields, closest first: `
245
+ + `${rankByCloseness(unknown, Object.keys(record)).join(", ")}.`, "run the command without --fields to list every available field.");
246
+ }
247
+ if (options.json === true) {
248
+ runtime.write(`${JSON.stringify(Object.fromEntries(requested.map((field) => [field, record[field]])))}\n`);
249
+ return;
250
+ }
251
+ runtime.write(renderTable(["FIELD", "VALUE"], requested.map((field) => [field, formatCell(record[field])])));
252
+ }
253
+ function registerList(query, runtime) {
254
+ addQueryScopeOptions(query
255
+ .command("list")
256
+ .description("List visible queries (saved work package queries)")
257
+ .option("--starred", "only queries you starred")
258
+ .option("--json", PAGED_JSON_HELP)
259
+ .option("--fields <list>", "comma-separated columns to show")
260
+ .option("--limit <n>", "maximum number of results to show")
261
+ .option("--all", "fetch every page instead of one limited page")).action(async (options) => {
262
+ runtime.setJsonMode(options.json === true);
263
+ // Flag misuse is refused before any traffic.
264
+ const { pick } = rowViewOf(QUERY_COLUMNS, options);
265
+ const limit = parsePageSize(options.limit);
266
+ const { getPage, scope } = await connectQuery(runtime, options);
267
+ const basePath = queriesPath(scope);
268
+ const keep = (row) => options.starred !== true || row.starred === true;
269
+ // The starred flag is applied here, not by the server: the filter set
270
+ // of the collection is not documented for it. A client-side filter
271
+ // needs every page, or a short first page could hide a starred query.
272
+ const walkAll = options.all === true || options.starred === true;
273
+ if (walkAll) {
274
+ const startPath = withPageSize(basePath, await allPageSize(getPage));
275
+ const rows = [];
276
+ for await (const element of halElements(getPage, startPath)) {
277
+ const row = flattenQueryRecord(element);
278
+ if (!keep(row)) {
279
+ continue;
280
+ }
281
+ if (options.all === true && options.json === true) {
282
+ runtime.write(`${JSON.stringify(pick(row))}\n`);
283
+ }
284
+ else {
285
+ rows.push(row);
286
+ }
287
+ }
288
+ if (options.all === true && options.json === true) {
289
+ return;
290
+ }
291
+ const shown = options.all === true ? rows : rows.slice(0, limit);
292
+ emitRows(runtime, QUERY_COLUMNS, shown, options);
293
+ if (shown.length < rows.length) {
294
+ runtime.writeErr(`Showing ${String(shown.length)} of ${String(rows.length)} queries. `
295
+ + "Pass --all to fetch every result.\n");
296
+ }
297
+ return;
298
+ }
299
+ const page = (await getPage(withPageSize(basePath, limit)));
300
+ const elements = page._embedded?.elements ?? [];
301
+ const shown = elements.slice(0, limit).map(flattenQueryRecord);
302
+ emitRows(runtime, QUERY_COLUMNS, shown, options);
303
+ const total = Math.max(typeof page.total === "number" ? page.total : elements.length, elements.length);
304
+ if (total > shown.length) {
305
+ runtime.writeErr(`Showing ${String(shown.length)} of ${String(total)} queries. `
306
+ + "Pass --all to fetch every result.\n");
307
+ }
308
+ });
309
+ }
310
+ function registerGet(query, runtime) {
311
+ addQueryScopeOptions(query
312
+ .command("get")
313
+ .description('Show one query by id, name, or "default"')
314
+ .argument("<id-or-name>", 'query id, exact name, or "default"')
315
+ .option("--json", "emit a flat JSON record")
316
+ .option("--fields <list>", "comma-separated fields to show")).action(async (reference, options) => {
317
+ const connection = await connectQuery(runtime, options);
318
+ const ref = await resolveQueryRef(connection, reference);
319
+ renderQueryRecord(runtime, options, flattenQueryRecord(await fetchQuery(connection, ref)));
320
+ });
321
+ }
322
+ export function registerQueryCommands(query, runtime) {
323
+ query.description("Inspect and manage saved work package queries");
324
+ registerList(query, runtime);
325
+ registerGet(query, runtime);
326
+ registerQueryRun(query, runtime);
327
+ registerQueryManage(query, runtime);
328
+ registerQueryWrite(query, runtime);
329
+ }
330
+ //# sourceMappingURL=query.js.map
@@ -7,7 +7,7 @@ import { apiDelete, apiGet, apiPatchRaw, apiPostRaw, authenticate, } from "../co
7
7
  import { allPageSize, halElements, parsePageSize, withPageSize } from "../core/paginate.js";
8
8
  import { isIdForm, rankByCloseness, resolveName, } from "../context/resolve.js";
9
9
  import { parseProjectOverride, } from "../context/profile.js";
10
- import { loadProjectVocabulary, loadProjectVocabularyById, refreshStoredMetadata, } from "../context/metadata.js";
10
+ import { loadProjectVocabulary, loadProjectVocabularyById, refreshStoredMetadata, requireVocabulary, } from "../context/metadata.js";
11
11
  import { formatCell, renderTable } from "../output/table.js";
12
12
  // One flat row per time entry; the work package sits on every row so a
13
13
  // multi-wp listing stays a single table instead of a nested grouping.
@@ -166,7 +166,7 @@ function membersSource(env, profile) {
166
166
  label: "user",
167
167
  load: async () => {
168
168
  if (profile.project === undefined) {
169
- throw new OpCliError("USAGE_ERROR", "--user needs a project to look member names up in.", "pass --project <name-or-id> or set a default project on the profile.");
169
+ throw new OpCliError("USAGE_ERROR", "--user needs a project to look member names up in.", "pass --project <name-or-id> (or --workspace) or set a default project on the profile.");
170
170
  }
171
171
  const select = (vocabulary) => vocabulary.members.map((member) => ({
172
172
  name: member.name,
@@ -210,7 +210,7 @@ async function resolveUserValues(env, profile, raws) {
210
210
  function activitiesSource(env, profile, projectId) {
211
211
  return {
212
212
  label: "activity",
213
- load: async () => (await loadProjectVocabularyById(env, profile, projectId)).activities.map((activity) => ({ name: activity.name, owner: "activity", value: activity.id })),
213
+ load: async () => requireVocabulary(await loadProjectVocabularyById(env, profile, projectId), "activities").map((activity) => ({ name: activity.name, owner: "activity", value: activity.id })),
214
214
  refresh: async () => {
215
215
  await refreshStoredMetadata(env, profile);
216
216
  },