@pubid/pubid 0.1.68 → 0.1.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -165,15 +165,89 @@ With the manifest loaded, `PubidUrn.fromSlug` covers all 41 flavors
165
165
  that resolve identifier types (nist, ieee and oiml included — the three
166
166
  the barrel could not reach from a worker). `grammarImplementation`
167
167
  (open-ended parse routing) deliberately stays behind the node-only
168
- barrel: it cannot load in a worker today. The invariants are pinned by
168
+ barrel: the barrel as a whole still carries the node-only parg runtime
169
+ for the ten other artifact-backed flavors. The invariants are pinned by
169
170
  `test/register-types.test.ts`: the manifest registers exactly the
170
171
  barrel's type set, and no node-only module is reachable from the worker
171
172
  entry's import graph.
172
173
 
174
+ ## Worker-safe parse: nist / ieee / oiml (pubid-ts#232)
175
+
176
+ The three flavors the barrel could not serve in a worker now ship
177
+ dedicated worker entries with no `node:*` module in their import graph:
178
+
179
+ - **nist / ieee** run the baked PARG artifact over parsanol's wasm
180
+ engine. Their implementations are environment-agnostic; the node
181
+ entries (`dist/flavors/<flavor>/index.js`) keep the lazy `node:fs`
182
+ artifact load they always had (zero regression), while the worker
183
+ entries build the same implementations over `parsanol/browser` and
184
+ the artifact bundled at build time (`dist/parg/artifacts/` — the same
185
+ checksummed payloads `vendor/parg/` ships, re-emitted by
186
+ `npm run artifact` so the two cannot drift). The ~2.7 MB wasm loads
187
+ lazily on the first entry call, once per isolate; the parse calls
188
+ themselves stay synchronous.
189
+ - **oiml** never needed the artifact — its grammar is the pure-TS
190
+ parslet port. It lacked a flavor index; it now has one
191
+ (`dist/flavors/oiml/index.js`, the node barrel surface), and the
192
+ worker entry routes its co-published ISO side to the parg-free iso
193
+ implementation. No wasm at all.
194
+
195
+ A Cloudflare Worker consumes them like this (`relaton-api-js`'s
196
+ `engine.ts`; `NO_WORKER_ENGINE = {nist, ieee, oiml}` dissolves). The
197
+ wasm argument is whatever `parsanol/browser`'s `initialize()` takes —
198
+ URL (the lazy path: a one-time R2/CDN fetch on the first parse), a
199
+ CompiledWasm module (bundled), or raw bytes:
200
+
201
+ ```ts
202
+ // Lazy (the ~2.7 MB wasm fetches once, on the first nist/ieee entry call):
203
+ const WASM_URL = "https://assets.example.com/parsanol/parsanol_bg.wasm";
204
+
205
+ import { nistWorkerGrammarImplementation } from "@pubid/pubid/dist/flavors/nist/worker.js";
206
+ import { ieeeWorkerGrammarImplementation } from "@pubid/pubid/dist/flavors/ieee/worker.js";
207
+ import { oimlWorkerGrammarImplementation } from "@pubid/pubid/dist/flavors/oiml/worker.js";
208
+
209
+ const nist = await nistWorkerGrammarImplementation(WASM_URL);
210
+ const ieee = await ieeeWorkerGrammarImplementation({ wasm: WASM_URL });
211
+ const oiml = oimlWorkerGrammarImplementation(); // sync — no wasm at all
212
+
213
+ nist.parse("NIST SP 800-53r5");
214
+ ieee.parse("IEEE Std 802.3-2022");
215
+ oiml.parse("OIML R 49-1:2024"); // and "ISO 4064-1:2024|OIML R 49-1:2024"
216
+ ```
217
+
218
+ Bundled instead of fetched: vendor the wasm (its `exports` map does not
219
+ expose the vendored file as a subpath, so copy
220
+ `node_modules/parsanol/vendor/parsanol-web/parsanol_bg.wasm` into your
221
+ repo) and declare wrangler's CompiledWasm rule:
222
+
223
+ ```toml
224
+ # wrangler.toml — workerd compiles it at bundle load, no dynamic codegen:
225
+ rules = [{ type = "CompiledWasm", globs = ["**/parsanol_bg.wasm"], fallthrough = true }]
226
+ ```
227
+
228
+ ```ts
229
+ import parsanolWasm from "../vendor/parsanol_bg.wasm"; // WebAssembly.Module
230
+ const nist = await nistWorkerGrammarImplementation(parsanolWasm);
231
+ ```
232
+
233
+ The ieee worker entry routes its co-published iec side
234
+ through the parg-free iec implementation; the ansi side has no worker
235
+ implementation yet and rejects with the same "ANSI implementation
236
+ unavailable" the node router produces for an unknown flavor — inject
237
+ your own via `ieeeWorkerGrammarImplementation({ coPublished })`.
238
+
239
+ The receipts are pinned in CI: `npm run test:worker` runs
240
+ `test/worker/worker-parse.test.ts` inside workerd with NO
241
+ `nodejs_compat` (vitest-pool-workers), and `worker-graph.test.ts`
242
+ walks the compiled import graphs (no `node:*` module, nothing beyond
243
+ `parsanol/browser`) and bundles every entry with
244
+ `esbuild --platform=neutral` and no node externals.
245
+
173
246
  ## Development
174
247
 
175
248
  ```sh
176
249
  npm ci
177
250
  npm test # builds + runs the corpus harness tests
251
+ npm run test:worker # the worker gate: parse inside workerd, no nodejs_compat
178
252
  npm run conformance # prints the quadrant report for the pinned corpus
179
253
  ```
@@ -50,6 +50,52 @@ export declare abstract class IecIdentifier extends BaseIdentifier {
50
50
  numberPortion(): string;
51
51
  stageIterationValue(): string | undefined;
52
52
  languagePortion(): string;
53
+ /** The supplement/wrapper suffix hook (ruby Identifier#mr_supplement_suffix):
54
+ * `{type}.{number}.{year}` for supplements, nil for every other class. The
55
+ * base returns nil; the IEC supplement class carries the override. */
56
+ mrSupplementSuffix(): string | undefined;
57
+ /** The machine-readable slug (ruby Identifier#to_mr_string): the flat MR
58
+ * segments joined with ".". Wrapper classes override to compose their
59
+ * chain (Consolidated/Vap/Supplement); every other class takes this path,
60
+ * which is byte-identical with what the shared renderer produces for it.
61
+ * The all-parts form has no MR (ruby Pubid::AllParts#render raises
62
+ * NotImplementedError — the all-parts TS boolean is that wrapper). */
63
+ toMrString(): string;
64
+ /** Ruby Identifier#mr_publisher: the publisher, lowercased, "/" dash-joined
65
+ * ("iso-iec"). The copublishers are a separate attribute and contribute no
66
+ * segment (the shared hook reads the publisher only). */
67
+ protected mrPublisher(): string | undefined;
68
+ /** Ruby Identifier#mr_type: the typed stage's type code, lowercased; nil for
69
+ * the international standard (the default face carries no type token). */
70
+ protected mrType(): string | undefined;
71
+ /** Ruby Identifier#mr_number_with_part: number-part-subpart, dash-joined,
72
+ * lowercased; nil without a number (a hook returning "" would gain a blank
73
+ * segment and a double dot in the slug). */
74
+ protected mrNumberWithPart(): string | undefined;
75
+ /** Ruby Identifier#mr_year: the year, month/day dash-extended; "--" when the
76
+ * date is undated; nil without a date. */
77
+ protected mrYear(): string | undefined;
78
+ /** Ruby Identifier#mr_edition: "ed{number}" — the IEC edition is the
79
+ * Components::Edition component, and the hook reads its number. */
80
+ protected mrEdition(): string | undefined;
81
+ /** Ruby Identifier#mr_languages: the language codes, hyphen-joined, no
82
+ * parens (parens are shell-/URL-unsafe). */
83
+ protected mrLanguages(): string | undefined;
84
+ /** The standard this identifier supplements, dropping its own supplement
85
+ * layer (one level). The base supplements nothing, so it is returned
86
+ * unchanged; the consolidated chain overrides to yield its leading member. */
87
+ dropSupplements(): IecIdentifier;
88
+ /** Excluded attributes are dropped; every other value passes through
89
+ * excludeFromNested so the exclusion also propagates into nested
90
+ * identifiers (wrapper types store their identity on an inner member).
91
+ * :amendment / :supplement are structural, not attributes — they reduce a
92
+ * supplemented identifier to the standard it wraps (#dropSupplements). */
93
+ exclude(...args: string[]): IecIdentifier;
94
+ /** Fuzz-level equality: two identifiers match when they are equal after
95
+ * excluding the given aspects. `ignore` accepts the same symbols as
96
+ * #exclude (e.g. "date", "edition", "amendment"). The primitive relaton
97
+ * uses to match a reference against catalogue hits at varying strictness. */
98
+ matches(other: IecIdentifier, ignore?: string[]): boolean;
53
99
  }
54
100
  export declare const IEC_CLASSES: {
55
101
  readonly KIND_CLASSES: Partial<Record<IecTypeCode, IdentifierStatic>>;
@@ -319,6 +319,142 @@ export class IecIdentifier extends BaseIdentifier {
319
319
  return "";
320
320
  return `(${this.languages.map((l) => l.code).join(",")})`;
321
321
  }
322
+ // --- MR string (ruby to_mr_string, Renderers::MrString) ---------------------
323
+ /** The supplement/wrapper suffix hook (ruby Identifier#mr_supplement_suffix):
324
+ * `{type}.{number}.{year}` for supplements, nil for every other class. The
325
+ * base returns nil; the IEC supplement class carries the override. */
326
+ mrSupplementSuffix() {
327
+ return undefined;
328
+ }
329
+ /** The machine-readable slug (ruby Identifier#to_mr_string): the flat MR
330
+ * segments joined with ".". Wrapper classes override to compose their
331
+ * chain (Consolidated/Vap/Supplement); every other class takes this path,
332
+ * which is byte-identical with what the shared renderer produces for it.
333
+ * The all-parts form has no MR (ruby Pubid::AllParts#render raises
334
+ * NotImplementedError — the all-parts TS boolean is that wrapper). */
335
+ toMrString() {
336
+ if (this.all_parts === true) {
337
+ throw new Error("an all-parts identifier has no mr_string form yet");
338
+ }
339
+ return [
340
+ this.mrPublisher(),
341
+ this.mrType(),
342
+ this.mrNumberWithPart(),
343
+ this.mrYear(),
344
+ this.mrEdition(),
345
+ this.mrLanguages(),
346
+ ]
347
+ .filter((segment) => segment !== undefined)
348
+ .join(".");
349
+ }
350
+ /** Ruby Identifier#mr_publisher: the publisher, lowercased, "/" dash-joined
351
+ * ("iso-iec"). The copublishers are a separate attribute and contribute no
352
+ * segment (the shared hook reads the publisher only). */
353
+ mrPublisher() {
354
+ return this.publisher?.toLowerCase().replaceAll("/", "-");
355
+ }
356
+ /** Ruby Identifier#mr_type: the typed stage's type code, lowercased; nil for
357
+ * the international standard (the default face carries no type token). */
358
+ mrType() {
359
+ const code = this.typedStage?.typeCode;
360
+ return code === undefined || code === "is" ? undefined : code.toLowerCase();
361
+ }
362
+ /** Ruby Identifier#mr_number_with_part: number-part-subpart, dash-joined,
363
+ * lowercased; nil without a number (a hook returning "" would gain a blank
364
+ * segment and a double dot in the slug). */
365
+ mrNumberWithPart() {
366
+ if (this.number === undefined)
367
+ return undefined;
368
+ return [this.number, this.part, this.subpart]
369
+ .filter((v) => v !== undefined)
370
+ .join("-")
371
+ .toLowerCase();
372
+ }
373
+ /** Ruby Identifier#mr_year: the year, month/day dash-extended; "--" when the
374
+ * date is undated; nil without a date. */
375
+ mrYear() {
376
+ const date = this.date;
377
+ if (date === undefined)
378
+ return undefined;
379
+ if (date.undated)
380
+ return "--";
381
+ if (date.year === undefined || date.year === "")
382
+ return undefined;
383
+ let result = String(date.year);
384
+ if (date.month !== undefined && date.month !== "")
385
+ result += `-${date.month}`;
386
+ if (date.day !== undefined && date.day !== "")
387
+ result += `-${date.day}`;
388
+ return result;
389
+ }
390
+ /** Ruby Identifier#mr_edition: "ed{number}" — the IEC edition is the
391
+ * Components::Edition component, and the hook reads its number. */
392
+ mrEdition() {
393
+ return this.edition === undefined ? undefined : `ed${this.edition}`;
394
+ }
395
+ /** Ruby Identifier#mr_languages: the language codes, hyphen-joined, no
396
+ * parens (parens are shell-/URL-unsafe). */
397
+ mrLanguages() {
398
+ if (this.languages.length === 0)
399
+ return undefined;
400
+ return this.languages.map((l) => l.code.toLowerCase()).join("-");
401
+ }
402
+ // --- the supplement-peeling algebra (ruby Identifier#drop_supplements /
403
+ // #exclude / #matches?, the relaton-api-js citation-validation primitive)
404
+ /** The standard this identifier supplements, dropping its own supplement
405
+ * layer (one level). The base supplements nothing, so it is returned
406
+ * unchanged; the consolidated chain overrides to yield its leading member. */
407
+ dropSupplements() {
408
+ return this;
409
+ }
410
+ /** Excluded attributes are dropped; every other value passes through
411
+ * excludeFromNested so the exclusion also propagates into nested
412
+ * identifiers (wrapper types store their identity on an inner member).
413
+ * :amendment / :supplement are structural, not attributes — they reduce a
414
+ * supplemented identifier to the standard it wraps (#dropSupplements). */
415
+ exclude(...args) {
416
+ const supplementKeys = args.filter((a) => a === "amendment" || a === "supplement");
417
+ if (supplementKeys.length > 0) {
418
+ return this.dropSupplements().exclude(...args.filter((a) => !supplementKeys.includes(a)));
419
+ }
420
+ const excluded = new Set(args);
421
+ // Map :year to :date (year-in-date flavors), but ALSO keep :year so a
422
+ // flavor that models the edition as a plain `year` attribute has it
423
+ // excluded too (ruby's own comment).
424
+ if (excluded.has("year"))
425
+ excluded.add("date");
426
+ const attrs = {};
427
+ for (const [name] of Object.entries(this.constructor.attributes)) {
428
+ const value = excluded.has(name)
429
+ ? undefined
430
+ : this[name];
431
+ attrs[name] = excludeFromNested(value, args);
432
+ }
433
+ const rebuilt = new this.constructor(attrs);
434
+ // The runtime typed stage is not an attribute (ruby's rebuild carries it
435
+ // as one), so it rides the copy explicitly.
436
+ rebuilt.typedStage = this.typedStage;
437
+ return rebuilt;
438
+ }
439
+ /** Fuzz-level equality: two identifiers match when they are equal after
440
+ * excluding the given aspects. `ignore` accepts the same symbols as
441
+ * #exclude (e.g. "date", "edition", "amendment"). The primitive relaton
442
+ * uses to match a reference against catalogue hits at varying strictness. */
443
+ matches(other, ignore = []) {
444
+ return this.exclude(...ignore).equals(other.exclude(...ignore));
445
+ }
446
+ }
447
+ /** Propagate an #exclude into a nested attribute value: recurse when it is
448
+ * (or contains) another identifier, otherwise return it unchanged. Passes
449
+ * the original args so nested identifiers re-apply the same :year->:date
450
+ * mapping themselves (ruby Identifier#exclude_from_nested). */
451
+ function excludeFromNested(value, args) {
452
+ if (value instanceof BaseIdentifier) {
453
+ return value.exclude(...args);
454
+ }
455
+ if (Array.isArray(value))
456
+ return value.map((item) => excludeFromNested(item, args));
457
+ return value;
322
458
  }
323
459
  function iecSingleClass(kind) {
324
460
  const name = TYPE_NAMES[kind];
@@ -576,6 +712,41 @@ function iecSupplementClass(kind) {
576
712
  return "";
577
713
  return " ";
578
714
  }
715
+ /** Ruby IEC SupplementIdentifier#mr_supplement_suffix:
716
+ * `/{type}.{number}.{year}` (e.g. "/amd.1.2016") — the segments the
717
+ * MrString renderer and the consolidated composition append so the
718
+ * full supplement chain round-trips losslessly (gem issue #142). */
719
+ mrSupplementSuffix() {
720
+ const segments = [];
721
+ const type = this.mrType();
722
+ if (type !== undefined)
723
+ segments.push(type);
724
+ if (this.number !== undefined)
725
+ segments.push(String(this.number));
726
+ const year = this.date?.year;
727
+ if (year !== undefined && year !== "")
728
+ segments.push(String(year));
729
+ return segments.length === 0 ? undefined : segments.join(".");
730
+ }
731
+ /** Ruby IEC SupplementIdentifier#to_mr_string: the chain head routes
732
+ * through the BASE's own #toMrString, not a flat renderer recursion —
733
+ * the flat path renders the wrapped document without a wrapper class's
734
+ * own composition, so a corrigendum over a consolidated version
735
+ * ("IEC 60335-1:2010+AMD1:2013 CSV/COR1:2014") dropped the part and the
736
+ * whole chain behind its suffix. For every class without a #toMrString
737
+ * override the base's own path produces the string the renderer would,
738
+ * so the standalone supplement chains are unchanged; where a wrapper
739
+ * carries one (the Vap) the full chain survives. */
740
+ toMrString() {
741
+ const suffix = this.mrSupplementSuffix();
742
+ if (suffix === undefined)
743
+ return super.toMrString();
744
+ const base = this.base;
745
+ if (base === undefined)
746
+ return suffix;
747
+ const head = base.toMrString();
748
+ return head === "" ? suffix : `${head}_${suffix}`;
749
+ }
579
750
  static fromHash(hash) {
580
751
  // The supplement restores its type's published stage when no stage
581
752
  // code rode the hash (ruby restores Amendment -> Amd — the glued
@@ -624,6 +795,25 @@ function iecVapClass() {
624
795
  result += ` ED${this.edition}`;
625
796
  return result;
626
797
  }
798
+ /** Ruby VapIdentifier#to_mr_string: the wrapped chain's MR with the VAP
799
+ * code (or codes — the multi-deliverable face prints `EXV-CMV`) appended
800
+ * as the final segment. Without it the VAP renders the generic flat slug
801
+ * through its delegated number, which drops the part and shares one slug
802
+ * with the bare base document ("IEC 60601-1:2005+AMD1:2012 CSV" keyed
803
+ * "iec.60601.2005", the same slug as the part 2 chain and — for a
804
+ * part-less base — the base itself; the #142 collision one layer down).
805
+ * The corrigendum-over-VAP face composes on top of this through the
806
+ * supplement's base-routed head. */
807
+ toMrString() {
808
+ const head = this.base?.toMrString();
809
+ if (head === undefined || head === "")
810
+ return "";
811
+ const codes = this.vap
812
+ .map((code) => code.toLowerCase().trim())
813
+ .filter((code) => code !== "")
814
+ .join("-");
815
+ return codes === "" ? head : `${head}_${codes}`;
816
+ }
627
817
  }
628
818
  registerType(IecVapIdentifier);
629
819
  return IecVapIdentifier;
@@ -635,6 +825,40 @@ function iecConsolidatedClass() {
635
825
  identifiers: { type: IecIdentifier, collection: true, initializeEmpty: true },
636
826
  });
637
827
  static mappings = keyValue({ wire: "identifiers", to: "identifiers" });
828
+ /** Dropping the supplement layer yields the leading member — the base
829
+ * standard alone (the CEN counterpart's shape). This is what makes the
830
+ * structural exclusions reach a consolidated chain: exclude("amendment")
831
+ * / exclude("supplement") and their matches(ignore) forms peel the
832
+ * composition to the document it supplements, so a consolidated
833
+ * reference matches the bare base record (the primitive
834
+ * relaton-api-js's citation-validation uses to resolve a consolidated
835
+ * docid onto the edition it amends). */
836
+ dropSupplements() {
837
+ return this.identifiers[0] ?? this;
838
+ }
839
+ /** Ruby ConsolidatedIdentifier#to_mr_string: the base member's own MR
840
+ * (its part/subpart ride on the member, so the slug keeps the full
841
+ * designation), then each supplement member behind a `plus-` marker —
842
+ * the CEN counterpart's composition. Without it the chain rendered the
843
+ * generic flat slug, which both dropped the part and shared one slug
844
+ * with the bare base document ("IEC 60601-1:2005+AMD1:2012 CSV" keyed
845
+ * "iec.60601.2005", colliding with the part-less rendering of the
846
+ * part 2 chain and with the base itself). The `plus-` marker keeps the
847
+ * consolidated slug distinct from the standalone supplement chain's
848
+ * ("iec.60601-1.2005_amd.1.2012"), mirroring the CEN ruling that a
849
+ * consolidated form must not share a slug with the document it composes. */
850
+ toMrString() {
851
+ const [base, ...supplements] = this.identifiers;
852
+ if (base === undefined)
853
+ return "";
854
+ const parts = [base.toMrString()];
855
+ for (const member of supplements) {
856
+ const suffix = member.mrSupplementSuffix();
857
+ if (suffix !== undefined)
858
+ parts.push(`plus-${suffix}`);
859
+ }
860
+ return parts.join("_");
861
+ }
638
862
  render() {
639
863
  return this.identifiers
640
864
  .map((id, idx) => {
@@ -1,4 +1,4 @@
1
- import { normalizeShape } from "../../parg/runtime.js";
1
+ import { normalizeShape } from "../../parg/shape.js";
2
2
  /**
3
3
  * The baked PARG artifact's parse shape → the builder tree. The
4
4
  * artifact (the gem's own runtime grammar) differs from the hand
@@ -0,0 +1,16 @@
1
+ import type { Tree } from "../../grammar/engine.js";
2
+ import type { FlavorImplementation, Identifier } from "../../conformance/implementation.js";
3
+ export interface IeeeParseDeps {
4
+ /** The artifact engine's bound-parse (the parseAndBind contract). */
5
+ parseAndBind(input: string): unknown;
6
+ /** The co-published side resolver ("iec", "ansi"); undefined when
7
+ * the flavor is unavailable in the current environment. */
8
+ coPublished(flavor: string): FlavorImplementation | undefined;
9
+ }
10
+ export interface IeeeParseEngine {
11
+ parseSource(input: string): Tree;
12
+ coPublished(flavor: string): FlavorImplementation | undefined;
13
+ }
14
+ export declare function makeIeeeParseEngine(deps: IeeeParseDeps): IeeeParseEngine;
15
+ export declare function ieeeParseImpl(env: IeeeParseEngine, input: string): Identifier;
16
+ export declare function makeIeeeGrammarImplementation(env: IeeeParseEngine): FlavorImplementation;