@cognite/cli 1.8.0-alpha.sdk-gen → 1.9.0-alpha.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,68 @@
1
+ # Eval cases for {{displayName}}
2
+ #
3
+ # Each case is a conversation with the agent plus one or more "scorers" that
4
+ # judge the responses. An LLM judge grades every scored turn. Run the suite with:
5
+ #
6
+ # cognite agents eval
7
+ #
8
+ # Supported scorer types:
9
+ # - correctness: compares the answer to a reference description you provide
10
+ # (`reference`). Use it when you can describe a good answer.
11
+ # - faithfulness: checks the answer is grounded in the supplied `context` and
12
+ # does not hallucinate. Use it for retrieval / grounded answers.
13
+ # - toolSelection: checks whether the agent picked an appropriate tool (or
14
+ # correctly used none) for the question, based on the tools
15
+ # configured in agent.yaml. Requires no extra fields, but only
16
+ # makes sense once you've added tools (see README.md's
17
+ # "Adding tools" section).
18
+ #
19
+ # These are placeholders — edit the inputs, references, and context to match what
20
+ # your agent actually does, then add more cases over time.
21
+
22
+ cases:
23
+ # Single-turn case scored for correctness.
24
+ - id: greeting
25
+ turns:
26
+ - input: "Hi, what can you help me with?"
27
+ scorers:
28
+ - type: correctness
29
+ # Describe what a good answer looks like; the judge compares against this.
30
+ reference: >-
31
+ A friendly greeting that briefly explains what this agent can help
32
+ the user with.
33
+
34
+ # Single-turn case scored for faithfulness against supplied context.
35
+ - id: grounded-answer
36
+ turns:
37
+ - input: "Where is the main compressor located?"
38
+ scorers:
39
+ - type: faithfulness
40
+ # The answer must be grounded in this context and not invent facts.
41
+ context: >-
42
+ The main compressor (unit C-101) is installed on Deck 2 of the
43
+ North platform, next to the gas separation train.
44
+
45
+ # Single-turn case scored for tool selection. Assumes you've added the
46
+ # `find_assets` tool from README.md's "Adding tools" example — the judge
47
+ # checks whether the agent picked an appropriate tool (or none) based on
48
+ # the tools listed in agent.yaml.
49
+ - id: find-assets-tool
50
+ turns:
51
+ - input: "Find assets related to compressors in the knowledge graph."
52
+ scorers:
53
+ - type: toolSelection
54
+
55
+ # Multi-turn case: the agent should carry context across turns.
56
+ - id: assets-followup
57
+ turns:
58
+ - input: "List the assets in the cooling system."
59
+ scorers:
60
+ - type: correctness
61
+ reference: "Lists the assets that belong to the cooling system."
62
+ - input: "Now show only the ones that are currently active."
63
+ scorers:
64
+ - type: correctness
65
+ # Relies on the previous turn — the judge sees the earlier turns as context.
66
+ reference: >-
67
+ Narrows the previously listed cooling-system assets down to only
68
+ the active ones.
@@ -20,8 +20,20 @@ cognite agents publish
20
20
  | Path | Purpose |
21
21
  |------|---------|
22
22
  | `agent.yaml` | Agent definition (externalId, tools, model, instructions) |
23
+ | `eval/cases.yaml` | Example eval cases — run with `cognite agents eval` |
23
24
  | `README.md` | This file |
24
25
 
26
+ ## Evaluating the agent
27
+
28
+ `eval/cases.yaml` contains starter test cases (single-turn and multi-turn) that
29
+ grade the agent's responses with an LLM judge. After pushing the agent, run:
30
+
31
+ ```bash
32
+ cognite agents eval
33
+ ```
34
+
35
+ Edit the cases to match what your agent does, and add more over time.
36
+
25
37
  ## Adding tools
26
38
 
27
39
  Edit the `tools` array in `agent.yaml`. Available tool types:
@@ -2,4 +2,4 @@
2
2
  to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>.npmrc'
3
3
  ---
4
4
  engine-strict=true
5
- min-release-age=0
5
+ min-release-age=1
@@ -10,6 +10,7 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
10
10
 
11
11
  - To start a new feature, run `/speckit.specify <description>` in Claude Code or Cursor. It generates a properly numbered feature directory and a spec to fill in. Then run `/speckit.clarify` → `/speckit.plan` → `/speckit.tasks` → `/speckit.implement`.
12
12
  - When user-visible behavior changes in an existing feature, update its `specs/<NNN>-<feature>/spec.md` before or alongside the code change.
13
+ - When a feature touches Cognite Data Fusion data, the spec must document existing CDF views read from, new views needed, and spaces used.
13
14
  <% } else { -%>
14
15
  ## 0. Product Spec (SPEC.md)
15
16
 
@@ -21,64 +22,15 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
21
22
 
22
23
  ---
23
24
 
24
- ## 1. CDF Data & Generated SDK
25
+ ## 1. UI Components
25
26
 
26
- Before writing any feature code that reads CDF data model instances, check whether a generated SDK exists:
27
+ Always check Aura before reaching for a raw HTML element or custom CSS/Tailwind solution. If Aura has a component that covers the need, use it. Only fall back to custom solutions when Aura genuinely doesn't cover the use case.
27
28
 
28
- ```bash
29
- ls src/generated_sdks/
30
- ```
31
-
32
- ### If the SDK does not exist
33
-
34
- Stop. Do not write placeholder code or stub SDK calls. Tell the user:
35
-
36
- > To read data from your CDF data model, you'll need to generate a typed SDK first. Run this from the app root (where `app.json` lives):
37
- >
38
- > ```bash
39
- > npx @cognite/cli@<%= cliVersion %> apps sdk --interactive
40
- > ```
41
- >
42
- > The wizard will log you in via the browser, let you pick a data model, and write the generated files into `src/generated_sdks/`. Come back when it's done.
43
-
44
- Wait for the user to confirm generation is complete before continuing.
45
-
46
- ### If the SDK exists
47
-
48
- Use `createSdk(client)` from `src/generated_sdks/<name>/index.ts` for all reads. Rules:
49
-
50
- - **Read the generated TypeScript types first** (`src/generated_sdks/<name>/types.generated.ts`) to understand what views, fields, and relations are available — the return types show exactly which fields exist on list vs detail queries, including relation fields
51
- - **Do not call `client.instances.list`, `client.instances.query`, or `client.instances.search` directly** — always go through the generated SDK for reads
52
- - The SDK is **resource-namespaced and read-only**: `sdk.<resource>.<query | getById | count | search | aggregate>(...)`, where `<resource>` is the camelCase view name (e.g. view `MyView` → `sdk.myView`). No write operations.
53
- - Relation fields appear only where the type exposes them: list/search results include direct relations as references; `getById` additionally includes reverse relations and edges as connection objects (`{ items: [...], pageInfo: {...} }`)
54
- - `getById` takes flat `{ space, externalId }`; `count` returns a number; `query` sort uses `direction: 'ascending' | 'descending'`; `select` narrows the fetched fields (identity is always returned and is not selectable)
55
- - For writes, use `client.instances.upsert` / `client.instances.delete` directly
56
-
57
- ```ts
58
- import { createSdk } from '../generated_sdks/<name>';
59
-
60
- const sdk = createSdk(client); // no network call — instantiation is synchronous
61
-
62
- const result = await sdk.myView.query({
63
- filter: { status: { eq: 'active' } },
64
- select: ['name', 'status'], // optional: fetch only these fields (identity always returned)
65
- limit: 25,
66
- });
67
- // result.items[0].relatedView ← direct relation fields resolve in the same call
68
-
69
- const detail = await sdk.myView.getById({ space: '...', externalId: '...' });
70
- // detail.reverseRelationField.items ← reverse/edge relations only available here
71
- ```
29
+ Import each component from its own subpath — `@cognite/aura/components/button`, `@cognite/aura/components/card`, etc. — rather than from the `@cognite/aura/components` barrel. The barrel pulls in Aura's entire dependency graph (including large libraries like mermaid and shiki), which slows the build and can exhaust memory in constrained environments.
72
30
 
73
31
  ---
74
32
 
75
- ## 2. UI Components
76
-
77
- Always check `@cognite/aura/components` before reaching for a raw HTML element or custom CSS/Tailwind solution. If Aura has a component that covers the need, use it. Only fall back to custom solutions when Aura genuinely doesn't cover the use case.
78
-
79
- ---
80
-
81
- ## 3. Host integration (`@cognite/app-sdk`)
33
+ ## 2. Host integration (`@cognite/app-sdk`)
82
34
 
83
35
  The Fusion host exposes a `HostAppAPI` (imported as `HostAppAPI` from `@cognite/app-sdk`) via `connectToHostApp(...)`. Reach for it whenever the situation calls for it — don't hand-roll an equivalent or read browser globals directly.
84
36
 
@@ -125,7 +77,7 @@ async function updateState(next: AppState, api: HostAppAPI) {
125
77
 
126
78
  ---
127
79
 
128
- ## 4. Dependency Injection
80
+ ## 3. Dependency Injection
129
81
 
130
82
  **All non-stateless dependencies must be injected.** Never import and call a service, SDK client, or stateful module directly inside a component or hook — it makes the code untestable and tightly coupled.
131
83
 
@@ -159,7 +111,7 @@ export const doWork = async (props: Props, overrides?: Partial<Deps>) => {
159
111
 
160
112
  ---
161
113
 
162
- ## 5. Interface-Based Services
114
+ ## 4. Interface-Based Services
163
115
 
164
116
  Define an interface; implement with a class. Never reference the concrete class outside its own file.
165
117
 
@@ -176,7 +128,7 @@ export class ApiDataService implements DataService {
176
128
 
177
129
  ---
178
130
 
179
- ## 6. ViewModel Pattern
131
+ ## 5. ViewModel Pattern
180
132
 
181
133
  Business logic lives in `use<Name>ViewModel`. Components only render.
182
134
 
@@ -212,11 +164,11 @@ This matters because each call to a `useState`-backed hook creates an **independ
212
164
 
213
165
  ### Host-synced state inside a ViewModel
214
166
 
215
- When a ViewModel exposes state that falls under §3's "host-synced" category, the **ViewModel** — not the view component — is responsible for seeding from `initialState` and pushing changes via `syncInternalState`. The state itself still lives in the shared storage layer described above; the ViewModel just owns the read/write contract with the host.
167
+ When a ViewModel exposes state that falls under §2's "host-synced" category, the **ViewModel** — not the view component — is responsible for seeding from `initialState` and pushing changes via `syncInternalState`. The state itself still lives in the shared storage layer described above; the ViewModel just owns the read/write contract with the host.
216
168
 
217
169
  ---
218
170
 
219
- ## 7. Test-First Development
171
+ ## 6. Test-First Development
220
172
 
221
173
  Write tests before implementation for all non-trivial behavior changes.
222
174
 
@@ -312,7 +264,7 @@ Place reusable factories in `src/__mocks__/`. Use `.test` TLD for fake URLs (RFC
312
264
 
313
265
  ---
314
266
 
315
- ## 8. TypeScript Rules
267
+ ## 7. TypeScript Rules
316
268
 
317
269
  - Never use `any`; prefer `unknown` or explicit strong types
318
270
  - Never use `as` casts — they silence the compiler without providing safety. Use type guards instead.
@@ -339,14 +291,14 @@ const mock = { postMessage: vi.fn() } as Partial<Window> as Window;
339
291
 
340
292
  ---
341
293
 
342
- ## 9. CogniteClient / authentication
294
+ ## 8. CogniteClient / authentication
343
295
 
344
296
  Auth is handled by `CogniteSdkProvider` from `@cognite/app-sdk/react` (see `App.tsx`). Nested components get the client via `useCogniteSdk()`. To wire up or migrate auth, run the `/setup-flows-auth` skill.
345
297
 
346
298
  ---
347
299
 
348
300
 
349
- ## 10. Commits and pull requests
301
+ ## 9. Commits and pull requests
350
302
 
351
303
  Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/).
352
304
 
@@ -357,4 +309,4 @@ Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/
357
309
  - **Pull requests:** title and **Summary** should match the same vocabulary; do not replace conventional commits with only a PR headline.
358
310
  - Before committing: review **`git status`** and **`git diff`** (including staged); unstage and commit separately if the index mixes unrelated concerns.
359
311
 
360
- ---
312
+ ---
@@ -51,29 +51,27 @@ to: '<%= useSpecKit ? null : (useCurrentDir ? "" : ((directoryName || name) + "/
51
51
 
52
52
  ---
53
53
 
54
- ## CDF Data *(mandatory)*
54
+ ## Data Models & CDF Integration *(mandatory)*
55
55
 
56
56
  <!--
57
- Which data model does this app connect to? If you haven't already, generate a
58
- typed SDK by running from the app root:
59
-
60
- npx @cognite/cli@<%= cliVersion %> apps sdk --interactive
61
-
62
- Once generated, src/generated_sdks/<name>/types.generated.ts is the source of truth
63
- for what views, fields, and relations are available.
64
-
65
- Describe below what data this feature reads and why — in plain terms, not view IDs.
66
- Example: "Reads active work orders and their assigned assets."
57
+ Capture how this app integrates with Cognite Data Fusion data models.
58
+ Every Flows app should fill this in.
67
59
  -->
68
60
 
69
- ### Data model
61
+ ### Existing views
70
62
 
71
- <!-- Which data model: name, space, version. -->
63
+ <!--
64
+ CDF views this app reads from. Format: `<space>.<view>:<version>`.
65
+ -->
72
66
 
73
- ### What this app reads
67
+ ### New views
74
68
 
75
- <!-- Plain-language description of the data this feature needs and any key filters. -->
69
+ <!--
70
+ Views this app needs that don't yet exist. Describe properties and relationships.
71
+ -->
76
72
 
77
- ### Writes
73
+ ### Spaces
78
74
 
79
- <!-- Does this feature write back to CDF? If so, what and under what conditions? If read-only, note that here. -->
75
+ <!--
76
+ CDF spaces this app uses, and what each contains.
77
+ -->
@@ -7,7 +7,6 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>app.json'
7
7
  "externalId": "<%= name %>",
8
8
  "versionTag": "0.0.1",
9
9
  "infra": "appsApi",
10
- "sdk-gen-alpha-version": "<%= cliVersion %>",
11
10
  "deployments": [
12
11
  {
13
12
  "org": "<%= org %>",
@@ -4,11 +4,6 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>manifest.json'
4
4
  {
5
5
  "manifestVersion": 1,
6
6
  "permissions": {
7
- "network": [
8
- {
9
- "sources": ["https://api.mixpanel.com"],
10
- "directives": ["connect-src"]
11
- }
12
- ]
7
+ "network": []
13
8
  }
14
9
  }
@@ -7,7 +7,7 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
7
7
  "private": true,
8
8
  "type": "module",
9
9
  "engines": {
10
- "node": ">=20",
10
+ "node": ">=20 <22.23.0 || >=22.23.1 <24.17.0 || >=24.18.0 <26.3.1 || >=26.4.0",
11
11
  "npm": ">=11.10.0"
12
12
  },
13
13
  "scripts": {
@@ -28,13 +28,10 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
28
28
  "dependencies": {
29
29
  "@cognite/aura": "^0.3.1",
30
30
  "@cognite/sdk": "^10.10.0",
31
- "@cognite/cli": "<%= cliVersion %>",
32
31
  "@cognite/app-sdk": "^0.8.0",
33
32
  "@tabler/icons-react": "^3.35.0",
34
33
  "@tanstack/react-query": "^5.90.10",
35
34
  "clsx": "^2.1.1",
36
- "graphql": "^16.14.0",
37
- "graphql-tag": "^2.12.6",
38
35
  "react": "^18.3.1",
39
36
  "react-dom": "^18.3.1",
40
37
  "tailwind-merge": "^3.4.0"
@@ -45,12 +42,12 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
45
42
  "@testing-library/jest-dom": "^6.6.3",
46
43
  "@testing-library/react": "^16.1.0",
47
44
  "@testing-library/user-event": "^14.5.2",
48
- "@types/node": "^25.0.0",
45
+ "@types/node": "^26.0.0",
49
46
  "@types/react": "^18.3.1",
50
47
  "@types/react-dom": "^18.3.1",
51
48
  "@vitejs/plugin-react": ">=5.1.1 <6.0.0",
52
- "@vitest/coverage-v8": "4.1.8",
53
- "@vitest/ui": "4.1.8",
49
+ "@vitest/coverage-v8": "4.1.9",
50
+ "@vitest/ui": "4.1.9",
54
51
  "autoprefixer": "^10.4.22",
55
52
  "eslint": "9.39.4",
56
53
  "eslint-plugin-import": "^2.32.0",
@@ -64,6 +61,6 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
64
61
  "typescript": "^5.0.0",
65
62
  "typescript-eslint": "^8.46.4",
66
63
  "vite": ">=7.3.5 <8.0.0",
67
- "vitest": "4.1.8"
64
+ "vitest": "4.1.9"
68
65
  }
69
66
  }
@@ -6,21 +6,25 @@ import { useEffect, useState } from 'react';
6
6
  import { connectToHostApp as connectToHostAppImpl } from '@cognite/app-sdk';
7
7
  import type { HostAppAPI } from '@cognite/app-sdk';
8
8
  import { CogniteSdkProvider, useCogniteSdk } from '@cognite/app-sdk/react';
9
+ // Import per-component, not from the `@cognite/aura/components` barrel: the
10
+ // barrel pulls in Aura's whole dependency graph (including large libraries like
11
+ // mermaid and shiki), which slows the build and can exhaust memory in CI.
12
+ import { Alert, AlertDescription } from '@cognite/aura/components/alert';
13
+ import { Badge } from '@cognite/aura/components/badge';
9
14
  import {
10
- Alert,
11
- AlertDescription,
12
- Badge,
13
15
  Card,
14
16
  CardContent,
15
17
  CardDescription,
16
18
  CardHeader,
17
19
  CardTitle,
20
+ } from '@cognite/aura/components/card';
21
+ import {
18
22
  Collapsible,
19
23
  CollapsibleContent,
20
24
  CollapsibleTrigger,
21
- Loader,
22
- Separator,
23
- } from '@cognite/aura/components';
25
+ } from '@cognite/aura/components/collapsible';
26
+ import { Loader } from '@cognite/aura/components/loader';
27
+ import { Separator } from '@cognite/aura/components/separator';
24
28
  import { IconCaretUpDown, IconRocket } from '@tabler/icons-react';
25
29
 
26
30
  import appConfig from '../app.json';
@@ -0,0 +1,12 @@
1
+ var ke=Object.defineProperty;var re=n=>{throw TypeError(n)};var s=(n,e)=>ke(n,"name",{value:e,configurable:!0});var ie=(n,e,t)=>e.has(n)||re("Cannot "+t);var b=(n,e,t)=>(ie(n,e,"read from private field"),t?t.call(n):e.get(n)),se=(n,e,t)=>e.has(n)?re("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),oe=(n,e,t,r)=>(ie(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t);import{existsSync as ct}from"fs";import{mkdir as dt,readFile as ut}from"fs/promises";import{basename as lt,dirname as gt}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)}}};s(L,"HintedError");var u=L;var ae="https://docs.cognite.com/cdf/access/",xe="https://status.cognite.com";function Ie(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:xe};default:return{}}}s(Ie,"defaultHintForStatus");var M=class M 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=Ie(t),i=super.deriveDefaults(e);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};s(M,"HintedHttpError");var k=M;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}}s(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}}s(Pe,"hintForCause");import{inspect as Te}from"util";var j="[REDACTED]",w,D=class D{constructor(e){se(this,w);oe(this,w,e)}toString(){return j}toJSON(){return j}[Te.custom](){return j}expose(){return b(this,w)}equals(e){return b(this,w)===b(e,w)}static from(e){return new D(e)}};w=new WeakMap,s(D,"SensitiveString");var E=D;var pe="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 Re(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}}s(Re,"httpStatusHint");function f(n){let e=n instanceof Error?n:new Error(String(n));if(!C(e))return null;let t=Re(e.status);return t?Object.assign(new Error(`${e.message}
4
+ ${t}`),{cause:e}):null}s(f,"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}s(be,"findMissingArray");function De(n,e){if(!C(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}s(De,"isMissingExternalIdError");function $(n,e){return C(n)&&n.status===404||De(n,e)}s($,"isNotFoundError");var de=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],ue=["ACTIVE","PREVIEW"],G=class G extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};s(G,"AppVersionNotFoundError");var U=G,q=class q extends Error{constructor(e){super(`App ${e} not found`),this.name="AppNotFoundError",this.appExternalId=e}};s(q,"AppNotFoundError");var V=q;function N(n,e){return n.includes(e)}s(N,"includesValue");function $e(n){return N(de,n)}s($e,"isAppVersionLifecycleState");function Ue(n){return N(ue,n)}s(Ue,"isAppVersionAlias");function Ve(n){return typeof n.version=="string"&&$e(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||Ue(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}s(Ve,"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(!Ve(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}s(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}}s(Ne,"parseAppMetadata");var J=class J{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 f(i)??i}}async updateApps(e){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:e}})}catch(t){throw f(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 $(r,[e])?new V(e):f(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 p=encodeURIComponent(e),c=`${this.appsBasePath}/${p}/versions`,d=await this.client.authenticate();if(!d)throw new u("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let S=E.from(d),h=`${this.client.getBaseUrl()}${c}`,ee=new AbortController,we=setTimeout(()=>ee.abort(),300*1e3),A;try{A=await fetch(h,{method:"POST",headers:{Authorization:`Bearer ${S.expose()}`},body:a,signal:ee.signal})}catch(m){throw m instanceof Error&&m.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 ${h}`,{cause:m,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(we)}if(!A.ok){let m=await A.text(),v;try{v=JSON.parse(m)}catch{}let R=m;if(g(v)){let x=v.error;if(typeof x=="string")R=x;else if(g(x)){let I=x.message,ne=x.code;R=typeof I=="string"?I:ne!=null?`Unknown error (code: ${ne})`:m}else{let I=v.message;R=typeof I=="string"?I:m}}let te=A.headers.get("x-request-id"),Ae=te?` | X-Request-ID: ${te}`:"",ve=g(v)?v:m;throw new k(`Upload failed: ${A.status} \u2014 ${R}${Ae}`,{httpStatusCode:A.status,requestUrl:h,responseBody:ve})}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 ce(a.data)}catch(a){throw $(a,[e,t])?new U(e,t):f(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 ce(o[0])}catch(i){if($(i,[e]))return null;throw f(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(o=>({version:o}))}})}catch(o){throw f(o)??o}}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 f(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(p){throw f(p)??p}}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 _e(a.data)}catch(a){throw f(a)??a}}};s(J,"AppHostingApi");var F=J,Fe=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY","SCOPE_MISMATCH","VERIFICATION_FAILED"],Oe=["developer","certifier"];function _e(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=Be(t);return r?[r]:[]})}s(_e,"parseStoredSignatures");function Be(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===""||!N(Oe,t)||typeof r!="number"||typeof i!="number"||typeof o!="number"||!N(Fe,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:o,status:a}}s(Be,"parseStoredSignature");function He(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(He,"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 o=`${t}:`.padEnd(14);e.push(` ${o}"${r}" \u2192 "${i}"`)}return e.join(`
5
+ `)}s(Le,"formatMetadataDriftError");var z=class z{constructor(e){this.api=new F(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=He(i,{name:t,description:r});if(o.length!==0)throw new u(Le(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 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,o,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,o,a),p&&await this.publishAndActivate(e,i),console.log(`
8
+ \u2705 Deployment successful!`)}};s(z,"AppHostingClient");var P=z;import{execFileSync as O}from"child_process";import y from"fs";import l from"path";import{parseAndValidateManifestConfig as Ge}from"@cognite/app-sdk/vite";import{BlobReader as qe,Uint8ArrayWriter as Je,ZipWriter as ze}from"@zip.js/zip.js";import{execFileSync as Me}from"child_process";function je(n={}){let{execFileSync:e=Me}=n;try{return e("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}s(je,"isGitInstalled");function le(n={}){if(!je(n))throw new u("Git is not installed or not found on PATH.",{hint:"Install Git (https://git-scm.com) and ensure it is on your PATH, then try again.",shouldReport:!1})}s(le,"throwIfGitMissing");var Y="package.json",K="package-lock.json",ge="manifest.json",W=".cognite",Ye=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],X=class X{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,Y);if(!y.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=l.join(this.appRoot,K);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 ze(new Je,{level:9}),i=s(async(c,d)=>{await r.add(d,new qe(await y.openAsBlob(c))),t&&console.log(` \u{1F4C4} ${d}`)},"addFile"),o=s(async c=>{let d=await y.promises.readdir(c,{withFileTypes:!0});for(let S of d){let h=l.join(c,S.name);S.isDirectory()?await o(h):await i(h,l.relative(this.distPath,h).replace(/\\/g,"/"))}},"addDir"),a;try{await o(this.distPath);let c=l.join(this.appRoot,Y);await i(c,l.posix.join(W,Y));let d=l.join(this.appRoot,ge);if(y.existsSync(d)){let h=y.readFileSync(d,"utf-8");Ge(h,d),await i(d,l.posix.join(W,ge))}let S=l.join(this.appRoot,K);await i(S,l.posix.join(W,K)),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 u(`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=O("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw le(),new u("Source packaging requires a git repository.",{hint:"Run `git init` first.",shouldReport:!1,cause:c})}let r=O("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{O("git",["-C",t,"archive","--format=zip",`--output=${e}`,o])}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: ${l.basename(e)} (${p} 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=s(a=>a.split("/").some(p=>Ye.some(c=>c.test(p))),"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(X,"ApplicationPackager");var T=X;import Ke from"path";var fe=".cognite-bundles";function he(n,e){return`${n}-${e}.zip`}s(he,"bundleFileName");function _(n,e,t){return Ke.join(n,fe,he(e,t))}s(_,"bundlePath");import{CogniteClient as st}from"@cognite/sdk";function We(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}s(We,"exponentialBackoffWithJitter");function Xe(n){return new Promise(e=>setTimeout(e,n))}s(Xe,"sleep");async function me(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),i=e.delayInMsCalculator??We;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 p=i(o);e.onAttemptFail?.(a,o,p),await Xe(p),o++}}s(me,"retryAsync");var Ze="https://auth.cognite.com/oauth2/token",Qe=s(n=>typeof n=="object"&&n!==null&&"access_token"in n&&typeof n.access_token=="string","hasAccessToken");async function ye({idp:n,tokenUrl:e,init:t,missingTokenHint:r}){let i;try{i=await me(()=>fetch(e,t),{maxAttempts:3})}catch(p){throw new u(`Failed to fetch access token from ${e}`,{cause:p})}if(!i.ok){let p=await i.text();throw new k(`Failed to get token from ${n}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:e,responseBody:p})}let o=await i.text(),a;try{a=JSON.parse(o)}catch{throw new u(`Unexpected response from ${n} authentication (invalid JSON)`,{hint:r})}if(!Qe(a))throw new u(`No access token in ${n} authentication response`,{hint:r});return E.from(a.access_token)}s(ye,"fetchOAuthToken");var et=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"),tt=s(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=et()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return E.from(e)},"getSecretFromEnv"),nt=s((n,e)=>{let t=e.expose();return ye({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"),Se=s(({idp:n,tokenUrl:e,clientId:t,clientSecret:r,scopes:i,missingTokenHint:o})=>ye({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"),rt=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"),it=s((n,e,t,r,i)=>Se({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,clientId:n,clientSecret:e.expose(),scopes:i!==void 0?i:[rt(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),Z=s(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return E.from(e.COGNITE_TOKEN);let{deployClientId:t,deploySecretName:r,idpType:i="cdf",tenantId:o,baseUrl:a,scopes:p,tokenUrl:c}=n,d=tt(r);if(i==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return Se({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(!o)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return it(t,d,o,a,p)}return nt(t,d)},"getToken");async function B(n,e,t=process.env,r){let i=await Z(n,t),o=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(p=>new st(p)))({appId:e,project:n.project,baseUrl:o,oidcTokenProvider:s(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}s(B,"getSdk");import{existsSync as ot,readFileSync as at}from"fs";var H=[".dev.sig",".cert.sig"];function pt(n,e={}){let t=e.existsSync??ot,r=e.readFileSync??((o,a)=>at(o,a)),i=[];for(let o of H){let a=`${n}${o}`;if(!t(a))continue;let p=r(a,"utf8").trim();p.length>0&&i.push(p)}return i}s(pt,"discoverSignatures");async function Ee(n,e,{existsSync:t=ct,mkdir:r=dt,createZip:i=s((o,a)=>new T(o).createZip(a,!0),"createZipFn")}={}){let{externalId:o,versionTag:a}=n,p=_(e,o,a);if(t(p)){let d=H.some(S=>t(`${p}${S}`))?"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 u(`Bundle already exists: ${p}`,{hint:d,shouldReport:!1})}await r(gt(p),{recursive:!0}),await i(`${e}/dist`,p)}s(Ee,"packageBundle");async function Q(n,e,t,r,{readFile:i=ut,upload:o=s(async(a,p)=>new P(n).deploy(e.externalId,e.name,e.description,e.versionTag,a,p,r),"uploadFn")}={}){let a=_(t,e.externalId,e.versionTag),p;try{p=await i(a)}catch(c){throw new u(`Failed to read bundle file: ${a}`,{cause:c})}await o(p,lt(a))}s(Q,"uploadBundle");var ft=s(async(n,e,t)=>{let r=await B(n,t);await Ee(e,t),await Q(r,e,t,n.published)},"deploy"),ht=s(async(n,e,t)=>{let r=await B(n,t);await Q(r,e,t,n.published)},"deployBundle");export{P as a,T as b,fe as c,he as d,_ as e,Z as f,B as g,H as h,pt as i,Ee as j,Q as k,ft as l,ht as m};