diff --git a/.changeset/38595-rename-flow-references.md b/.changeset/38595-rename-flow-references.md new file mode 100644 index 00000000000..d8f3f8347b8 --- /dev/null +++ b/.changeset/38595-rename-flow-references.md @@ -0,0 +1,12 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): a package copied under a new namespace calls its own flows + +Clause-②: no +Metadata-protocol: none + +A package copy under a new namespace (an `unmanaged` install with `targetNamespace`, or `duplicatePackage`) renames the package's flows, `crm_child` to `crm2_child`. The names that call those flows now follow them: a `subflow` step's `config.flowName`, a translation's `flows` keys, and an action's `target` when its executor is `flow` (`type: 'flow'` on an action or an API endpoint, `actionType: 'flow'` on an `action:button` or `action:icon` page block). Before, the copy kept the source's name: its step failed on every run with "Flow not found", or, with the source package still installed, ran the source's flow. + +A value is rewritten only when it is exactly the name of a flow the copy renames. A flow the package does not hold keeps its name, and so does a `target` beside any other executor. A renamed name that meets a name the item already holds there (a translation's `flows` keyed by both `crm_child` and `crm2_child`) refuses that item, as the same meeting does for an object name. Nothing an author writes changes. diff --git a/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts b/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts new file mode 100644 index 00000000000..dfeaa94f5b9 --- /dev/null +++ b/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts @@ -0,0 +1,310 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38595] A package copy under a new namespace renames its flows, and every + * name that calls them follows: a `subflow` step's `config.flowName` and a + * flow action's `target` name the COPY's flow, through both copy doors — the + * unmanaged import's `targetNamespace` (ADR-0131 D6) and `duplicatePackage` + * (ADR-0070 D4), which share the one rename engine + * (`package-namespace-rename.ts`). + * + * Before the fix the copy's step kept the source's name: with no such flow it + * failed on every run, and with the source still installed it called the + * SOURCE's flow. The automation service here answers `listFlows` so a publish + * gate that judges a step's called flow against the deployment has a + * non-empty universe; the pins read the stored rows, so they hold with that + * gate and without it. + * + * The harness (`makeEngine`, `crmBody`) is copied from + * `package-unmanaged-install.test.ts`: a stub engine that keeps real rows, so + * the REAL save door and the REAL copy doors run against it. + */ +// Pays the lint root's first load at collection, never inside a clocked case. +import './lint-root-preload.testkit.js'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { assertEngineDeleteDispatch, assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; +import { ObjectStackProtocolImplementation } from './protocol.js'; +import { resetEnvWritableMetadataTypes } from './sys-metadata-repository.js'; + +type Row = Record; + +/** Equality, `null` and `$in`; any other operator is refused, so a matcher that ignored one cannot prove anything. */ +function matches(row: Row, where: Record = {}): boolean { + for (const [key, want] of Object.entries(where)) { + if (want === undefined) continue; + if (key.startsWith('$')) throw new Error(`stub engine: unsupported operator ${key}`); + const have = row[key] ?? null; + if (want !== null && typeof want === 'object' && !Array.isArray(want)) { + const ops = Object.keys(want); + if (ops.length !== 1 || ops[0] !== '$in') throw new Error(`stub engine: unsupported operator ${ops.join(',')}`); + if (!(want as { $in: unknown[] }).$in.includes(have)) return false; + continue; + } + if (have !== want) return false; + } + return true; +} + +/** A stub engine that keeps rows, and a registry that keeps packages and namespaces. */ +function makeEngine(opts: { artifacts?: Array<{ type: string; name: string; packageId: string }>; owners?: Record } = {}) { + const tables = new Map(); + const table = (name: string) => { + if (!tables.has(name)) tables.set(name, []); + return tables.get(name)!; + }; + let nextId = 0; + const writes: Array<{ op: string; table: string }> = []; + const packages = new Map(); + const namespaces = new Map>( + Object.entries(opts.owners ?? {}).map(([ns, ids]) => [ns, new Set(ids)]), + ); + const artifacts = opts.artifacts ?? []; + // What the registry was handed — the body every read then serves. + const registered: Array<{ type: string; item: any }> = []; + const objects: Array<{ item: any; packageId: string }> = []; + const ddl: string[] = []; + const engine: any = { + async syncObjectSchema(name: any) { ddl.push(`sync ${typeof name === 'string' ? name : name?.name}`); }, + async dropObjectSchema(name: any) { ddl.push(`drop ${typeof name === 'string' ? name : name?.name}`); }, + async find(t: string, q?: { where?: Record; limit?: number }) { + const rows = table(t).filter((r) => matches(r, q?.where)); + // The caller's bound, after the filter, by presence — as the engine applies it. + return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows; + }, + async findOne(t: string, q: { where: Record }) { + assertEngineFindOnePredicate(t, q); + return table(t).find((r) => matches(r, q.where)) ?? null; + }, + // One record, or the batch the seed loader inserts a dataset in. + async insert(t: string, data: Row | Row[]): Promise { + const one = (record: Row) => { + writes.push({ op: 'insert', table: t }); + nextId += 1; + const row = { id: `r_${nextId}`, ...record }; + table(t).push(row); + return { ...row }; + }; + return Array.isArray(data) ? data.map(one) : one(data); + }, + async update(t: string, data: Row, q?: Record) { + assertEngineUpdateDispatch(data, q); + writes.push({ op: 'update', table: t }); + const where = (q as { where?: Record } | undefined)?.where; + const hit = table(t).filter((r) => matches(r, where)); + for (const r of hit) Object.assign(r, data); + return { id: hit[0]?.id ?? null }; + }, + async delete(t: string, q?: Record) { + assertEngineDeleteDispatch(q); + writes.push({ op: 'delete', table: t }); + const where = (q as { where?: Record } | undefined)?.where; + const keep = table(t).filter((r) => !matches(r, where)); + const deleted = table(t).length - keep.length; + tables.set(t, keep); + return { deleted }; + }, + registry: { + registerItem: (type: string, item: any) => { registered.push({ type, item }); }, + // The OBJECT schema every data and metadata read serves, and the + // package it is registered under. + registerObject: (item: any, packageId: string) => { objects.push({ item, packageId }); }, + unregisterItem: () => {}, + listItems: () => [], + getItem: () => undefined, + getObject: () => undefined, + getArtifactItem: (type: string, name: string) => { + const hit = artifacts.find((a) => a.type === type && a.name === name); + return hit ? { name, _packageId: hit.packageId } : undefined; + }, + getPackage: (id: string) => packages.get(id), + installPackage: (manifest: any) => { + const pkg = { manifest, status: 'installed', enabled: true }; + packages.set(manifest.id, pkg); + if (manifest.namespace) { + if (!namespaces.has(manifest.namespace)) namespaces.set(manifest.namespace, new Set()); + namespaces.get(manifest.namespace)!.add(manifest.id); + } + return pkg; + }, + uninstallPackage: (id: string) => { + const pkg = packages.get(id); + packages.delete(id); + if (pkg?.manifest?.namespace) namespaces.get(pkg.manifest.namespace)?.delete(id); + }, + getNamespaceOwners: (ns: string) => [...(namespaces.get(ns) ?? [])], + }, + }; + return { engine, table, writes, packages, registered, objects, ddl }; +} + +/** + * A protocol whose automation engine holds `engineFlows`, so a gate that + * judges a step's called flow against the deployment is not judging an empty + * universe. + */ +function makeProtocol(engineFlows: readonly string[] = ['other_flow']) { + const harness = makeEngine(); + const services = new Map([['automation', { listFlows: async () => [...engineFlows] }]]); + const protocol = new ObjectStackProtocolImplementation(harness.engine, () => services as Map) as any; + return { ...harness, protocol }; +} + +/** A small, schema-valid package body — an object, a view of it, and an app. */ +function crmBody(extra: Record = {}): Record { + return { + id: 'com.example.crm', + namespace: 'crm', + version: '4.0.0', + type: 'app', + name: 'CRM', + scope: 'cloud', + objects: [{ + name: 'crm_lead', + label: 'Lead', + sharingModel: 'private', + fields: { title: { type: 'text', label: 'Title' } }, + }], + views: [{ + name: 'crm_lead_open', + label: 'Open leads', + object: 'crm_lead', + viewKind: 'list', + columns: [{ field: 'title', label: 'Title' }], + }], + // Not this verb's: seeds are data, and the door states what it did with them. + data: [{ object: 'crm_lead', records: [{ title: 'First' }] }], + // An empty bundle list converts into no `translation` item. + translations: [], + i18n: { defaultLocale: 'en' }, + ...extra, + }; +} + +const ENV_KEYS = ['OS_TENANCY_POSTURE', 'OS_MULTI_ORG_ENABLED', 'OS_METADATA_WRITABLE'] as const; +const saved: Record = {}; +beforeEach(() => { + for (const k of ENV_KEYS) saved[k] = process.env[k]; + for (const k of ENV_KEYS) delete process.env[k]; + resetEnvWritableMetadataTypes(); +}); +afterEach(() => { + for (const k of ENV_KEYS) { + if (saved[k] === undefined) delete process.env[k]; + else process.env[k] = saved[k]; + } + resetEnvWritableMetadataTypes(); +}); + +/** A flow; with `calls`, its one step is a `subflow` calling that flow by name. */ +const flow = (name: string, calls?: string) => ({ + name, + label: name, + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + ...(calls !== undefined ? [{ id: 'call', type: 'subflow', label: 'Call', config: { flowName: calls } }] : []), + ], + edges: calls !== undefined ? [{ id: 'e1', source: 'start', target: 'call' }] : [], +}); + +/** The package the card names: a flow calling a sibling, a flow action naming it, and a control action. */ +const callerBody = (flows = [flow('crm_parent', 'crm_child'), flow('crm_child')]) => crmBody({ + flows, + actions: [ + { name: 'crm_run_child', label: 'Run child', objectName: 'crm_lead', type: 'flow', target: 'crm_child' }, + // CONTROL: the same string as the target of another executor names no flow. + { name: 'crm_open_child', label: 'Open child', objectName: 'crm_lead', type: 'modal', target: 'crm_child' }, + ], +}); + +/** Every active row of one package: `type/name` → its stored body. */ +const itemsOf = (table: (name: string) => Row[], packageId: string): Record => Object.fromEntries( + table('sys_metadata') + .filter((r) => r.package_id === packageId && r.state === 'active') + .map((r) => [`${r.type}/${r.name}`, typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata]) + .sort(([a], [b]) => String(a).localeCompare(String(b))), +); + +/** The flow a stored flow's `subflow` step calls. */ +const calledBy = (body: any): unknown => body?.nodes?.find((n: any) => n?.type === 'subflow')?.config?.flowName; + +describe('importUnmanagedPackage with `targetNamespace` — the copy\'s callers name the copy\'s flows (#38595)', () => { + it('installs, and the stored `crm2_parent` calls `crm2_child`', async () => { + const { protocol, table } = makeProtocol(); + const result = await protocol.importUnmanagedPackage({ manifest: callerBody(), targetNamespace: 'crm2' }); + expect(result.copied.filter((c: { type: string }) => c.type === 'flow').map((c: { name: string }) => c.name).sort()) + .toEqual(['crm2_child', 'crm2_parent']); + const items = itemsOf(table, 'com.example.crm-copy'); + expect(Object.keys(items).filter((k) => k.startsWith('flow/'))).toEqual(['flow/crm2_child', 'flow/crm2_parent']); + expect(calledBy(items['flow/crm2_parent'])).toBe('crm2_child'); + }); + + it('a copied flow action\'s `target` names the copy\'s flow; a non-flow action\'s equal `target` keeps it (CONTROL)', async () => { + const { protocol, table } = makeProtocol(); + await protocol.importUnmanagedPackage({ manifest: callerBody(), targetNamespace: 'crm2' }); + const items = itemsOf(table, 'com.example.crm-copy'); + expect(items['action/crm2_run_child']).toMatchObject({ objectName: 'crm2_lead', type: 'flow', target: 'crm2_child' }); + expect(items['action/crm2_open_child']).toMatchObject({ objectName: 'crm2_lead', type: 'modal', target: 'crm_child' }); + }); + + it('with the source package\'s `crm_child` still installed, the copy calls its own `crm2_child`, never the source\'s', async () => { + const { protocol, table } = makeProtocol(['other_flow', 'crm_child']); + // The source, installed under its own names. + await protocol.importUnmanagedPackage({ manifest: callerBody(), targetPackageId: 'com.example.crm-base' }); + expect(calledBy(itemsOf(table, 'com.example.crm-base')['flow/crm_parent'])).toBe('crm_child'); + // The copy, beside it. + await protocol.importUnmanagedPackage({ + manifest: callerBody(), targetPackageId: 'com.example.crm2', targetNamespace: 'crm2', + }); + const copy = itemsOf(table, 'com.example.crm2'); + expect(calledBy(copy['flow/crm2_parent'])).toBe('crm2_child'); + expect(copy['action/crm2_run_child'].target).toBe('crm2_child'); + }); + + it('CONTROL: a flow the package does not hold keeps its name', async () => { + const { protocol, table } = makeProtocol(); + await protocol.importUnmanagedPackage({ + manifest: callerBody([flow('crm_parent', 'other_flow'), flow('crm_child')]), targetNamespace: 'crm2', + }); + expect(calledBy(itemsOf(table, 'com.example.crm-copy')['flow/crm2_parent'])).toBe('other_flow'); + }); +}); + +describe('duplicatePackage — the same items as the import: the copy\'s callers name the copy\'s flows (#38595)', () => { + // The called flow is stored first, so the copy loop writes it before its caller. + const body = () => callerBody([flow('crm_child'), flow('crm_parent', 'crm_child')]); + + it('the duplicate\'s `crm2_parent` calls `crm2_child` and its flow action names it, the source staying installed', async () => { + const viaDuplicate = makeProtocol(['other_flow', 'crm_child', 'crm_parent']); + await viaDuplicate.protocol.importUnmanagedPackage({ manifest: body(), targetPackageId: 'com.example.crm-base' }); + const duplicated = await viaDuplicate.protocol.duplicatePackage({ + sourcePackageId: 'com.example.crm-base', targetPackageId: 'com.example.crm2', targetNamespace: 'crm2', + }); + expect(duplicated.failed).toEqual([]); + const copy = itemsOf(viaDuplicate.table, 'com.example.crm2'); + expect(calledBy(copy['flow/crm2_parent'])).toBe('crm2_child'); + expect(copy['action/crm2_run_child'].target).toBe('crm2_child'); + expect(copy['action/crm2_open_child'].target).toBe('crm_child'); + // The source is untouched: it still calls its own flow. + expect(calledBy(itemsOf(viaDuplicate.table, 'com.example.crm-base')['flow/crm_parent'])).toBe('crm_child'); + }); + + it('parity: the duplicate and the import into the same namespace store identical flows and actions', async () => { + const viaDuplicate = makeProtocol(['other_flow', 'crm_child', 'crm_parent']); + await viaDuplicate.protocol.importUnmanagedPackage({ manifest: body(), targetPackageId: 'com.example.crm-base' }); + await viaDuplicate.protocol.duplicatePackage({ + sourcePackageId: 'com.example.crm-base', targetPackageId: 'com.example.crm2', targetNamespace: 'crm2', + }); + const viaImport = makeProtocol(); + await viaImport.protocol.importUnmanagedPackage({ manifest: body(), targetPackageId: 'com.example.crm2', targetNamespace: 'crm2' }); + const pick = (items: Record) => Object.fromEntries( + Object.entries(items).filter(([k]) => k.startsWith('flow/') || k.startsWith('action/')), + ); + const imported = pick(itemsOf(viaImport.table, 'com.example.crm2')); + expect(Object.keys(imported)).toEqual([ + 'action/crm2_open_child', 'action/crm2_run_child', 'flow/crm2_child', 'flow/crm2_parent', + ]); + expect(pick(itemsOf(viaDuplicate.table, 'com.example.crm2'))).toEqual(imported); + }); +}); diff --git a/packages/metadata-protocol/src/package-namespace-rename.test.ts b/packages/metadata-protocol/src/package-namespace-rename.test.ts index f57c27752d3..2e775ecbe05 100644 --- a/packages/metadata-protocol/src/package-namespace-rename.test.ts +++ b/packages/metadata-protocol/src/package-namespace-rename.test.ts @@ -323,3 +323,102 @@ describe('planNamespaceRename — a copied capability, and every grant and requi }); }); + +describe('planNamespaceRename — a flow name follows the flow, at every site that calls it (#38595)', () => { + const subflow = (name: string, calls: string) => ({ + name, label: name, type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'call', type: 'subflow', label: 'Call', config: { flowName: calls } }, + ], + edges: [{ id: 'e1', source: 'start', target: 'call' }], + }); + const flowItems: NamespaceRenameItem[] = [ + ...items, + { type: 'flow', name: 'crm_parent', body: subflow('crm_parent', 'crm_child') }, + { type: 'flow', name: 'crm_child', body: { name: 'crm_child', label: 'Child', type: 'autolaunched', nodes: [], edges: [] } }, + // The prefix swap keeps a flow without the source prefix, so nothing names it anew. + { type: 'flow', name: 'bare_child', body: { name: 'bare_child', label: 'Bare', type: 'autolaunched', nodes: [], edges: [] } }, + ]; + const plan = (targetNamespace = 'crm2', list = flowItems) => planNamespaceRename({ + sourcePackageId: 'com.example.crm', sourceNamespace: 'crm', targetNamespace, items: list, retryVerb: 'install', + }); + const itemOf = (out: unknown) => (out as { item: any }).item; + + it('a subflow step\'s `config.flowName` naming a package flow takes that flow\'s copy name', () => { + const rename = plan(); + expect(rename.copyName('flow', 'crm_child')).toBe('crm2_child'); + const parent = itemOf(rename.rewrite('flow', 'crm_parent', flowItems[3]!.body)); + expect(parent.name).toBe('crm2_parent'); + expect(parent.nodes[1].config.flowName).toBe('crm2_child'); + // The edge's `target` is a node id, not a flow: it is never a flow site. + expect(parent.edges[0]).toEqual({ id: 'e1', source: 'start', target: 'call' }); + }); + + it('CONTROL: a flow the package does not hold keeps its name, and so does one the prefix swap keeps', () => { + const rename = plan(); + expect(itemOf(rename.rewrite('flow', 'crm_parent', subflow('crm_parent', 'other_flow'))).nodes[1].config.flowName) + .toBe('other_flow'); + expect(itemOf(rename.rewrite('flow', 'crm_parent', subflow('crm_parent', 'bare_child'))).nodes[1].config.flowName) + .toBe('bare_child'); + // Never a substring: a name that merely contains a renamed flow's is another name. + expect(itemOf(rename.rewrite('flow', 'crm_parent', subflow('crm_parent', 'crm_child_v2'))).nodes[1].config.flowName) + .toBe('crm_child_v2'); + }); + + it('a flow action\'s `target` follows the flow; a `target` beside any other executor does not (CONTROL)', () => { + const rename = plan(); + const flowAction = itemOf(rename.rewrite('action', 'crm_run_child', { + name: 'crm_run_child', objectName: 'crm_lead', type: 'flow', target: 'crm_child', + })); + expect(flowAction).toMatchObject({ name: 'crm2_run_child', objectName: 'crm2_lead', type: 'flow', target: 'crm2_child' }); + for (const type of ['modal', 'script', 'api']) { + const other = itemOf(rename.rewrite('action', 'crm_open_child', { + name: 'crm_open_child', objectName: 'crm_lead', type, target: 'crm_child', + })); + expect(other.target).toBe('crm_child'); + } + }); + + it('the same `target` rule holds wherever an action sits: an object\'s actions, an API endpoint, a page action block', () => { + const rename = plan(); + const object = itemOf(rename.rewrite('object', 'crm_lead', { + name: 'crm_lead', fields: {}, actions: [{ name: 'run', type: 'flow', target: 'crm_child' }, { name: 'open', type: 'modal', target: 'crm_child' }], + })); + expect(object.actions.map((a: any) => a.target)).toEqual(['crm2_child', 'crm_child']); + const api = itemOf(rename.rewrite('api', 'crm_run', { name: 'crm_run', path: '/api/v1/apps/crm/run', method: 'POST', type: 'flow', target: 'crm_child' })); + expect(api.target).toBe('crm2_child'); + // On a page block `type` is the component, so the executor is `actionType`. + const page = itemOf(rename.rewrite('page', 'crm_home', { + name: 'crm_home', + regions: [{ components: [ + { type: 'action:button', properties: { label: 'Run', actionType: 'flow', target: 'crm_child' } }, + { type: 'action:button', properties: { label: 'Go', actionType: 'url', target: '/crm_child' } }, + ] }], + })); + expect(page.regions[0].components.map((c: any) => c.properties.target)).toEqual(['crm2_child', '/crm_child']); + }); + + it('a translation\'s `flows` keys follow the flows — the index\'s second flow site', () => { + const rename = plan(); + const bundle = itemOf(rename.rewrite('translation', 'crm_en', { + name: 'crm_en', locale: 'en', flows: { crm_child: { label: 'Child' }, other_flow: { label: 'Other' } }, + })); + expect(bundle.flows).toEqual({ crm2_child: { label: 'Child' }, other_flow: { label: 'Other' } }); + }); + + it('a renamed flow name meeting one the item already holds there is refused, never merged — as for an object', () => { + const out = plan().rewrite('translation', 'crm_en', { + name: 'crm_en', locale: 'en', flows: { crm_child: { label: 'Child' }, crm2_child: { label: 'Copy' } }, + }); + expect((out as { refusal: string }).refusal).toMatch( + /^Translation 'crm_en' is not copied: its `flows` key 'crm_child' follows the copied flow to 'crm2_child', a key it already holds there/, + ); + }); + + it('CONTROL: a copy that keeps the source namespace renames no flow and rewrites no call', () => { + const rename = plan('crm'); + expect(rename.copyName('flow', 'crm_child')).toBe('crm_child'); + expect(itemOf(rename.rewrite('flow', 'crm_parent', flowItems[3]!.body)).nodes[1].config.flowName).toBe('crm_child'); + }); +}); diff --git a/packages/metadata-protocol/src/package-namespace-rename.ts b/packages/metadata-protocol/src/package-namespace-rename.ts index 0bd58b7141d..e90813508b9 100644 --- a/packages/metadata-protocol/src/package-namespace-rename.ts +++ b/packages/metadata-protocol/src/package-namespace-rename.ts @@ -94,7 +94,8 @@ export interface NamespaceRename { */ copyNameRefusal(type: string, name: string): string | undefined; /** - * The body as the copy writes it: every name the copy renames rewritten, + * The body as the copy writes it: every name the copy renames rewritten + * (an object's, and a flow's at the sites that call a flow, #38595), * `name` set to {@link copyName}, a permission set's field-rule keys * following the renamed objects — or the collision that refuses it. * `item` is the body converted to today's protocol; `name` is its SOURCE @@ -138,6 +139,21 @@ function isCapabilityType(type: string): boolean { return (PLURAL_TO_SINGULAR[String(type)] ?? String(type)) === 'capability'; } +/** A `flow` row, in either spelling of the type. */ +function isFlowType(type: string): boolean { + return (PLURAL_TO_SINGULAR[String(type)] ?? String(type)) === 'flow'; +} + +/** + * [#38595] The keys that name an action's EXECUTOR beside its `target`: `type` + * on an action (`ActionSchema`, an inline action, an `action:group` member, an + * API endpoint), `actionType` on an `action:button` / `action:icon` page block, + * whose `type` is the component itself. When the executor is `'flow'`, the + * `target` is a flow name ("the flow name to invoke", `ActionSchema`'s + * docblock), so it is a flow reference site. See `flowTargetSite` below. + */ +const FLOW_EXECUTOR_KEYS = ['type', 'actionType'] as const; + /** * [#35157] The keys a body names capabilities under: a permission set GRANTS * them (`systemPermissions`) and a resource REQUIRES them @@ -463,10 +479,58 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam const objectReferenceProperties = new Set( (REFERENCE_SITES.byTarget.get('object') ?? []).map((site) => site.property), ); - type ReferenceCollision = { at: string; shape: 'key' | 'entry'; moved: string; met: string }; - const deepRewrite = (v: any, collisions: ReferenceCollision[], atReference = false, at = ''): any => { + + // [#38595] ⭐ A FLOW NAME FOLLOWS THE FLOW, AS AN OBJECT NAME FOLLOWS THE + // OBJECT. A package flow is copied under the prefix swap (`crm_child` → + // `crm2_child`), and a flow is called by name: a `subflow` step's + // `config.flowName`, a flow action's `target`. Left as written, the copy's + // step called `crm_child` — a flow no copy holds, so every run failed, or, + // with the source package still installed, the SOURCE's flow. So every + // value that names a flow this copy renames is rewritten to the copy's + // name, whole and only whole, at a flow reference site: the derived index's + // `flow` sites (`REFERENCE_SITES`, target `flow`: `flowName`, a + // translation's `flows` keys), read by property wherever it occurs, as the + // object sites are, since a node config is declared by a node descriptor + // the index reaches only through that property. A flow the package does + // not hold, or one the prefix swap keeps (no source prefix), is not + // renamed, so every name of it stays as written. A name that is not a + // renamed flow's falls through to the rules every string takes, so + // nothing that read the same before reads differently now. + // + // ⛔ REFUSED, NEVER MERGED, exactly as at an object site: a renamed flow + // name meeting one the item already holds there (a translation's `flows` + // keyed by both `crm_child` and `crm2_child`) is a collision. + const flowRenames = new Map(); + for (const item of items) { + if (!isFlowType(item?.type) || typeof item.name !== 'string') continue; + const nn = renameName(item.name); + if (nn !== item.name) flowRenames.set(item.name, nn); + } + const flowReferenceProperties = new Set( + (REFERENCE_SITES.byTarget.get('flow') ?? []).map((site) => site.property), + ); + type ReferenceSiteRename = { readonly noun: 'object' | 'flow'; readonly renames: ReadonlyMap }; + const OBJECT_SITE: ReferenceSiteRename = { noun: 'object', renames: renameMap }; + const FLOW_SITE: ReferenceSiteRename = { noun: 'flow', renames: flowRenames }; + // ⚠️ THE ONE HAND-WRITTEN FLOW SITE: an action's `target` when its + // executor is `'flow'` ({@link FLOW_EXECUTOR_KEYS}). The derived index + // cannot carry it — `target` names a URL, a script, a page, an endpoint + // or a form on the other executors, so a property-wide site would rewrite + // those too, and its "Used by" answer (`findReferencesToMeta`) would list + // them as flow references. The site is keyed on the declared shape, the + // `target` beside a `'flow'` executor in one object, and nothing else. + const flowTargetSite = (node: Record, key: string): ReferenceSiteRename | undefined => + key === 'target' && typeof node.target === 'string' + && FLOW_EXECUTOR_KEYS.some((executor) => node[executor] === 'flow') + ? FLOW_SITE + : undefined; + const referenceSiteOf = (key: string): ReferenceSiteRename | undefined => + objectReferenceProperties.has(key) ? OBJECT_SITE : flowReferenceProperties.has(key) ? FLOW_SITE : undefined; + + type ReferenceCollision = { at: string; shape: 'key' | 'entry'; noun: 'object' | 'flow'; moved: string; met: string }; + const deepRewrite = (v: any, collisions: ReferenceCollision[], site?: ReferenceSiteRename, at = ''): any => { if (typeof v === 'string') { - const whole = atReference ? renameMap.get(v) : undefined; + const whole = site ? site.renames.get(v) : undefined; if (whole !== undefined) return whole; const viewItem = viewItemRenames.get(v); if (viewItem !== undefined) return viewItem; @@ -484,8 +548,8 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam return last === 0 ? objectPass(v) : out + objectPass(v.slice(last)); } if (Array.isArray(v)) { - const out = v.map((element, i) => deepRewrite(element, collisions, atReference, `${at}[${i}]`)); - if (atReference) { + const out = v.map((element, i) => deepRewrite(element, collisions, site, `${at}[${i}]`)); + if (site) { const firstAt = new Map(); out.forEach((element, i) => { if (typeof element !== 'string') return; @@ -493,7 +557,7 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam if (j === undefined) { firstAt.set(element, i); } else if (v[j] !== v[i]) { - collisions.push({ at, shape: 'entry', moved: v[i] !== element ? v[i] : v[j], met: element }); + collisions.push({ at, shape: 'entry', noun: site.noun, moved: v[i] !== element ? v[i] : v[j], met: element }); } }); } @@ -503,10 +567,10 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam const o: any = {}; const from = new Map(); for (const [k, val] of Object.entries(v)) { - const key = atReference ? (renameMap.get(k) ?? k) : k; + const key = site ? (site.renames.get(k) ?? k) : k; const other = from.get(key); if (other !== undefined) { - collisions.push({ at, shape: 'key', moved: key === k ? other : k, met: key }); + collisions.push({ at, shape: 'key', noun: site?.noun ?? 'object', moved: key === k ? other : k, met: key }); } from.set(key, k); if (CAPABILITY_REFERENCE_KEYS.has(k)) { @@ -515,7 +579,7 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam } const entry = deepRewrite( val, collisions, - objectReferenceProperties.has(k) || (atReference && k === 'name'), + referenceSiteOf(k) ?? (site && k === 'name' ? site : flowTargetSite(v, k)), at ? `${at}.${k}` : k, ); // ⭐ A RECORD ENTRY'S `name` FOLLOWS ITS KEY. An entry that @@ -540,7 +604,7 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam return v; }; const describeCollision = (c: ReferenceCollision): string => - `its \`${c.at}\` ${c.shape} '${c.moved}' follows the copied object to '${c.met}', ` + `its \`${c.at}\` ${c.shape} '${c.moved}' follows the copied ${c.noun} to '${c.met}', ` + `${c.shape === 'key' ? 'a key' : 'an entry'} it already holds there, which this copy does not rename. ` + (c.shape === 'key' ? 'A record keeps one entry per key, so the copy would drop one of the two. ' diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 59522064a98..d376134e2ba 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -301,6 +301,21 @@ "verb": "update", "pinned": 4 }, + { + "file": "packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/package-unmanaged-install.test.ts", "verb": "delete",