@cognite/cli 1.6.0-alpha.sdk-gen → 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/.npmrc.ejs.t +1 -1
- package/_templates/app/new/root/AGENTS.md.ejs.t +12 -60
- package/_templates/app/new/root/SPEC.md.ejs.t +15 -17
- package/_templates/app/new/root/app.json.ejs.t +0 -1
- package/_templates/app/new/root/manifest.json.ejs.t +1 -6
- package/_templates/app/new/root/package.json.ejs.t +8 -11
- 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-IX7GU6LI.js → chunk-74X2P7OO.js} +8 -8
- package/dist/cli/cli.js +92 -195
- package/dist/deploy/index.js +1 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.js +1 -1
- package/package.json +6 -15
- package/dist/chunk-ATR2SGLU.js +0 -1
- package/dist/chunk-OIOJTLJU.js +0 -1
- package/dist/sdk-runtime/index.d.ts +0 -255
- package/dist/sdk-runtime/index.js +0 -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,62 +22,13 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
|
|
|
21
22
|
|
|
22
23
|
---
|
|
23
24
|
|
|
24
|
-
## 1.
|
|
25
|
-
|
|
26
|
-
Before writing any feature code that reads CDF data model instances, check whether a generated SDK exists:
|
|
27
|
-
|
|
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 **read-only**: `queryX`, `getByIdX`, `searchX`, `countX`, `aggregateX` — no write operations
|
|
53
|
-
- Relation fields appear only where the type exposes them: list/search results include direct relations as references; `getByIdX` additionally includes reverse relations and edges as connection objects (`{ items: [...], pageInfo: {...} }`)
|
|
54
|
-
- For writes, use `client.instances.upsert` / `client.instances.delete` directly
|
|
55
|
-
|
|
56
|
-
```ts
|
|
57
|
-
import { createSdk } from '../generated_sdks/<name>';
|
|
58
|
-
|
|
59
|
-
const sdk = createSdk(client); // no network call — instantiation is synchronous
|
|
60
|
-
|
|
61
|
-
const result = await sdk.queryMyView({
|
|
62
|
-
filter: { status: { eq: 'active' } },
|
|
63
|
-
limit: 25,
|
|
64
|
-
});
|
|
65
|
-
// result.items[0].relatedView ← direct relation fields resolve in the same call
|
|
66
|
-
|
|
67
|
-
const detail = await sdk.getByIdMyView({ space: '...', externalId: '...' });
|
|
68
|
-
// detail.reverseRelationField.items ← reverse/edge relations only available here
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
---
|
|
72
|
-
|
|
73
|
-
## 2. UI Components
|
|
25
|
+
## 1. UI Components
|
|
74
26
|
|
|
75
27
|
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.
|
|
76
28
|
|
|
77
29
|
---
|
|
78
30
|
|
|
79
|
-
##
|
|
31
|
+
## 2. Host integration (`@cognite/app-sdk`)
|
|
80
32
|
|
|
81
33
|
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.
|
|
82
34
|
|
|
@@ -123,7 +75,7 @@ async function updateState(next: AppState, api: HostAppAPI) {
|
|
|
123
75
|
|
|
124
76
|
---
|
|
125
77
|
|
|
126
|
-
##
|
|
78
|
+
## 3. Dependency Injection
|
|
127
79
|
|
|
128
80
|
**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.
|
|
129
81
|
|
|
@@ -157,7 +109,7 @@ export const doWork = async (props: Props, overrides?: Partial<Deps>) => {
|
|
|
157
109
|
|
|
158
110
|
---
|
|
159
111
|
|
|
160
|
-
##
|
|
112
|
+
## 4. Interface-Based Services
|
|
161
113
|
|
|
162
114
|
Define an interface; implement with a class. Never reference the concrete class outside its own file.
|
|
163
115
|
|
|
@@ -174,7 +126,7 @@ export class ApiDataService implements DataService {
|
|
|
174
126
|
|
|
175
127
|
---
|
|
176
128
|
|
|
177
|
-
##
|
|
129
|
+
## 5. ViewModel Pattern
|
|
178
130
|
|
|
179
131
|
Business logic lives in `use<Name>ViewModel`. Components only render.
|
|
180
132
|
|
|
@@ -210,11 +162,11 @@ This matters because each call to a `useState`-backed hook creates an **independ
|
|
|
210
162
|
|
|
211
163
|
### Host-synced state inside a ViewModel
|
|
212
164
|
|
|
213
|
-
When a ViewModel exposes state that falls under §
|
|
165
|
+
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.
|
|
214
166
|
|
|
215
167
|
---
|
|
216
168
|
|
|
217
|
-
##
|
|
169
|
+
## 6. Test-First Development
|
|
218
170
|
|
|
219
171
|
Write tests before implementation for all non-trivial behavior changes.
|
|
220
172
|
|
|
@@ -310,7 +262,7 @@ Place reusable factories in `src/__mocks__/`. Use `.test` TLD for fake URLs (RFC
|
|
|
310
262
|
|
|
311
263
|
---
|
|
312
264
|
|
|
313
|
-
##
|
|
265
|
+
## 7. TypeScript Rules
|
|
314
266
|
|
|
315
267
|
- Never use `any`; prefer `unknown` or explicit strong types
|
|
316
268
|
- Never use `as` casts — they silence the compiler without providing safety. Use type guards instead.
|
|
@@ -337,14 +289,14 @@ const mock = { postMessage: vi.fn() } as Partial<Window> as Window;
|
|
|
337
289
|
|
|
338
290
|
---
|
|
339
291
|
|
|
340
|
-
##
|
|
292
|
+
## 8. CogniteClient / authentication
|
|
341
293
|
|
|
342
294
|
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.
|
|
343
295
|
|
|
344
296
|
---
|
|
345
297
|
|
|
346
298
|
|
|
347
|
-
##
|
|
299
|
+
## 9. Commits and pull requests
|
|
348
300
|
|
|
349
301
|
Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/).
|
|
350
302
|
|
|
@@ -355,4 +307,4 @@ Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/
|
|
|
355
307
|
- **Pull requests:** title and **Summary** should match the same vocabulary; do not replace conventional commits with only a PR headline.
|
|
356
308
|
- Before committing: review **`git status`** and **`git diff`** (including staged); unstage and commit separately if the index mixes unrelated concerns.
|
|
357
309
|
|
|
358
|
-
---
|
|
310
|
+
---
|
|
@@ -51,29 +51,27 @@ to: '<%= useSpecKit ? null : (useCurrentDir ? "" : ((directoryName || name) + "/
|
|
|
51
51
|
|
|
52
52
|
---
|
|
53
53
|
|
|
54
|
-
## CDF
|
|
54
|
+
## Data Models & CDF Integration *(mandatory)*
|
|
55
55
|
|
|
56
56
|
<!--
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
npx @cognite/cli@<%= cliVersion %> apps sdk --interactive
|
|
61
|
-
|
|
62
|
-
Once generated, src/generated_sdks/<name>/schema.graphql 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
|
-
###
|
|
61
|
+
### Existing views
|
|
70
62
|
|
|
71
|
-
<!--
|
|
63
|
+
<!--
|
|
64
|
+
CDF views this app reads from. Format: `<space>.<view>:<version>`.
|
|
65
|
+
-->
|
|
72
66
|
|
|
73
|
-
###
|
|
67
|
+
### New views
|
|
74
68
|
|
|
75
|
-
<!--
|
|
69
|
+
<!--
|
|
70
|
+
Views this app needs that don't yet exist. Describe properties and relationships.
|
|
71
|
+
-->
|
|
76
72
|
|
|
77
|
-
###
|
|
73
|
+
### Spaces
|
|
78
74
|
|
|
79
|
-
<!--
|
|
75
|
+
<!--
|
|
76
|
+
CDF spaces this app uses, and what each contains.
|
|
77
|
+
-->
|
|
@@ -28,13 +28,10 @@ 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/
|
|
32
|
-
"@cognite/app-sdk": "^0.6.0",
|
|
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,25 +42,25 @@ 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": "^
|
|
45
|
+
"@types/node": "^25.0.0",
|
|
49
46
|
"@types/react": "^18.3.1",
|
|
50
47
|
"@types/react-dom": "^18.3.1",
|
|
51
|
-
"@vitejs/plugin-react": "
|
|
52
|
-
"@vitest/coverage-v8": "4.1.
|
|
53
|
-
"@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",
|
|
54
51
|
"autoprefixer": "^10.4.22",
|
|
55
52
|
"eslint": "9.39.4",
|
|
56
53
|
"eslint-plugin-import": "^2.32.0",
|
|
57
54
|
"eslint-plugin-no-only-tests": "^3.3.0",
|
|
58
55
|
"eslint-plugin-react-hooks": "^7.1.1",
|
|
59
56
|
"eslint-plugin-react-refresh": "^0.5.2",
|
|
60
|
-
"globals": "^
|
|
57
|
+
"globals": "^17.0.0",
|
|
61
58
|
"happy-dom": "^20.9.0",
|
|
62
59
|
"postcss": "^8.5.6",
|
|
63
60
|
"tailwindcss": "^4.1.17",
|
|
64
61
|
"typescript": "^5.0.0",
|
|
65
62
|
"typescript-eslint": "^8.46.4",
|
|
66
|
-
"vite": "7.3.
|
|
67
|
-
"vitest": "4.1.
|
|
63
|
+
"vite": ">=7.3.5 <8.0.0",
|
|
64
|
+
"vitest": "4.1.8"
|
|
68
65
|
}
|
|
69
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: {
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
|
|
2
|
-
See: ${
|
|
3
|
-
See: ${
|
|
4
|
-
${t}`),{cause:e}):null}o(m,"enrichedHttpError");function
|
|
5
|
-
`)}o(
|
|
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
6
|
\u{1F680} Deploying application via App Hosting API...
|
|
7
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
|
|
9
|
-
`).filter(Boolean),i=o(a=>a.split("/").some(c=>
|
|
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
10
|
`+s.map(a=>` ${a}`).join(`
|
|
11
11
|
`)+`
|
|
12
|
-
Hint: git rm --cached <file>`)}};o(Y,"ApplicationPackager");var T=Y;import
|
|
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};
|