authoring-cli 0.1.16 → 0.1.17

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 CHANGED
@@ -297,7 +297,7 @@ https://github.com/snomed/authoring-cli
297
297
  ## FAQ
298
298
 
299
299
  **Q: Can I use this on Windows or Linux?**
300
- 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.
300
+ A: The CLI runs on any Node.js 24+ environment. Automatic session capture during login works on macOS with Chrome, and on Linux with Chromium/Chrome (including a Termux:X11 proot-distro Debian on Android — `apt install chromium sqlite3`, and open the Termux:X11 app by hand once so `login` has a display to draw its sign-in window on). On Windows and any other unsupported platform, `login` will fail with a clear message. You can manually pass endpoints and a session cookie using flags, but that's not yet implemented.
301
301
 
302
302
  **Q: How do I use this with an AI agent?**
303
303
  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.
package/README.md CHANGED
@@ -75,7 +75,7 @@ Signed in as Jane Doe. (reused an existing Chrome session — no browser opened.
75
75
  Authoring services: https://authoring.ihtsdotools.org/authoring-services/ (production)
76
76
  ```
77
77
 
78
- **Current support**: automatic session capture works on **macOS with Google Chrome** only. On any other OS/browser combination, `login` fails immediately with a message naming the unsupported combination, rather than hanging or failing silently. Support for other platforms/browsers is possible future work.
78
+ **Current support**: automatic session capture works on **macOS with Google Chrome**, and on **Linux with Chromium/Chrome** — including a Termux:X11 proot-distro Debian on Android, where `login` auto-starts Termux:X11's own backend (`termux-x11 :1 &`) if nothing is already serving a display (the Termux:X11 **app** itself still needs to have been opened by hand at least once). On any other OS/browser combination, `login` fails immediately with a message naming the unsupported combination, rather than hanging or failing silently.
79
79
 
80
80
  `logout` deletes the locally stored session. It does not sign you out of IMS in Chrome, so a subsequent `login` will reuse that browser session.
81
81
 
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var gr=Object.create;var ae=Object.defineProperty;var yr=Object.getOwnPropertyDescriptor;var hr=Object.getOwnPropertyNames;var kr=Object.getPrototypeOf,Cr=Object.prototype.hasOwnProperty;var Ir=(e,t)=>{for(var r in t)ae(e,r,{get:t[r],enumerable:!0})},pt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of hr(t))!Cr.call(e,o)&&o!==r&&ae(e,o,{get:()=>t[o],enumerable:!(n=yr(t,o))||n.enumerable});return e};var T=(e,t,r)=>(r=e!=null?gr(kr(e)):{},pt(t||!e||!e.__esModule?ae(r,"default",{value:e,enumerable:!0}):r,e)),xr=e=>pt(ae({},"__esModule",{value:!0}),e);var Hi={};Ir(Hi,{COMMANDS:()=>ut,main:()=>fr,parsePositionals:()=>pr});module.exports=xr(Hi);var U={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"}},br={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},ce=Object.keys(U);function mt(e){return br[e.trim().toLowerCase()]??null}var z="uat",Wi=U.uat.imsEndpoint,Qi=U.uat.terminologyServerEndpoint,zi=U.uat.authoringServicesEndpoint;var Sr=T(require("http")),vr=T(require("https"));function I(e,t={}){let{method:r="GET",cookie:n,body:o,headers:i={},timeoutMs:s=15e3}=t;return new Promise((a,c)=>{let l;try{l=new URL(e)}catch(h){c(h);return}let d=l.protocol==="https:"?vr:Sr,u=o!==void 0?JSON.stringify(o):void 0,p={accept:"application/json",...i};if(u!==void 0&&(p["content-type"]="application/json",p["content-length"]=String(Buffer.byteLength(u))),n){let h=n.replace(/[^\x20-\x7e\t]/g,"");h&&(p.cookie=h)}let g=!1,y=d.request({hostname:l.hostname,port:l.port||void 0,path:l.pathname+l.search,method:r,headers:p},h=>{let b="";h.on("data",w=>{b+=w}),h.on("end",()=>{if(g)return;g=!0,clearTimeout(k);let w=h.statusCode??0,P=(h.headers["content-type"]??"").includes("application/json"),O=null,_=!1;if(b)try{O=JSON.parse(b)}catch{_=!P}a({statusCode:w,body:O,rawBody:b,sessionExpired:_})})});y.on("error",h=>{g||(g=!0,clearTimeout(k),c(h))});let k=setTimeout(()=>{g||(g=!0,y.destroy(),c(new Error(`Request to ${e} timed out after ${s}ms`)))},s);u!==void 0&&y.write(u),y.end()})}var F="900000000000509007",V="900000000000508004";var ft={[F]:"en-us",[V]:"en-gb"},gt={[F]:"true",[V]:"true"},Tr={},Ar={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:ft,dialectDefaults:gt,readOnlyDialects:Tr,defaultLanguage:"en"};function yt(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return Ar;let t={[F]:"en-us"},r={},n={},o=[];for(let c of Object.keys(e)){let l=c.match(/^requiredLanguageRefset\.(.+)/);if(l){let d=l[1];t[String(e[c])]=d,o.length===0&&o.push(d)}}let i=e.requiredLanguageRefsets;if(Array.isArray(i))for(let c of i){if(typeof c!="object"||c===null)continue;let l=null,d=null;for(let[y,k]of Object.entries(c))y.length===2&&(l=y,d=String(k));if(!l||!d)continue;let u=c.dialectName;t[d]=typeof u=="string"?u:l;let p=c.default;p==="true"&&!o.includes(l)&&o.push(l),p!=null&&(r[d]=String(p));let g=c.readOnly;g!=null&&(n[d]=String(g))}let s=e.optionalLanguageRefsets;if(Array.isArray(s))for(let c of s)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?ft:t,dialectDefaults:a?gt:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function Ne(e,t,r,n){let o={};for(let i of Object.keys(e.dialects)){let s=e.dialects[i];e.isExtension&&!r?s.includes(n)?o[i]="PREFERRED":s.includes(e.defaultLanguage)&&(o[i]="ACCEPTABLE"):s.includes(n)&&(o[i]=t),e.dialectDefaults[i]==="false"&&!r&&delete o[i],e.readOnlyDialects[i]==="true"&&delete o[i]}return o}function de(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[F]:"PREFERRED"}:Ne(e,"PREFERRED",t,"en")}var Rr="900000000000207008";function ht(e){return e.replace(/\/$/,"")}function A(e){return ht(e.terminologyServerEndpoint)}function E(e){return ht(e.authoringServicesEndpoint)}function kt(e){return`${new URL(E(e)).origin}/authoring-traceability-service`}function q(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function C(e,t,r){let n=t.projectKey||r?.projectKey,o=t.taskKey||r?.taskKey,i=!t.projectKey&&!t.taskKey,s=t.branchPath||(i?r?.branchPath:void 0);return!n||!o?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(s||(s=await wr(e,n,o)??void 0),s?{ok:!0,projectKey:n,taskKey:o,branchPath:s}:{ok:!1,error:`Could not resolve branch path for ${n}/${o}.`})}async function G(e,t){let r=A(e),n=await I(`${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),i=o[o.length-1],s=o.slice(0,-1).join("/");if(!i||!s)return{ok:!1,error:`Cannot create branch from path "${t}" \u2014 expected a parent and a name.`};let a=await I(`${r}/branches`,{method:"POST",body:{parent:s,name:i},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 wr(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body?.branchPath??null}async function Ct(e,t,r){let n=r?.get(t);if(n)return n;let o=`${E(e)}/projects/${t}`,s=(await I(o,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,s),s}async function M(e,t,r){let n=await Ct(e,t,r),o=n.multipleModuleEditingDisabled,i=!o||o==="false";return n.expectedExtensionModules?.length&&i?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:Rr}async function J(e,t,r){let n=await Ct(e,t,r);return yt(n)}async function De(e,t){let r=e.replace(/\/$/,"")+"/auth",n=await I(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 It=T(require("crypto"));var Er="116680003";function X(e,t,r,n,o="PREFERRED",i=!1){let s=e==="FSN"?de(n,i):Ne(n,o,i,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:s}}async function xt(e,t,r,n=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:i,taskKey:s,branchPath:a}=o,c=q(a),l=t.moduleId||await M(e,i,n),d=await J(e,i,n),u=t.preferredTerm||t.fsn,p=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,g={conceptId:null,moduleId:l,definitionStatus:"PRIMITIVE",active:!0,descriptions:[X("FSN",p,l,d,"PREFERRED",!0),X("SYNONYM",u,l,d,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:It.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:l,relationships:[{active:!0,groupId:0,type:{conceptId:Er},target:{conceptId:t.parentConceptId}}]}]},y=`${A(e)}/browser/${c}/${i}/${s}/concepts/?validate=true`,k=await I(y,{method:"POST",body:g,cookie:e.cookie});if(k.sessionExpired){let w="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${i}/${s}: SESSION EXPIRED`),{statusCode:401,body:{error:w}}}let h=k.body,b=h&&"conceptId"in h?h.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${i}/${s}: ${k.statusCode<300?"OK":"FAILED ("+k.statusCode+")"} \u2014 ${p}`+(b?` \u2192 ${b}`:"")),typeof b=="string"&&e.onValidationResults?.(b,h?.validationResults),{statusCode:k.statusCode,body:k.body}}var $r=["descriptions","descriptionFull","axioms","inferred","gci","gciAxiomsCount","full"],jr={descriptions:"--descriptions",descriptionFull:"--description-full",axioms:"--axioms",inferred:"--inferred",gci:"--gci",gciAxiomsCount:"--gci-axioms-count",full:"--full"};function Pr(e,t){return(Array.isArray(e[t])?e[t]:[]).filter(n=>n.active!==!1).length}function bt(e,t){return(Array.isArray(e.relationships)?e.relationships:[]).filter(n=>n.characteristicType===t)}function Z(e){return{conceptId:e.conceptId,fsn:e.fsn,pt:e.pt,active:e.active,definitionStatus:e.definitionStatus}}function ee(e){return typeof e=="object"&&e!==null}function Nr(e,t,r){let n=Array.isArray(e[r])?e[r]:[],o=[];for(let i of n){if(i.active===!1||typeof i.axiomId!="string")continue;(Array.isArray(i.relationships)?i.relationships:[]).forEach((a,c)=>{let l=a.type;if((ee(l)?l.conceptId:void 0)!==t)return;let u=a.target;o.push({axiomId:i.axiomId,relationshipId:typeof a.relationshipId=="string"?a.relationshipId:void 0,relationshipIndex:c,groupId:typeof a.groupId=="number"?a.groupId:0,targetId:ee(u)?u.conceptId:void 0,targetFsn:ee(u)&&ee(u.fsn)?u.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return o}async function le(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};if(!t.attributeType){let a=$r.filter(c=>t[c]);if(a.length>1)return{statusCode:400,body:{error:`Specify only one of ${a.map(c=>jr[c]).join(", ")}.`}}}if(!t.attributeType&&!t.descriptions&&!t.descriptionFull&&!t.axioms&&!t.inferred&&!t.gci&&!t.gciAxiomsCount&&!t.full){let a=`${A(e)}/${n.branchPath}/concepts/${t.conceptId}`,c=await I(a,{cookie:e.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:c.statusCode,body:c.body}}let o=`${A(e)}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await I(o,{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||!ee(i.body))return{statusCode:i.statusCode,body:i.body};let s=i.body;if(t.attributeType){let a=t.gci?"gciAxioms":"classAxioms",c=Nr(s,t.attributeType,a);return{statusCode:i.statusCode,body:{conceptId:t.conceptId,attributeType:t.attributeType,gci:!!t.gci,matches:c}}}if(t.descriptions){let a=Array.isArray(s.descriptions)?s.descriptions.filter(c=>c.active!==!1):[];return{statusCode:i.statusCode,body:{...Z(s),descriptions:a}}}return t.descriptionFull?{statusCode:i.statusCode,body:{...Z(s),descriptions:s.descriptions??[]}}:t.axioms?{statusCode:i.statusCode,body:{...Z(s),classAxioms:s.classAxioms??[],relationships:bt(s,"STATED_RELATIONSHIP")}}:t.inferred?{statusCode:i.statusCode,body:{...Z(s),relationships:bt(s,"INFERRED_RELATIONSHIP")}}:t.gci?{statusCode:i.statusCode,body:{...Z(s),gciAxioms:s.gciAxioms??[]}}:t.gciAxiomsCount?{statusCode:i.statusCode,body:{conceptId:s.conceptId,gciAxiomsCount:Pr(s,"gciAxioms")}}:{statusCode:i.statusCode,body:s}}var Dr=500,Or=1e4;async function ue(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o={expand:"fsn()"};t.term&&(o.termFilter=t.term),t.ecl&&(o.eclFilter=t.ecl),typeof t.active=="boolean"&&(o.activeFilter=t.active);let i=`${A(e)}/${n.branchPath}/concepts/search`,s=d=>({conceptId:d.conceptId,fsn:d.fsn?.term,pt:d.pt?.term,active:d.active,moduleId:d.moduleId});if(t.limit!==void 0){let d=await I(i,{method:"POST",body:{...o,limit:t.limit},cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let u=(d.body?.items??[]).map(s);return{statusCode:d.statusCode,body:{total:d.body?.total??u.length,items:u}}}let a=[],c=0,l=0;for(;;){let d=Math.min(Dr,Or-l);if(d<=0)break;let u=await I(i,{method:"POST",body:{...o,limit:d,offset:l},cookie:e.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(u.statusCode<200||u.statusCode>=300)return{statusCode:u.statusCode,body:u.body??{error:"Concept search failed."}};let p=u.body?.items??[];if(a.push(...p.map(s)),c=u.body?.total??a.length,l+=p.length,p.length===0||l>=c)break}return{statusCode:200,body:{total:c,items:a,...a.length<c?{truncated:!0,message:`Only ${a.length} of ${c} matches returned \u2014 Snowstorm caps unsorted search at offset+limit 10,000. Narrow the query (--term/--ecl/--active) to see the rest.`}:{}}}}var te=1e3;function Fr(e){let t=new Map;for(let r of e)for(let n of r){let o=n.referenceType?.conceptId??"",i=t.get(o);i?i.referencingConcepts=[...i.referencingConcepts??[],...n.referencingConcepts??[]]:t.set(o,{...n,referencingConcepts:[...n.referencingConcepts??[]]})}return[...t.values()]}async function St(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${A(e)}/${n.branchPath}/concepts/${t.conceptId}/references`,i=(d,u)=>{let p=new URLSearchParams;return typeof t.stated=="boolean"&&p.set("stated",String(t.stated)),p.set("limit",String(d)),p.set("offset",String(u)),I(`${o}?${p.toString()}`,{cookie:e.cookie})};if(typeof t.limit=="number"||typeof t.offset=="number"){let d=await i(t.limit??te,t.offset??0);return d.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:d.statusCode,body:d.body}}let s=[],a=0,c=0,l=0;for(;;){let d=await i(te,l);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:d.body??{error:"Could not fetch references."}};let u=d.body?.referencesByType??[];s.push(u),a=d.body?.total??a;let p=u.reduce((g,y)=>g+(y.referencingConcepts?.length??0),0);if(c+=p,p===0||p<te||c>=a)break;l+=te}return{statusCode:200,body:{total:a,limit:te,offset:0,referencesByType:Fr(s)}}}var Le=T(require("crypto"));function vt(e){return typeof e=="object"&&e!==null}function Lr(e){let t=e.type,r=e.target,n=vt(t)?t.conceptId:void 0,o=vt(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function Kr(e,t){let r=[...t];for(let n of e){let o=r.findIndex(i=>i.typeId===n.typeId&&i.targetId===n.targetId);if(o===-1)return!1;r.splice(o,1)}return!0}function Tt(e,t,r){let n=new Map;for(let s of e){let a=typeof s.groupId=="number"?s.groupId:0,c=n.get(a);c?c.push(s):n.set(a,[s])}let o=[];for(let[s,a]of n){if(r!=null?s!==r:s===0)continue;let c=a.map(Lr).filter(l=>l!=null);Kr(t,c)&&o.push(s)}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 i=o[0];return{ok:!0,groupId:i,relationships:n.get(i)}}var Mr=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],Br=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],_r=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],Ur=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],Vr=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],Ke=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function Ot(e){return Ke.includes(e)}function oe(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function pe(e){return typeof e=="object"&&e!==null}function At(e){return pe(e)?oe(e,Ur):e}function Ft(e){if(!pe(e))return e;let t=oe(e,_r);return"type"in t&&(t.type=At(t.type)),"target"in t&&(t.target=At(t.target)),t}function qr(e){return pe(e)?oe(e,Br):e}function Rt(e){if(!pe(e))return e;let t=oe(e,Vr);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(Ft)),t}function Me(e){let t=oe(e,Mr);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(qr)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(Ft)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(Rt)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(Rt)),t}function Gr(e){return new Promise(t=>setTimeout(t,e))}function Jr(e){if(e.statusCode!==400)return!1;let t=e.body;return t?.error==="BAD_REQUEST"&&typeof t.message=="string"&&t.message.includes("is already locked")}var Oe=[300,600,1200,2400,4800],wt=new Map;function Hr(e,t){let n=(wt.get(e)??Promise.resolve()).then(t,t);return wt.set(e,n.then(()=>{},()=>{})),n}async function R(e,t,r,n){try{return await Hr(t.branchPath,()=>Yr(e,t,r,n))}catch(o){return{statusCode:500,body:{error:o instanceof Error?o.message:String(o)}}}}async function Yr(e,t,r,n){for(let o=0;;o++){let i=A(e),s=`${i}/browser/${t.branchPath}/concepts/${r}`,a=await I(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:a.body}};let c=a.body,l=n(c);if(l)return l;let d=q(t.branchPath),u=`${i}/browser/${d}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,p=await I(u,{method:"PUT",body:Me(c),cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(Jr(p)&&o<Oe.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${o+1}/${Oe.length})`),await Gr(Oe[o]);continue}e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${p.statusCode<300?"OK":"FAILED ("+p.statusCode+")"} \u2014 ${r}`);let g=p.body;return e.onValidationResults?.(r,g?.validationResults),{statusCode:p.statusCode,body:p.body}}}var Et=["PREFERRED","ACCEPTABLE"];async function Lt(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&&!Et.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${Et.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n),s=await J(e,o.projectKey,n),a=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return R(e,o,t.conceptId,c=>{let l=Array.isArray(c.descriptions)?c.descriptions:[];return l.push(X(t.type,a,i,s,t.acceptability??"ACCEPTABLE",!1)),c.descriptions=l,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 C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return R(e,n,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s[o];if(!a)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${s.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 Mt(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 C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return R(e,n,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s[o];return a?(a.definitionStatus=t.status,i.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${s.length}).`}}})}async function Bt(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>o.effectiveTime==null?{statusCode:409,body:{error:`Unpublished concept ${t.conceptId} cannot be inactivated \u2014 it should be deleted instead (use delete-concept).`}}:(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 _t(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&&!Ot(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Ke.join(", ")}.`}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?s.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(s.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(s.term=t.term),t.caseSignificance&&(s.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Ut(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!Ot(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Ke.join(", ")}.`}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?(s.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}var Fe=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function $t(e){return Fe.includes(e)}function Vt(e){return e.us&&!$t(e.us)?{statusCode:400,body:{error:`us must be one of: ${Fe.join(", ")}.`}}:e.gb&&!$t(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${Fe.join(", ")}.`}}:null}function qt(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.`}}:Vt(e):{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function Be(e,t,r){let n=e.find(i=>i.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[F]:o[F]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[V]:o[V]=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 Gt(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=qt(n);if(o)return o;let i=await C(e,t,r);return i.ok?R(e,i,t.conceptId,s=>{let a=Array.isArray(s.descriptions)?s.descriptions:[];return Be(a,t.conceptId,n)}):{statusCode:400,body:{error:i.error}}}async function Jt(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 i=qt(o);if(i)return i}let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.descriptions)?o.descriptions:[];for(let s of t.entries){let a=Be(i,t.conceptId,s);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function Ht(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.descriptions)?o.descriptions:[],s=i.findIndex(a=>a.descriptionId===t.descriptionId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published description ${t.descriptionId} cannot be deleted \u2014 use inactivate-description instead.`}}:(i.splice(s,1),o.descriptions=i,null)}):{statusCode:400,body:{error:n.error}}}var me="REFERS_TO";async function Yt(e,t,r){if(!t.conceptId||!t.descriptionId||!t.indicator)return{statusCode:400,body:{error:"conceptId, descriptionId, and indicator are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?s.effectiveTime==null?{statusCode:409,body:{error:`Unpublished description ${t.descriptionId} cannot be inactivated \u2014 it should be deleted instead (use delete-description).`}}:(s.active=!1,s.inactivationIndicator=t.indicator,s.acceptabilityMap={},t.associationTargetId&&(s.associationTargets={[me]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}function jt(e,t,r){for(let n of e){if(n.descriptionId===t||n.active===!1||n.type!=="SYNONYM")continue;let o=n.acceptabilityMap;o?.[r]==="PREFERRED"&&(n.acceptabilityMap={...o,[r]:"ACCEPTABLE"})}}async function Wt(e,t,r,n=new Map){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},i=Vt(o);if(i)return i;let s=!!(t.lang||t.us||t.gb),a=await C(e,t,r);if(!a.ok)return{statusCode:400,body:{error:a.error}};let c=await J(e,a.projectKey,n);return R(e,a,t.conceptId,l=>{let d=Array.isArray(l.descriptions)?l.descriptions:[],u=d.find(g=>g.descriptionId===t.descriptionId);if(!u)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(u.active!==!1)return{statusCode:409,body:{error:`Description ${t.descriptionId} is already active.`}};if(u.type==="FSN"){if(s)return{statusCode:400,body:{error:"lang/us/gb do not apply when restoring an FSN \u2014 it is always PREFERRED in every dialect the project uses."}};let g=d.filter(y=>y.type==="FSN"&&y.active!==!1&&y.descriptionId!==t.descriptionId);if(g.length>1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${g.length} other active FSNs \u2014 cannot restore unambiguously.`}};if(g.length===1){let y=g[0];if(y.effectiveTime==null)d.splice(d.indexOf(y),1);else{if(!t.indicator)return{statusCode:400,body:{error:`Restoring this FSN requires --indicator, to retire the concept's current active (published) FSN ${String(y.descriptionId)} in the same save.`}};y.active=!1,y.inactivationIndicator=t.indicator,y.acceptabilityMap={},t.associationTargetId&&(y.associationTargets={[me]:[t.associationTargetId]})}}return u.active=!0,delete u.inactivationIndicator,delete u.associationTargets,u.acceptabilityMap=de(c,!1),l.descriptions=d,null}if(!s)return{statusCode:400,body:{error:"At least one of lang, us, or gb is required to restore this description's acceptability."}};u.active=!0,delete u.inactivationIndicator,delete u.associationTargets;let p=Be(d,t.conceptId,o);return p||(o.us==="PREFERRED"&&jt(d,t.descriptionId,F),o.gb==="PREFERRED"&&jt(d,t.descriptionId,V),null)})}var Wr="900000000000490003",Pt=["NOT_SEMANTICALLY_EQUIVALENT","OUTDATED","GRAMMATICAL_DESCRIPTION_ERROR","NONCONFORMANCE_TO_EDITORIAL_POLICY"];async function Qt(e,t,r){if(!t.conceptId||!t.descriptionId||!t.reason)return{statusCode:400,body:{error:"conceptId, descriptionId, and reason are required."}};if(!Pt.includes(t.reason))return{statusCode:400,body:{error:`reason must be one of: ${Pt.join(", ")}.`}};if(t.reason==="NOT_SEMANTICALLY_EQUIVALENT"){if(!t.targetId)return{statusCode:400,body:{error:"reason NOT_SEMANTICALLY_EQUIVALENT requires --target-id \u2014 the concept this description actually belongs under."}}}else if(t.targetId)return{statusCode:400,body:{error:`--target-id only applies to reason NOT_SEMANTICALLY_EQUIVALENT (paired with a REFERS_TO association) \u2014 omit it for ${t.reason}.`}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=`${A(e)}/${n.branchPath}/members?referencedComponentId=${encodeURIComponent(t.descriptionId)}&referenceSet=${Wr}&active=true`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||500,body:{error:`Could not check description ${t.descriptionId}'s current inactivation reason.`,details:s.body}};let a=(s.body.items??[])[0];return a?.released===!0?{statusCode:409,body:{error:`Description ${t.descriptionId}'s inactivation reason has already been published (effectiveTime ${String(a.effectiveTime)}) and cannot be changed.`}}:R(e,n,t.conceptId,c=>{let d=(Array.isArray(c.descriptions)?c.descriptions:[]).find(u=>u.descriptionId===t.descriptionId);return d?d.active!==!1?{statusCode:409,body:{error:`Description ${t.descriptionId} is active \u2014 use inactivate-description to inactivate it with a reason.`}}:(d.inactivationIndicator=t.reason,t.reason==="NOT_SEMANTICALLY_EQUIVALENT"?d.associationTargets={[me]:[t.targetId]}:delete d.associationTargets,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function zt(e,t,r,n=new Map){if(!t.conceptId||!t.term||!t.indicator)return{statusCode:400,body:{error:"conceptId, term, and indicator are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n),s=await J(e,o.projectKey,n),a=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return R(e,o,t.conceptId,c=>{let l=Array.isArray(c.descriptions)?c.descriptions:[],d;if(t.descriptionId){if(d=l.find(u=>u.descriptionId===t.descriptionId),!d)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(d.type!=="FSN")return{statusCode:400,body:{error:`Description ${t.descriptionId} is a ${String(d.type)}, not an FSN.`}}}else{let u=l.filter(p=>p.type==="FSN"&&p.active!==!1);if(u.length!==1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${u.length} active FSNs \u2014 pass --description-id to say which one to replace.`}};d=u[0]}return d.effectiveTime==null?{statusCode:409,body:{error:`Description ${String(d.descriptionId)} has no effectiveTime (never versioned) \u2014 use update-description instead.`}}:(d.active=!1,d.inactivationIndicator=t.indicator,d.acceptabilityMap={},t.associationTargetId&&(d.associationTargets={[me]:[t.associationTargetId]}),l.push(X("FSN",a,i,s,"PREFERRED",!1)),c.descriptions=l,null)})}async function _e(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 C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(a=>a.axiomId===t.axiomId);return s?(s.relationships=t.relationships,t.active!=null&&(s.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Xt(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 C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===t.axiomId);return s?(s.relationships=t.relationships,t.active!=null&&(s.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Zt(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."}};if(t.definitionStatus&&t.definitionStatus!=="PRIMITIVE"&&t.definitionStatus!=="FULLY_DEFINED")return{statusCode:400,body:{error:"definitionStatus must be PRIMITIVE or FULLY_DEFINED."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n);return R(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[];return a.push({axiomId:Le.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:i,relationships:t.relationships}),s.classAxioms=a,null})}async function eo(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 C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n);return R(e,o,t.conceptId,s=>{let a=Array.isArray(s.gciAxioms)?s.gciAxioms:[];return a.push({axiomId:Le.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:i,relationships:t.relationships}),s.gciAxioms=a,null})}async function to(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.classAxioms)?o.classAxioms:[],s=i.findIndex(a=>a.axiomId===t.axiomId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-axiom instead.`}}:i.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:(i.splice(s,1),o.classAxioms=i,null)}):{statusCode:400,body:{error:n.error}}}async function oo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.classAxioms)?o.classAxioms:[],s=i.find(c=>c.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};if(s.active===!1)return{statusCode:409,body:{error:`Axiom ${t.axiomId} is already inactive.`}};if(s.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-axiom).`}};let a=i.filter(c=>c!==s&&c.active!==!1);return a.length===0?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:a.every(c=>c.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished class axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-axiom to edit ${t.axiomId}'s content in place instead.`}}:(s.active=!1,null)}):{statusCode:400,body:{error:n.error}}}var Qr="116680003";function Nt(e,t){let r={active:!0,groupId:t,type:{conceptId:e.type?.id}};return e.concrete?r.concreteValue={dataType:e.value?.dataType,value:e.value?.value}:r.target={conceptId:e.target?.id},r}function zr(e){let t=[],r=Array.isArray(e.concepts)?e.concepts:[];for(let i of r)i?.id&&t.push({active:!0,groupId:0,type:{conceptId:Qr},target:{conceptId:i.id}});let n=Array.isArray(e.attributes)?e.attributes:[];for(let i of n)t.push(Nt(i,0));return(Array.isArray(e.groups)?e.groups:[]).forEach((i,s)=>{let a=Array.isArray(i.attributes)?i.attributes:[];for(let c of a)t.push(Nt(c,s+1))}),t}async function no(e,t,r,n){let o=A(e),i=await I(`${o}/browser/${t.branchPath}/concepts/${r}`,{cookie:e.cookie});if(i.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{ok:!1,result:{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:i.body,undetermined:!0}}};let s=Array.isArray(i.body.classAxioms)?i.body.classAxioms:[],a;if(n){if(a=s.find(c=>c.axiomId===n),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${n}.`,undetermined:!0}}}}else{let c=s.filter(l=>l.active!==!1);if(c.length===0)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has no active class axiom.`,undetermined:!0}}};if(c.length>1)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has ${c.length} active class axioms \u2014 pass axiomId to pick which one.`,undetermined:!0}}};a=c[0]}return{ok:!0,value:{axiom:a,axiomId:a.axiomId}}}var Xr="116680003";function Zr(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==Xr?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function ei(e,t,r){let n=A(e),o=await I(`${n}/${t.branchPath}/concepts/${r}/authoring-form`,{cookie:e.cookie,timeoutMs:6e4});if(o.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(o.statusCode<200||o.statusCode>=300||!o.body)return{ok:!1,result:{statusCode:o.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:o.body,undetermined:!0}}};let i=zr(o.body);return i.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.`,undetermined:!0}}}:{ok:!0,value:i}}async function ti(e,t,r,n){let o=await no(e,t,r,n);if(!o.ok)return o;let i=await ei(e,t,r);return i.ok?{ok:!0,value:{axiom:o.value.axiom,axiomId:o.value.axiomId,targetRelationships:i.value}}:i}function oi(e){let t=typeof e.typeId=="string"?e.typeId:e.type?.conceptId,r=e.concreteValue;if(r)return`${t}=#${r.dataType}:${r.value}`;let n=typeof e.destinationId=="string"?e.destinationId:e.target?.conceptId;return`${t}=${n}`}function Dt(e){let t=new Map;for(let o of e){if(o.active===!1)continue;let i=typeof o.groupId=="number"?o.groupId:0,s=t.get(i)??[];s.push(oi(o)),t.set(i,s)}let r=(t.get(0)??[]).slice().sort(),n=[];for(let[o,i]of t)o!==0&&n.push(i.slice().sort());return{ungrouped:r,groups:n}}function ni(e,t){let r=Dt(e),n=Dt(t);if(r.ungrouped.join("|")!==n.ungrouped.join("|"))return!1;let o=r.groups.map(s=>s.join("|")).sort(),i=n.groups.map(s=>s.join("|")).sort();return o.join("||")===i.join("||")}async function fe(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await ti(e,n,t.conceptId,t.axiomId);if(!o.ok)return o.result;let{axiom:i,axiomId:s,targetRelationships:a}=o.value,c=Array.isArray(i.relationships)?i.relationships:[];return ni(c,a)?(e.onLog?.(`[${new Date().toISOString()}] transform-axiom ${n.projectKey}/${n.taskKey}: already conforms \u2014 ${t.conceptId}`),{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,alreadyConformed:!0}}):_e(e,{conceptId:t.conceptId,axiomId:s,relationships:a,projectKey:n.projectKey,taskKey:n.taskKey},r)}async function ge(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await no(e,n,t.conceptId,t.axiomId);if(!o.ok)return o.result;let{axiom:i,axiomId:s}=o.value,a=Array.isArray(i.relationships)?i.relationships:[];return Zr(a)?{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!0,conforms:!1}}:{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!1,message:"Stated Is-a targets are all primitive \u2014 this cannot rule out a missing/mismatched attribute. Run transform-axiom to get a definitive, self-fixing answer."}}}async function ro(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 C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(d=>d.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(s.relationships)?s.relationships:[],c=t.relationshipId?a.findIndex(d=>d.relationshipId===t.relationshipId):t.relationshipIndex,l=c>=0?a[c]:void 0;return l?l.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${c}`} has effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.splice(c,1),s.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 io(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 C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(d=>d.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(s.relationships)?s.relationships:[],c=Tt(a,t.attributes,t.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${t.axiomId} ${c.error}`}};let l=c.relationships.find(d=>d.effectiveTime!=null);return l?{statusCode:409,body:{error:`Role group (groupId ${c.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(l.relationshipId)}) with effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(s.relationships=a.filter(d=>(typeof d.groupId=="number"?d.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function so(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.gciAxioms)?o.gciAxioms:[],s=i.findIndex(a=>a.axiomId===t.axiomId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published GCI axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-gci-axiom instead.`}}:(i.splice(s,1),o.gciAxioms=i,null)}):{statusCode:400,body:{error:n.error}}}async function ao(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.gciAxioms)?o.gciAxioms:[],s=i.find(c=>c.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}};if(s.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished GCI axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-gci-axiom).`}};if(s.active===!1)return{statusCode:409,body:{error:`GCI axiom ${t.axiomId} is already inactive.`}};let a=i.filter(c=>c!==s&&c.active!==!1);return a.length>0&&a.every(c=>c.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating GCI axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished GCI axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-gci-axiom to edit ${t.axiomId}'s content in place instead.`}}:(s.active=!1,null)}):{statusCode:400,body:{error:n.error}}}var ri=8;async function ye(e,t,r,n){let o=[],i=[],s=0,a=async()=>{for(;;){let l=s++;if(l>=r.length)return;let d=r[l];try{let u=await ge(e,{conceptId:d.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),p=u.body;if(u.statusCode<200||u.statusCode>=300){i.push({...d,error:p?.error??`HTTP ${u.statusCode}`});continue}p?.conclusive&&o.push({...d,axiomId:p.axiomId})}catch(u){i.push({...d,error:u instanceof Error?u.message:String(u)})}}},c=Math.min(ri,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:o,skipped:i}}async function co(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await ue(e,{...t,branchPath:n.branchPath},r);if(o.statusCode<200||o.statusCode>=300)return o;let i=o.body?.items??[],s=i.map(l=>({conceptId:l.conceptId,fsn:l.fsn,pt:l.pt})),{matched:a,skipped:c}=await ye(e,n,s,r);return{statusCode:200,body:{branchPath:n.branchPath,totalSearched:i.length,matched:a.length,skipped:c.length,results:a,skippedConcepts:c}}}async function lo(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(e),i=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};if(s.body.effectiveTime!=null)return{statusCode:409,body:{error:`Published concept ${t.conceptId} cannot be deleted \u2014 use inactivate-concept instead.`}};let a=`${o}/${n.branchPath}/concepts/${t.conceptId}`,c=await I(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 ii(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 he(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(e),i=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};let a=q(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,l=await I(c,{method:"POST",body:Me(s.body),cookie:e.cookie});if(l.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(l.statusCode<200||l.statusCode>=300)return{statusCode:l.statusCode,body:{error:"Validation check failed.",details:l.body}};let d=Array.isArray(l.body)?ii(l.body):[];return{statusCode:200,body:{conceptId:t.conceptId,validationResults:d,hasErrors:d.some(u=>u.severity==="ERROR"),hasWarnings:d.some(u=>u.severity==="WARNING")}}}var uo=200;async function si(e,t,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${A(e)}/browser/${t}/concepts/bulk-load`,i=!0;for(let s=0;s<r.length;s+=uo){let a=r.slice(s,s+uo),c=await I(o,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){i=!1;continue}for(let l of c.body)n.set(l.conceptId,{fsn:l.fsn?.term,pt:l.pt?.term})}return{terms:n,resolved:i}}async function L(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=[],i=0;for(;;){let k=`${kt(e)}/activities?size=500&page=${i}&onBranch=${encodeURIComponent(n.branchPath)}`,h=await I(k,{cookie:e.cookie});if(h.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(h.statusCode===404)return{statusCode:200,body:{branchPath:n.branchPath,concepts:[],conceptsClassified:[]}};if(h.statusCode<200||h.statusCode>=300)return{statusCode:h.statusCode,body:{error:"Could not fetch traceability for branch.",details:h.body}};o.push(...h.body?.content??[]);let b=h.body?.totalPages??1;if(h.body?.last!==!1||i+1>=b)break;i+=1}let s=new Map,a=new Map,c=(k,h,b,w)=>{let j=k.get(h);j?(w.forEach(P=>P&&j.componentSubTypes.add(P)),j.lastUpdatedTime=b):k.set(h,{conceptId:h,lastUpdatedTime:b,componentSubTypes:new Set(w.filter(P=>!!P))})};for(let k of o)if(!(k.activityType!=="CONTENT_CHANGE"&&k.activityType!=="CLASSIFICATION_SAVE"))for(let h of k.conceptChanges??[]){let b=String(h.conceptId),w=h.componentChanges??[],j=w.map(O=>O.componentSubType);if(k.activityType==="CLASSIFICATION_SAVE"){c(a,b,k.commitDate,j);continue}let P=w.some(O=>O.componentSubType!=="INFERRED_RELATIONSHIP");c(P?s:a,b,k.commitDate,j)}for(let k of s.keys())a.delete(k);let l=[...new Set([...s.keys(),...a.keys()])],{terms:d,resolved:u}=await si(e,n.branchPath,l),p=k=>[...k.values()].sort((h,b)=>(b.lastUpdatedTime??"").localeCompare(h.lastUpdatedTime??"")).map(h=>{let b=u&&!d.has(h.conceptId);return{conceptId:h.conceptId,fsn:d.get(h.conceptId)?.fsn,pt:d.get(h.conceptId)?.pt,...b?{deleted:!0}:{},lastUpdatedTime:h.lastUpdatedTime,changedComponentTypes:[...h.componentSubTypes]}}),g=p(s),y=p(a);return{statusCode:200,body:{branchPath:n.branchPath,...u?{summary:{concepts:g.length,conceptsDeleted:g.filter(k=>k.deleted).length,conceptsClassified:y.length}}:{},concepts:g,conceptsClassified:y}}}async function po(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await L(e,t,r);if(o.statusCode<200||o.statusCode>=300){let d=o.body;return{statusCode:o.statusCode,body:{error:d.error??"Could not list concepts for review."}}}let i=o.body.concepts??[],s=i.filter(d=>!d.deleted),a=s.map(d=>({conceptId:d.conceptId,fsn:d.fsn})),{matched:c,skipped:l}=await ye(e,n,a,r);return{statusCode:200,body:{branchPath:n.branchPath,totalReviewed:s.length,matched:c.length,skipped:l.length,skippedDeleted:i.length-s.length,results:c,skippedConcepts:l}}}async function ai(e,t,r,n){let o=[];for(let i of r){if(i.deleted){o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"deleted"});continue}let s=await he(e,{conceptId:i.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),a=s.body;if(s.statusCode<200||s.statusCode>=300){o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"failed",error:a.error??`HTTP ${s.statusCode}`});continue}let c=a.validationResults??[];o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:c.length===0?"clean":"issues",validationResults:c.length?c:void 0,hasErrors:a.hasErrors})}return o}async function mo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await L(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 i=o.body.concepts??[],s=await ai(e,n,i,r),a=c=>s.filter(l=>l.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:s.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:s}}}async function K(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body??null}var Ue=new Set;function fo(e){if(!(!e||typeof e!="object"))for(let t of Ue)t(e)}function ci(e){return Ue.add(e),()=>Ue.delete(e)}function di(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 ke(e){let t=()=>{};return{promise:new Promise(n=>{t=ci(o=>{di(o,e)&&(t(),n(o))})}),cancel:t}}var Je=["RUNNING","BUILDING","SCHEDULED","QUEUED"],He=["QUEUED","SCHEDULED","RUNNING"],li=["Promoted","Completed"],go=5e3;function Ge(e){return new Promise(t=>setTimeout(t,e))}async function ui(e,t,r){let n=0;for(;;){let{done:o,value:i}=await e();if(o)return{value:i,timedOut:!1};if(n>=r)return{value:i,timedOut:!0};n++,await Ge(t)}}function pi(){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 mi=pi(),fi=180;function gi(){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 yi=gi(),hi=900;async function ko(e,t,r,n,o){let i=r*1e3,s=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],l=n?ke(n):void 0,d=await Promise.race(l?[Ge(c).then(()=>{}),l.promise]:[Ge(c).then(()=>{})]);if(l?.cancel(),d){let g=d.event;o?.(`[${new Date().toISOString()}] woken by notification${g?`: ${g}`:""}`)}let{done:u,value:p}=await e();if(u)return{value:p,timedOut:!1};if(Date.now()-s>=i)return{value:p,timedOut:!0};a++}}async function Co(e,t,r){let n=await K(e,t,r);if(!n)return{error:`Could not fetch task ${t}/${r}.`};if(n.status&&li.includes(n.status))return{error:`Task ${t}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${E(e)}/projects/${t}/tasks/${r}`;await I(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function Ye(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await I(n,{method:"POST",body:{},cookie:e.cookie}),(await K(e,t,r))?.latestClassificationJson}async function yo(e,t,r,n,o){let i,{value:s,timedOut:a}=await ko(async()=>{let l=(await Ye(e,t,r))?.status;return l!==i&&(i=l,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${l??"unknown"}`)),{done:!(!l||Je.includes(l)),value:l}},mi,o,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:s,timedOut:a}}async function Ve(e,t,r){let n=`${A(e)}/${t}/classifications`,o=await I(n,{cookie:e.cookie});if(o.body?.items?.length)return o.body.items.find(i=>i.id===r)??o.body.items[o.body.items.length-1]}async function Io(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i}=n,s=await Ye(e,o,i);return s?{statusCode:200,body:{hasClassification:!0,jobId:s.id,status:s.status,running:Je.includes(s.status),latestClassificationJson:s}}:{statusCode:200,body:{hasClassification:!1}}}async function Ce(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=await Co(e,o,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??fi,l=await Ye(e,o,i),d=l?.status,u=l?.id;if(u&&d&&Je.includes(d)){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: found job ${u} already ${d} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:P}=await yo(e,o,i,s,c),O=await Ve(e,s,u),_={accepted:!1};return!P&&j==="COMPLETED"&&(_=await qe(e,s,o,i,u)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: attached job ${u} final status ${j??"unknown"}${P?" (timed out waiting)":""}, save ${JSON.stringify(_)}`),{statusCode:200,body:{jobId:u,finalStatus:j,timedOut:P,details:O,save:_,attachedToExisting:!0}}}if(u&&d==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: found job ${u} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await Ve(e,s,u),P=await qe(e,s,o,i,u);return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: accepted existing job ${u}, save ${JSON.stringify(P)}`),{statusCode:200,body:{jobId:u,finalStatus:"COMPLETED",timedOut:!1,details:j,save:P,acceptedExisting:!0}}}let p=`${E(e)}/projects/${o}/tasks/${i}/classifications`,g=await I(p,{method:"POST",body:{},cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!g.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: 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}};e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: started (${g.body.status??"unknown"})`);let y=g.body.id;if(!t.wait)return{statusCode:200,body:{jobId:y,status:g.body.status}};let{finalStatus:k,timedOut:h}=await yo(e,o,i,s,c),b=await Ve(e,s,y),w={accepted:!1};return!h&&k==="COMPLETED"&&(w=await qe(e,s,o,i,y)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: final status ${k??"unknown"}${h?" (timed out waiting)":""}, save ${JSON.stringify(w)}`),{statusCode:200,body:{jobId:y,finalStatus:k,timedOut:h,details:b,save:w}}}var ki=["SAVED","STALE","SAVE_FAILED"],Ci=120;async function qe(e,t,r,n,o){let i=`${A(e)}/${t}/classifications/${o}`,s=await I(i,{method:"PUT",body:{status:"SAVED"},cookie:e.cookie});if(s.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(s.statusCode<200||s.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${s.statusCode}).`};let a=Math.ceil(Ci*1e3/go),{value:c,timedOut:l}=await ui(async()=>{let u=(await I(i,{cookie:e.cookie})).body?.status;return{done:!!u&&ki.includes(u),value:u}},go,a);return l?{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 xo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i}=n,a=(await K(e,o,i))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&He.includes(a)}}}async function ho(e,t,r,n,o){let i,{value:s,timedOut:a}=await ko(async()=>{let l=(await K(e,t,r))?.latestValidationStatus;return l!==i&&(i=l,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${l??"unknown"}`)),{done:!(!l||He.includes(l)),value:l}},yi,o,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:s,timedOut:a}}async function bo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=await Co(e,o,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??hi,d=(await K(e,o,i))?.latestValidationStatus;if(d&&He.includes(d)){e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: validation already ${d} \u2014 waiting on it instead of starting a new one`);let{finalStatus:k,timedOut:h}=await ho(e,o,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: attached run final status ${k??"unknown"}${h?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:k,timedOut:h,attachedToExisting:!0}}}let u=`${E(e)}/projects/${o}/tasks/${i}/validation`;typeof t.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let p=await I(u,{method:"POST",body:{},cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(p.statusCode<200||p.statusCode>=300)return{statusCode:p.statusCode,body:{error:"Failed to start validation.",details:p.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:g,timedOut:y}=await ho(e,o,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: final status ${g??"unknown"}${y?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:g,timedOut:y}}}var Ii=8;function xi(e){return typeof e=="string"&&/timed out after \d+ms/.test(e)}async function So(e,t,r,n,o,i){let s=0,a=0,c=async()=>{for(;;){let d=a++;if(d>=r.length)return;let u=r[d];try{let p=await fe(e,{conceptId:u.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),g=p.body;p.statusCode<200||p.statusCode>=300?g?.undetermined?n.set(u.conceptId,{outcome:"skipped",error:g.error??`HTTP ${p.statusCode}`}):n.set(u.conceptId,{outcome:"failed",error:g?.error??`HTTP ${p.statusCode}`}):n.set(u.conceptId,{outcome:g?.alreadyConformed?"conformed":"transformed"})}catch(p){n.set(u.conceptId,{outcome:"failed",error:p instanceof Error?p.message:String(p)})}s+=1,e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: ${i} \u2014 ${u.conceptId} (${s}/${r.length})`)}},l=Math.min(Ii,r.length);await Promise.all(Array.from({length:l},()=>c()))}async function bi(e,t,r,n){let o=new Map;return await So(e,t,r,o,n,"axiom checked"),await Si(e,t,r,o,n),o}async function Si(e,t,r,n,o){let i=r.filter(s=>{let a=n.get(s.conceptId);return a?.outcome==="failed"&&xi(a.error)});i.length!==0&&(e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: reprocessing ${i.length} concept(s) that timed out on the first pass`),await So(e,t,i,n,o,"axiom rechecked"))}async function vo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await Ce(e,{projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath,wait:!0},r);if(o.statusCode===401)return o;let i=o.body,s=o.statusCode>=200&&o.statusCode<300?{jobId:i?.jobId,finalStatus:i?.finalStatus,timedOut:i?.timedOut,save:i?.save}:{error:i?.error??`HTTP ${o.statusCode}`},a=await L(e,t,r);if(a.statusCode<200||a.statusCode>=300){let y=a.body;return{statusCode:a.statusCode,body:{error:y.error??"Could not list concepts for review."}}}let c=a.body.concepts??[],l=c.filter(y=>!y.deleted).map(y=>({conceptId:y.conceptId,fsn:y.fsn})),d=await bi(e,n,l,r),u=[];for(let[y,k]of c.entries()){if(k.deleted){u.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"deleted"});continue}let h=d.get(k.conceptId),b=await le(e,{conceptId:k.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),w=b.body,j=`(${y+1}/${c.length})`;if(b.statusCode<200||b.statusCode>=300){e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: FAILED (${b.statusCode}) \u2014 ${k.conceptId} ${j}`),u.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"failed",error:w?.error??`HTTP ${b.statusCode}`,axiom:h});continue}e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: OK \u2014 ${k.conceptId} ${j}`),u.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"fetched",concept:b.body,axiom:h})}let p=y=>u.filter(k=>k.outcome===y).length,g=y=>Array.from(d.values()).filter(k=>k.outcome===y).length;return{statusCode:200,body:{branchPath:n.branchPath,classification:s,summary:{total:u.length,fetched:p("fetched"),skippedDeleted:p("deleted"),failed:p("failed"),axiomsTransformed:g("transformed"),axiomsConformed:g("conformed"),axiomsSkipped:g("skipped"),axiomsFailed:g("failed")},concepts:u}}}async function To(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",n=`${E(e)}/projects${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function Ao(e,t){let r=`${E(e)}/projects/${t}/tasks`;return(await I(r,{cookie:e.cookie})).body??[]}async function Ro(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",n=`${E(e)}/projects/my-tasks${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function wo(e,t){let r=`${E(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 I(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}}async function Eo(e,t){let r=`${E(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,n=await I(r,{cookie:e.cookie});return Array.isArray(n.body)?n.body:[]}var vi="IN_PROGRESS";async function $o(e,t){let r=`${E(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await I(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 I(r,{method:"PUT",body:{status:vi},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 jo(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 We(e){return JSON.stringify([e])}function Po(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 Qe(e,t={},r=""){let n=Object.entries(t).map(([o,i])=>`${o}:${i}`);return[e,...n,"",r].join(`
3
- `)+"\0"}function No(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
2
+ "use strict";var jr=Object.create;var le=Object.defineProperty;var Pr=Object.getOwnPropertyDescriptor;var Nr=Object.getOwnPropertyNames;var Dr=Object.getPrototypeOf,Or=Object.prototype.hasOwnProperty;var Fr=(e,t)=>{for(var r in t)le(e,r,{get:t[r],enumerable:!0})},St=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Nr(t))!Or.call(e,o)&&o!==r&&le(e,o,{get:()=>t[o],enumerable:!(n=Pr(t,o))||n.enumerable});return e};var T=(e,t,r)=>(r=e!=null?jr(Dr(e)):{},St(t||!e||!e.__esModule?le(r,"default",{value:e,enumerable:!0}):r,e)),Lr=e=>St(le({},"__esModule",{value:!0}),e);var Cs={};Fr(Cs,{COMMANDS:()=>bt,main:()=>$r,parsePositionals:()=>wr});module.exports=Lr(Cs);var U={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"}},Kr={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},pe=Object.keys(U);function vt(e){return Kr[e.trim().toLowerCase()]??null}var z="uat",xs=U.uat.imsEndpoint,bs=U.uat.terminologyServerEndpoint,Ss=U.uat.authoringServicesEndpoint;var Mr=T(require("http")),Br=T(require("https"));function I(e,t={}){let{method:r="GET",cookie:n,body:o,headers:i={},timeoutMs:s=15e3}=t;return new Promise((a,c)=>{let u;try{u=new URL(e)}catch(h){c(h);return}let d=u.protocol==="https:"?Br:Mr,l=o!==void 0?JSON.stringify(o):void 0,p={accept:"application/json",...i};if(l!==void 0&&(p["content-type"]="application/json",p["content-length"]=String(Buffer.byteLength(l))),n){let h=n.replace(/[^\x20-\x7e\t]/g,"");h&&(p.cookie=h)}let g=!1,y=d.request({hostname:u.hostname,port:u.port||void 0,path:u.pathname+u.search,method:r,headers:p},h=>{let b="";h.on("data",w=>{b+=w}),h.on("end",()=>{if(g)return;g=!0,clearTimeout(k);let w=h.statusCode??0,P=(h.headers["content-type"]??"").includes("application/json"),O=null,_=!1;if(b)try{O=JSON.parse(b)}catch{_=!P}a({statusCode:w,body:O,rawBody:b,sessionExpired:_})})});y.on("error",h=>{g||(g=!0,clearTimeout(k),c(h))});let k=setTimeout(()=>{g||(g=!0,y.destroy(),c(new Error(`Request to ${e} timed out after ${s}ms`)))},s);l!==void 0&&y.write(l),y.end()})}var F="900000000000509007",V="900000000000508004";var Tt={[F]:"en-us",[V]:"en-gb"},At={[F]:"true",[V]:"true"},_r={},Ur={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:Tt,dialectDefaults:At,readOnlyDialects:_r,defaultLanguage:"en"};function Rt(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return Ur;let t={[F]:"en-us"},r={},n={},o=[];for(let c of Object.keys(e)){let u=c.match(/^requiredLanguageRefset\.(.+)/);if(u){let d=u[1];t[String(e[c])]=d,o.length===0&&o.push(d)}}let i=e.requiredLanguageRefsets;if(Array.isArray(i))for(let c of i){if(typeof c!="object"||c===null)continue;let u=null,d=null;for(let[y,k]of Object.entries(c))y.length===2&&(u=y,d=String(k));if(!u||!d)continue;let l=c.dialectName;t[d]=typeof l=="string"?l:u;let p=c.default;p==="true"&&!o.includes(u)&&o.push(u),p!=null&&(r[d]=String(p));let g=c.readOnly;g!=null&&(n[d]=String(g))}let s=e.optionalLanguageRefsets;if(Array.isArray(s))for(let c of s)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?Tt:t,dialectDefaults:a?At:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function _e(e,t,r,n){let o={};for(let i of Object.keys(e.dialects)){let s=e.dialects[i];e.isExtension&&!r?s.includes(n)?o[i]="PREFERRED":s.includes(e.defaultLanguage)&&(o[i]="ACCEPTABLE"):s.includes(n)&&(o[i]=t),e.dialectDefaults[i]==="false"&&!r&&delete o[i],e.readOnlyDialects[i]==="true"&&delete o[i]}return o}function me(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[F]:"PREFERRED"}:_e(e,"PREFERRED",t,"en")}var Vr="900000000000207008";function wt(e){return e.replace(/\/$/,"")}function A(e){return wt(e.terminologyServerEndpoint)}function E(e){return wt(e.authoringServicesEndpoint)}function Et(e){return`${new URL(E(e)).origin}/authoring-traceability-service`}function q(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function C(e,t,r){let n=t.projectKey||r?.projectKey,o=t.taskKey||r?.taskKey,i=!t.projectKey&&!t.taskKey,s=t.branchPath||(i?r?.branchPath:void 0);return!n||!o?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(s||(s=await qr(e,n,o)??void 0),s?{ok:!0,projectKey:n,taskKey:o,branchPath:s}:{ok:!1,error:`Could not resolve branch path for ${n}/${o}.`})}async function J(e,t){let r=A(e),n=await I(`${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),i=o[o.length-1],s=o.slice(0,-1).join("/");if(!i||!s)return{ok:!1,error:`Cannot create branch from path "${t}" \u2014 expected a parent and a name.`};let a=await I(`${r}/branches`,{method:"POST",body:{parent:s,name:i},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 qr(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body?.branchPath??null}async function $t(e,t,r){let n=r?.get(t);if(n)return n;let o=`${E(e)}/projects/${t}`,s=(await I(o,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,s),s}async function M(e,t,r){let n=await $t(e,t,r),o=n.multipleModuleEditingDisabled,i=!o||o==="false";return n.expectedExtensionModules?.length&&i?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:Vr}async function G(e,t,r){let n=await $t(e,t,r);return Rt(n)}async function Ue(e,t){let r=e.replace(/\/$/,"")+"/auth",n=await I(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 jt=T(require("crypto"));var Jr="116680003";function Z(e,t,r,n,o="PREFERRED",i=!1){let s=e==="FSN"?me(n,i):_e(n,o,i,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:s}}async function Pt(e,t,r,n=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:i,taskKey:s,branchPath:a}=o,c=q(a),u=t.moduleId||await M(e,i,n),d=await G(e,i,n),l=t.preferredTerm||t.fsn,p=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,g={conceptId:null,moduleId:u,definitionStatus:"PRIMITIVE",active:!0,descriptions:[Z("FSN",p,u,d,"PREFERRED",!0),Z("SYNONYM",l,u,d,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:jt.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:u,relationships:[{active:!0,groupId:0,type:{conceptId:Jr},target:{conceptId:t.parentConceptId}}]}]},y=`${A(e)}/browser/${c}/${i}/${s}/concepts/?validate=true`,k=await I(y,{method:"POST",body:g,cookie:e.cookie});if(k.sessionExpired){let w="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${i}/${s}: SESSION EXPIRED`),{statusCode:401,body:{error:w}}}let h=k.body,b=h&&"conceptId"in h?h.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${i}/${s}: ${k.statusCode<300?"OK":"FAILED ("+k.statusCode+")"} \u2014 ${p}`+(b?` \u2192 ${b}`:"")),typeof b=="string"&&e.onValidationResults?.(b,h?.validationResults),{statusCode:k.statusCode,body:k.body}}var Gr=["descriptions","descriptionFull","axioms","inferred","gci","gciAxiomsCount","full"],Hr={descriptions:"--descriptions",descriptionFull:"--description-full",axioms:"--axioms",inferred:"--inferred",gci:"--gci",gciAxiomsCount:"--gci-axioms-count",full:"--full"};function Yr(e,t){return(Array.isArray(e[t])?e[t]:[]).filter(n=>n.active!==!1).length}function Nt(e,t){return(Array.isArray(e.relationships)?e.relationships:[]).filter(n=>n.characteristicType===t)}function ee(e){return{conceptId:e.conceptId,fsn:e.fsn,pt:e.pt,active:e.active,definitionStatus:e.definitionStatus}}function te(e){return typeof e=="object"&&e!==null}function Wr(e,t,r){let n=Array.isArray(e[r])?e[r]:[],o=[];for(let i of n){if(i.active===!1||typeof i.axiomId!="string")continue;(Array.isArray(i.relationships)?i.relationships:[]).forEach((a,c)=>{let u=a.type;if((te(u)?u.conceptId:void 0)!==t)return;let l=a.target;o.push({axiomId:i.axiomId,relationshipId:typeof a.relationshipId=="string"?a.relationshipId:void 0,relationshipIndex:c,groupId:typeof a.groupId=="number"?a.groupId:0,targetId:te(l)?l.conceptId:void 0,targetFsn:te(l)&&te(l.fsn)?l.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return o}async function fe(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};if(!t.attributeType){let a=Gr.filter(c=>t[c]);if(a.length>1)return{statusCode:400,body:{error:`Specify only one of ${a.map(c=>Hr[c]).join(", ")}.`}}}if(!t.attributeType&&!t.descriptions&&!t.descriptionFull&&!t.axioms&&!t.inferred&&!t.gci&&!t.gciAxiomsCount&&!t.full){let a=`${A(e)}/${n.branchPath}/concepts/${t.conceptId}`,c=await I(a,{cookie:e.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:c.statusCode,body:c.body}}let o=`${A(e)}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await I(o,{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||!te(i.body))return{statusCode:i.statusCode,body:i.body};let s=i.body;if(t.attributeType){let a=t.gci?"gciAxioms":"classAxioms",c=Wr(s,t.attributeType,a);return{statusCode:i.statusCode,body:{conceptId:t.conceptId,attributeType:t.attributeType,gci:!!t.gci,matches:c}}}if(t.descriptions){let a=Array.isArray(s.descriptions)?s.descriptions.filter(c=>c.active!==!1):[];return{statusCode:i.statusCode,body:{...ee(s),descriptions:a}}}return t.descriptionFull?{statusCode:i.statusCode,body:{...ee(s),descriptions:s.descriptions??[]}}:t.axioms?{statusCode:i.statusCode,body:{...ee(s),classAxioms:s.classAxioms??[],relationships:Nt(s,"STATED_RELATIONSHIP")}}:t.inferred?{statusCode:i.statusCode,body:{...ee(s),relationships:Nt(s,"INFERRED_RELATIONSHIP")}}:t.gci?{statusCode:i.statusCode,body:{...ee(s),gciAxioms:s.gciAxioms??[]}}:t.gciAxiomsCount?{statusCode:i.statusCode,body:{conceptId:s.conceptId,gciAxiomsCount:Yr(s,"gciAxioms")}}:{statusCode:i.statusCode,body:s}}var Xr=500,Qr=1e4;async function ge(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o={expand:"fsn()"};t.term&&(o.termFilter=t.term),t.ecl&&(o.eclFilter=t.ecl),typeof t.active=="boolean"&&(o.activeFilter=t.active);let i=`${A(e)}/${n.branchPath}/concepts/search`,s=d=>({conceptId:d.conceptId,fsn:d.fsn?.term,pt:d.pt?.term,active:d.active,moduleId:d.moduleId});if(t.limit!==void 0){let d=await I(i,{method:"POST",body:{...o,limit:t.limit},cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let l=(d.body?.items??[]).map(s);return{statusCode:d.statusCode,body:{total:d.body?.total??l.length,items:l}}}let a=[],c=0,u=0;for(;;){let d=Math.min(Xr,Qr-u);if(d<=0)break;let l=await I(i,{method:"POST",body:{...o,limit:d,offset:u},cookie:e.cookie});if(l.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(l.statusCode<200||l.statusCode>=300)return{statusCode:l.statusCode,body:l.body??{error:"Concept search failed."}};let p=l.body?.items??[];if(a.push(...p.map(s)),c=l.body?.total??a.length,u+=p.length,p.length===0||u>=c)break}return{statusCode:200,body:{total:c,items:a,...a.length<c?{truncated:!0,message:`Only ${a.length} of ${c} matches returned \u2014 Snowstorm caps unsorted search at offset+limit 10,000. Narrow the query (--term/--ecl/--active) to see the rest.`}:{}}}}var oe=1e3;function zr(e){let t=new Map;for(let r of e)for(let n of r){let o=n.referenceType?.conceptId??"",i=t.get(o);i?i.referencingConcepts=[...i.referencingConcepts??[],...n.referencingConcepts??[]]:t.set(o,{...n,referencingConcepts:[...n.referencingConcepts??[]]})}return[...t.values()]}async function Dt(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${A(e)}/${n.branchPath}/concepts/${t.conceptId}/references`,i=(d,l)=>{let p=new URLSearchParams;return typeof t.stated=="boolean"&&p.set("stated",String(t.stated)),p.set("limit",String(d)),p.set("offset",String(l)),I(`${o}?${p.toString()}`,{cookie:e.cookie})};if(typeof t.limit=="number"||typeof t.offset=="number"){let d=await i(t.limit??oe,t.offset??0);return d.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:d.statusCode,body:d.body}}let s=[],a=0,c=0,u=0;for(;;){let d=await i(oe,u);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:d.body??{error:"Could not fetch references."}};let l=d.body?.referencesByType??[];s.push(l),a=d.body?.total??a;let p=l.reduce((g,y)=>g+(y.referencingConcepts?.length??0),0);if(c+=p,p===0||p<oe||c>=a)break;u+=oe}return{statusCode:200,body:{total:a,limit:oe,offset:0,referencesByType:zr(s)}}}var Je=T(require("crypto"));function Ot(e){return typeof e=="object"&&e!==null}function Zr(e){let t=e.type,r=e.target,n=Ot(t)?t.conceptId:void 0,o=Ot(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function ei(e,t){let r=[...t];for(let n of e){let o=r.findIndex(i=>i.typeId===n.typeId&&i.targetId===n.targetId);if(o===-1)return!1;r.splice(o,1)}return!0}function Ft(e,t,r){let n=new Map;for(let s of e){let a=typeof s.groupId=="number"?s.groupId:0,c=n.get(a);c?c.push(s):n.set(a,[s])}let o=[];for(let[s,a]of n){if(r!=null?s!==r:s===0)continue;let c=a.map(Zr).filter(u=>u!=null);ei(t,c)&&o.push(s)}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 i=o[0];return{ok:!0,groupId:i,relationships:n.get(i)}}var ti=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],oi=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],ni=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],ri=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],ii=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],Ge=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function Gt(e){return Ge.includes(e)}function ne(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function ye(e){return typeof e=="object"&&e!==null}function Lt(e){return ye(e)?ne(e,ri):e}function Ht(e){if(!ye(e))return e;let t=ne(e,ni);return"type"in t&&(t.type=Lt(t.type)),"target"in t&&(t.target=Lt(t.target)),t}function si(e){return ye(e)?ne(e,oi):e}function Kt(e){if(!ye(e))return e;let t=ne(e,ii);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(Ht)),t}function He(e){let t=ne(e,ti);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(si)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(Ht)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(Kt)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(Kt)),t}function ai(e){return new Promise(t=>setTimeout(t,e))}function ci(e){if(e.statusCode!==400)return!1;let t=e.body;return t?.error==="BAD_REQUEST"&&typeof t.message=="string"&&t.message.includes("is already locked")}var Ve=[300,600,1200,2400,4800],Mt=new Map;function di(e,t){let n=(Mt.get(e)??Promise.resolve()).then(t,t);return Mt.set(e,n.then(()=>{},()=>{})),n}async function R(e,t,r,n){try{return await di(t.branchPath,()=>ui(e,t,r,n))}catch(o){return{statusCode:500,body:{error:o instanceof Error?o.message:String(o)}}}}async function ui(e,t,r,n){for(let o=0;;o++){let i=A(e),s=`${i}/browser/${t.branchPath}/concepts/${r}`,a=await I(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:a.body}};let c=a.body,u=n(c);if(u)return u;let d=q(t.branchPath),l=`${i}/browser/${d}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,p=await I(l,{method:"PUT",body:He(c),cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(ci(p)&&o<Ve.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${o+1}/${Ve.length})`),await ai(Ve[o]);continue}e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${p.statusCode<300?"OK":"FAILED ("+p.statusCode+")"} \u2014 ${r}`);let g=p.body;return e.onValidationResults?.(r,g?.validationResults),{statusCode:p.statusCode,body:p.body}}}var Bt=["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&&!Bt.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${Bt.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n),s=await G(e,o.projectKey,n),a=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return R(e,o,t.conceptId,c=>{let u=Array.isArray(c.descriptions)?c.descriptions:[];return u.push(Z(t.type,a,i,s,t.acceptability??"ACCEPTABLE",!1)),c.descriptions=u,null})}async function Wt(e,t,r){if(!t.conceptId||!t.typeId||!t.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return R(e,n,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s[o];if(!a)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${s.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 Xt(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 C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return R(e,n,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s[o];return a?(a.definitionStatus=t.status,i.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${s.length}).`}}})}async function Qt(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>o.effectiveTime==null?{statusCode:409,body:{error:`Unpublished concept ${t.conceptId} cannot be inactivated \u2014 it should be deleted instead (use delete-concept).`}}:(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 zt(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&&!Gt(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Ge.join(", ")}.`}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?s.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(s.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(s.term=t.term),t.caseSignificance&&(s.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Zt(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!Gt(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Ge.join(", ")}.`}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?(s.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}var qe=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function _t(e){return qe.includes(e)}function eo(e){return e.us&&!_t(e.us)?{statusCode:400,body:{error:`us must be one of: ${qe.join(", ")}.`}}:e.gb&&!_t(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${qe.join(", ")}.`}}:null}function to(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.`}}:eo(e):{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function Ye(e,t,r){let n=e.find(i=>i.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[F]:o[F]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[V]:o[V]=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 oo(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=to(n);if(o)return o;let i=await C(e,t,r);return i.ok?R(e,i,t.conceptId,s=>{let a=Array.isArray(s.descriptions)?s.descriptions:[];return Ye(a,t.conceptId,n)}):{statusCode:400,body:{error:i.error}}}async function no(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 i=to(o);if(i)return i}let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.descriptions)?o.descriptions:[];for(let s of t.entries){let a=Ye(i,t.conceptId,s);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function ro(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.descriptions)?o.descriptions:[],s=i.findIndex(a=>a.descriptionId===t.descriptionId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published description ${t.descriptionId} cannot be deleted \u2014 use inactivate-description instead.`}}:(i.splice(s,1),o.descriptions=i,null)}):{statusCode:400,body:{error:n.error}}}var he="REFERS_TO";async function io(e,t,r){if(!t.conceptId||!t.descriptionId||!t.indicator)return{statusCode:400,body:{error:"conceptId, descriptionId, and indicator are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?s.effectiveTime==null?{statusCode:409,body:{error:`Unpublished description ${t.descriptionId} cannot be inactivated \u2014 it should be deleted instead (use delete-description).`}}:(s.active=!1,s.inactivationIndicator=t.indicator,s.acceptabilityMap={},t.associationTargetId&&(s.associationTargets={[he]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}function Ut(e,t,r){for(let n of e){if(n.descriptionId===t||n.active===!1||n.type!=="SYNONYM")continue;let o=n.acceptabilityMap;o?.[r]==="PREFERRED"&&(n.acceptabilityMap={...o,[r]:"ACCEPTABLE"})}}async function so(e,t,r,n=new Map){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},i=eo(o);if(i)return i;let s=!!(t.lang||t.us||t.gb),a=await C(e,t,r);if(!a.ok)return{statusCode:400,body:{error:a.error}};let c=await G(e,a.projectKey,n);return R(e,a,t.conceptId,u=>{let d=Array.isArray(u.descriptions)?u.descriptions:[],l=d.find(g=>g.descriptionId===t.descriptionId);if(!l)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(l.active!==!1)return{statusCode:409,body:{error:`Description ${t.descriptionId} is already active.`}};if(l.type==="FSN"){if(s)return{statusCode:400,body:{error:"lang/us/gb do not apply when restoring an FSN \u2014 it is always PREFERRED in every dialect the project uses."}};let g=d.filter(y=>y.type==="FSN"&&y.active!==!1&&y.descriptionId!==t.descriptionId);if(g.length>1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${g.length} other active FSNs \u2014 cannot restore unambiguously.`}};if(g.length===1){let y=g[0];if(y.effectiveTime==null)d.splice(d.indexOf(y),1);else{if(!t.indicator)return{statusCode:400,body:{error:`Restoring this FSN requires --indicator, to retire the concept's current active (published) FSN ${String(y.descriptionId)} in the same save.`}};y.active=!1,y.inactivationIndicator=t.indicator,y.acceptabilityMap={},t.associationTargetId&&(y.associationTargets={[he]:[t.associationTargetId]})}}return l.active=!0,delete l.inactivationIndicator,delete l.associationTargets,l.acceptabilityMap=me(c,!1),u.descriptions=d,null}if(!s)return{statusCode:400,body:{error:"At least one of lang, us, or gb is required to restore this description's acceptability."}};l.active=!0,delete l.inactivationIndicator,delete l.associationTargets;let p=Ye(d,t.conceptId,o);return p||(o.us==="PREFERRED"&&Ut(d,t.descriptionId,F),o.gb==="PREFERRED"&&Ut(d,t.descriptionId,V),null)})}var li="900000000000490003",Vt=["NOT_SEMANTICALLY_EQUIVALENT","OUTDATED","GRAMMATICAL_DESCRIPTION_ERROR","NONCONFORMANCE_TO_EDITORIAL_POLICY"];async function ao(e,t,r){if(!t.conceptId||!t.descriptionId||!t.reason)return{statusCode:400,body:{error:"conceptId, descriptionId, and reason are required."}};if(!Vt.includes(t.reason))return{statusCode:400,body:{error:`reason must be one of: ${Vt.join(", ")}.`}};if(t.reason==="NOT_SEMANTICALLY_EQUIVALENT"){if(!t.targetId)return{statusCode:400,body:{error:"reason NOT_SEMANTICALLY_EQUIVALENT requires --target-id \u2014 the concept this description actually belongs under."}}}else if(t.targetId)return{statusCode:400,body:{error:`--target-id only applies to reason NOT_SEMANTICALLY_EQUIVALENT (paired with a REFERS_TO association) \u2014 omit it for ${t.reason}.`}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=`${A(e)}/${n.branchPath}/members?referencedComponentId=${encodeURIComponent(t.descriptionId)}&referenceSet=${li}&active=true`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||500,body:{error:`Could not check description ${t.descriptionId}'s current inactivation reason.`,details:s.body}};let a=(s.body.items??[])[0];return a?.released===!0?{statusCode:409,body:{error:`Description ${t.descriptionId}'s inactivation reason has already been published (effectiveTime ${String(a.effectiveTime)}) and cannot be changed.`}}:R(e,n,t.conceptId,c=>{let d=(Array.isArray(c.descriptions)?c.descriptions:[]).find(l=>l.descriptionId===t.descriptionId);return d?d.active!==!1?{statusCode:409,body:{error:`Description ${t.descriptionId} is active \u2014 use inactivate-description to inactivate it with a reason.`}}:(d.inactivationIndicator=t.reason,t.reason==="NOT_SEMANTICALLY_EQUIVALENT"?d.associationTargets={[he]:[t.targetId]}:delete d.associationTargets,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function co(e,t,r,n=new Map){if(!t.conceptId||!t.term||!t.indicator)return{statusCode:400,body:{error:"conceptId, term, and indicator are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n),s=await G(e,o.projectKey,n),a=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return R(e,o,t.conceptId,c=>{let u=Array.isArray(c.descriptions)?c.descriptions:[],d;if(t.descriptionId){if(d=u.find(l=>l.descriptionId===t.descriptionId),!d)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(d.type!=="FSN")return{statusCode:400,body:{error:`Description ${t.descriptionId} is a ${String(d.type)}, not an FSN.`}}}else{let l=u.filter(p=>p.type==="FSN"&&p.active!==!1);if(l.length!==1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${l.length} active FSNs \u2014 pass --description-id to say which one to replace.`}};d=l[0]}return d.effectiveTime==null?{statusCode:409,body:{error:`Description ${String(d.descriptionId)} has no effectiveTime (never versioned) \u2014 use update-description instead.`}}:(d.active=!1,d.inactivationIndicator=t.indicator,d.acceptabilityMap={},t.associationTargetId&&(d.associationTargets={[he]:[t.associationTargetId]}),u.push(Z("FSN",a,i,s,"PREFERRED",!1)),c.descriptions=u,null)})}async function We(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 C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(a=>a.axiomId===t.axiomId);return s?(s.relationships=t.relationships,t.active!=null&&(s.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function uo(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 C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===t.axiomId);return s?(s.relationships=t.relationships,t.active!=null&&(s.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function lo(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."}};if(t.definitionStatus&&t.definitionStatus!=="PRIMITIVE"&&t.definitionStatus!=="FULLY_DEFINED")return{statusCode:400,body:{error:"definitionStatus must be PRIMITIVE or FULLY_DEFINED."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n);return R(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[];return a.push({axiomId:Je.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:i,relationships:t.relationships}),s.classAxioms=a,null})}async function po(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 C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await M(e,o.projectKey,n);return R(e,o,t.conceptId,s=>{let a=Array.isArray(s.gciAxioms)?s.gciAxioms:[];return a.push({axiomId:Je.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:i,relationships:t.relationships}),s.gciAxioms=a,null})}async function mo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.classAxioms)?o.classAxioms:[],s=i.findIndex(a=>a.axiomId===t.axiomId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-axiom instead.`}}:i.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:(i.splice(s,1),o.classAxioms=i,null)}):{statusCode:400,body:{error:n.error}}}async function fo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.classAxioms)?o.classAxioms:[],s=i.find(c=>c.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};if(s.active===!1)return{statusCode:409,body:{error:`Axiom ${t.axiomId} is already inactive.`}};if(s.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-axiom).`}};let a=i.filter(c=>c!==s&&c.active!==!1);return a.length===0?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:a.every(c=>c.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished class axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-axiom to edit ${t.axiomId}'s content in place instead.`}}:(s.active=!1,null)}):{statusCode:400,body:{error:n.error}}}var pi="116680003";function qt(e,t){let r={active:!0,groupId:t,type:{conceptId:e.type?.id}};return e.concrete?r.concreteValue={dataType:e.value?.dataType,value:e.value?.value}:r.target={conceptId:e.target?.id},r}function mi(e){let t=[],r=Array.isArray(e.concepts)?e.concepts:[];for(let i of r)i?.id&&t.push({active:!0,groupId:0,type:{conceptId:pi},target:{conceptId:i.id}});let n=Array.isArray(e.attributes)?e.attributes:[];for(let i of n)t.push(qt(i,0));return(Array.isArray(e.groups)?e.groups:[]).forEach((i,s)=>{let a=Array.isArray(i.attributes)?i.attributes:[];for(let c of a)t.push(qt(c,s+1))}),t}async function go(e,t,r,n){let o=A(e),i=await I(`${o}/browser/${t.branchPath}/concepts/${r}`,{cookie:e.cookie});if(i.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{ok:!1,result:{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:i.body,undetermined:!0}}};let s=Array.isArray(i.body.classAxioms)?i.body.classAxioms:[],a;if(n){if(a=s.find(c=>c.axiomId===n),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${n}.`,undetermined:!0}}}}else{let c=s.filter(u=>u.active!==!1);if(c.length===0)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has no active class axiom.`,undetermined:!0}}};if(c.length>1)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has ${c.length} active class axioms \u2014 pass axiomId to pick which one.`,undetermined:!0}}};a=c[0]}return{ok:!0,value:{axiom:a,axiomId:a.axiomId}}}var fi="116680003";function gi(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==fi?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function yi(e,t,r){let n=A(e),o=await I(`${n}/${t.branchPath}/concepts/${r}/authoring-form`,{cookie:e.cookie,timeoutMs:6e4});if(o.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(o.statusCode<200||o.statusCode>=300||!o.body)return{ok:!1,result:{statusCode:o.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:o.body,undetermined:!0}}};let i=mi(o.body);return i.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.`,undetermined:!0}}}:{ok:!0,value:i}}async function hi(e,t,r,n){let o=await go(e,t,r,n);if(!o.ok)return o;let i=await yi(e,t,r);return i.ok?{ok:!0,value:{axiom:o.value.axiom,axiomId:o.value.axiomId,targetRelationships:i.value}}:i}function ki(e){let t=typeof e.typeId=="string"?e.typeId:e.type?.conceptId,r=e.concreteValue;if(r)return`${t}=#${r.dataType}:${r.value}`;let n=typeof e.destinationId=="string"?e.destinationId:e.target?.conceptId;return`${t}=${n}`}function Jt(e){let t=new Map;for(let o of e){if(o.active===!1)continue;let i=typeof o.groupId=="number"?o.groupId:0,s=t.get(i)??[];s.push(ki(o)),t.set(i,s)}let r=(t.get(0)??[]).slice().sort(),n=[];for(let[o,i]of t)o!==0&&n.push(i.slice().sort());return{ungrouped:r,groups:n}}function Ci(e,t){let r=Jt(e),n=Jt(t);if(r.ungrouped.join("|")!==n.ungrouped.join("|"))return!1;let o=r.groups.map(s=>s.join("|")).sort(),i=n.groups.map(s=>s.join("|")).sort();return o.join("||")===i.join("||")}async function ke(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await hi(e,n,t.conceptId,t.axiomId);if(!o.ok)return o.result;let{axiom:i,axiomId:s,targetRelationships:a}=o.value,c=Array.isArray(i.relationships)?i.relationships:[];return Ci(c,a)?(e.onLog?.(`[${new Date().toISOString()}] transform-axiom ${n.projectKey}/${n.taskKey}: already conforms \u2014 ${t.conceptId}`),{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,alreadyConformed:!0}}):We(e,{conceptId:t.conceptId,axiomId:s,relationships:a,projectKey:n.projectKey,taskKey:n.taskKey},r)}async function Ce(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await go(e,n,t.conceptId,t.axiomId);if(!o.ok)return o.result;let{axiom:i,axiomId:s}=o.value,a=Array.isArray(i.relationships)?i.relationships:[];return gi(a)?{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!0,conforms:!1}}:{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!1,message:"Stated Is-a targets are all primitive \u2014 this cannot rule out a missing/mismatched attribute. Run transform-axiom to get a definitive, self-fixing answer."}}}async function yo(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 C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(d=>d.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(s.relationships)?s.relationships:[],c=t.relationshipId?a.findIndex(d=>d.relationshipId===t.relationshipId):t.relationshipIndex,u=c>=0?a[c]:void 0;return u?u.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${c}`} has effectiveTime ${String(u.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.splice(c,1),s.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 ho(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 C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(d=>d.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(s.relationships)?s.relationships:[],c=Ft(a,t.attributes,t.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${t.axiomId} ${c.error}`}};let u=c.relationships.find(d=>d.effectiveTime!=null);return u?{statusCode:409,body:{error:`Role group (groupId ${c.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(u.relationshipId)}) with effectiveTime ${String(u.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(s.relationships=a.filter(d=>(typeof d.groupId=="number"?d.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function ko(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.gciAxioms)?o.gciAxioms:[],s=i.findIndex(a=>a.axiomId===t.axiomId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published GCI axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-gci-axiom instead.`}}:(i.splice(s,1),o.gciAxioms=i,null)}):{statusCode:400,body:{error:n.error}}}async function Co(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?R(e,n,t.conceptId,o=>{let i=Array.isArray(o.gciAxioms)?o.gciAxioms:[],s=i.find(c=>c.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}};if(s.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished GCI axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-gci-axiom).`}};if(s.active===!1)return{statusCode:409,body:{error:`GCI axiom ${t.axiomId} is already inactive.`}};let a=i.filter(c=>c!==s&&c.active!==!1);return a.length>0&&a.every(c=>c.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating GCI axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished GCI axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-gci-axiom to edit ${t.axiomId}'s content in place instead.`}}:(s.active=!1,null)}):{statusCode:400,body:{error:n.error}}}var Ii=8;async function Ie(e,t,r,n){let o=[],i=[],s=0,a=async()=>{for(;;){let u=s++;if(u>=r.length)return;let d=r[u];try{let l=await Ce(e,{conceptId:d.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),p=l.body;if(l.statusCode<200||l.statusCode>=300){i.push({...d,error:p?.error??`HTTP ${l.statusCode}`});continue}p?.conclusive&&o.push({...d,axiomId:p.axiomId})}catch(l){i.push({...d,error:l instanceof Error?l.message:String(l)})}}},c=Math.min(Ii,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:o,skipped:i}}async function Io(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await ge(e,{...t,branchPath:n.branchPath},r);if(o.statusCode<200||o.statusCode>=300)return o;let i=o.body?.items??[],s=i.map(u=>({conceptId:u.conceptId,fsn:u.fsn,pt:u.pt})),{matched:a,skipped:c}=await Ie(e,n,s,r);return{statusCode:200,body:{branchPath:n.branchPath,totalSearched:i.length,matched:a.length,skipped:c.length,results:a,skippedConcepts:c}}}async function xo(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(e),i=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};if(s.body.effectiveTime!=null)return{statusCode:409,body:{error:`Published concept ${t.conceptId} cannot be deleted \u2014 use inactivate-concept instead.`}};let a=`${o}/${n.branchPath}/concepts/${t.conceptId}`,c=await I(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 xi(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 xe(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(e),i=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};let a=q(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,u=await I(c,{method:"POST",body:He(s.body),cookie:e.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(u.statusCode<200||u.statusCode>=300)return{statusCode:u.statusCode,body:{error:"Validation check failed.",details:u.body}};let d=Array.isArray(u.body)?xi(u.body):[];return{statusCode:200,body:{conceptId:t.conceptId,validationResults:d,hasErrors:d.some(l=>l.severity==="ERROR"),hasWarnings:d.some(l=>l.severity==="WARNING")}}}var bo=200;async function bi(e,t,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${A(e)}/browser/${t}/concepts/bulk-load`,i=!0;for(let s=0;s<r.length;s+=bo){let a=r.slice(s,s+bo),c=await I(o,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){i=!1;continue}for(let u of c.body)n.set(u.conceptId,{fsn:u.fsn?.term,pt:u.pt?.term})}return{terms:n,resolved:i}}async function L(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=[],i=0;for(;;){let k=`${Et(e)}/activities?size=500&page=${i}&onBranch=${encodeURIComponent(n.branchPath)}`,h=await I(k,{cookie:e.cookie});if(h.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(h.statusCode===404)return{statusCode:200,body:{branchPath:n.branchPath,concepts:[],conceptsClassified:[]}};if(h.statusCode<200||h.statusCode>=300)return{statusCode:h.statusCode,body:{error:"Could not fetch traceability for branch.",details:h.body}};o.push(...h.body?.content??[]);let b=h.body?.totalPages??1;if(h.body?.last!==!1||i+1>=b)break;i+=1}let s=new Map,a=new Map,c=(k,h,b,w)=>{let j=k.get(h);j?(w.forEach(P=>P&&j.componentSubTypes.add(P)),j.lastUpdatedTime=b):k.set(h,{conceptId:h,lastUpdatedTime:b,componentSubTypes:new Set(w.filter(P=>!!P))})};for(let k of o)if(!(k.activityType!=="CONTENT_CHANGE"&&k.activityType!=="CLASSIFICATION_SAVE"))for(let h of k.conceptChanges??[]){let b=String(h.conceptId),w=h.componentChanges??[],j=w.map(O=>O.componentSubType);if(k.activityType==="CLASSIFICATION_SAVE"){c(a,b,k.commitDate,j);continue}let P=w.some(O=>O.componentSubType!=="INFERRED_RELATIONSHIP");c(P?s:a,b,k.commitDate,j)}for(let k of s.keys())a.delete(k);let u=[...new Set([...s.keys(),...a.keys()])],{terms:d,resolved:l}=await bi(e,n.branchPath,u),p=k=>[...k.values()].sort((h,b)=>(b.lastUpdatedTime??"").localeCompare(h.lastUpdatedTime??"")).map(h=>{let b=l&&!d.has(h.conceptId);return{conceptId:h.conceptId,fsn:d.get(h.conceptId)?.fsn,pt:d.get(h.conceptId)?.pt,...b?{deleted:!0}:{},lastUpdatedTime:h.lastUpdatedTime,changedComponentTypes:[...h.componentSubTypes]}}),g=p(s),y=p(a);return{statusCode:200,body:{branchPath:n.branchPath,...l?{summary:{concepts:g.length,conceptsDeleted:g.filter(k=>k.deleted).length,conceptsClassified:y.length}}:{},concepts:g,conceptsClassified:y}}}async function So(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await L(e,t,r);if(o.statusCode<200||o.statusCode>=300){let d=o.body;return{statusCode:o.statusCode,body:{error:d.error??"Could not list concepts for review."}}}let i=o.body.concepts??[],s=i.filter(d=>!d.deleted),a=s.map(d=>({conceptId:d.conceptId,fsn:d.fsn})),{matched:c,skipped:u}=await Ie(e,n,a,r);return{statusCode:200,body:{branchPath:n.branchPath,totalReviewed:s.length,matched:c.length,skipped:u.length,skippedDeleted:i.length-s.length,results:c,skippedConcepts:u}}}async function Si(e,t,r,n){let o=[];for(let i of r){if(i.deleted){o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"deleted"});continue}let s=await xe(e,{conceptId:i.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),a=s.body;if(s.statusCode<200||s.statusCode>=300){o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"failed",error:a.error??`HTTP ${s.statusCode}`});continue}let c=a.validationResults??[];o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:c.length===0?"clean":"issues",validationResults:c.length?c:void 0,hasErrors:a.hasErrors})}return o}async function vo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await L(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 i=o.body.concepts??[],s=await Si(e,n,i,r),a=c=>s.filter(u=>u.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:s.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:s}}}async function K(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body??null}var Xe=new Set;function To(e){if(!(!e||typeof e!="object"))for(let t of Xe)t(e)}function vi(e){return Xe.add(e),()=>Xe.delete(e)}function Ti(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 be(e){let t=()=>{};return{promise:new Promise(n=>{t=vi(o=>{Ti(o,e)&&(t(),n(o))})}),cancel:t}}var et=["RUNNING","BUILDING","SCHEDULED","QUEUED"],tt=["QUEUED","SCHEDULED","RUNNING"],Ai=["Promoted","Completed"],Ao=5e3;function Ze(e){return new Promise(t=>setTimeout(t,e))}async function Ri(e,t,r){let n=0;for(;;){let{done:o,value:i}=await e();if(o)return{value:i,timedOut:!1};if(n>=r)return{value:i,timedOut:!0};n++,await Ze(t)}}function wi(){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 Ei=wi(),$i=180;function ji(){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 Pi=ji(),Ni=900;async function Eo(e,t,r,n,o){let i=r*1e3,s=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],u=n?be(n):void 0,d=await Promise.race(u?[Ze(c).then(()=>{}),u.promise]:[Ze(c).then(()=>{})]);if(u?.cancel(),d){let g=d.event;o?.(`[${new Date().toISOString()}] woken by notification${g?`: ${g}`:""}`)}let{done:l,value:p}=await e();if(l)return{value:p,timedOut:!1};if(Date.now()-s>=i)return{value:p,timedOut:!0};a++}}async function $o(e,t,r){let n=await K(e,t,r);if(!n)return{error:`Could not fetch task ${t}/${r}.`};if(n.status&&Ai.includes(n.status))return{error:`Task ${t}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${E(e)}/projects/${t}/tasks/${r}`;await I(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function ot(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await I(n,{method:"POST",body:{},cookie:e.cookie}),(await K(e,t,r))?.latestClassificationJson}async function Ro(e,t,r,n,o){let i,{value:s,timedOut:a}=await Eo(async()=>{let u=(await ot(e,t,r))?.status;return u!==i&&(i=u,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${u??"unknown"}`)),{done:!(!u||et.includes(u)),value:u}},Ei,o,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:s,timedOut:a}}async function Qe(e,t,r){let n=`${A(e)}/${t}/classifications`,o=await I(n,{cookie:e.cookie});if(o.body?.items?.length)return o.body.items.find(i=>i.id===r)??o.body.items[o.body.items.length-1]}async function jo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i}=n,s=await ot(e,o,i);return s?{statusCode:200,body:{hasClassification:!0,jobId:s.id,status:s.status,running:et.includes(s.status),latestClassificationJson:s}}:{statusCode:200,body:{hasClassification:!1}}}async function Se(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=await $o(e,o,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??$i,u=await ot(e,o,i),d=u?.status,l=u?.id;if(l&&d&&et.includes(d)){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: found job ${l} already ${d} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:P}=await Ro(e,o,i,s,c),O=await Qe(e,s,l),_={accepted:!1};return!P&&j==="COMPLETED"&&(_=await ze(e,s,o,i,l)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: attached job ${l} final status ${j??"unknown"}${P?" (timed out waiting)":""}, save ${JSON.stringify(_)}`),{statusCode:200,body:{jobId:l,finalStatus:j,timedOut:P,details:O,save:_,attachedToExisting:!0}}}if(l&&d==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: found job ${l} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await Qe(e,s,l),P=await ze(e,s,o,i,l);return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: accepted existing job ${l}, save ${JSON.stringify(P)}`),{statusCode:200,body:{jobId:l,finalStatus:"COMPLETED",timedOut:!1,details:j,save:P,acceptedExisting:!0}}}let p=`${E(e)}/projects/${o}/tasks/${i}/classifications`,g=await I(p,{method:"POST",body:{},cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!g.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: 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}};e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: started (${g.body.status??"unknown"})`);let y=g.body.id;if(!t.wait)return{statusCode:200,body:{jobId:y,status:g.body.status}};let{finalStatus:k,timedOut:h}=await Ro(e,o,i,s,c),b=await Qe(e,s,y),w={accepted:!1};return!h&&k==="COMPLETED"&&(w=await ze(e,s,o,i,y)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: final status ${k??"unknown"}${h?" (timed out waiting)":""}, save ${JSON.stringify(w)}`),{statusCode:200,body:{jobId:y,finalStatus:k,timedOut:h,details:b,save:w}}}var Di=["SAVED","STALE","SAVE_FAILED"],Oi=120;async function ze(e,t,r,n,o){let i=`${A(e)}/${t}/classifications/${o}`,s=await I(i,{method:"PUT",body:{status:"SAVED"},cookie:e.cookie});if(s.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(s.statusCode<200||s.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${s.statusCode}).`};let a=Math.ceil(Oi*1e3/Ao),{value:c,timedOut:u}=await Ri(async()=>{let l=(await I(i,{cookie:e.cookie})).body?.status;return{done:!!l&&Di.includes(l),value:l}},Ao,a);return u?{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 Po(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i}=n,a=(await K(e,o,i))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&tt.includes(a)}}}async function wo(e,t,r,n,o){let i,{value:s,timedOut:a}=await Eo(async()=>{let u=(await K(e,t,r))?.latestValidationStatus;return u!==i&&(i=u,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${u??"unknown"}`)),{done:!(!u||tt.includes(u)),value:u}},Pi,o,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:s,timedOut:a}}async function No(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=await $o(e,o,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??Ni,d=(await K(e,o,i))?.latestValidationStatus;if(d&&tt.includes(d)){e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: validation already ${d} \u2014 waiting on it instead of starting a new one`);let{finalStatus:k,timedOut:h}=await wo(e,o,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: attached run final status ${k??"unknown"}${h?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:k,timedOut:h,attachedToExisting:!0}}}let l=`${E(e)}/projects/${o}/tasks/${i}/validation`;typeof t.enableMrcmValidation=="boolean"&&(l+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let p=await I(l,{method:"POST",body:{},cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(p.statusCode<200||p.statusCode>=300)return{statusCode:p.statusCode,body:{error:"Failed to start validation.",details:p.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:g,timedOut:y}=await wo(e,o,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: final status ${g??"unknown"}${y?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:g,timedOut:y}}}var Fi=8;function Li(e){return typeof e=="string"&&/timed out after \d+ms/.test(e)}async function Do(e,t,r,n,o,i){let s=0,a=0,c=async()=>{for(;;){let d=a++;if(d>=r.length)return;let l=r[d];try{let p=await ke(e,{conceptId:l.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),g=p.body;p.statusCode<200||p.statusCode>=300?g?.undetermined?n.set(l.conceptId,{outcome:"skipped",error:g.error??`HTTP ${p.statusCode}`}):n.set(l.conceptId,{outcome:"failed",error:g?.error??`HTTP ${p.statusCode}`}):n.set(l.conceptId,{outcome:g?.alreadyConformed?"conformed":"transformed"})}catch(p){n.set(l.conceptId,{outcome:"failed",error:p instanceof Error?p.message:String(p)})}s+=1,e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: ${i} \u2014 ${l.conceptId} (${s}/${r.length})`)}},u=Math.min(Fi,r.length);await Promise.all(Array.from({length:u},()=>c()))}async function Ki(e,t,r,n){let o=new Map;return await Do(e,t,r,o,n,"axiom checked"),await Mi(e,t,r,o,n),o}async function Mi(e,t,r,n,o){let i=r.filter(s=>{let a=n.get(s.conceptId);return a?.outcome==="failed"&&Li(a.error)});i.length!==0&&(e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: reprocessing ${i.length} concept(s) that timed out on the first pass`),await Do(e,t,i,n,o,"axiom rechecked"))}async function Oo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await Se(e,{projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath,wait:!0},r);if(o.statusCode===401)return o;let i=o.body,s=o.statusCode>=200&&o.statusCode<300?{jobId:i?.jobId,finalStatus:i?.finalStatus,timedOut:i?.timedOut,save:i?.save}:{error:i?.error??`HTTP ${o.statusCode}`},a=await L(e,t,r);if(a.statusCode<200||a.statusCode>=300){let y=a.body;return{statusCode:a.statusCode,body:{error:y.error??"Could not list concepts for review."}}}let c=a.body.concepts??[],u=c.filter(y=>!y.deleted).map(y=>({conceptId:y.conceptId,fsn:y.fsn})),d=await Ki(e,n,u,r),l=[];for(let[y,k]of c.entries()){if(k.deleted){l.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"deleted"});continue}let h=d.get(k.conceptId),b=await fe(e,{conceptId:k.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),w=b.body,j=`(${y+1}/${c.length})`;if(b.statusCode<200||b.statusCode>=300){e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: FAILED (${b.statusCode}) \u2014 ${k.conceptId} ${j}`),l.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"failed",error:w?.error??`HTTP ${b.statusCode}`,axiom:h});continue}e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: OK \u2014 ${k.conceptId} ${j}`),l.push({conceptId:k.conceptId,fsn:k.fsn,outcome:"fetched",concept:b.body,axiom:h})}let p=y=>l.filter(k=>k.outcome===y).length,g=y=>Array.from(d.values()).filter(k=>k.outcome===y).length;return{statusCode:200,body:{branchPath:n.branchPath,classification:s,summary:{total:l.length,fetched:p("fetched"),skippedDeleted:p("deleted"),failed:p("failed"),axiomsTransformed:g("transformed"),axiomsConformed:g("conformed"),axiomsSkipped:g("skipped"),axiomsFailed:g("failed")},concepts:l}}}async function Fo(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",n=`${E(e)}/projects${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function Lo(e,t){let r=`${E(e)}/projects/${t}/tasks`;return(await I(r,{cookie:e.cookie})).body??[]}async function Ko(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",n=`${E(e)}/projects/my-tasks${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function Mo(e,t){let r=`${E(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 I(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}}async function Bo(e,t){let r=`${E(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,n=await I(r,{cookie:e.cookie});return Array.isArray(n.body)?n.body:[]}var Bi="IN_PROGRESS";async function _o(e,t){let r=`${E(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await I(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 I(r,{method:"PUT",body:{status:Bi},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 Uo(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 nt(e){return JSON.stringify([e])}function Vo(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 rt(e,t={},r=""){let n=Object.entries(t).map(([o,i])=>`${o}:${i}`);return[e,...n,"",r].join(`
3
+ `)+"\0"}function qo(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
4
4
 
5
5
  `),n=r===-1?t:t.slice(0,r),o=r===-1?"":t.slice(r+2),i=n.split(`
6
- `),s=i[0],a={};for(let c of i.slice(1)){let l=c.indexOf(":");l!==-1&&(a[c.slice(0,l)]=c.slice(l+1))}return{command:s,headers:a,body:o}}var Oo=T(require("ws"));var Do=[1e3,2e3,5e3,1e4,3e4];function Fo(e,t={}){let r=t.createSocket??((d,u)=>new Oo.default(d,u)),n=!1,o,i=0,s,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(n)return;let d=Do[Math.min(i,Do.length-1)];i+=1,s=setTimeout(l,d)};function l(){if(n)return;let u=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${Po()}`,p=r(u,a?{headers:{cookie:a}}:{});o=p,p.on("message",g=>{let y=jo(g.toString());if(y.type==="open"){p.send(We(Qe("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(y.type==="close"){p.close();return}if(y.type==="message")for(let k of y.messages){let h=No(k);if(h){if(h.command==="CONNECTED"){i=0;let b=`/topic/user/${e.login}/notifications`;p.send(We(Qe("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:b})));continue}if(h.command==="MESSAGE"){try{e.onNotification(JSON.parse(h.body))}catch(b){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",b)}continue}h.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",h.headers,h.body)}}}),p.on("unexpected-response",(g,y)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${y.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),p.terminate()}),p.on("error",g=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",g.message)}),p.on("close",c)}return l(),{stop(){n=!0,s&&clearTimeout(s),o?.removeAllListeners(),o?.close()}}}function Lo(e,t,r={}){let n=r.startRelay??Fo,o=r.onNotification??fo,i=n({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:o});return{stop:()=>i.stop()}}var Ti=60;async function Ko(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=t.timeoutSeconds??Ti,c=ke({entityType:t.entityType,projectKey:o,taskKey:i,branchPath:s}),l,d=new Promise(g=>{l=setTimeout(()=>g({kind:"timeout"}),a*1e3)}),u=c.promise.then(g=>({kind:"notification",payload:g})),p=await Promise.race([u,d]);return c.cancel(),clearTimeout(l),p.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:p.payload}}}function x(e){if(!(!Array.isArray(e)||e.length===0))for(let t of e){let r=t.severity??"INFO",n=r==="ERROR"?"\u2717":r==="WARNING"?"\u26A0":"\u2139",o=t.componentId??t.conceptId??"?";console.log(`${n} ${r} [${o}] ${t.message??""}`)}}var zo=T(require("http")),Xo=require("child_process");var xe=T(require("fs")),Mo=T(require("os")),Bo=T(require("path"));function Ai(){return Bo.join(Mo.homedir(),"Library","Application Support","Google","Chrome","Local State")}function Ri(){let e=Ai();if(!xe.existsSync(e))return[];let t;try{t=JSON.parse(xe.readFileSync(e,"utf8"))}catch{return[]}let r=t?.profile?.info_cache??{};return Object.entries(r).map(([n,o])=>({directoryName:n,displayName:typeof o?.name=="string"&&o.name?o.name:n}))}var Ie=class extends Error{constructor(t,r){super(`Chrome profile "${t}" not found. Available profiles: ${r.length?r.map(n=>`"${n.displayName}"`).join(", "):"(none detected)"}`),this.name="ChromeProfileNotFoundError"}};function be(e,t=Ri()){if(!e){let n=t.find(o=>o.directoryName==="Default");if(n)return n;if(t.length)return t[0];throw new Ie("Default",t)}let r=t.find(n=>n.directoryName===e||n.displayName.toLowerCase()===e.toLowerCase());if(!r)throw new Ie(e,t);return r}var Yo=require("child_process"),Wo=require("util"),Ze=T(require("fs")),Te=T(require("os")),et=T(require("path"));var _o=require("child_process"),Uo=require("util"),Se=T(require("crypto")),B=T(require("fs")),wi=(0,Uo.promisify)(_o.exec);function ze(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}async function Vo(){let{stdout:e}=await wi('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return e.trim()}function qo(e){return Se.pbkdf2Sync(e,"saltysalt",1003,16,"sha1")}function Go(e,t){if(!e)return null;let r=Buffer.from(e,"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),i=r.subarray(3),s;try{let l=Se.createDecipheriv("aes-128-cbc",t,o);s=Buffer.concat([l.update(i),l.final()])}catch{return null}let a=s.length>32?s.subarray(32):null,c=s;return a&&ze(a)&&!ze(s)&&(c=a),ze(c)?c.toString("utf8"):null}function Jo(e,t){B.copyFileSync(e,t);for(let r of["-wal","-shm"]){let n=e+r;B.existsSync(n)&&B.copyFileSync(n,t+r)}}function Ho(e){for(let t of[e,e+"-wal",e+"-shm"])try{B.unlinkSync(t)}catch{}}var Ei=(0,Wo.promisify)(Yo.exec),ve=class extends Error{},Xe=class extends Error{};function $i(e){return et.join(Te.homedir(),"Library","Application Support","Google","Chrome",e,"Cookies")}function ji(){return Ze.existsSync("/Applications/Google Chrome.app")}function Pi(e){let t=e.split(".").filter(Boolean),r=[];for(let n=0;n+1<t.length;n++){let o=t.slice(n).join(".");r.push(o,`.${o}`)}return r}async function tt(e,t,r){let n=$i(e);if(!Ze.existsSync(n))return null;let o=et.join(Te.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);Jo(n,o);try{let i;try{i=await Vo()}catch{return null}let s=qo(i),a=u=>`'${u.replace(/'/g,"''")}'`,l=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${Pi(t).map(a).join(", ")}) AND name = ${a(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:d}=await Ei(`sqlite3 "${o}" "${l}"`);return Go(d.trim(),s)}catch{return null}finally{Ho(o)}}function Ni(e){return new Promise(t=>setTimeout(t,e))}async function Qo(e,t={}){let r=t.platform??process.platform,n=t.isChromeInstalled??ji;if(r!=="darwin")throw new ve(`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 ve("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=t.readCookie??tt,i=t.sleep??Ni,s=e.pollIntervalMs??750,a=e.timeoutMs??15e3,c=await o(e.profileDirectory,e.host,e.cookieName),l=Date.now()+a;for(;Date.now()<l;){let d=await o(e.profileDirectory,e.host,e.cookieName);if(d&&d!==c)return d;await i(s)}throw new Xe(`Timed out after ${a}ms waiting for a fresh "${e.cookieName}" cookie for ${e.host}. Complete login in the Chrome window that opened, or use the manual cookie-paste fallback.`)}function ot(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}function Di(e,t){let r=n=>`'${n.replace(/'/g,"'\\''")}'`;(0,Xo.exec)(`open -na ${r("Google Chrome")} ${r(e)} --args --profile-directory=${r(t)}`)}function Oi(){return`<!DOCTYPE html>
6
+ `),s=i[0],a={};for(let c of i.slice(1)){let u=c.indexOf(":");u!==-1&&(a[c.slice(0,u)]=c.slice(u+1))}return{command:s,headers:a,body:o}}var Go=T(require("ws"));var Jo=[1e3,2e3,5e3,1e4,3e4];function Ho(e,t={}){let r=t.createSocket??((d,l)=>new Go.default(d,l)),n=!1,o,i=0,s,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(n)return;let d=Jo[Math.min(i,Jo.length-1)];i+=1,s=setTimeout(u,d)};function u(){if(n)return;let l=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${Vo()}`,p=r(l,a?{headers:{cookie:a}}:{});o=p,p.on("message",g=>{let y=Uo(g.toString());if(y.type==="open"){p.send(nt(rt("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(y.type==="close"){p.close();return}if(y.type==="message")for(let k of y.messages){let h=qo(k);if(h){if(h.command==="CONNECTED"){i=0;let b=`/topic/user/${e.login}/notifications`;p.send(nt(rt("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:b})));continue}if(h.command==="MESSAGE"){try{e.onNotification(JSON.parse(h.body))}catch(b){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",b)}continue}h.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",h.headers,h.body)}}}),p.on("unexpected-response",(g,y)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${y.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),p.terminate()}),p.on("error",g=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",g.message)}),p.on("close",c)}return u(),{stop(){n=!0,s&&clearTimeout(s),o?.removeAllListeners(),o?.close()}}}function Yo(e,t,r={}){let n=r.startRelay??Ho,o=r.onNotification??To,i=n({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:o});return{stop:()=>i.stop()}}var _i=60;async function Wo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=t.timeoutSeconds??_i,c=be({entityType:t.entityType,projectKey:o,taskKey:i,branchPath:s}),u,d=new Promise(g=>{u=setTimeout(()=>g({kind:"timeout"}),a*1e3)}),l=c.promise.then(g=>({kind:"notification",payload:g})),p=await Promise.race([l,d]);return c.cancel(),clearTimeout(u),p.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:p.payload}}}function x(e){if(!(!Array.isArray(e)||e.length===0))for(let t of e){let r=t.severity??"INFO",n=r==="ERROR"?"\u2717":r==="WARNING"?"\u26A0":"\u2139",o=t.componentId??t.conceptId??"?";console.log(`${n} ${r} [${o}] ${t.message??""}`)}}var gn=T(require("http")),Ne=require("child_process");var Ae=T(require("fs")),st=T(require("os")),at=T(require("path"));var it=T(require("fs")),Xo=T(require("os")),Qo=T(require("path")),zo=[{path:"/usr/bin/chromium",configDir:"chromium"},{path:"/usr/bin/chromium-browser",configDir:"chromium"},{path:"/usr/bin/google-chrome-stable",configDir:"google-chrome"},{path:"/usr/bin/google-chrome",configDir:"google-chrome"},{path:"/snap/bin/chromium",configDir:"chromium"}],Ui=Array.from(new Set(zo.map(e=>e.configDir)));function re(){return zo.find(e=>it.existsSync(e.path))??null}function ve(e=Xo.homedir()){for(let t of Ui)if(it.existsSync(Qo.join(e,".config",t)))return t;return re()?.configDir??null}function Vi(e){if(e==="linux"){let t=ve();return t?at.join(st.homedir(),".config",t,"Local State"):""}return at.join(st.homedir(),"Library","Application Support","Google","Chrome","Local State")}function qi(e=process.platform){let t=Vi(e);if(!t||!Ae.existsSync(t))return[];let r;try{r=JSON.parse(Ae.readFileSync(t,"utf8"))}catch{return[]}let n=r?.profile?.info_cache??{};return Object.entries(n).map(([o,i])=>({directoryName:o,displayName:typeof i?.name=="string"&&i.name?i.name:o}))}var Te=class extends Error{constructor(t,r){super(`Chrome profile "${t}" not found. Available profiles: ${r.length?r.map(n=>`"${n.displayName}"`).join(", "):"(none detected)"}`),this.name="ChromeProfileNotFoundError"}};function Re(e,t=qi()){if(!e){let n=t.find(o=>o.directoryName==="Default");if(n)return n;if(t.length)return t[0];throw new Te("Default",t)}let r=t.find(n=>n.directoryName===e||n.displayName.toLowerCase()===e.toLowerCase());if(!r)throw new Te(e,t);return r}var dn=require("child_process"),un=require("util"),ut=T(require("fs")),ie=T(require("os")),Ee=T(require("path"));var Zo=require("child_process"),en=require("util"),we=T(require("crypto")),B=T(require("fs")),Ji=(0,en.promisify)(Zo.exec);function ct(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}var Gi="peanuts";async function tn(e=process.platform){if(e==="darwin"){let{stdout:t}=await Ji('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return t.trim()}if(e==="linux")return Gi;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}var on=1003,Hi=1;function nn(e){if(e==="darwin")return on;if(e==="linux")return Hi;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}function rn(e,t=on){return we.pbkdf2Sync(e,"saltysalt",t,16,"sha1")}function sn(e,t){if(!e)return null;let r=Buffer.from(e,"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),i=r.subarray(3),s;try{let u=we.createDecipheriv("aes-128-cbc",t,o);s=Buffer.concat([u.update(i),u.final()])}catch{return null}let a=s.length>32?s.subarray(32):null,c=s;return a&&ct(a)&&!ct(s)&&(c=a),ct(c)?c.toString("utf8"):null}function an(e,t){B.copyFileSync(e,t);for(let r of["-wal","-shm"]){let n=e+r;B.existsSync(n)&&B.copyFileSync(n,t+r)}}function cn(e){for(let t of[e,e+"-wal",e+"-shm"])try{B.unlinkSync(t)}catch{}}var Yi=(0,un.promisify)(dn.exec),$e=class extends Error{},dt=class extends Error{};function Wi(e,t){if(t==="linux"){let r=ve();return r?Ee.join(ie.homedir(),".config",r,e,"Cookies"):""}return Ee.join(ie.homedir(),"Library","Application Support","Google","Chrome",e,"Cookies")}function Xi(e=process.platform){return e==="linux"?re()!==null:ut.existsSync("/Applications/Google Chrome.app")}function Qi(e){let t=e.split(".").filter(Boolean),r=[];for(let n=0;n+1<t.length;n++){let o=t.slice(n).join(".");r.push(o,`.${o}`)}return r}async function lt(e,t,r,n=process.platform){let o=Wi(e,n);if(!o||!ut.existsSync(o))return null;let i=Ee.join(ie.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);an(o,i);try{let s;try{s=await tn(n)}catch{return null}let a=rn(s,nn(n)),c=p=>`'${p.replace(/'/g,"''")}'`,d=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${Qi(t).map(c).join(", ")}) AND name = ${c(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:l}=await Yi(`sqlite3 "${i}" "${d}"`);return sn(l.trim(),a)}catch{return null}finally{cn(i)}}function zi(e){return new Promise(t=>setTimeout(t,e))}async function ln(e,t={}){let r=t.platform??process.platform,n=t.isChromeInstalled??(()=>Xi(r));if(r!=="darwin"&&r!=="linux")throw new $e(`Automatic session capture is only supported on macOS or Linux with Chrome/Chromium. Detected platform: ${r}. Use the manual cookie-paste fallback instead.`);if(!n())throw new $e(r==="darwin"?"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.":'Automatic session capture requires a Chromium/Chrome binary (checked common Debian install paths), but none was found. Install one (e.g. "apt install chromium" in this proot-distro Debian), or use the manual cookie-paste fallback instead.');let o=t.readCookie??((d,l,p)=>lt(d,l,p,r)),i=t.sleep??zi,s=e.pollIntervalMs??750,a=e.timeoutMs??15e3,c=await o(e.profileDirectory,e.host,e.cookieName),u=Date.now()+a;for(;Date.now()<u;){let d=await o(e.profileDirectory,e.host,e.cookieName);if(d&&d!==c)return d;await i(s)}throw new dt(`Timed out after ${a}ms waiting for a fresh "${e.cookieName}" cookie for ${e.host}. Complete login in the Chrome window that opened, or use the manual cookie-paste fallback.`)}var Pe=require("child_process"),pn=require("util"),H=T(require("fs")),mn=T(require("net")),Zi=(0,pn.promisify)(Pe.exec),je=1,se=`:${je}`,es=["termux-x11","/data/data/com.termux/files/usr/bin/termux-x11"];function pt(e){return`/tmp/.X11-unix/X${e}`}async function ts(){for(let e of es){if(e.startsWith("/")){if(H.existsSync(e))return e;continue}try{return await Zi(`command -v ${e}`),e}catch{}}return null}function os(e,t=500){return new Promise(r=>{let n=pt(e);if(!H.existsSync(n)){r(!1);return}let o=mn.createConnection({path:n}),i=s=>{o.removeAllListeners(),o.destroy(),r(s)};o.setTimeout(t),o.once("connect",()=>i(!0)),o.once("error",()=>i(!1)),o.once("timeout",()=>i(!1))})}function ns(e,t=1e4){let r=Date.now()+t;return new Promise((n,o)=>{let i=()=>{if(H.existsSync(pt(e))){n();return}if(Date.now()>r){o(new Error(`Termux:X11's display socket for :${e} never appeared within ${t}ms`));return}setTimeout(i,100)};i()})}async function fn(e=process.platform){if(e!=="linux"||await os(je))return se;let t=await ts();if(t===null)return se;try{H.unlinkSync(pt(je))}catch{}return(0,Pe.spawn)(t,[se],{detached:!0,stdio:"ignore"}).unref(),await ns(je),se}function mt(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}var rs=["--no-sandbox","--password-store=basic","--force-device-scale-factor=2"];async function is(e,t){let r=re();if(!r)throw new Error('No Chromium/Chrome binary found (checked common Debian install paths). Install one (e.g. "apt install chromium" in this proot-distro Debian) and try again.');let n=process.env.DISPLAY||await fn();(0,Ne.spawn)(r.path,[...rs,`--profile-directory=${t}`,e],{detached:!0,stdio:"ignore",env:{...process.env,DISPLAY:n}}).unref()}function ss(e,t,r){if(r==="linux")return is(e,t);let n=o=>`'${o.replace(/'/g,"'\\''")}'`;(0,Ne.exec)(`open -na ${n("Google Chrome")} ${n(e)} --args --profile-directory=${n(t)}`)}function as(){return`<!DOCTYPE html>
7
7
  <html>
8
8
  <head>
9
9
  <meta charset="utf-8">
@@ -14,20 +14,20 @@
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 Zo(e,t={}){let r=e.cookieName??ot(e.host),n=t.openChrome??Di,o=t.resolveProfile??be,i=t.captureCookie??Qo,s=e.timeoutMs??12e4,a=o(e.chromeProfile);return new Promise((c,l)=>{let d=!1,u=g=>{d||(d=!0,p.close(),g())},p=zo.createServer((g,y)=>{if((g.url||"/").split("?")[0]==="/callback"){y.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),y.end(Oi());return}y.writeHead(404),y.end()});p.listen(0,"127.0.0.1",()=>{let y=`http://localhost:${p.address().port}/callback`,k=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(y)}`;n(k,a.directoryName),(async()=>{try{let h=await i({profileDirectory:a.directoryName,host:e.host,cookieName:r,timeoutMs:s});u(()=>c({cookie:`${r}=${h}`}))}catch(h){u(()=>l(h))}})()}),p.on("error",g=>u(()=>l(g)))})}var N=T(require("fs")),re=T(require("path")),en="AUTHORING_CLI_HOME";function Fi(){return re.join(process.cwd(),".authoring-cli")}function Li(){let e=process.env[en];return e&&e.trim()!==""?re.resolve(e):null}function Ae(){return Li()??Fi()}function ne(e){return re.join(e,"session.json")}function nt(){let e=ne(Ae());if(!N.existsSync(e))return null;let t=N.readFileSync(e,"utf8");return JSON.parse(t)}function Re(e){let t=Ae(),r={...e,updatedAt:new Date().toISOString()};try{N.mkdirSync(t,{recursive:!0,mode:448}),N.writeFileSync(ne(t),JSON.stringify(r,null,2),{mode:384})}catch(n){let o=n?.code;throw o==="EPERM"||o==="EACCES"?new Error(`Couldn't write the session to ${ne(t)} (${o}): the current directory isn't writable. Run authoring-cli from a writable directory, or set ${en} to an explicit, writable location.`):n}}function tn(){let e=ne(Ae());N.existsSync(e)&&N.unlinkSync(e)}function rt(){return ne(Ae())}function H(e){let t=nt();if(!t)throw new Error('Not signed in \u2014 run "login" first.');Re({...t,currentTask:e})}async function Ki(e,t,r,n){let o;try{o=be(n).directoryName}catch{return null}let i=await tt(o,t,r).catch(()=>null);if(!i)return null;let s=`${r}=${i}`,a=await De(e,s).catch(()=>null);return a?{cookie:s,account:a}:null}function on(e){let t=e?.displayName??e?.login;return t?`Signed in as ${t}.`:"Signed in. (Could not confirm account details \u2014 proceed with caution.)"}function nn(e){let t=Math.max(...e.map(r=>r.label.length));for(let{url:r,label:n,explicit:o,source:i}of e)console.log(` ${(n+":").padEnd(t+2)}${r} (${o?"from flag":i})`)}async function rn(e){let t=e.environment?mt(e.environment):z;if(!t){console.error(`Unknown environment: ${e.environment}
18
- Expected one of: ${ce.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=U[t],n=e.imsEndpoint||r.imsEndpoint,o=e.terminologyServerEndpoint||r.terminologyServerEndpoint,i=e.authoringServicesEndpoint||r.authoringServicesEndpoint,s;try{s=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||ot(s),l=t===z&&!e.environment?`${t}, default`:t,d=[{url:n,label:"IMS",explicit:!!e.imsEndpoint},{url:o,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:i,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(y=>({...y,source:l})),u=await Ki(n,s,c,e.chromeProfile);if(u){Re({cookie:u.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:i,account:u.account,currentTask:null}),console.log(`${on(u.account)} (reused an existing Chrome session \u2014 no browser opened.)`),nn(d),console.log(` Session: ${rt()}`);return}console.log(`Opening Chrome to sign in to ${n} ...`);let p;try{p=await Zo({imsEndpoint:n,host:s,cookieName:c,chromeProfile:e.chromeProfile})}catch(y){console.error(y instanceof Error?y.message:String(y)),process.exitCode=1;return}if(!p){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 De(n,p.cookie).catch(()=>null);Re({cookie:p.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:i,account:g,currentTask:null}),console.log(on(g)),nn(d),console.log(` Session: ${rt()}`)}async function sn(){tn(),console.log("Signed out.")}var Ee=T(require("fs")),we=T(require("path"));async function an(){let e=[we.join(__dirname,"../../HELP.md"),we.join(__dirname,"../HELP.md"),we.join(process.cwd(),"HELP.md")];for(let t of e)try{if(Ee.existsSync(t)){let r=Ee.readFileSync(t,"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 m(){let e=nt();return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function f(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,onLog:t=>console.error(t)}}function cn(e){return e.projectKey??e.key??"?"}async function dn(e){let t=m(),r=f(t),n=await To(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(i=>cn(i).length))+1;for(let i of n){let s=i.title??"";console.log(`${cn(i).padEnd(o)}${s?`"${s}"`:""}`)}}function $e(e){return e.taskKey??e.key??"?"}function ln(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Mi(e){return e.projectKey||$e(e).split("-")[0]||"?"}function it(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 st(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,i]of t)console.log(` ${o.padEnd(r)} ${String(i).padStart(n)}`)}async function un(e){let t=m(),r=f(t),n=e.mine||!e.project,o=n?await Ro(r):await Ao(r,e.project);if(n&&e.project){let d=e.project.toLowerCase();o=o.filter(u=>(u.projectKey??"").toLowerCase()===d||$e(u).toLowerCase().startsWith(`${d}-`))}if(e.status){let d=e.status.trim().toLowerCase();o=o.filter(u=>(u.status??"").toLowerCase()===d)}let i=it(o,Mi),s=it(o,ln),a=it(o,d=>d.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:o.length,byProject:Object.fromEntries(i),byAssignee:Object.fromEntries(s),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(" ")}`:""}.`),i.length>1&&st("By project",i),!n&&s.length>1&&st("By assignee",s),a.length>1&&st("By status",a);return}let l=Math.max(...o.map(d=>$e(d).length))+1;for(let d of o){let u=d.summary??d.title??"",p=d.status?` status=${d.status}`:"",g=n?"":` [${ln(d)}]`;console.log(`${$e(d).padEnd(l)}${u?`"${u}"`:""}${p}${g}`)}}async function pn(e){let t=m(),r=f(t),n=t.account?.login??t.account?.username,o=e.unassigned?void 0:e.assignee||n,i=await wo(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:o});if(!i.task){console.error(i.error??`Failed to create task in ${e.project}.`),process.exitCode=1;return}let s=i.task,a=s.key??s.taskKey,c=s.branchPath;if(e.json)console.log(JSON.stringify(s,null,2));else{console.log(`\u2713 Created task ${e.project}/${a} "${s.summary??e.summary}"${s.status?` status=${s.status}`:""}`),c&&console.log(` branch: ${c}`);let l=s.assignee?.displayName??s.assignee?.username;console.log(` assignee: ${l??"unassigned"}`)}if(c){let l=await G(r,c);if(!l.ok){console.error(`Task created, but its branch could not be prepared: ${l.error}`),process.exitCode=1;return}l.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}H({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function mn(e){let t=m(),r=f(t);if(!e.task){let i=await Eo(r,e.project);if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(`No deleted tasks in ${e.project}.`);return}console.log(`${i.length} deleted task${i.length===1?"":"s"} in ${e.project} \u2014 pass --task <key> to recover one:`);for(let s of i){let a=s.assignee?.displayName??s.assignee?.username??"unassigned";console.log(` ${s.key} "${s.summary??""}" [${a}]`)}return}let n=await $o(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 i=await G(r,o);if(!i.ok){console.error(`Task recovered, but its branch could not be prepared: ${i.error}`),process.exitCode=1;return}console.log(i.created?` created branch ${o}`:` branch ${o} still holds its content`)}e.noSelect||!o||(H({projectKey:e.project,taskKey:e.task,branchPath:o}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function fn(e){let t=m(),r=f(t),n=await K(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 G(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${o.error}`),process.exitCode=1;return}H({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 gn(e){let t=m();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 yn(e){let t=m(),r=f(t),n=await xt(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to create concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function hn(e){let t=m(),r=f(t),n={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},o=e.checkStatedParentsDefinitionStatus?await co(r,n,t.currentTask):await ue(r,n,t.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 kn(e){let t=m(),r=f(t),n=await le(r,{conceptId:e.id,attributeType:e.attributeType,gci:e.gci,descriptions:e.descriptions,descriptionFull:e.descriptionFull,axioms:e.axioms,inferred:e.inferred,gciAxiomsCount:e.gciAxiomsCount,full:e.full,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 Cn(e){let t=m(),r=f(t),n=await St(r,{conceptId:e.id,stated:e.stated,limit:e.limit?Number(e.limit):void 0,offset:e.offset?Number(e.offset):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 find references (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function In(e){let t=m(),r=f(t),n=await he(r,{conceptId:e.id,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 validate concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}let i=o.validationResults;if(!Array.isArray(i)||i.length===0){console.log(`No validation issues for concept ${e.id}.`);return}x(i),o.hasErrors&&(process.exitCode=1)}async function xn(e){let t=m(),r=f(t),n=e.checkStatedParentsDefinitionStatus?await po(r,{projectKey:e.project,taskKey:e.task},t.currentTask):await L(r,{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 list concepts for review (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function bn(e){let t=m(),r=f(t),n=await mo(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 i=o.results??[],s=o.summary;if(i.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of i){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}`),x(a.validationResults)}if(s){console.log("");let a=[`${s.validated} validated`,`${s.clean} clean`,`${s.withIssues} with issues`];s.skippedDeleted&&a.push(`${s.skippedDeleted} skipped (deleted on this branch)`),s.failed&&a.push(`${s.failed} failed`),console.log(a.join(", ")+".")}s&&(s.withIssues>0||s.failed>0)&&(process.exitCode=1)}async function Sn(e){let t=m(),r=f(t),n=await vo(r,{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 fetch concepts for review (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function vn(e){let t=m(),r=f(t),n=await Lt(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Tn(e){let t=m(),r=f(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add relationship (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function An(e){let t=m(),r=f(t),n=await ro(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to remove relationship (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Rn(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=m(),n=f(r),o=await io(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),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed role group from axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to remove role group (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function wn(e){let t=m(),r=f(t),n=await _t(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to update description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function En(e){let t=m(),r=f(t),n=await Ut(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}`),x(o.validationResults);return}let i=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}): ${i}`),process.exitCode=1}async function $n(e){let t=m(),r=f(t);if(e.entries){let s;try{s=JSON.parse(e.entries)}catch(d){console.error(`--entries is not valid JSON: ${d.message}`),process.exitCode=1;return}if(!Array.isArray(s)||s.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 Jt(r,{conceptId:e.id,entries:s,projectKey:e.project,taskKey:e.task},t.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${s.length} description(s) on concept ${e.id}`),x(c.validationResults);return}let l=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${l}`),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 Gt(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 s=[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} (${s.join(", ")})`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set acceptability (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function jn(e){let t=m(),r=f(t),n=await Bt(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to inactivate concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Pn(e){let t=m(),r=f(t),n=await Mt(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}`),x(o.validationResults);return}let i=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}): ${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=m(),n=f(r),o=await _e(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function Dn(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=m(),n=f(r),o=await Xt(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated GCI axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update GCI axiom (HTTP ${o.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}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}let r=m(),n=f(r),o=await eo(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(i.gciAxioms)?i.gciAxioms.map(l=>l.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})`:""}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add GCI axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function Fn(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}if(e.definitionStatus&&e.definitionStatus!=="PRIMITIVE"&&e.definitionStatus!=="FULLY_DEFINED"){console.error("--definition-status must be PRIMITIVE or FULLY_DEFINED."),process.exitCode=1;return}let r=m(),n=f(r),o=await Zt(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,definitionStatus:e.definitionStatus,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(i.classAxioms)?i.classAxioms.map(l=>l.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added class axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function Ln(e){let t=m(),r=f(t),n=await lo(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 i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Kn(e){let t=m(),r=f(t),n=await Ht(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 i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Mn(e){let t=m(),r=f(t),n=await Yt(r,{conceptId:e.id,descriptionId:e.descriptionId,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated description ${e.descriptionId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Bn(e){let t=m(),r=f(t),n=await Wt(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Restored description ${e.descriptionId} on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to restore description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function _n(e){let t=m(),r=f(t),n=await zt(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,semanticTag:e.tag,indicator:e.indicator,associationTargetId:e.associationTarget,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Replaced FSN on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to replace FSN (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Un(e){let t=m(),r=f(t),n=await Qt(r,{conceptId:e.id,descriptionId:e.descriptionId,reason:e.reason,targetId:e.targetId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set inactivation reason ${e.reason} on description ${e.descriptionId} (concept ${e.id})`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set description inactivation reason (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Vn(e){let t=m(),r=f(t),n=await to(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 i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function qn(e){let t=m(),r=f(t),n=await oo(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(`Inactivated axiom ${e.axiomId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Gn(e){let t=m(),r=f(t),n=await fe(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){if(o.alreadyConformed)console.log(`Concept ${e.id}'s axiom${o.axiomId?` ${o.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(o.replacedAxiomId){let s=Array.isArray(o.addResult?.classAxioms)?o.addResult.classAxioms.map(c=>c.axiomId).filter(Boolean):[],a=s.length>0?s[s.length-1]:void 0;console.log(`Transformed concept ${e.id} to authoring form: added axiom${a?` ${a}`:""} and inactivated published axiom ${o.replacedAxiomId}.`)}else console.log(`Transformed axiom${e.axiomId?` ${e.axiomId}`:""} on concept ${e.id} to authoring form.`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to transform axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Jn(e){let t=m(),r=f(t),n=await ge(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){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to check stated parents for concept ${e.id} (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}if(o.conclusive){console.log(`Concept ${e.id} does NOT conform to authoring form (axiom ${o.axiomId}) \u2014 a stated Is-a targets a fully-defined concept; run transform-axiom to fix.`),process.exitCode=1;return}console.log(`Concept ${e.id}: stated Is-a targets are all primitive (axiom ${o.axiomId}) \u2014 ${o.message}`)}async function Hn(e){let t=m(),r=f(t),n=await so(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 i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete GCI axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Yn(e){let t=m(),r=f(t),n=await ao(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(`Inactivated GCI axiom ${e.axiomId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate GCI axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}function Y(e){let t=e.account?.login;return t?Lo(f(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 Wn(e){let t=m(),r=f(t),n=Y(t),o;try{o=await Ce(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let i=o.body;if(o.statusCode>=200&&o.statusCode<300){i.finalStatus!==void 0?(console.log(`Classification ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),i.details&&console.log(JSON.stringify(i.details,null,2)),i.save&&(i.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${i.save.error?`: ${i.save.error}`:""}${i.save.status?` (status: ${i.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${i.jobId} (${i.status})`),i.timedOut&&(process.exitCode=1);return}let s=i.details!==void 0?` \u2014 details: ${JSON.stringify(i.details)}`:"";console.error(`Failed to start classification (HTTP ${o.statusCode}): ${i.error??JSON.stringify(i)}${s}`),process.exitCode=1}async function Qn(e){let t=m(),r=f(t),n=await Io(r,{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 check classification status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function zn(e){let t=m(),r=f(t),n=Y(t),o;try{o=await bo(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 i=o.body;if(o.statusCode>=200&&o.statusCode<300){i.finalStatus!==void 0?console.log(`Validation ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),i.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${o.statusCode}): ${i.error??JSON.stringify(i)}`),process.exitCode=1}async function Xn(e){let t=m(),r=f(t),n=await xo(r,{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 check validation status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Zn(e){let t=m(),r=f(t),n=Y(t);try{let o=await Ko(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),i=o.body;if(o.statusCode<200||o.statusCode>=300){let s=i.error?i.error:JSON.stringify(i);console.error(`Failed to watch for a notification (HTTP ${o.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2)),i.timedOut&&(process.exitCode=1)}finally{n?.stop()}}var dt=T(require("os")),W=T(require("path"));var v=T(require("fs")),at=T(require("os")),S=T(require("path")),$="authoring-cli",D=["claude","codex"];function je(e){let t=[S.resolve(e,"..","skills",$),S.resolve(e,"..","..","skills",$)];for(let r of t)if(v.existsSync(S.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 Bi(e){let t=[];return v.existsSync(S.join(e,".claude"))&&t.push("claude"),v.existsSync(S.join(e,".codex"))&&t.push("codex"),t}function ie(e,t){if(e==="all")return[...D];if(e){let n=e.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean),o=n.filter(i=>!D.includes(i));if(o.length)throw new Error(`Unknown --agent value(s): ${o.join(", ")}. Supported: ${D.join(", ")}, all.`);return n}let r=Bi(t);return r.length?r:["claude"]}var tr="# authoring-cli \u2014 SNOMED CT authoring guidance";function _i(e){let t=S.join(e,"SKILL.md"),r=S.join(e,"references","batch-authoring.md");return[tr,"",`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 Pe(e){try{return S.resolve(S.dirname(e),v.readlinkSync(e))}catch{return null}}function se(e){try{return v.lstatSync(e)}catch{return null}}function ct(e){let t=Pe(e);return t?v.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:se(e)?.isDirectory()?"an existing directory":"an existing file"}function or(e){let t=Pe(e);return t!==null&&S.basename(t)===$&&S.basename(S.dirname(t))==="skills"}function nr(e){if(!se(e)?.isFile())return!1;try{return v.readFileSync(e,"utf8").startsWith(tr)}catch{return!1}}function er(e){return v.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()).map(t=>S.relative(e,S.join(t.parentPath,t.name))).sort()}function rr(e,t){if(!t||!v.existsSync(t))return!1;try{let r=er(t);return r.join(`
20
- `)!==er(e).join(`
21
- `)?!1:r.every(n=>v.readFileSync(S.join(e,n)).equals(v.readFileSync(S.join(t,n))))}catch{return!1}}function Ui(e,t,r){let n=e.project?S.join(r,".claude","skills"):S.join(t,".claude","skills"),o=S.join(n,$),i=e.shippedSkillDir,s=e.project&&i.startsWith(r+S.sep)?S.relative(S.dirname(o),i):i,a=se(o),c=!1;if(a){let l=Pe(o);if(l===i&&v.existsSync(l))return{agent:"claude",path:o,status:"already-current",kind:"symlink",detail:i};if(!(or(o)||rr(o,i))&&!e.force)return{agent:"claude",path:o,status:"blocked",kind:"symlink",detail:ct(o)};v.rmSync(o,{recursive:!0,force:!0}),c=!0}v.mkdirSync(n,{recursive:!0});try{return v.symlinkSync(s,o,"dir"),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"symlink",detail:s}}catch(l){let d=l.code;if(d!=="EPERM"&&d!=="EACCES")throw l;return v.cpSync(i,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 Vi(e,t){let r=S.join(t,".codex","prompts"),n=S.join(r,`${$}.md`),o=_i(e.shippedSkillDir),i=se(n),s=!1;if(i){if((i.isFile()?v.readFileSync(n,"utf8"):null)===o)return{agent:"codex",path:n,status:"already-current",kind:"pointer"};if(!nr(n)&&!e.force)return{agent:"codex",path:n,status:"blocked",kind:"pointer",detail:ct(n)};v.rmSync(n,{recursive:!0,force:!0}),s=!0}return v.mkdirSync(r,{recursive:!0}),v.writeFileSync(n,o,"utf8"),{agent:"codex",path:n,status:s?"replaced":"installed",kind:"pointer"}}function ir(e){let t=e.homeDir??at.homedir(),r=e.cwd??process.cwd();return(e.agents??ie(void 0,t)).map(o=>o==="claude"?Ui(e,t,r):Vi(e,t))}function sr(e){let t=e.homeDir??at.homedir(),r=e.cwd??process.cwd();return e.agents.map(n=>{let o=n==="claude"?S.join(e.project?S.join(r,".claude"):S.join(t,".claude"),"skills",$):S.join(t,".codex","prompts",`${$}.md`);if(!se(o))return{agent:n,path:o,status:"not-registered"};if(!(n==="claude"?or(o)||rr(o,e.shippedSkillDir):nr(o))&&!e.force)return{agent:n,path:o,status:"left-alone",detail:`${ct(o)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let s=Pe(o)??void 0;return v.rmSync(o,{recursive:!0,force:!0}),{agent:n,path:o,status:"removed",detail:s}})}function ar(e){let t=dt.homedir();return e===t||e.startsWith(t+W.sep)?W.join("~",W.relative(t,e)):e}function qi(e){let t=ar(e.path);switch(e.status){case"installed":case"replaced":return e.kind==="symlink"?`${t} (symlink -> ${ar(e.detail??"")})`:e.kind==="copy"?`${t} (copy \u2014 ${e.detail})`:`${t} (pointer into the installed package)`;case"already-current":return`${t} (already registered \u2014 nothing to do)`;case"blocked":return`${t} NOT written \u2014 ${e.detail} is in the way; re-run with --force to replace it`}}async function cr(e){let t=je(__dirname),r=ie(e.agent,dt.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; Codex prompts are always user-global.");let n=ir({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),o=n.filter(a=>a.status==="installed"||a.status==="replaced"),i=n.filter(a=>a.status==="blocked");console.log(o.length?`Installed skill '${$}' for:`:i.length?`Could not install skill '${$}':`:`Skill '${$}' is already registered:`);for(let a of n)console.log(` ${a.agent.padEnd(7)} ${qi(a)}`);if(e.project&&r.includes("claude")&&console.log(`
17
+ </html>`}function yn(e,t={}){let r=e.cookieName??mt(e.host),n=t.platform??process.platform,o=t.openChrome??((u,d)=>ss(u,d,n)),i=t.resolveProfile??Re,s=t.captureCookie??ln,a=e.timeoutMs??12e4,c=i(e.chromeProfile);return new Promise((u,d)=>{let l=!1,p=y=>{l||(l=!0,g.close(),y())},g=gn.createServer((y,k)=>{if((y.url||"/").split("?")[0]==="/callback"){k.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),k.end(as());return}k.writeHead(404),k.end()});g.listen(0,"127.0.0.1",()=>{let k=`http://localhost:${g.address().port}/callback`,h=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(k)}`;(async()=>{try{await o(h,c.directoryName);let b=await s({profileDirectory:c.directoryName,host:e.host,cookieName:r,timeoutMs:a});p(()=>u({cookie:`${r}=${b}`}))}catch(b){p(()=>d(b))}})()}),g.on("error",y=>p(()=>d(y)))})}var N=T(require("fs")),ce=T(require("path")),hn="AUTHORING_CLI_HOME";function cs(){return ce.join(process.cwd(),".authoring-cli")}function ds(){let e=process.env[hn];return e&&e.trim()!==""?ce.resolve(e):null}function De(){return ds()??cs()}function ae(e){return ce.join(e,"session.json")}function ft(){let e=ae(De());if(!N.existsSync(e))return null;let t=N.readFileSync(e,"utf8");return JSON.parse(t)}function Oe(e){let t=De(),r={...e,updatedAt:new Date().toISOString()};try{N.mkdirSync(t,{recursive:!0,mode:448}),N.writeFileSync(ae(t),JSON.stringify(r,null,2),{mode:384})}catch(n){let o=n?.code;throw o==="EPERM"||o==="EACCES"?new Error(`Couldn't write the session to ${ae(t)} (${o}): the current directory isn't writable. Run authoring-cli from a writable directory, or set ${hn} to an explicit, writable location.`):n}}function kn(){let e=ae(De());N.existsSync(e)&&N.unlinkSync(e)}function gt(){return ae(De())}function Y(e){let t=ft();if(!t)throw new Error('Not signed in \u2014 run "login" first.');Oe({...t,currentTask:e})}async function us(e,t,r,n){let o;try{o=Re(n).directoryName}catch{return null}let i=await lt(o,t,r).catch(()=>null);if(!i)return null;let s=`${r}=${i}`,a=await Ue(e,s).catch(()=>null);return a?{cookie:s,account:a}:null}function Cn(e){let t=e?.displayName??e?.login;return t?`Signed in as ${t}.`:"Signed in. (Could not confirm account details \u2014 proceed with caution.)"}function In(e){let t=Math.max(...e.map(r=>r.label.length));for(let{url:r,label:n,explicit:o,source:i}of e)console.log(` ${(n+":").padEnd(t+2)}${r} (${o?"from flag":i})`)}async function xn(e){let t=e.environment?vt(e.environment):z;if(!t){console.error(`Unknown environment: ${e.environment}
18
+ Expected one of: ${pe.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=U[t],n=e.imsEndpoint||r.imsEndpoint,o=e.terminologyServerEndpoint||r.terminologyServerEndpoint,i=e.authoringServicesEndpoint||r.authoringServicesEndpoint,s;try{s=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||mt(s),u=t===z&&!e.environment?`${t}, default`:t,d=[{url:n,label:"IMS",explicit:!!e.imsEndpoint},{url:o,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:i,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(y=>({...y,source:u})),l=await us(n,s,c,e.chromeProfile);if(l){Oe({cookie:l.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:i,account:l.account,currentTask:null}),console.log(`${Cn(l.account)} (reused an existing Chrome session \u2014 no browser opened.)`),In(d),console.log(` Session: ${gt()}`);return}console.log(`Opening Chrome to sign in to ${n} ...`);let p;try{p=await yn({imsEndpoint:n,host:s,cookieName:c,chromeProfile:e.chromeProfile})}catch(y){console.error(y instanceof Error?y.message:String(y)),process.exitCode=1;return}if(!p){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 Ue(n,p.cookie).catch(()=>null);Oe({cookie:p.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:i,account:g,currentTask:null}),console.log(Cn(g)),In(d),console.log(` Session: ${gt()}`)}async function bn(){kn(),console.log("Signed out.")}var Le=T(require("fs")),Fe=T(require("path"));async function Sn(){let e=[Fe.join(__dirname,"../../HELP.md"),Fe.join(__dirname,"../HELP.md"),Fe.join(process.cwd(),"HELP.md")];for(let t of e)try{if(Le.existsSync(t)){let r=Le.readFileSync(t,"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 m(){let e=ft();return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function f(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,onLog:t=>console.error(t)}}function vn(e){return e.projectKey??e.key??"?"}async function Tn(e){let t=m(),r=f(t),n=await Fo(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(i=>vn(i).length))+1;for(let i of n){let s=i.title??"";console.log(`${vn(i).padEnd(o)}${s?`"${s}"`:""}`)}}function Ke(e){return e.taskKey??e.key??"?"}function An(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function ls(e){return e.projectKey||Ke(e).split("-")[0]||"?"}function yt(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 ht(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,i]of t)console.log(` ${o.padEnd(r)} ${String(i).padStart(n)}`)}async function Rn(e){let t=m(),r=f(t),n=e.mine||!e.project,o=n?await Ko(r):await Lo(r,e.project);if(n&&e.project){let d=e.project.toLowerCase();o=o.filter(l=>(l.projectKey??"").toLowerCase()===d||Ke(l).toLowerCase().startsWith(`${d}-`))}if(e.status){let d=e.status.trim().toLowerCase();o=o.filter(l=>(l.status??"").toLowerCase()===d)}let i=yt(o,ls),s=yt(o,An),a=yt(o,d=>d.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:o.length,byProject:Object.fromEntries(i),byAssignee:Object.fromEntries(s),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(" ")}`:""}.`),i.length>1&&ht("By project",i),!n&&s.length>1&&ht("By assignee",s),a.length>1&&ht("By status",a);return}let u=Math.max(...o.map(d=>Ke(d).length))+1;for(let d of o){let l=d.summary??d.title??"",p=d.status?` status=${d.status}`:"",g=n?"":` [${An(d)}]`;console.log(`${Ke(d).padEnd(u)}${l?`"${l}"`:""}${p}${g}`)}}async function wn(e){let t=m(),r=f(t),n=t.account?.login??t.account?.username,o=e.unassigned?void 0:e.assignee||n,i=await Mo(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:o});if(!i.task){console.error(i.error??`Failed to create task in ${e.project}.`),process.exitCode=1;return}let s=i.task,a=s.key??s.taskKey,c=s.branchPath;if(e.json)console.log(JSON.stringify(s,null,2));else{console.log(`\u2713 Created task ${e.project}/${a} "${s.summary??e.summary}"${s.status?` status=${s.status}`:""}`),c&&console.log(` branch: ${c}`);let u=s.assignee?.displayName??s.assignee?.username;console.log(` assignee: ${u??"unassigned"}`)}if(c){let u=await J(r,c);if(!u.ok){console.error(`Task created, but its branch could not be prepared: ${u.error}`),process.exitCode=1;return}u.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}Y({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function En(e){let t=m(),r=f(t);if(!e.task){let i=await Bo(r,e.project);if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(`No deleted tasks in ${e.project}.`);return}console.log(`${i.length} deleted task${i.length===1?"":"s"} in ${e.project} \u2014 pass --task <key> to recover one:`);for(let s of i){let a=s.assignee?.displayName??s.assignee?.username??"unassigned";console.log(` ${s.key} "${s.summary??""}" [${a}]`)}return}let n=await _o(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 i=await J(r,o);if(!i.ok){console.error(`Task recovered, but its branch could not be prepared: ${i.error}`),process.exitCode=1;return}console.log(i.created?` created branch ${o}`:` branch ${o} still holds its content`)}e.noSelect||!o||(Y({projectKey:e.project,taskKey:e.task,branchPath:o}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function $n(e){let t=m(),r=f(t),n=await K(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 J(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${o.error}`),process.exitCode=1;return}Y({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 jn(e){let t=m();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 Pn(e){let t=m(),r=f(t),n=await Pt(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to create concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Nn(e){let t=m(),r=f(t),n={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},o=e.checkStatedParentsDefinitionStatus?await Io(r,n,t.currentTask):await ge(r,n,t.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 Dn(e){let t=m(),r=f(t),n=await fe(r,{conceptId:e.id,attributeType:e.attributeType,gci:e.gci,descriptions:e.descriptions,descriptionFull:e.descriptionFull,axioms:e.axioms,inferred:e.inferred,gciAxiomsCount:e.gciAxiomsCount,full:e.full,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 On(e){let t=m(),r=f(t),n=await Dt(r,{conceptId:e.id,stated:e.stated,limit:e.limit?Number(e.limit):void 0,offset:e.offset?Number(e.offset):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 find references (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function Fn(e){let t=m(),r=f(t),n=await xe(r,{conceptId:e.id,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 validate concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}let i=o.validationResults;if(!Array.isArray(i)||i.length===0){console.log(`No validation issues for concept ${e.id}.`);return}x(i),o.hasErrors&&(process.exitCode=1)}async function Ln(e){let t=m(),r=f(t),n=e.checkStatedParentsDefinitionStatus?await So(r,{projectKey:e.project,taskKey:e.task},t.currentTask):await L(r,{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 list concepts for review (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Kn(e){let t=m(),r=f(t),n=await vo(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 i=o.results??[],s=o.summary;if(i.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of i){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}`),x(a.validationResults)}if(s){console.log("");let a=[`${s.validated} validated`,`${s.clean} clean`,`${s.withIssues} with issues`];s.skippedDeleted&&a.push(`${s.skippedDeleted} skipped (deleted on this branch)`),s.failed&&a.push(`${s.failed} failed`),console.log(a.join(", ")+".")}s&&(s.withIssues>0||s.failed>0)&&(process.exitCode=1)}async function Mn(e){let t=m(),r=f(t),n=await Oo(r,{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 fetch concepts for review (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Bn(e){let t=m(),r=f(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function _n(e){let t=m(),r=f(t),n=await Wt(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add relationship (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Un(e){let t=m(),r=f(t),n=await yo(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to remove relationship (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Vn(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=m(),n=f(r),o=await ho(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),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed role group from axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to remove role group (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function qn(e){let t=m(),r=f(t),n=await zt(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to update description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Jn(e){let t=m(),r=f(t),n=await Zt(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}`),x(o.validationResults);return}let i=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}): ${i}`),process.exitCode=1}async function Gn(e){let t=m(),r=f(t);if(e.entries){let s;try{s=JSON.parse(e.entries)}catch(d){console.error(`--entries is not valid JSON: ${d.message}`),process.exitCode=1;return}if(!Array.isArray(s)||s.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 no(r,{conceptId:e.id,entries:s,projectKey:e.project,taskKey:e.task},t.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${s.length} description(s) on concept ${e.id}`),x(c.validationResults);return}let u=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${u}`),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 oo(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 s=[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} (${s.join(", ")})`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set acceptability (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Hn(e){let t=m(),r=f(t),n=await Qt(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}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to inactivate concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Yn(e){let t=m(),r=f(t),n=await Xt(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}`),x(o.validationResults);return}let i=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}): ${i}`),process.exitCode=1}async function Wn(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=m(),n=f(r),o=await We(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function Xn(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=m(),n=f(r),o=await uo(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated GCI axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update GCI axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function Qn(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=m(),n=f(r),o=await po(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(i.gciAxioms)?i.gciAxioms.map(u=>u.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})`:""}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add GCI axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function zn(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}if(e.definitionStatus&&e.definitionStatus!=="PRIMITIVE"&&e.definitionStatus!=="FULLY_DEFINED"){console.error("--definition-status must be PRIMITIVE or FULLY_DEFINED."),process.exitCode=1;return}let r=m(),n=f(r),o=await lo(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,definitionStatus:e.definitionStatus,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(i.classAxioms)?i.classAxioms.map(u=>u.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added class axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function Zn(e){let t=m(),r=f(t),n=await xo(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 i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function er(e){let t=m(),r=f(t),n=await ro(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 i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function tr(e){let t=m(),r=f(t),n=await io(r,{conceptId:e.id,descriptionId:e.descriptionId,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated description ${e.descriptionId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function or(e){let t=m(),r=f(t),n=await so(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Restored description ${e.descriptionId} on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to restore description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function nr(e){let t=m(),r=f(t),n=await co(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,semanticTag:e.tag,indicator:e.indicator,associationTargetId:e.associationTarget,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Replaced FSN on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to replace FSN (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function rr(e){let t=m(),r=f(t),n=await ao(r,{conceptId:e.id,descriptionId:e.descriptionId,reason:e.reason,targetId:e.targetId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set inactivation reason ${e.reason} on description ${e.descriptionId} (concept ${e.id})`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set description inactivation reason (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function ir(e){let t=m(),r=f(t),n=await mo(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 i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function sr(e){let t=m(),r=f(t),n=await fo(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(`Inactivated axiom ${e.axiomId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function ar(e){let t=m(),r=f(t),n=await ke(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){if(o.alreadyConformed)console.log(`Concept ${e.id}'s axiom${o.axiomId?` ${o.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(o.replacedAxiomId){let s=Array.isArray(o.addResult?.classAxioms)?o.addResult.classAxioms.map(c=>c.axiomId).filter(Boolean):[],a=s.length>0?s[s.length-1]:void 0;console.log(`Transformed concept ${e.id} to authoring form: added axiom${a?` ${a}`:""} and inactivated published axiom ${o.replacedAxiomId}.`)}else console.log(`Transformed axiom${e.axiomId?` ${e.axiomId}`:""} on concept ${e.id} to authoring form.`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to transform axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function cr(e){let t=m(),r=f(t),n=await Ce(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){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to check stated parents for concept ${e.id} (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}if(o.conclusive){console.log(`Concept ${e.id} does NOT conform to authoring form (axiom ${o.axiomId}) \u2014 a stated Is-a targets a fully-defined concept; run transform-axiom to fix.`),process.exitCode=1;return}console.log(`Concept ${e.id}: stated Is-a targets are all primitive (axiom ${o.axiomId}) \u2014 ${o.message}`)}async function dr(e){let t=m(),r=f(t),n=await ko(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 i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete GCI axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function ur(e){let t=m(),r=f(t),n=await Co(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(`Inactivated GCI axiom ${e.axiomId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate GCI axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}function W(e){let t=e.account?.login;return t?Yo(f(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 lr(e){let t=m(),r=f(t),n=W(t),o;try{o=await Se(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let i=o.body;if(o.statusCode>=200&&o.statusCode<300){i.finalStatus!==void 0?(console.log(`Classification ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),i.details&&console.log(JSON.stringify(i.details,null,2)),i.save&&(i.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${i.save.error?`: ${i.save.error}`:""}${i.save.status?` (status: ${i.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${i.jobId} (${i.status})`),i.timedOut&&(process.exitCode=1);return}let s=i.details!==void 0?` \u2014 details: ${JSON.stringify(i.details)}`:"";console.error(`Failed to start classification (HTTP ${o.statusCode}): ${i.error??JSON.stringify(i)}${s}`),process.exitCode=1}async function pr(e){let t=m(),r=f(t),n=await jo(r,{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 check classification status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function mr(e){let t=m(),r=f(t),n=W(t),o;try{o=await No(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 i=o.body;if(o.statusCode>=200&&o.statusCode<300){i.finalStatus!==void 0?console.log(`Validation ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),i.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${o.statusCode}): ${i.error??JSON.stringify(i)}`),process.exitCode=1}async function fr(e){let t=m(),r=f(t),n=await Po(r,{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 check validation status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function gr(e){let t=m(),r=f(t),n=W(t);try{let o=await Wo(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),i=o.body;if(o.statusCode<200||o.statusCode>=300){let s=i.error?i.error:JSON.stringify(i);console.error(`Failed to watch for a notification (HTTP ${o.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2)),i.timedOut&&(process.exitCode=1)}finally{n?.stop()}}var It=T(require("os")),X=T(require("path"));var v=T(require("fs")),kt=T(require("os")),S=T(require("path")),$="authoring-cli",D=["claude","codex"];function Me(e){let t=[S.resolve(e,"..","skills",$),S.resolve(e,"..","..","skills",$)];for(let r of t)if(v.existsSync(S.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 ps(e){let t=[];return v.existsSync(S.join(e,".claude"))&&t.push("claude"),v.existsSync(S.join(e,".codex"))&&t.push("codex"),t}function de(e,t){if(e==="all")return[...D];if(e){let n=e.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean),o=n.filter(i=>!D.includes(i));if(o.length)throw new Error(`Unknown --agent value(s): ${o.join(", ")}. Supported: ${D.join(", ")}, all.`);return n}let r=ps(t);return r.length?r:["claude"]}var hr="# authoring-cli \u2014 SNOMED CT authoring guidance";function ms(e){let t=S.join(e,"SKILL.md"),r=S.join(e,"references","batch-authoring.md");return[hr,"",`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 Be(e){try{return S.resolve(S.dirname(e),v.readlinkSync(e))}catch{return null}}function ue(e){try{return v.lstatSync(e)}catch{return null}}function Ct(e){let t=Be(e);return t?v.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:ue(e)?.isDirectory()?"an existing directory":"an existing file"}function kr(e){let t=Be(e);return t!==null&&S.basename(t)===$&&S.basename(S.dirname(t))==="skills"}function Cr(e){if(!ue(e)?.isFile())return!1;try{return v.readFileSync(e,"utf8").startsWith(hr)}catch{return!1}}function yr(e){return v.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()).map(t=>S.relative(e,S.join(t.parentPath,t.name))).sort()}function Ir(e,t){if(!t||!v.existsSync(t))return!1;try{let r=yr(t);return r.join(`
20
+ `)!==yr(e).join(`
21
+ `)?!1:r.every(n=>v.readFileSync(S.join(e,n)).equals(v.readFileSync(S.join(t,n))))}catch{return!1}}function fs(e,t,r){let n=e.project?S.join(r,".claude","skills"):S.join(t,".claude","skills"),o=S.join(n,$),i=e.shippedSkillDir,s=e.project&&i.startsWith(r+S.sep)?S.relative(S.dirname(o),i):i,a=ue(o),c=!1;if(a){let u=Be(o);if(u===i&&v.existsSync(u))return{agent:"claude",path:o,status:"already-current",kind:"symlink",detail:i};if(!(kr(o)||Ir(o,i))&&!e.force)return{agent:"claude",path:o,status:"blocked",kind:"symlink",detail:Ct(o)};v.rmSync(o,{recursive:!0,force:!0}),c=!0}v.mkdirSync(n,{recursive:!0});try{return v.symlinkSync(s,o,"dir"),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"symlink",detail:s}}catch(u){let d=u.code;if(d!=="EPERM"&&d!=="EACCES")throw u;return v.cpSync(i,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 gs(e,t){let r=S.join(t,".codex","prompts"),n=S.join(r,`${$}.md`),o=ms(e.shippedSkillDir),i=ue(n),s=!1;if(i){if((i.isFile()?v.readFileSync(n,"utf8"):null)===o)return{agent:"codex",path:n,status:"already-current",kind:"pointer"};if(!Cr(n)&&!e.force)return{agent:"codex",path:n,status:"blocked",kind:"pointer",detail:Ct(n)};v.rmSync(n,{recursive:!0,force:!0}),s=!0}return v.mkdirSync(r,{recursive:!0}),v.writeFileSync(n,o,"utf8"),{agent:"codex",path:n,status:s?"replaced":"installed",kind:"pointer"}}function xr(e){let t=e.homeDir??kt.homedir(),r=e.cwd??process.cwd();return(e.agents??de(void 0,t)).map(o=>o==="claude"?fs(e,t,r):gs(e,t))}function br(e){let t=e.homeDir??kt.homedir(),r=e.cwd??process.cwd();return e.agents.map(n=>{let o=n==="claude"?S.join(e.project?S.join(r,".claude"):S.join(t,".claude"),"skills",$):S.join(t,".codex","prompts",`${$}.md`);if(!ue(o))return{agent:n,path:o,status:"not-registered"};if(!(n==="claude"?kr(o)||Ir(o,e.shippedSkillDir):Cr(o))&&!e.force)return{agent:n,path:o,status:"left-alone",detail:`${Ct(o)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let s=Be(o)??void 0;return v.rmSync(o,{recursive:!0,force:!0}),{agent:n,path:o,status:"removed",detail:s}})}function Sr(e){let t=It.homedir();return e===t||e.startsWith(t+X.sep)?X.join("~",X.relative(t,e)):e}function ys(e){let t=Sr(e.path);switch(e.status){case"installed":case"replaced":return e.kind==="symlink"?`${t} (symlink -> ${Sr(e.detail??"")})`:e.kind==="copy"?`${t} (copy \u2014 ${e.detail})`:`${t} (pointer into the installed package)`;case"already-current":return`${t} (already registered \u2014 nothing to do)`;case"blocked":return`${t} NOT written \u2014 ${e.detail} is in the way; re-run with --force to replace it`}}async function vr(e){let t=Me(__dirname),r=de(e.agent,It.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; Codex prompts are always user-global.");let n=xr({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),o=n.filter(a=>a.status==="installed"||a.status==="replaced"),i=n.filter(a=>a.status==="blocked");console.log(o.length?`Installed skill '${$}' for:`:i.length?`Could not install skill '${$}':`:`Skill '${$}' is already registered:`);for(let a of n)console.log(` ${a.agent.padEnd(7)} ${ys(a)}`);if(e.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.`),i.length){process.exitCode=1;return}o.length&&(console.log(`
24
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 s=D.filter(a=>!r.includes(a));s.length&&!e.agent&&console.log(`
25
- Skipped ${s.join(", ")} (no config directory found). Pass --agent ${s.join(",")} to register anyway.`)}var lt=T(require("os")),Q=T(require("path"));function dr(e){let t=lt.homedir();return e===t||e.startsWith(t+Q.sep)?Q.join("~",Q.relative(t,e)):e}function Gi(e){let t=dr(e.path);switch(e.status){case"removed":return e.detail?`${t} (was a symlink -> ${dr(e.detail)})`:`${t} (removed)`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function lr(e){let t=e.agent?ie(e.agent,lt.homedir()):[...D],r;try{r=je(__dirname)}catch{r=void 0}let n=sr({agents:t,project:e.project,force:e.force,shippedSkillDir:r}),o=n.filter(s=>s.status==="removed"),i=n.filter(s=>s.status==="left-alone");console.log(o.length?`Removed skill '${$}' registration for:`:i.length?`Left every registration of '${$}' in place:`:`No '${$}' registration found:`);for(let s of n)console.log(` ${s.agent.padEnd(7)} ${Gi(s)}`);if(i.length){process.exitCode=1;return}o.length&&console.log(`
26
- Restart your agent to drop /authoring-cli from its command list.`)}function Ji(e){let t={};for(let r=0;r<e.length;r++){let n=e[r];if(n.startsWith("--")){let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:"";t[o]=s}}return t}function pr(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var ut=[{name:"login",usage:`login [${ce.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 ${z}; any --*-endpoint overrides that environment's value)`,run:(e,t)=>rn({environment:t[0],imsEndpoint:e["ims-endpoint"],terminologyServerEndpoint:e["terminology-server-endpoint"],authoringServicesEndpoint:e["authoring-services-endpoint"],chromeProfile:e["chrome-profile"],cookieName:e["cookie-name"]})},{name:"logout",usage:"logout (deletes the locally stored session)",run:()=>sn()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>an()},{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:e=>cr({agent:e.agent,project:"project"in e,force:"force"in e})},{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:e=>lr({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"projects",usage:"projects [--json] (lists the projects available to you \u2014 no editor UI needed)",run:e=>dn({json:"json"in e})},{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:e=>un({project:e.project,mine:"mine"in e,status:e.status,summary:"summary"in e,json:"json"in e})},{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:e=>pn({project:e.project,summary:e.summary,description:e.description,assignee:e.assignee,unassigned:"unassigned"in e,noSelect:"no-select"in e,json:"json"in e})},{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 \u2014 there is no delete-task command; delete a task in the Authoring Workbench UI instead)",required:["project"],run:e=>mn({project:e.project,task:e.task,noSelect:"no-select"in e,json:"json"in e})},{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:e=>fn({project:e.project,task:e.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:e=>gn({project:e.project,task:e.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:e=>yn({fsn:e.fsn,tag:e.tag,pt:e.pt,parent:e.parent,module:e.module,project:e.project,task:e.task})},{name:"search-concepts",usage:"search-concepts [--term <text>] [--ecl <expr>] [--active true|false] [--limit N] [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (without --limit, pages through and returns every match rather than stopping at a fixed page size \u2014 Snowstorm still can't page an unsorted search past offset+limit 10,000, so a match count above that comes back with `truncated: true` and a message to narrow the query; --limit N caps the search to exactly N results in one request instead. --check-stated-parents-definition-status filters the search results down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate, checkable from one concept fetch per result with no classification prerequisite. It's read-only and only ever proves the non-conforming case (never \"conforms\"); an axiom with all-primitive stated parents can still be missing an attribute and simply won't appear here \u2014 run transform-axiom on candidates from a broader list if you need the complete check too. Concepts that can't even be checked for this \u2014 an ambiguous multi-axiom concept, or a fetch failure \u2014 are reported separately under skippedConcepts.)",run:e=>hn({term:e.term,ecl:e.ecl,active:e.active,limit:e.limit,checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--attribute-type <SCTID>] [--gci] [--descriptions] [--description-full] [--axioms] [--inferred] [--gci-axioms-count] [--full] [--project <projectKey> --task <taskKey>] (no flags: a lightweight {conceptId, fsn, pt, active, definitionStatus, moduleId, effectiveTime} summary \u2014 no descriptions array, no relationships/axioms, and no network fetch of the full concept at all. --descriptions: active descriptions only (FSN/PT/synonyms), inactive dropped entirely \u2014 the common case. --description-full: every description, active and inactive, with its full acceptabilityMap. --axioms: classAxioms plus the flat relationships[] list filtered to STATED_RELATIONSHIP \u2014 the stated definition, with no inferred content mixed in. --inferred: the flat relationships[] list filtered to INFERRED_RELATIONSHIP only \u2014 what classification produced, no axioms/stated content. --gci alone: gciAxioms only. --gci-axioms-count: just {conceptId, gciAxiomsCount} \u2014 the count of active gciAxioms, for a plain has-it-got-any-GCIs check that doesn't need the axioms' content at all. --full: the entire raw concept (every description, both axiom types, annotations, both stated and inferred relationships \u2014 this used to be the no-flags default). These are mutually exclusive \u2014 pass only one. --attribute-type filters the response down to just the active relationships of that attribute type \u2014 e.g. --attribute-type 363698007 for Finding site \u2014 returning {axiomId, relationshipId, groupId, targetId, targetFsn} per match, instead of the full concept; matches is [] if the concept has none. Scans classAxioms by default; add --gci to scan gciAxioms instead \u2014 the two are never combined, since a GCI axiom's relationships assert the opposite of a class axiom's. --attribute-type takes precedence over the other flags when combined with them)",required:["id"],run:e=>kn({id:e.id,attributeType:e["attribute-type"],gci:"gci"in e,descriptions:"descriptions"in e,descriptionFull:"description-full"in e,axioms:"axioms"in e,inferred:"inferred"in e,gciAxiomsCount:"gci-axioms-count"in e,full:"full"in e,project:e.project,task:e.task})},{name:"find-references",usage:"find-references --id <SCTID> [--stated] [--limit N] [--offset N] [--project <projectKey> --task <taskKey>] (lists every concept that references <SCTID> \u2014 as a stated Is-a parent or as an attribute value \u2014 grouped by reference type, via Snowstorm's own concept-references endpoint. Without --stated, reads the realized/inferred view (what's already classified); with --stated, reads the literal stated axioms instead, which is what catches a same-session edit before classification has run. Run both when sweeping referrers before delete-concept/inactivate-concept \u2014 neither view alone is a complete answer on a branch with pending, unclassified changes. Without --limit/--offset, pages through and returns every referencing concept rather than stopping at Snowstorm's own default page size (1000); pass --limit/--offset yourself to page through the results manually instead)",required:["id"],run:e=>Cn({id:e.id,stated:"stated"in e,limit:e.limit,offset:e.offset,project:e.project,task:e.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; does not check class-axiom authoring-form conformance \u2014 that needs the branch classified first, so it is checked and fixed once for the whole batch by review-concepts instead of per single-concept call here)",required:["id"],run:e=>In({id:e.id,project:e.project,task:e.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--check-stated-parents-definition-status] [--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-stated-parents-definition-status filters that list down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate. Read-only and only ever proves the non-conforming case; an axiom with all-primitive stated parents can still be missing an attribute and won't appear here. Concepts that can't even be checked for this are reported separately under skippedConcepts)`,run:e=>xn({checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.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; does not cover class-axiom authoring-form conformance, see review-concepts)',run:e=>bn({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:"review-concepts [--project <projectKey> --task <taskKey>] (the end-of-task review pipeline for every concept with pending stated changes: classifies the branch, transforms any class axiom that doesn't already match transform-axiom's standard authoring form, then fetches each concept's final representation \u2014 descriptions, relationships, axioms \u2014 reflecting any transform just applied. Does not re-run Snowstorm's own convention check (that already happened on each edit's own save); run validate-review-concepts yourself if you want that re-checked in batch. Still leaves the judgment-call checklist to a human/agent; see skills/authoring-cli/references/review-concepts.md)",run:e=>Sn({project:e.project,task:e.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:e=>vn({id:e.id,term:e.term,type:e.type,tag:e.tag,module:e.module,acceptability:e.acceptability,project:e.project,task:e.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:e=>wn({id:e.id,descriptionId:e["description-id"],term:e.term,caseSignificance:e["case-significance"],project:e.project,task:e.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:e=>En({id:e.id,descriptionId:e["description-id"],caseSignificance:e["case-significance"],project:e.project,task:e.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:e=>$n({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,entries:e.entries,project:e.project,task:e.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:e=>Tn({id:e.id,type:e.type,target:e.target,group:e.group,axiomIndex:e["axiom-index"],project:e.project,task:e.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:e=>An({id:e.id,axiomId:e["axiom-id"],relationshipId:e["relationship-id"],relationshipIndex:e["relationship-index"],project:e.project,task:e.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:e=>Rn({id:e.id,axiomId:e["axiom-id"],attributes:e.attributes,groupId:e["group-id"],project:e.project,task:e.task})},{name:"inactivate-concept",usage:"inactivate-concept --id <SCTID> --indicator <value> [--association-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>] (only if published; for an unpublished concept use delete-concept instead)",required:["id","indicator"],run:e=>jn({id:e.id,indicator:e.indicator,associationRefset:e["association-refset"],associationTarget:e["association-target"],project:e.project,task:e.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:e=>Pn({id:e.id,status:e.status,axiomIndex:e["axiom-index"],project:e.project,task:e.task})},{name:"update-axiom",usage:`update-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-axiom)`,required:["id","axiom-id","relationships"],run:e=>Nn({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.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>] (appends a genuinely additional class axiom alongside the concept's existing one(s) \u2014 to change an existing axiom's content instead, use update-axiom in place, published or not)`,required:["id","relationships"],run:e=>Fn({id:e.id,relationships:e.relationships,definitionStatus:e["definition-status"],moduleId:e["module-id"],project:e.project,task:e.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:e=>On({id:e.id,relationships:e.relationships,moduleId:e["module-id"],project:e.project,task:e.task})},{name:"update-gci-axiom",usage:`update-gci-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-gci-axiom)`,required:["id","axiom-id","relationships"],run:e=>Dn({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"delete-concept",usage:"delete-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (only if unpublished; a published concept 409s \u2014 use inactivate-concept instead)",required:["id"],run:e=>Ln({id:e.id,project:e.project,task:e.task})},{name:"delete-description",usage:"delete-description --id <SCTID> --description-id <descriptionId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published description 409s \u2014 use inactivate-description instead)",required:["id","description-id"],run:e=>Kn({id:e.id,descriptionId:e["description-id"],project:e.project,task:e.task})},{name:"inactivate-description",usage:"inactivate-description --id <SCTID> --description-id <descriptionId> --indicator <value> [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (retires a published FSN/PT/synonym without deleting it; --association-target is always a REFERS_TO association \u2014 a description has no other association type; for a never-versioned description use delete-description instead)",required:["id","description-id","indicator"],run:e=>Mn({id:e.id,descriptionId:e["description-id"],indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"restore-description",usage:`restore-description --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>] (reactivates a synonym/PT retired via inactivate-description; at least one of --lang, --us, --gb is required since acceptability was cleared on inactivation; restoring PREFERRED into a dialect that already has a PT auto-demotes that PT to ACCEPTABLE in the same save)
28
- restore-description --id <SCTID> --description-id <descriptionId> [--indicator <value>] [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (reactivates an FSN instead \u2014 no --lang/--us/--gb, it is always PREFERRED in every dialect; if the concept currently has another active FSN, a never-versioned one is dropped for free but a published one needs --indicator to retire it in the same save; --association-target there is always a REFERS_TO association)`,required:["id","description-id"],run:e=>Bn({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"replace-fsn",usage:'replace-fsn --id <SCTID> --term "<new FSN>" --indicator <value> [--description-id <oldFsnDescriptionId>] [--tag <semantic tag>] [--association-target <SCTID>] [--module <moduleId>] [--project <projectKey> --task <taskKey>] (retires the current FSN and adds its replacement in one save \u2014 neither order works as two separate calls; --description-id is required only if the concept has more than one active FSN; --association-target is always a REFERS_TO association; for a never-versioned FSN use update-description instead)',required:["id","term","indicator"],run:e=>_n({id:e.id,descriptionId:e["description-id"],term:e.term,tag:e.tag,indicator:e.indicator,associationTarget:e["association-target"],module:e.module,project:e.project,task:e.task})},{name:"set-description-inactivation-reason",usage:"set-description-inactivation-reason --id <SCTID> --description-id <descriptionId> --reason NOT_SEMANTICALLY_EQUIVALENT|OUTDATED|GRAMMATICAL_DESCRIPTION_ERROR|NONCONFORMANCE_TO_EDITORIAL_POLICY [--target-id <SCTID>] [--project <projectKey> --task <taskKey>] (assigns or retargets the reason on a description that is already inactive, without touching its active state \u2014 --target-id is required for reason NOT_SEMANTICALLY_EQUIVALENT (the concept this description actually belongs under, via a REFERS_TO association) and rejected for the other three reasons, which take no target; 409s if the reason currently assigned has already been published \u2014 only an unpublished reason can be retargeted; for a description that is still active, use inactivate-description instead)",required:["id","description-id","reason"],run:e=>Un({id:e.id,descriptionId:e["description-id"],reason:e.reason,targetId:e["target-id"],project:e.project,task:e.task})},{name:"delete-axiom",usage:"delete-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published axiom 409s \u2014 use inactivate-axiom instead)",required:["id","axiom-id"],run:e=>Vn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-axiom",usage:"inactivate-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished axiom use delete-axiom instead; a concept must retain at least one active class axiom; 409s if every other active class axiom is itself unpublished \u2014 that combination is the add-a-replacement-then-inactivate anti-pattern, not a legitimate retirement; use update-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>qn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.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; updates the axiom in place, published or not \u2014 omit --axiom-id to target the concept's sole active class axiom)",required:["id"],run:e=>Gn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"check-stated-parents-definition-status",usage:"check-stated-parents-definition-status --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (read-only, fast: checks only whether the class axiom's stated Is-a targets a fully-defined concept \u2014 provable without Snowstorm's own authoring-form computation, which can take upwards of 20s per concept. Reports non-conformance (and exits non-zero) the moment it finds one; otherwise reports inconclusive rather than conforms, since attribute-only mismatches \u2014 a stated axiom missing an inferred attribute even though its Is-a parents are already primitive \u2014 are invisible from stated relationships alone. Run transform-axiom for a definitive, self-fixing answer when this comes back inconclusive \u2014 it checks conformance itself and reports alreadyConformed: true without writing anything if there's nothing to fix)",required:["id"],run:e=>Jn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"delete-gci-axiom",usage:"delete-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published GCI axiom 409s \u2014 use inactivate-gci-axiom instead)",required:["id","axiom-id"],run:e=>Hn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-gci-axiom",usage:"inactivate-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished GCI axiom use delete-gci-axiom instead; unlike inactivate-axiom there is no minimum-active-count guard, since GCI axioms are optional; 409s if every other active GCI axiom is itself unpublished \u2014 use update-gci-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>Yn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.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:e=>Wn({wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"classification-status",usage:"classification-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>Qn({project:e.project,task:e.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:e=>zn({enableMrcm:"enable-mrcm"in e,wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"validation-status",usage:"validation-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>Xn({project:e.project,task:e.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:e=>Zn({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function mr(e){if(!e.aliases?.length)return e.usage;let t=`(alias: ${e.aliases.join(", ")})`;return e.usage.startsWith(e.name)?`${e.name} ${t}${e.usage.slice(e.name.length)}`:`${e.usage} ${t}`}function ur(){return["Usage: authoring-cli <command> [options]","","Commands:",...ut.map(e=>` ${mr(e)}`),"",'Run "login" first to sign in.',"With no --project/--task, actions target whatever task was",'last set via "select-task".'].join(`
29
- `)}async function fr(e=process.argv){let[,,t,...r]=e,n=Ji(r),o=pr(r);if(!t){console.log(ur());return}let i=ut.find(a=>a.name===t||a.aliases?.includes(t));if(!i){console.error(`Unknown command: ${t}
25
+ Skipped ${s.join(", ")} (no config directory found). Pass --agent ${s.join(",")} to register anyway.`)}var xt=T(require("os")),Q=T(require("path"));function Tr(e){let t=xt.homedir();return e===t||e.startsWith(t+Q.sep)?Q.join("~",Q.relative(t,e)):e}function hs(e){let t=Tr(e.path);switch(e.status){case"removed":return e.detail?`${t} (was a symlink -> ${Tr(e.detail)})`:`${t} (removed)`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function Ar(e){let t=e.agent?de(e.agent,xt.homedir()):[...D],r;try{r=Me(__dirname)}catch{r=void 0}let n=br({agents:t,project:e.project,force:e.force,shippedSkillDir:r}),o=n.filter(s=>s.status==="removed"),i=n.filter(s=>s.status==="left-alone");console.log(o.length?`Removed skill '${$}' registration for:`:i.length?`Left every registration of '${$}' in place:`:`No '${$}' registration found:`);for(let s of n)console.log(` ${s.agent.padEnd(7)} ${hs(s)}`);if(i.length){process.exitCode=1;return}o.length&&console.log(`
26
+ Restart your agent to drop /authoring-cli from its command list.`)}function ks(e){let t={};for(let r=0;r<e.length;r++){let n=e[r];if(n.startsWith("--")){let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:"";t[o]=s}}return t}function wr(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var bt=[{name:"login",usage:`login [${pe.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 on macOS (Chrome) or Linux (Chromium/Chrome, incl. Termux:X11). Environment defaults to ${z}; any --*-endpoint overrides that environment's value)`,run:(e,t)=>xn({environment:t[0],imsEndpoint:e["ims-endpoint"],terminologyServerEndpoint:e["terminology-server-endpoint"],authoringServicesEndpoint:e["authoring-services-endpoint"],chromeProfile:e["chrome-profile"],cookieName:e["cookie-name"]})},{name:"logout",usage:"logout (deletes the locally stored session)",run:()=>bn()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>Sn()},{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:e=>vr({agent:e.agent,project:"project"in e,force:"force"in e})},{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:e=>Ar({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"projects",usage:"projects [--json] (lists the projects available to you \u2014 no editor UI needed)",run:e=>Tn({json:"json"in e})},{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:e=>Rn({project:e.project,mine:"mine"in e,status:e.status,summary:"summary"in e,json:"json"in e})},{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:e=>wn({project:e.project,summary:e.summary,description:e.description,assignee:e.assignee,unassigned:"unassigned"in e,noSelect:"no-select"in e,json:"json"in e})},{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 \u2014 there is no delete-task command; delete a task in the Authoring Workbench UI instead)",required:["project"],run:e=>En({project:e.project,task:e.task,noSelect:"no-select"in e,json:"json"in e})},{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:e=>$n({project:e.project,task:e.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:e=>jn({project:e.project,task:e.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:e=>Pn({fsn:e.fsn,tag:e.tag,pt:e.pt,parent:e.parent,module:e.module,project:e.project,task:e.task})},{name:"search-concepts",usage:"search-concepts [--term <text>] [--ecl <expr>] [--active true|false] [--limit N] [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (without --limit, pages through and returns every match rather than stopping at a fixed page size \u2014 Snowstorm still can't page an unsorted search past offset+limit 10,000, so a match count above that comes back with `truncated: true` and a message to narrow the query; --limit N caps the search to exactly N results in one request instead. --check-stated-parents-definition-status filters the search results down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate, checkable from one concept fetch per result with no classification prerequisite. It's read-only and only ever proves the non-conforming case (never \"conforms\"); an axiom with all-primitive stated parents can still be missing an attribute and simply won't appear here \u2014 run transform-axiom on candidates from a broader list if you need the complete check too. Concepts that can't even be checked for this \u2014 an ambiguous multi-axiom concept, or a fetch failure \u2014 are reported separately under skippedConcepts.)",run:e=>Nn({term:e.term,ecl:e.ecl,active:e.active,limit:e.limit,checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--attribute-type <SCTID>] [--gci] [--descriptions] [--description-full] [--axioms] [--inferred] [--gci-axioms-count] [--full] [--project <projectKey> --task <taskKey>] (no flags: a lightweight {conceptId, fsn, pt, active, definitionStatus, moduleId, effectiveTime} summary \u2014 no descriptions array, no relationships/axioms, and no network fetch of the full concept at all. --descriptions: active descriptions only (FSN/PT/synonyms), inactive dropped entirely \u2014 the common case. --description-full: every description, active and inactive, with its full acceptabilityMap. --axioms: classAxioms plus the flat relationships[] list filtered to STATED_RELATIONSHIP \u2014 the stated definition, with no inferred content mixed in. --inferred: the flat relationships[] list filtered to INFERRED_RELATIONSHIP only \u2014 what classification produced, no axioms/stated content. --gci alone: gciAxioms only. --gci-axioms-count: just {conceptId, gciAxiomsCount} \u2014 the count of active gciAxioms, for a plain has-it-got-any-GCIs check that doesn't need the axioms' content at all. --full: the entire raw concept (every description, both axiom types, annotations, both stated and inferred relationships \u2014 this used to be the no-flags default). These are mutually exclusive \u2014 pass only one. --attribute-type filters the response down to just the active relationships of that attribute type \u2014 e.g. --attribute-type 363698007 for Finding site \u2014 returning {axiomId, relationshipId, groupId, targetId, targetFsn} per match, instead of the full concept; matches is [] if the concept has none. Scans classAxioms by default; add --gci to scan gciAxioms instead \u2014 the two are never combined, since a GCI axiom's relationships assert the opposite of a class axiom's. --attribute-type takes precedence over the other flags when combined with them)",required:["id"],run:e=>Dn({id:e.id,attributeType:e["attribute-type"],gci:"gci"in e,descriptions:"descriptions"in e,descriptionFull:"description-full"in e,axioms:"axioms"in e,inferred:"inferred"in e,gciAxiomsCount:"gci-axioms-count"in e,full:"full"in e,project:e.project,task:e.task})},{name:"find-references",usage:"find-references --id <SCTID> [--stated] [--limit N] [--offset N] [--project <projectKey> --task <taskKey>] (lists every concept that references <SCTID> \u2014 as a stated Is-a parent or as an attribute value \u2014 grouped by reference type, via Snowstorm's own concept-references endpoint. Without --stated, reads the realized/inferred view (what's already classified); with --stated, reads the literal stated axioms instead, which is what catches a same-session edit before classification has run. Run both when sweeping referrers before delete-concept/inactivate-concept \u2014 neither view alone is a complete answer on a branch with pending, unclassified changes. Without --limit/--offset, pages through and returns every referencing concept rather than stopping at Snowstorm's own default page size (1000); pass --limit/--offset yourself to page through the results manually instead)",required:["id"],run:e=>On({id:e.id,stated:"stated"in e,limit:e.limit,offset:e.offset,project:e.project,task:e.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; does not check class-axiom authoring-form conformance \u2014 that needs the branch classified first, so it is checked and fixed once for the whole batch by review-concepts instead of per single-concept call here)",required:["id"],run:e=>Fn({id:e.id,project:e.project,task:e.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--check-stated-parents-definition-status] [--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-stated-parents-definition-status filters that list down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate. Read-only and only ever proves the non-conforming case; an axiom with all-primitive stated parents can still be missing an attribute and won't appear here. Concepts that can't even be checked for this are reported separately under skippedConcepts)`,run:e=>Ln({checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.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; does not cover class-axiom authoring-form conformance, see review-concepts)',run:e=>Kn({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:"review-concepts [--project <projectKey> --task <taskKey>] (the end-of-task review pipeline for every concept with pending stated changes: classifies the branch, transforms any class axiom that doesn't already match transform-axiom's standard authoring form, then fetches each concept's final representation \u2014 descriptions, relationships, axioms \u2014 reflecting any transform just applied. Does not re-run Snowstorm's own convention check (that already happened on each edit's own save); run validate-review-concepts yourself if you want that re-checked in batch. Still leaves the judgment-call checklist to a human/agent; see skills/authoring-cli/references/review-concepts.md)",run:e=>Mn({project:e.project,task:e.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:e=>Bn({id:e.id,term:e.term,type:e.type,tag:e.tag,module:e.module,acceptability:e.acceptability,project:e.project,task:e.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:e=>qn({id:e.id,descriptionId:e["description-id"],term:e.term,caseSignificance:e["case-significance"],project:e.project,task:e.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:e=>Jn({id:e.id,descriptionId:e["description-id"],caseSignificance:e["case-significance"],project:e.project,task:e.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:e=>Gn({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,entries:e.entries,project:e.project,task:e.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:e=>_n({id:e.id,type:e.type,target:e.target,group:e.group,axiomIndex:e["axiom-index"],project:e.project,task:e.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:e=>Un({id:e.id,axiomId:e["axiom-id"],relationshipId:e["relationship-id"],relationshipIndex:e["relationship-index"],project:e.project,task:e.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:e=>Vn({id:e.id,axiomId:e["axiom-id"],attributes:e.attributes,groupId:e["group-id"],project:e.project,task:e.task})},{name:"inactivate-concept",usage:"inactivate-concept --id <SCTID> --indicator <value> [--association-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>] (only if published; for an unpublished concept use delete-concept instead)",required:["id","indicator"],run:e=>Hn({id:e.id,indicator:e.indicator,associationRefset:e["association-refset"],associationTarget:e["association-target"],project:e.project,task:e.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:e=>Yn({id:e.id,status:e.status,axiomIndex:e["axiom-index"],project:e.project,task:e.task})},{name:"update-axiom",usage:`update-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-axiom)`,required:["id","axiom-id","relationships"],run:e=>Wn({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.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>] (appends a genuinely additional class axiom alongside the concept's existing one(s) \u2014 to change an existing axiom's content instead, use update-axiom in place, published or not)`,required:["id","relationships"],run:e=>zn({id:e.id,relationships:e.relationships,definitionStatus:e["definition-status"],moduleId:e["module-id"],project:e.project,task:e.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:e=>Qn({id:e.id,relationships:e.relationships,moduleId:e["module-id"],project:e.project,task:e.task})},{name:"update-gci-axiom",usage:`update-gci-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-gci-axiom)`,required:["id","axiom-id","relationships"],run:e=>Xn({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"delete-concept",usage:"delete-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (only if unpublished; a published concept 409s \u2014 use inactivate-concept instead)",required:["id"],run:e=>Zn({id:e.id,project:e.project,task:e.task})},{name:"delete-description",usage:"delete-description --id <SCTID> --description-id <descriptionId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published description 409s \u2014 use inactivate-description instead)",required:["id","description-id"],run:e=>er({id:e.id,descriptionId:e["description-id"],project:e.project,task:e.task})},{name:"inactivate-description",usage:"inactivate-description --id <SCTID> --description-id <descriptionId> --indicator <value> [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (retires a published FSN/PT/synonym without deleting it; --association-target is always a REFERS_TO association \u2014 a description has no other association type; for a never-versioned description use delete-description instead)",required:["id","description-id","indicator"],run:e=>tr({id:e.id,descriptionId:e["description-id"],indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"restore-description",usage:`restore-description --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>] (reactivates a synonym/PT retired via inactivate-description; at least one of --lang, --us, --gb is required since acceptability was cleared on inactivation; restoring PREFERRED into a dialect that already has a PT auto-demotes that PT to ACCEPTABLE in the same save)
28
+ restore-description --id <SCTID> --description-id <descriptionId> [--indicator <value>] [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (reactivates an FSN instead \u2014 no --lang/--us/--gb, it is always PREFERRED in every dialect; if the concept currently has another active FSN, a never-versioned one is dropped for free but a published one needs --indicator to retire it in the same save; --association-target there is always a REFERS_TO association)`,required:["id","description-id"],run:e=>or({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"replace-fsn",usage:'replace-fsn --id <SCTID> --term "<new FSN>" --indicator <value> [--description-id <oldFsnDescriptionId>] [--tag <semantic tag>] [--association-target <SCTID>] [--module <moduleId>] [--project <projectKey> --task <taskKey>] (retires the current FSN and adds its replacement in one save \u2014 neither order works as two separate calls; --description-id is required only if the concept has more than one active FSN; --association-target is always a REFERS_TO association; for a never-versioned FSN use update-description instead)',required:["id","term","indicator"],run:e=>nr({id:e.id,descriptionId:e["description-id"],term:e.term,tag:e.tag,indicator:e.indicator,associationTarget:e["association-target"],module:e.module,project:e.project,task:e.task})},{name:"set-description-inactivation-reason",usage:"set-description-inactivation-reason --id <SCTID> --description-id <descriptionId> --reason NOT_SEMANTICALLY_EQUIVALENT|OUTDATED|GRAMMATICAL_DESCRIPTION_ERROR|NONCONFORMANCE_TO_EDITORIAL_POLICY [--target-id <SCTID>] [--project <projectKey> --task <taskKey>] (assigns or retargets the reason on a description that is already inactive, without touching its active state \u2014 --target-id is required for reason NOT_SEMANTICALLY_EQUIVALENT (the concept this description actually belongs under, via a REFERS_TO association) and rejected for the other three reasons, which take no target; 409s if the reason currently assigned has already been published \u2014 only an unpublished reason can be retargeted; for a description that is still active, use inactivate-description instead)",required:["id","description-id","reason"],run:e=>rr({id:e.id,descriptionId:e["description-id"],reason:e.reason,targetId:e["target-id"],project:e.project,task:e.task})},{name:"delete-axiom",usage:"delete-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published axiom 409s \u2014 use inactivate-axiom instead)",required:["id","axiom-id"],run:e=>ir({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-axiom",usage:"inactivate-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished axiom use delete-axiom instead; a concept must retain at least one active class axiom; 409s if every other active class axiom is itself unpublished \u2014 that combination is the add-a-replacement-then-inactivate anti-pattern, not a legitimate retirement; use update-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>sr({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.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; updates the axiom in place, published or not \u2014 omit --axiom-id to target the concept's sole active class axiom)",required:["id"],run:e=>ar({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"check-stated-parents-definition-status",usage:"check-stated-parents-definition-status --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (read-only, fast: checks only whether the class axiom's stated Is-a targets a fully-defined concept \u2014 provable without Snowstorm's own authoring-form computation, which can take upwards of 20s per concept. Reports non-conformance (and exits non-zero) the moment it finds one; otherwise reports inconclusive rather than conforms, since attribute-only mismatches \u2014 a stated axiom missing an inferred attribute even though its Is-a parents are already primitive \u2014 are invisible from stated relationships alone. Run transform-axiom for a definitive, self-fixing answer when this comes back inconclusive \u2014 it checks conformance itself and reports alreadyConformed: true without writing anything if there's nothing to fix)",required:["id"],run:e=>cr({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"delete-gci-axiom",usage:"delete-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published GCI axiom 409s \u2014 use inactivate-gci-axiom instead)",required:["id","axiom-id"],run:e=>dr({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-gci-axiom",usage:"inactivate-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished GCI axiom use delete-gci-axiom instead; unlike inactivate-axiom there is no minimum-active-count guard, since GCI axioms are optional; 409s if every other active GCI axiom is itself unpublished \u2014 use update-gci-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>ur({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.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:e=>lr({wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"classification-status",usage:"classification-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>pr({project:e.project,task:e.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:e=>mr({enableMrcm:"enable-mrcm"in e,wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"validation-status",usage:"validation-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>fr({project:e.project,task:e.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:e=>gr({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function Er(e){if(!e.aliases?.length)return e.usage;let t=`(alias: ${e.aliases.join(", ")})`;return e.usage.startsWith(e.name)?`${e.name} ${t}${e.usage.slice(e.name.length)}`:`${e.usage} ${t}`}function Rr(){return["Usage: authoring-cli <command> [options]","","Commands:",...bt.map(e=>` ${Er(e)}`),"",'Run "login" first to sign in.',"With no --project/--task, actions target whatever task was",'last set via "select-task".'].join(`
29
+ `)}async function $r(e=process.argv){let[,,t,...r]=e,n=ks(r),o=wr(r);if(!t){console.log(Rr());return}let i=bt.find(a=>a.name===t||a.aliases?.includes(t));if(!i){console.error(`Unknown command: ${t}
30
30
 
31
- ${ur()}`),process.exitCode=1;return}let s=(i.required??[]).filter(a=>!n[a]);if(s.length){console.error(`Missing required flag(s): ${s.map(a=>`--${a}`).join(", ")}
31
+ ${Rr()}`),process.exitCode=1;return}let s=(i.required??[]).filter(a=>!n[a]);if(s.length){console.error(`Missing required flag(s): ${s.map(a=>`--${a}`).join(", ")}
32
32
 
33
- Usage: ${mr(i)}`),process.exitCode=1;return}await i.run(n,o)}require.main===module&&fr().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});0&&(module.exports={COMMANDS,main,parsePositionals});
33
+ Usage: ${Er(i)}`),process.exitCode=1;return}await i.run(n,o)}require.main===module&&$r().catch(e=>{console.error(e instanceof Error?e.message:String(e)),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.16",
3
+ "version": "0.1.17",
4
4
  "description": "CLI for SNOMED CT authoring against authoring-services",
5
5
  "license": "Apache-2.0",
6
6
  "bin": {