@fcli.dev/config 0.0.0-stage → 0.4.2

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 (3) hide show
  1. package/index.js +392 -0
  2. package/package.json +19 -4
  3. package/README.md +0 -3
package/index.js ADDED
@@ -0,0 +1,392 @@
1
+ import { createRequire } from "node:module";
2
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, realpathSync } from "node:fs";
3
+ import { join, dirname, resolve, isAbsolute, sep } from "node:path";
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const { JSONPath } = require("jsonpath-plus");
7
+
8
+ /** Resolve the config file for a target: "project" | "global" | explicit path. */
9
+ function resolveTarget(target) {
10
+ if (target && target !== "project" && target !== "global") {
11
+ return target; // explicit path
12
+ }
13
+ if (target === "global") {
14
+ return join(process.env.HOME ?? "", ".f", "f.config.json");
15
+ }
16
+ // project: walk up from cwd
17
+ let dir = process.cwd();
18
+ for (let i = 0; i < 6; i++) {
19
+ const p = join(dir, "f.config.json");
20
+ if (existsSync(p)) return p;
21
+ dir = join(dir, "..");
22
+ }
23
+ // No project config found — default to creating in cwd.
24
+ return join(process.cwd(), "f.config.json");
25
+ }
26
+
27
+ function readDoc(path) {
28
+ if (!existsSync(path)) return {};
29
+ return JSON.parse(readFileSync(path, "utf8"));
30
+ }
31
+
32
+ function writeDoc(path, doc) {
33
+ mkdirSync(dirname(path), { recursive: true });
34
+ writeFileSync(path, JSON.stringify(doc, null, 2) + "\n");
35
+ }
36
+
37
+ /** Parse a value: try JSON first, fall back to raw string. */
38
+ function parseValue(raw) {
39
+ // NOTE: String(value) in the callers is only correct because every value that
40
+ // reaches it is already a string (an argv token). It is a trap for programmatic
41
+ // callers: configApi.add(t, "ucks", ["a"]) stringifies to "a" and stores the
42
+ // string, not the array. Parse non-strings through unchanged.
43
+ if (typeof raw !== "string") return raw;
44
+ try {
45
+ return JSON.parse(raw);
46
+ } catch {
47
+ return raw;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * A uck source that points into the store, or null. Checked at the moment the
53
+ * source is written, not when `f up` later tries to install it.
54
+ *
55
+ * Core refuses to install such a source: installing it copies a tree into
56
+ * itself, and the copy partly lands before the failure — which is how one
57
+ * mistyped path deleted `config/*` and `lib/*` from an author's own bucket and
58
+ * left it claiming to be a clone of another repo. Seeing that here, on
59
+ * `f config add`, beats seeing it during a later `f up`.
60
+ *
61
+ * Git URLs, npm specs and anything else that is not a filesystem path are
62
+ * untouched, and only the realpath is compared — a source that merely shares a
63
+ * label with a store ancestor is a name collision (ROADMAP C5), not a self-copy,
64
+ * so it stays allowed.
65
+ */
66
+ function insideStore(specifier) {
67
+ if (typeof specifier !== "string" || !specifier) return null;
68
+ if (/^(git\+|file|https?|ssh|ftps?):\/\//i.test(specifier)) return null;
69
+ if (specifier.startsWith("github:") || specifier.startsWith("git@")) return null;
70
+ const looksLikePath =
71
+ specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("~");
72
+ if (!looksLikePath) return null; // an npm spec
73
+ const expanded =
74
+ specifier.startsWith("~") ? join(process.env.HOME ?? "", specifier.slice(1)) : specifier;
75
+ let abs;
76
+ try {
77
+ abs = realpathSync(isAbsolute(expanded) ? expanded : resolve(process.cwd(), expanded));
78
+ } catch {
79
+ return null; // unresolvable here; core reports it at install time
80
+ }
81
+ let store;
82
+ try {
83
+ store = realpathSync(join(process.env.HOME ?? "", ".f", "ucks"));
84
+ } catch {
85
+ return null; // no store yet: nothing can be inside it
86
+ }
87
+ return abs === store || abs.startsWith(store + sep) ? abs : null;
88
+ }
89
+
90
+ /**
91
+ * Refuse to write a config whose uck sources point into the store. Throws
92
+ * instead of writing, so the file is never left describing an uninstallable
93
+ * source. NOTE: this guards the config only. Whether authors may *edit* store
94
+ * buckets is a separate, unresolved question — see ROADMAP-1.0.md C1(b).
95
+ */
96
+ function assertSourcesUsable(doc) {
97
+ const list = Array.isArray(doc?.ucks) ? doc.ucks : Array.isArray(doc?.extensions) ? doc.extensions : [];
98
+ const sources = list
99
+ .map((s) => (typeof s === "string" ? s : typeof s?.source === "string" ? s.source : null))
100
+ .filter(Boolean);
101
+ const bad = sources.filter(insideStore);
102
+ if (bad.length === 0) return;
103
+ const store = join(process.env.HOME ?? "", ".f", "ucks");
104
+ throw new Error(
105
+ `uck source(s) point into the store (${store}):\n ${bad.join("\n ")}\n` +
106
+ `A store bucket is a cache that f overwrites; a source inside it means copying a tree over itself.\n` +
107
+ `Add an external path instead (a clone you made), or push and add the git URL.`
108
+ );
109
+ }
110
+
111
+ /** Core ops. target: "project" | "global" | explicit path. */
112
+ const configApi = {
113
+ /** Read the whole doc (or a path). Returns the natural value (no extra array wrap). */
114
+ get(target, path) {
115
+ const file = resolveTarget(target);
116
+ const doc = readDoc(file);
117
+ if (!path) return doc;
118
+ const res = JSONPath({ path, json: doc, wrap: true });
119
+ if (!Array.isArray(res) || res.length === 0) return null;
120
+ // unwrap single match to its natural value; keep arrays for multi-match
121
+ return res.length === 1 ? res[0] : res;
122
+ },
123
+
124
+ /** Set a value at a JSONPath. Creates intermediate objects as needed. */
125
+ set(target, path, value) {
126
+ const file = resolveTarget(target);
127
+ const doc = readDoc(file);
128
+ const val = parseValue(value);
129
+ applySet(doc, path, val);
130
+ assertSourcesUsable(doc);
131
+ writeDoc(file, doc);
132
+ return val;
133
+ },
134
+
135
+ /** Append a value into an array at a JSONPath (ucks[$] style). */
136
+ add(target, path, value) {
137
+ const file = resolveTarget(target);
138
+ const doc = readDoc(file);
139
+ const val = parseValue(value);
140
+ applyAdd(doc, path, val);
141
+ assertSourcesUsable(doc);
142
+ writeDoc(file, doc);
143
+ return val;
144
+ },
145
+
146
+ /** Remove matches at a JSONPath. */
147
+ remove(target, path) {
148
+ const file = resolveTarget(target);
149
+ const doc = readDoc(file);
150
+ const n = applyRemove(doc, path);
151
+ writeDoc(file, doc);
152
+ return n;
153
+ },
154
+
155
+ /** List the whole doc (alias for get with no path). */
156
+ list(target) {
157
+ return this.get(target);
158
+ },
159
+ };
160
+
161
+ /** Set via resultType all (parent + parentProperty). */
162
+ function applySet(doc, path, value) {
163
+ // If the path selects nothing, create it by walking segments.
164
+ const existing = JSONPath({ path, json: doc, wrap: true });
165
+ if (Array.isArray(existing) && existing.length > 0) {
166
+ const all = JSONPath({ path, json: doc, resultType: "all" });
167
+ for (const item of all) {
168
+ if (item.parent && item.parentProperty != null) {
169
+ item.parent[item.parentProperty] = value;
170
+ }
171
+ }
172
+ return;
173
+ }
174
+ // Create intermediate structure then assign leaf.
175
+ setPathCreate(doc, path, value);
176
+ }
177
+
178
+ /** Walk a simple dotted/bracketed path, creating objects/arrays, set leaf. */
179
+ function setPathCreate(doc, path, value) {
180
+ const segments = parseSegments(path);
181
+ let cur = doc;
182
+ for (let i = 0; i < segments.length - 1; i++) {
183
+ const seg = segments[i];
184
+ if (cur[seg] == null) {
185
+ // Infer array vs object from next segment.
186
+ const next = segments[i + 1];
187
+ cur[seg] = /^\d+$/.test(next) || next === "$" ? [] : {};
188
+ }
189
+ cur = cur[seg];
190
+ }
191
+ const leaf = segments[segments.length - 1];
192
+ if (Array.isArray(cur) && (leaf === "$" || /^\d+$/.test(leaf))) {
193
+ if (leaf === "$") cur.push(value);
194
+ else cur[Number(leaf)] = value;
195
+ } else {
196
+ cur[leaf] = value;
197
+ }
198
+ }
199
+
200
+ /** Append into an array. Path must select an array (e.g. "ucks" or "ucks[$]"). */
201
+ function applyAdd(doc, path, value) {
202
+ // Append `value` to the array selected by `path`, creating it when absent.
203
+ //
204
+ // Everything is driven by JSONPath's own resultType "all" records
205
+ // (parent / parentProperty) — the same source of truth applySet uses. Two
206
+ // hand-rolled shortcuts lost data here:
207
+ // * the fallback was setPathCreate(doc, path, undefined): it assigned
208
+ // undefined, the key did not survive JSON.stringify, and
209
+ // `f config add ucks github:user/repo` — the example in this uck's own
210
+ // usage line — wrote {} and exited 0;
211
+ // * parseSegments("ucks[0]") returns ["ucks","0"], where "0" is part of the
212
+ // selector and not a container to walk into; walking it produced
213
+ // {"ucks":{"0":["b"]}}.
214
+ //
215
+ // An absent path must still work rather than fail: `add` is how a fresh config
216
+ // gets its first source, and it is f's own bootstrap path — ensureGlobalConfig()
217
+ // seeds a source with no ref, so `f config add <x>#main` on a machine that has
218
+ // never run f also lands here.
219
+ const clean = path.replace(/\[\$\]$/, "");
220
+ const segments = parseSegments(clean);
221
+ if (segments.length === 0) throw new Error(`config: '${path}' is not a usable path`);
222
+ const leaf = segments.at(-1);
223
+ const matches = JSONPath({ path: clean, json: doc, resultType: "all" });
224
+ const anchor = matches[0];
225
+ const parent = anchor && "parent" in anchor ? anchor.parent : undefined;
226
+ const prop = anchor && "parentProperty" in anchor ? anchor.parentProperty : undefined;
227
+ const owner =
228
+ clean.replace(/\[[^\]]*\]$/, "") ||
229
+ segments.slice(0, -1).reduce((acc, seg) => (seg.match(/^\d+$/) ? acc : acc + "." + seg), "").replace(/^\./, "") ||
230
+ "the array";
231
+
232
+ // A positional path is refused whether or not it currently matches.
233
+ // `add ucks[5] x` on a 1-element array matched nothing and would have written
234
+ // a HOLE — a hole serialises as null, and core's source loop does
235
+ // `typeof s === "string" ? s : s?.source`, so null becomes undefined and
236
+ // every later f command dies with "Uck source not found: undefined".
237
+ // `add ucks[0] x` on a 1-element array matched the element "a"; pushing onto
238
+ // a string is a no-op, so it reported success having changed nothing.
239
+ // Positions have no append semantics at all — `set` is the operation for them.
240
+ if (/^\d+$/.test(leaf)) {
241
+ throw new Error(
242
+ `config: '${clean}' addresses a position — use 'f config set' to replace it, or 'f config add ${owner}' to append`
243
+ );
244
+ }
245
+
246
+ if (Array.isArray(parent)) {
247
+ // The selector addressed an element of an array ($, or a name that JSONPath
248
+ // resolved through one). Only [$] means "append here".
249
+ if (leaf === "$") {
250
+ parent.push(value);
251
+ return;
252
+ }
253
+ throw new Error(`config: '${clean}' addresses a position — use 'f config add ${owner}' to append`);
254
+ }
255
+
256
+ if (parent !== undefined && prop !== undefined && prop !== null) {
257
+ if (parent[prop] === undefined) {
258
+ parent[prop] = [value];
259
+ return;
260
+ }
261
+ if (!Array.isArray(parent[prop]))
262
+ throw new Error(
263
+ `config: '${clean}' is ${typeof parent[prop]}, not an array — use 'f config set' to give it a value`
264
+ );
265
+ parent[prop].push(value);
266
+ return;
267
+ }
268
+
269
+ // Nothing matches: the key is absent. Create it (dotted paths included) and
270
+ // store an array.
271
+ let cursor = doc;
272
+ for (const seg of segments.slice(0, -1)) {
273
+ if (cursor[seg] === undefined) cursor[seg] = {};
274
+ cursor = cursor[seg];
275
+ if (cursor === null || typeof cursor !== "object")
276
+ throw new Error(`config: '${clean}' passes through a non-object`);
277
+ }
278
+ if (cursor[leaf] === undefined) cursor[leaf] = [];
279
+ if (!Array.isArray(cursor[leaf]))
280
+ throw new Error(`config: '${clean}' is not an array — use 'f config set' to give it a value`);
281
+ cursor[leaf].push(value);
282
+ }
283
+
284
+ function applyRemove(doc, path) {
285
+ // Collect parents+indices for array elements, or keys for object props.
286
+ const all = JSONPath({ path, json: doc, resultType: "all" });
287
+ let removed = 0;
288
+ for (const item of all) {
289
+ if (item.parent == null) continue;
290
+ const pp = item.parentProperty;
291
+ if (Array.isArray(item.parent)) {
292
+ const idx = Number(pp);
293
+ if (Number.isInteger(idx) && idx >= 0 && idx < item.parent.length) {
294
+ item.parent.splice(idx, 1);
295
+ removed++;
296
+ }
297
+ } else if (typeof item.parent === "object" && pp in item.parent) {
298
+ delete item.parent[pp];
299
+ removed++;
300
+ }
301
+ }
302
+ return removed;
303
+ }
304
+
305
+ /** Parse a path into segments: "ucks[2].source" -> ["ucks","2","source"]; "ucks" -> ["ucks"]. */
306
+ function parseSegments(path) {
307
+ const segs = [];
308
+ const re = /([^.[\]]+)|\[(\d+|\$)\]/g;
309
+ let m;
310
+ while ((m = re.exec(path)) !== null) {
311
+ if (m[1] !== undefined) segs.push(m[1]);
312
+ else segs.push(m[2]);
313
+ }
314
+ return segs;
315
+ }
316
+
317
+ /** The uck. */
318
+ export function register(ctx) {
319
+ return {
320
+ name: "config",
321
+ desc: "edit f.config.json via JSONPath (get/set/add/remove/list)",
322
+ // Programmatic entry: other ucks can do require("@fcli/config").configApi
323
+ configApi,
324
+ run: (argv, args) => {
325
+ const flags = [];
326
+ const pos = [];
327
+ for (const a of args._ ?? []) (a === "-g" ? flags : pos).push(a);
328
+ const target = flags.includes("-g") ? "global" : "project";
329
+
330
+ const [op, path, value] = pos;
331
+ if (!op) return usage();
332
+
333
+ // A config edit that cannot be done must fail as one line plus the fix
334
+ // (CONTRACT.md R3), not as a Node stack trace: this uck is the thing an LLM
335
+ // reaches for when it is already confused about config, and a 30-frame
336
+ // stack gives it nothing to act on. Previously there was no catch at all,
337
+ // so a throwing add/set printed the stack of an internal helper.
338
+ try {
339
+ switch (op) {
340
+ case "get":
341
+ if (!path) return usage("get requires a path (or omit for whole doc)");
342
+ print(configApi.get(target, path));
343
+ break;
344
+ case "list":
345
+ print(configApi.list(target));
346
+ break;
347
+ case "set":
348
+ if (!path || value == null) return usage("set requires <path> <value>");
349
+ configApi.set(target, path, value);
350
+ break;
351
+ case "add":
352
+ if (!path || value == null) return usage("add requires <path> <value>");
353
+ configApi.add(target, path, value);
354
+ break;
355
+ case "remove":
356
+ if (!path) return usage("remove requires a path");
357
+ configApi.remove(target, path);
358
+ break;
359
+ default:
360
+ usage();
361
+ }
362
+ } catch (e) {
363
+ process.stderr.write(`f: ${e instanceof Error ? e.message : String(e)}\n`);
364
+ process.exitCode = 1; // not exit(1): CONTRACT.md C5 — never truncate stdout
365
+ }
366
+ },
367
+ };
368
+ }
369
+
370
+ function print(v) {
371
+ process.stdout.write(typeof v === "string" ? v : JSON.stringify(v, null, 2) + "\n");
372
+ }
373
+
374
+ function usage(msg) {
375
+ const line = msg ? `f: ${msg}\n` : "";
376
+ process.stderr.write(
377
+ line +
378
+ "usage: f config [-g] <op> <path> [value]\n" +
379
+ " ops: get | set | add | remove | list\n" +
380
+ " -g target global ~/.f/f.config.json (default: project f.config.json)\n" +
381
+ " e.g. f config add ucks github:user/repo\n" +
382
+ " f config set ucks[0] ./my-uck\n" +
383
+ " f config remove 'ucks[?(@.source==\"./old\")]'\n"
384
+ );
385
+ // exitCode, not exit(): CONTRACT.md C5. process.exit() throws away whatever is
386
+ // still buffered on stdout when stdout is a pipe — which is exactly how an agent
387
+ // invokes a uck — so the truncation core just fixed would come back through a
388
+ // usage error, quietly.
389
+ process.exitCode = 1;
390
+ }
391
+
392
+ export default { register, configApi };
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "@fcli.dev/config",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "type": "module",
4
+ "description": "f uck: edit f.config.json via JSONPath",
5
+ "main": "index.js",
6
+ "dependencies": {
7
+ "jsonpath-plus": "^11.2.0"
8
+ },
9
+ "version": "0.4.2",
10
+ "license": "GPL-3.0-only",
11
+ "keywords": [
12
+ "fcli",
13
+ "fcli-uck",
14
+ "uck",
15
+ "cli"
16
+ ],
17
+ "files": [
18
+ "index.js",
19
+ "uckmain.js"
20
+ ]
21
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.