harnesstap 1.2.0 → 1.3.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 (202) hide show
  1. package/README.md +28 -15
  2. package/dist/apply-2GRNKR5H.js +67 -0
  3. package/dist/apply-2GRNKR5H.js.map +1 -0
  4. package/dist/approve-KQNCNH2R.js +181 -0
  5. package/dist/approve-KQNCNH2R.js.map +1 -0
  6. package/dist/audit-SLYOZCMI.js +434 -0
  7. package/dist/audit-SLYOZCMI.js.map +1 -0
  8. package/dist/auth-3IEVICFT.js +220 -0
  9. package/dist/auth-3IEVICFT.js.map +1 -0
  10. package/dist/bin.js +166 -0
  11. package/dist/bin.js.map +1 -0
  12. package/dist/chunk-2EIJYDNI.js +10945 -0
  13. package/dist/chunk-2EIJYDNI.js.map +1 -0
  14. package/dist/chunk-2H7UOFLK.js +11 -0
  15. package/dist/chunk-2H7UOFLK.js.map +1 -0
  16. package/dist/chunk-37E5M4JX.js +34 -0
  17. package/dist/chunk-37E5M4JX.js.map +1 -0
  18. package/dist/chunk-3FIWOI3H.js +98 -0
  19. package/dist/chunk-3FIWOI3H.js.map +1 -0
  20. package/dist/chunk-3IWTJCPA.js +6448 -0
  21. package/dist/chunk-3IWTJCPA.js.map +1 -0
  22. package/dist/chunk-3IZ7SEGT.js +346 -0
  23. package/dist/chunk-3IZ7SEGT.js.map +1 -0
  24. package/dist/chunk-3RBYT7QN.js +540 -0
  25. package/dist/chunk-3RBYT7QN.js.map +1 -0
  26. package/dist/chunk-4KNQZDZC.js +115 -0
  27. package/dist/chunk-4KNQZDZC.js.map +1 -0
  28. package/dist/chunk-5F3LNDZG.js +9 -0
  29. package/dist/chunk-5F3LNDZG.js.map +1 -0
  30. package/dist/chunk-63U7QWNY.js +364 -0
  31. package/dist/chunk-63U7QWNY.js.map +1 -0
  32. package/dist/chunk-6BY4BV5G.js +998 -0
  33. package/dist/chunk-6BY4BV5G.js.map +1 -0
  34. package/dist/chunk-7L2K4N25.js +610 -0
  35. package/dist/chunk-7L2K4N25.js.map +1 -0
  36. package/dist/chunk-7LWH5SWH.js +18 -0
  37. package/dist/chunk-7LWH5SWH.js.map +1 -0
  38. package/dist/chunk-BIBUCC2E.js +696 -0
  39. package/dist/chunk-BIBUCC2E.js.map +1 -0
  40. package/dist/chunk-BSOBXLYI.js +172 -0
  41. package/dist/chunk-BSOBXLYI.js.map +1 -0
  42. package/dist/chunk-C4QBVVEH.js +32 -0
  43. package/dist/chunk-C4QBVVEH.js.map +1 -0
  44. package/dist/chunk-CHQGE2HF.js +283 -0
  45. package/dist/chunk-CHQGE2HF.js.map +1 -0
  46. package/dist/chunk-DV74UZJI.js +87 -0
  47. package/dist/chunk-DV74UZJI.js.map +1 -0
  48. package/dist/chunk-DWVAR4BP.js +656 -0
  49. package/dist/chunk-DWVAR4BP.js.map +1 -0
  50. package/dist/chunk-DXKAKKLP.js +302 -0
  51. package/dist/chunk-DXKAKKLP.js.map +1 -0
  52. package/dist/chunk-EIWXS4RM.js +235 -0
  53. package/dist/chunk-EIWXS4RM.js.map +1 -0
  54. package/dist/chunk-EWBCFAF3.js +681 -0
  55. package/dist/chunk-EWBCFAF3.js.map +1 -0
  56. package/dist/chunk-F2L4VNQK.js +1759 -0
  57. package/dist/chunk-F2L4VNQK.js.map +1 -0
  58. package/dist/chunk-G26HZZDJ.js +1359 -0
  59. package/dist/chunk-G26HZZDJ.js.map +1 -0
  60. package/dist/chunk-GQKKX7OE.js +818 -0
  61. package/dist/chunk-GQKKX7OE.js.map +1 -0
  62. package/dist/chunk-GRJY22U6.js +691 -0
  63. package/dist/chunk-GRJY22U6.js.map +1 -0
  64. package/dist/chunk-H6DVP2SI.js +682 -0
  65. package/dist/chunk-H6DVP2SI.js.map +1 -0
  66. package/dist/chunk-HVVPTCKR.js +1173 -0
  67. package/dist/chunk-HVVPTCKR.js.map +1 -0
  68. package/dist/chunk-I6XFZLTJ.js +9 -0
  69. package/dist/chunk-I6XFZLTJ.js.map +1 -0
  70. package/dist/chunk-IBOABSIA.js +17 -0
  71. package/dist/chunk-IBOABSIA.js.map +1 -0
  72. package/dist/chunk-IK524ZDW.js +691 -0
  73. package/dist/chunk-IK524ZDW.js.map +1 -0
  74. package/dist/chunk-IRU7NBOT.js +141 -0
  75. package/dist/chunk-IRU7NBOT.js.map +1 -0
  76. package/dist/chunk-J4CKQXQ6.js +806 -0
  77. package/dist/chunk-J4CKQXQ6.js.map +1 -0
  78. package/dist/chunk-JKGSJGCC.js +311 -0
  79. package/dist/chunk-JKGSJGCC.js.map +1 -0
  80. package/dist/chunk-JQOKQKQT.js +158 -0
  81. package/dist/chunk-JQOKQKQT.js.map +1 -0
  82. package/dist/chunk-JRFUTIEH.js +426 -0
  83. package/dist/chunk-JRFUTIEH.js.map +1 -0
  84. package/dist/chunk-K2BPYEH5.js +491 -0
  85. package/dist/chunk-K2BPYEH5.js.map +1 -0
  86. package/dist/chunk-KCQC7YBK.js +7795 -0
  87. package/dist/chunk-KCQC7YBK.js.map +1 -0
  88. package/dist/chunk-KDAV2GUT.js +1357 -0
  89. package/dist/chunk-KDAV2GUT.js.map +1 -0
  90. package/dist/chunk-KDDXZBMC.js +583 -0
  91. package/dist/chunk-KDDXZBMC.js.map +1 -0
  92. package/dist/chunk-KMWHZSEG.js +41 -0
  93. package/dist/chunk-KMWHZSEG.js.map +1 -0
  94. package/dist/chunk-KRI4R7EM.js +25 -0
  95. package/dist/chunk-KRI4R7EM.js.map +1 -0
  96. package/dist/chunk-LNJ3WZZX.js +186 -0
  97. package/dist/chunk-LNJ3WZZX.js.map +1 -0
  98. package/dist/chunk-MWXA4PFE.js +103 -0
  99. package/dist/chunk-MWXA4PFE.js.map +1 -0
  100. package/dist/chunk-MY62SSKC.js +183 -0
  101. package/dist/chunk-MY62SSKC.js.map +1 -0
  102. package/dist/chunk-NAGAJ5UM.js +145 -0
  103. package/dist/chunk-NAGAJ5UM.js.map +1 -0
  104. package/dist/chunk-NJ7WRKIQ.js +532 -0
  105. package/dist/chunk-NJ7WRKIQ.js.map +1 -0
  106. package/dist/chunk-OS6NUIBJ.js +38 -0
  107. package/dist/chunk-OS6NUIBJ.js.map +1 -0
  108. package/dist/chunk-PXU2OS26.js +238 -0
  109. package/dist/chunk-PXU2OS26.js.map +1 -0
  110. package/dist/chunk-QO4LBDVI.js +496 -0
  111. package/dist/chunk-QO4LBDVI.js.map +1 -0
  112. package/dist/chunk-QRZPQNLX.js +65 -0
  113. package/dist/chunk-QRZPQNLX.js.map +1 -0
  114. package/dist/chunk-SNVAMWB7.js +40 -0
  115. package/dist/chunk-SNVAMWB7.js.map +1 -0
  116. package/dist/chunk-SPRVUATR.js +430 -0
  117. package/dist/chunk-SPRVUATR.js.map +1 -0
  118. package/dist/chunk-SY7G5QEI.js +35 -0
  119. package/dist/chunk-SY7G5QEI.js.map +1 -0
  120. package/dist/chunk-SZNBUIDR.js +6438 -0
  121. package/dist/chunk-SZNBUIDR.js.map +1 -0
  122. package/dist/chunk-TQ2NA4Z4.js +24 -0
  123. package/dist/chunk-TQ2NA4Z4.js.map +1 -0
  124. package/dist/chunk-TYULB6ZY.js +2959 -0
  125. package/dist/chunk-TYULB6ZY.js.map +1 -0
  126. package/dist/chunk-UJYFTXHV.js +296 -0
  127. package/dist/chunk-UJYFTXHV.js.map +1 -0
  128. package/dist/chunk-VC6OKCJF.js +184 -0
  129. package/dist/chunk-VC6OKCJF.js.map +1 -0
  130. package/dist/chunk-VL2NWCZV.js +118 -0
  131. package/dist/chunk-VL2NWCZV.js.map +1 -0
  132. package/dist/chunk-VL7BGD47.js +514 -0
  133. package/dist/chunk-VL7BGD47.js.map +1 -0
  134. package/dist/chunk-VQVUJYYY.js +244 -0
  135. package/dist/chunk-VQVUJYYY.js.map +1 -0
  136. package/dist/chunk-VZQG2JDV.js +9 -0
  137. package/dist/chunk-VZQG2JDV.js.map +1 -0
  138. package/dist/chunk-XFZQVYIN.js +115 -0
  139. package/dist/chunk-XFZQVYIN.js.map +1 -0
  140. package/dist/chunk-XGTTOO4R.js +84 -0
  141. package/dist/chunk-XGTTOO4R.js.map +1 -0
  142. package/dist/chunk-XQFT4PEP.js +60 -0
  143. package/dist/chunk-XQFT4PEP.js.map +1 -0
  144. package/dist/chunk-YDD3ES2K.js +571 -0
  145. package/dist/chunk-YDD3ES2K.js.map +1 -0
  146. package/dist/chunk-ZY2MZ2KQ.js +1140 -0
  147. package/dist/chunk-ZY2MZ2KQ.js.map +1 -0
  148. package/dist/compile-57EEIUMB.js +161 -0
  149. package/dist/compile-57EEIUMB.js.map +1 -0
  150. package/dist/config-4EJ3D7QJ.js +438 -0
  151. package/dist/config-4EJ3D7QJ.js.map +1 -0
  152. package/dist/doctor-EEV6P5CH.js +111 -0
  153. package/dist/doctor-EEV6P5CH.js.map +1 -0
  154. package/dist/environment-WFEG4DAT.js +2745 -0
  155. package/dist/environment-WFEG4DAT.js.map +1 -0
  156. package/dist/github-BSMQD72A.js +114 -0
  157. package/dist/github-BSMQD72A.js.map +1 -0
  158. package/dist/harness-VX3PNVQW.js +746 -0
  159. package/dist/harness-VX3PNVQW.js.map +1 -0
  160. package/dist/help-AW2HKX63.js +2079 -0
  161. package/dist/help-AW2HKX63.js.map +1 -0
  162. package/dist/help-BVFOZD7E.js +1892 -0
  163. package/dist/help-BVFOZD7E.js.map +1 -0
  164. package/dist/index.d.ts +164 -1
  165. package/dist/index.js +50 -59246
  166. package/dist/index.js.map +1 -1
  167. package/dist/init-SPN2GEZ4.js +873 -0
  168. package/dist/init-SPN2GEZ4.js.map +1 -0
  169. package/dist/lock-K2LLUU7H.js +455 -0
  170. package/dist/lock-K2LLUU7H.js.map +1 -0
  171. package/dist/marketplace-VEKSWGX3.js +495 -0
  172. package/dist/marketplace-VEKSWGX3.js.map +1 -0
  173. package/dist/mcp-T6DKIKSF.js +202 -0
  174. package/dist/mcp-T6DKIKSF.js.map +1 -0
  175. package/dist/migrate-OO37WSB2.js +1043 -0
  176. package/dist/migrate-OO37WSB2.js.map +1 -0
  177. package/dist/open-3V3QK5RK.js +32 -0
  178. package/dist/open-3V3QK5RK.js.map +1 -0
  179. package/dist/pack-V32UPC7W.js +99 -0
  180. package/dist/pack-V32UPC7W.js.map +1 -0
  181. package/dist/plugin-KOBNQ7GT.js +64 -0
  182. package/dist/plugin-KOBNQ7GT.js.map +1 -0
  183. package/dist/plugin-from-project-X3VO3MB6.js +16 -0
  184. package/dist/plugin-from-project-X3VO3MB6.js.map +1 -0
  185. package/dist/policy-F5MKZNOC.js +105 -0
  186. package/dist/policy-F5MKZNOC.js.map +1 -0
  187. package/dist/profile-H4PMH4XT.js +1886 -0
  188. package/dist/profile-H4PMH4XT.js.map +1 -0
  189. package/dist/project-QVNEJJGH.js +1392 -0
  190. package/dist/project-QVNEJJGH.js.map +1 -0
  191. package/dist/resource-GL4RLSGI.js +555 -0
  192. package/dist/resource-GL4RLSGI.js.map +1 -0
  193. package/dist/version-PBHZK44K.js +17 -0
  194. package/dist/version-PBHZK44K.js.map +1 -0
  195. package/package.json +21 -14
  196. package/schemas/ap-package.v1.json +36 -0
  197. package/schemas/fixtures/catalog-missing-schema.ap.json +13 -0
  198. package/schemas/fixtures/confidence.ap.json +13 -0
  199. package/schemas/fixtures/context7.ap.json +13 -0
  200. package/schemas/fixtures/minimal-with-schema.ap.json +13 -0
  201. package/schemas/fixtures/superpowers.ap.json +13 -0
  202. package/schemas/fixtures/third-party-skills.ap.json +13 -0
@@ -0,0 +1,1140 @@
1
+ import {
2
+ parseJsonc
3
+ } from "./chunk-VQVUJYYY.js";
4
+ import {
5
+ PACKAGE_VERSION,
6
+ fetchWithTimeout,
7
+ getHarnesstapDir
8
+ } from "./chunk-DWVAR4BP.js";
9
+
10
+ // src/config/catalog.ts
11
+ import { existsSync, readFileSync, writeFileSync } from "fs";
12
+ import { join } from "path";
13
+
14
+ // src/services/plugin-selector.ts
15
+ var DEFAULT_CATALOG_SLUG = "default";
16
+ var INVALID_SELECTOR_MESSAGE = "Invalid plugin selector. Use name, name@version, or org/catalog/name[@version].";
17
+ function splitVersionFromSegment(segment) {
18
+ if (!segment) {
19
+ throw new Error(INVALID_SELECTOR_MESSAGE);
20
+ }
21
+ const atIndex = segment.lastIndexOf("@");
22
+ if (atIndex === 0) {
23
+ throw new Error(INVALID_SELECTOR_MESSAGE);
24
+ }
25
+ if (atIndex > 0) {
26
+ const name = segment.slice(0, atIndex);
27
+ const version = segment.slice(atIndex + 1);
28
+ if (!name || !version) {
29
+ throw new Error(INVALID_SELECTOR_MESSAGE);
30
+ }
31
+ return { name, version };
32
+ }
33
+ return { name: segment };
34
+ }
35
+ function parsePluginSelector(selector) {
36
+ const trimmed = selector.trim();
37
+ if (!trimmed) {
38
+ throw new Error(INVALID_SELECTOR_MESSAGE);
39
+ }
40
+ if (!trimmed.includes("/")) {
41
+ const { name: name2, version: version2 } = splitVersionFromSegment(trimmed);
42
+ if (!name2) {
43
+ throw new Error(INVALID_SELECTOR_MESSAGE);
44
+ }
45
+ return { scope: "local", name: name2, version: version2 };
46
+ }
47
+ const segments = trimmed.split("/").filter((part) => part.length > 0);
48
+ if (segments.length !== 3) {
49
+ throw new Error(INVALID_SELECTOR_MESSAGE);
50
+ }
51
+ const lastIndex = segments.length - 1;
52
+ const lastSegment = segments[lastIndex];
53
+ if (!lastSegment) {
54
+ throw new Error(INVALID_SELECTOR_MESSAGE);
55
+ }
56
+ const { name: pluginName, version } = splitVersionFromSegment(lastSegment);
57
+ if (!pluginName) {
58
+ throw new Error(INVALID_SELECTOR_MESSAGE);
59
+ }
60
+ segments[lastIndex] = pluginName;
61
+ const [org, catalog, name] = segments;
62
+ if (!org || !catalog || !name) {
63
+ throw new Error(INVALID_SELECTOR_MESSAGE);
64
+ }
65
+ return {
66
+ scope: "published",
67
+ org,
68
+ catalog,
69
+ name,
70
+ version
71
+ };
72
+ }
73
+ function formatPublishedSelector(input) {
74
+ if (input.catalog === DEFAULT_CATALOG_SLUG) {
75
+ return `${input.org}/${input.name}`;
76
+ }
77
+ return `${input.org}/${input.catalog}/${input.name}`;
78
+ }
79
+ function formatPublishedSelectorWithVersion(selector) {
80
+ const base = formatPublishedSelector(selector);
81
+ return selector.version ? `${base}@${selector.version}` : base;
82
+ }
83
+ function formatCanonicalPublishedSelector(input) {
84
+ return `${input.org}/${input.catalog}/${input.name}`;
85
+ }
86
+ function formatCanonicalPublishedSelectorWithVersion(selector) {
87
+ const base = formatCanonicalPublishedSelector(selector);
88
+ return selector.version ? `${base}@${selector.version}` : base;
89
+ }
90
+ function resolvedRemotePluginFromCatalog(input) {
91
+ return {
92
+ org_slug: input.org,
93
+ catalog_slug: input.catalog,
94
+ plugin_slug: input.name,
95
+ ...input.version ? { version: input.version } : {}
96
+ };
97
+ }
98
+ function resolveRemotePluginSelector(selector, opts) {
99
+ const parsed = parsePluginSelector(selector);
100
+ if (parsed.scope === "local") {
101
+ if (opts.version && parsed.version) {
102
+ throw new Error(
103
+ "--version conflicts with version in selector. Remove --version or use selector without version."
104
+ );
105
+ }
106
+ if (!opts.org) {
107
+ throw new Error(
108
+ "org is required. Provide it in the selector as org/catalog/plugin or use --org <slug>"
109
+ );
110
+ }
111
+ return {
112
+ org_slug: opts.org,
113
+ catalog_slug: opts.catalog ?? DEFAULT_CATALOG_SLUG,
114
+ plugin_slug: parsed.name,
115
+ version: opts.version ?? parsed.version
116
+ };
117
+ }
118
+ if (opts.org && opts.org !== parsed.org) {
119
+ throw new Error(
120
+ "--org conflicts with org in selector. Remove --org or use selector without org."
121
+ );
122
+ }
123
+ if (opts.catalog && opts.catalog !== parsed.catalog) {
124
+ throw new Error(
125
+ "--catalog conflicts with catalog in selector. Remove --catalog or use selector without catalog."
126
+ );
127
+ }
128
+ if (opts.version && parsed.version) {
129
+ throw new Error(
130
+ "--version conflicts with version in selector. Remove --version or use selector without version."
131
+ );
132
+ }
133
+ return {
134
+ org_slug: parsed.org,
135
+ catalog_slug: opts.catalog ?? parsed.catalog,
136
+ plugin_slug: parsed.name,
137
+ version: opts.version ?? parsed.version
138
+ };
139
+ }
140
+
141
+ // src/config/catalog.ts
142
+ var DEFAULT_CATALOG_ORG_SLUG = "harnesstap-cloud";
143
+ var OPEN_CATALOG_ORG_ALIASES = [
144
+ DEFAULT_CATALOG_ORG_SLUG,
145
+ "harnessdeck-cloud"
146
+ ];
147
+ var DEFAULT_CLOUD_BASE_URL = "https://harnesstap.com";
148
+ var DEFAULT_CATALOG_SETTINGS = {
149
+ cloudBaseUrl: DEFAULT_CLOUD_BASE_URL,
150
+ connectedOrgs: [],
151
+ connectedPlugins: [],
152
+ publicCatalog: true,
153
+ registered: []
154
+ };
155
+ var INVALID_PUBLISH_CATALOG_SELECTOR = "Invalid catalog selector. Use org/catalog (e.g. acme/internal) or account@org/catalog.";
156
+ function normalizeCatalogSlug(slug) {
157
+ return slug.trim().toLowerCase();
158
+ }
159
+ function publishCatalogKey(catalog) {
160
+ return `${normalizeOrgSlug(catalog.org)}/${normalizeCatalogSlug(catalog.catalog)}`;
161
+ }
162
+ function parsePublishCatalogSelector(selector) {
163
+ const trimmed = selector.trim();
164
+ if (!trimmed) {
165
+ throw new Error(INVALID_PUBLISH_CATALOG_SELECTOR);
166
+ }
167
+ let account;
168
+ let path = trimmed;
169
+ const atIndex = trimmed.indexOf("@");
170
+ if (atIndex > 0) {
171
+ const beforeAt = trimmed.slice(0, atIndex);
172
+ const afterAt = trimmed.slice(atIndex + 1);
173
+ if (!beforeAt.includes("/") && afterAt.includes("/")) {
174
+ account = beforeAt.trim();
175
+ path = afterAt;
176
+ }
177
+ }
178
+ const parts = path.split("/").filter((part) => part.length > 0);
179
+ if (parts.length !== 2) {
180
+ throw new Error(INVALID_PUBLISH_CATALOG_SELECTOR);
181
+ }
182
+ const [org, catalog] = parts;
183
+ if (!org || !catalog) {
184
+ throw new Error(INVALID_PUBLISH_CATALOG_SELECTOR);
185
+ }
186
+ return {
187
+ org: normalizeOrgSlug(org),
188
+ catalog: normalizeCatalogSlug(catalog),
189
+ ...account ? { account } : {}
190
+ };
191
+ }
192
+ function formatPublishCatalogSelector(catalog) {
193
+ const base = `${catalog.org}/${catalog.catalog}`;
194
+ return catalog.account ? `${catalog.account}@${base}` : base;
195
+ }
196
+ function normalizeRegisteredCatalog(catalog) {
197
+ return {
198
+ org: normalizeOrgSlug(catalog.org),
199
+ catalog: normalizeCatalogSlug(catalog.catalog),
200
+ ...catalog.account?.trim() ? { account: catalog.account.trim() } : {}
201
+ };
202
+ }
203
+ function sortRegisteredCatalogs(catalogs) {
204
+ return [...catalogs].sort((left, right) => {
205
+ const orgCompare = left.org.localeCompare(right.org);
206
+ if (orgCompare !== 0) {
207
+ return orgCompare;
208
+ }
209
+ return left.catalog.localeCompare(right.catalog);
210
+ });
211
+ }
212
+ function getConfigPath(harnesstapDir = getHarnesstapDir()) {
213
+ const jsoncPath = join(harnesstapDir, "config.jsonc");
214
+ if (existsSync(jsoncPath) || !existsSync(join(harnesstapDir, "config.json"))) {
215
+ return jsoncPath;
216
+ }
217
+ return join(harnesstapDir, "config.json");
218
+ }
219
+ function normalizeOrgSlug(slug) {
220
+ return slug.trim().toLowerCase();
221
+ }
222
+ function normalizeSelector(selector) {
223
+ const trimmed = selector.trim();
224
+ const parts = trimmed.split("/").filter((part) => part.length > 0);
225
+ if (parts.length === 3) {
226
+ return `${parts[0]}/${parts[1]}/${parts[2]}`;
227
+ }
228
+ throw new Error(
229
+ `Invalid plugin selector: ${selector}. Use org/catalog/plugin.`
230
+ );
231
+ }
232
+ function resolveCloudBaseUrl(override) {
233
+ if (override?.trim()) {
234
+ return override.replace(/\/+$/, "");
235
+ }
236
+ if (process.env.HARNESSTAP_CLOUD_URL?.trim()) {
237
+ return process.env.HARNESSTAP_CLOUD_URL.replace(/\/+$/, "");
238
+ }
239
+ return loadCatalogSettings().cloudBaseUrl.replace(/\/+$/, "");
240
+ }
241
+ function loadCatalogSettings(harnesstapDir = getHarnesstapDir()) {
242
+ const path = getConfigPath(harnesstapDir);
243
+ if (!existsSync(path)) {
244
+ return { ...DEFAULT_CATALOG_SETTINGS };
245
+ }
246
+ try {
247
+ const raw = parseJsonc(readFileSync(path, "utf-8"));
248
+ const catalog = raw.catalog ?? {};
249
+ const connectedOrgs = Array.isArray(catalog.connectedOrgs) ? [...new Set(catalog.connectedOrgs.map((org) => normalizeOrgSlug(String(org))).filter(Boolean))] : [];
250
+ const connectedPlugins = Array.isArray(catalog.connectedPlugins) ? [...new Set(catalog.connectedPlugins.map((selector) => normalizeSelector(String(selector))))] : [];
251
+ const registered = Array.isArray(catalog.registered) ? sortRegisteredCatalogs(
252
+ catalog.registered.map((entry) => {
253
+ if (!entry || typeof entry !== "object") {
254
+ return void 0;
255
+ }
256
+ const record = entry;
257
+ if (typeof record.org !== "string" || typeof record.catalog !== "string") {
258
+ return void 0;
259
+ }
260
+ return normalizeRegisteredCatalog({
261
+ org: record.org,
262
+ catalog: record.catalog,
263
+ account: typeof record.account === "string" ? record.account : void 0
264
+ });
265
+ }).filter((entry) => entry !== void 0)
266
+ ) : [];
267
+ const registeredKeys = /* @__PURE__ */ new Set();
268
+ const uniqueRegistered = [];
269
+ for (const entry of registered) {
270
+ const key = publishCatalogKey(entry);
271
+ if (registeredKeys.has(key)) {
272
+ continue;
273
+ }
274
+ registeredKeys.add(key);
275
+ uniqueRegistered.push(entry);
276
+ }
277
+ return {
278
+ cloudBaseUrl: typeof catalog.cloudBaseUrl === "string" && catalog.cloudBaseUrl.trim() ? catalog.cloudBaseUrl.replace(/\/+$/, "") : DEFAULT_CATALOG_SETTINGS.cloudBaseUrl,
279
+ connectedOrgs: connectedOrgs.filter((org) => org !== DEFAULT_CATALOG_ORG_SLUG),
280
+ connectedPlugins,
281
+ publicCatalog: typeof catalog.publicCatalog === "boolean" ? catalog.publicCatalog : DEFAULT_CATALOG_SETTINGS.publicCatalog,
282
+ registered: uniqueRegistered
283
+ };
284
+ } catch {
285
+ return { ...DEFAULT_CATALOG_SETTINGS };
286
+ }
287
+ }
288
+ function saveCatalogSettings(input, harnesstapDir = getHarnesstapDir()) {
289
+ const path = getConfigPath(harnesstapDir);
290
+ let existing = {};
291
+ if (existsSync(path)) {
292
+ try {
293
+ existing = parseJsonc(readFileSync(path, "utf-8"));
294
+ } catch {
295
+ existing = {};
296
+ }
297
+ }
298
+ const current = loadCatalogSettings(harnesstapDir);
299
+ const next = {
300
+ cloudBaseUrl: input.cloudBaseUrl?.replace(/\/+$/, "") ?? current.cloudBaseUrl,
301
+ connectedOrgs: input.connectedOrgs ?? current.connectedOrgs,
302
+ connectedPlugins: input.connectedPlugins ?? current.connectedPlugins,
303
+ publicCatalog: input.publicCatalog ?? current.publicCatalog,
304
+ registered: input.registered ?? current.registered
305
+ };
306
+ writeFileSync(
307
+ path,
308
+ `${JSON.stringify({ ...existing, catalog: next }, null, 2)}
309
+ `,
310
+ "utf-8"
311
+ );
312
+ return next;
313
+ }
314
+ function resolveCatalogScope(input) {
315
+ const settings = loadCatalogSettings(input?.harnesstapDir);
316
+ return {
317
+ defaultOrgSlug: DEFAULT_CATALOG_ORG_SLUG,
318
+ orgs: [
319
+ .../* @__PURE__ */ new Set([
320
+ ...OPEN_CATALOG_ORG_ALIASES,
321
+ ...settings.connectedOrgs
322
+ ])
323
+ ],
324
+ selectors: settings.connectedPlugins,
325
+ cloudBaseUrl: resolveCloudBaseUrl(input?.baseUrl)
326
+ };
327
+ }
328
+ function isPublicCatalogEnabled(harnesstapDir = getHarnesstapDir()) {
329
+ const env = process.env.HARNESSTAP_PUBLIC_CATALOG?.trim().toLowerCase();
330
+ if (env === "0" || env === "false" || env === "no") {
331
+ return false;
332
+ }
333
+ if (env === "1" || env === "true" || env === "yes") {
334
+ return true;
335
+ }
336
+ return loadCatalogSettings(harnesstapDir).publicCatalog;
337
+ }
338
+ function formatCatalogScopeLabel(scope) {
339
+ const extras = [
340
+ ...scope.orgs.filter((org) => org !== scope.defaultOrgSlug),
341
+ ...scope.selectors
342
+ ];
343
+ if (extras.length === 0) {
344
+ return scope.defaultOrgSlug;
345
+ }
346
+ return `${scope.defaultOrgSlug} + ${extras.join(", ")}`;
347
+ }
348
+ function selectorVariants(selector) {
349
+ const orgSlug = normalizeOrgSlug(selector.orgSlug);
350
+ const catalogSlug = selector.catalogSlug.trim() || DEFAULT_CATALOG_SLUG;
351
+ const pluginSlug = selector.pluginSlug.trim();
352
+ const variants = [`${orgSlug}/${pluginSlug}`];
353
+ if (catalogSlug !== DEFAULT_CATALOG_SLUG) {
354
+ variants.push(`${orgSlug}/${catalogSlug}/${pluginSlug}`);
355
+ }
356
+ return variants;
357
+ }
358
+ function isSelectorInCatalogScope(selector, scope) {
359
+ const orgSlug = normalizeOrgSlug(selector.orgSlug);
360
+ const catalogSlug = selector.catalogSlug?.trim() || DEFAULT_CATALOG_SLUG;
361
+ const pluginSlug = selector.pluginSlug.trim();
362
+ if (scope.orgs.map(normalizeOrgSlug).includes(orgSlug)) {
363
+ return true;
364
+ }
365
+ const normalizedScopeSelectors = scope.selectors.map((entry) => normalizeSelector(entry));
366
+ return selectorVariants({ orgSlug, catalogSlug, pluginSlug }).some(
367
+ (variant) => normalizedScopeSelectors.includes(variant)
368
+ );
369
+ }
370
+ function formatOutOfScopeMessage(selector) {
371
+ return [
372
+ `Plugin ${selector} is not in your catalog scope.`,
373
+ `Connect the org: ht plugin catalog connect org <slug>`,
374
+ `Connect one lib: ht plugin catalog connect plugin ${selector}`
375
+ ].join("\n");
376
+ }
377
+ function connectCatalogOrg(orgSlug, harnesstapDir = getHarnesstapDir()) {
378
+ const normalized = normalizeOrgSlug(orgSlug);
379
+ if (OPEN_CATALOG_ORG_ALIASES.includes(normalized)) {
380
+ throw new Error(`${DEFAULT_CATALOG_ORG_SLUG} is always included in the default catalog.`);
381
+ }
382
+ const current = loadCatalogSettings(harnesstapDir);
383
+ if (current.connectedOrgs.includes(normalized)) {
384
+ return current;
385
+ }
386
+ return saveCatalogSettings({
387
+ connectedOrgs: [...current.connectedOrgs, normalized]
388
+ }, harnesstapDir);
389
+ }
390
+ function disconnectCatalogOrg(orgSlug, harnesstapDir = getHarnesstapDir()) {
391
+ const normalized = normalizeOrgSlug(orgSlug);
392
+ if (OPEN_CATALOG_ORG_ALIASES.includes(normalized)) {
393
+ throw new Error(`Cannot disconnect the default catalog org (${DEFAULT_CATALOG_ORG_SLUG}).`);
394
+ }
395
+ const current = loadCatalogSettings(harnesstapDir);
396
+ return saveCatalogSettings({
397
+ connectedOrgs: current.connectedOrgs.filter((org) => org !== normalized)
398
+ }, harnesstapDir);
399
+ }
400
+ function connectCatalogPlugin(selector, harnesstapDir = getHarnesstapDir()) {
401
+ const normalized = normalizeSelector(selector);
402
+ const current = loadCatalogSettings(harnesstapDir);
403
+ if (current.connectedPlugins.includes(normalized)) {
404
+ return current;
405
+ }
406
+ return saveCatalogSettings({
407
+ connectedPlugins: [...current.connectedPlugins, normalized]
408
+ }, harnesstapDir);
409
+ }
410
+ function disconnectCatalogPlugin(selector, harnesstapDir = getHarnesstapDir()) {
411
+ const normalized = normalizeSelector(selector);
412
+ const current = loadCatalogSettings(harnesstapDir);
413
+ return saveCatalogSettings({
414
+ connectedPlugins: current.connectedPlugins.filter((entry) => entry !== normalized)
415
+ }, harnesstapDir);
416
+ }
417
+ function loadRegisteredCatalogs(harnesstapDir = getHarnesstapDir()) {
418
+ return loadCatalogSettings(harnesstapDir).registered;
419
+ }
420
+ function registerPublishCatalog(selector, harnesstapDir = getHarnesstapDir()) {
421
+ const parsed = parsePublishCatalogSelector(selector);
422
+ const current = loadCatalogSettings(harnesstapDir);
423
+ const key = publishCatalogKey(parsed);
424
+ const existing = current.registered.find((entry) => publishCatalogKey(entry) === key);
425
+ if (existing) {
426
+ if (parsed.account && !existing.account) {
427
+ const updated = { ...existing, account: parsed.account };
428
+ const registered = current.registered.map(
429
+ (entry) => publishCatalogKey(entry) === key ? updated : entry
430
+ );
431
+ const settings2 = saveCatalogSettings({
432
+ registered: sortRegisteredCatalogs(registered)
433
+ }, harnesstapDir);
434
+ return { settings: settings2, catalog: updated, created: false };
435
+ }
436
+ return { settings: current, catalog: existing, created: false };
437
+ }
438
+ const settings = saveCatalogSettings({
439
+ registered: sortRegisteredCatalogs([...current.registered, parsed])
440
+ }, harnesstapDir);
441
+ return { settings, catalog: parsed, created: true };
442
+ }
443
+ function unregisterPublishCatalog(selector, harnesstapDir = getHarnesstapDir()) {
444
+ const parsed = parsePublishCatalogSelector(selector);
445
+ const key = publishCatalogKey(parsed);
446
+ const current = loadCatalogSettings(harnesstapDir);
447
+ return saveCatalogSettings({
448
+ registered: current.registered.filter((entry) => publishCatalogKey(entry) !== key)
449
+ }, harnesstapDir);
450
+ }
451
+ function ensureRegisteredPublishCatalog(selector, opts, harnesstapDir = getHarnesstapDir()) {
452
+ const parsed = parsePublishCatalogSelector(selector);
453
+ const withAccount = opts?.account?.trim() ? { ...parsed, account: opts.account.trim() } : parsed;
454
+ const selectorLabel = formatPublishCatalogSelector(withAccount);
455
+ const result = registerPublishCatalog(selectorLabel, harnesstapDir);
456
+ return { catalog: result.catalog, created: result.created };
457
+ }
458
+
459
+ // src/config/cloud-accounts.ts
460
+ import fs from "fs";
461
+ import { join as join2 } from "path";
462
+ function getCloudAccountsPath() {
463
+ return join2(getHarnesstapDir(), "cloud-accounts.json");
464
+ }
465
+ async function loadCloudAccounts() {
466
+ const path = getCloudAccountsPath();
467
+ if (!fs.existsSync(path)) {
468
+ return { default_account: void 0, accounts: {} };
469
+ }
470
+ const raw = fs.readFileSync(path, "utf8");
471
+ try {
472
+ const parsed = JSON.parse(raw);
473
+ if (!parsed.accounts) parsed.accounts = {};
474
+ return parsed;
475
+ } catch (_error) {
476
+ return { default_account: void 0, accounts: {} };
477
+ }
478
+ }
479
+ async function writeStore(file) {
480
+ const dir = getHarnesstapDir();
481
+ fs.mkdirSync(dir, { recursive: true });
482
+ const path = getCloudAccountsPath();
483
+ fs.writeFileSync(path, JSON.stringify(file, null, 2), { encoding: "utf8" });
484
+ try {
485
+ fs.chmodSync(path, 384);
486
+ } catch (_error) {
487
+ }
488
+ }
489
+ async function saveCloudAccount(accountName, account) {
490
+ const store = await loadCloudAccounts();
491
+ store.accounts = store.accounts || {};
492
+ store.accounts[accountName] = account;
493
+ await writeStore(store);
494
+ }
495
+ async function setDefaultCloudAccount(accountName) {
496
+ const store = await loadCloudAccounts();
497
+ store.default_account = accountName ?? null;
498
+ await writeStore(store);
499
+ }
500
+ async function getCloudAccount(accountName) {
501
+ const store = await loadCloudAccounts();
502
+ const name = accountName ?? store.default_account ?? void 0;
503
+ if (!name) return { accountName: void 0, account: void 0 };
504
+ return { accountName: name, account: store.accounts ? store.accounts[name] : void 0 };
505
+ }
506
+ async function updateCloudAccount(accountName, patch) {
507
+ const store = await loadCloudAccounts();
508
+ store.accounts = store.accounts || {};
509
+ const existing = store.accounts[accountName] || {};
510
+ store.accounts[accountName] = { ...existing, ...patch };
511
+ await writeStore(store);
512
+ }
513
+ async function clearCloudTokens(accountName) {
514
+ const store = await loadCloudAccounts();
515
+ if (!store.accounts) return;
516
+ const account = store.accounts[accountName];
517
+ if (!account) return;
518
+ delete account.accessToken;
519
+ delete account.accessTokenExpiresAt;
520
+ delete account.refreshToken;
521
+ delete account.refreshTokenExpiresAt;
522
+ store.accounts[accountName] = account;
523
+ await writeStore(store);
524
+ }
525
+ async function removeCloudAccount(accountName) {
526
+ const store = await loadCloudAccounts();
527
+ if (store.accounts && accountName in store.accounts) {
528
+ delete store.accounts[accountName];
529
+ }
530
+ if (store.default_account === accountName) {
531
+ store.default_account = void 0;
532
+ }
533
+ await writeStore(store);
534
+ }
535
+
536
+ // src/services/cloud-api-version.ts
537
+ var CLI_VERSION_HEADER = "X-HarnessTap-CLI-Version";
538
+ var API_VERSION_HEADER = "X-HarnessTap-API-Version";
539
+ var CLIENT_API_VERSION = 1;
540
+ var AP_PACKAGE_MEDIA_TYPE = "application/vnd.harnesstap.ap-package+json";
541
+ var CliTooOldError = class extends Error {
542
+ minimumVersion;
543
+ constructor(minimumVersion, fix) {
544
+ super(
545
+ `Your HarnessTap CLI (${PACKAGE_VERSION}) is too old for this cloud API, which requires ${minimumVersion} or newer.
546
+ fix: ${fix}`
547
+ );
548
+ this.name = "CliTooOldError";
549
+ this.minimumVersion = minimumVersion;
550
+ }
551
+ };
552
+ function cloudRequestHeaders(extra) {
553
+ return {
554
+ ...extra,
555
+ [CLI_VERSION_HEADER]: PACKAGE_VERSION,
556
+ [API_VERSION_HEADER]: String(CLIENT_API_VERSION)
557
+ };
558
+ }
559
+ async function throwIfCliTooOld(response) {
560
+ if (response.status !== 426) return;
561
+ let minimumVersion = "a newer version";
562
+ let fix = "npm install -g harnesstap@latest";
563
+ try {
564
+ const body = await response.clone().json();
565
+ if (body.minimumVersion) minimumVersion = body.minimumVersion;
566
+ if (body.fix) fix = body.fix;
567
+ } catch {
568
+ }
569
+ throw new CliTooOldError(minimumVersion, fix);
570
+ }
571
+ async function cloudFetch(input, init) {
572
+ const response = await fetchWithTimeout(input, {
573
+ ...init,
574
+ headers: cloudRequestHeaders(Object.fromEntries(new Headers(init?.headers).entries()))
575
+ });
576
+ await throwIfCliTooOld(response);
577
+ return response;
578
+ }
579
+
580
+ // src/services/cloud-client.ts
581
+ var DEFAULT_DEVICE_SCOPES = ["read", "publish"];
582
+ var DEVICE_AUTH_PATH = "/cli/auth/device";
583
+ function deviceVerificationUri(baseUrl) {
584
+ return `${baseUrl.replace(/\/+$/, "")}${DEVICE_AUTH_PATH}`;
585
+ }
586
+ function isLoopbackHttpUrl(value) {
587
+ try {
588
+ const url = new URL(value);
589
+ return url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]");
590
+ } catch {
591
+ return false;
592
+ }
593
+ }
594
+ function resolveDeviceVerificationUris(baseUrl, device) {
595
+ const fallback = deviceVerificationUri(baseUrl);
596
+ const verificationUri = device.verification_uri?.trim() && !isLoopbackHttpUrl(device.verification_uri) ? device.verification_uri.trim() : fallback;
597
+ const completeFromApi = device.verification_uri_complete?.trim();
598
+ const verificationUriComplete = completeFromApi && !isLoopbackHttpUrl(completeFromApi) ? completeFromApi : `${verificationUri}?user_code=${encodeURIComponent(device.user_code)}`;
599
+ return {
600
+ verification_uri: verificationUri,
601
+ verification_uri_complete: verificationUriComplete
602
+ };
603
+ }
604
+ function apiUrl(baseUrl, path) {
605
+ const normalized = baseUrl.replace(/\/+$/, "");
606
+ return `${normalized}/api${path.startsWith("/") ? path : `/${path}`}`;
607
+ }
608
+ async function refreshCloudAccessToken(baseUrl, refreshToken) {
609
+ const response = await cloudFetch(apiUrl(baseUrl, "/cli/token/refresh"), {
610
+ method: "POST",
611
+ headers: { "content-type": "application/json" },
612
+ body: JSON.stringify({ refresh_token: refreshToken })
613
+ });
614
+ if (!response.ok) {
615
+ throw new Error(`Failed to refresh token: ${response.status}`);
616
+ }
617
+ return await response.json();
618
+ }
619
+ function extractApiErrorCode(body) {
620
+ if (body && typeof body === "object" && "error" in body) {
621
+ return body.error?.code;
622
+ }
623
+ return void 0;
624
+ }
625
+ function parseApiError(body) {
626
+ if (body && typeof body === "object" && "error" in body) {
627
+ const error = body.error;
628
+ if (error?.message) return error.message;
629
+ if (error?.code) return error.code;
630
+ }
631
+ return JSON.stringify(body);
632
+ }
633
+ async function readResponseBody(response) {
634
+ const text = await response.text();
635
+ if (!text.trim()) {
636
+ return { body: {}, text: "" };
637
+ }
638
+ try {
639
+ return { body: JSON.parse(text), text };
640
+ } catch {
641
+ return { body: {}, text };
642
+ }
643
+ }
644
+ function describeApiFailure(response, body, text) {
645
+ const parsed = parseApiError(body);
646
+ if (parsed !== "{}") {
647
+ return `${response.status} ${parsed}`;
648
+ }
649
+ const trimmed = text.trim();
650
+ if (trimmed) {
651
+ const preview = trimmed.length > 240 ? `${trimmed.slice(0, 240)}...` : trimmed;
652
+ return `${response.status} ${preview}`;
653
+ }
654
+ return `${response.status} empty response (try again)`;
655
+ }
656
+ function isTransientPollFailure(response, body, text) {
657
+ if (response.status >= 500) return true;
658
+ if (response.status === 408 || response.status === 425) return true;
659
+ if (!response.ok && !extractApiErrorCode(body) && !text.trim()) return true;
660
+ return false;
661
+ }
662
+ function toSlug(value) {
663
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
664
+ }
665
+ function nextPublishVersion(latestVersion) {
666
+ if (!latestVersion) return "1.0.0";
667
+ const match = latestVersion.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)/);
668
+ if (!match) return "1.0.0";
669
+ return `${match[1]}.${match[2]}.${Number(match[3]) + 1}`;
670
+ }
671
+ function summaryFromPackage(apPackage, pluginName) {
672
+ const pluginJson = apPackage.files["plugin.json"];
673
+ if (pluginJson?.encoding === "utf8") {
674
+ try {
675
+ const manifest = JSON.parse(pluginJson.content);
676
+ if (typeof manifest.description === "string" && manifest.description.trim()) {
677
+ return manifest.description.trim();
678
+ }
679
+ } catch {
680
+ }
681
+ }
682
+ return `Published plugin ${pluginName}`;
683
+ }
684
+ async function requestDeviceCode(baseUrl, opts) {
685
+ const response = await cloudFetch(apiUrl(baseUrl, "/cli/device/code"), {
686
+ method: "POST",
687
+ headers: { "content-type": "application/json" },
688
+ body: JSON.stringify({ scopes: opts?.scopes ?? [...DEFAULT_DEVICE_SCOPES] })
689
+ });
690
+ if (!response.ok) {
691
+ const { body, text } = await readResponseBody(response);
692
+ if (response.status === 503 || /no available server/i.test(text)) {
693
+ throw new Error(
694
+ "HarnessTap Cloud is temporarily unavailable. Try again in a few minutes."
695
+ );
696
+ }
697
+ throw new Error(`Failed to request device code: ${describeApiFailure(response, body, text)}`);
698
+ }
699
+ const device = await response.json();
700
+ const uris = resolveDeviceVerificationUris(baseUrl, device);
701
+ return {
702
+ ...device,
703
+ verification_uri: uris.verification_uri,
704
+ verification_uri_complete: uris.verification_uri_complete
705
+ };
706
+ }
707
+ function parseRetryAfterMs(response, fallbackMs) {
708
+ const retryAfter = response.headers.get("retry-after")?.trim();
709
+ if (!retryAfter) return fallbackMs;
710
+ const seconds = Number(retryAfter);
711
+ if (Number.isFinite(seconds) && seconds > 0) {
712
+ return seconds * 1e3;
713
+ }
714
+ const retryAt = Date.parse(retryAfter);
715
+ if (Number.isFinite(retryAt)) {
716
+ return Math.max(0, retryAt - Date.now());
717
+ }
718
+ return fallbackMs;
719
+ }
720
+ async function pollDeviceTokenOnce(baseUrl, deviceCode, opts) {
721
+ const pollIntervalMs = opts?.intervalMs ?? 5e3;
722
+ const response = await cloudFetch(apiUrl(baseUrl, "/cli/device/token"), {
723
+ method: "POST",
724
+ headers: { "content-type": "application/json" },
725
+ body: JSON.stringify({ device_code: deviceCode })
726
+ });
727
+ if (response.ok) {
728
+ const { body: body2 } = await readResponseBody(response);
729
+ return { status: "authorized", token: body2 };
730
+ }
731
+ const { body, text } = await readResponseBody(response);
732
+ const code = extractApiErrorCode(body);
733
+ if (code === "authorization_pending") {
734
+ return { status: "pending", intervalMs: pollIntervalMs };
735
+ }
736
+ if (code === "slow_down") {
737
+ return { status: "pending", intervalMs: pollIntervalMs + 5e3 };
738
+ }
739
+ if (code === "rate_limit_exceeded") {
740
+ return {
741
+ status: "pending",
742
+ intervalMs: parseRetryAfterMs(response, pollIntervalMs)
743
+ };
744
+ }
745
+ if (isTransientPollFailure(response, body, text)) {
746
+ return { status: "pending", intervalMs: pollIntervalMs };
747
+ }
748
+ return {
749
+ status: "error",
750
+ message: `Failed to poll device token: ${describeApiFailure(response, body, text)}`
751
+ };
752
+ }
753
+ async function pollDeviceToken(baseUrl, deviceCode, opts) {
754
+ let pollIntervalMs = (opts?.interval ?? 5) * 1e3;
755
+ const maxPolls = opts?.maxPolls ?? 120;
756
+ for (let attempt = 0; attempt < maxPolls; attempt += 1) {
757
+ const result = await pollDeviceTokenOnce(baseUrl, deviceCode, {
758
+ intervalMs: pollIntervalMs
759
+ });
760
+ if (result.status === "authorized") {
761
+ return result.token;
762
+ }
763
+ if (result.status === "error") {
764
+ throw new Error(result.message);
765
+ }
766
+ pollIntervalMs = result.intervalMs;
767
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
768
+ }
769
+ throw new Error("Timed out polling device token");
770
+ }
771
+ function createCloudClient(opts) {
772
+ const state = {
773
+ baseUrl: opts.baseUrl.replace(/\/+$/, ""),
774
+ token: opts.token ? { ...opts.token } : void 0
775
+ };
776
+ async function ensureTokenValid() {
777
+ if (!state.token) throw new Error("Not authenticated");
778
+ const now = Math.floor(Date.now() / 1e3);
779
+ if (state.token.expires_at == null || state.token.expires_at > now + 5) return;
780
+ if (!state.token.refresh_token) throw new Error("No refresh token available");
781
+ const data = await refreshCloudAccessToken(state.baseUrl, state.token.refresh_token);
782
+ const expiresIn = data.expires_in ?? 3600;
783
+ const expiresAt = Math.floor(Date.now() / 1e3) + expiresIn;
784
+ state.token = {
785
+ access_token: data.access_token,
786
+ refresh_token: data.refresh_token || state.token.refresh_token,
787
+ expires_at: expiresAt
788
+ };
789
+ if (opts.onTokenRefreshed) {
790
+ await opts.onTokenRefreshed({
791
+ access_token: state.token.access_token,
792
+ refresh_token: state.token.refresh_token,
793
+ expires_at: expiresAt
794
+ });
795
+ }
796
+ }
797
+ async function authFetch(input, init) {
798
+ await ensureTokenValid();
799
+ const headers = new Headers(init?.headers);
800
+ if (!state.token) throw new Error("Missing auth token");
801
+ headers.set("Authorization", `Bearer ${state.token.access_token}`);
802
+ return cloudFetch(input, { ...init, headers });
803
+ }
804
+ async function listPublishedPlugins(orgId) {
805
+ const response = await authFetch(`${apiUrl(state.baseUrl, "/plugins")}?orgId=${encodeURIComponent(orgId)}`);
806
+ if (!response.ok) {
807
+ throw new Error(`list plugins failed: ${response.status}`);
808
+ }
809
+ const data = await response.json();
810
+ return data.plugins ?? [];
811
+ }
812
+ async function createPublishedPlugin(input) {
813
+ const response = await authFetch(apiUrl(state.baseUrl, "/plugins"), {
814
+ method: "POST",
815
+ headers: { "content-type": "application/json" },
816
+ body: JSON.stringify({
817
+ orgId: input.orgId,
818
+ name: input.name,
819
+ slug: input.slug,
820
+ summary: input.summary,
821
+ catalogSlug: input.catalogSlug
822
+ })
823
+ });
824
+ const body = await response.json().catch(() => ({}));
825
+ if (!response.ok) {
826
+ throw new Error(`create plugin failed: ${response.status} ${parseApiError(body)}`);
827
+ }
828
+ return body.plugin;
829
+ }
830
+ async function publishVersion(input) {
831
+ const response = await authFetch(apiUrl(state.baseUrl, "/plugins"), {
832
+ method: "PATCH",
833
+ headers: { "content-type": "application/json" },
834
+ body: JSON.stringify({
835
+ orgId: input.orgId,
836
+ pluginId: input.pluginId,
837
+ version: input.version,
838
+ summary: input.summary,
839
+ package: input.apPackage
840
+ })
841
+ });
842
+ const body = await response.json().catch(() => ({}));
843
+ if (!response.ok) {
844
+ throw new Error(`publish failed: ${response.status} ${parseApiError(body)}`);
845
+ }
846
+ return body;
847
+ }
848
+ return {
849
+ async whoami() {
850
+ const response = await authFetch(apiUrl(state.baseUrl, "/me"));
851
+ if (!response.ok) throw new Error(`whoami failed: ${response.status}`);
852
+ return await response.json();
853
+ },
854
+ async listOrgs() {
855
+ const response = await authFetch(apiUrl(state.baseUrl, "/me/orgs"));
856
+ if (!response.ok) throw new Error(`listOrgs failed: ${response.status}`);
857
+ const data = await response.json();
858
+ return data.orgs ?? [];
859
+ },
860
+ async planPluginPublishVersion(metadata) {
861
+ const orgSlug = String(metadata.org_slug ?? "");
862
+ const catalogSlug = String(metadata.catalog_slug ?? "default");
863
+ const pluginName = String(metadata.plugin_name ?? "");
864
+ if (!orgSlug || !pluginName) {
865
+ throw new Error("publish metadata must include org_slug and plugin_name.");
866
+ }
867
+ const orgs = await this.listOrgs();
868
+ const org = orgs.find((entry) => String(entry.slug) === orgSlug);
869
+ if (!org || typeof org.id !== "string") {
870
+ throw new Error(`Organization not found: ${orgSlug}`);
871
+ }
872
+ const slug = toSlug(pluginName);
873
+ const publishedPlugin = (await listPublishedPlugins(org.id)).find(
874
+ (entry) => entry.slug === slug && entry.catalogSlug === catalogSlug
875
+ );
876
+ return { nextVersion: nextPublishVersion(publishedPlugin?.latestVersion) };
877
+ },
878
+ async publishPackage(metadata, apPackage) {
879
+ const orgSlug = String(metadata.org_slug ?? "");
880
+ const catalogSlug = String(metadata.catalog_slug ?? "default");
881
+ const pluginName = String(metadata.plugin_name ?? "");
882
+ if (!orgSlug || !pluginName) {
883
+ throw new Error("publish metadata must include org_slug and plugin_name.");
884
+ }
885
+ const orgs = await this.listOrgs();
886
+ const org = orgs.find((entry) => String(entry.slug) === orgSlug);
887
+ if (!org || typeof org.id !== "string") {
888
+ throw new Error(`Organization not found: ${orgSlug}`);
889
+ }
890
+ const slug = toSlug(pluginName);
891
+ const summary = summaryFromPackage(apPackage, pluginName);
892
+ let publishedPlugin = (await listPublishedPlugins(org.id)).find(
893
+ (entry) => entry.slug === slug && entry.catalogSlug === catalogSlug
894
+ );
895
+ if (!publishedPlugin) {
896
+ try {
897
+ publishedPlugin = await createPublishedPlugin({
898
+ orgId: org.id,
899
+ name: pluginName,
900
+ slug,
901
+ summary,
902
+ catalogSlug
903
+ });
904
+ } catch (error) {
905
+ const message = error instanceof Error ? error.message : String(error);
906
+ if (!message.includes("409")) {
907
+ throw error;
908
+ }
909
+ publishedPlugin = (await listPublishedPlugins(org.id)).find(
910
+ (entry) => entry.slug === slug && entry.catalogSlug === catalogSlug
911
+ );
912
+ if (!publishedPlugin) {
913
+ throw error;
914
+ }
915
+ }
916
+ }
917
+ const version = nextPublishVersion(publishedPlugin.latestVersion);
918
+ const published = await publishVersion({
919
+ orgId: org.id,
920
+ pluginId: publishedPlugin.id,
921
+ version,
922
+ summary,
923
+ apPackage
924
+ });
925
+ return {
926
+ id: publishedPlugin.id,
927
+ version: published.version.version,
928
+ url: `${state.baseUrl}/catalogs/${catalogSlug}/${slug}`
929
+ };
930
+ },
931
+ async deletePublishedPlugin(input) {
932
+ const response = await authFetch(
933
+ `${apiUrl(state.baseUrl, `/plugins/${encodeURIComponent(input.pluginId)}`)}?orgId=${encodeURIComponent(input.orgId)}`,
934
+ { method: "DELETE" }
935
+ );
936
+ const body = await response.json().catch(() => ({}));
937
+ if (!response.ok) {
938
+ throw new Error(`delete plugin failed: ${response.status} ${parseApiError(body)}`);
939
+ }
940
+ },
941
+ async revokeRefreshToken() {
942
+ state.token = void 0;
943
+ return true;
944
+ },
945
+ _state: state
946
+ };
947
+ }
948
+
949
+ // src/services/cloud-account-auth.ts
950
+ var ACCESS_TOKEN_SKEW_SECONDS = 60;
951
+ function parseExpiresAtSeconds(value) {
952
+ if (typeof value === "number" && Number.isFinite(value)) {
953
+ return value;
954
+ }
955
+ if (typeof value === "string" && value.trim().length > 0) {
956
+ const asNumber = Number(value);
957
+ if (Number.isFinite(asNumber)) {
958
+ return asNumber;
959
+ }
960
+ const parsed = Date.parse(value);
961
+ if (Number.isFinite(parsed)) {
962
+ return Math.floor(parsed / 1e3);
963
+ }
964
+ }
965
+ return void 0;
966
+ }
967
+ function accessTokenNeedsRefresh(account, nowSeconds = Math.floor(Date.now() / 1e3)) {
968
+ if (!account.accessToken) {
969
+ return true;
970
+ }
971
+ const expiresAt = parseExpiresAtSeconds(account.accessTokenExpiresAt);
972
+ if (expiresAt == null) {
973
+ return false;
974
+ }
975
+ return expiresAt <= nowSeconds + ACCESS_TOKEN_SKEW_SECONDS;
976
+ }
977
+ function accountFromRefresh(account, refreshed, nowSeconds) {
978
+ return {
979
+ ...account,
980
+ accessToken: refreshed.access_token,
981
+ refreshToken: refreshed.refresh_token ?? account.refreshToken,
982
+ accessTokenExpiresAt: nowSeconds + (refreshed.expires_in ?? 3600),
983
+ ...refreshed.orgId ? { orgId: refreshed.orgId } : {},
984
+ ...refreshed.orgSlug ? { orgSlug: refreshed.orgSlug } : {},
985
+ ...refreshed.scopes ? { scopes: refreshed.scopes } : {}
986
+ };
987
+ }
988
+ async function ensureCloudAccountAccess(accountName) {
989
+ const loaded = await getCloudAccount(accountName);
990
+ const name = loaded.accountName;
991
+ const account = loaded.account;
992
+ if (!name || !account) {
993
+ return null;
994
+ }
995
+ if (!account.accessToken && !account.refreshToken) {
996
+ return null;
997
+ }
998
+ const nowSeconds = Math.floor(Date.now() / 1e3);
999
+ if (!accessTokenNeedsRefresh(account, nowSeconds)) {
1000
+ return {
1001
+ accountName: name,
1002
+ account,
1003
+ accessToken: account.accessToken
1004
+ };
1005
+ }
1006
+ if (!account.refreshToken) {
1007
+ if (account.accessToken) {
1008
+ return {
1009
+ accountName: name,
1010
+ account,
1011
+ accessToken: account.accessToken
1012
+ };
1013
+ }
1014
+ return null;
1015
+ }
1016
+ try {
1017
+ const refreshed = await refreshCloudAccessToken(
1018
+ account.cloudBaseUrl,
1019
+ account.refreshToken
1020
+ );
1021
+ const next = accountFromRefresh(account, refreshed, nowSeconds);
1022
+ await updateCloudAccount(name, next);
1023
+ return {
1024
+ accountName: name,
1025
+ account: next,
1026
+ accessToken: next.accessToken
1027
+ };
1028
+ } catch (error) {
1029
+ const message = error instanceof Error ? error.message : String(error);
1030
+ if (/Failed to refresh token: (400|401)/.test(message)) {
1031
+ await clearCloudTokens(name);
1032
+ return null;
1033
+ }
1034
+ if (account.accessToken) {
1035
+ return {
1036
+ accountName: name,
1037
+ account,
1038
+ accessToken: account.accessToken
1039
+ };
1040
+ }
1041
+ return null;
1042
+ }
1043
+ }
1044
+ async function forceRefreshCloudAccountAccess(accountName) {
1045
+ const loaded = await getCloudAccount(accountName);
1046
+ const name = loaded.accountName;
1047
+ const account = loaded.account;
1048
+ if (!name || !account?.refreshToken) {
1049
+ return null;
1050
+ }
1051
+ const nowSeconds = Math.floor(Date.now() / 1e3);
1052
+ try {
1053
+ const refreshed = await refreshCloudAccessToken(
1054
+ account.cloudBaseUrl,
1055
+ account.refreshToken
1056
+ );
1057
+ const next = accountFromRefresh(account, refreshed, nowSeconds);
1058
+ await updateCloudAccount(name, next);
1059
+ return {
1060
+ accountName: name,
1061
+ account: next,
1062
+ accessToken: next.accessToken
1063
+ };
1064
+ } catch (error) {
1065
+ const message = error instanceof Error ? error.message : String(error);
1066
+ if (/Failed to refresh token: (400|401)/.test(message)) {
1067
+ await clearCloudTokens(name);
1068
+ }
1069
+ return null;
1070
+ }
1071
+ }
1072
+ async function createPersistingCloudClient(accountName) {
1073
+ const ensured = await ensureCloudAccountAccess(accountName);
1074
+ if (!ensured) {
1075
+ return null;
1076
+ }
1077
+ const { account } = ensured;
1078
+ const client = createCloudClient({
1079
+ baseUrl: account.cloudBaseUrl,
1080
+ token: {
1081
+ access_token: ensured.accessToken,
1082
+ refresh_token: account.refreshToken,
1083
+ expires_at: parseExpiresAtSeconds(account.accessTokenExpiresAt)
1084
+ },
1085
+ onTokenRefreshed: async (token) => {
1086
+ await updateCloudAccount(ensured.accountName, {
1087
+ accessToken: token.access_token,
1088
+ refreshToken: token.refresh_token ?? account.refreshToken,
1089
+ accessTokenExpiresAt: token.expires_at
1090
+ });
1091
+ }
1092
+ });
1093
+ return { accountName: ensured.accountName, client };
1094
+ }
1095
+
1096
+ export {
1097
+ DEFAULT_CATALOG_SLUG,
1098
+ parsePluginSelector,
1099
+ formatPublishedSelector,
1100
+ formatPublishedSelectorWithVersion,
1101
+ formatCanonicalPublishedSelector,
1102
+ formatCanonicalPublishedSelectorWithVersion,
1103
+ resolvedRemotePluginFromCatalog,
1104
+ resolveRemotePluginSelector,
1105
+ DEFAULT_CATALOG_ORG_SLUG,
1106
+ publishCatalogKey,
1107
+ parsePublishCatalogSelector,
1108
+ formatPublishCatalogSelector,
1109
+ resolveCloudBaseUrl,
1110
+ loadCatalogSettings,
1111
+ resolveCatalogScope,
1112
+ isPublicCatalogEnabled,
1113
+ formatCatalogScopeLabel,
1114
+ isSelectorInCatalogScope,
1115
+ formatOutOfScopeMessage,
1116
+ connectCatalogOrg,
1117
+ disconnectCatalogOrg,
1118
+ connectCatalogPlugin,
1119
+ disconnectCatalogPlugin,
1120
+ loadRegisteredCatalogs,
1121
+ registerPublishCatalog,
1122
+ unregisterPublishCatalog,
1123
+ ensureRegisteredPublishCatalog,
1124
+ loadCloudAccounts,
1125
+ saveCloudAccount,
1126
+ setDefaultCloudAccount,
1127
+ getCloudAccount,
1128
+ updateCloudAccount,
1129
+ removeCloudAccount,
1130
+ AP_PACKAGE_MEDIA_TYPE,
1131
+ cloudFetch,
1132
+ deviceVerificationUri,
1133
+ requestDeviceCode,
1134
+ pollDeviceToken,
1135
+ createCloudClient,
1136
+ ensureCloudAccountAccess,
1137
+ forceRefreshCloudAccountAccess,
1138
+ createPersistingCloudClient
1139
+ };
1140
+ //# sourceMappingURL=chunk-ZY2MZ2KQ.js.map