@lbdudc/linea-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +358 -0
  2. package/dist/analysis/analyze.d.ts +105 -0
  3. package/dist/analysis/analyze.js +220 -0
  4. package/dist/analysis/analyze.js.map +1 -0
  5. package/dist/analysis/runtime.d.ts +97 -0
  6. package/dist/analysis/runtime.js +198 -0
  7. package/dist/analysis/runtime.js.map +1 -0
  8. package/dist/analysis/wheels/micropip-0.6.0-py3-none-any.whl +0 -0
  9. package/dist/analysis/wheels/packaging-23.2-py3-none-any.whl +0 -0
  10. package/dist/assets.d.ts +16 -0
  11. package/dist/assets.js +36 -0
  12. package/dist/assets.js.map +1 -0
  13. package/dist/constants.d.ts +77 -0
  14. package/dist/constants.js +76 -0
  15. package/dist/constants.js.map +1 -0
  16. package/dist/derivation/derive.d.ts +68 -0
  17. package/dist/derivation/derive.js +115 -0
  18. package/dist/derivation/derive.js.map +1 -0
  19. package/dist/derivation/engine.d.ts +48 -0
  20. package/dist/derivation/engine.js +98 -0
  21. package/dist/derivation/engine.js.map +1 -0
  22. package/dist/errors.d.ts +72 -0
  23. package/dist/errors.js +91 -0
  24. package/dist/errors.js.map +1 -0
  25. package/dist/feature-model/convert.d.ts +35 -0
  26. package/dist/feature-model/convert.js +47 -0
  27. package/dist/feature-model/convert.js.map +1 -0
  28. package/dist/feature-model/engine.d.ts +60 -0
  29. package/dist/feature-model/engine.js +139 -0
  30. package/dist/feature-model/engine.js.map +1 -0
  31. package/dist/feature-model/inspect.d.ts +67 -0
  32. package/dist/feature-model/inspect.js +113 -0
  33. package/dist/feature-model/inspect.js.map +1 -0
  34. package/dist/feature-model/io.d.ts +66 -0
  35. package/dist/feature-model/io.js +92 -0
  36. package/dist/feature-model/io.js.map +1 -0
  37. package/dist/feature-model/parse.d.ts +30 -0
  38. package/dist/feature-model/parse.js +36 -0
  39. package/dist/feature-model/parse.js.map +1 -0
  40. package/dist/feature-model/text.d.ts +54 -0
  41. package/dist/feature-model/text.js +126 -0
  42. package/dist/feature-model/text.js.map +1 -0
  43. package/dist/fs/archive.d.ts +23 -0
  44. package/dist/fs/archive.js +87 -0
  45. package/dist/fs/archive.js.map +1 -0
  46. package/dist/fs/diff.d.ts +40 -0
  47. package/dist/fs/diff.js +155 -0
  48. package/dist/fs/diff.js.map +1 -0
  49. package/dist/fs/format.d.ts +21 -0
  50. package/dist/fs/format.js +111 -0
  51. package/dist/fs/format.js.map +1 -0
  52. package/dist/fs/workspace.d.ts +77 -0
  53. package/dist/fs/workspace.js +103 -0
  54. package/dist/fs/workspace.js.map +1 -0
  55. package/dist/index.d.ts +50 -0
  56. package/dist/index.js +48 -0
  57. package/dist/index.js.map +1 -0
  58. package/dist/internal/guards.d.ts +15 -0
  59. package/dist/internal/guards.js +16 -0
  60. package/dist/internal/guards.js.map +1 -0
  61. package/dist/line/platform-files.d.ts +73 -0
  62. package/dist/line/platform-files.js +112 -0
  63. package/dist/line/platform-files.js.map +1 -0
  64. package/dist/line/scaffold.d.ts +88 -0
  65. package/dist/line/scaffold.js +145 -0
  66. package/dist/line/scaffold.js.map +1 -0
  67. package/dist/line/templates/core/extra.js +54 -0
  68. package/dist/line/templates/core/transformation.js +196 -0
  69. package/dist/line/templates/metamodels/dataModel/extra.js +328 -0
  70. package/dist/line/templates/metamodels/dataModel/transformation.js +211 -0
  71. package/dist/line/templates/metamodels/sensor/extra.js +36 -0
  72. package/dist/line/templates/metamodels/sensor/transformation.js +47 -0
  73. package/dist/line/templates/pipeline/.gitlab-ci.yml +51 -0
  74. package/dist/line/templates/pipeline/ci/test-client.sh +16 -0
  75. package/dist/line/templates/pipeline/ci/test-server.sh +16 -0
  76. package/dist/product/engine-spec.d.ts +25 -0
  77. package/dist/product/engine-spec.js +77 -0
  78. package/dist/product/engine-spec.js.map +1 -0
  79. package/dist/product/spec.d.ts +130 -0
  80. package/dist/product/spec.js +219 -0
  81. package/dist/product/spec.js.map +1 -0
  82. package/dist/product/version.d.ts +27 -0
  83. package/dist/product/version.js +49 -0
  84. package/dist/product/version.js.map +1 -0
  85. package/dist/products-index/products-index.d.ts +224 -0
  86. package/dist/products-index/products-index.js +395 -0
  87. package/dist/products-index/products-index.js.map +1 -0
  88. package/dist/selection/selection.d.ts +126 -0
  89. package/dist/selection/selection.js +152 -0
  90. package/dist/selection/selection.js.map +1 -0
  91. package/package.json +67 -0
@@ -0,0 +1,224 @@
1
+ /** One product of a line, as recorded in `products.json`. */
2
+ export interface ProductsIndexEntry {
3
+ /** Product name; same rules as any other name (`NAME_PATTERN`). */
4
+ readonly name: string;
5
+ /** Path of the product repository in the laboratory's GitLab. */
6
+ readonly repositorio: string;
7
+ /**
8
+ * Current product version (`VERSION_PATTERN`, i.e. `x.y.z`). **Optional**:
9
+ * every index written before this field existed is still valid, and an entry
10
+ * without it is never given one implicitly.
11
+ *
12
+ * It duplicates `spec.basicData.version`, which lives in the product's own
13
+ * repository. That is the point: the enrolled-products listing needs every
14
+ * version at once, and reading one file per product would be one GitLab
15
+ * request per row. The product repository stays the source of truth; this is
16
+ * the copy the line keeps to be able to list without fanning out.
17
+ */
18
+ readonly version?: string;
19
+ }
20
+ /** The whole index. */
21
+ export interface ProductsIndex {
22
+ readonly productos: ProductsIndexEntry[];
23
+ }
24
+ /** A problem found in an index. */
25
+ export interface ProductsIndexProblem {
26
+ /** Dotted path of the offending field, e.g. `productos[2].repositorio`. */
27
+ readonly path: string;
28
+ /** Stable machine-readable discriminator. */
29
+ readonly code: ProductsIndexProblemCode;
30
+ /**
31
+ * An i18n KEY, never a human-readable sentence — same policy as
32
+ * `ProductSpecError.messageKey`, so a consumer never has to guess whether to
33
+ * translate a value or render it raw.
34
+ *
35
+ * Two keys are inherited from the monolith and already translated:
36
+ * `invalid_name_characters` and `basicData_version_format` (the latter reads
37
+ * "Version must follow the format X.Y.Z", which is exactly the fact being
38
+ * reported, so it is reused instead of minting an untranslated twin). The
39
+ * rest are NEW (there was no products index to validate before ADR-011) and
40
+ * have no translation yet; they are listed in CHANGELOG.md for whoever
41
+ * migrates webui and linea-cli.
42
+ */
43
+ readonly messageKey: string;
44
+ }
45
+ /** Stable discriminators for index problems. */
46
+ export type ProductsIndexProblemCode = 'INDEX_NOT_OBJECT' | 'PRODUCTOS_NOT_ARRAY' | 'ENTRY_NOT_OBJECT' | 'NAME_REQUIRED' | 'NAME_INVALID_CHARACTERS' | 'NAME_DUPLICATED' | 'REPOSITORIO_REQUIRED' | 'VERSION_INVALID_FORMAT';
47
+ /** Result of validating an index. */
48
+ export interface ProductsIndexValidation {
49
+ readonly valid: boolean;
50
+ readonly errors: ProductsIndexProblem[];
51
+ }
52
+ /**
53
+ * An empty index.
54
+ *
55
+ * @returns A fresh `{ productos: [] }`. A new object every call, so callers can
56
+ * safely treat it as their own.
57
+ */
58
+ export declare const emptyProductsIndex: () => ProductsIndex;
59
+ /**
60
+ * Validates an index **without throwing**.
61
+ *
62
+ * Checks the ADR-011 shape plus the domain rules that make the index usable:
63
+ * names must be valid (`NAME_PATTERN`) and unique, and every entry needs a
64
+ * `repositorio`.
65
+ *
66
+ * @param params.index The index to validate. Anything, including nullish.
67
+ * @returns `valid` plus one entry per problem, in document order.
68
+ */
69
+ export declare const validateProductsIndex: ({ index }: {
70
+ index: unknown;
71
+ }) => ProductsIndexValidation;
72
+ /**
73
+ * Parses the JSON contents of a `products.json`.
74
+ *
75
+ * @param params.content Raw file contents.
76
+ * @returns The index, with only the normative fields kept per entry: `name`,
77
+ * `repositorio` and, when the file has it, `version`. An index written before
78
+ * `version` existed parses exactly as it always did.
79
+ * @throws {ProductsIndexError} when the JSON is malformed or does not satisfy
80
+ * the ADR-011 shape — which includes a `version` present but not `x.y.z`.
81
+ */
82
+ export declare const parseProductsIndex: ({ content }: {
83
+ content: string;
84
+ }) => ProductsIndex;
85
+ /**
86
+ * Serialises an index deterministically.
87
+ *
88
+ * Stability is a feature, not a detail: linea-server commits this file to the
89
+ * line repository on every product create/rename/delete, so an unstable
90
+ * serialisation would produce noisy diffs and spurious merge conflicts.
91
+ * Guarantees: entries sorted alphabetically by `name`, only the normative fields
92
+ * emitted and always in the same order (`name`, `repositorio`, `version`),
93
+ * two-space indentation, single trailing newline.
94
+ *
95
+ * An entry with no version emits **no `version` key** — not `null`, not `''`.
96
+ * That is what keeps an index written before this field byte-identical after a
97
+ * read/write round trip.
98
+ *
99
+ * @param params.index The index to serialise.
100
+ * @returns The JSON text to write.
101
+ * @throws {InvalidArgumentError} when `index` is not index-shaped.
102
+ */
103
+ export declare const serializeProductsIndex: ({ index }: {
104
+ index: ProductsIndex;
105
+ }) => string;
106
+ /**
107
+ * Adds a product to the index.
108
+ *
109
+ * @param params.index Current index. Not mutated.
110
+ * @param params.product Entry to add. `version` is optional; when given it must
111
+ * be `x.y.z`, and when omitted the entry simply has no version.
112
+ * @returns A new, sorted index.
113
+ * @throws {ProductsIndexError} when a product with that name is already there.
114
+ * @throws {InvalidArgumentError} when the arguments are malformed.
115
+ */
116
+ export declare const addProductToIndex: ({ index, product }: {
117
+ index: ProductsIndex;
118
+ product: ProductsIndexEntry;
119
+ }) => ProductsIndex;
120
+ /**
121
+ * Renames a product in the index, keeping its `repositorio` and its `version`.
122
+ *
123
+ * Note the repository path is intentionally left untouched: renaming a GitLab
124
+ * project does not necessarily move it, and linea-server is the only component
125
+ * that knows the new path. It should follow up with the real value if it changed.
126
+ *
127
+ * @param params.index Current index. Not mutated.
128
+ * @param params.from Current product name.
129
+ * @param params.to New product name.
130
+ * @returns A new, sorted index.
131
+ * @throws {ProductsIndexError} when `from` is missing or `to` already exists.
132
+ * @throws {InvalidArgumentError} when the arguments are malformed.
133
+ */
134
+ export declare const renameProductInIndex: ({ index, from, to }: {
135
+ index: ProductsIndex;
136
+ from: string;
137
+ to: string;
138
+ }) => ProductsIndex;
139
+ /**
140
+ * Removes a product from the index.
141
+ *
142
+ * IDEMPOTENT: removing a product that is not there returns an equivalent index
143
+ * instead of throwing, so a retried or replayed delete cannot fail half-way.
144
+ *
145
+ * @param params.index Current index. Not mutated.
146
+ * @param params.name Product to remove.
147
+ * @returns A new, sorted index.
148
+ * @throws {InvalidArgumentError} when the arguments are malformed.
149
+ */
150
+ export declare const removeProductFromIndex: ({ index, name }: {
151
+ index: ProductsIndex;
152
+ name: string;
153
+ }) => ProductsIndex;
154
+ /**
155
+ * Reads the index of a line working directory.
156
+ *
157
+ * A line with no `products.json` is a line with no products, not an error: the
158
+ * file only appears once the first product is created, and every line predating
159
+ * ADR-011 lacks it. A file that EXISTS but is corrupt is a different story and
160
+ * does throw — silently treating it as empty would let linea-server commit a
161
+ * fresh index over a real one and lose the product list.
162
+ *
163
+ * @param params.lineDir Root of the line working directory.
164
+ * @returns The index, or an empty one when the file is absent.
165
+ * @throws {ProductsIndexError} when the file exists but is malformed.
166
+ */
167
+ export declare const readProductsIndex: ({ lineDir }: {
168
+ lineDir: string;
169
+ }) => ProductsIndex;
170
+ /**
171
+ * Writes the index of a line working directory, creating it if needed.
172
+ *
173
+ * @param params.lineDir Root of the line working directory.
174
+ * @param params.index The index to write.
175
+ * @returns The absolute path written.
176
+ * @throws {InvalidArgumentError} when the arguments are malformed.
177
+ */
178
+ export declare const writeProductsIndex: ({ lineDir, index }: {
179
+ lineDir: string;
180
+ index: ProductsIndex;
181
+ }) => {
182
+ path: string;
183
+ };
184
+ /** Outcome of reconciling an index against the repositories actually observed. */
185
+ export interface ProductsIndexReconciliation {
186
+ /** The index with the newly discovered repositories added. */
187
+ readonly index: ProductsIndex;
188
+ /**
189
+ * Entries added because a repository existed but was not indexed. They carry
190
+ * a `version` only if the caller observed one.
191
+ */
192
+ readonly added: ProductsIndexEntry[];
193
+ /**
194
+ * Entries indexed but with no observed repository.
195
+ *
196
+ * REPORTED ONLY — they stay in `index`. The monolith's `prune` archived such
197
+ * rows in Mongo; without a database, dropping them here would silently destroy
198
+ * the record of a product whose repository the caller merely could not see
199
+ * (a permissions hiccup, a partial listing). linea-server decides.
200
+ */
201
+ readonly removed: ProductsIndexEntry[];
202
+ }
203
+ /**
204
+ * Reconciles an index against the repositories a caller actually observed.
205
+ *
206
+ * Adapted from the `reconcile*` pair of the monolith, which discovers GitLab
207
+ * projects by topic and creates the rows that are missing.
208
+ *
209
+ * Versions already recorded in the index are preserved verbatim, exactly like
210
+ * `repositorio`: the observation the caller makes is "this repository exists",
211
+ * not "this is the product's version", so it never overwrites what is indexed.
212
+ * A newly added entry keeps the `version` the caller supplied, if any.
213
+ *
214
+ * @param params.index Current index. Not mutated.
215
+ * @param params.repositories Repositories observed, as `{ name, repositorio }`
216
+ * plus an optional `version`. linea-server builds this from GitLab; linea-core
217
+ * never looks.
218
+ * @returns The reconciled index plus what was added and what is missing.
219
+ * @throws {InvalidArgumentError} when the arguments are malformed.
220
+ */
221
+ export declare const reconcileProductsIndex: ({ index, repositories }: {
222
+ index: ProductsIndex;
223
+ repositories: readonly ProductsIndexEntry[];
224
+ }) => ProductsIndexReconciliation;
@@ -0,0 +1,395 @@
1
+ /**
2
+ * The `products.json` index that lives at the root of every line repository.
3
+ *
4
+ * ADR-011 fixes the normative format:
5
+ *
6
+ * { "productos": [ { "name": "...", "repositorio": "/ruta/en/gitlab" } ] }
7
+ *
8
+ * The Spanish key `productos` is part of the decision and is NOT anglicised.
9
+ *
10
+ * ADR-011 foresaw its own extension ("el esquema es versionable: si se amplía
11
+ * (p. ej. versión del producto, estado), se hace de forma retrocompatible").
12
+ * That extension is now here: an entry MAY carry a `version` (`x.y.z`).
13
+ *
14
+ * { "productos": [ { "name": "...", "repositorio": "...", "version": "1.2.3" } ] }
15
+ *
16
+ * It is OPTIONAL and the compatibility rule is strict in both directions:
17
+ * - an index written before this change parses, validates and serialises
18
+ * exactly as before — no key appears out of nowhere;
19
+ * - an entry with no version does NOT emit `"version": null` or `""`, so
20
+ * reading and rewriting an old index is a byte-for-byte no-op.
21
+ * The reason it lives in the line's index at all — instead of in each product
22
+ * repository, where the rest of the spec lives — is that listing the products of
23
+ * a line has to show every version at once: one read per line instead of one
24
+ * GitLab request per product.
25
+ *
26
+ * This index replaces the `products` Mongo collection of the monolith, so there
27
+ * is no single function to migrate: the reconciliation semantics are adapted
28
+ * from `linea/server/src/model/services/LineService.js:reconcileLines` (~134-193)
29
+ * and `ProductService.js:reconcileProducts` (~232-295).
30
+ *
31
+ * Two deliberate departures from those (ADR-014, ADR-009):
32
+ * - No database and no `archived` flag, so there is **no `prune`**. Entries that
33
+ * no longer have a repository are REPORTED in `removed`, never dropped.
34
+ * Deciding what to do about them is linea-server's call.
35
+ * - Every mutation is pure: `add`/`rename`/`remove`/`reconcile` return a NEW
36
+ * index and never touch the input, so a caller can diff before committing.
37
+ */
38
+ import path from 'node:path';
39
+ import { NAME_PATTERN, PRODUCTS_INDEX_PATH, VERSION_PATTERN } from '../constants.js';
40
+ import { InvalidArgumentError, ProductsIndexError } from '../errors.js';
41
+ import { fileExists, readTextFile, writeTextFile } from '../fs/workspace.js';
42
+ import { isArray, isPlainObject } from '../internal/guards.js';
43
+ /** Alphabetical by `name`, so serialisation is stable across callers. */
44
+ const byName = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
45
+ /**
46
+ * Builds a normalised entry, keeping ONLY the normative fields.
47
+ *
48
+ * The `version` key is omitted altogether when there is no usable version, and
49
+ * that omission is the whole retro-compatibility guarantee: emitting `null` or
50
+ * `''` would change the bytes of every pre-existing `products.json` the moment
51
+ * linea-server read it and wrote it back.
52
+ */
53
+ const normalizeEntry = ({ name, repositorio, version }) => typeof version === 'string' && version !== ''
54
+ ? { name, repositorio, version }
55
+ : { name, repositorio };
56
+ /**
57
+ * Guards an incoming optional version. Absent (`undefined`) is fine; anything
58
+ * else has to be a `x.y.z` string.
59
+ *
60
+ * The mutating functions THROW here rather than reporting, unlike
61
+ * `validateProductsIndex`: they take their input from a caller's arguments, not
62
+ * from a file on disk, so a bad value is a programming error (ADR-018).
63
+ */
64
+ const assertOptionalVersion = ({ version, label }) => {
65
+ if (version === undefined)
66
+ return;
67
+ if (typeof version !== 'string' || !VERSION_PATTERN.test(version)) {
68
+ throw new InvalidArgumentError(`${label} must be a version like "1.2.3"; got ${JSON.stringify(version)}.`);
69
+ }
70
+ };
71
+ const assertIndex = (index) => {
72
+ if (!isPlainObject(index) || !Array.isArray(index.productos)) {
73
+ throw new InvalidArgumentError('"index" must be a { productos: [...] } object.');
74
+ }
75
+ return index;
76
+ };
77
+ /**
78
+ * An empty index.
79
+ *
80
+ * @returns A fresh `{ productos: [] }`. A new object every call, so callers can
81
+ * safely treat it as their own.
82
+ */
83
+ export const emptyProductsIndex = () => ({ productos: [] });
84
+ /**
85
+ * Validates an index **without throwing**.
86
+ *
87
+ * Checks the ADR-011 shape plus the domain rules that make the index usable:
88
+ * names must be valid (`NAME_PATTERN`) and unique, and every entry needs a
89
+ * `repositorio`.
90
+ *
91
+ * @param params.index The index to validate. Anything, including nullish.
92
+ * @returns `valid` plus one entry per problem, in document order.
93
+ */
94
+ export const validateProductsIndex = ({ index }) => {
95
+ if (!isPlainObject(index)) {
96
+ return {
97
+ valid: false,
98
+ errors: [{
99
+ path: '(root)',
100
+ code: 'INDEX_NOT_OBJECT',
101
+ messageKey: 'error_messages.products_index_not_object'
102
+ }]
103
+ };
104
+ }
105
+ if (!Array.isArray(index.productos)) {
106
+ return {
107
+ valid: false,
108
+ errors: [{
109
+ path: 'productos',
110
+ code: 'PRODUCTOS_NOT_ARRAY',
111
+ messageKey: 'error_messages.products_index_productos_not_array'
112
+ }]
113
+ };
114
+ }
115
+ const errors = [];
116
+ const seen = new Set();
117
+ index.productos.forEach((entry, position) => {
118
+ const at = `productos[${position}]`;
119
+ if (!isPlainObject(entry)) {
120
+ errors.push({
121
+ path: at,
122
+ code: 'ENTRY_NOT_OBJECT',
123
+ messageKey: 'error_messages.products_index_entry_not_object'
124
+ });
125
+ return;
126
+ }
127
+ const { name, repositorio, version } = entry;
128
+ if (typeof name !== 'string' || name === '') {
129
+ errors.push({
130
+ path: `${at}.name`,
131
+ code: 'NAME_REQUIRED',
132
+ messageKey: 'error_messages.products_index_name_required'
133
+ });
134
+ }
135
+ else if (!NAME_PATTERN.test(name)) {
136
+ errors.push({
137
+ path: `${at}.name`,
138
+ code: 'NAME_INVALID_CHARACTERS',
139
+ messageKey: 'error_messages.invalid_name_characters'
140
+ });
141
+ }
142
+ else if (seen.has(name)) {
143
+ errors.push({
144
+ path: `${at}.name`,
145
+ code: 'NAME_DUPLICATED',
146
+ messageKey: 'error_messages.products_index_name_duplicated'
147
+ });
148
+ }
149
+ else {
150
+ seen.add(name);
151
+ }
152
+ if (typeof repositorio !== 'string' || repositorio === '') {
153
+ errors.push({
154
+ path: `${at}.repositorio`,
155
+ code: 'REPOSITORIO_REQUIRED',
156
+ messageKey: 'error_messages.products_index_repositorio_required'
157
+ });
158
+ }
159
+ // OPTIONAL: absent is valid, and only `undefined` counts as absent. `''`,
160
+ // `null` and numbers are attempts at a version, and a wrong one is worth
161
+ // reporting: silently accepting them would put junk in the field the
162
+ // enrolled-products listing renders.
163
+ if (version !== undefined && (typeof version !== 'string' || !VERSION_PATTERN.test(version))) {
164
+ errors.push({
165
+ path: `${at}.version`,
166
+ code: 'VERSION_INVALID_FORMAT',
167
+ messageKey: 'error_messages.basicData_version_format'
168
+ });
169
+ }
170
+ });
171
+ return { valid: errors.length === 0, errors };
172
+ };
173
+ /**
174
+ * Parses the JSON contents of a `products.json`.
175
+ *
176
+ * @param params.content Raw file contents.
177
+ * @returns The index, with only the normative fields kept per entry: `name`,
178
+ * `repositorio` and, when the file has it, `version`. An index written before
179
+ * `version` existed parses exactly as it always did.
180
+ * @throws {ProductsIndexError} when the JSON is malformed or does not satisfy
181
+ * the ADR-011 shape — which includes a `version` present but not `x.y.z`.
182
+ */
183
+ export const parseProductsIndex = ({ content }) => {
184
+ if (typeof content !== 'string') {
185
+ throw new InvalidArgumentError('"content" must be a string.');
186
+ }
187
+ if (content.trim() === '')
188
+ return emptyProductsIndex();
189
+ let parsed;
190
+ try {
191
+ parsed = JSON.parse(content);
192
+ }
193
+ catch (error) {
194
+ throw new ProductsIndexError(`products.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
195
+ }
196
+ const validation = validateProductsIndex({ index: parsed });
197
+ if (!validation.valid) {
198
+ const summary = validation.errors.map((e) => `${e.path}: ${e.messageKey}`).join('; ');
199
+ throw new ProductsIndexError(`products.json does not satisfy the ADR-011 format: ${summary}`);
200
+ }
201
+ const index = parsed;
202
+ return { productos: index.productos.map(normalizeEntry) };
203
+ };
204
+ /**
205
+ * Serialises an index deterministically.
206
+ *
207
+ * Stability is a feature, not a detail: linea-server commits this file to the
208
+ * line repository on every product create/rename/delete, so an unstable
209
+ * serialisation would produce noisy diffs and spurious merge conflicts.
210
+ * Guarantees: entries sorted alphabetically by `name`, only the normative fields
211
+ * emitted and always in the same order (`name`, `repositorio`, `version`),
212
+ * two-space indentation, single trailing newline.
213
+ *
214
+ * An entry with no version emits **no `version` key** — not `null`, not `''`.
215
+ * That is what keeps an index written before this field byte-identical after a
216
+ * read/write round trip.
217
+ *
218
+ * @param params.index The index to serialise.
219
+ * @returns The JSON text to write.
220
+ * @throws {InvalidArgumentError} when `index` is not index-shaped.
221
+ */
222
+ export const serializeProductsIndex = ({ index }) => {
223
+ const checked = assertIndex(index);
224
+ const productos = [...checked.productos].sort(byName).map(normalizeEntry);
225
+ return `${JSON.stringify({ productos }, null, 2)}\n`;
226
+ };
227
+ /**
228
+ * Adds a product to the index.
229
+ *
230
+ * @param params.index Current index. Not mutated.
231
+ * @param params.product Entry to add. `version` is optional; when given it must
232
+ * be `x.y.z`, and when omitted the entry simply has no version.
233
+ * @returns A new, sorted index.
234
+ * @throws {ProductsIndexError} when a product with that name is already there.
235
+ * @throws {InvalidArgumentError} when the arguments are malformed.
236
+ */
237
+ export const addProductToIndex = ({ index, product }) => {
238
+ const checked = assertIndex(index);
239
+ if (!isPlainObject(product)) {
240
+ throw new InvalidArgumentError('"product" must be a { name, repositorio } object.');
241
+ }
242
+ const { name, repositorio, version } = product;
243
+ if (typeof name !== 'string' || !NAME_PATTERN.test(name)) {
244
+ throw new InvalidArgumentError(`Invalid product name ${JSON.stringify(name)}.`);
245
+ }
246
+ if (typeof repositorio !== 'string' || repositorio === '') {
247
+ throw new InvalidArgumentError('"product.repositorio" must be a non-empty string.');
248
+ }
249
+ assertOptionalVersion({ version, label: '"product.version"' });
250
+ if (checked.productos.some((entry) => entry.name === name)) {
251
+ throw new ProductsIndexError(`Product "${name}" is already in the index.`);
252
+ }
253
+ return {
254
+ productos: [...checked.productos, normalizeEntry({ name, repositorio, version })].sort(byName)
255
+ };
256
+ };
257
+ /**
258
+ * Renames a product in the index, keeping its `repositorio` and its `version`.
259
+ *
260
+ * Note the repository path is intentionally left untouched: renaming a GitLab
261
+ * project does not necessarily move it, and linea-server is the only component
262
+ * that knows the new path. It should follow up with the real value if it changed.
263
+ *
264
+ * @param params.index Current index. Not mutated.
265
+ * @param params.from Current product name.
266
+ * @param params.to New product name.
267
+ * @returns A new, sorted index.
268
+ * @throws {ProductsIndexError} when `from` is missing or `to` already exists.
269
+ * @throws {InvalidArgumentError} when the arguments are malformed.
270
+ */
271
+ export const renameProductInIndex = ({ index, from, to }) => {
272
+ const checked = assertIndex(index);
273
+ if (typeof from !== 'string' || from === '') {
274
+ throw new InvalidArgumentError('"from" must be a non-empty string.');
275
+ }
276
+ if (typeof to !== 'string' || !NAME_PATTERN.test(to)) {
277
+ throw new InvalidArgumentError(`Invalid product name ${JSON.stringify(to)}.`);
278
+ }
279
+ if (!checked.productos.some((entry) => entry.name === from)) {
280
+ throw new ProductsIndexError(`Product "${from}" is not in the index.`);
281
+ }
282
+ if (from !== to && checked.productos.some((entry) => entry.name === to)) {
283
+ throw new ProductsIndexError(`Product "${to}" is already in the index.`);
284
+ }
285
+ return {
286
+ productos: checked.productos
287
+ .map((entry) => (entry.name === from ? normalizeEntry({ ...entry, name: to }) : entry))
288
+ .sort(byName)
289
+ };
290
+ };
291
+ /**
292
+ * Removes a product from the index.
293
+ *
294
+ * IDEMPOTENT: removing a product that is not there returns an equivalent index
295
+ * instead of throwing, so a retried or replayed delete cannot fail half-way.
296
+ *
297
+ * @param params.index Current index. Not mutated.
298
+ * @param params.name Product to remove.
299
+ * @returns A new, sorted index.
300
+ * @throws {InvalidArgumentError} when the arguments are malformed.
301
+ */
302
+ export const removeProductFromIndex = ({ index, name }) => {
303
+ const checked = assertIndex(index);
304
+ if (typeof name !== 'string' || name === '') {
305
+ throw new InvalidArgumentError('"name" must be a non-empty string.');
306
+ }
307
+ return { productos: checked.productos.filter((entry) => entry.name !== name).sort(byName) };
308
+ };
309
+ /**
310
+ * Reads the index of a line working directory.
311
+ *
312
+ * A line with no `products.json` is a line with no products, not an error: the
313
+ * file only appears once the first product is created, and every line predating
314
+ * ADR-011 lacks it. A file that EXISTS but is corrupt is a different story and
315
+ * does throw — silently treating it as empty would let linea-server commit a
316
+ * fresh index over a real one and lose the product list.
317
+ *
318
+ * @param params.lineDir Root of the line working directory.
319
+ * @returns The index, or an empty one when the file is absent.
320
+ * @throws {ProductsIndexError} when the file exists but is malformed.
321
+ */
322
+ export const readProductsIndex = ({ lineDir }) => {
323
+ if (typeof lineDir !== 'string' || lineDir.trim() === '') {
324
+ throw new InvalidArgumentError('"lineDir" must be a non-empty path.');
325
+ }
326
+ const filePath = path.join(path.resolve(lineDir), PRODUCTS_INDEX_PATH);
327
+ if (!fileExists({ filePath }))
328
+ return emptyProductsIndex();
329
+ return parseProductsIndex({ content: readTextFile({ filePath }) });
330
+ };
331
+ /**
332
+ * Writes the index of a line working directory, creating it if needed.
333
+ *
334
+ * @param params.lineDir Root of the line working directory.
335
+ * @param params.index The index to write.
336
+ * @returns The absolute path written.
337
+ * @throws {InvalidArgumentError} when the arguments are malformed.
338
+ */
339
+ export const writeProductsIndex = ({ lineDir, index }) => {
340
+ if (typeof lineDir !== 'string' || lineDir.trim() === '') {
341
+ throw new InvalidArgumentError('"lineDir" must be a non-empty path.');
342
+ }
343
+ const content = serializeProductsIndex({ index });
344
+ const filePath = path.join(path.resolve(lineDir), PRODUCTS_INDEX_PATH);
345
+ return { path: writeTextFile({ filePath, content }) };
346
+ };
347
+ /**
348
+ * Reconciles an index against the repositories a caller actually observed.
349
+ *
350
+ * Adapted from the `reconcile*` pair of the monolith, which discovers GitLab
351
+ * projects by topic and creates the rows that are missing.
352
+ *
353
+ * Versions already recorded in the index are preserved verbatim, exactly like
354
+ * `repositorio`: the observation the caller makes is "this repository exists",
355
+ * not "this is the product's version", so it never overwrites what is indexed.
356
+ * A newly added entry keeps the `version` the caller supplied, if any.
357
+ *
358
+ * @param params.index Current index. Not mutated.
359
+ * @param params.repositories Repositories observed, as `{ name, repositorio }`
360
+ * plus an optional `version`. linea-server builds this from GitLab; linea-core
361
+ * never looks.
362
+ * @returns The reconciled index plus what was added and what is missing.
363
+ * @throws {InvalidArgumentError} when the arguments are malformed.
364
+ */
365
+ export const reconcileProductsIndex = ({ index, repositories }) => {
366
+ const checked = assertIndex(index);
367
+ if (!isArray(repositories)) {
368
+ throw new InvalidArgumentError('"repositories" must be an array of { name, repositorio }.');
369
+ }
370
+ for (const repository of repositories) {
371
+ if (!isPlainObject(repository) ||
372
+ typeof repository.name !== 'string' || repository.name === '' ||
373
+ typeof repository.repositorio !== 'string' || repository.repositorio === '') {
374
+ throw new InvalidArgumentError('Every entry of "repositories" must be a { name, repositorio } object with non-empty strings.');
375
+ }
376
+ assertOptionalVersion({
377
+ version: repository.version,
378
+ label: `"repositories[${repository.name}].version"`
379
+ });
380
+ }
381
+ const indexed = new Set(checked.productos.map((entry) => entry.name));
382
+ const observed = new Set(repositories.map((repository) => repository.name));
383
+ const added = repositories
384
+ .filter((repository) => !indexed.has(repository.name))
385
+ .map(normalizeEntry);
386
+ const removed = checked.productos
387
+ .filter((entry) => !observed.has(entry.name))
388
+ .map(normalizeEntry);
389
+ return {
390
+ index: { productos: [...checked.productos, ...added].sort(byName) },
391
+ added: [...added].sort(byName),
392
+ removed: [...removed].sort(byName)
393
+ };
394
+ };
395
+ //# sourceMappingURL=products-index.js.map