processViewerDeclaration.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. module.exports = function (data, options) {
  2. /*
  3. {
  4. packageName: string,
  5. moduleName: string,
  6. importsToRemove: Array<string>,
  7. classMap
  8. }
  9. */
  10. var str = "" + data;
  11. // this regex is not working on node 6 for some reason:
  12. // str = str.replace(/declare module 'babylonjs-viewer\/' {((?!(declare))(.|\n))*\n}/g, '');
  13. let lines = str.split('\n');
  14. var firstIndex = lines.findIndex((line => { return line.indexOf(`'${options.packageName}/'`) !== -1 }));
  15. var lastIndex = lines.findIndex(((line, idx) => { return line.trim() === '}' && idx > firstIndex }));
  16. lines.splice(firstIndex, lastIndex - firstIndex + 1);
  17. str = lines.join('\n');
  18. str = str.replace(/declare module (.*) {/g, `declare module ${options.moduleName} {`);
  19. str = str.replace("import * as BABYLON from 'babylonjs';", "");
  20. let regexp = new RegExp(`import {(.*)} from ['"]${options.packageName}(.*)['"];`, 'g');
  21. str = str.replace(regexp, '');
  22. if (options.importsToRemove) {
  23. while (options.importsToRemove.length) {
  24. let remove = options.importsToRemove.pop();
  25. str = str.replace(new RegExp(`import '${remove}';`), '');
  26. }
  27. }
  28. //find all used BABYLON and BABYLON-Loaders classes:
  29. if ((options.classMap)) {
  30. Object.keys(options.classMap).forEach(package => {
  31. var babylonRegex = new RegExp(`import {(.*)} from ['"](${package})['"];`, "g");
  32. var match = babylonRegex.exec(str);
  33. let classes = new Set();
  34. while (match != null) {
  35. if (match[1]) {
  36. match[1].split(",").forEach(element => {
  37. classes.add(element.trim());
  38. });
  39. }
  40. match = babylonRegex.exec(str);
  41. }
  42. str = str.replace(babylonRegex, '');
  43. classes.forEach(cls => {
  44. let rg = new RegExp(`([ <])(${cls})([^\\w])`, "g")
  45. str = str.replace(rg, `$1${options.classMap[package]}.$2$3`);
  46. });
  47. })
  48. }
  49. str = str.replace(/export {(.*)};/g, '');
  50. str = str.split("\n").filter(line => line.trim()).join("\n");
  51. return str;
  52. }