@pubid/pubid 0.1.44 → 0.1.45

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.
@@ -0,0 +1,666 @@
1
+ import { ParseFailed } from "../../grammar/engine.js";
2
+ import { PubidRuntime } from "../../parg/runtime.js";
3
+ import { BaseIdentifier, resolveType } from "../../model/identifier.js";
4
+ import { extendAttributes, keyValue } from "../../model/attribute.js";
5
+ import { PubidDate } from "../../model/component.js";
6
+ import { BaseUrnGenerator } from "../../model/urn-generator.js";
7
+ import { grammarImplementation } from "../index.js";
8
+ import { mrFromHash } from "../cen_cenelec/model.js";
9
+ export const STAGES = {
10
+ pren: { code: "pren", stage_code: "proposal", type_code: "en", abbr: "prEN" },
11
+ fpren: { code: "fpren", stage_code: "final_proposal", type_code: "en", abbr: "FprEN" },
12
+ };
13
+ /** The captured spelling → the serialized stage code (the builder's
14
+ * STAGE_MAP). */
15
+ const STAGE_MAP = {
16
+ prEN: "pren",
17
+ FprEN: "fpren",
18
+ };
19
+ export function locateStageByCode(code) {
20
+ return STAGES[code];
21
+ }
22
+ /** Ruby truthiness for a captured face: an absent capture is absent. */
23
+ function present(value) {
24
+ return value !== undefined && value !== null && value !== "";
25
+ }
26
+ function strOf(value) {
27
+ if (!present(value))
28
+ return undefined;
29
+ return String(value);
30
+ }
31
+ /** A raw capture leaf ({value, line, …}) yields its value; a bound
32
+ * scalar passes through (the run's internal captures bind only through
33
+ * the item row, so unbound ones arrive as raw leaves). */
34
+ function unwrap(capture) {
35
+ if (typeof capture === "object" && capture !== null && "value" in capture) {
36
+ return capture["value"];
37
+ }
38
+ return capture;
39
+ }
40
+ /** The builder's present_string: a capture the grammar bound as an
41
+ * empty string stores as nil (to_hash drops the empty string, so
42
+ * from_hash would give nil and the two identifiers would not be ==). */
43
+ function presentString(value) {
44
+ const s = strOf(value);
45
+ return s === undefined || s === "" ? undefined : s;
46
+ }
47
+ function isRecord(value) {
48
+ return typeof value === "object" && value !== null && !Array.isArray(value);
49
+ }
50
+ /** The publisher face: the captured column, else the class's declared
51
+ * publisher default (feature 5) — Ruby's default-valued Publisher
52
+ * component, which the render view and the fused URN group read. */
53
+ function publisherFace(id) {
54
+ const bound = strOf(id.publisher);
55
+ if (bound !== undefined)
56
+ return bound;
57
+ const spec = id.constructor.attributes["publisher"];
58
+ return typeof spec?.default === "string" ? spec.default : undefined;
59
+ }
60
+ /**
61
+ * The compiled flavor's identifier base: the shared render machinery
62
+ * (the definition's canonical template) and the FLAVOR-LOCAL type
63
+ * dispatch. The concrete classes carry the scheme's canonical wire tags
64
+ * (pubid:cencenelec:…), which deliberately stay OUT of the global type
65
+ * map — one scheme, one `_type`, one global resolution (the coded
66
+ * class); {@linkcode fromHash} routes the tags back here flavor-locally
67
+ * first (mirroring Ruby's flavor-base polymorphic_type_map), then falls
68
+ * through to the global registry for the cross-flavor nested identifiers
69
+ * (the adopted ISO/IEC document), exactly the TypeResolver order.
70
+ */
71
+ export class CenPfsIdentifier extends BaseIdentifier {
72
+ /** The wire tags the compiled classes answer, resolved flavor-locally. */
73
+ static localTypeMap = new Map();
74
+ /** The alias's own from_hash: the scheme tags route HERE, the
75
+ * cross-flavor tags (a nested adopted ISO/IEC document) fall through
76
+ * to the global registry, while the cen tags never reach the coded
77
+ * classes (coexistence, not cutover). */
78
+ static fromHash(hash) {
79
+ const tag = typeof hash["_type"] === "string" ? hash["_type"] : undefined;
80
+ const klass = tag !== undefined ? this.localTypeMap.get(tag) : undefined;
81
+ if (klass === undefined && tag !== undefined) {
82
+ const global = resolveType(tag);
83
+ if (global !== undefined)
84
+ return global.fromHash(hash);
85
+ }
86
+ const target = (klass ?? this);
87
+ return new target(target.applyMappings(target.inflateScalarComponents(hash)));
88
+ }
89
+ /** The definition's canonical face — the head alternation picks the
90
+ * first alternative whose direct fields captured: the draft face, the
91
+ * Guide word face, the adopted face, else the publisher face with the
92
+ * optional slash type; the run and the FRAG face follow. */
93
+ render() {
94
+ let root = this;
95
+ let run = "";
96
+ let members;
97
+ let frag;
98
+ if (root instanceof CenPfsFragment) {
99
+ frag = root.number;
100
+ root = root.base ?? root;
101
+ }
102
+ if (root instanceof CenPfsConsolidatedIdentifier) {
103
+ const [base, ...consolidated] = root.identifiers;
104
+ members = consolidated;
105
+ root = base ?? root;
106
+ }
107
+ while (root instanceof CenPfsSupplement) {
108
+ run = `/${root.supplementNotation()}${run}`;
109
+ root = root.base ?? root;
110
+ }
111
+ if (members !== undefined) {
112
+ for (const member of members) {
113
+ run += `+${member.supplementNotation()}`;
114
+ }
115
+ }
116
+ const view = {
117
+ publisher: publisherFace(root),
118
+ copublishers: root.copublishers !== undefined && root.copublishers.length > 0
119
+ ? root.copublishers.map((item) => `/${item}`).join("")
120
+ : undefined,
121
+ stage: root.typedStage?.abbr,
122
+ type: root.type !== undefined && (root.type === "TR" || root.type === "TS")
123
+ ? root.type
124
+ : undefined,
125
+ guide: root.type === "Guide" ? root.type : undefined,
126
+ number: strOf(root.number),
127
+ part: strOf(root.part),
128
+ version: root.version,
129
+ year: root.date?.year,
130
+ adopted: root["adopted"],
131
+ };
132
+ let head = "";
133
+ if (present(view.stage) && present(view.number)) {
134
+ head =
135
+ `${view.stage} ${view.number}` +
136
+ `${present(view.part) ? `-${view.part}` : ""}` +
137
+ `${present(view.version) ? String(view.version) : ""}` +
138
+ `${present(view.year) ? `:${view.year}` : ""}`;
139
+ }
140
+ else if (present(view.publisher) && present(view.guide) && present(view.number)) {
141
+ head =
142
+ `${view.publisher}${view.copublishers ?? ""} ${view.guide} ${view.number}` +
143
+ `${present(view.part) ? `-${view.part}` : ""}` +
144
+ `${present(view.year) ? `:${view.year}` : ""}`;
145
+ }
146
+ else if (present(view.publisher) && view.adopted !== undefined && view.adopted !== null) {
147
+ head = `${view.publisher}${view.copublishers ?? ""} ${String(view.adopted)}`;
148
+ }
149
+ else if (present(view.publisher) && present(view.number)) {
150
+ head =
151
+ `${view.publisher}${view.copublishers ?? ""}` +
152
+ `${present(view.type) ? `/${view.type}` : ""} ${view.number}` +
153
+ `${present(view.part) ? `-${view.part}` : ""}` +
154
+ `${present(view.version) ? String(view.version) : ""}` +
155
+ `${present(view.year) ? `:${view.year}` : ""}`;
156
+ }
157
+ const tail = run === ""
158
+ ? ""
159
+ : `${run}${present(frag) ? ` FRAG${frag}` : ""}`;
160
+ return head + tail;
161
+ }
162
+ }
163
+ /**
164
+ * The official URN: the definition's urn.official fused segments —
165
+ * urn:cen[:<publisher group>][:<adopted fused MR>][:<composed
166
+ * code>][:<year>][:<stage code>]; a wrapper reads through to its
167
+ * subject and appends its declared chain (:amd:/:cor:), the
168
+ * consolidated bundle marks each member with the plus marker, and the
169
+ * fragment's :frag: segments come last.
170
+ */
171
+ class CenPfsUrnGenerator extends BaseUrnGenerator {
172
+ generate() {
173
+ let id = this.identifier;
174
+ let fragSegments = [];
175
+ const wrapper = [];
176
+ let members;
177
+ if (id instanceof CenPfsFragment) {
178
+ fragSegments = wrapperSegments(id);
179
+ id = id.base ?? id;
180
+ }
181
+ if (id instanceof CenPfsConsolidatedIdentifier) {
182
+ const [base, ...consolidated] = id.identifiers;
183
+ members = consolidated;
184
+ id = base ?? id;
185
+ }
186
+ while (id instanceof CenPfsSupplement) {
187
+ wrapper.unshift(...wrapperSegments(id));
188
+ id = id.base ?? id;
189
+ }
190
+ const parts = ["urn", "cen", ...officialSegments(id), ...wrapper];
191
+ if (members !== undefined) {
192
+ for (const member of members)
193
+ parts.push("plus", ...wrapperSegments(member));
194
+ }
195
+ parts.push(...fragSegments);
196
+ return parts.join(":");
197
+ }
198
+ }
199
+ /** The fused official segments: the publisher group, the adopted
200
+ * document's MR string with its separators fused to colons, the
201
+ * composed code, the year, the draft-stage code. */
202
+ function officialSegments(id) {
203
+ const segments = [];
204
+ const group = [publisherFace(id), ...(id.copublishers ?? [])]
205
+ .filter((p) => present(p))
206
+ .map((p) => String(p).toLowerCase());
207
+ if (group.length > 0)
208
+ segments.push(group.join("-"));
209
+ const adopted = id["adopted"];
210
+ if (adopted !== undefined && adopted !== null) {
211
+ const mr = mrFromHash(adopted.toHash());
212
+ if (mr !== "")
213
+ segments.push(mr.replaceAll(".", ":").replaceAll("_", ":"));
214
+ }
215
+ const code = [
216
+ strOf(id.number),
217
+ present(id.part) ? `-${id.part}` : undefined,
218
+ ].filter((c) => present(c));
219
+ if (code.length > 0)
220
+ segments.push(code.join(""));
221
+ const date = [id.date?.year].filter((y) => present(y));
222
+ if (date.length > 0)
223
+ segments.push(date.join("-"));
224
+ const stageCode = id.typedStage?.stage_code;
225
+ if (stageCode !== undefined && stageCode !== "published") {
226
+ segments.push(`stage.${stageCode}`);
227
+ }
228
+ return segments;
229
+ }
230
+ /** One wrapper's declared URN chain: the kind word, then the wrapper's
231
+ * columns (the ordinal, the year-month date). */
232
+ function wrapperSegments(id) {
233
+ let segments;
234
+ if (id instanceof CenPfsAmendment) {
235
+ segments = ["amd", id.number, id.year];
236
+ }
237
+ else if (id instanceof CenPfsCorrigendum) {
238
+ segments = ["cor", id.number, id.supplementDate()];
239
+ }
240
+ else if (id instanceof CenPfsFragment) {
241
+ segments = ["frag", id.number];
242
+ }
243
+ else {
244
+ segments = [];
245
+ }
246
+ return segments.map((s) => String(s ?? "")).filter((s) => s !== "");
247
+ }
248
+ // --- the compiled class family -------------------------------------------------
249
+ /** The stage wire: the typed stage serializes as its compact code
250
+ * ("stage" => "pren") and reads back through the declared subset. */
251
+ const stageWire = {
252
+ wire: "stage",
253
+ to: "typedStage",
254
+ toWire: (model) => model["typedStage"]?.code,
255
+ fromWire: (hash) => {
256
+ const code = hash["stage"];
257
+ return typeof code === "string" ? locateStageByCode(code) : undefined;
258
+ },
259
+ };
260
+ /** A declared document family: the columns the coded builder casts, the
261
+ * class defaults, and the whitelist that keeps the wire flat. */
262
+ function documentClass(spec) {
263
+ class CenPfsDocument extends CenPfsIdentifier {
264
+ static get polymorphicName() {
265
+ return spec.tag;
266
+ }
267
+ static get attributes() {
268
+ return extendAttributes(BaseIdentifier, {
269
+ number: { type: "string" },
270
+ part: { type: "string" },
271
+ version: { type: "string" },
272
+ date: { type: PubidDate },
273
+ publisher: { type: "string", default: spec.publisher },
274
+ copublishers: { type: "string", collection: true },
275
+ type: { type: "string", default: spec.type },
276
+ typedStage: { type: "string" },
277
+ ...(spec.adopted
278
+ ? { adopted: { type: CenPfsIdentifier } }
279
+ : {}),
280
+ });
281
+ }
282
+ static get mappings() {
283
+ return keyValue({ wire: "number", to: "number" }, { wire: "part", to: "part" }, { wire: "version", to: "version" }, { wire: "date", to: "date" }, { wire: "publisher", to: "publisher" }, { wire: "copublishers", to: "copublishers" }, { wire: "type", to: "type" }, stageWire, ...(spec.adopted
284
+ ? [{ wire: "adopted", to: "adopted" }]
285
+ : []));
286
+ }
287
+ static urnGenerator = CenPfsUrnGenerator;
288
+ }
289
+ return CenPfsDocument;
290
+ }
291
+ /** The nine deliverable families plus the adoption wrapper (the
292
+ * definition's `types:` map): the token-free EuropeanNorm is the
293
+ * default class. */
294
+ export const CenPfsEuropeanNorm = documentClass({
295
+ tag: "pubid:cencenelec:european-norm",
296
+ publisher: "EN",
297
+ type: "EN",
298
+ });
299
+ export const CenPfsAdoptedEuropeanNorm = documentClass({
300
+ tag: "pubid:cencenelec:adopted-european-norm",
301
+ publisher: "EN",
302
+ type: "EN",
303
+ adopted: true,
304
+ });
305
+ export const CenPfsTechnicalReport = documentClass({
306
+ tag: "pubid:cencenelec:technical-report",
307
+ publisher: "EN",
308
+ type: "TR",
309
+ });
310
+ export const CenPfsTechnicalSpecification = documentClass({
311
+ tag: "pubid:cencenelec:technical-specification",
312
+ publisher: "EN",
313
+ type: "TS",
314
+ });
315
+ export const CenPfsGuide = documentClass({
316
+ tag: "pubid:cencenelec:guide",
317
+ publisher: "EN",
318
+ type: "Guide",
319
+ });
320
+ export const CenPfsCenReport = documentClass({
321
+ tag: "pubid:cencenelec:cen-report",
322
+ publisher: "CR",
323
+ type: "CR",
324
+ });
325
+ export const CenPfsCenWorkshopAgreement = documentClass({
326
+ tag: "pubid:cencenelec:cen-workshop-agreement",
327
+ publisher: "CWA",
328
+ type: "CWA",
329
+ });
330
+ export const CenPfsEuropeanSpecification = documentClass({
331
+ tag: "pubid:cencenelec:european-specification",
332
+ publisher: "ES",
333
+ type: "ES",
334
+ });
335
+ export const CenPfsEuropeanPrestandard = documentClass({
336
+ tag: "pubid:cencenelec:european-prestandard",
337
+ publisher: "ENV",
338
+ type: "ENV",
339
+ adopted: true,
340
+ });
341
+ export const CenPfsHarmonizationDocument = documentClass({
342
+ tag: "pubid:cencenelec:harmonization-document",
343
+ publisher: "HD",
344
+ type: "HD",
345
+ });
346
+ /** The type each declared token selects (feature 1); the token-free
347
+ * type is the default class. */
348
+ const TYPE_TOKENS = {
349
+ TR: CenPfsTechnicalReport,
350
+ TS: CenPfsTechnicalSpecification,
351
+ Guide: CenPfsGuide,
352
+ CR: CenPfsCenReport,
353
+ CWA: CenPfsCenWorkshopAgreement,
354
+ ES: CenPfsEuropeanSpecification,
355
+ ENV: CenPfsEuropeanPrestandard,
356
+ HD: CenPfsHarmonizationDocument,
357
+ };
358
+ /** The supplement wrapper base: the wrapper owns its ordinal and the
359
+ * base identifier; every rendered face reads through. */
360
+ class CenPfsSupplement extends CenPfsIdentifier {
361
+ static get attributes() {
362
+ return extendAttributes(BaseIdentifier, {
363
+ base: { type: CenPfsIdentifier },
364
+ number: { type: "string" },
365
+ year: { type: "string" },
366
+ month: { type: "string" },
367
+ });
368
+ }
369
+ static get mappings() {
370
+ return keyValue({ wire: "base", to: "base" }, { wire: "number", to: "number" }, { wire: "year", to: "year" }, { wire: "month", to: "month" });
371
+ }
372
+ static urnGenerator = CenPfsUrnGenerator;
373
+ /** The wrapper's date: "2016-11", "2003", or undefined. */
374
+ supplementDate() {
375
+ if (!present(this.year))
376
+ return undefined;
377
+ return [this.year, this.month]
378
+ .filter((m) => present(m))
379
+ .join("-");
380
+ }
381
+ /** The printed notation: the kind face, the ordinal (absent for an
382
+ * unnumbered corrigendum) and the declared date tail. */
383
+ supplementNotation() {
384
+ return (this.constructor.FACE +
385
+ (this.number ?? "") +
386
+ (present(this.year) ? `:${this.year}` : "") +
387
+ (present(this.month) ? `-${this.month}` : ""));
388
+ }
389
+ }
390
+ export class CenPfsAmendment extends CenPfsSupplement {
391
+ /** The kind face "A" is the run's dispatch token and the notation
392
+ * face. */
393
+ static get polymorphicName() {
394
+ return "pubid:cencenelec:amendment";
395
+ }
396
+ static FACE = "A";
397
+ }
398
+ export class CenPfsCorrigendum extends CenPfsSupplement {
399
+ /** The kind face "AC" is the run's dispatch token and the notation
400
+ * face. */
401
+ static get polymorphicName() {
402
+ return "pubid:cencenelec:corrigendum";
403
+ }
404
+ static FACE = "AC";
405
+ }
406
+ /** The consolidated (plus-run) bundle: the base document is the first
407
+ * member; the supplements carry no base. */
408
+ export class CenPfsConsolidatedIdentifier extends CenPfsIdentifier {
409
+ static get polymorphicName() {
410
+ return "pubid:cencenelec:consolidated-identifier";
411
+ }
412
+ static get attributes() {
413
+ return extendAttributes(BaseIdentifier, {
414
+ identifiers: {
415
+ type: CenPfsIdentifier,
416
+ collection: true,
417
+ },
418
+ });
419
+ }
420
+ static get mappings() {
421
+ return keyValue({ wire: "identifiers", to: "identifiers" });
422
+ }
423
+ static urnGenerator = CenPfsUrnGenerator;
424
+ }
425
+ /** The fragment wrapper: a fragment of the amendment it wraps; the
426
+ * fragment ordinal is its own `number`. */
427
+ export class CenPfsFragment extends CenPfsIdentifier {
428
+ static get polymorphicName() {
429
+ return "pubid:cencenelec:fragment";
430
+ }
431
+ static get attributes() {
432
+ return extendAttributes(BaseIdentifier, {
433
+ base: { type: CenPfsIdentifier },
434
+ number: { type: "string" },
435
+ });
436
+ }
437
+ static get mappings() {
438
+ return keyValue({ wire: "base", to: "base" }, { wire: "number", to: "number" });
439
+ }
440
+ static urnGenerator = CenPfsUrnGenerator;
441
+ }
442
+ for (const klass of [
443
+ CenPfsEuropeanNorm,
444
+ CenPfsAdoptedEuropeanNorm,
445
+ CenPfsTechnicalReport,
446
+ CenPfsTechnicalSpecification,
447
+ CenPfsGuide,
448
+ CenPfsCenReport,
449
+ CenPfsCenWorkshopAgreement,
450
+ CenPfsEuropeanSpecification,
451
+ CenPfsEuropeanPrestandard,
452
+ CenPfsHarmonizationDocument,
453
+ CenPfsAmendment,
454
+ CenPfsCorrigendum,
455
+ CenPfsConsolidatedIdentifier,
456
+ CenPfsFragment,
457
+ ]) {
458
+ CenPfsIdentifier.localTypeMap.set(klass.polymorphicName, klass);
459
+ }
460
+ // --- the builder (the generated builder's shape) -------------------------------
461
+ function copublishersOf(flat) {
462
+ const rows = flat["copublishers"];
463
+ if (!Array.isArray(rows))
464
+ return [];
465
+ return rows
466
+ .map((row) => strOf(unwrap(isRecord(row) ? row["copublisher"] : row)))
467
+ .filter((c) => c !== undefined && c !== "");
468
+ }
469
+ /** The class each reference selects: the type-position token first,
470
+ * then the publisher-position token (the publisher-type faces
471
+ * CR/CWA/…), then the token-free default class. */
472
+ function locateIdentifierKlass(flat) {
473
+ const token = presentString(unwrap(flat["guide"])) ?? presentString(unwrap(flat["type"]));
474
+ const publisher = strOf(unwrap(flat["publisher"]));
475
+ const selected = token ?? (publisher !== undefined && publisher in TYPE_TOKENS ? publisher : undefined);
476
+ return selected !== undefined
477
+ ? (TYPE_TOKENS[selected] ?? CenPfsEuropeanNorm)
478
+ : CenPfsEuropeanNorm;
479
+ }
480
+ /** The columns, as the coded builder's cast writes them. */
481
+ function assignAttributes(flat) {
482
+ const attrs = {};
483
+ const year = strOf(unwrap(flat["year"]));
484
+ if (year !== undefined)
485
+ attrs["date"] = new PubidDate({ year });
486
+ const number = strOf(unwrap(flat["number"]));
487
+ if (number !== undefined)
488
+ attrs["number"] = number;
489
+ const part = strOf(unwrap(flat["part"]));
490
+ if (part !== undefined)
491
+ attrs["part"] = part;
492
+ const version = presentString(unwrap(flat["version"]));
493
+ if (version !== undefined)
494
+ attrs["version"] = version;
495
+ const publisher = strOf(unwrap(flat["publisher"]));
496
+ if (publisher !== undefined)
497
+ attrs["publisher"] = publisher;
498
+ const copubs = copublishersOf(flat);
499
+ if (copubs.length > 0)
500
+ attrs["copublishers"] = copubs;
501
+ const typeToken = presentString(unwrap(flat["guide"])) ?? presentString(unwrap(flat["type"]));
502
+ if (typeToken !== undefined)
503
+ attrs["type"] = typeToken;
504
+ const stageCode = STAGE_MAP[strOf(unwrap(flat["stage"])) ?? ""];
505
+ if (stageCode !== undefined)
506
+ attrs["typedStage"] = locateStageByCode(stageCode);
507
+ return attrs;
508
+ }
509
+ /** The adopted-base dispatch (the §4 coded escape hatch): the adopted
510
+ * string parses with the owning scheme's implementation ("ISO" leads
511
+ * through iso — its ISO/IEC copublisher spelling included, "IEC"
512
+ * through iec); an ENV-prefixed adoption switches the class to the
513
+ * prestandard, the publisher staying ENV. */
514
+ function parseAdopted(adoptedStr) {
515
+ if (adoptedStr.startsWith("IEC")) {
516
+ const impl = grammarImplementation("iec");
517
+ if (impl === undefined)
518
+ throw new Error("iec implementation unavailable");
519
+ return impl.parse(adoptedStr);
520
+ }
521
+ if (adoptedStr.startsWith("ISO")) {
522
+ const impl = grammarImplementation("iso");
523
+ if (impl === undefined)
524
+ throw new Error("iso implementation unavailable");
525
+ return impl.parse(adoptedStr);
526
+ }
527
+ return undefined;
528
+ }
529
+ function adoptedBuild(flat) {
530
+ const adoptedStr = strOf(unwrap(flat["adopted"]))?.trim();
531
+ if (adoptedStr === undefined || adoptedStr === "")
532
+ return undefined;
533
+ const adoptedId = parseAdopted(adoptedStr);
534
+ const publisher = strOf(unwrap(flat["publisher"]));
535
+ if (publisher === "ENV") {
536
+ return new CenPfsEuropeanPrestandard({ publisher: "ENV", adopted: adoptedId });
537
+ }
538
+ const attrs = { adopted: adoptedId };
539
+ const stageCode = STAGE_MAP[strOf(unwrap(flat["stage"])) ?? ""];
540
+ if (stageCode !== undefined)
541
+ attrs["typedStage"] = locateStageByCode(stageCode);
542
+ if (publisher !== undefined)
543
+ attrs["publisher"] = publisher;
544
+ const copubs = copublishersOf(flat);
545
+ if (copubs.length > 0)
546
+ attrs["copublishers"] = copubs;
547
+ return new CenPfsAdoptedEuropeanNorm(attrs);
548
+ }
549
+ /** The implicit adoption probe: an EN with a bare number in the IEC
550
+ * range (60000-79999), no copublishers, no part and no supplements,
551
+ * adopts the corresponding IEC standard — the ISO-only range is
552
+ * intentionally NOT mapped (pubid#249). */
553
+ function implicitAdoption(flat) {
554
+ if (strOf(unwrap(flat["publisher"])) !== "EN")
555
+ return undefined;
556
+ if (copublishersOf(flat).length > 0)
557
+ return undefined;
558
+ if (present(flat["part"]))
559
+ return undefined;
560
+ const supplements = flat["supplements"];
561
+ if (Array.isArray(supplements) && supplements.length > 0)
562
+ return undefined;
563
+ const number = strOf(unwrap(flat["number"]))?.trim();
564
+ if (number === undefined || !/^\d{1,6}$/.test(number))
565
+ return undefined;
566
+ const num = Number.parseInt(number, 10);
567
+ if (!(num >= 60000 && num <= 79999))
568
+ return undefined;
569
+ const impl = grammarImplementation("iec");
570
+ if (impl === undefined)
571
+ return undefined;
572
+ return new CenPfsAdoptedEuropeanNorm({
573
+ adopted: impl.parse(`IEC ${number}`),
574
+ });
575
+ }
576
+ function buildBaseDocument(flat) {
577
+ if (present(flat["adopted"])) {
578
+ const built = adoptedBuild(flat);
579
+ if (built !== undefined)
580
+ return built;
581
+ }
582
+ const implicit = implicitAdoption(flat);
583
+ if (implicit !== undefined)
584
+ return implicit;
585
+ return new (locateIdentifierKlass(flat))(assignAttributes(flat));
586
+ }
587
+ /** The run's internal captures bind only through the item row, so the
588
+ * raw supplement item arrives as the capture map itself. */
589
+ function supplementItemOf(row) {
590
+ const inner = isRecord(row) ? row["supplement"] : undefined;
591
+ return isRecord(inner) ? inner : {};
592
+ }
593
+ /** The wrapper classes by kind face: the run's dispatch. */
594
+ function supplementFrom(item, base) {
595
+ const kind = strOf(unwrap(item["supplement_kind"])) ?? "";
596
+ const Wrapper = kind === CenPfsAmendment.FACE
597
+ ? CenPfsAmendment
598
+ : kind === CenPfsCorrigendum.FACE
599
+ ? CenPfsCorrigendum
600
+ : undefined;
601
+ if (Wrapper === undefined) {
602
+ throw new ParseFailed(`CEN: unknown supplement kind ${kind}`, 0);
603
+ }
604
+ const attrs = {};
605
+ if (base !== undefined)
606
+ attrs["base"] = base;
607
+ const number = presentString(unwrap(item["supplement_number"]));
608
+ if (number !== undefined)
609
+ attrs["number"] = number;
610
+ const year = presentString(unwrap(item["supplements_year"]));
611
+ if (year !== undefined)
612
+ attrs["year"] = year;
613
+ const month = presentString(unwrap(item["supplements_month"]));
614
+ if (month !== undefined)
615
+ attrs["month"] = month;
616
+ return new Wrapper(attrs);
617
+ }
618
+ /** The cen wrapper shapes: the slash run folds into the standalone
619
+ * wrapper chain, the plus run into the consolidated bundle. */
620
+ function wrapSupplements(base, flat) {
621
+ const rows = Array.isArray(flat["supplements"])
622
+ ? flat["supplements"]
623
+ : present(flat["supplements"])
624
+ ? [flat["supplements"]]
625
+ : [];
626
+ if (rows.length === 0)
627
+ return base;
628
+ const items = rows.map(supplementItemOf);
629
+ if (items.some((item) => item["supplements_plus"] !== undefined && item["supplements_plus"] !== null)) {
630
+ const members = items.map((item) => supplementFrom(item));
631
+ return new CenPfsConsolidatedIdentifier({
632
+ identifiers: [base, ...members],
633
+ });
634
+ }
635
+ return supplementFrom(items[0], base);
636
+ }
637
+ function wrapFragment(identifier, flat) {
638
+ const fragNumber = strOf(unwrap(flat["fragment_number"]));
639
+ if (fragNumber === undefined || fragNumber === "")
640
+ return identifier;
641
+ return new CenPfsFragment({ number: fragNumber, base: identifier });
642
+ }
643
+ export function buildCenPfsIdentifier(flat) {
644
+ return wrapFragment(wrapSupplements(buildBaseDocument(flat), flat), flat);
645
+ }
646
+ /**
647
+ * The artifact's declared bindings carry the parsed faces: the flat
648
+ * columns land on the model fields, the stage capture folds onto the
649
+ * typed stage (the definition's stage map), the supplement run folds
650
+ * into the synthesized wrapper chain (standalone) or the consolidated
651
+ * bundle (plus), and the adopted run dispatches through the hook — the
652
+ * same fold the Ruby builder performs.
653
+ */
654
+ let cachedRuntime;
655
+ export function cenPfsGrammarImplementation() {
656
+ return {
657
+ parse(input) {
658
+ cachedRuntime ??= PubidRuntime.load("cen_pfs");
659
+ const bound = cachedRuntime.parseAndBind(input);
660
+ if (bound === null || typeof bound !== "object") {
661
+ throw new ParseFailed("cen_pfs: the artifact rejected the input", 0);
662
+ }
663
+ return buildCenPfsIdentifier(bound);
664
+ },
665
+ };
666
+ }