1- 'use strict'
1+ 'use strict' ;
22
33const fs = require ( 'fs' ) ;
44const path = require ( 'path' ) ;
@@ -8,10 +8,16 @@ const {match} = require('posthtml/lib/api');
88const expressions = require ( 'posthtml-expressions' ) ;
99
1010module . exports = ( options = { } ) => {
11- options . root = options . root || './' ;
11+ options . root = options . root ? path . resolve ( options . root ) : process . cwd ( ) ;
1212 options . encoding = options . encoding || 'utf-8' ;
1313
1414 return function posthtmlInclude ( tree ) {
15+ const cwd = options . cwd ?
16+ path . resolve ( options . cwd ) :
17+ ( tree . options . from ?
18+ path . dirname ( path . resolve ( tree . options . from ) ) :
19+ process . cwd ( ) ) ;
20+
1521 tree . parser = tree . parser || parser ;
1622 tree . match = tree . match || match ;
1723
@@ -20,17 +26,23 @@ module.exports = (options = {}) => {
2026 let content ;
2127 let subtree ;
2228 let source ;
23- let posthtmlExpressionsOptions = options . posthtmlExpressionsOptions || { locals : false } ;
29+ let posthtmlExpressionsOptions = options . posthtmlExpressionsOptions || {
30+ locals : false
31+ } ;
2432 if ( options . delimiters ) {
2533 posthtmlExpressionsOptions . delimiters = options . delimiters ;
2634 }
2735
2836 if ( src ) {
29- src = path . resolve ( options . root , src ) ;
37+ src = path . isAbsolute ( src ) ?
38+ path . resolve ( cwd , src ) :
39+ path . join ( options . root , src ) ;
3040 source = fs . readFileSync ( src , options . encoding ) ;
3141
3242 try {
33- const localsRaw = node . attrs . locals || ( node . content ? node . content . join ( ) . replace ( / \n / g, '' ) : false ) ;
43+ const localsRaw =
44+ node . attrs . locals ||
45+ ( node . content ? node . content . join ( ) . replace ( / \n / g, '' ) : false ) ;
3446 const localsJson = JSON . parse ( localsRaw ) ;
3547 posthtmlExpressionsOptions = {
3648 ...posthtmlExpressionsOptions ,
@@ -46,10 +58,18 @@ module.exports = (options = {}) => {
4658 }
4759
4860 subtree = tree . parser ( source ) ;
61+ subtree . options = subtree . options || { } ;
62+ subtree . options . from = path . isAbsolute ( src ) ?
63+ src :
64+ ( tree . options . from ?
65+ path . relative ( tree . options . from , src ) :
66+ src ) ;
4967 subtree . match = tree . match ;
5068 subtree . parser = tree . parser ;
5169 subtree . messages = tree . messages ;
52- content = source . includes ( 'include' ) ? posthtmlInclude ( subtree ) : subtree ;
70+ content = source . includes ( 'include' ) ?
71+ posthtmlInclude ( subtree ) :
72+ subtree ;
5373
5474 if ( tree . messages ) {
5575 tree . messages . push ( {
0 commit comments