@cognite/cli 1.6.0 → 1.7.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -60,7 +60,7 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
60
60
  "tailwindcss": "^4.1.17",
61
61
  "typescript": "^5.0.0",
62
62
  "typescript-eslint": "^8.46.4",
63
- "vite": "7.3.2",
63
+ "vite": "7.3.5",
64
64
  "vitest": "4.1.7"
65
65
  }
66
66
  }
@@ -0,0 +1,12 @@
1
+ var we=Object.defineProperty;var ee=n=>{throw TypeError(n)};var o=(n,e)=>we(n,"name",{value:e,configurable:!0});var te=(n,e,t)=>e.has(n)||ee("Cannot "+t);var ne=(n,e,t)=>(te(n,e,"read from private field"),t?t.call(n):e.get(n)),re=(n,e,t)=>e.has(n)?ee("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),ie=(n,e,t,r)=>(te(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t);import{mkdir as nt,readFile as rt}from"fs/promises";import{basename as it,dirname as ot}from"path";var F=class F extends Error{constructor(e,t={}){super(e),this.name="HintedError",t.cause!==void 0&&(this.cause=t.cause);let r=this.deriveDefaults(t);this.hint=t.hint??r.hint,this.helpUrl=t.helpUrl??r.helpUrl,this.shouldReport=t.shouldReport??!0}deriveDefaults(e){return{hint:xe(e.cause)}}};o(F,"HintedError");var d=F;var oe="https://docs.cognite.com/cdf/access/",ve="https://status.cognite.com";function ke(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:oe};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:oe};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:ve};default:return{}}}o(ke,"defaultHintForStatus");var _=class _ extends d{constructor(e,t){super(e,t),this.name="HintedHttpError",this.httpStatusCode=t.httpStatusCode,this.requestUrl=t.requestUrl,this.responseBody=t.responseBody}deriveDefaults(e){let{httpStatusCode:t}=e,r=ke(t),i=super.deriveDefaults(e);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};o(_,"HintedHttpError");var v=_;function Ce(n,e){if(n)switch(n){case"ENOTFOUND":return e.hostname?`DNS lookup failed for ${e.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return e.hostname&&e.port?`Connection refused by ${e.hostname}:${e.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return e.path?`Permission denied: ${e.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return e.path?`File or directory not found: ${e.path}.`:"File or directory not found.";case"EISDIR":return e.path?`Expected a file but found a directory: ${e.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return e.port?`Port ${e.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}o(Ce,"hintForErrno");function xe(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,i=Ce(r.code,r);if(i!==void 0)return i;e=r.cause}}o(xe,"hintForCause");import{inspect as Ie}from"util";var L="[REDACTED]",x,R=class R{constructor(e){re(this,x);ie(this,x,e)}toString(){return L}toJSON(){return L}[Ie.custom](){return L}expose(){return ne(this,x)}static from(e){return new R(e)}};x=new WeakMap,o(R,"SensitiveString");var S=R;var se="https://docs.cognite.com/cdf/access/";function g(n){return n!==null&&typeof n=="object"}o(g,"isRecord");function I(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}o(I,"isHttpError");function Pe(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
+ See: ${se}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
3
+ See: ${se}`;default:return}}o(Pe,"httpStatusHint");function m(n){let e=n instanceof Error?n:new Error(String(n));if(!I(e))return null;let t=Pe(e.status);return t?Object.assign(new Error(`${e.message}
4
+ ${t}`),{cause:e}):null}o(m,"enrichedHttpError");function Te(n){if(!g(n))return null;let e=n.missing;if(Array.isArray(e))return e;let t=n.data;if(g(t)){let r=t.error;if(g(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(t.missing))return t.missing}return null}o(Te,"findMissingArray");function be(n,e){if(!I(n)||n.status!==400)return!1;let t=Te(n);return t?t.some(r=>g(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}o(be,"isMissingExternalIdError");function D(n,e){return I(n)&&n.status===404||be(n,e)}o(D,"isNotFoundError");var pe=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],ce=["ACTIVE","PREVIEW"],H=class H extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};o(H,"AppVersionNotFoundError");var $=H,B=class B extends Error{constructor(e){super(`App ${e} not found`),this.name="AppNotFoundError",this.appExternalId=e}};o(B,"AppNotFoundError");var U=B;function N(n,e){return n.includes(e)}o(N,"includesValue");function Re(n){return N(pe,n)}o(Re,"isAppVersionLifecycleState");function De(n){return N(ce,n)}o(De,"isAppVersionAlias");function $e(n){return typeof n.version=="string"&&Re(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||De(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}o($e,"isAppVersion");function ae(n){if(!g(n)){let e=JSON.stringify(n)?.slice(0,200)??String(n);throw new Error(`Invalid version response: expected object, got ${e}`)}if(!$e(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}o(ae,"parseAppVersion");function Ue(n){if(!g(n))throw new Error("Invalid app response: not an object");let{externalId:e,name:t,description:r}=n;if(typeof e!="string")throw new Error("Invalid app response: missing externalId");if(typeof t!="string")throw new Error("Invalid app response: missing name");if(r!=null&&typeof r!="string")throw new Error("Invalid app response: malformed description");return{externalId:e,name:t,description:typeof r=="string"?r:void 0}}o(Ue,"parseAppMetadata");var M=class M{constructor(e){this.client=e}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(e,t,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:e,name:t,description:r}]}})}catch(i){throw m(i)??i}}async updateApps(e){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:e}})}catch(t){throw m(t)??t}}async getApp(e){let t=`${this.appsBasePath}/${encodeURIComponent(e)}`;try{let r=await this.client.get(t);return Ue(r.data)}catch(r){throw D(r,[e])?new U(e):m(r)??r}}async uploadVersion(e,t,r,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${t}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),i),a.append("version",t),a.append("entryPath",s);let c=encodeURIComponent(e),p=`${this.appsBasePath}/${c}/versions`,u=await this.client.authenticate();if(!u)throw new d("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let E=S.from(u),f=`${this.client.getBaseUrl()}${p}`,X=new AbortController,Ee=setTimeout(()=>X.abort(),300*1e3),A;try{A=await fetch(f,{method:"POST",headers:{Authorization:`Bearer ${E.expose()}`},body:a,signal:X.signal})}catch(h){throw h instanceof Error&&h.name==="AbortError"?new d("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new d(`Failed to upload version to ${f}`,{cause:h,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(Ee)}if(!A.ok){let h=await A.text(),w;try{w=JSON.parse(h)}catch{}let b=h;if(g(w)){let k=w.error;if(typeof k=="string")b=k;else if(g(k)){let C=k.message,Q=k.code;b=typeof C=="string"?C:Q!=null?`Unknown error (code: ${Q})`:h}else{let C=w.message;b=typeof C=="string"?C:h}}let Z=A.headers.get("x-request-id"),Se=Z?` | X-Request-ID: ${Z}`:"",Ae=g(w)?w:h;throw new v(`Upload failed: ${A.status} \u2014 ${b}${Se}`,{httpStatusCode:A.status,requestUrl:f,responseBody:Ae})}console.log(`\u2705 Version ${t} uploaded`)}async getVersion(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${i}`;try{let a=await this.client.get(s);return ae(a.data)}catch(a){throw D(a,[e,t])?new $(e,t):m(a)??a}}async getActiveVersion(e){let t=encodeURIComponent(e),r=`${this.appsBasePath}/${t}/versions/list`;try{let i=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!g(i.data)||!Array.isArray(i.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=i.data;if(s.length===0)return null;if(s.length>1)throw new Error(`Unexpected response: ${s.length} versions have the ACTIVE alias, expected at most 1`);return ae(s[0])}catch(i){if(D(i,[e]))return null;throw m(i)??i}}async updateVersions(e,t){let r=encodeURIComponent(e),i=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(i,{data:{items:t}})}catch(s){throw m(s)??s}}async submitSignatures(e,t,r){let i=encodeURIComponent(e),s=encodeURIComponent(t),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(c){throw m(c)??c}}async listSignatures(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${i}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return Oe(a.data)}catch(a){throw m(a)??a}}};o(M,"AppHostingApi");var V=M,Ne=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Ve=["developer","certifier"];function Oe(n){if(!g(n))throw new Error("Invalid signatures response: expected an object with an items array");let{items:e}=n;if(!Array.isArray(e))throw new Error("Invalid signatures response: items property is missing or not an array");return e.flatMap(t=>{let r=Fe(t);return r?[r]:[]})}o(Oe,"parseStoredSignatures");function Fe(n){if(!g(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:s,status:a}=n;return typeof e!="string"||e===""||!N(Ve,t)||typeof r!="number"||typeof i!="number"||typeof s!="number"||!N(Ne,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:s,status:a}}o(Fe,"parseStoredSignature");function _e(n,e){let t=[];n.name!==e.name&&t.push({field:"name",remote:n.name,local:e.name});let r=n.description??"";return r!==e.description&&t.push({field:"description",remote:r,local:e.description}),t}o(_e,"diffAppMetadata");function Le(n){let e=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:t,remote:r,local:i}of n){let s=`${t}:`.padEnd(14);e.push(` ${s}"${r}" \u2192 "${i}"`)}return e.join(`
5
+ `)}o(Le,"formatMetadataDriftError");var j=class j{constructor(e){this.api=new V(e)}getVersion(e,t){return this.api.getVersion(e,t)}uploadVersion(e,t,r,i,s){return this.api.uploadVersion(e,t,r,i,s)}async ensureApp(e,t,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(e,t,r),console.log(`\u2705 App '${e}' created`)}catch(i){if(I(i)&&i.status===409){console.log(`\u2705 App '${e}' already exists`),await this.checkMetadataDrift(e,t,r);return}throw i}}async checkMetadataDrift(e,t,r){let i;try{i=await this.getApp(e)}catch{return}let s=_e(i,{name:t,description:r});if(s.length!==0)throw new d(Le(s),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(e){return this.api.getApp(e)}async updateAppMetadata(e,t,r){await this.api.updateApps([{externalId:e,update:{name:{set:t},description:r?{set:r}:{setNull:!0}}}])}async submitSignatures(e,t,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${t}...`),await this.api.submitSignatures(e,t,r),console.log("\u2705 Signatures stored"))}listSignatures(e,t){return this.api.listSignatures(e,t)}async publishVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(e,t){console.log(`\u{1F680} Publishing and activating version ${t}...`),await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${t} is now PUBLISHED and ACTIVE`)}getActiveVersion(e){return this.api.getActiveVersion(e)}async deactivateVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{alias:{setNull:!0}}}])}async activateVersion(e,t){let r=null;try{r=await this.api.getActiveVersion(e)}catch{r=null}let i=r&&r.version!==t?r.version:void 0;return await this.api.updateVersions(e,[{version:t,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(e,t,r,i,s,a,c=!1){console.log(`
6
+ \u{1F680} Deploying application via App Hosting API...
7
+ `),await this.ensureApp(e,t,r),await this.uploadVersion(e,i,s,a),c&&await this.publishAndActivate(e,i),console.log(`
8
+ \u2705 Deployment successful!`)}};o(j,"AppHostingClient");var P=j;import{execFileSync as O}from"child_process";import y from"fs";import l from"path";import{parseAndValidateManifestConfig as He}from"@cognite/app-sdk/vite";import{BlobReader as Be,Uint8ArrayWriter as Me,ZipWriter as je}from"@zip.js/zip.js";var q="package.json",J="package-lock.json",ue="manifest.json",G=".cognite",qe=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],Y=class Y{constructor(e="dist"){this.distPath=l.isAbsolute(e)?e:l.join(process.cwd(),e),this.appRoot=l.dirname(this.distPath)}validateBuildDirectory(){if(!y.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=l.join(this.appRoot,q);if(!y.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=l.join(this.appRoot,J);if(!y.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`)}async createZip(e="app.zip",t=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new je(new Me,{level:9}),i=o(async(p,u)=>{await r.add(u,new Be(await y.openAsBlob(p))),t&&console.log(` \u{1F4C4} ${u}`)},"addFile"),s=o(async p=>{let u=await y.promises.readdir(p,{withFileTypes:!0});for(let E of u){let f=l.join(p,E.name);E.isDirectory()?await s(f):await i(f,l.relative(this.distPath,f).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let p=l.join(this.appRoot,q);await i(p,l.posix.join(G,q));let u=l.join(this.appRoot,ue);if(y.existsSync(u)){let f=y.readFileSync(u,"utf-8");He(f,u),await i(u,l.posix.join(G,ue))}let E=l.join(this.appRoot,J);await i(E,l.posix.join(G,J)),a=await r.close()}catch(p){let u=p instanceof Error?p.message:String(p);throw new Error(`Failed to create zip: ${u}`)}try{await y.promises.writeFile(e,a)}catch(p){throw new d(`Failed to write bundle to ${e}`,{cause:p})}let c=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${c} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=O("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(p){throw p instanceof Error&&"code"in p&&p.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=O("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=r?r.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(t,s);try{O("git",["-C",t,"archive","--format=zip",`--output=${e}`,s])}catch(p){let u=p instanceof Error?p.message:String(p);throw new Error(`Failed to create source archive: ${u}`)}let c=(y.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${l.basename(e)} (${c} MB)`),e}validateNoSensitiveFiles(e,t){let r=O("git",["-C",e,"ls-tree","-r","--name-only",t],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
9
+ `).filter(Boolean),i=o(a=>a.split("/").some(c=>qe.some(p=>p.test(c))),"isSensitive"),s=r.filter(i);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
10
+ `+s.map(a=>` ${a}`).join(`
11
+ `)+`
12
+ Hint: git rm --cached <file>`)}};o(Y,"ApplicationPackager");var T=Y;import Je from"path";var de=".cognite-bundles";function le(n,e){return`${n}-${e}.zip`}o(le,"bundleFileName");function z(n,e,t){return Je.join(n,de,le(e,t))}o(z,"bundlePath");import{CogniteClient as tt}from"@cognite/sdk";function Ge(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}o(Ge,"exponentialBackoffWithJitter");function Ye(n){return new Promise(e=>setTimeout(e,n))}o(Ye,"sleep");async function ge(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),i=e.delayInMsCalculator??Ge;if(t<1)throw new Error("`maxAttempts` must be 1 or greater");if(t>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await n()}catch(a){if(s>=t||!r(a))throw a;let c=i(s);e.onAttemptFail?.(a,s,c),await Ye(c),s++}}o(ge,"retryAsync");var ze="https://auth.cognite.com/oauth2/token",Ke=o(n=>typeof n=="object"&&n!==null&&"access_token"in n&&typeof n.access_token=="string","hasAccessToken");async function fe({idp:n,tokenUrl:e,init:t,missingTokenHint:r}){let i;try{i=await ge(()=>fetch(e,t),{maxAttempts:3})}catch(c){throw new d(`Failed to fetch access token from ${e}`,{cause:c})}if(!i.ok){let c=await i.text();throw new v(`Failed to get token from ${n}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:e,responseBody:c})}let s=await i.text(),a;try{a=JSON.parse(s)}catch{throw new d(`Unexpected response from ${n} authentication (invalid JSON)`,{hint:r})}if(!Ke(a))throw new d(`No access token in ${n} authentication response`,{hint:r});return S.from(a.access_token)}o(fe,"fetchOAuthToken");var We=o(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let e=JSON.parse(n),t={};for(let[r,i]of Object.entries(e))if(typeof i=="string"){let s=r.toLowerCase().replace(/_/g,"-");t[s]=i}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),Xe=o(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=We()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return S.from(e)},"getSecretFromEnv"),Ze=o((n,e)=>{let t=e.expose();return fe({idp:"CDF",tokenUrl:ze,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${n}:${t}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."})},"getTokenCdf"),he=o(({idp:n,tokenUrl:e,clientId:t,clientSecret:r,scopes:i,missingTokenHint:s})=>fe({idp:n,tokenUrl:e,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:t,client_secret:r,grant_type:"client_credentials",...i!==void 0?{scope:i.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),Qe=o((n,e)=>{if(e!==void 0)return e.join(" ");if(!n)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(n).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${n}`)}},"resolveEntraScope"),et=o((n,e,t,r,i)=>he({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,clientId:n,clientSecret:e.expose(),scopes:i!==void 0?i:[Qe(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),K=o(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return S.from(e.COGNITE_TOKEN);let{deployClientId:t,deploySecretName:r,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:c,tokenUrl:p}=n,u=Xe(r);if(i==="oauth"){if(!p)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return he({idp:"OAuth",tokenUrl:p,clientId:t,clientSecret:u.expose(),scopes:c,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return et(t,u,s,a,c)}return Ze(t,u)},"getToken");async function W(n,e,t=process.env,r){let i=await K(n,t),s=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(c=>new tt(c)))({appId:e,project:n.project,baseUrl:s,oidcTokenProvider:o(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}o(W,"getSdk");async function me(n,e,t,r){let{externalId:i,name:s,description:a,versionTag:c}=e,p=z(t,i,c);await nt(ot(p),{recursive:!0}),await new T(`${t}/dist`).createZip(p,!0);let u;try{u=await rt(p)}catch(E){throw new d(`Failed to read bundle file: ${p}`,{cause:E})}await new P(n).deploy(i,s,a,c,u,it(p),r)}o(me,"packageAndUpload");var st=o(async(n,e,t)=>{let r=await W(n,t);await me(r,e,t,n.published)},"deploy");import{existsSync as at,readFileSync as pt}from"fs";var ye=[".dev.sig",".cert.sig"];function ct(n,e={}){let t=e.existsSync??at,r=e.readFileSync??((s,a)=>pt(s,a)),i=[];for(let s of ye){let a=`${n}${s}`;if(!t(a))continue;let c=r(a,"utf8").trim();c.length>0&&i.push(c)}return i}o(ct,"discoverSignatures");export{P as a,T as b,de as c,le as d,z as e,K as f,W as g,me as h,st as i,ye as j,ct as k};
package/dist/cli/cli.js CHANGED
@@ -1,28 +1,26 @@
1
1
  #!/usr/bin/env node
2
- var wo=Object.defineProperty;var o=(e,t)=>wo(e,"name",{value:t,configurable:!0});import{writeSync as Cc}from"fs";import{Command as Ec}from"commander";var Ye=class Ye extends Error{constructor(t,n={}){super(t),this.name="HintedError",n.cause!==void 0&&(this.cause=n.cause);let r=this.deriveDefaults(n);this.hint=n.hint??r.hint,this.helpUrl=n.helpUrl??r.helpUrl,this.shouldReport=n.shouldReport??!0}deriveDefaults(t){return{hint:ko(t.cause)}}};o(Ye,"HintedError");var u=Ye;function Yt(e){return e instanceof u}o(Yt,"isHintedError");var qt="https://docs.cognite.com/cdf/access/",vo="https://status.cognite.com";function Co(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:qt};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:qt};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:vo};default:return{}}}o(Co,"defaultHintForStatus");var Je=class Je extends u{constructor(t,n){super(t,n),this.name="HintedHttpError",this.httpStatusCode=n.httpStatusCode,this.requestUrl=n.requestUrl,this.responseBody=n.responseBody}deriveDefaults(t){let{httpStatusCode:n}=t,r=Co(n),i=super.deriveDefaults(t);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};o(Je,"HintedHttpError");var Q=Je;function Jt(e){return e instanceof Q}o(Jt,"isHintedHttpError");function Eo(e,t){if(e)switch(e){case"ENOTFOUND":return t.hostname?`DNS lookup failed for ${t.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return t.hostname&&t.port?`Connection refused by ${t.hostname}:${t.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return t.path?`Permission denied: ${t.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return t.path?`File or directory not found: ${t.path}.`:"File or directory not found.";case"EISDIR":return t.path?`Expected a file but found a directory: ${t.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return t.port?`Port ${t.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}o(Eo,"hintForErrno");function ko(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let r=t,i=Eo(r.code,r);if(i!==void 0)return i;t=r.cause}}o(ko,"hintForCause");import{existsSync as pi,readFileSync as ci}from"fs";import{join as li,resolve as Ie}from"path";import{verifyBundle as di}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as mi}from"jose";import Xe from"enquirer";import{email as bo,pipe as Po,safeParse as xo,string as Ao}from"valibot";var Do=Po(Ao(),bo());function ie(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!xo(Do,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}o(ie,"parseEmail");function se(e,t="--expires"){let n=Number(e);if(!Number.isInteger(n)||n<1||n>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return n}o(se,"parseExpiryMonths");import{execFileSync as ue}from"child_process";function Ce(e={}){let{execFileSync:t=ue}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(Ce,"isGitInstalled");function Ee(e,t={}){let{execFileSync:n=ue}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(Ee,"isInsideGitRepo");function zt(e,t={}){let{execFileSync:n=ue}=t;n("git",["-C",e,"init"],{stdio:"pipe"}),n("git",["-C",e,"add","."],{stdio:"pipe"}),n("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}o(zt,"gitInitAndCommit");function Wt(e={}){let{execFileSync:t=ue}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(Wt,"gitUserName");function Xt(e={}){let{execFileSync:t=ue}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(Xt,"gitUserEmail");var ke=3,Zt="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",Qt=`Key expiry in months (${1}-${12})`,en="Email address for the registry entry",tn=`Passphrase for the encrypted private key (min ${15} chars)`,nn="Confirm passphrase",rn=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),on=o(e=>`Passphrases do not match (attempt ${e}/${ke}).
3
- `,"passphraseMismatchMsg"),sn=`Passphrase confirmation failed after ${ke} attempts`,an=o(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),pn="How would you like to submit your key registration?",cn="Open in browser",ln="Copy link to clipboard";async function be(e){return Xe.prompt(e)}o(be,"defaultPrompt");function Ze(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}o(Ze,"parserAsValidator");var $o=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function te(e){let t=e.trim();if(!t)throw new Error("--kid must not be empty");if(t.length>64)throw new Error("--kid must be 64 characters or fewer");if(!$o.test(t))throw new Error("--kid must contain only lowercase letters, digits, and hyphens, and must not start or end with a hyphen (e.g. jsmith-dev-001)");return t}o(te,"parseKid");async function dn(e={}){let{prompt:t=be}=e,{kid:n}=await t({type:"input",name:"kid",message:Zt,validate:Ze(te)});return te(n)}o(dn,"promptKid");async function mn(e={}){let{prompt:t=o(r=>Xe.prompt(r),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:pn,choices:[{name:"browser",message:cn},{name:"clipboard",message:ln}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}o(mn,"promptZendeskAction");async function un(e={}){let{prompt:t=be}=e,{months:n}=await t({type:"input",name:"months",message:Qt,initial:String(6),validate:Ze(r=>se(r,"expiry"))});return se(n,"expiry")}o(un,"promptExpiryMonths");async function gn(e={}){let{prompt:t=be,gitUserEmail:n=Xt}=e,{email:r}=await t({type:"input",name:"email",message:en,initial:n(),validate:Ze(i=>ie(i,"email"))});return ie(r,"email")}o(gn,"promptEmail");async function fn(e={}){let{prompt:t=be,stderr:n=process.stderr}=e;for(let r=1;r<=ke;r+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:tn,validate:o(a=>a.length>=15?!0:rn(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:nn});if(i===s)return i;n.write(on(r))}throw new Error(sn)}o(fn,"promptPassphrase");async function yn(e,t={}){let{prompt:n=o(i=>Xe.prompt(i),"prompt")}=t,{confirmed:r}=await n({type:"confirm",name:"confirmed",message:an(e),initial:!1});return r}o(yn,"promptConfirmOverwrite");import{existsSync as Ko,readdirSync as Ho,readFileSync as jo}from"fs";import{join as et}from"path";import{execFile as To}from"child_process";import{promisify as Oo}from"util";import{execFileSync as hn}from"child_process";import{platform as Fo}from"os";import Ro from"path";function T(e,t={}){let{platform:n=Fo}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}o(T,"isOS");function Sn(e,t={}){let{exec:n=hn,log:r=console.log}=t,[i,s]=T("macos",t)?["open",[e]]:T("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{n(i,s)}catch{r(`Could not open browser \u2014 open manually:
4
- ${e}`)}}o(Sn,"openInBrowser");function wn(e,t={}){let{exec:n=hn,log:r=console.log}=t,[i,s]=T("macos",t)?["open",["-R",e]]:T("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[Ro.dirname(e)]];try{n(i,s)}catch{r(`Could not open file manager \u2014 files are at:
5
- ${e}`)}}o(wn,"revealInFileManager");var vn="cognite-flows",Uo=Oo(To),Cn=o((e,t)=>Uo(e,t),"defaultExecFile"),_o=-25300,Lo=_o&255;function No(e){if(!(e instanceof Error)||!("code"in e)||e.code!==Lo)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(No,"isKeychainNotFoundError");async function En(e,t,n={}){if(!T("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:r=Cn}=n;await r("security",["add-generic-password","-a",e,"-s",vn,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(En,"storeKeyInKeychain");async function Pe(e,t={}){if(!T("macos",t))return null;let{execFile:n=Cn}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",vn,"-w"]);return Buffer.from(r.trim(),"base64").toString("utf-8")}catch(r){if(No(r))return null;throw r}}o(Pe,"readKeyFromKeychain");import{homedir as Mo}from"os";import{join as kn}from"path";function x(e={}){let{env:t=process.env,homedir:n=Mo}=e,r=t.COGNITE_CLI_HOME?.trim()||kn(n(),".cognite-cli");return{home:r,keysDir:kn(r,"keys")}}o(x,"getConfig");var J=".pub.pem",tt=".key.jwe",nt=".meta.json";function xe(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}o(xe,"formatLocalKeySource");function Vo(e){return{existsSync:e.existsSync??Ko,readdirSync:e.readdirSync??Ho,readFileSync:e.readFileSync??((t,n)=>jo(t,n)),isOS:e.isOS??(t=>T(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>Pe(t))}}o(Vo,"resolveDeps");function Bo(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}o(Bo,"readEmailFromMeta");function Go(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(J)):[]}o(Go,"publicKeyEntries");function qo(e){return e.slice(0,-J.length)}o(qo,"kidFromPublicKeyFilename");async function Yo(e,t,n){if(n.isOS("macos")&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let r=et(t,`${e}${tt}`);return n.existsSync(r)?{kind:"encrypted-file",path:r}:{kind:"public-only"}}o(Yo,"resolveSource");async function Ae(e=x().keysDir,t={}){let n=Vo(t),r=new Set,i=Go(e,n).flatMap(s=>{let a=qo(s);return!a||r.has(a)?[]:(r.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let p=await Yo(s,e,n),c=et(e,`${s}${nt}`),l;try{l=Bo(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:et(e,a),email:l}}))}o(Ae,"discoverLocalKeys");import{createReadStream as Jo}from"fs";function De(e){let t=Jo(e);return new ReadableStream({start(n){t.on("data",r=>{let i=typeof r=="string"?Buffer.from(r):r;n.enqueue(new Uint8Array(i))}),t.on("end",()=>n.close()),t.on("error",r=>n.error(r))},cancel(){t.destroy()}})}o(De,"createWebStreamFromFile");import zo from"path";var bn=".cognite-bundles";function Pn(e,t){return`${e}-${t}.zip`}o(Pn,"bundleFileName");function B(e,t,n){return zo.join(e,bn,Pn(t,n))}o(B,"bundlePath");import{existsSync as ii,readFileSync as si}from"fs";import{resolve as ai}from"path";import{array as xn,boolean as Wo,check as ae,forward as pe,literal as Xo,maxLength as Zo,minLength as Qo,nonEmpty as z,object as An,optional as G,picklist as ei,pipe as K,safeParse as ti,string as L,url as Dn}from"valibot";var rt=K(L(),z("must not be empty")),ot=K(L(),z("must not be empty"),Zo(256,"must be 256 characters or fewer")),it=K(L(),z("must not be empty"),Dn("must be a valid URL")),ni=K(L(),z("must not be empty"),Dn("must be a valid URL")),st=K(L(),z("must not be empty")),at=K(L(),z("must not be empty")),ri=K(An({org:st,project:at,baseUrl:it,deployClientId:G(L(),""),deploySecretName:G(L(),""),published:G(Wo(),!1),idpType:G(ei(["cdf","entra_id","oauth"]),"cdf"),tenantId:G(L()),scopes:G(xn(K(L(),z("must not be empty")))),tokenUrl:G(ni)}),pe(ae(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),pe(ae(e=>e.idpType!=="oauth"||!!e.tokenUrl,'must be set when idpType is "oauth"'),["tokenUrl"]),pe(ae(e=>!e.tokenUrl||e.idpType==="oauth",'must only be set when idpType is "oauth"'),["tokenUrl"]),pe(ae(e=>e.idpType!=="oauth"||!!e.deployClientId,'must be set when idpType is "oauth"'),["deployClientId"]),pe(ae(e=>e.idpType!=="oauth"||!!e.deploySecretName,'must be set when idpType is "oauth"'),["deploySecretName"]),pe(ae(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),oi=An({name:rt,externalId:ot,versionTag:K(L(),z("must not be empty")),description:G(L(),""),deployments:K(xn(ri),Qo(1,"must contain at least one deployment")),infra:G(Xo("appsApi"))});function pt(e){let t=ti(oi,e);if(t.success)return t.output;let n=t.issues[0],r=n.path?.map(s=>s.key).join(".")??"",i=r?`"${r}" `:"";throw new Error(`app.json: ${i}${n.message}`)}o(pt,"validateAppConfig");function v(e,t={}){let{validator:n=pt,existsSync:r=ii,readFileSync:i=si}=t,s=ai(e,"app.json");if(!r(s))throw new Error(`No app.json found at ${s}. Make sure you're running this command from your app's root directory.`);let a=i(s,"utf-8"),p;try{p=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return n(p)}o(v,"loadAppConfig");var In=[".dev.sig",".cert.sig",".sig"];function ui(e){return{existsSync:e.existsSync??pi,readFileSync:e.readFileSync??((t,n)=>ci(t,n)),createBundleStream:e.createBundleStream??De,verifyBundle:e.verifyBundle??di,loadAppConfig:e.loadAppConfig??v,defaultKeyDir:e.defaultKeyDir??(()=>x().keysDir)}}o(ui,"resolveDeps");function gi(e,t){return In.map(n=>`${e}${n}`).find(n=>t(n))}o(gi,"findSiblingSignature");function fi(e){let t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}o(fi,"isCompactJws");function yi(e){try{let t=mi(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}o(yi,"readKidFromToken");function hi(e,t,n){try{te(e)}catch(i){throw new u(i instanceof Error?i.message:String(i),{shouldReport:!1})}if(!n.existsSync(t))throw new u(`Key directory not found: ${t}`,{shouldReport:!1});let r=li(t,`${e}${J}`);if(!n.existsSync(r))throw new u(`No public key found for kid "${e}" in ${t}`,{shouldReport:!1});try{return n.readFileSync(r,"utf-8")}catch(i){throw new u(`Failed to read public key file: ${r}`,{cause:i,shouldReport:!1})}}o(hi,"resolvePublicKeyForKid");function Si(e,t){let{payload:n,kid:r}=e;if(console.log(`Verified ${n.appId}@${n.version}`),console.log(` kid: ${r}`),console.log(` hash: ${n.bundleSha256}`),n.scopes&&n.scopes.length>0){let i=n.scopes.map(s=>`${s.org}/${s.project}`).join(", ");console.log(` scopes: ${i}`)}t&&console.log(JSON.stringify(n,null,2))}o(Si,"printResult");async function $n(e,t,n={},r=process.cwd()){let i=ui(n),s;if(e)s=Ie(r,e);else{let l;try{l=i.loadAppConfig(r)}catch(d){let m=d instanceof Error?d.message:String(d);throw new u(m,{cause:d,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}s=B(r,l.externalId,l.versionTag)}if(!i.existsSync(s)){let l=e?void 0:"Default derived from app.json \u2014 pass [bundle] explicitly to override.";throw new u(`Bundle not found: ${s}`,{hint:l,shouldReport:!1})}let a=t.sig?Ie(r,t.sig):gi(s,i.existsSync);if(!a)throw new u("No signature file found.",{hint:`Pass --sig <path> or place one of ${In.map(l=>`${s}${l}`).join(", ")} next to the bundle.`,shouldReport:!1});if(!i.existsSync(a))throw new u(`Signature file not found: ${a}`,{shouldReport:!1});let p;try{p=i.readFileSync(a,"utf-8").trim()}catch(l){throw new u(`Failed to read signature file: ${a}`,{cause:l,shouldReport:!1})}if(!fi(p))throw new u(`Malformed JWS in ${a}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let c;if(t.key){let l=Ie(r,t.key);if(!i.existsSync(l))throw new u(`Public key not found: ${l}`,{shouldReport:!1});try{c=i.readFileSync(l,"utf-8")}catch(d){throw new u(`Failed to read public key file: ${l}`,{cause:d,shouldReport:!1})}}else{let l=t.keyDir?Ie(r,t.keyDir):i.defaultKeyDir(),d=yi(p);if(!d)throw new u("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});c=hi(d,l,i)}try{let l=await i.verifyBundle({token:p,publicKeyPem:c,bundleStream:i.createBundleStream(s)});Si(l,t.verbose??!1)}catch(l){let d=l instanceof Error?l.message:String(l);throw new u(`Bundle rejected: ${d}`,{shouldReport:!1})}}o($n,"handleVerify");function Fn(e,t={}){return e.command("verify [bundle]").description("Verify a signed app bundle locally (default: derived from app.json)").option("-s, --sig <path>","Path to the signature file (default: sibling .dev.sig / .cert.sig / .sig)").option("--key <path>","Path to a public key PEM file").option("--key-dir <path>","Directory of <kid>.pub.pem files \u2014 kid is read from the token header (default: $COGNITE_CLI_HOME/keys)").option("-v, --verbose","Print the full decoded payload after verification").addHelpText("after",`
2
+ var _i=Object.defineProperty;var en=e=>{throw TypeError(e)};var i=(e,t)=>_i(e,"name",{value:t,configurable:!0});var tn=(e,t,n)=>t.has(e)||en("Cannot "+n);var nn=(e,t,n)=>(tn(e,t,"read from private field"),n?n.call(e):t.get(e)),rn=(e,t,n)=>t.has(e)?en("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),on=(e,t,n,r)=>(tn(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);import{writeSync as Gc}from"fs";import{Command as Yc}from"commander";var et=class et extends Error{constructor(t,n={}){super(t),this.name="HintedError",n.cause!==void 0&&(this.cause=n.cause);let r=this.deriveDefaults(n);this.hint=n.hint??r.hint,this.helpUrl=n.helpUrl??r.helpUrl,this.shouldReport=n.shouldReport??!0}deriveDefaults(t){return{hint:Mi(t.cause)}}};i(et,"HintedError");var u=et;function an(e){return e instanceof u}i(an,"isHintedError");var sn="https://docs.cognite.com/cdf/access/",Ki="https://status.cognite.com";function Li(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:sn};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:sn};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:Ki};default:return{}}}i(Li,"defaultHintForStatus");var tt=class tt extends u{constructor(t,n){super(t,n),this.name="HintedHttpError",this.httpStatusCode=n.httpStatusCode,this.requestUrl=n.requestUrl,this.responseBody=n.responseBody}deriveDefaults(t){let{httpStatusCode:n}=t,r=Li(n),o=super.deriveDefaults(t);return{hint:r.hint??o.hint,helpUrl:r.helpUrl}}};i(tt,"HintedHttpError");var te=tt;function pn(e){return e instanceof te}i(pn,"isHintedHttpError");function Ni(e,t){if(e)switch(e){case"ENOTFOUND":return t.hostname?`DNS lookup failed for ${t.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return t.hostname&&t.port?`Connection refused by ${t.hostname}:${t.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return t.path?`Permission denied: ${t.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return t.path?`File or directory not found: ${t.path}.`:"File or directory not found.";case"EISDIR":return t.path?`Expected a file but found a directory: ${t.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return t.port?`Port ${t.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}i(Ni,"hintForErrno");function Mi(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let r=t,o=Ni(r.code,r);if(o!==void 0)return o;t=r.cause}}i(Mi,"hintForCause");import{existsSync as $o,readFileSync as Ro}from"fs";import{join as To,resolve as _e}from"path";import{verifyBundle as Fo}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as Oo}from"jose";import ot from"enquirer";import{email as Hi,pipe as ji,safeParse as Vi,string as Bi}from"valibot";var Gi=ji(Bi(),Hi());function ae(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!Vi(Gi,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}i(ae,"parseEmail");function pe(e,t="--expires"){let n=Number(e);if(!Number.isInteger(n)||n<1||n>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return n}i(pe,"parseExpiryMonths");import{execFileSync as fe}from"child_process";function Pe(e={}){let{execFileSync:t=fe}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}i(Pe,"isGitInstalled");function xe(e,t={}){let{execFileSync:n=fe}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}i(xe,"isInsideGitRepo");function cn(e,t={}){let{execFileSync:n=fe}=t;n("git",["-C",e,"init"],{stdio:"pipe"}),n("git",["-C",e,"add","."],{stdio:"pipe"}),n("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}i(cn,"gitInitAndCommit");function ln(e={}){let{execFileSync:t=fe}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}i(ln,"gitUserName");function dn(e={}){let{execFileSync:t=fe}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}i(dn,"gitUserEmail");import{inspect as Yi}from"util";var nt="[REDACTED]",ye,Ae=class Ae{constructor(t){rn(this,ye);on(this,ye,t)}toString(){return nt}toJSON(){return nt}[Yi.custom](){return nt}expose(){return nn(this,ye)}static from(t){return new Ae(t)}};ye=new WeakMap,i(Ae,"SensitiveString");var w=Ae;var De=3,mn="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",un=`Key expiry in months (${1}-${12})`,gn="Email address for the registry entry",fn=`Passphrase for the encrypted private key (min ${15} chars)`,yn="Confirm passphrase",hn=i(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),Sn=i(e=>`Passphrases do not match (attempt ${e}/${De}).
3
+ `,"passphraseMismatchMsg"),wn=`Passphrase confirmation failed after ${De} attempts`,vn=i(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),Cn="How would you like to submit your key registration?",En="Open in browser",kn="Copy link to clipboard";async function Ie(e){return ot.prompt(e)}i(Ie,"defaultPrompt");function st(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}i(st,"parserAsValidator");var Ji=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function re(e){let t=e.trim();if(!t)throw new Error("--kid must not be empty");if(t.length>64)throw new Error("--kid must be 64 characters or fewer");if(!Ji.test(t))throw new Error("--kid must contain only lowercase letters, digits, and hyphens, and must not start or end with a hyphen (e.g. jsmith-dev-001)");return t}i(re,"parseKid");async function bn(e={}){let{prompt:t=Ie}=e,{kid:n}=await t({type:"input",name:"kid",message:mn,validate:st(re)});return re(n)}i(bn,"promptKid");async function Pn(e={}){let{prompt:t=i(r=>ot.prompt(r),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:Cn,choices:[{name:"browser",message:En},{name:"clipboard",message:kn}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}i(Pn,"promptZendeskAction");async function xn(e={}){let{prompt:t=Ie}=e,{months:n}=await t({type:"input",name:"months",message:un,initial:String(6),validate:st(r=>pe(r,"expiry"))});return pe(n,"expiry")}i(xn,"promptExpiryMonths");async function An(e={}){let{prompt:t=Ie,gitUserEmail:n=dn}=e,{email:r}=await t({type:"input",name:"email",message:gn,initial:n(),validate:st(o=>ae(o,"email"))});return ae(r,"email")}i(An,"promptEmail");async function Dn(e={}){let{prompt:t=Ie,stderr:n=process.stderr}=e;for(let r=1;r<=De;r+=1){let{passphrase:o}=await t({type:"password",name:"passphrase",message:fn,validate:i(a=>a.length>=15?!0:hn(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:yn});if(o===s)return w.from(o);n.write(Sn(r))}throw new Error(wn)}i(Dn,"promptPassphrase");async function In(e,t={}){let{prompt:n=i(o=>ot.prompt(o),"prompt")}=t,{confirmed:r}=await n({type:"confirm",name:"confirmed",message:vn(e),initial:!1});return r}i(In,"promptConfirmOverwrite");import{existsSync as ao,readdirSync as po,readFileSync as co}from"fs";import{join as pt}from"path";import{execFile as Xi}from"child_process";import{promisify as Zi}from"util";import{execFileSync as $n}from"child_process";import{platform as Wi}from"os";import zi from"path";function A(e,t={}){let{platform:n=Wi}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}i(A,"isOS");function Rn(e,t={}){let{exec:n=$n,log:r=console.log}=t,[o,s]=A("macos",t)?["open",[e]]:A("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{n(o,s)}catch{r(`Could not open browser \u2014 open manually:
4
+ ${e}`)}}i(Rn,"openInBrowser");function Tn(e,t={}){let{exec:n=$n,log:r=console.log}=t,[o,s]=A("macos",t)?["open",["-R",e]]:A("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[zi.dirname(e)]];try{n(o,s)}catch{r(`Could not open file manager \u2014 files are at:
5
+ ${e}`)}}i(Tn,"revealInFileManager");var Fn="cognite-flows",Qi=Zi(Xi),On=i((e,t)=>Qi(e,t),"defaultExecFile"),eo=-25300,to=eo&255;function no(e){if(!(e instanceof Error)||!("code"in e)||e.code!==to)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}i(no,"isKeychainNotFoundError");async function Un(e,t,n={}){let r=t.expose();if(!A("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:o=On}=n;await o("security",["add-generic-password","-a",e,"-s",Fn,"-w",Buffer.from(r,"utf-8").toString("base64"),"-U"])}i(Un,"storeKeyInKeychain");async function Re(e,t={}){if(!A("macos",t))return null;let{execFile:n=On}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",Fn,"-w"]);return w.from(Buffer.from(r.trim(),"base64").toString("utf-8"))}catch(r){if(no(r))return null;throw r}}i(Re,"readKeyFromKeychain");var Kn="cognite-cli-signing",ro="The native @napi-rs/keyring binary failed to load for this platform. Reinstall the CLI, or regenerate the key with `--output <path>` to use passphrase-encrypted file storage instead.",io="Multiple Windows Credential Manager entries match this kid. Open Credential Manager (Control Panel \u2192 User Accounts \u2192 Credential Manager \u2192 Windows Credentials) and remove the duplicates.",_n="Windows Credential Manager failed unexpectedly. Regenerate the key with `--output <path>` to fall back to passphrase-encrypted file storage.";function oo(e){if(!(e instanceof Error))return _n;let t=e.message.toLowerCase();return t.includes("cannot find module")||t.includes("module_not_found")||t.includes("failed to load native binding")?ro:t.includes("ambiguous")?io:_n}i(oo,"hintFor");function Ln(e,t,n){return new u(`Failed to ${e} signing key for kid "${t}" in Windows Credential Manager`,{cause:n,hint:oo(n),shouldReport:!1})}i(Ln,"wrapKeyringError");async function Nn(e,t){let{Entry:n}=await import("@napi-rs/keyring"),r=new n(e,t);return{setPassword:i(o=>r.setPassword(o),"setPassword"),getPassword:i(()=>r.getPassword(),"getPassword"),deleteCredential:i(()=>r.deleteCredential(),"deleteCredential")}}i(Nn,"defaultCreateEntry");async function Mn(e,t,n={}){let{createEntry:r=Nn}=n,o=Buffer.from(t.expose(),"utf-8").toString("base64");try{(await r(Kn,e)).setPassword(o)}catch(s){throw Ln("store",e,s)}}i(Mn,"storeSigningKey");async function Te(e,t={}){let{createEntry:n=Nn}=t;try{let o=(await n(Kn,e)).getPassword();return o===null?null:w.from(Buffer.from(o,"base64").toString("utf-8"))}catch(r){throw Ln("read",e,r)}}i(Te,"readSigningKey");import{homedir as so}from"os";import{join as at}from"path";function $(e={}){let{env:t=process.env,homedir:n=so}=e,r=t.COGNITE_CLI_HOME?.trim()||at(n(),".cognite-cli");return{home:r,keysDir:at(r,"keys"),sessionFile:at(r,"session.json")}}i($,"getConfig");var J=".pub.pem",ct=".key.jwe",lt=".meta.json";function Fe(e){switch(e.kind){case"keychain":return"OS credential store";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}i(Fe,"formatLocalKeySource");function lo(e){return{existsSync:e.existsSync??ao,readdirSync:e.readdirSync??po,readFileSync:e.readFileSync??((t,n)=>co(t,n)),isOS:e.isOS??(t=>A(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>Re(t)),readSigningKey:e.readSigningKey??(t=>Te(t))}}i(lo,"resolveDeps");function mo(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}i(mo,"readEmailFromMeta");function uo(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(J)):[]}i(uo,"publicKeyEntries");function go(e){return e.slice(0,-J.length)}i(go,"kidFromPublicKeyFilename");async function fo(e,t,n){if(n.isOS("macos")&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};if(n.isOS("windows")&&await n.readSigningKey(e).catch(()=>null)!==null)return{kind:"keychain"};let r=pt(t,`${e}${ct}`);return n.existsSync(r)?{kind:"encrypted-file",path:r}:{kind:"public-only"}}i(fo,"resolveSource");async function Oe(e=$().keysDir,t={}){let n=lo(t),r=new Set,o=uo(e,n).flatMap(s=>{let a=go(s);return!a||r.has(a)?[]:(r.add(a),[{kid:a,entry:s}])});return Promise.all(o.map(async({kid:s,entry:a})=>{let p=await fo(s,e,n),c=pt(e,`${s}${lt}`),l;try{l=mo(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:pt(e,a),email:l}}))}i(Oe,"discoverLocalKeys");import{createReadStream as yo}from"fs";function Ue(e){let t=yo(e);return new ReadableStream({start(n){t.on("data",r=>{let o=typeof r=="string"?Buffer.from(r):r;n.enqueue(new Uint8Array(o))}),t.on("end",()=>n.close()),t.on("error",r=>n.error(r))},cancel(){t.destroy()}})}i(Ue,"createWebStreamFromFile");import ho from"path";var Hn=".cognite-bundles";function jn(e,t){return`${e}-${t}.zip`}i(jn,"bundleFileName");function B(e,t,n){return ho.join(e,Hn,jn(t,n))}i(B,"bundlePath");import{existsSync as Ao,readFileSync as Do}from"fs";import{resolve as Io}from"path";import{array as Vn,boolean as So,check as ce,forward as le,literal as wo,maxLength as vo,minLength as Co,nonEmpty as W,object as Bn,optional as G,picklist as Eo,pipe as H,safeParse as ko,string as L,url as Gn}from"valibot";var dt=H(L(),W("must not be empty")),mt=H(L(),W("must not be empty"),vo(256,"must be 256 characters or fewer")),ut=H(L(),W("must not be empty"),Gn("must be a valid URL")),bo=H(L(),W("must not be empty"),Gn("must be a valid URL")),gt=H(L(),W("must not be empty")),ft=H(L(),W("must not be empty")),Po=H(Bn({org:gt,project:ft,baseUrl:ut,deployClientId:G(L(),""),deploySecretName:G(L(),""),published:G(So(),!1),idpType:G(Eo(["cdf","entra_id","oauth"]),"cdf"),tenantId:G(L()),scopes:G(Vn(H(L(),W("must not be empty")))),tokenUrl:G(bo)}),le(ce(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),le(ce(e=>e.idpType!=="oauth"||!!e.tokenUrl,'must be set when idpType is "oauth"'),["tokenUrl"]),le(ce(e=>!e.tokenUrl||e.idpType==="oauth",'must only be set when idpType is "oauth"'),["tokenUrl"]),le(ce(e=>e.idpType!=="oauth"||!!e.deployClientId,'must be set when idpType is "oauth"'),["deployClientId"]),le(ce(e=>e.idpType!=="oauth"||!!e.deploySecretName,'must be set when idpType is "oauth"'),["deploySecretName"]),le(ce(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),xo=Bn({name:dt,externalId:mt,versionTag:H(L(),W("must not be empty")),description:G(L(),""),deployments:H(Vn(Po),Co(1,"must contain at least one deployment")),infra:G(wo("appsApi"))});function yt(e){let t=ko(xo,e);if(t.success)return t.output;let n=t.issues[0],r=n.path?.map(s=>s.key).join(".")??"",o=r?`"${r}" `:"";throw new Error(`app.json: ${o}${n.message}`)}i(yt,"validateAppConfig");function E(e,t={}){let{validator:n=yt,existsSync:r=Ao,readFileSync:o=Do}=t,s=Io(e,"app.json");if(!r(s))throw new Error(`No app.json found at ${s}. Make sure you're running this command from your app's root directory.`);let a=o(s,"utf-8"),p;try{p=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return n(p)}i(E,"loadAppConfig");var Yn=[".dev.sig",".cert.sig",".sig"];function Uo(e){return{existsSync:e.existsSync??$o,readFileSync:e.readFileSync??((t,n)=>Ro(t,n)),createBundleStream:e.createBundleStream??Ue,verifyBundle:e.verifyBundle??Fo,loadAppConfig:e.loadAppConfig??E,defaultKeyDir:e.defaultKeyDir??(()=>$().keysDir)}}i(Uo,"resolveDeps");function _o(e,t){return Yn.map(n=>`${e}${n}`).find(n=>t(n))}i(_o,"findSiblingSignature");function Ko(e){let t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}i(Ko,"isCompactJws");function Lo(e){try{let t=Oo(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}i(Lo,"readKidFromToken");function No(e,t,n){try{re(e)}catch(o){throw new u(o instanceof Error?o.message:String(o),{shouldReport:!1})}if(!n.existsSync(t))throw new u(`Key directory not found: ${t}`,{shouldReport:!1});let r=To(t,`${e}${J}`);if(!n.existsSync(r))throw new u(`No public key found for kid "${e}" in ${t}`,{shouldReport:!1});try{return n.readFileSync(r,"utf-8")}catch(o){throw new u(`Failed to read public key file: ${r}`,{cause:o,shouldReport:!1})}}i(No,"resolvePublicKeyForKid");function Mo(e,t){let{payload:n,kid:r}=e;if(console.log(`Verified ${n.appId}@${n.version}`),console.log(` kid: ${r}`),console.log(` hash: ${n.bundleSha256}`),n.scopes&&n.scopes.length>0){let o=n.scopes.map(s=>`${s.org}/${s.project}`).join(", ");console.log(` scopes: ${o}`)}t&&console.log(JSON.stringify(n,null,2))}i(Mo,"printResult");async function qn(e,t,n={},r=process.cwd()){let o=Uo(n),s;if(e)s=_e(r,e);else{let l;try{l=o.loadAppConfig(r)}catch(d){let m=d instanceof Error?d.message:String(d);throw new u(m,{cause:d,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}s=B(r,l.externalId,l.versionTag)}if(!o.existsSync(s)){let l=e?void 0:"Default derived from app.json \u2014 pass [bundle] explicitly to override.";throw new u(`Bundle not found: ${s}`,{hint:l,shouldReport:!1})}let a=t.sig?_e(r,t.sig):_o(s,o.existsSync);if(!a)throw new u("No signature file found.",{hint:`Pass --sig <path> or place one of ${Yn.map(l=>`${s}${l}`).join(", ")} next to the bundle.`,shouldReport:!1});if(!o.existsSync(a))throw new u(`Signature file not found: ${a}`,{shouldReport:!1});let p;try{p=o.readFileSync(a,"utf-8").trim()}catch(l){throw new u(`Failed to read signature file: ${a}`,{cause:l,shouldReport:!1})}if(!Ko(p))throw new u(`Malformed JWS in ${a}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let c;if(t.key){let l=_e(r,t.key);if(!o.existsSync(l))throw new u(`Public key not found: ${l}`,{shouldReport:!1});try{c=o.readFileSync(l,"utf-8")}catch(d){throw new u(`Failed to read public key file: ${l}`,{cause:d,shouldReport:!1})}}else{let l=t.keyDir?_e(r,t.keyDir):o.defaultKeyDir(),d=Lo(p);if(!d)throw new u("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});c=No(d,l,o)}try{let l=await o.verifyBundle({token:p,publicKeyPem:c,bundleStream:o.createBundleStream(s)});Mo(l,t.verbose??!1)}catch(l){let d=l instanceof Error?l.message:String(l);throw new u(`Bundle rejected: ${d}`,{shouldReport:!1})}}i(qn,"handleVerify");function Jn(e,t={}){return e.command("verify [bundle]").description("Verify a signed app bundle locally (default: derived from app.json)").option("-s, --sig <path>","Path to the signature file (default: sibling .dev.sig / .cert.sig / .sig)").option("--key <path>","Path to a public key PEM file").option("--key-dir <path>","Directory of <kid>.pub.pem files \u2014 kid is read from the token header (default: $COGNITE_CLI_HOME/keys)").option("-v, --verbose","Print the full decoded payload after verification").addHelpText("after",`
6
6
  Bundles are stored in .cognite-bundles/<externalId>-<versionTag>.zip by default.
7
7
 
8
8
  Examples:
9
9
  cognite apps verify Verify default bundle (path from app.json)
10
10
  cognite apps verify .cognite-bundles/my-app-1.0.0.zip Verify a specific bundle
11
11
  cognite apps verify .cognite-bundles/my-app-1.0.0.zip --sig my-app-1.0.0.zip.dev.sig Verify with explicit signature
12
- cognite apps verify .cognite-bundles/my-app-1.0.0.zip --key /path/to/pub.pem Verify with explicit public key`).action((n,r)=>$n(n,r,t))}o(Fn,"registerVerifyCommand");var Rn="https://docs.cognite.com/cdf/access/";function O(e){return e!==null&&typeof e=="object"}o(O,"isRecord");function ne(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(ne,"isHttpError");function wi(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
13
- See: ${Rn}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
14
- See: ${Rn}`;default:return}}o(wi,"httpStatusHint");function q(e){let t=e instanceof Error?e:new Error(String(e));if(!ne(t))return null;let n=wi(t.status);return n?Object.assign(new Error(`${t.message}
15
- ${n}`),{cause:t}):null}o(q,"enrichedHttpError");function vi(e){if(!O(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(O(n)){let r=n.error;if(O(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}o(vi,"findMissingArray");function Ci(e,t){if(!ne(e)||e.status!==400)return!1;let n=vi(e);return n?n.some(r=>O(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}o(Ci,"isMissingExternalIdError");function $e(e,t){return ne(e)&&e.status===404||Ci(e,t)}o($e,"isNotFoundError");var On=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Un=["ACTIVE","PREVIEW"],ct=class ct extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};o(ct,"AppVersionNotFoundError");var H=ct,lt=class lt extends Error{constructor(t){super(`App ${t} not found`),this.name="AppNotFoundError",this.appExternalId=t}};o(lt,"AppNotFoundError");var ce=lt;function Fe(e,t){return e.includes(t)}o(Fe,"includesValue");function Ei(e){return Fe(On,e)}o(Ei,"isAppVersionLifecycleState");function ki(e){return Fe(Un,e)}o(ki,"isAppVersionAlias");function bi(e){return typeof e.version=="string"&&Ei(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||ki(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(bi,"isAppVersion");function Tn(e){if(!O(e)){let t=JSON.stringify(e)?.slice(0,200)??String(e);throw new Error(`Invalid version response: expected object, got ${t}`)}if(!bi(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}o(Tn,"parseAppVersion");function Pi(e){if(!O(e))throw new Error("Invalid app response: not an object");let{externalId:t,name:n,description:r}=e;if(typeof t!="string")throw new Error("Invalid app response: missing externalId");if(typeof n!="string")throw new Error("Invalid app response: missing name");if(r!=null&&typeof r!="string")throw new Error("Invalid app response: malformed description");return{externalId:t,name:n,description:typeof r=="string"?r:void 0}}o(Pi,"parseAppMetadata");var dt=class dt{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:r}]}})}catch(i){throw q(i)??i}}async updateApps(t){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:t}})}catch(n){throw q(n)??n}}async getApp(t){let n=`${this.appsBasePath}/${encodeURIComponent(t)}`;try{let r=await this.client.get(n);return Pi(r.data)}catch(r){throw $e(r,[t])?new ce(t):q(r)??r}}async uploadVersion(t,n,r,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),i),a.append("version",n),a.append("entryPath",s);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,l=await this.client.authenticate(),d=`${this.client.getBaseUrl()}${c}`,m=new AbortController,y=setTimeout(()=>m.abort(),300*1e3),f;try{f=await fetch(d,{method:"POST",headers:{Authorization:`Bearer ${l}`},body:a,signal:m.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?new u("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new u(`Failed to upload version to ${d}`,{cause:g,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(y)}if(!f.ok){let g=await f.text(),S;try{S=JSON.parse(g)}catch{}let w=g;if(O(S)){let M=S.error;if(typeof M=="string")w=M;else if(O(M)){let U=M.message,j=M.code;w=typeof U=="string"?U:j!=null?`Unknown error (code: ${j})`:g}else{let U=S.message;w=typeof U=="string"?U:g}}let P=f.headers.get("x-request-id"),h=P?` | X-Request-ID: ${P}`:"";throw new Q(`Upload failed: ${f.status} \u2014 ${w}${h}`,{httpStatusCode:f.status,requestUrl:d,responseBody:O(S)?S:g})}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),i=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${i}`;try{let a=await this.client.get(s);return Tn(a.data)}catch(a){throw $e(a,[t,n])?new H(t,n):q(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/versions/list`;try{let i=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!O(i.data)||!Array.isArray(i.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=i.data;if(s.length===0)return null;if(s.length>1)throw new Error(`Unexpected response: ${s.length} versions have the ACTIVE alias, expected at most 1`);return Tn(s[0])}catch(i){if($e(i,[t]))return null;throw q(i)??i}}async updateVersions(t,n){let r=encodeURIComponent(t),i=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(i,{data:{items:n}})}catch(s){throw q(s)??s}}async submitSignatures(t,n,r){let i=encodeURIComponent(t),s=encodeURIComponent(n),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(p){throw q(p)??p}}async listSignatures(t,n){let r=encodeURIComponent(t),i=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${i}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return Di(a.data)}catch(a){throw q(a)??a}}};o(dt,"AppHostingApi");var Re=dt,xi=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Ai=["developer","certifier"];function Di(e){if(!O(e))throw new Error("Invalid signatures response: expected an object with an items array");let{items:t}=e;if(!Array.isArray(t))throw new Error("Invalid signatures response: items property is missing or not an array");return t.flatMap(n=>{let r=Ii(n);return r?[r]:[]})}o(Di,"parseStoredSignatures");function Ii(e){if(!O(e))return null;let{signerKid:t,signerRole:n,signatureIat:r,receivedAt:i,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Fe(Ai,n)||typeof r!="number"||typeof i!="number"||typeof s!="number"||!Fe(xi,a)?null:{signerKid:t,signerRole:n,signatureIat:r,receivedAt:i,createdTime:s,status:a}}o(Ii,"parseStoredSignature");function mt(e,t){let n=[];e.name!==t.name&&n.push({field:"name",remote:e.name,local:t.name});let r=e.description??"";return r!==t.description&&n.push({field:"description",remote:r,local:t.description}),n}o(mt,"diffAppMetadata");function $i(e){let t=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:n,remote:r,local:i}of e){let s=`${n}:`.padEnd(14);t.push(` ${s}"${r}" \u2192 "${i}"`)}return t.join(`
16
- `)}o($i,"formatMetadataDriftError");var ut=class ut{constructor(t){this.api=new Re(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,i,s){return this.api.uploadVersion(t,n,r,i,s)}async ensureApp(t,n,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,r),console.log(`\u2705 App '${t}' created`)}catch(i){if(ne(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`),await this.checkMetadataDrift(t,n,r);return}throw i}}async checkMetadataDrift(t,n,r){let i;try{i=await this.getApp(t)}catch{return}let s=mt(i,{name:n,description:r});if(s.length!==0)throw new u($i(s),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(t){return this.api.getApp(t)}async updateAppMetadata(t,n,r){await this.api.updateApps([{externalId:t,update:{name:{set:n},description:r?{set:r}:{setNull:!0}}}])}async submitSignatures(t,n,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${n}...`),await this.api.submitSignatures(t,n,r),console.log("\u2705 Signatures stored"))}listSignatures(t,n){return this.api.listSignatures(t,n)}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{alias:{setNull:!0}}}])}async activateVersion(t,n){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let i=r&&r.version!==n?r.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(t,n,r,i,s,a,p=!1){console.log(`
12
+ cognite apps verify .cognite-bundles/my-app-1.0.0.zip --key /path/to/pub.pem Verify with explicit public key`).action((n,r)=>qn(n,r,t))}i(Jn,"registerVerifyCommand");var Wn="https://docs.cognite.com/cdf/access/";function K(e){return e!==null&&typeof e=="object"}i(K,"isRecord");function ie(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}i(ie,"isHttpError");function Ho(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
13
+ See: ${Wn}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
14
+ See: ${Wn}`;default:return}}i(Ho,"httpStatusHint");function Y(e){let t=e instanceof Error?e:new Error(String(e));if(!ie(t))return null;let n=Ho(t.status);return n?Object.assign(new Error(`${t.message}
15
+ ${n}`),{cause:t}):null}i(Y,"enrichedHttpError");function jo(e){if(!K(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(K(n)){let r=n.error;if(K(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}i(jo,"findMissingArray");function Vo(e,t){if(!ie(e)||e.status!==400)return!1;let n=jo(e);return n?n.some(r=>K(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}i(Vo,"isMissingExternalIdError");function Ke(e,t){return ie(e)&&e.status===404||Vo(e,t)}i(Ke,"isNotFoundError");var Xn=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Zn=["ACTIVE","PREVIEW"],ht=class ht extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};i(ht,"AppVersionNotFoundError");var j=ht,St=class St extends Error{constructor(t){super(`App ${t} not found`),this.name="AppNotFoundError",this.appExternalId=t}};i(St,"AppNotFoundError");var de=St;function Le(e,t){return e.includes(t)}i(Le,"includesValue");function Bo(e){return Le(Xn,e)}i(Bo,"isAppVersionLifecycleState");function Go(e){return Le(Zn,e)}i(Go,"isAppVersionAlias");function Yo(e){return typeof e.version=="string"&&Bo(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||Go(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}i(Yo,"isAppVersion");function zn(e){if(!K(e)){let t=JSON.stringify(e)?.slice(0,200)??String(e);throw new Error(`Invalid version response: expected object, got ${t}`)}if(!Yo(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}i(zn,"parseAppVersion");function qo(e){if(!K(e))throw new Error("Invalid app response: not an object");let{externalId:t,name:n,description:r}=e;if(typeof t!="string")throw new Error("Invalid app response: missing externalId");if(typeof n!="string")throw new Error("Invalid app response: missing name");if(r!=null&&typeof r!="string")throw new Error("Invalid app response: malformed description");return{externalId:t,name:n,description:typeof r=="string"?r:void 0}}i(qo,"parseAppMetadata");var wt=class wt{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:r}]}})}catch(o){throw Y(o)??o}}async updateApps(t){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:t}})}catch(n){throw Y(n)??n}}async getApp(t){let n=`${this.appsBasePath}/${encodeURIComponent(t)}`;try{let r=await this.client.get(n);return qo(r.data)}catch(r){throw Ke(r,[t])?new de(t):Y(r)??r}}async uploadVersion(t,n,r,o,s="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),o),a.append("version",n),a.append("entryPath",s);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,l=await this.client.authenticate();if(!l)throw new u("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let d=w.from(l),m=`${this.client.getBaseUrl()}${c}`,f=new AbortController,h=setTimeout(()=>f.abort(),300*1e3),g;try{g=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${d.expose()}`},body:a,signal:f.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new u("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new u(`Failed to upload version to ${m}`,{cause:y,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(h)}if(!g.ok){let y=await g.text(),S;try{S=JSON.parse(y)}catch{}let b=y;if(K(S)){let V=S.error;if(typeof V=="string")b=V;else if(K(V)){let I=V.message,k=V.code;b=typeof I=="string"?I:k!=null?`Unknown error (code: ${k})`:y}else{let I=S.message;b=typeof I=="string"?I:y}}let v=g.headers.get("x-request-id"),C=v?` | X-Request-ID: ${v}`:"",z=K(S)?S:y;throw new te(`Upload failed: ${g.status} \u2014 ${b}${C}`,{httpStatusCode:g.status,requestUrl:m,responseBody:z})}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),o=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${o}`;try{let a=await this.client.get(s);return zn(a.data)}catch(a){throw Ke(a,[t,n])?new j(t,n):Y(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/versions/list`;try{let o=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!K(o.data)||!Array.isArray(o.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=o.data;if(s.length===0)return null;if(s.length>1)throw new Error(`Unexpected response: ${s.length} versions have the ACTIVE alias, expected at most 1`);return zn(s[0])}catch(o){if(Ke(o,[t]))return null;throw Y(o)??o}}async updateVersions(t,n){let r=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:n}})}catch(s){throw Y(s)??s}}async submitSignatures(t,n,r){let o=encodeURIComponent(t),s=encodeURIComponent(n),a=`${this.appsBasePath}/${o}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(p){throw Y(p)??p}}async listSignatures(t,n){let r=encodeURIComponent(t),o=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${o}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return zo(a.data)}catch(a){throw Y(a)??a}}};i(wt,"AppHostingApi");var Ne=wt,Jo=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Wo=["developer","certifier"];function zo(e){if(!K(e))throw new Error("Invalid signatures response: expected an object with an items array");let{items:t}=e;if(!Array.isArray(t))throw new Error("Invalid signatures response: items property is missing or not an array");return t.flatMap(n=>{let r=Xo(n);return r?[r]:[]})}i(zo,"parseStoredSignatures");function Xo(e){if(!K(e))return null;let{signerKid:t,signerRole:n,signatureIat:r,receivedAt:o,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Le(Wo,n)||typeof r!="number"||typeof o!="number"||typeof s!="number"||!Le(Jo,a)?null:{signerKid:t,signerRole:n,signatureIat:r,receivedAt:o,createdTime:s,status:a}}i(Xo,"parseStoredSignature");function vt(e,t){let n=[];e.name!==t.name&&n.push({field:"name",remote:e.name,local:t.name});let r=e.description??"";return r!==t.description&&n.push({field:"description",remote:r,local:t.description}),n}i(vt,"diffAppMetadata");function Zo(e){let t=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:n,remote:r,local:o}of e){let s=`${n}:`.padEnd(14);t.push(` ${s}"${r}" \u2192 "${o}"`)}return t.join(`
16
+ `)}i(Zo,"formatMetadataDriftError");var Ct=class Ct{constructor(t){this.api=new Ne(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,o,s){return this.api.uploadVersion(t,n,r,o,s)}async ensureApp(t,n,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,r),console.log(`\u2705 App '${t}' created`)}catch(o){if(ie(o)&&o.status===409){console.log(`\u2705 App '${t}' already exists`),await this.checkMetadataDrift(t,n,r);return}throw o}}async checkMetadataDrift(t,n,r){let o;try{o=await this.getApp(t)}catch{return}let s=vt(o,{name:n,description:r});if(s.length!==0)throw new u(Zo(s),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(t){return this.api.getApp(t)}async updateAppMetadata(t,n,r){await this.api.updateApps([{externalId:t,update:{name:{set:n},description:r?{set:r}:{setNull:!0}}}])}async submitSignatures(t,n,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${n}...`),await this.api.submitSignatures(t,n,r),console.log("\u2705 Signatures stored"))}listSignatures(t,n){return this.api.listSignatures(t,n)}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{alias:{setNull:!0}}}])}async activateVersion(t,n){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let o=r&&r.version!==n?r.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(t,n,r,o,s,a,p=!1){console.log(`
17
17
  \u{1F680} Deploying application via App Hosting API...
18
- `),await this.ensureApp(t,n,r),await this.uploadVersion(t,i,s,a),p&&await this.publishAndActivate(t,i),console.log(`
19
- \u2705 Deployment successful!`)}};o(ut,"AppHostingClient");var E=ut;import{CogniteClient as ds}from"@cognite/sdk";import{CogniteClient as Ki}from"@cognite/sdk";function Fi(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}o(Fi,"exponentialBackoffWithJitter");function Ri(e){return new Promise(t=>setTimeout(t,e))}o(Ri,"sleep");async function _n(e,t={}){let n=t.maxAttempts??5,r=t.shouldRetry??(()=>!0),i=t.delayInMsCalculator??Fi;if(n<1)throw new Error("`maxAttempts` must be 1 or greater");if(n>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await e()}catch(a){if(s>=n||!r(a))throw a;let p=i(s);t.onAttemptFail?.(a,s,p),await Ri(p),s++}}o(_n,"retryAsync");var Ti="https://auth.cognite.com/oauth2/token",Oi=o(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function Ln({idp:e,tokenUrl:t,init:n,missingTokenHint:r}){let i;try{i=await _n(()=>fetch(t,n),{maxAttempts:3})}catch(p){throw new u(`Failed to fetch access token from ${t}`,{cause:p})}if(!i.ok){let p=await i.text();throw new Q(`Failed to get token from ${e}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:t,responseBody:p})}let s=await i.text(),a;try{a=JSON.parse(s)}catch{throw new u(`Unexpected response from ${e} authentication (invalid JSON):
20
- ${s}`,{hint:r})}if(!Oi(a))throw new u(`No access token in ${e} authentication response:
21
- ${s}`,{hint:r});return a.access_token}o(Ln,"fetchOAuthToken");var Ui=o(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),n={};for(let[r,i]of Object.entries(t))if(typeof i=="string"){let s=r.toLowerCase().replace(/_/g,"-");n[s]=i}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),_i=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=Ui()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),Li=o((e,t)=>Ln({idp:"CDF",tokenUrl:Ti,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${e}:${t}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."}),"getTokenCdf"),Nn=o(({idp:e,tokenUrl:t,clientId:n,clientSecret:r,scopes:i,missingTokenHint:s})=>Ln({idp:e,tokenUrl:t,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:r,grant_type:"client_credentials",...i!==void 0?{scope:i.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),Ni=o((e,t)=>{if(t!==void 0)return t.join(" ");if(!e)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(e).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${e}`)}},"resolveEntraScope"),Mi=o((e,t,n,r,i)=>Nn({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,clientId:e,clientSecret:t,scopes:i!==void 0?i:[Ni(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),gt=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:n,deploySecretName:r,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:p,tokenUrl:c}=e,l=_i(r);if(i==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return Nn({idp:"OAuth",tokenUrl:c,clientId:n,clientSecret:l,scopes:p,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Mi(n,l,s,a,p)}return Li(n,l)},"getToken");async function ge(e,t,n=process.env,r){let i=await gt(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new Ki(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i,"oidcTokenProvider")});return await a.authenticate(),a}o(ge,"getSdk");import Qi from"os";import es from"path";import ts from"open";import{buildAuthorizationUrl as ns,calculatePKCECodeChallenge as rs,discovery as os,None as is,randomPKCECodeVerifier as ss,randomState as as}from"openid-client";import Mn from"mixpanel";var Hi="5c4d853e7c3b77b1eb4468d5329b278c",fe="cognite-cli",ji=2e3,Kn={env:process.env,init:Mn.init.bind(Mn)},Vi={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function ft(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(ft,"isTelemetryDisabled");function Bi(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(Bi,"isDebug");function Te(e={}){let t=e.env??Kn.env,n=e.init??Kn.init,r=e.packageName,i=e.cliVersion,s=Bi(t);if(ft(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
22
- `),Vi;let a,p=new Set;function c(){if(a)return a;try{return a=n(Hi,{geolocate:!1,keepAlive:!1}),a}catch{return}}return o(c,"getClient"),{track(l,d={}){let m=c();if(!m)return;let y={...d,applicationId:fe,...r&&{packageName:r},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform};s&&process.stderr.write(`[telemetry] track ${l} ${JSON.stringify(y)}
23
- `);let f=o(()=>{},"finish"),g=new Promise(S=>{f=S});p.add(g);try{m.track(l,y,f)}catch{f()}g.finally(()=>p.delete(g))},async flush(l=ji){if(p.size===0)return;let d,m=new Promise(y=>{d=setTimeout(y,l),d.unref?.()});try{await Promise.race([Promise.allSettled([...p]),m])}finally{d&&clearTimeout(d)}s&&process.stderr.write(`[telemetry] flush done (${p.size} still pending)
24
- `)}}}o(Te,"createTelemetry");import qi from"https";import{authorizationCodeGrant as Yi}from"openid-client";function Hn(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}o(Hn,"escapeHtml");function yt(e,t,n){let r=Hn(t),i=Hn(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
25
- <h1>${r}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
18
+ `),await this.ensureApp(t,n,r),await this.uploadVersion(t,o,s,a),p&&await this.publishAndActivate(t,o),console.log(`
19
+ \u2705 Deployment successful!`)}};i(Ct,"AppHostingClient");var P=Ct;import{CogniteClient as Os}from"@cognite/sdk";import{CogniteClient as ps}from"@cognite/sdk";function Qo(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}i(Qo,"exponentialBackoffWithJitter");function es(e){return new Promise(t=>setTimeout(t,e))}i(es,"sleep");async function Qn(e,t={}){let n=t.maxAttempts??5,r=t.shouldRetry??(()=>!0),o=t.delayInMsCalculator??Qo;if(n<1)throw new Error("`maxAttempts` must be 1 or greater");if(n>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await e()}catch(a){if(s>=n||!r(a))throw a;let p=o(s);t.onAttemptFail?.(a,s,p),await es(p),s++}}i(Qn,"retryAsync");var ts="https://auth.cognite.com/oauth2/token",ns=i(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function er({idp:e,tokenUrl:t,init:n,missingTokenHint:r}){let o;try{o=await Qn(()=>fetch(t,n),{maxAttempts:3})}catch(p){throw new u(`Failed to fetch access token from ${t}`,{cause:p})}if(!o.ok){let p=await o.text();throw new te(`Failed to get token from ${e}: ${o.status} ${o.statusText}`,{httpStatusCode:o.status,requestUrl:t,responseBody:p})}let s=await o.text(),a;try{a=JSON.parse(s)}catch{throw new u(`Unexpected response from ${e} authentication (invalid JSON)`,{hint:r})}if(!ns(a))throw new u(`No access token in ${e} authentication response`,{hint:r});return w.from(a.access_token)}i(er,"fetchOAuthToken");var rs=i(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),n={};for(let[r,o]of Object.entries(t))if(typeof o=="string"){let s=r.toLowerCase().replace(/_/g,"-");n[s]=o}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),is=i(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=rs()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return w.from(t)},"getSecretFromEnv"),os=i((e,t)=>{let n=t.expose();return er({idp:"CDF",tokenUrl:ts,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${e}:${n}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."})},"getTokenCdf"),tr=i(({idp:e,tokenUrl:t,clientId:n,clientSecret:r,scopes:o,missingTokenHint:s})=>er({idp:e,tokenUrl:t,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:r,grant_type:"client_credentials",...o!==void 0?{scope:o.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),ss=i((e,t)=>{if(t!==void 0)return t.join(" ");if(!e)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(e).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${e}`)}},"resolveEntraScope"),as=i((e,t,n,r,o)=>tr({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,clientId:e,clientSecret:t.expose(),scopes:o!==void 0?o:[ss(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),Et=i(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return w.from(t.COGNITE_TOKEN);let{deployClientId:n,deploySecretName:r,idpType:o="cdf",tenantId:s,baseUrl:a,scopes:p,tokenUrl:c}=e,l=is(r);if(o==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return tr({idp:"OAuth",tokenUrl:c,clientId:n,clientSecret:l.expose(),scopes:p,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(o==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return as(n,l,s,a,p)}return os(n,l)},"getToken");async function he(e,t,n=process.env,r){let o=await Et(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new ps(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:i(async()=>o.expose(),"oidcTokenProvider")});return await a.authenticate(),a}i(he,"getSdk");import Es from"os";import ks from"path";import bs from"open";import{buildAuthorizationUrl as Ps,calculatePKCECodeChallenge as xs,discovery as As,None as Ds,randomPKCECodeVerifier as Is,randomState as $s}from"openid-client";import nr from"mixpanel";var cs="5c4d853e7c3b77b1eb4468d5329b278c",Se="cognite-cli",ls=2e3,rr={env:process.env,init:nr.init.bind(nr)},ds={track:i(()=>{},"track"),flush:i(async()=>{},"flush")};function kt(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}i(kt,"isTelemetryDisabled");function ms(e=process.env){if(e.GITHUB_ACTIONS)return"github-actions";if(e.TF_BUILD)return"azure-devops";if(e.GITLAB_CI)return"gitlab-ci";if(e.CIRCLECI)return"circleci";if(e.TRAVIS)return"travis-ci";if(e.BUILDKITE)return"buildkite";if(e.DRONE)return"drone";if(e.SEMAPHORE)return"semaphore";if(e.TEAMCITY_VERSION)return"teamcity";if(e.APPVEYOR)return"appveyor";if(e.CODEBUILD_BUILD_ID)return"aws-codebuild";if(e.HEROKU_TEST_RUN_ID)return"heroku-ci";if(e.BITBUCKET_BUILD_NUMBER)return"bitbucket-pipelines";if(e.JENKINS_URL||e.JENKINS_HOME)return"jenkins";if(e.CI&&e.CI!=="false"&&e.CI!=="0")return"ci-generic"}i(ms,"detectCiEnvironment");function us(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}i(us,"isDebug");function Me(e={}){let t=e.env??rr.env,n=e.init??rr.init,r=e.packageName,o=e.cliVersion,s=us(t),a=ms(t);if(kt(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
20
+ `),ds;let p,c=new Set;function l(){if(p)return p;try{return p=n(cs,{geolocate:!1,keepAlive:!1}),p}catch{return}}return i(l,"getClient"),{track(d,m={}){let f=l();if(!f)return;let h={...m,applicationId:Se,...r&&{packageName:r},...o&&{cliVersion:o},nodeVersion:process.version,platform:process.platform,...a&&{ciEnvironment:a}};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(h)}
21
+ `);let g=i(()=>{},"finish"),y=new Promise(S=>{g=S});c.add(y);try{f.track(d,h,g)}catch{g()}y.finally(()=>c.delete(y))},async flush(d=ls){if(c.size===0)return;let m,f=new Promise(h=>{m=setTimeout(h,d),m.unref?.()});try{await Promise.race([Promise.allSettled([...c]),f])}finally{m&&clearTimeout(m)}s&&process.stderr.write(`[telemetry] flush done (${c.size} still pending)
22
+ `)}}}i(Me,"createTelemetry");import fs from"https";import{authorizationCodeGrant as ys}from"openid-client";function ir(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}i(ir,"escapeHtml");function bt(e,t,n){let r=ir(t),o=ir(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
23
+ <h1>${r}</h1><p>${o}</p><p>You can close this window.</p>${e==="success"?`<style>
26
24
  @keyframes checkmark {
27
25
  0% { transform: scale(0); }
28
26
  50% { transform: scale(1.2); }
@@ -30,32 +28,32 @@ ${s}`,{hint:r});return a.access_token}o(Ln,"fetchOAuthToken");var Ui=o(()=>{let
30
28
  }
31
29
  h1 { animation: checkmark 0.5s ease-out; }
32
30
  </style>`:""}
33
- </body></html>`}o(yt,"generateHtml");import Gi from"net";function jn(e,t){return new Promise(n=>{let r=new Gi.Socket,i=o(s=>{r.removeAllListeners(),r.destroy(),n(s)},"done");r.setTimeout(500),r.once("connect",()=>i(!1)),r.once("timeout",()=>i(!0)),r.once("error",()=>i(!0)),r.connect(e,t)})}o(jn,"isHostPortFree");function Oe(e,t={}){return T("windows",t)?`Find the process: netstat -ano | findstr :${e} then kill it: taskkill /PID <pid> /F`:`Free port ${e} (e.g. lsof -ti :${e} | xargs kill) and retry.`}o(Oe,"freePortHint");async function Vn(e){if(e<0)throw new Error(`Invalid port: ${e}`);return e===0?!0:(await Promise.all([jn(e,"127.0.0.1"),jn(e,"::1")])).every(Boolean)}o(Vn,"isPortFree");async function Ji(e,t,n,r,i,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await s.authorizationCodeGrant(n,a,{pkceCodeVerifier:r,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(yt("success","Login Successful!","You can close this window and return to the terminal.")),{shouldClose:!0,tokens:p}}catch(p){let c=p instanceof Error?p:new Error(String(p));return t.writeHead(400,{"Content-Type":"text/html"}),t.end(yt("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(Ji,"handleCallback");function zi(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}o(zi,"formatTimeoutMinutes");function Bn(e,t,n,r,i,s={createServer:qi.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:Yi}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,y)=>{try{let f=await Ji(m,y,n,r,i,s);f.shouldClose&&(d(),f.error?p(f.error):f.tokens?a(f.tokens):p(new Error("No tokens received")))}catch(f){d(),p(f instanceof Error?f:new Error(String(f)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${zi(e.loginTimeout)}`))},e.loginTimeout);function d(){s.clearTimeout(l),c.close()}o(d,"cleanup"),c.on("error",m=>{d(),m.code==="EADDRINUSE"||m.code==="EACCES"?p(new u(`Port ${e.port} is already in use \u2014 the login callback server cannot start`,{cause:m,hint:Oe(e.port)})):p(new u(`Login callback server failed: ${m.message}`,{cause:m}))}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}o(Bn,"startCallbackServer");import{mkdirSync as Wi}from"fs";import{loadLocalCertificates as Xi}from"@cognite/app-sdk/https";var Zi={loadLocalCertificates:Xi,mkdirSync:Wi,logger:console};async function Gn(e,t=Zi){t.mkdirSync(e,{recursive:!0});let{cert:n,key:r,source:i}=await t.loadLocalCertificates({certDir:e}).catch(s=>{throw new u(`Failed to load SSL certificates from ${e}`,{cause:s,hint:"Run `npx @cognite/cli apps setup-https` to create trusted local certificates."})});return i==="mkcert"?t.logger.log("\u{1F510} Using mkcert certificates for HTTPS"):(t.logger.log("\u{1F510} Using in-memory self-signed certificate for HTTPS \u2014 your browser will give you a warning."),t.logger.log(" Run `npx @cognite/cli@latest apps setup-https` to install trusted local https certificates.")),{cert:n,key:r}}o(Gn,"getOrCreateCertificates");var ps={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:es.join(Qi.homedir(),".cdf-login")},cs={open:ts,getOrCreateCertificates:Gn,startCallbackServer:Bn,isPortFree:Vn,discovery:os,buildAuthorizationUrl:ns,randomPKCECodeVerifier:ss,calculatePKCECodeChallenge:rs,randomState:as,logger:console,telemetry:Te()};async function Yn(e,t=ps,n){return n===void 0?qn(e,t,cs):qn(e,t,n)}o(Yn,"login");async function ls(e,t){try{return await e.discovery(new URL(t.authority),t.clientId,void 0,is())}catch(n){throw new u(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:n})}}o(ls,"fetchOpenIdConfig");async function qn(e,t,n){if(!await n.isPortFree(t.port))throw n.telemetry?.track("Flows.CLI.PortInUse",{port:t.port}),new u(`Port ${t.port} is already in use \u2014 the login callback server cannot start`,{hint:Oe(t.port)});n.logger.log(`\u{1F510} Starting CDF login flow...
34
- `),n.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let i=await ls(n,t),s=n.randomPKCECodeVerifier(),a=await n.calculatePKCECodeChallenge(s),p=n.randomState(),c={redirect_uri:t.redirectUri,scope:"openid profile email",code_challenge:a,code_challenge_method:"S256",state:p};e&&(c.organization_hint=e);let l=n.buildAuthorizationUrl(i,c).toString(),d=await n.getOrCreateCertificates(t.certDir);e&&n.logger.log(`\u{1F3E2} Organization: ${e}`),n.logger.log(`\u{1F680} Opening browser for authentication...
35
- `);try{await n.open(l)}catch(m){let y=m instanceof Error?m.message:String(m);n.logger.error("\u274C Failed to open browser automatically."),n.logger.error(` Reason: ${y}`),n.logger.error(`Please open this URL manually:
36
- `),n.logger.error(l),n.logger.error("")}return n.startCallbackServer(t,d,i,s,p)}o(qn,"loginImpl");async function A(e,t,n={}){let{login:r=Yn,getSdk:i=ge,createClient:s=o(a=>new ds(a),"createClient")}=n;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await r(a),c=s({appId:t.appId,project:e.project,baseUrl:e.baseUrl,getToken:o(async()=>p.access_token,"getToken")});return await c.authenticate(),c}return i(e,t.appId)}o(A,"getClientForDeployment");import Jn from"enquirer";var zn="Enter custom target...";function Wn(e,t){let n=t.map((r,i)=>` ${i}: ${r.org}/${r.project}`).join(`
31
+ </body></html>`}i(bt,"generateHtml");import gs from"net";function or(e,t){return new Promise(n=>{let r=new gs.Socket,o=i(s=>{r.removeAllListeners(),r.destroy(),n(s)},"done");r.setTimeout(500),r.once("connect",()=>o(!1)),r.once("timeout",()=>o(!0)),r.once("error",()=>o(!0)),r.connect(e,t)})}i(or,"isHostPortFree");function He(e,t={}){return A("windows",t)?`Find the process: netstat -ano | findstr :${e} then kill it: taskkill /PID <pid> /F`:`Free port ${e} (e.g. lsof -ti :${e} | xargs kill) and retry.`}i(He,"freePortHint");async function sr(e){if(e<0)throw new Error(`Invalid port: ${e}`);return e===0?!0:(await Promise.all([or(e,"127.0.0.1"),or(e,"::1")])).every(Boolean)}i(sr,"isPortFree");async function hs(e,t,n,r,o,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await s.authorizationCodeGrant(n,a,{pkceCodeVerifier:r,expectedState:o});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(bt("success","Login Successful!","You can close this window and return to the terminal.")),{shouldClose:!0,tokens:p}}catch(p){let c=p instanceof Error?p:new Error(String(p));return t.writeHead(400,{"Content-Type":"text/html"}),t.end(bt("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}i(hs,"handleCallback");function Ss(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}i(Ss,"formatTimeoutMinutes");function ar(e,t,n,r,o,s={createServer:fs.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:ys}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,f)=>{try{let h=await hs(m,f,n,r,o,s);h.shouldClose&&(d(),h.error?p(h.error):h.tokens?a(h.tokens):p(new Error("No tokens received")))}catch(h){d(),p(h instanceof Error?h:new Error(String(h)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${Ss(e.loginTimeout)}`))},e.loginTimeout);function d(){s.clearTimeout(l),c.close()}i(d,"cleanup"),c.on("error",m=>{d(),m.code==="EADDRINUSE"||m.code==="EACCES"?p(new u(`Port ${e.port} is already in use \u2014 the login callback server cannot start`,{cause:m,hint:He(e.port)})):p(new u(`Login callback server failed: ${m.message}`,{cause:m}))}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}i(ar,"startCallbackServer");import{mkdirSync as ws}from"fs";import{loadLocalCertificates as vs}from"@cognite/app-sdk/https";var Cs={loadLocalCertificates:vs,mkdirSync:ws,logger:console};async function pr(e,t=Cs){t.mkdirSync(e,{recursive:!0});let{cert:n,key:r,source:o}=await t.loadLocalCertificates({certDir:e}).catch(s=>{throw new u(`Failed to load SSL certificates from ${e}`,{cause:s,hint:"Run `npx @cognite/cli apps setup-https` to create trusted local certificates."})});return o==="mkcert"?t.logger.log("\u{1F510} Using mkcert certificates for HTTPS"):(t.logger.log("\u{1F510} Using in-memory self-signed certificate for HTTPS \u2014 your browser will give you a warning."),t.logger.log(" Run `npx @cognite/cli@latest apps setup-https` to install trusted local https certificates.")),{cert:n,key:r}}i(pr,"getOrCreateCertificates");var Rs={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:ks.join(Es.homedir(),".cdf-login")},Ts={open:bs,getOrCreateCertificates:pr,startCallbackServer:ar,isPortFree:sr,discovery:As,buildAuthorizationUrl:Ps,randomPKCECodeVerifier:Is,calculatePKCECodeChallenge:xs,randomState:$s,logger:console,telemetry:Me()};async function lr(e,t=Rs,n){return n===void 0?cr(e,t,Ts):cr(e,t,n)}i(lr,"login");async function Fs(e,t){try{return await e.discovery(new URL(t.authority),t.clientId,void 0,Ds())}catch(n){throw new u(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:n})}}i(Fs,"fetchOpenIdConfig");async function cr(e,t,n){if(!await n.isPortFree(t.port))throw n.telemetry?.track("Flows.CLI.PortInUse",{port:t.port}),new u(`Port ${t.port} is already in use \u2014 the login callback server cannot start`,{hint:He(t.port)});n.logger.log(`\u{1F510} Starting CDF login flow...
32
+ `),n.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let o=await Fs(n,t),s=n.randomPKCECodeVerifier(),a=await n.calculatePKCECodeChallenge(s),p=n.randomState(),c={redirect_uri:t.redirectUri,scope:"openid profile email",code_challenge:a,code_challenge_method:"S256",state:p};e&&(c.organization_hint=e);let l=n.buildAuthorizationUrl(o,c).toString(),d=await n.getOrCreateCertificates(t.certDir);e&&n.logger.log(`\u{1F3E2} Organization: ${e}`),n.logger.log(`\u{1F680} Opening browser for authentication...
33
+ `);try{await n.open(l)}catch(m){let f=m instanceof Error?m.message:String(m);n.logger.error("\u274C Failed to open browser automatically."),n.logger.error(` Reason: ${f}`),n.logger.error(`Please open this URL manually:
34
+ `),n.logger.error(l),n.logger.error("")}return n.startCallbackServer(t,d,o,s,p)}i(cr,"loginImpl");async function R(e,t,n={}){let{login:r=lr,getSdk:o=he,createClient:s=i(a=>new Os(a),"createClient")}=n;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await r(a),c=w.from(p.access_token),l=s({appId:t.appId,project:e.project,baseUrl:e.baseUrl,getToken:i(async()=>c.expose(),"getToken")});return await l.authenticate(),l}return o(e,t.appId)}i(R,"getClientForDeployment");import dr from"enquirer";var mr="Enter custom target...";function ur(e,t){let n=t.map((r,o)=>` ${o}: ${r.org}/${r.project}`).join(`
37
35
  `);throw new Error(`Deployment "${e}" not found. Available deployments:
38
- ${n}`)}o(Wn,"deploymentNotFoundError");function b(e,t){if(e.length===0)throw new Error("No deployments configured in app.json");if(t===void 0)return e[0];if(/^\d+$/.test(t)){let r=e[Number.parseInt(t)];if(r)return r;Wn(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;Wn(t,e)}o(b,"findDeployment");function D(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o(D,"getMissingCredentials");async function I(e,t){if(t.baseUrl&&t.project)return{org:t.org??"",project:t.project,baseUrl:t.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"};if(t.deployment!==void 0)return b(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),zn],{selected:r}=await Jn.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==zn){let s=e.deployments.find(a=>`${a.org}/${a.project}`===r);if(s)return s;throw new Error(`Deployment "${r}" could not be resolved from app.json.`)}let i=await Jn.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:o(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:i.org||"",project:i.project,baseUrl:i.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}o(I,"resolveDeployment");import{existsSync as ms}from"fs";import{resolve as us}from"path";import{config as gs}from"dotenv";function $(e,t={existsSync:ms,config:gs}){let n=us(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}o($,"loadEnvFile");function F(e){e.infra!=="appsApi"&&(console.error(`
36
+ ${n}`)}i(ur,"deploymentNotFoundError");function D(e,t){if(e.length===0)throw new Error("No deployments configured in app.json");if(t===void 0)return e[0];if(/^\d+$/.test(t)){let r=e[Number.parseInt(t)];if(r)return r;ur(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;ur(t,e)}i(D,"findDeployment");function T(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}i(T,"getMissingCredentials");async function F(e,t){if(t.baseUrl&&t.project)return{org:t.org??"",project:t.project,baseUrl:t.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"};if(t.deployment!==void 0)return D(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),mr],{selected:r}=await dr.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==mr){let s=e.deployments.find(a=>`${a.org}/${a.project}`===r);if(s)return s;throw new Error(`Deployment "${r}" could not be resolved from app.json.`)}let o=await dr.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:i(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:o.org||"",project:o.project,baseUrl:o.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}i(F,"resolveDeployment");import{existsSync as Us}from"fs";import{resolve as _s}from"path";import{config as Ks}from"dotenv";function O(e,t={existsSync:Us,config:Ks}){let n=_s(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}i(O,"loadEnvFile");function U(e){e.infra!=="appsApi"&&(console.error(`
39
37
  \u26A0\uFE0F Legacy infrastructure is no longer supported.
40
38
 
41
39
  Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
42
40
  the old CDF Application Registry. This deploy path has been removed.
43
41
 
44
42
  To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
45
- `),process.exit(1))}o(F,"assertAppHostingInfra");async function fs(e){let t=process.cwd();$(t);let n=v(t);F(n);let r=e.interactive?await I(n,e):b(n.deployments,e.deployment);if(!e.interactive){let d=D(r);if(d.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${d.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let i=await A(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new E(i),{externalId:a,versionTag:p}=n,c;try{c=await s.getVersion(a,p)}catch(d){throw d instanceof H?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):d}if(c.alias==="ACTIVE"){console.log(` ${a} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${a} @ ${p}: version is ${c.lifecycleState} (terminal).`);c.lifecycleState==="DRAFT"&&(await s.publishVersion(a,p),console.log(`\u2713 Published ${a} @ ${p} is now PUBLISHED`));let{supersededVersion:l}=await s.activateVersion(a,p);console.log(`\u2713 Activated ${a} @ ${p} is now ACTIVE`),l&&console.log(` Superseded ${l} \u2192 PUBLISHED`)}o(fs,"handleActivate");function Xn(e){return e.command("activate").description("Activate the current app version (publish if needed, then set ACTIVE alias)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
43
+ `),process.exit(1))}i(U,"assertAppHostingInfra");async function Ls(e){let t=process.cwd();O(t);let n=E(t);U(n);let r=e.interactive?await F(n,e):D(n.deployments,e.deployment);if(!e.interactive){let d=T(r);if(d.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${d.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let o=await R(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new P(o),{externalId:a,versionTag:p}=n,c;try{c=await s.getVersion(a,p)}catch(d){throw d instanceof j?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):d}if(c.alias==="ACTIVE"){console.log(` ${a} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${a} @ ${p}: version is ${c.lifecycleState} (terminal).`);c.lifecycleState==="DRAFT"&&(await s.publishVersion(a,p),console.log(`\u2713 Published ${a} @ ${p} is now PUBLISHED`));let{supersededVersion:l}=await s.activateVersion(a,p);console.log(`\u2713 Activated ${a} @ ${p} is now ACTIVE`),l&&console.log(` Superseded ${l} \u2192 PUBLISHED`)}i(Ls,"handleActivate");function gr(e){return e.command("activate").description("Activate the current app version (publish if needed, then set ACTIVE alias)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
46
44
  Examples:
47
45
  npx @cognite/cli apps activate . Activate using env-var auth
48
- npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>fs(n))}o(Xn,"registerActivateCommand");import{basename as dr,dirname as Ws,normalize as Xs,resolve as Me}from"path";import{fileURLToPath as Zs,pathToFileURL as Qs}from"url";import{Logger as ea,runner as ta}from"hygen";import{safeParse as ys}from"valibot";function ye(e,t){return n=>{let r=ys(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}o(ye,"toPromptValidator");var Zn={name:ye("App name",ot),displayName:ye("Display name",rt),baseUrl:ye("Base URL",it),org:ye("Org",st),project:ye("Project",at)};function hs(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}o(hs,"composeValidators");function Ue(e){return e.map(t=>{if(!(t.name in Zn))return t;let n=Zn[t.name];return{...t,validate:hs(t.validate,n)}})}o(Ue,"applySchemaValidators");import{basename as Qn}from"path";import er from"enquirer";function ht(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(ht,"kebabCase");var Ss={type:"confirm",name:"useSpecKit",message:["Enable spec-driven development?"," Adds the github/spec-kit slash commands (/speckit.specify, .clarify, .plan, .tasks, .implement)"," to your app for use in Claude Code or Cursor. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
49
- `),initial:!1};async function ws(e,t,n){return e!==void 0?e:t?!!(await n([Ss])).useSpecKit:!1}o(ws,"resolveSpecKit");function vs(e){return typeof e=="function"}o(vs,"isFunctionInitial");function tr(e){return(e??"").trim().replace(/\/+$/,"")||"api"}o(tr,"normalizeCluster");function nr({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:i={},specKit:s,prompt:a=er.prompt.bind(er)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(C=>C[1]!==void 0)),l=Object.keys(c).length>0,d=e?Qn(process.cwd()):t?Qn(t):null,m=l&&d!==null,y=!m&&d?p.map(C=>C.name==="name"?{...C,initial:d}:C):p,f=Ue(y),g=m&&d?{...c,name:d}:c,S=new Set(Object.keys(g)),w=f.filter(C=>!S.has(C.name)),P=w.findIndex(C=>C.name==="baseUrl"),h;if(m){let C=tr(g.cluster),V=o(k=>vs(k.initial)?k.initial():k.initial,"resolveInitial"),oe=o(k=>{if(k.name==="baseUrl")return`https://${C}.cognitedata.com`;let W=V(k);if(W===void 0)throw new Error(`Non-interactive mode: --${ht(k.name)} has no default. Pass it as a flag.`);return W},"deriveValue");h=Object.fromEntries(w.map(k=>[k.name,oe(k)]))}else if(P!==-1){let C=w.filter(_=>_.name!=="baseUrl"),V=C.length>0?await a(C):{},oe=typeof V.cluster=="string"?V.cluster:"",W=`https://${tr(oe||g.cluster)}.cognitedata.com`,X=w[P],Z=await a([{...X,initial:W}]);h={...V,...Z}}else h=w.length>0?await a(w):{};let M={...g,...h},U=typeof M.name=="string"?M.name:"";U&&n(U);let me=await ws(s,!m&&w.length>0,a);return r?.(me),{...M,name:U,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:me}},"prompt")})}o(nr,"createAppPrompter");async function rr(e,t,n){let r=[];Object.values(t).some(s=>s!==void 0)&&n!==null&&r.push({key:"name",value:n,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&r.push({key:s,value:a,label:`--${ht(s)}`});for(let{key:s,value:a,label:p}of r){let c=e.find(d=>d.name===s)?.validate;if(!c)continue;let l=await c(a);if(l!==!0)throw new Error(`Invalid ${p}: ${l}`)}}o(rr,"validatePresets");import{cpSync as St,existsSync as xs,mkdirSync as wt,writeFileSync as As}from"fs";import{dirname as Le,posix as Ds,resolve as N}from"path";import{fileURLToPath as ir}from"url";import{copyFileSync as Cs,symlinkSync as Es}from"fs";import{dirname as ks,join as bs}from"path";function Ps(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}o(Ps,"errno");function or(e){return e instanceof Error?e.message:String(e)}o(or,"messageOf");function _e({target:e,linkPath:t,label:n,symlink:r=Es,copyFile:i=Cs}){try{return r(e,t),!0}catch(s){let a=Ps(s);if(a==="EEXIST")return!0;let p=or(s);if(a==="EPERM"||a==="EACCES")try{let c=bs(ks(t),e);return i(c,t),console.log(`\u2139\uFE0F Wrote ${n} as a copy of ${e} (symlinks need Developer Mode or an elevated shell on Windows).`),!0}catch(c){return console.warn(`\u26A0\uFE0F Could not create ${n} symlink: ${p} (copy fallback also failed: ${or(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,p),!1}}o(_e,"linkOrCopyOrWarn");var Is=N(Le(ir(import.meta.url)),"..","..","_vendor","spec-kit"),$s=N(Le(ir(import.meta.url)),"..","..","_cognite-spec-extensions"),Fs={branch_numbering:"sequential"},Rs=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}],Ts=[{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"},{from:"templates",to:".specify/templates"}];function sr({appDir:e,vendorDir:t=Is,cogniteExtensionsDir:n=$s}){let r=N(e,".specify"),i=N(r,"memory"),s=`prepare spec-kit install for appDir=${e}`;try{for(let{from:p,to:c}of Rs){let l=N(e,c);s=`copy ${p} to ${c}`,wt(Le(l),{recursive:!0}),St(N(t,p),l,{recursive:!0})}for(let{from:p,to:c}of Ts){let l=N(e,c);s=`copy cognite extension ${p} to ${c}`,wt(Le(l),{recursive:!0}),St(N(n,p),l,{recursive:!0})}let a=N(r,"extensions.yml");xs(a)||(s="write .specify/extensions.yml",St(N(n,"extensions.yml"),a)),s=`write init-options.json under specifyDir=${r}`,As(N(r,"init-options.json"),`${JSON.stringify(Fs,null,2)}
50
- `),s=`link .specify/memory/constitution.md in specifyDir=${r}`,wt(i,{recursive:!0}),_e({target:Ds.join("..","..","AGENTS.md"),linkPath:N(i,"constitution.md"),label:".specify/memory/constitution.md"})}catch(a){let p=a instanceof Error?a.message:String(a);throw new Error(`installSpecKit failed while ${s} (appDir=${e}, vendorDir=${t}): ${p}`,{cause:a})}}o(sr,"installSpecKit");import{execFileSync as Ne}from"child_process";import{mkdtempSync as Os,readdirSync as Us,rmSync as _s}from"fs";import{createRequire as Ls}from"module";import{tmpdir as Ns}from"os";import{join as Ms,resolve as ar}from"path";import{InvalidArgumentError as Ks}from"commander";import Hs from"enquirer";var pr="cognitedata/builder-skills",vt=["claude-code","cursor","github-copilot","opencode","codex"],js=Ls(import.meta.url).resolve("skills/bin/cli.mjs");function Ct(e,t={}){try{Ne(process.execPath,[js,...e],{stdio:"inherit",cwd:process.cwd(),...t,env:{...process.env,...t.env,DISABLE_TELEMETRY:"1"}})}catch(n){throw new u(`Skills CLI failed (${e.join(" ")})`,{cause:n,hint:"Check your internet connection and that git is installed, then try again."})}}o(Ct,"execSkillsCli");function Vs(){return vt.map(e=>["add",pr,"-a",e,"--skill","*","-y"])}o(Vs,"pullAllArgsPerAgent");var Bs=1e4;async function cr(e,t={}){let n=t.exec??Ct,r=t.timeout??Bs,i=t.readdir??(p=>Us(p));for(let p of Vs())try{n(p,{cwd:e,timeout:r,stdio:["pipe","pipe","inherit"]})}catch(c){let l=c instanceof Error?c.message:String(c);console.warn("\u26A0\uFE0F Could not pull skills for args ["+p.join(" ")+"]:",l)}let s=new Set;for(let p of[ar(e,".claude","skills"),ar(e,".agents","skills")])try{i(p).forEach(c=>s.add(c))}catch{}let a=s.size;a>0?console.log(`Installed ${a} skills successfully.`):console.log("No skills were installed.")}o(cr,"pullAllSkillsInto");function Gs(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new Ks("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}o(Gs,"validateSource");function qs(e){let t=Os(Ms(Ns(),"skills-"));try{try{Ne("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch{throw new Error(`Failed to clone skills repository "${e}". Please check your internet connection and ensure git is installed.`)}let n;try{n=Ne("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{n=Ne("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return n.toString().trim().split(/\r?\n/).filter(r=>!!r&&!r.startsWith("."))}finally{_s(t,{recursive:!0,force:!0})}}o(qs,"listRemoteSkills");async function Ys(e,t={}){let n=o(p=>Hs.prompt(p),"defaultPrompt"),{listSkills:r=qs,prompt:i=n}=t,s=r(e),{selected:a}=await i({type:"multiselect",name:"selected",message:"Select skills to install (space to toggle, a to toggle all, enter to confirm)",choices:s});return a}o(Ys,"pickSkillsInteractive");function Js(e,t,n){let r=["add",e.source,"-a",t];return e.skill?r.push("--skill",e.skill):n&&n.length>0?r.push("--skill",...n,"-y"):r.push("--skill","*","-y"),e.global&&r.push("--global"),r}o(Js,"buildPullArgs");async function zs(e){console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await Ys(e.source)}catch(r){let i=r instanceof Error?r.message:String(r);console.error(`Failed to resolve skills interactively: ${i}`),process.exitCode=1;return}if(t.length===0){console.log("No skills selected.");return}}let n=!1;for(let r of vt)try{Ct(Js(e,r,t))}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`\u26A0\uFE0F Could not pull skills for ${r}: ${s}`),n=!0}n?(console.log(`
46
+ npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>Ls(n))}i(gr,"registerActivateCommand");import{basename as Dr,dirname as wa,normalize as va,resolve as Ye}from"path";import{fileURLToPath as Ca,pathToFileURL as Ea}from"url";import{Logger as ka,runner as ba}from"hygen";import{safeParse as Ns}from"valibot";function we(e,t){return n=>{let r=Ns(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}i(we,"toPromptValidator");var fr={name:we("App name",mt),displayName:we("Display name",dt),baseUrl:we("Base URL",ut),org:we("Org",gt),project:we("Project",ft)};function Ms(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}i(Ms,"composeValidators");function je(e){return e.map(t=>{if(!(t.name in fr))return t;let n=fr[t.name];return{...t,validate:Ms(t.validate,n)}})}i(je,"applySchemaValidators");import{basename as yr}from"path";import hr from"enquirer";function Pt(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}i(Pt,"kebabCase");var Hs={type:"confirm",name:"useSpecKit",message:["Enable spec-driven development?"," Adds the github/spec-kit slash commands (/speckit.specify, .clarify, .plan, .tasks, .implement)"," to your app for use in Claude Code or Cursor. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
47
+ `),initial:!1};async function js(e,t,n){return e!==void 0?e:t?!!(await n([Hs])).useSpecKit:!1}i(js,"resolveSpecKit");function Vs(e){return typeof e=="function"}i(Vs,"isFunctionInitial");function Sr(e){return(e??"").trim().replace(/\/+$/,"")||"api"}i(Sr,"normalizeCluster");function wr({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:o={},specKit:s,prompt:a=hr.prompt.bind(hr)}){return()=>({prompt:i(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(o).filter(k=>k[1]!==void 0)),l=Object.keys(c).length>0,d=e?yr(process.cwd()):t?yr(t):null,m=l&&d!==null,f=!m&&d?p.map(k=>k.name==="name"?{...k,initial:d}:k):p,h=je(f),g=m&&d?{...c,name:d}:c,y=new Set(Object.keys(g)),S=h.filter(k=>!y.has(k.name)),b=S.findIndex(k=>k.name==="baseUrl"),v;if(m){let k=Sr(g.cluster),X=i(x=>Vs(x.initial)?x.initial():x.initial,"resolveInitial"),Z=i(x=>{if(x.name==="baseUrl")return`https://${k}.cognitedata.com`;let Q=X(x);if(Q===void 0)throw new Error(`Non-interactive mode: --${Pt(x.name)} has no default. Pass it as a flag.`);return Q},"deriveValue");v=Object.fromEntries(S.map(x=>[x.name,Z(x)]))}else if(b!==-1){let k=S.filter(ee=>ee.name!=="baseUrl"),X=k.length>0?await a(k):{},Z=typeof X.cluster=="string"?X.cluster:"",Q=`https://${Sr(Z||g.cluster)}.cognitedata.com`,se=S[b],be=await a([{...se,initial:Q}]);v={...X,...be}}else v=S.length>0?await a(S):{};let C={...g,...v},z=typeof C.name=="string"?C.name:"";z&&n(z);let I=await js(s,!m&&S.length>0,a);return r?.(I),{...C,name:z,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:I}},"prompt")})}i(wr,"createAppPrompter");async function vr(e,t,n){let r=[];Object.values(t).some(s=>s!==void 0)&&n!==null&&r.push({key:"name",value:n,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&r.push({key:s,value:a,label:`--${Pt(s)}`});for(let{key:s,value:a,label:p}of r){let c=e.find(d=>d.name===s)?.validate;if(!c)continue;let l=await c(a);if(l!==!0)throw new Error(`Invalid ${p}: ${l}`)}}i(vr,"validatePresets");import{cpSync as xt,existsSync as Ws,mkdirSync as At,writeFileSync as zs}from"fs";import{dirname as Be,posix as Xs,resolve as N}from"path";import{fileURLToPath as Er}from"url";import{copyFileSync as Bs,symlinkSync as Gs}from"fs";import{dirname as Ys,join as qs}from"path";function Js(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}i(Js,"errno");function Cr(e){return e instanceof Error?e.message:String(e)}i(Cr,"messageOf");function Ve({target:e,linkPath:t,label:n,symlink:r=Gs,copyFile:o=Bs}){try{return r(e,t),!0}catch(s){let a=Js(s);if(a==="EEXIST")return!0;let p=Cr(s);if(a==="EPERM"||a==="EACCES")try{let c=qs(Ys(t),e);return o(c,t),console.log(`\u2139\uFE0F Wrote ${n} as a copy of ${e} (symlinks need Developer Mode or an elevated shell on Windows).`),!0}catch(c){return console.warn(`\u26A0\uFE0F Could not create ${n} symlink: ${p} (copy fallback also failed: ${Cr(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,p),!1}}i(Ve,"linkOrCopyOrWarn");var Zs=N(Be(Er(import.meta.url)),"..","..","_vendor","spec-kit"),Qs=N(Be(Er(import.meta.url)),"..","..","_cognite-spec-extensions"),ea={branch_numbering:"sequential"},ta=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}],na=[{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"},{from:"templates",to:".specify/templates"}];function kr({appDir:e,vendorDir:t=Zs,cogniteExtensionsDir:n=Qs}){let r=N(e,".specify"),o=N(r,"memory"),s=`prepare spec-kit install for appDir=${e}`;try{for(let{from:p,to:c}of ta){let l=N(e,c);s=`copy ${p} to ${c}`,At(Be(l),{recursive:!0}),xt(N(t,p),l,{recursive:!0})}for(let{from:p,to:c}of na){let l=N(e,c);s=`copy cognite extension ${p} to ${c}`,At(Be(l),{recursive:!0}),xt(N(n,p),l,{recursive:!0})}let a=N(r,"extensions.yml");Ws(a)||(s="write .specify/extensions.yml",xt(N(n,"extensions.yml"),a)),s=`write init-options.json under specifyDir=${r}`,zs(N(r,"init-options.json"),`${JSON.stringify(ea,null,2)}
48
+ `),s=`link .specify/memory/constitution.md in specifyDir=${r}`,At(o,{recursive:!0}),Ve({target:Xs.join("..","..","AGENTS.md"),linkPath:N(o,"constitution.md"),label:".specify/memory/constitution.md"})}catch(a){let p=a instanceof Error?a.message:String(a);throw new Error(`installSpecKit failed while ${s} (appDir=${e}, vendorDir=${t}): ${p}`,{cause:a})}}i(kr,"installSpecKit");import{execFileSync as Ge}from"child_process";import{mkdtempSync as ra,readdirSync as ia,rmSync as oa}from"fs";import{createRequire as sa}from"module";import{tmpdir as aa}from"os";import{join as pa,resolve as br}from"path";import{InvalidArgumentError as ca}from"commander";import la from"enquirer";var Pr="cognitedata/builder-skills",Dt=["claude-code","cursor","github-copilot","opencode","codex"],da=sa(import.meta.url).resolve("skills/bin/cli.mjs");function It(e,t={}){try{Ge(process.execPath,[da,...e],{stdio:"inherit",cwd:process.cwd(),...t,env:{...process.env,...t.env,DISABLE_TELEMETRY:"1"}})}catch(n){throw new u(`Skills CLI failed (${e.join(" ")})`,{cause:n,hint:"Check your internet connection and that git is installed, then try again."})}}i(It,"execSkillsCli");function ma(){return Dt.map(e=>["add",Pr,"-a",e,"--skill","*","-y"])}i(ma,"pullAllArgsPerAgent");var ua=1e4;async function xr(e,t={}){let n=t.exec??It,r=t.timeout??ua,o=t.readdir??(p=>ia(p));for(let p of ma())try{n(p,{cwd:e,timeout:r,stdio:["pipe","pipe","inherit"]})}catch(c){let l=c instanceof Error?c.message:String(c);console.warn("\u26A0\uFE0F Could not pull skills for args ["+p.join(" ")+"]:",l)}let s=new Set;for(let p of[br(e,".claude","skills"),br(e,".agents","skills")])try{o(p).forEach(c=>s.add(c))}catch{}let a=s.size;a>0?console.log(`Installed ${a} skills successfully.`):console.log("No skills were installed.")}i(xr,"pullAllSkillsInto");function ga(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new ca("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}i(ga,"validateSource");function fa(e){let t=ra(pa(aa(),"skills-"));try{try{Ge("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch{throw new Error(`Failed to clone skills repository "${e}". Please check your internet connection and ensure git is installed.`)}let n;try{n=Ge("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{n=Ge("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return n.toString().trim().split(/\r?\n/).filter(r=>!!r&&!r.startsWith("."))}finally{oa(t,{recursive:!0,force:!0})}}i(fa,"listRemoteSkills");async function ya(e,t={}){let n=i(p=>la.prompt(p),"defaultPrompt"),{listSkills:r=fa,prompt:o=n}=t,s=r(e),{selected:a}=await o({type:"multiselect",name:"selected",message:"Select skills to install (space to toggle, a to toggle all, enter to confirm)",choices:s});return a}i(ya,"pickSkillsInteractive");function ha(e,t,n){let r=["add",e.source,"-a",t];return e.skill?r.push("--skill",e.skill):n&&n.length>0?r.push("--skill",...n,"-y"):r.push("--skill","*","-y"),e.global&&r.push("--global"),r}i(ha,"buildPullArgs");async function Sa(e){console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await ya(e.source)}catch(r){let o=r instanceof Error?r.message:String(r);console.error(`Failed to resolve skills interactively: ${o}`),process.exitCode=1;return}if(t.length===0){console.log("No skills selected.");return}}let n=!1;for(let r of Dt)try{It(ha(e,r,t))}catch(o){let s=o instanceof Error?o.message:String(o);console.warn(`\u26A0\uFE0F Could not pull skills for ${r}: ${s}`),n=!0}n?(console.log(`
51
49
  Skills pulled with some errors (see warnings above)`),process.exitCode=1):console.log(`
52
- Skills pulled successfully`)}o(zs,"handlePull");function lr(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
53
- Supports: ${vt.join(", ")}`).addHelpText("after",`
50
+ Skills pulled successfully`)}i(Sa,"handlePull");function Ar(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
51
+ Supports: ${Dt.join(", ")}`).addHelpText("after",`
54
52
  Examples:
55
53
  npx @cognite/cli apps skills pull Pull all skills
56
54
  npx @cognite/cli apps skills pull --skill create-client-tool Pull a specific skill
57
- npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository",Gs,pr).option("--skill <name>","Pull a specific skill by name").option("-i, --interactive","Interactively select which skills to install",!1).option("--global","Install skills globally",!1).action(zs),t.command("list").description("List installed skills").action(()=>{Ct(["list"])}),t}o(lr,"registerSkillsCommand");var mr=Me(Ws(Zs(import.meta.url)),"..","..","_templates");async function na(){let e=Me(mr,"app","new","prompt.js");return(await import(Qs(e).href)).default}o(na,"loadPromptDefs");function ra(e,t){return!e||t?null:Xs(e)}o(ra,"resolveDirName");function oa(e,t,n){if(e)return{cwd:process.cwd(),display:"."};let r=t??n;if(!r)throw new Error("App creation completed without a target directory or name.");return{cwd:Me(process.cwd(),r),display:r}}o(oa,"resolveAppLocation");function ia(e,t,n){let r=` npm install
58
- npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=n?`
55
+ npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository",ga,Pr).option("--skill <name>","Pull a specific skill by name").option("-i, --interactive","Interactively select which skills to install",!1).option("--global","Install skills globally",!1).action(Sa),t.command("list").description("List installed skills").action(()=>{It(["list"])}),t}i(Ar,"registerSkillsCommand");var Ir=Ye(wa(Ca(import.meta.url)),"..","..","_templates");async function Pa(){let e=Ye(Ir,"app","new","prompt.js");return(await import(Ea(e).href)).default}i(Pa,"loadPromptDefs");function xa(e,t){return!e||t?null:va(e)}i(xa,"resolveDirName");function Aa(e,t,n){if(e)return{cwd:process.cwd(),display:"."};let r=t??n;if(!r)throw new Error("App creation completed without a target directory or name.");return{cwd:Ye(process.cwd(),r),display:r}}i(Aa,"resolveAppLocation");function Da(e,t,n){let r=` npm install
56
+ npm run dev`,o="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=n?`
59
57
  To start spec-driven development:
60
58
  Run /speckit.specify in Claude Code or Cursor and describe your app.
61
59
  `:"",p=` # Or fully non-interactive (deploys first target from app.json):
@@ -65,7 +63,7 @@ To start spec-driven development:
65
63
  Next steps:
66
64
  ${r}
67
65
  ${a}
68
- ${i}
66
+ ${o}
69
67
  ${s}
70
68
  ${p}
71
69
  `);return}console.log(`
@@ -77,11 +75,11 @@ Or:
77
75
  cd "${t}"
78
76
  ${r}
79
77
  ${a}
80
- ${i}
78
+ ${o}
81
79
  cd "${t}"
82
80
  ${s}
83
81
  ${p}
84
- `)}o(ia,"printSuccessMessage");async function sa(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await cr(e)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}o(sa,"pullSkillsInto");function aa(e,t={}){let{isGitInstalled:n=Ce,isInsideGitRepo:r=Ee,gitInitAndCommit:i=zt}=t;if(!n()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!r(e)){console.log("Initialising git repository...");try{i(e)}catch(s){let p=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",p)}}}o(aa,"maybeInitGit");async function pa(e,t){let n=e==="."||e==="./",r=ra(e,n),i=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await na(),c=Ue(p),l=n?dr(process.cwd()):r?dr(r):null;await rr(c,a,l);let d=nr({isCurrentDir:n,dirName:r,onAppName:o(y=>{i=y},"onAppName"),onUseSpecKit:o(y=>{s=y},"onUseSpecKit"),presets:a,specKit:t.specKit});await ta(["app","new"],{templates:mr,cwd:process.cwd(),logger:new ea(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=oa(n,r,i);_e({target:"AGENTS.md",linkPath:Me(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&sr({appDir:m.cwd}),await sa(m.cwd),aa(m.cwd),ia(n,m.display,s)}o(pa,"handleCreate");function ur(e){return e.command("create").description("Create a new application.").argument("[directory]","Target directory (. for current, or subdirectory name)").option("--display-name <name>","App display name (skips the prompt)").option("--description <description>","App description (skips the prompt)").option("--org <org>","Deployment org (skips the prompt)").option("--project <project>","Deployment project (skips the prompt)").option("--cluster <cluster>","CDF cluster, e.g. greenfield (skips the prompt)").option("--base-url <url>","CDF base URL, e.g. https://greenfield.cognitedata.com (skips the prompt; defaults to cluster-derived URL when omitted)").option("--spec-kit","Install spec-kit slash commands (skips the prompt)").option("--no-spec-kit","Skip spec-kit installation (skips the prompt)").addHelpText("after",`
82
+ `)}i(Da,"printSuccessMessage");async function Ia(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await xr(e)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}i(Ia,"pullSkillsInto");function $a(e,t={}){let{isGitInstalled:n=Pe,isInsideGitRepo:r=xe,gitInitAndCommit:o=cn}=t;if(!n()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!r(e)){console.log("Initialising git repository...");try{o(e)}catch(s){let p=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",p)}}}i($a,"maybeInitGit");async function Ra(e,t){let n=e==="."||e==="./",r=xa(e,n),o=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await Pa(),c=je(p),l=n?Dr(process.cwd()):r?Dr(r):null;await vr(c,a,l);let d=wr({isCurrentDir:n,dirName:r,onAppName:i(f=>{o=f},"onAppName"),onUseSpecKit:i(f=>{s=f},"onUseSpecKit"),presets:a,specKit:t.specKit});await ba(["app","new"],{templates:Ir,cwd:process.cwd(),logger:new ka(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=Aa(n,r,o);Ve({target:"AGENTS.md",linkPath:Ye(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&kr({appDir:m.cwd}),await Ia(m.cwd),$a(m.cwd),Da(n,m.display,s)}i(Ra,"handleCreate");function $r(e){return e.command("create").description("Create a new application.").argument("[directory]","Target directory (. for current, or subdirectory name)").option("--display-name <name>","App display name (skips the prompt)").option("--description <description>","App description (skips the prompt)").option("--org <org>","Deployment org (skips the prompt)").option("--project <project>","Deployment project (skips the prompt)").option("--cluster <cluster>","CDF cluster, e.g. greenfield (skips the prompt)").option("--base-url <url>","CDF base URL, e.g. https://greenfield.cognitedata.com (skips the prompt; defaults to cluster-derived URL when omitted)").option("--spec-kit","Install spec-kit slash commands (skips the prompt)").option("--no-spec-kit","Skip spec-kit installation (skips the prompt)").addHelpText("after",`
85
83
  Non-interactive use (CI, scripts, AI agents):
86
84
  Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
87
85
  to skip every prompt. Missing flags fall back to the interactive prompt.
@@ -94,22 +92,22 @@ Examples:
94
92
  --display-name "My App" --description "My app" \\
95
93
  --org cog-atlas --project atlas-greenfield --cluster greenfield \\
96
94
  --base-url https://greenfield.cognitedata.com
97
- Fully non-interactive`).action(pa)}o(ur,"registerCreateCommand");import ca from"path";async function la(e,t,n){let r=await A(e,{interactive:t.interactive,appId:n,orgHint:t.org});return new E(r)}o(la,"defaultGetApiClient");async function da(e,t,n={}){let{loadEnvFile:r=$,loadAppConfig:i=v,getApiClient:s=la}=n,a=ca.resolve(process.cwd(),e);r(a);let p=i(a);F(p);let c=t.interactive?await I(p,t):b(p.deployments,t.deployment);if(!t.interactive){let y=D(c);if(y.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${y.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let{externalId:l}=p,d=await s(c,t,l),m=await d.getActiveVersion(l);if(!m){console.log(` ${l} has no active version \u2014 nothing to deactivate.`);return}await d.deactivateVersion(l,m.version),console.log(`\u2713 Deactivated ${l} @ ${m.version} \u2014 active alias removed`)}o(da,"handleDeactivate");function gr(e){return e.command("deactivate").description("Deactivate the app by removing its active version from service").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
95
+ Fully non-interactive`).action(Ra)}i($r,"registerCreateCommand");import Ta from"path";async function Fa(e,t,n){let r=await R(e,{interactive:t.interactive,appId:n,orgHint:t.org});return new P(r)}i(Fa,"defaultGetApiClient");async function Oa(e,t,n={}){let{loadEnvFile:r=O,loadAppConfig:o=E,getApiClient:s=Fa}=n,a=Ta.resolve(process.cwd(),e);r(a);let p=o(a);U(p);let c=t.interactive?await F(p,t):D(p.deployments,t.deployment);if(!t.interactive){let f=T(c);if(f.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${f.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let{externalId:l}=p,d=await s(c,t,l),m=await d.getActiveVersion(l);if(!m){console.log(` ${l} has no active version \u2014 nothing to deactivate.`);return}await d.deactivateVersion(l,m.version),console.log(`\u2713 Deactivated ${l} @ ${m.version} \u2014 active alias removed`)}i(Oa,"handleDeactivate");function Rr(e){return e.command("deactivate").description("Deactivate the app by removing its active version from service").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
98
96
  Examples:
99
97
  npx @cognite/cli apps deactivate . Deactivate using env-var auth
100
- npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>da(t,n))}o(gr,"registerDeactivateCommand");import{mkdir as ha,readFile as Sa}from"fs/promises";import{basename as wa,dirname as va}from"path";import{execFileSync as Ke}from"child_process";import Y from"fs";import R from"path";import{parseAndValidateManifestConfig as ma}from"@cognite/app-sdk/vite";import{BlobReader as ua,Uint8ArrayWriter as ga,ZipWriter as fa}from"@zip.js/zip.js";var Et="package.json",kt="package-lock.json",fr="manifest.json",bt=".cognite",ya=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],Pt=class Pt{constructor(t="dist"){this.distPath=R.isAbsolute(t)?t:R.join(process.cwd(),t),this.appRoot=R.dirname(this.distPath)}validateBuildDirectory(){if(!Y.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=R.join(this.appRoot,Et);if(!Y.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=R.join(this.appRoot,kt);if(!Y.existsSync(n))throw new Error(`"${n}" not found. It is required for deployment.`)}async createZip(t="app.zip",n=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new fa(new ga,{level:9}),i=o(async(c,l)=>{await r.add(l,new ua(await Y.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=o(async c=>{let l=await Y.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=R.join(c,d.name);d.isDirectory()?await s(m):await i(m,R.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=R.join(this.appRoot,Et);await i(c,R.posix.join(bt,Et));let l=R.join(this.appRoot,fr);if(Y.existsSync(l)){let m=Y.readFileSync(l,"utf-8");ma(m,l),await i(l,R.posix.join(bt,fr))}let d=R.join(this.appRoot,kt);await i(d,R.posix.join(bt,kt)),a=await r.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}try{await Y.promises.writeFile(t,a)}catch(c){throw new u(`Failed to write bundle to ${t}`,{cause:c})}let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let n;try{n=Ke("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=Ke("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=r?r.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(n,s);try{Ke("git",["-C",n,"archive","--format=zip",`--output=${t}`,s])}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${l}`)}let p=(Y.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${R.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,n){let r=Ke("git",["-C",t,"ls-tree","-r","--name-only",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
101
- `).filter(Boolean),i=o(a=>a.split("/").some(p=>ya.some(c=>c.test(p))),"isSensitive"),s=r.filter(i);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
98
+ npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>Oa(t,n))}i(Rr,"registerDeactivateCommand");import{mkdir as Ma,readFile as Ha}from"fs/promises";import{basename as ja,dirname as Va}from"path";import{execFileSync as qe}from"child_process";import q from"fs";import _ from"path";import{parseAndValidateManifestConfig as Ua}from"@cognite/app-sdk/vite";import{BlobReader as _a,Uint8ArrayWriter as Ka,ZipWriter as La}from"@zip.js/zip.js";var $t="package.json",Rt="package-lock.json",Tr="manifest.json",Tt=".cognite",Na=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],Ft=class Ft{constructor(t="dist"){this.distPath=_.isAbsolute(t)?t:_.join(process.cwd(),t),this.appRoot=_.dirname(this.distPath)}validateBuildDirectory(){if(!q.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=_.join(this.appRoot,$t);if(!q.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=_.join(this.appRoot,Rt);if(!q.existsSync(n))throw new Error(`"${n}" not found. It is required for deployment.`)}async createZip(t="app.zip",n=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new La(new Ka,{level:9}),o=i(async(c,l)=>{await r.add(l,new _a(await q.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=i(async c=>{let l=await q.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=_.join(c,d.name);d.isDirectory()?await s(m):await o(m,_.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=_.join(this.appRoot,$t);await o(c,_.posix.join(Tt,$t));let l=_.join(this.appRoot,Tr);if(q.existsSync(l)){let m=q.readFileSync(l,"utf-8");Ua(m,l),await o(l,_.posix.join(Tt,Tr))}let d=_.join(this.appRoot,Rt);await o(d,_.posix.join(Tt,Rt)),a=await r.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}try{await q.promises.writeFile(t,a)}catch(c){throw new u(`Failed to write bundle to ${t}`,{cause:c})}let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let n;try{n=qe("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=qe("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=r?r.replace(/\/$/,""):".",s=o==="."?"HEAD":`HEAD:${o}`;this.validateNoSensitiveFiles(n,s);try{qe("git",["-C",n,"archive","--format=zip",`--output=${t}`,s])}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${l}`)}let p=(q.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${_.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,n){let r=qe("git",["-C",t,"ls-tree","-r","--name-only",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
99
+ `).filter(Boolean),o=i(a=>a.split("/").some(p=>Na.some(c=>c.test(p))),"isSensitive"),s=r.filter(o);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
102
100
  `+s.map(a=>` ${a}`).join(`
103
101
  `)+`
104
- Hint: git rm --cached <file>`)}};o(Pt,"ApplicationPackager");var re=Pt;async function He(e,t,n,r){let{externalId:i,name:s,description:a,versionTag:p}=t,c=B(n,i,p);await ha(va(c),{recursive:!0}),await new re(`${n}/dist`).createZip(c,!0);let l;try{l=await Sa(c)}catch(d){throw new u(`Failed to read bundle file: ${c}`,{cause:d})}await new E(e).deploy(i,s,a,p,l,wa(c),r)}o(He,"packageAndUpload");var xt=o(async(e,t,n)=>{let r=await ge(e,n);await He(r,t,n,e.published)},"deploy");import{existsSync as Ca,readFileSync as Ea}from"fs";var yr=[".dev.sig",".cert.sig"];function he(e,t={}){let n=t.existsSync??Ca,r=t.readFileSync??((s,a)=>Ea(s,a)),i=[];for(let s of yr){let a=`${e}${s}`;if(!n(a))continue;let p=r(a,"utf8").trim();p.length>0&&i.push(p)}return i}o(he,"discoverSignatures");import{execSync as ka}from"child_process";function At(e,t=!0,n={execSync:ka}){console.log("\u{1F4E6} Building app with npm...");try{n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(r){throw new u(`npm run build failed in ${e}`,{cause:r,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}o(At,"buildApp");function hr(e,t){let{org:n,project:r,baseUrl:i}=e,s;try{s=new URL(i).hostname}catch{return null}let{externalId:a,versionTag:p}=t,c=new URLSearchParams({cluster:s,customAppVersion:p,workspace:"industrial-tools"});return`https://${n}.fusion.cognite.com/${r}/flows-apps/app/${encodeURIComponent(a)}?${c}`}o(hr,"generateFusionUrl");function Sr(e,t,n){let r=n?"\u{1F680} Deploy (Interactive)":"\u{1F680} Deploy",i=n?`${t.project} @ ${t.baseUrl}`:`${t.org}/${t.project}`;console.log(["",r,"=".repeat(r.length),`App: ${e.name} (${e.externalId})`,`Version: ${e.versionTag}`,`Target: ${i}`,""].join(`
105
- `))}o(Sr,"printDeployInfo");function wr(e,t){console.log(`
102
+ Hint: git rm --cached <file>`)}};i(Ft,"ApplicationPackager");var oe=Ft;async function Je(e,t,n,r){let{externalId:o,name:s,description:a,versionTag:p}=t,c=B(n,o,p);await Ma(Va(c),{recursive:!0}),await new oe(`${n}/dist`).createZip(c,!0);let l;try{l=await Ha(c)}catch(d){throw new u(`Failed to read bundle file: ${c}`,{cause:d})}await new P(e).deploy(o,s,a,p,l,ja(c),r)}i(Je,"packageAndUpload");var Ot=i(async(e,t,n)=>{let r=await he(e,n);await Je(r,t,n,e.published)},"deploy");import{existsSync as Ba,readFileSync as Ga}from"fs";var Fr=[".dev.sig",".cert.sig"];function ve(e,t={}){let n=t.existsSync??Ba,r=t.readFileSync??((s,a)=>Ga(s,a)),o=[];for(let s of Fr){let a=`${e}${s}`;if(!n(a))continue;let p=r(a,"utf8").trim();p.length>0&&o.push(p)}return o}i(ve,"discoverSignatures");import{execSync as Ya}from"child_process";function Ut(e,t=!0,n={execSync:Ya}){console.log("\u{1F4E6} Building app with npm...");try{n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(r){throw new u(`npm run build failed in ${e}`,{cause:r,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}i(Ut,"buildApp");function Or(e,t){let{org:n,project:r,baseUrl:o}=e,s;try{s=new URL(o).hostname}catch{return null}let{externalId:a,versionTag:p}=t,c=new URLSearchParams({cluster:s,customAppVersion:p,workspace:"industrial-tools"});return`https://${n}.fusion.cognite.com/${r}/flows-apps/app/${encodeURIComponent(a)}?${c}`}i(Or,"generateFusionUrl");function Ur(e,t,n){let r=n?"\u{1F680} Deploy (Interactive)":"\u{1F680} Deploy",o=n?`${t.project} @ ${t.baseUrl}`:`${t.org}/${t.project}`;console.log(["",r,"=".repeat(r.length),`App: ${e.name} (${e.externalId})`,`Version: ${e.versionTag}`,`Target: ${o}`,""].join(`
103
+ `))}i(Ur,"printDeployInfo");function _r(e,t){console.log(`
106
104
  \u2705 Successfully deployed ${e.name} version ${e.versionTag} to ${t.org?`${t.org}/`:""}${t.project}`),console.log("\u{1F512} App is deployed in draft mode");let n=e.deployments.length>1?` -d ${t.project}`:"";console.log(`
107
105
  To sign: npx @cognite/cli apps sign --interactive${n}`),console.log(`To publish: npx @cognite/cli apps publish .${n}`),console.log(`To activate: npx @cognite/cli apps activate .${n}`),console.log(`
108
- To submit for certification: npx @cognite/cli apps submit`);let r=hr(t,e);r&&console.log(`
106
+ To submit for certification: npx @cognite/cli apps submit`);let r=Or(t,e);r&&console.log(`
109
107
  \u{1F517} Open your app:
110
- ${r}`)}o(wr,"printDeployResult");async function ba(e,t,n,r,i){let s=D(t);if(s.length>0)throw new Error(`Deployment ${t.org}/${t.project} is missing ${s.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);Sr(e,t,!1),r.skipBuild||At(n),console.log(`
111
- \u{1F4E4} Deploying to ${t.org}/${t.project}...`),await i({...t,published:!1},{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},n),wr(e,t)}o(ba,"handleDeployNonInteractive");async function Pa(e,t,n,r){Sr(e,t,!0),r.skipBuild||At(n);let i=await A(t,{interactive:!0,appId:e.externalId,orgHint:r.org});console.log(`
112
- \u{1F4E4} Deploying to ${t.project}...`),await He(i,{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},n,!1),wr(e,t)}o(Pa,"handleDeployInteractive");async function xa(e,t=process.cwd(),n={}){let{loadEnvFile:r=$,loadAppConfig:i=v,deploy:s=xt}=n;r(t);let a=i(t);if(F(a),e.interactive){let c=await I(a,e);await Pa(a,c,t,e);return}let p=b(a.deployments,e.deployment);await ba(a,p,t,e,s)}o(xa,"handleDeploy");function vr(e){return e.command("deploy").description("Deploy your app to Cognite Data Fusion. Use --interactive for browser-based login (no env-var secrets required).").option("-d, --deployment <target>","Deployment target (index or project name)").option("--skip-build","Skip the build step",!1).option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
108
+ ${r}`)}i(_r,"printDeployResult");async function qa(e,t,n,r,o){let s=T(t);if(s.length>0)throw new Error(`Deployment ${t.org}/${t.project} is missing ${s.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);Ur(e,t,!1),r.skipBuild||Ut(n),console.log(`
109
+ \u{1F4E4} Deploying to ${t.org}/${t.project}...`),await o({...t,published:!1},{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},n),_r(e,t)}i(qa,"handleDeployNonInteractive");async function Ja(e,t,n,r){Ur(e,t,!0),r.skipBuild||Ut(n);let o=await R(t,{interactive:!0,appId:e.externalId,orgHint:r.org});console.log(`
110
+ \u{1F4E4} Deploying to ${t.project}...`),await Je(o,{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},n,!1),_r(e,t)}i(Ja,"handleDeployInteractive");async function Wa(e,t=process.cwd(),n={}){let{loadEnvFile:r=O,loadAppConfig:o=E,deploy:s=Ot}=n;r(t);let a=o(t);if(U(a),e.interactive){let c=await F(a,e);await Ja(a,c,t,e);return}let p=D(a.deployments,e.deployment);await qa(a,p,t,e,s)}i(Wa,"handleDeploy");function Kr(e){return e.command("deploy").description("Deploy your app to Cognite Data Fusion. Use --interactive for browser-based login (no env-var secrets required).").option("-d, --deployment <target>","Deployment target (index or project name)").option("--skip-build","Skip the build step",!1).option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
113
111
  Environment (non-interactive):
114
112
  deployClientId and deploySecretName are configured per deployment in app.json.
115
113
  deploySecretName is the name of the environment variable that holds the client
@@ -123,76 +121,75 @@ Examples:
123
121
  npx @cognite/cli apps deploy -d my-project Deploy to project by name
124
122
  npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
125
123
  npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
126
- npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>xa(t))}o(vr,"registerDeployCommand");function Aa(e,t){console.log(""),console.log(`Updating metadata for '${e}':`);for(let{field:n,remote:r,local:i}of t){let s=`${n}:`.padEnd(13);console.log(` ${s}"${r}" \u2192 "${i||"(none)"}"`)}}o(Aa,"printMetadataDiff");async function Da(e,t=process.cwd(),n={}){let{loadEnvFile:r=$,loadAppConfig:i=v,getClientForDeployment:s=A,createMetadataClient:a=o(S=>new E(S),"createMetadataClient"),getMissingCredentials:p=D}=n;r(t);let c=i(t);F(c);let l=e.interactive?await I(c,e):b(c.deployments,e.deployment);if(!e.interactive){let S=p(l);if(S.length>0)throw new Error(`Deployment ${l.org}/${l.project} is missing ${S.join(" and ")} in app.json. Use \`cognite apps metadata update --interactive\` for browser-based authentication instead.`)}let d=await s(l,{interactive:e.interactive,appId:c.externalId,orgHint:e.org}),m=a(d),y;try{y=await m.getApp(c.externalId)}catch(S){throw S instanceof ce?new Error(`App '${c.externalId}' is not deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):S}let f={name:c.name,description:c.description||""},g=mt(y,f);if(g.length===0){console.log(""),console.log(`Metadata for '${c.externalId}' already matches the deployed app \u2014 nothing to update.`),console.log("Edit name/description in app.json to change them.");return}Aa(c.externalId,g),await m.updateAppMetadata(c.externalId,c.name,c.description),console.log(""),console.log(`\u2705 Metadata for '${c.externalId}' updated`)}o(Da,"handleUpdateMetadata");function Cr(e){let t=e.command("metadata").summary("Manage the deployed app's metadata").description("Manage the deployed app's metadata (name and description).");return t.command("update").description("Update the deployed app's name and description from app.json").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
124
+ npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>Wa(t))}i(Kr,"registerDeployCommand");function za(e,t){console.log(""),console.log(`Updating metadata for '${e}':`);for(let{field:n,remote:r,local:o}of t){let s=`${n}:`.padEnd(13);console.log(` ${s}"${r}" \u2192 "${o||"(none)"}"`)}}i(za,"printMetadataDiff");async function Xa(e,t=process.cwd(),n={}){let{loadEnvFile:r=O,loadAppConfig:o=E,getClientForDeployment:s=R,createMetadataClient:a=i(y=>new P(y),"createMetadataClient"),getMissingCredentials:p=T}=n;r(t);let c=o(t);U(c);let l=e.interactive?await F(c,e):D(c.deployments,e.deployment);if(!e.interactive){let y=p(l);if(y.length>0)throw new Error(`Deployment ${l.org}/${l.project} is missing ${y.join(" and ")} in app.json. Use \`cognite apps metadata update --interactive\` for browser-based authentication instead.`)}let d=await s(l,{interactive:e.interactive,appId:c.externalId,orgHint:e.org}),m=a(d),f;try{f=await m.getApp(c.externalId)}catch(y){throw y instanceof de?new Error(`App '${c.externalId}' is not deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):y}let h={name:c.name,description:c.description||""},g=vt(f,h);if(g.length===0){console.log(""),console.log(`Metadata for '${c.externalId}' already matches the deployed app \u2014 nothing to update.`),console.log("Edit name/description in app.json to change them.");return}za(c.externalId,g),await m.updateAppMetadata(c.externalId,c.name,c.description),console.log(""),console.log(`\u2705 Metadata for '${c.externalId}' updated`)}i(Xa,"handleUpdateMetadata");function Lr(e){let t=e.command("metadata").summary("Manage the deployed app's metadata").description("Manage the deployed app's metadata (name and description).");return t.command("update").description("Update the deployed app's name and description from app.json").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
127
125
  Examples:
128
126
  npx @cognite/cli apps metadata update . Push name/description using env-var auth
129
- npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((n,r)=>Da(r)),t}o(Cr,"registerMetadataCommand");async function Ia(e,t,n){let r=await A(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org});return new E(r)}o(Ia,"defaultBuildApiClient");async function $a(e,t={}){let n=t.loadEnvFile??$,r=t.loadAppConfig??v,i=t.buildApiClient??Ia,s=t.discoverSignatures??he,a=process.cwd();n(a);let p=r(a);F(p);let c=e.interactive?await I(p,e):b(p.deployments,e.deployment);if(!e.interactive){let g=D(c);if(g.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${g.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let l=await i(c,e,p),{externalId:d,versionTag:m}=p,y;try{y=await l.getVersion(d,m)}catch(g){throw g instanceof H?new Error(`Version ${m} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):g}if(y.alias==="ACTIVE"){console.log(` ${d} @ ${m} is already ACTIVE \u2014 nothing to do.`);return}if(y.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${m} is already PUBLISHED \u2014 nothing to do.`);return}if(y.lifecycleState==="DEPRECATED"||y.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${m}: version is ${y.lifecycleState} (terminal).`);let f=s(B(a,d,m));f.length>0&&await l.submitSignatures(d,m,f),await l.publishVersion(d,m),console.log(`\u2713 Published ${d} @ ${m} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}o($a,"handlePublish");function Er(e){return e.command("publish").description("Publish the current app version (transition DRAFT \u2192 PUBLISHED)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
127
+ npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((n,r)=>Xa(r)),t}i(Lr,"registerMetadataCommand");async function Za(e,t,n){let r=await R(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org});return new P(r)}i(Za,"defaultBuildApiClient");async function Qa(e,t={}){let n=t.loadEnvFile??O,r=t.loadAppConfig??E,o=t.buildApiClient??Za,s=t.discoverSignatures??ve,a=process.cwd();n(a);let p=r(a);U(p);let c=e.interactive?await F(p,e):D(p.deployments,e.deployment);if(!e.interactive){let g=T(c);if(g.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${g.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let l=await o(c,e,p),{externalId:d,versionTag:m}=p,f;try{f=await l.getVersion(d,m)}catch(g){throw g instanceof j?new Error(`Version ${m} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):g}if(f.alias==="ACTIVE"){console.log(` ${d} @ ${m} is already ACTIVE \u2014 nothing to do.`);return}if(f.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${m} is already PUBLISHED \u2014 nothing to do.`);return}if(f.lifecycleState==="DEPRECATED"||f.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${m}: version is ${f.lifecycleState} (terminal).`);let h=s(B(a,d,m));h.length>0&&await l.submitSignatures(d,m,h),await l.publishVersion(d,m),console.log(`\u2713 Published ${d} @ ${m} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}i(Qa,"handlePublish");function Nr(e){return e.command("publish").description("Publish the current app version (transition DRAFT \u2192 PUBLISHED)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
130
128
  Examples:
131
129
  npx @cognite/cli apps publish . Publish using env-var auth
132
- npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>$a(n))}o(Er,"registerPublishCommand");import{spawnSync as Fa}from"child_process";import{mkdirSync as Ra}from"fs";import{resolve as Dt}from"path";var Ta=["localhost","local.cognite.ai","*.local.cognite.ai"],Oa={info:o(e=>{process.stdout.write(`${e}
133
- `)},"info"),error:o(e=>{process.stderr.write(`${e}
134
- `)},"error")},Ua={spawnSync:Fa,mkdirSync:Ra,logger:Oa};function _a(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}o(_a,"hasMkcert");function La({certDir:e=Dt(process.cwd(),"certificates/mkcert"),domains:t=Ta,deps:n={}}={}){let r={...Ua,...n},{spawnSync:i,mkdirSync:s,logger:a}=r;if(!_a(i))throw a.error("Error: mkcert is not installed."),a.error("Install it with: brew install mkcert (macOS, Linux, WSL)"),a.error("On Windows: choco install mkcert (or scoop install mkcert)"),a.error("See https://github.com/FiloSottile/mkcert#installation for other methods."),new Error("mkcert is not installed");if(a.info("\u2139\uFE0F Installing mkcert root CA into your local trust store."),a.info(" This allows your browser to trust locally-generated certificates."),a.info(" You may be prompted for your system password."),i("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");s(e,{recursive:!0});let c=Dt(e,"localhost.pem"),l=Dt(e,"localhost-key.pem");if(i("mkcert",["-cert-file",c,"-key-file",l,...t],{stdio:"inherit"}).status!==0)throw new Error("mkcert failed to generate certificates");return a.info(""),a.info("Certificates generated:"),a.info(` cert: ${c}`),a.info(` key: ${l}`),{certFile:c,keyFile:l}}o(La,"setupHttps");function Na(e){La({certDir:e.certDir})}o(Na,"handleSetupHttps");function kr(e){return e.command("setup-https").description("Generate trusted local HTTPS certificates via mkcert").option("--cert-dir <path>","Directory to write certs into (default: ./certificates/mkcert)").addHelpText("after",`
130
+ npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>Qa(n))}i(Nr,"registerPublishCommand");import{spawnSync as ep}from"child_process";import{mkdirSync as tp}from"fs";import{resolve as _t}from"path";var np=["localhost","local.cognite.ai","*.local.cognite.ai"],rp={info:i(e=>{process.stdout.write(`${e}
131
+ `)},"info"),error:i(e=>{process.stderr.write(`${e}
132
+ `)},"error")},ip={spawnSync:ep,mkdirSync:tp,logger:rp};function op(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}i(op,"hasMkcert");function sp({certDir:e=_t(process.cwd(),"certificates/mkcert"),domains:t=np,deps:n={}}={}){let r={...ip,...n},{spawnSync:o,mkdirSync:s,logger:a}=r;if(!op(o))throw a.error("Error: mkcert is not installed."),a.error("Install it with: brew install mkcert (macOS, Linux, WSL)"),a.error("On Windows: choco install mkcert (or scoop install mkcert)"),a.error("See https://github.com/FiloSottile/mkcert#installation for other methods."),new Error("mkcert is not installed");if(a.info("\u2139\uFE0F Installing mkcert root CA into your local trust store."),a.info(" This allows your browser to trust locally-generated certificates."),a.info(" You may be prompted for your system password."),o("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");s(e,{recursive:!0});let c=_t(e,"localhost.pem"),l=_t(e,"localhost-key.pem");if(o("mkcert",["-cert-file",c,"-key-file",l,...t],{stdio:"inherit"}).status!==0)throw new Error("mkcert failed to generate certificates");return a.info(""),a.info("Certificates generated:"),a.info(` cert: ${c}`),a.info(` key: ${l}`),{certFile:c,keyFile:l}}i(sp,"setupHttps");function ap(e){sp({certDir:e.certDir})}i(ap,"handleSetupHttps");function Mr(e){return e.command("setup-https").description("Generate trusted local HTTPS certificates via mkcert").option("--cert-dir <path>","Directory to write certs into (default: ./certificates/mkcert)").addHelpText("after",`
135
133
  Examples:
136
134
  npx @cognite/cli@latest apps setup-https Generate certs in ./certificates/mkcert
137
- npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>Na(t))}o(kr,"registerSetupHttpsCommand");import{existsSync as op,writeFileSync as ip}from"fs";import{basename as sp,dirname as ap,join as pp,resolve as Tt}from"path";import{parseScope as cp,signBundle as lp,validateScopes as dp}from"@cognite/app-sdk/codesigning";import{existsSync as tp,readFileSync as np}from"fs";import{pbkdf2 as Ha,randomBytes as ja}from"crypto";import{promisify as Va}from"util";import{CompactEncrypt as Ba,base64url as br,compactDecrypt as Ga}from"jose";var Ma=new TextEncoder,Ka=new TextDecoder,It={encode:o(e=>Ma.encode(e),"encode"),decode:o(e=>Ka.decode(e),"decode")};var qa=Va(Ha),Rt=6e5,Ya="sha512",$t="PBKDF2-HMAC-SHA512",Ft=16,je="A256GCM",Ja=32,Ve=2e6;async function Pr(e,t,n){return await qa(e,t,n,Ja,Ya)}o(Pr,"deriveKey");async function xr(e,t,n=Rt){if(!Number.isInteger(n)||n<1||n>Ve)throw new Error(`Invalid iterations: must be an integer between 1 and ${Ve}`);let r=ja(Ft),i=await Pr(t,r,n);return await new Ba(It.encode(e)).setProtectedHeader({alg:"dir",enc:je,kdf:$t,kdf_iter:n,kdf_salt:br.encode(r)}).encrypt(i)}o(xr,"encryptStringAsJwe");async function Ar(e,t){let{plaintext:n}=await Ga(e,async r=>{if(!e.length)throw new Error("Unexpected JWE empty value");if(t.length<15)throw new Error(`Invalid passphrase it should be at least ${15} but got ${t.length}`);if(r.alg!=="dir")throw new Error(`Unexpected JWE alg "${String(r.alg)}"; only "dir" is supported`);if(r.enc!==je)throw new Error(`Unexpected JWE enc "${String(r.enc)}"; only "${je}" is supported`);if(r.kdf!==$t)throw new Error(`Unexpected KDF "${String(r.kdf)}"; only "${$t}" is supported`);let i=Number(r.kdf_iter);if(!Number.isInteger(i)||i<1||i>Ve)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${Ve}`);if(typeof r.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let s=br.decode(r.kdf_salt);if(s.length!==Ft)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Ft} bytes, got ${s.length}`);return await Pr(t,s,i)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[je]});return It.decode(n)}o(Ar,"decryptJweAsString");function za(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}o(za,"isJweCompact");var Dr=za;import Wa from"enquirer";async function Xa(e){return Wa.prompt(e)}o(Xa,"defaultPrompt");async function Ir(e,t={}){let{prompt:n=Xa}=t,{passphrase:r}=await n({type:"password",name:"passphrase",message:e});return r}o(Ir,"promptPassphrase");import Qa from"enquirer";import{statSync as Za}from"fs";function $r(e,t=Za){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,r)=>r.mtime-n.mtime).map(({key:n})=>n)}o($r,"sortByMtime");async function ep(e){return Qa.prompt(e)}o(ep,"defaultPrompt");async function Fr(e,t={}){if(e.length===1)return e[0];let{prompt:n=ep,sortByMtime:r=$r}=t,i=r(e),s=i[0],{choice:a}=await n({type:"select",name:"choice",message:"Select signing identity",choices:[{name:"latest",message:`Use latest: ${s.kid}`},{name:"pick",message:"Pick from list"}]});if(a==="latest")return s;if(a==="pick"){let{kid:p}=await n({type:"select",name:"kid",message:"Select signing identity",choices:i.map(l=>({name:l.kid,message:[l.kid,l.email,xe(l.source)].filter(Boolean).join(" \u2014 ")}))}),c=i.find(l=>l.kid===p);if(!c)throw new Error("No signing identity selected");return c}else throw new Error(`Unexpected choice: "${a}"`)}o(Fr,"promptSigningIdentity");function rp(e){return{existsSync:e.existsSync??tp,readFileSync:e.readFileSync??((t,n)=>np(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??Pe,decryptJweAsString:e.decryptJweAsString??Ar,discoverLocalKeys:e.discoverLocalKeys??Ae,keysDir:e.keysDir??x().keysDir,promptPassphrase:e.promptPassphrase??Ir,promptSigningIdentity:e.promptSigningIdentity??Fr}}o(rp,"resolveDeps");async function Rr(e,t={}){let n=rp(t);if(e.keyPath){if(!n.existsSync(e.keyPath))throw new Error(`Key file not found: ${e.keyPath}`);if(!e.kid)throw new Error("--signing-identity <kid> is required when using --key");let s=n.readFileSync(e.keyPath,"utf-8").trim();if(Dr(s)){if(!e.interactive)throw new Error(`Key at ${e.keyPath} is passphrase-encrypted. Pass --interactive to enter the passphrase.`);let a=await n.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:await n.decryptJweAsString(s,a),kid:e.kid}}return{privateKeyPem:s,kid:e.kid}}let r=await n.discoverLocalKeys(n.keysDir);if(r.length===0)throw new Error("No signing keys found. Run `cognite keys generate` or pass --key.");let i;if(e.kid)i=r.find(s=>s.kid===e.kid);else if(e.interactive)i=await n.promptSigningIdentity(r);else throw new Error("--signing-identity <kid> is required. Pass --interactive to select it interactively.");if(!i)throw new Error(`No key found with kid "${e.kid}"`);switch(i.source.kind){case"keychain":{let s=await n.readKeyFromKeychain(i.kid);if(!s)throw new Error(`Key "${i.kid}" not found in Keychain`);return{privateKeyPem:s,kid:i.kid}}case"encrypted-file":{if(!e.interactive)throw new Error(`Key "${i.kid}" is passphrase-encrypted. Pass --interactive to enter the passphrase, or store the key in macOS Keychain for non-interactive use.`);let s=await n.promptPassphrase(`Passphrase for key ${i.kid}: `);return{privateKeyPem:await n.decryptJweAsString(n.readFileSync(i.source.path,"utf-8"),s),kid:i.kid}}case"public-only":throw new Error(`Key "${i.kid}" has no private key on this machine (public-only).`)}}o(Rr,"resolvePrivateKey");var mp=o(async(e,t,n,r,i)=>{let s=await A(e,{interactive:i.browserAuth??!1,appId:t,orgHint:i.org});await new E(s).submitSignatures(t,n,r)},"defaultSubmitSignatures");function up(e){return{existsSync:e.existsSync??op,writeFileSync:e.writeFileSync??ip,createBundleStream:e.createBundleStream??De,signBundle:e.signBundle??lp,parseScope:e.parseScope??cp,validateScopes:e.validateScopes??dp,loadAppConfig:e.loadAppConfig??v,resolvePrivateKey:e.resolvePrivateKey??(t=>Rr(t)),submitSignatures:e.submitSignatures??mp,discoverSignatures:e.discoverSignatures??he}}o(up,"resolveDeps");async function Tr(e,t,n={},r=process.cwd()){let i=up(n),s=t.appid,a=t.appVersion,p=[],c=i.loadAppConfig(r);if(s=s??c.externalId,a=a??c.versionTag,t.scope&&t.scope.length>0?p=t.scope.map(i.parseScope):p=c.deployments.map(h=>({org:h.org,project:h.project})),!s)throw new Error("--appid is required (or set externalId in app.json)");if(!a)throw new Error("--app-version is required (or set versionTag in app.json)");let l=e?Tt(r,e):B(r,s,a);if(!i.existsSync(l)){let h=e?"":" (default derived from app.json \u2014 pass [bundle] explicitly to override, or run `cognite apps deploy` first to populate .cognite-bundles/)";throw new Error(`Bundle not found: ${l}${h}`)}let d=i.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
135
+ npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>ap(t))}i(Mr,"registerSetupHttpsCommand");import{existsSync as Ap,writeFileSync as Dp}from"fs";import{basename as Ip,dirname as $p,join as Rp,resolve as Ht}from"path";import{parseScope as Tp,signBundle as Fp,validateScopes as Op}from"@cognite/app-sdk/codesigning";import{existsSync as bp,readFileSync as Pp}from"fs";import{pbkdf2 as lp,randomBytes as dp}from"crypto";import{promisify as mp}from"util";import{CompactEncrypt as up,base64url as Hr,compactDecrypt as gp}from"jose";var pp=new TextEncoder,cp=new TextDecoder,Kt={encode:i(e=>pp.encode(e),"encode"),decode:i(e=>cp.decode(e),"decode")};var fp=mp(lp),Mt=6e5,yp="sha512",Lt="PBKDF2-HMAC-SHA512",Nt=16,We="A256GCM",hp=32,ze=2e6;async function jr(e,t,n){return await fp(e,t,n,hp,yp)}i(jr,"deriveKey");async function Vr(e,t,n=Mt){if(!Number.isInteger(n)||n<1||n>ze)throw new Error(`Invalid iterations: must be an integer between 1 and ${ze}`);let r=dp(Nt),o=await jr(t.expose(),r,n);return await new up(Kt.encode(e.expose())).setProtectedHeader({alg:"dir",enc:We,kdf:Lt,kdf_iter:n,kdf_salt:Hr.encode(r)}).encrypt(o)}i(Vr,"encryptStringAsJwe");async function Br(e,t){let{plaintext:n}=await gp(e,async r=>{if(!e.length)throw new Error("Unexpected JWE empty value");let o=t.expose();if(o.length<15)throw new Error(`Invalid passphrase: must be at least ${15} characters`);if(r.alg!=="dir")throw new Error(`Unexpected JWE alg "${String(r.alg)}"; only "dir" is supported`);if(r.enc!==We)throw new Error(`Unexpected JWE enc "${String(r.enc)}"; only "${We}" is supported`);if(r.kdf!==Lt)throw new Error(`Unexpected KDF "${String(r.kdf)}"; only "${Lt}" is supported`);let s=Number(r.kdf_iter);if(!Number.isInteger(s)||s<1||s>ze)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${ze}`);if(typeof r.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let a=Hr.decode(r.kdf_salt);if(a.length!==Nt)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Nt} bytes, got ${a.length}`);return await jr(o,a,s)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[We]});return Kt.decode(n)}i(Br,"decryptJweAsString");function Sp(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}i(Sp,"isJweCompact");var Gr=Sp;import wp from"enquirer";async function vp(e){return wp.prompt(e)}i(vp,"defaultPrompt");async function Yr(e,t={}){let{prompt:n=vp}=t,{passphrase:r}=await n({type:"password",name:"passphrase",message:e});return w.from(r)}i(Yr,"promptPassphrase");import Ep from"enquirer";import{statSync as Cp}from"fs";function qr(e,t=Cp){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,r)=>r.mtime-n.mtime).map(({key:n})=>n)}i(qr,"sortByMtime");async function kp(e){return Ep.prompt(e)}i(kp,"defaultPrompt");async function Jr(e,t={}){if(e.length===1)return e[0];let{prompt:n=kp,sortByMtime:r=qr}=t,o=r(e),s=o[0],{choice:a}=await n({type:"select",name:"choice",message:"Select signing identity",choices:[{name:"latest",message:`Use latest: ${s.kid}`},{name:"pick",message:"Pick from list"}]});if(a==="latest")return s;if(a==="pick"){let{kid:p}=await n({type:"select",name:"kid",message:"Select signing identity",choices:o.map(l=>({name:l.kid,message:[l.kid,l.email,Fe(l.source)].filter(Boolean).join(" \u2014 ")}))}),c=o.find(l=>l.kid===p);if(!c)throw new Error("No signing identity selected");return c}else throw new Error(`Unexpected choice: "${a}"`)}i(Jr,"promptSigningIdentity");function xp(e){return{existsSync:e.existsSync??bp,readFileSync:e.readFileSync??((t,n)=>Pp(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??Re,readSigningKey:e.readSigningKey??Te,isOS:e.isOS??(t=>A(t)),decryptJweAsString:e.decryptJweAsString??Br,discoverLocalKeys:e.discoverLocalKeys??Oe,keysDir:e.keysDir??$().keysDir,promptPassphrase:e.promptPassphrase??Yr,promptSigningIdentity:e.promptSigningIdentity??Jr}}i(xp,"resolveDeps");async function Wr(e,t={}){let n=xp(t);if(e.keyPath){if(!n.existsSync(e.keyPath))throw new Error(`Key file not found: ${e.keyPath}`);if(!e.kid)throw new Error("--signing-identity <kid> is required when using --key");let s=n.readFileSync(e.keyPath,"utf-8").trim();if(Gr(s)){if(!e.interactive)throw new Error(`Key at ${e.keyPath} is passphrase-encrypted. Pass --interactive to enter the passphrase.`);let a=await n.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:w.from(await n.decryptJweAsString(s,a)),kid:e.kid}}return{privateKeyPem:w.from(s),kid:e.kid}}let r=await n.discoverLocalKeys(n.keysDir);if(r.length===0)throw new Error("No signing keys found. Run `cognite keys generate` or pass --key.");let o;if(e.kid)o=r.find(s=>s.kid===e.kid);else if(e.interactive)o=await n.promptSigningIdentity(r);else throw new Error("--signing-identity <kid> is required. Pass --interactive to select it interactively.");if(!o)throw new Error(`No key found with kid "${e.kid}"`);switch(o.source.kind){case"keychain":{let s=n.isOS("macos")?await n.readKeyFromKeychain(o.kid):await n.readSigningKey(o.kid);if(!s)throw new Error(`Key "${o.kid}" not found in OS credential store`);return{privateKeyPem:s,kid:o.kid}}case"encrypted-file":{if(!e.interactive)throw new Error(`Key "${o.kid}" is passphrase-encrypted. Pass --interactive to enter the passphrase, or store the key in macOS Keychain for non-interactive use.`);let s=await n.promptPassphrase(`Passphrase for key ${o.kid}: `);return{privateKeyPem:w.from(await n.decryptJweAsString(n.readFileSync(o.source.path,"utf-8"),s)),kid:o.kid}}case"public-only":throw new Error(`Key "${o.kid}" has no private key on this machine (public-only).`)}}i(Wr,"resolvePrivateKey");var Up=i(async(e,t,n,r,o)=>{let s=await R(e,{interactive:o.browserAuth??!1,appId:t,orgHint:o.org});await new P(s).submitSignatures(t,n,r)},"defaultSubmitSignatures");function _p(e){return{existsSync:e.existsSync??Ap,writeFileSync:e.writeFileSync??Dp,createBundleStream:e.createBundleStream??Ue,signBundle:e.signBundle??Fp,parseScope:e.parseScope??Tp,validateScopes:e.validateScopes??Op,loadAppConfig:e.loadAppConfig??E,resolvePrivateKey:e.resolvePrivateKey??(t=>Wr(t)),submitSignatures:e.submitSignatures??Up,discoverSignatures:e.discoverSignatures??ve}}i(_p,"resolveDeps");async function zr(e,t,n={},r=process.cwd()){let o=_p(n),s=t.appid,a=t.appVersion,p=[],c=o.loadAppConfig(r);if(s=s??c.externalId,a=a??c.versionTag,t.scope&&t.scope.length>0?p=t.scope.map(o.parseScope):p=c.deployments.map(v=>({org:v.org,project:v.project})),!s)throw new Error("--appid is required (or set externalId in app.json)");if(!a)throw new Error("--app-version is required (or set versionTag in app.json)");let l=e?Ht(r,e):B(r,s,a);if(!o.existsSync(l)){let v=e?"":" (default derived from app.json \u2014 pass [bundle] explicitly to override, or run `cognite apps deploy` first to populate .cognite-bundles/)";throw new Error(`Bundle not found: ${l}${v}`)}let d=o.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
138
136
  ${d.join(`
139
- `)}`);let{privateKeyPem:m,kid:y}=await i.resolvePrivateKey({keyPath:t.key?Tt(r,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),f=i.createBundleStream(l),g=await i.signBundle({privateKeyPem:m,kid:y,appId:s,version:a,bundleStream:f,role:t.asCertifier?"certifier":"developer",scopes:p}),S=t.output?Tt(r,t.output):pp(ap(l),`${sp(l)}.${t.asCertifier?"cert":"dev"}.sig`);i.writeFileSync(S,g.token,"utf-8"),console.log(`\u2705 Signed: ${S}`),console.log(` kid: ${g.kid}`),console.log(` bundle: ${g.payload.bundleSha256}`),console.log(` scopes: ${g.payload.scopes.map(h=>`${h.org}/${h.project}`).join(", ")}`),t.verbose&&console.log(`
140
- Payload:`,JSON.stringify(g.payload,null,2));let w=Array.from(new Set([...i.discoverSignatures(l),g.token])),P=t.interactive?await I(c,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):b(c.deployments,t.deployment);if(!t.browserAuth){let h=D(P);if(h.length>0)throw new Error(`Deployment ${P.org}/${P.project} is missing ${h.join(" and ")} in app.json. Pass --browser-auth to authenticate via browser instead.`)}await i.submitSignatures(P,s,a,w,t),console.log(`
141
- To publish: npx @cognite/cli apps publish .`)}o(Tr,"handleSign");function Or(e,t={}){return e.command("sign [bundle]").description("Sign an app bundle (defaults to .cognite-bundles/<app>-<version>.zip)").option("--key <path>","Private key PEM file path").option("-s, --signing-identity <kid>","Key ID for Keychain or file lookup").option("--appid <id>","Application ID (default: externalId from app.json)").option("-i, --identifier <id>","Alias for --appid").option("--app-version <version>","App version (default: versionTag from app.json)").option("--scope <org/project...>","Deployment scope(s) (default: deployments from app.json)").option("-r, --requirements <org/project...>","Alias for --scope").option("-o, --output <path>","Output file path (default: <bundle>.<dev|cert>.sig)").option("-v, --verbose","Display full payload after signing").option("--as-certifier","Counter-sign a developer signature as certifier").option("--interactive","Enable interactive prompts (key selection, passphrase, deployment target selection)",!1).option("--browser-auth","Use browser-based PKCE auth when submitting the signature",!1).option("-d, --deployment <target>","Deployment target from app.json (index or name; submit step only)").option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive or --browser-auth)").action((n,r)=>{let i={...r,appid:r.identifier??r.appid,scope:r.requirements??r.scope};return Tr(n,i,t)})}o(Or,"registerSignCommand");function gp(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(gp,"describeStatus");function fp(e){if(e.length===0)return["Signatures: none stored"];let t=["Signatures:"];for(let n of e){let r=n.status==="VALID"?"\u2705":"\u274C",i=new Date(n.signatureIat).toISOString();t.push(` ${r} ${n.signerKid} (${n.signerRole}, signed ${i}) \u2014 ${n.status}`)}return t}o(fp,"formatSignatures");async function yp(e){let t=process.cwd();$(t);let n=v(t);F(n);let r=e.interactive?await I(n,e):b(n.deployments,e.deployment);if(!e.interactive){let a=D(r);if(a.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let i=await A(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new E(i);console.log(""),console.log(`App: ${n.name} (${n.externalId})`),console.log(`Version: ${n.versionTag} (local)`);try{let a=await s.getVersion(n.externalId,n.versionTag);console.log(`Status: ${gp(a)}`);let p=await hp(s,n.externalId,n.versionTag);if(console.log(""),p==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let c of fp(p))console.log(c);a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof H){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}o(yp,"handleStatus");async function hp(e,t,n){try{return await e.listSignatures(t,n)}catch(r){if(ne(r)&&r.status===404||r instanceof Error&&/status code: 404/.test(r.message))return"endpoint-unavailable";throw r}}o(hp,"fetchSignatures");function Ur(e){return e.command("status").description("Show the deployment status and signatures of the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
137
+ `)}`);let{privateKeyPem:m,kid:f}=await o.resolvePrivateKey({keyPath:t.key?Ht(r,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),h=o.createBundleStream(l),g=await o.signBundle({privateKeyPem:m.expose(),kid:f,appId:s,version:a,bundleStream:h,role:t.asCertifier?"certifier":"developer",scopes:p}),y=t.output?Ht(r,t.output):Rp($p(l),`${Ip(l)}.${t.asCertifier?"cert":"dev"}.sig`);o.writeFileSync(y,g.token,"utf-8"),console.log(`\u2705 Signed: ${y}`),console.log(` kid: ${g.kid}`),console.log(` bundle: ${g.payload.bundleSha256}`),console.log(` scopes: ${g.payload.scopes.map(v=>`${v.org}/${v.project}`).join(", ")}`),t.verbose&&console.log(`
138
+ Payload:`,JSON.stringify(g.payload,null,2));let S=Array.from(new Set([...o.discoverSignatures(l),g.token])),b=t.interactive?await F(c,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):D(c.deployments,t.deployment);if(!t.browserAuth){let v=T(b);if(v.length>0)throw new Error(`Deployment ${b.org}/${b.project} is missing ${v.join(" and ")} in app.json. Pass --browser-auth to authenticate via browser instead.`)}await o.submitSignatures(b,s,a,S,t),console.log(`
139
+ To publish: npx @cognite/cli apps publish .`)}i(zr,"handleSign");function Xr(e,t={}){return e.command("sign [bundle]").description("Sign an app bundle (defaults to .cognite-bundles/<app>-<version>.zip)").option("--key <path>","Private key PEM file path").option("-s, --signing-identity <kid>","Key ID for Keychain or file lookup").option("--appid <id>","Application ID (default: externalId from app.json)").option("-i, --identifier <id>","Alias for --appid").option("--app-version <version>","App version (default: versionTag from app.json)").option("--scope <org/project...>","Deployment scope(s) (default: deployments from app.json)").option("-r, --requirements <org/project...>","Alias for --scope").option("-o, --output <path>","Output file path (default: <bundle>.<dev|cert>.sig)").option("-v, --verbose","Display full payload after signing").option("--as-certifier","Counter-sign a developer signature as certifier").option("--interactive","Enable interactive prompts (key selection, passphrase, deployment target selection)",!1).option("--browser-auth","Use browser-based PKCE auth when submitting the signature",!1).option("-d, --deployment <target>","Deployment target from app.json (index or name; submit step only)").option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive or --browser-auth)").action((n,r)=>{let o={...r,appid:r.identifier??r.appid,scope:r.requirements??r.scope};return zr(n,o,t)})}i(Xr,"registerSignCommand");function Kp(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}i(Kp,"describeStatus");function Lp(e){if(e.length===0)return["Signatures: none stored"];let t=["Signatures:"];for(let n of e){let r=n.status==="VALID"?"\u2705":"\u274C",o=new Date(n.signatureIat).toISOString();t.push(` ${r} ${n.signerKid} (${n.signerRole}, signed ${o}) \u2014 ${n.status}`)}return t}i(Lp,"formatSignatures");async function Np(e){let t=process.cwd();O(t);let n=E(t);U(n);let r=e.interactive?await F(n,e):D(n.deployments,e.deployment);if(!e.interactive){let a=T(r);if(a.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let o=await R(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new P(o);console.log(""),console.log(`App: ${n.name} (${n.externalId})`),console.log(`Version: ${n.versionTag} (local)`);try{let a=await s.getVersion(n.externalId,n.versionTag);console.log(`Status: ${Kp(a)}`);let p=await Mp(s,n.externalId,n.versionTag);if(console.log(""),p==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let c of Lp(p))console.log(c);a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof j){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}i(Np,"handleStatus");async function Mp(e,t,n){try{return await e.listSignatures(t,n)}catch(r){if(ie(r)&&r.status===404||r instanceof Error&&/status code: 404/.test(r.message))return"endpoint-unavailable";throw r}}i(Mp,"fetchSignatures");function Zr(e){return e.command("status").description("Show the deployment status and signatures of the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
142
140
  Examples:
143
141
  npx @cognite/cli apps status . Status using env-var auth
144
- npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>yp(n))}o(Ur,"registerStatusCommand");import{execFileSync as _t}from"child_process";import Ut from"fs";import Se from"path";import Cp from"readline";var _r="https://cognite.zendesk.com",Sp="360001234312",wp="tf_360015295097",vp="cognite_flows_certifications";function Lr(e,t,n){let r=new URLSearchParams({ticket_form_id:Sp,tf_priority:"normal",tf_subject:e,[wp]:vp,tf_description:t});return`${n}/hc/en-us/requests/new?${r}`}o(Lr,"buildUrl");function Nr(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}o(Nr,"escapeHtml");function Ot(e){return e.map(Nr).join("<br>")}o(Ot,"toHtml");function Mr(e,t=_r){let{appName:n,externalId:r,versionTag:i,archiveName:s,developerName:a,cdfProject:p,cdfCluster:c}=e,l=["Dear Cognite Platform Team,","","I would like to submit my Flows app for review and certification.","",`App name: ${n}`,`App external ID: ${r}`,`Version: ${i}`,p?`CDF project: ${p}`:void 0,c?`CDF cluster: ${c}`:void 0,"","`npx @cognite/cli apps submit` verified App-Brief.md,","code-review-report.md, and design-review-report.md are committed to git.","","Attached (all from dist/submit/):",`[ ] ${s??"src-<sha>.zip"} \u2014 source archive`,`[ ] ${r}-${i}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return Lr(`App Review Request: ${n}`,Ot(l.filter(d=>d!==void 0)),t)}o(Mr,"buildAppReviewUrl");function Kr(e,t,n,r,i=_r){let s=Ot(["Dear Cognite Platform Team,","","I would like to register my Flows app signing key for certified deployments.","",`Key ID (kid): ${e}`,`Developer email: ${t}`,`Expires: ${n}`,"","Please add the following entry to public_keys.yaml:"]),a=`<pre>${Nr(r.replace(/\r\n/g,`
145
- `))}</pre>`,p=Ot(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return Lr(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,i)}o(Kr,"buildKeyRegistrationUrl");function Ep(){return new Promise(e=>{let t=Cp.createInterface({input:process.stdin,output:process.stdout});t.question(`
146
- Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}o(Ep,"defaultPressEnter");var kp=[{pattern:"App-Brief.md",label:"App-Brief.md",skill:"flows-app-brief"},{pattern:"reviews/code-review/*/code-review-report.md",label:"reviews/code-review/feedback-round-<N>/code-review-report.md",skill:"flows-code-review"},{pattern:"reviews/design-review/*/design-review-report.md",label:"reviews/design-review/feedback-round-<N>/design-review-report.md",skill:"flows-design-review"}];function bp(e){let t=kp.filter(({pattern:n})=>_t("git",["-C",e,"ls-files","--",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length===0);if(t.length>0){let n=t.map(({label:r,skill:i})=>` ${r} \u2192 /${i}`);throw new Error(`Certification files are missing or not committed. Run the required skills in Claude Code first:
142
+ npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>Np(n))}i(Zr,"registerStatusCommand");import{execFileSync as Bt}from"child_process";import Vt from"fs";import Ce from"path";import Bp from"readline";var Qr="https://cognite.zendesk.com",Hp="360001234312",jp="tf_360015295097",Vp="cognite_flows_certifications";function ei(e,t,n){let r=new URLSearchParams({ticket_form_id:Hp,tf_priority:"normal",tf_subject:e,[jp]:Vp,tf_description:t});return`${n}/hc/en-us/requests/new?${r}`}i(ei,"buildUrl");function ti(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}i(ti,"escapeHtml");function jt(e){return e.map(ti).join("<br>")}i(jt,"toHtml");function ni(e,t=Qr){let{appName:n,externalId:r,versionTag:o,archiveName:s,developerName:a,cdfProject:p,cdfCluster:c}=e,l=["Dear Cognite Platform Team,","","I would like to submit my Flows app for review and certification.","",`App name: ${n}`,`App external ID: ${r}`,`Version: ${o}`,p?`CDF project: ${p}`:void 0,c?`CDF cluster: ${c}`:void 0,"","`npx @cognite/cli apps submit` verified App-Brief.md,","code-review-report.md, and design-review-report.md are committed to git.","","Attached (all from dist/submit/):",`[ ] ${s??"src-<sha>.zip"} \u2014 source archive`,`[ ] ${r}-${o}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return ei(`App Review Request: ${n}`,jt(l.filter(d=>d!==void 0)),t)}i(ni,"buildAppReviewUrl");function ri(e,t,n,r,o=Qr){let s=jt(["Dear Cognite Platform Team,","","I would like to register my Flows app signing key for certified deployments.","",`Key ID (kid): ${e}`,`Developer email: ${t}`,`Expires: ${n}`,"","Please add the following entry to public_keys.yaml:"]),a=`<pre>${ti(r.replace(/\r\n/g,`
143
+ `))}</pre>`,p=jt(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return ei(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,o)}i(ri,"buildKeyRegistrationUrl");function Gp(){return new Promise(e=>{let t=Bp.createInterface({input:process.stdin,output:process.stdout});t.question(`
144
+ Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}i(Gp,"defaultPressEnter");var Yp=[{pattern:"App-Brief.md",label:"App-Brief.md",skill:"flows-app-brief"},{pattern:"reviews/code-review/*/code-review-report.md",label:"reviews/code-review/feedback-round-<N>/code-review-report.md",skill:"flows-code-review"},{pattern:"reviews/design-review/*/design-review-report.md",label:"reviews/design-review/feedback-round-<N>/design-review-report.md",skill:"flows-design-review"}];function qp(e){let t=Yp.filter(({pattern:n})=>Bt("git",["-C",e,"ls-files","--",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length===0);if(t.length>0){let n=t.map(({label:r,skill:o})=>` ${r} \u2192 /${o}`);throw new Error(`Certification files are missing or not committed. Run the required skills in Claude Code first:
147
145
 
148
146
  `+n.join(`
149
- `)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}o(bp,"assertArtifactsCommitted");async function Pp(e=process.cwd(),t={}){let{openInBrowser:n=Sn,revealInFileManager:r=wn,pressEnter:i=Ep,isInteractive:s=o(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(!Ce())throw new Error("git is not installed. Install git and ensure it is in your PATH.");if(!Ee(e))throw new Error("Not a git repository. Run this command from your app's root directory.");$(e);let a=v(e);F(a),bp(e);let p=Se.join(e,"dist","submit");Ut.mkdirSync(p,{recursive:!0});let c=_t("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(_t("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length>0)throw new Error(`Working tree has uncommitted changes. Commit or stash them before submitting for certification.
147
+ `)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}i(qp,"assertArtifactsCommitted");async function Jp(e=process.cwd(),t={}){let{openInBrowser:n=Rn,revealInFileManager:r=Tn,pressEnter:o=Gp,isInteractive:s=i(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(!Pe())throw new Error("git is not installed. Install git and ensure it is in your PATH.");if(!xe(e))throw new Error("Not a git repository. Run this command from your app's root directory.");O(e);let a=E(e);U(a),qp(e);let p=Ce.join(e,"dist","submit");Vt.mkdirSync(p,{recursive:!0});let c=Bt("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(Bt("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length>0)throw new Error(`Working tree has uncommitted changes. Commit or stash them before submitting for certification.
150
148
 
151
- The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=Se.join(p,d);await new re(Se.join(e,"dist")).createSourceArchive(m);let f=`${a.externalId}-${a.versionTag}.zip`,g=Se.join(e,".cognite-bundles",f),S=!1;Ut.existsSync(g)&&(Ut.copyFileSync(g,Se.join(p,f)),S=!0);let w=Mr({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:Wt(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});console.log(`
152
- \u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(S?` ${f} \u2014 deploy bundle`:" \u26A0 Deploy bundle missing \u2014 run `apps deploy` to generate it, then re-run submit"),console.log(" \u2190 add your screen recording to this folder"),console.log(`
149
+ The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=Ce.join(p,d);await new oe(Ce.join(e,"dist")).createSourceArchive(m);let h=`${a.externalId}-${a.versionTag}.zip`,g=Ce.join(e,".cognite-bundles",h),y=!1;Vt.existsSync(g)&&(Vt.copyFileSync(g,Ce.join(p,h)),y=!0);let S=ni({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:ln(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});console.log(`
150
+ \u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(y?` ${h} \u2014 deploy bundle`:" \u26A0 Deploy bundle missing \u2014 run `apps deploy` to generate it, then re-run submit"),console.log(" \u2190 add your screen recording to this folder"),console.log(`
153
151
  Attach all files from dist/submit/ to the Zendesk ticket.`),console.log(`
154
- \u{1F517} ${w}`),s()&&(await i(),n(w),r(m))}o(Pp,"handleSubmit");function Hr(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
152
+ \u{1F517} ${S}`),s()&&(await o(),n(S),r(m))}i(Jp,"handleSubmit");function ii(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
155
153
  Examples:
156
- npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>Pp())}o(Hr,"registerSubmitCommand");function jr(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return ur(t),vr(t),Ur(t),Cr(t),Er(t),Xn(t),gr(t),kr(t),Hr(t),lr(t),Or(t),Fn(t),t}o(jr,"registerAppsCommand");import{existsSync as Fp,mkdirSync as Rp,writeFileSync as Tp}from"fs";import{dirname as Mt,join as ve}from"path";import{generateSigningKeyPair as Op}from"@cognite/app-sdk/codesigning";import Up from"open";function Vr(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth()+t,i=new Date(Date.UTC(n,r+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(n,r,s))}o(Vr,"addMonthsClamped");function Lt(e){return e.toISOString().slice(0,10)}o(Lt,"formatIsoDate");function Br(e=new Date){return Lt(e)}o(Br,"todayIso");import xp,{Chalk as Ap}from"chalk";var we=new Ap({level:0});function Gr(e){return e.isTTY?xp:we}o(Gr,"chalkForStream");var Be=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),qr=32,Yr=44,Jr=60,Dp="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function Ip(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==Yr&&t.length!==Jr)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${Yr} (raw) or ${Jr} (X.509-wrapped)`);let n=Buffer.from(t,"base64");if(n.length===Be.length+qr&&n.subarray(0,Be.length).equals(Be))return n.subarray(Be.length).toString("base64");if(n.length===qr)return n.toString("base64");throw new Error(`Unexpected Ed25519 public key length: got ${n.length} bytes, expected 32 (raw) or 44 (X.509-wrapped)`)}o(Ip,"pemBodyOneLine");function Nt(e,t=we,n=new Date){let r=zr(e.issuedAt??Br(n)),i=zr(e.expires),s=Ip(e.publicKeyPem),a=" ",p=o((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
154
+ npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>Jp())}i(ii,"registerSubmitCommand");function oi(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return $r(t),Kr(t),Zr(t),Lr(t),Nr(t),gr(t),Rr(t),Mr(t),ii(t),Ar(t),Xr(t),Jn(t),t}i(oi,"registerAppsCommand");import{existsSync as ec,mkdirSync as tc,writeFileSync as nc}from"fs";import{dirname as qt,join as ke}from"path";import{generateSigningKeyPair as rc}from"@cognite/app-sdk/codesigning";import ic from"open";function si(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth()+t,o=new Date(Date.UTC(n,r+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),o);return new Date(Date.UTC(n,r,s))}i(si,"addMonthsClamped");function Gt(e){return e.toISOString().slice(0,10)}i(Gt,"formatIsoDate");function ai(e=new Date){return Gt(e)}i(ai,"todayIso");import Wp,{Chalk as zp}from"chalk";var Ee=new zp({level:0});function pi(e){return e.isTTY?Wp:Ee}i(pi,"chalkForStream");var Xe=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),ci=32,li=44,di=60,Xp="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function Zp(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==li&&t.length!==di)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${li} (raw) or ${di} (X.509-wrapped)`);let n=Buffer.from(t,"base64");if(n.length===Xe.length+ci&&n.subarray(0,Xe.length).equals(Xe))return n.subarray(Xe.length).toString("base64");if(n.length===ci)return n.toString("base64");throw new Error(`Unexpected Ed25519 public key length: got ${n.length} bytes, expected 32 (raw) or 44 (X.509-wrapped)`)}i(Zp,"pemBodyOneLine");function Yt(e,t=Ee,n=new Date){let r=mi(e.issuedAt??ai(n)),o=mi(e.expires),s=Zp(e.publicKeyPem),a=" ",p=i((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
157
155
  `,"kv"),c="";return c+=`
158
- ${t.bold("Add this entry to")} ${t.magenta(Dp)} ${t.bold("under")} ${t.cyan("publicKeys:")}
156
+ ${t.bold("Add this entry to")} ${t.magenta(Xp)} ${t.bold("under")} ${t.cyan("publicKeys:")}
159
157
 
160
158
  `,c+=` ${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
161
- `,c+=p("publicKey",t.green(s)),c+=p("email",t.yellow(e.email)),c+=p("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),c+=p("issuedAt",t.green(r)),c+=p("expiresAt",t.green(i)),c+=p("revokedAt",t.dim("null")),c}o(Nt,"renderRegistryYamlBlock");function zr(e){let t=e.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return`${t}T00:00:00Z`;let n=new Date(t);if(Number.isNaN(n.getTime()))throw new Error(`Invalid date '${e}': expected YYYY-MM-DD or ISO-8601 instant`);return n.toISOString()}o(zr,"toIsoInstant");import $p from"clipboardy";function Wr(e){return $p.write(e)}o(Wr,"copyToClipboard");function _p(e){return{writeFileSync:e.writeFileSync??Tp,mkdirSync:e.mkdirSync??Rp,existsSync:e.existsSync??Fp,generateSigningKeyPair:e.generateSigningKeyPair??Op,encryptStringAsJwe:e.encryptStringAsJwe??xr,storeKeyInKeychain:e.storeKeyInKeychain??En,isOS:e.isOS??(t=>T(t)),promptKid:e.promptKid??dn,promptExpiryMonths:e.promptExpiryMonths??un,promptEmail:e.promptEmail??gn,promptPassphrase:e.promptPassphrase??fn,promptConfirmOverwrite:e.promptConfirmOverwrite??yn,discoverLocalKeys:e.discoverLocalKeys??(()=>Ae()),promptZendeskAction:e.promptZendeskAction??mn,openUrl:e.openUrl??(t=>Up(t)),copyToClipboard:e.copyToClipboard??Wr}}o(_p,"resolveDeps");function Zr(e,t={}){let n=_p(t),r=e.command("keys").description("Manage code signing keys");r.command("generate").description("Generate an Ed25519 keypair for code signing").option("-o, --output <path>","Encrypted private key output path (forces file storage even on macOS)").option("--no-keychain",`Skip macOS Keychain and write a passphrase-encrypted private key under ${x().keysDir} instead`).option("-e, --expires <months>",`Validity in months (${1}-${12}); skips the interactive prompt`).option("--email <address>","Email address for the registry entry; skips the interactive prompt").option("--kid <identifier>","Signing identity name for the registry (e.g. jsmith-dev-001); skips the interactive prompt").option("--force","Overwrite an existing key without prompting for confirmation").option("--copy-link","Copy the Zendesk registration link to the clipboard without prompting").option("--interactive","Prompt for any required flags that are not supplied",!1).action(i=>Kp(i,n)),r.command("list").description("List local signing identities and their storage location").action(()=>Lp(n))}o(Zr,"registerKeysCommand");async function Lp(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
162
- `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${x().keysDir}).
163
- `);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,xe(a.source),a.email??"\u2014"]),i=n.map((a,p)=>Math.max(a.length,...r.map(c=>c[p].length))),s=o(a=>a.map((p,c)=>p.padEnd(i[c])).join(" ").trimEnd(),"fmt");process.stdout.write(`${s(n)}
159
+ `,c+=p("publicKey",t.green(s)),c+=p("email",t.yellow(e.email)),c+=p("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),c+=p("issuedAt",t.green(r)),c+=p("expiresAt",t.green(o)),c+=p("revokedAt",t.dim("null")),c}i(Yt,"renderRegistryYamlBlock");function mi(e){let t=e.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return`${t}T00:00:00Z`;let n=new Date(t);if(Number.isNaN(n.getTime()))throw new Error(`Invalid date '${e}': expected YYYY-MM-DD or ISO-8601 instant`);return n.toISOString()}i(mi,"toIsoInstant");import Qp from"clipboardy";function ui(e){return Qp.write(e)}i(ui,"copyToClipboard");function oc(e){return{writeFileSync:e.writeFileSync??nc,mkdirSync:e.mkdirSync??tc,existsSync:e.existsSync??ec,generateSigningKeyPair:e.generateSigningKeyPair??rc,encryptStringAsJwe:e.encryptStringAsJwe??Vr,storeKeyInKeychain:e.storeKeyInKeychain??Un,storeSigningKey:e.storeSigningKey??Mn,isOS:e.isOS??(t=>A(t)),promptKid:e.promptKid??bn,promptExpiryMonths:e.promptExpiryMonths??xn,promptEmail:e.promptEmail??An,promptPassphrase:e.promptPassphrase??Dn,promptConfirmOverwrite:e.promptConfirmOverwrite??In,discoverLocalKeys:e.discoverLocalKeys??(()=>Oe()),promptZendeskAction:e.promptZendeskAction??Pn,openUrl:e.openUrl??(t=>ic(t)),copyToClipboard:e.copyToClipboard??ui}}i(oc,"resolveDeps");function fi(e,t={}){let n=oc(t),r=e.command("keys").description("Manage code signing keys");r.command("generate").description("Generate an Ed25519 keypair for code signing").option("-o, --output <path>","Encrypted private key output path (forces file storage even on macOS)").option("--no-keychain",`Skip the OS credential store (macOS Keychain / Windows Credential Manager) and write a passphrase-encrypted private key under ${$().keysDir} instead`).option("-e, --expires <months>",`Validity in months (${1}-${12}); skips the interactive prompt`).option("--email <address>","Email address for the registry entry; skips the interactive prompt").option("--kid <identifier>","Signing identity name for the registry (e.g. jsmith-dev-001); skips the interactive prompt").option("--force","Overwrite an existing key without prompting for confirmation").option("--copy-link","Copy the Zendesk registration link to the clipboard without prompting").option("--interactive","Prompt for any required flags that are not supplied",!1).action(o=>cc(o,n)),r.command("list").description("List local signing identities and their storage location").action(()=>sc(n))}i(fi,"registerKeysCommand");async function sc(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
160
+ `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${$().keysDir}).
161
+ `);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,Fe(a.source),a.email??"\u2014"]),o=n.map((a,p)=>Math.max(a.length,...r.map(c=>c[p].length))),s=i(a=>a.map((p,c)=>p.padEnd(o[c])).join(" ").trimEnd(),"fmt");process.stdout.write(`${s(n)}
164
162
  `);for(let a of r)process.stdout.write(`${s(a)}
165
- `)}o(Lp,"handleList");function Xr(e,t,n){let r=ve(x().keysDir,`${e}${J}`);return n.mkdirSync(Mt(r),{recursive:!0}),n.writeFileSync(r,t),r}o(Xr,"writePublicKey");async function Np(e,t,n,r,i,{force:s=!1}={}){let a=r??ve(x().keysDir,`${e}${tt}`);if(i.mkdirSync(Mt(a),{recursive:!0}),!s&&i.existsSync(a))throw new Error(`Refusing to overwrite existing key at ${a}. Delete it first if you really want to regenerate: rm ${a}`);let p=await i.encryptStringAsJwe(t,n);return i.writeFileSync(a,p,{mode:384}),a}o(Np,"writeEncryptedPrivateKey");function Mp(e,t,n){let r=[];if(e.expires===void 0)r.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{se(e.expires)}catch(i){r.push(i instanceof Error?i.message:String(i))}if(e.kid===void 0)r.push("--kid <identifier> is required. Pass --interactive to enter it interactively.");else try{let i=te(e.kid),s=ve(x().keysDir,`${i}${J}`);n(s)&&!e.force&&r.push(`Key "${i}" already exists. Use --force to overwrite without prompting.`)}catch(i){r.push(i instanceof Error?i.message:String(i))}if(e.email===void 0)r.push("--email <address> is required. Pass --interactive to enter it interactively.");else try{ie(e.email,"--email")}catch(i){r.push(i instanceof Error?i.message:String(i))}return t||r.push("A passphrase is required for encrypted key storage. Pass --interactive to enter it interactively."),r}o(Mp,"collectNonInteractiveErrors");async function Kp(e,t,n=new Date){let{isOS:r,existsSync:i,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:p,storeKeyInKeychain:c,promptExpiryMonths:l,promptKid:d,promptEmail:m,promptPassphrase:y,promptConfirmOverwrite:f}=t,g=e.interactive??!1,S=e.keychain!==!1&&r("macos")&&!e.output;if(!g){let _=Mp(e,S,i);if(_.length>0)throw new Error(_.join(`
166
- `))}let w;e.expires!==void 0?w=se(e.expires):w=await l();let P=Lt(Vr(n,w)),h;e.kid!==void 0?h=te(e.kid):h=await d();let M=ve(x().keysDir,`${h}${J}`),U=i(M);if(U&&!e.force&&!await f(h)){process.stderr.write(`Aborted.
167
- `);return}let j;e.email!==void 0?j=ie(e.email,"--email"):j=await m();let me=S?{kind:"keychain"}:{kind:"file",passphrase:await y()};process.stderr.write(`
163
+ `)}i(sc,"handleList");function gi(e,t,n){let r=ke($().keysDir,`${e}${J}`);return n.mkdirSync(qt(r),{recursive:!0}),n.writeFileSync(r,t),r}i(gi,"writePublicKey");async function ac(e,t,n,r,o,{force:s=!1}={}){let a=r??ke($().keysDir,`${e}${ct}`);if(o.mkdirSync(qt(a),{recursive:!0}),!s&&o.existsSync(a))throw new Error(`Refusing to overwrite existing key at ${a}. Delete it first if you really want to regenerate: rm ${a}`);let p=await o.encryptStringAsJwe(t,n);return o.writeFileSync(a,p,{mode:384}),a}i(ac,"writeEncryptedPrivateKey");function pc(e,t,n){let r=[];if(e.expires===void 0)r.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{pe(e.expires)}catch(o){r.push(o instanceof Error?o.message:String(o))}if(e.kid===void 0)r.push("--kid <identifier> is required. Pass --interactive to enter it interactively.");else try{let o=re(e.kid),s=ke($().keysDir,`${o}${J}`);n(s)&&!e.force&&r.push(`Key "${o}" already exists. Use --force to overwrite without prompting.`)}catch(o){r.push(o instanceof Error?o.message:String(o))}if(e.email===void 0)r.push("--email <address> is required. Pass --interactive to enter it interactively.");else try{ae(e.email,"--email")}catch(o){r.push(o instanceof Error?o.message:String(o))}return t||r.push("A passphrase is required for encrypted key storage. Pass --interactive to enter it interactively."),r}i(pc,"collectNonInteractiveErrors");async function cc(e,t,n=new Date){let{isOS:r,existsSync:o,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:p,storeKeyInKeychain:c,storeSigningKey:l,promptExpiryMonths:d,promptKid:m,promptEmail:f,promptPassphrase:h,promptConfirmOverwrite:g}=t,y=e.interactive??!1,S=e.keychain!==!1&&!e.output&&(r("macos")||r("windows"));if(!y){let M=pc(e,S,o);if(M.length>0)throw new Error(M.join(`
164
+ `))}let b;e.expires!==void 0?b=pe(e.expires):b=await d();let v=Gt(si(n,b)),C;e.kid!==void 0?C=re(e.kid):C=await m();let z=ke($().keysDir,`${C}${J}`),V=o(z);if(V&&!e.force&&!await g(C)){process.stderr.write(`Aborted.
165
+ `);return}let I;e.email!==void 0?I=ae(e.email,"--email"):I=await f();let k=S?{kind:"keychain"}:{kind:"file",passphrase:await h()};process.stderr.write(`
168
166
  Generating Ed25519 keypair...
169
167
 
170
- `);let{privateKeyPem:C,publicKeyPem:V}=await p(h);if(me.kind==="keychain"){await c(h,C);let _=Xr(h,V,t);process.stderr.write(`Public key: ${_}
171
- `),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${h})
172
- `)}else{let _=await Np(h,C,me.passphrase,e.output,t,{force:U}),So=Xr(h,V,t);process.stderr.write(`Public key: ${So}
173
- `),process.stderr.write(`Private key: ${_} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Rt.toLocaleString()})
174
- `),r("macos")||process.stderr.write(` (macOS Keychain integration is the default on darwin; on this OS we use the file.)
175
- `)}let oe=ve(x().keysDir,`${h}${nt}`);s(Mt(oe),{recursive:!0}),a(oe,JSON.stringify({email:j}));let k=Gr(process.stderr);process.stderr.write(`
176
- Signing identity (kid): ${k.green(h)}
177
- `),process.stderr.write(`Expires: ${P} (${w} month${w===1?"":"s"} from today)
178
- `);let W={kid:h,publicKeyPem:V,email:j,expires:P};g||(process.stderr.write(`
168
+ `);let{privateKeyPem:X,publicKeyPem:Z}=await p(C),x=w.from(X);if(k.kind==="keychain"){r("macos")?await c(C,x):await l(C,x);let M=gi(C,Z,t);process.stderr.write(`Public key: ${M}
169
+ `),process.stderr.write(`Private key: OS credential store (account: ${C})
170
+ `)}else{let M=await ac(C,x,k.passphrase,e.output,t,{force:V}),Ui=gi(C,Z,t);process.stderr.write(`Public key: ${Ui}
171
+ `),process.stderr.write(`Private key: ${M} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Mt.toLocaleString()})
172
+ `)}let Q=ke($().keysDir,`${C}${lt}`);s(qt(Q),{recursive:!0}),a(Q,JSON.stringify({email:I}));let se=pi(process.stderr);process.stderr.write(`
173
+ Signing identity (kid): ${se.green(C)}
174
+ `),process.stderr.write(`Expires: ${v} (${b} month${b===1?"":"s"} from today)
175
+ `);let be={kid:C,publicKeyPem:Z,email:I,expires:v};y||(process.stderr.write(`
179
176
  Key registration data:
180
177
 
181
- `),process.stderr.write(Nt(W,k,n)));let X=Kr(h,j,P,Nt(W,we,n));process.stderr.write(`
182
- ${k.bold("Next:")}
178
+ `),process.stderr.write(Yt(be,se,n)));let ee=ri(C,I,v,Yt(be,Ee,n));process.stderr.write(`
179
+ ${se.bold("Next:")}
183
180
  `),process.stderr.write(` 1. Register your signing key \u2014 submit this pre-filled Zendesk request:
184
- `);let Z;if(e.copyLink?Z="clipboard":g?Z=await t.promptZendeskAction():Z=null,Z==="browser")try{await t.openUrl(X),process.stderr.write(` Opening in browser...
185
- `)}catch{process.stderr.write(` URL: ${X}
186
- `)}else if(Z==="clipboard"){let _=!1;try{await t.copyToClipboard(X),_=!0}catch{}process.stderr.write(_&&!e.copyLink?` Link copied to clipboard.
187
- `:` URL: ${X}
188
- `)}else process.stderr.write(` URL: ${X}
181
+ `);let ge;if(e.copyLink?ge="clipboard":y?ge=await t.promptZendeskAction():ge=null,ge==="browser")try{await t.openUrl(ee),process.stderr.write(` Opening in browser...
182
+ `)}catch{process.stderr.write(` URL: ${ee}
183
+ `)}else if(ge==="clipboard"){let M=!1;try{await t.copyToClipboard(ee),M=!0}catch{}process.stderr.write(M&&!e.copyLink?` Link copied to clipboard.
184
+ `:` URL: ${ee}
185
+ `)}else process.stderr.write(` URL: ${ee}
189
186
  `);process.stderr.write(`
190
187
  2. Once your key is approved, sign your Dune app:
191
- `),process.stderr.write(` ${k.cyan(`cognite sign -s ${h}`)}
192
- `)}o(Kp,"handleGenerate");import{performance as Qr}from"perf_hooks";var eo=1e3,Ge;function Hp(){Ge=Qr.now()}o(Hp,"markActionStart");function jp(){Ge=void 0}o(jp,"resetActionStart");function Vp(){if(Ge!==void 0)return Math.max(0,Math.round(Qr.now()-Ge))}o(Vp,"snapshotActionDurationMs");function to(){let e=Vp();return jp(),{...e!==void 0&&{actionDurationMs:e}}}o(to,"takePerformanceFields");var Bp=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function Gp(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:Bp.has(t)?[t,n]:[t,"[REDACTED]"]))}o(Gp,"sanitize");function qp(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}o(qp,"getCommandPath");function no(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(no,"tryLoadAppConfig");function Kt(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(Kt,"commandFromArgv");function ro(e,t,n=v){e.hook("preAction",()=>{Hp()}),e.hook("postAction",async(r,i)=>{try{let s={command:qp(i),options:Gp(i.opts()),success:!0,...no(n),...to()};t.track("Flows.CLI.Command",{...s}),await t.flush(eo)}catch{}})}o(ro,"instrument");async function oo(e,t,n=v){try{let r={command:Kt(t),options:{},success:!1,...no(n),...to()};e.track("Flows.CLI.Command",{...r}),await e.flush(eo)}catch{}}o(oo,"trackFailure");var Yp="ERR_USE_AFTER_CLOSE";function so(e){return e instanceof Error&&"code"in e&&e.code===Yp}o(so,"isReadlineClosedError");function Jp(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(Jp,"isPlainObject");function Ht(e){return e==null||so(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Jp(e)&&Object.keys(e).length===0)}o(Ht,"isPromptCancel");var io=!1;function ao(){io||(io=!0,process.on("uncaughtException",e=>{so(e)&&(console.error(`
193
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{Ht(e)&&(console.error(`
194
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(ao,"installCancelHandler");import{homedir as zp,userInfo as Wp}from"os";var Xp=zp(),Zp=(()=>{try{return Wp().username}catch{return""}})();function le(e,t=Xp){if(!t||t==="/")return e;let n=e.replaceAll(t,"~"),r=t.replaceAll("\\","/");return r!==t&&(n=n.replaceAll(r,"~")),n=n.replace(/(?<![A-Za-z0-9_])[A-Za-z]:[/\\]Users[/\\][^\s/\\]+(?=[/\\]|$)/g,"~"),n=n.replace(/(?<![A-Za-z0-9_])\/(?:Users|home)\/[^\s/]+(?=[/\\]|$)/g,"~"),n}o(le,"redactHomedir");function Qp(e,t=Zp){if(!t||t.length<3)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp("(^|[\\/\\s:])"+n+"(?=[\\/\\s:.@]|$)","g");return e.replace(r,"$1<user>")}o(Qp,"redactUsername");var ec=1e3,tc="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",nc={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function rc(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(rc,"buildRelease");var oc="192.0.2.0";function ic(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:le(t.filename)},...t.abs_path!==void 0&&{abs_path:le(t.abs_path)},...t.module!==void 0&&{module:le(t.module)}}))}o(ic,"scrubStackFrames");function jt(e){return Qp(le(e))}o(jt,"redactPii");function sc(e){let t={...e.user,email:void 0,username:void 0,ip_address:oc,id:void 0},n=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?jt(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:ic(s.stacktrace.frames)}}})),r=e.contexts?.cli,i=r!==void 0?Object.fromEntries(Object.entries(r).map(([s,a])=>[s,typeof a=="string"?jt(a):a])):void 0;return{...e,message:e.message!==void 0?jt(e.message):e.message,user:t,server_name:void 0,...n!==void 0&&{exception:{...e.exception,values:n}},...i!==void 0&&{contexts:{...e.contexts,cli:i}}}}o(sc,"scrubPii");function po(e={}){let t=e.env??process.env;if(ft(t))return nc;let n=rc(e),r="production",i=null,s=null;function a(){return{dsn:tc,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:fe},contexts:{cli:{applicationId:fe,node:process.version,platform:process.platform}}},beforeSend:sc}}o(a,"buildInitOptions");async function p(){return i||(s||(s=(async()=>{try{let c=e.sdk??await import("@sentry/node");return c.init(a()),i=c,c}catch{return null}})()),s)}return o(p,"ensureSdk"),{async captureError(c,l){try{let d=await p();if(!d)return;d.captureException(c,ac(c,l))}catch{}},async flush(c=ec){try{if(!i)return;await i.flush(c)}catch{}}}}o(po,"createErrorReporter");function ac(e,t){let n={level:"fatal"},r={applicationId:fe,node:process.version,platform:process.platform};if(t?.command&&(n.tags={command:t.command},r.command=t.command),Yt(e)&&(e.hint&&(r.hint=e.hint),e.helpUrl&&(r.helpUrl=e.helpUrl),r.shouldReport=e.shouldReport),n.contexts={cli:r},Jt(e)&&(n.contexts.http={url:e.requestUrl!==void 0?le(e.requestUrl):void 0,status_code:e.httpStatusCode},e.responseBody!==void 0)){let i=typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody);n.extra={responseBody:le(i)}}return n}o(ac,"buildCaptureContext");import{mkdirSync as pc,readFileSync as cc,writeFileSync as lc}from"fs";import{homedir as dc}from"os";import{resolve as qe}from"path";import{debuglog as mc}from"util";import{lt as uc,parse as co}from"semver";var gc="https://registry.npmjs.org/@cognite/cli/latest",fc=1500,lo="upgrade-check.json",mo=qe(process.env.XDG_CACHE_HOME||qe(dc(),".cache"),"@cognite","cli"),Vt=mc("cognite-flows");function yc(e,t){return!e||!t||!co(e)||!co(t)?!1:uc(e,t)}o(yc,"isOutdated");async function hc({timeout:e=fc,registryUrl:t=gc,fetchImpl:n=globalThis.fetch}={}){if(typeof n!="function")return null;try{let r=await n(t,{signal:AbortSignal.timeout(e)});if(!r?.ok)return null;let i=await r.json();return typeof i?.version=="string"?i.version:null}catch(r){return Vt("fetchLatestVersion failed (%s): %O",t,r),null}}o(hc,"fetchLatestVersion");function Sc(e=mo,t=864e5){try{let n=cc(qe(e,lo),"utf-8"),r=JSON.parse(n);return typeof r.latest!="string"||typeof r.fetchedAt!="number"||Date.now()-r.fetchedAt>t?null:{latest:r.latest,fetchedAt:r.fetchedAt}}catch(n){return Vt("readUpgradeCheckCache failed (%s): %O",e,n),null}}o(Sc,"readUpgradeCheckCache");function wc(e,t){try{pc(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};lc(qe(e,lo),JSON.stringify(n))}catch(n){Vt("writeUpgradeCheckCache failed (%s): %O",e,n)}}o(wc,"writeUpgradeCheckCache");async function vc({cacheDir:e=mo,...t}={}){let n=await hc(t);n&&wc(e,n)}o(vc,"startBackgroundUpgradeCheck");function uo(e,{onOutdated:t,cacheDir:n,...r}={}){let i=Sc(n);if(i){yc(e,i.latest)&&t?.(e,i.latest);return}vc({cacheDir:n,...r})}o(uo,"preActionUpgradeCheck");import{default as nh,chalkStderr as go}from"chalk";function fo(e,t){let n=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],r=Math.max(...n.map(p=>[...p].length))+2,i="\u2500".repeat(r),s=o(p=>`\u2502 ${p}${" ".repeat(r-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...n.map(s),`\u2514${i}\u2518`].join(`
195
- `);return go.bold.yellow(a)}o(fo,"formatUpgradeWarning");function kc(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(kc,"isDep0040Warning");var Gt=process,bc=Gt.emit.bind(Gt);Gt.emit=function(e,...t){return e==="warning"&&kc(t[0])?!1:bc(e,...t)};ao();var de=new Ec;de.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.6.0").showHelpAfterError().configureOutput({writeOut:o(e=>Cc(1,e),"writeOut")});de.hook("preAction",()=>{uo("1.6.0",{onOutdated:o((e,t)=>{console.warn(`
196
- ${fo(e,t)}
197
- `)},"onOutdated")})});jr(de);Zr(de);var ho=Te({packageName:"@cognite/cli",cliVersion:"1.6.0"}),yo=po({packageName:"@cognite/cli",cliVersion:"1.6.0"});ro(de,ho);var Bt=process.argv.slice(2);de.parseAsync(Bt,{from:"user"}).catch(async e=>{await oo(ho,Bt),Ht(e)&&(console.error(`
198
- Cancelled.`),process.exit(130)),(!(e instanceof u)||e.shouldReport)&&(await yo.captureError(e,{command:Kt(Bt)}),await yo.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof u&&(e.hint||e.helpUrl)&&(console.error(""),e.hint&&console.error(`\u{1F4A1} ${e.hint}`),e.helpUrl&&console.error(`\u{1F4DA} ${e.helpUrl}`)),process.exit(1)});
188
+ `),process.stderr.write(` ${se.cyan(`cognite sign -s ${C}`)}
189
+ `)}i(cc,"handleGenerate");import{performance as yi}from"perf_hooks";var hi=1e3,Ze;function lc(){Ze=yi.now()}i(lc,"markActionStart");function dc(){Ze=void 0}i(dc,"resetActionStart");function mc(){if(Ze!==void 0)return Math.max(0,Math.round(yi.now()-Ze))}i(mc,"snapshotActionDurationMs");function Si(){let e=mc();return dc(),{...e!==void 0&&{actionDurationMs:e}}}i(Si,"takePerformanceFields");var uc=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function gc(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:uc.has(t)?[t,n]:[t,"[REDACTED]"]))}i(gc,"sanitize");function fc(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}i(fc,"getCommandPath");function wi(e){try{let t=e(process.cwd()),n=t.deployments[0];return{appName:t.name,appExternalId:t.externalId,appVersionTag:t.versionTag,...n&&{cogniteOrg:n.org,cogniteProject:n.project}}}catch{return{}}}i(wi,"tryLoadAppConfig");function Jt(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}i(Jt,"commandFromArgv");function vi(e,t,n=E){e.hook("preAction",()=>{lc()}),e.hook("postAction",async(r,o)=>{try{let s={command:fc(o),options:gc(o.opts()),success:!0,...wi(n),...Si()};t.track("Flows.CLI.Command",{...s}),await t.flush(hi)}catch{}})}i(vi,"instrument");async function Ci(e,t,n=E){try{let r={command:Jt(t),options:{},success:!1,...wi(n),...Si()};e.track("Flows.CLI.Command",{...r}),await e.flush(hi)}catch{}}i(Ci,"trackFailure");var yc="ERR_USE_AFTER_CLOSE";function ki(e){return e instanceof Error&&"code"in e&&e.code===yc}i(ki,"isReadlineClosedError");function hc(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(hc,"isPlainObject");function Wt(e){return e==null||ki(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&hc(e)&&Object.keys(e).length===0)}i(Wt,"isPromptCancel");var Ei=!1;function bi(){Ei||(Ei=!0,process.on("uncaughtException",e=>{ki(e)&&(console.error(`
190
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{Wt(e)&&(console.error(`
191
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}i(bi,"installCancelHandler");import{homedir as Sc,userInfo as wc}from"os";var vc=Sc(),Cc=(()=>{try{return wc().username}catch{return""}})();function me(e,t=vc){if(!t||t==="/")return e;let n=e.replaceAll(t,"~"),r=t.replaceAll("\\","/");return r!==t&&(n=n.replaceAll(r,"~")),n=n.replace(/(?<![A-Za-z0-9_])[A-Za-z]:[/\\]Users[/\\][^\s/\\]+(?=[/\\]|$)/g,"~"),n=n.replace(/(?<![A-Za-z0-9_])\/(?:Users|home)\/[^\s/]+(?=[/\\]|$)/g,"~"),n}i(me,"redactHomedir");function Ec(e,t=Cc){if(!t||t.length<3)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp("(^|[\\/\\s:])"+n+"(?=[\\/\\s:.@]|$)","g");return e.replace(r,"$1<user>")}i(Ec,"redactUsername");var kc=/(['"]?(?:access_token|accessToken|client_secret|clientSecret|refresh_token|refreshToken|password|token|passphrase)['"]?\s*:\s*)(?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*')/gi;function Pi(e){return e.replace(kc,(t,n)=>{let r=t[n.length];return`${n}${r}[REDACTED]${r}`})}i(Pi,"redactCredentials");var bc=1e3,Pc="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",xc={captureError:i(async()=>{},"captureError"),flush:i(async()=>{},"flush")};function Ac(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}i(Ac,"buildRelease");var Dc="192.0.2.0";function Ic(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:me(t.filename)},...t.abs_path!==void 0&&{abs_path:me(t.abs_path)},...t.module!==void 0&&{module:me(t.module)}}))}i(Ic,"scrubStackFrames");function zt(e){return Pi(Ec(me(e)))}i(zt,"redactPii");function $c(e){let t={...e.user,email:void 0,username:void 0,ip_address:Dc,id:void 0},n=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?zt(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:Ic(s.stacktrace.frames)}}})),r=e.contexts?.cli,o=r!==void 0?Object.fromEntries(Object.entries(r).map(([s,a])=>[s,typeof a=="string"?zt(a):a])):void 0;return{...e,message:e.message!==void 0?zt(e.message):e.message,user:t,server_name:void 0,...n!==void 0&&{exception:{...e.exception,values:n}},...o!==void 0&&{contexts:{...e.contexts,cli:o}}}}i($c,"scrubPii");function xi(e={}){let t=e.env??process.env;if(kt(t))return xc;let n=Ac(e),r="production",o=null,s=null;function a(){return{dsn:Pc,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:Se},contexts:{cli:{applicationId:Se,node:process.version,platform:process.platform}}},beforeSend:$c}}i(a,"buildInitOptions");async function p(){return o||(s||(s=(async()=>{try{let c=e.sdk??await import("@sentry/node");return c.init(a()),o=c,c}catch{return null}})()),s)}return i(p,"ensureSdk"),{async captureError(c,l){try{let d=await p();if(!d)return;d.captureException(c,Rc(c,l))}catch{}},async flush(c=bc){try{if(!o)return;await o.flush(c)}catch{}}}}i(xi,"createErrorReporter");function Rc(e,t){let n={level:"fatal"},r={applicationId:Se,node:process.version,platform:process.platform};if(t?.command&&(n.tags={command:t.command},r.command=t.command),an(e)&&(e.hint&&(r.hint=e.hint),e.helpUrl&&(r.helpUrl=e.helpUrl),r.shouldReport=e.shouldReport),n.contexts={cli:r},pn(e)&&(n.contexts.http={url:e.requestUrl!==void 0?me(e.requestUrl):void 0,status_code:e.httpStatusCode},e.responseBody!==void 0)){let o=typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody);n.extra={responseBody:Pi(me(o))}}return n}i(Rc,"buildCaptureContext");import{mkdirSync as Tc,readFileSync as Fc,writeFileSync as Oc}from"fs";import{homedir as Uc}from"os";import{resolve as Qe}from"path";import{debuglog as _c}from"util";import{lt as Kc,parse as Ai}from"semver";var Lc="https://registry.npmjs.org/@cognite/cli/latest",Nc=1500,Di="upgrade-check.json",Ii=Qe(process.env.XDG_CACHE_HOME||Qe(Uc(),".cache"),"@cognite","cli"),Xt=_c("cognite-flows");function Mc(e,t){return!e||!t||!Ai(e)||!Ai(t)?!1:Kc(e,t)}i(Mc,"isOutdated");async function Hc({timeout:e=Nc,registryUrl:t=Lc,fetchImpl:n=globalThis.fetch}={}){if(typeof n!="function")return null;try{let r=await n(t,{signal:AbortSignal.timeout(e)});if(!r?.ok)return null;let o=await r.json();return typeof o?.version=="string"?o.version:null}catch(r){return Xt("fetchLatestVersion failed (%s): %O",t,r),null}}i(Hc,"fetchLatestVersion");function jc(e=Ii,t=864e5){try{let n=Fc(Qe(e,Di),"utf-8"),r=JSON.parse(n);return typeof r.latest!="string"||typeof r.fetchedAt!="number"||Date.now()-r.fetchedAt>t?null:{latest:r.latest,fetchedAt:r.fetchedAt}}catch(n){return Xt("readUpgradeCheckCache failed (%s): %O",e,n),null}}i(jc,"readUpgradeCheckCache");function Vc(e,t){try{Tc(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};Oc(Qe(e,Di),JSON.stringify(n))}catch(n){Xt("writeUpgradeCheckCache failed (%s): %O",e,n)}}i(Vc,"writeUpgradeCheckCache");async function Bc({cacheDir:e=Ii,...t}={}){let n=await Hc(t);n&&Vc(e,n)}i(Bc,"startBackgroundUpgradeCheck");function $i(e,{onOutdated:t,cacheDir:n,...r}={}){let o=jc(n);if(o){Mc(e,o.latest)&&t?.(e,o.latest);return}Bc({cacheDir:n,...r})}i($i,"preActionUpgradeCheck");import{default as Gh,chalkStderr as Ri}from"chalk";function Ti(e,t){let n=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],r=Math.max(...n.map(p=>[...p].length))+2,o="\u2500".repeat(r),s=i(p=>`\u2502 ${p}${" ".repeat(r-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${o}\u2510`,...n.map(s),`\u2514${o}\u2518`].join(`
192
+ `);return Ri.bold.yellow(a)}i(Ti,"formatUpgradeWarning");function qc(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}i(qc,"isDep0040Warning");var Qt=process,Jc=Qt.emit.bind(Qt);Qt.emit=function(e,...t){return e==="warning"&&qc(t[0])?!1:Jc(e,...t)};bi();var ue=new Yc;ue.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.7.1-alpha.1").showHelpAfterError().configureOutput({writeOut:i(e=>Gc(1,e),"writeOut")});ue.hook("preAction",()=>{$i("1.7.1-alpha.1",{onOutdated:i((e,t)=>{console.warn(`
193
+ ${Ti(e,t)}
194
+ `)},"onOutdated")})});oi(ue);fi(ue);var Oi=Me({packageName:"@cognite/cli",cliVersion:"1.7.1-alpha.1"}),Fi=xi({packageName:"@cognite/cli",cliVersion:"1.7.1-alpha.1"});vi(ue,Oi);var Zt=process.argv.slice(2);ue.parseAsync(Zt,{from:"user"}).catch(async e=>{await Ci(Oi,Zt),Wt(e)&&(console.error(`
195
+ Cancelled.`),process.exit(130)),(!(e instanceof u)||e.shouldReport)&&(await Fi.captureError(e,{command:Jt(Zt)}),await Fi.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof u&&(e.hint||e.helpUrl)&&(console.error(""),e.hint&&console.error(`\u{1F4A1} ${e.hint}`),e.helpUrl&&console.error(`\u{1F4DA} ${e.helpUrl}`)),process.exit(1)});
@@ -1,4 +1,5 @@
1
1
  import { CogniteClient, ClientOptions } from '@cognite/sdk';
2
+ import { inspect } from 'node:util';
2
3
 
3
4
  /**
4
5
  * App Hosting HTTP API layer.
@@ -168,6 +169,26 @@ type Authenticatable = Pick<CogniteClient, 'authenticate'>;
168
169
  declare function getSdk(deployment: Deployment, folder: string, env?: NodeJS.ProcessEnv): Promise<CogniteClient>;
169
170
  declare function getSdk<C extends Authenticatable>(deployment: Deployment, folder: string, env: NodeJS.ProcessEnv, createClient: (opts: ClientOptions) => C): Promise<C>;
170
171
 
172
+ /**
173
+ * Wraps a secret string so it cannot accidentally leak through string
174
+ * coercion, `JSON.stringify`, or `util.inspect` / `console.log`. The raw
175
+ * value is only accessible via {@link expose}, which should be called at
176
+ * trusted boundaries (crypto operations, HTTP headers, SDK init) and nowhere
177
+ * else.
178
+ */
179
+ declare class SensitiveString {
180
+ #private;
181
+ constructor(value: string);
182
+ toString(): string;
183
+ toJSON(): string;
184
+ /** Covers `util.inspect` and `console.log`. */
185
+ [inspect.custom](): string;
186
+ /** Returns the raw value. Only call this at a trusted boundary. */
187
+ expose(): string;
188
+ /** Creates a {@link SensitiveString} wrapping `value`. */
189
+ static from(value: string): SensitiveString;
190
+ }
191
+
171
192
  /**
172
193
  * Get access token for deployment using the appropriate identity provider.
173
194
  * Supports both CDF OAuth and Entra ID (Azure AD) authentication.
@@ -175,7 +196,7 @@ declare function getSdk<C extends Authenticatable>(deployment: Deployment, folde
175
196
  * Set COGNITE_TOKEN to skip OAuth entirely (useful when running the CLI
176
197
  * against a local mock server — see cli/testing/msw/standalone.ts).
177
198
  */
178
- declare const getToken: (deployment: Deployment, env?: NodeJS.ProcessEnv) => Promise<string>;
199
+ declare const getToken: (deployment: Deployment, env?: NodeJS.ProcessEnv) => Promise<SensitiveString>;
179
200
 
180
201
  /**
181
202
  * Sibling-file discovery for bundle signatures written by `cognite sign`.
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-EYFDM46K.js";export{a as AppHostingClient,b as ApplicationPackager,c as BUNDLE_DIR,j as SIGNATURE_SUFFIXES,d as bundleFileName,e as bundlePath,i as deploy,k as discoverSignatures,g as getSdk,f as getToken,h as packageAndUpload};
1
+ import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-74X2P7OO.js";export{a as AppHostingClient,b as ApplicationPackager,c as BUNDLE_DIR,j as SIGNATURE_SUFFIXES,d as bundleFileName,e as bundlePath,i as deploy,k as discoverSignatures,g as getSdk,f as getToken,h as packageAndUpload};
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export { App, AppHostingClient, ApplicationPackager, BUNDLE_DIR, Deployment, SIGNATURE_SUFFIXES, bundleFileName, bundlePath, deploy, discoverSignatures, getSdk, getToken, packageAndUpload } from './deploy/index.js';
2
2
  import '@cognite/sdk';
3
+ import 'node:util';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-EYFDM46K.js";export{o as AppHostingClient,r as ApplicationPackager,e as BUNDLE_DIR,b as SIGNATURE_SUFFIXES,f as bundleFileName,m as bundlePath,a as deploy,c as discoverSignatures,t as getSdk,p as getToken,x as packageAndUpload};
1
+ import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-74X2P7OO.js";export{o as AppHostingClient,r as ApplicationPackager,e as BUNDLE_DIR,b as SIGNATURE_SUFFIXES,f as bundleFileName,m as bundlePath,a as deploy,c as discoverSignatures,t as getSdk,p as getToken,x as packageAndUpload};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cognite/cli",
3
- "version": "1.6.0",
3
+ "version": "1.7.1-alpha.1",
4
4
  "description": "CLI for Cognite Data Fusion",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "author": "Cognite",
@@ -48,6 +48,7 @@
48
48
  "dependencies": {
49
49
  "@cognite/app-sdk": "^0.7.0",
50
50
  "@cognite/sdk": "^10.10.0",
51
+ "@napi-rs/keyring": "^1.3.0",
51
52
  "@sentry/node": "^10.51.0",
52
53
  "@zip.js/zip.js": "^2.7.0",
53
54
  "chalk": "^5.6.2",
@@ -92,7 +93,7 @@
92
93
  "react-dom": "^19.2.6",
93
94
  "tsup": "^8.4.0",
94
95
  "typescript": "^5.0.0",
95
- "vitest": "4.1.7"
96
+ "vitest": "4.1.8"
96
97
  },
97
98
  "engines": {
98
99
  "node": ">=20"
@@ -1,14 +0,0 @@
1
- var de=Object.defineProperty;var s=(n,e)=>de(n,"name",{value:e,configurable:!0});import{mkdir as qe,readFile as Ge}from"fs/promises";import{basename as Je,dirname as Ye}from"path";var N=class N extends Error{constructor(e,t={}){super(e),this.name="HintedError",t.cause!==void 0&&(this.cause=t.cause);let r=this.deriveDefaults(t);this.hint=t.hint??r.hint,this.helpUrl=t.helpUrl??r.helpUrl,this.shouldReport=t.shouldReport??!0}deriveDefaults(e){return{hint:fe(e.cause)}}};s(N,"HintedError");var u=N;var K="https://docs.cognite.com/cdf/access/",ue="https://status.cognite.com";function le(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:K};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:K};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:ue};default:return{}}}s(le,"defaultHintForStatus");var V=class V extends u{constructor(e,t){super(e,t),this.name="HintedHttpError",this.httpStatusCode=t.httpStatusCode,this.requestUrl=t.requestUrl,this.responseBody=t.responseBody}deriveDefaults(e){let{httpStatusCode:t}=e,r=le(t),i=super.deriveDefaults(e);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};s(V,"HintedHttpError");var S=V;function ge(n,e){if(n)switch(n){case"ENOTFOUND":return e.hostname?`DNS lookup failed for ${e.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return e.hostname&&e.port?`Connection refused by ${e.hostname}:${e.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return e.path?`Permission denied: ${e.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return e.path?`File or directory not found: ${e.path}.`:"File or directory not found.";case"EISDIR":return e.path?`Expected a file but found a directory: ${e.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return e.port?`Port ${e.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}s(ge,"hintForErrno");function fe(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,i=ge(r.code,r);if(i!==void 0)return i;e=r.cause}}s(fe,"hintForCause");var W="https://docs.cognite.com/cdf/access/";function g(n){return n!==null&&typeof n=="object"}s(g,"isRecord");function C(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}s(C,"isHttpError");function he(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
- See: ${W}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
3
- See: ${W}`;default:return}}s(he,"httpStatusHint");function m(n){let e=n instanceof Error?n:new Error(String(n));if(!C(e))return null;let t=he(e.status);return t?Object.assign(new Error(`${e.message}
4
- ${t}`),{cause:e}):null}s(m,"enrichedHttpError");function me(n){if(!g(n))return null;let e=n.missing;if(Array.isArray(e))return e;let t=n.data;if(g(t)){let r=t.error;if(g(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(t.missing))return t.missing}return null}s(me,"findMissingArray");function ye(n,e){if(!C(n)||n.status!==400)return!1;let t=me(n);return t?t.some(r=>g(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}s(ye,"isMissingExternalIdError");function b(n,e){return C(n)&&n.status===404||ye(n,e)}s(b,"isNotFoundError");var Z=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Q=["ACTIVE","PREVIEW"],O=class O extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};s(O,"AppVersionNotFoundError");var T=O,_=class _ extends Error{constructor(e){super(`App ${e} not found`),this.name="AppNotFoundError",this.appExternalId=e}};s(_,"AppNotFoundError");var R=_;function D(n,e){return n.includes(e)}s(D,"includesValue");function Ee(n){return D(Z,n)}s(Ee,"isAppVersionLifecycleState");function Ae(n){return D(Q,n)}s(Ae,"isAppVersionAlias");function we(n){return typeof n.version=="string"&&Ee(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||Ae(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}s(we,"isAppVersion");function X(n){if(!g(n)){let e=JSON.stringify(n)?.slice(0,200)??String(n);throw new Error(`Invalid version response: expected object, got ${e}`)}if(!we(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}s(X,"parseAppVersion");function Se(n){if(!g(n))throw new Error("Invalid app response: not an object");let{externalId:e,name:t,description:r}=n;if(typeof e!="string")throw new Error("Invalid app response: missing externalId");if(typeof t!="string")throw new Error("Invalid app response: missing name");if(r!=null&&typeof r!="string")throw new Error("Invalid app response: malformed description");return{externalId:e,name:t,description:typeof r=="string"?r:void 0}}s(Se,"parseAppMetadata");var F=class F{constructor(e){this.client=e}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(e,t,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:e,name:t,description:r}]}})}catch(i){throw m(i)??i}}async updateApps(e){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:e}})}catch(t){throw m(t)??t}}async getApp(e){let t=`${this.appsBasePath}/${encodeURIComponent(e)}`;try{let r=await this.client.get(t);return Se(r.data)}catch(r){throw b(r,[e])?new R(e):m(r)??r}}async uploadVersion(e,t,r,i,o="index.html"){console.log(`\u{1F4E4} Uploading version ${t}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),i),a.append("version",t),a.append("entryPath",o);let c=encodeURIComponent(e),p=`${this.appsBasePath}/${c}/versions`,d=await this.client.authenticate(),f=`${this.client.getBaseUrl()}${p}`,E=new AbortController,pe=setTimeout(()=>E.abort(),300*1e3),A;try{A=await fetch(f,{method:"POST",headers:{Authorization:`Bearer ${d}`},body:a,signal:E.signal})}catch(h){throw h instanceof Error&&h.name==="AbortError"?new u("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new u(`Failed to upload version to ${f}`,{cause:h,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(pe)}if(!A.ok){let h=await A.text(),w;try{w=JSON.parse(h)}catch{}let x=h;if(g(w)){let k=w.error;if(typeof k=="string")x=k;else if(g(k)){let v=k.message,z=k.code;x=typeof v=="string"?v:z!=null?`Unknown error (code: ${z})`:h}else{let v=w.message;x=typeof v=="string"?v:h}}let Y=A.headers.get("x-request-id"),ce=Y?` | X-Request-ID: ${Y}`:"";throw new S(`Upload failed: ${A.status} \u2014 ${x}${ce}`,{httpStatusCode:A.status,requestUrl:f,responseBody:g(w)?w:h})}console.log(`\u2705 Version ${t} uploaded`)}async getVersion(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/${i}`;try{let a=await this.client.get(o);return X(a.data)}catch(a){throw b(a,[e,t])?new T(e,t):m(a)??a}}async getActiveVersion(e){let t=encodeURIComponent(e),r=`${this.appsBasePath}/${t}/versions/list`;try{let i=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!g(i.data)||!Array.isArray(i.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:o}=i.data;if(o.length===0)return null;if(o.length>1)throw new Error(`Unexpected response: ${o.length} versions have the ACTIVE alias, expected at most 1`);return X(o[0])}catch(i){if(b(i,[e]))return null;throw m(i)??i}}async updateVersions(e,t){let r=encodeURIComponent(e),i=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(i,{data:{items:t}})}catch(o){throw m(o)??o}}async submitSignatures(e,t,r){let i=encodeURIComponent(e),o=encodeURIComponent(t),a=`${this.appsBasePath}/${i}/versions/${o}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(c){throw m(c)??c}}async listSignatures(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/${i}/signatures/list`;try{let a=await this.client.post(o,{data:{}});return Ce(a.data)}catch(a){throw m(a)??a}}};s(F,"AppHostingApi");var $=F,ke=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],ve=["developer","certifier"];function Ce(n){if(!g(n))throw new Error("Invalid signatures response: expected an object with an items array");let{items:e}=n;if(!Array.isArray(e))throw new Error("Invalid signatures response: items property is missing or not an array");return e.flatMap(t=>{let r=Ie(t);return r?[r]:[]})}s(Ce,"parseStoredSignatures");function Ie(n){if(!g(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:o,status:a}=n;return typeof e!="string"||e===""||!D(ve,t)||typeof r!="number"||typeof i!="number"||typeof o!="number"||!D(ke,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:o,status:a}}s(Ie,"parseStoredSignature");function Pe(n,e){let t=[];n.name!==e.name&&t.push({field:"name",remote:n.name,local:e.name});let r=n.description??"";return r!==e.description&&t.push({field:"description",remote:r,local:e.description}),t}s(Pe,"diffAppMetadata");function xe(n){let e=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:t,remote:r,local:i}of n){let o=`${t}:`.padEnd(14);e.push(` ${o}"${r}" \u2192 "${i}"`)}return e.join(`
5
- `)}s(xe,"formatMetadataDriftError");var L=class L{constructor(e){this.api=new $(e)}getVersion(e,t){return this.api.getVersion(e,t)}uploadVersion(e,t,r,i,o){return this.api.uploadVersion(e,t,r,i,o)}async ensureApp(e,t,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(e,t,r),console.log(`\u2705 App '${e}' created`)}catch(i){if(C(i)&&i.status===409){console.log(`\u2705 App '${e}' already exists`),await this.checkMetadataDrift(e,t,r);return}throw i}}async checkMetadataDrift(e,t,r){let i;try{i=await this.getApp(e)}catch{return}let o=Pe(i,{name:t,description:r});if(o.length!==0)throw new u(xe(o),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(e){return this.api.getApp(e)}async updateAppMetadata(e,t,r){await this.api.updateApps([{externalId:e,update:{name:{set:t},description:r?{set:r}:{setNull:!0}}}])}async submitSignatures(e,t,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${t}...`),await this.api.submitSignatures(e,t,r),console.log("\u2705 Signatures stored"))}listSignatures(e,t){return this.api.listSignatures(e,t)}async publishVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(e,t){console.log(`\u{1F680} Publishing and activating version ${t}...`),await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${t} is now PUBLISHED and ACTIVE`)}getActiveVersion(e){return this.api.getActiveVersion(e)}async deactivateVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{alias:{setNull:!0}}}])}async activateVersion(e,t){let r=null;try{r=await this.api.getActiveVersion(e)}catch{r=null}let i=r&&r.version!==t?r.version:void 0;return await this.api.updateVersions(e,[{version:t,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(e,t,r,i,o,a,c=!1){console.log(`
6
- \u{1F680} Deploying application via App Hosting API...
7
- `),await this.ensureApp(e,t,r),await this.uploadVersion(e,i,o,a),c&&await this.publishAndActivate(e,i),console.log(`
8
- \u2705 Deployment successful!`)}};s(L,"AppHostingClient");var I=L;import{execFileSync as U}from"child_process";import y from"fs";import l from"path";import{parseAndValidateManifestConfig as be}from"@cognite/app-sdk/vite";import{BlobReader as Te,Uint8ArrayWriter as Re,ZipWriter as De}from"@zip.js/zip.js";var H="package.json",B="package-lock.json",ee="manifest.json",M=".cognite",$e=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],j=class j{constructor(e="dist"){this.distPath=l.isAbsolute(e)?e:l.join(process.cwd(),e),this.appRoot=l.dirname(this.distPath)}validateBuildDirectory(){if(!y.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=l.join(this.appRoot,H);if(!y.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=l.join(this.appRoot,B);if(!y.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`)}async createZip(e="app.zip",t=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new De(new Re,{level:9}),i=s(async(p,d)=>{await r.add(d,new Te(await y.openAsBlob(p))),t&&console.log(` \u{1F4C4} ${d}`)},"addFile"),o=s(async p=>{let d=await y.promises.readdir(p,{withFileTypes:!0});for(let f of d){let E=l.join(p,f.name);f.isDirectory()?await o(E):await i(E,l.relative(this.distPath,E).replace(/\\/g,"/"))}},"addDir"),a;try{await o(this.distPath);let p=l.join(this.appRoot,H);await i(p,l.posix.join(M,H));let d=l.join(this.appRoot,ee);if(y.existsSync(d)){let E=y.readFileSync(d,"utf-8");be(E,d),await i(d,l.posix.join(M,ee))}let f=l.join(this.appRoot,B);await i(f,l.posix.join(M,B)),a=await r.close()}catch(p){let d=p instanceof Error?p.message:String(p);throw new Error(`Failed to create zip: ${d}`)}try{await y.promises.writeFile(e,a)}catch(p){throw new u(`Failed to write bundle to ${e}`,{cause:p})}let c=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${c} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=U("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(p){throw p instanceof Error&&"code"in p&&p.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=U("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=r?r.replace(/\/$/,""):".",o=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(t,o);try{U("git",["-C",t,"archive","--format=zip",`--output=${e}`,o])}catch(p){let d=p instanceof Error?p.message:String(p);throw new Error(`Failed to create source archive: ${d}`)}let c=(y.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${l.basename(e)} (${c} MB)`),e}validateNoSensitiveFiles(e,t){let r=U("git",["-C",e,"ls-tree","-r","--name-only",t],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
9
- `).filter(Boolean),i=s(a=>a.split("/").some(c=>$e.some(p=>p.test(c))),"isSensitive"),o=r.filter(i);if(o.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
10
- `+o.map(a=>` ${a}`).join(`
11
- `)+`
12
- Hint: git rm --cached <file>`)}};s(j,"ApplicationPackager");var P=j;import Ue from"path";var te=".cognite-bundles";function ne(n,e){return`${n}-${e}.zip`}s(ne,"bundleFileName");function q(n,e,t){return Ue.join(n,te,ne(e,t))}s(q,"bundlePath");import{CogniteClient as je}from"@cognite/sdk";function Ne(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}s(Ne,"exponentialBackoffWithJitter");function Ve(n){return new Promise(e=>setTimeout(e,n))}s(Ve,"sleep");async function re(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),i=e.delayInMsCalculator??Ne;if(t<1)throw new Error("`maxAttempts` must be 1 or greater");if(t>100)throw new Error("`maxAttempts` must be 100 or less");let o=1;for(;;)try{return await n()}catch(a){if(o>=t||!r(a))throw a;let c=i(o);e.onAttemptFail?.(a,o,c),await Ve(c),o++}}s(re,"retryAsync");var Oe="https://auth.cognite.com/oauth2/token",_e=s(n=>typeof n=="object"&&n!==null&&"access_token"in n&&typeof n.access_token=="string","hasAccessToken");async function ie({idp:n,tokenUrl:e,init:t,missingTokenHint:r}){let i;try{i=await re(()=>fetch(e,t),{maxAttempts:3})}catch(c){throw new u(`Failed to fetch access token from ${e}`,{cause:c})}if(!i.ok){let c=await i.text();throw new S(`Failed to get token from ${n}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:e,responseBody:c})}let o=await i.text(),a;try{a=JSON.parse(o)}catch{throw new u(`Unexpected response from ${n} authentication (invalid JSON):
13
- ${o}`,{hint:r})}if(!_e(a))throw new u(`No access token in ${n} authentication response:
14
- ${o}`,{hint:r});return a.access_token}s(ie,"fetchOAuthToken");var Fe=s(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let e=JSON.parse(n),t={};for(let[r,i]of Object.entries(e))if(typeof i=="string"){let o=r.toLowerCase().replace(/_/g,"-");t[o]=i}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),Le=s(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=Fe()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return e},"getSecretFromEnv"),He=s((n,e)=>ie({idp:"CDF",tokenUrl:Oe,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${n}:${e}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."}),"getTokenCdf"),oe=s(({idp:n,tokenUrl:e,clientId:t,clientSecret:r,scopes:i,missingTokenHint:o})=>ie({idp:n,tokenUrl:e,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:t,client_secret:r,grant_type:"client_credentials",...i!==void 0?{scope:i.join(" ")}:{}})},missingTokenHint:o}),"getTokenWithClientCredentials"),Be=s((n,e)=>{if(e!==void 0)return e.join(" ");if(!n)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(n).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${n}`)}},"resolveEntraScope"),Me=s((n,e,t,r,i)=>oe({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,clientId:n,clientSecret:e,scopes:i!==void 0?i:[Be(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),G=s(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return e.COGNITE_TOKEN;let{deployClientId:t,deploySecretName:r,idpType:i="cdf",tenantId:o,baseUrl:a,scopes:c,tokenUrl:p}=n,d=Le(r);if(i==="oauth"){if(!p)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return oe({idp:"OAuth",tokenUrl:p,clientId:t,clientSecret:d,scopes:c,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!o)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Me(t,d,o,a,c)}return He(t,d)},"getToken");async function J(n,e,t=process.env,r){let i=await G(n,t),o=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(c=>new je(c)))({appId:e,project:n.project,baseUrl:o,oidcTokenProvider:s(async()=>i,"oidcTokenProvider")});return await a.authenticate(),a}s(J,"getSdk");async function se(n,e,t,r){let{externalId:i,name:o,description:a,versionTag:c}=e,p=q(t,i,c);await qe(Ye(p),{recursive:!0}),await new P(`${t}/dist`).createZip(p,!0);let d;try{d=await Ge(p)}catch(f){throw new u(`Failed to read bundle file: ${p}`,{cause:f})}await new I(n).deploy(i,o,a,c,d,Je(p),r)}s(se,"packageAndUpload");var ze=s(async(n,e,t)=>{let r=await J(n,t);await se(r,e,t,n.published)},"deploy");import{existsSync as Ke,readFileSync as We}from"fs";var ae=[".dev.sig",".cert.sig"];function Xe(n,e={}){let t=e.existsSync??Ke,r=e.readFileSync??((o,a)=>We(o,a)),i=[];for(let o of ae){let a=`${n}${o}`;if(!t(a))continue;let c=r(a,"utf8").trim();c.length>0&&i.push(c)}return i}s(Xe,"discoverSignatures");export{I as a,P as b,te as c,ne as d,q as e,G as f,J as g,se as h,ze as i,ae as j,Xe as k};