@atlaskit/ads-cli 0.8.2 → 0.10.0

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.
@@ -0,0 +1,500 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.runInitCommand = void 0;
8
+ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
9
+ var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
10
+ var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
11
+ var _nodeChild_process = require("node:child_process");
12
+ var _nodeFs = require("node:fs");
13
+ var _nodePath = _interopRequireDefault(require("node:path"));
14
+ var _createErrorEnvelope = require("../envelope/create-error-envelope");
15
+ var _createSuccessEnvelope = require("../envelope/create-success-envelope");
16
+ var _writeHumanError = require("../output/write-human-error");
17
+ var _writeJsonEnvelope = require("../output/write-json-envelope");
18
+ var _types = require("../types");
19
+ var _cliMetadata = require("./cli-metadata");
20
+ var _updateAgentsFile = require("./update-agents-file");
21
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
22
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
23
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
24
+ var SKILL_ENTRYPOINT = 'SKILL.md';
25
+ var SKILLS = [{
26
+ name: 'atlassian-design-system',
27
+ displayName: 'ADS',
28
+ relativePath: '.agents/skills/atlassian-design-system',
29
+ requiredFiles: [SKILL_ENTRYPOINT]
30
+ }, {
31
+ name: 'ui-styling-standard',
32
+ displayName: 'UI Styling Standard',
33
+ relativePath: '.agents/skills/ui-styling-standard',
34
+ requiredFiles: [SKILL_ENTRYPOINT]
35
+ }, {
36
+ name: 'a11y-foundation',
37
+ displayName: 'Accessibility Foundation',
38
+ relativePath: '.agents/skills/a11y-foundation',
39
+ requiredFiles: [SKILL_ENTRYPOINT]
40
+ }];
41
+ var ADS_SKILL = SKILLS[0];
42
+ var SKILL_GET_STARTED_RELATIVE_PATH = "".concat(ADS_SKILL.relativePath, "/references/get-started.md");
43
+ var GIT_MARKER = '.git';
44
+ var SKILLS_INSTALLER_PACKAGE = '@atlassian/skills';
45
+ var SKILLS_INSTALLER_UNAVAILABLE_REASON = 'skills-installer-unavailable';
46
+ var SKILLS_INSTALLER_UNAVAILABLE_ERROR_CODES = new Set(['EACCES', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'ENOENT', 'ENOTFOUND', 'ETIMEDOUT']);
47
+ var defaultPathExists = function defaultPathExists(target) {
48
+ try {
49
+ (0, _nodeFs.lstatSync)(target);
50
+ return true;
51
+ } catch (error) {
52
+ if (error.code === 'ENOENT') {
53
+ return false;
54
+ }
55
+ throw error;
56
+ }
57
+ };
58
+ var defaultRunProcess = function defaultRunProcess(_ref) {
59
+ var command = _ref.command,
60
+ args = _ref.args,
61
+ cwd = _ref.cwd,
62
+ capture = _ref.capture;
63
+ var result = (0, _nodeChild_process.spawnSync)(command, args, {
64
+ cwd: cwd,
65
+ encoding: 'utf8',
66
+ stdio: capture ? 'pipe' : 'inherit'
67
+ });
68
+ return {
69
+ status: result.status,
70
+ stdout: typeof result.stdout === 'string' ? result.stdout : '',
71
+ stderr: typeof result.stderr === 'string' ? result.stderr : '',
72
+ error: result.error
73
+ };
74
+ };
75
+ var processFailureMessage = function processFailureMessage(result, fallback) {
76
+ var _result$error;
77
+ var details = result.stderr.trim() || ((_result$error = result.error) === null || _result$error === void 0 ? void 0 : _result$error.message);
78
+ return details ? "".concat(fallback, ": ").concat(details) : fallback;
79
+ };
80
+ var isSkillsInstallerUnavailableFailure = function isSkillsInstallerUnavailableFailure(result) {
81
+ var _result$error2, _result$error$message, _result$error3;
82
+ if (result.status === null || (_result$error2 = result.error) !== null && _result$error2 !== void 0 && _result$error2.code && SKILLS_INSTALLER_UNAVAILABLE_ERROR_CODES.has(result.error.code)) {
83
+ return true;
84
+ }
85
+ var details = "".concat(result.stdout, "\n").concat(result.stderr, "\n").concat((_result$error$message = (_result$error3 = result.error) === null || _result$error3 === void 0 ? void 0 : _result$error3.message) !== null && _result$error$message !== void 0 ? _result$error$message : '').toLowerCase();
86
+ if (!details.trim()) {
87
+ return true;
88
+ }
89
+ return ['401 unauthorized', '403 forbidden', '404 not found', 'authentication required', 'could not resolve', 'e401', 'e403', 'e404', 'eneedauth', 'failed to fetch', 'network error', 'not in this registry', 'registry unavailable', 'unable to authenticate', 'unable to resolve'].some(function (message) {
90
+ return details.includes(message);
91
+ });
92
+ };
93
+ var createNotInstalledSkillResults = function createNotInstalledSkillResults(reason) {
94
+ return SKILLS.map(function (skillDefinition) {
95
+ return {
96
+ name: skillDefinition.name,
97
+ status: 'not-installed',
98
+ path: skillDefinition.relativePath,
99
+ reason: reason
100
+ };
101
+ });
102
+ };
103
+ var findRepositoryRoot = function findRepositoryRoot(cwd) {
104
+ var current = _nodePath.default.resolve(cwd);
105
+ while (true) {
106
+ if (defaultPathExists(_nodePath.default.join(current, GIT_MARKER))) {
107
+ return current;
108
+ }
109
+ var parent = _nodePath.default.dirname(current);
110
+ if (parent === current) {
111
+ return undefined;
112
+ }
113
+ current = parent;
114
+ }
115
+ };
116
+ var writeUsageError = function writeUsageError(_ref2) {
117
+ var message = _ref2.message,
118
+ json = _ref2.json,
119
+ writer = _ref2.writer;
120
+ if (json) {
121
+ (0, _writeJsonEnvelope.writeJsonEnvelope)({
122
+ envelope: (0, _createErrorEnvelope.createErrorEnvelope)({
123
+ command: 'init',
124
+ code: 'USAGE_ERROR',
125
+ message: message
126
+ }),
127
+ writer: writer
128
+ });
129
+ } else {
130
+ (0, _writeHumanError.writeHumanError)({
131
+ message: message,
132
+ writer: writer
133
+ });
134
+ writer.err('Usage: init');
135
+ }
136
+ return _types.ExitCode.UsageError;
137
+ };
138
+ var validateInput = function validateInput(input) {
139
+ if (input.positionals.length > 0) {
140
+ return '`init` does not accept positional arguments.';
141
+ }
142
+ var allowedFlags = new Set(['json']);
143
+ var unknownFlag = Object.keys(input.flags).find(function (flag) {
144
+ return !allowedFlags.has(flag);
145
+ });
146
+ if (unknownFlag) {
147
+ return "Unknown flag \"--".concat(unknownFlag, "\".");
148
+ }
149
+ return undefined;
150
+ };
151
+ var writeAgentsFileResult = function writeAgentsFileResult(_ref3) {
152
+ var result = _ref3.result,
153
+ writer = _ref3.writer;
154
+ switch (result.status) {
155
+ case 'created':
156
+ writer.out("\u2713 Created ".concat(_updateAgentsFile.AGENTS_FILE_RELATIVE_PATH, " with ADS setup guidance"));
157
+ return;
158
+ case 'appended':
159
+ writer.out("\u2713 Appended ADS setup guidance to ".concat(_updateAgentsFile.AGENTS_FILE_RELATIVE_PATH));
160
+ return;
161
+ case 'updated':
162
+ writer.out("\u2713 Updated ADS setup guidance in ".concat(_updateAgentsFile.AGENTS_FILE_RELATIVE_PATH));
163
+ return;
164
+ case 'already-current':
165
+ writer.out("\u2713 ADS setup guidance already current in ".concat(_updateAgentsFile.AGENTS_FILE_RELATIVE_PATH));
166
+ return;
167
+ case 'not-written':
168
+ writer.out("\u2013 ".concat(_updateAgentsFile.AGENTS_FILE_RELATIVE_PATH, " not updated because the current directory is not in a Git repository"));
169
+ }
170
+ };
171
+ var runInitCommand = exports.runInitCommand = /*#__PURE__*/function () {
172
+ var _ref5 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(_ref4) {
173
+ var input, json, writer, invocation, cwd, usageError, projectRoot, skills, agentsMd, repositorySetupErrors, npxCommand, skillsInstallerUnavailable, skillHumanOutput, _loop, _i, _SKILLS, skillResultsByName, _iterator, _step, line, installedSkills, _adsSkillInstalled, atlasCwd, atlasPluginStatus, _atlasCheck$error, atlasCheck, installResult, verification, adsSkillInstalled, nextStep, data;
174
+ return _regenerator.default.wrap(function (_context2) {
175
+ while (1) switch (_context2.prev = _context2.next) {
176
+ case 0:
177
+ input = _ref4.input, json = _ref4.json, writer = _ref4.writer, invocation = _ref4.invocation, cwd = _ref4.cwd;
178
+ usageError = validateInput(input);
179
+ if (!usageError) {
180
+ _context2.next = 1;
181
+ break;
182
+ }
183
+ return _context2.abrupt("return", writeUsageError({
184
+ message: usageError,
185
+ json: json,
186
+ writer: writer
187
+ }));
188
+ case 1:
189
+ projectRoot = findRepositoryRoot(cwd);
190
+ skills = [];
191
+ repositorySetupErrors = [];
192
+ if (projectRoot) {
193
+ _context2.next = 2;
194
+ break;
195
+ }
196
+ skills.push.apply(skills, (0, _toConsumableArray2.default)(createNotInstalledSkillResults('not-in-git-repository')));
197
+ if (!json) {
198
+ writer.out('– Repository-local skills not installed because the current directory is not in a Git repository');
199
+ }
200
+ agentsMd = {
201
+ status: 'not-written',
202
+ path: _updateAgentsFile.AGENTS_FILE_RELATIVE_PATH,
203
+ reason: 'not-in-git-repository'
204
+ };
205
+ if (!json) {
206
+ writeAgentsFileResult({
207
+ result: agentsMd,
208
+ writer: writer
209
+ });
210
+ }
211
+ _context2.next = 7;
212
+ break;
213
+ case 2:
214
+ npxCommand = process.platform === 'win32' ? 'npx.cmd' : 'npx';
215
+ skillsInstallerUnavailable = false;
216
+ skillHumanOutput = [];
217
+ _loop = /*#__PURE__*/_regenerator.default.mark(function _loop() {
218
+ var skillDefinition, skillPath, skillEntrypoint, skillPathExists, skillEntrypointExists, isCurrent, skillResult, result, missingRequiredFile, missingRelativePath, statusMessage, _t;
219
+ return _regenerator.default.wrap(function (_context) {
220
+ while (1) switch (_context.prev = _context.next) {
221
+ case 0:
222
+ skillDefinition = _SKILLS[_i];
223
+ _context.prev = 1;
224
+ skillPath = _nodePath.default.join(projectRoot, skillDefinition.relativePath);
225
+ skillEntrypoint = _nodePath.default.join(skillPath, SKILL_ENTRYPOINT);
226
+ skillPathExists = defaultPathExists(skillPath);
227
+ skillEntrypointExists = defaultPathExists(skillEntrypoint);
228
+ isCurrent = skillDefinition.requiredFiles.every(function (requiredFile) {
229
+ return defaultPathExists(_nodePath.default.join(skillPath, requiredFile));
230
+ });
231
+ if (!(skillPathExists && !skillEntrypointExists)) {
232
+ _context.next = 2;
233
+ break;
234
+ }
235
+ throw new Error("Cannot install the ".concat(skillDefinition.displayName, " skill because ").concat(skillDefinition.relativePath, " already exists without a ").concat(SKILL_ENTRYPOINT, ". Move or remove it, then run init again."));
236
+ case 2:
237
+ if (!isCurrent) {
238
+ _context.next = 3;
239
+ break;
240
+ }
241
+ skillResult = {
242
+ name: skillDefinition.name,
243
+ status: 'already-installed',
244
+ path: skillDefinition.relativePath
245
+ };
246
+ _context.next = 7;
247
+ break;
248
+ case 3:
249
+ result = defaultRunProcess({
250
+ command: npxCommand,
251
+ args: ['--yes', SKILLS_INSTALLER_PACKAGE, 'add', skillDefinition.name, '--universal', '--yes'],
252
+ cwd: projectRoot,
253
+ capture: true
254
+ });
255
+ if (!(result.status !== 0)) {
256
+ _context.next = 5;
257
+ break;
258
+ }
259
+ if (!isSkillsInstallerUnavailableFailure(result)) {
260
+ _context.next = 4;
261
+ break;
262
+ }
263
+ skillsInstallerUnavailable = true;
264
+ return _context.abrupt("return", 1);
265
+ case 4:
266
+ throw new Error(processFailureMessage(result, "Failed to install the ".concat(skillDefinition.displayName, " skill")));
267
+ case 5:
268
+ missingRequiredFile = skillDefinition.requiredFiles.find(function (requiredFile) {
269
+ return !defaultPathExists(_nodePath.default.join(skillPath, requiredFile));
270
+ });
271
+ if (!missingRequiredFile) {
272
+ _context.next = 6;
273
+ break;
274
+ }
275
+ missingRelativePath = "".concat(skillDefinition.relativePath, "/").concat(missingRequiredFile);
276
+ throw new Error("The skill installer completed without creating ".concat(missingRelativePath, "."));
277
+ case 6:
278
+ skillResult = {
279
+ name: skillDefinition.name,
280
+ status: skillEntrypointExists ? 'updated' : 'installed',
281
+ path: skillDefinition.relativePath
282
+ };
283
+ case 7:
284
+ skills.push(skillResult);
285
+ if (!json) {
286
+ statusMessage = skillResult.status === 'already-installed' ? 'already set up' : skillResult.status;
287
+ skillHumanOutput.push("\u2713 ".concat(skillDefinition.displayName, " skill ").concat(statusMessage, " at ").concat(skillDefinition.relativePath));
288
+ }
289
+ _context.next = 9;
290
+ break;
291
+ case 8:
292
+ _context.prev = 8;
293
+ _t = _context["catch"](1);
294
+ repositorySetupErrors.push(_t instanceof Error ? _t : new Error("Failed to set up the ".concat(skillDefinition.displayName, " skill.")));
295
+ case 9:
296
+ case "end":
297
+ return _context.stop();
298
+ }
299
+ }, _loop, null, [[1, 8]]);
300
+ });
301
+ _i = 0, _SKILLS = SKILLS;
302
+ case 3:
303
+ if (!(_i < _SKILLS.length)) {
304
+ _context2.next = 6;
305
+ break;
306
+ }
307
+ return _context2.delegateYield(_loop(), "t0", 4);
308
+ case 4:
309
+ if (!_context2.t0) {
310
+ _context2.next = 5;
311
+ break;
312
+ }
313
+ return _context2.abrupt("continue", 6);
314
+ case 5:
315
+ _i++;
316
+ _context2.next = 3;
317
+ break;
318
+ case 6:
319
+ if (skillsInstallerUnavailable) {
320
+ skillResultsByName = new Map(skills.map(function (skill) {
321
+ return [skill.name, skill];
322
+ }));
323
+ skills.splice.apply(skills, [0, skills.length].concat((0, _toConsumableArray2.default)(SKILLS.map(function (skillDefinition) {
324
+ var _skillResultsByName$g;
325
+ return (_skillResultsByName$g = skillResultsByName.get(skillDefinition.name)) !== null && _skillResultsByName$g !== void 0 ? _skillResultsByName$g : {
326
+ name: skillDefinition.name,
327
+ status: 'not-installed',
328
+ path: skillDefinition.relativePath,
329
+ reason: SKILLS_INSTALLER_UNAVAILABLE_REASON
330
+ };
331
+ }))));
332
+ }
333
+ if (!json) {
334
+ _iterator = _createForOfIteratorHelper(skillHumanOutput);
335
+ try {
336
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
337
+ line = _step.value;
338
+ writer.out(line);
339
+ }
340
+ } catch (err) {
341
+ _iterator.e(err);
342
+ } finally {
343
+ _iterator.f();
344
+ }
345
+ if (skillsInstallerUnavailable) {
346
+ writer.out(skillHumanOutput.length > 0 ? '– Remaining repository-local skills skipped because @atlassian/skills is unavailable; npx @atlaskit/ads-cli remains available' : '– Repository-local skills skipped because @atlassian/skills is unavailable; npx @atlaskit/ads-cli remains available');
347
+ }
348
+ }
349
+ installedSkills = skills.filter(function (skill) {
350
+ return skill.status !== 'not-installed';
351
+ });
352
+ _adsSkillInstalled = installedSkills.some(function (skill) {
353
+ return skill.name === ADS_SKILL.name;
354
+ });
355
+ if (skillsInstallerUnavailable || _adsSkillInstalled) {
356
+ try {
357
+ agentsMd = (0, _updateAgentsFile.updateAgentsFile)({
358
+ projectRoot: projectRoot,
359
+ guidance: _adsSkillInstalled ? {
360
+ mode: 'skills-installed',
361
+ skillEntrypoints: installedSkills.map(function (skill) {
362
+ return "".concat(skill.path, "/").concat(SKILL_ENTRYPOINT);
363
+ }),
364
+ getStartedPath: SKILL_GET_STARTED_RELATIVE_PATH
365
+ } : {
366
+ mode: 'public'
367
+ }
368
+ });
369
+ if (!json) {
370
+ writeAgentsFileResult({
371
+ result: agentsMd,
372
+ writer: writer
373
+ });
374
+ }
375
+ } catch (error) {
376
+ repositorySetupErrors.push(error instanceof Error ? error : new Error('Failed to set up the ADS repository guidance.'));
377
+ }
378
+ }
379
+ case 7:
380
+ atlasCwd = projectRoot !== null && projectRoot !== void 0 ? projectRoot : _nodePath.default.resolve(cwd);
381
+ if (!(invocation === _cliMetadata.CLI_ATLAS_INVOCATION)) {
382
+ _context2.next = 8;
383
+ break;
384
+ }
385
+ atlasPluginStatus = 'already-installed';
386
+ if (!json) {
387
+ writer.out('✓ Atlas CLI ADS plugin already available');
388
+ }
389
+ _context2.next = 13;
390
+ break;
391
+ case 8:
392
+ atlasCheck = defaultRunProcess({
393
+ command: 'atlas',
394
+ args: ['ads', '--help'],
395
+ cwd: atlasCwd,
396
+ capture: true
397
+ });
398
+ if (!(atlasCheck.status === 0)) {
399
+ _context2.next = 9;
400
+ break;
401
+ }
402
+ atlasPluginStatus = 'already-installed';
403
+ if (!json) {
404
+ writer.out('✓ Atlas CLI ADS plugin already available');
405
+ }
406
+ _context2.next = 13;
407
+ break;
408
+ case 9:
409
+ if (!(((_atlasCheck$error = atlasCheck.error) === null || _atlasCheck$error === void 0 ? void 0 : _atlasCheck$error.code) === 'ENOENT')) {
410
+ _context2.next = 10;
411
+ break;
412
+ }
413
+ atlasPluginStatus = 'atlas-cli-unavailable';
414
+ if (!json) {
415
+ writer.out('– Atlas CLI is unavailable; use npx @atlaskit/ads-cli for ADS commands');
416
+ }
417
+ _context2.next = 13;
418
+ break;
419
+ case 10:
420
+ installResult = defaultRunProcess({
421
+ command: 'atlas',
422
+ args: ['plugin', 'install', '--name', 'ads'],
423
+ cwd: atlasCwd,
424
+ capture: json
425
+ });
426
+ if (!(installResult.status !== 0)) {
427
+ _context2.next = 11;
428
+ break;
429
+ }
430
+ throw new Error(processFailureMessage(installResult, 'Failed to install the Atlas CLI ADS plugin. npx @atlaskit/ads-cli remains available'));
431
+ case 11:
432
+ verification = defaultRunProcess({
433
+ command: 'atlas',
434
+ args: ['ads', '--help'],
435
+ cwd: atlasCwd,
436
+ capture: true
437
+ });
438
+ if (!(verification.status !== 0)) {
439
+ _context2.next = 12;
440
+ break;
441
+ }
442
+ throw new Error('The Atlas CLI ADS plugin was installed but `atlas ads --help` did not succeed. npx @atlaskit/ads-cli remains available.');
443
+ case 12:
444
+ atlasPluginStatus = 'installed';
445
+ if (!json) {
446
+ writer.out('✓ Atlas CLI ADS plugin installed');
447
+ }
448
+ case 13:
449
+ if (!(repositorySetupErrors.length > 0)) {
450
+ _context2.next = 14;
451
+ break;
452
+ }
453
+ throw new Error(repositorySetupErrors.map(function (error) {
454
+ return error.message;
455
+ }).join('\n'));
456
+ case 14:
457
+ if (!(skills.length !== SKILLS.length || !agentsMd)) {
458
+ _context2.next = 15;
459
+ break;
460
+ }
461
+ throw new Error('Failed to determine the ADS repository setup result.');
462
+ case 15:
463
+ adsSkillInstalled = skills.some(function (skill) {
464
+ return skill.name === ADS_SKILL.name && skill.status !== 'not-installed';
465
+ });
466
+ nextStep = projectRoot && adsSkillInstalled ? SKILL_GET_STARTED_RELATIVE_PATH : null;
467
+ if (!json && nextStep) {
468
+ writer.out("\u2192 Next: follow ".concat(nextStep, " to complete repository setup"));
469
+ }
470
+ data = {
471
+ projectRoot: projectRoot !== null && projectRoot !== void 0 ? projectRoot : null,
472
+ skills: skills,
473
+ agentsMd: agentsMd,
474
+ atlas: {
475
+ status: atlasPluginStatus
476
+ },
477
+ nextStep: nextStep
478
+ };
479
+ if (json) {
480
+ (0, _writeJsonEnvelope.writeJsonEnvelope)({
481
+ envelope: (0, _createSuccessEnvelope.createSuccessEnvelope)({
482
+ envelopeType: 'init',
483
+ command: 'init',
484
+ data: data,
485
+ meta: {}
486
+ }),
487
+ writer: writer
488
+ });
489
+ }
490
+ return _context2.abrupt("return", _types.ExitCode.Ok);
491
+ case 16:
492
+ case "end":
493
+ return _context2.stop();
494
+ }
495
+ }, _callee);
496
+ }));
497
+ return function runInitCommand(_x) {
498
+ return _ref5.apply(this, arguments);
499
+ };
500
+ }();
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.updateAgentsFile = exports.AGENTS_FILE_RELATIVE_PATH = exports.ADS_INIT_START_MARKER = exports.ADS_INIT_END_MARKER = void 0;
8
+ var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
9
+ var _nodeCrypto = require("node:crypto");
10
+ var _nodeFs = require("node:fs");
11
+ var _nodePath = _interopRequireDefault(require("node:path"));
12
+ var ADS_INIT_START_MARKER = exports.ADS_INIT_START_MARKER = '<!-- ADS:INIT:START -->';
13
+ var ADS_INIT_END_MARKER = exports.ADS_INIT_END_MARKER = '<!-- ADS:INIT:END -->';
14
+ var AGENTS_FILE_RELATIVE_PATH = exports.AGENTS_FILE_RELATIVE_PATH = 'AGENTS.md';
15
+ var markerError = function markerError() {
16
+ return new Error("Cannot update ".concat(AGENTS_FILE_RELATIVE_PATH, " because the ").concat(ADS_INIT_START_MARKER, " and ").concat(ADS_INIT_END_MARKER, " markers are malformed or ambiguous. Repair or remove the markers, then run init again."));
17
+ };
18
+ var countOccurrences = function countOccurrences(content, value) {
19
+ return content.split(value).length - 1;
20
+ };
21
+ var isStandaloneMarker = function isStandaloneMarker(content, marker, index) {
22
+ var beforeIsLineBoundary = index === 0 || content[index - 1] === '\n';
23
+ var afterIndex = index + marker.length;
24
+ var afterIsLineBoundary = afterIndex === content.length || content[afterIndex] === '\n' || content[afterIndex] === '\r' && content[afterIndex + 1] === '\n';
25
+ return beforeIsLineBoundary && afterIsLineBoundary;
26
+ };
27
+ var detectLineEnding = function detectLineEnding(content) {
28
+ var _content$match$length, _content$match, _content$replace$matc, _content$replace$matc2;
29
+ var crlfCount = (_content$match$length = (_content$match = content.match(/\r\n/g)) === null || _content$match === void 0 ? void 0 : _content$match.length) !== null && _content$match$length !== void 0 ? _content$match$length : 0;
30
+ var lfOnlyCount = (_content$replace$matc = (_content$replace$matc2 = content.replace(/\r\n/g, '').match(/\n/g)) === null || _content$replace$matc2 === void 0 ? void 0 : _content$replace$matc2.length) !== null && _content$replace$matc !== void 0 ? _content$replace$matc : 0;
31
+ return crlfCount > lfOnlyCount ? '\r\n' : '\n';
32
+ };
33
+ var MCP_GUIDANCE = ['Use `atlas ads` first for structured ADS lookups. If Atlas is unavailable, use `npx @atlaskit/ads-cli` with the same trailing arguments.', '', '### Hosted ADS MCP fallback', '', 'Prefer the CLI first. Configure the hosted ADS MCP server only if this repository does not already configure `ads-mcp` or `atlassian-ads-mcp`. Merge the selected server into the existing configuration without replacing other servers, then reload the agent or IDE.', '', '**Cursor — `.cursor/mcp.json`:**', '', '```json', '{', ' "mcpServers": {', ' "ads-mcp": {', ' "url": "https://mcp.atlassian.com/v1/ads/public/mcp"', ' }', ' }', '}', '```', '', '**VS Code — `.vscode/mcp.json`:**', '', '```json', '{', ' "servers": {', ' "ads-mcp": {', ' "type": "http",', ' "url": "https://mcp.atlassian.com/v1/ads/public/mcp"', ' }', ' }', '}', '```', '', '**Codex — `.codex/config.toml`:**', '', '```toml', '[mcp_servers.atlassian-ads-mcp]', 'url = "https://mcp.atlassian.com/v1/ads/public/mcp"', '```', '', 'Do not add Rovo MCP configuration to the repository.'];
34
+ var renderManagedBlock = function renderManagedBlock(_ref) {
35
+ var lineEnding = _ref.lineEnding,
36
+ guidance = _ref.guidance;
37
+ var skillGuidance = guidance.mode === 'skills-installed' ? ['`init` installed repository-local guidance for setting up and using the Atlassian Design System.', '', 'For Atlassian frontend UI work—including component selection, tokens, icons, styling, accessibility, product content and ADS lint rules—follow:', ''].concat((0, _toConsumableArray2.default)(guidance.skillEntrypoints.map(function (entrypoint) {
38
+ return "- `".concat(entrypoint, "`");
39
+ })), ['', "Before starting frontend UI work, check and complete this repository's ADS setup by following:", '', "`".concat(guidance.getStartedPath, "`"), '', 'Apply only the setup that is missing, and preserve equivalent existing configuration.', '']) : ['`init` did not install repository-local skills. Use the public ADS CLI and optional MCP guidance below.', ''];
40
+ return [ADS_INIT_START_MARKER, '## Getting started with the Atlassian Design System', ''].concat((0, _toConsumableArray2.default)(skillGuidance), MCP_GUIDANCE, ['', "This is a temporary initialization section. It may be removed or rephrased once this repository's ADS setup has been completed.", ADS_INIT_END_MARKER]).join(lineEnding);
41
+ };
42
+ var readTargetStats = function readTargetStats(targetPath) {
43
+ try {
44
+ return (0, _nodeFs.lstatSync)(targetPath);
45
+ } catch (error) {
46
+ if (error.code === 'ENOENT') {
47
+ return undefined;
48
+ }
49
+ throw error;
50
+ }
51
+ };
52
+ var atomicWriteFile = function atomicWriteFile(_ref2) {
53
+ var targetPath = _ref2.targetPath,
54
+ content = _ref2.content,
55
+ mode = _ref2.mode,
56
+ targetExists = _ref2.targetExists;
57
+ var temporaryPath = _nodePath.default.join(_nodePath.default.dirname(targetPath), ".".concat(_nodePath.default.basename(targetPath), ".").concat(process.pid, ".").concat((0, _nodeCrypto.randomUUID)(), ".tmp"));
58
+ var temporaryFileExists = false;
59
+ try {
60
+ (0, _nodeFs.writeFileSync)(temporaryPath, content, {
61
+ encoding: 'utf8',
62
+ flag: 'wx',
63
+ mode: mode
64
+ });
65
+ temporaryFileExists = true;
66
+ try {
67
+ (0, _nodeFs.renameSync)(temporaryPath, targetPath);
68
+ temporaryFileExists = false;
69
+ } catch (error) {
70
+ var code = error.code;
71
+ var canFallbackOnWindows = process.platform === 'win32' && targetExists && (code === 'EACCES' || code === 'EEXIST' || code === 'EPERM');
72
+ if (!canFallbackOnWindows) {
73
+ throw error;
74
+ }
75
+ (0, _nodeFs.writeFileSync)(targetPath, content, {
76
+ encoding: 'utf8',
77
+ mode: mode
78
+ });
79
+ (0, _nodeFs.unlinkSync)(temporaryPath);
80
+ temporaryFileExists = false;
81
+ }
82
+ } finally {
83
+ if (temporaryFileExists) {
84
+ try {
85
+ (0, _nodeFs.unlinkSync)(temporaryPath);
86
+ } catch (_unused) {
87
+ // Preserve the original write failure if temporary cleanup also fails.
88
+ }
89
+ }
90
+ }
91
+ };
92
+ var updateAgentsFile = exports.updateAgentsFile = function updateAgentsFile(_ref3) {
93
+ var _stats$mode;
94
+ var projectRoot = _ref3.projectRoot,
95
+ guidance = _ref3.guidance;
96
+ var targetPath = _nodePath.default.join(projectRoot, AGENTS_FILE_RELATIVE_PATH);
97
+ var stats = readTargetStats(targetPath);
98
+ if (stats !== null && stats !== void 0 && stats.isSymbolicLink()) {
99
+ throw new Error("Cannot update ".concat(AGENTS_FILE_RELATIVE_PATH, " because it is a symbolic link."));
100
+ }
101
+ if (stats && !stats.isFile()) {
102
+ throw new Error("Cannot update ".concat(AGENTS_FILE_RELATIVE_PATH, " because it is not a regular file."));
103
+ }
104
+ var existingContent = stats ? (0, _nodeFs.readFileSync)(targetPath, 'utf8') : '';
105
+ var lineEnding = detectLineEnding(existingContent);
106
+ var managedBlock = renderManagedBlock({
107
+ lineEnding: lineEnding,
108
+ guidance: guidance
109
+ });
110
+ var startCount = countOccurrences(existingContent, ADS_INIT_START_MARKER);
111
+ var endCount = countOccurrences(existingContent, ADS_INIT_END_MARKER);
112
+ var nextContent;
113
+ var status;
114
+ if (!stats) {
115
+ nextContent = "".concat(managedBlock).concat(lineEnding);
116
+ status = 'created';
117
+ } else if (startCount === 0 && endCount === 0) {
118
+ var separator = existingContent.length === 0 ? '' : existingContent.endsWith("".concat(lineEnding).concat(lineEnding)) ? '' : existingContent.endsWith(lineEnding) ? lineEnding : "".concat(lineEnding).concat(lineEnding);
119
+ nextContent = "".concat(existingContent).concat(separator).concat(managedBlock).concat(lineEnding);
120
+ status = 'appended';
121
+ } else {
122
+ if (startCount !== 1 || endCount !== 1) {
123
+ throw markerError();
124
+ }
125
+ var startIndex = existingContent.indexOf(ADS_INIT_START_MARKER);
126
+ var endIndex = existingContent.indexOf(ADS_INIT_END_MARKER);
127
+ if (startIndex > endIndex || !isStandaloneMarker(existingContent, ADS_INIT_START_MARKER, startIndex) || !isStandaloneMarker(existingContent, ADS_INIT_END_MARKER, endIndex)) {
128
+ throw markerError();
129
+ }
130
+ var afterManagedBlock = endIndex + ADS_INIT_END_MARKER.length;
131
+ nextContent = "".concat(existingContent.slice(0, startIndex)).concat(managedBlock).concat(existingContent.slice(afterManagedBlock));
132
+ if (nextContent === existingContent) {
133
+ return {
134
+ status: 'already-current',
135
+ path: AGENTS_FILE_RELATIVE_PATH
136
+ };
137
+ }
138
+ status = 'updated';
139
+ }
140
+ atomicWriteFile({
141
+ targetPath: targetPath,
142
+ content: nextContent,
143
+ mode: (_stats$mode = stats === null || stats === void 0 ? void 0 : stats.mode) !== null && _stats$mode !== void 0 ? _stats$mode : 438,
144
+ targetExists: stats !== undefined
145
+ });
146
+ return {
147
+ status: status,
148
+ path: AGENTS_FILE_RELATIVE_PATH
149
+ };
150
+ };