Skip to content

Commit 1c03147

Browse files
committed
fix(types): align with fleet-strict flags (unused/indexed/verbatim/exact)
Fixes 157 type errors surfaced by the flipped flags in the fleet-canonical tsconfig.base.json: - noUnusedLocals / noUnusedParameters: drop unused destructure targets, prefix VS Code API callback params with `_`, replace assign-and-discard `const x = stack.pop()!` with a bare `stack.pop()` when only the side-effect matters. - noUncheckedIndexedAccess: add `!` to bounded for-loop array indexing, ?? fallbacks where index is past-end is possible, narrow optional chain results with explicit `if (!x) continue`. - noPropertyAccessFromIndexSignature: switch `match.groups.target` and `globPatterns.npm.packagejson.pattern` style accesses to bracket form (factored into a `globPattern(eco, file)` helper for parse-externals). - exactOptionalPropertyTypes: drop explicit `undefined` values from optional-property object literals (auth settings, fs-watch handler). - verbatimModuleSyntax: split mixed value/type imports — `SimPURL`, `PackageScoreAndAlerts`, `PURL_Type` now import via `import type`. - noPropertyAccessFromIndexSignature on `match.groups`, drop unused `json` and `getDefaultLogger` imports. Also fixes `flattenGlob` returning `string | undefined` (was `parts[0]` with `noUncheckedIndexedAccess` active, now `parts[0] ?? ''`) and stops the wasm-executor's `++goRefCount[id]` / `!--goRefCount[id]` from silently producing NaN by reading-then-writing via `(x ?? 0) + 1`.
1 parent 03f6439 commit 1c03147

13 files changed

Lines changed: 174 additions & 152 deletions

File tree

src/auth.ts

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,7 @@ export async function activate(
106106
return {}
107107
}
108108
async function syncLiveSessionFromDisk() {
109-
let settings_on_disk: { apiKey?: string } = {
110-
apiKey: undefined,
111-
}
109+
let settings_on_disk: { apiKey?: string } = {}
112110
try {
113111
const fromDisk = JSON.parse(
114112
Buffer.from(
@@ -197,14 +195,14 @@ export async function activate(
197195
return diskSessionsChanges.event(fn)
198196
},
199197
async getSessions(
200-
scopes: readonly string[] | undefined,
201-
options: vscode.AuthenticationProviderSessionOptions,
198+
_scopes: readonly string[] | undefined,
199+
_options: vscode.AuthenticationProviderSessionOptions,
202200
): Promise<vscode.AuthenticationSession[]> {
203201
return Array.from(liveSessions.values())
204202
},
205203
async createSession(
206-
scopes: readonly string[],
207-
options: vscode.AuthenticationProviderSessionOptions,
204+
_scopes: readonly string[],
205+
_options: vscode.AuthenticationProviderSessionOptions,
208206
): Promise<vscode.AuthenticationSession> {
209207
let organizations: OrganizationsRecord
210208
const apiKey: string =
@@ -223,6 +221,9 @@ export async function activate(
223221
throw new Error('User did not want to provide an API key')
224222
}
225223
const org = Object.values(organizations!.organizations)[0]
224+
if (!org) {
225+
throw new Error('No organization found for the provided API key')
226+
}
226227
const session = sessionFromAPIKey(apiKey, org)
227228
const oldSessions = Array.from(liveSessions.values())
228229
await syncLiveSessionToDisk(session)
@@ -273,13 +274,12 @@ export async function activate(
273274
)
274275
context.subscriptions.push(service)
275276
vscode.commands.registerCommand(`${EXTENSION_PREFIX}.login`, async () => {
276-
const session = await vscode.authentication.getSession(
277-
`${EXTENSION_PREFIX}`,
278-
[],
279-
{
280-
createIfNone: true,
281-
},
282-
)
277+
// The getSession call is intentionally side-effect-only: passing
278+
// `createIfNone: true` triggers the login flow if no session
279+
// exists; we don't need the returned session here.
280+
await vscode.authentication.getSession(`${EXTENSION_PREFIX}`, [], {
281+
createIfNone: true,
282+
})
283283
})
284284
try {
285285
await syncLiveSessionFromDisk()

src/data/editor-config.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export function activate(context: vscode.ExtensionContext) {
7171
fn,
7272
}
7373
for (let i = 0, { length } = sections; i < length; i += 1) {
74-
const section = sections[i]
74+
const section = sections[i]!
7575
const list = watchers.get(section) ?? new Set()
7676
list.add(listener)
7777
watchers.set(section, list)
@@ -83,7 +83,7 @@ export function activate(context: vscode.ExtensionContext) {
8383
currentValues: getValuesForListener(listener),
8484
dispose() {
8585
for (let i = 0, { length } = sections; i < length; i += 1) {
86-
const section = sections[i]
86+
const section = sections[i]!
8787
const list = watchers.get(section)
8888
if (!list) {
8989
continue

src/data/github.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export function orgOrUserFromString(url: string): string | undefined {
99
/^(?:git(?:\+ssh)?:\/\/)?(?<user>[^@]+@)?github.com[/:](?<target>[^/?#]*)(?=\/|$)/u // socket-hook: allow regex-alternation-order
1010
const match = ghHTTP.exec(url) || ghGit.exec(url)
1111
if (match) {
12-
return match.groups?.target || match.groups?.user
12+
return match.groups?.['target'] || match.groups?.['user']
1313
}
1414
}
1515

@@ -78,9 +78,9 @@ export async function sniffForGithubOrgOrUser(
7878
)
7979
const keys = Object.keys(gitConfig)
8080
for (let i = 0, { length } = keys; i < length; i += 1) {
81-
const key = keys[i]
81+
const key = keys[i]!
8282
if (key.startsWith('remote ')) {
83-
const url = gitConfig[key].url
83+
const url = gitConfig[key]?.url
8484
if (url) {
8585
const found = orgOrUserFromString(url)
8686
if (found) return found

src/data/glob-patterns.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,17 @@ export async function getGlobPatterns() {
3434
throw new Error(result.error.message)
3535
}
3636
for (const eco in result) {
37-
for (const name in result[eco]) {
38-
const target = result[eco][name]
37+
const bucket = result[eco]
38+
if (!bucket) continue
39+
for (const name in bucket) {
40+
const target = bucket[name]
41+
if (!target) continue
3942
target.pattern = caseDesensitize(flattenGlob(target.pattern))
4043
}
4144
}
4245
return result
4346
})
44-
.catch(err => {
47+
.catch(_err => {
4548
// allow retry
4649
globPatternsPromise = undefined
4750
// snapshot of supported patterns

src/data/go/wasm-executor.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ export class GoExecutor<
265265
goKeys!.set(v, id)
266266
goRefCount![id] = 0
267267
}
268-
++goRefCount![id]
268+
goRefCount![id] = (goRefCount![id] ?? 0) + 1
269269

270270
let typeFlag = 0
271271
switch (typeof v) {
@@ -371,7 +371,9 @@ export class GoExecutor<
371371
'syscall/js.finalizeRef': (sp: number) => {
372372
sp >>>= 0
373373
const id = this.mem!.getUint32(sp + 8, true)
374-
if (!--goRefCount![id]) {
374+
const next = (goRefCount![id] ?? 0) - 1
375+
goRefCount![id] = next
376+
if (next === 0) {
375377
const v = goValues!.get(id)
376378
goValues!.delete(id)
377379
goKeys!.delete(v)
@@ -563,7 +565,7 @@ export class GoExecutor<
563565

564566
const argv = offset
565567
for (let i = 0, { length } = argvPtrs; i < length; i += 1) {
566-
const ptr = argvPtrs[i]
568+
const ptr = argvPtrs[i]!
567569
this.mem!.setUint32(offset, ptr, true)
568570
this.mem!.setUint32(offset + 4, 0, true)
569571
offset += 8

src/data/python/interpreter.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,7 @@ export async function getPythonInterpreter(
286286
export async function initPython(): Promise<vscode.Disposable> {
287287
const ext = await getPythonExtension()
288288
if (ext) {
289-
return ext.environments.onDidChangeActiveEnvironmentPath((e: unknown) => {
289+
return ext.environments.onDidChangeActiveEnvironmentPath((_e: unknown) => {
290290
changeMSPython.fire()
291291
})
292292
}

src/extension.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ export async function activate(context: vscode.ExtensionContext) {
2525
)
2626
const provider: vscode.McpServerDefinitionProvider<vscode.McpHttpServerDefinition> =
2727
{
28-
provideMcpServerDefinitions(token) {
28+
provideMcpServerDefinitions(_token) {
2929
return [definition]
3030
},
31-
resolveMcpServerDefinition(definition, token) {
31+
resolveMcpServerDefinition(definition, _token) {
3232
return definition
3333
},
3434
}

src/fs-watch.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,10 @@ class SharedFilesystemWatcher {
4242
}
4343
watch(partial: SharedFilesystemWatcherHandler): vscode.Disposable {
4444
// avoid double push issue by making new identity
45-
const handler = {
46-
onDidChange: partial.onDidChange,
47-
onDidCreate: partial.onDidCreate,
48-
onDidDelete: partial.onDidDelete,
49-
}
45+
const handler: SharedFilesystemWatcherHandler = {}
46+
if (partial.onDidChange) handler.onDidChange = partial.onDidChange
47+
if (partial.onDidCreate) handler.onDidCreate = partial.onDidCreate
48+
if (partial.onDidDelete) handler.onDidDelete = partial.onDidDelete
5049
this.handlers.add(handler)
5150
return new vscode.Disposable(() => {
5251
this.handlers.delete(handler)
@@ -60,9 +59,12 @@ export function watch(
6059
pattern: string,
6160
handler: SharedFilesystemWatcherHandler,
6261
) {
63-
if (!watched[pattern])
64-
watched[pattern] = new SharedFilesystemWatcher(
62+
let existing = watched[pattern]
63+
if (!existing) {
64+
existing = new SharedFilesystemWatcher(
6565
vscode.workspace.createFileSystemWatcher(`**/${pattern}`),
6666
)
67-
return watched[pattern].watch(handler)
67+
watched[pattern] = existing
68+
}
69+
return existing.watch(handler)
6870
}

src/ui/decorations.ts

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
11
// max-file-lines: legitimate parser — VSCode-decoration manager for per-document PURL hover/decoration rendering; the per-eco classification, per-PURL alert grouping, and per-editor decoration pipeline are tightly coupled and split poorly.
22
import * as vscode from 'vscode'
3-
import { SimPURL, parseExternals } from './externals/parse-externals'
3+
import { parseExternals } from './externals/parse-externals'
4+
import type { SimPURL } from './externals/parse-externals'
45
import { PURLDataCache } from './purl-alerts-and-scores/manager'
5-
import { PackageScoreAndAlerts } from './purl-alerts-and-scores/manager'
6+
import type { PackageScoreAndAlerts } from './purl-alerts-and-scores/manager'
67
import { isGoBuiltin } from '../data/go/builtins'
78
import { logger } from '../infra/log'
89
import { PURLPackageData } from './purl-alerts-and-scores/manager'
910
import { SUPPORTED_LSP_LANGUAGE_IDS_TO_PARSER } from './languages'
1011
import { isPythonBuiltin } from '../data/python/interpreter'
1112
import * as Module from 'node:module'
1213
import { getGlobPatterns } from '../data/glob-patterns'
13-
import { getDefaultLogger } from '@socketsecurity/lib/logger'
1414

1515
export async function activate(context: vscode.ExtensionContext) {
1616
const decoManager = new DecorationManager(context)
1717
const langs = Object.keys(SUPPORTED_LSP_LANGUAGE_IDS_TO_PARSER)
1818
for (let i = 0, { length } = langs; i < length; i += 1) {
19-
const lang = langs[i]
19+
const lang = langs[i]!
2020
vscode.languages.registerHoverProvider(
2121
{
2222
language: lang,
@@ -33,14 +33,14 @@ export async function activate(context: vscode.ExtensionContext) {
3333
const patterns = await getGlobPatterns()
3434
const groupEntries = Object.entries(patterns)
3535
for (let i = 0, { length } = groupEntries; i < length; i += 1) {
36-
const patternsForGroup = groupEntries[i][1]
36+
const patternsForGroup = groupEntries[i]![1]
3737
const groupEntryRows = Object.entries(patternsForGroup)
3838
for (
3939
let j = 0, { length: rowLength } = groupEntryRows;
4040
j < rowLength;
4141
j += 1
4242
) {
43-
const { pattern } = groupEntryRows[j][1]
43+
const { pattern } = groupEntryRows[j]![1]
4444
vscode.languages.registerHoverProvider(
4545
{
4646
// language: 'json',
@@ -127,7 +127,7 @@ class DecorationManager {
127127
}
128128
const visibleEditors = vscode.window.visibleTextEditors
129129
for (let i = 0, { length } = visibleEditors; i < length; i += 1) {
130-
const editor = visibleEditors[i]
130+
const editor = visibleEditors[i]!
131131
const docURI = editor.document.uri.toString() as TextDocumentURIString
132132
const manager = managerForDoc(docURI)
133133
manager.update(editor.document)
@@ -137,7 +137,7 @@ class DecorationManager {
137137
if (!hasMeaningfulChange) {
138138
const { contentChanges } = doc
139139
for (let i = 0, { length } = contentChanges; i < length; i += 1) {
140-
const docChange = contentChanges[i]
140+
const docChange = contentChanges[i]!
141141
if (docChange.rangeLength !== 0) {
142142
hasMeaningfulChange = true
143143
break
@@ -164,7 +164,7 @@ class DecorationManager {
164164
this.editorChangeWatchers = vscode.window.onDidChangeVisibleTextEditors(
165165
editors => {
166166
for (let i = 0, { length } = editors; i < length; i += 1) {
167-
const editor = editors[i]
167+
const editor = editors[i]!
168168
const docURI = editor.document.uri.toString() as TextDocumentURIString
169169
const manager = managerForDoc(docURI)
170170
manager.decorateEditor(editor)
@@ -222,10 +222,12 @@ export function isLocalPackage(name: string, eco: string): boolean {
222222
if (eco === 'pypi') return name.startsWith('.')
223223
if (eco === 'go') {
224224
const parts = name.split('/')
225+
const first = parts[0]
226+
if (!first) return false
225227
return (
226228
parts.some(p => p.startsWith('.')) ||
227-
!parts[0].includes('.') ||
228-
!/[a-z0-9][a-z0-9.-]*/.test(parts[0])
229+
!first.includes('.') ||
230+
!/[a-z0-9][a-z0-9.-]*/.test(first)
229231
)
230232
}
231233
return false
@@ -325,7 +327,7 @@ class DecorationManagerForPURL {
325327
const {
326328
score: { overall: depscore },
327329
} = pkgData
328-
const { eco, name } = getPURLParts(this.purl)!
330+
const { eco } = getPURLParts(this.purl)!
329331
const depscoreStr = (depscore * 100).toFixed(0)
330332
const groupedAlerts = Object.groupBy(pkgData.alerts, alert => alert.action)
331333

@@ -341,7 +343,7 @@ class DecorationManagerForPURL {
341343
// grouping is intentionally lossy — fewer dedup buckets keeps the hover readable when many alerts share a type.
342344
const typesListed = new Set<string>()
343345
for (let i = 0, { length } = actionGroupedAlertSet; i < length; i += 1) {
344-
const alert = actionGroupedAlertSet[i]
346+
const alert = actionGroupedAlertSet[i]!
345347
// vscode markdown wants some kind of text for the table layout
346348
const extra = []
347349
const alternatePackage = alert.props?.alternatePackage
@@ -433,7 +435,7 @@ ${(['error', 'warn', 'monitor', 'ignore'] as const)
433435
const { alerts } = pkgData
434436
this.decorationType = decorationTypes.informativeDecoration
435437
for (let i = 0, { length } = alerts; i < length; i += 1) {
436-
const { action } = alerts[i]
438+
const { action } = alerts[i]!
437439
if (action === 'error') {
438440
this.decorationType = decorationTypes.errorDecoration
439441
break
@@ -453,13 +455,13 @@ class DecorationManagerForDocument {
453455
// parameterized, shared across all instances
454456
purlManagers: DecorationManagerForPURLCache
455457
async provideHover(
456-
document: vscode.TextDocument,
458+
_document: vscode.TextDocument,
457459
position: vscode.Position,
458460
): Promise<vscode.Hover | undefined> {
459461
// oxlint-disable-next-line socket/prefer-cached-for-loop -- iterating a Map.
460462
for (const [purl, { ranges }] of this.externalRefs) {
461463
for (let i = 0, { length } = ranges; i < length; i += 1) {
462-
const range = ranges[i]
464+
const range = ranges[i]!
463465
const intersects = range.contains(position)
464466
// logger.warn(document.getText(range), 'hovering over range', range, 'for purl', purl, 'intersects:', intersects, 'at position', position);
465467
if (intersects) {
@@ -528,7 +530,7 @@ class DecorationManagerForDocument {
528530
break
529531
}
530532
for (let i = 0, { length } = existing.ranges; i < length; i += 1) {
531-
if (!ranges[i].isEqual(existing.ranges[i])) {
533+
if (!ranges[i]!.isEqual(existing.ranges[i]!)) {
532534
isDirty = true
533535
break check_each_purl_is_same_ranges
534536
}
@@ -592,7 +594,7 @@ class DecorationManagerForDocument {
592594
)
593595
const visibleEditors = vscode.window.visibleTextEditors
594596
for (let i = 0, { length } = visibleEditors; i < length; i += 1) {
595-
const editor = visibleEditors[i]
597+
const editor = visibleEditors[i]!
596598
const editorURI = editor.document.uri.toString() as TextDocumentURIString
597599
if (editorURI === this.docURI) {
598600
logger.debug(`Matching editor ${editorURI} for decoration update`)

0 commit comments

Comments
 (0)