@cognite/cli 1.6.0 → 1.7.0
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/root/package.json.ejs.t +8 -8
- package/_templates/app/new/src/App.test.tsx.ejs.t +1 -0
- package/_templates/app/new/src/main.tsx.ejs.t +70 -0
- package/dist/chunk-74X2P7OO.js +12 -0
- package/dist/cli/cli.js +90 -92
- package/dist/deploy/index.d.ts +22 -1
- package/dist/deploy/index.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/package.json +7 -4
- package/dist/chunk-EYFDM46K.js +0 -14
package/dist/cli/cli.js
CHANGED
|
@@ -1,28 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`,"passphraseMismatchMsg"),
|
|
4
|
-
${e}`)}}o(
|
|
5
|
-
${e}`)}}o(
|
|
2
|
+
var $o=Object.defineProperty;var Zt=e=>{throw TypeError(e)};var o=(e,t)=>$o(e,"name",{value:t,configurable:!0});var Qt=(e,t,r)=>t.has(e)||Zt("Cannot "+r);var er=(e,t,r)=>(Qt(e,t,"read from private field"),r?r.call(e):t.get(e)),tr=(e,t,r)=>t.has(e)?Zt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),rr=(e,t,r,n)=>(Qt(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);import{writeSync as _c}from"fs";import{Command as Lc}from"commander";var Xe=class Xe extends Error{constructor(t,r={}){super(t),this.name="HintedError",r.cause!==void 0&&(this.cause=r.cause);let n=this.deriveDefaults(r);this.hint=r.hint??n.hint,this.helpUrl=r.helpUrl??n.helpUrl,this.shouldReport=r.shouldReport??!0}deriveDefaults(t){return{hint:Oo(t.cause)}}};o(Xe,"HintedError");var g=Xe;function or(e){return e instanceof g}o(or,"isHintedError");var nr="https://docs.cognite.com/cdf/access/",To="https://status.cognite.com";function Ro(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:nr};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:nr};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:To};default:return{}}}o(Ro,"defaultHintForStatus");var Ze=class Ze extends g{constructor(t,r){super(t,r),this.name="HintedHttpError",this.httpStatusCode=r.httpStatusCode,this.requestUrl=r.requestUrl,this.responseBody=r.responseBody}deriveDefaults(t){let{httpStatusCode:r}=t,n=Ro(r),i=super.deriveDefaults(t);return{hint:n.hint??i.hint,helpUrl:n.helpUrl}}};o(Ze,"HintedHttpError");var te=Ze;function ir(e){return e instanceof te}o(ir,"isHintedHttpError");function Fo(e,t){if(e)switch(e){case"ENOTFOUND":return t.hostname?`DNS lookup failed for ${t.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return t.hostname&&t.port?`Connection refused by ${t.hostname}:${t.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return t.path?`Permission denied: ${t.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return t.path?`File or directory not found: ${t.path}.`:"File or directory not found.";case"EISDIR":return t.path?`Expected a file but found a directory: ${t.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return t.port?`Port ${t.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}o(Fo,"hintForErrno");function Oo(e){let t=e,r=new Set;for(;t!=null&&!r.has(t)&&(r.add(t),typeof t=="object");){let n=t,i=Fo(n.code,n);if(i!==void 0)return i;t=n.cause}}o(Oo,"hintForCause");import{existsSync as vi,readFileSync as Ci}from"fs";import{join as Ei,resolve as Fe}from"path";import{verifyBundle as ki}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as bi}from"jose";import rt from"enquirer";import{email as Uo,pipe as _o,safeParse as Lo,string as No}from"valibot";var Ko=_o(No(),Uo());function ae(e,t="email"){let r=e.trim();if(!r)throw new Error(`${t} is required`);if(!Lo(Ko,r).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return r}o(ae,"parseEmail");function pe(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(pe,"parseExpiryMonths");import{execFileSync as ge}from"child_process";function be(e={}){let{execFileSync:t=ge}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(be,"isGitInstalled");function Pe(e,t={}){let{execFileSync:r=ge}=t;try{return r("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(Pe,"isInsideGitRepo");function sr(e,t={}){let{execFileSync:r=ge}=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(sr,"gitInitAndCommit");function ar(e={}){let{execFileSync:t=ge}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(ar,"gitUserName");function pr(e={}){let{execFileSync:t=ge}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(pr,"gitUserEmail");import{inspect as Mo}from"util";var Qe="[REDACTED]",fe,xe=class xe{constructor(t){tr(this,fe);rr(this,fe,t)}toString(){return Qe}toJSON(){return Qe}[Mo.custom](){return Qe}expose(){return er(this,fe)}static from(t){return new xe(t)}};fe=new WeakMap,o(xe,"SensitiveString");var v=xe;var Ae=3,cr="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",lr=`Key expiry in months (${1}-${12})`,dr="Email address for the registry entry",mr=`Passphrase for the encrypted private key (min ${15} chars)`,ur="Confirm passphrase",gr=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),fr=o(e=>`Passphrases do not match (attempt ${e}/${Ae}).
|
|
3
|
+
`,"passphraseMismatchMsg"),yr=`Passphrase confirmation failed after ${Ae} attempts`,hr=o(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),Sr="How would you like to submit your key registration?",wr="Open in browser",vr="Copy link to clipboard";async function De(e){return rt.prompt(e)}o(De,"defaultPrompt");function nt(e){return t=>{try{return e(t),!0}catch(r){return r instanceof Error?r.message:"Invalid"}}}o(nt,"parserAsValidator");var jo=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function ne(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(!jo.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(ne,"parseKid");async function Cr(e={}){let{prompt:t=De}=e,{kid:r}=await t({type:"input",name:"kid",message:cr,validate:nt(ne)});return ne(r)}o(Cr,"promptKid");async function Er(e={}){let{prompt:t=o(n=>rt.prompt(n),"prompt")}=e,{action:r}=await t({type:"select",name:"action",message:Sr,choices:[{name:"browser",message:wr},{name:"clipboard",message:vr}]});if(r!=="browser"&&r!=="clipboard")throw new Error(`Unexpected Zendesk action: ${r}`);return r}o(Er,"promptZendeskAction");async function kr(e={}){let{prompt:t=De}=e,{months:r}=await t({type:"input",name:"months",message:lr,initial:String(6),validate:nt(n=>pe(n,"expiry"))});return pe(r,"expiry")}o(kr,"promptExpiryMonths");async function br(e={}){let{prompt:t=De,gitUserEmail:r=pr}=e,{email:n}=await t({type:"input",name:"email",message:dr,initial:r(),validate:nt(i=>ae(i,"email"))});return ae(n,"email")}o(br,"promptEmail");async function Pr(e={}){let{prompt:t=De,stderr:r=process.stderr}=e;for(let n=1;n<=Ae;n+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:mr,validate:o(a=>a.length>=15?!0:gr(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:ur});if(i===s)return v.from(i);r.write(fr(n))}throw new Error(yr)}o(Pr,"promptPassphrase");async function xr(e,t={}){let{prompt:r=o(i=>rt.prompt(i),"prompt")}=t,{confirmed:n}=await r({type:"confirm",name:"confirmed",message:hr(e),initial:!1});return n}o(xr,"promptConfirmOverwrite");import{existsSync as Zo,readdirSync as Qo,readFileSync as ei}from"fs";import{join as st}from"path";import{execFile as Go}from"child_process";import{promisify as Yo}from"util";import{execFileSync as Ar}from"child_process";import{platform as Vo}from"os";import Bo from"path";function _(e,t={}){let{platform:r=Vo}=t;switch(r()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}o(_,"isOS");function Dr(e,t={}){let{exec:r=Ar,log:n=console.log}=t,[i,s]=_("macos",t)?["open",[e]]:_("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{r(i,s)}catch{n(`Could not open browser \u2014 open manually:
|
|
4
|
+
${e}`)}}o(Dr,"openInBrowser");function Ir(e,t={}){let{exec:r=Ar,log:n=console.log}=t,[i,s]=_("macos",t)?["open",["-R",e]]:_("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[Bo.dirname(e)]];try{r(i,s)}catch{n(`Could not open file manager \u2014 files are at:
|
|
5
|
+
${e}`)}}o(Ir,"revealInFileManager");var $r="cognite-flows",qo=Yo(Go),Tr=o((e,t)=>qo(e,t),"defaultExecFile"),Jo=-25300,zo=Jo&255;function Wo(e){if(!(e instanceof Error)||!("code"in e)||e.code!==zo)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(Wo,"isKeychainNotFoundError");async function Rr(e,t,r={}){let n=t.expose();if(!_("macos",r))throw new Error("Keychain storage is only supported on macOS");let{execFile:i=Tr}=r;await i("security",["add-generic-password","-a",e,"-s",$r,"-w",Buffer.from(n,"utf-8").toString("base64"),"-U"])}o(Rr,"storeKeyInKeychain");async function Ie(e,t={}){if(!_("macos",t))return null;let{execFile:r=Tr}=t;try{let{stdout:n}=await r("security",["find-generic-password","-a",e,"-s",$r,"-w"]);return v.from(Buffer.from(n.trim(),"base64").toString("utf-8"))}catch(n){if(Wo(n))return null;throw n}}o(Ie,"readKeyFromKeychain");import{homedir as Xo}from"os";import{join as it}from"path";function D(e={}){let{env:t=process.env,homedir:r=Xo}=e,n=t.COGNITE_CLI_HOME?.trim()||it(r(),".cognite-cli");return{home:n,keysDir:it(n,"keys"),sessionFile:it(n,"session.json")}}o(D,"getConfig");var X=".pub.pem",at=".key.jwe",pt=".meta.json";function $e(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}o($e,"formatLocalKeySource");function ti(e){return{existsSync:e.existsSync??Zo,readdirSync:e.readdirSync??Qo,readFileSync:e.readFileSync??((t,r)=>ei(t,r)),isOS:e.isOS??(t=>_(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>Ie(t))}}o(ti,"resolveDeps");function ri(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(ri,"readEmailFromMeta");function ni(e,t){return t.existsSync(e)?t.readdirSync(e).filter(r=>r.endsWith(X)):[]}o(ni,"publicKeyEntries");function oi(e){return e.slice(0,-X.length)}o(oi,"kidFromPublicKeyFilename");async function ii(e,t,r){if(r.isOS("macos")&&await r.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let n=st(t,`${e}${at}`);return r.existsSync(n)?{kind:"encrypted-file",path:n}:{kind:"public-only"}}o(ii,"resolveSource");async function Te(e=D().keysDir,t={}){let r=ti(t),n=new Set,i=ni(e,r).flatMap(s=>{let a=oi(s);return!a||n.has(a)?[]:(n.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let p=await ii(s,e,r),c=st(e,`${s}${pt}`),l;try{l=ri(r.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:st(e,a),email:l}}))}o(Te,"discoverLocalKeys");import{createReadStream as si}from"fs";function Re(e){let t=si(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(Re,"createWebStreamFromFile");import ai from"path";var Fr=".cognite-bundles";function Or(e,t){return`${e}-${t}.zip`}o(Or,"bundleFileName");function q(e,t,r){return ai.join(e,Fr,Or(t,r))}o(q,"bundlePath");import{existsSync as hi,readFileSync as Si}from"fs";import{resolve as wi}from"path";import{array as Ur,boolean as pi,check as ce,forward as le,literal as ci,maxLength as li,minLength as di,nonEmpty as Z,object as _r,optional as J,picklist as mi,pipe as V,safeParse as ui,string as N,url as Lr}from"valibot";var ct=V(N(),Z("must not be empty")),lt=V(N(),Z("must not be empty"),li(256,"must be 256 characters or fewer")),dt=V(N(),Z("must not be empty"),Lr("must be a valid URL")),gi=V(N(),Z("must not be empty"),Lr("must be a valid URL")),mt=V(N(),Z("must not be empty")),ut=V(N(),Z("must not be empty")),fi=V(_r({org:mt,project:ut,baseUrl:dt,deployClientId:J(N(),""),deploySecretName:J(N(),""),published:J(pi(),!1),idpType:J(mi(["cdf","entra_id","oauth"]),"cdf"),tenantId:J(N()),scopes:J(Ur(V(N(),Z("must not be empty")))),tokenUrl:J(gi)}),le(ce(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),le(ce(e=>e.idpType!=="oauth"||!!e.tokenUrl,'must be set when idpType is "oauth"'),["tokenUrl"]),le(ce(e=>!e.tokenUrl||e.idpType==="oauth",'must only be set when idpType is "oauth"'),["tokenUrl"]),le(ce(e=>e.idpType!=="oauth"||!!e.deployClientId,'must be set when idpType is "oauth"'),["deployClientId"]),le(ce(e=>e.idpType!=="oauth"||!!e.deploySecretName,'must be set when idpType is "oauth"'),["deploySecretName"]),le(ce(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),yi=_r({name:ct,externalId:lt,versionTag:V(N(),Z("must not be empty")),description:J(N(),""),deployments:V(Ur(fi),di(1,"must contain at least one deployment")),infra:J(ci("appsApi"))});function gt(e){let t=ui(yi,e);if(t.success)return t.output;let r=t.issues[0],n=r.path?.map(s=>s.key).join(".")??"",i=n?`"${n}" `:"";throw new Error(`app.json: ${i}${r.message}`)}o(gt,"validateAppConfig");function C(e,t={}){let{validator:r=gt,existsSync:n=hi,readFileSync:i=Si}=t,s=wi(e,"app.json");if(!n(s))throw new Error(`No app.json found at ${s}. Make sure you're running this command from your app's root directory.`);let a=i(s,"utf-8"),p;try{p=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return r(p)}o(C,"loadAppConfig");var Nr=[".dev.sig",".cert.sig",".sig"];function Pi(e){return{existsSync:e.existsSync??vi,readFileSync:e.readFileSync??((t,r)=>Ci(t,r)),createBundleStream:e.createBundleStream??Re,verifyBundle:e.verifyBundle??ki,loadAppConfig:e.loadAppConfig??C,defaultKeyDir:e.defaultKeyDir??(()=>D().keysDir)}}o(Pi,"resolveDeps");function xi(e,t){return Nr.map(r=>`${e}${r}`).find(r=>t(r))}o(xi,"findSiblingSignature");function Ai(e){let t=e.split(".");return t.length===3&&t.every(r=>r.length>0)}o(Ai,"isCompactJws");function Di(e){try{let t=bi(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}o(Di,"readKidFromToken");function Ii(e,t,r){let{existsSync:n,readFileSync:i}=r;try{ne(e)}catch(a){throw new g(a instanceof Error?a.message:String(a),{shouldReport:!1})}if(!n(t))throw new g(`Key directory not found: ${t}`,{shouldReport:!1});let s=Ei(t,`${e}${X}`);if(!n(s))throw new g(`No public key found for kid "${e}" in ${t}`,{shouldReport:!1});try{return i(s,"utf-8")}catch(a){throw new g(`Failed to read public key file: ${s}`,{cause:a,shouldReport:!1})}}o(Ii,"resolvePublicKeyForKid");function $i(e,t){let{payload:r,kid:n}=e;if(console.log(`Verified ${r.appId}@${r.version}`),console.log(` kid: ${n}`),console.log(` hash: ${r.bundleSha256}`),r.scopes&&r.scopes.length>0){let i=r.scopes.map(s=>`${s.org}/${s.project}`).join(", ");console.log(` scopes: ${i}`)}t&&console.log(JSON.stringify(r,null,2))}o($i,"printResult");async function Kr(e,t,r={},n=process.cwd()){let{existsSync:i,readFileSync:s,loadAppConfig:a,createBundleStream:p,verifyBundle:c,defaultKeyDir:l}=Pi(r),d;if(e)d=Fe(n,e);else{let u;try{u=a(n)}catch(f){let w=f instanceof Error?f.message:String(f);throw new g(w,{cause:f,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}d=q(n,u.externalId,u.versionTag)}if(!i(d)){let u=e?void 0:"Default derived from app.json \u2014 pass [bundle] explicitly to override.";throw new g(`Bundle not found: ${d}`,{hint:u,shouldReport:!1})}let m=t.sig?Fe(n,t.sig):xi(d,i);if(!m)throw new g("No signature file found.",{hint:`Pass --sig <path> or place one of ${Nr.map(u=>`${d}${u}`).join(", ")} next to the bundle.`,shouldReport:!1});if(!i(m))throw new g(`Signature file not found: ${m}`,{shouldReport:!1});let y;try{y=s(m,"utf-8").trim()}catch(u){throw new g(`Failed to read signature file: ${m}`,{cause:u,shouldReport:!1})}if(!Ai(y))throw new g(`Malformed JWS in ${m}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let S;if(t.key){let u=Fe(n,t.key);if(!i(u))throw new g(`Public key not found: ${u}`,{shouldReport:!1});try{S=s(u,"utf-8")}catch(f){throw new g(`Failed to read public key file: ${u}`,{cause:f,shouldReport:!1})}}else{let u=t.keyDir?Fe(n,t.keyDir):l(),f=Di(y);if(!f)throw new g("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});S=Ii(f,u,{existsSync:i,readFileSync:s})}try{let u=await c({token:y,publicKeyPem:S,bundleStream:p(d)});$i(u,t.verbose??!1)}catch(u){let f=u instanceof Error?u.message:String(u);throw new g(`Bundle rejected: ${f}`,{shouldReport:!1})}}o(Kr,"handleVerify");function Mr(e,t={}){return e.command("verify [bundle]").description("Verify a signed app bundle locally (default: derived from app.json)").option("-s, --sig <path>","Path to the signature file (default: sibling .dev.sig / .cert.sig / .sig)").option("--key <path>","Path to a public key PEM file").option("--key-dir <path>","Directory of <kid>.pub.pem files \u2014 kid is read from the token header (default: $COGNITE_CLI_HOME/keys)").option("-v, --verbose","Print the full decoded payload after verification").addHelpText("after",`
|
|
6
6
|
Bundles are stored in .cognite-bundles/<externalId>-<versionTag>.zip by default.
|
|
7
7
|
|
|
8
8
|
Examples:
|
|
9
9
|
cognite apps verify Verify default bundle (path from app.json)
|
|
10
10
|
cognite apps verify .cognite-bundles/my-app-1.0.0.zip Verify a specific bundle
|
|
11
11
|
cognite apps verify .cognite-bundles/my-app-1.0.0.zip --sig my-app-1.0.0.zip.dev.sig Verify with explicit signature
|
|
12
|
-
cognite apps verify .cognite-bundles/my-app-1.0.0.zip --key /path/to/pub.pem Verify with explicit public key`).action((n
|
|
13
|
-
See: ${
|
|
14
|
-
See: ${
|
|
15
|
-
${
|
|
16
|
-
`)}o(
|
|
12
|
+
cognite apps verify .cognite-bundles/my-app-1.0.0.zip --key /path/to/pub.pem Verify with explicit public key`).action((r,n)=>Kr(r,n,t))}o(Mr,"registerVerifyCommand");var Hr="https://docs.cognite.com/cdf/access/";function L(e){return e!==null&&typeof e=="object"}o(L,"isRecord");function oe(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(oe,"isHttpError");function Ti(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
13
|
+
See: ${Hr}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
14
|
+
See: ${Hr}`;default:return}}o(Ti,"httpStatusHint");function z(e){let t=e instanceof Error?e:new Error(String(e));if(!oe(t))return null;let r=Ti(t.status);return r?Object.assign(new Error(`${t.message}
|
|
15
|
+
${r}`),{cause:t}):null}o(z,"enrichedHttpError");function Ri(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(Ri,"findMissingArray");function Fi(e,t){if(!oe(e)||e.status!==400)return!1;let r=Ri(e);return r?r.some(n=>L(n)&&typeof n.externalId=="string"&&t.includes(n.externalId)):!1}o(Fi,"isMissingExternalIdError");function Oe(e,t){return oe(e)&&e.status===404||Fi(e,t)}o(Oe,"isNotFoundError");var Vr=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Br=["ACTIVE","PREVIEW"],ft=class ft extends Error{constructor(t,r){super(`Version ${r} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=r}};o(ft,"AppVersionNotFoundError");var B=ft,yt=class yt extends Error{constructor(t){super(`App ${t} not found`),this.name="AppNotFoundError",this.appExternalId=t}};o(yt,"AppNotFoundError");var de=yt;function Ue(e,t){return e.includes(t)}o(Ue,"includesValue");function Oi(e){return Ue(Vr,e)}o(Oi,"isAppVersionLifecycleState");function Ui(e){return Ue(Br,e)}o(Ui,"isAppVersionAlias");function _i(e){return typeof e.version=="string"&&Oi(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||Ui(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(_i,"isAppVersion");function jr(e){if(!L(e)){let t=JSON.stringify(e)?.slice(0,200)??String(e);throw new Error(`Invalid version response: expected object, got ${t}`)}if(!_i(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}o(jr,"parseAppVersion");function Li(e){if(!L(e))throw new Error("Invalid app response: not an object");let{externalId:t,name:r,description:n}=e;if(typeof t!="string")throw new Error("Invalid app response: missing externalId");if(typeof r!="string")throw new Error("Invalid app response: missing name");if(n!=null&&typeof n!="string")throw new Error("Invalid app response: malformed description");return{externalId:t,name:r,description:typeof n=="string"?n:void 0}}o(Li,"parseAppMetadata");var ht=class ht{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 z(i)??i}}async updateApps(t){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:t}})}catch(r){throw z(r)??r}}async getApp(t){let r=`${this.appsBasePath}/${encodeURIComponent(t)}`;try{let n=await this.client.get(r);return Li(n.data)}catch(n){throw Oe(n,[t])?new de(t):z(n)??n}}async uploadVersion(t,r,n,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${r}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(n)]),i),a.append("version",r),a.append("entryPath",s);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,l=await this.client.authenticate();if(!l)throw new g("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let d=v.from(l),m=`${this.client.getBaseUrl()}${c}`,y=new AbortController,S=setTimeout(()=>y.abort(),300*1e3),u;try{u=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${d.expose()}`},body:a,signal:y.signal})}catch(f){throw f instanceof Error&&f.name==="AbortError"?new g("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new g(`Failed to upload version to ${m}`,{cause:f,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(S)}if(!u.ok){let f=await u.text(),w;try{w=JSON.parse(f)}catch{}let E=f;if(L(w)){let P=w.error;if(typeof P=="string")E=P;else if(L(P)){let U=P.message,k=P.code;E=typeof U=="string"?U:k!=null?`Unknown error (code: ${k})`:f}else{let U=w.message;E=typeof U=="string"?U:f}}let h=u.headers.get("x-request-id"),M=h?` | X-Request-ID: ${h}`:"",H=L(w)?w:f;throw new te(`Upload failed: ${u.status} \u2014 ${E}${M}`,{httpStatusCode:u.status,requestUrl:m,responseBody:H})}console.log(`\u2705 Version ${r} uploaded`)}async getVersion(t,r){let n=encodeURIComponent(t),i=encodeURIComponent(r),s=`${this.appsBasePath}/${n}/versions/${i}`;try{let a=await this.client.get(s);return jr(a.data)}catch(a){throw Oe(a,[t,r])?new B(t,r):z(a)??a}}async getActiveVersion(t){let r=encodeURIComponent(t),n=`${this.appsBasePath}/${r}/versions/list`;try{let i=await this.client.post(n,{data:{filter:{aliases:["ACTIVE"]}}});if(!L(i.data)||!Array.isArray(i.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=i.data;if(s.length===0)return null;if(s.length>1)throw new Error(`Unexpected response: ${s.length} versions have the ACTIVE alias, expected at most 1`);return jr(s[0])}catch(i){if(Oe(i,[t]))return null;throw z(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(s){throw z(s)??s}}async submitSignatures(t,r,n){let i=encodeURIComponent(t),s=encodeURIComponent(r),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:n}})}catch(p){throw z(p)??p}}async listSignatures(t,r){let n=encodeURIComponent(t),i=encodeURIComponent(r),s=`${this.appsBasePath}/${n}/versions/${i}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return Mi(a.data)}catch(a){throw z(a)??a}}};o(ht,"AppHostingApi");var _e=ht,Ni=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Ki=["developer","certifier"];function Mi(e){if(!L(e))throw new Error("Invalid signatures response: expected an object with an items array");let{items:t}=e;if(!Array.isArray(t))throw new Error("Invalid signatures response: items property is missing or not an array");return t.flatMap(r=>{let n=Hi(r);return n?[n]:[]})}o(Mi,"parseStoredSignatures");function Hi(e){if(!L(e))return null;let{signerKid:t,signerRole:r,signatureIat:n,receivedAt:i,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Ue(Ki,r)||typeof n!="number"||typeof i!="number"||typeof s!="number"||!Ue(Ni,a)?null:{signerKid:t,signerRole:r,signatureIat:n,receivedAt:i,createdTime:s,status:a}}o(Hi,"parseStoredSignature");function St(e,t){let r=[];e.name!==t.name&&r.push({field:"name",remote:e.name,local:t.name});let n=e.description??"";return n!==t.description&&r.push({field:"description",remote:n,local:t.description}),r}o(St,"diffAppMetadata");function ji(e){let t=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:r,remote:n,local:i}of e){let s=`${r}:`.padEnd(14);t.push(` ${s}"${n}" \u2192 "${i}"`)}return t.join(`
|
|
16
|
+
`)}o(ji,"formatMetadataDriftError");var wt=class wt{constructor(t){this.api=new _e(t)}getVersion(t,r){return this.api.getVersion(t,r)}uploadVersion(t,r,n,i,s){return this.api.uploadVersion(t,r,n,i,s)}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(oe(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`),await this.checkMetadataDrift(t,r,n);return}throw i}}async checkMetadataDrift(t,r,n){let i;try{i=await this.getApp(t)}catch{return}let s=St(i,{name:r,description:n});if(s.length!==0)throw new g(ji(s),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(t){return this.api.getApp(t)}async updateAppMetadata(t,r,n){await this.api.updateApps([{externalId:t,update:{name:{set:r},description:n?{set:n}:{setNull:!0}}}])}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"))}listSignatures(t,r){return this.api.listSignatures(t,r)}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,s,a,p=!1){console.log(`
|
|
17
17
|
\u{1F680} Deploying application via App Hosting API...
|
|
18
|
-
`),await this.ensureApp(t,n
|
|
19
|
-
\u2705 Deployment successful!`)}};o(
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
`),
|
|
23
|
-
|
|
24
|
-
`)}}}o(Te,"createTelemetry");import qi from"https";import{authorizationCodeGrant as Yi}from"openid-client";function Hn(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}o(Hn,"escapeHtml");function yt(e,t,n){let r=Hn(t),i=Hn(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
|
|
25
|
-
<h1>${r}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
|
|
18
|
+
`),await this.ensureApp(t,r,n),await this.uploadVersion(t,i,s,a),p&&await this.publishAndActivate(t,i),console.log(`
|
|
19
|
+
\u2705 Deployment successful!`)}};o(wt,"AppHostingClient");var b=wt;import{CogniteClient as Ps}from"@cognite/sdk";import{CogniteClient as Zi}from"@cognite/sdk";function Vi(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}o(Vi,"exponentialBackoffWithJitter");function Bi(e){return new Promise(t=>setTimeout(t,e))}o(Bi,"sleep");async function Gr(e,t={}){let r=t.maxAttempts??5,n=t.shouldRetry??(()=>!0),i=t.delayInMsCalculator??Vi;if(r<1)throw new Error("`maxAttempts` must be 1 or greater");if(r>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await e()}catch(a){if(s>=r||!n(a))throw a;let p=i(s);t.onAttemptFail?.(a,s,p),await Bi(p),s++}}o(Gr,"retryAsync");var Gi="https://auth.cognite.com/oauth2/token",Yi=o(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function Yr({idp:e,tokenUrl:t,init:r,missingTokenHint:n}){let i;try{i=await Gr(()=>fetch(t,r),{maxAttempts:3})}catch(p){throw new g(`Failed to fetch access token from ${t}`,{cause:p})}if(!i.ok){let p=await i.text();throw new te(`Failed to get token from ${e}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:t,responseBody:p})}let s=await i.text(),a;try{a=JSON.parse(s)}catch{throw new g(`Unexpected response from ${e} authentication (invalid JSON)`,{hint:n})}if(!Yi(a))throw new g(`No access token in ${e} authentication response`,{hint:n});return v.from(a.access_token)}o(Yr,"fetchOAuthToken");var qi=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 s=n.toLowerCase().replace(/_/g,"-");r[s]=i}return r}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),Ji=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=qi()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return v.from(t)},"getSecretFromEnv"),zi=o((e,t)=>{let r=t.expose();return Yr({idp:"CDF",tokenUrl:Gi,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${e}:${r}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."})},"getTokenCdf"),qr=o(({idp:e,tokenUrl:t,clientId:r,clientSecret:n,scopes:i,missingTokenHint:s})=>Yr({idp:e,tokenUrl:t,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:r,client_secret:n,grant_type:"client_credentials",...i!==void 0?{scope:i.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),Wi=o((e,t)=>{if(t!==void 0)return t.join(" ");if(!e)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(e).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${e}`)}},"resolveEntraScope"),Xi=o((e,t,r,n,i)=>qr({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${r}/oauth2/v2.0/token`,clientId:e,clientSecret:t.expose(),scopes:i!==void 0?i:[Wi(n)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),vt=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return v.from(t.COGNITE_TOKEN);let{deployClientId:r,deploySecretName:n,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:p,tokenUrl:c}=e,l=Ji(n);if(i==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return qr({idp:"OAuth",tokenUrl:c,clientId:r,clientSecret:l.expose(),scopes:p,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Xi(r,l,s,a,p)}return zi(r,l)},"getToken");async function ye(e,t,r=process.env,n){let i=await vt(e,r),s=r.COGNITE_BASE_URL??e.baseUrl,a=(n??(p=>new Zi(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}o(ye,"getSdk");import ms from"os";import us from"path";import gs from"open";import{buildAuthorizationUrl as fs,calculatePKCECodeChallenge as ys,discovery as hs,None as Ss,randomPKCECodeVerifier as ws,randomState as vs}from"openid-client";import Jr from"mixpanel";var Qi="5c4d853e7c3b77b1eb4468d5329b278c",he="cognite-cli",es=2e3,zr={env:process.env,init:Jr.init.bind(Jr)},ts={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function Ct(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(Ct,"isTelemetryDisabled");function rs(e=process.env){if(e.GITHUB_ACTIONS)return"github-actions";if(e.TF_BUILD)return"azure-devops";if(e.GITLAB_CI)return"gitlab-ci";if(e.CIRCLECI)return"circleci";if(e.TRAVIS)return"travis-ci";if(e.BUILDKITE)return"buildkite";if(e.DRONE)return"drone";if(e.SEMAPHORE)return"semaphore";if(e.TEAMCITY_VERSION)return"teamcity";if(e.APPVEYOR)return"appveyor";if(e.CODEBUILD_BUILD_ID)return"aws-codebuild";if(e.HEROKU_TEST_RUN_ID)return"heroku-ci";if(e.BITBUCKET_BUILD_NUMBER)return"bitbucket-pipelines";if(e.JENKINS_URL||e.JENKINS_HOME)return"jenkins";if(e.CI&&e.CI!=="false"&&e.CI!=="0")return"ci-generic"}o(rs,"detectCiEnvironment");function ns(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(ns,"isDebug");function Le(e={}){let t=e.env??zr.env,r=e.init??zr.init,n=e.packageName,i=e.cliVersion,s=ns(t),a=rs(t);if(Ct(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
|
|
20
|
+
`),ts;let p,c=new Set;function l(){if(p)return p;try{return p=r(Qi,{geolocate:!1,keepAlive:!1}),p}catch{return}}return o(l,"getClient"),{track(d,m={}){let y=l();if(!y)return;let S={...m,applicationId:he,...n&&{packageName:n},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform,...a&&{ciEnvironment:a}};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(S)}
|
|
21
|
+
`);let u=o(()=>{},"finish"),f=new Promise(w=>{u=w});c.add(f);try{y.track(d,S,u)}catch{u()}f.finally(()=>c.delete(f))},async flush(d=es){if(c.size===0)return;let m,y=new Promise(S=>{m=setTimeout(S,d),m.unref?.()});try{await Promise.race([Promise.allSettled([...c]),y])}finally{m&&clearTimeout(m)}s&&process.stderr.write(`[telemetry] flush done (${c.size} still pending)
|
|
22
|
+
`)}}}o(Le,"createTelemetry");import is from"https";import{authorizationCodeGrant as ss}from"openid-client";function Wr(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}o(Wr,"escapeHtml");function Et(e,t,r){let n=Wr(t),i=Wr(r);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
|
|
23
|
+
<h1>${n}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
|
|
26
24
|
@keyframes checkmark {
|
|
27
25
|
0% { transform: scale(0); }
|
|
28
26
|
50% { transform: scale(1.2); }
|
|
@@ -30,32 +28,32 @@ ${s}`,{hint:r});return a.access_token}o(Ln,"fetchOAuthToken");var Ui=o(()=>{let
|
|
|
30
28
|
}
|
|
31
29
|
h1 { animation: checkmark 0.5s ease-out; }
|
|
32
30
|
</style>`:""}
|
|
33
|
-
</body></html>`}o(
|
|
34
|
-
`),
|
|
35
|
-
`);try{await
|
|
36
|
-
`),
|
|
31
|
+
</body></html>`}o(Et,"generateHtml");import os from"net";function Xr(e,t){return new Promise(r=>{let n=new os.Socket,i=o(s=>{n.removeAllListeners(),n.destroy(),r(s)},"done");n.setTimeout(500),n.once("connect",()=>i(!1)),n.once("timeout",()=>i(!0)),n.once("error",()=>i(!0)),n.connect(e,t)})}o(Xr,"isHostPortFree");function Ne(e,t={}){return _("windows",t)?`Find the process: netstat -ano | findstr :${e} then kill it: taskkill /PID <pid> /F`:`Free port ${e} (e.g. lsof -ti :${e} | xargs kill) and retry.`}o(Ne,"freePortHint");async function Zr(e){if(e<0)throw new Error(`Invalid port: ${e}`);return e===0?!0:(await Promise.all([Xr(e,"127.0.0.1"),Xr(e,"::1")])).every(Boolean)}o(Zr,"isPortFree");async function as(e,t,r,n,i,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await s.authorizationCodeGrant(r,a,{pkceCodeVerifier:n,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(Et("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(Et("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(as,"handleCallback");function ps(e){let t=e/6e4,r=Math.round(t*10)/10;return`${r} ${r===1?"minute":"minutes"}`}o(ps,"formatTimeoutMinutes");function Qr(e,t,r,n,i,s={createServer:is.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:ss}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,y)=>{try{let S=await as(m,y,r,n,i,s);S.shouldClose&&(d(),S.error?p(S.error):S.tokens?a(S.tokens):p(new Error("No tokens received")))}catch(S){d(),p(S instanceof Error?S:new Error(String(S)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${ps(e.loginTimeout)}`))},e.loginTimeout);function d(){s.clearTimeout(l),c.close()}o(d,"cleanup"),c.on("error",m=>{d(),m.code==="EADDRINUSE"||m.code==="EACCES"?p(new g(`Port ${e.port} is already in use \u2014 the login callback server cannot start`,{cause:m,hint:Ne(e.port)})):p(new g(`Login callback server failed: ${m.message}`,{cause:m}))}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}o(Qr,"startCallbackServer");import{mkdirSync as cs}from"fs";import{loadLocalCertificates as ls}from"@cognite/app-sdk/https";var ds={loadLocalCertificates:ls,mkdirSync:cs,logger:console};async function en(e,t=ds){t.mkdirSync(e,{recursive:!0});let{cert:r,key:n,source:i}=await t.loadLocalCertificates({certDir:e}).catch(s=>{throw new g(`Failed to load SSL certificates from ${e}`,{cause:s,hint:"Run `npx @cognite/cli apps setup-https` to create trusted local certificates."})});return i==="mkcert"?t.logger.log("\u{1F510} Using mkcert certificates for HTTPS"):(t.logger.log("\u{1F510} Using in-memory self-signed certificate for HTTPS \u2014 your browser will give you a warning."),t.logger.log(" Run `npx @cognite/cli@latest apps setup-https` to install trusted local https certificates.")),{cert:r,key:n}}o(en,"getOrCreateCertificates");var Cs="openid profile email",Es={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:us.join(ms.homedir(),".cdf-login")},ks={open:gs,getOrCreateCertificates:en,startCallbackServer:Qr,isPortFree:Zr,discovery:hs,buildAuthorizationUrl:fs,randomPKCECodeVerifier:ws,calculatePKCECodeChallenge:ys,randomState:vs,logger:console,telemetry:Le()};async function rn(e,t=Es,r){return r===void 0?tn(e,t,ks):tn(e,t,r)}o(rn,"login");async function bs(e,t){let{discovery:r}=e;try{return await r(new URL(t.authority),t.clientId,void 0,Ss())}catch(n){throw new g(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:n})}}o(bs,"fetchOpenIdConfig");async function tn(e,t,r){let{isPortFree:n,telemetry:i,logger:s,randomPKCECodeVerifier:a,calculatePKCECodeChallenge:p,randomState:c,buildAuthorizationUrl:l,getOrCreateCertificates:d,open:m,startCallbackServer:y}=r;if(!await n(t.port))throw i?.track("Flows.CLI.PortInUse",{port:t.port}),new g(`Port ${t.port} is already in use \u2014 the login callback server cannot start`,{hint:Ne(t.port)});s.log(`\u{1F510} Starting CDF login flow...
|
|
32
|
+
`),s.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let u=await bs(r,t),f=a(),w=await p(f),E=c(),h={redirect_uri:t.redirectUri,scope:t.scope??Cs,code_challenge:w,code_challenge_method:"S256",state:E};e&&(h.organization_hint=e);let M=l(u,h).toString(),H=await d(t.certDir);e&&s.log(`\u{1F3E2} Organization: ${e}`),s.log(`\u{1F680} Opening browser for authentication...
|
|
33
|
+
`);try{await m(M)}catch(P){let U=P instanceof Error?P.message:String(P);s.error("\u274C Failed to open browser automatically."),s.error(` Reason: ${U}`),s.error(`Please open this URL manually:
|
|
34
|
+
`),s.error(M),s.error("")}return y(t,H,u,f,E)}o(tn,"loginImpl");async function I(e,t,r={}){let{login:n=rn,getSdk:i=ye,createClient:s=o(a=>new Ps(a),"createClient")}=r;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await n(a),c=v.from(p.access_token),l=s({appId:t.appId,project:e.project,baseUrl:e.baseUrl,getToken:o(async()=>c.expose(),"getToken")});return await l.authenticate(),l}return i(e,t.appId)}o(I,"getClientForDeployment");import nn from"enquirer";var on="Enter custom target...";function sn(e,t){let r=t.map((n,i)=>` ${i}: ${n.org}/${n.project}`).join(`
|
|
37
35
|
`);throw new Error(`Deployment "${e}" not found. Available deployments:
|
|
38
|
-
${
|
|
36
|
+
${r}`)}o(sn,"deploymentNotFoundError");function x(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;sn(t,e)}let r=e.find(n=>n.project===t||`${n.org}/${n.project}`===t);if(r)return r;sn(t,e)}o(x,"findDeployment");function $(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o($,"getMissingCredentials");async function T(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 x(e.deployments,t.deployment);let r=[...e.deployments.map(s=>`${s.org}/${s.project}`),on],{selected:n}=await nn.prompt({type:"select",name:"selected",message:"Select deployment target",choices:r});if(n!==on){let s=e.deployments.find(a=>`${a.org}/${a.project}`===n);if(s)return s;throw new Error(`Deployment "${n}" could not be resolved from app.json.`)}let i=await nn.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:o(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(T,"resolveDeployment");import{existsSync as xs}from"fs";import{resolve as As}from"path";import{config as Ds}from"dotenv";function R(e,t={existsSync:xs,config:Ds}){let r=As(e,".env");t.existsSync(r)&&(console.log(`Loading environment variables from ${r}`),t.config({path:r}))}o(R,"loadEnvFile");function F(e){e.infra!=="appsApi"&&(console.error(`
|
|
39
37
|
\u26A0\uFE0F Legacy infrastructure is no longer supported.
|
|
40
38
|
|
|
41
39
|
Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
|
|
42
40
|
the old CDF Application Registry. This deploy path has been removed.
|
|
43
41
|
|
|
44
42
|
To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
|
|
45
|
-
`),process.exit(1))}o(F,"assertAppHostingInfra");async function
|
|
43
|
+
`),process.exit(1))}o(F,"assertAppHostingInfra");async function Is(e){let t=process.cwd();R(t);let r=C(t);F(r);let n=e.interactive?await T(r,e):x(r.deployments,e.deployment);if(!e.interactive){let 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 I(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),s=new b(i),{externalId:a,versionTag:p}=r,c;try{c=await s.getVersion(a,p)}catch(d){throw d instanceof B?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):d}if(c.alias==="ACTIVE"){console.log(` ${a} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${a} @ ${p}: version is ${c.lifecycleState} (terminal).`);c.lifecycleState==="DRAFT"&&(await s.publishVersion(a,p),console.log(`\u2713 Published ${a} @ ${p} is now PUBLISHED`));let{supersededVersion:l}=await s.activateVersion(a,p);console.log(`\u2713 Activated ${a} @ ${p} is now ACTIVE`),l&&console.log(` Superseded ${l} \u2192 PUBLISHED`)}o(Is,"handleActivate");function an(e){return e.command("activate").description("Activate the current app version (publish if needed, then set ACTIVE alias)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
46
44
|
Examples:
|
|
47
45
|
npx @cognite/cli apps activate . Activate using env-var auth
|
|
48
|
-
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,
|
|
49
|
-
`),initial:!1};async function
|
|
50
|
-
`),s=`link .specify/memory/constitution.md in specifyDir=${
|
|
46
|
+
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,r)=>Is(r))}o(an,"registerActivateCommand");import{basename as Cn,dirname as la,normalize as da,resolve as Ve}from"path";import{fileURLToPath as ma,pathToFileURL as ua}from"url";import{Logger as ga,runner as fa}from"hygen";import{safeParse as $s}from"valibot";function Se(e,t){return r=>{let n=$s(t,r);return n.success?!0:`${e} ${n.issues[0].message}`}}o(Se,"toPromptValidator");var pn={name:Se("App name",lt),displayName:Se("Display name",ct),baseUrl:Se("Base URL",dt),org:Se("Org",mt),project:Se("Project",ut)};function Ts(e,t){return e?async r=>{let n=t(r);return n===!0?e(r):n}:t}o(Ts,"composeValidators");function Ke(e){return e.map(t=>{if(!(t.name in pn))return t;let r=pn[t.name];return{...t,validate:Ts(t.validate,r)}})}o(Ke,"applySchemaValidators");import{basename as cn}from"path";import ln from"enquirer";function kt(e){return e.replace(/[A-Z]/g,(t,r)=>r===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(kt,"kebabCase");var Rs={type:"confirm",name:"useSpecKit",message:["Enable spec-driven development?"," Adds the github/spec-kit slash commands (/speckit.specify, .clarify, .plan, .tasks, .implement)"," to your app for use in Claude Code or Cursor. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
|
|
47
|
+
`),initial:!1};async function Fs(e,t,r){return e!==void 0?e:t?!!(await r([Rs])).useSpecKit:!1}o(Fs,"resolveSpecKit");function Os(e){return typeof e=="function"}o(Os,"isFunctionInitial");function dn(e){return(e??"").trim().replace(/\/+$/,"")||"api"}o(dn,"normalizeCluster");function mn({isCurrentDir:e,dirName:t,onAppName:r,onUseSpecKit:n,presets:i={},specKit:s,prompt:a=ln.prompt.bind(ln)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(k=>k[1]!==void 0)),l=Object.keys(c).length>0,d=e?cn(process.cwd()):t?cn(t):null,m=l&&d!==null,y=!m&&d?p.map(k=>k.name==="name"?{...k,initial:d}:k):p,S=Ke(y),u=m&&d?{...c,name:d}:c,f=new Set(Object.keys(u)),w=S.filter(k=>!f.has(k.name)),E=w.findIndex(k=>k.name==="baseUrl"),h;if(m){let k=dn(u.cluster),G=o(A=>Os(A.initial)?A.initial():A.initial,"resolveInitial"),se=o(A=>{if(A.name==="baseUrl")return`https://${k}.cognitedata.com`;let Y=G(A);if(Y===void 0)throw new Error(`Non-interactive mode: --${kt(A.name)} has no default. Pass it as a flag.`);return Y},"deriveValue");h=Object.fromEntries(w.map(A=>[A.name,se(A)]))}else if(E!==-1){let k=w.filter(ee=>ee.name!=="baseUrl"),G=k.length>0?await a(k):{},se=typeof G.cluster=="string"?G.cluster:"",Y=`https://${dn(se||u.cluster)}.cognitedata.com`,ke=w[E],Q=await a([{...ke,initial:Y}]);h={...G,...Q}}else h=w.length>0?await a(w):{};let M={...u,...h},H=typeof M.name=="string"?M.name:"";H&&r(H);let U=await Fs(s,!m&&w.length>0,a);return n?.(U),{...M,name:H,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:U}},"prompt")})}o(mn,"createAppPrompter");async function un(e,t,r){let n=[];Object.values(t).some(s=>s!==void 0)&&r!==null&&n.push({key:"name",value:r,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&n.push({key:s,value:a,label:`--${kt(s)}`});for(let{key:s,value:a,label:p}of n){let c=e.find(d=>d.name===s)?.validate;if(!c)continue;let l=await c(a);if(l!==!0)throw new Error(`Invalid ${p}: ${l}`)}}o(un,"validatePresets");import{cpSync as bt,existsSync as Ms,mkdirSync as Pt,writeFileSync as Hs}from"fs";import{dirname as He,posix as js,resolve as K}from"path";import{fileURLToPath as fn}from"url";import{copyFileSync as Us,symlinkSync as _s}from"fs";import{dirname as Ls,join as Ns}from"path";function Ks(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}o(Ks,"errno");function gn(e){return e instanceof Error?e.message:String(e)}o(gn,"messageOf");function Me({target:e,linkPath:t,label:r,symlink:n=_s,copyFile:i=Us}){try{return n(e,t),!0}catch(s){let a=Ks(s);if(a==="EEXIST")return!0;let p=gn(s);if(a==="EPERM"||a==="EACCES")try{let c=Ns(Ls(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: ${gn(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${r} symlink:`,p),!1}}o(Me,"linkOrCopyOrWarn");var Vs=K(He(fn(import.meta.url)),"..","..","_vendor","spec-kit"),Bs=K(He(fn(import.meta.url)),"..","..","_cognite-spec-extensions"),Gs={branch_numbering:"sequential"},Ys=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}],qs=[{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"},{from:"templates",to:".specify/templates"}];function yn({appDir:e,vendorDir:t=Vs,cogniteExtensionsDir:r=Bs}){let n=K(e,".specify"),i=K(n,"memory"),s=`prepare spec-kit install for appDir=${e}`;try{for(let{from:p,to:c}of Ys){let l=K(e,c);s=`copy ${p} to ${c}`,Pt(He(l),{recursive:!0}),bt(K(t,p),l,{recursive:!0})}for(let{from:p,to:c}of qs){let l=K(e,c);s=`copy cognite extension ${p} to ${c}`,Pt(He(l),{recursive:!0}),bt(K(r,p),l,{recursive:!0})}let a=K(n,"extensions.yml");Ms(a)||(s="write .specify/extensions.yml",bt(K(r,"extensions.yml"),a)),s=`write init-options.json under specifyDir=${n}`,Hs(K(n,"init-options.json"),`${JSON.stringify(Gs,null,2)}
|
|
48
|
+
`),s=`link .specify/memory/constitution.md in specifyDir=${n}`,Pt(i,{recursive:!0}),Me({target:js.join("..","..","AGENTS.md"),linkPath:K(i,"constitution.md"),label:".specify/memory/constitution.md"})}catch(a){let p=a instanceof Error?a.message:String(a);throw new Error(`installSpecKit failed while ${s} (appDir=${e}, vendorDir=${t}): ${p}`,{cause:a})}}o(yn,"installSpecKit");import{execFileSync as je}from"child_process";import{mkdtempSync as Js,readdirSync as zs,rmSync as Ws}from"fs";import{createRequire as Xs}from"module";import{tmpdir as Zs}from"os";import{join as Qs,resolve as hn}from"path";import{InvalidArgumentError as ea}from"commander";import ta from"enquirer";var Sn="cognitedata/builder-skills",xt=["claude-code","cursor","github-copilot","opencode","codex"],ra=Xs(import.meta.url).resolve("skills/bin/cli.mjs");function At(e,t={}){try{je(process.execPath,[ra,...e],{stdio:"inherit",cwd:process.cwd(),...t,env:{...process.env,...t.env,DISABLE_TELEMETRY:"1"}})}catch(r){throw new g(`Skills CLI failed (${e.join(" ")})`,{cause:r,hint:"Check your internet connection and that git is installed, then try again."})}}o(At,"execSkillsCli");function na(){return xt.map(e=>["add",Sn,"-a",e,"--skill","*","-y"])}o(na,"pullAllArgsPerAgent");var oa=1e4;async function wn(e,t={}){let r=t.exec??At,n=t.timeout??oa,i=t.readdir??(p=>zs(p));for(let p of na())try{r(p,{cwd:e,timeout:n,stdio:["pipe","pipe","inherit"]})}catch(c){let l=c instanceof Error?c.message:String(c);console.warn("\u26A0\uFE0F Could not pull skills for args ["+p.join(" ")+"]:",l)}let s=new Set;for(let p of[hn(e,".claude","skills"),hn(e,".agents","skills")])try{i(p).forEach(c=>s.add(c))}catch{}let a=s.size;a>0?console.log(`Installed ${a} skills successfully.`):console.log("No skills were installed.")}o(wn,"pullAllSkillsInto");function ia(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new ea("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}o(ia,"validateSource");function sa(e){let t=Js(Qs(Zs(),"skills-"));try{try{je("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch{throw new Error(`Failed to clone skills repository "${e}". Please check your internet connection and ensure git is installed.`)}let r;try{r=je("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{r=je("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return r.toString().trim().split(/\r?\n/).filter(n=>!!n&&!n.startsWith("."))}finally{Ws(t,{recursive:!0,force:!0})}}o(sa,"listRemoteSkills");async function aa(e,t={}){let r=o(p=>ta.prompt(p),"defaultPrompt"),{listSkills:n=sa,prompt:i=r}=t,s=n(e),{selected:a}=await i({type:"multiselect",name:"selected",message:"Select skills to install (space to toggle, a to toggle all, enter to confirm)",choices:s});return a}o(aa,"pickSkillsInteractive");function pa(e,t,r){let n=["add",e.source,"-a",t];return e.skill?n.push("--skill",e.skill):r&&r.length>0?n.push("--skill",...r,"-y"):n.push("--skill","*","-y"),e.global&&n.push("--global"),n}o(pa,"buildPullArgs");async function ca(e){console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await aa(e.source)}catch(n){let i=n instanceof Error?n.message:String(n);console.error(`Failed to resolve skills interactively: ${i}`),process.exitCode=1;return}if(t.length===0){console.log("No skills selected.");return}}let r=!1;for(let n of xt)try{At(pa(e,n,t))}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`\u26A0\uFE0F Could not pull skills for ${n}: ${s}`),r=!0}r?(console.log(`
|
|
51
49
|
Skills pulled with some errors (see warnings above)`),process.exitCode=1):console.log(`
|
|
52
|
-
Skills pulled successfully`)}o(
|
|
53
|
-
Supports: ${
|
|
50
|
+
Skills pulled successfully`)}o(ca,"handlePull");function vn(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
|
|
51
|
+
Supports: ${xt.join(", ")}`).addHelpText("after",`
|
|
54
52
|
Examples:
|
|
55
53
|
npx @cognite/cli apps skills pull Pull all skills
|
|
56
54
|
npx @cognite/cli apps skills pull --skill create-client-tool Pull a specific skill
|
|
57
|
-
npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository",
|
|
58
|
-
npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=
|
|
55
|
+
npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository",ia,Sn).option("--skill <name>","Pull a specific skill by name").option("-i, --interactive","Interactively select which skills to install",!1).option("--global","Install skills globally",!1).action(ca),t.command("list").description("List installed skills").action(()=>{At(["list"])}),t}o(vn,"registerSkillsCommand");var En=Ve(la(ma(import.meta.url)),"..","..","_templates");async function ya(){let e=Ve(En,"app","new","prompt.js");return(await import(ua(e).href)).default}o(ya,"loadPromptDefs");function ha(e,t){return!e||t?null:da(e)}o(ha,"resolveDirName");function Sa(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:Ve(process.cwd(),n),display:n}}o(Sa,"resolveAppLocation");function wa(e,t,r){let n=` npm install
|
|
56
|
+
npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=r?`
|
|
59
57
|
To start spec-driven development:
|
|
60
58
|
Run /speckit.specify in Claude Code or Cursor and describe your app.
|
|
61
59
|
`:"",p=` # Or fully non-interactive (deploys first target from app.json):
|
|
@@ -63,7 +61,7 @@ To start spec-driven development:
|
|
|
63
61
|
\u2705 App created successfully in current directory!
|
|
64
62
|
|
|
65
63
|
Next steps:
|
|
66
|
-
${
|
|
64
|
+
${n}
|
|
67
65
|
${a}
|
|
68
66
|
${i}
|
|
69
67
|
${s}
|
|
@@ -75,13 +73,13 @@ To open in Cursor:
|
|
|
75
73
|
cursor "${t}"
|
|
76
74
|
Or:
|
|
77
75
|
cd "${t}"
|
|
78
|
-
${
|
|
76
|
+
${n}
|
|
79
77
|
${a}
|
|
80
78
|
${i}
|
|
81
79
|
cd "${t}"
|
|
82
80
|
${s}
|
|
83
81
|
${p}
|
|
84
|
-
`)}o(
|
|
82
|
+
`)}o(wa,"printSuccessMessage");async function va(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await wn(e)}catch(t){let r=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",r)}}o(va,"pullSkillsInto");function Ca(e,t={}){let{isGitInstalled:r=be,isInsideGitRepo:n=Pe,gitInitAndCommit:i=sr}=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(s){let p=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",p)}}}o(Ca,"maybeInitGit");async function Ea(e,t){let r=e==="."||e==="./",n=ha(e,r),i=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await ya(),c=Ke(p),l=r?Cn(process.cwd()):n?Cn(n):null;await un(c,a,l);let d=mn({isCurrentDir:r,dirName:n,onAppName:o(y=>{i=y},"onAppName"),onUseSpecKit:o(y=>{s=y},"onUseSpecKit"),presets:a,specKit:t.specKit});await fa(["app","new"],{templates:En,cwd:process.cwd(),logger:new ga(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=Sa(r,n,i);Me({target:"AGENTS.md",linkPath:Ve(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&yn({appDir:m.cwd}),await va(m.cwd),Ca(m.cwd),wa(r,m.display,s)}o(Ea,"handleCreate");function kn(e){return e.command("create").description("Create a new application.").argument("[directory]","Target directory (. for current, or subdirectory name)").option("--display-name <name>","App display name (skips the prompt)").option("--description <description>","App description (skips the prompt)").option("--org <org>","Deployment org (skips the prompt)").option("--project <project>","Deployment project (skips the prompt)").option("--cluster <cluster>","CDF cluster, e.g. greenfield (skips the prompt)").option("--base-url <url>","CDF base URL, e.g. https://greenfield.cognitedata.com (skips the prompt; defaults to cluster-derived URL when omitted)").option("--spec-kit","Install spec-kit slash commands (skips the prompt)").option("--no-spec-kit","Skip spec-kit installation (skips the prompt)").addHelpText("after",`
|
|
85
83
|
Non-interactive use (CI, scripts, AI agents):
|
|
86
84
|
Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
|
|
87
85
|
to skip every prompt. Missing flags fall back to the interactive prompt.
|
|
@@ -94,22 +92,22 @@ Examples:
|
|
|
94
92
|
--display-name "My App" --description "My app" \\
|
|
95
93
|
--org cog-atlas --project atlas-greenfield --cluster greenfield \\
|
|
96
94
|
--base-url https://greenfield.cognitedata.com
|
|
97
|
-
Fully non-interactive`).action(
|
|
95
|
+
Fully non-interactive`).action(Ea)}o(kn,"registerCreateCommand");import ka from"path";async function ba(e,t,r){let n=await I(e,{interactive:t.interactive,appId:r,orgHint:t.org});return new b(n)}o(ba,"defaultGetApiClient");async function Pa(e,t,r={}){let{loadEnvFile:n=R,loadAppConfig:i=C,getApiClient:s=ba}=r,a=ka.resolve(process.cwd(),e);n(a);let p=i(a);F(p);let c=t.interactive?await T(p,t):x(p.deployments,t.deployment);if(!t.interactive){let y=$(c);if(y.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${y.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let{externalId:l}=p,d=await s(c,t,l),m=await d.getActiveVersion(l);if(!m){console.log(` ${l} has no active version \u2014 nothing to deactivate.`);return}await d.deactivateVersion(l,m.version),console.log(`\u2713 Deactivated ${l} @ ${m.version} \u2014 active alias removed`)}o(Pa,"handleDeactivate");function bn(e){return e.command("deactivate").description("Deactivate the app by removing its active version from service").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
98
96
|
Examples:
|
|
99
97
|
npx @cognite/cli apps deactivate . Deactivate using env-var auth
|
|
100
|
-
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,
|
|
101
|
-
`).filter(Boolean),i=o(a=>a.split("/").some(p
|
|
98
|
+
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,r)=>Pa(t,r))}o(bn,"registerDeactivateCommand");import{mkdir as Ta,readFile as Ra}from"fs/promises";import{basename as Fa,dirname as Oa}from"path";import{execFileSync as Be}from"child_process";import W from"fs";import O from"path";import{parseAndValidateManifestConfig as xa}from"@cognite/app-sdk/vite";import{BlobReader as Aa,Uint8ArrayWriter as Da,ZipWriter as Ia}from"@zip.js/zip.js";var Dt="package.json",It="package-lock.json",Pn="manifest.json",$t=".cognite",$a=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],Tt=class Tt{constructor(t="dist"){this.distPath=O.isAbsolute(t)?t:O.join(process.cwd(),t),this.appRoot=O.dirname(this.distPath)}validateBuildDirectory(){if(!W.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=O.join(this.appRoot,Dt);if(!W.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let r=O.join(this.appRoot,It);if(!W.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 Ia(new Da,{level:9}),i=o(async(c,l)=>{await n.add(l,new Aa(await W.openAsBlob(c))),r&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=o(async c=>{let l=await W.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=O.join(c,d.name);d.isDirectory()?await s(m):await i(m,O.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=O.join(this.appRoot,Dt);await i(c,O.posix.join($t,Dt));let l=O.join(this.appRoot,Pn);if(W.existsSync(l)){let m=W.readFileSync(l,"utf-8");xa(m,l),await i(l,O.posix.join($t,Pn))}let d=O.join(this.appRoot,It);await i(d,O.posix.join($t,It)),a=await n.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}try{await W.promises.writeFile(t,a)}catch(c){throw new g(`Failed to write bundle to ${t}`,{cause:c})}let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let r;try{r=Be("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let n=Be("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=n?n.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(r,s);try{Be("git",["-C",r,"archive","--format=zip",`--output=${t}`,s])}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${l}`)}let p=(W.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${O.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,r){let n=Be("git",["-C",t,"ls-tree","-r","--name-only",r],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
99
|
+
`).filter(Boolean),i=o(a=>a.split("/").some(p=>$a.some(c=>c.test(p))),"isSensitive"),s=n.filter(i);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
|
|
102
100
|
`+s.map(a=>` ${a}`).join(`
|
|
103
101
|
`)+`
|
|
104
|
-
Hint: git rm --cached <file>`)}};o(
|
|
105
|
-
`))}o(
|
|
106
|
-
\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
|
|
107
|
-
To sign: npx @cognite/cli apps sign --interactive${
|
|
108
|
-
To submit for certification: npx @cognite/cli apps submit`);let
|
|
102
|
+
Hint: git rm --cached <file>`)}};o(Tt,"ApplicationPackager");var ie=Tt;async function Ge(e,t,r,n){let{externalId:i,name:s,description:a,versionTag:p}=t,c=q(r,i,p);await Ta(Oa(c),{recursive:!0}),await new ie(`${r}/dist`).createZip(c,!0);let l;try{l=await Ra(c)}catch(d){throw new g(`Failed to read bundle file: ${c}`,{cause:d})}await new b(e).deploy(i,s,a,p,l,Fa(c),n)}o(Ge,"packageAndUpload");var Rt=o(async(e,t,r)=>{let n=await ye(e,r);await Ge(n,t,r,e.published)},"deploy");import{existsSync as Ua,readFileSync as _a}from"fs";var xn=[".dev.sig",".cert.sig"];function we(e,t={}){let r=t.existsSync??Ua,n=t.readFileSync??((s,a)=>_a(s,a)),i=[];for(let s of xn){let a=`${e}${s}`;if(!r(a))continue;let p=n(a,"utf8").trim();p.length>0&&i.push(p)}return i}o(we,"discoverSignatures");import{execSync as La}from"child_process";function Ft(e,t=!0,r={execSync:La}){console.log("\u{1F4E6} Building app with npm...");try{r.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(n){throw new g(`npm run build failed in ${e}`,{cause:n,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}o(Ft,"buildApp");function An(e,t){let{org:r,project:n,baseUrl:i}=e,s;try{s=new URL(i).hostname}catch{return null}let{externalId:a,versionTag:p}=t,c=new URLSearchParams({cluster:s,customAppVersion:p,workspace:"industrial-tools"});return`https://${r}.fusion.cognite.com/${n}/flows-apps/app/${encodeURIComponent(a)}?${c}`}o(An,"generateFusionUrl");function Dn(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(`
|
|
103
|
+
`))}o(Dn,"printDeployInfo");function In(e,t){console.log(`
|
|
104
|
+
\u2705 Successfully deployed ${e.name} version ${e.versionTag} to ${t.org?`${t.org}/`:""}${t.project}`),console.log("\u{1F512} App is deployed in draft mode");let r=e.deployments.length>1?` -d ${t.project}`:"";console.log(`
|
|
105
|
+
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}`),console.log(`
|
|
106
|
+
To submit for certification: npx @cognite/cli apps submit`);let n=An(t,e);n&&console.log(`
|
|
109
107
|
\u{1F517} Open your app:
|
|
110
|
-
${
|
|
111
|
-
\u{1F4E4} Deploying to ${t.org}/${t.project}...`),await i({...t,published:!1},{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},
|
|
112
|
-
\u{1F4E4} Deploying to ${t.project}...`),await
|
|
108
|
+
${n}`)}o(In,"printDeployResult");async function Na(e,t,r,n,i){let s=$(t);if(s.length>0)throw new Error(`Deployment ${t.org}/${t.project} is missing ${s.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);Dn(e,t,!1),n.skipBuild||Ft(r),console.log(`
|
|
109
|
+
\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),In(e,t)}o(Na,"handleDeployNonInteractive");async function Ka(e,t,r,n){Dn(e,t,!0),n.skipBuild||Ft(r);let i=await I(t,{interactive:!0,appId:e.externalId,orgHint:n.org});console.log(`
|
|
110
|
+
\u{1F4E4} Deploying to ${t.project}...`),await Ge(i,{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},r,!1),In(e,t)}o(Ka,"handleDeployInteractive");async function Ma(e,t=process.cwd(),r={}){let{loadEnvFile:n=R,loadAppConfig:i=C,deploy:s=Rt}=r;n(t);let a=i(t);if(F(a),e.interactive){let c=await T(a,e);await Ka(a,c,t,e);return}let p=x(a.deployments,e.deployment);await Na(a,p,t,e,s)}o(Ma,"handleDeploy");function $n(e){return e.command("deploy").description("Deploy your app to Cognite Data Fusion. Use --interactive for browser-based login (no env-var secrets required).").option("-d, --deployment <target>","Deployment target (index or project name)").option("--skip-build","Skip the build step",!1).option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
113
111
|
Environment (non-interactive):
|
|
114
112
|
deployClientId and deploySecretName are configured per deployment in app.json.
|
|
115
113
|
deploySecretName is the name of the environment variable that holds the client
|
|
@@ -123,76 +121,76 @@ Examples:
|
|
|
123
121
|
npx @cognite/cli apps deploy -d my-project Deploy to project by name
|
|
124
122
|
npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
|
|
125
123
|
npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
|
|
126
|
-
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>
|
|
124
|
+
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>Ma(t))}o($n,"registerDeployCommand");function Ha(e,t){console.log(""),console.log(`Updating metadata for '${e}':`);for(let{field:r,remote:n,local:i}of t){let s=`${r}:`.padEnd(13);console.log(` ${s}"${n}" \u2192 "${i||"(none)"}"`)}}o(Ha,"printMetadataDiff");async function ja(e,t=process.cwd(),r={}){let{loadEnvFile:n=R,loadAppConfig:i=C,getClientForDeployment:s=I,createMetadataClient:a=o(f=>new b(f),"createMetadataClient"),getMissingCredentials:p=$}=r;n(t);let c=i(t);F(c);let l=e.interactive?await T(c,e):x(c.deployments,e.deployment);if(!e.interactive){let f=p(l);if(f.length>0)throw new Error(`Deployment ${l.org}/${l.project} is missing ${f.join(" and ")} in app.json. Use \`cognite apps metadata update --interactive\` for browser-based authentication instead.`)}let d=await s(l,{interactive:e.interactive,appId:c.externalId,orgHint:e.org}),m=a(d),y;try{y=await m.getApp(c.externalId)}catch(f){throw f instanceof de?new Error(`App '${c.externalId}' is not deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):f}let S={name:c.name,description:c.description||""},u=St(y,S);if(u.length===0){console.log(""),console.log(`Metadata for '${c.externalId}' already matches the deployed app \u2014 nothing to update.`),console.log("Edit name/description in app.json to change them.");return}Ha(c.externalId,u),await m.updateAppMetadata(c.externalId,c.name,c.description),console.log(""),console.log(`\u2705 Metadata for '${c.externalId}' updated`)}o(ja,"handleUpdateMetadata");function Tn(e){let t=e.command("metadata").summary("Manage the deployed app's metadata").description("Manage the deployed app's metadata (name and description).");return t.command("update").description("Update the deployed app's name and description from app.json").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
127
125
|
Examples:
|
|
128
126
|
npx @cognite/cli apps metadata update . Push name/description using env-var auth
|
|
129
|
-
npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((n
|
|
127
|
+
npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((r,n)=>ja(n)),t}o(Tn,"registerMetadataCommand");async function Va(e,t,r){let n=await I(e,{interactive:t.interactive,appId:r.externalId,orgHint:t.org});return new b(n)}o(Va,"defaultBuildApiClient");async function Ba(e,t={}){let r=t.loadEnvFile??R,n=t.loadAppConfig??C,i=t.buildApiClient??Va,s=t.discoverSignatures??we,a=process.cwd();r(a);let p=n(a);F(p);let c=e.interactive?await T(p,e):x(p.deployments,e.deployment);if(!e.interactive){let u=$(c);if(u.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${u.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let l=await i(c,e,p),{externalId:d,versionTag:m}=p,y;try{y=await l.getVersion(d,m)}catch(u){throw u instanceof B?new Error(`Version ${m} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):u}if(y.alias==="ACTIVE"){console.log(` ${d} @ ${m} is already ACTIVE \u2014 nothing to do.`);return}if(y.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${m} is already PUBLISHED \u2014 nothing to do.`);return}if(y.lifecycleState==="DEPRECATED"||y.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${m}: version is ${y.lifecycleState} (terminal).`);let S=s(q(a,d,m));S.length>0&&await l.submitSignatures(d,m,S),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(Ba,"handlePublish");function Rn(e){return e.command("publish").description("Publish the current app version (transition DRAFT \u2192 PUBLISHED)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
130
128
|
Examples:
|
|
131
129
|
npx @cognite/cli apps publish . Publish using env-var auth
|
|
132
|
-
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,
|
|
130
|
+
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,r)=>Ba(r))}o(Rn,"registerPublishCommand");import{spawnSync as Ga}from"child_process";import{mkdirSync as Ya}from"fs";import{resolve as Ot}from"path";var qa=["localhost","local.cognite.ai","*.local.cognite.ai"],Ja={info:o(e=>{process.stdout.write(`${e}
|
|
133
131
|
`)},"info"),error:o(e=>{process.stderr.write(`${e}
|
|
134
|
-
`)},"error")},
|
|
132
|
+
`)},"error")},za={spawnSync:Ga,mkdirSync:Ya,logger:Ja};function Wa(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}o(Wa,"hasMkcert");function Xa({certDir:e=Ot(process.cwd(),"certificates/mkcert"),domains:t=qa,deps:r={}}={}){let n={...za,...r},{spawnSync:i,mkdirSync:s,logger:a}=n;if(!Wa(i))throw a.error("Error: mkcert is not installed."),a.error("Install it with: brew install mkcert (macOS, Linux, WSL)"),a.error("On Windows: choco install mkcert (or scoop install mkcert)"),a.error("See https://github.com/FiloSottile/mkcert#installation for other methods."),new Error("mkcert is not installed");if(a.info("\u2139\uFE0F Installing mkcert root CA into your local trust store."),a.info(" This allows your browser to trust locally-generated certificates."),a.info(" You may be prompted for your system password."),i("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");s(e,{recursive:!0});let c=Ot(e,"localhost.pem"),l=Ot(e,"localhost-key.pem");if(i("mkcert",["-cert-file",c,"-key-file",l,...t],{stdio:"inherit"}).status!==0)throw new Error("mkcert failed to generate certificates");return a.info(""),a.info("Certificates generated:"),a.info(` cert: ${c}`),a.info(` key: ${l}`),{certFile:c,keyFile:l}}o(Xa,"setupHttps");function Za(e){Xa({certDir:e.certDir})}o(Za,"handleSetupHttps");function Fn(e){return e.command("setup-https").description("Generate trusted local HTTPS certificates via mkcert").option("--cert-dir <path>","Directory to write certs into (default: ./certificates/mkcert)").addHelpText("after",`
|
|
135
133
|
Examples:
|
|
136
134
|
npx @cognite/cli@latest apps setup-https Generate certs in ./certificates/mkcert
|
|
137
|
-
npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>
|
|
135
|
+
npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>Za(t))}o(Fn,"registerSetupHttpsCommand");import{existsSync as Sp,writeFileSync as wp}from"fs";import{basename as vp,dirname as Cp,join as Ep,resolve as Kt}from"path";import{parseScope as kp,signBundle as bp,validateScopes as Pp}from"@cognite/app-sdk/codesigning";import{existsSync as fp,readFileSync as yp}from"fs";import{pbkdf2 as tp,randomBytes as rp}from"crypto";import{promisify as np}from"util";import{CompactEncrypt as op,base64url as On,compactDecrypt as ip}from"jose";var Qa=new TextEncoder,ep=new TextDecoder,Ut={encode:o(e=>Qa.encode(e),"encode"),decode:o(e=>ep.decode(e),"decode")};var sp=np(tp),Nt=6e5,ap="sha512",_t="PBKDF2-HMAC-SHA512",Lt=16,Ye="A256GCM",pp=32,qe=2e6;async function Un(e,t,r){return await sp(e,t,r,pp,ap)}o(Un,"deriveKey");async function _n(e,t,r=Nt){if(!Number.isInteger(r)||r<1||r>qe)throw new Error(`Invalid iterations: must be an integer between 1 and ${qe}`);let n=rp(Lt),i=await Un(t.expose(),n,r);return await new op(Ut.encode(e.expose())).setProtectedHeader({alg:"dir",enc:Ye,kdf:_t,kdf_iter:r,kdf_salt:On.encode(n)}).encrypt(i)}o(_n,"encryptStringAsJwe");async function Ln(e,t){let{plaintext:r}=await ip(e,async n=>{if(!e.length)throw new Error("Unexpected JWE empty value");let i=t.expose();if(i.length<15)throw new Error(`Invalid passphrase: must be at least ${15} characters`);if(n.alg!=="dir")throw new Error(`Unexpected JWE alg "${String(n.alg)}"; only "dir" is supported`);if(n.enc!==Ye)throw new Error(`Unexpected JWE enc "${String(n.enc)}"; only "${Ye}" is supported`);if(n.kdf!==_t)throw new Error(`Unexpected KDF "${String(n.kdf)}"; only "${_t}" is supported`);let s=Number(n.kdf_iter);if(!Number.isInteger(s)||s<1||s>qe)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${qe}`);if(typeof n.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let a=On.decode(n.kdf_salt);if(a.length!==Lt)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Lt} bytes, got ${a.length}`);return await Un(i,a,s)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[Ye]});return Ut.decode(r)}o(Ln,"decryptJweAsString");function cp(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}o(cp,"isJweCompact");var Nn=cp;import lp from"enquirer";async function dp(e){return lp.prompt(e)}o(dp,"defaultPrompt");async function Kn(e,t={}){let{prompt:r=dp}=t,{passphrase:n}=await r({type:"password",name:"passphrase",message:e});return v.from(n)}o(Kn,"promptPassphrase");import up from"enquirer";import{statSync as mp}from"fs";function Mn(e,t=mp){return e.map(r=>({key:r,mtime:t(r.publicKeyPath).mtimeMs})).sort((r,n)=>n.mtime-r.mtime).map(({key:r})=>r)}o(Mn,"sortByMtime");async function gp(e){return up.prompt(e)}o(gp,"defaultPrompt");async function Hn(e,t={}){if(e.length===1)return e[0];let{prompt:r=gp,sortByMtime:n=Mn}=t,i=n(e),s=i[0],{choice:a}=await r({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 r({type:"select",name:"kid",message:"Select signing identity",choices:i.map(l=>({name:l.kid,message:[l.kid,l.email,$e(l.source)].filter(Boolean).join(" \u2014 ")}))}),c=i.find(l=>l.kid===p);if(!c)throw new Error("No signing identity selected");return c}else throw new Error(`Unexpected choice: "${a}"`)}o(Hn,"promptSigningIdentity");function hp(e){return{existsSync:e.existsSync??fp,readFileSync:e.readFileSync??((t,r)=>yp(t,r)),readKeyFromKeychain:e.readKeyFromKeychain??Ie,decryptJweAsString:e.decryptJweAsString??Ln,discoverLocalKeys:e.discoverLocalKeys??Te,keysDir:e.keysDir??D().keysDir,promptPassphrase:e.promptPassphrase??Kn,promptSigningIdentity:e.promptSigningIdentity??Hn}}o(hp,"resolveDeps");async function jn(e,t={}){let r=hp(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 s=r.readFileSync(e.keyPath,"utf-8").trim();if(Nn(s)){if(!e.interactive)throw new Error(`Key at ${e.keyPath} is passphrase-encrypted. Pass --interactive to enter the passphrase.`);let a=await r.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:v.from(await r.decryptJweAsString(s,a)),kid:e.kid}}return{privateKeyPem:v.from(s),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;if(e.kid)i=n.find(s=>s.kid===e.kid);else if(e.interactive)i=await r.promptSigningIdentity(n);else throw new Error("--signing-identity <kid> is required. Pass --interactive to select it interactively.");if(!i)throw new Error(`No key found with kid "${e.kid}"`);switch(i.source.kind){case"keychain":{let s=await r.readKeyFromKeychain(i.kid);if(!s)throw new Error(`Key "${i.kid}" not found in Keychain`);return{privateKeyPem:s,kid:i.kid}}case"encrypted-file":{if(!e.interactive)throw new Error(`Key "${i.kid}" is passphrase-encrypted. Pass --interactive to enter the passphrase, or store the key in macOS Keychain for non-interactive use.`);let s=await r.promptPassphrase(`Passphrase for key ${i.kid}: `);return{privateKeyPem:v.from(await r.decryptJweAsString(r.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(jn,"resolvePrivateKey");var xp=o(async(e,t,r,n,i)=>{let s=await I(e,{interactive:i.browserAuth??!1,appId:t,orgHint:i.org});await new b(s).submitSignatures(t,r,n)},"defaultSubmitSignatures");function Ap(e){return{existsSync:e.existsSync??Sp,writeFileSync:e.writeFileSync??wp,createBundleStream:e.createBundleStream??Re,signBundle:e.signBundle??bp,parseScope:e.parseScope??kp,validateScopes:e.validateScopes??Pp,loadAppConfig:e.loadAppConfig??C,resolvePrivateKey:e.resolvePrivateKey??(t=>jn(t)),submitSignatures:e.submitSignatures??xp,discoverSignatures:e.discoverSignatures??we}}o(Ap,"resolveDeps");async function Vn(e,t,r={},n=process.cwd()){let i=Ap(r),s=t.appid,a=t.appVersion,p=[],c=i.loadAppConfig(n);if(s=s??c.externalId,a=a??c.versionTag,t.scope&&t.scope.length>0?p=t.scope.map(i.parseScope):p=c.deployments.map(h=>({org:h.org,project:h.project})),!s)throw new Error("--appid is required (or set externalId in app.json)");if(!a)throw new Error("--app-version is required (or set versionTag in app.json)");let l=e?Kt(n,e):q(n,s,a);if(!i.existsSync(l)){let h=e?"":" (default derived from app.json \u2014 pass [bundle] explicitly to override, or run `cognite apps deploy` first to populate .cognite-bundles/)";throw new Error(`Bundle not found: ${l}${h}`)}let d=i.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
|
|
138
136
|
${d.join(`
|
|
139
|
-
`)}`);let{privateKeyPem:m,kid:y}=await i.resolvePrivateKey({keyPath:t.key?
|
|
140
|
-
Payload:`,JSON.stringify(
|
|
141
|
-
To publish: npx @cognite/cli apps publish .`)}o(
|
|
137
|
+
`)}`);let{privateKeyPem:m,kid:y}=await i.resolvePrivateKey({keyPath:t.key?Kt(n,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),S=i.createBundleStream(l),u=await i.signBundle({privateKeyPem:m.expose(),kid:y,appId:s,version:a,bundleStream:S,role:t.asCertifier?"certifier":"developer",scopes:p}),f=t.output?Kt(n,t.output):Ep(Cp(l),`${vp(l)}.${t.asCertifier?"cert":"dev"}.sig`);i.writeFileSync(f,u.token,"utf-8"),console.log(`\u2705 Signed: ${f}`),console.log(` kid: ${u.kid}`),console.log(` bundle: ${u.payload.bundleSha256}`),console.log(` scopes: ${u.payload.scopes.map(h=>`${h.org}/${h.project}`).join(", ")}`),t.verbose&&console.log(`
|
|
138
|
+
Payload:`,JSON.stringify(u.payload,null,2));let w=Array.from(new Set([...i.discoverSignatures(l),u.token])),E=t.interactive?await T(c,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):x(c.deployments,t.deployment);if(!t.browserAuth){let h=$(E);if(h.length>0)throw new Error(`Deployment ${E.org}/${E.project} is missing ${h.join(" and ")} in app.json. Pass --browser-auth to authenticate via browser instead.`)}await i.submitSignatures(E,s,a,w,t),console.log(`
|
|
139
|
+
To publish: npx @cognite/cli apps publish .`)}o(Vn,"handleSign");function Bn(e,t={}){return e.command("sign [bundle]").description("Sign an app bundle (defaults to .cognite-bundles/<app>-<version>.zip)").option("--key <path>","Private key PEM file path").option("-s, --signing-identity <kid>","Key ID for Keychain or file lookup").option("--appid <id>","Application ID (default: externalId from app.json)").option("-i, --identifier <id>","Alias for --appid").option("--app-version <version>","App version (default: versionTag from app.json)").option("--scope <org/project...>","Deployment scope(s) (default: deployments from app.json)").option("-r, --requirements <org/project...>","Alias for --scope").option("-o, --output <path>","Output file path (default: <bundle>.<dev|cert>.sig)").option("-v, --verbose","Display full payload after signing").option("--as-certifier","Counter-sign a developer signature as certifier").option("--interactive","Enable interactive prompts (key selection, passphrase, deployment target selection)",!1).option("--browser-auth","Use browser-based PKCE auth when submitting the signature",!1).option("-d, --deployment <target>","Deployment target from app.json (index or name; submit step only)").option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive or --browser-auth)").action((r,n)=>{let i={...n,appid:n.identifier??n.appid,scope:n.requirements??n.scope};return Vn(r,i,t)})}o(Bn,"registerSignCommand");function Dp(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(Dp,"describeStatus");function Ip(e){if(e.length===0)return["Signatures: none stored"];let t=["Signatures:"];for(let r of e){let n=r.status==="VALID"?"\u2705":"\u274C",i=new Date(r.signatureIat).toISOString();t.push(` ${n} ${r.signerKid} (${r.signerRole}, signed ${i}) \u2014 ${r.status}`)}return t}o(Ip,"formatSignatures");async function $p(e){let t=process.cwd();R(t);let r=C(t);F(r);let n=e.interactive?await T(r,e):x(r.deployments,e.deployment);if(!e.interactive){let a=$(n);if(a.length>0)throw new Error(`Deployment ${n.org}/${n.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let i=await I(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),s=new b(i);console.log(""),console.log(`App: ${r.name} (${r.externalId})`),console.log(`Version: ${r.versionTag} (local)`);try{let a=await s.getVersion(r.externalId,r.versionTag);console.log(`Status: ${Dp(a)}`);let p=await Tp(s,r.externalId,r.versionTag);if(console.log(""),p==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let c of Ip(p))console.log(c);a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof B){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}o($p,"handleStatus");async function Tp(e,t,r){try{return await e.listSignatures(t,r)}catch(n){if(oe(n)&&n.status===404||n instanceof Error&&/status code: 404/.test(n.message))return"endpoint-unavailable";throw n}}o(Tp,"fetchSignatures");function Gn(e){return e.command("status").description("Show the deployment status and signatures of the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
142
140
|
Examples:
|
|
143
141
|
npx @cognite/cli apps status . Status using env-var auth
|
|
144
|
-
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,
|
|
145
|
-
`))}</pre>`,p=
|
|
146
|
-
Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}o(
|
|
142
|
+
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,r)=>$p(r))}o(Gn,"registerStatusCommand");import{execFileSync as jt}from"child_process";import Ht from"fs";import ve from"path";import Up from"readline";var Yn="https://cognite.zendesk.com",Rp="360001234312",Fp="tf_360015295097",Op="cognite_flows_certifications";function qn(e,t,r){let n=new URLSearchParams({ticket_form_id:Rp,tf_priority:"normal",tf_subject:e,[Fp]:Op,tf_description:t});return`${r}/hc/en-us/requests/new?${n}`}o(qn,"buildUrl");function Jn(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}o(Jn,"escapeHtml");function Mt(e){return e.map(Jn).join("<br>")}o(Mt,"toHtml");function zn(e,t=Yn){let{appName:r,externalId:n,versionTag:i,archiveName:s,developerName:a,cdfProject:p,cdfCluster:c}=e,l=["Dear Cognite Platform Team,","","I would like to submit my Flows app for review and certification.","",`App name: ${r}`,`App external ID: ${n}`,`Version: ${i}`,p?`CDF project: ${p}`:void 0,c?`CDF cluster: ${c}`:void 0,"","`npx @cognite/cli apps submit` verified App-Brief.md,","code-review-report.md, and design-review-report.md are committed to git.","","Attached (all from dist/submit/):",`[ ] ${s??"src-<sha>.zip"} \u2014 source archive`,`[ ] ${n}-${i}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return qn(`App Review Request: ${r}`,Mt(l.filter(d=>d!==void 0)),t)}o(zn,"buildAppReviewUrl");function Wn(e,t,r,n,i=Yn){let s=Mt(["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 public_keys.yaml:"]),a=`<pre>${Jn(n.replace(/\r\n/g,`
|
|
143
|
+
`))}</pre>`,p=Mt(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return qn(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,i)}o(Wn,"buildKeyRegistrationUrl");function _p(){return new Promise(e=>{let t=Up.createInterface({input:process.stdin,output:process.stdout});t.question(`
|
|
144
|
+
Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}o(_p,"defaultPressEnter");var Lp=[{pattern:"App-Brief.md",label:"App-Brief.md",skill:"flows-app-brief"},{pattern:"reviews/code-review/*/code-review-report.md",label:"reviews/code-review/feedback-round-<N>/code-review-report.md",skill:"flows-code-review"},{pattern:"reviews/design-review/*/design-review-report.md",label:"reviews/design-review/feedback-round-<N>/design-review-report.md",skill:"flows-design-review"}];function Np(e){let t=Lp.filter(({pattern:r})=>jt("git",["-C",e,"ls-files","--",r],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length===0);if(t.length>0){let r=t.map(({label:n,skill:i})=>` ${n} \u2192 /${i}`);throw new Error(`Certification files are missing or not committed. Run the required skills in Claude Code first:
|
|
147
145
|
|
|
148
|
-
`+
|
|
149
|
-
`)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}o(
|
|
146
|
+
`+r.join(`
|
|
147
|
+
`)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}o(Np,"assertArtifactsCommitted");async function Kp(e=process.cwd(),t={}){let{openInBrowser:r=Dr,revealInFileManager:n=Ir,pressEnter:i=_p,isInteractive:s=o(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(!be())throw new Error("git is not installed. Install git and ensure it is in your PATH.");if(!Pe(e))throw new Error("Not a git repository. Run this command from your app's root directory.");R(e);let a=C(e);F(a),Np(e);let p=ve.join(e,"dist","submit");Ht.mkdirSync(p,{recursive:!0});let c=jt("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(jt("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length>0)throw new Error(`Working tree has uncommitted changes. Commit or stash them before submitting for certification.
|
|
150
148
|
|
|
151
|
-
The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=
|
|
152
|
-
\u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(
|
|
149
|
+
The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=ve.join(p,d);await new ie(ve.join(e,"dist")).createSourceArchive(m);let S=`${a.externalId}-${a.versionTag}.zip`,u=ve.join(e,".cognite-bundles",S),f=!1;Ht.existsSync(u)&&(Ht.copyFileSync(u,ve.join(p,S)),f=!0);let w=zn({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:ar(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});console.log(`
|
|
150
|
+
\u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(f?` ${S} \u2014 deploy bundle`:" \u26A0 Deploy bundle missing \u2014 run `apps deploy` to generate it, then re-run submit"),console.log(" \u2190 add your screen recording to this folder"),console.log(`
|
|
153
151
|
Attach all files from dist/submit/ to the Zendesk ticket.`),console.log(`
|
|
154
|
-
\u{1F517} ${w}`),s()&&(await i(),
|
|
152
|
+
\u{1F517} ${w}`),s()&&(await i(),r(w),n(m))}o(Kp,"handleSubmit");function Xn(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
|
|
155
153
|
Examples:
|
|
156
|
-
npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>
|
|
154
|
+
npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>Kp())}o(Xn,"registerSubmitCommand");function Zn(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return kn(t),$n(t),Gn(t),Tn(t),Rn(t),an(t),bn(t),Fn(t),Xn(t),vn(t),Bn(t),Mr(t),t}o(Zn,"registerAppsCommand");import{existsSync as Gp,mkdirSync as Yp,writeFileSync as qp}from"fs";import{dirname as Gt,join as Ee}from"path";import{generateSigningKeyPair as Jp}from"@cognite/app-sdk/codesigning";import zp from"open";function Qn(e,t){let r=e.getUTCFullYear(),n=e.getUTCMonth()+t,i=new Date(Date.UTC(r,n+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(r,n,s))}o(Qn,"addMonthsClamped");function Vt(e){return e.toISOString().slice(0,10)}o(Vt,"formatIsoDate");function eo(e=new Date){return Vt(e)}o(eo,"todayIso");import Mp,{Chalk as Hp}from"chalk";var Ce=new Hp({level:0});function to(e){return e.isTTY?Mp:Ce}o(to,"chalkForStream");var Je=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),ro=32,no=44,oo=60,jp="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function Vp(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==no&&t.length!==oo)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${no} (raw) or ${oo} (X.509-wrapped)`);let r=Buffer.from(t,"base64");if(r.length===Je.length+ro&&r.subarray(0,Je.length).equals(Je))return r.subarray(Je.length).toString("base64");if(r.length===ro)return r.toString("base64");throw new Error(`Unexpected Ed25519 public key length: got ${r.length} bytes, expected 32 (raw) or 44 (X.509-wrapped)`)}o(Vp,"pemBodyOneLine");function Bt(e,t=Ce,r=new Date){let n=io(e.issuedAt??eo(r)),i=io(e.expires),s=Vp(e.publicKeyPem),a=" ",p=o((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
|
|
157
155
|
`,"kv"),c="";return c+=`
|
|
158
|
-
${t.bold("Add this entry to")} ${t.magenta(
|
|
156
|
+
${t.bold("Add this entry to")} ${t.magenta(jp)} ${t.bold("under")} ${t.cyan("publicKeys:")}
|
|
159
157
|
|
|
160
158
|
`,c+=` ${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
|
|
161
|
-
`,c+=p("publicKey",t.green(s)),c+=p("email",t.yellow(e.email)),c+=p("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),c+=p("issuedAt",t.green(
|
|
162
|
-
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${
|
|
163
|
-
`);return}let
|
|
164
|
-
`);for(let a of
|
|
165
|
-
`)}o(
|
|
166
|
-
`))}let w;e.expires!==void 0?w=
|
|
167
|
-
`);return}let
|
|
159
|
+
`,c+=p("publicKey",t.green(s)),c+=p("email",t.yellow(e.email)),c+=p("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),c+=p("issuedAt",t.green(n)),c+=p("expiresAt",t.green(i)),c+=p("revokedAt",t.dim("null")),c}o(Bt,"renderRegistryYamlBlock");function io(e){let t=e.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return`${t}T00:00:00Z`;let r=new Date(t);if(Number.isNaN(r.getTime()))throw new Error(`Invalid date '${e}': expected YYYY-MM-DD or ISO-8601 instant`);return r.toISOString()}o(io,"toIsoInstant");import Bp from"clipboardy";function so(e){return Bp.write(e)}o(so,"copyToClipboard");function Wp(e){return{writeFileSync:e.writeFileSync??qp,mkdirSync:e.mkdirSync??Yp,existsSync:e.existsSync??Gp,generateSigningKeyPair:e.generateSigningKeyPair??Jp,encryptStringAsJwe:e.encryptStringAsJwe??_n,storeKeyInKeychain:e.storeKeyInKeychain??Rr,isOS:e.isOS??(t=>_(t)),promptKid:e.promptKid??Cr,promptExpiryMonths:e.promptExpiryMonths??kr,promptEmail:e.promptEmail??br,promptPassphrase:e.promptPassphrase??Pr,promptConfirmOverwrite:e.promptConfirmOverwrite??xr,discoverLocalKeys:e.discoverLocalKeys??(()=>Te()),promptZendeskAction:e.promptZendeskAction??Er,openUrl:e.openUrl??(t=>zp(t)),copyToClipboard:e.copyToClipboard??so}}o(Wp,"resolveDeps");function po(e,t={}){let r=Wp(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 ${D().keysDir} instead`).option("-e, --expires <months>",`Validity in months (${1}-${12}); skips the interactive prompt`).option("--email <address>","Email address for the registry entry; skips the interactive prompt").option("--kid <identifier>","Signing identity name for the registry (e.g. jsmith-dev-001); skips the interactive prompt").option("--force","Overwrite an existing key without prompting for confirmation").option("--copy-link","Copy the Zendesk registration link to the clipboard without prompting").option("--interactive","Prompt for any required flags that are not supplied",!1).action(i=>ec(i,r)),n.command("list").description("List local signing identities and their storage location").action(()=>Xp(r))}o(po,"registerKeysCommand");async function Xp(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
|
|
160
|
+
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${D().keysDir}).
|
|
161
|
+
`);return}let r=["KID","SOURCE","EMAIL"],n=t.map(a=>[a.kid,$e(a.source),a.email??"\u2014"]),i=r.map((a,p)=>Math.max(a.length,...n.map(c=>c[p].length))),s=o(a=>a.map((p,c)=>p.padEnd(i[c])).join(" ").trimEnd(),"fmt");process.stdout.write(`${s(r)}
|
|
162
|
+
`);for(let a of n)process.stdout.write(`${s(a)}
|
|
163
|
+
`)}o(Xp,"handleList");function ao(e,t,r){let n=Ee(D().keysDir,`${e}${X}`);return r.mkdirSync(Gt(n),{recursive:!0}),r.writeFileSync(n,t),n}o(ao,"writePublicKey");async function Zp(e,t,r,n,i,{force:s=!1}={}){let a=n??Ee(D().keysDir,`${e}${at}`);if(i.mkdirSync(Gt(a),{recursive:!0}),!s&&i.existsSync(a))throw new Error(`Refusing to overwrite existing key at ${a}. Delete it first if you really want to regenerate: rm ${a}`);let p=await i.encryptStringAsJwe(t,r);return i.writeFileSync(a,p,{mode:384}),a}o(Zp,"writeEncryptedPrivateKey");function Qp(e,t,r){let n=[];if(e.expires===void 0)n.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{pe(e.expires)}catch(i){n.push(i instanceof Error?i.message:String(i))}if(e.kid===void 0)n.push("--kid <identifier> is required. Pass --interactive to enter it interactively.");else try{let i=ne(e.kid),s=Ee(D().keysDir,`${i}${X}`);r(s)&&!e.force&&n.push(`Key "${i}" already exists. Use --force to overwrite without prompting.`)}catch(i){n.push(i instanceof Error?i.message:String(i))}if(e.email===void 0)n.push("--email <address> is required. Pass --interactive to enter it interactively.");else try{ae(e.email,"--email")}catch(i){n.push(i instanceof Error?i.message:String(i))}return t||n.push("A passphrase is required for encrypted key storage. Pass --interactive to enter it interactively."),n}o(Qp,"collectNonInteractiveErrors");async function ec(e,t,r=new Date){let{isOS:n,existsSync:i,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:p,storeKeyInKeychain:c,promptExpiryMonths:l,promptKid:d,promptEmail:m,promptPassphrase:y,promptConfirmOverwrite:S}=t,u=e.interactive??!1,f=e.keychain!==!1&&n("macos")&&!e.output;if(!u){let j=Qp(e,f,i);if(j.length>0)throw new Error(j.join(`
|
|
164
|
+
`))}let w;e.expires!==void 0?w=pe(e.expires):w=await l();let E=Vt(Qn(r,w)),h;e.kid!==void 0?h=ne(e.kid):h=await d();let M=Ee(D().keysDir,`${h}${X}`),H=i(M);if(H&&!e.force&&!await S(h)){process.stderr.write(`Aborted.
|
|
165
|
+
`);return}let P;e.email!==void 0?P=ae(e.email,"--email"):P=await m();let U=f?{kind:"keychain"}:{kind:"file",passphrase:await y()};process.stderr.write(`
|
|
168
166
|
Generating Ed25519 keypair...
|
|
169
167
|
|
|
170
|
-
`);let{privateKeyPem:
|
|
168
|
+
`);let{privateKeyPem:k,publicKeyPem:G}=await p(h),se=v.from(k);if(U.kind==="keychain"){await c(h,se);let j=ao(h,G,t);process.stderr.write(`Public key: ${j}
|
|
171
169
|
`),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${h})
|
|
172
|
-
`)}else{let
|
|
173
|
-
`),process.stderr.write(`Private key: ${
|
|
174
|
-
`),
|
|
175
|
-
`)}let
|
|
176
|
-
Signing identity (kid): ${
|
|
177
|
-
`),process.stderr.write(`Expires: ${
|
|
178
|
-
`);let
|
|
170
|
+
`)}else{let j=await Zp(h,se,U.passphrase,e.output,t,{force:H}),Io=ao(h,G,t);process.stderr.write(`Public key: ${Io}
|
|
171
|
+
`),process.stderr.write(`Private key: ${j} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Nt.toLocaleString()})
|
|
172
|
+
`),n("macos")||process.stderr.write(` (macOS Keychain integration is the default on darwin; on this OS we use the file.)
|
|
173
|
+
`)}let A=Ee(D().keysDir,`${h}${pt}`);s(Gt(A),{recursive:!0}),a(A,JSON.stringify({email:P}));let Y=to(process.stderr);process.stderr.write(`
|
|
174
|
+
Signing identity (kid): ${Y.green(h)}
|
|
175
|
+
`),process.stderr.write(`Expires: ${E} (${w} month${w===1?"":"s"} from today)
|
|
176
|
+
`);let ke={kid:h,publicKeyPem:G,email:P,expires:E};u||(process.stderr.write(`
|
|
179
177
|
Key registration data:
|
|
180
178
|
|
|
181
|
-
`),process.stderr.write(
|
|
182
|
-
${
|
|
179
|
+
`),process.stderr.write(Bt(ke,Y,r)));let Q=Wn(h,P,E,Bt(ke,Ce,r));process.stderr.write(`
|
|
180
|
+
${Y.bold("Next:")}
|
|
183
181
|
`),process.stderr.write(` 1. Register your signing key \u2014 submit this pre-filled Zendesk request:
|
|
184
|
-
`);let
|
|
185
|
-
`)}catch{process.stderr.write(` URL: ${
|
|
186
|
-
`)}else if(
|
|
187
|
-
`:` URL: ${
|
|
188
|
-
`)}else process.stderr.write(` URL: ${
|
|
182
|
+
`);let ee;if(e.copyLink?ee="clipboard":u?ee=await t.promptZendeskAction():ee=null,ee==="browser")try{await t.openUrl(Q),process.stderr.write(` Opening in browser...
|
|
183
|
+
`)}catch{process.stderr.write(` URL: ${Q}
|
|
184
|
+
`)}else if(ee==="clipboard"){let j=!1;try{await t.copyToClipboard(Q),j=!0}catch{}process.stderr.write(j&&!e.copyLink?` Link copied to clipboard.
|
|
185
|
+
`:` URL: ${Q}
|
|
186
|
+
`)}else process.stderr.write(` URL: ${Q}
|
|
189
187
|
`);process.stderr.write(`
|
|
190
188
|
2. Once your key is approved, sign your Dune app:
|
|
191
|
-
`),process.stderr.write(` ${
|
|
192
|
-
`)}o(
|
|
193
|
-
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{
|
|
194
|
-
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(
|
|
195
|
-
`);return
|
|
196
|
-
${
|
|
197
|
-
`)},"onOutdated")})});
|
|
198
|
-
Cancelled.`),process.exit(130)),(!(e instanceof
|
|
189
|
+
`),process.stderr.write(` ${Y.cyan(`cognite sign -s ${h}`)}
|
|
190
|
+
`)}o(ec,"handleGenerate");import{performance as co}from"perf_hooks";var lo=1e3,ze;function tc(){ze=co.now()}o(tc,"markActionStart");function rc(){ze=void 0}o(rc,"resetActionStart");function nc(){if(ze!==void 0)return Math.max(0,Math.round(co.now()-ze))}o(nc,"snapshotActionDurationMs");function mo(){let e=nc();return rc(),{...e!==void 0&&{actionDurationMs:e}}}o(mo,"takePerformanceFields");var oc=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function ic(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>typeof r=="boolean"?[t,r]:oc.has(t)?[t,r]:[t,"[REDACTED]"]))}o(ic,"sanitize");function sc(e){let t=[],r=e;for(;r;)r.parent&&t.unshift(r.name()),r=r.parent;return t.join(" ")}o(sc,"getCommandPath");function uo(e){try{let t=e(process.cwd()),r=t.deployments[0];return{appName:t.name,appExternalId:t.externalId,appVersionTag:t.versionTag,...r&&{cogniteOrg:r.org,cogniteProject:r.project}}}catch{return{}}}o(uo,"tryLoadAppConfig");function Yt(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(Yt,"commandFromArgv");function go(e,t,r=C){e.hook("preAction",()=>{tc()}),e.hook("postAction",async(n,i)=>{try{let s={command:sc(i),options:ic(i.opts()),success:!0,...uo(r),...mo()};t.track("Flows.CLI.Command",{...s}),await t.flush(lo)}catch{}})}o(go,"instrument");async function fo(e,t,r=C){try{let n={command:Yt(t),options:{},success:!1,...uo(r),...mo()};e.track("Flows.CLI.Command",{...n}),await e.flush(lo)}catch{}}o(fo,"trackFailure");var ac="ERR_USE_AFTER_CLOSE";function ho(e){return e instanceof Error&&"code"in e&&e.code===ac}o(ho,"isReadlineClosedError");function pc(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(pc,"isPlainObject");function qt(e){return e==null||ho(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&pc(e)&&Object.keys(e).length===0)}o(qt,"isPromptCancel");var yo=!1;function So(){yo||(yo=!0,process.on("uncaughtException",e=>{ho(e)&&(console.error(`
|
|
191
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{qt(e)&&(console.error(`
|
|
192
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(So,"installCancelHandler");import{homedir as cc,userInfo as lc}from"os";var dc=cc(),mc=(()=>{try{return lc().username}catch{return""}})();function me(e,t=dc){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(me,"redactHomedir");function uc(e,t=mc){if(!t||t.length<3)return e;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp("(^|[\\/\\s:])"+r+"(?=[\\/\\s:.@]|$)","g");return e.replace(n,"$1<user>")}o(uc,"redactUsername");var gc=/(['"]?(?:access_token|accessToken|client_secret|clientSecret|refresh_token|refreshToken|password|token|passphrase)['"]?\s*:\s*)(?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*')/gi;function wo(e){return e.replace(gc,(t,r)=>{let n=t[r.length];return`${r}${n}[REDACTED]${n}`})}o(wo,"redactCredentials");var fc=1e3,yc="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",hc={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function Sc(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(Sc,"buildRelease");var wc="192.0.2.0";function vc(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:me(t.filename)},...t.abs_path!==void 0&&{abs_path:me(t.abs_path)},...t.module!==void 0&&{module:me(t.module)}}))}o(vc,"scrubStackFrames");function Jt(e){return wo(uc(me(e)))}o(Jt,"redactPii");function Cc(e){let t={...e.user,email:void 0,username:void 0,ip_address:wc,id:void 0},r=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?Jt(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:vc(s.stacktrace.frames)}}})),n=e.contexts?.cli,i=n!==void 0?Object.fromEntries(Object.entries(n).map(([s,a])=>[s,typeof a=="string"?Jt(a):a])):void 0;return{...e,message:e.message!==void 0?Jt(e.message):e.message,user:t,server_name:void 0,...r!==void 0&&{exception:{...e.exception,values:r}},...i!==void 0&&{contexts:{...e.contexts,cli:i}}}}o(Cc,"scrubPii");function vo(e={}){let t=e.env??process.env;if(Ct(t))return hc;let r=Sc(e),n="production",i=null,s=null;function a(){return{dsn:yc,release:r,environment:n,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:he},contexts:{cli:{applicationId:he,node:process.version,platform:process.platform}}},beforeSend:Cc}}o(a,"buildInitOptions");async function p(){return i||(s||(s=(async()=>{try{let c=e.sdk??await import("@sentry/node");return c.init(a()),i=c,c}catch{return null}})()),s)}return o(p,"ensureSdk"),{async captureError(c,l){try{let d=await p();if(!d)return;d.captureException(c,Ec(c,l))}catch{}},async flush(c=fc){try{if(!i)return;await i.flush(c)}catch{}}}}o(vo,"createErrorReporter");function Ec(e,t){let r={level:"fatal"},n={applicationId:he,node:process.version,platform:process.platform};if(t?.command&&(r.tags={command:t.command},n.command=t.command),or(e)&&(e.hint&&(n.hint=e.hint),e.helpUrl&&(n.helpUrl=e.helpUrl),n.shouldReport=e.shouldReport),r.contexts={cli:n},ir(e)&&(r.contexts.http={url:e.requestUrl!==void 0?me(e.requestUrl):void 0,status_code:e.httpStatusCode},e.responseBody!==void 0)){let i=typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody);r.extra={responseBody:wo(me(i))}}return r}o(Ec,"buildCaptureContext");import{mkdirSync as kc,readFileSync as bc,writeFileSync as Pc}from"fs";import{homedir as xc}from"os";import{resolve as We}from"path";import{debuglog as Ac}from"util";import{lt as Dc,parse as Co}from"semver";var Ic="https://registry.npmjs.org/@cognite/cli/latest",$c=1500,Eo="upgrade-check.json",ko=We(process.env.XDG_CACHE_HOME||We(xc(),".cache"),"@cognite","cli"),zt=Ac("cognite-flows");function Tc(e,t){return!e||!t||!Co(e)||!Co(t)?!1:Dc(e,t)}o(Tc,"isOutdated");async function Rc({timeout:e=$c,registryUrl:t=Ic,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 zt("fetchLatestVersion failed (%s): %O",t,n),null}}o(Rc,"fetchLatestVersion");function Fc(e=ko,t=864e5){try{let r=bc(We(e,Eo),"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 zt("readUpgradeCheckCache failed (%s): %O",e,r),null}}o(Fc,"readUpgradeCheckCache");function Oc(e,t){try{kc(e,{recursive:!0});let r={latest:t,fetchedAt:Date.now()};Pc(We(e,Eo),JSON.stringify(r))}catch(r){zt("writeUpgradeCheckCache failed (%s): %O",e,r)}}o(Oc,"writeUpgradeCheckCache");async function Uc({cacheDir:e=ko,...t}={}){let r=await Rc(t);r&&Oc(e,r)}o(Uc,"startBackgroundUpgradeCheck");function bo(e,{onOutdated:t,cacheDir:r,...n}={}){let i=Fc(r);if(i){Tc(e,i.latest)&&t?.(e,i.latest);return}Uc({cacheDir:r,...n})}o(bo,"preActionUpgradeCheck");import{default as Dh,chalkStderr as Po}from"chalk";function xo(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),s=o(p=>`\u2502 ${p}${" ".repeat(n-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...r.map(s),`\u2514${i}\u2518`].join(`
|
|
193
|
+
`);return Po.bold.yellow(a)}o(xo,"formatUpgradeWarning");function Nc(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(Nc,"isDep0040Warning");var Xt=process,Kc=Xt.emit.bind(Xt);Xt.emit=function(e,...t){return e==="warning"&&Nc(t[0])?!1:Kc(e,...t)};So();var ue=new Lc;ue.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.7.0").showHelpAfterError().configureOutput({writeOut:o(e=>_c(1,e),"writeOut")});ue.hook("preAction",()=>{bo("1.7.0",{onOutdated:o((e,t)=>{console.warn(`
|
|
194
|
+
${xo(e,t)}
|
|
195
|
+
`)},"onOutdated")})});Zn(ue);po(ue);var Do=Le({packageName:"@cognite/cli",cliVersion:"1.7.0"}),Ao=vo({packageName:"@cognite/cli",cliVersion:"1.7.0"});go(ue,Do);var Wt=process.argv.slice(2);ue.parseAsync(Wt,{from:"user"}).catch(async e=>{await fo(Do,Wt),qt(e)&&(console.error(`
|
|
196
|
+
Cancelled.`),process.exit(130)),(!(e instanceof g)||e.shouldReport)&&(await Ao.captureError(e,{command:Yt(Wt)}),await Ao.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof g&&(e.hint||e.helpUrl)&&(console.error(""),e.hint&&console.error(`\u{1F4A1} ${e.hint}`),e.helpUrl&&console.error(`\u{1F4DA} ${e.helpUrl}`)),process.exit(1)});
|