-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
158 lines (127 loc) · 5.59 KB
/
index.js
File metadata and controls
158 lines (127 loc) · 5.59 KB
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
// rollup-plugin-wc-bulder
import { createFilter } from 'rollup-pluginutils'
const MagicString = require('magic-string')
const fs = require('fs')
const path = require('path')
const postcss = require('postcss')
const cleanCSS = new (require('clean-css'))()
const minifyHTML = require('html-minifier').minify
const localPkg = require(path.join(process.cwd(), 'package.json'))
export default function wcbuilder (options = {}) {
const filter = createFilter(options.include, options.exclude)
if (!localPkg.hasOwnProperty('repository')) {
throw new Error(`The local package.json must have a repository attribute with a url sub-attribute, such as:\n${JSON.stringify({
repository: {
type: 'git',
url: 'git+https://github.com/owner/repo.git'
}
}, null, 2)}\n`)
}
const build = {
css: null,
js: null,
template: null,
tagName: null,
processCSS (filepath) {
build.css = postcss.parse(fs.readFileSync(path.join(path.dirname(filepath), 'style.css')).toString())
let newRules = []
build.css.walkRules(rule => newRules.push(
rule.clone({
selector: build.transformSelector(rule.selector)
})
))
build.css.append(newRules)
build.css = cleanCSS.minify(build.css.toString()).styles
},
processJS (code) {
build.js = code
let regex = /customElements\.define\([\'|\"](.*)[\'|\"]\,/i
let tagName = regex.exec(build.js)
if (tagName === null) {
console.error('ERROR: tag.js must include a Custom Element Definition as follows:')
console.info(`customElements.define('tag-name', ClassIdentifier)`)
return console.error('Aborting...')
}
tagName = tagName[1]
if (!tagName || !tagName.includes('-')) {
return console.error(`ERROR: Custom element must have a tag name with at least one hyphen! Aborting...`)
}
build.tagName = tagName
},
processTemplate (filepath) {
build.template = fs.readFileSync(path.join(path.dirname(filepath), 'template.html')).toString()
},
transformSelector (selector) {
if (!this.tagName) {
return console.error(`ERROR ${this.filename}: Valid tag name not found. Aborting...`)
}
let regex = {
host: /\:host\((.*?)\)\s?/i,
hostContext: /\:host-context\((.*?)\)\s?/i,
slotted: /\:{2}slotted\((.*?)\)\s?/i
}
// STEP 1: Replace :host() instances
let result = regex.host.exec(selector)
selector = result === null ? selector : selector.replace(result[0].trim(), `${this.tagName}${result[1]}`)
// STEP 2: Replace host-context() instances
result = regex.hostContext.exec(selector)
selector = result === null ? selector : selector.replace(result[0].trim(), `${result[1]} ${this.tagName}`)
// STEP 3: Replace ::slotted() instances
result = regex.slotted.exec(selector)
selector = result === null ? selector : selector.replace(result[0].trim(), `${result[1]}`)
// STEP 4: Replace remaining :host instances
return selector.replace(/\:host/gi, this.tagName)
}
}
return {
name: 'wcbuilder',
transform (code, filepath) {
if (!filter(filepath)) {
return null
}
const magicString = new MagicString(code)
// Process Files
build.processJS(code)
build.processCSS(filepath)
build.processTemplate(filepath)
// Provide a base element check in each webcomponent file.
options.requiresBaseElement = options.hasOwnProperty('requiresBaseElement') ? options.requiresBaseElement : true
if (options.hasOwnProperty('dependencies')) {
let dependencyCheck = `(function () {
let missingDependencies = Array.from(new Set([${options.dependencies.map(dep => '\'' + dep + '\'')}])).filter(dep => !customElements.get(dep))
if (missingDependencies.length > 0) {
console.error(\`[ERROR] <${build.tagName}> Required dependenc\${missingDependencies.length !== 1 ? 'ies' : 'y'} not found: \${missingDependencies.map(d => \`<\${d}>\`).join(', ').replace(', ' + missingDependencies[missingDependencies.length - 1], ' and ' + missingDependencies[missingDependencies.length - 1])}\`)
missingDependencies.forEach((dep, i) => console.info(\`\${i+1}. <\${dep}> is available at \${'${localPkg.repository.url.replace(/git\+|\.git/gi, '')}'.replace('${build.tagName.replace('author-', '')}', dep.replace('author-', ''))}\`))
}
})();
`
magicString.prependLeft(0, dependencyCheck)
}
if (options.requiresBaseElement === true) {
let baseClassCheck = `
if (!window.hasOwnProperty('AuthorBaseElement')) {
console.error('[ERROR] <${build.tagName}> Required dependency "AuthorBaseElement" not found.')
console.info('AuthorBaseElement is available at ${localPkg.repository.url.replace(/git\+|\.git/gi, '').replace(build.tagName.replace('author-', ''), 'base')}')
}
`
magicString.prependLeft(0, baseClassCheck)
}
// Concatenate results
let token = '{{TEMPLATE-STRING}}'
let start = build.js.indexOf(token)
let end = start + token.length
let injectedCode = minifyHTML(`<template><style>@charset "UTF-8"; ${build.css}</style>${build.template}</template>`, {
collapseWhitespace: true,
removeComments: true
})
magicString.overwrite(start, end, injectedCode)
let result = {
code: magicString.toString()
}
if (options.sourceMap !== false && options.sourcemap !== false) {
result.map = magicString.generateMap({ hires: true })
}
return result
}
}
}