@cognite/cli 1.5.0 → 1.6.0-alpha.sdk-gen

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.
@@ -1,4 +1,5 @@
1
1
  import { CogniteClient, ClientOptions } from '@cognite/sdk';
2
+ import { inspect } from 'node:util';
2
3
 
3
4
  /**
4
5
  * App Hosting HTTP API layer.
@@ -24,6 +25,12 @@ interface AppVersion {
24
25
  createdBy: string;
25
26
  appExternalId: string;
26
27
  }
28
+ /** Stored app metadata as returned by `GET /apps/:id`. */
29
+ interface AppMetadata {
30
+ externalId: string;
31
+ name: string;
32
+ description?: string;
33
+ }
27
34
  declare const SIGNATURE_STATUSES: readonly ["VALID", "REVOKED", "EXPIRED", "SIGNED_BEFORE_KEY_ISSUED", "IAT_IN_FUTURE", "BUNDLE_TOO_OLD", "KEY_NOT_IN_REGISTRY"];
28
35
  type SignatureStatus = (typeof SIGNATURE_STATUSES)[number];
29
36
  declare const SIGNER_ROLES: readonly ["developer", "certifier"];
@@ -43,10 +50,26 @@ declare class AppHostingClient {
43
50
  getVersion(appExternalId: string, version: string): Promise<AppVersion>;
44
51
  uploadVersion(appExternalId: string, version: string, fileContent: Buffer, fileName: string, entryPath?: string): Promise<void>;
45
52
  /**
46
- * Ensure the app exists creates it if missing, treats 409 Conflict as
53
+ * Ensure the app exists. Creates it when missing; treats 409 Conflict as
47
54
  * success so the call is safe to repeat.
55
+ *
56
+ * Deploy does not change an existing app's name or description — instead, when
57
+ * the app already exists, it checks for metadata drift. Any drift blocks the
58
+ * deploy; the user must run `apps metadata update` to sync first.
48
59
  */
49
60
  ensureApp(externalId: string, name: string, description: string): Promise<void>;
61
+ /**
62
+ * Drift check on deploy: any metadata drift blocks the deploy. A failed
63
+ * lookup must never block a deploy, so API errors here are swallowed.
64
+ */
65
+ private checkMetadataDrift;
66
+ /** Fetch the deployed app's stored metadata. Throws AppNotFoundError when absent. */
67
+ getApp(externalId: string): Promise<AppMetadata>;
68
+ /**
69
+ * Explicitly push the app's name and description to the backend. An empty
70
+ * description is sent as setNull, since the backend rejects blank strings.
71
+ */
72
+ updateAppMetadata(externalId: string, name: string, description: string): Promise<void>;
50
73
  /**
51
74
  * Submit verified compact-JWS signatures for a version uploaded earlier.
52
75
  * No-op when `items` is empty so callers can wire it unconditionally.
@@ -93,13 +116,15 @@ type Deployment = {
93
116
  deploySecretName: string;
94
117
  published: boolean;
95
118
  /** Identity provider type. Defaults to "cdf" if not specified */
96
- idpType?: 'cdf' | 'entra_id';
119
+ idpType?: 'cdf' | 'entra_id' | 'oauth';
97
120
  /** Tenant ID for Entra ID authentication. Required when idpType is "entra_id" */
98
121
  tenantId?: string;
99
122
  /** OAuth scopes to request. When omitted, token retrieval derives
100
123
  * `https://<cluster>.cognitedata.com/.default` from `baseUrl`. When set to `[]`,
101
124
  * an empty scope string is sent. */
102
125
  scopes?: string[];
126
+ /** OAuth token endpoint. Required when idpType is "oauth". */
127
+ tokenUrl?: string;
103
128
  };
104
129
  type App = {
105
130
  externalId: string;
@@ -144,6 +169,26 @@ type Authenticatable = Pick<CogniteClient, 'authenticate'>;
144
169
  declare function getSdk(deployment: Deployment, folder: string, env?: NodeJS.ProcessEnv): Promise<CogniteClient>;
145
170
  declare function getSdk<C extends Authenticatable>(deployment: Deployment, folder: string, env: NodeJS.ProcessEnv, createClient: (opts: ClientOptions) => C): Promise<C>;
146
171
 
172
+ /**
173
+ * Wraps a secret string so it cannot accidentally leak through string
174
+ * coercion, `JSON.stringify`, or `util.inspect` / `console.log`. The raw
175
+ * value is only accessible via {@link expose}, which should be called at
176
+ * trusted boundaries (crypto operations, HTTP headers, SDK init) and nowhere
177
+ * else.
178
+ */
179
+ declare class SensitiveString {
180
+ #private;
181
+ constructor(value: string);
182
+ toString(): string;
183
+ toJSON(): string;
184
+ /** Covers `util.inspect` and `console.log`. */
185
+ [inspect.custom](): string;
186
+ /** Returns the raw value. Only call this at a trusted boundary. */
187
+ expose(): string;
188
+ /** Creates a {@link SensitiveString} wrapping `value`. */
189
+ static from(value: string): SensitiveString;
190
+ }
191
+
147
192
  /**
148
193
  * Get access token for deployment using the appropriate identity provider.
149
194
  * Supports both CDF OAuth and Entra ID (Azure AD) authentication.
@@ -151,7 +196,7 @@ declare function getSdk<C extends Authenticatable>(deployment: Deployment, folde
151
196
  * Set COGNITE_TOKEN to skip OAuth entirely (useful when running the CLI
152
197
  * against a local mock server — see cli/testing/msw/standalone.ts).
153
198
  */
154
- declare const getToken: (deployment: Deployment, env?: NodeJS.ProcessEnv) => Promise<string>;
199
+ declare const getToken: (deployment: Deployment, env?: NodeJS.ProcessEnv) => Promise<SensitiveString>;
155
200
 
156
201
  /**
157
202
  * Sibling-file discovery for bundle signatures written by `cognite sign`.
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-5ABVQYYD.js";export{a as AppHostingClient,b as ApplicationPackager,c as BUNDLE_DIR,j as SIGNATURE_SUFFIXES,d as bundleFileName,e as bundlePath,i as deploy,k as discoverSignatures,g as getSdk,f as getToken,h as packageAndUpload};
1
+ import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-IX7GU6LI.js";import"../chunk-ATR2SGLU.js";export{a as AppHostingClient,b as ApplicationPackager,c as BUNDLE_DIR,j as SIGNATURE_SUFFIXES,d as bundleFileName,e as bundlePath,i as deploy,k as discoverSignatures,g as getSdk,f as getToken,h as packageAndUpload};
package/dist/index.d.ts CHANGED
@@ -1,2 +1,5 @@
1
1
  export { App, AppHostingClient, ApplicationPackager, BUNDLE_DIR, Deployment, SIGNATURE_SUFFIXES, bundleFileName, bundlePath, deploy, discoverSignatures, getSdk, getToken, packageAndUpload } from './deploy/index.js';
2
+ export { DuneRequester, DuneRuntime, ViewDefinition, ViewDefinitionProperty, createDuneRuntime, createDuneRuntimeFromViews } from './sdk-runtime/index.js';
2
3
  import '@cognite/sdk';
4
+ import 'node:util';
5
+ import 'graphql';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-5ABVQYYD.js";export{o as AppHostingClient,r as ApplicationPackager,e as BUNDLE_DIR,b as SIGNATURE_SUFFIXES,f as bundleFileName,m as bundlePath,a as deploy,c as discoverSignatures,t as getSdk,p as getToken,x as packageAndUpload};
1
+ import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-IX7GU6LI.js";import{a as d,b as g}from"./chunk-OIOJTLJU.js";import"./chunk-ATR2SGLU.js";export{o as AppHostingClient,r as ApplicationPackager,e as BUNDLE_DIR,b as SIGNATURE_SUFFIXES,f as bundleFileName,m as bundlePath,d as createDuneRuntime,g as createDuneRuntimeFromViews,a as deploy,c as discoverSignatures,t as getSdk,p as getToken,x as packageAndUpload};
@@ -0,0 +1,255 @@
1
+ import { ViewDefinition as ViewDefinition$1, ViewPropertyDefinition, EnumProperty, ConnectionDefinitionRead, ViewReference, FilterDefinition, SearchSort, AggregationDefinition, AggregatedResultItem, InstancesAPI, CogniteClient } from '@cognite/sdk';
2
+ import { DocumentNode, GraphQLSchema } from 'graphql';
3
+
4
+ interface GenerateSdkConfig {
5
+ name: string;
6
+ space: string;
7
+ dataModelExternalId: string;
8
+ dataModelVersion: string;
9
+ }
10
+
11
+ interface SharedViewId {
12
+ space: string;
13
+ externalId: string;
14
+ version: string;
15
+ }
16
+ type PropertyDescriptor = {
17
+ kind: 'scalar';
18
+ isList?: boolean;
19
+ graphqlType?: string;
20
+ } | {
21
+ kind: 'enum';
22
+ values: string[];
23
+ valueNames: Record<string, string>;
24
+ } | {
25
+ kind: 'directRelation';
26
+ targetView: SharedViewId;
27
+ } | {
28
+ kind: 'directRelationList';
29
+ targetView: SharedViewId;
30
+ } | {
31
+ kind: 'reverseDirect';
32
+ sourceView: SharedViewId;
33
+ throughProperty: string;
34
+ } | {
35
+ kind: 'reverseList';
36
+ sourceView: SharedViewId;
37
+ throughProperty: string;
38
+ } | {
39
+ kind: 'edge';
40
+ targetView: SharedViewId;
41
+ direction: 'outwards' | 'inwards';
42
+ };
43
+ interface SchemaView {
44
+ view: SharedViewId;
45
+ properties: Map<string, PropertyDescriptor>;
46
+ }
47
+ interface SchemaKnowledge {
48
+ view(ref: SharedViewId): SchemaView;
49
+ property(ref: SharedViewId, prop: string): PropertyDescriptor | undefined;
50
+ }
51
+
52
+ type DmsEnumPropertyType = EnumProperty & {
53
+ list?: boolean;
54
+ maxListSize?: number;
55
+ };
56
+ type CodegenPropertyType = Exclude<ViewPropertyDefinition['type'], EnumProperty> | DmsEnumPropertyType;
57
+ type ViewDefinitionProperty = ((Omit<ViewPropertyDefinition, 'type'> & {
58
+ type: CodegenPropertyType;
59
+ }) | ConnectionDefinitionRead) & {
60
+ constraintState?: Record<string, unknown>;
61
+ description?: string;
62
+ };
63
+ type ViewDefinition = Omit<ViewDefinition$1, 'properties'> & {
64
+ properties: Record<string, ViewDefinitionProperty>;
65
+ };
66
+
67
+ /**
68
+ * Executes an operation document in-process and resolves to its result.
69
+ * The generated SDK supplies the result/variable types at each call site
70
+ * (requester<TData, TVariables>(doc, vars)), so no cast is needed on the
71
+ * document constants themselves.
72
+ */
73
+ type DuneRequester = <TData, TVariables>(doc: DocumentNode, variables?: TVariables) => Promise<TData>;
74
+
75
+ interface PropertyRef {
76
+ view: ViewReference;
77
+ property: string;
78
+ }
79
+ interface ConnectionSelection {
80
+ limit?: number;
81
+ select: SelectionTree;
82
+ }
83
+ interface SelectionTree {
84
+ scalars: string[];
85
+ connections: Map<string, ConnectionSelection>;
86
+ }
87
+ interface SortClause {
88
+ property: PropertyRef;
89
+ direction: 'ascending' | 'descending';
90
+ /** When true, nulls sort before non-nulls. Defaults to false. */
91
+ nullsFirst?: boolean;
92
+ }
93
+ /** Pre-translated DMS logical filter (output of translateFilter in resolver layer). */
94
+ type LogicalFilter = FilterDefinition;
95
+ interface QueryInput {
96
+ view: ViewReference;
97
+ filter?: LogicalFilter;
98
+ sort?: SortClause[];
99
+ select: SelectionTree;
100
+ /** Page size. Defaults to INITIAL_BATCH_LIMIT if omitted. */
101
+ limit?: number;
102
+ /** Opaque cursor from a previous ListResult.pageInfo.endCursor. */
103
+ cursor?: string;
104
+ }
105
+ interface ListResult<T = Record<string, unknown>> {
106
+ items: T[];
107
+ pageInfo: {
108
+ endCursor: string | null;
109
+ hasNextPage: boolean;
110
+ };
111
+ }
112
+
113
+ interface SearchInput {
114
+ view: ViewReference;
115
+ /** Full-text search term. */
116
+ query?: string;
117
+ filter?: LogicalFilter;
118
+ sort?: SearchSort[];
119
+ select: SelectionTree;
120
+ /** Max items to return. Defaults to searchLimit config. */
121
+ limit?: number;
122
+ /** Restrict search to specific property names within the view. */
123
+ properties?: string[];
124
+ }
125
+
126
+ interface AggregateInput {
127
+ view: ViewReference;
128
+ filter?: LogicalFilter;
129
+ aggregates: AggregationDefinition[];
130
+ groupBy?: string[];
131
+ /** Optional full-text query to scope which instances are aggregated. */
132
+ query?: string;
133
+ }
134
+ interface AggregateOutput {
135
+ items: AggregatedResultItem[];
136
+ }
137
+
138
+ type DmsClient = Pick<InstancesAPI, 'query' | 'search' | 'aggregate' | 'retrieve' | 'upsert' | 'delete' | 'sync' | 'inspect'>;
139
+ interface PlannerConfig {
140
+ initialBatchLimit: number;
141
+ maxBatchLimit: number;
142
+ searchLimit: number;
143
+ inFilterChunkSize: number;
144
+ reverseListChunkSize: number;
145
+ previewLimit: number;
146
+ nestedDetailLimit: number;
147
+ enableRemoveNotConnected: boolean;
148
+ max408Retries: number;
149
+ max429Retries: number;
150
+ retryBaseDelayMs: number;
151
+ maxConcurrentRequests: number;
152
+ /** Maximum SelectionTree nesting depth. Throws PlannerValidationError if exceeded. */
153
+ maxNestingDepth: number;
154
+ /** Hard ceiling for listAll without an explicit maxTotal. Throws rather than silently truncating. */
155
+ maxTotalItems: number;
156
+ /** Maximum filter-tree recursion depth (_and/_or/_not/nested). Throws PlannerValidationError if exceeded. */
157
+ maxFilterDepth: number;
158
+ }
159
+
160
+ type UnpackedNode = {
161
+ space: string;
162
+ externalId: string;
163
+ } & Record<string, unknown>;
164
+
165
+ /** Properties registered once at client init and merged into every subsequent event. */
166
+ interface SdkTelemetryBaseProperties {
167
+ project?: string;
168
+ }
169
+ /** Typed map of every event name to its specific properties. */
170
+ interface SdkTelemetryEventMap {
171
+ 'Flows.SDK.ClientCreated': {
172
+ viewCount: number;
173
+ };
174
+ 'Flows.SDK.OperationExecuted': {
175
+ operationType: 'query' | 'search' | 'count' | 'aggregate' | 'retrieve';
176
+ viewExternalId: string;
177
+ success: boolean;
178
+ durationMs: number;
179
+ };
180
+ }
181
+ type SdkTelemetryEventName = keyof SdkTelemetryEventMap;
182
+ interface SdkTelemetry {
183
+ track<E extends SdkTelemetryEventName>(eventName: E, properties: SdkTelemetryEventMap[E]): void;
184
+ flush(timeoutMs?: number): Promise<void>;
185
+ /** Merge properties into every subsequent event (Mixpanel-style super properties). */
186
+ register(baseProperties: SdkTelemetryBaseProperties): void;
187
+ }
188
+
189
+ declare class QueryRunner {
190
+ private readonly dms;
191
+ private readonly schema;
192
+ private readonly config;
193
+ private readonly executor;
194
+ private readonly telemetry;
195
+ get schemaKnowledge(): SchemaKnowledge | undefined;
196
+ get maxFilterDepth(): number;
197
+ constructor(dms: DmsClient, schema?: SchemaKnowledge, config?: Partial<PlannerConfig>, telemetry?: SdkTelemetry);
198
+ private trackOperation;
199
+ private _queryPage;
200
+ query(input: QueryInput): Promise<ListResult<UnpackedNode>>;
201
+ /**
202
+ * Collects all pages until exhaustion. `input.limit` is the page size.
203
+ * `maxTotal` sets an explicit ceiling — without it, throws at `config.maxTotalItems`
204
+ * to prevent unbounded fetches.
205
+ */
206
+ queryAll(input: Omit<QueryInput, 'cursor'>, maxTotal?: number): Promise<UnpackedNode[]>;
207
+ /**
208
+ * Full-text or filter-based search returning a single (non-paginated) result set.
209
+ * Use for top-level discovery; DMS search has eventual consistency — do not use
210
+ * for writes-then-reads or where strong consistency is required.
211
+ */
212
+ search(input: SearchInput): Promise<ListResult<UnpackedNode>>;
213
+ /**
214
+ * Fetches specific nodes by space+externalId. Returns an empty array when ids is empty.
215
+ * Extracts view-scoped properties before returning, matching the shape of list results.
216
+ */
217
+ retrieve(ids: Array<{
218
+ space: string;
219
+ externalId: string;
220
+ }>, view: ViewReference): Promise<UnpackedNode[]>;
221
+ /**
222
+ * Returns the total count of instances matching the filter.
223
+ * Wraps the filter with hasData so only instances with data in the view are counted.
224
+ */
225
+ count(input: {
226
+ view: ViewReference;
227
+ filter?: LogicalFilter;
228
+ }): Promise<number>;
229
+ aggregate(input: AggregateInput): Promise<AggregateOutput>;
230
+ /**
231
+ * Async generator — yields one ListResult per page.
232
+ * Lets callers stream results or stop early without fetching remaining pages.
233
+ */
234
+ queryPages(input: Omit<QueryInput, 'cursor'>): AsyncGenerator<ListResult<UnpackedNode>>;
235
+ }
236
+
237
+ interface DuneRuntime {
238
+ schema: GraphQLSchema;
239
+ rootValue: Record<string, unknown>;
240
+ runner: QueryRunner;
241
+ /** Backs the generated SDK methods — executes each operation document in-process. */
242
+ requester: DuneRequester;
243
+ }
244
+ /**
245
+ * Builds the full runtime from a data model config. Fetches views from CDF,
246
+ * builds the GraphQL schema, wires resolvers, and returns a ready requester.
247
+ */
248
+ declare function createDuneRuntime(config: GenerateSdkConfig, client: CogniteClient, telemetry?: SdkTelemetry): Promise<DuneRuntime>;
249
+ /**
250
+ * Builds the runtime directly from an array of ViewDefinition objects — skips the
251
+ * data model lookup. Useful when you already have views from sdk.views.list().
252
+ */
253
+ declare function createDuneRuntimeFromViews(views: ViewDefinition[], client: CogniteClient, telemetry?: SdkTelemetry): DuneRuntime;
254
+
255
+ export { type DuneRequester, type DuneRuntime, type ViewDefinition, type ViewDefinitionProperty, createDuneRuntime, createDuneRuntimeFromViews };
@@ -0,0 +1 @@
1
+ import{a,b}from"../chunk-OIOJTLJU.js";import"../chunk-ATR2SGLU.js";export{a as createDuneRuntime,b as createDuneRuntimeFromViews};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cognite/cli",
3
- "version": "1.5.0",
3
+ "version": "1.6.0-alpha.sdk-gen",
4
4
  "description": "CLI for Cognite Data Fusion",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "author": "Cognite",
@@ -22,6 +22,11 @@
22
22
  "types": "./dist/deploy/index.d.ts",
23
23
  "import": "./dist/deploy/index.js",
24
24
  "default": "./dist/deploy/index.js"
25
+ },
26
+ "./sdk-runtime": {
27
+ "types": "./dist/sdk-runtime/index.d.ts",
28
+ "import": "./dist/sdk-runtime/index.js",
29
+ "default": "./dist/sdk-runtime/index.js"
25
30
  }
26
31
  },
27
32
  "bin": {
@@ -46,8 +51,14 @@
46
51
  "refresh-spec-kit": "bash scripts/refresh-spec-kit.sh"
47
52
  },
48
53
  "dependencies": {
49
- "@cognite/app-sdk": "^0.6.0",
50
- "@cognite/sdk": "^10.10.0",
54
+ "@cognite/app-sdk": "^0.7.0",
55
+ "@cognite/sdk": "^10.11.0",
56
+ "@graphql-codegen/add": "^7.0.1",
57
+ "@graphql-codegen/cli": "^7.0.0",
58
+ "@graphql-codegen/typescript": "^6.0.1",
59
+ "@graphql-codegen/typescript-document-nodes": "^6.0.1",
60
+ "@graphql-codegen/typescript-operations": "^6.0.2",
61
+ "@napi-rs/keyring": "^1.3.0",
51
62
  "@sentry/node": "^10.51.0",
52
63
  "@zip.js/zip.js": "^2.7.0",
53
64
  "chalk": "^5.6.2",
@@ -56,6 +67,7 @@
56
67
  "dotenv": "^17.4.2",
57
68
  "enquirer": "^2.4.1",
58
69
  "execa": "^5.1.1",
70
+ "graphql": "^16.14.0",
59
71
  "hygen": "^6.2.11",
60
72
  "jose": "^6.2.2",
61
73
  "mixpanel": "^0.21.0",
@@ -92,7 +104,7 @@
92
104
  "react-dom": "^19.2.6",
93
105
  "tsup": "^8.4.0",
94
106
  "typescript": "^5.0.0",
95
- "vitest": "4.1.7"
107
+ "vitest": "4.1.8"
96
108
  },
97
109
  "engines": {
98
110
  "node": ">=20"
@@ -1,13 +0,0 @@
1
- var ie=Object.defineProperty;var i=(n,e)=>ie(n,"name",{value:e,configurable:!0});import{mkdir as _e,readFile as Fe}from"fs/promises";import{basename as Oe,dirname as Le}from"path";var D=class D 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:ue(e.cause)}}};i(D,"HintedError");var w=D;var J="https://docs.cognite.com/cdf/access/",ae="https://status.cognite.com";function ce(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:J};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:J};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:ae};default:return{}}}i(ce,"defaultHintForStatus");var U=class U extends w{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=ce(t),o=super.deriveDefaults(e);return{hint:r.hint??o.hint,helpUrl:r.helpUrl}}};i(U,"HintedHttpError");var x=U;function pe(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}}i(pe,"hintForErrno");function ue(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,o=pe(r.code,r);if(o!==void 0)return o;e=r.cause}}i(ue,"hintForCause");var K="https://docs.cognite.com/cdf/access/";function d(n){return n!==null&&typeof n=="object"}i(d,"isRecord");function C(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}i(C,"isHttpError");function le(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
- See: ${K}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
3
- See: ${K}`;default:return}}i(le,"httpStatusHint");function y(n){let e=n instanceof Error?n:new Error(String(n));if(!C(e))return null;let t=le(e.status);return t?Object.assign(new Error(`${e.message}
4
- ${t}`),{cause:e}):null}i(y,"enrichedHttpError");function de(n){if(!d(n))return null;let e=n.missing;if(Array.isArray(e))return e;let t=n.data;if(d(t)){let r=t.error;if(d(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(t.missing))return t.missing}return null}i(de,"findMissingArray");function ge(n,e){if(!C(n)||n.status!==400)return!1;let t=de(n);return t?t.some(r=>d(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}i(ge,"isMissingExternalIdError");function N(n,e){return C(n)&&n.status===404||ge(n,e)}i(N,"isNotFoundError");var X=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Z=["ACTIVE","PREVIEW"],V=class V extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};i(V,"AppVersionNotFoundError");var b=V;function R(n,e){return n.includes(e)}i(R,"includesValue");function fe(n){return R(X,n)}i(fe,"isAppVersionLifecycleState");function he(n){return R(Z,n)}i(he,"isAppVersionAlias");function me(n){return typeof n.version=="string"&&fe(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||he(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}i(me,"isAppVersion");function W(n){if(!d(n))throw new Error("Invalid version response: not an object");if(!me(n))throw new Error("Invalid version response: missing or malformed fields");return n}i(W,"parseAppVersion");var _=class _{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(o){throw y(o)??o}}async uploadVersion(e,t,r,o,s="index.html"){console.log(`\u{1F4E4} Uploading version ${t}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),o),a.append("version",t),a.append("entryPath",s);let p=encodeURIComponent(e),c=`${this.appsBasePath}/${p}/versions`,u=await this.client.authenticate(),m=`${this.client.getBaseUrl()}${c}`,h=new AbortController,oe=setTimeout(()=>h.abort(),300*1e3),E;try{E=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${u}`},body:a,signal:h.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?new Error("Upload timed out after 5 minutes"):g}finally{clearTimeout(oe)}if(!E.ok){let g=await E.text(),S;try{S=JSON.parse(g)}catch{}let I=g;if(d(S)){let A=S.error;if(typeof A=="string")I=A;else if(d(A)){let k=A.message,z=A.code;I=typeof k=="string"?k:z!=null?`Unknown error (code: ${z})`:g}else{let k=S.message;I=typeof k=="string"?k:g}}let Y=E.headers.get("x-request-id"),se=Y?` | X-Request-ID: ${Y}`:"";throw new x(`Upload failed: ${E.status} \u2014 ${I}${se}`,{httpStatusCode:E.status,requestUrl:m,responseBody:d(S)?S:g})}console.log(`\u2705 Version ${t} uploaded`)}async getVersion(e,t){let r=encodeURIComponent(e),o=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${o}`;try{let a=await this.client.get(s);return W(a.data)}catch(a){throw N(a,[e,t])?new b(e,t):y(a)??a}}async getActiveVersion(e){let t=encodeURIComponent(e),r=`${this.appsBasePath}/${t}/active`;try{let o=await this.client.get(r);return W(o.data)}catch(o){if(N(o,[e]))return null;throw y(o)??o}}async updateVersions(e,t){let r=encodeURIComponent(e),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:t}})}catch(s){throw y(s)??s}}async submitSignatures(e,t,r){let o=encodeURIComponent(e),s=encodeURIComponent(t),a=`${this.appsBasePath}/${o}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(p){throw y(p)??p}}async listSignatures(e,t){let r=encodeURIComponent(e),o=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${o}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return Se(a.data)}catch(a){throw y(a)??a}}};i(_,"AppHostingApi");var T=_,ye=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Ee=["developer","certifier"];function Se(n){if(!d(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=we(t);return r?[r]:[]})}i(Se,"parseStoredSignatures");function we(n){if(!d(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:s,status:a}=n;return typeof e!="string"||e===""||!R(Ee,t)||typeof r!="number"||typeof o!="number"||typeof s!="number"||!R(ye,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:s,status:a}}i(we,"parseStoredSignature");var F=class F{constructor(e){this.api=new T(e)}getVersion(e,t){return this.api.getVersion(e,t)}uploadVersion(e,t,r,o,s){return this.api.uploadVersion(e,t,r,o,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(o){if(C(o)&&o.status===409){console.log(`\u2705 App '${e}' already exists`);return}throw o}}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 o=r&&r.version!==t?r.version:void 0;return await this.api.updateVersions(e,[{version:t,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(e,t,r,o,s,a,p=!1){console.log(`
5
- \u{1F680} Deploying application via App Hosting API...
6
- `);try{await this.ensureApp(e,t,r),await this.uploadVersion(e,o,s,a),p&&await this.publishAndActivate(e,o),console.log(`
7
- \u2705 Deployment successful!`)}catch(c){let u=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${u}`),{cause:c})}}};i(F,"AppHostingClient");var v=F;import{execFileSync as $}from"child_process";import f from"fs";import l from"path";import{parseAndValidateManifestConfig as Ae}from"@cognite/app-sdk/vite";import{BlobReader as ke,Uint8ArrayWriter as Ce,ZipWriter as ve}from"@zip.js/zip.js";var O="package.json",L="package-lock.json",Q="manifest.json",B=".cognite",Pe=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],H=class H{constructor(e="dist"){this.distPath=l.isAbsolute(e)?e:l.join(process.cwd(),e),this.appRoot=l.dirname(this.distPath)}validateBuildDirectory(){if(!f.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=l.join(this.appRoot,O);if(!f.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=l.join(this.appRoot,L);if(!f.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 ve(new Ce,{level:9}),o=i(async(c,u)=>{await r.add(u,new ke(await f.openAsBlob(c))),t&&console.log(` \u{1F4C4} ${u}`)},"addFile"),s=i(async c=>{let u=await f.promises.readdir(c,{withFileTypes:!0});for(let m of u){let h=l.join(c,m.name);m.isDirectory()?await s(h):await o(h,l.relative(this.distPath,h).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=l.join(this.appRoot,O);await o(c,l.posix.join(B,O));let u=l.join(this.appRoot,Q);if(f.existsSync(u)){let h=f.readFileSync(u,"utf-8");Ae(h,u),await o(u,l.posix.join(B,Q))}let m=l.join(this.appRoot,L);await o(m,l.posix.join(B,L)),a=await r.close()}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${u}`)}await f.promises.writeFile(e,a);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=$("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=$("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=r?r.replace(/\/$/,""):".",s=o==="."?"HEAD":`HEAD:${o}`;this.validateNoSensitiveFiles(t,s);try{$("git",["-C",t,"archive","--format=zip",`--output=${e}`,s])}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${u}`)}let p=(f.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${l.basename(e)} (${p} MB)`),e}validateNoSensitiveFiles(e,t){let r=$("git",["-C",e,"ls-tree","-r","--name-only",t],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
8
- `).filter(Boolean),o=i(a=>a.split("/").some(p=>Pe.some(c=>c.test(p))),"isSensitive"),s=r.filter(o);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
9
- `+s.map(a=>` ${a}`).join(`
10
- `)+`
11
- Hint: git rm --cached <file>`)}};i(H,"ApplicationPackager");var P=H;import Ie from"path";var ee=".cognite-bundles";function te(n,e){return`${n}-${e}.zip`}i(te,"bundleFileName");function j(n,e,t){return Ie.join(n,ee,te(e,t))}i(j,"bundlePath");import{CogniteClient as Ve}from"@cognite/sdk";function xe(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}i(xe,"exponentialBackoffWithJitter");function be(n){return new Promise(e=>setTimeout(e,n))}i(be,"sleep");async function M(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),o=e.delayInMsCalculator??xe;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=o(s);e.onAttemptFail?.(a,s,p),await be(p),s++}}i(M,"retryAsync");var Re=i(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let e=JSON.parse(n),t={};for(let[r,o]of Object.entries(e))if(typeof o=="string"){let s=r.toLowerCase().replace(/_/g,"-");t[s]=o}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),Te=i(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=Re()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return e},"getSecretFromEnv"),$e=i(n=>{if(!n)return"";try{return new URL(n).hostname.replace(/\.cognitedata\.com$/,"")}catch{let e=n.replace(/^https?:\/\//,"");return e=e.split("/")[0],e=e.split(":")[0],e=e.replace(/\.cognitedata\.com$/,""),e}},"extractClusterFromUrl"),De=i(async(n,e)=>{let t=`Basic ${btoa(`${n}:${e}`)}`,r="https://auth.cognite.com/oauth2/token",o={grant_type:"client_credentials"},s;try{s=await M(()=>fetch(r,{method:"POST",headers:{Authorization:t,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(o)}),{maxAttempts:3})}catch(p){throw new w(`Failed to fetch access token from ${r}`,{cause:p})}if(!s.ok){let p=await s.text();throw new Error(`Failed to get token from CDF: ${s.status} ${s.statusText}
12
- ${p}`)}let a=await s.json();if(!a.access_token)throw new Error("No access token returned from CDF authentication");return a.access_token},"getTokenCdf"),Ue=i((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");let t=$e(n);if(!t)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${n}`);return`https://${t}.cognitedata.com/.default`},"resolveEntraScope"),Ne=i(async(n,e,t,r,o)=>{let s=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,a=Ue(r,o),p;try{p=await M(()=>fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:e,grant_type:"client_credentials",...a?{scope:a}:{}})}),{maxAttempts:3})}catch(u){throw new w(`Failed to fetch access token from ${s}`,{cause:u})}if(!p.ok){let u=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
13
- ${u}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),q=i(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return e.COGNITE_TOKEN;let{deployClientId:t,deploySecretName:r,idpType:o="cdf",tenantId:s,baseUrl:a,scopes:p}=n,c=Te(r);if(o==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Ne(t,c,s,a,p)}return De(t,c)},"getToken");async function G(n,e,t=process.env,r){let o=await q(n,t),s=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(p=>new Ve(p)))({appId:e,project:n.project,baseUrl:s,oidcTokenProvider:i(async()=>o,"oidcTokenProvider")});return await a.authenticate(),a}i(G,"getSdk");async function ne(n,e,t,r){let{externalId:o,name:s,description:a,versionTag:p}=e,c=j(t,o,p);await _e(Le(c),{recursive:!0}),await new P(`${t}/dist`).createZip(c,!0);let u=await Fe(c);await new v(n).deploy(o,s,a,p,u,Oe(c),r)}i(ne,"packageAndUpload");var Be=i(async(n,e,t)=>{let r=await G(n,t);await ne(r,e,t,n.published)},"deploy");import{existsSync as He,readFileSync as je}from"fs";var re=[".dev.sig",".cert.sig"];function Me(n,e={}){let t=e.existsSync??He,r=e.readFileSync??((s,a)=>je(s,a)),o=[];for(let s of re){let a=`${n}${s}`;if(!t(a))continue;let p=r(a,"utf8").trim();p.length>0&&o.push(p)}return o}i(Me,"discoverSignatures");export{v as a,P as b,ee as c,te as d,j as e,q as f,G as g,ne as h,Be as i,re as j,Me as k};