@giantswarm-io/pro 1.11.2 → 1.15.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/src/lib/items.js CHANGED
@@ -7,15 +7,22 @@
7
7
  * without console output.
8
8
  */
9
9
 
10
- import { fetchPaginated, graphQLWithAuth } from './api.js';
10
+ import { fetchBounded, graphQLWithAuth, withPartialData } from './api.js';
11
+ import { getItemRelations, getDependencyCounts } from './relations.js';
11
12
  import {
12
13
  LIST_ITEMS_QUERY,
14
+ LIST_ITEM_IDS_QUERY,
15
+ LIST_ITEMS_BY_ID_QUERY,
13
16
  ISSUE_DETAIL_QUERY,
14
17
  ITEM_ISSUE_REFS_QUERY,
18
+ BOARD_ITEM_QUERY,
19
+ BOARDS,
20
+ DEFAULT_BOARD,
15
21
  UPDATE_ITEM_FIELD_MUTATION,
16
22
  CLEAR_ITEM_FIELD_MUTATION
17
23
  } from './project.js';
18
- import { listFields, findMatchingOption } from './fields.js';
24
+ import { listFields, findMatchingOption, findMatchingIteration } from './fields.js';
25
+ import { parseIssueRef } from './rest-api.js';
19
26
  import { logger } from './logger.js';
20
27
 
21
28
  function escapeProjectQueryValue(value) {
@@ -47,7 +54,12 @@ export async function getItemByID(itemId, token) {
47
54
  };
48
55
 
49
56
  try {
50
- const issueDetails = await graphQLWithAuth(ISSUE_DETAIL_QUERY, { id: itemId }, token);
57
+ // The relations come in a request of their own, which may fail without
58
+ // costing the details: its error is reported as relationsError.
59
+ const [issueDetails, relations] = await Promise.all([
60
+ graphQLWithAuth(ISSUE_DETAIL_QUERY, { id: itemId }, token),
61
+ getItemRelations(itemId, token).catch(error => ({ error }))
62
+ ]);
51
63
  if (!issueDetails?.node) {
52
64
  throw new Error('Project item not found');
53
65
  }
@@ -101,6 +113,15 @@ export async function getItemByID(itemId, token) {
101
113
  if (issueDetails.node.content.projectsV2?.nodes) {
102
114
  item.projects = issueDetails.node.content.projectsV2.nodes.map(p => p.title);
103
115
  }
116
+ // Issues only: a pull request or a draft carries no relations, nor a
117
+ // relations error.
118
+ const isIssue = issueDetails.node.content.__typename === 'Issue';
119
+ if (isIssue && relations?.error) {
120
+ logger.warn('Issue relations unreadable', { itemId, error: relations.error.message });
121
+ item.relationsError = relations.error.message;
122
+ } else if (isIssue && relations) {
123
+ Object.assign(item, relations);
124
+ }
104
125
  }
105
126
  } catch (err) {
106
127
  logger.error(`Error fetching issue details: ${err.message}`);
@@ -148,6 +169,51 @@ export async function resolveItemIssues(itemIds, token) {
148
169
  return refs;
149
170
  }
150
171
 
172
+ /**
173
+ * Resolve one project item by its project item ID and check it is on the
174
+ * given board. Writes against a board (field updates, archiving) call this
175
+ * first so a wrong, deleted or misplaced item ID fails with an error that
176
+ * names the item and the board instead of a GraphQL or type error.
177
+ * @param {string} itemId - Project item (PVTI) ID
178
+ * @param {string} boardKey - Board key (e.g. "roadmap", "customer")
179
+ * @param {string} [token] - Optional per-request GitHub token
180
+ * @returns {Promise<{id: string, issue: string|null}>} - The item, with its
181
+ * issue as "owner/repo#N" (null for draft issues and unreadable content)
182
+ * @throws {Error} - When the item does not exist or is on another board
183
+ */
184
+ export async function resolveBoardItem(itemId, boardKey, token) {
185
+ const key = (boardKey || DEFAULT_BOARD).toLowerCase();
186
+ const board = BOARDS[key];
187
+ if (!board) {
188
+ throw new Error(`Unknown board '${boardKey}'. Valid boards: ${Object.keys(BOARDS).join(', ')}`);
189
+ }
190
+ const boardName = `the ${key} board (#${board.number})`;
191
+
192
+ let node = null;
193
+ try {
194
+ const result = await graphQLWithAuth(BOARD_ITEM_QUERY, { itemId }, token);
195
+ node = result?.node;
196
+ } catch (error) {
197
+ // GitHub answers an unknown node ID with a NOT_FOUND error.
198
+ if (!error.errors?.some(e => e.type === 'NOT_FOUND')) throw error;
199
+ }
200
+
201
+ if (!node?.project?.id) {
202
+ throw new Error(`No item '${itemId}' on ${boardName}: the item ID does not resolve to a project item. Look it up with get_item_by_issue.`);
203
+ }
204
+
205
+ const content = node.content;
206
+ const issue = content?.number && content.repository?.nameWithOwner
207
+ ? `${content.repository.nameWithOwner}#${content.number}`
208
+ : null;
209
+
210
+ if (node.project.id !== board.id) {
211
+ throw new Error(`No item for ${issue || `'${itemId}'`} on ${boardName}: item '${itemId}' belongs to project #${node.project.number}.`);
212
+ }
213
+
214
+ return { id: node.id, issue };
215
+ }
216
+
151
217
  /**
152
218
  * Derive a GitHub Projects query key from a field name.
153
219
  * E.g. "Working Group" -> "working-group", "SIG" -> "sig", "Team" -> "team"
@@ -180,31 +246,298 @@ function resolveRepositoryName(repository) {
180
246
  return `giantswarm/${trimmed}`;
181
247
  }
182
248
 
249
+ /**
250
+ * The query qualifier of a board field that stands for an issue attribute
251
+ * rather than a project field value, by its data type.
252
+ */
253
+ const QUALIFIER_BY_DATA_TYPE = {
254
+ ASSIGNEES: 'assignee',
255
+ LABELS: 'label',
256
+ REPOSITORY: 'repo',
257
+ MILESTONE: 'milestone',
258
+ PARENT_ISSUE: 'parent-issue',
259
+ REVIEWERS: 'reviewers',
260
+ ISSUE_TYPE: 'type',
261
+ CREATED: 'created',
262
+ UPDATED: 'updated',
263
+ CLOSED: 'closed'
264
+ };
265
+
266
+ /** Board field data types the Projects query cannot filter on. */
267
+ const UNFILTERABLE_DATA_TYPES = new Set(['TITLE', 'LINKED_PULL_REQUESTS', 'SUB_ISSUES_PROGRESS']);
268
+
269
+ /**
270
+ * list_issues' own issue filters, which `exclude` takes as keys next to the
271
+ * board's field names, and their query qualifiers.
272
+ */
273
+ const ISSUE_FILTER_QUALIFIERS = {
274
+ repository: 'repo',
275
+ assignee: 'assignee',
276
+ label: 'label',
277
+ milestone: 'milestone',
278
+ type: 'type',
279
+ parentIssue: 'parent-issue',
280
+ updated: 'updated',
281
+ created: 'created',
282
+ closed: 'closed',
283
+ reason: 'reason'
284
+ };
285
+
286
+ /** A query value, quoted when it holds whitespace or a quote. */
287
+ function queryValue(value) {
288
+ return /[\s"]/.test(value) ? `"${escapeProjectQueryValue(value)}"` : value;
289
+ }
290
+
291
+ /** A comma-separated (OR) list of query values, each quoted on its own. */
292
+ function queryValueList(value, mapPart = part => part) {
293
+ return value
294
+ .split(',')
295
+ .map(part => part.trim())
296
+ .filter(Boolean)
297
+ .map(part => queryValue(mapPart(part)))
298
+ .join(',');
299
+ }
300
+
301
+ /**
302
+ * A comparison, range or @-keyword value without whitespace, which carries
303
+ * no meaning there: the query cannot quote it, and a space would split the
304
+ * value into further terms (and `exclude` negate only the first).
305
+ */
306
+ function comparisonValue(value) {
307
+ return value.replace(/\s+/g, '');
308
+ }
309
+
310
+ /**
311
+ * The query term for an issue-level qualifier.
312
+ * Dates (created, updated, closed) keep GitHub's comparison and range syntax.
313
+ * @returns {string|null} - The term, or null for a list without values
314
+ * @throws {Error} When a parent issue is not a URL or owner/repo#number
315
+ */
316
+ function qualifierTerm(qualifier, value) {
317
+ switch (qualifier) {
318
+ case 'created':
319
+ case 'updated':
320
+ case 'closed':
321
+ return `${qualifier}:${comparisonValue(value)}`;
322
+ case 'reason':
323
+ return `reason:${queryValue(value)}`;
324
+ case 'repo': {
325
+ const list = queryValueList(value, resolveRepositoryName);
326
+ return list ? `repo:${list}` : null;
327
+ }
328
+ case 'parent-issue': {
329
+ const list = queryValueList(value, part => {
330
+ const { owner, repo, issue_number } = parseIssueRef(part);
331
+ return `${owner}/${repo}#${issue_number}`;
332
+ });
333
+ return list ? `parent-issue:${list}` : null;
334
+ }
335
+ default: {
336
+ const list = queryValueList(value);
337
+ return list ? `${qualifier}:${list}` : null;
338
+ }
339
+ }
340
+ }
341
+
342
+ /**
343
+ * The query term that matches a board field (or, with issueFilters, one of
344
+ * list_issues' issue filters) against a value.
345
+ *
346
+ * - single-select: option names, validated and resolved to the board's
347
+ * spelling; comma-separated for OR
348
+ * - iteration: iteration titles (current, upcoming or completed), or
349
+ * GitHub's keywords such as "@current", "@next", "@previous" and ranges
350
+ * - date and number: GitHub's comparison syntax (">2026-01-01",
351
+ * "2026-01-01..2026-03-31", ">1", "@today")
352
+ * - text: the exact text
353
+ * - fields standing for issue attributes (Assignees, Labels, Repository,
354
+ * Milestone, Parent issue, ...): their issue qualifier
355
+ *
356
+ * @param {string} param - The parameter the entry came from, for errors
357
+ * @param {string} name - Field name (or issue filter name)
358
+ * @param {string} value - Requested value, trimmed
359
+ * @param {Object[]} allFields - The board's fields
360
+ * @param {boolean} issueFilters - Whether issue filter names are accepted
361
+ * @returns {string|null} - The query term, or null for a list without values
362
+ * @throws {Error} Naming the unknown field or value and what is available
363
+ */
364
+ function fieldTerm(param, name, value, allFields, issueFilters) {
365
+ const field = allFields.find(f => f?.name?.toLowerCase() === name.toLowerCase());
366
+ if (!field) {
367
+ const filterName = issueFilters &&
368
+ Object.keys(ISSUE_FILTER_QUALIFIERS).find(key => key.toLowerCase() === name.toLowerCase());
369
+ if (filterName) {
370
+ return qualifierTerm(ISSUE_FILTER_QUALIFIERS[filterName], value);
371
+ }
372
+ const available = allFields.map(f => f?.name).filter(Boolean);
373
+ const extra = issueFilters ? `; or one of ${Object.keys(ISSUE_FILTER_QUALIFIERS).join(', ')}` : '';
374
+ throw new Error(`${param}: field '${name}' not found. Available fields: ${available.join(', ')}${extra}`);
375
+ }
376
+
377
+ const queryKey = fieldNameToQueryKey(field.name);
378
+
379
+ if (field.__typename === 'ProjectV2SingleSelectField') {
380
+ const options = field.options || [];
381
+ // An option name may hold a comma: take the whole value first.
382
+ const parts = findMatchingOption(options, value) || !value.includes(',')
383
+ ? [value]
384
+ : value.split(',').map(part => part.trim()).filter(Boolean);
385
+ if (parts.length === 0) return null;
386
+ const names = parts.map(part => {
387
+ const option = findMatchingOption(options, part);
388
+ if (!option) {
389
+ throw new Error(`${param}: value '${part}' not found for field '${field.name}'. Available options: ${options.map(o => o.name).join(', ')}`);
390
+ }
391
+ return `"${escapeProjectQueryValue(option.name)}"`;
392
+ });
393
+ return `${queryKey}:${names.join(',')}`;
394
+ }
395
+
396
+ if (field.__typename === 'ProjectV2IterationField') {
397
+ const configuration = field.configuration || {};
398
+ const iterations = [...(configuration.iterations || []), ...(configuration.completedIterations || [])];
399
+ const titles = value.split(',').map(part => part.trim()).filter(Boolean).map(part => {
400
+ if (part.startsWith('@')) return comparisonValue(part);
401
+ const iteration = findMatchingIteration({ configuration: { iterations } }, part);
402
+ if (!iteration) {
403
+ throw new Error(`${param}: iteration '${part}' not found for field '${field.name}'. Available iterations: ${iterations.map(i => i.title).join(', ')}; or "@current", "@next", "@previous"`);
404
+ }
405
+ return `"${escapeProjectQueryValue(iteration.title)}"`;
406
+ });
407
+ return titles.length ? `${queryKey}:${titles.join(',')}` : null;
408
+ }
409
+
410
+ if (UNFILTERABLE_DATA_TYPES.has(field.dataType)) {
411
+ throw new Error(`${param}: field '${field.name}' cannot be filtered on${field.dataType === 'TITLE' ? '; use keyword' : ''}.`);
412
+ }
413
+
414
+ const qualifier = QUALIFIER_BY_DATA_TYPE[field.dataType];
415
+ if (qualifier) {
416
+ return qualifierTerm(qualifier, value);
417
+ }
418
+
419
+ if (field.dataType === 'TEXT') {
420
+ return `${queryKey}:"${escapeProjectQueryValue(value)}"`;
421
+ }
422
+
423
+ // DATE and NUMBER fields: GitHub's comparison and range syntax as given
424
+ return `${queryKey}:${comparisonValue(value)}`;
425
+ }
426
+
427
+ /** Reads by id a full read keeps running at once. */
428
+ const MAX_PARALLEL_READS = 6;
429
+
430
+ /**
431
+ * Read every item of a board listing from a cursor on, in board order.
432
+ *
433
+ * A page of items with their content takes GitHub about 3 s, and the cursors
434
+ * are opaque, so a long listing read page after page grows past the gateway
435
+ * timeout (pro#194). The ids of a page take a third of that: the ids are
436
+ * walked page after page, and each page of ids is read by id as soon as it
437
+ * arrives, while the walk goes on.
438
+ *
439
+ * @param {string} boardId - The GitHub project node ID
440
+ * @param {string|null} filterQuery - The composed project query
441
+ * @param {string} after - Cursor to continue from
442
+ * @param {string} [token] - Optional per-request GitHub token
443
+ * @param {(items: Object[]) => void} [onPage] - Called with each page of items as it is read
444
+ * @returns {Promise<Object[]>} - The items, as LIST_ITEMS_QUERY returns them
445
+ */
446
+ async function readItemsInParallel(boardId, filterQuery, after, token, onPage = () => {}) {
447
+ const reads = [];
448
+ const settled = new Set();
449
+ let inFlight = [];
450
+ let failed = null;
451
+ const readPage = async ids => {
452
+ try {
453
+ // An item deleted after the walk listed it is NOT_FOUND; GitHub still
454
+ // answers the others.
455
+ const { data } = await withPartialData(
456
+ graphQLWithAuth(LIST_ITEMS_BY_ID_QUERY, { ids }, token),
457
+ error => error.type === 'NOT_FOUND'
458
+ );
459
+ // No more requests for a read that has already failed.
460
+ if (!failed) onPage((data?.nodes || []).filter(Boolean));
461
+ return data;
462
+ } catch (error) {
463
+ failed ??= error;
464
+ throw error;
465
+ }
466
+ };
467
+
468
+ let cursor = after;
469
+ while (cursor && !failed) {
470
+ let result;
471
+ try {
472
+ result = await graphQLWithAuth(
473
+ LIST_ITEM_IDS_QUERY,
474
+ { projectId: boardId, filterQuery, after: cursor },
475
+ token
476
+ );
477
+ } catch (error) {
478
+ // The reads still running then start no count requests either.
479
+ failed ??= error;
480
+ throw error;
481
+ }
482
+ const page = result?.node?.items;
483
+ const ids = (page?.nodes || []).map(node => node?.id).filter(Boolean);
484
+ if (ids.length > 0) {
485
+ const read = readPage(ids);
486
+ // Observed at once, so a read failing during the walk is no unhandled
487
+ // rejection; Promise.all below still reports it. At most
488
+ // MAX_PARALLEL_READS run at once, against GitHub's secondary limits.
489
+ read.then(() => settled.add(read), () => settled.add(read));
490
+ reads.push(read);
491
+ inFlight.push(read);
492
+ if (inFlight.length >= MAX_PARALLEL_READS) {
493
+ await Promise.race(inFlight).catch(() => {});
494
+ inFlight = inFlight.filter(r => !settled.has(r));
495
+ }
496
+ }
497
+ cursor = page?.pageInfo?.hasNextPage ? page.pageInfo.endCursor : null;
498
+ }
499
+ if (failed) throw failed;
500
+ const pages = await Promise.all(reads);
501
+ return pages.flatMap(page => (page?.nodes || []).filter(Boolean));
502
+ }
503
+
183
504
  /**
184
505
  * List and filter items in a project board
185
506
  * @param {Object} options - Filtering options
186
507
  * @param {string} options.boardId - The GitHub project node ID (required)
187
508
  * @param {string} [options.repository] - Filter by repository (short name or "owner/name")
188
- * @param {Object} [options.filters] - Field name to value map for filtering (single-select fields)
509
+ * @param {Object} [options.filters] - Field name to value map for filtering (any filterable field, see fieldTerm)
510
+ * @param {Object} [options.exclude] - Like filters, negated; also takes the issue filter names
189
511
  * @param {string[]} [options.emptyFields] - Return only items where these fields have no value set
512
+ * @param {string[]} [options.nonEmptyFields] - Return only items where these fields have a value set
190
513
  * @param {string} [options.assignee] - Filter by assignee GitHub username (comma-separated for OR)
191
514
  * @param {string} [options.label] - Filter by label name (comma-separated for OR)
192
515
  * @param {string} [options.state] - Filter by issue state: "open" or "closed"
193
516
  * @param {string} [options.keyword] - Free text search matching titles and text fields
517
+ * @param {string} [options.milestone] - Filter by milestone title (comma-separated for OR)
518
+ * @param {string} [options.type] - Filter by issue type (comma-separated for OR)
519
+ * @param {string} [options.parentIssue] - Filter by parent issue (URL or owner/repo#number)
194
520
  * @param {string} [options.updated] - Filter by last-updated date (e.g. ">@today-7d")
195
521
  * @param {string} [options.created] - Filter by creation date (e.g. ">@today-90d")
196
522
  * @param {string} [options.closed] - Filter by closed date (e.g. ">@today-30d")
197
523
  * @param {string} [options.reason] - Filter by close reason: "completed", "not planned", or "reopened"
524
+ * @param {number} [options.limit] - Stop after this many listed items (0: every item). The
525
+ * GraphQL pages are sized to the remainder, so a small limit is one small request.
526
+ * @param {string} [options.after] - Cursor of an earlier, cut result (its nextCursor) to continue from
198
527
  * @param {string} [options.token] - Optional per-request GitHub token
199
- * @returns {Promise<Object>} - Result with status and data
528
+ * @returns {Promise<Object>} - Result with status and data; `truncated` is true when the
529
+ * limit stopped the listing with items left, and `nextCursor` then continues it
200
530
  */
201
531
  export async function listItems(options) {
202
532
  const first = 100;
203
533
  try {
204
534
  const {
205
- boardId, repository = null, filters = {}, emptyFields = [],
535
+ boardId, repository = null, filters = {}, exclude = {},
536
+ emptyFields = [], nonEmptyFields = [],
206
537
  assignee = null, label = null, state = null, keyword = null,
207
- updated = null, created = null, closed = null, reason = null, token
538
+ milestone = null, type = null, parentIssue = null,
539
+ updated = null, created = null, closed = null, reason = null,
540
+ limit = 0, after = null, token
208
541
  } = options;
209
542
 
210
543
  if (!boardId) {
@@ -214,84 +547,36 @@ export async function listItems(options) {
214
547
  // Build server-side filter query
215
548
  const queryTerms = [];
216
549
 
217
- // Repository filter uses GitHub Projects built-in repo: prefix
218
- if (repository) {
219
- const fullRepo = resolveRepositoryName(repository);
220
- queryTerms.push(`repo:${fullRepo}`);
221
- }
222
-
223
- // Assignee filter — supports comma-separated usernames for OR matching
224
- if (assignee) {
225
- const trimmed = assignee.trim();
226
- if (trimmed) {
227
- queryTerms.push(`assignee:${trimmed}`);
228
- }
229
- }
230
-
231
- // Label filter — supports comma-separated labels for OR matching.
232
- // Each individual label that contains spaces is quoted separately so that
233
- // e.g. "bug fix,enhancement" becomes label:"bug fix",enhancement.
234
- if (label) {
235
- const trimmed = label.trim();
236
- if (trimmed) {
237
- if (trimmed.includes(',')) {
238
- const parts = trimmed.split(',').map(p => {
239
- const s = p.trim();
240
- return s.includes(' ') ? `"${escapeProjectQueryValue(s)}"` : s;
241
- });
242
- queryTerms.push(`label:${parts.join(',')}`);
243
- } else if (trimmed.includes(' ')) {
244
- queryTerms.push(`label:"${escapeProjectQueryValue(trimmed)}"`);
245
- } else {
246
- queryTerms.push(`label:${trimmed}`);
247
- }
248
- }
249
- }
250
-
251
- // Issue state filter (is:open, is:closed)
252
- if (state) {
253
- const trimmed = state.trim().toLowerCase();
254
- if (trimmed === 'open' || trimmed === 'closed') {
255
- queryTerms.push(`is:${trimmed}`);
256
- }
257
- }
258
-
259
- // Last-updated date filter — passed through using GitHub's query syntax.
260
- // Examples: ">@today-7d", "<@today-30d", "@today", ">2025-01-01"
261
- if (updated) {
262
- const trimmed = updated.trim();
263
- if (trimmed) {
264
- queryTerms.push(`updated:${trimmed}`);
265
- }
266
- }
267
-
268
- // Created date filter — same GitHub Projects query syntax as `updated`.
269
- // Examples: ">@today-90d", "<@today-30d", "@today", ">2025-01-01"
270
- if (created) {
271
- const trimmed = created.trim();
272
- if (trimmed) {
273
- queryTerms.push(`created:${trimmed}`);
274
- }
275
- }
276
-
277
- // Closed date filter — same GitHub Projects query syntax as `updated`.
278
- // Examples: ">@today-30d", "<@today-7d", "@today", ">2025-01-01"
279
- if (closed) {
280
- const trimmed = closed.trim();
281
- if (trimmed) {
282
- queryTerms.push(`closed:${trimmed}`);
283
- }
284
- }
285
-
286
- // Close reason filter
287
- if (reason) {
288
- const trimmed = reason.trim();
289
- if (trimmed) {
290
- if (trimmed.includes(' ')) {
291
- queryTerms.push(`reason:"${escapeProjectQueryValue(trimmed)}"`);
292
- } else {
293
- queryTerms.push(`reason:${trimmed}`);
550
+ // Issue filters, each in GitHub Projects query syntax. List values are
551
+ // comma-separated for OR matching; a value with spaces is quoted on its
552
+ // own, so "bug fix,enhancement" becomes label:"bug fix",enhancement.
553
+ // Dates (updated, created, closed) are passed through, e.g. ">@today-7d",
554
+ // "<@today-30d", "@today", ">2025-01-01".
555
+ const issueFilters = [
556
+ ['repo', repository],
557
+ ['assignee', assignee],
558
+ ['label', label],
559
+ ['is', state],
560
+ ['milestone', milestone],
561
+ ['type', type],
562
+ ['parent-issue', parentIssue],
563
+ ['updated', updated],
564
+ ['created', created],
565
+ ['closed', closed],
566
+ ['reason', reason]
567
+ ];
568
+ for (const [qualifier, value] of issueFilters) {
569
+ const trimmed = typeof value === 'string' ? value.trim() : '';
570
+ if (!trimmed) continue;
571
+ if (qualifier === 'is') {
572
+ // Issue state filter (is:open, is:closed)
573
+ const lower = trimmed.toLowerCase();
574
+ if (lower === 'open' || lower === 'closed') {
575
+ queryTerms.push(`is:${lower}`);
294
576
  }
577
+ } else {
578
+ const term = qualifierTerm(qualifier, trimmed);
579
+ if (term) queryTerms.push(term);
295
580
  }
296
581
  }
297
582
 
@@ -309,64 +594,43 @@ export async function listItems(options) {
309
594
  }
310
595
  }
311
596
 
312
- // Generic field filters
313
- const filterEntries = Object.entries(filters).filter(
314
- ([, value]) => typeof value === 'string' && value.trim() !== ''
315
- );
597
+ // Generic field filters, and their negation
598
+ const nonBlank = map => Object.entries(map || {})
599
+ .filter(([, value]) => typeof value === 'string' && value.trim() !== '')
600
+ .map(([name, value]) => [name, value.trim()]);
601
+ const filterEntries = nonBlank(filters).filter(([, value]) => value.toLowerCase() !== 'all');
602
+ const excludeEntries = nonBlank(exclude);
316
603
 
317
604
  // Fetch board fields once if needed for filter validation or emptyFields validation
318
- const needFields = filterEntries.length > 0 || emptyFields.length > 0;
605
+ const needFields = filterEntries.length > 0 || excludeEntries.length > 0 ||
606
+ emptyFields.length > 0 || nonEmptyFields.length > 0;
319
607
  const allFields = needFields ? await listFields(boardId, token) : [];
320
608
 
321
- // Validate emptyFields names against actual board fields
322
- if (emptyFields.length > 0) {
323
- const allFieldNames = allFields.map(f => f.name.toLowerCase());
324
- for (const fn of emptyFields) {
609
+ // Validate emptyFields and nonEmptyFields names against actual board fields
610
+ const allFieldNames = allFields.map(f => f?.name?.toLowerCase());
611
+ for (const [param, names] of [['emptyFields', emptyFields], ['nonEmptyFields', nonEmptyFields]]) {
612
+ for (const fn of names) {
325
613
  if (!allFieldNames.some(n => n === fn.toLowerCase())) {
326
614
  const available = allFields.map(f => f.name);
327
615
  return {
328
616
  status: 'error',
329
- error: `emptyFields: field '${fn}' not found. Available fields: ${available.join(', ')}`
617
+ error: `${param}: field '${fn}' not found. Available fields: ${available.join(', ')}`
330
618
  };
331
619
  }
332
620
  }
333
621
  }
334
622
 
335
- if (filterEntries.length > 0) {
336
- for (const [fieldName, requestedValue] of filterEntries) {
337
- const trimmedValue = requestedValue.trim();
338
- if (trimmedValue.toLowerCase() === 'all') {
339
- continue;
340
- }
341
-
342
- const field = allFields.find(fieldNode =>
343
- fieldNode.__typename === 'ProjectV2SingleSelectField' &&
344
- fieldNode.name.toLowerCase() === fieldName.toLowerCase()
345
- );
346
-
347
- if (!field) {
348
- const availableFields = allFields
349
- .filter(f => f.__typename === 'ProjectV2SingleSelectField')
350
- .map(f => f.name);
351
- return {
352
- status: 'error',
353
- error: `Field '${fieldName}' not found. Available single-select fields: ${availableFields.join(', ')}`
354
- };
355
- }
356
-
357
- const matchingOption = findMatchingOption(field.options || [], trimmedValue);
358
- if (!matchingOption) {
359
- const availableOptions = (field.options || []).map(o => o.name);
360
- return {
361
- status: 'error',
362
- error: `Value '${trimmedValue}' not found for field '${field.name}'. Available options: ${availableOptions.join(', ')}`
363
- };
364
- }
365
-
366
- const escapedValue = escapeProjectQueryValue(matchingOption.name);
367
- const queryKey = fieldNameToQueryKey(field.name);
368
- queryTerms.push(`${queryKey}:"${escapedValue}"`);
623
+ try {
624
+ for (const [fieldName, value] of filterEntries) {
625
+ const term = fieldTerm('filters', fieldName, value, allFields, false);
626
+ if (term) queryTerms.push(term);
627
+ }
628
+ for (const [fieldName, value] of excludeEntries) {
629
+ const term = fieldTerm('exclude', fieldName, value, allFields, true);
630
+ if (term) queryTerms.push(`-${term}`);
369
631
  }
632
+ } catch (error) {
633
+ return { status: 'error', error: error.message };
370
634
  }
371
635
 
372
636
  // Add server-side no:<field> filters for emptyFields.
@@ -375,32 +639,15 @@ export async function listItems(options) {
375
639
  // The client-side filter below is kept as a safety net in case the
376
640
  // heuristic in fieldNameToQueryKey doesn't match a particular field.
377
641
  for (const fieldName of emptyFields) {
378
- const queryKey = fieldNameToQueryKey(fieldName);
379
- queryTerms.push(`no:${queryKey}`);
642
+ queryTerms.push(`no:${fieldNameToQueryKey(fieldName)}`);
380
643
  }
381
644
 
382
- const projectQuery = queryTerms.join(' ');
645
+ // has:<field-key> matches items where the field has a value.
646
+ for (const fieldName of nonEmptyFields) {
647
+ queryTerms.push(`has:${fieldNameToQueryKey(fieldName)}`);
648
+ }
383
649
 
384
- // totalCount is computed by GitHub for the query as sent (server-side
385
- // filters applied), including items whose content we cannot read.
386
- let totalCount = null;
387
- const allItems = await fetchPaginated(
388
- LIST_ITEMS_QUERY,
389
- { projectId: boardId, first, filterQuery: projectQuery || null },
390
- result => {
391
- if (!result?.node?.items) {
392
- return { nodes: [], pageInfo: { hasNextPage: false } };
393
- }
394
- if (typeof result.node.items.totalCount === 'number') {
395
- totalCount = result.node.items.totalCount;
396
- }
397
- return {
398
- nodes: result.node.items.nodes || [],
399
- pageInfo: result.node.items.pageInfo || { hasNextPage: false }
400
- };
401
- },
402
- token
403
- );
650
+ const projectQuery = queryTerms.join(' ');
404
651
 
405
652
  // Generic empty-field filtering (supports single-select, text, date, and iteration fields)
406
653
  function hasNonEmptyField(item, fieldName) {
@@ -424,7 +671,7 @@ export async function listItems(options) {
424
671
  }
425
672
 
426
673
  let hidden = 0;
427
- const filtered = allItems.filter(item => {
674
+ function isListed(item) {
428
675
  if (!item.fieldValues || !item.fieldValues.nodes) return false;
429
676
 
430
677
  for (const fieldName of emptyFields) {
@@ -438,19 +685,84 @@ export async function listItems(options) {
438
685
  return false;
439
686
  }
440
687
  return true;
441
- });
688
+ }
689
+
690
+ // totalCount is computed by GitHub for the query as sent (server-side
691
+ // filters applied), including items whose content we cannot read.
692
+ // The pages are read until `limit` listed items are collected, so
693
+ // `hidden` counts the unreadable items among the pages read.
694
+ let totalCount = null;
695
+ const readPage = result => {
696
+ if (!result?.node?.items) {
697
+ return { nodes: [], pageInfo: { hasNextPage: false } };
698
+ }
699
+ if (typeof result.node.items.totalCount === 'number') {
700
+ totalCount = result.node.items.totalCount;
701
+ }
702
+ return {
703
+ nodes: result.node.items.nodes || [],
704
+ pageInfo: result.node.items.pageInfo || { hasNextPage: false }
705
+ };
706
+ };
707
+
708
+ // Open dependency counts come in requests of their own, which may fail
709
+ // without costing the list: an error is reported as dependencyCountsError.
710
+ // A full read asks for each page's counts as soon as the page is read.
711
+ const countReads = [];
712
+ const countIssues = nodes => {
713
+ const ids = nodes.map(node => node?.content?.id).filter(Boolean);
714
+ if (ids.length > 0) countReads.push(getDependencyCounts(ids, token));
715
+ };
716
+
717
+ let items, hasNextPage, endCursor;
718
+ if (limit === 0) {
719
+ // A full read: the first page as usual, then the rest in parallel.
720
+ const firstPage = readPage(await graphQLWithAuth(
721
+ LIST_ITEMS_QUERY,
722
+ { projectId: boardId, first, after, filterQuery: projectQuery || null },
723
+ token
724
+ ));
725
+ countIssues(firstPage.nodes);
726
+ items = firstPage.nodes.filter(isListed);
727
+ if (firstPage.pageInfo.hasNextPage && firstPage.pageInfo.endCursor) {
728
+ const rest = await readItemsInParallel(boardId, projectQuery || null, firstPage.pageInfo.endCursor, token, countIssues);
729
+ items.push(...rest.filter(isListed));
730
+ }
731
+ hasNextPage = false;
732
+ } else {
733
+ ({ nodes: items, hasNextPage, endCursor } = await fetchBounded(
734
+ LIST_ITEMS_QUERY,
735
+ { projectId: boardId, first, filterQuery: projectQuery || null },
736
+ readPage,
737
+ token,
738
+ { after, limit, keep: isListed }
739
+ ));
740
+ countIssues(items);
741
+ }
742
+
743
+ // getDependencyCounts never rejects: a failed request is its `error`.
744
+ const dependencyCounts = new Map();
745
+ let dependencyCountsError;
746
+ for (const { counts, error } of await Promise.all(countReads)) {
747
+ for (const [id, summary] of counts) dependencyCounts.set(id, summary);
748
+ dependencyCountsError ??= error;
749
+ }
442
750
 
443
751
  return {
444
752
  status: 'success',
445
753
  hidden,
446
754
  totalCount,
447
- data: filtered.map(item => {
755
+ truncated: hasNextPage,
756
+ ...(hasNextPage ? { nextCursor: endCursor } : {}),
757
+ ...(dependencyCountsError ? { dependencyCountsError } : {}),
758
+ data: items.map(item => {
448
759
  // Build compact fields map, omitting empty values
449
760
  const fields = {};
450
761
  if (item.fieldValues?.nodes) {
451
762
  for (const node of item.fieldValues.nodes) {
452
- if (node.field?.name && node.name) {
453
- fields[node.field.name] = node.name;
763
+ const value = node.name ?? node.title ?? node.date;
764
+ if (node.field?.name && value) {
765
+ fields[node.field.name] = value;
454
766
  }
455
767
  }
456
768
  }
@@ -478,10 +790,14 @@ export async function listItems(options) {
478
790
  fields
479
791
  };
480
792
 
481
- // Only include closedAt, assignees, and labels when non-empty to keep output compact
793
+ // Only include closedAt, assignees, labels and dependency counts when non-empty to keep output compact
482
794
  if (item.content?.closedAt) entry.closedAt = item.content.closedAt;
483
795
  if (assignees.length > 0) entry.assignees = assignees;
484
796
  if (labels.length > 0) entry.labels = labels;
797
+ // Open dependencies only, as counts: get_issue_details and list_issue_relations name them
798
+ const deps = dependencyCounts.get(item.content?.id);
799
+ if (deps?.blockedBy > 0) entry.openBlockedBy = deps.blockedBy;
800
+ if (deps?.blocking > 0) entry.openBlocking = deps.blocking;
485
801
 
486
802
  return entry;
487
803
  })