LocalModulesHelpers.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const LocalModule = require("./LocalModule");
  7. /** @typedef {import("../javascript/JavascriptParser").ParserState} ParserState */
  8. /**
  9. * @param {string} parent parent module
  10. * @param {string} mod module to resolve
  11. * @returns {string} resolved module
  12. */
  13. const lookup = (parent, mod) => {
  14. if (mod.charAt(0) !== ".") return mod;
  15. var path = parent.split("/");
  16. var segments = mod.split("/");
  17. path.pop();
  18. for (let i = 0; i < segments.length; i++) {
  19. const seg = segments[i];
  20. if (seg === "..") {
  21. path.pop();
  22. } else if (seg !== ".") {
  23. path.push(seg);
  24. }
  25. }
  26. return path.join("/");
  27. };
  28. /**
  29. * @param {ParserState} state parser state
  30. * @param {string} name name
  31. * @returns {LocalModule} local module
  32. */
  33. exports.addLocalModule = (state, name) => {
  34. if (!state.localModules) {
  35. state.localModules = [];
  36. }
  37. const m = new LocalModule(name, state.localModules.length);
  38. state.localModules.push(m);
  39. return m;
  40. };
  41. /**
  42. * @param {ParserState} state parser state
  43. * @param {string} name name
  44. * @param {string} [namedModule] named module
  45. * @returns {LocalModule | null} local module or null
  46. */
  47. exports.getLocalModule = (state, name, namedModule) => {
  48. if (!state.localModules) return null;
  49. if (namedModule) {
  50. // resolve dependency name relative to the defining named module
  51. name = lookup(namedModule, name);
  52. }
  53. for (let i = 0; i < state.localModules.length; i++) {
  54. if (state.localModules[i].name === name) {
  55. return state.localModules[i];
  56. }
  57. }
  58. return null;
  59. };