@prisma/orm-toolchain 8.0.0-rc.24-dev.28 → 8.0.0-rc.24-dev.29
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/README.md +1 -3
- package/dist/{aggregate-CRIdmKmq.mjs → aggregate-7sB4u_aJ.mjs} +11 -5
- package/dist/aggregate-7sB4u_aJ.mjs.map +1 -0
- package/dist/{aggregate-C6PGBKyb.d.mts → aggregate-DgWdbWNs.d.mts} +12 -6
- package/dist/{aggregate-C6PGBKyb.d.mts.map → aggregate-DgWdbWNs.d.mts.map} +1 -1
- package/dist/{caught-errors-I1l50iPc-D_-F2M3t.mjs → caught-errors-D_pbHqmS-B-4jRN6g.mjs} +52 -11
- package/dist/caught-errors-D_pbHqmS-B-4jRN6g.mjs.map +1 -0
- package/dist/cli-telemetry.mjs +1 -1
- package/dist/cli.d.mts +2 -2
- package/dist/cli.mjs +1094 -1012
- package/dist/cli.mjs.map +1 -1
- package/dist/cli__control-api.d.mts +16 -14
- 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__init-contribution.d.mts +101 -0
- package/dist/cli__init-contribution.d.mts.map +1 -0
- package/dist/cli__init-contribution.mjs +1 -0
- package/dist/cli__init-output.d.mts +3 -3
- package/dist/cli__init-output.mjs +1 -1
- package/dist/cli__migration-cli.mjs +3 -3
- package/dist/cli__migration-cli.mjs.map +1 -1
- package/dist/config-loader.d.mts +1 -1
- package/dist/config-loader.mjs +1 -1
- package/dist/{db-sign-Bv-FZMAD-uQhMNCC7.d.mts → db-sign-DLIR5swa-DQ0aN1nU.d.mts} +25 -21
- package/dist/db-sign-DLIR5swa-DQ0aN1nU.d.mts.map +1 -0
- package/dist/{domain-type-generation-BlYB8GiS-k0HNTf4f.mjs → domain-type-generation-BGcbGgHJ-Cdw5RNaZ.mjs} +11 -12
- package/dist/domain-type-generation-BGcbGgHJ-Cdw5RNaZ.mjs.map +1 -0
- package/dist/{domain-type-generation-D5cG6TGd-DKLpO6ZA.d.mts → domain-type-generation-BP8J5hy8-CxSjSRCh.d.mts} +6 -5
- package/dist/domain-type-generation-BP8J5hy8-CxSjSRCh.d.mts.map +1 -0
- package/dist/emitter.d.mts +3 -3
- package/dist/emitter.mjs +3 -3
- package/dist/emitter__domain-type-generation.d.mts +2 -2
- package/dist/emitter__domain-type-generation.mjs +2 -2
- package/dist/{exports-RTLU0w9r.mjs → exports-BiXPktAF.mjs} +4 -4
- package/dist/{exports-RTLU0w9r.mjs.map → exports-BiXPktAF.mjs.map} +1 -1
- package/dist/{exports-CVgs3YWV-BF4rqnxF.mjs → exports-CCuYD8dO-yw1GizAT.mjs} +28 -18
- package/dist/exports-CCuYD8dO-yw1GizAT.mjs.map +1 -0
- package/dist/{exports-CSVHjfwG.mjs → exports-CZ6dPu-O.mjs} +35 -10
- package/dist/exports-CZ6dPu-O.mjs.map +1 -0
- package/dist/{index-BHYAWGxJ.d.mts → index-C09OeJjf.d.mts} +7 -12
- package/dist/index-C09OeJjf.d.mts.map +1 -0
- package/dist/{index-BhNbc269.d.mts → index-C3KtOcBP.d.mts} +3 -1
- package/dist/index-C3KtOcBP.d.mts.map +1 -0
- package/dist/migration-tools.d.mts +1 -1
- package/dist/migration-tools.mjs +3 -3
- package/dist/migration-tools__aggregate.d.mts +1 -1
- package/dist/migration-tools__aggregate.mjs +1 -1
- package/dist/migration-tools__ref-resolution.mjs +1 -1
- package/dist/migration-tools__refs.mjs +1 -1
- package/dist/{output-BcC8eB0h-C5bRd-aC.mjs → output-E6F4-EMc-CqlzGlv-.mjs} +50 -9
- package/dist/output-E6F4-EMc-CqlzGlv-.mjs.map +1 -0
- package/dist/{ref-DfuqRCA7-CPPoVHY9.mjs → ref-PQOM_LTC-lyfzb0MO.mjs} +535 -270
- package/dist/ref-PQOM_LTC-lyfzb0MO.mjs.map +1 -0
- package/dist/{ref-resolution-C9j2SSb6.mjs → ref-resolution-C0xsiRig.mjs} +2 -2
- package/dist/{ref-resolution-C9j2SSb6.mjs.map → ref-resolution-C0xsiRig.mjs.map} +1 -1
- package/dist/{refs-t_JbIjGo-CRpBRRkq.mjs → refs-t_JbIjGo-BVCqKpXd.mjs} +2 -2
- package/dist/{refs-t_JbIjGo-CRpBRRkq.mjs.map → refs-t_JbIjGo-BVCqKpXd.mjs.map} +1 -1
- package/dist/vite-plugin-contract-emit.mjs +4 -5
- package/dist/vite-plugin-contract-emit.mjs.map +1 -1
- package/package.json +12 -15
- package/dist/aggregate-CRIdmKmq.mjs.map +0 -1
- package/dist/caught-errors-I1l50iPc-D_-F2M3t.mjs.map +0 -1
- package/dist/db-sign-Bv-FZMAD-uQhMNCC7.d.mts.map +0 -1
- package/dist/domain-type-generation-BlYB8GiS-k0HNTf4f.mjs.map +0 -1
- package/dist/domain-type-generation-D5cG6TGd-DKLpO6ZA.d.mts.map +0 -1
- package/dist/exports-CSVHjfwG.mjs.map +0 -1
- package/dist/exports-CVgs3YWV-BF4rqnxF.mjs.map +0 -1
- package/dist/import-roots-DlSoi7oS.d.mts +0 -119
- package/dist/import-roots-DlSoi7oS.d.mts.map +0 -1
- package/dist/import-roots-Dqs1_cn4.mjs +0 -224
- package/dist/import-roots-Dqs1_cn4.mjs.map +0 -1
- package/dist/index-BHYAWGxJ.d.mts.map +0 -1
- package/dist/index-BhNbc269.d.mts.map +0 -1
- package/dist/output-BcC8eB0h-C5bRd-aC.mjs.map +0 -1
- package/dist/publish-surface.d.mts +0 -3
- package/dist/publish-surface.mjs +0 -3
- package/dist/publish-surface__import-roots.d.mts +0 -2
- package/dist/publish-surface__import-roots.mjs +0 -2
- package/dist/publish-surface__shells.d.mts +0 -2
- package/dist/publish-surface__shells.mjs +0 -2
- package/dist/quick-reference-mongo.md +0 -116
- package/dist/quick-reference-postgres.md +0 -95
- package/dist/quick-reference-prisma7.md +0 -80
- package/dist/readme-mongo.md +0 -35
- package/dist/readme-postgres.md +0 -34
- package/dist/ref-DfuqRCA7-CPPoVHY9.mjs.map +0 -1
- package/dist/shells-BA7YJyPT.mjs +0 -777
- package/dist/shells-BA7YJyPT.mjs.map +0 -1
- package/dist/shells-D7NNxMLT.d.mts +0 -129
- package/dist/shells-D7NNxMLT.d.mts.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as expandContractInputs } from "./exports-
|
|
1
|
+
import { a as expandContractInputs } from "./exports-CZ6dPu-O.mjs";
|
|
2
2
|
import { t as EMPTY_CONTRACT_HASH } from "./constants-CM-w38DQ-Cz_EXbOc.mjs";
|
|
3
3
|
import { D as errorNoInvariantPath, M as errorUnknownInvariant, b as errorInvalidRefName, r as errorContractDeserializationFailed, t as MigrationToolsError, y as errorInvalidRefFile } from "./errors-BMq40nYH-Cg8PBect.mjs";
|
|
4
4
|
import { r as verifyMigrationHash, t as computeMigrationHash } from "./hash-BAZVWU4a-BQovI7hF.mjs";
|
|
@@ -8,36 +8,34 @@ import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigratio
|
|
|
8
8
|
import { i as findPathWithDecision, r as findPath } from "./migration-graph-BoiiZAaU-DLht12k7.mjs";
|
|
9
9
|
import { c as readContractSpaceHeadRef, l as spaceMigrationDirectory, o as isValidSpaceId, s as listContractSpaceDirectories, t as APP_SPACE_ID$1, u as spaceRefsDirectory } from "./verify-contract-spaces-BOnqhfQs-BBq5YOKo.mjs";
|
|
10
10
|
import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-OVZ0QzWJ.mjs";
|
|
11
|
-
import { $ as
|
|
12
|
-
import { r as getEmittedArtifactPaths, t as emit } from "./exports-
|
|
11
|
+
import { $ as errorStatementInvalid, A as errorFileNotFound, B as errorPathUnreachable, Ct as statementFlag, E as errorContractValidationFailed, Et as writtenMigrationRunCommand, G as errorRefSetEmptySentinel, H as errorPlanOriginUnknown, I as errorMigrationHasUnfilledPlaceholders, K as errorRefSetHashNotInGraph, N as errorInvalidSpaceId, Q as errorStatementDidNotResolveLoss, R as errorMigrationPlanningFailed, S as errorConsentUnused, St as shellQuoted, T as errorContractTypesModuleMissing, Tt as toStructuralEdge, U as errorPlanProducedNoOperations, V as errorPlanForgotTheFlag, W as errorRefSetBundleNotFound, X as errorSpaceNotFound, Y as errorSnapshotMissing, Z as errorStatementAnswersNoQuestion, at as errorUnexpected, b as errorAmbiguousMigrationRef, bt as runCommandAction, c as cliCommand, d as closeQuietly, dt as planThenApply, et as errorStatementNeedsMigrationFile, f as collectDeclaredInvariants, ft as printedPath, g as dbUpdateRerun, gt as requireLiveDatabase, h as dbMigrateRerun, j as errorFromCaught, l as cliErrorFromStructured, lt as migrationModuleOf, m as contractTypesModuleOf, mt as readContractEnvelope, n as CliStructuredError$1, nt as errorStatementUnresolved, ot as getTargetMigrations, pt as printedPlanCommand, q as errorRuntime, r as STORE_ORIGIN_SNAPSHOT_STEPS, rt as errorTargetMigrationNotSupported, s as chooseAction, st as mapRefResolutionError, t as ActionableCliError, tt as errorStatementOriginUnknown, ut as migrationsDirFor, v as editFileAction, vt as resolveContractPath, w as errorContractConfigMissing, x as errorConfigValidation$1, xt as selfEmitCommand, yt as resolveMigrationPaths } from "./caught-errors-D_pbHqmS-B-4jRN6g.mjs";
|
|
12
|
+
import { r as getEmittedArtifactPaths, t as emit } from "./exports-CCuYD8dO-yw1GizAT.mjs";
|
|
13
13
|
import { n as isGraphNode, t as assertHashIsGraphNode } from "./graph-membership-D7m41lWA-B68g1CRS.mjs";
|
|
14
|
-
import { a as readRefs, d as validateRefValue, n as advanceRef, r as deleteRef, s as refsByContractHash, t as HEAD_REF_NAME, u as validateRefName } from "./refs-t_JbIjGo-
|
|
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-
|
|
14
|
+
import { a as readRefs, d as validateRefValue, n as advanceRef, r as deleteRef, s as refsByContractHash, t as HEAD_REF_NAME, u as validateRefName } from "./refs-t_JbIjGo-BVCqKpXd.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-7sB4u_aJ.mjs";
|
|
16
16
|
import { a as writeMigrationTs, n as formatMigrationTs } from "./migration-ts-DDgjsR1O.mjs";
|
|
17
|
-
import { c as
|
|
18
|
-
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-C9j2SSb6.mjs";
|
|
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-C0xsiRig.mjs";
|
|
19
18
|
import { createRequire } from "node:module";
|
|
20
19
|
import { ifDefined } from "@prisma/orm-framework/utils/defined";
|
|
21
20
|
import { CliStructuredError } from "@prisma/orm-framework/errors/control";
|
|
22
|
-
import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, createControlStack, databasePoliciesOf, databasePolicyDifferences, databasePolicyValueText, describeMigrationStatement, enumValueCoordinateFromJson, enumValueStatementText, fieldStatementText, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, modelStatementText, movedDatabasePoliciesWhy, planOriginOf, valueObjectFieldStatementText, withDeclaredDatabasePolicies } from "@prisma/orm-framework/components/control";
|
|
21
|
+
import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, DATA_PROTECTION_KEYS, createControlStack, databasePoliciesOf, databasePolicyDifferences, databasePolicyValueText, describeMigrationStatement, enumValueCoordinateFromJson, enumValueStatementText, fieldStatementText, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, modelStatementText, movedDatabasePoliciesWhy, planOriginOf, valueObjectFieldStatementText, withDeclaredDatabasePolicies } from "@prisma/orm-framework/components/control";
|
|
23
22
|
import { InternalError } from "@prisma/orm-framework/utils/internal-error";
|
|
23
|
+
import { notOk, ok } from "@prisma/orm-framework/utils/result";
|
|
24
24
|
import { docsUrlFor, isStructuredError, isStructuredErrorCode, structuredError } from "@prisma/orm-framework/utils/structured-error";
|
|
25
25
|
import { basename, dirname, isAbsolute, join, relative, resolve } from "pathe";
|
|
26
26
|
import { errorMarkerPoliciesCorrupt } from "@prisma/orm-framework/errors/execution";
|
|
27
27
|
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
28
28
|
import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
|
|
29
29
|
import { type } from "arktype";
|
|
30
|
-
import { existsSync,
|
|
30
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
31
|
+
import { compareCodeUnits } from "@prisma/orm-framework/contract/hashing-utils";
|
|
31
32
|
import { asNamespaceId, valueObjectAt, valueObjectsWithCoordinates } from "@prisma/orm-framework/contract/types";
|
|
32
|
-
import { keepInternalSpecifiers } from "@prisma/orm-framework/components/emission";
|
|
33
33
|
import { UNBOUND_NAMESPACE_ID, changedElementCoordinates } from "@prisma/orm-framework/components/ir";
|
|
34
|
-
import { notOk, ok } from "@prisma/orm-framework/utils/result";
|
|
35
34
|
import { mergeCapabilityMatrices } from "@prisma/orm-framework/components/components";
|
|
36
35
|
import { isDeepStrictEqual } from "node:util";
|
|
37
36
|
import { canonicalStringify } from "@prisma/orm-framework/utils/canonical-stringify";
|
|
38
37
|
import { abortable } from "@prisma/orm-framework/utils/abortable";
|
|
39
|
-
|
|
40
|
-
//#region ../../../1-framework/3-tooling/cli/dist/ref-DfuqRCA7.mjs
|
|
38
|
+
//#region ../../../1-framework/3-tooling/cli/dist/ref-PQOM_LTC.mjs
|
|
41
39
|
/**
|
|
42
40
|
* The meta of a contract that failed to load because the family refused it, such as the columns whose defaults it refused, for the command to report: the refusal's own meta, or the `refusedDefaults` a migration-tools error kept from it.
|
|
43
41
|
*/
|
|
@@ -123,7 +121,7 @@ function isPlainObject(value) {
|
|
|
123
121
|
function sortDeep(value) {
|
|
124
122
|
if (Array.isArray(value)) return value.map(sortDeep);
|
|
125
123
|
if (!isPlainObject(value)) return value;
|
|
126
|
-
const entries = Object.entries(value).sort(([a], [b]) => a
|
|
124
|
+
const entries = Object.entries(value).sort(([a], [b]) => compareCodeUnits(a, b));
|
|
127
125
|
const next = {};
|
|
128
126
|
for (const [key, child] of entries) next[key] = sortDeep(child);
|
|
129
127
|
return next;
|
|
@@ -131,15 +129,25 @@ function sortDeep(value) {
|
|
|
131
129
|
function sortDeepTyped(value) {
|
|
132
130
|
return sortDeep(value);
|
|
133
131
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
"
|
|
132
|
+
const TYPE_IMPORT_MEMBERS_THE_EMITTER_READS_FROM_THE_DESCRIPTOR = [
|
|
133
|
+
"import",
|
|
134
|
+
"typeImports",
|
|
135
|
+
"parameterizedOutputTypes"
|
|
136
|
+
];
|
|
137
|
+
const CODEC_MEMBERS_HOLDING_FUNCTIONS = ["controlPlaneHooks", "codecDescriptors"];
|
|
138
|
+
const CONTRACT_TYPES_KEYS_WITH_OMITTED_MEMBERS = /* @__PURE__ */ new Map([
|
|
139
|
+
["aggregateDescriptors", /* @__PURE__ */ new Set()],
|
|
140
|
+
["codecTypes", /* @__PURE__ */ new Set([...TYPE_IMPORT_MEMBERS_THE_EMITTER_READS_FROM_THE_DESCRIPTOR, ...CODEC_MEMBERS_HOLDING_FUNCTIONS])],
|
|
141
|
+
["operationTypes", /* @__PURE__ */ new Set(["import"])],
|
|
142
|
+
["queryOperationTypes", /* @__PURE__ */ new Set(["import"])]
|
|
142
143
|
]);
|
|
144
|
+
function contractTypesEntry(key, value) {
|
|
145
|
+
const omitted = CONTRACT_TYPES_KEYS_WITH_OMITTED_MEMBERS.get(key);
|
|
146
|
+
if (omitted === void 0) return void 0;
|
|
147
|
+
if (!isPlainObject(value)) return [key, value];
|
|
148
|
+
const kept = Object.entries(value).filter(([member]) => !omitted.has(member));
|
|
149
|
+
return kept.length > 0 ? [key, Object.fromEntries(kept)] : void 0;
|
|
150
|
+
}
|
|
143
151
|
function extractExtensionPackMeta(component) {
|
|
144
152
|
const { kind, id, version, capabilities, types } = component;
|
|
145
153
|
const base = {
|
|
@@ -150,16 +158,11 @@ function extractExtensionPackMeta(component) {
|
|
|
150
158
|
version
|
|
151
159
|
};
|
|
152
160
|
if (capabilities) base["capabilities"] = capabilities;
|
|
153
|
-
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
...carried,
|
|
159
|
-
codecTypes: cleanedCodecTypes
|
|
160
|
-
};
|
|
161
|
-
} else base["types"] = carried;
|
|
162
|
-
}
|
|
161
|
+
const carried = Object.entries(types ?? {}).flatMap(([key, value]) => {
|
|
162
|
+
const entry = contractTypesEntry(key, value);
|
|
163
|
+
return entry === void 0 ? [] : [entry];
|
|
164
|
+
});
|
|
165
|
+
if (carried.length > 0) base["types"] = Object.fromEntries(carried);
|
|
163
166
|
return base;
|
|
164
167
|
}
|
|
165
168
|
/**
|
|
@@ -611,14 +614,15 @@ function startText(fromHash) {
|
|
|
611
614
|
return fromHash === "empty" ? "the empty contract (the space has no marker)" : `the contract its marker names ("${fromHash}")`;
|
|
612
615
|
}
|
|
613
616
|
const INSTALL_MATCHING = "Install a version of the extension whose migrations start from the contract the database is at";
|
|
617
|
+
const INSTALL_WITH_MIGRATIONS = "Install a version of the extension that ships its migrations";
|
|
614
618
|
/** The way out for an extension space: only another version of the extension changes its migrations. */
|
|
615
|
-
function extensionAdvice$1(space) {
|
|
616
|
-
const rerun = cliCommand(space.invocation, space.command);
|
|
619
|
+
function extensionAdvice$1(space, install = INSTALL_MATCHING) {
|
|
620
|
+
const rerun = space.command === "db migrate" ? dbMigrateRerun(space.invocation) : cliCommand(space.invocation, space.command);
|
|
617
621
|
const list = cliCommand(space.invocation, "migration list", ["--space", space.spaceId]);
|
|
618
622
|
return {
|
|
619
|
-
fix: `The migrations of extension space "${space.spaceId}" come with the extension. ${
|
|
623
|
+
fix: `The migrations of extension space "${space.spaceId}" come with the extension. ${install}, then run \`${rerun}\` again. List the space's migrations with \`${list}\`.`,
|
|
620
624
|
nextActions: [
|
|
621
|
-
chooseAction(
|
|
625
|
+
chooseAction(install),
|
|
622
626
|
runCommandAction(`List the migrations of extension space "${space.spaceId}"`, list),
|
|
623
627
|
runCommandAction(`Run ${space.command} again`, rerun)
|
|
624
628
|
]
|
|
@@ -637,6 +641,18 @@ function errorExtensionPathUnreachable(space) {
|
|
|
637
641
|
}
|
|
638
642
|
}, extensionAdvice$1(space));
|
|
639
643
|
}
|
|
644
|
+
/** `MIGRATION.PATH_UNREACHABLE` for an extension space that declares storage Prisma manages and ships no migrations to create it. */
|
|
645
|
+
function errorExtensionNeverPlanned(space) {
|
|
646
|
+
return errorPathUnreachable({
|
|
647
|
+
summary: `No on-disk migrations for extension space "${space.spaceId}"`,
|
|
648
|
+
why: `Extension space "${space.spaceId}" declares storage that Prisma manages, but the extension ships no migrations for it, and its head ref targets "${space.targetHash}".`,
|
|
649
|
+
meta: {
|
|
650
|
+
kind: "neverPlanned",
|
|
651
|
+
spaceId: space.spaceId,
|
|
652
|
+
targetHash: space.targetHash
|
|
653
|
+
}
|
|
654
|
+
}, extensionAdvice$1(space, INSTALL_WITH_MIGRATIONS));
|
|
655
|
+
}
|
|
640
656
|
/**
|
|
641
657
|
* `MIGRATION.NO_INVARIANT_PATH` for an extension space whose migrations reach the extension's head
|
|
642
658
|
* from where the database is, but not through the ones that provide the invariants its head requires.
|
|
@@ -765,6 +781,16 @@ function planningRefusedError(conflicts, context) {
|
|
|
765
781
|
...ifDefined("docsUrl", refused.docsUrl)
|
|
766
782
|
});
|
|
767
783
|
}
|
|
784
|
+
/** Each data protection setting's `forbidden` level. */
|
|
785
|
+
const FORBIDDEN_LEVEL = {
|
|
786
|
+
dataLoss: "data-loss-forbidden",
|
|
787
|
+
accessWidening: "access-widening-forbidden"
|
|
788
|
+
};
|
|
789
|
+
/** Each data protection setting's `permitted` level. */
|
|
790
|
+
const PERMITTED_LEVEL = {
|
|
791
|
+
dataLoss: "data-loss-permitted",
|
|
792
|
+
accessWidening: "access-widening-permitted"
|
|
793
|
+
};
|
|
768
794
|
/** `change: migrate; dataProtection.dataLoss: data-loss-forbidden`: the declared side of each difference. */
|
|
769
795
|
function declaredSettingsText(differences) {
|
|
770
796
|
return differences.map(({ setting, declared }) => `${setting}: ${databasePolicyValueText(declared)}`).join("; ");
|
|
@@ -824,6 +850,72 @@ function errorChangePolicyForbids(args) {
|
|
|
824
850
|
meta
|
|
825
851
|
});
|
|
826
852
|
}
|
|
853
|
+
const FORBIDDEN_CHANGE = {
|
|
854
|
+
dataLoss: "data loss",
|
|
855
|
+
accessWidening: "changing who can read or write data"
|
|
856
|
+
};
|
|
857
|
+
/** Who refuses the change: the database's own policy, or the one a ref declares for its database. */
|
|
858
|
+
function refusingPolicy(source, forbids) {
|
|
859
|
+
return source.kind === "ref" ? `${source.refName} declares a data protection policy that forbids ${forbids}, so these operations cannot run on the database it describes.` : `This database's data protection policy forbids ${forbids}, so these operations cannot run on it.`;
|
|
860
|
+
}
|
|
861
|
+
const KEEP_APPLIED_MIGRATION = "If another database has already applied this migration, keep it as it is: this database cannot run it until its data protection policy changes.";
|
|
862
|
+
function doItAnyway(source) {
|
|
863
|
+
return source.kind === "ref" ? `To do it anyway, whoever owns that database must first change the data protection policy ${source.refName} declares.` : "To do it anyway, whoever owns the database must first change its data protection policy.";
|
|
864
|
+
}
|
|
865
|
+
/** What a user can do instead of a refused change, for the command that refused it. */
|
|
866
|
+
function keepProtected(refusal, command, invocation) {
|
|
867
|
+
const migrated = command === "db migrate";
|
|
868
|
+
if (refusal.setting === "accessWidening") return [
|
|
869
|
+
refusingPolicy(refusal.source, FORBIDDEN_CHANGE.accessWidening),
|
|
870
|
+
...migrated ? [KEEP_APPLIED_MIGRATION, "If none has, remove the operation from the migration."] : ["Keep the contract's access rules as they are."],
|
|
871
|
+
doItAnyway(refusal.source)
|
|
872
|
+
].join(" ");
|
|
873
|
+
const changesType = refusal.operations.some(({ loss }) => loss === "typeChange");
|
|
874
|
+
return [
|
|
875
|
+
refusingPolicy(refusal.source, "losing data"),
|
|
876
|
+
...migrated ? [KEEP_APPLIED_MIGRATION, "If none has, and a model or field was only renamed or its type changed, delete it and plan it again with --rename or --convert; otherwise remove the operation from the migration."] : [
|
|
877
|
+
"If a model or field was only renamed, state the rename with --rename <old>:<new>.",
|
|
878
|
+
...changesType ? [`For a type change, write the conversion with ${cliCommand(invocation === void 0 ? void 0 : {
|
|
879
|
+
...invocation,
|
|
880
|
+
dbGiven: false
|
|
881
|
+
}, "migration plan", ["--convert", "<field>"])}.`] : [],
|
|
882
|
+
"Otherwise keep it in the contract."
|
|
883
|
+
],
|
|
884
|
+
doItAnyway(refusal.source)
|
|
885
|
+
].join(" ");
|
|
886
|
+
}
|
|
887
|
+
function refusedOperationText(operation) {
|
|
888
|
+
const where = operation.migration === void 0 ? `in contract space "${operation.spaceId}"` : `in migration ${operation.migration} of contract space "${operation.spaceId}"`;
|
|
889
|
+
return `${operation.label} (${operation.subject}), ${where}.`;
|
|
890
|
+
}
|
|
891
|
+
/** `MIGRATION.DATA_PROTECTION_FORBIDS`: a run would lose data, or change who can read or write data, where a setting forbids it. */
|
|
892
|
+
function errorDataProtectionForbids(args) {
|
|
893
|
+
const { spaceId, command, refusals } = args;
|
|
894
|
+
const refNames = new Set(refusals.map(({ source }) => source.kind === "ref" ? source.refName : void 0));
|
|
895
|
+
const [onlyRefName] = refNames;
|
|
896
|
+
const refName = refNames.size === 1 ? onlyRefName : void 0;
|
|
897
|
+
const policyHolder = refName === void 0 ? "This database's data protection policy" : `${refName} declares a data protection policy that`;
|
|
898
|
+
const forbidden = refusals.map(({ setting }) => FORBIDDEN_CHANGE[setting]).join(" and ");
|
|
899
|
+
const why = refusals.flatMap(({ setting, source, operations }) => [`${source.kind === "ref" ? `${source.refName} declares` : "The marker records"} ${setting}: ${FORBIDDEN_LEVEL[setting]}.`, ...operations.map(refusedOperationText)]).join(" ");
|
|
900
|
+
const recoveries = refusals.map((refusal) => keepProtected(refusal, command, args.invocation));
|
|
901
|
+
return new ActionableCliError("MIGRATION.DATA_PROTECTION_FORBIDS", `${policyHolder} forbids ${forbidden}`, {
|
|
902
|
+
why,
|
|
903
|
+
fix: recoveries.join(" "),
|
|
904
|
+
nextActions: recoveries.map(chooseAction),
|
|
905
|
+
meta: {
|
|
906
|
+
spaceId,
|
|
907
|
+
command,
|
|
908
|
+
settings: refusals.map(({ setting }) => ({
|
|
909
|
+
setting,
|
|
910
|
+
level: FORBIDDEN_LEVEL[setting]
|
|
911
|
+
})),
|
|
912
|
+
operations: refusals.flatMap(({ setting, operations }) => operations.map((operation) => ({
|
|
913
|
+
setting,
|
|
914
|
+
...operation
|
|
915
|
+
})))
|
|
916
|
+
}
|
|
917
|
+
});
|
|
918
|
+
}
|
|
827
919
|
/**
|
|
828
920
|
* `CLI.INVALID_ARGUMENTS`: consent to write policies was given without a ref whose policies it could
|
|
829
921
|
* write. `command` names the CLI command that was run, whose flags the error names; without it, the
|
|
@@ -1044,7 +1136,7 @@ const MODEL_RENAMES = "model";
|
|
|
1044
1136
|
const FIELD_RENAMES = "field";
|
|
1045
1137
|
const LISTED_LIMIT = 20;
|
|
1046
1138
|
const CHECK_NAMES_FIX = "The old name must exist in the origin contract and not in the destination contract, and the new name the other way round. Names match exactly, including case.";
|
|
1047
|
-
const STORED_NAME_ONLY = "
|
|
1139
|
+
const STORED_NAME_ONLY = "A model or field that keeps its name needs no statement when only its stored name changes (@map or @@map).";
|
|
1048
1140
|
const REPEATED_NAME_FIX = "Give each model, field or enum value at most one statement, and each new name to one model, field or enum value only.";
|
|
1049
1141
|
function qualifiedModel(coordinate) {
|
|
1050
1142
|
return modelDisplayName(coordinate);
|
|
@@ -1468,7 +1560,7 @@ function resolveModelRename(state, statement, from, to) {
|
|
|
1468
1560
|
const toKey = `${MODEL_RENAMES}:${qualifiedModel(to)}`;
|
|
1469
1561
|
if (state.renamedFrom.has(fromKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames "${qualifiedModel(from)}".`, REPEATED_NAME_FIX));
|
|
1470
1562
|
if (state.renamedTo.has(toKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames a model to "${qualifiedModel(to)}".`, REPEATED_NAME_FIX));
|
|
1471
|
-
if (qualifiedModel(from) === qualifiedModel(to)) return notOk(errorStatementInvalid(statement, `The statement renames model "${qualifiedModel(from)}" to itself.`, `Leave out --${statement.verb} ${statement.text}. ${STORED_NAME_ONLY}`));
|
|
1563
|
+
if (qualifiedModel(from) === qualifiedModel(to)) return notOk(errorStatementInvalid(statement, `The statement renames model "${qualifiedModel(from)}" to itself.`, `Leave out --${statement.verb} ${statement.text} and plan again. ${STORED_NAME_ONLY}`));
|
|
1472
1564
|
if (modelAt(state.origin.contract, to) !== void 0 && modelAt(state.destination.contract, from) !== void 0) return notOk(swapRefusal(statement, "model", qualifiedModel(from), qualifiedModel(to)));
|
|
1473
1565
|
if (modelAt(state.origin.contract, to) !== void 0) return notOk(errorStatementUnresolved(statement, `"${qualifiedModel(to)}" already exists in the origin contract, so it cannot be the new name of a model.`, CHECK_NAMES_FIX));
|
|
1474
1566
|
if (modelAt(state.destination.contract, from) !== void 0) return notOk(errorStatementUnresolved(statement, `"${qualifiedModel(from)}" still exists in the destination contract, so it was not renamed.`, CHECK_NAMES_FIX));
|
|
@@ -1527,7 +1619,7 @@ function resolveFieldRename(state, statement, from, to) {
|
|
|
1527
1619
|
const toKey = `${FIELD_RENAMES}:${qualifiedField(to.coordinate)}`;
|
|
1528
1620
|
if (state.renamedFrom.has(fromKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames "${qualifiedField(from.coordinate)}".`, REPEATED_NAME_FIX));
|
|
1529
1621
|
if (state.renamedTo.has(toKey)) return notOk(errorStatementInvalid(statement, `An earlier statement already renames a field to "${qualifiedField(to.coordinate)}".`, REPEATED_NAME_FIX));
|
|
1530
|
-
if (from.coordinate.field === to.coordinate.field) return notOk(errorStatementInvalid(statement, `The statement renames field "${toModel}.${to.coordinate.field}" to itself.`, `Leave out --${statement.verb} ${statement.text}. ${STORED_NAME_ONLY}`));
|
|
1622
|
+
if (from.coordinate.field === to.coordinate.field) return notOk(errorStatementInvalid(statement, `The statement renames field "${toModel}.${to.coordinate.field}" to itself.`, `Leave out --${statement.verb} ${statement.text} and plan again. ${STORED_NAME_ONLY}`));
|
|
1531
1623
|
if (hasField(from.model, to.coordinate.field) && hasField(to.model, from.coordinate.field)) return notOk(swapRefusal(statement, "field", `${toModel}.${from.coordinate.field}`, `${toModel}.${to.coordinate.field}`));
|
|
1532
1624
|
if (hasField(from.model, to.coordinate.field)) return notOk(errorStatementUnresolved(statement, `The field "${to.coordinate.field}" already exists on the origin model "${qualifiedModel(from.coordinate)}", so it cannot be the new name of a field.`, newNameTakenFix(statement, from.coordinate.field, to.coordinate.field)));
|
|
1533
1625
|
if (hasField(to.model, from.coordinate.field)) return notOk(errorStatementUnresolved(statement, `The field "${from.coordinate.field}" still exists on the destination model "${toModel}", so it was not renamed.`, oldNameReusedFix(statement, from.coordinate.field, to.coordinate.field)));
|
|
@@ -1611,7 +1703,7 @@ function swapRefusal(statement, entity, first, second) {
|
|
|
1611
1703
|
const oldName = statement.from.join(".");
|
|
1612
1704
|
const newName = statement.to.join(".");
|
|
1613
1705
|
const temporary = entity === "model" ? "<temporary name>" : `${statement.to.slice(0, -1).join(".")}.<temporary name>`;
|
|
1614
|
-
const keptNames = entity === "enumValue" ? " If the members keep their names and only their stored values trade places, leave out the statement:
|
|
1706
|
+
const keptNames = entity === "enumValue" ? " If the members keep their names and only their stored values trade places, leave out the statement: a member that keeps its name needs no statement. Stored values that trade places take two plans, through a stored value no member stores." : "";
|
|
1615
1707
|
return errorStatementInvalid(statement, `"${first}" and "${second}" swap names: each is both an old name and a new name, and statements cannot swap names in one plan.`, `Make the swap in three plans. First change the contract so that "${first}" has a temporary name, and plan it with --${verb} ${oldName}:${temporary}. Then give "${second}" the name "${first}", and plan it with --${verb} ${newName}:${oldName}. Then give the temporary name the name "${second}", and plan it with --${verb} ${temporary}:${newName}.${keptNames}`);
|
|
1616
1708
|
}
|
|
1617
1709
|
/**
|
|
@@ -2657,6 +2749,7 @@ async function askPlanQuestions(input) {
|
|
|
2657
2749
|
const consented = /* @__PURE__ */ new Map();
|
|
2658
2750
|
const usedPreAnswers = /* @__PURE__ */ new Set();
|
|
2659
2751
|
for (let round = 0;; round += 1) {
|
|
2752
|
+
const answeredWithoutAsking = [];
|
|
2660
2753
|
const contracts = {
|
|
2661
2754
|
origin: input.origin,
|
|
2662
2755
|
originKnown: input.originKnown,
|
|
@@ -2686,7 +2779,13 @@ async function askPlanQuestions(input) {
|
|
|
2686
2779
|
if (statement !== void 0) usedPreAnswers.add(statement);
|
|
2687
2780
|
}
|
|
2688
2781
|
entries.forEach((entry, index) => {
|
|
2689
|
-
if (input.consentAll[verb]
|
|
2782
|
+
if (!input.consentAll[verb] && !matched.answered.has(index)) return;
|
|
2783
|
+
consent(verb, entry, texts[index] ?? "");
|
|
2784
|
+
if (!matched.answered.has(index)) answeredWithoutAsking.push({
|
|
2785
|
+
verb,
|
|
2786
|
+
subject: texts[index] ?? "",
|
|
2787
|
+
...ifDefined("removedNamespace", removedNamespaceOf(entry.subject, plan.namespaces))
|
|
2788
|
+
});
|
|
2690
2789
|
});
|
|
2691
2790
|
}
|
|
2692
2791
|
const losses = pending("delete", plan.dataLoss);
|
|
@@ -2706,7 +2805,7 @@ async function askPlanQuestions(input) {
|
|
|
2706
2805
|
loss,
|
|
2707
2806
|
question: acceptingNamespaceAnswers(dataLossQuestion(loss, roundContracts, editsOf(loss), sameSubject(loss).map(({ label }) => label)), removedNamespaceOf(loss.subject, plan.namespaces), contracts)
|
|
2708
2807
|
})), !input.originKnown), plan.namespaces?.added ?? []), ...accessChanges.map((change) => accessChangeQuestion(change, contracts))];
|
|
2709
|
-
const answers = await input.answer(questions);
|
|
2808
|
+
const answers = await input.answer(questions, answeredWithoutAsking);
|
|
2710
2809
|
checkAnswers(questions, answers);
|
|
2711
2810
|
const typed = [];
|
|
2712
2811
|
answers.forEach((answer, index) => {
|
|
@@ -3223,6 +3322,7 @@ async function buildReadAggregate(config, options) {
|
|
|
3223
3322
|
aggregate: loaded.value,
|
|
3224
3323
|
contractHash,
|
|
3225
3324
|
storageNameOf: (operation) => familyInstance.storageNameOf(operation),
|
|
3325
|
+
accessChangesOf: (operations) => familyInstance.accessChangesOf(operations),
|
|
3226
3326
|
markerLocation: familyInstance.markerLocation
|
|
3227
3327
|
});
|
|
3228
3328
|
} catch (error) {
|
|
@@ -3288,6 +3388,58 @@ function checkRunPolicies(args) {
|
|
|
3288
3388
|
toWrite
|
|
3289
3389
|
});
|
|
3290
3390
|
}
|
|
3391
|
+
/** The data protection levels a checked run obeys: those it records when it consents to a change, otherwise those in force. */
|
|
3392
|
+
function dataProtectionOfRun(checked) {
|
|
3393
|
+
return checked.toWrite?.policies.dataProtection ?? checked.inForce.dataProtection;
|
|
3394
|
+
}
|
|
3395
|
+
/** The data protection settings a checked run obeys at their `permitted` level: nobody is asked about what they cover. */
|
|
3396
|
+
function permittedSettingsOfRun(checked) {
|
|
3397
|
+
const levels = dataProtectionOfRun(checked);
|
|
3398
|
+
return DATA_PROTECTION_KEYS.filter((setting) => levels[setting] === PERMITTED_LEVEL[setting]);
|
|
3399
|
+
}
|
|
3400
|
+
function forbiddingSettings(levels, sourceOf) {
|
|
3401
|
+
return Object.fromEntries(DATA_PROTECTION_KEYS.flatMap((setting) => levels?.[setting] === FORBIDDEN_LEVEL[setting] ? [[setting, sourceOf(setting)]] : []));
|
|
3402
|
+
}
|
|
3403
|
+
/**
|
|
3404
|
+
* The settings a checked run forbids. A setting the run records from `ref` is the ref's; any other
|
|
3405
|
+
* is the marker's.
|
|
3406
|
+
*/
|
|
3407
|
+
function forbiddingSettingsOfRun(checked, ref) {
|
|
3408
|
+
const declared = checked.toWrite === void 0 ? void 0 : ref?.policies?.dataProtection;
|
|
3409
|
+
return forbiddingSettings(dataProtectionOfRun(checked), (setting) => ref !== void 0 && declared?.[setting] !== void 0 ? {
|
|
3410
|
+
kind: "ref",
|
|
3411
|
+
refName: ref.name
|
|
3412
|
+
} : { kind: "marker" });
|
|
3413
|
+
}
|
|
3414
|
+
/** The settings `ref` declares at their `forbidden` level, which a plan made for it obeys. */
|
|
3415
|
+
function forbiddingSettingsOfRef(ref) {
|
|
3416
|
+
return forbiddingSettings(ref.policies?.dataProtection, () => ({
|
|
3417
|
+
kind: "ref",
|
|
3418
|
+
refName: ref.name
|
|
3419
|
+
}));
|
|
3420
|
+
}
|
|
3421
|
+
/** Refuses the operations that lose data or change access where a forbidden setting covers them; `undefined` when none is refused. */
|
|
3422
|
+
function refuseForbiddenChanges(args) {
|
|
3423
|
+
const operationsOf = {
|
|
3424
|
+
dataLoss: args.dataLoss,
|
|
3425
|
+
accessWidening: args.accessChanges
|
|
3426
|
+
};
|
|
3427
|
+
const refusals = DATA_PROTECTION_KEYS.flatMap((setting) => {
|
|
3428
|
+
const source = args.forbidden[setting];
|
|
3429
|
+
const operations = operationsOf[setting];
|
|
3430
|
+
return source === void 0 || operations.length === 0 ? [] : [{
|
|
3431
|
+
setting,
|
|
3432
|
+
source,
|
|
3433
|
+
operations
|
|
3434
|
+
}];
|
|
3435
|
+
});
|
|
3436
|
+
return refusals.length === 0 ? void 0 : errorDataProtectionForbids({
|
|
3437
|
+
spaceId: args.appSpaceId,
|
|
3438
|
+
command: args.command,
|
|
3439
|
+
refusals,
|
|
3440
|
+
invocation: args.invocation
|
|
3441
|
+
});
|
|
3442
|
+
}
|
|
3291
3443
|
/**
|
|
3292
3444
|
* Strips operation objects to their public shape (id, label, operationClass).
|
|
3293
3445
|
* Used at the API boundary to avoid leaking internal fields (precheck, execute, postcheck, etc.).
|
|
@@ -3641,6 +3793,22 @@ async function executeRun(options) {
|
|
|
3641
3793
|
spanId: SPAN_IDS$1.introspect,
|
|
3642
3794
|
outcome: "ok"
|
|
3643
3795
|
});
|
|
3796
|
+
const refuseForbidden = (planned, texts) => {
|
|
3797
|
+
if (options.action !== "dbUpdate" || checkedPolicies === void 0) return void 0;
|
|
3798
|
+
const operations = (entries) => plannedOperations(planned.orderedResolutions, entries, {
|
|
3799
|
+
origin: fromContract ?? EMPTY_ORIGIN$1,
|
|
3800
|
+
destination: contract,
|
|
3801
|
+
statements: texts
|
|
3802
|
+
});
|
|
3803
|
+
return refuseForbiddenChanges({
|
|
3804
|
+
appSpaceId: aggregate.app.spaceId,
|
|
3805
|
+
command: "db update",
|
|
3806
|
+
invocation: options.invocation,
|
|
3807
|
+
forbidden: forbiddingSettingsOfRun(checkedPolicies, options.ref),
|
|
3808
|
+
dataLoss: operations(planned.subjects.dataLoss),
|
|
3809
|
+
accessChanges: operations(planned.subjects.accessChanges)
|
|
3810
|
+
});
|
|
3811
|
+
};
|
|
3644
3812
|
const plan = async (texts, resolved) => {
|
|
3645
3813
|
onProgress?.({
|
|
3646
3814
|
action,
|
|
@@ -3663,7 +3831,8 @@ async function executeRun(options) {
|
|
|
3663
3831
|
fromContract,
|
|
3664
3832
|
statements: resolved
|
|
3665
3833
|
},
|
|
3666
|
-
storageNameOf: (operation) => familyInstance.storageNameOf(operation)
|
|
3834
|
+
storageNameOf: (operation) => familyInstance.storageNameOf(operation),
|
|
3835
|
+
accessChangesOf: (operations) => familyInstance.accessChangesOf(operations)
|
|
3667
3836
|
});
|
|
3668
3837
|
if (!planned.ok) {
|
|
3669
3838
|
onProgress?.({
|
|
@@ -3698,7 +3867,7 @@ async function executeRun(options) {
|
|
|
3698
3867
|
...entry,
|
|
3699
3868
|
label: operations[entry.operationIndex]?.label ?? JSON.stringify(entry.subject)
|
|
3700
3869
|
}));
|
|
3701
|
-
|
|
3870
|
+
const run = {
|
|
3702
3871
|
planned: planned.value,
|
|
3703
3872
|
orderedResolutions,
|
|
3704
3873
|
subjects,
|
|
@@ -3709,13 +3878,23 @@ async function executeRun(options) {
|
|
|
3709
3878
|
accessChanges: labelled(subjects.accessChanges),
|
|
3710
3879
|
temporaryValues: subjects.temporaryValues,
|
|
3711
3880
|
...ifDefined("namespaces", orderedResolutions.find(({ spaceId }) => spaceId === aggregate.app.spaceId)?.entry.namespaces)
|
|
3712
|
-
}
|
|
3881
|
+
};
|
|
3882
|
+
const refused = refuseForbidden(run, texts.filter(isPlannedStatement));
|
|
3883
|
+
return refused === void 0 ? ok(run) : notOk({ refused });
|
|
3713
3884
|
};
|
|
3714
3885
|
const first = await plan(statementTexts, firstResolved);
|
|
3715
3886
|
if (!first.ok) return notOk(first.failure.refused);
|
|
3716
3887
|
let run = first.value;
|
|
3717
3888
|
let plannedTexts = statementTexts.filter(isPlannedStatement);
|
|
3718
3889
|
let consented = [];
|
|
3890
|
+
const permitted = checkedPolicies === void 0 ? [] : permittedSettingsOfRun(checkedPolicies);
|
|
3891
|
+
const consentAll = options.action === "dbUpdate" ? {
|
|
3892
|
+
delete: options.acceptDataLoss || permitted.includes("dataLoss"),
|
|
3893
|
+
allow: options.acceptAccessChanges || permitted.includes("accessWidening")
|
|
3894
|
+
} : {
|
|
3895
|
+
delete: false,
|
|
3896
|
+
allow: false
|
|
3897
|
+
};
|
|
3719
3898
|
if (options.action === "dbUpdate" && mode === "apply") {
|
|
3720
3899
|
const answered = await askPlanQuestions({
|
|
3721
3900
|
plan: run,
|
|
@@ -3723,10 +3902,7 @@ async function executeRun(options) {
|
|
|
3723
3902
|
canConvert: false,
|
|
3724
3903
|
statements: plannedTexts,
|
|
3725
3904
|
preAnswers: consentTexts,
|
|
3726
|
-
consentAll
|
|
3727
|
-
delete: options.acceptDataLoss,
|
|
3728
|
-
allow: options.acceptAccessChanges
|
|
3729
|
-
},
|
|
3905
|
+
consentAll,
|
|
3730
3906
|
origin: fromContract ?? EMPTY_ORIGIN$1,
|
|
3731
3907
|
originKnown: fromContract !== null,
|
|
3732
3908
|
destination: contract,
|
|
@@ -3756,10 +3932,7 @@ async function executeRun(options) {
|
|
|
3756
3932
|
consented = givenConsents({
|
|
3757
3933
|
plan: run,
|
|
3758
3934
|
statements: statementTexts,
|
|
3759
|
-
consentAll
|
|
3760
|
-
delete: options.acceptDataLoss,
|
|
3761
|
-
allow: options.acceptAccessChanges
|
|
3762
|
-
},
|
|
3935
|
+
consentAll,
|
|
3763
3936
|
contracts: {
|
|
3764
3937
|
origin: fromContract ?? EMPTY_ORIGIN$1,
|
|
3765
3938
|
destination: contract,
|
|
@@ -3805,7 +3978,8 @@ async function executeRun(options) {
|
|
|
3805
3978
|
summary,
|
|
3806
3979
|
appliedStatements,
|
|
3807
3980
|
subjects,
|
|
3808
|
-
databaseStorageHash
|
|
3981
|
+
databaseStorageHash,
|
|
3982
|
+
permitted
|
|
3809
3983
|
});
|
|
3810
3984
|
}
|
|
3811
3985
|
const applied = await runMigration({
|
|
@@ -3845,7 +4019,8 @@ async function executeRun(options) {
|
|
|
3845
4019
|
subjects,
|
|
3846
4020
|
databaseStorageHash,
|
|
3847
4021
|
changedStorageEntities: signedWithoutOperations ? changedStorageEntities(fromContract, contract) : void 0,
|
|
3848
|
-
databasePoliciesUpdated: policiesToWrite?.differences
|
|
4022
|
+
databasePoliciesUpdated: policiesToWrite?.differences,
|
|
4023
|
+
permitted
|
|
3849
4024
|
});
|
|
3850
4025
|
}
|
|
3851
4026
|
/** The origin of a database whose marker names no readable contract: no models. */
|
|
@@ -3915,6 +4090,27 @@ async function readAppOrigin(input) {
|
|
|
3915
4090
|
};
|
|
3916
4091
|
}
|
|
3917
4092
|
}
|
|
4093
|
+
/**
|
|
4094
|
+
* The operations of a plan that `entries` name, each with its space and its subject as the user
|
|
4095
|
+
* names it. `entries` index the operations of every space, in apply order.
|
|
4096
|
+
*/
|
|
4097
|
+
function plannedOperations(orderedResolutions, entries, contracts) {
|
|
4098
|
+
const placed = orderedResolutions.flatMap((resolution) => resolution.entry.displayOps.map((operation) => ({
|
|
4099
|
+
spaceId: resolution.spaceId,
|
|
4100
|
+
operation
|
|
4101
|
+
})));
|
|
4102
|
+
return entries.map(({ operationIndex, subject, loss }) => {
|
|
4103
|
+
const at = placed[operationIndex];
|
|
4104
|
+
if (at === void 0) throw new InternalError(`Unreachable: the plan names operation ${operationIndex}, which it does not hold`);
|
|
4105
|
+
return {
|
|
4106
|
+
spaceId: at.spaceId,
|
|
4107
|
+
operationId: at.operation.id,
|
|
4108
|
+
subject: subjectText(subject, contracts),
|
|
4109
|
+
label: at.operation.label,
|
|
4110
|
+
...ifDefined("loss", loss)
|
|
4111
|
+
};
|
|
4112
|
+
});
|
|
4113
|
+
}
|
|
3918
4114
|
/** How many operations the spaces applied before `spaceId` list ahead of it in `operations`. */
|
|
3919
4115
|
function operationsBefore(orderedResolutions, spaceId) {
|
|
3920
4116
|
const position = orderedResolutions.findIndex((resolution) => resolution.spaceId === spaceId);
|
|
@@ -4000,6 +4196,7 @@ function mapPlannerError(error, context) {
|
|
|
4000
4196
|
function wrapPlanResult(args) {
|
|
4001
4197
|
return ok({
|
|
4002
4198
|
mode: "plan",
|
|
4199
|
+
...args.permitted.length > 0 ? { permitted: args.permitted } : {},
|
|
4003
4200
|
...ifDefined("databaseStorageHash", args.databaseStorageHash),
|
|
4004
4201
|
...ifDefined("appliedStatements", args.appliedStatements),
|
|
4005
4202
|
...args.subjects,
|
|
@@ -4018,6 +4215,7 @@ function wrapPlanResult(args) {
|
|
|
4018
4215
|
function wrapApplyResult(args) {
|
|
4019
4216
|
return ok({
|
|
4020
4217
|
mode: "apply",
|
|
4218
|
+
...args.permitted.length > 0 ? { permitted: args.permitted } : {},
|
|
4021
4219
|
...ifDefined("databasePoliciesUpdated", args.databasePoliciesUpdated),
|
|
4022
4220
|
...ifDefined("databaseStorageHash", args.databaseStorageHash),
|
|
4023
4221
|
...ifDefined("changedStorageEntities", args.changedStorageEntities),
|
|
@@ -4492,7 +4690,7 @@ async function executeDbUpdate(options) {
|
|
|
4492
4690
|
...ifDefined("onProgress", options.onProgress)
|
|
4493
4691
|
});
|
|
4494
4692
|
}
|
|
4495
|
-
function isRecord$
|
|
4693
|
+
function isRecord$1(value) {
|
|
4496
4694
|
return typeof value === "object" && value !== null;
|
|
4497
4695
|
}
|
|
4498
4696
|
function failedToResolveContractSource(why, fix, meta, cause, diagnostics) {
|
|
@@ -4506,8 +4704,8 @@ function failedToResolveContractSource(why, fix, meta, cause, diagnostics) {
|
|
|
4506
4704
|
}
|
|
4507
4705
|
function diagnosticLocation(diagnostic) {
|
|
4508
4706
|
const sourceId = typeof diagnostic["sourceId"] === "string" ? diagnostic["sourceId"] : void 0;
|
|
4509
|
-
const span = isRecord$
|
|
4510
|
-
const start = span && isRecord$
|
|
4707
|
+
const span = isRecord$1(diagnostic["span"]) ? diagnostic["span"] : void 0;
|
|
4708
|
+
const start = span && isRecord$1(span["start"]) ? span["start"] : void 0;
|
|
4511
4709
|
return {
|
|
4512
4710
|
sourceId,
|
|
4513
4711
|
line: start && typeof start["line"] === "number" ? start["line"] : void 0,
|
|
@@ -4528,7 +4726,7 @@ function formatLocation({ sourceId, line, character }) {
|
|
|
4528
4726
|
}
|
|
4529
4727
|
/** One source diagnostic as a line of text: `<sourceId>:<line>:<column> <code> <message>`. */
|
|
4530
4728
|
function formatSourceDiagnostic(raw) {
|
|
4531
|
-
if (!isRecord$
|
|
4729
|
+
if (!isRecord$1(raw)) return String(raw);
|
|
4532
4730
|
const code = typeof raw["code"] === "string" ? raw["code"] : "diagnostic";
|
|
4533
4731
|
const message = typeof raw["message"] === "string" ? raw["message"] : "";
|
|
4534
4732
|
return [
|
|
@@ -4544,7 +4742,7 @@ function formatSourceDiagnostic(raw) {
|
|
|
4544
4742
|
* yet dotted is wrapped as `CONTRACT.SOURCE_DIAGNOSTIC` and named in the summary.
|
|
4545
4743
|
*/
|
|
4546
4744
|
function sourceDiagnosticToFinding(raw, severity, cwd) {
|
|
4547
|
-
if (!isRecord$
|
|
4745
|
+
if (!isRecord$1(raw)) return void 0;
|
|
4548
4746
|
const code = typeof raw["code"] === "string" ? raw["code"] : "diagnostic";
|
|
4549
4747
|
const message = typeof raw["message"] === "string" ? raw["message"] : "";
|
|
4550
4748
|
const location = displayLocation(diagnosticLocation(raw), cwd);
|
|
@@ -4598,7 +4796,7 @@ function diagnosticLocationSuffix(diagnostic) {
|
|
|
4598
4796
|
function mapDiagnosticsToIssues(diagnostics) {
|
|
4599
4797
|
const issues = [];
|
|
4600
4798
|
for (const raw of diagnostics) {
|
|
4601
|
-
if (!isRecord$
|
|
4799
|
+
if (!isRecord$1(raw)) continue;
|
|
4602
4800
|
const code = typeof raw["code"] === "string" ? raw["code"] : "diagnostic";
|
|
4603
4801
|
const message = typeof raw["message"] === "string" ? raw["message"] : "";
|
|
4604
4802
|
issues.push({
|
|
@@ -4617,15 +4815,15 @@ function failedWith(error) {
|
|
|
4617
4815
|
*/
|
|
4618
4816
|
function validateProviderResult(providerResult, cwd) {
|
|
4619
4817
|
const raw = providerResult;
|
|
4620
|
-
if (!isRecord$
|
|
4818
|
+
if (!isRecord$1(raw) || typeof raw["ok"] !== "boolean") return failedWith(failedToResolveContractSource("Contract source provider returned malformed result shape.", "Ensure contract.source.load resolves to ok(Contract) or notOk({ summary, diagnostics })."));
|
|
4621
4819
|
if (providerResult.ok) {
|
|
4622
4820
|
const value = providerResult.value;
|
|
4623
4821
|
if (value === void 0 || value === null) return failedWith(failedToResolveContractSource("Contract source provider returned malformed success result: missing value.", "Ensure contract.source.load success payload is ok(Contract)."));
|
|
4624
4822
|
return ok(providerResult.value);
|
|
4625
4823
|
}
|
|
4626
4824
|
const failure = providerResult.failure;
|
|
4627
|
-
if (!isRecord$
|
|
4628
|
-
if (failure["diagnostics"].some((diagnostic) => !isRecord$
|
|
4825
|
+
if (!isRecord$1(failure) || typeof failure["summary"] !== "string" || !Array.isArray(failure["diagnostics"])) return failedWith(failedToResolveContractSource("Contract source provider returned malformed failure result: expected summary and diagnostics.", "Ensure contract.source.load failure payload is notOk({ summary, diagnostics, meta? })."));
|
|
4826
|
+
if (failure["diagnostics"].some((diagnostic) => !isRecord$1(diagnostic) || typeof diagnostic["sourceId"] !== "string")) return failedWith(failedToResolveContractSource("Contract source provider returned malformed failure result: each diagnostic must include a string sourceId.", "Include the source filename in each diagnostic returned by contract.source.load."));
|
|
4629
4827
|
return notOk({
|
|
4630
4828
|
error: failedToResolveContractSource(failure["summary"], "Edit the source where each finding points, then run the command again.", {
|
|
4631
4829
|
diagnostics: failure["diagnostics"],
|
|
@@ -4698,7 +4896,7 @@ async function askSource(inputs, reportWarning) {
|
|
|
4698
4896
|
try {
|
|
4699
4897
|
providerResult = await unlessAborted(source.load(sourceContext));
|
|
4700
4898
|
} catch (error) {
|
|
4701
|
-
if (signal.aborted || isRecord$
|
|
4899
|
+
if (signal.aborted || isRecord$1(error) && error["name"] === "AbortError") throw error;
|
|
4702
4900
|
if (isStructuredError(error)) return failedWith(cliErrorFromStructured(error));
|
|
4703
4901
|
return failedWith(failedToResolveContractSource(error instanceof Error ? error.message : String(error), "Ensure contract.source.load resolves to ok(Contract) or returns structured diagnostics.", void 0, error));
|
|
4704
4902
|
}
|
|
@@ -4900,11 +5098,13 @@ async function migrationSource(directory) {
|
|
|
4900
5098
|
throw error;
|
|
4901
5099
|
}
|
|
4902
5100
|
}
|
|
4903
|
-
|
|
5101
|
+
function isPackageModule(module) {
|
|
5102
|
+
return !module.startsWith("./") && !module.startsWith("../") && !module.startsWith("/");
|
|
5103
|
+
}
|
|
4904
5104
|
const NAME_START = /[A-Za-z_$]/;
|
|
4905
5105
|
const NAME_PART = /[\w$]/;
|
|
4906
5106
|
/**
|
|
4907
|
-
* Whether the source calls
|
|
5107
|
+
* Whether the source calls a `placeholder` it imports from a package, by the
|
|
4908
5108
|
* local name it imports it under or through a namespace import. Comments and the text of strings
|
|
4909
5109
|
* are not code, so a `placeholder(` there is not a call.
|
|
4910
5110
|
*/
|
|
@@ -4925,7 +5125,7 @@ function placeholderImports(tokens) {
|
|
|
4925
5125
|
if (token.kind !== "name" || token.text !== "import") return;
|
|
4926
5126
|
const fromAt = tokens.findIndex((each, at) => at > index && each.kind === "name" && each.text === "from");
|
|
4927
5127
|
const module = tokens[fromAt + 1];
|
|
4928
|
-
if (fromAt < 0 || module?.kind !== "string" || !
|
|
5128
|
+
if (fromAt < 0 || module?.kind !== "string" || !isPackageModule(module.text)) return;
|
|
4929
5129
|
const clause = tokens.slice(index + 1, fromAt);
|
|
4930
5130
|
if (clause[0]?.text === "*" && clause[1]?.text === "as" && clause[2] !== void 0) {
|
|
4931
5131
|
namespaces.add(clause[2].text);
|
|
@@ -5069,6 +5269,7 @@ async function executeMigrate(options) {
|
|
|
5069
5269
|
refName: ref?.name
|
|
5070
5270
|
},
|
|
5071
5271
|
storageNameOf: (operation) => familyInstance.storageNameOf(operation),
|
|
5272
|
+
accessChangesOf: (operations) => familyInstance.accessChangesOf(operations),
|
|
5072
5273
|
migrationsDir,
|
|
5073
5274
|
invocation: options.invocation,
|
|
5074
5275
|
readLedger: (spaceId) => familyInstance.readLedger({
|
|
@@ -5088,6 +5289,14 @@ async function executeMigrate(options) {
|
|
|
5088
5289
|
invocation: options.invocation
|
|
5089
5290
|
});
|
|
5090
5291
|
if (!checkedPolicies.ok) return notOk(checkedPolicies.failure);
|
|
5292
|
+
const forbidden = refuseForbiddenMigrations({
|
|
5293
|
+
appSpaceId: aggregate.app.spaceId,
|
|
5294
|
+
checked: checkedPolicies.value,
|
|
5295
|
+
ref,
|
|
5296
|
+
outcomes: planned.value,
|
|
5297
|
+
invocation: options.invocation
|
|
5298
|
+
});
|
|
5299
|
+
if (forbidden !== void 0) return notOk(forbidden);
|
|
5091
5300
|
const policiesToWrite = checkedPolicies.value.toWrite;
|
|
5092
5301
|
const allSpaces = [aggregate.app, ...aggregate.extensions];
|
|
5093
5302
|
const perSpacePlans = /* @__PURE__ */ new Map();
|
|
@@ -5099,8 +5308,20 @@ async function executeMigrate(options) {
|
|
|
5099
5308
|
plansKeptFromRunner.set(space.spaceId, outcome.plan);
|
|
5100
5309
|
continue;
|
|
5101
5310
|
}
|
|
5102
|
-
if (outcome.kind === "never-planned") return notOk(
|
|
5103
|
-
|
|
5311
|
+
if (outcome.kind === "never-planned") return notOk(neverPlannedSpaceFailure(outcome, {
|
|
5312
|
+
appSpaceId: aggregate.app.spaceId,
|
|
5313
|
+
migrationsDir,
|
|
5314
|
+
invocation: options.invocation
|
|
5315
|
+
}));
|
|
5316
|
+
if (outcome.kind === "unreachable") return notOk(unreachableSpaceFailure({
|
|
5317
|
+
spaceId: outcome.spaceId,
|
|
5318
|
+
fromHash: contractHashAtMarker(outcome.liveMarker),
|
|
5319
|
+
targetHash: outcome.targetHash
|
|
5320
|
+
}, {
|
|
5321
|
+
appSpaceId: aggregate.app.spaceId,
|
|
5322
|
+
toArgument: toArgumentFor(target, aggregate.app.graph()),
|
|
5323
|
+
invocation: options.invocation
|
|
5324
|
+
}));
|
|
5104
5325
|
if (outcome.kind === "unsatisfiable") throw noInvariantPathError({
|
|
5105
5326
|
graph: outcome.targetSpace.graph(),
|
|
5106
5327
|
fromHash: outcome.liveHash,
|
|
@@ -5196,6 +5417,49 @@ async function executeMigrate(options) {
|
|
|
5196
5417
|
...ifDefined("databasePoliciesUpdated", policiesToWrite?.differences)
|
|
5197
5418
|
});
|
|
5198
5419
|
}
|
|
5420
|
+
/** The migration of `edges` that holds the operation at `operationIndex` of their joined operations. */
|
|
5421
|
+
function migrationAt(edges, operationIndex) {
|
|
5422
|
+
let start = 0;
|
|
5423
|
+
for (const edge of edges) {
|
|
5424
|
+
if (operationIndex < start + edge.operationCount) return edge.dirName;
|
|
5425
|
+
start += edge.operationCount;
|
|
5426
|
+
}
|
|
5427
|
+
}
|
|
5428
|
+
function recordedOperations(spaceId, entry, subjects) {
|
|
5429
|
+
return subjects.map(({ operationIndex, subject }) => {
|
|
5430
|
+
const operation = entry.displayOps[operationIndex];
|
|
5431
|
+
if (operation === void 0) throw new InternalError(`Unreachable: space "${spaceId}" names operation ${operationIndex}, which its plan does not hold`);
|
|
5432
|
+
return {
|
|
5433
|
+
spaceId,
|
|
5434
|
+
...ifDefined("migration", migrationAt(entry.migrationEdges, operationIndex)),
|
|
5435
|
+
operationId: operation.id,
|
|
5436
|
+
subject: subjectText(subject, {
|
|
5437
|
+
origin: entry.destinationContract,
|
|
5438
|
+
statements: []
|
|
5439
|
+
}),
|
|
5440
|
+
label: operation.label
|
|
5441
|
+
};
|
|
5442
|
+
});
|
|
5443
|
+
}
|
|
5444
|
+
/**
|
|
5445
|
+
* Refuses a run whose pending migrations, in any space, lose data or change who can read or write
|
|
5446
|
+
* data where the run's data protection policy forbids it. `db migrate`, `db migrate --show` and the
|
|
5447
|
+
* control API's `migrate` all decide it here.
|
|
5448
|
+
*/
|
|
5449
|
+
function refuseForbiddenMigrations(args) {
|
|
5450
|
+
const pending = [...args.outcomes].flatMap(([spaceId, outcome]) => outcome.kind === "ok" ? [{
|
|
5451
|
+
spaceId,
|
|
5452
|
+
entry: outcome.plan
|
|
5453
|
+
}] : []);
|
|
5454
|
+
return refuseForbiddenChanges({
|
|
5455
|
+
appSpaceId: args.appSpaceId,
|
|
5456
|
+
command: "db migrate",
|
|
5457
|
+
invocation: args.invocation,
|
|
5458
|
+
forbidden: forbiddingSettingsOfRun(args.checked, args.ref),
|
|
5459
|
+
dataLoss: pending.flatMap(({ spaceId, entry }) => recordedOperations(spaceId, entry, entry.dataLoss)),
|
|
5460
|
+
accessChanges: pending.flatMap(({ spaceId, entry }) => recordedOperations(spaceId, entry, entry.accessChanges))
|
|
5461
|
+
});
|
|
5462
|
+
}
|
|
5199
5463
|
const MIGRATE_POLICY = { allowedOperationClasses: [
|
|
5200
5464
|
"additive",
|
|
5201
5465
|
"widening",
|
|
@@ -5264,7 +5528,7 @@ async function runPolicyOnly(args) {
|
|
|
5264
5528
|
*
|
|
5265
5529
|
* @internal Exported for `executeMigrateShowCommand`.
|
|
5266
5530
|
*/
|
|
5267
|
-
function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker, refName, storageNameOf }) {
|
|
5531
|
+
function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker, refName, storageNameOf, accessChangesOf }) {
|
|
5268
5532
|
const isAppSpace = space.spaceId === aggregate.app.spaceId;
|
|
5269
5533
|
const headRef = requireHeadRef(space);
|
|
5270
5534
|
const graph = space.graph();
|
|
@@ -5327,7 +5591,8 @@ function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker
|
|
|
5327
5591
|
space: targetSpace,
|
|
5328
5592
|
currentMarker: liveMarker,
|
|
5329
5593
|
...isAppSpace && refName !== void 0 ? { refName } : {},
|
|
5330
|
-
storageNameOf
|
|
5594
|
+
storageNameOf,
|
|
5595
|
+
accessChangesOf
|
|
5331
5596
|
});
|
|
5332
5597
|
if (walked.kind === "unreachable") return {
|
|
5333
5598
|
kind: "unreachable",
|
|
@@ -5366,7 +5631,8 @@ function planSpaces(args) {
|
|
|
5366
5631
|
refInvariants: isAppSpace ? appTarget.invariants : void 0,
|
|
5367
5632
|
liveMarker: args.markers.get(space.spaceId) ?? null,
|
|
5368
5633
|
...isAppSpace ? ifDefined("refName", appTarget.refName) : {},
|
|
5369
|
-
storageNameOf: args.storageNameOf
|
|
5634
|
+
storageNameOf: args.storageNameOf,
|
|
5635
|
+
accessChangesOf: args.accessChangesOf
|
|
5370
5636
|
});
|
|
5371
5637
|
return [space.spaceId, outcome];
|
|
5372
5638
|
}));
|
|
@@ -5494,49 +5760,90 @@ function buildSuccess(args) {
|
|
|
5494
5760
|
};
|
|
5495
5761
|
}
|
|
5496
5762
|
/**
|
|
5763
|
+
* `MIGRATION.PATH_UNREACHABLE` for a space with managed storage and no migrations. The application
|
|
5764
|
+
* space is advised to plan its first migration; an extension space's advice is to install a version
|
|
5765
|
+
* of the extension that ships them.
|
|
5766
|
+
*/
|
|
5767
|
+
function neverPlannedSpaceFailure(space, run) {
|
|
5768
|
+
if (space.spaceId === run.appSpaceId) return buildNeverPlannedFailure(space.spaceId, space.targetHash, run.migrationsDir, run.invocation);
|
|
5769
|
+
return errorExtensionNeverPlanned({
|
|
5770
|
+
spaceId: space.spaceId,
|
|
5771
|
+
targetHash: space.targetHash,
|
|
5772
|
+
command: "db migrate",
|
|
5773
|
+
invocation: run.invocation
|
|
5774
|
+
});
|
|
5775
|
+
}
|
|
5776
|
+
/**
|
|
5777
|
+
* `MIGRATION.PATH_UNREACHABLE` for a space with no path from its marker to its target. The
|
|
5778
|
+
* application space is advised to plan the missing migration; an extension space's migrations come
|
|
5779
|
+
* with the extension, so its advice is to install a version that has them. `fromHash` is the
|
|
5780
|
+
* contract the path would start from: the one the marker names, or an offline `--from`.
|
|
5781
|
+
*/
|
|
5782
|
+
function unreachableSpaceFailure(space, run) {
|
|
5783
|
+
if (space.spaceId === run.appSpaceId) return buildPathNotFoundFailure(space.spaceId, space.fromHash, space.targetHash, run.toArgument, run.invocation);
|
|
5784
|
+
return errorExtensionPathUnreachable({
|
|
5785
|
+
spaceId: space.spaceId,
|
|
5786
|
+
fromHash: space.fromHash,
|
|
5787
|
+
targetHash: space.targetHash,
|
|
5788
|
+
command: "db migrate",
|
|
5789
|
+
invocation: run.invocation
|
|
5790
|
+
});
|
|
5791
|
+
}
|
|
5792
|
+
/**
|
|
5793
|
+
* What `--to` takes to name the application space's target: a ref's name, or the hash of a contract
|
|
5794
|
+
* a migration names. `undefined` for the emitted contract, and for a hash no migration names, which
|
|
5795
|
+
* `--to` cannot resolve and which only the emitted contract can be.
|
|
5796
|
+
*/
|
|
5797
|
+
function toArgumentFor(target, appGraph) {
|
|
5798
|
+
if (target === void 0) return void 0;
|
|
5799
|
+
if (target.kind === "ref") return target.ref.name;
|
|
5800
|
+
return isGraphNode(target.hash, appGraph) ? target.hash : void 0;
|
|
5801
|
+
}
|
|
5802
|
+
/**
|
|
5497
5803
|
* Build the `neverPlanned` failure raised when a contract space that
|
|
5498
5804
|
* declares managed storage elements has no on-disk migration graph but
|
|
5499
5805
|
* migrate was asked to reach a target hash. All-external spaces never reach
|
|
5500
5806
|
* this: they resolve declaratively (marker advances to the head ref with
|
|
5501
5807
|
* zero operations). The `why` states only the condition; the recovery
|
|
5502
|
-
* sequence is
|
|
5808
|
+
* sequence is `planThenApply`'s.
|
|
5503
5809
|
*
|
|
5504
5810
|
* @internal Exported for testing only.
|
|
5505
5811
|
*/
|
|
5506
|
-
function buildNeverPlannedFailure(spaceId, targetHash, migrationsDir) {
|
|
5812
|
+
function buildNeverPlannedFailure(spaceId, targetHash, migrationsDir, invocation) {
|
|
5813
|
+
const meta = {
|
|
5814
|
+
spaceId,
|
|
5815
|
+
targetHash,
|
|
5816
|
+
kind: "neverPlanned"
|
|
5817
|
+
};
|
|
5507
5818
|
return errorPathUnreachable({
|
|
5508
5819
|
summary: `No on-disk migrations for contract space "${spaceId}"`,
|
|
5509
5820
|
why: `migrate is replay-only: a contract space that declares managed storage elements must have an authored migration graph on disk. Space "${spaceId}" has no migrations under \`${migrationsDir}/${spaceId}/\` but its head ref targets "${targetHash}".`,
|
|
5510
|
-
meta
|
|
5511
|
-
|
|
5512
|
-
targetHash,
|
|
5513
|
-
kind: "neverPlanned"
|
|
5514
|
-
}
|
|
5515
|
-
});
|
|
5821
|
+
meta
|
|
5822
|
+
}, planThenApply(meta, void 0, invocation));
|
|
5516
5823
|
}
|
|
5517
5824
|
/**
|
|
5518
5825
|
* Build the `pathUnreachable` failure raised when an emitted contract has no
|
|
5519
5826
|
* on-disk migration edge from the current marker to the target. The `why`
|
|
5520
5827
|
* states only the condition (no edge between the two named states, and migrate
|
|
5521
5828
|
* replays edges rather than inventing them); the recovery sequence — plan the
|
|
5522
|
-
* edge, then re-apply — is
|
|
5829
|
+
* edge, then re-apply — is `planThenApply`'s, so the
|
|
5523
5830
|
* two read as one non-redundant plan-then-apply story.
|
|
5524
5831
|
*
|
|
5525
5832
|
* @internal Exported for testing only.
|
|
5526
5833
|
*/
|
|
5527
|
-
function buildPathNotFoundFailure(spaceId,
|
|
5528
|
-
const
|
|
5529
|
-
const
|
|
5834
|
+
function buildPathNotFoundFailure(spaceId, fromHash, targetHash, toArgument, invocation) {
|
|
5835
|
+
const fromText = fromHash === "empty" ? "the empty contract" : `"${fromHash}"`;
|
|
5836
|
+
const meta = {
|
|
5837
|
+
spaceId,
|
|
5838
|
+
fromHash,
|
|
5839
|
+
targetHash,
|
|
5840
|
+
kind: "pathUnreachable"
|
|
5841
|
+
};
|
|
5530
5842
|
return errorPathUnreachable({
|
|
5531
|
-
summary:
|
|
5843
|
+
summary: "Current contract has no planned migration path",
|
|
5532
5844
|
why: `No migration edge connects ${fromText} to the target "${targetHash}" in contract space "${spaceId}". The on-disk migration graph does not join the two, and migrate replays existing edges — it never invents one.`,
|
|
5533
|
-
meta
|
|
5534
|
-
|
|
5535
|
-
fromHash,
|
|
5536
|
-
targetHash,
|
|
5537
|
-
kind: "pathUnreachable"
|
|
5538
|
-
}
|
|
5539
|
-
});
|
|
5845
|
+
meta
|
|
5846
|
+
}, planThenApply(meta, toArgument, invocation));
|
|
5540
5847
|
}
|
|
5541
5848
|
function failedMigrationOnDisk(failed, migrationsDir) {
|
|
5542
5849
|
return {
|
|
@@ -5952,6 +6259,7 @@ var ControlClientImpl = class {
|
|
|
5952
6259
|
}
|
|
5953
6260
|
async emit(options) {
|
|
5954
6261
|
const { onProgress, contractConfig } = options;
|
|
6262
|
+
if (!contractConfig.typesModule) throw errorContractTypesModuleMissing();
|
|
5955
6263
|
this.init();
|
|
5956
6264
|
if (!this.familyInstance) throw new InternalError("Family instance was not initialized. This is a bug.");
|
|
5957
6265
|
onProgress?.({
|
|
@@ -6014,7 +6322,7 @@ var ControlClientImpl = class {
|
|
|
6014
6322
|
...sourceWarningsOf(warnings)
|
|
6015
6323
|
});
|
|
6016
6324
|
}
|
|
6017
|
-
const result = await this.emitArtifacts(deserializedContract,
|
|
6325
|
+
const result = await this.emitArtifacts(deserializedContract, contractConfig.typesModule);
|
|
6018
6326
|
onProgress?.({
|
|
6019
6327
|
action: "emit",
|
|
6020
6328
|
kind: "spanEnd",
|
|
@@ -6046,6 +6354,7 @@ var ControlClientImpl = class {
|
|
|
6046
6354
|
}
|
|
6047
6355
|
}
|
|
6048
6356
|
async renderContractDts(options) {
|
|
6357
|
+
if (!options.typesModule) throw errorContractTypesModuleMissing();
|
|
6049
6358
|
this.init();
|
|
6050
6359
|
if (!this.familyInstance) throw new InternalError("Family instance was not initialized. This is a bug.");
|
|
6051
6360
|
let contract;
|
|
@@ -6060,7 +6369,7 @@ var ControlClientImpl = class {
|
|
|
6060
6369
|
});
|
|
6061
6370
|
}
|
|
6062
6371
|
try {
|
|
6063
|
-
const { contractDts } = await this.emitArtifacts(contract, options.
|
|
6372
|
+
const { contractDts } = await this.emitArtifacts(contract, options.typesModule);
|
|
6064
6373
|
return ok({ contractDts });
|
|
6065
6374
|
} catch (error) {
|
|
6066
6375
|
return notOk({
|
|
@@ -6071,14 +6380,14 @@ var ControlClientImpl = class {
|
|
|
6071
6380
|
});
|
|
6072
6381
|
}
|
|
6073
6382
|
}
|
|
6074
|
-
emitArtifacts(contract,
|
|
6383
|
+
emitArtifacts(contract, typesModule) {
|
|
6075
6384
|
const familyInstance = this.familyInstance;
|
|
6076
6385
|
if (!familyInstance) throw new InternalError("Family instance was not initialized. This is a bug.");
|
|
6077
6386
|
const { contractSerializer } = this.options.target;
|
|
6078
6387
|
return emit(contract, this.stack, this.options.family.emission, {
|
|
6079
6388
|
serializeContract: (c) => contractSerializer.serializeContract(c),
|
|
6080
6389
|
deserializeContract: (json) => familyInstance.deserializeContract(json),
|
|
6081
|
-
|
|
6390
|
+
typesModule,
|
|
6082
6391
|
...ifDefined("shouldPreserveEmpty", contractSerializer.shouldPreserveEmpty),
|
|
6083
6392
|
...ifDefined("sortStorage", contractSerializer.sortStorage),
|
|
6084
6393
|
...ifDefined("supportsNamespaces", this.options.target.supportsNamespaces)
|
|
@@ -6106,111 +6415,6 @@ function queueEmitByOutput(outputJsonPath, action) {
|
|
|
6106
6415
|
function disposeEmitQueue(outputJsonPath) {
|
|
6107
6416
|
emitQueues.delete(outputJsonPath);
|
|
6108
6417
|
}
|
|
6109
|
-
/**
|
|
6110
|
-
* The import root of the project being emitted for, read from its own
|
|
6111
|
-
* manifest.
|
|
6112
|
-
*
|
|
6113
|
-
* Generated files are kept by the application, so every package name in them
|
|
6114
|
-
* has to be one the application can resolve — which means one of its direct
|
|
6115
|
-
* dependencies (ADR 242). The application already states those in
|
|
6116
|
-
* `package.json`, so emission reads them instead of taking a mode from
|
|
6117
|
-
* configuration that could disagree with what is installed.
|
|
6118
|
-
*/
|
|
6119
|
-
const DEPENDENCY_FIELDS = ["dependencies", "devDependencies"];
|
|
6120
|
-
function isRecord$1(value) {
|
|
6121
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6122
|
-
}
|
|
6123
|
-
/** The error codes that mean "no manifest here", as opposed to "cannot read it". */
|
|
6124
|
-
const MANIFEST_ABSENT_CODES = /* @__PURE__ */ new Set(["ENOENT", "ENOTDIR"]);
|
|
6125
|
-
function errorCode(error) {
|
|
6126
|
-
if (!isRecord$1(error)) return void 0;
|
|
6127
|
-
const code = error["code"];
|
|
6128
|
-
return typeof code === "string" ? code : void 0;
|
|
6129
|
-
}
|
|
6130
|
-
/**
|
|
6131
|
-
* The nearest `package.json` at or above `from`, or `undefined` if there is
|
|
6132
|
-
* none. The nearest one wins: a package inside a workspace states its own
|
|
6133
|
-
* dependencies, and the workspace root's are somebody else's.
|
|
6134
|
-
*
|
|
6135
|
-
* @throws {CliStructuredError} when a manifest is there but cannot be used —
|
|
6136
|
-
* unreadable, not valid JSON, or not a JSON object. Only "there is no manifest
|
|
6137
|
-
* at this level" continues the walk up; treating a permissions failure that
|
|
6138
|
-
* way would silently emit against the wrong project's dependencies.
|
|
6139
|
-
*/
|
|
6140
|
-
function nearestManifest(from) {
|
|
6141
|
-
let dir = from;
|
|
6142
|
-
while (true) {
|
|
6143
|
-
const path = join(dir, "package.json");
|
|
6144
|
-
let raw;
|
|
6145
|
-
try {
|
|
6146
|
-
raw = readFileSync(path, "utf8");
|
|
6147
|
-
} catch (cause) {
|
|
6148
|
-
if (!MANIFEST_ABSENT_CODES.has(errorCode(cause) ?? "")) throw errorRuntime("CLI.PROJECT_MANIFEST_UNREADABLE", `Failed to read ${path}`, {
|
|
6149
|
-
why: `\`${path}\` exists but could not be read: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
6150
|
-
fix: `Make \`${path}\` readable, then re-run the command. Emission reads it to decide which package names generated files should import.`,
|
|
6151
|
-
meta: { path },
|
|
6152
|
-
cause
|
|
6153
|
-
});
|
|
6154
|
-
const parent = dirname(dir);
|
|
6155
|
-
if (parent === dir) return void 0;
|
|
6156
|
-
dir = parent;
|
|
6157
|
-
continue;
|
|
6158
|
-
}
|
|
6159
|
-
let parsed;
|
|
6160
|
-
try {
|
|
6161
|
-
parsed = JSON.parse(raw);
|
|
6162
|
-
} catch (cause) {
|
|
6163
|
-
throw errorRuntime("CLI.PROJECT_MANIFEST_INVALID", `Failed to parse ${path}`, {
|
|
6164
|
-
why: `\`${path}\` is not valid JSON: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
6165
|
-
fix: `Fix the JSON syntax in \`${path}\` (a missing comma or unbalanced brace is the most common cause), then re-run the command. Emission reads it to decide which package names generated files should import.`,
|
|
6166
|
-
meta: { path },
|
|
6167
|
-
cause
|
|
6168
|
-
});
|
|
6169
|
-
}
|
|
6170
|
-
if (!isRecord$1(parsed)) throw errorRuntime("CLI.PROJECT_MANIFEST_INVALID", `Failed to read ${path}`, {
|
|
6171
|
-
why: `\`${path}\` is valid JSON but not a JSON object, so it states no dependencies.`,
|
|
6172
|
-
fix: `Make \`${path}\` a JSON object with the usual manifest fields, then re-run the command. Emission reads it to decide which package names generated files should import.`,
|
|
6173
|
-
meta: { path }
|
|
6174
|
-
});
|
|
6175
|
-
return {
|
|
6176
|
-
manifest: parsed,
|
|
6177
|
-
path
|
|
6178
|
-
};
|
|
6179
|
-
}
|
|
6180
|
-
}
|
|
6181
|
-
function declaredDependencies(manifest) {
|
|
6182
|
-
return DEPENDENCY_FIELDS.flatMap((field) => {
|
|
6183
|
-
const value = manifest[field];
|
|
6184
|
-
return isRecord$1(value) ? Object.keys(value) : [];
|
|
6185
|
-
});
|
|
6186
|
-
}
|
|
6187
|
-
/**
|
|
6188
|
-
* The import root for the project at `projectDir`, or for the working
|
|
6189
|
-
* directory when no project directory is known.
|
|
6190
|
-
*
|
|
6191
|
-
* A project with no manifest, or one that names no published package, is on
|
|
6192
|
-
* the internal root — which emits every specifier exactly as authored, so a
|
|
6193
|
-
* project that has not moved to published names is unaffected.
|
|
6194
|
-
*/
|
|
6195
|
-
function projectImportRoot(projectDir) {
|
|
6196
|
-
const nearest = nearestManifest(projectDir === void 0 ? resolve(".") : resolve(projectDir));
|
|
6197
|
-
if (nearest === void 0) return internalImportRoot;
|
|
6198
|
-
try {
|
|
6199
|
-
return importRootForDependencies(declaredDependencies(nearest.manifest));
|
|
6200
|
-
} catch (cause) {
|
|
6201
|
-
if (!(cause instanceof ImportRootError)) throw cause;
|
|
6202
|
-
throw errorRuntime("CLI.PROJECT_MANIFEST_INVALID", `Failed to read ${nearest.path}`, {
|
|
6203
|
-
why: `\`${nearest.path}\` states dependencies emission cannot import from: ${cause.message}.`,
|
|
6204
|
-
fix: `Keep one database facade in \`${nearest.path}\`, then re-run the command. Emission reads it to decide which package names generated files should import.`,
|
|
6205
|
-
meta: { path: nearest.path },
|
|
6206
|
-
cause
|
|
6207
|
-
});
|
|
6208
|
-
}
|
|
6209
|
-
}
|
|
6210
|
-
/** The specifier resolver emission should use for the project at `projectDir`. */
|
|
6211
|
-
function createProjectSpecifierResolver(projectDir) {
|
|
6212
|
-
return createImportSpecifierResolver(projectImportRoot(projectDir));
|
|
6213
|
-
}
|
|
6214
6418
|
function isRecord(value) {
|
|
6215
6419
|
return typeof value === "object" && value !== null;
|
|
6216
6420
|
}
|
|
@@ -6285,33 +6489,35 @@ async function publishContractArtifactPair({ outputJsonPath, outputDtsPath, cont
|
|
|
6285
6489
|
await Promise.allSettled([rm(tempJsonPath, { force: true }), rm(tempDtsPath, { force: true })]);
|
|
6286
6490
|
}
|
|
6287
6491
|
}
|
|
6288
|
-
|
|
6289
|
-
|
|
6290
|
-
|
|
6291
|
-
|
|
6292
|
-
|
|
6293
|
-
if (pkg) packages.add(pkg);
|
|
6294
|
-
}
|
|
6295
|
-
return [...packages];
|
|
6492
|
+
function isCheckedModule(module) {
|
|
6493
|
+
return !module.startsWith("#") && !module.startsWith("./") && !module.startsWith("../");
|
|
6494
|
+
}
|
|
6495
|
+
function packageOf(module) {
|
|
6496
|
+
return module.split("/").slice(0, module.startsWith("@") ? 2 : 1).join("/");
|
|
6296
6497
|
}
|
|
6297
|
-
function
|
|
6298
|
-
|
|
6299
|
-
|
|
6300
|
-
|
|
6301
|
-
|
|
6498
|
+
function errorCode(error) {
|
|
6499
|
+
return typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
6500
|
+
}
|
|
6501
|
+
function isInstalled(pkg, resolve) {
|
|
6502
|
+
try {
|
|
6302
6503
|
resolve.resolve(`${pkg}/package.json`);
|
|
6303
|
-
|
|
6304
|
-
|
|
6504
|
+
return true;
|
|
6505
|
+
} catch (error) {
|
|
6506
|
+
return errorCode(error) !== "MODULE_NOT_FOUND";
|
|
6305
6507
|
}
|
|
6508
|
+
}
|
|
6509
|
+
function validateContractDeps(modules, outputDir) {
|
|
6510
|
+
const resolve$1 = createRequire(resolve(outputDir, "package.json"));
|
|
6511
|
+
const missing = [...new Set(modules.filter(isCheckedModule).map(packageOf))].filter((pkg) => !isInstalled(pkg, resolve$1));
|
|
6306
6512
|
if (missing.length === 0) return { missing };
|
|
6307
6513
|
return {
|
|
6308
6514
|
missing,
|
|
6309
6515
|
warning: [
|
|
6310
6516
|
"contract.d.ts imports types from packages that are not installed:",
|
|
6311
|
-
missing.map((
|
|
6517
|
+
...missing.map((pkg) => ` - ${pkg}`),
|
|
6312
6518
|
"",
|
|
6313
6519
|
"Install them with your package manager:",
|
|
6314
|
-
...missing.map((
|
|
6520
|
+
...missing.map((pkg) => ` ${pkg}`)
|
|
6315
6521
|
].join("\n")
|
|
6316
6522
|
};
|
|
6317
6523
|
}
|
|
@@ -6473,12 +6679,14 @@ function endSpan(onProgress, spanId, outcome) {
|
|
|
6473
6679
|
* @throws {DOMException} `AbortError` if cancelled via `signal`
|
|
6474
6680
|
*/
|
|
6475
6681
|
async function executeContractEmit(options, dependencies = defaultContractEmitDependencies) {
|
|
6476
|
-
const { config, cwd,
|
|
6682
|
+
const { config, cwd, outputPath, signal = new AbortController().signal, onProgress } = options;
|
|
6477
6683
|
const unlessAborted = abortable(signal);
|
|
6478
6684
|
const contractConfig = requireContractConfig(config);
|
|
6479
6685
|
const effectiveOutput = outputPath !== void 0 ? join(outputPath, "contract.json") : contractConfig.output;
|
|
6480
6686
|
if (!effectiveOutput) throw errorContractConfigMissing({ why: "Contract config must have output path. This should not happen if defineConfig() was used." });
|
|
6481
6687
|
requireSourceProvider(contractConfig);
|
|
6688
|
+
const { typesModule } = contractConfig;
|
|
6689
|
+
if (typesModule === void 0) throw errorContractTypesModuleMissing();
|
|
6482
6690
|
let outputPaths;
|
|
6483
6691
|
try {
|
|
6484
6692
|
outputPaths = getEmittedArtifactPaths(effectiveOutput);
|
|
@@ -6521,7 +6729,7 @@ async function executeContractEmit(options, dependencies = defaultContractEmitDe
|
|
|
6521
6729
|
outputJsonPath,
|
|
6522
6730
|
serializeContract,
|
|
6523
6731
|
deserializeContract: (json) => familyInstance.deserializeContract(json),
|
|
6524
|
-
|
|
6732
|
+
typesModule,
|
|
6525
6733
|
...ifDefined("shouldPreserveEmpty", contractSerializer.shouldPreserveEmpty),
|
|
6526
6734
|
...ifDefined("sortStorage", contractSerializer.sortStorage),
|
|
6527
6735
|
...ifDefined("supportsNamespaces", config.target.supportsNamespaces)
|
|
@@ -6548,7 +6756,11 @@ async function executeContractEmit(options, dependencies = defaultContractEmitDe
|
|
|
6548
6756
|
contractDts: emitResult.contractDts,
|
|
6549
6757
|
publicationToken: String(process.hrtime.bigint())
|
|
6550
6758
|
});
|
|
6551
|
-
const validationWarning = validateContractDeps(
|
|
6759
|
+
const validationWarning = validateContractDeps([typesModule, ...[
|
|
6760
|
+
...stack.codecTypeImports ?? [],
|
|
6761
|
+
...stack.queryOperationTypeImports ?? [],
|
|
6762
|
+
...stack.parameterizedOutputTypeImports ?? []
|
|
6763
|
+
].map((spec) => spec.package)], dirname(outputDtsPath)).warning;
|
|
6552
6764
|
return {
|
|
6553
6765
|
storageHash: emitResult.storageHash,
|
|
6554
6766
|
...ifDefined("executionHash", emitResult.executionHash),
|
|
@@ -6586,7 +6798,7 @@ function errorContractDtsRenderFailed(contractJsonPath, failure) {
|
|
|
6586
6798
|
async function renderSnapshotDeclarations(args) {
|
|
6587
6799
|
const rendered = await args.client.renderContractDts({
|
|
6588
6800
|
contract: args.contractJson,
|
|
6589
|
-
|
|
6801
|
+
typesModule: args.typesModule
|
|
6590
6802
|
});
|
|
6591
6803
|
if (!rendered.ok) return notOk(errorContractDtsRenderFailed(args.contractJsonPath, rendered.failure));
|
|
6592
6804
|
return ok(rendered.value.contractDts);
|
|
@@ -6603,25 +6815,19 @@ function computeRefAdvancementName(options) {
|
|
|
6603
6815
|
/**
|
|
6604
6816
|
* Everything `executeRefAdvancement` needs, produced before a command does the
|
|
6605
6817
|
* work that precedes the ref write: the ref name is validated and the
|
|
6606
|
-
* declarations of the contract to snapshot are rendered from its JSON
|
|
6607
|
-
*
|
|
6608
|
-
* read or rendered after the database is touched, so a contract that cannot
|
|
6818
|
+
* declarations of the contract to snapshot are rendered from its JSON. Nothing
|
|
6819
|
+
* is read or rendered after the database is touched, so a contract that cannot
|
|
6609
6820
|
* be snapshotted refuses the command before it changes anything.
|
|
6610
6821
|
*/
|
|
6611
6822
|
async function preflightRefAdvancement(args) {
|
|
6612
6823
|
if (!validateRefName(args.name)) return notOk(errorInvalidRefName(args.name));
|
|
6613
|
-
|
|
6614
|
-
|
|
6615
|
-
resolveImportSpecifier = createProjectSpecifierResolver(args.projectDir);
|
|
6616
|
-
} catch (error) {
|
|
6617
|
-
if (CliStructuredError$1.is(error)) return notOk(error);
|
|
6618
|
-
throw error;
|
|
6619
|
-
}
|
|
6824
|
+
const typesModule = contractTypesModuleOf(args.config);
|
|
6825
|
+
if (!typesModule.ok) return typesModule;
|
|
6620
6826
|
const rendered = await renderSnapshotDeclarations({
|
|
6621
6827
|
client: args.client,
|
|
6622
6828
|
contractJson: args.contractJson,
|
|
6623
6829
|
contractJsonPath: args.contractJsonPath,
|
|
6624
|
-
|
|
6830
|
+
typesModule: typesModule.value
|
|
6625
6831
|
});
|
|
6626
6832
|
if (!rendered.ok) return rendered;
|
|
6627
6833
|
return ok({
|
|
@@ -6933,11 +7139,12 @@ async function executeMigrateShowPlan(options) {
|
|
|
6933
7139
|
}
|
|
6934
7140
|
const loaded = await buildReadAggregate(config, { migrationsDir });
|
|
6935
7141
|
if (!loaded.ok) return notOk(loaded.failure);
|
|
6936
|
-
const { aggregate, contractHash, storageNameOf, markerLocation } = loaded.value;
|
|
7142
|
+
const { aggregate, contractHash, storageNameOf, accessChangesOf, markerLocation } = loaded.value;
|
|
6937
7143
|
const appGraph = aggregate.app.graph();
|
|
6938
7144
|
let targetHash = contractHash;
|
|
6939
7145
|
let refInvariants;
|
|
6940
7146
|
let namedRef;
|
|
7147
|
+
let targetsEmittedContract = !liveTarget;
|
|
6941
7148
|
const refContext = {
|
|
6942
7149
|
graph: appGraph,
|
|
6943
7150
|
refs: allRefs,
|
|
@@ -6947,6 +7154,7 @@ async function executeMigrateShowPlan(options) {
|
|
|
6947
7154
|
const toResult = resolveContractRef$1(options.to, refContext);
|
|
6948
7155
|
if (!toResult.ok) return notOk(toResult.failure);
|
|
6949
7156
|
targetHash = toResult.value.hash;
|
|
7157
|
+
targetsEmittedContract = toResult.value.provenance.kind === "reserved-contract";
|
|
6950
7158
|
if (toResult.value.provenance.kind === "ref") {
|
|
6951
7159
|
const refName = toResult.value.provenance.refName;
|
|
6952
7160
|
const refEntry = allRefs[refName];
|
|
@@ -6980,7 +7188,8 @@ async function executeMigrateShowPlan(options) {
|
|
|
6980
7188
|
invariants: refInvariants,
|
|
6981
7189
|
refName: void 0
|
|
6982
7190
|
},
|
|
6983
|
-
storageNameOf
|
|
7191
|
+
storageNameOf,
|
|
7192
|
+
accessChangesOf
|
|
6984
7193
|
});
|
|
6985
7194
|
let outcomes;
|
|
6986
7195
|
if (options.from !== void 0 && !liveOrigin) {
|
|
@@ -7031,6 +7240,14 @@ async function executeMigrateShowPlan(options) {
|
|
|
7031
7240
|
invocation: options.invocation
|
|
7032
7241
|
});
|
|
7033
7242
|
if (!permitted.ok) return notOk(permitted.failure);
|
|
7243
|
+
const forbidden = refuseForbiddenMigrations({
|
|
7244
|
+
appSpaceId: aggregate.app.spaceId,
|
|
7245
|
+
checked: permitted.value,
|
|
7246
|
+
ref: namedRef,
|
|
7247
|
+
outcomes: checked.value,
|
|
7248
|
+
invocation: options.invocation
|
|
7249
|
+
});
|
|
7250
|
+
if (forbidden !== void 0) return notOk(forbidden);
|
|
7034
7251
|
if (liveOrigin) outcomes = checked.value;
|
|
7035
7252
|
} catch (error) {
|
|
7036
7253
|
return notOk(errorFromCaught(error, (message) => `Failed to read live DB marker: ${message}`, { connection: typeof dbConnection === "string" ? dbConnection : void 0 }));
|
|
@@ -7039,33 +7256,32 @@ async function executeMigrateShowPlan(options) {
|
|
|
7039
7256
|
}
|
|
7040
7257
|
}
|
|
7041
7258
|
const planned = outcomes ?? planSpaces(planInputs());
|
|
7259
|
+
const requestedTarget = targetsEmittedContract ? void 0 : namedRef === void 0 ? {
|
|
7260
|
+
kind: "hash",
|
|
7261
|
+
hash: targetHash
|
|
7262
|
+
} : {
|
|
7263
|
+
kind: "ref",
|
|
7264
|
+
ref: namedRef
|
|
7265
|
+
};
|
|
7042
7266
|
const orderedMigrations = [];
|
|
7043
7267
|
for (const space of spacesInApplyOrder(aggregate)) {
|
|
7044
7268
|
const outcome = planned.get(space.spaceId);
|
|
7045
7269
|
if (outcome === void 0) throw new InternalError(`Unreachable: no planned outcome for space "${space.spaceId}"`);
|
|
7046
7270
|
if (outcome.kind === "at-head") continue;
|
|
7047
|
-
if (outcome.kind === "never-planned") return notOk(
|
|
7048
|
-
|
|
7049
|
-
|
|
7050
|
-
|
|
7051
|
-
|
|
7052
|
-
|
|
7053
|
-
|
|
7054
|
-
|
|
7271
|
+
if (outcome.kind === "never-planned") return notOk(neverPlannedSpaceFailure(outcome, {
|
|
7272
|
+
appSpaceId: aggregate.app.spaceId,
|
|
7273
|
+
migrationsDir,
|
|
7274
|
+
invocation: options.invocation
|
|
7275
|
+
}));
|
|
7276
|
+
if (outcome.kind === "unreachable" || outcome.kind === "marker-outside-graph") return notOk(unreachableSpaceFailure({
|
|
7277
|
+
spaceId: outcome.spaceId,
|
|
7278
|
+
fromHash: outcome.kind === "marker-outside-graph" ? outcome.markerHash : contractHashAtMarker(outcome.liveMarker),
|
|
7279
|
+
targetHash: outcome.targetHash
|
|
7280
|
+
}, {
|
|
7281
|
+
appSpaceId: aggregate.app.spaceId,
|
|
7282
|
+
toArgument: toArgumentFor(requestedTarget, appGraph),
|
|
7283
|
+
invocation: options.invocation
|
|
7055
7284
|
}));
|
|
7056
|
-
if (outcome.kind === "unreachable" || outcome.kind === "marker-outside-graph") {
|
|
7057
|
-
const fromHash = outcome.kind === "marker-outside-graph" ? outcome.markerHash : outcome.liveMarker?.storageHash ?? "empty";
|
|
7058
|
-
return notOk(errorPathUnreachable({
|
|
7059
|
-
summary: `No migration path from ${fromHash.slice(0, 14)} to ${outcome.targetHash.slice(0, 14)} in space "${outcome.spaceId}".`,
|
|
7060
|
-
why: `The migration graph has no path from the from-state to the target in space "${outcome.spaceId}".`,
|
|
7061
|
-
meta: {
|
|
7062
|
-
spaceId: outcome.spaceId,
|
|
7063
|
-
fromHash,
|
|
7064
|
-
targetHash: outcome.targetHash,
|
|
7065
|
-
kind: "pathUnreachable"
|
|
7066
|
-
}
|
|
7067
|
-
}));
|
|
7068
|
-
}
|
|
7069
7285
|
if (outcome.kind === "unsatisfiable") return notOk(errorRuntime("MIGRATION.NO_INVARIANT_PATH", `Missing required invariants for space "${outcome.spaceId}"`, {
|
|
7070
7286
|
why: `The path requires invariants not available on disk: ${outcome.missing.join(", ")}`,
|
|
7071
7287
|
fix: "Add a migration on the path that runs `dataTransform({ invariantId: \"<id>\", … })` for each missing invariant, or retarget the ref to a hash whose path already provides them.",
|
|
@@ -7794,9 +8010,15 @@ async function resolveToForPlan(optionsTo, input) {
|
|
|
7794
8010
|
});
|
|
7795
8011
|
if (!resolution.ok) return resolution;
|
|
7796
8012
|
const { hash, contract } = resolution.value;
|
|
8013
|
+
const { provenance } = refResult.value;
|
|
8014
|
+
const entry = provenance.kind === "ref" ? refs[provenance.refName] : void 0;
|
|
7797
8015
|
return ok({
|
|
7798
8016
|
hash,
|
|
7799
|
-
contract
|
|
8017
|
+
contract,
|
|
8018
|
+
ref: provenance.kind === "ref" && entry !== void 0 ? {
|
|
8019
|
+
name: provenance.refName,
|
|
8020
|
+
...entry
|
|
8021
|
+
} : void 0
|
|
7800
8022
|
});
|
|
7801
8023
|
}
|
|
7802
8024
|
/**
|
|
@@ -7805,6 +8027,10 @@ async function resolveToForPlan(optionsTo, input) {
|
|
|
7805
8027
|
async function executeMigrationNewCommand(options) {
|
|
7806
8028
|
const config = options.config;
|
|
7807
8029
|
const cwd = options.cwd;
|
|
8030
|
+
const migrationModule = migrationModuleOf(config);
|
|
8031
|
+
if (!migrationModule.ok) return migrationModule;
|
|
8032
|
+
const typesModule = contractTypesModuleOf(config);
|
|
8033
|
+
if (!typesModule.ok) return typesModule;
|
|
7808
8034
|
const { migrationsDir, appMigrationsDir, appMigrationsRelative } = resolveMigrationPaths(config, cwd);
|
|
7809
8035
|
const stack = createControlStack(config);
|
|
7810
8036
|
const familyInstance = config.family.create(stack);
|
|
@@ -7905,12 +8131,11 @@ async function executeMigrationNewCommand(options) {
|
|
|
7905
8131
|
config.adapter,
|
|
7906
8132
|
...config.extensions ?? []
|
|
7907
8133
|
]);
|
|
7908
|
-
const resolveSpecifier = createProjectSpecifierResolver(options.projectDir);
|
|
7909
8134
|
const declarations = await renderSnapshotDeclarations({
|
|
7910
8135
|
client: options.client,
|
|
7911
8136
|
contractJson: parsedContract,
|
|
7912
8137
|
contractJsonPath: contractPathAbsolute,
|
|
7913
|
-
|
|
8138
|
+
typesModule: typesModule.value
|
|
7914
8139
|
});
|
|
7915
8140
|
if (!declarations.ok) return notOk(declarations.failure);
|
|
7916
8141
|
await writeMigrationPackage(packageDir, metadata, []);
|
|
@@ -7924,7 +8149,7 @@ async function executeMigrationNewCommand(options) {
|
|
|
7924
8149
|
fromHash,
|
|
7925
8150
|
toHash: toStorageHash,
|
|
7926
8151
|
snapshotsImportPath: snapshotsImportPathFrom(packageDir, migrationsDir)
|
|
7927
|
-
}, APP_SPACE_ID).renderTypeScript(
|
|
8152
|
+
}, APP_SPACE_ID).renderTypeScript(migrationModule.value));
|
|
7928
8153
|
return ok({
|
|
7929
8154
|
ok: true,
|
|
7930
8155
|
dir: relative(cwd, packageDir),
|
|
@@ -7958,7 +8183,7 @@ const EMPTY_ORIGIN = {
|
|
|
7958
8183
|
domain: { namespaces: {} },
|
|
7959
8184
|
storage: { namespaces: {} }
|
|
7960
8185
|
};
|
|
7961
|
-
async function runPlannerLeg(planner, migrations, frameworkComponents, contract, origin, destination, statements, spaceId, ownership, snapshotsImportPath,
|
|
8186
|
+
async function runPlannerLeg(planner, migrations, frameworkComponents, contract, origin, destination, statements, spaceId, ownership, snapshotsImportPath, migrationModule, refused = (conflicts) => errorMigrationPlanningFailed({ conflicts: castAs(conflicts) })) {
|
|
7962
8187
|
const fromContract = origin.kind === "contract" ? origin.contract : null;
|
|
7963
8188
|
const fromSchema = migrations.contractToSchema(fromContract, frameworkComponents);
|
|
7964
8189
|
const plannerResult = planner.plan({
|
|
@@ -8010,7 +8235,7 @@ async function runPlannerLeg(planner, migrations, frameworkComponents, contract,
|
|
|
8010
8235
|
return ok({
|
|
8011
8236
|
plannedOps,
|
|
8012
8237
|
listedOps: listed.filter((op) => op !== void 0),
|
|
8013
|
-
migrationTsContent: plannerResult.plan.renderTypeScript(
|
|
8238
|
+
migrationTsContent: plannerResult.plan.renderTypeScript(migrationModule),
|
|
8014
8239
|
hasPlaceholders,
|
|
8015
8240
|
dataLoss: plannerResult.dataLoss.map(({ operationIndex, subject, loss, label, keepDataAdvice, keepDataEdit }) => ({
|
|
8016
8241
|
operationIndex: position(operationIndex),
|
|
@@ -8020,6 +8245,16 @@ async function runPlannerLeg(planner, migrations, frameworkComponents, contract,
|
|
|
8020
8245
|
...ifDefined("keepDataAdvice", keepDataAdvice),
|
|
8021
8246
|
...ifDefined("keepDataEdit", keepDataEdit)
|
|
8022
8247
|
})),
|
|
8248
|
+
accessChanges: plannerResult.accessChanges.map(({ operationIndex, subject, widens }) => {
|
|
8249
|
+
const label = listed[operationIndex]?.label;
|
|
8250
|
+
if (label === void 0) throw new InternalError(`Unreachable: the planner lists an access change at operation ${operationIndex}, which it did not plan`);
|
|
8251
|
+
return {
|
|
8252
|
+
operationIndex: position(operationIndex),
|
|
8253
|
+
subject,
|
|
8254
|
+
widens,
|
|
8255
|
+
label
|
|
8256
|
+
};
|
|
8257
|
+
}),
|
|
8023
8258
|
appliedStatements: reportAppliedStatements(plannerResult.appliedStatements.map((applied) => ({
|
|
8024
8259
|
...applied,
|
|
8025
8260
|
operationIndexes: applied.operationIndexes.flatMap((index) => {
|
|
@@ -8128,6 +8363,10 @@ async function executeMigrationPlanCommand(options, startTime, callbacks) {
|
|
|
8128
8363
|
async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
8129
8364
|
const config = options.config;
|
|
8130
8365
|
const cwd = options.cwd;
|
|
8366
|
+
const migrationModule = migrationModuleOf(config);
|
|
8367
|
+
if (!migrationModule.ok) return migrationModule;
|
|
8368
|
+
const typesModule = contractTypesModuleOf(config);
|
|
8369
|
+
if (!typesModule.ok) return typesModule;
|
|
8131
8370
|
const { configPath, migrationsDir, appMigrationsDir, appMigrationsRelative } = resolveMigrationPaths(config, cwd);
|
|
8132
8371
|
const contractPathAbsolute = resolveContractPath(config);
|
|
8133
8372
|
const contractPath = relative(cwd, contractPathAbsolute);
|
|
@@ -8217,12 +8456,14 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
8217
8456
|
kind: "contract",
|
|
8218
8457
|
contract: resolvedFrom.fromContract
|
|
8219
8458
|
};
|
|
8459
|
+
let toRef;
|
|
8220
8460
|
if (options.to !== void 0) {
|
|
8221
8461
|
const toResolution = await resolveToForPlan(options.to, { space: resolutionSpace });
|
|
8222
8462
|
if (!toResolution.ok) return notOk(toResolution.failure);
|
|
8223
8463
|
toContract = toResolution.value.contract;
|
|
8224
8464
|
toStorageHash = toResolution.value.hash;
|
|
8225
8465
|
destinationInStore = true;
|
|
8466
|
+
toRef = toResolution.value.ref;
|
|
8226
8467
|
}
|
|
8227
8468
|
let statements = [];
|
|
8228
8469
|
const statementTexts = options.statements ?? [];
|
|
@@ -8246,14 +8487,13 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
8246
8487
|
statements: texts,
|
|
8247
8488
|
resolved
|
|
8248
8489
|
});
|
|
8249
|
-
const resolveImportSpecifier = createProjectSpecifierResolver(options.projectDir);
|
|
8250
8490
|
let destinationDeclarations = null;
|
|
8251
8491
|
if (!destinationInStore && fromHash !== toStorageHash) {
|
|
8252
8492
|
const rendered = await renderSnapshotDeclarations({
|
|
8253
8493
|
client: options.client,
|
|
8254
8494
|
contractJson: emittedContractJson,
|
|
8255
8495
|
contractJsonPath: contractPathAbsolute,
|
|
8256
|
-
|
|
8496
|
+
typesModule: typesModule.value
|
|
8257
8497
|
});
|
|
8258
8498
|
if (!rendered.ok) return notOk(rendered.failure);
|
|
8259
8499
|
destinationDeclarations = rendered.value;
|
|
@@ -8307,6 +8547,31 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
8307
8547
|
});
|
|
8308
8548
|
}
|
|
8309
8549
|
try {
|
|
8550
|
+
const plannedOperations = (leg, entries, planned) => entries.map((entry) => ({
|
|
8551
|
+
spaceId: aggregate.app.spaceId,
|
|
8552
|
+
...ifDefined("operationId", entry.operationIndex === void 0 ? void 0 : leg.listedOps[entry.operationIndex]?.id),
|
|
8553
|
+
subject: subjectText(entry.subject, {
|
|
8554
|
+
origin: fromContract ?? EMPTY_ORIGIN,
|
|
8555
|
+
destination: toContract,
|
|
8556
|
+
statements: planned
|
|
8557
|
+
}),
|
|
8558
|
+
label: entry.label,
|
|
8559
|
+
...ifDefined("loss", entry.loss)
|
|
8560
|
+
}));
|
|
8561
|
+
const refuseForbidden = (leg, planned) => toRef === void 0 ? void 0 : refuseForbiddenChanges({
|
|
8562
|
+
appSpaceId: aggregate.app.spaceId,
|
|
8563
|
+
command: "migration plan",
|
|
8564
|
+
invocation: invocationOf(options),
|
|
8565
|
+
forbidden: forbiddingSettingsOfRef(toRef),
|
|
8566
|
+
dataLoss: plannedOperations(leg, leg.dataLoss, planned),
|
|
8567
|
+
accessChanges: plannedOperations(leg, leg.accessChanges, planned)
|
|
8568
|
+
});
|
|
8569
|
+
const planLeg = async (texts, ...args) => {
|
|
8570
|
+
const leg = await runPlannerLeg(...args);
|
|
8571
|
+
if (!leg.ok) return leg;
|
|
8572
|
+
const refused = refuseForbidden(leg.value, texts.filter(isPlannedStatement));
|
|
8573
|
+
return refused === void 0 ? leg : notOk(refused);
|
|
8574
|
+
};
|
|
8310
8575
|
const planner = migrations.createPlanner(controlAdapter);
|
|
8311
8576
|
const planDestination = {
|
|
8312
8577
|
hash: toStorageHash,
|
|
@@ -8342,12 +8607,12 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
8342
8607
|
const deltaDirName = formatMigrationDirName(deltaTimestamp, options.name ?? "migration");
|
|
8343
8608
|
const baselinePackageDir = join(appMigrationsDir, baselineDirName);
|
|
8344
8609
|
const deltaPackageDir = join(appMigrationsDir, deltaDirName);
|
|
8345
|
-
const baselineLeg = await
|
|
8610
|
+
const baselineLeg = await planLeg([], planner, migrations, frameworkComponents, fromContract, { kind: "baseline" }, {
|
|
8346
8611
|
hash: fromHash,
|
|
8347
8612
|
isEmitted: false
|
|
8348
|
-
}, [], aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(baselinePackageDir, migrationsDir),
|
|
8613
|
+
}, [], aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(baselinePackageDir, migrationsDir), migrationModule.value);
|
|
8349
8614
|
if (!baselineLeg.ok) return baselineLeg;
|
|
8350
|
-
const planBaselineDelta = (texts, resolved) =>
|
|
8615
|
+
const planBaselineDelta = (texts, resolved) => planLeg(texts, planner, migrations, frameworkComponents, aggregate.app.contract(), fromOrigin, planDestination, resolved, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(deltaPackageDir, migrationsDir), migrationModule.value, refusedWith(texts, resolved));
|
|
8351
8616
|
const plannedDelta = fromHash === toStorageHash ? void 0 : await planBaselineDelta(statementTexts, statements);
|
|
8352
8617
|
if (plannedDelta !== void 0 && !plannedDelta.ok) return plannedDelta;
|
|
8353
8618
|
const answered = await answerDataLoss(baselineLeg.value, plannedDelta?.ok === true ? plannedDelta.value : void 0, planBaselineDelta);
|
|
@@ -8465,7 +8730,7 @@ async function executeMigrationPlanCommandInner(options, startTime, callbacks) {
|
|
|
8465
8730
|
}
|
|
8466
8731
|
const timestamp = /* @__PURE__ */ new Date();
|
|
8467
8732
|
const packageDir = join(appMigrationsDir, formatMigrationDirName(timestamp, options.name ?? "migration"));
|
|
8468
|
-
const planDelta = (texts, resolved) =>
|
|
8733
|
+
const planDelta = (texts, resolved) => planLeg(texts, planner, migrations, frameworkComponents, aggregate.app.contract(), fromOrigin, planDestination, resolved, aggregate.app.spaceId, aggregate, snapshotsImportPathFrom(packageDir, migrationsDir), migrationModule.value, refusedWith(texts, resolved));
|
|
8469
8734
|
const plannedDelta = await planDelta(statementTexts, statements);
|
|
8470
8735
|
if (!plannedDelta.ok) return plannedDelta;
|
|
8471
8736
|
const answered = await answerDataLoss(void 0, plannedDelta.value, planDelta);
|
|
@@ -8693,4 +8958,4 @@ async function executeRefListCommand(options) {
|
|
|
8693
8958
|
//#endregion
|
|
8694
8959
|
export { planEverySpace as $, executeMigrationNewCommand as A, labelsText as B, errorPermitPolicyChangeNeedsRef as C, statusForMigrationHash as Ct, executeDbUpdate as D, executeDbSign as E, withWarningFindings as Et, executeRefSetCommand as F, loadContractSource as G, liveMarkerUse as H, findPackageByDirPath as I, looksLikePath as J, loadContractSourceWithStack as K, formatSourceDiagnostic as L, executeRefAdvancement as M, executeRefDeleteCommand as N, executeDbVerify as O, executeRefListCommand as P, migrationSpaceListEntriesFromAggregate as Q, hasMigrationPath as R, enumerateCheckSpaces as S, sourceWarningDiagnostic as St, executeDbInit as T, validateLoadedContract as Tt, loadAggregateIntegrityViolations as U, listRefsByContractHash as V, loadContractRawSafely as W, mapIntegrityViolations as X, mapContractAtError as Y, matchConsents as Z, databasePoliciesInForce as _, runContractSpaceSeedPhase as _t, advanceRefSafely as a, refusePackageCorruptionOnAggregate as at, disposeEmitQueue as b, skippedOperationsText as bt, buildContractSpaceAggregate as c, requireDatabaseForLiveMarkerUse as ct, buildRefAdvancementFields as d, resolveContractRefToSnapshot as dt, preflightRefAdvancement as et, checkSingleTarget as f, resolveFromForPlan as ft, createControlClient as g, retryCommandFor as gt, convertAndDelete as h, resolveToForPlan as ht, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as i, refuseMissingInvariantPath as it, executeMigrationPlanCommand as j, executeMigrateShowPlan as k, buildMigrationSpaceGraphEntries as l, resolveAppTargetPath as lt, contractValidationMeta as m, resolveStatements as mt, NO_REF_ADVANCEMENT as n, refuseContractSpaceIntegrity as nt, appContractStandInFromIdentity as o, refuseUnknownInvariants as ot, computeRefAdvancementName as p, resolveMigrationRef as pt, loadContractSpaceAggregateForCli as q, RECORDED_CONTRACT_REF_FORMS as r, refuseDeclaredExtensionTargetMismatch as rt, appliedHashesFromLedger as s, renamedAndDeleted as st, ALL_CONTRACT_REF_FORMS as t, readMigrationRefs as tt, buildReadAggregate as u, resolveContractRef$1 as ut, declaredSettingsText as v, runMigrationCheck as vt, executeContractEmit as w, toDeclaredExtensionsFromRaw as wt, enrichContract as x, snapshotVerifierFor as xt, deriveStatusEdgeAnnotations as y, runMigrationList as yt, isStatementVerb as z };
|
|
8695
8960
|
|
|
8696
|
-
//# sourceMappingURL=ref-
|
|
8961
|
+
//# sourceMappingURL=ref-PQOM_LTC-lyfzb0MO.mjs.map
|