@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
|
@@ -28,7 +28,7 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
|
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"@cognite/aura": "^0.1.7",
|
|
30
30
|
"@cognite/sdk": "^10.10.0",
|
|
31
|
-
"@cognite/app-sdk": "^0.
|
|
31
|
+
"@cognite/app-sdk": "^0.8.0",
|
|
32
32
|
"@tabler/icons-react": "^3.35.0",
|
|
33
33
|
"@tanstack/react-query": "^5.90.10",
|
|
34
34
|
"clsx": "^2.1.1",
|
|
@@ -42,25 +42,25 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
|
|
|
42
42
|
"@testing-library/jest-dom": "^6.6.3",
|
|
43
43
|
"@testing-library/react": "^16.1.0",
|
|
44
44
|
"@testing-library/user-event": "^14.5.2",
|
|
45
|
-
"@types/node": "^
|
|
45
|
+
"@types/node": "^25.0.0",
|
|
46
46
|
"@types/react": "^18.3.1",
|
|
47
47
|
"@types/react-dom": "^18.3.1",
|
|
48
|
-
"@vitejs/plugin-react": "
|
|
49
|
-
"@vitest/coverage-v8": "4.1.
|
|
50
|
-
"@vitest/ui": "4.1.
|
|
48
|
+
"@vitejs/plugin-react": ">=5.1.1 <6.0.0",
|
|
49
|
+
"@vitest/coverage-v8": "4.1.8",
|
|
50
|
+
"@vitest/ui": "4.1.8",
|
|
51
51
|
"autoprefixer": "^10.4.22",
|
|
52
52
|
"eslint": "9.39.4",
|
|
53
53
|
"eslint-plugin-import": "^2.32.0",
|
|
54
54
|
"eslint-plugin-no-only-tests": "^3.3.0",
|
|
55
55
|
"eslint-plugin-react-hooks": "^7.1.1",
|
|
56
56
|
"eslint-plugin-react-refresh": "^0.5.2",
|
|
57
|
-
"globals": "^
|
|
57
|
+
"globals": "^17.0.0",
|
|
58
58
|
"happy-dom": "^20.9.0",
|
|
59
59
|
"postcss": "^8.5.6",
|
|
60
60
|
"tailwindcss": "^4.1.17",
|
|
61
61
|
"typescript": "^5.0.0",
|
|
62
62
|
"typescript-eslint": "^8.46.4",
|
|
63
|
-
"vite": "7.3.
|
|
64
|
-
"vitest": "4.1.
|
|
63
|
+
"vite": ">=7.3.5 <8.0.0",
|
|
64
|
+
"vitest": "4.1.8"
|
|
65
65
|
}
|
|
66
66
|
}
|
|
@@ -24,6 +24,7 @@ function makeApi(): HostAppAPI {
|
|
|
24
24
|
unregisterAgentServer: vi.fn<HostAppAPI['unregisterAgentServer']>(() => Promise.resolve()),
|
|
25
25
|
sendAgentLayoutMode: vi.fn<HostAppAPI['sendAgentLayoutMode']>(() => Promise.resolve()),
|
|
26
26
|
sendAgentMessage: vi.fn<HostAppAPI['sendAgentMessage']>(() => Promise.resolve()),
|
|
27
|
+
sendAgentTheme: vi.fn<HostAppAPI['sendAgentTheme']>(() => Promise.resolve()),
|
|
27
28
|
};
|
|
28
29
|
}
|
|
29
30
|
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
---
|
|
2
2
|
to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>src/main.tsx'
|
|
3
3
|
---
|
|
4
|
+
import {
|
|
5
|
+
dispatchSessionExpired,
|
|
6
|
+
MESSAGE_TYPES,
|
|
7
|
+
reloadPreservingRoute,
|
|
8
|
+
restoreRouteOnBoot,
|
|
9
|
+
} from '@cognite/app-sdk';
|
|
4
10
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
5
11
|
import React from 'react';
|
|
6
12
|
import ReactDOM from 'react-dom/client';
|
|
@@ -9,6 +15,70 @@ import App from './App.tsx';
|
|
|
9
15
|
|
|
10
16
|
import './styles.css';
|
|
11
17
|
|
|
18
|
+
// Session-recovery helpers (opt-in; safe to remove).
|
|
19
|
+
restoreRouteOnBoot();
|
|
20
|
+
|
|
21
|
+
// Host refreshed the session: reload, keeping the current route.
|
|
22
|
+
window.addEventListener('message', (event) => {
|
|
23
|
+
if (event.source !== window.parent) return; // ignore non-host senders
|
|
24
|
+
if (event.data?.type === MESSAGE_TYPES.FUSION_HOST.SESSION_REFRESHED) {
|
|
25
|
+
reloadPreservingRoute();
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
// A failed dynamic import (chunk load) usually means the session expired; messages vary by browser, so match case-insensitively.
|
|
30
|
+
const isDynamicImportFailure = (message: string): boolean => {
|
|
31
|
+
const lower = message.toLowerCase();
|
|
32
|
+
return (
|
|
33
|
+
lower.includes('failed to fetch dynamically imported module') || // Chromium
|
|
34
|
+
lower.includes('error loading dynamically imported module') || // Firefox
|
|
35
|
+
lower.includes('importing a module script failed') // Safari
|
|
36
|
+
);
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const RECOVERY_GUARD_KEY = '__cogniteSessionRecovery';
|
|
40
|
+
const RECOVERY_MAX_ATTEMPTS = 3;
|
|
41
|
+
const RECOVERY_WINDOW_MS = 30_000;
|
|
42
|
+
|
|
43
|
+
// Cap recovery reloads per window so a non-session chunk failure can't loop forever.
|
|
44
|
+
const requestSessionRecovery = (now: number = Date.now()): void => {
|
|
45
|
+
let attempts = 0;
|
|
46
|
+
let since = now;
|
|
47
|
+
try {
|
|
48
|
+
const saved = JSON.parse(sessionStorage.getItem(RECOVERY_GUARD_KEY) ?? '{}') as {
|
|
49
|
+
attempts?: number;
|
|
50
|
+
since?: number;
|
|
51
|
+
};
|
|
52
|
+
if (now - (saved.since ?? 0) <= RECOVERY_WINDOW_MS) {
|
|
53
|
+
attempts = saved.attempts ?? 0;
|
|
54
|
+
since = saved.since ?? now;
|
|
55
|
+
}
|
|
56
|
+
} catch {
|
|
57
|
+
// sessionStorage unavailable (sandboxed doc): dispatch uncapped.
|
|
58
|
+
}
|
|
59
|
+
if (attempts >= RECOVERY_MAX_ATTEMPTS) return;
|
|
60
|
+
try {
|
|
61
|
+
sessionStorage.setItem(RECOVERY_GUARD_KEY, JSON.stringify({ attempts: attempts + 1, since }));
|
|
62
|
+
} catch {
|
|
63
|
+
// Can't persist the count; recovering once still beats not recovering.
|
|
64
|
+
}
|
|
65
|
+
dispatchSessionExpired();
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
window.addEventListener('unhandledrejection', (event) => {
|
|
69
|
+
if (isDynamicImportFailure(event.reason?.message ?? '')) requestSessionRecovery();
|
|
70
|
+
});
|
|
71
|
+
window.addEventListener(
|
|
72
|
+
'error',
|
|
73
|
+
(event) => {
|
|
74
|
+
// ErrorEvent.message is the reliable string; event.error can be null (e.g. cross-origin).
|
|
75
|
+
if (isDynamicImportFailure(event.message || event.error?.message || '')) {
|
|
76
|
+
requestSessionRecovery();
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
true, // capture phase: chunk/resource load errors do not bubble to window
|
|
80
|
+
);
|
|
81
|
+
|
|
12
82
|
const queryClient = new QueryClient({
|
|
13
83
|
defaultOptions: {
|
|
14
84
|
queries: {
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
var we=Object.defineProperty;var ee=n=>{throw TypeError(n)};var o=(n,e)=>we(n,"name",{value:e,configurable:!0});var te=(n,e,t)=>e.has(n)||ee("Cannot "+t);var ne=(n,e,t)=>(te(n,e,"read from private field"),t?t.call(n):e.get(n)),re=(n,e,t)=>e.has(n)?ee("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),ie=(n,e,t,r)=>(te(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t);import{mkdir as nt,readFile as rt}from"fs/promises";import{basename as it,dirname as ot}from"path";var F=class F extends Error{constructor(e,t={}){super(e),this.name="HintedError",t.cause!==void 0&&(this.cause=t.cause);let r=this.deriveDefaults(t);this.hint=t.hint??r.hint,this.helpUrl=t.helpUrl??r.helpUrl,this.shouldReport=t.shouldReport??!0}deriveDefaults(e){return{hint:xe(e.cause)}}};o(F,"HintedError");var d=F;var oe="https://docs.cognite.com/cdf/access/",ve="https://status.cognite.com";function ke(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:oe};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:oe};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:ve};default:return{}}}o(ke,"defaultHintForStatus");var _=class _ extends d{constructor(e,t){super(e,t),this.name="HintedHttpError",this.httpStatusCode=t.httpStatusCode,this.requestUrl=t.requestUrl,this.responseBody=t.responseBody}deriveDefaults(e){let{httpStatusCode:t}=e,r=ke(t),i=super.deriveDefaults(e);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};o(_,"HintedHttpError");var v=_;function Ce(n,e){if(n)switch(n){case"ENOTFOUND":return e.hostname?`DNS lookup failed for ${e.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return e.hostname&&e.port?`Connection refused by ${e.hostname}:${e.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return e.path?`Permission denied: ${e.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return e.path?`File or directory not found: ${e.path}.`:"File or directory not found.";case"EISDIR":return e.path?`Expected a file but found a directory: ${e.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return e.port?`Port ${e.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}o(Ce,"hintForErrno");function xe(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,i=Ce(r.code,r);if(i!==void 0)return i;e=r.cause}}o(xe,"hintForCause");import{inspect as Ie}from"util";var L="[REDACTED]",x,R=class R{constructor(e){re(this,x);ie(this,x,e)}toString(){return L}toJSON(){return L}[Ie.custom](){return L}expose(){return ne(this,x)}static from(e){return new R(e)}};x=new WeakMap,o(R,"SensitiveString");var S=R;var se="https://docs.cognite.com/cdf/access/";function g(n){return n!==null&&typeof n=="object"}o(g,"isRecord");function I(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}o(I,"isHttpError");function Pe(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
2
|
+
See: ${se}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
3
|
+
See: ${se}`;default:return}}o(Pe,"httpStatusHint");function m(n){let e=n instanceof Error?n:new Error(String(n));if(!I(e))return null;let t=Pe(e.status);return t?Object.assign(new Error(`${e.message}
|
|
4
|
+
${t}`),{cause:e}):null}o(m,"enrichedHttpError");function Te(n){if(!g(n))return null;let e=n.missing;if(Array.isArray(e))return e;let t=n.data;if(g(t)){let r=t.error;if(g(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(t.missing))return t.missing}return null}o(Te,"findMissingArray");function be(n,e){if(!I(n)||n.status!==400)return!1;let t=Te(n);return t?t.some(r=>g(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}o(be,"isMissingExternalIdError");function D(n,e){return I(n)&&n.status===404||be(n,e)}o(D,"isNotFoundError");var pe=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],ce=["ACTIVE","PREVIEW"],H=class H extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};o(H,"AppVersionNotFoundError");var $=H,B=class B extends Error{constructor(e){super(`App ${e} not found`),this.name="AppNotFoundError",this.appExternalId=e}};o(B,"AppNotFoundError");var U=B;function N(n,e){return n.includes(e)}o(N,"includesValue");function Re(n){return N(pe,n)}o(Re,"isAppVersionLifecycleState");function De(n){return N(ce,n)}o(De,"isAppVersionAlias");function $e(n){return typeof n.version=="string"&&Re(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||De(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}o($e,"isAppVersion");function ae(n){if(!g(n)){let e=JSON.stringify(n)?.slice(0,200)??String(n);throw new Error(`Invalid version response: expected object, got ${e}`)}if(!$e(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}o(ae,"parseAppVersion");function Ue(n){if(!g(n))throw new Error("Invalid app response: not an object");let{externalId:e,name:t,description:r}=n;if(typeof e!="string")throw new Error("Invalid app response: missing externalId");if(typeof t!="string")throw new Error("Invalid app response: missing name");if(r!=null&&typeof r!="string")throw new Error("Invalid app response: malformed description");return{externalId:e,name:t,description:typeof r=="string"?r:void 0}}o(Ue,"parseAppMetadata");var M=class M{constructor(e){this.client=e}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(e,t,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:e,name:t,description:r}]}})}catch(i){throw m(i)??i}}async updateApps(e){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:e}})}catch(t){throw m(t)??t}}async getApp(e){let t=`${this.appsBasePath}/${encodeURIComponent(e)}`;try{let r=await this.client.get(t);return Ue(r.data)}catch(r){throw D(r,[e])?new U(e):m(r)??r}}async uploadVersion(e,t,r,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${t}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),i),a.append("version",t),a.append("entryPath",s);let c=encodeURIComponent(e),p=`${this.appsBasePath}/${c}/versions`,u=await this.client.authenticate();if(!u)throw new d("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let E=S.from(u),f=`${this.client.getBaseUrl()}${p}`,X=new AbortController,Ee=setTimeout(()=>X.abort(),300*1e3),A;try{A=await fetch(f,{method:"POST",headers:{Authorization:`Bearer ${E.expose()}`},body:a,signal:X.signal})}catch(h){throw h instanceof Error&&h.name==="AbortError"?new d("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new d(`Failed to upload version to ${f}`,{cause:h,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(Ee)}if(!A.ok){let h=await A.text(),w;try{w=JSON.parse(h)}catch{}let b=h;if(g(w)){let k=w.error;if(typeof k=="string")b=k;else if(g(k)){let C=k.message,Q=k.code;b=typeof C=="string"?C:Q!=null?`Unknown error (code: ${Q})`:h}else{let C=w.message;b=typeof C=="string"?C:h}}let Z=A.headers.get("x-request-id"),Se=Z?` | X-Request-ID: ${Z}`:"",Ae=g(w)?w:h;throw new v(`Upload failed: ${A.status} \u2014 ${b}${Se}`,{httpStatusCode:A.status,requestUrl:f,responseBody:Ae})}console.log(`\u2705 Version ${t} uploaded`)}async getVersion(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${i}`;try{let a=await this.client.get(s);return ae(a.data)}catch(a){throw D(a,[e,t])?new $(e,t):m(a)??a}}async getActiveVersion(e){let t=encodeURIComponent(e),r=`${this.appsBasePath}/${t}/versions/list`;try{let i=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!g(i.data)||!Array.isArray(i.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=i.data;if(s.length===0)return null;if(s.length>1)throw new Error(`Unexpected response: ${s.length} versions have the ACTIVE alias, expected at most 1`);return ae(s[0])}catch(i){if(D(i,[e]))return null;throw m(i)??i}}async updateVersions(e,t){let r=encodeURIComponent(e),i=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(i,{data:{items:t}})}catch(s){throw m(s)??s}}async submitSignatures(e,t,r){let i=encodeURIComponent(e),s=encodeURIComponent(t),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(c){throw m(c)??c}}async listSignatures(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${i}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return Oe(a.data)}catch(a){throw m(a)??a}}};o(M,"AppHostingApi");var V=M,Ne=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Ve=["developer","certifier"];function Oe(n){if(!g(n))throw new Error("Invalid signatures response: expected an object with an items array");let{items:e}=n;if(!Array.isArray(e))throw new Error("Invalid signatures response: items property is missing or not an array");return e.flatMap(t=>{let r=Fe(t);return r?[r]:[]})}o(Oe,"parseStoredSignatures");function Fe(n){if(!g(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:s,status:a}=n;return typeof e!="string"||e===""||!N(Ve,t)||typeof r!="number"||typeof i!="number"||typeof s!="number"||!N(Ne,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:s,status:a}}o(Fe,"parseStoredSignature");function _e(n,e){let t=[];n.name!==e.name&&t.push({field:"name",remote:n.name,local:e.name});let r=n.description??"";return r!==e.description&&t.push({field:"description",remote:r,local:e.description}),t}o(_e,"diffAppMetadata");function Le(n){let e=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:t,remote:r,local:i}of n){let s=`${t}:`.padEnd(14);e.push(` ${s}"${r}" \u2192 "${i}"`)}return e.join(`
|
|
5
|
+
`)}o(Le,"formatMetadataDriftError");var j=class j{constructor(e){this.api=new V(e)}getVersion(e,t){return this.api.getVersion(e,t)}uploadVersion(e,t,r,i,s){return this.api.uploadVersion(e,t,r,i,s)}async ensureApp(e,t,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(e,t,r),console.log(`\u2705 App '${e}' created`)}catch(i){if(I(i)&&i.status===409){console.log(`\u2705 App '${e}' already exists`),await this.checkMetadataDrift(e,t,r);return}throw i}}async checkMetadataDrift(e,t,r){let i;try{i=await this.getApp(e)}catch{return}let s=_e(i,{name:t,description:r});if(s.length!==0)throw new d(Le(s),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(e){return this.api.getApp(e)}async updateAppMetadata(e,t,r){await this.api.updateApps([{externalId:e,update:{name:{set:t},description:r?{set:r}:{setNull:!0}}}])}async submitSignatures(e,t,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${t}...`),await this.api.submitSignatures(e,t,r),console.log("\u2705 Signatures stored"))}listSignatures(e,t){return this.api.listSignatures(e,t)}async publishVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(e,t){console.log(`\u{1F680} Publishing and activating version ${t}...`),await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${t} is now PUBLISHED and ACTIVE`)}getActiveVersion(e){return this.api.getActiveVersion(e)}async deactivateVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{alias:{setNull:!0}}}])}async activateVersion(e,t){let r=null;try{r=await this.api.getActiveVersion(e)}catch{r=null}let i=r&&r.version!==t?r.version:void 0;return await this.api.updateVersions(e,[{version:t,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(e,t,r,i,s,a,c=!1){console.log(`
|
|
6
|
+
\u{1F680} Deploying application via App Hosting API...
|
|
7
|
+
`),await this.ensureApp(e,t,r),await this.uploadVersion(e,i,s,a),c&&await this.publishAndActivate(e,i),console.log(`
|
|
8
|
+
\u2705 Deployment successful!`)}};o(j,"AppHostingClient");var P=j;import{execFileSync as O}from"child_process";import y from"fs";import l from"path";import{parseAndValidateManifestConfig as He}from"@cognite/app-sdk/vite";import{BlobReader as Be,Uint8ArrayWriter as Me,ZipWriter as je}from"@zip.js/zip.js";var q="package.json",J="package-lock.json",ue="manifest.json",G=".cognite",qe=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],Y=class Y{constructor(e="dist"){this.distPath=l.isAbsolute(e)?e:l.join(process.cwd(),e),this.appRoot=l.dirname(this.distPath)}validateBuildDirectory(){if(!y.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=l.join(this.appRoot,q);if(!y.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=l.join(this.appRoot,J);if(!y.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`)}async createZip(e="app.zip",t=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new je(new Me,{level:9}),i=o(async(p,u)=>{await r.add(u,new Be(await y.openAsBlob(p))),t&&console.log(` \u{1F4C4} ${u}`)},"addFile"),s=o(async p=>{let u=await y.promises.readdir(p,{withFileTypes:!0});for(let E of u){let f=l.join(p,E.name);E.isDirectory()?await s(f):await i(f,l.relative(this.distPath,f).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let p=l.join(this.appRoot,q);await i(p,l.posix.join(G,q));let u=l.join(this.appRoot,ue);if(y.existsSync(u)){let f=y.readFileSync(u,"utf-8");He(f,u),await i(u,l.posix.join(G,ue))}let E=l.join(this.appRoot,J);await i(E,l.posix.join(G,J)),a=await r.close()}catch(p){let u=p instanceof Error?p.message:String(p);throw new Error(`Failed to create zip: ${u}`)}try{await y.promises.writeFile(e,a)}catch(p){throw new d(`Failed to write bundle to ${e}`,{cause:p})}let c=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${c} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=O("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(p){throw p instanceof Error&&"code"in p&&p.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=O("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=r?r.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(t,s);try{O("git",["-C",t,"archive","--format=zip",`--output=${e}`,s])}catch(p){let u=p instanceof Error?p.message:String(p);throw new Error(`Failed to create source archive: ${u}`)}let c=(y.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${l.basename(e)} (${c} MB)`),e}validateNoSensitiveFiles(e,t){let r=O("git",["-C",e,"ls-tree","-r","--name-only",t],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
9
|
+
`).filter(Boolean),i=o(a=>a.split("/").some(c=>qe.some(p=>p.test(c))),"isSensitive"),s=r.filter(i);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
|
|
10
|
+
`+s.map(a=>` ${a}`).join(`
|
|
11
|
+
`)+`
|
|
12
|
+
Hint: git rm --cached <file>`)}};o(Y,"ApplicationPackager");var T=Y;import Je from"path";var de=".cognite-bundles";function le(n,e){return`${n}-${e}.zip`}o(le,"bundleFileName");function z(n,e,t){return Je.join(n,de,le(e,t))}o(z,"bundlePath");import{CogniteClient as tt}from"@cognite/sdk";function Ge(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}o(Ge,"exponentialBackoffWithJitter");function Ye(n){return new Promise(e=>setTimeout(e,n))}o(Ye,"sleep");async function ge(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),i=e.delayInMsCalculator??Ge;if(t<1)throw new Error("`maxAttempts` must be 1 or greater");if(t>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await n()}catch(a){if(s>=t||!r(a))throw a;let c=i(s);e.onAttemptFail?.(a,s,c),await Ye(c),s++}}o(ge,"retryAsync");var ze="https://auth.cognite.com/oauth2/token",Ke=o(n=>typeof n=="object"&&n!==null&&"access_token"in n&&typeof n.access_token=="string","hasAccessToken");async function fe({idp:n,tokenUrl:e,init:t,missingTokenHint:r}){let i;try{i=await ge(()=>fetch(e,t),{maxAttempts:3})}catch(c){throw new d(`Failed to fetch access token from ${e}`,{cause:c})}if(!i.ok){let c=await i.text();throw new v(`Failed to get token from ${n}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:e,responseBody:c})}let s=await i.text(),a;try{a=JSON.parse(s)}catch{throw new d(`Unexpected response from ${n} authentication (invalid JSON)`,{hint:r})}if(!Ke(a))throw new d(`No access token in ${n} authentication response`,{hint:r});return S.from(a.access_token)}o(fe,"fetchOAuthToken");var We=o(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let e=JSON.parse(n),t={};for(let[r,i]of Object.entries(e))if(typeof i=="string"){let s=r.toLowerCase().replace(/_/g,"-");t[s]=i}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),Xe=o(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=We()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return S.from(e)},"getSecretFromEnv"),Ze=o((n,e)=>{let t=e.expose();return fe({idp:"CDF",tokenUrl:ze,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${n}:${t}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."})},"getTokenCdf"),he=o(({idp:n,tokenUrl:e,clientId:t,clientSecret:r,scopes:i,missingTokenHint:s})=>fe({idp:n,tokenUrl:e,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:t,client_secret:r,grant_type:"client_credentials",...i!==void 0?{scope:i.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),Qe=o((n,e)=>{if(e!==void 0)return e.join(" ");if(!n)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(n).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${n}`)}},"resolveEntraScope"),et=o((n,e,t,r,i)=>he({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,clientId:n,clientSecret:e.expose(),scopes:i!==void 0?i:[Qe(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),K=o(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return S.from(e.COGNITE_TOKEN);let{deployClientId:t,deploySecretName:r,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:c,tokenUrl:p}=n,u=Xe(r);if(i==="oauth"){if(!p)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return he({idp:"OAuth",tokenUrl:p,clientId:t,clientSecret:u.expose(),scopes:c,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return et(t,u,s,a,c)}return Ze(t,u)},"getToken");async function W(n,e,t=process.env,r){let i=await K(n,t),s=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(c=>new tt(c)))({appId:e,project:n.project,baseUrl:s,oidcTokenProvider:o(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}o(W,"getSdk");async function me(n,e,t,r){let{externalId:i,name:s,description:a,versionTag:c}=e,p=z(t,i,c);await nt(ot(p),{recursive:!0}),await new T(`${t}/dist`).createZip(p,!0);let u;try{u=await rt(p)}catch(E){throw new d(`Failed to read bundle file: ${p}`,{cause:E})}await new P(n).deploy(i,s,a,c,u,it(p),r)}o(me,"packageAndUpload");var st=o(async(n,e,t)=>{let r=await W(n,t);await me(r,e,t,n.published)},"deploy");import{existsSync as at,readFileSync as pt}from"fs";var ye=[".dev.sig",".cert.sig"];function ct(n,e={}){let t=e.existsSync??at,r=e.readFileSync??((s,a)=>pt(s,a)),i=[];for(let s of ye){let a=`${n}${s}`;if(!t(a))continue;let c=r(a,"utf8").trim();c.length>0&&i.push(c)}return i}o(ct,"discoverSignatures");export{P as a,T as b,de as c,le as d,z as e,K as f,W as g,me as h,st as i,ye as j,ct as k};
|