@cognite/cli 1.5.1 → 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-MZWFUPT4.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-MZWFUPT4.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.1",
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 ae=Object.defineProperty;var i=(n,e)=>ae(n,"name",{value:e,configurable:!0});import{mkdir as Oe,readFile as Le}from"fs/promises";import{basename as He,dirname as Be}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:le(e.cause)}}};i(D,"HintedError");var l=D;var Y="https://docs.cognite.com/cdf/access/",ce="https://status.cognite.com";function pe(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:Y};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:Y};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:ce};default:return{}}}i(pe,"defaultHintForStatus");var U=class U extends l{constructor(e,t){super(e,t),this.name="HintedHttpError",this.httpStatusCode=t.httpStatusCode,this.requestUrl=t.requestUrl,this.responseBody=t.responseBody}deriveDefaults(e){let{httpStatusCode:t}=e,r=pe(t),o=super.deriveDefaults(e);return{hint:r.hint??o.hint,helpUrl:r.helpUrl}}};i(U,"HintedHttpError");var A=U;function ue(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(ue,"hintForErrno");function le(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,o=ue(r.code,r);if(o!==void 0)return o;e=r.cause}}i(le,"hintForCause");var z="https://docs.cognite.com/cdf/access/";function g(n){return n!==null&&typeof n=="object"}i(g,"isRecord");function v(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}i(v,"isHttpError");function de(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
- See: ${z}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
3
- See: ${z}`;default:return}}i(de,"httpStatusHint");function E(n){let e=n instanceof Error?n:new Error(String(n));if(!v(e))return null;let t=de(e.status);return t?Object.assign(new Error(`${e.message}
4
- ${t}`),{cause:e}):null}i(E,"enrichedHttpError");function ge(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}i(ge,"findMissingArray");function he(n,e){if(!v(n)||n.status!==400)return!1;let t=ge(n);return t?t.some(r=>g(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}i(he,"isMissingExternalIdError");function N(n,e){return v(n)&&n.status===404||he(n,e)}i(N,"isNotFoundError");var W=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],X=["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 T(n,e){return n.includes(e)}i(T,"includesValue");function fe(n){return T(W,n)}i(fe,"isAppVersionLifecycleState");function me(n){return T(X,n)}i(me,"isAppVersionAlias");function ye(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||me(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}i(ye,"isAppVersion");function K(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(!ye(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}i(K,"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 E(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(),h=`${this.client.getBaseUrl()}${c}`,y=new AbortController,se=setTimeout(()=>y.abort(),300*1e3),S;try{S=await fetch(h,{method:"POST",headers:{Authorization:`Bearer ${u}`},body:a,signal:y.signal})}catch(f){throw f instanceof Error&&f.name==="AbortError"?new l("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new l(`Failed to upload version to ${h}`,{cause:f,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(se)}if(!S.ok){let f=await S.text(),w;try{w=JSON.parse(f)}catch{}let x=f;if(g(w)){let k=w.error;if(typeof k=="string")x=k;else if(g(k)){let C=k.message,J=k.code;x=typeof C=="string"?C:J!=null?`Unknown error (code: ${J})`:f}else{let C=w.message;x=typeof C=="string"?C:f}}let G=S.headers.get("x-request-id"),ie=G?` | X-Request-ID: ${G}`:"";throw new A(`Upload failed: ${S.status} \u2014 ${x}${ie}`,{httpStatusCode:S.status,requestUrl:h,responseBody:g(w)?w:f})}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 K(a.data)}catch(a){throw N(a,[e,t])?new b(e,t):E(a)??a}}async getActiveVersion(e){let t=encodeURIComponent(e),r=`${this.appsBasePath}/${t}/versions/list`;try{let o=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!g(o.data)||!Array.isArray(o.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=o.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 K(s[0])}catch(o){if(N(o,[e]))return null;throw E(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 E(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 E(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 we(a.data)}catch(a){throw E(a)??a}}};i(_,"AppHostingApi");var R=_,Ee=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Se=["developer","certifier"];function we(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=Ae(t);return r?[r]:[]})}i(we,"parseStoredSignatures");function Ae(n){if(!g(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:s,status:a}=n;return typeof e!="string"||e===""||!T(Se,t)||typeof r!="number"||typeof o!="number"||typeof s!="number"||!T(Ee,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:s,status:a}}i(Ae,"parseStoredSignature");var F=class F{constructor(e){this.api=new R(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(v(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
- `),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!`)}};i(F,"AppHostingClient");var I=F;import{execFileSync as $}from"child_process";import m from"fs";import d from"path";import{parseAndValidateManifestConfig as ke}from"@cognite/app-sdk/vite";import{BlobReader as Ce,Uint8ArrayWriter as ve,ZipWriter as Ie}from"@zip.js/zip.js";var O="package.json",L="package-lock.json",Z="manifest.json",H=".cognite",Pe=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],B=class B{constructor(e="dist"){this.distPath=d.isAbsolute(e)?e:d.join(process.cwd(),e),this.appRoot=d.dirname(this.distPath)}validateBuildDirectory(){if(!m.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=d.join(this.appRoot,O);if(!m.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=d.join(this.appRoot,L);if(!m.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 Ie(new ve,{level:9}),o=i(async(c,u)=>{await r.add(u,new Ce(await m.openAsBlob(c))),t&&console.log(` \u{1F4C4} ${u}`)},"addFile"),s=i(async c=>{let u=await m.promises.readdir(c,{withFileTypes:!0});for(let h of u){let y=d.join(c,h.name);h.isDirectory()?await s(y):await o(y,d.relative(this.distPath,y).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=d.join(this.appRoot,O);await o(c,d.posix.join(H,O));let u=d.join(this.appRoot,Z);if(m.existsSync(u)){let y=m.readFileSync(u,"utf-8");ke(y,u),await o(u,d.posix.join(H,Z))}let h=d.join(this.appRoot,L);await o(h,d.posix.join(H,L)),a=await r.close()}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${u}`)}try{await m.promises.writeFile(e,a)}catch(c){throw new l(`Failed to write bundle to ${e}`,{cause:c})}let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${p} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=$("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=(m.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${d.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(B,"ApplicationPackager");var P=B;import xe from"path";var Q=".cognite-bundles";function ee(n,e){return`${n}-${e}.zip`}i(ee,"bundleFileName");function j(n,e,t){return xe.join(n,Q,ee(e,t))}i(j,"bundlePath");import{CogniteClient as Fe}from"@cognite/sdk";function be(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}i(be,"exponentialBackoffWithJitter");function Te(n){return new Promise(e=>setTimeout(e,n))}i(Te,"sleep");async function te(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),o=e.delayInMsCalculator??be;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 Te(p),s++}}i(te,"retryAsync");var Re=i(n=>typeof n=="object"&&n!==null&&"access_token"in n&&typeof n.access_token=="string","hasAccessToken");async function ne({idp:n,tokenUrl:e,init:t,missingTokenHint:r}){let o;try{o=await te(()=>fetch(e,t),{maxAttempts:3})}catch(p){throw new l(`Failed to fetch access token from ${e}`,{cause:p})}if(!o.ok){let p=await o.text();throw new A(`Failed to get token from ${n}: ${o.status} ${o.statusText}`,{httpStatusCode:o.status,requestUrl:e,responseBody:p})}let s=await o.text(),a;try{a=JSON.parse(s)}catch{throw new l(`Unexpected response from ${n} authentication (invalid JSON):
12
- ${s}`,{hint:r})}if(!Re(a))throw new l(`No access token in ${n} authentication response:
13
- ${s}`,{hint:r});return a.access_token}i(ne,"fetchOAuthToken");var $e=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"),De=i(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=$e()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return e},"getSecretFromEnv"),Ue=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"),Ne=i((n,e)=>ne({idp:"CDF",tokenUrl:"https://auth.cognite.com/oauth2/token",init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${n}:${e}`)}`,"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"),Ve=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=Ue(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"),_e=i((n,e,t,r,o)=>{let s=Ve(r,o);return ne({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:e,grant_type:"client_credentials",...s?{scope:s}:{}})},missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."})},"getTokenEntra"),M=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=De(r);if(o==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return _e(t,c,s,a,p)}return Ne(t,c)},"getToken");async function q(n,e,t=process.env,r){let o=await M(n,t),s=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(p=>new Fe(p)))({appId:e,project:n.project,baseUrl:s,oidcTokenProvider:i(async()=>o,"oidcTokenProvider")});return await a.authenticate(),a}i(q,"getSdk");async function re(n,e,t,r){let{externalId:o,name:s,description:a,versionTag:p}=e,c=j(t,o,p);await Oe(Be(c),{recursive:!0}),await new P(`${t}/dist`).createZip(c,!0);let u;try{u=await Le(c)}catch(h){throw new l(`Failed to read bundle file: ${c}`,{cause:h})}await new I(n).deploy(o,s,a,p,u,He(c),r)}i(re,"packageAndUpload");var je=i(async(n,e,t)=>{let r=await q(n,t);await re(r,e,t,n.published)},"deploy");import{existsSync as Me,readFileSync as qe}from"fs";var oe=[".dev.sig",".cert.sig"];function Ge(n,e={}){let t=e.existsSync??Me,r=e.readFileSync??((s,a)=>qe(s,a)),o=[];for(let s of oe){let a=`${n}${s}`;if(!t(a))continue;let p=r(a,"utf8").trim();p.length>0&&o.push(p)}return o}i(Ge,"discoverSignatures");export{I as a,P as b,Q as c,ee as d,j as e,M as f,q as g,re as h,je as i,oe as j,Ge as k};