@triflare/fx 2.2.0 → 2.3.0-alpha.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.
package/src/features.js CHANGED
@@ -1,89 +1,46 @@
1
1
  /**
2
- * Built-in, project-local features.
2
+ * Optional feature management.
3
3
  *
4
- * `fx feature <name> enable` copies a feature's extension source into the
5
- * project and records that file under `features:` in `fx.yml`. Builds load the
6
- * committed file, so an Fx upgrade never changes a project's feature code, and
7
- * the project keeps working offline (and in Fx versions that predate the
8
- * feature system) because the extension is an ordinary JavaScript file.
4
+ * Every feature is described by `./feature-registry.js` and switched under the
5
+ * single `fx.features` key. Enabling an extension-backed feature copies its
6
+ * source into the project and records that file under `fx.features`, so an Fx
7
+ * upgrade never changes a project's feature code and the project keeps working
8
+ * offline. Core features (tests, run, partial sprites) are built into Fx and
9
+ * only record their switch.
9
10
  */
10
11
  import crypto from "node:crypto";
11
12
  import fs from "node:fs";
12
13
  import path from "node:path";
13
- import { fileURLToPath } from "node:url";
14
14
  import { parseConfig } from "./config.js";
15
15
  import {
16
- addFeatureEntry,
17
- readFxValue,
16
+ readFeatureSetting,
17
+ readTopLevelFeatureEntries,
18
18
  removeFeatureEntry,
19
- setFxScalar,
19
+ removeFeatureSetting,
20
+ removeFxKey,
21
+ removeTopLevelKey,
22
+ setFeatureSetting,
20
23
  } from "./config-edit.js";
24
+ import {
25
+ CORE_FEATURES,
26
+ FEATURES,
27
+ FeatureError,
28
+ coreFeatureNames,
29
+ featureNames,
30
+ getFeature,
31
+ } from "./feature-registry.js";
21
32
  import { loadExtensions } from "./extensions.js";
22
33
  import { formatDiff } from "./vendor.js";
23
34
 
24
- export class FeatureError extends Error {
25
- constructor(message, options) {
26
- super(message, options);
27
- this.name = "FeatureError";
28
- }
29
- }
30
-
31
- /**
32
- * Feature registry. `source` points at the fork that ships with Fx; `enable`
33
- * copies it into the project so the project owns (and pins) the bytes.
34
- */
35
- export const FEATURES = {
36
- temporaryvariables: {
37
- name: "temporaryvariables",
38
- title: "Temporary Variables",
39
- summary: "Disposable per-thread and per-run variables.",
40
- extensionId: "fxTempVars",
41
- filename: "fx-tempvars.js",
42
- source: fileURLToPath(
43
- new URL("../vendor/tempvars/fx-tempvars.js", import.meta.url),
44
- ),
45
- },
46
- };
47
-
48
- /**
49
- * Built-in language features. They live behind a single `fx.<name>` setting,
50
- * so they are enabled and disabled without touching `features:`. A core
51
- * feature may still ship an extension; Fx loads that bundled source itself
52
- * instead of copying it into the project.
53
- */
54
- export const CORE_FEATURES = {
55
- tests: {
56
- name: "tests",
57
- title: "Testing",
58
- summary: "Write project tests and run them with `fx test`.",
59
- core: true,
60
- command: "test",
61
- },
62
- run: {
63
- name: "run",
64
- title: "Running",
65
- summary: "Run headless entry points with `fx run`.",
66
- core: true,
67
- command: "run",
68
- },
35
+ export {
36
+ CORE_FEATURES,
37
+ FEATURES,
38
+ FeatureError,
39
+ coreFeatureNames,
40
+ featureNames,
41
+ getFeature,
69
42
  };
70
43
 
71
- /** List feature names for help and error messages. */
72
- export function featureNames() {
73
- return [...Object.keys(FEATURES), ...Object.keys(CORE_FEATURES)].sort();
74
- }
75
-
76
- /** Resolve one feature by name. */
77
- export function getFeature(name) {
78
- const key = String(name ?? "");
79
- const feature = FEATURES[key] ?? CORE_FEATURES[key];
80
- if (!feature)
81
- throw new FeatureError(
82
- `Unknown feature ${JSON.stringify(key)}. Available features: ${featureNames().join(", ")}.`,
83
- );
84
- return feature;
85
- }
86
-
87
44
  /** Absolute path of the extension source Fx ships for a feature. */
88
45
  export function featureSourcePath(name) {
89
46
  return getFeature(name).source;
@@ -169,9 +126,45 @@ function writeFileAtomic(file, data) {
169
126
  }
170
127
  }
171
128
 
172
- /** Read the `features:` list from a config file. */
173
- function readFeatureEntries(configPath) {
174
- return parseConfig(fs.readFileSync(configPath, "utf8")).features;
129
+ function isPlainObject(value) {
130
+ return value != null && typeof value === "object" && !Array.isArray(value);
131
+ }
132
+
133
+ /** Read a config file, or null when the project has none yet. */
134
+ function readConfig(configPath) {
135
+ if (!configPath || !fs.existsSync(configPath)) return null;
136
+ return parseConfig(fs.readFileSync(configPath, "utf8"));
137
+ }
138
+
139
+ /** The effective extension entry for a feature, if it is enabled. */
140
+ function featureEntry(configPath, feature) {
141
+ if (feature.core) return null;
142
+ const loaded = readConfig(configPath);
143
+ return loaded?.features.find((entry) => entry.name === feature.name) ?? null;
144
+ }
145
+
146
+ /**
147
+ * The value to write when re-enabling a core feature. A value from either the
148
+ * new key or the legacy `fx.<name>` setting keeps its options, so disabling and
149
+ * enabling again does not reset a pattern, timeout, or seed.
150
+ */
151
+ function retainedCoreValue(configPath, feature) {
152
+ const own = readFeatureSetting(configPath, feature.name);
153
+ if (isPlainObject(own)) return { ...own, enabled: true };
154
+ const loaded = readConfig(configPath);
155
+ const legacy = loaded?.raw?.fx?.[feature.name];
156
+ if (isPlainObject(legacy)) return { ...legacy, enabled: true };
157
+ return true;
158
+ }
159
+
160
+ /** The value to write when disabling a core feature, keeping its options. */
161
+ function disabledCoreValue(configPath, feature) {
162
+ const own = readFeatureSetting(configPath, feature.name);
163
+ if (isPlainObject(own)) return { ...own, enabled: false };
164
+ const loaded = readConfig(configPath);
165
+ const legacy = loaded?.raw?.fx?.[feature.name];
166
+ if (isPlainObject(legacy)) return { ...legacy, enabled: false };
167
+ return false;
175
168
  }
176
169
 
177
170
  /**
@@ -186,30 +179,27 @@ function readFeatureEntries(configPath) {
186
179
  * @param {boolean} [options.force] replace a modified copy
187
180
  * @returns {{feature: object, name: string, file: string, path: string, changed: boolean, configChanged: boolean}}
188
181
  */
189
- /** True when a feature's setting is enabled in the project config. */
190
- function coreFeatureEnabled(configPath, feature) {
191
- if (!configPath || !fs.existsSync(configPath)) return false;
192
- return Boolean(readFxValue(configPath, feature.name));
193
- }
194
-
195
182
  /**
196
183
  * Whether a feature is currently enabled in a project.
197
- * @param {{configPath?: string, name: string}} options
184
+ *
185
+ * `fx.features` is the canonical switch; the older `fx.<name>` setting and
186
+ * top-level `features:` entries stay readable, with the new key winning.
187
+ *
188
+ * @param {{configPath?: string, config?: object, name: string}} options
198
189
  */
199
- export function featureEnabled({ configPath, name } = {}) {
190
+ export function featureEnabled({ configPath, config, name } = {}) {
200
191
  const feature = getFeature(name);
201
- if (feature.core) return coreFeatureEnabled(configPath, feature);
202
- if (!configPath || !fs.existsSync(configPath)) return false;
203
- return Boolean(
204
- readFeatureEntries(configPath).find((entry) => entry.name === feature.name),
205
- );
192
+ const loaded = config ?? readConfig(configPath);
193
+ if (!loaded) return false;
194
+ if (feature.core) return Boolean(loaded.fx?.[feature.name]);
195
+ return Boolean(loaded.features?.find((entry) => entry.name === feature.name));
206
196
  }
207
197
 
208
198
  /**
209
199
  * Enable a feature in a project.
210
200
  *
211
201
  * Extension features copy their source into the project; core features only
212
- * record `fx.<name>: true` in `fx.yml`.
202
+ * record `fx.features.<name>: true` in `fx.yml`.
213
203
  *
214
204
  * @param {object} options
215
205
  * @param {string} options.configPath
@@ -228,15 +218,27 @@ export function enableFeature({
228
218
  } = {}) {
229
219
  const feature = getFeature(name);
230
220
  if (feature.core) {
231
- const changed = !coreFeatureEnabled(configPath, feature);
232
- if (changed) setFxScalar(configPath, feature.name, true);
221
+ if (featureEnabled({ configPath, name: feature.name }))
222
+ return {
223
+ feature,
224
+ name: feature.name,
225
+ file: null,
226
+ path: null,
227
+ changed: false,
228
+ configChanged: false,
229
+ };
230
+ setFeatureSetting(
231
+ configPath,
232
+ feature.name,
233
+ retainedCoreValue(configPath, feature),
234
+ );
233
235
  return {
234
236
  feature,
235
237
  name: feature.name,
236
238
  file: null,
237
239
  path: null,
238
- changed,
239
- configChanged: changed,
240
+ changed: true,
241
+ configChanged: true,
240
242
  };
241
243
  }
242
244
  const dir = assertInside(
@@ -261,18 +263,29 @@ export function enableFeature({
261
263
  writeFileAtomic(target, source);
262
264
  }
263
265
  const file = relativeProjectPath(configDir, target);
264
- const configured = readFeatureEntries(configPath).find(
265
- (entry) => entry.name === feature.name,
266
- );
267
- const needsEntry = !configured || configured.file !== file;
268
- if (needsEntry) addFeatureEntry(configPath, feature.name, file);
266
+ const own = readFeatureSetting(configPath, feature.name);
267
+ let configChanged = false;
268
+ if (own !== file) {
269
+ setFeatureSetting(configPath, feature.name, file);
270
+ configChanged = true;
271
+ }
272
+ // Enabling an older project moves its entry under `fx.features`, so a
273
+ // project ends up with the canonical key once it is written to.
274
+ if (
275
+ readTopLevelFeatureEntries(configPath).some(
276
+ (entry) => entry.name === feature.name,
277
+ )
278
+ ) {
279
+ removeFeatureEntry(configPath, feature.name);
280
+ configChanged = true;
281
+ }
269
282
  return {
270
283
  feature,
271
284
  name: feature.name,
272
285
  file,
273
286
  path: target,
274
287
  changed,
275
- configChanged: needsEntry,
288
+ configChanged,
276
289
  };
277
290
  }
278
291
 
@@ -281,12 +294,12 @@ export function enableFeature({
281
294
  *
282
295
  * A file is deleted only when its name and bytes match the packaged feature
283
296
  * source that `enable`/`update` write. A hand-pointed or edited project file is
284
- * user-owned and survives, even though its `features:` entry is removed.
297
+ * user-owned and survives, even though its config entry is removed.
285
298
  */
286
299
  export function disableFeature({ configPath, configDir, name } = {}) {
287
300
  const feature = getFeature(name);
288
301
  if (feature.core) {
289
- if (!coreFeatureEnabled(configPath, feature))
302
+ if (!featureEnabled({ configPath, name: feature.name }))
290
303
  return {
291
304
  feature,
292
305
  name: feature.name,
@@ -294,21 +307,20 @@ export function disableFeature({ configPath, configDir, name } = {}) {
294
307
  changed: false,
295
308
  warning: null,
296
309
  };
297
- setFxScalar(configPath, feature.name, false);
310
+ setFeatureSetting(
311
+ configPath,
312
+ feature.name,
313
+ disabledCoreValue(configPath, feature),
314
+ );
298
315
  return {
299
316
  feature,
300
317
  name: feature.name,
301
318
  file: null,
302
319
  changed: true,
303
- warning:
304
- feature.name === "tests"
305
- ? `${feature.title} will become a core feature in a future version.`
306
- : null,
320
+ warning: null,
307
321
  };
308
322
  }
309
- const entry = readFeatureEntries(configPath).find(
310
- (candidate) => candidate.name === feature.name,
311
- );
323
+ const entry = featureEntry(configPath, feature);
312
324
  if (!entry)
313
325
  throw new FeatureError(
314
326
  `${feature.title} is not enabled. Run "fx feature ${feature.name} enable" first.`,
@@ -331,6 +343,7 @@ export function disableFeature({ configPath, configDir, name } = {}) {
331
343
  installedByFx = false;
332
344
  }
333
345
  }
346
+ removeFeatureSetting(configPath, feature.name);
334
347
  removeFeatureEntry(configPath, feature.name);
335
348
  if (installedByFx) fs.rmSync(target, { force: true });
336
349
  return {
@@ -357,9 +370,7 @@ export function updateFeature({
357
370
  throw new FeatureError(
358
371
  `${feature.title} is built into Fx, so there is no vendored source or lock entry to update.`,
359
372
  );
360
- const entry = readFeatureEntries(configPath).find(
361
- (candidate) => candidate.name === feature.name,
362
- );
373
+ const entry = featureEntry(configPath, feature);
363
374
  if (!entry)
364
375
  throw new FeatureError(
365
376
  `${feature.title} is not enabled. Run "fx feature ${feature.name} enable" first.`,
@@ -467,3 +478,100 @@ export async function loadFeatureExtensions({ configDir, config } = {}) {
467
478
 
468
479
  return { catalog, extensionUrls, warnings, ids, unsandboxed };
469
480
  }
481
+
482
+ /**
483
+ * Move legacy feature settings under the single `fx.features` key.
484
+ *
485
+ * Legacy sources are `fx.tests`, `fx.run`, `fx.partialSprites`, and the
486
+ * top-level `features:` mapping. A value already present under `fx.features`
487
+ * wins; the legacy copy is removed either way. The config is backed up before
488
+ * it is changed.
489
+ *
490
+ * @param {{configPath: string, dryRun?: boolean}} options
491
+ * @returns {{migrated: string[], conflicts: string[], changed: boolean, backup: string|null, diff: string, configPath: string}}
492
+ */
493
+ export function migrateFeatureConfig({ configPath, dryRun = false } = {}) {
494
+ const original = fs.readFileSync(configPath, "utf8");
495
+ const loaded = parseConfig(original);
496
+ const rawFx = isPlainObject(loaded.raw?.fx) ? loaded.raw.fx : {};
497
+ const legacyEntries = readTopLevelFeatureEntries(configPath);
498
+ const coreNames = new Set(coreFeatureNames());
499
+
500
+ const migrated = new Set();
501
+ const moves = {};
502
+ // Top-level entries that can be removed after migration. A core-named entry
503
+ // stays where it is: writing its file path under `fx.features` would change
504
+ // the meaning of the key and make the result unloadable.
505
+ const removable = [];
506
+ const conflicts = [];
507
+ const legacyCoreKeys = coreFeatureNames().filter((name) =>
508
+ Object.hasOwn(rawFx, name),
509
+ );
510
+ for (const name of legacyCoreKeys) {
511
+ migrated.add(name);
512
+ if (readFeatureSetting(configPath, name) === undefined)
513
+ moves[name] = rawFx[name];
514
+ }
515
+ for (const entry of legacyEntries) {
516
+ if (coreNames.has(entry.name)) {
517
+ conflicts.push(entry.name);
518
+ continue;
519
+ }
520
+ migrated.add(entry.name);
521
+ removable.push(entry.name);
522
+ if (readFeatureSetting(configPath, entry.name) === undefined)
523
+ moves[entry.name] = entry.file;
524
+ }
525
+
526
+ if (
527
+ Object.keys(moves).length === 0 &&
528
+ removable.length === 0 &&
529
+ legacyCoreKeys.length === 0
530
+ )
531
+ return {
532
+ migrated: [],
533
+ conflicts,
534
+ changed: false,
535
+ backup: null,
536
+ diff: "",
537
+ configPath,
538
+ };
539
+
540
+ const dir = path.dirname(configPath);
541
+ const temp = path.join(
542
+ dir,
543
+ `.fx-migrate-${process.pid}-${crypto.randomBytes(4).toString("hex")}.yml`,
544
+ );
545
+ const target = dryRun ? temp : configPath;
546
+ if (dryRun) fs.writeFileSync(temp, original);
547
+
548
+ const backup = dryRun ? null : `${configPath}.bak`;
549
+ if (backup) fs.writeFileSync(backup, original);
550
+ try {
551
+ for (const [name, value] of Object.entries(moves))
552
+ setFeatureSetting(target, name, value);
553
+ for (const name of legacyCoreKeys) removeFxKey(target, name);
554
+ if (removable.length > 0) {
555
+ if (removable.length === legacyEntries.length)
556
+ removeTopLevelKey(target, "features");
557
+ else for (const name of removable) removeFeatureEntry(target, name);
558
+ }
559
+
560
+ const updated = fs.readFileSync(target, "utf8");
561
+ // Refuse to leave behind a config that the normal loader cannot read.
562
+ parseConfig(updated);
563
+ return {
564
+ migrated: [...migrated],
565
+ conflicts,
566
+ changed: true,
567
+ backup,
568
+ diff: formatDiff(original, updated, path.basename(configPath)),
569
+ configPath,
570
+ };
571
+ } catch (error) {
572
+ if (!dryRun) fs.writeFileSync(configPath, original);
573
+ throw error;
574
+ } finally {
575
+ if (dryRun) fs.rmSync(temp, { force: true });
576
+ }
577
+ }