Skip to content

Commit e6e90d8

Browse files
committed
feat(cloud-connection): unmanaged install can copy the package's sample data
An unmanaged install asked for its sample data (seedSampleData) has the import write each seed dataset into the new base as a seed item, the copy's seed receipt in the environment ledger. The install door loads the rows from those stored bodies, owned by the installer, and the purge door removes exactly them for the base's id. Claude-Session: https://claude.ai/code/session_01FEkQ5pQJCx8STEq28nr3Ej Co-Authored-By: Claude <noreply@anthropic.com>
1 parent e2e6ec7 commit e6e90d8

6 files changed

Lines changed: 519 additions & 36 deletions

File tree

‎packages/cloud-connection/src/marketplace-install-local-plugin.ts‎

Lines changed: 252 additions & 21 deletions
Large diffs are not rendered by default.

‎packages/cloud-connection/src/marketplace-install-local-purge.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,20 @@ export interface PurgeSeedDataset {
7272
records: ReadonlyArray<Record<string, unknown>>;
7373
}
7474

75+
/**
76+
* [#30808] One stored `seed` item of an unmanaged copy's seed receipt, as the
77+
* dataset it declares: the members `SeedSchema` declares, and no other — the
78+
* served envelope (`_packageId`, `_diagnostics`, …) never reaches the loader
79+
* or the matcher. `undefined` for a body that names no object or no records.
80+
*/
81+
export function seedDatasetOfReceiptItem(body: unknown): PurgeSeedDataset | undefined {
82+
if (body === null || typeof body !== 'object' || Array.isArray(body)) return undefined;
83+
const dataset = Object.fromEntries(Object.entries(body).filter(([key]) => key in SeedSchema.shape));
84+
return typeof dataset.object === 'string' && Array.isArray(dataset.records)
85+
? dataset as unknown as PurgeSeedDataset
86+
: undefined;
87+
}
88+
7589
/** The per-record outcome counts the purge route answers with. */
7690
export interface SamplePurgeOutcome {
7791
deleted: number;

‎packages/metadata-protocol/src/package-unmanaged-install.test.ts‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1175,3 +1175,123 @@ describe('the rename parity — one package, one `targetNamespace`, two doors, i
11751175
.toBe(viaDuplicate.packages.get('com.example.acme')?.manifest.namespace);
11761176
});
11771177
});
1178+
1179+
describe('the sample data, copied when the door asks — the seed receipt (#30808)', () => {
1180+
/** Two datasets in load order: the lead names its account by the account's natural key. */
1181+
const seededBody = (extra: Record<string, unknown> = {}) => renamableBody({
1182+
data: [
1183+
{ object: 'crm_account', externalId: 'title', records: [{ title: 'Acme' }, { title: 'crm_lead' }] },
1184+
{ object: 'crm_lead', externalId: 'title', records: [{ title: 'First', account: 'Acme' }] },
1185+
],
1186+
...extra,
1187+
});
1188+
const seedRows = (table: (name: string) => Row[]) => table('sys_metadata')
1189+
.filter((r) => r.type === 'seed' && r.state === 'active')
1190+
.map((r) => ({ name: r.name, package_id: r.package_id, body: typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata }));
1191+
1192+
it('off by default: no `seed` item is planned or written, and the answer lists none', async () => {
1193+
expect(plan(seededBody()).items.filter((i) => i.type === 'seed')).toEqual([]);
1194+
const { protocol, table } = makeProtocol();
1195+
const result = await protocol.importUnmanagedPackage({ manifest: seededBody() });
1196+
expect(result.copied.filter((c: any) => c.type === 'seed')).toEqual([]);
1197+
expect(seedRows(table)).toEqual([]);
1198+
});
1199+
1200+
it('asked for: one `seed` item per dataset, after every other item, named `<object>_seed`, the records verbatim', () => {
1201+
const p = plan(seededBody(), { seedData: true });
1202+
const seeds = p.items.filter((i) => i.type === 'seed');
1203+
expect(seeds.map((i) => i.name)).toEqual(['crm_account_seed', 'crm_lead_seed']);
1204+
expect(p.items.slice(-2)).toEqual(seeds);
1205+
expect(seeds[0]!.body).toEqual({ object: 'crm_account', externalId: 'title', records: [{ title: 'Acme' }, { title: 'crm_lead' }] });
1206+
});
1207+
1208+
it('under a `targetNamespace`, only `object` follows the rename map: no record value is rewritten, `externalId` stays', () => {
1209+
const p = plan(seededBody(), { seedData: true, targetNamespace: 'acme' });
1210+
const seeds = p.items.filter((i) => i.type === 'seed');
1211+
expect(seeds.map((i) => [i.name, i.body.object])).toEqual([
1212+
['acme_account_seed', 'acme_account'],
1213+
['acme_lead_seed', 'acme_lead'],
1214+
]);
1215+
// A record value spelled like a source object name is data, never a reference to rename.
1216+
expect(seeds[0]!.body.records).toEqual([{ title: 'Acme' }, { title: 'crm_lead' }]);
1217+
expect(seeds[0]!.body.externalId).toBe('title');
1218+
});
1219+
1220+
it('names a second dataset of one object `<object>_seed_2`', () => {
1221+
const p = plan(seededBody({
1222+
data: [
1223+
{ object: 'crm_lead', externalId: 'title', locale: 'en', records: [{ title: 'First' }] },
1224+
{ object: 'crm_lead', externalId: 'title', locale: 'zh-CN', records: [{ title: '首个' }] },
1225+
],
1226+
}), { seedData: true });
1227+
expect(p.items.filter((i) => i.type === 'seed').map((i) => i.name)).toEqual(['crm_lead_seed', 'crm_lead_seed_2']);
1228+
});
1229+
1230+
it('refuses a dataset that names no object or carries no records — INVALID_REQUEST / 400, before anything is written', async () => {
1231+
const body = seededBody({ data: [{ object: 'crm_lead', records: 'none' }, { records: [] }] });
1232+
const planned = (() => { try { plan(body, { seedData: true }); } catch (e) { return e; } return undefined; })() as any;
1233+
expect([resolveThrownHttpError(planned).status, resolveThrownHttpError(planned).code]).toEqual([400, 'INVALID_REQUEST']);
1234+
expect(planned.message).toContain('`data[0]` (object \'crm_lead\') has no `records` array');
1235+
expect(planned.message).toContain('`data[1]` names no `object`');
1236+
// Off, the same body is not this refusal's: `data` stays the door's.
1237+
expect(() => plan(body)).not.toThrow();
1238+
const { protocol, writes, packages } = makeProtocol();
1239+
const err = await refusalOf(() => protocol.importUnmanagedPackage({ manifest: body, seedData: true }));
1240+
expect(resolveThrownHttpError(err).code).toBe('INVALID_REQUEST');
1241+
expect(writes).toEqual([]);
1242+
expect(packages.size).toBe(0);
1243+
});
1244+
1245+
it('refuses the copy whole when `seed` is not runtime-creatable — asked of the registry\'s own flag', () => {
1246+
const err = (() => {
1247+
try {
1248+
plan(seededBody(), { seedData: true, isRuntimeCreatable: (t: string) => t !== 'seed' && registryCreatable(t) });
1249+
} catch (e) { return e; }
1250+
return undefined;
1251+
})() as any;
1252+
expect(err?.details?.findings).toEqual([expect.objectContaining({ key: 'data' })]);
1253+
});
1254+
1255+
it('the verb writes each seed item into the NEW base, environment-wide, the renamed object in its body', async () => {
1256+
const { protocol, table } = makeProtocol();
1257+
const result = await protocol.importUnmanagedPackage({
1258+
manifest: seededBody(), targetPackageId: 'com.example.acme', targetNamespace: 'acme', seedData: true,
1259+
});
1260+
expect(ImportUnmanagedPackageResponseSchema.parse(result)).toEqual(result);
1261+
expect(result.copied.slice(-2)).toEqual([{ type: 'seed', name: 'acme_account_seed' }, { type: 'seed', name: 'acme_lead_seed' }]);
1262+
const rows = seedRows(table);
1263+
expect(rows.map((r) => [r.name, r.package_id, r.body.object])).toEqual([
1264+
['acme_account_seed', 'com.example.acme', 'acme_account'],
1265+
['acme_lead_seed', 'com.example.acme', 'acme_lead'],
1266+
]);
1267+
expect(rows[0]!.body.records).toEqual([{ title: 'Acme' }, { title: 'crm_lead' }]);
1268+
expect(table('sys_metadata').filter((r) => r.type === 'seed').every((r) => !('organization_id' in r))).toBe(true);
1269+
});
1270+
1271+
it('a seed item the save door refuses rolls the whole copy back — no base, no item', async () => {
1272+
const { protocol, table, packages } = makeProtocol();
1273+
const err = await refusalOf(() => protocol.importUnmanagedPackage({
1274+
manifest: seededBody({ data: [{ object: 'crm_lead', externalId: 7, records: [] }] }), seedData: true,
1275+
}));
1276+
expect(resolveThrownHttpError(err).status).toBeGreaterThanOrEqual(400);
1277+
expect(err.details?.failedItem).toEqual({ type: 'seed', name: 'crm_lead_seed' });
1278+
expect(packages.has('com.example.crm-copy')).toBe(false);
1279+
expect(table('sys_metadata').filter((r) => r.package_id === 'com.example.crm-copy' && r.state === 'active')).toEqual([]);
1280+
});
1281+
1282+
it('a re-run is refused 409 before any write: the `-copy` base exists', async () => {
1283+
const { protocol, writes } = makeProtocol();
1284+
await protocol.importUnmanagedPackage({ manifest: seededBody(), seedData: true });
1285+
const before = writes.length;
1286+
const err = await refusalOf(() => protocol.importUnmanagedPackage({ manifest: seededBody(), seedData: true }));
1287+
expect([resolveThrownHttpError(err).status, resolveThrownHttpError(err).code]).toEqual([409, 'RESOURCE_CONFLICT']);
1288+
expect(writes.length).toBe(before);
1289+
});
1290+
1291+
1292+
it('`seedData` is the door\'s, never the published request\'s: the declaration still refuses an undeclared key', async () => {
1293+
const { protocol } = makeProtocol();
1294+
const err = await refusalOf(() => protocol.importUnmanagedPackage({ manifest: seededBody(), withSampleData: true }));
1295+
expect(resolveThrownHttpError(err).status).toBe(400);
1296+
});
1297+
});

‎packages/metadata-protocol/src/package-unmanaged-install.ts‎

Lines changed: 115 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
* - the artifact envelope (`packages`, a nested `manifest`), because one
4141
* import copies one package.
4242
*
43-
* ## Translations are copied; seeds and deployment configuration are not
43+
* ## Translations are copied; seeds only when the door asks; deployment configuration never
4444
*
4545
* - `translations` (i18n bundles) are COPIED, converted: each locale of each
4646
* bundle becomes one `translation` item named `<namespace>_<locale>` (the
@@ -51,9 +51,19 @@
5151
* ledger entry, so its bundles live where environment translations live —
5252
* in the environment ledger, reloaded at every boot by the
5353
* authored-translation sync;
54-
* - `data` (seed datasets) is data, never a metadata item (the artifact loader
55-
* says so beside its collection map), so a copy of the metadata cannot carry
56-
* it; the install door that calls this verb states what it did with it;
54+
* - `data` (seed datasets) is data, never a metadata item of the package (the
55+
* artifact loader says so beside its collection map), so a copy of the
56+
* metadata does not carry it; the install door that calls this verb states
57+
* what it did with it. [#30808] When that door ASKS for the sample data
58+
* (`seedData`, door-stated like `actor`, off by default), each dataset is
59+
* written into the base as one `seed` item ({@link unmanagedSeedItems}) — the
60+
* copy's SEED RECEIPT in the environment ledger. The door loads the rows
61+
* from those stored bodies, owned by the installer, and the purge door
62+
* deletes exactly them by the same `externalId` match it runs for a managed
63+
* install's ledger body, so no row gains a marker key. Under a rename only
64+
* the dataset's `object` follows the copy's object name: the records are
65+
* data, written verbatim, so each `externalId` value stays the one the
66+
* package shipped;
5767
* - deployment configuration (`i18n`, `requires`, `datasourceMapping`, `api`,
5868
* …) is read by the BOOT of the stack that declares it, never by an install
5969
* of a package, in either mode.
@@ -109,7 +119,12 @@ import { ASSEMBLED_VIEW_ITEMS_KEY, expandViewContainer, isAggregatedViewContaine
109119
import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security';
110120
import { resolveTenancyPosture } from '@objectstack/types';
111121
import { deriveViewContainerObject } from '@objectstack/metadata/view-container';
112-
import { PLATFORM_RESERVED_NAMESPACES, planNamespaceRename, type NamespaceRename } from './package-namespace-rename.js';
122+
import {
123+
METADATA_ITEM_NAME_STORAGE_LIMIT,
124+
PLATFORM_RESERVED_NAMESPACES,
125+
planNamespaceRename,
126+
type NamespaceRename,
127+
} from './package-namespace-rename.js';
113128

114129
/**
115130
* Every collection the import copies: manifest key → metadata type. The
@@ -366,6 +381,13 @@ export function planUnmanagedImport(
366381
* source's. Judged here, by the manifest key's own declaration.
367382
*/
368383
targetNamespace?: string;
384+
/**
385+
* [#30808] The install door asked for the package's sample data: each
386+
* `data` dataset is planned as a `seed` item of the base, after every
387+
* other item ({@link unmanagedSeedItems}). Absent or `false`, `data` is
388+
* left to the door, as before.
389+
*/
390+
seedData?: boolean;
369391
isRuntimeCreatable: (type: string) => boolean;
370392
loadOrderOf: (type: string) => number;
371393
/**
@@ -443,8 +465,20 @@ export function planUnmanagedImport(
443465
});
444466
}
445467
break;
446-
case 'base':
447468
case 'door':
469+
// [#30808] Asked for, the sample data is copied as `seed` items —
470+
// refused whole if that type ever stops being one the save door
471+
// may create, as `translations` is above.
472+
if (key === SEED_DATA_KEY && options.seedData === true && unmanagedInstallValueCarries(value)
473+
&& !options.isRuntimeCreatable(UNMANAGED_SEED_TYPE)) {
474+
findings.push({
475+
key,
476+
reason: `the sample data was asked for and is copied as '${UNMANAGED_SEED_TYPE}' items, and the `
477+
+ `metadata-type registry declares '${UNMANAGED_SEED_TYPE}' runtime-uncreatable`,
478+
});
479+
}
480+
break;
481+
case 'base':
448482
case 'deployment':
449483
break;
450484
default:
@@ -574,6 +608,13 @@ export function planUnmanagedImport(
574608
}));
575609
rename = planned;
576610
}
611+
// [#30808] The sample data, when the door asked for it: one `seed` item per
612+
// dataset, after every other item, so each object a dataset fills is
613+
// written (and its table made) before the seed naming it.
614+
if (options.seedData === true && unmanagedInstallValueCarries(manifest[SEED_DATA_KEY])) {
615+
const objectRenames = rename?.objectRenames;
616+
items = [...items, ...unmanagedSeedItems(manifest[SEED_DATA_KEY], (object) => objectRenames?.get(object) ?? object)];
617+
}
577618
const sourceVersion = stringKey(manifest, 'version');
578619
const baseManifest: Record<string, unknown> = {
579620
...identity,
@@ -628,6 +669,74 @@ export function unmanagedInstallRenameRefusal(
628669
/** The metadata type a `translations` bundle's locales are copied as. */
629670
const TRANSLATION_TYPE = 'translation';
630671

672+
/** [#30808] The package body key that carries the seed datasets. */
673+
const SEED_DATA_KEY = 'data';
674+
675+
/** [#30808] The metadata type a seed dataset is copied as when the door asks for the sample data. */
676+
export const UNMANAGED_SEED_TYPE = 'seed';
677+
678+
/**
679+
* [#30808] The `data` datasets as the copy's `seed` items — the seed receipt
680+
* the install door loads the rows from and the purge door deletes them by.
681+
*
682+
* - Each dataset is ONE item, in declaration order, named after the object it
683+
* fills as the copy names it: `<object>_seed`, then `<object>_seed_2`, … for
684+
* a second dataset of one object (a per-locale pair, say).
685+
* - The body is the dataset as the package declared it, with `object` set to
686+
* the copy's name for it (`copyObjectName`, the rename's own object map).
687+
* ⛔ Nothing else is rewritten: the records are data, not metadata, so the
688+
* rename engine's free-text rewrite — which turns any value spelled like a
689+
* source object name into the copy's — never reaches them, and every
690+
* `externalId` value (the purge's identity) is the one the package shipped.
691+
* - A dataset that is not an object, or names no object or no records, refuses
692+
* the import before anything is written (`INVALID_REQUEST` / 400), as an
693+
* unnamed item does; so does an item name the save door's grammar refuses.
694+
*/
695+
export function unmanagedSeedItems(
696+
value: unknown,
697+
copyObjectName: (object: string) => string,
698+
): UnmanagedImportItem[] {
699+
const problems: string[] = [];
700+
if (!Array.isArray(value)) {
701+
problems.push(`\`${SEED_DATA_KEY}\` is not an array of seed datasets`);
702+
}
703+
const items: UnmanagedImportItem[] = [];
704+
const perObject = new Map<string, number>();
705+
(Array.isArray(value) ? value : []).forEach((dataset: unknown, index) => {
706+
if (!isPlainRecord(dataset)) {
707+
problems.push(`\`${SEED_DATA_KEY}[${index}]\` is not a seed dataset object`);
708+
return;
709+
}
710+
if (typeof dataset.object !== 'string' || dataset.object === '') {
711+
problems.push(`\`${SEED_DATA_KEY}[${index}]\` names no \`object\``);
712+
return;
713+
}
714+
if (!Array.isArray(dataset.records)) {
715+
problems.push(`\`${SEED_DATA_KEY}[${index}]\` (object '${dataset.object}') has no \`records\` array`);
716+
return;
717+
}
718+
const object = copyObjectName(dataset.object);
719+
const nth = (perObject.get(object) ?? 0) + 1;
720+
perObject.set(object, nth);
721+
const name = nth === 1 ? `${object}_seed` : `${object}_seed_${nth}`;
722+
if (!METADATA_ITEM_NAME_PATTERN.test(name) || name.length > METADATA_ITEM_NAME_STORAGE_LIMIT) {
723+
problems.push(`\`${SEED_DATA_KEY}[${index}]\` would be copied as the seed item ${JSON.stringify(name)}, which is not a legal metadata item name`);
724+
return;
725+
}
726+
items.push({ type: UNMANAGED_SEED_TYPE, name, key: SEED_DATA_KEY, body: { ...dataset, object }, expands: [] });
727+
});
728+
if (problems.length > 0) {
729+
const shown = problems.slice(0, 5).join('; ');
730+
throw refusal(
731+
'INVALID_REQUEST',
732+
400,
733+
`The package's sample data cannot be copied as written: ${shown}`
734+
+ `${problems.length > 5 ? ` (+${problems.length - 5} more)` : ''}. Nothing was installed.`,
735+
);
736+
}
737+
return items;
738+
}
739+
631740
/** A plain `{ … }` object — the shape a bundle, and each group in it, takes. */
632741
function isPlainRecord(value: unknown): value is Record<string, unknown> {
633742
return value !== null && typeof value === 'object' && !Array.isArray(value);

0 commit comments

Comments
 (0)