@omnia/tooling-vue 8.0.91-vnext → 8.0.92-dev

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 (26) hide show
  1. package/internal-do-not-import-from-here/config/omnia.fx.core_a2892051-fd9f-4056-ae8d-30d16d48417d.manifest.json +1 -0
  2. package/internal-do-not-import-from-here/config/omnia.fx.ux_dee030cc-4ab3-4158-bb06-8049f5c67542.manifest.json +1 -0
  3. package/internal-do-not-import-from-here/config/omnia.fx_a5a89056-b5f5-475d-8518-a1f55090379d.manifest.json +1 -0
  4. package/internal-do-not-import-from-here/config/omnia.vendor.manifest.json +1 -1
  5. package/internal-do-not-import-from-here/config/tooling.output.json +1 -1
  6. package/internal-do-not-import-from-here/config/wctypings.d.ts +4435 -1498
  7. package/internal-do-not-import-from-here/shared.d.ts +11 -6
  8. package/internal-do-not-import-from-here/shared.js +32 -12
  9. package/internal-do-not-import-from-here/tasks/ComponentDocRegistrations.js +1 -1
  10. package/internal-do-not-import-from-here/tasks/bundle.js +65 -380
  11. package/internal-do-not-import-from-here/tasks/doc.d.ts +3 -1
  12. package/internal-do-not-import-from-here/tasks/doc.js +393 -392
  13. package/internal-do-not-import-from-here/tasks/vendor.js +16 -12
  14. package/internal-do-not-import-from-here/vite/hmr/graph.js +3 -1
  15. package/internal-do-not-import-from-here/vite/plugins/OmniaPlugin.js +1 -1
  16. package/internal-do-not-import-from-here/webpack-loaders/doc-loader.d.ts +1 -0
  17. package/internal-do-not-import-from-here/webpack-loaders/doc-loader.js +11 -0
  18. package/internal-do-not-import-from-here/webpack-loaders/esbuild-custom-loader.d.ts +1 -0
  19. package/internal-do-not-import-from-here/webpack-loaders/esbuild-custom-loader.js +10 -0
  20. package/internal-do-not-import-from-here/webpack-loaders/ts-loader.d.ts +5 -2
  21. package/internal-do-not-import-from-here/webpack-loaders/ts-loader.js +8 -0
  22. package/internal-do-not-import-from-here/webpack-loaders/tsx-loader.d.ts +3 -3
  23. package/internal-do-not-import-from-here/webpack-loaders/tsx-loader.js +3 -0
  24. package/internal-do-not-import-from-here/webpack-loaders/wc-loader.d.ts +1 -1
  25. package/internal-do-not-import-from-here/webpack-loaders/wc-loader.js +5 -1
  26. package/package.json +7 -8
@@ -1,424 +1,425 @@
1
1
  'use strict';
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.importSnippetCode = exports.generateComponentTypingsAndDoc = void 0;
3
4
  const tslib_1 = require("tslib");
4
- const fs = require('fs');
5
+ const fs_1 = tslib_1.__importDefault(require("fs"));
6
+ const path_1 = tslib_1.__importDefault(require("path"));
5
7
  const shared_1 = require("../shared");
6
- const $ = tslib_1.__importStar(require("../variables"));
7
- let relativeOutDir = "client/tooling/vue/docs";
8
- if ($.isExtensionEnv) {
9
- relativeOutDir = "node_modules/@omnia/tooling-vue/internal-do-not-import-from-here/docs";
10
- }
11
- let outDir = $.tooling.utils.root(relativeOutDir);
12
- let extensionEnvironment = {
13
- paths: {
14
- composorImportPath: $.isExtensionEnv ? '@omnia/tooling-composers' : '../../../tooling/composers',
15
- topicImportPath: $.isExtensionEnv ? '@omnia/fx-models' : '../../../fx/models',
16
- messageBusTopicMediatorImportPath: $.isExtensionEnv ? '@omnia/fx' : '../../../fx'
17
- },
18
- outPutPaths: {
19
- folder: outDir + "/",
20
- rawFile: outDir + '/docs.json',
21
- manifest: outDir + '/docs.manifest.ts',
22
- navRegistration: outDir + '/nav.ts'
8
+ const tooling_composers_1 = require("@omnia/tooling-composers");
9
+ const tooling_1 = require("@omnia/tooling");
10
+ const core_1 = require("@swc/core");
11
+ const fsExtra = tslib_1.__importStar(require("fs-extra"));
12
+ const fx_models_1 = require("@omnia/fx-models");
13
+ async function generateComponentTypingsAndDoc(componentRegistrations) {
14
+ tooling_1.utils.log("Generate components typings and documentation running...");
15
+ var startTime = new Date().getTime();
16
+ let DefineVueType;
17
+ (function (DefineVueType) {
18
+ DefineVueType[DefineVueType["Prop"] = 0] = "Prop";
19
+ DefineVueType[DefineVueType["Model"] = 1] = "Model";
20
+ DefineVueType[DefineVueType["Slot"] = 2] = "Slot";
21
+ DefineVueType[DefineVueType["Emit"] = 4] = "Emit";
22
+ })(DefineVueType || (DefineVueType = {}));
23
+ const docResult = {};
24
+ function getPropertyFunctionTypeAsString(type) {
25
+ let params = "";
26
+ if (type.params?.length > 0) {
27
+ type.params.forEach(p => {
28
+ params += `${p.value}:${extractTypeToString(p.typeAnnotation)}, `;
29
+ });
30
+ params = params.replace(/,\s*$/, "");
31
+ }
32
+ return `(${params}) => ${extractTypeToString(type.typeAnnotation)}`;
23
33
  }
24
- };
25
- $.tooling.core.registerBuildTask({
26
- stage: $.tooling.core.TaskStage.AfterScanManifests,
27
- order: 1,
28
- task: function () {
29
- return generateDocManifest();
34
+ function extractTypeToString(tsType) {
35
+ let result = "";
36
+ if (tsType.type === "TsTypeAnnotation") {
37
+ return extractTypeToString(tsType.typeAnnotation);
38
+ }
39
+ switch (tsType.type) {
40
+ case "TsLiteralType":
41
+ result = tsType.literal.value;
42
+ break;
43
+ case "TsKeywordType":
44
+ result = tsType.kind;
45
+ break;
46
+ case "TsTypeReference":
47
+ result = tsType.typeName.value;
48
+ break;
49
+ case "TsFunctionType":
50
+ result = getPropertyFunctionTypeAsString(tsType);
51
+ break;
52
+ default:
53
+ break;
54
+ }
55
+ return result;
30
56
  }
31
- });
32
- function generateDocManifest() {
33
- return new Promise(function (resolve, reject) {
34
- resolve();
35
- // documentalist package jave issue with security
36
- // so we will find another solution in omnia 7.
37
- //let enableDocs = $.composers.DevelopmentBuildConfiguration.isEnableDocumentation;
38
- //if (enableDocs !== true && process.argv.length > 0) {
39
- // enableDocs = process.argv.find(argv => argv === "--docs") !== undefined;
40
- //}
41
- //if (enableDocs !== true) {
42
- // resolve();
43
- //}
44
- //else {
45
- // $.tooling.log('Generating documentation manifest', $.tooling.LogTypes.HeadLine);
46
- // let startTime = new Date().getTime();
47
- // //ensure folder
48
- // if (!fs.existsSync(outDir)) {
49
- // fs.mkdirSync(outDir);
50
- // }
51
- // else {
52
- // // cleanup exist docs
53
- // $.del.sync([outDir + '/**', '!' + outDir]);
54
- // }
55
- // let componentRegistrations = $.composers.ComponentRegistry.getComponentRegistrations();
56
- // let docs = extractDocPathForComponents(componentRegistrations);
57
- // $.tooling.logTime(`Found [${docs.componentsDocCount}] component(s) have documentation`, startTime);
58
- // if (docs.paths.length > 0) {
59
- // generate(docs.paths).then(() => {
60
- // $.tooling.logTime('Done - Generating documentation manifest', startTime);
61
- // resolve();
62
- // }, reject);
63
- // }
64
- // else {
65
- // $.tooling.logTime('Done - Generating documentation manifest', startTime);
66
- // resolve();
67
- // }
68
- //}
69
- });
70
- }
71
- function generate(paths) {
72
- return new Promise(function (resolve, reject) {
73
- const { Documentalist, TypescriptPlugin } = require("documentalist");
74
- new Documentalist()
75
- .use(/\.ts?$/, new TypescriptPlugin())
76
- .documentGlobs(...paths) // ← async operation, returns a Promise
77
- .then(docs => {
78
- //console.log("ahihi", docs.typescript);
79
- var rootModel = docs.typescript;
80
- var filterFilesPath = filterInterfaceFilePaths(rootModel, paths);
81
- var elementInterfaces = getWebComponentAndMainInterface(Object.keys(filterFilesPath));
82
- var fxDocs = builtFxDocs(rootModel, elementInterfaces);
83
- writeFile(extensionEnvironment.outPutPaths.rawFile, JSON.stringify(fxDocs, null, 2)); //For debugging purpose
84
- writeDocsManifest(extensionEnvironment.outPutPaths.manifest, extensionEnvironment.paths.composorImportPath, fxDocs);
85
- writeNavRegistrion(extensionEnvironment.outPutPaths.navRegistration, extensionEnvironment.paths.topicImportPath, extensionEnvironment.paths.messageBusTopicMediatorImportPath, fxDocs);
86
- writeDocsRegistration(extensionEnvironment.outPutPaths.folder, extensionEnvironment.paths.topicImportPath, extensionEnvironment.paths.messageBusTopicMediatorImportPath, fxDocs);
87
- let docManifestRelativePath = relativeOutDir + "/docs.manifest.ts";
88
- let docManifestAbsolutePath = $.tooling.utils.root(docManifestRelativePath);
89
- // register docs manifest
90
- if ($.fs.existsSync(docManifestAbsolutePath)) {
91
- try {
92
- $.composers.ManifestRegistry.setCurrentManifestPath(docManifestRelativePath);
93
- require(docManifestAbsolutePath);
94
- $.composers.ManifestRegistry.setCurrentManifestPath();
95
- delete require.cache[docManifestAbsolutePath];
96
- }
97
- catch (ex) {
98
- console.dir(ex.stack);
99
- reject();
100
- }
101
- }
102
- resolve();
103
- }, reject);
104
- });
105
- }
106
- function getSamples(interfaceFilePath) {
107
- var elementNameReg = /elementName:( )*['"][^'"]+['"]/g; //Only @Prop has define default value
108
- var entryPointReg = /entryPoint:( )*['"][^'"]+['"]/g;
109
- var samples = [];
110
- var interfaceSegments = interfaceFilePath.split('\\');
111
- interfaceSegments.splice(-1, 1);
112
- var folderPath = interfaceSegments.join('\\') + '\\samples';
113
- var samplesManifests = getAllFilesInFolderRecursively(folderPath);
114
- for (var sampleManifest of samplesManifests) {
115
- var content = readFile(sampleManifest.filePath);
116
- var elemNameMatches = content.match(elementNameReg);
117
- var entryPointMatches = content.match(entryPointReg);
118
- if (elemNameMatches && entryPointMatches) {
119
- for (var i = 0; i < entryPointMatches.length; i++) {
120
- var elemNameMatch = elemNameMatches[i];
121
- var entryPointMatch = entryPointMatches[i];
122
- var sampleElemDefinition = elemNameMatch.split(':').pop();
123
- sampleElemDefinition = sampleElemDefinition.trim();
124
- var sampleElem = sampleElemDefinition.substr(1, sampleElemDefinition.length - 2);
125
- var entryPointDefinition = entryPointMatch.split(':').pop();
126
- entryPointDefinition = entryPointDefinition.trim();
127
- var entryPoint = entryPointDefinition.substr(1, entryPointDefinition.length - 2);
128
- entryPoint = entryPoint.replace('./', '').replace('.jsx', '.tsx').split('/').join('\\');
129
- var sampleTsxFilePath = sampleManifest.dirPath + '\\' + entryPoint;
130
- var sampleTsxFileContent = readFile(sampleTsxFilePath);
131
- sampleTsxFileContent = sampleTsxFileContent.replace(new RegExp('\\r\\n', 'g'), '\\\\r\\\\n');
132
- //console.log(sampleTsxFileContent);
133
- samples.push({ elem: sampleElem, content: sampleTsxFileContent });
57
+ function getPropertyInfo(ce, result) {
58
+ const identifier = ce.callee?.property?.value;
59
+ if (identifier) {
60
+ switch (identifier) {
61
+ case "name":
62
+ result.name = ce.arguments[0].expression.value;
63
+ getPropertyInfo(ce.callee.object, result);
64
+ break;
65
+ case "vModel":
66
+ result.type = DefineVueType.Model;
67
+ result.propertyTypeAsString = extractTypeToString(ce.typeArguments.params[0]);
68
+ result.name = result.name ? `v-model:${result.name}` : result.name;
69
+ break;
70
+ case "slots":
71
+ result.type = DefineVueType.Slot;
72
+ result.propertyTypeAsObject = {};
73
+ ce.typeArguments.params[0].members
74
+ .forEach(m => {
75
+ result.propertyTypeAsObject[m.key.value] = extractTypeToString(m.typeAnnotation);
76
+ });
77
+ break;
78
+ case "prop":
79
+ result.type = DefineVueType.Prop;
80
+ result.propertyTypeAsString = extractTypeToString(ce.typeArguments.params[0]);
81
+ break;
82
+ case "emit":
83
+ result.type = DefineVueType.Emit;
84
+ result.propertyTypeAsString = extractTypeToString(ce.typeArguments.params[0]);
85
+ break;
86
+ default:
87
+ getPropertyInfo(ce.callee.object, result);
134
88
  }
135
89
  }
136
90
  }
137
- return samples;
138
- }
139
- function writeDocsRegistration(outputFolder, topicImportPath, messageBusTopicMediatorImportPath, fxDocs) {
140
- for (var elem of Object.keys(fxDocs)) {
141
- var content = '';
142
- var docsRegistrationMsg = generateDocsRegistrationMsg(fxDocs, elem);
143
- var json = JSON.stringify(docsRegistrationMsg)
144
- .replace(new RegExp('`', 'g'), '\\`');
145
- json = json
146
- .replace(new RegExp('\\\\\\\\\\\\`', 'g'), '\\\\\\\\\\`');
147
- json = json
148
- .replace(new RegExp('\\\\"', 'g'), '\\\\"');
149
- content += `import { Topic } from "${topicImportPath}";\r\n`;
150
- content += `import { MessageBusTopicMediator } from '${messageBusTopicMediatorImportPath}';\r\n`;
151
- content += `const topic: Topic<string> = {namespace: "omfx.docs",name: "docs"};\r\n`;
152
- content += `const registerNav = new MessageBusTopicMediator<any>(topic, { caching: { size: Number.MAX_SAFE_INTEGER} });\r\n`;
153
- content += 'registerNav.publish(JSON.parse(`' + json + '`))';
154
- writeFile(outputFolder + elem + '.ts', content);
155
- }
156
- }
157
- function writeDocsManifest(path, composorImportPath, fxDocs) {
158
- var content = '';
159
- content += `import { Composer } from "${composorImportPath}";\r\n`;
160
- content += '\r\n';
161
- content += `Composer.registerManifest("${$.tooling.utils.generateGuid()}", "fxdocs")\r\n`;
162
- content += ` .registerResources({resourcePaths:['./nav.ts']})\r\n`;
163
- content += ` .withLoadRules().loadIfManifestLoaded({omniaServiceId:'da059968-e431-48b5-a865-d33d0fa29c9d', resourceId:'052f0298-1dc7-4d0c-b4b9-3c8497ca08f5'})\r\n`;
164
- content += '\r\n';
165
- for (var elem of Object.keys(fxDocs)) {
166
- content += '\r\n';
167
- content += `Composer.registerManifest("${$.tooling.utils.generateGuid()}", "${elem}")\r\n`;
168
- content += ` .registerResources({resourcePaths:['./${elem}.ts']})\r\n`;
169
- content += ` .withLoadRules().loadIfManifestLoaded({omniaServiceId:'da059968-e431-48b5-a865-d33d0fa29c9d', resourceId:'052f0298-1dc7-4d0c-b4b9-3c8497ca08f5'})\r\n`;
170
- content += ` .and().loadByDomMatching({ cssSelector: "omfx-docs-resource[source='${elem}']" });\r\n`;
171
- content += '\r\n';
172
- }
173
- writeFile(path, content);
174
- }
175
- function writeNavRegistrion(path, topicImportPath, messageBusTopicMediatorImportPath, fxDocs) {
176
- var content = '';
177
- var navRegistrationMsg = getNavRegistrationMsg(fxDocs);
178
- content += `import { Topic } from "${topicImportPath}";\r\n`;
179
- content += `import { MessageBusTopicMediator } from '${messageBusTopicMediatorImportPath}';\r\n`;
180
- content += `const topic: Topic<string> = {namespace: "omfx.docs",name: "nav"};\r\n`;
181
- content += `const registerNav = new MessageBusTopicMediator<any>(topic, { caching: { size: Number.MAX_SAFE_INTEGER} });\r\n`;
182
- content += 'registerNav.publish(JSON.parse(`' + JSON.stringify(navRegistrationMsg) + '`))';
183
- writeFile(path, content);
184
- }
185
- function generateDocsRegistrationMsg(fxDocs, elem) {
186
- var props = [];
187
- var elemDocumentation = elem;
188
- if (fxDocs[elem] && fxDocs[elem].documentation && fxDocs[elem].documentation.contentsRaw) {
189
- elemDocumentation = fxDocs[elem].documentation.contentsRaw;
190
- }
191
- var elemName = elemDocumentation.split('-')[0];
192
- var elemDescription = elemDocumentation.split('-')[1] || '';
193
- if (fxDocs[elem].props) {
194
- for (var prop of Object.keys(fxDocs[elem].props)) {
195
- var propObj = fxDocs[elem].props[prop];
196
- var description = '';
197
- if (propObj.documentation && propObj.documentation.contentsRaw) {
198
- description = propObj.documentation.contentsRaw;
199
- if (description && description.indexOf('\"') >= 0) {
200
- description = description.replace(new RegExp('\\"', 'g'), '\\\"');
91
+ async function buildDoc(wc) {
92
+ try {
93
+ const wcPath = (0, shared_1.convertManifestPathToEntryPath)(wc.manifestPath, [wc.componentOptions.entryPoint])[0];
94
+ const wcParseResult = await (0, core_1.parseFile)(wcPath, {
95
+ syntax: 'typescript',
96
+ target: 'es2020',
97
+ tsx: true,
98
+ decorators: true,
99
+ dynamicImport: true
100
+ });
101
+ wcParseResult.body.forEach(b => {
102
+ if (b.type === 'ExportDefaultExpression'
103
+ && b.expression.callee?.value === "defineVueComponent") {
104
+ if (b.expression.arguments[0].expression.type === "ArrowFunctionExpression") {
105
+ const params = b.expression.arguments[0].expression.params;
106
+ const typeParams = params[0].typeAnnotation.typeAnnotation.typeParams.params;
107
+ const props = typeParams[0];
108
+ props.types.forEach((t) => {
109
+ const typeName = t.typeName.value;
110
+ if (typeName === "DefineProp"
111
+ || typeName === "DefineVModel"
112
+ || typeName === "DefineSlot"
113
+ || typeName === "DefineEmit") {
114
+ // const isDefineVModel = (t.typeName as Identifier).value === "DefineVModel$";
115
+ if (!docResult[wc.componentOptions.elementName]) {
116
+ docResult[wc.componentOptions.elementName] = {
117
+ emits: {},
118
+ models: {},
119
+ props: {},
120
+ slots: {}
121
+ };
122
+ }
123
+ const params = t.typeParams.params;
124
+ const name = extractTypeToString(params[0]);
125
+ const type = extractTypeToString(params[1]);
126
+ if (typeName === "DefineProp" || typeName === "DefineVModel") { // props or vmodel
127
+ const required = params.length > 2 ? extractTypeToString(params[2]) : false;
128
+ const description = params.length > 3 ? extractTypeToString(params[3]) : "";
129
+ if (typeName === "DefineVModel") {
130
+ docResult[wc.componentOptions.elementName].models[name] = {
131
+ type: type,
132
+ description: description,
133
+ required: required.toString().toLowerCase() === "true" ? true : false
134
+ };
135
+ }
136
+ else { // props
137
+ docResult[wc.componentOptions.elementName].props[name] = {
138
+ type: type,
139
+ description: description,
140
+ required: required.toString().toLowerCase() === "true" ? true : false
141
+ };
142
+ }
143
+ }
144
+ else { // slots or emits
145
+ const description = params.length > 2 ? extractTypeToString(params[2]) : "";
146
+ if (typeName === "DefineEmit") {
147
+ docResult[wc.componentOptions.elementName].emits[name] = {
148
+ type: type,
149
+ description: description,
150
+ };
151
+ }
152
+ else { // slots
153
+ docResult[wc.componentOptions.elementName].slots[name] = {
154
+ type: type,
155
+ description: description,
156
+ };
157
+ }
158
+ }
159
+ }
160
+ });
161
+ }
162
+ else {
163
+ b.expression.arguments[0].expression
164
+ .properties?.filter(p => p.key.value === "props"
165
+ || p.key.value === "emits")
166
+ ?.forEach(propsIdentifier => {
167
+ if (propsIdentifier) {
168
+ propsIdentifier.value
169
+ .properties?.forEach(p => {
170
+ const em = p.arguments;
171
+ if (em?.callee?.property?.value === "doc$") {
172
+ const PropertyResult = {
173
+ type: null,
174
+ propertyTypeAsString: "",
175
+ name: ""
176
+ };
177
+ getPropertyInfo(em, PropertyResult);
178
+ if (!docResult[wc.componentOptions.elementName]) {
179
+ docResult[wc.componentOptions.elementName] = {
180
+ emits: {},
181
+ models: {},
182
+ props: {},
183
+ slots: {}
184
+ };
185
+ }
186
+ switch (PropertyResult.type) {
187
+ case DefineVueType.Prop:
188
+ docResult[wc.componentOptions.elementName].props[PropertyResult.name] = {
189
+ type: PropertyResult.propertyTypeAsString,
190
+ description: em.arguments[0].expression.value
191
+ };
192
+ break;
193
+ case DefineVueType.Model:
194
+ docResult[wc.componentOptions.elementName].models[PropertyResult.name] = {
195
+ type: PropertyResult.propertyTypeAsString,
196
+ description: em.arguments[0].expression.value
197
+ };
198
+ break;
199
+ case DefineVueType.Emit:
200
+ docResult[wc.componentOptions.elementName].emits[PropertyResult.name] = {
201
+ type: PropertyResult.propertyTypeAsString,
202
+ description: em.arguments[0].expression.value
203
+ };
204
+ break;
205
+ case DefineVueType.Slot:
206
+ em.arguments[0].expression
207
+ .properties
208
+ .forEach(p => {
209
+ const slotName = p.key.value;
210
+ docResult[wc.componentOptions.elementName].slots[slotName] = {
211
+ type: PropertyResult.propertyTypeAsObject[slotName],
212
+ description: p.value.value
213
+ };
214
+ });
215
+ break;
216
+ default:
217
+ break;
218
+ }
219
+ }
220
+ });
221
+ }
222
+ });
223
+ }
201
224
  }
202
- }
203
- var defaultValue = propObj.defaultValue;
204
- if (defaultValue && defaultValue.indexOf('\"') >= 0) {
205
- defaultValue = defaultValue.replace(new RegExp('\\"', 'g'), '\\\"');
206
- }
207
- props.push({ name: prop, type: propObj.type, description: description, defaultValue: defaultValue });
225
+ });
208
226
  }
209
- }
210
- return { elem: elem, name: elemName, description: elemDescription, props: props, sampleElems: fxDocs[elem].samples };
211
- }
212
- function getNavRegistrationMsg(fxDocs) {
213
- var componentNodes = [];
214
- for (var elem of Object.keys(fxDocs)) {
215
- var name = elem;
216
- if (fxDocs[elem] && fxDocs[elem].documentation && fxDocs[elem].documentation.contentsRaw) {
217
- name = fxDocs[elem].documentation.contentsRaw.split('-')[0].trim();
227
+ catch (ex) {
228
+ tooling_1.utils.log(`Have a exception when extract doc$ for web component manifest -> ${wc.manifestPath}`, tooling_1.utils.LogTypes.Error);
229
+ console.error(ex);
230
+ throw new Error("Exit, have an exception.");
218
231
  }
219
- componentNodes.push({ name: name, elem: elem });
220
232
  }
221
- return { extension: $.composers.ServiceManifestRegistry.getServiceInfo().title || $.composers.ServiceManifestRegistry.getServiceInfo().id, componentNodes };
222
- }
223
- function builtFxDocs(rootModel, elementInterfaces) {
224
- var fxDocs = {};
225
- let componentRegistrations = $.composers.ComponentRegistry.getComponentRegistrations();
226
- for (var element in elementInterfaces) {
227
- console.log('process for', element);
228
- var elementDoc = {};
229
- var elementInfo = elementInterfaces[element];
230
- var rootNode = rootModel[elementInfo.interface];
231
- elementDoc.documentation = rootNode.documentation;
232
- var props = {};
233
- getComponentProperties(rootModel, elementInfo.interface, props);
234
- let componentRegistration = componentRegistrations.find(c => c.componentOptions.elementName === element);
235
- if (componentRegistration) {
236
- let componentPath = (0, shared_1.convertManifestPathToEntryPath)(componentRegistration.manifestPath, [componentRegistration.componentOptions.entryPoint])[0];
237
- getComponentPropertiesDefaultValue(componentPath, props);
233
+ let docPath = path_1.default.resolve(__dirname, "ComponentDocRegistrations.ts");
234
+ ;
235
+ let wcTypings = `
236
+ //{{importWC}}
237
+
238
+ type ExtractJsxProps<T> = {
239
+ [K in keyof (T extends { propsDefinition: any } ? T["propsDefinition"] : T)]: T extends {
240
+ propsDefinition: any;
241
+ }
242
+ ? T["propsDefinition"][K]
243
+ : never;
244
+ } & { $children?: any; };
245
+
246
+ declare global {
247
+ namespace JSX {
248
+ interface Element { }
249
+ interface ElementClass { }
250
+
251
+ interface IntrinsicElements {
252
+ //{{elementName}}
238
253
  }
239
- elementDoc.props = props;
240
- var samples = getSamples(elementInfo.interfaceFilePath);
241
- elementDoc.samples = samples;
242
- fxDocs[element] = elementDoc;
243
254
  }
244
- return fxDocs;
245
- }
246
- function getComponentPropertiesDefaultValue(componentPath, props) {
247
- //var folderPath = interfaceFilePath.substring(0, interfaceFilePath.lastIndexOf('\\') + 1);
248
- //var interfaceFileName = interfaceFilePath.substring(folderPath.length);
249
- //var implementationFileName = interfaceFileName.substring(1) + 'x'; // IName.ts => Name.tsx
250
- //var implementationPath = folderPath + implementationFileName;
251
- var fileContent = readFile(componentPath);
252
- var reg = /@Prop\(\{[^\)d]+(default)[^\)]+\)[a-zA-Z0-9?_ ]+:/g; //Only @Prop has define default value
253
- var regResults = fileContent.match(reg);
254
- if (regResults) {
255
- for (var regResultContent of regResults) {
256
- var propertyName = getPropertyNameFromPropDecorator(regResultContent);
257
- var defaultValue = getDefaultValueFromPropDecorator(regResultContent);
258
- if (propertyName && props[propertyName]) {
259
- props[propertyName].defaultValue = defaultValue;
260
- }
255
+ }`;
256
+ if (shared_1.isExtensionEnv) {
257
+ wcTypings = `import { VueComponentBaseProps } from "@omnia/fx/ux";
258
+ ${wcTypings}`;
259
+ }
260
+ else {
261
+ wcTypings = `import { VueComponentBaseProps } from "../../../../client/fx/ux/index";
262
+ ${wcTypings}`;
263
+ }
264
+ const elementNamespaces = {};
265
+ const wcNamespace = (0, shared_1.getBuildOption)()?.componentNamespace;
266
+ const info = shared_1.ConfigurationManager.outputInfo.get();
267
+ info.wc = {
268
+ namespaces: wcNamespace ? [wcNamespace] : null,
269
+ mappings: {}
270
+ };
271
+ await tooling_1.utils.asyncForEach(componentRegistrations, async (wc) => {
272
+ wcTypings = generateWebComponentTypings(wc, wcTypings, info, elementNamespaces);
273
+ if ((0, shared_1.getBuildOption)().docResourceManifestId) {
274
+ await buildDoc(wc);
261
275
  }
276
+ });
277
+ if (Object.keys(elementNamespaces).length > 0) {
278
+ let result = `declare global {
279
+ //{{namespace}}
280
+ }`;
281
+ Object.keys(elementNamespaces).forEach(key => {
282
+ result = result.replace("//{{namespace}}", `
283
+ let ${key}: ${JSON.stringify(elementNamespaces[key], null, 2)
284
+ .replace(/\"typeof /g, "typeof ").replace(/ <<end>>\"/g, "")}
285
+ //{{namespace}}
286
+ `);
287
+ });
288
+ wcTypings = wcTypings + `
289
+ ${result}
290
+ `;
262
291
  }
292
+ if (Object.keys(docResult).length > 0) {
293
+ fsExtra.outputFileSync(docPath, `
294
+ import { extendApi } from "@omnia/fx";
295
+ import { ComponentDoc } from "@omnia/fx-models";
296
+
297
+ extendApi(api => api.fx.docs.registrations, api => {
298
+
299
+ const registrations: { [elementName: string]: ComponentDoc } = ${JSON.stringify(docResult)}
300
+
301
+ Object.keys(registrations).forEach(elementName => {
302
+ api.register(elementName, registrations[elementName]);
303
+ });
304
+ });
305
+ `);
306
+ // create dynamic doc manifest
307
+ tooling_composers_1.ManifestRegistry.setCurrentManifestPath(`${path_1.default.relative(tooling_1.utils.root(""), path_1.default.resolve(__dirname))}/`);
308
+ tooling_composers_1.Composer
309
+ .registerManifest((0, shared_1.getBuildOption)().docResourceManifestId || new fx_models_1.Guid(`${tooling_1.utils.generateGuid()}`), "omnia.fx.docs.components.registraions")
310
+ .registerResources({
311
+ resourcePaths: ["./ComponentDocRegistrations.ts"]
312
+ })
313
+ .withTarget(fx_models_1.ClientManifestTargetTypes.docs)
314
+ .extendApi(api => api.fx.docs.registrations);
315
+ tooling_composers_1.ManifestRegistry.setCurrentManifestPath();
316
+ }
317
+ shared_1.ConfigurationManager.webComponentTypings.update(wcTypings);
318
+ shared_1.ConfigurationManager.outputInfo.update(info);
319
+ tooling_1.utils.logTime('Done - Generate components typings and documentation', startTime);
263
320
  }
264
- function getDefaultValueFromPropDecorator(propDecorator) {
265
- //Since default value is complex, so we cannot use regex to get it
266
- var defaultValue = '';
267
- var startIndex = propDecorator.indexOf("default") + "default".length;
268
- var regularValueReg = /[a-zA-Z0-9_.]/;
269
- var scope = 0;
270
- let start = false;
271
- let enteredScope = false;
272
- let enteredScopeKind = "";
273
- var beforeCharacter = '';
274
- var character = '';
275
- for (var index = startIndex; index < propDecorator.length; index++) {
276
- beforeCharacter = character;
277
- character = propDecorator[index];
278
- if (start) {
279
- //IF the first default value character is not a object begin ({...), then we mark a flag to stop by ending at a normal text
280
- if (!defaultValue.trim() && (character === "{" || character === "[" || character === "'" || character === '"')) {
281
- enteredScope = true;
321
+ exports.generateComponentTypingsAndDoc = generateComponentTypingsAndDoc;
322
+ function generateWebComponentTypings(wc, template, info, elementNamespace) {
323
+ // export default defineVueWebComponent
324
+ const wcPath = wc.componentOptions.entryPointPath;
325
+ let content = fsExtra.readFileSync(wcPath, 'utf8');
326
+ if (content.indexOf("defineVueComponent") > -1) {
327
+ if (!new RegExp('export\\s+default\\s+').test(content)) {
328
+ throw new Error(`Missing statement 'export default a vue web component' in ${wcPath}`);
329
+ }
330
+ let friendlyManifestId = `wc${wc.manifest.resourceId.toString().replace(/-/g, '').toLowerCase()}`;
331
+ let importPath = wcPath.substring(0, wcPath.lastIndexOf('.tsx'));
332
+ if (importPath.indexOf("./") === 0) {
333
+ importPath = importPath.replace("./", "");
334
+ }
335
+ if (shared_1.isExtensionEnv) {
336
+ importPath = `../../../../${importPath}`;
337
+ }
338
+ else {
339
+ importPath = `../../../../${importPath}`;
340
+ }
341
+ if (info.wc.namespaces) {
342
+ let elementName = wc.componentOptions.elementName.replace(/-/g, ".");
343
+ const namespace = (wc.componentOptions.namespace === true ? "" : wc.componentOptions.namespace) || (0, shared_1.getBuildOption)()?.componentNamespace;
344
+ if (namespace && elementName.indexOf(`${namespace}.`) !== 0) {
345
+ elementName = `${namespace}.${elementName}`;
282
346
  }
283
- defaultValue += character;
284
- if (enteredScope && character.trim()) {
285
- if (character === "{" && (!enteredScopeKind || enteredScopeKind === "{")) {
286
- enteredScopeKind = "{";
287
- scope++;
288
- }
289
- else if (character === "}" && enteredScopeKind === "{") {
290
- scope--;
291
- if (scope === 0)
292
- break;
293
- }
294
- else if (character === "[" && (!enteredScopeKind || enteredScopeKind === "[")) {
295
- enteredScopeKind = "[";
296
- scope++;
297
- }
298
- else if (character === "]" && enteredScopeKind === "]") {
299
- scope--;
300
- if (scope === 0)
301
- break;
302
- }
303
- else if (character === "'" && !enteredScopeKind) {
304
- enteredScopeKind = "'";
305
- }
306
- else if (character === "'" && enteredScopeKind === "'" && beforeCharacter !== '\\') {
307
- break;
308
- }
309
- else if (character === '"' && !enteredScopeKind) {
310
- enteredScopeKind = '"';
311
- }
312
- else if (character === '"' && enteredScopeKind === '"' && beforeCharacter !== '\\') {
313
- break;
314
- }
347
+ if (info.wc.namespaces && info.wc.namespaces.indexOf(elementName.split(".")[0]) === -1) {
348
+ info.wc.namespaces.push(elementName.split(".")[0]);
315
349
  }
316
- if (!enteredScope && defaultValue.trim() && character && !regularValueReg.test(character))
317
- break;
318
- }
319
- if (character === ":")
320
- start = true;
321
- }
322
- return defaultValue.trim();
323
- }
324
- function getPropertyNameFromPropDecorator(propDecorator) {
325
- propDecorator = propDecorator.substring(propDecorator.lastIndexOf(')') + 1);
326
- propDecorator = propDecorator.substring(0, propDecorator.lastIndexOf(':'));
327
- var name = propDecorator.trim();
328
- name = name.replace("?", ""); //remove optional in name
329
- return name;
330
- }
331
- function getComponentProperties(rootModel, key, props) {
332
- var model = rootModel[key];
333
- var properties = model.properties;
334
- for (var property of properties) {
335
- props[property.name] = {
336
- documentation: property.documentation,
337
- type: property.type || 'any'
338
- };
339
- }
340
- if (model.extends) {
341
- for (var extend of model.extends) {
342
- if (extend !== 'any') {
343
- getComponentProperties(rootModel, extend, props);
350
+ info.wc.mappings[elementName] = wc.componentOptions.elementName;
351
+ try {
352
+ populateElementNamespace(elementNamespace, elementName, friendlyManifestId);
353
+ }
354
+ catch (ex) {
355
+ tooling_1.utils.log(`Have a exception in building element namespace with element name: ${wc.componentOptions.elementName}`, tooling_1.utils.LogTypes.Error);
356
+ console.error(ex);
357
+ throw new Error("Exit, have an exception.");
344
358
  }
345
359
  }
360
+ return template
361
+ .replace(/\/\/{{importWC}}/, `import ${friendlyManifestId} from '${importPath}';
362
+ //{{importWC}}`)
363
+ .replace(/\/\/{{elementName}}/, `"${wc.componentOptions.elementName}": typeof ${friendlyManifestId} extends { propsDefinition: infer TProp } ? (TProp & Omit<VueComponentBaseProps, keyof TProp>) : typeof ${friendlyManifestId} extends (...args: any[]) => any ? ExtractJsxProps<Pick<ReturnType<typeof ${friendlyManifestId}>, "propsDefinition">> : never
364
+ //{{elementName}}`);
365
+ // .replace(/\/\/{{nselementName}}/, `"${elementName}": { new(...args: any[]): { $props: typeof ${friendlyManifestId}.propsDefinition & Omit<VueComponentBaseProps, keyof typeof ${friendlyManifestId}.propsDefinition> } }
366
+ // //{{nselementName}}`)
346
367
  }
368
+ return template;
347
369
  }
348
- function getWebComponentAndMainInterface(interfacePaths) {
349
- var result = {};
350
- var infoReg = /\/\*@WebComponentInterface\([^\)]+\)\*\/[ \n\r]+export[ ]+interface[ ]+[^ ]+/m;
351
- var elementReg = /\([^\)]+\)/m;
352
- for (var path of interfacePaths) {
353
- var fileContent = readFile(path);
354
- var infoRegResult = infoReg.exec(fileContent);
355
- if (infoRegResult) {
356
- var infoRegResultContent = infoRegResult[0];
357
- var elementRegResult = elementReg.exec(infoRegResultContent);
358
- var elementRegResultContent = elementRegResult[0];
359
- var element = elementRegResultContent.substring(2, elementRegResultContent.length - 2);
360
- var interfaceName = infoRegResultContent.substring(infoRegResultContent.lastIndexOf(' ') + 1);
361
- result[element] = {
362
- interface: interfaceName,
363
- interfaceFilePath: path
364
- };
365
- }
370
+ function importSnippetCode(content, filePath) {
371
+ let result = content;
372
+ const ext = path_1.default.extname(filePath);
373
+ if (filePath.indexOf(".md.ts") > -1) {
374
+ result = content.replace(/\@import\/.*;/g, function (match) {
375
+ let fromLine = 0;
376
+ let toLine = 0;
377
+ const indexStartLine = match.indexOf("{");
378
+ if (indexStartLine > -1) {
379
+ const numbers = match.substring(indexStartLine + 1, match.indexOf("}")).split("-");
380
+ fromLine = Number(numbers[0]);
381
+ toLine = Number(numbers[1]);
382
+ }
383
+ const fileName = match.substring(0, indexStartLine || match.length - 1)
384
+ .replace("@import/", "")
385
+ .replace(";", "");
386
+ let fileContent = fs_1.default.readFileSync(fileName, 'utf-8');
387
+ if (fromLine > 0) {
388
+ fileContent = fileContent.split(/\r?\n/).slice(fromLine - 1, toLine).join("\n");
389
+ }
390
+ return fileContent;
391
+ });
366
392
  }
367
393
  return result;
368
394
  }
369
- function filterInterfaceFilePaths(model, scanPaths) {
370
- var filesPath = {};
371
- for (var key in model) {
372
- let filePath = model[key].fileName;
373
- if (filePath) {
374
- filePath = filePath.replace(/\\/g, "/");
375
- if (scanPaths.find(path => path.indexOf(filePath) > -1) !== undefined) {
376
- filesPath[filePath] = true;
395
+ exports.importSnippetCode = importSnippetCode;
396
+ function populateElementNamespace(namespace, elementName, importElement) {
397
+ const parts = elementName.split(".");
398
+ for (let i = 0; i < parts.length; i++) {
399
+ const name = parts[i];
400
+ if (typeof namespace === "string") {
401
+ throw new Error("Build element namespace -> that element name contain another element name");
402
+ }
403
+ if (!namespace[name]) {
404
+ if (i === parts.length - 1) {
405
+ namespace[name] = `typeof ${importElement} extends { propsDefinition: infer TProp } ? { new(...args: any[]): { $props: TProp & Omit<VueComponentBaseProps, keyof TProp> } } : typeof ${importElement} <<end>>`;
406
+ }
407
+ else {
408
+ namespace = namespace[name] = {};
377
409
  }
378
410
  }
379
- }
380
- return filesPath;
381
- }
382
- //function getFiles(filepath) {
383
- // return fs.readdirSync(filepath).filter(function (file) {
384
- // return fs.statSync($.path.join(filepath, file)).isFile();
385
- // });
386
- //}
387
- function writeFile(filepath, content) {
388
- fs.writeFileSync(filepath, content);
389
- }
390
- function readFile(filePath) {
391
- return fs.readFileSync(filePath, 'utf-8');
392
- }
393
- function getAllFilesInFolderRecursively(dirPath) {
394
- var files = [];
395
- if (fs.existsSync(dirPath)) {
396
- var paths = fs.readdirSync(dirPath).map(function (file) { return { dirPath: dirPath, filePath: dirPath + '\\' + file }; });
397
- files = paths.filter(function (path) {
398
- return fs.statSync(path.filePath).isFile() && path.filePath.indexOf('.manifest.ts') >= 0;
399
- });
400
- var folders = paths.filter(function (path) {
401
- return fs.statSync(path.filePath).isFile() === false;
402
- });
403
- for (var path of folders) {
404
- files = files.concat(getAllFilesInFolderRecursively(path.filePath));
411
+ else {
412
+ if (i === parts.length - 1) {
413
+ namespace[`${name}$`] = `typeof ${importElement} extends { propsDefinition: infer TProp } ? { new(...args: any[]): { $props: TProp & Omit<VueComponentBaseProps, keyof TProp> } } : typeof ${importElement} <<end>>`;
414
+ // throw new Error("Build element namespace -> Exist an element name contain a above that element name");
415
+ }
416
+ else {
417
+ if (typeof namespace[name] === "string") {
418
+ namespace[`${name}$`] = namespace[name];
419
+ namespace[name] = {};
420
+ }
421
+ namespace = namespace[name];
422
+ }
405
423
  }
406
424
  }
407
- return files;
408
- }
409
- ;
410
- function extractDocPathForComponents(componentRegistrations) {
411
- let componentsDocCount = 0;
412
- let paths = [];
413
- componentRegistrations.forEach((comp) => {
414
- let defPaths = comp.componentOptions.documentations;
415
- if (defPaths) {
416
- componentsDocCount++;
417
- defPaths.forEach((defPath) => {
418
- paths.push((0, shared_1.convertManifestPathToEntryPath)(comp.manifestPath, [defPath])[0]);
419
- //paths.push($.tooling.utils.root(convertManifestPathToEntryPath(comp.manifestPath, [defPath])[0]));
420
- });
421
- }
422
- });
423
- return { componentsDocCount, paths };
424
425
  }