Plugin.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. import type PugLexer from "pug-lexer";
  2. import type { PugPlugin, PugToken, PugAST, PugNode, PugNodes, PugNodeAttribute, LexerPlugin, Options } from "pug";
  3. import type PupperCompiler from "..";
  4. import { Hook } from "./plugin/Hook";
  5. import { ConditionalHook } from "./plugin/hooks/ConditionalHook";
  6. import { ForEachHook } from "./plugin/hooks/ForEachHook";
  7. import { ComponentHook } from "./plugin/hooks/ComponentHook";
  8. import { PropertyHook } from "./plugin/hooks/PropertyHook";
  9. import { PupperToAlpineHook } from "./plugin/hooks/PupperToAlpineHook";
  10. import { ImportHook } from "./plugin/hooks/ImportHook";
  11. import { CompilerNode } from "../model/core/nodes/CompilerNode";
  12. import { StyleAndScriptHook } from "./plugin/hooks/StyleAndScriptHook";
  13. import { AstNode } from "./plugin/nodes/AstNode";
  14. import { EachNode } from "./plugin/nodes/EachNode";
  15. import { TagNode } from "./plugin/nodes/TagNode";
  16. import { NodeModel } from "../model/core/NodeModel";
  17. import { MixinNode } from "./plugin/nodes/MixinNode";
  18. import { ConditionalNode } from "./plugin/nodes/ConditionalNode";
  19. import pugError from "pug-error";
  20. import { Pug } from "../typings/pug";
  21. import { TemplateTagNode } from "./plugin/nodes/tags/TemplateTagNode";
  22. type THookArray = { new(plugin: Plugin): Hook }[];
  23. export type TPugNodesWithTypes = {
  24. [key in PugNodes["type"]]: Extract<PugNodes, { type: key }>
  25. }
  26. export type TPugNodeTypes = Pick<PugNodes, "type">["type"];
  27. /**
  28. * Anything that extends a compiler node.
  29. */
  30. export type TCompilerNode<T extends CompilerNode = any> = T;
  31. /**
  32. * The relationship between a pug node type and a plugin node.
  33. */
  34. interface INodeModelPugNodeTypeRelationship extends Record<TPugNodeTypes, TCompilerNode> {
  35. Tag: TagNode;
  36. Conditional: ConditionalNode;
  37. Each: EachNode;
  38. Mixin: MixinNode;
  39. //Block: AstNode;
  40. }
  41. /**
  42. * Retrieves a node model by the pug node type.
  43. */
  44. type TNodeModelByPugNodeType<TNode extends TPugNodeTypes> = Pick<INodeModelPugNodeTypeRelationship, TNode>;
  45. /**
  46. * Retrieves the node model by the pug node.
  47. */
  48. type TNodeModelByPugNode<TNode extends PugNodes, TNodeType extends TPugNodeTypes = TNode["type"]> = TNodeModelByPugNodeType<TNodeType>;
  49. export { PugToken, PugAST, PugNode, PugNodeAttribute, PugNodes, CompilerNode as IPluginNode };
  50. /**
  51. * Documentation for this class is available in the PugPlugin interface
  52. */
  53. export default class Plugin implements PugPlugin {
  54. public static Hooks: THookArray = [
  55. ConditionalHook,
  56. //ForEachHook,
  57. ComponentHook,
  58. PropertyHook,
  59. PupperToAlpineHook,
  60. ImportHook,
  61. StyleAndScriptHook
  62. ];
  63. /**
  64. * Creates a compiler node from a pug node.
  65. * @param node The pug node.
  66. * @param parent The parent node to this node.
  67. * @returns
  68. */
  69. public static createNode<TNode extends PugNodes>(node: TNode, parent: NodeModel): TNodeModelByPugNode<TNode> | CompilerNode {
  70. // If somehow this happens, prevent from going further
  71. if (node instanceof CompilerNode) {
  72. return node;
  73. }
  74. switch(node.type) {
  75. default:
  76. return new CompilerNode(node, parent);
  77. case "Each":
  78. return new EachNode(node, parent);
  79. case "Tag":
  80. return this.makeTagNode(node, parent);
  81. case "Mixin":
  82. return new MixinNode(node, parent);
  83. case "Conditional":
  84. return new ConditionalNode(node, parent);
  85. }
  86. }
  87. /**
  88. * Creates a compiler tag node.
  89. * @param node The pug node related to this new node.
  90. * @param parent The parent node related to this node.
  91. * @returns
  92. */
  93. public static makeTagNode(node: Pug.Nodes.TagNode, parent: NodeModel): TagNode {
  94. switch(node.name) {
  95. default:
  96. return new TagNode(node, parent);
  97. case "template":
  98. return new TemplateTagNode(node, parent);
  99. }
  100. }
  101. /**
  102. * A handler for the plugin filters.
  103. */
  104. private filters: Record<string, Function[]> = {};
  105. /**
  106. * Any data to be shared between hooks and phases.
  107. */
  108. public sharedData: Record<any, any> = {};
  109. public lex: LexerPlugin;
  110. constructor(
  111. public compiler: PupperCompiler,
  112. public options: Options & {
  113. contents?: string
  114. }
  115. ) {
  116. this.prepareHooks();
  117. // Create the lexer
  118. this.lex = {
  119. isExpression: (lexer: PugLexer.Lexer, exp: string) =>
  120. this.applyFilters<string, boolean>("testExpression", exp)
  121. };
  122. }
  123. /**
  124. * Prepares a list of ordered hooks.
  125. */
  126. protected prepareHooks() {
  127. const hookOrder: string[] = [];
  128. Plugin.Hooks
  129. // Create the hooks instances
  130. .map((Hook) => new Hook(this))
  131. .sort((b, a) => {
  132. if (a.$before) {
  133. const $before = a.$before?.map((hook) => hook.prototype.constructor.name);
  134. // If A needs to run before B
  135. if ($before.includes(b.constructor.name)) {
  136. return -1;
  137. } else {
  138. return 1;
  139. }
  140. }
  141. if (a.$after) {
  142. const $after = a.$after.map((hook) => hook.prototype.constructor.name);
  143. // If A needs to run after B
  144. if ($after.includes(b.constructor.name)) {
  145. return 1;
  146. } else {
  147. return -1;
  148. }
  149. }
  150. return 0;
  151. })
  152. .forEach((hook) => {
  153. // Prepare their filters
  154. hook.prepareFilters();
  155. hookOrder.push(hook.constructor.name);
  156. });
  157. }
  158. /**
  159. * Retrieves the compiler options
  160. * @returns
  161. */
  162. public getCompilerOptions() {
  163. return this.options;
  164. }
  165. /**
  166. * Adds a filter to a given event.
  167. * @param filter The filter to be added.
  168. * @param callback The filter callback.
  169. * @returns
  170. */
  171. public addFilter(filter: string, callback: Function) {
  172. if (this.filters[filter] === undefined) {
  173. this.filters[filter] = [];
  174. }
  175. return this.filters[filter].push(callback);
  176. }
  177. public applyFilters<TValue, TResultingValue = TValue>(filter: string, value: TValue): TResultingValue {
  178. // If has no filters, return the initial value
  179. if (this.filters[filter] === undefined) {
  180. return value as any as TResultingValue;
  181. }
  182. try {
  183. for(let callback of this.filters[filter]) {
  184. value = callback(value);
  185. }
  186. } catch(e) {
  187. console.error(e);
  188. throw e;
  189. }
  190. return value as any as TResultingValue;
  191. }
  192. /**
  193. * Parses the children of a node.
  194. * @param node The node or node array to be parsed.
  195. * @returns
  196. */
  197. public parseChildren<TInput extends NodeModel | NodeModel[], TResult>(node: TInput) {
  198. if (Array.isArray(node)) {
  199. this.applyFilters("parse", node);
  200. node.forEach((node) => {
  201. this.parseChildren(node);
  202. });
  203. return node;
  204. }
  205. node.setChildren(
  206. this.applyFilters("parse", node.getChildren())
  207. );
  208. node.getChildren().forEach((child) => {
  209. if (child.hasChildren()) {
  210. this.parseChildren(child);
  211. }
  212. });
  213. return node;
  214. }
  215. /**
  216. * Parses an AST.
  217. * @param ast The AST to be parsed.
  218. * @returns
  219. */
  220. public parseNodes(ast: PugAST) {
  221. try {
  222. const astNode = new AstNode(ast, this);
  223. // Parse the AST children
  224. this.parseChildren(astNode);
  225. return astNode.toPugNode();
  226. } catch(e) {
  227. console.error(e);
  228. throw e;
  229. }
  230. }
  231. /**
  232. * Pug filters implementations
  233. */
  234. public preLex(template: string) {
  235. this.options.contents = this.applyFilters("preLex", template);
  236. return this.options.contents;
  237. }
  238. public preParse(tokens: PugToken[]) {
  239. return this.applyFilters("lex", tokens);
  240. }
  241. public postParse(block: PugAST) {
  242. return this.parseNodes(block);
  243. }
  244. public preCodeGen(ast: PugAST): PugAST {
  245. return this.applyFilters("preCodeGen", ast);
  246. }
  247. public postCodeGen(code: string): string {
  248. return this.applyFilters("postCodeGen", code);
  249. }
  250. /**
  251. * Makes a compilation error.
  252. * @param code The error code.
  253. * @param message The error message.
  254. * @param data The error data.
  255. * @returns
  256. */
  257. public makeError(code: string, message: string, data: {
  258. line?: number;
  259. column?: number;
  260. } = {}) {
  261. return pugError(code, message, {
  262. ...data,
  263. filename: this.options.filename,
  264. src: this.options.contents
  265. } as any);
  266. }
  267. /**
  268. * Makes an error with "COMPILATION_ERROR" code.
  269. * @param message The error message.
  270. * @param data The error data.
  271. * @returns
  272. */
  273. public makeParseError(message: string, data: {
  274. line?: number;
  275. column?: number;
  276. } = {}) {
  277. return this.makeError("COMPILATION_ERROR", message, data);
  278. }
  279. }