@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.
package/README.md CHANGED
@@ -31,6 +31,26 @@ pnpm deploy
31
31
  ```
32
32
 
33
33
  Deployment targets are configured in `app.json` at the project root.
34
+ Set `idpType` to `"oauth"` and provide a `tokenUrl` to use a generic OAuth
35
+ client credentials flow for non-interactive deploys:
36
+
37
+ ```json
38
+ {
39
+ "deployments": [
40
+ {
41
+ "baseUrl": "https://api.cognitedata.com",
42
+ "idpType": "oauth",
43
+ "deployClientId": "client-id",
44
+ "deploySecretName": "MY_CLIENT_SECRET",
45
+ "scopes": ["https://api.cognitedata.com/.default"],
46
+ "tokenUrl": "https://idp.example.com/oauth/token"
47
+ }
48
+ ]
49
+ }
50
+ ```
51
+
52
+ The CLI posts `client_id`, `client_secret`, `grant_type=client_credentials`,
53
+ and optional `scopes` to `tokenUrl`.
34
54
 
35
55
  ## AI skills
36
56
 
@@ -2,4 +2,4 @@
2
2
  to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>.npmrc'
3
3
  ---
4
4
  engine-strict=true
5
- min-release-age=1
5
+ min-release-age=0
@@ -10,7 +10,6 @@ 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.
14
13
  <% } else { -%>
15
14
  ## 0. Product Spec (SPEC.md)
16
15
 
@@ -22,13 +21,62 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
22
21
 
23
22
  ---
24
23
 
25
- ## 1. UI Components
24
+ ## 1. CDF Data & Generated SDK
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
26
74
 
27
75
  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.
28
76
 
29
77
  ---
30
78
 
31
- ## 2. Host integration (`@cognite/app-sdk`)
79
+ ## 3. Host integration (`@cognite/app-sdk`)
32
80
 
33
81
  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.
34
82
 
@@ -75,7 +123,7 @@ async function updateState(next: AppState, api: HostAppAPI) {
75
123
 
76
124
  ---
77
125
 
78
- ## 3. Dependency Injection
126
+ ## 4. Dependency Injection
79
127
 
80
128
  **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.
81
129
 
@@ -109,7 +157,7 @@ export const doWork = async (props: Props, overrides?: Partial<Deps>) => {
109
157
 
110
158
  ---
111
159
 
112
- ## 4. Interface-Based Services
160
+ ## 5. Interface-Based Services
113
161
 
114
162
  Define an interface; implement with a class. Never reference the concrete class outside its own file.
115
163
 
@@ -126,7 +174,7 @@ export class ApiDataService implements DataService {
126
174
 
127
175
  ---
128
176
 
129
- ## 5. ViewModel Pattern
177
+ ## 6. ViewModel Pattern
130
178
 
131
179
  Business logic lives in `use<Name>ViewModel`. Components only render.
132
180
 
@@ -162,11 +210,11 @@ This matters because each call to a `useState`-backed hook creates an **independ
162
210
 
163
211
  ### Host-synced state inside a ViewModel
164
212
 
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.
213
+ When a ViewModel exposes state that falls under §3's "host-synced" category, the **ViewModel** — not the view component — is responsible for seeding from `initialState` and pushing changes via `syncInternalState`. The state itself still lives in the shared storage layer described above; the ViewModel just owns the read/write contract with the host.
166
214
 
167
215
  ---
168
216
 
169
- ## 6. Test-First Development
217
+ ## 7. Test-First Development
170
218
 
171
219
  Write tests before implementation for all non-trivial behavior changes.
172
220
 
@@ -262,7 +310,7 @@ Place reusable factories in `src/__mocks__/`. Use `.test` TLD for fake URLs (RFC
262
310
 
263
311
  ---
264
312
 
265
- ## 7. TypeScript Rules
313
+ ## 8. TypeScript Rules
266
314
 
267
315
  - Never use `any`; prefer `unknown` or explicit strong types
268
316
  - Never use `as` casts — they silence the compiler without providing safety. Use type guards instead.
@@ -289,14 +337,14 @@ const mock = { postMessage: vi.fn() } as Partial<Window> as Window;
289
337
 
290
338
  ---
291
339
 
292
- ## 8. CogniteClient / authentication
340
+ ## 9. CogniteClient / authentication
293
341
 
294
342
  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.
295
343
 
296
344
  ---
297
345
 
298
346
 
299
- ## 9. Commits and pull requests
347
+ ## 10. Commits and pull requests
300
348
 
301
349
  Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/).
302
350
 
@@ -307,4 +355,4 @@ Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/
307
355
  - **Pull requests:** title and **Summary** should match the same vocabulary; do not replace conventional commits with only a PR headline.
308
356
  - Before committing: review **`git status`** and **`git diff`** (including staged); unstage and commit separately if the index mixes unrelated concerns.
309
357
 
310
- ---
358
+ ---
@@ -51,27 +51,29 @@ to: '<%= useSpecKit ? null : (useCurrentDir ? "" : ((directoryName || name) + "/
51
51
 
52
52
  ---
53
53
 
54
- ## Data Models & CDF Integration *(mandatory)*
54
+ ## CDF Data *(mandatory)*
55
55
 
56
56
  <!--
57
- Capture how this app integrates with Cognite Data Fusion data models.
58
- Every Flows app should fill this in.
59
- -->
57
+ Which data model does this app connect to? If you haven't already, generate a
58
+ typed SDK by running from the app root:
60
59
 
61
- ### Existing views
60
+ npx @cognite/cli@<%= cliVersion %> apps sdk --interactive
62
61
 
63
- <!--
64
- CDF views this app reads from. Format: `<space>.<view>:<version>`.
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."
65
67
  -->
66
68
 
67
- ### New views
69
+ ### Data model
68
70
 
69
- <!--
70
- Views this app needs that don't yet exist. Describe properties and relationships.
71
- -->
71
+ <!-- Which data model: name, space, version. -->
72
72
 
73
- ### Spaces
73
+ ### What this app reads
74
74
 
75
- <!--
76
- CDF spaces this app uses, and what each contains.
77
- -->
75
+ <!-- Plain-language description of the data this feature needs and any key filters. -->
76
+
77
+ ### Writes
78
+
79
+ <!-- Does this feature write back to CDF? If so, what and under what conditions? If read-only, note that here. -->
@@ -7,6 +7,7 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>app.json'
7
7
  "externalId": "<%= name %>",
8
8
  "versionTag": "0.0.1",
9
9
  "infra": "appsApi",
10
+ "sdk-gen-alpha-version": "<%= cliVersion %>",
10
11
  "deployments": [
11
12
  {
12
13
  "org": "<%= org %>",
@@ -4,6 +4,11 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>manifest.json'
4
4
  {
5
5
  "manifestVersion": 1,
6
6
  "permissions": {
7
- "network": []
7
+ "network": [
8
+ {
9
+ "sources": ["https://api.mixpanel.com"],
10
+ "directives": ["connect-src"]
11
+ }
12
+ ]
8
13
  }
9
14
  }
@@ -28,10 +28,13 @@ 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/cli": "<%= cliVersion %>",
31
32
  "@cognite/app-sdk": "^0.6.0",
32
33
  "@tabler/icons-react": "^3.35.0",
33
34
  "@tanstack/react-query": "^5.90.10",
34
35
  "clsx": "^2.1.1",
36
+ "graphql": "^16.14.0",
37
+ "graphql-tag": "^2.12.6",
35
38
  "react": "^18.3.1",
36
39
  "react-dom": "^18.3.1",
37
40
  "tailwind-merge": "^3.4.0"
@@ -0,0 +1 @@
1
+ var g=Object.defineProperty;var e=a=>{throw TypeError(a)};var h=(a,b)=>g(a,"name",{value:b,configurable:!0});var f=(a,b,c)=>b.has(a)||e("Cannot "+c);var i=(a,b,c)=>(f(a,b,"read from private field"),c?c.call(a):b.get(a)),j=(a,b,c)=>b.has(a)?e("Cannot add the same private member more than once"):b instanceof WeakSet?b.add(a):b.set(a,c),k=(a,b,c,d)=>(f(a,b,"write to private field"),d?d.call(a,c):b.set(a,c),c);export{h as a,i as b,j as c,k as d};
@@ -0,0 +1,12 @@
1
+ import{a as o,b as ee,c as te,d as ne}from"./chunk-ATR2SGLU.js";import{mkdir as Qe,readFile as et}from"fs/promises";import{basename as tt,dirname as nt}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:ve(e.cause)}}};o(F,"HintedError");var d=F;var re="https://docs.cognite.com/cdf/access/",Se="https://status.cognite.com";function Ae(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:re};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:re};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:Se};default:return{}}}o(Ae,"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=Ae(t),i=super.deriveDefaults(e);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};o(_,"HintedHttpError");var v=_;function we(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(we,"hintForErrno");function ve(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,i=we(r.code,r);if(i!==void 0)return i;e=r.cause}}o(ve,"hintForCause");import{inspect as ke}from"util";var L="[REDACTED]",x,R=class R{constructor(e){te(this,x);ne(this,x,e)}toString(){return L}toJSON(){return L}[ke.custom](){return L}expose(){return ee(this,x)}static from(e){return new R(e)}};x=new WeakMap,o(R,"SensitiveString");var S=R;var ie="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 Ce(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
+ See: ${ie}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
3
+ See: ${ie}`;default:return}}o(Ce,"httpStatusHint");function m(n){let e=n instanceof Error?n:new Error(String(n));if(!I(e))return null;let t=Ce(e.status);return t?Object.assign(new Error(`${e.message}
4
+ ${t}`),{cause:e}):null}o(m,"enrichedHttpError");function xe(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(xe,"findMissingArray");function Ie(n,e){if(!I(n)||n.status!==400)return!1;let t=xe(n);return t?t.some(r=>g(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}o(Ie,"isMissingExternalIdError");function D(n,e){return I(n)&&n.status===404||Ie(n,e)}o(D,"isNotFoundError");var se=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],ae=["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 Pe(n){return N(se,n)}o(Pe,"isAppVersionLifecycleState");function Te(n){return N(ae,n)}o(Te,"isAppVersionAlias");function be(n){return typeof n.version=="string"&&Pe(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||Te(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}o(be,"isAppVersion");function oe(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(!be(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}o(oe,"parseAppVersion");function Re(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(Re,"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 Re(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,me=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(me)}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"),ye=Z?` | X-Request-ID: ${Z}`:"",Ee=g(w)?w:h;throw new v(`Upload failed: ${A.status} \u2014 ${b}${ye}`,{httpStatusCode:A.status,requestUrl:f,responseBody:Ee})}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 oe(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 oe(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 Ue(a.data)}catch(a){throw m(a)??a}}};o(M,"AppHostingApi");var V=M,De=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],$e=["developer","certifier"];function Ue(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=Ne(t);return r?[r]:[]})}o(Ue,"parseStoredSignatures");function Ne(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($e,t)||typeof r!="number"||typeof i!="number"||typeof s!="number"||!N(De,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:s,status:a}}o(Ne,"parseStoredSignature");function Ve(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(Ve,"diffAppMetadata");function Oe(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(Oe,"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=Ve(i,{name:t,description:r});if(s.length!==0)throw new d(Oe(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
+ \u{1F680} Deploying application via App Hosting API...
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 Fe}from"@cognite/app-sdk/vite";import{BlobReader as _e,Uint8ArrayWriter as Le,ZipWriter as He}from"@zip.js/zip.js";var q="package.json",J="package-lock.json",pe="manifest.json",G=".cognite",Be=[/^\.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 He(new Le,{level:9}),i=o(async(p,u)=>{await r.add(u,new _e(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,pe);if(y.existsSync(u)){let f=y.readFileSync(u,"utf-8");Fe(f,u),await i(u,l.posix.join(G,pe))}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=>Be.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
+ `+s.map(a=>` ${a}`).join(`
11
+ `)+`
12
+ Hint: git rm --cached <file>`)}};o(Y,"ApplicationPackager");var T=Y;import Me from"path";var ce=".cognite-bundles";function ue(n,e){return`${n}-${e}.zip`}o(ue,"bundleFileName");function z(n,e,t){return Me.join(n,ce,ue(e,t))}o(z,"bundlePath");import{CogniteClient as Ze}from"@cognite/sdk";function je(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}o(je,"exponentialBackoffWithJitter");function qe(n){return new Promise(e=>setTimeout(e,n))}o(qe,"sleep");async function de(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),i=e.delayInMsCalculator??je;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 qe(c),s++}}o(de,"retryAsync");var Je="https://auth.cognite.com/oauth2/token",Ge=o(n=>typeof n=="object"&&n!==null&&"access_token"in n&&typeof n.access_token=="string","hasAccessToken");async function le({idp:n,tokenUrl:e,init:t,missingTokenHint:r}){let i;try{i=await de(()=>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(!Ge(a))throw new d(`No access token in ${n} authentication response`,{hint:r});return S.from(a.access_token)}o(le,"fetchOAuthToken");var Ye=o(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let e=JSON.parse(n),t={};for(let[r,i]of Object.entries(e))if(typeof i=="string"){let s=r.toLowerCase().replace(/_/g,"-");t[s]=i}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),ze=o(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=Ye()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return S.from(e)},"getSecretFromEnv"),Ke=o((n,e)=>{let t=e.expose();return le({idp:"CDF",tokenUrl:Je,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"),ge=o(({idp:n,tokenUrl:e,clientId:t,clientSecret:r,scopes:i,missingTokenHint:s})=>le({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"),We=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"),Xe=o((n,e,t,r,i)=>ge({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,clientId:n,clientSecret:e.expose(),scopes:i!==void 0?i:[We(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=ze(r);if(i==="oauth"){if(!p)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return ge({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 Xe(t,u,s,a,c)}return Ke(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 Ze(c)))({appId:e,project:n.project,baseUrl:s,oidcTokenProvider:o(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}o(W,"getSdk");async function fe(n,e,t,r){let{externalId:i,name:s,description:a,versionTag:c}=e,p=z(t,i,c);await Qe(nt(p),{recursive:!0}),await new T(`${t}/dist`).createZip(p,!0);let u;try{u=await et(p)}catch(E){throw new d(`Failed to read bundle file: ${p}`,{cause:E})}await new P(n).deploy(i,s,a,c,u,tt(p),r)}o(fe,"packageAndUpload");var rt=o(async(n,e,t)=>{let r=await W(n,t);await fe(r,e,t,n.published)},"deploy");import{existsSync as it,readFileSync as ot}from"fs";var he=[".dev.sig",".cert.sig"];function st(n,e={}){let t=e.existsSync??it,r=e.readFileSync??((s,a)=>ot(s,a)),i=[];for(let s of he){let a=`${n}${s}`;if(!t(a))continue;let c=r(a,"utf8").trim();c.length>0&&i.push(c)}return i}o(st,"discoverSignatures");export{P as a,T as b,ce as c,ue as d,z as e,K as f,W as g,fe as h,rt as i,he as j,st as k};
@@ -0,0 +1 @@
1
+ import{a as o}from"./chunk-ATR2SGLU.js";import{GraphQLSchema as nr,GraphQLObjectType as ir,GraphQLNonNull as I,GraphQLList as P,GraphQLString as b,GraphQLInt as or,GraphQLInputObjectType as ot,printSchema as sr}from"graphql";function U(e){return{space:e.space,externalId:e.externalId,version:e.version}}o(U,"toSharedViewId");function Tt(e){switch(e){case"text":return"String";case"boolean":return"Boolean";case"int32":case"int64":return"Int";case"float32":case"float64":return"Float";case"timestamp":return"DateTime";case"date":return"Date";case"json":return"JSON";case"timeseries":return"CogniteTimeSeriesReference";case"file":return"CogniteFileReference";case"sequence":return"CogniteSequenceReference";case"enum":return"String";default:return"String"}}o(Tt,"dmsTypeToGraphQL");function Qe(e){if(!("source"in e)){if(e.type?.type==="direct")return e.type.list?e.type.source?{kind:"directRelationList",targetView:U(e.type.source)}:{kind:"scalar",isList:!1,graphqlType:"JSON"}:e.type.source?{kind:"directRelation",targetView:U(e.type.source)}:{kind:"scalar",isList:!1,graphqlType:"JSON"};if(e.type?.type==="enum"){let t=e.type,r={};if(typeof t=="object"&&t!==null&&"values"in t){let i=t.values;if(typeof i=="object"&&i!==null)for(let[n,a]of Object.entries(i))r[n]={name:typeof a=="object"&&a!==null&&"name"in a?String(a.name):void 0}}return{kind:"enum",values:Object.keys(r),valueNames:Object.fromEntries(Object.entries(r).map(([i,n])=>[i,n.name??i]))}}return{kind:"scalar",isList:e.type!==void 0&&"list"in e.type&&e.type.list===!0,graphqlType:e.type?.type?Tt(e.type.type):"String"}}if("through"in e)return{kind:e.connectionType==="single_reverse_direct_relation"?"reverseDirect":"reverseList",sourceView:U(e.source),throughProperty:e.through.identifier};if(e.connectionType==="single_edge_connection"||e.connectionType==="multi_edge_connection"){let t=e.direction==="inwards"?"inwards":"outwards";return{kind:"edge",targetView:U(e.source),direction:t}}return{kind:"scalar"}}o(Qe,"parsePropertyDescriptor");var _e=new Set(["String","Boolean","Int","Float","DateTime","Date"]);var kt=new Set(["String","Int","Float","DateTime","Date"]);function Me(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:_e.has(e.graphqlType??"String")}o(Me,"isFilterableDescriptor");function Oe(e){return e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:_e.has(e.graphqlType??"String")}o(Oe,"isSortableDescriptor");function qe(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind==="scalar"&&e.isList!==!0&&kt.has(e.graphqlType??"")}o(qe,"hasInOpDescriptor");function Ge(e){return e.kind==="scalar"&&e.isList===!0}o(Ge,"hasListOpsDescriptor");function $e(e,t,r){let i=e.property(t,r);return i?i.kind==="directRelation"?!1:i.kind==="directRelationList"?!0:i.kind==="scalar"&&i.graphqlType==="JSON":!0}o($e,"isListThroughProperty");function F(e){return e.usedFor!=="edge"}o(F,"isNodeOrAll");function z(e){return{query:`query${e}`,getById:`get${e}ById`,count:`count${e}`,search:`search${e}`,aggregate:`aggregate${e}`}}o(z,"viewOperationNames");function Be(e){let t=new Set;return e.filter(r=>t.has(r.externalId)?!1:(t.add(r.externalId),!0))}o(Be,"dedupeByExternalId");function k(e){return Object.entries(e.properties).map(([t,r])=>[t,Qe(r),r.description])}o(k,"parsedProperties");import{GraphQLObjectType as je,GraphQLNonNull as Q,GraphQLString as me,GraphQLFloat as Y,GraphQLList as Nt,GraphQLEnumType as At}from"graphql";import{GraphQLScalarType as L,Kind as S}from"graphql";function H(e){switch(e.kind){case S.STRING:case S.BOOLEAN:return e.value;case S.INT:return parseInt(e.value,10);case S.FLOAT:return parseFloat(e.value);case S.OBJECT:{let t={};for(let r of e.fields)t[r.name.value]=H(r.value);return t}case S.LIST:return e.values.map(H);case S.NULL:return null;default:return null}}o(H,"parseLiteralJSON");var Lt=new L({name:"DateTime",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===S.STRING?e.value:null,"parseLiteral")}),Dt=new L({name:"Date",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===S.STRING?e.value:null,"parseLiteral")}),fe=new L({name:"JSON",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:H}),vt=new L({name:"CogniteTimeSeriesReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===S.STRING?e.value:null,"parseLiteral")}),Et=new L({name:"CogniteFileReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===S.STRING?e.value:null,"parseLiteral")}),bt=new L({name:"CogniteSequenceReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===S.STRING?e.value:null,"parseLiteral")}),X=new L({name:"ListLimit",description:"Limit for list/search queries (1\u20131000).",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===S.INT?parseInt(e.value,10):null,"parseLiteral")}),Ct=new L({name:"DirectRelationList",description:"A list of direct-relation node references ({ space, externalId }).",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:H}),D={DateTime:Lt,Date:Dt,JSON:fe,CogniteTimeSeriesReference:vt,CogniteFileReference:Et,CogniteSequenceReference:bt,ListLimit:X,DirectRelationList:Ct};var Pt=new At({name:"AggregateFunction",values:{count:{value:"count"},avg:{value:"avg"},sum:{value:"sum"},min:{value:"min"},max:{value:"max"},histogram:{value:"histogram"}}}),Ke={function:{type:new Q(Pt)},property:{type:me},interval:{type:Y}},Vt=new je({name:"HistogramBucket",fields:{start:{type:new Q(Y)},count:{type:new Q(Y)}}}),Ue=new je({name:"AggregateResult",fields:{aggregate:{type:new Q(me)},property:{type:me},value:{type:Y},buckets:{type:new Nt(new Q(Vt))},group:{type:fe}}});import{GraphQLObjectType as ye,GraphQLNonNull as C,GraphQLList as Ft,GraphQLString as ge,GraphQLBoolean as Qt}from"graphql";var _t=new ye({name:"PageInfo",fields:{endCursor:{type:ge},hasNextPage:{type:new C(Qt)}}}),J=new ye({name:"NodeReference",fields:{space:{type:new C(ge)},externalId:{type:new C(ge)}}});function W(e,t){return new ye({name:`${e}Connection`,fields:{items:{type:new C(new Ft(new C(t)))},pageInfo:{type:new C(_t)}}})}o(W,"makeConnectionType");import{GraphQLInputObjectType as N,GraphQLList as R,GraphQLNonNull as We,GraphQLString as E,GraphQLBoolean as x,GraphQLFloat as jt,GraphQLInt as Kt}from"graphql";import{GraphQLObjectType as Mt,GraphQLNonNull as ze,GraphQLList as Ot,GraphQLString as Z,GraphQLBoolean as qt,GraphQLInt as Xe,GraphQLFloat as Gt,GraphQLEnumType as $t}from"graphql";function He(e){return e==="String"?Z:e==="Boolean"?qt:e==="Int"?Xe:e==="Float"?Gt:D[e]??Z}o(He,"scalarForName");function Ye(e){return{typeRegistry:new Map,connectionRegistry:new Map,viewsByExtId:new Map(e.map(t=>[t.externalId,t])),enumRegistry:new Map,enumFilterRegistry:new Map}}o(Ye,"createTypeContext");function Bt(e){let t=e.replace(/[^_A-Za-z0-9]/g,"_");return/^[0-9]/.test(t)&&(t=`_${t}`),t||"_UNKNOWN"}o(Bt,"sanitizeEnumValue");function he(e,t,r,i){let n=r.enumRegistry.get(e);if(n)return n;let a=new $t({name:e,values:Object.fromEntries(t.map(s=>[Bt(s),{value:s,description:i?.[s]}]))});return r.enumRegistry.set(e,a),a}o(he,"getOrCreateEnumType");function Je(e,t){return new Mt({name:e.externalId,description:e.description??e.name,fields:o(()=>{let r={space:{type:new ze(Z)},externalId:{type:new ze(Z)}};for(let[i,n,a]of k(e))if(n.kind==="scalar")n.isList?r[i]={type:new Ot(He(n.graphqlType??"String")),description:a}:r[i]={type:He(n.graphqlType??"String"),description:a};else if(n.kind==="enum"){let s=`${e.externalId}${i.charAt(0).toUpperCase()}${i.slice(1)}`;r[i]={type:he(s,n.values,t,n.valueNames),description:a}}else if(n.kind==="directRelation"){let s=t.typeRegistry.get(n.targetView.externalId)??J;r[i]={type:s,description:a}}else if(n.kind==="directRelationList")r[i]={type:D.DirectRelationList,description:a};else if(n.kind==="reverseList"||n.kind==="edge"){let s=n.kind==="reverseList"?n.sourceView.externalId:n.targetView.externalId,p=t.typeRegistry.get(s)??J,u=t.connectionRegistry.get(s);u||(u=W(s,p),t.connectionRegistry.set(s,u)),r[i]={type:u,description:a,args:{limit:{type:Xe}}}}else if(n.kind==="reverseDirect"){let s=t.typeRegistry.get(n.sourceView.externalId)??J;r[i]={type:s,description:a}}return r},"fields")})}o(Je,"generateViewObjectType");function A(e,t,r){let i={isNull:{type:x},exists:{type:x},eq:{type:t}};return r.hasIn&&(i.in={type:new R(t)}),r.hasPrefix&&(i.prefix={type:E}),r.hasRange&&(i.gte={type:t},i.gt={type:t},i.lte={type:t},i.lt={type:t}),r.hasListOps&&(i.containsAny={type:new R(t)},i.containsAll={type:new R(t)},i.overlaps={type:new R(t)}),new N({name:e,fields:i})}o(A,"makeScalarFilter");var we=A("StringFilter",E,{hasIn:!0,hasPrefix:!0}),Ut=A("BooleanFilter",x,{}),zt=A("IntFilter",Kt,{hasIn:!0,hasRange:!0}),Ht=A("FloatFilter",jt,{hasIn:!0,hasRange:!0}),Xt=A("DateTimeFilter",D.DateTime,{hasIn:!0,hasRange:!0}),Yt=A("DateFilter",D.Date,{hasIn:!0,hasRange:!0}),Jt=new N({name:"StringListFilter",fields:{isNull:{type:x},exists:{type:x},containsAny:{type:new R(E)},containsAll:{type:new R(E)},overlaps:{type:new R(E)}}}),_=new N({name:"DirectRelationRef",fields:{space:{type:new We(E)},externalId:{type:new We(E)}}}),Wt=new N({name:"DirectRelationFilter",fields:{isNull:{type:x},exists:{type:x},eq:{type:_},in:{type:new R(_)}}});function Zt(e){switch(e){case"String":return we;case"Boolean":return Ut;case"Int":return zt;case"Float":return Ht;case"DateTime":return Xt;case"Date":return Yt;default:return we}}o(Zt,"scalarFilterForName");var Ze=["space","externalId"];function et(e,t,r){let i=t.get(e.externalId),n={};for(let s of Ze)n[s]={type:we};let a=new Set(Ze);for(let[s,p]of k(e)){if(a.has(s))continue;let u=Me(p),c=Ge(p);if(!(!u&&!c))if(p.kind==="directRelation"){let f={isNull:{type:x},exists:{type:x},eq:{type:_},in:{type:new R(_)}};qe(p)&&(f.in={type:new R(_)});let l=t.get(p.targetView.externalId);l&&(f.nested={type:l}),n[s]=l?{type:new N({name:`_${e.externalId}_${s}_Filter`,fields:f})}:{type:Wt}}else if(p.kind==="enum"){let f=`${e.externalId}${s.charAt(0).toUpperCase()}${s.slice(1)}`,l=he(f,p.values,r),d=r.enumFilterRegistry.get(f);d||(d=new N({name:`${f}Filter`,fields:{isNull:{type:x},exists:{type:x},eq:{type:l},in:{type:new R(l)}}}),r.enumFilterRegistry.set(f,d)),n[s]={type:d}}else if(c)n[s]={type:Jt};else{let f=p.kind==="scalar"?p.graphqlType??"String":"String",l=Zt(f);l&&(n[s]={type:l})}}return{...n,hasData:{type:x},matchAll:{type:x},_and:{type:new R(i)},_or:{type:new R(i)},_not:{type:i}}}o(et,"generateFilterFields");import{GraphQLEnumType as tt,GraphQLInputObjectType as rt,GraphQLList as er,GraphQLNonNull as ee,GraphQLString as tr,GraphQLBoolean as rr}from"graphql";var te=new tt({name:"SortDirection",values:{ASC:{value:"ascending"},DESC:{value:"descending"}}});function nt(e){let t=[];for(let[i,n]of k(e))Oe(n)&&t.push(i);if(t.length===0)return null;let r=new tt({name:`${e.externalId}SortField`,values:Object.fromEntries(t.map(i=>[i,{value:i}]))});return new rt({name:`${e.externalId}Sort`,fields:{field:{type:new ee(r)},direction:{type:new ee(te)},nullsFirst:{type:rr}}})}o(nt,"generateSortInput");var it=new rt({name:"SearchSort",fields:{property:{type:new ee(new er(new ee(tr)))},direction:{type:te}}});function st(e){let t=e.filter(F),r=Ye(t);for(let l of t){let d=Je(l,r);r.typeRegistry.set(l.externalId,d)}let i=new Map;for(let l of t){let d=new ot({name:`${l.externalId}Filter`,fields:o(()=>et(l,i,r),"fields")});i.set(l.externalId,d)}let n={};for(let l of t){let d=l.externalId,m=z(d),g=r.typeRegistry.get(d),y=r.connectionRegistry.get(d);y||(y=W(d,g),r.connectionRegistry.set(d,y));let w=i.get(d),T=nt(l),V={limit:{type:X},cursor:{type:b},filter:{type:w}};T&&(V.sort={type:new P(T)}),n[m.query]={type:new I(y),args:V},n[m.getById]={type:g,args:{space:{type:new I(b)},externalId:{type:new I(b)}}},n[m.count]={type:new I(or),args:{filter:{type:w}}},n[m.search]={type:new I(y),args:{query:{type:b},limit:{type:X},filter:{type:w},sort:{type:new P(new I(it))},properties:{type:new P(new I(b))}}},n[m.aggregate]={type:new I(new P(new I(Ue))),args:{filter:{type:w},aggregates:{type:new P(new I(new ot({name:`${d}AggregateRequest`,fields:Ke})))},groupBy:{type:new P(new I(b))},query:{type:b}}}}let a=[];for(let[l,d]of r.typeRegistry)a.push({name:d.name,source:`typeRegistry[${l}]`});for(let[l,d]of r.connectionRegistry)a.push({name:d.name,source:`connectionRegistry[${l}]`});let s=new Map;for(let{name:l,source:d}of a)s.has(l)||s.set(l,[]),s.get(l).push(d);for(let[l,d]of s)if(d.length>1)throw new Error(`[dune] duplicate GraphQL type "${l}" from: ${d.join(", ")}`);let p=new nr({query:new ir({name:"Query",fields:n}),types:[te,...Object.values(D),...r.enumRegistry.values()]}),u=new Map,c=new Map;for(let l of t){let d=new Map;for(let[g,y]of k(l))d.set(g,y);let m={view:{space:l.space,externalId:l.externalId,version:l.version},properties:d};u.set(`${l.space}:${l.externalId}`,m),c.set(l.externalId,m)}let f={view(l){let d=u.get(`${l.space}:${l.externalId}`)??c.get(l.externalId);if(!d)throw new Error(`SchemaKnowledge: no view for "${l.space}:${l.externalId}"`);return d},property(l,d){return(u.get(`${l.space}:${l.externalId}`)??c.get(l.externalId))?.properties.get(d)}};return{schema:p,sdl:sr(p),schemaKnowledge:f}}o(st,"buildSchema");async function at(e,t){let i=(await t.dataModels.retrieve([{space:e.space,externalId:e.dataModelExternalId,version:e.dataModelVersion}],{inlineViews:!1})).items[0];if(!i)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} not found`);if(!i.views?.length)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} has no views`);let n=i.views.map(s=>({space:s.space,externalId:s.externalId,version:s.version}));return(await t.views.retrieve(n,{includeInheritedProperties:!0})).items}o(at,"fetchViews");import{execute as ar}from"graphql";function ct(e,t){return async(r,i)=>{let n=await ar({schema:e,document:r,variableValues:i,rootValue:t,fieldResolver:o((a,s,p,u)=>{let c=a[u.fieldName];return typeof c=="function"?c(a,s,p,u):c},"fieldResolver")});if(n.errors?.length)throw n.errors[0];return n.data}}o(ct,"createDuneRequester");import{CogniteError as lr}from"@cognite/sdk";function cr(e){let t=e.property.view;return{property:[t.space,`${t.externalId}/${t.version}`,e.property.property],direction:e.direction,nullsFirst:e.nullsFirst??!1}}o(cr,"compileSortClause");function pr(e,t){let r=new Set,i=new Map(e.map(n=>[n.name,n]));for(let n of e){if(n.queryable)continue;let a=n.from;if(!a||a in t)continue;let s=i.get(a);s?.view&&(t[a]={sources:[{source:s.view,properties:["*"]}]},r.add(a))}return r}o(pr,"injectPhantomSelects");function Se(e,t,r){let i={},n={};for(let c of e){if(!c.queryable)continue;if(c.kind==="edgeIntermediate"){let d={edges:{from:c.from,direction:c.direction,maxDistance:1},limit:Math.min(c.limit,r)};c.filter&&(d.edges.filter=c.filter),c.limitEach!=null&&(d.edges.limitEach=c.limitEach),i[c.name]=d,n[c.name]={sources:[]};continue}let f={filter:c.filter};c.from&&(f.from=c.from),c.chainTo?f.chainTo=c.chainTo:c.through?(f.through={view:c.through.view,identifier:c.through.property},f.direction=c.direction):c.direction&&(f.direction=c.direction);let l={limit:Math.min(c.limit,r),nodes:f};c.sort&&c.sort.length>0&&(l.sort=c.sort.map(cr)),i[c.name]=l,n[c.name]={sources:[{source:c.view,properties:c.select}]}}let a=pr(e,n),s={with:i,select:n},p={},u=!1;for(let c of e){if(!c.queryable||c.kind==="edgeIntermediate")continue;let f=t.get(c.name);f!=null&&(p[c.name]=f,u=!0)}return u&&(s.cursors=p),{query:s,tempSelectSteps:a}}o(Se,"compileQuery");function xe(e,t){let r=[];for(let i=0;i<e.length;i+=t)r.push(e.slice(i,i+t));return r}o(xe,"chunkArray");function ur(e){let t=e.through;return[t.view.space,`${t.view.externalId}/${t.view.version}`,t.property]}o(ur,"throughPropertyPath");function dr(e,t){let r=e.filter,i={containsAny:{property:ur(e),values:t}};return r?{and:[r,i]}:i}o(dr,"containsAnyParentFilter");var Re=class Re{constructor(t,r){this.dms=t;this.config=r}async run(t,r,i){let{response:n,tempSelectSteps:a,batchLimit:s}=await this.queryWithRetry(t,r,i),p={},u=new Map;for(let[c,f]of Object.entries(n.items))p[c]=f,u.set(c,n.nextCursor[c]??null);return await this.fetchReverseLists(t,p),{batch:p,nextCursors:u,tempSelectSteps:a,batchLimit:s}}async fetchConnections(t,r){await this.fetchReverseLists(t,r),await this.fetchQueryableConnections(t,r),await this.fetchEdgeConnections(t,r)}async queryWithRetry(t,r,i){let n=i,a=0;for(;;){let{query:s,tempSelectSteps:p}=Se(t,r,n);try{return{response:await this.dms.query({with:s.with,select:s.select,cursors:s.cursors}),tempSelectSteps:p,batchLimit:n}}catch(u){if(u instanceof lr&&u.status===408){if(a>=this.config.max408Retries)throw u;a++,n=Math.max(1,Math.floor(n/2))}else throw u}}}async fetchReverseLists(t,r){let i=t.filter(n=>!n.queryable&&n.from&&n.kind==="reverseList");for(let n of i){let a=r[n.from]??[];if(a.length===0){r[n.name]=[];continue}let s=a.map(c=>({space:c.space,externalId:c.externalId})),p=xe(s,this.config.reverseListChunkSize),u=await Promise.all(p.map(async c=>{let f=[],l;do{let d={limit:n.limit,nodes:{filter:dr(n,c)}},m=await this.dms.query({with:{[n.name]:d},select:{[n.name]:{sources:[{source:n.view,properties:n.select}]}},...l?{cursors:{[n.name]:l}}:{}});f.push(...m.items[n.name]??[]),l=m.nextCursor?.[n.name]??void 0}while(l);return f}));r[n.name]=u.flat()}}async fetchQueryableConnections(t,r){let i=t.filter(n=>n.queryable&&n.from&&(n.kind==="directRelation"||n.kind==="reverseDirect"));for(let n of i){let a=r[n.from]??[];if(a.length===0){r[n.name]=[];continue}if(n.kind==="directRelation"){let s=n.through,p=`${s.view.externalId}/${s.view.version}`,u=[],c=new Set;for(let d of a){let m=d.properties?.[s.view.space]?.[p]?.[s.property];if(m&&typeof m=="object"&&"space"in m&&"externalId"in m&&typeof m.space=="string"&&typeof m.externalId=="string"){let g=`${m.space}:${m.externalId}`;c.has(g)||(c.add(g),u.push({space:m.space,externalId:m.externalId}))}}if(u.length===0){r[n.name]=[];continue}let f=xe(u,this.config.inFilterChunkSize),l=await Promise.all(f.map(d=>this.dms.retrieve({items:d.map(m=>({instanceType:"node",...m})),sources:[{source:n.view}]})));r[n.name]=l.flatMap(d=>d.items)}else{let s=a.map(l=>({space:l.space,externalId:l.externalId})),p=n.through,u=[p.view.space,`${p.view.externalId}/${p.view.version}`,p.property],c=xe(s,this.config.inFilterChunkSize),f=[];for(let l of c){let d=n.limit-f.length;if(d<=0)break;let m=await this.dms.search({view:n.view,filter:{in:{property:u,values:l}},limit:d});f.push(...m.items)}r[n.name]=f}}}async fetchEdgeConnections(t,r){let i=t.filter(n=>n.kind==="edgeIntermediate"&&n.from);for(let n of i){let a=r[n.from]??[],s=t.find(d=>d.kind==="edge"&&d.from===n.name);if(!s)continue;if(a.length===0){r[n.name]=[],r[s.name]=[];continue}let p=`${n.from}__edge_root`,u={nodes:{filter:{or:a.map(d=>({and:[{equals:{property:["node","space"],value:d.space}},{equals:{property:["node","externalId"],value:d.externalId}}]}))}},limit:a.length},c={edges:{from:p,direction:n.direction,maxDistance:1},limit:n.limit};n.filter&&(c.edges.filter=n.filter),n.limitEach!=null&&(c.edges.limitEach=n.limitEach);let f={nodes:{from:n.name,chainTo:s.chainTo},limit:s.limit};s.filter&&(f.nodes.filter=s.filter);let l=await this.dms.query({with:{[p]:u,[n.name]:c,[s.name]:f},select:{[p]:{sources:[]},[n.name]:{sources:[]},[s.name]:{sources:[{source:s.view,properties:s.select}]}}});r[n.name]=l.items[n.name]??[],r[s.name]=l.items[s.name]??[]}}};o(Re,"QueryExecutor");var M=Re;var fr={endCursor:null,hasNextPage:!1};function lt(e){return{items:e,pageInfo:fr}}o(lt,"wrapConnection");function ne(e){if(!e||typeof e!="object"||!("space"in e)||!("externalId"in e))return!1;let{space:t,externalId:r}=e;return typeof t=="string"&&typeof r=="string"}o(ne,"isDmsRef");function mr(e,t){if(ne(e))return e;if(typeof e!="object"||e===null||!("externalId"in e))return;let{externalId:r}=e;if(typeof r!="string")return;let i="space"in e&&typeof e.space=="string"?e.space:t;return i?{space:i,externalId:r}:void 0}o(mr,"resolveParentRef");function gr(e,t,r){if(ne(e)){t(e);return}if(Array.isArray(e))for(let i of e){let n=mr(i,r);n&&t(n)}}o(gr,"forEachParentRef");var yr=/^[a-z]{2,3}(-[a-zA-Z0-9]{2,4})?$/;function ie(e){if(!e||typeof e!="object"||Array.isArray(e)||ne(e))return e;let t=Object.entries(e);return t.length===0||!t.every(r=>typeof r[1]=="string"&&yr.test(r[0]))?e:t.find(([r])=>r==="en")?.[1]??t[0][1]}o(ie,"coerceTextWithLocale");function ut(e,t){let r=`${t.externalId}/${t.version}`,i=e.properties?.[t.space]?.[r]??{},n={};for(let[a,s]of Object.entries(i))n[a]=ie(s);return{...n,space:e.space,externalId:e.externalId}}o(ut,"extractViewProperties");function re(e,t,r,i){if(t.length===0)return;let n=[...r.values()].filter(s=>s.from===e.name&&s.fieldName),a=[...r.values()].filter(s=>s.kind==="edge"&&s.fieldName&&s.from!=null&&r.get(s.from)?.from===e.name);for(let s of[...n,...a]){let p=(i[s.name]??[]).map(u=>ut(u,s.view));if(s.kind==="directRelation"){let u=new Map;for(let c of p)u.set(`${c.space}:${c.externalId}`,c);for(let c of t){let f=c[s.fieldName];c[s.fieldName]=ne(f)?u.get(`${f.space}:${f.externalId}`)??null:null}re(s,p,r,i)}else if(s.kind==="reverseDirect"||s.kind==="reverseList"){let u=s.through.property,c=new Map;for(let f of t)c.set(`${f.space}:${f.externalId}`,[]);for(let f of p){let l=f[u];l!=null?gr(l,d=>{c.get(`${d.space}:${d.externalId}`)?.push(f)},f.space):t.length===1&&c.get(`${t[0].space}:${t[0].externalId}`)?.push(f)}for(let f of t){let l=c.get(`${f.space}:${f.externalId}`)??[];f[s.fieldName]=s.kind==="reverseList"?lt(l):l}re(s,p,r,i)}else if(s.kind==="edge"){let u=i[s.from]??[],c=new Map;for(let l of u){if(l.instanceType!=="edge")continue;let{startNode:d,endNode:m}=l;if(!d||!m)continue;let g=s.chainTo==="destination"?d:m,y=s.chainTo==="destination"?m:d,w=`${g.space}:${g.externalId}`,T=`${y.space}:${y.externalId}`,V=c.get(w)??[];V.push(T),c.set(w,V)}let f=new Map;for(let l of p)f.set(`${l.space}:${l.externalId}`,l);for(let l of t){let d=`${l.space}:${l.externalId}`,g=(c.get(d)??[]).map(y=>f.get(y)).filter(y=>y!==void 0);l[s.fieldName]=lt(g)}re(s,p,r,i)}}}o(re,"nestChildrenForStep");function hr(e,t,r){let i=e.find(a=>!a.from);if(!i)return r;let n=new Map(e.map(a=>[a.name,a]));return re(i,r,n,t),r}o(hr,"nestChildren");function oe(e,t){let r=e.find(n=>!n.from);if(!r)return[];let i=(t[r.name]??[]).map(n=>ut(n,r.view));return hr(e,t,i)}o(oe,"unpack");function Ie(e,t){for(let r of e)delete t[r]}o(Ie,"stripTempSelects");function dt(){return{initialBatchLimit:1e3,maxBatchLimit:5e3,searchLimit:1e3,inFilterChunkSize:100,reverseListChunkSize:1e3,previewLimit:3,nestedDetailLimit:5,enableRemoveNotConnected:!1,max408Retries:3,max429Retries:5,retryBaseDelayMs:500,maxConcurrentRequests:4,maxNestingDepth:2,maxTotalItems:1e4,maxFilterDepth:16}}o(dt,"defaultPlannerConfig");var ve=class ve extends Error{constructor(t){super(t),this.name="PlannerValidationError"}};o(ve,"PlannerValidationError");var h=ve;function Ee(e){let t={};for(let[r,i]of e)i!=null&&(t[r]=i);return Object.keys(t).length===0?null:btoa(JSON.stringify(t))}o(Ee,"encodeCursors");function Er(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;for(let t of Object.values(e))if(typeof t!="string")return!1;return!0}o(Er,"isStringRecord");function be(e){if(!e)return new Map;let t;try{t=JSON.parse(atob(e))}catch{throw new h("Invalid pagination cursor \u2014 the value is malformed or has been modified by the client.")}if(!Er(t))throw new h("Invalid pagination cursor \u2014 expected a JSON object of {stepName: string}.");return new Map(Object.entries(t))}o(be,"decodeCursors");import{CogniteError as br}from"@cognite/sdk";function ft(){return{max429Retries:5,retryBaseDelayMs:500,maxConcurrentRequests:4}}o(ft,"defaultRetryConfig");function Cr(e){return new Promise(t=>setTimeout(t,e))}o(Cr,"sleep");var Ne=class Ne{constructor(t){this.queue=[];this.count=t}acquire(){return this.count>0?(this.count--,Promise.resolve()):new Promise(t=>this.queue.push(t))}release(){let t=this.queue.shift();t?t():this.count++}};o(Ne,"Semaphore");var Ce=Ne,Ae=class Ae{constructor(t,r=ft()){this.inner=t;this.config=r;this.semaphore=new Ce(r.maxConcurrentRequests)}query(t){return this.withRetry(()=>this.inner.query(t))}search(t){return this.withRetry(()=>this.inner.search(t))}aggregate(t){return this.withRetry(()=>this.inner.aggregate(t))}retrieve(t){return this.withRetry(()=>this.inner.retrieve(t))}sync(t){return this.withRetry(()=>this.inner.sync(t))}upsert(t){return this.inner.upsert(t)}delete(t){return this.inner.delete(t)}inspect(t){return this.inner.inspect(t)}async withRetry(t){let r=0;for(;;){await this.semaphore.acquire();let i=!1;try{return await t()}catch(n){if(n instanceof br&&n.status===429){if(r>=this.config.max429Retries)throw n;r++,this.semaphore.release(),i=!0,await Cr(this.config.retryBaseDelayMs*2**(r-1))}else throw n}finally{i||this.semaphore.release()}}}};o(Ae,"RetryingDmsClient");var O=Ae;function ae(e){return e.connections.size===0?0:1+Math.max(...[...e.connections.values()].map(t=>ae(t.select)))}o(ae,"selectionDepth");function Nr(e,t,r){for(let i of t.scalars)if(i!=="*"&&!r.property(e,i))throw new h(`Property "${i}" does not exist on view ${e.externalId}/${e.version}`);for(let[i]of t.connections)if(!r.property(e,i))throw new h(`Connection "${i}" does not exist on view ${e.externalId}/${e.version}`)}o(Nr,"validateSelection");function G(e){return{hasData:[e]}}o(G,"hasDataFilter");function Ar(e,t){let r=G(t);return e?{and:[e,r]}:r}o(Ar,"scopedFilter");function Pr(e,t,r,i,n){return{name:"0",kind:"root",view:e,filter:Ar(t,e),sort:r&&r.length>0?r:void 0,select:i.length>0?i:["*"],limit:n,queryable:!0}}o(Pr,"makeRootStep");function Vr(e,t,r,i,n,a){return{name:e,from:t.name,kind:"directRelation",view:i,through:{view:t.view,property:r},direction:"outwards",filter:G(i),select:n.length>0?n:["*"],limit:a,queryable:!0,fieldName:r}}o(Vr,"makeDirectRelationStep");function Fr(e,t,r,i,n,a,s){return{name:e,from:t.name,kind:"reverseDirect",view:i,through:{view:i,property:n},direction:"inwards",filter:G(i),select:a.length>0?a:["*"],limit:s,queryable:!0,fieldName:r}}o(Fr,"makeReverseDirectStep");function Qr(e,t,r,i,n,a,s,p){return{name:e,from:t.name,kind:"reverseList",view:i,through:{view:i,property:n},direction:"inwards",filter:G(i),select:a.length>0?a:["*"],limit:s,queryable:!p,fieldName:r}}o(Qr,"makeReverseListStep");function _r(e,t,r,i,n,a,s,p){let u={name:e,from:r.name,kind:"edgeIntermediate",view:n,direction:a,filter:void 0,select:[],limit:p,limitEach:p,queryable:!0},c={name:t,from:e,kind:"edge",view:n,filter:G(n),select:s.length>0?s:["*"],limit:p,queryable:!0,fieldName:i,chainTo:a==="outwards"?"destination":"source"};return[u,c]}o(_r,"makeEdgeSteps");function se(e){return{type:"view",space:e.space,externalId:e.externalId,version:e.version}}o(se,"toRef");function mt(e,t){return e.length===0||e.includes("*")||e.includes(t)?e:[...e,t]}o(mt,"withThroughProperty");function Mr(e,t){return e.includes("*")||e.includes(t)?e:[...e,t]}o(Mr,"withDirectRelationRef");function q(e,t,r,i,n,a){let s=0;for(let[p,u]of r.connections){let c=n.property(t,p);if(!c)continue;s++;let f=u.limit??i,l=u.select.scalars,d=u.select,m=`${e.name}_${s}`;if(c.kind==="directRelation"){e.select=Mr(e.select,p);let g=se(c.targetView),y=Vr(m,e,p,g,l,f);a.push(y),q(y,g,d,i,n,a)}else if(c.kind==="reverseDirect"){let g=se(c.sourceView),y=mt(l,c.throughProperty),w=Fr(m,e,p,g,c.throughProperty,y,f);a.push(w),q(w,g,d,i,n,a)}else if(c.kind==="reverseList"){let g=se(c.sourceView),y=mt(l,c.throughProperty),w=$e(n,c.sourceView,c.throughProperty),T=Qr(m,e,p,g,c.throughProperty,y,f,w);a.push(T),q(T,g,d,i,n,a)}else if(c.kind==="edge"){let g=se(c.targetView),y=`${e.name}_${s}_e`,[w,T]=_r(y,m,e,p,g,c.direction,l,f);a.push(w,T),q(T,g,d,i,n,a)}}}o(q,"addConnectionSteps");function ce(e,t,r,i,n,a,s){a&&Nr(e,t,a);let p=Pr(e,r,i,t.scalars,n),u=[p];return a&&q(p,e,t,s??n,a,u),u}o(ce,"buildSteps");var Or="5c4d853e7c3b77b1eb4468d5329b278c",qr="https://api.mixpanel.com/track",Gr="flows-typed-ts-sdk";var $={ClientCreated:"Flows.SDK.ClientCreated",OperationExecuted:"Flows.SDK.OperationExecuted"};function $r(e){return typeof e=="object"&&e!==null}o($r,"isRecord");function gt(){let e=globalThis;return $r(e)?e:{}}o(gt,"defaultEnv");function Br(e=gt()){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(Br,"isSdkTelemetryDisabled");function jr(e){return{track(t,r,i){let n=JSON.stringify([{event:t,properties:{token:e,...r}}]),a=new URLSearchParams({data:n});fetch(qr,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a.toString(),keepalive:!0}).then(()=>i(),()=>i())}}}o(jr,"fetchInit");var Kr={track:o(()=>{},"track"),flush:o(async()=>{},"flush"),register:o(()=>{},"register")};function Ur(e={}){let t=e.env??gt();if(Br(t))return Kr;let r=e.init??jr,i,n=new Set,a={};function s(){return i||(i=r(Or)),i}return o(s,"getClient"),{register(p){a={...a,...p}},track(p,u){let c=s(),f={...a,...u,applicationId:Gr},l=o(()=>{},"finish"),d=new Promise(m=>{l=m});n.add(d);try{c.track(p,f,l)}catch{l()}d.finally(()=>n.delete(d))},async flush(p=2e3){if(n.size===0)return;let u,c=new Promise(f=>{u=setTimeout(f,p),u.unref?.()});try{await Promise.race([Promise.allSettled([...n]),c])}finally{u!==void 0&&clearTimeout(u)}}}}o(Ur,"createSdkTelemetry");var B=Ur();var Pe=class Pe{get schemaKnowledge(){return this.schema}get maxFilterDepth(){return this.config.maxFilterDepth}constructor(t,r,i,n=B){this.schema=r,this.config={...dt(),...i},this.telemetry=n,this.dms=new O(t,{max429Retries:this.config.max429Retries,retryBaseDelayMs:this.config.retryBaseDelayMs,maxConcurrentRequests:this.config.maxConcurrentRequests}),this.executor=new M(this.dms,{max408Retries:this.config.max408Retries,inFilterChunkSize:this.config.inFilterChunkSize,reverseListChunkSize:this.config.reverseListChunkSize})}async trackOperation(t,r,i){let n=performance.now();try{let a=await i();return this.telemetry.track($.OperationExecuted,{operationType:t,viewExternalId:r.externalId,success:!0,durationMs:Math.round(performance.now()-n)}),a}catch(a){throw this.telemetry.track($.OperationExecuted,{operationType:t,viewExternalId:r.externalId,success:!1,durationMs:Math.round(performance.now()-n)}),a}}async _queryPage(t){let r=ae(t.select);if(r>this.config.maxNestingDepth)throw new h(`Query nesting depth ${r} exceeds the maximum of ${this.config.maxNestingDepth} enforced by the Data Modeling service. Reduce connection depth.`);let i=t.limit??this.config.initialBatchLimit,n=ce(t.view,t.select,t.filter,t.sort,i,this.schema,this.config.previewLimit);if(n.length===0)return{items:[],pageInfo:{endCursor:null,hasNextPage:!1}};let a=new Map(be(t.cursor)),s=Math.min(this.config.initialBatchLimit,this.config.maxBatchLimit),{batch:p,nextCursors:u,tempSelectSteps:c}=await this.executor.run(n,a,s);Ie(c,p);let f=oe(n,p),l=n[0],d=u.get(l.name)??null,m=Ee(u),g=d!=null;return{items:f,pageInfo:{endCursor:m,hasNextPage:g}}}async query(t){return this.trackOperation("query",t.view,()=>this._queryPage(t))}async queryAll(t,r){let i=r??this.config.maxTotalItems,n=[],a,s=!0;for(;s;){let p=await this._queryPage({...t,cursor:a});if(n.push(...p.items),s=p.pageInfo.hasNextPage,a=p.pageInfo.endCursor??void 0,n.length>=i){if(r===void 0&&s)throw new h(`listAll reached the hard ceiling of ${i} items. Pass an explicit maxTotal to acknowledge this or raise maxTotalItems in config.`);break}}return n}async search(t){return this.trackOperation("search",t.view,async()=>{let r=t.limit??this.config.searchLimit,i=await this.dms.search({view:t.view,query:t.query,filter:t.filter,sort:t.sort,limit:r,properties:t.properties}),n=ce(t.view,t.select,void 0,void 0,r,this.schema,this.config.previewLimit),a={0:i.items};return await this.executor.fetchConnections(n,a),{items:oe(n,a),pageInfo:{endCursor:null,hasNextPage:!1}}})}async retrieve(t,r){return this.trackOperation("retrieve",r,async()=>{if(t.length===0)return[];let i=await this.dms.retrieve({items:t.map(a=>({instanceType:"node",space:a.space,externalId:a.externalId})),sources:[{source:r}]}),n=`${r.externalId}/${r.version}`;return i.items.map(a=>{let s=a.properties?.[r.space]?.[n]??{},p={};for(let[u,c]of Object.entries(s))p[u]=ie(c);return{...p,space:a.space,externalId:a.externalId}})})}async count(t){return this.trackOperation("count",t.view,async()=>{let i=(await this.dms.aggregate({view:t.view,filter:t.filter,aggregates:[{count:{property:"externalId"}}]})).items[0]?.aggregates[0];return(i?.aggregate!=="histogram"?i?.value:void 0)??0})}async aggregate(t){return this.trackOperation("aggregate",t.view,async()=>({items:(await this.dms.aggregate({view:t.view,filter:t.filter,aggregates:t.aggregates,groupBy:t.groupBy,query:t.query})).items}))}async*queryPages(t){let r,i=!0;for(;i;){let n=await this._queryPage({...t,cursor:r});yield n,i=n.pageInfo.hasNextPage,r=n.pageInfo.endCursor??void 0}}};o(Pe,"QueryRunner");var j=Pe;function Ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Ve,"isRecord");function pe(e){return typeof e=="string"||typeof e=="number"}o(pe,"isScalar");var zr={space:["node","space"],externalId:["node","externalId"]};function Hr(e,t){return zr[t]??[e.space,`${e.externalId}/${e.version}`,t]}o(Hr,"propRef");var Xr={exists:o((e,t)=>typeof t!="boolean"?void 0:t?{exists:{property:e}}:{not:{exists:{property:e}}},"exists"),eq:o((e,t)=>({equals:{property:e,value:t}}),"eq"),in:o((e,t)=>Array.isArray(t)?{in:{property:e,values:t}}:void 0,"in"),isNull:o((e,t)=>typeof t!="boolean"?void 0:t?{not:{exists:{property:e}}}:{exists:{property:e}},"isNull"),prefix:o((e,t)=>typeof t=="string"?{prefix:{property:e,value:t}}:void 0,"prefix"),gte:o((e,t)=>pe(t)?{range:{property:e,gte:t}}:void 0,"gte"),gt:o((e,t)=>pe(t)?{range:{property:e,gt:t}}:void 0,"gt"),lte:o((e,t)=>pe(t)?{range:{property:e,lte:t}}:void 0,"lte"),lt:o((e,t)=>pe(t)?{range:{property:e,lt:t}}:void 0,"lt"),containsAny:o((e,t)=>Array.isArray(t)?{containsAny:{property:e,values:t}}:void 0,"containsAny"),containsAll:o((e,t)=>Array.isArray(t)?{containsAll:{property:e,values:t}}:void 0,"containsAll"),overlaps:o((e,t)=>Array.isArray(t)?{containsAny:{property:e,values:t}}:void 0,"overlaps")};function Yr(e,t,r,i,n,a){let s=Hr(r,e),p=Object.entries(t).flatMap(([u,c])=>{if(c==null)return[];if(u==="nested"&&i&&Ve(c)){let l=i.property(r,e);if(l?.kind==="directRelation"){let d={type:"view",...l.targetView},m=le(c,d,i,n+1,a);if(m)return[{nested:{scope:[r.space,`${r.externalId}/${r.version}`,e],filter:m}}]}return[]}let f=Xr[u]?.(s,c);return f?[f]:[]});if(p.length!==0)return p.length===1?p[0]:{and:p}}o(Yr,"translatePropertyFilter");function Jr(e){if(e.length!==0)return e.length===1?e[0]:{and:e}}o(Jr,"collapse");function v(e,t,r,i=16){return le(e,t,r,0,i)}o(v,"buildFilter");function le(e,t,r,i,n){if(i>n)throw new h(`Filter nesting depth ${i} exceeds maximum ${n}. Reduce _and/_or/_not/nested nesting.`);if(!Ve(e))return;let a=Object.entries(e).flatMap(([s,p])=>{if(p==null)return[];if(s==="_not"){let u=le(p,t,r,i+1,n);return u?[{not:u}]:[]}if(s==="hasData"&&typeof p=="boolean"&&p)return[{hasData:[{type:"view",space:t.space,externalId:t.externalId,version:t.version}]}];if(s==="matchAll"&&typeof p=="boolean"&&p)return[{matchAll:{}}];if((s==="_and"||s==="_or")&&Array.isArray(p)){let u=p.flatMap(c=>{let f=le(c,t,r,i+1,n);return f?[f]:[]});return u.length>0?[s==="_and"?{and:u}:{or:u}]:[]}if(Ve(p)){let u=Yr(s,p,t,r,i,n);return u?[u]:[]}return[]});return Jr(a)}o(le,"buildFilterImpl");var Wr={avg:o(e=>({avg:{property:e.property}}),"avg"),sum:o(e=>({sum:{property:e.property}}),"sum"),min:o(e=>({min:{property:e.property}}),"min"),max:o(e=>({max:{property:e.property}}),"max"),count:o(e=>({count:{property:e.property??"externalId"}}),"count"),histogram:o(e=>({histogram:{property:e.property,interval:e.interval}}),"histogram")};function Zr(e){let t=Wr[e.function];if(!t)throw new h(`Unknown aggregation function '${e.function}'`);if(e.function!=="count"&&!e.property)throw new h(`Property is required for '${e.function}' aggregation`);if(e.function==="histogram"&&e.interval===void 0)throw new h("Interval is required for 'histogram' aggregation");return t(e)}o(Zr,"toAggregationDefinition");function yt(e,t){return o(async function(i,n){let{items:a}=await t.aggregate({view:e,filter:v(n.filter,e,t.schemaKnowledge,t.maxFilterDepth),aggregates:(n.aggregates??[{function:"count"}]).map(Zr),groupBy:n.groupBy,query:n.query});return a.flatMap(s=>s.aggregates.map(p=>{if(p.aggregate==="histogram"){let{aggregate:l,property:d,buckets:m}=p;return{aggregate:l,property:d,value:null,buckets:m,group:s.group??null}}let{aggregate:u,property:c,value:f}=p;return{aggregate:u,property:c,value:f,buckets:null,group:s.group??null}}))},"aggregateResolver")}o(yt,"makeAggregateResolver");function ht(e,t){return o(async function(i,n){let a=v(n.filter,e,t.schemaKnowledge,t.maxFilterDepth);return t.count({view:e,filter:a})},"countResolver")}o(ht,"makeCountResolver");import{Kind as K,isObjectType as en,getNamedType as tn}from"graphql";function ue(e,t){let r=[];for(let i of e.selections)if(i.kind===K.FIELD)r.push(i);else if(i.kind===K.INLINE_FRAGMENT&&i.selectionSet)r.push(...ue(i.selectionSet,t));else if(i.kind===K.FRAGMENT_SPREAD){let n=t[i.name.value];n&&r.push(...ue(n.selectionSet,t))}return r}o(ue,"collectFields");var rn=new Set(["space","externalId"]);function wt(e,t,r){let i=[],n=new Map;for(let a of ue(e,r.fragments)){let s=a.name.value;if(s==="__typename"||rn.has(s))continue;if(!a.selectionSet){i.push(s);continue}let p=r.schema.getType(t);if(en(p)){let u=p.getFields()[s];if(u){let c=tn(u.type).name,f=wt(a.selectionSet,c,r),l=a.arguments?.find(m=>m.name.value==="limit"),d;if(l){if(l.value.kind===K.INT)d=parseInt(l.value.value,10);else if(l.value.kind===K.VARIABLE){let m=r.variableValues?.[l.value.name.value];typeof m=="number"&&(d=m)}}n.set(s,{limit:d,select:f});continue}}i.push(s)}return{scalars:i,connections:n}}o(wt,"buildTree");function Fe(e,t,r){return e?wt(e,t,r):{scalars:[],connections:new Map}}o(Fe,"buildSelectionTree");function de(e,t){let r=e.fieldNodes[0]?.selectionSet;if(!r)return{scalars:[],connections:new Map};let i=ue(r,e.fragments).find(n=>n.name.value==="items");return Fe(i?.selectionSet,t,e)}o(de,"buildSelectionTreeFromListInfo");function St(e,t,r){return o(async function(n,a,s,p){let{space:u,externalId:c}=a,f=Fe(p.fieldNodes[0]?.selectionSet,t,p),l={and:[{equals:{property:["node","space"],value:u}},{equals:{property:["node","externalId"],value:c}}]},{items:d}=await r.query({view:e,select:f,filter:l,limit:1});return d[0]??null},"getByIdResolver")}o(St,"makeGetByIdResolver");function xt(e,t,r){return o(async function(n,a,s,p){let u=de(p,t),c=v(a.filter,e,r.schemaKnowledge,r.maxFilterDepth),f=nn(a.sort,e);return r.query({view:e,select:u,filter:c,sort:f,cursor:a.cursor,limit:a.limit})},"queryResolver")}o(xt,"makeQueryResolver");function nn(e,t){if(!(!e||e.length===0))return e.map(r=>({property:{view:t,property:r.field},direction:r.direction??"ascending",nullsFirst:r.nullsFirst}))}o(nn,"parseSortArg");function Rt(e,t,r){return o(async function(n,a,s,p){let u=de(p,t),c={view:e,query:a.query,limit:a.limit,filter:v(a.filter,e,r.schemaKnowledge,r.maxFilterDepth),sort:a.sort,select:u,properties:a.properties},{items:f,pageInfo:l}=await r.search(c);return{items:f,pageInfo:l}},"searchResolver")}o(Rt,"makeSearchResolver");function on(e,t){let r={};for(let i of e.filter(F)){let n={type:"view",space:i.space,externalId:i.externalId,version:i.version},a=i.externalId,s=z(a);r[s.query]=xt(n,a,t),r[s.getById]=St(n,a,t),r[s.count]=ht(n,t),r[s.search]=Rt(n,a,t),r[s.aggregate]=yt(n,t)}return r}o(on,"buildRootValue");async function sn(e,t,r=B){let i=await at(e,t);return It(i,t,r)}o(sn,"createDuneRuntime");function It(e,t,r=B){let i=Be(e),{schema:n,schemaKnowledge:a}=st(i),s=new j(t.instances,a,void 0,r),p=on(i,s),u=ct(n,p);return r.register({project:t.project}),r.track($.ClientCreated,{viewCount:e.filter(F).length}),{schema:n,rootValue:p,runner:s,requester:u}}o(It,"createDuneRuntimeFromViews");export{sn as a,It as b};