Skip to main content

mtlx-core

Parse, validate, package, and transform MaterialX documents. Pure: runs in Node, browsers, and workers alike. Filesystem helpers live in mtlx-core/node; texture processing (which needs sharp) lives in mtlx-core/textures.

Other​

MaterialXReadLimits​

Resource budgets for untrusted XML documents and ZIP archives. Values must be positive safe integers.

Properties​

PropertyType
maxXmlBytesnumber
maxXmlDepthnumber
maxXmlElementsnumber
maxArchiveBytesnumber
maxArchiveEntriesnumber
maxEntryBytesnumber
maxExpandedBytesnumber

DEFAULT_MATERIALX_READ_LIMITS​

const DEFAULT_MATERIALX_READ_LIMITS: Readonly<MaterialXReadLimits>;

Conservative defaults; callers processing trusted larger assets can override individual budgets.


nodeType()​

function nodeType(spec): string | undefined;

Parameters​

ParameterType
specMaterialXNodeSpec

Returns​

string | undefined


getNodeCatalog()​

function getNodeCatalog(document?, registry?): MaterialXNodeSpec[];

Catalog also accepts definitions embedded in the document; source XML remains untouched.

Parameters​

ParameterTypeDefault value
document?MaterialXDocumentundefined
registry?MaterialXNodeSpec[]materialXNodeRegistry

Returns​

MaterialXNodeSpec[]


findNodeSpec()​

function findNodeSpec(element, catalog): MaterialXNodeSpec | undefined;

Parameters​

ParameterType
elementMaterialXElement
catalogMaterialXNodeSpec[]

Returns​

MaterialXNodeSpec | undefined


getNodeGraphScope()​

function getNodeGraphScope(
document,
element,
scope,
spec?
): string | undefined;

Expand only implementations whose contents are present in this document.

Parameters​

ParameterType
documentMaterialXDocument
elementMaterialXElement
scopestring
spec?MaterialXNodeSpec

Returns​

string | undefined


resolveResourcePath()​

function resolveResourcePath(documentPath, value): string;

Parameters​

ParameterType
documentPathstring
valuestring

Returns​

string


relativeResourcePath()​

function relativeResourcePath(documentPath, target): string;

Parameters​

ParameterType
documentPathstring
targetstring

Returns​

string


MaterialXDependencyEdge​

Extends​

  • ResourceReference

Properties​

PropertyTypeDescriptionInherited from
elementMaterialXElement-ResourceReference.element
attributestring-ResourceReference.attribute
valuestring-ResourceReference.value
resolvedValuestringEffective filename after the nearest inherited fileprefix is applied.ResourceReference.resolvedValue
documentPathstring--
targetPathstring--
resourceId?string--

MaterialXResourceGraph​

Properties​

PropertyType
resourcesobject[]
edgesMaterialXDependencyEdge[]

buildResourceGraph()​

function buildResourceGraph(pkg): MaterialXResourceGraph;

A graph snapshot retains original reference values for a single, non-cascading rewrite.

Parameters​

ParameterType
pkgMaterialXPackage

Returns​

MaterialXResourceGraph


cloneMaterialXPackage()​

function cloneMaterialXPackage(pkg): MaterialXPackage;

Parameters​

ParameterType
pkgMaterialXPackage

Returns​

MaterialXPackage


planResourceDestinations()​

function planResourceDestinations(
pkg,
desired,
reserved?
): Map<string, string>;

Allocate a complete mapping, reserving unchanged and incoming names before suffixing.

Parameters​

ParameterType
pkgMaterialXPackage
desired(resource) => string
reserved?Iterable<string>

Returns​

Map<string, string>


applyResourceDestinations()​

function applyResourceDestinations(
pkg,
destinations,
rootPath?
): void;

Apply one original→destination map to every dependency edge, then relocate resources/root.

Parameters​

ParameterTypeDefault value
pkgMaterialXPackageundefined
destinationsReadonlyMap<string, string>undefined
rootPath?stringpkg.rootPath

Returns​

void


DeepReadonly​

type DeepReadonly<T> = { readonly [K in keyof T]: DeepReadonly<T[K]> };

A recursively read-only view, suitable for immutable editor snapshots.

Type Parameters​

Type Parameter
T

ReadonlyMaterialXDocument​

type ReadonlyMaterialXDocument = DeepReadonly<MaterialXDocument>;

MaterialXValueType​

type MaterialXValueType = string;

MaterialXElement​

Properties​

PropertyType
namestring
attributesRecord<string, string>
text?string
childrenMaterialXElement[]

MaterialXInput​

Extends​

  • MaterialXPort

Properties​

PropertyModifierTypeInherited from
namereadonlystringMaterialXPort.name
type?readonlystringMaterialXPort.type
value?readonlystringMaterialXPort.value
attributesreadonlyReadonly<Record<string, string>>MaterialXPort.attributes
nodeName?readonlystring-
output?readonlystring-

MaterialXOutput​

Extends​

  • MaterialXPort

Properties​

PropertyModifierTypeInherited from
namereadonlystringMaterialXPort.name
type?readonlystringMaterialXPort.type
value?readonlystringMaterialXPort.value
attributesreadonlyReadonly<Record<string, string>>MaterialXPort.attributes

MaterialXParameter​

Extends​

  • MaterialXPort

Properties​

PropertyModifierTypeInherited from
namereadonlystringMaterialXPort.name
type?readonlystringMaterialXPort.type
value?readonlystringMaterialXPort.value
attributesreadonlyReadonly<Record<string, string>>MaterialXPort.attributes

MaterialXNode​

Properties​

PropertyModifierType
categoryreadonlystring
name?readonlystring
type?readonlystring
attributesreadonlyReadonly<Record<string, string>>
inputsreadonlyreadonly MaterialXInput[]
outputsreadonlyreadonly MaterialXOutput[]
parametersreadonlyreadonly MaterialXParameter[]

MaterialXNodeGraph​

Properties​

PropertyModifierType
name?readonlystring
attributesreadonlyReadonly<Record<string, string>>
inputsreadonlyreadonly MaterialXInput[]
outputsreadonlyreadonly MaterialXOutput[]
parametersreadonlyreadonly MaterialXParameter[]
nodesreadonlyreadonly MaterialXNode[]

MaterialXNodePortSpec​

Properties​

PropertyTypeDescription
namestring-
type?string-
value?stringLiteral default; absent when the definition uses implicit geometry or a connection.
attributes?Readonly<Record<string, string>>Original definition metadata, including uiname, enum, ranges and defaultgeomprop.

validateMaterialXPackage()​

function validateMaterialXPackage(pkg, options?): MaterialXValidationIssue[];

Checks package dependencies by identity/base path, and document rules in resolved include scope.

Parameters​

ParameterType
pkgMaterialXPackage
options?MaterialXValidationOptions

Returns​

MaterialXValidationIssue[]


MATERIALX_VALIDATION_RULES​

const MATERIALX_VALIDATION_RULES: readonly ["basic", "structure", "types", "resources", "renderer-support", "unused"];

MaterialXValidationRule​

type MaterialXValidationRule = typeof MATERIALX_VALIDATION_RULES[number];

MaterialXValidationOptions​

Properties​

PropertyTypeDescription
registry?MaterialXNodeSpec[]-
rules?readonly ( | "resources" | "basic" | "structure" | "types" | "renderer-support" | "unused")[]Defaults to basic. These checks do not establish full MaterialX conformance.
availableResources?readonly string[]Resolved document-relative resource names, provided by the host.
supportedCategories?readonly string[]Categories explicitly supported by the host renderer; omission reports unassessed.

validateDocument()​

function validateDocument(document, registryOrOptions?): MaterialXValidationIssue[];

Validates selected independent rules. The legacy custom-registry argument remains supported.

Parameters​

ParameterTypeDefault value
documentMaterialXDocumentundefined
registryOrOptions?| MaterialXNodeSpec[] | MaterialXValidationOptionsmaterialXNodeRegistry

Returns​

MaterialXValidationIssue[]


checkMaterialXText()​

function checkMaterialXText(
xml,
location?,
limits?,
options?
): MaterialXValidationIssue[];

Parse failures are reported as issues, rather than thrown.

Parameters​

ParameterTypeDefault value
xmlstringundefined
location?string''
limits?Partial<MaterialXReadLimits>undefined
options?MaterialXValidationOptionsundefined

Returns​

MaterialXValidationIssue[]


createMaterialXDocument()​

function createMaterialXDocument(attributes?, elements?): MaterialXDocument;

Creates a document whose typed views are always derived from its canonical element tree. Edit attributes and elements; typed views are read-only snapshots of the current tree.

Parameters​

ParameterTypeDefault value
attributes?Record<string, string>{}
elements?MaterialXElement[][]

Returns​

MaterialXDocument


cloneMaterialXDocument()​

function cloneMaterialXDocument(document): MaterialXDocument;

Parameters​

ParameterType
documentReadonlyMaterialXDocument

Returns​

MaterialXDocument

Packaging​

MaterialXZipEntry​

One file entry read from a .mtlx.zip archive.

Properties​

PropertyType
pathstring
dataUint8Array

MaterialXZipArchive​

The result of inspectMaterialXZipArchive.

Properties​

PropertyType
entriesMaterialXZipEntry[]
rootEntry?MaterialXZipEntry
issuesMaterialXValidationIssue[]

inspectMaterialXZipArchive()​

function inspectMaterialXZipArchive(data, overrides?): MaterialXZipArchive;

Unzips .mtlx.zip bytes in memory and locates the root .mtlx entry. Works in Node and the browser.

Parameters​

ParameterType
dataUint8Array
overrides?Partial<MaterialXReadLimits>

Returns​

MaterialXZipArchive


createMaterialXZipArchive()​

function createMaterialXZipArchive(entries): Uint8Array;

Builds a DEFLATE-compressed .mtlx.zip archive in memory. No ordering, compression, or alignment constraints.

Parameters​

ParameterType
entriesMaterialXPackageEntry[]

Returns​

Uint8Array


MaterialXFormat​

type MaterialXFormat = "mtlx" | "mtlx.zip";

A MaterialX file format, detected from its file extension.

  • mtlx — a loose XML document with resources referenced by relative path.
  • mtlx.zip — a relaxed, ordinary zip containing a .mtlx document plus resources.

detectFormat()​

function detectFormat(filePath): MaterialXFormat;

Detects the MaterialXFormat of a path from its extension. Anything that is not .mtlx.zip is treated as a loose .mtlx document, except .mtlz, which is rejected: the bespoke .mtlz container format is no longer supported.

Parameters​

ParameterType
filePathstring

Returns​

MaterialXFormat


MaterialXResource​

One resource (texture, library, or other file) referenced by a MaterialX document.

archivePath is the normalized, archive-relative POSIX path (textures/albedo.png) that the document now references; sourcePath is the path it was originally read from.

Properties​

PropertyTypeDescription
id?stringStable identity in a resolved dependency graph.
document?MaterialXDocumentCanonical tree for an included MaterialX document; serialized on output.
archivePathstring-
sourcePathstring-
dataUint8Array-

MaterialXPackage​

A MaterialX document together with every resource it references, held in memory.

This is the unit that transform pipelines operate on and that the Node entry point (mtlx-core/node) reads from and writes to either MaterialXFormat. The document's file references always point at resources[i].archivePath.

Example:

import { loadMaterialXPackage, writeMaterialXPackage } from 'mtlx-core/node';
import { transform } from 'mtlx-core';
import { resizeTextures } from 'mtlx-core/textures';

const pkg = await loadMaterialXPackage('material.mtlx');
await transform(pkg, resizeTextures({ maxImageSize: 1024, targets: [{ format: 'webp' }] }));
await writeMaterialXPackage(pkg, 'material.mtlx.zip');

Properties​

PropertyTypeDescription
rootPathstringArchive-relative path of the root .mtlx document, e.g. material.mtlx.
documentMaterialXDocument-
resourcesMaterialXResource[]-

MaterialXPackageEntry​

A { path, data } pair, the input to createMaterialXZipArchive.

Properties​

PropertyType
pathstring
dataUint8Array

ResourceReader​

type ResourceReader = (relativePath) => Promise<Uint8Array>;

Reads the bytes of a resource referenced by a document, given its normalized root-relative POSIX path. Callers supply this so the library never touches a filesystem itself: the Node entry point wraps fs.readFile, a browser can serve entries from an unzipped archive.

Parameters​

ParameterType
relativePathstring

Returns​

Promise<Uint8Array>


resolveMaterialXResources()​

function resolveMaterialXResources(
document,
readResource,
options?
): Promise<MaterialXResource[]>;

Collects every file referenced by a document and rewrites the references to archive paths.

Walks file/filename/href/uri/source attributes and any type="filename" value, rejects external (http:), absolute, or root-escaping references, reads each unique file via readResource, assigns it an archive path under textures/, libraries/, or resources/, and rewrites the document's attributes in place to those paths.

Example:

const resources = await resolveMaterialXResources(document, (rel) => readFile(path.join(rootDir, rel)));

Parameters​

ParameterType
documentMaterialXDocument
readResourceResourceReader
options?{ rootPath?: string; limits?: Partial<MaterialXReadLimits>; }
options.rootPath?string
options.limits?Partial<MaterialXReadLimits>

Returns​

Promise<MaterialXResource[]>


relocateTextureResources()​

function relocateTextureResources(pkg, libraryPath): void;

Moves every image resource's archive path under libraryPath, rewriting document references to match. Used for loose .mtlx output when --texture-library is given; irrelevant to .mtlx.zip, which retains archive-relative resources. Non-image resources (other .mtlx libraries, misc files) are left where they are.

Parameters​

ParameterType
pkgMaterialXPackage
libraryPathstring

Returns​

void


packageToEntries()​

function packageToEntries(pkg, options?): MaterialXPackageEntry[];

Flattens a package into { path, data } entries, root document first. By default throws on unsafe archive paths so nothing downstream can write outside its target directory — pass { validate: false } only for loose .mtlx output whose resources were deliberately relocated (e.g. via relocateTextureResources) to an absolute or ..-relative disk path, which is not a valid archive path but is a valid write target on a real filesystem.

Parameters​

ParameterType
pkgMaterialXPackage
options?{ validate?: boolean; }
options.validate?boolean

Returns​

MaterialXPackageEntry[]


mergeMaterialXPackages()​

function mergeMaterialXPackages(packages): MaterialXPackage;

Combines multiple packages into one, root document first. Resources are concatenated, renaming (and rewriting references to) any archive path that collides with one already taken. Throws if two inputs share a top-level element name (materials, nodegraphs, etc.), since MaterialX names must be unique within a document and there's no safe way to rename one without also rewriting every reference to it.

A single-package input is returned as-is.

Parameters​

ParameterType
packagesMaterialXPackage[]

Returns​

MaterialXPackage


packageFromArchive()​

function packageFromArchive(archive, options?): MaterialXPackage;

Builds a package from an inspected archive. Accepts the result of inspectMaterialXZipArchive; throws if the archive reported errors or has no root document.

Parameters​

ParameterType
archive{ entries: object[]; rootEntry?: { path: string; data: Uint8Array; }; issues: object[]; }
archive.entriesobject[]
archive.rootEntry?{ path: string; data: Uint8Array; }
archive.rootEntry.pathstring
archive.rootEntry.dataUint8Array
archive.issuesobject[]
options?{ limits?: Partial<MaterialXReadLimits>; }
options.limits?Partial<MaterialXReadLimits>

Returns​

MaterialXPackage

Parsing​

MaterialInfo​

A node's name and category.

Properties​

PropertyType
name?string
categorystring

MaterialXSummary​

The result of summarizeMaterialX.

Properties​

PropertyTypeDescription
pathstring-
version?string-
colorspace?string-
nodeGraphCountnumber-
topLevelNodeCountnumber-
nodeCategoriesstring[]-
materialsMaterialInfo[]-
referencedTexturesstring[]-
nodesMaterialInfo[]Actual nodes from every graph depth, excluding graph containers, ports, and metadata.

summarizeMaterialX()​

function summarizeMaterialX(path, document): MaterialXSummary;

Summarizes a parsed document: version, colorspace, materials, referenced textures, and nodes. Powers the CLI's info command and the VS Code extension's stats panel.

Example:

const summary = summarizeMaterialX('material.mtlx', document);
console.log(summary.materials.map((material) => material.name));

Parameters​

ParameterType
pathstring
documentMaterialXDocument

Returns​

MaterialXSummary


MaterialXDocument​

The in-memory form of a .mtlx file, mirroring its XML structure.

nodes and nodeGraphs are derived read-only snapshots; elements is the canonical tree that serializeMaterialX writes back out.

Properties​

PropertyModifierType
attributespublicRecord<string, string>
nodesreadonlyreadonly MaterialXNode[]
nodeGraphsreadonlyreadonly MaterialXNodeGraph[]
elementspublicMaterialXElement[]

parseMaterialX()​

function parseMaterialX(xml, limits?): MaterialXDocument;

Parses MaterialX XML text into a MaterialXDocument.

Preserves ordered elements, explicit attributes, text and comments semantically. Source whitespace, quote style and XML declarations are not preserved byte-for-byte. Throws with line and column on malformed XML, a missing <materialx> root, or comments outside that root.

Example:

const document = parseMaterialX(await readFile('material.mtlx', 'utf8'));
console.log(document.attributes.version, document.nodeGraphs.length);

Reference:

Parameters​

ParameterType
xmlstring
limits?Partial<MaterialXReadLimits>

Returns​

MaterialXDocument


serializeMaterialX()​

function serializeMaterialX(document): string;

Serializes a MaterialXDocument back to XML text. The inverse of parseMaterialX; a parse → serialize → parse round trip yields the same document.

Parameters​

ParameterType
documentReadonlyMaterialXDocument

Returns​

string

Transforms​

Transform​

type Transform = (pkg) => void | Promise<void>;

A step in a transform pipeline. Transforms mutate the package in place and may be async. Functions that take options return a Transform, so they read as a declarative list:

await transform(pkg, resizeTextures({ maxImageSize: 2048 }), myCustomTransform);

Parameters​

ParameterType
pkgMaterialXPackage

Returns​

void | Promise<void>


transform()​

function transform(pkg, ...transforms): Promise<MaterialXPackage>;

Applies transforms to a package in order, awaiting each one. Returns the same package for chaining.

Parameters​

ParameterType
pkgMaterialXPackage
...transformsTransform[]

Returns​

Promise<MaterialXPackage>


rewriteResourcePath()​

function rewriteResourcePath(
document,
from,
to
): number;

Rewrites resource-reference attributes equal to from, returning how many were changed. Use this when a transform renames a resource (e.g. textures/a.png → textures/a.webp).

Parameters​

ParameterType
documentMaterialXDocument
fromstring
tostring

Returns​

number

Validation​

MaterialXAsset​

One file that makes up a material: the root document, a texture, or a nested document.

Properties​

PropertyTypeDescription
pathstringRelative to the root document's directory; for archives, the entry path.
bytes?numberUncompressed size; undefined when the resource could not be read.

MaterialXInspection​

Results of every available rule, with explicit resource coverage.

Properties​

PropertyTypeDescription
issuesMaterialXValidationIssue[]-
summary?MaterialXSummary-
parseError?string-
resourcesCheckedboolean-
assetsMaterialXAsset[]Root document first, then every dependency that was attempted.
totalBytesnumberSum of every readable asset.
resourcePathsstring[]All attempted paths, including missing files, relative to the root document's directory.
resourcesMaterialXResource[]Successfully read loose resources; hosts may reuse their bytes for rendering.

inspectMaterialX()​

function inspectMaterialX(
raw,
fileName,
options?
): Promise<MaterialXInspection>;

Inspects XML or ZIP bytes using all validation rules. A host reader enables recursive loose dependency checks without mutating source bytes; archives use their own inventory. Reader failures are collected so one missing file does not hide other issues. The host must bound each read; this function also bounds dependency count and total retained bytes.

Parameters​

ParameterType
rawUint8Array
fileNamestring
options?{ readResource?: ResourceReader; supportedCategories?: readonly string[]; }
options.readResource?ResourceReader
options.supportedCategories?readonly string[]

Returns​

Promise<MaterialXInspection>


checkMaterialXZipArchive()​

function checkMaterialXZipArchive(
data,
limits?,
validation?
): MaterialXValidationIssue[];

Inspects .mtlx.zip bytes and validates the root document it contains.

Parameters​

ParameterType
dataUint8Array
limits?Partial<MaterialXReadLimits>
validation?MaterialXValidationOptions

Returns​

MaterialXValidationIssue[]


materialXNodeRegistry​

const materialXNodeRegistry: MaterialXNodeSpec[];

Every node category validateDocument recognizes: the standard library generated from the MaterialX node definitions plus a few built-in structural elements.


MaterialXNodeSpec​

A node definition entry in the materialXNodeRegistry.

Properties​

PropertyType
categorystring
nodeDefName?string
type?string
nodeGroup?string
attributes?Readonly<Record<string, string>>
inputsMaterialXNodePortSpec[]
outputsMaterialXNodePortSpec[]
parametersMaterialXNodePortSpec[]

MaterialXValidationIssue​

One finding from validation. Errors make a file unusable; warnings are advisory.

Properties​

PropertyTypeDescription
graph?objectOptional graph coordinates for highlighting nodes and connections in a UI.
graph.scopestringSlash-separated nodegraph path; empty for the document scope.
graph.containers?object[]All enclosing graph containers and compound instances affected by this finding.
graph.nodeIdsstring[]-
graph.input?string-
graph.source?string-
graph.output?string-
code?stringStable machine-readable identifier when supplied by the producing rule.
rule?string-
level"error" | "warning"-
messagestring-
locationstring-