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