@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/deploy/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CogniteClient, ClientOptions } from '@cognite/sdk';
|
|
2
|
+
import { inspect } from 'node:util';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* App Hosting HTTP API layer.
|
|
@@ -168,6 +169,26 @@ type Authenticatable = Pick<CogniteClient, 'authenticate'>;
|
|
|
168
169
|
declare function getSdk(deployment: Deployment, folder: string, env?: NodeJS.ProcessEnv): Promise<CogniteClient>;
|
|
169
170
|
declare function getSdk<C extends Authenticatable>(deployment: Deployment, folder: string, env: NodeJS.ProcessEnv, createClient: (opts: ClientOptions) => C): Promise<C>;
|
|
170
171
|
|
|
172
|
+
/**
|
|
173
|
+
* Wraps a secret string so it cannot accidentally leak through string
|
|
174
|
+
* coercion, `JSON.stringify`, or `util.inspect` / `console.log`. The raw
|
|
175
|
+
* value is only accessible via {@link expose}, which should be called at
|
|
176
|
+
* trusted boundaries (crypto operations, HTTP headers, SDK init) and nowhere
|
|
177
|
+
* else.
|
|
178
|
+
*/
|
|
179
|
+
declare class SensitiveString {
|
|
180
|
+
#private;
|
|
181
|
+
constructor(value: string);
|
|
182
|
+
toString(): string;
|
|
183
|
+
toJSON(): string;
|
|
184
|
+
/** Covers `util.inspect` and `console.log`. */
|
|
185
|
+
[inspect.custom](): string;
|
|
186
|
+
/** Returns the raw value. Only call this at a trusted boundary. */
|
|
187
|
+
expose(): string;
|
|
188
|
+
/** Creates a {@link SensitiveString} wrapping `value`. */
|
|
189
|
+
static from(value: string): SensitiveString;
|
|
190
|
+
}
|
|
191
|
+
|
|
171
192
|
/**
|
|
172
193
|
* Get access token for deployment using the appropriate identity provider.
|
|
173
194
|
* Supports both CDF OAuth and Entra ID (Azure AD) authentication.
|
|
@@ -175,7 +196,7 @@ declare function getSdk<C extends Authenticatable>(deployment: Deployment, folde
|
|
|
175
196
|
* Set COGNITE_TOKEN to skip OAuth entirely (useful when running the CLI
|
|
176
197
|
* against a local mock server — see cli/testing/msw/standalone.ts).
|
|
177
198
|
*/
|
|
178
|
-
declare const getToken: (deployment: Deployment, env?: NodeJS.ProcessEnv) => Promise<
|
|
199
|
+
declare const getToken: (deployment: Deployment, env?: NodeJS.ProcessEnv) => Promise<SensitiveString>;
|
|
179
200
|
|
|
180
201
|
/**
|
|
181
202
|
* Sibling-file discovery for bundle signatures written by `cognite sign`.
|
package/dist/deploy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-74X2P7OO.js";export{a as AppHostingClient,b as ApplicationPackager,c as BUNDLE_DIR,j as SIGNATURE_SUFFIXES,d as bundleFileName,e as bundlePath,i as deploy,k as discoverSignatures,g as getSdk,f as getToken,h as packageAndUpload};
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-
|
|
1
|
+
import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-74X2P7OO.js";export{o as AppHostingClient,r as ApplicationPackager,e as BUNDLE_DIR,b as SIGNATURE_SUFFIXES,f as bundleFileName,m as bundlePath,a as deploy,c as discoverSignatures,t as getSdk,p as getToken,x as packageAndUpload};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cognite/cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"description": "CLI for Cognite Data Fusion",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"author": "Cognite",
|
|
@@ -40,14 +40,16 @@
|
|
|
40
40
|
"prepack": "pnpm run build",
|
|
41
41
|
"prepublishOnly": "pnpm run build",
|
|
42
42
|
"test": "vitest run",
|
|
43
|
+
"test:coverage": "vitest run --coverage",
|
|
43
44
|
"test:watch": "vitest",
|
|
44
45
|
"mock:server": "tsx cli/testing/msw/standalone.ts",
|
|
45
46
|
"mock:deploy": "cd ../../apps/mock-app && pnpm build && COGNITE_TOKEN=test-token COGNITE_BASE_URL=http://localhost:9090 node ../../packages/cli/dist/cli/cli.js deploy --skip-build",
|
|
46
47
|
"refresh-spec-kit": "bash scripts/refresh-spec-kit.sh"
|
|
47
48
|
},
|
|
48
49
|
"dependencies": {
|
|
49
|
-
"@cognite/app-sdk": "^0.
|
|
50
|
+
"@cognite/app-sdk": "^0.8.0",
|
|
50
51
|
"@cognite/sdk": "^10.10.0",
|
|
52
|
+
"@napi-rs/keyring": "^1.3.0",
|
|
51
53
|
"@sentry/node": "^10.51.0",
|
|
52
54
|
"@zip.js/zip.js": "^2.7.0",
|
|
53
55
|
"chalk": "^5.6.2",
|
|
@@ -58,7 +60,7 @@
|
|
|
58
60
|
"execa": "^5.1.1",
|
|
59
61
|
"hygen": "^6.2.11",
|
|
60
62
|
"jose": "^6.2.2",
|
|
61
|
-
"mixpanel": "^0.
|
|
63
|
+
"mixpanel": "^0.22.0",
|
|
62
64
|
"open": "^10.1.0",
|
|
63
65
|
"openid-client": "^6.8.3",
|
|
64
66
|
"semver": "^7.7.0",
|
|
@@ -92,7 +94,8 @@
|
|
|
92
94
|
"react-dom": "^19.2.6",
|
|
93
95
|
"tsup": "^8.4.0",
|
|
94
96
|
"typescript": "^5.0.0",
|
|
95
|
-
"vitest": "4.1.
|
|
97
|
+
"@vitest/coverage-v8": "4.1.8",
|
|
98
|
+
"vitest": "4.1.8"
|
|
96
99
|
},
|
|
97
100
|
"engines": {
|
|
98
101
|
"node": ">=20"
|
package/dist/chunk-EYFDM46K.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
var de=Object.defineProperty;var s=(n,e)=>de(n,"name",{value:e,configurable:!0});import{mkdir as qe,readFile as Ge}from"fs/promises";import{basename as Je,dirname as Ye}from"path";var N=class N extends Error{constructor(e,t={}){super(e),this.name="HintedError",t.cause!==void 0&&(this.cause=t.cause);let r=this.deriveDefaults(t);this.hint=t.hint??r.hint,this.helpUrl=t.helpUrl??r.helpUrl,this.shouldReport=t.shouldReport??!0}deriveDefaults(e){return{hint:fe(e.cause)}}};s(N,"HintedError");var u=N;var K="https://docs.cognite.com/cdf/access/",ue="https://status.cognite.com";function le(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:K};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:K};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:ue};default:return{}}}s(le,"defaultHintForStatus");var V=class V extends u{constructor(e,t){super(e,t),this.name="HintedHttpError",this.httpStatusCode=t.httpStatusCode,this.requestUrl=t.requestUrl,this.responseBody=t.responseBody}deriveDefaults(e){let{httpStatusCode:t}=e,r=le(t),i=super.deriveDefaults(e);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};s(V,"HintedHttpError");var S=V;function ge(n,e){if(n)switch(n){case"ENOTFOUND":return e.hostname?`DNS lookup failed for ${e.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return e.hostname&&e.port?`Connection refused by ${e.hostname}:${e.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return e.path?`Permission denied: ${e.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return e.path?`File or directory not found: ${e.path}.`:"File or directory not found.";case"EISDIR":return e.path?`Expected a file but found a directory: ${e.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return e.port?`Port ${e.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}s(ge,"hintForErrno");function fe(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,i=ge(r.code,r);if(i!==void 0)return i;e=r.cause}}s(fe,"hintForCause");var W="https://docs.cognite.com/cdf/access/";function g(n){return n!==null&&typeof n=="object"}s(g,"isRecord");function C(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}s(C,"isHttpError");function he(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
2
|
-
See: ${W}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
3
|
-
See: ${W}`;default:return}}s(he,"httpStatusHint");function m(n){let e=n instanceof Error?n:new Error(String(n));if(!C(e))return null;let t=he(e.status);return t?Object.assign(new Error(`${e.message}
|
|
4
|
-
${t}`),{cause:e}):null}s(m,"enrichedHttpError");function me(n){if(!g(n))return null;let e=n.missing;if(Array.isArray(e))return e;let t=n.data;if(g(t)){let r=t.error;if(g(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(t.missing))return t.missing}return null}s(me,"findMissingArray");function ye(n,e){if(!C(n)||n.status!==400)return!1;let t=me(n);return t?t.some(r=>g(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}s(ye,"isMissingExternalIdError");function b(n,e){return C(n)&&n.status===404||ye(n,e)}s(b,"isNotFoundError");var Z=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Q=["ACTIVE","PREVIEW"],O=class O extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};s(O,"AppVersionNotFoundError");var T=O,_=class _ extends Error{constructor(e){super(`App ${e} not found`),this.name="AppNotFoundError",this.appExternalId=e}};s(_,"AppNotFoundError");var R=_;function D(n,e){return n.includes(e)}s(D,"includesValue");function Ee(n){return D(Z,n)}s(Ee,"isAppVersionLifecycleState");function Ae(n){return D(Q,n)}s(Ae,"isAppVersionAlias");function we(n){return typeof n.version=="string"&&Ee(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||Ae(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}s(we,"isAppVersion");function X(n){if(!g(n)){let e=JSON.stringify(n)?.slice(0,200)??String(n);throw new Error(`Invalid version response: expected object, got ${e}`)}if(!we(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}s(X,"parseAppVersion");function Se(n){if(!g(n))throw new Error("Invalid app response: not an object");let{externalId:e,name:t,description:r}=n;if(typeof e!="string")throw new Error("Invalid app response: missing externalId");if(typeof t!="string")throw new Error("Invalid app response: missing name");if(r!=null&&typeof r!="string")throw new Error("Invalid app response: malformed description");return{externalId:e,name:t,description:typeof r=="string"?r:void 0}}s(Se,"parseAppMetadata");var F=class F{constructor(e){this.client=e}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(e,t,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:e,name:t,description:r}]}})}catch(i){throw m(i)??i}}async updateApps(e){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:e}})}catch(t){throw m(t)??t}}async getApp(e){let t=`${this.appsBasePath}/${encodeURIComponent(e)}`;try{let r=await this.client.get(t);return Se(r.data)}catch(r){throw b(r,[e])?new R(e):m(r)??r}}async uploadVersion(e,t,r,i,o="index.html"){console.log(`\u{1F4E4} Uploading version ${t}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),i),a.append("version",t),a.append("entryPath",o);let c=encodeURIComponent(e),p=`${this.appsBasePath}/${c}/versions`,d=await this.client.authenticate(),f=`${this.client.getBaseUrl()}${p}`,E=new AbortController,pe=setTimeout(()=>E.abort(),300*1e3),A;try{A=await fetch(f,{method:"POST",headers:{Authorization:`Bearer ${d}`},body:a,signal:E.signal})}catch(h){throw h instanceof Error&&h.name==="AbortError"?new u("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new u(`Failed to upload version to ${f}`,{cause:h,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(pe)}if(!A.ok){let h=await A.text(),w;try{w=JSON.parse(h)}catch{}let x=h;if(g(w)){let k=w.error;if(typeof k=="string")x=k;else if(g(k)){let v=k.message,z=k.code;x=typeof v=="string"?v:z!=null?`Unknown error (code: ${z})`:h}else{let v=w.message;x=typeof v=="string"?v:h}}let Y=A.headers.get("x-request-id"),ce=Y?` | X-Request-ID: ${Y}`:"";throw new S(`Upload failed: ${A.status} \u2014 ${x}${ce}`,{httpStatusCode:A.status,requestUrl:f,responseBody:g(w)?w:h})}console.log(`\u2705 Version ${t} uploaded`)}async getVersion(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/${i}`;try{let a=await this.client.get(o);return X(a.data)}catch(a){throw b(a,[e,t])?new T(e,t):m(a)??a}}async getActiveVersion(e){let t=encodeURIComponent(e),r=`${this.appsBasePath}/${t}/versions/list`;try{let i=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!g(i.data)||!Array.isArray(i.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:o}=i.data;if(o.length===0)return null;if(o.length>1)throw new Error(`Unexpected response: ${o.length} versions have the ACTIVE alias, expected at most 1`);return X(o[0])}catch(i){if(b(i,[e]))return null;throw m(i)??i}}async updateVersions(e,t){let r=encodeURIComponent(e),i=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(i,{data:{items:t}})}catch(o){throw m(o)??o}}async submitSignatures(e,t,r){let i=encodeURIComponent(e),o=encodeURIComponent(t),a=`${this.appsBasePath}/${i}/versions/${o}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(c){throw m(c)??c}}async listSignatures(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/${i}/signatures/list`;try{let a=await this.client.post(o,{data:{}});return Ce(a.data)}catch(a){throw m(a)??a}}};s(F,"AppHostingApi");var $=F,ke=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],ve=["developer","certifier"];function Ce(n){if(!g(n))throw new Error("Invalid signatures response: expected an object with an items array");let{items:e}=n;if(!Array.isArray(e))throw new Error("Invalid signatures response: items property is missing or not an array");return e.flatMap(t=>{let r=Ie(t);return r?[r]:[]})}s(Ce,"parseStoredSignatures");function Ie(n){if(!g(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:o,status:a}=n;return typeof e!="string"||e===""||!D(ve,t)||typeof r!="number"||typeof i!="number"||typeof o!="number"||!D(ke,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:o,status:a}}s(Ie,"parseStoredSignature");function Pe(n,e){let t=[];n.name!==e.name&&t.push({field:"name",remote:n.name,local:e.name});let r=n.description??"";return r!==e.description&&t.push({field:"description",remote:r,local:e.description}),t}s(Pe,"diffAppMetadata");function xe(n){let e=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:t,remote:r,local:i}of n){let o=`${t}:`.padEnd(14);e.push(` ${o}"${r}" \u2192 "${i}"`)}return e.join(`
|
|
5
|
-
`)}s(xe,"formatMetadataDriftError");var L=class L{constructor(e){this.api=new $(e)}getVersion(e,t){return this.api.getVersion(e,t)}uploadVersion(e,t,r,i,o){return this.api.uploadVersion(e,t,r,i,o)}async ensureApp(e,t,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(e,t,r),console.log(`\u2705 App '${e}' created`)}catch(i){if(C(i)&&i.status===409){console.log(`\u2705 App '${e}' already exists`),await this.checkMetadataDrift(e,t,r);return}throw i}}async checkMetadataDrift(e,t,r){let i;try{i=await this.getApp(e)}catch{return}let o=Pe(i,{name:t,description:r});if(o.length!==0)throw new u(xe(o),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(e){return this.api.getApp(e)}async updateAppMetadata(e,t,r){await this.api.updateApps([{externalId:e,update:{name:{set:t},description:r?{set:r}:{setNull:!0}}}])}async submitSignatures(e,t,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${t}...`),await this.api.submitSignatures(e,t,r),console.log("\u2705 Signatures stored"))}listSignatures(e,t){return this.api.listSignatures(e,t)}async publishVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(e,t){console.log(`\u{1F680} Publishing and activating version ${t}...`),await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${t} is now PUBLISHED and ACTIVE`)}getActiveVersion(e){return this.api.getActiveVersion(e)}async deactivateVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{alias:{setNull:!0}}}])}async activateVersion(e,t){let r=null;try{r=await this.api.getActiveVersion(e)}catch{r=null}let i=r&&r.version!==t?r.version:void 0;return await this.api.updateVersions(e,[{version:t,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(e,t,r,i,o,a,c=!1){console.log(`
|
|
6
|
-
\u{1F680} Deploying application via App Hosting API...
|
|
7
|
-
`),await this.ensureApp(e,t,r),await this.uploadVersion(e,i,o,a),c&&await this.publishAndActivate(e,i),console.log(`
|
|
8
|
-
\u2705 Deployment successful!`)}};s(L,"AppHostingClient");var I=L;import{execFileSync as U}from"child_process";import y from"fs";import l from"path";import{parseAndValidateManifestConfig as be}from"@cognite/app-sdk/vite";import{BlobReader as Te,Uint8ArrayWriter as Re,ZipWriter as De}from"@zip.js/zip.js";var H="package.json",B="package-lock.json",ee="manifest.json",M=".cognite",$e=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],j=class j{constructor(e="dist"){this.distPath=l.isAbsolute(e)?e:l.join(process.cwd(),e),this.appRoot=l.dirname(this.distPath)}validateBuildDirectory(){if(!y.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=l.join(this.appRoot,H);if(!y.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=l.join(this.appRoot,B);if(!y.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`)}async createZip(e="app.zip",t=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new De(new Re,{level:9}),i=s(async(p,d)=>{await r.add(d,new Te(await y.openAsBlob(p))),t&&console.log(` \u{1F4C4} ${d}`)},"addFile"),o=s(async p=>{let d=await y.promises.readdir(p,{withFileTypes:!0});for(let f of d){let E=l.join(p,f.name);f.isDirectory()?await o(E):await i(E,l.relative(this.distPath,E).replace(/\\/g,"/"))}},"addDir"),a;try{await o(this.distPath);let p=l.join(this.appRoot,H);await i(p,l.posix.join(M,H));let d=l.join(this.appRoot,ee);if(y.existsSync(d)){let E=y.readFileSync(d,"utf-8");be(E,d),await i(d,l.posix.join(M,ee))}let f=l.join(this.appRoot,B);await i(f,l.posix.join(M,B)),a=await r.close()}catch(p){let d=p instanceof Error?p.message:String(p);throw new Error(`Failed to create zip: ${d}`)}try{await y.promises.writeFile(e,a)}catch(p){throw new u(`Failed to write bundle to ${e}`,{cause:p})}let c=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${c} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=U("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(p){throw p instanceof Error&&"code"in p&&p.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=U("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=r?r.replace(/\/$/,""):".",o=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(t,o);try{U("git",["-C",t,"archive","--format=zip",`--output=${e}`,o])}catch(p){let d=p instanceof Error?p.message:String(p);throw new Error(`Failed to create source archive: ${d}`)}let c=(y.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${l.basename(e)} (${c} MB)`),e}validateNoSensitiveFiles(e,t){let r=U("git",["-C",e,"ls-tree","-r","--name-only",t],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
9
|
-
`).filter(Boolean),i=s(a=>a.split("/").some(c=>$e.some(p=>p.test(c))),"isSensitive"),o=r.filter(i);if(o.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
|
|
10
|
-
`+o.map(a=>` ${a}`).join(`
|
|
11
|
-
`)+`
|
|
12
|
-
Hint: git rm --cached <file>`)}};s(j,"ApplicationPackager");var P=j;import Ue from"path";var te=".cognite-bundles";function ne(n,e){return`${n}-${e}.zip`}s(ne,"bundleFileName");function q(n,e,t){return Ue.join(n,te,ne(e,t))}s(q,"bundlePath");import{CogniteClient as je}from"@cognite/sdk";function Ne(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}s(Ne,"exponentialBackoffWithJitter");function Ve(n){return new Promise(e=>setTimeout(e,n))}s(Ve,"sleep");async function re(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),i=e.delayInMsCalculator??Ne;if(t<1)throw new Error("`maxAttempts` must be 1 or greater");if(t>100)throw new Error("`maxAttempts` must be 100 or less");let o=1;for(;;)try{return await n()}catch(a){if(o>=t||!r(a))throw a;let c=i(o);e.onAttemptFail?.(a,o,c),await Ve(c),o++}}s(re,"retryAsync");var Oe="https://auth.cognite.com/oauth2/token",_e=s(n=>typeof n=="object"&&n!==null&&"access_token"in n&&typeof n.access_token=="string","hasAccessToken");async function ie({idp:n,tokenUrl:e,init:t,missingTokenHint:r}){let i;try{i=await re(()=>fetch(e,t),{maxAttempts:3})}catch(c){throw new u(`Failed to fetch access token from ${e}`,{cause:c})}if(!i.ok){let c=await i.text();throw new S(`Failed to get token from ${n}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:e,responseBody:c})}let o=await i.text(),a;try{a=JSON.parse(o)}catch{throw new u(`Unexpected response from ${n} authentication (invalid JSON):
|
|
13
|
-
${o}`,{hint:r})}if(!_e(a))throw new u(`No access token in ${n} authentication response:
|
|
14
|
-
${o}`,{hint:r});return a.access_token}s(ie,"fetchOAuthToken");var Fe=s(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let e=JSON.parse(n),t={};for(let[r,i]of Object.entries(e))if(typeof i=="string"){let o=r.toLowerCase().replace(/_/g,"-");t[o]=i}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),Le=s(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=Fe()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return e},"getSecretFromEnv"),He=s((n,e)=>ie({idp:"CDF",tokenUrl:Oe,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${n}:${e}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."}),"getTokenCdf"),oe=s(({idp:n,tokenUrl:e,clientId:t,clientSecret:r,scopes:i,missingTokenHint:o})=>ie({idp:n,tokenUrl:e,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:t,client_secret:r,grant_type:"client_credentials",...i!==void 0?{scope:i.join(" ")}:{}})},missingTokenHint:o}),"getTokenWithClientCredentials"),Be=s((n,e)=>{if(e!==void 0)return e.join(" ");if(!n)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(n).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${n}`)}},"resolveEntraScope"),Me=s((n,e,t,r,i)=>oe({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,clientId:n,clientSecret:e,scopes:i!==void 0?i:[Be(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),G=s(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return e.COGNITE_TOKEN;let{deployClientId:t,deploySecretName:r,idpType:i="cdf",tenantId:o,baseUrl:a,scopes:c,tokenUrl:p}=n,d=Le(r);if(i==="oauth"){if(!p)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return oe({idp:"OAuth",tokenUrl:p,clientId:t,clientSecret:d,scopes:c,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!o)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Me(t,d,o,a,c)}return He(t,d)},"getToken");async function J(n,e,t=process.env,r){let i=await G(n,t),o=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(c=>new je(c)))({appId:e,project:n.project,baseUrl:o,oidcTokenProvider:s(async()=>i,"oidcTokenProvider")});return await a.authenticate(),a}s(J,"getSdk");async function se(n,e,t,r){let{externalId:i,name:o,description:a,versionTag:c}=e,p=q(t,i,c);await qe(Ye(p),{recursive:!0}),await new P(`${t}/dist`).createZip(p,!0);let d;try{d=await Ge(p)}catch(f){throw new u(`Failed to read bundle file: ${p}`,{cause:f})}await new I(n).deploy(i,o,a,c,d,Je(p),r)}s(se,"packageAndUpload");var ze=s(async(n,e,t)=>{let r=await J(n,t);await se(r,e,t,n.published)},"deploy");import{existsSync as Ke,readFileSync as We}from"fs";var ae=[".dev.sig",".cert.sig"];function Xe(n,e={}){let t=e.existsSync??Ke,r=e.readFileSync??((o,a)=>We(o,a)),i=[];for(let o of ae){let a=`${n}${o}`;if(!t(a))continue;let c=r(a,"utf8").trim();c.length>0&&i.push(c)}return i}s(Xe,"discoverSignatures");export{I as a,P as b,te as c,ne as d,q as e,G as f,J as g,se as h,ze as i,ae as j,Xe as k};
|