deno_doc 0.201.0

doc generation for deno
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
use super::DocNodeWithContext;
use super::FileMode;
use super::RenderContext;
use super::UrlResolveKind;
use crate::DeclarationDef;
use crate::js_doc::JsDocTag;
use indexmap::IndexMap;
use regex::Regex;
use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow;

#[cfg(target_arch = "wasm32")]
use std::cell::RefCell;
#[cfg(target_arch = "wasm32")]
use std::ffi::c_void;

#[cfg(target_arch = "wasm32")]
thread_local! {
  static RENDER_CONTEXT: RefCell<*const c_void> = const { RefCell::new(std::ptr::null()) };
  static DOC_NODE: RefCell<*const c_void> = const { RefCell::new(std::ptr::null()) };
}

lazy_static! {
  static ref IDENTIFIER_RE: Regex = Regex::new(r"[^a-zA-Z$_]").unwrap();
}

/// JavaScript/TypeScript reserved words that cannot be used as identifiers.
const JS_RESERVED_WORDS: &[&str] = &[
  "abstract",
  "arguments",
  "async",
  "await",
  "boolean",
  "break",
  "byte",
  "case",
  "catch",
  "char",
  "class",
  "const",
  "continue",
  "debugger",
  "default",
  "delete",
  "do",
  "double",
  "else",
  "enum",
  "eval",
  "export",
  "extends",
  "false",
  "final",
  "finally",
  "float",
  "for",
  "function",
  "goto",
  "if",
  "implements",
  "import",
  "in",
  "instanceof",
  "int",
  "interface",
  "let",
  "long",
  "native",
  "new",
  "null",
  "package",
  "private",
  "protected",
  "public",
  "return",
  "short",
  "static",
  "super",
  "switch",
  "synchronized",
  "this",
  "throw",
  "throws",
  "transient",
  "true",
  "try",
  "typeof",
  "var",
  "void",
  "volatile",
  "while",
  "with",
  "yield",
];

fn is_reserved_word(s: &str) -> bool {
  JS_RESERVED_WORDS.contains(&s)
}

/// Capitalize the first letter of a string.
fn capitalize_first(s: &str) -> String {
  let mut chars = s.chars();
  match chars.next() {
    None => String::new(),
    Some(c) => c.to_uppercase().to_string() + chars.as_str(),
  }
}

fn render_css_for_usage(name: &str) -> String {
  format!(
    r#"
#{name}:checked ~ *:last-child > :not(#{name}_content) {{
  display: none;
}}
#{name}:checked ~ nav #{name}_active_dropdown {{
  display: flex;
}}
#{name}:checked ~ nav label[for='{name}'] {{
  cursor: unset;
  background-color: var(--ddoc-usage-active-bg);
}}
"#
  )
}

fn usage_to_md(
  ctx: &RenderContext,
  symbol: Option<&DocNodeWithContext>,
  url: &str,
  custom_file_identifier: Option<&str>,
) -> String {
  let usage = if let Some(symbol) = symbol
    && let UrlResolveKind::Symbol {
      symbol: symbol_name,
      ..
    } = ctx.get_current_resolve()
  {
    let mut parts = symbol_name.split('.');

    let top_node = symbol.get_topmost_ancestor();

    let is_default = top_node.is_default || &*top_node.name == "default";

    let import_symbol: Box<str> = if is_default {
      if top_node.is_default {
        let default_name = top_node.get_name();
        if default_name == "default" {
          get_identifier_for_file(ctx, custom_file_identifier).into()
        } else {
          default_name.into()
        }
      } else {
        "module".into()
      }
    } else {
      parts.clone().next().unwrap().into()
    };

    let usage_symbol = if symbol.parent.is_some() {
      None
    } else {
      let last = parts.next_back();
      if let Some(usage_symbol) = last {
        if usage_symbol == symbol_name {
          None
        } else {
          Some((
            usage_symbol,
            // if it is namespaces within namespaces, we simply re-join them together
            // instead of trying to figure out some sort of nested restructuring
            if is_default {
              import_symbol.clone()
            } else {
              let capacity = symbol_name.len() - usage_symbol.len() - 1;
              let mut joined = String::with_capacity(capacity);
              for part in parts {
                if !joined.is_empty() {
                  joined.push('.');
                }
                joined.push_str(part);
              }
              joined.into_boxed_str()
            },
          ))
        }
      } else {
        None
      }
    };

    let is_type = symbol
      .parent
      .as_ref()
      .map_or_else(|| &symbol.inner, |parent| &parent.inner)
      .declarations
      .iter()
      .all(|decl| {
        matches!(
          decl.def,
          DeclarationDef::TypeAlias(..) | DeclarationDef::Interface(..)
        )
      });

    let mut usage_statement = if is_default {
      format!(
        r#"import {}{} from "{url}";"#,
        if is_type { "type " } else { "" },
        html_escape::encode_text(&import_symbol),
      )
    } else {
      format!(
        r#"import {{ {}{} }} from "{url}";"#,
        if is_type { "type " } else { "" },
        html_escape::encode_text(&import_symbol),
      )
    };

    if let Some((usage_symbol, local_var)) = usage_symbol {
      usage_statement.push_str(&format!(
        "\n{} {{ {} }} = {local_var};",
        if is_type { "type" } else { "const" },
        html_escape::encode_text(usage_symbol),
      ));
    }

    usage_statement
  } else if ctx.ctx.doc_nodes.len() == 1
    && let nodes = ctx.ctx.doc_nodes.values().next().unwrap()
    && nodes.len() == 1
  {
    // this branch is special casing for single symbol export
    let is_default = nodes[0].is_default || &*nodes[0].name == "default";

    if is_default {
      format!(
        r#"import {} from "{url}";"#,
        get_identifier_for_file(ctx, custom_file_identifier),
      )
    } else {
      let is_type = nodes[0].declarations.iter().all(|decl| {
        matches!(
          decl.def,
          DeclarationDef::TypeAlias(..) | DeclarationDef::Interface(..)
        )
      });

      format!(
        r#"import {}{{ {} }} from "{url}";"#,
        if is_type { "type " } else { "" },
        html_escape::encode_text(&nodes[0].get_name()),
      )
    }
  } else {
    let module_import_symbol =
      get_identifier_for_file(ctx, custom_file_identifier);

    format!(r#"import * as {module_import_symbol} from "{url}";"#)
  };

  format!("```typescript\n{usage}\n```")
}

fn get_identifier_for_file(
  ctx: &RenderContext,
  custom_file_identifier: Option<&str>,
) -> String {
  let maybe_identifier =
    if let Some(file) = ctx.get_current_resolve().get_file() {
      ctx.ctx.module_docs.get(file).and_then(|js_doc| {
        js_doc.tags.iter().find_map(|tag| {
          if let JsDocTag::Module { name } = tag {
            name.as_ref().map(|name| name.to_string())
          } else {
            None
          }
        })
      })
    } else if let Some(context_name) = custom_file_identifier {
      Some(context_name.to_string())
    } else {
      ctx.ctx.package_name.clone()
    };

  maybe_identifier.as_ref().map_or_else(
    || "mod".to_string(),
    |identifier| {
      let sanitized = IDENTIFIER_RE.replace_all(identifier, "_").to_string();
      if is_reserved_word(&sanitized) {
        capitalize_first(&sanitized)
      } else {
        sanitized
      }
    },
  )
}

#[cfg(not(feature = "rust"))]
pub type UsageToMd<'a> = &'a js_sys::Function;
#[cfg(feature = "rust")]
pub type UsageToMd<'a> = &'a dyn Fn(&str, Option<&str>) -> String;

#[derive(Clone, Debug, Serialize, Deserialize)]
struct UsageCtx {
  name: String,
  content: String,
  icon: Option<Cow<'static, str>>,
  additional_css: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UsagesCtx {
  usages: Vec<UsageCtx>,
  composed: bool,
}

impl UsagesCtx {
  pub const TEMPLATE: &'static str = "usages";

  pub fn new(
    ctx: &RenderContext,
    symbol: Option<&DocNodeWithContext>,
  ) -> Option<Self> {
    let Some(usage_composer) = &ctx.ctx.usage_composer else {
      return None;
    };

    let is_single_mode = usage_composer.is_single_mode();

    if is_single_mode && ctx.ctx.file_mode == FileMode::SingleDts {
      return None;
    }

    #[cfg(not(target_arch = "wasm32"))]
    let usage_to_md_closure =
      move |url: &str, custom_file_identifier: Option<&str>| {
        usage_to_md(ctx, symbol, url, custom_file_identifier)
      };

    #[cfg(target_arch = "wasm32")]
    {
      let ctx_ptr = ctx as *const RenderContext as *const c_void;
      RENDER_CONTEXT.set(ctx_ptr);
      let node_ptr = symbol
        .map(|s| s as *const DocNodeWithContext as *const c_void)
        .unwrap_or(std::ptr::null());
      DOC_NODE.set(node_ptr);
    }

    #[cfg(target_arch = "wasm32")]
    let usage_to_md_closure =
      move |url: String, custom_file_identifier: Option<String>| {
        RENDER_CONTEXT.with(|ctx| {
          let render_ctx_ptr = *ctx.borrow() as *const RenderContext;
          assert!(!render_ctx_ptr.is_null());
          // SAFETY: this pointer is valid until destroyed, which is done
          //  after compose is called
          let render_ctx = unsafe { &*render_ctx_ptr };

          let usage = DOC_NODE.with(|node| {
            let node_ptr = *node.borrow();
            // SAFETY: the pointer is valid until destroyed, which is done
            //  after compose is called
            let symbol = if node_ptr.is_null() {
              None
            } else {
              Some(unsafe { &*(node_ptr as *const DocNodeWithContext) })
            };

            let usage = usage_to_md(
              &render_ctx,
              symbol,
              &url,
              custom_file_identifier.as_deref(),
            );

            usage
          });

          *ctx.borrow_mut() =
            render_ctx as *const RenderContext as *const c_void;
          usage
        })
      };

    #[cfg(target_arch = "wasm32")]
    let usage_to_md_closure =
      wasm_bindgen::prelude::Closure::wrap(Box::new(usage_to_md_closure)
        as Box<dyn Fn(String, Option<String>) -> String>);
    #[cfg(target_arch = "wasm32")]
    let usage_to_md_closure = &wasm_bindgen::JsCast::unchecked_ref::<
      js_sys::Function,
    >(usage_to_md_closure.as_ref());

    let usages =
      usage_composer.compose(ctx.get_current_resolve(), &usage_to_md_closure);

    #[cfg(target_arch = "wasm32")]
    {
      let render_ctx =
        RENDER_CONTEXT.replace(std::ptr::null()) as *const RenderContext;
      // SAFETY: take the pointer and drop it
      let _ = unsafe { &*render_ctx };

      let doc_node_ptr = DOC_NODE.replace(std::ptr::null());
      // SAFETY: take the pointer and drop it
      if !doc_node_ptr.is_null() {
        let _ = unsafe { &*(doc_node_ptr as *const DocNodeWithContext) };
      }
    };

    if usages.is_empty() {
      None
    } else {
      let usages = usages
        .into_iter()
        .map(|(entry, content)| UsageCtx {
          additional_css: if is_single_mode {
            String::new()
          } else {
            render_css_for_usage(&entry.name)
          },
          name: entry.name,
          icon: entry.icon,
          content: crate::html::jsdoc::render_markdown(ctx, &content, true),
        })
        .collect::<Vec<_>>();

      Some(UsagesCtx {
        usages,
        composed: !is_single_mode,
      })
    }
  }
}

#[derive(Eq, PartialEq, Hash, serde::Deserialize)]
pub struct UsageComposerEntry {
  pub name: String,
  pub icon: Option<Cow<'static, str>>,
}

pub trait UsageComposer: Send + Sync {
  fn is_single_mode(&self) -> bool;

  fn compose(
    &self,
    current_resolve: UrlResolveKind,
    usage_to_md: UsageToMd,
  ) -> IndexMap<UsageComposerEntry, String>;
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_is_reserved_word() {
    assert!(is_reserved_word("enum"));
    assert!(is_reserved_word("class"));
    assert!(is_reserved_word("function"));
    assert!(is_reserved_word("import"));
    assert!(is_reserved_word("export"));
    assert!(is_reserved_word("let"));
    assert!(is_reserved_word("const"));
    assert!(is_reserved_word("var"));
    assert!(is_reserved_word("yield"));
    assert!(is_reserved_word("await"));

    assert!(!is_reserved_word("foo"));
    assert!(!is_reserved_word("myEnum"));
    assert!(!is_reserved_word("Enum"));
    assert!(!is_reserved_word(""));
  }

  #[test]
  fn test_capitalize_first() {
    assert_eq!(capitalize_first("enum"), "Enum");
    assert_eq!(capitalize_first("class"), "Class");
    assert_eq!(capitalize_first("foo"), "Foo");
    assert_eq!(capitalize_first(""), "");
    assert_eq!(capitalize_first("a"), "A");
    assert_eq!(capitalize_first("ABC"), "ABC");
  }

  #[test]
  fn test_identifier_re_sanitization() {
    assert_eq!(IDENTIFIER_RE.replace_all("foo-bar", "_"), "foo_bar");
    assert_eq!(IDENTIFIER_RE.replace_all("@scope/pkg", "_"), "_scope_pkg");
    assert_eq!(IDENTIFIER_RE.replace_all("hello_world", "_"), "hello_world");
  }
}