@cognite/cli 1.1.0-alpha.50 → 1.1.0-alpha.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import{a as o,e as Lt}from"../chunk-A5ASLC6T.js";import{writeSync as fp}from"fs";import{Command as yp}from"commander";var Ot="https://docs.cognite.com/cdf/access/";function j(e){return e!==null&&typeof e=="object"}o(j,"isRecord");function pe(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(pe,"isHttpError");function no(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
3
- See: ${Ot}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
4
- See: ${Ot}`;default:return}}o(no,"httpStatusHint");function ee(e){let t=e instanceof Error?e:new Error(String(e));if(!pe(t))return null;let n=no(t.status);return n?Object.assign(new Error(`${t.message}
5
- ${n}`),{cause:t}):null}o(ee,"enrichedHttpError");function ro(e){if(!j(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(j(n)){let r=n.error;if(j(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}o(ro,"findMissingArray");function oo(e,t){if(!pe(e)||e.status!==400)return!1;let n=ro(e);return n?n.some(r=>j(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}o(oo,"isMissingExternalIdError");function Ke(e,t){return pe(e)&&e.status===404||oo(e,t)}o(Ke,"isNotFoundError");var _t=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],jt=["ACTIVE","PREVIEW"],Ge=class Ge extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};o(Ge,"AppVersionNotFoundError");var F=Ge;function Mt(e,t){return e.includes(t)}o(Mt,"includesValue");function io(e){return Mt(_t,e)}o(io,"isAppVersionLifecycleState");function so(e){return Mt(jt,e)}o(so,"isAppVersionAlias");function ao(e){return typeof e.version=="string"&&io(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||so(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(ao,"isAppVersion");function Nt(e){if(!j(e))throw new Error("Invalid version response: not an object");if(!ao(e))throw new Error("Invalid version response: missing or malformed fields");return e}o(Nt,"parseAppVersion");var He=class He{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 ee(i)??i}}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`,d=await this.client.authenticate(),l=`${this.client.getBaseUrl()}${c}`,m=new AbortController,g=setTimeout(()=>m.abort(),300*1e3),f;try{f=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${d}`},body:a,signal:m.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new Error("Upload timed out after 5 minutes"):y}finally{clearTimeout(g)}if(!f.ok){let y=await f.text(),w=y;try{let C=JSON.parse(y);if(j(C)){let k=C.error;if(typeof k=="string")w=k;else if(j(k)){let T=k.message,x=k.code;w=typeof T=="string"?T:x!=null?`Unknown error (code: ${x})`:y}else{let T=C.message;w=typeof T=="string"?T:y}}}catch{}let u=f.headers.get("x-request-id"),h=u?` | X-Request-ID: ${u}`:"",S=Object.assign(new Error(`Upload failed: ${f.status} \u2014 ${w}${h}`),{status:f.status});throw ee(S)??S}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 Nt(a.data)}catch(a){throw Ke(a,[t,n])?new F(t,n):ee(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/active`;try{let i=await this.client.get(r);return Nt(i.data)}catch(i){if(Ke(i,[t]))return null;throw ee(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 ee(s)??s}}};o(He,"AppHostingApi");var xe=He;var Be=class Be{constructor(t){this.api=new xe(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(pe(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw i}}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`)}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(`
2
+ import{a as o,e as Ut}from"../chunk-VTE66IK5.js";import{writeSync as $p}from"fs";import{Command as Tp}from"commander";var Kt="https://docs.cognite.com/cdf/access/";function U(e){return e!==null&&typeof e=="object"}o(U,"isRecord");function de(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(de,"isHttpError");function go(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
3
+ See: ${Kt}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
4
+ See: ${Kt}`;default:return}}o(go,"httpStatusHint");function ne(e){let t=e instanceof Error?e:new Error(String(e));if(!de(t))return null;let n=go(t.status);return n?Object.assign(new Error(`${t.message}
5
+ ${n}`),{cause:t}):null}o(ne,"enrichedHttpError");function fo(e){if(!U(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(U(n)){let r=n.error;if(U(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}o(fo,"findMissingArray");function yo(e,t){if(!de(e)||e.status!==400)return!1;let n=fo(e);return n?n.some(r=>U(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}o(yo,"isMissingExternalIdError");function Ye(e,t){return de(e)&&e.status===404||yo(e,t)}o(Ye,"isNotFoundError");var Ht=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Bt=["ACTIVE","PREVIEW"],ze=class ze extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};o(ze,"AppVersionNotFoundError");var L=ze;function qt(e,t){return e.includes(t)}o(qt,"includesValue");function ho(e){return qt(Ht,e)}o(ho,"isAppVersionLifecycleState");function wo(e){return qt(Bt,e)}o(wo,"isAppVersionAlias");function So(e){return typeof e.version=="string"&&ho(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||wo(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(So,"isAppVersion");function Gt(e){if(!U(e))throw new Error("Invalid version response: not an object");if(!So(e))throw new Error("Invalid version response: missing or malformed fields");return e}o(Gt,"parseAppVersion");var We=class We{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 ne(i)??i}}async uploadVersion(t,n,r,i,a="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let s=new FormData;s.append("file",new Blob([new Uint8Array(r)]),i),s.append("version",n),s.append("entryPath",a);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,d=await this.client.authenticate(),l=`${this.client.getBaseUrl()}${c}`,m=new AbortController,g=setTimeout(()=>m.abort(),300*1e3),f;try{f=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${d}`},body:s,signal:m.signal})}catch(h){throw h instanceof Error&&h.name==="AbortError"?new Error("Upload timed out after 5 minutes"):h}finally{clearTimeout(g)}if(!f.ok){let h=await f.text(),w=h;try{let v=JSON.parse(h);if(U(v)){let x=v.error;if(typeof x=="string")w=x;else if(U(x)){let b=x.message,C=x.code;w=typeof b=="string"?b:C!=null?`Unknown error (code: ${C})`:h}else{let b=v.message;w=typeof b=="string"?b:h}}}catch{}let u=f.headers.get("x-request-id"),y=u?` | X-Request-ID: ${u}`:"",S=Object.assign(new Error(`Upload failed: ${f.status} \u2014 ${w}${y}`),{status:f.status});throw ne(S)??S}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),i=encodeURIComponent(n),a=`${this.appsBasePath}/${r}/versions/${i}`;try{let s=await this.client.get(a);return Gt(s.data)}catch(s){throw Ye(s,[t,n])?new L(t,n):ne(s)??s}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/active`;try{let i=await this.client.get(r);return Gt(i.data)}catch(i){if(Ye(i,[t]))return null;throw ne(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(a){throw ne(a)??a}}};o(We,"AppHostingApi");var Pe=We;var Xe=class Xe{constructor(t){this.api=new Pe(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,i,a){return this.api.uploadVersion(t,n,r,i,a)}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(de(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw i}}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,a,s,p=!1){console.log(`
6
6
  \u{1F680} Deploying application via App Hosting API...
7
- `);try{await this.ensureApp(t,n,r),await this.uploadVersion(t,i,s,a),p&&await this.publishAndActivate(t,i),console.log(`
8
- \u2705 Deployment successful!`)}catch(c){let d=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${d}`),{cause:c})}}};o(Be,"AppHostingClient");var E=Be;import{existsSync as So,readFileSync as Co}from"fs";import{resolve as xo}from"path";import{array as po,boolean as co,check as Vt,forward as Ut,literal as lo,maxLength as mo,minLength as uo,nonEmpty as te,object as Kt,optional as B,picklist as go,pipe as M,safeParse as fo,string as L,url as yo}from"valibot";var qe=M(L(),te("must not be empty")),Qe=M(L(),te("must not be empty"),mo(256,"must be 256 characters or fewer")),Je=M(L(),te("must not be empty"),yo("must be a valid URL")),Ye=M(L(),te("must not be empty")),ze=M(L(),te("must not be empty")),ho=M(Kt({org:Ye,project:ze,baseUrl:Je,deployClientId:B(L(),""),deploySecretName:B(L(),""),published:B(co(),!1),idpType:B(go(["cdf","entra_id"]),"cdf"),tenantId:B(L())}),Ut(Vt(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),Ut(Vt(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),wo=Kt({name:qe,externalId:Qe,versionTag:M(L(),te("must not be empty")),description:B(L(),""),deployments:M(po(ho),uo(1,"must contain at least one deployment")),infra:B(lo("appsApi"))});function We(e){let t=fo(wo,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(We,"validateAppConfig");function v(e,t={}){let{validator:n=We,existsSync:r=So,readFileSync:i=Co}=t,s=xo(e,"app.json");if(!r(s))throw new Error("No app.json found in current directory. 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");import{CogniteClient as Bo}from"@cognite/sdk";import{CogniteClient as Io}from"@cognite/sdk";var vo=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"),ko=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=vo()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),Eo=o(e=>{if(!e)return"";try{return new URL(e).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=e.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),bo=o(async(e,t)=>{let n=`Basic ${btoa(`${e}:${t}`)}`,r=await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:n,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})});if(!r.ok){let s=await r.text();throw new Error(`Failed to get token from CDF: ${r.status} ${r.statusText}
9
- ${s}`)}let i=await r.json();if(!i.access_token)throw new Error("No access token returned from CDF authentication");return i.access_token},"getTokenCdf"),Po=o(async(e,t,n,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let i=Eo(r);if(!i)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${r}`);let s=`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,a=`https://${i}.cognitedata.com/.default`,p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,client_secret:t,scope:a,grant_type:"client_credentials"})});if(!p.ok){let d=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
10
- ${d}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),ce=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}=e,p=ko(r);if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Po(n,p,s,a)}return bo(n,p)},"getToken");async function le(e,t,n=process.env,r){let i=await ce(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new Io(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i,"oidcTokenProvider")});return await a.authenticate(),a}o(le,"getSdk");import Lo from"os";import Oo from"path";import No from"open";import{buildAuthorizationUrl as _o,calculatePKCECodeChallenge as jo,discovery as Mo,None as Vo,randomPKCECodeVerifier as Uo,randomState as Ko}from"openid-client";import Ao from"https";import{authorizationCodeGrant as $o}from"openid-client";function Gt(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}o(Gt,"escapeHtml");function Xe(e,t,n){let r=Gt(t),i=Gt(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
7
+ `);try{await this.ensureApp(t,n,r),await this.uploadVersion(t,i,a,s),p&&await this.publishAndActivate(t,i),console.log(`
8
+ \u2705 Deployment successful!`)}catch(c){let d=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${d}`),{cause:c})}}};o(Xe,"AppHostingClient");var E=Xe;import{existsSync as $o,readFileSync as To}from"fs";import{resolve as Ro}from"path";import{array as vo,boolean as Co,check as Qt,forward as Jt,literal as xo,maxLength as ko,minLength as Eo,nonEmpty as re,object as Yt,optional as J,picklist as bo,pipe as K,safeParse as Po,string as N,url as Ao}from"valibot";var Ze=K(N(),re("must not be empty")),et=K(N(),re("must not be empty"),ko(256,"must be 256 characters or fewer")),tt=K(N(),re("must not be empty"),Ao("must be a valid URL")),nt=K(N(),re("must not be empty")),rt=K(N(),re("must not be empty")),Io=K(Yt({org:nt,project:rt,baseUrl:tt,deployClientId:J(N(),""),deploySecretName:J(N(),""),published:J(Co(),!1),idpType:J(bo(["cdf","entra_id"]),"cdf"),tenantId:J(N())}),Jt(Qt(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),Jt(Qt(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),Do=Yt({name:Ze,externalId:et,versionTag:K(N(),re("must not be empty")),description:J(N(),""),deployments:K(vo(Io),Eo(1,"must contain at least one deployment")),infra:J(xo("appsApi"))});function ot(e){let t=Po(Do,e);if(t.success)return t.output;let n=t.issues[0],r=n.path?.map(a=>a.key).join(".")??"",i=r?`"${r}" `:"";throw new Error(`app.json: ${i}${n.message}`)}o(ot,"validateAppConfig");function k(e,t={}){let{validator:n=ot,existsSync:r=$o,readFileSync:i=To}=t,a=Ro(e,"app.json");if(!r(a))throw new Error("No app.json found in current directory. Make sure you're running this command from your app's root directory.");let s=i(a,"utf-8"),p;try{p=JSON.parse(s)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return n(p)}o(k,"loadAppConfig");import{CogniteClient as ni}from"@cognite/sdk";import{CogniteClient as _o}from"@cognite/sdk";var Fo=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 a=r.toLowerCase().replace(/_/g,"-");n[a]=i}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),Oo=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=Fo()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),Lo=o(e=>{if(!e)return"";try{return new URL(e).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=e.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),No=o(async(e,t)=>{let n=`Basic ${btoa(`${e}:${t}`)}`,r=await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:n,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})});if(!r.ok){let a=await r.text();throw new Error(`Failed to get token from CDF: ${r.status} ${r.statusText}
9
+ ${a}`)}let i=await r.json();if(!i.access_token)throw new Error("No access token returned from CDF authentication");return i.access_token},"getTokenCdf"),jo=o(async(e,t,n,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let i=Lo(r);if(!i)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${r}`);let a=`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,s=`https://${i}.cognitedata.com/.default`,p=await fetch(a,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,client_secret:t,scope:s,grant_type:"client_credentials"})});if(!p.ok){let d=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
10
+ ${d}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),me=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:n,deploySecretName:r,idpType:i="cdf",tenantId:a,baseUrl:s}=e,p=Oo(r);if(i==="entra_id"){if(!a)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return jo(n,p,a,s)}return No(n,p)},"getToken");async function ue(e,t,n=process.env,r){let i=await me(e,n),a=n.COGNITE_BASE_URL??e.baseUrl,s=(r??(p=>new _o(p)))({appId:t,project:e.project,baseUrl:a,oidcTokenProvider:o(async()=>i,"oidcTokenProvider")});return await s.authenticate(),s}o(ue,"getSdk");import Bo from"os";import qo from"path";import Qo from"open";import{buildAuthorizationUrl as Jo,calculatePKCECodeChallenge as Yo,discovery as zo,None as Wo,randomPKCECodeVerifier as Xo,randomState as Zo}from"openid-client";import Mo from"https";import{authorizationCodeGrant as Vo}from"openid-client";function zt(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}o(zt,"escapeHtml");function it(e,t,n){let r=zt(t),i=zt(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
11
11
  <h1>${r}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
12
12
  @keyframes checkmark {
13
13
  0% { transform: scale(0); }
@@ -16,28 +16,28 @@ ${d}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token
16
16
  }
17
17
  h1 { animation: checkmark 0.5s ease-out; }
18
18
  </style>`:""}
19
- </body></html>`}o(Xe,"generateHtml");async function Do(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(Xe("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(Xe("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(Do,"handleCallback");function To(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}o(To,"formatTimeoutMinutes");function Ht(e,t,n,r,i,s={createServer:Ao.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:$o}){return new Promise((a,p)=>{let c,d=s.setTimeout(()=>{c?.close(),p(new Error(`Login timeout - no response received within ${To(e.loginTimeout)}`))},e.loginTimeout);c=s.createServer(t,async(l,m)=>{try{let g=await Do(l,m,n,r,i,s);g.shouldClose&&(s.clearTimeout(d),c?.close(),g.error?p(g.error):g.tokens?a(g.tokens):p(new Error("No tokens received")))}catch(g){s.clearTimeout(d),c?.close(),p(g instanceof Error?g:new Error(String(g)))}}),c.on("error",l=>{s.clearTimeout(d),l.code==="EADDRINUSE"?console.error(`\u274C Port ${e.port} is already in use.`):console.error(`\u274C Server error: ${l.message}`),p(l)}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}o(Ht,"startCallbackServer");import{execFileSync as Ro}from"child_process";import Ze from"fs";import Bt from"path";function qt(e,t,n){return{key:n.readFileSync(e),cert:n.readFileSync(t)}}o(qt,"loadCertificates");function Fo(e,t,n,r){console.log("\u{1F510} Generating self-signed certificate for HTTPS..."),r.existsSync(e)||r.mkdirSync(e,{recursive:!0});try{return r.execFileSync("openssl",["req","-x509","-newkey","rsa:2048","-nodes","-sha256","-subj","/CN=localhost","-keyout",t,"-out",n,"-days","365"],{stdio:["ignore","pipe","ignore"]}),console.log("\u2705 Certificate generated and saved locally"),qt(t,n,r)}catch{throw new Error(`Failed to generate self-signed certificate. Make sure openssl is installed.
19
+ </body></html>`}o(it,"generateHtml");async function Uo(e,t,n,r,i,a){let s=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(s.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await a.authorizationCodeGrant(n,s,{pkceCodeVerifier:r,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(it("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(it("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(Uo,"handleCallback");function Ko(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}o(Ko,"formatTimeoutMinutes");function Wt(e,t,n,r,i,a={createServer:Mo.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:Vo}){return new Promise((s,p)=>{let c,d=a.setTimeout(()=>{c?.close(),p(new Error(`Login timeout - no response received within ${Ko(e.loginTimeout)}`))},e.loginTimeout);c=a.createServer(t,async(l,m)=>{try{let g=await Uo(l,m,n,r,i,a);g.shouldClose&&(a.clearTimeout(d),c?.close(),g.error?p(g.error):g.tokens?s(g.tokens):p(new Error("No tokens received")))}catch(g){a.clearTimeout(d),c?.close(),p(g instanceof Error?g:new Error(String(g)))}}),c.on("error",l=>{a.clearTimeout(d),l.code==="EADDRINUSE"?console.error(`\u274C Port ${e.port} is already in use.`):console.error(`\u274C Server error: ${l.message}`),p(l)}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}o(Wt,"startCallbackServer");import{execFileSync as Go}from"child_process";import st from"fs";import Xt from"path";function Zt(e,t,n){return{key:n.readFileSync(e),cert:n.readFileSync(t)}}o(Zt,"loadCertificates");function Ho(e,t,n,r){console.log("\u{1F510} Generating self-signed certificate for HTTPS..."),r.existsSync(e)||r.mkdirSync(e,{recursive:!0});try{return r.execFileSync("openssl",["req","-x509","-newkey","rsa:2048","-nodes","-sha256","-subj","/CN=localhost","-keyout",t,"-out",n,"-days","365"],{stdio:["ignore","pipe","ignore"]}),console.log("\u2705 Certificate generated and saved locally"),Zt(t,n,r)}catch{throw new Error(`Failed to generate self-signed certificate. Make sure openssl is installed.
20
20
  On macOS: openssl is pre-installed
21
21
  On Linux: sudo apt-get install openssl
22
- On Windows: Install OpenSSL or use WSL`)}}o(Fo,"generateCertificate");function Qt(e,t={existsSync:Ze.existsSync,readFileSync:o(n=>Ze.readFileSync(n),"readFileSync"),mkdirSync:o((n,r)=>{Ze.mkdirSync(n,r)},"mkdirSync"),execFileSync:Ro}){let n=Bt.join(e,"localhost-key.pem"),r=Bt.join(e,"localhost-cert.pem");return t.existsSync(n)&&t.existsSync(r)?qt(n,r,t):Fo(e,n,r,t)}o(Qt,"getOrCreateCertificates");var Go={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:Oo.join(Lo.homedir(),".cdf-login")},Ho={open:No,getOrCreateCertificates:Qt,startCallbackServer:Ht,discovery:Mo,buildAuthorizationUrl:_o,randomPKCECodeVerifier:Uo,calculatePKCECodeChallenge:jo,randomState:Ko,logger:console};async function ve(e,t=Go,n){return n===void 0?Jt(e,t,Ho):Jt(e,t,n)}o(ve,"login");async function Jt(e,t,n){n.logger.log(`\u{1F510} Starting CDF login flow...
23
- `),n.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let r=await n.discovery(new URL(t.authority),t.clientId,void 0,Vo()),i=n.randomPKCECodeVerifier(),s=await n.calculatePKCECodeChallenge(i),a=n.randomState(),p={redirect_uri:t.redirectUri,scope:"openid profile email",code_challenge:s,code_challenge_method:"S256",state:a};e&&(p.organization_hint=e);let c=n.buildAuthorizationUrl(r,p).toString(),d=n.getOrCreateCertificates(t.certDir);e&&n.logger.log(`\u{1F3E2} Organization: ${e}`),n.logger.log(`\u{1F680} Opening browser for authentication...
22
+ On Windows: Install OpenSSL or use WSL`)}}o(Ho,"generateCertificate");function en(e,t={existsSync:st.existsSync,readFileSync:o(n=>st.readFileSync(n),"readFileSync"),mkdirSync:o((n,r)=>{st.mkdirSync(n,r)},"mkdirSync"),execFileSync:Go}){let n=Xt.join(e,"localhost-key.pem"),r=Xt.join(e,"localhost-cert.pem");return t.existsSync(n)&&t.existsSync(r)?Zt(n,r,t):Ho(e,n,r,t)}o(en,"getOrCreateCertificates");var ei={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:qo.join(Bo.homedir(),".cdf-login")},ti={open:Qo,getOrCreateCertificates:en,startCallbackServer:Wt,discovery:zo,buildAuthorizationUrl:Jo,randomPKCECodeVerifier:Xo,calculatePKCECodeChallenge:Yo,randomState:Zo,logger:console};async function Ae(e,t=ei,n){return n===void 0?tn(e,t,ti):tn(e,t,n)}o(Ae,"login");async function tn(e,t,n){n.logger.log(`\u{1F510} Starting CDF login flow...
23
+ `),n.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let r=await n.discovery(new URL(t.authority),t.clientId,void 0,Wo()),i=n.randomPKCECodeVerifier(),a=await n.calculatePKCECodeChallenge(i),s=n.randomState(),p={redirect_uri:t.redirectUri,scope:"openid profile email",code_challenge:a,code_challenge_method:"S256",state:s};e&&(p.organization_hint=e);let c=n.buildAuthorizationUrl(r,p).toString(),d=n.getOrCreateCertificates(t.certDir);e&&n.logger.log(`\u{1F3E2} Organization: ${e}`),n.logger.log(`\u{1F680} Opening browser for authentication...
24
24
  `);try{await n.open(c)}catch(l){let m=l instanceof Error?l.message:String(l);n.logger.error("\u274C Failed to open browser automatically."),n.logger.error(` Reason: ${m}`),n.logger.error(`Please open this URL manually:
25
- `),n.logger.error(c),n.logger.error("")}return n.startCallbackServer(t,d,r,i,a)}o(Jt,"loginImpl");async function V(e,t,n={}){let{login:r=ve,getSdk:i=le,createClient:s=o(a=>new Bo(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(V,"getClientForDeployment");import Yt from"enquirer";var zt="Enter custom target...";function Wt(e,t){let n=t.map((r,i)=>` ${i}: ${r.org}/${r.project}`).join(`
25
+ `),n.logger.error(c),n.logger.error("")}return n.startCallbackServer(t,d,r,i,s)}o(tn,"loginImpl");async function j(e,t,n={}){let{login:r=Ae,getSdk:i=ue,createClient:a=o(s=>new ni(s),"createClient")}=n;if(t.interactive){let s=t.orgHint||e.org||void 0,p=await r(s),c=a({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(j,"getClientForDeployment");import nn from"enquirer";var rn="Enter custom target...";function on(e,t){let n=t.map((r,i)=>` ${i}: ${r.org}/${r.project}`).join(`
26
26
  `);throw new Error(`Deployment "${e}" not found. Available deployments:
27
- ${n}`)}o(Wt,"deploymentNotFoundError");function N(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;Wt(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;Wt(t,e)}o(N,"findDeployment");function O(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o(O,"getMissingCredentials");async function U(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 N(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),zt],{selected:r}=await Yt.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==zt){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 Yt.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(U,"resolveDeployment");import{existsSync as qo}from"fs";import{resolve as Qo}from"path";import{config as Jo}from"dotenv";function $(e,t={existsSync:qo,config:Jo}){let n=Qo(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}o($,"loadEnvFile");function K(e){e.infra!=="appsApi"&&(console.error(`
27
+ ${n}`)}o(on,"deploymentNotFoundError");function F(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;on(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;on(t,e)}o(F,"findDeployment");function T(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o(T,"getMissingCredentials");async function _(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 F(e.deployments,t.deployment);let n=[...e.deployments.map(a=>`${a.org}/${a.project}`),rn],{selected:r}=await nn.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==rn){let a=e.deployments.find(s=>`${s.org}/${s.project}`===r);if(a)return a;throw new Error(`Deployment "${r}" could not be resolved from app.json.`)}let i=await nn.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:o(a=>a?!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(_,"resolveDeployment");import{existsSync as ri}from"fs";import{resolve as oi}from"path";import{config as ii}from"dotenv";function P(e,t={existsSync:ri,config:ii}){let n=oi(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}o(P,"loadEnvFile");function M(e){e.infra!=="appsApi"&&(console.error(`
28
28
  \u26A0\uFE0F Legacy infrastructure is no longer supported.
29
29
 
30
30
  Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
31
31
  the old CDF Application Registry. This deploy path has been removed.
32
32
 
33
33
  To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
34
- `),process.exit(1))}o(K,"assertAppHostingInfra");async function Yo(e){let t=process.cwd();$(t);let n=v(t);K(n);let r=e.interactive?await U(n,e):N(n.deployments,e.deployment);if(!e.interactive){let l=O(r);if(l.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${l.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let i=await V(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(l){throw l instanceof F?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):l}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:d}=await s.activateVersion(a,p);console.log(`\u2713 Activated ${a} @ ${p} is now ACTIVE`),d&&console.log(` Superseded ${d} \u2192 PUBLISHED`)}o(Yo,"handleActivate");function Xt(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",`
34
+ `),process.exit(1))}o(M,"assertAppHostingInfra");async function si(e){let t=process.cwd();P(t);let n=k(t);M(n);let r=e.interactive?await _(n,e):F(n.deployments,e.deployment);if(!e.interactive){let l=T(r);if(l.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${l.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let i=await j(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),a=new E(i),{externalId:s,versionTag:p}=n,c;try{c=await a.getVersion(s,p)}catch(l){throw l instanceof L?new Error(`Version ${p} of ${s} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):l}if(c.alias==="ACTIVE"){console.log(` ${s} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${s} @ ${p}: version is ${c.lifecycleState} (terminal).`);c.lifecycleState==="DRAFT"&&(await a.publishVersion(s,p),console.log(`\u2713 Published ${s} @ ${p} is now PUBLISHED`));let{supersededVersion:d}=await a.activateVersion(s,p);console.log(`\u2713 Activated ${s} @ ${p} is now ACTIVE`),d&&console.log(` Superseded ${d} \u2192 PUBLISHED`)}o(si,"handleActivate");function sn(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",`
35
35
  Examples:
36
36
  npx @cognite/cli apps activate . Activate using env-var auth
37
- npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>Yo(n))}o(Xt,"registerActivateCommand");import{readdirSync as pi}from"fs";import{basename as un,dirname as ci,normalize as li,resolve as me}from"path";import{fileURLToPath as di,pathToFileURL as mi}from"url";import{Logger as ui,runner as gi}from"hygen";import{safeParse as zo}from"valibot";function de(e,t){return n=>{let r=zo(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}o(de,"toPromptValidator");var Zt={name:de("App name",Qe),displayName:de("Display name",qe),baseUrl:de("Base URL",Je),org:de("Org",Ye),project:de("Project",ze)};function Wo(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}o(Wo,"composeValidators");function ke(e){return e.map(t=>{if(!(t.name in Zt))return t;let n=Zt[t.name];return{...t,validate:Wo(t.validate,n)}})}o(ke,"applySchemaValidators");import{execFileSync as Ee}from"child_process";function en(e={}){let{execFileSync:t=Ee}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(en,"isGitInstalled");function tn(e,t={}){let{execFileSync:n=Ee}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(tn,"isInsideGitRepo");function nn(e,t={}){let{execFileSync:n=Ee}=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(nn,"gitInitAndCommit");function rn(e={}){let{execFileSync:t=Ee}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(rn,"gitUserEmail");import{basename as sn}from"path";import an from"enquirer";function on(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(on,"kebabCase");var Xo={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(`
38
- `),initial:!1};async function Zo(e){return!!(await e([Xo])).useSpecKit}o(Zo,"promptForSpecKit");async function ei(e,t,n){return e!==void 0?e:t?Zo(n):!1}o(ei,"resolveSpecKit");function pn({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:i={},specKit:s,prompt:a=an.prompt.bind(an)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(x=>x[1]!==void 0)),d=Object.keys(c).length>0,l=e?sn(process.cwd()):t?sn(t):null,m=d&&l!==null,g=!m&&l?p.map(x=>x.name==="name"?{...x,initial:l}:x):p,f=ke(g),y=m?{...c,name:l}:c,w=new Set(Object.keys(y)),u=f.filter(x=>!w.has(x.name)),h=u.findIndex(x=>x.name==="baseUrl"),S;if(h!==-1){let x=u.filter(to=>to.name!=="baseUrl"),Ue=x.length>0?await a(x):{},zr=typeof Ue.cluster=="string"?Ue.cluster:"",Wr=typeof y.cluster=="string"?y.cluster:"",Xr=`https://${(zr||Wr).trim().replace(/\/+$/,"")||"api"}.cognitedata.com`,Zr=u[h],eo=await a([{...Zr,initial:Xr}]);S={...Ue,...eo}}else S=u.length>0?await a(u):{};let C={...y,...S},k=typeof C.name=="string"?C.name:"";k&&n(k);let T=await ei(s,u.length>0,a);return r?.(T),{...C,name:k,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:T}},"prompt")})}o(pn,"createAppPrompter");async function cn(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:`--${on(s)}`});for(let{key:s,value:a,label:p}of r){let c=e.find(l=>l.name===s)?.validate;if(!c)continue;let d=await c(a);if(d!==!0)throw new Error(`Invalid ${p}: ${d}`)}}o(cn,"validatePresets");import{cpSync as ni,mkdirSync as ln,writeFileSync as ri}from"fs";import{dirname as dn,resolve as q}from"path";import{fileURLToPath as oi}from"url";import{symlinkSync as ti}from"fs";function be({target:e,linkPath:t,label:n,symlink:r=ti}){try{return r(e,t),!0}catch(i){if(i instanceof Error&&"code"in i&&i.code==="EEXIST")return!0;let s=i instanceof Error?i.message:String(i);return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,s),!1}}o(be,"symlinkOrWarn");var ii=q(dn(oi(import.meta.url)),"..","..","_vendor","spec-kit"),si={branch_numbering:"sequential"},ai=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}];function mn({appDir:e,vendorDir:t=ii}){let n=q(e,".specify"),r=q(n,"memory"),i=`prepare spec-kit install for appDir=${e}`;try{for(let{from:s,to:a}of ai){let p=q(e,a);i=`copy ${s} to ${a}`,ln(dn(p),{recursive:!0}),ni(q(t,s),p,{recursive:!0})}i=`write init-options.json under specifyDir=${n}`,ri(q(n,"init-options.json"),`${JSON.stringify(si,null,2)}
39
- `),i=`link .specify/memory/constitution.md in specifyDir=${n}`,ln(r,{recursive:!0}),be({target:"../../AGENTS.md",linkPath:q(r,"constitution.md"),label:".specify/memory/constitution.md"})}catch(s){let a=s instanceof Error?s.message:String(s);throw new Error(`installSpecKit failed while ${i} (appDir=${e}, vendorDir=${t}): ${a}`,{cause:s})}}o(mn,"installSpecKit");var gn=me(ci(di(import.meta.url)),"..","..","_templates");async function fi(){let e=me(gn,"app","new","prompt.js");return(await import(mi(e).href)).default}o(fi,"loadPromptDefs");function yi(e,t){return!e||t?null:li(e)}o(yi,"resolveDirName");function hi(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(hi,"resolveAppLocation");function wi(e,t,n){let r=` npm install
40
- npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=n?`
37
+ npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>si(n))}o(sn,"registerActivateCommand");import{readdirSync as ki}from"fs";import{basename as Cn,dirname as Ei,normalize as bi,resolve as fe}from"path";import{fileURLToPath as Pi,pathToFileURL as Ai}from"url";import{Logger as Ii,runner as Di}from"hygen";import{execFileSync as Ie}from"child_process";function an(e={}){let{execFileSync:t=Ie}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(an,"isGitInstalled");function pn(e,t={}){let{execFileSync:n=Ie}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(pn,"isInsideGitRepo");function cn(e,t={}){let{execFileSync:n=Ie}=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(cn,"gitInitAndCommit");function ln(e={}){let{execFileSync:t=Ie}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(ln,"gitUserEmail");import{safeParse as ai}from"valibot";function ge(e,t){return n=>{let r=ai(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}o(ge,"toPromptValidator");var dn={name:ge("App name",et),displayName:ge("Display name",Ze),baseUrl:ge("Base URL",tt),org:ge("Org",nt),project:ge("Project",rt)};function pi(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}o(pi,"composeValidators");function De(e){return e.map(t=>{if(!(t.name in dn))return t;let n=dn[t.name];return{...t,validate:pi(t.validate,n)}})}o(De,"applySchemaValidators");import{basename as un}from"path";import gn from"enquirer";function mn(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(mn,"kebabCase");var ci={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(`
38
+ `),initial:!1};async function li(e){return!!(await e([ci])).useSpecKit}o(li,"promptForSpecKit");async function di(e,t,n){return e!==void 0?e:t?li(n):!1}o(di,"resolveSpecKit");function fn({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:i={},specKit:a,prompt:s=gn.prompt.bind(gn)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return s([p]);let c=Object.fromEntries(Object.entries(i).filter(C=>C[1]!==void 0)),d=Object.keys(c).length>0,l=e?un(process.cwd()):t?un(t):null,m=d&&l!==null,g=!m&&l?p.map(C=>C.name==="name"?{...C,initial:l}:C):p,f=De(g),h=m?{...c,name:l}:c,w=new Set(Object.keys(h)),u=f.filter(C=>!w.has(C.name)),y=u.findIndex(C=>C.name==="baseUrl"),S;if(y!==-1){let C=u.filter(uo=>uo.name!=="baseUrl"),q=C.length>0?await s(C):{},be=typeof q.cluster=="string"?q.cluster:"",Q=typeof h.cluster=="string"?h.cluster:"",co=`https://${(be||Q).trim().replace(/\/+$/,"")||"api"}.cognitedata.com`,lo=u[y],mo=await s([{...lo,initial:co}]);S={...q,...mo}}else S=u.length>0?await s(u):{};let v={...h,...S},x=typeof v.name=="string"?v.name:"";x&&n(x);let b=await di(a,u.length>0,s);return r?.(b),{...v,name:x,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:b}},"prompt")})}o(fn,"createAppPrompter");async function yn(e,t,n){let r=[];Object.values(t).some(a=>a!==void 0)&&n!==null&&r.push({key:"name",value:n,label:"directory"});for(let[a,s]of Object.entries(t))s!==void 0&&r.push({key:a,value:s,label:`--${mn(a)}`});for(let{key:a,value:s,label:p}of r){let c=e.find(l=>l.name===a)?.validate;if(!c)continue;let d=await c(s);if(d!==!0)throw new Error(`Invalid ${p}: ${d}`)}}o(yn,"validatePresets");import{cpSync as hi,mkdirSync as wn,writeFileSync as wi}from"fs";import{dirname as Sn,resolve as Y}from"path";import{fileURLToPath as Si}from"url";import{copyFileSync as mi,symlinkSync as ui}from"fs";import{dirname as gi,join as fi}from"path";function yi(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}o(yi,"errno");function hn(e){return e instanceof Error?e.message:String(e)}o(hn,"messageOf");function $e({target:e,linkPath:t,label:n,symlink:r=ui,copyFile:i=mi}){try{return r(e,t),!0}catch(a){let s=yi(a);if(s==="EEXIST")return!0;let p=hn(a);if(s==="EPERM"||s==="EACCES")try{let c=fi(gi(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: ${hn(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,p),!1}}o($e,"linkOrCopyOrWarn");var vi=Y(Sn(Si(import.meta.url)),"..","..","_vendor","spec-kit"),Ci={branch_numbering:"sequential"},xi=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}];function vn({appDir:e,vendorDir:t=vi}){let n=Y(e,".specify"),r=Y(n,"memory"),i=`prepare spec-kit install for appDir=${e}`;try{for(let{from:a,to:s}of xi){let p=Y(e,s);i=`copy ${a} to ${s}`,wn(Sn(p),{recursive:!0}),hi(Y(t,a),p,{recursive:!0})}i=`write init-options.json under specifyDir=${n}`,wi(Y(n,"init-options.json"),`${JSON.stringify(Ci,null,2)}
39
+ `),i=`link .specify/memory/constitution.md in specifyDir=${n}`,wn(r,{recursive:!0}),$e({target:"../../AGENTS.md",linkPath:Y(r,"constitution.md"),label:".specify/memory/constitution.md"})}catch(a){let s=a instanceof Error?a.message:String(a);throw new Error(`installSpecKit failed while ${i} (appDir=${e}, vendorDir=${t}): ${s}`,{cause:a})}}o(vn,"installSpecKit");var xn=fe(Ei(Pi(import.meta.url)),"..","..","_templates");async function $i(){let e=fe(xn,"app","new","prompt.js");return(await import(Ai(e).href)).default}o($i,"loadPromptDefs");function Ti(e,t){return!e||t?null:bi(e)}o(Ti,"resolveDirName");function Ri(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:fe(process.cwd(),r),display:r}}o(Ri,"resolveAppLocation");function Fi(e,t,n){let r=` npm install
40
+ npm run dev`,i="To deploy your app:",a="npx @cognite/cli apps deploy --interactive",s=n?`
41
41
  To start spec-driven development:
42
42
  Run /speckit.specify in Claude Code or Cursor and describe your app.
43
43
  `:"",p=` # Or fully non-interactive (deploys first target from app.json):
@@ -46,9 +46,9 @@ To start spec-driven development:
46
46
 
47
47
  Next steps:
48
48
  ${r}
49
- ${a}
49
+ ${s}
50
50
  ${i}
51
- ${s}
51
+ ${a}
52
52
  ${p}
53
53
  `);return}console.log(`
54
54
  \u2705 App created successfully!
@@ -58,13 +58,13 @@ To open in Cursor:
58
58
  Or:
59
59
  cd "${t}"
60
60
  ${r}
61
- ${a}
61
+ ${s}
62
62
  ${i}
63
63
  cd "${t}"
64
- ${s}
64
+ ${a}
65
65
  ${p}
66
- `)}o(wi,"printSuccessMessage");async function Si(e){try{let{execSkillsCli:t,pullAllArgs:n}=await import("../skills-GQ5TZKCM.js");console.log("\u{1F9E0} Pulling skills into your app..."),t(n(),{cwd:e,timeout:3e4,stdio:["pipe","pipe","inherit"]});let r=me(e,".agents","skills"),i=0;try{i=pi(r).length}catch{console.warn(`Skills directory not found after pull \u2014 no skills may have been installed (expected: ${r})`)}let s=i>0?`${i} skills`:"skills";console.log(`\u2705 Installed ${s} successfully to
67
- ${r}`)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}o(Si,"pullSkillsInto");function Ci(e,t={}){let{isGitInstalled:n=en,isInsideGitRepo:r=tn,gitInitAndCommit:i=nn}=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(Ci,"maybeInitGit");async function xi(e,t){let n=e==="."||e==="./",r=yi(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 fi(),c=ke(p),d=n?un(process.cwd()):r?un(r):null;await cn(c,a,d);let l=pn({isCurrentDir:n,dirName:r,onAppName:o(g=>{i=g},"onAppName"),onUseSpecKit:o(g=>{s=g},"onUseSpecKit"),presets:a,specKit:t.specKit});await gi(["app","new"],{templates:gn,cwd:process.cwd(),logger:new ui(console.log.bind(console)),createPrompter:l,debug:!!process.env.DEBUG});let m=hi(n,r,i);be({target:"AGENTS.md",linkPath:me(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&mn({appDir:m.cwd}),await Si(m.cwd),Ci(m.cwd),wi(n,m.display,s)}o(xi,"handleCreate");function fn(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",`
66
+ `)}o(Fi,"printSuccessMessage");async function Oi(e){try{let{execSkillsCli:t,pullAllArgs:n}=await import("../skills-SV7BPHAZ.js");console.log("\u{1F9E0} Pulling skills into your app..."),t(n(),{cwd:e,timeout:3e4,stdio:["pipe","pipe","inherit"]});let r=fe(e,".agents","skills"),i=0;try{i=ki(r).length}catch{console.warn(`Skills directory not found after pull \u2014 no skills may have been installed (expected: ${r})`)}let a=i>0?`${i} skills`:"skills";console.log(`\u2705 Installed ${a} successfully to
67
+ ${r}`)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}o(Oi,"pullSkillsInto");function Li(e,t={}){let{isGitInstalled:n=an,isInsideGitRepo:r=pn,gitInitAndCommit:i=cn}=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(a){let p=(a&&typeof a=="object"&&"stderr"in a&&a.stderr?String(a.stderr).trim():"")||(a instanceof Error?a.message:String(a));console.warn("Could not initialise git repository:",p)}}}o(Li,"maybeInitGit");async function Ni(e,t){let n=e==="."||e==="./",r=Ti(e,n),i=null,a=!1,s={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await $i(),c=De(p),d=n?Cn(process.cwd()):r?Cn(r):null;await yn(c,s,d);let l=fn({isCurrentDir:n,dirName:r,onAppName:o(g=>{i=g},"onAppName"),onUseSpecKit:o(g=>{a=g},"onUseSpecKit"),presets:s,specKit:t.specKit});await Di(["app","new"],{templates:xn,cwd:process.cwd(),logger:new Ii(console.log.bind(console)),createPrompter:l,debug:!!process.env.DEBUG});let m=Ri(n,r,i);$e({target:"AGENTS.md",linkPath:fe(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),a&&vn({appDir:m.cwd}),await Oi(m.cwd),Li(m.cwd),Fi(n,m.display,a)}o(Ni,"handleCreate");function kn(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",`
68
68
  Non-interactive use (CI, scripts, AI agents):
69
69
  Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
70
70
  to skip every prompt. Missing flags fall back to the interactive prompt.
@@ -77,14 +77,17 @@ Examples:
77
77
  --display-name "My App" --description "My app" \\
78
78
  --org cog-atlas --project atlas-greenfield --cluster greenfield \\
79
79
  --base-url https://greenfield.cognitedata.com
80
- Fully non-interactive`).action(xi)}o(fn,"registerCreateCommand");import{readFile as Ai,unlink as $i}from"fs/promises";import{basename as Di}from"path";import hn from"fs";import Pi from"path";import G from"fs";import b from"path";import{parseAndValidateManifestConfig as vi}from"@cognite/app-sdk/vite";import{BlobReader as ki,Uint8ArrayWriter as Ei,ZipWriter as bi}from"@zip.js/zip.js";var et="package.json",tt="package-lock.json",yn="manifest.json",nt=".cognite",rt=class rt{constructor(t="dist"){this.distPath=b.isAbsolute(t)?t:b.join(process.cwd(),t),this.appRoot=b.dirname(this.distPath)}validateBuildDirectory(){if(!G.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=b.join(this.appRoot,et);if(!G.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=b.join(this.appRoot,tt);if(!G.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 bi(new Ei,{level:9}),i=o(async(c,d)=>{await r.add(d,new ki(await G.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${d}`)},"addFile"),s=o(async c=>{let d=await G.promises.readdir(c,{withFileTypes:!0});for(let l of d){let m=b.join(c,l.name);l.isDirectory()?await s(m):await i(m,b.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=b.join(this.appRoot,et);await i(c,b.posix.join(nt,et));let d=b.join(this.appRoot,yn);if(G.existsSync(d)){let m=G.readFileSync(d,"utf-8");vi(m,d),await i(d,b.posix.join(nt,yn))}let l=b.join(this.appRoot,tt);await i(l,b.posix.join(nt,tt)),a=await r.close()}catch(c){let d=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${d}`)}await G.promises.writeFile(t,a);let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}};o(rt,"ApplicationPackager");var Q=rt;var ot=o(async(e,t,n)=>{let r=await new Q(`${n}/dist`).createZip("app.zip",!0);try{let{externalId:i,name:s,description:a,versionTag:p}=t,c=await le(e,n),d=new E(c),l=hn.readFileSync(r),m=Pi.basename(r);await d.deploy(i,s,a,p,l,m,e.published)}finally{try{hn.unlinkSync(r)}catch{}}},"deploy");import{execSync as Ii}from"child_process";function it(e,t=!0,n={execSync:Ii}){console.log("\u{1F4E6} Building app with npm..."),n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"}),console.log("\u2705 Build successful")}o(it,"buildApp");function wn(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(wn,"generateFusionUrl");function Sn(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(`
81
- `))}o(Sn,"printDeployInfo");function Cn(e,t){console.log(`
80
+ Fully non-interactive`).action(Ni)}o(kn,"registerCreateCommand");import ji from"path";async function _i(e,t,n){let r=await j(e,{interactive:t.interactive,appId:n,orgHint:t.org});return new E(r)}o(_i,"defaultGetApiClient");async function Mi(e,t,n={}){let{loadEnvFile:r=P,loadAppConfig:i=k,getApiClient:a=_i}=n,s=ji.resolve(process.cwd(),e);r(s);let p=i(s);M(p);let c=t.interactive?await _(p,t):F(p.deployments,t.deployment);if(!t.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 \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let d=await a(c,t,p.externalId),{externalId:l}=p,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(Mi,"handleDeactivate");function En(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",`
81
+ Examples:
82
+ npx @cognite/cli apps deactivate . Deactivate using env-var auth
83
+ npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>Mi(t,n))}o(En,"registerDeactivateCommand");import{readFile as qi,unlink as Qi}from"fs/promises";import{basename as Ji}from"path";import Pn from"fs";import Hi from"path";import G from"fs";import A from"path";import{parseAndValidateManifestConfig as Vi}from"@cognite/app-sdk/vite";import{BlobReader as Ui,Uint8ArrayWriter as Ki,ZipWriter as Gi}from"@zip.js/zip.js";var at="package.json",pt="package-lock.json",bn="manifest.json",ct=".cognite",lt=class lt{constructor(t="dist"){this.distPath=A.isAbsolute(t)?t:A.join(process.cwd(),t),this.appRoot=A.dirname(this.distPath)}validateBuildDirectory(){if(!G.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=A.join(this.appRoot,at);if(!G.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=A.join(this.appRoot,pt);if(!G.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 Gi(new Ki,{level:9}),i=o(async(c,d)=>{await r.add(d,new Ui(await G.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${d}`)},"addFile"),a=o(async c=>{let d=await G.promises.readdir(c,{withFileTypes:!0});for(let l of d){let m=A.join(c,l.name);l.isDirectory()?await a(m):await i(m,A.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),s;try{await a(this.distPath);let c=A.join(this.appRoot,at);await i(c,A.posix.join(ct,at));let d=A.join(this.appRoot,bn);if(G.existsSync(d)){let m=G.readFileSync(d,"utf-8");Vi(m,d),await i(d,A.posix.join(ct,bn))}let l=A.join(this.appRoot,pt);await i(l,A.posix.join(ct,pt)),s=await r.close()}catch(c){let d=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${d}`)}await G.promises.writeFile(t,s);let p=(s.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}};o(lt,"ApplicationPackager");var z=lt;var dt=o(async(e,t,n)=>{let r=await new z(`${n}/dist`).createZip("app.zip",!0);try{let{externalId:i,name:a,description:s,versionTag:p}=t,c=await ue(e,n),d=new E(c),l=Pn.readFileSync(r),m=Hi.basename(r);await d.deploy(i,a,s,p,l,m,e.published)}finally{try{Pn.unlinkSync(r)}catch{}}},"deploy");import{execSync as Bi}from"child_process";function mt(e,t=!0,n={execSync:Bi}){console.log("\u{1F4E6} Building app with npm..."),n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"}),console.log("\u2705 Build successful")}o(mt,"buildApp");function An(e,t){let{org:n,project:r,baseUrl:i}=e,a;try{a=new URL(i).hostname}catch{return null}let{externalId:s,versionTag:p}=t,c=new URLSearchParams({cluster:a,customAppVersion:p,workspace:"industrial-tools"});return`https://${n}.fusion.cognite.com/${r}/flows-apps/app/${encodeURIComponent(s)}?${c}`}o(An,"generateFusionUrl");function In(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(`
84
+ `))}o(In,"printDeployInfo");function Dn(e,t){console.log(`
82
85
  \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(`
83
- To publish: npx @cognite/cli apps publish .${n}`),console.log(`To activate: npx @cognite/cli apps activate .${n}`);let r=wn(t,e);r&&console.log(`
86
+ To publish: npx @cognite/cli apps publish .${n}`),console.log(`To activate: npx @cognite/cli apps activate .${n}`);let r=An(t,e);r&&console.log(`
84
87
  \u{1F517} Open your app:
85
- ${r}`)}o(Cn,"printDeployResult");async function Ti(e,t,n,r,i){let s=O(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.`);Sn(e,t,!1),r.skipBuild||it(n),console.log(`
86
- \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),Cn(e,t)}o(Ti,"handleDeployNonInteractive");async function Ri(e,t,n,r){Sn(e,t,!0),r.skipBuild||it(n);let i=await V(t,{interactive:!0,appId:e.externalId,orgHint:r.org});console.log(`
87
- \u{1F4E4} Deploying to ${t.project}...`);let s=await new Q(`${n}/dist`).createZip("app.zip",!0);try{let a=await Ai(s);await new E(i).deploy(e.externalId,e.name,e.description,e.versionTag,a,Di(s),!1),Cn(e,t)}finally{await $i(s).catch(()=>{})}}o(Ri,"handleDeployInteractive");async function Fi(e,t=process.cwd(),n={}){let{loadEnvFile:r=$,loadAppConfig:i=v,deploy:s=ot}=n;r(t);let a=i(t);if(K(a),e.interactive){let c=await U(a,e);await Ri(a,c,t,e);return}let p=N(a.deployments,e.deployment);await Ti(a,p,t,e,s)}o(Fi,"handleDeploy");function xn(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",`
88
+ ${r}`)}o(Dn,"printDeployResult");async function Yi(e,t,n,r,i){let a=T(t);if(a.length>0)throw new Error(`Deployment ${t.org}/${t.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);In(e,t,!1),r.skipBuild||mt(n),console.log(`
89
+ \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),Dn(e,t)}o(Yi,"handleDeployNonInteractive");async function zi(e,t,n,r){In(e,t,!0),r.skipBuild||mt(n);let i=await j(t,{interactive:!0,appId:e.externalId,orgHint:r.org});console.log(`
90
+ \u{1F4E4} Deploying to ${t.project}...`);let a=await new z(`${n}/dist`).createZip("app.zip",!0);try{let s=await qi(a);await new E(i).deploy(e.externalId,e.name,e.description,e.versionTag,s,Ji(a),!1),Dn(e,t)}finally{await Qi(a).catch(()=>{})}}o(zi,"handleDeployInteractive");async function Wi(e,t=process.cwd(),n={}){let{loadEnvFile:r=P,loadAppConfig:i=k,deploy:a=dt}=n;r(t);let s=i(t);if(M(s),e.interactive){let c=await _(s,e);await zi(s,c,t,e);return}let p=F(s.deployments,e.deployment);await Yi(s,p,t,e,a)}o(Wi,"handleDeploy");function $n(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",`
88
91
  Environment (non-interactive):
89
92
  deployClientId and deploySecretName are configured per deployment in app.json.
90
93
  deploySecretName is the name of the environment variable that holds the client
@@ -98,22 +101,22 @@ Examples:
98
101
  npx @cognite/cli apps deploy -d my-project Deploy to project by name
99
102
  npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
100
103
  npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
101
- npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>Fi(t))}o(xn,"registerDeployCommand");async function Li(e){let t=process.cwd();$(t);let n=v(t);K(n);let r=e.interactive?await U(n,e):N(n.deployments,e.deployment);if(!e.interactive){let d=O(r);if(d.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${d.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let i=await V(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 F?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==="PUBLISHED"){console.log(` ${a} @ ${p} is already PUBLISHED \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${a} @ ${p}: version is ${c.lifecycleState} (terminal).`);await s.publishVersion(a,p),console.log(`\u2713 Published ${a} @ ${p} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}o(Li,"handlePublish");function vn(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",`
104
+ npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>Wi(t))}o($n,"registerDeployCommand");async function Xi(e){let t=process.cwd();P(t);let n=k(t);M(n);let r=e.interactive?await _(n,e):F(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 \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let i=await j(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),a=new E(i),{externalId:s,versionTag:p}=n,c;try{c=await a.getVersion(s,p)}catch(d){throw d instanceof L?new Error(`Version ${p} of ${s} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):d}if(c.alias==="ACTIVE"){console.log(` ${s} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="PUBLISHED"){console.log(` ${s} @ ${p} is already PUBLISHED \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${s} @ ${p}: version is ${c.lifecycleState} (terminal).`);await a.publishVersion(s,p),console.log(`\u2713 Published ${s} @ ${p} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}o(Xi,"handlePublish");function Tn(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",`
102
105
  Examples:
103
106
  npx @cognite/cli apps publish . Publish using env-var auth
104
- npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>Li(n))}o(vn,"registerPublishCommand");function Oi(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(Oi,"describeStatus");async function Ni(e){let t=process.cwd();$(t);let n=v(t);K(n);let r=e.interactive?await U(n,e):N(n.deployments,e.deployment);if(!e.interactive){let a=O(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 V(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),p=Oi(a);console.log(`Status: ${p}`),a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof F){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}o(Ni,"handleStatus");function kn(e){return e.command("status").description("Show the deployment status 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",`
107
+ npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>Xi(n))}o(Tn,"registerPublishCommand");function Zi(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(Zi,"describeStatus");async function es(e){let t=process.cwd();P(t);let n=k(t);M(n);let r=e.interactive?await _(n,e):F(n.deployments,e.deployment);if(!e.interactive){let s=T(r);if(s.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${s.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let i=await j(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),a=new E(i);console.log(""),console.log(`App: ${n.name} (${n.externalId})`),console.log(`Version: ${n.versionTag} (local)`);try{let s=await a.getVersion(n.externalId,n.versionTag),p=Zi(s);console.log(`Status: ${p}`),s.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(s){if(s instanceof L){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw s}}o(es,"handleStatus");function Rn(e){return e.command("status").description("Show the deployment status 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",`
105
108
  Examples:
106
109
  npx @cognite/cli apps status . Status using env-var auth
107
- npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>Ni(n))}o(kn,"registerStatusCommand");import{existsSync as Zn,readFileSync as ye,writeFileSync as ft,mkdirSync as Fs}from"fs";import{resolve as _}from"path";import{fileURLToPath as Ls}from"url";import{CogniteClient as Os}from"@cognite/sdk";import{mkdirSync as Ds,readFileSync as Ts,rmSync as Rs,writeFileSync as se}from"fs";import{resolve as H}from"path";import{generate as Yn}from"@graphql-codegen/cli";import{GraphQLSchema as hs,GraphQLObjectType as ws,GraphQLNonNull as R,GraphQLList as ie,GraphQLString as W,GraphQLInt as Ss,GraphQLInputObjectType as Kn,printSchema as Cs}from"graphql";function st(e){return{space:e.space,externalId:e.externalId,version:e.version}}o(st,"toSharedViewId");function _i(e){switch(e){case"text":return"String";case"boolean":return"Boolean";case"int32":case"int64":return"Int";case"float32":case"float64":return"Float";case"timestamp":return"DateTime";case"date":return"Date";case"json":return"JSON";case"timeseries":return"CogniteTimeSeriesReference";case"file":return"CogniteFileReference";case"sequence":return"CogniteSequenceReference";case"enum":return"String";default:return"String"}}o(_i,"dmsTypeToGraphQL");function En(e){if(!("source"in e)){if(e.type?.type==="direct")return e.type.list?{kind:"scalar",isList:!1,graphqlType:"JSON"}:e.type.source?{kind:"directRelation",targetView:st(e.type.source)}:{kind:"scalar",isList:!1,graphqlType:"JSON"};if(e.type?.type==="enum"){let t=e.type,n={};if(typeof t=="object"&&t!==null&&"values"in t){let r=t.values;if(typeof r=="object"&&r!==null)for(let[i,s]of Object.entries(r))n[i]={name:typeof s=="object"&&s!==null&&"name"in s?String(s.name):void 0}}return{kind:"enum",values:Object.keys(n),valueNames:Object.fromEntries(Object.entries(n).map(([r,i])=>[r,i.name??r]))}}return{kind:"scalar",isList:e.type!==void 0&&"list"in e.type&&e.type.list===!0,graphqlType:e.type?.type?_i(e.type.type):"String"}}if("through"in e)return{kind:e.connectionType==="single_reverse_direct_relation"?"reverseDirect":"reverseList",sourceView:st(e.source),throughProperty:e.through.identifier};if(e.connectionType==="single_edge_connection"||e.connectionType==="multi_edge_connection"){let t=e.direction==="inwards"?"inwards":"outwards";return{kind:"edge",targetView:st(e.source),direction:t}}return{kind:"scalar"}}o(En,"parsePropertyDescriptor");var bn=new Set(["String","Boolean","Int","Float","DateTime","Date"]);var ji=new Set(["String","Int","Float","DateTime","Date"]);function Pe(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:bn.has(e.graphqlType??"String")}o(Pe,"isFilterableDescriptor");function Ie(e){return e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:bn.has(e.graphqlType??"String")}o(Ie,"isSortableDescriptor");function Pn(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind==="scalar"&&e.isList!==!0&&ji.has(e.graphqlType??"")}o(Pn,"hasInOpDescriptor");function In(e){return e.kind==="scalar"&&e.isList===!0}o(In,"hasListOpsDescriptor");function ue(e){return e.usedFor!=="edge"}o(ue,"isNodeOrAll");function D(e){return Object.entries(e.properties).map(([t,n])=>[t,En(n),n.description])}o(D,"parsedProperties");import{GraphQLObjectType as An,GraphQLNonNull as ge,GraphQLString as lt,GraphQLFloat as $e,GraphQLList as Hi,GraphQLEnumType as Bi}from"graphql";import{GraphQLScalarType as J,Kind as P}from"graphql";function at(e){switch(e.kind){case P.STRING:case P.BOOLEAN:return e.value;case P.INT:return parseInt(e.value,10);case P.FLOAT:return parseFloat(e.value);case P.OBJECT:{let t={};for(let n of e.fields)t[n.name.value]=at(n.value);return t}case P.LIST:return e.values.map(at);case P.NULL:return null;default:return null}}o(at,"parseLiteralJSON");var Mi=new J({name:"DateTime",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Vi=new J({name:"Date",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),pt=new J({name:"JSON",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:at}),Ui=new J({name:"CogniteTimeSeriesReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Ki=new J({name:"CogniteFileReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Gi=new J({name:"CogniteSequenceReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Ae=new J({name:"ListLimit",description:"Limit for list/search queries (1\u20131000).",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.INT?parseInt(e.value,10):null,"parseLiteral")}),Y={DateTime:Mi,Date:Vi,JSON:pt,CogniteTimeSeriesReference:Ui,CogniteFileReference:Ki,CogniteSequenceReference:Gi,ListLimit:Ae},ct={DateTime:"string",Date:"string",JSON:"unknown",CogniteTimeSeriesReference:"string",CogniteFileReference:"string",CogniteSequenceReference:"string",ListLimit:"number"};var qi=new Bi({name:"AggregateFunction",values:{count:{value:"count"},avg:{value:"avg"},sum:{value:"sum"},min:{value:"min"},max:{value:"max"},histogram:{value:"histogram"}}}),$n={function:{type:new ge(qi)},property:{type:lt},interval:{type:$e}},Qi=new An({name:"HistogramBucket",fields:{start:{type:new ge($e)},count:{type:new ge($e)}}}),Dn=new An({name:"AggregateResult",fields:{aggregate:{type:new ge(lt)},property:{type:lt},value:{type:$e},buckets:{type:new Hi(new ge(Qi))},group:{type:pt}}});import{GraphQLObjectType as mt,GraphQLNonNull as ne,GraphQLList as Ji,GraphQLString as dt,GraphQLBoolean as Yi}from"graphql";var zi=new mt({name:"PageInfo",fields:{endCursor:{type:dt},hasNextPage:{type:new ne(Yi)}}}),De=new mt({name:"NodeReference",fields:{space:{type:new ne(dt)},externalId:{type:new ne(dt)}}});function Te(e,t){return new mt({name:`${e}Connection`,fields:{items:{type:new ne(new Ji(new ne(t)))},pageInfo:{type:new ne(zi)}}})}o(Te,"makeConnectionType");import{GraphQLInputObjectType as re,GraphQLList as A,GraphQLNonNull as On,GraphQLString as z,GraphQLBoolean as I,GraphQLFloat as os,GraphQLInt as is}from"graphql";import{GraphQLObjectType as Wi,GraphQLNonNull as Tn,GraphQLList as Xi,GraphQLString as Re,GraphQLBoolean as Zi,GraphQLInt as es,GraphQLFloat as ts,GraphQLEnumType as ns}from"graphql";function Rn(e){return e==="String"?Re:e==="Boolean"?Zi:e==="Int"?es:e==="Float"?ts:Y[e]??Re}o(Rn,"scalarForName");function Fn(e){return{typeRegistry:new Map,connectionRegistry:new Map,viewsByExtId:new Map(e.map(t=>[t.externalId,t])),enumRegistry:new Map,enumFilterRegistry:new Map}}o(Fn,"createTypeContext");function rs(e){let t=e.replace(/[^_A-Za-z0-9]/g,"_");return/^[0-9]/.test(t)&&(t=`_${t}`),t||"_UNKNOWN"}o(rs,"sanitizeEnumValue");function ut(e,t,n,r){let i=n.enumRegistry.get(e);if(i)return i;let s=new ns({name:e,values:Object.fromEntries(t.map(a=>[rs(a),{value:a,description:r?.[a]}]))});return n.enumRegistry.set(e,s),s}o(ut,"getOrCreateEnumType");function Ln(e,t){return new Wi({name:e.externalId,description:e.description??e.name,fields:o(()=>{let n={space:{type:new Tn(Re)},externalId:{type:new Tn(Re)}};for(let[r,i,s]of D(e))if(i.kind==="scalar")i.isList?n[r]={type:new Xi(Rn(i.graphqlType??"String")),description:s}:n[r]={type:Rn(i.graphqlType??"String"),description:s};else if(i.kind==="enum"){let a=`${e.externalId}${r.charAt(0).toUpperCase()}${r.slice(1)}`;n[r]={type:ut(a,i.values,t,i.valueNames),description:s}}else if(i.kind==="directRelation"){let a=t.typeRegistry.get(i.targetView.externalId)??De;n[r]={type:a,description:s}}else if(i.kind==="reverseList"||i.kind==="edge"){let a=i.kind==="reverseList"?i.sourceView.externalId:i.targetView.externalId,p=t.typeRegistry.get(a)??De,c=t.connectionRegistry.get(a);c||(c=Te(a,p),t.connectionRegistry.set(a,c)),n[r]={type:c,description:s}}else if(i.kind==="reverseDirect"){let a=t.typeRegistry.get(i.sourceView.externalId)??De;n[r]={type:a,description:s}}return n},"fields")})}o(Ln,"generateViewObjectType");function oe(e,t,n){let r={isNull:{type:I},exists:{type:I},eq:{type:t}};return n.hasIn&&(r.in={type:new A(t)}),n.hasPrefix&&(r.prefix={type:z}),n.hasRange&&(r.gte={type:t},r.gt={type:t},r.lte={type:t},r.lt={type:t}),n.hasListOps&&(r.containsAny={type:new A(t)},r.containsAll={type:new A(t)},r.overlaps={type:new A(t)}),new re({name:e,fields:r})}o(oe,"makeScalarFilter");var Fe=oe("StringFilter",z,{hasIn:!0,hasPrefix:!0}),ss=oe("BooleanFilter",I,{}),as=oe("IntFilter",is,{hasIn:!0,hasRange:!0}),ps=oe("FloatFilter",os,{hasIn:!0,hasRange:!0}),cs=oe("DateTimeFilter",Y.DateTime,{hasIn:!0,hasRange:!0}),ls=oe("DateFilter",Y.Date,{hasIn:!0,hasRange:!0}),ds=new re({name:"StringListFilter",fields:{isNull:{type:I},exists:{type:I},containsAny:{type:new A(z)},containsAll:{type:new A(z)},overlaps:{type:new A(z)}}}),fe=new re({name:"DirectRelationRef",fields:{space:{type:new On(z)},externalId:{type:new On(z)}}}),ms=new re({name:"DirectRelationFilter",fields:{isNull:{type:I},exists:{type:I},eq:{type:fe},in:{type:new A(fe)}}});function us(e){switch(e){case"String":return Fe;case"Boolean":return ss;case"Int":return as;case"Float":return ps;case"DateTime":return cs;case"Date":return ls;default:return Fe}}o(us,"scalarFilterForName");var Nn=["space","externalId"];function _n(e,t,n){let r=t.get(e.externalId),i={};for(let a of Nn)i[a]={type:Fe};let s=new Set(Nn);for(let[a,p]of D(e)){if(s.has(a))continue;let c=Pe(p),d=In(p);if(!(!c&&!d))if(p.kind==="directRelation"){let l={isNull:{type:I},exists:{type:I},eq:{type:fe},in:{type:new A(fe)}};Pn(p)&&(l.in={type:new A(fe)});let m=t.get(p.targetView.externalId);m&&(l.nested={type:m}),i[a]=m?{type:new re({name:`_${e.externalId}_${a}_Filter`,fields:l})}:{type:ms}}else if(p.kind==="enum"){let l=`${e.externalId}${a.charAt(0).toUpperCase()}${a.slice(1)}`,m=ut(l,p.values,n),g=n.enumFilterRegistry.get(l);g||(g=new re({name:`${l}Filter`,fields:{isNull:{type:I},exists:{type:I},eq:{type:m},in:{type:new A(m)}}}),n.enumFilterRegistry.set(l,g)),i[a]={type:g}}else if(d)i[a]={type:ds};else{let l=p.kind==="scalar"?p.graphqlType??"String":"String",m=us(l);m&&(i[a]={type:m})}}return{...i,hasData:{type:I},matchAll:{type:I},_and:{type:new A(r)},_or:{type:new A(r)},_not:{type:r}}}o(_n,"generateFilterFields");import{GraphQLEnumType as jn,GraphQLInputObjectType as Mn,GraphQLList as gs,GraphQLNonNull as Le,GraphQLString as fs,GraphQLBoolean as ys}from"graphql";var Oe=new jn({name:"SortDirection",values:{ASC:{value:"ascending"},DESC:{value:"descending"}}});function Vn(e){let t=[];for(let[r,i]of D(e))Ie(i)&&t.push(r);if(t.length===0)return null;let n=new jn({name:`${e.externalId}SortField`,values:Object.fromEntries(t.map(r=>[r,{value:r}]))});return new Mn({name:`${e.externalId}Sort`,fields:{field:{type:new Le(n)},direction:{type:new Le(Oe)},nullsFirst:{type:ys}}})}o(Vn,"generateSortInput");var Un=new Mn({name:"SearchSort",fields:{property:{type:new Le(new gs(new Le(fs)))},direction:{type:Oe}}});function Gn(e){let t=e.filter(ue),n=Fn(t);for(let l of t){let m=Ln(l,n);n.typeRegistry.set(l.externalId,m)}let r=new Map;for(let l of t){let m=new Kn({name:`${l.externalId}Filter`,fields:o(()=>_n(l,r,n),"fields")});r.set(l.externalId,m)}let i={};for(let l of t){let m=l.externalId,g=n.typeRegistry.get(m),f=n.connectionRegistry.get(m);f||(f=Te(m,g),n.connectionRegistry.set(m,f));let y=r.get(m),w=Vn(l),u={limit:{type:Ae},cursor:{type:W},filter:{type:y}};w&&(u.sort={type:new ie(w)}),i[`query${m}`]={type:new R(f),args:u},i[`get${m}ById`]={type:g,args:{space:{type:new R(W)},externalId:{type:new R(W)}}},i[`count${m}`]={type:new R(Ss),args:{filter:{type:y}}},i[`search${m}`]={type:new R(f),args:{query:{type:W},limit:{type:Ae},filter:{type:y},sort:{type:new ie(new R(Un))},properties:{type:new ie(new R(W))}}},i[`aggregate${m}`]={type:new R(new ie(new R(Dn))),args:{filter:{type:y},aggregates:{type:new ie(new R(new Kn({name:`${m}AggregateRequest`,fields:$n})))},groupBy:{type:new ie(new R(W))},query:{type:W}}}}let s=[];for(let[l,m]of n.typeRegistry)s.push({name:m.name,source:`typeRegistry[${l}]`});for(let[l,m]of n.connectionRegistry)s.push({name:m.name,source:`connectionRegistry[${l}]`});let a=new Map;for(let{name:l,source:m}of s)a.has(l)||a.set(l,[]),a.get(l).push(m);for(let[l,m]of a)m.length>1&&console.error(`[dune] duplicate type "${l}" from: ${m.join(", ")}`);let p=new hs({query:new ws({name:"Query",fields:i}),types:[Oe,...Object.values(Y),...n.enumRegistry.values()]}),c=new Map;for(let l of t){let m=new Map;for(let[g,f]of D(l))m.set(g,f);c.set(l.externalId,{view:{space:l.space,externalId:l.externalId,version:l.version},properties:m})}let d={view(l){let m=c.get(l.externalId);if(!m)throw new Error(`SchemaKnowledge: no view for externalId "${l.externalId}"`);return m},property(l,m){return c.get(l.externalId)?.properties.get(m)}};return{schema:p,sdl:Cs(p),schemaKnowledge:d}}o(Gn,"buildSchema");async function Hn(e,t){let r=(await t.dataModels.retrieve([{space:e.space,externalId:e.dataModelExternalId,version:e.dataModelVersion}],{inlineViews:!1})).items[0];if(!r)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} not found`);if(!r.views?.length)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} has no views`);let i=r.views.map(a=>({space:a.space,externalId:a.externalId,version:a.version}));return(await t.views.retrieve(i,{includeInheritedProperties:!0})).items}o(Hn,"fetchViews");import{GraphQLObjectType as xs,GraphQLNonNull as vs,GraphQLList as ks,isScalarType as Es,isEnumType as bs,parse as Ps,print as Is}from"graphql";function gt(e,t){let n=e.getType(t);if(!(n instanceof xs))return[];let r=n.getFields(),i=[];for(let[s,a]of Object.entries(r)){let p=a.type;for(;p instanceof vs||p instanceof ks;)p=p.ofType;(Es(p)||bs(p))&&i.push(s)}return i}o(gt,"scalarFieldsFor");function As(e,t){let n=gt(e,t),r=["space","externalId"];for(let i of["name","description"])n.includes(i)&&r.push(i);return r.join(" ")}o(As,"minimalRelationFields");function Bn(e,t,n){let r=[];for(let[i,s]of D(e))if(s.kind==="directRelation"||s.kind==="reverseDirect"){let a=s.kind==="directRelation"?s.targetView.externalId:s.sourceView.externalId;if(n)r.push(`${i} { ${As(t,a)} }`);else{let c=["space","externalId",...gt(t,a).filter(d=>d!=="space"&&d!=="externalId")];r.push(`${i} { ${c.join(" ")} }`)}}else!n&&(s.kind==="reverseList"||s.kind==="edge")&&r.push(`${i} { items { space externalId } pageInfo { hasNextPage endCursor } }`);return r}o(Bn,"relationFieldsFor");function qn(e,t,n,r){return`query ${e}(${t}) {
110
+ npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>es(n))}o(Rn,"registerStatusCommand");import{existsSync as pr,readFileSync as Se,writeFileSync as xt,mkdirSync as Ws}from"fs";import{resolve as V}from"path";import{fileURLToPath as Xs}from"url";import{CogniteClient as Zs}from"@cognite/sdk";import{mkdirSync as Js,readFileSync as Ys,rmSync as zs,writeFileSync as pe}from"fs";import{resolve as H}from"path";import{generate as or}from"@graphql-codegen/cli";import{GraphQLSchema as Ls,GraphQLObjectType as Ns,GraphQLNonNull as O,GraphQLList as ae,GraphQLString as ee,GraphQLInt as js,GraphQLInputObjectType as Wn,printSchema as _s}from"graphql";function ut(e){return{space:e.space,externalId:e.externalId,version:e.version}}o(ut,"toSharedViewId");function ts(e){switch(e){case"text":return"String";case"boolean":return"Boolean";case"int32":case"int64":return"Int";case"float32":case"float64":return"Float";case"timestamp":return"DateTime";case"date":return"Date";case"json":return"JSON";case"timeseries":return"CogniteTimeSeriesReference";case"file":return"CogniteFileReference";case"sequence":return"CogniteSequenceReference";case"enum":return"String";default:return"String"}}o(ts,"dmsTypeToGraphQL");function Fn(e){if(!("source"in e)){if(e.type?.type==="direct")return e.type.list?{kind:"scalar",isList:!1,graphqlType:"JSON"}:e.type.source?{kind:"directRelation",targetView:ut(e.type.source)}:{kind:"scalar",isList:!1,graphqlType:"JSON"};if(e.type?.type==="enum"){let t=e.type,n={};if(typeof t=="object"&&t!==null&&"values"in t){let r=t.values;if(typeof r=="object"&&r!==null)for(let[i,a]of Object.entries(r))n[i]={name:typeof a=="object"&&a!==null&&"name"in a?String(a.name):void 0}}return{kind:"enum",values:Object.keys(n),valueNames:Object.fromEntries(Object.entries(n).map(([r,i])=>[r,i.name??r]))}}return{kind:"scalar",isList:e.type!==void 0&&"list"in e.type&&e.type.list===!0,graphqlType:e.type?.type?ts(e.type.type):"String"}}if("through"in e)return{kind:e.connectionType==="single_reverse_direct_relation"?"reverseDirect":"reverseList",sourceView:ut(e.source),throughProperty:e.through.identifier};if(e.connectionType==="single_edge_connection"||e.connectionType==="multi_edge_connection"){let t=e.direction==="inwards"?"inwards":"outwards";return{kind:"edge",targetView:ut(e.source),direction:t}}return{kind:"scalar"}}o(Fn,"parsePropertyDescriptor");var On=new Set(["String","Boolean","Int","Float","DateTime","Date"]);var ns=new Set(["String","Int","Float","DateTime","Date"]);function Te(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:On.has(e.graphqlType??"String")}o(Te,"isFilterableDescriptor");function Re(e){return e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:On.has(e.graphqlType??"String")}o(Re,"isSortableDescriptor");function Ln(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind==="scalar"&&e.isList!==!0&&ns.has(e.graphqlType??"")}o(Ln,"hasInOpDescriptor");function Nn(e){return e.kind==="scalar"&&e.isList===!0}o(Nn,"hasListOpsDescriptor");function ye(e){return e.usedFor!=="edge"}o(ye,"isNodeOrAll");function R(e){return Object.entries(e.properties).map(([t,n])=>[t,Fn(n),n.description])}o(R,"parsedProperties");import{GraphQLObjectType as jn,GraphQLNonNull as he,GraphQLString as ht,GraphQLFloat as Oe,GraphQLList as ps,GraphQLEnumType as cs}from"graphql";import{GraphQLScalarType as W,Kind as I}from"graphql";function gt(e){switch(e.kind){case I.STRING:case I.BOOLEAN:return e.value;case I.INT:return parseInt(e.value,10);case I.FLOAT:return parseFloat(e.value);case I.OBJECT:{let t={};for(let n of e.fields)t[n.name.value]=gt(n.value);return t}case I.LIST:return e.values.map(gt);case I.NULL:return null;default:return null}}o(gt,"parseLiteralJSON");var rs=new W({name:"DateTime",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===I.STRING?e.value:null,"parseLiteral")}),os=new W({name:"Date",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===I.STRING?e.value:null,"parseLiteral")}),ft=new W({name:"JSON",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:gt}),is=new W({name:"CogniteTimeSeriesReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===I.STRING?e.value:null,"parseLiteral")}),ss=new W({name:"CogniteFileReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===I.STRING?e.value:null,"parseLiteral")}),as=new W({name:"CogniteSequenceReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===I.STRING?e.value:null,"parseLiteral")}),Fe=new W({name:"ListLimit",description:"Limit for list/search queries (1\u20131000).",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===I.INT?parseInt(e.value,10):null,"parseLiteral")}),X={DateTime:rs,Date:os,JSON:ft,CogniteTimeSeriesReference:is,CogniteFileReference:ss,CogniteSequenceReference:as,ListLimit:Fe},yt={DateTime:"string",Date:"string",JSON:"unknown",CogniteTimeSeriesReference:"string",CogniteFileReference:"string",CogniteSequenceReference:"string",ListLimit:"number"};var ls=new cs({name:"AggregateFunction",values:{count:{value:"count"},avg:{value:"avg"},sum:{value:"sum"},min:{value:"min"},max:{value:"max"},histogram:{value:"histogram"}}}),_n={function:{type:new he(ls)},property:{type:ht},interval:{type:Oe}},ds=new jn({name:"HistogramBucket",fields:{start:{type:new he(Oe)},count:{type:new he(Oe)}}}),Mn=new jn({name:"AggregateResult",fields:{aggregate:{type:new he(ht)},property:{type:ht},value:{type:Oe},buckets:{type:new ps(new he(ds))},group:{type:ft}}});import{GraphQLObjectType as St,GraphQLNonNull as oe,GraphQLList as ms,GraphQLString as wt,GraphQLBoolean as us}from"graphql";var gs=new St({name:"PageInfo",fields:{endCursor:{type:wt},hasNextPage:{type:new oe(us)}}}),Le=new St({name:"NodeReference",fields:{space:{type:new oe(wt)},externalId:{type:new oe(wt)}}});function Ne(e,t){return new St({name:`${e}Connection`,fields:{items:{type:new oe(new ms(new oe(t)))},pageInfo:{type:new oe(gs)}}})}o(Ne,"makeConnectionType");import{GraphQLInputObjectType as ie,GraphQLList as $,GraphQLNonNull as Hn,GraphQLString as Z,GraphQLBoolean as D,GraphQLFloat as xs,GraphQLInt as ks}from"graphql";import{GraphQLObjectType as fs,GraphQLNonNull as Vn,GraphQLList as ys,GraphQLString as je,GraphQLBoolean as hs,GraphQLInt as ws,GraphQLFloat as Ss,GraphQLEnumType as vs}from"graphql";function Un(e){return e==="String"?je:e==="Boolean"?hs:e==="Int"?ws:e==="Float"?Ss:X[e]??je}o(Un,"scalarForName");function Kn(e){return{typeRegistry:new Map,connectionRegistry:new Map,viewsByExtId:new Map(e.map(t=>[t.externalId,t])),enumRegistry:new Map,enumFilterRegistry:new Map}}o(Kn,"createTypeContext");function Cs(e){let t=e.replace(/[^_A-Za-z0-9]/g,"_");return/^[0-9]/.test(t)&&(t=`_${t}`),t||"_UNKNOWN"}o(Cs,"sanitizeEnumValue");function vt(e,t,n,r){let i=n.enumRegistry.get(e);if(i)return i;let a=new vs({name:e,values:Object.fromEntries(t.map(s=>[Cs(s),{value:s,description:r?.[s]}]))});return n.enumRegistry.set(e,a),a}o(vt,"getOrCreateEnumType");function Gn(e,t){return new fs({name:e.externalId,description:e.description??e.name,fields:o(()=>{let n={space:{type:new Vn(je)},externalId:{type:new Vn(je)}};for(let[r,i,a]of R(e))if(i.kind==="scalar")i.isList?n[r]={type:new ys(Un(i.graphqlType??"String")),description:a}:n[r]={type:Un(i.graphqlType??"String"),description:a};else if(i.kind==="enum"){let s=`${e.externalId}${r.charAt(0).toUpperCase()}${r.slice(1)}`;n[r]={type:vt(s,i.values,t,i.valueNames),description:a}}else if(i.kind==="directRelation"){let s=t.typeRegistry.get(i.targetView.externalId)??Le;n[r]={type:s,description:a}}else if(i.kind==="reverseList"||i.kind==="edge"){let s=i.kind==="reverseList"?i.sourceView.externalId:i.targetView.externalId,p=t.typeRegistry.get(s)??Le,c=t.connectionRegistry.get(s);c||(c=Ne(s,p),t.connectionRegistry.set(s,c)),n[r]={type:c,description:a}}else if(i.kind==="reverseDirect"){let s=t.typeRegistry.get(i.sourceView.externalId)??Le;n[r]={type:s,description:a}}return n},"fields")})}o(Gn,"generateViewObjectType");function se(e,t,n){let r={isNull:{type:D},exists:{type:D},eq:{type:t}};return n.hasIn&&(r.in={type:new $(t)}),n.hasPrefix&&(r.prefix={type:Z}),n.hasRange&&(r.gte={type:t},r.gt={type:t},r.lte={type:t},r.lt={type:t}),n.hasListOps&&(r.containsAny={type:new $(t)},r.containsAll={type:new $(t)},r.overlaps={type:new $(t)}),new ie({name:e,fields:r})}o(se,"makeScalarFilter");var _e=se("StringFilter",Z,{hasIn:!0,hasPrefix:!0}),Es=se("BooleanFilter",D,{}),bs=se("IntFilter",ks,{hasIn:!0,hasRange:!0}),Ps=se("FloatFilter",xs,{hasIn:!0,hasRange:!0}),As=se("DateTimeFilter",X.DateTime,{hasIn:!0,hasRange:!0}),Is=se("DateFilter",X.Date,{hasIn:!0,hasRange:!0}),Ds=new ie({name:"StringListFilter",fields:{isNull:{type:D},exists:{type:D},containsAny:{type:new $(Z)},containsAll:{type:new $(Z)},overlaps:{type:new $(Z)}}}),we=new ie({name:"DirectRelationRef",fields:{space:{type:new Hn(Z)},externalId:{type:new Hn(Z)}}}),$s=new ie({name:"DirectRelationFilter",fields:{isNull:{type:D},exists:{type:D},eq:{type:we},in:{type:new $(we)}}});function Ts(e){switch(e){case"String":return _e;case"Boolean":return Es;case"Int":return bs;case"Float":return Ps;case"DateTime":return As;case"Date":return Is;default:return _e}}o(Ts,"scalarFilterForName");var Bn=["space","externalId"];function qn(e,t,n){let r=t.get(e.externalId),i={};for(let s of Bn)i[s]={type:_e};let a=new Set(Bn);for(let[s,p]of R(e)){if(a.has(s))continue;let c=Te(p),d=Nn(p);if(!(!c&&!d))if(p.kind==="directRelation"){let l={isNull:{type:D},exists:{type:D},eq:{type:we},in:{type:new $(we)}};Ln(p)&&(l.in={type:new $(we)});let m=t.get(p.targetView.externalId);m&&(l.nested={type:m}),i[s]=m?{type:new ie({name:`_${e.externalId}_${s}_Filter`,fields:l})}:{type:$s}}else if(p.kind==="enum"){let l=`${e.externalId}${s.charAt(0).toUpperCase()}${s.slice(1)}`,m=vt(l,p.values,n),g=n.enumFilterRegistry.get(l);g||(g=new ie({name:`${l}Filter`,fields:{isNull:{type:D},exists:{type:D},eq:{type:m},in:{type:new $(m)}}}),n.enumFilterRegistry.set(l,g)),i[s]={type:g}}else if(d)i[s]={type:Ds};else{let l=p.kind==="scalar"?p.graphqlType??"String":"String",m=Ts(l);m&&(i[s]={type:m})}}return{...i,hasData:{type:D},matchAll:{type:D},_and:{type:new $(r)},_or:{type:new $(r)},_not:{type:r}}}o(qn,"generateFilterFields");import{GraphQLEnumType as Qn,GraphQLInputObjectType as Jn,GraphQLList as Rs,GraphQLNonNull as Me,GraphQLString as Fs,GraphQLBoolean as Os}from"graphql";var Ve=new Qn({name:"SortDirection",values:{ASC:{value:"ascending"},DESC:{value:"descending"}}});function Yn(e){let t=[];for(let[r,i]of R(e))Re(i)&&t.push(r);if(t.length===0)return null;let n=new Qn({name:`${e.externalId}SortField`,values:Object.fromEntries(t.map(r=>[r,{value:r}]))});return new Jn({name:`${e.externalId}Sort`,fields:{field:{type:new Me(n)},direction:{type:new Me(Ve)},nullsFirst:{type:Os}}})}o(Yn,"generateSortInput");var zn=new Jn({name:"SearchSort",fields:{property:{type:new Me(new Rs(new Me(Fs)))},direction:{type:Ve}}});function Xn(e){let t=e.filter(ye),n=Kn(t);for(let l of t){let m=Gn(l,n);n.typeRegistry.set(l.externalId,m)}let r=new Map;for(let l of t){let m=new Wn({name:`${l.externalId}Filter`,fields:o(()=>qn(l,r,n),"fields")});r.set(l.externalId,m)}let i={};for(let l of t){let m=l.externalId,g=n.typeRegistry.get(m),f=n.connectionRegistry.get(m);f||(f=Ne(m,g),n.connectionRegistry.set(m,f));let h=r.get(m),w=Yn(l),u={limit:{type:Fe},cursor:{type:ee},filter:{type:h}};w&&(u.sort={type:new ae(w)}),i[`query${m}`]={type:new O(f),args:u},i[`get${m}ById`]={type:g,args:{space:{type:new O(ee)},externalId:{type:new O(ee)}}},i[`count${m}`]={type:new O(js),args:{filter:{type:h}}},i[`search${m}`]={type:new O(f),args:{query:{type:ee},limit:{type:Fe},filter:{type:h},sort:{type:new ae(new O(zn))},properties:{type:new ae(new O(ee))}}},i[`aggregate${m}`]={type:new O(new ae(new O(Mn))),args:{filter:{type:h},aggregates:{type:new ae(new O(new Wn({name:`${m}AggregateRequest`,fields:_n})))},groupBy:{type:new ae(new O(ee))},query:{type:ee}}}}let a=[];for(let[l,m]of n.typeRegistry)a.push({name:m.name,source:`typeRegistry[${l}]`});for(let[l,m]of n.connectionRegistry)a.push({name:m.name,source:`connectionRegistry[${l}]`});let s=new Map;for(let{name:l,source:m}of a)s.has(l)||s.set(l,[]),s.get(l).push(m);for(let[l,m]of s)m.length>1&&console.error(`[dune] duplicate type "${l}" from: ${m.join(", ")}`);let p=new Ls({query:new Ns({name:"Query",fields:i}),types:[Ve,...Object.values(X),...n.enumRegistry.values()]}),c=new Map;for(let l of t){let m=new Map;for(let[g,f]of R(l))m.set(g,f);c.set(l.externalId,{view:{space:l.space,externalId:l.externalId,version:l.version},properties:m})}let d={view(l){let m=c.get(l.externalId);if(!m)throw new Error(`SchemaKnowledge: no view for externalId "${l.externalId}"`);return m},property(l,m){return c.get(l.externalId)?.properties.get(m)}};return{schema:p,sdl:_s(p),schemaKnowledge:d}}o(Xn,"buildSchema");async function Zn(e,t){let r=(await t.dataModels.retrieve([{space:e.space,externalId:e.dataModelExternalId,version:e.dataModelVersion}],{inlineViews:!1})).items[0];if(!r)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} not found`);if(!r.views?.length)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} has no views`);let i=r.views.map(s=>({space:s.space,externalId:s.externalId,version:s.version}));return(await t.views.retrieve(i,{includeInheritedProperties:!0})).items}o(Zn,"fetchViews");import{GraphQLObjectType as Ms,GraphQLNonNull as Vs,GraphQLList as Us,isScalarType as Ks,isEnumType as Gs,parse as Hs,print as Bs}from"graphql";function Ct(e,t){let n=e.getType(t);if(!(n instanceof Ms))return[];let r=n.getFields(),i=[];for(let[a,s]of Object.entries(r)){let p=s.type;for(;p instanceof Vs||p instanceof Us;)p=p.ofType;(Ks(p)||Gs(p))&&i.push(a)}return i}o(Ct,"scalarFieldsFor");function qs(e,t){let n=Ct(e,t),r=["space","externalId"];for(let i of["name","description"])n.includes(i)&&r.push(i);return r.join(" ")}o(qs,"minimalRelationFields");function er(e,t,n){let r=[];for(let[i,a]of R(e))if(a.kind==="directRelation"||a.kind==="reverseDirect"){let s=a.kind==="directRelation"?a.targetView.externalId:a.sourceView.externalId;if(n)r.push(`${i} { ${qs(t,s)} }`);else{let c=["space","externalId",...Ct(t,s).filter(d=>d!=="space"&&d!=="externalId")];r.push(`${i} { ${c.join(" ")} }`)}}else!n&&(a.kind==="reverseList"||a.kind==="edge")&&r.push(`${i} { items { space externalId } pageInfo { hasNextPage endCursor } }`);return r}o(er,"relationFieldsFor");function tr(e,t,n,r){return`query ${e}(${t}) {
108
111
  ${e}(${n}) {
109
112
  items {
110
113
  ${r}
111
114
  }
112
115
  pageInfo { hasNextPage endCursor }
113
116
  }
114
- }`}o(qn,"paginatedOp");function Qn(e,t){let n=e.externalId,r=gt(t,n),i=Bn(e,t,!0),s=Bn(e,t,!1),a=[...r,...i].join(`
115
- `),p=[...r,...s].join(`
116
- `),c=!!t.getType(`${n}Sort`),d=qn(`query${n}`,c?`$limit: ListLimit, $cursor: String, $filter: ${n}Filter, $sort: [${n}Sort!]`:`$limit: ListLimit, $cursor: String, $filter: ${n}Filter`,c?"limit: $limit, cursor: $cursor, filter: $filter, sort: $sort":"limit: $limit, cursor: $cursor, filter: $filter",a),l=qn(`search${n}`,`$query: String, $limit: ListLimit, $filter: ${n}Filter, $sort: [SearchSort!], $properties: [String!]`,"query: $query, limit: $limit, filter: $filter, sort: $sort, properties: $properties",a),m=`query get${n}ById($space: String!, $externalId: String!) {
117
+ }`}o(tr,"paginatedOp");function nr(e,t){let n=e.externalId,r=Ct(t,n),i=er(e,t,!0),a=er(e,t,!1),s=[...r,...i].join(`
118
+ `),p=[...r,...a].join(`
119
+ `),c=!!t.getType(`${n}Sort`),d=tr(`query${n}`,c?`$limit: ListLimit, $cursor: String, $filter: ${n}Filter, $sort: [${n}Sort!]`:`$limit: ListLimit, $cursor: String, $filter: ${n}Filter`,c?"limit: $limit, cursor: $cursor, filter: $filter, sort: $sort":"limit: $limit, cursor: $cursor, filter: $filter",s),l=tr(`search${n}`,`$query: String, $limit: ListLimit, $filter: ${n}Filter, $sort: [SearchSort!], $properties: [String!]`,"query: $query, limit: $limit, filter: $filter, sort: $sort, properties: $properties",s),m=`query get${n}ById($space: String!, $externalId: String!) {
117
120
  get${n}ById(space: $space, externalId: $externalId) {
118
121
  ${p}
119
122
  }
@@ -128,26 +131,26 @@ Examples:
128
131
  buckets { start count }
129
132
  group
130
133
  }
131
- }`;return Is(Ps([d,m,g,l,f].join(`
134
+ }`;return Bs(Hs([d,m,g,l,f].join(`
132
135
 
133
- `)))}o(Qn,"generateViewOperations");function $s(e){return{availableOnList:e.kind==="scalar",returnsMany:e.kind==="reverseList"||e.kind==="edge",filterable:Pe(e),sortable:Ie(e)}}o($s,"fetchCharacteristics");function Jn(e){return{generatedAt:new Date().toISOString(),views:e.map(t=>({space:t.space,externalId:t.externalId,version:t.version,properties:Object.fromEntries(D(t).map(([n,r])=>[n,{kind:r.kind,fetch:$s(r)}]))}))}}o(Jn,"buildSdkMetadata");async function zn(e,t,n){let r=await Hn(e,t),i=new Set,s=r.filter(u=>i.has(u.externalId)?(console.error(`[dune] dedup: dropped ${u.space}/${u.externalId} (duplicate externalId)`),!1):(i.add(u.externalId),!0));console.error(`[dune] views after dedup: ${s.length} (was ${r.length})`);let{schema:a,sdl:p}=Gn(s),c=s.filter(ue),d=H(n,e.name);Rs(d,{recursive:!0,force:!0}),Ds(d,{recursive:!0}),se(H(d,"schema.graphql"),p,"utf-8"),se(H(d,"sdk-metadata.json"),JSON.stringify(Jn(c),null,2),"utf-8"),se(H(d,"views.generated.ts"),`import type { ViewDefinition } from '@cognite/sdk';
136
+ `)))}o(nr,"generateViewOperations");function Qs(e){return{availableOnList:e.kind==="scalar",returnsMany:e.kind==="reverseList"||e.kind==="edge",filterable:Te(e),sortable:Re(e)}}o(Qs,"fetchCharacteristics");function rr(e){return{generatedAt:new Date().toISOString(),views:e.map(t=>({space:t.space,externalId:t.externalId,version:t.version,properties:Object.fromEntries(R(t).map(([n,r])=>[n,{kind:r.kind,fetch:Qs(r)}]))}))}}o(rr,"buildSdkMetadata");async function ir(e,t,n){let r=await Zn(e,t),i=new Set,a=r.filter(u=>i.has(u.externalId)?(console.error(`[dune] dedup: dropped ${u.space}/${u.externalId} (duplicate externalId)`),!1):(i.add(u.externalId),!0));console.error(`[dune] views after dedup: ${a.length} (was ${r.length})`);let{schema:s,sdl:p}=Xn(a),c=a.filter(ye),d=H(n,e.name);zs(d,{recursive:!0,force:!0}),Js(d,{recursive:!0}),pe(H(d,"schema.graphql"),p,"utf-8"),pe(H(d,"sdk-metadata.json"),JSON.stringify(rr(c),null,2),"utf-8"),pe(H(d,"views.generated.ts"),`import type { ViewDefinition } from '@cognite/sdk';
134
137
 
135
138
  // Auto-generated \u2014 do not edit.
136
139
  export const views: ViewDefinition[] = ${JSON.stringify(c,null,2)};
137
- `,"utf-8"),await Yn({schema:p,generates:{[H(d,"types.generated.ts")]:{plugins:["typescript"],config:{scalars:ct}}}},!0);for(let u of c){let h=Qn(u,a),S=H(d,`${u.externalId}.generated.ts`);await Yn({schema:p,documents:h,generates:{[S]:{plugins:["typescript-operations","typescript-generic-sdk"],config:{scalars:ct,namespacedImportName:"Types"}}}},!0);let C=Ts(S,"utf-8");C=C.replace(/^import \{ DocumentNode \} from 'graphql';$/m,"import type { DocumentNode } from 'graphql';").replace(/Requester<C = \{\}>/g,"Requester<C = Record<string, never>>"),C.includes("import type * as Types")||(C=C.replace(/^import type \{ DocumentNode \} from 'graphql';$/m,`import type { DocumentNode } from 'graphql';
138
- import type * as Types from './types.generated.js';`)),se(S,C)}let l=c.map(u=>u.externalId).sort((u,h)=>u.localeCompare(h)),m=o(u=>u.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[\s_-]+/).filter(Boolean).map(h=>h.charAt(0).toUpperCase()+h.slice(1).toLowerCase()).join(""),"normalizeTypeName"),g=[...l.map(u=>`import { getSdk as get${u}Sdk } from './${u}.generated.js';`),"import { views } from './views.generated.js';"].sort((u,h)=>{let S=o(C=>C.match(/from '(\.\/[^']+)'/)?.[1]??"","path");return S(u).localeCompare(S(h),void 0,{sensitivity:"base"})}).join(`
140
+ `,"utf-8"),await or({schema:p,generates:{[H(d,"types.generated.ts")]:{plugins:["typescript"],config:{scalars:yt}}}},!0);for(let u of c){let y=nr(u,s),S=H(d,`${u.externalId}.generated.ts`);await or({schema:p,documents:y,generates:{[S]:{plugins:["typescript-operations","typescript-generic-sdk"],config:{scalars:yt,namespacedImportName:"Types"}}}},!0);let v=Ys(S,"utf-8");v=v.replace(/^import \{ DocumentNode \} from 'graphql';$/m,"import type { DocumentNode } from 'graphql';").replace(/Requester<C = \{\}>/g,"Requester<C = Record<string, never>>"),v.includes("import type * as Types")||(v=v.replace(/^import type \{ DocumentNode \} from 'graphql';$/m,`import type { DocumentNode } from 'graphql';
141
+ import type * as Types from './types.generated.js';`)),pe(S,v)}let l=c.map(u=>u.externalId).sort((u,y)=>u.localeCompare(y)),m=o(u=>u.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[\s_-]+/).filter(Boolean).map(y=>y.charAt(0).toUpperCase()+y.slice(1).toLowerCase()).join(""),"normalizeTypeName"),g=[...l.map(u=>`import { getSdk as get${u}Sdk } from './${u}.generated.js';`),"import { views } from './views.generated.js';"].sort((u,y)=>{let S=o(v=>v.match(/from '(\.\/[^']+)'/)?.[1]??"","path");return S(u).localeCompare(S(y),void 0,{sensitivity:"base"})}).join(`
139
142
  `),f=l.map(u=>` ...get${u}Sdk(requester),`).join(`
140
- `),y=l.map(u=>{let h=m(u);return`export type {
141
- ${["query","get","count","search","aggregate"].flatMap(k=>{let T=k==="get"?`Get${h}ById`:`${k.charAt(0).toUpperCase()+k.slice(1)}${h}`;return[` ${T}Query`,` ${T}QueryVariables`]}).join(`,
143
+ `),h=l.map(u=>{let y=m(u);return`export type {
144
+ ${["query","get","count","search","aggregate"].flatMap(x=>{let b=x==="get"?`Get${y}ById`:`${x.charAt(0).toUpperCase()+x.slice(1)}${y}`;return[` ${b}Query`,` ${b}QueryVariables`]}).join(`,
142
145
  `)},
143
146
  } from './${u}.generated.js';`}).join(`
144
- `);se(H(d,"index.ts"),`import { createDuneRuntimeFromViews } from '@cognite/cli';
147
+ `);pe(H(d,"index.ts"),`import { createDuneRuntimeFromViews } from '@cognite/cli';
145
148
  import type { CogniteClient } from '@cognite/sdk';
146
149
 
147
150
  ${g}
148
151
 
149
152
  export * from './types.generated.js';
150
- ${y}
153
+ ${h}
151
154
 
152
155
  // Internal \u2014 merges all per-view getSdk() functions.
153
156
  // Not exported: callers use createSdk() instead.
@@ -169,7 +172,7 @@ export function createSdk(client: CogniteClient): Sdk {
169
172
  return makeSdk(runtime.requester);
170
173
  }
171
174
  `,"utf-8");let w=l.flatMap(u=>[` query${u}: vi.fn(() => Promise.resolve({ query${u}: { items: [], pageInfo: { hasNextPage: false, endCursor: null } } })),`,` get${u}ById: vi.fn(() => Promise.resolve({ get${u}ById: null })),`,` count${u}: vi.fn(() => Promise.resolve({ count${u}: 0 })),`,` search${u}: vi.fn(() => Promise.resolve({ search${u}: { items: [], pageInfo: { hasNextPage: false, endCursor: null } } })),`,` aggregate${u}: vi.fn(() => Promise.resolve({ aggregate${u}: [] })),`]).join(`
172
- `);return se(H(d,"test-helpers.ts"),`import { vi } from 'vitest';
175
+ `);return pe(H(d,"test-helpers.ts"),`import { vi } from 'vitest';
173
176
 
174
177
  import type { Sdk } from './index.js';
175
178
 
@@ -179,27 +182,27 @@ ${w}
179
182
  ...overrides,
180
183
  } as Sdk;
181
184
  }
182
- `,"utf-8"),{sdkDir:d,viewCount:c.length}}o(zn,"generateSdk");var Ne=Symbol("BACK");async function er(e,t={}){let n=process.cwd();$(n);let r=e.deployments[0],{baseUrl:i,project:s}=r;if(t.interactive){console.log(`Starting browser login...
183
- `);let c=await ve(t.orgHint??r.org??void 0);if(!c?.access_token)throw new Error("No access token received");return console.log(`
185
+ `,"utf-8"),{sdkDir:d,viewCount:c.length}}o(ir,"generateSdk");var Ue=Symbol("BACK");async function cr(e,t={}){let n=process.cwd();P(n);let r=e.deployments[0],{baseUrl:i,project:a}=r;if(t.interactive){console.log(`Starting browser login...
186
+ `);let c=await Ae(t.orgHint??r.org??void 0);if(!c?.access_token)throw new Error("No access token received");return console.log(`
184
187
  \u2705 Authentication successful!
185
- `),{token:c.access_token,baseUrl:i,project:s}}if(process.env.COGNITE_TOKEN)return{token:process.env.COGNITE_TOKEN,baseUrl:i,project:s};let a=O(r);if(a.length>0)throw new Error(`Missing deployment credentials (${a.join(", ")}). Set COGNITE_TOKEN in .env, configure deployClientId/deploySecretName, or run with --interactive for browser login.`);let p=await ce(r);return console.log(`\u2705 Authenticated
186
- `),{token:p,baseUrl:i,project:s}}o(er,"resolveAuth");async function ht(e){let t=await import("enquirer"),n=t.default?.[e]??t[e];if(typeof n!="function")throw new Error(`Enquirer class "${e}" not found`);return n}o(ht,"getEnquirerClass");async function yt(e,t,n){let r=await ht("Select"),i=t.map((c,d)=>({name:n(c,d),value:d})),a=await new r({message:e,choices:i.map(c=>c.name)}).run(),p=i.findIndex(c=>c.name===a);return t[p]}o(yt,"pick");async function Ns(e,t,n){let r=await ht("AutoComplete"),i=t.map((l,m)=>n(l,m)),s=new Map(i.map((l,m)=>[l,m])),p=await new r({message:e,limit:12,choices:i}).run();if(s.has(p))return t[s.get(p)];let c=o(l=>String(l).replace(/\[[0-9;]*m/g,"").trim(),"clean"),d=c(p);for(let[l,m]of s)if(c(l)===d)return t[m];for(let[l,m]of s)if(c(l).includes(d)||d.includes(c(l)))return t[m];throw new Error(`Could not match selection "${p}" to any item`)}o(Ns,"searchPick");async function _s(e,t=""){let n=await ht("Input");return new n({message:e,initial:t}).run()}o(_s,"ask");async function js(e,t,n={}){let r=await fetch(e,{method:n.method??"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:n.body!==void 0?JSON.stringify(n.body):void 0});if(!r.ok){let i=await r.text().catch(()=>"");throw new Error(`CDF API error ${r.status} ${r.statusText}: ${i}`)}return r.json()}o(js,"cdfFetch");async function Ms(e,t,n){return(await js(`${e}/api/v1/projects/${t}/models/datamodels?includeGlobal=true&limit=1000`,n)).items??[]}o(Ms,"fetchDataModels");async function Vs(e,t={}){let n=process.cwd();process.chdir(e);try{$(e);let r=v(e),{token:i,baseUrl:s,project:a}=await er(r,t),p=null;async function c(){return p||(p=await Ms(s,a,i),p.sort((g,f)=>`${g.space}/${g.externalId}`.localeCompare(`${f.space}/${f.externalId}`))),p}o(c,"getModels");let d={chosenModel:null,sdkName:null},l=[async()=>{console.log(`
188
+ `),{token:c.access_token,baseUrl:i,project:a}}if(process.env.COGNITE_TOKEN)return{token:process.env.COGNITE_TOKEN,baseUrl:i,project:a};let s=T(r);if(s.length>0)throw new Error(`Missing deployment credentials (${s.join(", ")}). Set COGNITE_TOKEN in .env, configure deployClientId/deploySecretName, or run with --interactive for browser login.`);let p=await me(r);return console.log(`\u2705 Authenticated
189
+ `),{token:p,baseUrl:i,project:a}}o(cr,"resolveAuth");async function Et(e){let t=await import("enquirer"),n=t.default?.[e]??t[e];if(typeof n!="function")throw new Error(`Enquirer class "${e}" not found`);return n}o(Et,"getEnquirerClass");async function kt(e,t,n){let r=await Et("Select"),i=t.map((c,d)=>({name:n(c,d),value:d})),s=await new r({message:e,choices:i.map(c=>c.name)}).run(),p=i.findIndex(c=>c.name===s);return t[p]}o(kt,"pick");async function ea(e,t,n){let r=await Et("AutoComplete"),i=t.map((l,m)=>n(l,m)),a=new Map(i.map((l,m)=>[l,m])),p=await new r({message:e,limit:12,choices:i}).run();if(a.has(p))return t[a.get(p)];let c=o(l=>String(l).replace(/\[[0-9;]*m/g,"").trim(),"clean"),d=c(p);for(let[l,m]of a)if(c(l)===d)return t[m];for(let[l,m]of a)if(c(l).includes(d)||d.includes(c(l)))return t[m];throw new Error(`Could not match selection "${p}" to any item`)}o(ea,"searchPick");async function ta(e,t=""){let n=await Et("Input");return new n({message:e,initial:t}).run()}o(ta,"ask");async function na(e,t,n={}){let r=await fetch(e,{method:n.method??"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:n.body!==void 0?JSON.stringify(n.body):void 0});if(!r.ok){let i=await r.text().catch(()=>"");throw new Error(`CDF API error ${r.status} ${r.statusText}: ${i}`)}return r.json()}o(na,"cdfFetch");async function ra(e,t,n){return(await na(`${e}/api/v1/projects/${t}/models/datamodels?includeGlobal=true&limit=1000`,n)).items??[]}o(ra,"fetchDataModels");async function oa(e,t={}){let n=process.cwd();process.chdir(e);try{P(e);let r=k(e),{token:i,baseUrl:a,project:s}=await cr(r,t),p=null;async function c(){return p||(p=await ra(a,s,i),p.sort((g,f)=>`${g.space}/${g.externalId}`.localeCompare(`${f.space}/${f.externalId}`))),p}o(c,"getModels");let d={chosenModel:null,sdkName:null},l=[async()=>{console.log(`
187
190
  \u{1F510} Fetching data models...`);let g=await c();if(g.length===0)throw new Error("No data models found.");return console.log(`\u{1F50D} Found ${g.length} model(s). Type to search.
188
- `),d.chosenModel=await Ns("\u{1F4E6} Select a data model:",g,f=>`${f.space} \u2192 ${f.externalId} / ${f.version}${f.name?` \u2014 ${f.name}`:""}`),!0},async()=>{let g=d.chosenModel.externalId.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9-_]/g,"-").toLowerCase(),f=await _s(`
189
- SDK name (folder under src/generated_sdks/, "back" to go back):`,g);if(f.toLowerCase()==="back")return Ne;let u=(JSON.parse(ye(_(e,"app.json"),"utf-8")).generatedSdks??[]).find(h=>h.name===f);if(u){console.log(`
190
- \u26A0\uFE0F An SDK named "${f}" already exists in app.json:`),console.log(` ${u.dataModelSpace} / ${u.dataModelExternalId} @ ${u.dataModelVersion}`);let h=await yt("What would you like to do?",["Replace existing entry","Pick a different name","Cancel"],S=>S);if(h==="Cancel"&&(console.log(`
191
+ `),d.chosenModel=await ea("\u{1F4E6} Select a data model:",g,f=>`${f.space} \u2192 ${f.externalId} / ${f.version}${f.name?` \u2014 ${f.name}`:""}`),!0},async()=>{let g=d.chosenModel.externalId.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9-_]/g,"-").toLowerCase(),f=await ta(`
192
+ SDK name (folder under src/generated_sdks/, "back" to go back):`,g);if(f.toLowerCase()==="back")return Ue;let u=(JSON.parse(Se(V(e,"app.json"),"utf-8")).generatedSdks??[]).find(y=>y.name===f);if(u){console.log(`
193
+ \u26A0\uFE0F An SDK named "${f}" already exists in app.json:`),console.log(` ${u.dataModelSpace} / ${u.dataModelExternalId} @ ${u.dataModelVersion}`);let y=await kt("What would you like to do?",["Replace existing entry","Pick a different name","Cancel"],S=>S);if(y==="Cancel"&&(console.log(`
191
194
  Cancelled.
192
- `),process.exit(0)),h==="Pick a different name")return Ne}return d.sdkName=f,!0},async()=>{let g={name:d.sdkName,dataModelSpace:d.chosenModel.space,dataModelExternalId:d.chosenModel.externalId,dataModelVersion:String(d.chosenModel.version)};console.log(`
193
- \u2500\u2500 Summary \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(` Space: ${g.dataModelSpace}`),console.log(` Model: ${g.dataModelExternalId} @ ${g.dataModelVersion}`),console.log(" Views: all"),console.log(` SDK name: ${d.sdkName}`),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let f=await yt("Write to app.json?",["Yes","Back","Cancel"],y=>y);return f==="Back"?Ne:(f==="Cancel"&&(console.log(`
195
+ `),process.exit(0)),y==="Pick a different name")return Ue}return d.sdkName=f,!0},async()=>{let g={name:d.sdkName,dataModelSpace:d.chosenModel.space,dataModelExternalId:d.chosenModel.externalId,dataModelVersion:String(d.chosenModel.version)};console.log(`
196
+ \u2500\u2500 Summary \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(` Space: ${g.dataModelSpace}`),console.log(` Model: ${g.dataModelExternalId} @ ${g.dataModelVersion}`),console.log(" Views: all"),console.log(` SDK name: ${d.sdkName}`),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let f=await kt("Write to app.json?",["Yes","Back","Cancel"],h=>h);return f==="Back"?Ue:(f==="Cancel"&&(console.log(`
194
197
  Cancelled.
195
- `),process.exit(0)),Us(e,g),!0)}],m=0;for(;m<l.length;)await l[m]()===Ne?(m=Math.max(0,m-1),console.log("")):m++;return{sdkName:d.sdkName,auth:{token:i,baseUrl:s,project:a}}}finally{process.chdir(n)}}o(Vs,"runWizard");function Us(e,t){let n=_(e,"app.json"),r=JSON.parse(ye(n,"utf-8"));r.generatedSdks=[...r.generatedSdks??[],t],ft(n,JSON.stringify(r,null,2)+`
196
- `);let i=_(e,".dune","sdk-configs");try{Zn(i)||Fs(i,{recursive:!0}),ft(_(i,`${t.name}.json`),JSON.stringify(t,null,2)+`
198
+ `),process.exit(0)),ia(e,g),!0)}],m=0;for(;m<l.length;)await l[m]()===Ue?(m=Math.max(0,m-1),console.log("")):m++;return{sdkName:d.sdkName,auth:{token:i,baseUrl:a,project:s}}}finally{process.chdir(n)}}o(oa,"runWizard");function ia(e,t){let n=V(e,"app.json"),r=JSON.parse(Se(n,"utf-8"));r.generatedSdks=[...r.generatedSdks??[],t],xt(n,JSON.stringify(r,null,2)+`
199
+ `);let i=V(e,".dune","sdk-configs");try{pr(i)||Ws(i,{recursive:!0}),xt(V(i,`${t.name}.json`),JSON.stringify(t,null,2)+`
197
200
  `),console.log(`
198
201
  \u2705 Added "${t.name}" to app.json`),console.log(` Config saved to .dune/sdk-configs/${t.name}.json`)}catch{console.log(`
199
- \u2705 Added "${t.name}" to app.json`)}t.instanceSpaces&&console.log(` Scoped to: ${t.instanceSpaces.join(", ")}`),t.views&&console.log(` Views: ${t.views.map(s=>s.externalId).join(", ")}`),console.log("")}o(Us,"writeEntry");async function Wn(e,t,n,r={}){let i=n??process.cwd();$(i);let s=v(i),p=(JSON.parse(ye(_(i,"app.json"),"utf-8")).generatedSdks??[]).find(w=>w.name===e);p||(console.error(`No SDK named "${e}" in generatedSdks`),process.exit(1));let{token:c}=t??await er(s,r),d=s.deployments[0],l=new Os({appId:s.externalId,project:d.project,baseUrl:d.baseUrl,oidcTokenProvider:o(async()=>c,"oidcTokenProvider")});await l.authenticate();let m=_(i,"src/generated_sdks");console.log(`
200
- \u2699\uFE0F Generating "${p.name}" (${p.dataModelSpace}/${p.dataModelExternalId}@${p.dataModelVersion})...`);let{sdkDir:g,viewCount:f}=await zn({name:p.name,space:p.dataModelSpace,dataModelExternalId:p.dataModelExternalId,dataModelVersion:p.dataModelVersion},l,m);console.log(`\u2705 Generated SDK for ${f} view(s) \u2192 ${g}`);let y=_(i,"package.json");if(Zn(y)){let w=JSON.parse(ye(y,"utf-8")),u=w.dependencies??{},h=[];u.graphql||(u.graphql="^16.0.0",h.push("graphql")),u["graphql-tag"]||(u["graphql-tag"]="^2.12.0",h.push("graphql-tag"));let S=r.linkLocal?`file:${_(Ls(import.meta.url),"../../..")}`:"^1.1.0-alpha.50";u["@cognite/cli"]!==S&&(u["@cognite/cli"]=S,h.push("@cognite/cli")),h.length>0&&(w.dependencies=u,ft(y,JSON.stringify(w,null,2)+`
202
+ \u2705 Added "${t.name}" to app.json`)}t.instanceSpaces&&console.log(` Scoped to: ${t.instanceSpaces.join(", ")}`),t.views&&console.log(` Views: ${t.views.map(a=>a.externalId).join(", ")}`),console.log("")}o(ia,"writeEntry");async function sr(e,t,n,r={}){let i=n??process.cwd();P(i);let a=k(i),p=(JSON.parse(Se(V(i,"app.json"),"utf-8")).generatedSdks??[]).find(w=>w.name===e);p||(console.error(`No SDK named "${e}" in generatedSdks`),process.exit(1));let{token:c}=t??await cr(a,r),d=a.deployments[0],l=new Zs({appId:a.externalId,project:d.project,baseUrl:d.baseUrl,oidcTokenProvider:o(async()=>c,"oidcTokenProvider")});await l.authenticate();let m=V(i,"src/generated_sdks");console.log(`
203
+ \u2699\uFE0F Generating "${p.name}" (${p.dataModelSpace}/${p.dataModelExternalId}@${p.dataModelVersion})...`);let{sdkDir:g,viewCount:f}=await ir({name:p.name,space:p.dataModelSpace,dataModelExternalId:p.dataModelExternalId,dataModelVersion:p.dataModelVersion},l,m);console.log(`\u2705 Generated SDK for ${f} view(s) \u2192 ${g}`);let h=V(i,"package.json");if(pr(h)){let w=JSON.parse(Se(h,"utf-8")),u=w.dependencies??{},y=[];u.graphql||(u.graphql="^16.0.0",y.push("graphql")),u["graphql-tag"]||(u["graphql-tag"]="^2.12.0",y.push("graphql-tag"));let S=r.linkLocal?`file:${V(Xs(import.meta.url),"../../..")}`:"^1.1.0-alpha.51";u["@cognite/cli"]!==S&&(u["@cognite/cli"]=S,y.push("@cognite/cli")),y.length>0&&(w.dependencies=u,xt(h,JSON.stringify(w,null,2)+`
201
204
  `,"utf-8"),console.log(`
202
- \u{1F4E6} Updated package.json: ${h.join(", ")} (run npm install)`))}}o(Wn,"generate");function Xn(e){return{interactive:e.interactive,orgHint:e.org,linkLocal:e.linkLocal}}o(Xn,"sdkCommandOptions");function tr(e){e.command("sdk").summary("Add or regenerate typed GraphQL SDKs from CDF data models").description(`Add or regenerate typed GraphQL SDKs from CDF data models.
205
+ \u{1F4E6} Updated package.json: ${y.join(", ")} (run npm install)`))}}o(sr,"generate");function ar(e){return{interactive:e.interactive,orgHint:e.org,linkLocal:e.linkLocal}}o(ar,"sdkCommandOptions");function lr(e){e.command("sdk").summary("Add or regenerate typed GraphQL SDKs from CDF data models").description(`Add or regenerate typed GraphQL SDKs from CDF data models.
203
206
  Run with --interactive for the guided wizard (pick a data model, update app.json, generate types).`).option("--interactive","Run the guided wizard (pick data model, update app.json, generate types)").option("--org <org>","Organization hint for login (only with --interactive)").option("--link-local","Point @cognite/cli at the local monorepo package (default: use published version from npm)").addHelpText("after",`
204
207
  Examples:
205
208
  npx @cognite/cli apps sdk --interactive Guided setup: pick a data model, add to app.json, generate types
@@ -207,36 +210,37 @@ Examples:
207
210
  npx @cognite/cli apps sdk generate my-sdk Regenerate a specific SDK by name
208
211
 
209
212
  Without --interactive, this command only shows help. Use --interactive for the guided wizard.
210
- Non-interactive auth for generate uses the same env vars as apps deploy (COGNITE_TOKEN or deployment credentials).`).action(async function(n){if(!n.interactive){this.outputHelp();return}let r=process.cwd(),i=Xn(n),{sdkName:s,auth:a}=await Vs(r,i);await Wn(s,a,r,i)}).command("generate [name]").description("Regenerate TypeScript types for an existing SDK from app.json").option("--interactive","Authenticate via browser login (same as apps deploy --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").option("--link-local","Point @cognite/cli at the local monorepo package (default: use published version from npm)").action(async(n,r)=>{let i=process.cwd(),s=Xn(r),p=JSON.parse(ye(_(i,"app.json"),"utf-8")).generatedSdks??[];p.length===0&&(console.error('No generatedSdks entries found in app.json. Run "cognite apps sdk --interactive" first.'),process.exit(1));let c=n??(p.length===1?p[0].name:await yt("Which SDK to regenerate?",p,d=>d.name));await Wn(typeof c=="string"?c:c.name,void 0,i,s)})}o(tr,"registerSdkCommand");function nr(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return fn(t),xn(t),kn(t),vn(t),Xt(t),Lt(t),tr(t),t}o(nr,"registerAppsCommand");import{existsSync as La,mkdirSync as Oa,writeFileSync as Na}from"fs";import{dirname as Pt,join as It}from"path";import{execFile as Gs}from"child_process";import{promisify as Hs}from"util";import{platform as Ks}from"os";function X(e={}){let{platform:t=Ks}=e;return t()==="darwin"}o(X,"isMacOS");var rr="cognite-flows",Bs=Hs(Gs),or=o((e,t)=>Bs(e,t),"defaultExecFile"),qs=-25300,Qs=qs&255;function Js(e){if(!(e instanceof Error)||!("code"in e)||e.code!==Qs)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(Js,"isKeychainNotFoundError");async function ir(e,t,n={}){if(!X(n))throw new Error("Keychain storage is only supported on macOS");let{execFile:r=or}=n;await r("security",["add-generic-password","-a",e,"-s",rr,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(ir,"storeKeyInKeychain");async function sr(e,t={}){if(!X(t))return null;let{execFile:n=or}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",rr,"-w"]);return Buffer.from(r.trim(),"base64").toString("utf-8")}catch(r){if(Js(r))return null;throw r}}o(sr,"readKeyFromKeychain");import{pbkdf2 as Ws,randomBytes as Xs}from"crypto";import{promisify as Zs}from"util";import{CompactEncrypt as ea,base64url as ta,compactDecrypt as ru}from"jose";var Ys=new TextEncoder,zs=new TextDecoder,ar={encode:o(e=>Ys.encode(e),"encode"),decode:o(e=>zs.decode(e),"decode")};var na=Zs(Ws),wt=6e5,ra="sha512",oa="PBKDF2-HMAC-SHA512",ia=16,sa="A256GCM",aa=32,pr=2e6;async function pa(e,t,n){return await na(e,t,n,aa,ra)}o(pa,"deriveKey");async function cr(e,t,n=wt){if(!Number.isInteger(n)||n<1||n>pr)throw new Error(`Invalid iterations: must be an integer between 1 and ${pr}`);let r=Xs(ia),i=await pa(t,r,n);return await new ea(ar.encode(e)).setProtectedHeader({alg:"dir",enc:sa,kdf:oa,kdf_iter:n,kdf_salt:ta.encode(r)}).encrypt(i)}o(cr,"encryptStringAsJwe");import{calculateJwkThumbprint as ca,exportJWK as la,exportPKCS8 as da,exportSPKI as ma,generateKeyPair as ua}from"jose";async function lr(){let{publicKey:e,privateKey:t}=await ua("EdDSA",{extractable:!0}),n=await da(t),r=await ma(e),i=await la(e),s=await ca(i);return{privateKeyPem:n,publicKeyPem:r,kid:s}}o(lr,"generateSigningKeyPair");import{existsSync as fa,readdirSync as ya,readFileSync as ha}from"fs";import{join as _e}from"path";import{homedir as ga}from"os";import{join as dr}from"path";function Z(e={}){let{env:t=process.env,homedir:n=ga}=e,r=t.DUNE_HOME?.trim()||dr(n(),".dune");return{home:r,keysDir:dr(r,"keys")}}o(Z,"getConfig");var je=".pub.pem",St=".key.jwe",wa=".pem",Ct=".meta.json";function mr(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"legacy-unencrypted-file":return`${e.path} (unencrypted \u2014 rotate)`;case"public-only":return"public-only (private key missing)"}}o(mr,"formatLocalKeySource");function Sa(e){return{existsSync:e.existsSync??fa,readdirSync:e.readdirSync??ya,readFileSync:e.readFileSync??((t,n)=>ha(t,n)),isMacOS:e.isMacOS??(()=>X()),readKeyFromKeychain:e.readKeyFromKeychain??(t=>sr(t))}}o(Sa,"resolveDeps");function Ca(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(Ca,"readEmailFromMeta");function xa(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(je)):[]}o(xa,"publicKeyEntries");function va(e){return e.slice(0,-je.length)}o(va,"kidFromPublicKeyFilename");async function ka(e,t,n){if(n.isMacOS()&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let r=_e(t,`${e}${St}`);if(n.existsSync(r))return{kind:"encrypted-file",path:r};let i=_e(t,`${e}${wa}`);return n.existsSync(i)?{kind:"legacy-unencrypted-file",path:i}:{kind:"public-only"}}o(ka,"resolveSource");async function ur(e=Z().keysDir,t={}){let n=Sa(t),r=new Set,i=xa(e,n).flatMap(s=>{let a=va(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 ka(s,e,n),c=_e(e,`${s}${Ct}`),d;try{d=Ca(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:_e(e,a),email:d}}))}o(ur,"discoverLocalKeys");function gr(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(gr,"addMonthsClamped");function xt(e){return e.toISOString().slice(0,10)}o(xt,"formatIsoDate");function fr(e=new Date){return xt(e)}o(fr,"todayIso");import Ea,{Chalk as ba}from"chalk";var vt=new ba({level:0});function yr(e){return e.isTTY?Ea:vt}o(yr,"chalkForStream");function Pa(e){return e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"")}o(Pa,"pemBodyOneLine");function hr(e,t=vt,n=new Date){let r=e.issuedAt??fr(n),i=Pa(e.publicKeyPem),s=" ",a=o((c,d)=>`${s}${t.cyan(c)}${t.dim(":")} ${d}
213
+ Non-interactive auth for generate uses the same env vars as apps deploy (COGNITE_TOKEN or deployment credentials).`).action(async function(n){if(!n.interactive){this.outputHelp();return}let r=process.cwd(),i=ar(n),{sdkName:a,auth:s}=await oa(r,i);await sr(a,s,r,i)}).command("generate [name]").description("Regenerate TypeScript types for an existing SDK from app.json").option("--interactive","Authenticate via browser login (same as apps deploy --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").option("--link-local","Point @cognite/cli at the local monorepo package (default: use published version from npm)").action(async(n,r)=>{let i=process.cwd(),a=ar(r),p=JSON.parse(Se(V(i,"app.json"),"utf-8")).generatedSdks??[];p.length===0&&(console.error('No generatedSdks entries found in app.json. Run "cognite apps sdk --interactive" first.'),process.exit(1));let c=n??(p.length===1?p[0].name:await kt("Which SDK to regenerate?",p,d=>d.name));await sr(typeof c=="string"?c:c.name,void 0,i,a)})}o(lr,"registerSdkCommand");function dr(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return kn(t),$n(t),Rn(t),Tn(t),sn(t),En(t),Ut(t),lr(t),t}o(dr,"registerAppsCommand");import{existsSync as Qa,mkdirSync as Ja,writeFileSync as Ya}from"fs";import{dirname as Ft,join as qe}from"path";import{generateSigningKeyPair as za}from"@cognite/app-sdk/codesigning";import{execFile as aa}from"child_process";import{promisify as pa}from"util";import{platform as sa}from"os";function te(e={}){let{platform:t=sa}=e;return t()==="darwin"}o(te,"isMacOS");var mr="cognite-flows",ca=pa(aa),ur=o((e,t)=>ca(e,t),"defaultExecFile"),la=-25300,da=la&255;function ma(e){if(!(e instanceof Error)||!("code"in e)||e.code!==da)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(ma,"isKeychainNotFoundError");async function gr(e,t,n={}){if(!te(n))throw new Error("Keychain storage is only supported on macOS");let{execFile:r=ur}=n;await r("security",["add-generic-password","-a",e,"-s",mr,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(gr,"storeKeyInKeychain");async function fr(e,t={}){if(!te(t))return null;let{execFile:n=ur}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",mr,"-w"]);return Buffer.from(r.trim(),"base64").toString("utf-8")}catch(r){if(ma(r))return null;throw r}}o(fr,"readKeyFromKeychain");import{pbkdf2 as fa,randomBytes as ya}from"crypto";import{promisify as ha}from"util";import{CompactEncrypt as wa,base64url as Sa,compactDecrypt as Au}from"jose";var ua=new TextEncoder,ga=new TextDecoder,yr={encode:o(e=>ua.encode(e),"encode"),decode:o(e=>ga.decode(e),"decode")};var va=ha(fa),bt=6e5,Ca="sha512",xa="PBKDF2-HMAC-SHA512",ka=16,Ea="A256GCM",ba=32,hr=2e6;async function Pa(e,t,n){return await va(e,t,n,ba,Ca)}o(Pa,"deriveKey");async function wr(e,t,n=bt){if(!Number.isInteger(n)||n<1||n>hr)throw new Error(`Invalid iterations: must be an integer between 1 and ${hr}`);let r=ya(ka),i=await Pa(t,r,n);return await new wa(yr.encode(e)).setProtectedHeader({alg:"dir",enc:Ea,kdf:xa,kdf_iter:n,kdf_salt:Sa.encode(r)}).encrypt(i)}o(wr,"encryptStringAsJwe");import{existsSync as Ia,readdirSync as Da,readFileSync as $a}from"fs";import{join as Ke}from"path";import{homedir as Aa}from"os";import{join as Sr}from"path";function B(e={}){let{env:t=process.env,homedir:n=Aa}=e,r=t.DUNE_HOME?.trim()||Sr(n(),".dune");return{home:r,keysDir:Sr(r,"keys")}}o(B,"getConfig");var Ce=".pub.pem",Pt=".key.jwe",Ta=".pem",At=".meta.json";function vr(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"legacy-unencrypted-file":return`${e.path} (unencrypted \u2014 rotate)`;case"public-only":return"public-only (private key missing)"}}o(vr,"formatLocalKeySource");function Ra(e){return{existsSync:e.existsSync??Ia,readdirSync:e.readdirSync??Da,readFileSync:e.readFileSync??((t,n)=>$a(t,n)),isMacOS:e.isMacOS??(()=>te()),readKeyFromKeychain:e.readKeyFromKeychain??(t=>fr(t))}}o(Ra,"resolveDeps");function Fa(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(Fa,"readEmailFromMeta");function Oa(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(Ce)):[]}o(Oa,"publicKeyEntries");function La(e){return e.slice(0,-Ce.length)}o(La,"kidFromPublicKeyFilename");async function Na(e,t,n){if(n.isMacOS()&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let r=Ke(t,`${e}${Pt}`);if(n.existsSync(r))return{kind:"encrypted-file",path:r};let i=Ke(t,`${e}${Ta}`);return n.existsSync(i)?{kind:"legacy-unencrypted-file",path:i}:{kind:"public-only"}}o(Na,"resolveSource");async function Cr(e=B().keysDir,t={}){let n=Ra(t),r=new Set,i=Oa(e,n).flatMap(a=>{let s=La(a);return!s||r.has(s)?[]:(r.add(s),[{kid:s,entry:a}])});return Promise.all(i.map(async({kid:a,entry:s})=>{let p=await Na(a,e,n),c=Ke(e,`${a}${At}`),d;try{d=Fa(n.readFileSync(c,"utf8"))}catch{}return{kid:a,source:p,publicKeyPath:Ke(e,s),email:d}}))}o(Cr,"discoverLocalKeys");function xr(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth()+t,i=new Date(Date.UTC(n,r+1,0)).getUTCDate(),a=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(n,r,a))}o(xr,"addMonthsClamped");function It(e){return e.toISOString().slice(0,10)}o(It,"formatIsoDate");function kr(e=new Date){return It(e)}o(kr,"todayIso");import ja,{Chalk as _a}from"chalk";var Dt=new _a({level:0});function Er(e){return e.isTTY?ja:Dt}o(Er,"chalkForStream");function Ma(e){return e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"")}o(Ma,"pemBodyOneLine");function br(e,t=Dt,n=new Date){let r=e.issuedAt??kr(n),i=Ma(e.publicKeyPem),a=" ",s=o((c,d)=>`${a}${t.cyan(c)}${t.dim(":")} ${d}
211
214
  `,"kv"),p="";return p+=`
212
215
  ${t.bold("Add this entry to")} ${t.magenta("services/app-hosting/config/signing-keys.yaml")} ${t.bold("under")} ${t.cyan("public_keys:")}
213
216
 
214
217
  `,p+=`${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
215
- `,p+=a("public_key",t.green(i)),p+=a("email",t.yellow(e.email)),p+=a("capabilities",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),p+=a("issued_at",t.green(r)),p+=a("expires",t.green(e.expires)),p+=a("revoked_at",t.dim("null")),p}o(hr,"renderRegistryEntry");import{email as Ia,pipe as Aa,safeParse as $a,string as Da}from"valibot";var Ta=Aa(Da(),Ia());function we(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!$a(Ta,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}o(we,"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 Fa from"enquirer";var Me=3,wr=`Key expiry in months (${1}-${12})`,Sr="Email address for the registry entry",Cr=`Passphrase for the encrypted private key (min ${15} chars)`,xr="Confirm passphrase",vr=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),kr=o(e=>`Passphrases do not match (attempt ${e}/${Me}).
216
- `,"passphraseMismatchMsg"),Er=`Passphrase confirmation failed after ${Me} attempts`;async function bt(e){return Fa.prompt(e)}o(bt,"defaultPrompt");function br(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}o(br,"parserAsValidator");async function Pr(e={}){let{prompt:t=bt}=e,{months:n}=await t({type:"input",name:"months",message:wr,initial:String(6),validate:br(r=>Se(r,"expiry"))});return Se(n,"expiry")}o(Pr,"promptExpiryMonths");async function Ir(e={}){let{prompt:t=bt,gitUserEmail:n=rn}=e,{email:r}=await t({type:"input",name:"email",message:Sr,initial:n(),validate:br(i=>we(i,"email"))});return we(r,"email")}o(Ir,"promptEmail");async function Ar(e={}){let{prompt:t=bt,stderr:n=process.stderr}=e;for(let r=1;r<=Me;r+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:Cr,validate:o(a=>a.length>=15?!0:vr(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:xr});if(i===s)return i;n.write(kr(r))}throw new Error(Er)}o(Ar,"promptPassphrase");function _a(e){return{writeFileSync:e.writeFileSync??Na,mkdirSync:e.mkdirSync??Oa,existsSync:e.existsSync??La,generateSigningKeyPair:e.generateSigningKeyPair??lr,encryptStringAsJwe:e.encryptStringAsJwe??cr,storeKeyInKeychain:e.storeKeyInKeychain??ir,isMacOS:e.isMacOS??X,promptExpiryMonths:e.promptExpiryMonths??Pr,promptEmail:e.promptEmail??Ir,promptPassphrase:e.promptPassphrase??Ar,discoverLocalKeys:e.discoverLocalKeys??(()=>ur())}}o(_a,"resolveDeps");function Dr(e,t={}){let n=_a(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 ~/.dune/keys/ 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").action(i=>Va(i,n)),r.command("list").description("List local signing identities and their storage location").action(()=>ja(n))}o(Dr,"registerKeysCommand");async function ja(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
217
- `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${Z().keysDir}).
218
- `);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,mr(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)}
219
- `);for(let a of r)process.stdout.write(`${s(a)}
220
- `)}o(ja,"handleList");function $r(e,t,n){let r=It(Z().keysDir,`${e}${je}`);return n.mkdirSync(Pt(r),{recursive:!0}),n.writeFileSync(r,t),r}o($r,"writePublicKey");async function Ma(e,t,n,r,i){let s=r??It(Z().keysDir,`${e}${St}`);if(i.mkdirSync(Pt(s),{recursive:!0}),i.existsSync(s))throw new Error(`Refusing to overwrite existing key at ${s}. Delete it first if you really want to regenerate: rm ${s}`);let a=await i.encryptStringAsJwe(t,n);return i.writeFileSync(s,a,{mode:384}),s}o(Ma,"writeEncryptedPrivateKey");async function Va(e,t,n=new Date){let r=e.keychain!==!1&&t.isMacOS()&&!e.output,i=e.expires!==void 0?Se(e.expires):await t.promptExpiryMonths(),s=xt(gr(n,i)),a=e.email!==void 0?we(e.email,"--email"):await t.promptEmail(),p=r?null:await t.promptPassphrase();process.stderr.write(`
218
+ `,p+=s("public_key",t.green(i)),p+=s("email",t.yellow(e.email)),p+=s("capabilities",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),p+=s("issued_at",t.green(r)),p+=s("expires",t.green(e.expires)),p+=s("revoked_at",t.dim("null")),p}o(br,"renderRegistryEntry");import{email as Va,pipe as Ua,safeParse as Ka,string as Ga}from"valibot";var Ha=Ua(Ga(),Va());function xe(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!Ka(Ha,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}o(xe,"parseEmail");function ke(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(ke,"parseExpiryMonths");import Lr from"enquirer";var Ge=3,Pr="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",Ar=`Key expiry in months (${1}-${12})`,Ir="Email address for the registry entry",Dr=`Passphrase for the encrypted private key (min ${15} chars)`,$r="Confirm passphrase",Tr=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),Rr=o(e=>`Passphrases do not match (attempt ${e}/${Ge}).
219
+ `,"passphraseMismatchMsg"),Fr=`Passphrase confirmation failed after ${Ge} attempts`,Or=o(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg");async function Be(e){return Lr.prompt(e)}o(Be,"defaultPrompt");function Rt(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}o(Rt,"parserAsValidator");var qa=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function He(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(!qa.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(He,"parseKid");async function Nr(e={}){let{prompt:t=Be}=e,{kid:n}=await t({type:"input",name:"kid",message:Pr,validate:Rt(He)});return He(n)}o(Nr,"promptKid");async function jr(e={}){let{prompt:t=Be}=e,{months:n}=await t({type:"input",name:"months",message:Ar,initial:String(6),validate:Rt(r=>ke(r,"expiry"))});return ke(n,"expiry")}o(jr,"promptExpiryMonths");async function _r(e={}){let{prompt:t=Be,gitUserEmail:n=ln}=e,{email:r}=await t({type:"input",name:"email",message:Ir,initial:n(),validate:Rt(i=>xe(i,"email"))});return xe(r,"email")}o(_r,"promptEmail");async function Mr(e={}){let{prompt:t=Be,stderr:n=process.stderr}=e;for(let r=1;r<=Ge;r+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:Dr,validate:o(s=>s.length>=15?!0:Tr(),"validate")}),{confirm:a}=await t({type:"password",name:"confirm",message:$r});if(i===a)return i;n.write(Rr(r))}throw new Error(Fr)}o(Mr,"promptPassphrase");async function Vr(e,t={}){let{prompt:n=o(i=>Lr.prompt(i),"prompt")}=t,{confirmed:r}=await n({type:"confirm",name:"confirmed",message:Or(e),initial:!1});return r}o(Vr,"promptConfirmOverwrite");function Wa(e){return{writeFileSync:e.writeFileSync??Ya,mkdirSync:e.mkdirSync??Ja,existsSync:e.existsSync??Qa,generateSigningKeyPair:e.generateSigningKeyPair??za,encryptStringAsJwe:e.encryptStringAsJwe??wr,storeKeyInKeychain:e.storeKeyInKeychain??gr,isMacOS:e.isMacOS??te,promptKid:e.promptKid??Nr,promptExpiryMonths:e.promptExpiryMonths??jr,promptEmail:e.promptEmail??_r,promptPassphrase:e.promptPassphrase??Mr,promptConfirmOverwrite:e.promptConfirmOverwrite??Vr,discoverLocalKeys:e.discoverLocalKeys??(()=>Cr())}}o(Wa,"resolveDeps");function Kr(e,t={}){let n=Wa(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 ~/.dune/keys/ 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").action(i=>ep(i,n)),r.command("list").description("List local signing identities and their storage location").action(()=>Xa(n))}o(Kr,"registerKeysCommand");async function Xa(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
220
+ `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${B().keysDir}).
221
+ `);return}let n=["KID","SOURCE","EMAIL"],r=t.map(s=>[s.kid,vr(s.source),s.email??"\u2014"]),i=n.map((s,p)=>Math.max(s.length,...r.map(c=>c[p].length))),a=o(s=>s.map((p,c)=>p.padEnd(i[c])).join(" ").trimEnd(),"fmt");process.stdout.write(`${a(n)}
222
+ `);for(let s of r)process.stdout.write(`${a(s)}
223
+ `)}o(Xa,"handleList");function Ur(e,t,n){let r=qe(B().keysDir,`${e}${Ce}`);return n.mkdirSync(Ft(r),{recursive:!0}),n.writeFileSync(r,t),r}o(Ur,"writePublicKey");async function Za(e,t,n,r,i,{force:a=!1}={}){let s=r??qe(B().keysDir,`${e}${Pt}`);if(i.mkdirSync(Ft(s),{recursive:!0}),!a&&i.existsSync(s))throw new Error(`Refusing to overwrite existing key at ${s}. Delete it first if you really want to regenerate: rm ${s}`);let p=await i.encryptStringAsJwe(t,n);return i.writeFileSync(s,p,{mode:384}),s}o(Za,"writeEncryptedPrivateKey");async function ep(e,t,n=new Date){let{isMacOS:r,existsSync:i,mkdirSync:a,writeFileSync:s,generateSigningKeyPair:p,storeKeyInKeychain:c,promptExpiryMonths:d,promptKid:l,promptEmail:m,promptPassphrase:g,promptConfirmOverwrite:f}=t,h=e.keychain!==!1&&r()&&!e.output,w=e.expires!==void 0?ke(e.expires):await d(),u=It(xr(n,w)),y=e.kid!==void 0?He(e.kid):await l(),S=qe(B().keysDir,`${y}${Ce}`),v=i(S);if(v&&!e.force&&!await f(y)){process.stderr.write(`Aborted.
224
+ `);return}let x=e.email!==void 0?xe(e.email,"--email"):await m(),b=h?null:await g();process.stderr.write(`
221
225
  Generating Ed25519 keypair...
222
226
 
223
- `);let{privateKeyPem:c,publicKeyPem:d,kid:l}=await t.generateSigningKeyPair();if(r){await t.storeKeyInKeychain(l,c);let f=$r(l,d,t);process.stderr.write(`Public key: ${f}
224
- `),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${l})
225
- `)}else{if(p===null)throw new Error("passphrase is required when not using Keychain");let f=await Ma(l,c,p,e.output,t),y=$r(l,d,t);process.stderr.write(`Public key: ${y}
226
- `),process.stderr.write(`Private key: ${f} (JWE, AES-256-GCM, PBKDF2-SHA512 x${wt.toLocaleString()})
227
- `),t.isMacOS()||process.stderr.write(` (macOS Keychain integration is the default on darwin; on this OS we use the file.)
228
- `)}let m=It(Z().keysDir,`${l}${Ct}`);t.mkdirSync(Pt(m),{recursive:!0}),t.writeFileSync(m,JSON.stringify({email:a}));let g=yr(process.stderr);process.stderr.write(`
229
- Signing identity (kid): ${g.green(l)}
230
- `),process.stderr.write(`Expires: ${s} (${i} month${i===1?"":"s"} from today)
231
- `),process.stderr.write(hr({kid:l,publicKeyPem:d,email:a,expires:s},g,n)),process.stderr.write(`
232
- ${g.bold("Next:")} open a PR against the ${g.magenta("infrastructure")} repo with that block, then \`${g.cyan(`cognite sign -s ${l}`)}\`
233
- `)}o(Va,"handleGenerate");var Tr=1e3,Ua=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function Ka(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:Ua.has(t)?[t,n]:[t,"[REDACTED]"]))}o(Ka,"sanitize");function Ga(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}o(Ga,"getCommandPath");function Rr(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(Rr,"tryLoadAppConfig");function At(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(At,"commandFromArgv");function Fr(e,t,n=v){e.hook("postAction",async(r,i)=>{try{let s={command:Ga(i),options:Ka(i.opts()),success:!0,...Rr(n)};t.track("Flows.CLI.Command",s),await t.flush(Tr)}catch{}})}o(Fr,"instrument");async function Lr(e,t,n=v){try{let r={command:At(t),options:{},success:!1,...Rr(n)};e.track("Flows.CLI.Command",r),await e.flush(Tr)}catch{}}o(Lr,"trackFailure");var Ha="ERR_USE_AFTER_CLOSE";function Nr(e){return e instanceof Error&&"code"in e&&e.code===Ha}o(Nr,"isReadlineClosedError");function Ba(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(Ba,"isPlainObject");function $t(e){return e==null||Nr(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Ba(e)&&Object.keys(e).length===0)}o($t,"isPromptCancel");var Or=!1;function _r(){Or||(Or=!0,process.on("uncaughtException",e=>{Nr(e)&&(console.error(`
234
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{$t(e)&&(console.error(`
235
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(_r,"installCancelHandler");import jr from"mixpanel";var qa="5c4d853e7c3b77b1eb4468d5329b278c",Ce="cognite-cli",Qa=2e3,Mr={env:process.env,init:jr.init.bind(jr)},Ja={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function Dt(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(Dt,"isTelemetryDisabled");function Ya(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(Ya,"isDebug");function Vr(e={}){let t=e.env??Mr.env,n=e.init??Mr.init,r=e.packageName,i=e.cliVersion,s=Ya(t);if(Dt(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
236
- `),Ja;let a,p=new Set;function c(){if(a)return a;try{return a=n(qa,{geolocate:!1,keepAlive:!1}),a}catch{return}}return o(c,"getClient"),{track(d,l={}){let m=c();if(!m)return;let g={...l,applicationId:Ce,...r&&{packageName:r},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(g)}
237
- `);let f=o(()=>{},"finish"),y=new Promise(w=>{f=w});p.add(y);try{m.track(d,g,f)}catch{f()}y.finally(()=>p.delete(y))},async flush(d=Qa){if(p.size===0)return;let l,m=new Promise(g=>{l=setTimeout(g,d),l.unref?.()});try{await Promise.race([Promise.allSettled([...p]),m])}finally{l&&clearTimeout(l)}s&&process.stderr.write(`[telemetry] flush done (${p.size} still pending)
238
- `)}}}o(Vr,"createTelemetry");var za=1e3,Wa="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",Xa={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function Za(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(Za,"buildRelease");var ep="192.0.2.0";function tp(e){let t={...e.user,email:void 0,username:void 0,ip_address:ep,id:void 0};return{...e,user:t,server_name:void 0}}o(tp,"scrubPii");function Ur(e={}){let t=e.env??process.env;if(Dt(t))return Xa;let n=Za(e),r="production",i=null,s=null;function a(){return{dsn:Wa,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:Ce},contexts:{cli:{applicationId:Ce,node:process.version,platform:process.platform}}},beforeSend:tp}}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,d){try{let l=await p();if(!l)return;let m={level:"fatal"};d?.command&&(m.tags={command:d.command},m.contexts={cli:{applicationId:Ce,node:process.version,platform:process.platform,command:d.command}}),l.captureException(c,m)}catch{}},async flush(c=za){try{if(!i)return;await i.flush(c)}catch{}}}}o(Ur,"createErrorReporter");import{mkdirSync as np,readFileSync as rp,writeFileSync as op}from"fs";import{homedir as ip}from"os";import{resolve as Ve}from"path";import{debuglog as sp}from"util";import{lt as ap,parse as Kr}from"semver";var pp="https://registry.npmjs.org/@cognite/cli/latest",cp=1500,Gr="upgrade-check.json",Hr=Ve(process.env.XDG_CACHE_HOME||Ve(ip(),".cache"),"@cognite","cli"),Tt=sp("cognite-flows");function lp(e,t){return!e||!t||!Kr(e)||!Kr(t)?!1:ap(e,t)}o(lp,"isOutdated");async function dp({timeout:e=cp,registryUrl:t=pp,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 Tt("fetchLatestVersion failed (%s): %O",t,r),null}}o(dp,"fetchLatestVersion");function mp(e=Hr,t=864e5){try{let n=rp(Ve(e,Gr),"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 Tt("readUpgradeCheckCache failed (%s): %O",e,n),null}}o(mp,"readUpgradeCheckCache");function up(e,t){try{np(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};op(Ve(e,Gr),JSON.stringify(n))}catch(n){Tt("writeUpgradeCheckCache failed (%s): %O",e,n)}}o(up,"writeUpgradeCheckCache");async function gp({cacheDir:e=Hr,...t}={}){let n=await dp(t);n&&up(e,n)}o(gp,"startBackgroundUpgradeCheck");function Br(e,{onOutdated:t,cacheDir:n,...r}={}){let i=mp(n);if(i){lp(e,i.latest)&&t?.(e,i.latest);return}gp({cacheDir:n,...r})}o(Br,"preActionUpgradeCheck");import{default as Dg,chalkStderr as qr}from"chalk";function Qr(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(`
239
- `);return qr.bold.yellow(a)}o(Qr,"formatUpgradeWarning");function hp(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(hp,"isDep0040Warning");var Ft=process,wp=Ft.emit.bind(Ft);Ft.emit=function(e,...t){return e==="warning"&&hp(t[0])?!1:wp(e,...t)};_r();var ae=new yp;ae.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.1.0-alpha.50").showHelpAfterError().configureOutput({writeOut:o(e=>fp(1,e),"writeOut")});ae.hook("preAction",()=>{Br("1.1.0-alpha.50",{onOutdated:o((e,t)=>{console.warn(`
240
- ${Qr(e,t)}
241
- `)},"onOutdated")})});nr(ae);Dr(ae);var Yr=Vr({packageName:"@cognite/cli",cliVersion:"1.1.0-alpha.50"}),Jr=Ur({packageName:"@cognite/cli",cliVersion:"1.1.0-alpha.50"});Fr(ae,Yr);var Rt=process.argv.slice(2);ae.parseAsync(Rt,{from:"user"}).catch(async e=>{await Lr(Yr,Rt),$t(e)&&(console.error(`
242
- Cancelled.`),process.exit(130)),await Jr.captureError(e,{command:At(Rt)}),await Jr.flush(),console.error(e instanceof Error?`\u274C ${e.message}`:e),process.exit(1)});
227
+ `);let{privateKeyPem:C,publicKeyPem:q}=await p(y);if(h){await c(y,C);let le=Ur(y,q,t);process.stderr.write(`Public key: ${le}
228
+ `),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${y})
229
+ `)}else{if(b===null)throw new Error("passphrase is required when not using Keychain");let le=await Za(y,C,b,e.output,t,{force:v}),Vt=Ur(y,q,t);process.stderr.write(`Public key: ${Vt}
230
+ `),process.stderr.write(`Private key: ${le} (JWE, AES-256-GCM, PBKDF2-SHA512 x${bt.toLocaleString()})
231
+ `),r()||process.stderr.write(` (macOS Keychain integration is the default on darwin; on this OS we use the file.)
232
+ `)}let be=qe(B().keysDir,`${y}${At}`);a(Ft(be),{recursive:!0}),s(be,JSON.stringify({email:x}));let Q=Er(process.stderr);process.stderr.write(`
233
+ Signing identity (kid): ${Q.green(y)}
234
+ `),process.stderr.write(`Expires: ${u} (${w} month${w===1?"":"s"} from today)
235
+ `),process.stderr.write(br({kid:y,publicKeyPem:q,email:x,expires:u},Q,n)),process.stderr.write(`
236
+ ${Q.bold("Next:")} open a PR against the ${Q.magenta("infrastructure")} repo with that block, then \`${Q.cyan(`cognite sign -s ${y}`)}\`
237
+ `)}o(ep,"handleGenerate");var Gr=1e3,tp=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function np(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:tp.has(t)?[t,n]:[t,"[REDACTED]"]))}o(np,"sanitize");function rp(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}o(rp,"getCommandPath");function Hr(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(Hr,"tryLoadAppConfig");function Ot(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(Ot,"commandFromArgv");function Br(e,t,n=k){e.hook("postAction",async(r,i)=>{try{let a={command:rp(i),options:np(i.opts()),success:!0,...Hr(n)};t.track("Flows.CLI.Command",a),await t.flush(Gr)}catch{}})}o(Br,"instrument");async function qr(e,t,n=k){try{let r={command:Ot(t),options:{},success:!1,...Hr(n)};e.track("Flows.CLI.Command",r),await e.flush(Gr)}catch{}}o(qr,"trackFailure");var op="ERR_USE_AFTER_CLOSE";function Jr(e){return e instanceof Error&&"code"in e&&e.code===op}o(Jr,"isReadlineClosedError");function ip(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(ip,"isPlainObject");function Lt(e){return e==null||Jr(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&ip(e)&&Object.keys(e).length===0)}o(Lt,"isPromptCancel");var Qr=!1;function Yr(){Qr||(Qr=!0,process.on("uncaughtException",e=>{Jr(e)&&(console.error(`
238
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{Lt(e)&&(console.error(`
239
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(Yr,"installCancelHandler");import{homedir as lp}from"os";import zr from"mixpanel";var sp="5c4d853e7c3b77b1eb4468d5329b278c",Ee="cognite-cli",ap=2e3,Wr={env:process.env,init:zr.init.bind(zr)},pp={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function Nt(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(Nt,"isTelemetryDisabled");function cp(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(cp,"isDebug");function Xr(e={}){let t=e.env??Wr.env,n=e.init??Wr.init,r=e.packageName,i=e.cliVersion,a=cp(t);if(Nt(t))return a&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
240
+ `),pp;let s,p=new Set;function c(){if(s)return s;try{return s=n(sp,{geolocate:!1,keepAlive:!1}),s}catch{return}}return o(c,"getClient"),{track(d,l={}){let m=c();if(!m)return;let g={...l,applicationId:Ee,...r&&{packageName:r},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform};a&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(g)}
241
+ `);let f=o(()=>{},"finish"),h=new Promise(w=>{f=w});p.add(h);try{m.track(d,g,f)}catch{f()}h.finally(()=>p.delete(h))},async flush(d=ap){if(p.size===0)return;let l,m=new Promise(g=>{l=setTimeout(g,d),l.unref?.()});try{await Promise.race([Promise.allSettled([...p]),m])}finally{l&&clearTimeout(l)}a&&process.stderr.write(`[telemetry] flush done (${p.size} still pending)
242
+ `)}}}o(Xr,"createTelemetry");var Qe=lp();function Zr(e,t=Qe){if(!t||t==="/")return e;let n=e.replaceAll(t,"~"),r=t.replaceAll("\\","/");return r!==t&&(n=n.replaceAll(r,"~")),n}o(Zr,"redactHomedir");var dp=1e3,mp="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",up={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function gp(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(gp,"buildRelease");var fp="192.0.2.0";function yp(e){let t={...e.user,email:void 0,username:void 0,ip_address:fp,id:void 0},n=e.exception?.values?.map(r=>({...r,value:r.value!==void 0?Zr(r.value):r.value}));return{...e,message:e.message!==void 0?Zr(e.message):e.message,user:t,server_name:void 0,...n!==void 0&&{exception:{...e.exception,values:n}}}}o(yp,"scrubPii");function eo(e={}){let t=e.env??process.env;if(Nt(t))return up;let n=gp(e),r="production",i=null,a=null;function s(c){let d=Qe&&Qe!=="/"?[c.rewriteFramesIntegration({root:Qe})]:[];return{dsn:mp,release:n,environment:r,defaultIntegrations:!1,integrations:d,sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:Ee},contexts:{cli:{applicationId:Ee,node:process.version,platform:process.platform}}},beforeSend:yp}}o(s,"buildInitOptions");async function p(){return i||(a||(a=(async()=>{try{let c=e.sdk??await import("@sentry/node");return c.init(s(c)),i=c,c}catch{return null}})()),a)}return o(p,"ensureSdk"),{async captureError(c,d){try{let l=await p();if(!l)return;let m={level:"fatal"};d?.command&&(m.tags={command:d.command},m.contexts={cli:{applicationId:Ee,node:process.version,platform:process.platform,command:d.command}}),l.captureException(c,m)}catch{}},async flush(c=dp){try{if(!i)return;await i.flush(c)}catch{}}}}o(eo,"createErrorReporter");import{mkdirSync as hp,readFileSync as wp,writeFileSync as Sp}from"fs";import{homedir as vp}from"os";import{resolve as Je}from"path";import{debuglog as Cp}from"util";import{lt as xp,parse as to}from"semver";var kp="https://registry.npmjs.org/@cognite/cli/latest",Ep=1500,no="upgrade-check.json",ro=Je(process.env.XDG_CACHE_HOME||Je(vp(),".cache"),"@cognite","cli"),jt=Cp("cognite-flows");function bp(e,t){return!e||!t||!to(e)||!to(t)?!1:xp(e,t)}o(bp,"isOutdated");async function Pp({timeout:e=Ep,registryUrl:t=kp,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 jt("fetchLatestVersion failed (%s): %O",t,r),null}}o(Pp,"fetchLatestVersion");function Ap(e=ro,t=864e5){try{let n=wp(Je(e,no),"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 jt("readUpgradeCheckCache failed (%s): %O",e,n),null}}o(Ap,"readUpgradeCheckCache");function Ip(e,t){try{hp(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};Sp(Je(e,no),JSON.stringify(n))}catch(n){jt("writeUpgradeCheckCache failed (%s): %O",e,n)}}o(Ip,"writeUpgradeCheckCache");async function Dp({cacheDir:e=ro,...t}={}){let n=await Pp(t);n&&Ip(e,n)}o(Dp,"startBackgroundUpgradeCheck");function oo(e,{onOutdated:t,cacheDir:n,...r}={}){let i=Ap(n);if(i){bp(e,i.latest)&&t?.(e,i.latest);return}Dp({cacheDir:n,...r})}o(oo,"preActionUpgradeCheck");import{default as Xg,chalkStderr as io}from"chalk";function so(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),a=o(p=>`\u2502 ${p}${" ".repeat(r-1-[...p].length)}\u2502`,"pad"),s=[`\u250C${i}\u2510`,...n.map(a),`\u2514${i}\u2518`].join(`
243
+ `);return io.bold.yellow(s)}o(so,"formatUpgradeWarning");function Rp(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(Rp,"isDep0040Warning");var Mt=process,Fp=Mt.emit.bind(Mt);Mt.emit=function(e,...t){return e==="warning"&&Rp(t[0])?!1:Fp(e,...t)};Yr();var ce=new Tp;ce.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.1.0-alpha.51").showHelpAfterError().configureOutput({writeOut:o(e=>$p(1,e),"writeOut")});ce.hook("preAction",()=>{oo("1.1.0-alpha.51",{onOutdated:o((e,t)=>{console.warn(`
244
+ ${so(e,t)}
245
+ `)},"onOutdated")})});dr(ce);Kr(ce);var po=Xr({packageName:"@cognite/cli",cliVersion:"1.1.0-alpha.51"}),ao=eo({packageName:"@cognite/cli",cliVersion:"1.1.0-alpha.51"});Br(ce,po);var _t=process.argv.slice(2);ce.parseAsync(_t,{from:"user"}).catch(async e=>{await qr(po,_t),Lt(e)&&(console.error(`
246
+ Cancelled.`),process.exit(130)),await ao.captureError(e,{command:Ot(_t)}),await ao.flush(),console.error(e instanceof Error?`\u274C ${e.message}`:e),process.exit(1)});