@mermanjs/node-wasm 0.9.3 → 0.10.0-alpha.2

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
@@ -12,6 +12,7 @@ import {
12
12
  parseRuntimeCatalogJsonText,
13
13
  parseTransportJsonText,
14
14
  sameJsonValue,
15
+ snapshotTransportJsonValue,
15
16
  } from "./errors.mjs";
16
17
  import {
17
18
  BINDING_OPTION_GROUP_SPECS,
@@ -149,11 +150,16 @@ function encodeIconPacks(packs) {
149
150
 
150
151
  export function normalizeBindingOptions(value = {}) {
151
152
  if (!isPlainObject(value)) throw new TypeError("bindingOptions must be a plain object.");
152
- const normalized = cloneBoundedJsonValue(value, "bindingOptions");
153
+ const normalized = snapshotTransportJsonValue(
154
+ value,
155
+ "bindingOptions",
156
+ NODE_TRANSPORT_LIMITS.binding_options,
157
+ );
153
158
  normalized.version ??= BINDING_OPTIONS_SCHEMA_VERSION;
154
159
  if (normalized.version !== BINDING_OPTIONS_SCHEMA_VERSION) {
160
+ const version = typeof normalized.version === "object" ? "non-scalar" : normalized.version;
155
161
  throw new RangeError(
156
- `Unsupported binding options schema version \`${normalized.version}\`; expected ${BINDING_OPTIONS_SCHEMA_VERSION}.`,
162
+ `Unsupported binding options schema version \`${version}\`; expected ${BINDING_OPTIONS_SCHEMA_VERSION}.`,
157
163
  );
158
164
  }
159
165
  normalized.runtime_policy ??= "deterministic";
@@ -162,13 +168,16 @@ export function normalizeBindingOptions(value = {}) {
162
168
  "bindingOptions.runtime_policy must be `deterministic` for @mermanjs/node.",
163
169
  );
164
170
  }
165
- normalized.resources ??= {};
171
+ normalized.resources ??= Object.create(null);
166
172
  if (!isPlainObject(normalized.resources)) {
167
173
  throw new TypeError("bindingOptions.resources must be a plain object.");
168
174
  }
169
175
  normalized.resources.profile ??= "interactive";
170
176
  if (!RESOURCE_PROFILES.has(normalized.resources.profile)) {
171
- throw new RangeError(`Unknown resource profile \`${normalized.resources.profile}\`.`);
177
+ const profile = typeof normalized.resources.profile === "object"
178
+ ? "non-scalar"
179
+ : normalized.resources.profile;
180
+ throw new RangeError(`Unknown resource profile \`${profile}\`.`);
172
181
  }
173
182
  if (normalized.environment !== undefined) {
174
183
  if (!isPlainObject(normalized.environment)) {
@@ -176,10 +185,11 @@ export function normalizeBindingOptions(value = {}) {
176
185
  }
177
186
  if (
178
187
  normalized.environment.text_measurement !== undefined &&
188
+ normalized.environment.text_measurement !== null &&
179
189
  normalized.environment.text_measurement !== "deterministic"
180
190
  ) {
181
191
  throw new RangeError(
182
- "bindingOptions.environment.text_measurement must be `deterministic`.",
192
+ "bindingOptions.environment.text_measurement must be `deterministic` or null.",
183
193
  );
184
194
  }
185
195
  }
@@ -218,39 +228,35 @@ export class MermanEngine {
218
228
  }
219
229
 
220
230
  renderSvg(source, options = {}) {
221
- return this.executeOperation(
231
+ return this.#execute(
222
232
  { operationId: "svg", source, optionsJson: options.optionsJson },
223
233
  { signal: options.signal, timeoutMs: options.timeoutMs },
224
- ).then((result) => result.data);
234
+ false,
235
+ );
225
236
  }
226
237
 
227
238
  renderSvgSync(source, options = {}) {
228
- return this.executeOperationSync(
229
- {
230
- operationId: "svg",
231
- source,
232
- optionsJson: options.optionsJson,
233
- },
239
+ return this.#executeSync(
240
+ { operationId: "svg", source, optionsJson: options.optionsJson },
234
241
  { timeoutMs: options.timeoutMs },
235
- ).data;
242
+ false,
243
+ );
236
244
  }
237
245
 
238
246
  svgPlanJson(source, options = {}) {
239
- return this.executeOperation(
247
+ return this.#execute(
240
248
  { operationId: "svg-plan-json", source, optionsJson: options.optionsJson },
241
249
  { signal: options.signal, timeoutMs: options.timeoutMs },
242
- ).then((result) => result.data);
250
+ false,
251
+ );
243
252
  }
244
253
 
245
254
  svgPlanJsonSync(source, options = {}) {
246
- return this.executeOperationSync(
247
- {
248
- operationId: "svg-plan-json",
249
- source,
250
- optionsJson: options.optionsJson,
251
- },
255
+ return this.#executeSync(
256
+ { operationId: "svg-plan-json", source, optionsJson: options.optionsJson },
252
257
  { timeoutMs: options.timeoutMs },
253
- ).data;
258
+ false,
259
+ );
254
260
  }
255
261
 
256
262
  metadataJson(id) {
@@ -277,7 +283,11 @@ export class MermanEngine {
277
283
  return value;
278
284
  }
279
285
 
280
- executeOperation(request, { signal, timeoutMs } = {}) {
286
+ executeOperation(request, options = {}) {
287
+ return this.#execute(request, options, true);
288
+ }
289
+
290
+ #execute(request, { signal, timeoutMs } = {}, includeMetadata) {
281
291
  try {
282
292
  this.#executor.assertOpen();
283
293
  } catch (error) {
@@ -285,7 +295,7 @@ export class MermanEngine {
285
295
  }
286
296
  const prepared = prepareOperationRequest(request, { timeoutMs });
287
297
  if (signal?.aborted) return Promise.reject(abortError());
288
- const encoded = operationRequestJson(prepared);
298
+ const encoded = operationRequestJson(prepared, includeMetadata);
289
299
  return this.#executor.submit(
290
300
  async () => {
291
301
  // A signal can flip after queue admission but before this start microtask runs. That work
@@ -303,17 +313,26 @@ export class MermanEngine {
303
313
  throw decodeWireInvocationError(cause, "Merman operation");
304
314
  }
305
315
  return decodeWireResponse(responseJson, encoded.expectation, {
316
+ includeMetadata,
306
317
  allowedCancellationReasons: invocationCancellationReasons(signal, timeoutMs),
307
318
  requireUnavailable: !this.#operationIds.has(encoded.expectation.operation_id),
319
+ availableCapabilityIds: this.#runtimeCatalog.capabilities.capability_ids,
308
320
  });
309
321
  },
310
322
  { signal },
311
323
  );
312
324
  }
313
325
 
314
- executeOperationSync(request, { timeoutMs } = {}) {
326
+ executeOperationSync(request, options = {}) {
327
+ return this.#executeSync(request, options, true);
328
+ }
329
+
330
+ #executeSync(request, { timeoutMs } = {}, includeMetadata) {
315
331
  this.#executor.assertSyncAvailable();
316
- const encoded = operationRequestJson(prepareOperationRequest(request, { timeoutMs }));
332
+ const encoded = operationRequestJson(
333
+ prepareOperationRequest(request, { timeoutMs }),
334
+ includeMetadata,
335
+ );
317
336
  let responseJson;
318
337
  try {
319
338
  responseJson = this.#transport.executeSync(encoded.json, timeoutMs);
@@ -321,8 +340,10 @@ export class MermanEngine {
321
340
  throw decodeWireInvocationError(cause, "Merman operation");
322
341
  }
323
342
  return decodeWireResponse(responseJson, encoded.expectation, {
343
+ includeMetadata,
324
344
  allowedCancellationReasons: invocationCancellationReasons(undefined, timeoutMs),
325
345
  requireUnavailable: !this.#operationIds.has(encoded.expectation.operation_id),
346
+ availableCapabilityIds: this.#runtimeCatalog.capabilities.capability_ids,
326
347
  });
327
348
  }
328
349
 
@@ -408,7 +429,8 @@ function prepareOperationRequest(value, { timeoutMs } = {}) {
408
429
  return { expectation, request, value };
409
430
  }
410
431
 
411
- function operationRequestJson({ expectation, request, value }) {
432
+ function operationRequestJson({ expectation, request, value }, includeMetadata) {
433
+ if (!includeMetadata) request.include_metadata = false;
412
434
  const optionsJson = value.optionsJson;
413
435
  if (optionsJson !== undefined) {
414
436
  if (typeof optionsJson !== "string") {
@@ -1229,139 +1251,6 @@ function sortedUniqueFieldIdentifiers(value, field) {
1229
1251
  return value;
1230
1252
  }
1231
1253
 
1232
- function cloneBoundedJsonValue(root, label) {
1233
- const limits = NODE_TRANSPORT_LIMITS.binding_options;
1234
- const active = new WeakSet();
1235
- const clone = jsonContainerClone(root, label);
1236
- const stack = [{ depth: 1, source: root, target: clone, exiting: false }];
1237
- let members = 0;
1238
- let tokens = 1;
1239
-
1240
- while (stack.length > 0) {
1241
- const frame = stack.pop();
1242
- if (frame.exiting) {
1243
- active.delete(frame.source);
1244
- continue;
1245
- }
1246
- if (active.has(frame.source)) {
1247
- throw new TypeError(`${label} must not contain cyclic references.`);
1248
- }
1249
- if (frame.depth > limits.max_depth) {
1250
- throw new RangeError(`${label} exceeds the structural depth limit ${limits.max_depth}.`);
1251
- }
1252
- active.add(frame.source);
1253
- stack.push({ ...frame, exiting: true });
1254
-
1255
- const entries = jsonContainerEntries(
1256
- frame.source,
1257
- label,
1258
- limits.max_members - members,
1259
- limits.max_members,
1260
- );
1261
- members += entries.length;
1262
- if (members > limits.max_members) {
1263
- throw new RangeError(`${label} exceeds the member-work limit ${limits.max_members}.`);
1264
- }
1265
-
1266
- for (let index = entries.length - 1; index >= 0; index -= 1) {
1267
- const [key, child] = entries[index];
1268
- assertUtf8Field(key, `${label} object key`, limits.max_string_utf8_bytes);
1269
- tokens += 1;
1270
- if (tokens > limits.max_tokens) {
1271
- throw new RangeError(`${label} exceeds the token-work limit ${limits.max_tokens}.`);
1272
- }
1273
-
1274
- if (child === null || typeof child === "boolean") {
1275
- defineJsonValue(frame.target, key, child);
1276
- } else if (typeof child === "string") {
1277
- assertUtf8Field(child, `${label}.${key}`, limits.max_string_utf8_bytes);
1278
- defineJsonValue(frame.target, key, child);
1279
- } else if (typeof child === "number") {
1280
- if (!Number.isFinite(child)) {
1281
- throw new TypeError(`${label}.${key} must be a finite JSON number.`);
1282
- }
1283
- defineJsonValue(frame.target, key, child);
1284
- } else if (typeof child === "object") {
1285
- const childClone = jsonContainerClone(child, `${label}.${key}`);
1286
- defineJsonValue(frame.target, key, childClone);
1287
- stack.push({
1288
- depth: frame.depth + 1,
1289
- source: child,
1290
- target: childClone,
1291
- exiting: false,
1292
- });
1293
- } else {
1294
- throw new TypeError(`${label}.${key} is not a JSON wire value.`);
1295
- }
1296
- }
1297
- }
1298
- return clone;
1299
- }
1300
-
1301
- function jsonContainerClone(value, label) {
1302
- if (Array.isArray(value)) return [];
1303
- if (!isPlainObject(value)) {
1304
- throw new TypeError(`${label} must contain only arrays and plain objects.`);
1305
- }
1306
- return Object.getPrototypeOf(value) === null ? Object.create(null) : {};
1307
- }
1308
-
1309
- function jsonContainerEntries(value, label, remainingMembers, maxMembers) {
1310
- if (Array.isArray(value)) {
1311
- if (value.length > remainingMembers) {
1312
- throw new RangeError(`${label} exceeds the member-work limit ${maxMembers}.`);
1313
- }
1314
- const keys = Reflect.ownKeys(value);
1315
- if (keys.some((key) => typeof key === "symbol")) {
1316
- throw new TypeError(`${label} must not contain symbol keys.`);
1317
- }
1318
- for (let index = 0; index < value.length; index += 1) {
1319
- if (!Object.hasOwn(value, index)) {
1320
- throw new TypeError(`${label} arrays must not contain holes.`);
1321
- }
1322
- }
1323
- if (keys.length !== value.length + 1) {
1324
- throw new TypeError(`${label} arrays must not contain custom properties.`);
1325
- }
1326
- const entries = new Array(value.length);
1327
- for (let index = 0; index < value.length; index += 1) {
1328
- const key = String(index);
1329
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
1330
- if (!descriptor?.enumerable || !("value" in descriptor)) {
1331
- throw new TypeError(`${label}.${key} must be an enumerable data property.`);
1332
- }
1333
- entries[index] = [key, descriptor.value];
1334
- }
1335
- return entries;
1336
- }
1337
-
1338
- const entries = [];
1339
- for (const key of Reflect.ownKeys(value)) {
1340
- if (typeof key === "symbol") {
1341
- throw new TypeError(`${label} must not contain symbol keys.`);
1342
- }
1343
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
1344
- if (!descriptor?.enumerable || !("value" in descriptor)) {
1345
- throw new TypeError(`${label}.${key} must be an enumerable data property.`);
1346
- }
1347
- entries.push([key, descriptor.value]);
1348
- }
1349
- return entries;
1350
- }
1351
-
1352
- function defineJsonValue(target, key, value) {
1353
- if (Array.isArray(target)) {
1354
- target[Number(key)] = value;
1355
- return;
1356
- }
1357
- Object.defineProperty(target, key, {
1358
- configurable: true,
1359
- enumerable: true,
1360
- value,
1361
- writable: true,
1362
- });
1363
- }
1364
-
1365
1254
  function isPlainObject(value) {
1366
1255
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1367
1256
  const prototype = Object.getPrototypeOf(value);
package/dist/errors.mjs CHANGED
@@ -102,6 +102,7 @@ export class MermanOperationError extends MermanError {
102
102
  this.codeName = payload.code_name ?? null;
103
103
  this.kind = payload.kind ?? "generic";
104
104
  this.capabilityId = payload.capability_id ?? null;
105
+ this.details = payload.details ?? null;
105
106
  this.resourceDetails = payload.details?.resource ?? null;
106
107
  this.iconRegistryDetails = payload.details?.icon_registry ?? null;
107
108
  this.diagnosticDetails = payload.details?.diagnostic ?? null;
@@ -133,7 +134,7 @@ export class MermanLifecycleError extends MermanError {
133
134
  export class MermanUnsupportedTargetError extends MermanError {
134
135
  constructor({ platform, arch, libc = null, reason = null }) {
135
136
  const target = [platform, arch, libc].filter(Boolean).join("-");
136
- super(reason ?? `Unsupported Merman Node target: ${target}.`, {
137
+ super(`${reason ?? `Unsupported Merman Node target: ${target}.`} Use @mermanjs/node-wasm explicitly for a portable Node transport.`, {
137
138
  code: "MERMAN_UNSUPPORTED_TARGET",
138
139
  });
139
140
  this.platform = platform;
@@ -173,6 +174,18 @@ export class MermanInvalidTransportError extends MermanError {
173
174
  export { NODE_TRANSPORT_FIELD_LIMITS, NODE_TRANSPORT_LIMITS, NODE_WIRE_CONTRACT };
174
175
 
175
176
  export function parseTransportJsonText(value, label, limits) {
177
+ assertTransportJsonTextLimits(value, label, limits);
178
+ try {
179
+ return JSON.parse(value);
180
+ } catch (cause) {
181
+ throw new MermanInvalidTransportError(
182
+ `Merman transport returned invalid ${label} JSON.`,
183
+ cause,
184
+ );
185
+ }
186
+ }
187
+
188
+ function assertTransportJsonTextLimits(value, label, limits) {
176
189
  if (typeof value !== "string") {
177
190
  throw new MermanInvalidTransportError(`Merman transport ${label} must be JSON text.`);
178
191
  }
@@ -186,14 +199,6 @@ export function parseTransportJsonText(value, label, limits) {
186
199
  );
187
200
  }
188
201
  scanBoundedJsonText(value, label, limits);
189
- try {
190
- return JSON.parse(value);
191
- } catch (cause) {
192
- throw new MermanInvalidTransportError(
193
- `Merman transport returned invalid ${label} JSON.`,
194
- cause,
195
- );
196
- }
197
202
  }
198
203
 
199
204
  export function encodeTransportJson(value, label, limits) {
@@ -202,7 +207,7 @@ export function encodeTransportJson(value, label, limits) {
202
207
  }
203
208
  let boundedValue;
204
209
  try {
205
- boundedValue = cloneJsonWireValueWithinLimit(value, label, limits);
210
+ boundedValue = snapshotTransportJsonValue(value, label, limits);
206
211
  } catch (cause) {
207
212
  if (cause instanceof MermanInvalidTransportError) throw cause;
208
213
  throw new MermanInvalidTransportError(
@@ -219,17 +224,21 @@ export function encodeTransportJson(value, label, limits) {
219
224
  cause,
220
225
  );
221
226
  }
222
- parseTransportJsonText(text, label, limits);
227
+ assertTransportJsonTextLimits(text, label, limits);
223
228
  return text;
224
229
  }
225
230
 
226
- function cloneJsonWireValueWithinLimit(value, label, limits) {
227
- const budget = { label, max: limits.max_utf8_bytes, used: 0 };
231
+ export function snapshotTransportJsonValue(value, label, limits) {
232
+ if (!limits || typeof limits !== "object") {
233
+ throw new TypeError(`Missing Node wire limits for ${label}.`);
234
+ }
235
+ const budget = { label, max: limits.max_utf8_bytes, used: 0, members: 0, tokens: 0 };
228
236
  const active = new WeakSet();
229
237
  return cloneJsonWireValue(value, label, limits, budget, active, 1);
230
238
  }
231
239
 
232
240
  function cloneJsonWireValue(value, label, limits, budget, active, depth) {
241
+ addJsonWireToken(budget, limits);
233
242
  if (value === null) {
234
243
  addJsonWireBytes(budget, 4);
235
244
  return null;
@@ -239,7 +248,7 @@ function cloneJsonWireValue(value, label, limits, budget, active, depth) {
239
248
  return value;
240
249
  }
241
250
  if (typeof value === "string") {
242
- addJsonStringWireBytes(value, label, budget);
251
+ addJsonStringWireBytes(value, label, limits, budget);
243
252
  return value;
244
253
  }
245
254
  if (typeof value === "number") {
@@ -277,16 +286,19 @@ function cloneJsonWireValue(value, label, limits, budget, active, depth) {
277
286
  }
278
287
 
279
288
  function cloneJsonWireArray(value, label, limits, budget, active, depth) {
289
+ addJsonWireMembers(budget, limits, value.length);
280
290
  const keys = Reflect.ownKeys(value);
281
291
  if (keys.some((key) => typeof key === "symbol")) {
282
292
  throw new TypeError(`${label} must not contain symbol keys.`);
283
293
  }
294
+ if (keys.length < value.length + 1) {
295
+ throw new TypeError(`${label} arrays must not contain holes.`);
296
+ }
284
297
  if (keys.length !== value.length + 1) {
285
298
  throw new TypeError(`${label} arrays must not contain custom properties.`);
286
299
  }
287
300
 
288
- const clone = [];
289
- Object.defineProperty(clone, "toJSON", { value: undefined });
301
+ const clone = Object.setPrototypeOf([], null);
290
302
  addJsonWireBytes(budget, 1);
291
303
  for (let index = 0; index < value.length; index += 1) {
292
304
  if (!Object.hasOwn(value, index)) {
@@ -311,10 +323,12 @@ function cloneJsonWireArray(value, label, limits, budget, active, depth) {
311
323
  }
312
324
 
313
325
  function cloneJsonWireObject(value, label, limits, budget, active, depth) {
326
+ const keys = Reflect.ownKeys(value);
327
+ addJsonWireMembers(budget, limits, keys.length);
314
328
  const clone = Object.create(null);
315
329
  addJsonWireBytes(budget, 1);
316
330
  let member = 0;
317
- for (const key of Reflect.ownKeys(value)) {
331
+ for (const key of keys) {
318
332
  if (typeof key === "symbol") {
319
333
  throw new TypeError(`${label} must not contain symbol keys.`);
320
334
  }
@@ -323,7 +337,8 @@ function cloneJsonWireObject(value, label, limits, budget, active, depth) {
323
337
  throw new TypeError(`${label}.${key} must be an enumerable data property.`);
324
338
  }
325
339
  if (member > 0) addJsonWireBytes(budget, 1);
326
- addJsonStringWireBytes(key, `${label} object key`, budget);
340
+ addJsonWireToken(budget, limits);
341
+ addJsonStringWireBytes(key, `${label} object key`, limits, budget);
327
342
  addJsonWireBytes(budget, 1);
328
343
  const child = cloneJsonWireValue(
329
344
  descriptor.value,
@@ -345,12 +360,33 @@ function cloneJsonWireObject(value, label, limits, budget, active, depth) {
345
360
  return clone;
346
361
  }
347
362
 
348
- function addJsonStringWireBytes(value, label, budget) {
363
+ function addJsonWireMembers(budget, limits, count) {
364
+ if (count > limits.max_members - budget.members) {
365
+ throw new MermanInvalidTransportError(
366
+ `Merman transport ${budget.label} exceeds the member-work limit ${limits.max_members}.`,
367
+ );
368
+ }
369
+ budget.members += count;
370
+ }
371
+
372
+ function addJsonWireToken(budget, limits) {
373
+ budget.tokens += 1;
374
+ if (budget.tokens > limits.max_tokens) {
375
+ throw new MermanInvalidTransportError(
376
+ `Merman transport ${budget.label} exceeds the token-work limit ${limits.max_tokens}.`,
377
+ );
378
+ }
379
+ }
380
+
381
+ function addJsonStringWireBytes(value, label, limits, budget) {
382
+ let utf8Bytes = 0;
349
383
  addJsonWireBytes(budget, 1);
350
384
  for (let index = 0; index < value.length; index += 1) {
351
385
  const codeUnit = value.charCodeAt(index);
386
+ let characterBytes = utf8LengthOfCodeUnit(codeUnit);
387
+ let wireBytes = characterBytes;
352
388
  if (codeUnit === 0x22 || codeUnit === 0x5c) {
353
- addJsonWireBytes(budget, 2);
389
+ wireBytes = 2;
354
390
  } else if (
355
391
  codeUnit === 0x08 ||
356
392
  codeUnit === 0x09 ||
@@ -358,13 +394,9 @@ function addJsonStringWireBytes(value, label, budget) {
358
394
  codeUnit === 0x0c ||
359
395
  codeUnit === 0x0d
360
396
  ) {
361
- addJsonWireBytes(budget, 2);
397
+ wireBytes = 2;
362
398
  } else if (codeUnit <= 0x1f) {
363
- addJsonWireBytes(budget, 6);
364
- } else if (codeUnit <= 0x7f) {
365
- addJsonWireBytes(budget, 1);
366
- } else if (codeUnit <= 0x7ff) {
367
- addJsonWireBytes(budget, 2);
399
+ wireBytes = 6;
368
400
  } else if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {
369
401
  const low = value.charCodeAt(index + 1);
370
402
  if (!(low >= 0xdc00 && low <= 0xdfff)) {
@@ -372,15 +404,21 @@ function addJsonStringWireBytes(value, label, budget) {
372
404
  `Merman transport ${label} contains an isolated UTF-16 surrogate.`,
373
405
  );
374
406
  }
375
- addJsonWireBytes(budget, 4);
407
+ characterBytes = 4;
408
+ wireBytes = 4;
376
409
  index += 1;
377
410
  } else if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {
378
411
  throw new MermanInvalidTransportError(
379
412
  `Merman transport ${label} contains an isolated UTF-16 surrogate.`,
380
413
  );
381
- } else {
382
- addJsonWireBytes(budget, 3);
383
414
  }
415
+ utf8Bytes += characterBytes;
416
+ if (utf8Bytes > limits.max_string_utf8_bytes) {
417
+ throw new MermanInvalidTransportError(
418
+ `Merman transport ${label} contains a string exceeding the ${limits.max_string_utf8_bytes}-byte field limit.`,
419
+ );
420
+ }
421
+ addJsonWireBytes(budget, wireBytes);
384
422
  }
385
423
  addJsonWireBytes(budget, 1);
386
424
  }
@@ -864,7 +902,12 @@ export function abortError() {
864
902
  export function decodeWireResponse(
865
903
  value,
866
904
  expectation,
867
- { allowedCancellationReasons = [], requireUnavailable = false } = {},
905
+ {
906
+ includeMetadata = true,
907
+ allowedCancellationReasons = [],
908
+ requireUnavailable = false,
909
+ availableCapabilityIds = [],
910
+ } = {},
868
911
  ) {
869
912
  const cancellationReasons = validateAllowedCancellationReasons(allowedCancellationReasons);
870
913
  const envelope = parseTransportJsonText(
@@ -890,6 +933,7 @@ export function decodeWireResponse(
890
933
  expectation,
891
934
  requireUnavailable,
892
935
  cancellationReasons,
936
+ availableCapabilityIds,
893
937
  );
894
938
  throw new MermanOperationError(error);
895
939
  }
@@ -903,7 +947,7 @@ export function decodeWireResponse(
903
947
  "Merman transport executed an operation that its runtime catalog does not advertise.",
904
948
  );
905
949
  }
906
- return validateSuccessResult(envelope.result, expectation);
950
+ return validateSuccessResult(envelope.result, expectation, includeMetadata);
907
951
  }
908
952
 
909
953
  function validateAllowedCancellationReasons(reasons) {
@@ -959,7 +1003,7 @@ function validateEnvelopeHeader(envelope, label) {
959
1003
  }
960
1004
  }
961
1005
 
962
- function validateSuccessResult(result, expectation) {
1006
+ function validateSuccessResult(result, expectation, includeMetadata) {
963
1007
  if (
964
1008
  !isPlainJsonObject(result) ||
965
1009
  typeof result.operation_id !== "string" ||
@@ -967,7 +1011,7 @@ function validateSuccessResult(result, expectation) {
967
1011
  typeof result.media_type !== "string" ||
968
1012
  result.media_type.length === 0 ||
969
1013
  typeof result.data !== "string" ||
970
- typeof result.metadata_json !== "string"
1014
+ (includeMetadata && typeof result.metadata_json !== "string")
971
1015
  ) {
972
1016
  throw new MermanInvalidTransportError("Merman transport returned an invalid result envelope.");
973
1017
  }
@@ -986,11 +1030,6 @@ function validateSuccessResult(result, expectation) {
986
1030
  "response data",
987
1031
  NODE_TRANSPORT_FIELD_LIMITS.data_utf8_bytes,
988
1032
  );
989
- assertUtf8Field(
990
- result.metadata_json,
991
- "response metadata_json",
992
- NODE_TRANSPORT_FIELD_LIMITS.metadata_json_utf8_bytes,
993
- );
994
1033
  if (
995
1034
  !expectation ||
996
1035
  result.operation_id !== expectation.operation_id ||
@@ -1000,6 +1039,19 @@ function validateSuccessResult(result, expectation) {
1000
1039
  "Merman transport result identity does not match the requested operation contract.",
1001
1040
  );
1002
1041
  }
1042
+ if (!includeMetadata) {
1043
+ if (Object.hasOwn(result, "metadata_json")) {
1044
+ throw new MermanInvalidTransportError(
1045
+ "Merman transport returned metadata for a data-only operation.",
1046
+ );
1047
+ }
1048
+ return result.data;
1049
+ }
1050
+ assertUtf8Field(
1051
+ result.metadata_json,
1052
+ "response metadata_json",
1053
+ NODE_TRANSPORT_FIELD_LIMITS.metadata_json_utf8_bytes,
1054
+ );
1003
1055
  const metadata = parseTransportJsonText(
1004
1056
  result.metadata_json,
1005
1057
  "nested operation metadata",
@@ -1032,6 +1084,7 @@ function validateErrorPayload(
1032
1084
  expectation = null,
1033
1085
  requireUnavailable = false,
1034
1086
  allowedCancellationReasons = new Set(),
1087
+ availableCapabilityIds = [],
1035
1088
  ) {
1036
1089
  if (
1037
1090
  !isPlainJsonObject(error) ||
@@ -1096,7 +1149,11 @@ function validateErrorPayload(
1096
1149
  }
1097
1150
  } else if (
1098
1151
  expectation &&
1099
- (error.kind === "missing-capability" || error.kind === "unknown-operation")
1152
+ (error.kind === "unknown-operation" ||
1153
+ (error.kind === "missing-capability" &&
1154
+ (error.capability_id === expectation.availability_capability_id ||
1155
+ // The environment policy may disable a compiled math backend for this request.
1156
+ (error.capability_id !== "math" && availableCapabilityIds.includes(error.capability_id)))))
1100
1157
  ) {
1101
1158
  throw new MermanInvalidTransportError(
1102
1159
  "Merman transport contradicted its advertised operation catalog.",