authoring-cli 0.1.1 → 0.1.3
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.
- package/HELP.md +313 -0
- package/dist/index.js +16 -16
- package/package.json +2 -1
- package/skills/authoring-cli/SKILL.md +97 -8
- package/skills/authoring-cli/references/review-concepts.md +57 -4
package/HELP.md
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
# authoring-cli Help
|
|
2
|
+
|
|
3
|
+
A comprehensive guide to using authoring-cli for SNOMED CT authoring.
|
|
4
|
+
|
|
5
|
+
## Quick Start
|
|
6
|
+
|
|
7
|
+
### 1. Install
|
|
8
|
+
```bash
|
|
9
|
+
npm install -g authoring-cli
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
### 2. Sign In
|
|
13
|
+
```bash
|
|
14
|
+
authoring-cli login
|
|
15
|
+
```
|
|
16
|
+
This opens Chrome to your organization's login page. Once you sign in, your session is captured automatically.
|
|
17
|
+
|
|
18
|
+
### 3. Select a Task
|
|
19
|
+
```bash
|
|
20
|
+
authoring-cli tasks --mine
|
|
21
|
+
authoring-cli select-task --project PROJ --task PROJ-123
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
### 4. Start Authoring
|
|
25
|
+
```bash
|
|
26
|
+
authoring-cli create-concept --fsn "Hepatic structure" --parent 64572001
|
|
27
|
+
authoring-cli add-description --id <concept-id> --term "Liver structure" --type SYNONYM
|
|
28
|
+
authoring-cli classify --wait
|
|
29
|
+
authoring-cli validate-review-concepts
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Common Workflows
|
|
35
|
+
|
|
36
|
+
### Create a New Concept
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
authoring-cli create-concept \
|
|
40
|
+
--fsn "Hepatic inflammation" \
|
|
41
|
+
--parent 128139003 \
|
|
42
|
+
--tag "[disease]"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Add a Synonym
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
authoring-cli add-description \
|
|
49
|
+
--id 64572001 \
|
|
50
|
+
--term "Liver disease" \
|
|
51
|
+
--type SYNONYM \
|
|
52
|
+
--acceptability PREFERRED
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Set US/GB Acceptability
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
# Set one description at a time
|
|
59
|
+
authoring-cli set-acceptability \
|
|
60
|
+
--id 64572001 \
|
|
61
|
+
--description-id <desc-id> \
|
|
62
|
+
--us PREFERRED \
|
|
63
|
+
--gb ACCEPTABLE
|
|
64
|
+
|
|
65
|
+
# Or set multiple descriptions atomically
|
|
66
|
+
authoring-cli set-acceptability \
|
|
67
|
+
--id 64572001 \
|
|
68
|
+
--entries '[
|
|
69
|
+
{"descriptionId":"<id1>","us":"PREFERRED"},
|
|
70
|
+
{"descriptionId":"<id2>","gb":"ACCEPTABLE"}
|
|
71
|
+
]'
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Update an Axiom
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
authoring-cli update-axiom \
|
|
78
|
+
--id 64572001 \
|
|
79
|
+
--axiom-id <axiom-id> \
|
|
80
|
+
--relationships '[
|
|
81
|
+
{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"310305003"}},
|
|
82
|
+
{"active":true,"groupId":1,"type":{"conceptId":"405813007"},"target":{"conceptId":"280115004"}}
|
|
83
|
+
]'
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Validate and Classify
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
# Validate the current concept
|
|
90
|
+
authoring-cli validate-concept --id 64572001
|
|
91
|
+
|
|
92
|
+
# Validate all concepts with pending changes
|
|
93
|
+
authoring-cli validate-review-concepts
|
|
94
|
+
|
|
95
|
+
# Run classification
|
|
96
|
+
authoring-cli classify --wait
|
|
97
|
+
|
|
98
|
+
# Check classification status
|
|
99
|
+
authoring-cli classification-status
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Review Concepts Before Save
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
# List concepts with pending changes
|
|
106
|
+
authoring-cli get-concepts-for-review
|
|
107
|
+
|
|
108
|
+
# Get full details for review
|
|
109
|
+
authoring-cli review-concepts
|
|
110
|
+
|
|
111
|
+
# Validate all at once
|
|
112
|
+
authoring-cli validate-review-concepts
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## Command Reference
|
|
118
|
+
|
|
119
|
+
### Authentication
|
|
120
|
+
- `authoring-cli login [environment]` — Sign in (environment: production, uat, dev)
|
|
121
|
+
- `authoring-cli logout` — Sign out and remove stored session
|
|
122
|
+
|
|
123
|
+
### Task Management
|
|
124
|
+
- `authoring-cli projects` — List available projects
|
|
125
|
+
- `authoring-cli tasks [--project PROJECT] [--mine] [--status STATUS] [--summary]` — List tasks
|
|
126
|
+
- `authoring-cli select-task --project PROJECT --task TASK` — Select a task
|
|
127
|
+
- `authoring-cli current-task` — Show currently selected task
|
|
128
|
+
- `authoring-cli create-task --project PROJECT --summary "TITLE"` — Create a task
|
|
129
|
+
- `authoring-cli delete-task [--project PROJECT --task TASK]` — Delete a task
|
|
130
|
+
- `authoring-cli recover-task --project PROJECT [--task TASK]` — Recover deleted tasks
|
|
131
|
+
|
|
132
|
+
### Concept Management
|
|
133
|
+
- `authoring-cli create-concept --fsn "FSN" --parent SCTID [--tag TAG] [--pt PT]` — Create concept
|
|
134
|
+
- `authoring-cli get-concept --id SCTID` — Fetch a concept
|
|
135
|
+
- `authoring-cli search-concepts [--term TEXT] [--ecl EXPRESSION]` — Search concepts
|
|
136
|
+
- `authoring-cli delete-concept --id SCTID` — Delete unversioned concept (only if never published)
|
|
137
|
+
|
|
138
|
+
### Descriptions
|
|
139
|
+
- `authoring-cli add-description --id SCTID --term "TERM" --type FSN|SYNONYM` — Add description
|
|
140
|
+
- `authoring-cli update-description --id SCTID --description-id ID [--term "TERM"]` — Update unversioned description
|
|
141
|
+
- `authoring-cli delete-description --id SCTID --description-id ID` — Delete unversioned description
|
|
142
|
+
- `authoring-cli set-case-significance --id SCTID --description-id ID --case-significance VALUE` — Set case significance
|
|
143
|
+
- `authoring-cli set-acceptability --id SCTID --description-id ID [--us VALUE] [--gb VALUE]` — Set acceptability
|
|
144
|
+
- `authoring-cli set-acceptability --id SCTID --entries '[...]'` — Set multiple acceptabilities atomically
|
|
145
|
+
|
|
146
|
+
### Relationships & Axioms
|
|
147
|
+
- `authoring-cli add-relationship --id SCTID --type SCTID --target SCTID [--group N]` — Add relationship
|
|
148
|
+
- `authoring-cli remove-relationship --id SCTID --axiom-id ID --relationship-id ID` — Remove relationship
|
|
149
|
+
- `authoring-cli remove-role-group --id SCTID --axiom-id ID --attributes '[...]'` — Remove role group
|
|
150
|
+
- `authoring-cli add-axiom --id SCTID --relationships '[...]'` — Add class axiom
|
|
151
|
+
- `authoring-cli update-axiom --id SCTID --axiom-id ID --relationships '[...]'` — Update axiom
|
|
152
|
+
- `authoring-cli delete-axiom --id SCTID --axiom-id ID` — Delete axiom
|
|
153
|
+
- `authoring-cli inactivate-axiom --id SCTID --axiom-id ID` — Inactivate published axiom
|
|
154
|
+
|
|
155
|
+
### GCI Axioms
|
|
156
|
+
- `authoring-cli add-gci-axiom --id SCTID --relationships '[...]'` — Add GCI axiom
|
|
157
|
+
- `authoring-cli update-gci-axiom --id SCTID --axiom-id ID --relationships '[...]'` — Update GCI axiom
|
|
158
|
+
- `authoring-cli delete-gci-axiom --id SCTID --axiom-id ID` — Delete unversioned GCI axiom
|
|
159
|
+
|
|
160
|
+
### Concept Status
|
|
161
|
+
- `authoring-cli set-definition-status --id SCTID --status PRIMITIVE|FULLY_DEFINED` — Set definition status
|
|
162
|
+
- `authoring-cli inactivate-concept --id SCTID --indicator VALUE [--association-refset ID --association-target SCTID]` — Inactivate concept
|
|
163
|
+
- `authoring-cli transform-axiom --id SCTID [--axiom-id ID]` — Rewrite axiom to standard form
|
|
164
|
+
- `authoring-cli check-authoring-form --id SCTID [--axiom-id ID]` — Check if axiom is in standard form
|
|
165
|
+
|
|
166
|
+
### Validation & Classification
|
|
167
|
+
- `authoring-cli validate-concept --id SCTID` — Validate a single concept (read-only)
|
|
168
|
+
- `authoring-cli get-concepts-for-review [--check-authoring-form]` — List concepts awaiting review
|
|
169
|
+
- `authoring-cli validate-review-concepts` — Validate all concepts with pending changes
|
|
170
|
+
- `authoring-cli review-concepts` — Get full details of all concepts with pending changes
|
|
171
|
+
- `authoring-cli classify [--wait] [--timeout SECONDS]` — Classify task (self-healing)
|
|
172
|
+
- `authoring-cli classification-status` — Check classification job status
|
|
173
|
+
- `authoring-cli validate-task [--enable-mrcm] [--wait] [--timeout SECONDS]` — Validate entire task
|
|
174
|
+
- `authoring-cli validation-status` — Check validation job status
|
|
175
|
+
|
|
176
|
+
### Real-time Notifications
|
|
177
|
+
- `authoring-cli watch-notification [--entity-type TYPE] [--timeout SECONDS]` — Wait for next notification
|
|
178
|
+
|
|
179
|
+
### Skill Management
|
|
180
|
+
- `authoring-cli install-skill [--agent claude|codex|all] [--force]` — Register authoring guidance with your AI agent
|
|
181
|
+
- `authoring-cli uninstall-skill [--agent claude|codex|all]` — Unregister the skill (run before uninstalling the package)
|
|
182
|
+
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
## Tips & Troubleshooting
|
|
186
|
+
|
|
187
|
+
### Session Management
|
|
188
|
+
- Your session is stored in `~/.authoring-cli/session.json`
|
|
189
|
+
- If you have multiple Chrome profiles, specify which one: `authoring-cli login --chrome-profile "Work Profile"`
|
|
190
|
+
- If your session expires during use, you'll get a `401 Unauthorized` error — run `authoring-cli login` again
|
|
191
|
+
|
|
192
|
+
### Task Selection
|
|
193
|
+
- If you don't pass `--project` and `--task` to a command, it uses your last selected task
|
|
194
|
+
- Use `authoring-cli current-task` to see what's currently selected
|
|
195
|
+
- Selecting a task creates its branch if it doesn't exist yet
|
|
196
|
+
|
|
197
|
+
### Validation & Classification
|
|
198
|
+
- `validate-concept` is a **read-only** check — it doesn't save anything
|
|
199
|
+
- `classify --wait` will poll until classification finishes, or timeout after 180 seconds (configurable)
|
|
200
|
+
- If classification is already running, `classify` will attach to that job instead of starting a new one
|
|
201
|
+
- Always run `validate-review-concepts` before classifying to catch obvious issues early
|
|
202
|
+
|
|
203
|
+
### Relationships & Axioms
|
|
204
|
+
- Relationships must be specified as JSON: `--relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]'`
|
|
205
|
+
- `add-relationship --group N` automatically groups relationships (group 0 = ungrouped, group 1+ = attributes)
|
|
206
|
+
- You cannot edit published axioms directly — you must inactivate the old one and add a new one
|
|
207
|
+
- `remove-relationship` only works on unversioned (never-published) relationships
|
|
208
|
+
|
|
209
|
+
### Descriptions & Acceptability
|
|
210
|
+
- The `set-acceptability --entries` form lets you set multiple descriptions in one atomic save, working around the exactly-one-PREFERRED-per-dialect constraint
|
|
211
|
+
- When setting different acceptabilities for US and GB, understand that both default to PREFERRED if a language refset is used
|
|
212
|
+
- Use `--acceptability PREFERRED` when creating a description to mark it as preferred immediately
|
|
213
|
+
|
|
214
|
+
### Error Messages
|
|
215
|
+
- `effectiveTime is not null` — the concept or property is published and cannot be directly edited
|
|
216
|
+
- `Not the only PREFERRED description in the {lang} refset` — you're trying to make two descriptions PREFERRED in the same dialect
|
|
217
|
+
- `module-mismatched` — you're editing with the wrong module for this extension branch
|
|
218
|
+
- `not found (404)` — the concept, description, or relationship ID doesn't exist
|
|
219
|
+
|
|
220
|
+
### Performance
|
|
221
|
+
- For large searches, add `--limit N` to avoid huge result sets
|
|
222
|
+
- Use `--json` flag to get machine-readable output suitable for scripting
|
|
223
|
+
- Classification can take 2-20+ minutes depending on the branch size; use `--timeout` to wait longer if needed
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## Best Practices
|
|
228
|
+
|
|
229
|
+
### Before Starting
|
|
230
|
+
1. Run `authoring-cli login` and select your task
|
|
231
|
+
2. Check the task status and any existing concepts: `authoring-cli get-concepts-for-review`
|
|
232
|
+
3. Review project-specific metadata: `authoring-cli projects --json`
|
|
233
|
+
|
|
234
|
+
### During Authoring
|
|
235
|
+
1. Create or update concepts one at a time
|
|
236
|
+
2. Use `validate-concept` frequently to catch issues early
|
|
237
|
+
3. Use `get-concepts-for-review` to track what you've changed
|
|
238
|
+
4. Run `classify --wait` to see inferred relationships before final validation
|
|
239
|
+
|
|
240
|
+
### Before Saving
|
|
241
|
+
1. Run `validate-review-concepts` on all changed concepts
|
|
242
|
+
2. Review any warnings about dialect acceptability
|
|
243
|
+
3. Check `classification-status` if you classified earlier
|
|
244
|
+
4. Ensure no axioms are in non-standard form (use `check-authoring-form` if needed)
|
|
245
|
+
|
|
246
|
+
### Large Batches
|
|
247
|
+
- Use the authoring guidance skill: `authoring-cli install-skill`, then `/authoring-cli` in your agent
|
|
248
|
+
- The skill documents batch authoring methodology: `authoring-cli/references/batch-authoring.md`
|
|
249
|
+
- For tracking across sessions, the skill explains the resumable-tracker pattern
|
|
250
|
+
|
|
251
|
+
---
|
|
252
|
+
|
|
253
|
+
## Get More Help
|
|
254
|
+
|
|
255
|
+
### Command Details
|
|
256
|
+
```bash
|
|
257
|
+
# See all available commands and flags
|
|
258
|
+
authoring-cli
|
|
259
|
+
|
|
260
|
+
# Get help on a specific command (usage text)
|
|
261
|
+
authoring-cli <command> --help
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
### Authoring Guidance
|
|
265
|
+
The package includes detailed guidance on SNOMED CT authoring best practices, Snowstorm constraints, and batch methodologies. Register it with your AI agent:
|
|
266
|
+
|
|
267
|
+
```bash
|
|
268
|
+
authoring-cli install-skill
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
Then use `/authoring-cli` in Claude Code or your agent to get guidance while you work.
|
|
272
|
+
|
|
273
|
+
### Server-side Constraints
|
|
274
|
+
If you encounter a server error (4xx/5xx), check the error message carefully — it often tells you exactly what's wrong. Common issues:
|
|
275
|
+
|
|
276
|
+
- **Save validation errors** — described in the error response; fix the concept and try again
|
|
277
|
+
- **Publication gating** — some operations are forbidden on published concepts
|
|
278
|
+
- **Module requirements** — extension branches require the correct module ID
|
|
279
|
+
- **Dialect constraints** — exactly one PREFERRED description per language refset
|
|
280
|
+
|
|
281
|
+
### Reporting Issues
|
|
282
|
+
If you find a bug or have a feature request, check the GitHub repository:
|
|
283
|
+
```
|
|
284
|
+
https://github.com/snomed/authoring-cli
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
---
|
|
288
|
+
|
|
289
|
+
## FAQ
|
|
290
|
+
|
|
291
|
+
**Q: Can I use this on Windows or Linux?**
|
|
292
|
+
A: The CLI runs on any Node.js 24+ environment, but automatic session capture during login only works on macOS with Chrome. On other platforms, `login` will fail with a clear message. You can manually pass endpoints and a session cookie using flags, but that's not yet implemented.
|
|
293
|
+
|
|
294
|
+
**Q: How do I use this with an AI agent?**
|
|
295
|
+
A: Install the bundled authoring skill (`authoring-cli install-skill`), then invoke `/authoring-cli` in Claude Code or Codex. The skill teaches the agent about Snowstorm constraints and SNOMED CT modeling rules.
|
|
296
|
+
|
|
297
|
+
**Q: Can I undo a change?**
|
|
298
|
+
A: There's no built-in undo. However:
|
|
299
|
+
- Unversioned changes can be deleted or reverted with a new command
|
|
300
|
+
- Published concepts cannot be edited directly — you must inactivate and create new ones
|
|
301
|
+
- Use `--wait` with classify/validate to review changes before they're locked in
|
|
302
|
+
|
|
303
|
+
**Q: What if I accidentally delete a task?**
|
|
304
|
+
A: Use `recover-task` — it brings the task back out of the Deleted status with all its content intact.
|
|
305
|
+
|
|
306
|
+
**Q: How do I batch large changes?**
|
|
307
|
+
A: Run commands in sequence, using `--json` output to parse results. The authoring guidance skill documents patterns for resumable batch operations: see `/authoring-cli` after running `install-skill`.
|
|
308
|
+
|
|
309
|
+
**Q: My session expired. What do I do?**
|
|
310
|
+
A: Run `authoring-cli login` again to get a fresh session.
|
|
311
|
+
|
|
312
|
+
**Q: Can I target multiple projects at once?**
|
|
313
|
+
A: No, you work on one selected task at a time. Switching between tasks is instant: `select-task --project PROJ2 --task PROJ2-456`.
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var En=Object.create;var Z=Object.defineProperty;var jn=Object.getOwnPropertyDescriptor;var Nn=Object.getOwnPropertyNames;var Pn=Object.getPrototypeOf,Dn=Object.prototype.hasOwnProperty;var On=(e,t)=>{for(var r in t)Z(e,r,{get:t[r],enumerable:!0})},We=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Nn(t))!Dn.call(e,o)&&o!==r&&Z(e,o,{get:()=>t[o],enumerable:!(n=jn(t,o))||n.enumerable});return e};var v=(e,t,r)=>(r=e!=null?En(Pn(e)):{},We(t||!e||!e.__esModule?Z(r,"default",{value:e,enumerable:!0}):r,e)),Ln=e=>We(Z({},"__esModule",{value:!0}),e);var Kr={};On(Kr,{COMMANDS:()=>He,main:()=>An,parsePositionals:()=>Rn});module.exports=Ln(Kr);var F={production:{imsEndpoint:"https://authoring.ihtsdotools.org/",terminologyServerEndpoint:"https://authoring.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://authoring.ihtsdotools.org/authoring-services/",cookieName:"ims-ihtsdo"},uat:{imsEndpoint:"https://uat-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://uat-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://uat-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"uat-ims-ihtsdo"},dev:{imsEndpoint:"https://dev-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://dev-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://dev-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"dev-ims-ihtsdo"}},Kn={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},ee=Object.keys(F);function Ye(e){return Kn[e.trim().toLowerCase()]??null}var H="uat",Fr=F.uat.imsEndpoint,Mr=F.uat.terminologyServerEndpoint,Ur=F.uat.authoringServicesEndpoint;var Bn=v(require("http")),Fn=v(require("https"));function y(e,t={}){let{method:r="GET",cookie:n,body:o,headers:s={},timeoutMs:i=15e3}=t;return new Promise((a,c)=>{let d;try{d=new URL(e)}catch(C){c(C);return}let l=d.protocol==="https:"?Fn:Bn,u=o!==void 0?JSON.stringify(o):void 0,g={accept:"application/json",...s};if(u!==void 0&&(g["content-type"]="application/json",g["content-length"]=String(Buffer.byteLength(u))),n){let C=n.replace(/[^\x20-\x7e\t]/g,"");C&&(g.cookie=C)}let f=l.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:g},C=>{let h="";C.on("data",k=>{h+=k}),C.on("end",()=>{let k=C.statusCode??0,N=(C.headers["content-type"]??"").includes("application/json"),j=null,A=!1;if(h)try{j=JSON.parse(h)}catch{A=!N}a({statusCode:k,body:j,rawBody:h,sessionExpired:A})})});f.on("error",c),f.setTimeout(i,()=>{f.destroy(new Error(`Request to ${e} timed out after ${i}ms`))}),u!==void 0&&f.write(u),f.end()})}var K="900000000000509007",W="900000000000508004";var ze={[K]:"en-us",[W]:"en-gb"},Xe={[K]:"true",[W]:"true"},Mn={},Un={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:ze,dialectDefaults:Xe,readOnlyDialects:Mn,defaultLanguage:"en"};function Qe(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return Un;let t={[K]:"en-us"},r={},n={},o=[];for(let c of Object.keys(e)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let l=d[1];t[String(e[c])]=l,o.length===0&&o.push(l)}}let s=e.requiredLanguageRefsets;if(Array.isArray(s))for(let c of s){if(typeof c!="object"||c===null)continue;let d=null,l=null;for(let[C,h]of Object.entries(c))C.length===2&&(d=C,l=String(h));if(!d||!l)continue;let u=c.dialectName;t[l]=typeof u=="string"?u:d;let g=c.default;g==="true"&&!o.includes(d)&&o.push(d),g!=null&&(r[l]=String(g));let f=c.readOnly;f!=null&&(n[l]=String(f))}let i=e.optionalLanguageRefsets;if(Array.isArray(i))for(let c of i)c&&typeof c=="object"&&"refsetId"in c&&(t[String(c.refsetId)]=String(c.language??""));let a=!!e.useInternationalLanguageRefsets;return{isExtension:!0,useInternationalLanguageRefsets:a,dialects:a?ze:t,dialectDefaults:a?Xe:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function Ce(e,t,r,n){let o={};for(let s of Object.keys(e.dialects)){let i=e.dialects[s];e.isExtension&&!r?i.includes(n)?o[s]="PREFERRED":i.includes(e.defaultLanguage)&&(o[s]="ACCEPTABLE"):i.includes(n)&&(o[s]=t),e.dialectDefaults[s]==="false"&&!r&&delete o[s],e.readOnlyDialects[s]==="true"&&delete o[s]}return o}function Ze(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[K]:"PREFERRED"}:Ce(e,"PREFERRED",t,"en")}var _n="900000000000207008";function et(e){return e.replace(/\/$/,"")}function w(e){return et(e.terminologyServerEndpoint)}function R(e){return et(e.authoringServicesEndpoint)}function tt(e){return`${new URL(R(e)).origin}/authoring-traceability-service`}function M(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function I(e,t,r){let n=t.projectKey||r?.projectKey,o=t.taskKey||r?.taskKey,s=!t.projectKey&&!t.taskKey,i=t.branchPath||(s?r?.branchPath:void 0);return!n||!o?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(i||(i=await Vn(e,n,o)??void 0),i?{ok:!0,projectKey:n,taskKey:o,branchPath:i}:{ok:!1,error:`Could not resolve branch path for ${n}/${o}.`})}async function U(e,t){let r=w(e),n=await y(`${r}/branches/${encodeURIComponent(t)}`,{cookie:e.cookie});if(n.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode>=200&&n.statusCode<300)return{ok:!0,created:!1};if(n.statusCode!==404)return{ok:!1,error:`Could not check branch ${t} (HTTP ${n.statusCode}).`};let o=t.split("/").filter(Boolean),s=o[o.length-1],i=o.slice(0,-1).join("/");if(!s||!i)return{ok:!1,error:`Cannot create branch from path "${t}" \u2014 expected a parent and a name.`};let a=await y(`${r}/branches`,{method:"POST",body:{parent:i,name:s},cookie:e.cookie});return a.sessionExpired?{ok:!1,error:"IMS session expired \u2014 re-sign in."}:a.statusCode<200||a.statusCode>=300?{ok:!1,error:`Could not create branch ${t} (HTTP ${a.statusCode}).`}:{ok:!0,created:!0}}async function Vn(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}`;return(await y(n,{cookie:e.cookie})).body?.branchPath??null}async function ot(e,t,r){let n=r?.get(t);if(n)return n;let o=`${R(e)}/projects/${t}`,i=(await y(o,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,i),i}async function Y(e,t,r){let n=await ot(e,t,r),o=n.multipleModuleEditingDisabled,s=!o||o==="false";return n.expectedExtensionModules?.length&&s?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:_n}async function te(e,t,r){let n=await ot(e,t,r);return Qe(n)}async function he(e,t){let r=e.replace(/\/$/,"")+"/auth",n=await y(r,{cookie:t,timeoutMs:8e3});return n.statusCode>=200&&n.statusCode<300&&n.body?n.body:(console.warn(`[authoring-cli] fetchAccountDetails: HTTP ${n.statusCode} from ${r}`),null)}var nt=v(require("crypto"));var qn="116680003";function oe(e,t,r,n,o="PREFERRED",s=!1){let i=e==="FSN"?Ze(n,s):Ce(n,o,s,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:i}}async function rt(e,t,r,n=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await I(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:s,taskKey:i,branchPath:a}=o,c=M(a),d=t.moduleId||await Y(e,s,n),l=await te(e,s,n),u=t.preferredTerm||t.fsn,g=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,f={conceptId:null,moduleId:d,definitionStatus:"PRIMITIVE",active:!0,descriptions:[oe("FSN",g,d,l,"PREFERRED",!0),oe("SYNONYM",u,d,l,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:nt.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:d,relationships:[{active:!0,groupId:0,type:{conceptId:qn},target:{conceptId:t.parentConceptId}}]}]},C=`${w(e)}/browser/${c}/${s}/${i}/concepts/?validate=true`,h=await y(C,{method:"POST",body:f,cookie:e.cookie});if(h.sessionExpired){let N="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: SESSION EXPIRED`),{statusCode:401,body:{error:N}}}let k=h.body,T=k&&"conceptId"in k?k.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: ${h.statusCode<300?"OK":"FAILED ("+h.statusCode+")"} \u2014 ${g}`+(T?` \u2192 ${T}`:"")),typeof T=="string"&&e.onValidationResults?.(T,k?.validationResults),{statusCode:h.statusCode,body:h.body}}async function ne(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${w(e)}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await y(o,{cookie:e.cookie});return s.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:s.statusCode,body:s.body}}async function st(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o={limit:t.limit??50,expand:"fsn()"};t.term&&(o.termFilter=t.term),t.ecl&&(o.eclFilter=t.ecl),typeof t.active=="boolean"&&(o.activeFilter=t.active);let s=`${w(e)}/${n.branchPath}/concepts/search`,i=await y(s,{method:"POST",body:o,cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let a=(i.body?.items??[]).map(c=>({conceptId:c.conceptId,fsn:c.fsn?.term,pt:c.pt?.term,active:c.active,moduleId:c.moduleId}));return{statusCode:i.statusCode,body:{total:i.body?.total??a.length,items:a}}}async function it(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=w(e),s=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await y(s,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:i.body}};if(i.body.effectiveTime!=null)return{statusCode:409,body:{error:`Concept ${t.conceptId} has effectiveTime ${String(i.body.effectiveTime)} set (already versioned) \u2014 cannot delete.`}};let a=`${o}/${n.branchPath}/concepts/${t.conceptId}`,c=await y(a,{method:"DELETE",cookie:e.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] delete-concept ${n.projectKey}/${n.taskKey}: ${c.statusCode<300?"OK":"FAILED ("+c.statusCode+")"} \u2014 ${t.conceptId}`),c.statusCode===409?{statusCode:409,body:{error:`Cannot delete concept ${t.conceptId} \u2014 one or more of its components is published.`,details:c.body}}:{statusCode:c.statusCode,body:c.body})}function at(e){return typeof e=="object"&&e!==null}function Jn(e){let t=e.type,r=e.target,n=at(t)?t.conceptId:void 0,o=at(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function Gn(e,t){let r=[...t];for(let n of e){let o=r.findIndex(s=>s.typeId===n.typeId&&s.targetId===n.targetId);if(o===-1)return!1;r.splice(o,1)}return!0}function ct(e,t,r){let n=new Map;for(let i of e){let a=typeof i.groupId=="number"?i.groupId:0,c=n.get(a);c?c.push(i):n.set(a,[i])}let o=[];for(let[i,a]of n){if(r!=null?i!==r:i===0)continue;let c=a.map(Jn).filter(d=>d!=null);Gn(t,c)&&o.push(i)}if(o.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(o.length>1)return{ok:!1,statusCode:409,error:`has ${o.length} role groups matching the given attributes (groupIds: ${o.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let s=o[0];return{ok:!0,groupId:s,relationships:n.get(s)}}var mt=v(require("crypto"));var Hn=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],Wn=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],Yn=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],zn=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],Xn=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],xe=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function ft(e){return xe.includes(e)}function z(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function re(e){return typeof e=="object"&&e!==null}function dt(e){return re(e)?z(e,zn):e}function gt(e){if(!re(e))return e;let t=z(e,Yn);return"type"in t&&(t.type=dt(t.type)),"target"in t&&(t.target=dt(t.target)),t}function Qn(e){return re(e)?z(e,Wn):e}function lt(e){if(!re(e))return e;let t=z(e,Xn);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(gt)),t}function be(e){let t=z(e,Hn);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(Qn)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(gt)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(lt)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(lt)),t}async function E(e,t,r,n){let o=w(e),s=`${o}/browser/${t.branchPath}/concepts/${r}`,i=await y(s,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:i.body}};let a=i.body,c=n(a);if(c)return c;let d=M(t.branchPath),l=`${o}/browser/${d}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,u=await y(l,{method:"PUT",body:be(a),cookie:e.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${u.statusCode<300?"OK":"FAILED ("+u.statusCode+")"} \u2014 ${r}`);let g=u.body;return e.onValidationResults?.(r,g?.validationResults),{statusCode:u.statusCode,body:u.body}}var ut=["PREFERRED","ACCEPTABLE"];async function yt(e,t,r,n=new Map){if(!t.conceptId||!t.term||!t.type)return{statusCode:400,body:{error:"conceptId, term, and type are required."}};if(t.type!=="FSN"&&t.type!=="SYNONYM")return{statusCode:400,body:{error:"type must be FSN or SYNONYM."}};if(t.acceptability&&!ut.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${ut.join(", ")}.`}};let o=await I(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await Y(e,o.projectKey,n),i=await te(e,o.projectKey,n),a=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return E(e,o,t.conceptId,c=>{let d=Array.isArray(c.descriptions)?c.descriptions:[];return d.push(oe(t.type,a,s,i,t.acceptability??"ACCEPTABLE",!1)),c.descriptions=d,null})}async function kt(e,t,r){if(!t.conceptId||!t.typeId||!t.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return E(e,n,t.conceptId,s=>{let i=Array.isArray(s.classAxioms)?s.classAxioms:[],a=i[o];if(!a)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${i.length}).`}};let c=Array.isArray(a.relationships)?a.relationships:[];return c.push({active:!0,groupId:t.groupId??0,type:{conceptId:t.typeId},target:{conceptId:t.targetId}}),a.relationships=c,null})}async function Ct(e,t,r){if(!t.conceptId||!t.status)return{statusCode:400,body:{error:"conceptId and status are required."}};if(t.status!=="PRIMITIVE"&&t.status!=="FULLY_DEFINED")return{statusCode:400,body:{error:"status must be PRIMITIVE or FULLY_DEFINED."}};let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return E(e,n,t.conceptId,s=>{let i=Array.isArray(s.classAxioms)?s.classAxioms:[],a=i[o];return a?(a.definitionStatus=t.status,s.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${i.length}).`}}})}async function ht(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>(o.active=!1,o.inactivationIndicator=t.indicator,t.associationRefsetId&&t.associationTargetId&&(o.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null)):{statusCode:400,body:{error:n.error}}}async function It(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};if(!t.term&&!t.caseSignificance)return{statusCode:400,body:{error:"At least one of term or caseSignificance must be provided."}};if(t.caseSignificance&&!ft(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${xe.join(", ")}.`}};let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(i.term=t.term),t.caseSignificance&&(i.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}async function xt(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!ft(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${xe.join(", ")}.`}};let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return i?(i.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}var Ie=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function pt(e){return Ie.includes(e)}function bt(e){return e.descriptionId?!e.lang&&!e.us&&!e.gb?{statusCode:400,body:{error:`Entry for description ${e.descriptionId} must set at least one of lang, us, or gb.`}}:e.us&&!pt(e.us)?{statusCode:400,body:{error:`us must be one of: ${Ie.join(", ")}.`}}:e.gb&&!pt(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${Ie.join(", ")}.`}}:null:{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function St(e,t,r){let n=e.find(s=>s.descriptionId===r.descriptionId);if(!n)return{statusCode:404,body:{error:`Concept ${t} has no description ${r.descriptionId}.`}};r.lang&&(n.lang=r.lang);let o={...n.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete o[K]:o[K]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[W]:o[W]=r.gb),n.active!==!1&&Object.keys(o).length===0?{statusCode:400,body:{error:`Description ${r.descriptionId} would have an empty acceptabilityMap (Not Acceptable in every dialect) \u2014 an active description must be acceptable in at least one.`}}:(n.acceptabilityMap=o,null)}async function vt(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},o=bt(n);if(o)return o;let s=await I(e,t,r);return s.ok?E(e,s,t.conceptId,i=>{let a=Array.isArray(i.descriptions)?i.descriptions:[];return St(a,t.conceptId,n)}):{statusCode:400,body:{error:s.error}}}async function Tt(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};if(!Array.isArray(t.entries)||t.entries.length===0)return{statusCode:400,body:{error:"entries must be a non-empty array."}};for(let o of t.entries){let s=bt(o);if(s)return s}let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[];for(let i of t.entries){let a=St(s,t.conceptId,i);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function wt(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[],i=s.findIndex(a=>a.descriptionId===t.descriptionId);return i===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.descriptions=s,null)}):{statusCode:400,body:{error:n.error}}}async function Rt(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(a=>a.axiomId===t.axiomId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${t.axiomId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(i.relationships=t.relationships,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function $t(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let i=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===t.axiomId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`GCI axiom ${t.axiomId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(i.relationships=t.relationships,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function At(e,t,r,n=new Map){if(!t.conceptId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(t.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};let o=await I(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await Y(e,o.projectKey,n);return E(e,o,t.conceptId,i=>{let a=Array.isArray(i.gciAxioms)?i.gciAxioms:[];return a.push({axiomId:mt.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),i.gciAxioms=a,null})}async function Et(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let s=Array.isArray(o.classAxioms)?o.classAxioms:[],i=s.findIndex(a=>a.axiomId===t.axiomId);return i===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:s.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${t.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.classAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}async function jt(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};if(!t.relationshipId&&t.relationshipIndex==null)return{statusCode:400,body:{error:"One of relationshipId or relationshipIndex is required."}};let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.axiomId===t.axiomId);if(!i)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(i.relationships)?i.relationships:[],c=t.relationshipId?a.findIndex(l=>l.relationshipId===t.relationshipId):t.relationshipIndex,d=c>=0?a[c]:void 0;return d?d.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${c}`} has effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.splice(c,1),i.relationships=a,null):{statusCode:404,body:{error:`Axiom ${t.axiomId} has no relationship ${t.relationshipId??`at index ${t.relationshipIndex}`}.`}}}):{statusCode:400,body:{error:n.error}}}async function Nt(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.attributes)||t.attributes.length===0)return{statusCode:400,body:{error:"conceptId, axiomId, and a non-empty attributes array are required."}};for(let o of t.attributes)if(!o||typeof o.typeId!="string"||typeof o.targetId!="string")return{statusCode:400,body:{error:"Each attributes entry requires typeId and targetId."}};let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.axiomId===t.axiomId);if(!i)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(i.relationships)?i.relationships:[],c=ct(a,t.attributes,t.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${t.axiomId} ${c.error}`}};let d=c.relationships.find(l=>l.effectiveTime!=null);return d?{statusCode:409,body:{error:`Role group (groupId ${c.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(d.relationshipId)}) with effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(i.relationships=a.filter(l=>(typeof l.groupId=="number"?l.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function Pt(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await I(e,t,r);return n.ok?E(e,n,t.conceptId,o=>{let s=Array.isArray(o.gciAxioms)?o.gciAxioms:[],i=s.findIndex(a=>a.axiomId===t.axiomId);return i===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`GCI axiom ${t.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.gciAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}function Zn(e){let t=[];for(let r of e)t.some(o=>o.componentId===r.componentId&&o.severity===r.severity&&o.conceptId===r.conceptId&&o.message===r.message)||t.push(r);return t}async function se(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=w(e),s=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await y(s,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:i.body}};let a=M(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,d=await y(c,{method:"POST",body:be(i.body),cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(d.statusCode<200||d.statusCode>=300)return{statusCode:d.statusCode,body:{error:"Validation check failed.",details:d.body}};let l=Array.isArray(d.body)?Zn(d.body):[];return{statusCode:200,body:{conceptId:t.conceptId,validationResults:l,hasErrors:l.some(u=>u.severity==="ERROR"),hasWarnings:l.some(u=>u.severity==="WARNING")}}}var Dt=200;async function er(e,t,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${w(e)}/browser/${t}/concepts/bulk-load`,s=!0;for(let i=0;i<r.length;i+=Dt){let a=r.slice(i,i+Dt),c=await y(o,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){s=!1;continue}for(let d of c.body)n.set(d.conceptId,{fsn:d.fsn?.term,pt:d.pt?.term})}return{terms:n,resolved:s}}async function _(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${tt(e)}/activities?size=500&onBranch=${encodeURIComponent(n.branchPath)}`,s=await y(o,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode===404)return{statusCode:200,body:{branchPath:n.branchPath,concepts:[],conceptsClassified:[]}};if(s.statusCode<200||s.statusCode>=300)return{statusCode:s.statusCode,body:{error:"Could not fetch traceability for branch.",details:s.body}};let i=new Map,a=new Map,c=(h,k,T,N)=>{let j=h.get(k);j?(N.forEach(A=>A&&j.componentSubTypes.add(A)),j.lastUpdatedTime=T):h.set(k,{conceptId:k,lastUpdatedTime:T,componentSubTypes:new Set(N.filter(A=>!!A))})};for(let h of s.body?.content??[])if(!(h.activityType!=="CONTENT_CHANGE"&&h.activityType!=="CLASSIFICATION_SAVE"))for(let k of h.conceptChanges??[]){let T=String(k.conceptId),N=k.componentChanges??[],j=N.map(G=>G.componentSubType);if(h.activityType==="CLASSIFICATION_SAVE"){c(a,T,h.commitDate,j);continue}let A=N.some(G=>G.componentSubType!=="INFERRED_RELATIONSHIP");c(A?i:a,T,h.commitDate,j)}for(let h of i.keys())a.delete(h);let d=[...new Set([...i.keys(),...a.keys()])],{terms:l,resolved:u}=await er(e,n.branchPath,d),g=h=>[...h.values()].sort((k,T)=>(T.lastUpdatedTime??"").localeCompare(k.lastUpdatedTime??"")).map(k=>{let T=u&&!l.has(k.conceptId);return{conceptId:k.conceptId,fsn:l.get(k.conceptId)?.fsn,pt:l.get(k.conceptId)?.pt,...T?{deleted:!0}:{},lastUpdatedTime:k.lastUpdatedTime,changedComponentTypes:[...k.componentSubTypes]}}),f=g(i),C=g(a);return{statusCode:200,body:{branchPath:n.branchPath,...u?{summary:{concepts:f.length,conceptsDeleted:f.filter(h=>h.deleted).length,conceptsClassified:C.length}}:{},concepts:f,conceptsClassified:C}}}async function Ot(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await _(e,t,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=[];for(let c of s){if(c.deleted){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"deleted"});continue}let d=await se(e,{conceptId:c.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),l=d.body;if(d.statusCode<200||d.statusCode>=300){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"failed",error:l.error??`HTTP ${d.statusCode}`});continue}let u=l.validationResults??[];i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:u.length===0?"clean":"issues",validationResults:u.length?u:void 0,hasErrors:l.hasErrors})}let a=c=>i.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:i.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:i}}}async function Lt(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await _(e,t,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=[];for(let c of s){if(c.deleted){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"deleted"});continue}let d=await ne(e,{conceptId:c.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),l=d.body;if(d.statusCode<200||d.statusCode>=300){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"failed",error:l?.error??`HTTP ${d.statusCode}`});continue}i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"fetched",concept:d.body})}let a=c=>i.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:i.length,fetched:a("fetched"),skippedDeleted:a("deleted"),failed:a("failed")},concepts:i}}}var Se=new Set;function Kt(e){if(!(!e||typeof e!="object"))for(let t of Se)t(e)}function tr(e){return Se.add(e),()=>Se.delete(e)}function or(e,t){return t.entityType!==void 0&&e.entityType!==t.entityType?!1:e.task?e.task===t.taskKey&&e.project===t.projectKey:e.project?e.project===t.projectKey:e.branchPath===t.branchPath}function ie(e){let t=()=>{};return{promise:new Promise(n=>{t=tr(o=>{or(o,e)&&(t(),n(o))})}),cancel:t}}async function O(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}`;return(await y(n,{cookie:e.cookie})).body??null}var Re=["RUNNING","BUILDING","SCHEDULED","QUEUED"],$e=["QUEUED","SCHEDULED","RUNNING"],nr=["Promoted","Completed"],Bt=5e3;function we(e){return new Promise(t=>setTimeout(t,e))}async function rr(e,t,r){let n=0;for(;;){let{done:o,value:s}=await e();if(o)return{value:s,timedOut:!1};if(n>=r)return{value:s,timedOut:!0};n++,await we(t)}}function sr(){let e=[9e4];for(let t=0;t<3;t++)e.push(1e4);for(let t=0;t<12;t++)e.push(5e3);return e}var ir=sr(),ar=180;function cr(){let e=[3e5];for(let t=0;t<5;t++)e.push(6e4);for(let t=0;t<10;t++)e.push(3e4);return e}var dr=cr(),lr=900;async function Ut(e,t,r,n,o){let s=r*1e3,i=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],d=n?ie(n):void 0,l=await Promise.race(d?[we(c).then(()=>{}),d.promise]:[we(c).then(()=>{})]);if(d?.cancel(),l){let f=l.event;o?.(`[${new Date().toISOString()}] woken by notification${f?`: ${f}`:""}`)}let{done:u,value:g}=await e();if(u)return{value:g,timedOut:!1};if(Date.now()-i>=s)return{value:g,timedOut:!0};a++}}async function _t(e,t,r){let n=await O(e,t,r);if(!n)return{error:`Could not fetch task ${t}/${r}.`};if(n.status&&nr.includes(n.status))return{error:`Task ${t}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${R(e)}/projects/${t}/tasks/${r}`;await y(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function Ae(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await y(n,{method:"POST",body:{},cookie:e.cookie}),(await O(e,t,r))?.latestClassificationJson}async function Ft(e,t,r,n,o){let s,{value:i,timedOut:a}=await Ut(async()=>{let d=(await Ae(e,t,r))?.status;return d!==s&&(s=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||Re.includes(d)),value:d}},ir,o,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:i,timedOut:a}}async function ve(e,t,r){let n=`${w(e)}/${t}/classifications`,o=await y(n,{cookie:e.cookie});if(o.body?.items?.length)return o.body.items.find(s=>s.id===r)??o.body.items[o.body.items.length-1]}async function Vt(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,i=await Ae(e,o,s);return i?{statusCode:200,body:{hasClassification:!0,jobId:i.id,status:i.status,running:Re.includes(i.status),latestClassificationJson:i}}:{statusCode:200,body:{hasClassification:!1}}}async function qt(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await _t(e,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??ar,d=await Ae(e,o,s),l=d?.status,u=d?.id;if(u&&l&&Re.includes(l)){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:A}=await Ft(e,o,s,i,c),G=await ve(e,i,u),ke={accepted:!1};return!A&&j==="COMPLETED"&&(ke=await Te(e,i,o,s,u)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: attached job ${u} final status ${j??"unknown"}${A?" (timed out waiting)":""}, save ${JSON.stringify(ke)}`),{statusCode:200,body:{jobId:u,finalStatus:j,timedOut:A,details:G,save:ke,attachedToExisting:!0}}}if(u&&l==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await ve(e,i,u),A=await Te(e,i,o,s,u);return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: accepted existing job ${u}, save ${JSON.stringify(A)}`),{statusCode:200,body:{jobId:u,finalStatus:"COMPLETED",timedOut:!1,details:j,save:A,acceptedExisting:!0}}}let g=`${R(e)}/projects/${o}/tasks/${s}/classifications`,f=await y(g,{method:"POST",body:{},cookie:e.cookie});if(f.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!f.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: start failed (HTTP ${f.statusCode}) \u2014 raw body: ${f.rawBody}`),{statusCode:f.statusCode||500,body:{error:"Failed to start classification.",details:f.body??f.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: started (${f.body.status??"unknown"})`);let C=f.body.id;if(!t.wait)return{statusCode:200,body:{jobId:C,status:f.body.status}};let{finalStatus:h,timedOut:k}=await Ft(e,o,s,i,c),T=await ve(e,i,C),N={accepted:!1};return!k&&h==="COMPLETED"&&(N=await Te(e,i,o,s,C)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: final status ${h??"unknown"}${k?" (timed out waiting)":""}, save ${JSON.stringify(N)}`),{statusCode:200,body:{jobId:C,finalStatus:h,timedOut:k,details:T,save:N}}}var ur=["SAVED","STALE","SAVE_FAILED"],pr=120;async function Te(e,t,r,n,o){let s=`${w(e)}/${t}/classifications/${o}`,i=await y(s,{method:"PUT",body:{status:"SAVED"},cookie:e.cookie});if(i.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(i.statusCode<200||i.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${i.statusCode}).`};let a=Math.ceil(pr*1e3/Bt),{value:c,timedOut:d}=await rr(async()=>{let u=(await y(s,{cookie:e.cookie})).body?.status;return{done:!!u&&ur.includes(u),value:u}},Bt,a);return d?{accepted:!1,status:c,error:"Timed out waiting for classification results to save."}:c==="SAVED"?{accepted:!0,status:c}:{accepted:!1,status:c,error:c==="STALE"?"Report stale \u2014 re-classify and save.":"Saving classification failed."}}async function Jt(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,a=(await O(e,o,s))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&$e.includes(a)}}}async function Mt(e,t,r,n,o){let s,{value:i,timedOut:a}=await Ut(async()=>{let d=(await O(e,t,r))?.latestValidationStatus;return d!==s&&(s=d,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||$e.includes(d)),value:d}},dr,o,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:i,timedOut:a}}async function Gt(e,t,r){let n=await I(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await _t(e,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??lr,l=(await O(e,o,s))?.latestValidationStatus;if(l&&$e.includes(l)){e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: validation already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:h,timedOut:k}=await Mt(e,o,s,i,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: attached run final status ${h??"unknown"}${k?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:h,timedOut:k,attachedToExisting:!0}}}let u=`${R(e)}/projects/${o}/tasks/${s}/validation`;typeof t.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let g=await y(u,{method:"POST",body:{},cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(g.statusCode<200||g.statusCode>=300)return{statusCode:g.statusCode,body:{error:"Failed to start validation.",details:g.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:f,timedOut:C}=await Mt(e,o,s,i,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: final status ${f??"unknown"}${C?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:f,timedOut:C}}}async function Ht(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",n=`${R(e)}/projects${r}`;return(await y(n,{cookie:e.cookie})).body??[]}async function Wt(e,t){let r=`${R(e)}/projects/${t}/tasks`;return(await y(r,{cookie:e.cookie})).body??[]}async function Yt(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",n=`${R(e)}/projects/my-tasks${r}`;return(await y(n,{cookie:e.cookie})).body??[]}async function zt(e,t){let r=`${R(e)}/projects/${t.projectKey}/tasks`,n={summary:t.summary};t.description!==void 0&&(n.description=t.description),t.assigneeUsername&&(n.assignee={username:t.assigneeUsername});let o=await y(r,{method:"POST",body:n,cookie:e.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to create task in ${t.projectKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}var mr=["FORWARD","DIVERGED"];async function fr(e,t){if(!t)return!1;let r=`${w(e)}/branches/${encodeURIComponent(t)}`,n=await y(r,{cookie:e.cookie});return mr.includes(n.body?.state??"")}var gr=["Promoted","Completed"];async function Xt(e,t){let r=`${R(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await y(r,{cookie:e.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode}).`};let o=n.body.status;if(o&&gr.includes(o))return{statusCode:409,error:`${t.projectKey}/${t.taskKey} has status ${o} \u2014 its work is already in the project, so the task cannot be deleted.`};if(o==="Deleted")return{statusCode:200,task:n.body,alreadyDeleted:!0};let s=await fr(e,n.body.branchPath),i=await y(r,{method:"PUT",body:{status:"DELETED"},cookie:e.cookie});return i.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:i.statusCode<200||i.statusCode>=300||!i.body?{statusCode:i.statusCode||500,error:`Failed to delete ${t.projectKey}/${t.taskKey} (HTTP ${i.statusCode})${i.rawBody?`: ${i.rawBody}`:""}`}:{statusCode:i.statusCode,task:i.body,hadUnpromotedChanges:s}}async function Qt(e,t){let r=`${R(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,n=await y(r,{cookie:e.cookie});return Array.isArray(n.body)?n.body:[]}var yr="IN_PROGRESS";async function Zt(e,t){let r=`${R(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await y(r,{cookie:e.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode}).`};if(n.body.status!=="Deleted")return{statusCode:200,task:n.body,notDeleted:!0};let o=await y(r,{method:"PUT",body:{status:yr},cookie:e.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to recover ${t.projectKey}/${t.taskKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}function eo(e){if(e==="o")return{type:"open"};if(e==="h")return{type:"heartbeat"};if(e.startsWith("a"))try{return{type:"message",messages:JSON.parse(e.slice(1))}}catch{return{type:"unknown",raw:e}}if(e.startsWith("c"))try{let[t,r]=JSON.parse(e.slice(1));return{type:"close",code:t,reason:r}}catch{return{type:"unknown",raw:e}}return{type:"unknown",raw:e}}function Ee(e){return JSON.stringify([e])}function to(e=Math.random){let t=String(Math.floor(e()*1e3)).padStart(3,"0"),r="abcdefghijklmnopqrstuvwxyz0123456789",n="";for(let o=0;o<8;o++)n+=r[Math.floor(e()*r.length)];return`${t}/${n}/websocket`}function je(e,t={},r=""){let n=Object.entries(t).map(([o,s])=>`${o}:${s}`);return[e,...n,"",r].join(`
|
|
3
|
-
`)+"\0"}function
|
|
2
|
+
"use strict";var Yn=Object.create;var tt=Object.defineProperty;var Wn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Xn=Object.getPrototypeOf,Qn=Object.prototype.hasOwnProperty;var Zn=(t,e)=>{for(var r in e)tt(t,r,{get:e[r],enumerable:!0})},ne=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of zn(e))!Qn.call(t,o)&&o!==r&&tt(t,o,{get:()=>e[o],enumerable:!(n=Wn(e,o))||n.enumerable});return t};var v=(t,e,r)=>(r=t!=null?Yn(Xn(t)):{},ne(e||!t||!t.__esModule?tt(r,"default",{value:t,enumerable:!0}):r,t)),tr=t=>ne(tt({},"__esModule",{value:!0}),t);var rs={};Zn(rs,{COMMANDS:()=>oe,main:()=>Hn,parsePositionals:()=>Jn});module.exports=tr(rs);var M={production:{imsEndpoint:"https://authoring.ihtsdotools.org/",terminologyServerEndpoint:"https://authoring.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://authoring.ihtsdotools.org/authoring-services/",cookieName:"ims-ihtsdo"},uat:{imsEndpoint:"https://uat-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://uat-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://uat-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"uat-ims-ihtsdo"},dev:{imsEndpoint:"https://dev-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://dev-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://dev-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"dev-ims-ihtsdo"}},er={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},et=Object.keys(M);function re(t){return er[t.trim().toLowerCase()]??null}var W="uat",is=M.uat.imsEndpoint,as=M.uat.terminologyServerEndpoint,cs=M.uat.authoringServicesEndpoint;var or=v(require("http")),nr=v(require("https"));function y(t,e={}){let{method:r="GET",cookie:n,body:o,headers:s={},timeoutMs:i=15e3}=e;return new Promise((a,c)=>{let d;try{d=new URL(t)}catch(C){c(C);return}let l=d.protocol==="https:"?nr:or,u=o!==void 0?JSON.stringify(o):void 0,f={accept:"application/json",...s};if(u!==void 0&&(f["content-type"]="application/json",f["content-length"]=String(Buffer.byteLength(u))),n){let C=n.replace(/[^\x20-\x7e\t]/g,"");C&&(f.cookie=C)}let g=l.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:f},C=>{let x="";C.on("data",h=>{x+=h}),C.on("end",()=>{let h=C.statusCode??0,P=(C.headers["content-type"]??"").includes("application/json"),j=null,E=!1;if(x)try{j=JSON.parse(x)}catch{E=!P}a({statusCode:h,body:j,rawBody:x,sessionExpired:E})})});g.on("error",c),g.setTimeout(i,()=>{g.destroy(new Error(`Request to ${t} timed out after ${i}ms`))}),u!==void 0&&g.write(u),g.end()})}var L="900000000000509007",z="900000000000508004";var se={[L]:"en-us",[z]:"en-gb"},ie={[L]:"true",[z]:"true"},rr={},sr={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:se,dialectDefaults:ie,readOnlyDialects:rr,defaultLanguage:"en"};function ae(t){if(!t||!("defaultModuleId"in t)||t.defaultModuleId==null)return sr;let e={[L]:"en-us"},r={},n={},o=[];for(let c of Object.keys(t)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let l=d[1];e[String(t[c])]=l,o.length===0&&o.push(l)}}let s=t.requiredLanguageRefsets;if(Array.isArray(s))for(let c of s){if(typeof c!="object"||c===null)continue;let d=null,l=null;for(let[C,x]of Object.entries(c))C.length===2&&(d=C,l=String(x));if(!d||!l)continue;let u=c.dialectName;e[l]=typeof u=="string"?u:d;let f=c.default;f==="true"&&!o.includes(d)&&o.push(d),f!=null&&(r[l]=String(f));let g=c.readOnly;g!=null&&(n[l]=String(g))}let i=t.optionalLanguageRefsets;if(Array.isArray(i))for(let c of i)c&&typeof c=="object"&&"refsetId"in c&&(e[String(c.refsetId)]=String(c.language??""));let a=!!t.useInternationalLanguageRefsets;return{isExtension:!0,useInternationalLanguageRefsets:a,dialects:a?se:e,dialectDefaults:a?ie:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function St(t,e,r,n){let o={};for(let s of Object.keys(t.dialects)){let i=t.dialects[s];t.isExtension&&!r?i.includes(n)?o[s]="PREFERRED":i.includes(t.defaultLanguage)&&(o[s]="ACCEPTABLE"):i.includes(n)&&(o[s]=e),t.dialectDefaults[s]==="false"&&!r&&delete o[s],t.readOnlyDialects[s]==="true"&&delete o[s]}return o}function ce(t,e){return t.isExtension&&!t.useInternationalLanguageRefsets?{[L]:"PREFERRED"}:St(t,"PREFERRED",e,"en")}var ir="900000000000207008";function de(t){return t.replace(/\/$/,"")}function A(t){return de(t.terminologyServerEndpoint)}function w(t){return de(t.authoringServicesEndpoint)}function le(t){return`${new URL(w(t)).origin}/authoring-traceability-service`}function _(t){return t.split("/").filter(Boolean).slice(0,-2).join("/")}async function k(t,e,r){let n=e.projectKey||r?.projectKey,o=e.taskKey||r?.taskKey,s=!e.projectKey&&!e.taskKey,i=e.branchPath||(s?r?.branchPath:void 0);return!n||!o?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(i||(i=await ar(t,n,o)??void 0),i?{ok:!0,projectKey:n,taskKey:o,branchPath:i}:{ok:!1,error:`Could not resolve branch path for ${n}/${o}.`})}async function U(t,e){let r=A(t),n=await y(`${r}/branches/${encodeURIComponent(e)}`,{cookie:t.cookie});if(n.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode>=200&&n.statusCode<300)return{ok:!0,created:!1};if(n.statusCode!==404)return{ok:!1,error:`Could not check branch ${e} (HTTP ${n.statusCode}).`};let o=e.split("/").filter(Boolean),s=o[o.length-1],i=o.slice(0,-1).join("/");if(!s||!i)return{ok:!1,error:`Cannot create branch from path "${e}" \u2014 expected a parent and a name.`};let a=await y(`${r}/branches`,{method:"POST",body:{parent:i,name:s},cookie:t.cookie});return a.sessionExpired?{ok:!1,error:"IMS session expired \u2014 re-sign in."}:a.statusCode<200||a.statusCode>=300?{ok:!1,error:`Could not create branch ${e} (HTTP ${a.statusCode}).`}:{ok:!0,created:!0}}async function ar(t,e,r){let n=`${w(t)}/projects/${e}/tasks/${r}`;return(await y(n,{cookie:t.cookie})).body?.branchPath??null}async function ue(t,e,r){let n=r?.get(e);if(n)return n;let o=`${w(t)}/projects/${e}`,i=(await y(o,{cookie:t.cookie})).body?.metadata??{};return r?.set(e,i),i}async function V(t,e,r){let n=await ue(t,e,r),o=n.multipleModuleEditingDisabled,s=!o||o==="false";return n.expectedExtensionModules?.length&&s?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:ir}async function ot(t,e,r){let n=await ue(t,e,r);return ae(n)}async function vt(t,e){let r=t.replace(/\/$/,"")+"/auth",n=await y(r,{cookie:e,timeoutMs:8e3});return n.statusCode>=200&&n.statusCode<300&&n.body?n.body:(console.warn(`[authoring-cli] fetchAccountDetails: HTTP ${n.statusCode} from ${r}`),null)}var pe=v(require("crypto"));var cr="116680003";function nt(t,e,r,n,o="PREFERRED",s=!1){let i=t==="FSN"?ce(n,s):St(n,o,s,"en");return{active:!0,moduleId:r,type:t,term:e,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:i}}async function me(t,e,r,n=new Map){if(!e.fsn||!e.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await k(t,e,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:s,taskKey:i,branchPath:a}=o,c=_(a),d=e.moduleId||await V(t,s,n),l=await ot(t,s,n),u=e.preferredTerm||e.fsn,f=e.semanticTag?`${e.fsn} (${e.semanticTag})`:e.fsn,g={conceptId:null,moduleId:d,definitionStatus:"PRIMITIVE",active:!0,descriptions:[nt("FSN",f,d,l,"PREFERRED",!0),nt("SYNONYM",u,d,l,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:pe.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:d,relationships:[{active:!0,groupId:0,type:{conceptId:cr},target:{conceptId:e.parentConceptId}}]}]},C=`${A(t)}/browser/${c}/${s}/${i}/concepts/?validate=true`,x=await y(C,{method:"POST",body:g,cookie:t.cookie});if(x.sessionExpired){let P="IMS session expired \u2014 re-sign in.";return t.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: SESSION EXPIRED`),{statusCode:401,body:{error:P}}}let h=x.body,T=h&&"conceptId"in h?h.conceptId:void 0;return t.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: ${x.statusCode<300?"OK":"FAILED ("+x.statusCode+")"} \u2014 ${f}`+(T?` \u2192 ${T}`:"")),typeof T=="string"&&t.onValidationResults?.(T,h?.validationResults),{statusCode:x.statusCode,body:x.body}}async function rt(t,e,r){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${A(t)}/browser/${n.branchPath}/concepts/${e.conceptId}`,s=await y(o,{cookie:t.cookie});return s.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:s.statusCode,body:s.body}}async function st(t,e,r){if(!e.term&&!e.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o={limit:e.limit??50,expand:"fsn()"};e.term&&(o.termFilter=e.term),e.ecl&&(o.eclFilter=e.ecl),typeof e.active=="boolean"&&(o.activeFilter=e.active);let s=`${A(t)}/${n.branchPath}/concepts/search`,i=await y(s,{method:"POST",body:o,cookie:t.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let a=(i.body?.items??[]).map(c=>({conceptId:c.conceptId,fsn:c.fsn?.term,pt:c.pt?.term,active:c.active,moduleId:c.moduleId}));return{statusCode:i.statusCode,body:{total:i.body?.total??a.length,items:a}}}var At=v(require("crypto"));function fe(t){return typeof t=="object"&&t!==null}function dr(t){let e=t.type,r=t.target,n=fe(e)?e.conceptId:void 0,o=fe(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function lr(t,e){let r=[...e];for(let n of t){let o=r.findIndex(s=>s.typeId===n.typeId&&s.targetId===n.targetId);if(o===-1)return!1;r.splice(o,1)}return!0}function ge(t,e,r){let n=new Map;for(let i of t){let a=typeof i.groupId=="number"?i.groupId:0,c=n.get(a);c?c.push(i):n.set(a,[i])}let o=[];for(let[i,a]of n){if(r!=null?i!==r:i===0)continue;let c=a.map(dr).filter(d=>d!=null);lr(e,c)&&o.push(i)}if(o.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(o.length>1)return{ok:!1,statusCode:409,error:`has ${o.length} role groups matching the given attributes (groupIds: ${o.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let s=o[0];return{ok:!0,groupId:s,relationships:n.get(s)}}var ur=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],pr=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],mr=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],fr=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],gr=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],wt=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function be(t){return wt.includes(t)}function X(t,e){let r={};for(let n of e)n in t&&(r[n]=t[n]);return r}function it(t){return typeof t=="object"&&t!==null}function ye(t){return it(t)?X(t,fr):t}function Se(t){if(!it(t))return t;let e=X(t,mr);return"type"in e&&(e.type=ye(e.type)),"target"in e&&(e.target=ye(e.target)),e}function yr(t){return it(t)?X(t,pr):t}function ke(t){if(!it(t))return t;let e=X(t,gr);return Array.isArray(e.relationships)&&(e.relationships=e.relationships.map(Se)),e}function Rt(t){let e=X(t,ur);return Array.isArray(e.descriptions)&&(e.descriptions=e.descriptions.map(yr)),Array.isArray(e.relationships)&&(e.relationships=e.relationships.map(Se)),Array.isArray(e.classAxioms)&&(e.classAxioms=e.classAxioms.map(ke)),Array.isArray(e.gciAxioms)&&(e.gciAxioms=e.gciAxioms.map(ke)),e}async function R(t,e,r,n){let o=A(t),s=`${o}/browser/${e.branchPath}/concepts/${r}`,i=await y(s,{cookie:t.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:i.body}};let a=i.body,c=n(a);if(c)return c;let d=_(e.branchPath),l=`${o}/browser/${d}/${e.projectKey}/${e.taskKey}/concepts/${r}?validate=true`,u=await y(l,{method:"PUT",body:Rt(a),cookie:t.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};t.onLog?.(`[${new Date().toISOString()}] update-concept ${e.projectKey}/${e.taskKey}: ${u.statusCode<300?"OK":"FAILED ("+u.statusCode+")"} \u2014 ${r}`);let f=u.body;return t.onValidationResults?.(r,f?.validationResults),{statusCode:u.statusCode,body:u.body}}var he=["PREFERRED","ACCEPTABLE"];async function ve(t,e,r,n=new Map){if(!e.conceptId||!e.term||!e.type)return{statusCode:400,body:{error:"conceptId, term, and type are required."}};if(e.type!=="FSN"&&e.type!=="SYNONYM")return{statusCode:400,body:{error:"type must be FSN or SYNONYM."}};if(e.acceptability&&!he.includes(e.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${he.join(", ")}.`}};let o=await k(t,e,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=e.moduleId||await V(t,o.projectKey,n),i=await ot(t,o.projectKey,n),a=e.type==="FSN"&&e.semanticTag?`${e.term} (${e.semanticTag})`:e.term;return R(t,o,e.conceptId,c=>{let d=Array.isArray(c.descriptions)?c.descriptions:[];return d.push(nt(e.type,a,s,i,e.acceptability??"ACCEPTABLE",!1)),c.descriptions=d,null})}async function Te(t,e,r){if(!e.conceptId||!e.typeId||!e.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=e.axiomIndex??0;return R(t,n,e.conceptId,s=>{let i=Array.isArray(s.classAxioms)?s.classAxioms:[],a=i[o];if(!a)return{statusCode:400,body:{error:`Concept ${e.conceptId} has no classAxiom at index ${o} (has ${i.length}).`}};let c=Array.isArray(a.relationships)?a.relationships:[];return c.push({active:!0,groupId:e.groupId??0,type:{conceptId:e.typeId},target:{conceptId:e.targetId}}),a.relationships=c,null})}async function Ae(t,e,r){if(!e.conceptId||!e.status)return{statusCode:400,body:{error:"conceptId and status are required."}};if(e.status!=="PRIMITIVE"&&e.status!=="FULLY_DEFINED")return{statusCode:400,body:{error:"status must be PRIMITIVE or FULLY_DEFINED."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=e.axiomIndex??0;return R(t,n,e.conceptId,s=>{let i=Array.isArray(s.classAxioms)?s.classAxioms:[],a=i[o];return a?(a.definitionStatus=e.status,s.definitionStatus=e.status,null):{statusCode:400,body:{error:`Concept ${e.conceptId} has no classAxiom at index ${o} (has ${i.length}).`}}})}async function we(t,e,r){if(!e.conceptId||!e.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>(o.active=!1,o.inactivationIndicator=e.indicator,e.associationRefsetId&&e.associationTargetId&&(o.associationTargets={[e.associationRefsetId]:[e.associationTargetId]}),null)):{statusCode:400,body:{error:n.error}}}async function Re(t,e,r){if(!e.conceptId||!e.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};if(!e.term&&!e.caseSignificance)return{statusCode:400,body:{error:"At least one of term or caseSignificance must be provided."}};if(e.caseSignificance&&!be(e.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${wt.join(", ")}.`}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===e.descriptionId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`Description ${e.descriptionId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(e.term&&(i.term=e.term),e.caseSignificance&&(i.caseSignificance=e.caseSignificance),null):{statusCode:404,body:{error:`Concept ${e.conceptId} has no description ${e.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}async function $e(t,e,r){if(!e.conceptId||!e.descriptionId||!e.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!be(e.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${wt.join(", ")}.`}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===e.descriptionId);return i?(i.caseSignificance=e.caseSignificance,null):{statusCode:404,body:{error:`Concept ${e.conceptId} has no description ${e.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}var Tt=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function Ce(t){return Tt.includes(t)}function Ee(t){return t.descriptionId?!t.lang&&!t.us&&!t.gb?{statusCode:400,body:{error:`Entry for description ${t.descriptionId} must set at least one of lang, us, or gb.`}}:t.us&&!Ce(t.us)?{statusCode:400,body:{error:`us must be one of: ${Tt.join(", ")}.`}}:t.gb&&!Ce(t.gb)?{statusCode:400,body:{error:`gb must be one of: ${Tt.join(", ")}.`}}:null:{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function je(t,e,r){let n=t.find(s=>s.descriptionId===r.descriptionId);if(!n)return{statusCode:404,body:{error:`Concept ${e} has no description ${r.descriptionId}.`}};r.lang&&(n.lang=r.lang);let o={...n.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete o[L]:o[L]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[z]:o[z]=r.gb),n.active!==!1&&Object.keys(o).length===0?{statusCode:400,body:{error:`Description ${r.descriptionId} would have an empty acceptabilityMap (Not Acceptable in every dialect) \u2014 an active description must be acceptable in at least one.`}}:(n.acceptabilityMap=o,null)}async function Pe(t,e,r){if(!e.conceptId||!e.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n={descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb},o=Ee(n);if(o)return o;let s=await k(t,e,r);return s.ok?R(t,s,e.conceptId,i=>{let a=Array.isArray(i.descriptions)?i.descriptions:[];return je(a,e.conceptId,n)}):{statusCode:400,body:{error:s.error}}}async function Ne(t,e,r){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};if(!Array.isArray(e.entries)||e.entries.length===0)return{statusCode:400,body:{error:"entries must be a non-empty array."}};for(let o of e.entries){let s=Ee(o);if(s)return s}let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[];for(let i of e.entries){let a=je(s,e.conceptId,i);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function De(t,e,r){if(!e.conceptId||!e.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[],i=s.findIndex(a=>a.descriptionId===e.descriptionId);return i===-1?{statusCode:404,body:{error:`Concept ${e.conceptId} has no description ${e.descriptionId}.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Description ${e.descriptionId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.descriptions=s,null)}):{statusCode:400,body:{error:n.error}}}async function $t(t,e,r){if(!e.conceptId||!e.axiomId||!Array.isArray(e.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(a=>a.axiomId===e.axiomId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${e.axiomId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(i.relationships=e.relationships,null):{statusCode:404,body:{error:`Concept ${e.conceptId} has no class axiom ${e.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Oe(t,e,r){if(!e.conceptId||!e.axiomId||!Array.isArray(e.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===e.axiomId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`GCI axiom ${e.axiomId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(i.relationships=e.relationships,null):{statusCode:404,body:{error:`Concept ${e.conceptId} has no GCI axiom ${e.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Et(t,e,r,n=new Map){if(!e.conceptId||!Array.isArray(e.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(e.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};if(e.definitionStatus&&e.definitionStatus!=="PRIMITIVE"&&e.definitionStatus!=="FULLY_DEFINED")return{statusCode:400,body:{error:"definitionStatus must be PRIMITIVE or FULLY_DEFINED."}};let o=await k(t,e,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=e.moduleId||await V(t,o.projectKey,n);return R(t,o,e.conceptId,i=>{let a=Array.isArray(i.classAxioms)?i.classAxioms:[];return a.push({axiomId:At.randomUUID(),definitionStatus:e.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:e.relationships}),i.classAxioms=a,null})}async function Fe(t,e,r,n=new Map){if(!e.conceptId||!Array.isArray(e.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(e.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};let o=await k(t,e,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=e.moduleId||await V(t,o.projectKey,n);return R(t,o,e.conceptId,i=>{let a=Array.isArray(i.gciAxioms)?i.gciAxioms:[];return a.push({axiomId:At.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:e.relationships}),i.gciAxioms=a,null})}async function Ke(t,e,r){if(!e.conceptId||!e.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let s=Array.isArray(o.classAxioms)?o.classAxioms:[],i=s.findIndex(a=>a.axiomId===e.axiomId);return i===-1?{statusCode:404,body:{error:`Concept ${e.conceptId} has no class axiom ${e.axiomId}.`}}:s.length<2?{statusCode:409,body:{error:`Concept ${e.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${e.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.classAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}async function jt(t,e,r){if(!e.conceptId||!e.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let s=Array.isArray(o.classAxioms)?o.classAxioms:[],i=s.find(c=>c.axiomId===e.axiomId);return i?i.active===!1?{statusCode:409,body:{error:`Axiom ${e.axiomId} is already inactive.`}}:s.filter(c=>c!==i&&c.active!==!1).length===0?{statusCode:409,body:{error:`Concept ${e.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:(i.active=!1,null):{statusCode:404,body:{error:`Concept ${e.conceptId} has no class axiom ${e.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}var kr="116680003";function xe(t,e){let r={active:!0,groupId:e,type:{conceptId:t.type?.id}};return t.concrete?r.concreteValue={dataType:t.value?.dataType,value:t.value?.value}:r.target={conceptId:t.target?.id},r}function hr(t){let e=[],r=Array.isArray(t.concepts)?t.concepts:[];for(let s of r)s?.id&&e.push({active:!0,groupId:0,type:{conceptId:kr},target:{conceptId:s.id}});let n=Array.isArray(t.attributes)?t.attributes:[];for(let s of n)e.push(xe(s,0));return(Array.isArray(t.groups)?t.groups:[]).forEach((s,i)=>{let a=Array.isArray(s.attributes)?s.attributes:[];for(let c of a)e.push(xe(c,i+1))}),e}async function Le(t,e,r,n){let o=A(t),s=await y(`${o}/browser/${e.branchPath}/concepts/${r}`,{cookie:t.cookie});if(s.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{ok:!1,result:{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:s.body}}};let i=Array.isArray(s.body.classAxioms)?s.body.classAxioms:[],a;if(n){if(a=i.find(l=>l.axiomId===n),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${n}.`}}}}else{let l=i.filter(u=>u.active!==!1);if(l.length===0)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has no active class axiom.`}}};if(l.length>1)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has ${l.length} active class axioms \u2014 pass axiomId to pick which one.`}}};a=l[0]}let c=await y(`${o}/${e.branchPath}/concepts/${r}/authoring-form`,{cookie:t.cookie});if(c.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}};if(c.statusCode<200||c.statusCode>=300||!c.body)return{ok:!1,result:{statusCode:c.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:c.body}}};let d=hr(c.body);return d.length===0?{ok:!1,result:{statusCode:409,body:{error:`Authoring form for ${r} produced no relationships \u2014 the concept likely hasn't been classified since its last stated edit. Run classify --wait first.`}}}:{ok:!0,value:{axiom:a,axiomId:a.axiomId,targetRelationships:d}}}function Cr(t){let e=typeof t.typeId=="string"?t.typeId:t.type?.conceptId,r=t.concreteValue;if(r)return`${e}=#${r.dataType}:${r.value}`;let n=typeof t.destinationId=="string"?t.destinationId:t.target?.conceptId;return`${e}=${n}`}function Ie(t){let e=new Map;for(let o of t){if(o.active===!1)continue;let s=typeof o.groupId=="number"?o.groupId:0,i=e.get(s)??[];i.push(Cr(o)),e.set(s,i)}let r=(e.get(0)??[]).slice().sort(),n=[];for(let[o,s]of e)o!==0&&n.push(s.slice().sort());return{ungrouped:r,groups:n}}function Be(t,e){let r=Ie(t),n=Ie(e);if(r.ungrouped.join("|")!==n.ungrouped.join("|"))return!1;let o=r.groups.map(i=>i.join("|")).sort(),s=n.groups.map(i=>i.join("|")).sort();return o.join("||")===s.join("||")}async function Me(t,e,r,n=new Map){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await k(t,e,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=await Le(t,o,e.conceptId,e.axiomId);if(!s.ok)return s.result;let{axiom:i,axiomId:a,targetRelationships:c}=s.value,d=Array.isArray(i.relationships)?i.relationships:[];if(Be(d,c))return{statusCode:200,body:{conceptId:e.conceptId,axiomId:a,alreadyConformed:!0}};if(!(i.effectiveTime!=null))return $t(t,{conceptId:e.conceptId,axiomId:a,relationships:c,projectKey:o.projectKey,taskKey:o.taskKey},r);let u=await Et(t,{conceptId:e.conceptId,relationships:c,moduleId:typeof i.moduleId=="string"?i.moduleId:void 0,definitionStatus:i.definitionStatus,projectKey:o.projectKey,taskKey:o.taskKey},r,n);if(u.statusCode<200||u.statusCode>=300)return u;let f=await jt(t,{conceptId:e.conceptId,axiomId:a,projectKey:o.projectKey,taskKey:o.taskKey},r);return f.statusCode<200||f.statusCode>=300?{statusCode:f.statusCode,body:{error:`Added the transformed axiom but failed to inactivate published axiom ${a}: ${JSON.stringify(f.body)}`,addResult:u.body}}:{statusCode:f.statusCode,body:{replacedAxiomId:a,addResult:u.body,inactivateResult:f.body}}}async function q(t,e,r){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await Le(t,n,e.conceptId,e.axiomId);if(!o.ok)return o.result;let{axiom:s,axiomId:i,targetRelationships:a}=o.value,c=Array.isArray(s.relationships)?s.relationships:[],d=Be(c,a);return{statusCode:200,body:{conceptId:e.conceptId,axiomId:i,conforms:d}}}async function _e(t,e,r){if(!e.conceptId||!e.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};if(!e.relationshipId&&e.relationshipIndex==null)return{statusCode:400,body:{error:"One of relationshipId or relationshipIndex is required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.axiomId===e.axiomId);if(!i)return{statusCode:404,body:{error:`Concept ${e.conceptId} has no class axiom ${e.axiomId}.`}};let a=Array.isArray(i.relationships)?i.relationships:[],c=e.relationshipId?a.findIndex(l=>l.relationshipId===e.relationshipId):e.relationshipIndex,d=c>=0?a[c]:void 0;return d?d.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${e.relationshipId??`at index ${c}`} has effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.splice(c,1),i.relationships=a,null):{statusCode:404,body:{error:`Axiom ${e.axiomId} has no relationship ${e.relationshipId??`at index ${e.relationshipIndex}`}.`}}}):{statusCode:400,body:{error:n.error}}}async function Ue(t,e,r){if(!e.conceptId||!e.axiomId||!Array.isArray(e.attributes)||e.attributes.length===0)return{statusCode:400,body:{error:"conceptId, axiomId, and a non-empty attributes array are required."}};for(let o of e.attributes)if(!o||typeof o.typeId!="string"||typeof o.targetId!="string")return{statusCode:400,body:{error:"Each attributes entry requires typeId and targetId."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.axiomId===e.axiomId);if(!i)return{statusCode:404,body:{error:`Concept ${e.conceptId} has no class axiom ${e.axiomId}.`}};let a=Array.isArray(i.relationships)?i.relationships:[],c=ge(a,e.attributes,e.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${e.axiomId} ${c.error}`}};let d=c.relationships.find(l=>l.effectiveTime!=null);return d?{statusCode:409,body:{error:`Role group (groupId ${c.groupId}) on axiom ${e.axiomId} has a relationship (relationshipId ${String(d.relationshipId)}) with effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(i.relationships=a.filter(l=>(typeof l.groupId=="number"?l.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function Ve(t,e,r){if(!e.conceptId||!e.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let s=Array.isArray(o.gciAxioms)?o.gciAxioms:[],i=s.findIndex(a=>a.axiomId===e.axiomId);return i===-1?{statusCode:404,body:{error:`Concept ${e.conceptId} has no GCI axiom ${e.axiomId}.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`GCI axiom ${e.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.gciAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}async function at(t,e,r,n,o){let s=[],i=[];for(let a of r){let c=await q(t,{conceptId:a.conceptId,projectKey:e.projectKey,taskKey:e.taskKey,branchPath:e.branchPath},o),d=c.body;if(c.statusCode<200||c.statusCode>=300||typeof d?.conforms!="boolean"){i.push({...a,error:d?.error??`HTTP ${c.statusCode}`});continue}d.conforms===n&&s.push({...a,axiomId:d.axiomId,conforms:d.conforms})}return{matched:s,skipped:i}}async function qe(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await st(t,{...e,branchPath:n.branchPath},r);if(o.statusCode<200||o.statusCode>=300)return o;let s=o.body?.items??[],i=e.conformed===!0,a=s.map(l=>({conceptId:l.conceptId,fsn:l.fsn,pt:l.pt})),{matched:c,skipped:d}=await at(t,n,a,i,r);return{statusCode:200,body:{branchPath:n.branchPath,totalSearched:s.length,conformed:i,matched:c.length,skipped:d.length,results:c,skippedConcepts:d}}}async function Je(t,e,r){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(t),s=`${o}/browser/${n.branchPath}/concepts/${e.conceptId}`,i=await y(s,{cookie:t.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${e.conceptId}.`,details:i.body}};if(i.body.effectiveTime!=null)return{statusCode:409,body:{error:`Concept ${e.conceptId} has effectiveTime ${String(i.body.effectiveTime)} set (already versioned) \u2014 cannot delete.`}};let a=`${o}/${n.branchPath}/concepts/${e.conceptId}`,c=await y(a,{method:"DELETE",cookie:t.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(t.onLog?.(`[${new Date().toISOString()}] delete-concept ${n.projectKey}/${n.taskKey}: ${c.statusCode<300?"OK":"FAILED ("+c.statusCode+")"} \u2014 ${e.conceptId}`),c.statusCode===409?{statusCode:409,body:{error:`Cannot delete concept ${e.conceptId} \u2014 one or more of its components is published.`,details:c.body}}:{statusCode:c.statusCode,body:c.body})}function xr(t){let e=[];for(let r of t)e.some(o=>o.componentId===r.componentId&&o.severity===r.severity&&o.conceptId===r.conceptId&&o.message===r.message)||e.push(r);return e}async function ct(t,e,r){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(t),s=`${o}/browser/${n.branchPath}/concepts/${e.conceptId}`,i=await y(s,{cookie:t.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${e.conceptId}.`,details:i.body}};let a=_(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,d=await y(c,{method:"POST",body:Rt(i.body),cookie:t.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(d.statusCode<200||d.statusCode>=300)return{statusCode:d.statusCode,body:{error:"Validation check failed.",details:d.body}};let l=Array.isArray(d.body)?xr(d.body):[],u=await q(t,{conceptId:e.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),f=u.body;return u.statusCode>=200&&u.statusCode<300&&f?.conforms===!1&&l.push({conceptId:e.conceptId,componentId:f.axiomId,severity:"WARNING",message:"Axiom does not conform to the standard authoring form (Is-a the proximal primitive parent(s) plus every currently-inferred attribute) \u2014 run transform-axiom to fix."}),{statusCode:200,body:{conceptId:e.conceptId,validationResults:l,hasErrors:l.some(g=>g.severity==="ERROR"),hasWarnings:l.some(g=>g.severity==="WARNING")}}}var Ge=200;async function Ir(t,e,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${A(t)}/browser/${e}/concepts/bulk-load`,s=!0;for(let i=0;i<r.length;i+=Ge){let a=r.slice(i,i+Ge),c=await y(o,{method:"POST",body:{conceptIds:a},cookie:t.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){s=!1;continue}for(let d of c.body)n.set(d.conceptId,{fsn:d.fsn?.term,pt:d.pt?.term})}return{terms:n,resolved:s}}async function O(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${le(t)}/activities?size=500&onBranch=${encodeURIComponent(n.branchPath)}`,s=await y(o,{cookie:t.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode===404)return{statusCode:200,body:{branchPath:n.branchPath,concepts:[],conceptsClassified:[]}};if(s.statusCode<200||s.statusCode>=300)return{statusCode:s.statusCode,body:{error:"Could not fetch traceability for branch.",details:s.body}};let i=new Map,a=new Map,c=(x,h,T,P)=>{let j=x.get(h);j?(P.forEach(E=>E&&j.componentSubTypes.add(E)),j.lastUpdatedTime=T):x.set(h,{conceptId:h,lastUpdatedTime:T,componentSubTypes:new Set(P.filter(E=>!!E))})};for(let x of s.body?.content??[])if(!(x.activityType!=="CONTENT_CHANGE"&&x.activityType!=="CLASSIFICATION_SAVE"))for(let h of x.conceptChanges??[]){let T=String(h.conceptId),P=h.componentChanges??[],j=P.map(Y=>Y.componentSubType);if(x.activityType==="CLASSIFICATION_SAVE"){c(a,T,x.commitDate,j);continue}let E=P.some(Y=>Y.componentSubType!=="INFERRED_RELATIONSHIP");c(E?i:a,T,x.commitDate,j)}for(let x of i.keys())a.delete(x);let d=[...new Set([...i.keys(),...a.keys()])],{terms:l,resolved:u}=await Ir(t,n.branchPath,d),f=x=>[...x.values()].sort((h,T)=>(T.lastUpdatedTime??"").localeCompare(h.lastUpdatedTime??"")).map(h=>{let T=u&&!l.has(h.conceptId);return{conceptId:h.conceptId,fsn:l.get(h.conceptId)?.fsn,pt:l.get(h.conceptId)?.pt,...T?{deleted:!0}:{},lastUpdatedTime:h.lastUpdatedTime,changedComponentTypes:[...h.componentSubTypes]}}),g=f(i),C=f(a);return{statusCode:200,body:{branchPath:n.branchPath,...u?{summary:{concepts:g.length,conceptsDeleted:g.filter(x=>x.deleted).length,conceptsClassified:C.length}}:{},concepts:g,conceptsClassified:C}}}async function He(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await O(t,e,r);if(o.statusCode<200||o.statusCode>=300){let u=o.body;return{statusCode:o.statusCode,body:{error:u.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=s.filter(u=>!u.deleted),a=e.conformed===!0,c=i.map(u=>({conceptId:u.conceptId,fsn:u.fsn})),{matched:d,skipped:l}=await at(t,n,c,a,r);return{statusCode:200,body:{branchPath:n.branchPath,conformed:a,totalReviewed:i.length,matched:d.length,skipped:l.length,skippedDeleted:s.length-i.length,results:d,skippedConcepts:l}}}async function Ye(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await O(t,e,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=[];for(let c of s){if(c.deleted){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"deleted"});continue}let d=await ct(t,{conceptId:c.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),l=d.body;if(d.statusCode<200||d.statusCode>=300){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"failed",error:l.error??`HTTP ${d.statusCode}`});continue}let u=l.validationResults??[];i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:u.length===0?"clean":"issues",validationResults:u.length?u:void 0,hasErrors:l.hasErrors})}let a=c=>i.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:i.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:i}}}async function We(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await O(t,e,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=[];for(let c of s){if(c.deleted){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"deleted"});continue}let d=await rt(t,{conceptId:c.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),l=d.body;if(d.statusCode<200||d.statusCode>=300){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"failed",error:l?.error??`HTTP ${d.statusCode}`});continue}i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"fetched",concept:d.body})}let a=c=>i.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:i.length,fetched:a("fetched"),skippedDeleted:a("deleted"),failed:a("failed")},concepts:i}}}var Pt=new Set;function ze(t){if(!(!t||typeof t!="object"))for(let e of Pt)e(t)}function br(t){return Pt.add(t),()=>Pt.delete(t)}function Sr(t,e){return e.entityType!==void 0&&t.entityType!==e.entityType?!1:t.task?t.task===e.taskKey&&t.project===e.projectKey:t.project?t.project===e.projectKey:t.branchPath===e.branchPath}function dt(t){let e=()=>{};return{promise:new Promise(n=>{e=br(o=>{Sr(o,t)&&(e(),n(o))})}),cancel:e}}async function F(t,e,r){let n=`${w(t)}/projects/${e}/tasks/${r}`;return(await y(n,{cookie:t.cookie})).body??null}var Ft=["RUNNING","BUILDING","SCHEDULED","QUEUED"],Kt=["QUEUED","SCHEDULED","RUNNING"],vr=["Promoted","Completed"],Xe=5e3;function Ot(t){return new Promise(e=>setTimeout(e,t))}async function Tr(t,e,r){let n=0;for(;;){let{done:o,value:s}=await t();if(o)return{value:s,timedOut:!1};if(n>=r)return{value:s,timedOut:!0};n++,await Ot(e)}}function Ar(){let t=[9e4];for(let e=0;e<3;e++)t.push(1e4);for(let e=0;e<12;e++)t.push(5e3);return t}var wr=Ar(),Rr=180;function $r(){let t=[3e5];for(let e=0;e<5;e++)t.push(6e4);for(let e=0;e<10;e++)t.push(3e4);return t}var Er=$r(),jr=900;async function to(t,e,r,n,o){let s=r*1e3,i=Date.now(),a=0;for(;;){let c=e[Math.min(a,e.length-1)],d=n?dt(n):void 0,l=await Promise.race(d?[Ot(c).then(()=>{}),d.promise]:[Ot(c).then(()=>{})]);if(d?.cancel(),l){let g=l.event;o?.(`[${new Date().toISOString()}] woken by notification${g?`: ${g}`:""}`)}let{done:u,value:f}=await t();if(u)return{value:f,timedOut:!1};if(Date.now()-i>=s)return{value:f,timedOut:!0};a++}}async function eo(t,e,r){let n=await F(t,e,r);if(!n)return{error:`Could not fetch task ${e}/${r}.`};if(n.status&&vr.includes(n.status))return{error:`Task ${e}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${w(t)}/projects/${e}/tasks/${r}`;await y(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:t.cookie})}return{}}async function Lt(t,e,r){let n=`${w(t)}/projects/${e}/tasks/${r}/classifications/status/cache-evict`;return await y(n,{method:"POST",body:{},cookie:t.cookie}),(await F(t,e,r))?.latestClassificationJson}async function Qe(t,e,r,n,o){let s,{value:i,timedOut:a}=await to(async()=>{let d=(await Lt(t,e,r))?.status;return d!==s&&(s=d,t.onLog?.(`[${new Date().toISOString()}] classify ${e}/${r}: status ${d??"unknown"}`)),{done:!(!d||Ft.includes(d)),value:d}},wr,o,{entityType:"Classification",projectKey:e,taskKey:r,branchPath:n},t.onLog);return{finalStatus:i,timedOut:a}}async function Nt(t,e,r){let n=`${A(t)}/${e}/classifications`,o=await y(n,{cookie:t.cookie});if(o.body?.items?.length)return o.body.items.find(s=>s.id===r)??o.body.items[o.body.items.length-1]}async function oo(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,i=await Lt(t,o,s);return i?{statusCode:200,body:{hasClassification:!0,jobId:i.id,status:i.status,running:Ft.includes(i.status),latestClassificationJson:i}}:{statusCode:200,body:{hasClassification:!1}}}async function no(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await eo(t,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=e.timeoutSeconds??Rr,d=await Lt(t,o,s),l=d?.status,u=d?.id;if(u&&l&&Ft.includes(l)){t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:E}=await Qe(t,o,s,i,c),Y=await Nt(t,i,u),bt={accepted:!1};return!E&&j==="COMPLETED"&&(bt=await Dt(t,i,o,s,u)),t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: attached job ${u} final status ${j??"unknown"}${E?" (timed out waiting)":""}, save ${JSON.stringify(bt)}`),{statusCode:200,body:{jobId:u,finalStatus:j,timedOut:E,details:Y,save:bt,attachedToExisting:!0}}}if(u&&l==="COMPLETED"){t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await Nt(t,i,u),E=await Dt(t,i,o,s,u);return t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: accepted existing job ${u}, save ${JSON.stringify(E)}`),{statusCode:200,body:{jobId:u,finalStatus:"COMPLETED",timedOut:!1,details:j,save:E,acceptedExisting:!0}}}let f=`${w(t)}/projects/${o}/tasks/${s}/classifications`,g=await y(f,{method:"POST",body:{},cookie:t.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!g.body?.id)return t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: start failed (HTTP ${g.statusCode}) \u2014 raw body: ${g.rawBody}`),{statusCode:g.statusCode||500,body:{error:"Failed to start classification.",details:g.body??g.rawBody}};t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: started (${g.body.status??"unknown"})`);let C=g.body.id;if(!e.wait)return{statusCode:200,body:{jobId:C,status:g.body.status}};let{finalStatus:x,timedOut:h}=await Qe(t,o,s,i,c),T=await Nt(t,i,C),P={accepted:!1};return!h&&x==="COMPLETED"&&(P=await Dt(t,i,o,s,C)),t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: final status ${x??"unknown"}${h?" (timed out waiting)":""}, save ${JSON.stringify(P)}`),{statusCode:200,body:{jobId:C,finalStatus:x,timedOut:h,details:T,save:P}}}var Pr=["SAVED","STALE","SAVE_FAILED"],Nr=120;async function Dt(t,e,r,n,o){let s=`${A(t)}/${e}/classifications/${o}`,i=await y(s,{method:"PUT",body:{status:"SAVED"},cookie:t.cookie});if(i.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(i.statusCode<200||i.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${i.statusCode}).`};let a=Math.ceil(Nr*1e3/Xe),{value:c,timedOut:d}=await Tr(async()=>{let u=(await y(s,{cookie:t.cookie})).body?.status;return{done:!!u&&Pr.includes(u),value:u}},Xe,a);return d?{accepted:!1,status:c,error:"Timed out waiting for classification results to save."}:c==="SAVED"?{accepted:!0,status:c}:{accepted:!1,status:c,error:c==="STALE"?"Report stale \u2014 re-classify and save.":"Saving classification failed."}}async function ro(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,a=(await F(t,o,s))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&Kt.includes(a)}}}async function Ze(t,e,r,n,o){let s,{value:i,timedOut:a}=await to(async()=>{let d=(await F(t,e,r))?.latestValidationStatus;return d!==s&&(s=d,t.onLog?.(`[${new Date().toISOString()}] validate-task ${e}/${r}: status ${d??"unknown"}`)),{done:!(!d||Kt.includes(d)),value:d}},Er,o,{entityType:"Validation",projectKey:e,taskKey:r,branchPath:n},t.onLog);return{finalStatus:i,timedOut:a}}async function so(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await eo(t,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=e.timeoutSeconds??jr,l=(await F(t,o,s))?.latestValidationStatus;if(l&&Kt.includes(l)){t.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: validation already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:x,timedOut:h}=await Ze(t,o,s,i,c);return t.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: attached run final status ${x??"unknown"}${h?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:x,timedOut:h,attachedToExisting:!0}}}let u=`${w(t)}/projects/${o}/tasks/${s}/validation`;typeof e.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${e.enableMrcmValidation}`);let f=await y(u,{method:"POST",body:{},cookie:t.cookie});if(f.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(f.statusCode<200||f.statusCode>=300)return{statusCode:f.statusCode,body:{error:"Failed to start validation.",details:f.body}};if(t.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: started`),!e.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:g,timedOut:C}=await Ze(t,o,s,i,c);return t.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: final status ${g??"unknown"}${C?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:g,timedOut:C}}}async function io(t,e={}){let r=e.lightweight!==void 0?`?lightweight=${e.lightweight}`:"",n=`${w(t)}/projects${r}`;return(await y(n,{cookie:t.cookie})).body??[]}async function ao(t,e){let r=`${w(t)}/projects/${e}/tasks`;return(await y(r,{cookie:t.cookie})).body??[]}async function co(t,e={}){let r=e.excludePromoted!==void 0?`?excludePromoted=${e.excludePromoted}`:"",n=`${w(t)}/projects/my-tasks${r}`;return(await y(n,{cookie:t.cookie})).body??[]}async function lo(t,e){let r=`${w(t)}/projects/${e.projectKey}/tasks`,n={summary:e.summary};e.description!==void 0&&(n.description=e.description),e.assigneeUsername&&(n.assignee={username:e.assigneeUsername});let o=await y(r,{method:"POST",body:n,cookie:t.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to create task in ${e.projectKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}var Dr=["FORWARD","DIVERGED"];async function Or(t,e){if(!e)return!1;let r=`${A(t)}/branches/${encodeURIComponent(e)}`,n=await y(r,{cookie:t.cookie});return Dr.includes(n.body?.state??"")}var Fr=["Promoted","Completed"];async function uo(t,e){let r=`${w(t)}/projects/${e.projectKey}/tasks/${e.taskKey}`,n=await y(r,{cookie:t.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${e.projectKey}/${e.taskKey} (HTTP ${n.statusCode}).`};let o=n.body.status;if(o&&Fr.includes(o))return{statusCode:409,error:`${e.projectKey}/${e.taskKey} has status ${o} \u2014 its work is already in the project, so the task cannot be deleted.`};if(o==="Deleted")return{statusCode:200,task:n.body,alreadyDeleted:!0};let s=await Or(t,n.body.branchPath),i=await y(r,{method:"PUT",body:{status:"DELETED"},cookie:t.cookie});return i.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:i.statusCode<200||i.statusCode>=300||!i.body?{statusCode:i.statusCode||500,error:`Failed to delete ${e.projectKey}/${e.taskKey} (HTTP ${i.statusCode})${i.rawBody?`: ${i.rawBody}`:""}`}:{statusCode:i.statusCode,task:i.body,hadUnpromotedChanges:s}}async function po(t,e){let r=`${w(t)}/projects/tasks/search?projectKeys=${encodeURIComponent(e)}&statuses=Deleted`,n=await y(r,{cookie:t.cookie});return Array.isArray(n.body)?n.body:[]}var Kr="IN_PROGRESS";async function mo(t,e){let r=`${w(t)}/projects/${e.projectKey}/tasks/${e.taskKey}`,n=await y(r,{cookie:t.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${e.projectKey}/${e.taskKey} (HTTP ${n.statusCode}).`};if(n.body.status!=="Deleted")return{statusCode:200,task:n.body,notDeleted:!0};let o=await y(r,{method:"PUT",body:{status:Kr},cookie:t.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to recover ${e.projectKey}/${e.taskKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}function fo(t){if(t==="o")return{type:"open"};if(t==="h")return{type:"heartbeat"};if(t.startsWith("a"))try{return{type:"message",messages:JSON.parse(t.slice(1))}}catch{return{type:"unknown",raw:t}}if(t.startsWith("c"))try{let[e,r]=JSON.parse(t.slice(1));return{type:"close",code:e,reason:r}}catch{return{type:"unknown",raw:t}}return{type:"unknown",raw:t}}function Bt(t){return JSON.stringify([t])}function go(t=Math.random){let e=String(Math.floor(t()*1e3)).padStart(3,"0"),r="abcdefghijklmnopqrstuvwxyz0123456789",n="";for(let o=0;o<8;o++)n+=r[Math.floor(t()*r.length)];return`${e}/${n}/websocket`}function Mt(t,e={},r=""){let n=Object.entries(e).map(([o,s])=>`${o}:${s}`);return[t,...n,"",r].join(`
|
|
3
|
+
`)+"\0"}function yo(t){let e=t.replace(/\0$/,"");if(e.trim()==="")return null;let r=e.indexOf(`
|
|
4
4
|
|
|
5
|
-
`),n=r===-1?
|
|
6
|
-
`),i=s[0],a={};for(let c of s.slice(1)){let d=c.indexOf(":");d!==-1&&(a[c.slice(0,d)]=c.slice(d+1))}return{command:i,headers:a,body:o}}var
|
|
5
|
+
`),n=r===-1?e:e.slice(0,r),o=r===-1?"":e.slice(r+2),s=n.split(`
|
|
6
|
+
`),i=s[0],a={};for(let c of s.slice(1)){let d=c.indexOf(":");d!==-1&&(a[c.slice(0,d)]=c.slice(d+1))}return{command:i,headers:a,body:o}}var ho=v(require("ws"));var ko=[1e3,2e3,5e3,1e4,3e4];function Co(t,e={}){let r=e.createSocket??((l,u)=>new ho.default(l,u)),n=!1,o,s=0,i,a=t.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(n)return;let l=ko[Math.min(s,ko.length-1)];s+=1,i=setTimeout(d,l)};function d(){if(n)return;let u=`${t.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${go()}`,f=r(u,a?{headers:{cookie:a}}:{});o=f,f.on("message",g=>{let C=fo(g.toString());if(C.type==="open"){f.send(Bt(Mt("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(C.type==="close"){f.close();return}if(C.type==="message")for(let x of C.messages){let h=yo(x);if(h){if(h.command==="CONNECTED"){s=0;let T=`/topic/user/${t.login}/notifications`;f.send(Bt(Mt("SUBSCRIBE",{id:`sca-subscription-id-${t.login}`,destination:T})));continue}if(h.command==="MESSAGE"){try{t.onNotification(JSON.parse(h.body))}catch(T){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",T)}continue}h.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",h.headers,h.body)}}}),f.on("unexpected-response",(g,C)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${C.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),f.terminate()}),f.on("error",g=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",g.message)}),f.on("close",c)}return d(),{stop(){n=!0,i&&clearTimeout(i),o?.removeAllListeners(),o?.close()}}}function xo(t,e,r={}){let n=r.startRelay??Co,o=r.onNotification??ze,s=n({authoringServicesEndpoint:t.authoringServicesEndpoint,cookie:t.cookie,login:e,onNotification:o});return{stop:()=>s.stop()}}var Lr=60;async function Io(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=e.timeoutSeconds??Lr,c=dt({entityType:e.entityType,projectKey:o,taskKey:s,branchPath:i}),d,l=new Promise(g=>{d=setTimeout(()=>g({kind:"timeout"}),a*1e3)}),u=c.promise.then(g=>({kind:"notification",payload:g})),f=await Promise.race([u,l]);return c.cancel(),clearTimeout(d),f.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:f.payload}}}function I(t){if(!(!Array.isArray(t)||t.length===0))for(let e of t){let r=e.severity??"INFO",n=r==="ERROR"?"\u2717":r==="WARNING"?"\u26A0":"\u2139",o=e.componentId??e.conceptId??"?";console.log(`${n} ${r} [${o}] ${e.message??""}`)}}var Do=v(require("http")),Oo=require("child_process");var ut=v(require("fs")),bo=v(require("os")),So=v(require("path"));function Br(){return So.join(bo.homedir(),"Library","Application Support","Google","Chrome","Local State")}function Mr(){let t=Br();if(!ut.existsSync(t))return[];let e;try{e=JSON.parse(ut.readFileSync(t,"utf8"))}catch{return[]}let r=e?.profile?.info_cache??{};return Object.entries(r).map(([n,o])=>({directoryName:n,displayName:typeof o?.name=="string"&&o.name?o.name:n}))}var lt=class extends Error{constructor(e,r){super(`Chrome profile "${e}" not found. Available profiles: ${r.length?r.map(n=>`"${n.displayName}"`).join(", "):"(none detected)"}`),this.name="ChromeProfileNotFoundError"}};function pt(t,e=Mr()){if(!t){let n=e.find(o=>o.directoryName==="Default");if(n)return n;if(e.length)return e[0];throw new lt("Default",e)}let r=e.find(n=>n.directoryName===t||n.displayName.toLowerCase()===t.toLowerCase());if(!r)throw new lt(t,e);return r}var jo=require("child_process"),Po=require("util"),Vt=v(require("fs")),gt=v(require("os")),qt=v(require("path"));var vo=require("child_process"),To=require("util"),mt=v(require("crypto")),B=v(require("fs")),_r=(0,To.promisify)(vo.exec);function _t(t){for(let e=0;e<t.length;e++){let r=t[e];if(r<32||r>=127)return!1}return!0}async function Ao(){let{stdout:t}=await _r('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return t.trim()}function wo(t){return mt.pbkdf2Sync(t,"saltysalt",1003,16,"sha1")}function Ro(t,e){if(!t)return null;let r=Buffer.from(t,"hex");if(r.length<4)return null;let n=r.subarray(0,3).toString("utf8");if(n!=="v10"&&n!=="v11")return null;let o=Buffer.alloc(16,32),s=r.subarray(3),i;try{let d=mt.createDecipheriv("aes-128-cbc",e,o);i=Buffer.concat([d.update(s),d.final()])}catch{return null}let a=i.length>32?i.subarray(32):null,c=i;return a&&_t(a)&&!_t(i)&&(c=a),_t(c)?c.toString("utf8"):null}function $o(t,e){B.copyFileSync(t,e);for(let r of["-wal","-shm"]){let n=t+r;B.existsSync(n)&&B.copyFileSync(n,e+r)}}function Eo(t){for(let e of[t,t+"-wal",t+"-shm"])try{B.unlinkSync(e)}catch{}}var Ur=(0,Po.promisify)(jo.exec),ft=class extends Error{},Ut=class extends Error{};function Vr(t){return qt.join(gt.homedir(),"Library","Application Support","Google","Chrome",t,"Cookies")}function qr(){return Vt.existsSync("/Applications/Google Chrome.app")}function Jr(t){let e=t.split(".").filter(Boolean),r=[];for(let n=0;n+1<e.length;n++){let o=e.slice(n).join(".");r.push(o,`.${o}`)}return r}async function Jt(t,e,r){let n=Vr(t);if(!Vt.existsSync(n))return null;let o=qt.join(gt.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);$o(n,o);try{let s;try{s=await Ao()}catch{return null}let i=wo(s),a=u=>`'${u.replace(/'/g,"''")}'`,d=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${Jr(e).map(a).join(", ")}) AND name = ${a(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:l}=await Ur(`sqlite3 "${o}" "${d}"`);return Ro(l.trim(),i)}catch{return null}finally{Eo(o)}}function Gr(t){return new Promise(e=>setTimeout(e,t))}async function No(t,e={}){let r=e.platform??process.platform,n=e.isChromeInstalled??qr;if(r!=="darwin")throw new ft(`Automatic session capture is only supported on macOS with Google Chrome. Detected platform: ${r}. Use the manual cookie-paste fallback instead.`);if(!n())throw new ft("Automatic session capture requires Google Chrome (checked /Applications/Google Chrome.app), but it was not found. Install Chrome, or use the manual cookie-paste fallback instead.");let o=e.readCookie??Jt,s=e.sleep??Gr,i=t.pollIntervalMs??750,a=t.timeoutMs??15e3,c=await o(t.profileDirectory,t.host,t.cookieName),d=Date.now()+a;for(;Date.now()<d;){let l=await o(t.profileDirectory,t.host,t.cookieName);if(l&&l!==c)return l;await s(i)}throw new Ut(`Timed out after ${a}ms waiting for a fresh "${t.cookieName}" cookie for ${t.host}. Complete login in the Chrome window that opened, or use the manual cookie-paste fallback.`)}function Gt(t){let e=t.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return e?`${e[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}function Hr(t,e){let r=n=>`'${n.replace(/'/g,"'\\''")}'`;(0,Oo.exec)(`open -a ${r("Google Chrome")} ${r(t)} --args --profile-directory=${r(e)}`)}function Yr(){return`<!DOCTYPE html>
|
|
7
7
|
<html>
|
|
8
8
|
<head>
|
|
9
9
|
<meta charset="utf-8">
|
|
@@ -14,19 +14,19 @@
|
|
|
14
14
|
<h3>You're signed in.</h3>
|
|
15
15
|
<p>Return to your terminal \u2014 the CLI is finishing sign-in automatically. You can close this tab.</p>
|
|
16
16
|
</body>
|
|
17
|
-
</html>`}function
|
|
18
|
-
Expected one of: ${ee.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=F[t],n=e.imsEndpoint||r.imsEndpoint,o=e.terminologyServerEndpoint||r.terminologyServerEndpoint,s=e.authoringServicesEndpoint||r.authoringServicesEndpoint,i;try{i=new URL(n).hostname}catch{console.error(`Invalid --ims-endpoint: ${n}`),process.exitCode=1;return}let a=e.imsEndpoint?null:r.cookieName,c=e.cookieName||a||Ke(i),d=t===H&&!e.environment?`${t}, default`:t,l=[{url:n,label:"IMS",explicit:!!e.imsEndpoint},{url:o,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:s,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(C=>({...C,source:d})),u=await $r(n,i,c,e.chromeProfile);if(u){me({cookie:u.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:u.account,currentTask:null}),console.log(`${Ro(u.account)} (reused an existing Chrome session \u2014 no browser opened.)`),$o(l);return}console.log(`Opening Chrome to sign in to ${n} ...`);let g=await So({imsEndpoint:n,host:i,cookieName:c,chromeProfile:e.chromeProfile});if(!g){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let f=await he(n,g.cookie).catch(()=>null);me({cookie:g.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:f,currentTask:null}),console.log(Ro(f)),$o(l)}async function Eo(){wo(),console.log("Signed out.")}function p(){let e=Me();return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function m(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,onLog:t=>console.error(t)}}function jo(e){return e.projectKey??e.key??"?"}async function No(e){let t=p(),r=m(t),n=await Ht(r);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log("No projects available.");return}let o=Math.max(...n.map(s=>jo(s).length))+1;for(let s of n){let i=s.title??"";console.log(`${jo(s).padEnd(o)}${i?`"${i}"`:""}`)}}function fe(e){return e.taskKey??e.key??"?"}function Po(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Ar(e){return e.projectKey||fe(e).split("-")[0]||"?"}function Ue(e,t){let r=new Map;for(let n of e){let o=t(n);r.set(o,(r.get(o)??0)+1)}return[...r].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0]))}function _e(e,t){let r=Math.max(...t.map(([o])=>o.length)),n=Math.max(...t.map(([,o])=>String(o).length));console.log(""),console.log(`${e}:`);for(let[o,s]of t)console.log(` ${o.padEnd(r)} ${String(s).padStart(n)}`)}async function Do(e){let t=p(),r=m(t),n=e.mine||!e.project,o=n?await Yt(r):await Wt(r,e.project);if(n&&e.project){let l=e.project.toLowerCase();o=o.filter(u=>(u.projectKey??"").toLowerCase()===l||fe(u).toLowerCase().startsWith(`${l}-`))}if(e.status){let l=e.status.trim().toLowerCase();o=o.filter(u=>(u.status??"").toLowerCase()===l)}let s=Ue(o,Ar),i=Ue(o,Po),a=Ue(o,l=>l.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:o.length,byProject:Object.fromEntries(s),byAssignee:Object.fromEntries(i),byStatus:Object.fromEntries(a)}:o,null,2));return}let c=[n?"assigned to you":null,e.project?`in project ${e.project}`:null,e.status?`with status "${e.status}"`:null].filter(Boolean);if(o.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(e.summary){console.log(`${o.length} task${o.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),s.length>1&&_e("By project",s),!n&&i.length>1&&_e("By assignee",i),a.length>1&&_e("By status",a);return}let d=Math.max(...o.map(l=>fe(l).length))+1;for(let l of o){let u=l.summary??l.title??"",g=l.status?` status=${l.status}`:"",f=n?"":` [${Po(l)}]`;console.log(`${fe(l).padEnd(d)}${u?`"${u}"`:""}${g}${f}`)}}async function Oo(e){let t=p(),r=m(t),n=t.account?.login??t.account?.username,o=e.unassigned?void 0:e.assignee||n,s=await zt(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:o});if(!s.task){console.error(s.error??`Failed to create task in ${e.project}.`),process.exitCode=1;return}let i=s.task,a=i.key??i.taskKey,c=i.branchPath;if(e.json)console.log(JSON.stringify(i,null,2));else{console.log(`\u2713 Created task ${e.project}/${a} "${i.summary??e.summary}"${i.status?` status=${i.status}`:""}`),c&&console.log(` branch: ${c}`);let d=i.assignee?.displayName??i.assignee?.username;console.log(` assignee: ${d??"unassigned"}`)}if(c){let d=await U(r,c);if(!d.ok){console.error(`Task created, but its branch could not be prepared: ${d.error}`),process.exitCode=1;return}d.created&&!e.json&&console.log(` created branch ${c}`)}if(!e.noSelect){if(!a||!c){console.error("Task created, but it could not be selected (no key/branchPath in the response) \u2014 use select-task."),process.exitCode=1;return}L({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function Lo(e){let t=p(),r=m(t),n=t.currentTask;if(!!e.project!=!!e.task){console.error("Pass --project and --task together, or neither to delete the currently selected task."),process.exitCode=1;return}let o=e.project||n?.projectKey,s=e.task||n?.taskKey;if(!o||!s){console.error('No task to delete: pass --project/--task, or select one with "select-task".'),process.exitCode=1;return}let i=await Xt(r,{projectKey:o,taskKey:s});if(i.error){console.error(i.error),process.exitCode=1;return}i.alreadyDeleted?console.log(`${o}/${s} is already deleted.`):console.log(`\u2713 Deleted task ${o}/${s}`),i.hadUnpromotedChanges&&console.log(` note: its branch had changes that were never promoted. They still exist on ${i.task?.branchPath??"the task branch"}, but a deleted task appears in no listing \u2014 move it out of Deleted to reach them again.`),n&&n.projectKey===o&&n.taskKey===s&&(L(null),console.log(" cleared the current task selection."))}async function Ko(e){let t=p(),r=m(t);if(!e.task){let s=await Qt(r,e.project);if(e.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){console.log(`No deleted tasks in ${e.project}.`);return}console.log(`${s.length} deleted task${s.length===1?"":"s"} in ${e.project} \u2014 pass --task <key> to recover one:`);for(let i of s){let a=i.assignee?.displayName??i.assignee?.username??"unassigned";console.log(` ${i.key} "${i.summary??""}" [${a}]`)}return}let n=await Zt(r,{projectKey:e.project,taskKey:e.task});if(n.error){console.error(n.error),process.exitCode=1;return}if(n.notDeleted){console.log(`${e.project}/${e.task} is not deleted (status ${n.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${e.project}/${e.task} (status ${n.task?.status??"In Progress"})`);let o=n.task?.branchPath;if(o){let s=await U(r,o);if(!s.ok){console.error(`Task recovered, but its branch could not be prepared: ${s.error}`),process.exitCode=1;return}console.log(s.created?` created branch ${o}`:` branch ${o} still holds its content`)}e.noSelect||!o||(L({projectKey:e.project,taskKey:e.task,branchPath:o}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function Bo(e){let t=p(),r=m(t),n=await O(r,e.project,e.task);if(!n||!n.branchPath){console.error(`Could not resolve task ${e.project}/${e.task} (no branchPath returned).`),process.exitCode=1;return}let o=await U(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${o.error}`),process.exitCode=1;return}L({projectKey:e.project,taskKey:e.task,branchPath:n.branchPath}),console.log(`\u2713 Current task set to ${e.project}/${e.task} (${n.branchPath})`),o.created&&console.log(` created branch ${n.branchPath}`)}async function Fo(e){let t=p();if(!t.currentTask){console.log('No task currently selected. Run "select-task", or pass --project/--task explicitly to any command.');return}let{projectKey:r,taskKey:n,branchPath:o}=t.currentTask;console.log(`Current task: ${r}/${n} (${o})`),(e.project||e.task)&&((!e.project||e.project===r)&&(!e.task||e.task===n)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function Mo(e){let t=p(),r=m(t),n=await rt(r,{fsn:e.fsn,semanticTag:e.tag,preferredTerm:e.pt,parentConceptId:e.parent,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300&&o.conceptId){console.log(`Created concept ${o.conceptId}`),b(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to create concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Uo(e){let t=p(),r=m(t),n=await st(r,{term:e.term,ecl:e.ecl,active:e.active!==void 0?e.active==="true":void 0,limit:e.limit?Number(e.limit):void 0,projectKey:e.project,taskKey:e.task},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to search concepts (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function _o(e){let t=p(),r=m(t),n=await ne(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to get concept (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function Vo(e){let t=p(),r=m(t),n=await se(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to validate concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}let s=o.validationResults;if(!Array.isArray(s)||s.length===0){console.log(`No validation issues for concept ${e.id}.`);return}b(s),o.hasErrors&&(process.exitCode=1)}async function qo(e){let t=p(),r=m(t),n=await _(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to list concepts for review (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Jo(e){let t=p(),r=m(t),n=await Ot(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${n.statusCode}): ${o.error??JSON.stringify(o)}`),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(n.body,null,2)),o.summary&&(o.summary.withIssues>0||o.summary.failed>0)&&(process.exitCode=1);return}let s=o.results??[],i=o.summary;if(s.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of s){let c=`${a.conceptId}${a.fsn?` "${a.fsn}"`:""}`;if(a.outcome==="deleted"){console.log(`\u2014 ${c} deleted on this branch \u2014 skipped`);continue}if(a.outcome==="failed"){console.log(`\u2717 ${c} could not be validated: ${a.error??"unknown error"}`);continue}if(a.outcome==="clean"){console.log(`\u2713 ${c}`);continue}console.log(`\u26A0 ${c}`),b(a.validationResults)}if(i){console.log("");let a=[`${i.validated} validated`,`${i.clean} clean`,`${i.withIssues} with issues`];i.skippedDeleted&&a.push(`${i.skippedDeleted} skipped (deleted on this branch)`),i.failed&&a.push(`${i.failed} failed`),console.log(a.join(", ")+".")}i&&(i.withIssues>0||i.failed>0)&&(process.exitCode=1)}async function Go(e){let t=p(),r=m(t),n=await Lt(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to fetch concepts for review (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Ho(e){let t=p(),r=m(t),n=await yt(r,{conceptId:e.id,term:e.term,type:e.type,semanticTag:e.tag,moduleId:e.module,acceptability:e.acceptability,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added ${e.type} description to concept ${e.id}`),b(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Wo(e){let t=p(),r=m(t),n=await kt(r,{conceptId:e.id,typeId:e.type,targetId:e.target,groupId:e.group?Number(e.group):void 0,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added relationship (${e.type} -> ${e.target}) to concept ${e.id}`),b(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add relationship (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Yo(e){let t=p(),r=m(t),n=await jt(r,{conceptId:e.id,axiomId:e.axiomId,relationshipId:e.relationshipId,relationshipIndex:e.relationshipIndex?Number(e.relationshipIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Removed relationship from axiom ${e.axiomId} on concept ${e.id}`),b(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to remove relationship (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function zo(e){let t;try{t=JSON.parse(e.attributes)}catch(a){console.error(`--attributes must be valid JSON (an array of {"typeId":"...","targetId":"..."} objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await Nt(n,{conceptId:e.id,axiomId:e.axiomId,attributes:t,groupId:e.groupId!=null&&e.groupId!==""?Number(e.groupId):void 0,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed role group from axiom ${e.axiomId} on concept ${e.id}`),b(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to remove role group (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Xo(e){let t=p(),r=m(t),n=await It(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated description ${e.descriptionId} on concept ${e.id}`),b(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to update description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Qo(e){let t=p(),r=m(t),n=await xt(r,{conceptId:e.id,descriptionId:e.descriptionId,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set case significance of description ${e.descriptionId} to ${e.caseSignificance}`),b(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set case significance (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Zo(e){let t=p(),r=m(t);if(e.entries){let i;try{i=JSON.parse(e.entries)}catch(l){console.error(`--entries is not valid JSON: ${l.message}`),process.exitCode=1;return}if(!Array.isArray(i)||i.length===0){console.error("--entries must be a non-empty JSON array of {descriptionId, lang?, us?, gb?} objects."),process.exitCode=1;return}let a=await Tt(r,{conceptId:e.id,entries:i,projectKey:e.project,taskKey:e.task},t.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${i.length} description(s) on concept ${e.id}`),b(c.validationResults);return}let d=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${d}`),process.exitCode=1;return}if(!e.descriptionId){console.error("Either --description-id (with --lang/--us/--gb) or --entries is required."),process.exitCode=1;return}let n=await vt(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){let i=[e.lang?`lang=${e.lang}`:void 0,e.us?`us=${e.us}`:void 0,e.gb?`gb=${e.gb}`:void 0].filter(Boolean);console.log(`Set acceptability of description ${e.descriptionId} (${i.join(", ")})`),b(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set acceptability (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function en(e){let t=p(),r=m(t),n=await ht(r,{conceptId:e.id,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated concept ${e.id}`),b(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to inactivate concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function tn(e){let t=p(),r=m(t),n=await Ct(r,{conceptId:e.id,status:e.status,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set definition status of concept ${e.id} to ${e.status}`),b(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set definition status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function on(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await Rt(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated axiom ${e.axiomId} on concept ${e.id}`),b(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to update axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function nn(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await $t(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated GCI axiom ${e.axiomId} on concept ${e.id}`),b(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to update GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function rn(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}let r=p(),n=m(r),o=await At(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(s.gciAxioms)?s.gciAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added GCI axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),b(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to add GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function sn(e){let t=p(),r=m(t),n=await it(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function an(e){let t=p(),r=m(t),n=await wt(r,{conceptId:e.id,descriptionId:e.descriptionId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted description ${e.descriptionId} from concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function cn(e){let t=p(),r=m(t),n=await Et(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted axiom ${e.axiomId} from concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function dn(e){let t=p(),r=m(t),n=await Pt(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted GCI axiom ${e.axiomId} from concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete GCI axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}function V(e){let t=e.account?.login;return t?io(m(e),t):(console.error("[authoring-cli] no login resolved from the signed-in account \u2014 notifications will only arrive via polling fallback, not a live push."),null)}async function ln(e){let t=p(),r=m(t),n=V(t),o;try{o=await qt(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let s=o.body;if(o.statusCode>=200&&o.statusCode<300){s.finalStatus!==void 0?(console.log(`Classification ${s.finalStatus}${s.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),s.details&&console.log(JSON.stringify(s.details,null,2)),s.save&&(s.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${s.save.error?`: ${s.save.error}`:""}${s.save.status?` (status: ${s.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${s.jobId} (${s.status})`),s.timedOut&&(process.exitCode=1);return}let i=s.details!==void 0?` \u2014 details: ${JSON.stringify(s.details)}`:"";console.error(`Failed to start classification (HTTP ${o.statusCode}): ${s.error??JSON.stringify(s)}${i}`),process.exitCode=1}async function un(e){let t=p(),r=m(t),n=await Vt(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check classification status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function pn(e){let t=p(),r=m(t),n=V(t),o;try{o=await Gt(r,{enableMrcmValidation:e.enableMrcm,wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let s=o.body;if(o.statusCode>=200&&o.statusCode<300){s.finalStatus!==void 0?console.log(`Validation ${s.finalStatus}${s.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),s.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${o.statusCode}): ${s.error??JSON.stringify(s)}`),process.exitCode=1}async function mn(e){let t=p(),r=m(t),n=await Jt(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check validation status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function fn(e){let t=p(),r=m(t),n=V(t);try{let o=await ao(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),s=o.body;if(o.statusCode<200||o.statusCode>=300){let i=s.error?s.error:JSON.stringify(s);console.error(`Failed to watch for a notification (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2)),s.timedOut&&(process.exitCode=1)}finally{n?.stop()}}var Je=v(require("os")),q=v(require("path"));var S=v(require("fs")),Ve=v(require("os")),x=v(require("path")),$="authoring-cli",D=["claude","codex"];function ge(e){let t=[x.resolve(e,"..","skills",$),x.resolve(e,"..","..","skills",$)];for(let r of t)if(S.existsSync(x.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${$}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function Er(e){let t=[];return S.existsSync(x.join(e,".claude"))&&t.push("claude"),S.existsSync(x.join(e,".codex"))&&t.push("codex"),t}function X(e,t){if(e==="all")return[...D];if(e){let n=e.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),o=n.filter(s=>!D.includes(s));if(o.length)throw new Error(`Unknown --agent value(s): ${o.join(", ")}. Supported: ${D.join(", ")}, all.`);return n}let r=Er(t);return r.length?r:["claude"]}var yn="# authoring-cli \u2014 SNOMED CT authoring guidance";function jr(e){let t=x.join(e,"SKILL.md"),r=x.join(e,"references","batch-authoring.md");return[yn,"",`Read \`${t}\` now, and follow it for the rest of this session whenever you run the`,"`authoring-cli` command \u2014 before any concept creation, description/acceptability edit,","relationship or axiom edit, `classify`, or `validate-task`. It documents server-side","constraints and async behavior that fail or mislead in non-obvious ways, so reading it after","a command has already failed is too late.","",`Also read \`${r}\` when the task is a large, multi-session batch (tens to thousands of`,"concepts generated from a source list).","","Both files live inside the installed `authoring-cli` npm package, so they stay in step with","the CLI itself. If the paths above no longer exist, the package moved or was upgraded to a","different location \u2014 re-run `authoring-cli install-skill` to refresh this prompt.",""].join(`
|
|
19
|
-
`)}function
|
|
20
|
-
`)!==
|
|
21
|
-
`)?!1:r.every(n=>S.readFileSync(
|
|
17
|
+
</html>`}function Fo(t,e={}){let r=t.cookieName??Gt(t.host),n=e.openChrome??Hr,o=e.resolveProfile??pt,s=e.captureCookie??No,i=t.callbackTimeoutMs??12e4,a=o(t.chromeProfile);return new Promise((c,d)=>{let l=!1,u=g=>{l||(l=!0,f.close(),g())},f=Do.createServer((g,C)=>{if((g.url||"/").split("?")[0]==="/callback"){C.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),C.end(Yr()),(async()=>{try{let h=await s({profileDirectory:a.directoryName,host:t.host,cookieName:r});u(()=>c({cookie:`${r}=${h}`}))}catch(h){u(()=>d(h))}})();return}C.writeHead(404),C.end()});f.listen(0,"127.0.0.1",()=>{let C=`http://localhost:${f.address().port}/callback`,x=`${t.imsEndpoint}?serviceReferer=${encodeURIComponent(C)}`;n(x,a.directoryName)}),f.on("error",g=>u(()=>d(g))),setTimeout(()=>u(()=>c(null)),i)})}var N=v(require("fs")),Ko=v(require("os")),Ht=v(require("path"));function Lo(){return Ht.join(Ko.homedir(),".authoring-cli")}function Yt(){return Ht.join(Lo(),"session.json")}function Wt(){let t=Yt();if(!N.existsSync(t))return null;let e=N.readFileSync(t,"utf8");return JSON.parse(e)}function yt(t){N.mkdirSync(Lo(),{recursive:!0,mode:448});let e={...t,updatedAt:new Date().toISOString()};N.writeFileSync(Yt(),JSON.stringify(e,null,2),{mode:384})}function Bo(){let t=Yt();N.existsSync(t)&&N.unlinkSync(t)}function K(t){let e=Wt();if(!e)throw new Error('Not signed in \u2014 run "login" first.');yt({...e,currentTask:t})}async function Wr(t,e,r,n){let o;try{o=pt(n).directoryName}catch{return null}let s=await Jt(o,e,r).catch(()=>null);if(!s)return null;let i=`${r}=${s}`,a=await vt(t,i).catch(()=>null);return a?{cookie:i,account:a}:null}function Mo(t){let e=t?.displayName??t?.login;return e?`Signed in as ${e}.`:"Signed in. (Could not confirm account details \u2014 proceed with caution.)"}function _o(t){let e=Math.max(...t.map(r=>r.label.length));for(let{url:r,label:n,explicit:o,source:s}of t)console.log(` ${(n+":").padEnd(e+2)}${r} (${o?"from flag":s})`)}async function Uo(t){let e=t.environment?re(t.environment):W;if(!e){console.error(`Unknown environment: ${t.environment}
|
|
18
|
+
Expected one of: ${et.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=M[e],n=t.imsEndpoint||r.imsEndpoint,o=t.terminologyServerEndpoint||r.terminologyServerEndpoint,s=t.authoringServicesEndpoint||r.authoringServicesEndpoint,i;try{i=new URL(n).hostname}catch{console.error(`Invalid --ims-endpoint: ${n}`),process.exitCode=1;return}let a=t.imsEndpoint?null:r.cookieName,c=t.cookieName||a||Gt(i),d=e===W&&!t.environment?`${e}, default`:e,l=[{url:n,label:"IMS",explicit:!!t.imsEndpoint},{url:o,label:"Terminology server",explicit:!!t.terminologyServerEndpoint},{url:s,label:"Authoring services",explicit:!!t.authoringServicesEndpoint}].map(C=>({...C,source:d})),u=await Wr(n,i,c,t.chromeProfile);if(u){yt({cookie:u.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:u.account,currentTask:null}),console.log(`${Mo(u.account)} (reused an existing Chrome session \u2014 no browser opened.)`),_o(l);return}console.log(`Opening Chrome to sign in to ${n} ...`);let f=await Fo({imsEndpoint:n,host:i,cookieName:c,chromeProfile:t.chromeProfile});if(!f){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let g=await vt(n,f.cookie).catch(()=>null);yt({cookie:f.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:g,currentTask:null}),console.log(Mo(g)),_o(l)}async function Vo(){Bo(),console.log("Signed out.")}var ht=v(require("fs")),kt=v(require("path"));async function qo(){let t=[kt.join(__dirname,"../../HELP.md"),kt.join(__dirname,"../HELP.md"),kt.join(process.cwd(),"HELP.md")];for(let e of t)try{if(ht.existsSync(e)){let r=ht.readFileSync(e,"utf8");console.log(r);return}}catch{}console.error("Could not locate HELP.md."),console.log(""),console.log("For help, see the README:"),console.log(" npm view authoring-cli readme"),console.log(""),console.log("Or visit: https://github.com/snomed/authoring-cli"),process.exit(1)}function p(){let t=Wt();return t||(console.error('Not signed in. Run "login" first.'),process.exit(1)),t}function m(t){return{cookie:t.cookie,terminologyServerEndpoint:t.terminologyServerEndpoint,authoringServicesEndpoint:t.authoringServicesEndpoint,imsEndpoint:t.imsEndpoint,onLog:e=>console.error(e)}}function Jo(t){return t.projectKey??t.key??"?"}async function Go(t){let e=p(),r=m(e),n=await io(r);if(t.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log("No projects available.");return}let o=Math.max(...n.map(s=>Jo(s).length))+1;for(let s of n){let i=s.title??"";console.log(`${Jo(s).padEnd(o)}${i?`"${i}"`:""}`)}}function Ct(t){return t.taskKey??t.key??"?"}function Ho(t){return t.assignee?.displayName??t.assignee?.username??"unassigned"}function zr(t){return t.projectKey||Ct(t).split("-")[0]||"?"}function zt(t,e){let r=new Map;for(let n of t){let o=e(n);r.set(o,(r.get(o)??0)+1)}return[...r].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0]))}function Xt(t,e){let r=Math.max(...e.map(([o])=>o.length)),n=Math.max(...e.map(([,o])=>String(o).length));console.log(""),console.log(`${t}:`);for(let[o,s]of e)console.log(` ${o.padEnd(r)} ${String(s).padStart(n)}`)}async function Yo(t){let e=p(),r=m(e),n=t.mine||!t.project,o=n?await co(r):await ao(r,t.project);if(n&&t.project){let l=t.project.toLowerCase();o=o.filter(u=>(u.projectKey??"").toLowerCase()===l||Ct(u).toLowerCase().startsWith(`${l}-`))}if(t.status){let l=t.status.trim().toLowerCase();o=o.filter(u=>(u.status??"").toLowerCase()===l)}let s=zt(o,zr),i=zt(o,Ho),a=zt(o,l=>l.status??"unknown");if(t.json){console.log(JSON.stringify(t.summary?{total:o.length,byProject:Object.fromEntries(s),byAssignee:Object.fromEntries(i),byStatus:Object.fromEntries(a)}:o,null,2));return}let c=[n?"assigned to you":null,t.project?`in project ${t.project}`:null,t.status?`with status "${t.status}"`:null].filter(Boolean);if(o.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(t.summary){console.log(`${o.length} task${o.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),s.length>1&&Xt("By project",s),!n&&i.length>1&&Xt("By assignee",i),a.length>1&&Xt("By status",a);return}let d=Math.max(...o.map(l=>Ct(l).length))+1;for(let l of o){let u=l.summary??l.title??"",f=l.status?` status=${l.status}`:"",g=n?"":` [${Ho(l)}]`;console.log(`${Ct(l).padEnd(d)}${u?`"${u}"`:""}${f}${g}`)}}async function Wo(t){let e=p(),r=m(e),n=e.account?.login??e.account?.username,o=t.unassigned?void 0:t.assignee||n,s=await lo(r,{projectKey:t.project,summary:t.summary,description:t.description,assigneeUsername:o});if(!s.task){console.error(s.error??`Failed to create task in ${t.project}.`),process.exitCode=1;return}let i=s.task,a=i.key??i.taskKey,c=i.branchPath;if(t.json)console.log(JSON.stringify(i,null,2));else{console.log(`\u2713 Created task ${t.project}/${a} "${i.summary??t.summary}"${i.status?` status=${i.status}`:""}`),c&&console.log(` branch: ${c}`);let d=i.assignee?.displayName??i.assignee?.username;console.log(` assignee: ${d??"unassigned"}`)}if(c){let d=await U(r,c);if(!d.ok){console.error(`Task created, but its branch could not be prepared: ${d.error}`),process.exitCode=1;return}d.created&&!t.json&&console.log(` created branch ${c}`)}if(!t.noSelect){if(!a||!c){console.error("Task created, but it could not be selected (no key/branchPath in the response) \u2014 use select-task."),process.exitCode=1;return}K({projectKey:t.project,taskKey:a,branchPath:c}),t.json||console.log(`\u2713 Current task set to ${t.project}/${a}`)}}async function zo(t){let e=p(),r=m(e),n=e.currentTask;if(!!t.project!=!!t.task){console.error("Pass --project and --task together, or neither to delete the currently selected task."),process.exitCode=1;return}let o=t.project||n?.projectKey,s=t.task||n?.taskKey;if(!o||!s){console.error('No task to delete: pass --project/--task, or select one with "select-task".'),process.exitCode=1;return}let i=await uo(r,{projectKey:o,taskKey:s});if(i.error){console.error(i.error),process.exitCode=1;return}i.alreadyDeleted?console.log(`${o}/${s} is already deleted.`):console.log(`\u2713 Deleted task ${o}/${s}`),i.hadUnpromotedChanges&&console.log(` note: its branch had changes that were never promoted. They still exist on ${i.task?.branchPath??"the task branch"}, but a deleted task appears in no listing \u2014 move it out of Deleted to reach them again.`),n&&n.projectKey===o&&n.taskKey===s&&(K(null),console.log(" cleared the current task selection."))}async function Xo(t){let e=p(),r=m(e);if(!t.task){let s=await po(r,t.project);if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){console.log(`No deleted tasks in ${t.project}.`);return}console.log(`${s.length} deleted task${s.length===1?"":"s"} in ${t.project} \u2014 pass --task <key> to recover one:`);for(let i of s){let a=i.assignee?.displayName??i.assignee?.username??"unassigned";console.log(` ${i.key} "${i.summary??""}" [${a}]`)}return}let n=await mo(r,{projectKey:t.project,taskKey:t.task});if(n.error){console.error(n.error),process.exitCode=1;return}if(n.notDeleted){console.log(`${t.project}/${t.task} is not deleted (status ${n.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${t.project}/${t.task} (status ${n.task?.status??"In Progress"})`);let o=n.task?.branchPath;if(o){let s=await U(r,o);if(!s.ok){console.error(`Task recovered, but its branch could not be prepared: ${s.error}`),process.exitCode=1;return}console.log(s.created?` created branch ${o}`:` branch ${o} still holds its content`)}t.noSelect||!o||(K({projectKey:t.project,taskKey:t.task,branchPath:o}),console.log(`\u2713 Current task set to ${t.project}/${t.task}`))}async function Qo(t){let e=p(),r=m(e),n=await F(r,t.project,t.task);if(!n||!n.branchPath){console.error(`Could not resolve task ${t.project}/${t.task} (no branchPath returned).`),process.exitCode=1;return}let o=await U(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${t.project}/${t.task}: ${o.error}`),process.exitCode=1;return}K({projectKey:t.project,taskKey:t.task,branchPath:n.branchPath}),console.log(`\u2713 Current task set to ${t.project}/${t.task} (${n.branchPath})`),o.created&&console.log(` created branch ${n.branchPath}`)}async function Zo(t){let e=p();if(!e.currentTask){console.log('No task currently selected. Run "select-task", or pass --project/--task explicitly to any command.');return}let{projectKey:r,taskKey:n,branchPath:o}=e.currentTask;console.log(`Current task: ${r}/${n} (${o})`),(t.project||t.task)&&((!t.project||t.project===r)&&(!t.task||t.task===n)||console.log(`Note: --project/--task (${t.project??"*"}/${t.task??"*"}) do not match the currently selected task.`))}async function tn(t){let e=p(),r=m(e),n=await me(r,{fsn:t.fsn,semanticTag:t.tag,preferredTerm:t.pt,parentConceptId:t.parent,moduleId:t.module,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300&&o.conceptId){console.log(`Created concept ${o.conceptId}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to create concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function en(t){let e=p(),r=m(e),n={term:t.term,ecl:t.ecl,active:t.active!==void 0?t.active==="true":void 0,limit:t.limit?Number(t.limit):void 0,projectKey:t.project,taskKey:t.task},o=t.checkAuthoringForm?await qe(r,{...n,conformed:t.conformed===!0},e.currentTask):await st(r,n,e.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to search concepts (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function on(t){let e=p(),r=m(e),n=await rt(r,{conceptId:t.id,projectKey:t.project,taskKey:t.task},e.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to get concept (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function nn(t){let e=p(),r=m(e),n=await ct(r,{conceptId:t.id,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to validate concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}let s=o.validationResults;if(!Array.isArray(s)||s.length===0){console.log(`No validation issues for concept ${t.id}.`);return}I(s),o.hasErrors&&(process.exitCode=1)}async function rn(t){let e=p(),r=m(e),n=t.checkAuthoringForm?await He(r,{projectKey:t.project,taskKey:t.task,conformed:t.conformed===!0},e.currentTask):await O(r,{projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to list concepts for review (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function sn(t){let e=p(),r=m(e),n=await Ye(r,{projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${n.statusCode}): ${o.error??JSON.stringify(o)}`),process.exitCode=1;return}if(t.json){console.log(JSON.stringify(n.body,null,2)),o.summary&&(o.summary.withIssues>0||o.summary.failed>0)&&(process.exitCode=1);return}let s=o.results??[],i=o.summary;if(s.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of s){let c=`${a.conceptId}${a.fsn?` "${a.fsn}"`:""}`;if(a.outcome==="deleted"){console.log(`\u2014 ${c} deleted on this branch \u2014 skipped`);continue}if(a.outcome==="failed"){console.log(`\u2717 ${c} could not be validated: ${a.error??"unknown error"}`);continue}if(a.outcome==="clean"){console.log(`\u2713 ${c}`);continue}console.log(`\u26A0 ${c}`),I(a.validationResults)}if(i){console.log("");let a=[`${i.validated} validated`,`${i.clean} clean`,`${i.withIssues} with issues`];i.skippedDeleted&&a.push(`${i.skippedDeleted} skipped (deleted on this branch)`),i.failed&&a.push(`${i.failed} failed`),console.log(a.join(", ")+".")}i&&(i.withIssues>0||i.failed>0)&&(process.exitCode=1)}async function an(t){let e=p(),r=m(e),n=await We(r,{projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to fetch concepts for review (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function cn(t){let e=p(),r=m(e),n=await ve(r,{conceptId:t.id,term:t.term,type:t.type,semanticTag:t.tag,moduleId:t.module,acceptability:t.acceptability,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added ${t.type} description to concept ${t.id}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function dn(t){let e=p(),r=m(e),n=await Te(r,{conceptId:t.id,typeId:t.type,targetId:t.target,groupId:t.group?Number(t.group):void 0,axiomIndex:t.axiomIndex?Number(t.axiomIndex):void 0,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added relationship (${t.type} -> ${t.target}) to concept ${t.id}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add relationship (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function ln(t){let e=p(),r=m(e),n=await _e(r,{conceptId:t.id,axiomId:t.axiomId,relationshipId:t.relationshipId,relationshipIndex:t.relationshipIndex?Number(t.relationshipIndex):void 0,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Removed relationship from axiom ${t.axiomId} on concept ${t.id}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to remove relationship (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function un(t){let e;try{e=JSON.parse(t.attributes)}catch(a){console.error(`--attributes must be valid JSON (an array of {"typeId":"...","targetId":"..."} objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await Ue(n,{conceptId:t.id,axiomId:t.axiomId,attributes:e,groupId:t.groupId!=null&&t.groupId!==""?Number(t.groupId):void 0,projectKey:t.project,taskKey:t.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed role group from axiom ${t.axiomId} on concept ${t.id}`),I(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to remove role group (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function pn(t){let e=p(),r=m(e),n=await Re(r,{conceptId:t.id,descriptionId:t.descriptionId,term:t.term,caseSignificance:t.caseSignificance,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated description ${t.descriptionId} on concept ${t.id}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to update description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function mn(t){let e=p(),r=m(e),n=await $e(r,{conceptId:t.id,descriptionId:t.descriptionId,caseSignificance:t.caseSignificance,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set case significance of description ${t.descriptionId} to ${t.caseSignificance}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set case significance (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function fn(t){let e=p(),r=m(e);if(t.entries){let i;try{i=JSON.parse(t.entries)}catch(l){console.error(`--entries is not valid JSON: ${l.message}`),process.exitCode=1;return}if(!Array.isArray(i)||i.length===0){console.error("--entries must be a non-empty JSON array of {descriptionId, lang?, us?, gb?} objects."),process.exitCode=1;return}let a=await Ne(r,{conceptId:t.id,entries:i,projectKey:t.project,taskKey:t.task},e.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${i.length} description(s) on concept ${t.id}`),I(c.validationResults);return}let d=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${d}`),process.exitCode=1;return}if(!t.descriptionId){console.error("Either --description-id (with --lang/--us/--gb) or --entries is required."),process.exitCode=1;return}let n=await Pe(r,{conceptId:t.id,descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){let i=[t.lang?`lang=${t.lang}`:void 0,t.us?`us=${t.us}`:void 0,t.gb?`gb=${t.gb}`:void 0].filter(Boolean);console.log(`Set acceptability of description ${t.descriptionId} (${i.join(", ")})`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set acceptability (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function gn(t){let e=p(),r=m(e),n=await we(r,{conceptId:t.id,indicator:t.indicator,associationRefsetId:t.associationRefset,associationTargetId:t.associationTarget,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated concept ${t.id}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to inactivate concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function yn(t){let e=p(),r=m(e),n=await Ae(r,{conceptId:t.id,status:t.status,axiomIndex:t.axiomIndex?Number(t.axiomIndex):void 0,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set definition status of concept ${t.id} to ${t.status}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set definition status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function kn(t){let e;try{e=JSON.parse(t.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await $t(n,{conceptId:t.id,axiomId:t.axiomId,relationships:e,projectKey:t.project,taskKey:t.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated axiom ${t.axiomId} on concept ${t.id}`),I(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to update axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function hn(t){let e;try{e=JSON.parse(t.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await Oe(n,{conceptId:t.id,axiomId:t.axiomId,relationships:e,projectKey:t.project,taskKey:t.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated GCI axiom ${t.axiomId} on concept ${t.id}`),I(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to update GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Cn(t){let e;try{e=JSON.parse(t.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(e)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}let r=p(),n=m(r),o=await Fe(n,{conceptId:t.id,relationships:e,moduleId:t.moduleId,projectKey:t.project,taskKey:t.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(s.gciAxioms)?s.gciAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added GCI axiom to concept ${t.id}${c?` (axiomId ${c})`:""}`),I(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to add GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function xn(t){let e;try{e=JSON.parse(t.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(e)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}if(t.definitionStatus&&t.definitionStatus!=="PRIMITIVE"&&t.definitionStatus!=="FULLY_DEFINED"){console.error("--definition-status must be PRIMITIVE or FULLY_DEFINED."),process.exitCode=1;return}let r=p(),n=m(r),o=await Et(n,{conceptId:t.id,relationships:e,moduleId:t.moduleId,definitionStatus:t.definitionStatus,projectKey:t.project,taskKey:t.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(s.classAxioms)?s.classAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added class axiom to concept ${t.id}${c?` (axiomId ${c})`:""}`),I(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to add axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function In(t){let e=p(),r=m(e),n=await Je(r,{conceptId:t.id,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted concept ${t.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function bn(t){let e=p(),r=m(e),n=await De(r,{conceptId:t.id,descriptionId:t.descriptionId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted description ${t.descriptionId} from concept ${t.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Sn(t){let e=p(),r=m(e),n=await Ke(r,{conceptId:t.id,axiomId:t.axiomId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted axiom ${t.axiomId} from concept ${t.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function vn(t){let e=p(),r=m(e),n=await jt(r,{conceptId:t.id,axiomId:t.axiomId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated axiom ${t.axiomId} on concept ${t.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Tn(t){let e=p(),r=m(e),n=await Me(r,{conceptId:t.id,axiomId:t.axiomId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){if(o.alreadyConformed)console.log(`Concept ${t.id}'s axiom${o.axiomId?` ${o.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(o.replacedAxiomId){let i=Array.isArray(o.addResult?.classAxioms)?o.addResult.classAxioms.map(c=>c.axiomId).filter(Boolean):[],a=i.length>0?i[i.length-1]:void 0;console.log(`Transformed concept ${t.id} to authoring form: added axiom${a?` ${a}`:""} and inactivated published axiom ${o.replacedAxiomId}.`)}else console.log(`Transformed axiom${t.axiomId?` ${t.axiomId}`:""} on concept ${t.id} to authoring form.`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to transform axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function An(t){let e=p(),r=m(e),n=await q(r,{conceptId:t.id,axiomId:t.axiomId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check authoring form for concept ${t.id} (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}if(o.conforms){console.log(`Concept ${t.id} conforms to authoring form (axiom ${o.axiomId}).`);return}console.log(`Concept ${t.id} does NOT conform to authoring form (axiom ${o.axiomId}) \u2014 run transform-axiom to fix.`),process.exitCode=1}async function wn(t){let e=p(),r=m(e),n=await Ve(r,{conceptId:t.id,axiomId:t.axiomId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted GCI axiom ${t.axiomId} from concept ${t.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete GCI axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}function J(t){let e=t.account?.login;return e?xo(m(t),e):(console.error("[authoring-cli] no login resolved from the signed-in account \u2014 notifications will only arrive via polling fallback, not a live push."),null)}async function Rn(t){let e=p(),r=m(e),n=J(e),o;try{o=await no(r,{wait:!!t.wait,timeoutSeconds:t.timeout?Number(t.timeout):void 0,projectKey:t.project,taskKey:t.task},e.currentTask)}finally{n?.stop()}let s=o.body;if(o.statusCode>=200&&o.statusCode<300){s.finalStatus!==void 0?(console.log(`Classification ${s.finalStatus}${s.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),s.details&&console.log(JSON.stringify(s.details,null,2)),s.save&&(s.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${s.save.error?`: ${s.save.error}`:""}${s.save.status?` (status: ${s.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${s.jobId} (${s.status})`),s.timedOut&&(process.exitCode=1);return}let i=s.details!==void 0?` \u2014 details: ${JSON.stringify(s.details)}`:"";console.error(`Failed to start classification (HTTP ${o.statusCode}): ${s.error??JSON.stringify(s)}${i}`),process.exitCode=1}async function $n(t){let e=p(),r=m(e),n=await oo(r,{projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check classification status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function En(t){let e=p(),r=m(e),n=J(e),o;try{o=await so(r,{enableMrcmValidation:t.enableMrcm,wait:!!t.wait,timeoutSeconds:t.timeout?Number(t.timeout):void 0,projectKey:t.project,taskKey:t.task},e.currentTask)}finally{n?.stop()}let s=o.body;if(o.statusCode>=200&&o.statusCode<300){s.finalStatus!==void 0?console.log(`Validation ${s.finalStatus}${s.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),s.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${o.statusCode}): ${s.error??JSON.stringify(s)}`),process.exitCode=1}async function jn(t){let e=p(),r=m(e),n=await ro(r,{projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check validation status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Pn(t){let e=p(),r=m(e),n=J(e);try{let o=await Io(r,{projectKey:t.project,taskKey:t.task,entityType:t.entityType,timeoutSeconds:t.timeout?Number(t.timeout):void 0},e.currentTask),s=o.body;if(o.statusCode<200||o.statusCode>=300){let i=s.error?s.error:JSON.stringify(s);console.error(`Failed to watch for a notification (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2)),s.timedOut&&(process.exitCode=1)}finally{n?.stop()}}var te=v(require("os")),G=v(require("path"));var S=v(require("fs")),Qt=v(require("os")),b=v(require("path")),$="authoring-cli",D=["claude","codex"];function xt(t){let e=[b.resolve(t,"..","skills",$),b.resolve(t,"..","..","skills",$)];for(let r of e)if(S.existsSync(b.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${$}/SKILL.md in: ${e.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function Xr(t){let e=[];return S.existsSync(b.join(t,".claude"))&&e.push("claude"),S.existsSync(b.join(t,".codex"))&&e.push("codex"),e}function Q(t,e){if(t==="all")return[...D];if(t){let n=t.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),o=n.filter(s=>!D.includes(s));if(o.length)throw new Error(`Unknown --agent value(s): ${o.join(", ")}. Supported: ${D.join(", ")}, all.`);return n}let r=Xr(e);return r.length?r:["claude"]}var Dn="# authoring-cli \u2014 SNOMED CT authoring guidance";function Qr(t){let e=b.join(t,"SKILL.md"),r=b.join(t,"references","batch-authoring.md");return[Dn,"",`Read \`${e}\` now, and follow it for the rest of this session whenever you run the`,"`authoring-cli` command \u2014 before any concept creation, description/acceptability edit,","relationship or axiom edit, `classify`, or `validate-task`. It documents server-side","constraints and async behavior that fail or mislead in non-obvious ways, so reading it after","a command has already failed is too late.","",`Also read \`${r}\` when the task is a large, multi-session batch (tens to thousands of`,"concepts generated from a source list).","","Both files live inside the installed `authoring-cli` npm package, so they stay in step with","the CLI itself. If the paths above no longer exist, the package moved or was upgraded to a","different location \u2014 re-run `authoring-cli install-skill` to refresh this prompt.",""].join(`
|
|
19
|
+
`)}function It(t){try{return b.resolve(b.dirname(t),S.readlinkSync(t))}catch{return null}}function Z(t){try{return S.lstatSync(t)}catch{return null}}function Zt(t){let e=It(t);return e?S.existsSync(e)?`an existing symlink -> ${e}`:`a dangling symlink -> ${e}`:Z(t)?.isDirectory()?"an existing directory":"an existing file"}function On(t){let e=It(t);return e!==null&&b.basename(e)===$&&b.basename(b.dirname(e))==="skills"}function Fn(t){if(!Z(t)?.isFile())return!1;try{return S.readFileSync(t,"utf8").startsWith(Dn)}catch{return!1}}function Nn(t){return S.readdirSync(t,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(e=>b.relative(t,b.join(e.parentPath,e.name))).sort()}function Kn(t,e){if(!e||!S.existsSync(e))return!1;try{let r=Nn(e);return r.join(`
|
|
20
|
+
`)!==Nn(t).join(`
|
|
21
|
+
`)?!1:r.every(n=>S.readFileSync(b.join(t,n)).equals(S.readFileSync(b.join(e,n))))}catch{return!1}}function Zr(t,e,r){let n=t.project?b.join(r,".claude","skills"):b.join(e,".claude","skills"),o=b.join(n,$),s=t.shippedSkillDir,i=t.project&&s.startsWith(r+b.sep)?b.relative(b.dirname(o),s):s,a=Z(o),c=!1;if(a){let d=It(o);if(d===s&&S.existsSync(d))return{agent:"claude",path:o,status:"already-current",kind:"symlink",detail:s};if(!(On(o)||Kn(o,s))&&!t.force)return{agent:"claude",path:o,status:"blocked",kind:"symlink",detail:Zt(o)};S.rmSync(o,{recursive:!0,force:!0}),c=!0}S.mkdirSync(n,{recursive:!0});try{return S.symlinkSync(i,o,"dir"),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"symlink",detail:i}}catch(d){let l=d.code;if(l!=="EPERM"&&l!=="EACCES")throw d;return S.cpSync(s,o,{recursive:!0}),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"copy",detail:"symlinks unavailable on this platform \u2014 copied instead; re-run install-skill after upgrading the CLI"}}}function ts(t,e){let r=b.join(e,".codex","prompts"),n=b.join(r,`${$}.md`),o=Qr(t.shippedSkillDir),s=Z(n),i=!1;if(s){if((s.isFile()?S.readFileSync(n,"utf8"):null)===o)return{agent:"codex",path:n,status:"already-current",kind:"pointer"};if(!Fn(n)&&!t.force)return{agent:"codex",path:n,status:"blocked",kind:"pointer",detail:Zt(n)};S.rmSync(n,{recursive:!0,force:!0}),i=!0}return S.mkdirSync(r,{recursive:!0}),S.writeFileSync(n,o,"utf8"),{agent:"codex",path:n,status:i?"replaced":"installed",kind:"pointer"}}function Ln(t){let e=t.homeDir??Qt.homedir(),r=t.cwd??process.cwd();return(t.agents??Q(void 0,e)).map(o=>o==="claude"?Zr(t,e,r):ts(t,e))}function Bn(t){let e=t.homeDir??Qt.homedir(),r=t.cwd??process.cwd();return t.agents.map(n=>{let o=n==="claude"?b.join(t.project?b.join(r,".claude"):b.join(e,".claude"),"skills",$):b.join(e,".codex","prompts",`${$}.md`);if(!Z(o))return{agent:n,path:o,status:"not-registered"};if(!(n==="claude"?On(o)||Kn(o,t.shippedSkillDir):Fn(o))&&!t.force)return{agent:n,path:o,status:"left-alone",detail:`${Zt(o)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let i=It(o)??void 0;return S.rmSync(o,{recursive:!0,force:!0}),{agent:n,path:o,status:"removed",detail:i}})}function Mn(t){let e=te.homedir();return t===e||t.startsWith(e+G.sep)?G.join("~",G.relative(e,t)):t}function es(t){let e=Mn(t.path);switch(t.status){case"installed":case"replaced":return t.kind==="symlink"?`${e} (symlink -> ${Mn(t.detail??"")})`:t.kind==="copy"?`${e} (copy \u2014 ${t.detail})`:`${e} (pointer into the installed package)`;case"already-current":return`${e} (already registered \u2014 nothing to do)`;case"blocked":return`${e} NOT written \u2014 ${t.detail} is in the way; re-run with --force to replace it`}}async function _n(t){let e=xt(__dirname),r=Q(t.agent,te.homedir());t.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; Codex prompts are always user-global.");let n=Ln({agents:r,project:t.project,force:t.force,shippedSkillDir:e}),o=n.filter(a=>a.status==="installed"||a.status==="replaced"),s=n.filter(a=>a.status==="blocked");console.log(o.length?`Installed skill '${$}' for:`:s.length?`Could not install skill '${$}':`:`Skill '${$}' is already registered:`);for(let a of n)console.log(` ${a.agent.padEnd(7)} ${es(a)}`);if(t.project&&r.includes("claude")&&console.log(`
|
|
22
22
|
Project-scoped install: commit .claude/skills only if authoring-cli is a dependency of this
|
|
23
23
|
repo \u2014 a link into a globally installed package resolves on your machine alone.`),s.length){process.exitCode=1;return}o.length&&(console.log(`
|
|
24
|
-
Restart your agent, then use /${$}.`),n.some(a=>a.kind==="symlink")&&console.log('The symlink points into this package, so "npm update -g authoring-cli" updates the skill too.'),console.log('To unregister: "authoring-cli uninstall-skill" \u2014 run it before "npm rm -g authoring-cli".'));let i=D.filter(a=>!r.includes(a));i.length&&!
|
|
25
|
-
Skipped ${i.join(", ")} (no config directory found). Pass --agent ${i.join(",")} to register anyway.`)}var
|
|
26
|
-
Restart your agent to drop /authoring-cli from its command list.`)}function
|
|
27
|
-
set-acceptability --id <SCTID> --entries '[{"descriptionId":"...","gb":"PREFERRED"},{"descriptionId":"...","gb":"ACCEPTABLE"}]' [--project <projectKey> --task <taskKey>] (applies all entries in one save)`,required:["id"],run:
|
|
28
|
-
`)}async function
|
|
24
|
+
Restart your agent, then use /${$}.`),n.some(a=>a.kind==="symlink")&&console.log('The symlink points into this package, so "npm update -g authoring-cli" updates the skill too.'),console.log('To unregister: "authoring-cli uninstall-skill" \u2014 run it before "npm rm -g authoring-cli".'));let i=D.filter(a=>!r.includes(a));i.length&&!t.agent&&console.log(`
|
|
25
|
+
Skipped ${i.join(", ")} (no config directory found). Pass --agent ${i.join(",")} to register anyway.`)}var ee=v(require("os")),H=v(require("path"));function Un(t){let e=ee.homedir();return t===e||t.startsWith(e+H.sep)?H.join("~",H.relative(e,t)):t}function os(t){let e=Un(t.path);switch(t.status){case"removed":return t.detail?`${e} (was a symlink -> ${Un(t.detail)})`:`${e} (removed)`;case"not-registered":return`${e} (nothing registered here)`;case"left-alone":return`${e} KEPT \u2014 ${t.detail}`}}async function Vn(t){let e=t.agent?Q(t.agent,ee.homedir()):[...D],r;try{r=xt(__dirname)}catch{r=void 0}let n=Bn({agents:e,project:t.project,force:t.force,shippedSkillDir:r}),o=n.filter(i=>i.status==="removed"),s=n.filter(i=>i.status==="left-alone");console.log(o.length?`Removed skill '${$}' registration for:`:s.length?`Left every registration of '${$}' in place:`:`No '${$}' registration found:`);for(let i of n)console.log(` ${i.agent.padEnd(7)} ${os(i)}`);if(s.length){process.exitCode=1;return}o.length&&console.log(`
|
|
26
|
+
Restart your agent to drop /authoring-cli from its command list.`)}function ns(t){let e={};for(let r=0;r<t.length;r++){let n=t[r];if(n.startsWith("--")){let o=n.slice(2),s=t[r+1],i=s&&!s.startsWith("--")?t[++r]:"";e[o]=i}}return e}function Jn(t){let e=[];for(let r of t){if(r.startsWith("--"))break;e.push(r)}return e}var oe=[{name:"login",usage:`login [${et.join("|")}] [--ims-endpoint <url>] [--terminology-server-endpoint <url>] [--authoring-services-endpoint <url>] [--chrome-profile <name>] [--cookie-name <name>] (opens Chrome to sign in; automatically captures the session, macOS + Chrome only at launch. Environment defaults to ${W}; any --*-endpoint overrides that environment's value)`,run:(t,e)=>Uo({environment:e[0],imsEndpoint:t["ims-endpoint"],terminologyServerEndpoint:t["terminology-server-endpoint"],authoringServicesEndpoint:t["authoring-services-endpoint"],chromeProfile:t["chrome-profile"],cookieName:t["cookie-name"]})},{name:"logout",usage:"logout (deletes the locally stored session)",run:()=>Vo()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>qo()},{name:"install-skill",aliases:["install-skills"],usage:`install-skill [--agent ${D.join("|")}|all] [--project] [--force] (registers the authoring guidance skill bundled with this package with your AI agent, so /authoring-cli works alongside these commands \u2014 defaults to whichever agents are installed)`,run:t=>_n({agent:t.agent,project:"project"in t,force:"force"in t})},{name:"uninstall-skill",aliases:["uninstall-skills"],usage:`uninstall-skill [--agent ${D.join("|")}|all] [--project] [--force] (removes what install-skill registered \u2014 run this BEFORE "npm rm -g authoring-cli", since npm runs no uninstall hooks and this command goes away with the package)`,run:t=>Vn({agent:t.agent,project:"project"in t,force:"force"in t})},{name:"projects",usage:"projects [--json] (lists the projects available to you \u2014 no editor UI needed)",run:t=>Go({json:"json"in t})},{name:"tasks",usage:`tasks [--project <projectKey>] [--mine] [--status <status>] [--summary] [--json] (lists a project's tasks, or your own tasks across all projects if --project is omitted; --mine restricts to tasks assigned to you, --status filters by status e.g. "In Progress", --summary prints counts by project/assignee/status instead of one line per task)`,run:t=>Yo({project:t.project,mine:"mine"in t,status:t.status,summary:"summary"in t,json:"json"in t})},{name:"create-task",usage:'create-task --project <projectKey> --summary "<title>" [--description "<text>"] [--assignee <username>] [--unassigned] [--no-select] [--json] (creates a task via authoring-services and selects it; assigned to you unless overridden)',required:["project","summary"],run:t=>Wo({project:t.project,summary:t.summary,description:t.description,assignee:t.assignee,unassigned:"unassigned"in t,noSelect:"no-select"in t,json:"json"in t})},{name:"delete-task",usage:"delete-task [--project <projectKey> --task <taskKey>] (marks the task Deleted, defaulting to the selected task and clearing that selection; the branch and its content are left alone)",run:t=>zo({project:t.project,task:t.task})},{name:"recover-task",usage:"recover-task --project <projectKey> [--task <taskKey>] [--no-select] [--json] (without --task, lists the project's deleted tasks; with it, moves that task out of Deleted, keeps its branch content, and selects it)",required:["project"],run:t=>Xo({project:t.project,task:t.task,noSelect:"no-select"in t,json:"json"in t})},{name:"select-task",usage:"select-task --project <projectKey> --task <taskKey> (sets the task subsequent commands target when --project/--task are omitted)",required:["project","task"],run:t=>Qo({project:t.project,task:t.task})},{name:"current-task",usage:"current-task [--project <projectKey> --task <taskKey>] (prints the locally selected task; with --project/--task, notes whether they match \u2014 standalone has no editor UI to compare against instead)",run:t=>Zo({project:t.project,task:t.task})},{name:"create-concept",usage:'create-concept --fsn "<term>" --parent <SCTID> [--tag <semantic tag>] [--pt "<preferred term>"] [--module <moduleId>] [--project <projectKey> --task <taskKey>]',required:["fsn","parent"],run:t=>tn({fsn:t.fsn,tag:t.tag,pt:t.pt,parent:t.parent,module:t.module,project:t.project,task:t.task})},{name:"search-concepts",usage:"search-concepts [--term <text>] [--ecl <expr>] [--active true|false] [--limit N] [--check-authoring-form] [--conformed] [--project <projectKey> --task <taskKey>] (--check-authoring-form filters the search results down to concepts whose class axiom does \u2014 by default \u2014 NOT match transform-axiom's standard authoring form; add --conformed to see the ones that already do instead. Concepts that can't be checked \u2014 not yet classified since their last stated edit, an ambiguous multi-axiom concept \u2014 are reported separately under skippedConcepts rather than counted as either.)",run:t=>en({term:t.term,ecl:t.ecl,active:t.active,limit:t.limit,checkAuthoringForm:"check-authoring-form"in t,conformed:"conformed"in t,project:t.project,task:t.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--project <projectKey> --task <taskKey>]",required:["id"],run:t=>on({id:t.id,project:t.project,task:t.task})},{name:"validate-concept",usage:"validate-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (read-only check of the concept's current saved state \u2014 same convention rules the interactive editor runs on save, without saving anything)",required:["id"],run:t=>nn({id:t.id,project:t.project,task:t.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--check-authoring-form] [--conformed] [--project <projectKey> --task <taskKey>] (lists concepts with pending stated changes and concepts affected only by classification, derived from the task branch's traceability log, same as the Authoring Workbench's "Concepts for Review" tab; entries marked "deleted": true were created and then deleted on this branch and no longer exist. --check-authoring-form filters that list down to concepts whose class axiom does \u2014 by default \u2014 NOT match transform-axiom's standard authoring form; add --conformed to see the ones that already do instead; concepts that can't be checked are reported separately under skippedConcepts)`,run:t=>rn({checkAuthoringForm:"check-authoring-form"in t,conformed:"conformed"in t,project:t.project,task:t.task})},{name:"validate-review-concepts",usage:'validate-review-concepts [--project <projectKey> --task <taskKey>] [--json] (runs validate-concept on every concept with pending stated changes \u2014 the "concepts" list from get-concepts-for-review \u2014 skipping ones deleted on this branch, and prints a pass/issue tally; exits non-zero if any concept has issues)',run:t=>sn({project:t.project,task:t.task,json:"json"in t})},{name:"review-concepts",usage:"review-concepts [--project <projectKey> --task <taskKey>] (fetches the full concept representation \u2014 descriptions, relationships, axioms \u2014 for every concept with pending stated changes on the task, for an editorial review against SNOMED CT naming and modelling standards; see skills/authoring-cli/references/review-concepts.md. This is a data-gathering step, not a validation run \u2014 it performs no Snowstorm validation of its own)",run:t=>an({project:t.project,task:t.task})},{name:"add-description",usage:'add-description --id <SCTID> --term "<text>" --type FSN|SYNONYM [--tag <semanticTag>] [--module <id>] [--acceptability PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>]',required:["id","term","type"],run:t=>cn({id:t.id,term:t.term,type:t.type,tag:t.tag,module:t.module,acceptability:t.acceptability,project:t.project,task:t.task})},{name:"update-description",usage:'update-description --id <SCTID> --description-id <descriptionId> [--term "<text>"] [--case-significance <value>] [--project <projectKey> --task <taskKey>] (only if never versioned; reuses the existing descriptionId)',required:["id","description-id"],run:t=>pn({id:t.id,descriptionId:t["description-id"],term:t.term,caseSignificance:t["case-significance"],project:t.project,task:t.task})},{name:"set-case-significance",usage:"set-case-significance --id <SCTID> --description-id <descriptionId> --case-significance CASE_INSENSITIVE|INITIAL_CHARACTER_CASE_INSENSITIVE|ENTIRE_TERM_CASE_SENSITIVE [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id","description-id","case-significance"],run:t=>mn({id:t.id,descriptionId:t["description-id"],caseSignificance:t["case-significance"],project:t.project,task:t.task})},{name:"set-acceptability",usage:`set-acceptability --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--project <projectKey> --task <taskKey>] (at least one of --lang, --us, --gb required)
|
|
27
|
+
set-acceptability --id <SCTID> --entries '[{"descriptionId":"...","gb":"PREFERRED"},{"descriptionId":"...","gb":"ACCEPTABLE"}]' [--project <projectKey> --task <taskKey>] (applies all entries in one save)`,required:["id"],run:t=>fn({id:t.id,descriptionId:t["description-id"],lang:t.lang,us:t.us,gb:t.gb,entries:t.entries,project:t.project,task:t.task})},{name:"add-relationship",usage:"add-relationship --id <SCTID> --type <SCTID> --target <SCTID> [--group N] [--axiom-index N] [--project <projectKey> --task <taskKey>]",required:["id","type","target"],run:t=>dn({id:t.id,type:t.type,target:t.target,group:t.group,axiomIndex:t["axiom-index"],project:t.project,task:t.task})},{name:"remove-relationship",aliases:["delete-relationship"],usage:"remove-relationship --id <SCTID> --axiom-id <axiomId> (--relationship-id <relationshipId> | --relationship-index N) [--project <projectKey> --task <taskKey>] (only if the targeted relationship was never versioned)",required:["id","axiom-id"],run:t=>ln({id:t.id,axiomId:t["axiom-id"],relationshipId:t["relationship-id"],relationshipIndex:t["relationship-index"],project:t.project,task:t.task})},{name:"remove-role-group",aliases:["delete-role-group","delete-rolegroup"],usage:`remove-role-group --id <SCTID> --axiom-id <axiomId> --attributes '[{"typeId":"...","targetId":"..."}]' [--group-id N] [--project <projectKey> --task <taskKey>]`,required:["id","axiom-id","attributes"],run:t=>un({id:t.id,axiomId:t["axiom-id"],attributes:t.attributes,groupId:t["group-id"],project:t.project,task:t.task})},{name:"inactivate-concept",usage:"inactivate-concept --id <SCTID> --indicator <value> [--association-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>]",required:["id","indicator"],run:t=>gn({id:t.id,indicator:t.indicator,associationRefset:t["association-refset"],associationTarget:t["association-target"],project:t.project,task:t.task})},{name:"set-definition-status",usage:"set-definition-status --id <SCTID> --status PRIMITIVE|FULLY_DEFINED [--axiom-index N] [--project <projectKey> --task <taskKey>]",required:["id","status"],run:t=>yn({id:t.id,status:t.status,axiomIndex:t["axiom-index"],project:t.project,task:t.task})},{name:"update-axiom",usage:`update-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--project <projectKey> --task <taskKey>] (only if never versioned; replaces the axiom's relationships wholesale)`,required:["id","axiom-id","relationships"],run:t=>kn({id:t.id,axiomId:t["axiom-id"],relationships:t.relationships,project:t.project,task:t.task})},{name:"add-axiom",usage:`add-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--definition-status PRIMITIVE|FULLY_DEFINED] [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds a new class axiom; use to replace a published axiom \u2014 add the replacement here, then inactivate-axiom the old one)`,required:["id","relationships"],run:t=>xn({id:t.id,relationships:t.relationships,definitionStatus:t["definition-status"],moduleId:t["module-id"],project:t.project,task:t.task})},{name:"add-gci-axiom",usage:`add-gci-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds a new GCI axiom; the relationships are the axiom's sufficient-condition side)`,required:["id","relationships"],run:t=>Cn({id:t.id,relationships:t.relationships,moduleId:t["module-id"],project:t.project,task:t.task})},{name:"update-gci-axiom",usage:`update-gci-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--project <projectKey> --task <taskKey>] (only if never versioned; replaces the axiom's relationships wholesale)`,required:["id","axiom-id","relationships"],run:t=>hn({id:t.id,axiomId:t["axiom-id"],relationships:t.relationships,project:t.project,task:t.task})},{name:"delete-concept",usage:"delete-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id"],run:t=>In({id:t.id,project:t.project,task:t.task})},{name:"delete-description",usage:"delete-description --id <SCTID> --description-id <descriptionId> [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id","description-id"],run:t=>bn({id:t.id,descriptionId:t["description-id"],project:t.project,task:t.task})},{name:"delete-axiom",usage:"delete-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id","axiom-id"],run:t=>Sn({id:t.id,axiomId:t["axiom-id"],project:t.project,task:t.task})},{name:"inactivate-axiom",usage:"inactivate-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (retires a class axiom, including an already-published one, without deleting it; a concept must retain at least one active class axiom)",required:["id","axiom-id"],run:t=>vn({id:t.id,axiomId:t["axiom-id"],project:t.project,task:t.task})},{name:"transform-axiom",usage:"transform-axiom --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (rewrites a class axiom into the standard authoring form \u2014 Is-a to the proximal primitive parent(s) plus every currently-inferred attribute, per Snowstorm's own authoring-form computation; a never-versioned axiom is updated in place, a published one is replaced by adding the transformed axiom and inactivating the original \u2014 omit --axiom-id to target the concept's sole active class axiom)",required:["id"],run:t=>Tn({id:t.id,axiomId:t["axiom-id"],project:t.project,task:t.task})},{name:"check-authoring-form",usage:"check-authoring-form --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (read-only: reports whether a concept's class axiom already matches transform-axiom's standard authoring form, without writing anything; exits non-zero if it does not, or if it can't be checked (not yet classified, ambiguous multi-axiom concept) \u2014 same axiom-selection rule as transform-axiom, omit --axiom-id to target the sole active one)",required:["id"],run:t=>An({id:t.id,axiomId:t["axiom-id"],project:t.project,task:t.task})},{name:"delete-gci-axiom",usage:"delete-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id","axiom-id"],run:t=>wn({id:t.id,axiomId:t["axiom-id"],project:t.project,task:t.task})},{name:"classify",usage:"classify [--wait] [--timeout <seconds>, default 180] [--project <projectKey> --task <taskKey>] (self-healing: attaches to an already-running job, accepts an already-completed-but-unsaved one, or starts fresh)",run:t=>Rn({wait:"wait"in t,timeout:t.timeout,project:t.project,task:t.task})},{name:"classification-status",usage:"classification-status [--project <projectKey> --task <taskKey>] (read-only)",run:t=>$n({project:t.project,task:t.task})},{name:"validate-task",usage:"validate-task [--enable-mrcm] [--wait] [--timeout <seconds>, default 900] [--project <projectKey> --task <taskKey>] (validates the whole task branch \u2014 distinct from validate-concept)",run:t=>En({enableMrcm:"enable-mrcm"in t,wait:"wait"in t,timeout:t.timeout,project:t.project,task:t.task})},{name:"validation-status",usage:"validation-status [--project <projectKey> --task <taskKey>] (read-only)",run:t=>jn({project:t.project,task:t.task})},{name:"watch-notification",usage:"watch-notification [--entity-type <type>] [--timeout <seconds>, default 60] [--project <projectKey> --task <taskKey>] (blocks until the next real-time notification for this task arrives, or the timeout elapses \u2014 opens a temporary STOMP connection for the duration of this call)",run:t=>Pn({project:t.project,task:t.task,entityType:t["entity-type"],timeout:t.timeout})}];function Gn(t){if(!t.aliases?.length)return t.usage;let e=`(alias: ${t.aliases.join(", ")})`;return t.usage.startsWith(t.name)?`${t.name} ${e}${t.usage.slice(t.name.length)}`:`${t.usage} ${e}`}function qn(){return["Usage: authoring-cli <command> [options]","","Commands:",...oe.map(t=>` ${Gn(t)}`),"",'Run "login" first to sign in.',"With no --project/--task, actions target whatever task was",'last set via "select-task".'].join(`
|
|
28
|
+
`)}async function Hn(t=process.argv){let[,,e,...r]=t,n=ns(r),o=Jn(r);if(!e){console.log(qn());return}let s=oe.find(a=>a.name===e||a.aliases?.includes(e));if(!s){console.error(`Unknown command: ${e}
|
|
29
29
|
|
|
30
|
-
${
|
|
30
|
+
${qn()}`),process.exitCode=1;return}let i=(s.required??[]).filter(a=>!n[a]);if(i.length){console.error(`Missing required flag(s): ${i.map(a=>`--${a}`).join(", ")}
|
|
31
31
|
|
|
32
|
-
Usage: ${
|
|
32
|
+
Usage: ${Gn(s)}`),process.exitCode=1;return}await s.run(n,o)}require.main===module&&Hn().catch(t=>{console.error(t instanceof Error?t.message:String(t)),process.exitCode=1});0&&(module.exports={COMMANDS,main,parsePositionals});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "authoring-cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "CLI for SNOMED CT authoring against authoring-services",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"bin": {
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"files": [
|
|
10
10
|
"dist/index.js",
|
|
11
|
+
"HELP.md",
|
|
11
12
|
"skills/"
|
|
12
13
|
],
|
|
13
14
|
"engines": {
|
|
@@ -446,6 +446,92 @@ actually discriminate), how to shape the antecedent (genus + nexus + defining at
|
|
|
446
446
|
role-group partition that silently changes an axiom's meaning if got wrong), and how to derive the
|
|
447
447
|
axiom set from the terminology's own content rather than from theory alone.
|
|
448
448
|
|
|
449
|
+
### Replacing a published axiom
|
|
450
|
+
|
|
451
|
+
`update-axiom` and `delete-axiom` both refuse outright once an axiom's own `effectiveTime` is set —
|
|
452
|
+
there is no in-place edit for a released axiom's content, by design (rewriting a versioned axiom's
|
|
453
|
+
relationships, or removing it wholesale, risks silently changing what already shipped). "Replace"
|
|
454
|
+
therefore means two separate calls, not one: add the new axiom, then retire the old one.
|
|
455
|
+
|
|
456
|
+
```
|
|
457
|
+
authoring-cli add-axiom --id <SCTID> --relationships \
|
|
458
|
+
'[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}},
|
|
459
|
+
{"active":true,"groupId":1,"type":{"conceptId":"363698007"},"target":{"conceptId":"..."}}]'
|
|
460
|
+
|
|
461
|
+
authoring-cli inactivate-axiom --id <SCTID> --axiom-id <oldAxiomId>
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
Like `add-gci-axiom`, `add-axiom` has **no publication gate** — it appends a brand-new axiom, so a
|
|
465
|
+
released concept accepts it normally. `inactivate-axiom` also has no `effectiveTime` gate — setting
|
|
466
|
+
`active: false` on a released axiom's row is the normal RF2 retirement path, not an edit to its
|
|
467
|
+
content — but it does enforce that **at least one class axiom stays active**, so run `add-axiom`
|
|
468
|
+
first: the concept must never be left without a stated definition, even momentarily within the
|
|
469
|
+
same task.
|
|
470
|
+
|
|
471
|
+
The new axiom's `definitionStatus` defaults to `PRIMITIVE` regardless of what the axiom being
|
|
472
|
+
replaced was. If the axiom you're retiring was the concept's `FULLY_DEFINED` one and the new axiom
|
|
473
|
+
should take over that role, follow up with `set-definition-status --status FULLY_DEFINED
|
|
474
|
+
--axiom-index <N>` (index into `classAxioms` from a fresh `get-concept` — `add-axiom`'s own output
|
|
475
|
+
reports the server-assigned `axiomId` for the one you just added).
|
|
476
|
+
|
|
477
|
+
### Collapsing an axiom to the standard authoring form
|
|
478
|
+
|
|
479
|
+
`transform-axiom --id <SCTID> [--axiom-id <axiomId>]` rewrites a class axiom to Is-a the proximal
|
|
480
|
+
primitive parent(s) plus every currently-inferred attribute — the shape editorial convention
|
|
481
|
+
expects a primitive concept's stated definition to take, letting the classifier re-derive the more
|
|
482
|
+
specific hierarchy instead of the axiom asserting it directly. It gets this shape from Snowstorm's
|
|
483
|
+
own `GET .../authoring-form` (the same proximal-primitive-parent substitution the classifier itself
|
|
484
|
+
uses), not a local reimplementation, then routes through exactly the mechanism above: `update-axiom`
|
|
485
|
+
in place if the axiom has never been versioned, or `add-axiom` (carrying over the old axiom's
|
|
486
|
+
`moduleId` and `definitionStatus`) followed by `inactivate-axiom` if it has.
|
|
487
|
+
|
|
488
|
+
The one silent trap: **the target concept must already be classified**. `authoring-form` reads the
|
|
489
|
+
concept's saved *inferred* relationships to do the substitution, not a live reasoner call — call it
|
|
490
|
+
on a concept that predates the last classification (e.g. one just created on the current task) and
|
|
491
|
+
it comes back with no parents and no attributes at all, which `transform-axiom` then refuses to
|
|
492
|
+
write as an axiom ("produced no relationships"). That error names the symptom, not the cause; if you
|
|
493
|
+
see it, `classify --wait` the task first, then retry. If the axiom already matches authoring form,
|
|
494
|
+
`transform-axiom` checks that before writing anything and reports `alreadyConformed: true` rather
|
|
495
|
+
than reaching Snowstorm at all — the naive version of this reached `add-axiom` and let it 400 with
|
|
496
|
+
"Active Concept should not have duplicate axioms" for a published axiom, which was a real but
|
|
497
|
+
needless error to make the caller decode.
|
|
498
|
+
|
|
499
|
+
**It also surfaces on its own**: `validate-concept` runs this same check alongside Snowstorm's
|
|
500
|
+
own save-time validation and folds a non-conformant result in as a synthetic `WARNING` naming the
|
|
501
|
+
axiom and pointing at `transform-axiom` — you don't have to think to run `check-authoring-form`
|
|
502
|
+
separately to notice it. Because `validate-review-concepts` calls `validate-concept` per concept,
|
|
503
|
+
that warning shows up there too, on every concept with pending changes on the task, not just the
|
|
504
|
+
ones you happen to check by hand. It's silent only when authoring form can't be determined at all
|
|
505
|
+
(not classified since the last stated edit, or more than one active class axiom) — same
|
|
506
|
+
"can't-tell, not conforming" distinction as the `skippedConcepts` bucket below.
|
|
507
|
+
|
|
508
|
+
**Finding which concepts need it**: `search-concepts` takes the same `--check-authoring-form`
|
|
509
|
+
[`--conformed`] pair as a filter — it runs the ordinary search to define scope, then checks every
|
|
510
|
+
result with the same axiom-selection and authoring-form lookup `transform-axiom` itself uses, so a
|
|
511
|
+
concept it reports as not conforming is exactly one `transform-axiom` would act on:
|
|
512
|
+
|
|
513
|
+
```
|
|
514
|
+
authoring-cli search-concepts --ecl "<< 71388002 |Procedure|" --check-authoring-form
|
|
515
|
+
authoring-cli search-concepts --ecl "<< 71388002 |Procedure|" --check-authoring-form --conformed
|
|
516
|
+
```
|
|
517
|
+
|
|
518
|
+
Default is the non-conforming bucket (the one worth acting on); add `--conformed` to see the ones
|
|
519
|
+
already fine instead. This costs two extra HTTP calls per search result (concept + authoring-form),
|
|
520
|
+
run sequentially, so keep `--limit` reasonable on a broad ECL. Concepts that can't be checked at all
|
|
521
|
+
— not classified since their last stated edit, or with more than one active class axiom — are
|
|
522
|
+
reported separately under `skippedConcepts`, not silently counted into either bucket.
|
|
523
|
+
|
|
524
|
+
`get-concepts-for-review` takes the same `--check-authoring-form [--conformed]` pair, scoped to the
|
|
525
|
+
task's pending-changes list instead of an ECL — useful right before ending a task, to catch a
|
|
526
|
+
stated edit that never got run through `transform-axiom`. Deleted-on-this-branch entries are
|
|
527
|
+
skipped the same way `validate-review-concepts` skips them (not checked, not counted).
|
|
528
|
+
|
|
529
|
+
For a single concept you already have in mind, `check-authoring-form --id <SCTID> [--axiom-id
|
|
530
|
+
<axiomId>]` is the same read-only check as a standalone command — same axiom-selection rule and
|
|
531
|
+
same errors as `transform-axiom`, but it never writes anything. It exits non-zero both when the
|
|
532
|
+
axiom doesn't conform and when it can't be checked at all, so it composes in a shell conditional
|
|
533
|
+
(`check-authoring-form --id <id> || transform-axiom --id <id>`).
|
|
534
|
+
|
|
449
535
|
## Redundant stated Is-a relationships
|
|
450
536
|
|
|
451
537
|
Adding a new stated `Is a` (`116680003`) parent to a concept that already has a broader stated
|
|
@@ -466,12 +552,12 @@ more specific one. Resolve it immediately rather than leaving it as residue:
|
|
|
466
552
|
<id> --axiom-id <axiomId> --relationship-index <N>` removes just that one relationship
|
|
467
553
|
cleanly, in one call, **regardless of whether the axiom itself has been released** — prefer
|
|
468
554
|
this over rewriting the whole axiom.
|
|
469
|
-
- Else (that specific relationship has itself been versioned) →
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
555
|
+
- Else (that specific relationship has itself been versioned) → try `update-axiom` if the *whole
|
|
556
|
+
axiom* has never been versioned (rewrite the full list with the redundant parent dropped). If
|
|
557
|
+
the axiom is genuinely versioned too, `update-axiom` 409s — fall back to "Replacing a published
|
|
558
|
+
axiom" above: `add-axiom` with the full relationship list minus the redundant parent, then
|
|
559
|
+
`inactivate-axiom` on the original. Don't leave both stated parents in place and file it as
|
|
560
|
+
expected residue — the warning is real and resolvable in one CLI session.
|
|
475
561
|
3. Re-run `validate-concept --id <id>` to confirm the warning cleared.
|
|
476
562
|
|
|
477
563
|
## Deleting a concept
|
|
@@ -513,8 +599,11 @@ a reference you're looking straight at.
|
|
|
513
599
|
- **Children must be re-parented, not orphaned.** Decide their new parent deliberately: usually the
|
|
514
600
|
concept that supersedes the one being deleted, or failing that the deleted concept's own parent,
|
|
515
601
|
so the child doesn't silently jump up the hierarchy. Retarget with `update-axiom`, rewriting the
|
|
516
|
-
full relationship list with only that `Is a` target changed
|
|
517
|
-
|
|
602
|
+
full relationship list with only that `Is a` target changed — or, if the child's axiom is itself
|
|
603
|
+
versioned and `update-axiom` 409s, `add-axiom` with the corrected list followed by
|
|
604
|
+
`inactivate-axiom` on the original (see "Replacing a published axiom" above). Dropping the `Is a`
|
|
605
|
+
outright is only right when the child has other parents that already place it correctly — check,
|
|
606
|
+
don't assume.
|
|
518
607
|
- **Attribute references** get retargeted the same way, onto whichever concept now carries the
|
|
519
608
|
meaning.
|
|
520
609
|
- **A retrofitted `Is a` added to an existing published concept** (the common case when the
|
|
@@ -67,7 +67,12 @@ hierarchy, confirmed against the guide's `general-naming-conventions/` section:
|
|
|
67
67
|
Read the axiom from `get-concept`, not a cached summary, and check:
|
|
68
68
|
|
|
69
69
|
- **Multiple stated parentage is clinically coherent** — each parent should independently be true of
|
|
70
|
-
the concept, not just "close enough" to the intended meaning.
|
|
70
|
+
the concept, not just "close enough" to the intended meaning. This is a judgment call distinct
|
|
71
|
+
from whether one stated parent is redundant given another (e.g. one is an ancestor of the other) —
|
|
72
|
+
that's a save-time drools check Snowstorm already runs (`Concept should not contain any
|
|
73
|
+
redundantly stated IsA relationships`, surfaced by `validate-concept` and every write; see
|
|
74
|
+
`SKILL.md`'s "Redundant stated Is-a relationships" section), not an editorial call for this
|
|
75
|
+
checklist to duplicate.
|
|
71
76
|
- **Attribute values aren't more general than the concept's position in the hierarchy implies.** A
|
|
72
77
|
specific disorder with an unusually generic `Finding site` is worth a second look even if nothing
|
|
73
78
|
rejects the save.
|
|
@@ -89,6 +94,19 @@ Read the axiom from `get-concept`, not a cached summary, and check:
|
|
|
89
94
|
on it (or on a structurally-parallel batch generated from it — see `SKILL.md`'s substitution
|
|
90
95
|
pattern) misrepresents it, regardless of what `definitionStatus` the source concept happened to
|
|
91
96
|
carry.
|
|
97
|
+
- **The axiom should already be in authoring form** — Is-a the proximal primitive parent(s) plus
|
|
98
|
+
every currently-inferred attribute, not a more specific stated parent the classifier could
|
|
99
|
+
re-derive on its own. Unlike the judgment calls elsewhere in this checklist, this one is
|
|
100
|
+
mechanically checkable rather than a call to weigh, and `validate-review-concepts` already
|
|
101
|
+
surfaces it as a `WARNING` on any concept it can determine — you don't need a separate pass just
|
|
102
|
+
to notice it. Run `check-authoring-form --id <id>` per concept, or `get-concepts-for-review
|
|
103
|
+
--check-authoring-form` to check the whole review batch at once, only when you want the answer
|
|
104
|
+
without running full validation, or need the ones `validate-review-concepts` stays silent on
|
|
105
|
+
(not classified since the last stated edit, or more than one active class axiom). Treat anything
|
|
106
|
+
either surfaces as a warning, not a candidate for editorial debate — fix it with
|
|
107
|
+
`transform-axiom --id <id>`, and see `SKILL.md`'s "Collapsing an axiom to the standard authoring
|
|
108
|
+
form" for what that does and the one case it can't check (a concept that hasn't been classified
|
|
109
|
+
since its last stated edit).
|
|
92
110
|
- **MRCM domain/range conformance isn't fully visible from `get-concept` or `validate-concept`.**
|
|
93
111
|
Both surface Snowstorm's save-time checks, which catch cardinality and some domain/range
|
|
94
112
|
violations, but not every MRCM constraint is enforced synchronously at save. If an attribute's
|
|
@@ -170,10 +188,45 @@ full — treat the table as where to look, confirm what it says before relying o
|
|
|
170
188
|
from a page not summarized here, and strip GitBook markup (`{% hint %}` blocks, feedback-button
|
|
171
189
|
`<a>` tags) from whatever comes back.
|
|
172
190
|
|
|
191
|
+
## Verifying concept meaning against the professional literature
|
|
192
|
+
|
|
193
|
+
The checks above assume you already know what the concept is supposed to mean — that you can
|
|
194
|
+
recognise a synonym conflation, judge whether an attribute value is too generic, or confirm an
|
|
195
|
+
eponym's published form. When the concept's subject matter is genuinely unfamiliar or ambiguous,
|
|
196
|
+
that assumption doesn't hold, and guessing at a plausible-sounding meaning risks signing off on
|
|
197
|
+
content that's wrong in a way none of the mechanical checks catch. In that case, web search for
|
|
198
|
+
reputable professional publications before making the call, not instead of it.
|
|
199
|
+
|
|
200
|
+
Reach for a search when:
|
|
201
|
+
|
|
202
|
+
- A description names a term you don't already recognise, or one that reads as plausibly meaning
|
|
203
|
+
two different clinical ideas — before deciding whether it's a synonym conflation or two
|
|
204
|
+
legitimate names for the same thing.
|
|
205
|
+
- An eponym's possessive form isn't obviously covered by the general rule above — confirm the
|
|
206
|
+
actual published form rather than guessing from familiarity.
|
|
207
|
+
- An attribute value (finding site, associated morphology, causative agent, and the like) looks
|
|
208
|
+
plausible from the axiom alone but you can't independently confirm it's the value a domain
|
|
209
|
+
expert would actually assert.
|
|
210
|
+
- The concept sits in a domain you don't have working familiarity with — a specific lab assay, a
|
|
211
|
+
rare syndrome, a device class — where the alternative to searching is silently endorsing content
|
|
212
|
+
on the strength of the name alone.
|
|
213
|
+
|
|
214
|
+
"Reputable" here means specialty society or college guidelines, peer-reviewed journal articles,
|
|
215
|
+
established clinical/technical textbooks, WHO or other national-authority classifications, and
|
|
216
|
+
regulatory or manufacturer documentation for substances and devices. General-audience sites, forum
|
|
217
|
+
answers, and unsourced summaries can point toward a real source but aren't themselves a basis for
|
|
218
|
+
an editorial decision — follow them to something citable before relying on it.
|
|
219
|
+
|
|
220
|
+
This is an input to the judgment calls already in this checklist, not a separate pass with its own
|
|
221
|
+
pass/fail criteria — a search that confirms existing content needs no write-up; one that changes a
|
|
222
|
+
decision should say what it found and where.
|
|
223
|
+
|
|
173
224
|
## What this checklist is not
|
|
174
225
|
|
|
175
226
|
This is an editorial review, not a validation run — it doesn't check what Snowstorm enforces at
|
|
176
227
|
save time (MRCM cardinality, description constraints, and the like), and it isn't a substitute for
|
|
177
|
-
whatever command does check that.
|
|
178
|
-
this pass is judging whether content is *right*, not whether it saves, which is exactly the
|
|
179
|
-
residue no command can absorb.
|
|
228
|
+
whatever command does check that. Almost nothing here can be delegated to a CLI flag: the whole
|
|
229
|
+
point of this pass is judging whether content is *right*, not whether it saves, which is exactly the
|
|
230
|
+
kind of residue no command can absorb. Authoring-form conformance is the one exception — it has a
|
|
231
|
+
single correct shape, not a range of defensible ones, so it's checked with `check-authoring-form`
|
|
232
|
+
rather than judged by eye; everything else above still needs a human or agent's editorial read.
|