@cognite/cli 1.0.0-alpha.42 → 1.1.0-alpha.48

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
@@ -83,7 +83,7 @@ To test against your own app instead of the fixture:
83
83
 
84
84
  ```bash
85
85
  cd apps/my-app
86
- COGNITE_TOKEN=test-token COGNITE_BASE_URL=http://localhost:9090 pnpm exec dune apps deploy --skip-build
86
+ COGNITE_TOKEN=test-token COGNITE_BASE_URL=http://localhost:9090 pnpm exec cognite apps deploy --skip-build
87
87
  ```
88
88
 
89
89
  #### Simulating error scenarios
@@ -0,0 +1,11 @@
1
+ ---
2
+ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>.mcp.json'
3
+ ---
4
+ {
5
+ "mcpServers": {
6
+ "cognite-docs": {
7
+ "type": "http",
8
+ "url": "https://docs.cognite.com/mcp"
9
+ }
10
+ }
11
+ }
@@ -0,0 +1,10 @@
1
+ ---
2
+ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>.cursor/mcp.json'
3
+ ---
4
+ {
5
+ "mcpServers": {
6
+ "cognite-docs": {
7
+ "url": "https://docs.cognite.com/mcp"
8
+ }
9
+ }
10
+ }
@@ -3,7 +3,7 @@ export default [
3
3
  type: 'input',
4
4
  name: 'name',
5
5
  message: 'What is the app name? (use kebab-case, e.g., my-awesome-app)',
6
- initial: 'my-dune-app',
6
+ initial: 'my-flows-app',
7
7
  validate: (input) =>
8
8
  /^[a-z][a-z0-9-]*$/.test(input)
9
9
  ? true
@@ -13,13 +13,13 @@ export default [
13
13
  type: 'input',
14
14
  name: 'displayName',
15
15
  message: 'What is the display name? (e.g., My Awesome App)',
16
- initial: 'My Dune app',
16
+ initial: 'My Flows app',
17
17
  },
18
18
  {
19
19
  type: 'input',
20
20
  name: 'description',
21
21
  message: 'What is the app description?',
22
- initial: 'A Dune application',
22
+ initial: 'A Flows application',
23
23
  },
24
24
  {
25
25
  type: 'input',
@@ -2,3 +2,4 @@
2
2
  to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>.npmrc'
3
3
  ---
4
4
  engine-strict=true
5
+ min-release-age=2
@@ -22,7 +22,13 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
22
22
 
23
23
  ---
24
24
 
25
- ## 1. Dependency Injection
25
+ ## 1. UI Components
26
+
27
+ Always check `@cognite/aura/components` before reaching for a raw HTML element or custom CSS/Tailwind solution. If Aura has a component that covers the need, use it. Only fall back to custom solutions when Aura genuinely doesn't cover the use case.
28
+
29
+ ---
30
+
31
+ ## 2. Dependency Injection
26
32
 
27
33
  Inject dependencies via React context (hooks/components) or factory-override pattern (plain functions). Never hard-code dependencies.
28
34
 
@@ -51,7 +57,7 @@ export const doWork = async (props: Props, overrides?: Partial<Deps>) => {
51
57
 
52
58
  ---
53
59
 
54
- ## 2. Interface-Based Services
60
+ ## 3. Interface-Based Services
55
61
 
56
62
  Define an interface; implement with a class. Never reference the concrete class outside its own file.
57
63
 
@@ -68,7 +74,7 @@ export class ApiDataService implements DataService {
68
74
 
69
75
  ---
70
76
 
71
- ## 3. ViewModel Pattern
77
+ ## 4. ViewModel Pattern
72
78
 
73
79
  Business logic lives in `use<Name>ViewModel`. Components only render.
74
80
 
@@ -91,7 +97,7 @@ export const TodoView = () => {
91
97
 
92
98
  ---
93
99
 
94
- ## 4. Test-First Development
100
+ ## 5. Test-First Development
95
101
 
96
102
  Write tests before implementation for all non-trivial behavior changes.
97
103
 
@@ -187,7 +193,7 @@ Place reusable factories in `src/__mocks__/`. Use `.test` TLD for fake URLs (RFC
187
193
 
188
194
  ---
189
195
 
190
- ## 5. TypeScript Rules
196
+ ## 6. TypeScript Rules
191
197
 
192
198
  - Never use `any`; prefer `unknown` or explicit strong types
193
199
  - Never use `as unknown as T`; for partial test doubles use `{ ...defaults, ...overrides } as T`
@@ -201,7 +207,7 @@ function createMockWindow(overrides: Partial<Window> = {}): Window {
201
207
 
202
208
  ---
203
209
 
204
- ## 6. Commits and pull requests
210
+ ## 7. Commits and pull requests
205
211
 
206
212
  Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/).
207
213
 
@@ -0,0 +1,11 @@
1
+ ---
2
+ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>.vscode/mcp.json'
3
+ ---
4
+ {
5
+ "servers": {
6
+ "cognite-docs": {
7
+ "type": "http",
8
+ "url": "https://docs.cognite.com/mcp"
9
+ }
10
+ }
11
+ }
@@ -4,25 +4,25 @@ Selected, generated files from [github/spec-kit](https://github.com/github/spec-
4
4
 
5
5
  ## Why this exists
6
6
 
7
- Dune app authors should not need Python, `uv`, or network access just because they pass `dune create --spec-kit`.
7
+ Flows app authors should not need Python, `uv`, or network access just because they pass `cognite create --spec-kit`.
8
8
 
9
- Instead, Dune maintainers refresh spec-kit inside this monorepo, commit the selected generated files here, and let `dune create` copy them into new apps. That keeps end-user scaffolding fast and JS/TS-only while still letting us track upstream spec-kit intentionally.
9
+ Instead, Flows builder app maintainers refresh spec-kit inside this monorepo, commit the selected generated files here, and let `cognite create` copy them into new apps. That keeps end-user scaffolding fast and JS/TS-only while still letting us track upstream spec-kit intentionally.
10
10
 
11
11
  ## Maintainer-only refresh
12
12
 
13
- The refresh script is for Dune monorepo maintainers only:
13
+ The refresh script is for Flows app maintainers only:
14
14
 
15
15
  ```sh
16
16
  pnpm --filter @cognite/cli refresh-spec-kit <tag>
17
17
  ```
18
18
 
19
- It requires `uv` locally, which provides `uvx`. That is acceptable for maintainers; it must not become a requirement for generated Dune apps.
19
+ It requires `uv` locally, which provides `uvx`. That is acceptable for maintainers; it must not become a requirement for generated Flows apps.
20
20
 
21
21
  The script runs spec-kit's own `specify init` for the requested tag, stages the selected output in a temporary directory, and swaps it into `_vendor/spec-kit` only after all copies succeed.
22
22
 
23
23
  ## What we vendor
24
24
 
25
- We vendor the parts Dune uses:
25
+ We vendor the parts Flows apps uses:
26
26
 
27
27
  - generated `commands/speckit.{specify,clarify,plan,tasks,implement,analyze,checklist}.md`
28
28
  - `templates/{spec,plan,tasks,checklist}-template.md`
@@ -30,10 +30,10 @@ We vendor the parts Dune uses:
30
30
 
31
31
  Deliberately excluded:
32
32
 
33
- - spec-kit's `AGENTS.md`, constitution command, and constitution template, because Dune uses the app's `AGENTS.md` as the constitution
33
+ - spec-kit's `AGENTS.md`, constitution command, and constitution template, because Flows apps uses the app's `AGENTS.md` as the constitution
34
34
  - integration metadata/workflows generated by `specify init`
35
35
  - optional commands such as taskstoissues
36
- - PowerShell scripts, until Dune chooses to support a PowerShell command set
36
+ - PowerShell scripts, until Flows apps chooses to support a PowerShell command set
37
37
  - spec-kit's Python CLI, tests, and docs
38
38
 
39
- **Cadence:** refresh at least once per Dune CLI minor release, sooner if upstream ships a fix we depend on.
39
+ **Cadence:** refresh at least once per cognite CLI minor release, sooner if upstream ships a fix we depend on.
@@ -0,0 +1,9 @@
1
+ var W=Object.defineProperty;var s=(e,t)=>W(e,"name",{value:t,configurable:!0});import Y from"fs";import gt from"path";var F="https://docs.cognite.com/cdf/access/";function m(e){return e!==null&&typeof e=="object"}s(m,"isRecord");function P(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}s(P,"isHttpError");function Z(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
+ See: ${F}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
3
+ See: ${F}`;default:return}}s(Z,"httpStatusHint");function A(e){let t=e instanceof Error?e:new Error(String(e));if(!P(t))return null;let n=Z(t.status);return n?Object.assign(new Error(`${t.message}
4
+ ${n}`),{cause:t}):null}s(A,"enrichedHttpError");function X(e){if(!m(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(m(n)){let r=n.error;if(m(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}s(X,"findMissingArray");function Q(e,t){if(!P(e)||e.status!==400)return!1;let n=X(e);return n?n.some(r=>m(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}s(Q,"isMissingExternalIdError");function $(e,t){return P(e)&&e.status===404||Q(e,t)}s($,"isNotFoundError");var M=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],J=["ACTIVE","PREVIEW"],I=class I extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};s(I,"AppVersionNotFoundError");var k=I;function q(e,t){return e.includes(t)}s(q,"includesValue");function tt(e){return q(M,e)}s(tt,"isAppVersionLifecycleState");function et(e){return q(J,e)}s(et,"isAppVersionAlias");function nt(e){return typeof e.version=="string"&&tt(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||et(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}s(nt,"isAppVersion");function H(e){if(!m(e))throw new Error("Invalid version response: not an object");if(!nt(e))throw new Error("Invalid version response: missing or malformed fields");return e}s(H,"parseAppVersion");var T=class T{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:r}]}})}catch(o){throw A(o)??o}}async uploadVersion(t,n,r,o,i="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),o),a.append("version",n),a.append("entryPath",i);let l=encodeURIComponent(t),c=`${this.appsBasePath}/${l}/versions`,p=await this.client.authenticate(),g=`${this.client.getBaseUrl()}${c}`,u=new AbortController,G=setTimeout(()=>u.abort(),300*1e3),h;try{h=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${p}`},body:a,signal:u.signal})}catch(f){throw f instanceof Error&&f.name==="AbortError"?new Error("Upload timed out after 5 minutes"):f}finally{clearTimeout(G)}if(!h.ok){let f=await h.text(),V=f;try{let x=JSON.parse(f);if(m(x)){let w=x.error;if(typeof w=="string")V=w;else if(m(w)){let E=w.message,B=w.code;V=typeof E=="string"?E:B!=null?`Unknown error (code: ${B})`:f}else{let E=x.message;V=typeof E=="string"?E:f}}}catch{}let j=h.headers.get("x-request-id"),K=j?` | X-Request-ID: ${j}`:"",N=Object.assign(new Error(`Upload failed: ${h.status} \u2014 ${V}${K}`),{status:h.status});throw A(N)??N}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),o=encodeURIComponent(n),i=`${this.appsBasePath}/${r}/versions/${o}`;try{let a=await this.client.get(i);return H(a.data)}catch(a){throw $(a,[t,n])?new k(t,n):A(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/active`;try{let o=await this.client.get(r);return H(o.data)}catch(o){if($(o,[t]))return null;throw A(o)??o}}async updateVersions(t,n){let r=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:n}})}catch(i){throw A(i)??i}}};s(T,"AppHostingApi");var v=T;var b=class b{constructor(t){this.api=new v(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,o,i){return this.api.uploadVersion(t,n,r,o,i)}async ensureApp(t,n,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,r),console.log(`\u2705 App '${t}' created`)}catch(o){if(P(o)&&o.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw o}}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{alias:{setNull:!0}}}])}async activateVersion(t,n){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let o=r&&r.version!==n?r.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(t,n,r,o,i,a,l=!1){console.log(`
5
+ \u{1F680} Deploying application via App Hosting API...
6
+ `);try{await this.ensureApp(t,n,r),await this.uploadVersion(t,o,i,a),l&&await this.publishAndActivate(t,o),console.log(`
7
+ \u2705 Deployment successful!`)}catch(c){let p=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${p}`),{cause:c})}}};s(b,"AppHostingClient");var S=b;import y from"fs";import d from"path";import{parseAndValidateManifestConfig as rt}from"@cognite/app-sdk/vite";import{BlobReader as ot,Uint8ArrayWriter as st,ZipWriter as it}from"@zip.js/zip.js";var R="package.json",D="package-lock.json",z="manifest.json",_=".cognite",L=class L{constructor(t="dist"){this.distPath=d.isAbsolute(t)?t:d.join(process.cwd(),t),this.appRoot=d.dirname(this.distPath)}validateBuildDirectory(){if(!y.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=d.join(this.appRoot,R);if(!y.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=d.join(this.appRoot,D);if(!y.existsSync(n))throw new Error(`"${n}" not found. It is required for deployment.`)}async createZip(t="app.zip",n=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new it(new st,{level:9}),o=s(async(c,p)=>{await r.add(p,new ot(await y.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${p}`)},"addFile"),i=s(async c=>{let p=await y.promises.readdir(c,{withFileTypes:!0});for(let g of p){let u=d.join(c,g.name);g.isDirectory()?await i(u):await o(u,d.relative(this.distPath,u).replace(/\\/g,"/"))}},"addDir"),a;try{await i(this.distPath);let c=d.join(this.appRoot,R);await o(c,d.posix.join(_,R));let p=d.join(this.appRoot,z);if(y.existsSync(p)){let u=y.readFileSync(p,"utf-8");rt(u,p),await o(p,d.posix.join(_,z))}let g=d.join(this.appRoot,D);await o(g,d.posix.join(_,D)),a=await r.close()}catch(c){let p=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${p}`)}await y.promises.writeFile(t,a);let l=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${l} MB)`),t}};s(L,"ApplicationPackager");var C=L;import{CogniteClient as ut}from"@cognite/sdk";var at=s(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),n={};for(let[r,o]of Object.entries(t))if(typeof o=="string"){let i=r.toLowerCase().replace(/_/g,"-");n[i]=o}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),ct=s(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=at()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),pt=s(e=>{if(!e)return"";try{return new URL(e).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=e.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),lt=s(async(e,t)=>{let n=`Basic ${btoa(`${e}:${t}`)}`,r=await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:n,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})});if(!r.ok){let i=await r.text();throw new Error(`Failed to get token from CDF: ${r.status} ${r.statusText}
8
+ ${i}`)}let o=await r.json();if(!o.access_token)throw new Error("No access token returned from CDF authentication");return o.access_token},"getTokenCdf"),dt=s(async(e,t,n,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let o=pt(r);if(!o)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${r}`);let i=`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,a=`https://${o}.cognitedata.com/.default`,l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,client_secret:t,scope:a,grant_type:"client_credentials"})});if(!l.ok){let p=await l.text();throw new Error(`Failed to get token from Entra ID: ${l.status} ${l.statusText}
9
+ ${p}`)}let c=await l.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),O=s(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:n,deploySecretName:r,idpType:o="cdf",tenantId:i,baseUrl:a}=e,l=ct(r);if(o==="entra_id"){if(!i)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return dt(n,l,i,a)}return lt(n,l)},"getToken");async function U(e,t,n=process.env,r){let o=await O(e,n),i=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(l=>new ut(l)))({appId:t,project:e.project,baseUrl:i,oidcTokenProvider:s(async()=>o,"oidcTokenProvider")});return await a.authenticate(),a}s(U,"getSdk");var ft=s(async(e,t,n)=>{let r=await new C(`${n}/dist`).createZip("app.zip",!0);try{let{externalId:o,name:i,description:a,versionTag:l}=t,c=await U(e,n),p=new S(c),g=Y.readFileSync(r),u=gt.basename(r);await p.deploy(o,i,a,l,g,u,e.published)}finally{try{Y.unlinkSync(r)}catch{}}},"deploy");export{S as a,C as b,O as c,U as d,ft as e};
package/dist/cli/cli.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{a as o,e as Ne}from"../chunk-A5ASLC6T.js";import{writeSync as vi}from"fs";import{Command as xi}from"commander";var Ke="https://docs.cognite.com/cdf/access/";function k(e){return e!==null&&typeof e=="object"}o(k,"isRecord");function H(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(H,"isHttpError");function xr(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
3
- See: ${Ke}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
4
- See: ${Ke}`;default:return}}o(xr,"httpStatusHint");function j(e){let t=e instanceof Error?e:new Error(String(e));if(!H(t))return null;let r=xr(t.status);return r?Object.assign(new Error(`${t.message}
5
- ${r}`),{cause:t}):null}o(j,"enrichedHttpError");function Pr(e){if(!k(e))return null;let t=e.missing;if(Array.isArray(t))return t;let r=e.data;if(k(r)){let n=r.error;if(k(n)&&Array.isArray(n.missing))return n.missing;if(Array.isArray(r.missing))return r.missing}return null}o(Pr,"findMissingArray");function br(e,t){if(!H(e)||e.status!==400)return!1;let r=Pr(e);return r?r.some(n=>k(n)&&typeof n.externalId=="string"&&t.includes(n.externalId)):!1}o(br,"isMissingExternalIdError");function se(e,t){return H(e)&&e.status===404||br(e,t)}o(se,"isNotFoundError");var Me=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Ve=["ACTIVE","PREVIEW"],ae=class ae extends Error{constructor(t,r){super(`Version ${r} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=r}};o(ae,"AppVersionNotFoundError");var C=ae;function He(e,t){return e.includes(t)}o(He,"includesValue");function Ar(e){return He(Me,e)}o(Ar,"isAppVersionLifecycleState");function kr(e){return He(Ve,e)}o(kr,"isAppVersionAlias");function Dr(e){return typeof e.version=="string"&&Ar(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||kr(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(Dr,"isAppVersion");function je(e){if(!k(e))throw new Error("Invalid version response: not an object");if(!Dr(e))throw new Error("Invalid version response: missing or malformed fields");return e}o(je,"parseAppVersion");var pe=class pe{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,r,n){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:r,description:n}]}})}catch(i){throw j(i)??i}}async uploadVersion(t,r,n,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${r}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(n)]),i),a.append("version",r),a.append("entryPath",s);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,l=await this.client.authenticate(),m=`${this.client.getBaseUrl()}${c}`,d=new AbortController,u=setTimeout(()=>d.abort(),300*1e3),f;try{f=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${l}`},body:a,signal:d.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?new Error("Upload timed out after 5 minutes"):g}finally{clearTimeout(u)}if(!f.ok){let g=await f.text(),b=g;try{let U=JSON.parse(g);if(k(U)){let x=U.error;if(typeof x=="string")b=x;else if(k(x)){let A=x.message,y=x.code;b=typeof A=="string"?A:y!=null?`Unknown error (code: ${y})`:g}else{let A=U.message;b=typeof A=="string"?A:g}}}catch{}let v=f.headers.get("x-request-id"),Z=v?` | X-Request-ID: ${v}`:"",K=Object.assign(new Error(`Upload failed: ${f.status} \u2014 ${b}${Z}`),{status:f.status});throw j(K)??K}console.log(`\u2705 Version ${r} uploaded`)}async getVersion(t,r){let n=encodeURIComponent(t),i=encodeURIComponent(r),s=`${this.appsBasePath}/${n}/versions/${i}`;try{let a=await this.client.get(s);return je(a.data)}catch(a){throw se(a,[t,r])?new C(t,r):j(a)??a}}async getActiveVersion(t){let r=encodeURIComponent(t),n=`${this.appsBasePath}/${r}/active`;try{let i=await this.client.get(n);return je(i.data)}catch(i){if(se(i,[t]))return null;throw j(i)??i}}async updateVersions(t,r){let n=encodeURIComponent(t),i=`${this.appsBasePath}/${n}/versions/update`;try{await this.client.post(i,{data:{items:r}})}catch(s){throw j(s)??s}}};o(pe,"AppHostingApi");var ee=pe;var ce=class ce{constructor(t){this.api=new ee(t)}getVersion(t,r){return this.api.getVersion(t,r)}uploadVersion(t,r,n,i,s){return this.api.uploadVersion(t,r,n,i,s)}async ensureApp(t,r,n){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,r,n),console.log(`\u2705 App '${t}' created`)}catch(i){if(H(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw i}}async publishVersion(t,r){await this.api.updateVersions(t,[{version:r,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,r){console.log(`\u{1F680} Publishing and activating version ${r}...`),await this.api.updateVersions(t,[{version:r,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${r} is now PUBLISHED and ACTIVE`)}async activateVersion(t,r){let n=null;try{n=await this.api.getActiveVersion(t)}catch{n=null}let i=n&&n.version!==r?n.version:void 0;return await this.api.updateVersions(t,[{version:r,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(t,r,n,i,s,a,p=!1){console.log(`
2
+ import{a as o,e as Ge}from"../chunk-A5ASLC6T.js";import{writeSync as Bi}from"fs";import{Command as Yi}from"commander";var Be="https://docs.cognite.com/cdf/access/";function F(e){return e!==null&&typeof e=="object"}o(F,"isRecord");function B(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(B,"isHttpError");function Un(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
3
+ See: ${Be}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
4
+ See: ${Be}`;default:return}}o(Un,"httpStatusHint");function V(e){let t=e instanceof Error?e:new Error(String(e));if(!B(t))return null;let n=Un(t.status);return n?Object.assign(new Error(`${t.message}
5
+ ${n}`),{cause:t}):null}o(V,"enrichedHttpError");function Ln(e){if(!F(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(F(n)){let r=n.error;if(F(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}o(Ln,"findMissingArray");function Nn(e,t){if(!B(e)||e.status!==400)return!1;let n=Ln(e);return n?n.some(r=>F(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}o(Nn,"isMissingExternalIdError");function pe(e,t){return B(e)&&e.status===404||Nn(e,t)}o(pe,"isNotFoundError");var Je=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Xe=["ACTIVE","PREVIEW"],le=class le extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};o(le,"AppVersionNotFoundError");var E=le;function ze(e,t){return e.includes(t)}o(ze,"includesValue");function jn(e){return ze(Je,e)}o(jn,"isAppVersionLifecycleState");function Kn(e){return ze(Xe,e)}o(Kn,"isAppVersionAlias");function Mn(e){return typeof e.version=="string"&&jn(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||Kn(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(Mn,"isAppVersion");function Ye(e){if(!F(e))throw new Error("Invalid version response: not an object");if(!Mn(e))throw new Error("Invalid version response: missing or malformed fields");return e}o(Ye,"parseAppVersion");var me=class me{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:r}]}})}catch(i){throw V(i)??i}}async uploadVersion(t,n,r,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),i),a.append("version",n),a.append("entryPath",s);let c=encodeURIComponent(t),p=`${this.appsBasePath}/${c}/versions`,l=await this.client.authenticate(),m=`${this.client.getBaseUrl()}${p}`,d=new AbortController,u=setTimeout(()=>d.abort(),300*1e3),f;try{f=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${l}`},body:a,signal:d.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?new Error("Upload timed out after 5 minutes"):g}finally{clearTimeout(u)}if(!f.ok){let g=await f.text(),T=g;try{let _=JSON.parse(g);if(F(_)){let I=_.error;if(typeof I=="string")T=I;else if(F(I)){let $=I.message,y=I.code;T=typeof $=="string"?$:y!=null?`Unknown error (code: ${y})`:g}else{let $=_.message;T=typeof $=="string"?$:g}}}catch{}let D=f.headers.get("x-request-id"),Z=D?` | X-Request-ID: ${D}`:"",M=Object.assign(new Error(`Upload failed: ${f.status} \u2014 ${T}${Z}`),{status:f.status});throw V(M)??M}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),i=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${i}`;try{let a=await this.client.get(s);return Ye(a.data)}catch(a){throw pe(a,[t,n])?new E(t,n):V(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/active`;try{let i=await this.client.get(r);return Ye(i.data)}catch(i){if(pe(i,[t]))return null;throw V(i)??i}}async updateVersions(t,n){let r=encodeURIComponent(t),i=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(i,{data:{items:n}})}catch(s){throw V(s)??s}}};o(me,"AppHostingApi");var ee=me;var de=class de{constructor(t){this.api=new ee(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,i,s){return this.api.uploadVersion(t,n,r,i,s)}async ensureApp(t,n,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,r),console.log(`\u2705 App '${t}' created`)}catch(i){if(B(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw i}}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{alias:{setNull:!0}}}])}async activateVersion(t,n){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let i=r&&r.version!==n?r.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(t,n,r,i,s,a,c=!1){console.log(`
6
6
  \u{1F680} Deploying application via App Hosting API...
7
- `);try{await this.ensureApp(t,r,n),await this.uploadVersion(t,i,s,a),p&&await this.publishAndActivate(t,i),console.log(`
8
- \u2705 Deployment successful!`)}catch(c){let l=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${l}`),{cause:c})}}};o(ce,"AppHostingClient");var h=ce;import{existsSync as Kr,readFileSync as jr}from"fs";import{resolve as Mr}from"path";import{array as Ir,boolean as Tr,check as Be,forward as Ge,literal as $r,maxLength as Fr,minLength as Or,nonEmpty as M,object as Ye,optional as D,picklist as Rr,pipe as I,safeParse as _r,string as E,url as Ur}from"valibot";var le=I(E(),M("must not be empty")),me=I(E(),M("must not be empty"),Fr(256,"must be 256 characters or fewer")),de=I(E(),M("must not be empty"),Ur("must be a valid URL")),ue=I(E(),M("must not be empty")),ge=I(E(),M("must not be empty")),Lr=I(Ye({org:ue,project:ge,baseUrl:de,deployClientId:D(E(),""),deploySecretName:D(E(),""),published:D(Tr(),!1),idpType:D(Rr(["cdf","entra_id"]),"cdf"),tenantId:D(E()),scope:D(E())}),Ge(Be(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),Ge(Be(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),Nr=Ye({name:le,externalId:me,versionTag:I(E(),M("must not be empty")),description:D(E(),""),deployments:I(Ir(Lr),Or(1,"must contain at least one deployment")),infra:D($r("appsApi"))});function fe(e){let t=_r(Nr,e);if(t.success)return t.output;let r=t.issues[0],n=r.path?.map(s=>s.key).join(".")??"",i=n?`"${n}" `:"";throw new Error(`app.json: ${i}${r.message}`)}o(fe,"validateAppConfig");function w(e,t={}){let{validator:r=fe,existsSync:n=Kr,readFileSync:i=jr}=t,s=Mr(e,"app.json");if(!n(s))throw new Error("No app.json found in current directory. Make sure you're running this command from your app's root directory.");let a=i(s,"utf-8"),p;try{p=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return r(p)}o(w,"loadAppConfig");import{CogniteClient as dn}from"@cognite/sdk";import{CogniteClient as Jr}from"@cognite/sdk";var Vr=o(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),r={};for(let[n,i]of Object.entries(t))if(typeof i=="string"){let s=n.toLowerCase().replace(/_/g,"-");r[s]=i}return r}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),Hr=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=Vr()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),Br=o(e=>{if(!e)return"";try{return new URL(e).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=e.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),Gr=o(async(e,t)=>{let r=`Basic ${btoa(`${e}:${t}`)}`,n=await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:r,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})});if(!n.ok){let s=await n.text();throw new Error(`Failed to get token from CDF: ${n.status} ${n.statusText}
9
- ${s}`)}let i=await n.json();if(!i.access_token)throw new Error("No access token returned from CDF authentication");return i.access_token},"getTokenCdf"),Yr=o(async(e,t,r,n,i)=>{let s;if(i)s=i;else{if(!n)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let l=Br(n);if(!l)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${n}`);s=`https://${l}.cognitedata.com/.default`}let a=`https://login.microsoftonline.com/${r}/oauth2/v2.0/token`,p=await fetch(a,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,client_secret:t,scope:s,grant_type:"client_credentials"})});if(!p.ok){let l=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
10
- ${l}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),ye=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:r,deploySecretName:n,idpType:i="cdf",tenantId:s,baseUrl:a,scope:p}=e,c=Hr(n);if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Yr(r,c,s,a,p)}return Gr(r,c)},"getToken");var B=o(async(e,t,r=process.env)=>{let n=await ye(e,r),i=r.COGNITE_BASE_URL??e.baseUrl,s=new Jr({appId:t,project:e.project,baseUrl:i,oidcTokenProvider:o(async()=>n,"oidcTokenProvider")});return await s.authenticate(),s},"getSdk");import en from"os";import tn from"path";import rn from"open";import{buildAuthorizationUrl as nn,calculatePKCECodeChallenge as on,discovery as sn,None as an,randomPKCECodeVerifier as pn,randomState as cn}from"openid-client";import Xr from"https";import{authorizationCodeGrant as qr}from"openid-client";function Je(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}o(Je,"escapeHtml");function he(e,t,r){let n=Je(t),i=Je(r);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
11
- <h1>${n}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
7
+ `);try{await this.ensureApp(t,n,r),await this.uploadVersion(t,i,s,a),c&&await this.publishAndActivate(t,i),console.log(`
8
+ \u2705 Deployment successful!`)}catch(p){let l=p instanceof Error?p.message:String(p);throw Object.assign(new Error(`Deployment failed: ${l}`),{cause:p})}}};o(de,"AppHostingClient");var h=de;import{existsSync as Qn,readFileSync as Zn}from"fs";import{resolve as er}from"path";import{array as Vn,boolean as Hn,check as We,forward as qe,literal as Gn,maxLength as Bn,minLength as Yn,nonEmpty as H,object as Qe,optional as U,picklist as Jn,pipe as O,safeParse as Xn,string as v,url as zn}from"valibot";var ue=O(v(),H("must not be empty")),ge=O(v(),H("must not be empty"),Bn(256,"must be 256 characters or fewer")),fe=O(v(),H("must not be empty"),zn("must be a valid URL")),ye=O(v(),H("must not be empty")),he=O(v(),H("must not be empty")),Wn=O(Qe({org:ye,project:he,baseUrl:fe,deployClientId:U(v(),""),deploySecretName:U(v(),""),published:U(Hn(),!1),idpType:U(Jn(["cdf","entra_id"]),"cdf"),tenantId:U(v())}),qe(We(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),qe(We(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),qn=Qe({name:ue,externalId:ge,versionTag:O(v(),H("must not be empty")),description:U(v(),""),deployments:O(Vn(Wn),Yn(1,"must contain at least one deployment")),infra:U(Gn("appsApi"))});function Ce(e){let t=Xn(qn,e);if(t.success)return t.output;let n=t.issues[0],r=n.path?.map(s=>s.key).join(".")??"",i=r?`"${r}" `:"";throw new Error(`app.json: ${i}${n.message}`)}o(Ce,"validateAppConfig");function C(e,t={}){let{validator:n=Ce,existsSync:r=Qn,readFileSync:i=Zn}=t,s=er(e,"app.json");if(!r(s))throw new Error("No app.json found in current directory. Make sure you're running this command from your app's root directory.");let a=i(s,"utf-8"),c;try{c=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return n(c)}o(C,"loadAppConfig");import{CogniteClient as br}from"@cognite/sdk";import{CogniteClient as sr}from"@cognite/sdk";var tr=o(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),n={};for(let[r,i]of Object.entries(t))if(typeof i=="string"){let s=r.toLowerCase().replace(/_/g,"-");n[s]=i}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),nr=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=tr()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),rr=o(e=>{if(!e)return"";try{return new URL(e).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=e.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),or=o(async(e,t)=>{let n=`Basic ${btoa(`${e}:${t}`)}`,r=await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:n,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})});if(!r.ok){let s=await r.text();throw new Error(`Failed to get token from CDF: ${r.status} ${r.statusText}
9
+ ${s}`)}let i=await r.json();if(!i.access_token)throw new Error("No access token returned from CDF authentication");return i.access_token},"getTokenCdf"),ir=o(async(e,t,n,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let i=rr(r);if(!i)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${r}`);let s=`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,a=`https://${i}.cognitedata.com/.default`,c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,client_secret:t,scope:a,grant_type:"client_credentials"})});if(!c.ok){let l=await c.text();throw new Error(`Failed to get token from Entra ID: ${c.status} ${c.statusText}
10
+ ${l}`)}let p=await c.json();if(!p.access_token)throw new Error("No access token returned from Entra ID authentication");return p.access_token},"getTokenEntra"),we=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:n,deploySecretName:r,idpType:i="cdf",tenantId:s,baseUrl:a}=e,c=nr(r);if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return ir(n,c,s,a)}return or(n,c)},"getToken");async function Y(e,t,n=process.env,r){let i=await we(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(c=>new sr(c)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i,"oidcTokenProvider")});return await a.authenticate(),a}o(Y,"getSdk");import ur from"os";import gr from"path";import fr from"open";import{buildAuthorizationUrl as yr,calculatePKCECodeChallenge as hr,discovery as Cr,None as wr,randomPKCECodeVerifier as Er,randomState as Sr}from"openid-client";import ar from"https";import{authorizationCodeGrant as cr}from"openid-client";function Ze(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}o(Ze,"escapeHtml");function Ee(e,t,n){let r=Ze(t),i=Ze(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
11
+ <h1>${r}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
12
12
  @keyframes checkmark {
13
13
  0% { transform: scale(0); }
14
14
  50% { transform: scale(1.2); }
@@ -16,40 +16,40 @@ ${l}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token
16
16
  }
17
17
  h1 { animation: checkmark 0.5s ease-out; }
18
18
  </style>`:""}
19
- </body></html>`}o(he,"generateHtml");async function zr(e,t,r,n,i,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await s.authorizationCodeGrant(r,a,{pkceCodeVerifier:n,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(he("success","Login Successful!","You can close this window and return to the terminal.")),{shouldClose:!0,tokens:p}}catch(p){let c=p instanceof Error?p:new Error(String(p));return t.writeHead(400,{"Content-Type":"text/html"}),t.end(he("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(zr,"handleCallback");function Wr(e){let t=e/6e4,r=Math.round(t*10)/10;return`${r} ${r===1?"minute":"minutes"}`}o(Wr,"formatTimeoutMinutes");function Xe(e,t,r,n,i,s={createServer:Xr.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:qr}){return new Promise((a,p)=>{let c,l=s.setTimeout(()=>{c?.close(),p(new Error(`Login timeout - no response received within ${Wr(e.loginTimeout)}`))},e.loginTimeout);c=s.createServer(t,async(m,d)=>{try{let u=await zr(m,d,r,n,i,s);u.shouldClose&&(s.clearTimeout(l),c?.close(),u.error?p(u.error):u.tokens?a(u.tokens):p(new Error("No tokens received")))}catch(u){s.clearTimeout(l),c?.close(),p(u instanceof Error?u:new Error(String(u)))}}),c.on("error",m=>{s.clearTimeout(l),m.code==="EADDRINUSE"?console.error(`\u274C Port ${e.port} is already in use.`):console.error(`\u274C Server error: ${m.message}`),p(m)}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}o(Xe,"startCallbackServer");import{execFileSync as Qr}from"child_process";import Ee from"fs";import qe from"path";function ze(e,t,r){return{key:r.readFileSync(e),cert:r.readFileSync(t)}}o(ze,"loadCertificates");function Zr(e,t,r,n){console.log("\u{1F510} Generating self-signed certificate for HTTPS..."),n.existsSync(e)||n.mkdirSync(e,{recursive:!0});try{return n.execFileSync("openssl",["req","-x509","-newkey","rsa:2048","-nodes","-sha256","-subj","/CN=localhost","-keyout",t,"-out",r,"-days","365"],{stdio:["ignore","pipe","ignore"]}),console.log("\u2705 Certificate generated and saved locally"),ze(t,r,n)}catch{throw new Error(`Failed to generate self-signed certificate. Make sure openssl is installed.
19
+ </body></html>`}o(Ee,"generateHtml");async function pr(e,t,n,r,i,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let c=await s.authorizationCodeGrant(n,a,{pkceCodeVerifier:r,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(Ee("success","Login Successful!","You can close this window and return to the terminal.")),{shouldClose:!0,tokens:c}}catch(c){let p=c instanceof Error?c:new Error(String(c));return t.writeHead(400,{"Content-Type":"text/html"}),t.end(Ee("error","Authentication Error",p.message)),{shouldClose:!0,error:p}}}o(pr,"handleCallback");function lr(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}o(lr,"formatTimeoutMinutes");function et(e,t,n,r,i,s={createServer:ar.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:cr}){return new Promise((a,c)=>{let p,l=s.setTimeout(()=>{p?.close(),c(new Error(`Login timeout - no response received within ${lr(e.loginTimeout)}`))},e.loginTimeout);p=s.createServer(t,async(m,d)=>{try{let u=await pr(m,d,n,r,i,s);u.shouldClose&&(s.clearTimeout(l),p?.close(),u.error?c(u.error):u.tokens?a(u.tokens):c(new Error("No tokens received")))}catch(u){s.clearTimeout(l),p?.close(),c(u instanceof Error?u:new Error(String(u)))}}),p.on("error",m=>{s.clearTimeout(l),m.code==="EADDRINUSE"?console.error(`\u274C Port ${e.port} is already in use.`):console.error(`\u274C Server error: ${m.message}`),c(m)}),p.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}o(et,"startCallbackServer");import{execFileSync as mr}from"child_process";import Se from"fs";import tt from"path";function nt(e,t,n){return{key:n.readFileSync(e),cert:n.readFileSync(t)}}o(nt,"loadCertificates");function dr(e,t,n,r){console.log("\u{1F510} Generating self-signed certificate for HTTPS..."),r.existsSync(e)||r.mkdirSync(e,{recursive:!0});try{return r.execFileSync("openssl",["req","-x509","-newkey","rsa:2048","-nodes","-sha256","-subj","/CN=localhost","-keyout",t,"-out",n,"-days","365"],{stdio:["ignore","pipe","ignore"]}),console.log("\u2705 Certificate generated and saved locally"),nt(t,n,r)}catch{throw new Error(`Failed to generate self-signed certificate. Make sure openssl is installed.
20
20
  On macOS: openssl is pre-installed
21
21
  On Linux: sudo apt-get install openssl
22
- On Windows: Install OpenSSL or use WSL`)}}o(Zr,"generateCertificate");function We(e,t={existsSync:Ee.existsSync,readFileSync:o(r=>Ee.readFileSync(r),"readFileSync"),mkdirSync:o((r,n)=>{Ee.mkdirSync(r,n)},"mkdirSync"),execFileSync:Qr}){let r=qe.join(e,"localhost-key.pem"),n=qe.join(e,"localhost-cert.pem");return t.existsSync(r)&&t.existsSync(n)?ze(r,n,t):Zr(e,r,n,t)}o(We,"getOrCreateCertificates");var ln={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:tn.join(en.homedir(),".cdf-login")},mn={open:rn,getOrCreateCertificates:We,startCallbackServer:Xe,discovery:sn,buildAuthorizationUrl:nn,randomPKCECodeVerifier:pn,calculatePKCECodeChallenge:on,randomState:cn,logger:console};async function Ze(e,t=ln,r){return r===void 0?Qe(e,t,mn):Qe(e,t,r)}o(Ze,"login");async function Qe(e,t,r){r.logger.log(`\u{1F510} Starting CDF login flow...
23
- `),r.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let n=await r.discovery(new URL(t.authority),t.clientId,void 0,an()),i=r.randomPKCECodeVerifier(),s=await r.calculatePKCECodeChallenge(i),a=r.randomState(),p={redirect_uri:t.redirectUri,scope:"openid profile email",code_challenge:s,code_challenge_method:"S256",state:a};e&&(p.organization_hint=e);let c=r.buildAuthorizationUrl(n,p).toString(),l=r.getOrCreateCertificates(t.certDir);e&&r.logger.log(`\u{1F3E2} Organization: ${e}`),r.logger.log(`\u{1F680} Opening browser for authentication...
24
- `);try{await r.open(c)}catch(m){let d=m instanceof Error?m.message:String(m);r.logger.error("\u274C Failed to open browser automatically."),r.logger.error(` Reason: ${d}`),r.logger.error(`Please open this URL manually:
25
- `),r.logger.error(c),r.logger.error("")}return r.startCallbackServer(t,l,n,i,a)}o(Qe,"loginImpl");async function T(e,t,r={}){let{login:n=Ze,getSdk:i=B,createClient:s=o(a=>new dn(a),"createClient")}=r;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await n(a),c=s({appId:t.appId,project:e.project,baseUrl:e.baseUrl,getToken:o(async()=>p.access_token,"getToken")});return await c.authenticate(),c}return i(e,t.appId)}o(T,"getClientForDeployment");import{existsSync as un}from"fs";import{resolve as gn}from"path";import{config as fn}from"dotenv";function $(e,t={existsSync:un,config:fn}){let r=gn(e,".env");t.existsSync(r)&&(console.log(`Loading environment variables from ${r}`),t.config({path:r}))}o($,"loadEnvFile");import et from"enquirer";var tt="Enter custom target...";function rt(e,t){let r=t.map((n,i)=>` ${i}: ${n.org}/${n.project}`).join(`
22
+ On Windows: Install OpenSSL or use WSL`)}}o(dr,"generateCertificate");function rt(e,t={existsSync:Se.existsSync,readFileSync:o(n=>Se.readFileSync(n),"readFileSync"),mkdirSync:o((n,r)=>{Se.mkdirSync(n,r)},"mkdirSync"),execFileSync:mr}){let n=tt.join(e,"localhost-key.pem"),r=tt.join(e,"localhost-cert.pem");return t.existsSync(n)&&t.existsSync(r)?nt(n,r,t):dr(e,n,r,t)}o(rt,"getOrCreateCertificates");var vr={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:gr.join(ur.homedir(),".cdf-login")},xr={open:fr,getOrCreateCertificates:rt,startCallbackServer:et,discovery:Cr,buildAuthorizationUrl:yr,randomPKCECodeVerifier:Er,calculatePKCECodeChallenge:hr,randomState:Sr,logger:console};async function it(e,t=vr,n){return n===void 0?ot(e,t,xr):ot(e,t,n)}o(it,"login");async function ot(e,t,n){n.logger.log(`\u{1F510} Starting CDF login flow...
23
+ `),n.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let r=await n.discovery(new URL(t.authority),t.clientId,void 0,wr()),i=n.randomPKCECodeVerifier(),s=await n.calculatePKCECodeChallenge(i),a=n.randomState(),c={redirect_uri:t.redirectUri,scope:"openid profile email",code_challenge:s,code_challenge_method:"S256",state:a};e&&(c.organization_hint=e);let p=n.buildAuthorizationUrl(r,c).toString(),l=n.getOrCreateCertificates(t.certDir);e&&n.logger.log(`\u{1F3E2} Organization: ${e}`),n.logger.log(`\u{1F680} Opening browser for authentication...
24
+ `);try{await n.open(p)}catch(m){let d=m instanceof Error?m.message:String(m);n.logger.error("\u274C Failed to open browser automatically."),n.logger.error(` Reason: ${d}`),n.logger.error(`Please open this URL manually:
25
+ `),n.logger.error(p),n.logger.error("")}return n.startCallbackServer(t,l,r,i,a)}o(ot,"loginImpl");async function x(e,t,n={}){let{login:r=it,getSdk:i=Y,createClient:s=o(a=>new br(a),"createClient")}=n;if(t.interactive){let a=t.orgHint||e.org||void 0,c=await r(a),p=s({appId:t.appId,project:e.project,baseUrl:e.baseUrl,getToken:o(async()=>c.access_token,"getToken")});return await p.authenticate(),p}return i(e,t.appId)}o(x,"getClientForDeployment");import st from"enquirer";var at="Enter custom target...";function ct(e,t){let n=t.map((r,i)=>` ${i}: ${r.org}/${r.project}`).join(`
26
26
  `);throw new Error(`Deployment "${e}" not found. Available deployments:
27
- ${r}`)}o(rt,"deploymentNotFoundError");function P(e,t){if(e.length===0)throw new Error("No deployments configured in app.json");if(t===void 0)return e[0];if(/^\d+$/.test(t)){let n=e[Number.parseInt(t)];if(n)return n;rt(t,e)}let r=e.find(n=>n.project===t||`${n.org}/${n.project}`===t);if(r)return r;rt(t,e)}o(P,"findDeployment");function F(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o(F,"getMissingCredentials");async function O(e,t){if(t.baseUrl&&t.project)return{org:t.org??"",project:t.project,baseUrl:t.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"};if(t.deployment!==void 0)return P(e.deployments,t.deployment);let r=[...e.deployments.map(s=>`${s.org}/${s.project}`),tt],{selected:n}=await et.prompt({type:"select",name:"selected",message:"Select deployment target",choices:r});if(n!==tt){let s=e.deployments.find(a=>`${a.org}/${a.project}`===n);if(s)return s;throw new Error(`Deployment "${n}" could not be resolved from app.json.`)}let i=await et.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:o(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:i.org||"",project:i.project,baseUrl:i.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}o(O,"resolveDeployment");function R(e){e.infra!=="appsApi"&&(console.error(`
27
+ ${n}`)}o(ct,"deploymentNotFoundError");function S(e,t){if(e.length===0)throw new Error("No deployments configured in app.json");if(t===void 0)return e[0];if(/^\d+$/.test(t)){let r=e[Number.parseInt(t)];if(r)return r;ct(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;ct(t,e)}o(S,"findDeployment");function b(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o(b,"getMissingCredentials");async function P(e,t){if(t.baseUrl&&t.project)return{org:t.org??"",project:t.project,baseUrl:t.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"};if(t.deployment!==void 0)return S(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),at],{selected:r}=await st.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==at){let s=e.deployments.find(a=>`${a.org}/${a.project}`===r);if(s)return s;throw new Error(`Deployment "${r}" could not be resolved from app.json.`)}let i=await st.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:o(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:i.org||"",project:i.project,baseUrl:i.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}o(P,"resolveDeployment");import{existsSync as Pr}from"fs";import{resolve as Ar}from"path";import{config as kr}from"dotenv";function A(e,t={existsSync:Pr,config:kr}){let n=Ar(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}o(A,"loadEnvFile");function k(e){e.infra!=="appsApi"&&(console.error(`
28
28
  \u26A0\uFE0F Legacy infrastructure is no longer supported.
29
29
 
30
30
  Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
31
31
  the old CDF Application Registry. This deploy path has been removed.
32
32
 
33
33
  To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
34
- `),process.exit(1))}o(R,"assertAppHostingInfra");async function yn(e){let t=process.cwd();$(t);let r=w(t);R(r);let n=e.interactive?await O(r,e):P(r.deployments,e.deployment);if(!e.interactive){let m=F(n);if(m.length>0)throw new Error(`Deployment ${n.org}/${n.project} is missing ${m.join(" and ")} in app.json. Use \`dune apps activate --interactive\` for browser-based authentication instead.`)}let i=await T(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),s=new h(i),{externalId:a,versionTag:p}=r,c;try{c=await s.getVersion(a,p)}catch(m){throw m instanceof C?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):m}if(c.alias==="ACTIVE"){console.log(` ${a} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${a} @ ${p}: version is ${c.lifecycleState} (terminal).`);c.lifecycleState==="DRAFT"&&(await s.publishVersion(a,p),console.log(`\u2713 Published ${a} @ ${p} is now PUBLISHED`));let{supersededVersion:l}=await s.activateVersion(a,p);console.log(`\u2713 Activated ${a} @ ${p} is now ACTIVE`),l&&console.log(` Superseded ${l} \u2192 PUBLISHED`)}o(yn,"handleActivate");function nt(e){return e.command("activate").description("Activate the current app version (publish if needed, then set ACTIVE alias)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
34
+ `),process.exit(1))}o(k,"assertAppHostingInfra");async function Dr(e){let t=process.cwd();A(t);let n=C(t);k(n);let r=e.interactive?await P(n,e):S(n.deployments,e.deployment);if(!e.interactive){let m=b(r);if(m.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${m.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let i=await x(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new h(i),{externalId:a,versionTag:c}=n,p;try{p=await s.getVersion(a,c)}catch(m){throw m instanceof E?new Error(`Version ${c} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):m}if(p.alias==="ACTIVE"){console.log(` ${a} @ ${c} is already ACTIVE \u2014 nothing to do.`);return}if(p.lifecycleState==="DEPRECATED"||p.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${a} @ ${c}: version is ${p.lifecycleState} (terminal).`);p.lifecycleState==="DRAFT"&&(await s.publishVersion(a,c),console.log(`\u2713 Published ${a} @ ${c} is now PUBLISHED`));let{supersededVersion:l}=await s.activateVersion(a,c);console.log(`\u2713 Activated ${a} @ ${c} is now ACTIVE`),l&&console.log(` Superseded ${l} \u2192 PUBLISHED`)}o(Dr,"handleActivate");function pt(e){return e.command("activate").description("Activate the current app version (publish if needed, then set ACTIVE alias)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
35
35
  Examples:
36
36
  npx @cognite/cli apps activate . Activate using env-var auth
37
- npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,r)=>yn(r))}o(nt,"registerActivateCommand");import{readdirSync as In}from"fs";import{basename as ut,dirname as Tn,normalize as $n,resolve as Y}from"path";import{fileURLToPath as Fn,pathToFileURL as On}from"url";import{Logger as Rn,runner as _n}from"hygen";import{safeParse as hn}from"valibot";function G(e,t){return r=>{let n=hn(t,r);return n.success?!0:`${e} ${n.issues[0].message}`}}o(G,"toPromptValidator");var ot={name:G("App name",me),displayName:G("Display name",le),baseUrl:G("Base URL",de),org:G("Org",ue),project:G("Project",ge)};function En(e,t){return e?async r=>{let n=t(r);return n===!0?e(r):n}:t}o(En,"composeValidators");function te(e){return e.map(t=>{if(!(t.name in ot))return t;let r=ot[t.name];return{...t,validate:En(t.validate,r)}})}o(te,"applySchemaValidators");import{basename as st}from"path";import at from"enquirer";function it(e){return e.replace(/[A-Z]/g,(t,r)=>r===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(it,"kebabCase");var wn={type:"confirm",name:"useSpecKit",message:["Enable spec-driven development?"," Adds the github/spec-kit slash commands (/speckit.specify, .clarify, .plan, .tasks, .implement)"," to your app for use in Claude Code or Cursor. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
38
- `),initial:!1};async function Cn(e){return!!(await e([wn])).useSpecKit}o(Cn,"promptForSpecKit");async function Sn(e,t,r){return e!==void 0?e:t?Cn(r):!1}o(Sn,"resolveSpecKit");function pt({isCurrentDir:e,dirName:t,onAppName:r,onUseSpecKit:n,presets:i={},specKit:s,prompt:a=at.prompt.bind(at)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(y=>y[1]!==void 0)),l=Object.keys(c).length>0,m=e?st(process.cwd()):t?st(t):null,d=l&&m!==null,u=!d&&m?p.map(y=>y.name==="name"?{...y,initial:m}:y):p,f=te(u),g=d?{...c,name:m}:c,b=new Set(Object.keys(g)),v=f.filter(y=>!b.has(y.name)),Z=v.findIndex(y=>y.name==="baseUrl"),K;if(Z!==-1){let y=v.filter(vr=>vr.name!=="baseUrl"),ie=y.length>0?await a(y):{},hr=typeof ie.cluster=="string"?ie.cluster:"",Er=typeof g.cluster=="string"?g.cluster:"",wr=`https://${(hr||Er).trim().replace(/\/+$/,"")||"api"}.cognitedata.com`,Cr=v[Z],Sr=await a([{...Cr,initial:wr}]);K={...ie,...Sr}}else K=v.length>0?await a(v):{};let U={...g,...K},x=typeof U.name=="string"?U.name:"";x&&r(x);let A=await Sn(s,v.length>0,a);return n?.(A),{...U,name:x,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:A}},"prompt")})}o(pt,"createAppPrompter");async function ct(e,t,r){let n=[];Object.values(t).some(s=>s!==void 0)&&r!==null&&n.push({key:"name",value:r,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&n.push({key:s,value:a,label:`--${it(s)}`});for(let{key:s,value:a,label:p}of n){let c=e.find(m=>m.name===s)?.validate;if(!c)continue;let l=await c(a);if(l!==!0)throw new Error(`Invalid ${p}: ${l}`)}}o(ct,"validatePresets");import{cpSync as xn,mkdirSync as lt,writeFileSync as Pn}from"fs";import{dirname as mt,resolve as L}from"path";import{fileURLToPath as bn}from"url";import{symlinkSync as vn}from"fs";function re({target:e,linkPath:t,label:r,symlink:n=vn}){try{return n(e,t),!0}catch(i){if(i instanceof Error&&"code"in i&&i.code==="EEXIST")return!0;let s=i instanceof Error?i.message:String(i);return console.warn(`\u26A0\uFE0F Could not create ${r} symlink:`,s),!1}}o(re,"symlinkOrWarn");var An=L(mt(bn(import.meta.url)),"..","..","_vendor","spec-kit"),kn={branch_numbering:"sequential"},Dn=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}];function dt({appDir:e,vendorDir:t=An}){let r=L(e,".specify"),n=L(r,"memory"),i=`prepare spec-kit install for appDir=${e}`;try{for(let{from:s,to:a}of Dn){let p=L(e,a);i=`copy ${s} to ${a}`,lt(mt(p),{recursive:!0}),xn(L(t,s),p,{recursive:!0})}i=`write init-options.json under specifyDir=${r}`,Pn(L(r,"init-options.json"),`${JSON.stringify(kn,null,2)}
39
- `),i=`link .specify/memory/constitution.md in specifyDir=${r}`,lt(n,{recursive:!0}),re({target:"../../AGENTS.md",linkPath:L(n,"constitution.md"),label:".specify/memory/constitution.md"})}catch(s){let a=s instanceof Error?s.message:String(s);throw new Error(`installSpecKit failed while ${i} (appDir=${e}, vendorDir=${t}): ${a}`,{cause:s})}}o(dt,"installSpecKit");var gt=Y(Tn(Fn(import.meta.url)),"..","..","_templates");async function Un(){let e=Y(gt,"app","new","prompt.js");return(await import(On(e).href)).default}o(Un,"loadPromptDefs");function Ln(e,t){return!e||t?null:$n(e)}o(Ln,"resolveDirName");function Nn(e,t,r){if(e)return{cwd:process.cwd(),display:"."};let n=t??r;if(!n)throw new Error("App creation completed without a target directory or name.");return{cwd:Y(process.cwd(),n),display:n}}o(Nn,"resolveAppLocation");function Kn(e,t,r){let n=` npm install
40
- npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=r?`
37
+ npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>Dr(n))}o(pt,"registerActivateCommand");import{readdirSync as Mr}from"fs";import{basename as xt,dirname as Vr,normalize as Hr,resolve as X}from"path";import{fileURLToPath as Gr,pathToFileURL as Br}from"url";import{Logger as Yr,runner as Jr}from"hygen";import{safeParse as Ir}from"valibot";function J(e,t){return n=>{let r=Ir(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}o(J,"toPromptValidator");var lt={name:J("App name",ge),displayName:J("Display name",ue),baseUrl:J("Base URL",fe),org:J("Org",ye),project:J("Project",he)};function Tr(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}o(Tr,"composeValidators");function te(e){return e.map(t=>{if(!(t.name in lt))return t;let n=lt[t.name];return{...t,validate:Tr(t.validate,n)}})}o(te,"applySchemaValidators");import{execFileSync as ne}from"child_process";function mt(e={}){let{execFileSync:t=ne}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(mt,"isGitInstalled");function dt(e,t={}){let{execFileSync:n=ne}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(dt,"isInsideGitRepo");function ut(e,t={}){let{execFileSync:n=ne}=t;n("git",["-C",e,"init"],{stdio:"pipe"}),n("git",["-C",e,"add","."],{stdio:"pipe"}),n("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}o(ut,"gitInitAndCommit");function gt(e={}){let{execFileSync:t=ne}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(gt,"gitUserEmail");import{basename as yt}from"path";import ht from"enquirer";function ft(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(ft,"kebabCase");var $r={type:"confirm",name:"useSpecKit",message:["Enable spec-driven development?"," Adds the github/spec-kit slash commands (/speckit.specify, .clarify, .plan, .tasks, .implement)"," to your app for use in Claude Code or Cursor. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
38
+ `),initial:!1};async function Fr(e){return!!(await e([$r])).useSpecKit}o(Fr,"promptForSpecKit");async function Or(e,t,n){return e!==void 0?e:t?Fr(n):!1}o(Or,"resolveSpecKit");function Ct({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:i={},specKit:s,prompt:a=ht.prompt.bind(ht)}){return()=>({prompt:o(async c=>{if(!Array.isArray(c))return a([c]);let p=Object.fromEntries(Object.entries(i).filter(y=>y[1]!==void 0)),l=Object.keys(p).length>0,m=e?yt(process.cwd()):t?yt(t):null,d=l&&m!==null,u=!d&&m?c.map(y=>y.name==="name"?{...y,initial:m}:y):c,f=te(u),g=d?{...p,name:m}:p,T=new Set(Object.keys(g)),D=f.filter(y=>!T.has(y.name)),Z=D.findIndex(y=>y.name==="baseUrl"),M;if(Z!==-1){let y=D.filter(_n=>_n.name!=="baseUrl"),ce=y.length>0?await a(y):{},Tn=typeof ce.cluster=="string"?ce.cluster:"",$n=typeof g.cluster=="string"?g.cluster:"",Fn=`https://${(Tn||$n).trim().replace(/\/+$/,"")||"api"}.cognitedata.com`,On=D[Z],Rn=await a([{...On,initial:Fn}]);M={...ce,...Rn}}else M=D.length>0?await a(D):{};let _={...g,...M},I=typeof _.name=="string"?_.name:"";I&&n(I);let $=await Or(s,D.length>0,a);return r?.($),{..._,name:I,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:$}},"prompt")})}o(Ct,"createAppPrompter");async function wt(e,t,n){let r=[];Object.values(t).some(s=>s!==void 0)&&n!==null&&r.push({key:"name",value:n,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&r.push({key:s,value:a,label:`--${ft(s)}`});for(let{key:s,value:a,label:c}of r){let p=e.find(m=>m.name===s)?.validate;if(!p)continue;let l=await p(a);if(l!==!0)throw new Error(`Invalid ${c}: ${l}`)}}o(wt,"validatePresets");import{cpSync as _r,mkdirSync as Et,writeFileSync as Ur}from"fs";import{dirname as St,resolve as L}from"path";import{fileURLToPath as Lr}from"url";import{symlinkSync as Rr}from"fs";function re({target:e,linkPath:t,label:n,symlink:r=Rr}){try{return r(e,t),!0}catch(i){if(i instanceof Error&&"code"in i&&i.code==="EEXIST")return!0;let s=i instanceof Error?i.message:String(i);return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,s),!1}}o(re,"symlinkOrWarn");var Nr=L(St(Lr(import.meta.url)),"..","..","_vendor","spec-kit"),jr={branch_numbering:"sequential"},Kr=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}];function vt({appDir:e,vendorDir:t=Nr}){let n=L(e,".specify"),r=L(n,"memory"),i=`prepare spec-kit install for appDir=${e}`;try{for(let{from:s,to:a}of Kr){let c=L(e,a);i=`copy ${s} to ${a}`,Et(St(c),{recursive:!0}),_r(L(t,s),c,{recursive:!0})}i=`write init-options.json under specifyDir=${n}`,Ur(L(n,"init-options.json"),`${JSON.stringify(jr,null,2)}
39
+ `),i=`link .specify/memory/constitution.md in specifyDir=${n}`,Et(r,{recursive:!0}),re({target:"../../AGENTS.md",linkPath:L(r,"constitution.md"),label:".specify/memory/constitution.md"})}catch(s){let a=s instanceof Error?s.message:String(s);throw new Error(`installSpecKit failed while ${i} (appDir=${e}, vendorDir=${t}): ${a}`,{cause:s})}}o(vt,"installSpecKit");var bt=X(Vr(Gr(import.meta.url)),"..","..","_templates");async function Xr(){let e=X(bt,"app","new","prompt.js");return(await import(Br(e).href)).default}o(Xr,"loadPromptDefs");function zr(e,t){return!e||t?null:Hr(e)}o(zr,"resolveDirName");function Wr(e,t,n){if(e)return{cwd:process.cwd(),display:"."};let r=t??n;if(!r)throw new Error("App creation completed without a target directory or name.");return{cwd:X(process.cwd(),r),display:r}}o(Wr,"resolveAppLocation");function qr(e,t,n){let r=` npm install
40
+ npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=n?`
41
41
  To start spec-driven development:
42
42
  Run /speckit.specify in Claude Code or Cursor and describe your app.
43
- `:"",p=` # Or fully non-interactive (deploys first target from app.json):
43
+ `:"",c=` # Or fully non-interactive (deploys first target from app.json):
44
44
  npx @cognite/cli apps deploy`;if(e){console.log(`
45
45
  \u2705 App created successfully in current directory!
46
46
 
47
47
  Next steps:
48
- ${n}
48
+ ${r}
49
49
  ${a}
50
50
  ${i}
51
51
  ${s}
52
- ${p}
52
+ ${c}
53
53
  `);return}console.log(`
54
54
  \u2705 App created successfully!
55
55
 
@@ -57,14 +57,14 @@ To open in Cursor:
57
57
  cursor "${t}"
58
58
  Or:
59
59
  cd "${t}"
60
- ${n}
60
+ ${r}
61
61
  ${a}
62
62
  ${i}
63
63
  cd "${t}"
64
64
  ${s}
65
- ${p}
66
- `)}o(Kn,"printSuccessMessage");async function jn(e){try{let{execSkillsCli:t,pullAllArgs:r}=await import("../skills-GQ5TZKCM.js");console.log("\u{1F9E0} Pulling skills into your app..."),t(r(),{cwd:e,timeout:3e4,stdio:["pipe","pipe","inherit"]});let n=Y(e,".agents","skills"),i=0;try{i=In(n).length}catch{console.warn(`Skills directory not found after pull \u2014 no skills may have been installed (expected: ${n})`)}let s=i>0?`${i} skills`:"skills";console.log(`\u2705 Installed ${s} successfully to
67
- ${n}`)}catch(t){let r=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",r)}}o(jn,"pullSkillsInto");async function Mn(e,t){let r=e==="."||e==="./",n=Ln(e,r),i=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await Un(),c=te(p),l=r?ut(process.cwd()):n?ut(n):null;await ct(c,a,l);let m=pt({isCurrentDir:r,dirName:n,onAppName:o(u=>{i=u},"onAppName"),onUseSpecKit:o(u=>{s=u},"onUseSpecKit"),presets:a,specKit:t.specKit});await _n(["app","new"],{templates:gt,cwd:process.cwd(),logger:new Rn(console.log.bind(console)),createPrompter:m,debug:!!process.env.DEBUG});let d=Nn(r,n,i);re({target:"AGENTS.md",linkPath:Y(d.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&dt({appDir:d.cwd}),Kn(r,d.display,s),await jn(d.cwd)}o(Mn,"handleCreate");function ft(e){return e.command("create").description("Create a new application.").argument("[directory]","Target directory (. for current, or subdirectory name)").option("--display-name <name>","App display name (skips the prompt)").option("--description <description>","App description (skips the prompt)").option("--org <org>","Deployment org (skips the prompt)").option("--project <project>","Deployment project (skips the prompt)").option("--cluster <cluster>","CDF cluster, e.g. greenfield (skips the prompt)").option("--base-url <url>","CDF base URL, e.g. https://greenfield.cognitedata.com (skips the prompt; defaults to cluster-derived URL when omitted)").option("--spec-kit","Install spec-kit slash commands (skips the prompt)").option("--no-spec-kit","Skip spec-kit installation (skips the prompt)").addHelpText("after",`
65
+ ${c}
66
+ `)}o(qr,"printSuccessMessage");async function Qr(e){try{let{execSkillsCli:t,pullAllArgs:n}=await import("../skills-GQ5TZKCM.js");console.log("\u{1F9E0} Pulling skills into your app..."),t(n(),{cwd:e,timeout:3e4,stdio:["pipe","pipe","inherit"]});let r=X(e,".agents","skills"),i=0;try{i=Mr(r).length}catch{console.warn(`Skills directory not found after pull \u2014 no skills may have been installed (expected: ${r})`)}let s=i>0?`${i} skills`:"skills";console.log(`\u2705 Installed ${s} successfully to
67
+ ${r}`)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}o(Qr,"pullSkillsInto");function Zr(e,t={}){let{isGitInstalled:n=mt,isInsideGitRepo:r=dt,gitInitAndCommit:i=ut}=t;if(!n()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!r(e)){console.log("Initialising git repository...");try{i(e)}catch(s){let c=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",c)}}}o(Zr,"maybeInitGit");async function eo(e,t){let n=e==="."||e==="./",r=zr(e,n),i=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},c=await Xr(),p=te(c),l=n?xt(process.cwd()):r?xt(r):null;await wt(p,a,l);let m=Ct({isCurrentDir:n,dirName:r,onAppName:o(u=>{i=u},"onAppName"),onUseSpecKit:o(u=>{s=u},"onUseSpecKit"),presets:a,specKit:t.specKit});await Jr(["app","new"],{templates:bt,cwd:process.cwd(),logger:new Yr(console.log.bind(console)),createPrompter:m,debug:!!process.env.DEBUG});let d=Wr(n,r,i);re({target:"AGENTS.md",linkPath:X(d.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&vt({appDir:d.cwd}),await Qr(d.cwd),Zr(d.cwd),qr(n,d.display,s)}o(eo,"handleCreate");function Pt(e){return e.command("create").description("Create a new application.").argument("[directory]","Target directory (. for current, or subdirectory name)").option("--display-name <name>","App display name (skips the prompt)").option("--description <description>","App description (skips the prompt)").option("--org <org>","Deployment org (skips the prompt)").option("--project <project>","Deployment project (skips the prompt)").option("--cluster <cluster>","CDF cluster, e.g. greenfield (skips the prompt)").option("--base-url <url>","CDF base URL, e.g. https://greenfield.cognitedata.com (skips the prompt; defaults to cluster-derived URL when omitted)").option("--spec-kit","Install spec-kit slash commands (skips the prompt)").option("--no-spec-kit","Skip spec-kit installation (skips the prompt)").addHelpText("after",`
68
68
  Non-interactive use (CI, scripts, AI agents):
69
69
  Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
70
70
  to skip every prompt. Missing flags fall back to the interactive prompt.
@@ -77,14 +77,17 @@ Examples:
77
77
  --display-name "My App" --description "My app" \\
78
78
  --org cog-atlas --project atlas-greenfield --cluster greenfield \\
79
79
  --base-url https://greenfield.cognitedata.com
80
- Fully non-interactive`).action(Mn)}o(ft,"registerCreateCommand");import{readFile as Xn,unlink as qn}from"fs/promises";import{basename as zn}from"path";import ht from"fs";import Yn from"path";import _ from"fs";import S from"path";import{parseAndValidateManifestConfig as Vn}from"@cognite/app-sdk/vite";import{BlobReader as Hn,Uint8ArrayWriter as Bn,ZipWriter as Gn}from"@zip.js/zip.js";var we="package.json",Ce="package-lock.json",yt="manifest.json",Se=class Se{constructor(t="dist",r={}){this.distPath=S.isAbsolute(t)?t:S.join(process.cwd(),t),this.appRoot=S.dirname(this.distPath),this.requireLockFile=r.requireLockFile??!1}validateBuildDirectory(){if(!_.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=S.join(this.appRoot,we);if(!_.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);if(this.requireLockFile){let r=S.join(this.appRoot,Ce);if(!_.existsSync(r))throw new Error(`"${r}" not found. It is required for deployment.`)}}async createZip(t="app.zip",r=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let n=new Gn(new Bn,{level:9}),i=o(async(c,l)=>{await n.add(l,new Hn(await _.openAsBlob(c))),r&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=o(async c=>{let l=await _.promises.readdir(c,{withFileTypes:!0});for(let m of l){let d=S.join(c,m.name);m.isDirectory()?await s(d):await i(d,S.relative(this.distPath,d).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath),await i(S.join(this.appRoot,we),we);let c=S.join(this.appRoot,yt);if(_.existsSync(c)){let l=_.readFileSync(c,"utf-8");Vn(l,c),await i(c,yt)}this.requireLockFile&&await i(S.join(this.appRoot,Ce),Ce),a=await n.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}await _.promises.writeFile(t,a);let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}};o(Se,"ApplicationPackager");var N=Se;var ve=o(async(e,t,r)=>{let n=await new N(`${r}/dist`,{requireLockFile:!0}).createZip("app.zip",!0);try{let{externalId:i,name:s,description:a,versionTag:p}=t,c=await B(e,r),l=new h(c),m=ht.readFileSync(n),d=Yn.basename(n);await l.deploy(i,s,a,p,m,d,e.published)}finally{try{ht.unlinkSync(n)}catch{}}},"deploy");import{execSync as Jn}from"child_process";function xe(e,t=!0,r={execSync:Jn}){console.log("\u{1F4E6} Building app with npm..."),r.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"}),console.log("\u2705 Build successful")}o(xe,"buildApp");function Et(e,t){let{org:r,project:n,baseUrl:i}=e,s;try{s=new URL(i).hostname}catch{return null}let{externalId:a,versionTag:p}=t,c=new URLSearchParams({cluster:s,customAppVersion:p,workspace:"industrial-tools"});return`https://${r}.fusion.cognite.com/${n}/flows-apps/app/${encodeURIComponent(a)}?${c}`}o(Et,"generateFusionUrl");function wt(e,t,r){let n=r?"\u{1F680} Deploy (Interactive)":"\u{1F680} Deploy",i=r?`${t.project} @ ${t.baseUrl}`:`${t.org}/${t.project}`;console.log(["",n,"=".repeat(n.length),`App: ${e.name} (${e.externalId})`,`Version: ${e.versionTag}`,`Target: ${i}`,""].join(`
81
- `))}o(wt,"printDeployInfo");function Ct(e,t){console.log(`
82
- \u2705 Successfully deployed ${e.name} version ${e.versionTag} to ${t.org?`${t.org}/`:""}${t.project}`),console.log("\u{1F512} App is deployed in draft mode");let r=e.deployments.length>1?` -d ${t.project}`:"";console.log(`
83
- To publish: npx @cognite/cli apps publish .${r}`),console.log(`To activate: npx @cognite/cli apps activate .${r}`);let n=Et(t,e);n&&console.log(`
80
+ Fully non-interactive`).action(eo)}o(Pt,"registerCreateCommand");async function to(e){let t=process.cwd();A(t);let n=C(t);k(n);let r=e.interactive?await P(n,e):S(n.deployments,e.deployment);if(!e.interactive){let l=b(r);if(l.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${l.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let i=await x(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new h(i),{externalId:a,versionTag:c}=n,p;try{p=await s.getVersion(a,c)}catch(l){if(l instanceof E){console.log(` ${a} @ ${c} has not been deployed yet \u2014 nothing to deactivate.`);return}throw l}if(p.alias!=="ACTIVE"){console.log(` ${a} @ ${c} is not active (status: ${p.lifecycleState}) \u2014 nothing to deactivate.`);return}await s.deactivateVersion(a,c),console.log(`\u2713 Deactivated ${a} @ ${c} \u2014 active alias removed`)}o(to,"handleDeactivate");function At(e){return e.command("deactivate").description("Deactivate the app by removing its active version from service").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
81
+ Examples:
82
+ npx @cognite/cli apps deactivate . Deactivate using env-var auth
83
+ npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>to(n))}o(At,"registerDeactivateCommand");import{readFile as co,unlink as po}from"fs/promises";import{basename as lo}from"path";import Dt from"fs";import so from"path";import R from"fs";import w from"path";import{parseAndValidateManifestConfig as no}from"@cognite/app-sdk/vite";import{BlobReader as ro,Uint8ArrayWriter as oo,ZipWriter as io}from"@zip.js/zip.js";var ve="package.json",xe="package-lock.json",kt="manifest.json",be=".cognite",Pe=class Pe{constructor(t="dist"){this.distPath=w.isAbsolute(t)?t:w.join(process.cwd(),t),this.appRoot=w.dirname(this.distPath)}validateBuildDirectory(){if(!R.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=w.join(this.appRoot,ve);if(!R.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=w.join(this.appRoot,xe);if(!R.existsSync(n))throw new Error(`"${n}" not found. It is required for deployment.`)}async createZip(t="app.zip",n=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new io(new oo,{level:9}),i=o(async(p,l)=>{await r.add(l,new ro(await R.openAsBlob(p))),n&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=o(async p=>{let l=await R.promises.readdir(p,{withFileTypes:!0});for(let m of l){let d=w.join(p,m.name);m.isDirectory()?await s(d):await i(d,w.relative(this.distPath,d).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let p=w.join(this.appRoot,ve);await i(p,w.posix.join(be,ve));let l=w.join(this.appRoot,kt);if(R.existsSync(l)){let d=R.readFileSync(l,"utf-8");no(d,l),await i(l,w.posix.join(be,kt))}let m=w.join(this.appRoot,xe);await i(m,w.posix.join(be,xe)),a=await r.close()}catch(p){let l=p instanceof Error?p.message:String(p);throw new Error(`Failed to create zip: ${l}`)}await R.promises.writeFile(t,a);let c=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${c} MB)`),t}};o(Pe,"ApplicationPackager");var N=Pe;var Ae=o(async(e,t,n)=>{let r=await new N(`${n}/dist`).createZip("app.zip",!0);try{let{externalId:i,name:s,description:a,versionTag:c}=t,p=await Y(e,n),l=new h(p),m=Dt.readFileSync(r),d=so.basename(r);await l.deploy(i,s,a,c,m,d,e.published)}finally{try{Dt.unlinkSync(r)}catch{}}},"deploy");import{execSync as ao}from"child_process";function ke(e,t=!0,n={execSync:ao}){console.log("\u{1F4E6} Building app with npm..."),n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"}),console.log("\u2705 Build successful")}o(ke,"buildApp");function It(e,t){let{org:n,project:r,baseUrl:i}=e,s;try{s=new URL(i).hostname}catch{return null}let{externalId:a,versionTag:c}=t,p=new URLSearchParams({cluster:s,customAppVersion:c,workspace:"industrial-tools"});return`https://${n}.fusion.cognite.com/${r}/flows-apps/app/${encodeURIComponent(a)}?${p}`}o(It,"generateFusionUrl");function Tt(e,t,n){let r=n?"\u{1F680} Deploy (Interactive)":"\u{1F680} Deploy",i=n?`${t.project} @ ${t.baseUrl}`:`${t.org}/${t.project}`;console.log(["",r,"=".repeat(r.length),`App: ${e.name} (${e.externalId})`,`Version: ${e.versionTag}`,`Target: ${i}`,""].join(`
84
+ `))}o(Tt,"printDeployInfo");function $t(e,t){console.log(`
85
+ \u2705 Successfully deployed ${e.name} version ${e.versionTag} to ${t.org?`${t.org}/`:""}${t.project}`),console.log("\u{1F512} App is deployed in draft mode");let n=e.deployments.length>1?` -d ${t.project}`:"";console.log(`
86
+ To publish: npx @cognite/cli apps publish .${n}`),console.log(`To activate: npx @cognite/cli apps activate .${n}`);let r=It(t,e);r&&console.log(`
84
87
  \u{1F517} Open your app:
85
- ${n}`)}o(Ct,"printDeployResult");async function Wn(e,t,r,n,i){let s=F(t);if(s.length>0)throw new Error(`Deployment ${t.org}/${t.project} is missing ${s.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);wt(e,t,!1),n.skipBuild||xe(r),console.log(`
86
- \u{1F4E4} Deploying to ${t.org}/${t.project}...`),await i({...t,published:!1},{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},r),Ct(e,t)}o(Wn,"handleDeployNonInteractive");async function Qn(e,t,r,n){wt(e,t,!0),n.skipBuild||xe(r);let i=await T(t,{interactive:!0,appId:e.externalId,orgHint:n.org});console.log(`
87
- \u{1F4E4} Deploying to ${t.project}...`);let s=await new N(`${r}/dist`).createZip("app.zip",!0);try{let a=await Xn(s);await new h(i).deploy(e.externalId,e.name,e.description,e.versionTag,a,zn(s),!1),Ct(e,t)}finally{await qn(s).catch(()=>{})}}o(Qn,"handleDeployInteractive");async function Zn(e,t=process.cwd(),r={}){let{loadEnvFile:n=$,loadAppConfig:i=w,deploy:s=ve}=r;n(t);let a=i(t);if(R(a),e.interactive){let c=await O(a,e);await Qn(a,c,t,e);return}let p=P(a.deployments,e.deployment);await Wn(a,p,t,e,s)}o(Zn,"handleDeploy");function St(e){return e.command("deploy").description("Deploy your app to Cognite Data Fusion. Use --interactive for browser-based login (no env-var secrets required).").option("-d, --deployment <target>","Deployment target (index or project name)").option("--skip-build","Skip the build step",!1).option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
88
+ ${r}`)}o($t,"printDeployResult");async function mo(e,t,n,r,i){let s=b(t);if(s.length>0)throw new Error(`Deployment ${t.org}/${t.project} is missing ${s.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);Tt(e,t,!1),r.skipBuild||ke(n),console.log(`
89
+ \u{1F4E4} Deploying to ${t.org}/${t.project}...`),await i({...t,published:!1},{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},n),$t(e,t)}o(mo,"handleDeployNonInteractive");async function uo(e,t,n,r){Tt(e,t,!0),r.skipBuild||ke(n);let i=await x(t,{interactive:!0,appId:e.externalId,orgHint:r.org});console.log(`
90
+ \u{1F4E4} Deploying to ${t.project}...`);let s=await new N(`${n}/dist`).createZip("app.zip",!0);try{let a=await co(s);await new h(i).deploy(e.externalId,e.name,e.description,e.versionTag,a,lo(s),!1),$t(e,t)}finally{await po(s).catch(()=>{})}}o(uo,"handleDeployInteractive");async function go(e,t=process.cwd(),n={}){let{loadEnvFile:r=A,loadAppConfig:i=C,deploy:s=Ae}=n;r(t);let a=i(t);if(k(a),e.interactive){let p=await P(a,e);await uo(a,p,t,e);return}let c=S(a.deployments,e.deployment);await mo(a,c,t,e,s)}o(go,"handleDeploy");function Ft(e){return e.command("deploy").description("Deploy your app to Cognite Data Fusion. Use --interactive for browser-based login (no env-var secrets required).").option("-d, --deployment <target>","Deployment target (index or project name)").option("--skip-build","Skip the build step",!1).option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
88
91
  Environment (non-interactive):
89
92
  deployClientId and deploySecretName are configured per deployment in app.json.
90
93
  deploySecretName is the name of the environment variable that holds the client
@@ -98,38 +101,42 @@ Examples:
98
101
  npx @cognite/cli apps deploy -d my-project Deploy to project by name
99
102
  npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
100
103
  npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
101
- npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>Zn(t))}o(St,"registerDeployCommand");async function eo(e){let t=process.cwd();$(t);let r=w(t);R(r);let n=e.interactive?await O(r,e):P(r.deployments,e.deployment);if(!e.interactive){let l=F(n);if(l.length>0)throw new Error(`Deployment ${n.org}/${n.project} is missing ${l.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let i=await T(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),s=new h(i),{externalId:a,versionTag:p}=r,c;try{c=await s.getVersion(a,p)}catch(l){throw l instanceof C?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):l}if(c.alias==="ACTIVE"){console.log(` ${a} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="PUBLISHED"){console.log(` ${a} @ ${p} is already PUBLISHED \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${a} @ ${p}: version is ${c.lifecycleState} (terminal).`);await s.publishVersion(a,p),console.log(`\u2713 Published ${a} @ ${p} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}o(eo,"handlePublish");function vt(e){return e.command("publish").description("Publish the current app version (transition DRAFT \u2192 PUBLISHED)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
104
+ npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>go(t))}o(Ft,"registerDeployCommand");async function fo(e){let t=process.cwd();A(t);let n=C(t);k(n);let r=e.interactive?await P(n,e):S(n.deployments,e.deployment);if(!e.interactive){let l=b(r);if(l.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${l.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let i=await x(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new h(i),{externalId:a,versionTag:c}=n,p;try{p=await s.getVersion(a,c)}catch(l){throw l instanceof E?new Error(`Version ${c} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):l}if(p.alias==="ACTIVE"){console.log(` ${a} @ ${c} is already ACTIVE \u2014 nothing to do.`);return}if(p.lifecycleState==="PUBLISHED"){console.log(` ${a} @ ${c} is already PUBLISHED \u2014 nothing to do.`);return}if(p.lifecycleState==="DEPRECATED"||p.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${a} @ ${c}: version is ${p.lifecycleState} (terminal).`);await s.publishVersion(a,c),console.log(`\u2713 Published ${a} @ ${c} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}o(fo,"handlePublish");function Ot(e){return e.command("publish").description("Publish the current app version (transition DRAFT \u2192 PUBLISHED)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
102
105
  Examples:
103
106
  npx @cognite/cli apps publish . Publish using env-var auth
104
- npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,r)=>eo(r))}o(vt,"registerPublishCommand");function to(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(to,"describeStatus");async function ro(e){let t=process.cwd();$(t);let r=w(t);R(r);let n=e.interactive?await O(r,e):P(r.deployments,e.deployment);if(!e.interactive){let a=F(n);if(a.length>0)throw new Error(`Deployment ${n.org}/${n.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let i=await T(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),s=new h(i);console.log(""),console.log(`App: ${r.name} (${r.externalId})`),console.log(`Version: ${r.versionTag} (local)`);try{let a=await s.getVersion(r.externalId,r.versionTag),p=to(a);console.log(`Status: ${p}`),a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof C){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}o(ro,"handleStatus");function xt(e){return e.command("status").description("Show the deployment status of the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
107
+ npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>fo(n))}o(Ot,"registerPublishCommand");function yo(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(yo,"describeStatus");async function ho(e){let t=process.cwd();A(t);let n=C(t);k(n);let r=e.interactive?await P(n,e):S(n.deployments,e.deployment);if(!e.interactive){let a=b(r);if(a.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let i=await x(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new h(i);console.log(""),console.log(`App: ${n.name} (${n.externalId})`),console.log(`Version: ${n.versionTag} (local)`);try{let a=await s.getVersion(n.externalId,n.versionTag),c=yo(a);console.log(`Status: ${c}`),a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof E){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}o(ho,"handleStatus");function Rt(e){return e.command("status").description("Show the deployment status of the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
105
108
  Examples:
106
109
  npx @cognite/cli apps status . Status using env-var auth
107
- npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,r)=>ro(r))}o(xt,"registerStatusCommand");function Pt(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return ft(t),St(t),xt(t),vt(t),nt(t),Ne(t),t}o(Pt,"registerAppsCommand");import{existsSync as Vo,mkdirSync as Ho,writeFileSync as Bo}from"fs";import{dirname as Te,join as $e}from"path";import{execFile as oo}from"child_process";import{promisify as io}from"util";import{platform as no}from"os";function J(e={}){let{platform:t=no}=e;return t()==="darwin"}o(J,"isMacOS");var so="cognite-dune",ao=io(oo),po=o((e,t)=>ao(e,t),"defaultExecFile"),co=-25300,Tp=co&255;async function bt(e,t,r={}){if(!J(r))throw new Error("Keychain storage is only supported on macOS");let{execFile:n=po}=r;await n("security",["add-generic-password","-a",e,"-s",so,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(bt,"storeKeyInKeychain");import{pbkdf2 as uo,randomBytes as go}from"crypto";import{promisify as fo}from"util";import{CompactEncrypt as yo,base64url as ho,compactDecrypt as Kp}from"jose";var lo=new TextEncoder,mo=new TextDecoder,At={encode:o(e=>lo.encode(e),"encode"),decode:o(e=>mo.decode(e),"decode")};var Eo=fo(uo),Pe=6e5,wo="sha512",Co="PBKDF2-HMAC-SHA512",So=16,vo="A256GCM",xo=32,kt=2e6;async function Po(e,t,r){return await Eo(e,t,r,xo,wo)}o(Po,"deriveKey");async function Dt(e,t,r=Pe){if(!Number.isInteger(r)||r<1||r>kt)throw new Error(`Invalid iterations: must be an integer between 1 and ${kt}`);let n=go(So),i=await Po(t,n,r);return await new yo(At.encode(e)).setProtectedHeader({alg:"dir",enc:vo,kdf:Co,kdf_iter:r,kdf_salt:ho.encode(n)}).encrypt(i)}o(Dt,"encryptStringAsJwe");import{calculateJwkThumbprint as bo,exportJWK as Ao,exportPKCS8 as ko,exportSPKI as Do,generateKeyPair as Io}from"jose";async function It(){let{publicKey:e,privateKey:t}=await Io("EdDSA",{extractable:!0}),r=await ko(t),n=await Do(e),i=await Ao(e),s=await bo(i);return{privateKeyPem:r,publicKeyPem:n,kid:s}}o(It,"generateSigningKeyPair");import{existsSync as Zp,readdirSync as ec}from"fs";import{join as rc}from"path";import{homedir as To}from"os";import{join as Tt}from"path";function q(e={}){let{env:t=process.env,homedir:r=To}=e,n=t.DUNE_HOME?.trim()||Tt(r(),".dune");return{home:n,keysDir:Tt(n,"keys")}}o(q,"getConfig");var $t=".pub.pem",Ft=".key.jwe";var Ot=".meta.json";function Rt(e,t){let r=e.getUTCFullYear(),n=e.getUTCMonth()+t,i=new Date(Date.UTC(r,n+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(r,n,s))}o(Rt,"addMonthsClamped");function be(e){return e.toISOString().slice(0,10)}o(be,"formatIsoDate");function _t(e=new Date){return be(e)}o(_t,"todayIso");import $o,{Chalk as Fo}from"chalk";var Ae=new Fo({level:0});function Ut(e){return e.isTTY?$o:Ae}o(Ut,"chalkForStream");function Oo(e){return e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"")}o(Oo,"pemBodyOneLine");function Lt(e,t=Ae,r=new Date){let n=e.issuedAt??_t(r),i=Oo(e.publicKeyPem),s=" ",a=o((c,l)=>`${s}${t.cyan(c)}${t.dim(":")} ${l}
108
- `,"kv"),p="";return p+=`
110
+ npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>ho(n))}o(Rt,"registerStatusCommand");function _t(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return Pt(t),Ft(t),Rt(t),Ot(t),pt(t),At(t),Ge(t),t}o(_t,"registerAppsCommand");import{existsSync as li,mkdirSync as mi,writeFileSync as di}from"fs";import{dirname as Ue,join as Le}from"path";import{execFile as wo}from"child_process";import{promisify as Eo}from"util";import{platform as Co}from"os";function j(e={}){let{platform:t=Co}=e;return t()==="darwin"}o(j,"isMacOS");var Ut="cognite-flows",So=Eo(wo),Lt=o((e,t)=>So(e,t),"defaultExecFile"),vo=-25300,xo=vo&255;function bo(e){if(!(e instanceof Error)||!("code"in e)||e.code!==xo)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(bo,"isKeychainNotFoundError");async function Nt(e,t,n={}){if(!j(n))throw new Error("Keychain storage is only supported on macOS");let{execFile:r=Lt}=n;await r("security",["add-generic-password","-a",e,"-s",Ut,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(Nt,"storeKeyInKeychain");async function jt(e,t={}){if(!j(t))return null;let{execFile:n=Lt}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",Ut,"-w"]);return Buffer.from(r.trim(),"base64").toString("utf-8")}catch(r){if(bo(r))return null;throw r}}o(jt,"readKeyFromKeychain");import{pbkdf2 as ko,randomBytes as Do}from"crypto";import{promisify as Io}from"util";import{CompactEncrypt as To,base64url as $o,compactDecrypt as Ep}from"jose";var Po=new TextEncoder,Ao=new TextDecoder,Kt={encode:o(e=>Po.encode(e),"encode"),decode:o(e=>Ao.decode(e),"decode")};var Fo=Io(ko),De=6e5,Oo="sha512",Ro="PBKDF2-HMAC-SHA512",_o=16,Uo="A256GCM",Lo=32,Mt=2e6;async function No(e,t,n){return await Fo(e,t,n,Lo,Oo)}o(No,"deriveKey");async function Vt(e,t,n=De){if(!Number.isInteger(n)||n<1||n>Mt)throw new Error(`Invalid iterations: must be an integer between 1 and ${Mt}`);let r=Do(_o),i=await No(t,r,n);return await new To(Kt.encode(e)).setProtectedHeader({alg:"dir",enc:Uo,kdf:Ro,kdf_iter:n,kdf_salt:$o.encode(r)}).encrypt(i)}o(Vt,"encryptStringAsJwe");import{calculateJwkThumbprint as jo,exportJWK as Ko,exportPKCS8 as Mo,exportSPKI as Vo,generateKeyPair as Ho}from"jose";async function Ht(){let{publicKey:e,privateKey:t}=await Ho("EdDSA",{extractable:!0}),n=await Mo(t),r=await Vo(e),i=await Ko(e),s=await jo(i);return{privateKeyPem:n,publicKeyPem:r,kid:s}}o(Ht,"generateSigningKeyPair");import{existsSync as Bo,readdirSync as Yo,readFileSync as Jo}from"fs";import{join as oe}from"path";import{homedir as Go}from"os";import{join as Gt}from"path";function K(e={}){let{env:t=process.env,homedir:n=Go}=e,r=t.DUNE_HOME?.trim()||Gt(n(),".dune");return{home:r,keysDir:Gt(r,"keys")}}o(K,"getConfig");var ie=".pub.pem",Ie=".key.jwe",Xo=".pem",Te=".meta.json";function Bt(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"legacy-unencrypted-file":return`${e.path} (unencrypted \u2014 rotate)`;case"public-only":return"public-only (private key missing)"}}o(Bt,"formatLocalKeySource");function zo(e){return{existsSync:e.existsSync??Bo,readdirSync:e.readdirSync??Yo,readFileSync:e.readFileSync??((t,n)=>Jo(t,n)),isMacOS:e.isMacOS??(()=>j()),readKeyFromKeychain:e.readKeyFromKeychain??(t=>jt(t))}}o(zo,"resolveDeps");function Wo(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}o(Wo,"readEmailFromMeta");function qo(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(ie)):[]}o(qo,"publicKeyEntries");function Qo(e){return e.slice(0,-ie.length)}o(Qo,"kidFromPublicKeyFilename");async function Zo(e,t,n){if(n.isMacOS()&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let r=oe(t,`${e}${Ie}`);if(n.existsSync(r))return{kind:"encrypted-file",path:r};let i=oe(t,`${e}${Xo}`);return n.existsSync(i)?{kind:"legacy-unencrypted-file",path:i}:{kind:"public-only"}}o(Zo,"resolveSource");async function Yt(e=K().keysDir,t={}){let n=zo(t),r=new Set,i=qo(e,n).flatMap(s=>{let a=Qo(s);return!a||r.has(a)?[]:(r.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let c=await Zo(s,e,n),p=oe(e,`${s}${Te}`),l;try{l=Wo(n.readFileSync(p,"utf8"))}catch{}return{kid:s,source:c,publicKeyPath:oe(e,a),email:l}}))}o(Yt,"discoverLocalKeys");function Jt(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth()+t,i=new Date(Date.UTC(n,r+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(n,r,s))}o(Jt,"addMonthsClamped");function $e(e){return e.toISOString().slice(0,10)}o($e,"formatIsoDate");function Xt(e=new Date){return $e(e)}o(Xt,"todayIso");import ei,{Chalk as ti}from"chalk";var Fe=new ti({level:0});function zt(e){return e.isTTY?ei:Fe}o(zt,"chalkForStream");function ni(e){return e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"")}o(ni,"pemBodyOneLine");function Wt(e,t=Fe,n=new Date){let r=e.issuedAt??Xt(n),i=ni(e.publicKeyPem),s=" ",a=o((p,l)=>`${s}${t.cyan(p)}${t.dim(":")} ${l}
111
+ `,"kv"),c="";return c+=`
109
112
  ${t.bold("Add this entry to")} ${t.magenta("services/app-hosting/config/signing-keys.yaml")} ${t.bold("under")} ${t.cyan("public_keys:")}
110
113
 
111
- `,p+=`${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
112
- `,p+=a("public_key",t.green(i)),p+=a("email",t.yellow(e.email)),p+=a("capabilities",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),p+=a("issued_at",t.green(n)),p+=a("expires",t.green(e.expires)),p+=a("revoked_at",t.dim("null")),p}o(Lt,"renderRegistryEntry");import{email as Ro,pipe as _o,safeParse as Uo,string as Lo}from"valibot";var No=_o(Lo(),Ro());function z(e,t="email"){let r=e.trim();if(!r)throw new Error(`${t} is required`);if(!Uo(No,r).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return r}o(z,"parseEmail");function W(e,t="--expires"){let r=Number(e);if(!Number.isInteger(r)||r<1||r>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return r}o(W,"parseExpiryMonths");import Mo from"enquirer";import{execFileSync as Ko}from"child_process";function Nt(e={}){let{execFileSync:t=Ko}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(Nt,"gitUserEmail");var ne=3,Kt=`Key expiry in months (${1}-${12})`,jt="Email address for the registry entry",Mt=`Passphrase for the encrypted private key (min ${15} chars)`,Vt="Confirm passphrase",Ht=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),Bt=o(e=>`Passphrases do not match (attempt ${e}/${ne}).
113
- `,"passphraseMismatchMsg"),Gt=`Passphrase confirmation failed after ${ne} attempts`;async function Ie(e){return Mo.prompt(e)}o(Ie,"defaultPrompt");function Yt(e){return t=>{try{return e(t),!0}catch(r){return r instanceof Error?r.message:"Invalid"}}}o(Yt,"parserAsValidator");async function Jt(e={}){let{prompt:t=Ie}=e,{months:r}=await t({type:"input",name:"months",message:Kt,initial:String(6),validate:Yt(n=>W(n,"expiry"))});return W(r,"expiry")}o(Jt,"promptExpiryMonths");async function Xt(e={}){let{prompt:t=Ie,gitUserEmail:r=Nt}=e,{email:n}=await t({type:"input",name:"email",message:jt,initial:r(),validate:Yt(i=>z(i,"email"))});return z(n,"email")}o(Xt,"promptEmail");async function qt(e={}){let{prompt:t=Ie,stderr:r=process.stderr}=e;for(let n=1;n<=ne;n+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:Mt,validate:o(a=>a.length>=15?!0:Ht(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:Vt});if(i===s)return i;r.write(Bt(n))}throw new Error(Gt)}o(qt,"promptPassphrase");function Go(e){return{writeFileSync:e.writeFileSync??Bo,mkdirSync:e.mkdirSync??Ho,existsSync:e.existsSync??Vo,generateSigningKeyPair:e.generateSigningKeyPair??It,encryptStringAsJwe:e.encryptStringAsJwe??Dt,storeKeyInKeychain:e.storeKeyInKeychain??bt,isMacOS:e.isMacOS??J,promptExpiryMonths:e.promptExpiryMonths??Jt,promptEmail:e.promptEmail??Xt,promptPassphrase:e.promptPassphrase??qt}}o(Go,"resolveDeps");function Wt(e,t={}){let r=Go(t);e.command("keys").description("Manage code signing keys").command("generate").description("Generate an Ed25519 keypair for code signing").option("-o, --output <path>","Encrypted private key output path (forces file storage even on macOS)").option("--no-keychain","Skip macOS Keychain and write a passphrase-encrypted private key under ~/.dune/keys/ instead").option("-e, --expires <months>",`Validity in months (${1}-${12}); skips the interactive prompt`).option("--email <address>","Email address for the registry entry; skips the interactive prompt").action(i=>Jo(i,r))}o(Wt,"registerKeysCommand");function zt(e,t,r){let n=$e(q().keysDir,`${e}${$t}`);return r.mkdirSync(Te(n),{recursive:!0}),r.writeFileSync(n,t),n}o(zt,"writePublicKey");async function Yo(e,t,r,n,i){let s=n??$e(q().keysDir,`${e}${Ft}`);if(i.mkdirSync(Te(s),{recursive:!0}),i.existsSync(s))throw new Error(`Refusing to overwrite existing key at ${s}. Delete it first if you really want to regenerate: rm ${s}`);let a=await i.encryptStringAsJwe(t,r);return i.writeFileSync(s,a,{mode:384}),s}o(Yo,"writeEncryptedPrivateKey");async function Jo(e,t,r=new Date){let n=e.keychain!==!1&&t.isMacOS()&&!e.output,i=e.expires!==void 0?W(e.expires):await t.promptExpiryMonths(),s=be(Rt(r,i)),a=e.email!==void 0?z(e.email,"--email"):await t.promptEmail(),p=n?null:await t.promptPassphrase();process.stderr.write(`
114
+ `,c+=`${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
115
+ `,c+=a("public_key",t.green(i)),c+=a("email",t.yellow(e.email)),c+=a("capabilities",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),c+=a("issued_at",t.green(r)),c+=a("expires",t.green(e.expires)),c+=a("revoked_at",t.dim("null")),c}o(Wt,"renderRegistryEntry");import{email as ri,pipe as oi,safeParse as ii,string as si}from"valibot";var ai=oi(si(),ri());function W(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!ii(ai,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}o(W,"parseEmail");function q(e,t="--expires"){let n=Number(e);if(!Number.isInteger(n)||n<1||n>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return n}o(q,"parseExpiryMonths");import pi from"enquirer";var se=3,qt=`Key expiry in months (${1}-${12})`,Qt="Email address for the registry entry",Zt=`Passphrase for the encrypted private key (min ${15} chars)`,en="Confirm passphrase",tn=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),nn=o(e=>`Passphrases do not match (attempt ${e}/${se}).
116
+ `,"passphraseMismatchMsg"),rn=`Passphrase confirmation failed after ${se} attempts`;async function _e(e){return pi.prompt(e)}o(_e,"defaultPrompt");function on(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}o(on,"parserAsValidator");async function sn(e={}){let{prompt:t=_e}=e,{months:n}=await t({type:"input",name:"months",message:qt,initial:String(6),validate:on(r=>q(r,"expiry"))});return q(n,"expiry")}o(sn,"promptExpiryMonths");async function an(e={}){let{prompt:t=_e,gitUserEmail:n=gt}=e,{email:r}=await t({type:"input",name:"email",message:Qt,initial:n(),validate:on(i=>W(i,"email"))});return W(r,"email")}o(an,"promptEmail");async function cn(e={}){let{prompt:t=_e,stderr:n=process.stderr}=e;for(let r=1;r<=se;r+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:Zt,validate:o(a=>a.length>=15?!0:tn(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:en});if(i===s)return i;n.write(nn(r))}throw new Error(rn)}o(cn,"promptPassphrase");function ui(e){return{writeFileSync:e.writeFileSync??di,mkdirSync:e.mkdirSync??mi,existsSync:e.existsSync??li,generateSigningKeyPair:e.generateSigningKeyPair??Ht,encryptStringAsJwe:e.encryptStringAsJwe??Vt,storeKeyInKeychain:e.storeKeyInKeychain??Nt,isMacOS:e.isMacOS??j,promptExpiryMonths:e.promptExpiryMonths??sn,promptEmail:e.promptEmail??an,promptPassphrase:e.promptPassphrase??cn,discoverLocalKeys:e.discoverLocalKeys??(()=>Yt())}}o(ui,"resolveDeps");function ln(e,t={}){let n=ui(t),r=e.command("keys").description("Manage code signing keys");r.command("generate").description("Generate an Ed25519 keypair for code signing").option("-o, --output <path>","Encrypted private key output path (forces file storage even on macOS)").option("--no-keychain","Skip macOS Keychain and write a passphrase-encrypted private key under ~/.dune/keys/ instead").option("-e, --expires <months>",`Validity in months (${1}-${12}); skips the interactive prompt`).option("--email <address>","Email address for the registry entry; skips the interactive prompt").action(i=>yi(i,n)),r.command("list").description("List local signing identities and their storage location").action(()=>gi(n))}o(ln,"registerKeysCommand");async function gi(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
117
+ `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${K().keysDir}).
118
+ `);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,Bt(a.source),a.email??"\u2014"]),i=n.map((a,c)=>Math.max(a.length,...r.map(p=>p[c].length))),s=o(a=>a.map((c,p)=>c.padEnd(i[p])).join(" ").trimEnd(),"fmt");process.stdout.write(`${s(n)}
119
+ `);for(let a of r)process.stdout.write(`${s(a)}
120
+ `)}o(gi,"handleList");function pn(e,t,n){let r=Le(K().keysDir,`${e}${ie}`);return n.mkdirSync(Ue(r),{recursive:!0}),n.writeFileSync(r,t),r}o(pn,"writePublicKey");async function fi(e,t,n,r,i){let s=r??Le(K().keysDir,`${e}${Ie}`);if(i.mkdirSync(Ue(s),{recursive:!0}),i.existsSync(s))throw new Error(`Refusing to overwrite existing key at ${s}. Delete it first if you really want to regenerate: rm ${s}`);let a=await i.encryptStringAsJwe(t,n);return i.writeFileSync(s,a,{mode:384}),s}o(fi,"writeEncryptedPrivateKey");async function yi(e,t,n=new Date){let r=e.keychain!==!1&&t.isMacOS()&&!e.output,i=e.expires!==void 0?q(e.expires):await t.promptExpiryMonths(),s=$e(Jt(n,i)),a=e.email!==void 0?W(e.email,"--email"):await t.promptEmail(),c=r?null:await t.promptPassphrase();process.stderr.write(`
114
121
  Generating Ed25519 keypair...
115
122
 
116
- `);let{privateKeyPem:c,publicKeyPem:l,kid:m}=await t.generateSigningKeyPair();if(n){await t.storeKeyInKeychain(m,c);let f=zt(m,l,t);process.stderr.write(`Public key: ${f}
123
+ `);let{privateKeyPem:p,publicKeyPem:l,kid:m}=await t.generateSigningKeyPair();if(r){await t.storeKeyInKeychain(m,p);let f=pn(m,l,t);process.stderr.write(`Public key: ${f}
117
124
  `),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${m})
118
- `)}else{if(p===null)throw new Error("passphrase is required when not using Keychain");let f=await Yo(m,c,p,e.output,t),g=zt(m,l,t);process.stderr.write(`Public key: ${g}
119
- `),process.stderr.write(`Private key: ${f} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Pe.toLocaleString()})
125
+ `)}else{if(c===null)throw new Error("passphrase is required when not using Keychain");let f=await fi(m,p,c,e.output,t),g=pn(m,l,t);process.stderr.write(`Public key: ${g}
126
+ `),process.stderr.write(`Private key: ${f} (JWE, AES-256-GCM, PBKDF2-SHA512 x${De.toLocaleString()})
120
127
  `),t.isMacOS()||process.stderr.write(` (macOS Keychain integration is the default on darwin; on this OS we use the file.)
121
- `)}let d=$e(q().keysDir,`${m}${Ot}`);t.mkdirSync(Te(d),{recursive:!0}),t.writeFileSync(d,JSON.stringify({email:a}));let u=Ut(process.stderr);process.stderr.write(`
128
+ `)}let d=Le(K().keysDir,`${m}${Te}`);t.mkdirSync(Ue(d),{recursive:!0}),t.writeFileSync(d,JSON.stringify({email:a}));let u=zt(process.stderr);process.stderr.write(`
122
129
  Signing identity (kid): ${u.green(m)}
123
130
  `),process.stderr.write(`Expires: ${s} (${i} month${i===1?"":"s"} from today)
124
- `),process.stderr.write(Lt({kid:m,publicKeyPem:l,email:a,expires:s},u,r)),process.stderr.write(`
131
+ `),process.stderr.write(Wt({kid:m,publicKeyPem:l,email:a,expires:s},u,n)),process.stderr.write(`
125
132
  ${u.bold("Next:")} open a PR against the ${u.magenta("infrastructure")} repo with that block, then \`${u.cyan(`cognite sign -s ${m}`)}\`
126
- `)}o(Jo,"handleGenerate");var Qt=1e3,Xo=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function qo(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>typeof r=="boolean"?[t,r]:Xo.has(t)?[t,r]:[t,"[REDACTED]"]))}o(qo,"sanitize");function zo(e){let t=[],r=e;for(;r;)r.parent&&t.unshift(r.name()),r=r.parent;return t.join(" ")}o(zo,"getCommandPath");function Zt(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(Zt,"tryLoadAppConfig");function Fe(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(Fe,"commandFromArgv");function er(e,t,r=w){e.hook("postAction",async(n,i)=>{try{let s={command:zo(i),options:qo(i.opts()),success:!0,...Zt(r)};t.track("Flows.CLI.Command",s),await t.flush(Qt)}catch{}})}o(er,"instrument");async function tr(e,t,r=w){try{let n={command:Fe(t),options:{},success:!1,...Zt(r)};e.track("Flows.CLI.Command",n),await e.flush(Qt)}catch{}}o(tr,"trackFailure");var Wo="ERR_USE_AFTER_CLOSE";function nr(e){return e instanceof Error&&"code"in e&&e.code===Wo}o(nr,"isReadlineClosedError");function Qo(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(Qo,"isPlainObject");function Oe(e){return e==null||nr(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Qo(e)&&Object.keys(e).length===0)}o(Oe,"isPromptCancel");var rr=!1;function or(){rr||(rr=!0,process.on("uncaughtException",e=>{nr(e)&&(console.error(`
127
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{Oe(e)&&(console.error(`
128
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(or,"installCancelHandler");import ir from"mixpanel";var Zo="5c4d853e7c3b77b1eb4468d5329b278c",Q="cognite-cli",ei=2e3,sr={env:process.env,init:ir.init.bind(ir)},ti={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function Re(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(Re,"isTelemetryDisabled");function ri(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(ri,"isDebug");function ar(e={}){let t=e.env??sr.env,r=e.init??sr.init,n=e.packageName,i=e.cliVersion,s=ri(t);if(Re(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
129
- `),ti;let a,p=new Set;function c(){if(a)return a;try{return a=r(Zo,{geolocate:!1,keepAlive:!1}),a}catch{return}}return o(c,"getClient"),{track(l,m={}){let d=c();if(!d)return;let u={...m,applicationId:Q,...n&&{packageName:n},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform};s&&process.stderr.write(`[telemetry] track ${l} ${JSON.stringify(u)}
130
- `);let f=o(()=>{},"finish"),g=new Promise(b=>{f=b});p.add(g);try{d.track(l,u,f)}catch{f()}g.finally(()=>p.delete(g))},async flush(l=ei){if(p.size===0)return;let m,d=new Promise(u=>{m=setTimeout(u,l),m.unref?.()});try{await Promise.race([Promise.allSettled([...p]),d])}finally{m&&clearTimeout(m)}s&&process.stderr.write(`[telemetry] flush done (${p.size} still pending)
131
- `)}}}o(ar,"createTelemetry");var ni=1e3,oi="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",ii={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function si(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(si,"buildRelease");var ai="192.0.2.0";function pi(e){let t={...e.user,email:void 0,username:void 0,ip_address:ai,id:void 0};return{...e,user:t,server_name:void 0}}o(pi,"scrubPii");function pr(e={}){let t=e.env??process.env;if(Re(t))return ii;let r=si(e),n="production",i=null,s=null;function a(){return{dsn:oi,release:r,environment:n,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:Q},contexts:{cli:{applicationId:Q,node:process.version,platform:process.platform}}},beforeSend:pi}}o(a,"buildInitOptions");async function p(){return i||(s||(s=(async()=>{try{let c=e.sdk??await import("@sentry/node");return c.init(a()),i=c,c}catch{return null}})()),s)}return o(p,"ensureSdk"),{async captureError(c,l){try{let m=await p();if(!m)return;let d={level:"fatal"};l?.command&&(d.tags={command:l.command},d.contexts={cli:{applicationId:Q,node:process.version,platform:process.platform,command:l.command}}),m.captureException(c,d)}catch{}},async flush(c=ni){try{if(!i)return;await i.flush(c)}catch{}}}}o(pr,"createErrorReporter");import{mkdirSync as ci,readFileSync as li,writeFileSync as mi}from"fs";import{homedir as di}from"os";import{resolve as oe}from"path";import{debuglog as ui}from"util";import{lt as gi,parse as cr}from"semver";var fi="https://registry.npmjs.org/@cognite/cli/latest",yi=1500,lr="upgrade-check.json",mr=oe(process.env.XDG_CACHE_HOME||oe(di(),".cache"),"@cognite","cli"),_e=ui("cognite-dune");function hi(e,t){return!e||!t||!cr(e)||!cr(t)?!1:gi(e,t)}o(hi,"isOutdated");async function Ei({timeout:e=yi,registryUrl:t=fi,fetchImpl:r=globalThis.fetch}={}){if(typeof r!="function")return null;try{let n=await r(t,{signal:AbortSignal.timeout(e)});if(!n?.ok)return null;let i=await n.json();return typeof i?.version=="string"?i.version:null}catch(n){return _e("fetchLatestVersion failed (%s): %O",t,n),null}}o(Ei,"fetchLatestVersion");function wi(e=mr,t=864e5){try{let r=li(oe(e,lr),"utf-8"),n=JSON.parse(r);return typeof n.latest!="string"||typeof n.fetchedAt!="number"||Date.now()-n.fetchedAt>t?null:{latest:n.latest,fetchedAt:n.fetchedAt}}catch(r){return _e("readUpgradeCheckCache failed (%s): %O",e,r),null}}o(wi,"readUpgradeCheckCache");function Ci(e,t){try{ci(e,{recursive:!0});let r={latest:t,fetchedAt:Date.now()};mi(oe(e,lr),JSON.stringify(r))}catch(r){_e("writeUpgradeCheckCache failed (%s): %O",e,r)}}o(Ci,"writeUpgradeCheckCache");async function Si({cacheDir:e=mr,...t}={}){let r=await Ei(t);r&&Ci(e,r)}o(Si,"startBackgroundUpgradeCheck");function dr(e,{onOutdated:t,cacheDir:r,...n}={}){let i=wi(r);if(i){hi(e,i.latest)&&t?.(e,i.latest);return}Si({cacheDir:r,...n})}o(dr,"preActionUpgradeCheck");import{default as wl,chalkStderr as ur}from"chalk";function gr(e,t){let r=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],n=Math.max(...r.map(p=>[...p].length))+2,i="\u2500".repeat(n),s=o(p=>`\u2502 ${p}${" ".repeat(n-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...r.map(s),`\u2514${i}\u2518`].join(`
132
- `);return ur.bold.yellow(a)}o(gr,"formatUpgradeWarning");function Pi(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(Pi,"isDep0040Warning");var Le=process,bi=Le.emit.bind(Le);Le.emit=function(e,...t){return e==="warning"&&Pi(t[0])?!1:bi(e,...t)};or();var V=new xi;V.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.0.0-alpha.42").showHelpAfterError().configureOutput({writeOut:o(e=>vi(1,e),"writeOut")});V.hook("preAction",()=>{dr("1.0.0-alpha.42",{onOutdated:o((e,t)=>{console.warn(`
133
- ${gr(e,t)}
134
- `)},"onOutdated")})});Pt(V);Wt(V);var yr=ar({packageName:"@cognite/cli",cliVersion:"1.0.0-alpha.42"}),fr=pr({packageName:"@cognite/cli",cliVersion:"1.0.0-alpha.42"});er(V,yr);var Ue=process.argv.slice(2);V.parseAsync(Ue,{from:"user"}).catch(async e=>{await tr(yr,Ue),Oe(e)&&(console.error(`
135
- Cancelled.`),process.exit(130)),await fr.captureError(e,{command:Fe(Ue)}),await fr.flush(),console.error(e instanceof Error?`\u274C ${e.message}`:e),process.exit(1)});
133
+ `)}o(yi,"handleGenerate");var mn=1e3,hi=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function Ci(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:hi.has(t)?[t,n]:[t,"[REDACTED]"]))}o(Ci,"sanitize");function wi(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}o(wi,"getCommandPath");function dn(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(dn,"tryLoadAppConfig");function Ne(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(Ne,"commandFromArgv");function un(e,t,n=C){e.hook("postAction",async(r,i)=>{try{let s={command:wi(i),options:Ci(i.opts()),success:!0,...dn(n)};t.track("Flows.CLI.Command",s),await t.flush(mn)}catch{}})}o(un,"instrument");async function gn(e,t,n=C){try{let r={command:Ne(t),options:{},success:!1,...dn(n)};e.track("Flows.CLI.Command",r),await e.flush(mn)}catch{}}o(gn,"trackFailure");var Ei="ERR_USE_AFTER_CLOSE";function yn(e){return e instanceof Error&&"code"in e&&e.code===Ei}o(yn,"isReadlineClosedError");function Si(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(Si,"isPlainObject");function je(e){return e==null||yn(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Si(e)&&Object.keys(e).length===0)}o(je,"isPromptCancel");var fn=!1;function hn(){fn||(fn=!0,process.on("uncaughtException",e=>{yn(e)&&(console.error(`
134
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{je(e)&&(console.error(`
135
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(hn,"installCancelHandler");import Cn from"mixpanel";var vi="5c4d853e7c3b77b1eb4468d5329b278c",Q="cognite-cli",xi=2e3,wn={env:process.env,init:Cn.init.bind(Cn)},bi={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function Ke(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(Ke,"isTelemetryDisabled");function Pi(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(Pi,"isDebug");function En(e={}){let t=e.env??wn.env,n=e.init??wn.init,r=e.packageName,i=e.cliVersion,s=Pi(t);if(Ke(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
136
+ `),bi;let a,c=new Set;function p(){if(a)return a;try{return a=n(vi,{geolocate:!1,keepAlive:!1}),a}catch{return}}return o(p,"getClient"),{track(l,m={}){let d=p();if(!d)return;let u={...m,applicationId:Q,...r&&{packageName:r},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform};s&&process.stderr.write(`[telemetry] track ${l} ${JSON.stringify(u)}
137
+ `);let f=o(()=>{},"finish"),g=new Promise(T=>{f=T});c.add(g);try{d.track(l,u,f)}catch{f()}g.finally(()=>c.delete(g))},async flush(l=xi){if(c.size===0)return;let m,d=new Promise(u=>{m=setTimeout(u,l),m.unref?.()});try{await Promise.race([Promise.allSettled([...c]),d])}finally{m&&clearTimeout(m)}s&&process.stderr.write(`[telemetry] flush done (${c.size} still pending)
138
+ `)}}}o(En,"createTelemetry");var Ai=1e3,ki="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",Di={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function Ii(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(Ii,"buildRelease");var Ti="192.0.2.0";function $i(e){let t={...e.user,email:void 0,username:void 0,ip_address:Ti,id:void 0};return{...e,user:t,server_name:void 0}}o($i,"scrubPii");function Sn(e={}){let t=e.env??process.env;if(Ke(t))return Di;let n=Ii(e),r="production",i=null,s=null;function a(){return{dsn:ki,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:Q},contexts:{cli:{applicationId:Q,node:process.version,platform:process.platform}}},beforeSend:$i}}o(a,"buildInitOptions");async function c(){return i||(s||(s=(async()=>{try{let p=e.sdk??await import("@sentry/node");return p.init(a()),i=p,p}catch{return null}})()),s)}return o(c,"ensureSdk"),{async captureError(p,l){try{let m=await c();if(!m)return;let d={level:"fatal"};l?.command&&(d.tags={command:l.command},d.contexts={cli:{applicationId:Q,node:process.version,platform:process.platform,command:l.command}}),m.captureException(p,d)}catch{}},async flush(p=Ai){try{if(!i)return;await i.flush(p)}catch{}}}}o(Sn,"createErrorReporter");import{mkdirSync as Fi,readFileSync as Oi,writeFileSync as Ri}from"fs";import{homedir as _i}from"os";import{resolve as ae}from"path";import{debuglog as Ui}from"util";import{lt as Li,parse as vn}from"semver";var Ni="https://registry.npmjs.org/@cognite/cli/latest",ji=1500,xn="upgrade-check.json",bn=ae(process.env.XDG_CACHE_HOME||ae(_i(),".cache"),"@cognite","cli"),Me=Ui("cognite-flows");function Ki(e,t){return!e||!t||!vn(e)||!vn(t)?!1:Li(e,t)}o(Ki,"isOutdated");async function Mi({timeout:e=ji,registryUrl:t=Ni,fetchImpl:n=globalThis.fetch}={}){if(typeof n!="function")return null;try{let r=await n(t,{signal:AbortSignal.timeout(e)});if(!r?.ok)return null;let i=await r.json();return typeof i?.version=="string"?i.version:null}catch(r){return Me("fetchLatestVersion failed (%s): %O",t,r),null}}o(Mi,"fetchLatestVersion");function Vi(e=bn,t=864e5){try{let n=Oi(ae(e,xn),"utf-8"),r=JSON.parse(n);return typeof r.latest!="string"||typeof r.fetchedAt!="number"||Date.now()-r.fetchedAt>t?null:{latest:r.latest,fetchedAt:r.fetchedAt}}catch(n){return Me("readUpgradeCheckCache failed (%s): %O",e,n),null}}o(Vi,"readUpgradeCheckCache");function Hi(e,t){try{Fi(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};Ri(ae(e,xn),JSON.stringify(n))}catch(n){Me("writeUpgradeCheckCache failed (%s): %O",e,n)}}o(Hi,"writeUpgradeCheckCache");async function Gi({cacheDir:e=bn,...t}={}){let n=await Mi(t);n&&Hi(e,n)}o(Gi,"startBackgroundUpgradeCheck");function Pn(e,{onOutdated:t,cacheDir:n,...r}={}){let i=Vi(n);if(i){Ki(e,i.latest)&&t?.(e,i.latest);return}Gi({cacheDir:n,...r})}o(Pn,"preActionUpgradeCheck");import{default as Jl,chalkStderr as An}from"chalk";function kn(e,t){let n=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],r=Math.max(...n.map(c=>[...c].length))+2,i="\u2500".repeat(r),s=o(c=>`\u2502 ${c}${" ".repeat(r-1-[...c].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...n.map(s),`\u2514${i}\u2518`].join(`
139
+ `);return An.bold.yellow(a)}o(kn,"formatUpgradeWarning");function Ji(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(Ji,"isDep0040Warning");var He=process,Xi=He.emit.bind(He);He.emit=function(e,...t){return e==="warning"&&Ji(t[0])?!1:Xi(e,...t)};hn();var G=new Yi;G.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.1.0-alpha.48").showHelpAfterError().configureOutput({writeOut:o(e=>Bi(1,e),"writeOut")});G.hook("preAction",()=>{Pn("1.1.0-alpha.48",{onOutdated:o((e,t)=>{console.warn(`
140
+ ${kn(e,t)}
141
+ `)},"onOutdated")})});_t(G);ln(G);var In=En({packageName:"@cognite/cli",cliVersion:"1.1.0-alpha.48"}),Dn=Sn({packageName:"@cognite/cli",cliVersion:"1.1.0-alpha.48"});un(G,In);var Ve=process.argv.slice(2);G.parseAsync(Ve,{from:"user"}).catch(async e=>{await gn(In,Ve),je(e)&&(console.error(`
142
+ Cancelled.`),process.exit(130)),await Dn.captureError(e,{command:Ne(Ve)}),await Dn.flush(),console.error(e instanceof Error?`\u274C ${e.message}`:e),process.exit(1)});
@@ -1,4 +1,4 @@
1
- import { CogniteClient } from '@cognite/sdk';
1
+ import { CogniteClient, ClientOptions } from '@cognite/sdk';
2
2
 
3
3
  type Deployment = {
4
4
  org: string;
@@ -11,13 +11,6 @@ type Deployment = {
11
11
  idpType?: "cdf" | "entra_id";
12
12
  /** Tenant ID for Entra ID authentication. Required when idpType is "entra_id" */
13
13
  tenantId?: string;
14
- /**
15
- * OAuth scope for Entra ID authentication. When set, overrides the scope
16
- * that would otherwise be derived from baseUrl
17
- * (e.g. "https://<cluster>.cognitedata.com/.default").
18
- * Use this for non-standard CDF environments such as private-link deployments.
19
- */
20
- scope?: string;
21
14
  };
22
15
  type App = {
23
16
  externalId: string;
@@ -67,6 +60,9 @@ declare class AppHostingClient {
67
60
  publishVersion(appExternalId: string, version: string): Promise<void>;
68
61
  /** Publish the version and immediately set it as the ACTIVE alias. */
69
62
  publishAndActivate(appExternalId: string, version: string): Promise<void>;
63
+ getActiveVersion(appExternalId: string): Promise<AppVersion | null>;
64
+ /** Remove the ACTIVE alias from a version, taking it out of service without changing its lifecycle state. */
65
+ deactivateVersion(appExternalId: string, version: string): Promise<void>;
70
66
  /**
71
67
  * Set the ACTIVE alias on a version. Returns the version that was
72
68
  * previously active (if any) so callers can surface "Superseded X"
@@ -94,19 +90,17 @@ declare class AppHostingClient {
94
90
  *
95
91
  * Handles packaging of build directories into deployment-ready zip files.
96
92
  */
97
- interface ApplicationPackagerOptions {
98
- requireLockFile?: boolean;
99
- }
100
93
  declare class ApplicationPackager {
101
94
  private distPath;
102
95
  private appRoot;
103
- private requireLockFile;
104
- constructor(distDirectory?: string, options?: ApplicationPackagerOptions);
96
+ constructor(distDirectory?: string);
105
97
  validateBuildDirectory(): void;
106
98
  createZip(outputFilename?: string, verbose?: boolean): Promise<string>;
107
99
  }
108
100
 
109
- declare const getSdk: (deployment: Deployment, folder: string, env?: NodeJS.ProcessEnv) => Promise<CogniteClient>;
101
+ type Authenticatable = Pick<CogniteClient, 'authenticate'>;
102
+ declare function getSdk(deployment: Deployment, folder: string, env?: NodeJS.ProcessEnv): Promise<CogniteClient>;
103
+ declare function getSdk<C extends Authenticatable>(deployment: Deployment, folder: string, env: NodeJS.ProcessEnv, createClient: (opts: ClientOptions) => C): Promise<C>;
110
104
 
111
105
  /**
112
106
  * Get access token for deployment using the appropriate identity provider.
@@ -1,9 +1 @@
1
- import{a as s}from"../chunk-EI7MMDWY.js";import J from"fs";import ut from"path";var j="https://docs.cognite.com/cdf/access/";function f(e){return e!==null&&typeof e=="object"}s(f,"isRecord");function S(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}s(S,"isHttpError");function K(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
- See: ${j}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
3
- See: ${j}`;default:return}}s(K,"httpStatusHint");function w(e){let t=e instanceof Error?e:new Error(String(e));if(!S(t))return null;let n=K(t.status);return n?Object.assign(new Error(`${t.message}
4
- ${n}`),{cause:t}):null}s(w,"enrichedHttpError");function W(e){if(!f(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(f(n)){let r=n.error;if(f(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}s(W,"findMissingArray");function Z(e,t){if(!S(e)||e.status!==400)return!1;let n=W(e);return n?n.some(r=>f(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}s(Z,"isMissingExternalIdError");function x(e,t){return S(e)&&e.status===404||Z(e,t)}s(x,"isNotFoundError");var H=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],q=["ACTIVE","PREVIEW"],I=class I extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};s(I,"AppVersionNotFoundError");var C=I;function M(e,t){return e.includes(t)}s(M,"includesValue");function X(e){return M(H,e)}s(X,"isAppVersionLifecycleState");function Q(e){return M(q,e)}s(Q,"isAppVersionAlias");function tt(e){return typeof e.version=="string"&&X(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||Q(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}s(tt,"isAppVersion");function N(e){if(!f(e))throw new Error("Invalid version response: not an object");if(!tt(e))throw new Error("Invalid version response: missing or malformed fields");return e}s(N,"parseAppVersion");var T=class T{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:r}]}})}catch(o){throw w(o)??o}}async uploadVersion(t,n,r,o,i="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let c=new FormData;c.append("file",new Blob([new Uint8Array(r)]),o),c.append("version",n),c.append("entryPath",i);let l=encodeURIComponent(t),a=`${this.appsBasePath}/${l}/versions`,p=await this.client.authenticate(),h=`${this.client.getBaseUrl()}${a}`,d=new AbortController,Y=setTimeout(()=>d.abort(),300*1e3),y;try{y=await fetch(h,{method:"POST",headers:{Authorization:`Bearer ${p}`},body:c,signal:d.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?new Error("Upload timed out after 5 minutes"):g}finally{clearTimeout(Y)}if(!y.ok){let g=await y.text(),V=g;try{let v=JSON.parse(g);if(f(v)){let A=v.error;if(typeof A=="string")V=A;else if(f(A)){let E=A.message,B=A.code;V=typeof E=="string"?E:B!=null?`Unknown error (code: ${B})`:g}else{let E=v.message;V=typeof E=="string"?E:g}}}catch{}let U=y.headers.get("x-request-id"),G=U?` | X-Request-ID: ${U}`:"",O=Object.assign(new Error(`Upload failed: ${y.status} \u2014 ${V}${G}`),{status:y.status});throw w(O)??O}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),o=encodeURIComponent(n),i=`${this.appsBasePath}/${r}/versions/${o}`;try{let c=await this.client.get(i);return N(c.data)}catch(c){throw x(c,[t,n])?new C(t,n):w(c)??c}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/active`;try{let o=await this.client.get(r);return N(o.data)}catch(o){if(x(o,[t]))return null;throw w(o)??o}}async updateVersions(t,n){let r=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:n}})}catch(i){throw w(i)??i}}};s(T,"AppHostingApi");var $=T;var b=class b{constructor(t){this.api=new $(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,o,i){return this.api.uploadVersion(t,n,r,o,i)}async ensureApp(t,n,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,r),console.log(`\u2705 App '${t}' created`)}catch(o){if(S(o)&&o.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw o}}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}async activateVersion(t,n){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let o=r&&r.version!==n?r.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(t,n,r,o,i,c,l=!1){console.log(`
5
- \u{1F680} Deploying application via App Hosting API...
6
- `);try{await this.ensureApp(t,n,r),await this.uploadVersion(t,o,i,c),l&&await this.publishAndActivate(t,o),console.log(`
7
- \u2705 Deployment successful!`)}catch(a){let p=a instanceof Error?a.message:String(a);throw Object.assign(new Error(`Deployment failed: ${p}`),{cause:a})}}};s(b,"AppHostingClient");var P=b;import m from"fs";import u from"path";import{parseAndValidateManifestConfig as et}from"@cognite/app-sdk/vite";import{BlobReader as nt,Uint8ArrayWriter as rt,ZipWriter as ot}from"@zip.js/zip.js";var R="package.json",L="package-lock.json",z="manifest.json",D=class D{constructor(t="dist",n={}){this.distPath=u.isAbsolute(t)?t:u.join(process.cwd(),t),this.appRoot=u.dirname(this.distPath),this.requireLockFile=n.requireLockFile??!1}validateBuildDirectory(){if(!m.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=u.join(this.appRoot,R);if(!m.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);if(this.requireLockFile){let n=u.join(this.appRoot,L);if(!m.existsSync(n))throw new Error(`"${n}" not found. It is required for deployment.`)}}async createZip(t="app.zip",n=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new ot(new rt,{level:9}),o=s(async(a,p)=>{await r.add(p,new nt(await m.openAsBlob(a))),n&&console.log(` \u{1F4C4} ${p}`)},"addFile"),i=s(async a=>{let p=await m.promises.readdir(a,{withFileTypes:!0});for(let h of p){let d=u.join(a,h.name);h.isDirectory()?await i(d):await o(d,u.relative(this.distPath,d).replace(/\\/g,"/"))}},"addDir"),c;try{await i(this.distPath),await o(u.join(this.appRoot,R),R);let a=u.join(this.appRoot,z);if(m.existsSync(a)){let p=m.readFileSync(a,"utf-8");et(p,a),await o(a,z)}this.requireLockFile&&await o(u.join(this.appRoot,L),L),c=await r.close()}catch(a){let p=a instanceof Error?a.message:String(a);throw new Error(`Failed to create zip: ${p}`)}await m.promises.writeFile(t,c);let l=(c.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${l} MB)`),t}};s(D,"ApplicationPackager");var k=D;import{CogniteClient as lt}from"@cognite/sdk";var st=s(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),n={};for(let[r,o]of Object.entries(t))if(typeof o=="string"){let i=r.toLowerCase().replace(/_/g,"-");n[i]=o}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),it=s(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=st()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),at=s(e=>{if(!e)return"";try{return new URL(e).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=e.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),ct=s(async(e,t)=>{let n=`Basic ${btoa(`${e}:${t}`)}`,r=await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:n,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})});if(!r.ok){let i=await r.text();throw new Error(`Failed to get token from CDF: ${r.status} ${r.statusText}
8
- ${i}`)}let o=await r.json();if(!o.access_token)throw new Error("No access token returned from CDF authentication");return o.access_token},"getTokenCdf"),pt=s(async(e,t,n,r,o)=>{let i;if(o)i=o;else{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let p=at(r);if(!p)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${r}`);i=`https://${p}.cognitedata.com/.default`}let c=`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,client_secret:t,scope:i,grant_type:"client_credentials"})});if(!l.ok){let p=await l.text();throw new Error(`Failed to get token from Entra ID: ${l.status} ${l.statusText}
9
- ${p}`)}let a=await l.json();if(!a.access_token)throw new Error("No access token returned from Entra ID authentication");return a.access_token},"getTokenEntra"),_=s(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:n,deploySecretName:r,idpType:o="cdf",tenantId:i,baseUrl:c,scope:l}=e,a=it(r);if(o==="entra_id"){if(!i)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return pt(n,a,i,c,l)}return ct(n,a)},"getToken");var F=s(async(e,t,n=process.env)=>{let r=await _(e,n),o=n.COGNITE_BASE_URL??e.baseUrl,i=new lt({appId:t,project:e.project,baseUrl:o,oidcTokenProvider:s(async()=>r,"oidcTokenProvider")});return await i.authenticate(),i},"getSdk");var dt=s(async(e,t,n)=>{let r=await new k(`${n}/dist`,{requireLockFile:!0}).createZip("app.zip",!0);try{let{externalId:o,name:i,description:c,versionTag:l}=t,a=await F(e,n),p=new P(a),h=J.readFileSync(r),d=ut.basename(r);await p.deploy(o,i,c,l,h,d,e.published)}finally{try{J.unlinkSync(r)}catch{}}},"deploy");export{P as AppHostingClient,k as ApplicationPackager,dt as deploy,F as getSdk,_ as getToken};
1
+ import{a,b,c,d,e}from"../chunk-QOJVLP7E.js";export{a as AppHostingClient,b as ApplicationPackager,e as deploy,d as getSdk,c as getToken};
package/dist/index.d.ts CHANGED
@@ -1,4 +1,2 @@
1
- export { AppSdkAuthProvider, CDFConfig, DuneAuthProvider, DuneAuthProviderContext, DuneAuthProviderProps, DuneContextValue, EMPTY_SDK, createCDFSDK, getToken, useDune } from './auth/index.js';
2
- import 'react/jsx-runtime';
3
- import 'react';
1
+ export { App, AppHostingClient, ApplicationPackager, Deployment, deploy, getSdk, getToken } from './deploy/index.js';
4
2
  import '@cognite/sdk';
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}from"./chunk-QGJ3VKXY.js";import"./chunk-EI7MMDWY.js";export{p as AppSdkAuthProvider,m as DuneAuthProvider,f as DuneAuthProviderContext,e as EMPTY_SDK,r as createCDFSDK,o as getToken,t as useDune};
1
+ import{a as o,b as r,c as e,d as f,e as m}from"./chunk-QOJVLP7E.js";export{o as AppHostingClient,r as ApplicationPackager,m as deploy,f as getSdk,e as getToken};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cognite/cli",
3
- "version": "1.0.0-alpha.42",
3
+ "version": "1.1.0-alpha.48",
4
4
  "description": "CLI for Cognite Data Fusion",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Cognite",
@@ -18,21 +18,10 @@
18
18
  "import": "./dist/index.js",
19
19
  "default": "./dist/index.js"
20
20
  },
21
- "./auth": {
22
- "types": "./dist/auth/index.d.ts",
23
- "import": "./dist/auth/index.js",
24
- "default": "./dist/auth/index.js"
25
- },
26
21
  "./deploy": {
27
22
  "types": "./dist/deploy/index.d.ts",
28
23
  "import": "./dist/deploy/index.js",
29
24
  "default": "./dist/deploy/index.js"
30
- },
31
- "./vite": {
32
- "types": "./dist/vite/index.d.ts",
33
- "development": "./src/vite/index.ts",
34
- "import": "./dist/vite/index.js",
35
- "default": "./dist/vite/index.js"
36
25
  }
37
26
  },
38
27
  "bin": {
@@ -1,51 +0,0 @@
1
- import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import * as react from 'react';
3
- import { ReactNode } from 'react';
4
- import { CogniteClient } from '@cognite/sdk';
5
-
6
- interface AppSdkAuthProviderProps {
7
- children: ReactNode;
8
- loadingComponent?: ReactNode;
9
- errorComponent?: (error: string) => ReactNode;
10
- }
11
- /**
12
- * Auth provider for apps running in the new Fusion app host (dune-app-host).
13
- * Uses @cognite/app-sdk's Comlink handshake to connect to the host and obtain
14
- * tokens on-demand. Exposes the same DuneContextValue ({ sdk, isLoading,
15
- * error }) as DuneAuthProvider so useDune() works unchanged.
16
- */
17
- declare const AppSdkAuthProvider: ({ children, loadingComponent, errorComponent, }: AppSdkAuthProviderProps) => react_jsx_runtime.JSX.Element;
18
-
19
- interface DuneContextValue {
20
- sdk: CogniteClient;
21
- isLoading: boolean;
22
- error?: string;
23
- }
24
- declare const DuneAuthProviderContext: react.Context<DuneContextValue>;
25
- interface DuneAuthProviderProps {
26
- children: ReactNode;
27
- useIFrameAuthentication?: boolean;
28
- useLocalConfiguration?: {
29
- org: string;
30
- project: string;
31
- baseUrl: string;
32
- };
33
- loadingComponent?: ReactNode;
34
- errorComponent?: (error: string) => ReactNode;
35
- }
36
- declare const DuneAuthProvider: ({ children, loadingComponent, errorComponent, }: DuneAuthProviderProps) => react_jsx_runtime.JSX.Element;
37
-
38
- declare const useDune: () => DuneContextValue;
39
-
40
- interface CDFConfig {
41
- project: string;
42
- baseUrl: string;
43
- clientId: string;
44
- clientSecret: string;
45
- appId?: string;
46
- }
47
- declare const getToken: (clientId: string, clientSecret: string) => Promise<any>;
48
- declare const createCDFSDK: (config: CDFConfig) => Promise<CogniteClient>;
49
- declare const EMPTY_SDK: CogniteClient;
50
-
51
- export { AppSdkAuthProvider, type CDFConfig, DuneAuthProvider, DuneAuthProviderContext, type DuneAuthProviderProps, type DuneContextValue, EMPTY_SDK, createCDFSDK, getToken, useDune };
@@ -1 +0,0 @@
1
- import{a,b,c,d,e,f,g}from"../chunk-QGJ3VKXY.js";import"../chunk-EI7MMDWY.js";export{f as AppSdkAuthProvider,e as DuneAuthProvider,d as DuneAuthProviderContext,c as EMPTY_SDK,b as createCDFSDK,a as getToken,g as useDune};
@@ -1 +0,0 @@
1
- var c=Object.defineProperty;var d=(a,b)=>c(a,"name",{value:b,configurable:!0});export{d as a};
@@ -1 +0,0 @@
1
- import{a as t}from"./chunk-EI7MMDWY.js";import{connectToHostApp as b}from"@cognite/app-sdk";import{CogniteClient as U}from"@cognite/sdk";import{useEffect as N,useState as v}from"react";import{CogniteClient as R}from"@cognite/sdk";import{createContext as I,useEffect as L,useState as P}from"react";import{CogniteClient as A}from"@cognite/sdk";var D=t(async(n,e)=>{let o=`Basic ${btoa(`${n}:${e}`)}`;return(await(await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:o,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})})).json()).access_token},"getToken"),T=t(async n=>{let{project:e,baseUrl:o,clientId:r,clientSecret:d,appId:c="cdf-authentication-package"}=n;if(!e||!o||!r||!d)throw new Error("Missing required configuration. Please provide: project, baseUrl, clientId, clientSecret");let u=new A({appId:c,project:e,baseUrl:o,oidcTokenProvider:t(async()=>await D(r,d),"oidcTokenProvider")});return await u.authenticate(),u},"createCDFSDK"),p=new A({appId:"cdf-authentication-package",project:"",oidcTokenProvider:t(async()=>"","oidcTokenProvider")}),E=t(()=>{console.log("\u{1F511} Requesting credentials from parent..."),window.parent&&window.parent!==window&&window.parent.postMessage({type:"REQUEST_CREDENTIALS"},"*")},"requestCredentials"),S=t(n=>{if(n.data?.type==="PROVIDE_CREDENTIALS"&&n.data?.credentials){let e=n.data.credentials;if(e.token&&e.baseUrl&&e.project)return console.log("\u{1F389} useCredentials received credentials:",{hasToken:!!e.token,tokenLength:e.token?.length||0,project:e.project,baseUrl:e.baseUrl}),e}},"handleCredentialsResponse");import{Fragment as w,jsx as l,jsxs as x}from"react/jsx-runtime";var g=I({sdk:p,isLoading:!1}),y=t(({children:n,loadingComponent:e=l("div",{children:"Loading CDF authentication..."}),errorComponent:o=t(r=>x("div",{children:["Authentication error: ",r]}),"errorComponent")})=>l(_,{loadingComponent:e,errorComponent:o,children:n}),"DuneAuthProvider"),_=t(({children:n,loadingComponent:e=l("div",{children:"Loading CDF authentication..."}),errorComponent:o=t(r=>x("div",{children:["Authentication error: ",r]}),"errorComponent")})=>{let[r,d]=P(!0),[c,u]=P(p),[s]=P();return L(()=>{E();let f=t(async i=>{console.log("\u{1F50D} Handling message from Fusion");let a=S(i);if(!a)return;let h=new R({appId:"dune-app",project:a.project,baseUrl:a.baseUrl,oidcTokenProvider:t(async()=>a.token,"oidcTokenProvider")});await h.authenticate(),u(h),d(!1)},"handleMessage");return console.log("\u{1F50D} Adding message listener"),window.addEventListener("message",f),()=>window.removeEventListener("message",f)},[]),console.log("\u{1F50D} CDFIframeAuthenticationInnerProvider",c,r,s),s&&o?l(w,{children:o(s)}):r&&e?l(w,{children:e}):l(g.Provider,{value:{sdk:c,isLoading:r,error:s},children:n})},"FusionIframeAuthenticationInnerProvider");import{Fragment as k,jsx as C,jsxs as j}from"react/jsx-runtime";var F=t(({children:n,loadingComponent:e=C("div",{children:"Loading CDF authentication..."}),errorComponent:o=t(r=>j("div",{children:["Authentication error: ",r]}),"errorComponent")})=>{let[r,d]=v(p),[c,u]=v(!0),[s,f]=v();return N(()=>{b().then(async({api:i})=>{let[a,h]=await Promise.all([i.getProject(),i.getBaseUrl()]),m=new U({appId:"dune-app",project:a,baseUrl:h,oidcTokenProvider:t(async()=>i.getAccessToken(),"oidcTokenProvider")});await m.authenticate(),d(m),f(void 0)}).catch(i=>{let a=i instanceof Error?i.message:String(i);f(a)}).finally(()=>{u(!1)})},[]),s&&o?C(k,{children:o(s)}):c&&e?C(k,{children:e}):C(g.Provider,{value:{sdk:r,isLoading:c,error:s},children:n})},"AppSdkAuthProvider");import{useContext as M}from"react";var Y=t(()=>{let n=M(g);if(!n)throw new Error("useDune must be used within a DuneAuthProvider");return n},"useDune");export{D as a,T as b,p as c,g as d,y as e,F as f,Y as g};
@@ -1 +0,0 @@
1
- export { CspFetchDirective, MANIFEST_VERSION, ManifestConfig, NetworkAllowlistRule, buildFrameAncestors, buildHostedAppContentSecurityPolicy, fusionOpenPlugin, getManifestNetworkRules, loadManifestConfig, manifestCspPlugin, parseAndValidateManifestConfig, validateManifestConfig } from '@cognite/app-sdk/vite';
@@ -1 +0,0 @@
1
- import"../chunk-EI7MMDWY.js";import{fusionOpenPlugin as i,manifestCspPlugin as n,buildFrameAncestors as o,buildHostedAppContentSecurityPolicy as s,getManifestNetworkRules as a,loadManifestConfig as l,MANIFEST_VERSION as f,parseAndValidateManifestConfig as p,validateManifestConfig as r}from"@cognite/app-sdk/vite";export{f as MANIFEST_VERSION,o as buildFrameAncestors,s as buildHostedAppContentSecurityPolicy,i as fusionOpenPlugin,a as getManifestNetworkRules,l as loadManifestConfig,n as manifestCspPlugin,p as parseAndValidateManifestConfig,r as validateManifestConfig};