@mjasnikovs/pi-nop 0.0.0-stage → 0.1.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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +114 -2
  3. package/assets/hero.png +0 -0
  4. package/assets/hero.svg +1 -0
  5. package/package.json +85 -5
  6. package/src/config/box.ts +29 -0
  7. package/src/config/command.ts +138 -0
  8. package/src/config/config.ts +238 -0
  9. package/src/config/sections.ts +58 -0
  10. package/src/index.ts +17 -0
  11. package/src/plan/ask.ts +226 -0
  12. package/src/plan/goal.ts +43 -0
  13. package/src/plan/panel.ts +567 -0
  14. package/src/plan/plan.ts +581 -0
  15. package/src/plan/steps.ts +192 -0
  16. package/src/plan/track.ts +133 -0
  17. package/src/search/brave.ts +56 -0
  18. package/src/search/ddg.ts +67 -0
  19. package/src/search/engines.ts +63 -0
  20. package/src/search/exa.ts +74 -0
  21. package/src/search/search.ts +58 -0
  22. package/src/subagent/answer.ts +151 -0
  23. package/src/subagent/budget.ts +19 -0
  24. package/src/subagent/describe.ts +8 -0
  25. package/src/subagent/docs/docs.ts +123 -0
  26. package/src/subagent/docs/files.ts +89 -0
  27. package/src/subagent/docs/header.ts +60 -0
  28. package/src/subagent/docs/locate.ts +261 -0
  29. package/src/subagent/docs/manifest.ts +43 -0
  30. package/src/subagent/docs/npm.ts +247 -0
  31. package/src/subagent/fetch/digest.ts +379 -0
  32. package/src/subagent/fetch/errors.ts +10 -0
  33. package/src/subagent/fetch/fetch.ts +176 -0
  34. package/src/subagent/fetch/pdf.ts +115 -0
  35. package/src/subagent/guards/churn.ts +37 -0
  36. package/src/subagent/guards/circle.ts +49 -0
  37. package/src/subagent/guards/ground.ts +75 -0
  38. package/src/subagent/guards/guard.ts +24 -0
  39. package/src/subagent/guards/guards.ts +107 -0
  40. package/src/subagent/guards/key.ts +13 -0
  41. package/src/subagent/guards/leak.ts +42 -0
  42. package/src/subagent/guards/lines.ts +24 -0
  43. package/src/subagent/guards/loop.ts +77 -0
  44. package/src/subagent/guards/repeat.ts +70 -0
  45. package/src/subagent/guards/stale.ts +38 -0
  46. package/src/subagent/guards/toolCall.ts +46 -0
  47. package/src/subagent/guards/visited.ts +89 -0
  48. package/src/subagent/progress.ts +34 -0
  49. package/src/subagent/slots.ts +42 -0
  50. package/src/subagent/subagent.ts +537 -0
  51. package/src/subagent/subagentTui.ts +292 -0
  52. package/src/tui/hidden.ts +16 -0
  53. package/src/tui/spinner.ts +64 -0
  54. package/src/types/turndown-plugin-gfm.d.ts +5 -0
@@ -0,0 +1,261 @@
1
+ import {existsSync, realpathSync} from 'node:fs'
2
+ import {isBuiltin} from 'node:module'
3
+ import {dirname, join, sep} from 'node:path'
4
+ import ts from 'typescript'
5
+
6
+ import {isNamed, readManifest} from './manifest'
7
+ import type {Named} from './manifest'
8
+ import {download, packTarget, resolveVersion, versionPattern} from './npm'
9
+ import type {Wanted} from './npm'
10
+
11
+ enum LocateErrors {
12
+ Builtin = 'Docs failed: runtime module without its types package installed: ',
13
+ BadName = 'Docs failed: not an npm package name: ',
14
+ BadVersion = 'Docs failed: not a version or dist-tag: ',
15
+ NoManifest = 'Docs failed: no package.json for ',
16
+ NotUnpacked = 'Docs failed: unpacked but not found: '
17
+ }
18
+
19
+ type Package = {
20
+ manifest: Named
21
+ dir: string
22
+ }
23
+
24
+ type Origin = 'installed' | 'downloaded' | 'types-only' | 'runtime'
25
+
26
+ type Located = {
27
+ /** The name asked for; the folder name under an npm alias, `node:fs` for a runtime module. */
28
+ asked: string
29
+ pkg: Package
30
+ source: Origin
31
+ entry?: string
32
+ /** Other packages that hold the declarations: @types/x, or what a one-line stub points at. */
33
+ types: Package[]
34
+ /** The version on disk, when a downloaded one was asked for instead. */
35
+ installed?: string
36
+ }
37
+
38
+ type Project = {
39
+ path?: string
40
+ range?: string
41
+ }
42
+
43
+ const resolveOptions: ts.CompilerOptions = {moduleResolution: ts.ModuleResolutionKind.Bundler}
44
+ const packageNamePattern = /^(@[^/\s@:]+\/)?[^./\s@:-][^/\s@:]*$/
45
+ const runtimePrefix = /^(node|bun):/
46
+
47
+ const packageName = (module: string): string => {
48
+ const parts = module.split('/')
49
+ return parts[0]?.startsWith('@') ? parts.slice(0, 2).join('/') : (parts[0] ?? module)
50
+ }
51
+
52
+ const typesModule = (module: string): string | undefined => {
53
+ if (module.startsWith('bun:')) return 'bun'
54
+ return module.startsWith('node:') || isBuiltin(module) ? 'node' : undefined
55
+ }
56
+
57
+ // A subpath segment of `.` or `..` would resolve into another package.
58
+ const assertPackage = (module: string): void => {
59
+ const dotted = module.split('/').some(segment => segment === '.' || segment === '..')
60
+
61
+ if (dotted || !packageNamePattern.test(packageName(module)))
62
+ throw new Error(LocateErrors.BadName + module)
63
+ }
64
+
65
+ const findUp = (from: string, test: (dir: string) => boolean): string | undefined => {
66
+ for (let dir = from; ; dir = dirname(dir)) {
67
+ if (test(dir)) return dir
68
+ if (dirname(dir) === dir) return undefined
69
+ }
70
+ }
71
+
72
+ const hasManifest = (dir: string): boolean => existsSync(join(dir, 'package.json'))
73
+
74
+ const readPackage = (dir: string): Package => {
75
+ const manifest = readManifest(dir)
76
+
77
+ if (!isNamed(manifest)) throw new Error(LocateErrors.NoManifest + dir)
78
+ return {manifest, dir}
79
+ }
80
+
81
+ const packages = (located: Located): Package[] => [located.pkg, ...located.types]
82
+
83
+ const projectOf = (name: string, cwd: string): Project => {
84
+ const dir = findUp(cwd, hasManifest)
85
+
86
+ if (dir === undefined) return {}
87
+
88
+ const manifest = readManifest(dir)
89
+ const range =
90
+ manifest.dependencies?.[name]
91
+ ?? manifest.devDependencies?.[name]
92
+ ?? manifest.peerDependencies?.[name]
93
+ ?? manifest.optionalDependencies?.[name]
94
+ return {path: join(dir, 'package.json'), range}
95
+ }
96
+
97
+ const findPackageDir = (name: string, cwd: string): string | undefined => {
98
+ const dir = findUp(cwd, here => hasManifest(join(here, 'node_modules', name)))
99
+ return dir === undefined ? undefined : realpathSync(join(dir, 'node_modules', name))
100
+ }
101
+
102
+ const packageRootOf = (file: string, name: string): string => {
103
+ const dir = findUp(dirname(file), here => hasManifest(here) && readManifest(here).name === name)
104
+
105
+ if (dir === undefined) throw new Error(`${LocateErrors.NoManifest}${name} above ${file}`)
106
+ return dir
107
+ }
108
+
109
+ // One hop only: bun-types references node, which is not the package asked about.
110
+ const stubTargets = (entry: string): Package[] => {
111
+ const text = ts.sys.readFile(entry) ?? ''
112
+
113
+ if (ts.createSourceFile(entry, text, ts.ScriptTarget.Latest).statements.length > 0) return []
114
+ return ts.preProcessFile(text).typeReferenceDirectives.flatMap(({fileName}) => {
115
+ const resolved = ts.resolveTypeReferenceDirective(
116
+ fileName,
117
+ entry,
118
+ {},
119
+ ts.sys
120
+ ).resolvedTypeReferenceDirective
121
+ const name = resolved?.packageId?.name
122
+
123
+ if (name === undefined || resolved?.resolvedFileName === undefined) return []
124
+ return [readPackage(packageRootOf(realpathSync(resolved.resolvedFileName), name))]
125
+ })
126
+ }
127
+
128
+ // TypeScript resolves relative to a containing file, which need not exist.
129
+ const resolveEntry = (module: string, cwd: string): ts.ResolvedModuleFull | undefined => {
130
+ const resolved = ts.resolveModuleName(
131
+ module,
132
+ join(cwd, 'pi-nop.ts'),
133
+ resolveOptions,
134
+ ts.sys
135
+ ).resolvedModule
136
+
137
+ if (resolved === undefined) return undefined
138
+ return {...resolved, resolvedFileName: realpathSync(resolved.resolvedFileName)}
139
+ }
140
+
141
+ // The package a resolved entry belongs to: the asked one, or @types/x when that answered.
142
+ const packageOf = (resolved?: ts.ResolvedModuleFull): Package | undefined => {
143
+ const name = resolved?.packageId?.name
144
+
145
+ if (resolved === undefined || name === undefined) return undefined
146
+ return readPackage(packageRootOf(resolved.resolvedFileName, name))
147
+ }
148
+
149
+ // @types/x answered for x. Under an npm alias the names match and nothing is added.
150
+ const typesFor = (pkg: Package, resolved: Package | undefined, stubs: Package[]): Package[] => {
151
+ if (resolved === undefined || resolved.manifest.name === pkg.manifest.name) return stubs
152
+ return [resolved, ...stubs]
153
+ }
154
+
155
+ type Found = Omit<Located, 'asked' | 'source'> & {onDisk: boolean}
156
+
157
+ const asLocated = (asked: string, source: Origin, {onDisk: _onDisk, ...found}: Found): Located => ({
158
+ asked,
159
+ source,
160
+ ...found
161
+ })
162
+
163
+ const packageAt = (
164
+ module: string,
165
+ cwd: string,
166
+ resolved?: ts.ResolvedModuleFull
167
+ ): Found | undefined => {
168
+ const dir = findPackageDir(packageName(module), cwd)
169
+ const resolvedPackage = packageOf(resolved)
170
+ const pkg = dir === undefined ? resolvedPackage : readPackage(dir)
171
+
172
+ if (pkg === undefined) return undefined
173
+
174
+ const stubs =
175
+ resolved?.extension.startsWith('.d.') === true ? stubTargets(resolved.resolvedFileName) : []
176
+ return {
177
+ pkg,
178
+ entry: resolved?.resolvedFileName,
179
+ types: typesFor(pkg, resolvedPackage, stubs),
180
+ onDisk: dir !== undefined
181
+ }
182
+ }
183
+
184
+ // Only a package on disk can satisfy a version; @types/x carries its own numbering.
185
+ const matchesVersion = (local: Found, version?: string): boolean =>
186
+ version === undefined || (local.onDisk && version === local.pkg.manifest.version)
187
+
188
+ const locateIn = (module: string, cwd: string): Found | undefined =>
189
+ packageAt(module, cwd, resolveEntry(module, cwd))
190
+
191
+ // A tree unpacked into the cache must not pick up a stray @types from an ancestor node_modules.
192
+ const locateDownloaded = (module: string, root: string): Found | undefined => {
193
+ const fence = realpathSync(root) + sep
194
+ const resolved = resolveEntry(module, root)
195
+ const inside = resolved?.resolvedFileName.startsWith(fence) === true
196
+ const found = packageAt(module, root, inside ? resolved : undefined)
197
+
198
+ if (found === undefined) return undefined
199
+ return {...found, types: found.types.filter(pkg => pkg.dir.startsWith(fence))}
200
+ }
201
+
202
+ const locate = async (
203
+ module: string,
204
+ cwd: string,
205
+ wanted: Wanted = {},
206
+ signal?: AbortSignal
207
+ ): Promise<Located> => {
208
+ const prefixed = runtimePrefix.test(module)
209
+
210
+ if (!prefixed) assertPackage(module)
211
+ if (wanted.version !== undefined && !versionPattern.test(wanted.version))
212
+ throw new Error(LocateErrors.BadVersion + wanted.version)
213
+
214
+ const name = packageName(module)
215
+ // A builtin name the project declares, or pins, is the npm package. Otherwise it is node's,
216
+ // from @types/node, even when a dependency hoisted a same-named polyfill into node_modules.
217
+ const runtime = typesModule(module)
218
+ const unpinned = wanted.version === undefined && wanted.range === undefined
219
+
220
+ // The `bun` npm package is the binary; only resolved declarations count as its types.
221
+ if (runtime !== undefined && (prefixed || unpinned)) {
222
+ const types = locateIn(runtime, cwd)
223
+
224
+ if (types?.entry === undefined) throw new Error(LocateErrors.Builtin + module)
225
+ if (!types.onDisk) return asLocated(module, 'runtime', types)
226
+
227
+ // node_modules/bun is the binary; the declarations are the first package after it.
228
+ const [pkg, ...rest] = types.types
229
+
230
+ if (pkg === undefined) throw new Error(LocateErrors.Builtin + module)
231
+ return asLocated(module, 'runtime', {...types, pkg, types: rest})
232
+ }
233
+
234
+ const local = locateIn(module, cwd)
235
+ const want = local?.onDisk === true ? await resolveVersion(name, wanted, cwd, signal) : wanted
236
+
237
+ if (local !== undefined && matchesVersion(local, want.version))
238
+ return asLocated(name, local.onDisk ? 'installed' : 'types-only', local)
239
+
240
+ const root = await download(name, packTarget(name, want), cwd, signal)
241
+ const fetched = locateDownloaded(module, root)
242
+
243
+ if (fetched === undefined) throw new Error(`${LocateErrors.NotUnpacked}${module} in ${root}`)
244
+ return {
245
+ ...asLocated(name, 'downloaded', fetched),
246
+ installed: local?.onDisk === true ? local.pkg.manifest.version : undefined
247
+ }
248
+ }
249
+
250
+ export {
251
+ assertPackage,
252
+ locate,
253
+ locateDownloaded,
254
+ LocateErrors,
255
+ locateIn,
256
+ packageName,
257
+ packages,
258
+ projectOf,
259
+ typesModule
260
+ }
261
+ export type {Located, Package, Project}
@@ -0,0 +1,43 @@
1
+ import {readFileSync} from 'node:fs'
2
+ import {join} from 'node:path'
3
+ import {type Static, Type} from 'typebox'
4
+ import Value from 'typebox/value'
5
+
6
+ const deps = Type.Optional(Type.Record(Type.String(), Type.String()))
7
+ // A project root or a nested `{"type": "module"}` marker may have no name.
8
+ const manifestSchema = Type.Object({
9
+ name: Type.Optional(Type.String()),
10
+ /** A workspace or git package may ship none. */
11
+ version: Type.Optional(Type.String()),
12
+ homepage: Type.Optional(Type.String()),
13
+ repository: Type.Optional(
14
+ Type.Union([Type.String(), Type.Object({url: Type.Optional(Type.String())})])
15
+ ),
16
+ dependencies: deps,
17
+ devDependencies: deps,
18
+ peerDependencies: deps,
19
+ optionalDependencies: deps
20
+ })
21
+
22
+ type Manifest = Static<typeof manifestSchema>
23
+ type Named = Manifest & {name: string}
24
+
25
+ const fields = Type.Record(Type.String(), Type.Unknown())
26
+ const promised = (key: string, value: unknown): boolean =>
27
+ Object.hasOwn(manifestSchema.properties, key)
28
+ && Value.Check(manifestSchema.properties[key as keyof Manifest], value)
29
+
30
+ // A field that is not what package.json promises is dropped, not trusted.
31
+ const readManifest = (dir: string): Manifest => {
32
+ const raw = Value.Parse(fields, JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')))
33
+ const kept = Object.entries(raw).filter(([key, value]) => promised(key, value))
34
+ return Value.Parse(manifestSchema, Object.fromEntries(kept))
35
+ }
36
+
37
+ const isNamed = (manifest: Manifest): manifest is Named => manifest.name !== undefined
38
+
39
+ const spec = (manifest: Named): string =>
40
+ manifest.version === undefined ? manifest.name : `${manifest.name}@${manifest.version}`
41
+
42
+ export {isNamed, readManifest, spec}
43
+ export type {Manifest, Named}
@@ -0,0 +1,247 @@
1
+ import {execFile} from 'node:child_process'
2
+ import {existsSync, mkdirSync, mkdtempSync, renameSync, rmSync} from 'node:fs'
3
+ import {join} from 'node:path'
4
+ import {promisify} from 'node:util'
5
+ import {getAgentDir} from '@earendil-works/pi-coding-agent'
6
+ import {Type} from 'typebox'
7
+ import Value from 'typebox/value'
8
+
9
+ import {describe} from '../describe'
10
+ import {unlessAborted} from '../subagent'
11
+ import {readManifest} from './manifest'
12
+
13
+ const run = promisify(execFile)
14
+
15
+ enum NpmErrors {
16
+ Missing = 'not on npm: ',
17
+ Failed = 'npm failed: ',
18
+ Unservable = 'Docs failed: not installed, and declared from outside the registry: '
19
+ }
20
+
21
+ type Wanted = {
22
+ version?: string
23
+ range?: string
24
+ }
25
+
26
+ type Target = {
27
+ /** The registry package: the alias target under an npm: range. */
28
+ name: string
29
+ spec: string
30
+ }
31
+
32
+ type View = {
33
+ version: string
34
+ deprecated?: string
35
+ latest: string
36
+ }
37
+
38
+ // npm's codes for "no such package or version". Anything else is npm or the network failing.
39
+ const missingCodes = ['E404', 'ETARGET', 'EINVALIDTAGNAME', 'EINVALIDPACKAGENAME']
40
+
41
+ // npm 10 prints `npm error code X`; npm 9 printed `npm ERR! code X`.
42
+ const npmCode = (error: unknown): string => {
43
+ const text = describe(error)
44
+ return /^npm (error|ERR!) code (\S+)/m.exec(text)?.[2] ?? text
45
+ }
46
+
47
+ // npm runs in the project, so .npmrc scopes, mirrors and auth hold, the same as an install would.
48
+ const npm = async (
49
+ target: Target,
50
+ args: string[],
51
+ cwd: string,
52
+ signal?: AbortSignal
53
+ ): Promise<string> =>
54
+ run('npm', args, {cwd, signal})
55
+ .then(({stdout}) => stdout)
56
+ .catch((error: unknown) => {
57
+ unlessAborted(signal, error)
58
+ const code = npmCode(error)
59
+ const lead = missingCodes.includes(code) ? NpmErrors.Missing : NpmErrors.Failed
60
+ throw new Error(`${lead}${target.name}@${target.spec} (${code})`, {cause: error})
61
+ })
62
+
63
+ const viewed = Type.Object({
64
+ version: Type.String(),
65
+ deprecated: Type.Optional(Type.String()),
66
+ 'dist-tags.latest': Type.String()
67
+ })
68
+ const viewedShape = Type.Union([viewed, Type.Array(viewed)])
69
+
70
+ // `name` and `version` always exist, so the answer is an object, or an array of them for a range.
71
+ const view = async (target: Target, cwd: string, signal?: AbortSignal): Promise<View> => {
72
+ const fields = ['name', 'version', 'deprecated', 'dist-tags.latest']
73
+ const stdout = await npm(
74
+ target,
75
+ ['view', '--json', '--', `${target.name}@${target.spec}`, ...fields],
76
+ cwd,
77
+ signal
78
+ )
79
+ const parsed = Value.Parse(viewedShape, JSON.parse(stdout))
80
+ const last = Array.isArray(parsed) ? parsed.at(-1) : parsed
81
+
82
+ if (last === undefined)
83
+ throw new Error(`${NpmErrors.Missing}${target.name}@${target.spec} (empty)`)
84
+ return {version: last.version, deprecated: last.deprecated, latest: last['dist-tags.latest']}
85
+ }
86
+
87
+ type Facts = {
88
+ latest?: string
89
+ deprecated?: string
90
+ error?: string
91
+ }
92
+
93
+ // Our own errors carry npm's whole stderr as `cause`; the header wants the one-line message.
94
+ const message = (error: unknown): string => (error instanceof Error ? error.message : String(error))
95
+ const isMissing = (error: unknown): boolean => message(error).startsWith(NpmErrors.Missing)
96
+
97
+ // The registry view of one package: latest, and the deprecation of the version in hand. A
98
+ // version the registry never saw (a git install) is simply not deprecated.
99
+ const facts = async (
100
+ name: string,
101
+ version: string | undefined,
102
+ cwd: string,
103
+ signal?: AbortSignal
104
+ ): Promise<Facts> => {
105
+ try {
106
+ const seen = await view({name, spec: version ?? 'latest'}, cwd, signal)
107
+ return {latest: seen.latest, deprecated: seen.deprecated}
108
+ } catch (error) {
109
+ if (signal?.aborted) throw error
110
+ if (version === undefined || !isMissing(error)) return {error: message(error)}
111
+ return facts(name, undefined, cwd, signal)
112
+ }
113
+ }
114
+
115
+ const cacheDir = (): string => join(getAgentDir(), 'cache', 'pi-nop-docs')
116
+
117
+ // An alias tree is keyed by both names, so real foo@1 and foo aliasing bar@1 never share a folder.
118
+ const cacheRoot = (asked: string, name: string, version: string): string => {
119
+ const label = asked === name ? `${asked}@${version}` : `${asked}=${name}@${version}`
120
+ return join(cacheDir(), label.replaceAll('/', '+'))
121
+ }
122
+
123
+ // Two callers may finish the same unpack together; the tree already there is as good as ours.
124
+ const moveIntoCache = (tree: string, root: string): void => {
125
+ try {
126
+ renameSync(tree, root)
127
+ } catch (error) {
128
+ if (!existsSync(root)) throw error
129
+ }
130
+ }
131
+
132
+ const unpack = async (
133
+ asked: string,
134
+ target: Target,
135
+ scratch: string,
136
+ cwd: string,
137
+ signal?: AbortSignal
138
+ ): Promise<string> => {
139
+ const stdout = await npm(
140
+ target,
141
+ [
142
+ 'pack',
143
+ '--ignore-scripts',
144
+ '--pack-destination',
145
+ scratch,
146
+ '--',
147
+ `${target.name}@${target.spec}`
148
+ ],
149
+ cwd,
150
+ signal
151
+ )
152
+ const tarball = join(scratch, stdout.trim().split('\n').at(-1) ?? '')
153
+ const dir = join(scratch, 'tree', 'node_modules', asked)
154
+ mkdirSync(dir, {recursive: true})
155
+ await run('tar', ['-xzf', tarball, '-C', dir, '--strip-components=1'], {signal}).catch(
156
+ (error: unknown) => {
157
+ unlessAborted(signal, error)
158
+ throw error
159
+ }
160
+ )
161
+ return join(scratch, 'tree')
162
+ }
163
+
164
+ const exactVersion = /^\d+\.\d+\.\d+(-[\w.-]+)?$/
165
+
166
+ // A tag names one version, so it is looked up and can hit the cache. A range is left to
167
+ // `npm pack`, which picks the highest match the way an install would; `npm view` lists in
168
+ // publish order.
169
+ const isRange = (spec: string): boolean =>
170
+ !exactVersion.test(spec) && /^[\d^~<>=*]|[\s|]/.test(spec)
171
+
172
+ // The scratch folder goes whatever happens, so a lost rename or a failure leaves nothing behind.
173
+ const unpackIntoCache = async (
174
+ asked: string,
175
+ target: Target,
176
+ cwd: string,
177
+ signal?: AbortSignal
178
+ ): Promise<string> => {
179
+ mkdirSync(cacheDir(), {recursive: true})
180
+ const scratch = mkdtempSync(join(cacheDir(), 'pack-'))
181
+
182
+ try {
183
+ const tree = await unpack(asked, target, scratch, cwd, signal)
184
+ const version = readManifest(join(tree, 'node_modules', asked)).version ?? target.spec
185
+ const root = cacheRoot(asked, target.name, version)
186
+ moveIntoCache(tree, root)
187
+ return root
188
+ } finally {
189
+ rmSync(scratch, {recursive: true, force: true})
190
+ }
191
+ }
192
+
193
+ const download = async (
194
+ asked: string,
195
+ target: Target,
196
+ cwd: string,
197
+ signal?: AbortSignal
198
+ ): Promise<string> => {
199
+ if (exactVersion.test(target.spec)) {
200
+ const known = cacheRoot(asked, target.name, target.spec)
201
+ return existsSync(known) ? known : unpackIntoCache(asked, target, cwd, signal)
202
+ }
203
+
204
+ if (isRange(target.spec)) return unpackIntoCache(asked, target, cwd, signal)
205
+
206
+ const {version} = await view(target, cwd, signal)
207
+ return download(asked, {name: target.name, spec: version}, cwd, signal)
208
+ }
209
+
210
+ // A version from the model is an exact version or a dist-tag, never a path, URL or protocol.
211
+ const versionPattern = /^[\w.-]+$/
212
+
213
+ // "latest" or a tag is the registry's word for a version; the installed copy may be it.
214
+ const resolveVersion = async (
215
+ asked: string,
216
+ wanted: Wanted,
217
+ cwd: string,
218
+ signal?: AbortSignal
219
+ ): Promise<Wanted> => {
220
+ if (
221
+ wanted.version === undefined
222
+ || exactVersion.test(wanted.version)
223
+ || isRange(wanted.version)
224
+ )
225
+ return wanted
226
+ return {...wanted, version: (await view(packTarget(asked, wanted), cwd, signal)).version}
227
+ }
228
+
229
+ // A workspace:, file: or git range names something the registry does not have, and a
230
+ // same-named stranger there would be the wrong answer. An npm: range names the real package.
231
+ const fromRegistry = (range: string | undefined): boolean =>
232
+ range === undefined || range.startsWith('npm:') || !/[:/]/.test(range)
233
+
234
+ const packTarget = (asked: string, wanted: Wanted): Target => {
235
+ if (!fromRegistry(wanted.range))
236
+ throw new Error(`${NpmErrors.Unservable}${asked} (${wanted.range})`)
237
+
238
+ const alias = /^npm:(.+?)(?:@([^@]+))?$/.exec(wanted.range ?? '')
239
+ const name = alias?.[1] ?? asked
240
+ const range = alias === null ? wanted.range : alias[2]
241
+
242
+ if (wanted.version !== undefined) return {name, spec: wanted.version}
243
+ return {name, spec: range ?? 'latest'}
244
+ }
245
+
246
+ export {download, facts, fromRegistry, packTarget, resolveVersion, versionPattern, view}
247
+ export type {Facts, Wanted}