@microsoft/connected-workbooks 2.1.24-beta → 3.0.0

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.
Files changed (46) hide show
  1. package/README.md +25 -13
  2. package/dist/generators.js +1 -1
  3. package/dist/{GridParser.js → gridParser.js} +18 -8
  4. package/dist/gridUtils.js +58 -0
  5. package/dist/index.d.ts +2 -2
  6. package/dist/src/generators.js +14 -0
  7. package/dist/src/types.js +28 -0
  8. package/dist/src/utils/arrayUtils.js +46 -0
  9. package/dist/src/utils/constants.js +145 -0
  10. package/dist/src/utils/documentUtils.js +102 -0
  11. package/dist/src/utils/gridUtils.js +103 -0
  12. package/dist/src/utils/htmlUtils.js +19 -0
  13. package/dist/src/utils/index.js +24 -0
  14. package/dist/src/utils/mashupDocumentParser.js +145 -0
  15. package/dist/src/utils/pqUtils.js +100 -0
  16. package/dist/src/utils/tableUtils.js +143 -0
  17. package/dist/src/utils/xmlInnerPartsUtils.js +227 -0
  18. package/dist/src/utils/xmlPartsUtils.js +68 -0
  19. package/dist/src/workbookTemplate.js +7 -0
  20. package/dist/tests/arrayUtils.test.js +65 -0
  21. package/dist/tests/documentUtils.test.js +35 -0
  22. package/dist/tests/gridUtils.test.js +168 -0
  23. package/dist/tests/htmlUtils.test.js +109 -0
  24. package/dist/tests/mashupDocumentParser.test.js +59 -0
  25. package/dist/tests/mocks/PqMock.js +7 -0
  26. package/dist/tests/mocks/index.js +24 -0
  27. package/dist/tests/mocks/section1mSimpleQueryMock.js +18 -0
  28. package/dist/tests/mocks/xmlMocks.js +12 -0
  29. package/dist/tests/tableUtils.test.js +63 -0
  30. package/dist/tests/workbookQueryTemplate.test.js +64 -0
  31. package/dist/tests/workbookTableTemplate.test.js +54 -0
  32. package/dist/tests/xmlInnerPartsUtils.test.js +51 -0
  33. package/dist/types.d.ts +4 -1
  34. package/dist/utils/constants.js +20 -9
  35. package/dist/utils/documentUtils.js +9 -5
  36. package/dist/utils/gridUtils.js +103 -0
  37. package/dist/utils/htmlUtils.js +3 -3
  38. package/dist/utils/index.js +5 -1
  39. package/dist/utils/mashupDocumentParser.js +6 -24
  40. package/dist/utils/pqUtils.js +7 -4
  41. package/dist/utils/tableUtils.js +18 -19
  42. package/dist/utils/xmlInnerPartsUtils.js +38 -9
  43. package/dist/utils/xmlPartsUtils.js +12 -6
  44. package/dist/workbookManager.d.ts +3 -3
  45. package/dist/workbookManager.js +17 -22
  46. package/package.json +5 -3
package/README.md CHANGED
@@ -1,7 +1,6 @@
1
1
  # Connected Workbooks
2
2
  [![Build Status](https://obilshield.visualstudio.com/ConnectedWorkbooks/_apis/build/status/microsoft.connected-workbooks?branchName=main)](https://obilshield.visualstudio.com/ConnectedWorkbooks/_build/latest?definitionId=14&branchName=main)
3
3
  [![License](https://img.shields.io/github/license/microsoft/connected-workbooks)](https://github.com/microsoft/connected-workbooks/blob/master/LICENSE)
4
- [![Snyk Vulnerabilities](https://img.shields.io/snyk/vulnerabilities/github/microsoft/connected-workbooks)](https://snyk.io/test/github/microsoft/connected-workbooks)
5
4
 
6
5
  A pure JS library, Microsoft backed, that provides xlsx workbook generation capabilities, allowing for:
7
6
  1. Fundemental **"Export to Excel"** capabilities for tabular data (landing in a table in Excel).
@@ -31,12 +30,12 @@ workbookManager.downloadWorkbook(blob, "MyTable.xlsx");
31
30
  ```
32
31
 
33
32
  ### 2. Export a table from raw data:
34
- ```
33
+ ```typescript
35
34
  import workbookManager from '@microsoft/connected-workbooks';
36
35
 
37
36
  const grid = {
38
- "promoteHeaders": true,
39
- "data": [
37
+ config: { promoteHeaders:true, adjustColumnNames:true }
38
+ data: [
40
39
  ["Product", "Price", "InStock", "Category", "Date"],
41
40
  ["Widget A", 19.99, true, "Electronics", "10/26/2024"],
42
41
  ["Gizmo B", 9.99, true, "Accessories", "10/26/2024"],
@@ -52,11 +51,17 @@ workbookManager.downloadWorkbook(blob, "MyTable.xlsx");
52
51
 
53
52
  ### 3. Control Document Properties:
54
53
  ```typescript
55
- const blob = await workbookManager.generateTableWorkbookFromHtml(
56
- document.querySelector('table') as HTMLTableElement,
57
- {createdBy: 'John Doe', lastModifiedBy: 'Jane Doe', description: 'This is a sample table'});
54
+ const blob = await workbookManager.generateTableWorkbookFromHtml(
55
+ document.querySelector('table') as HTMLTableElement, {
56
+ docProps: {
57
+ createdBy: 'John Doe',
58
+ lastModifiedBy: 'Jane Doe',
59
+ description: 'This is a sample table'
60
+ }
61
+ }
62
+ );
58
63
 
59
- workbookManager.downloadWorkbook(blob, "MyTable.xlsx");
64
+ workbookManager.downloadWorkbook(blob, "MyTable.xlsx");
60
65
  ```
61
66
  ![image](https://github.com/microsoft/connected-workbooks/assets/7674478/c267c9eb-6367-419d-832d-5a835c7683f9)
62
67
 
@@ -69,7 +74,9 @@ const blob = await workbookManager.generateSingleQueryWorkbook({
69
74
  Source = {1..10} \
70
75
  in \
71
76
  Source',
72
- refreshOnOpen: true});
77
+ refreshOnOpen: true
78
+ });
79
+
73
80
  workbookManager.downloadWorkbook(blob, "MyConnectedWorkbook.xlsx");
74
81
  ```
75
82
  ![image](https://github.com/microsoft/connected-workbooks/assets/7674478/57bd986c-6309-4963-8d86-911ccf496c3f)
@@ -127,7 +134,7 @@ async function `generateTableWorkbookFromHtml`: `Promise<Blob>`
127
134
  |Parameter | Type | Required | Description |
128
135
  |--- |--- |--- |--- |
129
136
  | htmlTable | HTMLTableElement | __required__ | Initial data loaded to workbook |
130
- | docProps | [DocProps](#docprops) | optional | Custom workbook properties |
137
+ | fileConfigs | [FileConfigs](#fileconfigs) | optional | Custom file configurations |
131
138
 
132
139
  #### 3. Generate a table workbook with raw data
133
140
  ```typescript
@@ -137,7 +144,7 @@ async function `generateTableWorkbookFromGrid`: `Promise<Blob>`
137
144
  |Parameter | Type | Required | Description |
138
145
  |--- |--- |--- |--- |
139
146
  | grid | [Grid](#grid) | __required__ | Initial data loaded to workbook |
140
- | docProps | [DocProps](#docprops) | optional | Custom workbook properties |
147
+ | fileConfigs | [FileConfigs](#fileconfigs) | optional | Custom file configurations |
141
148
  </br>
142
149
 
143
150
  ### Types
@@ -152,9 +159,14 @@ async function `generateTableWorkbookFromGrid`: `Promise<Blob>`
152
159
  #### Grid
153
160
  |Parameter | Type | Required | Description |
154
161
  |---|---|---|---|
155
- | data | (string | number | boolean)[][] | __required__ | Grid data
156
- | promoteHeaders | boolean | optional | Should first row of gridData be used as the header, defaults to false - generating "Column1", "Column2"...
162
+ | data | (string \| number \| boolean)[][] | __required__ | Grid data
163
+ | config | GridConfig | optional | customizations to Grid handling (see GridConfig)
157
164
 
165
+ #### GridConfig
166
+ |Parameter | Type | Required | Description |
167
+ |---|---|---|---|
168
+ | promoteHeaders | boolean | optional | Should first row of gridData be used as the header, defaults to false - generating "Column1", "Column2"...
169
+ | adjustColumnNames | boolean | optional | Should column names be adjusted to be valid Excel names (Fix duplicates for example), defaults to true
158
170
 
159
171
  #### FileConfigs
160
172
  |Parameter | Type | Required | Description |
@@ -7,7 +7,7 @@ const generateMashupXMLTemplate = (base64) => `<?xml version="1.0" encoding="utf
7
7
  exports.generateMashupXMLTemplate = generateMashupXMLTemplate;
8
8
  const generateSingleQueryMashup = (queryName, query) => `section Section1;
9
9
 
10
- shared ${queryName} =
10
+ shared #"${queryName}" =
11
11
  ${query};`;
12
12
  exports.generateSingleQueryMashup = generateSingleQueryMashup;
13
13
  const generateCustomXmlFilePath = (i) => `customXml/item${i}.xml`;
@@ -1,7 +1,10 @@
1
1
  "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
2
4
  Object.defineProperty(exports, "__esModule", { value: true });
3
5
  exports.parseToTableData = void 0;
4
6
  const constants_1 = require("./utils/constants");
7
+ const utils_1 = require("./utils");
5
8
  const parseToTableData = (grid) => {
6
9
  if (!grid) {
7
10
  return undefined;
@@ -12,12 +15,13 @@ const parseToTableData = (grid) => {
12
15
  };
13
16
  exports.parseToTableData = parseToTableData;
14
17
  const parseGridRows = (grid) => {
18
+ var _a, _b;
15
19
  const gridData = grid.data;
16
20
  if (!gridData) {
17
21
  throw new Error(constants_1.gridNotFoundErr);
18
22
  }
19
23
  const rows = [];
20
- if (!grid.promoteHeaders) {
24
+ if (!((_a = grid.config) === null || _a === void 0 ? void 0 : _a.promoteHeaders)) {
21
25
  const row = [];
22
26
  for (const prop in gridData[0]) {
23
27
  const cellValue = gridData[0][prop];
@@ -30,19 +34,25 @@ const parseGridRows = (grid) => {
30
34
  const row = [];
31
35
  for (const prop in rowData) {
32
36
  const cellValue = rowData[prop];
33
- row.push(cellValue.toString());
37
+ row.push((_b = cellValue === null || cellValue === void 0 ? void 0 : cellValue.toString()) !== null && _b !== void 0 ? _b : "");
34
38
  }
35
39
  rows.push(row);
36
40
  }
37
41
  return rows;
38
42
  };
39
43
  const generateColumnNames = (grid) => {
40
- if (grid.promoteHeaders) {
41
- return grid.data[0].map((columnName) => columnName.toString());
42
- }
44
+ var _a;
43
45
  const columnNames = [];
44
- for (let i = 0; i < grid.data[0].length; i++) {
45
- columnNames.push(`Column ${i + 1}`);
46
+ if (!((_a = grid.config) === null || _a === void 0 ? void 0 : _a.promoteHeaders)) {
47
+ for (let i = 0; i < grid.data[0].length; i++) {
48
+ columnNames.push(`${constants_1.defaults.columnName} ${i + 1}`);
49
+ }
50
+ return columnNames;
51
+ }
52
+ // We are adjusting column names by default.
53
+ if (!grid.config || grid.config.adjustColumnNames === undefined || grid.config.adjustColumnNames) {
54
+ return utils_1.tableUtils.getAdjustedColumnNames(grid.data[0]);
46
55
  }
47
- return columnNames;
56
+ // Get column names and failed if it's not a legal name.
57
+ return utils_1.tableUtils.getRawColumnNames(grid.data[0]);
48
58
  };
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.parseToTableData = void 0;
6
+ const constants_1 = require("./utils/constants");
7
+ const utils_1 = require("./utils");
8
+ const parseToTableData = (grid) => {
9
+ if (!grid) {
10
+ return undefined;
11
+ }
12
+ const columnNames = generateColumnNames(grid);
13
+ const rows = parseGridRows(grid);
14
+ return { columnNames: columnNames, rows: rows };
15
+ };
16
+ exports.parseToTableData = parseToTableData;
17
+ const parseGridRows = (grid) => {
18
+ var _a, _b;
19
+ const gridData = grid.data;
20
+ if (!gridData) {
21
+ throw new Error(constants_1.gridNotFoundErr);
22
+ }
23
+ const rows = [];
24
+ if (!((_a = grid.config) === null || _a === void 0 ? void 0 : _a.promoteHeaders)) {
25
+ const row = [];
26
+ for (const prop in gridData[0]) {
27
+ const cellValue = gridData[0][prop];
28
+ row.push(cellValue.toString());
29
+ }
30
+ rows.push(row);
31
+ }
32
+ for (let i = 1; i < gridData.length; i++) {
33
+ const rowData = gridData[i];
34
+ const row = [];
35
+ for (const prop in rowData) {
36
+ const cellValue = rowData[prop];
37
+ row.push((_b = cellValue === null || cellValue === void 0 ? void 0 : cellValue.toString()) !== null && _b !== void 0 ? _b : "");
38
+ }
39
+ rows.push(row);
40
+ }
41
+ return rows;
42
+ };
43
+ const generateColumnNames = (grid) => {
44
+ var _a;
45
+ const columnNames = [];
46
+ if (!((_a = grid.config) === null || _a === void 0 ? void 0 : _a.promoteHeaders)) {
47
+ for (let i = 0; i < grid.data[0].length; i++) {
48
+ columnNames.push(`${constants_1.defaults.columnName} ${i + 1}`);
49
+ }
50
+ return columnNames;
51
+ }
52
+ // We are adjusting column names by default.
53
+ if (!grid.config || grid.config.adjustColumnNames === undefined || grid.config.adjustColumnNames) {
54
+ return utils_1.tableUtils.getAdjustedColumnNames(grid.data[0]);
55
+ }
56
+ // Get column names and failed if it's not a legal name.
57
+ return utils_1.tableUtils.getRawColumnNames(grid.data[0]);
58
+ };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as workbookManager from "./workbookManager";
2
2
  import { DataTypes } from "./types";
3
- import type { QueryInfo, FileConfigs, Grid } from "./types";
3
+ import type { QueryInfo, FileConfigs, Grid, DocProps } from "./types";
4
4
  export { DataTypes };
5
- export type { QueryInfo, FileConfigs, Grid };
5
+ export type { QueryInfo, FileConfigs, Grid, DocProps };
6
6
  export default workbookManager;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.generateCustomXmlFilePath = exports.generateSingleQueryMashup = exports.generateMashupXMLTemplate = void 0;
6
+ const generateMashupXMLTemplate = (base64) => `<?xml version="1.0" encoding="utf-16"?><DataMashup xmlns="http://schemas.microsoft.com/DataMashup">${base64}</DataMashup>`;
7
+ exports.generateMashupXMLTemplate = generateMashupXMLTemplate;
8
+ const generateSingleQueryMashup = (queryName, query) => `section Section1;
9
+
10
+ shared #"${queryName}" =
11
+ ${query};`;
12
+ exports.generateSingleQueryMashup = generateSingleQueryMashup;
13
+ const generateCustomXmlFilePath = (i) => `customXml/item${i}.xml`;
14
+ exports.generateCustomXmlFilePath = generateCustomXmlFilePath;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.DocPropsAutoUpdatedElements = exports.DocPropsModifiableElements = exports.DataTypes = void 0;
6
+ var DataTypes;
7
+ (function (DataTypes) {
8
+ DataTypes[DataTypes["null"] = 0] = "null";
9
+ DataTypes[DataTypes["string"] = 1] = "string";
10
+ DataTypes[DataTypes["number"] = 2] = "number";
11
+ DataTypes[DataTypes["boolean"] = 3] = "boolean";
12
+ })(DataTypes = exports.DataTypes || (exports.DataTypes = {}));
13
+ var DocPropsModifiableElements;
14
+ (function (DocPropsModifiableElements) {
15
+ DocPropsModifiableElements["title"] = "dc:title";
16
+ DocPropsModifiableElements["subject"] = "dc:subject";
17
+ DocPropsModifiableElements["keywords"] = "cp:keywords";
18
+ DocPropsModifiableElements["createdBy"] = "dc:creator";
19
+ DocPropsModifiableElements["description"] = "dc:description";
20
+ DocPropsModifiableElements["lastModifiedBy"] = "cp:lastModifiedBy";
21
+ DocPropsModifiableElements["category"] = "cp:category";
22
+ DocPropsModifiableElements["revision"] = "cp:revision";
23
+ })(DocPropsModifiableElements = exports.DocPropsModifiableElements || (exports.DocPropsModifiableElements = {}));
24
+ var DocPropsAutoUpdatedElements;
25
+ (function (DocPropsAutoUpdatedElements) {
26
+ DocPropsAutoUpdatedElements["created"] = "dcterms:created";
27
+ DocPropsAutoUpdatedElements["modified"] = "dcterms:modified";
28
+ })(DocPropsAutoUpdatedElements = exports.DocPropsAutoUpdatedElements || (exports.DocPropsAutoUpdatedElements = {}));
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.ArrayReader = void 0;
6
+ class ArrayReader {
7
+ constructor(array) {
8
+ this._array = array;
9
+ this._position = 0;
10
+ }
11
+ getInt32() {
12
+ const retVal = new DataView(this._array, this._position, 4).getInt32(0, true);
13
+ this._position += 4;
14
+ return retVal;
15
+ }
16
+ getBytes(bytes) {
17
+ const retVal = this._array.slice(this._position, bytes ? bytes + this._position : bytes);
18
+ this._position += retVal.byteLength;
19
+ return new Uint8Array(retVal);
20
+ }
21
+ reset() {
22
+ this._position = 0;
23
+ }
24
+ }
25
+ exports.ArrayReader = ArrayReader;
26
+ function getInt32Buffer(val) {
27
+ const packageSizeBuffer = new ArrayBuffer(4);
28
+ new DataView(packageSizeBuffer).setInt32(0, val, true);
29
+ return new Uint8Array(packageSizeBuffer);
30
+ }
31
+ function concatArrays(...args) {
32
+ let size = 0;
33
+ args.forEach((arr) => (size += arr.byteLength));
34
+ const retVal = new Uint8Array(size);
35
+ let position = 0;
36
+ args.forEach((arr) => {
37
+ retVal.set(arr, position);
38
+ position += arr.byteLength;
39
+ });
40
+ return retVal;
41
+ }
42
+ exports.default = {
43
+ ArrayReader,
44
+ getInt32Buffer,
45
+ concatArrays,
46
+ };
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.maxQueryLength = exports.divider = exports.section1PathPrefix = exports.emptyValue = exports.falseValue = exports.trueValue = exports.pivotCachesPathPrefix = exports.xmlTextResultType = exports.textResultType = exports.application = exports.uint8ArrayType = exports.blobFileType = exports.relsNotFoundErr = exports.templateFileNotSupportedErr = exports.arrayIsntMxNErr = exports.unexpectedErr = exports.promotedHeadersCannotBeUsedWithoutAdjustingColumnNamesErr = exports.InvalidColumnNameErr = exports.stylesNotFoundErr = exports.EmptyQueryNameErr = exports.QueryNameInvalidCharsErr = exports.QueryNameMaxLengthErr = exports.invalidDataTypeErr = exports.headerNotFoundErr = exports.invalidValueInColumnErr = exports.tableNotFoundErr = exports.queryTableNotFoundErr = exports.templateWithInitialDataErr = exports.formulaSectionNotFoundErr = exports.queryConnectionNotFoundErr = exports.queryAndPivotTableNotFoundErr = exports.queryNameNotFoundErr = exports.emptyQueryMashupErr = exports.base64NotFoundErr = exports.sheetsNotFoundErr = exports.connectionsNotFoundErr = exports.sharedStringsNotFoundErr = exports.docPropsRootElement = exports.docMetadataXmlPath = exports.relsXmlPath = exports.docPropsCoreXmlPath = exports.section1mPath = exports.pivotCachesPath = exports.queryTablesPath = exports.workbookXmlPath = exports.queryTableXmlPath = exports.tableXmlPath = exports.sheetsXmlPath = exports.sharedStringsXmlPath = exports.connectionsXmlPath = void 0;
6
+ exports.URLS = exports.defaults = exports.elementAttributesValues = exports.dataTypeKind = exports.elementAttributes = exports.element = exports.BOM = exports.falseStr = exports.trueStr = void 0;
7
+ exports.connectionsXmlPath = "xl/connections.xml";
8
+ exports.sharedStringsXmlPath = "xl/sharedStrings.xml";
9
+ exports.sheetsXmlPath = "xl/worksheets/sheet1.xml";
10
+ exports.tableXmlPath = "xl/tables/table1.xml";
11
+ exports.queryTableXmlPath = "xl/queryTables/queryTable1.xml";
12
+ exports.workbookXmlPath = "xl/workbook.xml";
13
+ exports.queryTablesPath = "xl/queryTables/";
14
+ exports.pivotCachesPath = "xl/pivotCache/";
15
+ exports.section1mPath = "Formulas/Section1.m";
16
+ exports.docPropsCoreXmlPath = "docProps/core.xml";
17
+ exports.relsXmlPath = "_rels/.rels";
18
+ exports.docMetadataXmlPath = "docMetadata";
19
+ exports.docPropsRootElement = "cp:coreProperties";
20
+ exports.sharedStringsNotFoundErr = "SharedStrings were not found in template";
21
+ exports.connectionsNotFoundErr = "Connections were not found in template";
22
+ exports.sheetsNotFoundErr = "Sheets were not found in template";
23
+ exports.base64NotFoundErr = "Base64 was not found in template";
24
+ exports.emptyQueryMashupErr = "Query mashup is empty";
25
+ exports.queryNameNotFoundErr = "Query name was not found";
26
+ exports.queryAndPivotTableNotFoundErr = "No such query found in Query Table or Pivot Table found in given template";
27
+ exports.queryConnectionNotFoundErr = "No connection found for query";
28
+ exports.formulaSectionNotFoundErr = "Formula section wasn't found in template";
29
+ exports.templateWithInitialDataErr = "Cannot use a template file with initial data";
30
+ exports.queryTableNotFoundErr = "Query table wasn't found in template";
31
+ exports.tableNotFoundErr = "Table wasn't found in template";
32
+ exports.invalidValueInColumnErr = "Invalid cell value in column";
33
+ exports.headerNotFoundErr = "Invalid JSON file, header is missing";
34
+ exports.invalidDataTypeErr = "Invalid JSON file, invalid data type";
35
+ exports.QueryNameMaxLengthErr = "Query names are limited to 80 characters";
36
+ exports.QueryNameInvalidCharsErr = 'Query names cannot contain periods or quotation marks. (. ")';
37
+ exports.EmptyQueryNameErr = "Query name cannot be empty";
38
+ exports.stylesNotFoundErr = "Styles were not found in template";
39
+ exports.InvalidColumnNameErr = "Invalid column name";
40
+ exports.promotedHeadersCannotBeUsedWithoutAdjustingColumnNamesErr = "Headers cannot be promoted without adjusting column names";
41
+ exports.unexpectedErr = "Unexpected error";
42
+ exports.arrayIsntMxNErr = "Array isn't MxN";
43
+ exports.templateFileNotSupportedErr = "Template file is not supported for this API call";
44
+ exports.relsNotFoundErr = ".rels were not found in template";
45
+ exports.blobFileType = "blob";
46
+ exports.uint8ArrayType = "uint8array";
47
+ exports.application = "application/xlsx";
48
+ exports.textResultType = "text";
49
+ exports.xmlTextResultType = "text/xml";
50
+ exports.pivotCachesPathPrefix = "pivotCacheDefinition";
51
+ exports.trueValue = "1";
52
+ exports.falseValue = "0";
53
+ exports.emptyValue = "";
54
+ exports.section1PathPrefix = "Section1/";
55
+ exports.divider = "/";
56
+ exports.maxQueryLength = 80;
57
+ exports.trueStr = "true";
58
+ exports.falseStr = "false";
59
+ exports.BOM = "\ufeff";
60
+ exports.element = {
61
+ sharedStringTable: "sst",
62
+ text: "t",
63
+ sharedStringItem: "si",
64
+ cellValue: "v",
65
+ databaseProperties: "dbPr",
66
+ queryTable: "queryTable",
67
+ cacheSource: "cacheSource",
68
+ item: "Item",
69
+ items: "Items",
70
+ itemPath: "ItemPath",
71
+ itemType: "ItemType",
72
+ itemLocation: "ItemLocation",
73
+ entry: "Entry",
74
+ stableEntries: "StableEntries",
75
+ tableColumns: "tableColumns",
76
+ tableColumn: "tableColumn",
77
+ table: "table",
78
+ autoFilter: "autoFilter",
79
+ definedName: "definedName",
80
+ queryTableFields: "queryTableFields",
81
+ queryTableField: "queryTableField",
82
+ queryTableRefresh: "queryTableRefresh",
83
+ sheetData: "sheetData",
84
+ row: "row",
85
+ dimension: "dimension",
86
+ selection: "selection",
87
+ kindCell: "c",
88
+ };
89
+ exports.elementAttributes = {
90
+ connection: "connection",
91
+ command: "command",
92
+ refreshOnLoad: "refreshOnLoad",
93
+ count: "count",
94
+ uniqueCount: "uniqueCount",
95
+ queryTable: "queryTable",
96
+ connectionId: "connectionId",
97
+ cacheSource: "cacheSource",
98
+ name: "name",
99
+ description: "description",
100
+ id: "id",
101
+ type: "Type",
102
+ value: "Value",
103
+ relationshipInfo: "RelationshipInfoContainer",
104
+ resultType: "ResultType",
105
+ fillColumnNames: "FillColumnNames",
106
+ fillTarget: "FillTarget",
107
+ fillLastUpdated: "FillLastUpdated",
108
+ day: "d",
109
+ uniqueName: "uniqueName",
110
+ queryTableFieldId: "queryTableFieldId",
111
+ reference: "ref",
112
+ sqref: "sqref",
113
+ tableColumnId: "tableColumnId",
114
+ nextId: "nextId",
115
+ row: "r",
116
+ spans: "spans",
117
+ x14acDyDescent: "x14ac:dyDescent",
118
+ xr3uid: "xr3:uid",
119
+ };
120
+ exports.dataTypeKind = {
121
+ string: "str",
122
+ number: "1",
123
+ boolean: "b",
124
+ };
125
+ exports.elementAttributesValues = {
126
+ connectionName: (queryName) => `Query - ${queryName}`,
127
+ connectionDescription: (queryName) => `Connection to the '${queryName}' query in the workbook.`,
128
+ connection: (queryName) => `Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location="${queryName}";`,
129
+ connectionCommand: (queryName) => `SELECT * FROM [${queryName}]`,
130
+ tableResultType: () => "sTable",
131
+ };
132
+ exports.defaults = {
133
+ queryName: "Query1",
134
+ sheetName: "Sheet1",
135
+ columnName: "Column",
136
+ };
137
+ exports.URLS = {
138
+ PQ: [
139
+ "http://schemas.microsoft.com/DataMashup",
140
+ "http://schemas.microsoft.com/DataExplorer",
141
+ "http://schemas.microsoft.com/DataMashup/Temp",
142
+ "http://schemas.microsoft.com/DataExplorer/Temp",
143
+ ],
144
+ CONNECTED_WORKBOOK: "http://schemas.microsoft.com/ConnectedWorkbook",
145
+ };
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6
+ return new (P || (P = Promise))(function (resolve, reject) {
7
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
11
+ });
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ const constants_1 = require("./constants");
15
+ const types_1 = require("../types");
16
+ const createOrUpdateProperty = (doc, parent, property, value) => {
17
+ if (value === undefined) {
18
+ return;
19
+ }
20
+ const elements = parent.getElementsByTagName(property);
21
+ if ((elements === null || elements === void 0 ? void 0 : elements.length) === 0) {
22
+ const newElement = doc.createElement(property);
23
+ newElement.textContent = value;
24
+ parent.appendChild(newElement);
25
+ }
26
+ else if (elements.length > 1) {
27
+ throw new Error(`Invalid DocProps core.xml, multiple ${property} elements`);
28
+ }
29
+ else if ((elements === null || elements === void 0 ? void 0 : elements.length) > 0) {
30
+ elements[0].textContent = value;
31
+ }
32
+ };
33
+ const getDocPropsProperties = (zip) => __awaiter(void 0, void 0, void 0, function* () {
34
+ var _a;
35
+ const docPropsCoreXmlString = yield ((_a = zip.file(constants_1.docPropsCoreXmlPath)) === null || _a === void 0 ? void 0 : _a.async(constants_1.textResultType));
36
+ if (docPropsCoreXmlString === undefined) {
37
+ throw new Error("DocProps core.xml was not found in template");
38
+ }
39
+ const parser = new DOMParser();
40
+ const doc = parser.parseFromString(docPropsCoreXmlString, constants_1.xmlTextResultType);
41
+ const properties = doc.getElementsByTagName(constants_1.docPropsRootElement).item(0);
42
+ if (properties === null) {
43
+ throw new Error("Invalid DocProps core.xml");
44
+ }
45
+ return { doc, properties };
46
+ });
47
+ const getCellReferenceAbsolute = (col, row) => {
48
+ // 65 is the ascii value of first column 'A'
49
+ return "$" + String.fromCharCode(col + 65) + "$" + row.toString();
50
+ };
51
+ const getCellReferenceRelative = (col, row) => {
52
+ // 65 is the ascii value of first column 'A'
53
+ return String.fromCharCode(col + 65) + row.toString();
54
+ };
55
+ const getTableReference = (numberOfCols, numberOfRows) => {
56
+ return `A1:${getCellReferenceRelative(numberOfCols, numberOfRows)}`;
57
+ };
58
+ const createCellElement = (doc, colIndex, rowIndex, data) => {
59
+ const cell = doc.createElementNS(doc.documentElement.namespaceURI, constants_1.element.kindCell);
60
+ cell.setAttribute(constants_1.elementAttributes.row, getCellReferenceRelative(colIndex, rowIndex + 1));
61
+ const cellData = doc.createElementNS(doc.documentElement.namespaceURI, constants_1.element.cellValue);
62
+ updateCellData(data, cell, cellData, rowIndex === 0);
63
+ cell.appendChild(cellData);
64
+ return cell;
65
+ };
66
+ const updateCellData = (data, cell, cellData, rowHeader) => {
67
+ switch (resolveType(data, rowHeader)) {
68
+ case types_1.DataTypes.string:
69
+ cell.setAttribute(constants_1.element.text, constants_1.dataTypeKind.string);
70
+ break;
71
+ case types_1.DataTypes.number:
72
+ cell.setAttribute(constants_1.element.text, constants_1.dataTypeKind.number);
73
+ break;
74
+ case types_1.DataTypes.boolean:
75
+ cell.setAttribute(constants_1.element.text, constants_1.dataTypeKind.boolean);
76
+ break;
77
+ }
78
+ cellData.textContent = data;
79
+ };
80
+ const resolveType = (originalData, rowHeader) => {
81
+ const data = originalData;
82
+ if (rowHeader) {
83
+ // Headers should be string by default.
84
+ return types_1.DataTypes.string;
85
+ }
86
+ let dataType = isNaN(Number(data)) ? types_1.DataTypes.string : types_1.DataTypes.number;
87
+ if (dataType == types_1.DataTypes.string) {
88
+ if (data.trim() == constants_1.trueStr || data.trim() == constants_1.falseStr) {
89
+ dataType = types_1.DataTypes.boolean;
90
+ }
91
+ }
92
+ return dataType;
93
+ };
94
+ exports.default = {
95
+ createOrUpdateProperty,
96
+ getDocPropsProperties,
97
+ getCellReferenceRelative,
98
+ getCellReferenceAbsolute,
99
+ createCell: createCellElement,
100
+ getTableReference,
101
+ resolveType,
102
+ };