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
use crate::error::PrinterErrorKind;
use crate::properties::css_modules::{Composes, Specifier};
use crate::selector::Selectors;
use data_encoding::{Encoding, Specification};
use lazy_static::lazy_static;
use parcel_selectors::SelectorList;
use serde::Serialize;
use smallvec::{smallvec, SmallVec};
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::fmt::Write;
use std::hash::{Hash, Hasher};
use std::path::Path;
#[derive(Default, Clone, Debug)]
pub struct Config<'i> {
pub pattern: Pattern<'i>,
pub dashed_idents: bool,
}
#[derive(Clone, Debug)]
pub struct Pattern<'i> {
pub segments: SmallVec<[Segment<'i>; 2]>,
}
impl<'i> Default for Pattern<'i> {
fn default() -> Self {
Pattern {
segments: smallvec![Segment::Hash, Segment::Literal("_"), Segment::Local],
}
}
}
#[derive(Debug)]
pub enum PatternParseError {
UnknownPlaceholder(String, usize),
UnclosedBrackets(usize),
}
impl std::fmt::Display for PatternParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use PatternParseError::*;
match self {
UnknownPlaceholder(p, i) => write!(
f,
"Error parsing CSS modules pattern: unknown placeholder \"{}\" at index {}",
p, i
),
UnclosedBrackets(i) => write!(f, "Error parsing CSS modules pattern: unclosed brackets at index {}", i),
}
}
}
impl std::error::Error for PatternParseError {}
impl<'i> Pattern<'i> {
pub fn parse(mut input: &'i str) -> Result<Self, PatternParseError> {
let mut segments = SmallVec::new();
let mut start_idx: usize = 0;
while !input.is_empty() {
if input.starts_with('[') {
if let Some(end_idx) = input.find(']') {
let segment = match &input[0..=end_idx] {
"[name]" => Segment::Name,
"[local]" => Segment::Local,
"[hash]" => Segment::Hash,
s => return Err(PatternParseError::UnknownPlaceholder(s.into(), start_idx)),
};
segments.push(segment);
start_idx += end_idx + 1;
input = &input[end_idx + 1..];
} else {
return Err(PatternParseError::UnclosedBrackets(start_idx));
}
} else {
let end_idx = input.find('[').unwrap_or_else(|| input.len());
segments.push(Segment::Literal(&input[0..end_idx]));
start_idx += end_idx;
input = &input[end_idx..];
}
}
Ok(Pattern { segments })
}
pub fn write<W, E>(&self, hash: &str, path: &Path, local: &str, mut write: W) -> Result<(), E>
where
W: FnMut(&str) -> Result<(), E>,
{
for segment in &self.segments {
match segment {
Segment::Literal(s) => {
write(s)?;
}
Segment::Name => {
write(path.file_stem().unwrap().to_str().unwrap())?;
}
Segment::Local => {
write(local)?;
}
Segment::Hash => {
write(hash)?;
}
}
}
Ok(())
}
#[inline]
fn write_to_string(
&self,
mut res: String,
hash: &str,
path: &Path,
local: &str,
) -> Result<String, std::fmt::Error> {
self.write(hash, path, local, |s| res.write_str(s))?;
Ok(res)
}
}
#[derive(Clone, Debug)]
pub enum Segment<'i> {
Literal(&'i str),
Name,
Local,
Hash,
}
#[derive(PartialEq, Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum CssModuleReference {
Local {
name: String,
},
Global {
name: String,
},
Dependency {
name: String,
specifier: String,
},
}
#[derive(PartialEq, Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CssModuleExport {
pub name: String,
pub composes: Vec<CssModuleReference>,
pub is_referenced: bool,
}
pub type CssModuleExports = HashMap<String, CssModuleExport>;
pub type CssModuleReferences = HashMap<String, CssModuleReference>;
lazy_static! {
static ref ENCODER: Encoding = {
let mut spec = Specification::new();
spec
.symbols
.push_str("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-");
spec.encoding().unwrap()
};
}
pub(crate) struct CssModule<'a, 'b, 'c> {
pub config: &'a Config<'b>,
pub path: &'c Path,
pub hash: String,
pub exports: &'a mut CssModuleExports,
pub references: &'a mut HashMap<String, CssModuleReference>,
}
impl<'a, 'b, 'c> CssModule<'a, 'b, 'c> {
pub fn new(
config: &'a Config<'b>,
filename: &'c str,
exports: &'a mut CssModuleExports,
references: &'a mut HashMap<String, CssModuleReference>,
) -> Self {
Self {
config,
path: Path::new(filename),
hash: hash(filename, matches!(config.pattern.segments[0], Segment::Hash)),
exports,
references,
}
}
pub fn add_local(&mut self, exported: &str, local: &str) {
self.exports.entry(exported.into()).or_insert_with(|| CssModuleExport {
name: self
.config
.pattern
.write_to_string(String::new(), &self.hash, &self.path, local)
.unwrap(),
composes: vec![],
is_referenced: false,
});
}
pub fn add_dashed(&mut self, local: &str) {
self.exports.entry(local.into()).or_insert_with(|| CssModuleExport {
name: self
.config
.pattern
.write_to_string("--".into(), &self.hash, &self.path, &local[2..])
.unwrap(),
composes: vec![],
is_referenced: false,
});
}
pub fn reference(&mut self, name: &str) {
match self.exports.entry(name.into()) {
std::collections::hash_map::Entry::Occupied(mut entry) => {
entry.get_mut().is_referenced = true;
}
std::collections::hash_map::Entry::Vacant(entry) => {
entry.insert(CssModuleExport {
name: self
.config
.pattern
.write_to_string(String::new(), &self.hash, &self.path, name)
.unwrap(),
composes: vec![],
is_referenced: true,
});
}
}
}
pub fn reference_dashed(&mut self, name: &str, from: &Option<Specifier>) -> Option<String> {
let (reference, key) = match from {
Some(Specifier::Global) => return Some(name[2..].into()),
Some(Specifier::File(file)) => (
CssModuleReference::Dependency {
name: name.to_string(),
specifier: file.to_string(),
},
file.as_ref(),
),
None => {
match self.exports.entry(name.into()) {
std::collections::hash_map::Entry::Occupied(mut entry) => {
entry.get_mut().is_referenced = true;
}
std::collections::hash_map::Entry::Vacant(entry) => {
entry.insert(CssModuleExport {
name: self
.config
.pattern
.write_to_string("--".into(), &self.hash, &self.path, name)
.unwrap(),
composes: vec![],
is_referenced: true,
});
}
}
return None;
}
};
let hash = hash(&format!("{}_{}_{}", self.hash, name, key), false);
let name = format!("--{}", hash);
self.references.insert(name.clone(), reference);
Some(hash)
}
pub fn handle_composes(
&mut self,
selectors: &SelectorList<Selectors>,
composes: &Composes,
) -> Result<(), PrinterErrorKind> {
for sel in &selectors.0 {
if sel.len() == 1 {
match sel.iter_raw_match_order().next().unwrap() {
parcel_selectors::parser::Component::Class(ref id) => {
for name in &composes.names {
let reference = match &composes.from {
None => CssModuleReference::Local {
name: self
.config
.pattern
.write_to_string(String::new(), &self.hash, &self.path, name.0.as_ref())
.unwrap(),
},
Some(Specifier::Global) => CssModuleReference::Global {
name: name.0.as_ref().into(),
},
Some(Specifier::File(file)) => CssModuleReference::Dependency {
name: name.0.to_string(),
specifier: file.to_string(),
},
};
let export = self.exports.get_mut(&id.0.as_ref().to_owned()).unwrap();
if !export.composes.contains(&reference) {
export.composes.push(reference);
}
}
continue;
}
_ => {}
}
}
return Err(PrinterErrorKind::InvalidComposesSelector);
}
Ok(())
}
}
pub(crate) fn hash(s: &str, at_start: bool) -> String {
let mut hasher = DefaultHasher::new();
s.hash(&mut hasher);
let hash = hasher.finish() as u32;
let hash = ENCODER.encode(&hash.to_le_bytes());
if at_start && matches!(hash.as_bytes()[0], b'0'..=b'9') {
format!("_{}", hash)
} else {
hash
}
}