@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
@@ -0,0 +1,903 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file swizzle.copy module graph — decides, for each module a component
5
+ * reaches, whether the copy imports it from the owner package's public
6
+ * exports or carries it in the output.
7
+ *
8
+ * @input the owner package's source root and `exports` map, the component folder
9
+ * @output the files the copy holds, each with its rewritten source
10
+ * @position api/swizzle adapter helper; the copy leaf reaches it through _adapter.mjs
11
+ */
12
+
13
+ import * as fs from 'node:fs';
14
+ import * as path from 'node:path';
15
+ import {isBuiltin} from 'node:module';
16
+ import {packageOf} from '../../foundation/render/served-packages.mjs';
17
+ import {resolveInstalledPackageDir} from '../../foundation/integrations/installed-package.mjs';
18
+ import {parse} from '@babel/parser';
19
+ import {
20
+ inspectPackageExport,
21
+ sourceExportTarget,
22
+ } from '../../foundation/discovery/package-exports.mjs';
23
+ import {
24
+ moduleExportOrigins,
25
+ resolveLocalModule,
26
+ } from '../../foundation/discovery/module-exports.mjs';
27
+ import {
28
+ allTargets,
29
+ isRecord,
30
+ subpathDeclaration,
31
+ } from '../../foundation/integrations/exports-subpaths.mjs';
32
+
33
+ /** The extensions an extensionless import may name, in resolution order. */
34
+ const CODE_FILE = /\.[cm]?[jt]sx?$/;
35
+ const DECLARATION_FILE = /\.d\.[cm]?ts$/;
36
+ const STYLEX_FILE = /\.stylex\.[cm]?[jt]sx?$/;
37
+
38
+ /** @param {string} file */
39
+ const toPosix = file => file.split(path.sep).join('/');
40
+
41
+ /**
42
+ * The file an import names, or null when no file is there.
43
+ * @param {string} fromFile absolute path of the importing file
44
+ * @param {string} specifier a relative specifier
45
+ * @param {Map<string, string|null>} cache resolutions already made in this copy
46
+ * @returns {string|null}
47
+ */
48
+ function resolveRelative(fromFile, specifier, cache) {
49
+ const base = path.resolve(path.dirname(fromFile), specifier);
50
+ const known = cache.get(base);
51
+ if (known !== undefined) return known;
52
+ const found = resolveLocalModule(specifier, fromFile);
53
+ cache.set(base, found);
54
+ return found;
55
+ }
56
+
57
+ /**
58
+ * @typedef {object} ImportSpecifier
59
+ * @property {string} imported the exported name (`default` for a default import)
60
+ * @property {string} local
61
+ * @property {boolean} typeOnly
62
+ *
63
+ * @typedef {object} ModuleReference
64
+ * @property {'named'|'namespace'|'sideEffect'|'dynamic'|'reexportAll'|'reexportNamed'} kind
65
+ * @property {string} source the specifier as written
66
+ * @property {number} start statement (or, for `import()`, string literal) start
67
+ * @property {number} end
68
+ * @property {boolean} typeOnly the whole statement is `import type` / `export type`
69
+ * @property {ImportSpecifier[]} specifiers
70
+ * @property {string} [namespace] the local name of `* as X`
71
+ *
72
+ * @typedef {object} ParsedModule
73
+ * @property {string} code
74
+ * @property {ModuleReference[]} references
75
+ * @property {Set<string>} declares names the module declares and exports
76
+
77
+ */
78
+
79
+ /**
80
+ * A module's source and every module reference in it: static imports and
81
+ * re-exports, `import()` calls, and `import('…')` types.
82
+ * @param {string} file
83
+ * @returns {ParsedModule}
84
+ */
85
+ function parseModule(file) {
86
+ const code = fs.readFileSync(file, 'utf-8');
87
+ /** @type {ParsedModule} */
88
+ const parsed = {code, references: [], declares: new Set()};
89
+ if (!CODE_FILE.test(file)) return parsed;
90
+ const ast = parse(code, {
91
+ sourceType: 'module',
92
+ errorRecovery: true,
93
+ plugins: /\.[cm]?tsx?$/.test(file) ? ['typescript', 'jsx'] : ['jsx'],
94
+ });
95
+ const {references} = parsed;
96
+ // Babel's node types mark positions optional; a parsed file always has them.
97
+ for (const node of /** @type {any[]} */ (ast.program.body)) {
98
+ for (const d of node.declaration?.declarations ?? [node.declaration]) {
99
+ if (node.type === 'ExportNamedDeclaration' && d?.id?.name)
100
+ parsed.declares.add(d.id.name);
101
+ }
102
+ if (node.type === 'ImportDeclaration') {
103
+ const typeOnly = node.importKind === 'type';
104
+ const base = {
105
+ source: node.source.value,
106
+ start: node.start,
107
+ end: node.end,
108
+ typeOnly,
109
+ };
110
+ const namespace = node.specifiers.find(
111
+ (/** @type {any} */ s) => s.type === 'ImportNamespaceSpecifier',
112
+ );
113
+ const named = node.specifiers.filter(
114
+ (/** @type {any} */ s) => s.type !== 'ImportNamespaceSpecifier',
115
+ );
116
+ if (node.specifiers.length === 0) {
117
+ references.push({...base, kind: 'sideEffect', specifiers: []});
118
+ } else if (namespace && named.length === 0) {
119
+ references.push({
120
+ ...base,
121
+ kind: 'namespace',
122
+ specifiers: [],
123
+ namespace: namespace.local.name,
124
+ });
125
+ } else if (!namespace) {
126
+ references.push({
127
+ ...base,
128
+ kind: 'named',
129
+ specifiers: named.map((/** @type {any} */ s) => ({
130
+ imported:
131
+ s.type === 'ImportDefaultSpecifier'
132
+ ? 'default'
133
+ : s.imported.type === 'StringLiteral'
134
+ ? s.imported.value
135
+ : s.imported.name,
136
+ local: s.local.name,
137
+ typeOnly: typeOnly || s.importKind === 'type',
138
+ })),
139
+ });
140
+ } else {
141
+ // `import X, * as Y from` names the whole module.
142
+ references.push({...base, kind: 'namespace', specifiers: []});
143
+ }
144
+ } else if (node.type === 'ExportAllDeclaration') {
145
+ references.push({
146
+ kind: 'reexportAll',
147
+ source: node.source.value,
148
+ start: node.start,
149
+ end: node.end,
150
+ typeOnly: node.exportKind === 'type',
151
+ specifiers: [],
152
+ });
153
+ } else if (node.type === 'ExportNamedDeclaration' && node.source) {
154
+ const typeOnly = node.exportKind === 'type';
155
+ references.push({
156
+ kind: 'reexportNamed',
157
+ source: node.source.value,
158
+ start: node.start,
159
+ end: node.end,
160
+ typeOnly,
161
+ specifiers: node.specifiers.map((/** @type {any} */ s) => ({
162
+ imported: s.type === 'ExportNamespaceSpecifier' ? '*' : s.local.name,
163
+ local:
164
+ s.exported.type === 'StringLiteral'
165
+ ? s.exported.value
166
+ : s.exported.name,
167
+ typeOnly: typeOnly || s.exportKind === 'type',
168
+ })),
169
+ });
170
+ }
171
+ }
172
+ visitDynamicReferences(ast.program, literal => {
173
+ references.push({
174
+ kind: 'dynamic',
175
+ source: literal.value,
176
+ start: literal.start,
177
+ end: literal.end,
178
+ typeOnly: false,
179
+ specifiers: [],
180
+ });
181
+ });
182
+ return parsed;
183
+ }
184
+
185
+ /**
186
+ * Call `onLiteral` with the string literal of every `import('…')` call and
187
+ * `import('…')` type under a node.
188
+ * @param {any} node
189
+ * @param {(literal: {value: string, start: number, end: number}) => void} onLiteral
190
+ */
191
+ function visitDynamicReferences(node, onLiteral) {
192
+ if (node == null || typeof node !== 'object') return;
193
+ if (Array.isArray(node)) {
194
+ for (const child of node) visitDynamicReferences(child, onLiteral);
195
+ return;
196
+ }
197
+ if (
198
+ node.type === 'CallExpression' &&
199
+ node.callee?.type === 'Import' &&
200
+ node.arguments[0]?.type === 'StringLiteral'
201
+ ) {
202
+ onLiteral(node.arguments[0]);
203
+ } else if (
204
+ node.type === 'ImportExpression' &&
205
+ node.source?.type === 'StringLiteral'
206
+ ) {
207
+ onLiteral(node.source);
208
+ } else if (node.type === 'TSImportType') {
209
+ const literal =
210
+ node.argument?.type === 'TSLiteralType'
211
+ ? node.argument.literal
212
+ : node.argument;
213
+ if (literal?.type === 'StringLiteral') onLiteral(literal);
214
+ }
215
+ for (const key of Object.keys(node)) {
216
+ if (
217
+ key === 'loc' ||
218
+ key === 'leadingComments' ||
219
+ key === 'trailingComments' ||
220
+ key === 'innerComments'
221
+ )
222
+ continue;
223
+ const value = node[key];
224
+ if (value && typeof value === 'object')
225
+ visitDynamicReferences(value, onLiteral);
226
+ }
227
+ }
228
+
229
+ /**
230
+ * @typedef {'value' | 'type'} ExportKind `value` reads runtime exports only;
231
+ * `type` reads type-only exports too
232
+ *
233
+ * @typedef {(file: string, kind: ExportKind) => Map<string, {file: string, name: string}>} OriginsOf
234
+ * every name a module exports, with where it is declared
235
+ *
236
+ * @typedef {Map<string, Array<{subpath: string, name: string}>>} ExportersByOrigin
237
+ * `file#name` of a declaration -> the subpaths that export it, and as what
238
+ *
239
+ * @typedef {object} PublicSurface
240
+ * @property {Record<ExportKind, ExportersByOrigin>} byOrigin the subpaths
241
+ * that export each declaration as a value, and as a value or a type
242
+ * @property {Map<string, string>} byFile source file -> the subpath that
243
+ * exports exactly that file
244
+ * @property {Record<string, unknown>|undefined} exportsField
245
+ */
246
+
247
+ /**
248
+ * Every public subpath of a package with the source file under `root` that
249
+ * the shared export readers give it. `./internal/*` is never public.
250
+ * @param {{exports?: unknown}} pkg
251
+ * @param {string} packageDir
252
+ * @param {string} root
253
+ * @returns {Array<[string, string]>}
254
+ */
255
+ function exportedSourceFiles(pkg, packageDir, root) {
256
+ const exportsField = pkg.exports;
257
+ const subpathMap =
258
+ isRecord(exportsField) &&
259
+ Object.keys(exportsField).some(key => key.startsWith('.'));
260
+ const candidates = new Set(['.']);
261
+ if (subpathMap) {
262
+ for (const [key, value] of Object.entries(exportsField)) {
263
+ if (!key.includes('*')) {
264
+ candidates.add(key);
265
+ continue;
266
+ }
267
+ for (const subpath of wildcardSubpaths(packageDir, root, key, value)) {
268
+ candidates.add(subpath);
269
+ }
270
+ }
271
+ }
272
+ /** @type {Array<[string, string]>} */
273
+ const found = [];
274
+ for (const subpath of candidates) {
275
+ if (/^\.\/internal(\/|$)/.test(subpath)) continue;
276
+ const inspected = inspectPackageExport(pkg, packageDir, subpath);
277
+ if (!inspected.exported) continue;
278
+ const file =
279
+ sourceExportTarget(pkg, packageDir, subpath) ?? inspected.target;
280
+ if (
281
+ file &&
282
+ file.startsWith(root + path.sep) &&
283
+ !DECLARATION_FILE.test(file)
284
+ ) {
285
+ found.push([subpath, file]);
286
+ }
287
+ }
288
+ return found;
289
+ }
290
+
291
+ /**
292
+ * The subpaths a `*` key names: one per file its target patterns match.
293
+ * @param {string} packageDir
294
+ * @param {string} root
295
+ * @param {string} key
296
+ * @param {unknown} value
297
+ * @returns {string[]}
298
+ */
299
+ function wildcardSubpaths(packageDir, root, key, value) {
300
+ /** @type {string[]} */
301
+ const subpaths = [];
302
+ for (const pattern of allTargets(value)) {
303
+ if (!pattern.startsWith('./') || !pattern.includes('*')) continue;
304
+ const fixed = pattern.slice(2, pattern.indexOf('*'));
305
+ const base = path.resolve(
306
+ packageDir,
307
+ fixed.slice(0, fixed.lastIndexOf('/') + 1),
308
+ );
309
+ if (!base.startsWith(root) || !fs.existsSync(base)) continue;
310
+ for (const entry of fs.readdirSync(base, {
311
+ recursive: true,
312
+ withFileTypes: true,
313
+ })) {
314
+ if (!entry.isFile()) continue;
315
+ const file = path.join(entry.parentPath, entry.name);
316
+ if (path.relative(base, file).split(path.sep).includes('node_modules'))
317
+ continue;
318
+ const rel = toPosix(path.relative(packageDir, file));
319
+ if (!rel.startsWith(fixed)) continue;
320
+ const rest = rel.slice(fixed.length);
321
+ for (let end = 1; end <= rest.length; end++) {
322
+ const star = rest.slice(0, end);
323
+ if (pattern.slice(2).replaceAll('*', star) === rel) {
324
+ subpaths.push(key.replace('*', star));
325
+ break;
326
+ }
327
+ }
328
+ }
329
+ }
330
+ return subpaths;
331
+ }
332
+
333
+ /**
334
+ * The owner package's public surface, read from its `exports` map: each
335
+ * subpath with a `source` condition under the source root, and the
336
+ * declarations it exports. `./internal/*` subpaths are not public.
337
+ * @param {string} packageDir
338
+ * @param {string} srcRoot
339
+ * @param {OriginsOf} originsOf
340
+ * @returns {PublicSurface}
341
+ */
342
+ function publicSurfaceOf(packageDir, srcRoot, originsOf) {
343
+ /** @type {{exports?: unknown}} */
344
+ let pkg;
345
+ try {
346
+ pkg = JSON.parse(
347
+ fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),
348
+ );
349
+ } catch {
350
+ pkg = {};
351
+ }
352
+ const exportsField =
353
+ pkg.exports && typeof pkg.exports === 'object'
354
+ ? /** @type {Record<string, unknown>} */ (pkg.exports)
355
+ : undefined;
356
+ /** @type {PublicSurface['byOrigin']} */
357
+ const byOrigin = {value: new Map(), type: new Map()};
358
+ /** @type {PublicSurface['byFile']} */
359
+ const byFile = new Map();
360
+ for (const [subpath, sourceFile] of exportedSourceFiles(
361
+ pkg,
362
+ packageDir,
363
+ srcRoot,
364
+ )) {
365
+ byFile.set(sourceFile, subpath);
366
+ if (!CODE_FILE.test(sourceFile)) continue;
367
+ for (const kind of /** @type {const} */ (['value', 'type'])) {
368
+ for (const [name, origin] of originsOf(sourceFile, kind)) {
369
+ const key = `${origin.file}#${origin.name}`;
370
+ const list = byOrigin[kind].get(key) ?? [];
371
+ list.push({subpath, name});
372
+ byOrigin[kind].set(key, list);
373
+ }
374
+ }
375
+ }
376
+ return {byOrigin, byFile, exportsField};
377
+ }
378
+
379
+ /**
380
+ * A specifier that is either fixed (a public subpath) or computed from where
381
+ * two copied files land.
382
+ * @typedef {string | {from: string, to: string}} SpecifierChoice
383
+ *
384
+ * @typedef {object} PlannedEdit
385
+ * @property {number} start
386
+ * @property {number} end
387
+ * @property {(specifierOf: (choice: SpecifierChoice) => string) => string} render
388
+ *
389
+ * @typedef {object} CopyPlan
390
+ * @property {Map<string, {code: string, edits: PlannedEdit[]}>} files every
391
+ * file the copy holds (absolute source path), with the edits its imports need
392
+ * @property {Map<string, Set<string>>} dependsOn file -> carried files its
393
+ * computed specifiers point at
394
+ * @property {Map<string, string>} otherPackages the source root of each other
395
+ * Astryx package the copy carries modules from, with its package name
396
+ * @property {Record<string, string>} dependencies each npm package the copied
397
+ * files import, other than the owner package and Node's built-in modules,
398
+ * with the range the owner package declares
399
+ */
400
+
401
+ /**
402
+ * Follow a component's module graph from its entry files and decide what the
403
+ * copy holds. A module inside the component folder is copied. A module
404
+ * outside it is reached through the owner package's public exports when every
405
+ * name taken from it is public there; otherwise the module that defines the
406
+ * name is copied, and imported by relative path. Tests, stories and docs are
407
+ * never reached, so they are never copied.
408
+ *
409
+ * @param {object} options
410
+ * @param {string} options.packageDir the owner package root
411
+ * @param {string} options.srcRoot its source root
412
+ * @param {string} options.componentDir
413
+ * @param {string} options.ownerPackage
414
+ * @param {string[]} options.entries absolute entry files of the component
415
+ * @returns {CopyPlan}
416
+ */
417
+ export function planCopy({
418
+ packageDir,
419
+ srcRoot,
420
+ componentDir,
421
+ ownerPackage,
422
+ entries,
423
+ }) {
424
+ // Every read is cached for this copy only, so a later copy sees the
425
+ // package as it is then.
426
+ const exportMemos = {value: new Map(), type: new Map()};
427
+ /** @type {OriginsOf} */
428
+ const originsOf = (file, kind) =>
429
+ moduleExportOrigins(file, {
430
+ types: kind === 'type',
431
+ memo: exportMemos[kind],
432
+ });
433
+ /** @param {string} file @param {string} name */
434
+ const originOf = (file, name) => originsOf(file, 'type').get(name) ?? null;
435
+ /**
436
+ * The name a module exports one of its own bindings under, or null.
437
+ * @param {{file: string, name: string}} origin
438
+ */
439
+ const exportNameOf = origin => {
440
+ for (const [name, found] of originsOf(origin.file, 'type')) {
441
+ if (found.file === origin.file && found.name === origin.name) return name;
442
+ }
443
+ return null;
444
+ };
445
+ /** @type {Map<string, string|null>} */
446
+ const resolutions = new Map();
447
+ /** @type {CopyPlan['files']} */
448
+ const files = new Map();
449
+ /** @type {CopyPlan['dependsOn']} */
450
+ const dependsOn = new Map();
451
+ /** @type {Set<string>} */
452
+ const packages = new Set();
453
+ const queue = [...entries];
454
+ const queued = new Set(queue);
455
+ /** @param {string} file */
456
+ const enqueue = file => {
457
+ if (!queued.has(file)) {
458
+ queued.add(file);
459
+ queue.push(file);
460
+ }
461
+ };
462
+ /** @param {string} file */
463
+ const inComponent = file => file.startsWith(componentDir + path.sep);
464
+
465
+ /**
466
+ * @typedef {ReturnType<typeof makeContext>} PackageContext
467
+ */
468
+
469
+ /**
470
+ * How references inside one package's source are planned: its public
471
+ * surface and the subpaths a name or module is imported from.
472
+ * @param {{packageDir: string, srcRoot: string, ownerPackage: string}} pkg
473
+ */
474
+ function makeContext({packageDir, srcRoot, ownerPackage}) {
475
+ const surface = publicSurfaceOf(packageDir, srcRoot, originsOf);
476
+ /** @param {string} file */
477
+ const inSource = file => file.startsWith(srcRoot + path.sep);
478
+ /**
479
+ * The subpaths that export a module's export: as a value when the import
480
+ * takes a value, since a type-only export is erased at runtime.
481
+ * @param {string} file
482
+ * @param {string} name
483
+ * @param {boolean} typeOnly
484
+ */
485
+ const exportersOf = (file, name, typeOnly) => {
486
+ const origin = originOf(file, name);
487
+ if (!origin) return [];
488
+ const kind = typeOnly ? 'type' : 'value';
489
+ return surface.byOrigin[kind].get(`${origin.file}#${origin.name}`) ?? [];
490
+ };
491
+ /**
492
+ * The subpath that exports every name a module exports, with the same
493
+ * definition. An exactly exported file is its own subpath.
494
+ * @param {string} file
495
+ * @returns {string|null}
496
+ */
497
+ const subpathCoveringModule = file => {
498
+ const exact = surface.byFile.get(file);
499
+ if (exact) return exact;
500
+ const names = [...originsOf(file, 'type').keys()];
501
+ if (names.length === 0) return null;
502
+ const values = originsOf(file, 'value');
503
+ const options = names.map(name =>
504
+ exportersOf(file, name, !values.has(name))
505
+ .filter(o => o.name === name)
506
+ .map(o => o.subpath),
507
+ );
508
+ const common = options.reduce((acc, list) =>
509
+ acc.filter(s => list.includes(s)),
510
+ );
511
+ return STYLEX_FILE.test(file) ? null : pickSubpath(common, file);
512
+ };
513
+
514
+ /**
515
+ * The public subpath to take a name from. A StyleX module is imported by
516
+ * its own exported path, because the StyleX compiler resolves styles and
517
+ * variables from the real module; when that path is not exported, there is
518
+ * no public import.
519
+ * @param {string[]} subpaths subpaths that export the name
520
+ * @param {string} target the module the import names
521
+ * @param {string} [originFile] the module that defines the name
522
+ * @returns {string|null}
523
+ */
524
+ const choosePublic = (subpaths, target, originFile) => {
525
+ const exact = originFile ? surface.byFile.get(originFile) : undefined;
526
+ if (exact && subpaths.includes(exact)) return exact;
527
+ if (
528
+ STYLEX_FILE.test(target) ||
529
+ (originFile && STYLEX_FILE.test(originFile))
530
+ )
531
+ return null;
532
+ return pickSubpath(subpaths, target);
533
+ };
534
+
535
+ /**
536
+ * Prefer the subpath of the module's top folder, then the package root.
537
+ * @param {string[]} subpaths
538
+ * @param {string} file
539
+ * @returns {string|null}
540
+ */
541
+ const pickSubpath = (subpaths, file) => {
542
+ if (subpaths.length === 0) return null;
543
+ const top = `./${toPosix(path.relative(srcRoot, file)).split('/')[0]}`;
544
+ return (
545
+ subpaths.find(s => s === top) ??
546
+ subpaths.find(s => s === '.') ??
547
+ [...subpaths].sort((a, b) => a.length - b.length)[0]
548
+ );
549
+ };
550
+
551
+ /** @param {string} subpath */
552
+ const publicSpecifier = subpath =>
553
+ subpath === '.' ? ownerPackage : `${ownerPackage}/${subpath.slice(2)}`;
554
+
555
+ return {
556
+ packageDir,
557
+ srcRoot,
558
+ ownerPackage,
559
+ surface,
560
+ inSource,
561
+ exportersOf,
562
+ subpathCoveringModule,
563
+ choosePublic,
564
+ publicSpecifier,
565
+ };
566
+ }
567
+ const owner = makeContext({packageDir, srcRoot, ownerPackage});
568
+ /** @type {Map<string, PackageContext>} other packages' contexts, by source root */
569
+ const others = new Map();
570
+ /** @param {string} file */
571
+ const contextOf = file => {
572
+ if (file.startsWith(srcRoot + path.sep)) return owner;
573
+ for (const [root, context] of others) {
574
+ if (file.startsWith(root + path.sep)) return context;
575
+ }
576
+ return owner;
577
+ };
578
+
579
+ /**
580
+ * The source module a bare import of another Astryx package's
581
+ * `./internal/*` path names, or null. That module is carried, and its
582
+ * package gets a context of its own.
583
+ * @param {string} file
584
+ * @param {string} specifier
585
+ * @returns {string|null}
586
+ */
587
+ const internalModuleOf = (file, specifier) => {
588
+ const name = packageOf(specifier);
589
+ const sub = specifier.slice(name.length + 1);
590
+ if (!name.startsWith('@astryxdesign/') || name === ownerPackage)
591
+ return null;
592
+ if (!/^internal(\/|$)/.test(sub)) return null;
593
+ const installed = resolveInstalledPackageDir(name, path.dirname(file));
594
+ if (!installed) return null;
595
+ const dir = fs.realpathSync(installed.packageDir);
596
+ /** @type {{exports?: unknown}} */
597
+ let pkg;
598
+ try {
599
+ pkg = JSON.parse(
600
+ fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'),
601
+ );
602
+ } catch {
603
+ return null;
604
+ }
605
+ const target = sourceExportTarget(pkg, dir, `./${sub}`);
606
+ // A StyleX module's identity is its path, so the copy keeps importing it
607
+ // by its exported path and agrees with the package on it.
608
+ if (!target || STYLEX_FILE.test(target)) return null;
609
+ const src = path.join(dir, 'src');
610
+ const root = target.startsWith(src + path.sep) ? src : dir;
611
+ if (!others.has(root)) {
612
+ others.set(
613
+ root,
614
+ makeContext({packageDir: dir, srcRoot: root, ownerPackage: name}),
615
+ );
616
+ }
617
+ return target;
618
+ };
619
+
620
+ /**
621
+ * Carry a module in the copy.
622
+ * @param {string} from
623
+ * @param {string} to
624
+ * @returns {SpecifierChoice}
625
+ */
626
+ const carry = (from, to) => {
627
+ enqueue(to);
628
+ const deps = dependsOn.get(from) ?? new Set();
629
+ deps.add(to);
630
+ dependsOn.set(from, deps);
631
+ return {from, to};
632
+ };
633
+
634
+ while (queue.length > 0) {
635
+ const file = /** @type {string} */ (queue.shift());
636
+ const parsed = parseModule(file);
637
+ /** @type {PlannedEdit[]} */
638
+ const edits = [];
639
+ files.set(file, {code: parsed.code, edits});
640
+ if (!CODE_FILE.test(file)) continue;
641
+ const context = contextOf(file);
642
+ for (const ref of parsed.references) {
643
+ if (!ref.source.startsWith('.')) {
644
+ const internal = internalModuleOf(file, ref.source);
645
+ if (internal) {
646
+ edits.push(sourceEdit(parsed.code, ref, carry(file, internal)));
647
+ continue;
648
+ }
649
+ const builtin = ref.source.startsWith('node:') || isBuiltin(ref.source);
650
+ const name = packageOf(ref.source);
651
+ if (!builtin && name !== ownerPackage) packages.add(name);
652
+ continue;
653
+ }
654
+ const target = resolveRelative(file, ref.source, resolutions);
655
+ // A dangling import is left for the build to report.
656
+ if (!target) continue;
657
+ if (inComponent(target)) {
658
+ // Files of the component keep their relative imports of each other.
659
+ if (inComponent(file)) enqueue(target);
660
+ else edits.push(sourceEdit(parsed.code, ref, carry(file, target)));
661
+ continue;
662
+ }
663
+ if (!CODE_FILE.test(target) || !context.inSource(target)) {
664
+ // An asset, such as `../../locales/en.json` or a stylesheet, that the
665
+ // package exports by its own path is imported from the package.
666
+ const subpath = `./${toPosix(path.relative(context.packageDir, target))}`;
667
+ if (
668
+ subpathDeclaration(context.surface.exportsField, subpath).state ===
669
+ 'declared'
670
+ ) {
671
+ if (context !== owner) packages.add(context.ownerPackage);
672
+ edits.push(
673
+ sourceEdit(
674
+ parsed.code,
675
+ ref,
676
+ `${context.ownerPackage}/${subpath.slice(2)}`,
677
+ ),
678
+ );
679
+ continue;
680
+ }
681
+ // An unexported asset in the source is carried; one outside it is
682
+ // left for the build to report.
683
+ if (!context.inSource(target)) continue;
684
+ edits.push(sourceEdit(parsed.code, ref, carry(file, target)));
685
+ continue;
686
+ }
687
+ edits.push(planReference(context, file, parsed.code, ref, target));
688
+ }
689
+ }
690
+ return {
691
+ files,
692
+ dependsOn,
693
+ dependencies: declaredRanges(packageDir, packages),
694
+ otherPackages: new Map(
695
+ [...others].map(([root, c]) => [root, c.ownerPackage]),
696
+ ),
697
+ };
698
+
699
+ /**
700
+ * Decide one reference that leaves the component folder.
701
+ * @param {PackageContext} context the package the importing file is in
702
+ * @param {string} file
703
+ * @param {string} code
704
+ * @param {ModuleReference} ref
705
+ * @param {string} target
706
+ * @returns {PlannedEdit}
707
+ */
708
+ function planReference(context, file, code, ref, target) {
709
+ // A carried module of another package imports that package's public names
710
+ // from it, so the copy depends on it.
711
+ if (context !== owner) packages.add(context.ownerPackage);
712
+ if (ref.kind !== 'named' && ref.kind !== 'reexportNamed') {
713
+ const covering = context.subpathCoveringModule(target);
714
+ return sourceEdit(
715
+ code,
716
+ ref,
717
+ covering ? context.publicSpecifier(covering) : carry(file, target),
718
+ );
719
+ }
720
+ /** @type {Array<{choice: SpecifierChoice, specs: ImportSpecifier[]}>} */
721
+ const groups = [];
722
+ /** @param {SpecifierChoice} choice @param {ImportSpecifier} spec */
723
+ const add = (choice, spec) => {
724
+ const same = groups.find(g =>
725
+ typeof choice === 'string'
726
+ ? g.choice === choice
727
+ : typeof g.choice !== 'string' && g.choice.to === choice.to,
728
+ );
729
+ if (same) same.specs.push(spec);
730
+ else groups.push({choice, specs: [spec]});
731
+ };
732
+ for (const spec of ref.specifiers) {
733
+ if (spec.imported === '*') {
734
+ const covering = context.subpathCoveringModule(target);
735
+ add(
736
+ covering ? context.publicSpecifier(covering) : carry(file, target),
737
+ spec,
738
+ );
739
+ continue;
740
+ }
741
+ const origin = originOf(target, spec.imported);
742
+ const publicOptions = context.exportersOf(
743
+ target,
744
+ spec.imported,
745
+ spec.typeOnly,
746
+ );
747
+ const chosen = context.choosePublic(
748
+ publicOptions.map(o => o.subpath),
749
+ target,
750
+ origin?.file,
751
+ );
752
+ if (chosen) {
753
+ const exported = /** @type {{name: string}} */ (
754
+ publicOptions.find(o => o.subpath === chosen)
755
+ ).name;
756
+ add(context.publicSpecifier(chosen), {...spec, imported: exported});
757
+ } else {
758
+ // Take the name from the module that defines it, so the copy carries
759
+ // that module and not a whole barrel. An origin names a binding, so
760
+ // the import uses the name that module exports it under.
761
+ // A module that declares the name itself, even as an alias, is carried.
762
+ const definingExport =
763
+ origin &&
764
+ origin.file !== target &&
765
+ context.inSource(origin.file) &&
766
+ !parseModule(target).declares.has(spec.imported)
767
+ ? exportNameOf(origin)
768
+ : null;
769
+ if (origin && definingExport != null) {
770
+ add(carry(file, origin.file), {...spec, imported: definingExport});
771
+ } else {
772
+ add(carry(file, target), spec);
773
+ }
774
+ }
775
+ }
776
+ // One source and the same names: keep the statement as written and swap
777
+ // only its specifier.
778
+ const unchangedNames =
779
+ groups.length === 1 &&
780
+ groups[0].specs.every(
781
+ (spec, i) => spec.imported === ref.specifiers[i].imported,
782
+ );
783
+ if (unchangedNames) return sourceEdit(code, ref, groups[0].choice);
784
+ return {
785
+ start: ref.start,
786
+ end: ref.end,
787
+ render: specifierOf => renderStatements(ref, groups, specifierOf),
788
+ };
789
+ }
790
+ }
791
+
792
+ /**
793
+ * The version range the owner package declares for each npm package the copy
794
+ * imports, by name; `*` for one it does not declare.
795
+ * @param {string} packageDir
796
+ * @param {Iterable<string>} names
797
+ * @returns {Record<string, string>}
798
+ */
799
+ function declaredRanges(packageDir, names) {
800
+ /** @type {Record<string, Record<string, string>>} */
801
+ let manifest = {};
802
+ try {
803
+ manifest = JSON.parse(
804
+ fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),
805
+ );
806
+ } catch {
807
+ // An unreadable manifest declares nothing.
808
+ }
809
+ /** @type {Record<string, string>} */
810
+ const ranges = {};
811
+ for (const name of [...names].sort()) {
812
+ ranges[name] =
813
+ manifest.dependencies?.[name] ??
814
+ manifest.optionalDependencies?.[name] ??
815
+ manifest.peerDependencies?.[name] ??
816
+ '*';
817
+ }
818
+ return ranges;
819
+ }
820
+
821
+ /**
822
+ * An edit that replaces only the string literal of a reference.
823
+ * @param {string} code
824
+ * @param {ModuleReference} ref
825
+ * @param {SpecifierChoice} choice
826
+ * @returns {PlannedEdit}
827
+ */
828
+ function sourceEdit(code, ref, choice) {
829
+ const slice = code.slice(ref.start, ref.end);
830
+ const quoted = new RegExp(
831
+ `(['"])${ref.source.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\1`,
832
+ );
833
+ const m = slice.match(quoted);
834
+ const at = m && m.index != null ? ref.start + m.index : ref.start;
835
+ const length = m ? m[0].length : 0;
836
+ const quote = m ? m[1] : "'";
837
+ return {
838
+ start: at,
839
+ end: at + length,
840
+ render: specifierOf =>
841
+ m ? `${quote}${specifierOf(choice)}${quote}` : slice,
842
+ };
843
+ }
844
+
845
+ /**
846
+ * The statements that replace one named import or re-export, one per source.
847
+ * @param {ModuleReference} ref
848
+ * @param {Array<{choice: SpecifierChoice, specs: ImportSpecifier[]}>} groups
849
+ * @param {(choice: SpecifierChoice) => string} specifierOf
850
+ */
851
+ function renderStatements(ref, groups, specifierOf) {
852
+ const keyword = ref.kind === 'reexportNamed' ? 'export' : 'import';
853
+ const statements = [];
854
+ for (const {choice, specs} of groups) {
855
+ const specifier = specifierOf(choice);
856
+ const star = specs.find(s => s.imported === '*');
857
+ if (star) statements.push(`export * as ${star.local} from '${specifier}';`);
858
+ const named = specs.filter(s => s.imported !== '*');
859
+ if (named.length === 0) continue;
860
+ const allType = ref.typeOnly || named.every(s => s.typeOnly);
861
+ const parts = named.map(s => {
862
+ const prefix = !allType && s.typeOnly ? 'type ' : '';
863
+ return s.imported === s.local
864
+ ? `${prefix}${s.local}`
865
+ : `${prefix}${s.imported} as ${s.local}`;
866
+ });
867
+ const head = `${keyword} ${allType ? 'type ' : ''}`;
868
+ const oneLine = `${head}{${parts.join(', ')}} from '${specifier}';`;
869
+ statements.push(
870
+ oneLine.length <= 80
871
+ ? oneLine
872
+ : `${head}{\n${parts.map(p => ` ${p},`).join('\n')}\n} from '${specifier}';`,
873
+ );
874
+ }
875
+ return statements.join('\n');
876
+ }
877
+
878
+ /**
879
+ * The source of a planned file with its edits applied.
880
+ * @param {{code: string, edits: PlannedEdit[]}} planned
881
+ * @param {(choice: SpecifierChoice) => string} specifierOf
882
+ */
883
+ export function renderFile(planned, specifierOf) {
884
+ let out = planned.code;
885
+ for (const edit of [...planned.edits].sort((a, b) => b.start - a.start)) {
886
+ out =
887
+ out.slice(0, edit.start) + edit.render(specifierOf) + out.slice(edit.end);
888
+ }
889
+ return out;
890
+ }
891
+
892
+ /**
893
+ * The relative specifier from one written file to another.
894
+ * @param {string} fromDest
895
+ * @param {string} toDest
896
+ */
897
+ export function relativeSpecifierBetween(fromDest, toDest) {
898
+ let rel = toPosix(path.relative(path.dirname(fromDest), toDest));
899
+ rel = DECLARATION_FILE.test(toDest)
900
+ ? rel.replace(/\.d\.[cm]?ts$/, '')
901
+ : rel.replace(/\.(?:[cm]?[jt]sx?)$/, '');
902
+ return rel.startsWith('.') ? rel : `./${rel}`;
903
+ }