use-angular 0.0.1

Angular ecosystem metadata primitives for RustUse
Documentation
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]

use core::{fmt, str::FromStr};
use std::error::Error;
use use_js_identifier::{JsIdentifier, JsIdentifierError};

/// Angular version-family labels.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum AngularVersionFamily {
    Angular2,
    Angular3,
    Angular4,
    Angular5,
    Angular6,
    Angular7,
    Angular8,
    Angular9,
    Angular10,
    Angular11,
    Angular12,
    Angular13,
    Angular14,
    Angular15,
    Angular16,
    Angular17,
    Angular18,
    Angular19,
    Angular20,
}

impl AngularVersionFamily {
    /// Returns the version-family label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Angular2 => "angular2",
            Self::Angular3 => "angular3",
            Self::Angular4 => "angular4",
            Self::Angular5 => "angular5",
            Self::Angular6 => "angular6",
            Self::Angular7 => "angular7",
            Self::Angular8 => "angular8",
            Self::Angular9 => "angular9",
            Self::Angular10 => "angular10",
            Self::Angular11 => "angular11",
            Self::Angular12 => "angular12",
            Self::Angular13 => "angular13",
            Self::Angular14 => "angular14",
            Self::Angular15 => "angular15",
            Self::Angular16 => "angular16",
            Self::Angular17 => "angular17",
            Self::Angular18 => "angular18",
            Self::Angular19 => "angular19",
            Self::Angular20 => "angular20",
        }
    }
}

impl fmt::Display for AngularVersionFamily {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for AngularVersionFamily {
    type Err = AngularNameError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_label(input)?.as_str() {
            "angular2" | "2" => Ok(Self::Angular2),
            "angular3" | "3" => Ok(Self::Angular3),
            "angular4" | "4" => Ok(Self::Angular4),
            "angular5" | "5" => Ok(Self::Angular5),
            "angular6" | "6" => Ok(Self::Angular6),
            "angular7" | "7" => Ok(Self::Angular7),
            "angular8" | "8" => Ok(Self::Angular8),
            "angular9" | "9" => Ok(Self::Angular9),
            "angular10" | "10" => Ok(Self::Angular10),
            "angular11" | "11" => Ok(Self::Angular11),
            "angular12" | "12" => Ok(Self::Angular12),
            "angular13" | "13" => Ok(Self::Angular13),
            "angular14" | "14" => Ok(Self::Angular14),
            "angular15" | "15" => Ok(Self::Angular15),
            "angular16" | "16" => Ok(Self::Angular16),
            "angular17" | "17" => Ok(Self::Angular17),
            "angular18" | "18" => Ok(Self::Angular18),
            "angular19" | "19" => Ok(Self::Angular19),
            "angular20" | "20" => Ok(Self::Angular20),
            _ => Err(AngularNameError::UnknownLabel),
        }
    }
}

/// Angular file-kind labels.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum AngularFileKind {
    Component,
    Template,
    Stylesheet,
    Spec,
    Service,
    Module,
    RoutingModule,
    Config,
}

impl AngularFileKind {
    /// Returns the file-kind label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Component => "component",
            Self::Template => "template",
            Self::Stylesheet => "stylesheet",
            Self::Spec => "spec",
            Self::Service => "service",
            Self::Module => "module",
            Self::RoutingModule => "routing-module",
            Self::Config => "config",
        }
    }
}

impl fmt::Display for AngularFileKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for AngularFileKind {
    type Err = AngularNameError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_label(input)?.as_str() {
            "component" => Ok(Self::Component),
            "template" => Ok(Self::Template),
            "stylesheet" | "style" | "styles" => Ok(Self::Stylesheet),
            "spec" | "test" => Ok(Self::Spec),
            "service" => Ok(Self::Service),
            "module" => Ok(Self::Module),
            "routingmodule" | "routing" => Ok(Self::RoutingModule),
            "config" => Ok(Self::Config),
            _ => Err(AngularNameError::UnknownLabel),
        }
    }
}

/// Angular artifact-kind labels.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum AngularArtifactKind {
    Component,
    Directive,
    Pipe,
    Service,
    Module,
    Guard,
    Resolver,
    Interceptor,
}

impl AngularArtifactKind {
    /// Returns the artifact-kind label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Component => "component",
            Self::Directive => "directive",
            Self::Pipe => "pipe",
            Self::Service => "service",
            Self::Module => "module",
            Self::Guard => "guard",
            Self::Resolver => "resolver",
            Self::Interceptor => "interceptor",
        }
    }
}

impl fmt::Display for AngularArtifactKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for AngularArtifactKind {
    type Err = AngularNameError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_label(input)?.as_str() {
            "component" => Ok(Self::Component),
            "directive" => Ok(Self::Directive),
            "pipe" => Ok(Self::Pipe),
            "service" => Ok(Self::Service),
            "module" => Ok(Self::Module),
            "guard" => Ok(Self::Guard),
            "resolver" => Ok(Self::Resolver),
            "interceptor" => Ok(Self::Interceptor),
            _ => Err(AngularNameError::UnknownLabel),
        }
    }
}

/// Angular standalone mode labels.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum AngularStandaloneMode {
    Standalone,
    NgModuleBased,
}

impl AngularStandaloneMode {
    /// Returns the standalone mode label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Standalone => "standalone",
            Self::NgModuleBased => "ng-module-based",
        }
    }
}

impl fmt::Display for AngularStandaloneMode {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for AngularStandaloneMode {
    type Err = AngularNameError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_label(input)?.as_str() {
            "standalone" => Ok(Self::Standalone),
            "ngmodulebased" | "ngmodule" | "modulebased" => Ok(Self::NgModuleBased),
            _ => Err(AngularNameError::UnknownLabel),
        }
    }
}

/// Common Angular config file labels.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum AngularConfigFile {
    AngularJson,
    TsConfigAppJson,
    TsConfigSpecJson,
}

impl AngularConfigFile {
    /// Returns the config file label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::AngularJson => "angular.json",
            Self::TsConfigAppJson => "tsconfig.app.json",
            Self::TsConfigSpecJson => "tsconfig.spec.json",
        }
    }
}

impl fmt::Display for AngularConfigFile {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for AngularConfigFile {
    type Err = AngularNameError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_label(input)?.as_str() {
            "angularjson" | "angular.json" => Ok(Self::AngularJson),
            "tsconfigappjson" | "tsconfig.app.json" => Ok(Self::TsConfigAppJson),
            "tsconfigspecjson" | "tsconfig.spec.json" => Ok(Self::TsConfigSpecJson),
            _ => Err(AngularNameError::UnknownLabel),
        }
    }
}

/// Validated Angular directive class name metadata.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AngularDirectiveName(String);

impl AngularDirectiveName {
    /// Creates a `PascalCase` Angular directive class name.
    ///
    /// # Errors
    ///
    /// Returns [`AngularNameError`] when `input` is not an ASCII identifier or is not `PascalCase`-shaped.
    pub fn new(input: &str) -> Result<Self, AngularNameError> {
        validate_pascal_case(input).map(Self)
    }

    /// Returns the directive name.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for AngularDirectiveName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for AngularDirectiveName {
    type Err = AngularNameError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Self::new(input)
    }
}

impl TryFrom<&str> for AngularDirectiveName {
    type Error = AngularNameError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// Validated Angular selector metadata.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AngularSelector(String);

impl AngularSelector {
    /// Creates a lightly validated Angular selector.
    ///
    /// # Errors
    ///
    /// Returns [`AngularNameError`] when `input` is empty, contains whitespace, or is not selector-shaped.
    pub fn new(input: &str) -> Result<Self, AngularNameError> {
        let trimmed = input.trim();
        if trimmed.is_empty() {
            return Err(AngularNameError::Empty);
        }
        if trimmed.chars().any(char::is_whitespace) {
            return Err(AngularNameError::ContainsWhitespace);
        }
        if !is_selector_shape(trimmed) {
            return Err(AngularNameError::InvalidSelector);
        }
        Ok(Self(trimmed.to_string()))
    }

    /// Returns the selector.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for AngularSelector {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for AngularSelector {
    type Err = AngularNameError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Self::new(input)
    }
}

impl TryFrom<&str> for AngularSelector {
    type Error = AngularNameError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// Validated Angular module name metadata.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AngularModuleName(String);

impl AngularModuleName {
    /// Creates Angular module name metadata.
    ///
    /// # Errors
    ///
    /// Returns [`AngularNameError`] when `input` is empty or contains whitespace.
    pub fn new(input: &str) -> Result<Self, AngularNameError> {
        let trimmed = input.trim();
        if trimmed.is_empty() {
            return Err(AngularNameError::Empty);
        }
        if trimmed.chars().any(char::is_whitespace) {
            return Err(AngularNameError::ContainsWhitespace);
        }
        Ok(Self(trimmed.to_string()))
    }

    /// Returns the module name.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for AngularModuleName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for AngularModuleName {
    type Err = AngularNameError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Self::new(input)
    }
}

impl TryFrom<&str> for AngularModuleName {
    type Error = AngularNameError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// Error returned when Angular metadata is invalid.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AngularNameError {
    Empty,
    ContainsWhitespace,
    Identifier(JsIdentifierError),
    NotPascalCase,
    InvalidSelector,
    UnknownLabel,
}

impl fmt::Display for AngularNameError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("Angular metadata text cannot be empty"),
            Self::ContainsWhitespace => {
                formatter.write_str("Angular metadata text cannot contain whitespace")
            }
            Self::Identifier(error) => write!(formatter, "{error}"),
            Self::NotPascalCase => {
                formatter.write_str("Angular artifact name must be `PascalCase`-shaped")
            }
            Self::InvalidSelector => formatter.write_str("invalid Angular selector"),
            Self::UnknownLabel => formatter.write_str("unknown Angular metadata label"),
        }
    }
}

impl Error for AngularNameError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Identifier(error) => Some(error),
            Self::Empty
            | Self::ContainsWhitespace
            | Self::NotPascalCase
            | Self::InvalidSelector
            | Self::UnknownLabel => None,
        }
    }
}

fn validate_pascal_case(input: &str) -> Result<String, AngularNameError> {
    let identifier = JsIdentifier::new(input).map_err(AngularNameError::Identifier)?;
    if !identifier
        .as_str()
        .chars()
        .next()
        .is_some_and(|character| character.is_ascii_uppercase())
    {
        return Err(AngularNameError::NotPascalCase);
    }
    Ok(identifier.as_str().to_string())
}

fn is_selector_shape(input: &str) -> bool {
    if let Some(inner) = input
        .strip_prefix('[')
        .and_then(|value| value.strip_suffix(']'))
    {
        return !inner.is_empty() && inner.chars().all(is_selector_character);
    }
    if let Some(class_selector) = input.strip_prefix('.') {
        return !class_selector.is_empty() && class_selector.chars().all(is_selector_character);
    }
    !input.is_empty() && input.chars().all(is_selector_character)
}

const fn is_selector_character(character: char) -> bool {
    character.is_ascii_alphanumeric() || matches!(character, '-' | '_')
}

fn normalized_label(input: &str) -> Result<String, AngularNameError> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Err(AngularNameError::Empty);
    }
    Ok(trimmed
        .chars()
        .filter(|character| !matches!(character, '-' | '_' | ' '))
        .flat_map(char::to_lowercase)
        .collect())
}

#[cfg(test)]
mod tests {
    use super::{
        AngularArtifactKind, AngularConfigFile, AngularDirectiveName, AngularFileKind,
        AngularModuleName, AngularNameError, AngularSelector, AngularStandaloneMode,
        AngularVersionFamily,
    };
    use use_js_identifier::JsIdentifierError;

    #[test]
    fn validates_selectors() -> Result<(), AngularNameError> {
        assert_eq!(AngularSelector::new("app-root")?.as_str(), "app-root");
        assert_eq!(
            AngularSelector::new("[appHighlight]")?.as_str(),
            "[appHighlight]"
        );
        assert_eq!(AngularSelector::new(".app-card")?.as_str(), ".app-card");
        assert_eq!(AngularSelector::new(""), Err(AngularNameError::Empty));
        assert_eq!(
            AngularSelector::new("app root"),
            Err(AngularNameError::ContainsWhitespace)
        );
        assert_eq!(
            AngularSelector::new("#app"),
            Err(AngularNameError::InvalidSelector)
        );
        Ok(())
    }

    #[test]
    fn validates_names() -> Result<(), AngularNameError> {
        assert_eq!(
            AngularDirectiveName::new("AppHighlight")?.as_str(),
            "AppHighlight"
        );
        assert_eq!(
            AngularModuleName::new("FeatureModule")?.as_str(),
            "FeatureModule"
        );
        assert_eq!(
            AngularDirectiveName::new("appHighlight"),
            Err(AngularNameError::NotPascalCase)
        );
        assert_eq!(
            AngularDirectiveName::new("1App"),
            Err(AngularNameError::Identifier(
                JsIdentifierError::InvalidStart { character: '1' }
            ))
        );
        assert_eq!(
            AngularModuleName::new("Feature Module"),
            Err(AngularNameError::ContainsWhitespace)
        );
        Ok(())
    }

    #[test]
    fn parses_labels() -> Result<(), AngularNameError> {
        assert_eq!(
            "angular17".parse::<AngularVersionFamily>()?,
            AngularVersionFamily::Angular17
        );
        assert_eq!(
            "routing-module".parse::<AngularFileKind>()?,
            AngularFileKind::RoutingModule
        );
        assert_eq!(
            "component".parse::<AngularArtifactKind>()?,
            AngularArtifactKind::Component
        );
        assert_eq!(
            "ng-module".parse::<AngularStandaloneMode>()?,
            AngularStandaloneMode::NgModuleBased
        );
        assert_eq!(
            "angular.json".parse::<AngularConfigFile>()?,
            AngularConfigFile::AngularJson
        );
        assert_eq!(AngularArtifactKind::Service.to_string(), "service");
        Ok(())
    }
}