@yaks/cli 0.0.0-stage → 0.2.36

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 (331) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1059 -2
  3. package/_dist/account-forward.d.ts +12 -0
  4. package/_dist/account-forward.d.ts.map +1 -0
  5. package/_dist/accounts.d.ts +23 -0
  6. package/_dist/accounts.d.ts.map +1 -0
  7. package/_dist/answer.d.ts +88 -0
  8. package/_dist/answer.d.ts.map +1 -0
  9. package/_dist/apply.d.ts +17 -0
  10. package/_dist/apply.d.ts.map +1 -0
  11. package/_dist/args.d.ts +86 -0
  12. package/_dist/args.d.ts.map +1 -0
  13. package/_dist/commands.d.ts +15 -0
  14. package/_dist/commands.d.ts.map +1 -0
  15. package/_dist/complete.d.ts +15 -0
  16. package/_dist/complete.d.ts.map +1 -0
  17. package/_dist/config.d.ts +37 -0
  18. package/_dist/config.d.ts.map +1 -0
  19. package/_dist/dependencies.d.ts +6 -0
  20. package/_dist/dependencies.d.ts.map +1 -0
  21. package/_dist/facets.d.ts +71 -0
  22. package/_dist/facets.d.ts.map +1 -0
  23. package/_dist/grammar.d.ts +5 -0
  24. package/_dist/grammar.d.ts.map +1 -0
  25. package/_dist/host.d.ts +164 -0
  26. package/_dist/host.d.ts.map +1 -0
  27. package/_dist/install.d.ts +43 -0
  28. package/_dist/install.d.ts.map +1 -0
  29. package/_dist/main.d.ts +16 -0
  30. package/_dist/main.d.ts.map +1 -0
  31. package/_dist/memo.d.ts +60 -0
  32. package/_dist/memo.d.ts.map +1 -0
  33. package/_dist/mod.d.ts +46 -0
  34. package/_dist/mod.d.ts.map +1 -0
  35. package/_dist/page.d.ts +73 -0
  36. package/_dist/page.d.ts.map +1 -0
  37. package/_dist/platform.d.ts +27 -0
  38. package/_dist/platform.d.ts.map +1 -0
  39. package/_dist/reader.d.ts +10 -0
  40. package/_dist/reader.d.ts.map +1 -0
  41. package/_dist/release.d.ts +48 -0
  42. package/_dist/release.d.ts.map +1 -0
  43. package/_dist/remote.d.ts +13 -0
  44. package/_dist/remote.d.ts.map +1 -0
  45. package/_dist/reported.d.ts +11 -0
  46. package/_dist/reported.d.ts.map +1 -0
  47. package/_dist/roles.d.ts +2 -0
  48. package/_dist/roles.d.ts.map +1 -0
  49. package/_dist/roster.d.ts +41 -0
  50. package/_dist/roster.d.ts.map +1 -0
  51. package/_dist/rpc.d.ts +29 -0
  52. package/_dist/rpc.d.ts.map +1 -0
  53. package/_dist/run.d.ts +164 -0
  54. package/_dist/run.d.ts.map +1 -0
  55. package/_dist/runtime.d.ts +4 -0
  56. package/_dist/runtime.d.ts.map +1 -0
  57. package/_dist/searching.d.ts +7 -0
  58. package/_dist/searching.d.ts.map +1 -0
  59. package/_dist/show.d.ts +22 -0
  60. package/_dist/show.d.ts.map +1 -0
  61. package/_dist/store.d.ts +25 -0
  62. package/_dist/store.d.ts.map +1 -0
  63. package/_dist/terminal.d.ts +17 -0
  64. package/_dist/terminal.d.ts.map +1 -0
  65. package/_dist/tool.d.ts +55 -0
  66. package/_dist/tool.d.ts.map +1 -0
  67. package/_dist/tty.d.ts +3 -0
  68. package/_dist/tty.d.ts.map +1 -0
  69. package/_dist/vault.d.ts +9 -0
  70. package/_dist/vault.d.ts.map +1 -0
  71. package/_dist/words.d.ts +11 -0
  72. package/_dist/words.d.ts.map +1 -0
  73. package/_dist/yak.d.ts +10 -0
  74. package/_dist/yak.d.ts.map +1 -0
  75. package/account-forward.js +40 -0
  76. package/account-forward.js.map +1 -0
  77. package/account-forward.ts +50 -0
  78. package/accounts.js +162 -0
  79. package/accounts.js.map +1 -0
  80. package/accounts.ts +228 -0
  81. package/answer.js +394 -0
  82. package/answer.js.map +1 -0
  83. package/answer.ts +569 -0
  84. package/apply.js +49 -0
  85. package/apply.js.map +1 -0
  86. package/apply.ts +54 -0
  87. package/args.js +420 -0
  88. package/args.js.map +1 -0
  89. package/args.ts +494 -0
  90. package/code.js +209 -0
  91. package/code.js.map +1 -0
  92. package/code.ts +227 -0
  93. package/commands.js +131 -0
  94. package/commands.js.map +1 -0
  95. package/commands.ts +142 -0
  96. package/complete.js +104 -0
  97. package/complete.js.map +1 -0
  98. package/complete.ts +152 -0
  99. package/config.js +125 -0
  100. package/config.js.map +1 -0
  101. package/config.ts +180 -0
  102. package/declarations.js +67 -0
  103. package/declarations.js.map +1 -0
  104. package/declarations.ts +84 -0
  105. package/deno.json +1 -0
  106. package/dependencies.js +126 -0
  107. package/dependencies.js.map +1 -0
  108. package/dependencies.ts +141 -0
  109. package/derive.js +102 -0
  110. package/derive.js.map +1 -0
  111. package/derive.ts +125 -0
  112. package/drain.js +83 -0
  113. package/drain.js.map +1 -0
  114. package/drain.ts +115 -0
  115. package/duties.ts +17 -0
  116. package/exports.json +1486 -0
  117. package/external.js +373 -0
  118. package/external.js.map +1 -0
  119. package/external.ts +435 -0
  120. package/facets.js +214 -0
  121. package/facets.js.map +1 -0
  122. package/facets.ts +232 -0
  123. package/feedback.js +54 -0
  124. package/feedback.js.map +1 -0
  125. package/feedback.ts +57 -0
  126. package/files.js +84 -0
  127. package/files.js.map +1 -0
  128. package/files.ts +112 -0
  129. package/get_starts.js +31 -0
  130. package/get_starts.js.map +1 -0
  131. package/get_starts.ts +34 -0
  132. package/git-credential.js +79 -0
  133. package/git-credential.js.map +1 -0
  134. package/git-credential.ts +77 -0
  135. package/grammar.js +4 -0
  136. package/grammar.js.map +1 -0
  137. package/grammar.ts +5 -0
  138. package/held.js +51 -0
  139. package/held.js.map +1 -0
  140. package/held.ts +66 -0
  141. package/host.js +1174 -0
  142. package/host.js.map +1 -0
  143. package/host.ts +1343 -0
  144. package/init.js +138 -0
  145. package/init.js.map +1 -0
  146. package/init.ts +139 -0
  147. package/install.js +216 -0
  148. package/install.js.map +1 -0
  149. package/install.ts +223 -0
  150. package/lifetime.js +56 -0
  151. package/lifetime.js.map +1 -0
  152. package/lifetime.ts +66 -0
  153. package/local-page.ts +114 -0
  154. package/local.js +417 -0
  155. package/local.js.map +1 -0
  156. package/local.ts +537 -0
  157. package/lockfile.js +20 -0
  158. package/lockfile.js.map +1 -0
  159. package/lockfile.ts +32 -0
  160. package/machines.js +33 -0
  161. package/machines.js.map +1 -0
  162. package/machines.ts +51 -0
  163. package/made/4f855610bdabcd736100d34e4e467ea5.json +1 -0
  164. package/main.js +534 -0
  165. package/main.js.map +1 -0
  166. package/main.ts +547 -0
  167. package/mcp.js +108 -0
  168. package/mcp.js.map +1 -0
  169. package/mcp.ts +113 -0
  170. package/member.js +103 -0
  171. package/member.js.map +1 -0
  172. package/member.ts +133 -0
  173. package/memo.js +503 -0
  174. package/memo.js.map +1 -0
  175. package/memo.ts +634 -0
  176. package/mod.js +46 -0
  177. package/mod.js.map +1 -0
  178. package/mod.ts +99 -0
  179. package/operations.js +53 -0
  180. package/operations.js.map +1 -0
  181. package/operations.ts +68 -0
  182. package/package.json +115 -4
  183. package/page.js +211 -0
  184. package/page.js.map +1 -0
  185. package/page.ts +308 -0
  186. package/parser.js +45 -0
  187. package/parser.js.map +1 -0
  188. package/parser.ts +77 -0
  189. package/people-search.js +112 -0
  190. package/people-search.js.map +1 -0
  191. package/people-search.ts +162 -0
  192. package/platform.js +184 -0
  193. package/platform.js.map +1 -0
  194. package/platform.ts +224 -0
  195. package/platform_effects.js +5 -0
  196. package/platform_effects.js.map +1 -0
  197. package/platform_effects.ts +13 -0
  198. package/prepare.js +40 -0
  199. package/prepare.js.map +1 -0
  200. package/prepare.ts +46 -0
  201. package/read_activity.js +54 -0
  202. package/read_activity.js.map +1 -0
  203. package/read_activity.ts +61 -0
  204. package/read_thread.js +387 -0
  205. package/read_thread.js.map +1 -0
  206. package/read_thread.ts +506 -0
  207. package/read_worker.ts +164 -0
  208. package/reader.js +48 -0
  209. package/reader.js.map +1 -0
  210. package/reader.ts +57 -0
  211. package/release.js +82 -0
  212. package/release.js.map +1 -0
  213. package/release.json +127 -0
  214. package/release.ts +98 -0
  215. package/remote-page.ts +70 -0
  216. package/remote.js +96 -0
  217. package/remote.js.map +1 -0
  218. package/remote.ts +153 -0
  219. package/report.js +83 -0
  220. package/report.js.map +1 -0
  221. package/report.ts +101 -0
  222. package/reported.js +32 -0
  223. package/reported.js.map +1 -0
  224. package/reported.ts +38 -0
  225. package/restart.js +349 -0
  226. package/restart.js.map +1 -0
  227. package/restart.ts +478 -0
  228. package/restore.js +32 -0
  229. package/restore.js.map +1 -0
  230. package/restore.ts +38 -0
  231. package/roles.js +32 -0
  232. package/roles.js.map +1 -0
  233. package/roles.ts +49 -0
  234. package/roster.js +65 -0
  235. package/roster.js.map +1 -0
  236. package/roster.ts +84 -0
  237. package/rpc.js +113 -0
  238. package/rpc.js.map +1 -0
  239. package/rpc.ts +159 -0
  240. package/run.js +533 -0
  241. package/run.js.map +1 -0
  242. package/run.ts +741 -0
  243. package/runtime.js +381 -0
  244. package/runtime.js.map +1 -0
  245. package/runtime.ts +433 -0
  246. package/sandboxes.js +26 -0
  247. package/sandboxes.js.map +1 -0
  248. package/sandboxes.ts +30 -0
  249. package/searching.js +33 -0
  250. package/searching.js.map +1 -0
  251. package/searching.ts +50 -0
  252. package/show.js +109 -0
  253. package/show.js.map +1 -0
  254. package/show.ts +144 -0
  255. package/shown.js +13 -0
  256. package/shown.js.map +1 -0
  257. package/shown.ts +44 -0
  258. package/stall.js +90 -0
  259. package/stall.js.map +1 -0
  260. package/stall.ts +156 -0
  261. package/stall_profile.js +113 -0
  262. package/stall_profile.js.map +1 -0
  263. package/stall_profile.ts +142 -0
  264. package/stall_wait.js +183 -0
  265. package/stall_wait.js.map +1 -0
  266. package/stall_wait.ts +249 -0
  267. package/stall_wait_worker.ts +11 -0
  268. package/start.js +349 -0
  269. package/start.js.map +1 -0
  270. package/start.ts +343 -0
  271. package/starvation.js +147 -0
  272. package/starvation.js.map +1 -0
  273. package/starvation.ts +224 -0
  274. package/store.js +118 -0
  275. package/store.js.map +1 -0
  276. package/store.ts +193 -0
  277. package/subcommands.js +62 -0
  278. package/subcommands.js.map +1 -0
  279. package/subcommands.ts +77 -0
  280. package/terminal.js +93 -0
  281. package/terminal.js.map +1 -0
  282. package/terminal.ts +128 -0
  283. package/text.js +20 -0
  284. package/text.js.map +1 -0
  285. package/text.ts +37 -0
  286. package/tool.js +76 -0
  287. package/tool.js.map +1 -0
  288. package/tool.ts +157 -0
  289. package/trace_control.js +231 -0
  290. package/trace_control.js.map +1 -0
  291. package/trace_control.ts +233 -0
  292. package/traces.js +138 -0
  293. package/traces.js.map +1 -0
  294. package/traces.ts +160 -0
  295. package/tracker.js +22 -0
  296. package/tracker.js.map +1 -0
  297. package/tracker.ts +27 -0
  298. package/tty.js +82 -0
  299. package/tty.js.map +1 -0
  300. package/tty.ts +142 -0
  301. package/unit_failure.js +178 -0
  302. package/unit_failure.js.map +1 -0
  303. package/unit_failure.ts +191 -0
  304. package/upkeep_thread.js +32 -0
  305. package/upkeep_thread.js.map +1 -0
  306. package/upkeep_thread.ts +35 -0
  307. package/upkeep_worker.ts +27 -0
  308. package/vault.js +186 -0
  309. package/vault.js.map +1 -0
  310. package/vault.ts +220 -0
  311. package/vocab-ids.js +63 -0
  312. package/vocab-ids.js.map +1 -0
  313. package/vocab-ids.ts +62 -0
  314. package/vocab.json +35 -0
  315. package/warm.js +138 -0
  316. package/warm.js.map +1 -0
  317. package/warm.ts +171 -0
  318. package/watch_revision.js +25 -0
  319. package/watch_revision.js.map +1 -0
  320. package/watch_revision.ts +30 -0
  321. package/words.js +29 -0
  322. package/words.js.map +1 -0
  323. package/words.ts +41 -0
  324. package/workspaces.js +40 -0
  325. package/workspaces.js.map +1 -0
  326. package/workspaces.ts +58 -0
  327. package/yak-unit-failure.conf +6 -0
  328. package/yak-unit-handoff.conf +2 -0
  329. package/yak.js +123 -0
  330. package/yak.js.map +1 -0
  331. package/yak.ts +136 -0
package/memo.ts ADDED
@@ -0,0 +1,634 @@
1
+ import * as system from '@yaks/process/system'
2
+ import * as disk from '@yaks/file/io'
3
+ import { runtimeTree } from './runtime.js'
4
+ // Derived command declarations, kept between processes while their inputs and
5
+ // sources agree. A memo is disposable: an unreadable memo or a source whose
6
+ // dependencies cannot be proved leaves the ordinary derivation in charge.
7
+ // Every command asks, so a hit is proved the way a version control index
8
+ // proves a clean tree: by each source's stat as it was read, or its
9
+ // directory's stat while it remains absent, and by contents where a stat
10
+ // moved. Inside the snapshot a command runs from (./runtime.ts), which
11
+ // nothing rewrites while it runs, the snapshot's id proves every file. A memo
12
+ // nothing has read for a day (a deleted worktree's, a probe config's, an older
13
+ // version's) goes at the next miss.
14
+
15
+ /** A source module, or an optional facet of a configured package. */
16
+ export type MemoRoot = string | readonly [plugin: string, facet: string]
17
+
18
+ export type MemoFiles = {
19
+ readTextFileSync: (path: string) => string
20
+ statSync: (
21
+ path: string,
22
+ ) => Pick<disk.FileInfo, 'size' | 'mtime' | 'ctime' | 'ino'>
23
+ mkdirSync: (path: string, options: disk.MkdirOptions) => void
24
+ writeTextFileSync: (
25
+ path: string,
26
+ text: string,
27
+ options: disk.WriteFileOptions,
28
+ ) => void
29
+ renameSync: (from: string, to: string) => void
30
+ removeSync: (path: string) => void
31
+ readDirSync: (path: string) => Iterable<{ name: string }>
32
+ utimeSync: (path: string, atime: Date, mtime: Date) => void
33
+ }
34
+
35
+ export type MemoOptions = {
36
+ dir?: string
37
+ files?: MemoFiles
38
+ resolve?: (specifier: string) => string
39
+ /** Function-valued fields excluded from each facet's derived data. */
40
+ callbacks?: { [facet: string]: readonly string[] }
41
+ /** Literal source dependencies; injected at the filesystem boundary in tests. */
42
+ imports?: (source: string, name?: string) => Promise<string[]>
43
+ /** The digest boundary is synchronous in memory tests. */
44
+ digest?: (text: string) => string | Promise<string>
45
+ /** A directory whose files cannot change while this process runs, and the
46
+ * id naming its contents (./runtime.ts `runtimeTree`): a memo kept under
47
+ * the same id proves every file inside it without asking for its stat. */
48
+ tree?: { root: string; id: string }
49
+ }
50
+
51
+ type Record<T> = {
52
+ version: number
53
+ roots: string[]
54
+ files: string[]
55
+ /** each file's stat as its contents were read, '' where they could still
56
+ * change without moving it */
57
+ stats: string[]
58
+ absent?: { [path: string]: readonly [directory: string, stat: string] }
59
+ /** each file's path and contents (or absence), digested */
60
+ sums: string[]
61
+ /** each source module's dependencies, as written in it */
62
+ lexed: { [path: string]: string[] }
63
+ /** the id of the tree (`MemoOptions.tree`) its files inside were read in */
64
+ tree?: string
65
+ value: T
66
+ }
67
+
68
+ let VERSION = 8
69
+ let HOUR = 3_600_000
70
+ let DAY = 24 * HOUR
71
+ let FILES = ['deno.json', 'deno.jsonc']
72
+ let encoder = new TextEncoder()
73
+ let sha256 = async (text: string): Promise<string> =>
74
+ Array.from(
75
+ new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(text))),
76
+ (b) => b.toString(16).padStart(2, '0'),
77
+ ).join('')
78
+ // Each path and present value carries its UTF-16 length; absence has its own
79
+ // marker. Concatenated entries have exactly one reading, including empty files.
80
+ let framed = (path: string, text: string | null): string =>
81
+ `${path.length}:${path}${text === null ? 'n' : `s${text.length}:${text}`}`
82
+ let local = (s: string) => s.startsWith('file:')
83
+ let packaged = (s: string) => /^(?:npm|jsr):/.test(s)
84
+ // A version on JSR never changes once published, so a module jsr.io serves at
85
+ // one (what an installed `yak` resolves its packages to) is as fixed as a
86
+ // pinned specifier.
87
+ let immutable = (s: string) =>
88
+ /^(?:npm|jsr):[^\s]+@\d+\.\d+\.\d+(?:[-+][\w.-]+)?(?:\/|$)/.test(s) ||
89
+ /^https:\/\/jsr\.io\/@[^/]+\/[^/]+\/\d+\.\d+\.\d+(?:[-+][\w.-]+)?\//
90
+ .test(s) ||
91
+ s.startsWith('node:')
92
+ let packageKey = (s: string): string => {
93
+ let key = /^(?:npm|jsr):(?:@[^/]+\/)?[^/@]+@[^/]+/.exec(s)?.[0] ?? s
94
+ // Deno records JSR's ^N.0.0 ranges as N; both describe the same releases.
95
+ return key.startsWith('jsr:')
96
+ ? key.replace(/@\^([1-9]\d*)\.0\.0$/, '@$1')
97
+ : key
98
+ }
99
+ let pathOf = (s: string) => decodeURIComponent(new URL(s).pathname)
100
+
101
+ /** The memos a miss sweeps: those nothing has read for a day. A hit moves its
102
+ * memo's time at most hourly, so a memo in use never ages out.
103
+ *
104
+ * ```ts
105
+ * import { assertEquals } from '@std/assert'
106
+ * let now = Date.parse('2026-10-12T12:00:00Z')
107
+ * assertEquals(
108
+ * idle([
109
+ * { name: 'gone.json', at: now - 2 * 86_400_000 },
110
+ * { name: 'used.json', at: now - 3_600_000 },
111
+ * ], now),
112
+ * ['gone.json'],
113
+ * )
114
+ * ```
115
+ */
116
+ export let idle = (
117
+ entries: readonly { name: string; at: number }[],
118
+ now: number,
119
+ ): string[] => entries.filter((e) => now - e.at > DAY).map((e) => e.name)
120
+
121
+ // No parser in an ordinary memo hit, and no subprocess in either path.
122
+ import type { ImportSpecifier } from 'es-module-lexer/js'
123
+
124
+ export let sourceImports = (
125
+ source: string,
126
+ parsed: readonly ImportSpecifier[],
127
+ ): string[] =>
128
+ parsed.filter((i) => {
129
+ if (!i.n) return false
130
+ if (i.d >= 0) return true
131
+ if (i.d != -1) return false
132
+ let statement = source.slice(i.ss, i.se)
133
+ .replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, ' ')
134
+ if (/^(?:import|export)\s+type\s+(?!from\b)/.test(statement)) return false
135
+ let named = /^(?:import|export)\s*\{([^}]*)\}\s*from\b/.exec(statement)
136
+ let members = named?.[1].split(',').filter((s) => s.trim())
137
+ return !members?.length ||
138
+ !members.every((s) => /^\s*type\s+(?!as\b)/.test(s))
139
+ }).map((i) => i.n!)
140
+
141
+ let importsOf = async (
142
+ source: string,
143
+ name?: string,
144
+ callbacks: readonly string[] = [],
145
+ ): Promise<string[]> => {
146
+ let { parse } = await import('es-module-lexer/js')
147
+ try {
148
+ let parsed = parse(source)[0]
149
+ if (!callbacks.length || !parsed.some((i) => i.d >= 0)) {
150
+ return sourceImports(source, parsed)
151
+ }
152
+ } catch {
153
+ /* TSX needs the syntax-aware scanner too. */
154
+ }
155
+ return (await import('./parser.js')).imports(source, name, callbacks)
156
+ }
157
+
158
+ let directory = (): string | undefined => {
159
+ try {
160
+ let root = system.env.get('XDG_CACHE_HOME')
161
+ let home = system.env.get('HOME')
162
+ return root || home ? `${root ?? `${home}/.cache`}/yak/cli` : undefined
163
+ } catch {
164
+ return undefined
165
+ }
166
+ }
167
+
168
+ /** Reuse JSON data while the configuration and every literal source dependency
169
+ * are unchanged. Static imports and literal dynamic imports are tracked; a
170
+ * caller supplies roots for modules chosen by runtime callbacks. Callbacks
171
+ * projected out of the data keep their imports for invocation. A source agrees
172
+ * while its stat has not moved, or, once it has, while its contents (or its
173
+ * absence) still do. Only the digest of `inputs` is kept; callers project away
174
+ * closures and host capabilities before returning their data. */
175
+ export let remember = async <T>(
176
+ inputs: unknown,
177
+ roots: readonly MemoRoot[],
178
+ make: () => T | Promise<T>,
179
+ opts: MemoOptions & { valid?: (value: T) => boolean | Promise<boolean> } = {},
180
+ ): Promise<T> => {
181
+ let io = opts.files ?? disk
182
+ let digest = opts.digest ?? sha256
183
+ let locate = opts.resolve ?? import.meta.resolve
184
+ let tree = 'tree' in opts ? opts.tree : runtimeTree()
185
+ let resolved = new Map<string, string>()
186
+ let resolve = (specifier: string): string => {
187
+ let known = resolved.get(specifier)
188
+ if (known !== undefined) return known
189
+ let found = locate(specifier)
190
+ resolved.set(specifier, found)
191
+ return found
192
+ }
193
+ let dir = opts.dir ?? directory()
194
+ if (!dir) return await make()
195
+ let file: string
196
+ let identities: string[] = []
197
+ let starts: string[] = []
198
+ let packages: string[] = []
199
+ let callbacks = new Map<string, readonly string[]>()
200
+ try {
201
+ file = `${dir}/${await digest(
202
+ JSON.stringify([
203
+ VERSION,
204
+ system.version,
205
+ inputs,
206
+ roots,
207
+ opts.callbacks ?? {},
208
+ ]),
209
+ )}.json`
210
+ for (let root of roots) {
211
+ if (typeof root == 'string') {
212
+ let spec = resolve(root)
213
+ if (!local(spec) && !packaged(spec) && !immutable(spec)) {
214
+ throw new Error('mutable module')
215
+ }
216
+ starts.push(spec)
217
+ callbacks.set(spec, [])
218
+ identities.push(spec)
219
+ } else {
220
+ let [plugin, facet] = root
221
+ // Even an absent export depends on its package's export map.
222
+ let owner = resolve(plugin)
223
+ if (!local(owner) && !packaged(owner) && !immutable(owner)) {
224
+ throw new Error('mutable module')
225
+ }
226
+ packages.push(owner)
227
+ let spec: string | undefined
228
+ try {
229
+ spec = resolve(`${plugin}/${facet}`)
230
+ } catch {
231
+ /* The derivation decides whether an absent facet is allowed. */
232
+ }
233
+ if (spec && !local(spec) && !packaged(spec) && !immutable(spec)) {
234
+ throw new Error('mutable module')
235
+ }
236
+ identities.push(owner, spec ?? `absent:${plugin}/${facet}`)
237
+ if (spec) {
238
+ starts.push(spec)
239
+ let excluded = opts.callbacks?.[facet] ?? []
240
+ let known = callbacks.get(spec)
241
+ callbacks.set(
242
+ spec,
243
+ known ? known.filter((n) => excluded.includes(n)) : excluded,
244
+ )
245
+ }
246
+ }
247
+ }
248
+ } catch {
249
+ return await make()
250
+ }
251
+
252
+ let read = (path: string): string | null => {
253
+ try {
254
+ return io.readTextFileSync(path)
255
+ } catch (e) {
256
+ if (e instanceof disk.errors.NotFound) return null
257
+ throw e
258
+ }
259
+ }
260
+ // A file's size, times and inode, which every write to it moves. One written
261
+ // within the clock's last tick could be written again without moving them,
262
+ // so it has no stat to trust ('').
263
+ let stat = (path: string): string => {
264
+ try {
265
+ let { size, mtime, ctime, ino } = io.statSync(path)
266
+ let at = [mtime?.getTime(), ctime?.getTime()]
267
+ return at.some((t) => t == null || Date.now() - t < 2)
268
+ ? ''
269
+ : `${size} ${at.join(' ')} ${ino}`
270
+ } catch (e) {
271
+ if (e instanceof disk.errors.NotFound) return 'absent'
272
+ throw e
273
+ }
274
+ }
275
+ // A stable directory listing distinguishes a missing leaf from a broken
276
+ // symlink. Its stat then proves that absence without asking for the leaf.
277
+ let absent = (
278
+ files: string[],
279
+ stats: string[],
280
+ prior: Record<T>['absent'] = {},
281
+ ): Record<T>['absent'] => {
282
+ let directories = new Map<string, Set<string>>()
283
+ let proved: NonNullable<Record<T>['absent']> = { ...prior }
284
+ for (let [i, path] of files.entries()) {
285
+ if (stats[i] != 'absent') continue
286
+ let parent = path.slice(0, path.lastIndexOf('/')) || '/'
287
+ let names = directories.get(parent)
288
+ if (!names) directories.set(parent, names = new Set())
289
+ names.add(path)
290
+ }
291
+ for (let [parent, paths] of directories) {
292
+ try {
293
+ let before = stat(parent)
294
+ if (!before || before == 'absent') continue
295
+ let names = new Set(Array.from(io.readDirSync(parent), (e) => e.name))
296
+ if (before != stat(parent)) continue
297
+ for (let path of paths) {
298
+ delete proved[path]
299
+ if (!names.has(path.slice(path.lastIndexOf('/') + 1))) {
300
+ proved[path] = [parent, before]
301
+ }
302
+ }
303
+ } catch { /* An absence we cannot prove still checks the file. */ }
304
+ }
305
+ return proved
306
+ }
307
+ let sum = async (path: string, text = read(path)) =>
308
+ await digest(framed(path, text))
309
+ // Whether each file still holds what its digest says, reading only those
310
+ // whose stat is not the one it had when it was digested.
311
+ let agree = async (
312
+ files: string[],
313
+ now: string[],
314
+ was: string[],
315
+ sums: string[],
316
+ ) => {
317
+ for (let [i, path] of files.entries()) {
318
+ if (now[i] && now[i] == was[i]) continue
319
+ if (await sum(path) != sums[i]) return false
320
+ }
321
+ return true
322
+ }
323
+ let keep = (record: Record<T>) => {
324
+ let draft = `${file}.${crypto.randomUUID()}`
325
+ try {
326
+ io.mkdirSync(dir, { recursive: true, mode: 0o700 })
327
+ io.writeTextFileSync(draft, JSON.stringify(record), { mode: 0o600 })
328
+ io.renameSync(draft, file)
329
+ } catch {
330
+ /* Persistence is optional. */
331
+ } finally {
332
+ try {
333
+ io.removeSync(draft)
334
+ } catch { /* A renamed draft is already gone. */ }
335
+ }
336
+ }
337
+ // A hit says it was read, at most hourly, so a sweep leaves it alone.
338
+ let seen = () => {
339
+ try {
340
+ let at = io.statSync(file).mtime?.getTime()
341
+ if (at != null && Date.now() - at > HOUR) {
342
+ let now = new Date()
343
+ io.utimeSync(file, now, now)
344
+ }
345
+ } catch { /* An unrefreshed memo is only rebuilt sooner. */ }
346
+ }
347
+ let sweep = () => {
348
+ try {
349
+ let entries = []
350
+ for (let { name } of io.readDirSync(dir)) {
351
+ let path = `${dir}/${name}`
352
+ if (path == file) continue
353
+ try {
354
+ let at = io.statSync(path).mtime?.getTime()
355
+ if (at != null) entries.push({ name, at })
356
+ } catch { /* Another miss swept it first. */ }
357
+ }
358
+ for (let name of idle(entries, Date.now())) {
359
+ try {
360
+ io.removeSync(`${dir}/${name}`)
361
+ } catch { /* Another miss swept it first. */ }
362
+ }
363
+ } catch { /* Sweeping is optional. */ }
364
+ }
365
+ // The record a miss scans from: a source whose stat has not moved since
366
+ // keeps its digest and its dependencies there, and is not read again.
367
+ let prior = new Map<string, { stat: string; sum: string; lexed?: string[] }>()
368
+ try {
369
+ let known: Record<T> = JSON.parse(read(file) ?? 'null')
370
+ let current = known?.version == VERSION &&
371
+ JSON.stringify(known.roots) == JSON.stringify(identities) &&
372
+ Array.isArray(known.files) && Array.isArray(known.stats) &&
373
+ Array.isArray(known.sums) &&
374
+ known.stats.length == known.files.length &&
375
+ known.sums.length == known.files.length
376
+ if (current) {
377
+ for (let [i, path] of known.files.entries()) {
378
+ prior.set(path, {
379
+ stat: known.stats[i],
380
+ sum: known.sums[i],
381
+ lexed: known.lexed?.[path],
382
+ })
383
+ }
384
+ }
385
+ if (
386
+ current && 'value' in known &&
387
+ (!opts.valid || await opts.valid(known.value))
388
+ ) {
389
+ // A witness whose directory moved proves nothing, and its leaf is
390
+ // stat'd instead. A hit never lists a directory or rewrites the memo:
391
+ // an ancestor that is always moving (/tmp, a home directory) would
392
+ // cost every command a listing of it. A file inside the tree the memo
393
+ // was kept in holds what it held then, and keeps its stat unasked.
394
+ let directories = new Map<string, string>()
395
+ let fixed = tree && known.tree == tree.id ? `${tree.root}/` : undefined
396
+ let stats = known.files.map((path, i) => {
397
+ if (fixed && path.startsWith(fixed) && known.stats[i]) {
398
+ return known.stats[i]
399
+ }
400
+ let witness = known.absent?.[path]
401
+ if (witness) {
402
+ let [parent, before] = witness
403
+ let now = directories.get(parent)
404
+ if (now === undefined) directories.set(parent, now = stat(parent))
405
+ if (now && now == before) return 'absent'
406
+ }
407
+ return stat(path)
408
+ })
409
+ if (stats.every((s, i) => s && s == known.stats[i])) {
410
+ // Proved in a tree it was not kept in, it is kept under this one,
411
+ // once, so the next hit here asks nothing inside it.
412
+ if (tree && known.tree != tree.id) keep({ ...known, tree: tree.id })
413
+ else seen()
414
+ return known.value
415
+ }
416
+ // A stat moved without saying whether its contents did (a checkout, a
417
+ // touch): contents that still agree keep the memo, under the new stats.
418
+ if (await agree(known.files, stats, known.stats, known.sums)) {
419
+ keep({
420
+ ...known,
421
+ stats,
422
+ absent: absent(known.files, stats, known.absent),
423
+ tree: tree?.id,
424
+ })
425
+ return known.value
426
+ }
427
+ }
428
+ } catch (error) {
429
+ if (error instanceof disk.errors.PermissionDenied) return await make()
430
+ // A damaged memo is rebuilt.
431
+ }
432
+
433
+ // If a miss cannot be kept, source scanning buys nothing. Check the write
434
+ // boundary before loading the parser or walking the dependency graph.
435
+ let probe = `${file}.${crypto.randomUUID()}`
436
+ let writable = false
437
+ try {
438
+ io.mkdirSync(dir, { recursive: true, mode: 0o700 })
439
+ io.writeTextFileSync(probe, '', { mode: 0o600, createNew: true })
440
+ writable = true
441
+ } catch {
442
+ /* Derivation needs no writable cache. */
443
+ } finally {
444
+ try {
445
+ io.removeSync(probe)
446
+ } catch { /* An unsuccessful write may have created nothing. */ }
447
+ }
448
+ if (!writable) return await make()
449
+
450
+ let sources = new Map<string, string | null>()
451
+ let stats = new Map<string, string>()
452
+ let sums = new Map<string, string>()
453
+ let lexed = new Map<string, string[]>()
454
+ type Imports = { [key: string]: string }
455
+ type Manifest = {
456
+ imports?: Imports
457
+ scopes?: { [scope: string]: Imports }
458
+ base: URL
459
+ }
460
+ let locks = new Map<string, { [specifier: string]: string }>()
461
+ let scanned = new Set<string>()
462
+ // Its stat before its contents: a write after the read moves the stat kept.
463
+ // A file the stat found absent is absent, and is not asked again. One whose
464
+ // stat is the prior record's keeps that record's digest and dependencies,
465
+ // and is read only where its contents are asked for.
466
+ let note = (path: string) => {
467
+ if (!stats.has(path)) {
468
+ let at = stat(path)
469
+ stats.set(path, at)
470
+ let was = prior.get(path)
471
+ if (at && at == was?.stat) {
472
+ sums.set(path, was.sum)
473
+ if (was.lexed) lexed.set(path, was.lexed)
474
+ }
475
+ if (at == 'absent') sources.set(path, null)
476
+ }
477
+ }
478
+ let watch = (path: string): string | null => {
479
+ note(path)
480
+ if (!sources.has(path)) sources.set(path, read(path))
481
+ return sources.get(path)!
482
+ }
483
+ // A configuration file, with the lock and import map it names watched too.
484
+ // A JSONC form this JSON reader cannot prove derives normally.
485
+ let manifest = (text: string, base: URL): Manifest => {
486
+ let doc = JSON.parse(text)
487
+ if (doc.lock !== false) {
488
+ let lock = new URL(
489
+ typeof doc.lock == 'string' ? doc.lock : doc.lock?.path ?? 'deno.lock',
490
+ base,
491
+ )
492
+ let path = pathOf(lock.href)
493
+ if (!locks.has(path)) {
494
+ let text = watch(path)
495
+ if (text !== null) locks.set(path, JSON.parse(text).specifiers ?? {})
496
+ }
497
+ }
498
+ if (!doc.importMap) return { ...doc, base }
499
+ let map = new URL(doc.importMap, base)
500
+ let held = watch(pathOf(map.href))
501
+ if (held === null) throw new Error('absent import map')
502
+ return { ...JSON.parse(held), base: map }
503
+ }
504
+ // The configurations over a directory, nearest first. Each directory's
505
+ // files are watched once, however many modules a walk finds in it.
506
+ let over = new Map<string, Manifest[]>()
507
+ let governing = (dir: URL): Manifest[] => {
508
+ let known = over.get(dir.href)
509
+ if (known) return known
510
+ let here = pathOf(dir.href)
511
+ let found = FILES.flatMap((name) => {
512
+ let text = watch(here + name)
513
+ return text === null ? [] : [manifest(text, new URL(name, dir))]
514
+ })
515
+ let up = new URL('../', dir)
516
+ let chain = up.href == dir.href ? found : [...found, ...governing(up)]
517
+ over.set(dir.href, chain)
518
+ return chain
519
+ }
520
+ let ancestry = (specifier: string): Manifest[] =>
521
+ local(specifier) ? governing(new URL('.', specifier)) : []
522
+ let relative = (specifier: string, from: string): string => {
523
+ let address = (name: string, base: URL | string): string =>
524
+ /^(?:\.?\.?\/|[a-z][\w+.-]*:)/i.test(name)
525
+ ? new URL(name, base).href
526
+ : name
527
+ let asked = address(specifier, from)
528
+ for (let doc of ancestry(from)) {
529
+ let scopes = Object.keys(doc.scopes ?? {}).filter((s) =>
530
+ from.startsWith(new URL(s, doc.base).href)
531
+ ).sort((a, b) =>
532
+ new URL(b, doc.base).href.length - new URL(a, doc.base).href.length
533
+ )
534
+ for (
535
+ let map of [...scopes.map((s) => doc.scopes![s]), doc.imports ?? {}]
536
+ ) {
537
+ let key = Object.keys(map).filter((k) =>
538
+ address(k, doc.base) == asked ||
539
+ k.endsWith('/') && asked.startsWith(address(k, doc.base)) ||
540
+ packaged(map[k]) && asked.startsWith(`${k}/`)
541
+ ).sort((a, b) =>
542
+ address(b, doc.base).length - address(a, doc.base).length
543
+ )[0]
544
+ if (!key) {
545
+ continue
546
+ }
547
+ let mapped = map[key] + asked.slice(address(key, doc.base).length)
548
+ return packaged(mapped) || immutable(mapped)
549
+ ? mapped
550
+ : mapped.startsWith('.') || mapped.startsWith('/')
551
+ ? new URL(mapped, doc.base).href
552
+ : resolve(mapped)
553
+ }
554
+ }
555
+ return packaged(asked) || immutable(asked)
556
+ ? asked
557
+ : asked == specifier
558
+ ? resolve(specifier)
559
+ : asked
560
+ }
561
+ let visit = async (specifier: string): Promise<void> => {
562
+ if (scanned.has(specifier)) return
563
+ scanned.add(specifier)
564
+ if (!local(specifier)) {
565
+ if (
566
+ !immutable(specifier) &&
567
+ ![...locks.values()].some((lock) =>
568
+ /^\d+\.\d+\.\d+(?:[-+][\w.-]+)?(?:_[^\s]+)?$/.test(
569
+ lock[packageKey(specifier)] ?? '',
570
+ )
571
+ )
572
+ ) throw new Error('mutable module')
573
+ return
574
+ }
575
+ ancestry(specifier)
576
+ let path = pathOf(specifier)
577
+ note(path)
578
+ if (stats.get(path) == 'absent' || !/\.[cm]?[jt]sx?$/.test(specifier)) {
579
+ return
580
+ }
581
+ let imports = opts.imports ??
582
+ ((source: string, name?: string) =>
583
+ importsOf(source, name, callbacks.get(specifier)))
584
+ let dependencies = lexed.get(path)
585
+ if (!dependencies) {
586
+ lexed.set(path, dependencies = await imports(watch(path)!, specifier))
587
+ }
588
+ for (let dependency of dependencies) {
589
+ await visit(relative(dependency, specifier))
590
+ }
591
+ }
592
+ let proved = false
593
+ try {
594
+ packages.forEach(ancestry)
595
+ starts.filter(local).forEach(ancestry)
596
+ for (let source of starts) await visit(source)
597
+ // Sources all immutable leave no file to watch: their identities, which
598
+ // carry their versions, are the whole proof.
599
+ proved = true
600
+ } catch { /* A source we cannot prove is derived normally. */ }
601
+ let digested = false
602
+ try {
603
+ for (let path of stats.keys()) {
604
+ if (!sums.has(path)) sums.set(path, await sum(path, watch(path)))
605
+ }
606
+ digested = proved
607
+ } catch { /* A failed digest still leaves ordinary derivation usable. */ }
608
+
609
+ // Derivation errors always reach the caller, regardless of cache failures.
610
+ let value = await make()
611
+ if (digested) {
612
+ try {
613
+ // A source changed while derivation ran: the next call must derive too.
614
+ let files = [...stats.keys()]
615
+ let was = files.map((path) => stats.get(path)!)
616
+ let digests = files.map((path) => sums.get(path)!)
617
+ if (await agree(files, files.map(stat), was, digests)) {
618
+ keep({
619
+ version: VERSION,
620
+ roots: identities,
621
+ files,
622
+ stats: was,
623
+ absent: absent(files, was),
624
+ sums: digests,
625
+ lexed: Object.fromEntries(lexed),
626
+ tree: tree?.id,
627
+ value,
628
+ })
629
+ sweep()
630
+ }
631
+ } catch { /* Persistence is optional. */ }
632
+ }
633
+ return value
634
+ }
package/mod.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The `yak` command line, as a library.
3
+ *
4
+ * The command itself is the other export — `./yak`, which `./install` puts on
5
+ * PATH — and this module is what it is assembled from, for anybody building
6
+ * the same thing: the tools of the graph a config file names, or the ones an
7
+ * MCP server lists, read at run time, every tool a subcommand, and the command
8
+ * line parsed through each tool's own input schema.
9
+ *
10
+ * ```ts ignore
11
+ * import { argsFor, doorUrl, rpc } from '@yaks/cli'
12
+ *
13
+ * let ask = rpc({ url: doorUrl('yaks.app'), token: '…' })
14
+ * let { tools } = await ask('tools/list') as { tools: [] }
15
+ * ```
16
+ *
17
+ * A program with subcommands of its own passes them in and runs the same
18
+ * program: `exit(await main(args, commands))`, with `args` and `exit` from
19
+ * `@yaks/process/system` and `main` from
20
+ * `@yaks/cli/main`.
21
+ *
22
+ * A program that is not `yak` at all calls `cli(commands, opts)` — its
23
+ * subcommands, and the name it goes by. One whose commands run tools on a
24
+ * graph it opened itself draws each answer the way `yak` does: `registry` of
25
+ * the plugins' views, and `show`.
26
+ *
27
+ * @module
28
+ */ export { appGrammar, argsFor, inflate, saidIn, Usage, valueOf } from "./args.js";
29
+ export { bundlesIn, CHUNK, chunks } from "./apply.js";
30
+ export { registry } from "./answer.js";
31
+ export { show } from "./tty.js";
32
+ export { complete } from "./complete.js";
33
+ export { doorUrl, initialize, PROTOCOL, Refused, rpc, Unauthorized } from "./rpc.js";
34
+ export { rosterAfter, saidBy, STALE, versionIn } from "./roster.js";
35
+ export { lineOf, safe, sketch, toolHelp, toolLines, wrap } from "./show.js";
36
+ export { cached, configDir, forget, remember, stateDir, tokenFor } from "./store.js";
37
+ export { commandOf, titleOf, typeOf } from "./tool.js";
38
+ export { aimed, cli, commandFor, globals, helpTool, unique, usage } from "./run.js";
39
+ export { configPath, read } from "./config.js";
40
+ export { runtimeSource } from "./runtime.js";
41
+ export { fileVault, vaultOf } from "./vault.js";
42
+ export { listed, printed, rosterOf } from "./platform.js";
43
+ export { appStray, appTools, toolCall } from "./commands.js";
44
+ export { readJson } from "./remote.js";
45
+ export { accountHost, closeAccounts, personal, personalPath } from "./accounts.js";
46
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GAED,SACE,UAAU,EACV,OAAO,EAEP,OAAO,EAGP,MAAM,EACN,KAAK,EACL,OAAO,oBACS;AAClB,SAAS,SAAS,EAAE,KAAK,EAAE,MAAM,qBAAoB;AACrD,SAAS,QAAQ,sBAA8C;AAC/D,SAAS,IAAI,mBAAkB;AAC/B,SAAS,QAAQ,wBAAoC;AACrD,SAEE,OAAO,EACP,UAAU,EACV,QAAQ,EACR,OAAO,EAEP,GAAG,EACH,YAAY,mBACG;AACjB,SAAsB,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,sBAAqB;AAChF,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,oBAAmB;AAC3E,SACE,MAAM,EACN,SAAS,EACT,MAAM,EACN,QAAQ,EAER,QAAQ,EACR,QAAQ,qBACS;AACnB,SACE,SAAS,EAIT,OAAO,EACP,MAAM,oBACU;AAClB,SACE,KAAK,EACL,GAAG,EAEH,UAAU,EAEV,OAAO,EACP,QAAQ,EAER,MAAM,EACN,KAAK,mBACU;AACjB,SAAsB,UAAU,EAAE,IAAI,sBAAqB;AAC3D,SAAS,aAAa,uBAAsB;AAC5C,SAAS,SAAS,EAAE,OAAO,qBAAoB;AAC/C,SAAS,MAAM,EAAE,OAAO,EAAE,QAAQ,wBAAuB;AACzD,SAAS,QAAQ,EAAE,QAAQ,EAAE,QAAQ,wBAAuB;AAC5D,SAAS,QAAQ,sBAAqB;AAEtC,SACE,WAAW,EAEX,aAAa,EACb,QAAQ,EACR,YAAY,wBACQ"}