Repository navigation
Expand file tree
/
Copy pathprotocol-package-commits.ts
More file actions
2232 lines (2189 loc) · 133 KB
/
Copy pathprotocol-package-commits.ts
File metadata and controls
2232 lines (2189 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* [#29985 codemod] The "Package revert, duplicate, import, orphans, commits,
* revertCommit, rollback" facet of `ObjectStackProtocolImplementation`: the
* bodies of `revertStoredPackage`, `duplicatePackage`,
* `importUnmanagedPackage`, `reassignOrphanedMetadata`, `listCommits`,
* `readRevertableCommit`, `revertCommit`, `rollbackToPackageCommit`,
* `rollbackMetaItemUnaudited` moved out of `protocol.ts` whole by
* `scripts/codemod-split-protocol.mjs`.
*
* A MOVE, not a redesign. `ProtocolPackageCommitsFacet` is a stateless facet over the host
* (ruling 6624345766): each static method below is the body of the class
* member of the same name as `packages/metadata-protocol/scripts/host-split.mjs`
* moves one (ruling E, item E1), with `this.<member>` read as `host.<member>`
* and nothing else changed. The facet holds no state: the fields stay on the
* class, and a body reaches them through the host (`protocol-host.ts`).
*
* The class keeps every member as a one-line delegation. A public member
* keeps its docblock there, which the published `.d.ts` prints; a private
* member's docblock moved here with its body (docblock ownership).
*
* What a body reads from elsewhere, it imports from where `protocol.ts`
* imports it. Nothing re-exports this module, so the published surface does
* not move.
*/
import { ImportUnmanagedPackageRequestSchema } from '@objectstack/spec/api';
import type {
ImportUnmanagedPackageRequest,
ImportUnmanagedPackageResponse,
InstallPackageRequest,
} from '@objectstack/spec/api';
import { packageScopedRowWhere } from './sys-metadata-repository.js';
import type { SysMetadataRepository } from './sys-metadata-repository.js';
import { ConflictError, assertProtocolCompat } from '@objectstack/metadata-core';
import { planUnmanagedImport, unmanagedInstallPostureRefusal } from './package-unmanaged-install.js';
import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared';
import {
DEFAULT_METADATA_TYPE_REGISTRY,
ManifestSchema,
deriveNamespaceFromPackageId,
manifestIdRefusal,
} from '@objectstack/spec/kernel';
import { REFERENCE_SITES } from './reference-sites.js';
import { extensionFieldSuffixRefusalError, judgeExtensionFieldSuffix } from './protocol-extension-field-suffix.js';
import { customizationPairManifestRefusal } from './protocol-customization-package.js';
import {
canonicalMetaType,
canonicalizeMetaRequestType,
overlaySchemaDeclaredKey,
} from './protocol-meta-type-schema.js';
import { permissionSetOwnerBindingRefusal } from './protocol-authoring-refusals.js';
import { zodIssuesToMetadataIssues } from './protocol-metadata-issues.js';
import {
bundleMemberDiscriminator,
memberOption,
mutationEventMember,
resolveBundleMemberSelector,
} from './protocol-bundle-members.js';
import { compareAuditInstants, isoFromValidDate } from './protocol-version-tokens.js';
import {
clientFacingFailureCode,
clientFacingFailureText,
declaresClientRefusal,
metadataIssueHeadline,
} from './protocol-client-failures.js';
import { isNonCanonicalStoredType } from './protocol-stored-overlay-types.js';
import type { RollbackMetaItemRequest } from './protocol-door-requests.js';
import type { ProtocolHost } from './protocol-host.js';
/**
* [#30319] The grant keys of a stored permission set's `objects` map: what a
* copy of that row holds because the source does (the save request's
* `inheritedGrantObjects`). The same derivation as the permission-set clone
* door's `inheritedGrantObjectsOf` (`@objectstack/runtime`, which depends on
* this package, so it is restated, not imported).
*/
function storedGrantObjectKeys(stored: unknown): string[] {
const objects = stored && typeof stored === 'object' ? (stored as { objects?: unknown }).objects : undefined;
return objects && typeof objects === 'object' && !Array.isArray(objects) ? Object.keys(objects) : [];
}
export class ProtocolPackageCommitsFacet {
/** The body of `ObjectStackProtocolImplementation#revertStoredPackage`; the method's docblock there is its contract. */
static async revertStoredPackage(host: Pick<ProtocolHost, 'discardDraftInItsScope' | 'ensureOverlayIndex' | 'findEnvironmentRows' | 'getOverlayRepo' | 'refuseOrganizationScopedWrite' | 'rethrowUnlessMetadataStoreUnprovisioned'>, request: {
packageId: string;
actor?: string;
}): Promise<{
stored: boolean;
discarded: Array<{ type: string; name: string }>;
}> {
// [ADR-0131 D6] FIRST: an organization-scoped revert is refused.
host.refuseOrganizationScopedWrite(
`Package '${request.packageId}'`, request,
);
await host.ensureOverlayIndex();
let drafts: Awaited<ReturnType<SysMetadataRepository['listDrafts']>>;
let publishedRows: unknown[];
try {
drafts = await host.getOverlayRepo().listDrafts({ packageId: request.packageId });
// [#21911] The explicit system opt-in — see findServedOverlayRow.
publishedRows = (await host.findEnvironmentRows('sys_metadata', {
where: packageScopedRowWhere('active', { packageId: request.packageId }),
limit: 1,
context: { isSystem: true },
})) as unknown[];
} catch (error) {
host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata');
return { stored: false, discarded: [] };
}
if (drafts.length === 0 && publishedRows.length === 0) return { stored: false, discarded: [] };
if (publishedRows.length === 0) {
const err = new Error(
`Package '${request.packageId}' has never been published, so there is no published version to `
+ 'revert to. Publish the package first, or discard its drafts to drop them.',
) as Error & { code?: string; status?: number };
err.code = 'RESOURCE_CONFLICT';
err.status = 409;
throw err;
}
const discarded: Array<{ type: string; name: string }> = [];
for (const d of drafts) {
await host.discardDraftInItsScope(d, request.actor);
discarded.push({ type: d.type, name: d.name });
}
return { stored: true, discarded };
}
/** The body of `ObjectStackProtocolImplementation#duplicatePackage`; the method's docblock there is its contract. */
static async duplicatePackage(host: Pick<ProtocolHost, 'convertStoredItem' | 'engine' | 'findEnvironmentRows' | 'installPackage' | 'refuseOrganizationScopedWrite' | 'resolveFlowCanonicalizer' | 'saveMetaItem'>, request: {
sourcePackageId: string;
targetPackageId: string;
targetName?: string;
targetNamespace?: string;
actor?: string;
}): Promise<{
success: boolean;
copiedCount: number;
failedCount: number;
targetPackageId: string;
copied: Array<{ type: string; name: string }>;
failed: Array<{ type: string; name: string; error: string }>;
}> {
// [ADR-0131 D6] FIRST: an organization-scoped duplicate is refused.
host.refuseOrganizationScopedWrite(
`Package '${request.targetPackageId}'`, request,
);
// [#19417] ⭐ THE TARGET ID IS PARSED BEFORE ANYTHING IS MINTED — same
// declaration, same surfaced sentence, one key over.
//
// This door builds `dupManifest` with `id: request.targetPackageId` and
// writes it through {@link installPackage}, so the gate there already
// covers the WRITE. It does not cover this method, for two reasons that
// are both about where the refusal lands:
//
// ① a refusal of the `installPackage` call below is rethrown before
// any item is copied, so it would not be lost — but it names
// `manifest.id`, the key of a manifest this door builds, never the
// `targetPackageId` the caller wrote (the closing paragraph below);
// ② the refusal has to precede the MUTATIONS, and the manifest write
// is not the first of them. #14451 already established the position
// for this door's other precondition: `duplicatePackage` mints the
// target package record ahead of its copy loop, so a refusal any
// later leaves the empty shell behind.
//
// The key named is `targetPackageId`, because that is the authoring
// path the caller actually wrote — `manifestIdRefusal` takes the key so
// one declaration can name itself correctly at every door.
const declaredTargetId = ManifestSchema.shape.id.safeParse(request.targetPackageId);
if (!declaredTargetId.success) {
throw Object.assign(
new Error(manifestIdRefusal('targetPackageId', request.targetPackageId)),
{ statusCode: 400 },
);
}
const registry: any = (host.engine as any).registry;
const srcPkg = registry?.getPackage?.(request.sourcePackageId);
// [#19417] ⭐ ONE ASSUMPTION, ONE IMPLEMENTATION. Both namespaces were
// derived here by a RAW `id.split('.').pop()`, while
// {@link installPackage} derives the very same default with the spec
// helper `deriveNamespaceFromPackageId` — which sanitises to the
// namespace charset, truncates to 20 and answers `null` when nothing
// valid comes out. The raw copy did none of that, and `targetNs` is not
// a label: it is spliced into every copied OBJECT name as
// `${targetNs}_${short}`, and an object name is
// `/^[a-z_][a-z0-9_]*$/` (`packages/spec/src/data/object.zod.ts`).
//
// So the Studio's own default duplicate id — `<sourceId>-copy`, the
// value both objectui duplicate dialogs prefill — derived the namespace
// `leave-copy` and minted object names `leave-copy_ticket`, which the
// object declaration refuses. The helper answers `leave_copy`. The
// source side is the same rule read backwards: the prefix these rows
// actually carry is the one `installPackage` stamped, i.e. the helper's,
// so matching them with the raw split found nothing and the copy landed
// under the SOURCE's names — the collision the re-namespacing exists to
// prevent.
//
// [#19577] ⭐ AN EXPLICIT `targetNamespace` STILL WINS OVER THE DEFAULT,
// BUT IT IS PARSED, NOT TAKEN RAW. Whichever branch answered, the value
// becomes the copy's `manifest.namespace` AND the prefix of every copied
// object name, so both branches pass ONE parse before anything is
// minted — `ManifestSchema.shape.namespace`, the declaration itself,
// never a hand-copied regex. An explicit value was the more reachable
// hole of the two: it is pure caller input, and `targetNamespace:
// 'my-ns'` minted `my-ns_ticket`, a name the object declaration refuses.
//
// ⛔ A refused explicit value is REFUSED, never sanitised the way the
// derivation sanitises an id: it is what the caller wrote, and a copy
// quietly landing under a namespace nobody wrote is the silent rewrite
// this door exists not to perform.
//
// The sentence is the DECLARATION's, surfaced — the discipline the id
// gate above follows — and this door adds only the key it read and the
// value that arrived. The throw carries `statusCode: 400` and no `code`,
// exactly like the id refusal above, so an HTTP boundary answers the
// status-derived `VALIDATION_ERROR` on both branches (`resolveThrownHttpError`).
const sourceNs: string =
(srcPkg?.manifest?.namespace as string) ?? (deriveNamespaceFromPackageId(request.sourcePackageId) ?? '');
const explicitNs = request.targetNamespace;
const targetNs: string | null = explicitNs ?? deriveNamespaceFromPackageId(request.targetPackageId);
// `?? ''` because the declaration is `.optional()`: an ABSENT value
// passes it, and a derivation that produced nothing must not.
const declaredTargetNs = ManifestSchema.shape.namespace.safeParse(targetNs ?? '');
if (targetNs == null || !declaredTargetNs.success) {
const rule = declaredTargetNs.error?.issues[0]?.message ?? 'See `manifest.namespace`';
throw Object.assign(
new Error(
explicitNs != null
? `Invalid package namespace '${String(explicitNs)}' on \`targetNamespace\`. ${rule}. `
+ 'It becomes the copy\'s `manifest.namespace` and the prefix of every copied object name.'
// Reachable only for an id the pattern admits but the
// namespace charset cannot carry (a single-letter final
// segment) — never a copy renamed with an empty prefix.
: `Cannot derive a package namespace from '${request.targetPackageId}'. `
+ `Pass \`targetNamespace\` explicitly. ${rule}.`,
),
{ statusCode: 400 },
);
}
// [ADR-0146 D3] A copy into a paired customization package id must carry
// what the pair's ensure door writes — the base's pair namespace and the
// dependency on the base — judged on the record this verb WOULD install,
// before a row is read. `installPackage` asks the same predicate of the
// record it is handed; asking here as well covers a source with no
// registered manifest, whose copy mints no record for that gate to judge
// and would otherwise land items under a pair id no package holds.
const pairRefusal = customizationPairManifestRefusal(
{ id: request.targetPackageId, namespace: targetNs, dependencies: srcPkg?.manifest?.dependencies },
(id) => registry?.getPackage?.(id),
);
if (pairRefusal !== undefined) throw Object.assign(new Error(pairRefusal), { statusCode: 400 });
// [ADR-0131 D6] The source's ENVIRONMENT rows — the ones every `/meta`
// read serves. A legacy organization-scoped row is served by none of
// them and waits for the promotion ceremony (ADR-0131 C7); copying it
// would write its body environment-wide under the new package, a
// promotion this verb has no business performing, and — beside the
// environment row of the same item — land two bodies on one target key.
const where: Record<string, unknown> = {
package_id: request.sourcePackageId,
state: 'active',
};
// [#21911] The explicit system opt-in — see findServedOverlayRow.
const rows = (await host.findEnvironmentRows('sys_metadata', { where, context: { isSystem: true } })) as any[];
// Rows other than objects and qualified view items (each below) are
// renamed by the source-prefix swap alone; a name without the prefix
// keeps it (the docblock re-namespaces OBJECT names).
const renameName = (name: string): string =>
sourceNs && typeof name === 'string' && name.startsWith(`${sourceNs}_`)
? `${targetNs}_${name.slice(sourceNs.length + 1)}`
: name;
// ⭐ EVERY OBJECT GETS A NAME IN THE TARGET NAMESPACE (ADR-0070 D4, read
// with ADR-0129 D2). An object name IS its table name and its registry
// key, so a copy that keeps the source's name is a second claim on the
// source's object: before PR #23510 it stored a target row the registry
// refused, over the source's table, and after it the copy failed with
// the ADR-0029 D9.9 ownership prescription, which names no way out for
// a duplicate. ADR-0129 D2 says what the name is: every object a
// package defines is `${namespace}_${shortName}`, and the prefix rule's
// own prescription for a name that lacks the prefix
// (`validateObjectNamespacePrefix`) is "rename it to
// `${namespace}_${name}`". The copy is a NEW object, so that rename
// costs nothing here — while renaming the SOURCE object would move its
// table. A prefixed name swaps the source prefix for the target's;
// a name WITHOUT the source prefix (a direct-publish save stored
// before that door read the prefix rule — #24547 — or a package that
// had no namespace) takes the target prefix in front of its whole name.
//
// ⛔ REFUSED, NEVER RE-INVENTED: when that name is already claimed — by
// the copy of a prefixed sibling (`ticket` and `iojn_ticket` both name
// `iojn2_ticket`) or by an object the source package holds — the object
// is reported in `failed[]` before anything is written for it, at its
// own name, with the rename that clears it. A second invented name
// (a numeric suffix, a third prefix) would be a name nobody wrote.
const objectNames = new Set<string>(
rows.filter((row) => row?.type === 'object' && typeof row.name === 'string').map((row) => row.name as string),
);
const renameMap = new Map<string, string>();
const prefixed: string[] = [];
const unprefixed: string[] = [];
for (const name of objectNames) {
if (sourceNs && name.startsWith(`${sourceNs}_`)) prefixed.push(name);
else unprefixed.push(name);
}
for (const name of prefixed) {
const nn = renameName(name);
if (nn !== name) renameMap.set(name, nn);
}
// Every name a prefixed object's copy takes (itself, when the target
// namespace IS the source's), and every name the source holds.
const claimedBy = new Map<string, string>(prefixed.map((name) => [renameName(name), name]));
const refusedObjects = new Map<string, string>();
for (const name of unprefixed) {
const nn = `${targetNs}_${name}`;
const holder = claimedBy.get(nn) ?? (objectNames.has(nn) ? nn : undefined);
if (holder !== undefined) {
const lacks = sourceNs
? `lacks the '${sourceNs}_' prefix of package '${request.sourcePackageId}' (ADR-0129 D2: `
+ 'every object a package defines carries its namespace as a name prefix)'
: `carries no namespace prefix (package '${request.sourcePackageId}' declares no namespace)`;
const taken = holder === nn
? `'${nn}' is an object package '${request.sourcePackageId}' already holds`
: `'${nn}' is already the copy name of object '${holder}'`;
refusedObjects.set(
name,
`Object '${name}' is not copied: its name ${lacks}, so its copy is named '${nn}' in `
+ `namespace '${targetNs}', and ${taken}. Rename '${name}' on the source to `
+ `${sourceNs ? `a '${sourceNs}_' name` : 'a name'} no other object in the package uses, `
+ 'then duplicate again.',
);
continue;
}
renameMap.set(name, nn);
claimedBy.set(nn, name);
}
// Longest-first, identifier-boundary rewrite so `iojn_task` never corrupts
// `iojn_task_log`, and `iojn_x` inside `record.iojn_x`/`iojn_x.view` matches.
// Prefixed names only: a prefixed name is distinctive enough to find in
// free text, a bare one is not (below).
//
// ⭐ THE BOUNDARY HOLDS ON BOTH SIDES. With the right side alone, a
// name that merely ENDS in an object's name was rewritten inside it:
// the field `x_iojn_task` came out `x_iojn2_task` — its `name` and every
// value naming it — while its `fields` key stayed, so the copy's key
// and `name` disagreed. `x_iojn_task` is another identifier, never the
// object: `renameName` swaps the source prefix only at the START of a
// name, and this rewrite now matches only a whole identifier too.
//
// ⭐ A PREFIXED NAME THAT IS ALSO A FIELD KEY IS NOT DISTINCTIVE. When a
// package object declares a field keyed like a prefixed package object
// (`fields.iojn_customer` beside the object `iojn_customer`), a free-text
// value spelled that way may name the field — a list view's `columns`,
// a form's `sections[].fields` — and the field keeps its key. Renaming
// it as the object copied a column or form field the copy does not
// have. Such a name is treated as a bare name is: rewritten only at an
// object-reference property (below), never in free text.
const fieldKeys = new Set<string>();
for (const row of rows) {
if (row?.type !== 'object') continue;
let body: any;
try {
body = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata;
} catch {
continue; // the copy loop reports an unparseable row at its own name
}
const fields = body?.fields;
if (fields && typeof fields === 'object' && !Array.isArray(fields)) {
for (const key of Object.keys(fields)) fieldKeys.add(key);
}
}
const olds = prefixed
.filter((name) => renameMap.has(name) && !fieldKeys.has(name))
.sort((a, b) => b.length - a.length);
const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = olds.length
? new RegExp(`(?<![A-Za-z0-9_])(${olds.map(esc).join('|')})(?![A-Za-z0-9_])`, 'g')
: null;
// ⭐ A VIEW ITEM'S NAME FOLLOWS ITS OBJECT. A view row's qualified name
// is `<object>.<viewKey>` (`ViewItemNameSchema`,
// `packages/spec/src/ui/view.zod.ts`: "the object can be recovered from
// the prefix, so the registry key never collides across objects"), so
// its object part takes exactly the rename its `object` property takes
// — `renameMap`, whole — and its view key is left as stored:
// `ticket.board` copies as `iojn2_ticket.board` beside the body's
// `object: 'iojn2_ticket'`. The source-prefix swap (`renameName`)
// reached a prefixed object's items only: a bare object's item kept
// `ticket.board`, a name the source's item still holds, so a by-name
// read naming no package served the source and the copy was shadowed.
// The swap also moved an item of an object OUTSIDE the package that
// carries the source prefix (`iojn_ext.board` → `iojn2_ext.board`)
// while its `object` stayed `iojn_ext`. An object this copy does not
// rename keeps its items' names.
//
// A value that IS such a name, whole, follows the item: a form action's
// `target` (`<object>.<viewKey>`) kept `ticket.entry`, so the copy's
// button opened the SOURCE's form, on the source's object. Whole values
// only, and only names of the view items this copy renames — a bare
// object's name is never rewritten inside free text (below).
const isQualifiedViewRow = (row: any): boolean =>
(PLURAL_TO_SINGULAR[String(row?.type)] ?? String(row?.type)) === 'view'
&& typeof row?.name === 'string' && row.name.includes('.');
const viewItemRenames = new Map<string, string>();
for (const row of rows) {
if (!isQualifiedViewRow(row)) continue;
const dot = (row.name as string).indexOf('.');
const renamed = renameMap.get((row.name as string).slice(0, dot));
if (renamed !== undefined) viewItemRenames.set(row.name, `${renamed}${(row.name as string).slice(dot)}`);
}
// ⭐ AT AN OBJECT-REFERENCE PROPERTY, A NAME IS REWRITTEN WHOLE — the
// only place a BARE name is rewritten. Measured: putting `ticket` in the
// free-text rewrite above turns "A support ticket raised by a customer"
// into "A support iojn2_ticket raised …", and the same match renames the
// value of a lookup FIELD called `ticket` (`fields.ticket.name`). So a
// value is rewritten only where it sits under a property that names an
// object — the derived site index (`REFERENCE_SITES`, target `object`:
// `reference`, `object`, `objectName`, `objects`, …), read by property
// wherever it occurs in any item, because flow node configs (`config.
// objectName`) are declared by node descriptors the index does not
// walk — and only when it equals a renamed name exactly, in the four
// shapes a name arrives in there: a string, an array element, a record
// KEY (`permission.objects` is keyed by object name) or a `.name`. The
// record key holds for prefixed names too: a copied permission set
// otherwise kept `objects.<source object>`, a grant on the SOURCE.
//
// ⛔ REFUSED, NEVER MERGED: at a reference site, a renamed name can
// meet a name the item already holds there — the source also names
// the object the copy is about to be called (`dupdst_customer`, an
// object outside the package or not yet created) beside its own
// (`dupsrc_customer`). Two record KEYS that land on one key keep only
// the last entry: a permission set's `objects` dropped a grant (and
// the copied object could gain edit and delete its source never gave
// it), a translation's `objects` dropped a label. Two array ELEMENTS
// that land on one name bind it twice: a hook's handler ran twice per
// event on the copied object. So every such meeting is recorded in
// `collisions` — the path, the name that moved, the name it met — and
// the call site refuses the item in `failed[]` before anything is
// written for it. `renameMap` is one-to-one, so a meeting is always a
// renamed name and a name this copy does not rename; an element the
// source itself repeats is copied as stored.
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 => {
if (typeof v === 'string') {
const whole = atReference ? renameMap.get(v) : undefined;
if (whole !== undefined) return whole;
const viewItem = viewItemRenames.get(v);
if (viewItem !== undefined) return viewItem;
return re ? v.replace(re, (m) => renameMap.get(m) ?? m) : v;
}
if (Array.isArray(v)) {
const out = v.map((element, i) => deepRewrite(element, collisions, atReference, `${at}[${i}]`));
if (atReference) {
const firstAt = new Map<string, number>();
out.forEach((element, i) => {
if (typeof element !== 'string') return;
const j = firstAt.get(element);
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 });
}
});
}
return out;
}
if (v && typeof v === 'object') {
const o: any = {};
const from = new Map<string, string>();
for (const [k, val] of Object.entries(v)) {
const key = atReference ? (renameMap.get(k) ?? k) : k;
const other = from.get(key);
if (other !== undefined) {
collisions.push({ at, shape: 'key', moved: key === k ? other : k, met: key });
}
from.set(key, k);
const entry = deepRewrite(
val, collisions,
objectReferenceProperties.has(k) || (atReference && k === 'name'),
at ? `${at}.${k}` : k,
);
// ⭐ A RECORD ENTRY'S `name` FOLLOWS ITS KEY. An entry that
// echoes its key in `name` (an object's field: `fields`
// keyed by field name) is ONE identity spelled twice, so
// the name takes the key's rename decision. Outside a
// reference site a key is never renamed, while the
// free-text rewrite above renamed a `name` equal to a
// prefixed object's: the field `iojn_customer` was copied
// as `fields.iojn_customer.name: 'iojn2_customer'`. The
// data plane addresses the column by the key, the save
// door's FLS lint reads the `name`, so a copied permission
// set's rule on that field was refused at the copy.
if (typeof (val as any)?.name === 'string' && (val as any).name === k
&& entry && typeof entry === 'object' && !Array.isArray(entry)) {
entry.name = key;
}
o[key] = entry;
}
return o;
}
return v;
};
const describeCollision = (c: ReferenceCollision): string =>
`its \`${c.at}\` ${c.shape} '${c.moved}' follows the copied object 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. '
: `The copy would name '${c.met}' twice. `)
+ `Remove '${c.moved}' or '${c.met}' on the source, then duplicate again.`;
// ⭐ A COPIED PERMISSION SET'S FIELD RULES FOLLOW THE RENAMED OBJECTS.
// `PermissionSetSchema.fields` is a record keyed `<entity_name>.<field_name>`
// (`packages/spec/src/security/permission.zod.ts`), and the security
// plugin reads a set's rules for an object by the key prefix
// `<object>.` (`PermissionEvaluator.getFieldPermissions`). Left as
// stored, the copy's rules govern the SOURCE's object and the
// duplicate's object gets none: a field the source set hides is
// readable on the copy for whoever holds the copied set.
//
// `deepRewrite` cannot carry it: the derived site index reads
// `permission.fields` as a site naming `field` items (its property
// spells that type), never an object, and has no arm for a composite
// key — and widening the index would also change the "Used by" answer
// it feeds (`findReferencesToMeta`). So this step is keyed on the
// declared shape — the `fields` record of a copied `permission` item —
// never on a property name, which would also catch an object's own
// `fields` (keyed by field name).
//
// The split: object and field names are both `^[a-z_][a-z0-9_]*$`, so
// a key's object part is everything before its FIRST `.`. It is
// rewritten only when it equals a renamed object name exactly, and the
// field part is never read — `dupsrc_customer.dupsrc_customer` becomes
// `dupdst_customer.dupsrc_customer`. A key naming an object outside the
// package keeps its name.
//
// ⛔ REFUSED, NEVER MERGED: when a renamed key equals a key the set
// already holds (the source also governs an object, outside the
// package, named like the copy), keeping either rule would silently
// drop the other, so the set is reported in `failed[]` with both keys.
// `Object.fromEntries` defines own properties, so no key can land on
// the prototype.
const rewriteFieldRuleKeys = (fields: Record<string, unknown>): { fields: Record<string, unknown> } | { collision: string } => {
const out = new Map<string, unknown>();
const from = new Map<string, string>();
for (const [key, rule] of Object.entries(fields)) {
const dot = key.indexOf('.');
const renamed = dot > 0 ? renameMap.get(key.slice(0, dot)) : undefined;
const next = renamed === undefined ? key : `${renamed}${key.slice(dot)}`;
const other = from.get(next);
if (other !== undefined) {
const moved = next === key ? other : key;
return {
collision: `its field rule '${moved}' follows object '${moved.slice(0, moved.indexOf('.'))}' `
+ `to '${next}', a key the set already holds for object `
+ `'${next.slice(0, next.indexOf('.'))}', which this copy does not rename. `
+ `Remove '${moved}' or '${next}' on the source, then duplicate again.`,
};
}
out.set(next, rule);
from.set(next, key);
}
return { fields: Object.fromEntries(out) };
};
// [ADR-0146 D10, #28564] ⭐ THE `__c` RESERVATION, JUDGED AGAINST THE
// TARGET, before the copy's first mutation (the package record below):
// every object the copy would write is the target's own object, so a
// copy of a `.custom` pair's objects into a plain id carries their
// `__c` fields into a package that may not declare one. Refused whole,
// with the save door's judge and envelope (`VALIDATION_ERROR` / 400),
// so no half-copied app is left behind; a copy into a pair id writes
// the pair's own objects, which are not judged. An unparseable row is
// left to the copy loop, which reports it. See
// {@link judgeExtensionFieldSuffix}.
{
const copiedObjects: Record<string, unknown> = {};
for (const row of rows) {
if (row?.type !== 'object' || typeof row.name !== 'string') continue;
let body: unknown;
try {
body = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata;
} catch {
continue;
}
if (body && typeof body === 'object' && !Array.isArray(body)) {
copiedObjects[row.name] = { ...(body as Record<string, unknown>), name: renameMap.get(row.name) ?? row.name };
}
}
const suffixRefusals = judgeExtensionFieldSuffix({ packageId: request.targetPackageId, objects: copiedObjects });
if (suffixRefusals.length > 0) throw extensionFieldSuffixRefusalError(suffixRefusals);
}
if (srcPkg?.manifest && typeof registry?.installPackage === 'function') {
try {
// Route through installPackage (not a bare registry write) so the
// duplicated base ALSO lands in sys_packages — otherwise the copy
// would vanish from GET /packages on the next restart (#2532).
// Spread-then-strip: the source may carry `scope` (e.g. 'project'
// on a code package) — copying it would brand the duplicate as
// read-only in every writability heuristic, when the whole point
// of a duplicate is a WRITABLE base. The copy is scope-less.
const dupManifest: Record<string, unknown> = {
...srcPkg.manifest,
id: request.targetPackageId,
name: request.targetName ?? `${srcPkg.manifest.name ?? request.sourcePackageId} (copy)`,
namespace: targetNs,
};
delete dupManifest.scope;
await host.installPackage({ manifest: dupManifest } as InstallPackageRequest);
} catch (e: any) {
// [#24041] ⭐ A REFUSED PACKAGE RECORD REFUSES THE DUPLICATE —
// the refusal itself, rethrown unchanged, before any item is
// copied (ruling B, claim amendment 6227008947).
//
// This catch used to drop it and copy anyway. A refused install
// leaves no registry record and no `sys_packages` row, so the
// copy's items were live, bound to an id no package record
// holds, absent from `GET /packages`. After a namespace conflict
// they also sat inside a namespace another package owns — the
// very state ADR-0048 Phase 1's install-time gate in
// `SchemaRegistry.installPackage` exists to refuse. The sibling
// verb {@link importUnmanagedPackage} states the rule this door
// now keeps: "There is no half-copied app."
//
// Nothing needs undoing: this call is the duplicate's FIRST
// mutation (everything above it reads), and a refused install
// leaves nothing behind — the registry judges before it writes,
// and a failed persist undoes the registry write before it
// throws (#21243). So the door answers the refusal's own status:
// `422 NAMESPACE_CONFLICT` with the registry's remedy (choose
// another namespace), or the primitive's `500` for a store fault.
//
// Logged once, because neither the primitive nor the HTTP door
// logs it. A store fault's driver text rides only on the error's
// `cause`, which no answer quotes, so the error itself is handed
// to the log for that one; a client refusal's sentence is
// already the whole story.
console.warn(
`[protocol.duplicatePackage] refused: the package record for '${request.targetPackageId}' `
+ `(copy of '${request.sourcePackageId}') was not installed, so nothing was copied: `
+ `${typeof e?.code === 'string' ? `${e.code}: ` : ''}${e?.message ?? e}`,
...(declaresClientRefusal(e) ? [] : [e]),
);
throw e;
}
}
const copied: Array<{ type: string; name: string }> = [];
const failed: Array<{ type: string; name: string; error: string }> = [];
// Resolved once for the whole copy: every flow row in this package needs
// the same engine, and a package with fifty flows should not walk the
// service table fifty times.
const canonicalizeFlow = host.resolveFlowCanonicalizer();
for (const row of rows) {
const refusal = row?.type === 'object' ? refusedObjects.get(row.name) : undefined;
if (refusal !== undefined) {
failed.push({ type: row.type, name: row.name, error: refusal });
continue;
}
const newName = row?.type === 'object'
? (renameMap.get(row.name) ?? row.name)
: isQualifiedViewRow(row)
? (viewItemRenames.get(row.name) ?? row.name)
: renameName(row.name);
const rawType = String(row.type);
const singular = PLURAL_TO_SINGULAR[rawType] ?? rawType;
let body: unknown;
try {
body = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : (row.metadata ?? {});
} catch {
failed.push({ type: row.type, name: row.name, error: 'unparseable metadata' });
continue;
}
// Canonicalize the source row before re-saving (#3903): the copy is
// a NEW write and must pass today's schema gate, so a legacy shape
// the chain owns is lifted rather than failing the copy —
// duplication never mints new rows in a pre-protocol dialect.
//
// For `flow` that guarantee was false until #4498: `convertStoredItem`
// returns flows untouched, and `FlowNodeSchema.config` is an open
// `z.record`, so a pre-17 body (`delete_record` with `config.filters`)
// sailed through `saveMetaItem` and landed verbatim in a brand-new
// row. ADR-0087 justifies the whole stored-metadata design on new
// writes being canonical — "a strictly shrinking concern" — and this
// was the one live producer contradicting it.
let item: any;
if (singular === 'flow') {
if (!canonicalizeFlow) {
// No engine in this process (control-plane / metadata-only
// host). Copy the source body as-is — the honest behaviour,
// and no worse than the source row already is — rather than
// failing a duplication that has nothing to do with flows.
// `os migrate meta --stored --apply` is the finish line for
// both rows, and it reports what it could not canonicalize.
item = body;
} else {
try {
const result = canonicalizeFlow(String(row.name ?? ''), body);
item = result.storable;
} catch (e: any) {
// `FlowSchema` is strict (#4001) and the region validator
// hard-fails: this source row cannot register at all, so
// the copy would be broken the same way. Report it.
failed.push({
type: row.type,
name: row.name,
error: `the flow does not canonicalize: ${e?.message ?? String(e)}`,
});
continue;
}
}
} else {
try {
item = host.convertStoredItem(rawType, body);
} catch (e: any) {
// A tombstoned key throws here (ADR-0087 D2) — a genuine
// contract violation in the source, not a parse failure.
failed.push({
type: row.type,
name: row.name,
error: `the source item does not convert: ${e?.message ?? String(e)}`,
});
continue;
}
}
const collisions: ReferenceCollision[] = [];
const rewritten = deepRewrite(item, collisions);
if (collisions.length > 0) {
const noun = singular === 'permission'
? 'Permission set'
: `${singular.charAt(0).toUpperCase()}${singular.slice(1)}`;
const more = collisions.length - 1;
failed.push({
type: row.type,
name: row.name,
error: `${noun} '${row.name}' is not copied: ${describeCollision(collisions[0]!)}`
+ (more > 0 ? ` It has ${more} more such collision${more === 1 ? '' : 's'}.` : ''),
});
continue;
}
if (rewritten && typeof rewritten === 'object' && !Array.isArray(rewritten)) {
rewritten.name = newName;
// [ADR-0086 D3] A permission set that declares its SOURCE
// package as its owner is copied declaring the target, the
// package the copy is saved into: the save door refuses a
// `packageId` that disagrees with that binding
// ({@link permissionSetOwnerBindingRefusal}), and the copy's
// owner is the target. Any other declared value is left as
// stored, so a source row that already disagreed with its own
// binding is reported in `failed[]` with the door's remedy.
if (singular === 'permission' && rewritten.packageId === request.sourcePackageId) {
rewritten.packageId = request.targetPackageId;
}
if (singular === 'permission' && rewritten.fields
&& typeof rewritten.fields === 'object' && !Array.isArray(rewritten.fields)) {
const result = rewriteFieldRuleKeys(rewritten.fields);
if ('collision' in result) {
failed.push({
type: row.type,
name: row.name,
error: `Permission set '${row.name}' is not copied: ${result.collision}`,
});
continue;
}
rewritten.fields = result.fields;
}
}
try {
await host.saveMetaItem({
type: row.type,
name: newName,
item: rewritten,
mode: 'publish',
packageId: request.targetPackageId,
// [commit 82cb6e849] Which door the refusal below will be prescribing
// a remedy FOR. Stated by the server, never by the caller —
// `duplicatePackage`'s own request type has no such field,
// exactly as `source` is server-stated one gate down. The
// Phase 3a-destructive gate reaches this call on the
// duplicate-AGAIN workflow, and its `?force=true` default
// would name a parameter this door does not accept.
writeFace: 'package-duplicate',
// [#30319] A copied permission set's grants are the SOURCE
// row's, so the unknown-object refusal does not judge the
// keys that row holds as stored — the clone door's rule
// (#30255) for this door's copy. A platform set may grant on
// an optional plugin's object this deployment does not
// install (`sys_comment`, `@objectstack/plugin-audit`).
// Derived from the stored row, never from the request; a key
// the rewrite above renamed is not the source's, and is judged.
...(singular === 'permission' ? { inheritedGrantObjects: storedGrantObjectKeys(body) } : {}),
...(request.actor ? { actor: request.actor } : {}),
});
copied.push({ type: row.type, name: newName });
} catch (e: any) {
// [#8333 · P10] `failed[].error` is copy-response DATA.
// Measured on `origin/main` by failing the `sys_metadata`
// insert under `saveMetaItem`: the field carried `SQLITE_ERROR:
// no such table: sys_metadata` verbatim.
//
// This `try` wraps exactly one call, and `saveMetaItem`'s
// authored refusals all declare 4xx — the spec rejection is
// `422 INVALID_METADATA` (measured: the whole "Unrecognized
// key(s) on this view container … Wrap it: `defineView({ … })`"
// prescription comes through unchanged), the author-time gate
// likewise 422, the org/overridability refusals 403. Nothing an
// author needs is blanked.
//
// ⛔ The two sibling `failed[]` pushes ABOVE this one (`the flow
// does not canonicalize` / `the source item does not convert`)
// are deliberately untouched: they interpolate authored
// schema-validation text, not driver text, and #8333 records
// them as examined-and-left.
failed.push({
type: row.type, name: row.name,
error: clientFacingFailureText(e, 'copy failed'),
});
console.warn(
`[protocol.duplicatePackage] copy failed for ${row.type}/${row.name} → `
+ `'${request.targetPackageId}': ${e?.message ?? e}`,
);
}
}
return {
success: failed.length === 0 && copied.length > 0,
copiedCount: copied.length,
failedCount: failed.length,
targetPackageId: request.targetPackageId,
copied,
failed,
};
}
/** The body of `ObjectStackProtocolImplementation#importUnmanagedPackage`; the method's docblock there is its contract. */
static async importUnmanagedPackage(host: Pick<ProtocolHost, 'convertStoredItem' | 'engine' | 'installPackage' | 'isRuntimeCreateAllowed' | 'refuseOrganizationScopedWrite' | 'resolveFlowCanonicalizer' | 'rollBackUnmanagedImport' | 'saveMetaItem' | 'unmanagedImportCollisions'>, request: ImportUnmanagedPackageRequest & { actor?: string },): Promise<ImportUnmanagedPackageResponse> {
const rawSourceId = (request as { manifest?: { id?: unknown } } | undefined)?.manifest?.id;
const sourceLabel = typeof rawSourceId === 'string' && rawSourceId !== '' ? rawSourceId : '(unnamed)';
// 1. FIRST, as on every package write verb.
host.refuseOrganizationScopedWrite(`Package '${sourceLabel}'`, request);
// 2. The request, through its published declaration. The two keys that
// are never a body's — the door's `actor`, and the organization the
// refusal above has already judged — are read off before the parse.
const { actor, organizationId: _scopeJudgedAbove, ...body } =
(request ?? {}) as ImportUnmanagedPackageRequest & { actor?: string; organizationId?: unknown };
const declared = ImportUnmanagedPackageRequestSchema.safeParse(body);
if (!declared.success) {
const issues = zodIssuesToMetadataIssues(declared.error.issues);
throw Object.assign(
new Error(`Invalid unmanaged install request: ${metadataIssueHeadline(issues)}.`),
{ statusCode: 400, issues },
);
}
// 3. The deployment walls organizations: nothing is read or written.
const walled = unmanagedInstallPostureRefusal(sourceLabel);
if (walled) throw walled;
// 4. Everything the body alone can answer.
const plan = planUnmanagedImport(declared.data.manifest, {
...(declared.data.targetPackageId !== undefined ? { targetPackageId: declared.data.targetPackageId } : {}),
...(declared.data.targetName !== undefined ? { targetName: declared.data.targetName } : {}),
// The save door's own predicate — registry-only, the hatch unread.
isRuntimeCreatable: (type) => host.isRuntimeCreateAllowed(type),
// The save door's own schema, asked which types declare the
// `protection` block the copy strips (ADR-0010 Phase 4.3).
protectionDeclarationOf: (type) => overlaySchemaDeclaredKey(type, 'protection'),
loadOrderOf: (type) =>
DEFAULT_METADATA_TYPE_REGISTRY.find((entry) => entry.type === type)?.loadOrder ?? Number.MAX_SAFE_INTEGER,
});
const { sourcePackageId, targetPackageId, namespace } = plan;
// 5. The handshake `installPackage` asks too — asked here so a refusal
// precedes the base.
assertProtocolCompat(declared.data.manifest);
// 6. A NEW base, under a namespace nobody owns.
const registry: any = (host.engine as any).registry;
if (registry?.getPackage?.(targetPackageId) || (host.engine as any).manifests?.has?.(targetPackageId)) {
throw Object.assign(new Error(
`Package '${targetPackageId}' already exists. An unmanaged install of '${sourcePackageId}' writes into a `
+ 'NEW base, never into an existing one. Name another `targetPackageId`, or uninstall '
+ `'${targetPackageId}' first.`,
), { code: 'RESOURCE_CONFLICT', status: 409, details: { targetPackageId } });
}
const owners: unknown = registry?.getNamespaceOwners?.(namespace);
if (Array.isArray(owners) && owners.length > 0) {
throw Object.assign(new Error(
`The namespace '${namespace}' of package '${sourcePackageId}' is already owned by `
+ `${owners.map((o) => `'${String(o)}'`).join(', ')}. The unmanaged copy keeps the source namespace, `
+ 'so it cannot sit beside a package that owns it — a managed install of this same package '
+ 'included. Uninstall that package first, or keep the managed install.',
), { code: 'RESOURCE_CONFLICT', status: 409, details: { namespace, owners } });
}
// 7. Today's protocol, item by item — the conversion a managed install
// applies to an artifact, so an older package imports as it installs.
const canonicalizeFlow = plan.items.some((i) => i.type === 'flow') ? host.resolveFlowCanonicalizer() : undefined;
const prepared: Array<{ type: string; name: string; item: unknown }> = [];
const unconvertible: string[] = [];
for (const planned of plan.items) {
try {
if (planned.type !== 'flow') {
prepared.push({ type: planned.type, name: planned.name, item: host.convertStoredItem(planned.type, planned.body) });
} else if (!canonicalizeFlow) {
// No engine in this process: the body as declared, exactly as
// `duplicatePackage` copies it; the save door still judges it.
prepared.push({ type: planned.type, name: planned.name, item: planned.body });
} else {
const result = canonicalizeFlow(planned.name, planned.body);
prepared.push({ type: planned.type, name: planned.name, item: result.storable });
}
} catch (e: any) {
unconvertible.push(`${planned.type} '${planned.name}': ${e?.message ?? String(e)}`);
}
}
if (unconvertible.length > 0) {
throw Object.assign(new Error(
`Package '${sourcePackageId}' cannot be installed unmanaged: ${unconvertible.length} item(s) do not convert `
+ `to this runtime's protocol — ${unconvertible.slice(0, 3).join('; ')}`
+ `${unconvertible.length > 3 ? ` (+${unconvertible.length - 3} more)` : ''}. Rebuild the package against `
+ 'this protocol, then install again.',
), { code: 'INVALID_METADATA', status: 422 });
}
// 8. Every name the copy would take, against the environment and the
// managed packages — the save door would refuse or overlay them.
const collisions = await host.unmanagedImportCollisions(plan.items);
if (collisions.length > 0) {
throw Object.assign(new Error(
`Package '${sourcePackageId}' cannot be installed unmanaged: ${collisions.length} of its names are already `
+ `taken — ${collisions.slice(0, 3).map((c) => `${c.type} '${c.name}' (${c.heldBy})`).join('; ')}`
+ `${collisions.length > 3 ? ` (+${collisions.length - 3} more)` : ''}. The copy keeps every name `
+ 'the package declares, so remove or rename the items that hold them, then install again.',
), { code: 'RESOURCE_CONFLICT', status: 409, details: { collisions } });
}
// The base. Not best-effort: a refusal here is the import's, and
// `installPackage` leaves nothing behind when it refuses.
await host.installPackage({ manifest: plan.baseManifest } as InstallPackageRequest);
const copied: Array<{ type: string; name: string }> = [];
for (const item of prepared) {
try {
await host.saveMetaItem({
type: item.type,
name: item.name,
item: item.item,
mode: 'publish',
packageId: targetPackageId,
// Server-stated, as on every face: no body reaches this field.
writeFace: 'package-unmanaged-import',
// [#30319] No `inheritedGrantObjects`, deliberately: the
// package is the request's body, not a stored row, so its
// permission sets are new writes and every grant is judged.
...(actor ? { actor } : {}),
});
copied.push({ type: item.type, name: item.name });
} catch (e: any) {
throw await host.rollBackUnmanagedImport(e, {
sourcePackageId, targetPackageId, failed: item, copiedCount: copied.length, actor,
});
}
}
return {
sourcePackageId,
...(plan.sourceVersion !== undefined ? { sourceVersion: plan.sourceVersion } : {}),
targetPackageId,
namespace,
copiedCount: copied.length,
copied,
// Planned before the base existed; every item was written, so every
// lock listed was dropped from a copy that now exists.
strippedLocks: plan.strippedLocks,
};
}
/** The body of `ObjectStackProtocolImplementation#reassignOrphanedMetadata`; the method's docblock there is its contract. */
static async reassignOrphanedMetadata(host: Pick<ProtocolHost, 'applyRegistryWriteThrough' | 'classifyObjectContribution' | 'engine' | 'findEnvironmentRows' | 'isArtifactBacked' | 'overlayPackageMismatchError' | 'refuseOrganizationScopedWrite' | 'releaseAdoptedObjectOwner' | 'storedOverlayEntries'>, request: {
targetPackageId: string;
actor?: string;
}): Promise<{
success: boolean;
reassignedCount: number;
reassigned: Array<{ type: string; name: string }>;
targetPackageId: string;
}> {
// [ADR-0131 D6] FIRST: an organization-scoped adoption is refused.
host.refuseOrganizationScopedWrite(