aboutsummaryrefslogtreecommitdiff
path: root/dist/index.js
blob: 447eeb16e3e6b328a715ac9f8c08d432ad2977a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
'use strict';

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var parseAttr = require('md-attr-parser');

var htmlElemAttr = require('html-element-attributes');

var isWhiteSpace = require('is-whitespace-character');

var supportedElements = new Set(['link', 'atxHeading', 'strong', 'emphasis', 'deletion', 'code', 'setextHeading', 'fencedCode', 'reference', 'footnoteCall', 'autoLink']);
var blockElements = new Set(['atxHeading', 'setextHeading']);
var particularElements = new Set(['fencedCode']);
var particularTokenize = {};

var DOMEventHandler = require('./dom-event-handler.js');
/* Table convertion between type and HTML tagName */


var convTypeTag = {
  image: 'img',
  link: 'a',
  heading: 'h1',
  strong: 'strong',
  emphasis: 'em',
  "delete": 's',
  inlineCode: 'code',
  code: 'code',
  linkReference: 'a',
  '*': '*'
};
/* This function is a generic function that transform
 * the tokenize function a node type to a version that understand
 * attributes.
 *
 * The tokenizer function of strong will tokenize **STRONG STRING**
 * this function extand it to tokenize **STRONG STRING**{list=of attributes}
 *
 * - The prefix is '\n' for block node and '' for inline one
 *
 * The syntax is for atxHeading ::
 * ## HEAD TITLE
 * {attributes}
 *
 * Attributes are on the next line.
 *
 * - The old parser is the old function user to tokenize
 * - The config is the configuration of this plugin
 *
 */

function tokenizeGenerator(prefix, oldParser, config) {
  function token(eat, value, silent) {
    // This we call the old tokenize
    var self = this;
    var eaten = oldParser.call(self, eat, value, silent);
    var index = 0;
    var parsedAttr;
    var length = value.length;

    if (!eaten || !eaten.position) {
      return undefined;
    }

    var type = convTypeTag[eaten.type];
    index = eaten.position.end.offset - eaten.position.start.offset; // Then we check for attributes

    if (index + prefix.length < length && value.charAt(index + prefix.length) === '{') {
      // If any, parse it
      parsedAttr = parseAttr(value, index + prefix.length, config.mdAttrConfig);
    } // If parsed configure the node


    if (parsedAttr) {
      if (config.scope && config.scope !== 'none') {
        var filtredProp = filterAttributes(parsedAttr.prop, config, type);

        if (filtredProp !== {}) {
          if (eaten.data) {
            eaten.data.hProperties = filtredProp;
          } else {
            eaten.data = {
              hProperties: filtredProp
            };
          }
        }
      }

      eaten = eat(prefix + parsedAttr.eaten)(eaten);
    }

    return eaten;
  } // Return the new tokenizer function


  return token;
}

function tokenizeModifierGenerator(oldParser, config) {
  function token(eat, value, silent) {
    // This we call the old tokenize
    var self = this;
    var eaten = oldParser.call(self, eat, value, silent);
    var index = 0;

    if (!eaten || !eaten.position || !eaten.children || eaten.children.length <= 0) {
      return eaten;
    }

    var type = convTypeTag[eaten.type];
    var lastChild = eaten.children[eaten.children.length - 1];

    if (!lastChild.value || lastChild.value.length <= 0 || lastChild.value[lastChild.value.length - 1] !== '}') {
      return eaten;
    }

    index = lastChild.value.lastIndexOf('{');

    if (index <= 0) {
      return eaten;
    }

    var parsedAttr = parseAttr(lastChild.value, index, config.mdAttrConfig);

    if (parsedAttr.eaten.length !== lastChild.value.length - index) {
      return eaten;
    }

    index -= 1;

    while (index >= 0 && isWhiteSpace(lastChild.value[index])) {
      index -= 1;
    }

    if (index < 0) {
      return eaten;
    } // If parsed configure the node


    if (parsedAttr) {
      if (config.scope && config.scope !== 'none') {
        var filtredProp = filterAttributes(parsedAttr.prop, config, type);

        if (filtredProp !== {}) {
          if (eaten.data) {
            eaten.data.hProperties = filtredProp;
          } else {
            eaten.data = {
              hProperties: filtredProp
            };
          }
        }
      }

      lastChild.value = lastChild.value.slice(0, index + 1);
    }

    return eaten;
  } // Return the new tokenizer function


  return token;
} // A generic function to parse attributes


function filterAttributes(prop, config, type) {
  var scope = config.scope;
  var extend = config.extend;
  var allowDangerousDOMEventHandlers = config.allowDangerousDOMEventHandlers;
  var specific = htmlElemAttr;

  var extendTag = function (extend) {
    var t = {};
    Object.getOwnPropertyNames(extend).forEach(function (p) {
      t[convTypeTag[p]] = extend[p];
    });
    return t;
  }(extend); // Delete empty key/class/id attributes


  Object.getOwnPropertyNames(prop).forEach(function (p) {
    if (p !== 'key' && p !== 'class' && p !== 'id') {
      prop[p] = prop[p] || '';
    }
  });

  var isDangerous = function isDangerous(p) {
    return DOMEventHandler.includes(p);
  };

  var isSpecific = function isSpecific(p) {
    return type in specific && specific[type].includes(p);
  };

  var isGlobal = function isGlobal(p) {
    return htmlElemAttr['*'].includes(p) || p.match(/^aria-[a-z][a-z.-_\d]*$/) || p.match(/^data-[a-z][a-z_.-0-9]*$/);
  };

  var inScope = function inScope() {
    return false;
  }; // Function used to `or combine` two other function.


  var orFunc = function orFunc(fun, fun2) {
    return function (x) {
      return fun(x) || fun2(x);
    };
  }; // Respect the scope configuration


  switch (scope) {
    case 'none':
      // Plugin is disabled
      break;

    case 'permissive':
    case 'every':
      if (allowDangerousDOMEventHandlers) {
        inScope = function inScope() {
          return true;
        };
      } else {
        inScope = function inScope(x) {
          return !isDangerous(x);
        };
      }

      break;

    case 'extended':
    default:
      inScope = function inScope(p) {
        return extendTag && type in extendTag && extendTag[type].includes(p);
      };

      inScope = orFunc(inScope, function (p) {
        return '*' in extendTag && extendTag['*'].includes(p);
      });
    // Or if it in the specific scope, fallthrough

    case 'specific':
      inScope = orFunc(inScope, isSpecific);
    // Or if it in the global scope fallthrough

    case 'global':
      inScope = orFunc(inScope, isGlobal);

      if (allowDangerousDOMEventHandlers) {
        // If allowed add dangerous attributes to global scope
        inScope = orFunc(inScope, isDangerous);
      }

  } // If an attributes isn't in the scope, delete it


  Object.getOwnPropertyNames(prop).forEach(function (p) {
    if (!inScope(p)) {
      delete prop[p];
    }
  });
  return prop;
}
/* This is a special modification of the function tokenizeGenerator
 * to parse the fencedCode info string and the fallback
 * customAttr parser
 *
 * It's only temporary
 */


function tokenizeFencedCode(oldParser, config) {
  var prefix = '\n';

  function token(eat, value, silent) {
    // This we call the old tokenize
    var self = this;
    var eaten = oldParser.call(self, eat, value, silent);
    var parsedAttr;
    var parsedByCustomAttr = false;

    if (!eaten || !eaten.position) {
      return undefined;
    }

    var type = convTypeTag[eaten.type]; // First, parse the info string
    // which is the 'lang' attributes of 'eaten'.

    if (eaten.lang) {
      // Then the meta
      if (eaten.meta) {
        parsedAttr = parseAttr(eaten.meta);
      } else {
        // If it's an old version, we can still find from the attributes
        // from 'value' ¯\_(ツ)_/¯
        // Bad hack, will be deleted soon
        parsedAttr = parseAttr(value, value.indexOf(' '));
      }
    } // If parsed configure the node


    if (parsedAttr) {
      if (config.scope && config.scope !== 'none') {
        var filtredProp = filterAttributes(parsedAttr.prop, config, type);

        if (filtredProp !== {}) {
          if (eaten.data) {
            eaten.data.hProperties = _objectSpread(_objectSpread({}, eaten.data.hProperties), filtredProp);
          } else {
            eaten.data = {
              hProperties: filtredProp
            };
          }
        }
      }

      if (parsedByCustomAttr) {
        eaten = eat(prefix + parsedAttr.eaten)(eaten);
      }
    }

    return eaten;
  } // Return the new tokenizer function


  return token;
}

particularTokenize.fencedCode = tokenizeFencedCode;
remarkAttr.SUPPORTED_ELEMENTS = supportedElements;
module.exports = remarkAttr;
/* Function that is exported */

function remarkAttr(userConfig) {
  var parser = this.Parser;
  var defaultConfig = {
    allowDangerousDOMEventHandlers: false,
    elements: supportedElements,
    extend: {},
    scope: 'extended',
    mdAttrConfig: undefined,
    enableAtxHeaderInline: true,
    disableBlockElements: false
  };

  var config = _objectSpread(_objectSpread({}, defaultConfig), userConfig);

  if (!isRemarkParser(parser)) {
    throw new Error('Missing parser to attach `remark-attr` [link] (to)');
  }

  var tokenizers = parser.prototype.inlineTokenizers;
  var tokenizersBlock = parser.prototype.blockTokenizers; // For each elements, replace the old tokenizer by the new one

  config.elements.forEach(function (element) {
    if ((element in tokenizersBlock || element in tokenizers) && supportedElements.has(element)) {
      if (!config.disableBlockElements && blockElements.has(element)) {
        var oldElement = tokenizersBlock[element];
        tokenizersBlock[element] = tokenizeGenerator('\n', oldElement, config);
      } else if (particularElements.has(element)) {
        var _oldElement = tokenizersBlock[element];
        tokenizersBlock[element] = particularTokenize[element](_oldElement, config);
      } else {
        var _oldElement2 = tokenizers[element];
        var elementTokenize = tokenizeGenerator('', _oldElement2, config);
        elementTokenize.locator = tokenizers[element].locator;
        tokenizers[element] = elementTokenize;
      }

      if (config.enableAtxHeaderInline && element === 'atxHeading') {
        var _oldElement3 = tokenizersBlock[element];
        tokenizersBlock[element] = tokenizeModifierGenerator(_oldElement3, config);
      }
    }
  });
}

function isRemarkParser(parser) {
  return Boolean(parser && parser.prototype && parser.prototype.inlineTokenizers && parser.prototype.inlineTokenizers.link && parser.prototype.inlineTokenizers.link.locator);
}