@mablhq/mabl-cli 1.50.0 → 1.50.5

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.
@@ -461,51 +461,62 @@ class MablApiClient extends basicApiClient_1.BasicApiClient {
461
461
  throw toApiError(`Failed to get File Upload URL`, error);
462
462
  }
463
463
  }
464
- async getDatatables(workspaceId, limit) {
464
+ async queryDataTables(workspaceId, limit, cursor) {
465
465
  try {
466
- const datatablesQueryString = queryString.stringify({
467
- organization_id: workspaceId,
466
+ const dataTablesQueryString = queryString.stringify({
467
+ workspace_id: workspaceId,
468
468
  limit,
469
+ cursor,
469
470
  });
470
- return await this.makeGetRequest(`${this.baseApiUrl}/variables/tables?${datatablesQueryString}`).then((result) => { var _a; return (_a = result.variableTables) !== null && _a !== void 0 ? _a : []; });
471
+ return await this.makeGetRequest(`${this.baseApiUrl}/dataTables?${dataTablesQueryString}`).then((result) => result);
471
472
  }
472
473
  catch (error) {
473
- throw toApiError(`Failed to retrieve datatables`, error);
474
+ throw toApiError(`Failed to retrieve DataTables`, error);
474
475
  }
475
476
  }
476
- async getDatatable(datatableId) {
477
+ async getDataTable(dataTableId) {
477
478
  try {
478
- return await this.makeGetRequest(`${this.baseApiUrl}/variables/tables/${datatableId}`);
479
+ return await this.makeGetRequest(`${this.baseApiUrl}/dataTables/${dataTableId}`);
479
480
  }
480
481
  catch (error) {
481
- throw toApiError(`Failed to get datatable`, error);
482
+ throw toApiError(`Failed to get DataTable`, error);
482
483
  }
483
484
  }
484
- async createDatatable(workspaceId, options) {
485
+ async createDataTable(dataTableCreateRequest) {
485
486
  try {
486
- const datatablesQueryString = queryString.stringify({
487
- organization_id: workspaceId,
487
+ return await this.makePostRequest(`${this.baseApiUrl}/dataTables`, dataTableCreateRequest);
488
+ }
489
+ catch (error) {
490
+ throw toApiError(`Failed to create DataTable`, error);
491
+ }
492
+ }
493
+ async queryScenarios(dataTableId, limit, cursor) {
494
+ try {
495
+ const scenariosQueryString = queryString.stringify({
496
+ data_table_id: dataTableId,
497
+ limit,
498
+ cursor,
488
499
  });
489
- return await this.makePostRequest(`${this.baseApiUrl}/variables/tables?${datatablesQueryString}`, options).then((result) => result);
500
+ return await this.makeGetRequest(`${this.baseApiUrl}/dataTables/scenarios?${scenariosQueryString}`);
490
501
  }
491
502
  catch (error) {
492
- throw toApiError(`Failed to create datatable`, error);
503
+ throw toApiError(`Failed to get Scenarios`, error);
493
504
  }
494
505
  }
495
- async getDatatableRows(datatableId) {
506
+ async getScenario(scenarioId) {
496
507
  try {
497
- return await this.makeGetRequest(`${this.baseApiUrl}/variables/tables/${datatableId}/rows`).then((result) => { var _a; return (_a = result.variableRows) !== null && _a !== void 0 ? _a : []; });
508
+ return await this.makeGetRequest(`${this.baseApiUrl}/dataTables/scenarios/${scenarioId}`);
498
509
  }
499
510
  catch (error) {
500
- throw toApiError(`Failed to get datatable rows`, error);
511
+ throw toApiError(`Failed to get Scenario`, error);
501
512
  }
502
513
  }
503
- async getDatatableRow(datatableRowId) {
514
+ async updateDataTable(tableId, updateRequest) {
504
515
  try {
505
- return await this.makeGetRequest(`${this.baseApiUrl}/variables/rows/${datatableRowId}`);
516
+ return await this.makePatchRequest(`${this.baseApiUrl}/variables/tables/${tableId}`, updateRequest);
506
517
  }
507
518
  catch (error) {
508
- throw toApiError(`Failed to get datatable row`, error);
519
+ throw toApiError(`Failed to create DataTable`, error);
509
520
  }
510
521
  }
511
522
  async getSessionEmails(sessionId) {
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CommandArgTrainerVersion = exports.CommandArgTo = exports.CommandArgSilent = exports.CommandArgRevision = exports.CommandArgMaxHeartbeatAge = exports.CommandArgPlanId = exports.CommandArgContentTypes = exports.CommandArgPreview = exports.CommandArgOutputFilePath = exports.CommandArgOutput = exports.CommandArgNoPrompt = exports.CommandArgPrompt = exports.CommandArgPortNumber = exports.CommandArgName = exports.CommandArgMablBranchChangesOnly = exports.CommandArgMablBranch = exports.CommandArgMablAutoLogin = exports.CommandArgMablAutoBranch = exports.CommandArgLinkBypass = exports.CommandArgLinkLabel = exports.CommandArgLimitOutput = exports.CommandArgLabels = exports.CommandArgLabelsInclude = exports.CommandArgLabelsExclude = exports.CommandArgTestInteractionSpeed = exports.CommandArgTestRunId = exports.CommandArgTestFile = exports.CommandArgInput = exports.CommandArgId = exports.CommandArgUserAgent = exports.CommandArgHttpHeaders = exports.CommandArgHelp = exports.CommandArgFromPlanId = exports.CommandArgFrom = exports.CommandArgFormat = exports.CommandArgFastFailure = exports.CommandArgOverrideEnvironmentId = exports.CommandArgEnvironmentId = exports.CommandArgEnableLink = exports.CommandArgDetailLevel = exports.CommandArgDescription = exports.CommandArgDeploymentId = exports.CommandArgDecrypt = exports.CommandArgDataTables = exports.CommandArgCredentials = exports.CommandArgBasicAuthCredentials = exports.CommandArgBrowsers = exports.CommandArgBrowser = exports.CommandArgApplicationId = exports.CommandArgApiKey = void 0;
4
- exports.SCENARIO_NAME_HEADER = exports.ValidBrowserTypesForLocalRuns = exports.BrowserTypeSelections = exports.DefaultBrowserType = exports.DefaultBranchName = exports.DefaultOutputFormatChoices = exports.DetailLevelFormats = exports.ReporterOptions = exports.OutputFormats = exports.CommandArgAliases = exports.CommandArgBrowserEnableExtensions = exports.CommandArgBrowserIgnoreCertificateErrors = exports.CommandArgBrowserDisableIsolation = exports.ListTimeFormat = exports.CommandArgReporterOptions = exports.CommandArgReporter = exports.CommandArgWorkspaceId = exports.CommandArgVersion = exports.CommandArgVariables = exports.CommandArgUrlApi = exports.CommandArgUrlApp = exports.CommandArgUrl = void 0;
4
+ exports.SCENARIO_ID_HEADER = exports.SCENARIO_NAME_HEADER = exports.ValidBrowserTypesForLocalRuns = exports.BrowserTypeSelections = exports.DefaultBrowserType = exports.DefaultBranchName = exports.DefaultOutputFormatChoices = exports.DetailLevelFormats = exports.ReporterOptions = exports.OutputFormats = exports.CommandArgAliases = exports.CommandArgBrowserEnableExtensions = exports.CommandArgBrowserIgnoreCertificateErrors = exports.CommandArgBrowserDisableIsolation = exports.ListTimeFormat = exports.CommandArgReporterOptions = exports.CommandArgReporter = exports.CommandArgWorkspaceId = exports.CommandArgVersion = exports.CommandArgVariables = exports.CommandArgUrlApi = exports.CommandArgUrlApp = exports.CommandArgUrl = void 0;
5
5
  const browserTypes_1 = require("./browserTypes");
6
6
  exports.CommandArgApiKey = 'api-key';
7
7
  exports.CommandArgApplicationId = 'application-id';
@@ -125,3 +125,4 @@ exports.ValidBrowserTypesForLocalRuns = [
125
125
  browserTypes_1.BrowserType.Webkit,
126
126
  ];
127
127
  exports.SCENARIO_NAME_HEADER = 'Scenario name';
128
+ exports.SCENARIO_ID_HEADER = 'Scenario ID';
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.command = 'datatables <command>';
4
- exports.describe = 'Manage mabl datatables';
4
+ exports.describe = 'Manage mabl DataTables';
5
5
  exports.builder = (yargs) => yargs.commandDir('datatables_cmds').demandCommand();
@@ -1,40 +1,11 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
2
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.parseCsvRows = exports.parseJsonRows = void 0;
30
3
  const path_1 = require("path");
31
4
  const mablApiClientFactory_1 = require("../../../api/mablApiClientFactory");
32
5
  const util_1 = require("../../commandUtil/util");
33
6
  const constants_1 = require("../../constants");
34
- const fs = __importStar(require("fs"));
35
- const csv_parser_1 = __importDefault(require("csv-parser"));
36
7
  const describe_1 = require("../../commandUtil/describe");
37
- const csvUtil_1 = require("../../../util/csvUtil");
8
+ const utils_1 = require("../utils");
38
9
  exports.command = `create <${constants_1.CommandArgInput}>`;
39
10
  exports.describe = 'Create a new mabl DataTable';
40
11
  exports.builder = (yargs) => {
@@ -50,99 +21,41 @@ exports.builder = (yargs) => {
50
21
  })
51
22
  .option(constants_1.CommandArgName, {
52
23
  alias: 'table-name',
24
+ demandOption: false,
53
25
  describe: `The name for your new DataTable`,
54
26
  type: 'string',
55
27
  })
56
28
  .option(constants_1.CommandArgFormat, {
57
29
  alias: 'fmt',
58
- describe: `Specify the format of your input file`,
59
- choices: [constants_1.OutputFormats.Json, constants_1.OutputFormats.Csv, undefined],
30
+ demandOption: false,
31
+ describe: `Specify the format of your input file (checks file extension type by default)`,
32
+ choices: [constants_1.OutputFormats.Json, constants_1.OutputFormats.Csv],
60
33
  });
61
34
  };
62
35
  exports.handler = (0, util_1.failWrapper)(createDataTable);
63
- var AllowedExtensions;
64
- (function (AllowedExtensions) {
65
- AllowedExtensions["Csv"] = ".csv";
66
- AllowedExtensions["Json"] = ".json";
67
- })(AllowedExtensions || (AllowedExtensions = {}));
68
36
  async function createDataTable(parsed) {
69
- const input = parsed.input;
70
- const format = parsed.format || tryInferFormat(input);
71
- const name = parsed.name || (0, path_1.basename)((0, path_1.resolve)(input));
37
+ var _a, _b;
38
+ const { input } = parsed;
39
+ const format = (_a = parsed.format) !== null && _a !== void 0 ? _a : (0, utils_1.inferFileFormat)(input);
40
+ const name = (_b = parsed.name) !== null && _b !== void 0 ? _b : (0, path_1.basename)((0, path_1.resolve)(input));
72
41
  const workspaceId = await (0, util_1.getWorkspaceId)(parsed);
73
- let rows = [];
42
+ let scenarios = [];
74
43
  switch (format) {
75
44
  case constants_1.OutputFormats.Json:
76
- const jsonInput = fs.readFileSync(input, 'utf-8');
77
- rows = parseJsonRows(jsonInput);
45
+ scenarios = (0, utils_1.parseJsonScenarios)(input);
78
46
  break;
79
47
  case constants_1.OutputFormats.Csv:
80
- const csvInput = [];
81
- await new Promise((resolve) => {
82
- fs.createReadStream(input)
83
- .pipe((0, csv_parser_1.default)())
84
- .on('data', (data) => csvInput.push(data))
85
- .on('end', () => resolve());
86
- });
87
- rows = parseCsvRows(csvInput);
48
+ scenarios = await (0, utils_1.parseCsvScenarios)(input);
88
49
  break;
89
50
  default:
90
51
  throw Error(`${format} is not a valid option.`);
91
52
  }
92
- const options = {
93
- prototype: {
94
- name,
95
- organization_id: workspaceId,
96
- },
97
- mappings: rows.map((datatableRow) => ({
98
- scenario_id: datatableRow.scenario,
99
- row: datatableRow.columns.map((column) => ({
100
- name: column.name,
101
- value: column.value,
102
- })),
103
- })),
53
+ const dataTableCreateRequest = {
54
+ workspace_id: workspaceId,
55
+ data_table: { name },
56
+ scenarios,
104
57
  };
105
58
  const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
106
- const datatableRows = await apiClient.createDatatable(workspaceId, options);
107
- (0, describe_1.outputEntity)(datatableRows, constants_1.OutputFormats.Json);
108
- }
109
- function tryInferFormat(input) {
110
- const extension = (0, path_1.extname)(input);
111
- switch (extension) {
112
- case AllowedExtensions.Csv:
113
- return constants_1.OutputFormats.Csv;
114
- case AllowedExtensions.Json:
115
- return constants_1.OutputFormats.Json;
116
- default:
117
- throw new Error('No format could be inferred, please specify a format for your input data.');
118
- }
119
- }
120
- function parseJsonRows(input) {
121
- const parsedJson = JSON.parse(input);
122
- if (isDataTableRowArray(parsedJson)) {
123
- return parsedJson;
124
- }
125
- throw Error('Json input was not formatted correctly');
126
- }
127
- exports.parseJsonRows = parseJsonRows;
128
- function isDataTableRowArray(arg) {
129
- return (Array.isArray(arg) &&
130
- arg.every((row) => typeof row.scenario === 'string' &&
131
- Array.isArray(row.columns) &&
132
- row.columns.every((col) => typeof col.name === 'string' && typeof col.value === 'string')));
133
- }
134
- function parseCsvRows(input) {
135
- if (input.length === 0) {
136
- return [];
137
- }
138
- return input.map((rows) => ({
139
- scenario: (0, csvUtil_1.desanitizeCellOutput)(rows[constants_1.SCENARIO_NAME_HEADER]),
140
- columns: Object.entries(rows)
141
- .filter(([key, _]) => key !== constants_1.SCENARIO_NAME_HEADER)
142
- .map(([key, value]) => ({
143
- name: (0, csvUtil_1.desanitizeCellOutput)(key),
144
- value: (0, csvUtil_1.desanitizeCellOutput)(value),
145
- })),
146
- }));
59
+ const dataTable = await apiClient.createDataTable(dataTableCreateRequest);
60
+ (0, describe_1.outputEntity)(dataTable, constants_1.OutputFormats.Json);
147
61
  }
148
- exports.parseCsvRows = parseCsvRows;
@@ -5,13 +5,13 @@ const constants_1 = require("../../constants");
5
5
  const util_1 = require("../../commandUtil/util");
6
6
  const describe_1 = require("../../commandUtil/describe");
7
7
  exports.command = `describe <${constants_1.CommandArgId}>`;
8
- exports.describe = 'Describe a specific mabl datatable';
8
+ exports.describe = 'Describe a specific DataTable';
9
9
  exports.builder = (0, describe_1.getDescribeBuilderOptions)();
10
- exports.handler = (0, util_1.failWrapper)(getDatatable);
11
- async function getDatatable(parsed) {
10
+ exports.handler = (0, util_1.failWrapper)(describeDataTable);
11
+ async function describeDataTable(parsed) {
12
12
  const output = parsed.output;
13
- const datatableId = parsed.id;
13
+ const dataTableId = parsed.id;
14
14
  const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
15
- const datatable = await apiClient.getDatatable(datatableId);
16
- (0, describe_1.outputEntity)(datatable, output);
15
+ const dataTable = await apiClient.getDataTable(dataTableId);
16
+ (0, describe_1.outputEntity)(dataTable, output);
17
17
  }
@@ -6,70 +6,79 @@ const util_1 = require("../../commandUtil/util");
6
6
  const constants_1 = require("../../constants");
7
7
  const fileUtil_1 = require("../../commandUtil/fileUtil");
8
8
  const js_yaml_1 = require("js-yaml");
9
- const csvUtil_1 = require("../../../util/csvUtil");
10
9
  const sync_1 = require("csv-stringify/sync");
10
+ const utils_1 = require("../utils");
11
11
  exports.command = `export <${constants_1.CommandArgId}>`;
12
- exports.describe = 'Export a mabl test in a specified file format';
12
+ exports.describe = 'Export a DataTable in a specified file format';
13
13
  exports.builder = (yargs) => {
14
14
  yargs
15
15
  .positional(constants_1.CommandArgId, {
16
- describe: 'Datatable id to export',
16
+ describe: 'DataTable id to export',
17
17
  type: 'string',
18
18
  })
19
19
  .option(constants_1.CommandArgFormat, {
20
20
  alias: 'fmt',
21
21
  default: constants_1.OutputFormats.Yaml,
22
- describe: `Specify a format for the datatable export`,
22
+ describe: `Specify a format for the DataTable export`,
23
23
  choices: [constants_1.OutputFormats.Json, constants_1.OutputFormats.Yaml, constants_1.OutputFormats.Csv],
24
24
  });
25
25
  };
26
- exports.handler = (0, util_1.failWrapper)(exportDatatable);
27
- async function exportDatatable(parsed) {
28
- const datatableId = parsed.id;
26
+ exports.handler = (0, util_1.failWrapper)(exportDataTable);
27
+ async function exportDataTable(parsed) {
28
+ var _a;
29
+ const dataTableId = parsed.id;
29
30
  const format = parsed.format;
30
31
  const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
31
- const datatableRows = await apiClient.getDatatableRows(datatableId);
32
+ const scenarioQueryResult = await apiClient.queryScenarios(dataTableId);
33
+ const scenarios = (_a = scenarioQueryResult.scenarios) !== null && _a !== void 0 ? _a : [];
32
34
  let output = '';
33
35
  switch (format) {
34
36
  case constants_1.OutputFormats.Json:
35
- output = dumpToJson(datatableRows);
37
+ output = dumpToJson(scenarios);
36
38
  break;
37
39
  case constants_1.OutputFormats.Yaml:
38
- output = dumpToYaml(datatableRows);
40
+ output = dumpToYaml(scenarios);
39
41
  break;
40
42
  case constants_1.OutputFormats.Csv:
41
- output = dumpToCsv(datatableRows);
43
+ output = dumpToCsv(scenarios);
42
44
  break;
45
+ default:
46
+ throw Error(`${format} is not a valid option.`);
43
47
  }
44
- (0, fileUtil_1.writeExportedEntityToFile)(output, format, datatableId);
48
+ (0, fileUtil_1.writeExportedEntityToFile)(output, format, dataTableId);
45
49
  }
46
- function stripDatatableRows(datatableRows) {
47
- return datatableRows.map((variableRow) => ({
48
- scenario: variableRow.scenario_id,
49
- columns: variableRow.row,
50
+ function toScenarioExportFormat(scenarios) {
51
+ return scenarios.map((scenario) => ({
52
+ id: scenario.id,
53
+ name: scenario.name,
54
+ variables: scenario.variables,
50
55
  }));
51
56
  }
52
- function dumpToJson(datatableRows) {
53
- return JSON.stringify(stripDatatableRows(datatableRows), null, 2);
57
+ function dumpToJson(scenarios) {
58
+ return JSON.stringify(toScenarioExportFormat(scenarios), null, 2);
54
59
  }
55
- function dumpToYaml(datatableRows) {
56
- return (0, js_yaml_1.dump)(stripDatatableRows(datatableRows));
60
+ function dumpToYaml(scenarios) {
61
+ return (0, js_yaml_1.dump)(toScenarioExportFormat(scenarios));
57
62
  }
58
- function dumpToCsv(datatableRows) {
63
+ function dumpToCsv(scenarios) {
59
64
  const output = [];
60
- if (datatableRows.length === 0) {
65
+ if (scenarios.length === 0) {
61
66
  return '';
62
67
  }
63
68
  const headers = [
69
+ constants_1.SCENARIO_ID_HEADER,
64
70
  constants_1.SCENARIO_NAME_HEADER,
65
- ...(datatableRows[0].row || []).map((variable) => (0, csvUtil_1.sanitizeCellInput)(variable.name || '')),
71
+ ...(scenarios[0].variables || []).map((variable) => (0, utils_1.sanitizeCsvCellInput)(variable.name || '')),
66
72
  ];
67
73
  output.push(headers);
68
- datatableRows.forEach(({ scenario_id = '', row = [] }) => {
74
+ scenarios.forEach((scenario) => {
75
+ var _a;
76
+ const variables = (_a = scenario.variables) !== null && _a !== void 0 ? _a : [];
69
77
  const sanitizedRowValues = [
70
- scenario_id,
71
- ...row.map((variable) => variable.value || ''),
72
- ].map(csvUtil_1.sanitizeCellInput);
78
+ scenario.id,
79
+ scenario.name,
80
+ ...variables.map((variable) => variable.value || ''),
81
+ ].map((val) => (0, utils_1.sanitizeCsvCellInput)(val !== null && val !== void 0 ? val : ''));
73
82
  output.push(sanitizedRowValues);
74
83
  });
75
84
  return (0, sync_1.stringify)(output);
@@ -4,15 +4,15 @@ const mablApiClientFactory_1 = require("../../../api/mablApiClientFactory");
4
4
  const util_1 = require("../../commandUtil/util");
5
5
  const list_1 = require("../../commandUtil/list");
6
6
  exports.command = 'list';
7
- exports.describe = 'List your datatables';
7
+ exports.describe = 'List your DataTables';
8
8
  exports.builder = (0, list_1.getListBuilderOptions)('datatables');
9
- exports.handler = (0, util_1.failWrapper)(listDatatables);
10
- async function listDatatables(parsed) {
9
+ exports.handler = (0, util_1.failWrapper)(listDataTables);
10
+ async function listDataTables(parsed) {
11
+ var _a;
11
12
  const output = parsed.output;
12
13
  const limit = parsed.limit;
13
14
  const workspaceId = await (0, util_1.getWorkspaceId)(parsed);
14
15
  const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
15
- const datatables = await apiClient.getDatatables(workspaceId, limit);
16
- (0, list_1.outputEntities)(datatables, output);
17
- return datatables.length;
16
+ const queryResult = await apiClient.queryDataTables(workspaceId, limit);
17
+ (0, list_1.outputEntities)((_a = queryResult.dataTables) !== null && _a !== void 0 ? _a : [], output);
18
18
  }
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildUpdateRequest = void 0;
4
+ const mablApiClientFactory_1 = require("../../../api/mablApiClientFactory");
5
+ const util_1 = require("../../commandUtil/util");
6
+ const constants_1 = require("../../constants");
7
+ const pureUtil_1 = require("../../../util/pureUtil");
8
+ const utils_1 = require("../utils");
9
+ const domUtil_1 = require("../../../domUtil");
10
+ exports.command = `update <${constants_1.CommandArgId}> <${constants_1.CommandArgInput}>`;
11
+ exports.describe = 'Update a mabl DataTable';
12
+ exports.builder = (yargs) => {
13
+ yargs
14
+ .positional(constants_1.CommandArgId, {
15
+ describe: 'ID of DataTable to update',
16
+ type: 'string',
17
+ })
18
+ .positional(constants_1.CommandArgInput, {
19
+ alias: 'file',
20
+ describe: 'Relative path file to create DataTable from',
21
+ })
22
+ .option(constants_1.CommandArgWorkspaceId, {
23
+ alias: constants_1.CommandArgAliases.WorkspaceId,
24
+ describe: `Workspace your DataTable is exists in`,
25
+ type: 'string',
26
+ })
27
+ .option(constants_1.CommandArgFormat, {
28
+ alias: 'fmt',
29
+ demandOption: false,
30
+ describe: `Specify the format of your input file (checks file extension type by default)`,
31
+ choices: [constants_1.OutputFormats.Json, constants_1.OutputFormats.Csv],
32
+ });
33
+ };
34
+ exports.handler = (0, util_1.failWrapper)(updateDataTable);
35
+ async function updateDataTable(parsed) {
36
+ var _a;
37
+ const { id: dataTableId, input } = parsed;
38
+ const format = (_a = parsed.format) !== null && _a !== void 0 ? _a : (0, utils_1.inferFileFormat)(input);
39
+ const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
40
+ const dataTable = await apiClient.getDataTable(dataTableId);
41
+ let scenarios;
42
+ switch (format) {
43
+ case constants_1.OutputFormats.Json:
44
+ scenarios = (0, utils_1.parseJsonScenarios)(input);
45
+ break;
46
+ case constants_1.OutputFormats.Csv:
47
+ scenarios = await (0, utils_1.parseCsvScenarios)(input);
48
+ break;
49
+ default:
50
+ throw Error(`${format} is not a valid option.`);
51
+ }
52
+ const request = buildUpdateRequest(scenarios, dataTable);
53
+ await apiClient.updateDataTable(dataTableId, request);
54
+ }
55
+ function buildUpdateRequest(scenarios, dataTable) {
56
+ var _a, _b, _c;
57
+ if (scenarios.length === 0 || !scenarios) {
58
+ throw Error('Must have at least 1 scenario in DataTable.');
59
+ }
60
+ const validationVariables = scenarios[0].variables;
61
+ scenarios.forEach((scenario) => {
62
+ var _a, _b, _c;
63
+ if (scenario.id && !((_a = dataTable.scenario_ids) === null || _a === void 0 ? void 0 : _a.includes(scenario.id))) {
64
+ throw Error(`Scenario in input with ID ${scenario.id} does not exist in DataTable scenario_ids.`);
65
+ }
66
+ if (((_b = scenario.variables) === null || _b === void 0 ? void 0 : _b.length) === 0 || !scenario.variables) {
67
+ throw Error('Must have at least 1 variable in a scenario.');
68
+ }
69
+ if (scenario.variables.length !== (validationVariables === null || validationVariables === void 0 ? void 0 : validationVariables.length)) {
70
+ throw Error('All scenarios must have the same number of variables.');
71
+ }
72
+ (_c = scenario.variables) === null || _c === void 0 ? void 0 : _c.forEach((variable, index) => {
73
+ if (!(0, domUtil_1.isValidUserVariableName)(variable.name)) {
74
+ throw Error(`Invalid variable name: ${variable.name}. Variable names must start with a letter or underscore (_) followed by letters, numbers, and underscores and cannot be "user", "web", or "mail"`);
75
+ }
76
+ if (variable.name !== validationVariables[index].name) {
77
+ throw Error('All scenarios must have the same variable names and be in the same order.');
78
+ }
79
+ });
80
+ });
81
+ const parsedScenarioMap = scenarios
82
+ .filter((scenario) => scenario.id !== undefined)
83
+ .reduce((acc, scenario) => {
84
+ acc[scenario.id] = scenario;
85
+ return acc;
86
+ }, {});
87
+ const updatedRows = ((_a = dataTable.scenario_ids) === null || _a === void 0 ? void 0 : _a.filter((id) => parsedScenarioMap[id] !== undefined).map((id) => {
88
+ const variableRow = (0, utils_1.scenarioAsVariableRow)(parsedScenarioMap[id]);
89
+ return {
90
+ id: variableRow.id || '',
91
+ scenario_id: variableRow.scenario_id || '',
92
+ row: variableRow.row || [],
93
+ };
94
+ }).filter(pureUtil_1.isDefined)) || [];
95
+ const updatedRowIds = updatedRows
96
+ .map((row) => row.id)
97
+ .filter(pureUtil_1.isDefined);
98
+ const addedRows = scenarios
99
+ .filter((row) => row.id === undefined)
100
+ .map((scenario) => {
101
+ const variableRow = (0, utils_1.scenarioAsVariableRow)(scenario);
102
+ return {
103
+ id: variableRow.id,
104
+ scenario_id: variableRow.scenario_id,
105
+ row: variableRow.row,
106
+ };
107
+ });
108
+ const deletedRowIds = (_c = (_b = dataTable.scenario_ids) === null || _b === void 0 ? void 0 : _b.filter((id) => !updatedRowIds.includes(id))) !== null && _c !== void 0 ? _c : [];
109
+ const prototype = {
110
+ ...(0, utils_1.dataTableAsVariableTable)(dataTable),
111
+ row_ids: updatedRows.map((row) => row.id).filter(pureUtil_1.isDefined),
112
+ };
113
+ return {
114
+ prototype,
115
+ updatedRows,
116
+ deletedRowIds,
117
+ addedRows,
118
+ };
119
+ }
120
+ exports.buildUpdateRequest = buildUpdateRequest;