A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
'use strict';
// `businessProcessFlows[]` — the App Spec surface over the SDK's BPF authoring.
//
// Layered the same way as business-rules.test.js, because each layer fails silently in its own way:
// 1. VALIDATION — the spec surface mirrors the slice the build can actually deploy AND verify.
// A step bound to a column that does not exist is accepted by the platform and simply renders
// bound to nothing, so nothing downstream would catch it.
// 2. MAPPING — `bpfDef` produces the SDK's artifact shape. This is the dangerous layer: the
// adapter's step normalizer copies exactly id/name/fieldName/required and DROPS every other
// key, so the plausible spelling (`fieldLogicalName`) is silently discarded and the step
// deploys bound to nothing.
// 3. REAL BUNDLE — the mapped def is pushed through the shipped SDK and the wire payload is
// inspected. Only this proves the authored stages and columns reach the platform.
// 4. BUILD / TEARDOWN / VERIFY — the phase is additive-idempotent, the teardown is ordered and
// scoped, and verify reconciles existence + cardinality + state.
const test = require('node:test');
const assert = require('node:assert');
const os = require('node:os');
const path = require('node:path');
const fs = require('node:fs');
const { validateAppSpec } = require('../lib/app-spec.js');
// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).
const { inOwnFolder } = require('./helpers/own-app-folder.js');
const { bpfDef, bpfFilter, runSdkBuild: runSdkBuildInPlace, planFor, PHASES } = require('../lib/sdk-build.js');
const runSdkBuild = inOwnFolder(runSdkBuildInPlace);
const { verifySpec } = require('../lib/verify-spec.js');
const { planTeardown, KIND_HANDLERS } = require('../lib/sdk-teardown.js');
const { PHASES: STAGE_PHASES, STAGES } = require('../lib/stages.js');
const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
const dirs = [];
test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
// Minimal spec that is valid on its own, so a validation failure below is always about the flow.
function specWith(flows) {
return {
solution: { uniqueName: 'BPF', displayName: 'BPF', publisherPrefix: 'new' },
app: { name: 'BPF App', description: '' },
entities: [{
schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets',
primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' },
columns: [
{ schemaName: 'new_status', displayName: 'Status', type: 'Choice', options: ['New', 'Closed'] },
{ schemaName: 'new_notes', displayName: 'Notes', type: 'Memo' },
{ schemaName: 'new_owner', displayName: 'Owner', type: 'Text' },
],
}],
appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'new_ticket', title: 'Tickets' }] }] }] },
businessProcessFlows: flows,
};
}
const FLOW = {
name: 'Ticket Handling',
entity: 'new_ticket',
stages: [
{ name: 'Triage', steps: [{ name: 'Subject', field: 'new_subject', required: true }] },
// Every step binds a column: the platform rejects a step with no `datafieldname`, so there is no
// field-less "checklist" step to fixture here. See the step-field test below.
{ name: 'Resolve', steps: [{ name: 'Notes', field: 'new_notes' }, { name: 'Confirmed with customer', field: 'new_owner' }] },
],
};
const errorsFor = (flows) => (validateAppSpec(specWith(flows), { profile: 'plan' }).errors || []);
// --- 1. validation ------------------------------------------------------------------------------
test('a well-formed business process flow validates', () => {
const v = validateAppSpec(specWith([FLOW]), { profile: 'plan' });
assert.strictEqual(v.ok, true, JSON.stringify(v.errors));
});
test('a flow must name a known entity, and its steps must name that entity\'s own columns', () => {
assert.ok(errorsFor([{ ...FLOW, entity: 'new_nope' }]).some((e) => /unknown entity/.test(e)));
// The silent case: the platform materializes the stage and renders a step bound to nothing.
const bad = errorsFor([{ ...FLOW, stages: [{ name: 'Triage', steps: [{ name: 'Ghost', field: 'new_ghost' }] }] }]);
assert.ok(bad.some((e) => /'new_ghost', which is not a column on new_ticket/.test(e)), JSON.stringify(bad));
});
test('a lookup created by a relationship counts as a column of the referencing table', () => {
// Same rule the business-rule validator applies — a lookup IS a real column, just declared under
// relationships[]. Sharing one helper is what keeps the two from disagreeing.
const spec = specWith([{ ...FLOW, stages: [{ name: 'Triage', steps: [{ name: 'Acct', field: 'new_accountid' }] }] }]);
spec.entities.push({
schemaName: 'new_account', displayName: 'Account', pluralName: 'Accounts',
primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [],
});
spec.relationships = [{ type: 'OneToMany', referenced: 'new_account', referencing: 'new_ticket', lookup: { schemaName: 'new_accountid', displayName: 'Account' } }];
const v = validateAppSpec(spec, { profile: 'plan' });
assert.strictEqual(v.ok, true, JSON.stringify(v.errors));
});
test('a flow needs stages, stages need names and at least one step, and names must be unique', () => {
assert.ok(errorsFor([{ ...FLOW, stages: [] }]).some((e) => /stages\[\] is required/.test(e)));
assert.ok(errorsFor([{ ...FLOW, stages: [{ steps: [{ name: 'S' }] }] }]).some((e) => /every stage needs a name/.test(e)));
assert.ok(errorsFor([{ ...FLOW, stages: [{ name: 'A', steps: [{ name: 'S' }] }, { name: 'A', steps: [{ name: 'T' }] }] }])
.some((e) => /duplicate stage name 'A'/.test(e)));
assert.ok(errorsFor([{ ...FLOW, stages: [{ name: 'A', steps: [{ name: 'S', field: 'new_notes' }, { name: 'S', field: 'new_owner' }] }] }])
.some((e) => /duplicate step name 'S'/.test(e)));
});
test('a stage with no steps is rejected — the SDK would substitute a phantom "New Step"', () => {
// createDefault injects a placeholder step when a stage has none, so an empty stage deploys a step
// the author never wrote — and the SDK's own stage-needs-step rule never fires, because the
// placeholder is injected before it looks.
for (const stages of [[{ name: 'Only', steps: [] }], [{ name: 'Only' }]]) {
assert.ok(errorsFor([{ ...FLOW, stages }]).some((e) => /has no steps/.test(e) && /New Step/.test(e)), JSON.stringify(stages));
}
});
test('two flows whose names derive the same Dataverse unique name are rejected', () => {
// The SDK derives `uniquename` as new_<name lower-cased, non-alphanumerics stripped> — it IGNORES
// the table. Activation then creates a backing TABLE with that name, so the second flow cannot
// deploy at all. An (entity, name) key would let all three of these through.
assert.ok(errorsFor([FLOW, { ...FLOW }]).some((e) => /derive the Dataverse unique name 'new_tickethandling'/.test(e)));
// Same name, DIFFERENT table — still a collision, because the derivation ignores the entity.
const spec = specWith([FLOW, { ...FLOW, entity: 'new_other' }]);
spec.entities.push({
schemaName: 'new_other', displayName: 'Other', pluralName: 'Others',
primaryAttribute: { schemaName: 'new_othername', displayName: 'Name' }, columns: [],
});
spec.businessProcessFlows[1].stages = [{ name: 'Triage', steps: [{ name: 'Name', field: 'new_othername' }] }];
const errs = validateAppSpec(spec, { profile: 'plan' }).errors || [];
assert.ok(errs.some((e) => /derive the Dataverse unique name/.test(e)), JSON.stringify(errs));
// Case and punctuation are stripped, so these collide too.
assert.ok(errorsFor([FLOW, { ...FLOW, name: 'ticket-handling' }]).some((e) => /derive the Dataverse unique name/.test(e)));
// Renaming clears it — the message suggests exactly this shape.
spec.businessProcessFlows[1].name = 'Ticket Handling (Cases)';
assert.strictEqual(validateAppSpec(spec, { profile: 'plan' }).ok, true, JSON.stringify(validateAppSpec(spec, { profile: 'plan' }).errors));
});
test('bpfUniqueName mirrors the SDK derivation exactly', () => {
const { bpfUniqueName } = require('../lib/app-spec.js');
assert.strictEqual(bpfUniqueName('Ticket Handling'), 'new_tickethandling');
assert.strictEqual(bpfUniqueName('ticket-handling'), 'new_tickethandling');
assert.strictEqual(bpfUniqueName('Ticket Handling!'), 'new_tickethandling');
// The SDK falls back to a literal when the name normalizes to nothing, so two such flows collide.
assert.strictEqual(bpfUniqueName('!!!'), 'new_businessprocessflow');
assert.strictEqual(bpfUniqueName(''), 'new_businessprocessflow');
});
test('REAL BUNDLE: the derived uniquename really does ignore the table and the punctuation', async () => {
// bpfUniqueName is a MIRROR of SDK behaviour, so it has to be checked against the bundle — a mirror
// that drifts would silently stop catching the collision it exists to catch.
const { bpfUniqueName } = require('../lib/app-spec.js');
for (const [name, entity] of [['Ticket Handling', 'new_ticket'], ['ticket-handling', 'new_case'], ['!!!', 'new_ticket']]) {
const { sdk, writes } = await realSdk();
const art = await sdk.createArtifact('bpf', bpfDef({ name, entity, status: 'Draft', stages: [{ name: 'S', steps: [{ name: 'P' }] }] }));
await sdk.pushArtifact('bpf', art.id);
const post = writes.find((w) => w.verb === 'POST' && /\/workflows$/.test(w.url));
assert.strictEqual(post.body.uniquename, bpfUniqueName(name), `${name} on ${entity}`);
}
});
// The platform rejects a step with no bound column:
// HTTP 400 ... Attribute - datafieldname of ControlStep cannot be null or empty
// This was originally modelled as optional ("a checklist item"), which validated fine and then HALTED
// a live build in the business-process-flows phase — after the solution, table, columns, views and
// forms were already created. Isolated by A/B live: the identical flow with every step bound deploys
// and activates cleanly.
test('a step that binds no field is rejected — the platform requires a datafieldname', () => {
const errs = errorsFor([{ ...FLOW, stages: [{ name: 'A', steps: [{ name: 'Call the customer' }] }] }]);
assert.ok(errs.some((e) => /binds no field/.test(e)), `expected a step-field error, got ${JSON.stringify(errs)}`);
// The message has to tell the author what to do instead, not just say no.
assert.ok(errs.some((e) => /datafieldname of ControlStep/.test(e)), 'must quote the platform error so it is searchable');
assert.ok(errs.some((e) => /Boolean/.test(e)), 'must name the workaround (bind a Boolean flag)');
// A required-but-unbound step is the same defect, and must not slip through a different branch.
assert.ok(errorsFor([{ ...FLOW, stages: [{ name: 'A', steps: [{ name: 'Nothing', required: true }] }] }])
.some((e) => /binds no field/.test(e)));
// A bound step is still fine.
assert.deepStrictEqual(errorsFor([{ ...FLOW, stages: [{ name: 'A', steps: [{ name: 'Call the customer', field: 'new_owner' }] }] }]), []);
});
test('a BLANK or null field is the same defect as a missing one, and says so', () => {
// Treating only `undefined` as missing let these fall through to the column check, which reported
// `references ''` — or `references 'null'` from stringifying the value — instead of the actionable
// message. Same defect, same guidance.
for (const bad of ['', ' ', null]) {
const errs = errorsFor([{ ...FLOW, stages: [{ name: 'A', steps: [{ name: 'X', field: bad }] }] }]);
assert.ok(
errs.some((e) => /binds no field/.test(e)),
`field ${JSON.stringify(bad)} must report "binds no field"; got ${JSON.stringify(errs)}`,
);
assert.ok(!errs.some((e) => /references '/.test(e)), `field ${JSON.stringify(bad)} must not report a bogus column reference`);
}
// A real column name that simply does not exist STILL reports the column error — the blank check
// must not swallow that case.
assert.ok(errorsFor([{ ...FLOW, stages: [{ name: 'A', steps: [{ name: 'X', field: 'new_nope' }] }] }])
.some((e) => /references 'new_nope'/.test(e)));
});
test('status and order are constrained', () => {
assert.ok(errorsFor([{ ...FLOW, status: 'Published' }]).some((e) => /status must be Active\|Draft/.test(e)));
assert.ok(errorsFor([{ ...FLOW, order: 0 }]).some((e) => /order must be a positive integer/.test(e)));
assert.ok(errorsFor([{ ...FLOW, order: 1.5 }]).some((e) => /order must be a positive integer/.test(e)));
assert.deepStrictEqual(errorsFor([{ ...FLOW, status: 'Draft', order: 3 }]), []);
});
test('a cross-entity stage is rejected rather than silently retargeted', () => {
// The SDK models a per-stage entity, so this would deploy as a DIFFERENT process (one spanning
// records) instead of failing — the author would not find out from the build.
assert.ok(errorsFor([{ ...FLOW, stages: [{ name: 'A', entity: 'new_other', steps: [{ name: 'S' }] }] }])
.some((e) => /cross-entity flows are not supported/.test(e)));
// Restating the flow's own entity is harmless.
assert.deepStrictEqual(errorsFor([{ ...FLOW, stages: [{ name: 'A', entity: 'new_ticket', steps: [{ name: 'S', field: 'new_notes' }] }] }]), []);
});
test('a knob the build cannot verify is REJECTED, not ignored — at flow, stage AND step level', () => {
// Silently dropping a key the author wrote is how a spec "deploys" something it does not: they
// would see the stages appear and reasonably assume the rest applied.
//
// `securityRoles` is NO LONGER in this list: it is supported since #513 (see the dedicated tests
// below). It stays rejected as an ARRAY though — the shape here — because the supported form is
// an object, so the old spelling still fails rather than being read as something else.
for (const key of ['branch', 'actions', 'globalActions']) {
const errs = errorsFor([{ ...FLOW, [key]: [{}] }]);
assert.ok(errs.some((e) => new RegExp(`unsupported key '${key}'`).test(e)), `${key}: ${JSON.stringify(errs)}`);
}
const arrayRoles = errorsFor([{ ...FLOW, securityRoles: ['Salesperson'] }]);
assert.ok(arrayRoles.some((e) => /securityRoles must be an object like \{ "personas"/.test(e)), JSON.stringify(arrayRoles));
// STAGE level is where an author would naturally write branching/actions — the SDK models them
// there, and bpfDef maps only name/entity/steps, so an unguarded key vanishes without a word.
for (const key of ['branch', 'actions', 'nextStageId', 'category', 'relationshipName']) {
const errs = errorsFor([{ ...FLOW, stages: [{ name: 'A', [key]: key === 'category' ? 3 : [{}], steps: [{ name: 'S' }] }] }]);
assert.ok(errs.some((e) => new RegExp(`stage 'A' has unsupported key '${key}'`).test(e)), `stage.${key}: ${JSON.stringify(errs)}`);
}
// STEP level: `fieldLogicalName` is the plausible spelling (it is what the SDK calls the key on
// other artifacts), and the step normalizer drops it — deploying a step bound to nothing.
const stepErrs = errorsFor([{ ...FLOW, stages: [{ name: 'A', steps: [{ name: 'S', fieldLogicalName: 'new_notes' }] }] }]);
assert.ok(stepErrs.some((e) => /step 'S' has unsupported key 'fieldLogicalName'/.test(e)), JSON.stringify(stepErrs));
assert.ok(stepErrs.some((e) => /the column key is 'field'/.test(e)), 'the message must name the right key');
});
// --- 2. mapping ---------------------------------------------------------------------------------
test('bpfDef maps onto the SDK artifact shape — and uses `fieldName`, not `fieldLogicalName`', () => {
const def = bpfDef({ ...FLOW, description: 'How tickets are handled', order: 7 });
assert.strictEqual(def.name, 'Ticket Handling');
assert.strictEqual(def.entityLogicalName, 'new_ticket');
assert.strictEqual(def.status, 'Active', 'a flow is invisible until activated, so Active is the default');
assert.strictEqual(def.description, 'How tickets are handled');
assert.strictEqual(def.order, 7);
// THE trap this test exists for. The adapter's step normalizer copies id/name/fieldName/required
// and drops everything else, so `fieldLogicalName` would vanish without any error and the step
// would deploy bound to nothing.
assert.deepStrictEqual(def.stages, [
{ name: 'Triage', entityLogicalName: 'new_ticket', steps: [{ name: 'Subject', fieldName: 'new_subject', required: true }] },
{ name: 'Resolve', entityLogicalName: 'new_ticket', steps: [{ name: 'Notes', fieldName: 'new_notes' }, { name: 'Confirmed with customer', fieldName: 'new_owner' }] },
]);
});
test('bpfDef omits absent optionals rather than emitting undefined', () => {
// `{ required: undefined }` is not the same as no key: the adapter checks `!== undefined`.
const def = bpfDef(FLOW);
assert.ok(!('description' in def), 'no description key when none was authored');
assert.ok(!('order' in def), 'no order key when none was authored');
assert.deepStrictEqual(Object.keys(def.stages[1].steps[1]), ['name', 'fieldName'], 'a step with no `required` carries only name + fieldName');
});
test('bpfDef lower-cases the entity everywhere it appears', () => {
const def = bpfDef({ ...FLOW, entity: 'New_Ticket', stages: [{ name: 'A', steps: [{ name: 'S', field: 'New_Notes' }] }] });
assert.strictEqual(def.entityLogicalName, 'new_ticket');
assert.strictEqual(def.stages[0].entityLogicalName, 'new_ticket');
assert.strictEqual(def.stages[0].steps[0].fieldName, 'new_notes');
});
test('bpfFilter selects the BPF definition only — not the activated copy, not a task flow', () => {
const f = bpfFilter('Ticket Handling', 'new_ticket');
assert.match(f, /category eq 4/, 'category 4 = BusinessProcessFlow');
assert.match(f, /type eq 1/, 'definition rows only; the platform owns the type-2 activated copy');
assert.match(f, /businessprocesstype eq 0/, 'BusinessFlow only — a task flow is also category 4');
assert.match(f, /name eq 'Ticket Handling'/);
assert.match(f, /primaryentity eq 'new_ticket'/);
// Scoping to the entity as well as the name is what stops a same-named flow on another table
// being adopted as this one.
assert.strictEqual(bpfFilter("O'Brien", 'NEW_Ticket').includes("name eq 'O''Brien'"), true, 'OData literals are escaped');
assert.match(bpfFilter('x', 'NEW_Ticket'), /primaryentity eq 'new_ticket'/, 'the entity is lower-cased');
});
test('every BPF query in build, verify and teardown goes through bpfFilter', () => {
// The business-rule equivalent of this test exists because an unfiltered query made teardown fail
// on every activated rule. Enforce the same discipline here by construction rather than by review.
for (const file of ['sdk-build.js', 'verify-spec.js', 'sdk-teardown.js']) {
const src = fs.readFileSync(path.join(__dirname, '..', 'lib', file), 'utf8');
const category4 = [...src.matchAll(/category eq 4/g)].length;
const inFilter = [...src.matchAll(/bpfFilter\(/g)].length;
if (file === 'sdk-build.js') {
assert.strictEqual(category4, 1, 'sdk-build.js defines the filter exactly once');
} else {
assert.strictEqual(category4, 0, `${file} must not hand-roll a category-4 filter`);
assert.ok(inFilter > 0, `${file} must use bpfFilter`);
}
}
});
// --- 3. real bundle -----------------------------------------------------------------------------
async function realSdk({ honourPrefer = true } = {}) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bpf-'));
dirs.push(dir);
const writes = [];
const reads = [];
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
// The `workflows` write contract, as MEASURED against a live org rather than assumed:
// plain POST -> 204, `OData-EntityId` only — no body, no ETag
// POST Prefer: return=representation -> 201, the row in the BODY with `@odata.etag`
// plain PATCH -> 204 — no body, NO ETag
// PATCH Prefer: return=representation -> 200, `ETag` header AND `@odata.etag`
// An earlier version of this fake answered EVERY PATCH with an ETag. No Dataverse does that, and
// it produced a wrong conclusion recorded downstream (that only a Draft flow could reach the
// create read-back the SDK then had). Answering by the request's own `Prefer` keeps the fixture
// honest about what the SDK asks for: a write that is not echoed gets no token here, exactly as
// against a real org, instead of one the server never sent papering over the gap.
// `honourPrefer: false` models an environment that ignores `Prefer` — which the SDK now REFUSES
// (`BPF_CREATE_NO_TOKEN`) rather than recovers with a by-id read-back.
// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-entity-web-api#create-with-data-returned
const echo = (options) => honourPrefer
&& /return=representation/i.test(String(((options && options.headers) || {}).Prefer || ''));
const entityId = (id) => ({ 'odata-entityid': `https://contoso.crm.dynamics.com/api/data/v9.2/workflows(${id})` });
const sdk = createMakerSdk({
workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com',
httpClient: {
// A real Dataverse GET of a record carries `@odata.etag`. A single-record read
// (`/workflows(<id>)`) returns the ROW; a collection read returns `{ value: [...] }`. Both
// shapes are produced here so the token lookup works whichever the SDK uses.
get: async (url) => {
reads.push(String(url));
const m = /\/workflows\(([^)]+)\)/i.exec(String(url));
if (m) {
return { status: 200, headers: { etag: 'W/"1001"' },
body: { workflowid: m[1].replace(/'/g, ''), '@odata.etag': 'W/"1001"', statecode: 0, statuscode: 1 } };
}
if (/\/workflows/i.test(String(url))) {
return { status: 200, headers: {}, body: { value: [] } };
}
return { status: 200, headers: {}, body: { value: [] } };
},
post: async (url, body, options) => {
writes.push({ verb: 'POST', url: String(url), body, headers: (options && options.headers) || {} });
// The workflowid is minted CLIENT-side (the keyed-create contract), so the row the server
// echoes carries the id that was posted.
const id = String((body && body.workflowid) || '44444444-4444-4444-4444-444444444444');
if (echo(options)) {
return { status: 201, headers: entityId(id), body: { workflowid: id, '@odata.etag': 'W/"1001"' } };
}
return { status: 204, headers: entityId(id), body: undefined };
},
patch: async (url, body, options) => {
writes.push({ verb: 'PATCH', url: String(url), body, headers: (options && options.headers) || {} });
if (echo(options)) {
return { status: 200, headers: { etag: 'W/"1002"' }, body: { '@odata.etag': 'W/"1002"' } };
}
return { status: 204, headers: {}, body: undefined };
},
put: async () => ({ status: 204, headers: {}, body: {} }),
delete: async (url, options) => {
writes.push({ verb: 'DELETE', url: String(url), body: undefined, headers: (options && options.headers) || {} });
return { status: 204, headers: {}, body: {} };
},
},
});
await sdk.initWorkspace();
return { sdk, writes, reads };
}
test('REAL BUNDLE: a BPF is authored through the generic artifact lifecycle', async () => {
// There is no dedicated BPF method on the SDK surface — it is createArtifact -> pushArtifact, and
// the whole stage/step tree rides on the create payload (unlike a business rule's condition tree,
// which needs an updateElement). Pinning that tells a future implementer which surface to build on.
const { sdk } = await realSdk();
const art = await sdk.createArtifact('bpf', bpfDef(FLOW));
assert.ok(art && art.id, 'createArtifact returns an artifact with an id');
assert.deepStrictEqual(Object.keys(art).sort(), ['entityLogicalName', 'id', 'name', 'stages', 'status']);
// The adapter stamps ids on stages and steps; the plugin deliberately does not mint them.
assert.strictEqual(art.stages.length, 2);
assert.ok(art.stages.every((s) => s.id), 'every stage is id-stamped by the adapter');
assert.ok(art.stages.every((s) => (s.steps || []).every((p) => p.id)), 'every step is id-stamped by the adapter');
const pushed = await sdk.pushArtifact('bpf', art.id);
assert.strictEqual(pushed.saved, true, 'the push commits');
});
test('REAL BUNDLE: the wire payload is a category-4 BusinessFlow definition carrying the stages', async () => {
const { sdk, writes } = await realSdk();
const art = await sdk.createArtifact('bpf', bpfDef({ ...FLOW, status: 'Draft', description: 'd' }));
await sdk.pushArtifact('bpf', art.id);
const post = writes.find((w) => w.verb === 'POST' && /\/workflows$/.test(w.url));
assert.ok(post, `a workflows create must be issued; got ${JSON.stringify(writes.map((w) => w.verb + ' ' + w.url))}`);
// The discriminating columns. A flow written with the wrong category/businessprocesstype is not a
// BPF at all — and would then be invisible to every query in build, verify and teardown.
assert.strictEqual(post.body.category, 4, 'category 4 = BusinessProcessFlow');
assert.strictEqual(post.body.type, 1, 'type 1 = definition');
assert.strictEqual(post.body.businessprocesstype, 0, 'businessprocesstype 0 = BusinessFlow (not a task flow)');
assert.strictEqual(post.body.scope, 4, 'scope 4 = Organization');
assert.strictEqual(post.body.primaryentity, 'new_ticket');
assert.strictEqual(post.body.name, 'Ticket Handling');
// The authored stages and the bound columns must survive compilation into the XAML — if they did
// not, the flow would deploy as an empty process and nothing would report it.
const xaml = post.body.xaml;
assert.ok(typeof xaml === 'string' && xaml.length > 1000, `expected substantial XAML, got ${xaml && xaml.length}`);
assert.match(xaml, /StageStep\d+: Triage/);
assert.match(xaml, /StageStep\d+: Resolve/);
assert.ok(xaml.includes('new_subject'), 'the bound column reached the compiled process');
assert.ok(xaml.includes('new_notes'), 'the second bound column reached the compiled process');
});
// --- a create whose writes are not echoed is REFUSED, never recovered by reading the record back --
// The bundle's bpf create takes its concurrency token ONLY from the echo of a write it issued itself
// (the POST, then the activation PATCH), and asks each of them to echo (`Prefer:
// return=representation`), so against an ordinary org no token is ever missing. It used to fall
// back to reading the record back by id. The SDK removed that deliberately: the id is minted by the
// caller and known before the POST lands, so a second writer can edit the row in the gap, and the
// read-back then hands back THEIR token paired with OUR content — the next push overwrites them.
// These tests pin the replacement: refuse, say the flow exists, and leave it exactly as created.
// A by-id read of this fixture always yields a token, so only the SDK declining to issue one keeps
// these green.
//
// What happens next is not the SDK's advice: this plugin's next build finds the flow with its reuse
// query (name + table) and only converges its state. The advice itself —
// `fetchArtifact('bpf', id, { overwrite: true })` — was measured against this bundle to adopt the row
// and turn the next push into a conditional update; the plain `fetchArtifact` it used to prescribe
// kept the never-pushed local copy, re-issued the create, and was refused with 412.
const byIdReads = (reads) => reads.filter((u) => /\/workflows\([^)]+\)/i.test(u));
test('REAL BUNDLE: a create whose write is not echoed is refused, not recovered by a by-id read-back', async () => {
const { sdk, reads, writes } = await realSdk({ honourPrefer: false });
const art = await sdk.createArtifact('bpf', bpfDef({ ...FLOW, status: 'Draft' }));
await assert.rejects(
() => sdk.pushArtifact('bpf', art.id),
(e) => {
assert.strictEqual(e.code, 'BPF_CREATE_NO_TOKEN', `unexpected code ${e && e.code}: ${e && e.message}`);
assert.match(String(e.message), /EXISTS/, 'the message must say the flow was created, so nobody authors it twice');
assert.match(String(e.message), /NOT rolled back/, 'and that it was left in place');
return true;
});
assert.deepStrictEqual(byIdReads(reads), [], 'no by-id read-back may be issued for a token');
assert.ok(!writes.some((w) => w.verb === 'DELETE'), 'a flow nobody can condition a delete on must not be deleted');
});
// An Active flow is not activated either: an activation that cannot be conditioned on our own write
// would enable whatever the row holds by then, including another writer's edit.
test('REAL BUNDLE: an Active create whose write is not echoed is left Draft, never activated blind', async () => {
const { sdk, reads, writes } = await realSdk({ honourPrefer: false });
const art = await sdk.createArtifact('bpf', bpfDef({ ...FLOW, status: 'Active' }));
await assert.rejects(
() => sdk.pushArtifact('bpf', art.id),
(e) => {
assert.strictEqual(e.code, 'BPF_CREATE_NO_TOKEN', `unexpected code ${e && e.code}: ${e && e.message}`);
assert.match(String(e.message), /NOT activated/, 'the message must say the flow is still Draft');
return true;
});
assert.ok(!writes.some((w) => w.verb === 'PATCH' && w.body && w.body.statecode === 1), 'no activation may be sent');
assert.deepStrictEqual(byIdReads(reads), [], 'no by-id read-back may be issued for a token');
assert.ok(!writes.some((w) => w.verb === 'DELETE'), 'the created flow is left in place, not rolled back');
});
// Against the MEASURED contract the token arrives WITH the write, so no read-back is issued. This
// pins the premise the fixture above is built on: if a later bundle stops asking `workflows` writes
// to echo, this fails loudly instead of the refusal tests quietly passing for the wrong reason.
test('REAL BUNDLE: against an echoing server the create takes its token from the write itself', async () => {
const { sdk, reads, writes } = await realSdk();
const art = await sdk.createArtifact('bpf', bpfDef({ ...FLOW, status: 'Active' }));
const pushed = await sdk.pushArtifact('bpf', art.id);
assert.strictEqual(pushed.saved, true);
const post = writes.find((w) => w.verb === 'POST' && /\/workflows$/.test(w.url));
const activate = writes.find((w) => w.verb === 'PATCH' && w.body && w.body.statecode === 1);
for (const [label, w] of [['create', post], ['activation', activate]]) {
assert.ok(w, `the ${label} write must be issued`);
assert.match(String(w.headers.Prefer || ''), /return=representation/,
`the ${label} write must ask for its token to be echoed; headers were ${JSON.stringify(w.headers)}`);
}
assert.ok(!reads.some((u) => /\/workflows\([^)]+\)/i.test(u)),
`no by-id read-back may be needed; reads were ${JSON.stringify(reads)}`);
});
test('REAL BUNDLE: an Active flow is activated in the same push (statecode 1 / statuscode 2)', async () => {
// Activation is a SECOND, non-atomic request. It is what makes the process appear on the form, so
// a re-vendor that stopped issuing it would deploy flows nobody can see.
const { sdk, writes } = await realSdk();
const art = await sdk.createArtifact('bpf', bpfDef({ ...FLOW, status: 'Active' }));
await sdk.pushArtifact('bpf', art.id);
const patch = writes.find((w) => w.verb === 'PATCH' && /workflows\(/.test(w.url));
assert.ok(patch, `an activation PATCH must follow the create; got ${JSON.stringify(writes.map((w) => w.verb + ' ' + w.url))}`);
assert.deepStrictEqual(patch.body, { statecode: 1, statuscode: 2 });
});
// A live build failed this way: activating a flow on a table created seconds earlier outlasted the
// transport's wait, the activation COMMITTED anyway, and the transport re-sent it — carrying the
// token the first attempt had just superseded — so it was refused with a 412, and the create rolled
// itself back on that false "concurrent edit". Driven through the plugin's REAL transport, because
// that is where the re-send lived; every other test here injects its own client.
test('REAL BUNDLE + REAL TRANSPORT: an activation that commits after the client stopped waiting is not re-sent', async () => {
const { createAzHttpClient } = require('../lib/sdk-http-client.js');
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bpf-timeout-'));
dirs.push(dir);
const ORG = 'https://contoso.crm.dynamics.com';
let row = null;
const activations = [];
const conflict = { statusCode: 412, headers: {}, body: JSON.stringify({ error: { code: '0x80060882', message: 'The version of the existing record doesn\'t match the RowVersion property provided.' } }) };
// The measured `workflows` contract: an echoed write carries the row version; a stale `If-Match`
// answers 412; the version moves on every committed write.
const request = async ({ url, method, headers, body }) => {
const u = String(url);
const tok = () => `W/"${row.version}"`;
const ifMatch = headers['If-Match'];
if (method === 'POST' && /\/workflows$/.test(u)) {
row = { id: JSON.parse(body).workflowid, version: 1, statecode: 0 };
return { statusCode: 201, headers: {}, body: JSON.stringify({ workflowid: row.id, '@odata.etag': tok() }) };
}
if (method === 'PATCH' && /\/workflows\(/.test(u)) {
const b = JSON.parse(body);
if (b.statecode === 1) activations.push(ifMatch);
if (ifMatch && ifMatch !== tok()) return conflict;
if (b.statecode !== undefined) row.statecode = b.statecode;
row.version += 1;
if (b.statecode === 1 && activations.length === 1) return { error: 'Request timed out' }; // committed, unanswered
return { statusCode: 200, headers: { etag: tok() }, body: JSON.stringify({ '@odata.etag': tok() }) };
}
if (method === 'GET' && /\/workflows\(/.test(u)) {
return { statusCode: 200, headers: { etag: tok() }, body: JSON.stringify({ workflowid: row.id, statecode: row.statecode, '@odata.etag': tok() }) };
}
if (method === 'DELETE' && /\/workflows\(/.test(u)) {
if (ifMatch && ifMatch !== tok()) return conflict;
row = null;
return { statusCode: 204, headers: {}, body: '' };
}
return { statusCode: 200, headers: {}, body: JSON.stringify({ value: [] }) };
};
const httpClient = createAzHttpClient(ORG, { getToken: () => 'TOK', request, sleep: async () => {} });
const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: ORG, httpClient });
await sdk.initWorkspace();
const art = await sdk.createArtifact('bpf', bpfDef({ ...FLOW, status: 'Active' }));
await assert.rejects(() => sdk.pushArtifact('bpf', art.id), (e) => {
assert.doesNotMatch(String(e.message), /Original failure: Version conflict/, 'a committed activation must not be reported as somebody else\'s edit');
assert.match(String(e.message), /Request timed out/, 'the real cause — an unanswered write — is what must be reported');
return true;
});
assert.strictEqual(activations.length, 1, `the activation must be sent exactly once; got ${activations.length}`);
assert.ok(row && row.statecode === 1, 'the flow the platform activated is left in place for the next build to adopt');
});
test('REAL BUNDLE: a Draft flow is NOT activated', async () => {
const { sdk, writes } = await realSdk();
const art = await sdk.createArtifact('bpf', bpfDef({ ...FLOW, status: 'Draft' }));
await sdk.pushArtifact('bpf', art.id);
assert.strictEqual(writes.some((w) => w.verb === 'PATCH'), false, 'Draft must not be activated');
});
test('REAL BUNDLE: XML carrying character data still parses (the headless text-node regression)', async () => {
// Every BPF push crashed with `TypeError: Cannot read properties of null (reading 'length')` in the
// vendored (headless) bundle, and ONLY there: the SDK's grammar walk descended into TEXT nodes, and
// @xmldom/xmldom exposes a text node's `childNodes` as null where jsdom returns an empty NodeList.
// The BPF XAML template always contains text (`<mva:VisualBasic.Settings>`, stage/step ids,
// `False`), so this was input-independent — while the SDK's own jsdom suite stayed green.
//
// This asserts the SHIPPED bundle is fixed. A re-vendor that reintroduces it fails here rather
// than in a user's build.
const { sdk } = await realSdk();
const art = await sdk.createArtifact('bpf', bpfDef(FLOW));
await assert.doesNotReject(() => sdk.pushArtifact('bpf', art.id));
});
// --- 4. build phase -----------------------------------------------------------------------------
test('the phase is registered in PHASES and in the ui stage', () => {
assert.ok(PHASES.includes('business-process-flows'));
assert.deepStrictEqual(STAGE_PHASES, PHASES, 'stages.js is the single source of truth for the engine');
assert.ok(STAGES.ui.includes('business-process-flows'));
// Right after business-rules: both are authored against the entity's columns and nothing later.
assert.strictEqual(PHASES[PHASES.indexOf('business-rules') + 1], 'business-process-flows');
});
test('planFor lists each flow with its stage count', () => {
const items = planFor(specWith([FLOW]), { phases: ['business-process-flows'] });
const labels = items.filter((i) => i.phase === 'business-process-flows').map((i) => i.label);
assert.deepStrictEqual(labels, ['business process flow "Ticket Handling" on new_ticket (2 stages)']);
// Singular/plural, because a plan is read by a human before they approve it.
const one = planFor(specWith([{ ...FLOW, stages: [FLOW.stages[0]] }]), { phases: ['business-process-flows'] });
assert.match(one.find((i) => i.phase === 'business-process-flows').label, /\(1 stage\)$/);
});
// Minimal provision double: only the surface the business-process-flows phase touches.
function provisionWithFlows(rows) {
const calls = [];
return {
calls,
provision: {
queryRecords: async (entity, opts) => {
if (entity === 'workflow') { calls.push(['queryRecords', entity, opts]); return rows; }
return entity === 'solution' ? [] : [{ publisherid: 'pub-1' }];
},
updateRecord: async (e, id, patch) => { calls.push(['updateRecord', e, id, patch]); },
deleteRecord: async (e, id) => { calls.push(['deleteRecord', e, id]); },
createArtifact: (kind, def) => { calls.push(['createArtifact', kind, def]); return { id: 'bpf-new' }; },
updateElement: async () => undefined,
pushArtifact: async (kind, id) => { calls.push(['pushArtifact', kind, id]); return { id: 'bpf-new', saved: true, publish: { kind: 'notRequested' } }; },
addSolutionComponent: async (a) => { calls.push(['addSolutionComponent', a]); },
},
};
}
const buildFlow = async (rows, opts = {}) => {
const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();
const { provision, calls } = provisionWithFlows(rows);
const warnings = [];
const spec = specWith([{ ...FLOW, ...(opts.status ? { status: opts.status } : {}) }]);
await runSdkBuild(spec, { sdk, provisionSdk: provision, apply: true, phases: ['business-process-flows'], warn: (m) => warnings.push(m) });
return { calls, warnings };
};
test('a new flow is created, pushed, and added to the solution as a workflow component', async () => {
const { calls } = await buildFlow([]);
const created = calls.find((c) => c[0] === 'createArtifact');
assert.ok(created, 'the flow is created');
assert.strictEqual(created[1], 'bpf');
assert.strictEqual(created[2].entityLogicalName, 'new_ticket');
assert.ok(calls.some((c) => c[0] === 'pushArtifact' && c[1] === 'bpf'));
const solComponent = calls.find((c) => c[0] === 'addSolutionComponent');
assert.ok(solComponent, 'the flow must join the solution or it will not travel on export/import');
assert.strictEqual(solComponent[1].componentId, 'bpf-new');
assert.strictEqual(solComponent[1].componentType, 29, 'componentType 29 = workflow');
});
test('an existing flow is REUSED, not duplicated (the rebuild path)', async () => {
const { calls } = await buildFlow([{ workflowid: 'existing', statecode: 1, createdon: '2026-01-01T00:00:00Z' }]);
assert.strictEqual(calls.some((c) => c[0] === 'createArtifact'), false, 'a rebuild must not stack a second process on the table');
assert.strictEqual(calls.some((c) => c[0] === 'updateRecord'), false, 'an already-correct flow is left alone');
});
test('the reuse query is ORDERED and asks for more than one row', async () => {
// `top: 1` unordered adopts an arbitrary row and hides duplicates entirely — the business-rule bug.
const { calls } = await buildFlow([{ workflowid: 'only', statecode: 1, createdon: '2026-01-01T00:00:00Z' }]);
const q = calls.find((c) => c[0] === 'queryRecords');
assert.ok(q[2].top > 1, `the reuse query must be able to SEE duplicates; top was ${q[2].top}`);
assert.match(String(q[2].orderBy), /createdon asc/, 'oldest-first makes the surviving row deterministic');
assert.match(String(q[2].filter), /category eq 4 and type eq 1 and businessprocesstype eq 0/);
});
test('a flow deployed in the WRONG state is converged, in both directions', async () => {
// "Exists, so skip" would report success over a process nobody can see (Draft), or one still
// running after the spec asked for Draft.
const draftOnServer = await buildFlow([{ workflowid: 'w1', statecode: 0, createdon: '2026-01-01T00:00:00Z' }], { status: 'Active' });
assert.deepStrictEqual(draftOnServer.calls.find((c) => c[0] === 'updateRecord').slice(1), ['workflow', 'w1', { statecode: 1, statuscode: 2 }]);
const activeOnServer = await buildFlow([{ workflowid: 'w1', statecode: 1, createdon: '2026-01-01T00:00:00Z' }], { status: 'Draft' });
assert.deepStrictEqual(activeOnServer.calls.find((c) => c[0] === 'updateRecord').slice(1), ['workflow', 'w1', { statecode: 0, statuscode: 1 }]);
});
test('pre-existing duplicates are WARNED about, not silently adopted', async () => {
const { warnings } = await buildFlow([
{ workflowid: 'oldest', statecode: 1, createdon: '2026-01-01T00:00:00Z' },
{ workflowid: 'dupe', statecode: 1, createdon: '2026-01-01T00:00:05Z' },
]);
assert.ok(warnings.some((w) => /2 definitions exist with this name/.test(w)), JSON.stringify(warnings));
});
test('a flow that cannot be activated warns instead of halting the build', async () => {
// One wedged process must not block an otherwise-good app; `--verify` reports the real state.
const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();
const { provision } = provisionWithFlows([{ workflowid: 'w1', statecode: 0, createdon: '2026-01-01T00:00:00Z' }]);
provision.updateRecord = async () => { throw new Error('Invalid operation'); };
const warnings = [];
const res = await runSdkBuild(specWith([FLOW]), { sdk, provisionSdk: provision, apply: true, phases: ['business-process-flows'], warn: (m) => warnings.push(m) });
assert.strictEqual(res.ok, true, 'the build survives');
assert.ok(warnings.some((w) => /could not be activated/.test(w)), JSON.stringify(warnings));
});
test('a spec with no flows makes no workflow calls at all', async () => {
const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();
const { provision, calls } = provisionWithFlows([]);
const spec = specWith([]);
delete spec.businessProcessFlows;
await runSdkBuild(spec, { sdk, provisionSdk: provision, apply: true, phases: ['business-process-flows'] });
assert.strictEqual(calls.length, 0);
});
// --- 5. teardown --------------------------------------------------------------------------------
test('teardown removes each flow BEFORE the table it is bound to', async () => {
const steps = planTeardown(specWith([FLOW]));
const kinds = steps.map((s) => s.kind);
const flowAt = kinds.indexOf('businessProcessFlows');
assert.ok(flowAt > -1, `a flow step must be planned; got ${JSON.stringify(kinds)}`);
// The kind is SINGULAR (`table`) — planTeardown emits kind 'table' with phase 'tables'. Guarding on
// 'tables' made `tableAt` permanently -1, so the ordering assertion below never ran and moving BPF
// teardown after the table delete stayed green. Assert the index is real before comparing.
const tableAt = kinds.indexOf('table');
assert.ok(tableAt > -1, `a table step must be planned; got ${JSON.stringify(kinds)}`);
assert.ok(flowAt < tableAt, 'an activated flow is a workflow row bound to the entity — it cannot be left for the table delete to cascade');
assert.deepStrictEqual(steps[flowAt].target, { entity: 'new_ticket', name: 'Ticket Handling' });
});
test('teardown resolves a flow through bpfFilter and deactivates before deleting', async () => {
const handler = KIND_HANDLERS.businessProcessFlows;
const queries = [];
const ops = [];
const sdk = {
queryRecords: async (e, o) => { queries.push([e, o]); return [{ workflowid: 'w1', statecode: 1 }]; },
updateRecord: async (e, id, patch) => { ops.push(['update', id, patch]); },
deleteRecord: async (e, id) => { ops.push(['delete', id]); },
};
const items = await handler.resolve(sdk, { entity: 'new_ticket', name: 'Ticket Handling' });
assert.match(String(queries[0][1].filter), /category eq 4 and type eq 1 and businessprocesstype eq 0/);
assert.deepStrictEqual(items, [{ id: 'w1', name: 'Ticket Handling', statecode: 1 }]);
await handler.del(sdk, items[0]);
// Dataverse refuses to delete an ACTIVATED process, and the error names neither the flow nor why.
assert.deepStrictEqual(ops, [['update', 'w1', { statecode: 0, statuscode: 1 }], ['delete', 'w1']]);
assert.strictEqual(handler.tolerateNotFound, true, 'an already-gone flow is "deleted"');
});
test('teardown does not deactivate a flow that is already Draft', async () => {
const ops = [];
const sdk = {
queryRecords: async () => [{ workflowid: 'w1', statecode: 0 }],
updateRecord: async (e, id) => { ops.push(['update', id]); },
deleteRecord: async (e, id) => { ops.push(['delete', id]); },
};
const handler = KIND_HANDLERS.businessProcessFlows;
await handler.del(sdk, (await handler.resolve(sdk, { entity: 'new_ticket', name: 'X' }))[0]);
assert.deepStrictEqual(ops, [['delete', 'w1']]);
});
// --- 6. verify ----------------------------------------------------------------------------------
const flowReader = (workflows) => ({
findTable: async () => ({ logicalName: 'new_ticket' }),
findColumns: async () => [{ logicalName: 'new_subject' }, { logicalName: 'new_notes' }, { logicalName: 'new_owner' }, { logicalName: 'new_status' }],
queryRecords: async (entity) => (entity === 'workflow' ? workflows : []),
sitemapXml: async () => '',
});
const flowCheck = (r) => r.checks.find((c) => c.kind === 'business-process-flow');
const flowSpec = (status) => specWith([{ ...FLOW, ...(status ? { status } : {}) }]);
test('verify PASSES an Active flow the spec wants Active', async () => {
const c = flowCheck(await verifySpec(flowSpec(), flowReader([{ workflowid: 'w1', statecode: 1 }])));
assert.strictEqual(c.present, true);
});
test('verify FAILS a flow that never deployed', async () => {
const c = flowCheck(await verifySpec(flowSpec(), flowReader([])));
assert.strictEqual(c.present, false);
assert.match(c.detail, /not deployed/);
});
test('verify FAILS a flow deployed as Draft — "exists" is not "appears on the form"', async () => {
const c = flowCheck(await verifySpec(flowSpec(), flowReader([{ workflowid: 'w1', statecode: 0 }])));
assert.strictEqual(c.present, false);
assert.match(c.detail, /DRAFT/);
});
test('verify FAILS duplicates — users would be offered the same process twice', async () => {
const c = flowCheck(await verifySpec(flowSpec(), flowReader([{ workflowid: 'w1', statecode: 1 }, { workflowid: 'w2', statecode: 1 }])));
assert.strictEqual(c.present, false);
assert.match(c.detail, /2 process flows share this name/);
});
test('verify counts a flow the server repeats once, and never reads a read cut short as "deployed once"', async () => {
const same = { workflowid: 'w1', statecode: 1 };
assert.strictEqual(flowCheck(await verifySpec(flowSpec(), flowReader([same, { ...same }]))).present, true, 'one flow read twice is one flow');
// The SDK marks an answer that is not every row with a non-enumerable `hasMore`.
const partial = [same];
Object.defineProperty(partial, 'hasMore', { value: true, enumerable: false });
const r = await verifySpec(flowSpec(), flowReader(partial));
assert.strictEqual(flowCheck(r), undefined, 'neither a pass nor a failure');
assert.match((r.unverified || []).join('\n'), /^business-process-flow:new_ticket\..* \(the read answered 1 definition row\(s\) and said more exist/m);
});
test('verify FAILS an ACTIVE flow the spec asks to be Draft', async () => {
const c = flowCheck(await verifySpec(flowSpec('Draft'), flowReader([{ workflowid: 'w1', statecode: 1 }])));
assert.strictEqual(c.present, false);
assert.match(c.detail, /running/);
});
test('verify fails CLOSED when the workflow read itself errors', async () => {
// "Could not look" must never read as "present and correct".
const read = Object.assign(flowReader([]), {
queryRecords: async (entity) => { if (entity === 'workflow') throw new Error('HTTP 401'); return []; },
});
const c = flowCheck(await verifySpec(flowSpec(), read));
assert.strictEqual(c.present, false);
assert.match(c.detail, /could not be read/);
});
// --- 7. the spec diff SEES a flow change --------------------------------------------------------
//
// `PHASE_SLICES` is an explicit map, so a phase missing from it makes its slice invisible: the diff
// reports "nothing changed" and `--changed-only` classifies a real edit as a NO-OP and does nothing.
// business-rules was in exactly that state, which is why these assertions cover both phases.
const { diffPhases } = require('../lib/phase-diff.js');
const { classifyChanges } = require('../lib/classify-changes.js');
test('a flow-only edit is a real change, not a no-op', () => {
const prior = specWith([FLOW]);
// The added stage binds a real column. A field-less step is not a valid spec (the platform rejects
// an empty `datafieldname`), and a diff fixture that the validator would reject is a trap: it makes
// the test pass on input a build could never carry. Assert the fixture's validity so it stays honest.
const current = specWith([{ ...FLOW, stages: [...FLOW.stages, { name: 'Close', steps: [{ name: 'Sign off', field: 'new_status' }] }] }]);
assert.strictEqual(validateAppSpec(current, { profile: 'plan' }).ok, true, 'the diff fixture must itself be a valid spec');
assert.deepStrictEqual(diffPhases(current, prior), ['business-process-flows']);
});
test('a business-RULE-only edit is a real change too (the same map governs both)', () => {
const rule = { name: 'R', entity: 'new_ticket', conditions: [{ field: 'new_owner', operator: 'Equals', value: 'x' }], actions: [{ type: 'SetVisibility', field: 'new_notes', visible: false }] };
const prior = { ...specWith([]), businessRules: [rule] };
const current = { ...specWith([]), businessRules: [{ ...rule, actions: [{ type: 'SetVisibility', field: 'new_notes', visible: true }] }] };
assert.deepStrictEqual(diffPhases(current, prior), ['business-rules']);
});
test('an EDITED flow forces a full build, and records debt only for an edit the build refuses — it applies the rest in place', () => {
const prior = specWith([FLOW]);
// Renaming a stage and editing a step is applied in place (bpf-stage-edits.test.js): a full build, and nothing left behind.
const renamed = specWith([{ ...FLOW, stages: [{ name: 'Renamed', steps: [{ name: 'Subject', field: 'new_subject' }] }, FLOW.stages[1]] }]);
const applied = classifyChanges(renamed, prior);
assert.strictEqual(applied.verdict, 'full');
assert.ok(applied.fullReasons.some((x) => /business-process-flows.*stages changed — reconciled by a full build/.test(x)), JSON.stringify(applied.fullReasons));
assert.deepStrictEqual(applied.debt, []);
// Dropping a stage is refused (a record may sit on it), so a rebuild leaves the flow as it was — which is debt.
const dropped = specWith([{ ...FLOW, stages: [FLOW.stages[0]] }]);
const refused = classifyChanges(dropped, prior);
assert.strictEqual(refused.verdict, 'full');
assert.ok(refused.fullReasons.some((x) => /business-process-flows.*edited/.test(x)), JSON.stringify(refused.fullReasons));
assert.deepStrictEqual(refused.debt, [{ artifactType: 'businessProcessFlow', identity: 'new_ticket|Ticket Handling', reason: 'businessProcessFlow-edit-not-convergent' }]);
});
test('an ADDED flow forces a full build with NO debt — a full build creates it correctly', () => {
const prior = specWith([]);
const current = specWith([FLOW]);
const r = classifyChanges(current, prior);
assert.strictEqual(r.verdict, 'full');
assert.deepStrictEqual(r.debt, []);
});
// --- 6. regressions found by live-testing the feature ------------------------------------------
// Each block below guards a defect that ALREADY SHIPPED in the first cut of this feature. They are
// grouped here rather than scattered so the provenance stays attached to the assertion.
test('REGRESSION: an object-valued businessProcessFlows is a validation error, not a TypeError', () => {
// `businessProcessFlows` was missing from spec-shape COLLECTIONS, so a mid-edit object reached the
// phase`s for...of and threw `object is not iterable`. businessRules already handled this; the new
// collection repeated the mistake it documents.
const spec = specWith([FLOW]);
spec.businessProcessFlows = { name: 'X', entity: 'new_ticket', stages: [] };
let errs;
assert.doesNotThrow(() => { errs = validateAppSpec(spec, { profile: 'plan' }).errors || []; });
assert.ok(errs.some((e) => /businessProcessFlows must be an array/.test(e)), `got ${JSON.stringify(errs)}`);
});
test('REGRESSION: object-valued stages and steps are validation errors too', () => {
for (const [label, flow] of Object.entries({
stages: { ...FLOW, stages: { name: 'S' } },
steps: { ...FLOW, stages: [{ name: 'S', steps: { name: 'x' } }] },
})) {
const spec = specWith([flow]);
let errs;
assert.doesNotThrow(() => { errs = validateAppSpec(spec, { profile: 'plan' }).errors || []; }, `${label} threw`);
assert.ok(errs.length, `${label}: expected a validation error`);
}
});
test('REGRESSION: a non-string flow name is rejected before the SDK lower-cases it', () => {
// The SDK derives the unique name via `.toLowerCase()`, so a non-string died inside the bundle.
assert.ok(errorsFor([{ ...FLOW, name: {} }]).some((e) => /name must be a non-empty string/.test(e)));
assert.ok(errorsFor([{ ...FLOW, name: ' ' }]).some((e) => /name (is required|must be a non-empty string)/.test(e)));
});
test('REGRESSION: a non-string description is rejected', () => {
assert.ok(errorsFor([{ ...FLOW, description: {} }]).length, 'a non-string description must not reach the SDK');
});
test('REGRESSION: the SDK stage/step ceilings are enforced as spec errors', () => {
const many = (n) => Array.from({ length: n }, (_, i) => ({ name: `S${i}`, steps: [{ name: 'x', field: 'new_notes' }] }));
assert.deepStrictEqual(errorsFor([{ ...FLOW, stages: many(30) }]), [], '30 stages is allowed');
assert.ok(errorsFor([{ ...FLOW, stages: many(31) }]).some((e) => /at most 30/.test(e)), '31 stages must be rejected');
const steps = (n) => [{ name: 'S', steps: Array.from({ length: n }, (_, i) => ({ name: `Step${i}`, field: 'new_notes' })) }];
assert.deepStrictEqual(errorsFor([{ ...FLOW, stages: steps(30) }]), [], '30 steps is allowed');
assert.ok(errorsFor([{ ...FLOW, stages: steps(31) }]).some((e) => /at most 30 per stage/.test(e)), '31 steps must be rejected');
});
test('REGRESSION: a REUSED flow is still added to the solution', async () => {
// addSolutionComponent was only on the create path, so a flow created by an earlier run whose
// component add failed would be reused forever and never travel on export.
const { calls } = await buildFlow([{ workflowid: 'w-existing', statecode: 1, createdon: '2020-01-01T00:00:00Z' }]);
const added = calls.filter((c) => c[0] === 'addSolutionComponent');
assert.strictEqual(added.length, 1, `a reused flow must still be added to the solution; calls: ${JSON.stringify(calls.map((c) => c[0]))}`);
assert.strictEqual(added[0][1].componentId, 'w-existing');
});
test('REGRESSION: a failing solution add on the reuse path warns, it does not halt', async () => {
const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();
const { provision } = provisionWithFlows([{ workflowid: 'w-existing', statecode: 1, createdon: '2020-01-01T00:00:00Z' }]);
provision.addSolutionComponent = async () => { throw new Error('component add refused'); };
const warnings = [];
const res = await runSdkBuild(specWith([FLOW]), { sdk, provisionSdk: provision, apply: true, phases: ['business-process-flows'], warn: (m) => warnings.push(m) });
assert.strictEqual(res.ok, true, 'solution bookkeeping must not fail an otherwise-good build');
assert.ok(warnings.some((w) => /could not be added to solution/.test(w)), `got ${JSON.stringify(warnings)}`);
});
test('REGRESSION: a transport TIMEOUT on the flow delete is resolved by POLLING, not reported as failure', async () => {
// Deleting an activated BPF cascades a backing-TABLE drop, measured live at longer than the 60s
// client timeout on two of three runs. The server completes anyway, so reporting the timeout as a
// failure told the operator to clean up something already gone.
//
// The row is STILL PRESENT at the moment the client times out — a single re-read reproduces the
// false failure, which is exactly what the first version of this fix did. So the row here only
// disappears on the third probe.
const handler = KIND_HANDLERS.businessProcessFlows;
let queried = 0;
const sdk = {
queryRecords: async () => { queried++; return queried < 3 ? [{ workflowid: 'w1' }] : []; },
updateRecord: async () => {},
deleteRecord: async () => { throw new Error('Transport failure reaching https://example.crm.dynamics.com/api/data/v9.0/workflows(w1): Request failed: Request timed out'); },
};
const realDelay = global.setTimeout;
global.setTimeout = (fn) => realDelay(fn, 0); // keep the test fast; the polling shape is what matters
try {
await assert.doesNotReject(() => handler.del(sdk, { id: 'w1', statecode: 1 }));
} finally {
global.setTimeout = realDelay;
}
assert.ok(queried >= 3, `must keep polling until the row is gone; polled ${queried}x`);
});
test('REGRESSION: a probe that itself fails does not end the wait early', async () => {
const handler = KIND_HANDLERS.businessProcessFlows;
let queried = 0;
const sdk = {
queryRecords: async () => { queried++; if (queried < 3) throw new Error('probe blew up'); return []; },
updateRecord: async () => {},
deleteRecord: async () => { throw new Error('Request timed out'); },
};
const realDelay = global.setTimeout;
global.setTimeout = (fn) => realDelay(fn, 0);
try {
await assert.doesNotReject(() => handler.del(sdk, { id: 'w1', statecode: 1 }));
} finally {
global.setTimeout = realDelay;
}
assert.ok(queried >= 3, 'a failed probe is not evidence the row survived');
});
test('REGRESSION: a timeout is NOT swallowed when the row survives the whole wait', async () => {
const handler = KIND_HANDLERS.businessProcessFlows;
let queried = 0;
const sdk = {
queryRecords: async () => { queried++; return [{ workflowid: 'w1' }]; }, // never goes away: a real failure
updateRecord: async () => {},
deleteRecord: async () => { throw new Error('Request timed out'); },
};
const realDelay = global.setTimeout;
global.setTimeout = (fn) => realDelay(fn, 0);
try {
await assert.rejects(() => handler.del(sdk, { id: 'w1', statecode: 1 }), /timed out/);
} finally {
global.setTimeout = realDelay;
}
// The budget must be bounded by ATTEMPTS: a wall-clock deadline cannot be shortened by stubbing the
// sleep, so this exact case blocked the suite for four real minutes.
assert.ok(queried > 1 && queried <= 20, `polled a bounded number of times; got ${queried}`);
});
test('REGRESSION: a real HTTP error on delete is never re-read away', async () => {
const handler = KIND_HANDLERS.businessProcessFlows;
let queried = 0;
const sdk = {
queryRecords: async () => { queried++; return []; },
updateRecord: async () => {},
deleteRecord: async () => { throw new Error('HTTP 403 from .../workflows(w1): principal lacks prvDeleteWorkflow'); },
};
await assert.rejects(() => handler.del(sdk, { id: 'w1', statecode: 1 }), /403/);
assert.strictEqual(queried, 0, 'a status-carrying error means something specific and must not be second-guessed');
});
test('REGRESSION: a status-only edit is a full build but NOT permanent debt', () => {
// The build DOES converge status (the reuse branch flips statecode in both directions), so filing
// `-edit-not-convergent` debt claimed a divergence that a rebuild removes. Anything else about the
// flow genuinely is not reapplied, so it must still be recorded.
const { classifyChanges } = require('../lib/classify-changes.js');
const draft = specWith([{ ...FLOW, status: 'Draft' }]);
const active = specWith([{ ...FLOW, status: 'Active' }]);
const statusOnly = classifyChanges(active, draft);
assert.deepStrictEqual(statusOnly.debt, [], `a status-only edit is reconciled; got ${JSON.stringify(statusOnly.debt)}`);
assert.ok(statusOnly.changedPhases.includes('business-process-flows'), 'it still needs a full build');
assert.ok(statusOnly.fullReasons.some((r) => /status changed — reconciled/.test(r)), JSON.stringify(statusOnly.fullReasons));
// A stage edit the build REFUSES — two stages replaced by one, which it cannot tell from a removal — is NOT converged and must still be debt.
const restaged = specWith([{ ...FLOW, stages: [{ name: 'Only', steps: [{ name: 'S', field: 'new_notes' }] }] }]);
const stageEdit = classifyChanges(restaged, draft);
assert.ok(stageEdit.debt.some((d) => /edit-not-convergent/.test(d.reason)), `a stage edit is real debt; got ${JSON.stringify(stageEdit.debt)}`);
});
test('REGRESSION: a securityRoles-only edit is a full build but NOT permanent debt either (#513)', () => {
// Stronger than the `status` case above. A BPF grant always targets a PERSONA role, and the
// security phase applies persona roles with `ReplacePrivilegesRole` — so a rebuild both ADDS a
// newly-declared persona and REMOVES one that was dropped. Filing permanent debt disabled every
// later fast apply over a divergence a full build erases. (`roleGrants[]` would NOT qualify: it is
// additive and cannot revoke.)
const { classifyChanges } = require('../lib/classify-changes.js');
const withPersonas = (personas) => {
const s = specWith([personas ? { ...FLOW, securityRoles: { personas } } : { ...FLOW }]);
s.personas = [{ persona: 'Dispatcher', jobs: [{ name: 'J', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] }];
return s;
};
const none = withPersonas(null);
const granted = withPersonas(['Dispatcher']);
for (const [label, cur, prior] of [['added', granted, none], ['removed', none, granted]]) {
const r = classifyChanges(cur, prior);
assert.deepStrictEqual(r.debt, [], `securityRoles ${label} is reconciled; got ${JSON.stringify(r.debt)}`);
assert.ok(r.changedPhases.includes('business-process-flows'), `${label}: it still needs a full build`);
assert.ok(r.fullReasons.some((x) => /securityRoles changed — reconciled/.test(x)),
`${label}: and the reason must name the field that changed, not the whole converged list: ${JSON.stringify(r.fullReasons)}`);
}
});
test('REGRESSION: the same status-only rule applies to business rules', () => {
// Business rules converge status in their reuse branch too, so they shared the bug and the fix.
const { classifyChanges } = require('../lib/classify-changes.js');
const rule = (status) => ({
solution: { uniqueName: 'BPF', displayName: 'BPF', publisherPrefix: 'new' },
app: { name: 'BPF App', description: '' },
entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets', primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' } }],
appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'new_ticket', title: 'Tickets' }] }] }] },
businessRules: [{ name: 'R', entity: 'new_ticket', status, conditions: [], actions: [] }],
});
const r = classifyChanges(rule('Active'), rule('Draft'));
assert.deepStrictEqual(r.debt, [], `got ${JSON.stringify(r.debt)}`);
});
test('REAL BUNDLE: the 30-stage / 30-step ceilings match the SDK rule, not a magic number of ours', () => {
// MEASURED: neither `createArtifact` nor `pushArtifact` enforces these — both happily accept 31
// stages and 31 steps. The SDK's `too-many-stages` / `too-many-steps` rules live in a validator the
// plugin never calls, so the spec-level ceiling is the ONLY enforcement on the path we use. That
// makes it worth pinning, and it cannot be pinned behaviourally: assert the bundle still states the
// same number, so a re-vendor that changes the limit fails here rather than letting the spec quietly
// reject flows the platform would now accept (or accept ones it would not).
const bundle = fs.readFileSync(BUNDLE, 'utf8');
const stageRule = bundle.match(/a BPF allows at most (\d+) stages/);
const stepRule = bundle.match(/a stage allows at most (\d+) steps/);
assert.ok(stageRule, "the bundle no longer states a stage ceiling — re-check what the SDK enforces");
assert.ok(stepRule, "the bundle no longer states a step ceiling — re-check what the SDK enforces");
assert.strictEqual(Number(stageRule[1]), 30, 'the SDK stage ceiling changed; update BPF_MAX_STAGES');
assert.strictEqual(Number(stepRule[1]), 30, 'the SDK step ceiling changed; update BPF_MAX_STEPS');
// And the spec agrees with that number at exactly the boundary, in both directions.
const stages = (n) => Array.from({ length: n }, (_, i) => ({ name: `S${i}`, steps: [{ name: 'x', field: 'new_notes' }] }));
const steps = (n) => [{ name: 'S', steps: Array.from({ length: n }, (_, i) => ({ name: `P${i}`, field: 'new_notes' })) }];
assert.deepStrictEqual(errorsFor([{ ...FLOW, stages: stages(30) }]), [], 'the spec accepts the ceiling');
assert.ok(errorsFor([{ ...FLOW, stages: stages(31) }]).some((e) => /at most 30/.test(e)), 'and rejects one over');
assert.deepStrictEqual(errorsFor([{ ...FLOW, stages: steps(30) }]), []);
assert.ok(errorsFor([{ ...FLOW, stages: steps(31) }]).some((e) => /at most 30 per stage/.test(e)));
});
// --- the derived unique name is a TABLE name, not just a flow name ------------------------------
//
// Activating a flow makes the platform create an org-owned BACKING TABLE whose logical name is the
// flow's derived unique name (`new_` + the display name lower-cased with punctuation stripped —
// note the `new_` is fixed, it is NOT the solution's publisher prefix). The spec already rejects two
// flows that derive the same name, for exactly that reason.
//
// But the same collision exists against a TABLE, and that axis was unchecked: a flow named "Ticket"
// on a spec that also creates `new_ticket` derives `new_ticket`, validates clean, and then fails in
// the business-process-flows phase — after the solution, tables, columns, views, forms and the app
// have all been created. The maker is left with a half-built app and a platform error naming a
// table they did not think they were creating.
test('a flow whose derived unique name collides with a DECLARED TABLE is rejected', () => {
const { bpfUniqueName } = require('../lib/app-spec.js');
// Guard the premise, so this test cannot quietly stop testing anything if the derivation changes.
assert.strictEqual(bpfUniqueName('Ticket'), 'new_ticket',
'the premise of this test is that the derivation can produce a declared table name');
const res = validateAppSpec(specWith([{ ...FLOW, name: 'Ticket' }]), { profile: 'plan' });
assert.strictEqual(res.ok, false, 'this collision must not validate clean');
const err = (res.errors || []).find((e) => /new_ticket/.test(e) && /table/i.test(e));
assert.ok(err, `expected a table-collision error; got ${JSON.stringify(res.errors)}`);
// The message has to say what to do — the maker cannot rename the derivation, only the flow.
assert.match(err, /rename/i, `the error must tell the author how to resolve it; got: ${err}`);
});
test('the table collision is case- and punctuation-insensitive, like the derivation itself', () => {
for (const name of ['ticket', 'Ticket!', 'T I C K E T']) {
const res = validateAppSpec(specWith([{ ...FLOW, name }]), { profile: 'plan' });
assert.strictEqual(res.ok, false, `${JSON.stringify(name)} derives new_ticket and must be rejected`);
}
});
test('a flow name that does NOT collide still validates (the guard adds no false positive)', () => {
const res = validateAppSpec(specWith([{ ...FLOW, name: 'Ticket Handling' }]), { profile: 'plan' });
assert.strictEqual(res.ok, true, JSON.stringify(res.errors));
});
test('an EXISTING (not-created) table still collides — the backing table clashes either way', () => {
// `existing: true` means the build does not create the table, but it is still there in the org,
// and activation would still try to create a table with that logical name.
const spec = specWith([{ ...FLOW, name: 'Ticket' }]);
spec.entities[0].existing = true;
const res = validateAppSpec(spec, { profile: 'plan' });
assert.strictEqual(res.ok, false, 'a referenced table collides exactly like a created one');
});
// --- the derived unique name can collide with something the SPEC CANNOT SEE ---------------------
//
// The reuse query keys on (name, entity); the server keys on the derived unique name, which ignores
// the entity and strips case and punctuation. A rename that preserves the derived name, or a flow of
// the same derived name on another table, is therefore invisible to reuse and fails inside the
// create — with a platform error about a BACKING TABLE the author never mentioned.
function provisionWithUniqueClash({ clashRows, failUniqueQuery = false }) {
const calls = [];
return {
calls,
provision: {
queryRecords: async (entity, opts) => {
if (entity !== 'workflow') return entity === 'solution' ? [] : [{ publisherid: 'pub-1' }];
calls.push(['queryRecords', opts.filter]);
// The uniquename probe is the ONLY workflow query that filters on uniquename; the reuse
// query filters on name+primaryentity and must keep returning nothing so the create path runs.
if (/uniquename eq /.test(opts.filter || '')) {
if (failUniqueQuery) throw new Error('uniquename is not filterable here');
return clashRows;
}
return [];
},
updateRecord: async () => undefined,
deleteRecord: async () => undefined,
createArtifact: (kind, def) => { calls.push(['createArtifact', kind, def]); return { id: 'bpf-new' }; },
updateElement: async () => undefined,
pushArtifact: async (kind, id) => { calls.push(['pushArtifact', kind, id]); return { id: 'bpf-new', saved: true, publish: { kind: 'notRequested' } }; },
addSolutionComponent: async () => undefined,
},
};
}
test('a flow whose derived unique name is already taken HALTS instead of failing inside the create', async () => {
const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();
const { provision, calls } = provisionWithUniqueClash({
clashRows: [{ workflowid: 'other-1', name: 'ticket-handling', primaryentity: 'new_other' }],
});
const err = await runSdkBuild(specWith([FLOW]), {
sdk, provisionSdk: provision, apply: true, phases: ['business-process-flows'], warn: () => {},
}).then(() => null, (e) => e);
assert.ok(err, 'the collision must stop the build rather than be attempted');
assert.match(err.message, /ticket-handling/, `the halt must name the conflicting flow; got: ${err.message}`);
assert.match(err.message, /new_tickethandling/, 'and the derived name that actually collides');
assert.match(err.message, /new_other/, 'and the table it is on, so the author can find it');
assert.match(err.message, /[Rr]ename/, 'and what to do about it');
assert.strictEqual(calls.some((c) => c[0] === 'createArtifact'), false,
'nothing may be written once the collision is known');
});
test('the uniquename probe is BEST-EFFORT: a query it cannot run does not block the build', async () => {
// A diagnostic must never be the thing that breaks a build. If the probe cannot run, the create
// proceeds and the platform gets to speak for itself.
const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();
const { provision, calls } = provisionWithUniqueClash({ clashRows: [], failUniqueQuery: true });
await runSdkBuild(specWith([FLOW]), {
sdk, provisionSdk: provision, apply: true, phases: ['business-process-flows'], warn: () => {},
});
assert.ok(calls.some((c) => c[0] === 'createArtifact'), 'the flow is still created');
assert.ok(calls.some((c) => c[0] === 'pushArtifact'), 'and still pushed');
});
test('no clash means no interference — the create path is unchanged', async () => {
const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();
const { provision, calls } = provisionWithUniqueClash({ clashRows: [] });
await runSdkBuild(specWith([FLOW]), {
sdk, provisionSdk: provision, apply: true, phases: ['business-process-flows'], warn: () => {},
});
assert.ok(calls.some((c) => c[0] === 'createArtifact'), 'the flow is created');
// The probe must query the DERIVED name, not the display name — that is the whole point.
const probe = calls.find((c) => c[0] === 'queryRecords' && /uniquename eq /.test(c[1] || ''));
assert.ok(probe, `expected a uniquename probe; got ${JSON.stringify(calls.filter((c) => c[0] === 'queryRecords'))}`);
assert.match(probe[1], /uniquename eq 'new_tickethandling'/);
});
// --- the derived name can also be owned by a TABLE, not only by another flow --------------------
test('the build-time probe also refuses when a TABLE already owns the derived name', async () => {
// Activation creates a real table called `new_<derived>`. An unrelated table already holding that
// logical name blocks the flow just as surely as a rival flow does — and that table need not have
// come from any flow at all, so querying only `workflows` missed the commonest environment-side
// collision. Reported by peer review; the workflows-only probe let this reach the push and fail
// as an opaque "Entity ... already exists".
const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();
const { provision, calls } = provisionWithUniqueClash({ clashRows: [] });
provision.findTables = async () => ([{ logicalName: 'new_unrelated' }, { logicalName: 'new_tickethandling' }]);
const err = await runSdkBuild(specWith([FLOW]), {
sdk, provisionSdk: provision, apply: true, phases: ['business-process-flows'], warn: () => {},
}).then(() => null, (e) => e);
assert.ok(err, 'a table owning the derived name must stop the build');
assert.match(err.message, /new_tickethandling/, `the halt must name the derived value; got: ${err.message}`);
assert.match(err.message, /table/i, 'and say it is a TABLE that owns it, not a flow');
assert.strictEqual(calls.some((c) => c[0] === 'createArtifact'), false, 'nothing may be written');
});
test('the table probe is best-effort and absent-safe (an older transport has no findTables)', async () => {
const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();
for (const [label, mutate] of [
['absent', (p) => { delete p.findTables; }],
['throws', (p) => { p.findTables = async () => { throw new Error('metadata read refused'); }; }],
['no match', (p) => { p.findTables = async () => ([{ logicalName: 'new_something_else' }]); }],
]) {
const { provision, calls } = provisionWithUniqueClash({ clashRows: [] });
mutate(provision);
await runSdkBuild(specWith([FLOW]), {
sdk, provisionSdk: provision, apply: true, phases: ['business-process-flows'], warn: () => {},
});
assert.ok(calls.some((c) => c[0] === 'createArtifact'), `findTables ${label}: the flow is still created`);
}
});
test('a flow clash is reported as a FLOW and a table clash as a TABLE — the remedy differs', async () => {
const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();
const { provision } = provisionWithUniqueClash({
clashRows: [{ workflowid: 'other-1', name: 'ticket-handling', primaryentity: 'new_other' }],
});
// Both owners present: the flow is the more actionable one to name, and it is found first.
provision.findTables = async () => ([{ logicalName: 'new_tickethandling' }]);
const err = await runSdkBuild(specWith([FLOW]), {
sdk, provisionSdk: provision, apply: true, phases: ['business-process-flows'], warn: () => {},
}).then(() => null, (e) => e);
assert.ok(err);
assert.match(err.message, /the flow "ticket-handling"/, `got: ${err.message}`);
});