Skip to content

YuzeScript ​

What is YuzeScript? ​

YuzeScript is a JavaScript-based scripting language for writing custom logic in Yuze. It runs on the V8 engine and supports modern JavaScript features including async/await.

YuzeScript is used in:

  • Workflow steps: Process and transform datapoints with custom logic
  • Schema Mapping Expressions: Calculate field values during data transformation
  • API Connectors: Handle incoming HTTP requests and produce datapoints

The editor provides IntelliSense with type definitions based on your schemas, making it easier to write correct code.

YuzeScript in Workflow Steps ​

In a workflow step, YuzeScript lets you write custom processing logic.

Available globals: context (consume/produce/workflowStep/vars), yuze (master data helpers), and console (logging).

source, target, and request are not available here. There is no HTTP client or fetch — outbound API calls are handled by connectors, not workflow scripts.

context.consume ​

Retrieves all datapoints from the consumed feed. Takes no arguments, returns an array matching the input feed schema.

javascript
const datapoints = await context.consume();

for (const dp of datapoints) {
  console.log(dp.EquipmentId);
}

context.produce ​

Writes datapoints to the produced feed. Accepts a single object or an array.

javascript
await context.produce({
  EquipmentId: 'PUMP-001',
  Status: 'Active'
});

// Or multiple datapoints
await context.produce([
  { EquipmentId: 'PUMP-001', Status: 'Active' },
  { EquipmentId: 'PUMP-002', Status: 'Inactive' }
]);

Producing master data ​

When the step is set to produce master data, each produced object becomes a master data item of the type named in its Identifier. DisplayName and Identifier are required, ParentId is optional, and MappingIdentifiers adds mapping identifiers per source system. Every other field is stored on the item.

javascript
await context.produce({
  Identifier: 'master-data:Equipment:PUMP-001',
  DisplayName: 'Main pump',
  ParentId: 'master-data:Location:PLANT-A',
  MappingIdentifiers: { SAP: ['10001234'], Maximo: ['A-1'] },
  SerialNumber: 'SN-12345'
});

Mapping identifiers are only added, never removed. To delete items, use the yuze master data helpers instead.

context.workflowStep ​

Identifies the current workflow step instance. Useful for logging or conditional logic.

javascript
console.log(context.workflowStep.Id);    // UUID string
console.log(context.workflowStep.Name);  // Workflow step name

TIP

context.yuzecase is a legacy alias for context.workflowStep and still works, but prefer context.workflowStep in new scripts.

context.vars ​

Reads variables defined on the workflow (see the workflow Settings tab). Reference a variable by name as context.vars.<name>. A name that isn't defined reads as undefined.

javascript
console.log('Reporting year: ' + context.vars.YEAR);

await context.produce({
  EquipmentId: 'PUMP-001',
  Year: context.vars.YEAR
});

TIP

The same variables can also be used in non-script settings via the double-curly-brace token form. Inside YuzeScript, use context.vars.YEAR instead — it's valid code the editor understands.

Complete Workflow Step Example ​

javascript
const datapoints = await context.consume();

const results = datapoints.map(dp => ({
  ...dp,
  processed: true,
  processedAt: new Date().toISOString()
}));

await context.produce(results);

Enriching with Master Data ​

When looking up master data for each item, use a for loop instead of .map() because each iteration requires await:

javascript
const items = await context.consume();
const enriched = [];
for (const item of items) {
  const ref = await yuze.createExternalMasterDataItemReference('Equipment', 'SAP', item.EquipmentId);
  const equipment = await yuze.lookupMasterDataItem(ref);
  enriched.push({
    ...item,
    EquipmentName: equipment?.displayName || 'Unknown'
  });
}
await context.produce(enriched);

Testing a Workflow Step Script ​

The YuzeScript workflow step has a second editor, Tests, next to the expression. Write Jest-style tests there, run them with the play button next to the editor, and read the results underneath it. The tests must pass before the step can be saved: saving with a failing test is refused with the failing test names.

Tests run on the server in the same engine as the step, but never against real data. Every yuze.* function that reads or writes master data or datapoints — lookupMasterDataItem, lookupMasterDataItemSystemKey, searchMasterDataItems, searchDataPoints, saveMasterDataItem, deleteMasterDataItem, saveMasterDataHierarchy, ensureMasterDataType, lake.createTable, lake.table(name).load and lake.table(name).clear — throws unless the test supplies it through runStep({ yuze: ... }). The error names the function and shows the replacement. Only xml, sha256Hash, crypto.uuidv4 and the two reference builders work unreplaced, because they read no stored data.

runStep ​

runStep(options) runs the expression once and returns the datapoints it produced. Every option is optional.

javascript
const produced = await runStep({
  consume: [{ EquipmentId: 'PUMP-001', Status: 'Active' }], // what context.consume() returns
  vars: { YEAR: '2026' },                                  // what context.vars holds
  workflowStep: { Id: 'step-1', Name: 'Enrich equipment' }, // what context.workflowStep holds
  yuze: {                                                  // replacements for yuze.* functions
    lookupMasterDataItem: async (reference) => ({ displayName: 'Main pump' }),
    saveMasterDataItem: async (item) => { saved.push(item); },
  },
});

Produced items come back the way the next step in the workflow sees them: fields with a null or undefined value are dropped.

Test structure ​

describe, it (or test), beforeAll, afterAll, beforeEach and afterEach work as in Jest. it.skip and describe.skip skip; it.only and describe.only run only the marked tests.

javascript
describe('equipment enrichment', () => {
  it('adds the equipment name from master data', async () => {
    const produced = await runStep({
      consume: [{ EquipmentId: 'PUMP-001' }],
      yuze: { lookupMasterDataItem: async () => ({ displayName: 'Main pump' }) },
    });

    expect(produced).toEqual([{ EquipmentId: 'PUMP-001', EquipmentName: 'Main pump' }]);
  });

  it('falls back to Unknown when the item is missing', async () => {
    const produced = await runStep({
      consume: [{ EquipmentId: 'GHOST' }],
      yuze: { lookupMasterDataItem: async () => null },
    });

    expect(produced[0].EquipmentName).toBe('Unknown');
  });
});

Matchers ​

expect(value) supports toBe, toEqual, toStrictEqual, toBeTruthy, toBeFalsy, toBeNull, toBeUndefined, toBeDefined, toBeNaN, toBeInstanceOf, toBeGreaterThan, toBeGreaterThanOrEqual, toBeLessThan, toBeLessThanOrEqual, toBeCloseTo, toHaveLength, toContain, toContainEqual, toHaveProperty, toMatch, toMatchObject and toThrow. Prefix a matcher with .not to negate it. Use await expect(promise).resolves.<matcher>() and await expect(promise).rejects.toThrow() for promises, including runStep() itself.

To check only part of a value, put expect.anything(), expect.any(String), expect.objectContaining({...}), expect.arrayContaining([...]), expect.stringContaining('...') or expect.stringMatching(/.../) where you would write the expected value, e.g. expect(produced).toEqual([expect.objectContaining({ EquipmentId: 'PUMP-001' })]).

console.log output from the test and from the step is captured per test and shown with the result.

YuzeScript in Schema Mappings ​

In schema mapping expressions, YuzeScript calculates field values during data transformation. You work with source (input data) and assign values to target fields.

Available globals: source (read-only input), target (writable output), yuze (master data helpers), and console (logging).

context and request are not available here. Only explicitly mapped fields assigned to target appear in the output.

source ​

The input data being transformed. Contains all fields from the source schema (read-only).

javascript
console.log(source.FirstName);  // 'John'
console.log(source.LastName);   // 'Doe'
console.log(source.Address.City);

target ​

The output data structure. Assign values to target properties to set the output fields.

javascript
target.FullName = source.FirstName + ' ' + source.LastName;
target.ProcessedAt = new Date().toISOString();

Complete Schema Mapping Example ​

javascript
target.FullName = source.FirstName + ' ' + source.LastName;
target.Address = [source.Street, source.City, source.Country].filter(Boolean).join(', ');
target.Priority = source.Severity > 7 ? 'High' : 'Low';

Testing a Schema Mapping Expression ​

Each Expression task has a Tests editor next to the expression. The tests work like those of a workflow step (see Testing a Workflow Step Script for the test structure and matchers), run with the play button, and must pass before the mapping can be saved. Saving with a failing test is refused with the task and the failing test names.

runMapping(options) runs the expression once and returns target. Both options are optional: source is what the expression reads as source, and yuze replaces yuze.* functions for the run, as with runStep.

javascript
it('joins the names', async () => {
  const target = await runMapping({ source: { FirstName: 'John', LastName: 'Doe' } });

  expect(target.FullName).toBe('John Doe');
});

YuzeScript in API Connectors ​

API connectors use YuzeScript to handle incoming HTTP requests and produce datapoints.

Available globals: request (incoming HTTP request), context.produce() (write datapoints), yuze (master data helpers), and console (logging).

context.consume(), source, and target are not available here.

request ​

The incoming HTTP request object:

  • request.method — HTTP method ('POST', 'GET', etc.)
  • request.headers — Object with header names as keys
  • request.query — Query parameters from the URL
  • request.path — URL path after connector base URL
  • request.body — Parsed body. JSON is parsed natively. XML is auto-converted to JSON: all values become strings, single child elements are objects (not arrays), attributes become @name, text content becomes #text. Empty when the body was empty or could not be parsed.
  • request.bodyRaw — Raw unparsed body string. Use when you need the exact original text or when the auto-converted JSON shape is not suitable.
  • request.bodyParseError — A description of why the body could not be parsed, or empty when it was parsed successfully.
javascript
console.log(request.method);              // 'POST'
console.log(request.headers['content-type']);
console.log(request.query.status);        // query parameter
console.log(request.path);                // URL path after connector base URL
console.log(request.body);                // parsed body (JSON or XML-to-JSON)
console.log(request.bodyRaw);            // raw unparsed body string
console.log(request.bodyParseError);     // why parsing failed, if it did

WARNING

When the body cannot be parsed, request.body is empty rather than the raw text. Check request.bodyParseError before reading fields from the body — otherwise a sender with a broken payload gets a success response while nothing is processed.

javascript
if (request.bodyParseError) {
  return { status: 400, body: { error: request.bodyParseError } };
}

response (Return Value) ​

Return an object { status, body?, headers? } to define the HTTP response.

javascript
return {
  status: 200,
  body: { success: true }
};

// Error response
return {
  status: 400,
  body: { error: 'Invalid request' }
};

// With custom response headers
return {
  status: 200,
  body: { ok: true },
  headers: { 'X-Request-Id': request.headers['x-request-id'] || 'none' }
};

context.produce (API Connector) ​

Writes datapoints to the configured feed.

javascript
await context.produce(request.body);

Complete API Connector Example ​

javascript
await context.produce(request.body);

return {
  status: 200,
  body: { success: true }
};

Testing an API Connector Script ​

The API connector script has a Tests editor next to the script. The tests work like those of a workflow step (see Testing a Workflow Step Script for the test structure and matchers), run with the play button, and must pass before the connector can be saved. Saving with a failing test is refused with the failing test names.

runRequest(options) runs the script once and returns { response, produced }: the object the script returned and the datapoints it passed to context.produce(). Every option is optional.

javascript
const { response, produced } = await runRequest({
  method: 'POST',                         // request.method, defaults to 'POST'
  path: 'orders',                         // request.path, defaults to ''
  headers: { 'content-type': 'application/json' },
  query: { source: 'SAP' },
  body: { orderId: 'A-1' },               // request.body; request.bodyRaw defaults to it as JSON
  yuze: { lookupMasterDataItem: async () => null },
});

expect(response.status).toBe(200);
expect(produced).toEqual([{ orderId: 'A-1' }]);

To test a body that could not be parsed, pass body: null with the bodyRaw and bodyParseError the script should see.

Documenting an API Connector Script ​

The API connector script also has an OpenAPI editor, next to Script and Tests. It holds the description of the API your script answers: the paths and methods it handles, what callers send and what they get back. This description is what Open documentation shows for the Hosted API.

To write it, open the editor in full screen and click the sparkle button at the top of the AI assistant. The assistant reads your script, writes the description, and offers to replace the OpenAPI editor's content with it. When you later change the script, ask the assistant to update the description too.

TIP

You don't need to add addresses or sign-in details to the description. The platform fills in the Hosted API's own URLs and the ways to sign in.

WARNING

Saving is refused when the description is not a valid OpenAPI document. The message says what is wrong. Without a description, the documentation lists no endpoints.

YuzeScript in Hosted API Response Scripts ​

A Hosted API can run a script on the JSON or text response of each endpoint before it reaches the caller. Use it to add a value looked up from master data, rename fields, or leave fields out. Add the script on the Endpoints tab of the Hosted API (see Response scripts).

Available globals: response (the parsed JSON response, or the text), yuze (master data helpers), and console (logging).

The script can only read data: functions that save or delete master data, or create, load, alter or clear lake tables, fail the call. A script that runs longer than 30 seconds is stopped and fails the call.

context, request, source, and target are not available here.

response ​

The JSON response of the endpoint: an object or an array, with the field names as the endpoint sends them. When the endpoint declares its response type, the editor suggests the fields as you type. When the endpoint returns text, response is that text; returning text keeps the response text, and returning an object or an array turns it into JSON.

The caller gets what the script returns, so always end with a return: change response and return it, or return a new value. A script that returns nothing or null fails the call.

javascript
// Add a property
const hazard = await yuze.lookupMasterDataItem(`master-data:Hazard:${response.name}`);
response.hazard = hazard?.displayName;
return response;
javascript
// Return a new value
return { name: response.name, hazard: response.hazardCode };

Arrays ​

When the endpoint returns a list, the script gets the whole list, so look up a value for each item:

javascript
for (const item of response) {
  const hazard = await yuze.lookupMasterDataItem(`master-data:Hazard:${item.name}`);
  item.hazard = hazard?.displayName;
}
return response;

WARNING

yuze.lookupMasterDataItem returns null when the item doesn't exist. Use ?. as above: a script that throws gives the caller an error (500) instead of the response.

Error responses, and responses that aren't JSON, don't reach the script. With JSON → XML on the endpoint, the result of the script is converted to XML.

Testing a Hosted API Response Script ​

The response script dialog has a Tests tab next to the script. The tests work like those of a workflow step (see Testing a Workflow Step Script for the test structure and matchers), run with the play button, and must pass before the Hosted API can be saved. Saving with a failing test is refused with the endpoint and the failing test names.

runResponse(options) runs the script once and returns what it returns. response is the JSON response the script gets, and yuze replaces yuze.* functions for the run, as with runStep. A script that returns nothing fails the test.

javascript
it('adds the hazard', async () => {
  const result = await runResponse({
    response: { name: 'Lead' },
    yuze: { lookupMasterDataItem: async () => ({ displayName: 'Toxic' }) },
  });

  expect(result).toEqual({ name: 'Lead', hazard: 'Toxic' });
});

Built-in Functions ​

The yuze object provides helper functions available in all contexts.

yuze.createExternalMasterDataItemReference ​

Creates a reference to a master data item from an external system.

javascript
const ref = await yuze.createExternalMasterDataItemReference(
  'Equipment',  // type
  'SAP',        // source system
  'PUMP-001'    // source ID
);
// Returns: 'master-data-ext:Equipment:SAP:PUMP-001'

yuze.createInternalMasterDataItemReference ​

Creates a reference to an internally managed master data item.

javascript
const ref = await yuze.createInternalMasterDataItemReference(
  'Location',   // type
  'SITE-A'      // ID
);
// Returns: 'master-data:Location:SITE-A'

yuze.lookupMasterDataItem ​

Retrieves a master data item by its identifier. Returns null if not found.

javascript
const item = await yuze.lookupMasterDataItem('master-data:Equipment:PUMP-001');

if (item) {
  console.log(item.displayName);
  console.log(item.properties.Status);
  console.log(item.mappingIdentifiers.SAP[0]);
}

yuze.searchMasterDataItems ​

Searches for master data items with filters. Returns paginated results with a continue token for fetching additional pages.

Parameters:

  • query: Search criteria
    • type: Master data type to search
    • onlyRootItems: (optional) Filter to only root items
    • metadata: (optional) Filter by metadata field values
  • pagination: Pagination options
    • pageSize: Number of items per page
    • nextPageToken: (optional) Token from previous result for next page

Returns: CursorPagingResult<MasterDataItem>

  • items: Array of matching master data items
  • nextPageToken: Token for fetching the next page (undefined if no more pages)

Basic Example ​

javascript
const result = await yuze.searchMasterDataItems(
  {
    type: 'Equipment',
    onlyRootItems: true,
    metadata: { Status: 'Active' }
  },
  { pageSize: 50 }
);

for (const item of result.items) {
  console.log(item.displayName);
}

Paginating Through All Results ​

Use a do-while loop to fetch all pages using the nextPageToken:

javascript
let nextPageToken = undefined;

do {
  const result = await yuze.searchMasterDataItems(
    {
      type: 'Equipment',
      metadata: { Status: 'Active' }
    },
    {
      pageSize: 100,
      nextPageToken: nextPageToken
    }
  );

  for (const item of result.items) {
    console.log(`Processing: ${item.displayName}`);
  }

  nextPageToken = result.nextPageToken;
} while (nextPageToken);

yuze.lookupMasterDataItemSystemKey ​

Gets the external system identifier for a master data item.

javascript
const sapId = await yuze.lookupMasterDataItemSystemKey(
  'master-data:Equipment:PUMP-001',
  'SAP'
);
// Returns: 'SAP-PUMP-001' or null

yuze.saveMasterDataItem ​

Creates or updates a master data item.

javascript
await yuze.saveMasterDataItem({
  identifier: 'master-data-ext:Equipment:SAP:PUMP-001',
  displayName: 'Main Cooling Pump',
  parentId: 'master-data:Location:PLANT-A',
  properties: {
    SerialNumber: 'SN-12345',
    Status: 'Active'
  },
  mappingIdentifiers: {
    SAP: ['10001234']
  }
});

yuze.deleteMasterDataItem ​

Deletes a master data item by its identifier. Children of the item are not deleted — they are left without a parent.

javascript
await yuze.deleteMasterDataItem('master-data:Equipment:PUMP-001');

yuze.saveMasterDataHierarchy ​

Saves one or more complete master data trees in a single call, keeping stored data in step with the source system that owns them. The items you pass are authoritative for the trees they describe: each item is created or updated as needed, and any item already stored under one of those trees that is not in your payload is removed. Use this when a source owns a whole hierarchy and you want the stored data to match its latest payload exactly — instead of dropping and re-creating the tree.

Pass the flat list of items (parent links are carried on each item via parentId, the same item shape as yuze.saveMasterDataItem above) plus an options object:

javascript
const result = await yuze.saveMasterDataHierarchy(
  [
    { identifier: 'master-data:Location:PLANT-A', displayName: 'Plant A' },
    {
      identifier: 'master-data:Location:LINE-1',
      displayName: 'Assembly Line 1',
      parentId: 'master-data:Location:PLANT-A'
    },
    {
      identifier: 'master-data:Location:CELL-1',
      displayName: 'Cell 1',
      parentId: 'master-data:Location:LINE-1'
    }
  ],
  { onMissing: { strategy: 'delete' } }
);

console.log(result); // { Inserted, Updated, Unchanged, Deleted, Unlinked, Archived }

Rules for the items you pass — the call fails, and saves nothing, when one is broken:

  • Every parentId must point to an item in the same call. A parent that is already stored but not in your payload doesn't count: send whole trees, starting from the root.
  • All items must be of one master data type, and each identifier may appear only once. A parent chain that loops back on itself is rejected.
  • If the master data type's schema has key fields, the key in each identifier must be those fields' values. Otherwise the key is whatever follows the type in the identifier, used as-is.
  • If the type has a schema, each item must fill every field the schema marks as required, including items that only exist to hold the tree together, such as the root.

Options:

  • onMissing — what to do with items still stored under a tree but missing from your payload. Pass an object { strategy, property }. Supported strategies:
    • 'delete' (default) — remove them, so stored data matches the source.
    • 'unlink' — keep them, detaching the removed branch from its parent so it survives as its own tree.
    • 'archive' — keep them exactly where they are and stamp the current timestamp into a metadata property so you can recognise them as archived. The property name is set via property (defaults to 'ArchivedAt'). Already-archived items keep their original timestamp — re-running the sync does not move it or re-archive them.
javascript
// Archive missing items into a custom property instead of deleting them
const result = await yuze.saveMasterDataHierarchy(
  items,
  { onMissing: { strategy: 'archive', property: 'RetiredOn' } }
);

Only items that actually changed are updated; unchanged items are left as-is. When anything inside a tree changes, its ancestors up to the root are marked as changed as well, so Incremental Sync re-syncs only the affected hierarchies rather than the entire dataset.

Choosing the archive property

The property you archive into is yours to choose, because "archived" means different things to different sources — some flag a status field, others stamp a retirement date. If you don't pass property, the timestamp lands in ArchivedAt. Reserved properties (DisplayName, Identifier, ParentId) can't be used.

Re-sending an archived item un-archives it

If an archived item later reappears in your payload, it is treated as a normal update and the archive marker is cleared — the item is live again. You don't need a separate "un-archive" step: sending the item back is the signal. (The marker is only cleared if your payload doesn't itself carry that property; whatever you send for it wins.)

Authority is per tree, not across trees

Removal only applies to the trees you actually send: items missing from a tree you send are removed, but a whole hierarchy you simply stop sending is left untouched — there is no signal to distinguish "deliberately removed" from "not included in this run." Decide per workflow how entire hierarchies get retired; the save can't infer it.

yuze.ensureMasterDataType ​

Makes sure a master data type exists, creating it when it is missing. Pass a schemaVersionId to bind the type to a schema, so every item saved to it is checked against that schema; leave it out for a type whose items are free-form.

javascript
await yuze.ensureMasterDataType('Pump', {
  displayName: 'Pumps',                          // optional, only used when the type is created
  schemaVersionId: 'schema-version:pumps:1.0'    // optional
});
  • An existing type is left as it is, so the call is safe to repeat on every run.
  • The call fails when the type already exists bound to a different schema (or to none, when you pass one). It never changes an existing type's schema.
  • The schema must exist and have an Identifier and a DisplayName field.

Saving an item of an unknown type with yuze.saveMasterDataItem still creates that type, but without a schema. Call yuze.ensureMasterDataType first when the type should have one.

yuze.lake.createTable ​

Creates a table in the customer's data lake. Available only when the data lake is turned on for the customer, and only in workflow steps.

javascript
const { created } = await yuze.lake.createTable('incidents', {
  description: 'Incidents from the EHS system',   // optional
  columns: [
    { name: 'ID', type: 'BIGINT', nullable: false, description: "The incident's id in the EHS system" },
    { name: 'TITLE', type: 'VARCHAR' },
    { name: 'AMOUNT', type: 'DECIMAL(18,4)' },
    { name: 'OPENED_AT', type: 'TIMESTAMPTZ' }
  ],
  key: ['ID'],         // optional
  ifNotExists: true   // optional, true by default
});
// created: true when this call made the table, false when it was already there
  • Table names use up to 63 lowercase letters, digits and _, starting with a letter.
  • Column names use up to 63 letters, digits and _, not starting with a digit. Their case is kept, so a table can carry the column names of the system it is loaded into. Two columns can't differ only in case.
  • Column types: VARCHAR, BOOLEAN, INTEGER, BIGINT, DOUBLE, DATE, TIMESTAMP, TIMESTAMPTZ, TIMESTAMP_NS (nanoseconds, as pandas writes them), TIME, UUID, BLOB (bytes, such as a SQL Server rowversion) or DECIMAL(precision,scale) with a precision up to 38.
    • A BLOB column loads only from a Parquet binary column, never from text. A table with one can't be read row by row: read it with Read lake table as files or Read lake table changes as files. Files keep the column binary and are much faster than rows.
    • Snowflake reads a Parquet binary column as text unless told otherwise. Load these files with FILE_FORMAT = (TYPE = PARQUET BINARY_AS_TEXT = FALSE) into a BINARY column. Text columns still load as text.
  • nullable is optional and true by default. With nullable: false, writing a row without a value for the column fails.
  • description is optional, on the table and on each column. A blank description counts as none.
  • key is optional and lists the columns that identify a row, e.g. ['ID'] or ['SITE', 'ID']. Key columns refuse rows without a value, whatever their nullable says. A merge load keeps one row per key, so a table it loads needs a key. A table with a key can't be loaded with append, so it never holds a key on more than one row.
  • With ifNotExists on, a table with the same name is left as it is, whatever its columns, key and descriptions, so the call is safe to repeat on every run. As with SQL's CREATE TABLE IF NOT EXISTS, only the name is compared. With ifNotExists: false, the call fails when the table exists.
  • The call never changes an existing table. Add columns with alter. A different key or a changed column needs a table with another name.
  • Two runs creating the same table at once both succeed: one creates it, the other finds it.
  • Every table also gets columns of its own. Four say which landed file each row came from: _yuze_file (the folder and the file name, e.g. ehs/incident:incidents.parquet), _yuze_file_version, _yuze_file_hash and _yuze_landed_at. _yuze_deleted is true on a row a merge marked deleted and false otherwise. Your own column names can't start with _yuze_.

yuze.lake.table(name).load ​

Loads the files landed in a landing folder into a table made with yuze.lake.createTable. Each run loads only the files the table hasn't loaded yet, so the call is safe to repeat on every run. Available only when the data lake is turned on for the customer, and only in workflow steps.

javascript
const incidents = yuze.lake.table('incidents');

const result = await incidents.load({
  read: {
    folder: 'ehs/incident',
    parquet: {}
  },
  mode: 'append'
});
// result: { version, files, inserted, replaced, deleted }

// Keep one row per key, the latest by CHANGED_AT:
await yuze.lake.table('incidents_current').load({
  read: { folder: 'ehs/incident', parquet: {} },
  mode: 'merge',
  order: 'CHANGED_AT'
});

// The same, where the files mark a deleted record with OP = 'D':
await yuze.lake.table('incidents_current').load({
  read: { folder: 'ehs/incident', parquet: {} },
  mode: 'merge',
  order: 'CHANGED_AT',
  deletes: { when: { column: 'OP', equals: 'D' }, action: 'mark' }   // or action: 'remove'
});
  • read.folder is the landing folder to read. Subfolders aren't read. When a file has landed in several versions since the last load, only the latest is loaded.

  • parquet: {} names the files' format. Parquet is the only format a load reads for now, and it takes no options.

  • mode decides what happens to rows already in the table:

ModeWhat it doesUse it when
appendAdds every row read. A file's earlier versions keep their rows. A table with a key refuses it.The table has no key, and every file is new and never changes, such as daily exports with the date in their name
mergeKeeps one row per key of the table: a row read replaces the table's row with the same key, and a new key is added. The table needs a key, set when it was created.The files hold changes to records, and the table should hold each record's latest state
  • The key comes from the table, not the load. Every row read needs a value in each key column, or the load fails.

  • order (merge only, optional) names the table column that orders a key's changes, such as a change timestamp. When the files hold several rows for one key, the one with the highest order value wins. A row read never replaces a table row with a higher order value, so a change that arrives late doesn't undo a newer one. Rows with the same order value, or no order, are decided by landing: the latest landed file wins, and within a file the last row.

  • deletes (merge only, optional) says which rows read are deletes: those whose when.column equals when.equals (text, a number, or true/false, e.g. { column: 'Op', equals: 'D' } or { column: '_fivetran_deleted', equals: true }). The column must be one of the table's. A delete competes with the key's other rows by order like any change, and only a delete that wins acts on its key:

    • action: 'mark' keeps the key's row with the delete row's values and sets _yuze_deleted to true. A later change to the key brings it back with _yuze_deleted false. A change older than the delete doesn't undo it, so use mark when changes can arrive out of order. The delete row's values are written, so a source that sends only the key on a delete needs every other column nullable, or remove.
    • action: 'remove' removes the key's row; a delete for a key the table doesn't have changes nothing. Nothing remembers the delete, so a change older than it that arrives later adds the key again.
  • The result tells you the table version the load made (version), the files it loaded (files), the rows it added (inserted), the table rows a merge replaced (replaced), a merged key's earlier row, and the keys a merge marked deleted or removed (deleted). A marked row also counts as added; a removed one doesn't. When there was nothing new, files is 0 and nothing is written.

  • Columns are matched by name, ignoring case and order, and each value is converted to its column's type. A file without a column the table has loads it empty, so a source can drop a column. A file without a column that refuses nulls, such as a key column, or without a merge's order or deletes column, fails the load. A merge replaces each key's whole row, so when a source renames or drops a column, the merged rows lose that column's values. Columns in the files that the table doesn't have are left out, unless extraColumns says otherwise.

  • extraColumns (optional) decides what a column in the files that the table doesn't have does. 'ignore', the default, leaves it out and loads the rest. 'error' fails the load and names the file and the column, so a source that starts sending a new column doesn't go unnoticed. Nothing is loaded.

  • A column whose type in a file doesn't match the table fails the whole load, so a source that changes a column's type doesn't go unnoticed. A type that holds every value without loss is accepted, such as a whole number into a BIGINT or DECIMAL column, or a date into a TIMESTAMP column. Anything else, such as text into a number column or a number into a VARCHAR column, fails. The message names the file, the column and both types. Nothing is loaded.

  • A value that doesn't fit its column fails the whole load too, such as a date too far in the future for a TIMESTAMP column. The message names the file, the column and how many values don't fit, but never a value. Nothing is loaded.

  • An empty file counts as loaded and adds no rows.

  • Two runs loading the same table at once take turns: the second loads only what the first left.

WARNING

With append, a changed file adds its new rows next to its old ones. When a source can send a record again, use merge on a table with a key. A merge keeps rows that a file's new version no longer has. When a source resends whole files as the full current data, call clear and then load again.

yuze.lake.table(name).alter ​

Adds columns to a table made with yuze.lake.createTable, for example when a source's files gain a column. Available only when the data lake is turned on for the customer, and only in workflow steps.

javascript
const { version, added } = await yuze.lake.table('incidents').alter({
  addColumns: [
    { name: 'SITE', type: 'VARCHAR', description: 'The site the incident happened at' },
    { name: 'COST', type: 'DECIMAL(18,2)' },
  ],
});
// version: the table version the change made; added: the columns that were new, e.g. ['SITE']
  • New columns go after the table's other columns. Rows the table already has hold no value in them. Loads fill them from the files that have them and leave them empty for files that don't, such as files landed before the change.
  • A column the table already has with the same type and description is left as it is, so a script can ask for the same columns on every run. added lists only the new ones.
  • Added columns take nulls: nullable: false is refused, because the rows the table has would have no value.
  • A column the table has with another type or description is refused. A column's type can't be changed, and columns can't be dropped or renamed.
  • No data is rewritten. Reading a table version from before the change gives the columns it had then.
  • alter waits for a load or clear of the same table to finish.

yuze.lake.table(name).clear ​

Empties a table made with yuze.lake.createTable and forgets which files it loaded. The next load reads the latest version of every file in its folder again, so a clear followed by a load rebuilds the table. Available only when the data lake is turned on for the customer, and only in workflow steps.

javascript
const { version, deleted } = await yuze.lake.table('incidents').clear();
// version: the table version the clear made; deleted: the rows it removed

await yuze.lake.table('incidents').load({ read: { folder: 'ehs/incident', parquet: {} }, mode: 'merge' });
  • The table keeps its columns and description. Only its rows go.
  • Other tables that load from the same folder keep the files they loaded.
  • Earlier table versions stay readable until they expire, like after any load.
  • A clear waits for a load of the same table to finish, and a load waits for a clear.

WARNING

After a clear, the table holds only what the next loads read from the files in its folder. Clear a table on purpose, for example when a source sends all its data again, not on every run.

yuze.sha256Hash ​

Calculates a SHA-256 hash. Useful for deduplication.

javascript
const hash = await yuze.sha256Hash({ id: 123, name: 'Test' });
// Returns: 64-character hex string

yuze.crypto.uuidv4 ​

Generates a random version 4 UUID. Each call returns a new one.

javascript
const id = yuze.crypto.uuidv4();
// Returns: e.g. '3f2b8c1e-9a4d-4e7f-b1c2-5d6e7f8a9b0c'

Use it for new identifiers, not for secrets such as passwords or API keys.

yuze.searchDataPoints ​

Searches recorded data points with filters. Returns paginated results with a continue token for fetching additional pages.

Parameters:

  • query: Search criteria (all fields optional)
    • schema: A schema id (e.g. 'schema:emissions') or a schema version id (e.g. 'schema-version:emissions:1.0') — the form is detected automatically. A schema id matches data points of any version of that schema; a schema version id matches only that version.
    • fromDate / toDate: ISO-8601 timestamps bounding the data point's timestamp.
    • bucket: Restrict to a single bucket.
    • propertyFilters: Array of { propertyName, operator, value }. Operators: Equals, NotEquals, Contains, StartsWith, EndsWith, IsNull, IsNotNull (value is omitted for the last two).
  • pagination: Pagination options.
    • pageSize: Number of items per page (required).
    • nextPageToken: (optional) Opaque cursor to read from. Omit (or pass null) to start from the beginning; pass back either token from a previous result to continue from there. Results are always ordered oldest → newest.

Returns:

  • items: Array of matching data points (code, type, values, numberValue, stringValue, schemas, associatedWith, bucket, timeStamp, position, …)
  • nextPageToken: Cursor for the next page, or null once you have read everything. Loop while it is set to walk the whole result set.
  • resumeToken: Cursor for where you got to. Stays set even once you are caught up, so you can save it and pass it back on a later run to read only what has been written since. null only when nothing has ever matched your query.

Both are opaque — store them as-is and pass them back verbatim; don't parse or build them.

Paginate through everything with a do-while loop:

javascript
let nextPageToken = undefined;
const all = [];

do {
  const result = await yuze.searchDataPoints(
    { schema: 'schema:emissions' },
    { pageSize: 100, nextPageToken }
  );

  all.push(...result.items);
  nextPageToken = result.nextPageToken;
} while (nextPageToken);
javascript
const result = await yuze.searchDataPoints(
  {
    schema: 'schema:emissions',
    fromDate: '2026-01-01T00:00:00Z',
    propertyFilters: [
      { propertyName: 'Scope', operator: 'Equals', value: 'Scope 1' },
      { propertyName: 'Note', operator: 'IsNotNull' }
    ]
  },
  { pageSize: 50 }
);

for (const dataPoint of result.items) {
  console.log(dataPoint.code, dataPoint.numberValue);
}

Reading only what's new (remembering where you left off) ​

Use resumeToken when you want a script to pick up where it left off rather than re-read everything. Persist it, and next time you pass it back you continue from that point — so you only ever read data points written since.

  • First read / from scratch: omit nextPageToken (or pass null). Results come oldest-first.
  • Read only what's new: pass the previous run's resumeToken back.
  • Re-read everything: omit the token again.

resumeToken stays set once any data has matched, including on a page that came back empty — so it's always safe to save. That's the difference between the two tokens: nextPageToken goes null to end a paging loop, resumeToken survives one so it can be stored between runs.

javascript
// Example: an API connector that returns new emissions data points since the caller's last token.
const page = await yuze.searchDataPoints(
  { schema: 'schema-version:emissions:1.0' },
  {
    pageSize: 200,
    nextPageToken: request.query.token ?? null  // null on the first call
  }
);

return {
  status: 200,
  body: {
    items: page.items.map(x => x.values),
    // The caller persists this and sends it back next time to get only newer data points.
    token: page.resumeToken ?? null
  }
};

WARNING

This surfaces newly written data points only — not edits or deletes to existing ones. It's a "read what's new" feed, not a full change feed.

XML transformations ​

yuze.xml converts between XML and plain JavaScript objects — useful when an external system speaks XML but the rest of your script works with objects. These helpers are synchronous (no await needed).

yuze.xml.build ​

Builds an XML string from an object. Keys starting with @_ become attributes; arrays become repeated elements; text is entity-escaped automatically — never hand-concatenate XML.

javascript
const xml = yuze.xml.build({
  Order: {
    '@_id': 'A1',
    Customer: 'Foo & Sons',   // the & is escaped to &amp; for you
    Line: ['Widget', 'Gadget'] // an array becomes repeated <Line> elements
  }
}, { format: true });          // format: true pretty-prints with indentation

// <Order id="A1">
//   <Customer>Foo &amp; Sons</Customer>
//   <Line>Widget</Line>
//   <Line>Gadget</Line>
// </Order>
return xml;

yuze.xml.parse ​

Parses an XML string into an object. By default it throws if the XML is malformed, so you never get silent garbage.

Always list repeating elements in arrays. XML has no array syntax, so a single <Line> parses as an object but two <Line> elements parse as an array. That inconsistency breaks scripts that expect a list. Naming the element in arrays forces it to always be an array — even when there's only one.

javascript
const doc = yuze.xml.parse(xml, { arrays: ['Line'] });

const orderId = doc.Order['@_id'];      // attributes are read with the @_ prefix
const lines = doc.Order.Line;           // always an array thanks to the arrays option

WARNING

All parsed values are strings — even numbers. <Code>00123</Code> parses as the string "00123" (this deliberately preserves leading zeros in external-system IDs). Convert explicitly when you need a number: Number(doc.Item.Code).

Some systems send XML that isn't quite valid — a tag left unclosed, several root elements in one response, a bare & in a description. Add loose: true to skip the well-formedness check and read whatever the document can give you.

javascript
const doc = yuze.xml.parse(supplierResponse, { loose: true, arrays: ['Line'] });

WARNING

loose: true trades safety for tolerance: broken structure is guessed at rather than reported, so an element you expect may be missing or nested somewhere else. Use it only for a system you know sends invalid XML, and check the fields you depend on afterwards. Attributes written without a value (<Line urgent>) come back as true rather than as a string. Truly unreadable input — an unterminated comment, a quote left open — still fails.

yuze.xml.validate ​

Checks whether a string is well-formed XML without parsing it. Returns { valid: true } or { valid: false, error: '...' }.

javascript
const check = yuze.xml.validate(input);
if (!check.valid) {
  throw new Error('Bad XML from the supplier: ' + check.error);
}

Console Logging ​

Standard console methods are available and captured in execution logs:

javascript
console.log('Processing started');
console.warn('Missing optional field');
console.error('Failed to process item');
MethodLog Level
console.log()Information
console.warn()Warning
console.error()Error

Error Handling ​

Script errors include line numbers and stack traces. Use try-catch for graceful error handling:

javascript
try {
  const item = await yuze.lookupMasterDataItem(identifier);
  if (!item) {
    console.warn(`Item not found: ${identifier}`);
    return null;
  }
  return item.properties;
} catch (error) {
  console.error(`Lookup failed: ${error.message}`);
  throw error;
}

Tips ​

  • Use async/await: All yuze functions and context methods are asynchronous
  • Check for null: Lookup functions return null when items are not found
  • Use console.log: Debug your scripts by logging intermediate values