ZZZ Digital Lab

Back to n8n workflow hardening

code/prepare_events.js

// SYNTHETIC. n8n Code node: Run Once for All Items. No external modules.
const MAX_BATCH = 50;
const input = $input.all();
if (input.length !== 1) throw new Error('ONE_ENVELOPE_REQUIRED');
const envelope = input[0].json.body ?? input[0].json;
const events = envelope.events;
if (!Array.isArray(events) || events.length === 0) throw new Error('EVENTS_REQUIRED');
if (events.length > MAX_BATCH) throw new Error('BATCH_LIMIT');
const seen = new Map();
const output = [];
for (const event of events) {
  if (!event || typeof event.event_id !== 'string' || typeof event.source !== 'string' ||
      typeof event.customer_ref !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(event.event_id || '') ||
      !/^[A-Za-z0-9_-]{1,32}$/.test(event.source || '') ||
      !/^[A-Za-z0-9_-]{1,64}$/.test(event.customer_ref || '') ||
      !Number.isSafeInteger(event.amount_minor) || event.amount_minor < 0 ||
      event.amount_minor > 100000000 || event.currency !== 'USD') throw new Error('EVENT_SCHEMA');
  const payload = {event_id:event.event_id, source:event.source, customer_ref:event.customer_ref,
                   amount_minor:event.amount_minor, currency:event.currency};
  const idempotencyKey = 'lead-event:v1:' + payload.source + ':' + payload.event_id;
  const canonical = JSON.stringify(payload);
  if (seen.has(idempotencyKey)) {
    if (seen.get(idempotencyKey) !== canonical) throw new Error('IDEMPOTENCY_CONFLICT');
    continue;
  }
  seen.set(idempotencyKey, canonical);
  output.push({json:{synthetic:true,idempotencyKey,payload},pairedItem:{item:0}});
}
return output;