@mermanjs/node-wasm 0.11.0 → 0.12.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.
package/dist/engine.mjs CHANGED
@@ -1,20 +1,29 @@
1
1
  import { BoundedExecutor } from "./bounded-executor.mjs";
2
- import { supportsDirectNativeSvg } from "./native-loader.mjs";
2
+ import {
3
+ getInstalledWasmSvgResponseSync,
4
+ supportsDirectNativeSvg,
5
+ takeVersionCheckedRuntimeCatalog,
6
+ } from "./native-loader.mjs";
7
+ import { nodeWireContract } from "./transport-contract.mjs";
3
8
  import {
4
9
  MermanInvalidTransportError,
5
10
  NODE_TRANSPORT_FIELD_LIMITS,
6
11
  NODE_TRANSPORT_LIMITS,
7
12
  NODE_WIRE_CONTRACT,
8
13
  abortError,
14
+ addJsonEnvelopeBytes,
15
+ addJsonEnvelopeStringBytes,
9
16
  assertUtf8Field,
10
17
  decodeWireInvocationError,
11
18
  decodeWireResponse,
12
19
  encodeTransportJson,
13
20
  jsonStringFieldBytes,
21
+ normalizeOperationSignal,
14
22
  parseRuntimeCatalogJsonText,
15
23
  parseTransportJsonText,
16
24
  sameJsonValue,
17
25
  snapshotTransportJsonValue,
26
+ validateOperationOptionsJson,
18
27
  } from "./errors.mjs";
19
28
  import {
20
29
  BINDING_OPTION_GROUP_SPECS,
@@ -24,6 +33,7 @@ import {
24
33
  BINDING_TRANSPORT_EXPOSURE_SPECS,
25
34
  CAPABILITY_SPECS,
26
35
  CONSTRUCTOR_SERVICE_SPECS,
36
+ ICON_REGISTRY_CONSTRUCTOR_SERVICE_ID,
27
37
  METADATA_SPECS,
28
38
  RUNTIME_CATALOG_FIELD_IDENTIFIER_PATTERN,
29
39
  RUNTIME_CATALOG_IDENTIFIER_PATTERN,
@@ -90,20 +100,37 @@ const COMPILED_PREREQUISITES_BY_OPERATION_ID = new Map(
90
100
  const KNOWN_OUTPUT_CONTRACT_BY_ID = new Map(
91
101
  NODE_WIRE_CONTRACT.artifact.output_contracts.map((contract) => [contract.id, contract]),
92
102
  );
93
- const THEME_AUTHORING_INPUT_LIMITS = Object.freeze({
103
+ const THEME_REQUEST_LIMITS = Object.freeze({
94
104
  ...NODE_TRANSPORT_LIMITS.metadata,
95
105
  max_utf8_bytes: NODE_TRANSPORT_FIELD_LIMITS.source_utf8_bytes,
96
106
  max_string_utf8_bytes: NODE_TRANSPORT_FIELD_LIMITS.source_utf8_bytes,
97
107
  });
98
- const THEME_AUTHORING_RESULT_LIMITS = Object.freeze({
108
+ const THEME_RESULT_LIMITS = Object.freeze({
99
109
  ...NODE_TRANSPORT_LIMITS.metadata,
100
110
  max_utf8_bytes: NODE_TRANSPORT_FIELD_LIMITS.data_utf8_bytes,
101
111
  max_string_utf8_bytes: NODE_TRANSPORT_FIELD_LIMITS.data_utf8_bytes,
102
112
  });
103
113
  const MAX_OPERATION_TIMEOUT_MS = 0xffff_ffff;
114
+ const OPERATION_REQUEST_FIELDS = new Set(["operationId", "source", "uri", "options", "optionsJson"]);
104
115
  const SVG_REQUEST_FRAME_BYTES = '{"operation_id":"svg","source":"","uri":null,"include_metadata":false}'.length;
116
+ const DRAW_LIST_REQUEST_FRAME_BYTES = '{"operation_id":"draw-list-json","source":"","uri":null,"include_metadata":false}'.length;
105
117
  const SVG_OPTIONS_FRAME_BYTES = ',"options_json":""'.length;
106
118
  const SVG_TIMEOUT_FRAME_BYTES = ',"operation_control":{"timeout_ms":}'.length;
119
+ const SVG_ID_OPTIONS_BYTES = '{"svg":{"diagram_id":""}}'.length;
120
+ const ICON_PACK_ENTRY_JSON_FRAME_BYTES = '{"json":}'.length;
121
+ const ICON_PACK_REGISTRATION_NAME_KEY_BYTES = ',"registrationName":'.length;
122
+ const ICON_PACK_ENVELOPE_MIN_ENTRY_BYTES = '{"json":""}'.length;
123
+ const ICON_PACK_ENVELOPE_ARRAY_FRAME_BYTES = "[]".length;
124
+ const ICON_PACK_ENVELOPE_OVERHEAD_PER_PACK = '{"json":"","registrationName":""},'.length;
125
+ export const ICON_PACK_MAX_ENVELOPE_PACKS = 1024;
126
+ export const ICON_PACK_MAX_ENVELOPE_BYTES = deriveIconPackMaxEnvelopeBytes();
127
+ // Reserve the largest direct frame, timeout, and six escaped bytes per admitted options byte.
128
+ const DIRECT_SVG_SOURCE_UNIT_BOUND = Math.floor(Math.min(
129
+ NODE_TRANSPORT_FIELD_LIMITS.source_utf8_bytes / 3,
130
+ (NODE_TRANSPORT_LIMITS.request.max_utf8_bytes -
131
+ directOperationFrameBytes(Math.max(SVG_REQUEST_FRAME_BYTES, DRAW_LIST_REQUEST_FRAME_BYTES), 0, MAX_OPERATION_TIMEOUT_MS) -
132
+ SVG_OPTIONS_FRAME_BYTES - 6 * NODE_TRANSPORT_FIELD_LIMITS.options_json_utf8_bytes) / 6,
133
+ ));
107
134
  const MERMAN_ENGINE_CONSTRUCTION_TOKEN = Symbol("MermanEngine construction");
108
135
 
109
136
  export async function createNodeEngine(
@@ -113,7 +140,7 @@ export async function createNodeEngine(
113
140
  concurrency = 1,
114
141
  maxQueue = 64,
115
142
  } = {},
116
- { loadTransport } = {},
143
+ { loadTransport, localLayout = null, candidate = null } = {},
117
144
  ) {
118
145
  if (typeof loadTransport !== "function") {
119
146
  throw new MermanInvalidTransportError("A concrete Node candidate transport loader is required.");
@@ -128,15 +155,18 @@ export async function createNodeEngine(
128
155
  const transport = await loadTransport(optionsJson, iconPacksJson);
129
156
  try {
130
157
  assertTransport(transport);
131
- const runtimeCatalog = validateRuntimeCatalog(await transport.runtimeCatalogJson());
132
- const directSvg = supportsDirectNativeSvg(transport) &&
133
- runtimeCatalog.capabilities.operation_ids.includes("svg");
158
+ const catalogText = await transport.runtimeCatalogJson();
159
+ const catalog = takeVersionCheckedRuntimeCatalog(transport, catalogText) ??
160
+ parseRuntimeCatalogJsonText(catalogText);
161
+ const runtimeCatalog = validateParsedRuntimeCatalog(catalog, { localLayout, candidate });
162
+ const supportsSvg = runtimeCatalog.capabilities.operation_ids.includes("svg");
134
163
  return new MermanEngine(
135
164
  MERMAN_ENGINE_CONSTRUCTION_TOKEN,
136
165
  transport,
137
166
  runtimeCatalog,
138
167
  { concurrency, maxQueue },
139
- directSvg,
168
+ supportsSvg && supportsDirectNativeSvg(transport),
169
+ supportsSvg ? getInstalledWasmSvgResponseSync(transport) : undefined,
140
170
  );
141
171
  } catch (error) {
142
172
  await disposeUnusableTransport(transport);
@@ -144,25 +174,131 @@ export async function createNodeEngine(
144
174
  }
145
175
  }
146
176
 
147
- function encodeIconPacks(packs) {
177
+ function deriveIconPackMaxEnvelopeBytes() {
178
+ const spec = CONSTRUCTOR_SERVICE_SPEC_BY_ID.get(ICON_REGISTRY_CONSTRUCTOR_SERVICE_ID);
179
+ if (spec === undefined) {
180
+ throw new Error("Generated binding contract is missing the icon-registry constructor service.");
181
+ }
182
+ const limitById = new Map(spec.resource_limits.map((limit) => [limit.id, limit.value]));
183
+ const maxPacks = limitById.get("max_icon_registry_packs");
184
+ const maxInputBytes = limitById.get("max_icon_registry_input_bytes");
185
+ const maxPrefixBytes = limitById.get("max_icon_registry_prefix_bytes");
186
+ if (
187
+ !positiveSafeInteger(maxPacks) ||
188
+ !positiveSafeInteger(maxInputBytes) ||
189
+ !positiveSafeInteger(maxPrefixBytes)
190
+ ) {
191
+ throw new Error("Generated binding contract is missing icon-registry envelope resource limits.");
192
+ }
193
+ // Matches `build_icon_registry_from_json` in `crates/merman-bindings-core/src/services.rs`.
194
+ return (
195
+ 6 * (maxInputBytes + maxPacks * maxPrefixBytes) +
196
+ maxPacks * ICON_PACK_ENVELOPE_OVERHEAD_PER_PACK +
197
+ ICON_PACK_ENVELOPE_ARRAY_FRAME_BYTES
198
+ );
199
+ }
200
+
201
+ export function encodeIconPacks(packs, maxEnvelopeBytes = ICON_PACK_MAX_ENVELOPE_BYTES) {
202
+ if (!Number.isSafeInteger(maxEnvelopeBytes) || maxEnvelopeBytes < 0) {
203
+ throw new RangeError("iconPacks maxEnvelopeBytes must be a non-negative safe integer.");
204
+ }
148
205
  if (packs === undefined) return undefined;
149
206
  if (!Array.isArray(packs)) throw new TypeError("iconPacks must be an array.");
150
- const normalized = [];
151
- for (const pack of packs) {
152
- if (!isPlainObject(pack) || typeof pack.json !== "string") {
153
- throw new TypeError("iconPacks entries must contain an already loaded JSON string.");
207
+
208
+ const packCount = packs.length;
209
+ if (!Number.isSafeInteger(packCount) || packCount < 0) {
210
+ throw new TypeError("iconPacks must be an array.");
211
+ }
212
+ if (packCount > ICON_PACK_MAX_ENVELOPE_PACKS) {
213
+ throw new MermanInvalidTransportError(
214
+ `Merman transport iconPacks exceeds the ${ICON_PACK_MAX_ENVELOPE_PACKS}-pack wire limit.`,
215
+ );
216
+ }
217
+ const budget = { label: "iconPacks", max: maxEnvelopeBytes, used: 0 };
218
+ addJsonEnvelopeBytes(budget, ICON_PACK_ENVELOPE_ARRAY_FRAME_BYTES);
219
+ if (packCount > 0) {
220
+ // Reject arrays whose minimum possible encoded envelope already exceeds the wire ceiling
221
+ // before materializing Reflect.ownKeys() on oversized inputs.
222
+ const minContentBytes = packCount * ICON_PACK_ENVELOPE_MIN_ENTRY_BYTES + (packCount - 1);
223
+ if (minContentBytes > budget.max - budget.used) {
224
+ addJsonEnvelopeBytes(budget, minContentBytes);
225
+ }
226
+ }
227
+
228
+ const packKeys = Reflect.ownKeys(packs);
229
+ if (packKeys.some((key) => typeof key === "symbol")) {
230
+ throw new TypeError("iconPacks must not contain symbol keys.");
231
+ }
232
+ if (packKeys.length < packCount + 1) {
233
+ throw new TypeError("iconPacks arrays must not contain holes.");
234
+ }
235
+ if (packKeys.length !== packCount + 1) {
236
+ throw new TypeError("iconPacks arrays must not contain custom properties.");
237
+ }
238
+
239
+ const normalized = Object.setPrototypeOf([], null);
240
+ for (let index = 0; index < packCount; index += 1) {
241
+ const elementDescriptor = Object.getOwnPropertyDescriptor(packs, String(index));
242
+ if (elementDescriptor === undefined) {
243
+ throw new TypeError("iconPacks arrays must not contain holes.");
244
+ }
245
+ if (!elementDescriptor.enumerable || !("value" in elementDescriptor)) {
246
+ throw new TypeError(`iconPacks[${index}] must be an enumerable data property.`);
247
+ }
248
+ const pack = elementDescriptor.value;
249
+ const jsonCopyHint = "Pass a plain copy such as `{ json: pack.json }`.";
250
+ if (!isPlainObject(pack)) {
251
+ throw new TypeError(`iconPacks[${index}] must be a plain object with a json string. ${jsonCopyHint}`);
252
+ }
253
+
254
+ let json;
255
+ let hasJson = false;
256
+ let registrationName;
257
+ for (const key of Reflect.ownKeys(pack)) {
258
+ if (typeof key === "symbol") {
259
+ throw new TypeError(`iconPacks[${index}] must not contain symbol keys.`);
260
+ }
261
+ if (key !== "json" && key !== "registrationName") {
262
+ throw new TypeError("iconPacks entries only accept json and registrationName.");
263
+ }
264
+ const descriptor = Object.getOwnPropertyDescriptor(pack, key);
265
+ if (!descriptor?.enumerable || !("value" in descriptor)) {
266
+ const hint = key === "json" ? ` ${jsonCopyHint}` : "";
267
+ throw new TypeError(`iconPacks[${index}].${key} must be an enumerable data property.${hint}`);
268
+ }
269
+ if (key === "json") {
270
+ json = descriptor.value;
271
+ hasJson = true;
272
+ } else {
273
+ registrationName = descriptor.value;
274
+ }
154
275
  }
155
- if (Object.keys(pack).some((key) => key !== "json" && key !== "registrationName")) {
156
- throw new TypeError("iconPacks entries only accept json and registrationName.");
276
+
277
+ if (!hasJson || typeof json !== "string") {
278
+ throw new TypeError("iconPacks entries must contain an already loaded JSON string.");
157
279
  }
158
- if (pack.registrationName !== undefined && typeof pack.registrationName !== "string") {
280
+ if (registrationName !== undefined && typeof registrationName !== "string") {
159
281
  throw new TypeError("iconPacks registrationName must be a string.");
160
282
  }
161
- normalized.push({
162
- json: pack.json,
163
- ...(pack.registrationName === undefined ? {} : { registrationName: pack.registrationName }),
164
- });
283
+
284
+ if (index > 0) addJsonEnvelopeBytes(budget, 1);
285
+ addJsonEnvelopeBytes(budget, ICON_PACK_ENTRY_JSON_FRAME_BYTES);
286
+ addJsonEnvelopeStringBytes(json, `iconPacks[${index}].json`, budget);
287
+
288
+ const entry = Object.create(null);
289
+ entry.json = json;
290
+ if (registrationName !== undefined) {
291
+ addJsonEnvelopeBytes(budget, ICON_PACK_REGISTRATION_NAME_KEY_BYTES);
292
+ addJsonEnvelopeStringBytes(
293
+ registrationName,
294
+ `iconPacks[${index}].registrationName`,
295
+ budget,
296
+ );
297
+ entry.registrationName = registrationName;
298
+ }
299
+ normalized[index] = entry;
165
300
  }
301
+
166
302
  return JSON.stringify(normalized);
167
303
  }
168
304
 
@@ -216,6 +352,7 @@ export function normalizeBindingOptions(value = {}) {
216
352
 
217
353
  export class MermanEngine {
218
354
  #directSvg;
355
+ #executeWasmSvgResponseSync;
219
356
  #disposePromise = null;
220
357
  #executor;
221
358
  #metadataIds;
@@ -223,7 +360,10 @@ export class MermanEngine {
223
360
  #runtimeCatalog;
224
361
  #transport;
225
362
 
226
- constructor(constructionToken, transport, runtimeCatalog, queueOptions, directSvg) {
363
+ constructor(
364
+ constructionToken, transport, runtimeCatalog, queueOptions,
365
+ directSvg, executeWasmSvgResponseSync = undefined,
366
+ ) {
227
367
  if (constructionToken !== MERMAN_ENGINE_CONSTRUCTION_TOKEN) {
228
368
  throw new MermanInvalidTransportError(
229
369
  "MermanEngine instances must be created with createNodeEngine().",
@@ -231,6 +371,7 @@ export class MermanEngine {
231
371
  }
232
372
  this.#transport = transport;
233
373
  this.#directSvg = directSvg;
374
+ this.#executeWasmSvgResponseSync = executeWasmSvgResponseSync;
234
375
  this.#runtimeCatalog = runtimeCatalog;
235
376
  this.#metadataIds = new Set(
236
377
  runtimeCatalog.metadata_ids.filter((id) => METADATA_SPEC_BY_ID.has(id)),
@@ -247,66 +388,108 @@ export class MermanEngine {
247
388
  return structuredClone(this.#runtimeCatalog);
248
389
  }
249
390
 
250
- renderSvg(source, options = {}) {
391
+ async renderSvg(source, options = {}) {
251
392
  return this.#execute(
252
- { operationId: "svg", source, optionsJson: options.optionsJson },
393
+ { operationId: "svg", source, optionsJson: encodeRequestOptions(options) },
253
394
  { signal: options.signal, timeoutMs: options.timeoutMs },
254
395
  false,
396
+ options.diagramId,
255
397
  );
256
398
  }
257
399
 
258
400
  renderSvgSync(source, options = {}) {
401
+ this.#executor.assertSyncAvailable("renderSvgSync");
259
402
  return this.#executeSync(
260
- { operationId: "svg", source, optionsJson: options.optionsJson },
403
+ { operationId: "svg", source, optionsJson: encodeRequestOptions(options) },
261
404
  { timeoutMs: options.timeoutMs },
262
405
  false,
406
+ options.diagramId,
407
+ "renderSvgSync",
263
408
  );
264
409
  }
265
410
 
266
- svgPlanJson(source, options = {}) {
411
+ async svgPlanJson(source, options = {}) {
267
412
  return this.#execute(
268
- { operationId: "svg-plan-json", source, optionsJson: options.optionsJson },
413
+ { operationId: "svg-plan-json", source, optionsJson: encodeRequestOptions(options) },
269
414
  { signal: options.signal, timeoutMs: options.timeoutMs },
270
415
  false,
416
+ options.diagramId,
271
417
  );
272
418
  }
273
419
 
274
420
  svgPlanJsonSync(source, options = {}) {
421
+ this.#executor.assertSyncAvailable("svgPlanJsonSync");
275
422
  return this.#executeSync(
276
- { operationId: "svg-plan-json", source, optionsJson: options.optionsJson },
423
+ { operationId: "svg-plan-json", source, optionsJson: encodeRequestOptions(options) },
277
424
  { timeoutMs: options.timeoutMs },
278
425
  false,
426
+ options.diagramId,
427
+ "svgPlanJsonSync",
279
428
  );
280
429
  }
281
430
 
282
- materializeTheme(input, options = {}) {
283
- return this.#themeAuthoring("materialize-theme-json", input, options);
431
+ async drawListJson(source, options = {}) {
432
+ return this.#execute(
433
+ { operationId: "draw-list-json", source, optionsJson: encodeRequestOptions(options) },
434
+ { signal: options.signal, timeoutMs: options.timeoutMs },
435
+ false,
436
+ options.diagramId,
437
+ );
284
438
  }
285
439
 
286
- describeThemeSupport(query, options = {}) {
287
- return this.#themeAuthoring("describe-theme-support-json", query, options);
440
+ drawListJsonSync(source, options = {}) {
441
+ this.#executor.assertSyncAvailable("drawListJsonSync");
442
+ return this.#executeSync(
443
+ { operationId: "draw-list-json", source, optionsJson: encodeRequestOptions(options) },
444
+ { timeoutMs: options.timeoutMs },
445
+ false,
446
+ options.diagramId,
447
+ "drawListJsonSync",
448
+ );
288
449
  }
289
450
 
290
- exportThemePreset(presetId, options = {}) {
451
+ async exportThemePreset(presetId, options = {}) {
291
452
  if (typeof presetId !== "string") {
292
- return Promise.reject(new TypeError("theme preset ID must be a string."));
453
+ throw new TypeError("theme preset ID must be a string.");
293
454
  }
294
- return this.#themeAuthoring("export-theme-preset-json", presetId, options);
455
+ return this.#executeThemeJson("export-theme-preset", presetId, options);
295
456
  }
296
457
 
297
- async #themeAuthoring(operationId, input, options) {
298
- const source = typeof input === "string"
299
- ? input
300
- : encodeTransportJson(input, "theme authoring input", THEME_AUTHORING_INPUT_LIMITS);
301
- const json = await this.#execute(
302
- { operationId, source, optionsJson: options.optionsJson },
303
- { signal: options.signal, timeoutMs: options.timeoutMs },
304
- false,
458
+ async resolveTheme(document, { appearance, auto_fix_contrast, expand, signal, timeoutMs } = {}) {
459
+ if (typeof document !== "string" && !isPlainObject(document)) {
460
+ throw new TypeError("theme document must be a plain object or JSON text.");
461
+ }
462
+ const source = encodeTransportJson(
463
+ {
464
+ document,
465
+ ...(appearance === undefined ? {} : { appearance }),
466
+ ...(auto_fix_contrast === undefined ? {} : { auto_fix_contrast }),
467
+ ...(expand === undefined ? {} : { expand }),
468
+ },
469
+ "theme resolution request",
470
+ THEME_REQUEST_LIMITS,
305
471
  );
306
- return parseTransportJsonText(json, "theme authoring result", THEME_AUTHORING_RESULT_LIMITS);
472
+ return this.#executeThemeJson("resolve-theme", source, { signal, timeoutMs });
473
+ }
474
+
475
+ async #executeThemeJson(operationId, source, options) {
476
+ const json = await this.#execute({ operationId, source }, options, false);
477
+ return parseTransportJsonText(json, "theme operation result", THEME_RESULT_LIMITS);
478
+ }
479
+
480
+ themeCatalog() {
481
+ const { parsed } = this.#readMetadata("theme-catalog");
482
+ if (parsed?.schema_version !== 2) {
483
+ throw new MermanInvalidTransportError("Merman transport returned an unsupported theme catalog schema.");
484
+ }
485
+ return parsed;
307
486
  }
308
487
 
309
488
  metadataJson(id) {
489
+ return this.#readMetadata(id).json;
490
+ }
491
+
492
+ #readMetadata(id) {
310
493
  this.#executor.assertOpen();
311
494
  if (typeof id !== "string" || id.length === 0) {
312
495
  throw new TypeError("metadata id must be a non-empty string.");
@@ -316,87 +499,121 @@ export class MermanEngine {
316
499
  `metadata id \`${id}\` is not callable through this SDK and artifact contract.`,
317
500
  );
318
501
  }
319
- let value;
502
+ let json;
320
503
  try {
321
- value = this.#transport.metadataJson(id);
504
+ json = this.#transport.metadataJson(id);
322
505
  } catch (cause) {
323
506
  throw decodeWireInvocationError(cause, `Merman metadata \`${id}\``);
324
507
  }
325
- parseTransportJsonText(
326
- value,
508
+ const parsed = parseTransportJsonText(
509
+ json,
327
510
  `metadata \`${id}\``,
328
511
  NODE_TRANSPORT_LIMITS.metadata,
329
512
  );
330
- return value;
513
+ return { json, parsed };
331
514
  }
332
515
 
333
516
  executeOperation(request, options = {}) {
334
517
  return this.#execute(request, options, true);
335
518
  }
336
519
 
337
- #execute(request, { signal, timeoutMs } = {}, includeMetadata) {
520
+ #execute(request, options = {}, includeMetadata, diagramId) {
338
521
  try {
522
+ const { timeoutMs } = options;
339
523
  this.#executor.assertOpen();
524
+ const signal = normalizeOperationSignal(options.signal);
525
+ const directSvg = this.#usesDirectSvg(request, includeMetadata);
526
+ const directDrawList = this.#usesDirectDrawList(request, includeMetadata, false);
527
+ const directData = directSvg || directDrawList;
528
+ const prepared = prepareOperationRequest(request, { timeoutMs, directSvg: directData });
529
+ const { expectation } = prepared;
530
+ if (signal?.aborted) return Promise.reject(abortError());
531
+ const useTypedId = diagramId !== undefined && prepareSvgDiagramId(
532
+ prepared, diagramId, timeoutMs, directSvg && !!this.#transport.executeSvgWithId,
533
+ );
534
+ let execute;
535
+ if (useTypedId) {
536
+ execute = (forwarded) => this.#transport.executeSvgWithId(request.source, diagramId, forwarded, timeoutMs);
537
+ } else if (directSvg) {
538
+ const optionsJson = prepareDirectOperationOptions(prepared, timeoutMs, SVG_REQUEST_FRAME_BYTES);
539
+ const { source } = prepared.request;
540
+ execute = (forwarded) => this.#transport.executeSvg(source, optionsJson, forwarded, timeoutMs);
541
+ } else if (directDrawList) {
542
+ const optionsJson = prepareDirectOperationOptions(prepared, timeoutMs, DRAW_LIST_REQUEST_FRAME_BYTES);
543
+ const { source } = prepared.request;
544
+ execute = (forwarded) => this.#transport.executeDrawList(source, optionsJson, forwarded, timeoutMs);
545
+ } else {
546
+ const requestJson = operationRequestJson(prepared, includeMetadata);
547
+ execute = (forwarded) => this.#transport.execute(requestJson, forwarded, timeoutMs);
548
+ }
549
+ return this.#executor.submit(
550
+ async () => {
551
+ // A signal can flip after queue admission but before this start microtask runs. That work
552
+ // has not crossed the transport boundary, so preserve the established AbortError result.
553
+ if (signal?.aborted) throw abortError();
554
+ let response;
555
+ try {
556
+ response = await executeTransportOperation(execute, signal);
557
+ } catch (cause) {
558
+ throw decodeWireInvocationError(cause, "Merman operation");
559
+ }
560
+ return this.#decodeOperationResponse(response, expectation, {
561
+ includeMetadata,
562
+ directSvgResponse: directData,
563
+ signal,
564
+ timeoutMs,
565
+ });
566
+ },
567
+ { signal },
568
+ );
340
569
  } catch (error) {
341
570
  return Promise.reject(error);
342
571
  }
343
- const directSvg = this.#usesDirectSvg(request, includeMetadata);
344
- const prepared = prepareOperationRequest(request, { timeoutMs, directSvg });
345
- const { expectation } = prepared;
346
- if (signal?.aborted) return Promise.reject(abortError());
347
- let execute;
348
- if (directSvg) {
349
- const optionsJson = prepareDirectSvgOptions(prepared, timeoutMs);
350
- const { source } = prepared.request;
351
- execute = (forwarded) => this.#transport.executeSvg(source, optionsJson, forwarded, timeoutMs);
352
- } else {
353
- const requestJson = operationRequestJson(prepared, includeMetadata);
354
- execute = (forwarded) => this.#transport.execute(requestJson, forwarded, timeoutMs);
355
- }
356
- return this.#executor.submit(
357
- async () => {
358
- // A signal can flip after queue admission but before this start microtask runs. That work
359
- // has not crossed the transport boundary, so preserve the established AbortError result.
360
- if (signal?.aborted) throw abortError();
361
- let response;
362
- try {
363
- response = await executeTransportOperation(execute, signal);
364
- } catch (cause) {
365
- throw decodeWireInvocationError(cause, "Merman operation");
366
- }
367
- return this.#decodeOperationResponse(response, expectation, {
368
- includeMetadata,
369
- directSvg,
370
- signal,
371
- timeoutMs,
372
- });
373
- },
374
- { signal },
375
- );
376
572
  }
377
573
 
378
574
  executeOperationSync(request, options = {}) {
379
- return this.#executeSync(request, options, true);
575
+ this.#executor.assertSyncAvailable("executeOperationSync");
576
+ return this.#executeSync(request, options, true, undefined, "executeOperationSync");
380
577
  }
381
578
 
382
- #executeSync(request, { timeoutMs } = {}, includeMetadata) {
383
- this.#executor.assertSyncAvailable();
579
+ #executeSync(request, { timeoutMs } = {}, includeMetadata, diagramId, syncMethod = "executeOperationSync") {
384
580
  const directSvg = this.#usesDirectSvg(request, includeMetadata);
385
- const prepared = prepareOperationRequest(request, { timeoutMs, directSvg });
386
- const payload = directSvg
387
- ? prepareDirectSvgOptions(prepared, timeoutMs)
388
- : operationRequestJson(prepared, includeMetadata);
581
+ const directDrawList = this.#usesDirectDrawList(request, includeMetadata, true);
582
+ const directData = directSvg || directDrawList;
583
+ const prepared = prepareOperationRequest(request, { timeoutMs, directSvg: directData });
584
+ const useTypedId = diagramId !== undefined && prepareSvgDiagramId(
585
+ prepared, diagramId, timeoutMs, directSvg && !!this.#transport.executeSvgWithIdSync,
586
+ );
587
+ let payload = diagramId;
588
+ if (!useTypedId) {
589
+ payload = directSvg
590
+ ? prepareDirectOperationOptions(prepared, timeoutMs, SVG_REQUEST_FRAME_BYTES)
591
+ : directDrawList
592
+ ? prepareDirectOperationOptions(prepared, timeoutMs, DRAW_LIST_REQUEST_FRAME_BYTES)
593
+ : operationRequestJson(prepared, includeMetadata);
594
+ }
595
+ this.#executor.assertSyncAvailable(syncMethod);
596
+ const wasmSvgResponse = this.#executeWasmSvgResponseSync !== undefined &&
597
+ !includeMetadata && prepared.expectation.operation_id === "svg";
389
598
  let response;
390
599
  try {
391
- response = directSvg
392
- ? this.#transport.executeSvgSync(prepared.request.source, payload, timeoutMs)
393
- : this.#transport.executeSync(payload, timeoutMs);
600
+ if (directSvg) {
601
+ response = useTypedId
602
+ ? this.#transport.executeSvgWithIdSync(request.source, payload, timeoutMs)
603
+ : this.#transport.executeSvgSync(request.source, payload, timeoutMs);
604
+ } else if (directDrawList) {
605
+ response = this.#transport.executeDrawListSync(request.source, payload, timeoutMs);
606
+ } else if (wasmSvgResponse) {
607
+ response = this.#executeWasmSvgResponseSync(payload, timeoutMs);
608
+ } else {
609
+ response = this.#transport.executeSync(payload, timeoutMs);
610
+ }
394
611
  } catch (cause) {
395
612
  throw decodeWireInvocationError(cause, "Merman operation");
396
613
  }
397
614
  return this.#decodeOperationResponse(response, prepared.expectation, {
398
615
  includeMetadata,
399
- directSvg,
616
+ directSvgResponse: directData || wasmSvgResponse,
400
617
  timeoutMs,
401
618
  });
402
619
  }
@@ -405,17 +622,25 @@ export class MermanEngine {
405
622
  return this.#directSvg && !includeMetadata && request.operationId === "svg";
406
623
  }
407
624
 
408
- #decodeOperationResponse(response, expectation, { includeMetadata, directSvg, signal, timeoutMs }) {
409
- if (directSvg) {
625
+ #usesDirectDrawList(request, includeMetadata, sync) {
626
+ return this.#directSvg &&
627
+ !includeMetadata &&
628
+ request.operationId === "draw-list-json" &&
629
+ Boolean(sync ? this.#transport.executeDrawListSync : this.#transport.executeDrawList);
630
+ }
631
+
632
+ #decodeOperationResponse(response, expectation, { includeMetadata, directSvgResponse, signal, timeoutMs }) {
633
+ if (directSvgResponse) {
410
634
  if (typeof response === "string") return response;
411
635
  if (response === null || typeof response !== "object" || !Object.hasOwn(response, "errorJson")) {
412
- throw new MermanInvalidTransportError("The native SVG operation returned an invalid result.");
636
+ const label = expectation.operation_id === "svg" ? "SVG" : "DrawList";
637
+ throw new MermanInvalidTransportError(`The direct ${label} operation returned an invalid result.`);
413
638
  }
414
639
  response = response.errorJson;
415
640
  }
416
641
  return decodeWireResponse(response, expectation, {
417
642
  includeMetadata,
418
- requireError: directSvg,
643
+ requireError: directSvgResponse,
419
644
  allowedCancellationReasons: invocationCancellationReasons(signal, timeoutMs),
420
645
  requireUnavailable: !this.#operationIds.has(expectation.operation_id),
421
646
  availableCapabilityIds: this.#runtimeCatalog.capabilities.capability_ids,
@@ -429,6 +654,28 @@ export class MermanEngine {
429
654
  });
430
655
  return this.#disposePromise;
431
656
  }
657
+
658
+ [Symbol.dispose]() {
659
+ // Synchronous resource management starts disposal without awaiting in-flight work.
660
+ // dispose() and async disposal still expose the same promise and its result.
661
+ void this.dispose().catch(() => {});
662
+ }
663
+
664
+ [Symbol.asyncDispose]() {
665
+ return this.dispose();
666
+ }
667
+ }
668
+
669
+ function encodeRequestOptions({ options, optionsJson, diagramId }) {
670
+ if (options === undefined) return optionsJson;
671
+ if (optionsJson !== undefined) {
672
+ throw new TypeError("options and optionsJson cannot be used together.");
673
+ }
674
+ if (diagramId !== undefined) {
675
+ throw new TypeError("Use options.svg.diagram_id when supplying options with an SVG ID.");
676
+ }
677
+ if (!isPlainObject(options)) throw new TypeError("options must be a plain object.");
678
+ return encodeTransportJson(options, "operation request options", NODE_TRANSPORT_LIMITS.binding_options);
432
679
  }
433
680
 
434
681
  function invocationCancellationReasons(signal, timeoutMs) {
@@ -440,9 +687,8 @@ function invocationCancellationReasons(signal, timeoutMs) {
440
687
 
441
688
  function prepareOperationRequest(value, { timeoutMs, directSvg }) {
442
689
  if (!isPlainObject(value)) throw new TypeError("operation request must be a plain object.");
443
- const knownFields = new Set(["operationId", "source", "uri", "optionsJson"]);
444
690
  for (const field of Object.keys(value)) {
445
- if (!knownFields.has(field)) {
691
+ if (!OPERATION_REQUEST_FIELDS.has(field)) {
446
692
  throw new TypeError(`unknown operation request field \`${field}\`.`);
447
693
  }
448
694
  }
@@ -472,11 +718,18 @@ function prepareOperationRequest(value, { timeoutMs, directSvg }) {
472
718
  "operation request operationId",
473
719
  NODE_TRANSPORT_FIELD_LIMITS.operation_id_utf8_bytes,
474
720
  );
475
- const sourceBytes = (directSvg ? jsonStringFieldBytes : assertUtf8Field)(
476
- source,
477
- "operation request source",
478
- NODE_TRANSPORT_FIELD_LIMITS.source_utf8_bytes,
479
- );
721
+ let sourceByteBound;
722
+ if (directSvg && source.length <= DIRECT_SVG_SOURCE_UNIT_BOUND && source.isWellFormed()) {
723
+ // Every admitted options or typed-ID frame still fits with this upper bound.
724
+ sourceByteBound = source.length * 6;
725
+ } else {
726
+ const measureSource = directSvg ? jsonStringFieldBytes : assertUtf8Field;
727
+ sourceByteBound = measureSource(
728
+ source,
729
+ "operation request source",
730
+ NODE_TRANSPORT_FIELD_LIMITS.source_utf8_bytes,
731
+ );
732
+ }
480
733
  if (normalizedUri !== null) {
481
734
  assertUtf8Field(
482
735
  normalizedUri,
@@ -501,32 +754,45 @@ function prepareOperationRequest(value, { timeoutMs, directSvg }) {
501
754
  }
502
755
  request.operation_control = { timeout_ms: timeoutMs };
503
756
  }
504
- return { expectation, request, value, sourceBytes };
757
+ return { expectation, request, value, sourceByteBound, diagramIdOptionsJson: undefined };
505
758
  }
506
759
 
507
- function operationRequestJson({ request, value }, includeMetadata) {
760
+ function operationOptionsJsonBytes(optionsJson, fromDiagramId, countJsonEscapes = false) {
761
+ if (!fromDiagramId) return validateOperationOptionsJson(optionsJson, countJsonEscapes);
762
+
763
+ // The diagram ID fallback already encoded and checked the binding options document.
764
+ const measureField = countJsonEscapes ? jsonStringFieldBytes : assertUtf8Field;
765
+ return measureField(
766
+ optionsJson,
767
+ "operation request optionsJson",
768
+ NODE_TRANSPORT_FIELD_LIMITS.options_json_utf8_bytes,
769
+ );
770
+ }
771
+
772
+ function operationRequestJson({ request, value, diagramIdOptionsJson }, includeMetadata) {
508
773
  if (!includeMetadata) request.include_metadata = false;
509
- const optionsJson = value.optionsJson;
774
+ const optionsJson = diagramIdOptionsJson ?? encodeRequestOptions(value);
510
775
  if (optionsJson !== undefined) {
511
- validateOperationOptionsJson(optionsJson, assertUtf8Field);
776
+ operationOptionsJsonBytes(optionsJson, diagramIdOptionsJson !== undefined);
512
777
  request.options_json = optionsJson;
513
778
  }
514
779
  return encodeTransportJson(request, "operation request", NODE_TRANSPORT_LIMITS.request);
515
780
  }
516
781
 
517
- function prepareDirectSvgOptions({ value, sourceBytes }, timeoutMs) {
782
+ function prepareDirectOperationOptions(
783
+ { value, sourceByteBound, diagramIdOptionsJson },
784
+ timeoutMs,
785
+ baseFrameBytes,
786
+ ) {
518
787
  // Match the former fixed request's byte budget without building or scanning the document.
519
- let requestBytes = SVG_REQUEST_FRAME_BYTES + sourceBytes;
520
- if (timeoutMs !== undefined) {
521
- requestBytes += SVG_TIMEOUT_FRAME_BYTES + String(timeoutMs).length;
522
- }
523
- const optionsJson = value.optionsJson;
788
+ let requestByteBound = directOperationFrameBytes(baseFrameBytes, sourceByteBound, timeoutMs);
789
+ const optionsJson = diagramIdOptionsJson ?? value.optionsJson;
524
790
  if (optionsJson !== undefined) {
525
- requestBytes +=
526
- SVG_OPTIONS_FRAME_BYTES + validateOperationOptionsJson(optionsJson, jsonStringFieldBytes);
791
+ const optionsBytes = operationOptionsJsonBytes(optionsJson, diagramIdOptionsJson !== undefined, true);
792
+ requestByteBound += SVG_OPTIONS_FRAME_BYTES + optionsBytes;
527
793
  }
528
794
  const max = NODE_TRANSPORT_LIMITS.request.max_utf8_bytes;
529
- if (requestBytes > max) {
795
+ if (requestByteBound > max) {
530
796
  throw new MermanInvalidTransportError(
531
797
  `Merman transport operation request exceeds the ${max}-byte wire limit.`,
532
798
  );
@@ -534,14 +800,46 @@ function prepareDirectSvgOptions({ value, sourceBytes }, timeoutMs) {
534
800
  return optionsJson;
535
801
  }
536
802
 
537
- function validateOperationOptionsJson(optionsJson, measureField) {
538
- if (typeof optionsJson !== "string") {
539
- throw new TypeError("optionsJson must be a JSON string when provided.");
803
+ function directOperationFrameBytes(baseFrameBytes, sourceByteBound, timeoutMs) {
804
+ const timeoutBytes = timeoutMs === undefined ? 0 : SVG_TIMEOUT_FRAME_BYTES + String(timeoutMs).length;
805
+ return baseFrameBytes + sourceByteBound + timeoutBytes;
806
+ }
807
+
808
+ function directSvgFrameBytes(sourceByteBound, timeoutMs) {
809
+ return directOperationFrameBytes(SVG_REQUEST_FRAME_BYTES, sourceByteBound, timeoutMs);
810
+ }
811
+
812
+ function prepareSvgDiagramId(prepared, diagramId, timeoutMs, typedTransport) {
813
+ if (prepared.request.operation_id !== "svg") {
814
+ throw new TypeError("diagramId is only supported by renderSvg() and renderSvgSync().");
815
+ }
816
+ if (typeof diagramId !== "string") throw new TypeError("diagramId must be a string when provided.");
817
+ if (prepared.value.optionsJson !== undefined) {
818
+ throw new TypeError("diagramId and optionsJson cannot be used together.");
540
819
  }
541
- const label = "operation request optionsJson";
542
- const bytes = measureField(optionsJson, label, NODE_TRANSPORT_FIELD_LIMITS.options_json_utf8_bytes);
543
- parseTransportJsonText(optionsJson, label, NODE_TRANSPORT_LIMITS.binding_options);
544
- return bytes;
820
+
821
+ // A UTF-16 unit needs at most six bytes in compact JSON, and enclosing that JSON as a
822
+ // request field expands it by at most twice. Use the exact wire path near either limit.
823
+ const optionsLimit = NODE_TRANSPORT_FIELD_LIMITS.options_json_utf8_bytes;
824
+ const maxOptionsBytes = SVG_ID_OPTIONS_BYTES + diagramId.length * 6;
825
+ if (typedTransport && maxOptionsBytes <= optionsLimit &&
826
+ directSvgFrameBytes(prepared.sourceByteBound, timeoutMs) + SVG_OPTIONS_FRAME_BYTES + maxOptionsBytes * 2 <=
827
+ NODE_TRANSPORT_LIMITS.request.max_utf8_bytes) {
828
+ assertUtf8Field(diagramId, "operation request diagramId", optionsLimit);
829
+ return true;
830
+ }
831
+
832
+ try {
833
+ prepared.diagramIdOptionsJson = encodeTransportJson(
834
+ { svg: { diagram_id: diagramId } }, "operation request diagramId", NODE_TRANSPORT_LIMITS.binding_options,
835
+ );
836
+ } catch (error) {
837
+ // The encoder can exhaust the document budget before reaching the end of the ID.
838
+ // Give raw ID field and UTF-16 errors the same priority as the typed input path.
839
+ assertUtf8Field(diagramId, "operation request diagramId.svg.diagram_id", optionsLimit);
840
+ throw error;
841
+ }
842
+ return false;
545
843
  }
546
844
 
547
845
  async function executeTransportOperation(execute, signal) {
@@ -592,13 +890,11 @@ async function disposeUnusableTransport(transport) {
592
890
  }
593
891
  }
594
892
 
595
- export function validateRuntimeCatalog(value) {
596
- if (typeof value !== "string") {
597
- throw new MermanInvalidTransportError(
598
- "Merman transport runtime catalog must be JSON text.",
599
- );
600
- }
601
- const catalog = parseRuntimeCatalogJsonText(value);
893
+ export function validateRuntimeCatalog(value, { localLayout = null, candidate = null } = {}) {
894
+ return validateParsedRuntimeCatalog(parseRuntimeCatalogJsonText(value), { localLayout, candidate });
895
+ }
896
+
897
+ function validateParsedRuntimeCatalog(catalog, { localLayout, candidate }) {
602
898
  if (!isPlainObject(catalog)) {
603
899
  throw new MermanInvalidTransportError("Merman transport returned an invalid runtime catalog.");
604
900
  }
@@ -649,7 +945,9 @@ export function validateRuntimeCatalog(value) {
649
945
  validateOperationRelations({ capabilityIds, operationIds, outputIds });
650
946
  const metadataIds = validateMetadataIds(catalog.metadata_ids, new Set(capabilityIds));
651
947
  validateKnownArtifactIdentity({
948
+ candidate,
652
949
  capabilityIds,
950
+ localLayout,
653
951
  metadataIds,
654
952
  operationIds,
655
953
  outputIds,
@@ -689,13 +987,17 @@ export function validateRuntimeCatalog(value) {
689
987
  }
690
988
 
691
989
  function validateKnownArtifactIdentity({
990
+ candidate,
692
991
  capabilityIds,
992
+ localLayout,
693
993
  metadataIds,
694
994
  operationIds,
695
995
  outputIds,
696
996
  systemAdapterIds,
697
997
  }) {
698
- const expected = NODE_WIRE_CONTRACT.artifact;
998
+ const expected = nodeWireContract(
999
+ localLayout, candidate === "node-wasm" ? "wasm" : "napi", capabilityIds,
1000
+ ).artifact;
699
1001
  validateKnownIds(
700
1002
  capabilityIds,
701
1003
  expected.capability_ids,