helpers.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import Type from './type'
  7. import Symbol, { Arguments, isSymbol } from './symbol'
  8. export function symbol<A extends Arguments, T extends Type<S>, S>(args: A, type: T, description?: string) {
  9. return Symbol('', args, type, description);
  10. }
  11. export function normalizeTable(table: any) {
  12. _normalizeTable('', '', table);
  13. }
  14. export function symbolList(table: any): Symbol[] {
  15. const list: Symbol[] = [];
  16. _symbolList(table, list);
  17. return list;
  18. }
  19. function formatKey(key: string) {
  20. const regex = /([a-z])([A-Z])([a-z]|$)/g;
  21. // do this twice because 'xXxX'
  22. return key.replace(regex, (s, a, b, c) => `${a}-${b.toLocaleLowerCase()}${c}`).replace(regex, (s, a, b, c) => `${a}-${b.toLocaleLowerCase()}${c}`);
  23. }
  24. function _normalizeTable(namespace: string, key: string, obj: any) {
  25. if (isSymbol(obj)) {
  26. obj.info.namespace = namespace;
  27. obj.info.name = obj.info.name || formatKey(key);
  28. obj.id = `${obj.info.namespace}.${obj.info.name}`;
  29. return;
  30. }
  31. const currentNs = `${obj['@namespace'] || formatKey(key)}`;
  32. const newNs = namespace ? `${namespace}.${currentNs}` : currentNs;
  33. for (const childKey of Object.keys(obj)) {
  34. if (typeof obj[childKey] !== 'object' && !isSymbol(obj[childKey])) continue;
  35. _normalizeTable(newNs, childKey, obj[childKey]);
  36. }
  37. }
  38. function _symbolList(obj: any, list: Symbol[]) {
  39. if (isSymbol(obj)) {
  40. list.push(obj);
  41. return;
  42. }
  43. for (const childKey of Object.keys(obj)) {
  44. if (typeof obj[childKey] !== 'object' && !isSymbol(obj[childKey])) continue;
  45. _symbolList(obj[childKey], list);
  46. }
  47. }