liusuyi
2023-04-24 4737f1e038743ced243c9e52423404d9034d6107
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
'use strict';
 
const CONSTANTS = require('./constants.js');
const SYNC = 'sync';
const ATTRIBUTE_PRIORITIES = [SYNC, 'async', 'defer'];
 
const common = require('./common.js');
const debug = common.debug;
const isScript = common.isScript;
const matches = common.matches;
const getScriptName = common.getScriptName;
 
const shouldUpdate = (options) => {
  if (ATTRIBUTE_PRIORITIES.indexOf(options.defaultAttribute) < 0) {
    throw new Error(`${CONSTANTS.PLUGIN}: invalid default attribute`);
  }
  return !(options.defaultAttribute === SYNC &&
           options.inline.test.length === 0 &&
           options.async.test.length === 0 &&
           options.defer.test.length === 0 &&
           options.module.test.length === 0);
};
 
const update = (assets, options, tags) => {
  const update = updateElement.bind(null, assets, options);
  return tags.map(update);
};
 
const updateElement = (assets, options, tag) => {
  return (isScript(tag))
    ? updateScriptElement(assets, options, tag)
    : tag;
};
 
const updateScriptElement = (assets, options, tag) => {
  debug(`${CONSTANTS.EVENT}: processing <script> element: ${JSON.stringify(tag)}`);
  return (isInline(options, tag))
    ? replaceWithInlineElement(assets, options, tag)
    : updateSrcElement(options, tag);
};
 
const isInline = (options, tag) =>
  matches(getScriptName(options, tag), options.inline.test);
 
const replaceWithInlineElement = (assets, options, tag) => {
  const scriptName = getScriptName(options, tag);
  const asset = assets[scriptName];
  if (!asset) throw new Error(`${CONSTANTS.PLUGIN}: no asset with href '${scriptName}'`);
  const newTag = {
    tagName: 'script',
    closeTag: true,
    innerHTML: asset.source()
  };
  debug(`${CONSTANTS.PLUGIN}: replaced by: ${JSON.stringify(newTag)}`);
  return newTag;
};
 
const updateSrcElement = (options, tag) => {
  const scriptName = getScriptName(options, tag);
  // select new attribute, if any, by priority
  let newAttribute;
  ATTRIBUTE_PRIORITIES.some(attribute => {
    if (matches(scriptName, options[attribute].test)) {
      newAttribute = attribute;
      return true;
    }
  });
  if (!newAttribute) newAttribute = options.defaultAttribute;
  if (newAttribute !== SYNC) {
    tag.attributes[newAttribute] = true;
  }
  // possibly overwrite existing type attribute
  if (matches(scriptName, options.module.test)) {
    tag.attributes.type = 'module';
  }
  debug(`${CONSTANTS.PLUGIN}: updated to: ${JSON.stringify(tag)}`);
  return tag;
};
 
module.exports = {
  shouldUpdate,
  update
};