@astryxdesign/cli 0.6.0 → 0.6.1

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 (219) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +76 -67
  3. package/api/build/build.test.mjs +37 -0
  4. package/api/build/build.type.mjs +1 -1
  5. package/api/build/kit/kit.mjs +31 -1
  6. package/api/component/_adapter.mjs +14 -28
  7. package/api/component/integration-import-agreement.test.mjs +318 -0
  8. package/api/doctor/doctor.d.mts +32 -3
  9. package/api/doctor/doctor.doc.mjs +2 -1
  10. package/api/doctor/doctor.mjs +97 -4
  11. package/api/doctor/doctor.test.mjs +90 -1
  12. package/api/gap-report/gap-report-worker.d.mts +4 -0
  13. package/api/gap-report/gap-report-worker.mjs +73 -0
  14. package/api/gap-report/gap-report.d.mts +81 -0
  15. package/api/gap-report/gap-report.doc.d.mts +9 -0
  16. package/api/gap-report/gap-report.doc.mjs +127 -0
  17. package/api/gap-report/gap-report.mjs +707 -0
  18. package/api/gap-report/gap-report.test.mjs +1210 -0
  19. package/api/gap-report/gap-report.type.d.mts +88 -0
  20. package/api/gap-report/gap-report.type.mjs +69 -0
  21. package/api/index.d.mts +8 -1
  22. package/api/index.mjs +24 -1
  23. package/api/integration/add-contribution.d.mts +44 -0
  24. package/api/integration/add-contribution.mjs +1160 -0
  25. package/api/integration/add-contribution.test.mjs +733 -0
  26. package/api/integration/add-helpers.d.mts +80 -0
  27. package/api/integration/add-helpers.mjs +333 -0
  28. package/api/integration/add-helpers.test.mjs +161 -0
  29. package/api/integration/add-theme.d.mts +10 -0
  30. package/api/integration/add-theme.mjs +332 -0
  31. package/api/integration/add-theme.test.mjs +194 -0
  32. package/api/integration/integration-authoring.type.d.mts +55 -0
  33. package/api/integration/integration-authoring.type.mjs +76 -0
  34. package/api/integration/integration-block-exports.test.mjs +4 -0
  35. package/api/integration/integrationAdd.doc.d.mts +5 -0
  36. package/api/integration/integrationAdd.doc.mjs +100 -0
  37. package/api/integration/integrationAddAgentDoc.doc.d.mts +5 -0
  38. package/api/integration/integrationAddAgentDoc.doc.mjs +49 -0
  39. package/api/integration/integrationAddCodemod.doc.d.mts +5 -0
  40. package/api/integration/integrationAddCodemod.doc.mjs +55 -0
  41. package/api/integration/integrationAddComponent.doc.d.mts +5 -0
  42. package/api/integration/integrationAddComponent.doc.mjs +49 -0
  43. package/api/integration/integrationAddDoc.doc.d.mts +5 -0
  44. package/api/integration/integrationAddDoc.doc.mjs +59 -0
  45. package/api/integration/integrationAddTemplate.doc.d.mts +5 -0
  46. package/api/integration/integrationAddTemplate.doc.mjs +55 -0
  47. package/api/integration/integrationAddTheme.doc.d.mts +5 -0
  48. package/api/integration/integrationAddTheme.doc.mjs +85 -0
  49. package/api/integration/integrationPackCheck.doc.d.mts +5 -0
  50. package/api/integration/integrationPackCheck.doc.mjs +35 -0
  51. package/api/integration/pack-check.d.mts +27 -0
  52. package/api/integration/pack-check.mjs +795 -0
  53. package/api/integration/pack-check.test.mjs +569 -0
  54. package/api/integration/pack-check.type.d.mts +45 -0
  55. package/api/integration/pack-check.type.mjs +56 -0
  56. package/api/integration/public-api.test.mjs +21 -0
  57. package/api/integration/validate-integration.mjs +221 -11
  58. package/api/integration/validate-integration.test.mjs +189 -5
  59. package/api/integration/validateIntegration.doc.mjs +2 -2
  60. package/api/json/index.ts +1 -0
  61. package/api/search/search.mjs +19 -1
  62. package/api/theme/_adapter.d.mts +26 -28
  63. package/api/theme/_adapter.mjs +101 -38
  64. package/api/theme/add/add.d.mts +2 -1
  65. package/api/theme/add/add.mjs +56 -20
  66. package/api/theme/add/add.test.mjs +1 -0
  67. package/api/theme/build/build.d.mts +25 -0
  68. package/api/theme/build/build.mjs +101 -70
  69. package/api/theme/build/build.test.mjs +77 -44
  70. package/api/theme/integration-themes.test.mjs +183 -0
  71. package/api/theme/list/list.d.mts +10 -2
  72. package/api/theme/list/list.mjs +31 -10
  73. package/api/theme/list/list.test.mjs +102 -23
  74. package/api/theme/listThemes.doc.d.mts +1 -5
  75. package/api/theme/listThemes.doc.mjs +6 -13
  76. package/api/theme/targets/targets.test.mjs +22 -8
  77. package/api/theme/theme.d.mts +1 -1
  78. package/api/theme/theme.mjs +1 -1
  79. package/api/theme/theme.type.d.mts +9 -0
  80. package/api/theme/theme.type.mjs +3 -1
  81. package/api/theme/themeAdd.doc.d.mts +1 -4
  82. package/api/theme/themeAdd.doc.mjs +31 -31
  83. package/api/theme/themeBuild.doc.mjs +1 -1
  84. package/api/theme/themeList.doc.d.mts +1 -4
  85. package/api/theme/themeList.doc.mjs +7 -15
  86. package/api/theme/themeListAvailable.doc.d.mts +8 -0
  87. package/api/theme/themeListAvailable.doc.mjs +57 -0
  88. package/api/theme/themeTargets.doc.mjs +21 -7
  89. package/api/upgrade/_adapter.d.mts +2 -0
  90. package/api/upgrade/_adapter.mjs +1 -0
  91. package/api/upgrade/registry/registry.d.mts +40 -0
  92. package/api/upgrade/registry/registry.mjs +1154 -0
  93. package/api/upgrade/registry/registry.test.mjs +826 -0
  94. package/api/upgrade/run/run.mjs +49 -8
  95. package/api/upgrade/status/status.d.mts +6 -4
  96. package/api/upgrade/status/status.mjs +26 -8
  97. package/api/upgrade/upgrade.d.mts +2 -2
  98. package/api/upgrade/upgrade.doc.mjs +33 -9
  99. package/api/upgrade/upgrade.mjs +34 -7
  100. package/api/upgrade/upgrade.test.mjs +198 -8
  101. package/api/upgrade/upgrade.type.d.mts +90 -1
  102. package/api/upgrade/upgrade.type.mjs +51 -2
  103. package/assets/docs/cli-integrations.doc.mjs +152 -28
  104. package/assets/docs/getting-started.doc.mjs +1 -1
  105. package/assets/docs/{shadcn-compatibility.doc.mjs → shadcn-compatibility.doc.draft.mjs} +23 -13
  106. package/assets/docs/styling.doc.mjs +3 -3
  107. package/assets/docs/theme.doc.dense.mjs +2 -2
  108. package/assets/docs/theme.doc.mjs +23 -13
  109. package/assets/docs/theme.doc.zh.mjs +1 -1
  110. package/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.doc.mjs +2 -1
  111. package/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.tsx +38 -12
  112. package/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadShowcase.doc.mjs +15 -0
  113. package/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadShowcase.tsx +87 -0
  114. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs +23 -0
  115. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx +75 -0
  116. package/assets/templates/blocks/components/BreadcrumbItem/BreadcrumbItemShowcase.tsx +5 -19
  117. package/assets/templates/blocks/components/Center/CenterHorizontal.doc.mjs +3 -2
  118. package/assets/templates/blocks/components/Center/CenterHorizontal.tsx +4 -5
  119. package/assets/templates/blocks/components/Toast/ToastAction.tsx +2 -1
  120. package/assets/templates/blocks/components/Toast/ToastDeduplication.tsx +2 -1
  121. package/assets/templates/blocks/components/Toast/ToastDismiss.tsx +2 -1
  122. package/assets/templates/blocks/components/Toast/ToastShowcase.tsx +2 -1
  123. package/assets/templates/blocks/components/Toast/ToastStacking.tsx +2 -1
  124. package/assets/templates/blocks/components/Toast/ToastTypes.tsx +2 -1
  125. package/assets/templates/pages/dashboard/template.doc.mjs +2 -2
  126. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +3 -2
  127. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +3 -2
  128. package/assets/templates/pages/dashboard-comparison/template.doc.mjs +3 -3
  129. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -2
  130. package/assets/templates/pages/dashboard-progress/template.doc.mjs +2 -2
  131. package/assets/templates/pages/dashboard-scorecard/template.doc.mjs +2 -2
  132. package/assets/templates/themes/butter/butterTheme.ts +3 -3
  133. package/assets/templates/themes/neutral/neutralTheme.ts +2 -2
  134. package/assets/templates/themes/stone/stoneTheme.ts +3 -3
  135. package/assets/theme.template.ts +4 -7
  136. package/authoring/config/config.doc.mjs +9 -1
  137. package/authoring/config/parse.d.mts +2 -0
  138. package/authoring/config/parse.mjs +28 -3
  139. package/authoring/config/parse.test.mjs +25 -3
  140. package/authoring/config/type.ts +3 -0
  141. package/authoring/doctypes/_schema.d.mts +3 -0
  142. package/authoring/doctypes/_schema.mjs +6 -1
  143. package/authoring/doctypes/base/type.ts +6 -6
  144. package/authoring/doctypes/component/component.doc.mjs +6 -0
  145. package/authoring/doctypes/component/type.ts +2 -0
  146. package/authoring/gap-report/parse.d.mts +63 -0
  147. package/authoring/gap-report/parse.mjs +121 -0
  148. package/authoring/gap-report/parse.test.mjs +172 -0
  149. package/authoring/gap-report/type.ts +107 -0
  150. package/authoring/index.d.mts +1 -0
  151. package/authoring/index.d.ts +12 -0
  152. package/authoring/index.mjs +4 -0
  153. package/authoring/integration/integration.doc.mjs +14 -2
  154. package/authoring/integration/parse.test.mjs +9 -4
  155. package/authoring/integration/schema.d.mts +2 -0
  156. package/authoring/integration/schema.mjs +1 -0
  157. package/authoring/integration/type.ts +23 -6
  158. package/authoring/shadcn/receipt.d.mts +219 -0
  159. package/authoring/shadcn/receipt.mjs +248 -0
  160. package/authoring/shadcn/receipt.test.mjs +187 -0
  161. package/authoring/shadcn/source-variants.d.mts +28 -0
  162. package/authoring/shadcn/source-variants.mjs +176 -0
  163. package/authoring/shadcn/source-variants.test.mjs +120 -0
  164. package/clients/cli/commands/build-theme.mjs +54 -19
  165. package/clients/cli/commands/build-theme.variants.test.mjs +15 -12
  166. package/clients/cli/commands/component/index.mjs +1 -1
  167. package/clients/cli/commands/docs.test.mjs +1 -0
  168. package/clients/cli/commands/doctor-integration.doc.mjs +1 -1
  169. package/clients/cli/commands/gap-report.doc.mjs +73 -0
  170. package/clients/cli/commands/gap-report.mjs +114 -0
  171. package/clients/cli/commands/gap-report.test.mjs +198 -0
  172. package/clients/cli/commands/import-hint-correctness.test.mjs +88 -0
  173. package/clients/cli/commands/integration-add.doc.mjs +88 -0
  174. package/clients/cli/commands/integration-authoring.test.mjs +177 -0
  175. package/clients/cli/commands/integration-pack.doc.mjs +34 -0
  176. package/clients/cli/commands/integration-real-world.test.mjs +618 -0
  177. package/clients/cli/commands/integration.doc.mjs +28 -0
  178. package/clients/cli/commands/integration.mjs +153 -0
  179. package/clients/cli/commands/theme-add.doc.mjs +11 -6
  180. package/clients/cli/commands/theme-list.doc.mjs +21 -5
  181. package/clients/cli/commands/theme-targets.behavior.test.mjs +19 -2
  182. package/clients/cli/commands/theme.doc.mjs +2 -2
  183. package/clients/cli/commands/upgrade.doc.mjs +17 -4
  184. package/clients/cli/commands/upgrade.mjs +12 -1
  185. package/clients/cli/commands/upgrade.test.mjs +41 -0
  186. package/clients/cli/index.mjs +5 -0
  187. package/clients/cli/lib/component-format.mjs +42 -26
  188. package/clients/cli/lib/component-format.test.mjs +34 -3
  189. package/clients/cli/lib/manifest.mjs +12 -0
  190. package/foundation/config/project-themes.test.mjs +127 -0
  191. package/foundation/config/project.d.mts +23 -4
  192. package/foundation/config/project.mjs +96 -9
  193. package/foundation/config/project.test.mjs +132 -6
  194. package/foundation/discovery/component-discovery.d.mts +36 -0
  195. package/foundation/discovery/component-discovery.mjs +96 -0
  196. package/foundation/discovery/theme-discovery.d.mts +39 -0
  197. package/foundation/discovery/theme-discovery.mjs +650 -0
  198. package/foundation/discovery/theme-discovery.test.mjs +375 -0
  199. package/foundation/discovery/theming-targets.d.mts +16 -0
  200. package/foundation/discovery/theming-targets.mjs +39 -3
  201. package/foundation/discovery/theming-targets.test.mjs +139 -0
  202. package/foundation/integrations/autolink.d.mts +96 -0
  203. package/foundation/integrations/autolink.mjs +265 -0
  204. package/foundation/integrations/autolink.test.mjs +430 -0
  205. package/foundation/integrations/contribution-inventory.d.mts +152 -0
  206. package/foundation/integrations/contribution-inventory.mjs +497 -0
  207. package/foundation/integrations/contribution-inventory.test.mjs +361 -0
  208. package/foundation/integrations/integrations.d.mts +73 -9
  209. package/foundation/integrations/integrations.mjs +158 -8
  210. package/foundation/integrations/integrations.test.mjs +152 -29
  211. package/foundation/integrations/manifest-writer.d.mts +56 -0
  212. package/foundation/integrations/manifest-writer.mjs +328 -0
  213. package/foundation/integrations/manifest-writer.test.mjs +229 -0
  214. package/foundation/integrations/validate-contributions.mjs +81 -6
  215. package/foundation/response/error-codes.d.mts +4 -1
  216. package/foundation/response/error-codes.doc.mjs +16 -1
  217. package/foundation/response/error-codes.mjs +10 -1
  218. package/foundation/response/response-types.doc.mjs +23 -2
  219. package/package.json +8 -1
@@ -0,0 +1,707 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Automatic gap-report routing and delivery — fan-out composition.
5
+ *
6
+ * Resolves the report target from the configured project, then fans the
7
+ * normalized report out to every effective handler: project config first,
8
+ * then each loaded integration in astryx.config order. Each handler is
9
+ * isolated in a worker: stdout→stderr, process exit contained, 30 s timeout,
10
+ * one throw/timeout/exit = that handler's failed delivery; later handlers still
11
+ * run. A public handler is skipped (consent_required) unless confirmPublic.
12
+ *
13
+ * When the effective handler set is empty, a built-in GitHub/routed-only
14
+ * fallback runs. Any handlers present suppress the built-in fallback.
15
+ */
16
+
17
+ import {Worker} from 'node:worker_threads';
18
+ import {AstryxError} from '../error.mjs';
19
+ import {Project} from '../../foundation/config/project.mjs';
20
+ import {CORE_PACKAGE} from '../../foundation/discovery/component-discovery.mjs';
21
+ import {captureEnv} from '../../foundation/debug/event.mjs';
22
+ import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
23
+ import {parseGapReportReceipt} from '../../authoring/gap-report/parse.mjs';
24
+
25
+ /** @typedef {import('../../authoring/gap-report/type').GapReportHandler} GapReportHandler */
26
+ /** @typedef {import('../../authoring/gap-report/type').GapReport} GapReport */
27
+
28
+ const HANDLER_TIMEOUT_MS = 30_000;
29
+ const HANDLER_ABORT_GRACE_MS = 25;
30
+ const HANDLER_WORKER = new URL('./gap-report-worker.mjs', import.meta.url);
31
+
32
+ /** Fixed category vocabulary retained from the original CLI surface. */
33
+ export const GAP_REPORT_CATEGORIES = Object.freeze([
34
+ Object.freeze({value: 'missing_component', label: 'Missing component'}),
35
+ Object.freeze({value: 'missing_variant', label: 'Missing variant or prop'}),
36
+ Object.freeze({value: 'layout_gap', label: 'Layout gap'}),
37
+ Object.freeze({value: 'styling_gap', label: 'Styling gap'}),
38
+ Object.freeze({value: 'a11y_gap', label: 'Accessibility gap'}),
39
+ Object.freeze({value: 'api_friction', label: 'API friction'}),
40
+ Object.freeze({value: 'docs_gap', label: 'Documentation gap'}),
41
+ Object.freeze({value: 'other', label: 'Other'}),
42
+ ]);
43
+
44
+ export const PUBLIC_CONFIRMATION_MESSAGE =
45
+ 'Rerun with --confirm-public to file this report.';
46
+
47
+ /**
48
+ * @typedef {object} ReportTarget
49
+ * @property {string} package
50
+ * @property {string|null} version
51
+ * @property {string|null} issuesUrl
52
+ */
53
+
54
+ /**
55
+ * @typedef {(
56
+ * | {kind: 'handler', handlerType: 'project'|'integration', handlerName: string, handler: GapReportHandler, modulePath: string, handlerSource: 'project'|'integration'}
57
+ * | {kind: 'malformed', handlerType: 'integration', handlerName: string, error: string}
58
+ * )} HandlerEntry
59
+ */
60
+
61
+ /** @param {string} value @returns {number} */
62
+ function characterCount(value) {
63
+ return Array.from(value).length;
64
+ }
65
+
66
+ /**
67
+ * @param {unknown} value
68
+ * @param {string} label
69
+ * @param {number} max
70
+ * @returns {string}
71
+ */
72
+ function requiredText(value, label, max) {
73
+ if (typeof value !== 'string' || value.trim() === '') {
74
+ throw new AstryxError(
75
+ `${label} is required.`,
76
+ undefined,
77
+ ERROR_CODES.ERR_MISSING_ARGUMENT,
78
+ );
79
+ }
80
+ const normalized = value.trim();
81
+ if (characterCount(normalized) > max) {
82
+ throw new AstryxError(
83
+ `${label} must be ${max} characters or fewer.`,
84
+ undefined,
85
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
86
+ );
87
+ }
88
+ return normalized;
89
+ }
90
+
91
+ /**
92
+ * @param {unknown} value
93
+ * @returns {string|undefined}
94
+ */
95
+ function optionalDetail(value) {
96
+ if (value == null || value === '') return undefined;
97
+ if (typeof value !== 'string') {
98
+ throw new AstryxError(
99
+ 'detail must be a string.',
100
+ undefined,
101
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
102
+ );
103
+ }
104
+ const normalized = value.trim();
105
+ if (normalized === '') return undefined;
106
+ if (characterCount(normalized) > 8000) {
107
+ throw new AstryxError(
108
+ 'detail must be 8000 characters or fewer.',
109
+ undefined,
110
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
111
+ );
112
+ }
113
+ return normalized;
114
+ }
115
+
116
+ /**
117
+ * @param {Project} project
118
+ * @param {string} packageName
119
+ * @returns {ReportTarget}
120
+ */
121
+ function targetForPackage(project, packageName) {
122
+ if (packageName === CORE_PACKAGE) {
123
+ return {
124
+ package: CORE_PACKAGE,
125
+ version: null,
126
+ issuesUrl: project.issuesUrl({package: CORE_PACKAGE}) ?? null,
127
+ };
128
+ }
129
+
130
+ const integration = project.loadedIntegrations.find(
131
+ item => item.name === packageName || item.__spec === packageName,
132
+ );
133
+ if (!integration) {
134
+ throw new AstryxError(
135
+ `No loaded integration package named "${packageName}".`,
136
+ project.loadedIntegrations.map(item => ({
137
+ name: item.name,
138
+ reason: 'loaded integration',
139
+ })),
140
+ ERROR_CODES.ERR_UNKNOWN_PACKAGE,
141
+ );
142
+ }
143
+
144
+ return {
145
+ package: integration.name,
146
+ version: integration.version ?? null,
147
+ issuesUrl: project.issuesUrl({package: integration.name}) ?? null,
148
+ };
149
+ }
150
+
151
+ /**
152
+ * Select the report TARGET: the package the report describes.
153
+ * Explicit package first, then unique exact component owner, else Core.
154
+ * Target selection does not depend on handler count.
155
+ *
156
+ * @param {Project} project
157
+ * @param {string} component
158
+ * @param {string|undefined} packageName
159
+ * @returns {Promise<ReportTarget>}
160
+ */
161
+ async function selectTarget(project, component, packageName) {
162
+ if (packageName) return targetForPackage(project, packageName);
163
+
164
+ const bareComponent = component.startsWith('XDS')
165
+ ? component.slice(3)
166
+ : component;
167
+ const owners = [
168
+ ...new Set(
169
+ (await project.components())
170
+ .filter(
171
+ record => record.name.toLowerCase() === bareComponent.toLowerCase(),
172
+ )
173
+ .map(record => record.package),
174
+ ),
175
+ ];
176
+
177
+ if (owners.length > 1) {
178
+ throw new AstryxError(
179
+ `Component "${component}" is provided by multiple packages. Re-run with --package <pkg> to choose one.`,
180
+ owners.map(owner => ({name: owner, reason: 'provides this component'})),
181
+ ERROR_CODES.ERR_AMBIGUOUS_COMPONENT,
182
+ );
183
+ }
184
+ if (owners.length === 1) return targetForPackage(project, owners[0]);
185
+
186
+ return targetForPackage(project, CORE_PACKAGE);
187
+ }
188
+
189
+ /**
190
+ * Collect the effective handler set in delivery order: project config first,
191
+ * then integrations in config order. Valid handlers dedupe by handle identity;
192
+ * malformed integration exports retain their position as failed deliveries.
193
+ *
194
+ * @param {Project} project
195
+ * @returns {HandlerEntry[]}
196
+ */
197
+ export function collectGapReportHandlers(project) {
198
+ /** @type {HandlerEntry[]} */
199
+ const entries = [];
200
+ /** @type {Set<Function>} */
201
+ const seen = new Set();
202
+
203
+ const projectHandler = project.config.gapReport;
204
+ if (projectHandler != null) {
205
+ seen.add(projectHandler.handle);
206
+ entries.push({
207
+ kind: 'handler',
208
+ handlerType: 'project',
209
+ handlerName: 'project',
210
+ handler: projectHandler,
211
+ modulePath: project.configPath ?? '',
212
+ handlerSource: 'project',
213
+ });
214
+ }
215
+
216
+ for (const integration of project.loadedIntegrations) {
217
+ if (integration.__loadError) continue;
218
+ if (integration.__gapReportError) {
219
+ entries.push({
220
+ kind: 'malformed',
221
+ handlerType: 'integration',
222
+ handlerName: integration.name,
223
+ error: integration.__gapReportError,
224
+ });
225
+ continue;
226
+ }
227
+ const handler = integration.__gapReport;
228
+ if (handler == null || seen.has(handler.handle)) continue;
229
+ seen.add(handler.handle);
230
+ entries.push({
231
+ kind: 'handler',
232
+ handlerType: 'integration',
233
+ handlerName: integration.name,
234
+ handler,
235
+ modulePath: integration.__manifestFile,
236
+ handlerSource: 'integration',
237
+ });
238
+ }
239
+
240
+ return entries;
241
+ }
242
+
243
+ /** @param {string} message */
244
+ function failedHandler(message) {
245
+ return {status: /** @type {const} */ ('failed'), url: null, message};
246
+ }
247
+
248
+ /**
249
+ * Call one handler in its own worker. The worker owns process.exit,
250
+ * process.exitCode, stdout, and every continuation the handler creates. A
251
+ * timeout aborts the supplied signal, gives the handler one short turn to
252
+ * observe it, then terminates the isolate before the next handler starts.
253
+ *
254
+ * @param {Extract<HandlerEntry, {kind: 'handler'}>} entry
255
+ * @param {GapReport} report cloned before this call
256
+ * @param {number} [timeoutMs]
257
+ * @returns {Promise<Pick<import('./gap-report.type.mjs').GapReportDelivery, 'status'|'url'|'message'>>}
258
+ */
259
+ async function callHandler(entry, report, timeoutMs = HANDLER_TIMEOUT_MS) {
260
+ const worker = new Worker(HANDLER_WORKER, {
261
+ workerData: {
262
+ modulePath: entry.modulePath,
263
+ handlerSource: entry.handlerSource,
264
+ report,
265
+ },
266
+ stdout: true,
267
+ stderr: true,
268
+ execArgv: process.execArgv.filter(arg => !arg.startsWith('--input-type')),
269
+ });
270
+
271
+ for (const stream of [worker.stdout, worker.stderr]) {
272
+ stream?.on('data', chunk => {
273
+ try {
274
+ process.stderr.write(chunk);
275
+ } catch {
276
+ // Handler diagnostics are best effort.
277
+ }
278
+ });
279
+ }
280
+
281
+ return await new Promise(resolve => {
282
+ let settled = false;
283
+ let timedOut = false;
284
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
285
+ let timeout;
286
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
287
+ let abortGrace;
288
+ const timeoutOutcome = failedHandler('Gap report handler timed out.');
289
+
290
+ /** @param {Pick<import('./gap-report.type.mjs').GapReportDelivery, 'status'|'url'|'message'>} outcome */
291
+ const finish = outcome => {
292
+ if (settled) return;
293
+ settled = true;
294
+ if (timeout !== undefined) clearTimeout(timeout);
295
+ if (abortGrace !== undefined) clearTimeout(abortGrace);
296
+ Promise.resolve(worker.terminate())
297
+ .catch(() => {})
298
+ .finally(() => resolve(outcome));
299
+ };
300
+
301
+ const beginTimeout = () => {
302
+ if (timeout !== undefined) clearTimeout(timeout);
303
+ timeout = setTimeout(() => {
304
+ if (settled) return;
305
+ timedOut = true;
306
+ try {
307
+ worker.postMessage({type: 'abort'});
308
+ } catch {
309
+ // The worker may have exited at the timeout boundary.
310
+ }
311
+ abortGrace = setTimeout(
312
+ () => finish(timeoutOutcome),
313
+ HANDLER_ABORT_GRACE_MS,
314
+ );
315
+ }, timeoutMs);
316
+ };
317
+
318
+ worker.on('message', message => {
319
+ if (settled || timedOut) return;
320
+ if (message?.kind === 'ready') {
321
+ beginTimeout();
322
+ return;
323
+ }
324
+ if (message?.kind === 'exit-code') {
325
+ finish(failedHandler('Handler changed process.exitCode.'));
326
+ return;
327
+ }
328
+ if (message?.kind === 'error') {
329
+ finish(failedHandler(String(message.message)));
330
+ return;
331
+ }
332
+ if (message?.kind !== 'result') {
333
+ finish(failedHandler('Handler worker returned an invalid message.'));
334
+ return;
335
+ }
336
+
337
+ const receipt = parseGapReportReceipt(message.value);
338
+ if (!receipt) {
339
+ finish(failedHandler('Handler returned an invalid receipt.'));
340
+ return;
341
+ }
342
+ finish({
343
+ status: receipt.status,
344
+ url: receipt.url ?? null,
345
+ message: receipt.message ?? null,
346
+ });
347
+ });
348
+
349
+ worker.on('error', error => {
350
+ if (!timedOut) {
351
+ finish(
352
+ failedHandler(error instanceof Error ? error.message : String(error)),
353
+ );
354
+ }
355
+ });
356
+
357
+ worker.on('exit', code => {
358
+ if (settled) return;
359
+ if (timedOut) {
360
+ finish(timeoutOutcome);
361
+ return;
362
+ }
363
+ finish(failedHandler(`Handler called process.exit(${String(code)}).`));
364
+ });
365
+
366
+ beginTimeout();
367
+ });
368
+ }
369
+
370
+ /**
371
+ * Deliver one report to the ordered effective handler set. This helper is
372
+ * exported only for focused contract tests; it is not part of the package API.
373
+ *
374
+ * @param {HandlerEntry[]} entries
375
+ * @param {GapReport} report
376
+ * @param {{confirmPublic?: boolean, timeoutMs?: number}} [options]
377
+ * @returns {Promise<import('./gap-report.type.mjs').GapReportDelivery[]>}
378
+ */
379
+ export async function deliverGapReportHandlers(
380
+ entries,
381
+ report,
382
+ {confirmPublic = false, timeoutMs = HANDLER_TIMEOUT_MS} = {},
383
+ ) {
384
+ /** @type {import('./gap-report.type.mjs').GapReportDelivery[]} */
385
+ const deliveries = [];
386
+
387
+ for (const entry of entries) {
388
+ if (entry.kind === 'malformed') {
389
+ deliveries.push({
390
+ handlerType: entry.handlerType,
391
+ handler: entry.handlerName,
392
+ audience: null,
393
+ status: 'failed',
394
+ url: null,
395
+ message: entry.error,
396
+ });
397
+ continue;
398
+ }
399
+
400
+ const {handler} = entry;
401
+ if (handler.audience === 'public' && !confirmPublic) {
402
+ deliveries.push({
403
+ handlerType: entry.handlerType,
404
+ handler: entry.handlerName,
405
+ audience: handler.audience,
406
+ status: 'consent_required',
407
+ url: null,
408
+ message: PUBLIC_CONFIRMATION_MESSAGE,
409
+ });
410
+ continue;
411
+ }
412
+
413
+ const outcome = await callHandler(
414
+ entry,
415
+ structuredClone(report),
416
+ timeoutMs,
417
+ );
418
+ deliveries.push({
419
+ handlerType: entry.handlerType,
420
+ handler: entry.handlerName,
421
+ audience: handler.audience,
422
+ ...outcome,
423
+ });
424
+ }
425
+
426
+ return deliveries;
427
+ }
428
+
429
+ /**
430
+ * @param {string} issuesUrl
431
+ * @returns {{repo: string}|null}
432
+ */
433
+ function githubRoute(issuesUrl) {
434
+ try {
435
+ const url = new URL(issuesUrl);
436
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com') return null;
437
+ const parts = url.pathname.split('/').filter(Boolean);
438
+ if (
439
+ parts.length < 3 ||
440
+ parts.length > 4 ||
441
+ parts[2] !== 'issues' ||
442
+ (parts.length === 4 && parts[3] !== 'new')
443
+ ) {
444
+ return null;
445
+ }
446
+ return {repo: `${parts[0]}/${parts[1]}`};
447
+ } catch {
448
+ return null;
449
+ }
450
+ }
451
+
452
+ /**
453
+ * Built-in GitHub fallback — runs only when the effective handler set is empty.
454
+ * Requires confirmPublic.
455
+ *
456
+ * @param {ReportTarget} target
457
+ * @param {{component: string, categoryLabel: string, intention: string, detail?: string, source: string, timestamp: string}} report
458
+ * @param {{repo: string}} github
459
+ * @returns {Promise<Pick<import('./gap-report.type.mjs').GapReportDelivery, 'status'|'url'|'message'>>}
460
+ */
461
+ async function runGithubFallback(target, report, github) {
462
+ const {execFile} = await import('node:child_process');
463
+ const title = `[gap] ${report.component}: ${report.intention.slice(0, 70)}`;
464
+ const body = [
465
+ `Component: ${report.component}`,
466
+ `Category: ${report.categoryLabel}`,
467
+ `Source: ${report.source}`,
468
+ `Reported: ${report.timestamp}`,
469
+ '',
470
+ '## Intention',
471
+ '',
472
+ report.intention,
473
+ ...(report.detail ? ['', '## Additional context', '', report.detail] : []),
474
+ ].join('\n');
475
+
476
+ try {
477
+ const output = await new Promise((resolve, reject) => {
478
+ execFile(
479
+ 'gh',
480
+ [
481
+ 'issue',
482
+ 'create',
483
+ '--repo',
484
+ github.repo,
485
+ '--title',
486
+ title,
487
+ '--body',
488
+ body,
489
+ ],
490
+ {encoding: 'utf8', timeout: HANDLER_TIMEOUT_MS, windowsHide: true},
491
+ (error, stdout) => {
492
+ if (error) reject(error);
493
+ else resolve(stdout);
494
+ },
495
+ );
496
+ });
497
+
498
+ const value = /** @type {string} */ (output).trim();
499
+ let url = null;
500
+ try {
501
+ const parsedUrl = new URL(value);
502
+ if (parsedUrl.protocol === 'https:' || parsedUrl.protocol === 'http:') {
503
+ url = value;
504
+ }
505
+ } catch {
506
+ // non-URL output from gh
507
+ }
508
+ return {
509
+ status: /** @type {const} */ ('filed'),
510
+ url,
511
+ message: url ? 'Gap report filed.' : value || 'Gap report filed.',
512
+ };
513
+ } catch {
514
+ return {
515
+ status: /** @type {const} */ ('failed'),
516
+ url: null,
517
+ message:
518
+ 'GitHub CLI could not create the routed issue. Install and authenticate gh, then retry.',
519
+ };
520
+ }
521
+ }
522
+
523
+ /**
524
+ * Compute the aggregate status from the deliveries.
525
+ * @param {import('./gap-report.type.mjs').GapReportDelivery[]} deliveries
526
+ * @returns {import('./gap-report.type.mjs').GapReportAggregateStatus}
527
+ */
528
+ function aggregateStatus(deliveries) {
529
+ if (deliveries.length === 0) return 'skipped';
530
+
531
+ const statuses = new Set(deliveries.map(d => d.status));
532
+
533
+ // All consent_required
534
+ if (statuses.size === 1 && statuses.has('consent_required'))
535
+ return 'consent_required';
536
+ // All skipped
537
+ if (statuses.size === 1 && statuses.has('skipped')) return 'skipped';
538
+ // All failed
539
+ if (statuses.size === 1 && statuses.has('failed')) return 'failed';
540
+ // All routed_only (no filed)
541
+ if (
542
+ !statuses.has('filed') &&
543
+ statuses.has('routed_only') &&
544
+ !statuses.has('failed')
545
+ )
546
+ return 'routed_only';
547
+
548
+ const hasFiled = statuses.has('filed');
549
+ const hasFailed = statuses.has('failed');
550
+ const hasHandledWithoutFiling =
551
+ statuses.has('routed_only') ||
552
+ statuses.has('skipped') ||
553
+ statuses.has('consent_required');
554
+
555
+ if (hasFailed && (hasFiled || hasHandledWithoutFiling)) return 'partial';
556
+ if (hasFailed) return 'failed';
557
+ if (hasFiled) return 'filed';
558
+
559
+ // Mixed non-failure (e.g. routed_only + consent_required + skipped)
560
+ if (statuses.has('routed_only')) return 'routed_only';
561
+ if (statuses.has('consent_required')) return 'consent_required';
562
+ return 'skipped';
563
+ }
564
+
565
+ /**
566
+ * List categories or route and file one gap report through the fan-out.
567
+ *
568
+ * @param {string|undefined} component
569
+ * @param {import('./gap-report.type.mjs').GapReportOptions} [options]
570
+ * @returns {Promise<import('./gap-report.type.mjs').GapReportCategoriesResponse | import('./gap-report.type.mjs').GapReportReceiptResponse>}
571
+ */
572
+ export async function gapReport(component, options = {}) {
573
+ if (options.listCategories) {
574
+ return {
575
+ type: 'gap-report.categories',
576
+ data: GAP_REPORT_CATEGORIES.map(category => ({...category})),
577
+ };
578
+ }
579
+
580
+ const resolvedComponent = requiredText(component, 'component', 120);
581
+ const category = requiredText(options.category, 'category', 80);
582
+ const categoryEntry = GAP_REPORT_CATEGORIES.find(
583
+ entry => entry.value === category,
584
+ );
585
+ if (!categoryEntry) {
586
+ throw new AstryxError(
587
+ `Unknown gap category "${category}".`,
588
+ GAP_REPORT_CATEGORIES.map(entry => ({
589
+ name: entry.value,
590
+ reason: entry.label,
591
+ })),
592
+ ERROR_CODES.ERR_UNKNOWN_CATEGORY,
593
+ );
594
+ }
595
+ const intention = requiredText(options.reason, 'reason', 2000);
596
+ const detail = optionalDetail(options.detail);
597
+ const cwd = (await import('node:path')).resolve(options.cwd ?? process.cwd());
598
+ const project = await Project.load(cwd);
599
+ const target = await selectTarget(
600
+ project,
601
+ resolvedComponent,
602
+ options.package,
603
+ );
604
+
605
+ const entries = collectGapReportHandlers(project);
606
+
607
+ const timestamp = new Date().toISOString();
608
+ const source = captureEnv().invocationSource;
609
+
610
+ /** @type {GapReport} */
611
+ const report = {
612
+ schemaVersion: 1,
613
+ component: resolvedComponent,
614
+ category:
615
+ /** @type {import('../../authoring/gap-report/type').GapReportCategory} */ (
616
+ categoryEntry.value
617
+ ),
618
+ categoryLabel: categoryEntry.label,
619
+ intention,
620
+ ...(detail ? {detail} : {}),
621
+ source,
622
+ timestamp,
623
+ target: {
624
+ package: target.package,
625
+ version: target.version,
626
+ issuesUrl: target.issuesUrl,
627
+ },
628
+ };
629
+
630
+ /** @type {import('./gap-report.type.mjs').GapReportDelivery[]} */
631
+ const deliveries = [];
632
+
633
+ if (entries.length > 0) {
634
+ deliveries.push(
635
+ ...(await deliverGapReportHandlers(entries, report, {
636
+ confirmPublic: options.confirmPublic === true,
637
+ })),
638
+ );
639
+ } else {
640
+ if (!target.issuesUrl) {
641
+ throw new AstryxError(
642
+ `Package "${target.package}" provides neither a report handler nor an issues URL.`,
643
+ undefined,
644
+ ERROR_CODES.ERR_NOT_FOUND,
645
+ );
646
+ }
647
+
648
+ const github = githubRoute(target.issuesUrl);
649
+ if (github != null && options.confirmPublic !== true) {
650
+ deliveries.push({
651
+ handlerType: 'fallback',
652
+ handler: 'github',
653
+ audience: 'public',
654
+ status: 'consent_required',
655
+ url: null,
656
+ message: PUBLIC_CONFIRMATION_MESSAGE,
657
+ });
658
+ } else if (github) {
659
+ const outcome = await runGithubFallback(
660
+ target,
661
+ {
662
+ component: resolvedComponent,
663
+ categoryLabel: categoryEntry.label,
664
+ intention,
665
+ detail,
666
+ source,
667
+ timestamp,
668
+ },
669
+ github,
670
+ );
671
+ deliveries.push({
672
+ handlerType: 'fallback',
673
+ handler: 'github',
674
+ audience: 'public',
675
+ ...outcome,
676
+ });
677
+ } else {
678
+ deliveries.push({
679
+ handlerType: 'fallback',
680
+ handler: 'issuesUrl',
681
+ audience: null,
682
+ status: 'routed_only',
683
+ url: target.issuesUrl,
684
+ message:
685
+ 'No automatic handler is available; open the routed URL to file this report.',
686
+ });
687
+ }
688
+ }
689
+
690
+ const filedCount = deliveries.filter(d => d.status === 'filed').length;
691
+ const routedOnlyCount = deliveries.filter(
692
+ d => d.status === 'routed_only',
693
+ ).length;
694
+ const status = aggregateStatus(deliveries);
695
+
696
+ return {
697
+ type: 'gap-report.file',
698
+ data: {
699
+ status,
700
+ package: target.package,
701
+ issuesUrl: target.issuesUrl,
702
+ deliveries,
703
+ filedCount,
704
+ routedOnlyCount,
705
+ },
706
+ };
707
+ }