@lbdudc/linea-core 0.1.0 → 0.1.1

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 (37) hide show
  1. package/README.md +358 -358
  2. package/dist/analysis/analyze.js.map +1 -1
  3. package/dist/analysis/runtime.js.map +1 -1
  4. package/dist/assets.js.map +1 -1
  5. package/dist/constants.js.map +1 -1
  6. package/dist/derivation/derive.js.map +1 -1
  7. package/dist/derivation/engine.js.map +1 -1
  8. package/dist/errors.js.map +1 -1
  9. package/dist/feature-model/convert.js.map +1 -1
  10. package/dist/feature-model/engine.js.map +1 -1
  11. package/dist/feature-model/inspect.js.map +1 -1
  12. package/dist/feature-model/io.js.map +1 -1
  13. package/dist/feature-model/parse.js.map +1 -1
  14. package/dist/feature-model/text.js.map +1 -1
  15. package/dist/fs/archive.js.map +1 -1
  16. package/dist/fs/diff.js.map +1 -1
  17. package/dist/fs/format.js.map +1 -1
  18. package/dist/fs/workspace.js.map +1 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/internal/guards.js.map +1 -1
  21. package/dist/line/platform-files.js.map +1 -1
  22. package/dist/line/scaffold.js.map +1 -1
  23. package/dist/line/templates/core/extra.js +54 -54
  24. package/dist/line/templates/core/transformation.js +196 -196
  25. package/dist/line/templates/metamodels/dataModel/extra.js +328 -328
  26. package/dist/line/templates/metamodels/dataModel/transformation.js +211 -211
  27. package/dist/line/templates/metamodels/sensor/extra.js +36 -36
  28. package/dist/line/templates/metamodels/sensor/transformation.js +47 -47
  29. package/dist/line/templates/pipeline/.gitlab-ci.yml +51 -51
  30. package/dist/line/templates/pipeline/ci/test-client.sh +16 -16
  31. package/dist/line/templates/pipeline/ci/test-server.sh +16 -16
  32. package/dist/product/engine-spec.js.map +1 -1
  33. package/dist/product/spec.js.map +1 -1
  34. package/dist/product/version.js.map +1 -1
  35. package/dist/products-index/products-index.js.map +1 -1
  36. package/dist/selection/selection.js.map +1 -1
  37. package/package.json +67 -67
@@ -1,51 +1,51 @@
1
- #
2
- # A pipeline is composed of independent jobs that run scripts, grouped into stages.
3
- # Stages run in sequential order, but jobs within stages run in parallel.
4
- #
5
- # For more information, see: https://docs.gitlab.com/ee/ci/yaml/index.html#stages
6
-
7
- stages:
8
- - test
9
-
10
- # Test commands live in ci/test-server.sh and ci/test-client.sh.
11
- # Domain engineers edit those scripts to wire in real tests; this YAML should
12
- # not need changes.
13
-
14
- test_server:
15
- stage: test
16
- image: gradle:8-jdk21
17
- variables:
18
- GRADLE_USER_HOME: "$CI_PROJECT_DIR/.gradle"
19
- script:
20
- - sh ./ci/test-server.sh
21
- cache:
22
- key: gradle-$CI_COMMIT_REF_SLUG
23
- paths:
24
- - .gradle/caches
25
- - .gradle/wrapper
26
- artifacts:
27
- when: always
28
- reports:
29
- junit: server/build/test-results/test/**/TEST-*.xml
30
- expire_in: 1 week
31
- rules:
32
- - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
33
- - if: '$CI_COMMIT_BRANCH'
34
-
35
- test_client:
36
- stage: test
37
- image: node:20
38
- script:
39
- - sh ./ci/test-client.sh
40
- cache:
41
- key: node-$CI_COMMIT_REF_SLUG
42
- paths:
43
- - client/node_modules
44
- artifacts:
45
- when: always
46
- reports:
47
- junit: client/test-results/**/junit*.xml
48
- expire_in: 1 week
49
- rules:
50
- - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
51
- - if: '$CI_COMMIT_BRANCH'
1
+ #
2
+ # A pipeline is composed of independent jobs that run scripts, grouped into stages.
3
+ # Stages run in sequential order, but jobs within stages run in parallel.
4
+ #
5
+ # For more information, see: https://docs.gitlab.com/ee/ci/yaml/index.html#stages
6
+
7
+ stages:
8
+ - test
9
+
10
+ # Test commands live in ci/test-server.sh and ci/test-client.sh.
11
+ # Domain engineers edit those scripts to wire in real tests; this YAML should
12
+ # not need changes.
13
+
14
+ test_server:
15
+ stage: test
16
+ image: gradle:8-jdk21
17
+ variables:
18
+ GRADLE_USER_HOME: "$CI_PROJECT_DIR/.gradle"
19
+ script:
20
+ - sh ./ci/test-server.sh
21
+ cache:
22
+ key: gradle-$CI_COMMIT_REF_SLUG
23
+ paths:
24
+ - .gradle/caches
25
+ - .gradle/wrapper
26
+ artifacts:
27
+ when: always
28
+ reports:
29
+ junit: server/build/test-results/test/**/TEST-*.xml
30
+ expire_in: 1 week
31
+ rules:
32
+ - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
33
+ - if: '$CI_COMMIT_BRANCH'
34
+
35
+ test_client:
36
+ stage: test
37
+ image: node:20
38
+ script:
39
+ - sh ./ci/test-client.sh
40
+ cache:
41
+ key: node-$CI_COMMIT_REF_SLUG
42
+ paths:
43
+ - client/node_modules
44
+ artifacts:
45
+ when: always
46
+ reports:
47
+ junit: client/test-results/**/junit*.xml
48
+ expire_in: 1 week
49
+ rules:
50
+ - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
51
+ - if: '$CI_COMMIT_BRANCH'
@@ -1,16 +1,16 @@
1
- #!/bin/sh
2
- #
3
- # Client test command for this product.
4
- #
5
- # Default is a no-op (exit 0) so generated products with no tests yield a
6
- # green pipeline. Replace the echo+exit below with the real test command,
7
- # e.g.:
8
- #
9
- # cd client && npm ci && npm test
10
- # cd client && yarn install --frozen-lockfile && yarn test
11
- #
12
- # Any non-zero exit will fail the test_client job in .gitlab-ci.yml.
13
-
14
- echo "[test-client] No client tests defined for this product."
15
- echo "[test-client] Edit ci/test-client.sh to wire in real tests."
16
- exit 0
1
+ #!/bin/sh
2
+ #
3
+ # Client test command for this product.
4
+ #
5
+ # Default is a no-op (exit 0) so generated products with no tests yield a
6
+ # green pipeline. Replace the echo+exit below with the real test command,
7
+ # e.g.:
8
+ #
9
+ # cd client && npm ci && npm test
10
+ # cd client && yarn install --frozen-lockfile && yarn test
11
+ #
12
+ # Any non-zero exit will fail the test_client job in .gitlab-ci.yml.
13
+
14
+ echo "[test-client] No client tests defined for this product."
15
+ echo "[test-client] Edit ci/test-client.sh to wire in real tests."
16
+ exit 0
@@ -1,16 +1,16 @@
1
- #!/bin/sh
2
- #
3
- # Server test command for this product.
4
- #
5
- # Default is a no-op (exit 0) so generated products with no tests yield a
6
- # green pipeline. Replace the echo+exit below with the real test command,
7
- # e.g.:
8
- #
9
- # cd server && ./gradlew test
10
- # cd server && mvn test
11
- #
12
- # Any non-zero exit will fail the test_server job in .gitlab-ci.yml.
13
-
14
- echo "[test-server] No server tests defined for this product."
15
- echo "[test-server] Edit ci/test-server.sh to wire in real tests."
16
- exit 0
1
+ #!/bin/sh
2
+ #
3
+ # Server test command for this product.
4
+ #
5
+ # Default is a no-op (exit 0) so generated products with no tests yield a
6
+ # green pipeline. Replace the echo+exit below with the real test command,
7
+ # e.g.:
8
+ #
9
+ # cd server && ./gradlew test
10
+ # cd server && mvn test
11
+ #
12
+ # Any non-zero exit will fail the test_server job in .gitlab-ci.yml.
13
+
14
+ echo "[test-server] No server tests defined for this product."
15
+ echo "[test-server] Edit ci/test-server.sh to wire in real tests."
16
+ exit 0
@@ -1 +1 @@
1
- {"version":3,"file":"engine-spec.js","sourceRoot":"","sources":["../../src/product/engine-spec.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAUrD;;;;;;;;;GASG;AACH,8EAA8E;AAC9E,gFAAgF;AAChF,4CAA4C;AAC5C,wEAAwE;AACxE,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAE,QAAiB,EAAW,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAA;AAE3F;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,EAAE,IAAI,EAAyB,EAA4B,EAAE;IAC3F,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC;QACzB,MAAM,IAAI,oBAAoB,CAAC,2BAA2B,CAAC,CAAA;IAC7D,CAAC;IAED,MAAM,MAAM,GAAG,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAA;IAC1E,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;QAAE,OAAO,IAAI,CAAA;IAEvC,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;IACvE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,SAAS,CAAC;QAAE,OAAO,IAAI,CAAA;IAEzF,MAAM,aAAa,GAAG,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAA;IAEhF,OAAO;QACL,QAAQ,EAAE,MAAM,CAAC,QAAoB;QACrC,IAAI,EAAE;YACJ,GAAG,UAAU;YACb,SAAS,EAAE;gBACT,GAAG,UAAU,CAAC,SAAS;gBACvB,QAAQ,EAAE,QAAQ,CAAC,aAAa,EAAE,QAAQ,EAAE,EAAE,CAAC;gBAC/C,qEAAqE;gBACrE,mDAAmD;gBACnD,OAAO,EAAE,aAAa,EAAE,OAAO;aAChC;SACF;KACF,CAAA;AACH,CAAC,CAAA","sourcesContent":["/**\r\n * Adapts a product spec to the shape `spl-js-engine` expects.\r\n *\r\n * HARDENED PORT of\r\n * `linea/server/src/model/services/generatePipeline.js:buildEngineSpec` (~34-50).\r\n * The original guards the shortcut with plain truthiness\r\n * (`parsed?.features && parsed?.data?.basicData`), so a spec with\r\n * `sensor.parsed.features = 'ABC'` takes the shortcut and hands the engine a\r\n * string where it expects an array. Here the checks are `Array.isArray` and\r\n * `isPlainObject`, so such a spec passes through untouched instead.\r\n * Its comment explains the intent: when a product carries a parsed sensor DSL,\r\n * pipe it straight to the engine's shortcut path, which activates when both\r\n * `input.data` and `input.data.basicData` are present (see the mock platform's\r\n * `transformation.js:modelTransformation`). Otherwise the spec passes through.\r\n *\r\n * The sensor DSL itself is out of scope for linea-core in this batch; this\r\n * function only routes an ALREADY parsed `sensor.parsed` payload, which is why it\r\n * needs no DSL dependency.\r\n */\r\nimport { InvalidArgumentError } from '../errors.js'\r\nimport { isPlainObject } from '../internal/guards.js'\r\nimport type { ProductSpec } from './spec.js'\r\n\r\n/** A spec in the engine's shortcut shape. */\r\nexport interface EngineSpec {\r\n features: string[]\r\n data: Record<string, unknown>\r\n [key: string]: unknown\r\n}\r\n\r\n/**\r\n * Reproduces the monolith's `spec.basicData?.database || {}`.\r\n *\r\n * `??` would NOT be equivalent: `||` also replaces falsy non-nullish values\r\n * (`''`, `0`, `0n`, `false`, `NaN`). The schema types `database` as an Object so\r\n * the difference is unreachable in practice, but parity is parity and a silent\r\n * behaviour change here would be invisible until a generation produced the wrong\r\n * config. Written as a ternary on the value itself, which IS `||` by definition\r\n * and therefore cannot drift from it.\r\n */\r\n// NOTE: `??` is precisely the WRONG operator here. The monolith uses `||`, so\r\n// falsy non-nullish values must fall back too; that is the entire point of this\r\n// helper, and the lint rule cannot know it.\r\n// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\r\nconst truthyOr = (value: unknown, fallback: unknown): unknown => (value ? value : fallback)\r\n\r\n/**\r\n * Builds the spec handed to `DerivationEngine.generateProduct` / `generateZip`.\r\n *\r\n * Returns the input spec **by reference** when there is no sensor shortcut to\r\n * apply, exactly like the monolith — `generatePipeline.test.js:23-35` asserts\r\n * identity with `toBe(spec)`, so that is contractual, not incidental.\r\n *\r\n * The shortcut applies only when `spec.sensor.parsed` has BOTH `features` and\r\n * `data.basicData`. In that case `database` and `version` are carried over from\r\n * the product's own `basicData`, with `database` defaulting to `{}`.\r\n *\r\n * @param params.spec The product spec.\r\n * @returns Either the same spec, or a new object in the engine shortcut shape.\r\n * @throws {InvalidArgumentError} when `spec` is not an object.\r\n */\r\nexport const buildEngineSpec = ({ spec }: { spec: ProductSpec }): ProductSpec | EngineSpec => {\r\n if (!isPlainObject(spec)) {\r\n throw new InvalidArgumentError('\"spec\" must be an object.')\r\n }\r\n\r\n const parsed = isPlainObject(spec.sensor) ? spec.sensor.parsed : undefined\r\n if (!isPlainObject(parsed)) return spec\r\n\r\n const parsedData = isPlainObject(parsed.data) ? parsed.data : undefined\r\n if (!Array.isArray(parsed.features) || !isPlainObject(parsedData?.basicData)) return spec\r\n\r\n const specBasicData = isPlainObject(spec.basicData) ? spec.basicData : undefined\r\n\r\n return {\r\n features: parsed.features as string[],\r\n data: {\r\n ...parsedData,\r\n basicData: {\r\n ...parsedData.basicData,\r\n database: truthyOr(specBasicData?.database, {}),\r\n // No default: the monolith passes `spec.basicData?.version` straight\r\n // through, so an absent version stays `undefined`.\r\n version: specBasicData?.version\r\n }\r\n }\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"engine-spec.js","sourceRoot":"","sources":["../../src/product/engine-spec.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAUrD;;;;;;;;;GASG;AACH,8EAA8E;AAC9E,gFAAgF;AAChF,4CAA4C;AAC5C,wEAAwE;AACxE,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAE,QAAiB,EAAW,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAA;AAE3F;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,EAAE,IAAI,EAAyB,EAA4B,EAAE;IAC3F,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC;QACzB,MAAM,IAAI,oBAAoB,CAAC,2BAA2B,CAAC,CAAA;IAC7D,CAAC;IAED,MAAM,MAAM,GAAG,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAA;IAC1E,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;QAAE,OAAO,IAAI,CAAA;IAEvC,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;IACvE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,SAAS,CAAC;QAAE,OAAO,IAAI,CAAA;IAEzF,MAAM,aAAa,GAAG,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAA;IAEhF,OAAO;QACL,QAAQ,EAAE,MAAM,CAAC,QAAoB;QACrC,IAAI,EAAE;YACJ,GAAG,UAAU;YACb,SAAS,EAAE;gBACT,GAAG,UAAU,CAAC,SAAS;gBACvB,QAAQ,EAAE,QAAQ,CAAC,aAAa,EAAE,QAAQ,EAAE,EAAE,CAAC;gBAC/C,qEAAqE;gBACrE,mDAAmD;gBACnD,OAAO,EAAE,aAAa,EAAE,OAAO;aAChC;SACF;KACF,CAAA;AACH,CAAC,CAAA","sourcesContent":["/**\n * Adapts a product spec to the shape `spl-js-engine` expects.\n *\n * HARDENED PORT of\n * `linea/server/src/model/services/generatePipeline.js:buildEngineSpec` (~34-50).\n * The original guards the shortcut with plain truthiness\n * (`parsed?.features && parsed?.data?.basicData`), so a spec with\n * `sensor.parsed.features = 'ABC'` takes the shortcut and hands the engine a\n * string where it expects an array. Here the checks are `Array.isArray` and\n * `isPlainObject`, so such a spec passes through untouched instead.\n * Its comment explains the intent: when a product carries a parsed sensor DSL,\n * pipe it straight to the engine's shortcut path, which activates when both\n * `input.data` and `input.data.basicData` are present (see the mock platform's\n * `transformation.js:modelTransformation`). Otherwise the spec passes through.\n *\n * The sensor DSL itself is out of scope for linea-core in this batch; this\n * function only routes an ALREADY parsed `sensor.parsed` payload, which is why it\n * needs no DSL dependency.\n */\nimport { InvalidArgumentError } from '../errors.js'\nimport { isPlainObject } from '../internal/guards.js'\nimport type { ProductSpec } from './spec.js'\n\n/** A spec in the engine's shortcut shape. */\nexport interface EngineSpec {\n features: string[]\n data: Record<string, unknown>\n [key: string]: unknown\n}\n\n/**\n * Reproduces the monolith's `spec.basicData?.database || {}`.\n *\n * `??` would NOT be equivalent: `||` also replaces falsy non-nullish values\n * (`''`, `0`, `0n`, `false`, `NaN`). The schema types `database` as an Object so\n * the difference is unreachable in practice, but parity is parity and a silent\n * behaviour change here would be invisible until a generation produced the wrong\n * config. Written as a ternary on the value itself, which IS `||` by definition\n * and therefore cannot drift from it.\n */\n// NOTE: `??` is precisely the WRONG operator here. The monolith uses `||`, so\n// falsy non-nullish values must fall back too; that is the entire point of this\n// helper, and the lint rule cannot know it.\n// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\nconst truthyOr = (value: unknown, fallback: unknown): unknown => (value ? value : fallback)\n\n/**\n * Builds the spec handed to `DerivationEngine.generateProduct` / `generateZip`.\n *\n * Returns the input spec **by reference** when there is no sensor shortcut to\n * apply, exactly like the monolith — `generatePipeline.test.js:23-35` asserts\n * identity with `toBe(spec)`, so that is contractual, not incidental.\n *\n * The shortcut applies only when `spec.sensor.parsed` has BOTH `features` and\n * `data.basicData`. In that case `database` and `version` are carried over from\n * the product's own `basicData`, with `database` defaulting to `{}`.\n *\n * @param params.spec The product spec.\n * @returns Either the same spec, or a new object in the engine shortcut shape.\n * @throws {InvalidArgumentError} when `spec` is not an object.\n */\nexport const buildEngineSpec = ({ spec }: { spec: ProductSpec }): ProductSpec | EngineSpec => {\n if (!isPlainObject(spec)) {\n throw new InvalidArgumentError('\"spec\" must be an object.')\n }\n\n const parsed = isPlainObject(spec.sensor) ? spec.sensor.parsed : undefined\n if (!isPlainObject(parsed)) return spec\n\n const parsedData = isPlainObject(parsed.data) ? parsed.data : undefined\n if (!Array.isArray(parsed.features) || !isPlainObject(parsedData?.basicData)) return spec\n\n const specBasicData = isPlainObject(spec.basicData) ? spec.basicData : undefined\n\n return {\n features: parsed.features as string[],\n data: {\n ...parsedData,\n basicData: {\n ...parsedData.basicData,\n database: truthyOr(specBasicData?.database, {}),\n // No default: the monolith passes `spec.basicData?.version` straight\n // through, so an absent version stays `undefined`.\n version: specBasicData?.version\n }\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"spec.js","sourceRoot":"","sources":["../../src/product/spec.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,YAAY,EACZ,eAAe,EAChB,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAA;AAC5E,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAuErD;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,EAAE,IAAI,EAAqB,EAAyB,EAAE;IACxF,MAAM,MAAM,GAAuB,EAAE,CAAA;IAErC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC;QACzB,OAAO;YACL,KAAK,EAAE,KAAK;YACZ,MAAM,EAAE,CAAC;oBACP,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,iBAAiB;oBACvB,UAAU,EAAE,uCAAuC;iBACpD,CAAC;SACH,CAAA;IACH,CAAC;IAED,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,CAAA;IAChC,IAAI,CAAC,aA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AC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;SAClE;QACD,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC;YACpC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC;YACpB,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC;gBAC5B,CAAC,CAAC,EAAE,GAAG,IAAI,CAAC,QAAQ,EAAE;gBACtB,CAAC,CAAC,EAAE;QACR,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;QAC7D,MAAM,EAAE;YACN,GAAG,MAAM;YACT,GAAG,EAAE,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE;YACrD,MAAM,EAAE,MAAM,CAAC,MAAM,IAAI,IAAI;SAC9B;KACF,CAAA;AACH,CAAC,CAAA","sourcesContent":["/**\r\n * Product spec validation and default filling.\r\n *\r\n * Migrated from:\r\n * - `linea/server/src/rest/validators/productValidators.js` (createProductValidator,\r\n * updateProductValidator) and `commonValidators.js` (`nameRule`, `versionRule`)\r\n * - `linea/server/src/model/entities/product.js` — the Mongoose schema defaults\r\n * - `linea/server/src/model/services/generatePipeline.js:saveProductVersion`\r\n * (~212-222) — the defaults applied right before returning a generated product\r\n *\r\n * The monolith validates at the HTTP edge with express-validator and fills\r\n * defaults twice: once through the Mongoose schema and once again in\r\n * `saveProductVersion`. Neither mechanism exists in linea-core, so both collapse\r\n * into these two functions.\r\n *\r\n * `linea-cli/src/core/specSchema.ts` duplicates the same rules with Zod today and\r\n * is meant to call this instead.\r\n */\r\nimport {\r\n DEFAULT_LANGUAGES,\r\n DEFAULT_SRID,\r\n NAME_PATTERN,\r\n VERSION_PATTERN\r\n} from '../constants.js'\r\nimport { InvalidArgumentError, InvalidProductSpecError } from '../errors.js'\r\nimport { isPlainObject } from '../internal/guards.js'\r\n\r\n/** `spec.basicData` — product identity and generation-wide settings. */\r\nexport interface ProductBasicData {\r\n name?: string\r\n version?: string\r\n languages?: string[]\r\n SRID?: string\r\n database?: Record<string, unknown>\r\n extra?: Record<string, unknown>\r\n testEnvironment?: { image?: string, command?: string }\r\n createdAt?: unknown\r\n [key: string]: unknown\r\n}\r\n\r\n/** A product spec as stored by the monolith and consumed by the engine. */\r\nexport interface ProductSpec {\r\n basicData?: ProductBasicData\r\n dataModel?: { cells?: unknown[], [key: string]: unknown }\r\n features?: string[] | Record<string, boolean>\r\n statics?: unknown[]\r\n sensor?: { dsl?: string, parsed?: unknown }\r\n /** Legacy feature-selection field. */\r\n selection?: string[]\r\n [key: string]: unknown\r\n}\r\n\r\n/** A single spec problem. */\r\nexport interface ProductSpecError {\r\n /** Dotted path of the offending field, e.g. `spec.basicData.name`. */\r\n readonly path: string\r\n /** Stable machine-readable discriminator. */\r\n readonly code: ProductSpecErrorCode\r\n /**\r\n * An i18n KEY, never a human-readable sentence. Always pass it through the\r\n * consumer's translation function; there is nothing sensible to render raw.\r\n *\r\n * Five keys are INHERITED verbatim from the monolith and already have\r\n * translations in `linea/client/src/i18n/{en,es,gl}`:\r\n * `spec_object_validation`, `basicData_object_validation`,\r\n * `basicData_name_validation`, `invalid_name_characters`,\r\n * `basicData_version_format`.\r\n *\r\n * Four keys are NEW and have NO translation yet, because the monolith enforced\r\n * these constraints through the Mongoose schema rather than express-validator,\r\n * so there was no key to copy: `basicData_languages_validation`,\r\n * `basicData_SRID_validation`, `spec_features_validation`,\r\n * `spec_statics_validation`. Until webui and linea-cli add them, vue-i18n will\r\n * render the key itself. Tracked in CHANGELOG.md.\r\n */\r\n readonly messageKey: string\r\n}\r\n\r\n/** Stable discriminators for spec problems. */\r\nexport type ProductSpecErrorCode =\r\n | 'SPEC_NOT_OBJECT'\r\n | 'BASIC_DATA_NOT_OBJECT'\r\n | 'NAME_REQUIRED'\r\n | 'NAME_INVALID_CHARACTERS'\r\n | 'VERSION_FORMAT'\r\n | 'LANGUAGES_NOT_STRING_ARRAY'\r\n | 'SRID_NOT_STRING'\r\n | 'FEATURES_INVALID_SHAPE'\r\n | 'STATICS_NOT_ARRAY'\r\n\r\n/** Result of validating a spec. */\r\nexport interface ProductSpecValidation {\r\n readonly valid: boolean\r\n readonly errors: ProductSpecError[]\r\n}\r\n\r\n/**\r\n * Validates a product spec **without throwing**.\r\n *\r\n * Reproduces `createProductValidator` / `updateProductValidator` with their exact\r\n * i18n keys, and ADDS shape checks for the fields whose type the Mongoose schema\r\n * used to enforce (`languages`, `SRID`, `features`, `statics`). Those four carry\r\n * new keys with no translation yet — see `ProductSpecError.messageKey`.\r\n *\r\n * `lineId` is NOT validated here: it is a GitLab/persistence concern that lives\r\n * in linea-server (ADR-003), even though `createProductValidator` checks it.\r\n *\r\n * @param params.spec The spec to validate. Anything, including nullish.\r\n * @returns `valid` plus one entry per problem, in a stable order.\r\n */\r\nexport const validateProductSpec = ({ spec }: { spec: unknown }): ProductSpecValidation => {\r\n const errors: ProductSpecError[] = []\r\n\r\n if (!isPlainObject(spec)) {\r\n return {\r\n valid: false,\r\n errors: [{\r\n path: 'spec',\r\n code: 'SPEC_NOT_OBJECT',\r\n messageKey: 'error_messages.spec_object_validation'\r\n }]\r\n }\r\n }\r\n\r\n const basicData = spec.basicData\r\n if (!isPlainObject(basicData)) {\r\n return {\r\n valid: false,\r\n errors: [{\r\n path: 'spec.basicData',\r\n code: 'BASIC_DATA_NOT_OBJECT',\r\n messageKey: 'error_messages.basicData_object_validation'\r\n }]\r\n }\r\n }\r\n\r\n const name = basicData.name\r\n if (typeof name !== 'string' || name === '') {\r\n errors.push({\r\n path: 'spec.basicData.name',\r\n code: 'NAME_REQUIRED',\r\n messageKey: 'error_messages.basicData_name_validation'\r\n })\r\n } else if (!NAME_PATTERN.test(name)) {\r\n errors.push({\r\n path: 'spec.basicData.name',\r\n code: 'NAME_INVALID_CHARACTERS',\r\n messageKey: 'error_messages.invalid_name_characters'\r\n })\r\n }\r\n\r\n if (typeof basicData.version !== 'string' || !VERSION_PATTERN.test(basicData.version)) {\r\n errors.push({\r\n path: 'spec.basicData.version',\r\n code: 'VERSION_FORMAT',\r\n messageKey: 'error_messages.basicData_version_format'\r\n })\r\n }\r\n\r\n const { languages } = basicData\r\n if (\r\n languages !== undefined &&\r\n (!Array.isArray(languages) || languages.some((l) => typeof l !== 'string'))\r\n ) {\r\n errors.push({\r\n path: 'spec.basicData.languages',\r\n code: 'LANGUAGES_NOT_STRING_ARRAY',\r\n messageKey: 'error_messages.basicData_languages_validation'\r\n })\r\n }\r\n\r\n if (basicData.SRID !== undefined && typeof basicData.SRID !== 'string') {\r\n errors.push({\r\n path: 'spec.basicData.SRID',\r\n code: 'SRID_NOT_STRING',\r\n messageKey: 'error_messages.basicData_SRID_validation'\r\n })\r\n }\r\n\r\n const { features } = spec\r\n const featuresValid =\r\n features === undefined ||\r\n (Array.isArray(features) && features.every((f) => typeof f === 'string')) ||\r\n isPlainObject(features)\r\n if (!featuresValid) {\r\n errors.push({\r\n path: 'spec.features',\r\n code: 'FEATURES_INVALID_SHAPE',\r\n messageKey: 'error_messages.spec_features_validation'\r\n })\r\n }\r\n\r\n if (spec.statics !== undefined && !Array.isArray(spec.statics)) {\r\n errors.push({\r\n path: 'spec.statics',\r\n code: 'STATICS_NOT_ARRAY',\r\n messageKey: 'error_messages.spec_statics_validation'\r\n })\r\n }\r\n\r\n return { valid: errors.length === 0, errors }\r\n}\r\n\r\n/**\r\n * Validates a product spec and throws when it is not acceptable.\r\n *\r\n * The throwing counterpart of `validateProductSpec`, mirroring the\r\n * `validateFeatureSelection` / `assertFeatureSelection` pair. It is what makes\r\n * `InvalidProductSpecError` reachable: the monolith's equivalent is\r\n * express-validator short-circuiting the request with a 400 before\r\n * `ProductService.createProduct` ever runs, which has no direct analogue in a\r\n * library.\r\n *\r\n * The message lists every problem with its i18n key. Callers that need the\r\n * problems as DATA (to build an HTTP response body, say) should call\r\n * `validateProductSpec` instead — that is precisely what it is for, and it keeps\r\n * this error free of ad-hoc payload properties.\r\n *\r\n * @param params.spec The spec to validate.\r\n * @returns The spec, unchanged, when it is valid.\r\n * @throws {InvalidProductSpecError} listing every problem found.\r\n */\r\nexport const assertProductSpec = ({ spec }: { spec: ProductSpec }): ProductSpec => {\r\n const { valid, errors } = validateProductSpec({ spec })\r\n if (!valid) {\r\n const summary = errors.map((error) => `${error.path}: ${error.messageKey}`).join('; ')\r\n throw new InvalidProductSpecError(`Invalid product spec: ${summary}`)\r\n }\r\n return spec\r\n}\r\n\r\n/**\r\n * Fills a product spec with the domain defaults.\r\n *\r\n * Union of the two places the monolith applies defaults:\r\n * - `entities/product.js` (Mongoose schema): `version` `'0.0.0'`, `database` `{}`,\r\n * `extra` `{}`, `testEnvironment` `{ image: '', command: '' }`, `languages`\r\n * `['en','es','gl']`, `SRID` `'4326'`, `dataModel.cells` `[]`, `features` `[]`,\r\n * `statics` `[]`, `sensor` `{ dsl: '', parsed: null }`.\r\n * - `generatePipeline.js:saveProductVersion` (~212-222), which re-applies\r\n * `database`, `extra`, `languages` and `SRID` with `||` right before returning.\r\n *\r\n * `||` semantics are preserved for those four, which is subtler than it looks:\r\n * an empty-string `SRID` falls back to `'4326'` because `''` is falsy, but an\r\n * EMPTY `languages` array is kept because `[]` is truthy. Both match the monolith.\r\n *\r\n * PURE: returns a new object and never mutates the input. `basicData.createdAt`\r\n * is deliberately NOT filled — the schema defaults it to `Date.now`, which would\r\n * make this function non-deterministic. Timestamping is persistence metadata and\r\n * belongs to linea-server.\r\n *\r\n * @param params.spec The spec to complete.\r\n * @returns A new spec with defaults applied.\r\n * @throws {InvalidArgumentError} when `spec` is not an object.\r\n */\r\nexport const normalizeProductSpec = ({ spec }: { spec: ProductSpec }): ProductSpec => {\r\n if (!isPlainObject(spec)) {\r\n throw new InvalidArgumentError('\"spec\" must be an object.')\r\n }\r\n const basicData = isPlainObject(spec.basicData) ? spec.basicData : {}\r\n const dataModel = isPlainObject(spec.dataModel) ? spec.dataModel : {}\r\n const sensor = isPlainObject(spec.sensor) ? spec.sensor : {}\r\n const testEnvironment = isPlainObject(basicData.testEnvironment)\r\n ? basicData.testEnvironment\r\n : {}\r\n\r\n const { languages } = basicData\r\n\r\n return {\r\n ...spec,\r\n basicData: {\r\n ...basicData,\r\n name: typeof basicData.name === 'string' ? basicData.name : '',\r\n version: typeof basicData.version === 'string' && basicData.version !== ''\r\n ? basicData.version\r\n : '0.0.0',\r\n database: isPlainObject(basicData.database) ? basicData.database : {},\r\n extra: isPlainObject(basicData.extra) ? basicData.extra : {},\r\n testEnvironment: {\r\n image: typeof testEnvironment.image === 'string' ? testEnvironment.image : '',\r\n command: typeof testEnvironment.command === 'string' ? testEnvironment.command : ''\r\n },\r\n // An EMPTY array is kept. `saveProductVersion` uses `languages || [...]`\r\n // and `[]` is truthy in JavaScript, so the monolith preserves it; the\r\n // Mongoose default only fires when the path is `undefined`. A user who\r\n // deselected every language must generate the same product here.\r\n languages: Array.isArray(languages) ? [...languages] : [...DEFAULT_LANGUAGES],\r\n SRID: typeof basicData.SRID === 'string' && basicData.SRID !== ''\r\n ? basicData.SRID\r\n : DEFAULT_SRID\r\n },\r\n dataModel: {\r\n ...dataModel,\r\n cells: Array.isArray(dataModel.cells) ? [...dataModel.cells] : []\r\n },\r\n features: Array.isArray(spec.features)\r\n ? [...spec.features]\r\n : isPlainObject(spec.features)\r\n ? { ...spec.features }\r\n : [],\r\n statics: Array.isArray(spec.statics) ? [...spec.statics] : [],\r\n sensor: {\r\n ...sensor,\r\n dsl: typeof sensor.dsl === 'string' ? sensor.dsl : '',\r\n parsed: sensor.parsed ?? null\r\n }\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"spec.js","sourceRoot":"","sources":["../../src/product/spec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AAG,MAAM;YACT,GAAG,EAAE,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE;YACrD,MAAM,EAAE,MAAM,CAAC,MAAM,IAAI,IAAI;SAC9B;KACF,CAAA;AACH,CAAC,CAAA","sourcesContent":["/**\n * Product spec validation and default filling.\n *\n * Migrated from:\n * - `linea/server/src/rest/validators/productValidators.js` (createProductValidator,\n * updateProductValidator) and `commonValidators.js` (`nameRule`, `versionRule`)\n * - `linea/server/src/model/entities/product.js` — the Mongoose schema defaults\n * - `linea/server/src/model/services/generatePipeline.js:saveProductVersion`\n * (~212-222) — the defaults applied right before returning a generated product\n *\n * The monolith validates at the HTTP edge with express-validator and fills\n * defaults twice: once through the Mongoose schema and once again in\n * `saveProductVersion`. Neither mechanism exists in linea-core, so both collapse\n * into these two functions.\n *\n * `linea-cli/src/core/specSchema.ts` duplicates the same rules with Zod today and\n * is meant to call this instead.\n */\nimport {\n DEFAULT_LANGUAGES,\n DEFAULT_SRID,\n NAME_PATTERN,\n VERSION_PATTERN\n} from '../constants.js'\nimport { InvalidArgumentError, InvalidProductSpecError } from '../errors.js'\nimport { isPlainObject } from '../internal/guards.js'\n\n/** `spec.basicData` — product identity and generation-wide settings. */\nexport interface ProductBasicData {\n name?: string\n version?: string\n languages?: string[]\n SRID?: string\n database?: Record<string, unknown>\n extra?: Record<string, unknown>\n testEnvironment?: { image?: string, command?: string }\n createdAt?: unknown\n [key: string]: unknown\n}\n\n/** A product spec as stored by the monolith and consumed by the engine. */\nexport interface ProductSpec {\n basicData?: ProductBasicData\n dataModel?: { cells?: unknown[], [key: string]: unknown }\n features?: string[] | Record<string, boolean>\n statics?: unknown[]\n sensor?: { dsl?: string, parsed?: unknown }\n /** Legacy feature-selection field. */\n selection?: string[]\n [key: string]: unknown\n}\n\n/** A single spec problem. */\nexport interface ProductSpecError {\n /** Dotted path of the offending field, e.g. `spec.basicData.name`. */\n readonly path: string\n /** Stable machine-readable discriminator. */\n readonly code: ProductSpecErrorCode\n /**\n * An i18n KEY, never a human-readable sentence. Always pass it through the\n * consumer's translation function; there is nothing sensible to render raw.\n *\n * Five keys are INHERITED verbatim from the monolith and already have\n * translations in `linea/client/src/i18n/{en,es,gl}`:\n * `spec_object_validation`, `basicData_object_validation`,\n * `basicData_name_validation`, `invalid_name_characters`,\n * `basicData_version_format`.\n *\n * Four keys are NEW and have NO translation yet, because the monolith enforced\n * these constraints through the Mongoose schema rather than express-validator,\n * so there was no key to copy: `basicData_languages_validation`,\n * `basicData_SRID_validation`, `spec_features_validation`,\n * `spec_statics_validation`. Until webui and linea-cli add them, vue-i18n will\n * render the key itself. Tracked in CHANGELOG.md.\n */\n readonly messageKey: string\n}\n\n/** Stable discriminators for spec problems. */\nexport type ProductSpecErrorCode =\n | 'SPEC_NOT_OBJECT'\n | 'BASIC_DATA_NOT_OBJECT'\n | 'NAME_REQUIRED'\n | 'NAME_INVALID_CHARACTERS'\n | 'VERSION_FORMAT'\n | 'LANGUAGES_NOT_STRING_ARRAY'\n | 'SRID_NOT_STRING'\n | 'FEATURES_INVALID_SHAPE'\n | 'STATICS_NOT_ARRAY'\n\n/** Result of validating a spec. */\nexport interface ProductSpecValidation {\n readonly valid: boolean\n readonly errors: ProductSpecError[]\n}\n\n/**\n * Validates a product spec **without throwing**.\n *\n * Reproduces `createProductValidator` / `updateProductValidator` with their exact\n * i18n keys, and ADDS shape checks for the fields whose type the Mongoose schema\n * used to enforce (`languages`, `SRID`, `features`, `statics`). Those four carry\n * new keys with no translation yet — see `ProductSpecError.messageKey`.\n *\n * `lineId` is NOT validated here: it is a GitLab/persistence concern that lives\n * in linea-server (ADR-003), even though `createProductValidator` checks it.\n *\n * @param params.spec The spec to validate. Anything, including nullish.\n * @returns `valid` plus one entry per problem, in a stable order.\n */\nexport const validateProductSpec = ({ spec }: { spec: unknown }): ProductSpecValidation => {\n const errors: ProductSpecError[] = []\n\n if (!isPlainObject(spec)) {\n return {\n valid: false,\n errors: [{\n path: 'spec',\n code: 'SPEC_NOT_OBJECT',\n messageKey: 'error_messages.spec_object_validation'\n }]\n }\n }\n\n const basicData = spec.basicData\n if (!isPlainObject(basicData)) {\n return {\n valid: false,\n errors: [{\n path: 'spec.basicData',\n code: 'BASIC_DATA_NOT_OBJECT',\n messageKey: 'error_messages.basicData_object_validation'\n }]\n }\n }\n\n const name = basicData.name\n if (typeof name !== 'string' || name === '') {\n errors.push({\n path: 'spec.basicData.name',\n code: 'NAME_REQUIRED',\n messageKey: 'error_messages.basicData_name_validation'\n })\n } else if (!NAME_PATTERN.test(name)) {\n errors.push({\n path: 'spec.basicData.name',\n code: 'NAME_INVALID_CHARACTERS',\n messageKey: 'error_messages.invalid_name_characters'\n })\n }\n\n if (typeof basicData.version !== 'string' || !VERSION_PATTERN.test(basicData.version)) {\n errors.push({\n path: 'spec.basicData.version',\n code: 'VERSION_FORMAT',\n messageKey: 'error_messages.basicData_version_format'\n })\n }\n\n const { languages } = basicData\n if (\n languages !== undefined &&\n (!Array.isArray(languages) || languages.some((l) => typeof l !== 'string'))\n ) {\n errors.push({\n path: 'spec.basicData.languages',\n code: 'LANGUAGES_NOT_STRING_ARRAY',\n messageKey: 'error_messages.basicData_languages_validation'\n })\n }\n\n if (basicData.SRID !== undefined && typeof basicData.SRID !== 'string') {\n errors.push({\n path: 'spec.basicData.SRID',\n code: 'SRID_NOT_STRING',\n messageKey: 'error_messages.basicData_SRID_validation'\n })\n }\n\n const { features } = spec\n const featuresValid =\n features === undefined ||\n (Array.isArray(features) && features.every((f) => typeof f === 'string')) ||\n isPlainObject(features)\n if (!featuresValid) {\n errors.push({\n path: 'spec.features',\n code: 'FEATURES_INVALID_SHAPE',\n messageKey: 'error_messages.spec_features_validation'\n })\n }\n\n if (spec.statics !== undefined && !Array.isArray(spec.statics)) {\n errors.push({\n path: 'spec.statics',\n code: 'STATICS_NOT_ARRAY',\n messageKey: 'error_messages.spec_statics_validation'\n })\n }\n\n return { valid: errors.length === 0, errors }\n}\n\n/**\n * Validates a product spec and throws when it is not acceptable.\n *\n * The throwing counterpart of `validateProductSpec`, mirroring the\n * `validateFeatureSelection` / `assertFeatureSelection` pair. It is what makes\n * `InvalidProductSpecError` reachable: the monolith's equivalent is\n * express-validator short-circuiting the request with a 400 before\n * `ProductService.createProduct` ever runs, which has no direct analogue in a\n * library.\n *\n * The message lists every problem with its i18n key. Callers that need the\n * problems as DATA (to build an HTTP response body, say) should call\n * `validateProductSpec` instead — that is precisely what it is for, and it keeps\n * this error free of ad-hoc payload properties.\n *\n * @param params.spec The spec to validate.\n * @returns The spec, unchanged, when it is valid.\n * @throws {InvalidProductSpecError} listing every problem found.\n */\nexport const assertProductSpec = ({ spec }: { spec: ProductSpec }): ProductSpec => {\n const { valid, errors } = validateProductSpec({ spec })\n if (!valid) {\n const summary = errors.map((error) => `${error.path}: ${error.messageKey}`).join('; ')\n throw new InvalidProductSpecError(`Invalid product spec: ${summary}`)\n }\n return spec\n}\n\n/**\n * Fills a product spec with the domain defaults.\n *\n * Union of the two places the monolith applies defaults:\n * - `entities/product.js` (Mongoose schema): `version` `'0.0.0'`, `database` `{}`,\n * `extra` `{}`, `testEnvironment` `{ image: '', command: '' }`, `languages`\n * `['en','es','gl']`, `SRID` `'4326'`, `dataModel.cells` `[]`, `features` `[]`,\n * `statics` `[]`, `sensor` `{ dsl: '', parsed: null }`.\n * - `generatePipeline.js:saveProductVersion` (~212-222), which re-applies\n * `database`, `extra`, `languages` and `SRID` with `||` right before returning.\n *\n * `||` semantics are preserved for those four, which is subtler than it looks:\n * an empty-string `SRID` falls back to `'4326'` because `''` is falsy, but an\n * EMPTY `languages` array is kept because `[]` is truthy. Both match the monolith.\n *\n * PURE: returns a new object and never mutates the input. `basicData.createdAt`\n * is deliberately NOT filled — the schema defaults it to `Date.now`, which would\n * make this function non-deterministic. Timestamping is persistence metadata and\n * belongs to linea-server.\n *\n * @param params.spec The spec to complete.\n * @returns A new spec with defaults applied.\n * @throws {InvalidArgumentError} when `spec` is not an object.\n */\nexport const normalizeProductSpec = ({ spec }: { spec: ProductSpec }): ProductSpec => {\n if (!isPlainObject(spec)) {\n throw new InvalidArgumentError('\"spec\" must be an object.')\n }\n const basicData = isPlainObject(spec.basicData) ? spec.basicData : {}\n const dataModel = isPlainObject(spec.dataModel) ? spec.dataModel : {}\n const sensor = isPlainObject(spec.sensor) ? spec.sensor : {}\n const testEnvironment = isPlainObject(basicData.testEnvironment)\n ? basicData.testEnvironment\n : {}\n\n const { languages } = basicData\n\n return {\n ...spec,\n basicData: {\n ...basicData,\n name: typeof basicData.name === 'string' ? basicData.name : '',\n version: typeof basicData.version === 'string' && basicData.version !== ''\n ? basicData.version\n : '0.0.0',\n database: isPlainObject(basicData.database) ? basicData.database : {},\n extra: isPlainObject(basicData.extra) ? basicData.extra : {},\n testEnvironment: {\n image: typeof testEnvironment.image === 'string' ? testEnvironment.image : '',\n command: typeof testEnvironment.command === 'string' ? testEnvironment.command : ''\n },\n // An EMPTY array is kept. `saveProductVersion` uses `languages || [...]`\n // and `[]` is truthy in JavaScript, so the monolith preserves it; the\n // Mongoose default only fires when the path is `undefined`. A user who\n // deselected every language must generate the same product here.\n languages: Array.isArray(languages) ? [...languages] : [...DEFAULT_LANGUAGES],\n SRID: typeof basicData.SRID === 'string' && basicData.SRID !== ''\n ? basicData.SRID\n : DEFAULT_SRID\n },\n dataModel: {\n ...dataModel,\n cells: Array.isArray(dataModel.cells) ? [...dataModel.cells] : []\n },\n features: Array.isArray(spec.features)\n ? [...spec.features]\n : isPlainObject(spec.features)\n ? { ...spec.features }\n : [],\n statics: Array.isArray(spec.statics) ? [...spec.statics] : [],\n sensor: {\n ...sensor,\n dsl: typeof sensor.dsl === 'string' ? sensor.dsl : '',\n parsed: sensor.parsed ?? null\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/product/version.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AAEnD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,EAC/B,OAAO,EACP,KAAK,EAIN,EAAU,EAAE;IACX,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QAClE,MAAM,IAAI,oBAAoB,CAC5B,mCAAmC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,CAC9D,CAAA;IACH,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QACvD,MAAM,IAAI,oBAAoB,CAAC,6CAA6C,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC/F,CAAC;IAED,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;IAC5C,OAAO,KAAK;SACT,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE;QACf,IAAI,CAAC,KAAK,KAAK;YAAE,OAAO,IAAI,GAAG,CAAC,CAAA;QAChC,IAAI,CAAC,GAAG,KAAK;YAAE,OAAO,CAAC,CAAA;QACvB,OAAO,IAAI,CAAA;IACb,CAAC,CAAC;SACD,IAAI,CAAC,GAAG,CAAC,CAAA;AACd,CAAC,CAAA","sourcesContent":["/**\r\n * Product version arithmetic.\r\n *\r\n * Migrated from `linea/server/src/model/services/utils.js:incrementVersion` (~152-163).\r\n */\r\nimport { VERSION_PATTERN } from '../constants.js'\r\nimport { InvalidArgumentError } from '../errors.js'\r\n\r\n/**\r\n * Bumps one component of an `x.y.z` version, zeroing everything to its right.\r\n *\r\n * Verbatim algorithm of the monolith: the component at `index` is incremented\r\n * and every component after it is reset to 0.\r\n *\r\n * incrementVersion({ version: '1.2.3', index: 0 }) === '2.0.0'\r\n * incrementVersion({ version: '1.2.3', index: 1 }) === '1.3.0'\r\n * incrementVersion({ version: '1.2.3', index: 2 }) === '1.2.4'\r\n *\r\n * The monolith bumps index 1 on a feature-model save (`LineService.js:406`) and\r\n * on a conversion, and index 2 on a product generation.\r\n *\r\n * HARDENED (ADR-019): the original does `version.split('.').map(Number)` with no\r\n * validation, so `'abc'` silently yields `'NaN.NaN.NaN'` and would be persisted.\r\n * Here a version that does not match `VERSION_PATTERN` is rejected.\r\n *\r\n * @param params.version Current version, `x.y.z`.\r\n * @param params.index Zero-based component to bump: 0 major, 1 minor, 2 patch.\r\n * @returns The bumped version.\r\n * @throws {InvalidArgumentError} when `version` is not `x.y.z` or `index` is not\r\n * an integer in `[0, 2]`.\r\n */\r\nexport const incrementVersion = ({\r\n version,\r\n index\r\n}: {\r\n version: string\r\n index: number\r\n}): string => {\r\n if (typeof version !== 'string' || !VERSION_PATTERN.test(version)) {\r\n throw new InvalidArgumentError(\r\n `\"version\" must match x.y.z, got ${JSON.stringify(version)}.`\r\n )\r\n }\r\n if (!Number.isInteger(index) || index < 0 || index > 2) {\r\n throw new InvalidArgumentError(`\"index\" must be an integer in [0, 2], got ${String(index)}.`)\r\n }\r\n\r\n const parts = version.split('.').map(Number)\r\n return parts\r\n .map((part, i) => {\r\n if (i === index) return part + 1\r\n if (i > index) return 0\r\n return part\r\n })\r\n .join('.')\r\n}\r\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/product/version.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AAEnD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,EAC/B,OAAO,EACP,KAAK,EAIN,EAAU,EAAE;IACX,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QAClE,MAAM,IAAI,oBAAoB,CAC5B,mCAAmC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,CAC9D,CAAA;IACH,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QACvD,MAAM,IAAI,oBAAoB,CAAC,6CAA6C,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC/F,CAAC;IAED,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;IAC5C,OAAO,KAAK;SACT,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE;QACf,IAAI,CAAC,KAAK,KAAK;YAAE,OAAO,IAAI,GAAG,CAAC,CAAA;QAChC,IAAI,CAAC,GAAG,KAAK;YAAE,OAAO,CAAC,CAAA;QACvB,OAAO,IAAI,CAAA;IACb,CAAC,CAAC;SACD,IAAI,CAAC,GAAG,CAAC,CAAA;AACd,CAAC,CAAA","sourcesContent":["/**\n * Product version arithmetic.\n *\n * Migrated from `linea/server/src/model/services/utils.js:incrementVersion` (~152-163).\n */\nimport { VERSION_PATTERN } from '../constants.js'\nimport { InvalidArgumentError } from '../errors.js'\n\n/**\n * Bumps one component of an `x.y.z` version, zeroing everything to its right.\n *\n * Verbatim algorithm of the monolith: the component at `index` is incremented\n * and every component after it is reset to 0.\n *\n * incrementVersion({ version: '1.2.3', index: 0 }) === '2.0.0'\n * incrementVersion({ version: '1.2.3', index: 1 }) === '1.3.0'\n * incrementVersion({ version: '1.2.3', index: 2 }) === '1.2.4'\n *\n * The monolith bumps index 1 on a feature-model save (`LineService.js:406`) and\n * on a conversion, and index 2 on a product generation.\n *\n * HARDENED (ADR-019): the original does `version.split('.').map(Number)` with no\n * validation, so `'abc'` silently yields `'NaN.NaN.NaN'` and would be persisted.\n * Here a version that does not match `VERSION_PATTERN` is rejected.\n *\n * @param params.version Current version, `x.y.z`.\n * @param params.index Zero-based component to bump: 0 major, 1 minor, 2 patch.\n * @returns The bumped version.\n * @throws {InvalidArgumentError} when `version` is not `x.y.z` or `index` is not\n * an integer in `[0, 2]`.\n */\nexport const incrementVersion = ({\n version,\n index\n}: {\n version: string\n index: number\n}): string => {\n if (typeof version !== 'string' || !VERSION_PATTERN.test(version)) {\n throw new InvalidArgumentError(\n `\"version\" must match x.y.z, got ${JSON.stringify(version)}.`\n )\n }\n if (!Number.isInteger(index) || index < 0 || index > 2) {\n throw new InvalidArgumentError(`\"index\" must be an integer in [0, 2], got ${String(index)}.`)\n }\n\n const parts = version.split('.').map(Number)\n return parts\n .map((part, i) => {\n if (i === index) return part + 1\n if (i > index) return 0\n return part\n })\n .join('.')\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"products-index.js","sourceRoot":"","sources":["../../src/products-index/products-index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACpF,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAA;AACvE,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAC5E,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAkE9D,yEAAyE;AACzE,MAAM,MAAM,GAAG,CAAC,CAAqB,EAAE,CAAqB,EAAU,EAAE,CACtE,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IA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ADR-011 fixes the normative format:\r\n *\r\n * { \"productos\": [ { \"name\": \"...\", \"repositorio\": \"/ruta/en/gitlab\" } ] }\r\n *\r\n * The Spanish key `productos` is part of the decision and is NOT anglicised.\r\n *\r\n * ADR-011 foresaw its own extension (\"el esquema es versionable: si se amplía\r\n * (p. ej. versión del producto, estado), se hace de forma retrocompatible\").\r\n * That extension is now here: an entry MAY carry a `version` (`x.y.z`).\r\n *\r\n * { \"productos\": [ { \"name\": \"...\", \"repositorio\": \"...\", \"version\": \"1.2.3\" } ] }\r\n *\r\n * It is OPTIONAL and the compatibility rule is strict in both directions:\r\n * - an index written before this change parses, validates and serialises\r\n * exactly as before — no key appears out of nowhere;\r\n * - an entry with no version does NOT emit `\"version\": null` or `\"\"`, so\r\n * reading and rewriting an old index is a byte-for-byte no-op.\r\n * The reason it lives in the line's index at all — instead of in each product\r\n * repository, where the rest of the spec lives — is that listing the products of\r\n * a line has to show every version at once: one read per line instead of one\r\n * GitLab request per product.\r\n *\r\n * This index replaces the `products` Mongo collection of the monolith, so there\r\n * is no single function to migrate: the reconciliation semantics are adapted\r\n * from `linea/server/src/model/services/LineService.js:reconcileLines` (~134-193)\r\n * and `ProductService.js:reconcileProducts` (~232-295).\r\n *\r\n * Two deliberate departures from those (ADR-014, ADR-009):\r\n * - No database and no `archived` flag, so there is **no `prune`**. Entries that\r\n * no longer have a repository are REPORTED in `removed`, never dropped.\r\n * Deciding what to do about them is linea-server's call.\r\n * - Every mutation is pure: `add`/`rename`/`remove`/`reconcile` return a NEW\r\n * index and never touch the input, so a caller can diff before committing.\r\n */\r\nimport path from 'node:path'\r\nimport { NAME_PATTERN, PRODUCTS_INDEX_PATH, VERSION_PATTERN } from '../constants.js'\r\nimport { InvalidArgumentError, ProductsIndexError } from '../errors.js'\r\nimport { fileExists, readTextFile, writeTextFile } from '../fs/workspace.js'\r\nimport { isArray, isPlainObject } from '../internal/guards.js'\r\n\r\n/** One product of a line, as recorded in `products.json`. */\r\nexport interface ProductsIndexEntry {\r\n /** Product name; same rules as any other name (`NAME_PATTERN`). */\r\n readonly name: string\r\n /** Path of the product repository in the laboratory's GitLab. */\r\n readonly repositorio: string\r\n /**\r\n * Current product version (`VERSION_PATTERN`, i.e. `x.y.z`). **Optional**:\r\n * every index written before this field existed is still valid, and an entry\r\n * without it is never given one implicitly.\r\n *\r\n * It duplicates `spec.basicData.version`, which lives in the product's own\r\n * repository. That is the point: the enrolled-products listing needs every\r\n * version at once, and reading one file per product would be one GitLab\r\n * request per row. The product repository stays the source of truth; this is\r\n * the copy the line keeps to be able to list without fanning out.\r\n */\r\n readonly version?: string\r\n}\r\n\r\n/** The whole index. */\r\nexport interface ProductsIndex {\r\n readonly productos: ProductsIndexEntry[]\r\n}\r\n\r\n/** A problem found in an index. */\r\nexport interface ProductsIndexProblem {\r\n /** Dotted path of the offending field, e.g. `productos[2].repositorio`. */\r\n readonly path: string\r\n /** Stable machine-readable discriminator. */\r\n readonly code: ProductsIndexProblemCode\r\n /**\r\n * An i18n KEY, never a human-readable sentence — same policy as\r\n * `ProductSpecError.messageKey`, so a consumer never has to guess whether to\r\n * translate a value or render it raw.\r\n *\r\n * Two keys are inherited from the monolith and already translated:\r\n * `invalid_name_characters` and `basicData_version_format` (the latter reads\r\n * \"Version must follow the format X.Y.Z\", which is exactly the fact being\r\n * reported, so it is reused instead of minting an untranslated twin). The\r\n * rest are NEW (there was no products index to validate before ADR-011) and\r\n * have no translation yet; they are listed in CHANGELOG.md for whoever\r\n * migrates webui and linea-cli.\r\n */\r\n readonly messageKey: string\r\n}\r\n\r\n/** Stable discriminators for index problems. */\r\nexport type ProductsIndexProblemCode =\r\n | 'INDEX_NOT_OBJECT'\r\n | 'PRODUCTOS_NOT_ARRAY'\r\n | 'ENTRY_NOT_OBJECT'\r\n | 'NAME_REQUIRED'\r\n | 'NAME_INVALID_CHARACTERS'\r\n | 'NAME_DUPLICATED'\r\n | 'REPOSITORIO_REQUIRED'\r\n | 'VERSION_INVALID_FORMAT'\r\n\r\n/** Result of validating an index. */\r\nexport interface ProductsIndexValidation {\r\n readonly valid: boolean\r\n readonly errors: ProductsIndexProblem[]\r\n}\r\n\r\n/** Alphabetical by `name`, so serialisation is stable across callers. */\r\nconst byName = (a: ProductsIndexEntry, b: ProductsIndexEntry): number =>\r\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0\r\n\r\n/**\r\n * Builds a normalised entry, keeping ONLY the normative fields.\r\n *\r\n * The `version` key is omitted altogether when there is no usable version, and\r\n * that omission is the whole retro-compatibility guarantee: emitting `null` or\r\n * `''` would change the bytes of every pre-existing `products.json` the moment\r\n * linea-server read it and wrote it back.\r\n */\r\nconst normalizeEntry = ({\r\n name,\r\n repositorio,\r\n version\r\n}: ProductsIndexEntry): ProductsIndexEntry =>\r\n typeof version === 'string' && version !== ''\r\n ? { name, repositorio, version }\r\n : { name, repositorio }\r\n\r\n/**\r\n * Guards an incoming optional version. Absent (`undefined`) is fine; anything\r\n * else has to be a `x.y.z` string.\r\n *\r\n * The mutating functions THROW here rather than reporting, unlike\r\n * `validateProductsIndex`: they take their input from a caller's arguments, not\r\n * from a file on disk, so a bad value is a programming error (ADR-018).\r\n */\r\nconst assertOptionalVersion = ({\r\n version,\r\n label\r\n}: {\r\n version: unknown\r\n label: string\r\n}): void => {\r\n if (version === undefined) return\r\n if (typeof version !== 'string' || !VERSION_PATTERN.test(version)) {\r\n throw new InvalidArgumentError(\r\n `${label} must be a version like \"1.2.3\"; got ${JSON.stringify(version)}.`\r\n )\r\n }\r\n}\r\n\r\nconst assertIndex = (index: unknown): ProductsIndex => {\r\n if (!isPlainObject(index) || !Array.isArray(index.productos)) {\r\n throw new InvalidArgumentError('\"index\" must be a { productos: [...] } object.')\r\n }\r\n return index as unknown as ProductsIndex\r\n}\r\n\r\n/**\r\n * An empty index.\r\n *\r\n * @returns A fresh `{ productos: [] }`. A new object every call, so callers can\r\n * safely treat it as their own.\r\n */\r\nexport const emptyProductsIndex = (): ProductsIndex => ({ productos: [] })\r\n\r\n/**\r\n * Validates an index **without throwing**.\r\n *\r\n * Checks the ADR-011 shape plus the domain rules that make the index usable:\r\n * names must be valid (`NAME_PATTERN`) and unique, and every entry needs a\r\n * `repositorio`.\r\n *\r\n * @param params.index The index to validate. Anything, including nullish.\r\n * @returns `valid` plus one entry per problem, in document order.\r\n */\r\nexport const validateProductsIndex = ({ index }: { index: unknown }): ProductsIndexValidation => {\r\n if (!isPlainObject(index)) {\r\n return {\r\n valid: false,\r\n errors: [{\r\n path: '(root)',\r\n code: 'INDEX_NOT_OBJECT',\r\n messageKey: 'error_messages.products_index_not_object'\r\n }]\r\n }\r\n }\r\n if (!Array.isArray(index.productos)) {\r\n return {\r\n valid: false,\r\n errors: [{\r\n path: 'productos',\r\n code: 'PRODUCTOS_NOT_ARRAY',\r\n messageKey: 'error_messages.products_index_productos_not_array'\r\n }]\r\n }\r\n }\r\n\r\n const errors: ProductsIndexProblem[] = []\r\n const seen = new Set<string>()\r\n\r\n index.productos.forEach((entry: unknown, position: number) => {\r\n const at = `productos[${position}]`\r\n if (!isPlainObject(entry)) {\r\n errors.push({\r\n path: at,\r\n code: 'ENTRY_NOT_OBJECT',\r\n messageKey: 'error_messages.products_index_entry_not_object'\r\n })\r\n return\r\n }\r\n\r\n const { name, repositorio, version } = entry\r\n if (typeof name !== 'string' || name === '') {\r\n errors.push({\r\n path: `${at}.name`,\r\n code: 'NAME_REQUIRED',\r\n messageKey: 'error_messages.products_index_name_required'\r\n })\r\n } else if (!NAME_PATTERN.test(name)) {\r\n errors.push({\r\n path: `${at}.name`,\r\n code: 'NAME_INVALID_CHARACTERS',\r\n messageKey: 'error_messages.invalid_name_characters'\r\n })\r\n } else if (seen.has(name)) {\r\n errors.push({\r\n path: `${at}.name`,\r\n code: 'NAME_DUPLICATED',\r\n messageKey: 'error_messages.products_index_name_duplicated'\r\n })\r\n } else {\r\n seen.add(name)\r\n }\r\n\r\n if (typeof repositorio !== 'string' || repositorio === '') {\r\n errors.push({\r\n path: `${at}.repositorio`,\r\n code: 'REPOSITORIO_REQUIRED',\r\n messageKey: 'error_messages.products_index_repositorio_required'\r\n })\r\n }\r\n\r\n // OPTIONAL: absent is valid, and only `undefined` counts as absent. `''`,\r\n // `null` and numbers are attempts at a version, and a wrong one is worth\r\n // reporting: silently accepting them would put junk in the field the\r\n // enrolled-products listing renders.\r\n if (version !== undefined && (typeof version !== 'string' || !VERSION_PATTERN.test(version))) {\r\n errors.push({\r\n path: `${at}.version`,\r\n code: 'VERSION_INVALID_FORMAT',\r\n messageKey: 'error_messages.basicData_version_format'\r\n })\r\n }\r\n })\r\n\r\n return { valid: errors.length === 0, errors }\r\n}\r\n\r\n/**\r\n * Parses the JSON contents of a `products.json`.\r\n *\r\n * @param params.content Raw file contents.\r\n * @returns The index, with only the normative fields kept per entry: `name`,\r\n * `repositorio` and, when the file has it, `version`. An index written before\r\n * `version` existed parses exactly as it always did.\r\n * @throws {ProductsIndexError} when the JSON is malformed or does not satisfy\r\n * the ADR-011 shape — which includes a `version` present but not `x.y.z`.\r\n */\r\nexport const parseProductsIndex = ({ content }: { content: string }): ProductsIndex => {\r\n if (typeof content !== 'string') {\r\n throw new InvalidArgumentError('\"content\" must be a string.')\r\n }\r\n if (content.trim() === '') return emptyProductsIndex()\r\n\r\n let parsed: unknown\r\n try {\r\n parsed = JSON.parse(content)\r\n } catch (error) {\r\n throw new ProductsIndexError(\r\n `products.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,\r\n { cause: error }\r\n )\r\n }\r\n\r\n const validation = validateProductsIndex({ index: parsed })\r\n if (!validation.valid) {\r\n const summary = validation.errors.map((e) => `${e.path}: ${e.messageKey}`).join('; ')\r\n throw new ProductsIndexError(`products.json does not satisfy the ADR-011 format: ${summary}`)\r\n }\r\n\r\n const index = parsed as ProductsIndex\r\n return { productos: index.productos.map(normalizeEntry) }\r\n}\r\n\r\n/**\r\n * Serialises an index deterministically.\r\n *\r\n * Stability is a feature, not a detail: linea-server commits this file to the\r\n * line repository on every product create/rename/delete, so an unstable\r\n * serialisation would produce noisy diffs and spurious merge conflicts.\r\n * Guarantees: entries sorted alphabetically by `name`, only the normative fields\r\n * emitted and always in the same order (`name`, `repositorio`, `version`),\r\n * two-space indentation, single trailing newline.\r\n *\r\n * An entry with no version emits **no `version` key** — not `null`, not `''`.\r\n * That is what keeps an index written before this field byte-identical after a\r\n * read/write round trip.\r\n *\r\n * @param params.index The index to serialise.\r\n * @returns The JSON text to write.\r\n * @throws {InvalidArgumentError} when `index` is not index-shaped.\r\n */\r\nexport const serializeProductsIndex = ({ index }: { index: ProductsIndex }): string => {\r\n const checked = assertIndex(index)\r\n const productos = [...checked.productos].sort(byName).map(normalizeEntry)\r\n return `${JSON.stringify({ productos }, null, 2)}\\n`\r\n}\r\n\r\n/**\r\n * Adds a product to the index.\r\n *\r\n * @param params.index Current index. Not mutated.\r\n * @param params.product Entry to add. `version` is optional; when given it must\r\n * be `x.y.z`, and when omitted the entry simply has no version.\r\n * @returns A new, sorted index.\r\n * @throws {ProductsIndexError} when a product with that name is already there.\r\n * @throws {InvalidArgumentError} when the arguments are malformed.\r\n */\r\nexport const addProductToIndex = ({\r\n index,\r\n product\r\n}: {\r\n index: ProductsIndex\r\n product: ProductsIndexEntry\r\n}): ProductsIndex => {\r\n const checked = assertIndex(index)\r\n if (!isPlainObject(product)) {\r\n throw new InvalidArgumentError('\"product\" must be a { name, repositorio } object.')\r\n }\r\n const { name, repositorio, version } = product\r\n if (typeof name !== 'string' || !NAME_PATTERN.test(name)) {\r\n throw new InvalidArgumentError(`Invalid product name ${JSON.stringify(name)}.`)\r\n }\r\n if (typeof repositorio !== 'string' || repositorio === '') {\r\n throw new InvalidArgumentError('\"product.repositorio\" must be a non-empty string.')\r\n }\r\n assertOptionalVersion({ version, label: '\"product.version\"' })\r\n if (checked.productos.some((entry) => entry.name === name)) {\r\n throw new ProductsIndexError(`Product \"${name}\" is already in the index.`)\r\n }\r\n\r\n return {\r\n productos: [...checked.productos, normalizeEntry({ name, repositorio, version })].sort(byName)\r\n }\r\n}\r\n\r\n/**\r\n * Renames a product in the index, keeping its `repositorio` and its `version`.\r\n *\r\n * Note the repository path is intentionally left untouched: renaming a GitLab\r\n * project does not necessarily move it, and linea-server is the only component\r\n * that knows the new path. It should follow up with the real value if it changed.\r\n *\r\n * @param params.index Current index. Not mutated.\r\n * @param params.from Current product name.\r\n * @param params.to New product name.\r\n * @returns A new, sorted index.\r\n * @throws {ProductsIndexError} when `from` is missing or `to` already exists.\r\n * @throws {InvalidArgumentError} when the arguments are malformed.\r\n */\r\nexport const renameProductInIndex = ({\r\n index,\r\n from,\r\n to\r\n}: {\r\n index: ProductsIndex\r\n from: string\r\n to: string\r\n}): ProductsIndex => {\r\n const checked = assertIndex(index)\r\n if (typeof from !== 'string' || from === '') {\r\n throw new InvalidArgumentError('\"from\" must be a non-empty string.')\r\n }\r\n if (typeof to !== 'string' || !NAME_PATTERN.test(to)) {\r\n throw new InvalidArgumentError(`Invalid product name ${JSON.stringify(to)}.`)\r\n }\r\n if (!checked.productos.some((entry) => entry.name === from)) {\r\n throw new ProductsIndexError(`Product \"${from}\" is not in the index.`)\r\n }\r\n if (from !== to && checked.productos.some((entry) => entry.name === to)) {\r\n throw new ProductsIndexError(`Product \"${to}\" is already in the index.`)\r\n }\r\n\r\n return {\r\n productos: checked.productos\r\n .map((entry) => (entry.name === from ? normalizeEntry({ ...entry, name: to }) : entry))\r\n .sort(byName)\r\n }\r\n}\r\n\r\n/**\r\n * Removes a product from the index.\r\n *\r\n * IDEMPOTENT: removing a product that is not there returns an equivalent index\r\n * instead of throwing, so a retried or replayed delete cannot fail half-way.\r\n *\r\n * @param params.index Current index. Not mutated.\r\n * @param params.name Product to remove.\r\n * @returns A new, sorted index.\r\n * @throws {InvalidArgumentError} when the arguments are malformed.\r\n */\r\nexport const removeProductFromIndex = ({\r\n index,\r\n name\r\n}: {\r\n index: ProductsIndex\r\n name: string\r\n}): ProductsIndex => {\r\n const checked = assertIndex(index)\r\n if (typeof name !== 'string' || name === '') {\r\n throw new InvalidArgumentError('\"name\" must be a non-empty string.')\r\n }\r\n return { productos: checked.productos.filter((entry) => entry.name !== name).sort(byName) }\r\n}\r\n\r\n/**\r\n * Reads the index of a line working directory.\r\n *\r\n * A line with no `products.json` is a line with no products, not an error: the\r\n * file only appears once the first product is created, and every line predating\r\n * ADR-011 lacks it. A file that EXISTS but is corrupt is a different story and\r\n * does throw — silently treating it as empty would let linea-server commit a\r\n * fresh index over a real one and lose the product list.\r\n *\r\n * @param params.lineDir Root of the line working directory.\r\n * @returns The index, or an empty one when the file is absent.\r\n * @throws {ProductsIndexError} when the file exists but is malformed.\r\n */\r\nexport const readProductsIndex = ({ lineDir }: { lineDir: string }): ProductsIndex => {\r\n if (typeof lineDir !== 'string' || lineDir.trim() === '') {\r\n throw new InvalidArgumentError('\"lineDir\" must be a non-empty path.')\r\n }\r\n const filePath = path.join(path.resolve(lineDir), PRODUCTS_INDEX_PATH)\r\n if (!fileExists({ filePath })) return emptyProductsIndex()\r\n return parseProductsIndex({ content: readTextFile({ filePath }) })\r\n}\r\n\r\n/**\r\n * Writes the index of a line working directory, creating it if needed.\r\n *\r\n * @param params.lineDir Root of the line working directory.\r\n * @param params.index The index to write.\r\n * @returns The absolute path written.\r\n * @throws {InvalidArgumentError} when the arguments are malformed.\r\n */\r\nexport const writeProductsIndex = ({\r\n lineDir,\r\n index\r\n}: {\r\n lineDir: string\r\n index: ProductsIndex\r\n}): { path: string } => {\r\n if (typeof lineDir !== 'string' || lineDir.trim() === '') {\r\n throw new InvalidArgumentError('\"lineDir\" must be a non-empty path.')\r\n }\r\n const content = serializeProductsIndex({ index })\r\n const filePath = path.join(path.resolve(lineDir), PRODUCTS_INDEX_PATH)\r\n return { path: writeTextFile({ filePath, content }) }\r\n}\r\n\r\n/** Outcome of reconciling an index against the repositories actually observed. */\r\nexport interface ProductsIndexReconciliation {\r\n /** The index with the newly discovered repositories added. */\r\n readonly index: ProductsIndex\r\n /**\r\n * Entries added because a repository existed but was not indexed. They carry\r\n * a `version` only if the caller observed one.\r\n */\r\n readonly added: ProductsIndexEntry[]\r\n /**\r\n * Entries indexed but with no observed repository.\r\n *\r\n * REPORTED ONLY — they stay in `index`. The monolith's `prune` archived such\r\n * rows in Mongo; without a database, dropping them here would silently destroy\r\n * the record of a product whose repository the caller merely could not see\r\n * (a permissions hiccup, a partial listing). linea-server decides.\r\n */\r\n readonly removed: ProductsIndexEntry[]\r\n}\r\n\r\n/**\r\n * Reconciles an index against the repositories a caller actually observed.\r\n *\r\n * Adapted from the `reconcile*` pair of the monolith, which discovers GitLab\r\n * projects by topic and creates the rows that are missing.\r\n *\r\n * Versions already recorded in the index are preserved verbatim, exactly like\r\n * `repositorio`: the observation the caller makes is \"this repository exists\",\r\n * not \"this is the product's version\", so it never overwrites what is indexed.\r\n * A newly added entry keeps the `version` the caller supplied, if any.\r\n *\r\n * @param params.index Current index. Not mutated.\r\n * @param params.repositories Repositories observed, as `{ name, repositorio }`\r\n * plus an optional `version`. linea-server builds this from GitLab; linea-core\r\n * never looks.\r\n * @returns The reconciled index plus what was added and what is missing.\r\n * @throws {InvalidArgumentError} when the arguments are malformed.\r\n */\r\nexport const reconcileProductsIndex = ({\r\n index,\r\n repositories\r\n}: {\r\n index: ProductsIndex\r\n repositories: readonly ProductsIndexEntry[]\r\n}): ProductsIndexReconciliation => {\r\n const checked = assertIndex(index)\r\n if (!isArray(repositories)) {\r\n throw new InvalidArgumentError('\"repositories\" must be an array of { name, repositorio }.')\r\n }\r\n for (const repository of repositories) {\r\n if (!isPlainObject(repository) ||\r\n typeof repository.name !== 'string' || repository.name === '' ||\r\n typeof repository.repositorio !== 'string' || repository.repositorio === '') {\r\n throw new InvalidArgumentError(\r\n 'Every entry of \"repositories\" must be a { name, repositorio } object with non-empty strings.'\r\n )\r\n }\r\n assertOptionalVersion({\r\n version: repository.version,\r\n label: `\"repositories[${repository.name}].version\"`\r\n })\r\n }\r\n\r\n const indexed = new Set(checked.productos.map((entry) => entry.name))\r\n const observed = new Set(repositories.map((repository) => repository.name))\r\n\r\n const added = repositories\r\n .filter((repository) => !indexed.has(repository.name))\r\n .map(normalizeEntry)\r\n\r\n const removed = checked.productos\r\n .filter((entry) => !observed.has(entry.name))\r\n .map(normalizeEntry)\r\n\r\n return {\r\n index: { productos: [...checked.productos, ...added].sort(byName) },\r\n added: [...added].sort(byName),\r\n removed: [...removed].sort(byName)\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"products-index.js","sourceRoot":"","sources":["../../src/products-index/products-index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACpF,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAA;AACvE,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAC5E,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAkE9D,yEAAyE;AACzE,MAAM,MAAM,GAAG,CAAC,CAAqB,EAAE,CAAqB,EAAU,EAAE,CACtE,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAEhD;;;;;;;GAOG;AACH,MAAM,cAAc,GAAG,CAAC,EACtB,IAAI,EACJ,WAAW,EACX,OAAO,EACY,EAAsB,EAAE,CAC3C,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,EAAE;IAC3C,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE;IAChC,CAAC,CAAC,EAA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,IAAI,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAA;IAE3E,MAAM,KAAK,GAAG,YAAY;SACvB,MAAM,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;SACrD,GAAG,CAAC,cAAc,CAAC,CAAA;IAEtB,MAAM,OAAO,GAAG,OAAO,CAAC,SAAS;SAC9B,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;SAC5C,GAAG,CAAC,cAAc,CAAC,CAAA;IAEtB,OAAO;QACL,KAAK,EAAE,EAAE,SAAS,EAAE,CAAC,GAAG,OAAO,CAAC,SAAS,EAAE,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;QACnE,KAAK,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;QAC9B,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;KACnC,CAAA;AACH,CAAC,CAAA","sourcesContent":["/**\n * The `products.json` index that lives at the root of every line repository.\n *\n * ADR-011 fixes the normative format:\n *\n * { \"productos\": [ { \"name\": \"...\", \"repositorio\": \"/ruta/en/gitlab\" } ] }\n *\n * The Spanish key `productos` is part of the decision and is NOT anglicised.\n *\n * ADR-011 foresaw its own extension (\"el esquema es versionable: si se amplía\n * (p. ej. versión del producto, estado), se hace de forma retrocompatible\").\n * That extension is now here: an entry MAY carry a `version` (`x.y.z`).\n *\n * { \"productos\": [ { \"name\": \"...\", \"repositorio\": \"...\", \"version\": \"1.2.3\" } ] }\n *\n * It is OPTIONAL and the compatibility rule is strict in both directions:\n * - an index written before this change parses, validates and serialises\n * exactly as before — no key appears out of nowhere;\n * - an entry with no version does NOT emit `\"version\": null` or `\"\"`, so\n * reading and rewriting an old index is a byte-for-byte no-op.\n * The reason it lives in the line's index at all — instead of in each product\n * repository, where the rest of the spec lives — is that listing the products of\n * a line has to show every version at once: one read per line instead of one\n * GitLab request per product.\n *\n * This index replaces the `products` Mongo collection of the monolith, so there\n * is no single function to migrate: the reconciliation semantics are adapted\n * from `linea/server/src/model/services/LineService.js:reconcileLines` (~134-193)\n * and `ProductService.js:reconcileProducts` (~232-295).\n *\n * Two deliberate departures from those (ADR-014, ADR-009):\n * - No database and no `archived` flag, so there is **no `prune`**. Entries that\n * no longer have a repository are REPORTED in `removed`, never dropped.\n * Deciding what to do about them is linea-server's call.\n * - Every mutation is pure: `add`/`rename`/`remove`/`reconcile` return a NEW\n * index and never touch the input, so a caller can diff before committing.\n */\nimport path from 'node:path'\nimport { NAME_PATTERN, PRODUCTS_INDEX_PATH, VERSION_PATTERN } from '../constants.js'\nimport { InvalidArgumentError, ProductsIndexError } from '../errors.js'\nimport { fileExists, readTextFile, writeTextFile } from '../fs/workspace.js'\nimport { isArray, isPlainObject } from '../internal/guards.js'\n\n/** One product of a line, as recorded in `products.json`. */\nexport interface ProductsIndexEntry {\n /** Product name; same rules as any other name (`NAME_PATTERN`). */\n readonly name: string\n /** Path of the product repository in the laboratory's GitLab. */\n readonly repositorio: string\n /**\n * Current product version (`VERSION_PATTERN`, i.e. `x.y.z`). **Optional**:\n * every index written before this field existed is still valid, and an entry\n * without it is never given one implicitly.\n *\n * It duplicates `spec.basicData.version`, which lives in the product's own\n * repository. That is the point: the enrolled-products listing needs every\n * version at once, and reading one file per product would be one GitLab\n * request per row. The product repository stays the source of truth; this is\n * the copy the line keeps to be able to list without fanning out.\n */\n readonly version?: string\n}\n\n/** The whole index. */\nexport interface ProductsIndex {\n readonly productos: ProductsIndexEntry[]\n}\n\n/** A problem found in an index. */\nexport interface ProductsIndexProblem {\n /** Dotted path of the offending field, e.g. `productos[2].repositorio`. */\n readonly path: string\n /** Stable machine-readable discriminator. */\n readonly code: ProductsIndexProblemCode\n /**\n * An i18n KEY, never a human-readable sentence — same policy as\n * `ProductSpecError.messageKey`, so a consumer never has to guess whether to\n * translate a value or render it raw.\n *\n * Two keys are inherited from the monolith and already translated:\n * `invalid_name_characters` and `basicData_version_format` (the latter reads\n * \"Version must follow the format X.Y.Z\", which is exactly the fact being\n * reported, so it is reused instead of minting an untranslated twin). The\n * rest are NEW (there was no products index to validate before ADR-011) and\n * have no translation yet; they are listed in CHANGELOG.md for whoever\n * migrates webui and linea-cli.\n */\n readonly messageKey: string\n}\n\n/** Stable discriminators for index problems. */\nexport type ProductsIndexProblemCode =\n | 'INDEX_NOT_OBJECT'\n | 'PRODUCTOS_NOT_ARRAY'\n | 'ENTRY_NOT_OBJECT'\n | 'NAME_REQUIRED'\n | 'NAME_INVALID_CHARACTERS'\n | 'NAME_DUPLICATED'\n | 'REPOSITORIO_REQUIRED'\n | 'VERSION_INVALID_FORMAT'\n\n/** Result of validating an index. */\nexport interface ProductsIndexValidation {\n readonly valid: boolean\n readonly errors: ProductsIndexProblem[]\n}\n\n/** Alphabetical by `name`, so serialisation is stable across callers. */\nconst byName = (a: ProductsIndexEntry, b: ProductsIndexEntry): number =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0\n\n/**\n * Builds a normalised entry, keeping ONLY the normative fields.\n *\n * The `version` key is omitted altogether when there is no usable version, and\n * that omission is the whole retro-compatibility guarantee: emitting `null` or\n * `''` would change the bytes of every pre-existing `products.json` the moment\n * linea-server read it and wrote it back.\n */\nconst normalizeEntry = ({\n name,\n repositorio,\n version\n}: ProductsIndexEntry): ProductsIndexEntry =>\n typeof version === 'string' && version !== ''\n ? { name, repositorio, version }\n : { name, repositorio }\n\n/**\n * Guards an incoming optional version. Absent (`undefined`) is fine; anything\n * else has to be a `x.y.z` string.\n *\n * The mutating functions THROW here rather than reporting, unlike\n * `validateProductsIndex`: they take their input from a caller's arguments, not\n * from a file on disk, so a bad value is a programming error (ADR-018).\n */\nconst assertOptionalVersion = ({\n version,\n label\n}: {\n version: unknown\n label: string\n}): void => {\n if (version === undefined) return\n if (typeof version !== 'string' || !VERSION_PATTERN.test(version)) {\n throw new InvalidArgumentError(\n `${label} must be a version like \"1.2.3\"; got ${JSON.stringify(version)}.`\n )\n }\n}\n\nconst assertIndex = (index: unknown): ProductsIndex => {\n if (!isPlainObject(index) || !Array.isArray(index.productos)) {\n throw new InvalidArgumentError('\"index\" must be a { productos: [...] } object.')\n }\n return index as unknown as ProductsIndex\n}\n\n/**\n * An empty index.\n *\n * @returns A fresh `{ productos: [] }`. A new object every call, so callers can\n * safely treat it as their own.\n */\nexport const emptyProductsIndex = (): ProductsIndex => ({ productos: [] })\n\n/**\n * Validates an index **without throwing**.\n *\n * Checks the ADR-011 shape plus the domain rules that make the index usable:\n * names must be valid (`NAME_PATTERN`) and unique, and every entry needs a\n * `repositorio`.\n *\n * @param params.index The index to validate. Anything, including nullish.\n * @returns `valid` plus one entry per problem, in document order.\n */\nexport const validateProductsIndex = ({ index }: { index: unknown }): ProductsIndexValidation => {\n if (!isPlainObject(index)) {\n return {\n valid: false,\n errors: [{\n path: '(root)',\n code: 'INDEX_NOT_OBJECT',\n messageKey: 'error_messages.products_index_not_object'\n }]\n }\n }\n if (!Array.isArray(index.productos)) {\n return {\n valid: false,\n errors: [{\n path: 'productos',\n code: 'PRODUCTOS_NOT_ARRAY',\n messageKey: 'error_messages.products_index_productos_not_array'\n }]\n }\n }\n\n const errors: ProductsIndexProblem[] = []\n const seen = new Set<string>()\n\n index.productos.forEach((entry: unknown, position: number) => {\n const at = `productos[${position}]`\n if (!isPlainObject(entry)) {\n errors.push({\n path: at,\n code: 'ENTRY_NOT_OBJECT',\n messageKey: 'error_messages.products_index_entry_not_object'\n })\n return\n }\n\n const { name, repositorio, version } = entry\n if (typeof name !== 'string' || name === '') {\n errors.push({\n path: `${at}.name`,\n code: 'NAME_REQUIRED',\n messageKey: 'error_messages.products_index_name_required'\n })\n } else if (!NAME_PATTERN.test(name)) {\n errors.push({\n path: `${at}.name`,\n code: 'NAME_INVALID_CHARACTERS',\n messageKey: 'error_messages.invalid_name_characters'\n })\n } else if (seen.has(name)) {\n errors.push({\n path: `${at}.name`,\n code: 'NAME_DUPLICATED',\n messageKey: 'error_messages.products_index_name_duplicated'\n })\n } else {\n seen.add(name)\n }\n\n if (typeof repositorio !== 'string' || repositorio === '') {\n errors.push({\n path: `${at}.repositorio`,\n code: 'REPOSITORIO_REQUIRED',\n messageKey: 'error_messages.products_index_repositorio_required'\n })\n }\n\n // OPTIONAL: absent is valid, and only `undefined` counts as absent. `''`,\n // `null` and numbers are attempts at a version, and a wrong one is worth\n // reporting: silently accepting them would put junk in the field the\n // enrolled-products listing renders.\n if (version !== undefined && (typeof version !== 'string' || !VERSION_PATTERN.test(version))) {\n errors.push({\n path: `${at}.version`,\n code: 'VERSION_INVALID_FORMAT',\n messageKey: 'error_messages.basicData_version_format'\n })\n }\n })\n\n return { valid: errors.length === 0, errors }\n}\n\n/**\n * Parses the JSON contents of a `products.json`.\n *\n * @param params.content Raw file contents.\n * @returns The index, with only the normative fields kept per entry: `name`,\n * `repositorio` and, when the file has it, `version`. An index written before\n * `version` existed parses exactly as it always did.\n * @throws {ProductsIndexError} when the JSON is malformed or does not satisfy\n * the ADR-011 shape — which includes a `version` present but not `x.y.z`.\n */\nexport const parseProductsIndex = ({ content }: { content: string }): ProductsIndex => {\n if (typeof content !== 'string') {\n throw new InvalidArgumentError('\"content\" must be a string.')\n }\n if (content.trim() === '') return emptyProductsIndex()\n\n let parsed: unknown\n try {\n parsed = JSON.parse(content)\n } catch (error) {\n throw new ProductsIndexError(\n `products.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n )\n }\n\n const validation = validateProductsIndex({ index: parsed })\n if (!validation.valid) {\n const summary = validation.errors.map((e) => `${e.path}: ${e.messageKey}`).join('; ')\n throw new ProductsIndexError(`products.json does not satisfy the ADR-011 format: ${summary}`)\n }\n\n const index = parsed as ProductsIndex\n return { productos: index.productos.map(normalizeEntry) }\n}\n\n/**\n * Serialises an index deterministically.\n *\n * Stability is a feature, not a detail: linea-server commits this file to the\n * line repository on every product create/rename/delete, so an unstable\n * serialisation would produce noisy diffs and spurious merge conflicts.\n * Guarantees: entries sorted alphabetically by `name`, only the normative fields\n * emitted and always in the same order (`name`, `repositorio`, `version`),\n * two-space indentation, single trailing newline.\n *\n * An entry with no version emits **no `version` key** — not `null`, not `''`.\n * That is what keeps an index written before this field byte-identical after a\n * read/write round trip.\n *\n * @param params.index The index to serialise.\n * @returns The JSON text to write.\n * @throws {InvalidArgumentError} when `index` is not index-shaped.\n */\nexport const serializeProductsIndex = ({ index }: { index: ProductsIndex }): string => {\n const checked = assertIndex(index)\n const productos = [...checked.productos].sort(byName).map(normalizeEntry)\n return `${JSON.stringify({ productos }, null, 2)}\\n`\n}\n\n/**\n * Adds a product to the index.\n *\n * @param params.index Current index. Not mutated.\n * @param params.product Entry to add. `version` is optional; when given it must\n * be `x.y.z`, and when omitted the entry simply has no version.\n * @returns A new, sorted index.\n * @throws {ProductsIndexError} when a product with that name is already there.\n * @throws {InvalidArgumentError} when the arguments are malformed.\n */\nexport const addProductToIndex = ({\n index,\n product\n}: {\n index: ProductsIndex\n product: ProductsIndexEntry\n}): ProductsIndex => {\n const checked = assertIndex(index)\n if (!isPlainObject(product)) {\n throw new InvalidArgumentError('\"product\" must be a { name, repositorio } object.')\n }\n const { name, repositorio, version } = product\n if (typeof name !== 'string' || !NAME_PATTERN.test(name)) {\n throw new InvalidArgumentError(`Invalid product name ${JSON.stringify(name)}.`)\n }\n if (typeof repositorio !== 'string' || repositorio === '') {\n throw new InvalidArgumentError('\"product.repositorio\" must be a non-empty string.')\n }\n assertOptionalVersion({ version, label: '\"product.version\"' })\n if (checked.productos.some((entry) => entry.name === name)) {\n throw new ProductsIndexError(`Product \"${name}\" is already in the index.`)\n }\n\n return {\n productos: [...checked.productos, normalizeEntry({ name, repositorio, version })].sort(byName)\n }\n}\n\n/**\n * Renames a product in the index, keeping its `repositorio` and its `version`.\n *\n * Note the repository path is intentionally left untouched: renaming a GitLab\n * project does not necessarily move it, and linea-server is the only component\n * that knows the new path. It should follow up with the real value if it changed.\n *\n * @param params.index Current index. Not mutated.\n * @param params.from Current product name.\n * @param params.to New product name.\n * @returns A new, sorted index.\n * @throws {ProductsIndexError} when `from` is missing or `to` already exists.\n * @throws {InvalidArgumentError} when the arguments are malformed.\n */\nexport const renameProductInIndex = ({\n index,\n from,\n to\n}: {\n index: ProductsIndex\n from: string\n to: string\n}): ProductsIndex => {\n const checked = assertIndex(index)\n if (typeof from !== 'string' || from === '') {\n throw new InvalidArgumentError('\"from\" must be a non-empty string.')\n }\n if (typeof to !== 'string' || !NAME_PATTERN.test(to)) {\n throw new InvalidArgumentError(`Invalid product name ${JSON.stringify(to)}.`)\n }\n if (!checked.productos.some((entry) => entry.name === from)) {\n throw new ProductsIndexError(`Product \"${from}\" is not in the index.`)\n }\n if (from !== to && checked.productos.some((entry) => entry.name === to)) {\n throw new ProductsIndexError(`Product \"${to}\" is already in the index.`)\n }\n\n return {\n productos: checked.productos\n .map((entry) => (entry.name === from ? normalizeEntry({ ...entry, name: to }) : entry))\n .sort(byName)\n }\n}\n\n/**\n * Removes a product from the index.\n *\n * IDEMPOTENT: removing a product that is not there returns an equivalent index\n * instead of throwing, so a retried or replayed delete cannot fail half-way.\n *\n * @param params.index Current index. Not mutated.\n * @param params.name Product to remove.\n * @returns A new, sorted index.\n * @throws {InvalidArgumentError} when the arguments are malformed.\n */\nexport const removeProductFromIndex = ({\n index,\n name\n}: {\n index: ProductsIndex\n name: string\n}): ProductsIndex => {\n const checked = assertIndex(index)\n if (typeof name !== 'string' || name === '') {\n throw new InvalidArgumentError('\"name\" must be a non-empty string.')\n }\n return { productos: checked.productos.filter((entry) => entry.name !== name).sort(byName) }\n}\n\n/**\n * Reads the index of a line working directory.\n *\n * A line with no `products.json` is a line with no products, not an error: the\n * file only appears once the first product is created, and every line predating\n * ADR-011 lacks it. A file that EXISTS but is corrupt is a different story and\n * does throw — silently treating it as empty would let linea-server commit a\n * fresh index over a real one and lose the product list.\n *\n * @param params.lineDir Root of the line working directory.\n * @returns The index, or an empty one when the file is absent.\n * @throws {ProductsIndexError} when the file exists but is malformed.\n */\nexport const readProductsIndex = ({ lineDir }: { lineDir: string }): ProductsIndex => {\n if (typeof lineDir !== 'string' || lineDir.trim() === '') {\n throw new InvalidArgumentError('\"lineDir\" must be a non-empty path.')\n }\n const filePath = path.join(path.resolve(lineDir), PRODUCTS_INDEX_PATH)\n if (!fileExists({ filePath })) return emptyProductsIndex()\n return parseProductsIndex({ content: readTextFile({ filePath }) })\n}\n\n/**\n * Writes the index of a line working directory, creating it if needed.\n *\n * @param params.lineDir Root of the line working directory.\n * @param params.index The index to write.\n * @returns The absolute path written.\n * @throws {InvalidArgumentError} when the arguments are malformed.\n */\nexport const writeProductsIndex = ({\n lineDir,\n index\n}: {\n lineDir: string\n index: ProductsIndex\n}): { path: string } => {\n if (typeof lineDir !== 'string' || lineDir.trim() === '') {\n throw new InvalidArgumentError('\"lineDir\" must be a non-empty path.')\n }\n const content = serializeProductsIndex({ index })\n const filePath = path.join(path.resolve(lineDir), PRODUCTS_INDEX_PATH)\n return { path: writeTextFile({ filePath, content }) }\n}\n\n/** Outcome of reconciling an index against the repositories actually observed. */\nexport interface ProductsIndexReconciliation {\n /** The index with the newly discovered repositories added. */\n readonly index: ProductsIndex\n /**\n * Entries added because a repository existed but was not indexed. They carry\n * a `version` only if the caller observed one.\n */\n readonly added: ProductsIndexEntry[]\n /**\n * Entries indexed but with no observed repository.\n *\n * REPORTED ONLY — they stay in `index`. The monolith's `prune` archived such\n * rows in Mongo; without a database, dropping them here would silently destroy\n * the record of a product whose repository the caller merely could not see\n * (a permissions hiccup, a partial listing). linea-server decides.\n */\n readonly removed: ProductsIndexEntry[]\n}\n\n/**\n * Reconciles an index against the repositories a caller actually observed.\n *\n * Adapted from the `reconcile*` pair of the monolith, which discovers GitLab\n * projects by topic and creates the rows that are missing.\n *\n * Versions already recorded in the index are preserved verbatim, exactly like\n * `repositorio`: the observation the caller makes is \"this repository exists\",\n * not \"this is the product's version\", so it never overwrites what is indexed.\n * A newly added entry keeps the `version` the caller supplied, if any.\n *\n * @param params.index Current index. Not mutated.\n * @param params.repositories Repositories observed, as `{ name, repositorio }`\n * plus an optional `version`. linea-server builds this from GitLab; linea-core\n * never looks.\n * @returns The reconciled index plus what was added and what is missing.\n * @throws {InvalidArgumentError} when the arguments are malformed.\n */\nexport const reconcileProductsIndex = ({\n index,\n repositories\n}: {\n index: ProductsIndex\n repositories: readonly ProductsIndexEntry[]\n}): ProductsIndexReconciliation => {\n const checked = assertIndex(index)\n if (!isArray(repositories)) {\n throw new InvalidArgumentError('\"repositories\" must be an array of { name, repositorio }.')\n }\n for (const repository of repositories) {\n if (!isPlainObject(repository) ||\n typeof repository.name !== 'string' || repository.name === '' ||\n typeof repository.repositorio !== 'string' || repository.repositorio === '') {\n throw new InvalidArgumentError(\n 'Every entry of \"repositories\" must be a { name, repositorio } object with non-empty strings.'\n )\n }\n assertOptionalVersion({\n version: repository.version,\n label: `\"repositories[${repository.name}].version\"`\n })\n }\n\n const indexed = new Set(checked.productos.map((entry) => entry.name))\n const observed = new Set(repositories.map((repository) => repository.name))\n\n const added = repositories\n .filter((repository) => !indexed.has(repository.name))\n .map(normalizeEntry)\n\n const removed = checked.productos\n .filter((entry) => !observed.has(entry.name))\n .map(normalizeEntry)\n\n return {\n index: { productos: [...checked.productos, ...added].sort(byName) },\n added: [...added].sort(byName),\n removed: [...removed].sort(byName)\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"selection.js","sourceRoot":"","sources":["../../src/selection/selection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,oBAAoB,EAAE,4BAA4B,EAAE,MAAM,cAAc,CAAA;AACjF,OAAO,EACL,iBAAiB,EACjB,wBAAw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\n * - `linea/server/src/model/services/utils.js:normalizeFeatureSelection` (~172-186)\r\n * - `linea/server/src/model/services/ProductService.js:#validateSpecFeatures` (~37-58)\r\n * - `linea/server/src/model/services/ProductService.js:getProductHealth` (~481-519),\r\n * which is where the `{ valid, features, error, errorType }` shape comes from\r\n * - `linea/server/src/agents/tools/harvest.js:validateModelAgainstProducts` (~113-133)\r\n *\r\n * The monolith spreads this logic across a service that also reads GitLab and a\r\n * Mongo-backed agent tool. Here it is pure: the caller supplies the parsed model\r\n * and the selections, and nothing reaches the network or a database.\r\n */\r\nimport { InvalidArgumentError, FeatureSelectionInvalidError } from '../errors.js'\r\nimport {\r\n completeSelection,\r\n describeSelectionFailure,\r\n type FeatureModelValue\r\n} from '../feature-model/engine.js'\r\nimport { isArray } from '../internal/guards.js'\r\n\r\n/** The three historical shapes of `spec.features` accepted by the monolith. */\r\nexport type FeatureSelectionInput = string[] | Record<string, boolean> | undefined\r\n\r\n/** Minimal view of a product spec needed to read its feature selection. */\r\nexport interface SelectionBearingSpec {\r\n features?: FeatureSelectionInput\r\n /** Deprecated field name, still present in old specs. */\r\n selection?: string[]\r\n [key: string]: unknown\r\n}\r\n\r\nconst assertModel = (model: unknown): FeatureModelValue => {\r\n if (model === null || typeof model !== 'object') {\r\n throw new InvalidArgumentError('\"model\" must be a value returned by parseFeatureModel().')\r\n }\r\n return model as FeatureModelValue\r\n}\r\n\r\nconst assertFeatureArray = (features: unknown): string[] => {\r\n if (!Array.isArray(features) || features.some((f) => typeof f !== 'string')) {\r\n throw new InvalidArgumentError('\"features\" must be an array of strings.')\r\n }\r\n return features as string[]\r\n}\r\n\r\n/**\r\n * Normalises a spec's feature selection into a plain string array.\r\n *\r\n * Verbatim behaviour of `utils.js:normalizeFeatureSelection`, covering all three\r\n * historical shapes:\r\n * - `string[]` — canonical form.\r\n * - `{ FeatureName: true | false }` — object map used by early client builds;\r\n * only truthy keys are kept.\r\n * - `spec.selection` — legacy field name, used as a fallback when `features` is\r\n * absent **or an empty array**. That second condition is easy to miss and is\r\n * load-bearing: a spec with `features: []` and a populated `selection` must\r\n * resolve to `selection`.\r\n *\r\n * @param params.spec Product spec (or anything spec-shaped). May be nullish.\r\n * @returns The selected feature names. Always an array, never `undefined`.\r\n */\r\nexport const normalizeFeatureSelection = ({\r\n spec\r\n}: {\r\n spec: SelectionBearingSpec | null | undefined\r\n}): string[] => {\r\n let features: unknown = spec?.features\r\n\r\n // Object-map shape: { FeatureName: true/false }\r\n if (features !== null && typeof features === 'object' && !Array.isArray(features)) {\r\n const map = features as Record<string, boolean>\r\n features = Object.keys(map).filter((key) => map[key])\r\n }\r\n\r\n // Fall back to spec.selection when features is absent OR empty.\r\n if (!Array.isArray(features) || features.length === 0) {\r\n features = spec?.selection ?? []\r\n }\r\n\r\n return Array.isArray(features) ? (features as string[]) : []\r\n}\r\n\r\n/** Outcome of checking a selection against a feature model. */\r\nexport interface FeatureSelectionVerdict {\r\n /** Whether the selection is satisfiable under the model. */\r\n readonly valid: boolean\r\n /** The expanded selection when valid, `null` otherwise. */\r\n readonly completed: string[] | null\r\n /** Failure reason when invalid, `null` otherwise. */\r\n readonly error: string | null\r\n /**\r\n * Engine discriminator when invalid: `'TOO_MANY_CHILDS'`, `'MISSING_CHILD'`,\r\n * or `null` when the engine did not supply one.\r\n */\r\n readonly errorType: string | null\r\n}\r\n\r\n/**\r\n * Checks a feature selection against a model **without throwing**.\r\n *\r\n * Same contract as `ProductService.js:getProductHealth`, which reports\r\n * `{ valid, error, errorType }` so the UI can show why a product no longer fits\r\n * its line. `completed` is the expansion that `completeFeatureSelection` returns,\r\n * exposed so callers do not have to validate twice.\r\n *\r\n * @param params.model A model returned by `parseFeatureModel`.\r\n * @param params.features Selected feature names.\r\n * @returns The verdict. Never throws for an invalid selection.\r\n * @throws {InvalidArgumentError} only when the arguments themselves are wrong.\r\n */\r\nexport const validateFeatureSelection = ({\r\n model,\r\n features\r\n}: {\r\n model: FeatureModelValue\r\n features: string[]\r\n}): FeatureSelectionVerdict => {\r\n const checked = assertModel(model)\r\n const selection = assertFeatureArray(features)\r\n try {\r\n const completed = completeSelection(checked, selection)\r\n return { valid: true, completed, error: null, errorType: null }\r\n } catch (error) {\r\n const { message, errorType } = describeSelectionFailure(error)\r\n return { valid: false, completed: null, error: message, errorType }\r\n }\r\n}\r\n\r\n/**\r\n * Checks a feature selection and throws when it is invalid.\r\n *\r\n * This is the guard `ProductService.js:#validateSpecFeatures` puts on\r\n * create/update so a bad selection surfaces at the door instead of blowing up\r\n * during generation. The monolith lets the engine's raw `FeatureSelectionError`\r\n * escape (its `onError` maps it to a 400); linea-core wraps it in\r\n * `FeatureSelectionInvalidError` so callers get the `LineaCoreError` taxonomy\r\n * with a stable `.code` (ADR-018) — and, unlike the engine's class, a real\r\n * `Error` with a stack.\r\n *\r\n * Note the monolith's guard is best-effort in a different sense: it *skips*\r\n * validation when the selection is empty or the model cannot be read. That\r\n * skipping is a caller policy (it depends on GitLab availability), so it stays\r\n * in linea-server; here an empty selection is validated like any other.\r\n *\r\n * @param params.model A model returned by `parseFeatureModel`.\r\n * @param params.features Selected feature names.\r\n * @returns The expanded selection.\r\n * @throws {FeatureSelectionInvalidError} when the selection is not satisfiable.\r\n * @throws {InvalidArgumentError} when the arguments themselves are wrong.\r\n */\r\nexport const assertFeatureSelection = ({\r\n model,\r\n features\r\n}: {\r\n model: FeatureModelValue\r\n features: string[]\r\n}): string[] => {\r\n const verdict = validateFeatureSelection({ model, features })\r\n if (!verdict.valid || verdict.completed === null) {\r\n throw new FeatureSelectionInvalidError(\r\n verdict.error ?? 'The feature selection is not valid for this feature model.'\r\n )\r\n }\r\n return verdict.completed\r\n}\r\n\r\n/** A named feature selection, e.g. one product's. */\r\nexport interface NamedSelection {\r\n /** Identifier reported back in `broken`. */\r\n readonly name: string\r\n /** Selected feature names. */\r\n readonly features: string[]\r\n}\r\n\r\n/** Why a particular named selection no longer fits the model. */\r\nexport interface BrokenSelection {\r\n readonly name: string\r\n readonly reason: string\r\n}\r\n\r\n/** Result of checking a whole portfolio of selections against one model. */\r\nexport interface ModelAgainstSelectionsVerdict {\r\n readonly valid: boolean\r\n readonly broken: BrokenSelection[]\r\n}\r\n\r\n/**\r\n * Answers \"does this model still admit every one of these selections?\".\r\n *\r\n * Migrated from `harvest.js:validateModelAgainstProducts` (~113-133), used to\r\n * decide whether a proposed feature-model edit would break existing products.\r\n *\r\n * DELIBERATE SIGNATURE CHANGE (ADR-014): the monolith takes Mongo product\r\n * documents and digs out `product.spec` and `product.spec.basicData.name`\r\n * itself. linea-core knows nothing about persisted products, so it takes\r\n * `[{ name, features }]`. Whoever reads them — from `products.json` (ADR-011) or\r\n * from GitLab — is linea-server; pair this with `normalizeFeatureSelection` to\r\n * go from a spec to `features`.\r\n *\r\n * @param params.model A model returned by `parseFeatureModel`.\r\n * @param params.selections The named selections to check.\r\n * @returns `valid` plus one entry per broken selection. Never throws for a\r\n * broken selection.\r\n * @throws {InvalidArgumentError} when the arguments themselves are wrong.\r\n */\r\nexport const validateModelAgainstSelections = ({\r\n model,\r\n selections\r\n}: {\r\n model: FeatureModelValue\r\n selections: readonly NamedSelection[]\r\n}): ModelAgainstSelectionsVerdict => {\r\n const checked = assertModel(model)\r\n if (!isArray(selections)) {\r\n throw new InvalidArgumentError('\"selections\" must be an array of { name, features }.')\r\n }\r\n\r\n const broken: BrokenSelection[] = []\r\n for (const selection of selections) {\r\n if (selection === null || typeof selection !== 'object') {\r\n throw new InvalidArgumentError('Every entry of \"selections\" must be an object.')\r\n }\r\n if (typeof selection.name !== 'string' || selection.name === '') {\r\n throw new InvalidArgumentError('Every entry of \"selections\" needs a non-empty \"name\".')\r\n }\r\n const verdict = validateFeatureSelection({ model: checked, features: selection.features })\r\n if (!verdict.valid) {\r\n broken.push({ name: selection.name, reason: verdict.error ?? 'unknown reason' })\r\n }\r\n }\r\n\r\n return { valid: broken.length === 0, broken }\r\n}\r\n"]}
1
+ {"version":3,"file":"selection.js","sourceRoot":"","sources":["../../src/selection/selection.ts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E,KAAK,EAAE,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;AAC/C,CAAC,CAAA","sourcesContent":["/**\n * Feature selection normalisation and validation.\n *\n * Migrated from:\n * - `linea/server/src/model/services/utils.js:normalizeFeatureSelection` (~172-186)\n * - `linea/server/src/model/services/ProductService.js:#validateSpecFeatures` (~37-58)\n * - `linea/server/src/model/services/ProductService.js:getProductHealth` (~481-519),\n * which is where the `{ valid, features, error, errorType }` shape comes from\n * - `linea/server/src/agents/tools/harvest.js:validateModelAgainstProducts` (~113-133)\n *\n * The monolith spreads this logic across a service that also reads GitLab and a\n * Mongo-backed agent tool. Here it is pure: the caller supplies the parsed model\n * and the selections, and nothing reaches the network or a database.\n */\nimport { InvalidArgumentError, FeatureSelectionInvalidError } from '../errors.js'\nimport {\n completeSelection,\n describeSelectionFailure,\n type FeatureModelValue\n} from '../feature-model/engine.js'\nimport { isArray } from '../internal/guards.js'\n\n/** The three historical shapes of `spec.features` accepted by the monolith. */\nexport type FeatureSelectionInput = string[] | Record<string, boolean> | undefined\n\n/** Minimal view of a product spec needed to read its feature selection. */\nexport interface SelectionBearingSpec {\n features?: FeatureSelectionInput\n /** Deprecated field name, still present in old specs. */\n selection?: string[]\n [key: string]: unknown\n}\n\nconst assertModel = (model: unknown): FeatureModelValue => {\n if (model === null || typeof model !== 'object') {\n throw new InvalidArgumentError('\"model\" must be a value returned by parseFeatureModel().')\n }\n return model as FeatureModelValue\n}\n\nconst assertFeatureArray = (features: unknown): string[] => {\n if (!Array.isArray(features) || features.some((f) => typeof f !== 'string')) {\n throw new InvalidArgumentError('\"features\" must be an array of strings.')\n }\n return features as string[]\n}\n\n/**\n * Normalises a spec's feature selection into a plain string array.\n *\n * Verbatim behaviour of `utils.js:normalizeFeatureSelection`, covering all three\n * historical shapes:\n * - `string[]` — canonical form.\n * - `{ FeatureName: true | false }` — object map used by early client builds;\n * only truthy keys are kept.\n * - `spec.selection` — legacy field name, used as a fallback when `features` is\n * absent **or an empty array**. That second condition is easy to miss and is\n * load-bearing: a spec with `features: []` and a populated `selection` must\n * resolve to `selection`.\n *\n * @param params.spec Product spec (or anything spec-shaped). May be nullish.\n * @returns The selected feature names. Always an array, never `undefined`.\n */\nexport const normalizeFeatureSelection = ({\n spec\n}: {\n spec: SelectionBearingSpec | null | undefined\n}): string[] => {\n let features: unknown = spec?.features\n\n // Object-map shape: { FeatureName: true/false }\n if (features !== null && typeof features === 'object' && !Array.isArray(features)) {\n const map = features as Record<string, boolean>\n features = Object.keys(map).filter((key) => map[key])\n }\n\n // Fall back to spec.selection when features is absent OR empty.\n if (!Array.isArray(features) || features.length === 0) {\n features = spec?.selection ?? []\n }\n\n return Array.isArray(features) ? (features as string[]) : []\n}\n\n/** Outcome of checking a selection against a feature model. */\nexport interface FeatureSelectionVerdict {\n /** Whether the selection is satisfiable under the model. */\n readonly valid: boolean\n /** The expanded selection when valid, `null` otherwise. */\n readonly completed: string[] | null\n /** Failure reason when invalid, `null` otherwise. */\n readonly error: string | null\n /**\n * Engine discriminator when invalid: `'TOO_MANY_CHILDS'`, `'MISSING_CHILD'`,\n * or `null` when the engine did not supply one.\n */\n readonly errorType: string | null\n}\n\n/**\n * Checks a feature selection against a model **without throwing**.\n *\n * Same contract as `ProductService.js:getProductHealth`, which reports\n * `{ valid, error, errorType }` so the UI can show why a product no longer fits\n * its line. `completed` is the expansion that `completeFeatureSelection` returns,\n * exposed so callers do not have to validate twice.\n *\n * @param params.model A model returned by `parseFeatureModel`.\n * @param params.features Selected feature names.\n * @returns The verdict. Never throws for an invalid selection.\n * @throws {InvalidArgumentError} only when the arguments themselves are wrong.\n */\nexport const validateFeatureSelection = ({\n model,\n features\n}: {\n model: FeatureModelValue\n features: string[]\n}): FeatureSelectionVerdict => {\n const checked = assertModel(model)\n const selection = assertFeatureArray(features)\n try {\n const completed = completeSelection(checked, selection)\n return { valid: true, completed, error: null, errorType: null }\n } catch (error) {\n const { message, errorType } = describeSelectionFailure(error)\n return { valid: false, completed: null, error: message, errorType }\n }\n}\n\n/**\n * Checks a feature selection and throws when it is invalid.\n *\n * This is the guard `ProductService.js:#validateSpecFeatures` puts on\n * create/update so a bad selection surfaces at the door instead of blowing up\n * during generation. The monolith lets the engine's raw `FeatureSelectionError`\n * escape (its `onError` maps it to a 400); linea-core wraps it in\n * `FeatureSelectionInvalidError` so callers get the `LineaCoreError` taxonomy\n * with a stable `.code` (ADR-018) — and, unlike the engine's class, a real\n * `Error` with a stack.\n *\n * Note the monolith's guard is best-effort in a different sense: it *skips*\n * validation when the selection is empty or the model cannot be read. That\n * skipping is a caller policy (it depends on GitLab availability), so it stays\n * in linea-server; here an empty selection is validated like any other.\n *\n * @param params.model A model returned by `parseFeatureModel`.\n * @param params.features Selected feature names.\n * @returns The expanded selection.\n * @throws {FeatureSelectionInvalidError} when the selection is not satisfiable.\n * @throws {InvalidArgumentError} when the arguments themselves are wrong.\n */\nexport const assertFeatureSelection = ({\n model,\n features\n}: {\n model: FeatureModelValue\n features: string[]\n}): string[] => {\n const verdict = validateFeatureSelection({ model, features })\n if (!verdict.valid || verdict.completed === null) {\n throw new FeatureSelectionInvalidError(\n verdict.error ?? 'The feature selection is not valid for this feature model.'\n )\n }\n return verdict.completed\n}\n\n/** A named feature selection, e.g. one product's. */\nexport interface NamedSelection {\n /** Identifier reported back in `broken`. */\n readonly name: string\n /** Selected feature names. */\n readonly features: string[]\n}\n\n/** Why a particular named selection no longer fits the model. */\nexport interface BrokenSelection {\n readonly name: string\n readonly reason: string\n}\n\n/** Result of checking a whole portfolio of selections against one model. */\nexport interface ModelAgainstSelectionsVerdict {\n readonly valid: boolean\n readonly broken: BrokenSelection[]\n}\n\n/**\n * Answers \"does this model still admit every one of these selections?\".\n *\n * Migrated from `harvest.js:validateModelAgainstProducts` (~113-133), used to\n * decide whether a proposed feature-model edit would break existing products.\n *\n * DELIBERATE SIGNATURE CHANGE (ADR-014): the monolith takes Mongo product\n * documents and digs out `product.spec` and `product.spec.basicData.name`\n * itself. linea-core knows nothing about persisted products, so it takes\n * `[{ name, features }]`. Whoever reads them — from `products.json` (ADR-011) or\n * from GitLab — is linea-server; pair this with `normalizeFeatureSelection` to\n * go from a spec to `features`.\n *\n * @param params.model A model returned by `parseFeatureModel`.\n * @param params.selections The named selections to check.\n * @returns `valid` plus one entry per broken selection. Never throws for a\n * broken selection.\n * @throws {InvalidArgumentError} when the arguments themselves are wrong.\n */\nexport const validateModelAgainstSelections = ({\n model,\n selections\n}: {\n model: FeatureModelValue\n selections: readonly NamedSelection[]\n}): ModelAgainstSelectionsVerdict => {\n const checked = assertModel(model)\n if (!isArray(selections)) {\n throw new InvalidArgumentError('\"selections\" must be an array of { name, features }.')\n }\n\n const broken: BrokenSelection[] = []\n for (const selection of selections) {\n if (selection === null || typeof selection !== 'object') {\n throw new InvalidArgumentError('Every entry of \"selections\" must be an object.')\n }\n if (typeof selection.name !== 'string' || selection.name === '') {\n throw new InvalidArgumentError('Every entry of \"selections\" needs a non-empty \"name\".')\n }\n const verdict = validateFeatureSelection({ model: checked, features: selection.features })\n if (!verdict.valid) {\n broken.push({ name: selection.name, reason: verdict.error ?? 'unknown reason' })\n }\n }\n\n return { valid: broken.length === 0, broken }\n}\n"]}