@prisma/orm-toolchain 8.0.0-rc.16-dev.7 → 8.0.0-rc.16-dev.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{aggregate-BGdw05Nj.d.mts → aggregate-C23h_Ybm.d.mts} +29 -21
- package/dist/{aggregate-BGdw05Nj.d.mts.map → aggregate-C23h_Ybm.d.mts.map} +1 -1
- package/dist/{aggregate-CG8Nfsg1.mjs → aggregate-DlfOyErc.mjs} +15 -2
- package/dist/aggregate-DlfOyErc.mjs.map +1 -0
- package/dist/{caught-errors-DHRx2eml-Az6yWv1r.mjs → caught-errors-HFQjjQVE-b_GDV-6J.mjs} +42 -4
- package/dist/caught-errors-HFQjjQVE-b_GDV-6J.mjs.map +1 -0
- package/dist/cli.mjs +153 -124
- package/dist/cli.mjs.map +1 -1
- package/dist/cli__control-api.d.mts +31 -50
- package/dist/cli__control-api.d.mts.map +1 -1
- package/dist/cli__control-api.mjs +2 -2
- package/dist/cli__control-api__testing.d.mts +1 -1
- package/dist/cli__control-api__testing.mjs +2 -0
- package/dist/cli__control-api__testing.mjs.map +1 -1
- package/dist/cli__migration-cli.mjs +1 -1
- package/dist/cli__migration-cli.mjs.map +1 -1
- package/dist/{db-sign-DqskX43K-CtEwW2Y6.d.mts → db-sign-BPf9SzzX-CwOFPxoZ.d.mts} +85 -70
- package/dist/db-sign-BPf9SzzX-CwOFPxoZ.d.mts.map +1 -0
- package/dist/migration-tools.d.mts +1 -1
- package/dist/migration-tools.mjs +1 -1
- package/dist/migration-tools__aggregate.d.mts +1 -1
- package/dist/migration-tools__aggregate.mjs +1 -1
- package/dist/{ref-QYB51IgO-ywgKx10n.mjs → ref-Cc_CTagE-C070Ym7p.mjs} +657 -227
- package/dist/ref-Cc_CTagE-C070Ym7p.mjs.map +1 -0
- package/dist/vite-plugin-contract-emit.mjs +1 -1
- package/package.json +13 -13
- package/dist/aggregate-CG8Nfsg1.mjs.map +0 -1
- package/dist/caught-errors-DHRx2eml-Az6yWv1r.mjs.map +0 -1
- package/dist/db-sign-DqskX43K-CtEwW2Y6.d.mts.map +0 -1
- package/dist/ref-QYB51IgO-ywgKx10n.mjs.map +0 -1
|
@@ -8,24 +8,22 @@ import { t as EMPTY_CONTRACT_HASH } from "./constants-CM-w38DQ-Cz_EXbOc.mjs";
|
|
|
8
8
|
import { i as findPathWithDecision, r as findPath } from "./migration-graph-BoiiZAaU-DLht12k7.mjs";
|
|
9
9
|
import { a as isValidSpaceId, c as spaceMigrationDirectory, l as spaceRefsDirectory, o as listContractSpaceDirectories, s as readContractSpaceHeadRef, t as APP_SPACE_ID$1 } from "./verify-contract-spaces-CYjc343k-ClHHEkJF.mjs";
|
|
10
10
|
import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-DGu96Hkk.mjs";
|
|
11
|
-
import { $ as runCommandAction, A as
|
|
11
|
+
import { $ as runCommandAction, A as errorRefSetEmptySentinel, B as errorStatementOriginUnknown, C as errorMigrationPlanningFailed, D as errorPlanOriginUnknown, E as errorPlanForgotTheFlag, F as errorSnapshotMissing, G as getTargetMigrations, H as errorTargetMigrationNotSupported, I as errorSpaceNotFound, J as readContractEnvelope, K as mapRefResolutionError, L as errorStatementAnswersNoQuestion, N as errorRuntime, O as errorPlanProducedNoOperations, Q as resolveMigrationPaths, R as errorStatementDidNotResolveLoss, T as errorPathUnreachable, V as errorStatementUnresolved, W as errorUnexpected, X as requireLiveDatabase, Z as resolveContractPath, a as closeQuietly, b as errorMarkerMismatch, c as errorAmbiguousMigrationRef, d as errorContractConfigMissing, f as errorContractValidationFailed, g as errorFromCaught, h as errorFileNotFound, i as chooseAction, j as errorRefSetHashNotInGraph, k as errorRefSetBundleNotFound, l as errorConfigValidation$1, n as CliStructuredError$1, o as collectDeclaredInvariants, r as STORE_ORIGIN_SNAPSHOT_STEPS, tt as toStructuralEdge, v as errorInvalidSpaceId, z as errorStatementInvalid } from "./caught-errors-HFQjjQVE-b_GDV-6J.mjs";
|
|
12
12
|
import { r as getEmittedArtifactPaths, t as emit } from "./exports-DaDckULH-JNQeM6Nn.mjs";
|
|
13
13
|
import { n as isGraphNode, t as assertHashIsGraphNode } from "./graph-membership-C_ZO26nT-B7C4CJsh.mjs";
|
|
14
14
|
import { d as writeRef, i as readRefs, l as validateRefName, n as deleteRef, o as refsByContractHash, t as HEAD_REF_NAME, u as validateRefValue } from "./refs-qwvw4_dV-DNg_7WTD.mjs";
|
|
15
|
-
import { a as contractHashAtMarker, c as loadContractSpaceAggregate, d as requireHeadRef, f as resolveRecordedPath, m as verifyMigration, n as buildFabricatedMigrationEdge, p as spacesInApplyOrder, r as collectAggregateNamespaces, t as allStorageElementsExternal, u as planMigration } from "./aggregate-
|
|
15
|
+
import { a as contractHashAtMarker, c as loadContractSpaceAggregate, d as requireHeadRef, f as resolveRecordedPath, m as verifyMigration, n as buildFabricatedMigrationEdge, p as spacesInApplyOrder, r as collectAggregateNamespaces, t as allStorageElementsExternal, u as planMigration } from "./aggregate-DlfOyErc.mjs";
|
|
16
16
|
import { c as internalImportRoot, o as importRootForDependencies, r as createImportSpecifierResolver, t as ImportRootError } from "./import-roots-BeAYfehL.mjs";
|
|
17
17
|
import { c as parseContractRef, l as parseMigrationRef, o as isLiveMarkerRef, r as RESERVED_CONTRACT_REFS, s as isReservedContractRef, t as EMPTY_CONTRACT_REF } from "./ref-resolution-Be_zewf7.mjs";
|
|
18
18
|
import { i as writeMigrationTs } from "./migration-ts-FyF55c4M.mjs";
|
|
19
19
|
import { createRequire } from "node:module";
|
|
20
20
|
import { ifDefined } from "@prisma/orm-framework/utils/defined";
|
|
21
21
|
import { CliStructuredError } from "@prisma/orm-framework/errors/control";
|
|
22
|
-
import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, createControlStack, describeMigrationStatement, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, modelDisplayName, planOriginOf } from "@prisma/orm-framework/components/control";
|
|
22
|
+
import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, createControlStack, describeMigrationStatement, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, planOriginOf } from "@prisma/orm-framework/components/control";
|
|
23
23
|
import { InternalError } from "@prisma/orm-framework/utils/internal-error";
|
|
24
24
|
import { isStructuredErrorCode, structuredError } from "@prisma/orm-framework/utils/structured-error";
|
|
25
25
|
import { basename, dirname, isAbsolute, join, relative, resolve } from "pathe";
|
|
26
26
|
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
27
|
-
import { createHash } from "node:crypto";
|
|
28
|
-
import { canonicalizeJson } from "@prisma/orm-framework/components/utils";
|
|
29
27
|
import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
|
|
30
28
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
31
29
|
import { keepInternalSpecifiers } from "@prisma/orm-framework/components/emission";
|
|
@@ -35,7 +33,7 @@ import { mergeCapabilityMatrices } from "@prisma/orm-framework/components/compon
|
|
|
35
33
|
import { asNamespaceId } from "@prisma/orm-framework/contract/types";
|
|
36
34
|
import { abortable } from "@prisma/orm-framework/utils/abortable";
|
|
37
35
|
import { resolve as resolve$1 } from "node:path";
|
|
38
|
-
//#region ../../../1-framework/3-tooling/cli/dist/ref-
|
|
36
|
+
//#region ../../../1-framework/3-tooling/cli/dist/ref-Cc_CTagE.mjs
|
|
39
37
|
/**
|
|
40
38
|
* Asserts that all framework components are compatible with the expected family and target.
|
|
41
39
|
*
|
|
@@ -168,16 +166,21 @@ function enrichContract(ir, components) {
|
|
|
168
166
|
extensions: sortDeepTyped(extensions)
|
|
169
167
|
};
|
|
170
168
|
}
|
|
169
|
+
function formsFix(verb) {
|
|
170
|
+
return verb === "delete" ? "Write the statement as --delete <name>, where the name is Model, namespace.Model, Model.field or namespace.Model.field, or the storage name the refusal gave, for example --delete Legacy or --delete User.nickname." : "Write the statement as --allow <name>, where the name is the model the refusal gave, for example --allow User.";
|
|
171
|
+
}
|
|
171
172
|
/**
|
|
172
|
-
*
|
|
173
|
-
*
|
|
173
|
+
* Checks the text of one delete or allow statement. The text stays unresolved: it names what a
|
|
174
|
+
* plan would do to a subject, so it is matched by equality against the plan's subjects, not
|
|
175
|
+
* resolved against the contracts. Any name a subject can have is accepted, since a storage name
|
|
176
|
+
* may contain any character a quoted identifier can.
|
|
174
177
|
*/
|
|
175
|
-
function
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
})
|
|
178
|
+
function parseConsentStatement(statement) {
|
|
179
|
+
if (statement.text.trim() === "") return notOk(errorStatementInvalid(statement, "The statement names nothing.", formsFix(statement.verb)));
|
|
180
|
+
return ok({
|
|
181
|
+
verb: statement.verb,
|
|
182
|
+
text: statement.text
|
|
183
|
+
});
|
|
181
184
|
}
|
|
182
185
|
const MAX_SEGMENTS = 3;
|
|
183
186
|
/** The forms a statement takes, with an example of each. */
|
|
@@ -546,13 +549,32 @@ function resolveStatement(state, statement, later) {
|
|
|
546
549
|
return notOk(errorStatementInvalid(statement, "The statement names a model on one side and a field on the other.", mixedSidesFix(statement.verb, statement.from, statement.to)));
|
|
547
550
|
}
|
|
548
551
|
/**
|
|
549
|
-
* Resolves the statements a user gave, in order, against the origin and
|
|
552
|
+
* Resolves the rename statements a user gave, in order, against the origin and
|
|
550
553
|
* destination contracts. Each resolved statement names its old and new entity
|
|
551
|
-
* by namespace, model and field.
|
|
554
|
+
* by namespace, model and field. A delete or allow statement is checked and
|
|
555
|
+
* left out: it names what a plan would do to a subject, so it is matched against
|
|
556
|
+
* the plan, and it needs no origin contract.
|
|
552
557
|
*/
|
|
553
558
|
function resolveStatements(input) {
|
|
554
|
-
|
|
555
|
-
|
|
559
|
+
const parsed = [];
|
|
560
|
+
for (const entry of input.statements) {
|
|
561
|
+
if (entry.verb === "delete" || entry.verb === "allow") {
|
|
562
|
+
const statement = parseConsentStatement({
|
|
563
|
+
...entry,
|
|
564
|
+
verb: entry.verb
|
|
565
|
+
});
|
|
566
|
+
if (!statement.ok) return statement;
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
if (input.origin.kind === "missing") return notOk(errorStatementOriginUnknown(input.origin));
|
|
570
|
+
const statement = parseRenameStatement({
|
|
571
|
+
...entry,
|
|
572
|
+
verb: entry.verb
|
|
573
|
+
});
|
|
574
|
+
if (!statement.ok) return statement;
|
|
575
|
+
parsed.push(statement.value);
|
|
576
|
+
}
|
|
577
|
+
if (parsed.length === 0 || input.origin.kind === "missing") return ok([]);
|
|
556
578
|
const state = {
|
|
557
579
|
origin: {
|
|
558
580
|
name: "origin",
|
|
@@ -566,12 +588,6 @@ function resolveStatements(input) {
|
|
|
566
588
|
renamedFrom: /* @__PURE__ */ new Set(),
|
|
567
589
|
renamedTo: /* @__PURE__ */ new Set()
|
|
568
590
|
};
|
|
569
|
-
const parsed = [];
|
|
570
|
-
for (const entry of input.statements) {
|
|
571
|
-
const statement = parseRenameStatement(entry);
|
|
572
|
-
if (!statement.ok) return statement;
|
|
573
|
-
parsed.push(statement.value);
|
|
574
|
-
}
|
|
575
591
|
const resolved = [];
|
|
576
592
|
for (const [index, statement] of parsed.entries()) {
|
|
577
593
|
const result = resolveStatement(state, statement, parsed.slice(index + 1));
|
|
@@ -580,6 +596,330 @@ function resolveStatements(input) {
|
|
|
580
596
|
}
|
|
581
597
|
return ok(resolved);
|
|
582
598
|
}
|
|
599
|
+
function modelText(contract, coordinate) {
|
|
600
|
+
return Object.keys(contract.domain.namespaces).length > 1 ? modelDisplayName(coordinate) : coordinate.model;
|
|
601
|
+
}
|
|
602
|
+
/** The model a rename statement of `contracts` gives `coordinate` in the destination, if any. */
|
|
603
|
+
function renamedModel(coordinate, contracts) {
|
|
604
|
+
if (contracts.destination === void 0 || contracts.renames.length === 0) return void 0;
|
|
605
|
+
const resolved = resolveStatements({
|
|
606
|
+
statements: contracts.renames,
|
|
607
|
+
origin: {
|
|
608
|
+
kind: "contract",
|
|
609
|
+
contract: contracts.origin
|
|
610
|
+
},
|
|
611
|
+
destination: contracts.destination
|
|
612
|
+
});
|
|
613
|
+
if (!resolved.ok) return void 0;
|
|
614
|
+
return resolved.value.find((statement) => statement.entity === "model" && statement.from.namespaceId === coordinate.namespaceId && statement.from.model === coordinate.model)?.to;
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* The subject as a statement names it: `Model` or `Model.field`, with the namespace when its
|
|
618
|
+
* contract has several, or the storage name when no model stores what the operation is about. A
|
|
619
|
+
* field of a model the plan renames is named through the model's new name, as a rename of the
|
|
620
|
+
* field is written.
|
|
621
|
+
*/
|
|
622
|
+
function subjectText(subject, contracts) {
|
|
623
|
+
switch (subject.kind) {
|
|
624
|
+
case "model": return modelText(contracts.origin, subject);
|
|
625
|
+
case "field": {
|
|
626
|
+
const renamed = renamedModel(subject, contracts);
|
|
627
|
+
return `${renamed === void 0 || contracts.destination === void 0 ? modelText(contracts.origin, subject) : modelText(contracts.destination, renamed)}.${subject.field}`;
|
|
628
|
+
}
|
|
629
|
+
case "storage": return subject.name;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
/** The statement's description, written as its question names the subject: `delete field "User.nickname"`. */
|
|
633
|
+
function consentDescription(verb, subject, text) {
|
|
634
|
+
return `${verb} ${subject.kind} "${text}"`;
|
|
635
|
+
}
|
|
636
|
+
function lossText(subject, text, originKnown) {
|
|
637
|
+
switch (subject.kind) {
|
|
638
|
+
case "model": return `would lose the data of model "${text}"`;
|
|
639
|
+
case "field": return `would lose the values of field "${text}"`;
|
|
640
|
+
case "storage": return originKnown ? `would lose the data in "${text}", which no model of the origin contract stores` : `would lose the data in "${text}", named by its storage name because the origin contract is unknown; --delete loses its rows`;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* How to keep the rows of a storage subject that was renamed, when the origin contract is unknown:
|
|
645
|
+
* store the snapshot of the contract the database is at, as `MIGRATION.STATEMENT_ORIGIN_UNKNOWN`
|
|
646
|
+
* advises, then answer with a rename. The refusal gives it once, on its first storage question. The
|
|
647
|
+
* engine does not put the CLI's name in a question's text, so the steps name `prisma`.
|
|
648
|
+
*/
|
|
649
|
+
const ORIGIN_SNAPSHOT_RECOVERY = ["If it was renamed, keep its data instead: store the snapshot of the contract the database is at, then run this command again and answer with --rename.", ...STORE_ORIGIN_SNAPSHOT_STEPS.map((step) => step.replaceAll("{bin}", "prisma"))].join(" ");
|
|
650
|
+
function sameCoordinate(statement, subject) {
|
|
651
|
+
if (subject.kind === "storage") return false;
|
|
652
|
+
const { from } = statement;
|
|
653
|
+
if (from.namespaceId !== subject.namespaceId || from.model !== subject.model) return false;
|
|
654
|
+
return subject.kind === "field" ? statement.entity === "field" && statement.from.field === subject.field : statement.entity === "model";
|
|
655
|
+
}
|
|
656
|
+
function namesSubject(verb, subject) {
|
|
657
|
+
return (text) => text === subject ? void 0 : `${verb} names "${subject}": --${verb} ${subject}.`;
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* How the target says to keep a subject's data by hand when its planner carries out no rename, or
|
|
661
|
+
* `undefined` when it carries them out.
|
|
662
|
+
*/
|
|
663
|
+
function keepDataByHandFor(migrations, origin) {
|
|
664
|
+
const refused = migrations.renameStatements;
|
|
665
|
+
return refused === void 0 ? void 0 : (subject) => refused.keepDataByHand(subject, origin);
|
|
666
|
+
}
|
|
667
|
+
/** A rename as a statement is written: a field's new name keeps the model, `User.nickname:User.<new name>`. */
|
|
668
|
+
function renameForm(subject, text) {
|
|
669
|
+
return subject.kind === "field" ? `${text}:${text.slice(0, text.lastIndexOf("."))}.<new name>` : `${text}:<new name>`;
|
|
670
|
+
}
|
|
671
|
+
/** Whether a rename statement of the plan already gives the subject a new name. */
|
|
672
|
+
function renamedByPlan(subject, contracts) {
|
|
673
|
+
if (subject.kind === "storage" || contracts.renames.length === 0) return false;
|
|
674
|
+
const resolved = resolveStatements({
|
|
675
|
+
statements: contracts.renames,
|
|
676
|
+
origin: {
|
|
677
|
+
kind: "contract",
|
|
678
|
+
contract: contracts.origin
|
|
679
|
+
},
|
|
680
|
+
destination: contracts.destination
|
|
681
|
+
});
|
|
682
|
+
return resolved.ok && resolved.value.some((statement) => sameCoordinate(statement, subject));
|
|
683
|
+
}
|
|
684
|
+
/** Whether the destination still has the subject's model or field, under the name a rename gives it. */
|
|
685
|
+
function inDestination(subject, contracts) {
|
|
686
|
+
if (subject.kind === "storage") return false;
|
|
687
|
+
const model = renamedModel(subject, contracts) ?? subject;
|
|
688
|
+
const destinationModel = contracts.destination.domain.namespaces[model.namespaceId]?.models[model.model];
|
|
689
|
+
if (destinationModel === void 0) return false;
|
|
690
|
+
return subject.kind === "model" || Object.hasOwn(destinationModel.fields, subject.field);
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* The question for one operation that would lose data. A model or field the destination no longer
|
|
694
|
+
* has, and no rename of the plan renamed, may be renamed instead of deleted; a rename is resolved
|
|
695
|
+
* against the two contracts after the plan's other renames, and its old name must be the subject.
|
|
696
|
+
* A subject the destination keeps, such as a field whose type changes, and data no model stores,
|
|
697
|
+
* can only be deleted. Where the target's planner carries out no rename, `keepDataByHand` says how
|
|
698
|
+
* to keep the data instead.
|
|
699
|
+
*/
|
|
700
|
+
function dataLossQuestion(loss, contracts) {
|
|
701
|
+
const subject = subjectText(loss.subject, contracts);
|
|
702
|
+
const renamable = contracts.keepDataByHand === void 0 && loss.subject.kind !== "storage" && !inDestination(loss.subject, contracts) && !renamedByPlan(loss.subject, contracts);
|
|
703
|
+
const deleteNames = namesSubject("delete", subject);
|
|
704
|
+
return {
|
|
705
|
+
question: [`${loss.label} ${lossText(loss.subject, subject, contracts.originKnown)}.`, ...contracts.keepDataByHand === void 0 ? [] : [contracts.keepDataByHand(loss.subject)]].join(" "),
|
|
706
|
+
subject,
|
|
707
|
+
verbs: renamable ? ["rename", "delete"] : ["delete"],
|
|
708
|
+
forms: renamable ? { rename: renameForm(loss.subject, subject) } : {},
|
|
709
|
+
validate: (verb, text) => {
|
|
710
|
+
if (verb !== "rename") return deleteNames(text);
|
|
711
|
+
const resolved = resolveStatements({
|
|
712
|
+
statements: [...contracts.renames, {
|
|
713
|
+
verb: "rename",
|
|
714
|
+
text
|
|
715
|
+
}],
|
|
716
|
+
origin: {
|
|
717
|
+
kind: "contract",
|
|
718
|
+
contract: contracts.origin
|
|
719
|
+
},
|
|
720
|
+
destination: contracts.destination
|
|
721
|
+
});
|
|
722
|
+
if (!resolved.ok) return `${resolved.failure.message}. ${resolved.failure.why ?? ""}`.trim();
|
|
723
|
+
const statement = resolved.value.at(-1);
|
|
724
|
+
return statement !== void 0 && sameCoordinate(statement, loss.subject) ? void 0 : `The rename's old name is not "${subject}". Write it as ${renameForm(loss.subject, subject)}.`;
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* The question for one operation that changes who can read or write its subject's rows: it widens
|
|
730
|
+
* access, as disabling row-level security does, or changes it either way, as dropping a policy
|
|
731
|
+
* does. Each such operation is its own question, answered by its own `allow`.
|
|
732
|
+
*/
|
|
733
|
+
function accessWideningQuestion(widening, contracts) {
|
|
734
|
+
const subject = subjectText(widening.subject, contracts);
|
|
735
|
+
return {
|
|
736
|
+
question: `${widening.label} would ${widening.widens ? "widen" : "change"} who can read and write its rows.`,
|
|
737
|
+
subject,
|
|
738
|
+
verbs: ["allow"],
|
|
739
|
+
forms: {},
|
|
740
|
+
validate: (_verb, text) => namesSubject("allow", subject)(text)
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
const keyOf = (planned) => migrationSubjectKey(planned.subject);
|
|
744
|
+
/**
|
|
745
|
+
* The pre-answers that answer a question about `text`: every `delete` of the subject, or the
|
|
746
|
+
* first `allow` of it no earlier question took, since an `allow` answers one operation.
|
|
747
|
+
*/
|
|
748
|
+
function givenFor(verb, text, preAnswers, taken) {
|
|
749
|
+
const matching = preAnswers.filter((statement) => statement.verb === verb && statement.text === text);
|
|
750
|
+
if (verb === "delete") return matching;
|
|
751
|
+
const first = matching.find((statement) => !taken.has(statement));
|
|
752
|
+
return first === void 0 ? [] : [first];
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* A `delete` answers for its subject; an `allow` for its one operation, known by its label and
|
|
756
|
+
* subject, since a re-plan moves every operation's position.
|
|
757
|
+
*/
|
|
758
|
+
function questionKey(verb, entry) {
|
|
759
|
+
return verb === "allow" ? `allow:${entry.label}:${keyOf(entry)}` : `delete:${keyOf(entry)}`;
|
|
760
|
+
}
|
|
761
|
+
function checkAnswers(questions, answers) {
|
|
762
|
+
if (answers.length !== questions.length) {
|
|
763
|
+
const noun = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
764
|
+
throw new InternalError(`answerQuestions gave ${noun(answers.length, "answer")} for ${noun(questions.length, "question")}; answer each question in order, or throw to refuse.`, { cause: {
|
|
765
|
+
questions: questions.map(({ subject }) => subject),
|
|
766
|
+
answers
|
|
767
|
+
} });
|
|
768
|
+
}
|
|
769
|
+
questions.forEach((question, index) => {
|
|
770
|
+
const answer = answers[index];
|
|
771
|
+
if (answer === void 0) return;
|
|
772
|
+
const cause = { cause: {
|
|
773
|
+
question: question.subject,
|
|
774
|
+
verbs: question.verbs,
|
|
775
|
+
answer
|
|
776
|
+
} };
|
|
777
|
+
if (!question.verbs.includes(answer.verb)) throw new InternalError(`answerQuestions answered "${question.question}" with ${answer.verb}, which it does not accept; it accepts ${question.verbs.join(" or ")}.`, cause);
|
|
778
|
+
const rejected = question.validate(answer.verb, answer.text);
|
|
779
|
+
if (rejected !== void 0) throw new InternalError(`answerQuestions answered "${question.question}" wrongly: ${rejected}`, cause);
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
function withRecoveryOnFirstStorageQuestion(asked, recoveryApplies) {
|
|
783
|
+
const first = recoveryApplies ? asked.findIndex(({ loss }) => loss.subject.kind === "storage") : -1;
|
|
784
|
+
return asked.map(({ question }, index) => index === first ? {
|
|
785
|
+
...question,
|
|
786
|
+
question: `${question.question} ${ORIGIN_SNAPSHOT_RECOVERY}`
|
|
787
|
+
} : question);
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* Asks about every operation of a plan that would lose data and, when `askAccess`, every one that
|
|
791
|
+
* would widen access, until each is answered. A `delete` or `allow` text in `preAnswers`, or
|
|
792
|
+
* `consentAll` for its verb, answers its question without asking. A rename typed at the prompt is a statement
|
|
793
|
+
* the plan did not have, so the plan is made again with it, and the operation it answered must be
|
|
794
|
+
* gone; a loss the new plan has on the same subject, such as a type change on the renamed field,
|
|
795
|
+
* is asked in the next round. The first round asks even when nothing is in question, so a statement no question consumed is
|
|
796
|
+
* refused before anything is done.
|
|
797
|
+
*/
|
|
798
|
+
async function askPlanQuestions(input) {
|
|
799
|
+
let plan = input.plan;
|
|
800
|
+
let renames = input.renames;
|
|
801
|
+
const consented = /* @__PURE__ */ new Map();
|
|
802
|
+
const usedPreAnswers = /* @__PURE__ */ new Set();
|
|
803
|
+
for (let round = 0;; round += 1) {
|
|
804
|
+
const contracts = {
|
|
805
|
+
origin: input.origin,
|
|
806
|
+
originKnown: input.originKnown,
|
|
807
|
+
keepDataByHand: input.keepDataByHand,
|
|
808
|
+
destination: input.destination,
|
|
809
|
+
renames
|
|
810
|
+
};
|
|
811
|
+
const pending = (verb, planned) => [...new Map(planned.filter((entry) => !consented.has(questionKey(verb, entry))).map((entry) => [questionKey(verb, entry), entry])).values()];
|
|
812
|
+
const consent = (verb, entry, text) => consented.set(questionKey(verb, entry), {
|
|
813
|
+
verb,
|
|
814
|
+
subject: entry.subject,
|
|
815
|
+
text,
|
|
816
|
+
operationIndex: entry.operationIndex
|
|
817
|
+
});
|
|
818
|
+
for (const [verb, entries] of [["delete", pending("delete", plan.dataLoss)], ["allow", input.askAccess ? pending("allow", plan.accessWidening) : []]]) for (const entry of entries) {
|
|
819
|
+
const text = subjectText(entry.subject, contracts);
|
|
820
|
+
const given = givenFor(verb, text, input.preAnswers, usedPreAnswers);
|
|
821
|
+
for (const statement of given) usedPreAnswers.add(statement);
|
|
822
|
+
if (input.consentAll[verb] || given.length > 0) consent(verb, entry, text);
|
|
823
|
+
}
|
|
824
|
+
const losses = pending("delete", plan.dataLoss);
|
|
825
|
+
const widenings = input.askAccess ? pending("allow", plan.accessWidening) : [];
|
|
826
|
+
if (losses.length + widenings.length === 0 && round > 0) break;
|
|
827
|
+
const questions = [...withRecoveryOnFirstStorageQuestion(losses.map((loss) => ({
|
|
828
|
+
loss,
|
|
829
|
+
question: dataLossQuestion(loss, contracts)
|
|
830
|
+
})), !input.originKnown && input.keepDataByHand === void 0), ...widenings.map((widening) => accessWideningQuestion(widening, contracts))];
|
|
831
|
+
const answers = await input.answer(questions);
|
|
832
|
+
checkAnswers(questions, answers);
|
|
833
|
+
const typedRenames = [];
|
|
834
|
+
answers.forEach((answer, index) => {
|
|
835
|
+
const entry = [...losses, ...widenings][index];
|
|
836
|
+
const question = questions[index];
|
|
837
|
+
if (entry === void 0 || question === void 0) return;
|
|
838
|
+
if (answer.verb === "rename") typedRenames.push({
|
|
839
|
+
text: answer.text,
|
|
840
|
+
loss: entry
|
|
841
|
+
});
|
|
842
|
+
else consent(answer.verb, entry, question.subject);
|
|
843
|
+
});
|
|
844
|
+
if (typedRenames.length === 0) {
|
|
845
|
+
if (losses.length + widenings.length === 0) break;
|
|
846
|
+
continue;
|
|
847
|
+
}
|
|
848
|
+
renames = [...renames, ...typedRenames.map(({ text }) => ({
|
|
849
|
+
verb: "rename",
|
|
850
|
+
text
|
|
851
|
+
}))];
|
|
852
|
+
const replanned = await input.replan(renames);
|
|
853
|
+
if (!replanned.ok) return replanned;
|
|
854
|
+
plan = replanned.value;
|
|
855
|
+
for (const entry of plan.accessWidening) {
|
|
856
|
+
const allowed = consented.get(questionKey("allow", entry));
|
|
857
|
+
if (allowed !== void 0) consented.set(questionKey("allow", entry), {
|
|
858
|
+
...allowed,
|
|
859
|
+
operationIndex: entry.operationIndex
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
const operationOf = (entry) => `${entry.label}:${keyOf(entry)}`;
|
|
863
|
+
const stillPlanned = new Set(plan.dataLoss.map(operationOf));
|
|
864
|
+
const unresolved = typedRenames.find(({ loss }) => stillPlanned.has(operationOf(loss)));
|
|
865
|
+
if (unresolved !== void 0) return notOk(errorStatementDidNotResolveLoss({
|
|
866
|
+
verb: "rename",
|
|
867
|
+
text: unresolved.text
|
|
868
|
+
}, subjectText(unresolved.loss.subject, contracts)));
|
|
869
|
+
}
|
|
870
|
+
const unused = input.preAnswers.filter((statement) => !usedPreAnswers.has(statement));
|
|
871
|
+
if (unused.length > 0) return notOk(errorStatementAnswersNoQuestion(unused, questionSubjects(plan, input.askAccess, {
|
|
872
|
+
...input,
|
|
873
|
+
renames
|
|
874
|
+
})));
|
|
875
|
+
return ok({
|
|
876
|
+
plan,
|
|
877
|
+
renames,
|
|
878
|
+
consented: [...consented.values()]
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
function questionSubjects(plan, askAccess, contracts) {
|
|
882
|
+
const subjects = [...plan.dataLoss, ...askAccess ? plan.accessWidening : []].map((entry) => subjectText(entry.subject, contracts));
|
|
883
|
+
return [...new Set(subjects)];
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Refuses the `delete` and `allow` statements that name no subject a plan asks about, without
|
|
887
|
+
* asking anything: a run that only plans still says which statements would consent to nothing.
|
|
888
|
+
*/
|
|
889
|
+
function refuseUnusedConsents(input) {
|
|
890
|
+
const subjects = questionSubjects(input.plan, true, input.contracts);
|
|
891
|
+
const used = /* @__PURE__ */ new Set();
|
|
892
|
+
for (const [verb, entries] of [["delete", input.plan.dataLoss], ["allow", input.plan.accessWidening]]) for (const entry of entries) {
|
|
893
|
+
const text = subjectText(entry.subject, input.contracts);
|
|
894
|
+
for (const statement of givenFor(verb, text, input.statements, used)) used.add(statement);
|
|
895
|
+
}
|
|
896
|
+
const unused = input.statements.filter((statement) => statement.verb !== "rename" && !used.has(statement));
|
|
897
|
+
return unused.length === 0 ? ok(void 0) : notOk(errorStatementAnswersNoQuestion(unused, subjects));
|
|
898
|
+
}
|
|
899
|
+
/**
|
|
900
|
+
* `operationOffset` is the number of operations the result lists before the plan that applied the
|
|
901
|
+
* statements, so that each position indexes the result's `operations`.
|
|
902
|
+
*/
|
|
903
|
+
function reportAppliedStatements(applied, fromContract, contract, operationOffset) {
|
|
904
|
+
return applied.map((entry) => ({
|
|
905
|
+
verb: "rename",
|
|
906
|
+
statement: migrationStatementJson(entry.statement),
|
|
907
|
+
operationIndexes: entry.operationIndexes.map((index) => operationOffset + index),
|
|
908
|
+
description: describeMigrationStatement(entry.statement, fromContract ?? contract, contract)
|
|
909
|
+
}));
|
|
910
|
+
}
|
|
911
|
+
/** A delete or allow statement a plan applied, with the positions of the operations it consented to. */
|
|
912
|
+
function reportConsentStatement(consented, operationIndexes) {
|
|
913
|
+
return {
|
|
914
|
+
verb: consented.verb,
|
|
915
|
+
statement: {
|
|
916
|
+
kind: consented.verb,
|
|
917
|
+
subject: migrationSubjectJson(consented.subject)
|
|
918
|
+
},
|
|
919
|
+
operationIndexes,
|
|
920
|
+
description: consentDescription(consented.verb, consented.subject, consented.text)
|
|
921
|
+
};
|
|
922
|
+
}
|
|
583
923
|
/**
|
|
584
924
|
* Project the CLI's `Config.extensions` array into the canonical
|
|
585
925
|
* {@link ExtensionPackInput} shape. The single `as ExtensionPackLike`
|
|
@@ -864,7 +1204,8 @@ async function buildReadAggregate(config, options) {
|
|
|
864
1204
|
if (!loaded.ok) return loaded;
|
|
865
1205
|
return ok({
|
|
866
1206
|
aggregate: loaded.value,
|
|
867
|
-
contractHash
|
|
1207
|
+
contractHash,
|
|
1208
|
+
storageNameOf: (operation) => familyInstance.storageNameOf(operation)
|
|
868
1209
|
});
|
|
869
1210
|
} catch (error) {
|
|
870
1211
|
return notOk(errorFromCaught(error, (message) => `Failed to read migrations directory: ${message}`));
|
|
@@ -882,20 +1223,6 @@ function stripOperations(operations) {
|
|
|
882
1223
|
}));
|
|
883
1224
|
}
|
|
884
1225
|
/**
|
|
885
|
-
* Content identity of a `db update` plan: what it does (the ordered display
|
|
886
|
-
* operations) and where it lands (the destination storage hash). A
|
|
887
|
-
* `DESTRUCTIVE_CHANGES` refusal names the refused plan by this hash, and the
|
|
888
|
-
* apply that carries the consent back recomputes it to prove it is still
|
|
889
|
-
* applying the plan that was consented to.
|
|
890
|
-
*/
|
|
891
|
-
function computePlanHash(plan) {
|
|
892
|
-
const canonical = canonicalizeJson({
|
|
893
|
-
operations: plan.operations,
|
|
894
|
-
destination: { storageHash: plan.destination.storageHash }
|
|
895
|
-
});
|
|
896
|
-
return createHash("sha256").update(canonical).digest("hex");
|
|
897
|
-
}
|
|
898
|
-
/**
|
|
899
1226
|
* Span id emitted via `onProgress` for the run phase. Stable
|
|
900
1227
|
* identifier consumed by the structured-output renderer and by tests.
|
|
901
1228
|
*/
|
|
@@ -1077,25 +1404,25 @@ async function executeRun(options) {
|
|
|
1077
1404
|
if (!loaded.ok) throw loaded.failure;
|
|
1078
1405
|
const aggregate = loaded.value;
|
|
1079
1406
|
const markerRows = await familyInstance.readAllMarkers({ driver });
|
|
1080
|
-
|
|
1081
|
-
|
|
1407
|
+
const appOrigin = options.action === "dbUpdate" ? await readAppOrigin({
|
|
1408
|
+
marker: markerRows.get(aggregate.app.spaceId) ?? null,
|
|
1409
|
+
migrationsDir,
|
|
1410
|
+
deserializeContract: (json) => familyInstance.deserializeContract(json),
|
|
1411
|
+
...ifDefined("verifySnapshotContent", options.verifySnapshotContent)
|
|
1412
|
+
}) : void 0;
|
|
1413
|
+
const fromContract = appOrigin?.contract ?? null;
|
|
1082
1414
|
const statementTexts = options.action === "dbUpdate" ? options.statements : [];
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
marker: markerRows.get(aggregate.app.spaceId) ?? null,
|
|
1086
|
-
migrationsDir,
|
|
1087
|
-
deserializeContract: (json) => familyInstance.deserializeContract(json),
|
|
1088
|
-
...ifDefined("verifySnapshotContent", options.verifySnapshotContent)
|
|
1089
|
-
});
|
|
1415
|
+
const resolveRenames = (texts) => {
|
|
1416
|
+
if (texts.length === 0 || appOrigin === void 0) return [];
|
|
1090
1417
|
const resolved = resolveStatements({
|
|
1091
|
-
statements:
|
|
1418
|
+
statements: texts,
|
|
1092
1419
|
origin: appOrigin.origin,
|
|
1093
1420
|
destination: contract
|
|
1094
1421
|
});
|
|
1095
1422
|
if (!resolved.ok) throw resolved.failure;
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1423
|
+
return resolved.value;
|
|
1424
|
+
};
|
|
1425
|
+
const statements = resolveRenames(statementTexts);
|
|
1099
1426
|
if (mode === "apply") {
|
|
1100
1427
|
const orphanMarkerError = detectOrphanMarkers(aggregate, markerRows);
|
|
1101
1428
|
if (orphanMarkerError !== null) throw orphanMarkerError;
|
|
@@ -1116,49 +1443,124 @@ async function executeRun(options) {
|
|
|
1116
1443
|
spanId: SPAN_IDS$1.introspect,
|
|
1117
1444
|
outcome: "ok"
|
|
1118
1445
|
});
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1446
|
+
const plan = async (resolved) => {
|
|
1447
|
+
onProgress?.({
|
|
1448
|
+
action,
|
|
1449
|
+
kind: "spanStart",
|
|
1450
|
+
spanId: SPAN_IDS$1.plan,
|
|
1451
|
+
label: "Planning migration"
|
|
1452
|
+
});
|
|
1453
|
+
const planned = await planMigration({
|
|
1454
|
+
aggregate,
|
|
1455
|
+
currentDBState: {
|
|
1456
|
+
markersBySpaceId: markerRows,
|
|
1457
|
+
schemaIntrospection: schemaIR
|
|
1458
|
+
},
|
|
1459
|
+
adapter,
|
|
1460
|
+
migrations,
|
|
1461
|
+
frameworkComponents,
|
|
1462
|
+
callerPolicy: { ignoreGraphFor: /* @__PURE__ */ new Set([aggregate.app.spaceId]) },
|
|
1463
|
+
operationPolicy: policy,
|
|
1464
|
+
appSpace: {
|
|
1465
|
+
fromContract,
|
|
1466
|
+
statements: resolved
|
|
1467
|
+
},
|
|
1468
|
+
storageNameOf: (operation) => familyInstance.storageNameOf(operation)
|
|
1469
|
+
});
|
|
1470
|
+
if (!planned.ok) {
|
|
1471
|
+
onProgress?.({
|
|
1472
|
+
action,
|
|
1473
|
+
kind: "spanEnd",
|
|
1474
|
+
spanId: SPAN_IDS$1.plan,
|
|
1475
|
+
outcome: "error"
|
|
1476
|
+
});
|
|
1477
|
+
return notOk(mapPlannerError(planned.failure));
|
|
1139
1478
|
}
|
|
1140
|
-
});
|
|
1141
|
-
if (!planResult.ok) {
|
|
1142
1479
|
onProgress?.({
|
|
1143
1480
|
action,
|
|
1144
1481
|
kind: "spanEnd",
|
|
1145
1482
|
spanId: SPAN_IDS$1.plan,
|
|
1146
|
-
outcome: "
|
|
1483
|
+
outcome: "ok"
|
|
1147
1484
|
});
|
|
1148
|
-
|
|
1485
|
+
const orderedResolutions = collectOrdered(planned.value.applyOrder, planned.value.perSpace);
|
|
1486
|
+
const subjects = action === "dbUpdate" ? subjectsAcrossSpaces(orderedResolutions) : {
|
|
1487
|
+
dataLoss: [],
|
|
1488
|
+
accessWidening: []
|
|
1489
|
+
};
|
|
1490
|
+
const operations = orderedResolutions.flatMap((r) => r.entry.displayOps);
|
|
1491
|
+
const labelled = (entries) => entries.map((entry) => ({
|
|
1492
|
+
...entry,
|
|
1493
|
+
label: operations[entry.operationIndex]?.label ?? JSON.stringify(entry.subject)
|
|
1494
|
+
}));
|
|
1495
|
+
return ok({
|
|
1496
|
+
planned: planned.value,
|
|
1497
|
+
orderedResolutions,
|
|
1498
|
+
subjects,
|
|
1499
|
+
dataLoss: labelled(subjects.dataLoss),
|
|
1500
|
+
accessWidening: labelled(subjects.accessWidening)
|
|
1501
|
+
});
|
|
1502
|
+
};
|
|
1503
|
+
const first = await plan(statements);
|
|
1504
|
+
if (!first.ok) return first.failure;
|
|
1505
|
+
let run = first.value;
|
|
1506
|
+
let renameTexts = statementTexts.filter((statement) => statement.verb === "rename");
|
|
1507
|
+
let consented = [];
|
|
1508
|
+
if (options.action === "dbUpdate" && mode === "apply") {
|
|
1509
|
+
const answered = await askPlanQuestions({
|
|
1510
|
+
plan: run,
|
|
1511
|
+
askAccess: true,
|
|
1512
|
+
renames: renameTexts,
|
|
1513
|
+
preAnswers: statementTexts.filter((statement) => statement.verb !== "rename"),
|
|
1514
|
+
consentAll: {
|
|
1515
|
+
delete: options.acceptDataLoss,
|
|
1516
|
+
allow: options.acceptAccessWidening
|
|
1517
|
+
},
|
|
1518
|
+
origin: fromContract ?? EMPTY_ORIGIN$1,
|
|
1519
|
+
originKnown: fromContract !== null,
|
|
1520
|
+
keepDataByHand: keepDataByHandFor(migrations, fromContract ?? EMPTY_ORIGIN$1),
|
|
1521
|
+
destination: contract,
|
|
1522
|
+
answer: options.answerQuestions,
|
|
1523
|
+
replan: (renames) => plan(resolveRenames(renames))
|
|
1524
|
+
});
|
|
1525
|
+
if (!answered.ok) {
|
|
1526
|
+
if (CliStructuredError$1.is(answered.failure)) throw answered.failure;
|
|
1527
|
+
return answered.failure;
|
|
1528
|
+
}
|
|
1529
|
+
run = answered.value.plan;
|
|
1530
|
+
renameTexts = [...answered.value.renames];
|
|
1531
|
+
consented = answered.value.consented;
|
|
1149
1532
|
}
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1533
|
+
if (options.action === "dbUpdate" && mode === "plan") {
|
|
1534
|
+
const refused = refuseUnusedConsents({
|
|
1535
|
+
plan: run,
|
|
1536
|
+
statements: statementTexts,
|
|
1537
|
+
contracts: {
|
|
1538
|
+
origin: fromContract ?? EMPTY_ORIGIN$1,
|
|
1539
|
+
destination: contract,
|
|
1540
|
+
renames: renameTexts
|
|
1541
|
+
}
|
|
1542
|
+
});
|
|
1543
|
+
if (!refused.ok) throw refused.failure;
|
|
1544
|
+
}
|
|
1545
|
+
const { planned, orderedResolutions } = run;
|
|
1157
1546
|
const plannerWarnings = aggregatePlannerWarnings(orderedResolutions);
|
|
1158
1547
|
const appResolution = orderedResolutions.find((r) => r.spaceId === aggregate.app.spaceId);
|
|
1159
1548
|
if (!appResolution) throw new InternalError("Aggregate planner returned no plan for the app space — the planner is supposed to always emit one.");
|
|
1160
1549
|
const appPlan = appResolution.entry.plan;
|
|
1161
|
-
const appliedStatements = action === "dbUpdate" ? reportAppliedStatements(appResolution.entry.appliedStatements, fromContract, contract, operationsBefore(orderedResolutions, aggregate.app.spaceId)) : void 0;
|
|
1550
|
+
const appliedStatements = action === "dbUpdate" ? [...reportAppliedStatements(appResolution.entry.appliedStatements, fromContract, contract, operationsBefore(orderedResolutions, aggregate.app.spaceId)), ...consented.map((entry) => reportConsentStatement(entry, entry.verb === "allow" && entry.operationIndex !== void 0 ? [entry.operationIndex] : run.subjects.dataLoss.filter(({ subject }) => migrationSubjectKey(subject) === migrationSubjectKey(entry.subject)).map(({ operationIndex }) => operationIndex)))] : void 0;
|
|
1551
|
+
const contractsAsked = {
|
|
1552
|
+
origin: fromContract ?? EMPTY_ORIGIN$1,
|
|
1553
|
+
destination: contract,
|
|
1554
|
+
renames: renameTexts
|
|
1555
|
+
};
|
|
1556
|
+
const asked = (entries) => entries.map((entry) => ({
|
|
1557
|
+
...entry,
|
|
1558
|
+
text: subjectText(entry.subject, contractsAsked)
|
|
1559
|
+
}));
|
|
1560
|
+
const subjects = action === "dbUpdate" ? {
|
|
1561
|
+
dataLoss: asked(run.subjects.dataLoss),
|
|
1562
|
+
accessWidening: asked(run.subjects.accessWidening)
|
|
1563
|
+
} : void 0;
|
|
1162
1564
|
if (mode === "plan") {
|
|
1163
1565
|
const aggregateOps = orderedResolutions.flatMap((r) => r.entry.displayOps);
|
|
1164
1566
|
const preview = hasOperationPreview(familyInstance) ? familyInstance.toOperationPreview(aggregateOps) : void 0;
|
|
@@ -1171,31 +1573,14 @@ async function executeRun(options) {
|
|
|
1171
1573
|
perSpace,
|
|
1172
1574
|
summary,
|
|
1173
1575
|
appliedStatements,
|
|
1174
|
-
|
|
1175
|
-
});
|
|
1176
|
-
}
|
|
1177
|
-
if (options.consentedPlanHash !== void 0) {
|
|
1178
|
-
const planHash = computePlanHash({
|
|
1179
|
-
operations: stripOperations(orderedResolutions.flatMap((r) => r.entry.displayOps)),
|
|
1180
|
-
destination: appPlan.destination
|
|
1181
|
-
});
|
|
1182
|
-
if (planHash !== options.consentedPlanHash) return notOk({
|
|
1183
|
-
code: "CONSENT_PLAN_MISMATCH",
|
|
1184
|
-
summary: "The plan changed between consent and apply",
|
|
1185
|
-
why: "The plan recomputed for the consented apply is not the plan that was consented to, so applying it could destroy something nobody agreed to.",
|
|
1186
|
-
conflicts: void 0,
|
|
1187
|
-
meta: void 0,
|
|
1188
|
-
consentPlanMismatch: {
|
|
1189
|
-
consentedPlanHash: options.consentedPlanHash,
|
|
1190
|
-
planHash
|
|
1191
|
-
},
|
|
1576
|
+
subjects,
|
|
1192
1577
|
...ifDefined("warnings", plannerWarnings)
|
|
1193
1578
|
});
|
|
1194
1579
|
}
|
|
1195
1580
|
const applied = await runMigration({
|
|
1196
1581
|
aggregate,
|
|
1197
|
-
perSpacePlans:
|
|
1198
|
-
applyOrder:
|
|
1582
|
+
perSpacePlans: planned.perSpace,
|
|
1583
|
+
applyOrder: planned.applyOrder,
|
|
1199
1584
|
driver,
|
|
1200
1585
|
familyInstance,
|
|
1201
1586
|
migrations,
|
|
@@ -1221,9 +1606,12 @@ async function executeRun(options) {
|
|
|
1221
1606
|
perSpace: applied.value.perSpace,
|
|
1222
1607
|
summary,
|
|
1223
1608
|
appliedStatements,
|
|
1609
|
+
subjects,
|
|
1224
1610
|
...ifDefined("warnings", plannerWarnings)
|
|
1225
1611
|
});
|
|
1226
1612
|
}
|
|
1613
|
+
/** The origin of a database whose marker names no readable contract: no models. */
|
|
1614
|
+
const EMPTY_ORIGIN$1 = { domain: { namespaces: {} } };
|
|
1227
1615
|
/**
|
|
1228
1616
|
* The contract the application space's marker names, from the local snapshot
|
|
1229
1617
|
* store, or where it was looked for and why it could not be used.
|
|
@@ -1291,6 +1679,20 @@ function operationsBefore(orderedResolutions, spaceId) {
|
|
|
1291
1679
|
const position = orderedResolutions.findIndex((resolution) => resolution.spaceId === spaceId);
|
|
1292
1680
|
return orderedResolutions.slice(0, position).reduce((count, resolution) => count + resolution.entry.displayOps.length, 0);
|
|
1293
1681
|
}
|
|
1682
|
+
/**
|
|
1683
|
+
* What the planned operations lose and whose access they widen, across every space, each at its
|
|
1684
|
+
* position in the operations the result reports.
|
|
1685
|
+
*/
|
|
1686
|
+
function subjectsAcrossSpaces(orderedResolutions) {
|
|
1687
|
+
const offset = (resolution, entries) => entries.map((entry) => ({
|
|
1688
|
+
...entry,
|
|
1689
|
+
operationIndex: entry.operationIndex + operationsBefore(orderedResolutions, resolution.spaceId)
|
|
1690
|
+
}));
|
|
1691
|
+
return {
|
|
1692
|
+
dataLoss: orderedResolutions.flatMap((resolution) => offset(resolution, resolution.entry.dataLoss)),
|
|
1693
|
+
accessWidening: orderedResolutions.flatMap((resolution) => offset(resolution, resolution.entry.accessWidening))
|
|
1694
|
+
};
|
|
1695
|
+
}
|
|
1294
1696
|
function aggregatePlannerWarnings(orderedResolutions) {
|
|
1295
1697
|
const warnings = orderedResolutions.flatMap((r) => r.entry.warnings ?? []);
|
|
1296
1698
|
return warnings.length > 0 ? warnings : void 0;
|
|
@@ -1360,6 +1762,7 @@ function wrapPlanResult(args) {
|
|
|
1360
1762
|
return ok({
|
|
1361
1763
|
mode: "plan",
|
|
1362
1764
|
...ifDefined("appliedStatements", args.appliedStatements),
|
|
1765
|
+
...args.subjects,
|
|
1363
1766
|
plan: {
|
|
1364
1767
|
operations: stripOperations(args.operations),
|
|
1365
1768
|
...ifDefined("preview", args.preview)
|
|
@@ -1377,6 +1780,7 @@ function wrapApplyResult(args) {
|
|
|
1377
1780
|
return ok({
|
|
1378
1781
|
mode: "apply",
|
|
1379
1782
|
...ifDefined("appliedStatements", args.appliedStatements),
|
|
1783
|
+
...args.subjects,
|
|
1380
1784
|
plan: { operations: stripOperations(args.operations) },
|
|
1381
1785
|
destination: {
|
|
1382
1786
|
storageHash: args.destination.storageHash,
|
|
@@ -1744,17 +2148,9 @@ const DB_UPDATE_POLICY = { allowedOperationClasses: [
|
|
|
1744
2148
|
"widening",
|
|
1745
2149
|
"destructive"
|
|
1746
2150
|
] };
|
|
1747
|
-
/**
|
|
1748
|
-
* Execute `db update` against the configured contract.
|
|
1749
|
-
*
|
|
1750
|
-
* Routes through the loader → planner → runner pipeline. Destructive
|
|
1751
|
-
* operations require either `acceptDataLoss: true` or a prior
|
|
1752
|
-
* `mode: 'plan'` invocation that surfaces the destructive ops; the
|
|
1753
|
-
* confirmation gate is implemented here so the lower-level applier
|
|
1754
|
-
* remains policy-agnostic.
|
|
1755
|
-
*/
|
|
2151
|
+
/** Execute `db update` against the configured contract. */
|
|
1756
2152
|
async function executeDbUpdate(options) {
|
|
1757
|
-
|
|
2153
|
+
return await executeRun({
|
|
1758
2154
|
driver: options.driver,
|
|
1759
2155
|
adapter: options.adapter,
|
|
1760
2156
|
familyInstance: options.familyInstance,
|
|
@@ -1766,54 +2162,13 @@ async function executeDbUpdate(options) {
|
|
|
1766
2162
|
extensions: options.extensions ?? [],
|
|
1767
2163
|
policy: DB_UPDATE_POLICY,
|
|
1768
2164
|
action: "dbUpdate",
|
|
2165
|
+
mode: options.mode,
|
|
1769
2166
|
statements: options.statements ?? [],
|
|
2167
|
+
answerQuestions: options.answerQuestions,
|
|
2168
|
+
acceptDataLoss: options.acceptDataLoss ?? false,
|
|
2169
|
+
acceptAccessWidening: options.acceptAccessWidening ?? false,
|
|
1770
2170
|
...ifDefined("verifySnapshotContent", options.verifySnapshotContent),
|
|
1771
2171
|
...ifDefined("onProgress", options.onProgress)
|
|
1772
|
-
};
|
|
1773
|
-
if (options.mode === "apply" && !options.acceptDataLoss && options.consent === void 0) {
|
|
1774
|
-
const refusal = await guardDestructiveChanges(sharedInputs);
|
|
1775
|
-
if (refusal !== null) return refusal;
|
|
1776
|
-
}
|
|
1777
|
-
return await executeRun({
|
|
1778
|
-
...sharedInputs,
|
|
1779
|
-
mode: options.mode,
|
|
1780
|
-
...ifDefined("consentedPlanHash", options.consent?.planHash)
|
|
1781
|
-
});
|
|
1782
|
-
}
|
|
1783
|
-
/**
|
|
1784
|
-
* Pre-plan once when running `db update apply` without `acceptDataLoss`.
|
|
1785
|
-
* Surfaces destructive operations across every space; if any are
|
|
1786
|
-
* planned, returns a `DESTRUCTIVE_CHANGES` failure that the CLI shows
|
|
1787
|
-
* as a confirmation prompt. Returns `null` when the apply is safe to
|
|
1788
|
-
* run.
|
|
1789
|
-
*/
|
|
1790
|
-
async function guardDestructiveChanges(sharedInputs) {
|
|
1791
|
-
const planResult = await executeRun({
|
|
1792
|
-
...sharedInputs,
|
|
1793
|
-
mode: "plan"
|
|
1794
|
-
});
|
|
1795
|
-
if (!planResult.ok) return planResult;
|
|
1796
|
-
const destructiveOps = planResult.value.plan.operations.filter((op) => op.operationClass === "destructive").map((op) => ({
|
|
1797
|
-
id: op.id,
|
|
1798
|
-
label: op.label
|
|
1799
|
-
}));
|
|
1800
|
-
if (destructiveOps.length === 0) return null;
|
|
1801
|
-
const databaseName = await sharedInputs.driver.databaseName?.();
|
|
1802
|
-
return notOk({
|
|
1803
|
-
code: "DESTRUCTIVE_CHANGES",
|
|
1804
|
-
summary: `Planned ${destructiveOps.length} destructive operation(s) that require confirmation`,
|
|
1805
|
-
why: "Destructive operations require explicit consent, which the caller has not given",
|
|
1806
|
-
conflicts: void 0,
|
|
1807
|
-
meta: void 0,
|
|
1808
|
-
destructiveChanges: {
|
|
1809
|
-
destructiveOperations: destructiveOps,
|
|
1810
|
-
databaseName,
|
|
1811
|
-
planHash: computePlanHash({
|
|
1812
|
-
operations: planResult.value.plan.operations,
|
|
1813
|
-
destination: planResult.value.destination
|
|
1814
|
-
})
|
|
1815
|
-
},
|
|
1816
|
-
...ifDefined("warnings", planResult.value.warnings)
|
|
1817
2172
|
});
|
|
1818
2173
|
}
|
|
1819
2174
|
function isRecord$2(value) {
|
|
@@ -2079,7 +2434,8 @@ async function executeMigrate(options) {
|
|
|
2079
2434
|
targetHash: spaceTargetHash,
|
|
2080
2435
|
refInvariants: isAppSpace && refHash !== void 0 ? refInvariants : void 0,
|
|
2081
2436
|
liveMarker: markerRows.get(space.spaceId) ?? null,
|
|
2082
|
-
...isAppSpace ? { refName } : {}
|
|
2437
|
+
...isAppSpace ? { refName } : {},
|
|
2438
|
+
storageNameOf: (operation) => familyInstance.storageNameOf(operation)
|
|
2083
2439
|
});
|
|
2084
2440
|
if (outcome.kind === "at-head") {
|
|
2085
2441
|
plansKeptFromRunner.set(space.spaceId, outcome.plan);
|
|
@@ -2191,7 +2547,7 @@ async function executeMigrate(options) {
|
|
|
2191
2547
|
*
|
|
2192
2548
|
* @internal Exported for `executeMigrateShowCommand`.
|
|
2193
2549
|
*/
|
|
2194
|
-
function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker, refName }) {
|
|
2550
|
+
function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker, refName, storageNameOf }) {
|
|
2195
2551
|
const isAppSpace = space.spaceId === aggregate.app.spaceId;
|
|
2196
2552
|
const headRef = requireHeadRef(space);
|
|
2197
2553
|
if (space.graph().nodes.size === 0) {
|
|
@@ -2244,7 +2600,8 @@ function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker
|
|
|
2244
2600
|
aggregateTargetId: aggregate.targetId,
|
|
2245
2601
|
space: targetSpace,
|
|
2246
2602
|
currentMarker: liveMarker,
|
|
2247
|
-
...isAppSpace && refName !== void 0 ? { refName } : {}
|
|
2603
|
+
...isAppSpace && refName !== void 0 ? { refName } : {},
|
|
2604
|
+
storageNameOf
|
|
2248
2605
|
});
|
|
2249
2606
|
if (walked.kind === "unreachable") return {
|
|
2250
2607
|
kind: "unreachable",
|
|
@@ -2294,6 +2651,8 @@ function buildAtHeadResolution(args) {
|
|
|
2294
2651
|
destinationContract: space.contract(),
|
|
2295
2652
|
strategy: "declared-state",
|
|
2296
2653
|
appliedStatements: [],
|
|
2654
|
+
dataLoss: [],
|
|
2655
|
+
accessWidening: [],
|
|
2297
2656
|
migrationEdges: [buildFabricatedMigrationEdge({
|
|
2298
2657
|
currentMarkerStorageHash: liveMarker?.storageHash,
|
|
2299
2658
|
destinationStorageHash: targetHash,
|
|
@@ -2646,8 +3005,9 @@ var ControlClientImpl = class {
|
|
|
2646
3005
|
targetId: this.options.target.targetId,
|
|
2647
3006
|
extensions: this.options.extensions ?? [],
|
|
2648
3007
|
...ifDefined("acceptDataLoss", options.acceptDataLoss),
|
|
2649
|
-
...ifDefined("
|
|
3008
|
+
...ifDefined("acceptAccessWidening", options.acceptAccessWidening),
|
|
2650
3009
|
...ifDefined("statements", options.statements),
|
|
3010
|
+
answerQuestions: options.answerQuestions,
|
|
2651
3011
|
...ifDefined("verifySnapshotContent", this.snapshotVerifier),
|
|
2652
3012
|
...ifDefined("onProgress", onProgress)
|
|
2653
3013
|
});
|
|
@@ -3399,6 +3759,20 @@ async function advanceRefSafely(args) {
|
|
|
3399
3759
|
throw error;
|
|
3400
3760
|
}
|
|
3401
3761
|
}
|
|
3762
|
+
const SHELL_SAFE = /^[A-Za-z0-9_.:/@%+,-]+$/;
|
|
3763
|
+
/** The value as a shell passes it through unchanged, single-quoted when needed. */
|
|
3764
|
+
function shellQuoted(value) {
|
|
3765
|
+
return SHELL_SAFE.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
|
|
3766
|
+
}
|
|
3767
|
+
/**
|
|
3768
|
+
* A statement written as a flag a shell passes through unchanged: the value is single-quoted when
|
|
3769
|
+
* it has a character a shell would read, and joined with `=` when it starts with `-`, which a
|
|
3770
|
+
* parser would otherwise read as a flag.
|
|
3771
|
+
*/
|
|
3772
|
+
function statementFlag(statement) {
|
|
3773
|
+
const value = shellQuoted(statement.text);
|
|
3774
|
+
return statement.text.startsWith("-") ? `--${statement.verb}=${value}` : `--${statement.verb} ${value}`;
|
|
3775
|
+
}
|
|
3402
3776
|
const RECORDED_FORMS = [
|
|
3403
3777
|
"hash",
|
|
3404
3778
|
"prefix",
|
|
@@ -3521,7 +3895,7 @@ function retryCommandFor(args) {
|
|
|
3521
3895
|
...suggestsOffline ? ["--from <contract>"] : [],
|
|
3522
3896
|
...args.to === void 0 ? [] : [`--to ${args.to}`],
|
|
3523
3897
|
...args.advanceRef === void 0 ? [] : [`--advance-ref ${args.advanceRef}`],
|
|
3524
|
-
...(args.
|
|
3898
|
+
...(args.statements ?? []).map(statementFlag),
|
|
3525
3899
|
...needsConnection ? ["--db $DATABASE_URL"] : []
|
|
3526
3900
|
].join(" ");
|
|
3527
3901
|
}
|
|
@@ -3657,7 +4031,7 @@ async function executeMigrateShowPlan(options) {
|
|
|
3657
4031
|
}
|
|
3658
4032
|
const loaded = await buildReadAggregate(config, { migrationsDir });
|
|
3659
4033
|
if (!loaded.ok) return notOk(loaded.failure);
|
|
3660
|
-
const { aggregate, contractHash } = loaded.value;
|
|
4034
|
+
const { aggregate, contractHash, storageNameOf } = loaded.value;
|
|
3661
4035
|
const appGraph = aggregate.app.graph();
|
|
3662
4036
|
let targetHash = contractHash;
|
|
3663
4037
|
let refInvariants;
|
|
@@ -3734,7 +4108,8 @@ async function executeMigrateShowPlan(options) {
|
|
|
3734
4108
|
aggregate,
|
|
3735
4109
|
targetHash: isAppSpace ? targetHash : headRef.hash,
|
|
3736
4110
|
refInvariants: isAppSpace ? refInvariants : void 0,
|
|
3737
|
-
liveMarker: markerBySpace.get(space.spaceId) ?? null
|
|
4111
|
+
liveMarker: markerBySpace.get(space.spaceId) ?? null,
|
|
4112
|
+
storageNameOf
|
|
3738
4113
|
});
|
|
3739
4114
|
if (outcome.kind === "at-head") continue;
|
|
3740
4115
|
if (outcome.kind === "never-planned") return notOk(errorPathUnreachable({
|
|
@@ -4741,11 +5116,11 @@ async function runPlannerLeg(planner, migrations, frameworkComponents, contract,
|
|
|
4741
5116
|
reason: "refused",
|
|
4742
5117
|
error: errorMigrationPlanningFailed({ conflicts: castAs(plannerResult.conflicts) })
|
|
4743
5118
|
});
|
|
4744
|
-
let
|
|
5119
|
+
let resolved = [];
|
|
4745
5120
|
let hasPlaceholders = false;
|
|
4746
5121
|
try {
|
|
4747
|
-
|
|
4748
|
-
if (
|
|
5122
|
+
resolved = await Promise.all(plannerResult.plan.operations);
|
|
5123
|
+
if (resolved.length === 0 && !noOperationsExpected) return notOk({
|
|
4749
5124
|
reason: "noOperations",
|
|
4750
5125
|
error: errorPlanProducedNoOperations(origin, destination)
|
|
4751
5126
|
});
|
|
@@ -4753,20 +5128,49 @@ async function runPlannerLeg(planner, migrations, frameworkComponents, contract,
|
|
|
4753
5128
|
if (CliStructuredError$1.is(e) && e.code === "MIGRATION.UNFILLED_PLACEHOLDER") {
|
|
4754
5129
|
hasPlaceholders = true;
|
|
4755
5130
|
try {
|
|
4756
|
-
|
|
5131
|
+
resolved = (await Promise.allSettled(plannerResult.plan.operations)).map((entry) => entry.status === "fulfilled" ? entry.value : void 0);
|
|
4757
5132
|
} catch {
|
|
4758
|
-
|
|
5133
|
+
resolved = [];
|
|
4759
5134
|
}
|
|
4760
5135
|
} else throw e;
|
|
4761
5136
|
}
|
|
5137
|
+
const plannedOps = resolved.filter((op) => op !== void 0);
|
|
5138
|
+
const position = resolvedPositions(resolved);
|
|
4762
5139
|
return ok({
|
|
4763
5140
|
plannedOps,
|
|
4764
5141
|
migrationTsContent: plannerResult.plan.renderTypeScript(resolveImportSpecifier),
|
|
4765
5142
|
hasPlaceholders,
|
|
4766
|
-
|
|
5143
|
+
dataLoss: plannerResult.dataLoss.map(({ operationIndex, subject }) => ({
|
|
5144
|
+
operationIndex: position(operationIndex),
|
|
5145
|
+
subject,
|
|
5146
|
+
label: resolved[operationIndex]?.label ?? subjectText(subject, {
|
|
5147
|
+
origin: fromContract ?? EMPTY_ORIGIN,
|
|
5148
|
+
renames: []
|
|
5149
|
+
})
|
|
5150
|
+
})),
|
|
5151
|
+
appliedStatements: reportAppliedStatements(plannerResult.appliedStatements.map((applied) => ({
|
|
5152
|
+
...applied,
|
|
5153
|
+
operationIndexes: applied.operationIndexes.flatMap((index) => {
|
|
5154
|
+
const at = position(index);
|
|
5155
|
+
return at === void 0 ? [] : [at];
|
|
5156
|
+
})
|
|
5157
|
+
})), fromContract, contract, 0)
|
|
4767
5158
|
});
|
|
4768
5159
|
}
|
|
4769
5160
|
/**
|
|
5161
|
+
* Maps a position in the plan's operations to the position of that operation among those that
|
|
5162
|
+
* resolved, which is what a result's `operations` lists: `undefined` for an unfilled placeholder.
|
|
5163
|
+
*/
|
|
5164
|
+
function resolvedPositions(resolved) {
|
|
5165
|
+
const positions = [];
|
|
5166
|
+
let next = 0;
|
|
5167
|
+
for (const op of resolved) {
|
|
5168
|
+
positions.push(op === void 0 ? void 0 : next);
|
|
5169
|
+
if (op !== void 0) next += 1;
|
|
5170
|
+
}
|
|
5171
|
+
return (planIndex) => positions[planIndex];
|
|
5172
|
+
}
|
|
5173
|
+
/**
|
|
4770
5174
|
* The operations a result lists. For a leg with unfilled placeholders these are the operations
|
|
4771
5175
|
* that resolved; the placeholders themselves are not operations yet.
|
|
4772
5176
|
*/
|
|
@@ -4792,46 +5196,42 @@ async function writePlannedMigrationPackage(packageDir, fromHash, toHash, create
|
|
|
4792
5196
|
await writeMigrationTs(packageDir, leg.migrationTsContent);
|
|
4793
5197
|
}
|
|
4794
5198
|
/**
|
|
4795
|
-
*
|
|
4796
|
-
*
|
|
4797
|
-
* is
|
|
4798
|
-
*
|
|
4799
|
-
* leaves the app-space migrations directory untouched (the extension seed
|
|
4800
|
-
* phase runs earlier and unconditionally, as it does for no-op runs).
|
|
4801
|
-
* A leg with unfilled placeholders is still checked over the operations
|
|
4802
|
-
* that did resolve. Returns `null` when the write may proceed.
|
|
5199
|
+
* Asks about every operation of the planned legs that would lose data, until each is answered,
|
|
5200
|
+
* before anything is written. A delete answer consents to the loss of its subject. A rename typed
|
|
5201
|
+
* at the prompt is a statement the plan did not have, so the delta is planned again with it, and
|
|
5202
|
+
* the loss it answered must be gone.
|
|
4803
5203
|
*/
|
|
4804
|
-
function
|
|
4805
|
-
const
|
|
4806
|
-
|
|
4807
|
-
|
|
4808
|
-
|
|
4809
|
-
operations: ops.map((op) => ({
|
|
4810
|
-
id: op.id,
|
|
4811
|
-
label: op.label,
|
|
4812
|
-
operationClass: op.operationClass
|
|
4813
|
-
})),
|
|
4814
|
-
destination: { storageHash: baselineToHash }
|
|
5204
|
+
async function answerPlannedDataLoss(input) {
|
|
5205
|
+
const legs = (delta) => ({
|
|
5206
|
+
delta,
|
|
5207
|
+
dataLoss: [...input.baseline?.dataLoss ?? [], ...delta?.dataLoss ?? []],
|
|
5208
|
+
accessWidening: []
|
|
4815
5209
|
});
|
|
4816
|
-
|
|
4817
|
-
|
|
4818
|
-
|
|
4819
|
-
|
|
4820
|
-
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
|
|
4827
|
-
|
|
4828
|
-
|
|
4829
|
-
|
|
4830
|
-
|
|
4831
|
-
|
|
4832
|
-
|
|
5210
|
+
const answered = await askPlanQuestions({
|
|
5211
|
+
plan: legs(input.delta),
|
|
5212
|
+
askAccess: false,
|
|
5213
|
+
renames: input.renames,
|
|
5214
|
+
preAnswers: input.consents,
|
|
5215
|
+
consentAll: {
|
|
5216
|
+
delete: false,
|
|
5217
|
+
allow: false
|
|
5218
|
+
},
|
|
5219
|
+
origin: input.origin,
|
|
5220
|
+
originKnown: input.originKnown,
|
|
5221
|
+
keepDataByHand: input.keepDataByHand,
|
|
5222
|
+
destination: input.destination,
|
|
5223
|
+
answer: input.answer,
|
|
5224
|
+
replan: async (renames) => {
|
|
5225
|
+
const replanned = await input.planDelta(renames);
|
|
5226
|
+
return replanned.ok ? ok(legs(replanned.value)) : replanned;
|
|
5227
|
+
}
|
|
5228
|
+
});
|
|
5229
|
+
if (!answered.ok) return answered;
|
|
5230
|
+
const { delta } = answered.value.plan;
|
|
5231
|
+
return ok({
|
|
5232
|
+
delta,
|
|
5233
|
+
deletes: answered.value.consented.map((consented) => reportConsentStatement(consented, (delta?.dataLoss ?? []).filter((loss) => migrationSubjectKey(loss.subject) === migrationSubjectKey(consented.subject)).flatMap(({ operationIndex }) => operationIndex === void 0 ? [] : [operationIndex])))
|
|
4833
5234
|
});
|
|
4834
|
-
return null;
|
|
4835
5235
|
}
|
|
4836
5236
|
async function executeMigrationPlanCommand(options, startTime, callbacks) {
|
|
4837
5237
|
try {
|
|
@@ -4967,12 +5367,10 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
4967
5367
|
extensions: toExtensionInputs(config.extensions ?? [])
|
|
4968
5368
|
});
|
|
4969
5369
|
for (const record of seedResult.seeded) callbacks?.onSeeded?.(record);
|
|
4970
|
-
const
|
|
5370
|
+
const emittedExtensionDirs = seedResult.seeded.flatMap((r) => r.newMigrationDirs.map((dirName) => ({
|
|
4971
5371
|
spaceId: r.spaceId,
|
|
4972
5372
|
dirName
|
|
4973
5373
|
})));
|
|
4974
|
-
const carried = options.carryEmittedExtensionDirs ?? [];
|
|
4975
|
-
const emittedExtensionDirs = [...carried, ...seededThisRun.filter((entry) => !carried.some((prior) => prior.spaceId === entry.spaceId && prior.dirName === entry.dirName))];
|
|
4976
5374
|
if (fromHash === toStorageHash && !isAutoBaseline && statements.length === 0) return ok({
|
|
4977
5375
|
ok: true,
|
|
4978
5376
|
noOp: true,
|
|
@@ -5015,6 +5413,30 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
5015
5413
|
hash: toStorageHash,
|
|
5016
5414
|
isEmitted: options.to === void 0
|
|
5017
5415
|
};
|
|
5416
|
+
const answerDataLoss = (baseline, delta, planDelta) => answerPlannedDataLoss({
|
|
5417
|
+
baseline,
|
|
5418
|
+
delta,
|
|
5419
|
+
renames: statementTexts.filter((statement) => statement.verb === "rename"),
|
|
5420
|
+
consents: statementTexts.filter((statement) => statement.verb !== "rename"),
|
|
5421
|
+
origin: fromContract ?? EMPTY_ORIGIN,
|
|
5422
|
+
originKnown: true,
|
|
5423
|
+
keepDataByHand: keepDataByHandFor(migrations, fromContract ?? EMPTY_ORIGIN),
|
|
5424
|
+
destination: toContract,
|
|
5425
|
+
answer: options.answerQuestions,
|
|
5426
|
+
planDelta: async (renames) => {
|
|
5427
|
+
const resolved = resolveStatements({
|
|
5428
|
+
statements: renames,
|
|
5429
|
+
origin: {
|
|
5430
|
+
kind: "contract",
|
|
5431
|
+
contract: fromContract ?? EMPTY_ORIGIN
|
|
5432
|
+
},
|
|
5433
|
+
destination: toContract
|
|
5434
|
+
});
|
|
5435
|
+
if (!resolved.ok) return resolved;
|
|
5436
|
+
const leg = await planDelta(resolved.value);
|
|
5437
|
+
return leg.ok ? leg : notOk(leg.failure.error);
|
|
5438
|
+
}
|
|
5439
|
+
});
|
|
5018
5440
|
if (isAutoBaseline && fromHash !== null && fromContract !== null && fromContractInStore) {
|
|
5019
5441
|
const deltaTimestamp = /* @__PURE__ */ new Date();
|
|
5020
5442
|
const baselineTimestamp = /* @__PURE__ */ new Date(deltaTimestamp.getTime() - 6e4);
|
|
@@ -5030,10 +5452,13 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
5030
5452
|
isEmitted: false
|
|
5031
5453
|
}, [], false, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(baselinePackageDir, migrationsDir), resolveImportSpecifier);
|
|
5032
5454
|
if (!baselineLeg.ok) return notOk(baselineLeg.failure.error);
|
|
5033
|
-
const
|
|
5034
|
-
|
|
5035
|
-
|
|
5036
|
-
|
|
5455
|
+
const planBaselineDelta = (resolved) => runPlannerLeg(planner, migrations, frameworkComponents, aggregate.app.contract(), fromOrigin, planDestination, resolved, false, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(deltaPackageDir, migrationsDir), resolveImportSpecifier);
|
|
5456
|
+
const plannedDelta = fromHash === toStorageHash ? void 0 : await planBaselineDelta(statements);
|
|
5457
|
+
if (plannedDelta !== void 0 && !plannedDelta.ok && plannedDelta.failure.reason === "refused") return notOk(plannedDelta.failure.error);
|
|
5458
|
+
const answered = await answerDataLoss(baselineLeg.value, plannedDelta?.ok === true ? plannedDelta.value : void 0, planBaselineDelta);
|
|
5459
|
+
if (!answered.ok) return notOk(answered.failure);
|
|
5460
|
+
const deltaLeg = plannedDelta === void 0 || !plannedDelta.ok || answered.value.delta === void 0 ? plannedDelta : ok(answered.value.delta);
|
|
5461
|
+
const deletes = answered.value.deletes;
|
|
5037
5462
|
await writePlannedMigrationPackage(baselinePackageDir, null, fromHash, baselineTimestamp, baselineLeg.value);
|
|
5038
5463
|
if (deltaLeg !== void 0 && !deltaLeg.ok) return notOk(deltaLeg.failure.error);
|
|
5039
5464
|
if (deltaLeg === void 0) {
|
|
@@ -5055,7 +5480,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
5055
5480
|
emittedExtensionDirs,
|
|
5056
5481
|
...warnings.length > 0 ? { warnings } : {},
|
|
5057
5482
|
pendingPlaceholders: true,
|
|
5058
|
-
appliedStatements: statementsWithoutOperations,
|
|
5483
|
+
appliedStatements: [...statementsWithoutOperations, ...deletes],
|
|
5059
5484
|
summary: "Planned baseline with placeholder(s) — edit migration.ts then run `node migration.ts` to self-emit",
|
|
5060
5485
|
timings: { total: Date.now() - startTime }
|
|
5061
5486
|
});
|
|
@@ -5075,7 +5500,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
5075
5500
|
emittedExtensionDirs,
|
|
5076
5501
|
...preview !== void 0 ? { preview } : {},
|
|
5077
5502
|
...warnings.length > 0 ? { warnings } : {},
|
|
5078
|
-
appliedStatements: statementsWithoutOperations,
|
|
5503
|
+
appliedStatements: [...statementsWithoutOperations, ...deletes],
|
|
5079
5504
|
summary: buildAutoBaselinePlanSummary(baselineOps.length, 0, emittedExtensionDirs.length),
|
|
5080
5505
|
timings: { total: Date.now() - startTime }
|
|
5081
5506
|
});
|
|
@@ -5096,7 +5521,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
5096
5521
|
emittedExtensionDirs,
|
|
5097
5522
|
...warnings.length > 0 ? { warnings } : {},
|
|
5098
5523
|
pendingPlaceholders: true,
|
|
5099
|
-
appliedStatements: deltaLeg.value.appliedStatements,
|
|
5524
|
+
appliedStatements: [...deltaLeg.value.appliedStatements, ...deletes],
|
|
5100
5525
|
summary: "Planned baseline + migration with placeholder(s) — edit migration.ts then run `node migration.ts` to self-emit",
|
|
5101
5526
|
timings: { total: Date.now() - startTime }
|
|
5102
5527
|
});
|
|
@@ -5121,15 +5546,20 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
5121
5546
|
emittedExtensionDirs,
|
|
5122
5547
|
...preview !== void 0 ? { preview } : {},
|
|
5123
5548
|
...warnings.length > 0 ? { warnings } : {},
|
|
5124
|
-
appliedStatements: deltaLeg.value.appliedStatements,
|
|
5549
|
+
appliedStatements: [...deltaLeg.value.appliedStatements, ...deletes],
|
|
5125
5550
|
summary: buildAutoBaselinePlanSummary(baselineOps.length, deltaOps.length, emittedExtensionDirs.length),
|
|
5126
5551
|
timings: { total: Date.now() - startTime }
|
|
5127
5552
|
});
|
|
5128
5553
|
}
|
|
5129
5554
|
const timestamp = /* @__PURE__ */ new Date();
|
|
5130
5555
|
const packageDir = join(appMigrationsDir, formatMigrationDirName(timestamp, options.name ?? "migration"));
|
|
5131
|
-
const
|
|
5132
|
-
|
|
5556
|
+
const planDelta = (resolved) => runPlannerLeg(planner, migrations, frameworkComponents, aggregate.app.contract(), fromOrigin, planDestination, resolved, resolved.length > 0 && fromHash === toStorageHash, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(packageDir, migrationsDir), resolveImportSpecifier);
|
|
5557
|
+
const plannedDelta = await planDelta(statements);
|
|
5558
|
+
if (!plannedDelta.ok) return notOk(plannedDelta.failure.error);
|
|
5559
|
+
const answered = await answerDataLoss(void 0, plannedDelta.value, planDelta);
|
|
5560
|
+
if (!answered.ok) return notOk(answered.failure);
|
|
5561
|
+
const deltaLeg = ok(answered.value.delta ?? plannedDelta.value);
|
|
5562
|
+
const deletes = answered.value.deletes;
|
|
5133
5563
|
if (!deltaLeg.value.hasPlaceholders && deltaLeg.value.plannedOps.length === 0) return ok({
|
|
5134
5564
|
ok: true,
|
|
5135
5565
|
noOp: true,
|
|
@@ -5138,7 +5568,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
5138
5568
|
operations: [],
|
|
5139
5569
|
emittedExtensionDirs,
|
|
5140
5570
|
...warnings.length > 0 ? { warnings } : {},
|
|
5141
|
-
appliedStatements: deltaLeg.value.appliedStatements,
|
|
5571
|
+
appliedStatements: [...deltaLeg.value.appliedStatements, ...deletes],
|
|
5142
5572
|
summary: "No changes to plan: the statements need no operations",
|
|
5143
5573
|
timings: { total: Date.now() - startTime }
|
|
5144
5574
|
});
|
|
@@ -5155,7 +5585,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
5155
5585
|
...warnings.length > 0 ? { warnings } : {},
|
|
5156
5586
|
pendingPlaceholders: true,
|
|
5157
5587
|
...fromDefaulted ? { fromDefaulted } : {},
|
|
5158
|
-
appliedStatements: deltaLeg.value.appliedStatements,
|
|
5588
|
+
appliedStatements: [...deltaLeg.value.appliedStatements, ...deletes],
|
|
5159
5589
|
summary: "Planned migration with placeholder(s) — edit migration.ts then run `node migration.ts` to self-emit",
|
|
5160
5590
|
timings: { total: Date.now() - startTime }
|
|
5161
5591
|
});
|
|
@@ -5176,7 +5606,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
5176
5606
|
...preview !== void 0 ? { preview } : {},
|
|
5177
5607
|
...fromDefaulted ? { fromDefaulted } : {},
|
|
5178
5608
|
...warnings.length > 0 ? { warnings } : {},
|
|
5179
|
-
appliedStatements: deltaLeg.value.appliedStatements,
|
|
5609
|
+
appliedStatements: [...deltaLeg.value.appliedStatements, ...deletes],
|
|
5180
5610
|
summary: buildPlanSummary(plannedOps.length, emittedExtensionDirs.length),
|
|
5181
5611
|
timings: { total: Date.now() - startTime }
|
|
5182
5612
|
});
|
|
@@ -5319,6 +5749,6 @@ async function executeRefListCommand(options) {
|
|
|
5319
5749
|
}
|
|
5320
5750
|
}
|
|
5321
5751
|
//#endregion
|
|
5322
|
-
export { refuseUnknownInvariants as $, executeRefListCommand as A, loadContractSourceWithStack as B, executeDbUpdate as C, executeMigrationPlanCommand as D, executeMigrationNewCommand as E, listRefsByContractHash as F, migrationSpaceListEntriesFromAggregate as G, looksLikePath as H, liveMarkerUse as I, refuseContractSpaceIntegrity as J, preflightRefAdvancement as K, loadAggregateIntegrityViolations as L, findPackageByDirPath as M, formatSourceDiagnostic as N, executeRefAdvancement as O, hasMigrationPath as P, refusePackageCorruptionOnAggregate as Q, loadContractRawSafely as R, executeDbSign as S, executeMigrateShowPlan as T, mapContractAtError as U, loadContractSpaceAggregateForCli as V, mapIntegrityViolations as W, refuseMarkerOutsideGraph as X, refuseDeclaredExtensionTargetMismatch as Y, refuseMissingInvariantPath as Z, disposeEmitQueue as _, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as a, resolveMigrationRef as at, executeContractEmit as b, appliedHashesFromLedger as c, retryCommandFor as ct, buildReadAggregate as d, runMigrationList as dt, requireDatabaseForLiveMarkerUse as et, buildRefAdvancementFields as f,
|
|
5752
|
+
export { refuseUnknownInvariants as $, executeRefListCommand as A, loadContractSourceWithStack as B, executeDbUpdate as C, executeMigrationPlanCommand as D, executeMigrationNewCommand as E, listRefsByContractHash as F, migrationSpaceListEntriesFromAggregate as G, looksLikePath as H, liveMarkerUse as I, refuseContractSpaceIntegrity as J, preflightRefAdvancement as K, loadAggregateIntegrityViolations as L, findPackageByDirPath as M, formatSourceDiagnostic as N, executeRefAdvancement as O, hasMigrationPath as P, refusePackageCorruptionOnAggregate as Q, loadContractRawSafely as R, executeDbSign as S, executeMigrateShowPlan as T, mapContractAtError as U, loadContractSpaceAggregateForCli as V, mapIntegrityViolations as W, refuseMarkerOutsideGraph as X, refuseDeclaredExtensionTargetMismatch as Y, refuseMissingInvariantPath as Z, disposeEmitQueue as _, toDeclaredExtensionsFromRaw as _t, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as a, resolveMigrationRef as at, executeContractEmit as b, appliedHashesFromLedger as c, retryCommandFor as ct, buildReadAggregate as d, runMigrationList as dt, requireDatabaseForLiveMarkerUse as et, buildRefAdvancementFields as f, shellQuoted as ft, deriveStatusEdgeAnnotations as g, statusForMigrationHash as gt, createControlClient as h, statementFlag as ht, RECORDED_CONTRACT_REF_FORMS as i, resolveFromForPlan as it, executeRefSetCommand as j, executeRefDeleteCommand as k, buildContractSpaceAggregate as l, runContractSpaceSeedPhase as lt, computeRefAdvancementName as m, sourceWarningDiagnostic as mt, DB_UPDATE_POLICY as n, resolveContractRef$1 as nt, advanceRefSafely as o, resolveStatements as ot, checkSingleTarget as p, snapshotVerifierFor as pt, readMigrationRefs as q, NO_REF_ADVANCEMENT as r, resolveContractRefToSnapshot as rt, appContractStandInFromIdentity as s, resolveToForPlan as st, ALL_CONTRACT_REF_FORMS as t, resolveAppTargetPath as tt, buildMigrationSpaceGraphEntries as u, runMigrationCheck as ut, enrichContract as v, validateLoadedContract as vt, executeDbVerify as w, executeDbInit as x, enumerateCheckSpaces as y, loadContractSource as z };
|
|
5323
5753
|
|
|
5324
|
-
//# sourceMappingURL=ref-
|
|
5754
|
+
//# sourceMappingURL=ref-Cc_CTagE-C070Ym7p.mjs.map
|