@lbdudc/linea-core 0.1.1 → 0.2.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.
- package/README.md +132 -260
- package/dist/analysis/analyze.d.ts +0 -54
- package/dist/analysis/analyze.js +1 -70
- package/dist/analysis/analyze.js.map +1 -1
- package/dist/analysis/runtime.d.ts +4 -73
- package/dist/analysis/runtime.js +7 -100
- package/dist/analysis/runtime.js.map +1 -1
- package/dist/analysis/uvl-text.d.ts +8 -0
- package/dist/analysis/uvl-text.js +70 -0
- package/dist/analysis/uvl-text.js.map +1 -0
- package/dist/assets.d.ts +0 -12
- package/dist/assets.js +0 -25
- package/dist/assets.js.map +1 -1
- package/dist/ci/annotations.d.ts +6 -0
- package/dist/ci/annotations.js +12 -0
- package/dist/ci/annotations.js.map +1 -0
- package/dist/ci/leftovers.d.ts +25 -0
- package/dist/ci/leftovers.js +50 -0
- package/dist/ci/leftovers.js.map +1 -0
- package/dist/ci/pairwise.d.ts +11 -0
- package/dist/ci/pairwise.js +35 -0
- package/dist/ci/pairwise.js.map +1 -0
- package/dist/ci/pipeline.d.ts +18 -0
- package/dist/ci/pipeline.js +26 -0
- package/dist/ci/pipeline.js.map +1 -0
- package/dist/ci/select.d.ts +28 -0
- package/dist/ci/select.js +43 -0
- package/dist/ci/select.js.map +1 -0
- package/dist/ci/validate-specs.d.ts +52 -0
- package/dist/ci/validate-specs.js +212 -0
- package/dist/ci/validate-specs.js.map +1 -0
- package/dist/constants.d.ts +1 -60
- package/dist/constants.js +1 -58
- package/dist/constants.js.map +1 -1
- package/dist/derivation/derive.d.ts +0 -56
- package/dist/derivation/derive.js +21 -72
- package/dist/derivation/derive.js.map +1 -1
- package/dist/derivation/engine.d.ts +10 -42
- package/dist/derivation/engine.js +37 -68
- package/dist/derivation/engine.js.map +1 -1
- package/dist/derivation/selection-error.d.ts +7 -0
- package/dist/derivation/selection-error.js +13 -0
- package/dist/derivation/selection-error.js.map +1 -0
- package/dist/errors.d.ts +19 -47
- package/dist/errors.js +28 -47
- package/dist/errors.js.map +1 -1
- package/dist/feature-model/uvl.d.ts +52 -0
- package/dist/feature-model/uvl.js +191 -0
- package/dist/feature-model/uvl.js.map +1 -0
- package/dist/fs/archive.d.ts +0 -16
- package/dist/fs/archive.js +0 -36
- package/dist/fs/archive.js.map +1 -1
- package/dist/fs/diff.d.ts +0 -30
- package/dist/fs/diff.js +4 -65
- package/dist/fs/diff.js.map +1 -1
- package/dist/fs/format.d.ts +0 -16
- package/dist/fs/format.js +0 -52
- package/dist/fs/format.js.map +1 -1
- package/dist/fs/workspace.d.ts +0 -52
- package/dist/fs/workspace.js +0 -56
- package/dist/fs/workspace.js.map +1 -1
- package/dist/index.d.ts +23 -29
- package/dist/index.js +15 -35
- package/dist/index.js.map +1 -1
- package/dist/internal/guards.d.ts +0 -13
- package/dist/internal/guards.js +0 -13
- package/dist/internal/guards.js.map +1 -1
- package/dist/line/deletion.d.ts +33 -0
- package/dist/line/deletion.js +23 -0
- package/dist/line/deletion.js.map +1 -0
- package/dist/line/platform-files.d.ts +15 -64
- package/dist/line/platform-files.js +18 -94
- package/dist/line/platform-files.js.map +1 -1
- package/dist/line/restoration.d.ts +27 -0
- package/dist/line/restoration.js +27 -0
- package/dist/line/restoration.js.map +1 -0
- package/dist/line/scaffold.d.ts +26 -57
- package/dist/line/scaffold.js +32 -93
- package/dist/line/scaffold.js.map +1 -1
- package/dist/line/templates/core/transformation.js +17 -5
- package/dist/line/templates/pipeline/github-ci.yml +50 -0
- package/dist/line/templates/pipeline/spl-gitlab-ci.yml +182 -0
- package/dist/modules/configuration/configure.d.ts +52 -0
- package/dist/modules/configuration/configure.js +101 -0
- package/dist/modules/configuration/configure.js.map +1 -0
- package/dist/modules/configuration/constants.d.ts +17 -0
- package/dist/modules/configuration/constants.js +14 -0
- package/dist/modules/configuration/constants.js.map +1 -0
- package/dist/modules/configuration/index.d.ts +6 -0
- package/dist/modules/configuration/index.js +5 -0
- package/dist/modules/configuration/index.js.map +1 -0
- package/dist/modules/configuration/names.d.ts +9 -0
- package/dist/modules/configuration/names.js +7 -0
- package/dist/modules/configuration/names.js.map +1 -0
- package/dist/modules/configuration/selection.d.ts +32 -0
- package/dist/modules/configuration/selection.js +49 -0
- package/dist/modules/configuration/selection.js.map +1 -0
- package/dist/modules/diagnostics.d.ts +2 -0
- package/dist/modules/diagnostics.js +2 -0
- package/dist/modules/diagnostics.js.map +1 -0
- package/dist/modules/index.d.ts +18 -0
- package/dist/modules/index.js +18 -0
- package/dist/modules/index.js.map +1 -0
- package/dist/modules/metamodels/engine.d.ts +93 -0
- package/dist/modules/metamodels/engine.js +10 -0
- package/dist/modules/metamodels/engine.js.map +1 -0
- package/dist/modules/metamodels/files.d.ts +40 -0
- package/dist/modules/metamodels/files.js +58 -0
- package/dist/modules/metamodels/files.js.map +1 -0
- package/dist/modules/metamodels/index.d.ts +8 -0
- package/dist/modules/metamodels/index.js +5 -0
- package/dist/modules/metamodels/index.js.map +1 -0
- package/dist/modules/metamodels/layout.d.ts +23 -0
- package/dist/modules/metamodels/layout.js +29 -0
- package/dist/modules/metamodels/layout.js.map +1 -0
- package/dist/modules/metamodels/offered.d.ts +15 -0
- package/dist/modules/metamodels/offered.js +14 -0
- package/dist/modules/metamodels/offered.js.map +1 -0
- package/dist/modules/metamodels/prepare.d.ts +20 -0
- package/dist/modules/metamodels/prepare.js +155 -0
- package/dist/modules/metamodels/prepare.js.map +1 -0
- package/dist/modules/packages/index.d.ts +4 -0
- package/dist/modules/packages/index.js +4 -0
- package/dist/modules/packages/index.js.map +1 -0
- package/dist/modules/packages/location.d.ts +21 -0
- package/dist/modules/packages/location.js +34 -0
- package/dist/modules/packages/location.js.map +1 -0
- package/dist/modules/packages/manifests.d.ts +33 -0
- package/dist/modules/packages/manifests.js +231 -0
- package/dist/modules/packages/manifests.js.map +1 -0
- package/dist/modules/packages/source.d.ts +34 -0
- package/dist/modules/packages/source.js +128 -0
- package/dist/modules/packages/source.js.map +1 -0
- package/dist/modules/products/check.d.ts +28 -0
- package/dist/modules/products/check.js +61 -0
- package/dist/modules/products/check.js.map +1 -0
- package/dist/modules/products/derive.d.ts +30 -0
- package/dist/modules/products/derive.js +56 -0
- package/dist/modules/products/derive.js.map +1 -0
- package/dist/modules/products/index.d.ts +5 -0
- package/dist/modules/products/index.js +4 -0
- package/dist/modules/products/index.js.map +1 -0
- package/dist/modules/products/seed.d.ts +18 -0
- package/dist/modules/products/seed.js +23 -0
- package/dist/modules/products/seed.js.map +1 -0
- package/dist/modules/registry/catalog.d.ts +64 -0
- package/dist/modules/registry/catalog.js +91 -0
- package/dist/modules/registry/catalog.js.map +1 -0
- package/dist/modules/registry/index.d.ts +5 -0
- package/dist/modules/registry/index.js +4 -0
- package/dist/modules/registry/index.js.map +1 -0
- package/dist/modules/registry/registry.d.ts +34 -0
- package/dist/modules/registry/registry.js +37 -0
- package/dist/modules/registry/registry.js.map +1 -0
- package/dist/modules/registry/routing.d.ts +8 -0
- package/dist/modules/registry/routing.js +23 -0
- package/dist/modules/registry/routing.js.map +1 -0
- package/dist/modules/resolution/closure.d.ts +28 -0
- package/dist/modules/resolution/closure.js +105 -0
- package/dist/modules/resolution/closure.js.map +1 -0
- package/dist/modules/resolution/index.d.ts +4 -0
- package/dist/modules/resolution/index.js +3 -0
- package/dist/modules/resolution/index.js.map +1 -0
- package/dist/modules/resolution/resolve.d.ts +33 -0
- package/dist/modules/resolution/resolve.js +59 -0
- package/dist/modules/resolution/resolve.js.map +1 -0
- package/dist/modules/resolution/resolvers.d.ts +23 -0
- package/dist/modules/resolution/resolvers.js +34 -0
- package/dist/modules/resolution/resolvers.js.map +1 -0
- package/dist/modules/spl/check.d.ts +25 -0
- package/dist/modules/spl/check.js +21 -0
- package/dist/modules/spl/check.js.map +1 -0
- package/dist/modules/spl/cip.d.ts +67 -0
- package/dist/modules/spl/cip.js +98 -0
- package/dist/modules/spl/cip.js.map +1 -0
- package/dist/modules/spl/feature-model.d.ts +39 -0
- package/dist/modules/spl/feature-model.js +106 -0
- package/dist/modules/spl/feature-model.js.map +1 -0
- package/dist/modules/spl/index.d.ts +6 -0
- package/dist/modules/spl/index.js +4 -0
- package/dist/modules/spl/index.js.map +1 -0
- package/dist/modules/spl/platform.d.ts +49 -0
- package/dist/modules/spl/platform.js +316 -0
- package/dist/modules/spl/platform.js.map +1 -0
- package/dist/modules/types.d.ts +132 -0
- package/dist/modules/types.js +2 -0
- package/dist/modules/types.js.map +1 -0
- package/dist/product/engine-spec.d.ts +0 -16
- package/dist/product/engine-spec.js +4 -50
- package/dist/product/engine-spec.js.map +1 -1
- package/dist/product/spec.d.ts +0 -82
- package/dist/product/spec.js +0 -79
- package/dist/product/spec.js.map +1 -1
- package/dist/product/version.d.ts +0 -23
- package/dist/product/version.js +0 -28
- package/dist/product/version.js.map +1 -1
- package/dist/products-index/products-index.d.ts +0 -165
- package/dist/products-index/products-index.js +0 -176
- package/dist/products-index/products-index.js.map +1 -1
- package/dist/workspace/context.d.ts +25 -0
- package/dist/workspace/context.js +43 -0
- package/dist/workspace/context.js.map +1 -0
- package/dist/workspace/gitExclude.d.ts +2 -0
- package/dist/workspace/gitExclude.js +19 -0
- package/dist/workspace/gitExclude.js.map +1 -0
- package/dist/workspace/host.d.ts +14 -0
- package/dist/workspace/host.js +13 -0
- package/dist/workspace/host.js.map +1 -0
- package/dist/workspace/index.d.ts +12 -0
- package/dist/workspace/index.js +12 -0
- package/dist/workspace/index.js.map +1 -0
- package/dist/workspace/local.d.ts +81 -0
- package/dist/workspace/local.js +287 -0
- package/dist/workspace/local.js.map +1 -0
- package/dist/workspace/modular.d.ts +95 -0
- package/dist/workspace/modular.js +301 -0
- package/dist/workspace/modular.js.map +1 -0
- package/dist/workspace/operations.d.ts +35 -0
- package/dist/workspace/operations.js +57 -0
- package/dist/workspace/operations.js.map +1 -0
- package/dist/workspace/origin.d.ts +20 -0
- package/dist/workspace/origin.js +19 -0
- package/dist/workspace/origin.js.map +1 -0
- package/package.json +22 -7
- package/dist/feature-model/convert.d.ts +0 -35
- package/dist/feature-model/convert.js +0 -47
- package/dist/feature-model/convert.js.map +0 -1
- package/dist/feature-model/engine.d.ts +0 -60
- package/dist/feature-model/engine.js +0 -139
- package/dist/feature-model/engine.js.map +0 -1
- package/dist/feature-model/inspect.d.ts +0 -67
- package/dist/feature-model/inspect.js +0 -113
- package/dist/feature-model/inspect.js.map +0 -1
- package/dist/feature-model/io.d.ts +0 -66
- package/dist/feature-model/io.js +0 -92
- package/dist/feature-model/io.js.map +0 -1
- package/dist/feature-model/parse.d.ts +0 -30
- package/dist/feature-model/parse.js +0 -36
- package/dist/feature-model/parse.js.map +0 -1
- package/dist/feature-model/text.d.ts +0 -54
- package/dist/feature-model/text.js +0 -126
- package/dist/feature-model/text.js.map +0 -1
- package/dist/line/templates/metamodels/dataModel/extra.js +0 -328
- package/dist/line/templates/metamodels/dataModel/transformation.js +0 -211
- package/dist/line/templates/metamodels/sensor/extra.js +0 -36
- package/dist/line/templates/metamodels/sensor/transformation.js +0 -47
- package/dist/selection/selection.d.ts +0 -126
- package/dist/selection/selection.js +0 -152
- package/dist/selection/selection.js.map +0 -1
package/dist/analysis/analyze.js
CHANGED
|
@@ -1,27 +1,12 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Feature model analysis (ADR-008, ADR-021).
|
|
3
|
-
*
|
|
4
|
-
* Migrated from `linea/flamapy-server/main.py`: `/analyze` (~215-270),
|
|
5
|
-
* `/analyze/bdd` (~273-340) and `/analyze/metric` (~340-367). The RESPONSE SHAPE
|
|
6
|
-
* is contractual — webui and linea-cli already consume these exact keys — so it
|
|
7
|
-
* is reproduced field for field, including the `_`-prefixed metadata.
|
|
8
|
-
*
|
|
9
|
-
* The `safe()` pattern of `main.py:105-117` is preserved: an operation that
|
|
10
|
-
* fails yields `null` in its own field and never aborts the whole response. A
|
|
11
|
-
* partially analysable model still returns everything it could compute.
|
|
12
|
-
*/
|
|
13
1
|
import { ANALYSIS_THRESHOLDS } from '../constants.js';
|
|
14
2
|
import { InvalidArgumentError } from '../errors.js';
|
|
15
|
-
import { estimateFeatureCount, normalizeUvl } from '
|
|
3
|
+
import { estimateFeatureCount, normalizeUvl } from './uvl-text.js';
|
|
16
4
|
import { createAnalysisRuntime, disposeAnalysisRuntime, runOperation, useRuntime } from './runtime.js';
|
|
17
|
-
/** Metrics `analyzeMetric` accepts, matching the `match` arms of `main.py`. */
|
|
18
5
|
export const ANALYSIS_METRICS = ['satisfiable', 'deadFeatures', 'falseOptionalFeatures'];
|
|
19
|
-
/** BDD fields, in the order `main.py` lists them. */
|
|
20
6
|
const BDD_FIELDS = [
|
|
21
7
|
'configsNumber', 'configDistribution', 'featureInclusionProb',
|
|
22
8
|
'homogeneity', 'variability', 'uniqueFeatures', 'variantFeatures'
|
|
23
9
|
];
|
|
24
|
-
/** Verbatim from `main.py`'s `/analyze`. */
|
|
25
10
|
const modelSizeOf = (featureCount) => {
|
|
26
11
|
if (featureCount < 50)
|
|
27
12
|
return 'small';
|
|
@@ -31,10 +16,6 @@ const modelSizeOf = (featureCount) => {
|
|
|
31
16
|
return 'large';
|
|
32
17
|
return 'very_large';
|
|
33
18
|
};
|
|
34
|
-
/**
|
|
35
|
-
* Normalises and sanity-checks the input, mirroring every endpoint's preamble.
|
|
36
|
-
* `main.py` answers HTTP 400 when the document does not start with `features`.
|
|
37
|
-
*/
|
|
38
19
|
const prepareUvl = (uvl) => {
|
|
39
20
|
if (typeof uvl !== 'string') {
|
|
40
21
|
throw new InvalidArgumentError('"uvl" must be a string.');
|
|
@@ -54,10 +35,6 @@ const assertMode = (mode) => {
|
|
|
54
35
|
}
|
|
55
36
|
return mode;
|
|
56
37
|
};
|
|
57
|
-
/**
|
|
58
|
-
* `main.py:safe()` — run an operation, and on failure record `null` instead of
|
|
59
|
-
* letting one broken metric take the whole response down.
|
|
60
|
-
*/
|
|
61
38
|
const safe = async (run) => {
|
|
62
39
|
try {
|
|
63
40
|
return await run();
|
|
@@ -66,12 +43,9 @@ const safe = async (run) => {
|
|
|
66
43
|
return null;
|
|
67
44
|
}
|
|
68
45
|
};
|
|
69
|
-
/** Runs `body` with a runtime, creating and disposing a private one if needed. */
|
|
70
46
|
const withRuntime = async (runtime, body) => {
|
|
71
47
|
if (runtime !== undefined)
|
|
72
48
|
return await body(runtime);
|
|
73
|
-
// Bootstrapping costs ~2.3 s; callers running more than one analysis should
|
|
74
|
-
// create a runtime once and pass it in.
|
|
75
49
|
const owned = await createAnalysisRuntime();
|
|
76
50
|
try {
|
|
77
51
|
return await body(owned);
|
|
@@ -80,21 +54,6 @@ const withRuntime = async (runtime, body) => {
|
|
|
80
54
|
disposeAnalysisRuntime({ runtime: owned });
|
|
81
55
|
}
|
|
82
56
|
};
|
|
83
|
-
/**
|
|
84
|
-
* Fast analysis: structural metrics plus the SAT group.
|
|
85
|
-
*
|
|
86
|
-
* PARITY QUIRK: `mode` does NOT change what is computed. `main.py` always runs
|
|
87
|
-
* the PySAT operations here and only echoes the requested mode back in
|
|
88
|
-
* `_solveMode`; the BDD group lives in `analyzeFeatureModelBdd`. Reproduced as
|
|
89
|
-
* is, because webui reads `_solveMode` to label the result.
|
|
90
|
-
*
|
|
91
|
-
* @param params.uvl UVL document. Normalised internally.
|
|
92
|
-
* @param params.mode Solver to report. Defaults to `'BDD'`.
|
|
93
|
-
* @param params.runtime Optional runtime to reuse.
|
|
94
|
-
* @returns Every field of `main.py`'s `/analyze`. Individual failures are `null`.
|
|
95
|
-
* @throws {InvalidArgumentError} for a non-string or non-`features` document.
|
|
96
|
-
* @throws {AnalysisRuntimeError} if the runtime cannot start or was disposed.
|
|
97
|
-
*/
|
|
98
57
|
export const analyzeFeatureModel = async ({ uvl, mode, runtime }) => {
|
|
99
58
|
const document = prepareUvl(uvl);
|
|
100
59
|
const solveMode = assertMode(mode);
|
|
@@ -123,20 +82,6 @@ export const analyzeFeatureModel = async ({ uvl, mode, runtime }) => {
|
|
|
123
82
|
};
|
|
124
83
|
});
|
|
125
84
|
};
|
|
126
|
-
/**
|
|
127
|
-
* Slow analysis: the BDD group plus full configuration enumeration.
|
|
128
|
-
*
|
|
129
|
-
* Both are exponential, so `ANALYSIS_THRESHOLDS` gates them exactly as `main.py`
|
|
130
|
-
* does with `SKIP_BDD` and `SKIP_ENUM`:
|
|
131
|
-
* - at or above 100 features, every field is `null` and all eight names land in
|
|
132
|
-
* `_skipped` — the runtime is not even touched;
|
|
133
|
-
* - above 30 features, `configurations` alone is skipped.
|
|
134
|
-
*
|
|
135
|
-
* @param params.uvl UVL document.
|
|
136
|
-
* @param params.runtime Optional runtime to reuse.
|
|
137
|
-
* @returns Every field of `main.py`'s `/analyze/bdd`.
|
|
138
|
-
* @throws {InvalidArgumentError} for a non-string or non-`features` document.
|
|
139
|
-
*/
|
|
140
85
|
export const analyzeFeatureModelBdd = async ({ uvl, runtime }) => {
|
|
141
86
|
const document = prepareUvl(uvl);
|
|
142
87
|
const started = Date.now();
|
|
@@ -181,20 +126,6 @@ export const analyzeFeatureModelBdd = async ({ uvl, runtime }) => {
|
|
|
181
126
|
};
|
|
182
127
|
});
|
|
183
128
|
};
|
|
184
|
-
/**
|
|
185
|
-
* Computes a single metric.
|
|
186
|
-
*
|
|
187
|
-
* Mirrors the `match` of `main.py`'s `/analyze/metric`, including which solver
|
|
188
|
-
* each arm uses: only `satisfiable` honours `mode` (PySAT or BDD); the other two
|
|
189
|
-
* are PySAT-only and always report `_solveMode: 'SAT'`.
|
|
190
|
-
*
|
|
191
|
-
* @param params.uvl UVL document.
|
|
192
|
-
* @param params.metric One of `ANALYSIS_METRICS`.
|
|
193
|
-
* @param params.mode Solver, only meaningful for `satisfiable`. Defaults to `'BDD'`.
|
|
194
|
-
* @param params.runtime Optional runtime to reuse.
|
|
195
|
-
* @returns The metric plus the solver actually used.
|
|
196
|
-
* @throws {InvalidArgumentError} for an unknown metric or a malformed document.
|
|
197
|
-
*/
|
|
198
129
|
export const analyzeMetric = async ({ uvl, metric, mode, runtime }) => {
|
|
199
130
|
const document = prepareUvl(uvl);
|
|
200
131
|
const requestedMode = assertMode(mode);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analyze.js","sourceRoot":"","sources":["../../src/analysis/analyze.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAA;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AACnD,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAC7E,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,YAAY,EACZ,UAAU,EAEX,MAAM,cAAc,CAAA;AAKrB,+EAA+E;AAC/E,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,aAAa,EAAE,cAAc,EAAE,uBAAuB,CAAU,CAAA;AA8CjG,qDAAqD;AACrD,MAAM,UAAU,GAAG;IACjB,eAAe,EAAE,oBAAoB,EAAE,sBAAsB;IAC7D,aAAa,EAAE,aAAa,EAAE,gBAAgB,EAAE,iBAAiB;CACzD,CAAA;AAEV,4CAA4C;AAC5C,MAAM,WAAW,GAAG,CAAC,YAAoB,EAAU,EAAE;IACnD,IAAI,YAAY,GAAG,EAAE;QAAE,OAAO,OAAO,CAAA;IACrC,IAAI,YAAY,GAAG,GAAG;QAAE,OAAO,QAAQ,CAAA;IACvC,IAAI,YAAY,GAAG,GAAG;QAAE,OAAO,OAAO,CAAA;IACtC,OAAO,YAAY,CAAA;AACrB,CAAC,CAAA;AAED;;;GAGG;AACH,MAAM,UAAU,GAAG,CAAC,GAAY,EAAU,EAAE;IAC1C,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC5B,MAAM,IAAI,oBAAoB,CAAC,yBAAyB,CAAC,CAAA;IAC3D,CAAC;IACD,MAAM,UAAU,GAAG,YAAY,CAAC,EAAE,GAAG,EAAE,CAAC,CAAA;IACxC,IAAI,CAAC,UAAU,CAAC,UAAU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AAa,GAAG,UAAU,CAAC,IAAI,CAAC,CAAA;IACtC,IAAI,CAAE,gBAAsC,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QAC9D,MAAM,IAAI,oBAAoB,CAC5B,kBAAkB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,gBAAgB,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CACvF,CAAA;IACH,CAAC;IAED,OAAO,MAAM,WAAW,CAAC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE;QACnD,MAAM,KAAK,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAA;QAElC,IAAI,MAAM,KAAK,aAAa,EAAE,CAAC;YAC7B,MAAM,MAAM,GAAG,aAAa,KAAK,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAA;YACxD,OAAO;gBACL,WAAW,EAAE,MAAM,IAAI,CAAC,KAAK,IAAI,EAAE,CACjC,MAAM,YAAY,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;gBAC7D,UAAU,EAAE,aAAa;aAC1B,CAAA;QACH,CAAC;QAED,MAAM,SAAS,GAAG,MAAM,KAAK,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,uBAAuB,CAAA;QACtF,OAAO;YACL,CAAC,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC,KAAK,IAAI,EAAE,CAC9B,MAAM,YAAY,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;YAC1D,UAAU,EAAE,KAAc;SAC3B,CAAA;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA","sourcesContent":["/**\n * Feature model analysis (ADR-008, ADR-021).\n *\n * Migrated from `linea/flamapy-server/main.py`: `/analyze` (~215-270),\n * `/analyze/bdd` (~273-340) and `/analyze/metric` (~340-367). The RESPONSE SHAPE\n * is contractual — webui and linea-cli already consume these exact keys — so it\n * is reproduced field for field, including the `_`-prefixed metadata.\n *\n * The `safe()` pattern of `main.py:105-117` is preserved: an operation that\n * fails yields `null` in its own field and never aborts the whole response. A\n * partially analysable model still returns everything it could compute.\n */\nimport { ANALYSIS_THRESHOLDS } from '../constants.js'\nimport { InvalidArgumentError } from '../errors.js'\nimport { estimateFeatureCount, normalizeUvl } from '../feature-model/text.js'\nimport {\n createAnalysisRuntime,\n disposeAnalysisRuntime,\n runOperation,\n useRuntime,\n type AnalysisRuntime\n} from './runtime.js'\n\n/** Solver requested by the caller. */\nexport type AnalysisMode = 'SAT' | 'BDD'\n\n/** Metrics `analyzeMetric` accepts, matching the `match` arms of `main.py`. */\nexport const ANALYSIS_METRICS = ['satisfiable', 'deadFeatures', 'falseOptionalFeatures'] as const\n\n/** A metric name accepted by `analyzeMetric`. */\nexport type AnalysisMetric = (typeof ANALYSIS_METRICS)[number]\n\n/** Structural + SAT analysis, the fast path. */\nexport interface FeatureModelAnalysis {\n coreFeatures: unknown\n averageBranchingFactor: unknown\n maxDepth: unknown\n estimatedConfigurations: unknown\n leafNumber: unknown\n leafFeatures: unknown\n atomicSets: unknown\n satisfiable: unknown\n deadFeatures: unknown\n falseOptionalFeatures: unknown\n /** Features counted by `estimateFeatureCount` over the normalised document. */\n _featureCount: number\n /** `'small' | 'medium' | 'large' | 'very_large'`, thresholds from `main.py`. */\n _modelSize: string\n /** Echo of the requested mode. */\n _solveMode: AnalysisMode\n /** Always `[]` here: the fast path skips nothing. */\n _skipped: string[]\n _elapsedMs: number\n}\n\n/** BDD + enumeration analysis, the slow path. */\nexport interface FeatureModelBddAnalysis {\n configurations: unknown\n configsNumber: unknown\n configDistribution: unknown\n featureInclusionProb: unknown\n homogeneity: unknown\n variability: unknown\n uniqueFeatures: unknown\n variantFeatures: unknown\n /** Fields deliberately not computed because the model is too large. */\n _skipped: string[]\n _elapsedMs: number\n}\n\n/** Result of `analyzeMetric`: the requested metric plus the solver used. */\nexport type MetricAnalysis = Partial<Record<AnalysisMetric, unknown>> & { _solveMode: AnalysisMode }\n\n/** BDD fields, in the order `main.py` lists them. */\nconst BDD_FIELDS = [\n 'configsNumber', 'configDistribution', 'featureInclusionProb',\n 'homogeneity', 'variability', 'uniqueFeatures', 'variantFeatures'\n] as const\n\n/** Verbatim from `main.py`'s `/analyze`. */\nconst modelSizeOf = (featureCount: number): string => {\n if (featureCount < 50) return 'small'\n if (featureCount < 100) return 'medium'\n if (featureCount < 250) return 'large'\n return 'very_large'\n}\n\n/**\n * Normalises and sanity-checks the input, mirroring every endpoint's preamble.\n * `main.py` answers HTTP 400 when the document does not start with `features`.\n */\nconst prepareUvl = (uvl: unknown): string => {\n if (typeof uvl !== 'string') {\n throw new InvalidArgumentError('\"uvl\" must be a string.')\n }\n const normalised = normalizeUvl({ uvl })\n if (!normalised.startsWith('features')) {\n throw new InvalidArgumentError(\n 'The UVL document must start with \"features\". Got: ' +\n `${JSON.stringify(normalised.slice(0, 40))}`\n )\n }\n return normalised\n}\n\nconst assertMode = (mode: unknown): AnalysisMode => {\n if (mode === undefined) return 'BDD'\n if (mode !== 'SAT' && mode !== 'BDD') {\n throw new InvalidArgumentError(`\"mode\" must be \"SAT\" or \"BDD\", got ${JSON.stringify(mode)}.`)\n }\n return mode\n}\n\n/**\n * `main.py:safe()` — run an operation, and on failure record `null` instead of\n * letting one broken metric take the whole response down.\n */\nconst safe = async (run: () => Promise<unknown>): Promise<unknown> => {\n try {\n return await run()\n } catch {\n return null\n }\n}\n\n/** Runs `body` with a runtime, creating and disposing a private one if needed. */\nconst withRuntime = async <T>(\n runtime: AnalysisRuntime | undefined,\n body: (provided: AnalysisRuntime) => Promise<T>\n): Promise<T> => {\n if (runtime !== undefined) return await body(runtime)\n // Bootstrapping costs ~2.3 s; callers running more than one analysis should\n // create a runtime once and pass it in.\n const owned = await createAnalysisRuntime()\n try {\n return await body(owned)\n } finally {\n disposeAnalysisRuntime({ runtime: owned })\n }\n}\n\n/**\n * Fast analysis: structural metrics plus the SAT group.\n *\n * PARITY QUIRK: `mode` does NOT change what is computed. `main.py` always runs\n * the PySAT operations here and only echoes the requested mode back in\n * `_solveMode`; the BDD group lives in `analyzeFeatureModelBdd`. Reproduced as\n * is, because webui reads `_solveMode` to label the result.\n *\n * @param params.uvl UVL document. Normalised internally.\n * @param params.mode Solver to report. Defaults to `'BDD'`.\n * @param params.runtime Optional runtime to reuse.\n * @returns Every field of `main.py`'s `/analyze`. Individual failures are `null`.\n * @throws {InvalidArgumentError} for a non-string or non-`features` document.\n * @throws {AnalysisRuntimeError} if the runtime cannot start or was disposed.\n */\nexport const analyzeFeatureModel = async ({\n uvl,\n mode,\n runtime\n}: {\n uvl: string\n mode?: AnalysisMode\n runtime?: AnalysisRuntime\n}): Promise<FeatureModelAnalysis> => {\n const document = prepareUvl(uvl)\n const solveMode = assertMode(mode)\n const started = Date.now()\n const featureCount = estimateFeatureCount({ uvl: document })\n\n return await withRuntime(runtime, async (provided) => {\n const state = useRuntime(provided)\n const basic = async (operation: string): Promise<unknown> =>\n await safe(async () => await runOperation(state, operation, document, 'basic'))\n const pysat = async (operation: string): Promise<unknown> =>\n await safe(async () => await runOperation(state, operation, document, 'pysat'))\n\n return {\n coreFeatures: await basic('core_features'),\n averageBranchingFactor: await basic('average_branching_factor'),\n maxDepth: await basic('max_depth'),\n estimatedConfigurations: await basic('estimated_number_of_configurations'),\n leafNumber: await basic('count_leafs'),\n leafFeatures: await basic('leaf_features'),\n atomicSets: await basic('atomic_sets'),\n satisfiable: await pysat('Satisfiable'),\n deadFeatures: await pysat('DeadFeatures'),\n falseOptionalFeatures: await pysat('FalseOptionalFeatures'),\n _featureCount: featureCount,\n _modelSize: modelSizeOf(featureCount),\n _solveMode: solveMode,\n _skipped: [],\n _elapsedMs: Date.now() - started\n }\n })\n}\n\n/**\n * Slow analysis: the BDD group plus full configuration enumeration.\n *\n * Both are exponential, so `ANALYSIS_THRESHOLDS` gates them exactly as `main.py`\n * does with `SKIP_BDD` and `SKIP_ENUM`:\n * - at or above 100 features, every field is `null` and all eight names land in\n * `_skipped` — the runtime is not even touched;\n * - above 30 features, `configurations` alone is skipped.\n *\n * @param params.uvl UVL document.\n * @param params.runtime Optional runtime to reuse.\n * @returns Every field of `main.py`'s `/analyze/bdd`.\n * @throws {InvalidArgumentError} for a non-string or non-`features` document.\n */\nexport const analyzeFeatureModelBdd = async ({\n uvl,\n runtime\n}: {\n uvl: string\n runtime?: AnalysisRuntime\n}): Promise<FeatureModelBddAnalysis> => {\n const document = prepareUvl(uvl)\n const started = Date.now()\n const featureCount = estimateFeatureCount({ uvl: document })\n const skipped: string[] = []\n\n if (featureCount >= ANALYSIS_THRESHOLDS.skipBdd) {\n skipped.push('configurations', ...BDD_FIELDS)\n return {\n configurations: null,\n configsNumber: null,\n configDistribution: null,\n featureInclusionProb: null,\n homogeneity: null,\n variability: null,\n uniqueFeatures: null,\n variantFeatures: null,\n _skipped: skipped,\n _elapsedMs: Date.now() - started\n }\n }\n\n return await withRuntime(runtime, async (provided) => {\n const state = useRuntime(provided)\n\n let configurations: unknown = null\n if (featureCount <= ANALYSIS_THRESHOLDS.skipEnumeration) {\n configurations = await safe(async () =>\n await runOperation(state, 'configurations', document, 'basic'))\n } else {\n skipped.push('configurations')\n }\n\n const bdd = async (operation: string): Promise<unknown> =>\n await safe(async () => await runOperation(state, operation, document, 'bdd'))\n\n return {\n configurations,\n configsNumber: await bdd('ConfigurationsNumber'),\n configDistribution: await bdd('ProductDistribution'),\n featureInclusionProb: await bdd('FeatureInclusionProbability'),\n homogeneity: await bdd('Homogeneity'),\n variability: await bdd('Variability'),\n uniqueFeatures: await bdd('UniqueFeatures'),\n variantFeatures: await bdd('VariantFeatures'),\n _skipped: skipped,\n _elapsedMs: Date.now() - started\n }\n })\n}\n\n/**\n * Computes a single metric.\n *\n * Mirrors the `match` of `main.py`'s `/analyze/metric`, including which solver\n * each arm uses: only `satisfiable` honours `mode` (PySAT or BDD); the other two\n * are PySAT-only and always report `_solveMode: 'SAT'`.\n *\n * @param params.uvl UVL document.\n * @param params.metric One of `ANALYSIS_METRICS`.\n * @param params.mode Solver, only meaningful for `satisfiable`. Defaults to `'BDD'`.\n * @param params.runtime Optional runtime to reuse.\n * @returns The metric plus the solver actually used.\n * @throws {InvalidArgumentError} for an unknown metric or a malformed document.\n */\nexport const analyzeMetric = async ({\n uvl,\n metric,\n mode,\n runtime\n}: {\n uvl: string\n metric: AnalysisMetric\n mode?: AnalysisMode\n runtime?: AnalysisRuntime\n}): Promise<MetricAnalysis> => {\n const document = prepareUvl(uvl)\n const requestedMode = assertMode(mode)\n if (!(ANALYSIS_METRICS as readonly string[]).includes(metric)) {\n throw new InvalidArgumentError(\n `Unknown metric ${JSON.stringify(metric)}. Supported: ${ANALYSIS_METRICS.join(', ')}.`\n )\n }\n\n return await withRuntime(runtime, async (provided) => {\n const state = useRuntime(provided)\n\n if (metric === 'satisfiable') {\n const solver = requestedMode === 'SAT' ? 'pysat' : 'bdd'\n return {\n satisfiable: await safe(async () =>\n await runOperation(state, 'Satisfiable', document, solver)),\n _solveMode: requestedMode\n }\n }\n\n const operation = metric === 'deadFeatures' ? 'DeadFeatures' : 'FalseOptionalFeatures'\n return {\n [metric]: await safe(async () =>\n await runOperation(state, operation, document, 'pysat')),\n _solveMode: 'SAT' as const\n }\n })\n}\n"]}
|
|
1
|
+
{"version":3,"file":"analyze.js","sourceRoot":"","sources":["../../src/analysis/analyze.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAA;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AACnD,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAClE,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,YAAY,EACZ,UAAU,EAEX,MAAM,cAAc,CAAA;AAIrB,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,aAAa,EAAE,cAAc,EAAE,uBAAuB,CAAU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AC1B,CAAA;QACH,CAAC;QAED,MAAM,SAAS,GAAG,MAAM,KAAK,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,uBAAuB,CAAA;QACtF,OAAO;YACL,CAAC,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC,KAAK,IAAI,EAAE,CAC9B,MAAM,YAAY,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;YAC1D,UAAU,EAAE,KAAc;SAC3B,CAAA;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA","sourcesContent":["import { ANALYSIS_THRESHOLDS } from '../constants.js'\nimport { InvalidArgumentError } from '../errors.js'\nimport { estimateFeatureCount, normalizeUvl } from './uvl-text.js'\nimport {\n createAnalysisRuntime,\n disposeAnalysisRuntime,\n runOperation,\n useRuntime,\n type AnalysisRuntime\n} from './runtime.js'\n\nexport type AnalysisMode = 'SAT' | 'BDD'\n\nexport const ANALYSIS_METRICS = ['satisfiable', 'deadFeatures', 'falseOptionalFeatures'] as const\n\nexport type AnalysisMetric = (typeof ANALYSIS_METRICS)[number]\n\nexport interface FeatureModelAnalysis {\n coreFeatures: unknown\n averageBranchingFactor: unknown\n maxDepth: unknown\n estimatedConfigurations: unknown\n leafNumber: unknown\n leafFeatures: unknown\n atomicSets: unknown\n satisfiable: unknown\n deadFeatures: unknown\n falseOptionalFeatures: unknown\n _featureCount: number\n _modelSize: string\n _solveMode: AnalysisMode\n _skipped: string[]\n _elapsedMs: number\n}\n\nexport interface FeatureModelBddAnalysis {\n configurations: unknown\n configsNumber: unknown\n configDistribution: unknown\n featureInclusionProb: unknown\n homogeneity: unknown\n variability: unknown\n uniqueFeatures: unknown\n variantFeatures: unknown\n _skipped: string[]\n _elapsedMs: number\n}\n\nexport type MetricAnalysis = Partial<Record<AnalysisMetric, unknown>> & { _solveMode: AnalysisMode }\n\nconst BDD_FIELDS = [\n 'configsNumber', 'configDistribution', 'featureInclusionProb',\n 'homogeneity', 'variability', 'uniqueFeatures', 'variantFeatures'\n] as const\n\nconst modelSizeOf = (featureCount: number): string => {\n if (featureCount < 50) return 'small'\n if (featureCount < 100) return 'medium'\n if (featureCount < 250) return 'large'\n return 'very_large'\n}\n\nconst prepareUvl = (uvl: unknown): string => {\n if (typeof uvl !== 'string') {\n throw new InvalidArgumentError('\"uvl\" must be a string.')\n }\n const normalised = normalizeUvl({ uvl })\n if (!normalised.startsWith('features')) {\n throw new InvalidArgumentError(\n 'The UVL document must start with \"features\". Got: ' +\n `${JSON.stringify(normalised.slice(0, 40))}`\n )\n }\n return normalised\n}\n\nconst assertMode = (mode: unknown): AnalysisMode => {\n if (mode === undefined) return 'BDD'\n if (mode !== 'SAT' && mode !== 'BDD') {\n throw new InvalidArgumentError(`\"mode\" must be \"SAT\" or \"BDD\", got ${JSON.stringify(mode)}.`)\n }\n return mode\n}\n\nconst safe = async (run: () => Promise<unknown>): Promise<unknown> => {\n try {\n return await run()\n } catch {\n return null\n }\n}\n\nconst withRuntime = async <T>(\n runtime: AnalysisRuntime | undefined,\n body: (provided: AnalysisRuntime) => Promise<T>\n): Promise<T> => {\n if (runtime !== undefined) return await body(runtime)\n const owned = await createAnalysisRuntime()\n try {\n return await body(owned)\n } finally {\n disposeAnalysisRuntime({ runtime: owned })\n }\n}\n\nexport const analyzeFeatureModel = async ({\n uvl,\n mode,\n runtime\n}: {\n uvl: string\n mode?: AnalysisMode\n runtime?: AnalysisRuntime\n}): Promise<FeatureModelAnalysis> => {\n const document = prepareUvl(uvl)\n const solveMode = assertMode(mode)\n const started = Date.now()\n const featureCount = estimateFeatureCount({ uvl: document })\n\n return await withRuntime(runtime, async (provided) => {\n const state = useRuntime(provided)\n const basic = async (operation: string): Promise<unknown> =>\n await safe(async () => await runOperation(state, operation, document, 'basic'))\n const pysat = async (operation: string): Promise<unknown> =>\n await safe(async () => await runOperation(state, operation, document, 'pysat'))\n\n return {\n coreFeatures: await basic('core_features'),\n averageBranchingFactor: await basic('average_branching_factor'),\n maxDepth: await basic('max_depth'),\n estimatedConfigurations: await basic('estimated_number_of_configurations'),\n leafNumber: await basic('count_leafs'),\n leafFeatures: await basic('leaf_features'),\n atomicSets: await basic('atomic_sets'),\n satisfiable: await pysat('Satisfiable'),\n deadFeatures: await pysat('DeadFeatures'),\n falseOptionalFeatures: await pysat('FalseOptionalFeatures'),\n _featureCount: featureCount,\n _modelSize: modelSizeOf(featureCount),\n _solveMode: solveMode,\n _skipped: [],\n _elapsedMs: Date.now() - started\n }\n })\n}\n\nexport const analyzeFeatureModelBdd = async ({\n uvl,\n runtime\n}: {\n uvl: string\n runtime?: AnalysisRuntime\n}): Promise<FeatureModelBddAnalysis> => {\n const document = prepareUvl(uvl)\n const started = Date.now()\n const featureCount = estimateFeatureCount({ uvl: document })\n const skipped: string[] = []\n\n if (featureCount >= ANALYSIS_THRESHOLDS.skipBdd) {\n skipped.push('configurations', ...BDD_FIELDS)\n return {\n configurations: null,\n configsNumber: null,\n configDistribution: null,\n featureInclusionProb: null,\n homogeneity: null,\n variability: null,\n uniqueFeatures: null,\n variantFeatures: null,\n _skipped: skipped,\n _elapsedMs: Date.now() - started\n }\n }\n\n return await withRuntime(runtime, async (provided) => {\n const state = useRuntime(provided)\n\n let configurations: unknown = null\n if (featureCount <= ANALYSIS_THRESHOLDS.skipEnumeration) {\n configurations = await safe(async () =>\n await runOperation(state, 'configurations', document, 'basic'))\n } else {\n skipped.push('configurations')\n }\n\n const bdd = async (operation: string): Promise<unknown> =>\n await safe(async () => await runOperation(state, operation, document, 'bdd'))\n\n return {\n configurations,\n configsNumber: await bdd('ConfigurationsNumber'),\n configDistribution: await bdd('ProductDistribution'),\n featureInclusionProb: await bdd('FeatureInclusionProbability'),\n homogeneity: await bdd('Homogeneity'),\n variability: await bdd('Variability'),\n uniqueFeatures: await bdd('UniqueFeatures'),\n variantFeatures: await bdd('VariantFeatures'),\n _skipped: skipped,\n _elapsedMs: Date.now() - started\n }\n })\n}\n\nexport const analyzeMetric = async ({\n uvl,\n metric,\n mode,\n runtime\n}: {\n uvl: string\n metric: AnalysisMetric\n mode?: AnalysisMode\n runtime?: AnalysisRuntime\n}): Promise<MetricAnalysis> => {\n const document = prepareUvl(uvl)\n const requestedMode = assertMode(mode)\n if (!(ANALYSIS_METRICS as readonly string[]).includes(metric)) {\n throw new InvalidArgumentError(\n `Unknown metric ${JSON.stringify(metric)}. Supported: ${ANALYSIS_METRICS.join(', ')}.`\n )\n }\n\n return await withRuntime(runtime, async (provided) => {\n const state = useRuntime(provided)\n\n if (metric === 'satisfiable') {\n const solver = requestedMode === 'SAT' ? 'pysat' : 'bdd'\n return {\n satisfiable: await safe(async () =>\n await runOperation(state, 'Satisfiable', document, solver)),\n _solveMode: requestedMode\n }\n }\n\n const operation = metric === 'deadFeatures' ? 'DeadFeatures' : 'FalseOptionalFeatures'\n return {\n [metric]: await safe(async () =>\n await runOperation(state, operation, document, 'pysat')),\n _solveMode: 'SAT' as const\n }\n })\n}\n"]}
|
|
@@ -1,97 +1,28 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* How flamapy is asked to solve an operation.
|
|
3
|
-
*
|
|
4
|
-
* Declared locally instead of importing `TypeSolving` from
|
|
5
|
-
* `@lbdudc/flamapy.js`, and `PyodideHandle` below instead of pyodide's
|
|
6
|
-
* `PyodideInterface`, for the reason stated in `feature-model/engine.ts`: no
|
|
7
|
-
* `.d.ts` emitted into `dist/` may reference a dependency that ships no types.
|
|
8
|
-
* `RuntimeState` is reachable from the public `AnalysisRuntime`, so a
|
|
9
|
-
* third-party type in its shape leaks into the published declarations and
|
|
10
|
-
* breaks every consumer compiling with `skipLibCheck: false` — which is exactly
|
|
11
|
-
* how linea-server and linea-cli are meant to build. Verified by
|
|
12
|
-
* `npm run check:consumer`.
|
|
13
|
-
*/
|
|
14
1
|
type SolvingType = 'basic' | 'pysat' | 'pysat_diagnosis' | 'bdd';
|
|
15
|
-
/** The slice of pyodide's interface this module actually uses. */
|
|
16
2
|
interface PyodideHandle {
|
|
17
3
|
FS: unknown;
|
|
18
4
|
runPythonAsync: (code: string) => Promise<unknown>;
|
|
19
|
-
loadPackage: (names: string | string[]
|
|
5
|
+
loadPackage: (names: string | string[], options?: {
|
|
6
|
+
messageCallback?: (m: string) => void;
|
|
7
|
+
errorCallback?: (m: string) => void;
|
|
8
|
+
}) => Promise<unknown>;
|
|
20
9
|
}
|
|
21
10
|
declare const analysisRuntimeBrand: unique symbol;
|
|
22
|
-
/**
|
|
23
|
-
* An initialised analysis runtime.
|
|
24
|
-
*
|
|
25
|
-
* Opaque: it wraps a Pyodide instance plus the queue that serialises operations
|
|
26
|
-
* on it. Create it with `createAnalysisRuntime`, pass it to the analysis
|
|
27
|
-
* functions, and release it with `disposeAnalysisRuntime`.
|
|
28
|
-
*/
|
|
29
11
|
export interface AnalysisRuntime {
|
|
30
12
|
readonly [analysisRuntimeBrand]: 'linea-core/AnalysisRuntime';
|
|
31
13
|
}
|
|
32
14
|
interface RuntimeState {
|
|
33
15
|
pyodide: PyodideHandle;
|
|
34
|
-
/**
|
|
35
|
-
* Tail of the serialisation chain.
|
|
36
|
-
*
|
|
37
|
-
* flamapy writes the model to a FIXED path (`uvlfile.uvl`) inside Pyodide's
|
|
38
|
-
* virtual filesystem, so two concurrent operations on the same interpreter
|
|
39
|
-
* would overwrite each other's input. Every operation queues behind the
|
|
40
|
-
* previous one. The queue is per-runtime, never per-module.
|
|
41
|
-
*/
|
|
42
16
|
queue: Promise<void>;
|
|
43
17
|
disposed: boolean;
|
|
44
18
|
}
|
|
45
|
-
/** Options for `createAnalysisRuntime`. */
|
|
46
19
|
export interface AnalysisRuntimeOptions {
|
|
47
|
-
/**
|
|
48
|
-
* Override the directory pyodide loads `micropip`/`packaging` from. Defaults
|
|
49
|
-
* to the wheels vendored inside this package; only useful for testing.
|
|
50
|
-
*/
|
|
51
20
|
wheelsDir?: string;
|
|
52
21
|
}
|
|
53
|
-
/**
|
|
54
|
-
* Brings up a Pyodide interpreter with flamapy installed.
|
|
55
|
-
*
|
|
56
|
-
* Costs roughly 2.3 s, so a caller running several analyses should create ONE
|
|
57
|
-
* runtime and reuse it. Everything is read from disk: no network, ever.
|
|
58
|
-
*
|
|
59
|
-
* Before returning, a canary operation is run. If it fails — or comes back
|
|
60
|
-
* `undefined`, which is exactly what a silently broken bootstrap produces — this
|
|
61
|
-
* throws instead of handing out a runtime that would report empty metrics
|
|
62
|
-
* (ADR-021).
|
|
63
|
-
*
|
|
64
|
-
* @param options.wheelsDir Optional override of the vendored wheels directory.
|
|
65
|
-
* @returns An initialised runtime handle, owned by the caller.
|
|
66
|
-
* @throws {AnalysisRuntimeError} when the bootstrap or the canary fails.
|
|
67
|
-
*/
|
|
68
22
|
export declare const createAnalysisRuntime: ({ wheelsDir }?: AnalysisRuntimeOptions) => Promise<AnalysisRuntime>;
|
|
69
|
-
/**
|
|
70
|
-
* Retires a runtime handle.
|
|
71
|
-
*
|
|
72
|
-
* IT DOES NOT FREE MEMORY, and callers must plan around that. Pyodide exposes no
|
|
73
|
-
* teardown, so the ~180 MB WASM heap an interpreter holds stays allocated for
|
|
74
|
-
* the life of the process; all this does is mark the handle unusable so later
|
|
75
|
-
* analyses fail loudly instead of running on a half-torn-down interpreter.
|
|
76
|
-
*
|
|
77
|
-
* The practical consequence for linea-server: do NOT create a runtime per
|
|
78
|
-
* request. Create a small, long-lived set of them and reuse. Creating and
|
|
79
|
-
* disposing per request leaks an interpreter's worth of memory every time.
|
|
80
|
-
*
|
|
81
|
-
* Idempotent.
|
|
82
|
-
*
|
|
83
|
-
* @param params.runtime The runtime to retire.
|
|
84
|
-
*/
|
|
85
23
|
export declare const disposeAnalysisRuntime: ({ runtime }: {
|
|
86
24
|
runtime: AnalysisRuntime;
|
|
87
25
|
}) => void;
|
|
88
|
-
/**
|
|
89
|
-
* Runs one flamapy operation on a runtime, serialised behind any previous one.
|
|
90
|
-
*
|
|
91
|
-
* INTERNAL. `operation` is a `FLAMAFeatureModel` method name for `'basic'`, or
|
|
92
|
-
* the suffix of a `PySAT*`/`BDD*` operation otherwise.
|
|
93
|
-
*/
|
|
94
26
|
export declare const runOperation: (state: RuntimeState, operation: string, uvl: string, type: SolvingType) => Promise<unknown>;
|
|
95
|
-
/** INTERNAL: unwraps a handle for the analysis functions. */
|
|
96
27
|
export declare const useRuntime: (runtime: AnalysisRuntime) => RuntimeState;
|
|
97
28
|
export {};
|
package/dist/analysis/runtime.js
CHANGED
|
@@ -1,22 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The Pyodide/flamapy runtime used for feature model analysis (ADR-021).
|
|
3
|
-
*
|
|
4
|
-
* Replaces `@lbdudc/flamapy.js`'s own `setupPyodide()`, which calls
|
|
5
|
-
* `loadPyodide()` with no options and then `loadPackage('micropip')` — and on a
|
|
6
|
-
* cold install that DOWNLOADS `micropip` and `packaging` from
|
|
7
|
-
* `cdn.jsdelivr.net`, breaking ADR-002. Worse, with no network it does not
|
|
8
|
-
* throw: every operation silently returns `undefined`.
|
|
9
|
-
*
|
|
10
|
-
* Here both wheels are vendored under `src/analysis/wheels/` and handed to
|
|
11
|
-
* pyodide via `packageCacheDir`, so nothing is ever fetched. A canary operation
|
|
12
|
-
* proves the bootstrap actually works before the runtime is handed out.
|
|
13
|
-
*
|
|
14
|
-
* Also replaces the historical `FlamapyWrapper` of the monolith
|
|
15
|
-
* (`server/src/utils/flamapyUtils.mjs` before commit ed2e037), which kept a
|
|
16
|
-
* module-level `_pyodidePromise` and a module-level `_opQueue`. ADR-014 forbids
|
|
17
|
-
* that: the instance AND its serialisation queue live inside a handle the
|
|
18
|
-
* CALLER owns.
|
|
19
|
-
*/
|
|
20
1
|
import fs from 'node:fs';
|
|
21
2
|
import path from 'node:path';
|
|
22
3
|
import { createRequire } from 'node:module';
|
|
@@ -26,60 +7,18 @@ import { resolveAsset } from '../assets.js';
|
|
|
26
7
|
import { AnalysisRuntimeError, InvalidArgumentError } from '../errors.js';
|
|
27
8
|
const toState = (runtime) => runtime;
|
|
28
9
|
const toRuntime = (state) => state;
|
|
29
|
-
/** Directory holding the vendored wheels (ADR-021). */
|
|
30
10
|
const vendoredWheelsDir = () => resolveAsset({ segments: ['analysis', 'wheels'] });
|
|
31
|
-
/**
|
|
32
|
-
* The wheels pyodide needs before flamapy can be installed.
|
|
33
|
-
*
|
|
34
|
-
* Their presence is checked by NAME, not just the directory's, and that check is
|
|
35
|
-
* the only thing standing between this module and the network. `packageCacheDir`
|
|
36
|
-
* is a CACHE, not an override: on a miss pyodide silently falls back to
|
|
37
|
-
* `https://cdn.jsdelivr.net/pyodide/v0.26.2/full/`, downloads the wheel and
|
|
38
|
-
* carries on as if nothing happened. Verified — with an empty directory the
|
|
39
|
-
* bootstrap SUCCEEDS over the network. So a missing wheel does not degrade the
|
|
40
|
-
* runtime, it quietly breaks ADR-002, which is worse: it is a failure that only
|
|
41
|
-
* shows up as traffic nobody is watching.
|
|
42
|
-
*
|
|
43
|
-
* These exact filenames are TIED TO pyodide 0.26.2, which is why `pyodide` is
|
|
44
|
-
* pinned exactly in `dependencies` rather than floated. Bumping pyodide means
|
|
45
|
-
* re-vendoring the wheels its release expects; if the names stop matching, this
|
|
46
|
-
* guard fires and the analysis stops working — loudly, which is the point.
|
|
47
|
-
*/
|
|
48
11
|
const REQUIRED_WHEELS = ['micropip-0.6.0-py3-none-any.whl', 'packaging-23.2-py3-none-any.whl'];
|
|
49
|
-
/** Directory of `@lbdudc/flamapy.js`'s `lib/`, which holds `py/` and its wheels. */
|
|
50
12
|
const flamapyLibDir = () => {
|
|
51
13
|
const require = createRequire(import.meta.url);
|
|
52
14
|
return path.dirname(require.resolve('@lbdudc/flamapy.js/lib/python-utils.js'));
|
|
53
15
|
};
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
* `python_stdlib.zip`, `pyodide-lock.json`).
|
|
57
|
-
*
|
|
58
|
-
* Passed explicitly rather than left to pyodide's self-location: it derives its
|
|
59
|
-
* `indexURL` from its own module URL, which breaks under a bundler or test
|
|
60
|
-
* runner that rewrites module paths. Vitest makes it look for
|
|
61
|
-
* `node_modules/src/js/pyodide-lock.json`, which does not exist. Resolving from
|
|
62
|
-
* the package manifest is stable everywhere.
|
|
63
|
-
*/
|
|
16
|
+
/** Pyodide's own chatter is not for the output of a program that uses this. */
|
|
17
|
+
const silent = () => { };
|
|
64
18
|
const pyodideIndexDir = () => {
|
|
65
19
|
const require = createRequire(import.meta.url);
|
|
66
20
|
return path.dirname(require.resolve('pyodide/package.json'));
|
|
67
21
|
};
|
|
68
|
-
/**
|
|
69
|
-
* Brings up a Pyodide interpreter with flamapy installed.
|
|
70
|
-
*
|
|
71
|
-
* Costs roughly 2.3 s, so a caller running several analyses should create ONE
|
|
72
|
-
* runtime and reuse it. Everything is read from disk: no network, ever.
|
|
73
|
-
*
|
|
74
|
-
* Before returning, a canary operation is run. If it fails — or comes back
|
|
75
|
-
* `undefined`, which is exactly what a silently broken bootstrap produces — this
|
|
76
|
-
* throws instead of handing out a runtime that would report empty metrics
|
|
77
|
-
* (ADR-021).
|
|
78
|
-
*
|
|
79
|
-
* @param options.wheelsDir Optional override of the vendored wheels directory.
|
|
80
|
-
* @returns An initialised runtime handle, owned by the caller.
|
|
81
|
-
* @throws {AnalysisRuntimeError} when the bootstrap or the canary fails.
|
|
82
|
-
*/
|
|
83
22
|
export const createAnalysisRuntime = async ({ wheelsDir = vendoredWheelsDir() } = {}) => {
|
|
84
23
|
if (typeof wheelsDir !== 'string' || wheelsDir.trim() === '') {
|
|
85
24
|
throw new InvalidArgumentError('"wheelsDir" must be a non-empty path when provided.');
|
|
@@ -87,9 +26,6 @@ export const createAnalysisRuntime = async ({ wheelsDir = vendoredWheelsDir() }
|
|
|
87
26
|
if (!fs.existsSync(wheelsDir)) {
|
|
88
27
|
throw new AnalysisRuntimeError(`Vendored wheels directory not found: ${wheelsDir}. The package build must copy src/analysis/wheels/ into dist/.`);
|
|
89
28
|
}
|
|
90
|
-
// Checked BEFORE booting pyodide, because after that it is too late: a missing
|
|
91
|
-
// wheel is fetched from the CDN and the bootstrap succeeds online. See
|
|
92
|
-
// REQUIRED_WHEELS. This is the guard ADR-002 actually rests on.
|
|
93
29
|
const missing = REQUIRED_WHEELS.filter((wheel) => !fs.existsSync(path.join(wheelsDir, wheel)));
|
|
94
30
|
if (missing.length > 0) {
|
|
95
31
|
throw new AnalysisRuntimeError(`Vendored wheels missing from ${wheelsDir}: ${missing.join(', ')}. ` +
|
|
@@ -100,13 +36,15 @@ export const createAnalysisRuntime = async ({ wheelsDir = vendoredWheelsDir() }
|
|
|
100
36
|
try {
|
|
101
37
|
pyodide = await loadPyodide({
|
|
102
38
|
indexURL: pyodideIndexDir(),
|
|
103
|
-
packageCacheDir: wheelsDir
|
|
39
|
+
packageCacheDir: wheelsDir,
|
|
40
|
+
// what pyodide says while it loads packages is not for the output of a program that uses this (a CLI's --json)
|
|
41
|
+
stdout: silent,
|
|
42
|
+
stderr: silent
|
|
104
43
|
});
|
|
105
|
-
// pyodide types `FS` as `any`; narrow it to just what is used here.
|
|
106
44
|
const vfs = pyodide.FS;
|
|
107
45
|
vfs.mkdirTree('/mnt');
|
|
108
46
|
vfs.mount(vfs.filesystems.NODEFS, { root: libDir }, '/mnt');
|
|
109
|
-
await pyodide.loadPackage('micropip');
|
|
47
|
+
await pyodide.loadPackage('micropip', { messageCallback: silent, errorCallback: silent });
|
|
110
48
|
await pyodide.runPythonAsync(fs.readFileSync(path.join(libDir, 'py', 'packages.py'), 'utf8'));
|
|
111
49
|
await pyodide.runPythonAsync('await install_packages()');
|
|
112
50
|
}
|
|
@@ -114,11 +52,6 @@ export const createAnalysisRuntime = async ({ wheelsDir = vendoredWheelsDir() }
|
|
|
114
52
|
throw new AnalysisRuntimeError(`Could not start the feature model analysis runtime: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
115
53
|
}
|
|
116
54
|
const state = { pyodide, queue: Promise.resolve(), disposed: false };
|
|
117
|
-
// ── Canary (ADR-021) ───────────────────────────────────────────────────────
|
|
118
|
-
// flamapy.js swallows bootstrap failures: `loadAndRunPythonScript` catches and
|
|
119
|
-
// only console.errors, and `install_packages()` has its own bare `except`. The
|
|
120
|
-
// result is every operation returning `undefined` with no error at all. This
|
|
121
|
-
// proves the stack really works before the runtime escapes.
|
|
122
55
|
const CANARY_UVL = 'features\n Root\n mandatory\n A\n B\n';
|
|
123
56
|
let canary;
|
|
124
57
|
try {
|
|
@@ -134,22 +67,6 @@ export const createAnalysisRuntime = async ({ wheelsDir = vendoredWheelsDir() }
|
|
|
134
67
|
}
|
|
135
68
|
return toRuntime(state);
|
|
136
69
|
};
|
|
137
|
-
/**
|
|
138
|
-
* Retires a runtime handle.
|
|
139
|
-
*
|
|
140
|
-
* IT DOES NOT FREE MEMORY, and callers must plan around that. Pyodide exposes no
|
|
141
|
-
* teardown, so the ~180 MB WASM heap an interpreter holds stays allocated for
|
|
142
|
-
* the life of the process; all this does is mark the handle unusable so later
|
|
143
|
-
* analyses fail loudly instead of running on a half-torn-down interpreter.
|
|
144
|
-
*
|
|
145
|
-
* The practical consequence for linea-server: do NOT create a runtime per
|
|
146
|
-
* request. Create a small, long-lived set of them and reuse. Creating and
|
|
147
|
-
* disposing per request leaks an interpreter's worth of memory every time.
|
|
148
|
-
*
|
|
149
|
-
* Idempotent.
|
|
150
|
-
*
|
|
151
|
-
* @param params.runtime The runtime to retire.
|
|
152
|
-
*/
|
|
153
70
|
export const disposeAnalysisRuntime = ({ runtime }) => {
|
|
154
71
|
if (runtime === null || typeof runtime !== 'object') {
|
|
155
72
|
throw new InvalidArgumentError('"runtime" must be a value returned by createAnalysisRuntime().');
|
|
@@ -157,7 +74,6 @@ export const disposeAnalysisRuntime = ({ runtime }) => {
|
|
|
157
74
|
const state = toState(runtime);
|
|
158
75
|
state.disposed = true;
|
|
159
76
|
};
|
|
160
|
-
/** Converts a Pyodide proxy into plain JavaScript, mirroring flamapy's `pythonToJs`. */
|
|
161
77
|
const toJs = (value) => {
|
|
162
78
|
if (value === null || typeof value !== 'object')
|
|
163
79
|
return value;
|
|
@@ -168,23 +84,14 @@ const toJs = (value) => {
|
|
|
168
84
|
proxy.destroy?.();
|
|
169
85
|
return converted;
|
|
170
86
|
};
|
|
171
|
-
/**
|
|
172
|
-
* Runs one flamapy operation on a runtime, serialised behind any previous one.
|
|
173
|
-
*
|
|
174
|
-
* INTERNAL. `operation` is a `FLAMAFeatureModel` method name for `'basic'`, or
|
|
175
|
-
* the suffix of a `PySAT*`/`BDD*` operation otherwise.
|
|
176
|
-
*/
|
|
177
87
|
export const runOperation = async (state, operation, uvl, type) => {
|
|
178
88
|
if (state.disposed) {
|
|
179
89
|
throw new AnalysisRuntimeError('This analysis runtime has already been disposed.');
|
|
180
90
|
}
|
|
181
91
|
const run = state.queue.then(async () => toJs(await executeFlamapyOperation(state.pyodide, operation, uvl, [], {}, type)));
|
|
182
|
-
// Advance the chain even when this operation rejects, or one failure would
|
|
183
|
-
// deadlock every later operation on the runtime.
|
|
184
92
|
state.queue = run.then(() => undefined, () => undefined);
|
|
185
93
|
return await run;
|
|
186
94
|
};
|
|
187
|
-
/** INTERNAL: unwraps a handle for the analysis functions. */
|
|
188
95
|
export const useRuntime = (runtime) => {
|
|
189
96
|
if (runtime === null || typeof runtime !== 'object') {
|
|
190
97
|
throw new InvalidArgumentError('"runtime" must be a value returned by createAnalysisRuntime().');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/analysis/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AACrC,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAA;AAEhF,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAC3C,OA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,CAAA;IACxD,OAAO,MAAM,GAAG,CAAA;AAClB,CAAC,CAAA;AAED,6DAA6D;AAC7D,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,OAAwB,EAAgB,EAAE;IACnE,IAAI,OAAO,KAAK,IAAI,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QACpD,MAAM,IAAI,oBAAoB,CAAC,gEAAgE,CAAC,CAAA;IAClG,CAAC;IACD,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IAC9B,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;QACnB,MAAM,IAAI,oBAAoB,CAAC,kDAAkD,CAAC,CAAA;IACpF,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA","sourcesContent":["/**\n * The Pyodide/flamapy runtime used for feature model analysis (ADR-021).\n *\n * Replaces `@lbdudc/flamapy.js`'s own `setupPyodide()`, which calls\n * `loadPyodide()` with no options and then `loadPackage('micropip')` — and on a\n * cold install that DOWNLOADS `micropip` and `packaging` from\n * `cdn.jsdelivr.net`, breaking ADR-002. Worse, with no network it does not\n * throw: every operation silently returns `undefined`.\n *\n * Here both wheels are vendored under `src/analysis/wheels/` and handed to\n * pyodide via `packageCacheDir`, so nothing is ever fetched. A canary operation\n * proves the bootstrap actually works before the runtime is handed out.\n *\n * Also replaces the historical `FlamapyWrapper` of the monolith\n * (`server/src/utils/flamapyUtils.mjs` before commit ed2e037), which kept a\n * module-level `_pyodidePromise` and a module-level `_opQueue`. ADR-014 forbids\n * that: the instance AND its serialisation queue live inside a handle the\n * CALLER owns.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { createRequire } from 'node:module'\nimport { loadPyodide } from 'pyodide'\nimport { executeFlamapyOperation } from '@lbdudc/flamapy.js/lib/python-utils.js'\nimport type { PyodideLike } from '@lbdudc/flamapy.js'\nimport { resolveAsset } from '../assets.js'\nimport { AnalysisRuntimeError, InvalidArgumentError } from '../errors.js'\n\n/**\n * How flamapy is asked to solve an operation.\n *\n * Declared locally instead of importing `TypeSolving` from\n * `@lbdudc/flamapy.js`, and `PyodideHandle` below instead of pyodide's\n * `PyodideInterface`, for the reason stated in `feature-model/engine.ts`: no\n * `.d.ts` emitted into `dist/` may reference a dependency that ships no types.\n * `RuntimeState` is reachable from the public `AnalysisRuntime`, so a\n * third-party type in its shape leaks into the published declarations and\n * breaks every consumer compiling with `skipLibCheck: false` — which is exactly\n * how linea-server and linea-cli are meant to build. Verified by\n * `npm run check:consumer`.\n */\ntype SolvingType = 'basic' | 'pysat' | 'pysat_diagnosis' | 'bdd'\n\n/** The slice of pyodide's interface this module actually uses. */\ninterface PyodideHandle {\n FS: unknown\n runPythonAsync: (code: string) => Promise<unknown>\n loadPackage: (names: string | string[]) => Promise<unknown>\n}\n\ndeclare const analysisRuntimeBrand: unique symbol\n\n/**\n * An initialised analysis runtime.\n *\n * Opaque: it wraps a Pyodide instance plus the queue that serialises operations\n * on it. Create it with `createAnalysisRuntime`, pass it to the analysis\n * functions, and release it with `disposeAnalysisRuntime`.\n */\nexport interface AnalysisRuntime {\n readonly [analysisRuntimeBrand]: 'linea-core/AnalysisRuntime'\n}\n\ninterface RuntimeState {\n pyodide: PyodideHandle\n /**\n * Tail of the serialisation chain.\n *\n * flamapy writes the model to a FIXED path (`uvlfile.uvl`) inside Pyodide's\n * virtual filesystem, so two concurrent operations on the same interpreter\n * would overwrite each other's input. Every operation queues behind the\n * previous one. The queue is per-runtime, never per-module.\n */\n queue: Promise<void>\n disposed: boolean\n}\n\nconst toState = (runtime: AnalysisRuntime): RuntimeState =>\n runtime as unknown as RuntimeState\n\nconst toRuntime = (state: RuntimeState): AnalysisRuntime =>\n state as unknown as AnalysisRuntime\n\n/** Directory holding the vendored wheels (ADR-021). */\nconst vendoredWheelsDir = (): string => resolveAsset({ segments: ['analysis', 'wheels'] })\n\n/**\n * The wheels pyodide needs before flamapy can be installed.\n *\n * Their presence is checked by NAME, not just the directory's, and that check is\n * the only thing standing between this module and the network. `packageCacheDir`\n * is a CACHE, not an override: on a miss pyodide silently falls back to\n * `https://cdn.jsdelivr.net/pyodide/v0.26.2/full/`, downloads the wheel and\n * carries on as if nothing happened. Verified — with an empty directory the\n * bootstrap SUCCEEDS over the network. So a missing wheel does not degrade the\n * runtime, it quietly breaks ADR-002, which is worse: it is a failure that only\n * shows up as traffic nobody is watching.\n *\n * These exact filenames are TIED TO pyodide 0.26.2, which is why `pyodide` is\n * pinned exactly in `dependencies` rather than floated. Bumping pyodide means\n * re-vendoring the wheels its release expects; if the names stop matching, this\n * guard fires and the analysis stops working — loudly, which is the point.\n */\nconst REQUIRED_WHEELS = ['micropip-0.6.0-py3-none-any.whl', 'packaging-23.2-py3-none-any.whl']\n\n/** Directory of `@lbdudc/flamapy.js`'s `lib/`, which holds `py/` and its wheels. */\nconst flamapyLibDir = (): string => {\n const require = createRequire(import.meta.url)\n return path.dirname(require.resolve('@lbdudc/flamapy.js/lib/python-utils.js'))\n}\n\n/**\n * Directory holding pyodide's own runtime files (`pyodide.asm.wasm`,\n * `python_stdlib.zip`, `pyodide-lock.json`).\n *\n * Passed explicitly rather than left to pyodide's self-location: it derives its\n * `indexURL` from its own module URL, which breaks under a bundler or test\n * runner that rewrites module paths. Vitest makes it look for\n * `node_modules/src/js/pyodide-lock.json`, which does not exist. Resolving from\n * the package manifest is stable everywhere.\n */\nconst pyodideIndexDir = (): string => {\n const require = createRequire(import.meta.url)\n return path.dirname(require.resolve('pyodide/package.json'))\n}\n\n/** Options for `createAnalysisRuntime`. */\nexport interface AnalysisRuntimeOptions {\n /**\n * Override the directory pyodide loads `micropip`/`packaging` from. Defaults\n * to the wheels vendored inside this package; only useful for testing.\n */\n wheelsDir?: string\n}\n\n/**\n * Brings up a Pyodide interpreter with flamapy installed.\n *\n * Costs roughly 2.3 s, so a caller running several analyses should create ONE\n * runtime and reuse it. Everything is read from disk: no network, ever.\n *\n * Before returning, a canary operation is run. If it fails — or comes back\n * `undefined`, which is exactly what a silently broken bootstrap produces — this\n * throws instead of handing out a runtime that would report empty metrics\n * (ADR-021).\n *\n * @param options.wheelsDir Optional override of the vendored wheels directory.\n * @returns An initialised runtime handle, owned by the caller.\n * @throws {AnalysisRuntimeError} when the bootstrap or the canary fails.\n */\nexport const createAnalysisRuntime = async ({\n wheelsDir = vendoredWheelsDir()\n}: AnalysisRuntimeOptions = {}): Promise<AnalysisRuntime> => {\n if (typeof wheelsDir !== 'string' || wheelsDir.trim() === '') {\n throw new InvalidArgumentError('\"wheelsDir\" must be a non-empty path when provided.')\n }\n if (!fs.existsSync(wheelsDir)) {\n throw new AnalysisRuntimeError(\n `Vendored wheels directory not found: ${wheelsDir}. The package build must copy src/analysis/wheels/ into dist/.`\n )\n }\n // Checked BEFORE booting pyodide, because after that it is too late: a missing\n // wheel is fetched from the CDN and the bootstrap succeeds online. See\n // REQUIRED_WHEELS. This is the guard ADR-002 actually rests on.\n const missing = REQUIRED_WHEELS.filter(\n (wheel) => !fs.existsSync(path.join(wheelsDir, wheel))\n )\n if (missing.length > 0) {\n throw new AnalysisRuntimeError(\n `Vendored wheels missing from ${wheelsDir}: ${missing.join(', ')}. ` +\n 'Without them pyodide would silently download them from cdn.jsdelivr.net, breaking ADR-002.'\n )\n }\n\n const libDir = flamapyLibDir()\n let pyodide: PyodideHandle\n try {\n pyodide = await loadPyodide({\n indexURL: pyodideIndexDir(),\n packageCacheDir: wheelsDir\n })\n // pyodide types `FS` as `any`; narrow it to just what is used here.\n const vfs = pyodide.FS as {\n mkdirTree: (dir: string) => void\n mount: (fs: unknown, options: { root: string }, mountpoint: string) => void\n filesystems: { NODEFS: unknown }\n }\n vfs.mkdirTree('/mnt')\n vfs.mount(vfs.filesystems.NODEFS, { root: libDir }, '/mnt')\n await pyodide.loadPackage('micropip')\n await pyodide.runPythonAsync(fs.readFileSync(path.join(libDir, 'py', 'packages.py'), 'utf8'))\n await pyodide.runPythonAsync('await install_packages()')\n } catch (error) {\n throw new AnalysisRuntimeError(\n `Could not start the feature model analysis runtime: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n )\n }\n\n const state: RuntimeState = { pyodide, queue: Promise.resolve(), disposed: false }\n\n // ── Canary (ADR-021) ───────────────────────────────────────────────────────\n // flamapy.js swallows bootstrap failures: `loadAndRunPythonScript` catches and\n // only console.errors, and `install_packages()` has its own bare `except`. The\n // result is every operation returning `undefined` with no error at all. This\n // proves the stack really works before the runtime escapes.\n const CANARY_UVL = 'features\\n Root\\n mandatory\\n A\\n B\\n'\n let canary: unknown\n try {\n canary = await runOperation(state, 'core_features', CANARY_UVL, 'basic')\n } catch (error) {\n throw new AnalysisRuntimeError(\n `The analysis runtime started but its canary operation failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n )\n }\n if (!Array.isArray(canary) || canary.length === 0) {\n throw new AnalysisRuntimeError(\n 'The analysis runtime started but returned no result for its canary operation. ' +\n 'This is the signature of a Pyodide bootstrap that failed silently — most likely the ' +\n 'vendored micropip/packaging wheels are missing, so flamapy never installed (ADR-021).'\n )\n }\n\n return toRuntime(state)\n}\n\n/**\n * Retires a runtime handle.\n *\n * IT DOES NOT FREE MEMORY, and callers must plan around that. Pyodide exposes no\n * teardown, so the ~180 MB WASM heap an interpreter holds stays allocated for\n * the life of the process; all this does is mark the handle unusable so later\n * analyses fail loudly instead of running on a half-torn-down interpreter.\n *\n * The practical consequence for linea-server: do NOT create a runtime per\n * request. Create a small, long-lived set of them and reuse. Creating and\n * disposing per request leaks an interpreter's worth of memory every time.\n *\n * Idempotent.\n *\n * @param params.runtime The runtime to retire.\n */\nexport const disposeAnalysisRuntime = ({ runtime }: { runtime: AnalysisRuntime }): void => {\n if (runtime === null || typeof runtime !== 'object') {\n throw new InvalidArgumentError('\"runtime\" must be a value returned by createAnalysisRuntime().')\n }\n const state = toState(runtime)\n state.disposed = true\n}\n\n/** Converts a Pyodide proxy into plain JavaScript, mirroring flamapy's `pythonToJs`. */\nconst toJs = (value: unknown): unknown => {\n if (value === null || typeof value !== 'object') return value\n const proxy = value as { toJs?: (options: { dicts: boolean }) => unknown, destroy?: () => void }\n if (typeof proxy.toJs !== 'function') return value\n const converted = proxy.toJs({ dicts: true })\n proxy.destroy?.()\n return converted\n}\n\n/**\n * Runs one flamapy operation on a runtime, serialised behind any previous one.\n *\n * INTERNAL. `operation` is a `FLAMAFeatureModel` method name for `'basic'`, or\n * the suffix of a `PySAT*`/`BDD*` operation otherwise.\n */\nexport const runOperation = async (\n state: RuntimeState,\n operation: string,\n uvl: string,\n type: SolvingType\n): Promise<unknown> => {\n if (state.disposed) {\n throw new AnalysisRuntimeError('This analysis runtime has already been disposed.')\n }\n const run = state.queue.then(async () =>\n toJs(await executeFlamapyOperation(\n state.pyodide as unknown as PyodideLike,\n operation,\n uvl,\n [],\n {},\n type\n ))\n )\n // Advance the chain even when this operation rejects, or one failure would\n // deadlock every later operation on the runtime.\n state.queue = run.then(() => undefined, () => undefined)\n return await run\n}\n\n/** INTERNAL: unwraps a handle for the analysis functions. */\nexport const useRuntime = (runtime: AnalysisRuntime): RuntimeState => {\n if (runtime === null || typeof runtime !== 'object') {\n throw new InvalidArgumentError('\"runtime\" must be a value returned by createAnalysisRuntime().')\n }\n const state = toState(runtime)\n if (state.disposed) {\n throw new AnalysisRuntimeError('This analysis runtime has already been disposed.')\n }\n return state\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/analysis/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AACrC,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAA;AAEhF,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,cAAc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AAC;QACpD,MAAM,IAAI,oBAAoB,CAAC,gEAAgE,CAAC,CAAA;IAClG,CAAC;IACD,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IAC9B,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;QACnB,MAAM,IAAI,oBAAoB,CAAC,kDAAkD,CAAC,CAAA;IACpF,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA","sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\nimport { createRequire } from 'node:module'\nimport { loadPyodide } from 'pyodide'\nimport { executeFlamapyOperation } from '@lbdudc/flamapy.js/lib/python-utils.js'\nimport type { PyodideLike } from '@lbdudc/flamapy.js'\nimport { resolveAsset } from '../assets.js'\nimport { AnalysisRuntimeError, InvalidArgumentError } from '../errors.js'\n\ntype SolvingType = 'basic' | 'pysat' | 'pysat_diagnosis' | 'bdd'\n\ninterface PyodideHandle {\n FS: unknown\n runPythonAsync: (code: string) => Promise<unknown>\n loadPackage: (names: string | string[], options?: { messageCallback?: (m: string) => void; errorCallback?: (m: string) => void }) => Promise<unknown>\n}\n\ndeclare const analysisRuntimeBrand: unique symbol\n\nexport interface AnalysisRuntime {\n readonly [analysisRuntimeBrand]: 'linea-core/AnalysisRuntime'\n}\n\ninterface RuntimeState {\n pyodide: PyodideHandle\n queue: Promise<void>\n disposed: boolean\n}\n\nconst toState = (runtime: AnalysisRuntime): RuntimeState =>\n runtime as unknown as RuntimeState\n\nconst toRuntime = (state: RuntimeState): AnalysisRuntime =>\n state as unknown as AnalysisRuntime\n\nconst vendoredWheelsDir = (): string => resolveAsset({ segments: ['analysis', 'wheels'] })\n\nconst REQUIRED_WHEELS = ['micropip-0.6.0-py3-none-any.whl', 'packaging-23.2-py3-none-any.whl']\n\nconst flamapyLibDir = (): string => {\n const require = createRequire(import.meta.url)\n return path.dirname(require.resolve('@lbdudc/flamapy.js/lib/python-utils.js'))\n}\n\n/** Pyodide's own chatter is not for the output of a program that uses this. */\nconst silent = (): void => { /* nothing */ }\n\nconst pyodideIndexDir = (): string => {\n const require = createRequire(import.meta.url)\n return path.dirname(require.resolve('pyodide/package.json'))\n}\n\nexport interface AnalysisRuntimeOptions {\n wheelsDir?: string\n}\n\nexport const createAnalysisRuntime = async ({\n wheelsDir = vendoredWheelsDir()\n}: AnalysisRuntimeOptions = {}): Promise<AnalysisRuntime> => {\n if (typeof wheelsDir !== 'string' || wheelsDir.trim() === '') {\n throw new InvalidArgumentError('\"wheelsDir\" must be a non-empty path when provided.')\n }\n if (!fs.existsSync(wheelsDir)) {\n throw new AnalysisRuntimeError(\n `Vendored wheels directory not found: ${wheelsDir}. The package build must copy src/analysis/wheels/ into dist/.`\n )\n }\n const missing = REQUIRED_WHEELS.filter(\n (wheel) => !fs.existsSync(path.join(wheelsDir, wheel))\n )\n if (missing.length > 0) {\n throw new AnalysisRuntimeError(\n `Vendored wheels missing from ${wheelsDir}: ${missing.join(', ')}. ` +\n 'Without them pyodide would silently download them from cdn.jsdelivr.net, breaking ADR-002.'\n )\n }\n\n const libDir = flamapyLibDir()\n let pyodide: PyodideHandle\n try {\n pyodide = await loadPyodide({\n indexURL: pyodideIndexDir(),\n packageCacheDir: wheelsDir,\n // what pyodide says while it loads packages is not for the output of a program that uses this (a CLI's --json)\n stdout: silent,\n stderr: silent\n })\n const vfs = pyodide.FS as {\n mkdirTree: (dir: string) => void\n mount: (fs: unknown, options: { root: string }, mountpoint: string) => void\n filesystems: { NODEFS: unknown }\n }\n vfs.mkdirTree('/mnt')\n vfs.mount(vfs.filesystems.NODEFS, { root: libDir }, '/mnt')\n await pyodide.loadPackage('micropip', { messageCallback: silent, errorCallback: silent })\n await pyodide.runPythonAsync(fs.readFileSync(path.join(libDir, 'py', 'packages.py'), 'utf8'))\n await pyodide.runPythonAsync('await install_packages()')\n } catch (error) {\n throw new AnalysisRuntimeError(\n `Could not start the feature model analysis runtime: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n )\n }\n\n const state: RuntimeState = { pyodide, queue: Promise.resolve(), disposed: false }\n\n const CANARY_UVL = 'features\\n Root\\n mandatory\\n A\\n B\\n'\n let canary: unknown\n try {\n canary = await runOperation(state, 'core_features', CANARY_UVL, 'basic')\n } catch (error) {\n throw new AnalysisRuntimeError(\n `The analysis runtime started but its canary operation failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n )\n }\n if (!Array.isArray(canary) || canary.length === 0) {\n throw new AnalysisRuntimeError(\n 'The analysis runtime started but returned no result for its canary operation. ' +\n 'This is the signature of a Pyodide bootstrap that failed silently — most likely the ' +\n 'vendored micropip/packaging wheels are missing, so flamapy never installed (ADR-021).'\n )\n }\n\n return toRuntime(state)\n}\n\nexport const disposeAnalysisRuntime = ({ runtime }: { runtime: AnalysisRuntime }): void => {\n if (runtime === null || typeof runtime !== 'object') {\n throw new InvalidArgumentError('\"runtime\" must be a value returned by createAnalysisRuntime().')\n }\n const state = toState(runtime)\n state.disposed = true\n}\n\nconst toJs = (value: unknown): unknown => {\n if (value === null || typeof value !== 'object') return value\n const proxy = value as { toJs?: (options: { dicts: boolean }) => unknown, destroy?: () => void }\n if (typeof proxy.toJs !== 'function') return value\n const converted = proxy.toJs({ dicts: true })\n proxy.destroy?.()\n return converted\n}\n\nexport const runOperation = async (\n state: RuntimeState,\n operation: string,\n uvl: string,\n type: SolvingType\n): Promise<unknown> => {\n if (state.disposed) {\n throw new AnalysisRuntimeError('This analysis runtime has already been disposed.')\n }\n const run = state.queue.then(async () =>\n toJs(await executeFlamapyOperation(\n state.pyodide as unknown as PyodideLike,\n operation,\n uvl,\n [],\n {},\n type\n ))\n )\n state.queue = run.then(() => undefined, () => undefined)\n return await run\n}\n\nexport const useRuntime = (runtime: AnalysisRuntime): RuntimeState => {\n if (runtime === null || typeof runtime !== 'object') {\n throw new InvalidArgumentError('\"runtime\" must be a value returned by createAnalysisRuntime().')\n }\n const state = toState(runtime)\n if (state.disposed) {\n throw new AnalysisRuntimeError('This analysis runtime has already been disposed.')\n }\n return state\n}\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The UVL with its tabs as spaces and its line breaks unified, as the analysis service reads it. */
|
|
2
|
+
export declare const normalizeUvl: ({ uvl }: {
|
|
3
|
+
uvl: string;
|
|
4
|
+
}) => string;
|
|
5
|
+
/** About how many features a UVL text declares: what decides how much of the analysis is worth asking for. */
|
|
6
|
+
export declare const estimateFeatureCount: ({ uvl }: {
|
|
7
|
+
uvl: string;
|
|
8
|
+
}) => number;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { InvalidArgumentError } from '../errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* What the flamapy analysis needs of the UVL text it is given. (The feature model itself is bango's: a model of the feature metamodel, which
|
|
4
|
+
* `printUvl` writes as UVL; these only prepare that text for the analysis service.)
|
|
5
|
+
*/
|
|
6
|
+
const UVL_GROUP_KEYWORDS = new Set([
|
|
7
|
+
'mandatory',
|
|
8
|
+
'optional',
|
|
9
|
+
'alternative',
|
|
10
|
+
'or',
|
|
11
|
+
'features',
|
|
12
|
+
'constraints'
|
|
13
|
+
]);
|
|
14
|
+
const assertUvlString = (uvl, parameter) => {
|
|
15
|
+
if (typeof uvl !== 'string') {
|
|
16
|
+
throw new InvalidArgumentError(`"${parameter}" must be a string.`);
|
|
17
|
+
}
|
|
18
|
+
return uvl;
|
|
19
|
+
};
|
|
20
|
+
const expandTabs = (line, tabSize = 4) => {
|
|
21
|
+
let out = '';
|
|
22
|
+
let column = 0;
|
|
23
|
+
for (const char of line) {
|
|
24
|
+
if (char === '\t') {
|
|
25
|
+
const width = tabSize - (column % tabSize);
|
|
26
|
+
out += ' '.repeat(width);
|
|
27
|
+
column += width;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
out += char;
|
|
31
|
+
column += 1;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
};
|
|
36
|
+
/** The UVL with its tabs as spaces and its line breaks unified, as the analysis service reads it. */
|
|
37
|
+
export const normalizeUvl = ({ uvl }) => {
|
|
38
|
+
const unified = assertUvlString(uvl, 'uvl').trim().replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
39
|
+
return unified
|
|
40
|
+
.split('\n')
|
|
41
|
+
.map((line) => expandTabs(line, 4))
|
|
42
|
+
.join('\n');
|
|
43
|
+
};
|
|
44
|
+
/** About how many features a UVL text declares: what decides how much of the analysis is worth asking for. */
|
|
45
|
+
export const estimateFeatureCount = ({ uvl }) => {
|
|
46
|
+
const document = assertUvlString(uvl, 'uvl');
|
|
47
|
+
let inConstraints = false;
|
|
48
|
+
let count = 0;
|
|
49
|
+
for (const line of document.split('\n')) {
|
|
50
|
+
const trimmed = line.trim();
|
|
51
|
+
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('#'))
|
|
52
|
+
continue;
|
|
53
|
+
if (trimmed === 'constraints') {
|
|
54
|
+
inConstraints = true;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (inConstraints)
|
|
58
|
+
continue;
|
|
59
|
+
if (trimmed === 'features')
|
|
60
|
+
continue;
|
|
61
|
+
const indent = line.length - line.trimStart().length;
|
|
62
|
+
if (indent >= 2) {
|
|
63
|
+
const name = trimmed.split(/[\s{[]/)[0];
|
|
64
|
+
if (name && !UVL_GROUP_KEYWORDS.has(name))
|
|
65
|
+
count += 1;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return count;
|
|
69
|
+
};
|
|
70
|
+
//# sourceMappingURL=uvl-text.js.map
|