@cognite/cli 1.7.0 → 1.8.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.
@@ -0,0 +1,66 @@
1
+ # {{displayName}}
2
+
3
+ > Edit `agent.yaml` to configure your agent — tools, model, instructions.
4
+
5
+ ## Quick start
6
+
7
+ ```bash
8
+ # Push agent config to CDF (draft)
9
+ cognite agents push
10
+
11
+ # Open agent in Fusion for testing
12
+ cognite agents open
13
+
14
+ # Publish agent (makes it visible to users)
15
+ cognite agents publish
16
+ ```
17
+
18
+ ## Project layout
19
+
20
+ | Path | Purpose |
21
+ |------|---------|
22
+ | `agent.yaml` | Agent definition (externalId, tools, model, instructions) |
23
+ | `README.md` | This file |
24
+
25
+ ## Adding tools
26
+
27
+ Edit the `tools` array in `agent.yaml`. Available tool types:
28
+
29
+ - `analyzeData` — analyze tabular or structured data
30
+ - `analyzeImage` — analyze images and P&ID diagrams
31
+ - `analyzeTimeSeries` — analyze time series data
32
+ - `askDocument` — ask questions about documents
33
+ - `callFunction` — call a Cognite Function
34
+ - `callRestApi` — call an external REST API
35
+ - `callWebhook` — POST a payload to an external webhook
36
+ - `examineDataSemantically` — semantic data examination
37
+ - `query` — structured queries against CDF data models
38
+ - `queryKnowledgeGraph` — query CDF data models with natural language
39
+ - `queryTimeSeriesDatapoints` — fetch raw or aggregated time series data
40
+ - `runPythonCode` — execute custom Python code
41
+ - `summarizeDocument` — summarize documents
42
+ - `timeSeriesAnalysis` — advanced time series analysis and anomaly detection
43
+
44
+ Example tool:
45
+
46
+ ```yaml
47
+ tools:
48
+ - name: find_assets
49
+ type: queryKnowledgeGraph
50
+ description: Find assets and related instances in the knowledge graph.
51
+ configuration:
52
+ version: v2
53
+ dataModels:
54
+ - space: cdf_cdm
55
+ externalId: CogniteCore
56
+ version: v1
57
+ viewExternalIds:
58
+ - CogniteAsset
59
+ instanceSpaces:
60
+ type: all
61
+ ```
62
+
63
+ ## Deployment with Toolkit
64
+
65
+ The generated `agent.yaml` is compatible with [Cognite Toolkit](https://docs.cognite.com/cdf/deploy/toolkit/).
66
+ Place it in your Toolkit module under `agents/` and deploy with `cdf deploy`.
@@ -2,7 +2,7 @@
2
2
  to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>vitest.config.ts'
3
3
  ---
4
4
  import react from '@vitejs/plugin-react';
5
- import { defineConfig } from 'vitest/config';
5
+ import { configDefaults, defineConfig } from 'vitest/config';
6
6
 
7
7
  export default defineConfig({
8
8
  plugins: [react()],
@@ -10,10 +10,11 @@ export default defineConfig({
10
10
  globals: true,
11
11
  environment: 'happy-dom',
12
12
  setupFiles: ['vitest.setup.ts'],
13
+ exclude: [...configDefaults.exclude, '.claude/**', '.agents/**'],
13
14
  coverage: {
14
15
  provider: 'v8',
15
16
  reporter: ['text', 'json', 'html', 'lcov'],
16
- exclude: ['node_modules/', 'dist/', 'vitest.setup.ts', '**/*.config.ts', '**/*.d.ts'],
17
+ exclude: ['node_modules/', 'dist/', '.claude/', '.agents/', 'vitest.setup.ts', '**/*.config.ts', '**/*.d.ts'],
17
18
  },
18
19
  },
19
20
  });
@@ -26,7 +26,7 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
26
26
  "setup-https": "npx @cognite/cli@latest apps setup-https"
27
27
  },
28
28
  "dependencies": {
29
- "@cognite/aura": "^0.1.7",
29
+ "@cognite/aura": "^0.2.0",
30
30
  "@cognite/sdk": "^10.10.0",
31
31
  "@cognite/app-sdk": "^0.8.0",
32
32
  "@tabler/icons-react": "^3.35.0",
@@ -2,6 +2,7 @@
2
2
  to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>src/App.test.tsx'
3
3
  ---
4
4
  import { render, screen, waitFor } from '@testing-library/react';
5
+ import userEvent from '@testing-library/user-event';
5
6
  import { beforeEach, describe, expect, it, vi } from 'vitest';
6
7
  import type { HostAppAPI, ConnectToHostAppResult } from '@cognite/app-sdk';
7
8
  import { CogniteClient } from '@cognite/sdk';
@@ -35,9 +36,9 @@ function makeLoadingDeps(): AppDeps {
35
36
  };
36
37
  }
37
38
 
38
- function makeConnectedDeps(): AppDeps {
39
+ function makeConnectedDeps(api = makeApi()): AppDeps {
39
40
  return {
40
- connectToHostApp: vi.fn<AppDeps['connectToHostApp']>(() => Promise.resolve({ api: makeApi() })),
41
+ connectToHostApp: vi.fn<AppDeps['connectToHostApp']>(() => Promise.resolve({ api })),
41
42
  createClient: vi.fn<AppDeps['createClient']>((config) => new CogniteClient(config)),
42
43
  };
43
44
  }
@@ -69,4 +70,33 @@ describe('App', () => {
69
70
  expect(screen.getAllByText(/SPEC\.md/).length).toBeGreaterThan(0);
70
71
  expect(screen.getByText(/apps deploy --interactive/)).toBeInTheDocument();
71
72
  });
73
+
74
+ it('syncs internal state when the open step changes', async () => {
75
+ const api = makeApi();
76
+ render(<App deps={makeConnectedDeps(api)} />);
77
+ await waitFor(() => expect(screen.getByText('App deployment checklist')).toBeInTheDocument());
78
+
79
+ await userEvent.click(screen.getByText('Explore'));
80
+
81
+ expect(api.syncInternalState).toHaveBeenCalledWith(
82
+ JSON.stringify({ openStep: 'Explore' })
83
+ );
84
+ });
85
+
86
+ it('restores the open step from initial state', async () => {
87
+ const api = makeApi();
88
+ const deps: AppDeps = {
89
+ connectToHostApp: vi.fn<AppDeps['connectToHostApp']>(() =>
90
+ Promise.resolve({ api, initialState: JSON.stringify({ openStep: 'Deploy' }) })
91
+ ),
92
+ createClient: vi.fn<AppDeps['createClient']>((config) => new CogniteClient(config)),
93
+ };
94
+ render(<App deps={deps} />);
95
+ await waitFor(() => expect(screen.getByText('App deployment checklist')).toBeInTheDocument());
96
+
97
+ await waitFor(() =>
98
+ expect(screen.getByRole('button', { name: /deploy/i })).toHaveAttribute('aria-expanded', 'true')
99
+ );
100
+ expect(screen.getByRole('button', { name: /plan/i })).toHaveAttribute('aria-expanded', 'false');
101
+ });
72
102
  });
@@ -2,6 +2,9 @@
2
2
  to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>src/App.tsx'
3
3
  ---
4
4
  import type { ComponentProps } from 'react';
5
+ import { useEffect, useState } from 'react';
6
+ import { connectToHostApp as connectToHostAppImpl } from '@cognite/app-sdk';
7
+ import type { HostAppAPI } from '@cognite/app-sdk';
5
8
  import { CogniteSdkProvider, useCogniteSdk } from '@cognite/app-sdk/react';
6
9
  import {
7
10
  Alert,
@@ -62,6 +65,8 @@ const CHECKLIST_STEPS = [
62
65
  },
63
66
  ] as const;
64
67
 
68
+ type AppInternalState = { openStep: string | null };
69
+
65
70
  const loadingFallback = (
66
71
  <main className="min-h-screen bg-muted/50 text-foreground">
67
72
  <section className="mx-auto flex min-h-screen w-full max-w-lg flex-col justify-center p-4 sm:p-8">
@@ -91,13 +96,37 @@ const errorFallback = (
91
96
  </main>
92
97
  );
93
98
 
94
- function AppContent() {
99
+ type AppContentProps = { api: HostAppAPI | null; initialState?: string };
100
+
101
+ function AppContent({ api, initialState }: AppContentProps) {
95
102
  const client = useCogniteSdk();
96
103
 
97
104
  const deployment = appConfig.deployments?.[0];
98
105
  const orgLabel = deployment?.org ?? '';
99
106
  const projectLabel = deployment?.project ?? client.project ?? '';
100
107
 
108
+ const [openStep, setOpenStep] = useState<string | null>(CHECKLIST_STEPS[0].label);
109
+
110
+ // initialState is restored from the ?customAppInternalState search param by the host.
111
+ useEffect(() => {
112
+ if (!initialState) return;
113
+ try {
114
+ const saved = JSON.parse(initialState) as AppInternalState;
115
+ if (typeof saved.openStep === 'string' || saved.openStep === null) {
116
+ setOpenStep(saved.openStep);
117
+ }
118
+ } catch {
119
+ // ignore malformed saved state
120
+ }
121
+ }, [initialState]);
122
+
123
+ function handleStepToggle(label: string, isOpen: boolean) {
124
+ const next = isOpen ? label : null;
125
+ setOpenStep(next);
126
+ // Writes to the ?customAppInternalState search param so the URL is bookmarkable/shareable.
127
+ void api?.syncInternalState(JSON.stringify({ openStep: next } satisfies AppInternalState));
128
+ }
129
+
101
130
  return (
102
131
  <main className="min-h-screen bg-muted/50 text-foreground">
103
132
  <section className="mx-auto flex min-h-screen w-full max-w-3xl flex-col justify-center p-4 sm:p-8">
@@ -118,8 +147,12 @@ function AppContent() {
118
147
  </div>
119
148
 
120
149
  <div className="flex flex-col gap-4 px-4">
121
- {CHECKLIST_STEPS.map((step, index) => (
122
- <Collapsible key={step.label} defaultOpen={index === 0}>
150
+ {CHECKLIST_STEPS.map((step) => (
151
+ <Collapsible
152
+ key={step.label}
153
+ open={openStep === step.label}
154
+ onOpenChange={(isOpen) => handleStepToggle(step.label, isOpen)}
155
+ >
123
156
  <CollapsibleTrigger className="w-full">
124
157
  <div className="flex w-full min-w-0 items-center justify-between gap-3 text-left">
125
158
  <span className="text-lg">{step.label}</span>
@@ -202,12 +235,28 @@ function AppContent() {
202
235
 
203
236
  type AppProps = {
204
237
  deps?: ComponentProps<typeof CogniteSdkProvider>['deps'];
238
+ connectToHostApp?: typeof connectToHostAppImpl;
205
239
  };
206
240
 
207
- function App({ deps }: AppProps) {
241
+ function App({
242
+ deps,
243
+ connectToHostApp = deps?.connectToHostApp ?? connectToHostAppImpl,
244
+ }: AppProps) {
245
+ const [connection, setConnection] = useState<{ api: HostAppAPI; initialState?: string } | null>(null);
246
+
247
+ useEffect(() => {
248
+ let cancelled = false;
249
+ void connectToHostApp().then((result) => {
250
+ if (!cancelled) setConnection(result);
251
+ });
252
+ return () => {
253
+ cancelled = true;
254
+ };
255
+ }, [connectToHostApp]);
256
+
208
257
  return (
209
258
  <CogniteSdkProvider loadingFallback={loadingFallback} errorFallback={errorFallback} deps={deps}>
210
- <AppContent />
259
+ <AppContent api={connection?.api ?? null} initialState={connection?.initialState} />
211
260
  </CogniteSdkProvider>
212
261
  );
213
262
  }
@@ -1,12 +1,6 @@
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';
10
4
  import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
11
5
  import React from 'react';
12
6
  import ReactDOM from 'react-dom/client';
@@ -15,70 +9,6 @@ import App from './App.tsx';
15
9
 
16
10
  import './styles.css';
17
11
 
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
-
82
12
  const queryClient = new QueryClient({
83
13
  defaultOptions: {
84
14
  queries: {
@@ -0,0 +1,12 @@
1
+ var ve=Object.defineProperty;var ne=n=>{throw TypeError(n)};var o=(n,e)=>ve(n,"name",{value:e,configurable:!0});var re=(n,e,t)=>e.has(n)||ne("Cannot "+t);var ie=(n,e,t)=>(re(n,e,"read from private field"),t?t.call(n):e.get(n)),se=(n,e,t)=>e.has(n)?ne("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),oe=(n,e,t,r)=>(re(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t);import{existsSync as ot}from"fs";import{mkdir as at,readFile as pt}from"fs/promises";import{basename as ct,dirname as dt}from"path";var L=class L 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:Pe(e.cause)}}};o(L,"HintedError");var l=L;var ae="https://docs.cognite.com/cdf/access/",ke="https://status.cognite.com";function xe(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:ae};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:ae};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:ke};default:return{}}}o(xe,"defaultHintForStatus");var H=class H extends l{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=xe(t),i=super.deriveDefaults(e);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};o(H,"HintedHttpError");var v=H;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 Pe(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(Pe,"hintForCause");import{inspect as Ie}from"util";var M="[REDACTED]",C,R=class R{constructor(e){se(this,C);oe(this,C,e)}toString(){return M}toJSON(){return M}[Ie.custom](){return M}expose(){return ie(this,C)}static from(e){return new R(e)}};C=new WeakMap,o(R,"SensitiveString");var S=R;var pe="https://docs.cognite.com/cdf/access/";function g(n){return n!==null&&typeof n=="object"}o(g,"isRecord");function P(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}o(P,"isHttpError");function Te(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
+ See: ${pe}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
3
+ See: ${pe}`;default:return}}o(Te,"httpStatusHint");function h(n){let e=n instanceof Error?n:new Error(String(n));if(!P(e))return null;let t=Te(e.status);return t?Object.assign(new Error(`${e.message}
4
+ ${t}`),{cause:e}):null}o(h,"enrichedHttpError");function be(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(be,"findMissingArray");function Re(n,e){if(!P(n)||n.status!==400)return!1;let t=be(n);return t?t.some(r=>g(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}o(Re,"isMissingExternalIdError");function D(n,e){return P(n)&&n.status===404||Re(n,e)}o(D,"isNotFoundError");var de=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],le=["ACTIVE","PREVIEW"],j=class j extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};o(j,"AppVersionNotFoundError");var $=j,q=class q extends Error{constructor(e){super(`App ${e} not found`),this.name="AppNotFoundError",this.appExternalId=e}};o(q,"AppNotFoundError");var U=q;function N(n,e){return n.includes(e)}o(N,"includesValue");function De(n){return N(de,n)}o(De,"isAppVersionLifecycleState");function $e(n){return N(le,n)}o($e,"isAppVersionAlias");function Ue(n){return typeof n.version=="string"&&De(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||$e(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}o(Ue,"isAppVersion");function ce(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(!Ue(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}o(ce,"parseAppVersion");function Ne(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(Ne,"parseAppMetadata");var G=class G{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 h(i)??i}}async updateApps(e){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:e}})}catch(t){throw h(t)??t}}async getApp(e){let t=`${this.appsBasePath}/${encodeURIComponent(e)}`;try{let r=await this.client.get(t);return Ne(r.data)}catch(r){throw D(r,[e])?new U(e):h(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 p=encodeURIComponent(e),c=`${this.appsBasePath}/${p}/versions`,d=await this.client.authenticate();if(!d)throw new l("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let E=S.from(d),f=`${this.client.getBaseUrl()}${c}`,Q=new AbortController,Se=setTimeout(()=>Q.abort(),300*1e3),w;try{w=await fetch(f,{method:"POST",headers:{Authorization:`Bearer ${E.expose()}`},body:a,signal:Q.signal})}catch(m){throw m instanceof Error&&m.name==="AbortError"?new l("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 l(`Failed to upload version to ${f}`,{cause:m,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(Se)}if(!w.ok){let m=await w.text(),A;try{A=JSON.parse(m)}catch{}let b=m;if(g(A)){let k=A.error;if(typeof k=="string")b=k;else if(g(k)){let x=k.message,te=k.code;b=typeof x=="string"?x:te!=null?`Unknown error (code: ${te})`:m}else{let x=A.message;b=typeof x=="string"?x:m}}let ee=w.headers.get("x-request-id"),we=ee?` | X-Request-ID: ${ee}`:"",Ae=g(A)?A:m;throw new v(`Upload failed: ${w.status} \u2014 ${b}${we}`,{httpStatusCode:w.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 ce(a.data)}catch(a){throw D(a,[e,t])?new $(e,t):h(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 ce(s[0])}catch(i){if(D(i,[e]))return null;throw h(i)??i}}async deleteVersions(e,t){let r=encodeURIComponent(e),i=`${this.appsBasePath}/${r}/versions/delete`;try{await this.client.post(i,{data:{items:t.map(s=>({version:s}))}})}catch(s){throw h(s)??s}}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 h(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(p){throw h(p)??p}}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 h(a)??a}}};o(G,"AppHostingApi");var V=G,Ve=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Fe=["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=_e(t);return r?[r]:[]})}o(Oe,"parseStoredSignatures");function _e(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(Fe,t)||typeof r!="number"||typeof i!="number"||typeof s!="number"||!N(Ve,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:s,status:a}}o(_e,"parseStoredSignature");function Be(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(Be,"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(P(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=Be(i,{name:t,description:r});if(s.length!==0)throw new l(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 deleteVersion(e,t){await this.api.deleteVersions(e,[t])}async deprecateVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"DEPRECATED"}}}])}async archiveVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"ARCHIVED"}}}])}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,p=!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),p&&await this.publishAndActivate(e,i),console.log(`
8
+ \u2705 Deployment successful!`)}};o(J,"AppHostingClient");var I=J;import{execFileSync as F}from"child_process";import y from"fs";import u from"path";import{parseAndValidateManifestConfig as He}from"@cognite/app-sdk/vite";import{BlobReader as Me,Uint8ArrayWriter as je,ZipWriter as qe}from"@zip.js/zip.js";var z="package.json",Y="package-lock.json",ue="manifest.json",K=".cognite",Ge=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],W=class W{constructor(e="dist"){this.distPath=u.isAbsolute(e)?e:u.join(process.cwd(),e),this.appRoot=u.dirname(this.distPath)}validateBuildDirectory(){if(!y.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=u.join(this.appRoot,z);if(!y.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=u.join(this.appRoot,Y);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 qe(new je,{level:9}),i=o(async(c,d)=>{await r.add(d,new Me(await y.openAsBlob(c))),t&&console.log(` \u{1F4C4} ${d}`)},"addFile"),s=o(async c=>{let d=await y.promises.readdir(c,{withFileTypes:!0});for(let E of d){let f=u.join(c,E.name);E.isDirectory()?await s(f):await i(f,u.relative(this.distPath,f).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=u.join(this.appRoot,z);await i(c,u.posix.join(K,z));let d=u.join(this.appRoot,ue);if(y.existsSync(d)){let f=y.readFileSync(d,"utf-8");He(f,d),await i(d,u.posix.join(K,ue))}let E=u.join(this.appRoot,Y);await i(E,u.posix.join(K,Y)),a=await r.close()}catch(c){let d=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${d}`)}try{await y.promises.writeFile(e,a)}catch(c){throw new l(`Failed to write bundle to ${e}`,{cause:c})}let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${p} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=F("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 r=F("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{F("git",["-C",t,"archive","--format=zip",`--output=${e}`,s])}catch(c){let d=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${d}`)}let p=(y.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${u.basename(e)} (${p} MB)`),e}validateNoSensitiveFiles(e,t){let r=F("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(p=>Ge.some(c=>c.test(p))),"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(W,"ApplicationPackager");var T=W;import Je from"path";var ge=".cognite-bundles";function he(n,e){return`${n}-${e}.zip`}o(he,"bundleFileName");function O(n,e,t){return Je.join(n,ge,he(e,t))}o(O,"bundlePath");import{CogniteClient as nt}from"@cognite/sdk";function ze(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}o(ze,"exponentialBackoffWithJitter");function Ye(n){return new Promise(e=>setTimeout(e,n))}o(Ye,"sleep");async function fe(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),i=e.delayInMsCalculator??ze;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 p=i(s);e.onAttemptFail?.(a,s,p),await Ye(p),s++}}o(fe,"retryAsync");var Ke="https://auth.cognite.com/oauth2/token",We=o(n=>typeof n=="object"&&n!==null&&"access_token"in n&&typeof n.access_token=="string","hasAccessToken");async function me({idp:n,tokenUrl:e,init:t,missingTokenHint:r}){let i;try{i=await fe(()=>fetch(e,t),{maxAttempts:3})}catch(p){throw new l(`Failed to fetch access token from ${e}`,{cause:p})}if(!i.ok){let p=await i.text();throw new v(`Failed to get token from ${n}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:e,responseBody:p})}let s=await i.text(),a;try{a=JSON.parse(s)}catch{throw new l(`Unexpected response from ${n} authentication (invalid JSON)`,{hint:r})}if(!We(a))throw new l(`No access token in ${n} authentication response`,{hint:r});return S.from(a.access_token)}o(me,"fetchOAuthToken");var Xe=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"),Ze=o(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=Xe()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return S.from(e)},"getSecretFromEnv"),Qe=o((n,e)=>{let t=e.expose();return me({idp:"CDF",tokenUrl:Ke,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"),ye=o(({idp:n,tokenUrl:e,clientId:t,clientSecret:r,scopes:i,missingTokenHint:s})=>me({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"),et=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"),tt=o((n,e,t,r,i)=>ye({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,clientId:n,clientSecret:e.expose(),scopes:i!==void 0?i:[et(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),X=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:p,tokenUrl:c}=n,d=Ze(r);if(i==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return ye({idp:"OAuth",tokenUrl:c,clientId:t,clientSecret:d.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 tt(t,d,s,a,p)}return Qe(t,d)},"getToken");async function _(n,e,t=process.env,r){let i=await X(n,t),s=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(p=>new nt(p)))({appId:e,project:n.project,baseUrl:s,oidcTokenProvider:o(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}o(_,"getSdk");import{existsSync as rt,readFileSync as it}from"fs";var B=[".dev.sig",".cert.sig"];function st(n,e={}){let t=e.existsSync??rt,r=e.readFileSync??((s,a)=>it(s,a)),i=[];for(let s of B){let a=`${n}${s}`;if(!t(a))continue;let p=r(a,"utf8").trim();p.length>0&&i.push(p)}return i}o(st,"discoverSignatures");async function Ee(n,e,{existsSync:t=ot,mkdir:r=at,createZip:i=o((s,a)=>new T(s).createZip(a,!0),"createZipFn")}={}){let{externalId:s,versionTag:a}=n,p=O(e,s,a);if(t(p)){let d=B.some(E=>t(`${p}${E}`))?"A signed bundle already exists here. Re-deploying will invalidate the signing process. Bump versionTag in app.json to deploy as a new version, or delete the bundle and its .sig files then re-sign after deploying.":"Bump versionTag in app.json to deploy as a new version, or delete the existing bundle from .cognite-bundles/ to redeploy the same version.";throw new l(`Bundle already exists: ${p}`,{hint:d,shouldReport:!1})}await r(dt(p),{recursive:!0}),await i(`${e}/dist`,p)}o(Ee,"packageBundle");async function Z(n,e,t,r,{readFile:i=pt,upload:s=o(async(a,p)=>new I(n).deploy(e.externalId,e.name,e.description,e.versionTag,a,p,r),"uploadFn")}={}){let a=O(t,e.externalId,e.versionTag),p;try{p=await i(a)}catch(c){throw new l(`Failed to read bundle file: ${a}`,{cause:c})}await s(p,ct(a))}o(Z,"uploadBundle");var lt=o(async(n,e,t)=>{let r=await _(n,t);await Ee(e,t),await Z(r,e,t,n.published)},"deploy"),ut=o(async(n,e,t)=>{let r=await _(n,t);await Z(r,e,t,n.published)},"deployBundle");export{I as a,T as b,ge as c,he as d,O as e,X as f,_ as g,B as h,st as i,Ee as j,Z as k,lt as l,ut as m};