diff --git a/.changeset/35524-bare-save-follows-base-dependent-member.md b/.changeset/35524-bare-save-follows-base-dependent-member.md new file mode 100644 index 00000000000..97915932282 --- /dev/null +++ b/.changeset/35524-bare-save-follows-base-dependent-member.md @@ -0,0 +1,19 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol)!: a save naming no package, at a bundle member only a dependent package holds, writes the base package's row the read naming no package addresses + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a caller that saves, publishes or discards a bundled type's item (today `email_template`) without naming a package, where an authored base package holds the item's canonical member as a stored row, an authored package that declares the base holds a stored row of another member (for example `fr-FR`), and the base holds no row of that member. The read naming no package already takes the base's address at that member and answers `404`. + +- FROM: the save naming no package (REST `PUT` and in process, `active` mode) rewrote the dependent's row at that member, and the read naming no package then still answered `404` (or `409 RESOURCE_CONFLICT` where the rows had been stored after boot). The `draft` save wrote the dependent's draft; the draft read, per-item publish and draft discard naming no package read, promoted or removed the dependent's draft. +- TO: the save naming no package writes the base's row (or, in `draft` mode, the base's draft) at that member, exactly as the same save naming the base (`?package=BASE`, `packageId: BASE`) does; the dependent's row is left byte-unchanged, and the next read naming no package serves the saved content (`200`). The draft read, per-item publish and draft discard naming no package act on the base's draft there. With only the dependent's draft stored at that member, the per-item publish naming no package answers `404 NO_DRAFT` naming that draft, and the draft discard naming no package discards nothing and says which draft remains, as the same requests naming the base answer. + +**Not moved.** The canonical member (a base and its dependent both holding it, or only the dependent holding it), two packages neither of which declares the other, a base that ships the name in code, and the delete, history, diff and rollback naming no package at this member. + +The fix for a caller: to change the dependent's row or draft at that member, name the dependent (`?package=DEPENDENT` on the REST door, `packageId` in process). diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 14dd06ccaa6..c9d9c3f2268 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -869,7 +869,16 @@ export class ProtocolSaveFacet { host, 'save', request.type, writeType, request.name, itemDiscriminator(writeType, request.item), address, ); if (holderRefusal) throw holderRefusal; - if (address.packageId !== null) request = { ...request, packageId: address.packageId }; + // [#35524] …and a named non-canonical member only a dependent + // holds, where the read naming no package takes the row-held + // base's address: the base's row, as the save naming the base + // writes it ({@link packagelessRowHeldBaseAddress}), never the + // dependent's row the read does not serve there. + const base = address.candidates.length === 1 + ? await packagelessRowHeldBaseAddress(host, writeType, request.name, member) + : undefined; + const resolved = base ?? address.packageId; + if (resolved !== null) request = { ...request, packageId: resolved }; } } @@ -901,8 +910,11 @@ export class ProtocolSaveFacet { // draft save's inherited package (the named-base rule and the late // override re-judgment): the base is judged exactly as the save // naming it is, an id no installed package has refused `422`. + // [#35524] …and the same where the active rows at the member are bound + // to the one dependent whose addition the read naming no package does + // not serve (it takes the base's address there): the base's draft. let followedBase: string | undefined; - if (draftAddress?.kind === 'ambiguous') { + if (draftAddress !== undefined && (draftAddress.kind === 'ambiguous' || draftAddress.into !== null)) { const base = await packagelessRowHeldBaseAddress( host, singularType, request.name, itemDiscriminator(singularType, request.item), ); @@ -3247,18 +3259,28 @@ export function disabledHoldersOnlyRefusal( * that base does, and every dependent's row stays where it is, read and * written at its own `?package=`. * - * Asked only where those doors would refuse naming two or more packages, and - * answered over the item's ACTIVE rows at `member`, as the read judges them: + * Asked where those doors would refuse naming two or more packages, and + * [#35524] by the save (publish and draft mode) and the draft doors' + * address ({@link packagelessRowHeldBaseDraftAddress}) where the rows are + * bound to one package; answered over the item's ACTIVE rows at `member`, as + * the read judges them: * * - the base, when two or more packages hold a row there, none of them * package-less (#33210: a package-less row beside them is a customization * of no one holder, and the refusal stands), and one is the row-held base; - * - `undefined` otherwise, and the door refuses as before: a type with no + * - [#35524] the base, when one dependent holds the only row there, at a + * named non-canonical member the base holds no row of: the read takes the + * base's address there (and answers 404 until the base holds a row), so + * the bare save writes the base's row or draft, as the save naming the + * base does, and the next bare read serves it. The canonical member stays + * the dependent's, as the read serves it (#33210 contract review S1); + * - `undefined` otherwise, and the door answers as before: a type with no * members (#34441 contract review M1: no bundle additions), a name a * package ships, holders with no base relation, a disabled holder (the - * served-holder judgment's), and a member the base holds no row of (the - * read takes the base's address there and answers 404; that cell is not - * moved here). + * served-holder judgment's), and, of the one-holder cell, the base's own + * row. The bare delete, history, diff and rollback ask only with two or + * more holders, so at the one-holder cell they still act on the + * dependent's row. * * FROM (`main` 8596c80eda): each of those doors refused `409 * RESOURCE_CONFLICT` naming the base and the dependent while the read @@ -3285,9 +3307,48 @@ export async function packagelessRowHeldBaseAddress( return undefined; } const address = await host.packagelessAddress(singular, name, member, 'active', activeRows); - if (address.candidates.length < 2 || address.unbound) return undefined; + if (address.candidates.length === 0 || address.unbound) return undefined; const base = await rowHeldBaseAddressOf(host, singular, name, member, activeRows); - return base !== undefined && address.candidates.includes(base) ? base : undefined; + if (base === undefined) return undefined; + // [#35524] Two or more holders at the member: the base is one of them. One + // holder: a dependent's addition the base holds no row of, where the read + // takes the base's address (`rowHeldBaseAddressOf`'s S1-guarded arm). + return address.candidates.includes(base) === address.candidates.length > 1 ? base : undefined; +} + +/** + * [#35524, epic ruling 6781691009, #34348 ruling (b)] THE DRAFT ADDRESS the + * draft doors naming no package take (the draft save, the strict draft read, + * the per-item publish and the draft discard, through + * `packagelessDraftAddress`), at a named non-canonical member whose active + * rows are bound to one dependent only, where the read naming no package + * takes the row-held base's address ({@link packagelessRowHeldBaseAddress}): + * that base's draft, promoted into the base's row, as the same request naming + * the base addresses it. So the draft a bare draft save writes there is the + * draft the bare draft read, publish and discard act on, and the dependent's + * draft is read, published and discarded at its own `?package=`. + * + * `pending` (the draft address the stored rows give) itself otherwise: an ambiguous address (the doors ask + * {@link packagelessRowHeldBaseAddress} for it themselves, #34681), an address + * not bound to a package by the active rows, and every cell that judgment + * declines. + * + * FROM (`main` a73edb3cd7): the bare draft save wrote the dependent's draft + * there and the bare publish promoted it into the dependent's row, while the + * bare read at the member answered 404 (the base's address). + */ +export async function packagelessRowHeldBaseDraftAddress( + host: Pick, + type: string, + name: string, + member: string | undefined, + pending: ReturnType, +): Promise>> { + const address = await pending; + if (address.kind === 'ambiguous' || address.into === null) return address; + const base = await packagelessRowHeldBaseAddress(host, type, name, member); + if (base === undefined) return address; + return { kind: address.drafts.candidates.includes(base) ? 'draft' : 'none', key: base, into: base, drafts: address.drafts }; } /** diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 4db04119c5b..c672534b9fe 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -619,7 +619,7 @@ import { ProtocolWriteGatesTables } from './protocol-write-gates-tables.js'; import { ProtocolRegistryHydrationFacet, type ObjectRegistryRefusal, type RegistryHealStop, type RegistryWriteThroughRequest } from './protocol-registry-hydration.js'; import type { HealPackageBinding } from './protocol-heal-binding.js'; // [#29985 codemod] Save refusals, saveMetaItem, saveConflict, migrateStoredMetadata: the members below delegate to its facet, `ProtocolSaveFacet`. -import { ProtocolSaveFacet } from './protocol-save.js'; +import { ProtocolSaveFacet, packagelessRowHeldBaseDraftAddress } from './protocol-save.js'; // [#29985 codemod] History, publish, drafts, publish backfill: the members below delegate to its facet, `ProtocolHistoryAndPublishFacet`. import { ProtocolHistoryAndPublishFacet } from './protocol-history-and-publish.js'; import type { RegistryQuestion } from './registry-question.js'; @@ -7976,7 +7976,12 @@ export class ObjectStackProtocolImplementation implements getOverlayRepo: (...a) => this.getOverlayRepo(...a), readItemActiveRows: (...a) => this.readItemActiveRows(...a), }; - return packagelessDraftAddress.call(host, type, name, member, body); + // [#35524] …at the draft address the read naming no package takes + // there: the row-held base's, where the member's active rows are + // bound to one dependent only ({@link packagelessRowHeldBaseDraftAddress}). + return packagelessRowHeldBaseDraftAddress( + protocolHost(this), type, name, member, packagelessDraftAddress.call(host, type, name, member, body), + ); } /** diff --git a/packages/runtime/src/domains/meta-bare-save-dependent-only-member-35524.test.ts b/packages/runtime/src/domains/meta-bare-save-dependent-only-member-35524.test.ts new file mode 100644 index 00000000000..795779d7a21 --- /dev/null +++ b/packages/runtime/src/domains/meta-bare-save-dependent-only-member-35524.test.ts @@ -0,0 +1,298 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#35524, epic ruling 6781691009, #34348 ruling (b), ADR-0150 D3/D5] A +// bundled type's name no package ships, held as stored rows by an authored +// base WA (its `en-US` row) and an authored dependent WD that declares WA (its +// `fr-FR` row, a bundle addition). At the named non-canonical member `fr-FR` +// only WD holds a row, and the read naming no package takes the row-held +// base's address there (#33210 (c), pinned unchanged in +// `meta-disabled-holder-served-stack.test.ts` M1, M2, S2): 404. The write +// naming no package now resolves its address as that read does: the bare +// save (the REST door and in process, publish and draft mode) writes WA's +// row or draft at `fr-FR`, exactly as the save naming WA does, WD's row stays +// byte-unchanged, and the next bare read serves what was saved. The draft +// doors naming no package (the strict draft read, the per-item publish and +// the draft discard) take the same draft address, so the draft a bare draft +// save writes is the one they read, promote and discard; at this cell the +// dependent's own draft is reached at its own `?package=`, as the request +// naming WA answers. Driven on a booted kernel (the real protocol, metadata +// service, registry and `sys_metadata` store). +// +// FROM (`main` a73edb3cd7, measured through these doors): the bare read at +// `fr-FR` answered 404, the bare save answered 200 and rewrote WD's row, and +// the bare read after it answered 404 on a kernel whose registry had hydrated +// both rows at boot, or 409 RESOURCE_CONFLICT (the base's address names WA, +// the registry then named WD the holder) where the rows were stored after +// boot. The bare draft save wrote WD's draft, the bare draft read served it, +// and the bare publish promoted it into WD's row; the bare publish and +// discard of WD's draft promoted or removed it. +// +// Measured beside it, pinned as they read: the canonical member a base and +// its dependent both hold (the #34681 cell) and the canonical member only the +// dependent holds (#33210 contract review S1) keep their writes; two holders +// with no base relation are still refused 409 at a member both hold; a base +// that ships the name in code keeps answering as it does today (the bare read +// 404, the bare save writing the dependent's customization row: not moved by +// this change, see the PR's acceptance notes); a read-only base holding rows +// answers the bare save as `?package=` does. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { MetadataPlugin } from '@objectstack/metadata'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { resolveThrownHttpError } from '@objectstack/types'; +import type { EngineQueryOptions } from '@objectstack/spec/data'; +import { HttpDispatcher } from '../http-dispatcher.js'; + +const CALLER = { userId: 'u_dep_member', tenantId: 'org_qa', isSystem: true, positions: [], permissions: [], systemPermissions: ['manage_metadata'] }; +const A = 'com.qa.depmemberbase'; +const D = 'com.qa.depmemberaddon'; +const U = 'com.qa.depmemberother'; +const WA = 'com.qa.authoredbase'; +const WD = 'com.qa.authoredaddon'; +const WU = 'com.qa.authoredother'; + +interface ManifestDoor { register(artifact: unknown): Promise | void } +interface Booted { kernel: ObjectKernel; engine: ObjectQL; root: string; protocol: any } + +const template = (locale: string, subject: string) => ({ label: subject, locale, subject, bodyHtml: `

${subject}

` }); +const appManifest = (id: string, extra: Record = {}) => ({ + id, name: id.split('.').pop(), namespace: id.split('.').pop()!.replace(/[^a-z]/g, ''), version: '1.0.0', type: 'app', objects: [], ...extra, +}); +const MANIFESTS = [ + appManifest(A, { emailTemplates: [{ name: 'shipmail', ...template('en-US', 'base code en') }] }), + appManifest(D, { dependencies: { [A]: '*' } }), + appManifest(U), +]; + +async function boot(file: string): Promise { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + const root = mkdtempSync(join(tmpdir(), 'os-meta-dep-member-')); + const engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true }) as any, true); + await kernel.use(new MetadataPlugin({ watch: false, rootDir: root })); + await kernel.use(new ObjectQLPlugin({ ql: engine })); + const host: Plugin = { + name: 'qa.dep-member-host', + dependencies: ['com.objectstack.engine.objectql'], + init: async (ctx: PluginContext) => { + for (const manifest of MANIFESTS) await ctx.getService('manifest').register(manifest); + }, + }; + await kernel.use(host); + await kernel.bootstrap(); + await engine.syncSchemas(); + engine.registry.installPackage({ id: WA, name: WA, version: '1.0.0', type: 'app' } as any, 'authored'); + engine.registry.installPackage({ id: WD, name: WD, version: '1.0.0', type: 'app', dependencies: { [WA]: '*' } } as any, 'authored'); + engine.registry.installPackage({ id: WU, name: WU, version: '1.0.0', type: 'app' } as any, 'authored'); + return { kernel, engine, root, protocol: kernel.getService('protocol') }; +} + +const layRow = (engine: ObjectQL, type: string, name: string, packageId: string | null, metadata: Record, state: 'active' | 'draft' = 'active') => engine.insert('sys_metadata', { + type, name, namespace: 'default', package_id: packageId, scope: 'platform', strategy: 'merge', state, version: 1, + ...(type === 'email_template' && metadata.locale !== 'en-US' ? { bundle_member: metadata.locale } : {}), + metadata: JSON.stringify({ name, ...metadata }), +}, { context: { isSystem: true } } as any); +const layCell = async (engine: ObjectQL, name: string, base: string, dependent: string) => { + await layRow(engine, 'email_template', name, base, template('en-US', 'base en')); + await layRow(engine, 'email_template', name, dependent, template('fr-FR', 'addon fr')); +}; +const rowsOf = async (engine: ObjectQL, name: string) => ((await engine.find('sys_metadata', { where: { type: 'email_template', name }, context: { isSystem: true } } satisfies EngineQueryOptions)) as any[]) + .map((row) => { + const body = JSON.parse(String(row.metadata)); + return `${row.state}:${row.package_id ?? null}:${row.bundle_member ?? '-'}:${body.subject ?? body.label}`; + }).sort(); +const codeOf = (body: any): unknown => (body?.error && typeof body.error === 'object' ? body.error.code : body?.code); +const unwrap = (body: any) => body?.data ?? body; +async function dispatch(kernel: ObjectKernel, method: 'GET' | 'PUT', path: string, query: Record = {}, body?: unknown) { + const dispatcher = new HttpDispatcher(kernel as any, undefined, { enforceProjectMembership: false }); + (dispatcher as any).timedResolveExecutionContext = async () => ({ ...CALLER }); + const search = new URLSearchParams(query).toString(); + const raw = new Request(`http://localhost/api/v1${path}${search ? `?${search}` : ''}`, body === undefined + ? { method } + : { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + try { + const out: any = await dispatcher.dispatch(method, path, body ?? {}, query, { request: raw } as any, '/api/v1'); + return { status: out.response?.status as number | undefined, body: out.response?.body }; + } catch (e) { + const thrown = resolveThrownHttpError(e); + return { status: thrown.status, body: { error: { code: thrown.code, message: String((e as Error)?.message ?? '') } } }; + } +} +const bareRead = async (b: Booted, name: string, query: Record = {}) => { + const r = await dispatch(b.kernel, 'GET', `/meta/email_template/${name}`, query); + return r.status === 200 ? [200, unwrap(r.body)?.item?.subject, unwrap(r.body)?.packageId ?? null] : [r.status, codeOf(r.body), String(r.body?.error?.message ?? '').slice(0, 400)]; +}; +const settle = (call: Promise): Promise => call.then( + (resolved) => ({ ok: resolved?.success ?? true, message: resolved?.message }), + (error: any) => ({ code: error?.code, status: error?.status ?? error?.httpStatus, message: String(error?.message ?? '') }), +); +const putFr = (b: Booted, name: string, subject: string, query: Record = {}) => + dispatch(b.kernel, 'PUT', `/meta/email_template/${name}`, query, { name, ...template('fr-FR', subject) }); +const saveFr = (b: Booted, name: string, subject: string, extra: Record = {}) => + settle(b.protocol.saveMetaItem({ type: 'email_template', name, item: { name, ...template('fr-FR', subject) }, ...extra })); + +const fr = { member: 'fr-FR' }; +/** Every stored column of the dependent's `fr-FR` row, for a byte-identity comparison. */ +const dependentRow = async (engine: ObjectQL, name: string, dependent = WD) => JSON.stringify(((await engine.find('sys_metadata', { where: { type: 'email_template', name, package_id: dependent }, context: { isSystem: true } } satisfies EngineQueryOptions)) as any[]) + .filter((row) => row.bundle_member === 'fr-FR')); +/** The rows of `name` with the name blanked, to compare two names' writes. */ +const shapeOf = async (engine: ObjectQL, name: string) => (await rowsOf(engine, name)).map((row) => row.replace(name, 'NAME')); + +describe('[#35524] the bare save at a member only the dependent holds writes the row-held base\'s row the bare read addresses', () => { + const dirs: string[] = []; + afterAll(() => { for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); }); + const freshFile = () => { + const dir = mkdtempSync(join(tmpdir(), 'os-meta-dep-member-db-')); + dirs.push(dir); + return join(dir, 'meta.sqlite'); + }; + const down = async (b: Booted) => { + if (b.kernel.getState() === 'running') await b.kernel.shutdown(); + dirs.push(b.root); + }; + + it('the bare save (REST door and in process) writes what ?package= writes, leaves the dependent\'s row byte-unchanged, and the bare read then serves it, before and after a restart', async () => { + const file = freshFile(); + let b = await boot(file); + try { + for (const name of ['dm_rest', 'dm_proc', 'dm_named']) await layCell(b.engine, name, WA, WD); + } finally { + await down(b); + } + // Booted over the stored rows, so the registry hydrated both packages' rows. + b = await boot(file); + try { + expect(await bareRead(b, 'dm_rest', fr)).toEqual([404, 'RESOURCE_NOT_FOUND', expect.any(String)]); + const before = await dependentRow(b.engine, 'dm_rest'); + const put = await putFr(b, 'dm_rest', 'edited fr'); + expect(put.status, JSON.stringify(put.body)).toBe(200); + expect(await dependentRow(b.engine, 'dm_rest')).toBe(before); + const proc = await saveFr(b, 'dm_proc', 'edited fr'); + expect(proc.message, JSON.stringify(proc)).toContain(`package=${WA}`); + const named = await saveFr(b, 'dm_named', 'edited fr', { packageId: WA }); + expect(named.ok, JSON.stringify(named)).toBe(true); + const expected = [`active:${WD}:fr-FR:addon fr`, `active:${WA}:-:base en`, `active:${WA}:fr-FR:edited fr`]; + for (const name of ['dm_rest', 'dm_proc', 'dm_named']) { + expect([name, ...await rowsOf(b.engine, name)]).toEqual([name, ...expected]); + expect(await bareRead(b, name, fr)).toEqual([200, 'edited fr', WA]); + expect(await bareRead(b, name, { ...fr, package: WD })).toEqual([200, 'addon fr', WD]); + } + expect(await shapeOf(b.engine, 'dm_rest')).toEqual(await shapeOf(b.engine, 'dm_named')); + } finally { + await down(b); + } + b = await boot(file); + try { + expect(await bareRead(b, 'dm_rest', fr)).toEqual([200, 'edited fr', WA]); + } finally { + await down(b); + } + }, 120_000); + + describe('one boot', () => { + let b: Booted; + beforeAll(async () => { b = await boot(freshFile()); }, 120_000); + afterAll(async () => { if (b) await down(b); }); + + it('rows stored after boot: the bare save writes the base\'s row and the bare read serves it (it answered 409 after the save)', async () => { + await layCell(b.engine, 'dm_cold', WA, WD); + expect((await bareRead(b, 'dm_cold', fr))[0]).toBe(404); + const put = await putFr(b, 'dm_cold', 'edited fr'); + expect(put.status, JSON.stringify(put.body)).toBe(200); + expect(await rowsOf(b.engine, 'dm_cold')).toEqual([`active:${WD}:fr-FR:addon fr`, `active:${WA}:-:base en`, `active:${WA}:fr-FR:edited fr`]); + expect(await bareRead(b, 'dm_cold', fr)).toEqual([200, 'edited fr', WA]); + }); + + it('the bare draft save writes the base\'s draft, as ?package= does; the bare draft read, publish and discard act on that draft', async () => { + await layCell(b.engine, 'dd_bare', WA, WD); + await layCell(b.engine, 'dd_named', WA, WD); + const before = await dependentRow(b.engine, 'dd_bare'); + const bare = await saveFr(b, 'dd_bare', 'drafted fr', { mode: 'draft' }); + const named = await saveFr(b, 'dd_named', 'drafted fr', { mode: 'draft', packageId: WA }); + expect(bare.message, JSON.stringify(bare)).toContain(`package=${WA}`); + expect(named.ok, JSON.stringify(named)).toBe(true); + expect(await rowsOf(b.engine, 'dd_bare')).toEqual([`active:${WD}:fr-FR:addon fr`, `active:${WA}:-:base en`, `draft:${WA}:fr-FR:drafted fr`]); + expect(await shapeOf(b.engine, 'dd_bare')).toEqual(await shapeOf(b.engine, 'dd_named')); + expect(await dependentRow(b.engine, 'dd_bare')).toBe(before); + const read = await b.protocol.getMetaItem({ type: 'email_template', name: 'dd_bare', member: 'fr-FR', state: 'draft' }); + expect([read?.item?.subject, read?.item?._packageId]).toEqual(['drafted fr', WA]); + const published = await settle(b.protocol.publishMetaItem({ type: 'email_template', name: 'dd_bare', member: 'fr-FR' })); + expect(published.ok, JSON.stringify(published)).toBe(true); + expect(await rowsOf(b.engine, 'dd_bare')).toEqual([`active:${WD}:fr-FR:addon fr`, `active:${WA}:-:base en`, `active:${WA}:fr-FR:drafted fr`]); + expect(await bareRead(b, 'dd_bare', fr)).toEqual([200, 'drafted fr', WA]); + // The discard removes the draft the bare draft save wrote. + await layCell(b.engine, 'dd_discard', WA, WD); + expect((await saveFr(b, 'dd_discard', 'drafted fr', { mode: 'draft' })).ok).toBe(true); + const discarded = await settle(b.protocol.deleteMetaItem({ type: 'email_template', name: 'dd_discard', member: 'fr-FR', state: 'draft' })); + expect(discarded.message, JSON.stringify(discarded)).toContain(`(package=${WA})`); + expect(await rowsOf(b.engine, 'dd_discard')).toEqual([`active:${WD}:fr-FR:addon fr`, `active:${WA}:-:base en`]); + }); + + it('the dependent\'s own draft at the cell: the bare publish and discard answer what ?package= answers, and ?package= reaches it', async () => { + const outcome = (answer: any) => (answer.code !== undefined ? [answer.code, answer.status] : ['ok', answer.ok]); + const seen: Record = {}; + for (const [label, at] of [['bare', {}], ['named', { packageId: WA }]] as const) { + const name = `dd_own_${label}`; + await layCell(b.engine, name, WA, WD); + await layRow(b.engine, 'email_template', name, WD, template('fr-FR', 'addon fr draft'), 'draft'); + const publish = await settle(b.protocol.publishMetaItem({ type: 'email_template', name, member: 'fr-FR', ...at })); + const discard = await settle(b.protocol.deleteMetaItem({ type: 'email_template', name, member: 'fr-FR', state: 'draft', ...at })); + seen[label] = { publish: outcome(publish), discard: outcome(discard), rows: await shapeOf(b.engine, name) }; + } + expect(seen.bare, JSON.stringify(seen)).toEqual(seen.named); + expect(seen.bare).toMatchObject({ rows: [`active:${WD}:fr-FR:addon fr`, `active:${WA}:-:base en`, `draft:${WD}:fr-FR:addon fr draft`] }); + const own = await settle(b.protocol.publishMetaItem({ type: 'email_template', name: 'dd_own_bare', member: 'fr-FR', packageId: WD })); + expect(own.ok, JSON.stringify(own)).toBe(true); + expect(await rowsOf(b.engine, 'dd_own_bare')).toEqual([`active:${WD}:fr-FR:addon fr draft`, `active:${WA}:-:base en`]); + }); + + it('a read-only base holding rows: the bare save at the dependent\'s member answers what ?package= answers', async () => { + await layCell(b.engine, 'ro_cell', A, D); + const bare = await saveFr(b, 'ro_cell', 'edited'); + const named = await saveFr(b, 'ro_cell', 'edited', { packageId: A }); + expect([bare.code, bare.status], JSON.stringify(bare)).toEqual(['WRITABLE_PACKAGE_REQUIRED', 422]); + expect([bare.code, bare.status]).toEqual([named.code, named.status]); + expect(bare.message).toContain(`'${A}'`); + expect(await rowsOf(b.engine, 'ro_cell')).toEqual([`active:${D}:fr-FR:addon fr`, `active:${A}:-:base en`]); + }); + + it('CONTROLS: the canonical member keeps its writes, unrelated holders are still refused at a shared member, and a shipped base answers as it did', async () => { + // The #34681 cell: base and dependent both hold the canonical member; the bare save writes the base's row. + await layRow(b.engine, 'email_template', 'c_shared', WA, template('en-US', 'base en')); + await layRow(b.engine, 'email_template', 'c_shared', WD, template('en-US', 'addon en')); + await layRow(b.engine, 'email_template', 'c_shared', WD, template('fr-FR', 'addon fr')); + const shared = await settle(b.protocol.saveMetaItem({ type: 'email_template', name: 'c_shared', item: { name: 'c_shared', ...template('en-US', 'edited en') } })); + expect(shared.message, JSON.stringify(shared)).toContain(`package=${WA}`); + expect(await rowsOf(b.engine, 'c_shared')).toEqual([`active:${WD}:-:addon en`, `active:${WD}:fr-FR:addon fr`, `active:${WA}:-:edited en`]); + // The S1 mirror: the canonical member only the dependent holds is served and written at the dependent. + await layRow(b.engine, 'email_template', 'c_s1', WA, template('fr-FR', 'base fr')); + await layRow(b.engine, 'email_template', 'c_s1', WD, template('en-US', 'addon en')); + expect(await bareRead(b, 'c_s1')).toEqual([200, 'addon en', WD]); + const s1 = await settle(b.protocol.saveMetaItem({ type: 'email_template', name: 'c_s1', item: { name: 'c_s1', ...template('en-US', 'edited en') } })); + expect(s1.message, JSON.stringify(s1)).toContain(`package=${WD}`); + expect(await rowsOf(b.engine, 'c_s1')).toEqual([`active:${WD}:-:edited en`, `active:${WA}:fr-FR:base fr`]); + // Two packages, neither declaring the other, at a member both hold: refused 409 naming both. + await layRow(b.engine, 'email_template', 'c_unrel', WA, template('en-US', 'a en')); + await layRow(b.engine, 'email_template', 'c_unrel', WU, template('en-US', 'u en')); + expect((await bareRead(b, 'c_unrel')).slice(0, 2)).toEqual([409, 'RESOURCE_CONFLICT']); + const unrel = await settle(b.protocol.saveMetaItem({ type: 'email_template', name: 'c_unrel', item: { name: 'c_unrel', ...template('en-US', 'x') } })); + expect([unrel.code, unrel.status], JSON.stringify(unrel)).toEqual(['RESOURCE_CONFLICT', 409]); + for (const id of [WA, WU]) expect(unrel.message).toContain(id); + // …and at a member only one of them holds, that package's row is read and written. + await layCell(b.engine, 'c_unrel_fr', WA, WU); + expect(await bareRead(b, 'c_unrel_fr', fr)).toEqual([200, 'addon fr', WU]); + expect((await saveFr(b, 'c_unrel_fr', 'x')).message).toContain(`package=${WU}`); + // A base that ships the name in code: answered as today (not moved here). + await layRow(b.engine, 'email_template', 'shipmail', D, template('fr-FR', 'addon fr')); + expect((await bareRead(b, 'shipmail', fr))[0]).toBe(404); + const ship = await saveFr(b, 'shipmail', 'edited'); + expect(ship.message, JSON.stringify(ship)).toContain(`package=${D}`); + expect(await rowsOf(b.engine, 'shipmail')).toEqual([`active:${D}:fr-FR:edited`]); + }); + }); +});