authoring-cli 0.1.3 → 0.1.5
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 +2 -1
- package/dist/index.js +16 -16
- package/package.json +1 -1
- package/skills/authoring-cli/SKILL.md +129 -15
- package/skills/authoring-cli/references/batch-authoring.md +33 -16
- package/skills/authoring-cli/references/gci-modeling.md +22 -9
- package/skills/authoring-cli/references/review-concepts.md +20 -2
package/HELP.md
CHANGED
|
@@ -131,8 +131,9 @@ authoring-cli validate-review-concepts
|
|
|
131
131
|
|
|
132
132
|
### Concept Management
|
|
133
133
|
- `authoring-cli create-concept --fsn "FSN" --parent SCTID [--tag TAG] [--pt PT]` — Create concept
|
|
134
|
-
- `authoring-cli get-concept --id SCTID` — Fetch a concept
|
|
134
|
+
- `authoring-cli get-concept --id SCTID [--attribute-type TYPEID] [--gci]` — Fetch a concept, or just its relationships of one attribute type (add --gci to check gciAxioms instead of classAxioms)
|
|
135
135
|
- `authoring-cli search-concepts [--term TEXT] [--ecl EXPRESSION]` — Search concepts
|
|
136
|
+
- `authoring-cli find-references --id SCTID [--stated]` — List everything that references a concept (Is-a children and attribute values)
|
|
136
137
|
- `authoring-cli delete-concept --id SCTID` — Delete unversioned concept (only if never published)
|
|
137
138
|
|
|
138
139
|
### Descriptions
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Yn=Object.create;var tt=Object.defineProperty;var Wn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Xn=Object.getPrototypeOf,Qn=Object.prototype.hasOwnProperty;var Zn=(t,e)=>{for(var r in e)tt(t,r,{get:e[r],enumerable:!0})},ne=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of zn(e))!Qn.call(t,o)&&o!==r&&tt(t,o,{get:()=>e[o],enumerable:!(n=Wn(e,o))||n.enumerable});return t};var v=(t,e,r)=>(r=t!=null?Yn(Xn(t)):{},ne(e||!t||!t.__esModule?tt(r,"default",{value:t,enumerable:!0}):r,t)),tr=t=>ne(tt({},"__esModule",{value:!0}),t);var rs={};Zn(rs,{COMMANDS:()=>oe,main:()=>Hn,parsePositionals:()=>Jn});module.exports=tr(rs);var M={production:{imsEndpoint:"https://authoring.ihtsdotools.org/",terminologyServerEndpoint:"https://authoring.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://authoring.ihtsdotools.org/authoring-services/",cookieName:"ims-ihtsdo"},uat:{imsEndpoint:"https://uat-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://uat-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://uat-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"uat-ims-ihtsdo"},dev:{imsEndpoint:"https://dev-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://dev-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://dev-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"dev-ims-ihtsdo"}},er={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},et=Object.keys(M);function re(t){return er[t.trim().toLowerCase()]??null}var W="uat",is=M.uat.imsEndpoint,as=M.uat.terminologyServerEndpoint,cs=M.uat.authoringServicesEndpoint;var or=v(require("http")),nr=v(require("https"));function y(t,e={}){let{method:r="GET",cookie:n,body:o,headers:s={},timeoutMs:i=15e3}=e;return new Promise((a,c)=>{let d;try{d=new URL(t)}catch(C){c(C);return}let l=d.protocol==="https:"?nr:or,u=o!==void 0?JSON.stringify(o):void 0,f={accept:"application/json",...s};if(u!==void 0&&(f["content-type"]="application/json",f["content-length"]=String(Buffer.byteLength(u))),n){let C=n.replace(/[^\x20-\x7e\t]/g,"");C&&(f.cookie=C)}let g=l.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:f},C=>{let x="";C.on("data",h=>{x+=h}),C.on("end",()=>{let h=C.statusCode??0,P=(C.headers["content-type"]??"").includes("application/json"),j=null,E=!1;if(x)try{j=JSON.parse(x)}catch{E=!P}a({statusCode:h,body:j,rawBody:x,sessionExpired:E})})});g.on("error",c),g.setTimeout(i,()=>{g.destroy(new Error(`Request to ${t} timed out after ${i}ms`))}),u!==void 0&&g.write(u),g.end()})}var L="900000000000509007",z="900000000000508004";var se={[L]:"en-us",[z]:"en-gb"},ie={[L]:"true",[z]:"true"},rr={},sr={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:se,dialectDefaults:ie,readOnlyDialects:rr,defaultLanguage:"en"};function ae(t){if(!t||!("defaultModuleId"in t)||t.defaultModuleId==null)return sr;let e={[L]:"en-us"},r={},n={},o=[];for(let c of Object.keys(t)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let l=d[1];e[String(t[c])]=l,o.length===0&&o.push(l)}}let s=t.requiredLanguageRefsets;if(Array.isArray(s))for(let c of s){if(typeof c!="object"||c===null)continue;let d=null,l=null;for(let[C,x]of Object.entries(c))C.length===2&&(d=C,l=String(x));if(!d||!l)continue;let u=c.dialectName;e[l]=typeof u=="string"?u:d;let f=c.default;f==="true"&&!o.includes(d)&&o.push(d),f!=null&&(r[l]=String(f));let g=c.readOnly;g!=null&&(n[l]=String(g))}let i=t.optionalLanguageRefsets;if(Array.isArray(i))for(let c of i)c&&typeof c=="object"&&"refsetId"in c&&(e[String(c.refsetId)]=String(c.language??""));let a=!!t.useInternationalLanguageRefsets;return{isExtension:!0,useInternationalLanguageRefsets:a,dialects:a?se:e,dialectDefaults:a?ie:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function St(t,e,r,n){let o={};for(let s of Object.keys(t.dialects)){let i=t.dialects[s];t.isExtension&&!r?i.includes(n)?o[s]="PREFERRED":i.includes(t.defaultLanguage)&&(o[s]="ACCEPTABLE"):i.includes(n)&&(o[s]=e),t.dialectDefaults[s]==="false"&&!r&&delete o[s],t.readOnlyDialects[s]==="true"&&delete o[s]}return o}function ce(t,e){return t.isExtension&&!t.useInternationalLanguageRefsets?{[L]:"PREFERRED"}:St(t,"PREFERRED",e,"en")}var ir="900000000000207008";function de(t){return t.replace(/\/$/,"")}function A(t){return de(t.terminologyServerEndpoint)}function w(t){return de(t.authoringServicesEndpoint)}function le(t){return`${new URL(w(t)).origin}/authoring-traceability-service`}function _(t){return t.split("/").filter(Boolean).slice(0,-2).join("/")}async function k(t,e,r){let n=e.projectKey||r?.projectKey,o=e.taskKey||r?.taskKey,s=!e.projectKey&&!e.taskKey,i=e.branchPath||(s?r?.branchPath:void 0);return!n||!o?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(i||(i=await ar(t,n,o)??void 0),i?{ok:!0,projectKey:n,taskKey:o,branchPath:i}:{ok:!1,error:`Could not resolve branch path for ${n}/${o}.`})}async function U(t,e){let r=A(t),n=await y(`${r}/branches/${encodeURIComponent(e)}`,{cookie:t.cookie});if(n.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode>=200&&n.statusCode<300)return{ok:!0,created:!1};if(n.statusCode!==404)return{ok:!1,error:`Could not check branch ${e} (HTTP ${n.statusCode}).`};let o=e.split("/").filter(Boolean),s=o[o.length-1],i=o.slice(0,-1).join("/");if(!s||!i)return{ok:!1,error:`Cannot create branch from path "${e}" \u2014 expected a parent and a name.`};let a=await y(`${r}/branches`,{method:"POST",body:{parent:i,name:s},cookie:t.cookie});return a.sessionExpired?{ok:!1,error:"IMS session expired \u2014 re-sign in."}:a.statusCode<200||a.statusCode>=300?{ok:!1,error:`Could not create branch ${e} (HTTP ${a.statusCode}).`}:{ok:!0,created:!0}}async function ar(t,e,r){let n=`${w(t)}/projects/${e}/tasks/${r}`;return(await y(n,{cookie:t.cookie})).body?.branchPath??null}async function ue(t,e,r){let n=r?.get(e);if(n)return n;let o=`${w(t)}/projects/${e}`,i=(await y(o,{cookie:t.cookie})).body?.metadata??{};return r?.set(e,i),i}async function V(t,e,r){let n=await ue(t,e,r),o=n.multipleModuleEditingDisabled,s=!o||o==="false";return n.expectedExtensionModules?.length&&s?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:ir}async function ot(t,e,r){let n=await ue(t,e,r);return ae(n)}async function vt(t,e){let r=t.replace(/\/$/,"")+"/auth",n=await y(r,{cookie:e,timeoutMs:8e3});return n.statusCode>=200&&n.statusCode<300&&n.body?n.body:(console.warn(`[authoring-cli] fetchAccountDetails: HTTP ${n.statusCode} from ${r}`),null)}var pe=v(require("crypto"));var cr="116680003";function nt(t,e,r,n,o="PREFERRED",s=!1){let i=t==="FSN"?ce(n,s):St(n,o,s,"en");return{active:!0,moduleId:r,type:t,term:e,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:i}}async function me(t,e,r,n=new Map){if(!e.fsn||!e.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await k(t,e,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:s,taskKey:i,branchPath:a}=o,c=_(a),d=e.moduleId||await V(t,s,n),l=await ot(t,s,n),u=e.preferredTerm||e.fsn,f=e.semanticTag?`${e.fsn} (${e.semanticTag})`:e.fsn,g={conceptId:null,moduleId:d,definitionStatus:"PRIMITIVE",active:!0,descriptions:[nt("FSN",f,d,l,"PREFERRED",!0),nt("SYNONYM",u,d,l,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:pe.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:d,relationships:[{active:!0,groupId:0,type:{conceptId:cr},target:{conceptId:e.parentConceptId}}]}]},C=`${A(t)}/browser/${c}/${s}/${i}/concepts/?validate=true`,x=await y(C,{method:"POST",body:g,cookie:t.cookie});if(x.sessionExpired){let P="IMS session expired \u2014 re-sign in.";return t.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: SESSION EXPIRED`),{statusCode:401,body:{error:P}}}let h=x.body,T=h&&"conceptId"in h?h.conceptId:void 0;return t.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: ${x.statusCode<300?"OK":"FAILED ("+x.statusCode+")"} \u2014 ${f}`+(T?` \u2192 ${T}`:"")),typeof T=="string"&&t.onValidationResults?.(T,h?.validationResults),{statusCode:x.statusCode,body:x.body}}async function rt(t,e,r){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${A(t)}/browser/${n.branchPath}/concepts/${e.conceptId}`,s=await y(o,{cookie:t.cookie});return s.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:s.statusCode,body:s.body}}async function st(t,e,r){if(!e.term&&!e.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o={limit:e.limit??50,expand:"fsn()"};e.term&&(o.termFilter=e.term),e.ecl&&(o.eclFilter=e.ecl),typeof e.active=="boolean"&&(o.activeFilter=e.active);let s=`${A(t)}/${n.branchPath}/concepts/search`,i=await y(s,{method:"POST",body:o,cookie:t.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let a=(i.body?.items??[]).map(c=>({conceptId:c.conceptId,fsn:c.fsn?.term,pt:c.pt?.term,active:c.active,moduleId:c.moduleId}));return{statusCode:i.statusCode,body:{total:i.body?.total??a.length,items:a}}}var At=v(require("crypto"));function fe(t){return typeof t=="object"&&t!==null}function dr(t){let e=t.type,r=t.target,n=fe(e)?e.conceptId:void 0,o=fe(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function lr(t,e){let r=[...e];for(let n of t){let o=r.findIndex(s=>s.typeId===n.typeId&&s.targetId===n.targetId);if(o===-1)return!1;r.splice(o,1)}return!0}function ge(t,e,r){let n=new Map;for(let i of t){let a=typeof i.groupId=="number"?i.groupId:0,c=n.get(a);c?c.push(i):n.set(a,[i])}let o=[];for(let[i,a]of n){if(r!=null?i!==r:i===0)continue;let c=a.map(dr).filter(d=>d!=null);lr(e,c)&&o.push(i)}if(o.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(o.length>1)return{ok:!1,statusCode:409,error:`has ${o.length} role groups matching the given attributes (groupIds: ${o.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let s=o[0];return{ok:!0,groupId:s,relationships:n.get(s)}}var ur=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],pr=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],mr=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],fr=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],gr=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],wt=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function be(t){return wt.includes(t)}function X(t,e){let r={};for(let n of e)n in t&&(r[n]=t[n]);return r}function it(t){return typeof t=="object"&&t!==null}function ye(t){return it(t)?X(t,fr):t}function Se(t){if(!it(t))return t;let e=X(t,mr);return"type"in e&&(e.type=ye(e.type)),"target"in e&&(e.target=ye(e.target)),e}function yr(t){return it(t)?X(t,pr):t}function ke(t){if(!it(t))return t;let e=X(t,gr);return Array.isArray(e.relationships)&&(e.relationships=e.relationships.map(Se)),e}function Rt(t){let e=X(t,ur);return Array.isArray(e.descriptions)&&(e.descriptions=e.descriptions.map(yr)),Array.isArray(e.relationships)&&(e.relationships=e.relationships.map(Se)),Array.isArray(e.classAxioms)&&(e.classAxioms=e.classAxioms.map(ke)),Array.isArray(e.gciAxioms)&&(e.gciAxioms=e.gciAxioms.map(ke)),e}async function R(t,e,r,n){let o=A(t),s=`${o}/browser/${e.branchPath}/concepts/${r}`,i=await y(s,{cookie:t.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:i.body}};let a=i.body,c=n(a);if(c)return c;let d=_(e.branchPath),l=`${o}/browser/${d}/${e.projectKey}/${e.taskKey}/concepts/${r}?validate=true`,u=await y(l,{method:"PUT",body:Rt(a),cookie:t.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};t.onLog?.(`[${new Date().toISOString()}] update-concept ${e.projectKey}/${e.taskKey}: ${u.statusCode<300?"OK":"FAILED ("+u.statusCode+")"} \u2014 ${r}`);let f=u.body;return t.onValidationResults?.(r,f?.validationResults),{statusCode:u.statusCode,body:u.body}}var he=["PREFERRED","ACCEPTABLE"];async function ve(t,e,r,n=new Map){if(!e.conceptId||!e.term||!e.type)return{statusCode:400,body:{error:"conceptId, term, and type are required."}};if(e.type!=="FSN"&&e.type!=="SYNONYM")return{statusCode:400,body:{error:"type must be FSN or SYNONYM."}};if(e.acceptability&&!he.includes(e.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${he.join(", ")}.`}};let o=await k(t,e,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=e.moduleId||await V(t,o.projectKey,n),i=await ot(t,o.projectKey,n),a=e.type==="FSN"&&e.semanticTag?`${e.term} (${e.semanticTag})`:e.term;return R(t,o,e.conceptId,c=>{let d=Array.isArray(c.descriptions)?c.descriptions:[];return d.push(nt(e.type,a,s,i,e.acceptability??"ACCEPTABLE",!1)),c.descriptions=d,null})}async function Te(t,e,r){if(!e.conceptId||!e.typeId||!e.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=e.axiomIndex??0;return R(t,n,e.conceptId,s=>{let i=Array.isArray(s.classAxioms)?s.classAxioms:[],a=i[o];if(!a)return{statusCode:400,body:{error:`Concept ${e.conceptId} has no classAxiom at index ${o} (has ${i.length}).`}};let c=Array.isArray(a.relationships)?a.relationships:[];return c.push({active:!0,groupId:e.groupId??0,type:{conceptId:e.typeId},target:{conceptId:e.targetId}}),a.relationships=c,null})}async function Ae(t,e,r){if(!e.conceptId||!e.status)return{statusCode:400,body:{error:"conceptId and status are required."}};if(e.status!=="PRIMITIVE"&&e.status!=="FULLY_DEFINED")return{statusCode:400,body:{error:"status must be PRIMITIVE or FULLY_DEFINED."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=e.axiomIndex??0;return R(t,n,e.conceptId,s=>{let i=Array.isArray(s.classAxioms)?s.classAxioms:[],a=i[o];return a?(a.definitionStatus=e.status,s.definitionStatus=e.status,null):{statusCode:400,body:{error:`Concept ${e.conceptId} has no classAxiom at index ${o} (has ${i.length}).`}}})}async function we(t,e,r){if(!e.conceptId||!e.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>(o.active=!1,o.inactivationIndicator=e.indicator,e.associationRefsetId&&e.associationTargetId&&(o.associationTargets={[e.associationRefsetId]:[e.associationTargetId]}),null)):{statusCode:400,body:{error:n.error}}}async function Re(t,e,r){if(!e.conceptId||!e.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};if(!e.term&&!e.caseSignificance)return{statusCode:400,body:{error:"At least one of term or caseSignificance must be provided."}};if(e.caseSignificance&&!be(e.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${wt.join(", ")}.`}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===e.descriptionId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`Description ${e.descriptionId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(e.term&&(i.term=e.term),e.caseSignificance&&(i.caseSignificance=e.caseSignificance),null):{statusCode:404,body:{error:`Concept ${e.conceptId} has no description ${e.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}async function $e(t,e,r){if(!e.conceptId||!e.descriptionId||!e.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!be(e.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${wt.join(", ")}.`}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===e.descriptionId);return i?(i.caseSignificance=e.caseSignificance,null):{statusCode:404,body:{error:`Concept ${e.conceptId} has no description ${e.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}var Tt=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function Ce(t){return Tt.includes(t)}function Ee(t){return t.descriptionId?!t.lang&&!t.us&&!t.gb?{statusCode:400,body:{error:`Entry for description ${t.descriptionId} must set at least one of lang, us, or gb.`}}:t.us&&!Ce(t.us)?{statusCode:400,body:{error:`us must be one of: ${Tt.join(", ")}.`}}:t.gb&&!Ce(t.gb)?{statusCode:400,body:{error:`gb must be one of: ${Tt.join(", ")}.`}}:null:{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function je(t,e,r){let n=t.find(s=>s.descriptionId===r.descriptionId);if(!n)return{statusCode:404,body:{error:`Concept ${e} has no description ${r.descriptionId}.`}};r.lang&&(n.lang=r.lang);let o={...n.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete o[L]:o[L]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[z]:o[z]=r.gb),n.active!==!1&&Object.keys(o).length===0?{statusCode:400,body:{error:`Description ${r.descriptionId} would have an empty acceptabilityMap (Not Acceptable in every dialect) \u2014 an active description must be acceptable in at least one.`}}:(n.acceptabilityMap=o,null)}async function Pe(t,e,r){if(!e.conceptId||!e.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n={descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb},o=Ee(n);if(o)return o;let s=await k(t,e,r);return s.ok?R(t,s,e.conceptId,i=>{let a=Array.isArray(i.descriptions)?i.descriptions:[];return je(a,e.conceptId,n)}):{statusCode:400,body:{error:s.error}}}async function Ne(t,e,r){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};if(!Array.isArray(e.entries)||e.entries.length===0)return{statusCode:400,body:{error:"entries must be a non-empty array."}};for(let o of e.entries){let s=Ee(o);if(s)return s}let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[];for(let i of e.entries){let a=je(s,e.conceptId,i);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function De(t,e,r){if(!e.conceptId||!e.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[],i=s.findIndex(a=>a.descriptionId===e.descriptionId);return i===-1?{statusCode:404,body:{error:`Concept ${e.conceptId} has no description ${e.descriptionId}.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Description ${e.descriptionId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.descriptions=s,null)}):{statusCode:400,body:{error:n.error}}}async function $t(t,e,r){if(!e.conceptId||!e.axiomId||!Array.isArray(e.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(a=>a.axiomId===e.axiomId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${e.axiomId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(i.relationships=e.relationships,null):{statusCode:404,body:{error:`Concept ${e.conceptId} has no class axiom ${e.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Oe(t,e,r){if(!e.conceptId||!e.axiomId||!Array.isArray(e.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===e.axiomId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`GCI axiom ${e.axiomId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(i.relationships=e.relationships,null):{statusCode:404,body:{error:`Concept ${e.conceptId} has no GCI axiom ${e.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Et(t,e,r,n=new Map){if(!e.conceptId||!Array.isArray(e.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(e.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};if(e.definitionStatus&&e.definitionStatus!=="PRIMITIVE"&&e.definitionStatus!=="FULLY_DEFINED")return{statusCode:400,body:{error:"definitionStatus must be PRIMITIVE or FULLY_DEFINED."}};let o=await k(t,e,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=e.moduleId||await V(t,o.projectKey,n);return R(t,o,e.conceptId,i=>{let a=Array.isArray(i.classAxioms)?i.classAxioms:[];return a.push({axiomId:At.randomUUID(),definitionStatus:e.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:e.relationships}),i.classAxioms=a,null})}async function Fe(t,e,r,n=new Map){if(!e.conceptId||!Array.isArray(e.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(e.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};let o=await k(t,e,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=e.moduleId||await V(t,o.projectKey,n);return R(t,o,e.conceptId,i=>{let a=Array.isArray(i.gciAxioms)?i.gciAxioms:[];return a.push({axiomId:At.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:e.relationships}),i.gciAxioms=a,null})}async function Ke(t,e,r){if(!e.conceptId||!e.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let s=Array.isArray(o.classAxioms)?o.classAxioms:[],i=s.findIndex(a=>a.axiomId===e.axiomId);return i===-1?{statusCode:404,body:{error:`Concept ${e.conceptId} has no class axiom ${e.axiomId}.`}}:s.length<2?{statusCode:409,body:{error:`Concept ${e.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${e.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.classAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}async function jt(t,e,r){if(!e.conceptId||!e.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let s=Array.isArray(o.classAxioms)?o.classAxioms:[],i=s.find(c=>c.axiomId===e.axiomId);return i?i.active===!1?{statusCode:409,body:{error:`Axiom ${e.axiomId} is already inactive.`}}:s.filter(c=>c!==i&&c.active!==!1).length===0?{statusCode:409,body:{error:`Concept ${e.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:(i.active=!1,null):{statusCode:404,body:{error:`Concept ${e.conceptId} has no class axiom ${e.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}var kr="116680003";function xe(t,e){let r={active:!0,groupId:e,type:{conceptId:t.type?.id}};return t.concrete?r.concreteValue={dataType:t.value?.dataType,value:t.value?.value}:r.target={conceptId:t.target?.id},r}function hr(t){let e=[],r=Array.isArray(t.concepts)?t.concepts:[];for(let s of r)s?.id&&e.push({active:!0,groupId:0,type:{conceptId:kr},target:{conceptId:s.id}});let n=Array.isArray(t.attributes)?t.attributes:[];for(let s of n)e.push(xe(s,0));return(Array.isArray(t.groups)?t.groups:[]).forEach((s,i)=>{let a=Array.isArray(s.attributes)?s.attributes:[];for(let c of a)e.push(xe(c,i+1))}),e}async function Le(t,e,r,n){let o=A(t),s=await y(`${o}/browser/${e.branchPath}/concepts/${r}`,{cookie:t.cookie});if(s.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{ok:!1,result:{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:s.body}}};let i=Array.isArray(s.body.classAxioms)?s.body.classAxioms:[],a;if(n){if(a=i.find(l=>l.axiomId===n),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${n}.`}}}}else{let l=i.filter(u=>u.active!==!1);if(l.length===0)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has no active class axiom.`}}};if(l.length>1)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has ${l.length} active class axioms \u2014 pass axiomId to pick which one.`}}};a=l[0]}let c=await y(`${o}/${e.branchPath}/concepts/${r}/authoring-form`,{cookie:t.cookie});if(c.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}};if(c.statusCode<200||c.statusCode>=300||!c.body)return{ok:!1,result:{statusCode:c.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:c.body}}};let d=hr(c.body);return d.length===0?{ok:!1,result:{statusCode:409,body:{error:`Authoring form for ${r} produced no relationships \u2014 the concept likely hasn't been classified since its last stated edit. Run classify --wait first.`}}}:{ok:!0,value:{axiom:a,axiomId:a.axiomId,targetRelationships:d}}}function Cr(t){let e=typeof t.typeId=="string"?t.typeId:t.type?.conceptId,r=t.concreteValue;if(r)return`${e}=#${r.dataType}:${r.value}`;let n=typeof t.destinationId=="string"?t.destinationId:t.target?.conceptId;return`${e}=${n}`}function Ie(t){let e=new Map;for(let o of t){if(o.active===!1)continue;let s=typeof o.groupId=="number"?o.groupId:0,i=e.get(s)??[];i.push(Cr(o)),e.set(s,i)}let r=(e.get(0)??[]).slice().sort(),n=[];for(let[o,s]of e)o!==0&&n.push(s.slice().sort());return{ungrouped:r,groups:n}}function Be(t,e){let r=Ie(t),n=Ie(e);if(r.ungrouped.join("|")!==n.ungrouped.join("|"))return!1;let o=r.groups.map(i=>i.join("|")).sort(),s=n.groups.map(i=>i.join("|")).sort();return o.join("||")===s.join("||")}async function Me(t,e,r,n=new Map){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await k(t,e,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=await Le(t,o,e.conceptId,e.axiomId);if(!s.ok)return s.result;let{axiom:i,axiomId:a,targetRelationships:c}=s.value,d=Array.isArray(i.relationships)?i.relationships:[];if(Be(d,c))return{statusCode:200,body:{conceptId:e.conceptId,axiomId:a,alreadyConformed:!0}};if(!(i.effectiveTime!=null))return $t(t,{conceptId:e.conceptId,axiomId:a,relationships:c,projectKey:o.projectKey,taskKey:o.taskKey},r);let u=await Et(t,{conceptId:e.conceptId,relationships:c,moduleId:typeof i.moduleId=="string"?i.moduleId:void 0,definitionStatus:i.definitionStatus,projectKey:o.projectKey,taskKey:o.taskKey},r,n);if(u.statusCode<200||u.statusCode>=300)return u;let f=await jt(t,{conceptId:e.conceptId,axiomId:a,projectKey:o.projectKey,taskKey:o.taskKey},r);return f.statusCode<200||f.statusCode>=300?{statusCode:f.statusCode,body:{error:`Added the transformed axiom but failed to inactivate published axiom ${a}: ${JSON.stringify(f.body)}`,addResult:u.body}}:{statusCode:f.statusCode,body:{replacedAxiomId:a,addResult:u.body,inactivateResult:f.body}}}async function q(t,e,r){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await Le(t,n,e.conceptId,e.axiomId);if(!o.ok)return o.result;let{axiom:s,axiomId:i,targetRelationships:a}=o.value,c=Array.isArray(s.relationships)?s.relationships:[],d=Be(c,a);return{statusCode:200,body:{conceptId:e.conceptId,axiomId:i,conforms:d}}}async function _e(t,e,r){if(!e.conceptId||!e.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};if(!e.relationshipId&&e.relationshipIndex==null)return{statusCode:400,body:{error:"One of relationshipId or relationshipIndex is required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.axiomId===e.axiomId);if(!i)return{statusCode:404,body:{error:`Concept ${e.conceptId} has no class axiom ${e.axiomId}.`}};let a=Array.isArray(i.relationships)?i.relationships:[],c=e.relationshipId?a.findIndex(l=>l.relationshipId===e.relationshipId):e.relationshipIndex,d=c>=0?a[c]:void 0;return d?d.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${e.relationshipId??`at index ${c}`} has effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.splice(c,1),i.relationships=a,null):{statusCode:404,body:{error:`Axiom ${e.axiomId} has no relationship ${e.relationshipId??`at index ${e.relationshipIndex}`}.`}}}):{statusCode:400,body:{error:n.error}}}async function Ue(t,e,r){if(!e.conceptId||!e.axiomId||!Array.isArray(e.attributes)||e.attributes.length===0)return{statusCode:400,body:{error:"conceptId, axiomId, and a non-empty attributes array are required."}};for(let o of e.attributes)if(!o||typeof o.typeId!="string"||typeof o.targetId!="string")return{statusCode:400,body:{error:"Each attributes entry requires typeId and targetId."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.axiomId===e.axiomId);if(!i)return{statusCode:404,body:{error:`Concept ${e.conceptId} has no class axiom ${e.axiomId}.`}};let a=Array.isArray(i.relationships)?i.relationships:[],c=ge(a,e.attributes,e.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${e.axiomId} ${c.error}`}};let d=c.relationships.find(l=>l.effectiveTime!=null);return d?{statusCode:409,body:{error:`Role group (groupId ${c.groupId}) on axiom ${e.axiomId} has a relationship (relationshipId ${String(d.relationshipId)}) with effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(i.relationships=a.filter(l=>(typeof l.groupId=="number"?l.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function Ve(t,e,r){if(!e.conceptId||!e.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await k(t,e,r);return n.ok?R(t,n,e.conceptId,o=>{let s=Array.isArray(o.gciAxioms)?o.gciAxioms:[],i=s.findIndex(a=>a.axiomId===e.axiomId);return i===-1?{statusCode:404,body:{error:`Concept ${e.conceptId} has no GCI axiom ${e.axiomId}.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`GCI axiom ${e.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.gciAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}async function at(t,e,r,n,o){let s=[],i=[];for(let a of r){let c=await q(t,{conceptId:a.conceptId,projectKey:e.projectKey,taskKey:e.taskKey,branchPath:e.branchPath},o),d=c.body;if(c.statusCode<200||c.statusCode>=300||typeof d?.conforms!="boolean"){i.push({...a,error:d?.error??`HTTP ${c.statusCode}`});continue}d.conforms===n&&s.push({...a,axiomId:d.axiomId,conforms:d.conforms})}return{matched:s,skipped:i}}async function qe(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await st(t,{...e,branchPath:n.branchPath},r);if(o.statusCode<200||o.statusCode>=300)return o;let s=o.body?.items??[],i=e.conformed===!0,a=s.map(l=>({conceptId:l.conceptId,fsn:l.fsn,pt:l.pt})),{matched:c,skipped:d}=await at(t,n,a,i,r);return{statusCode:200,body:{branchPath:n.branchPath,totalSearched:s.length,conformed:i,matched:c.length,skipped:d.length,results:c,skippedConcepts:d}}}async function Je(t,e,r){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(t),s=`${o}/browser/${n.branchPath}/concepts/${e.conceptId}`,i=await y(s,{cookie:t.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${e.conceptId}.`,details:i.body}};if(i.body.effectiveTime!=null)return{statusCode:409,body:{error:`Concept ${e.conceptId} has effectiveTime ${String(i.body.effectiveTime)} set (already versioned) \u2014 cannot delete.`}};let a=`${o}/${n.branchPath}/concepts/${e.conceptId}`,c=await y(a,{method:"DELETE",cookie:t.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(t.onLog?.(`[${new Date().toISOString()}] delete-concept ${n.projectKey}/${n.taskKey}: ${c.statusCode<300?"OK":"FAILED ("+c.statusCode+")"} \u2014 ${e.conceptId}`),c.statusCode===409?{statusCode:409,body:{error:`Cannot delete concept ${e.conceptId} \u2014 one or more of its components is published.`,details:c.body}}:{statusCode:c.statusCode,body:c.body})}function xr(t){let e=[];for(let r of t)e.some(o=>o.componentId===r.componentId&&o.severity===r.severity&&o.conceptId===r.conceptId&&o.message===r.message)||e.push(r);return e}async function ct(t,e,r){if(!e.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(t),s=`${o}/browser/${n.branchPath}/concepts/${e.conceptId}`,i=await y(s,{cookie:t.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${e.conceptId}.`,details:i.body}};let a=_(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,d=await y(c,{method:"POST",body:Rt(i.body),cookie:t.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(d.statusCode<200||d.statusCode>=300)return{statusCode:d.statusCode,body:{error:"Validation check failed.",details:d.body}};let l=Array.isArray(d.body)?xr(d.body):[],u=await q(t,{conceptId:e.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),f=u.body;return u.statusCode>=200&&u.statusCode<300&&f?.conforms===!1&&l.push({conceptId:e.conceptId,componentId:f.axiomId,severity:"WARNING",message:"Axiom does not conform to the standard authoring form (Is-a the proximal primitive parent(s) plus every currently-inferred attribute) \u2014 run transform-axiom to fix."}),{statusCode:200,body:{conceptId:e.conceptId,validationResults:l,hasErrors:l.some(g=>g.severity==="ERROR"),hasWarnings:l.some(g=>g.severity==="WARNING")}}}var Ge=200;async function Ir(t,e,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${A(t)}/browser/${e}/concepts/bulk-load`,s=!0;for(let i=0;i<r.length;i+=Ge){let a=r.slice(i,i+Ge),c=await y(o,{method:"POST",body:{conceptIds:a},cookie:t.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){s=!1;continue}for(let d of c.body)n.set(d.conceptId,{fsn:d.fsn?.term,pt:d.pt?.term})}return{terms:n,resolved:s}}async function O(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${le(t)}/activities?size=500&onBranch=${encodeURIComponent(n.branchPath)}`,s=await y(o,{cookie:t.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode===404)return{statusCode:200,body:{branchPath:n.branchPath,concepts:[],conceptsClassified:[]}};if(s.statusCode<200||s.statusCode>=300)return{statusCode:s.statusCode,body:{error:"Could not fetch traceability for branch.",details:s.body}};let i=new Map,a=new Map,c=(x,h,T,P)=>{let j=x.get(h);j?(P.forEach(E=>E&&j.componentSubTypes.add(E)),j.lastUpdatedTime=T):x.set(h,{conceptId:h,lastUpdatedTime:T,componentSubTypes:new Set(P.filter(E=>!!E))})};for(let x of s.body?.content??[])if(!(x.activityType!=="CONTENT_CHANGE"&&x.activityType!=="CLASSIFICATION_SAVE"))for(let h of x.conceptChanges??[]){let T=String(h.conceptId),P=h.componentChanges??[],j=P.map(Y=>Y.componentSubType);if(x.activityType==="CLASSIFICATION_SAVE"){c(a,T,x.commitDate,j);continue}let E=P.some(Y=>Y.componentSubType!=="INFERRED_RELATIONSHIP");c(E?i:a,T,x.commitDate,j)}for(let x of i.keys())a.delete(x);let d=[...new Set([...i.keys(),...a.keys()])],{terms:l,resolved:u}=await Ir(t,n.branchPath,d),f=x=>[...x.values()].sort((h,T)=>(T.lastUpdatedTime??"").localeCompare(h.lastUpdatedTime??"")).map(h=>{let T=u&&!l.has(h.conceptId);return{conceptId:h.conceptId,fsn:l.get(h.conceptId)?.fsn,pt:l.get(h.conceptId)?.pt,...T?{deleted:!0}:{},lastUpdatedTime:h.lastUpdatedTime,changedComponentTypes:[...h.componentSubTypes]}}),g=f(i),C=f(a);return{statusCode:200,body:{branchPath:n.branchPath,...u?{summary:{concepts:g.length,conceptsDeleted:g.filter(x=>x.deleted).length,conceptsClassified:C.length}}:{},concepts:g,conceptsClassified:C}}}async function He(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await O(t,e,r);if(o.statusCode<200||o.statusCode>=300){let u=o.body;return{statusCode:o.statusCode,body:{error:u.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=s.filter(u=>!u.deleted),a=e.conformed===!0,c=i.map(u=>({conceptId:u.conceptId,fsn:u.fsn})),{matched:d,skipped:l}=await at(t,n,c,a,r);return{statusCode:200,body:{branchPath:n.branchPath,conformed:a,totalReviewed:i.length,matched:d.length,skipped:l.length,skippedDeleted:s.length-i.length,results:d,skippedConcepts:l}}}async function Ye(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await O(t,e,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=[];for(let c of s){if(c.deleted){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"deleted"});continue}let d=await ct(t,{conceptId:c.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),l=d.body;if(d.statusCode<200||d.statusCode>=300){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"failed",error:l.error??`HTTP ${d.statusCode}`});continue}let u=l.validationResults??[];i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:u.length===0?"clean":"issues",validationResults:u.length?u:void 0,hasErrors:l.hasErrors})}let a=c=>i.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:i.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:i}}}async function We(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await O(t,e,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=[];for(let c of s){if(c.deleted){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"deleted"});continue}let d=await rt(t,{conceptId:c.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),l=d.body;if(d.statusCode<200||d.statusCode>=300){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"failed",error:l?.error??`HTTP ${d.statusCode}`});continue}i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"fetched",concept:d.body})}let a=c=>i.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:i.length,fetched:a("fetched"),skippedDeleted:a("deleted"),failed:a("failed")},concepts:i}}}var Pt=new Set;function ze(t){if(!(!t||typeof t!="object"))for(let e of Pt)e(t)}function br(t){return Pt.add(t),()=>Pt.delete(t)}function Sr(t,e){return e.entityType!==void 0&&t.entityType!==e.entityType?!1:t.task?t.task===e.taskKey&&t.project===e.projectKey:t.project?t.project===e.projectKey:t.branchPath===e.branchPath}function dt(t){let e=()=>{};return{promise:new Promise(n=>{e=br(o=>{Sr(o,t)&&(e(),n(o))})}),cancel:e}}async function F(t,e,r){let n=`${w(t)}/projects/${e}/tasks/${r}`;return(await y(n,{cookie:t.cookie})).body??null}var Ft=["RUNNING","BUILDING","SCHEDULED","QUEUED"],Kt=["QUEUED","SCHEDULED","RUNNING"],vr=["Promoted","Completed"],Xe=5e3;function Ot(t){return new Promise(e=>setTimeout(e,t))}async function Tr(t,e,r){let n=0;for(;;){let{done:o,value:s}=await t();if(o)return{value:s,timedOut:!1};if(n>=r)return{value:s,timedOut:!0};n++,await Ot(e)}}function Ar(){let t=[9e4];for(let e=0;e<3;e++)t.push(1e4);for(let e=0;e<12;e++)t.push(5e3);return t}var wr=Ar(),Rr=180;function $r(){let t=[3e5];for(let e=0;e<5;e++)t.push(6e4);for(let e=0;e<10;e++)t.push(3e4);return t}var Er=$r(),jr=900;async function to(t,e,r,n,o){let s=r*1e3,i=Date.now(),a=0;for(;;){let c=e[Math.min(a,e.length-1)],d=n?dt(n):void 0,l=await Promise.race(d?[Ot(c).then(()=>{}),d.promise]:[Ot(c).then(()=>{})]);if(d?.cancel(),l){let g=l.event;o?.(`[${new Date().toISOString()}] woken by notification${g?`: ${g}`:""}`)}let{done:u,value:f}=await t();if(u)return{value:f,timedOut:!1};if(Date.now()-i>=s)return{value:f,timedOut:!0};a++}}async function eo(t,e,r){let n=await F(t,e,r);if(!n)return{error:`Could not fetch task ${e}/${r}.`};if(n.status&&vr.includes(n.status))return{error:`Task ${e}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${w(t)}/projects/${e}/tasks/${r}`;await y(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:t.cookie})}return{}}async function Lt(t,e,r){let n=`${w(t)}/projects/${e}/tasks/${r}/classifications/status/cache-evict`;return await y(n,{method:"POST",body:{},cookie:t.cookie}),(await F(t,e,r))?.latestClassificationJson}async function Qe(t,e,r,n,o){let s,{value:i,timedOut:a}=await to(async()=>{let d=(await Lt(t,e,r))?.status;return d!==s&&(s=d,t.onLog?.(`[${new Date().toISOString()}] classify ${e}/${r}: status ${d??"unknown"}`)),{done:!(!d||Ft.includes(d)),value:d}},wr,o,{entityType:"Classification",projectKey:e,taskKey:r,branchPath:n},t.onLog);return{finalStatus:i,timedOut:a}}async function Nt(t,e,r){let n=`${A(t)}/${e}/classifications`,o=await y(n,{cookie:t.cookie});if(o.body?.items?.length)return o.body.items.find(s=>s.id===r)??o.body.items[o.body.items.length-1]}async function oo(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,i=await Lt(t,o,s);return i?{statusCode:200,body:{hasClassification:!0,jobId:i.id,status:i.status,running:Ft.includes(i.status),latestClassificationJson:i}}:{statusCode:200,body:{hasClassification:!1}}}async function no(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await eo(t,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=e.timeoutSeconds??Rr,d=await Lt(t,o,s),l=d?.status,u=d?.id;if(u&&l&&Ft.includes(l)){t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:E}=await Qe(t,o,s,i,c),Y=await Nt(t,i,u),bt={accepted:!1};return!E&&j==="COMPLETED"&&(bt=await Dt(t,i,o,s,u)),t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: attached job ${u} final status ${j??"unknown"}${E?" (timed out waiting)":""}, save ${JSON.stringify(bt)}`),{statusCode:200,body:{jobId:u,finalStatus:j,timedOut:E,details:Y,save:bt,attachedToExisting:!0}}}if(u&&l==="COMPLETED"){t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await Nt(t,i,u),E=await Dt(t,i,o,s,u);return t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: accepted existing job ${u}, save ${JSON.stringify(E)}`),{statusCode:200,body:{jobId:u,finalStatus:"COMPLETED",timedOut:!1,details:j,save:E,acceptedExisting:!0}}}let f=`${w(t)}/projects/${o}/tasks/${s}/classifications`,g=await y(f,{method:"POST",body:{},cookie:t.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!g.body?.id)return t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: start failed (HTTP ${g.statusCode}) \u2014 raw body: ${g.rawBody}`),{statusCode:g.statusCode||500,body:{error:"Failed to start classification.",details:g.body??g.rawBody}};t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: started (${g.body.status??"unknown"})`);let C=g.body.id;if(!e.wait)return{statusCode:200,body:{jobId:C,status:g.body.status}};let{finalStatus:x,timedOut:h}=await Qe(t,o,s,i,c),T=await Nt(t,i,C),P={accepted:!1};return!h&&x==="COMPLETED"&&(P=await Dt(t,i,o,s,C)),t.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: final status ${x??"unknown"}${h?" (timed out waiting)":""}, save ${JSON.stringify(P)}`),{statusCode:200,body:{jobId:C,finalStatus:x,timedOut:h,details:T,save:P}}}var Pr=["SAVED","STALE","SAVE_FAILED"],Nr=120;async function Dt(t,e,r,n,o){let s=`${A(t)}/${e}/classifications/${o}`,i=await y(s,{method:"PUT",body:{status:"SAVED"},cookie:t.cookie});if(i.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(i.statusCode<200||i.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${i.statusCode}).`};let a=Math.ceil(Nr*1e3/Xe),{value:c,timedOut:d}=await Tr(async()=>{let u=(await y(s,{cookie:t.cookie})).body?.status;return{done:!!u&&Pr.includes(u),value:u}},Xe,a);return d?{accepted:!1,status:c,error:"Timed out waiting for classification results to save."}:c==="SAVED"?{accepted:!0,status:c}:{accepted:!1,status:c,error:c==="STALE"?"Report stale \u2014 re-classify and save.":"Saving classification failed."}}async function ro(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,a=(await F(t,o,s))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&Kt.includes(a)}}}async function Ze(t,e,r,n,o){let s,{value:i,timedOut:a}=await to(async()=>{let d=(await F(t,e,r))?.latestValidationStatus;return d!==s&&(s=d,t.onLog?.(`[${new Date().toISOString()}] validate-task ${e}/${r}: status ${d??"unknown"}`)),{done:!(!d||Kt.includes(d)),value:d}},Er,o,{entityType:"Validation",projectKey:e,taskKey:r,branchPath:n},t.onLog);return{finalStatus:i,timedOut:a}}async function so(t,e,r){let n=await k(t,e,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await eo(t,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=e.timeoutSeconds??jr,l=(await F(t,o,s))?.latestValidationStatus;if(l&&Kt.includes(l)){t.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: validation already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:x,timedOut:h}=await Ze(t,o,s,i,c);return t.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: attached run final status ${x??"unknown"}${h?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:x,timedOut:h,attachedToExisting:!0}}}let u=`${w(t)}/projects/${o}/tasks/${s}/validation`;typeof e.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${e.enableMrcmValidation}`);let f=await y(u,{method:"POST",body:{},cookie:t.cookie});if(f.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(f.statusCode<200||f.statusCode>=300)return{statusCode:f.statusCode,body:{error:"Failed to start validation.",details:f.body}};if(t.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: started`),!e.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:g,timedOut:C}=await Ze(t,o,s,i,c);return t.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: final status ${g??"unknown"}${C?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:g,timedOut:C}}}async function io(t,e={}){let r=e.lightweight!==void 0?`?lightweight=${e.lightweight}`:"",n=`${w(t)}/projects${r}`;return(await y(n,{cookie:t.cookie})).body??[]}async function ao(t,e){let r=`${w(t)}/projects/${e}/tasks`;return(await y(r,{cookie:t.cookie})).body??[]}async function co(t,e={}){let r=e.excludePromoted!==void 0?`?excludePromoted=${e.excludePromoted}`:"",n=`${w(t)}/projects/my-tasks${r}`;return(await y(n,{cookie:t.cookie})).body??[]}async function lo(t,e){let r=`${w(t)}/projects/${e.projectKey}/tasks`,n={summary:e.summary};e.description!==void 0&&(n.description=e.description),e.assigneeUsername&&(n.assignee={username:e.assigneeUsername});let o=await y(r,{method:"POST",body:n,cookie:t.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to create task in ${e.projectKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}var Dr=["FORWARD","DIVERGED"];async function Or(t,e){if(!e)return!1;let r=`${A(t)}/branches/${encodeURIComponent(e)}`,n=await y(r,{cookie:t.cookie});return Dr.includes(n.body?.state??"")}var Fr=["Promoted","Completed"];async function uo(t,e){let r=`${w(t)}/projects/${e.projectKey}/tasks/${e.taskKey}`,n=await y(r,{cookie:t.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${e.projectKey}/${e.taskKey} (HTTP ${n.statusCode}).`};let o=n.body.status;if(o&&Fr.includes(o))return{statusCode:409,error:`${e.projectKey}/${e.taskKey} has status ${o} \u2014 its work is already in the project, so the task cannot be deleted.`};if(o==="Deleted")return{statusCode:200,task:n.body,alreadyDeleted:!0};let s=await Or(t,n.body.branchPath),i=await y(r,{method:"PUT",body:{status:"DELETED"},cookie:t.cookie});return i.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:i.statusCode<200||i.statusCode>=300||!i.body?{statusCode:i.statusCode||500,error:`Failed to delete ${e.projectKey}/${e.taskKey} (HTTP ${i.statusCode})${i.rawBody?`: ${i.rawBody}`:""}`}:{statusCode:i.statusCode,task:i.body,hadUnpromotedChanges:s}}async function po(t,e){let r=`${w(t)}/projects/tasks/search?projectKeys=${encodeURIComponent(e)}&statuses=Deleted`,n=await y(r,{cookie:t.cookie});return Array.isArray(n.body)?n.body:[]}var Kr="IN_PROGRESS";async function mo(t,e){let r=`${w(t)}/projects/${e.projectKey}/tasks/${e.taskKey}`,n=await y(r,{cookie:t.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${e.projectKey}/${e.taskKey} (HTTP ${n.statusCode}).`};if(n.body.status!=="Deleted")return{statusCode:200,task:n.body,notDeleted:!0};let o=await y(r,{method:"PUT",body:{status:Kr},cookie:t.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to recover ${e.projectKey}/${e.taskKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}function fo(t){if(t==="o")return{type:"open"};if(t==="h")return{type:"heartbeat"};if(t.startsWith("a"))try{return{type:"message",messages:JSON.parse(t.slice(1))}}catch{return{type:"unknown",raw:t}}if(t.startsWith("c"))try{let[e,r]=JSON.parse(t.slice(1));return{type:"close",code:e,reason:r}}catch{return{type:"unknown",raw:t}}return{type:"unknown",raw:t}}function Bt(t){return JSON.stringify([t])}function go(t=Math.random){let e=String(Math.floor(t()*1e3)).padStart(3,"0"),r="abcdefghijklmnopqrstuvwxyz0123456789",n="";for(let o=0;o<8;o++)n+=r[Math.floor(t()*r.length)];return`${e}/${n}/websocket`}function Mt(t,e={},r=""){let n=Object.entries(e).map(([o,s])=>`${o}:${s}`);return[t,...n,"",r].join(`
|
|
3
|
-
`)+"\0"}function
|
|
2
|
+
"use strict";var tr=Object.create;var ne=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var nr=Object.getOwnPropertyNames;var rr=Object.getPrototypeOf,sr=Object.prototype.hasOwnProperty;var ir=(e,t)=>{for(var r in t)ne(e,r,{get:t[r],enumerable:!0})},rt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of nr(t))!sr.call(e,o)&&o!==r&&ne(e,o,{get:()=>t[o],enumerable:!(n=or(t,o))||n.enumerable});return e};var v=(e,t,r)=>(r=e!=null?tr(rr(e)):{},rt(t||!e||!e.__esModule?ne(r,"default",{value:e,enumerable:!0}):r,e)),ar=e=>rt(ne({},"__esModule",{value:!0}),e);var ps={};ir(ps,{COMMANDS:()=>nt,main:()=>er,parsePositionals:()=>Qn});module.exports=ar(ps);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"}},cr={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},re=Object.keys(U);function st(e){return cr[e.trim().toLowerCase()]??null}var Y="uat",fs=U.uat.imsEndpoint,gs=U.uat.terminologyServerEndpoint,ys=U.uat.authoringServicesEndpoint;var dr=v(require("http")),lr=v(require("https"));function k(e,t={}){let{method:r="GET",cookie:n,body:o,headers:s={},timeoutMs:i=15e3}=t;return new Promise((a,c)=>{let d;try{d=new URL(e)}catch(C){c(C);return}let l=d.protocol==="https:"?lr:dr,u=o!==void 0?JSON.stringify(o):void 0,f={accept:"application/json",...s};if(u!==void 0&&(f["content-type"]="application/json",f["content-length"]=String(Buffer.byteLength(u))),n){let C=n.replace(/[^\x20-\x7e\t]/g,"");C&&(f.cookie=C)}let g=l.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:f},C=>{let I="";C.on("data",h=>{I+=h}),C.on("end",()=>{let h=C.statusCode??0,N=(C.headers["content-type"]??"").includes("application/json"),E=null,j=!1;if(I)try{E=JSON.parse(I)}catch{j=!N}a({statusCode:h,body:E,rawBody:I,sessionExpired:j})})});g.on("error",c),g.setTimeout(i,()=>{g.destroy(new Error(`Request to ${e} timed out after ${i}ms`))}),u!==void 0&&g.write(u),g.end()})}var L="900000000000509007",z="900000000000508004";var it={[L]:"en-us",[z]:"en-gb"},at={[L]:"true",[z]:"true"},ur={},pr={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:it,dialectDefaults:at,readOnlyDialects:ur,defaultLanguage:"en"};function ct(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return pr;let t={[L]:"en-us"},r={},n={},o=[];for(let c of Object.keys(e)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let l=d[1];t[String(e[c])]=l,o.length===0&&o.push(l)}}let s=e.requiredLanguageRefsets;if(Array.isArray(s))for(let c of s){if(typeof c!="object"||c===null)continue;let d=null,l=null;for(let[C,I]of Object.entries(c))C.length===2&&(d=C,l=String(I));if(!d||!l)continue;let u=c.dialectName;t[l]=typeof u=="string"?u:d;let f=c.default;f==="true"&&!o.includes(d)&&o.push(d),f!=null&&(r[l]=String(f));let g=c.readOnly;g!=null&&(n[l]=String(g))}let i=e.optionalLanguageRefsets;if(Array.isArray(i))for(let c of i)c&&typeof c=="object"&&"refsetId"in c&&(t[String(c.refsetId)]=String(c.language??""));let a=!!e.useInternationalLanguageRefsets;return{isExtension:!0,useInternationalLanguageRefsets:a,dialects:a?it:t,dialectDefaults:a?at:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function ve(e,t,r,n){let o={};for(let s of Object.keys(e.dialects)){let i=e.dialects[s];e.isExtension&&!r?i.includes(n)?o[s]="PREFERRED":i.includes(e.defaultLanguage)&&(o[s]="ACCEPTABLE"):i.includes(n)&&(o[s]=t),e.dialectDefaults[s]==="false"&&!r&&delete o[s],e.readOnlyDialects[s]==="true"&&delete o[s]}return o}function dt(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[L]:"PREFERRED"}:ve(e,"PREFERRED",t,"en")}var mr="900000000000207008";function lt(e){return e.replace(/\/$/,"")}function T(e){return lt(e.terminologyServerEndpoint)}function R(e){return lt(e.authoringServicesEndpoint)}function ut(e){return`${new URL(R(e)).origin}/authoring-traceability-service`}function _(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function y(e,t,r){let n=t.projectKey||r?.projectKey,o=t.taskKey||r?.taskKey,s=!t.projectKey&&!t.taskKey,i=t.branchPath||(s?r?.branchPath:void 0);return!n||!o?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(i||(i=await fr(e,n,o)??void 0),i?{ok:!0,projectKey:n,taskKey:o,branchPath:i}:{ok:!1,error:`Could not resolve branch path for ${n}/${o}.`})}async function V(e,t){let r=T(e),n=await k(`${r}/branches/${encodeURIComponent(t)}`,{cookie:e.cookie});if(n.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode>=200&&n.statusCode<300)return{ok:!0,created:!1};if(n.statusCode!==404)return{ok:!1,error:`Could not check branch ${t} (HTTP ${n.statusCode}).`};let o=t.split("/").filter(Boolean),s=o[o.length-1],i=o.slice(0,-1).join("/");if(!s||!i)return{ok:!1,error:`Cannot create branch from path "${t}" \u2014 expected a parent and a name.`};let a=await k(`${r}/branches`,{method:"POST",body:{parent:i,name:s},cookie:e.cookie});return a.sessionExpired?{ok:!1,error:"IMS session expired \u2014 re-sign in."}:a.statusCode<200||a.statusCode>=300?{ok:!1,error:`Could not create branch ${t} (HTTP ${a.statusCode}).`}:{ok:!0,created:!0}}async function fr(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}`;return(await k(n,{cookie:e.cookie})).body?.branchPath??null}async function pt(e,t,r){let n=r?.get(t);if(n)return n;let o=`${R(e)}/projects/${t}`,i=(await k(o,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,i),i}async function B(e,t,r){let n=await pt(e,t,r),o=n.multipleModuleEditingDisabled,s=!o||o==="false";return n.expectedExtensionModules?.length&&s?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:mr}async function X(e,t,r){let n=await pt(e,t,r);return ct(n)}async function Te(e,t){let r=e.replace(/\/$/,"")+"/auth",n=await k(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 mt=v(require("crypto"));var gr="116680003";function Q(e,t,r,n,o="PREFERRED",s=!1){let i=e==="FSN"?dt(n,s):ve(n,o,s,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:i}}async function ft(e,t,r,n=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await y(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:s,taskKey:i,branchPath:a}=o,c=_(a),d=t.moduleId||await B(e,s,n),l=await X(e,s,n),u=t.preferredTerm||t.fsn,f=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,g={conceptId:null,moduleId:d,definitionStatus:"PRIMITIVE",active:!0,descriptions:[Q("FSN",f,d,l,"PREFERRED",!0),Q("SYNONYM",u,d,l,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:mt.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:d,relationships:[{active:!0,groupId:0,type:{conceptId:gr},target:{conceptId:t.parentConceptId}}]}]},C=`${T(e)}/browser/${c}/${s}/${i}/concepts/?validate=true`,I=await k(C,{method:"POST",body:g,cookie:e.cookie});if(I.sessionExpired){let N="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: SESSION EXPIRED`),{statusCode:401,body:{error:N}}}let h=I.body,A=h&&"conceptId"in h?h.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${i}: ${I.statusCode<300?"OK":"FAILED ("+I.statusCode+")"} \u2014 ${f}`+(A?` \u2192 ${A}`:"")),typeof A=="string"&&e.onValidationResults?.(A,h?.validationResults),{statusCode:I.statusCode,body:I.body}}function Z(e){return typeof e=="object"&&e!==null}function yr(e,t,r){let n=Array.isArray(e[r])?e[r]:[],o=[];for(let s of n){if(s.active===!1||typeof s.axiomId!="string")continue;(Array.isArray(s.relationships)?s.relationships:[]).forEach((a,c)=>{let d=a.type;if((Z(d)?d.conceptId:void 0)!==t)return;let u=a.target;o.push({axiomId:s.axiomId,relationshipId:typeof a.relationshipId=="string"?a.relationshipId:void 0,relationshipIndex:c,groupId:typeof a.groupId=="number"?a.groupId:0,targetId:Z(u)?u.conceptId:void 0,targetFsn:Z(u)&&Z(u.fsn)?u.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return o}async function se(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${T(e)}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await k(o,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(t.attributeType&&s.statusCode>=200&&s.statusCode<300&&Z(s.body)){let i=t.gci?"gciAxioms":"classAxioms",a=yr(s.body,t.attributeType,i);return{statusCode:s.statusCode,body:{conceptId:t.conceptId,attributeType:t.attributeType,gci:!!t.gci,matches:a}}}return{statusCode:s.statusCode,body:s.body}}async function ie(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o={limit:t.limit??50,expand:"fsn()"};t.term&&(o.termFilter=t.term),t.ecl&&(o.eclFilter=t.ecl),typeof t.active=="boolean"&&(o.activeFilter=t.active);let s=`${T(e)}/${n.branchPath}/concepts/search`,i=await k(s,{method:"POST",body:o,cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let a=(i.body?.items??[]).map(c=>({conceptId:c.conceptId,fsn:c.fsn?.term,pt:c.pt?.term,active:c.active,moduleId:c.moduleId}));return{statusCode:i.statusCode,body:{total:i.body?.total??a.length,items:a}}}async function gt(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=new URLSearchParams;typeof t.stated=="boolean"&&o.set("stated",String(t.stated)),typeof t.limit=="number"&&o.set("limit",String(t.limit)),typeof t.offset=="number"&&o.set("offset",String(t.offset));let s=o.toString(),i=`${T(e)}/${n.branchPath}/concepts/${t.conceptId}/references`+(s?`?${s}`:""),a=await k(i,{cookie:e.cookie});return a.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:a.statusCode,body:a.body}}var we=v(require("crypto"));function yt(e){return typeof e=="object"&&e!==null}function kr(e){let t=e.type,r=e.target,n=yt(t)?t.conceptId:void 0,o=yt(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function hr(e,t){let r=[...t];for(let n of e){let o=r.findIndex(s=>s.typeId===n.typeId&&s.targetId===n.targetId);if(o===-1)return!1;r.splice(o,1)}return!0}function kt(e,t,r){let n=new Map;for(let i of e){let a=typeof i.groupId=="number"?i.groupId:0,c=n.get(a);c?c.push(i):n.set(a,[i])}let o=[];for(let[i,a]of n){if(r!=null?i!==r:i===0)continue;let c=a.map(kr).filter(d=>d!=null);hr(t,c)&&o.push(i)}if(o.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(o.length>1)return{ok:!1,statusCode:409,error:`has ${o.length} role groups matching the given attributes (groupIds: ${o.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let s=o[0];return{ok:!0,groupId:s,relationships:n.get(s)}}var Cr=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],Ir=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],xr=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],br=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],Sr=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],Re=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function vt(e){return Re.includes(e)}function ee(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function ae(e){return typeof e=="object"&&e!==null}function ht(e){return ae(e)?ee(e,br):e}function Tt(e){if(!ae(e))return e;let t=ee(e,xr);return"type"in t&&(t.type=ht(t.type)),"target"in t&&(t.target=ht(t.target)),t}function vr(e){return ae(e)?ee(e,Ir):e}function Ct(e){if(!ae(e))return e;let t=ee(e,Sr);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(Tt)),t}function $e(e){let t=ee(e,Cr);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(vr)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(Tt)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(Ct)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(Ct)),t}async function w(e,t,r,n){let o=T(e),s=`${o}/browser/${t.branchPath}/concepts/${r}`,i=await k(s,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:i.body}};let a=i.body,c=n(a);if(c)return c;let d=_(t.branchPath),l=`${o}/browser/${d}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,u=await k(l,{method:"PUT",body:$e(a),cookie:e.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${u.statusCode<300?"OK":"FAILED ("+u.statusCode+")"} \u2014 ${r}`);let f=u.body;return e.onValidationResults?.(r,f?.validationResults),{statusCode:u.statusCode,body:u.body}}var It=["PREFERRED","ACCEPTABLE"];async function At(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&&!It.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${It.join(", ")}.`}};let o=await y(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await B(e,o.projectKey,n),i=await X(e,o.projectKey,n),a=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return w(e,o,t.conceptId,c=>{let d=Array.isArray(c.descriptions)?c.descriptions:[];return d.push(Q(t.type,a,s,i,t.acceptability??"ACCEPTABLE",!1)),c.descriptions=d,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 y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return w(e,n,t.conceptId,s=>{let i=Array.isArray(s.classAxioms)?s.classAxioms:[],a=i[o];if(!a)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${i.length}).`}};let c=Array.isArray(a.relationships)?a.relationships:[];return c.push({active:!0,groupId:t.groupId??0,type:{conceptId:t.typeId},target:{conceptId:t.targetId}}),a.relationships=c,null})}async function Rt(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 y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return w(e,n,t.conceptId,s=>{let i=Array.isArray(s.classAxioms)?s.classAxioms:[],a=i[o];return a?(a.definitionStatus=t.status,s.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${i.length}).`}}})}async function $t(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>(o.active=!1,o.inactivationIndicator=t.indicator,t.associationRefsetId&&t.associationTargetId&&(o.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null)):{statusCode:400,body:{error:n.error}}}async function jt(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&&!vt(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Re.join(", ")}.`}};let n=await y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(i.term=t.term),t.caseSignificance&&(i.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Et(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!vt(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Re.join(", ")}.`}};let n=await y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return i?(i.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}var Ae=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function xt(e){return Ae.includes(e)}function Nt(e){return e.descriptionId?!e.lang&&!e.us&&!e.gb?{statusCode:400,body:{error:`Entry for description ${e.descriptionId} must set at least one of lang, us, or gb.`}}:e.us&&!xt(e.us)?{statusCode:400,body:{error:`us must be one of: ${Ae.join(", ")}.`}}:e.gb&&!xt(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${Ae.join(", ")}.`}}:null:{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function Pt(e,t,r){let n=e.find(s=>s.descriptionId===r.descriptionId);if(!n)return{statusCode:404,body:{error:`Concept ${t} has no description ${r.descriptionId}.`}};r.lang&&(n.lang=r.lang);let o={...n.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete o[L]:o[L]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[z]:o[z]=r.gb),n.active!==!1&&Object.keys(o).length===0?{statusCode:400,body:{error:`Description ${r.descriptionId} would have an empty acceptabilityMap (Not Acceptable in every dialect) \u2014 an active description must be acceptable in at least one.`}}:(n.acceptabilityMap=o,null)}async function Dt(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=Nt(n);if(o)return o;let s=await y(e,t,r);return s.ok?w(e,s,t.conceptId,i=>{let a=Array.isArray(i.descriptions)?i.descriptions:[];return Pt(a,t.conceptId,n)}):{statusCode:400,body:{error:s.error}}}async function Ft(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};if(!Array.isArray(t.entries)||t.entries.length===0)return{statusCode:400,body:{error:"entries must be a non-empty array."}};for(let o of t.entries){let s=Nt(o);if(s)return s}let n=await y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[];for(let i of t.entries){let a=Pt(s,t.conceptId,i);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function Ot(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=Array.isArray(o.descriptions)?o.descriptions:[],i=s.findIndex(a=>a.descriptionId===t.descriptionId);return i===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.descriptions=s,null)}):{statusCode:400,body:{error:n.error}}}async function Kt(e,t,r){if(!t.conceptId||!t.descriptionId||!t.indicator)return{statusCode:400,body:{error:"conceptId, descriptionId, and indicator are required."}};let n=await y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return i?i.effectiveTime==null?{statusCode:409,body:{error:`Description ${t.descriptionId} has no effectiveTime (never versioned) \u2014 use delete-description instead.`}}:(i.active=!1,i.inactivationIndicator=t.indicator,i.acceptabilityMap={},t.associationRefsetId&&t.associationTargetId&&(i.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Lt(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 y(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await B(e,o.projectKey,n),i=await X(e,o.projectKey,n),a=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return w(e,o,t.conceptId,c=>{let d=Array.isArray(c.descriptions)?c.descriptions:[],l;if(t.descriptionId){if(l=d.find(u=>u.descriptionId===t.descriptionId),!l)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(l.type!=="FSN")return{statusCode:400,body:{error:`Description ${t.descriptionId} is a ${String(l.type)}, not an FSN.`}}}else{let u=d.filter(f=>f.type==="FSN"&&f.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.`}};l=u[0]}return l.effectiveTime==null?{statusCode:409,body:{error:`Description ${String(l.descriptionId)} has no effectiveTime (never versioned) \u2014 use update-description instead.`}}:(l.active=!1,l.inactivationIndicator=t.indicator,l.acceptabilityMap={},t.associationRefsetId&&t.associationTargetId&&(l.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),d.push(Q("FSN",a,s,i,"PREFERRED",!1)),c.descriptions=d,null)})}async function je(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 y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(a=>a.axiomId===t.axiomId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${t.axiomId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(i.relationships=t.relationships,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Bt(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 y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===t.axiomId);return i?i.effectiveTime!=null?{statusCode:409,body:{error:`GCI axiom ${t.axiomId} has effectiveTime ${String(i.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(i.relationships=t.relationships,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function Ee(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 y(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await B(e,o.projectKey,n);return w(e,o,t.conceptId,i=>{let a=Array.isArray(i.classAxioms)?i.classAxioms:[];return a.push({axiomId:we.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),i.classAxioms=a,null})}async function Mt(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 y(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=t.moduleId||await B(e,o.projectKey,n);return w(e,o,t.conceptId,i=>{let a=Array.isArray(i.gciAxioms)?i.gciAxioms:[];return a.push({axiomId:we.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),i.gciAxioms=a,null})}async function Ut(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=Array.isArray(o.classAxioms)?o.classAxioms:[],i=s.findIndex(a=>a.axiomId===t.axiomId);return i===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:s.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`Axiom ${t.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.classAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}async function Ne(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=Array.isArray(o.classAxioms)?o.classAxioms:[],i=s.find(c=>c.axiomId===t.axiomId);return i?i.active===!1?{statusCode:409,body:{error:`Axiom ${t.axiomId} is already inactive.`}}:s.filter(c=>c!==i&&c.active!==!1).length===0?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:(i.active=!1,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}var Tr="116680003";function bt(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 Ar(e){let t=[],r=Array.isArray(e.concepts)?e.concepts:[];for(let s of r)s?.id&&t.push({active:!0,groupId:0,type:{conceptId:Tr},target:{conceptId:s.id}});let n=Array.isArray(e.attributes)?e.attributes:[];for(let s of n)t.push(bt(s,0));return(Array.isArray(e.groups)?e.groups:[]).forEach((s,i)=>{let a=Array.isArray(s.attributes)?s.attributes:[];for(let c of a)t.push(bt(c,i+1))}),t}async function _t(e,t,r,n){let o=T(e),s=await k(`${o}/browser/${t.branchPath}/concepts/${r}`,{cookie:e.cookie});if(s.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{ok:!1,result:{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:s.body}}};let i=Array.isArray(s.body.classAxioms)?s.body.classAxioms:[],a;if(n){if(a=i.find(l=>l.axiomId===n),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${n}.`}}}}else{let l=i.filter(u=>u.active!==!1);if(l.length===0)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has no active class axiom.`}}};if(l.length>1)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has ${l.length} active class axioms \u2014 pass axiomId to pick which one.`}}};a=l[0]}let c=await k(`${o}/${t.branchPath}/concepts/${r}/authoring-form`,{cookie:e.cookie});if(c.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}};if(c.statusCode<200||c.statusCode>=300||!c.body)return{ok:!1,result:{statusCode:c.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:c.body}}};let d=Ar(c.body);return d.length===0?{ok:!1,result:{statusCode:409,body:{error:`Authoring form for ${r} produced no relationships \u2014 the concept likely hasn't been classified since its last stated edit. Run classify --wait first.`}}}:{ok:!0,value:{axiom:a,axiomId:a.axiomId,targetRelationships:d}}}function wr(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 St(e){let t=new Map;for(let o of e){if(o.active===!1)continue;let s=typeof o.groupId=="number"?o.groupId:0,i=t.get(s)??[];i.push(wr(o)),t.set(s,i)}let r=(t.get(0)??[]).slice().sort(),n=[];for(let[o,s]of t)o!==0&&n.push(s.slice().sort());return{ungrouped:r,groups:n}}function Vt(e,t){let r=St(e),n=St(t);if(r.ungrouped.join("|")!==n.ungrouped.join("|"))return!1;let o=r.groups.map(i=>i.join("|")).sort(),s=n.groups.map(i=>i.join("|")).sort();return o.join("||")===s.join("||")}async function qt(e,t,r,n=new Map){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await y(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let s=await _t(e,o,t.conceptId,t.axiomId);if(!s.ok)return s.result;let{axiom:i,axiomId:a,targetRelationships:c}=s.value,d=Array.isArray(i.relationships)?i.relationships:[];if(Vt(d,c))return{statusCode:200,body:{conceptId:t.conceptId,axiomId:a,alreadyConformed:!0}};if(!(i.effectiveTime!=null))return je(e,{conceptId:t.conceptId,axiomId:a,relationships:c,projectKey:o.projectKey,taskKey:o.taskKey},r);let u=await Ee(e,{conceptId:t.conceptId,relationships:c,moduleId:typeof i.moduleId=="string"?i.moduleId:void 0,definitionStatus:i.definitionStatus,projectKey:o.projectKey,taskKey:o.taskKey},r,n);if(u.statusCode<200||u.statusCode>=300)return u;let f=await Ne(e,{conceptId:t.conceptId,axiomId:a,projectKey:o.projectKey,taskKey:o.taskKey},r);return f.statusCode<200||f.statusCode>=300?{statusCode:f.statusCode,body:{error:`Added the transformed axiom but failed to inactivate published axiom ${a}: ${JSON.stringify(f.body)}`,addResult:u.body}}:{statusCode:f.statusCode,body:{replacedAxiomId:a,addResult:u.body,inactivateResult:f.body}}}async function q(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await _t(e,n,t.conceptId,t.axiomId);if(!o.ok)return o.result;let{axiom:s,axiomId:i,targetRelationships:a}=o.value,c=Array.isArray(s.relationships)?s.relationships:[],d=Vt(c,a);return{statusCode:200,body:{conceptId:t.conceptId,axiomId:i,conforms:d}}}async function Jt(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};if(!t.relationshipId&&t.relationshipIndex==null)return{statusCode:400,body:{error:"One of relationshipId or relationshipIndex is required."}};let n=await y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.axiomId===t.axiomId);if(!i)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(i.relationships)?i.relationships:[],c=t.relationshipId?a.findIndex(l=>l.relationshipId===t.relationshipId):t.relationshipIndex,d=c>=0?a[c]:void 0;return d?d.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${c}`} has effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.splice(c,1),i.relationships=a,null):{statusCode:404,body:{error:`Axiom ${t.axiomId} has no relationship ${t.relationshipId??`at index ${t.relationshipIndex}`}.`}}}):{statusCode:400,body:{error:n.error}}}async function Gt(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 y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(l=>l.axiomId===t.axiomId);if(!i)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(i.relationships)?i.relationships:[],c=kt(a,t.attributes,t.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${t.axiomId} ${c.error}`}};let d=c.relationships.find(l=>l.effectiveTime!=null);return d?{statusCode:409,body:{error:`Role group (groupId ${c.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(d.relationshipId)}) with effectiveTime ${String(d.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(i.relationships=a.filter(l=>(typeof l.groupId=="number"?l.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function Ht(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await y(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=Array.isArray(o.gciAxioms)?o.gciAxioms:[],i=s.findIndex(a=>a.axiomId===t.axiomId);return i===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:s[i].effectiveTime!=null?{statusCode:409,body:{error:`GCI axiom ${t.axiomId} has effectiveTime ${String(s[i].effectiveTime)} set (already versioned) \u2014 cannot delete.`}}:(s.splice(i,1),o.gciAxioms=s,null)}):{statusCode:400,body:{error:n.error}}}async function ce(e,t,r,n,o){let s=[],i=[];for(let a of r){let c=await q(e,{conceptId:a.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),d=c.body;if(c.statusCode<200||c.statusCode>=300||typeof d?.conforms!="boolean"){i.push({...a,error:d?.error??`HTTP ${c.statusCode}`});continue}d.conforms===n&&s.push({...a,axiomId:d.axiomId,conforms:d.conforms})}return{matched:s,skipped:i}}async function Wt(e,t,r){let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await ie(e,{...t,branchPath:n.branchPath},r);if(o.statusCode<200||o.statusCode>=300)return o;let s=o.body?.items??[],i=t.conformed===!0,a=s.map(l=>({conceptId:l.conceptId,fsn:l.fsn,pt:l.pt})),{matched:c,skipped:d}=await ce(e,n,a,i,r);return{statusCode:200,body:{branchPath:n.branchPath,totalSearched:s.length,conformed:i,matched:c.length,skipped:d.length,results:c,skippedConcepts:d}}}async function Yt(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=T(e),s=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await k(s,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:i.body}};if(i.body.effectiveTime!=null)return{statusCode:409,body:{error:`Concept ${t.conceptId} has effectiveTime ${String(i.body.effectiveTime)} set (already versioned) \u2014 cannot delete.`}};let a=`${o}/${n.branchPath}/concepts/${t.conceptId}`,c=await k(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 Rr(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 de(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=T(e),s=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await k(s,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:i.body}};let a=_(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,d=await k(c,{method:"POST",body:$e(i.body),cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(d.statusCode<200||d.statusCode>=300)return{statusCode:d.statusCode,body:{error:"Validation check failed.",details:d.body}};let l=Array.isArray(d.body)?Rr(d.body):[],u=await q(e,{conceptId:t.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),f=u.body;return u.statusCode>=200&&u.statusCode<300&&f?.conforms===!1&&l.push({conceptId:t.conceptId,componentId:f.axiomId,severity:"WARNING",message:"Axiom does not conform to the standard authoring form (Is-a the proximal primitive parent(s) plus every currently-inferred attribute) \u2014 run transform-axiom to fix."}),{statusCode:200,body:{conceptId:t.conceptId,validationResults:l,hasErrors:l.some(g=>g.severity==="ERROR"),hasWarnings:l.some(g=>g.severity==="WARNING")}}}var zt=200;async function $r(e,t,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${T(e)}/browser/${t}/concepts/bulk-load`,s=!0;for(let i=0;i<r.length;i+=zt){let a=r.slice(i,i+zt),c=await k(o,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){s=!1;continue}for(let d of c.body)n.set(d.conceptId,{fsn:d.fsn?.term,pt:d.pt?.term})}return{terms:n,resolved:s}}async function F(e,t,r){let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${ut(e)}/activities?size=500&onBranch=${encodeURIComponent(n.branchPath)}`,s=await k(o,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode===404)return{statusCode:200,body:{branchPath:n.branchPath,concepts:[],conceptsClassified:[]}};if(s.statusCode<200||s.statusCode>=300)return{statusCode:s.statusCode,body:{error:"Could not fetch traceability for branch.",details:s.body}};let i=new Map,a=new Map,c=(I,h,A,N)=>{let E=I.get(h);E?(N.forEach(j=>j&&E.componentSubTypes.add(j)),E.lastUpdatedTime=A):I.set(h,{conceptId:h,lastUpdatedTime:A,componentSubTypes:new Set(N.filter(j=>!!j))})};for(let I of s.body?.content??[])if(!(I.activityType!=="CONTENT_CHANGE"&&I.activityType!=="CLASSIFICATION_SAVE"))for(let h of I.conceptChanges??[]){let A=String(h.conceptId),N=h.componentChanges??[],E=N.map(W=>W.componentSubType);if(I.activityType==="CLASSIFICATION_SAVE"){c(a,A,I.commitDate,E);continue}let j=N.some(W=>W.componentSubType!=="INFERRED_RELATIONSHIP");c(j?i:a,A,I.commitDate,E)}for(let I of i.keys())a.delete(I);let d=[...new Set([...i.keys(),...a.keys()])],{terms:l,resolved:u}=await $r(e,n.branchPath,d),f=I=>[...I.values()].sort((h,A)=>(A.lastUpdatedTime??"").localeCompare(h.lastUpdatedTime??"")).map(h=>{let A=u&&!l.has(h.conceptId);return{conceptId:h.conceptId,fsn:l.get(h.conceptId)?.fsn,pt:l.get(h.conceptId)?.pt,...A?{deleted:!0}:{},lastUpdatedTime:h.lastUpdatedTime,changedComponentTypes:[...h.componentSubTypes]}}),g=f(i),C=f(a);return{statusCode:200,body:{branchPath:n.branchPath,...u?{summary:{concepts:g.length,conceptsDeleted:g.filter(I=>I.deleted).length,conceptsClassified:C.length}}:{},concepts:g,conceptsClassified:C}}}async function Xt(e,t,r){let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await F(e,t,r);if(o.statusCode<200||o.statusCode>=300){let u=o.body;return{statusCode:o.statusCode,body:{error:u.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=s.filter(u=>!u.deleted),a=t.conformed===!0,c=i.map(u=>({conceptId:u.conceptId,fsn:u.fsn})),{matched:d,skipped:l}=await ce(e,n,c,a,r);return{statusCode:200,body:{branchPath:n.branchPath,conformed:a,totalReviewed:i.length,matched:d.length,skipped:l.length,skippedDeleted:s.length-i.length,results:d,skippedConcepts:l}}}async function Qt(e,t,r){let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await F(e,t,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=[];for(let c of s){if(c.deleted){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"deleted"});continue}let d=await de(e,{conceptId:c.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),l=d.body;if(d.statusCode<200||d.statusCode>=300){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"failed",error:l.error??`HTTP ${d.statusCode}`});continue}let u=l.validationResults??[];i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:u.length===0?"clean":"issues",validationResults:u.length?u:void 0,hasErrors:l.hasErrors})}let a=c=>i.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:i.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:i}}}async function Zt(e,t,r){let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await F(e,t,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let s=o.body.concepts??[],i=[];for(let c of s){if(c.deleted){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"deleted"});continue}let d=await se(e,{conceptId:c.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),l=d.body;if(d.statusCode<200||d.statusCode>=300){i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"failed",error:l?.error??`HTTP ${d.statusCode}`});continue}i.push({conceptId:c.conceptId,fsn:c.fsn,outcome:"fetched",concept:d.body})}let a=c=>i.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:i.length,fetched:a("fetched"),skippedDeleted:a("deleted"),failed:a("failed")},concepts:i}}}var Pe=new Set;function eo(e){if(!(!e||typeof e!="object"))for(let t of Pe)t(e)}function jr(e){return Pe.add(e),()=>Pe.delete(e)}function Er(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 le(e){let t=()=>{};return{promise:new Promise(n=>{t=jr(o=>{Er(o,e)&&(t(),n(o))})}),cancel:t}}async function O(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}`;return(await k(n,{cookie:e.cookie})).body??null}var Ke=["RUNNING","BUILDING","SCHEDULED","QUEUED"],Le=["QUEUED","SCHEDULED","RUNNING"],Nr=["Promoted","Completed"],to=5e3;function Oe(e){return new Promise(t=>setTimeout(t,e))}async function Pr(e,t,r){let n=0;for(;;){let{done:o,value:s}=await e();if(o)return{value:s,timedOut:!1};if(n>=r)return{value:s,timedOut:!0};n++,await Oe(t)}}function Dr(){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 Fr=Dr(),Or=180;function Kr(){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 Lr=Kr(),Br=900;async function ro(e,t,r,n,o){let s=r*1e3,i=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],d=n?le(n):void 0,l=await Promise.race(d?[Oe(c).then(()=>{}),d.promise]:[Oe(c).then(()=>{})]);if(d?.cancel(),l){let g=l.event;o?.(`[${new Date().toISOString()}] woken by notification${g?`: ${g}`:""}`)}let{done:u,value:f}=await e();if(u)return{value:f,timedOut:!1};if(Date.now()-i>=s)return{value:f,timedOut:!0};a++}}async function so(e,t,r){let n=await O(e,t,r);if(!n)return{error:`Could not fetch task ${t}/${r}.`};if(n.status&&Nr.includes(n.status))return{error:`Task ${t}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${R(e)}/projects/${t}/tasks/${r}`;await k(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function Be(e,t,r){let n=`${R(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await k(n,{method:"POST",body:{},cookie:e.cookie}),(await O(e,t,r))?.latestClassificationJson}async function oo(e,t,r,n,o){let s,{value:i,timedOut:a}=await ro(async()=>{let d=(await Be(e,t,r))?.status;return d!==s&&(s=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||Ke.includes(d)),value:d}},Fr,o,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:i,timedOut:a}}async function De(e,t,r){let n=`${T(e)}/${t}/classifications`,o=await k(n,{cookie:e.cookie});if(o.body?.items?.length)return o.body.items.find(s=>s.id===r)??o.body.items[o.body.items.length-1]}async function io(e,t,r){let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,i=await Be(e,o,s);return i?{statusCode:200,body:{hasClassification:!0,jobId:i.id,status:i.status,running:Ke.includes(i.status),latestClassificationJson:i}}:{statusCode:200,body:{hasClassification:!1}}}async function ao(e,t,r){let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await so(e,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??Or,d=await Be(e,o,s),l=d?.status,u=d?.id;if(u&&l&&Ke.includes(l)){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:E,timedOut:j}=await oo(e,o,s,i,c),W=await De(e,i,u),Se={accepted:!1};return!j&&E==="COMPLETED"&&(Se=await Fe(e,i,o,s,u)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: attached job ${u} final status ${E??"unknown"}${j?" (timed out waiting)":""}, save ${JSON.stringify(Se)}`),{statusCode:200,body:{jobId:u,finalStatus:E,timedOut:j,details:W,save:Se,attachedToExisting:!0}}}if(u&&l==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: found job ${u} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let E=await De(e,i,u),j=await Fe(e,i,o,s,u);return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: accepted existing job ${u}, save ${JSON.stringify(j)}`),{statusCode:200,body:{jobId:u,finalStatus:"COMPLETED",timedOut:!1,details:E,save:j,acceptedExisting:!0}}}let f=`${R(e)}/projects/${o}/tasks/${s}/classifications`,g=await k(f,{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}/${s}: start failed (HTTP ${g.statusCode}) \u2014 raw body: ${g.rawBody}`),{statusCode:g.statusCode||500,body:{error:"Failed to start classification.",details:g.body??g.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: started (${g.body.status??"unknown"})`);let C=g.body.id;if(!t.wait)return{statusCode:200,body:{jobId:C,status:g.body.status}};let{finalStatus:I,timedOut:h}=await oo(e,o,s,i,c),A=await De(e,i,C),N={accepted:!1};return!h&&I==="COMPLETED"&&(N=await Fe(e,i,o,s,C)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${s}: final status ${I??"unknown"}${h?" (timed out waiting)":""}, save ${JSON.stringify(N)}`),{statusCode:200,body:{jobId:C,finalStatus:I,timedOut:h,details:A,save:N}}}var Mr=["SAVED","STALE","SAVE_FAILED"],Ur=120;async function Fe(e,t,r,n,o){let s=`${T(e)}/${t}/classifications/${o}`,i=await k(s,{method:"PUT",body:{status:"SAVED"},cookie:e.cookie});if(i.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(i.statusCode<200||i.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${i.statusCode}).`};let a=Math.ceil(Ur*1e3/to),{value:c,timedOut:d}=await Pr(async()=>{let u=(await k(s,{cookie:e.cookie})).body?.status;return{done:!!u&&Mr.includes(u),value:u}},to,a);return d?{accepted:!1,status:c,error:"Timed out waiting for classification results to save."}:c==="SAVED"?{accepted:!0,status:c}:{accepted:!1,status:c,error:c==="STALE"?"Report stale \u2014 re-classify and save.":"Saving classification failed."}}async function co(e,t,r){let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s}=n,a=(await O(e,o,s))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&Le.includes(a)}}}async function no(e,t,r,n,o){let s,{value:i,timedOut:a}=await ro(async()=>{let d=(await O(e,t,r))?.latestValidationStatus;return d!==s&&(s=d,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||Le.includes(d)),value:d}},Lr,o,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:i,timedOut:a}}async function lo(e,t,r){let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=await so(e,o,s);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??Br,l=(await O(e,o,s))?.latestValidationStatus;if(l&&Le.includes(l)){e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: validation already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:I,timedOut:h}=await no(e,o,s,i,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: attached run final status ${I??"unknown"}${h?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:I,timedOut:h,attachedToExisting:!0}}}let u=`${R(e)}/projects/${o}/tasks/${s}/validation`;typeof t.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let f=await k(u,{method:"POST",body:{},cookie:e.cookie});if(f.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(f.statusCode<200||f.statusCode>=300)return{statusCode:f.statusCode,body:{error:"Failed to start validation.",details:f.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:g,timedOut:C}=await no(e,o,s,i,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${s}: final status ${g??"unknown"}${C?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:g,timedOut:C}}}async function uo(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",n=`${R(e)}/projects${r}`;return(await k(n,{cookie:e.cookie})).body??[]}async function po(e,t){let r=`${R(e)}/projects/${t}/tasks`;return(await k(r,{cookie:e.cookie})).body??[]}async function mo(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",n=`${R(e)}/projects/my-tasks${r}`;return(await k(n,{cookie:e.cookie})).body??[]}async function fo(e,t){let r=`${R(e)}/projects/${t.projectKey}/tasks`,n={summary:t.summary};t.description!==void 0&&(n.description=t.description),t.assigneeUsername&&(n.assignee={username:t.assigneeUsername});let o=await k(r,{method:"POST",body:n,cookie:e.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to create task in ${t.projectKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}var _r=["FORWARD","DIVERGED"];async function Vr(e,t){if(!t)return!1;let r=`${T(e)}/branches/${encodeURIComponent(t)}`,n=await k(r,{cookie:e.cookie});return _r.includes(n.body?.state??"")}var qr=["Promoted","Completed"];async function go(e,t){let r=`${R(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await k(r,{cookie:e.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode}).`};let o=n.body.status;if(o&&qr.includes(o))return{statusCode:409,error:`${t.projectKey}/${t.taskKey} has status ${o} \u2014 its work is already in the project, so the task cannot be deleted.`};if(o==="Deleted")return{statusCode:200,task:n.body,alreadyDeleted:!0};let s=await Vr(e,n.body.branchPath),i=await k(r,{method:"PUT",body:{status:"DELETED"},cookie:e.cookie});return i.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:i.statusCode<200||i.statusCode>=300||!i.body?{statusCode:i.statusCode||500,error:`Failed to delete ${t.projectKey}/${t.taskKey} (HTTP ${i.statusCode})${i.rawBody?`: ${i.rawBody}`:""}`}:{statusCode:i.statusCode,task:i.body,hadUnpromotedChanges:s}}async function yo(e,t){let r=`${R(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,n=await k(r,{cookie:e.cookie});return Array.isArray(n.body)?n.body:[]}var Jr="IN_PROGRESS";async function ko(e,t){let r=`${R(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await k(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 k(r,{method:"PUT",body:{status:Jr},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 ho(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 Me(e){return JSON.stringify([e])}function Co(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 Ue(e,t={},r=""){let n=Object.entries(t).map(([o,s])=>`${o}:${s}`);return[e,...n,"",r].join(`
|
|
3
|
+
`)+"\0"}function Io(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
|
|
4
4
|
|
|
5
|
-
`),n=r===-1?
|
|
6
|
-
`),i=s[0],a={};for(let c of s.slice(1)){let d=c.indexOf(":");d!==-1&&(a[c.slice(0,d)]=c.slice(d+1))}return{command:i,headers:a,body:o}}var
|
|
5
|
+
`),n=r===-1?t:t.slice(0,r),o=r===-1?"":t.slice(r+2),s=n.split(`
|
|
6
|
+
`),i=s[0],a={};for(let c of s.slice(1)){let d=c.indexOf(":");d!==-1&&(a[c.slice(0,d)]=c.slice(d+1))}return{command:i,headers:a,body:o}}var bo=v(require("ws"));var xo=[1e3,2e3,5e3,1e4,3e4];function So(e,t={}){let r=t.createSocket??((l,u)=>new bo.default(l,u)),n=!1,o,s=0,i,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(n)return;let l=xo[Math.min(s,xo.length-1)];s+=1,i=setTimeout(d,l)};function d(){if(n)return;let u=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${Co()}`,f=r(u,a?{headers:{cookie:a}}:{});o=f,f.on("message",g=>{let C=ho(g.toString());if(C.type==="open"){f.send(Me(Ue("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(C.type==="close"){f.close();return}if(C.type==="message")for(let I of C.messages){let h=Io(I);if(h){if(h.command==="CONNECTED"){s=0;let A=`/topic/user/${e.login}/notifications`;f.send(Me(Ue("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:A})));continue}if(h.command==="MESSAGE"){try{e.onNotification(JSON.parse(h.body))}catch(A){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",A)}continue}h.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",h.headers,h.body)}}}),f.on("unexpected-response",(g,C)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${C.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),f.terminate()}),f.on("error",g=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",g.message)}),f.on("close",c)}return d(),{stop(){n=!0,i&&clearTimeout(i),o?.removeAllListeners(),o?.close()}}}function vo(e,t,r={}){let n=r.startRelay??So,o=r.onNotification??eo,s=n({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:o});return{stop:()=>s.stop()}}var Gr=60;async function To(e,t,r){let n=await y(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:s,branchPath:i}=n,a=t.timeoutSeconds??Gr,c=le({entityType:t.entityType,projectKey:o,taskKey:s,branchPath:i}),d,l=new Promise(g=>{d=setTimeout(()=>g({kind:"timeout"}),a*1e3)}),u=c.promise.then(g=>({kind:"notification",payload:g})),f=await Promise.race([u,l]);return c.cancel(),clearTimeout(d),f.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:f.payload}}}function 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 Lo=v(require("http")),Bo=require("child_process");var pe=v(require("fs")),Ao=v(require("os")),wo=v(require("path"));function Hr(){return wo.join(Ao.homedir(),"Library","Application Support","Google","Chrome","Local State")}function Wr(){let e=Hr();if(!pe.existsSync(e))return[];let t;try{t=JSON.parse(pe.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 ue=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 me(e,t=Wr()){if(!e){let n=t.find(o=>o.directoryName==="Default");if(n)return n;if(t.length)return t[0];throw new ue("Default",t)}let r=t.find(n=>n.directoryName===e||n.displayName.toLowerCase()===e.toLowerCase());if(!r)throw new ue(e,t);return r}var Fo=require("child_process"),Oo=require("util"),qe=v(require("fs")),ye=v(require("os")),Je=v(require("path"));var Ro=require("child_process"),$o=require("util"),fe=v(require("crypto")),M=v(require("fs")),Yr=(0,$o.promisify)(Ro.exec);function _e(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}async function jo(){let{stdout:e}=await Yr('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return e.trim()}function Eo(e){return fe.pbkdf2Sync(e,"saltysalt",1003,16,"sha1")}function No(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),s=r.subarray(3),i;try{let d=fe.createDecipheriv("aes-128-cbc",t,o);i=Buffer.concat([d.update(s),d.final()])}catch{return null}let a=i.length>32?i.subarray(32):null,c=i;return a&&_e(a)&&!_e(i)&&(c=a),_e(c)?c.toString("utf8"):null}function Po(e,t){M.copyFileSync(e,t);for(let r of["-wal","-shm"]){let n=e+r;M.existsSync(n)&&M.copyFileSync(n,t+r)}}function Do(e){for(let t of[e,e+"-wal",e+"-shm"])try{M.unlinkSync(t)}catch{}}var zr=(0,Oo.promisify)(Fo.exec),ge=class extends Error{},Ve=class extends Error{};function Xr(e){return Je.join(ye.homedir(),"Library","Application Support","Google","Chrome",e,"Cookies")}function Qr(){return qe.existsSync("/Applications/Google Chrome.app")}function Zr(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 Ge(e,t,r){let n=Xr(e);if(!qe.existsSync(n))return null;let o=Je.join(ye.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);Po(n,o);try{let s;try{s=await jo()}catch{return null}let i=Eo(s),a=u=>`'${u.replace(/'/g,"''")}'`,d=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${Zr(t).map(a).join(", ")}) AND name = ${a(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:l}=await zr(`sqlite3 "${o}" "${d}"`);return No(l.trim(),i)}catch{return null}finally{Do(o)}}function es(e){return new Promise(t=>setTimeout(t,e))}async function Ko(e,t={}){let r=t.platform??process.platform,n=t.isChromeInstalled??Qr;if(r!=="darwin")throw new ge(`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 ge("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??Ge,s=t.sleep??es,i=e.pollIntervalMs??750,a=e.timeoutMs??15e3,c=await o(e.profileDirectory,e.host,e.cookieName),d=Date.now()+a;for(;Date.now()<d;){let l=await o(e.profileDirectory,e.host,e.cookieName);if(l&&l!==c)return l;await s(i)}throw new Ve(`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 He(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}function ts(e,t){let r=n=>`'${n.replace(/'/g,"'\\''")}'`;(0,Bo.exec)(`open -a ${r("Google Chrome")} ${r(e)} --args --profile-directory=${r(t)}`)}function os(){return`<!DOCTYPE html>
|
|
7
7
|
<html>
|
|
8
8
|
<head>
|
|
9
9
|
<meta charset="utf-8">
|
|
@@ -14,19 +14,19 @@
|
|
|
14
14
|
<h3>You're signed in.</h3>
|
|
15
15
|
<p>Return to your terminal \u2014 the CLI is finishing sign-in automatically. You can close this tab.</p>
|
|
16
16
|
</body>
|
|
17
|
-
</html>`}function
|
|
18
|
-
Expected one of: ${et.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=M[e],n=t.imsEndpoint||r.imsEndpoint,o=t.terminologyServerEndpoint||r.terminologyServerEndpoint,s=t.authoringServicesEndpoint||r.authoringServicesEndpoint,i;try{i=new URL(n).hostname}catch{console.error(`Invalid --ims-endpoint: ${n}`),process.exitCode=1;return}let a=t.imsEndpoint?null:r.cookieName,c=t.cookieName||a||Gt(i),d=e===W&&!t.environment?`${e}, default`:e,l=[{url:n,label:"IMS",explicit:!!t.imsEndpoint},{url:o,label:"Terminology server",explicit:!!t.terminologyServerEndpoint},{url:s,label:"Authoring services",explicit:!!t.authoringServicesEndpoint}].map(C=>({...C,source:d})),u=await Wr(n,i,c,t.chromeProfile);if(u){yt({cookie:u.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:u.account,currentTask:null}),console.log(`${Mo(u.account)} (reused an existing Chrome session \u2014 no browser opened.)`),_o(l);return}console.log(`Opening Chrome to sign in to ${n} ...`);let f=await Fo({imsEndpoint:n,host:i,cookieName:c,chromeProfile:t.chromeProfile});if(!f){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let g=await vt(n,f.cookie).catch(()=>null);yt({cookie:f.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:g,currentTask:null}),console.log(Mo(g)),_o(l)}async function Vo(){Bo(),console.log("Signed out.")}var ht=v(require("fs")),kt=v(require("path"));async function qo(){let t=[kt.join(__dirname,"../../HELP.md"),kt.join(__dirname,"../HELP.md"),kt.join(process.cwd(),"HELP.md")];for(let e of t)try{if(ht.existsSync(e)){let r=ht.readFileSync(e,"utf8");console.log(r);return}}catch{}console.error("Could not locate HELP.md."),console.log(""),console.log("For help, see the README:"),console.log(" npm view authoring-cli readme"),console.log(""),console.log("Or visit: https://github.com/snomed/authoring-cli"),process.exit(1)}function p(){let t=Wt();return t||(console.error('Not signed in. Run "login" first.'),process.exit(1)),t}function m(t){return{cookie:t.cookie,terminologyServerEndpoint:t.terminologyServerEndpoint,authoringServicesEndpoint:t.authoringServicesEndpoint,imsEndpoint:t.imsEndpoint,onLog:e=>console.error(e)}}function Jo(t){return t.projectKey??t.key??"?"}async function Go(t){let e=p(),r=m(e),n=await io(r);if(t.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log("No projects available.");return}let o=Math.max(...n.map(s=>Jo(s).length))+1;for(let s of n){let i=s.title??"";console.log(`${Jo(s).padEnd(o)}${i?`"${i}"`:""}`)}}function Ct(t){return t.taskKey??t.key??"?"}function Ho(t){return t.assignee?.displayName??t.assignee?.username??"unassigned"}function zr(t){return t.projectKey||Ct(t).split("-")[0]||"?"}function zt(t,e){let r=new Map;for(let n of t){let o=e(n);r.set(o,(r.get(o)??0)+1)}return[...r].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0]))}function Xt(t,e){let r=Math.max(...e.map(([o])=>o.length)),n=Math.max(...e.map(([,o])=>String(o).length));console.log(""),console.log(`${t}:`);for(let[o,s]of e)console.log(` ${o.padEnd(r)} ${String(s).padStart(n)}`)}async function Yo(t){let e=p(),r=m(e),n=t.mine||!t.project,o=n?await co(r):await ao(r,t.project);if(n&&t.project){let l=t.project.toLowerCase();o=o.filter(u=>(u.projectKey??"").toLowerCase()===l||Ct(u).toLowerCase().startsWith(`${l}-`))}if(t.status){let l=t.status.trim().toLowerCase();o=o.filter(u=>(u.status??"").toLowerCase()===l)}let s=zt(o,zr),i=zt(o,Ho),a=zt(o,l=>l.status??"unknown");if(t.json){console.log(JSON.stringify(t.summary?{total:o.length,byProject:Object.fromEntries(s),byAssignee:Object.fromEntries(i),byStatus:Object.fromEntries(a)}:o,null,2));return}let c=[n?"assigned to you":null,t.project?`in project ${t.project}`:null,t.status?`with status "${t.status}"`:null].filter(Boolean);if(o.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(t.summary){console.log(`${o.length} task${o.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),s.length>1&&Xt("By project",s),!n&&i.length>1&&Xt("By assignee",i),a.length>1&&Xt("By status",a);return}let d=Math.max(...o.map(l=>Ct(l).length))+1;for(let l of o){let u=l.summary??l.title??"",f=l.status?` status=${l.status}`:"",g=n?"":` [${Ho(l)}]`;console.log(`${Ct(l).padEnd(d)}${u?`"${u}"`:""}${f}${g}`)}}async function Wo(t){let e=p(),r=m(e),n=e.account?.login??e.account?.username,o=t.unassigned?void 0:t.assignee||n,s=await lo(r,{projectKey:t.project,summary:t.summary,description:t.description,assigneeUsername:o});if(!s.task){console.error(s.error??`Failed to create task in ${t.project}.`),process.exitCode=1;return}let i=s.task,a=i.key??i.taskKey,c=i.branchPath;if(t.json)console.log(JSON.stringify(i,null,2));else{console.log(`\u2713 Created task ${t.project}/${a} "${i.summary??t.summary}"${i.status?` status=${i.status}`:""}`),c&&console.log(` branch: ${c}`);let d=i.assignee?.displayName??i.assignee?.username;console.log(` assignee: ${d??"unassigned"}`)}if(c){let d=await U(r,c);if(!d.ok){console.error(`Task created, but its branch could not be prepared: ${d.error}`),process.exitCode=1;return}d.created&&!t.json&&console.log(` created branch ${c}`)}if(!t.noSelect){if(!a||!c){console.error("Task created, but it could not be selected (no key/branchPath in the response) \u2014 use select-task."),process.exitCode=1;return}K({projectKey:t.project,taskKey:a,branchPath:c}),t.json||console.log(`\u2713 Current task set to ${t.project}/${a}`)}}async function zo(t){let e=p(),r=m(e),n=e.currentTask;if(!!t.project!=!!t.task){console.error("Pass --project and --task together, or neither to delete the currently selected task."),process.exitCode=1;return}let o=t.project||n?.projectKey,s=t.task||n?.taskKey;if(!o||!s){console.error('No task to delete: pass --project/--task, or select one with "select-task".'),process.exitCode=1;return}let i=await uo(r,{projectKey:o,taskKey:s});if(i.error){console.error(i.error),process.exitCode=1;return}i.alreadyDeleted?console.log(`${o}/${s} is already deleted.`):console.log(`\u2713 Deleted task ${o}/${s}`),i.hadUnpromotedChanges&&console.log(` note: its branch had changes that were never promoted. They still exist on ${i.task?.branchPath??"the task branch"}, but a deleted task appears in no listing \u2014 move it out of Deleted to reach them again.`),n&&n.projectKey===o&&n.taskKey===s&&(K(null),console.log(" cleared the current task selection."))}async function Xo(t){let e=p(),r=m(e);if(!t.task){let s=await po(r,t.project);if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){console.log(`No deleted tasks in ${t.project}.`);return}console.log(`${s.length} deleted task${s.length===1?"":"s"} in ${t.project} \u2014 pass --task <key> to recover one:`);for(let i of s){let a=i.assignee?.displayName??i.assignee?.username??"unassigned";console.log(` ${i.key} "${i.summary??""}" [${a}]`)}return}let n=await mo(r,{projectKey:t.project,taskKey:t.task});if(n.error){console.error(n.error),process.exitCode=1;return}if(n.notDeleted){console.log(`${t.project}/${t.task} is not deleted (status ${n.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${t.project}/${t.task} (status ${n.task?.status??"In Progress"})`);let o=n.task?.branchPath;if(o){let s=await U(r,o);if(!s.ok){console.error(`Task recovered, but its branch could not be prepared: ${s.error}`),process.exitCode=1;return}console.log(s.created?` created branch ${o}`:` branch ${o} still holds its content`)}t.noSelect||!o||(K({projectKey:t.project,taskKey:t.task,branchPath:o}),console.log(`\u2713 Current task set to ${t.project}/${t.task}`))}async function Qo(t){let e=p(),r=m(e),n=await F(r,t.project,t.task);if(!n||!n.branchPath){console.error(`Could not resolve task ${t.project}/${t.task} (no branchPath returned).`),process.exitCode=1;return}let o=await U(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${t.project}/${t.task}: ${o.error}`),process.exitCode=1;return}K({projectKey:t.project,taskKey:t.task,branchPath:n.branchPath}),console.log(`\u2713 Current task set to ${t.project}/${t.task} (${n.branchPath})`),o.created&&console.log(` created branch ${n.branchPath}`)}async function Zo(t){let e=p();if(!e.currentTask){console.log('No task currently selected. Run "select-task", or pass --project/--task explicitly to any command.');return}let{projectKey:r,taskKey:n,branchPath:o}=e.currentTask;console.log(`Current task: ${r}/${n} (${o})`),(t.project||t.task)&&((!t.project||t.project===r)&&(!t.task||t.task===n)||console.log(`Note: --project/--task (${t.project??"*"}/${t.task??"*"}) do not match the currently selected task.`))}async function tn(t){let e=p(),r=m(e),n=await me(r,{fsn:t.fsn,semanticTag:t.tag,preferredTerm:t.pt,parentConceptId:t.parent,moduleId:t.module,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300&&o.conceptId){console.log(`Created concept ${o.conceptId}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to create concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function en(t){let e=p(),r=m(e),n={term:t.term,ecl:t.ecl,active:t.active!==void 0?t.active==="true":void 0,limit:t.limit?Number(t.limit):void 0,projectKey:t.project,taskKey:t.task},o=t.checkAuthoringForm?await qe(r,{...n,conformed:t.conformed===!0},e.currentTask):await st(r,n,e.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to search concepts (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function on(t){let e=p(),r=m(e),n=await rt(r,{conceptId:t.id,projectKey:t.project,taskKey:t.task},e.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to get concept (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function nn(t){let e=p(),r=m(e),n=await ct(r,{conceptId:t.id,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to validate concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}let s=o.validationResults;if(!Array.isArray(s)||s.length===0){console.log(`No validation issues for concept ${t.id}.`);return}I(s),o.hasErrors&&(process.exitCode=1)}async function rn(t){let e=p(),r=m(e),n=t.checkAuthoringForm?await He(r,{projectKey:t.project,taskKey:t.task,conformed:t.conformed===!0},e.currentTask):await O(r,{projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to list concepts for review (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function sn(t){let e=p(),r=m(e),n=await Ye(r,{projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${n.statusCode}): ${o.error??JSON.stringify(o)}`),process.exitCode=1;return}if(t.json){console.log(JSON.stringify(n.body,null,2)),o.summary&&(o.summary.withIssues>0||o.summary.failed>0)&&(process.exitCode=1);return}let s=o.results??[],i=o.summary;if(s.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of s){let c=`${a.conceptId}${a.fsn?` "${a.fsn}"`:""}`;if(a.outcome==="deleted"){console.log(`\u2014 ${c} deleted on this branch \u2014 skipped`);continue}if(a.outcome==="failed"){console.log(`\u2717 ${c} could not be validated: ${a.error??"unknown error"}`);continue}if(a.outcome==="clean"){console.log(`\u2713 ${c}`);continue}console.log(`\u26A0 ${c}`),I(a.validationResults)}if(i){console.log("");let a=[`${i.validated} validated`,`${i.clean} clean`,`${i.withIssues} with issues`];i.skippedDeleted&&a.push(`${i.skippedDeleted} skipped (deleted on this branch)`),i.failed&&a.push(`${i.failed} failed`),console.log(a.join(", ")+".")}i&&(i.withIssues>0||i.failed>0)&&(process.exitCode=1)}async function an(t){let e=p(),r=m(e),n=await We(r,{projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to fetch concepts for review (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function cn(t){let e=p(),r=m(e),n=await ve(r,{conceptId:t.id,term:t.term,type:t.type,semanticTag:t.tag,moduleId:t.module,acceptability:t.acceptability,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added ${t.type} description to concept ${t.id}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function dn(t){let e=p(),r=m(e),n=await Te(r,{conceptId:t.id,typeId:t.type,targetId:t.target,groupId:t.group?Number(t.group):void 0,axiomIndex:t.axiomIndex?Number(t.axiomIndex):void 0,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added relationship (${t.type} -> ${t.target}) to concept ${t.id}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add relationship (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function ln(t){let e=p(),r=m(e),n=await _e(r,{conceptId:t.id,axiomId:t.axiomId,relationshipId:t.relationshipId,relationshipIndex:t.relationshipIndex?Number(t.relationshipIndex):void 0,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Removed relationship from axiom ${t.axiomId} on concept ${t.id}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to remove relationship (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function un(t){let e;try{e=JSON.parse(t.attributes)}catch(a){console.error(`--attributes must be valid JSON (an array of {"typeId":"...","targetId":"..."} objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await Ue(n,{conceptId:t.id,axiomId:t.axiomId,attributes:e,groupId:t.groupId!=null&&t.groupId!==""?Number(t.groupId):void 0,projectKey:t.project,taskKey:t.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed role group from axiom ${t.axiomId} on concept ${t.id}`),I(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to remove role group (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function pn(t){let e=p(),r=m(e),n=await Re(r,{conceptId:t.id,descriptionId:t.descriptionId,term:t.term,caseSignificance:t.caseSignificance,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated description ${t.descriptionId} on concept ${t.id}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to update description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function mn(t){let e=p(),r=m(e),n=await $e(r,{conceptId:t.id,descriptionId:t.descriptionId,caseSignificance:t.caseSignificance,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set case significance of description ${t.descriptionId} to ${t.caseSignificance}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set case significance (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function fn(t){let e=p(),r=m(e);if(t.entries){let i;try{i=JSON.parse(t.entries)}catch(l){console.error(`--entries is not valid JSON: ${l.message}`),process.exitCode=1;return}if(!Array.isArray(i)||i.length===0){console.error("--entries must be a non-empty JSON array of {descriptionId, lang?, us?, gb?} objects."),process.exitCode=1;return}let a=await Ne(r,{conceptId:t.id,entries:i,projectKey:t.project,taskKey:t.task},e.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${i.length} description(s) on concept ${t.id}`),I(c.validationResults);return}let d=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${d}`),process.exitCode=1;return}if(!t.descriptionId){console.error("Either --description-id (with --lang/--us/--gb) or --entries is required."),process.exitCode=1;return}let n=await Pe(r,{conceptId:t.id,descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){let i=[t.lang?`lang=${t.lang}`:void 0,t.us?`us=${t.us}`:void 0,t.gb?`gb=${t.gb}`:void 0].filter(Boolean);console.log(`Set acceptability of description ${t.descriptionId} (${i.join(", ")})`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set acceptability (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function gn(t){let e=p(),r=m(e),n=await we(r,{conceptId:t.id,indicator:t.indicator,associationRefsetId:t.associationRefset,associationTargetId:t.associationTarget,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated concept ${t.id}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to inactivate concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function yn(t){let e=p(),r=m(e),n=await Ae(r,{conceptId:t.id,status:t.status,axiomIndex:t.axiomIndex?Number(t.axiomIndex):void 0,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set definition status of concept ${t.id} to ${t.status}`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set definition status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function kn(t){let e;try{e=JSON.parse(t.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await $t(n,{conceptId:t.id,axiomId:t.axiomId,relationships:e,projectKey:t.project,taskKey:t.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated axiom ${t.axiomId} on concept ${t.id}`),I(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to update axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function hn(t){let e;try{e=JSON.parse(t.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await Oe(n,{conceptId:t.id,axiomId:t.axiomId,relationships:e,projectKey:t.project,taskKey:t.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated GCI axiom ${t.axiomId} on concept ${t.id}`),I(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to update GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Cn(t){let e;try{e=JSON.parse(t.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(e)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}let r=p(),n=m(r),o=await Fe(n,{conceptId:t.id,relationships:e,moduleId:t.moduleId,projectKey:t.project,taskKey:t.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(s.gciAxioms)?s.gciAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added GCI axiom to concept ${t.id}${c?` (axiomId ${c})`:""}`),I(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to add GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function xn(t){let e;try{e=JSON.parse(t.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(e)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}if(t.definitionStatus&&t.definitionStatus!=="PRIMITIVE"&&t.definitionStatus!=="FULLY_DEFINED"){console.error("--definition-status must be PRIMITIVE or FULLY_DEFINED."),process.exitCode=1;return}let r=p(),n=m(r),o=await Et(n,{conceptId:t.id,relationships:e,moduleId:t.moduleId,definitionStatus:t.definitionStatus,projectKey:t.project,taskKey:t.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(s.classAxioms)?s.classAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added class axiom to concept ${t.id}${c?` (axiomId ${c})`:""}`),I(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to add axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function In(t){let e=p(),r=m(e),n=await Je(r,{conceptId:t.id,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted concept ${t.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function bn(t){let e=p(),r=m(e),n=await De(r,{conceptId:t.id,descriptionId:t.descriptionId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted description ${t.descriptionId} from concept ${t.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Sn(t){let e=p(),r=m(e),n=await Ke(r,{conceptId:t.id,axiomId:t.axiomId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted axiom ${t.axiomId} from concept ${t.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function vn(t){let e=p(),r=m(e),n=await jt(r,{conceptId:t.id,axiomId:t.axiomId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated axiom ${t.axiomId} on concept ${t.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Tn(t){let e=p(),r=m(e),n=await Me(r,{conceptId:t.id,axiomId:t.axiomId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){if(o.alreadyConformed)console.log(`Concept ${t.id}'s axiom${o.axiomId?` ${o.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(o.replacedAxiomId){let i=Array.isArray(o.addResult?.classAxioms)?o.addResult.classAxioms.map(c=>c.axiomId).filter(Boolean):[],a=i.length>0?i[i.length-1]:void 0;console.log(`Transformed concept ${t.id} to authoring form: added axiom${a?` ${a}`:""} and inactivated published axiom ${o.replacedAxiomId}.`)}else console.log(`Transformed axiom${t.axiomId?` ${t.axiomId}`:""} on concept ${t.id} to authoring form.`),I(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to transform axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function An(t){let e=p(),r=m(e),n=await q(r,{conceptId:t.id,axiomId:t.axiomId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check authoring form for concept ${t.id} (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}if(o.conforms){console.log(`Concept ${t.id} conforms to authoring form (axiom ${o.axiomId}).`);return}console.log(`Concept ${t.id} does NOT conform to authoring form (axiom ${o.axiomId}) \u2014 run transform-axiom to fix.`),process.exitCode=1}async function wn(t){let e=p(),r=m(e),n=await Ve(r,{conceptId:t.id,axiomId:t.axiomId,projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted GCI axiom ${t.axiomId} from concept ${t.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete GCI axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}function J(t){let e=t.account?.login;return e?xo(m(t),e):(console.error("[authoring-cli] no login resolved from the signed-in account \u2014 notifications will only arrive via polling fallback, not a live push."),null)}async function Rn(t){let e=p(),r=m(e),n=J(e),o;try{o=await no(r,{wait:!!t.wait,timeoutSeconds:t.timeout?Number(t.timeout):void 0,projectKey:t.project,taskKey:t.task},e.currentTask)}finally{n?.stop()}let s=o.body;if(o.statusCode>=200&&o.statusCode<300){s.finalStatus!==void 0?(console.log(`Classification ${s.finalStatus}${s.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),s.details&&console.log(JSON.stringify(s.details,null,2)),s.save&&(s.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${s.save.error?`: ${s.save.error}`:""}${s.save.status?` (status: ${s.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${s.jobId} (${s.status})`),s.timedOut&&(process.exitCode=1);return}let i=s.details!==void 0?` \u2014 details: ${JSON.stringify(s.details)}`:"";console.error(`Failed to start classification (HTTP ${o.statusCode}): ${s.error??JSON.stringify(s)}${i}`),process.exitCode=1}async function $n(t){let e=p(),r=m(e),n=await oo(r,{projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check classification status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function En(t){let e=p(),r=m(e),n=J(e),o;try{o=await so(r,{enableMrcmValidation:t.enableMrcm,wait:!!t.wait,timeoutSeconds:t.timeout?Number(t.timeout):void 0,projectKey:t.project,taskKey:t.task},e.currentTask)}finally{n?.stop()}let s=o.body;if(o.statusCode>=200&&o.statusCode<300){s.finalStatus!==void 0?console.log(`Validation ${s.finalStatus}${s.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),s.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${o.statusCode}): ${s.error??JSON.stringify(s)}`),process.exitCode=1}async function jn(t){let e=p(),r=m(e),n=await ro(r,{projectKey:t.project,taskKey:t.task},e.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check validation status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Pn(t){let e=p(),r=m(e),n=J(e);try{let o=await Io(r,{projectKey:t.project,taskKey:t.task,entityType:t.entityType,timeoutSeconds:t.timeout?Number(t.timeout):void 0},e.currentTask),s=o.body;if(o.statusCode<200||o.statusCode>=300){let i=s.error?s.error:JSON.stringify(s);console.error(`Failed to watch for a notification (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2)),s.timedOut&&(process.exitCode=1)}finally{n?.stop()}}var te=v(require("os")),G=v(require("path"));var S=v(require("fs")),Qt=v(require("os")),b=v(require("path")),$="authoring-cli",D=["claude","codex"];function xt(t){let e=[b.resolve(t,"..","skills",$),b.resolve(t,"..","..","skills",$)];for(let r of e)if(S.existsSync(b.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${$}/SKILL.md in: ${e.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function Xr(t){let e=[];return S.existsSync(b.join(t,".claude"))&&e.push("claude"),S.existsSync(b.join(t,".codex"))&&e.push("codex"),e}function Q(t,e){if(t==="all")return[...D];if(t){let n=t.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),o=n.filter(s=>!D.includes(s));if(o.length)throw new Error(`Unknown --agent value(s): ${o.join(", ")}. Supported: ${D.join(", ")}, all.`);return n}let r=Xr(e);return r.length?r:["claude"]}var Dn="# authoring-cli \u2014 SNOMED CT authoring guidance";function Qr(t){let e=b.join(t,"SKILL.md"),r=b.join(t,"references","batch-authoring.md");return[Dn,"",`Read \`${e}\` now, and follow it for the rest of this session whenever you run the`,"`authoring-cli` command \u2014 before any concept creation, description/acceptability edit,","relationship or axiom edit, `classify`, or `validate-task`. It documents server-side","constraints and async behavior that fail or mislead in non-obvious ways, so reading it after","a command has already failed is too late.","",`Also read \`${r}\` when the task is a large, multi-session batch (tens to thousands of`,"concepts generated from a source list).","","Both files live inside the installed `authoring-cli` npm package, so they stay in step with","the CLI itself. If the paths above no longer exist, the package moved or was upgraded to a","different location \u2014 re-run `authoring-cli install-skill` to refresh this prompt.",""].join(`
|
|
19
|
-
`)}function
|
|
20
|
-
`)!==
|
|
21
|
-
`)?!1:r.every(n=>S.readFileSync(b.join(
|
|
17
|
+
</html>`}function Mo(e,t={}){let r=e.cookieName??He(e.host),n=t.openChrome??ts,o=t.resolveProfile??me,s=t.captureCookie??Ko,i=e.callbackTimeoutMs??12e4,a=o(e.chromeProfile);return new Promise((c,d)=>{let l=!1,u=g=>{l||(l=!0,f.close(),g())},f=Lo.createServer((g,C)=>{if((g.url||"/").split("?")[0]==="/callback"){C.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),C.end(os()),(async()=>{try{let h=await s({profileDirectory:a.directoryName,host:e.host,cookieName:r});u(()=>c({cookie:`${r}=${h}`}))}catch(h){u(()=>d(h))}})();return}C.writeHead(404),C.end()});f.listen(0,"127.0.0.1",()=>{let C=`http://localhost:${f.address().port}/callback`,I=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(C)}`;n(I,a.directoryName)}),f.on("error",g=>u(()=>d(g))),setTimeout(()=>u(()=>c(null)),i)})}var P=v(require("fs")),Uo=v(require("os")),We=v(require("path"));function _o(){return We.join(Uo.homedir(),".authoring-cli")}function Ye(){return We.join(_o(),"session.json")}function ze(){let e=Ye();if(!P.existsSync(e))return null;let t=P.readFileSync(e,"utf8");return JSON.parse(t)}function ke(e){P.mkdirSync(_o(),{recursive:!0,mode:448});let t={...e,updatedAt:new Date().toISOString()};P.writeFileSync(Ye(),JSON.stringify(t,null,2),{mode:384})}function Vo(){let e=Ye();P.existsSync(e)&&P.unlinkSync(e)}function K(e){let t=ze();if(!t)throw new Error('Not signed in \u2014 run "login" first.');ke({...t,currentTask:e})}async function ns(e,t,r,n){let o;try{o=me(n).directoryName}catch{return null}let s=await Ge(o,t,r).catch(()=>null);if(!s)return null;let i=`${r}=${s}`,a=await Te(e,i).catch(()=>null);return a?{cookie:i,account:a}:null}function qo(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 Jo(e){let t=Math.max(...e.map(r=>r.label.length));for(let{url:r,label:n,explicit:o,source:s}of e)console.log(` ${(n+":").padEnd(t+2)}${r} (${o?"from flag":s})`)}async function Go(e){let t=e.environment?st(e.environment):Y;if(!t){console.error(`Unknown environment: ${e.environment}
|
|
18
|
+
Expected one of: ${re.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,s=e.authoringServicesEndpoint||r.authoringServicesEndpoint,i;try{i=new URL(n).hostname}catch{console.error(`Invalid --ims-endpoint: ${n}`),process.exitCode=1;return}let a=e.imsEndpoint?null:r.cookieName,c=e.cookieName||a||He(i),d=t===Y&&!e.environment?`${t}, default`:t,l=[{url:n,label:"IMS",explicit:!!e.imsEndpoint},{url:o,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:s,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(C=>({...C,source:d})),u=await ns(n,i,c,e.chromeProfile);if(u){ke({cookie:u.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:u.account,currentTask:null}),console.log(`${qo(u.account)} (reused an existing Chrome session \u2014 no browser opened.)`),Jo(l);return}console.log(`Opening Chrome to sign in to ${n} ...`);let f=await Mo({imsEndpoint:n,host:i,cookieName:c,chromeProfile:e.chromeProfile});if(!f){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let g=await Te(n,f.cookie).catch(()=>null);ke({cookie:f.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:s,account:g,currentTask:null}),console.log(qo(g)),Jo(l)}async function Ho(){Vo(),console.log("Signed out.")}var Ce=v(require("fs")),he=v(require("path"));async function Wo(){let e=[he.join(__dirname,"../../HELP.md"),he.join(__dirname,"../HELP.md"),he.join(process.cwd(),"HELP.md")];for(let t of e)try{if(Ce.existsSync(t)){let r=Ce.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 p(){let e=ze();return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function m(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,onLog:t=>console.error(t)}}function Yo(e){return e.projectKey??e.key??"?"}async function zo(e){let t=p(),r=m(t),n=await uo(r);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log("No projects available.");return}let o=Math.max(...n.map(s=>Yo(s).length))+1;for(let s of n){let i=s.title??"";console.log(`${Yo(s).padEnd(o)}${i?`"${i}"`:""}`)}}function Ie(e){return e.taskKey??e.key??"?"}function Xo(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function rs(e){return e.projectKey||Ie(e).split("-")[0]||"?"}function Xe(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 Qe(e,t){let r=Math.max(...t.map(([o])=>o.length)),n=Math.max(...t.map(([,o])=>String(o).length));console.log(""),console.log(`${e}:`);for(let[o,s]of t)console.log(` ${o.padEnd(r)} ${String(s).padStart(n)}`)}async function Qo(e){let t=p(),r=m(t),n=e.mine||!e.project,o=n?await mo(r):await po(r,e.project);if(n&&e.project){let l=e.project.toLowerCase();o=o.filter(u=>(u.projectKey??"").toLowerCase()===l||Ie(u).toLowerCase().startsWith(`${l}-`))}if(e.status){let l=e.status.trim().toLowerCase();o=o.filter(u=>(u.status??"").toLowerCase()===l)}let s=Xe(o,rs),i=Xe(o,Xo),a=Xe(o,l=>l.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:o.length,byProject:Object.fromEntries(s),byAssignee:Object.fromEntries(i),byStatus:Object.fromEntries(a)}:o,null,2));return}let c=[n?"assigned to you":null,e.project?`in project ${e.project}`:null,e.status?`with status "${e.status}"`:null].filter(Boolean);if(o.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(e.summary){console.log(`${o.length} task${o.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),s.length>1&&Qe("By project",s),!n&&i.length>1&&Qe("By assignee",i),a.length>1&&Qe("By status",a);return}let d=Math.max(...o.map(l=>Ie(l).length))+1;for(let l of o){let u=l.summary??l.title??"",f=l.status?` status=${l.status}`:"",g=n?"":` [${Xo(l)}]`;console.log(`${Ie(l).padEnd(d)}${u?`"${u}"`:""}${f}${g}`)}}async function Zo(e){let t=p(),r=m(t),n=t.account?.login??t.account?.username,o=e.unassigned?void 0:e.assignee||n,s=await fo(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:o});if(!s.task){console.error(s.error??`Failed to create task in ${e.project}.`),process.exitCode=1;return}let i=s.task,a=i.key??i.taskKey,c=i.branchPath;if(e.json)console.log(JSON.stringify(i,null,2));else{console.log(`\u2713 Created task ${e.project}/${a} "${i.summary??e.summary}"${i.status?` status=${i.status}`:""}`),c&&console.log(` branch: ${c}`);let d=i.assignee?.displayName??i.assignee?.username;console.log(` assignee: ${d??"unassigned"}`)}if(c){let d=await V(r,c);if(!d.ok){console.error(`Task created, but its branch could not be prepared: ${d.error}`),process.exitCode=1;return}d.created&&!e.json&&console.log(` created branch ${c}`)}if(!e.noSelect){if(!a||!c){console.error("Task created, but it could not be selected (no key/branchPath in the response) \u2014 use select-task."),process.exitCode=1;return}K({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=p(),r=m(t),n=t.currentTask;if(!!e.project!=!!e.task){console.error("Pass --project and --task together, or neither to delete the currently selected task."),process.exitCode=1;return}let o=e.project||n?.projectKey,s=e.task||n?.taskKey;if(!o||!s){console.error('No task to delete: pass --project/--task, or select one with "select-task".'),process.exitCode=1;return}let i=await go(r,{projectKey:o,taskKey:s});if(i.error){console.error(i.error),process.exitCode=1;return}i.alreadyDeleted?console.log(`${o}/${s} is already deleted.`):console.log(`\u2713 Deleted task ${o}/${s}`),i.hadUnpromotedChanges&&console.log(` note: its branch had changes that were never promoted. They still exist on ${i.task?.branchPath??"the task branch"}, but a deleted task appears in no listing \u2014 move it out of Deleted to reach them again.`),n&&n.projectKey===o&&n.taskKey===s&&(K(null),console.log(" cleared the current task selection."))}async function tn(e){let t=p(),r=m(t);if(!e.task){let s=await yo(r,e.project);if(e.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){console.log(`No deleted tasks in ${e.project}.`);return}console.log(`${s.length} deleted task${s.length===1?"":"s"} in ${e.project} \u2014 pass --task <key> to recover one:`);for(let i of s){let a=i.assignee?.displayName??i.assignee?.username??"unassigned";console.log(` ${i.key} "${i.summary??""}" [${a}]`)}return}let n=await ko(r,{projectKey:e.project,taskKey:e.task});if(n.error){console.error(n.error),process.exitCode=1;return}if(n.notDeleted){console.log(`${e.project}/${e.task} is not deleted (status ${n.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${e.project}/${e.task} (status ${n.task?.status??"In Progress"})`);let o=n.task?.branchPath;if(o){let s=await V(r,o);if(!s.ok){console.error(`Task recovered, but its branch could not be prepared: ${s.error}`),process.exitCode=1;return}console.log(s.created?` created branch ${o}`:` branch ${o} still holds its content`)}e.noSelect||!o||(K({projectKey:e.project,taskKey:e.task,branchPath:o}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function on(e){let t=p(),r=m(t),n=await O(r,e.project,e.task);if(!n||!n.branchPath){console.error(`Could not resolve task ${e.project}/${e.task} (no branchPath returned).`),process.exitCode=1;return}let o=await V(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${o.error}`),process.exitCode=1;return}K({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 nn(e){let t=p();if(!t.currentTask){console.log('No task currently selected. Run "select-task", or pass --project/--task explicitly to any command.');return}let{projectKey:r,taskKey:n,branchPath:o}=t.currentTask;console.log(`Current task: ${r}/${n} (${o})`),(e.project||e.task)&&((!e.project||e.project===r)&&(!e.task||e.task===n)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function rn(e){let t=p(),r=m(t),n=await ft(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 s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to create concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function sn(e){let t=p(),r=m(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.checkAuthoringForm?await Wt(r,{...n,conformed:e.conformed===!0},t.currentTask):await ie(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 an(e){let t=p(),r=m(t),n=await se(r,{conceptId:e.id,attributeType:e.attributeType,gci:e.gci,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=p(),r=m(t),n=await gt(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 dn(e){let t=p(),r=m(t),n=await de(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to validate concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}let s=o.validationResults;if(!Array.isArray(s)||s.length===0){console.log(`No validation issues for concept ${e.id}.`);return}x(s),o.hasErrors&&(process.exitCode=1)}async function ln(e){let t=p(),r=m(t),n=e.checkAuthoringForm?await Xt(r,{projectKey:e.project,taskKey:e.task,conformed:e.conformed===!0},t.currentTask):await F(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to list concepts for review (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function un(e){let t=p(),r=m(t),n=await Qt(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${n.statusCode}): ${o.error??JSON.stringify(o)}`),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(n.body,null,2)),o.summary&&(o.summary.withIssues>0||o.summary.failed>0)&&(process.exitCode=1);return}let s=o.results??[],i=o.summary;if(s.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of s){let c=`${a.conceptId}${a.fsn?` "${a.fsn}"`:""}`;if(a.outcome==="deleted"){console.log(`\u2014 ${c} deleted on this branch \u2014 skipped`);continue}if(a.outcome==="failed"){console.log(`\u2717 ${c} could not be validated: ${a.error??"unknown error"}`);continue}if(a.outcome==="clean"){console.log(`\u2713 ${c}`);continue}console.log(`\u26A0 ${c}`),x(a.validationResults)}if(i){console.log("");let a=[`${i.validated} validated`,`${i.clean} clean`,`${i.withIssues} with issues`];i.skippedDeleted&&a.push(`${i.skippedDeleted} skipped (deleted on this branch)`),i.failed&&a.push(`${i.failed} failed`),console.log(a.join(", ")+".")}i&&(i.withIssues>0||i.failed>0)&&(process.exitCode=1)}async function pn(e){let t=p(),r=m(t),n=await Zt(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to fetch concepts for review (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function mn(e){let t=p(),r=m(t),n=await At(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 s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function fn(e){let t=p(),r=m(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 s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add relationship (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function gn(e){let t=p(),r=m(t),n=await Jt(r,{conceptId:e.id,axiomId:e.axiomId,relationshipId:e.relationshipId,relationshipIndex:e.relationshipIndex?Number(e.relationshipIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Removed relationship from axiom ${e.axiomId} on concept ${e.id}`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to remove relationship (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function yn(e){let t;try{t=JSON.parse(e.attributes)}catch(a){console.error(`--attributes must be valid JSON (an array of {"typeId":"...","targetId":"..."} objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await Gt(n,{conceptId:e.id,axiomId:e.axiomId,attributes:t,groupId:e.groupId!=null&&e.groupId!==""?Number(e.groupId):void 0,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed role group from axiom ${e.axiomId} on concept ${e.id}`),x(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to remove role group (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function kn(e){let t=p(),r=m(t),n=await jt(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 s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to update description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function hn(e){let t=p(),r=m(t),n=await Et(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 s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set case significance (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Cn(e){let t=p(),r=m(t);if(e.entries){let i;try{i=JSON.parse(e.entries)}catch(l){console.error(`--entries is not valid JSON: ${l.message}`),process.exitCode=1;return}if(!Array.isArray(i)||i.length===0){console.error("--entries must be a non-empty JSON array of {descriptionId, lang?, us?, gb?} objects."),process.exitCode=1;return}let a=await Ft(r,{conceptId:e.id,entries:i,projectKey:e.project,taskKey:e.task},t.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${i.length} description(s) on concept ${e.id}`),x(c.validationResults);return}let d=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${d}`),process.exitCode=1;return}if(!e.descriptionId){console.error("Either --description-id (with --lang/--us/--gb) or --entries is required."),process.exitCode=1;return}let n=await Dt(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){let i=[e.lang?`lang=${e.lang}`:void 0,e.us?`us=${e.us}`:void 0,e.gb?`gb=${e.gb}`:void 0].filter(Boolean);console.log(`Set acceptability of description ${e.descriptionId} (${i.join(", ")})`),x(o.validationResults);return}let s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set acceptability (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function In(e){let t=p(),r=m(t),n=await $t(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 s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to inactivate concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function xn(e){let t=p(),r=m(t),n=await Rt(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 s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set definition status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function bn(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await je(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated axiom ${e.axiomId} on concept ${e.id}`),x(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to update axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Sn(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=p(),n=m(r),o=await Bt(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated GCI axiom ${e.axiomId} on concept ${e.id}`),x(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to update GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function vn(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}let r=p(),n=m(r),o=await Mt(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(s.gciAxioms)?s.gciAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added GCI axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to add GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Tn(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=p(),n=m(r),o=await Ee(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,definitionStatus:e.definitionStatus,projectKey:e.project,taskKey:e.task},r.currentTask),s=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(s.classAxioms)?s.classAxioms.map(d=>d.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added class axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(s.validationResults);return}let i=s.error?s.error:s.validationResults?JSON.stringify(s.validationResults,null,2):JSON.stringify(s);console.error(`Failed to add axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function An(e){let t=p(),r=m(t),n=await Yt(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function wn(e){let t=p(),r=m(t),n=await Ot(r,{conceptId:e.id,descriptionId:e.descriptionId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted description ${e.descriptionId} from concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Rn(e){let t=p(),r=m(t),n=await Kt(r,{conceptId:e.id,descriptionId:e.descriptionId,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 description ${e.descriptionId} on concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate description (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function $n(e){let t=p(),r=m(t),n=await Lt(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,semanticTag:e.tag,indicator:e.indicator,associationRefsetId:e.associationRefset,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 s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to replace FSN (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function jn(e){let t=p(),r=m(t),n=await Ut(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted axiom ${e.axiomId} from concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function En(e){let t=p(),r=m(t),n=await Ne(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 s=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Nn(e){let t=p(),r=m(t),n=await qt(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 i=Array.isArray(o.addResult?.classAxioms)?o.addResult.classAxioms.map(c=>c.axiomId).filter(Boolean):[],a=i.length>0?i[i.length-1]:void 0;console.log(`Transformed concept ${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 s=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to transform axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}async function Pn(e){let t=p(),r=m(t),n=await q(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 s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check authoring form for concept ${e.id} (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}if(o.conforms){console.log(`Concept ${e.id} conforms to authoring form (axiom ${o.axiomId}).`);return}console.log(`Concept ${e.id} does NOT conform to authoring form (axiom ${o.axiomId}) \u2014 run transform-axiom to fix.`),process.exitCode=1}async function Dn(e){let t=p(),r=m(t),n=await Ht(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted GCI axiom ${e.axiomId} from concept ${e.id}`);return}let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete GCI axiom (HTTP ${n.statusCode}): ${s}`),process.exitCode=1}function J(e){let t=e.account?.login;return t?vo(m(e),t):(console.error("[authoring-cli] no login resolved from the signed-in account \u2014 notifications will only arrive via polling fallback, not a live push."),null)}async function Fn(e){let t=p(),r=m(t),n=J(t),o;try{o=await ao(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let s=o.body;if(o.statusCode>=200&&o.statusCode<300){s.finalStatus!==void 0?(console.log(`Classification ${s.finalStatus}${s.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),s.details&&console.log(JSON.stringify(s.details,null,2)),s.save&&(s.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${s.save.error?`: ${s.save.error}`:""}${s.save.status?` (status: ${s.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${s.jobId} (${s.status})`),s.timedOut&&(process.exitCode=1);return}let i=s.details!==void 0?` \u2014 details: ${JSON.stringify(s.details)}`:"";console.error(`Failed to start classification (HTTP ${o.statusCode}): ${s.error??JSON.stringify(s)}${i}`),process.exitCode=1}async function On(e){let t=p(),r=m(t),n=await io(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check classification status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Kn(e){let t=p(),r=m(t),n=J(t),o;try{o=await lo(r,{enableMrcmValidation:e.enableMrcm,wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let s=o.body;if(o.statusCode>=200&&o.statusCode<300){s.finalStatus!==void 0?console.log(`Validation ${s.finalStatus}${s.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),s.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${o.statusCode}): ${s.error??JSON.stringify(s)}`),process.exitCode=1}async function Ln(e){let t=p(),r=m(t),n=await co(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to check validation status (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Bn(e){let t=p(),r=m(t),n=J(t);try{let o=await To(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),s=o.body;if(o.statusCode<200||o.statusCode>=300){let i=s.error?s.error:JSON.stringify(s);console.error(`Failed to watch for a notification (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2)),s.timedOut&&(process.exitCode=1)}finally{n?.stop()}}var tt=v(require("os")),G=v(require("path"));var S=v(require("fs")),Ze=v(require("os")),b=v(require("path")),$="authoring-cli",D=["claude","codex"];function xe(e){let t=[b.resolve(e,"..","skills",$),b.resolve(e,"..","..","skills",$)];for(let r of t)if(S.existsSync(b.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${$}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function ss(e){let t=[];return S.existsSync(b.join(e,".claude"))&&t.push("claude"),S.existsSync(b.join(e,".codex"))&&t.push("codex"),t}function te(e,t){if(e==="all")return[...D];if(e){let n=e.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),o=n.filter(s=>!D.includes(s));if(o.length)throw new Error(`Unknown --agent value(s): ${o.join(", ")}. Supported: ${D.join(", ")}, all.`);return n}let r=ss(t);return r.length?r:["claude"]}var Un="# authoring-cli \u2014 SNOMED CT authoring guidance";function is(e){let t=b.join(e,"SKILL.md"),r=b.join(e,"references","batch-authoring.md");return[Un,"",`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 b.resolve(b.dirname(e),S.readlinkSync(e))}catch{return null}}function oe(e){try{return S.lstatSync(e)}catch{return null}}function et(e){let t=be(e);return t?S.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:oe(e)?.isDirectory()?"an existing directory":"an existing file"}function _n(e){let t=be(e);return t!==null&&b.basename(t)===$&&b.basename(b.dirname(t))==="skills"}function Vn(e){if(!oe(e)?.isFile())return!1;try{return S.readFileSync(e,"utf8").startsWith(Un)}catch{return!1}}function Mn(e){return S.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()).map(t=>b.relative(e,b.join(t.parentPath,t.name))).sort()}function qn(e,t){if(!t||!S.existsSync(t))return!1;try{let r=Mn(t);return r.join(`
|
|
20
|
+
`)!==Mn(e).join(`
|
|
21
|
+
`)?!1:r.every(n=>S.readFileSync(b.join(e,n)).equals(S.readFileSync(b.join(t,n))))}catch{return!1}}function as(e,t,r){let n=e.project?b.join(r,".claude","skills"):b.join(t,".claude","skills"),o=b.join(n,$),s=e.shippedSkillDir,i=e.project&&s.startsWith(r+b.sep)?b.relative(b.dirname(o),s):s,a=oe(o),c=!1;if(a){let d=be(o);if(d===s&&S.existsSync(d))return{agent:"claude",path:o,status:"already-current",kind:"symlink",detail:s};if(!(_n(o)||qn(o,s))&&!e.force)return{agent:"claude",path:o,status:"blocked",kind:"symlink",detail:et(o)};S.rmSync(o,{recursive:!0,force:!0}),c=!0}S.mkdirSync(n,{recursive:!0});try{return S.symlinkSync(i,o,"dir"),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"symlink",detail:i}}catch(d){let l=d.code;if(l!=="EPERM"&&l!=="EACCES")throw d;return S.cpSync(s,o,{recursive:!0}),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"copy",detail:"symlinks unavailable on this platform \u2014 copied instead; re-run install-skill after upgrading the CLI"}}}function cs(e,t){let r=b.join(t,".codex","prompts"),n=b.join(r,`${$}.md`),o=is(e.shippedSkillDir),s=oe(n),i=!1;if(s){if((s.isFile()?S.readFileSync(n,"utf8"):null)===o)return{agent:"codex",path:n,status:"already-current",kind:"pointer"};if(!Vn(n)&&!e.force)return{agent:"codex",path:n,status:"blocked",kind:"pointer",detail:et(n)};S.rmSync(n,{recursive:!0,force:!0}),i=!0}return S.mkdirSync(r,{recursive:!0}),S.writeFileSync(n,o,"utf8"),{agent:"codex",path:n,status:i?"replaced":"installed",kind:"pointer"}}function Jn(e){let t=e.homeDir??Ze.homedir(),r=e.cwd??process.cwd();return(e.agents??te(void 0,t)).map(o=>o==="claude"?as(e,t,r):cs(e,t))}function Gn(e){let t=e.homeDir??Ze.homedir(),r=e.cwd??process.cwd();return e.agents.map(n=>{let o=n==="claude"?b.join(e.project?b.join(r,".claude"):b.join(t,".claude"),"skills",$):b.join(t,".codex","prompts",`${$}.md`);if(!oe(o))return{agent:n,path:o,status:"not-registered"};if(!(n==="claude"?_n(o)||qn(o,e.shippedSkillDir):Vn(o))&&!e.force)return{agent:n,path:o,status:"left-alone",detail:`${et(o)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let i=be(o)??void 0;return S.rmSync(o,{recursive:!0,force:!0}),{agent:n,path:o,status:"removed",detail:i}})}function Hn(e){let t=tt.homedir();return e===t||e.startsWith(t+G.sep)?G.join("~",G.relative(t,e)):e}function ds(e){let t=Hn(e.path);switch(e.status){case"installed":case"replaced":return e.kind==="symlink"?`${t} (symlink -> ${Hn(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 Wn(e){let t=xe(__dirname),r=te(e.agent,tt.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; Codex prompts are always user-global.");let n=Jn({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),o=n.filter(a=>a.status==="installed"||a.status==="replaced"),s=n.filter(a=>a.status==="blocked");console.log(o.length?`Installed skill '${$}' for:`:s.length?`Could not install skill '${$}':`:`Skill '${$}' is already registered:`);for(let a of n)console.log(` ${a.agent.padEnd(7)} ${ds(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.`),s.length){process.exitCode=1;return}o.length&&(console.log(`
|
|
24
|
-
Restart your agent, then use /${$}.`),n.some(a=>a.kind==="symlink")&&console.log('The symlink points into this package, so "npm update -g authoring-cli" updates the skill too.'),console.log('To unregister: "authoring-cli uninstall-skill" \u2014 run it before "npm rm -g authoring-cli".'));let i=D.filter(a=>!r.includes(a));i.length&&!
|
|
25
|
-
Skipped ${i.join(", ")} (no config directory found). Pass --agent ${i.join(",")} to register anyway.`)}var
|
|
26
|
-
Restart your agent to drop /authoring-cli from its command list.`)}function ns(t){let e={};for(let r=0;r<t.length;r++){let n=t[r];if(n.startsWith("--")){let o=n.slice(2),s=t[r+1],i=s&&!s.startsWith("--")?t[++r]:"";e[o]=i}}return e}function Jn(t){let e=[];for(let r of t){if(r.startsWith("--"))break;e.push(r)}return e}var oe=[{name:"login",usage:`login [${et.join("|")}] [--ims-endpoint <url>] [--terminology-server-endpoint <url>] [--authoring-services-endpoint <url>] [--chrome-profile <name>] [--cookie-name <name>] (opens Chrome to sign in; automatically captures the session, macOS + Chrome only at launch. Environment defaults to ${W}; any --*-endpoint overrides that environment's value)`,run:(t,e)=>Uo({environment:e[0],imsEndpoint:t["ims-endpoint"],terminologyServerEndpoint:t["terminology-server-endpoint"],authoringServicesEndpoint:t["authoring-services-endpoint"],chromeProfile:t["chrome-profile"],cookieName:t["cookie-name"]})},{name:"logout",usage:"logout (deletes the locally stored session)",run:()=>Vo()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>qo()},{name:"install-skill",aliases:["install-skills"],usage:`install-skill [--agent ${D.join("|")}|all] [--project] [--force] (registers the authoring guidance skill bundled with this package with your AI agent, so /authoring-cli works alongside these commands \u2014 defaults to whichever agents are installed)`,run:t=>_n({agent:t.agent,project:"project"in t,force:"force"in t})},{name:"uninstall-skill",aliases:["uninstall-skills"],usage:`uninstall-skill [--agent ${D.join("|")}|all] [--project] [--force] (removes what install-skill registered \u2014 run this BEFORE "npm rm -g authoring-cli", since npm runs no uninstall hooks and this command goes away with the package)`,run:t=>Vn({agent:t.agent,project:"project"in t,force:"force"in t})},{name:"projects",usage:"projects [--json] (lists the projects available to you \u2014 no editor UI needed)",run:t=>Go({json:"json"in t})},{name:"tasks",usage:`tasks [--project <projectKey>] [--mine] [--status <status>] [--summary] [--json] (lists a project's tasks, or your own tasks across all projects if --project is omitted; --mine restricts to tasks assigned to you, --status filters by status e.g. "In Progress", --summary prints counts by project/assignee/status instead of one line per task)`,run:t=>Yo({project:t.project,mine:"mine"in t,status:t.status,summary:"summary"in t,json:"json"in t})},{name:"create-task",usage:'create-task --project <projectKey> --summary "<title>" [--description "<text>"] [--assignee <username>] [--unassigned] [--no-select] [--json] (creates a task via authoring-services and selects it; assigned to you unless overridden)',required:["project","summary"],run:t=>Wo({project:t.project,summary:t.summary,description:t.description,assignee:t.assignee,unassigned:"unassigned"in t,noSelect:"no-select"in t,json:"json"in t})},{name:"delete-task",usage:"delete-task [--project <projectKey> --task <taskKey>] (marks the task Deleted, defaulting to the selected task and clearing that selection; the branch and its content are left alone)",run:t=>zo({project:t.project,task:t.task})},{name:"recover-task",usage:"recover-task --project <projectKey> [--task <taskKey>] [--no-select] [--json] (without --task, lists the project's deleted tasks; with it, moves that task out of Deleted, keeps its branch content, and selects it)",required:["project"],run:t=>Xo({project:t.project,task:t.task,noSelect:"no-select"in t,json:"json"in t})},{name:"select-task",usage:"select-task --project <projectKey> --task <taskKey> (sets the task subsequent commands target when --project/--task are omitted)",required:["project","task"],run:t=>Qo({project:t.project,task:t.task})},{name:"current-task",usage:"current-task [--project <projectKey> --task <taskKey>] (prints the locally selected task; with --project/--task, notes whether they match \u2014 standalone has no editor UI to compare against instead)",run:t=>Zo({project:t.project,task:t.task})},{name:"create-concept",usage:'create-concept --fsn "<term>" --parent <SCTID> [--tag <semantic tag>] [--pt "<preferred term>"] [--module <moduleId>] [--project <projectKey> --task <taskKey>]',required:["fsn","parent"],run:t=>tn({fsn:t.fsn,tag:t.tag,pt:t.pt,parent:t.parent,module:t.module,project:t.project,task:t.task})},{name:"search-concepts",usage:"search-concepts [--term <text>] [--ecl <expr>] [--active true|false] [--limit N] [--check-authoring-form] [--conformed] [--project <projectKey> --task <taskKey>] (--check-authoring-form filters the search results down to concepts whose class axiom does \u2014 by default \u2014 NOT match transform-axiom's standard authoring form; add --conformed to see the ones that already do instead. Concepts that can't be checked \u2014 not yet classified since their last stated edit, an ambiguous multi-axiom concept \u2014 are reported separately under skippedConcepts rather than counted as either.)",run:t=>en({term:t.term,ecl:t.ecl,active:t.active,limit:t.limit,checkAuthoringForm:"check-authoring-form"in t,conformed:"conformed"in t,project:t.project,task:t.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--project <projectKey> --task <taskKey>]",required:["id"],run:t=>on({id:t.id,project:t.project,task:t.task})},{name:"validate-concept",usage:"validate-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (read-only check of the concept's current saved state \u2014 same convention rules the interactive editor runs on save, without saving anything)",required:["id"],run:t=>nn({id:t.id,project:t.project,task:t.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--check-authoring-form] [--conformed] [--project <projectKey> --task <taskKey>] (lists concepts with pending stated changes and concepts affected only by classification, derived from the task branch's traceability log, same as the Authoring Workbench's "Concepts for Review" tab; entries marked "deleted": true were created and then deleted on this branch and no longer exist. --check-authoring-form filters that list down to concepts whose class axiom does \u2014 by default \u2014 NOT match transform-axiom's standard authoring form; add --conformed to see the ones that already do instead; concepts that can't be checked are reported separately under skippedConcepts)`,run:t=>rn({checkAuthoringForm:"check-authoring-form"in t,conformed:"conformed"in t,project:t.project,task:t.task})},{name:"validate-review-concepts",usage:'validate-review-concepts [--project <projectKey> --task <taskKey>] [--json] (runs validate-concept on every concept with pending stated changes \u2014 the "concepts" list from get-concepts-for-review \u2014 skipping ones deleted on this branch, and prints a pass/issue tally; exits non-zero if any concept has issues)',run:t=>sn({project:t.project,task:t.task,json:"json"in t})},{name:"review-concepts",usage:"review-concepts [--project <projectKey> --task <taskKey>] (fetches the full concept representation \u2014 descriptions, relationships, axioms \u2014 for every concept with pending stated changes on the task, for an editorial review against SNOMED CT naming and modelling standards; see skills/authoring-cli/references/review-concepts.md. This is a data-gathering step, not a validation run \u2014 it performs no Snowstorm validation of its own)",run:t=>an({project:t.project,task:t.task})},{name:"add-description",usage:'add-description --id <SCTID> --term "<text>" --type FSN|SYNONYM [--tag <semanticTag>] [--module <id>] [--acceptability PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>]',required:["id","term","type"],run:t=>cn({id:t.id,term:t.term,type:t.type,tag:t.tag,module:t.module,acceptability:t.acceptability,project:t.project,task:t.task})},{name:"update-description",usage:'update-description --id <SCTID> --description-id <descriptionId> [--term "<text>"] [--case-significance <value>] [--project <projectKey> --task <taskKey>] (only if never versioned; reuses the existing descriptionId)',required:["id","description-id"],run:t=>pn({id:t.id,descriptionId:t["description-id"],term:t.term,caseSignificance:t["case-significance"],project:t.project,task:t.task})},{name:"set-case-significance",usage:"set-case-significance --id <SCTID> --description-id <descriptionId> --case-significance CASE_INSENSITIVE|INITIAL_CHARACTER_CASE_INSENSITIVE|ENTIRE_TERM_CASE_SENSITIVE [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id","description-id","case-significance"],run:t=>mn({id:t.id,descriptionId:t["description-id"],caseSignificance:t["case-significance"],project:t.project,task:t.task})},{name:"set-acceptability",usage:`set-acceptability --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--project <projectKey> --task <taskKey>] (at least one of --lang, --us, --gb required)
|
|
27
|
-
set-acceptability --id <SCTID> --entries '[{"descriptionId":"...","gb":"PREFERRED"},{"descriptionId":"...","gb":"ACCEPTABLE"}]' [--project <projectKey> --task <taskKey>] (applies all entries in one save)`,required:["id"],run:
|
|
28
|
-
`)}async function
|
|
24
|
+
Restart your agent, then use /${$}.`),n.some(a=>a.kind==="symlink")&&console.log('The symlink points into this package, so "npm update -g authoring-cli" updates the skill too.'),console.log('To unregister: "authoring-cli uninstall-skill" \u2014 run it before "npm rm -g authoring-cli".'));let i=D.filter(a=>!r.includes(a));i.length&&!e.agent&&console.log(`
|
|
25
|
+
Skipped ${i.join(", ")} (no config directory found). Pass --agent ${i.join(",")} to register anyway.`)}var ot=v(require("os")),H=v(require("path"));function Yn(e){let t=ot.homedir();return e===t||e.startsWith(t+H.sep)?H.join("~",H.relative(t,e)):e}function ls(e){let t=Yn(e.path);switch(e.status){case"removed":return e.detail?`${t} (was a symlink -> ${Yn(e.detail)})`:`${t} (removed)`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function zn(e){let t=e.agent?te(e.agent,ot.homedir()):[...D],r;try{r=xe(__dirname)}catch{r=void 0}let n=Gn({agents:t,project:e.project,force:e.force,shippedSkillDir:r}),o=n.filter(i=>i.status==="removed"),s=n.filter(i=>i.status==="left-alone");console.log(o.length?`Removed skill '${$}' registration for:`:s.length?`Left every registration of '${$}' in place:`:`No '${$}' registration found:`);for(let i of n)console.log(` ${i.agent.padEnd(7)} ${ls(i)}`);if(s.length){process.exitCode=1;return}o.length&&console.log(`
|
|
26
|
+
Restart your agent to drop /authoring-cli from its command list.`)}function us(e){let t={};for(let r=0;r<e.length;r++){let n=e[r];if(n.startsWith("--")){let o=n.slice(2),s=e[r+1],i=s&&!s.startsWith("--")?e[++r]:"";t[o]=i}}return t}function Qn(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var nt=[{name:"login",usage:`login [${re.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 ${Y}; any --*-endpoint overrides that environment's value)`,run:(e,t)=>Go({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:()=>Ho()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>Wo()},{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=>Wn({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=>zn({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=>zo({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=>Qo({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=>Zo({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:"delete-task",usage:"delete-task [--project <projectKey> --task <taskKey>] (marks the task Deleted, defaulting to the selected task and clearing that selection; the branch and its content are left alone)",run:e=>en({project:e.project,task:e.task})},{name:"recover-task",usage:"recover-task --project <projectKey> [--task <taskKey>] [--no-select] [--json] (without --task, lists the project's deleted tasks; with it, moves that task out of Deleted, keeps its branch content, and selects it)",required:["project"],run:e=>tn({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=>on({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=>nn({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=>rn({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-authoring-form] [--conformed] [--project <projectKey> --task <taskKey>] (--check-authoring-form filters the search results down to concepts whose class axiom does \u2014 by default \u2014 NOT match transform-axiom's standard authoring form; add --conformed to see the ones that already do instead. Concepts that can't be checked \u2014 not yet classified since their last stated edit, an ambiguous multi-axiom concept \u2014 are reported separately under skippedConcepts rather than counted as either.)",run:e=>sn({term:e.term,ecl:e.ecl,active:e.active,limit:e.limit,checkAuthoringForm:"check-authoring-form"in e,conformed:"conformed"in e,project:e.project,task:e.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--attribute-type <SCTID>] [--gci] [--project <projectKey> --task <taskKey>] (--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 is required for --gci to have any effect; a plain get-concept with no flags already shows gciAxioms.length for a quick has-it-got-any-GCIs check)",required:["id"],run:e=>an({id:e.id,attributeType:e["attribute-type"],gci:"gci"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)",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)",required:["id"],run:e=>dn({id:e.id,project:e.project,task:e.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--check-authoring-form] [--conformed] [--project <projectKey> --task <taskKey>] (lists concepts with pending stated changes and concepts affected only by classification, derived from the task branch's traceability log, same as the Authoring Workbench's "Concepts for Review" tab; entries marked "deleted": true were created and then deleted on this branch and no longer exist. --check-authoring-form filters that list down to concepts whose class axiom does \u2014 by default \u2014 NOT match transform-axiom's standard authoring form; add --conformed to see the ones that already do instead; concepts that can't be checked are reported separately under skippedConcepts)`,run:e=>ln({checkAuthoringForm:"check-authoring-form"in e,conformed:"conformed"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)',run:e=>un({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:"review-concepts [--project <projectKey> --task <taskKey>] (fetches the full concept representation \u2014 descriptions, relationships, axioms \u2014 for every concept with pending stated changes on the task, for an editorial review against SNOMED CT naming and modelling standards; see skills/authoring-cli/references/review-concepts.md. This is a data-gathering step, not a validation run \u2014 it performs no Snowstorm validation of its own)",run:e=>pn({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=>mn({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=>kn({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=>hn({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=>Cn({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=>fn({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=>gn({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=>yn({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>]",required:["id","indicator"],run:e=>In({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=>xn({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":"..."}}]' [--project <projectKey> --task <taskKey>] (only if never versioned; replaces the axiom's relationships wholesale)`,required:["id","axiom-id","relationships"],run:e=>bn({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,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>] (adds a new class axiom; use to replace a published axiom \u2014 add the replacement here, then inactivate-axiom the old one)`,required:["id","relationships"],run:e=>Tn({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=>vn({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":"..."}}]' [--project <projectKey> --task <taskKey>] (only if never versioned; replaces the axiom's relationships wholesale)`,required:["id","axiom-id","relationships"],run:e=>Sn({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,project:e.project,task:e.task})},{name:"delete-concept",usage:"delete-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id"],run:e=>An({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 never versioned)",required:["id","description-id"],run:e=>wn({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-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>] (retires a published FSN/PT/synonym without deleting it; for a never-versioned description use delete-description instead)",required:["id","description-id","indicator"],run:e=>Rn({id:e.id,descriptionId:e["description-id"],indicator:e.indicator,associationRefset:e["association-refset"],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-refset <id> --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; 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,associationRefset:e["association-refset"],associationTarget:e["association-target"],module:e.module,project:e.project,task:e.task})},{name:"delete-axiom",usage:"delete-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id","axiom-id"],run:e=>jn({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>] (retires a class axiom, including an already-published one, without deleting it; a concept must retain at least one active class axiom)",required:["id","axiom-id"],run:e=>En({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; a never-versioned axiom is updated in place, a published one is replaced by adding the transformed axiom and inactivating the original \u2014 omit --axiom-id to target the concept's sole active class axiom)",required:["id"],run:e=>Nn({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"check-authoring-form",usage:"check-authoring-form --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (read-only: reports whether a concept's class axiom already matches transform-axiom's standard authoring form, without writing anything; exits non-zero if it does not, or if it can't be checked (not yet classified, ambiguous multi-axiom concept) \u2014 same axiom-selection rule as transform-axiom, omit --axiom-id to target the sole active one)",required:["id"],run:e=>Pn({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 never versioned)",required:["id","axiom-id"],run:e=>Dn({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=>Fn({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=>On({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=>Kn({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=>Ln({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=>Bn({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function Zn(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 Xn(){return["Usage: authoring-cli <command> [options]","","Commands:",...nt.map(e=>` ${Zn(e)}`),"",'Run "login" first to sign in.',"With no --project/--task, actions target whatever task was",'last set via "select-task".'].join(`
|
|
28
|
+
`)}async function er(e=process.argv){let[,,t,...r]=e,n=us(r),o=Qn(r);if(!t){console.log(Xn());return}let s=nt.find(a=>a.name===t||a.aliases?.includes(t));if(!s){console.error(`Unknown command: ${t}
|
|
29
29
|
|
|
30
|
-
${
|
|
30
|
+
${Xn()}`),process.exitCode=1;return}let i=(s.required??[]).filter(a=>!n[a]);if(i.length){console.error(`Missing required flag(s): ${i.map(a=>`--${a}`).join(", ")}
|
|
31
31
|
|
|
32
|
-
Usage: ${
|
|
32
|
+
Usage: ${Zn(s)}`),process.exitCode=1;return}await s.run(n,o)}require.main===module&&er().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});0&&(module.exports={COMMANDS,main,parsePositionals});
|
package/package.json
CHANGED
|
@@ -163,6 +163,34 @@ Which list to run:
|
|
|
163
163
|
`"In Review"`, `"New"`, `"Promoted"`, ...). `--json` emits the raw task objects, for when you need
|
|
164
164
|
fields the line format doesn't print.
|
|
165
165
|
|
|
166
|
+
## Common authoring mistakes to avoid
|
|
167
|
+
|
|
168
|
+
Some mistakes are easy to make and don't trigger validation errors, so they slip through unless
|
|
169
|
+
you catch them during review or read the concept back afterward. Watch for these:
|
|
170
|
+
|
|
171
|
+
**FSN semantic tag errors:**
|
|
172
|
+
- **Duplicate semantic tags**: `Structure of deep flexor tendon within digit of hand (body
|
|
173
|
+
structure) (body structure)` is malformed. The FSN ends with exactly one semantic tag in
|
|
174
|
+
parentheses, not multiple identical ones. If you see duplicates, it's a copy-paste error.
|
|
175
|
+
- **Missing or wrong semantic tag**: every FSN must end with a semantic tag; verify it matches the
|
|
176
|
+
concept's actual domain. A body-structure concept should end with `(body structure)`, a finding
|
|
177
|
+
with `(finding)`, etc.
|
|
178
|
+
|
|
179
|
+
**Synonym specificity and meaning:**
|
|
180
|
+
- **Inappropriate synonyms that shift the concept's meaning**: a synonym must name the same clinical
|
|
181
|
+
entity — just a different way of saying it. Don't add a synonym that is too generic or names a
|
|
182
|
+
larger/different structure. For example, "finger and/or thumb" is inappropriate for "Structure of
|
|
183
|
+
deep flexor tendon within digit of hand (body structure)" because it names a broader anatomical
|
|
184
|
+
region, not the tendon structure itself. If the synonym would be true of multiple unrelated
|
|
185
|
+
concepts or a broader concept, it's the wrong synonym for this one.
|
|
186
|
+
- **Synonym conflation**: don't mix two genuinely different clinical ideas in different synonyms on
|
|
187
|
+
the same concept, expecting them to be clarified by acceptability or acceptability flags. The
|
|
188
|
+
Preferred Term and acceptable synonyms should all refer to the same clinical entity.
|
|
189
|
+
|
|
190
|
+
Run `review-concepts` before promoting a task to check these mistakes aren't hiding in your
|
|
191
|
+
pending changes — they save cleanly but are real content errors, not save-time constraint
|
|
192
|
+
violations.
|
|
193
|
+
|
|
166
194
|
## Ground truth vs. echoed validation results
|
|
167
195
|
|
|
168
196
|
Every concept-mutating command (`create-concept`, `add-description`, `set-acceptability`, ...)
|
|
@@ -219,6 +247,30 @@ to change together consistently. The plain single-description form (`--descripti
|
|
|
219
247
|
already-non-conflicting description from ACCEPTABLE to PREFERRED, or demoting a description that
|
|
220
248
|
isn't the dialect's sole PREFERRED one).
|
|
221
249
|
|
|
250
|
+
### Promoting a brand-new synonym to PT
|
|
251
|
+
|
|
252
|
+
If the synonym that should become PT doesn't exist yet, add it first — as ACCEPTABLE, not
|
|
253
|
+
PREFERRED. `add-description --acceptability ACCEPTABLE` can never collide with the constraint
|
|
254
|
+
above (it isn't claiming to be the sole PREFERRED anything), so that first save is always safe no
|
|
255
|
+
matter what's currently preferred. Only then swap preference from the old PT to the new one with
|
|
256
|
+
`set-acceptability --entries`, exactly as above:
|
|
257
|
+
|
|
258
|
+
```
|
|
259
|
+
authoring-cli add-description --id <SCTID> --term "<new term>" --type SYNONYM \
|
|
260
|
+
--acceptability ACCEPTABLE --project <projectKey> --task <taskKey>
|
|
261
|
+
# → descriptionId <newId>
|
|
262
|
+
|
|
263
|
+
authoring-cli set-acceptability --id <SCTID> \
|
|
264
|
+
--entries '[{"descriptionId":"<oldPtId>","us":"ACCEPTABLE","gb":"ACCEPTABLE"},
|
|
265
|
+
{"descriptionId":"<newId>","us":"PREFERRED","gb":"PREFERRED"}]' \
|
|
266
|
+
--project <projectKey> --task <taskKey>
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Two separate saves, but no invalid intermediate state at either boundary — the new synonym is never
|
|
270
|
+
PREFERRED until the same save that demotes the old one. Adding it as PREFERRED directly
|
|
271
|
+
(`--acceptability PREFERRED`) skips the staging step and fails outright instead: Snowstorm rejects
|
|
272
|
+
the add itself the moment it would create two PREFERRED synonyms in the same dialect.
|
|
273
|
+
|
|
222
274
|
## US/GB (and other dialect) spelling-variant pairs
|
|
223
275
|
|
|
224
276
|
When a synonym contains a word that's spelled differently in US vs. GB English — edema/oedema,
|
|
@@ -425,6 +477,18 @@ process". Get the direction backwards and nothing complains: the axiom saves, va
|
|
|
425
477
|
misbehaves at classification, where it drags unrelated concepts underneath your concept. Read the
|
|
426
478
|
axiom back with `get-concept` and check your concept is the one on the right of the `SubClassOf`.
|
|
427
479
|
|
|
480
|
+
**Checking whether a concept already has GCI axioms, before adding another:** a plain `get-concept
|
|
481
|
+
--id <SCTID>` already answers this — a non-zero `gciAxioms.length` on that response means the
|
|
482
|
+
concept has at least one, no filter needed. To check whether a *specific* attribute type is already
|
|
483
|
+
asserted inside an existing GCI — e.g. before adding a GCI whose antecedent would duplicate one
|
|
484
|
+
already there — add `--gci` to `get-concept`'s `--attribute-type` filter (see the substitution
|
|
485
|
+
pattern below for the flag's base behavior): `get-concept --id <SCTID> --attribute-type <typeId>
|
|
486
|
+
--gci` returns just that GCI's matching relationships instead of the whole concept. Without `--gci`,
|
|
487
|
+
`--attribute-type` scans `classAxioms` only — the two are never scanned together, since a class
|
|
488
|
+
axiom's relationships and a GCI's mean opposite things (see above). See
|
|
489
|
+
`references/gci-modeling.md`'s "Confirming the concept's current state" for the fuller pre-flight
|
|
490
|
+
check this feeds into.
|
|
491
|
+
|
|
428
492
|
The `groupId`s work exactly as they do in a class axiom, so the multi-group caveat above applies
|
|
429
493
|
here too — build the whole relationship list in one call.
|
|
430
494
|
|
|
@@ -574,22 +638,27 @@ read it *before* starting the cleanup below. The cleanup writes to other concept
|
|
|
574
638
|
only afterwards that the deletion can't proceed leaves you having re-parented children away from a
|
|
575
639
|
concept that's staying, and having stripped retrofits that should have stayed.
|
|
576
640
|
|
|
577
|
-
### 1. Find everything that references it —
|
|
641
|
+
### 1. Find everything that references it — one query, run twice
|
|
578
642
|
|
|
579
|
-
|
|
643
|
+
`find-references --id <SCTID>` wraps Snowstorm's own concept-references lookup, and covers both
|
|
644
|
+
kinds of reference in one call — attribute values (`Finding site`, `Procedure site`, `Associated
|
|
645
|
+
morphology`, …) *and* stated `Is a` children — grouped by reference type, instead of needing a
|
|
646
|
+
separate ECL query per kind:
|
|
580
647
|
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
-
|
|
584
|
-
|
|
585
|
-
the last classification — exactly the situation right after authoring.
|
|
648
|
+
```
|
|
649
|
+
authoring-cli find-references --id <SCTID> # inferred/realized view
|
|
650
|
+
authoring-cli find-references --id <SCTID> --stated # literal stated axioms
|
|
651
|
+
```
|
|
586
652
|
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
`
|
|
591
|
-
|
|
592
|
-
|
|
653
|
+
Run **both**. Without `--stated` it reads the *inferred* view — the realized, already-classified
|
|
654
|
+
state, which is what already-released content shows up under. With `--stated` it reads the literal
|
|
655
|
+
axioms as authored — which is what catches a same-session edit (a new relationship, a new stated
|
|
656
|
+
`Is a`) before classification has run, exactly the situation right after authoring. Neither view
|
|
657
|
+
alone is a complete answer on a branch with pending, unclassified changes; the inferred view misses
|
|
658
|
+
what you just stated, and the stated view misses anything the terminology already carries only
|
|
659
|
+
through inference. `--limit`/`--offset` page through `referencesByType[].referencingConcepts` on a
|
|
660
|
+
heavily-referenced concept — check `total` against what came back, the same caution as any other
|
|
661
|
+
paginated search here.
|
|
593
662
|
|
|
594
663
|
### 2. Deal with every reference before deleting anything
|
|
595
664
|
|
|
@@ -646,6 +715,41 @@ The same reference checks apply either way. Inactivation doesn't dangle referenc
|
|
|
646
715
|
does, but a still-active concept whose `Finding site` points at an inactive concept is its own
|
|
647
716
|
validation problem — check 1 is worth running before either command.
|
|
648
717
|
|
|
718
|
+
The same choice exists one level down, for a single description: `delete-description` splices a
|
|
719
|
+
never-versioned FSN/PT/synonym out entirely, while `inactivate-description --id <SCTID>
|
|
720
|
+
--description-id <descriptionId> --indicator <value> [--association-refset <id>
|
|
721
|
+
--association-target <SCTID>]` retires a *released* one in place, matching real RF2 data — an
|
|
722
|
+
already-inactive description always has an empty `acceptabilityMap`, so `inactivate-description`
|
|
723
|
+
clears it for you rather than leaving a stale PREFERRED/ACCEPTABLE entry behind. Each command
|
|
724
|
+
guards the case the other one is for: `delete-description` 409s on a versioned description,
|
|
725
|
+
`inactivate-description` 409s on one that was never versioned. Note this can still trip the "exactly one PREFERRED synonym per language refset" constraint above:
|
|
726
|
+
inactivating a dialect's sole PT clears its only PREFERRED entry in that refset, so
|
|
727
|
+
`inactivate-description` itself gets the 400 if you do it first. Same fix as replacing a published
|
|
728
|
+
axiom — promote the replacement synonym to PREFERRED with `set-acceptability`/`--entries` *before*
|
|
729
|
+
inactivating the old PT, not after, so the dialect never has zero PREFERREDs at any save boundary.
|
|
730
|
+
|
|
731
|
+
The FSN doesn't get that two-step luxury: `add-description` always creates a new FSN as
|
|
732
|
+
PREFERRED — `makeDescription`'s FSN path takes no acceptability parameter, so there's no
|
|
733
|
+
ACCEPTABLE-staged FSN to add safely first the way a synonym has. Retiring the old FSN and adding the
|
|
734
|
+
new one as two separate `inactivate-description` + `add-description` saves 400s no matter which
|
|
735
|
+
order you pick — add first and there are briefly two PREFERRED FSNs in the dialect, retire first and
|
|
736
|
+
there are briefly zero. Use `replace-fsn --id <SCTID> --term "<new FSN>" --indicator <value>
|
|
737
|
+
[--description-id <oldFsnDescriptionId>] [--association-refset <id> --association-target <SCTID>]`
|
|
738
|
+
instead — it bundles both edits into the one save that actually works. `--description-id` is only
|
|
739
|
+
required when the concept has more than one active FSN to disambiguate; a never-versioned FSN
|
|
740
|
+
should go through `update-description` (in-place term edit), not `replace-fsn`.
|
|
741
|
+
|
|
742
|
+
The same choice exists for a single class axiom too, with one asymmetry from the concept/description
|
|
743
|
+
pair above: `delete-axiom --id <SCTID> --axiom-id <axiomId>` refuses outright once that axiom's own
|
|
744
|
+
`effectiveTime` is set, but `inactivate-axiom --id <SCTID> --axiom-id <axiomId>` has no such gate —
|
|
745
|
+
setting `active: false` on an axiom's row is the normal RF2 retirement path regardless of whether it
|
|
746
|
+
was ever versioned, so it accepts both a released and a never-versioned axiom. There's no indicator
|
|
747
|
+
or association target at the axiom level; both commands instead guard the concept's minimum: it must
|
|
748
|
+
keep at least one class axiom (`delete-axiom` counts all of them) and, separately, at least one
|
|
749
|
+
*active* one (`inactivate-axiom` counts only active ones). See "Replacing a published axiom" above
|
|
750
|
+
for the add-axiom-then-inactivate-axiom sequence this feeds into when the goal is swapping an
|
|
751
|
+
axiom's content rather than just retiring it.
|
|
752
|
+
|
|
649
753
|
## Generating a concept structurally parallel to an existing one
|
|
650
754
|
|
|
651
755
|
A common authoring task, especially at scale: mint a new concept whose defining axiom is identical
|
|
@@ -656,8 +760,11 @@ across a large source list, see `references/batch-authoring.md`.)
|
|
|
656
760
|
1. Fetch the source's **real** defining axiom via `get-concept` — not a rendering or a note from an
|
|
657
761
|
earlier session; it may have changed. Identify exactly which relationship(s) carry the attribute
|
|
658
762
|
you're substituting (for a site swap: Finding site `363698007`, Procedure site `363704007`,
|
|
659
|
-
Procedure site - Direct `405813007`, Procedure site - Indirect `405814001`)
|
|
660
|
-
|
|
763
|
+
Procedure site - Direct `405813007`, Procedure site - Indirect `405814001`) — `get-concept --id
|
|
764
|
+
<sourceId> --attribute-type <typeId>` returns just those matches (target concept, `groupId`,
|
|
765
|
+
`relationshipId`) instead of making you pick them out of the full axiom dump by hand. Copy
|
|
766
|
+
everything else in the axiom — morphology, occurrence, method, due-to, the top-level `Is a` —
|
|
767
|
+
verbatim.
|
|
661
768
|
2. Verify the substituted value's target concept already exists via a live `search-concepts` with
|
|
662
769
|
an **exact** match check on the FSN, not a fuzzy hit and not a static/hardcoded mapping table —
|
|
663
770
|
terminology content drifts and a stale local table will confidently point you at the wrong
|
|
@@ -779,6 +886,13 @@ The names are deliberately distinct: `validate-task` validates the entire task b
|
|
|
779
886
|
job, like `classify`); `validate-concept` is a synchronous, read-only check of a single concept;
|
|
780
887
|
`validate-review-concepts` runs that per-concept check across your pending edits.
|
|
781
888
|
|
|
889
|
+
**Important:** `validate-review-concepts` catches Snowstorm-enforced issues (MRCM violations,
|
|
890
|
+
description constraints, etc.), but it does *not* catch content errors that save cleanly — duplicate
|
|
891
|
+
semantic tags in FSNs, inappropriate synonyms, synonym conflation, or other modeling mistakes. Those
|
|
892
|
+
require editorial review. Always follow `validate-review-concepts` with `review-concepts` to check
|
|
893
|
+
for these issues before promoting a task. See "Common authoring mistakes to avoid" above and the
|
|
894
|
+
full `references/review-concepts.md` checklist for what to watch for.
|
|
895
|
+
|
|
782
896
|
## Reviewing concepts against SNOMED CT terminology standards
|
|
783
897
|
|
|
784
898
|
```
|
|
@@ -76,24 +76,41 @@ value. If repeated re-lookups genuinely become a bottleneck at scale, that's a r
|
|
|
76
76
|
introduce a cache — but validate the cache against live search periodically rather than treating it
|
|
77
77
|
as permanently authoritative.
|
|
78
78
|
|
|
79
|
-
##
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
79
|
+
## Getting the source's attribute value without hand-parsing the axiom
|
|
80
|
+
|
|
81
|
+
The substitution pattern needs, for each source concept, the current target of whatever attribute
|
|
82
|
+
is being substituted (Finding site, Procedure site, ...). Use `get-concept --attribute-type
|
|
83
|
+
<typeId>` for this rather than pulling the full concept and picking the relationship out of
|
|
84
|
+
`classAxioms[].relationships[]` yourself — it returns just the matches, across every active class
|
|
85
|
+
axiom, with the fields the substitution step needs already extracted:
|
|
86
|
+
|
|
87
|
+
```
|
|
88
|
+
authoring-cli get-concept --id <sourceId> --attribute-type 363698007
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
```json
|
|
92
|
+
{
|
|
93
|
+
"conceptId": "<sourceId>",
|
|
94
|
+
"attributeType": "363698007",
|
|
95
|
+
"matches": [
|
|
96
|
+
{ "axiomId": "...", "relationshipId": "...", "relationshipIndex": 1, "groupId": 1,
|
|
97
|
+
"targetId": "53505006", "targetFsn": "Structure of nail unit of great toe",
|
|
98
|
+
"active": true, "effectiveTime": null, "released": false }
|
|
99
|
+
]
|
|
100
|
+
}
|
|
92
101
|
```
|
|
93
102
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
103
|
+
`matches` is `[]`, not an error, when the concept has none of that attribute — a real result worth
|
|
104
|
+
routing to `SKIPPED_TRIAGE`, not a failure to retry. `definitionStatus` (needed for step 3 of the
|
|
105
|
+
substitution pattern) is a single top-level field on the plain `get-concept` response — read it
|
|
106
|
+
directly from that JSON, no extraction needed.
|
|
107
|
+
|
|
108
|
+
If a scope-filtering or candidate-discovery script needs data this flag doesn't cover, that's a
|
|
109
|
+
capability gap in the CLI, not something to close with a `jq`/`node -e` script against raw
|
|
110
|
+
`get-concept` output — see `CLAUDE.md`'s guidance on when a missing capability is a feature request.
|
|
111
|
+
Either way, such a script should only ever *find candidates*, never decide fitness for creation on
|
|
112
|
+
its own — keep the compound-word/idiom/cardinality judgment calls (see `SKILL.md`) as an explicit
|
|
113
|
+
manual step after the script (or this flag) narrows the field.
|
|
97
114
|
|
|
98
115
|
## Closing out a session
|
|
99
116
|
|
|
@@ -160,17 +160,30 @@ information yet."
|
|
|
160
160
|
Read the live axioms before assuming anything about what's already there — a candidate can already
|
|
161
161
|
be modelled and simply not annotated as such in whatever list surfaced it:
|
|
162
162
|
|
|
163
|
-
```
|
|
164
|
-
authoring-cli get-concept --id <SCTID>
|
|
165
|
-
"\(.fsn.term) [\(.definitionStatus)] gci=\(.gciAxioms|length)",
|
|
166
|
-
(.classAxioms[] | "CLASS " + ([.relationships[]|select(.active)|"g\(.groupId):\(.type.pt.term)=\(.target.conceptId)|\(.target.fsn.term)"]|join(" | "))),
|
|
167
|
-
(.gciAxioms[] | "GCI " + ([.relationships[]|select(.active)|"g\(.groupId):\(.type.pt.term)=\(.target.conceptId)|\(.target.fsn.term)"]|join(" | ")))'
|
|
163
|
+
```
|
|
164
|
+
authoring-cli get-concept --id <SCTID>
|
|
168
165
|
```
|
|
169
166
|
|
|
170
|
-
`
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
167
|
+
Read `definitionStatus` and `gciAxioms.length` straight off that JSON — no extraction step needed
|
|
168
|
+
for a single concept; a non-zero `gciAxioms.length` is enough to answer "does this concept have a
|
|
169
|
+
GCI" without any filter. For each active relationship inside `classAxioms[].relationships[]` and
|
|
170
|
+
`gciAxioms[].relationships[]`, the fields that matter are `groupId`, `type.pt.term` (or
|
|
171
|
+
`type.conceptId`), and `target.fsn.term` (or `target.conceptId`); read `classAxioms` for the
|
|
172
|
+
target's own definition and `gciAxioms` for what it already asserts as sufficient conditions on
|
|
173
|
+
others. If you only need one attribute type's relationships rather than the whole axiom — e.g.
|
|
174
|
+
checking a specific candidate attribute in isolation — `get-concept --id <SCTID> --attribute-type
|
|
175
|
+
<typeId>` returns just those matches (target, `groupId`, `relationshipId`) instead, scanning
|
|
176
|
+
`classAxioms` by default. Add `--gci` to scan `gciAxioms` instead when the question is specifically
|
|
177
|
+
"does an *existing GCI* already assert this attribute" — e.g. confirming the tautology check
|
|
178
|
+
earlier in this file, or checking whether a candidate antecedent's defining attribute is already
|
|
179
|
+
covered by a GCI the target carries. The two scans are never combined in one call, since a class
|
|
180
|
+
axiom's relationships and a GCI's mean opposite things (see "What a GCI is" above) and conflating
|
|
181
|
+
their matches would misreport which side of the concept's definition the attribute lives on.
|
|
182
|
+
|
|
183
|
+
An empty `gciAxioms` array means there's no existing GCI on this concept — but check the checklist
|
|
184
|
+
above before concluding one is *needed*; the common outcome across any grouper-style hierarchy is
|
|
185
|
+
that most candidates correctly get none. Anything else means you're reviewing existing axioms,
|
|
186
|
+
which is a different job from authoring new ones — say so rather than adding duplicates on top.
|
|
174
187
|
|
|
175
188
|
## The antecedent: genus, nexus, defining attribute
|
|
176
189
|
|
|
@@ -85,7 +85,11 @@ Read the axiom from `get-concept`, not a cached summary, and check:
|
|
|
85
85
|
each other. A concept where everything landed in one group, or where a self-grouped attribute got
|
|
86
86
|
swept into a clinical-finding group, has had its actual meaning changed even though it validates —
|
|
87
87
|
this is the judgment layer behind the `add-relationship --group N` compaction hazard documented in
|
|
88
|
-
`SKILL.md`.
|
|
88
|
+
`SKILL.md`. To confirm which `groupId` two attribute types actually landed in without picking
|
|
89
|
+
through the full axiom by hand, run `get-concept --id <id> --attribute-type <typeId>` once per
|
|
90
|
+
type (e.g. Finding site `363698007`, Associated morphology `116676008`) and compare the returned
|
|
91
|
+
`groupId` values directly — same `groupId` means Snowstorm grouped them together, different
|
|
92
|
+
`groupId`s means it didn't.
|
|
89
93
|
- **Primitive vs. sufficiently-defined status is appropriate, not just consistent with the source
|
|
90
94
|
concept.** A concept should be sufficiently defined when its stated relationships are "adequate to
|
|
91
95
|
define it relative to its immediate supertypes" — i.e. another concept with the same parent and
|
|
@@ -121,16 +125,30 @@ Read the axiom from `get-concept`, not a cached summary, and check:
|
|
|
121
125
|
actually name two different clinical ideas, not two names for the same one.
|
|
122
126
|
`set-acceptability`/`add-description` will happily save either shape; only reading the terms
|
|
123
127
|
side by side catches the conflation.
|
|
128
|
+
- **Inappropriate synonyms that lose specificity** — a synonym that is too generic, vague, or
|
|
129
|
+
semantically shifts the concept's meaning. For example, "finger and/or thumb" is inappropriate as
|
|
130
|
+
a synonym for "Structure of deep flexor tendon within digit of hand (body structure)" because it
|
|
131
|
+
names a larger anatomical region, not the same structure — the synonym must name the same clinical
|
|
132
|
+
entity, just a different way of saying it. If the synonym would be true of a broader or differently
|
|
133
|
+
defined concept, it's the wrong synonym for this one.
|
|
124
134
|
- **No relationships beyond `Is a`** — likely under-modelled for a concept whose hierarchy position
|
|
125
135
|
implies it should carry at least one defining attribute (e.g. a disorder with no `Finding site`
|
|
126
136
|
or `Associated morphology` at all, when siblings all have one).
|
|
127
137
|
- **A parenthetical qualifier inside the FSN body, distinct from the semantic tag** — sometimes a
|
|
128
138
|
legitimate disambiguator, but can also signal that the concept should have been split, or that the
|
|
129
139
|
qualifying detail belongs in the definition/attributes instead of the name.
|
|
140
|
+
- **Duplicate semantic tags in the FSN** — the FSN must end with exactly one semantic tag in
|
|
141
|
+
parentheses, not multiple identical ones (e.g. "Structure of deep flexor tendon within digit of
|
|
142
|
+
hand (body structure)" is correct; "Structure of deep flexor tendon within digit of hand (body
|
|
143
|
+
structure) (body structure)" is wrong). If you see duplicate tags, it's a copy-paste or formatting
|
|
144
|
+
error that needs correction.
|
|
130
145
|
- **Value-set-style checks**: if the review surfaces a group of concepts meant to function as a set
|
|
131
146
|
(a batch you just authored, or an existing reference set), confirm every member is active — an
|
|
132
147
|
inactive code hiding inside an otherwise-active set is easy to miss one at a time and obvious once
|
|
133
|
-
counted.
|
|
148
|
+
counted. For a batch you just authored, `review-concepts`'s own output already has each member's
|
|
149
|
+
active status, no extra step needed. For an existing reference set, don't fetch every member with
|
|
150
|
+
`get-concept` to check by hand — `search-concepts --ecl "^ <refsetId>" --active false` asks
|
|
151
|
+
Snowstorm directly for just the inactive members of that refset in one call.
|
|
134
152
|
|
|
135
153
|
## Historical associations for inactive concepts encountered during review
|
|
136
154
|
|