@preventive/triage 1.0.0-alpha.78 → 1.0.0-alpha.79

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.78",
3
+ "version": "1.0.0-alpha.79",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -14,7 +14,7 @@ import type { PullDependencies } from './pull-dependencies.ts'
14
14
  import { ACCEPTING, askedOf, basesOf, comparedWith, latestOf, reviewsByVersion, reviewsOf } from './pull-dependency-reviews.ts'
15
15
  import { eachOf } from './queue.ts'
16
16
  import type { PublishedReview, RepoReviewState } from './repository-dependency-reviews.ts'
17
- import { type DependencyReviewEntry, type ReviewedBase, type ReviewedDependencies, askReviewed } from './reviewed-dependencies.ts'
17
+ import { type DependencyReviewEntry, type ReviewVerdict, type ReviewedBase, type ReviewedDependencies, askReviewed } from './reviewed-dependencies.ts'
18
18
 
19
19
  const FORMAT_AT_ONCE = 8
20
20
  // The longest comment told, past which none is.
@@ -78,6 +78,9 @@ export function withFormatted<T extends DependencyReview>(reviewed: ReviewedDepe
78
78
  // before a latest not accepting it, whatever that was compared with, as it
79
79
  // holds them all.
80
80
  interface Own { review: PublishedReview; pkgs: LockedPackage[] }
81
+ // What a verdict does to a version's review, as pull-dependency-reviews.ts
82
+ // stancesOf counts it: passes it, holds it rejected, or passes it by none.
83
+ const effectOf = (status: ReviewVerdict) => ACCEPTING.has(status) ? 'passes' : status === 'reject' ? 'holds' : 'withholds'
81
84
  function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string, any: boolean, bases: Map<string, ReviewedBase>): Map<string, Own> {
82
85
  // Theirs by the version they are of, each version probed once.
83
86
  const theirs = reviewsByVersion(reviews.filter(review => review.id !== undefined && review.reviewer === user))
@@ -106,14 +109,16 @@ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: str
106
109
  // there, as copying it would but repeat what `user` posted there, or undo a
107
110
  // later word of theirs holding it: the host's `lookup` passes it already; or
108
111
  // `user`'s own comments there (of `commented`, the reviews its comments
109
- // make) stand where it does, by their latest of it, the first of those as
110
- // late (as pull-dependency-reviews.ts stancesOf reads them), with its
111
- // verdict, or, later than it, not accepting what it accepts. Where their
112
- // latest comment stands elsewhere, an older one with its verdict leaves it
113
- // in: posted again, it stands. A version `lookup` fails to answer of keeps
114
- // its review. Where the host reads reviews of comments (`parseComments`),
115
- // what a review was compared with is its to weigh, so one compared with any
116
- // version is given.
112
+ // make) stand on it, by their latest of it, the first of those as late (as
113
+ // pull-dependency-reviews.ts stancesOf reads them), as it does (effectOf):
114
+ // accepting it with nits or without alike, as a host may read one verdict of
115
+ // a comment for each version it tells, which posting it again would but
116
+ // repeat. Or, later than it, they don't accept what it accepts, but where
117
+ // those as late tell its verdict too, posted beside another of an older
118
+ // review, which, standing first, posting it again sets right. A version
119
+ // `lookup` fails to answer of keeps its review. Where the host reads reviews
120
+ // of comments (`parseComments`), what a review was compared with is its to
121
+ // weigh, so one compared with any version is given.
117
122
  export async function formattedPull(reviewed: ReviewedDependencies | null, db: Pick<DependencyReviewStore, 'listOwnDependencyReviewsById'>, user: string,
118
123
  told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = [],
119
124
  bases: Map<string, ReviewedBase> = new Map()): Promise<string | null> {
@@ -126,7 +131,9 @@ export async function formattedPull(reviewed: ReviewedDependencies | null, db: P
126
131
  const made = reviewsOf(pkg, there)
127
132
  if (made.length === 0) return false
128
133
  const stance = latestOf(made)
129
- return stance.status === review.status || (stance.time > review.time && !ACCEPTING.has(stance.status) && ACCEPTING.has(review.status))
134
+ if (effectOf(stance.status) === effectOf(review.status)) return true
135
+ return stance.time > review.time && !ACCEPTING.has(stance.status) && ACCEPTING.has(review.status)
136
+ && !made.some(one => one.time === stance.time && one.status === review.status)
130
137
  }
131
138
  const ids = [...mine].filter(([, { review, pkgs }]) => pkgs.some(pkg => !passed.has(askedOf(pkg)[0]) && !posted(review, pkg))).map(([id]) => id)
132
139
  if (ids.length === 0) return null
@@ -158,7 +158,7 @@ import { setTimeout as delay } from 'node:timers/promises'
158
158
  import { type KeptStore, REPOSITORY_READ_KEPT_MS, authoredCommitStore, branchTipStore, bundleValidationStore, codeHeadStore, codeTreeStore, commitPullStore, githubTagStore, historyChangeStore, historyPageStore, historySquashStore, historyTreeStore,
159
159
  issueListStore, lockfileReadStore,
160
160
  npmDeltaStore, npmPublishTimeStore, npmVersionDeltaStore, npmVersionStore, ownKeptPrunes, patchStore, pullDependencyStore, pullListStore, repositoryReadStore, reviewBaselineStore, riskLineStore,
161
- scanReadStore, stasisDependencyStore } from './npm-kept.ts'
161
+ scanReadStore, stasisDependencyStore, teamDependencyStore } from './npm-kept.ts'
162
162
  import { plainObject } from './npm-manifest.ts'
163
163
  import { type NpmDelta, deltaKey, keptNpmDeltas, keptVersionDeltas, npmDelta, versionDeltaKey } from './npm-delta.ts'
164
164
  import { ADVISORIES_TIMEOUT_MS, fetchBundleAdvisories } from './bundle-advisories.ts'
@@ -2915,7 +2915,11 @@ async function handleRepositoryLockfiles(res: ServerResponse, deps: ManagedHttpD
2915
2915
  // once, GitHub asked nothing of them; each read with GitHub has its access
2916
2916
  // checked again after (readWholeRepositoryOf), and the reader's session
2917
2917
  // before each line, their team and grants before each telling a
2918
- // repository's.
2918
+ // repository's. Each repository's lines, once all were told, are kept for
2919
+ // its reader (teamDependencyStore, keptTeamRepository); with `kept=1`, those
2920
+ // kept of the repositories it reads are told first, together, one line each
2921
+ // (`{ repoId, kept, branch, pulls, dependencies }`, `kept` when they were
2922
+ // read), before it is read again, for the tab to show them meanwhile.
2919
2923
  const TEAM_REPOSITORIES_AT_ONCE = 4
2920
2924
  const TEAM_DEPENDENCIES_MS = 240_000
2921
2925
  const TEAM_PULL_PAGES = 20
@@ -2945,7 +2949,9 @@ async function handleTeamDependencies(res: ServerResponse, deps: ManagedHttpDeps
2945
2949
  const every = { branch: query.get('branches') === 'all', draft: query.get('drafts') === 'all' }
2946
2950
  const named = query.get('repoIds')
2947
2951
  const only = named === null ? null : new Set(named.split(',').map(Number))
2948
- if (only && (only.size === 0 || only.size > 1000 || [...only].some(id => !Number.isSafeInteger(id) || id <= 0))) { sendJson(res, 400, { error: 'bad-request' }); return }
2952
+ if ((only && (only.size === 0 || only.size > 1000 || [...only].some(id => !Number.isSafeInteger(id) || id <= 0))) || !['1', null].includes(query.get('kept'))) {
2953
+ sendJson(res, 400, { error: 'bad-request' }); return
2954
+ }
2949
2955
  const snapshot = await teamSnapshot(deps.db, s.session.id, teamId)
2950
2956
  const repoIds = [...new Set(snapshot.repositories.map(repo => repo.repoId))].filter(id => !only || only.has(id))
2951
2957
  const grants = await repositoryGrants(deps, s.user)
@@ -2963,8 +2969,10 @@ async function handleTeamDependencies(res: ServerResponse, deps: ManagedHttpDeps
2963
2969
  if (now?.user.id !== s.user.id || !roleAtLeast(now.user.role, 'view')) stopped = true
2964
2970
  const telling = lines.filter(line => line.repoId !== undefined && (line['branch'] || line['dependencies'])).map(line => line.repoId!)
2965
2971
  if (!stopped && telling.length > 0 && !await stillReads(now!.user, telling)) stopped = true
2966
- // With the app's users its reviewers are, as a repository's activity is told.
2967
- for (const line of lines) if (stopped || !await out.write(line['branch'] || line['dependencies'] ? await withAppUsers(deps.db, line) : line)) stopped = true
2972
+ // With the app's users its reviewers are, as a repository's activity is
2973
+ // told, those of lines told together looked up at once.
2974
+ const shown = stopped ? [] : await Promise.all(lines.map(line => line['branch'] || line['dependencies'] ? withAppUsers(deps.db, line) : line))
2975
+ for (const line of shown) if (stopped || !await out.write(line)) stopped = true
2968
2976
  if (stopped) out.cut()
2969
2977
  return !stopped
2970
2978
  }
@@ -2984,7 +2992,8 @@ async function handleTeamDependencies(res: ServerResponse, deps: ManagedHttpDeps
2984
2992
  if ('error' in access || !setting?.enabled) answered.push({ repoId, branch: null })
2985
2993
  else reading.push({ access, setting })
2986
2994
  }
2987
- if (answered.length > 0 && !await send(...answered)) return
2995
+ const kept = query.get('kept') === '1' ? await keptTeamLines(deps, reading, every) : []
2996
+ if (answered.length + kept.length > 0 && !await send(...answered, ...kept)) return
2988
2997
  const done = await eachOf(reading, TEAM_REPOSITORIES_AT_ONCE, ({ access, setting }) => stopped || Date.now() > deadline ? Promise.resolve(false)
2989
2998
  : teamRepositoryDependencies(deps, access, setting, deadline, send, () => wholeRepositoryAccess(deps, cookie, access.repo.repoId), every))
2990
2999
  if (stopped) return
@@ -3023,13 +3032,66 @@ async function handleTeamReviewChanges(req: IncomingMessage, res: ServerResponse
3023
3032
  sendJson(res, 200, { now, versions: changed.map(({ name, version }) => [name, version]) })
3024
3033
  }
3025
3034
 
3035
+ // What a team's Dependencies keeps of a repository it told whole to a
3036
+ // reader (teamDependencyStore): its default branch's line, its pull
3037
+ // requests' dependencies told (those GitHub failed left out, as still to be
3038
+ // told), and the lines their versions change, each once. By the reader and
3039
+ // their role, the repository, its review's setting, so that one set anew
3040
+ // tells none kept before, and what was asked (`every`).
3041
+ type KeptTeamRepository = { branch: object; pulls: object; dependencies: object[]; deltas: unknown[] }
3042
+ const TEAM_KEPT_VERSION = 1
3043
+ const teamKeptKey = (user: StoredUser, repoId: number, setting: RepoDependencyReview, every: TeamEvery) =>
3044
+ JSON.stringify([TEAM_KEPT_VERSION, user.id, user.role, repoId, setting, every.branch, every.draft])
3045
+ const keptTeamStore = (deps: ManagedHttpDeps) => teamDependencyStore<KeptTeamRepository>(deps.db, deps.config.debug)
3046
+
3047
+ // The lines kept of those of `reading` its reader was told whole before,
3048
+ // one a repository, in one read of the database: `kept` when its read began.
3049
+ async function keptTeamLines(deps: ManagedHttpDeps, reading: { access: WholeAccess; setting: RepoDependencyReview }[], every: TeamEvery): Promise<TeamDependencyLine[]> {
3050
+ if (reading.length === 0) return []
3051
+ const keys = reading.map(({ access, setting }) => teamKeptKey(access.user, access.repo.repoId, setting, every))
3052
+ const hits = await keptTeamStore(deps).readMany(keys)
3053
+ return reading.flatMap(({ access }, at) => {
3054
+ const hit = hits.get(keys[at]!)
3055
+ const value = hit?.value as Partial<KeptTeamRepository> | undefined
3056
+ if (!hit || !plainObject(value?.branch) || !plainObject(value.pulls) || !Array.isArray(value.dependencies)) return []
3057
+ return [{ repoId: access.repo.repoId, kept: hit.at, branch: value.branch, pulls: value.pulls, dependencies: value.dependencies,
3058
+ ...Array.isArray(value.deltas) && value.deltas.length > 0 ? { deltas: value.deltas } : {} }]
3059
+ })
3060
+ }
3061
+
3062
+ // The repository a read told `told` of, kept as told whole (KeptTeamRepository),
3063
+ // as of when it `began`; one told no review in effect, or why it couldn't be
3064
+ // read, kept no more, lest a reader be shown what no longer reads.
3065
+ async function keepTeamRepository(deps: ManagedHttpDeps, key: string, told: TeamDependencyLine[], began: number) {
3066
+ const store = keptTeamStore(deps)
3067
+ const head = told.find(line => line['branch'] !== undefined || line['error'] !== undefined)
3068
+ if (!head?.['branch'] || !plainObject(head['pulls'])) { await store.remove(key); return }
3069
+ const dependencies = told.flatMap(line => Array.isArray(line['dependencies']) ? line['dependencies'] as { error?: unknown }[] : []).filter(answer => answer.error === undefined)
3070
+ const deltas = new Map<string, unknown>()
3071
+ for (const line of told) {
3072
+ for (const delta of Array.isArray(line['deltas']) ? line['deltas'] as unknown[][] : []) deltas.set(JSON.stringify(delta.slice(0, 3)), delta)
3073
+ }
3074
+ await store.write(key, { branch: head['branch'] as object, pulls: head['pulls'], dependencies, deltas: [...deltas.values()] }, began)
3075
+ }
3076
+
3026
3077
  // A repository's lines of its team's Dependencies, as handleTeamDependencies
3027
- // tells them; whether all were written, none left for its time.
3078
+ // tells them; whether all were written, none left for its time. Kept for its
3079
+ // reader once all were (keepTeamRepository), what was kept before kept still
3080
+ // where they weren't.
3028
3081
  async function teamRepositoryDependencies(deps: ManagedHttpDeps, access: WholeAccess, setting: RepoDependencyReview, deadline: number,
3029
3082
  send: (...lines: TeamDependencyLine[]) => Promise<boolean>, reauthorize: () => Promise<WholeAccess | Refusal>, every: TeamEvery = DEFAULT_ONLY): Promise<boolean> {
3030
3083
  // The Stasis builds its answers want, asked for a batch of pull requests at a time, its default branch's with the first.
3031
3084
  const wants: StasisWant[] = []
3032
- try { return await teamRepositoryLines(deps, access, setting, deadline, send, reauthorize, wants, every) } finally { stasisReader(deps).build(wants) }
3085
+ const began = Date.now(), told: TeamDependencyLine[] = []
3086
+ const telling = (...lines: TeamDependencyLine[]) => {
3087
+ told.push(...lines)
3088
+ return send(...lines)
3089
+ }
3090
+ try {
3091
+ const whole = await teamRepositoryLines(deps, access, setting, deadline, telling, reauthorize, wants, every)
3092
+ if (whole) await keepTeamRepository(deps, teamKeptKey(access.user, access.repo.repoId, setting, every), told, began)
3093
+ return whole
3094
+ } finally { stasisReader(deps).build(wants) }
3033
3095
  }
3034
3096
  async function teamRepositoryLines(deps: ManagedHttpDeps, access: WholeAccess, setting: RepoDependencyReview, deadline: number,
3035
3097
  send: (...lines: TeamDependencyLine[]) => Promise<boolean>, reauthorize: () => Promise<WholeAccess | Refusal>, wants: StasisWant[], every: TeamEvery): Promise<boolean> {
@@ -16,7 +16,9 @@
16
16
  // lockfiles add (pull-dependencies.ts), and the lockfiles a commit lists and
17
17
  // each one's packages, as its dependency review reads them
18
18
  // (commit-lockfiles.ts); and the commit the code viewer keeps its
19
- // directories at, for as long as it does (codeHeadStore). Each store removes
19
+ // directories at, for as long as it does (codeHeadStore); and what a team's
20
+ // Dependencies tab was last told of each repository, by its reader, for a
21
+ // week (teamDependencyStore). Each store removes
20
22
  // its own rows kept longer than that as it writes, at most once an hour a
21
23
  // database (pruneKept), so that rows no read will take again don't pile up.
22
24
  // The database is an optimization: a failure reads as a miss, and writes
@@ -243,6 +245,14 @@ export const patchStore = (db: UpstreamCacheStore, debug = false): KeptStore<Kep
243
245
  // what its reader could check and the rules they were made by: kept a month
244
246
  // after they were made, as what they check never changes.
245
247
  export const bundleValidationStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'bundles/validations', HISTORY_PAGE_KEPT_MS, debug)
248
+ // What a team's Dependencies tab (http.ts handleTeamDependencies) was last
249
+ // told whole of a repository, by its reader, the repository, its review's
250
+ // setting and what was asked: its default branch's line and its pull
251
+ // requests' dependencies, sent first as kept while they are read again, then
252
+ // replaced. Each kept TEAM_DEPENDENCIES_KEPT_MS, as one a week old still
253
+ // shows a reader more than nothing while it is read.
254
+ export const TEAM_DEPENDENCIES_KEPT_MS = 7 * 24 * 60 * 60_000
255
+ export const teamDependencyStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'teams/dependencies', TEAM_DEPENDENCIES_KEPT_MS, debug)
246
256
  // What a repository's stasis.config.json has Stasis reach at a commit
247
257
  // (stasis-dependencies.ts): the versions, never the lockfile, by the
248
258
  // repository, the commit and the file's path, kept as its history's pages are.
@@ -10,7 +10,7 @@ import { revalidationLinks, securityLinks } from '../common/security-links.js'
10
10
  import { treeDependencyDirectory } from '../client/dependency-paths.js'
11
11
  import { liteWorkspace } from '../common/managed/finding-detail.js'
12
12
  import { managedTeamView } from '../common/managed/team-app.js'
13
- import { expandFindingValues, findingValueIndex } from '../common/managed/finding-values.js'
13
+ import { packTeamReports, unpackTeamReport } from '../common/managed/finding-values.js'
14
14
  import type { BlobStore } from './blob-store.ts'
15
15
  import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
16
16
  import type { TeamWorkspaceSummary } from './team-app.ts'
@@ -36,28 +36,37 @@ const REPORT_CACHE_BYTES = 16 * 1024 * 1024
36
36
  // the board (`lite`), its reports' file trees apart, and its team's catalog
37
37
  // summary (team-app.ts).
38
38
  type EncodedWorkspace = { reports: Buffer; lite: Buffer; trees: Buffer; summary: TeamWorkspaceSummary }
39
+ // One as kept: without its whole reports where they would not fit
40
+ // (retainReports).
41
+ type RetainedWorkspace = Omit<EncodedWorkspace, 'reports'> & { reports?: Buffer }
39
42
  export type TeamResponsePart = 'reports' | 'lite' | 'trees'
40
43
  // The part a team's `reports` or `trees` route asks for.
41
44
  export const teamResponsePart = (route: string, url: URL): TeamResponsePart =>
42
45
  route === 'trees' ? 'trees' : url.searchParams.get('lite') === '1' ? 'lite' : 'reports'
43
- const reportCaches = new WeakMap<ManagedDb, Map<string, EncodedWorkspace>>()
44
- const encodedBytes = ({ reports, lite, trees }: EncodedWorkspace) => reports.length + lite.length + trees.length
46
+ const reportCaches = new WeakMap<ManagedDb, Map<string, RetainedWorkspace>>()
47
+ const encodedBytes = ({ reports, lite, trees }: RetainedWorkspace) => (reports?.length ?? 0) + lite.length + trees.length
45
48
  // A workspace's report reads at once. Its reports' sizes are bounded together
46
49
  // before any is read, and each is held parsed till the build ends, so more at
47
50
  // once costs only the raw bytes in flight: a cold build of a team's reports
48
51
  // is so many storage round trips one after another.
49
52
  const WORKSPACE_READS_AT_ONCE = 16
53
+ // Its whole reports, by far its largest part, are kept with the rest where
54
+ // they fit, and left out where they do not: the board's copy and the trees,
55
+ // which a team's view opens on, are kept all the same, so that opening it
56
+ // again reads none of its reports, its whole reports built again apart.
50
57
  function retainReports(db: ManagedDb, key: string, encoded: EncodedWorkspace) {
51
- if (encodedBytes(encoded) > REPORT_CACHE_BYTES) return
58
+ let kept: RetainedWorkspace = encoded
59
+ if (encodedBytes(kept) > REPORT_CACHE_BYTES) { const { reports: _reports, ...rest } = encoded; kept = rest }
60
+ if (encodedBytes(kept) > REPORT_CACHE_BYTES) return
52
61
  let cache = reportCaches.get(db)
53
62
  if (!cache) { cache = new Map(); reportCaches.set(db, cache) }
54
63
  cache.delete(key)
55
- let total = encodedBytes(encoded) + [...cache.values()].reduce((sum, value) => sum + encodedBytes(value), 0)
64
+ let total = encodedBytes(kept) + [...cache.values()].reduce((sum, value) => sum + encodedBytes(value), 0)
56
65
  for (const [oldest, value] of cache) {
57
66
  if (total <= REPORT_CACHE_BYTES && cache.size < VISIBILITY_CACHE_MAX_SNAPSHOTS) break
58
67
  cache.delete(oldest); total -= encodedBytes(value)
59
68
  }
60
- cache.set(key, encoded)
69
+ cache.set(key, kept)
61
70
  }
62
71
  function visibilityWeight(visible: Visibility): number {
63
72
  return [...visible.values()].reduce((sum, v) => sum + v.ids.size + v.sourcePaths.size, 0)
@@ -237,21 +246,23 @@ async function buildTeamWorkspace(db: ManagedDb, store: BlobStore, snapshot: Tea
237
246
  // `{ reports, links }` as a response sends them, `spent` bytes already
238
247
  // counted against the bound; `folded` and its `lens` where the board's copy
239
248
  // left out rows App mode does not show (common/managed/finding-detail.js).
240
- // Its findings' packages and repositories are sent once each, in `values`
241
- // (common/managed/finding-values.js).
249
+ // The values its reports and their findings tell again and again (their
250
+ // severity, file, model, repository and so on) are sent once each, in
251
+ // `values`, and its findings' field names once for each shape of them, in
252
+ // `keys` (common/managed/finding-values.js).
242
253
  function encodeReports(reports: readonly TeamReport[], links: readonly string[][], spent: number,
243
254
  { folded = false, lens = null }: { folded?: false | 'rows' | 'app'; lens?: unknown } = {}): Buffer {
244
255
  let outputBytes = spent + 14
245
256
  const parts = [Buffer.from('{"reports":[')]
246
- const values = findingValueIndex()
247
- for (const [index, report] of reports.entries()) {
248
- const bytes = Buffer.from(JSON.stringify({ ...report, data: values.index(report.data) }))
257
+ const packed = packTeamReports(reports)
258
+ for (const [index, report] of packed.reports.entries()) {
259
+ const bytes = Buffer.from(JSON.stringify(report))
249
260
  outputBytes += bytes.length + 1
250
261
  if (outputBytes > MAX_REPORT_QUERY_BYTES) throw new TeamReportsError(413, 'batch-too-large')
251
262
  if (index) parts.push(Buffer.from(','))
252
263
  parts.push(bytes)
253
264
  }
254
- const tail = JSON.stringify({ ...links.length > 0 ? { links } : {}, ...folded ? { folded, lens } : {}, ...values.values.length > 0 ? { values: values.values } : {} })
265
+ const tail = JSON.stringify({ ...links.length > 0 ? { links } : {}, ...folded ? { folded, lens } : {}, ...packed.values ? { values: packed.values } : {}, ...packed.keys ? { keys: packed.keys } : {} })
255
266
  const suffix = Buffer.from(tail === '{}' ? ']}' : `],${tail.slice(1)}`)
256
267
  if (outputBytes + suffix.length > MAX_REPORT_QUERY_BYTES) throw new TeamReportsError(413, 'batch-too-large')
257
268
  parts.push(suffix)
@@ -283,9 +294,8 @@ export async function loadTeamSummary(db: ManagedDb, store: BlobStore, snapshot:
283
294
  }
284
295
  export async function loadTeamReports(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<TeamReport[]> {
285
296
  // Object consumers get their own copy, including when sharing a cold load.
286
- const body = JSON.parse((await loadTeamReportsResponse(db, store, snapshot)).toString('utf8')) as { reports: TeamReport[]; values?: unknown[] }
287
- for (const report of body.reports) expandFindingValues(report.data, body.values)
288
- return body.reports
297
+ const body = JSON.parse((await loadTeamReportsResponse(db, store, snapshot)).toString('utf8')) as { reports: TeamReport[]; values?: unknown; keys?: unknown }
298
+ return body.reports.map(report => unpackTeamReport(report, body)!)
289
299
  }
290
300
  async function teamVisibility(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<Visibility> {
291
301
  // A large snapshot may deliberately remain uncached, or be evicted by
@@ -1,3 +0,0 @@
1
- import{a as e}from"./chunk-6CCSTJWB.js";import{d as t,e as n,g as r,h as i,i as a}from"./chunk-EMNIV37E.js";import{q as o}from"./chunk-XLX6XXJF.js";import{J as s}from"./chunk-QRKFPLA4.js";import{a as c}from"./chunk-TUII34K2.js";var l=[`dependencies`,`security`],u={dependencies:`Dependencies`,security:`Security`},d=e(),f=Object.freeze(d.models),p=d.defaultModel,m=`x-upload-encryption`,h=1,g=1,_={name:`X25519`},v=34,y=1048576,b=65536,ee=`deepview-managed-upload.v1.content-key`;function x(e,t){let n=new Uint8Array(12);return new DataView(n.buffer).setUint32(7,e),n[11]=+!!t,n}async function S(e,t,n){let r=await crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveKey`]);return await crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:t,info:c(ee)},r,{name:`AES-GCM`,length:256},!1,[n])}async function C(e){let t=new Uint8Array(await e.slice(0,b).arrayBuffer());if(t.includes(0))return!1;try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(t,{stream:!0}),!0}catch{return!1}}async function w(e,t,n){let r=await C(e),[i,a]=await Promise.all([crypto.subtle.importKey(`raw`,t,_,!1,[]),crypto.subtle.generateKey(_,!1,[`deriveBits`])]),o=new Uint8Array(v);o[0]=h,o[1]=r?g:0,o.set(new Uint8Array(await crypto.subtle.exportKey(`raw`,a.publicKey)),2);let s=await S(await crypto.subtle.deriveBits({name:`X25519`,public:i},a.privateKey,256),o,`encrypt`),c=[new Blob([o])],l=new Uint8Array(y),u=0,d=0,f=async e=>{c.push(new Blob([await crypto.subtle.encrypt({name:`AES-GCM`,iv:x(d++,e)},s,l.subarray(0,u))])),u=0},p=(r?e.stream().pipeThrough(new CompressionStream(`gzip`)):e.stream()).getReader();try{for(let e=await p.read();!e.done;e=await p.read()){n?.throwIfAborted();for(let t=0;t<e.value.length;){u===y&&await f(!1);let n=Math.min(y-u,e.value.length-t);l.set(e.value.subarray(t,t+n),u),u+=n,t+=n}}}catch(e){throw await p.cancel(e).catch(()=>{}),e}return await f(!0),new Blob(c)}var T=null,E=0;function D(){return T?.user.role??null}function O(e){if(e!==null&&!i(e))throw TypeError(`Unknown managed preview role: ${e}. Expected ${r.join(`, `)}.`);E++,T=e===null?null:{user:{id:`preview:${e}`,login:e,name:e[0].toUpperCase()+e.slice(1),role:e,avatarUrl:null,lastSeenAt:Date.now(),lastActivityAt:null},csrfToken:null}}function te(e,t){let n=new URL(e,`http://managed-preview.invalid`).pathname,r=(t?.method??`GET`).toUpperCase();if(r===`POST`&&n===`/api/auth/logout`)return Response.json({ok:!0});if(r!==`GET`)throw Error(`Changes are not saved in the managed UI preview`);if(n===`/api/auth/session`)return Response.json(T);if(n===`/api/teams`)return Response.json({teams:[]});if(n.startsWith(`/api/admin/`)&&!a(T.user.role,`manage`)||[`/api/admin/users`,`/api/admin/teams`,`/api/admin/repositories`,`/api/admin/repositories/aliases`,`/api/admin/repositories/risk`].includes(n)&&T.user.role!==`admin`)return Response.json({error:`forbidden`},{status:403});if(n===`/api/admin/repositories/risk`)return new Response(`{"type":"repos","repos":[]}
2
- {"type":"done"}
3
- `,{headers:{"content-type":`application/x-ndjson`}});let i={"/api/admin/users":{users:[T.user]},"/api/admin/teams":{teams:[],users:[T.user],repos:[],permissions:l},"/api/admin/links":{shares:[]},"/api/admin/repositories":{repositories:[],total:0,connectedCount:0,installUrl:null,tokenMissing:!1},"/api/admin/repositories/aliases":{aliases:[],repos:[]},"/api/admin/repositories/resolve":{location:null},"/api/admin/reports":{reports:[],repos:[],maxBytes:26214400},"/api/admin/bundles":{bundles:[],repos:[],maxBytes:209715200},"/api/admin/history":{history:[],total:0,page:1,limit:100,filters:{repos:[],users:[]}},"/api/admin/scan/models":{models:f,defaultModel:p},"/api/admin/scan-results":{bundles:[],results:[]},"/api/auth/profile":{profile:{login:T.user.login,name:T.user.name,githubName:T.user.name,nameAccount:null,avatarAccount:null,accounts:[]}}};return Object.hasOwn(i,n)?Response.json(i[n]):Response.json({error:`not-found`},{status:404})}var k=3145728,ne=new Set([`/api/admin/reports`,`/api/admin/bundles`,`/api/admin/deduplication`]);async function A(e,t){let n=await t(`/api/admin/uploads/key`,{credentials:`same-origin`,signal:e.signal});if(n.status===404||n.status===405)return e;if(!n.ok)return n;let r=(await n.json())?.key;if(typeof r!=`string`)throw TypeError(`The server sent an invalid upload key`);let i=new Headers(e.headers);return i.set(m,`1`),{...e,headers:i,body:await w(e.body,Uint8Array.fromBase64(r,{alphabet:`base64url`}),e.signal)}}async function j(e,t,n){let r=null;if(e!==`/api/admin/deduplication`&&t.body.size>k){let i=await n(`/api/config`,{credentials:`same-origin`,signal:t.signal});if(!i.ok)return i;let a=(await i.json()).managed,o=a?.uploadMaxBytes?.[e.endsWith(`/reports`)?`reports`:`bundles`];if(Number.isSafeInteger(o)&&o>0&&t.body.size>o)return Response.json({error:`too-large`},{status:413});let s=a?.uploadChunkBytes;Number.isSafeInteger(s)&&s>0&&s<=k&&(r=s)}let i=await A(t,n);return i instanceof Response?i:r==null||i.body.size<=k?await n(e,i):await N(e,i,n,r)}var M=3;async function N(e,t,n,r){let i=t.body,a=crypto.randomUUID(),o=e.endsWith(`/reports`)?`reports`:`bundles`,s=Math.ceil(i.size/r),c=new Headers(t.headers);c.set(`content-type`,`application/octet-stream`);let l=0,u=!1;try{let d=null,f=!1,p=(await Promise.allSettled(Array.from({length:Math.min(M,s)},async()=>{for(;!f&&l<s;){let e=l++;try{let s=await n(`/api/admin/uploads/${o}/${a}/${e}`,{...t,headers:c,body:i.slice(e*r,(e+1)*r)});s.ok||(d??=s,f=!0)}catch(e){throw f=!0,e}}}))).find(e=>e.status===`rejected`);if(p)throw p.reason;if(d)return d;let m=new Headers(t.headers);m.set(`x-upload-id`,a),m.set(`x-upload-parts`,String(s)),m.set(`x-upload-size`,String(i.size));let h=await n(e,{...t,headers:m,body:``});return u=h.ok,h}finally{if(!u&&l>0){let e=new Headers(t.headers);e.set(`x-upload-parts`,String(l)),await n(`/api/admin/uploads/${o}/${a}`,{...t,method:`DELETE`,headers:e,body:void 0,signal:AbortSignal.timeout(1e4)}).catch(()=>{})}}}async function P(e){await e.json().then(e=>e?.error,()=>null)===`view-only`&&globalThis.document?.dispatchEvent(new CustomEvent(`managed-view-only`))}async function F(e,n){if(n?.signal?.throwIfAborted(),T)return te(e,n);let r=E;async function i(e,n){if(r!==E)throw new DOMException(`Managed session changed`,`AbortError`);let i=t();if(i){if(new URL(e,globalThis.location.origin).origin!==globalThis.location.origin)throw Error(`Public workspace requests must be same-origin`);let t=new Headers(n?.headers);t.set(`x-deepview-share`,i.token),n={...n,headers:t,credentials:`omit`,redirect:`error`}}let a=await fetch(e,{...n,cache:`no-store`});if(r!==E)throw new DOMException(`Managed session changed`,`AbortError`);return a.status===403&&![`GET`,`HEAD`].includes((n?.method??`GET`).toUpperCase())&&P(a.clone()),a}return n?.method===`POST`&&ne.has(e)&&n.body instanceof Blob?await j(e,n,i):await i(e,n)}var I=(e,t)=>[...new Set([...e?.keys()??[],...t.keys()])].filter(n=>e?.get(n)!==t.get(n)),L=e=>new Map([...Map.groupBy(e,([e])=>e)].map(([e,t])=>[e,JSON.stringify(t.map(([,e])=>e).toSorted())])),R=new class{constructor(e=()=>{}){this.resources=new Map,this.session=null,this.teamCatalog=null,this.reportCatalog=null,this.bundleCatalog=null,this.generation=0,this.sessionController=new AbortController,this.notify=e}setSession(e){(this.session?.id!==e?.id||this.session?.role!==e?.role)&&this.reset(),this.session=e}reset(){this.generation++,this.sessionController.abort(),this.sessionController=new AbortController,this.invalidate(),this.session=null,this.teamCatalog=null,this.reportCatalog=null,this.bundleCatalog=null}setReportCatalog(e){let t=new Map(e.map(e=>[e.id,JSON.stringify([e.cacheKey??null,e.reports.map(e=>[e.id,e.cacheKey??null,e.visible!==!1]).toSorted(),(e.bundles??[]).map(e=>[e.id,e.filename,e.repoFullName,e.repoDirectory??``]).toSorted()])])),n=new Set(I(this.teamCatalog,t).map(e=>`team:${e}`));for(let e of this.resources.keys())if(e.startsWith(`reports:content:team:`)){let[n]=e.slice(21).split(`:`);t.has(n)&&this.teamCatalog?.get(n)===t.get(n)||this.invalidate([e])}this.teamCatalog=t;let r=L(e.flatMap(e=>e.reports.map(t=>[t.id,JSON.stringify([e.id,t.cacheKey??null])]))),i=new Set([...n,...I(this.reportCatalog,r)]);this.reportCatalog=r;for(let e of this.resources.keys()){if(!e.startsWith(`reports:content:`)||e.startsWith(`reports:content:team:`))continue;let t=e.slice(16);(!r.has(t)||i.has(t))&&(this.invalidate([e]),i.add(t))}let a=L(e.flatMap(e=>(e.bundles??[]).map(t=>[t.id,JSON.stringify([e.id,e.cacheKey??null,t.filename,t.repoFullName,t.repoDirectory??``])]))),o=I(this.bundleCatalog,a);for(let e of o)i.add(`bundle:${e}`),this.invalidate([`bundle-metadata:${e}`]);let s=o.length>0;this.bundleCatalog=a;for(let e of this.resources.keys()){if(!e.startsWith(`report-sources:`)&&!e.startsWith(`finding-history:`))continue;let[,t,r]=e.split(`:`);(t?n.has(`team:${t}`):s||i.has(r))&&this.invalidate([e])}return i}read(e){return this.resources.get(e)?.data}invalidate(e){for(let[t,n]of this.resources)e&&!e.some(e=>t===e||t.startsWith(`${e}:`))||(n.controller?.abort(),this.resources.delete(t))}async mutate(e,t){let n=this.generation,r;try{r=await e()}catch(e){throw n===this.generation&&e?.name!==`AbortError`&&this.notify(`Couldn't save changes: ${e?.message??e}`),e}if(n!==this.generation)throw new DOMException(`Managed session changed`,`AbortError`);return this.invalidate(t),r}async load(e,t,n,{signal:r,apply:i=()=>{},retryInvalidated:a=!1}={}){let o=this.generation;for(;;){r?.throwIfAborted();let s=this.resources.get(e);if(s||(s={},this.resources.set(e,s)),s.data!==void 0&&i(s.data),!s.pending){let e=s.controller=new AbortController;s.pending=(async()=>{try{let t=await n(e.signal);return e.signal.throwIfAborted(),s.data=t,t}catch(n){throw!e.signal.aborted&&n?.name!==`AbortError`&&this.notify(`Couldn't refresh ${t}: ${n?.message??n}`),n}})().finally(()=>{s.pending=null})}try{let t=await s.pending;if(r?.throwIfAborted(),this.resources.get(e)!==s)throw new DOMException(`Managed data changed`,`AbortError`);return i(t),t}catch(t){if(!a||t?.name!==`AbortError`||r?.aborted||o!==this.generation||this.resources.get(e)===s)throw t}}}}(e=>{document.dispatchEvent(new CustomEvent(`managed-notice`,{detail:{message:e}}))});function z(e){R.setSession(e)}function B(e){return R.setReportCatalog(e)}function V(){R.reset()}var H=[`package`,`repo`],U=e=>Array.isArray(e?.findings)?`findings`:Array.isArray(e?.groups)?`groups`:null;function W(e,t){let n=U(e);if(!n||!Array.isArray(t))return e;for(let r of e[n].flat())if(r&&typeof r==`object`)for(let e of H)Number.isInteger(r[e])&&(r[e]=t[r[e]]);return e}async function G(e,t=null,n={}){let r;try{r=await F(e,{credentials:`same-origin`,headers:{accept:`application/json`},...n})}catch{return t}if(r.status===401||r.status===403)return null;if(!r.ok)return t;try{return await r.json()}catch{return t}}async function K({fallback:e=null,sent:r}={}){let i=t()||D()!==null?void 0:await r;if(i===null)return null;let a=q(i);if(a!==void 0)return a;let o;try{let r=t(),i=await F(r?n(r):`/api/auth/session`,{credentials:`same-origin`,headers:{accept:`application/json`}});if(i.status===401||i.status===403)return null;if(!i.ok)return e;o=await i.json()}catch{return e}let s=q(o);return s===void 0?e:s}function q(e){let n=e?.user;if(n===null)return null;if(n!==void 0&&typeof n.login==`string`)return{id:n.id,login:n.login,name:typeof n.name==`string`?n.name:null,avatarUrl:typeof n.avatarUrl==`string`?n.avatarUrl:null,role:typeof n.role==`string`?n.role:`none`,csrfToken:typeof e.csrfToken==`string`?e.csrfToken:null,...t()?{publicShare:!0}:{},...typeof e.viewer?.login==`string`?{viewer:{id:e.viewer.id,login:e.viewer.login,name:typeof e.viewer.name==`string`?e.viewer.name:null}}:{},...!t()&&e.dependencyReview===!0?{dependencyReview:!0}:{}}}function J(e){let t=t=>Number.isSafeInteger(e?.[t])&&e[t]>=0;return e?.appMode===!1?{appMode:!1,...t(`appReports`)&&{appReports:e.appReports},...t(`findings`)&&{findings:e.findings}}:e?.appMode===!0&&t(`appFindings`)?{appMode:!0,appFindings:e.appFindings}:null}function Y(e){if(typeof e?.sha!=`string`||typeof e.github!=`string`||!Array.isArray(e.tags))return null;let t=e.details,n=e=>typeof e==`string`?e:null,r=e=>Number.isSafeInteger(e)?e:null;return{sha:e.sha,github:e.github,tags:e.tags.filter(e=>typeof e==`string`),details:typeof t?.subject==`string`?{subject:t.subject,authorName:n(t.authorName),authorLogin:n(t.authorLogin),authoredAt:r(t.authoredAt),committedAt:r(t.committedAt)}:null}}async function re({fallback:e=[],signal:r,onRevision:i}={}){let a=t(),o=a?await G(n(a),null,{signal:r}):null,s=a?{teams:o?.team?[o.team]:[]}:await G(`/api/teams`,{teams:e},{signal:r}),c=s?.teams;return Array.isArray(c)?(i?.(typeof s.revision==`string`?s.revision:null),c.filter(e=>e!=null&&typeof e.id==`string`&&typeof e.name==`string`).map(e=>({id:e.id,slug:e.slug,name:e.name,...!a&&e.dependencyReview===!0?{dependencyReview:!0}:{},...e.permissions?{permissions:{dependencies:e.permissions.dependencies===!0,security:e.permissions.security===!0}}:{},...typeof e.cacheKey==`string`?{cacheKey:e.cacheKey}:{},...J(e.app)?{app:J(e.app)}:{},repos:Array.isArray(e.repos)?e.repos.filter(e=>Number.isSafeInteger(e?.repoId)&&e.repoId>0&&typeof e.fullName==`string`).map(e=>({repoId:e.repoId,fullName:e.fullName,path:typeof e.path==`string`&&e.path?e.path:null})):[],reports:Array.isArray(e.reports)?e.reports.filter(e=>e!=null&&typeof e.id==`string`&&typeof e.filename==`string`).map(e=>({id:e.id,slug:e.slug,filename:e.filename,visible:e.visible!==!1,...e.analyzer===null||typeof e.analyzer==`string`?{analyzer:e.analyzer}:{},repoFullName:typeof e.repoFullName==`string`?e.repoFullName:``,repoDirectory:typeof e.repoDirectory==`string`?e.repoDirectory:``,...typeof e.cacheKey==`string`?{cacheKey:e.cacheKey}:{}})):[],bundles:Array.isArray(e.bundles)?e.bundles.filter(e=>e!=null&&typeof e.id==`string`&&typeof e.filename==`string`).map(e=>({id:e.id,slug:e.slug,integrity:e.integrity,byteSize:e.byteSize,repoId:e.repoId,filename:e.filename,kind:e.kind,visible:e.visible!==!1,summary:e.summary??null,summaryRetryAt:Number.isSafeInteger(e.summaryRetryAt)&&e.summaryRetryAt>0?e.summaryRetryAt:null,repoDirectory:typeof e.repoDirectory==`string`?e.repoDirectory:``,repoFullName:typeof e.repoFullName==`string`?e.repoFullName:``,commitInfo:Y(e.commitInfo)})):[]}))):s==null?[]:e}function X(e){return e?.links===void 0?[]:Array.isArray(e.links)&&e.links.every(e=>Array.isArray(e)&&e.length>=2&&e.every(e=>typeof e==`string`))?e.links:null}function Z(e,t=null){return s(e?.data)===null||typeof e.repo?.directory!=`string`||e.repo.github!==null&&typeof e.repo.github!=`string`||X(e)===null?null:{data:W(e.data,t),repo:e.repo,...e.links?{links:e.links}:{}}}async function ie(e,{signal:t}={}){return Z(await G(`/api/reports/${encodeURIComponent(e)}`,null,{signal:t}))}async function ae(e,{signal:t}={}){let n=[...new Set(e)];if(n.length===0)return[];let r=await G(`/api/reports/query`,null,{method:`POST`,signal:t,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify({ids:n})});if(!Array.isArray(r?.reports)||r.reports.length!==n.length)return null;let i=new Map;for(let e of r.reports){let t=Z(e);if(!t||!n.includes(e.id)||i.has(e.id))return null;i.set(e.id,t)}let a=X(r);return a===null?null:e.map(e=>({...i.get(e),...a.length>0?{links:a}:{}}))}async function oe(e,{signal:t,reportId:n=null,lite:r=!1}={}){let i=new URLSearchParams(n===null?{}:{reportId:n});r&&i.set(`lite`,`1`);let a=await G(`/api/teams/${encodeURIComponent(e)}/reports${i.size>0?`?${i}`:``}`,null,{signal:t});if(!Array.isArray(a?.reports))return null;let o=[],s=new Set;for(let e of a.reports){let t=Z(e,a.values);if(!t||typeof e.id!=`string`||typeof e.filename!=`string`||s.has(e.id))return null;s.add(e.id),o.push({id:e.id,filename:e.filename,...t,...e.opensAsApp===!0?{opensAsApp:!0}:{}})}let c=X(a);return c===null?null:(Object.defineProperties(o,{links:{value:c},...[`rows`,`app`].includes(a.folded)?{folded:{value:a.folded},lens:{value:a.lens??null}}:{}}),o)}function Q(e){return e?`?team=${encodeURIComponent(e)}`:``}async function se(e,{reportId:t,...n}={}){let r=t==null?``:`?reportId=${encodeURIComponent(t)}`,i=await G(`/api/teams/${encodeURIComponent(e)}/annotations${r}`,null,n),{reports:a,entries:o,comments:s,issues:c={}}=i??{};if(!a||typeof a!=`object`||Array.isArray(a)||!o||typeof o!=`object`||Array.isArray(o)||!Array.isArray(s)||!c||typeof c!=`object`||Array.isArray(c)||Object.values(a).some(e=>!Array.isArray(e)||e.some(e=>typeof e!=`string`))||s.some(e=>!e||typeof e.findingId!=`string`))return null;let l=new Map;for(let[e,t]of s.entries()){let n=t.findingId,r=l.get(n)??[];r.push(e),l.set(n,r)}let u=new Map,d=new Map,f=typeof i.revision==`string`?i.revision:null;return Object.assign(e=>{if(!Object.hasOwn(a,e))return null;if(d.has(e))return d.get(e);let t=JSON.stringify(a[e]),n=u.get(t);if(!n){let r=[...new Set(a[e])],i=r.flatMap(e=>l.get(e)??[]);n={entries:Object.fromEntries(r.filter(e=>Object.hasOwn(o,e)).map(e=>[e,o[e]])),comments:i.toSorted((e,t)=>e-t).map(e=>s[e]),issues:Object.fromEntries(r.filter(e=>Object.hasOwn(c,e)).map(e=>[e,c[e]]))},u.set(t,n)}return d.set(e,n),n},{revision:f})}async function ce(e,t,n){let r=(await G(`/api/reports/${encodeURIComponent(e)}/triage${Q(t)}`,null,n))?.entries;return typeof r==`object`&&r&&!Array.isArray(r)?r:null}async function le(e,n,r=null){if(t())return[];let i=r===null?``:`?reportId=${encodeURIComponent(r)}`,a=await G(`/api/teams/${encodeURIComponent(e)}/fixes${i}`,null,{signal:n});return Array.isArray(a?.fixes)?a.fixes:null}async function ue(e,t,n){let r=await G(`/api/reports/${encodeURIComponent(e)}/comments${Q(t)}`,null,n);return Array.isArray(r?.comments)?r.comments:null}async function de(e,{findingId:t,body:n,commentId:r=null,version:i},a,o){let s=r==null?``:`/${encodeURIComponent(r)}`;try{let c=await F(`/api/reports/${encodeURIComponent(e)}/comments${s}${Q(o)}`,{method:r==null?`POST`:`PATCH`,credentials:`same-origin`,headers:{"content-type":`application/json`,...a?{"x-csrf-token":a}:{}},body:JSON.stringify(r==null?{findingId:t,body:n}:{body:n,version:i})});return{status:c.status,comment:c.ok?(await c.json()).comment:null}}catch{return{status:0,comment:null}}}async function fe(e,t,n,r,i){try{return(await F(`/api/reports/${encodeURIComponent(e)}/comments/${encodeURIComponent(t)}${Q(i)}`,{method:`DELETE`,credentials:`same-origin`,headers:{"content-type":`application/json`,...r?{"x-csrf-token":r}:{}},body:JSON.stringify({version:n})})).status}catch{return 0}}async function pe(e,t,n,r){try{return(await F(`/api/reports/${encodeURIComponent(e)}/triage${Q(r)}`,{method:`POST`,credentials:`same-origin`,headers:{"content-type":`application/json`,...n?{"x-csrf-token":n}:{}},body:JSON.stringify({entries:t})})).status}catch{return 0}}function $(e){e&&(location.href=e)}async function me(e){if(t())location.href=`/`;else{try{await F(`/api/auth/logout`,{method:`POST`,credentials:`same-origin`,headers:e?{"x-csrf-token":e}:{}})}catch{}location.reload()}}async function he(e,t){let n=await F(`/api/auth/view-as`,{method:`POST`,credentials:`same-origin`,headers:{"content-type":`application/json`,...t?{"x-csrf-token":t}:{}},body:JSON.stringify({userId:e})});if(!n.ok)throw Error(`HTTP ${n.status}`);location.assign(`/`)}async function ge(e){try{await F(`/api/auth/view-as`,{method:`DELETE`,credentials:`same-origin`,headers:e?{"x-csrf-token":e}:{}})}catch{}location.assign(o[`admin-users`])}async function _e(e){let t=await F(`/api/teams/${encodeURIComponent(e)}/share`,{credentials:`same-origin`});if(!t.ok)throw Error(`Could not load public links (${t.status})`);return(await t.json()).shares}async function ve(e,t,{id:n,revoke:r=!1,dependencies:i=!1,security:a=!1}={}){let o=n?`/${encodeURIComponent(n)}`:``,s=await F(`/api/teams/${encodeURIComponent(e)}/share${o}`,{method:r?`DELETE`:n?`PATCH`:`POST`,credentials:`same-origin`,headers:{"x-csrf-token":t,"content-type":`application/json`},...r?{}:{body:JSON.stringify({dependencies:i,security:a})}});if(!s.ok)throw Error(`Could not ${r?`revoke`:n?`update`:`create`} public link (${s.status})`);return s.json()}async function ye(e,t){let n=await F(`/api/bundles/${encodeURIComponent(e)}/download`,{credentials:`same-origin`});if(!n.ok)throw Error(`Could not download bundle (${n.status})`);let r=URL.createObjectURL(await n.blob()),i=document.createElement(`a`);i.href=r,i.download=t,i.click(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}export{u as a,D as b,O as c,F as d,R as e,z as f,B as g,V as h,K as i,re as j,ie as k,ae as l,oe as m,Q as n,se as o,ce as p,le as q,ue as r,de as s,fe as t,pe as u,$ as v,me as w,he as x,ge as y,_e as z,ve as A,ye as B};