@smeltjs/core 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 (199) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +55 -0
  3. package/THIRD-PARTY.md +140 -0
  4. package/dist/apply.d.ts +145 -0
  5. package/dist/apply.d.ts.map +1 -0
  6. package/dist/apply.js +244 -0
  7. package/dist/apply.js.map +1 -0
  8. package/dist/cache/prefix.d.ts +164 -0
  9. package/dist/cache/prefix.d.ts.map +1 -0
  10. package/dist/cache/prefix.js +361 -0
  11. package/dist/cache/prefix.js.map +1 -0
  12. package/dist/cli/args.d.ts +71 -0
  13. package/dist/cli/args.d.ts.map +1 -0
  14. package/dist/cli/args.js +308 -0
  15. package/dist/cli/args.js.map +1 -0
  16. package/dist/cli/bin.d.ts +3 -0
  17. package/dist/cli/bin.d.ts.map +1 -0
  18. package/dist/cli/bin.js +161 -0
  19. package/dist/cli/bin.js.map +1 -0
  20. package/dist/cli/config.d.ts +73 -0
  21. package/dist/cli/config.d.ts.map +1 -0
  22. package/dist/cli/config.js +144 -0
  23. package/dist/cli/config.js.map +1 -0
  24. package/dist/cli/init.d.ts +56 -0
  25. package/dist/cli/init.d.ts.map +1 -0
  26. package/dist/cli/init.js +449 -0
  27. package/dist/cli/init.js.map +1 -0
  28. package/dist/cli/report.d.ts +44 -0
  29. package/dist/cli/report.d.ts.map +1 -0
  30. package/dist/cli/report.js +113 -0
  31. package/dist/cli/report.js.map +1 -0
  32. package/dist/cli/resolve.d.ts +103 -0
  33. package/dist/cli/resolve.d.ts.map +1 -0
  34. package/dist/cli/resolve.js +106 -0
  35. package/dist/cli/resolve.js.map +1 -0
  36. package/dist/cli/run.d.ts +99 -0
  37. package/dist/cli/run.d.ts.map +1 -0
  38. package/dist/cli/run.js +351 -0
  39. package/dist/cli/run.js.map +1 -0
  40. package/dist/detect.d.ts +16 -0
  41. package/dist/detect.d.ts.map +1 -0
  42. package/dist/detect.js +18 -0
  43. package/dist/detect.js.map +1 -0
  44. package/dist/errors.d.ts +88 -0
  45. package/dist/errors.d.ts.map +1 -0
  46. package/dist/errors.js +107 -0
  47. package/dist/errors.js.map +1 -0
  48. package/dist/hash.d.ts +13 -0
  49. package/dist/hash.d.ts.map +1 -0
  50. package/dist/hash.js +16 -0
  51. package/dist/hash.js.map +1 -0
  52. package/dist/index.d.ts +121 -0
  53. package/dist/index.d.ts.map +1 -0
  54. package/dist/index.js +93 -0
  55. package/dist/index.js.map +1 -0
  56. package/dist/lang/bash.d.ts +3 -0
  57. package/dist/lang/bash.d.ts.map +1 -0
  58. package/dist/lang/bash.js +28 -0
  59. package/dist/lang/bash.js.map +1 -0
  60. package/dist/lang/c.d.ts +3 -0
  61. package/dist/lang/c.d.ts.map +1 -0
  62. package/dist/lang/c.js +39 -0
  63. package/dist/lang/c.js.map +1 -0
  64. package/dist/lang/c_sharp.d.ts +3 -0
  65. package/dist/lang/c_sharp.d.ts.map +1 -0
  66. package/dist/lang/c_sharp.js +37 -0
  67. package/dist/lang/c_sharp.js.map +1 -0
  68. package/dist/lang/cpp.d.ts +3 -0
  69. package/dist/lang/cpp.d.ts.map +1 -0
  70. package/dist/lang/cpp.js +46 -0
  71. package/dist/lang/cpp.js.map +1 -0
  72. package/dist/lang/go.d.ts +3 -0
  73. package/dist/lang/go.d.ts.map +1 -0
  74. package/dist/lang/go.js +31 -0
  75. package/dist/lang/go.js.map +1 -0
  76. package/dist/lang/java.d.ts +3 -0
  77. package/dist/lang/java.d.ts.map +1 -0
  78. package/dist/lang/java.js +34 -0
  79. package/dist/lang/java.js.map +1 -0
  80. package/dist/lang/javascript.d.ts +3 -0
  81. package/dist/lang/javascript.d.ts.map +1 -0
  82. package/dist/lang/javascript.js +28 -0
  83. package/dist/lang/javascript.js.map +1 -0
  84. package/dist/lang/kotlin.d.ts +3 -0
  85. package/dist/lang/kotlin.d.ts.map +1 -0
  86. package/dist/lang/kotlin.js +37 -0
  87. package/dist/lang/kotlin.js.map +1 -0
  88. package/dist/lang/php.d.ts +3 -0
  89. package/dist/lang/php.d.ts.map +1 -0
  90. package/dist/lang/php.js +37 -0
  91. package/dist/lang/php.js.map +1 -0
  92. package/dist/lang/profile.d.ts +130 -0
  93. package/dist/lang/profile.d.ts.map +1 -0
  94. package/dist/lang/profile.js +2 -0
  95. package/dist/lang/profile.js.map +1 -0
  96. package/dist/lang/python.d.ts +3 -0
  97. package/dist/lang/python.d.ts.map +1 -0
  98. package/dist/lang/python.js +33 -0
  99. package/dist/lang/python.js.map +1 -0
  100. package/dist/lang/registry.d.ts +31 -0
  101. package/dist/lang/registry.d.ts.map +1 -0
  102. package/dist/lang/registry.js +89 -0
  103. package/dist/lang/registry.js.map +1 -0
  104. package/dist/lang/ruby.d.ts +3 -0
  105. package/dist/lang/ruby.d.ts.map +1 -0
  106. package/dist/lang/ruby.js +47 -0
  107. package/dist/lang/ruby.js.map +1 -0
  108. package/dist/lang/rust.d.ts +3 -0
  109. package/dist/lang/rust.d.ts.map +1 -0
  110. package/dist/lang/rust.js +45 -0
  111. package/dist/lang/rust.js.map +1 -0
  112. package/dist/lang/swift.d.ts +3 -0
  113. package/dist/lang/swift.d.ts.map +1 -0
  114. package/dist/lang/swift.js +34 -0
  115. package/dist/lang/swift.js.map +1 -0
  116. package/dist/lang/tsx.d.ts +4 -0
  117. package/dist/lang/tsx.d.ts.map +1 -0
  118. package/dist/lang/tsx.js +11 -0
  119. package/dist/lang/tsx.js.map +1 -0
  120. package/dist/lang/typescript.d.ts +18 -0
  121. package/dist/lang/typescript.d.ts.map +1 -0
  122. package/dist/lang/typescript.js +61 -0
  123. package/dist/lang/typescript.js.map +1 -0
  124. package/dist/net/policy.d.ts +49 -0
  125. package/dist/net/policy.d.ts.map +1 -0
  126. package/dist/net/policy.js +120 -0
  127. package/dist/net/policy.js.map +1 -0
  128. package/dist/plan/grammar.d.ts +38 -0
  129. package/dist/plan/grammar.d.ts.map +1 -0
  130. package/dist/plan/grammar.js +85 -0
  131. package/dist/plan/grammar.js.map +1 -0
  132. package/dist/plan/lexical.d.ts +51 -0
  133. package/dist/plan/lexical.d.ts.map +1 -0
  134. package/dist/plan/lexical.js +167 -0
  135. package/dist/plan/lexical.js.map +1 -0
  136. package/dist/plan/planners.d.ts +35 -0
  137. package/dist/plan/planners.d.ts.map +1 -0
  138. package/dist/plan/planners.js +26 -0
  139. package/dist/plan/planners.js.map +1 -0
  140. package/dist/plan/structural.d.ts +68 -0
  141. package/dist/plan/structural.d.ts.map +1 -0
  142. package/dist/plan/structural.js +458 -0
  143. package/dist/plan/structural.js.map +1 -0
  144. package/dist/repomap/cache.d.ts +53 -0
  145. package/dist/repomap/cache.d.ts.map +1 -0
  146. package/dist/repomap/cache.js +139 -0
  147. package/dist/repomap/cache.js.map +1 -0
  148. package/dist/repomap/map.d.ts +161 -0
  149. package/dist/repomap/map.d.ts.map +1 -0
  150. package/dist/repomap/map.js +302 -0
  151. package/dist/repomap/map.js.map +1 -0
  152. package/dist/repomap/rank.d.ts +52 -0
  153. package/dist/repomap/rank.d.ts.map +1 -0
  154. package/dist/repomap/rank.js +155 -0
  155. package/dist/repomap/rank.js.map +1 -0
  156. package/dist/repomap/tags.d.ts +47 -0
  157. package/dist/repomap/tags.d.ts.map +1 -0
  158. package/dist/repomap/tags.js +101 -0
  159. package/dist/repomap/tags.js.map +1 -0
  160. package/dist/retrieve.d.ts +14 -0
  161. package/dist/retrieve.d.ts.map +1 -0
  162. package/dist/retrieve.js +44 -0
  163. package/dist/retrieve.js.map +1 -0
  164. package/dist/stages.d.ts +22 -0
  165. package/dist/stages.d.ts.map +1 -0
  166. package/dist/stages.js +33 -0
  167. package/dist/stages.js.map +1 -0
  168. package/dist/stats.d.ts +40 -0
  169. package/dist/stats.d.ts.map +1 -0
  170. package/dist/stats.js +37 -0
  171. package/dist/stats.js.map +1 -0
  172. package/dist/store-dir.d.ts +98 -0
  173. package/dist/store-dir.d.ts.map +1 -0
  174. package/dist/store-dir.js +379 -0
  175. package/dist/store-dir.js.map +1 -0
  176. package/dist/store.d.ts +36 -0
  177. package/dist/store.d.ts.map +1 -0
  178. package/dist/store.js +56 -0
  179. package/dist/store.js.map +1 -0
  180. package/dist/types.d.ts +298 -0
  181. package/dist/types.d.ts.map +1 -0
  182. package/dist/types.js +2 -0
  183. package/dist/types.js.map +1 -0
  184. package/grammars/tree-sitter-bash.wasm +0 -0
  185. package/grammars/tree-sitter-c.wasm +0 -0
  186. package/grammars/tree-sitter-c_sharp.wasm +0 -0
  187. package/grammars/tree-sitter-cpp.wasm +0 -0
  188. package/grammars/tree-sitter-go.wasm +0 -0
  189. package/grammars/tree-sitter-java.wasm +0 -0
  190. package/grammars/tree-sitter-javascript.wasm +0 -0
  191. package/grammars/tree-sitter-kotlin.wasm +0 -0
  192. package/grammars/tree-sitter-php.wasm +0 -0
  193. package/grammars/tree-sitter-python.wasm +0 -0
  194. package/grammars/tree-sitter-ruby.wasm +0 -0
  195. package/grammars/tree-sitter-rust.wasm +0 -0
  196. package/grammars/tree-sitter-swift.wasm +0 -0
  197. package/grammars/tree-sitter-tsx.wasm +0 -0
  198. package/grammars/tree-sitter-typescript.wasm +0 -0
  199. package/package.json +68 -0
@@ -0,0 +1,308 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { SUPPORTED_LANGUAGES } from '../detect.js';
3
+ import { CliUsageError } from '../errors.js';
4
+ import { isStrategy, STRATEGIES } from '../plan/planners.js';
5
+ import { STRUCTURAL_LANGUAGES } from '../plan/structural.js';
6
+ /** The command people type. Independent of the package name. */
7
+ export const CLI_NAME = 'smelt';
8
+ /**
9
+ * Argument parsing on `node:util.parseArgs` — stable since Node 20, which `engines`
10
+ * already requires.
11
+ *
12
+ * The CLI ships as a `bin` on the library rather than as a second package, and this
13
+ * import is the reason that is free: it adds no dependency, so the argument the second
14
+ * package existed to win — keeping the library's dependency tree small — is already won.
15
+ *
16
+ * @throws {CliUsageError} on anything the user got wrong. Never guesses.
17
+ */
18
+ export function parseSmeltArgs(argv) {
19
+ let parsed;
20
+ try {
21
+ parsed = parseArgs({
22
+ args: [...argv],
23
+ allowPositionals: true,
24
+ strict: true,
25
+ options: {
26
+ budget: { type: 'string' },
27
+ focus: { type: 'string', multiple: true },
28
+ language: { type: 'string' },
29
+ strategy: { type: 'string' },
30
+ ignore: { type: 'string', multiple: true },
31
+ cache: { type: 'string' },
32
+ json: { type: 'boolean' },
33
+ reconstruct: { type: 'boolean' },
34
+ help: { type: 'boolean', short: 'h' },
35
+ version: { type: 'boolean' },
36
+ },
37
+ });
38
+ }
39
+ catch (cause) {
40
+ throw new CliUsageError(`${CLI_NAME}: ${cause instanceof Error ? cause.message : String(cause)}\n` +
41
+ `Run \`${CLI_NAME} --help\`.`);
42
+ }
43
+ const { values, positionals } = parsed;
44
+ if (values.help === true)
45
+ return { mode: 'help', focus: [], json: false };
46
+ if (values.version === true) {
47
+ return { mode: 'version', focus: [], json: false };
48
+ }
49
+ if (positionals[0] === 'init') {
50
+ // `smelt init` is a subcommand, so a file literally named `init` needs `./init`.
51
+ if (positionals.length > 1) {
52
+ throw new CliUsageError(`${CLI_NAME}: init takes no further arguments.`);
53
+ }
54
+ const flags = Object.entries(values).filter(([, value]) => value !== undefined);
55
+ if (flags.length > 0) {
56
+ throw new CliUsageError(`${CLI_NAME}: init is interactive and takes no flags ` +
57
+ `(got --${flags.map(([name]) => name).join(', --')}). It asks instead.`);
58
+ }
59
+ return { mode: 'init', focus: [], json: false };
60
+ }
61
+ if (positionals[0] === 'map') {
62
+ // `smelt map` is a subcommand, so a file literally named `map` needs `./map`.
63
+ return parseMapArgs(values, positionals);
64
+ }
65
+ if (positionals[0] === 'retrieve') {
66
+ // A subcommand, like map and init — a file literally named `retrieve` needs `./retrieve`.
67
+ return parseRetrieveArgs(values, positionals);
68
+ }
69
+ if (positionals[0] === 'stats') {
70
+ return parseStatsArgs(values, positionals);
71
+ }
72
+ // These two belong to `smelt map` alone; silently ignoring a flag the user typed
73
+ // would be a setting they believed was in force.
74
+ if (values.ignore !== undefined || values.cache !== undefined) {
75
+ throw new CliUsageError(`${CLI_NAME}: --ignore and --cache belong to \`${CLI_NAME} map\`. A single-blob ` +
76
+ `run reads one file or stdin; there is no tree to walk and nothing to cache.`);
77
+ }
78
+ if (positionals.length > 1) {
79
+ throw new CliUsageError(`${CLI_NAME}: expected at most one file, got ${String(positionals.length)} ` +
80
+ `(${positionals.join(', ')}). smelt reads one blob at a time.`);
81
+ }
82
+ const file = positionals[0];
83
+ if (values.reconstruct === true) {
84
+ if (values.budget !== undefined) {
85
+ throw new CliUsageError(`${CLI_NAME}: --budget makes no sense with --reconstruct. Reconstruction puts ` +
86
+ `every byte back; there is nothing to fit.`);
87
+ }
88
+ return {
89
+ mode: 'reconstruct',
90
+ ...(file === undefined ? {} : { file }),
91
+ focus: [],
92
+ json: false,
93
+ };
94
+ }
95
+ const budgetBytes = parseBudget(values.budget);
96
+ const chosenStrategy = strategy(values.strategy);
97
+ return {
98
+ mode: 'smelt',
99
+ ...(file === undefined ? {} : { file }),
100
+ ...(budgetBytes === undefined ? {} : { budgetBytes }),
101
+ focus: values.focus ?? [],
102
+ ...(values.language === undefined ? {} : { language: language(values.language) }),
103
+ ...(chosenStrategy === undefined ? {} : { strategy: chosenStrategy }),
104
+ json: values.json === true,
105
+ };
106
+ }
107
+ /**
108
+ * The `map` subcommand's own validation: exactly one directory, the map-only flags,
109
+ * and the same budget rules as everything else — a missing `--budget` is not an
110
+ * error *here* (the config may carry `defaultBudgetBytes`), a malformed one always is.
111
+ */
112
+ function parseMapArgs(values, positionals) {
113
+ if (positionals.length < 2) {
114
+ throw new CliUsageError(`${CLI_NAME}: map needs the directory to read.\n` +
115
+ ` ${CLI_NAME} map <dir> --budget <bytes> [--focus <term>]...`);
116
+ }
117
+ if (positionals.length > 2) {
118
+ throw new CliUsageError(`${CLI_NAME}: map takes exactly one directory, got ` +
119
+ `${String(positionals.length - 1)} (${positionals.slice(1).join(', ')}).`);
120
+ }
121
+ if (values.reconstruct === true) {
122
+ throw new CliUsageError(`${CLI_NAME}: --reconstruct makes no sense with map. A map elides nothing, so ` +
123
+ `there is nothing to put back.`);
124
+ }
125
+ if (values.language !== undefined || values.strategy !== undefined) {
126
+ throw new CliUsageError(`${CLI_NAME}: --language and --strategy apply to single-blob runs. map reads a ` +
127
+ `whole tree, detects each file's language itself, and is not a planner ` +
128
+ `strategy — it returns a map, not an elision plan.`);
129
+ }
130
+ const budgetBytes = parseBudget(values.budget);
131
+ return {
132
+ mode: 'map',
133
+ dir: positionals[1],
134
+ ...(budgetBytes === undefined ? {} : { budgetBytes }),
135
+ focus: values.focus ?? [],
136
+ ignore: values.ignore ?? [],
137
+ ...(values.cache === undefined ? {} : { cacheDir: values.cache }),
138
+ json: values.json === true,
139
+ };
140
+ }
141
+ /**
142
+ * `retrieve` takes the hash and nothing else. Every flag is refused rather than
143
+ * ignored — the command prints the exact original bytes on stdout and nothing more,
144
+ * so a flag that changed the output would break the one contract it has, and a flag
145
+ * silently dropped would be a setting the user believed was in force. In particular
146
+ * there is no `--json`: the bytes ARE the output, and wrapping them would re-encode
147
+ * what the command exists to hand back verbatim.
148
+ */
149
+ function parseRetrieveArgs(values, positionals) {
150
+ const flags = Object.entries(values).filter(([, value]) => value !== undefined);
151
+ if (flags.length > 0) {
152
+ throw new CliUsageError(`${CLI_NAME}: retrieve takes no flags (got --${flags.map(([name]) => name).join(', --')}). ` +
153
+ `It prints the exact original bytes for one hash, nothing else — even --json ` +
154
+ `would wrap what must come back verbatim.`);
155
+ }
156
+ if (positionals.length !== 2) {
157
+ throw new CliUsageError(`${CLI_NAME}: retrieve needs exactly one hash — the one a marker printed.\n` +
158
+ ` ${CLI_NAME} retrieve 84998967370f38bc`);
159
+ }
160
+ return { mode: 'retrieve', hash: positionals[1] };
161
+ }
162
+ /** `stats` reads counters; `--json` is its only flag, everything else is refused. */
163
+ function parseStatsArgs(values, positionals) {
164
+ if (positionals.length > 1) {
165
+ throw new CliUsageError(`${CLI_NAME}: stats takes no further arguments, got ` +
166
+ `${positionals.slice(1).join(', ')}. It reports on the one configured store.`);
167
+ }
168
+ const flags = Object.entries(values).filter(([name, value]) => value !== undefined && name !== 'json');
169
+ if (flags.length > 0) {
170
+ throw new CliUsageError(`${CLI_NAME}: stats takes only --json ` +
171
+ `(got --${flags.map(([name]) => name).join(', --')}). It reads counters; there ` +
172
+ `is nothing to budget, focus or plan.`);
173
+ }
174
+ return { mode: 'stats', json: values['json'] === true };
175
+ }
176
+ /**
177
+ * `--budget` has no built-in default, for the same reason `smelt()` has none: a budget
178
+ * smelt invented would be smelt deciding how much of the caller's context to throw
179
+ * away, silently, at a number nobody chose. A *missing* flag is not an error here,
180
+ * though — `smelt.config.json` may carry a `defaultBudgetBytes` the user chose
181
+ * explicitly, and the runner errors only when neither exists. A malformed value is
182
+ * always an error.
183
+ */
184
+ function parseBudget(raw) {
185
+ if (raw === undefined)
186
+ return undefined;
187
+ if (!/^\d+$/.test(raw)) {
188
+ throw new CliUsageError(`${CLI_NAME}: --budget must be a whole number of bytes, got "${raw}".`);
189
+ }
190
+ const value = Number(raw);
191
+ if (value <= 0) {
192
+ throw new CliUsageError(`${CLI_NAME}: --budget must be greater than zero, got "${raw}".`);
193
+ }
194
+ return value;
195
+ }
196
+ function language(raw) {
197
+ const known = [...SUPPORTED_LANGUAGES, 'unknown'];
198
+ if (!known.includes(raw)) {
199
+ throw new CliUsageError(`${CLI_NAME}: unknown --language "${raw}". Known: ${known.join(', ')}.`);
200
+ }
201
+ return raw;
202
+ }
203
+ /** Membership in the {@link PLANNERS} registry is the whole validation. */
204
+ function strategy(raw) {
205
+ if (raw === undefined)
206
+ return undefined;
207
+ if (!isStrategy(raw)) {
208
+ throw new CliUsageError(`${CLI_NAME}: unknown --strategy "${raw}". Known: ${STRATEGIES.join(', ')}.`);
209
+ }
210
+ return raw;
211
+ }
212
+ /** The help text. Also the closest thing the CLI has to documentation. */
213
+ export function cliUsage() {
214
+ return `${CLI_NAME} — shrink text for a model, without lying about what was removed.
215
+
216
+ USAGE
217
+ ${CLI_NAME} <file> --budget <bytes> [--focus <term>]...
218
+ ${CLI_NAME} --budget <bytes> [--focus <term>]... < input
219
+ ${CLI_NAME} map <dir> --budget <bytes> [--focus <term>]... [--ignore <entry>]... [--cache <dir>]
220
+ ${CLI_NAME} retrieve <hash>
221
+ ${CLI_NAME} stats [--json]
222
+ ${CLI_NAME} --reconstruct <result.json>
223
+ ${CLI_NAME} --reconstruct < result.json
224
+ ${CLI_NAME} init
225
+
226
+ Smelted text goes to stdout and the report goes to stderr, so the two can be piped
227
+ apart: ${CLI_NAME} big.log --budget 4000 > small.log
228
+
229
+ CONFIG
230
+ ${CLI_NAME} init walks you through writing a smelt.config.json (and optional typed
231
+ stubs), one question at a time; nothing is written until a final confirm. Runs read
232
+ the nearest smelt.config.json, walking up from the working directory, for DEFAULTS
233
+ only — budget, strategy, store. An explicit flag always wins, and a malformed config
234
+ is a usage error, never silently ignored.
235
+
236
+ MAP
237
+ ${CLI_NAME} map <dir> renders a ranked symbol map of a whole repository — modelled
238
+ on Aider's repo-map (aider.chat/docs/repomap.html, design by Paul Gauthier) — to
239
+ stdout, with a short report on stderr. Local files only: symlinks are never
240
+ followed, binary files are skipped, and the map writes nothing to disk unless
241
+ --cache names a directory. Every included symbol carries a receipt: its
242
+ definition site and the measured reference counts that ranked it. Unlike a
243
+ smelt run, map never exits
244
+ 1: a plan can come back over budget because ${CLI_NAME} refuses to cut regions you
245
+ asked to keep, but the map fits itself to the budget by construction — symbols
246
+ are appended in rank order until the next line would not fit.
247
+
248
+ RETRIEVE & STATS
249
+ Every marker carries the hash of the bytes it replaced — <<smelt/v1: … —
250
+ retrieve("hash")>> — and the marker's retrieve("hash") is this command:
251
+ ${CLI_NAME} retrieve <hash> prints the exact original bytes on stdout, byte for
252
+ byte, nothing else. That closes the loop from pure shell: an agent that got a
253
+ marker asks for the bytes back with a command instead of a tool call, and the
254
+ retrieval is counted — asking for material back is exactly what the expansion
255
+ rate measures. An unknown hash and damaged bytes are distinct refusals (exit 3):
256
+ "never elided" and "the store was corrupted" call for different responses.
257
+
258
+ ${CLI_NAME} stats prints the same store's counters, one \`name value\` per line —
259
+ elisionsStored, bytesStored, retrieveCalls, uniqueRetrieved, expansionRate,
260
+ allElisionsRetrieved — and reading them is NOT counted as a retrieval. --json
261
+ emits the RetrieveStats verbatim in its own versioned envelope.
262
+
263
+ Both need somewhere for elisions to outlive the run that made them: a
264
+ smelt.config.json with a directory store (\`${CLI_NAME} init\` writes one). With a
265
+ memory store — or no config — every run's store dies with its process, so there
266
+ is nothing to retrieve across runs, and that is a usage error rather than a
267
+ quiet empty answer.
268
+
269
+ OPTIONS
270
+ --budget <bytes> Required, unless smelt.config.json sets defaultBudgetBytes.
271
+ Soft ceiling for the output, in UTF-8 bytes (for map: a hard
272
+ ceiling, met by construction). No built-in default: a budget
273
+ ${CLI_NAME} invented would decide for you.
274
+ --focus <term> What you were looking for. Repeatable. Matching regions and
275
+ their context survive; the runs between them collapse. For
276
+ map: symbols matching a term (by name or path) are promoted
277
+ to the front of the fill order, ranks unchanged.
278
+ --language <id> Override detection. One of: ${[...SUPPORTED_LANGUAGES, 'unknown'].join(', ')}.
279
+ --strategy <id> ${STRATEGIES.join(' or ')}. Defaults to lexical, unless
280
+ smelt.config.json says otherwise. structural parses
281
+ ${STRUCTURAL_LANGUAGES.join(', ')};
282
+ any other language is refused, never approximated.
283
+ --ignore <entry> map only. Repeatable. Replaces the default ignore list
284
+ (.git, node_modules): a bare name matches any path segment,
285
+ an entry containing / is a root-relative prefix.
286
+ --cache <dir> map only. Directory for the tags cache, keyed by content
287
+ hash. Only when given does the map write to disk at all.
288
+ --json Print a JSON envelope on stdout instead of the text:
289
+ { format, result, elided } for a smelt run — \`result\` is
290
+ the SmeltResult verbatim, \`elided\` carries the bytes, so
291
+ the envelope can be reconstructed; feed it back with
292
+ --reconstruct. For map: { format, map }, the RepoMap
293
+ structure verbatim.
294
+ --reconstruct Read a --json envelope and print the original text, byte for
295
+ byte. This is Law 3 you can run from a shell.
296
+ -h, --help This text.
297
+ --version The package version.
298
+
299
+ EXIT CODES
300
+ 0 under budget (map is always under budget by construction)
301
+ 1 over budget — the plan did not fit, and the report says so. Never silent.
302
+ map never exits 1; see MAP above.
303
+ 2 usage error
304
+ 3 smelt refused (a SmeltError: an unbuilt planner, an unknown hash, a corrupt store)
305
+ 4 unexpected internal error
306
+ `;
307
+ }
308
+ //# sourceMappingURL=args.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"args.js","sourceRoot":"","sources":["../../src/cli/args.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAE7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAG7D,gEAAgE;AAChE,MAAM,CAAC,MAAM,QAAQ,GAAG,OAAO,CAAC;AA4DhC;;;;;;;;;GASG;AACH,MAAM,UAAU,cAAc,CAAC,IAAuB;IACpD,IAAI,MAAM,CAAC;IACX,IAAI,CAAC;QACH,MAAM,GAAG,SAAS,CAAC;YACjB,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC;YACf,gBAAgB,EAAE,IAAI;YACtB,MAAM,EAAE,IAAI;YACZ,OAAO,EAAE;gBACP,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBAC1B,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE;gBACzC,QAAQ,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBAC5B,QAAQ,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;gBAC5B,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,I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+ #!/usr/bin/env node
2
+ import { readFileSync, readSync } from 'node:fs';
3
+ import { isatty } from 'node:tty';
4
+ import process from 'node:process';
5
+ import { EXIT, runCli } from './run.js';
6
+ /**
7
+ * The `smelt` binary: the thinnest possible shell around {@link runCli}.
8
+ *
9
+ * Everything decidable lives in `run.ts`, which returns an exit code instead of
10
+ * calling `exit`, so the whole CLI is testable in-process. This file owns only the
11
+ * things that cannot be tested without a real process: the shebang, stdin on fd 0, and
12
+ * the exit code itself. `test/cli-bin.test.ts` spawns the *built* binary for exactly
13
+ * those things — an in-process suite cannot see them.
14
+ *
15
+ * Two deliberate subtleties around fd 0:
16
+ *
17
+ * - **fd 0 may be non-blocking, and must still be read to EOF.** Two separate ways
18
+ * that happens in the wild: merely accessing `process.stdin` (even `.isTTY`) makes
19
+ * Node flip fd 0 into non-blocking mode, and a parent that spawned this process
20
+ * with piped stdio may hand over a socketpair that was *born* non-blocking. Either
21
+ * way a one-shot `readFileSync(0)` throws `EAGAIN` whenever the producer is slower
22
+ * than Node's startup — `(sleep 1; echo hi) | smelt --budget 100` used to die with
23
+ * an internal error. So: the TTY check is `tty.isatty(0)` (a plain syscall, no
24
+ * stream initialization), `process.stdin` is only handed over lazily to the one
25
+ * mode that needs a stream (`init`), and the read itself retries `EAGAIN` with a
26
+ * synchronous back-off until EOF.
27
+ * - **Bytes that are not UTF-8 are refused, never mangled.** Decoding invalid bytes
28
+ * would silently replace them with U+FFFD, and the result would still smelt,
29
+ * round-trip, and verify — of the wrong bytes. That violates the reversibility
30
+ * story at its root, so the binary refuses (exit code {@link EXIT.refused}) and
31
+ * names the first offending byte offset instead.
32
+ */
33
+ /** Reading fd 0 synchronously is the whole of "works in a pipe", with no stream plumbing. */
34
+ function readStdin() {
35
+ if (isatty(0)) {
36
+ process.stderr.write('smelt: no input. Pass a file, or pipe text in:\n' +
37
+ ' smelt src/server.ts --budget 4000\n' +
38
+ ' smelt --budget 4000 --focus TypeError < build.log\n');
39
+ process.exit(EXIT.usage);
40
+ }
41
+ const bytes = readAllOfFd0();
42
+ const offset = firstInvalidUtf8Offset(bytes);
43
+ if (offset !== -1) {
44
+ process.stderr.write(`smelt: stdin is not valid UTF-8 — first invalid byte at offset ${String(offset)} ` +
45
+ `(0x${bytes[offset].toString(16).padStart(2, '0')}). Decoding it would silently ` +
46
+ `replace bytes with U+FFFD, and the "original" smelt could then reconstruct would ` +
47
+ `not be your original. Refusing instead.\n`);
48
+ process.exit(EXIT.refused);
49
+ }
50
+ return bytes.toString('utf8');
51
+ }
52
+ /** `Atomics.wait` is the only dependency-free synchronous sleep Node offers. */
53
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
54
+ /**
55
+ * Every byte of fd 0, to EOF, whether the descriptor is blocking (a shell pipe, a
56
+ * redirected file) or non-blocking (a socketpair from a spawning parent). `EAGAIN`
57
+ * means "no bytes yet, not EOF" — wait briefly and try again; only a zero-byte read
58
+ * (or Windows' `EOF` on a closed pipe) ends the loop.
59
+ */
60
+ function readAllOfFd0() {
61
+ const chunks = [];
62
+ const chunk = Buffer.alloc(1 << 16);
63
+ for (;;) {
64
+ let bytesRead;
65
+ try {
66
+ bytesRead = readSync(0, chunk, 0, chunk.length, null);
67
+ }
68
+ catch (error) {
69
+ const code = error.code;
70
+ if (code === 'EAGAIN') {
71
+ Atomics.wait(sleeper, 0, 0, 10); // producer not ready — 10ms, then retry
72
+ continue;
73
+ }
74
+ if (code === 'EOF')
75
+ break; // Windows raises EOF instead of returning 0
76
+ throw error;
77
+ }
78
+ if (bytesRead === 0)
79
+ break;
80
+ chunks.push(Buffer.from(chunk.subarray(0, bytesRead)));
81
+ }
82
+ return Buffer.concat(chunks);
83
+ }
84
+ /**
85
+ * The byte offset where `bytes` stops being well-formed UTF-8, or `-1` when it is
86
+ * well-formed throughout. Implements the WHATWG/Unicode table exactly: continuation
87
+ * ranges tightened for E0/ED/F0/F4 so overlongs, surrogates and > U+10FFFF are
88
+ * invalid — the same sequences `Buffer.prototype.toString` would fold into U+FFFD.
89
+ */
90
+ function firstInvalidUtf8Offset(bytes) {
91
+ let i = 0;
92
+ while (i < bytes.length) {
93
+ const lead = bytes[i];
94
+ if (lead <= 0x7f) {
95
+ i += 1;
96
+ continue;
97
+ }
98
+ let length;
99
+ let firstLow = 0x80;
100
+ let firstHigh = 0xbf;
101
+ if (lead >= 0xc2 && lead <= 0xdf) {
102
+ length = 2;
103
+ }
104
+ else if (lead >= 0xe0 && lead <= 0xef) {
105
+ length = 3;
106
+ if (lead === 0xe0)
107
+ firstLow = 0xa0; // overlong
108
+ if (lead === 0xed)
109
+ firstHigh = 0x9f; // UTF-16 surrogates
110
+ }
111
+ else if (lead >= 0xf0 && lead <= 0xf4) {
112
+ length = 4;
113
+ if (lead === 0xf0)
114
+ firstLow = 0x90; // overlong
115
+ if (lead === 0xf4)
116
+ firstHigh = 0x8f; // above U+10FFFF
117
+ }
118
+ else {
119
+ return i; // a bare continuation byte, or C0/C1/F5–FF — invalid as a lead
120
+ }
121
+ if (i + length > bytes.length)
122
+ return i; // truncated sequence
123
+ for (let k = 1; k < length; k += 1) {
124
+ const continuation = bytes[i + k];
125
+ const low = k === 1 ? firstLow : 0x80;
126
+ const high = k === 1 ? firstHigh : 0xbf;
127
+ if (continuation < low || continuation > high)
128
+ return i;
129
+ }
130
+ i += length;
131
+ }
132
+ return -1;
133
+ }
134
+ /** `--version` should agree with the manifest, not with a second copy of the number. */
135
+ function packageVersion() {
136
+ const manifest = readFileSync(new URL('../../package.json', import.meta.url), 'utf8');
137
+ const parsed = JSON.parse(manifest);
138
+ return parsed.version ?? '0.0.0';
139
+ }
140
+ try {
141
+ process.exitCode = await runCli(process.argv.slice(2), {
142
+ stdout: (text) => void process.stdout.write(text),
143
+ stderr: (text) => void process.stderr.write(text),
144
+ stdin: readStdin,
145
+ version: packageVersion(),
146
+ cwd: process.cwd(),
147
+ // `smelt init` reads answers line by line, so it gets the stream, not readStdin's
148
+ // one-shot slurp of fd 0. A *getter*, because touching `process.stdin` at all
149
+ // flips fd 0 into non-blocking mode and breaks readStdin's readFileSync(0) for
150
+ // every other mode — only the `init` branch of runCli ever reads this property.
151
+ get initInput() {
152
+ return process.stdin;
153
+ },
154
+ });
155
+ }
156
+ catch (error) {
157
+ process.stderr.write(`smelt: unexpected internal error — this is a bug, please report it.\n` +
158
+ `${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
159
+ process.exitCode = EXIT.unexpected;
160
+ }
161
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","sourceRoot":"","sources":["../../src/cli/bin.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,OAAO,MAAM,cAAc,CAAC;AAEnC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAExC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,6FAA6F;AAC7F,SAAS,SAAS;IAChB,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;QACd,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,kDAAkD;YAChD,uCAAuC;YACvC,uDAAuD,CAC1D,CAAC;QACF,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;IACD,MAAM,KAAK,GAAG,YAAY,EAAE,CAAC;IAC7B,MAAM,MAAM,GAAG,sBAAsB,CAAC,KAAK,CAAC,CAAC;IAC7C,IAAI,MAAM,KAAK,CAAC,CAAC,EAAE,CAAC;QAClB,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,kEAAkE,MAAM,CAAC,MAAM,CAAC,GAAG;YACjF,MAAM,KAAK,CAAC,MAAM,CAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,gCAAgC;YAClF,mFAAm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AAC;KACF,CAAC,CAAC;AACL,CAAC;AAAC,OAAO,KAAK,EAAE,CAAC;IACf,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,uEAAuE;QACrE,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CACjF,CAAC;IACF,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC;AACrC,CAAC"}
@@ -0,0 +1,73 @@
1
+ import type { Strategy } from '../plan/planners.ts';
2
+ /**
3
+ * `smelt.config.json` — CLI defaults, and nothing more.
4
+ *
5
+ * This file exists so `smelt` can be run without retyping the same flags, and it is
6
+ * deliberately a *CLI* concern: the programmatic API never reads it. A library that
7
+ * reads config files off the caller's disk is a library whose behaviour depends on
8
+ * where it was invoked from, which is exactly the class of invisible input smelt
9
+ * refuses. `createSmelter()` takes explicit arguments; the CLI translates this file
10
+ * into those arguments, and explicit flags always win over it.
11
+ *
12
+ * The schema is versioned (`"smeltConfig": 1`) for the same reason the marker and the
13
+ * `--json` envelope are: files outlive the binaries that wrote them, and a mismatch
14
+ * must be identifiable rather than half-understood. Parsing is strict — an unknown
15
+ * key, a wrong type, or an unknown version is a {@link CliUsageError}, never a shrug.
16
+ * A config the CLI silently ignored would be a budget the user *thought* they set.
17
+ */
18
+ /** The file name looked for, from the working directory upward. */
19
+ export declare const CONFIG_FILE_NAME = "smelt.config.json";
20
+ /** The schema version this build reads and writes. */
21
+ export declare const CONFIG_VERSION = 1;
22
+ /** Where the CLI's elision store lives between runs. */
23
+ export type SmeltConfigStore = {
24
+ readonly kind: 'memory';
25
+ } | {
26
+ readonly kind: 'directory';
27
+ /** Resolved relative to the directory holding the config file, not the cwd. */
28
+ readonly path: string;
29
+ };
30
+ /** The parsed shape of `smelt.config.json`. Every field beyond the version is optional. */
31
+ export interface SmeltConfig {
32
+ readonly smeltConfig: typeof CONFIG_VERSION;
33
+ /** Used when a `smelt` run omits `--budget`. UTF-8 bytes, like every smelt budget. */
34
+ readonly defaultBudgetBytes?: number;
35
+ /** Used when a run omits `--strategy`. Validated against the {@link PLANNERS} registry. */
36
+ readonly strategy?: Strategy;
37
+ /** Used for every run; there is no store flag. Defaults to memory when absent. */
38
+ readonly store?: SmeltConfigStore;
39
+ }
40
+ /** A config plus where it was found — the path matters for resolving `store.path`. */
41
+ export interface LoadedConfig {
42
+ readonly path: string;
43
+ readonly config: SmeltConfig;
44
+ }
45
+ /**
46
+ * The nearest `smelt.config.json`, walking up from `cwd` to the filesystem root —
47
+ * the same discovery shape as `package.json`, so a config at a repo root covers the
48
+ * whole tree. `undefined` when there is none, which is not an error: flags alone are
49
+ * a complete interface.
50
+ */
51
+ export declare function findConfigFile(cwd: string): string | undefined;
52
+ /**
53
+ * Find and parse the nearest config. `undefined` when no file exists; a file that
54
+ * exists but is malformed **throws** — see {@link parseConfig}. The distinction is the
55
+ * point: "no config" is a fine state, "a config you cannot have meant" is not.
56
+ *
57
+ * @throws {CliUsageError} when a config file exists and is malformed.
58
+ */
59
+ export declare function loadNearestConfig(cwd: string): LoadedConfig | undefined;
60
+ /**
61
+ * Parse and validate one config file, strictly.
62
+ *
63
+ * Strict means: unknown keys are refused, not skipped. A typo'd `defaultBudgetByte`
64
+ * that parsed cleanly would leave the user believing a default was set while every
65
+ * run ignored it — a config error whose failure mode is *silence*, which is the one
66
+ * failure shape this project refuses everywhere else too.
67
+ *
68
+ * @throws {CliUsageError} naming the file and the exact problem.
69
+ */
70
+ export declare function parseConfig(text: string, path: string): SmeltConfig;
71
+ /** `store.path` is relative to the config file, so the config works from any cwd. */
72
+ export declare function resolveStorePath(loaded: LoadedConfig, path: string): string;
73
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/cli/config.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,E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