@lbdudc/linea-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +358 -0
  2. package/dist/analysis/analyze.d.ts +105 -0
  3. package/dist/analysis/analyze.js +220 -0
  4. package/dist/analysis/analyze.js.map +1 -0
  5. package/dist/analysis/runtime.d.ts +97 -0
  6. package/dist/analysis/runtime.js +198 -0
  7. package/dist/analysis/runtime.js.map +1 -0
  8. package/dist/analysis/wheels/micropip-0.6.0-py3-none-any.whl +0 -0
  9. package/dist/analysis/wheels/packaging-23.2-py3-none-any.whl +0 -0
  10. package/dist/assets.d.ts +16 -0
  11. package/dist/assets.js +36 -0
  12. package/dist/assets.js.map +1 -0
  13. package/dist/constants.d.ts +77 -0
  14. package/dist/constants.js +76 -0
  15. package/dist/constants.js.map +1 -0
  16. package/dist/derivation/derive.d.ts +68 -0
  17. package/dist/derivation/derive.js +115 -0
  18. package/dist/derivation/derive.js.map +1 -0
  19. package/dist/derivation/engine.d.ts +48 -0
  20. package/dist/derivation/engine.js +98 -0
  21. package/dist/derivation/engine.js.map +1 -0
  22. package/dist/errors.d.ts +72 -0
  23. package/dist/errors.js +91 -0
  24. package/dist/errors.js.map +1 -0
  25. package/dist/feature-model/convert.d.ts +35 -0
  26. package/dist/feature-model/convert.js +47 -0
  27. package/dist/feature-model/convert.js.map +1 -0
  28. package/dist/feature-model/engine.d.ts +60 -0
  29. package/dist/feature-model/engine.js +139 -0
  30. package/dist/feature-model/engine.js.map +1 -0
  31. package/dist/feature-model/inspect.d.ts +67 -0
  32. package/dist/feature-model/inspect.js +113 -0
  33. package/dist/feature-model/inspect.js.map +1 -0
  34. package/dist/feature-model/io.d.ts +66 -0
  35. package/dist/feature-model/io.js +92 -0
  36. package/dist/feature-model/io.js.map +1 -0
  37. package/dist/feature-model/parse.d.ts +30 -0
  38. package/dist/feature-model/parse.js +36 -0
  39. package/dist/feature-model/parse.js.map +1 -0
  40. package/dist/feature-model/text.d.ts +54 -0
  41. package/dist/feature-model/text.js +126 -0
  42. package/dist/feature-model/text.js.map +1 -0
  43. package/dist/fs/archive.d.ts +23 -0
  44. package/dist/fs/archive.js +87 -0
  45. package/dist/fs/archive.js.map +1 -0
  46. package/dist/fs/diff.d.ts +40 -0
  47. package/dist/fs/diff.js +155 -0
  48. package/dist/fs/diff.js.map +1 -0
  49. package/dist/fs/format.d.ts +21 -0
  50. package/dist/fs/format.js +111 -0
  51. package/dist/fs/format.js.map +1 -0
  52. package/dist/fs/workspace.d.ts +77 -0
  53. package/dist/fs/workspace.js +103 -0
  54. package/dist/fs/workspace.js.map +1 -0
  55. package/dist/index.d.ts +50 -0
  56. package/dist/index.js +48 -0
  57. package/dist/index.js.map +1 -0
  58. package/dist/internal/guards.d.ts +15 -0
  59. package/dist/internal/guards.js +16 -0
  60. package/dist/internal/guards.js.map +1 -0
  61. package/dist/line/platform-files.d.ts +73 -0
  62. package/dist/line/platform-files.js +112 -0
  63. package/dist/line/platform-files.js.map +1 -0
  64. package/dist/line/scaffold.d.ts +88 -0
  65. package/dist/line/scaffold.js +145 -0
  66. package/dist/line/scaffold.js.map +1 -0
  67. package/dist/line/templates/core/extra.js +54 -0
  68. package/dist/line/templates/core/transformation.js +196 -0
  69. package/dist/line/templates/metamodels/dataModel/extra.js +328 -0
  70. package/dist/line/templates/metamodels/dataModel/transformation.js +211 -0
  71. package/dist/line/templates/metamodels/sensor/extra.js +36 -0
  72. package/dist/line/templates/metamodels/sensor/transformation.js +47 -0
  73. package/dist/line/templates/pipeline/.gitlab-ci.yml +51 -0
  74. package/dist/line/templates/pipeline/ci/test-client.sh +16 -0
  75. package/dist/line/templates/pipeline/ci/test-server.sh +16 -0
  76. package/dist/product/engine-spec.d.ts +25 -0
  77. package/dist/product/engine-spec.js +77 -0
  78. package/dist/product/engine-spec.js.map +1 -0
  79. package/dist/product/spec.d.ts +130 -0
  80. package/dist/product/spec.js +219 -0
  81. package/dist/product/spec.js.map +1 -0
  82. package/dist/product/version.d.ts +27 -0
  83. package/dist/product/version.js +49 -0
  84. package/dist/product/version.js.map +1 -0
  85. package/dist/products-index/products-index.d.ts +224 -0
  86. package/dist/products-index/products-index.js +395 -0
  87. package/dist/products-index/products-index.js.map +1 -0
  88. package/dist/selection/selection.d.ts +126 -0
  89. package/dist/selection/selection.js +152 -0
  90. package/dist/selection/selection.js.map +1 -0
  91. package/package.json +67 -0
@@ -0,0 +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;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B,CAAA;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA","sourcesContent":["/**\r\n * Feature model analysis (ADR-008, ADR-021).\r\n *\r\n * Migrated from `linea/flamapy-server/main.py`: `/analyze` (~215-270),\r\n * `/analyze/bdd` (~273-340) and `/analyze/metric` (~340-367). The RESPONSE SHAPE\r\n * is contractual — webui and linea-cli already consume these exact keys — so it\r\n * is reproduced field for field, including the `_`-prefixed metadata.\r\n *\r\n * The `safe()` pattern of `main.py:105-117` is preserved: an operation that\r\n * fails yields `null` in its own field and never aborts the whole response. A\r\n * partially analysable model still returns everything it could compute.\r\n */\r\nimport { ANALYSIS_THRESHOLDS } from '../constants.js'\r\nimport { InvalidArgumentError } from '../errors.js'\r\nimport { estimateFeatureCount, normalizeUvl } from '../feature-model/text.js'\r\nimport {\r\n createAnalysisRuntime,\r\n disposeAnalysisRuntime,\r\n runOperation,\r\n useRuntime,\r\n type AnalysisRuntime\r\n} from './runtime.js'\r\n\r\n/** Solver requested by the caller. */\r\nexport type AnalysisMode = 'SAT' | 'BDD'\r\n\r\n/** Metrics `analyzeMetric` accepts, matching the `match` arms of `main.py`. */\r\nexport const ANALYSIS_METRICS = ['satisfiable', 'deadFeatures', 'falseOptionalFeatures'] as const\r\n\r\n/** A metric name accepted by `analyzeMetric`. */\r\nexport type AnalysisMetric = (typeof ANALYSIS_METRICS)[number]\r\n\r\n/** Structural + SAT analysis, the fast path. */\r\nexport interface FeatureModelAnalysis {\r\n coreFeatures: unknown\r\n averageBranchingFactor: unknown\r\n maxDepth: unknown\r\n estimatedConfigurations: unknown\r\n leafNumber: unknown\r\n leafFeatures: unknown\r\n atomicSets: unknown\r\n satisfiable: unknown\r\n deadFeatures: unknown\r\n falseOptionalFeatures: unknown\r\n /** Features counted by `estimateFeatureCount` over the normalised document. */\r\n _featureCount: number\r\n /** `'small' | 'medium' | 'large' | 'very_large'`, thresholds from `main.py`. */\r\n _modelSize: string\r\n /** Echo of the requested mode. */\r\n _solveMode: AnalysisMode\r\n /** Always `[]` here: the fast path skips nothing. */\r\n _skipped: string[]\r\n _elapsedMs: number\r\n}\r\n\r\n/** BDD + enumeration analysis, the slow path. */\r\nexport interface FeatureModelBddAnalysis {\r\n configurations: unknown\r\n configsNumber: unknown\r\n configDistribution: unknown\r\n featureInclusionProb: unknown\r\n homogeneity: unknown\r\n variability: unknown\r\n uniqueFeatures: unknown\r\n variantFeatures: unknown\r\n /** Fields deliberately not computed because the model is too large. */\r\n _skipped: string[]\r\n _elapsedMs: number\r\n}\r\n\r\n/** Result of `analyzeMetric`: the requested metric plus the solver used. */\r\nexport type MetricAnalysis = Partial<Record<AnalysisMetric, unknown>> & { _solveMode: AnalysisMode }\r\n\r\n/** BDD fields, in the order `main.py` lists them. */\r\nconst BDD_FIELDS = [\r\n 'configsNumber', 'configDistribution', 'featureInclusionProb',\r\n 'homogeneity', 'variability', 'uniqueFeatures', 'variantFeatures'\r\n] as const\r\n\r\n/** Verbatim from `main.py`'s `/analyze`. */\r\nconst modelSizeOf = (featureCount: number): string => {\r\n if (featureCount < 50) return 'small'\r\n if (featureCount < 100) return 'medium'\r\n if (featureCount < 250) return 'large'\r\n return 'very_large'\r\n}\r\n\r\n/**\r\n * Normalises and sanity-checks the input, mirroring every endpoint's preamble.\r\n * `main.py` answers HTTP 400 when the document does not start with `features`.\r\n */\r\nconst prepareUvl = (uvl: unknown): string => {\r\n if (typeof uvl !== 'string') {\r\n throw new InvalidArgumentError('\"uvl\" must be a string.')\r\n }\r\n const normalised = normalizeUvl({ uvl })\r\n if (!normalised.startsWith('features')) {\r\n throw new InvalidArgumentError(\r\n 'The UVL document must start with \"features\". Got: ' +\r\n `${JSON.stringify(normalised.slice(0, 40))}`\r\n )\r\n }\r\n return normalised\r\n}\r\n\r\nconst assertMode = (mode: unknown): AnalysisMode => {\r\n if (mode === undefined) return 'BDD'\r\n if (mode !== 'SAT' && mode !== 'BDD') {\r\n throw new InvalidArgumentError(`\"mode\" must be \"SAT\" or \"BDD\", got ${JSON.stringify(mode)}.`)\r\n }\r\n return mode\r\n}\r\n\r\n/**\r\n * `main.py:safe()` — run an operation, and on failure record `null` instead of\r\n * letting one broken metric take the whole response down.\r\n */\r\nconst safe = async (run: () => Promise<unknown>): Promise<unknown> => {\r\n try {\r\n return await run()\r\n } catch {\r\n return null\r\n }\r\n}\r\n\r\n/** Runs `body` with a runtime, creating and disposing a private one if needed. */\r\nconst withRuntime = async <T>(\r\n runtime: AnalysisRuntime | undefined,\r\n body: (provided: AnalysisRuntime) => Promise<T>\r\n): Promise<T> => {\r\n if (runtime !== undefined) return await body(runtime)\r\n // Bootstrapping costs ~2.3 s; callers running more than one analysis should\r\n // create a runtime once and pass it in.\r\n const owned = await createAnalysisRuntime()\r\n try {\r\n return await body(owned)\r\n } finally {\r\n disposeAnalysisRuntime({ runtime: owned })\r\n }\r\n}\r\n\r\n/**\r\n * Fast analysis: structural metrics plus the SAT group.\r\n *\r\n * PARITY QUIRK: `mode` does NOT change what is computed. `main.py` always runs\r\n * the PySAT operations here and only echoes the requested mode back in\r\n * `_solveMode`; the BDD group lives in `analyzeFeatureModelBdd`. Reproduced as\r\n * is, because webui reads `_solveMode` to label the result.\r\n *\r\n * @param params.uvl UVL document. Normalised internally.\r\n * @param params.mode Solver to report. Defaults to `'BDD'`.\r\n * @param params.runtime Optional runtime to reuse.\r\n * @returns Every field of `main.py`'s `/analyze`. Individual failures are `null`.\r\n * @throws {InvalidArgumentError} for a non-string or non-`features` document.\r\n * @throws {AnalysisRuntimeError} if the runtime cannot start or was disposed.\r\n */\r\nexport const analyzeFeatureModel = async ({\r\n uvl,\r\n mode,\r\n runtime\r\n}: {\r\n uvl: string\r\n mode?: AnalysisMode\r\n runtime?: AnalysisRuntime\r\n}): Promise<FeatureModelAnalysis> => {\r\n const document = prepareUvl(uvl)\r\n const solveMode = assertMode(mode)\r\n const started = Date.now()\r\n const featureCount = estimateFeatureCount({ uvl: document })\r\n\r\n return await withRuntime(runtime, async (provided) => {\r\n const state = useRuntime(provided)\r\n const basic = async (operation: string): Promise<unknown> =>\r\n await safe(async () => await runOperation(state, operation, document, 'basic'))\r\n const pysat = async (operation: string): Promise<unknown> =>\r\n await safe(async () => await runOperation(state, operation, document, 'pysat'))\r\n\r\n return {\r\n coreFeatures: await basic('core_features'),\r\n averageBranchingFactor: await basic('average_branching_factor'),\r\n maxDepth: await basic('max_depth'),\r\n estimatedConfigurations: await basic('estimated_number_of_configurations'),\r\n leafNumber: await basic('count_leafs'),\r\n leafFeatures: await basic('leaf_features'),\r\n atomicSets: await basic('atomic_sets'),\r\n satisfiable: await pysat('Satisfiable'),\r\n deadFeatures: await pysat('DeadFeatures'),\r\n falseOptionalFeatures: await pysat('FalseOptionalFeatures'),\r\n _featureCount: featureCount,\r\n _modelSize: modelSizeOf(featureCount),\r\n _solveMode: solveMode,\r\n _skipped: [],\r\n _elapsedMs: Date.now() - started\r\n }\r\n })\r\n}\r\n\r\n/**\r\n * Slow analysis: the BDD group plus full configuration enumeration.\r\n *\r\n * Both are exponential, so `ANALYSIS_THRESHOLDS` gates them exactly as `main.py`\r\n * does with `SKIP_BDD` and `SKIP_ENUM`:\r\n * - at or above 100 features, every field is `null` and all eight names land in\r\n * `_skipped` — the runtime is not even touched;\r\n * - above 30 features, `configurations` alone is skipped.\r\n *\r\n * @param params.uvl UVL document.\r\n * @param params.runtime Optional runtime to reuse.\r\n * @returns Every field of `main.py`'s `/analyze/bdd`.\r\n * @throws {InvalidArgumentError} for a non-string or non-`features` document.\r\n */\r\nexport const analyzeFeatureModelBdd = async ({\r\n uvl,\r\n runtime\r\n}: {\r\n uvl: string\r\n runtime?: AnalysisRuntime\r\n}): Promise<FeatureModelBddAnalysis> => {\r\n const document = prepareUvl(uvl)\r\n const started = Date.now()\r\n const featureCount = estimateFeatureCount({ uvl: document })\r\n const skipped: string[] = []\r\n\r\n if (featureCount >= ANALYSIS_THRESHOLDS.skipBdd) {\r\n skipped.push('configurations', ...BDD_FIELDS)\r\n return {\r\n configurations: null,\r\n configsNumber: null,\r\n configDistribution: null,\r\n featureInclusionProb: null,\r\n homogeneity: null,\r\n variability: null,\r\n uniqueFeatures: null,\r\n variantFeatures: null,\r\n _skipped: skipped,\r\n _elapsedMs: Date.now() - started\r\n }\r\n }\r\n\r\n return await withRuntime(runtime, async (provided) => {\r\n const state = useRuntime(provided)\r\n\r\n let configurations: unknown = null\r\n if (featureCount <= ANALYSIS_THRESHOLDS.skipEnumeration) {\r\n configurations = await safe(async () =>\r\n await runOperation(state, 'configurations', document, 'basic'))\r\n } else {\r\n skipped.push('configurations')\r\n }\r\n\r\n const bdd = async (operation: string): Promise<unknown> =>\r\n await safe(async () => await runOperation(state, operation, document, 'bdd'))\r\n\r\n return {\r\n configurations,\r\n configsNumber: await bdd('ConfigurationsNumber'),\r\n configDistribution: await bdd('ProductDistribution'),\r\n featureInclusionProb: await bdd('FeatureInclusionProbability'),\r\n homogeneity: await bdd('Homogeneity'),\r\n variability: await bdd('Variability'),\r\n uniqueFeatures: await bdd('UniqueFeatures'),\r\n variantFeatures: await bdd('VariantFeatures'),\r\n _skipped: skipped,\r\n _elapsedMs: Date.now() - started\r\n }\r\n })\r\n}\r\n\r\n/**\r\n * Computes a single metric.\r\n *\r\n * Mirrors the `match` of `main.py`'s `/analyze/metric`, including which solver\r\n * each arm uses: only `satisfiable` honours `mode` (PySAT or BDD); the other two\r\n * are PySAT-only and always report `_solveMode: 'SAT'`.\r\n *\r\n * @param params.uvl UVL document.\r\n * @param params.metric One of `ANALYSIS_METRICS`.\r\n * @param params.mode Solver, only meaningful for `satisfiable`. Defaults to `'BDD'`.\r\n * @param params.runtime Optional runtime to reuse.\r\n * @returns The metric plus the solver actually used.\r\n * @throws {InvalidArgumentError} for an unknown metric or a malformed document.\r\n */\r\nexport const analyzeMetric = async ({\r\n uvl,\r\n metric,\r\n mode,\r\n runtime\r\n}: {\r\n uvl: string\r\n metric: AnalysisMetric\r\n mode?: AnalysisMode\r\n runtime?: AnalysisRuntime\r\n}): Promise<MetricAnalysis> => {\r\n const document = prepareUvl(uvl)\r\n const requestedMode = assertMode(mode)\r\n if (!(ANALYSIS_METRICS as readonly string[]).includes(metric)) {\r\n throw new InvalidArgumentError(\r\n `Unknown metric ${JSON.stringify(metric)}. Supported: ${ANALYSIS_METRICS.join(', ')}.`\r\n )\r\n }\r\n\r\n return await withRuntime(runtime, async (provided) => {\r\n const state = useRuntime(provided)\r\n\r\n if (metric === 'satisfiable') {\r\n const solver = requestedMode === 'SAT' ? 'pysat' : 'bdd'\r\n return {\r\n satisfiable: await safe(async () =>\r\n await runOperation(state, 'Satisfiable', document, solver)),\r\n _solveMode: requestedMode\r\n }\r\n }\r\n\r\n const operation = metric === 'deadFeatures' ? 'DeadFeatures' : 'FalseOptionalFeatures'\r\n return {\r\n [metric]: await safe(async () =>\r\n await runOperation(state, operation, document, 'pysat')),\r\n _solveMode: 'SAT' as const\r\n }\r\n })\r\n}\r\n"]}
@@ -0,0 +1,97 @@
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
+ type SolvingType = 'basic' | 'pysat' | 'pysat_diagnosis' | 'bdd';
15
+ /** The slice of pyodide's interface this module actually uses. */
16
+ interface PyodideHandle {
17
+ FS: unknown;
18
+ runPythonAsync: (code: string) => Promise<unknown>;
19
+ loadPackage: (names: string | string[]) => Promise<unknown>;
20
+ }
21
+ 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
+ export interface AnalysisRuntime {
30
+ readonly [analysisRuntimeBrand]: 'linea-core/AnalysisRuntime';
31
+ }
32
+ interface RuntimeState {
33
+ 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
+ queue: Promise<void>;
43
+ disposed: boolean;
44
+ }
45
+ /** Options for `createAnalysisRuntime`. */
46
+ 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
+ wheelsDir?: string;
52
+ }
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
+ 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
+ export declare const disposeAnalysisRuntime: ({ runtime }: {
86
+ runtime: AnalysisRuntime;
87
+ }) => 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
+ export declare const runOperation: (state: RuntimeState, operation: string, uvl: string, type: SolvingType) => Promise<unknown>;
95
+ /** INTERNAL: unwraps a handle for the analysis functions. */
96
+ export declare const useRuntime: (runtime: AnalysisRuntime) => RuntimeState;
97
+ export {};
@@ -0,0 +1,198 @@
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
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import { createRequire } from 'node:module';
23
+ import { loadPyodide } from 'pyodide';
24
+ import { executeFlamapyOperation } from '@lbdudc/flamapy.js/lib/python-utils.js';
25
+ import { resolveAsset } from '../assets.js';
26
+ import { AnalysisRuntimeError, InvalidArgumentError } from '../errors.js';
27
+ const toState = (runtime) => runtime;
28
+ const toRuntime = (state) => state;
29
+ /** Directory holding the vendored wheels (ADR-021). */
30
+ 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
+ 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
+ const flamapyLibDir = () => {
51
+ const require = createRequire(import.meta.url);
52
+ return path.dirname(require.resolve('@lbdudc/flamapy.js/lib/python-utils.js'));
53
+ };
54
+ /**
55
+ * Directory holding pyodide's own runtime files (`pyodide.asm.wasm`,
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
+ */
64
+ const pyodideIndexDir = () => {
65
+ const require = createRequire(import.meta.url);
66
+ return path.dirname(require.resolve('pyodide/package.json'));
67
+ };
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
+ export const createAnalysisRuntime = async ({ wheelsDir = vendoredWheelsDir() } = {}) => {
84
+ if (typeof wheelsDir !== 'string' || wheelsDir.trim() === '') {
85
+ throw new InvalidArgumentError('"wheelsDir" must be a non-empty path when provided.');
86
+ }
87
+ if (!fs.existsSync(wheelsDir)) {
88
+ throw new AnalysisRuntimeError(`Vendored wheels directory not found: ${wheelsDir}. The package build must copy src/analysis/wheels/ into dist/.`);
89
+ }
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
+ const missing = REQUIRED_WHEELS.filter((wheel) => !fs.existsSync(path.join(wheelsDir, wheel)));
94
+ if (missing.length > 0) {
95
+ throw new AnalysisRuntimeError(`Vendored wheels missing from ${wheelsDir}: ${missing.join(', ')}. ` +
96
+ 'Without them pyodide would silently download them from cdn.jsdelivr.net, breaking ADR-002.');
97
+ }
98
+ const libDir = flamapyLibDir();
99
+ let pyodide;
100
+ try {
101
+ pyodide = await loadPyodide({
102
+ indexURL: pyodideIndexDir(),
103
+ packageCacheDir: wheelsDir
104
+ });
105
+ // pyodide types `FS` as `any`; narrow it to just what is used here.
106
+ const vfs = pyodide.FS;
107
+ vfs.mkdirTree('/mnt');
108
+ vfs.mount(vfs.filesystems.NODEFS, { root: libDir }, '/mnt');
109
+ await pyodide.loadPackage('micropip');
110
+ await pyodide.runPythonAsync(fs.readFileSync(path.join(libDir, 'py', 'packages.py'), 'utf8'));
111
+ await pyodide.runPythonAsync('await install_packages()');
112
+ }
113
+ catch (error) {
114
+ throw new AnalysisRuntimeError(`Could not start the feature model analysis runtime: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
115
+ }
116
+ 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
+ const CANARY_UVL = 'features\n Root\n mandatory\n A\n B\n';
123
+ let canary;
124
+ try {
125
+ canary = await runOperation(state, 'core_features', CANARY_UVL, 'basic');
126
+ }
127
+ catch (error) {
128
+ throw new AnalysisRuntimeError(`The analysis runtime started but its canary operation failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
129
+ }
130
+ if (!Array.isArray(canary) || canary.length === 0) {
131
+ throw new AnalysisRuntimeError('The analysis runtime started but returned no result for its canary operation. ' +
132
+ 'This is the signature of a Pyodide bootstrap that failed silently — most likely the ' +
133
+ 'vendored micropip/packaging wheels are missing, so flamapy never installed (ADR-021).');
134
+ }
135
+ return toRuntime(state);
136
+ };
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
+ export const disposeAnalysisRuntime = ({ runtime }) => {
154
+ if (runtime === null || typeof runtime !== 'object') {
155
+ throw new InvalidArgumentError('"runtime" must be a value returned by createAnalysisRuntime().');
156
+ }
157
+ const state = toState(runtime);
158
+ state.disposed = true;
159
+ };
160
+ /** Converts a Pyodide proxy into plain JavaScript, mirroring flamapy's `pythonToJs`. */
161
+ const toJs = (value) => {
162
+ if (value === null || typeof value !== 'object')
163
+ return value;
164
+ const proxy = value;
165
+ if (typeof proxy.toJs !== 'function')
166
+ return value;
167
+ const converted = proxy.toJs({ dicts: true });
168
+ proxy.destroy?.();
169
+ return converted;
170
+ };
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
+ export const runOperation = async (state, operation, uvl, type) => {
178
+ if (state.disposed) {
179
+ throw new AnalysisRuntimeError('This analysis runtime has already been disposed.');
180
+ }
181
+ 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
+ state.queue = run.then(() => undefined, () => undefined);
185
+ return await run;
186
+ };
187
+ /** INTERNAL: unwraps a handle for the analysis functions. */
188
+ export const useRuntime = (runtime) => {
189
+ if (runtime === null || typeof runtime !== 'object') {
190
+ throw new InvalidArgumentError('"runtime" must be a value returned by createAnalysisRuntime().');
191
+ }
192
+ const state = toState(runtime);
193
+ if (state.disposed) {
194
+ throw new AnalysisRuntimeError('This analysis runtime has already been disposed.');
195
+ }
196
+ return state;
197
+ };
198
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +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,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AAmDzE,MAAM,OAAO,GAAG,CAAC,OAAwB,EAAgB,EAAE,CACzD,OAAkC,CAAA;AAEpC,MAAM,SAAS,GAAG,CAAC,KAAmB,EAAmB,EAAE,CACzD,KAAmC,CAAA;AAErC,uDAAuD;AACvD,MAAM,iBAAiB,GAAG,GAAW,EAAE,CAAC,YAAY,CAAC,EAAE,QAAQ,EAAE,CAAC,UAAU,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAA;AAE1F;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,eAAe,GAAG,CAAC,iCAAiC,EAAE,iCAAiC,CAAC,CAAA;AAE9F,oFAAoF;AACpF,MAAM,aAAa,GAAG,GAAW,EAAE;IACjC,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IAC9C,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,wCAAwC,CAAC,CAAC,CAAA;AAChF,CAAC,CAAA;AAED;;;;;;;;;GASG;AACH,MAAM,eAAe,GAAG,GAAW,EAAE;IACnC,MAAM,OAAO,GAAG,aA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IAAiB,EACC,EAAE;IACpB,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;QACnB,MAAM,IAAI,oBAAoB,CAAC,kDAAkD,CAAC,CAAA;IACpF,CAAC;IACD,MAAM,GAAG,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE,CACtC,IAAI,CAAC,MAAM,uBAAuB,CAChC,KAAK,CAAC,OAAiC,EACvC,SAAS,EACT,GAAG,EACH,EAAE,EACF,EAAE,EACF,IAAI,CACL,CAAC,CACH,CAAA;IACD,2EAA2E;IAC3E,iDAAiD;IACjD,KAAK,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,SAAS,CAAC,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":["/**\r\n * The Pyodide/flamapy runtime used for feature model analysis (ADR-021).\r\n *\r\n * Replaces `@lbdudc/flamapy.js`'s own `setupPyodide()`, which calls\r\n * `loadPyodide()` with no options and then `loadPackage('micropip')` — and on a\r\n * cold install that DOWNLOADS `micropip` and `packaging` from\r\n * `cdn.jsdelivr.net`, breaking ADR-002. Worse, with no network it does not\r\n * throw: every operation silently returns `undefined`.\r\n *\r\n * Here both wheels are vendored under `src/analysis/wheels/` and handed to\r\n * pyodide via `packageCacheDir`, so nothing is ever fetched. A canary operation\r\n * proves the bootstrap actually works before the runtime is handed out.\r\n *\r\n * Also replaces the historical `FlamapyWrapper` of the monolith\r\n * (`server/src/utils/flamapyUtils.mjs` before commit ed2e037), which kept a\r\n * module-level `_pyodidePromise` and a module-level `_opQueue`. ADR-014 forbids\r\n * that: the instance AND its serialisation queue live inside a handle the\r\n * CALLER owns.\r\n */\r\nimport fs from 'node:fs'\r\nimport path from 'node:path'\r\nimport { createRequire } from 'node:module'\r\nimport { loadPyodide } from 'pyodide'\r\nimport { executeFlamapyOperation } from '@lbdudc/flamapy.js/lib/python-utils.js'\r\nimport type { PyodideLike } from '@lbdudc/flamapy.js'\r\nimport { resolveAsset } from '../assets.js'\r\nimport { AnalysisRuntimeError, InvalidArgumentError } from '../errors.js'\r\n\r\n/**\r\n * How flamapy is asked to solve an operation.\r\n *\r\n * Declared locally instead of importing `TypeSolving` from\r\n * `@lbdudc/flamapy.js`, and `PyodideHandle` below instead of pyodide's\r\n * `PyodideInterface`, for the reason stated in `feature-model/engine.ts`: no\r\n * `.d.ts` emitted into `dist/` may reference a dependency that ships no types.\r\n * `RuntimeState` is reachable from the public `AnalysisRuntime`, so a\r\n * third-party type in its shape leaks into the published declarations and\r\n * breaks every consumer compiling with `skipLibCheck: false` — which is exactly\r\n * how linea-server and linea-cli are meant to build. Verified by\r\n * `npm run check:consumer`.\r\n */\r\ntype SolvingType = 'basic' | 'pysat' | 'pysat_diagnosis' | 'bdd'\r\n\r\n/** The slice of pyodide's interface this module actually uses. */\r\ninterface PyodideHandle {\r\n FS: unknown\r\n runPythonAsync: (code: string) => Promise<unknown>\r\n loadPackage: (names: string | string[]) => Promise<unknown>\r\n}\r\n\r\ndeclare const analysisRuntimeBrand: unique symbol\r\n\r\n/**\r\n * An initialised analysis runtime.\r\n *\r\n * Opaque: it wraps a Pyodide instance plus the queue that serialises operations\r\n * on it. Create it with `createAnalysisRuntime`, pass it to the analysis\r\n * functions, and release it with `disposeAnalysisRuntime`.\r\n */\r\nexport interface AnalysisRuntime {\r\n readonly [analysisRuntimeBrand]: 'linea-core/AnalysisRuntime'\r\n}\r\n\r\ninterface RuntimeState {\r\n pyodide: PyodideHandle\r\n /**\r\n * Tail of the serialisation chain.\r\n *\r\n * flamapy writes the model to a FIXED path (`uvlfile.uvl`) inside Pyodide's\r\n * virtual filesystem, so two concurrent operations on the same interpreter\r\n * would overwrite each other's input. Every operation queues behind the\r\n * previous one. The queue is per-runtime, never per-module.\r\n */\r\n queue: Promise<void>\r\n disposed: boolean\r\n}\r\n\r\nconst toState = (runtime: AnalysisRuntime): RuntimeState =>\r\n runtime as unknown as RuntimeState\r\n\r\nconst toRuntime = (state: RuntimeState): AnalysisRuntime =>\r\n state as unknown as AnalysisRuntime\r\n\r\n/** Directory holding the vendored wheels (ADR-021). */\r\nconst vendoredWheelsDir = (): string => resolveAsset({ segments: ['analysis', 'wheels'] })\r\n\r\n/**\r\n * The wheels pyodide needs before flamapy can be installed.\r\n *\r\n * Their presence is checked by NAME, not just the directory's, and that check is\r\n * the only thing standing between this module and the network. `packageCacheDir`\r\n * is a CACHE, not an override: on a miss pyodide silently falls back to\r\n * `https://cdn.jsdelivr.net/pyodide/v0.26.2/full/`, downloads the wheel and\r\n * carries on as if nothing happened. Verified — with an empty directory the\r\n * bootstrap SUCCEEDS over the network. So a missing wheel does not degrade the\r\n * runtime, it quietly breaks ADR-002, which is worse: it is a failure that only\r\n * shows up as traffic nobody is watching.\r\n *\r\n * These exact filenames are TIED TO pyodide 0.26.2, which is why `pyodide` is\r\n * pinned exactly in `dependencies` rather than floated. Bumping pyodide means\r\n * re-vendoring the wheels its release expects; if the names stop matching, this\r\n * guard fires and the analysis stops working — loudly, which is the point.\r\n */\r\nconst REQUIRED_WHEELS = ['micropip-0.6.0-py3-none-any.whl', 'packaging-23.2-py3-none-any.whl']\r\n\r\n/** Directory of `@lbdudc/flamapy.js`'s `lib/`, which holds `py/` and its wheels. */\r\nconst flamapyLibDir = (): string => {\r\n const require = createRequire(import.meta.url)\r\n return path.dirname(require.resolve('@lbdudc/flamapy.js/lib/python-utils.js'))\r\n}\r\n\r\n/**\r\n * Directory holding pyodide's own runtime files (`pyodide.asm.wasm`,\r\n * `python_stdlib.zip`, `pyodide-lock.json`).\r\n *\r\n * Passed explicitly rather than left to pyodide's self-location: it derives its\r\n * `indexURL` from its own module URL, which breaks under a bundler or test\r\n * runner that rewrites module paths. Vitest makes it look for\r\n * `node_modules/src/js/pyodide-lock.json`, which does not exist. Resolving from\r\n * the package manifest is stable everywhere.\r\n */\r\nconst pyodideIndexDir = (): string => {\r\n const require = createRequire(import.meta.url)\r\n return path.dirname(require.resolve('pyodide/package.json'))\r\n}\r\n\r\n/** Options for `createAnalysisRuntime`. */\r\nexport interface AnalysisRuntimeOptions {\r\n /**\r\n * Override the directory pyodide loads `micropip`/`packaging` from. Defaults\r\n * to the wheels vendored inside this package; only useful for testing.\r\n */\r\n wheelsDir?: string\r\n}\r\n\r\n/**\r\n * Brings up a Pyodide interpreter with flamapy installed.\r\n *\r\n * Costs roughly 2.3 s, so a caller running several analyses should create ONE\r\n * runtime and reuse it. Everything is read from disk: no network, ever.\r\n *\r\n * Before returning, a canary operation is run. If it fails — or comes back\r\n * `undefined`, which is exactly what a silently broken bootstrap produces — this\r\n * throws instead of handing out a runtime that would report empty metrics\r\n * (ADR-021).\r\n *\r\n * @param options.wheelsDir Optional override of the vendored wheels directory.\r\n * @returns An initialised runtime handle, owned by the caller.\r\n * @throws {AnalysisRuntimeError} when the bootstrap or the canary fails.\r\n */\r\nexport const createAnalysisRuntime = async ({\r\n wheelsDir = vendoredWheelsDir()\r\n}: AnalysisRuntimeOptions = {}): Promise<AnalysisRuntime> => {\r\n if (typeof wheelsDir !== 'string' || wheelsDir.trim() === '') {\r\n throw new InvalidArgumentError('\"wheelsDir\" must be a non-empty path when provided.')\r\n }\r\n if (!fs.existsSync(wheelsDir)) {\r\n throw new AnalysisRuntimeError(\r\n `Vendored wheels directory not found: ${wheelsDir}. The package build must copy src/analysis/wheels/ into dist/.`\r\n )\r\n }\r\n // Checked BEFORE booting pyodide, because after that it is too late: a missing\r\n // wheel is fetched from the CDN and the bootstrap succeeds online. See\r\n // REQUIRED_WHEELS. This is the guard ADR-002 actually rests on.\r\n const missing = REQUIRED_WHEELS.filter(\r\n (wheel) => !fs.existsSync(path.join(wheelsDir, wheel))\r\n )\r\n if (missing.length > 0) {\r\n throw new AnalysisRuntimeError(\r\n `Vendored wheels missing from ${wheelsDir}: ${missing.join(', ')}. ` +\r\n 'Without them pyodide would silently download them from cdn.jsdelivr.net, breaking ADR-002.'\r\n )\r\n }\r\n\r\n const libDir = flamapyLibDir()\r\n let pyodide: PyodideHandle\r\n try {\r\n pyodide = await loadPyodide({\r\n indexURL: pyodideIndexDir(),\r\n packageCacheDir: wheelsDir\r\n })\r\n // pyodide types `FS` as `any`; narrow it to just what is used here.\r\n const vfs = pyodide.FS as {\r\n mkdirTree: (dir: string) => void\r\n mount: (fs: unknown, options: { root: string }, mountpoint: string) => void\r\n filesystems: { NODEFS: unknown }\r\n }\r\n vfs.mkdirTree('/mnt')\r\n vfs.mount(vfs.filesystems.NODEFS, { root: libDir }, '/mnt')\r\n await pyodide.loadPackage('micropip')\r\n await pyodide.runPythonAsync(fs.readFileSync(path.join(libDir, 'py', 'packages.py'), 'utf8'))\r\n await pyodide.runPythonAsync('await install_packages()')\r\n } catch (error) {\r\n throw new AnalysisRuntimeError(\r\n `Could not start the feature model analysis runtime: ${error instanceof Error ? error.message : String(error)}`,\r\n { cause: error }\r\n )\r\n }\r\n\r\n const state: RuntimeState = { pyodide, queue: Promise.resolve(), disposed: false }\r\n\r\n // ── Canary (ADR-021) ───────────────────────────────────────────────────────\r\n // flamapy.js swallows bootstrap failures: `loadAndRunPythonScript` catches and\r\n // only console.errors, and `install_packages()` has its own bare `except`. The\r\n // result is every operation returning `undefined` with no error at all. This\r\n // proves the stack really works before the runtime escapes.\r\n const CANARY_UVL = 'features\\n Root\\n mandatory\\n A\\n B\\n'\r\n let canary: unknown\r\n try {\r\n canary = await runOperation(state, 'core_features', CANARY_UVL, 'basic')\r\n } catch (error) {\r\n throw new AnalysisRuntimeError(\r\n `The analysis runtime started but its canary operation failed: ${error instanceof Error ? error.message : String(error)}`,\r\n { cause: error }\r\n )\r\n }\r\n if (!Array.isArray(canary) || canary.length === 0) {\r\n throw new AnalysisRuntimeError(\r\n 'The analysis runtime started but returned no result for its canary operation. ' +\r\n 'This is the signature of a Pyodide bootstrap that failed silently — most likely the ' +\r\n 'vendored micropip/packaging wheels are missing, so flamapy never installed (ADR-021).'\r\n )\r\n }\r\n\r\n return toRuntime(state)\r\n}\r\n\r\n/**\r\n * Retires a runtime handle.\r\n *\r\n * IT DOES NOT FREE MEMORY, and callers must plan around that. Pyodide exposes no\r\n * teardown, so the ~180 MB WASM heap an interpreter holds stays allocated for\r\n * the life of the process; all this does is mark the handle unusable so later\r\n * analyses fail loudly instead of running on a half-torn-down interpreter.\r\n *\r\n * The practical consequence for linea-server: do NOT create a runtime per\r\n * request. Create a small, long-lived set of them and reuse. Creating and\r\n * disposing per request leaks an interpreter's worth of memory every time.\r\n *\r\n * Idempotent.\r\n *\r\n * @param params.runtime The runtime to retire.\r\n */\r\nexport const disposeAnalysisRuntime = ({ runtime }: { runtime: AnalysisRuntime }): void => {\r\n if (runtime === null || typeof runtime !== 'object') {\r\n throw new InvalidArgumentError('\"runtime\" must be a value returned by createAnalysisRuntime().')\r\n }\r\n const state = toState(runtime)\r\n state.disposed = true\r\n}\r\n\r\n/** Converts a Pyodide proxy into plain JavaScript, mirroring flamapy's `pythonToJs`. */\r\nconst toJs = (value: unknown): unknown => {\r\n if (value === null || typeof value !== 'object') return value\r\n const proxy = value as { toJs?: (options: { dicts: boolean }) => unknown, destroy?: () => void }\r\n if (typeof proxy.toJs !== 'function') return value\r\n const converted = proxy.toJs({ dicts: true })\r\n proxy.destroy?.()\r\n return converted\r\n}\r\n\r\n/**\r\n * Runs one flamapy operation on a runtime, serialised behind any previous one.\r\n *\r\n * INTERNAL. `operation` is a `FLAMAFeatureModel` method name for `'basic'`, or\r\n * the suffix of a `PySAT*`/`BDD*` operation otherwise.\r\n */\r\nexport const runOperation = async (\r\n state: RuntimeState,\r\n operation: string,\r\n uvl: string,\r\n type: SolvingType\r\n): Promise<unknown> => {\r\n if (state.disposed) {\r\n throw new AnalysisRuntimeError('This analysis runtime has already been disposed.')\r\n }\r\n const run = state.queue.then(async () =>\r\n toJs(await executeFlamapyOperation(\r\n state.pyodide as unknown as PyodideLike,\r\n operation,\r\n uvl,\r\n [],\r\n {},\r\n type\r\n ))\r\n )\r\n // Advance the chain even when this operation rejects, or one failure would\r\n // deadlock every later operation on the runtime.\r\n state.queue = run.then(() => undefined, () => undefined)\r\n return await run\r\n}\r\n\r\n/** INTERNAL: unwraps a handle for the analysis functions. */\r\nexport const useRuntime = (runtime: AnalysisRuntime): RuntimeState => {\r\n if (runtime === null || typeof runtime !== 'object') {\r\n throw new InvalidArgumentError('\"runtime\" must be a value returned by createAnalysisRuntime().')\r\n }\r\n const state = toState(runtime)\r\n if (state.disposed) {\r\n throw new AnalysisRuntimeError('This analysis runtime has already been disposed.')\r\n }\r\n return state\r\n}\r\n"]}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Directory holding the packaged assets: `src/` when running from source,
3
+ * `dist/` when running from the published package.
4
+ */
5
+ export declare const assetsRoot: () => string;
6
+ /**
7
+ * Resolves the absolute path of an asset shipped with linea-core.
8
+ *
9
+ * @param params.segments Path segments relative to the assets root,
10
+ * e.g. `resolveAsset({ segments: ['line', 'templates', 'config.json'] })`.
11
+ * @returns Absolute path of the asset.
12
+ * @throws {InvalidArgumentError} if `segments` is not an array of strings.
13
+ */
14
+ export declare const resolveAsset: ({ segments }: {
15
+ segments: string[];
16
+ }) => string;
package/dist/assets.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Resolution of assets packaged with the library.
3
+ *
4
+ * Non-TypeScript files under `src/` (line templates, pipeline files...) are not
5
+ * compiled: `scripts/copy-assets.mjs` mirrors them into `dist/` at build time,
6
+ * preserving their relative path. That means `src/line/templates/x` ends up at
7
+ * `dist/line/templates/x`, so the path relative to THIS module is the same
8
+ * before and after the build.
9
+ *
10
+ * Resolution goes through `import.meta.url` and never through `process.cwd()`:
11
+ * linea-core is a library and must work regardless of where the host process was
12
+ * started from (ADR-014).
13
+ */
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+ import { InvalidArgumentError } from './errors.js';
17
+ /**
18
+ * Directory holding the packaged assets: `src/` when running from source,
19
+ * `dist/` when running from the published package.
20
+ */
21
+ export const assetsRoot = () => path.dirname(fileURLToPath(import.meta.url));
22
+ /**
23
+ * Resolves the absolute path of an asset shipped with linea-core.
24
+ *
25
+ * @param params.segments Path segments relative to the assets root,
26
+ * e.g. `resolveAsset({ segments: ['line', 'templates', 'config.json'] })`.
27
+ * @returns Absolute path of the asset.
28
+ * @throws {InvalidArgumentError} if `segments` is not an array of strings.
29
+ */
30
+ export const resolveAsset = ({ segments }) => {
31
+ if (!Array.isArray(segments) || segments.some((segment) => typeof segment !== 'string')) {
32
+ throw new InvalidArgumentError('"segments" must be an array of strings.');
33
+ }
34
+ return path.join(assetsRoot(), ...segments);
35
+ };
36
+ //# sourceMappingURL=assets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assets.js","sourceRoot":"","sources":["../src/assets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAElD;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAW,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;AAEpF;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,EAAE,QAAQ,EAA0B,EAAU,EAAE;IAC3E,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,OAAO,KAAK,QAAQ,CAAC,EAAE,CAAC;QACxF,MAAM,IAAI,oBAAoB,CAAC,yCAAyC,CAAC,CAAA;IAC3E,CAAC;IACD,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,GAAG,QAAQ,CAAC,CAAA;AAC7C,CAAC,CAAA","sourcesContent":["/**\r\n * Resolution of assets packaged with the library.\r\n *\r\n * Non-TypeScript files under `src/` (line templates, pipeline files...) are not\r\n * compiled: `scripts/copy-assets.mjs` mirrors them into `dist/` at build time,\r\n * preserving their relative path. That means `src/line/templates/x` ends up at\r\n * `dist/line/templates/x`, so the path relative to THIS module is the same\r\n * before and after the build.\r\n *\r\n * Resolution goes through `import.meta.url` and never through `process.cwd()`:\r\n * linea-core is a library and must work regardless of where the host process was\r\n * started from (ADR-014).\r\n */\r\nimport path from 'node:path'\r\nimport { fileURLToPath } from 'node:url'\r\nimport { InvalidArgumentError } from './errors.js'\r\n\r\n/**\r\n * Directory holding the packaged assets: `src/` when running from source,\r\n * `dist/` when running from the published package.\r\n */\r\nexport const assetsRoot = (): string => path.dirname(fileURLToPath(import.meta.url))\r\n\r\n/**\r\n * Resolves the absolute path of an asset shipped with linea-core.\r\n *\r\n * @param params.segments Path segments relative to the assets root,\r\n * e.g. `resolveAsset({ segments: ['line', 'templates', 'config.json'] })`.\r\n * @returns Absolute path of the asset.\r\n * @throws {InvalidArgumentError} if `segments` is not an array of strings.\r\n */\r\nexport const resolveAsset = ({ segments }: { segments: string[] }): string => {\r\n if (!Array.isArray(segments) || segments.some((segment) => typeof segment !== 'string')) {\r\n throw new InvalidArgumentError('\"segments\" must be an array of strings.')\r\n }\r\n return path.join(assetsRoot(), ...segments)\r\n}\r\n"]}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Domain constants of linea-core.
3
+ *
4
+ * ADR-014 forbids global mutable configuration, so everything the monolith read
5
+ * from `linea/server/src/resources/properties.yml` at runtime is frozen here as
6
+ * a constant. Callers that need different paths pass them explicitly.
7
+ */
8
+ /**
9
+ * Layout of a line's platform directory inside its repository.
10
+ *
11
+ * Migrated from `linea/server/src/resources/properties.yml` (`paths.platform.*`).
12
+ * The `./` prefix used by the YAML is dropped: these are repo-relative segments
13
+ * meant to be joined with a working directory (see `resolveLinePaths`).
14
+ */
15
+ export declare const PLATFORM_PATHS: {
16
+ /** `paths.platform.root` */
17
+ readonly root: "src/platform";
18
+ /** `paths.platform.code` — annotated source consumed by spl-js-engine. */
19
+ readonly code: "src/platform/code";
20
+ /** `paths.platform.model` — default (UVL) feature model. */
21
+ readonly model: "src/platform/model.uvl";
22
+ /** XML variant. properties.yml derives it via `model.replace('.uvl', '.xml')`. */
23
+ readonly modelXml: "src/platform/model.xml";
24
+ /** `paths.platform.config` */
25
+ readonly config: "src/platform/config.json";
26
+ /** `paths.platform.extraJS` */
27
+ readonly extraJs: "src/platform/extra.js";
28
+ /** `paths.platform.transformation` */
29
+ readonly transformation: "src/platform/transformation.js";
30
+ };
31
+ /**
32
+ * Product index kept at the root of every line repository (ADR-011).
33
+ * Format: `{ "productos": [{ "name", "repositorio", "version"? }] }`, where
34
+ * `version` is the optional, retro-compatible extension ADR-011 foresaw.
35
+ */
36
+ export declare const PRODUCTS_INDEX_PATH = "products.json";
37
+ /**
38
+ * Valid characters for line and product names.
39
+ * Migrated from `linea/server/src/rest/validators/commonValidators.js:NAME_PATTERN`.
40
+ */
41
+ export declare const NAME_PATTERN: RegExp;
42
+ /**
43
+ * Product version format (`x.y.z`).
44
+ * Migrated from `linea/server/src/rest/validators/commonValidators.js:VERSION_PATTERN`.
45
+ */
46
+ export declare const VERSION_PATTERN: RegExp;
47
+ /**
48
+ * Default UI languages of a generated product.
49
+ * Migrated from `linea/server/src/model/entities/product.js:32` and applied as a
50
+ * fallback in `generatePipeline.js:218`.
51
+ */
52
+ export declare const DEFAULT_LANGUAGES: readonly ["en", "es", "gl"];
53
+ /**
54
+ * Default spatial reference system of a generated product.
55
+ * Migrated from `linea/server/src/model/entities/product.js:36`.
56
+ */
57
+ export declare const DEFAULT_SRID = "4326";
58
+ /** Feature model notations supported by the engine. */
59
+ export declare const FEATURE_MODEL_TYPES: readonly ["UVL", "XML"];
60
+ /** A feature model notation. */
61
+ export type FeatureModelType = (typeof FEATURE_MODEL_TYPES)[number];
62
+ /**
63
+ * Analysis guard rails, kept for parity with `linea/flamapy-server/main.py`
64
+ * (`SKIP_ENUM`, `SKIP_BDD`). Full configuration enumeration and BDD construction
65
+ * are exponential; above these feature counts the monolith skips them.
66
+ *
67
+ * Consumed by `src/analysis/`, which lands in a later batch together with the
68
+ * offline-bootstrap ADR.
69
+ */
70
+ export declare const ANALYSIS_THRESHOLDS: {
71
+ /** Skip full enumeration above this feature count. */
72
+ readonly skipEnumeration: 30;
73
+ /** Skip BDD-based operations above this feature count. */
74
+ readonly skipBdd: 100;
75
+ };
76
+ /** Narrowing helper for values coming from outside the library. */
77
+ export declare const isFeatureModelType: (value: unknown) => value is FeatureModelType;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Domain constants of linea-core.
3
+ *
4
+ * ADR-014 forbids global mutable configuration, so everything the monolith read
5
+ * from `linea/server/src/resources/properties.yml` at runtime is frozen here as
6
+ * a constant. Callers that need different paths pass them explicitly.
7
+ */
8
+ /**
9
+ * Layout of a line's platform directory inside its repository.
10
+ *
11
+ * Migrated from `linea/server/src/resources/properties.yml` (`paths.platform.*`).
12
+ * The `./` prefix used by the YAML is dropped: these are repo-relative segments
13
+ * meant to be joined with a working directory (see `resolveLinePaths`).
14
+ */
15
+ export const PLATFORM_PATHS = {
16
+ /** `paths.platform.root` */
17
+ root: 'src/platform',
18
+ /** `paths.platform.code` — annotated source consumed by spl-js-engine. */
19
+ code: 'src/platform/code',
20
+ /** `paths.platform.model` — default (UVL) feature model. */
21
+ model: 'src/platform/model.uvl',
22
+ /** XML variant. properties.yml derives it via `model.replace('.uvl', '.xml')`. */
23
+ modelXml: 'src/platform/model.xml',
24
+ /** `paths.platform.config` */
25
+ config: 'src/platform/config.json',
26
+ /** `paths.platform.extraJS` */
27
+ extraJs: 'src/platform/extra.js',
28
+ /** `paths.platform.transformation` */
29
+ transformation: 'src/platform/transformation.js'
30
+ };
31
+ /**
32
+ * Product index kept at the root of every line repository (ADR-011).
33
+ * Format: `{ "productos": [{ "name", "repositorio", "version"? }] }`, where
34
+ * `version` is the optional, retro-compatible extension ADR-011 foresaw.
35
+ */
36
+ export const PRODUCTS_INDEX_PATH = 'products.json';
37
+ /**
38
+ * Valid characters for line and product names.
39
+ * Migrated from `linea/server/src/rest/validators/commonValidators.js:NAME_PATTERN`.
40
+ */
41
+ export const NAME_PATTERN = /^[a-zA-Z0-9_\-.]+$/;
42
+ /**
43
+ * Product version format (`x.y.z`).
44
+ * Migrated from `linea/server/src/rest/validators/commonValidators.js:VERSION_PATTERN`.
45
+ */
46
+ export const VERSION_PATTERN = /^\d+\.\d+\.\d+$/;
47
+ /**
48
+ * Default UI languages of a generated product.
49
+ * Migrated from `linea/server/src/model/entities/product.js:32` and applied as a
50
+ * fallback in `generatePipeline.js:218`.
51
+ */
52
+ export const DEFAULT_LANGUAGES = ['en', 'es', 'gl'];
53
+ /**
54
+ * Default spatial reference system of a generated product.
55
+ * Migrated from `linea/server/src/model/entities/product.js:36`.
56
+ */
57
+ export const DEFAULT_SRID = '4326';
58
+ /** Feature model notations supported by the engine. */
59
+ export const FEATURE_MODEL_TYPES = ['UVL', 'XML'];
60
+ /**
61
+ * Analysis guard rails, kept for parity with `linea/flamapy-server/main.py`
62
+ * (`SKIP_ENUM`, `SKIP_BDD`). Full configuration enumeration and BDD construction
63
+ * are exponential; above these feature counts the monolith skips them.
64
+ *
65
+ * Consumed by `src/analysis/`, which lands in a later batch together with the
66
+ * offline-bootstrap ADR.
67
+ */
68
+ export const ANALYSIS_THRESHOLDS = {
69
+ /** Skip full enumeration above this feature count. */
70
+ skipEnumeration: 30,
71
+ /** Skip BDD-based operations above this feature count. */
72
+ skipBdd: 100
73
+ };
74
+ /** Narrowing helper for values coming from outside the library. */
75
+ export const isFeatureModelType = (value) => typeof value === 'string' && FEATURE_MODEL_TYPES.includes(value);
76
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG;IAC5B,4BAA4B;IAC5B,IAAI,EAAE,cAAc;IACpB,0EAA0E;IAC1E,IAAI,EAAE,mBAAmB;IACzB,4DAA4D;IAC5D,KAAK,EAAE,wBAAwB;IAC/B,kFAAkF;IAClF,QAAQ,EAAE,wBAAwB;IAClC,8BAA8B;IAC9B,MAAM,EAAE,0BAA0B;IAClC,+BAA+B;IAC/B,OAAO,EAAE,uBAAuB;IAChC,sCAAsC;IACtC,cAAc,EAAE,gCAAgC;CACxC,CAAA;AAEV;;;;GAIG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,eAAe,CAAA;AAElD;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,oBAAoB,CAAA;AAEhD;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,iBAAiB,CAAA;AAEhD;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAU,CAAA;AAE5D;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAA;AAElC,uDAAuD;AACvD,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,KAAK,EAAE,KAAK,CAAU,CAAA;AAK1D;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,sDAAsD;IACtD,eAAe,EAAE,EAAE;IACnB,0DAA0D;IAC1D,OAAO,EAAE,GAAG;CACJ,CAAA;AAEV,mEAAmE;AACnE,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,KAAc,EAA6B,EAAE,CAC9E,OAAO,KAAK,KAAK,QAAQ,IAAK,mBAAyC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA","sourcesContent":["/**\r\n * Domain constants of linea-core.\r\n *\r\n * ADR-014 forbids global mutable configuration, so everything the monolith read\r\n * from `linea/server/src/resources/properties.yml` at runtime is frozen here as\r\n * a constant. Callers that need different paths pass them explicitly.\r\n */\r\n\r\n/**\r\n * Layout of a line's platform directory inside its repository.\r\n *\r\n * Migrated from `linea/server/src/resources/properties.yml` (`paths.platform.*`).\r\n * The `./` prefix used by the YAML is dropped: these are repo-relative segments\r\n * meant to be joined with a working directory (see `resolveLinePaths`).\r\n */\r\nexport const PLATFORM_PATHS = {\r\n /** `paths.platform.root` */\r\n root: 'src/platform',\r\n /** `paths.platform.code` — annotated source consumed by spl-js-engine. */\r\n code: 'src/platform/code',\r\n /** `paths.platform.model` — default (UVL) feature model. */\r\n model: 'src/platform/model.uvl',\r\n /** XML variant. properties.yml derives it via `model.replace('.uvl', '.xml')`. */\r\n modelXml: 'src/platform/model.xml',\r\n /** `paths.platform.config` */\r\n config: 'src/platform/config.json',\r\n /** `paths.platform.extraJS` */\r\n extraJs: 'src/platform/extra.js',\r\n /** `paths.platform.transformation` */\r\n transformation: 'src/platform/transformation.js'\r\n} as const\r\n\r\n/**\r\n * Product index kept at the root of every line repository (ADR-011).\r\n * Format: `{ \"productos\": [{ \"name\", \"repositorio\", \"version\"? }] }`, where\r\n * `version` is the optional, retro-compatible extension ADR-011 foresaw.\r\n */\r\nexport const PRODUCTS_INDEX_PATH = 'products.json'\r\n\r\n/**\r\n * Valid characters for line and product names.\r\n * Migrated from `linea/server/src/rest/validators/commonValidators.js:NAME_PATTERN`.\r\n */\r\nexport const NAME_PATTERN = /^[a-zA-Z0-9_\\-.]+$/\r\n\r\n/**\r\n * Product version format (`x.y.z`).\r\n * Migrated from `linea/server/src/rest/validators/commonValidators.js:VERSION_PATTERN`.\r\n */\r\nexport const VERSION_PATTERN = /^\\d+\\.\\d+\\.\\d+$/\r\n\r\n/**\r\n * Default UI languages of a generated product.\r\n * Migrated from `linea/server/src/model/entities/product.js:32` and applied as a\r\n * fallback in `generatePipeline.js:218`.\r\n */\r\nexport const DEFAULT_LANGUAGES = ['en', 'es', 'gl'] as const\r\n\r\n/**\r\n * Default spatial reference system of a generated product.\r\n * Migrated from `linea/server/src/model/entities/product.js:36`.\r\n */\r\nexport const DEFAULT_SRID = '4326'\r\n\r\n/** Feature model notations supported by the engine. */\r\nexport const FEATURE_MODEL_TYPES = ['UVL', 'XML'] as const\r\n\r\n/** A feature model notation. */\r\nexport type FeatureModelType = (typeof FEATURE_MODEL_TYPES)[number]\r\n\r\n/**\r\n * Analysis guard rails, kept for parity with `linea/flamapy-server/main.py`\r\n * (`SKIP_ENUM`, `SKIP_BDD`). Full configuration enumeration and BDD construction\r\n * are exponential; above these feature counts the monolith skips them.\r\n *\r\n * Consumed by `src/analysis/`, which lands in a later batch together with the\r\n * offline-bootstrap ADR.\r\n */\r\nexport const ANALYSIS_THRESHOLDS = {\r\n /** Skip full enumeration above this feature count. */\r\n skipEnumeration: 30,\r\n /** Skip BDD-based operations above this feature count. */\r\n skipBdd: 100\r\n} as const\r\n\r\n/** Narrowing helper for values coming from outside the library. */\r\nexport const isFeatureModelType = (value: unknown): value is FeatureModelType =>\r\n typeof value === 'string' && (FEATURE_MODEL_TYPES as readonly string[]).includes(value)\r\n"]}