@astryxdesign/cli 0.7.11 → 0.7.12-canary.0085c0f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/api/build/blocks/blocks.d.mts +41 -0
  2. package/api/build/blocks/blocks.mjs +118 -68
  3. package/api/build/kit/rank.mjs +21 -4
  4. package/api/build/kit/words.d.mts +1 -0
  5. package/api/build/kit/words.mjs +1 -1
  6. package/api/component/__fixtures__/resolutions/modules.txt +5 -5
  7. package/api/docs/_adapter.d.mts +22 -0
  8. package/api/docs/_adapter.mjs +81 -3
  9. package/api/docs/docs.doc.mjs +5 -5
  10. package/api/docs/docs.type.d.mts +21 -0
  11. package/api/docs/docs.type.mjs +11 -0
  12. package/api/docs/list/list.d.mts +5 -1
  13. package/api/docs/list/list.mjs +72 -6
  14. package/api/docs/node/node.mjs +2 -40
  15. package/api/doctor/doctor.d.mts +4 -4
  16. package/api/doctor/doctor.mjs +248 -78
  17. package/api/icon/_adapter.d.mts +3 -2
  18. package/api/icon/_adapter.mjs +8 -2
  19. package/api/icon/_authoring.d.mts +1 -0
  20. package/api/icon/_authoring.mjs +594 -67
  21. package/api/icon/_default-look.d.mts +155 -0
  22. package/api/icon/_default-look.mjs +474 -0
  23. package/api/icon/_records.d.mts +1 -1
  24. package/api/icon/_records.mjs +1 -0
  25. package/api/icon/add/add.mjs +269 -43
  26. package/api/icon/icon.type.d.mts +46 -2
  27. package/api/icon/icon.type.mjs +12 -2
  28. package/api/icon/iconAdd.doc.mjs +2 -2
  29. package/api/icon/iconNewDefinition.doc.mjs +3 -2
  30. package/api/icon/iconNewSet.doc.mjs +4 -4
  31. package/api/icon/map/map.mjs +11 -4
  32. package/api/icon/search/search.mjs +10 -9
  33. package/api/index.d.mts +1 -0
  34. package/api/index.mjs +1 -0
  35. package/api/integration/add-helpers.d.mts +15 -1
  36. package/api/integration/add-helpers.mjs +5 -2
  37. package/api/integration/authoring-checks.d.mts +0 -2
  38. package/api/integration/authoring-checks.mjs +1 -6
  39. package/api/logger.mjs +2 -1
  40. package/api/render/_adapter.mjs +9 -0
  41. package/api/render/render.doc.mjs +3 -3
  42. package/api/render/render.type.d.mts +1 -1
  43. package/api/render/render.type.mjs +1 -1
  44. package/api/search/ORDERING.md +3 -0
  45. package/api/search/_adapter.d.mts +32 -3
  46. package/api/search/_adapter.mjs +50 -22
  47. package/api/search/_fit-order.d.mts +47 -0
  48. package/api/search/_fit-order.mjs +257 -0
  49. package/api/search/_main-searcher.mjs +15 -5
  50. package/api/search/exportSearchIndex.doc.d.mts +10 -0
  51. package/api/search/exportSearchIndex.doc.mjs +58 -0
  52. package/api/search/rankSearchIndex.doc.d.mts +10 -0
  53. package/api/search/rankSearchIndex.doc.mjs +79 -0
  54. package/api/search/search-index.d.mts +44 -0
  55. package/api/search/search-index.mjs +270 -0
  56. package/api/search/search.type.d.mts +28 -0
  57. package/api/search/search.type.mjs +17 -0
  58. package/api/swizzle/_adapter.d.mts +1 -0
  59. package/api/swizzle/_adapter.mjs +4 -1
  60. package/api/swizzle/_moduleGraph.d.mts +178 -0
  61. package/api/swizzle/_moduleGraph.mjs +903 -0
  62. package/api/swizzle/copy/copy.d.mts +2 -43
  63. package/api/swizzle/copy/copy.mjs +287 -315
  64. package/api/swizzle/swizzle.d.mts +0 -2
  65. package/api/swizzle/swizzle.doc.mjs +13 -4
  66. package/api/swizzle/swizzle.mjs +3 -7
  67. package/api/swizzle/swizzle.type.d.mts +7 -1
  68. package/api/swizzle/swizzle.type.mjs +4 -2
  69. package/api/template/skeleton/skeleton.mjs +1 -1
  70. package/api/template/template.mjs +1 -0
  71. package/assets/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjs +1 -1
  72. package/assets/codemods/transforms/v0.1.0/index.mjs +1 -1
  73. package/assets/discover/official-packages.json +40 -0
  74. package/assets/docs/browser-support.doc.mjs +2 -2
  75. package/assets/docs/styling-overview.doc.mjs +6 -2
  76. package/assets/docs/tree/icon-sets.doc.mjs +13 -7
  77. package/assets/docs/tree/render-pages.doc.mjs +3 -3
  78. package/assets/docs/tree/tailwind.doc.mjs +41 -1
  79. package/assets/docs/tree/type-scale.doc.mjs +19 -2
  80. package/assets/templates/blocks/components/Calendar/useCalendarConstraintsHookUsage.doc.mjs +14 -0
  81. package/assets/templates/blocks/components/Calendar/useCalendarConstraintsHookUsage.tsx +146 -0
  82. package/assets/templates/blocks/components/Calendar/useCalendarNavigationHookUsage.doc.mjs +14 -0
  83. package/assets/templates/blocks/components/Calendar/useCalendarNavigationHookUsage.tsx +173 -0
  84. package/assets/templates/blocks/components/Hooks/useInputStatusIconHookUsage.tsx +1 -0
  85. package/assets/templates/blocks/components/Hooks/useInteractiveRoleHookUsage.doc.mjs +14 -0
  86. package/assets/templates/blocks/components/Hooks/useInteractiveRoleHookUsage.tsx +56 -0
  87. package/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.doc.mjs +2 -2
  88. package/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.tsx +66 -10
  89. package/assets/templates/blocks/components/Link/useLinkifyHookUsage.doc.mjs +14 -0
  90. package/assets/templates/blocks/components/Link/useLinkifyHookUsage.tsx +39 -0
  91. package/assets/templates/blocks/components/PowerSearch/usePowerSearchConfigHookUsage.doc.mjs +14 -0
  92. package/assets/templates/blocks/components/PowerSearch/usePowerSearchConfigHookUsage.tsx +83 -0
  93. package/assets/templates/blocks/components/Table/RowsVirtualizationHookUsage.doc.mjs +14 -0
  94. package/assets/templates/blocks/components/Table/RowsVirtualizationHookUsage.tsx +41 -0
  95. package/assets/templates/blocks/components/Table/TableRowIndexTable.doc.mjs +1 -1
  96. package/assets/templates/blocks/components/Table/TableRowIndexTable.tsx +2 -2
  97. package/assets/templates/blocks/components/Table/useTableColumnSettingsStateHookUsage.doc.mjs +14 -0
  98. package/assets/templates/blocks/components/Table/useTableColumnSettingsStateHookUsage.tsx +97 -0
  99. package/assets/templates/pages/course-detail/page.tsx +699 -0
  100. package/assets/templates/pages/course-detail/template.doc.mjs +37 -0
  101. package/assets/templates/pages/file-explorer/page.tsx +103 -79
  102. package/assets/templates/pages/table-filter/page.tsx +15 -23
  103. package/assets/templates/pages/table-grouped/page.tsx +190 -262
  104. package/assets/templates/pages/table-grouped/template.doc.mjs +0 -2
  105. package/assets/templates/pages/table-inbox/page.tsx +3 -6
  106. package/assets/templates/pages/theme-showcase/page.tsx +724 -792
  107. package/assets/templates/pages/theme-showcase/template.doc.mjs +4 -5
  108. package/assets/templates/themes/butter/butterTheme.ts +2 -2
  109. package/assets/templates/themes/gothic/gothicTheme.ts +16 -0
  110. package/assets/templates/themes/matcha/matchaTheme.ts +1 -1
  111. package/assets/templates/themes/neutral/neutralTheme.ts +6 -0
  112. package/assets/templates/themes/stone/stoneTheme.ts +1 -1
  113. package/assets/templates/themes/y2k/y2kPaletteRefs.generated.ts +1 -1
  114. package/assets/templates/themes/y2k/y2kTheme.ts +2 -2
  115. package/authoring/doctypes/template/type.ts +1 -0
  116. package/clients/cli/commands/docs.doc.mjs +5 -1
  117. package/clients/cli/commands/docs.mjs +30 -2
  118. package/clients/cli/commands/experimental/icon.mjs +56 -14
  119. package/clients/cli/commands/experimental-icon-add.doc.mjs +1 -1
  120. package/clients/cli/commands/experimental-icon-new-definition.doc.mjs +2 -1
  121. package/clients/cli/commands/experimental-icon-new-set.doc.mjs +2 -2
  122. package/clients/cli/commands/experimental-render.doc.mjs +1 -1
  123. package/clients/cli/commands/swizzle.doc.mjs +12 -3
  124. package/clients/cli/commands/swizzle.mjs +33 -9
  125. package/clients/cli/commands/template.mjs +204 -181
  126. package/clients/cli/lib/resolve-theme.mjs +16 -7
  127. package/foundation/discovery/component-discovery.mjs +1 -1
  128. package/foundation/discovery/component-loader.d.mts +1 -1
  129. package/foundation/discovery/doc-types.mjs +9 -2
  130. package/foundation/discovery/hook-discovery.mjs +31 -8
  131. package/foundation/discovery/icon-ranking.d.mts +27 -3
  132. package/foundation/discovery/icon-ranking.mjs +125 -8
  133. package/foundation/discovery/icon-set-checks.mjs +44 -35
  134. package/foundation/discovery/icon-set-discovery.d.mts +13 -0
  135. package/foundation/discovery/icon-set-discovery.mjs +25 -0
  136. package/foundation/discovery/icon-set-writer.d.mts +258 -20
  137. package/foundation/discovery/icon-set-writer.mjs +785 -87
  138. package/foundation/discovery/module-exports.d.mts +3 -2
  139. package/foundation/discovery/module-exports.mjs +167 -37
  140. package/foundation/discovery/template-adapter.mjs +2 -2
  141. package/foundation/doc-compiler/import.d.mts +5 -1
  142. package/foundation/doc-compiler/import.mjs +40 -6
  143. package/foundation/fs/import-url.d.mts +20 -0
  144. package/foundation/fs/import-url.mjs +22 -0
  145. package/foundation/fs/module-loader.d.mts +24 -3
  146. package/foundation/fs/module-loader.mjs +69 -47
  147. package/foundation/fs/paths.d.mts +2 -1
  148. package/foundation/fs/paths.mjs +3 -4
  149. package/foundation/render/charts.d.mts +59 -0
  150. package/foundation/render/charts.mjs +216 -0
  151. package/foundation/render/embedded-imports.d.mts +7 -7
  152. package/foundation/render/embedded-imports.mjs +63 -54
  153. package/foundation/render/page-host.d.mts +4 -0
  154. package/foundation/render/page-host.mjs +45 -0
  155. package/foundation/render/page-worker.mjs +350 -57
  156. package/foundation/render/render-page.d.mts +11 -6
  157. package/foundation/render/render-page.mjs +164 -54
  158. package/foundation/render/ts-paths.d.mts +63 -0
  159. package/foundation/render/ts-paths.mjs +138 -0
  160. package/foundation/response/error-codes.doc.mjs +3 -3
  161. package/foundation/response/error-codes.mjs +3 -2
  162. package/foundation/text/levenshtein.d.mts +6 -1
  163. package/foundation/text/levenshtein.mjs +25 -9
  164. package/foundation/text/shell-arg.d.mts +14 -0
  165. package/foundation/text/shell-arg.mjs +17 -0
  166. package/foundation/text/suggest-order.d.mts +8 -1
  167. package/foundation/text/suggest-order.mjs +72 -6
  168. package/foundation/xle/registry-core.mjs +1 -1
  169. package/package.json +7 -6
@@ -48,6 +48,7 @@ import {
48
48
  exportValueKind,
49
49
  followedExportNames,
50
50
  moduleExportOrigin,
51
+ staticExportBindings,
51
52
  } from './module-exports.mjs';
52
53
 
53
54
  /** @typedef {import('./icon-set-discovery.mjs').DiscoveredIconSet} DiscoveredIconSet */
@@ -100,10 +101,19 @@ export function iconIdOf(name) {
100
101
 
101
102
  /**
102
103
  * The name an icon set exports an icon as: PascalCase ending in `Icon`
103
- * (`Trash2` → `Trash2Icon`; `TrashIcon` stays).
104
+ * (`Trash2` → `Trash2Icon`; `TrashIcon` stays). A JavaScript name cannot
105
+ * start with a digit, so a name that starts with one is refused.
106
+ * {@link iconNaming} keeps a library prefix to prevent this (`fa0` →
107
+ * `Fa0Icon`).
104
108
  * @param {string} name
105
109
  */
106
110
  export function iconExportName(name) {
111
+ if (/^[0-9]/u.test(name)) {
112
+ throw new IconSetAuthoringError(
113
+ `The icon id "${iconIdOf(name)}" starts with a digit, and an export name cannot. Pass --id with an id that starts with a letter.`,
114
+ 'ERR_INVALID_ARGUMENT',
115
+ );
116
+ }
107
117
  const pascal = name[0].toUpperCase() + name.slice(1);
108
118
  return pascal.endsWith('Icon') ? pascal : `${pascal}Icon`;
109
119
  }
@@ -146,7 +156,11 @@ function packageDirOf(cwd) {
146
156
  * `selector` names, else the only set.
147
157
  * @param {string} cwd
148
158
  * @param {string} [selector] a set name
149
- * @returns {Promise<{packageDir: string, pkg: Record<string, any>, root: string, set: DiscoveredIconSet, sets: DiscoveredIconSet[]}>}
159
+ * The set's `module` names the package as package.json names it now;
160
+ * `moduleRenamed` says the data file still names an old name, so a command
161
+ * writes the data file even when nothing else changes; `moduleUpdate` gives
162
+ * the old and the new name for the receipt, else null.
163
+ * @returns {Promise<{packageDir: string, pkg: Record<string, any>, root: string, set: DiscoveredIconSet, sets: DiscoveredIconSet[], moduleRenamed: boolean, moduleUpdate: {previous: string, module: string} | null}>}
150
164
  */
151
165
  export async function findLocalIconSet(cwd, selector) {
152
166
  const packageDir = packageDirOf(cwd);
@@ -190,12 +204,20 @@ export async function findLocalIconSet(cwd, selector) {
190
204
  ? found.sets.filter(set => set.name === selector)
191
205
  : found.sets;
192
206
  if (named.length === 1) {
207
+ const set = {...named[0], packageDir};
208
+ const module = moduleInPackage(set.data.module, pkg.name);
209
+ const moduleUpdate =
210
+ module !== set.data.module ? {previous: set.data.module, module} : null;
211
+ const moduleRenamed = moduleUpdate != null;
212
+ if (moduleRenamed) set.data = {...set.data, module};
193
213
  return {
194
214
  packageDir,
195
215
  pkg,
196
216
  root,
197
- set: {...named[0], packageDir},
217
+ set,
198
218
  sets: found.sets,
219
+ moduleRenamed,
220
+ moduleUpdate,
199
221
  };
200
222
  }
201
223
  const broken = selector
@@ -229,6 +251,22 @@ export async function findLocalIconSet(cwd, selector) {
229
251
  );
230
252
  }
231
253
 
254
+ /**
255
+ * The data file's `module` in the package as it is named now. The data file
256
+ * belongs to the CLI, so after a package rename the next write gives the new
257
+ * name (`@acme/old/solid` → `@acme/new/solid`). A ./ path, or a package
258
+ * with no name, is left as it is.
259
+ * @param {string} module
260
+ * @param {unknown} name the package.json `name`
261
+ */
262
+ function moduleInPackage(module, name) {
263
+ if (typeof name !== 'string' || name === '' || module.startsWith('.')) {
264
+ return module;
265
+ }
266
+ const owner = iconModulePackage(module);
267
+ return owner === name ? module : `${name}${module.slice(owner.length)}`;
268
+ }
269
+
232
270
  /** The data file's fields, in the order the file is written. */
233
271
  const DATA_KEYS = [
234
272
  'schemaVersion',
@@ -599,7 +637,7 @@ const SCREAMING_CASE_RE = /^[A-Z][A-Z0-9_]+$/u;
599
637
  * set declares an adapter, also data exports, camelCase included: objects,
600
638
  * and plain strings only in a library whose candidates are all strings.
601
639
  * Left out: `default`, `Icon`, `…Provider` and `…Context` components, SCREAMING_CASE constants, number and boolean
602
- * exports, and `exclude`.
640
+ * exports, packs of other exports ({@link isIconPack}), and `exclude`.
603
641
  * @param {string} file
604
642
  * @param {{adapter?: boolean, exclude?: string[]}} [options] `exclude`: export
605
643
  * names that are not icons
@@ -609,7 +647,9 @@ function iconCandidates(file, {adapter = false, exclude = []} = {}) {
609
647
  const skipped = new Set(exclude);
610
648
  /** @type {Array<{name: string, adapt: boolean, scalar: string | null}>} */
611
649
  const out = [];
612
- for (const name of followedExportNames(file)) {
650
+ const names = followedExportNames(file);
651
+ const exported = new Set(names);
652
+ for (const name of names) {
613
653
  if (name === 'default' || name === 'Icon' || skipped.has(name)) continue;
614
654
  // A context provider or context (`LucideProvider`) is a component that
615
655
  // draws nothing.
@@ -622,7 +662,8 @@ function iconCandidates(file, {adapter = false, exclude = []} = {}) {
622
662
  } else if (
623
663
  adapter &&
624
664
  kind === 'data' &&
625
- /^[A-Za-z][A-Za-z0-9]*$/u.test(name)
665
+ /^[A-Za-z][A-Za-z0-9]*$/u.test(name) &&
666
+ !isIconPack(file, name, exported)
626
667
  ) {
627
668
  const scalar = exportScalarType(file, name);
628
669
  // A number or a boolean draws nothing; a string may be SVG markup.
@@ -637,6 +678,20 @@ function iconCandidates(file, {adapter = false, exclude = []} = {}) {
637
678
  : out;
638
679
  }
639
680
 
681
+ /**
682
+ * Whether a data export is a pack: an object whose keys are all other
683
+ * exports of the module, such as `fas` in a library that also exports
684
+ * `faXmark` and `faHouse`. A pack holds icons but draws nothing.
685
+ * @param {string} file
686
+ * @param {string} name
687
+ * @param {Set<string>} exported every export name of the module
688
+ */
689
+ function isIconPack(file, name, exported) {
690
+ const bindings = staticExportBindings(file, name);
691
+ if (bindings == null || bindings.size < 2) return false;
692
+ return [...bindings.keys()].every(key => key !== name && exported.has(key));
693
+ }
694
+
640
695
  /**
641
696
  * The exports of a library that are not icons and that wrapping it leaves
642
697
  * out (`Icon`, `LucideProvider`, `createLucideIcon`, constants), so the
@@ -690,7 +745,9 @@ export function libraryPrefix(names) {
690
745
 
691
746
  /**
692
747
  * An export's id and the name the set exports it as, with the library prefix
693
- * left out: `featherEye` with prefix `feather` is id `eye`, `EyeIcon`.
748
+ * left out: `featherEye` with prefix `feather` is id `eye`, `EyeIcon`. A
749
+ * name that would start with a digit keeps the prefix (`fa500px` is
750
+ * `fa-500px`, `Fa500pxIcon`).
694
751
  * @param {string} name
695
752
  * @param {string[]} prefix
696
753
  * @returns {{id: string, name: string}}
@@ -698,9 +755,12 @@ export function libraryPrefix(names) {
698
755
  export function iconNaming(name, prefix) {
699
756
  const all = iconIdOf(name).split('-');
700
757
  // Only a name that starts with the prefix, and has more after it, loses it.
758
+ // A name that would then start with a digit keeps the prefix: `fa0` is
759
+ // `fa-0`, `Fa0Icon`.
701
760
  const strip =
702
761
  all.length > prefix.length &&
703
- prefix.every((word, index) => all[index] === word);
762
+ prefix.every((word, index) => all[index] === word) &&
763
+ !/^[0-9]/u.test(all[prefix.length]);
704
764
  if (!strip) prefix = [];
705
765
  const words = all.slice(prefix.length);
706
766
  const id = words.join('-');
@@ -723,20 +783,405 @@ export function modulePrefix(file, options) {
723
783
  return libraryPrefix(prefixNames(iconCandidates(file, options)));
724
784
  }
725
785
 
786
+ /**
787
+ * How a module names its icons: the library prefix every icon export shares
788
+ * ({@link modulePrefix}) and the look words its names end in
789
+ * ({@link lookPositions}), read from its icon exports once. A large module
790
+ * reports its reading, as {@link libraryIcons} does.
791
+ * @param {string} file
792
+ * @param {{adapter?: boolean, module?: string, progress?: (line: string) => void}} [options]
793
+ * `module`: the module as the author named it, for progress; `progress`:
794
+ * hears the reading of a large module
795
+ * @returns {{prefix: string[], positions: Array<Set<string>>}}
796
+ */
797
+ export function moduleNaming(file, options = {}) {
798
+ const label = options.module ?? path.basename(file);
799
+ let count = 0;
800
+ return readingLibrary(
801
+ file,
802
+ {label, progress: options.progress},
803
+ () => {
804
+ const candidates = iconCandidates(file, options);
805
+ count = candidates.length;
806
+ const prefix = libraryPrefix(prefixNames(candidates));
807
+ const positions = lookPositions(
808
+ candidates.map(each => iconNaming(each.name, prefix).id),
809
+ );
810
+ return {prefix, positions};
811
+ },
812
+ () => `Found ${count} icon exports in ${label}.`,
813
+ );
814
+ }
815
+
816
+ /**
817
+ * An export's id and set name ({@link iconNaming}) without the look words
818
+ * its library's names end in ({@link lookPositions}):
819
+ * `XOutline24WGHT500Icon` is `x`, `XIcon`.
820
+ * @param {string} name
821
+ * @param {{prefix: string[], positions: Array<Set<string>>}} naming
822
+ * @returns {{id: string, name: string}}
823
+ */
824
+ export function iconNamingWithoutLook(name, {prefix, positions}) {
825
+ const named = iconNaming(name, prefix);
826
+ const {base} = splitLook(named.id.split('-'), positions);
827
+ if (base.length === named.id.split('-').length) return named;
828
+ const pascal = base
829
+ .map(word => word[0].toUpperCase() + word.slice(1))
830
+ .join('');
831
+ return {id: base.join('-'), name: iconExportName(pascal)};
832
+ }
833
+
834
+ /** A library with at least this many exports reports its reading. */
835
+ const PROGRESS_FROM = 1000;
836
+
837
+ /** Fewer icons than this never show a library's look positions. */
838
+ const LOOK_MIN_ICONS = 20;
839
+
840
+ /** More words than this in one trailing position are glyph names. */
841
+ const LOOK_MAX_VALUES = 12;
842
+
843
+ /** Words that name a look's style, never a glyph. */
844
+ const LOOK_STYLE_WORDS = new Set([
845
+ 'default',
846
+ 'regular',
847
+ 'outline',
848
+ 'outlined',
849
+ 'line',
850
+ 'linear',
851
+ 'stroke',
852
+ 'filled',
853
+ 'fill',
854
+ 'solid',
855
+ 'bold',
856
+ 'light',
857
+ 'thin',
858
+ 'duotone',
859
+ 'twotone',
860
+ 'mini',
861
+ 'micro',
862
+ 'sharp',
863
+ 'round',
864
+ 'rounded',
865
+ 'bulk',
866
+ 'broken',
867
+ ]);
868
+
869
+ /** Words that name a glyph's direction (`ArrowUp`), never a look. */
870
+ const DIRECTION_WORDS = new Set([
871
+ 'up',
872
+ 'down',
873
+ 'left',
874
+ 'right',
875
+ 'top',
876
+ 'bottom',
877
+ 'start',
878
+ 'end',
879
+ 'north',
880
+ 'south',
881
+ 'east',
882
+ 'west',
883
+ ]);
884
+
885
+ /**
886
+ * Whether the words that fill a trailing position name a look: each is
887
+ * numbered (`24`, `wght500`) or one is a style word, and none is a
888
+ * direction word. `ArrowUp` and `ArrowDown` are two glyphs, not two looks.
889
+ * @param {string[]} words
890
+ */
891
+ function namesLook(words) {
892
+ if (words.some(word => DIRECTION_WORDS.has(word))) return false;
893
+ return (
894
+ words.every(word => /^[a-z]*\d+$/u.test(word)) ||
895
+ words.some(word => LOOK_STYLE_WORDS.has(word))
896
+ );
897
+ }
898
+
899
+ /**
900
+ * The trailing words a library encodes its looks with: a style, a size, a
901
+ * weight (`XOutline24WGHT500Icon` is `x` in the `outline`, `24`, `wght500`
902
+ * look). A trailing position is a look position when, across at least
903
+ * {@link LOOK_MIN_ICONS} icons, at most {@link LOOK_MAX_VALUES} words fill
904
+ * it, each on at least 5% of the icons and together on at least 90%, and
905
+ * those words name a look ({@link namesLook}); the positions are read from
906
+ * the end while they hold. Glyph names never meet that bar (`trash-2` and
907
+ * `clock-10` are a few icons each, and `up` and `down` are directions), so
908
+ * a library that encodes no looks has none. Reads each id once per
909
+ * position and keeps only counts.
910
+ * @param {string[]} ids every icon's id
911
+ * @returns {Array<Set<string>>} the look positions, the last word first
912
+ */
913
+ export function lookPositions(ids) {
914
+ if (ids.length < LOOK_MIN_ICONS) return [];
915
+ /** @type {Array<Set<string>>} */
916
+ const positions = [];
917
+ const least = Math.max(2, Math.ceil(ids.length * 0.05));
918
+ while (positions.length < 4) {
919
+ /** @type {Map<string, number>} */
920
+ const counts = new Map();
921
+ for (const id of ids) {
922
+ const words = id.split('-');
923
+ const {base} = splitLook(words, positions);
924
+ if (base.length < 2 || base.length < words.length - positions.length) {
925
+ continue;
926
+ }
927
+ const last = /** @type {string} */ (base.at(-1));
928
+ counts.set(last, (counts.get(last) ?? 0) + 1);
929
+ }
930
+ const values = [...counts].filter(([, count]) => count >= least);
931
+ if (values.length === 0 || values.length > LOOK_MAX_VALUES) break;
932
+ const covered = values.reduce((sum, [, count]) => sum + count, 0);
933
+ if (covered < ids.length * 0.9) break;
934
+ if (!namesLook(values.map(([value]) => value))) break;
935
+ positions.push(new Set(values.map(([value]) => value)));
936
+ }
937
+ return positions;
938
+ }
939
+
940
+ /**
941
+ * An id's glyph words and its look words, by {@link lookPositions}:
942
+ * `x-outline-24-wght500` is `x` with `[wght500, 24, outline]`, null where
943
+ * the id has no look word.
944
+ * @param {string[]} words
945
+ * @param {Array<Set<string>>} positions
946
+ * @returns {{base: string[], look: Array<string | null>}}
947
+ */
948
+ export function splitLook(words, positions) {
949
+ let end = words.length;
950
+ /** @type {Array<string | null>} */
951
+ const look = positions.map(() => null);
952
+ for (const [index, position] of positions.entries()) {
953
+ const last = words[end - 1];
954
+ if (end < 2 || last == null || !position.has(last)) break;
955
+ look[index] = last;
956
+ end--;
957
+ }
958
+ return {base: end === words.length ? words : words.slice(0, end), look};
959
+ }
960
+
961
+ /** Style words a library's default look is usually named by. */
962
+ const DEFAULT_STYLE_WORDS = ['default', 'regular', 'outline', 'outlined'];
963
+
964
+ /**
965
+ * The word each look position prefers: a word of `prefer` it has (the set's
966
+ * default variant), else a usual default style word, else the middle of a
967
+ * series of numbered words (`wght300` … `wght700` gives `wght500`), else
968
+ * its first word in order.
969
+ * @param {Array<Set<string>>} positions
970
+ * @param {string[]} [prefer]
971
+ * @returns {string[]}
972
+ */
973
+ export function preferredLook(positions, prefer = []) {
974
+ const wanted = prefer.map(word => word.toLowerCase());
975
+ return positions.map(position => {
976
+ const values = [...position].sort();
977
+ const chosen =
978
+ wanted.find(word => position.has(word)) ??
979
+ DEFAULT_STYLE_WORDS.find(word => position.has(word));
980
+ if (chosen) return chosen;
981
+ const numbered = values.map(value => /^([a-z]*)(\d+)$/u.exec(value));
982
+ const lead = numbered[0]?.[1];
983
+ if (
984
+ values.length > 1 &&
985
+ numbered.every(match => match != null && match[1] === lead)
986
+ ) {
987
+ const series = values
988
+ .map((value, index) => ({
989
+ value,
990
+ n: Number(/** @type {RegExpExecArray} */ (numbered[index])[2]),
991
+ }))
992
+ .sort((a, b) => a.n - b.n);
993
+ return series[Math.floor((series.length - 1) / 2)].value;
994
+ }
995
+ return values[0];
996
+ });
997
+ }
998
+
999
+ /**
1000
+ * One icon a library gives.
1001
+ * @typedef {object} LibraryIcon
1002
+ * @property {string} export the library export it reads
1003
+ * @property {string} id
1004
+ * @property {string} name the name the set exports it as
1005
+ * @property {boolean} adapt
1006
+ * @property {string[]} aliases the ids of the other names the library
1007
+ * exports the icon as, leaving out the library's own name (`lucide-trash`)
1008
+ * @property {Array<string | null>} [look] in a library that encodes looks:
1009
+ * this export's look words by position, the last word first
1010
+ * @property {string[]} [looks] in a library that encodes looks: every
1011
+ * export that draws the glyph, this one included
1012
+ */
1013
+
1014
+ /**
1015
+ * The words a library's looks are named by, and the look a set takes from
1016
+ * it: what {@link libraryIcons} found, for the receipt.
1017
+ * @typedef {object} LibraryLookSummary
1018
+ * @property {string[][]} positions each position's words, sorted, the last
1019
+ * word of a name first
1020
+ * @property {string[]} preferred the word taken in each position
1021
+ * @property {number} exports how many exports draw the icons
1022
+ */
1023
+
726
1024
  /**
727
1025
  * Every icon a whole library exports, for wrapping it at once: one entry per
728
1026
  * component (and, with an adapter, per data export), read by its `…Icon`
729
1027
  * export when it has one (an alias of the same value is recorded once), with
730
1028
  * its id and the name the set exports it as from the name, the library
731
1029
  * prefix left out ({@link libraryPrefix}).
1030
+ *
1031
+ * A library that encodes looks in its export names ({@link lookPositions})
1032
+ * gives one icon per glyph: the look {@link preferredLook} prefers, its id
1033
+ * and name without the look words (`XOutline24WGHT500Icon` is `x`,
1034
+ * `XIcon`), and its `looks`, every export that draws the glyph.
732
1035
  * @param {string} file
733
- * @param {{adapter?: boolean, exclude?: string[]}} [options] `adapter`:
734
- * whether the set declares one; `exclude`: export names that are not icons
735
- * @returns {Array<{export: string, id: string, name: string, adapt: boolean, aliases: string[]}>}
736
- * `aliases`: the ids of the other names the library exports the icon as,
737
- * leaving out the library's own name (`lucide-trash`)
1036
+ * @param {{adapter?: boolean, exclude?: string[], prefer?: string[] | ((positions: Array<Set<string>>) => string[]), module?: string, progress?: (line: string) => void, summary?: (summary: LibraryLookSummary) => void}} [options]
1037
+ * `adapter`: whether the set declares one; `exclude`: export names that
1038
+ * are not icons; `prefer`: look words to prefer (the set's default
1039
+ * variant), or a function that gives them from the library's look
1040
+ * positions before any glyph is picked; `module`: the module as the author named it, for progress;
1041
+ * `progress`: hears the reading of a large module;
1042
+ * `summary`: hears the looks found, when the library has any
1043
+ * @returns {LibraryIcon[]}
738
1044
  */
739
1045
  export function libraryIcons(file, options = {}) {
1046
+ const label = options.module ?? path.basename(file);
1047
+ /** @type {LibraryIcon[]} */
1048
+ let all = [];
1049
+ return readingLibrary(
1050
+ file,
1051
+ {label, progress: options.progress},
1052
+ () => {
1053
+ all = collectLibraryIcons(file, options);
1054
+ const prefer =
1055
+ typeof options.prefer === 'function'
1056
+ ? options.prefer(lookPositions(all.map(icon => icon.id)))
1057
+ : options.prefer;
1058
+ const grouped = libraryLooks(all, prefer);
1059
+ if (grouped.positions.length > 0) {
1060
+ options.summary?.({
1061
+ positions: grouped.positions.map(position => [...position].sort()),
1062
+ preferred: grouped.preferred,
1063
+ exports: all.length,
1064
+ });
1065
+ }
1066
+ return grouped.icons;
1067
+ },
1068
+ icons =>
1069
+ icons.length === all.length
1070
+ ? `Found ${icons.length} icons in ${label}.`
1071
+ : `Found ${icons.length} icons in ${label}, drawn by ${all.length} exports in their looks.`,
1072
+ );
1073
+ }
1074
+
1075
+ /**
1076
+ * Read a library with its progress reported: when `progress` is given and
1077
+ * the module has {@link PROGRESS_FROM} exports or more, a line before `read`
1078
+ * runs and the line `found` gives after.
1079
+ * @template T
1080
+ * @param {string} file
1081
+ * @param {{label: string, progress?: (line: string) => void}} reading
1082
+ * `label`: the module as the author named it
1083
+ * @param {() => T} read
1084
+ * @param {(result: T) => string} found
1085
+ * @returns {T}
1086
+ */
1087
+ function readingLibrary(file, {label, progress}, read, found) {
1088
+ const exportCount = progress ? followedExportNames(file).length : 0;
1089
+ if (progress == null || exportCount < PROGRESS_FROM) return read();
1090
+ progress(`Reading ${exportCount} exports of ${label}...`);
1091
+ const result = read();
1092
+ progress(found(result));
1093
+ return result;
1094
+ }
1095
+
1096
+ /**
1097
+ * The library's icons grouped by glyph when its export names encode looks
1098
+ * ({@link libraryIcons}), with the look positions and the words preferred.
1099
+ * Without look positions the icons are returned as they are.
1100
+ * @param {LibraryIcon[]} all every icon, one per export
1101
+ * @param {string[]} [prefer]
1102
+ * @returns {{icons: LibraryIcon[], positions: Array<Set<string>>, preferred: string[]}}
1103
+ */
1104
+ export function libraryLooks(all, prefer = []) {
1105
+ const positions = lookPositions(all.map(icon => icon.id));
1106
+ if (positions.length === 0) return {icons: all, positions, preferred: []};
1107
+ const preferred = preferredLook(positions, prefer);
1108
+ // How far a look is from the preferred one, as a sortable key: the
1109
+ // position first in the name (the style) counts most.
1110
+ const distance = (/** @type {Array<string | null>} */ look) => {
1111
+ let key = '';
1112
+ for (let index = look.length - 1; index >= 0; index--) {
1113
+ key += look[index] === preferred[index] ? '0' : '1';
1114
+ }
1115
+ return key;
1116
+ };
1117
+ /** @type {Map<string, {best: LibraryIcon, look: Array<string | null>, key: string, looks: string[]}>} */
1118
+ const byGlyph = new Map();
1119
+ for (const icon of all) {
1120
+ const {base, look} = splitLook(icon.id.split('-'), positions);
1121
+ const id = base.join('-');
1122
+ const key = distance(look);
1123
+ const group = byGlyph.get(id);
1124
+ if (!group) {
1125
+ byGlyph.set(id, {best: icon, look, key, looks: [icon.export]});
1126
+ continue;
1127
+ }
1128
+ group.looks.push(icon.export);
1129
+ if (
1130
+ key < group.key ||
1131
+ (key === group.key && icon.export < group.best.export)
1132
+ ) {
1133
+ group.best = icon;
1134
+ group.look = look;
1135
+ group.key = key;
1136
+ }
1137
+ }
1138
+ /** @type {LibraryIcon[]} */
1139
+ const icons = [];
1140
+ for (const [id, {best, look, looks}] of byGlyph) {
1141
+ const pascal = id
1142
+ .split('-')
1143
+ .map(word => word[0].toUpperCase() + word.slice(1))
1144
+ .join('');
1145
+ icons.push({
1146
+ ...best,
1147
+ id,
1148
+ name: iconExportName(pascal),
1149
+ aliases: best.aliases.filter(alias => !byGlyph.has(alias)),
1150
+ look,
1151
+ looks: looks.sort(),
1152
+ });
1153
+ }
1154
+ icons.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
1155
+ return {icons, positions, preferred};
1156
+ }
1157
+
1158
+ /**
1159
+ * Every icon a library exports, one per export: {@link libraryIcons} before
1160
+ * looks are grouped. A large module reports its reading, as
1161
+ * {@link libraryIcons} does.
1162
+ * @param {string} file
1163
+ * @param {{adapter?: boolean, exclude?: string[], module?: string, progress?: (line: string) => void}} [options]
1164
+ * `module`: the module as the author named it, for progress; `progress`:
1165
+ * hears the reading of a large module
1166
+ * @returns {LibraryIcon[]}
1167
+ */
1168
+ export function everyLibraryIcon(file, options = {}) {
1169
+ const label = options.module ?? path.basename(file);
1170
+ return readingLibrary(
1171
+ file,
1172
+ {label, progress: options.progress},
1173
+ () => collectLibraryIcons(file, options),
1174
+ icons => `Found ${icons.length} exports in ${label}.`,
1175
+ );
1176
+ }
1177
+
1178
+ /**
1179
+ * {@link everyLibraryIcon} without progress.
1180
+ * @param {string} file
1181
+ * @param {{adapter?: boolean, exclude?: string[]}} [options]
1182
+ * @returns {LibraryIcon[]}
1183
+ */
1184
+ function collectLibraryIcons(file, options = {}) {
740
1185
  const candidates = iconCandidates(file, options);
741
1186
  /** @type {Map<string, {names: string[], adapt: boolean, scalar: string | null}>} */
742
1187
  const byOrigin = new Map();
@@ -830,16 +1275,29 @@ export function iconDefinitionSource(doc) {
830
1275
  }
831
1276
 
832
1277
  /**
833
- * Check a new icon definition for a set: a camelCase name no Astryx
834
- * definition has, a description, and at least one lower-case word.
1278
+ * A new definition's name as written in a command: camelCase as given, or
1279
+ * kebab-case as the docs list definitions (`ai-helper` is `aiHelper`).
1280
+ * @param {string} name
1281
+ */
1282
+ export function definitionNameFromInput(name) {
1283
+ return /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/u.test(name)
1284
+ ? name.replace(/-([a-z0-9])/gu, (_, c) => c.toUpperCase())
1285
+ : name;
1286
+ }
1287
+
1288
+ /**
1289
+ * Check a new icon definition for a set: a camelCase name (or its kebab-case
1290
+ * form, {@link definitionNameFromInput}) no Astryx definition has, a
1291
+ * description, and at least one lower-case word.
835
1292
  * @param {DiscoveredIconSet} set
836
- * @param {{name: string, description?: string, words?: string[]}} doc
1293
+ * @param {{name: string, description?: string, words?: string[]}} given
837
1294
  * @returns {{name: string, description: string, words: string[]}}
838
1295
  */
839
- export function checkNewDefinition(set, doc) {
1296
+ export function checkNewDefinition(set, given) {
1297
+ const doc = {...given, name: definitionNameFromInput(given.name)};
840
1298
  if (!/^[a-z][a-zA-Z0-9]*$/u.test(doc.name)) {
841
1299
  throw new IconSetAuthoringError(
842
- `Invalid icon definition name "${doc.name}": use camelCase starting with a lower-case letter.`,
1300
+ `Invalid icon definition name "${doc.name}": use camelCase (aiHelper) or kebab-case (ai-helper), starting with a lower-case letter.`,
843
1301
  'ERR_INVALID_ARGUMENT',
844
1302
  );
845
1303
  }
@@ -919,8 +1377,11 @@ const GENERATED_HEADER = [
919
1377
 
920
1378
  /**
921
1379
  * The top-level statements of a generated module, one normalized line each,
922
- * however the file was formatted: whitespace collapsed, no padding inside
923
- * braces, no trailing comma. Comments are dropped.
1380
+ * however a formatter left the file (Prettier's line breaks, double quotes,
1381
+ * trailing commas, semicolons or none): whitespace collapsed, no padding
1382
+ * inside braces or parentheses, no trailing comma, type members separated by
1383
+ * `; ` with none before the closing brace, no statement semicolon, and
1384
+ * single-quoted strings. Comments are dropped.
924
1385
  * @param {string} text
925
1386
  * @param {string} label the module's path, for the error
926
1387
  * @returns {string[]}
@@ -935,19 +1396,149 @@ function generatedStatements(text, label) {
935
1396
  'ERR_INVALID_ARGUMENT',
936
1397
  );
937
1398
  }
1399
+ return ast.program.body.map(node => {
1400
+ const start = /** @type {number} */ (node.start);
1401
+ // A formatter without semicolons ends each type member with a line
1402
+ // break, which collapses to a space: give each member its separator.
1403
+ const separators = typeMemberEnds(node)
1404
+ .filter(end => !/^\s*[;,]/u.test(text.slice(end, end + 1)))
1405
+ .filter(end => !/[;,]$/u.test(text.slice(end - 1, end)))
1406
+ .sort((a, b) => b - a);
1407
+ let statement = text.slice(start, /** @type {number} */ (node.end));
1408
+ for (const end of separators) {
1409
+ const at = end - start;
1410
+ statement = `${statement.slice(0, at)};${statement.slice(at)}`;
1411
+ }
1412
+ return normalizedStatement(statement);
1413
+ });
1414
+ }
1415
+
1416
+ /**
1417
+ * One statement's text in the normalized form {@link generatedStatements}
1418
+ * gives.
1419
+ * @param {string} statement
1420
+ */
1421
+ function normalizedStatement(statement) {
1422
+ return statement
1423
+ .replace(/\s+/gu, ' ')
1424
+ .replace(/"((?:[^"'\\]|\\.)*)"/gu, "'$1'")
1425
+ .replace(/([{(]) /gu, '$1')
1426
+ .replace(/[,;]? ?([})])/gu, '$1')
1427
+ .trim()
1428
+ .replace(/ ?;$/u, '');
1429
+ }
1430
+
1431
+ /**
1432
+ * Where each type member of a statement ends (the members of every type
1433
+ * literal and interface in it).
1434
+ * @param {any} node
1435
+ * @returns {number[]}
1436
+ */
1437
+ function typeMemberEnds(node) {
1438
+ /** @type {number[]} */
1439
+ const ends = [];
1440
+ /** @param {any} each */
1441
+ const visit = each => {
1442
+ if (each == null || typeof each !== 'object') return;
1443
+ if (Array.isArray(each)) {
1444
+ for (const item of each) visit(item);
1445
+ return;
1446
+ }
1447
+ if (typeof each.type !== 'string') return;
1448
+ const members =
1449
+ each.type === 'TSTypeLiteral'
1450
+ ? each.members
1451
+ : each.type === 'TSInterfaceBody'
1452
+ ? each.body
1453
+ : null;
1454
+ if (members) {
1455
+ for (const member of members) ends.push(member.end);
1456
+ }
1457
+ for (const key of Object.keys(each)) {
1458
+ if (
1459
+ key === 'loc' ||
1460
+ key === 'leadingComments' ||
1461
+ key === 'trailingComments' ||
1462
+ key === 'innerComments'
1463
+ ) {
1464
+ continue;
1465
+ }
1466
+ visit(each[key]);
1467
+ }
1468
+ };
1469
+ visit(node);
1470
+ return ends;
1471
+ }
1472
+
1473
+ /**
1474
+ * A normalized statement as the generated module writes it: with its
1475
+ * semicolon, except after a declaration that ends in its own block.
1476
+ * @param {string} statement
1477
+ */
1478
+ function terminated(statement) {
1479
+ return /^(?:export (?:default )?)?(?:declare )?(?:abstract )?(?:async )?(?:function\b|class\b|interface\b|enum\b|namespace\b|module\b)/u.test(
1480
+ statement,
1481
+ )
1482
+ ? statement
1483
+ : `${statement};`;
1484
+ }
1485
+
1486
+ /** Syntax-tree fields that only say how a file is laid out. */
1487
+ const LAYOUT_KEYS = new Set([
1488
+ 'start',
1489
+ 'end',
1490
+ 'loc',
1491
+ 'range',
1492
+ 'extra',
1493
+ 'leadingComments',
1494
+ 'trailingComments',
1495
+ 'innerComments',
1496
+ ]);
1497
+
1498
+ /**
1499
+ * The top-level statements of a module as syntax trees without positions,
1500
+ * comments, or raw text, one string each. A formatter changes line breaks,
1501
+ * quotes, semicolons, trailing commas, and the wrapping of long type
1502
+ * arguments; none of these change the tree.
1503
+ * @param {string} text
1504
+ * @returns {string[]}
1505
+ */
1506
+ function statementTrees(text) {
1507
+ const ast = parse(text, {sourceType: 'module', plugins: ['typescript']});
938
1508
  return ast.program.body.map(node =>
939
- text
940
- .slice(
941
- /** @type {number} */ (node.start),
942
- /** @type {number} */ (node.end),
943
- )
944
- .replace(/\s+/gu, ' ')
945
- .replace(/\{ /gu, '{')
946
- .replace(/,? \}/gu, '}')
947
- .replace(/,\}/gu, '}'),
1509
+ JSON.stringify(node, (key, value) =>
1510
+ LAYOUT_KEYS.has(key) ? undefined : value,
1511
+ ),
948
1512
  );
949
1513
  }
950
1514
 
1515
+ /**
1516
+ * Whether a generated declaration file declares what its generated module
1517
+ * gives, statement by statement however a formatter left either file
1518
+ * ({@link statementTrees}); the header comment is ignored.
1519
+ * @param {string} actual the declaration file as it is
1520
+ * @param {string} expected {@link generatedTypesText} for the module
1521
+ * @param {string} label the declaration file's path, for a parse error
1522
+ */
1523
+ export function generatedTypesMatch(actual, expected, label) {
1524
+ let have;
1525
+ try {
1526
+ have = statementTrees(actual);
1527
+ } catch {
1528
+ return false;
1529
+ }
1530
+ let want;
1531
+ try {
1532
+ want = statementTrees(expected);
1533
+ } catch (error) {
1534
+ throw new IconSetAuthoringError(
1535
+ `The declarations written for ${label} do not parse (${error instanceof Error ? error.message : String(error)}).`,
1536
+ 'ERR_INVALID_ARGUMENT',
1537
+ );
1538
+ }
1539
+ return have.length === want.length && have.every((s, i) => s === want[i]);
1540
+ }
1541
+
951
1542
  /** The local name the generated module gives the set's adapter. */
952
1543
  const ADAPTER_LOCAL = 'adaptIcon';
953
1544
 
@@ -955,7 +1546,7 @@ const ADAPTER_LOCAL = 'adaptIcon';
955
1546
  export const THEME_MAP_NAME = 'themeIcons';
956
1547
 
957
1548
  /** How the generated module imports React for its theme map. */
958
- const REACT_IMPORT = "import {createElement} from 'react';";
1549
+ const REACT_IMPORT = "import {createElement} from 'react'";
959
1550
 
960
1551
  /** The built-in icon definitions: the shared names a theme map covers. */
961
1552
  const BUILT_IN = new Set(ICON_NAMES);
@@ -987,10 +1578,15 @@ export function generatedModulePath(set, packageDir) {
987
1578
  * component
988
1579
  */
989
1580
 
990
- /** The props every theme-map element gets: sized to its box, hidden from assistive tech. */
1581
+ /**
1582
+ * The props every theme-map element gets: hidden from assistive tech, and
1583
+ * sized to its box by CSS as well as by attributes. A theme's icon sits in a
1584
+ * box whose font size is the icon size; CSS width and height override the
1585
+ * svg's own size attributes, so a component that writes its own (`size`
1586
+ * 24, ignoring `width` and `height`) still draws at the box's size.
1587
+ */
991
1588
  const THEME_ELEMENT_PROPS =
992
- "{'aria-hidden': true, 'width': '1em', 'height': '1em'}";
993
-
1589
+ "{'aria-hidden': true, 'width': '1em', 'height': '1em', 'style': {'width': '1em', 'height': '1em'}}";
994
1590
 
995
1591
  /**
996
1592
  * The declaration file's text for a generated module's statements: each
@@ -1003,10 +1599,11 @@ export function generatedTypesText(statements) {
1003
1599
  /** @type {string[]} */
1004
1600
  const lines = [];
1005
1601
  const react = new Set();
1006
- for (const statement of statements) {
1602
+ for (const given of statements) {
1603
+ const statement = normalizedStatement(given);
1007
1604
  if (statement.startsWith('import ')) continue;
1008
1605
  if (/^export (?:\*|\{[^}]*\}) from /u.test(statement)) {
1009
- lines.push(statement);
1606
+ lines.push(terminated(statement));
1010
1607
  continue;
1011
1608
  }
1012
1609
  const adapted = new RegExp(
@@ -1020,7 +1617,7 @@ export function generatedTypesText(statements) {
1020
1617
  );
1021
1618
  continue;
1022
1619
  }
1023
- const theme = /^export const (\w+) = \{(.*)\};$/u.exec(statement);
1620
+ const theme = /^export const (\w+) = \{(.*)\}$/u.exec(statement);
1024
1621
  if (
1025
1622
  theme &&
1026
1623
  (theme[1] === THEME_MAP_NAME || statement.includes('createElement('))
@@ -1091,46 +1688,47 @@ export function generatedModuleText(
1091
1688
  };
1092
1689
  const themeName = data.themeMap === THEME_MAP_NAME ? THEME_MAP_NAME : null;
1093
1690
  const lines = before == null ? [] : generatedStatements(before, generated);
1691
+ const lineSet = new Set(lines);
1094
1692
  // Written once, below: the adapter's import, React's createElement, and
1095
- // the theme map.
1096
- const adapterImport = new RegExp(`\\bas ${ADAPTER_LOCAL}\\b`, 'u');
1097
- const dropped = [...new Set(remove)].map(
1098
- name =>
1099
- new RegExp(
1100
- `(?:\\bas ${name}(?:Source)?\\}|^export const ${name} = |^export \\{${name}\\} |^import ${name}Source )`,
1101
- 'u',
1102
- ),
1103
- );
1693
+ // the theme map. Every lookup below is by name, so a library of twenty
1694
+ // thousand icons is written in one pass.
1695
+ const removed = new Set(remove);
1104
1696
  // A re-export binds no local name, so the theme map reads each re-exported
1105
1697
  // icon through an import that mirrors its re-export. Those imports are
1106
1698
  // rewritten with the theme map.
1107
1699
  const themeImport = (/** @type {string} */ line) =>
1108
1700
  themeName != null &&
1109
1701
  line.startsWith('import {') &&
1110
- lines.includes(`export${line.slice('import'.length)}`);
1111
- const managed = (/** @type {string} */ line) =>
1112
- dropped.some(pattern => pattern.test(line)) ||
1113
- adapterImport.test(line) ||
1114
- line === REACT_IMPORT ||
1115
- themeImport(line) ||
1116
- (themeName != null && line.startsWith(`export const ${themeName} = `));
1702
+ lineSet.has(`export${line.slice('import'.length)}`);
1703
+ const managed = (/** @type {string} */ line) => {
1704
+ const name = statementName(line);
1705
+ if (name != null) {
1706
+ if (removed.has(name)) return true;
1707
+ if (name.endsWith('Source') && removed.has(name.slice(0, -6))) {
1708
+ return true;
1709
+ }
1710
+ if (name === ADAPTER_LOCAL) return true;
1711
+ }
1712
+ return (
1713
+ line === REACT_IMPORT ||
1714
+ themeImport(line) ||
1715
+ (themeName != null && line.startsWith(`export const ${themeName} = `))
1716
+ );
1717
+ };
1117
1718
  const imports = new Set(
1118
1719
  lines.filter(line => line.startsWith('import ') && !managed(line)),
1119
1720
  );
1120
1721
  const exports = new Set(
1121
1722
  lines.filter(line => !line.startsWith('import ') && !managed(line)),
1122
1723
  );
1724
+ /** @type {Map<string, string>} each exported name → its statement */
1725
+ const exported = new Map();
1726
+ for (const line of exports) {
1727
+ const name = statementName(line);
1728
+ if (name != null && !exported.has(name)) exported.set(name, line);
1729
+ }
1123
1730
  /** @param {string} name */
1124
- const existing = name =>
1125
- [...exports].find(line =>
1126
- // The name the module exports: after `as`, alone in braces, or a
1127
- // const; never the source name of another export (`TrashIcon as
1128
- // TrashSolidIcon` exports TrashSolidIcon).
1129
- new RegExp(
1130
- `(?:\\bas\\s+${name}\\s*\\}|^export\\s+\\{\\s*${name}\\s*\\}|^export const\\s+${name}\\b)`,
1131
- 'u',
1132
- ).test(line),
1133
- );
1731
+ const existing = name => exported.get(name);
1134
1732
  for (const icon of icons) {
1135
1733
  const specifier = specifierOf(icon.from);
1136
1734
  /** @type {string[]} */
@@ -1141,29 +1739,32 @@ export function generatedModuleText(
1141
1739
  const local = `${icon.name}Source`;
1142
1740
  wantImports.push(
1143
1741
  icon.source === 'default'
1144
- ? `import ${local} from '${specifier}';`
1145
- : `import {${icon.source === local ? local : `${icon.source} as ${local}`}} from '${specifier}';`,
1742
+ ? `import ${local} from '${specifier}'`
1743
+ : `import {${icon.source === local ? local : `${icon.source} as ${local}`}} from '${specifier}'`,
1146
1744
  );
1147
- want.push(`export const ${icon.name} = ${ADAPTER_LOCAL}(${local});`);
1745
+ want.push(`export const ${icon.name} = ${ADAPTER_LOCAL}(${local})`);
1148
1746
  } else {
1149
1747
  want.push(
1150
1748
  icon.source === icon.name
1151
- ? `export {${icon.name}} from '${specifier}';`
1152
- : `export {${icon.source} as ${icon.name}} from '${specifier}';`,
1749
+ ? `export {${icon.name}} from '${specifier}'`
1750
+ : `export {${icon.source} as ${icon.name}} from '${specifier}'`,
1153
1751
  );
1154
1752
  }
1155
1753
  const prior = existing(icon.name);
1156
1754
  if (prior) {
1157
1755
  if (prior !== want[0]) {
1158
1756
  throw new IconSetAuthoringError(
1159
- `The generated icons module already exports ${icon.name} as \`${prior}\`. Pass another name, or edit ${generated}.`,
1757
+ `The generated icons module already exports ${icon.name} as \`${terminated(prior)}\`. Pass another name, or edit ${generated}.`,
1160
1758
  'ERR_FILE_EXISTS',
1161
1759
  );
1162
1760
  }
1163
1761
  continue;
1164
1762
  }
1165
1763
  for (const line of wantImports) imports.add(line);
1166
- for (const line of want) exports.add(line);
1764
+ for (const line of want) {
1765
+ exports.add(line);
1766
+ exported.set(icon.name, line);
1767
+ }
1167
1768
  }
1168
1769
  const needsAdapter = [...exports].some(line =>
1169
1770
  line.includes(`= ${ADAPTER_LOCAL}(`),
@@ -1186,12 +1787,9 @@ export function generatedModuleText(
1186
1787
  theme.push(
1187
1788
  ` ${name}: createElement(${exportName}, ${THEME_ELEMENT_PROPS}),`,
1188
1789
  );
1189
- const reexport = [...exports].find(line =>
1190
- new RegExp(
1191
- `^export \\{(?:\\w+ as )?${exportName}\\} from `,
1192
- 'u',
1193
- ).test(line),
1194
- );
1790
+ const line = exported.get(exportName);
1791
+ const reexport =
1792
+ line != null && line.startsWith('export {') ? line : undefined;
1195
1793
  if (reexport) {
1196
1794
  themeImports.add(`import${reexport.slice('export'.length)}`);
1197
1795
  }
@@ -1201,15 +1799,17 @@ export function generatedModuleText(
1201
1799
  const adapterLine =
1202
1800
  needsAdapter && data.adapter
1203
1801
  ? [
1204
- `import {${data.adapter.export} as ${ADAPTER_LOCAL}} from '${specifierOf(data.adapter.module)}';`,
1802
+ `import {${data.adapter.export} as ${ADAPTER_LOCAL}} from '${specifierOf(data.adapter.module)}'`,
1205
1803
  ]
1206
1804
  : [];
1207
1805
  const js = [
1208
1806
  ...GENERATED_HEADER,
1209
- ...(themeName ? [REACT_IMPORT] : []),
1210
- ...adapterLine,
1211
- ...[...imports, ...themeImports].sort(),
1212
- ...[...exports].sort(),
1807
+ ...[
1808
+ ...(themeName ? [REACT_IMPORT] : []),
1809
+ ...adapterLine,
1810
+ ...[...imports, ...themeImports].sort(),
1811
+ ...[...exports].sort(),
1812
+ ].map(terminated),
1213
1813
  ...(themeName
1214
1814
  ? theme.length > 0
1215
1815
  ? [`export const ${themeName} = {`, ...theme, '};']
@@ -1226,6 +1826,25 @@ export function generatedModuleText(
1226
1826
  };
1227
1827
  }
1228
1828
 
1829
+ /**
1830
+ * The name one generated statement binds: the name an export exports
1831
+ * (`export {A as B} from …` is `B`, `export {A} from …` is `A`, `export
1832
+ * const A = …` is `A`), or the local name an import binds (`import {A as
1833
+ * BSource} from …` is `BSource`, `import BSource from …` is `BSource`).
1834
+ * Null for anything else.
1835
+ * @param {string} line
1836
+ * @returns {string | null}
1837
+ */
1838
+ function statementName(line) {
1839
+ const named =
1840
+ /^(?:export|import) \{\s*([$\w]+)(?:\s+as\s+([$\w]+))?\s*\}/u.exec(line);
1841
+ if (named) return named[2] ?? named[1];
1842
+ const constant = /^export const ([$\w]+)\b/u.exec(line);
1843
+ if (constant) return constant[1];
1844
+ const plain = /^import ([$\w]+) from /u.exec(line);
1845
+ return plain ? plain[1] : null;
1846
+ }
1847
+
1229
1848
  /**
1230
1849
  * Every name the generated module already exports one library export as: `export {featherSun as SunIcon} from '…'` or the import an adapted
1231
1850
  * icon reads (`import {featherSun as SunIconSource} from '…'`). Adding the
@@ -1256,7 +1875,7 @@ export function generatedNamesOf(packageDir, generated, from, source) {
1256
1875
  .join('/');
1257
1876
  if (!specifier.startsWith('.')) specifier = `./${specifier}`;
1258
1877
  }
1259
- const tail = ` from '${specifier}';`;
1878
+ const tail = ` from '${specifier}'`;
1260
1879
  for (const statement of statements) {
1261
1880
  if (!statement.endsWith(tail)) continue;
1262
1881
  const head = statement.slice(0, -tail.length);
@@ -1295,10 +1914,11 @@ export function generatedNamesOf(packageDir, generated, from, source) {
1295
1914
  * differently; and a refresh changes only the icons its module supplies.
1296
1915
  * @param {string} packageDir
1297
1916
  * @param {string} generated
1298
- * @returns {Map<string, {module: string, source: string}>}
1917
+ * @returns {Map<string, {module: string, source: string, adapt: boolean}>}
1918
+ * `adapt`: the set's adapter turns the export into a component
1299
1919
  */
1300
1920
  export function generatedOrigins(packageDir, generated) {
1301
- /** @type {Map<string, {module: string, source: string}>} */
1921
+ /** @type {Map<string, {module: string, source: string, adapt: boolean}>} */
1302
1922
  const origins = new Map();
1303
1923
  const file = path.join(packageDir, generated);
1304
1924
  if (!fs.existsSync(file)) return origins;
@@ -1318,33 +1938,36 @@ export function generatedOrigins(packageDir, generated) {
1318
1938
  return `./${rel}`;
1319
1939
  };
1320
1940
  for (const statement of statements) {
1321
- const reexport = /^export \{(\w+)(?: as (\w+))?\} from '([^']+)';$/u.exec(
1941
+ const reexport = /^export \{(\w+)(?: as (\w+))?\} from '([^']+)'$/u.exec(
1322
1942
  statement,
1323
1943
  );
1324
1944
  if (reexport) {
1325
1945
  origins.set(reexport[2] ?? reexport[1], {
1326
1946
  module: fromRoot(reexport[3]),
1327
1947
  source: reexport[1],
1948
+ adapt: false,
1328
1949
  });
1329
1950
  continue;
1330
1951
  }
1331
- const adapted = /^import \{(\w+) as (\w+)Source\} from '([^']+)';$/u.exec(
1952
+ const adapted = /^import \{(\w+) as (\w+)Source\} from '([^']+)'$/u.exec(
1332
1953
  statement,
1333
1954
  );
1334
1955
  if (adapted) {
1335
1956
  origins.set(adapted[2], {
1336
1957
  module: fromRoot(adapted[3]),
1337
1958
  source: adapted[1],
1959
+ adapt: true,
1338
1960
  });
1339
1961
  continue;
1340
1962
  }
1341
- const adaptedDefault = /^import (\w+)Source from '([^']+)';$/u.exec(
1963
+ const adaptedDefault = /^import (\w+)Source from '([^']+)'$/u.exec(
1342
1964
  statement,
1343
1965
  );
1344
1966
  if (adaptedDefault) {
1345
1967
  origins.set(adaptedDefault[1], {
1346
1968
  module: fromRoot(adaptedDefault[2]),
1347
1969
  source: 'default',
1970
+ adapt: true,
1348
1971
  });
1349
1972
  }
1350
1973
  }
@@ -1376,6 +1999,63 @@ export function iconModulePackage(specifier) {
1376
1999
  return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
1377
2000
  }
1378
2001
 
2002
+ /**
2003
+ * The set's exports that read one file of a package, where a refresh from
2004
+ * that package's root can read them from the root instead. An export moves
2005
+ * when the root exports the same icon: an export that resolves to the same
2006
+ * file and binding. When the subpath export cannot be resolved, a root
2007
+ * export of the same name counts. Each maps to the root's
2008
+ * export and the module it reads now. Empty unless `root` is a package
2009
+ * root, not a subpath or a ./ path.
2010
+ * @param {Map<string, {module: string, source: string}>} origins the
2011
+ * set's exports ({@link generatedOrigins})
2012
+ * @param {{file: string, module: string}} root the refreshed module
2013
+ * @param {string[]} rootExports the root's icon exports
2014
+ * @param {{packageDir: string, pkg: Record<string, any>}} where
2015
+ * @returns {Map<string, {source: string, from: string}>}
2016
+ */
2017
+ export function packageRootMoves(origins, root, rootExports, where) {
2018
+ /** @type {Map<string, {source: string, from: string}>} */
2019
+ const moves = new Map();
2020
+ if (iconModulePackage(root.module) !== root.module) return moves;
2021
+ if (root.module.startsWith('.')) return moves;
2022
+ const subpaths = [...origins].filter(
2023
+ ([, origin]) =>
2024
+ !origin.module.startsWith('.') &&
2025
+ origin.module !== root.module &&
2026
+ iconModulePackage(origin.module) === root.module,
2027
+ );
2028
+ if (subpaths.length === 0) return moves;
2029
+ /** @param {{file: string, name: string}} origin */
2030
+ const keyOf = origin => `${origin.file}\0${origin.name}`;
2031
+ /** @type {Map<string, string>} */
2032
+ const byOrigin = new Map();
2033
+ for (const name of rootExports) {
2034
+ const origin = moduleExportOrigin(root.file, name);
2035
+ if (origin && !byOrigin.has(keyOf(origin))) {
2036
+ byOrigin.set(keyOf(origin), name);
2037
+ }
2038
+ }
2039
+ const names = new Set(rootExports);
2040
+ const self = {
2041
+ name: typeof where.pkg.name === 'string' ? where.pkg.name : '',
2042
+ dir: where.packageDir,
2043
+ };
2044
+ for (const [name, origin] of subpaths) {
2045
+ const file = resolveIconModule(origin.module, where.packageDir, self);
2046
+ const resolved = file ? moduleExportOrigin(file, origin.source) : null;
2047
+ // A name match counts only when the subpath export cannot be resolved.
2048
+ // A resolved export is the same icon only when it reads the same file.
2049
+ const source = resolved
2050
+ ? byOrigin.get(keyOf(resolved))
2051
+ : names.has(origin.source)
2052
+ ? origin.source
2053
+ : undefined;
2054
+ if (source) moves.set(name, {source, from: origin.module});
2055
+ }
2056
+ return moves;
2057
+ }
2058
+
1379
2059
  /**
1380
2060
  * Write the set's generated module and its declaration file
1381
2061
  * ({@link generatedModuleText}). Returns whether either changed, and a
@@ -1562,12 +2242,30 @@ export function entryWiringNote(packageDir, pkg, generated, options = {}) {
1562
2242
  inside(typesFile) &&
1563
2243
  fs.existsSync(typesFile) &&
1564
2244
  !isBuiltOrCommonJs(packageDir, typesFile) &&
1565
- !fs.readFileSync(typesFile, 'utf-8').includes(lineFor(typesFile))
2245
+ !hasStatement(typesFile, lineFor(typesFile))
1566
2246
  ? ` and \`${lineFor(typesFile)}\` to ${rel(typesFile)}`
1567
2247
  : '';
1568
2248
  return `Add \`${lineFor(entry)}\` to ${rel(entry)}${alsoTypes}, so the icons import from ${module}.`;
1569
2249
  }
1570
2250
 
2251
+ /**
2252
+ * Whether a file has a statement, however a formatter left it
2253
+ * ({@link generatedStatements}); a file that does not parse is searched for
2254
+ * the text as written.
2255
+ * @param {string} file
2256
+ * @param {string} statement
2257
+ */
2258
+ function hasStatement(file, statement) {
2259
+ const text = fs.readFileSync(file, 'utf-8');
2260
+ try {
2261
+ return generatedStatements(text, file).includes(
2262
+ normalizedStatement(statement),
2263
+ );
2264
+ } catch {
2265
+ return text.includes(statement);
2266
+ }
2267
+ }
2268
+
1571
2269
  /**
1572
2270
  * Whether the set's own module exports `name`, read without running it, and
1573
2271
  * the line its entry needs when it does not ({@link entryWiringNote}).