@contember/cli 2.2.0-alpha.17 → 2.2.0-alpha.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/development/src/commands/tenant/policy/TenantAuthLogCommand.cjs +1 -2
- package/dist/development/src/commands/tenant/policy/TenantAuthLogCommand.cjs.map +1 -1
- package/dist/development/src/commands/tenant/policy/TenantAuthLogCommand.js +2 -3
- package/dist/development/src/commands/tenant/policy/TenantAuthLogCommand.js.map +1 -1
- package/dist/development/src/commands/transfer/ExportCommand.cjs +2 -2
- package/dist/development/src/commands/transfer/ExportCommand.cjs.map +1 -1
- package/dist/development/src/commands/transfer/ImportCommand.cjs +2 -2
- package/dist/development/src/commands/transfer/ImportCommand.cjs.map +1 -1
- package/dist/development/src/lib/VersionChecker.cjs +2 -19
- package/dist/development/src/lib/VersionChecker.cjs.map +1 -1
- package/dist/development/src/lib/VersionChecker.js +2 -2
- package/dist/development/src/lib/VersionChecker.js.map +1 -1
- package/dist/development/src/lib/fs/FileSystem.cjs +36 -4
- package/dist/development/src/lib/fs/FileSystem.cjs.map +1 -1
- package/dist/development/src/lib/fs/FileSystem.js +35 -3
- package/dist/development/src/lib/fs/FileSystem.js.map +1 -1
- package/dist/development/src/lib/migrations/MigrationPrinter.cjs +9 -12
- package/dist/development/src/lib/migrations/MigrationPrinter.cjs.map +1 -1
- package/dist/development/src/lib/migrations/MigrationPrinter.js +10 -13
- package/dist/development/src/lib/migrations/MigrationPrinter.js.map +1 -1
- package/dist/development/src/lib/migrations/MigrationSnapshotFacade.cjs +1 -1
- package/dist/development/src/lib/migrations/MigrationSnapshotFacade.cjs.map +1 -1
- package/dist/development/src/lib/migrations/MigrationSnapshotFacade.js +1 -1
- package/dist/development/src/lib/migrations/MigrationSnapshotFacade.js.map +1 -1
- package/dist/development/src/lib/prompt/prompt.cjs +41 -7
- package/dist/development/src/lib/prompt/prompt.cjs.map +1 -1
- package/dist/development/src/lib/prompt/prompt.js +41 -7
- package/dist/development/src/lib/prompt/prompt.js.map +1 -1
- package/dist/development/src/lib/transfer/DataTransferClient.cjs +2 -2
- package/dist/development/src/lib/transfer/DataTransferClient.cjs.map +1 -1
- package/dist/development/src/lib/versionRange.cjs +276 -0
- package/dist/development/src/lib/versionRange.cjs.map +1 -0
- package/dist/development/src/lib/versionRange.js +276 -0
- package/dist/development/src/lib/versionRange.js.map +1 -0
- package/dist/production/src/commands/tenant/policy/TenantAuthLogCommand.cjs +1 -2
- package/dist/production/src/commands/tenant/policy/TenantAuthLogCommand.cjs.map +1 -1
- package/dist/production/src/commands/tenant/policy/TenantAuthLogCommand.js +2 -3
- package/dist/production/src/commands/tenant/policy/TenantAuthLogCommand.js.map +1 -1
- package/dist/production/src/commands/transfer/ExportCommand.cjs +2 -2
- package/dist/production/src/commands/transfer/ExportCommand.cjs.map +1 -1
- package/dist/production/src/commands/transfer/ImportCommand.cjs +2 -2
- package/dist/production/src/commands/transfer/ImportCommand.cjs.map +1 -1
- package/dist/production/src/lib/VersionChecker.cjs +2 -19
- package/dist/production/src/lib/VersionChecker.cjs.map +1 -1
- package/dist/production/src/lib/VersionChecker.js +2 -2
- package/dist/production/src/lib/VersionChecker.js.map +1 -1
- package/dist/production/src/lib/fs/FileSystem.cjs +36 -4
- package/dist/production/src/lib/fs/FileSystem.cjs.map +1 -1
- package/dist/production/src/lib/fs/FileSystem.js +35 -3
- package/dist/production/src/lib/fs/FileSystem.js.map +1 -1
- package/dist/production/src/lib/migrations/MigrationPrinter.cjs +9 -12
- package/dist/production/src/lib/migrations/MigrationPrinter.cjs.map +1 -1
- package/dist/production/src/lib/migrations/MigrationPrinter.js +10 -13
- package/dist/production/src/lib/migrations/MigrationPrinter.js.map +1 -1
- package/dist/production/src/lib/migrations/MigrationSnapshotFacade.cjs +1 -1
- package/dist/production/src/lib/migrations/MigrationSnapshotFacade.cjs.map +1 -1
- package/dist/production/src/lib/migrations/MigrationSnapshotFacade.js +1 -1
- package/dist/production/src/lib/migrations/MigrationSnapshotFacade.js.map +1 -1
- package/dist/production/src/lib/prompt/prompt.cjs +41 -7
- package/dist/production/src/lib/prompt/prompt.cjs.map +1 -1
- package/dist/production/src/lib/prompt/prompt.js +41 -7
- package/dist/production/src/lib/prompt/prompt.js.map +1 -1
- package/dist/production/src/lib/transfer/DataTransferClient.cjs +2 -2
- package/dist/production/src/lib/transfer/DataTransferClient.cjs.map +1 -1
- package/dist/production/src/lib/versionRange.cjs +276 -0
- package/dist/production/src/lib/versionRange.cjs.map +1 -0
- package/dist/production/src/lib/versionRange.js +276 -0
- package/dist/production/src/lib/versionRange.js.map +1 -0
- package/dist/types/commands/tenant/policy/TenantAuthLogCommand.d.ts.map +1 -1
- package/dist/types/lib/VersionChecker.d.ts.map +1 -1
- package/dist/types/lib/fs/FileSystem.d.ts +5 -0
- package/dist/types/lib/fs/FileSystem.d.ts.map +1 -1
- package/dist/types/lib/migrations/MigrationPrinter.d.ts.map +1 -1
- package/dist/types/lib/prompt/prompt.d.ts +17 -4
- package/dist/types/lib/prompt/prompt.d.ts.map +1 -1
- package/dist/types/lib/versionRange.d.ts +9 -0
- package/dist/types/lib/versionRange.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +17 -21
- package/src/commands/tenant/policy/TenantAuthLogCommand.ts +2 -5
- package/src/lib/VersionChecker.ts +3 -2
- package/src/lib/fs/FileSystem.ts +46 -3
- package/src/lib/migrations/MigrationPrinter.ts +10 -15
- package/src/lib/migrations/MigrationSnapshotFacade.ts +1 -1
- package/src/lib/prompt/prompt.ts +55 -18
- package/src/lib/versionRange.ts +347 -0
- package/tests/cases/unit/MigrationDiffCommand.test.ts +3 -7
- package/tests/cases/unit/MigrationExecutionFacade.test.ts +20 -25
- package/tests/cases/unit/MigrationRebaseCommand.test.ts +1 -3
- package/tests/cases/unit/MigrationSnapshotFacade.test.ts +1 -3
- package/tests/cases/unit/MigrationsValidator.test.ts +2 -2
- package/tests/cases/unit/actions.test.ts +2 -2
- package/tests/cases/unit/deploy.test.ts +4 -28
- package/tests/cases/unit/fileSystem.test.ts +63 -0
- package/tests/cases/unit/fixtures/semverCorpus.json +1157 -0
- package/tests/cases/unit/project.test.ts +2 -2
- package/tests/cases/unit/prompt.test.ts +64 -0
- package/tests/cases/unit/transfer.test.ts +1 -3
- package/tests/cases/unit/versionRange.test.ts +57 -0
- package/dist/development/src/lib/prompt/prompt.internal.cjs +0 -21
- package/dist/development/src/lib/prompt/prompt.internal.cjs.map +0 -1
- package/dist/development/src/lib/prompt/prompt.internal.js +0 -21
- package/dist/development/src/lib/prompt/prompt.internal.js.map +0 -1
- package/dist/production/src/lib/prompt/prompt.internal.cjs +0 -21
- package/dist/production/src/lib/prompt/prompt.internal.cjs.map +0 -1
- package/dist/production/src/lib/prompt/prompt.internal.js +0 -21
- package/dist/production/src/lib/prompt/prompt.internal.js.map +0 -1
- package/dist/types/lib/prompt/prompt.internal.d.ts +0 -37
- package/dist/types/lib/prompt/prompt.internal.d.ts.map +0 -1
- package/dist/types/lib/prompt/prompt.test.d.ts +0 -2
- package/dist/types/lib/prompt/prompt.test.d.ts.map +0 -1
- package/src/lib/prompt/prompt.internal.ts +0 -69
- package/src/lib/prompt/prompt.test.ts +0 -100
- package/types/chalk-table/index.d.ts +0 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MigrationPrinter.cjs","sources":["../../../../../../packages/cli/src/lib/migrations/MigrationPrinter.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"MigrationPrinter.cjs","sources":["../../../../../../packages/cli/src/lib/migrations/MigrationPrinter.ts"],"sourcesContent":["import { Schema } from '@contember/schema'\nimport { AnyMigrationStatus, Migration, MigrationDescriber, MigrationState } from '@contember/migrations-client'\nimport { emptyDatabaseMetadata } from '@contember/database'\nimport { escapeTerminalText, formatTable, Output, style } from '@contember/cli-common'\nimport { assertNever } from '../assertNever.js'\n\nexport interface MigrationDescriptionItem {\n\tmodification: string\n\tdescription: string\n\tisDestructive: boolean\n\tfailureWarning: string | null\n\tsql: string\n}\n\nexport interface MigrationStatusRow {\n\tstatus: string\n\tmigration: string\n\tinfo: string\n}\n\nexport const migrationStatusColumns: { field: keyof MigrationStatusRow & string; name: string }[] = [\n\t{ field: 'status', name: 'Status' },\n\t{ field: 'migration', name: 'Migration' },\n\t{ field: 'info', name: 'Info' },\n]\n\nexport class MigrationPrinter {\n\tconstructor(\n\t\tprivate readonly migrationsDescriber: MigrationDescriber,\n\t\tprivate readonly output: Output = new Output(),\n\t) {\n\t}\n\n\t/** The structured description of a migration — the data behind `migrations describe`. */\n\tdescribeMigration = (schema: Schema, migration: Migration): MigrationDescriptionItem[] => {\n\t\treturn this.migrationsDescriber.describeModifications(schema, migration).map(({ modification, getSql, description }) => ({\n\t\t\tmodification: modification.modification,\n\t\t\tdescription: description.message,\n\t\t\tisDestructive: description.isDestructive ?? false,\n\t\t\tfailureWarning: description.failureWarning ?? null,\n\t\t\tsql: getSql({\n\t\t\t\tsystemSchema: 'system',\n\t\t\t\tdatabaseMetadata: emptyDatabaseMetadata,\n\t\t\t\tinvalidateDatabaseMetadata: () => null,\n\t\t\t}),\n\t\t}))\n\t}\n\n\tformatMigrationDescription = (items: MigrationDescriptionItem[], options: { sqlOnly?: boolean; noSql?: boolean } = {}): string => {\n\t\tif (options.sqlOnly) {\n\t\t\treturn items.map(it => sanitizeMultiline(it.sql.trim())).filter(it => it !== '').join('\\n')\n\t\t}\n\t\treturn items.map(item => {\n\t\t\tconst lines = [style(item.isDestructive ? 'red' : 'blue', `${sanitizeMultiline(item.description)} [${sanitizeMultiline(item.modification)}]`)]\n\t\t\tif (item.failureWarning) {\n\t\t\t\tlines.push(style('bgWhite', style('redBright', sanitizeMultiline(item.failureWarning))))\n\t\t\t}\n\t\t\tif (!options.noSql) {\n\t\t\t\tlines.push(item.sql.trim() ? sanitizeMultiline(item.sql) : 'No sql to execute')\n\t\t\t}\n\t\t\t// the body is indented under its header, as console.group used to render it\n\t\t\treturn lines.map((line, index) => index === 0 ? line : indent(line)).join('\\n')\n\t\t}).join('\\n')\n\t}\n\n\t/** Prints the description as a diagnostic — a preamble of what a command is about to do. */\n\tprintMigrationDescription = (\n\t\tschema: Schema,\n\t\tmigration: Migration,\n\t\toptions: { sqlOnly?: boolean; noSql?: boolean },\n\t) => {\n\t\tconst description = this.formatMigrationDescription(this.describeMigration(schema, migration), options)\n\t\tif (description !== '') {\n\t\t\tfor (const line of description.split('\\n')) {\n\t\t\t\tthis.output.info(line)\n\t\t\t}\n\t\t}\n\t}\n\n\tstatusRows = (migrations: AnyMigrationStatus[]): MigrationStatusRow[] => {\n\t\treturn migrations.map((it): MigrationStatusRow => {\n\t\t\tswitch (it.state) {\n\t\t\t\tcase MigrationState.EXECUTED_ERROR:\n\t\t\t\t\treturn { status: style(['bgRedBright', 'white'], 'ERROR'), migration: it.name, info: it.errorMessage }\n\t\t\t\tcase MigrationState.EXECUTED_OK:\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: style(['bgGreen', 'blackBright'], 'Executed'),\n\t\t\t\t\t\tmigration: it.name,\n\t\t\t\t\t\tinfo: `Executed at ${it.executedMigration.executedAt.toISOString()}`,\n\t\t\t\t\t}\n\t\t\t\tcase MigrationState.EXECUTED_MISSING:\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: style(['bgRedBright', 'white'], 'ERROR'),\n\t\t\t\t\t\tmigration: it.name,\n\t\t\t\t\t\tinfo: it.errorMessage,\n\t\t\t\t\t}\n\t\t\t\tcase MigrationState.TO_EXECUTE_OK:\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: style(['bgBlueBright', 'white'], 'Not executed'),\n\t\t\t\t\t\tmigration: it.name,\n\t\t\t\t\t\tinfo: 'Will be executed during next deploy',\n\t\t\t\t\t}\n\t\t\t\tcase MigrationState.TO_EXECUTE_ERROR:\n\t\t\t\t\treturn { status: style(['bgRedBright', 'white'], 'ERROR'), migration: it.name, info: it.errorMessage }\n\t\t\t\tcase MigrationState.SKIP_EMPTY:\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: style(['bgYellow', 'white'], 'Skip'),\n\t\t\t\t\t\tmigration: it.name,\n\t\t\t\t\t\tinfo: `Skipped because empty`,\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn assertNever(it)\n\t\t\t}\n\t\t})\n\t}\n\n\tformatStatusTable = (migrations: AnyMigrationStatus[]): string => {\n\t\treturn formatTable(migrationStatusColumns, this.statusRows(migrations))\n\t}\n}\n\nconst indent = (text: string): string => text.split('\\n').map(line => ` ${line}`).join('\\n')\nconst sanitizeMultiline = (text: string): string => text.split('\\n').map(escapeTerminalText).join('\\n')\n"],"names":["Output","emptyDatabaseMetadata","style","MigrationState","assertNever","formatTable","escapeTerminalText"],"mappings":";;;;;;;;;AAoBO,MAAM,yBAAuF;AAAA,EACnG,EAAE,OAAO,UAAU,MAAM,SAAA;AAAA,EACzB,EAAE,OAAO,aAAa,MAAM,YAAA;AAAA,EAC5B,EAAE,OAAO,QAAQ,MAAM,OAAA;AACxB;AAEO,MAAM,iBAAiB;AAAA,EAC7B,YACkB,qBACA,SAAiB,IAAIA,UAAAA,UACrC;AAFgB,SAAA,sBAAA;AACA,SAAA,SAAA;AAKlB,kBAAA,MAAA,qBAAoB,CAAC,QAAgB,cAAqD;AACzF,aAAO,KAAK,oBAAoB,sBAAsB,QAAQ,SAAS,EAAE,IAAI,CAAC,EAAE,cAAc,QAAQ,YAAA,OAAmB;AAAA,QACxH,cAAc,aAAa;AAAA,QAC3B,aAAa,YAAY;AAAA,QACzB,eAAe,YAAY,iBAAiB;AAAA,QAC5C,gBAAgB,YAAY,kBAAkB;AAAA,QAC9C,KAAK,OAAO;AAAA,UACX,cAAc;AAAA,UACd,kBAAkBC,SAAAA;AAAAA,UAClB,4BAA4B,MAAM;AAAA,QAAA,CAClC;AAAA,MAAA,EACA;AAAA,IACH,CAAA;AAEA,kBAAA,MAAA,8BAA6B,CAAC,OAAmC,UA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AyB,KAAK,MAAM,IAAI,EAAE,IAAIC,UAAAA,kBAAkB,EAAE,KAAK,IAAI;;;"}
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import chalk from "chalk";
|
|
2
1
|
import { MigrationState } from "@contember/migrations-client";
|
|
3
2
|
import { emptyDatabaseMetadata } from "@contember/database";
|
|
4
|
-
import
|
|
5
|
-
import { Output, escapeTerminalText } from "@contember/cli-common";
|
|
3
|
+
import { Output, style, formatTable, escapeTerminalText } from "@contember/cli-common";
|
|
6
4
|
import { assertNever } from "../assertNever.js";
|
|
7
5
|
var __defProp = Object.defineProperty;
|
|
8
6
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
@@ -34,10 +32,9 @@ class MigrationPrinter {
|
|
|
34
32
|
return items.map((it) => sanitizeMultiline(it.sql.trim())).filter((it) => it !== "").join("\n");
|
|
35
33
|
}
|
|
36
34
|
return items.map((item) => {
|
|
37
|
-
const
|
|
38
|
-
const lines = [color(`${sanitizeMultiline(item.description)} [${sanitizeMultiline(item.modification)}]`)];
|
|
35
|
+
const lines = [style(item.isDestructive ? "red" : "blue", `${sanitizeMultiline(item.description)} [${sanitizeMultiline(item.modification)}]`)];
|
|
39
36
|
if (item.failureWarning) {
|
|
40
|
-
lines.push(
|
|
37
|
+
lines.push(style("bgWhite", style("redBright", sanitizeMultiline(item.failureWarning))));
|
|
41
38
|
}
|
|
42
39
|
if (!options.noSql) {
|
|
43
40
|
lines.push(item.sql.trim() ? sanitizeMultiline(item.sql) : "No sql to execute");
|
|
@@ -57,30 +54,30 @@ class MigrationPrinter {
|
|
|
57
54
|
return migrations.map((it) => {
|
|
58
55
|
switch (it.state) {
|
|
59
56
|
case MigrationState.EXECUTED_ERROR:
|
|
60
|
-
return { status:
|
|
57
|
+
return { status: style(["bgRedBright", "white"], "ERROR"), migration: it.name, info: it.errorMessage };
|
|
61
58
|
case MigrationState.EXECUTED_OK:
|
|
62
59
|
return {
|
|
63
|
-
status:
|
|
60
|
+
status: style(["bgGreen", "blackBright"], "Executed"),
|
|
64
61
|
migration: it.name,
|
|
65
62
|
info: `Executed at ${it.executedMigration.executedAt.toISOString()}`
|
|
66
63
|
};
|
|
67
64
|
case MigrationState.EXECUTED_MISSING:
|
|
68
65
|
return {
|
|
69
|
-
status:
|
|
66
|
+
status: style(["bgRedBright", "white"], "ERROR"),
|
|
70
67
|
migration: it.name,
|
|
71
68
|
info: it.errorMessage
|
|
72
69
|
};
|
|
73
70
|
case MigrationState.TO_EXECUTE_OK:
|
|
74
71
|
return {
|
|
75
|
-
status:
|
|
72
|
+
status: style(["bgBlueBright", "white"], "Not executed"),
|
|
76
73
|
migration: it.name,
|
|
77
74
|
info: "Will be executed during next deploy"
|
|
78
75
|
};
|
|
79
76
|
case MigrationState.TO_EXECUTE_ERROR:
|
|
80
|
-
return { status:
|
|
77
|
+
return { status: style(["bgRedBright", "white"], "ERROR"), migration: it.name, info: it.errorMessage };
|
|
81
78
|
case MigrationState.SKIP_EMPTY:
|
|
82
79
|
return {
|
|
83
|
-
status:
|
|
80
|
+
status: style(["bgYellow", "white"], "Skip"),
|
|
84
81
|
migration: it.name,
|
|
85
82
|
info: `Skipped because empty`
|
|
86
83
|
};
|
|
@@ -90,7 +87,7 @@ class MigrationPrinter {
|
|
|
90
87
|
});
|
|
91
88
|
});
|
|
92
89
|
__publicField(this, "formatStatusTable", (migrations) => {
|
|
93
|
-
return
|
|
90
|
+
return formatTable(migrationStatusColumns, this.statusRows(migrations));
|
|
94
91
|
});
|
|
95
92
|
}
|
|
96
93
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MigrationPrinter.js","sources":["../../../../../../packages/cli/src/lib/migrations/MigrationPrinter.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"MigrationPrinter.js","sources":["../../../../../../packages/cli/src/lib/migrations/MigrationPrinter.ts"],"sourcesContent":["import { Schema } from '@contember/schema'\nimport { AnyMigrationStatus, Migration, MigrationDescriber, MigrationState } from '@contember/migrations-client'\nimport { emptyDatabaseMetadata } from '@contember/database'\nimport { escapeTerminalText, formatTable, Output, style } from '@contember/cli-common'\nimport { assertNever } from '../assertNever.js'\n\nexport interface MigrationDescriptionItem {\n\tmodification: string\n\tdescription: string\n\tisDestructive: boolean\n\tfailureWarning: string | null\n\tsql: string\n}\n\nexport interface MigrationStatusRow {\n\tstatus: string\n\tmigration: string\n\tinfo: string\n}\n\nexport const migrationStatusColumns: { field: keyof MigrationStatusRow & string; name: string }[] = [\n\t{ field: 'status', name: 'Status' },\n\t{ field: 'migration', name: 'Migration' },\n\t{ field: 'info', name: 'Info' },\n]\n\nexport class MigrationPrinter {\n\tconstructor(\n\t\tprivate readonly migrationsDescriber: MigrationDescriber,\n\t\tprivate readonly output: Output = new Output(),\n\t) {\n\t}\n\n\t/** The structured description of a migration — the data behind `migrations describe`. */\n\tdescribeMigration = (schema: Schema, migration: Migration): MigrationDescriptionItem[] => {\n\t\treturn this.migrationsDescriber.describeModifications(schema, migration).map(({ modification, getSql, description }) => ({\n\t\t\tmodification: modification.modification,\n\t\t\tdescription: description.message,\n\t\t\tisDestructive: description.isDestructive ?? false,\n\t\t\tfailureWarning: description.failureWarning ?? null,\n\t\t\tsql: getSql({\n\t\t\t\tsystemSchema: 'system',\n\t\t\t\tdatabaseMetadata: emptyDatabaseMetadata,\n\t\t\t\tinvalidateDatabaseMetadata: () => null,\n\t\t\t}),\n\t\t}))\n\t}\n\n\tformatMigrationDescription = (items: MigrationDescriptionItem[], options: { sqlOnly?: boolean; noSql?: boolean } = {}): string => {\n\t\tif (options.sqlOnly) {\n\t\t\treturn items.map(it => sanitizeMultiline(it.sql.trim())).filter(it => it !== '').join('\\n')\n\t\t}\n\t\treturn items.map(item => {\n\t\t\tconst lines = [style(item.isDestructive ? 'red' : 'blue', `${sanitizeMultiline(item.description)} [${sanitizeMultiline(item.modification)}]`)]\n\t\t\tif (item.failureWarning) {\n\t\t\t\tlines.push(style('bgWhite', style('redBright', sanitizeMultiline(item.failureWarning))))\n\t\t\t}\n\t\t\tif (!options.noSql) {\n\t\t\t\tlines.push(item.sql.trim() ? sanitizeMultiline(item.sql) : 'No sql to execute')\n\t\t\t}\n\t\t\t// the body is indented under its header, as console.group used to render it\n\t\t\treturn lines.map((line, index) => index === 0 ? line : indent(line)).join('\\n')\n\t\t}).join('\\n')\n\t}\n\n\t/** Prints the description as a diagnostic — a preamble of what a command is about to do. */\n\tprintMigrationDescription = (\n\t\tschema: Schema,\n\t\tmigration: Migration,\n\t\toptions: { sqlOnly?: boolean; noSql?: boolean },\n\t) => {\n\t\tconst description = this.formatMigrationDescription(this.describeMigration(schema, migration), options)\n\t\tif (description !== '') {\n\t\t\tfor (const line of description.split('\\n')) {\n\t\t\t\tthis.output.info(line)\n\t\t\t}\n\t\t}\n\t}\n\n\tstatusRows = (migrations: AnyMigrationStatus[]): MigrationStatusRow[] => {\n\t\treturn migrations.map((it): MigrationStatusRow => {\n\t\t\tswitch (it.state) {\n\t\t\t\tcase MigrationState.EXECUTED_ERROR:\n\t\t\t\t\treturn { status: style(['bgRedBright', 'white'], 'ERROR'), migration: it.name, info: it.errorMessage }\n\t\t\t\tcase MigrationState.EXECUTED_OK:\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: style(['bgGreen', 'blackBright'], 'Executed'),\n\t\t\t\t\t\tmigration: it.name,\n\t\t\t\t\t\tinfo: `Executed at ${it.executedMigration.executedAt.toISOString()}`,\n\t\t\t\t\t}\n\t\t\t\tcase MigrationState.EXECUTED_MISSING:\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: style(['bgRedBright', 'white'], 'ERROR'),\n\t\t\t\t\t\tmigration: it.name,\n\t\t\t\t\t\tinfo: it.errorMessage,\n\t\t\t\t\t}\n\t\t\t\tcase MigrationState.TO_EXECUTE_OK:\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: style(['bgBlueBright', 'white'], 'Not executed'),\n\t\t\t\t\t\tmigration: it.name,\n\t\t\t\t\t\tinfo: 'Will be executed during next deploy',\n\t\t\t\t\t}\n\t\t\t\tcase MigrationState.TO_EXECUTE_ERROR:\n\t\t\t\t\treturn { status: style(['bgRedBright', 'white'], 'ERROR'), migration: it.name, info: it.errorMessage }\n\t\t\t\tcase MigrationState.SKIP_EMPTY:\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: style(['bgYellow', 'white'], 'Skip'),\n\t\t\t\t\t\tmigration: it.name,\n\t\t\t\t\t\tinfo: `Skipped because empty`,\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn assertNever(it)\n\t\t\t}\n\t\t})\n\t}\n\n\tformatStatusTable = (migrations: AnyMigrationStatus[]): string => {\n\t\treturn formatTable(migrationStatusColumns, this.statusRows(migrations))\n\t}\n}\n\nconst indent = (text: string): string => text.split('\\n').map(line => ` ${line}`).join('\\n')\nconst sanitizeMultiline = (text: string): string => text.split('\\n').map(escapeTerminalText).join('\\n')\n"],"names":[],"mappings":";;;;;;;AAoBO,MAAM,yBAAuF;AAAA,EACnG,EAAE,OAAO,UAAU,MAAM,SAAA;AAAA,EACzB,EAAE,OAAO,aAAa,MAAM,YAAA;AAAA,EAC5B,EAAE,OAAO,QAAQ,MAAM,OAAA;AACxB;AAEO,MAAM,iBAAiB;AAAA,EAC7B,YACkB,qBACA,SAAiB,IAAI,UACrC;AAFgB,SAAA,sBAAA;AACA,SAAA,SAAA;AAKlB,kBAAA,MAAA,qBAAoB,CAAC,QAAgB,cAAqD;AACzF,aAAO,KAAK,oBAAoB,sBAAsB,QAAQ,SAAS,EAAE,IAAI,CAAC,EAAE,cAAc,QAAQ,YAAA,OAAmB;AAAA,QACxH,cAAc,aAAa;AAAA,QAC3B,aAAa,YAAY;AAAA,QACzB,eAAe,YAAY,iBAAiB;AAAA,QAC5C,gBAAgB,YAAY,kBAAkB;AAAA,QAC9C,KAAK,OAAO;AAAA,UACX,cAAc;AAAA,UAC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SAAyB,KAAK,MAAM,IAAI,EAAE,IAAI,kBAAkB,EAAE,KAAK,IAAI;"}
|
|
@@ -108,7 +108,7 @@ class MigrationSnapshotFacade {
|
|
|
108
108
|
snapshotSchema = { ...snapshotSchema, ...await this.schemaStateManager.readState() };
|
|
109
109
|
}
|
|
110
110
|
const differences = schemaUtils.deepCompare(replaySchema, snapshotSchema, [], (path) => {
|
|
111
|
-
if (path[0] === "model" && path[1] === "entities" && (path[3] === "unique" || path[3] === "index")) {
|
|
111
|
+
if (path[0] === "model" && path[1] === "entities" && (path[3] === "unique" || path[3] === "index" || path[3] === "checks")) {
|
|
112
112
|
return (a, b) => schemaUtils.compareArraysIgnoreOrder(a, b, path);
|
|
113
113
|
}
|
|
114
114
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MigrationSnapshotFacade.cjs","sources":["../../../../../../packages/cli/src/lib/migrations/MigrationSnapshotFacade.ts"],"sourcesContent":["import { compareArraysIgnoreOrder, deepCompare, emptySchema } from '@contember/schema-utils'\nimport {\n\tcalculateMigrationChecksum,\n\tCoveredMigration,\n\tExecutedMigrationInfo,\n\tisSchemaMigration,\n\tMigrationContent,\n\tMigrationsResolver,\n\tSchemaDiffer,\n\tSchemaMigrator,\n\tSchemaStateManager,\n\tSchemaVersionBuilder,\n\tSnapshotFile,\n\tSnapshotInput,\n\tSnapshotManager,\n\tVERSION_LATEST,\n} from '@contember/migrations-client'\nimport { CliError, ExitCode, Output } from '@contember/cli-common'\n\nexport class MigrationSnapshotFacade {\n\tconstructor(\n\t\tprivate readonly migrationsResolver: MigrationsResolver,\n\t\tprivate readonly schemaVersionBuilder: SchemaVersionBuilder,\n\t\tprivate readonly schemaDiffer: SchemaDiffer,\n\t\tprivate readonly schemaMigrator: SchemaMigrator,\n\t\tprivate readonly schemaStateManager: SchemaStateManager,\n\t\tprivate readonly snapshotManager: SnapshotManager,\n\t\tprivate readonly output: Output = new Output(),\n\t) {\n\t}\n\n\t/** Builds a snapshot in memory without changing the filesystem. */\n\tasync prepare(): Promise<SnapshotFile> {\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tif (files.length === 0) {\n\t\t\tthrow new CliError('No migrations to snapshot', { code: 'MIGRATIONS_NOT_FOUND', exitCode: ExitCode.NotFound })\n\t\t}\n\t\tconst stateMode = await this.schemaStateManager.isStateMode()\n\t\tconst version = files[files.length - 1].version\n\n\t\t// Replay all schema migrations into a single schema. In state mode the non-model parts\n\t\t// (acl/validation/actions/settings) live in state/ and are skipped here; otherwise they\n\t\t// are part of the migration history and must be included in the collapsed modifications.\n\t\tconst collapsedSchema = await this.schemaVersionBuilder.buildSchemaAdvanced(emptySchema, () => true)\n\t\tconst modifications = this.schemaDiffer.diffSchemas(emptySchema, collapsedSchema, {\n\t\t\tskipNonModelDiffers: stateMode,\n\t\t})\n\n\t\tconst covers: CoveredMigration[] = []\n\t\tconst contentMigrations: string[] = []\n\t\tfor (const file of files) {\n\t\t\tconst content = await file.getContent()\n\t\t\tconst schema = isSchemaMigration(content)\n\t\t\tcovers.push({\n\t\t\t\tversion: file.version,\n\t\t\t\tname: file.name,\n\t\t\t\ttype: schema ? 'schema' : 'content',\n\t\t\t\tchecksum: schema ? calculateMigrationChecksum(content) : null,\n\t\t\t})\n\t\t\tif (!schema) {\n\t\t\t\tcontentMigrations.push(file.version)\n\t\t\t}\n\t\t}\n\n\t\tconst snapshot: SnapshotFile = {\n\t\t\tversion,\n\t\t\tstateMode,\n\t\t\tsnapshot: { formatVersion: VERSION_LATEST, modifications },\n\t\t\tcovers,\n\t\t\tcontentMigrations,\n\t\t}\n\t\treturn snapshot\n\t}\n\n\tasync write(snapshot: SnapshotFile): Promise<void> {\n\t\tawait this.snapshotManager.write(snapshot)\n\t}\n\n\t/**\n\t * Returns the snapshot when it can safely bootstrap the current project, else null.\n\t * The snapshot is only usable on an empty project (no executed migrations) and only when\n\t * none of the covered migration files have changed. A present-but-stale snapshot is skipped\n\t * with a warning, falling back to a full replay.\n\t */\n\tasync getUsableSnapshot(executedMigrations: ExecutedMigrationInfo[]): Promise<SnapshotFile | null> {\n\t\tif (!(await this.snapshotManager.exists())) {\n\t\t\treturn null\n\t\t}\n\t\tif (executedMigrations.length > 0) {\n\t\t\treturn null\n\t\t}\n\t\tconst snapshot = await this.snapshotManager.read()\n\t\tconst stale = await this.findStaleness(snapshot)\n\t\tif (stale) {\n\t\t\tthis.output.warn(`Ignoring snapshot: ${stale}. Run \"migrations snapshot\" to regenerate it.`)\n\t\t\treturn null\n\t\t}\n\t\treturn snapshot\n\t}\n\n\t/** Maps a snapshot to the GraphQL SnapshotInput; covered migrations are sent as Migration inputs. */\n\tasync buildSnapshotInput(snapshot: SnapshotFile): Promise<SnapshotInput> {\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tconst byVersion = new Map(files.map(it => [it.version, it]))\n\t\tconst covers: unknown[] = []\n\t\tfor (const covered of snapshot.covers) {\n\t\t\tconst file = byVersion.get(covered.version)\n\t\t\tif (!file) {\n\t\t\t\tthrow new CliError(`Snapshot covers missing migration ${covered.name}`, { code: 'SNAPSHOT_COVER_MISSING', exitCode: ExitCode.NotFound })\n\t\t\t}\n\t\t\tcovers.push(migrationContentToInput(covered.version, covered.name, await file.getContent()))\n\t\t}\n\t\treturn {\n\t\t\tformatVersion: snapshot.snapshot.formatVersion,\n\t\t\tmodifications: snapshot.snapshot.modifications,\n\t\t\tcovers,\n\t\t}\n\t}\n\n\t/** Offline check that the snapshot still equals a full replay of all migrations. */\n\tasync verify(): Promise<{ ok: boolean; message: string }> {\n\t\tif (!(await this.snapshotManager.exists())) {\n\t\t\tthrow new CliError('No snapshot found. Run \"migrations snapshot\" first.', { code: 'SNAPSHOT_NOT_FOUND', exitCode: ExitCode.NotFound })\n\t\t}\n\t\tconst snapshot = await this.snapshotManager.read()\n\n\t\tconst stale = await this.findStaleness(snapshot)\n\t\tif (stale) {\n\t\t\treturn { ok: false, message: `Snapshot is stale: ${stale}. Run \"migrations snapshot\" to regenerate it.` }\n\t\t}\n\n\t\tconst stateMode = await this.schemaStateManager.isStateMode()\n\t\tconst replaySchema = await this.schemaVersionBuilder.buildSchema()\n\t\tlet snapshotSchema = this.schemaMigrator.applyModifications(emptySchema, snapshot.snapshot.modifications, snapshot.snapshot.formatVersion)\n\t\tif (stateMode) {\n\t\t\tsnapshotSchema = { ...snapshotSchema, ...await this.schemaStateManager.readState() }\n\t\t}\n\n\t\t// Compare with the same order-insensitive equality that SchemaDiffer uses for its own\n\t\t// round-trip check. The collapsed differ emits fields/constraints in a fixed order that may\n\t\t// differ from a replay of an interleaved history (e.g. a column added to an entity that\n\t\t// already has a relation), so a raw checksum (JSON.stringify) would report false mismatches\n\t\t// on schemas that are in fact deeply equal.\n\t\tconst differences = deepCompare(replaySchema, snapshotSchema, [], path => {\n\t\t\tif (path[0] === 'model' && path[1] === 'entities' && (path[3] === 'unique' || path[3] === 'index')) {\n\t\t\t\treturn (a, b) => compareArraysIgnoreOrder(a, b, path)\n\t\t\t}\n\t\t\treturn null\n\t\t})\n\t\tif (differences.length === 0) {\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tmessage: `Snapshot is up to date (covers ${snapshot.covers.length} migrations up to ${snapshot.version}).`,\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmessage: 'Snapshot does not match a full replay of all migrations. Run \"migrations snapshot\" to regenerate it.',\n\t\t}\n\t}\n\n\tprivate async findStaleness(snapshot: SnapshotFile): Promise<string | null> {\n\t\t// The collapsed snapshot is built differently per mode (state mode omits the non-model parts,\n\t\t// see create()), and on bootstrap the non-model overlay is driven by the *current* mode. A mode\n\t\t// switch since the snapshot was created (e.g. migrations init-state) leaves the covers untouched\n\t\t// and would otherwise pass unnoticed, so treat it as stale and fall back to a full replay.\n\t\tif (snapshot.stateMode !== await this.schemaStateManager.isStateMode()) {\n\t\t\treturn `schema state mode changed since the snapshot was created`\n\t\t}\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tconst byVersion = new Map(files.map(it => [it.version, it]))\n\t\tfor (const covered of snapshot.covers) {\n\t\t\tconst file = byVersion.get(covered.version)\n\t\t\tif (!file) {\n\t\t\t\treturn `covered migration ${covered.name} is missing`\n\t\t\t}\n\t\t\tconst content = await file.getContent()\n\t\t\tconst currentType = isSchemaMigration(content) ? 'schema' : 'content'\n\t\t\t// A covered migration that flipped type (e.g. a content migration manually rewritten into a\n\t\t\t// schema one) is not reflected in the collapsed modifications, so the snapshot no longer\n\t\t\t// equals a replay. Schema covers also verify the checksum; content covers carry none (their\n\t\t\t// data is never reproduced), so the type check is the only identity they get.\n\t\t\tif (currentType !== covered.type) {\n\t\t\t\treturn `covered migration ${covered.name} changed type`\n\t\t\t}\n\t\t\tif (covered.type === 'schema') {\n\t\t\t\tconst checksum = isSchemaMigration(content) ? calculateMigrationChecksum(content) : null\n\t\t\t\tif (checksum !== covered.checksum) {\n\t\t\t\t\treturn `covered migration ${covered.name} has changed`\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Detect a migration added within the covered range (version <= snapshot.version) that the\n\t\t// snapshot does not know about — e.g. a teammate's migration with an earlier timestamp merged\n\t\t// after the snapshot was generated. Without this, bootstrapping would record the covers up to\n\t\t// snapshot.version and the subsequent normal replay would fail with MUST_FOLLOW_LATEST on the\n\t\t// in-range migration, leaving the database half-bootstrapped. Treat it as stale and fall back.\n\t\tconst coveredVersions = new Set(snapshot.covers.map(it => it.version))\n\t\tfor (const file of files) {\n\t\t\tif (file.version <= snapshot.version && !coveredVersions.has(file.version)) {\n\t\t\t\treturn `migration ${file.name} is within the covered range but not part of the snapshot`\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\nconst migrationContentToInput = (version: string, name: string, content: MigrationContent) => {\n\tif (isSchemaMigration(content)) {\n\t\treturn {\n\t\t\tversion,\n\t\t\tname,\n\t\t\ttype: 'SCHEMA',\n\t\t\tschemaMigration: {\n\t\t\t\tformatVersion: content.formatVersion,\n\t\t\t\tmodifications: content.modifications,\n\t\t\t\tskippedErrors: content.skippedErrors,\n\t\t\t},\n\t\t}\n\t}\n\t// Content migrations are only recorded as executed (no data is replayed), so the queries are irrelevant.\n\treturn { version, name, type: 'CONTENT', contentMigration: [] }\n}\n"],"names":["Output","CliError","ExitCode","emptySchema","isSchemaMigration","calculateMigrationChecksum","VERSION_LATEST","deepCompare","compareArraysIgnoreOrder"],"mappings":";;;;;AAmBO,MAAM,wBAAwB;AAAA,EACpC,YACkB,oBACA,sBACA,cACA,gBACA,oBACA,iBACA,SAAiB,IAAIA,UAAAA,UACrC;AAPgB,SAAA,qBAAA;AACA,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,iBAAA;AACA,SAAA,qBAAA;AACA,SAAA,kBAAA;AACA,SAAA,SAAA;AAAA,EAElB;AAAA;AAAA,EAGA,MAAM,UAAiC;AACtC,UAAM,QAAQ,MAAM,KAAK,mBAAmB,kBAAA;AAC5C,QAAI,MAAM,WAAW,GAAG;AACvB,YAAM,IAAIC,UAAAA,SAAS,6BAA6B,EAAE,MAAM,wBAAwB,UAAUC,mBAAS,UAAU;AAAA,IAC9G;AACA,UAAM,YAAY,MAAM,KAAK,mBAAmB,YAAA;AAChD,UAAM,UAAU,MAAM,MAAM,SAAS,CAAC,EAAE;AAKxC,UAAM,kBAAkB,MAAM,KAAK,qBAAqB,oBAAoBC,YAAAA,aAAa,MAAM,IAAI;AACnG,UAAM,gBAAgB,KAAK,aAAa,YAAYA,YAAAA,aAAa,iBAAiB;AAAA,MACjF,qBAAqB;AAAA,IAAA,CACrB;AAED,UAAM,SAA6B,CAAA;AACnC,UAAM,oBAA8B,CAAA;AACpC,eAAW,QAAQ,OAAO;AACzB,YAAM,UAAU,MAAM,KAAK,WAAA;AAC3B,YAAM,SAASC,iBAAAA,kBAAkB,OAAO;AACxC,aAAO,KAAK;AAAA,QACX,SAAS,KAAK;AAAA,QACd,MAAM,KAAK;AAAA,QACX,MAAM,SAAS,WAAW;AA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MAAM;AAAA,MACN,iBAAiB;AAAA,QAChB,eAAe,QAAQ;AAAA,QACvB,eAAe,QAAQ;AAAA,QACvB,eAAe,QAAQ;AAAA,MAAA;AAAA,IACxB;AAAA,EAEF;AAEA,SAAO,EAAE,SAAS,MAAM,MAAM,WAAW,kBAAkB,GAAC;AAC7D;;"}
|
|
1
|
+
{"version":3,"file":"MigrationSnapshotFacade.cjs","sources":["../../../../../../packages/cli/src/lib/migrations/MigrationSnapshotFacade.ts"],"sourcesContent":["import { compareArraysIgnoreOrder, deepCompare, emptySchema } from '@contember/schema-utils'\nimport {\n\tcalculateMigrationChecksum,\n\tCoveredMigration,\n\tExecutedMigrationInfo,\n\tisSchemaMigration,\n\tMigrationContent,\n\tMigrationsResolver,\n\tSchemaDiffer,\n\tSchemaMigrator,\n\tSchemaStateManager,\n\tSchemaVersionBuilder,\n\tSnapshotFile,\n\tSnapshotInput,\n\tSnapshotManager,\n\tVERSION_LATEST,\n} from '@contember/migrations-client'\nimport { CliError, ExitCode, Output } from '@contember/cli-common'\n\nexport class MigrationSnapshotFacade {\n\tconstructor(\n\t\tprivate readonly migrationsResolver: MigrationsResolver,\n\t\tprivate readonly schemaVersionBuilder: SchemaVersionBuilder,\n\t\tprivate readonly schemaDiffer: SchemaDiffer,\n\t\tprivate readonly schemaMigrator: SchemaMigrator,\n\t\tprivate readonly schemaStateManager: SchemaStateManager,\n\t\tprivate readonly snapshotManager: SnapshotManager,\n\t\tprivate readonly output: Output = new Output(),\n\t) {\n\t}\n\n\t/** Builds a snapshot in memory without changing the filesystem. */\n\tasync prepare(): Promise<SnapshotFile> {\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tif (files.length === 0) {\n\t\t\tthrow new CliError('No migrations to snapshot', { code: 'MIGRATIONS_NOT_FOUND', exitCode: ExitCode.NotFound })\n\t\t}\n\t\tconst stateMode = await this.schemaStateManager.isStateMode()\n\t\tconst version = files[files.length - 1].version\n\n\t\t// Replay all schema migrations into a single schema. In state mode the non-model parts\n\t\t// (acl/validation/actions/settings) live in state/ and are skipped here; otherwise they\n\t\t// are part of the migration history and must be included in the collapsed modifications.\n\t\tconst collapsedSchema = await this.schemaVersionBuilder.buildSchemaAdvanced(emptySchema, () => true)\n\t\tconst modifications = this.schemaDiffer.diffSchemas(emptySchema, collapsedSchema, {\n\t\t\tskipNonModelDiffers: stateMode,\n\t\t})\n\n\t\tconst covers: CoveredMigration[] = []\n\t\tconst contentMigrations: string[] = []\n\t\tfor (const file of files) {\n\t\t\tconst content = await file.getContent()\n\t\t\tconst schema = isSchemaMigration(content)\n\t\t\tcovers.push({\n\t\t\t\tversion: file.version,\n\t\t\t\tname: file.name,\n\t\t\t\ttype: schema ? 'schema' : 'content',\n\t\t\t\tchecksum: schema ? calculateMigrationChecksum(content) : null,\n\t\t\t})\n\t\t\tif (!schema) {\n\t\t\t\tcontentMigrations.push(file.version)\n\t\t\t}\n\t\t}\n\n\t\tconst snapshot: SnapshotFile = {\n\t\t\tversion,\n\t\t\tstateMode,\n\t\t\tsnapshot: { formatVersion: VERSION_LATEST, modifications },\n\t\t\tcovers,\n\t\t\tcontentMigrations,\n\t\t}\n\t\treturn snapshot\n\t}\n\n\tasync write(snapshot: SnapshotFile): Promise<void> {\n\t\tawait this.snapshotManager.write(snapshot)\n\t}\n\n\t/**\n\t * Returns the snapshot when it can safely bootstrap the current project, else null.\n\t * The snapshot is only usable on an empty project (no executed migrations) and only when\n\t * none of the covered migration files have changed. A present-but-stale snapshot is skipped\n\t * with a warning, falling back to a full replay.\n\t */\n\tasync getUsableSnapshot(executedMigrations: ExecutedMigrationInfo[]): Promise<SnapshotFile | null> {\n\t\tif (!(await this.snapshotManager.exists())) {\n\t\t\treturn null\n\t\t}\n\t\tif (executedMigrations.length > 0) {\n\t\t\treturn null\n\t\t}\n\t\tconst snapshot = await this.snapshotManager.read()\n\t\tconst stale = await this.findStaleness(snapshot)\n\t\tif (stale) {\n\t\t\tthis.output.warn(`Ignoring snapshot: ${stale}. Run \"migrations snapshot\" to regenerate it.`)\n\t\t\treturn null\n\t\t}\n\t\treturn snapshot\n\t}\n\n\t/** Maps a snapshot to the GraphQL SnapshotInput; covered migrations are sent as Migration inputs. */\n\tasync buildSnapshotInput(snapshot: SnapshotFile): Promise<SnapshotInput> {\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tconst byVersion = new Map(files.map(it => [it.version, it]))\n\t\tconst covers: unknown[] = []\n\t\tfor (const covered of snapshot.covers) {\n\t\t\tconst file = byVersion.get(covered.version)\n\t\t\tif (!file) {\n\t\t\t\tthrow new CliError(`Snapshot covers missing migration ${covered.name}`, { code: 'SNAPSHOT_COVER_MISSING', exitCode: ExitCode.NotFound })\n\t\t\t}\n\t\t\tcovers.push(migrationContentToInput(covered.version, covered.name, await file.getContent()))\n\t\t}\n\t\treturn {\n\t\t\tformatVersion: snapshot.snapshot.formatVersion,\n\t\t\tmodifications: snapshot.snapshot.modifications,\n\t\t\tcovers,\n\t\t}\n\t}\n\n\t/** Offline check that the snapshot still equals a full replay of all migrations. */\n\tasync verify(): Promise<{ ok: boolean; message: string }> {\n\t\tif (!(await this.snapshotManager.exists())) {\n\t\t\tthrow new CliError('No snapshot found. Run \"migrations snapshot\" first.', { code: 'SNAPSHOT_NOT_FOUND', exitCode: ExitCode.NotFound })\n\t\t}\n\t\tconst snapshot = await this.snapshotManager.read()\n\n\t\tconst stale = await this.findStaleness(snapshot)\n\t\tif (stale) {\n\t\t\treturn { ok: false, message: `Snapshot is stale: ${stale}. Run \"migrations snapshot\" to regenerate it.` }\n\t\t}\n\n\t\tconst stateMode = await this.schemaStateManager.isStateMode()\n\t\tconst replaySchema = await this.schemaVersionBuilder.buildSchema()\n\t\tlet snapshotSchema = this.schemaMigrator.applyModifications(emptySchema, snapshot.snapshot.modifications, snapshot.snapshot.formatVersion)\n\t\tif (stateMode) {\n\t\t\tsnapshotSchema = { ...snapshotSchema, ...await this.schemaStateManager.readState() }\n\t\t}\n\n\t\t// Compare with the same order-insensitive equality that SchemaDiffer uses for its own\n\t\t// round-trip check. The collapsed differ emits fields/constraints in a fixed order that may\n\t\t// differ from a replay of an interleaved history (e.g. a column added to an entity that\n\t\t// already has a relation), so a raw checksum (JSON.stringify) would report false mismatches\n\t\t// on schemas that are in fact deeply equal.\n\t\tconst differences = deepCompare(replaySchema, snapshotSchema, [], path => {\n\t\t\tif (path[0] === 'model' && path[1] === 'entities' && (path[3] === 'unique' || path[3] === 'index' || path[3] === 'checks')) {\n\t\t\t\treturn (a, b) => compareArraysIgnoreOrder(a, b, path)\n\t\t\t}\n\t\t\treturn null\n\t\t})\n\t\tif (differences.length === 0) {\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tmessage: `Snapshot is up to date (covers ${snapshot.covers.length} migrations up to ${snapshot.version}).`,\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmessage: 'Snapshot does not match a full replay of all migrations. Run \"migrations snapshot\" to regenerate it.',\n\t\t}\n\t}\n\n\tprivate async findStaleness(snapshot: SnapshotFile): Promise<string | null> {\n\t\t// The collapsed snapshot is built differently per mode (state mode omits the non-model parts,\n\t\t// see create()), and on bootstrap the non-model overlay is driven by the *current* mode. A mode\n\t\t// switch since the snapshot was created (e.g. migrations init-state) leaves the covers untouched\n\t\t// and would otherwise pass unnoticed, so treat it as stale and fall back to a full replay.\n\t\tif (snapshot.stateMode !== await this.schemaStateManager.isStateMode()) {\n\t\t\treturn `schema state mode changed since the snapshot was created`\n\t\t}\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tconst byVersion = new Map(files.map(it => [it.version, it]))\n\t\tfor (const covered of snapshot.covers) {\n\t\t\tconst file = byVersion.get(covered.version)\n\t\t\tif (!file) {\n\t\t\t\treturn `covered migration ${covered.name} is missing`\n\t\t\t}\n\t\t\tconst content = await file.getContent()\n\t\t\tconst currentType = isSchemaMigration(content) ? 'schema' : 'content'\n\t\t\t// A covered migration that flipped type (e.g. a content migration manually rewritten into a\n\t\t\t// schema one) is not reflected in the collapsed modifications, so the snapshot no longer\n\t\t\t// equals a replay. Schema covers also verify the checksum; content covers carry none (their\n\t\t\t// data is never reproduced), so the type check is the only identity they get.\n\t\t\tif (currentType !== covered.type) {\n\t\t\t\treturn `covered migration ${covered.name} changed type`\n\t\t\t}\n\t\t\tif (covered.type === 'schema') {\n\t\t\t\tconst checksum = isSchemaMigration(content) ? calculateMigrationChecksum(content) : null\n\t\t\t\tif (checksum !== covered.checksum) {\n\t\t\t\t\treturn `covered migration ${covered.name} has changed`\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Detect a migration added within the covered range (version <= snapshot.version) that the\n\t\t// snapshot does not know about — e.g. a teammate's migration with an earlier timestamp merged\n\t\t// after the snapshot was generated. Without this, bootstrapping would record the covers up to\n\t\t// snapshot.version and the subsequent normal replay would fail with MUST_FOLLOW_LATEST on the\n\t\t// in-range migration, leaving the database half-bootstrapped. Treat it as stale and fall back.\n\t\tconst coveredVersions = new Set(snapshot.covers.map(it => it.version))\n\t\tfor (const file of files) {\n\t\t\tif (file.version <= snapshot.version && !coveredVersions.has(file.version)) {\n\t\t\t\treturn `migration ${file.name} is within the covered range but not part of the snapshot`\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\nconst migrationContentToInput = (version: string, name: string, content: MigrationContent) => {\n\tif (isSchemaMigration(content)) {\n\t\treturn {\n\t\t\tversion,\n\t\t\tname,\n\t\t\ttype: 'SCHEMA',\n\t\t\tschemaMigration: {\n\t\t\t\tformatVersion: content.formatVersion,\n\t\t\t\tmodifications: content.modifications,\n\t\t\t\tskippedErrors: content.skippedErrors,\n\t\t\t},\n\t\t}\n\t}\n\t// Content migrations are only recorded as executed (no data is replayed), so the queries are irrelevant.\n\treturn { version, name, type: 'CONTENT', contentMigration: [] }\n}\n"],"names":["Output","CliError","ExitCode","emptySchema","isSchemaMigration","calculateMigrationChecksum","VERSION_LATEST","deepCompare","compareArraysIgnoreOrder"],"mappings":";;;;;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ade {
|
|
|
106
106
|
snapshotSchema = { ...snapshotSchema, ...await this.schemaStateManager.readState() };
|
|
107
107
|
}
|
|
108
108
|
const differences = deepCompare(replaySchema, snapshotSchema, [], (path) => {
|
|
109
|
-
if (path[0] === "model" && path[1] === "entities" && (path[3] === "unique" || path[3] === "index")) {
|
|
109
|
+
if (path[0] === "model" && path[1] === "entities" && (path[3] === "unique" || path[3] === "index" || path[3] === "checks")) {
|
|
110
110
|
return (a, b) => compareArraysIgnoreOrder(a, b, path);
|
|
111
111
|
}
|
|
112
112
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MigrationSnapshotFacade.js","sources":["../../../../../../packages/cli/src/lib/migrations/MigrationSnapshotFacade.ts"],"sourcesContent":["import { compareArraysIgnoreOrder, deepCompare, emptySchema } from '@contember/schema-utils'\nimport {\n\tcalculateMigrationChecksum,\n\tCoveredMigration,\n\tExecutedMigrationInfo,\n\tisSchemaMigration,\n\tMigrationContent,\n\tMigrationsResolver,\n\tSchemaDiffer,\n\tSchemaMigrator,\n\tSchemaStateManager,\n\tSchemaVersionBuilder,\n\tSnapshotFile,\n\tSnapshotInput,\n\tSnapshotManager,\n\tVERSION_LATEST,\n} from '@contember/migrations-client'\nimport { CliError, ExitCode, Output } from '@contember/cli-common'\n\nexport class MigrationSnapshotFacade {\n\tconstructor(\n\t\tprivate readonly migrationsResolver: MigrationsResolver,\n\t\tprivate readonly schemaVersionBuilder: SchemaVersionBuilder,\n\t\tprivate readonly schemaDiffer: SchemaDiffer,\n\t\tprivate readonly schemaMigrator: SchemaMigrator,\n\t\tprivate readonly schemaStateManager: SchemaStateManager,\n\t\tprivate readonly snapshotManager: SnapshotManager,\n\t\tprivate readonly output: Output = new Output(),\n\t) {\n\t}\n\n\t/** Builds a snapshot in memory without changing the filesystem. */\n\tasync prepare(): Promise<SnapshotFile> {\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tif (files.length === 0) {\n\t\t\tthrow new CliError('No migrations to snapshot', { code: 'MIGRATIONS_NOT_FOUND', exitCode: ExitCode.NotFound })\n\t\t}\n\t\tconst stateMode = await this.schemaStateManager.isStateMode()\n\t\tconst version = files[files.length - 1].version\n\n\t\t// Replay all schema migrations into a single schema. In state mode the non-model parts\n\t\t// (acl/validation/actions/settings) live in state/ and are skipped here; otherwise they\n\t\t// are part of the migration history and must be included in the collapsed modifications.\n\t\tconst collapsedSchema = await this.schemaVersionBuilder.buildSchemaAdvanced(emptySchema, () => true)\n\t\tconst modifications = this.schemaDiffer.diffSchemas(emptySchema, collapsedSchema, {\n\t\t\tskipNonModelDiffers: stateMode,\n\t\t})\n\n\t\tconst covers: CoveredMigration[] = []\n\t\tconst contentMigrations: string[] = []\n\t\tfor (const file of files) {\n\t\t\tconst content = await file.getContent()\n\t\t\tconst schema = isSchemaMigration(content)\n\t\t\tcovers.push({\n\t\t\t\tversion: file.version,\n\t\t\t\tname: file.name,\n\t\t\t\ttype: schema ? 'schema' : 'content',\n\t\t\t\tchecksum: schema ? calculateMigrationChecksum(content) : null,\n\t\t\t})\n\t\t\tif (!schema) {\n\t\t\t\tcontentMigrations.push(file.version)\n\t\t\t}\n\t\t}\n\n\t\tconst snapshot: SnapshotFile = {\n\t\t\tversion,\n\t\t\tstateMode,\n\t\t\tsnapshot: { formatVersion: VERSION_LATEST, modifications },\n\t\t\tcovers,\n\t\t\tcontentMigrations,\n\t\t}\n\t\treturn snapshot\n\t}\n\n\tasync write(snapshot: SnapshotFile): Promise<void> {\n\t\tawait this.snapshotManager.write(snapshot)\n\t}\n\n\t/**\n\t * Returns the snapshot when it can safely bootstrap the current project, else null.\n\t * The snapshot is only usable on an empty project (no executed migrations) and only when\n\t * none of the covered migration files have changed. A present-but-stale snapshot is skipped\n\t * with a warning, falling back to a full replay.\n\t */\n\tasync getUsableSnapshot(executedMigrations: ExecutedMigrationInfo[]): Promise<SnapshotFile | null> {\n\t\tif (!(await this.snapshotManager.exists())) {\n\t\t\treturn null\n\t\t}\n\t\tif (executedMigrations.length > 0) {\n\t\t\treturn null\n\t\t}\n\t\tconst snapshot = await this.snapshotManager.read()\n\t\tconst stale = await this.findStaleness(snapshot)\n\t\tif (stale) {\n\t\t\tthis.output.warn(`Ignoring snapshot: ${stale}. Run \"migrations snapshot\" to regenerate it.`)\n\t\t\treturn null\n\t\t}\n\t\treturn snapshot\n\t}\n\n\t/** Maps a snapshot to the GraphQL SnapshotInput; covered migrations are sent as Migration inputs. */\n\tasync buildSnapshotInput(snapshot: SnapshotFile): Promise<SnapshotInput> {\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tconst byVersion = new Map(files.map(it => [it.version, it]))\n\t\tconst covers: unknown[] = []\n\t\tfor (const covered of snapshot.covers) {\n\t\t\tconst file = byVersion.get(covered.version)\n\t\t\tif (!file) {\n\t\t\t\tthrow new CliError(`Snapshot covers missing migration ${covered.name}`, { code: 'SNAPSHOT_COVER_MISSING', exitCode: ExitCode.NotFound })\n\t\t\t}\n\t\t\tcovers.push(migrationContentToInput(covered.version, covered.name, await file.getContent()))\n\t\t}\n\t\treturn {\n\t\t\tformatVersion: snapshot.snapshot.formatVersion,\n\t\t\tmodifications: snapshot.snapshot.modifications,\n\t\t\tcovers,\n\t\t}\n\t}\n\n\t/** Offline check that the snapshot still equals a full replay of all migrations. */\n\tasync verify(): Promise<{ ok: boolean; message: string }> {\n\t\tif (!(await this.snapshotManager.exists())) {\n\t\t\tthrow new CliError('No snapshot found. Run \"migrations snapshot\" first.', { code: 'SNAPSHOT_NOT_FOUND', exitCode: ExitCode.NotFound })\n\t\t}\n\t\tconst snapshot = await this.snapshotManager.read()\n\n\t\tconst stale = await this.findStaleness(snapshot)\n\t\tif (stale) {\n\t\t\treturn { ok: false, message: `Snapshot is stale: ${stale}. Run \"migrations snapshot\" to regenerate it.` }\n\t\t}\n\n\t\tconst stateMode = await this.schemaStateManager.isStateMode()\n\t\tconst replaySchema = await this.schemaVersionBuilder.buildSchema()\n\t\tlet snapshotSchema = this.schemaMigrator.applyModifications(emptySchema, snapshot.snapshot.modifications, snapshot.snapshot.formatVersion)\n\t\tif (stateMode) {\n\t\t\tsnapshotSchema = { ...snapshotSchema, ...await this.schemaStateManager.readState() }\n\t\t}\n\n\t\t// Compare with the same order-insensitive equality that SchemaDiffer uses for its own\n\t\t// round-trip check. The collapsed differ emits fields/constraints in a fixed order that may\n\t\t// differ from a replay of an interleaved history (e.g. a column added to an entity that\n\t\t// already has a relation), so a raw checksum (JSON.stringify) would report false mismatches\n\t\t// on schemas that are in fact deeply equal.\n\t\tconst differences = deepCompare(replaySchema, snapshotSchema, [], path => {\n\t\t\tif (path[0] === 'model' && path[1] === 'entities' && (path[3] === 'unique' || path[3] === 'index')) {\n\t\t\t\treturn (a, b) => compareArraysIgnoreOrder(a, b, path)\n\t\t\t}\n\t\t\treturn null\n\t\t})\n\t\tif (differences.length === 0) {\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tmessage: `Snapshot is up to date (covers ${snapshot.covers.length} migrations up to ${snapshot.version}).`,\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmessage: 'Snapshot does not match a full replay of all migrations. Run \"migrations snapshot\" to regenerate it.',\n\t\t}\n\t}\n\n\tprivate async findStaleness(snapshot: SnapshotFile): Promise<string | null> {\n\t\t// The collapsed snapshot is built differently per mode (state mode omits the non-model parts,\n\t\t// see create()), and on bootstrap the non-model overlay is driven by the *current* mode. A mode\n\t\t// switch since the snapshot was created (e.g. migrations init-state) leaves the covers untouched\n\t\t// and would otherwise pass unnoticed, so treat it as stale and fall back to a full replay.\n\t\tif (snapshot.stateMode !== await this.schemaStateManager.isStateMode()) {\n\t\t\treturn `schema state mode changed since the snapshot was created`\n\t\t}\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tconst byVersion = new Map(files.map(it => [it.version, it]))\n\t\tfor (const covered of snapshot.covers) {\n\t\t\tconst file = byVersion.get(covered.version)\n\t\t\tif (!file) {\n\t\t\t\treturn `covered migration ${covered.name} is missing`\n\t\t\t}\n\t\t\tconst content = await file.getContent()\n\t\t\tconst currentType = isSchemaMigration(content) ? 'schema' : 'content'\n\t\t\t// A covered migration that flipped type (e.g. a content migration manually rewritten into a\n\t\t\t// schema one) is not reflected in the collapsed modifications, so the snapshot no longer\n\t\t\t// equals a replay. Schema covers also verify the checksum; content covers carry none (their\n\t\t\t// data is never reproduced), so the type check is the only identity they get.\n\t\t\tif (currentType !== covered.type) {\n\t\t\t\treturn `covered migration ${covered.name} changed type`\n\t\t\t}\n\t\t\tif (covered.type === 'schema') {\n\t\t\t\tconst checksum = isSchemaMigration(content) ? calculateMigrationChecksum(content) : null\n\t\t\t\tif (checksum !== covered.checksum) {\n\t\t\t\t\treturn `covered migration ${covered.name} has changed`\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Detect a migration added within the covered range (version <= snapshot.version) that the\n\t\t// snapshot does not know about — e.g. a teammate's migration with an earlier timestamp merged\n\t\t// after the snapshot was generated. Without this, bootstrapping would record the covers up to\n\t\t// snapshot.version and the subsequent normal replay would fail with MUST_FOLLOW_LATEST on the\n\t\t// in-range migration, leaving the database half-bootstrapped. Treat it as stale and fall back.\n\t\tconst coveredVersions = new Set(snapshot.covers.map(it => it.version))\n\t\tfor (const file of files) {\n\t\t\tif (file.version <= snapshot.version && !coveredVersions.has(file.version)) {\n\t\t\t\treturn `migration ${file.name} is within the covered range but not part of the snapshot`\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\nconst migrationContentToInput = (version: string, name: string, content: MigrationContent) => {\n\tif (isSchemaMigration(content)) {\n\t\treturn {\n\t\t\tversion,\n\t\t\tname,\n\t\t\ttype: 'SCHEMA',\n\t\t\tschemaMigration: {\n\t\t\t\tformatVersion: content.formatVersion,\n\t\t\t\tmodifications: content.modifications,\n\t\t\t\tskippedErrors: content.skippedErrors,\n\t\t\t},\n\t\t}\n\t}\n\t// Content migrations are only recorded as executed (no data is replayed), so the queries are irrelevant.\n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AW,WAAW,SAAS,QAAQ;AACtC,YAAM,OAAO,UAAU,IAAI,QAAQ,OAAO;AAC1C,UAAI,CAAC,MAAM;AACV,eAAO,qBAAqB,QAAQ,IAAI;AAAA,MACzC;AACA,YAAM,UAAU,MAAM,KAAK,WAAA;AAC3B,YAAM,cAAc,kBAAkB,OAAO,IAAI,WAAW;AAK5D,UAAI,gBAAgB,QAAQ,MAAM;AACjC,eAAO,qBAAqB,QAAQ,IAAI;AAAA,MACzC;AACA,UAAI,QAAQ,SAAS,UAAU;AAC9B,cAAM,WAAW,kBAAkB,OAAO,IAAI,2BAA2B,OAAO,IAAI;AACpF,YAAI,aAAa,QAAQ,UAAU;AAClC,iBAAO,qBAAqB,QAAQ,IAAI;AAAA,QACzC;AAAA,MACD;AAAA,IACD;AAMA,UAAM,kBAAkB,IAAI,IAAI,SAAS,OAAO,IAAI,CAAA,OAAM,GAAG,OAAO,CAAC;AACrE,eAAW,QAAQ,OAAO;AACzB,UAAI,KAAK,WAAW,SAAS,WAAW,CAAC,gBAAgB,IAAI,KAAK,OAAO,GAAG;AAC3E,eAAO,aAAa,KAAK,IAAI;AAAA,MAC9B;AAAA,IACD;AACA,WAAO;AAAA,EACR;AACD;AAEA,MAAM,0BAA0B,CAAC,SAAiB,MAAc,YAA8B;AAC7F,MAAI,kBAAkB,OAAO,GAAG;AAC/B,WAAO;AAAA,MACN;AAAA,MACA;AAAA,MACA,MAAM;AAAA,MACN,iBAAiB;AAAA,QAChB,eAAe,QAAQ;AAAA,QACvB,eAAe,QAAQ;AAAA,QACvB,eAAe,QAAQ;AAAA,MAAA;AAAA,IACxB;AAAA,EAEF;AAEA,SAAO,EAAE,SAAS,MAAM,MAAM,WAAW,kBAAkB,GAAC;AAC7D;"}
|
|
1
|
+
{"version":3,"file":"MigrationSnapshotFacade.js","sources":["../../../../../../packages/cli/src/lib/migrations/MigrationSnapshotFacade.ts"],"sourcesContent":["import { compareArraysIgnoreOrder, deepCompare, emptySchema } from '@contember/schema-utils'\nimport {\n\tcalculateMigrationChecksum,\n\tCoveredMigration,\n\tExecutedMigrationInfo,\n\tisSchemaMigration,\n\tMigrationContent,\n\tMigrationsResolver,\n\tSchemaDiffer,\n\tSchemaMigrator,\n\tSchemaStateManager,\n\tSchemaVersionBuilder,\n\tSnapshotFile,\n\tSnapshotInput,\n\tSnapshotManager,\n\tVERSION_LATEST,\n} from '@contember/migrations-client'\nimport { CliError, ExitCode, Output } from '@contember/cli-common'\n\nexport class MigrationSnapshotFacade {\n\tconstructor(\n\t\tprivate readonly migrationsResolver: MigrationsResolver,\n\t\tprivate readonly schemaVersionBuilder: SchemaVersionBuilder,\n\t\tprivate readonly schemaDiffer: SchemaDiffer,\n\t\tprivate readonly schemaMigrator: SchemaMigrator,\n\t\tprivate readonly schemaStateManager: SchemaStateManager,\n\t\tprivate readonly snapshotManager: SnapshotManager,\n\t\tprivate readonly output: Output = new Output(),\n\t) {\n\t}\n\n\t/** Builds a snapshot in memory without changing the filesystem. */\n\tasync prepare(): Promise<SnapshotFile> {\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tif (files.length === 0) {\n\t\t\tthrow new CliError('No migrations to snapshot', { code: 'MIGRATIONS_NOT_FOUND', exitCode: ExitCode.NotFound })\n\t\t}\n\t\tconst stateMode = await this.schemaStateManager.isStateMode()\n\t\tconst version = files[files.length - 1].version\n\n\t\t// Replay all schema migrations into a single schema. In state mode the non-model parts\n\t\t// (acl/validation/actions/settings) live in state/ and are skipped here; otherwise they\n\t\t// are part of the migration history and must be included in the collapsed modifications.\n\t\tconst collapsedSchema = await this.schemaVersionBuilder.buildSchemaAdvanced(emptySchema, () => true)\n\t\tconst modifications = this.schemaDiffer.diffSchemas(emptySchema, collapsedSchema, {\n\t\t\tskipNonModelDiffers: stateMode,\n\t\t})\n\n\t\tconst covers: CoveredMigration[] = []\n\t\tconst contentMigrations: string[] = []\n\t\tfor (const file of files) {\n\t\t\tconst content = await file.getContent()\n\t\t\tconst schema = isSchemaMigration(content)\n\t\t\tcovers.push({\n\t\t\t\tversion: file.version,\n\t\t\t\tname: file.name,\n\t\t\t\ttype: schema ? 'schema' : 'content',\n\t\t\t\tchecksum: schema ? calculateMigrationChecksum(content) : null,\n\t\t\t})\n\t\t\tif (!schema) {\n\t\t\t\tcontentMigrations.push(file.version)\n\t\t\t}\n\t\t}\n\n\t\tconst snapshot: SnapshotFile = {\n\t\t\tversion,\n\t\t\tstateMode,\n\t\t\tsnapshot: { formatVersion: VERSION_LATEST, modifications },\n\t\t\tcovers,\n\t\t\tcontentMigrations,\n\t\t}\n\t\treturn snapshot\n\t}\n\n\tasync write(snapshot: SnapshotFile): Promise<void> {\n\t\tawait this.snapshotManager.write(snapshot)\n\t}\n\n\t/**\n\t * Returns the snapshot when it can safely bootstrap the current project, else null.\n\t * The snapshot is only usable on an empty project (no executed migrations) and only when\n\t * none of the covered migration files have changed. A present-but-stale snapshot is skipped\n\t * with a warning, falling back to a full replay.\n\t */\n\tasync getUsableSnapshot(executedMigrations: ExecutedMigrationInfo[]): Promise<SnapshotFile | null> {\n\t\tif (!(await this.snapshotManager.exists())) {\n\t\t\treturn null\n\t\t}\n\t\tif (executedMigrations.length > 0) {\n\t\t\treturn null\n\t\t}\n\t\tconst snapshot = await this.snapshotManager.read()\n\t\tconst stale = await this.findStaleness(snapshot)\n\t\tif (stale) {\n\t\t\tthis.output.warn(`Ignoring snapshot: ${stale}. Run \"migrations snapshot\" to regenerate it.`)\n\t\t\treturn null\n\t\t}\n\t\treturn snapshot\n\t}\n\n\t/** Maps a snapshot to the GraphQL SnapshotInput; covered migrations are sent as Migration inputs. */\n\tasync buildSnapshotInput(snapshot: SnapshotFile): Promise<SnapshotInput> {\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tconst byVersion = new Map(files.map(it => [it.version, it]))\n\t\tconst covers: unknown[] = []\n\t\tfor (const covered of snapshot.covers) {\n\t\t\tconst file = byVersion.get(covered.version)\n\t\t\tif (!file) {\n\t\t\t\tthrow new CliError(`Snapshot covers missing migration ${covered.name}`, { code: 'SNAPSHOT_COVER_MISSING', exitCode: ExitCode.NotFound })\n\t\t\t}\n\t\t\tcovers.push(migrationContentToInput(covered.version, covered.name, await file.getContent()))\n\t\t}\n\t\treturn {\n\t\t\tformatVersion: snapshot.snapshot.formatVersion,\n\t\t\tmodifications: snapshot.snapshot.modifications,\n\t\t\tcovers,\n\t\t}\n\t}\n\n\t/** Offline check that the snapshot still equals a full replay of all migrations. */\n\tasync verify(): Promise<{ ok: boolean; message: string }> {\n\t\tif (!(await this.snapshotManager.exists())) {\n\t\t\tthrow new CliError('No snapshot found. Run \"migrations snapshot\" first.', { code: 'SNAPSHOT_NOT_FOUND', exitCode: ExitCode.NotFound })\n\t\t}\n\t\tconst snapshot = await this.snapshotManager.read()\n\n\t\tconst stale = await this.findStaleness(snapshot)\n\t\tif (stale) {\n\t\t\treturn { ok: false, message: `Snapshot is stale: ${stale}. Run \"migrations snapshot\" to regenerate it.` }\n\t\t}\n\n\t\tconst stateMode = await this.schemaStateManager.isStateMode()\n\t\tconst replaySchema = await this.schemaVersionBuilder.buildSchema()\n\t\tlet snapshotSchema = this.schemaMigrator.applyModifications(emptySchema, snapshot.snapshot.modifications, snapshot.snapshot.formatVersion)\n\t\tif (stateMode) {\n\t\t\tsnapshotSchema = { ...snapshotSchema, ...await this.schemaStateManager.readState() }\n\t\t}\n\n\t\t// Compare with the same order-insensitive equality that SchemaDiffer uses for its own\n\t\t// round-trip check. The collapsed differ emits fields/constraints in a fixed order that may\n\t\t// differ from a replay of an interleaved history (e.g. a column added to an entity that\n\t\t// already has a relation), so a raw checksum (JSON.stringify) would report false mismatches\n\t\t// on schemas that are in fact deeply equal.\n\t\tconst differences = deepCompare(replaySchema, snapshotSchema, [], path => {\n\t\t\tif (path[0] === 'model' && path[1] === 'entities' && (path[3] === 'unique' || path[3] === 'index' || path[3] === 'checks')) {\n\t\t\t\treturn (a, b) => compareArraysIgnoreOrder(a, b, path)\n\t\t\t}\n\t\t\treturn null\n\t\t})\n\t\tif (differences.length === 0) {\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tmessage: `Snapshot is up to date (covers ${snapshot.covers.length} migrations up to ${snapshot.version}).`,\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmessage: 'Snapshot does not match a full replay of all migrations. Run \"migrations snapshot\" to regenerate it.',\n\t\t}\n\t}\n\n\tprivate async findStaleness(snapshot: SnapshotFile): Promise<string | null> {\n\t\t// The collapsed snapshot is built differently per mode (state mode omits the non-model parts,\n\t\t// see create()), and on bootstrap the non-model overlay is driven by the *current* mode. A mode\n\t\t// switch since the snapshot was created (e.g. migrations init-state) leaves the covers untouched\n\t\t// and would otherwise pass unnoticed, so treat it as stale and fall back to a full replay.\n\t\tif (snapshot.stateMode !== await this.schemaStateManager.isStateMode()) {\n\t\t\treturn `schema state mode changed since the snapshot was created`\n\t\t}\n\t\tconst files = await this.migrationsResolver.getMigrationFiles()\n\t\tconst byVersion = new Map(files.map(it => [it.version, it]))\n\t\tfor (const covered of snapshot.covers) {\n\t\t\tconst file = byVersion.get(covered.version)\n\t\t\tif (!file) {\n\t\t\t\treturn `covered migration ${covered.name} is missing`\n\t\t\t}\n\t\t\tconst content = await file.getContent()\n\t\t\tconst currentType = isSchemaMigration(content) ? 'schema' : 'content'\n\t\t\t// A covered migration that flipped type (e.g. a content migration manually rewritten into a\n\t\t\t// schema one) is not reflected in the collapsed modifications, so the snapshot no longer\n\t\t\t// equals a replay. Schema covers also verify the checksum; content covers carry none (their\n\t\t\t// data is never reproduced), so the type check is the only identity they get.\n\t\t\tif (currentType !== covered.type) {\n\t\t\t\treturn `covered migration ${covered.name} changed type`\n\t\t\t}\n\t\t\tif (covered.type === 'schema') {\n\t\t\t\tconst checksum = isSchemaMigration(content) ? calculateMigrationChecksum(content) : null\n\t\t\t\tif (checksum !== covered.checksum) {\n\t\t\t\t\treturn `covered migration ${covered.name} has changed`\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Detect a migration added within the covered range (version <= snapshot.version) that the\n\t\t// snapshot does not know about — e.g. a teammate's migration with an earlier timestamp merged\n\t\t// after the snapshot was generated. Without this, bootstrapping would record the covers up to\n\t\t// snapshot.version and the subsequent normal replay would fail with MUST_FOLLOW_LATEST on the\n\t\t// in-range migration, leaving the database half-bootstrapped. Treat it as stale and fall back.\n\t\tconst coveredVersions = new Set(snapshot.covers.map(it => it.version))\n\t\tfor (const file of files) {\n\t\t\tif (file.version <= snapshot.version && !coveredVersions.has(file.version)) {\n\t\t\t\treturn `migration ${file.name} is within the covered range but not part of the snapshot`\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\nconst migrationContentToInput = (version: string, name: string, content: MigrationContent) => {\n\tif (isSchemaMigration(content)) {\n\t\treturn {\n\t\t\tversion,\n\t\t\tname,\n\t\t\ttype: 'SCHEMA',\n\t\t\tschemaMigration: {\n\t\t\t\tformatVersion: content.formatVersion,\n\t\t\t\tmodifications: content.modifications,\n\t\t\t\tskippedErrors: content.skippedErrors,\n\t\t\t},\n\t\t}\n\t}\n\t// Content migrations are only recorded as executed (no data is replayed), so the queries are irrelevant.\n\treturn { version, name, type: 'CONTENT', contentMigration: [] }\n}\n"],"names":[],"mappings":";;;AAmBO,MAAM,wBAAwB;AAAA,EACpC,YACkB,oBACA,sBACA,cACA,gBACA,oBACA,iBACA,SAAiB,IAAI,UACrC;AAPgB,SAAA,qBAAA;AACA,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,iBAAA;AACA,SAAA,qBAAA;AACA,SAAA,kBAAA;AACA,SAAA,SAAA;AAAA,EAElB;AAAA;AAAA,EAGA,MAAM,UAAiC;AACtC,UAAM,QAAQ,MAAM,KAAK,mBAAmB,kBAAA;AAC5C,QAAI,MAAM,WAAW,GAAG;AACvB,YAAM,IAAI,SAAS,6BAA6B,EAAE,MAAM,wBAAwB,UAAU,SAAS,UAAU;AAAA,IAC9G;AACA,UAAM,YAAY,MAA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AA,IACD;AAMA,UAAM,kBAAkB,IAAI,IAAI,SAAS,OAAO,IAAI,CAAA,OAAM,GAAG,OAAO,CAAC;AACrE,eAAW,QAAQ,OAAO;AACzB,UAAI,KAAK,WAAW,SAAS,WAAW,CAAC,gBAAgB,IAAI,KAAK,OAAO,GAAG;AAC3E,eAAO,aAAa,KAAK,IAAI;AAAA,MAC9B;AAAA,IACD;AACA,WAAO;AAAA,EACR;AACD;AAEA,MAAM,0BAA0B,CAAC,SAAiB,MAAc,YAA8B;AAC7F,MAAI,kBAAkB,OAAO,GAAG;AAC/B,WAAO;AAAA,MACN;AAAA,MACA;AAAA,MACA,MAAM;AAAA,MACN,iBAAiB;AAAA,QAChB,eAAe,QAAQ;AAAA,QACvB,eAAe,QAAQ;AAAA,QACvB,eAAe,QAAQ;AAAA,MAAA;AAAA,IACxB;AAAA,EAEF;AAEA,SAAO,EAAE,SAAS,MAAM,MAAM,WAAW,kBAAkB,GAAC;AAC7D;"}
|
|
@@ -1,13 +1,47 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
-
const
|
|
4
|
-
const
|
|
5
|
-
const
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
const cliCommon = require("@contember/cli-common");
|
|
4
|
+
const promptConfirm = async (output, { message, initial = false }) => {
|
|
5
|
+
const question = `${cliCommon.style("bold", message)} ${cliCommon.style("dim", initial ? "(Y/n)" : "(y/N)")} `;
|
|
6
|
+
for (; ; ) {
|
|
7
|
+
const answer = await output.prompt(question);
|
|
8
|
+
if (answer === void 0) {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
const normalized = answer.trim().toLowerCase();
|
|
12
|
+
if (normalized === "") {
|
|
13
|
+
return initial;
|
|
14
|
+
}
|
|
15
|
+
if (normalized === "y" || normalized === "yes") {
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
if (normalized === "n" || normalized === "no") {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
const promptSelect = async (output, { message, choices }) => {
|
|
24
|
+
if (choices.length === 0) {
|
|
25
|
+
return void 0;
|
|
26
|
+
}
|
|
27
|
+
const list = choices.map((choice, index) => ` ${cliCommon.style("cyan", String(index + 1))}) ${choice.title}
|
|
28
|
+
`).join("");
|
|
29
|
+
const ask = `${cliCommon.style("dim", `Choose 1-${choices.length}:`)} `;
|
|
30
|
+
let question = `${cliCommon.style("bold", message)}
|
|
31
|
+
${list}${ask}`;
|
|
32
|
+
for (; ; ) {
|
|
33
|
+
const answer = await output.prompt(question);
|
|
34
|
+
if (answer === void 0) {
|
|
35
|
+
return void 0;
|
|
36
|
+
}
|
|
37
|
+
const trimmed = answer.trim();
|
|
38
|
+
const choice = /^\d+$/.test(trimmed) ? choices[Number(trimmed) - 1] : void 0;
|
|
39
|
+
if (choice) {
|
|
40
|
+
return choice.value;
|
|
41
|
+
}
|
|
42
|
+
question = `${cliCommon.style("dim", `Enter a number from 1 to ${choices.length}:`)} `;
|
|
43
|
+
}
|
|
8
44
|
};
|
|
9
|
-
const promptConfirm = (output, options) => prompt_internal.promptConfirmWithRunner(output, options, runPrompt);
|
|
10
|
-
const promptSelect = (output, options) => prompt_internal.promptSelectWithRunner(output, options, runPrompt);
|
|
11
45
|
exports.promptConfirm = promptConfirm;
|
|
12
46
|
exports.promptSelect = promptSelect;
|
|
13
47
|
//# sourceMappingURL=prompt.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.cjs","sources":["../../../../../../packages/cli/src/lib/prompt/prompt.ts"],"sourcesContent":["import { Output } from '@contember/cli-common'\
|
|
1
|
+
{"version":3,"file":"prompt.cjs","sources":["../../../../../../packages/cli/src/lib/prompt/prompt.ts"],"sourcesContent":["import { Output, style } from '@contember/cli-common'\n\nexport interface ConfirmPromptOptions {\n\treadonly message: string\n\t/** The answer for an empty line. */\n\treadonly initial?: boolean\n}\n\nexport interface SelectPromptChoice<T extends string> {\n\treadonly title: string\n\treadonly value: T\n}\n\nexport interface SelectPromptOptions<T extends string> {\n\treadonly message: string\n\treadonly choices: readonly SelectPromptChoice<T>[]\n}\n\n/** Asks a yes/no question until it gets `y`, `yes`, `n`, `no` or an empty line. A closed input answers no. */\nexport const promptConfirm = async (output: Output, { message, initial = false }: ConfirmPromptOptions): Promise<boolean> => {\n\tconst question = `${style('bold', message)} ${style('dim', initial ? '(Y/n)' : '(y/N)')} `\n\tfor (;;) {\n\t\tconst answer = await output.prompt(question)\n\t\tif (answer === undefined) {\n\t\t\treturn false\n\t\t}\n\t\tconst normalized = answer.trim().toLowerCase()\n\t\tif (normalized === '') {\n\t\t\treturn initial\n\t\t}\n\t\tif (normalized === 'y' || normalized === 'yes') {\n\t\t\treturn true\n\t\t}\n\t\tif (normalized === 'n' || normalized === 'no') {\n\t\t\treturn false\n\t\t}\n\t}\n}\n\n/** Lists the choices with numbers and asks until one is picked. There is no default; a closed input picks nothing. */\nexport const promptSelect = async <const T extends string>(output: Output, { message, choices }: SelectPromptOptions<T>): Promise<T | undefined> => {\n\tif (choices.length === 0) {\n\t\treturn undefined\n\t}\n\tconst list = choices.map((choice, index) => ` ${style('cyan', String(index + 1))}) ${choice.title}\\n`).join('')\n\tconst ask = `${style('dim', `Choose 1-${choices.length}:`)} `\n\tlet question = `${style('bold', message)}\\n${list}${ask}`\n\tfor (;;) {\n\t\tconst answer = await output.prompt(question)\n\t\tif (answer === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst trimmed = answer.trim()\n\t\tconst choice = /^\\d+$/.test(trimmed) ? choices[Number(trimmed) - 1] : undefined\n\t\tif (choice) {\n\t\t\treturn choice.value\n\t\t}\n\t\tquestion = `${style('dim', `Enter a number from 1 to ${choices.length}:`)} `\n\t}\n}\n"],"names":["style"],"mappings":";;;AAmBO,MAAM,gBAAgB,OAAO,QAAgB,EAAE,SAAS,UAAU,YAAoD;AAC5H,QAAM,W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
|
2
|
-
|
|
3
|
-
const
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { style } from "@contember/cli-common";
|
|
2
|
+
const promptConfirm = async (output, { message, initial = false }) => {
|
|
3
|
+
const question = `${style("bold", message)} ${style("dim", initial ? "(Y/n)" : "(y/N)")} `;
|
|
4
|
+
for (; ; ) {
|
|
5
|
+
const answer = await output.prompt(question);
|
|
6
|
+
if (answer === void 0) {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
const normalized = answer.trim().toLowerCase();
|
|
10
|
+
if (normalized === "") {
|
|
11
|
+
return initial;
|
|
12
|
+
}
|
|
13
|
+
if (normalized === "y" || normalized === "yes") {
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
if (normalized === "n" || normalized === "no") {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const promptSelect = async (output, { message, choices }) => {
|
|
22
|
+
if (choices.length === 0) {
|
|
23
|
+
return void 0;
|
|
24
|
+
}
|
|
25
|
+
const list = choices.map((choice, index) => ` ${style("cyan", String(index + 1))}) ${choice.title}
|
|
26
|
+
`).join("");
|
|
27
|
+
const ask = `${style("dim", `Choose 1-${choices.length}:`)} `;
|
|
28
|
+
let question = `${style("bold", message)}
|
|
29
|
+
${list}${ask}`;
|
|
30
|
+
for (; ; ) {
|
|
31
|
+
const answer = await output.prompt(question);
|
|
32
|
+
if (answer === void 0) {
|
|
33
|
+
return void 0;
|
|
34
|
+
}
|
|
35
|
+
const trimmed = answer.trim();
|
|
36
|
+
const choice = /^\d+$/.test(trimmed) ? choices[Number(trimmed) - 1] : void 0;
|
|
37
|
+
if (choice) {
|
|
38
|
+
return choice.value;
|
|
39
|
+
}
|
|
40
|
+
question = `${style("dim", `Enter a number from 1 to ${choices.length}:`)} `;
|
|
41
|
+
}
|
|
6
42
|
};
|
|
7
|
-
const promptConfirm = (output, options) => promptConfirmWithRunner(output, options, runPrompt);
|
|
8
|
-
const promptSelect = (output, options) => promptSelectWithRunner(output, options, runPrompt);
|
|
9
43
|
export {
|
|
10
44
|
promptConfirm,
|
|
11
45
|
promptSelect
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.js","sources":["../../../../../../packages/cli/src/lib/prompt/prompt.ts"],"sourcesContent":["import { Output } from '@contember/cli-common'\
|
|
1
|
+
{"version":3,"file":"prompt.js","sources":["../../../../../../packages/cli/src/lib/prompt/prompt.ts"],"sourcesContent":["import { Output, style } from '@contember/cli-common'\n\nexport interface ConfirmPromptOptions {\n\treadonly message: string\n\t/** The answer for an empty line. */\n\treadonly initial?: boolean\n}\n\nexport interface SelectPromptChoice<T extends string> {\n\treadonly title: string\n\treadonly value: T\n}\n\nexport interface SelectPromptOptions<T extends string> {\n\treadonly message: string\n\treadonly choices: readonly SelectPromptChoice<T>[]\n}\n\n/** Asks a yes/no question until it gets `y`, `yes`, `n`, `no` or an empty line. A closed input answers no. */\nexport const promptConfirm = async (output: Output, { message, initial = false }: ConfirmPromptOptions): Promise<boolean> => {\n\tconst question = `${style('bold', message)} ${style('dim', initial ? '(Y/n)' : '(y/N)')} `\n\tfor (;;) {\n\t\tconst answer = await output.prompt(question)\n\t\tif (answer === undefined) {\n\t\t\treturn false\n\t\t}\n\t\tconst normalized = answer.trim().toLowerCase()\n\t\tif (normalized === '') {\n\t\t\treturn initial\n\t\t}\n\t\tif (normalized === 'y' || normalized === 'yes') {\n\t\t\treturn true\n\t\t}\n\t\tif (normalized === 'n' || normalized === 'no') {\n\t\t\treturn false\n\t\t}\n\t}\n}\n\n/** Lists the choices with numbers and asks until one is picked. There is no default; a closed input picks nothing. */\nexport const promptSelect = async <const T extends string>(output: Output, { message, choices }: SelectPromptOptions<T>): Promise<T | undefined> => {\n\tif (choices.length === 0) {\n\t\treturn undefined\n\t}\n\tconst list = choices.map((choice, index) => ` ${style('cyan', String(index + 1))}) ${choice.title}\\n`).join('')\n\tconst ask = `${style('dim', `Choose 1-${choices.length}:`)} `\n\tlet question = `${style('bold', message)}\\n${list}${ask}`\n\tfor (;;) {\n\t\tconst answer = await output.prompt(question)\n\t\tif (answer === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst trimmed = answer.trim()\n\t\tconst choice = /^\\d+$/.test(trimmed) ? choices[Number(trimmed) - 1] : undefined\n\t\tif (choice) {\n\t\t\treturn choice.value\n\t\t}\n\t\tquestion = `${style('dim', `Enter a number from 1 to ${choices.length}:`)} `\n\t}\n}\n"],"names":[],"mappings":";AAmBO,MAAM,gBAAgB,OAAO,QAAgB,EAAE,SAAS,UAAU,YAAoD;AAC5H,QAAM,WAAW,GAAG,MAAM,QAAQ,OAAO,CAAC,IAAI,MAAM,OAAO,UAAU,UAAU,OAAO,CAAC;AACvF,aAAS;AACR,UAAM,SAAS,MAAM,OAAO,OAAO,QAAQ;AAC3C,QAAI,WAAW,QAAW;AACzB,aAAO;AAAA,IACR;AACA,UAAM,aAAa,OAAO,KAAA,EAAO,YAAA;AACjC,QAAI,eAAe,IAAI;AACtB,aAAO;AAAA,IACR;AACA,QAAI,eAAe,OAAO,eAAe,OAAO;AAC/C,aAAO;AAAA,IACR;AACA,QAAI,eAAe,OAAO,eAAe,MAAM;AAC9C,aAAO;AAAA,IACR;AAAA,EACD;AACD;AAGO,MAAM,eAAe,OAA+B,QAAgB,EAAE,SAAS,cAA8D;AACnJ,MAAI,QAAQ,WAAW,GAAG;AACzB,WAAO;AAAA,EACR;AACA,QAAM,OAAO,QAAQ,IAAI,CAAC,QAAQ,UAAU,KAAK,MAAM,QAAQ,OAAO,QAAQ,CAAC,CAAC,CAAC,KAAK,OAAO,KAAK;AAAA,CAAI,EAAE,KAAK,EAAE;AAC/G,QAAM,MAAM,GAAG,MAAM,OAAO,YAAY,QAAQ,MAAM,GAAG,CAAC;AAC1D,MAAI,WAAW,GAAG,MAAM,QAAQ,OAAO,CAAC;AAAA,EAAK,IAAI,GAAG,GAAG;AACvD,aAAS;AACR,UAAM,SAAS,MAAM,OAAO,OAAO,QAAQ;AAC3C,QAAI,WAAW,QAAW;AACzB,aAAO;AAAA,IACR;AACA,UAAM,UAAU,OAAO,KAAA;AACvB,UAAM,SAAS,QAAQ,KAAK,OAAO,IAAI,QAAQ,OAAO,OAAO,IAAI,CAAC,IAAI;AACtE,QAAI,QAAQ;AACX,aAAO,OAAO;AAAA,IACf;AACA,eAAW,GAAG,MAAM,OAAO,4BAA4B,QAAQ,MAAM,GAAG,CAAC;AAAA,EAC1E;AACD;"}
|
|
@@ -4,7 +4,7 @@ const cliCommon = require("@contember/cli-common");
|
|
|
4
4
|
const stream = require("../stream.cjs");
|
|
5
5
|
const node_stream = require("node:stream");
|
|
6
6
|
const promises = require("node:stream/promises");
|
|
7
|
-
const
|
|
7
|
+
const zlib = require("node:zlib");
|
|
8
8
|
const TransportError = require("../errors/TransportError.cjs");
|
|
9
9
|
var __defProp = Object.defineProperty;
|
|
10
10
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
@@ -220,7 +220,7 @@ class DataTransferClient {
|
|
|
220
220
|
});
|
|
221
221
|
const uploadStream = new node_stream.PassThrough();
|
|
222
222
|
const abortController = new AbortController();
|
|
223
|
-
const rawPump = gzip ? promises.pipeline(stream$1, transformedStream,
|
|
223
|
+
const rawPump = gzip ? promises.pipeline(stream$1, transformedStream, zlib.createGzip(), uploadStream) : promises.pipeline(stream$1, transformedStream, uploadStream);
|
|
224
224
|
const context = transferContext("Import", project.endpoint);
|
|
225
225
|
const requestInit = {
|
|
226
226
|
headers: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTransferClient.cjs","sources":["../../../../../../packages/cli/src/lib/transfer/DataTransferClient.ts"],"sourcesContent":["import { CliError, ExitCode } from '@contember/cli-common'\nimport { LineTransform } from '../stream.js'\nimport { PassThrough, Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport { createGzip } from 'node:zlib'\nimport { RemoteProject } from '../project/RemoteProject.js'\nimport { toHttpTransportError, toTransportError } from '../errors/TransportError.js'\n\nconst transferContext = (action: 'Import' | 'Export', endpoint: string) => ({\n\tservice: `Data ${action.toLowerCase()}`,\n\tcodePrefix: `TRANSFER_${action.toUpperCase()}`,\n\turl: `${endpoint}/${action.toLowerCase()}`,\n})\n\nconst transferStreamError = (action: 'Import' | 'Export', cause: unknown): CliError =>\n\tnew CliError(`${action} stream failed`, {\n\t\tcode: `TRANSFER_${action.toUpperCase()}_STREAM_FAILED`,\n\t\texitCode: ExitCode.InputError,\n\t\tdetails: { operation: action.toLowerCase() },\n\t\tcause,\n\t})\n\ntype TransferCommandName =\n\t| 'importSystemSchemaBegin'\n\t| 'importContentSchemaBegin'\n\t| 'importSequence'\n\t| 'insertBegin'\n\t| 'insertRow'\n\t| 'insertEnd'\n\nconst transferCommandNames: ReadonlySet<string> = new Set<TransferCommandName>([\n\t'importSystemSchemaBegin',\n\t'importContentSchemaBegin',\n\t'importSequence',\n\t'insertBegin',\n\t'insertRow',\n\t'insertEnd',\n])\n\nconst isTransferCommandName = (value: string): value is TransferCommandName => transferCommandNames.has(value)\n\ninterface TransferEvent {\n\treadonly name: TransferCommandName\n\treadonly payload?: Record<string, unknown>\n}\n\nconst parseTransferEvent = (line: string): TransferEvent => {\n\tconst value: unknown = JSON.parse(line)\n\tif (!Array.isArray(value) || typeof value[0] !== 'string') {\n\t\tthrow invalidTransferCommand('TRANSFER_IMPORT_INVALID_COMMAND')\n\t}\n\tif (!isTransferCommandName(value[0])) {\n\t\tthrow invalidTransferCommand('TRANSFER_IMPORT_UNKNOWN_COMMAND')\n\t}\n\tconst payload = value[1]\n\treturn {\n\t\tname: value[0],\n\t\t...(typeof payload === 'object' && payload !== null && !Array.isArray(payload) ? { payload } : {}),\n\t}\n}\n\nconst invalidTransferCommand = (code: 'TRANSFER_IMPORT_INVALID_COMMAND' | 'TRANSFER_IMPORT_UNKNOWN_COMMAND'): CliError =>\n\tnew CliError('Import stream contains an unsupported command', {\n\t\tcode,\n\t\texitCode: ExitCode.InputError,\n\t\tdetails: { operation: 'import' },\n\t})\n\nconst normalizeImportStreamError = (cause: unknown): CliError => {\n\tif (\n\t\tcause instanceof CliError\n\t\t&& (cause.code === 'TRANSFER_IMPORT_INVALID_COMMAND' || cause.code === 'TRANSFER_IMPORT_UNKNOWN_COMMAND')\n\t) {\n\t\treturn cause\n\t}\n\treturn transferStreamError('Import', cause)\n}\n\nconst requireEventPayload = (event: TransferEvent): Record<string, unknown> => {\n\tif (event.payload === undefined) {\n\t\tthrow new Error(`Transfer event ${event.name} has no payload`)\n\t}\n\treturn event.payload\n}\n\nconst toBytes = (chunk: unknown): Uint8Array => {\n\tif (typeof chunk === 'string') {\n\t\treturn Buffer.from(chunk)\n\t}\n\tif (chunk instanceof Uint8Array) {\n\t\treturn chunk\n\t}\n\tthrow transferStreamError('Import', new Error('Unsupported stream chunk'))\n}\n\nconst toUploadStream = (stream: Readable): ReadableStream<Uint8Array> => {\n\tconst iterator: AsyncIterator<unknown> = stream[Symbol.asyncIterator]()\n\treturn new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst next = await iterator.next()\n\t\t\t\tif (next.done) {\n\t\t\t\t\tcontroller.close()\n\t\t\t\t} else {\n\t\t\t\t\tcontroller.enqueue(toBytes(next.value))\n\t\t\t\t}\n\t\t\t} catch (cause) {\n\t\t\t\tcontroller.error(transferStreamError('Import', cause))\n\t\t\t}\n\t\t},\n\t\tasync cancel() {\n\t\t\tstream.destroy()\n\t\t\ttry {\n\t\t\t\tawait iterator.return?.()\n\t\t\t} catch {\n\t\t\t\t// Stream cleanup must not replace the primary transfer error.\n\t\t\t}\n\t\t},\n\t})\n}\n\nclass WebResponseReadable extends Readable {\n\tprivate readonly reader: ReadableStreamDefaultReader<Uint8Array>\n\tprivate reading = false\n\tprivate released = false\n\n\tconstructor(stream: ReadableStream<Uint8Array>) {\n\t\tsuper()\n\t\tthis.reader = stream.getReader()\n\t}\n\n\tpublic override _read(): void {\n\t\tif (this.reading || this.destroyed) {\n\t\t\treturn\n\t\t}\n\t\tthis.reading = true\n\t\tvoid this.readNext()\n\t}\n\n\tpublic override _destroy(error: Error | null, callback: (error?: Error | null) => void): void {\n\t\tthis.cancelReader().then(\n\t\t\t() => callback(error),\n\t\t\t() => callback(error),\n\t\t)\n\t}\n\n\tprivate async readNext(): Promise<void> {\n\t\ttry {\n\t\t\tconst next = await this.reader.read()\n\t\t\tif (this.destroyed) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (next.done) {\n\t\t\t\tthis.releaseReader()\n\t\t\t\tthis.push(null)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.reading = false\n\t\t\tif (this.push(next.value)) {\n\t\t\t\tthis._read()\n\t\t\t}\n\t\t} catch (cause) {\n\t\t\tthis.destroy(cause instanceof Error ? cause : new Error('Export response stream failed'))\n\t\t}\n\t}\n\n\tprivate async cancelReader(): Promise<void> {\n\t\tif (this.released) {\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tawait this.reader.cancel()\n\t\t} catch {\n\t\t\t// Stream cleanup must not replace the primary transfer error.\n\t\t} finally {\n\t\t\tthis.releaseReader()\n\t\t}\n\t}\n\n\tprivate releaseReader(): void {\n\t\tif (!this.released) {\n\t\t\tthis.released = true\n\t\t\tthis.reader.releaseLock()\n\t\t}\n\t}\n}\n\nconst cancelResponseBody = async (response: Response): Promise<void> => {\n\ttry {\n\t\tawait response.body?.cancel()\n\t} catch {\n\t\t// The HTTP classification is the primary error.\n\t}\n}\n\nconst assertImportResult = async (response: Response): Promise<void> => {\n\tlet body: unknown\n\ttry {\n\t\tbody = await response.json()\n\t} catch (cause) {\n\t\tthrow new CliError('Import returned an invalid response', {\n\t\t\tcode: 'TRANSFER_IMPORT_INVALID_RESPONSE',\n\t\t\texitCode: ExitCode.InternalError,\n\t\t\tdetails: { operation: 'import' },\n\t\t\tcause,\n\t\t})\n\t}\n\tif (typeof body === 'object' && body !== null && 'ok' in body && body.ok === true) {\n\t\treturn\n\t}\n\tthrow new CliError('Import failed', {\n\t\tcode: 'IMPORT_FAILED',\n\t\texitCode: ExitCode.InputError,\n\t\tdetails: { operation: 'import' },\n\t})\n}\n\nexport interface DataExportResponse {\n\treadonly body: ReadableStream<Uint8Array> | Readable | null\n}\n\ntype ImportRequestOutcome =\n\t| { readonly type: 'response'; readonly response: Response }\n\t| { readonly type: 'request-error'; readonly error: CliError }\n\ntype ImportPumpOutcome =\n\t| { readonly type: 'pump-complete' }\n\t| { readonly type: 'pump-error'; readonly error: CliError }\n\ninterface StreamingRequestInit extends RequestInit {\n\treadonly duplex: 'half'\n}\n\nexport class DataTransferClient {\n\tdataImport = async ({ printProgress, stream, project, gzip }: {\n\t\tstream: Readable\n\t\tproject: RemoteProject\n\t\tprintProgress: (message: string) => void\n\t\tgzip: boolean\n\t}): Promise<void> => {\n\t\tlet table = ''\n\t\tlet rowCount = 0\n\t\tlet rowTotal = 0\n\t\tlet transferred = 0\n\t\tlet start = Date.now()\n\t\tconst transformedStream = new LineTransform(line => {\n\t\t\ttransferred += line.length + 1\n\t\t\tif (line === '') {\n\t\t\t\treturn ''\n\t\t\t}\n\t\t\tconst event = parseTransferEvent(line)\n\t\t\tswitch (event.name) {\n\t\t\t\tcase 'importSystemSchemaBegin':\n\t\t\t\t\treturn JSON.stringify([event.name, { ...requireEventPayload(event), project: project.name }])\n\t\t\t\tcase 'importContentSchemaBegin':\n\t\t\t\t\treturn JSON.stringify([event.name, { ...requireEventPayload(event), project: project.name }])\n\t\t\t\tcase 'importSequence':\n\t\t\t\t\tbreak\n\t\t\t\tcase 'insertBegin':\n\t\t\t\t\tif (typeof event.payload?.table !== 'string') {\n\t\t\t\t\t\tthrow new Error('Insert event has no table')\n\t\t\t\t\t}\n\t\t\t\t\ttable = event.payload.table\n\t\t\t\t\trowCount = 0\n\t\t\t\t\tbreak\n\t\t\t\tcase 'insertRow':\n\t\t\t\t\trowCount++\n\t\t\t\t\trowTotal++\n\t\t\t\t\tbreak\n\t\t\t\tcase 'insertEnd':\n\t\t\t\t\tbreak\n\t\t\t}\n\t\t\tif ((rowCount % 1000) === 0 || event.name !== 'insertRow') {\n\t\t\t\tconst mbs = Math.floor(transferred / 1024 / 1024).toString()\n\t\t\t\tconst durationS = Math.floor((Date.now() - start) / 1000)\n\t\t\t\tprintProgress(`transferred ${mbs} MiB; inserted ${rowCount} ${table} rows, ${rowTotal} total; ${durationS} seconds`)\n\t\t\t}\n\t\t\treturn line\n\t\t})\n\t\tconst uploadStream = new PassThrough()\n\t\tconst abortController = new AbortController()\n\t\tconst rawPump = gzip\n\t\t\t? pipeline(stream, transformedStream, createGzip(), uploadStream)\n\t\t\t: pipeline(stream, transformedStream, uploadStream)\n\t\tconst context = transferContext('Import', project.endpoint)\n\t\tconst requestInit: StreamingRequestInit = {\n\t\t\theaders: {\n\t\t\t\t'Authorization': `Bearer ${project.token}`,\n\t\t\t\t'Content-type': 'application/x-ndjson',\n\t\t\t\t...(gzip ? { 'Content-Encoding': 'gzip' } : {}),\n\t\t\t},\n\t\t\tmethod: 'POST',\n\t\t\tbody: toUploadStream(uploadStream),\n\t\t\tduplex: 'half',\n\t\t\tsignal: abortController.signal,\n\t\t}\n\t\tconst rawRequest = fetch(`${project.endpoint}/import`, requestInit)\n\t\tconst pump: Promise<ImportPumpOutcome> = rawPump.then(\n\t\t\t() => ({ type: 'pump-complete' }),\n\t\t\tcause => {\n\t\t\t\tabortController.abort()\n\t\t\t\treturn { type: 'pump-error', error: normalizeImportStreamError(cause) }\n\t\t\t},\n\t\t)\n\t\tconst request: Promise<ImportRequestOutcome> = rawRequest.then(\n\t\t\tresponse => ({ type: 'response', response }),\n\t\t\terror => ({ type: 'request-error', error: toTransportError(error, context) }),\n\t\t)\n\n\t\tconst first = await Promise.race([request, pump])\n\t\tif (first.type === 'pump-error') {\n\t\t\tabortController.abort()\n\t\t\tuploadStream.destroy()\n\t\t\tawait request\n\t\t\tthrow first.error\n\t\t}\n\t\tif (first.type === 'request-error') {\n\t\t\tabortController.abort()\n\t\t\tuploadStream.destroy()\n\t\t\tawait pump\n\t\t\tthrow first.error\n\t\t}\n\t\tconst requestResult = first.type === 'response' ? first : await request\n\t\tif (requestResult.type === 'request-error') {\n\t\t\tthrow requestResult.error\n\t\t}\n\t\tconst response = requestResult.response\n\t\tif (!response.ok) {\n\t\t\tabortController.abort()\n\t\t\tuploadStream.destroy()\n\t\t\tawait pump\n\t\t\tawait cancelResponseBody(response)\n\t\t\tthrow toHttpTransportError(\n\t\t\t\t{ status: response.status, retryAfter: response.headers.get('retry-after') },\n\t\t\t\tcontext,\n\t\t\t)\n\t\t}\n\t\tconst pumpResult = await pump\n\t\tif (pumpResult.type === 'pump-error') {\n\t\t\tthrow pumpResult.error\n\t\t}\n\t\tawait assertImportResult(response)\n\t}\n\n\tdataExport = async ({ project: { name: project, token, endpoint: baseUrl }, gzip, includeSystem, excludeTables }: {\n\t\tproject: RemoteProject\n\t\texcludeTables?: string[]\n\t\tincludeSystem: boolean\n\t\tgzip: boolean\n\t}): Promise<DataExportResponse> => {\n\t\tconst context = transferContext('Export', baseUrl)\n\t\tlet response: Response\n\t\ttry {\n\t\t\tresponse = await fetch(`${baseUrl}/export`, {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': `Bearer ${token}`,\n\t\t\t\t\t'Accept-Encoding': gzip ? 'gzip' : 'identity',\n\t\t\t\t\t'Content-type': 'application/json',\n\t\t\t\t},\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tprojects: [{ slug: project, system: includeSystem, excludeTables }],\n\t\t\t\t}),\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthrow toTransportError(error, context)\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tawait cancelResponseBody(response)\n\t\t\tthrow toHttpTransportError(\n\t\t\t\t{ status: response.status, retryAfter: response.headers.get('retry-after') },\n\t\t\t\tcontext,\n\t\t\t)\n\t\t}\n\t\treturn response\n\t}\n}\n\nexport const toDataExportStream = (response: DataExportResponse): Readable => {\n\tif (!response.body) {\n\t\tthrow new CliError('Export response does not contain a readable stream', {\n\t\t\tcode: 'TRANSFER_EXPORT_INVALID_RESPONSE',\n\t\t\texitCode: ExitCode.InternalError,\n\t\t\tdetails: { operation: 'export' },\n\t\t})\n\t}\n\treturn response.body instanceof Readable ? response.body : new WebResponseReadable(response.body)\n}\n\nexport const toDataTransferStreamError = (operation: 'Import' | 'Export', cause: unknown): CliError => transferStreamError(operation, cause)\n"],"names":["CliError","ExitCode","stream","Readable","LineTransform","PassThrough","pipeline","createGzip","response","toTransportError","toHttpTransportError"],"mappings":";;;;;;;;;;;AAQA,MAAM,kBAAkB,CAAC,QAA6B,cAAsB;AAAA,EAC3E,SAAS,QAAQ,OAAO,YAAA,CAAa;AAAA,EACrC,YAAY,YAAY,OAAO,YAAA,CAAa;AAAA,EAC5C,KAAK,GAAG,QAAQ,IAAI,OAAO,aAAa;AACzC;AAEA,MAAM,sBAAsB,CAAC,QAA6B,UACzD,IAAIA,UAAAA,SAAS,GAAG,MAAM,kBAAkB;AAAA,EACvC,MAAM,YAAY,OAAO,YAAA,CAAa;AAAA,EACtC,UAAUC,UAAAA,SAAS;AAAA,EACnB,SAAS,EAAE,WAAW,OAAO,cAAY;AAAA,EACzC;AACD,CAAC;AAUF,MAAM,2CAAgD,IAAyB;AAAA,EAC9E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,CAAC;AAED,MAAM,wBAAwB,CAAC,UAAgD,qBAAqB,IAAI,KAAK;AAO7G,MAAM,qBAAqB,CAAC,SAAgC;AAC3D,QAAM,QAAiB,KAAK,MAAM,IAAI;AACtC,MAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,OAAO,MAAM,CAAC,MAAM,UAAU;AAC1D,UAAM,uBAAuB,iCAAiC;AAAA,EAC/D;AACA,MAAI,CAAC,sBAA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AAE,SAAS,EAAE,MAAM,SAAS,OAAO,UAAU,QAAA,GAAW,MAAM,eAAe,oBAK9D;AAClC,YAAM,UAAU,gBAAgB,UAAU,OAAO;AACjD,UAAI;AACJ,UAAI;AACH,mBAAW,MAAM,MAAM,GAAG,OAAO,WAAW;AAAA,UAC3C,SAAS;AAAA,YACR,iBAAiB,UAAU,KAAK;AAAA,YAChC,mBAAmB,OAAO,SAAS;AAAA,YACnC,gBAAgB;AAAA,UAAA;AAAA,UAEjB,QAAQ;AAAA,UACR,MAAM,KAAK,UAAU;AAAA,YACpB,UAAU,CAAC,EAAE,MAAM,SAAS,QAAQ,eAAe,eAAe;AAAA,UAAA,CAClE;AAAA,QAAA,CACD;AAAA,MACF,SAAS,OAAO;AACf,cAAMD,eAAAA,iBAAiB,OAAO,OAAO;AAAA,MACtC;AACA,UAAI,CAAC,SAAS,IAAI;AACjB,cAAM,mBAAmB,QAAQ;AACjC,cAAMC,eAAAA;AAAAA,UACL,EAAE,QAAQ,SAAS,QAAQ,YAAY,SAAS,QAAQ,IAAI,aAAa,EAAA;AAAA,UACzE;AAAA,QAAA;AAAA,MAEF;AACA,aAAO;AAAA,IACR,CAAA;AAAA,EAAA;AACD;AAEO,MAAM,qBAAqB,CAAC,aAA2C;AAC7E,MAAI,CAAC,SAAS,MAAM;AACnB,UAAM,IAAIV,UAAAA,SAAS,sDAAsD;AAAA,MACxE,MAAM;AAAA,MACN,UAAUC,UAAAA,SAAS;AAAA,MACnB,SAAS,EAAE,WAAW,SAAA;AAAA,IAAS,CAC/B;AAAA,EACF;AACA,SAAO,SAAS,gBAAgBE,uBAAW,SAAS,OAAO,IAAI,oBAAoB,SAAS,IAAI;AACjG;AAEO,MAAM,4BAA4B,CAAC,WAAgC,UAA6B,oBAAoB,WAAW,KAAK;;;;"}
|
|
1
|
+
{"version":3,"file":"DataTransferClient.cjs","sources":["../../../../../../packages/cli/src/lib/transfer/DataTransferClient.ts"],"sourcesContent":["import { CliError, ExitCode } from '@contember/cli-common'\nimport { LineTransform } from '../stream.js'\nimport { PassThrough, Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport { createGzip } from 'node:zlib'\nimport { RemoteProject } from '../project/RemoteProject.js'\nimport { toHttpTransportError, toTransportError } from '../errors/TransportError.js'\n\nconst transferContext = (action: 'Import' | 'Export', endpoint: string) => ({\n\tservice: `Data ${action.toLowerCase()}`,\n\tcodePrefix: `TRANSFER_${action.toUpperCase()}`,\n\turl: `${endpoint}/${action.toLowerCase()}`,\n})\n\nconst transferStreamError = (action: 'Import' | 'Export', cause: unknown): CliError =>\n\tnew CliError(`${action} stream failed`, {\n\t\tcode: `TRANSFER_${action.toUpperCase()}_STREAM_FAILED`,\n\t\texitCode: ExitCode.InputError,\n\t\tdetails: { operation: action.toLowerCase() },\n\t\tcause,\n\t})\n\ntype TransferCommandName =\n\t| 'importSystemSchemaBegin'\n\t| 'importContentSchemaBegin'\n\t| 'importSequence'\n\t| 'insertBegin'\n\t| 'insertRow'\n\t| 'insertEnd'\n\nconst transferCommandNames: ReadonlySet<string> = new Set<TransferCommandName>([\n\t'importSystemSchemaBegin',\n\t'importContentSchemaBegin',\n\t'importSequence',\n\t'insertBegin',\n\t'insertRow',\n\t'insertEnd',\n])\n\nconst isTransferCommandName = (value: string): value is TransferCommandName => transferCommandNames.has(value)\n\ninterface TransferEvent {\n\treadonly name: TransferCommandName\n\treadonly payload?: Record<string, unknown>\n}\n\nconst parseTransferEvent = (line: string): TransferEvent => {\n\tconst value: unknown = JSON.parse(line)\n\tif (!Array.isArray(value) || typeof value[0] !== 'string') {\n\t\tthrow invalidTransferCommand('TRANSFER_IMPORT_INVALID_COMMAND')\n\t}\n\tif (!isTransferCommandName(value[0])) {\n\t\tthrow invalidTransferCommand('TRANSFER_IMPORT_UNKNOWN_COMMAND')\n\t}\n\tconst payload = value[1]\n\treturn {\n\t\tname: value[0],\n\t\t...(typeof payload === 'object' && payload !== null && !Array.isArray(payload) ? { payload } : {}),\n\t}\n}\n\nconst invalidTransferCommand = (code: 'TRANSFER_IMPORT_INVALID_COMMAND' | 'TRANSFER_IMPORT_UNKNOWN_COMMAND'): CliError =>\n\tnew CliError('Import stream contains an unsupported command', {\n\t\tcode,\n\t\texitCode: ExitCode.InputError,\n\t\tdetails: { operation: 'import' },\n\t})\n\nconst normalizeImportStreamError = (cause: unknown): CliError => {\n\tif (\n\t\tcause instanceof CliError\n\t\t&& (cause.code === 'TRANSFER_IMPORT_INVALID_COMMAND' || cause.code === 'TRANSFER_IMPORT_UNKNOWN_COMMAND')\n\t) {\n\t\treturn cause\n\t}\n\treturn transferStreamError('Import', cause)\n}\n\nconst requireEventPayload = (event: TransferEvent): Record<string, unknown> => {\n\tif (event.payload === undefined) {\n\t\tthrow new Error(`Transfer event ${event.name} has no payload`)\n\t}\n\treturn event.payload\n}\n\nconst toBytes = (chunk: unknown): Uint8Array => {\n\tif (typeof chunk === 'string') {\n\t\treturn Buffer.from(chunk)\n\t}\n\tif (chunk instanceof Uint8Array) {\n\t\treturn chunk\n\t}\n\tthrow transferStreamError('Import', new Error('Unsupported stream chunk'))\n}\n\nconst toUploadStream = (stream: Readable): ReadableStream<Uint8Array> => {\n\tconst iterator: AsyncIterator<unknown> = stream[Symbol.asyncIterator]()\n\treturn new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst next = await iterator.next()\n\t\t\t\tif (next.done) {\n\t\t\t\t\tcontroller.close()\n\t\t\t\t} else {\n\t\t\t\t\tcontroller.enqueue(toBytes(next.value))\n\t\t\t\t}\n\t\t\t} catch (cause) {\n\t\t\t\tcontroller.error(transferStreamError('Import', cause))\n\t\t\t}\n\t\t},\n\t\tasync cancel() {\n\t\t\tstream.destroy()\n\t\t\ttry {\n\t\t\t\tawait iterator.return?.()\n\t\t\t} catch {\n\t\t\t\t// Stream cleanup must not replace the primary transfer error.\n\t\t\t}\n\t\t},\n\t})\n}\n\nclass WebResponseReadable extends Readable {\n\tprivate readonly reader: ReadableStreamDefaultReader<Uint8Array>\n\tprivate reading = false\n\tprivate released = false\n\n\tconstructor(stream: ReadableStream<Uint8Array>) {\n\t\tsuper()\n\t\tthis.reader = stream.getReader()\n\t}\n\n\tpublic override _read(): void {\n\t\tif (this.reading || this.destroyed) {\n\t\t\treturn\n\t\t}\n\t\tthis.reading = true\n\t\tvoid this.readNext()\n\t}\n\n\tpublic override _destroy(error: Error | null, callback: (error?: Error | null) => void): void {\n\t\tthis.cancelReader().then(\n\t\t\t() => callback(error),\n\t\t\t() => callback(error),\n\t\t)\n\t}\n\n\tprivate async readNext(): Promise<void> {\n\t\ttry {\n\t\t\tconst next = await this.reader.read()\n\t\t\tif (this.destroyed) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (next.done) {\n\t\t\t\tthis.releaseReader()\n\t\t\t\tthis.push(null)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.reading = false\n\t\t\tif (this.push(next.value)) {\n\t\t\t\tthis._read()\n\t\t\t}\n\t\t} catch (cause) {\n\t\t\tthis.destroy(cause instanceof Error ? cause : new Error('Export response stream failed'))\n\t\t}\n\t}\n\n\tprivate async cancelReader(): Promise<void> {\n\t\tif (this.released) {\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tawait this.reader.cancel()\n\t\t} catch {\n\t\t\t// Stream cleanup must not replace the primary transfer error.\n\t\t} finally {\n\t\t\tthis.releaseReader()\n\t\t}\n\t}\n\n\tprivate releaseReader(): void {\n\t\tif (!this.released) {\n\t\t\tthis.released = true\n\t\t\tthis.reader.releaseLock()\n\t\t}\n\t}\n}\n\nconst cancelResponseBody = async (response: Response): Promise<void> => {\n\ttry {\n\t\tawait response.body?.cancel()\n\t} catch {\n\t\t// The HTTP classification is the primary error.\n\t}\n}\n\nconst assertImportResult = async (response: Response): Promise<void> => {\n\tlet body: unknown\n\ttry {\n\t\tbody = await response.json()\n\t} catch (cause) {\n\t\tthrow new CliError('Import returned an invalid response', {\n\t\t\tcode: 'TRANSFER_IMPORT_INVALID_RESPONSE',\n\t\t\texitCode: ExitCode.InternalError,\n\t\t\tdetails: { operation: 'import' },\n\t\t\tcause,\n\t\t})\n\t}\n\tif (typeof body === 'object' && body !== null && 'ok' in body && body.ok === true) {\n\t\treturn\n\t}\n\tthrow new CliError('Import failed', {\n\t\tcode: 'IMPORT_FAILED',\n\t\texitCode: ExitCode.InputError,\n\t\tdetails: { operation: 'import' },\n\t})\n}\n\nexport interface DataExportResponse {\n\treadonly body: ReadableStream<Uint8Array> | Readable | null\n}\n\ntype ImportRequestOutcome =\n\t| { readonly type: 'response'; readonly response: Response }\n\t| { readonly type: 'request-error'; readonly error: CliError }\n\ntype ImportPumpOutcome =\n\t| { readonly type: 'pump-complete' }\n\t| { readonly type: 'pump-error'; readonly error: CliError }\n\ninterface StreamingRequestInit extends RequestInit {\n\treadonly duplex: 'half'\n}\n\nexport class DataTransferClient {\n\tdataImport = async ({ printProgress, stream, project, gzip }: {\n\t\tstream: Readable\n\t\tproject: RemoteProject\n\t\tprintProgress: (message: string) => void\n\t\tgzip: boolean\n\t}): Promise<void> => {\n\t\tlet table = ''\n\t\tlet rowCount = 0\n\t\tlet rowTotal = 0\n\t\tlet transferred = 0\n\t\tlet start = Date.now()\n\t\tconst transformedStream = new LineTransform(line => {\n\t\t\ttransferred += line.length + 1\n\t\t\tif (line === '') {\n\t\t\t\treturn ''\n\t\t\t}\n\t\t\tconst event = parseTransferEvent(line)\n\t\t\tswitch (event.name) {\n\t\t\t\tcase 'importSystemSchemaBegin':\n\t\t\t\t\treturn JSON.stringify([event.name, { ...requireEventPayload(event), project: project.name }])\n\t\t\t\tcase 'importContentSchemaBegin':\n\t\t\t\t\treturn JSON.stringify([event.name, { ...requireEventPayload(event), project: project.name }])\n\t\t\t\tcase 'importSequence':\n\t\t\t\t\tbreak\n\t\t\t\tcase 'insertBegin':\n\t\t\t\t\tif (typeof event.payload?.table !== 'string') {\n\t\t\t\t\t\tthrow new Error('Insert event has no table')\n\t\t\t\t\t}\n\t\t\t\t\ttable = event.payload.table\n\t\t\t\t\trowCount = 0\n\t\t\t\t\tbreak\n\t\t\t\tcase 'insertRow':\n\t\t\t\t\trowCount++\n\t\t\t\t\trowTotal++\n\t\t\t\t\tbreak\n\t\t\t\tcase 'insertEnd':\n\t\t\t\t\tbreak\n\t\t\t}\n\t\t\tif ((rowCount % 1000) === 0 || event.name !== 'insertRow') {\n\t\t\t\tconst mbs = Math.floor(transferred / 1024 / 1024).toString()\n\t\t\t\tconst durationS = Math.floor((Date.now() - start) / 1000)\n\t\t\t\tprintProgress(`transferred ${mbs} MiB; inserted ${rowCount} ${table} rows, ${rowTotal} total; ${durationS} seconds`)\n\t\t\t}\n\t\t\treturn line\n\t\t})\n\t\tconst uploadStream = new PassThrough()\n\t\tconst abortController = new AbortController()\n\t\tconst rawPump = gzip\n\t\t\t? pipeline(stream, transformedStream, createGzip(), uploadStream)\n\t\t\t: pipeline(stream, transformedStream, uploadStream)\n\t\tconst context = transferContext('Import', project.endpoint)\n\t\tconst requestInit: StreamingRequestInit = {\n\t\t\theaders: {\n\t\t\t\t'Authorization': `Bearer ${project.token}`,\n\t\t\t\t'Content-type': 'application/x-ndjson',\n\t\t\t\t...(gzip ? { 'Content-Encoding': 'gzip' } : {}),\n\t\t\t},\n\t\t\tmethod: 'POST',\n\t\t\tbody: toUploadStream(uploadStream),\n\t\t\tduplex: 'half',\n\t\t\tsignal: abortController.signal,\n\t\t}\n\t\tconst rawRequest = fetch(`${project.endpoint}/import`, requestInit)\n\t\tconst pump: Promise<ImportPumpOutcome> = rawPump.then(\n\t\t\t() => ({ type: 'pump-complete' }),\n\t\t\tcause => {\n\t\t\t\tabortController.abort()\n\t\t\t\treturn { type: 'pump-error', error: normalizeImportStreamError(cause) }\n\t\t\t},\n\t\t)\n\t\tconst request: Promise<ImportRequestOutcome> = rawRequest.then(\n\t\t\tresponse => ({ type: 'response', response }),\n\t\t\terror => ({ type: 'request-error', error: toTransportError(error, context) }),\n\t\t)\n\n\t\tconst first = await Promise.race([request, pump])\n\t\tif (first.type === 'pump-error') {\n\t\t\tabortController.abort()\n\t\t\tuploadStream.destroy()\n\t\t\tawait request\n\t\t\tthrow first.error\n\t\t}\n\t\tif (first.type === 'request-error') {\n\t\t\tabortController.abort()\n\t\t\tuploadStream.destroy()\n\t\t\tawait pump\n\t\t\tthrow first.error\n\t\t}\n\t\tconst requestResult = first.type === 'response' ? first : await request\n\t\tif (requestResult.type === 'request-error') {\n\t\t\tthrow requestResult.error\n\t\t}\n\t\tconst response = requestResult.response\n\t\tif (!response.ok) {\n\t\t\tabortController.abort()\n\t\t\tuploadStream.destroy()\n\t\t\tawait pump\n\t\t\tawait cancelResponseBody(response)\n\t\t\tthrow toHttpTransportError(\n\t\t\t\t{ status: response.status, retryAfter: response.headers.get('retry-after') },\n\t\t\t\tcontext,\n\t\t\t)\n\t\t}\n\t\tconst pumpResult = await pump\n\t\tif (pumpResult.type === 'pump-error') {\n\t\t\tthrow pumpResult.error\n\t\t}\n\t\tawait assertImportResult(response)\n\t}\n\n\tdataExport = async ({ project: { name: project, token, endpoint: baseUrl }, gzip, includeSystem, excludeTables }: {\n\t\tproject: RemoteProject\n\t\texcludeTables?: string[]\n\t\tincludeSystem: boolean\n\t\tgzip: boolean\n\t}): Promise<DataExportResponse> => {\n\t\tconst context = transferContext('Export', baseUrl)\n\t\tlet response: Response\n\t\ttry {\n\t\t\tresponse = await fetch(`${baseUrl}/export`, {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': `Bearer ${token}`,\n\t\t\t\t\t'Accept-Encoding': gzip ? 'gzip' : 'identity',\n\t\t\t\t\t'Content-type': 'application/json',\n\t\t\t\t},\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tprojects: [{ slug: project, system: includeSystem, excludeTables }],\n\t\t\t\t}),\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthrow toTransportError(error, context)\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tawait cancelResponseBody(response)\n\t\t\tthrow toHttpTransportError(\n\t\t\t\t{ status: response.status, retryAfter: response.headers.get('retry-after') },\n\t\t\t\tcontext,\n\t\t\t)\n\t\t}\n\t\treturn response\n\t}\n}\n\nexport const toDataExportStream = (response: DataExportResponse): Readable => {\n\tif (!response.body) {\n\t\tthrow new CliError('Export response does not contain a readable stream', {\n\t\t\tcode: 'TRANSFER_EXPORT_INVALID_RESPONSE',\n\t\t\texitCode: ExitCode.InternalError,\n\t\t\tdetails: { operation: 'export' },\n\t\t})\n\t}\n\treturn response.body instanceof Readable ? response.body : new WebResponseReadable(response.body)\n}\n\nexport const toDataTransferStreamError = (operation: 'Import' | 'Export', cause: unknown): CliError => transferStreamError(operation, cause)\n"],"names":["CliError","ExitCode","stream","Readable","LineTransform","PassThrough","pipeline","createGzip","response","toTransportError","toHttpTransportError"],"mappings":";;;;;;;;;;;AAQA,MAAM,kBAAkB,CAAC,QAA6B,cAAsB;AAAA,EAC3E,SAAS,QAAQ,OAAO,YAAA,CAAa;AAAA,EACrC,YAAY,YAAY,OAAO,YAAA,CAAa;AAAA,EAC5C,KAAK,GAAG,QAAQ,IAAI,OAAO,aAAa;AACzC;AAEA,MAAM,sBAAsB,CAAC,QAA6B,UACzD,IAAIA,UAAAA,SAAS,GAAG,MAAM,kBAAkB;AAAA,EACvC,MAAM,YAAY,OAAO,YAAA,CAAa;AAAA,EACtC,UAAUC,UAAAA,SAAS;AAAA,EACnB,SAAS,EAAE,WAAW,OAAO,cAAY;AAAA,EACzC;AACD,CAAC;AAUF,MAAM,2CAAgD,IAAyB;AAAA,EAC9E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,CAAC;AAED,MAAM,wBAAwB,CAAC,UAAgD,qBAAqB,IAAI,KAAK;AAO7G,MAAM,qBAAqB,CAAC,SAAgC;AAC3D,QAAM,QAAiB,KAAK,MAAM,IAAI;AACtC,MAAI,CAAC,MAAM,QAAQ,KAAK,KAA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