Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v5
with:
node-version: 'lts/*'
# Pinned, not lts/*. n8n-workflow pulls in isolated-vm, which ships
# prebuilt binaries for Node 22 and 24 only, so on a newer Node npm ci
# has to compile it. Move this when the lockfile's isolated-vm does.
node-version: '24'
cache: 'npm'

- name: Install dependencies
Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v5
with:
node-version: 'lts/*'
# The same pin as ci.yml, for the same reason.
node-version: '24'
cache: 'npm'

- name: Install dependencies
Expand Down
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Changelog

## 0.3.0 — 2026-11-16

Render Template can load the chosen template's merge fields.

### Added

- **Merge Fields Source → From Template** on **Render → Render Template**.
Picking a template lists its merge fields, one input each, so nobody types
placeholder names. A field left empty keeps the template's own value, and so
does a field added to the template after the step was set up, so neither
renders as a raw placeholder. Each value takes the type of the template's
own value, so a "5" from a sheet fills a number placeholder as a number.
**Map Automatically** fills the fields from input columns with the same
names.
- Node version 2, where **From Template** is the default, so new Shotstack
steps show a template's fields as soon as it is picked. Saved workflows stay
on version 1, where **Fields** is still the default, so they are unchanged.

## 0.2.2 — 2026-10-30

Fixes the Shotstack credential in n8n's HTTP Request node. With the credential
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ Renders a template saved in your Shotstack account, filling in its placeholders.
| Field | Notes |
| --- | --- |
| **Template** | Pick one from the list, or paste an ID. Templates are made in [Shotstack Studio](https://shotstack.io/studio/). |
| **Merge Fields Source** | **Fields** for find/replace pairs, or **JSON** to supply the whole list at once. |
| **Merge Fields** | The find value is the placeholder name without braces. See [Merging data](https://shotstack.io/docs/guide/architecting-an-application/merging-data/). |
| **Merge Fields Source** | **From Template**, the default for new steps, loads the chosen template's merge fields, one input each. **Fields** for find/replace pairs, or **JSON** to supply the whole list at once. Steps saved before 0.3.0 keep **Fields** as their default. |
| **Merge Fields** | With **From Template**, a field left empty keeps the template's own value, and so does a field added to the template later. Each value takes the type of the template's own value, so a `5` from a sheet fills a number placeholder as a number. **Map Automatically** fills fields from input columns with the same names. With **Fields**, the find value is the placeholder name without braces. See [Merging data](https://shotstack.io/docs/guide/architecting-an-application/merging-data/). |

Returns the render `id`. This operation takes no Callback URL: the Edit API
accepts one on `POST /templates/render` and does not act on it. Use
Expand Down
8 changes: 7 additions & 1 deletion nodes/Shotstack/Shotstack.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { TELEMETRY_HEADERS } from './telemetry';
import { EDIT_BASE_URL } from './environment';
import { getTemplates } from './listSearch/getTemplates';
import { getModels } from './loadOptions/getModels';
import { getTemplateFields } from './resourceMapping/getTemplateFields';
import codexFile from './Shotstack.node.json';

export class Shotstack implements INodeType {
Expand All @@ -17,7 +18,9 @@ export class Shotstack implements INodeType {
dark: 'file:../../icons/shotstack.dark.svg',
},
group: ['transform'],
version: 1,
// Version 2 starts Render Template on the template's own merge fields. Saved
// workflows keep version 1, which defaults to Fields.
version: [1, 2],
// The operation values are OpenAPI operationIds, so the resource tells
// the reader which of the three a bare id belongs to.
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
Expand Down Expand Up @@ -87,5 +90,8 @@ export class Shotstack implements INodeType {
loadOptions: {
getModels,
},
resourceMapping: {
getTemplateFields,
},
};
}
84 changes: 84 additions & 0 deletions nodes/Shotstack/resourceMapping/getTemplateFields.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { NodeOperationError } from 'n8n-workflow';
import type {
IDataObject,
IExecuteSingleFunctions,
ILoadOptionsFunctions,
ResourceMapperFields,
} from 'n8n-workflow';
import { apiPathFor } from '../environment';
import { TELEMETRY_HEADERS } from '../telemetry';

export type MergeField = { find: string; replace: unknown };

// n8n starts every item of a run at once, so the items share one lookup instead of
// making one each. Keyed by run, so a template edited in Studio between runs is read fresh.
const lookups = new Map<string, Promise<MergeField[]>>();

/** The template's merge fields as saved in Shotstack, each with the template's own value. */
export async function templateMerge(
this: IExecuteSingleFunctions | ILoadOptionsFunctions,
id: string,
): Promise<MergeField[]> {
const credentials = await this.getCredentials('shotstackApi');
const path = apiPathFor(credentials?.environment);
const run = this.getExecutionId();
const key = `${run}:${path}:${id}`;
let lookup = run ? lookups.get(key) : undefined;
if (!lookup) {
lookup = (async () => {
const response = (await this.helpers.httpRequestWithAuthentication.call(this, 'shotstackApi', {
method: 'GET',
url: `https://api.shotstack.io/edit/${path}/templates/${encodeURIComponent(id)}`,
json: true,
timeout: 30000,
headers: { ...TELEMETRY_HEADERS },
})) as IDataObject;
const template = ((response?.response as IDataObject | undefined)?.template ?? {}) as IDataObject;
const merge = Array.isArray(template.merge) ? (template.merge as MergeField[]) : [];
return merge.filter((field) => typeof field?.find === 'string' && field.find !== '');
})();
if (run) {
if (lookups.size >= 100) lookups.clear();
lookups.set(key, lookup);
// Retry On Fail runs the step again inside the same run, so a failed lookup is dropped.
lookup.catch(() => lookups.delete(key));
}
}

try {
return await lookup;
} catch (error) {
// A new error for each caller, since n8n writes the item index onto the error it gets.
const status = String((error as { httpCode?: unknown }).httpCode ?? '');
const refused = status === '401' || status === '403';
throw new NodeOperationError(
this.getNode(),
refused ? 'Shotstack refused the API key' : "Couldn't read the template's merge fields",
{
description: refused
? 'Check the key, and check that the credential environment matches it. Sandbox and Production keep separate templates.'
: `${(error as Error).message}. Check that the template exists in the credential's environment.`,
...('getItemIndex' in this ? { itemIndex: (this as IExecuteSingleFunctions).getItemIndex() } : {}),
},
);
}
}

/** Lists the chosen template's merge fields, one input each, so nobody types placeholder names. */
export async function getTemplateFields(this: ILoadOptionsFunctions): Promise<ResourceMapperFields> {
const id = this.getNodeParameter('templateId', '', { extractValue: true }) as string;
if (!id) return { fields: [] };
return {
fields: (await templateMerge.call(this, id)).map(({ find }) => ({
id: find,
displayName: find,
required: false,
defaultMatch: false,
canBeUsedToMatch: false,
display: true,
// Text inputs throughout. The render step gives each value the type of the
// template's own value, which n8n's type check would refuse before it could.
type: 'string',
})),
};
}
99 changes: 81 additions & 18 deletions nodes/Shotstack/resources/render/postTemplateRender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,28 @@ import type {
INodeProperties,
PreSendAction,
} from 'n8n-workflow';
import { templateMerge } from '../../resourceMapping/getTemplateFields';

const showOnly = {
resource: ['render'],
operation: ['postTemplateRender'],
};

/**
* A value in the JSON type of the template's own value. Shotstack keeps each
* value's type, so a sheet's "5" fills a number placeholder as 5, and a number
* fills a text placeholder as text.
*/
const likeTemplate = (value: unknown, templateValue: unknown): unknown => {
if (typeof templateValue === 'number' && typeof value === 'string' && Number.isFinite(Number(value))) {
return Number(value);
}
if (typeof templateValue === 'string' && (typeof value === 'number' || typeof value === 'boolean')) {
return String(value);
}
return value;
};

/**
* Puts the merge list on the body, from whichever source the user chose.
*
Expand All @@ -29,7 +45,22 @@ const buildMerge: PreSendAction = async function (
const body = (requestOptions.body ?? {}) as IDataObject;
let merge: unknown;

if (source === 'json') {
if (source === 'template') {
// Built from the template as it is now. Shotstack does not fill gaps, so a
// field left empty, or added in Studio after this step was set up, goes out
// with the template's own value instead of as a raw placeholder.
// skipValidation: n8n would otherwise refuse "9" for a number, or an emptied
// field, before likeTemplate gets to convert it.
const id = this.getNodeParameter('templateId', '', { extractValue: true }) as string;
const given = ((this.getNodeParameter('templateFields.mappingMode', 'defineBelow') === 'autoMapInputData'
? this.getInputData().json
: this.getNodeParameter('templateFields.value', {}, { skipValidation: true })) ?? {}) as IDataObject;
merge = (id ? await templateMerge.call(this, id) : []).map(({ find, replace }) => {
const value = given[find];
const empty = value === undefined || value === null || (typeof value === 'string' && value.trim() === '');
return { find, replace: empty ? replace : likeTemplate(value, replace) };
});
} else if (source === 'json') {
const raw = this.getNodeParameter('mergeJson', '') as string | unknown[];
if (typeof raw === 'string') {
const text = raw.trim();
Expand Down Expand Up @@ -97,6 +128,34 @@ const buildMerge: PreSendAction = async function (
return requestOptions;
};

const mergeSourceV1: INodeProperties = {
displayName: 'Merge Fields Source',
name: 'mergeSource',
type: 'options',
noDataExpression: true,
default: 'fields',
displayOptions: { show: { ...showOnly, '@version': [1] } },
description:
"Whether to fill in the chosen template's own fields, type each placeholder yourself, or hand over a ready-made list. Choose JSON when an earlier step or an AI agent builds the list.",
options: [
{
name: 'From Template',
value: 'template',
description: "Load the chosen template's merge fields and fill in each one",
},
{
name: 'Fields',
value: 'fields',
description: 'Type each placeholder and its value',
},
{
name: 'JSON',
value: 'json',
description: 'Supply the whole list as [{"find":"NAME","replace":"value"}]',
},
],
};

export const postTemplateRenderDescription: INodeProperties[] = [
{
displayName: 'Template',
Expand Down Expand Up @@ -144,27 +203,31 @@ export const postTemplateRenderDescription: INodeProperties[] = [
},
},
},
mergeSourceV1,
// A new default needs a new version: n8n leaves a default value out of a saved workflow,
// so changing version 1's default would switch every saved step to the new source.
{ ...mergeSourceV1, default: 'template', displayOptions: { show: { ...showOnly, '@version': [2] } } },
{
displayName: 'Merge Fields Source',
name: 'mergeSource',
type: 'options',
displayName: 'Merge Fields',
name: 'templateFields',
type: 'resourceMapper',
noDataExpression: true,
default: 'fields',
displayOptions: { show: showOnly },
default: { mappingMode: 'defineBelow', value: null },
displayOptions: { show: { ...showOnly, mergeSource: ['template'] } },
description:
'Whether to fill the placeholders one at a time, or hand over a ready-made list. Choose JSON when an earlier step or an AI agent builds the list.',
options: [
{
name: 'Fields',
value: 'fields',
description: 'Type each placeholder and its value',
},
{
name: 'JSON',
value: 'json',
description: 'Supply the whole list as [{"find":"NAME","replace":"value"}]',
"The chosen template's merge fields. Leave one empty to keep the template's own value.",
typeOptions: {
loadOptionsDependsOn: ['templateId.value'],
resourceMapper: {
resourceMapperMethod: 'getTemplateFields',
mode: 'add',
fieldWords: { singular: 'merge field', plural: 'merge fields' },
addAllFields: true,
multiKeyMatch: false,
supportAutoMap: true,
noFieldsError: 'No merge fields yet. Pick a template above, or add placeholders to it in Shotstack Studio.',
},
],
},
},
{
displayName: 'Merge Fields (JSON)',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"lint:fix": "npm run gen && n8n-node lint --fix",
"release": "n8n-node release",
"prepublishOnly": "n8n-node prerelease",
"test": "npm run build && node test/package-loads.mjs && node test/credential-host-scope.mjs && node test/docs-match-ui.mjs && node test/environment-mapping.mjs && node test/wait-and-backoff.mjs && node test/submit-guards.mjs && node test/generation-guards.mjs",
"test": "npm run build && node test/package-loads.mjs && node test/credential-host-scope.mjs && node test/docs-match-ui.mjs && node test/environment-mapping.mjs && node test/wait-and-backoff.mjs && node test/submit-guards.mjs && node test/generation-guards.mjs && node test/template-fields.mjs",
"gen": "node scripts/build-user-agent.mjs"
},
"files": [
Expand Down
8 changes: 6 additions & 2 deletions scripts/review-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -348,8 +348,8 @@ const UNWALKABLE = [
/**
* Every name a rename can reach a user through, read from the built node.
*
* Mostly what n8n stores in a saved workflow. Also the list method key, which
* two files must agree on, so both ends are collected here.
* Mostly what n8n stores in a saved workflow. Also the list and resource mapper
* method keys, which two files must agree on, so both ends are collected here.
*/
const frozenNames = () => {
const names = new Set();
Expand All @@ -366,6 +366,9 @@ const frozenNames = () => {
names.add(mode.name);
if (mode.typeOptions?.searchListMethod) names.add(mode.typeOptions.searchListMethod);
}
// A resource mapper names the method that lists its fields, just the same.
const mapper = property.typeOptions?.resourceMapper?.resourceMapperMethod;
if (mapper) names.add(mapper);
for (const step of property.routing?.output?.postReceive ?? []) fromPostReceive(step);
for (const option of property.options ?? []) {
if (option.value !== undefined) names.add(String(option.value));
Expand All @@ -382,6 +385,7 @@ const frozenNames = () => {
walk(shotstack.description.properties);
names.add(shotstack.description.name);
for (const method of Object.keys(shotstack.methods?.listSearch ?? {})) names.add(method);
for (const method of Object.keys(shotstack.methods?.resourceMapping ?? {})) names.add(method);
// The product token only. Shotstack's render log keeps it, and nothing joins
// an old token to a new one. The version after the slash is meant to move.
names.add(String(req(resolve(process.cwd(), 'dist/nodes/Shotstack/userAgent.js')).USER_AGENT).split('/')[0]);
Expand Down
Loading
Loading