@cognite/cli 1.1.0-alpha.48 → 1.1.0-alpha.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_templates/app/new/root/.npmrc.ejs.t +0 -1
- package/_templates/app/new/root/package.json.ejs.t +3 -0
- package/dist/chunk-EI7MMDWY.js +1 -0
- package/dist/chunk-EILVJ2ZW.js +1 -0
- package/dist/chunk-HE6P4LDC.js +9 -0
- package/dist/cli/cli.js +152 -60
- package/dist/deploy/index.d.ts +0 -3
- package/dist/deploy/index.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/sdk-runtime/index.d.ts +199 -0
- package/dist/sdk-runtime/index.js +1 -0
- package/package.json +13 -3
- package/dist/chunk-QOJVLP7E.js +0 -9
|
@@ -26,10 +26,13 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
|
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"@cognite/aura": "^0.1.7",
|
|
28
28
|
"@cognite/sdk": "^10.3.0",
|
|
29
|
+
"@cognite/cli": "1.1.0-alpha.49",
|
|
29
30
|
"@cognite/app-sdk": "^0.4.0",
|
|
30
31
|
"@tabler/icons-react": "^3.35.0",
|
|
31
32
|
"@tanstack/react-query": "^5.90.10",
|
|
32
33
|
"clsx": "^2.1.1",
|
|
34
|
+
"graphql": "^16.14.0",
|
|
35
|
+
"graphql-tag": "^2.12.6",
|
|
33
36
|
"react": "^18.3.1",
|
|
34
37
|
"react-dom": "^18.3.1",
|
|
35
38
|
"tailwind-merge": "^3.4.0"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var c=Object.defineProperty;var d=(a,b)=>c(a,"name",{value:b,configurable:!0});export{d as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-EI7MMDWY.js";import{GraphQLSchema as Zt,GraphQLObjectType as er,GraphQLNonNull as x,GraphQLList as Q,GraphQLString as b,GraphQLInt as tr,GraphQLInputObjectType as Ye,printSchema as rr}from"graphql";function ie(e){return{space:e.space,externalId:e.externalId,version:e.version}}a(ie,"toSharedViewId");function St(e){switch(e){case"text":return"String";case"boolean":return"Boolean";case"int32":case"int64":return"Int";case"float32":case"float64":return"Float";case"timestamp":return"DateTime";case"date":return"Date";case"json":return"JSON";case"timeseries":return"CogniteTimeSeriesReference";case"file":return"CogniteFileReference";case"sequence":return"CogniteSequenceReference";case"enum":return"String";default:return"String"}}a(St,"dmsTypeToGraphQL");function Ne(e){if(!("source"in e)){if(e.type?.type==="direct")return e.type.list?{kind:"scalar",isList:!1,graphqlType:"JSON"}:e.type.source?{kind:"directRelation",targetView:ie(e.type.source)}:{kind:"scalar",isList:!1,graphqlType:"JSON"};if(e.type?.type==="enum"){let t=e.type,n={};if(typeof t=="object"&&t!==null&&"values"in t){let i=t.values;if(typeof i=="object"&&i!==null)for(let[r,s]of Object.entries(i))n[r]={name:typeof s=="object"&&s!==null&&"name"in s?String(s.name):void 0}}return{kind:"enum",values:Object.keys(n),valueNames:Object.fromEntries(Object.entries(n).map(([i,r])=>[i,r.name??i]))}}return{kind:"scalar",isList:e.type!==void 0&&"list"in e.type&&e.type.list===!0,graphqlType:e.type?.type?St(e.type.type):"String"}}if("through"in e)return{kind:e.connectionType==="single_reverse_direct_relation"?"reverseDirect":"reverseList",sourceView:ie(e.source),throughProperty:e.through.identifier};if(e.connectionType==="single_edge_connection"||e.connectionType==="multi_edge_connection"){let t=e.direction==="inwards"?"inwards":"outwards";return{kind:"edge",targetView:ie(e.source),direction:t}}return{kind:"scalar"}}a(Ne,"parsePropertyDescriptor");var Ee=new Set(["String","Boolean","Int","Float","DateTime","Date"]);var xt=new Set(["String","Int","Float","DateTime","Date"]);function Qe(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:Ee.has(e.graphqlType??"String")}a(Qe,"isFilterableDescriptor");function Ve(e){return e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:Ee.has(e.graphqlType??"String")}a(Ve,"isSortableDescriptor");function Fe(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind==="scalar"&&e.isList!==!0&&xt.has(e.graphqlType??"")}a(Fe,"hasInOpDescriptor");function Ae(e){return e.kind==="scalar"&&e.isList===!0}a(Ae,"hasListOpsDescriptor");function O(e){return e.usedFor!=="edge"}a(O,"isNodeOrAll");function T(e){return Object.entries(e.properties).map(([t,n])=>[t,Ne(n),n.description])}a(T,"parsedProperties");import{GraphQLObjectType as Pe,GraphQLNonNull as F,GraphQLString as ae,GraphQLFloat as j,GraphQLList as vt,GraphQLEnumType as kt}from"graphql";import{GraphQLScalarType as L,Kind as h}from"graphql";function oe(e){switch(e.kind){case h.STRING:case h.BOOLEAN:return e.value;case h.INT:return parseInt(e.value,10);case h.FLOAT:return parseFloat(e.value);case h.OBJECT:{let t={};for(let n of e.fields)t[n.name.value]=oe(n.value);return t}case h.LIST:return e.values.map(oe);case h.NULL:return null;default:return null}}a(oe,"parseLiteralJSON");var Rt=new L({name:"DateTime",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.STRING?e.value:null,"parseLiteral")}),It=new L({name:"Date",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.STRING?e.value:null,"parseLiteral")}),se=new L({name:"JSON",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:oe}),Tt=new L({name:"CogniteTimeSeriesReference",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.STRING?e.value:null,"parseLiteral")}),Dt=new L({name:"CogniteFileReference",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.STRING?e.value:null,"parseLiteral")}),Lt=new L({name:"CogniteSequenceReference",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.STRING?e.value:null,"parseLiteral")}),$=new L({name:"ListLimit",description:"Limit for list/search queries (1\u20131000).",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.INT?parseInt(e.value,10):null,"parseLiteral")}),v={DateTime:Rt,Date:It,JSON:se,CogniteTimeSeriesReference:Tt,CogniteFileReference:Dt,CogniteSequenceReference:Lt,ListLimit:$};var bt=new kt({name:"AggregateFunction",values:{count:{value:"count"},avg:{value:"avg"},sum:{value:"sum"},min:{value:"min"},max:{value:"max"},histogram:{value:"histogram"}}}),qe={function:{type:new F(bt)},property:{type:ae},interval:{type:j}},Ct=new Pe({name:"HistogramBucket",fields:{start:{type:new F(j)},count:{type:new F(j)}}}),_e=new Pe({name:"AggregateResult",fields:{aggregate:{type:new F(ae)},property:{type:ae},value:{type:j},buckets:{type:new vt(new F(Ct))},group:{type:se}}});import{GraphQLObjectType as pe,GraphQLNonNull as C,GraphQLList as Nt,GraphQLString as ce,GraphQLBoolean as Et}from"graphql";var Qt=new pe({name:"PageInfo",fields:{endCursor:{type:ce},hasNextPage:{type:new C(Et)}}}),B=new pe({name:"NodeReference",fields:{space:{type:new C(ce)},externalId:{type:new C(ce)}}});function K(e,t){return new pe({name:`${e}Connection`,fields:{items:{type:new C(new Nt(new C(t)))},pageInfo:{type:new C(Qt)}}})}a(K,"makeConnectionType");import{GraphQLInputObjectType as N,GraphQLList as S,GraphQLNonNull as je,GraphQLString as k,GraphQLBoolean as w,GraphQLFloat as Mt,GraphQLInt as Ot}from"graphql";import{GraphQLObjectType as Vt,GraphQLNonNull as Ge,GraphQLList as Ft,GraphQLString as U,GraphQLBoolean as At,GraphQLInt as Pt,GraphQLFloat as qt,GraphQLEnumType as _t}from"graphql";function Me(e){return e==="String"?U:e==="Boolean"?At:e==="Int"?Pt:e==="Float"?qt:v[e]??U}a(Me,"scalarForName");function Oe(e){return{typeRegistry:new Map,connectionRegistry:new Map,viewsByExtId:new Map(e.map(t=>[t.externalId,t])),enumRegistry:new Map,enumFilterRegistry:new Map}}a(Oe,"createTypeContext");function Gt(e){let t=e.replace(/[^_A-Za-z0-9]/g,"_");return/^[0-9]/.test(t)&&(t=`_${t}`),t||"_UNKNOWN"}a(Gt,"sanitizeEnumValue");function le(e,t,n,i){let r=n.enumRegistry.get(e);if(r)return r;let s=new _t({name:e,values:Object.fromEntries(t.map(o=>[Gt(o),{value:o,description:i?.[o]}]))});return n.enumRegistry.set(e,s),s}a(le,"getOrCreateEnumType");function $e(e,t){return new Vt({name:e.externalId,description:e.description??e.name,fields:a(()=>{let n={space:{type:new Ge(U)},externalId:{type:new Ge(U)}};for(let[i,r,s]of T(e))if(r.kind==="scalar")r.isList?n[i]={type:new Ft(Me(r.graphqlType??"String")),description:s}:n[i]={type:Me(r.graphqlType??"String"),description:s};else if(r.kind==="enum"){let o=`${e.externalId}${i.charAt(0).toUpperCase()}${i.slice(1)}`;n[i]={type:le(o,r.values,t,r.valueNames),description:s}}else if(r.kind==="directRelation"){let o=t.typeRegistry.get(r.targetView.externalId)??B;n[i]={type:o,description:s}}else if(r.kind==="reverseList"||r.kind==="edge"){let o=r.kind==="reverseList"?r.sourceView.externalId:r.targetView.externalId,u=t.typeRegistry.get(o)??B,d=t.connectionRegistry.get(o);d||(d=K(o,u),t.connectionRegistry.set(o,d)),n[i]={type:d,description:s}}else if(r.kind==="reverseDirect"){let o=t.typeRegistry.get(r.sourceView.externalId)??B;n[i]={type:o,description:s}}return n},"fields")})}a($e,"generateViewObjectType");function E(e,t,n){let i={isNull:{type:w},exists:{type:w},eq:{type:t}};return n.hasIn&&(i.in={type:new S(t)}),n.hasPrefix&&(i.prefix={type:k}),n.hasRange&&(i.gte={type:t},i.gt={type:t},i.lte={type:t},i.lt={type:t}),n.hasListOps&&(i.containsAny={type:new S(t)},i.containsAll={type:new S(t)},i.overlaps={type:new S(t)}),new N({name:e,fields:i})}a(E,"makeScalarFilter");var H=E("StringFilter",k,{hasIn:!0,hasPrefix:!0}),$t=E("BooleanFilter",w,{}),jt=E("IntFilter",Ot,{hasIn:!0,hasRange:!0}),Bt=E("FloatFilter",Mt,{hasIn:!0,hasRange:!0}),Kt=E("DateTimeFilter",v.DateTime,{hasIn:!0,hasRange:!0}),Ut=E("DateFilter",v.Date,{hasIn:!0,hasRange:!0}),Ht=new N({name:"StringListFilter",fields:{isNull:{type:w},exists:{type:w},containsAny:{type:new S(k)},containsAll:{type:new S(k)},overlaps:{type:new S(k)}}}),A=new N({name:"DirectRelationRef",fields:{space:{type:new je(k)},externalId:{type:new je(k)}}}),zt=new N({name:"DirectRelationFilter",fields:{isNull:{type:w},exists:{type:w},eq:{type:A},in:{type:new S(A)}}});function Xt(e){switch(e){case"String":return H;case"Boolean":return $t;case"Int":return jt;case"Float":return Bt;case"DateTime":return Kt;case"Date":return Ut;default:return H}}a(Xt,"scalarFilterForName");var Be=["space","externalId"];function Ke(e,t,n){let i=t.get(e.externalId),r={};for(let o of Be)r[o]={type:H};let s=new Set(Be);for(let[o,u]of T(e)){if(s.has(o))continue;let d=Qe(u),p=Ae(u);if(!(!d&&!p))if(u.kind==="directRelation"){let c={isNull:{type:w},exists:{type:w},eq:{type:A},in:{type:new S(A)}};Fe(u)&&(c.in={type:new S(A)});let l=t.get(u.targetView.externalId);l&&(c.nested={type:l}),r[o]=l?{type:new N({name:`_${e.externalId}_${o}_Filter`,fields:c})}:{type:zt}}else if(u.kind==="enum"){let c=`${e.externalId}${o.charAt(0).toUpperCase()}${o.slice(1)}`,l=le(c,u.values,n),m=n.enumFilterRegistry.get(c);m||(m=new N({name:`${c}Filter`,fields:{isNull:{type:w},exists:{type:w},eq:{type:l},in:{type:new S(l)}}}),n.enumFilterRegistry.set(c,m)),r[o]={type:m}}else if(p)r[o]={type:Ht};else{let c=u.kind==="scalar"?u.graphqlType??"String":"String",l=Xt(c);l&&(r[o]={type:l})}}return{...r,hasData:{type:w},matchAll:{type:w},_and:{type:new S(i)},_or:{type:new S(i)},_not:{type:i}}}a(Ke,"generateFilterFields");import{GraphQLEnumType as Ue,GraphQLInputObjectType as He,GraphQLList as Yt,GraphQLNonNull as z,GraphQLString as Jt,GraphQLBoolean as Wt}from"graphql";var X=new Ue({name:"SortDirection",values:{ASC:{value:"ascending"},DESC:{value:"descending"}}});function ze(e){let t=[];for(let[i,r]of T(e))Ve(r)&&t.push(i);if(t.length===0)return null;let n=new Ue({name:`${e.externalId}SortField`,values:Object.fromEntries(t.map(i=>[i,{value:i}]))});return new He({name:`${e.externalId}Sort`,fields:{field:{type:new z(n)},direction:{type:new z(X)},nullsFirst:{type:Wt}}})}a(ze,"generateSortInput");var Xe=new He({name:"SearchSort",fields:{property:{type:new z(new Yt(new z(Jt)))},direction:{type:X}}});function Je(e){let t=e.filter(O),n=Oe(t);for(let c of t){let l=$e(c,n);n.typeRegistry.set(c.externalId,l)}let i=new Map;for(let c of t){let l=new Ye({name:`${c.externalId}Filter`,fields:a(()=>Ke(c,i,n),"fields")});i.set(c.externalId,l)}let r={};for(let c of t){let l=c.externalId,m=n.typeRegistry.get(l),f=n.connectionRegistry.get(l);f||(f=K(l,m),n.connectionRegistry.set(l,f));let g=i.get(l),y=ze(c),D={limit:{type:$},cursor:{type:b},filter:{type:g}};y&&(D.sort={type:new Q(y)}),r[`query${l}`]={type:new x(f),args:D},r[`get${l}ById`]={type:m,args:{space:{type:new x(b)},externalId:{type:new x(b)}}},r[`count${l}`]={type:new x(tr),args:{filter:{type:g}}},r[`search${l}`]={type:new x(f),args:{query:{type:b},limit:{type:$},filter:{type:g},sort:{type:new Q(new x(Xe))},properties:{type:new Q(new x(b))}}},r[`aggregate${l}`]={type:new x(new Q(new x(_e))),args:{filter:{type:g},aggregates:{type:new Q(new x(new Ye({name:`${l}AggregateRequest`,fields:qe})))},groupBy:{type:new Q(new x(b))},query:{type:b}}}}let s=[];for(let[c,l]of n.typeRegistry)s.push({name:l.name,source:`typeRegistry[${c}]`});for(let[c,l]of n.connectionRegistry)s.push({name:l.name,source:`connectionRegistry[${c}]`});let o=new Map;for(let{name:c,source:l}of s)o.has(c)||o.set(c,[]),o.get(c).push(l);for(let[c,l]of o)l.length>1&&console.error(`[dune] duplicate type "${c}" from: ${l.join(", ")}`);let u=new Zt({query:new er({name:"Query",fields:r}),types:[X,...Object.values(v),...n.enumRegistry.values()]}),d=new Map;for(let c of t){let l=new Map;for(let[m,f]of T(c))l.set(m,f);d.set(c.externalId,{view:{space:c.space,externalId:c.externalId,version:c.version},properties:l})}let p={view(c){let l=d.get(c.externalId);if(!l)throw new Error(`SchemaKnowledge: no view for externalId "${c.externalId}"`);return l},property(c,l){return d.get(c.externalId)?.properties.get(l)}};return{schema:u,sdl:rr(u),schemaKnowledge:p}}a(Je,"buildSchema");async function We(e,t){let i=(await t.dataModels.retrieve([{space:e.space,externalId:e.dataModelExternalId,version:e.dataModelVersion}],{inlineViews:!1})).items[0];if(!i)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} not found`);if(!i.views?.length)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} has no views`);let r=i.views.map(o=>({space:o.space,externalId:o.externalId,version:o.version}));return(await t.views.retrieve(r,{includeInheritedProperties:!0})).items}a(We,"fetchViews");import{execute as nr,parse as Dn}from"graphql";function Ze(e,t){return async(n,i)=>{let r=await nr({schema:e,document:n,variableValues:i,rootValue:t,fieldResolver:a((s,o,u,d)=>{let p=s[d.fieldName];return typeof p=="function"?p(s,o,u,d):p},"fieldResolver")});if(r.errors?.length)throw r.errors[0];return r.data}}a(Ze,"createDuneRequester");import{CogniteError as gr}from"@cognite/sdk";function et(){return{initialBatchLimit:1e3,maxBatchLimit:5e3,searchLimit:1e3,inFilterChunkSize:100,previewLimit:3,nestedDetailLimit:5,enableRemoveNotConnected:!1,max408Retries:3,max429Retries:5,retryBaseDelayMs:500,maxConcurrentRequests:4,maxNestingDepth:2,maxTotalItems:1e4}}a(et,"defaultPlannerConfig");var fe=class fe extends Error{constructor(t){super(t),this.name="PlannerValidationError"}};a(fe,"PlannerValidationError");var I=fe;function J(e){return e.connections.size===0?0:1+Math.max(...[...e.connections.values()].map(t=>J(t.select)))}a(J,"selectionDepth");function mr(e,t,n){for(let i of t.scalars)if(i!=="*"&&!n.property(e,i))throw new I(`Property "${i}" does not exist on view ${e.externalId}/${e.version}`);for(let[i]of t.connections)if(!n.property(e,i))throw new I(`Connection "${i}" does not exist on view ${e.externalId}/${e.version}`)}a(mr,"validateSelection");function V(e){return{hasData:[e]}}a(V,"hasDataFilter");function rt(e,t){let n=V(t);return e?{and:[e,n]}:n}a(rt,"scopedFilter");function nt(e,t,n,i,r){return{name:"0",kind:"root",view:e,filter:rt(t,e),sort:n&&n.length>0?n:void 0,select:i.length>0?i:["*"],limit:r,queryable:!0}}a(nt,"makeRootStep");function it(e,t,n,i,r,s){return{name:e,from:t.name,kind:"directRelation",view:i,through:{view:t.view,property:n},direction:"outwards",filter:V(i),select:r.length>0?r:["*"],limit:s,queryable:!0,fieldName:n}}a(it,"makeDirectRelationStep");function ot(e,t,n,i,r,s,o){return{name:e,from:t.name,kind:"reverseDirect",view:i,through:{view:i,property:r},direction:"inwards",filter:V(i),select:s.length>0?s:["*"],limit:o,queryable:!0,fieldName:n}}a(ot,"makeReverseDirectStep");function st(e,t,n,i,r,s,o){return{name:e,from:t.name,kind:"reverseList",view:i,through:{view:i,property:r},direction:"inwards",filter:V(i),select:s.length>0?s:["*"],limit:o,queryable:!1,fieldName:n}}a(st,"makeReverseListStep");function at(e,t,n,i,r,s,o,u){let d={name:e,from:n.name,kind:"edgeIntermediate",view:r,direction:s,filter:void 0,select:[],limit:u,limitEach:u,queryable:!0},p={name:t,from:e,kind:"edge",view:r,filter:V(r),select:o.length>0?o:["*"],limit:u,queryable:!0,fieldName:i,chainTo:s==="outwards"?"destination":"source"};return[d,p]}a(at,"makeEdgeSteps");function Y(e){return{type:"view",space:e.space,externalId:e.externalId,version:e.version}}a(Y,"toRef");function P(e,t,n,i,r,s){let o=0;for(let[u,d]of n.connections){let p=r.property(t,u);if(!p)continue;o++;let c=d.limit??i,l=d.select.scalars,m=d.select,f=`${e.name}_${o}`;if(p.kind==="directRelation"){let g=Y(p.targetView),y=it(f,e,u,g,l,c);s.push(y),P(y,g,m,i,r,s)}else if(p.kind==="reverseDirect"){let g=Y(p.sourceView),y=ot(f,e,u,g,p.throughProperty,l,c);s.push(y),P(y,g,m,i,r,s)}else if(p.kind==="reverseList"){let g=Y(p.sourceView),y=st(f,e,u,g,p.throughProperty,l,c);s.push(y),P(y,g,m,i,r,s)}else if(p.kind==="edge"){let g=Y(p.targetView),y=`${e.name}_${o}_e`,[D,M]=at(y,f,e,u,g,p.direction,l,c);s.push(D,M),P(M,g,m,i,r,s)}}}a(P,"addConnectionSteps");function W(e,t,n,i,r,s,o){s&&mr(e,t,s);let u=nt(e,n,i,t.scalars,r),d=[u];return s&&P(u,e,t,o??r,s,d),d}a(W,"buildSteps");function ge(e,t){let n=new Set,i=new Map(e.map(r=>[r.name,r]));for(let r of e){if(r.queryable)continue;let s=r.from;if(!s||s in t)continue;let o=i.get(s);o?.view&&(t[s]={sources:[{source:o.view,properties:["*"]}]},n.add(s))}return n}a(ge,"injectPhantomSelects");function fr(e){let t=e.property.view;return{property:[t.space,`${t.externalId}/${t.version}`,e.property.property],direction:e.direction,nullsFirst:e.nullsFirst??!1}}a(fr,"compileSortClause");function ye(e,t,n){let i={},r={};for(let p of e){if(!p.queryable)continue;if(p.kind==="edgeIntermediate"){let m={edges:{from:p.from,direction:p.direction,maxDistance:1},limit:Math.min(p.limit,n)};p.filter&&(m.edges.filter=p.filter),p.limitEach!=null&&(m.edges.limitEach=p.limitEach),i[p.name]=m,r[p.name]={sources:[]};continue}let c={filter:p.filter};p.from&&(c.from=p.from),p.chainTo?c.chainTo=p.chainTo:p.through?(c.through={view:p.through.view,identifier:p.through.property},c.direction=p.direction):p.direction&&(c.direction=p.direction);let l={limit:Math.min(p.limit,n),nodes:c};p.sort&&p.sort.length>0&&(l.sort=p.sort.map(fr)),i[p.name]=l,r[p.name]={sources:[{source:p.view,properties:p.select}]}}let s=ge(e,r),o={with:i,select:r},u={},d=!1;for(let p of e){if(!p.queryable||p.kind==="edgeIntermediate")continue;let c=t.get(p.name);c!=null&&(u[p.name]=c,d=!0)}return d&&(o.cursors=u),{query:o,tempSelectSteps:s}}a(ye,"compileQuery");function he(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}a(he,"chunkArray");var we=class we{constructor(t,n){this.dms=t;this.config=n}async run(t,n,i){let{response:r,tempSelectSteps:s,batchLimit:o}=await this.queryWithRetry(t,n,i),u={},d=new Map;for(let[p,c]of Object.entries(r.items))u[p]=c,d.set(p,r.nextCursor[p]??null);return await this.fetchReverseLists(t,u),{batch:u,nextCursors:d,tempSelectSteps:s,batchLimit:o}}async queryWithRetry(t,n,i){let r=i,s=0;for(;;){let{query:o,tempSelectSteps:u}=ye(t,n,r);try{return{response:await this.dms.query({with:o.with,select:o.select,cursors:o.cursors}),tempSelectSteps:u,batchLimit:r}}catch(d){if(d instanceof gr&&d.status===408){if(s>=this.config.max408Retries)throw d;s++,r=Math.max(1,Math.floor(r/2))}else throw d}}}async fetchReverseLists(t,n){let i=t.filter(r=>!r.queryable&&r.from);for(let r of i){let s=n[r.from]??[];if(s.length===0){n[r.name]=[];continue}let o=s.map(l=>({space:l.space,externalId:l.externalId})),u=r.through,d=[u.view.space,`${u.view.externalId}/${u.view.version}`,u.property],p=he(o,this.config.inFilterChunkSize),c=[];for(let l of p){let m=r.limit-c.length;if(m<=0)break;let f=await this.dms.search({view:r.view,filter:{in:{property:d,values:l}},limit:m});c.push(...f.items)}n[r.name]=c}}async fetchQueryableConnections(t,n){let i=t.filter(r=>r.queryable&&r.from&&(r.kind==="directRelation"||r.kind==="reverseDirect"));for(let r of i){let s=n[r.from]??[];if(s.length===0){n[r.name]=[];continue}if(r.kind==="directRelation"){let o=r.through,u=`${o.view.externalId}/${o.view.version}`,d=[],p=new Set;for(let m of s){let f=m.properties?.[o.view.space]?.[u]?.[o.property];if(f&&typeof f=="object"&&"space"in f&&"externalId"in f){let g=f,y=`${g.space}:${g.externalId}`;p.has(y)||(p.add(y),d.push({space:g.space,externalId:g.externalId}))}}if(d.length===0){n[r.name]=[];continue}let c=he(d,this.config.inFilterChunkSize),l=[];for(let m of c){let f=await this.dms.retrieve({items:m.map(g=>({instanceType:"node",...g})),sources:[{source:r.view}]});l.push(...f.items)}n[r.name]=l}else{let o=s.map(l=>({space:l.space,externalId:l.externalId})),u=r.through,d=[u.view.space,`${u.view.externalId}/${u.view.version}`,u.property],p=he(o,this.config.inFilterChunkSize),c=[];for(let l of p){let m=r.limit-c.length;if(m<=0)break;let f=await this.dms.search({view:r.view,filter:{in:{property:d,values:l}},limit:m});c.push(...f.items)}n[r.name]=c}}}async fetchEdgeConnections(t,n){let i=t.filter(r=>r.kind==="edgeIntermediate"&&r.from);for(let r of i){let s=n[r.from]??[],o=t.find(f=>f.kind==="edge"&&f.from===r.name);if(!o)continue;if(s.length===0){n[r.name]=[],n[o.name]=[];continue}let u=`${r.from}__edge_root`,d=s.map(f=>f.externalId),p={nodes:{filter:{in:{property:["node","externalId"],values:d}}},limit:s.length},c={edges:{from:u,direction:r.direction,maxDistance:1},limit:r.limit};r.filter&&(c.edges.filter=r.filter),r.limitEach!=null&&(c.edges.limitEach=r.limitEach);let l={nodes:{from:r.name,chainTo:o.chainTo},limit:o.limit};o.filter&&(l.nodes.filter=o.filter);let m=await this.dms.query({with:{[u]:p,[r.name]:c,[o.name]:l},select:{[u]:{sources:[]},[r.name]:{sources:[]},[o.name]:{sources:[{source:o.view,properties:o.select}]}}});n[r.name]=m.items[r.name]??[],n[o.name]=m.items[o.name]??[]}}};a(we,"QueryExecutor");var q=we;var yr={endCursor:null,hasNextPage:!1};function ct(e){return{items:e,pageInfo:yr}}a(ct,"wrapConnection");function pt(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.space=="string"&&typeof t.externalId=="string"}a(pt,"isDmsRef");function lt(e,t){let n=`${t.externalId}/${t.version}`;return{...e.properties?.[t.space]?.[n]??{},space:e.space,externalId:e.externalId}}a(lt,"extractViewProperties");function Z(e,t,n,i){if(t.length===0)return;let r=[...n.values()].filter(o=>o.from===e.name&&o.fieldName),s=[...n.values()].filter(o=>o.kind==="edge"&&o.fieldName&&o.from!=null&&n.get(o.from)?.from===e.name);for(let o of[...r,...s]){let u=(i[o.name]??[]).map(d=>lt(d,o.view));if(o.kind==="directRelation"){let d=new Map;for(let p of u)d.set(`${p.space}:${p.externalId}`,p);for(let p of t){let c=p[o.fieldName];p[o.fieldName]=pt(c)?d.get(`${c.space}:${c.externalId}`)??null:null}Z(o,u,n,i)}else if(o.kind==="reverseDirect"||o.kind==="reverseList"){let d=o.through.property,p=new Map;for(let c of t)p.set(`${c.space}:${c.externalId}`,[]);for(let c of u){let l=c[d];pt(l)&&p.get(`${l.space}:${l.externalId}`)?.push(c)}for(let c of t){let l=p.get(`${c.space}:${c.externalId}`)??[];c[o.fieldName]=o.kind==="reverseList"?ct(l):l}Z(o,u,n,i)}else if(o.kind==="edge"){let d=i[o.from]??[],p=new Map;for(let l of d){if(l.instanceType!=="edge")continue;let{startNode:m,endNode:f}=l;if(!m||!f)continue;let g=o.chainTo==="destination"?m:f,y=o.chainTo==="destination"?f:m,D=`${g.space}:${g.externalId}`,M=`${y.space}:${y.externalId}`,Ce=p.get(D)??[];Ce.push(M),p.set(D,Ce)}let c=new Map;for(let l of u)c.set(`${l.space}:${l.externalId}`,l);for(let l of t){let m=`${l.space}:${l.externalId}`,g=(p.get(m)??[]).map(y=>c.get(y)).filter(y=>y!==void 0);l[o.fieldName]=ct(g)}Z(o,u,n,i)}}}a(Z,"nestChildrenForStep");function hr(e,t,n){let i=e.find(s=>!s.from);if(!i)return n;let r=new Map(e.map(s=>[s.name,s]));return Z(i,n,r,t),n}a(hr,"nestChildren");function ee(e,t){let n=e.find(r=>!r.from);if(!n)return[];let i=(t[n.name]??[]).map(r=>lt(r,n.view));return hr(e,t,i)}a(ee,"unpack");function Se(e,t){for(let n of e)delete t[n]}a(Se,"stripTempSelects");function xe(e){let t={};for(let[n,i]of e)i!=null&&(t[n]=i);return Object.keys(t).length===0?null:btoa(JSON.stringify(t))}a(xe,"encodeCursors");function Re(e){if(!e)return new Map;try{let t=JSON.parse(atob(e));return new Map(Object.entries(t))}catch{throw new I("Invalid pagination cursor \u2014 the value is malformed or has been modified by the client.")}}a(Re,"decodeCursors");import{CogniteError as wr}from"@cognite/sdk";function ut(){return{max429Retries:5,retryBaseDelayMs:500,maxConcurrentRequests:4}}a(ut,"defaultRetryConfig");function Sr(e){return new Promise(t=>setTimeout(t,e))}a(Sr,"sleep");var Te=class Te{constructor(t){this.queue=[];this.count=t}acquire(){return this.count>0?(this.count--,Promise.resolve()):new Promise(t=>this.queue.push(t))}release(){let t=this.queue.shift();t?t():this.count++}};a(Te,"Semaphore");var Ie=Te,De=class De{constructor(t,n=ut()){this.inner=t;this.config=n;this.semaphore=new Ie(n.maxConcurrentRequests)}query(t){return this.withRetry(()=>this.inner.query(t))}search(t){return this.withRetry(()=>this.inner.search(t))}aggregate(t){return this.withRetry(()=>this.inner.aggregate(t))}retrieve(t){return this.withRetry(()=>this.inner.retrieve(t))}sync(t){return this.withRetry(()=>this.inner.sync(t))}upsert(t){return this.inner.upsert(t)}delete(t){return this.inner.delete(t)}inspect(t){return this.inner.inspect(t)}async withRetry(t){let n=0;for(;;){await this.semaphore.acquire();try{return await t()}catch(i){if(i instanceof wr&&i.status===429){if(n>=this.config.max429Retries)throw i;n++,await Sr(this.config.retryBaseDelayMs*2**(n-1))}else throw i}finally{this.semaphore.release()}}}};a(De,"RetryingDmsClient");var _=De;var Le=class Le{get schemaKnowledge(){return this.schema}constructor(t,n,i){this.schema=n,this.config={...et(),...i},this.dms=new _(t,{max429Retries:this.config.max429Retries,retryBaseDelayMs:this.config.retryBaseDelayMs,maxConcurrentRequests:this.config.maxConcurrentRequests}),this.executor=new q(this.dms,{max408Retries:this.config.max408Retries,inFilterChunkSize:this.config.inFilterChunkSize})}async query(t){let n=J(t.select);if(n>this.config.maxNestingDepth)throw new I(`Query nesting depth ${n} exceeds maximum ${this.config.maxNestingDepth}. Reduce connection depth or raise maxNestingDepth in config.`);let i=t.limit??this.config.initialBatchLimit,r=W(t.view,t.select,t.filter,t.sort,i,this.schema,this.config.previewLimit),s=Re(t.cursor),o={steps:r,tempSelectSteps:new Set,cursors:new Map(s),batchLimit:Math.min(this.config.initialBatchLimit,this.config.maxBatchLimit)},{batch:u,nextCursors:d,tempSelectSteps:p}=await this.executor.run(r,o.cursors,o.batchLimit);Se(p,u);let c=ee(r,u),l=r[0],m=d.get(l.name)??null,f=xe(d),g=m!=null;return{items:c,pageInfo:{endCursor:f,hasNextPage:g}}}async queryAll(t,n){let i=n??this.config.maxTotalItems,r=[],s,o=!0;for(;o;){let u=await this.query({...t,cursor:s});if(r.push(...u.items),o=u.pageInfo.hasNextPage,s=u.pageInfo.endCursor??void 0,r.length>=i){if(n===void 0&&o)throw new I(`listAll reached the hard ceiling of ${i} items. Pass an explicit maxTotal to acknowledge this or raise maxTotalItems in config.`);break}}return r}async search(t){let n=t.limit??this.config.searchLimit,i=await this.dms.search({view:t.view,query:t.query,filter:t.filter,sort:t.sort,limit:n,properties:t.properties}),r=W(t.view,t.select,void 0,void 0,n,this.schema,this.config.previewLimit),s={0:i.items};return await this.executor.fetchReverseLists(r,s),await this.executor.fetchQueryableConnections(r,s),await this.executor.fetchEdgeConnections(r,s),{items:ee(r,s),pageInfo:{endCursor:null,hasNextPage:!1}}}async getByIds(t,n){if(t.length===0)return[];let i=await this.dms.retrieve({items:t.map(s=>({instanceType:"node",space:s.space,externalId:s.externalId})),sources:[{source:n}]}),r=`${n.externalId}/${n.version}`;return i.items.map(s=>({...s.properties?.[n.space]?.[r]??{},space:s.space,externalId:s.externalId}))}async count(t){let i=(await this.dms.aggregate({view:t.view,filter:t.filter,aggregates:[{count:{property:"externalId"}}]})).items[0]?.aggregates[0];return(i?.aggregate!=="histogram"?i?.value:void 0)??0}async aggregate(t){return{items:(await this.dms.aggregate({view:t.view,filter:t.filter,aggregates:t.aggregates,groupBy:t.groupBy,query:t.query})).items}}async*queryPages(t){let n,i=!0;for(;i;){let r=await this.query({...t,cursor:n});yield r,i=r.pageInfo.hasNextPage,n=r.pageInfo.endCursor??void 0}}};a(Le,"QueryRunner");var G=Le;function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ve,"isRecord");function te(e){return typeof e=="string"||typeof e=="number"}a(te,"isScalar");var xr={space:["node","space"],externalId:["node","externalId"]};function Rr(e,t){return xr[t]??[e.space,`${e.externalId}/${e.version}`,t]}a(Rr,"propRef");var Ir={exists:a((e,t)=>typeof t!="boolean"?void 0:t?{exists:{property:e}}:{not:{exists:{property:e}}},"exists"),eq:a((e,t)=>({equals:{property:e,value:t}}),"eq"),in:a((e,t)=>Array.isArray(t)?{in:{property:e,values:t}}:void 0,"in"),isNull:a((e,t)=>typeof t!="boolean"?void 0:t?{not:{exists:{property:e}}}:{exists:{property:e}},"isNull"),prefix:a((e,t)=>typeof t=="string"?{prefix:{property:e,value:t}}:void 0,"prefix"),gte:a((e,t)=>te(t)?{range:{property:e,gte:t}}:void 0,"gte"),gt:a((e,t)=>te(t)?{range:{property:e,gt:t}}:void 0,"gt"),lte:a((e,t)=>te(t)?{range:{property:e,lte:t}}:void 0,"lte"),lt:a((e,t)=>te(t)?{range:{property:e,lt:t}}:void 0,"lt"),containsAny:a((e,t)=>Array.isArray(t)?{containsAny:{property:e,values:t}}:void 0,"containsAny"),containsAll:a((e,t)=>Array.isArray(t)?{containsAll:{property:e,values:t}}:void 0,"containsAll"),overlaps:a((e,t)=>Array.isArray(t)?{containsAny:{property:e,values:t}}:void 0,"overlaps")};function Tr(e,t,n,i){let r=Rr(n,e),s=Object.entries(t).flatMap(([o,u])=>{if(u==null)return[];if(o==="nested"&&i&&ve(u)){let p=i.property(n,e);if(p?.kind==="directRelation"){let c={type:"view",...p.targetView},l=R(u,c,i);if(l)return[{nested:{scope:[n.space,`${n.externalId}/${n.version}`,e],filter:l}}]}return[]}let d=Ir[o]?.(r,u);return d?[d]:[]});if(s.length!==0)return s.length===1?s[0]:{and:s}}a(Tr,"translatePropertyFilter");function Dr(e){if(e.length!==0)return e.length===1?e[0]:{and:e}}a(Dr,"collapse");function R(e,t,n){if(!ve(e))return;let i=Object.entries(e).flatMap(([r,s])=>{if(s==null)return[];if(r==="_not"){let o=R(s,t,n);return o?[{not:o}]:[]}if(r==="hasData"&&typeof s=="boolean"&&s)return[{hasData:[{type:"view",space:t.space,externalId:t.externalId,version:t.version}]}];if(r==="matchAll"&&typeof s=="boolean"&&s)return[{matchAll:{}}];if((r==="_and"||r==="_or")&&Array.isArray(s)){let o=s.flatMap(u=>{let d=R(u,t,n);return d?[d]:[]});return o.length>0?[r==="_and"?{and:o}:{or:o}]:[]}if(ve(s)){let o=Tr(r,s,t,n);return o?[o]:[]}return[]});return Dr(i)}a(R,"buildFilter");function Lr(e){switch(e.function){case"avg":return{avg:{property:e.property}};case"sum":return{sum:{property:e.property}};case"min":return{min:{property:e.property}};case"max":return{max:{property:e.property}};case"histogram":return{histogram:{property:e.property,interval:e.interval}};default:return{count:{property:e.property??"externalId"}}}}a(Lr,"toAggregationDefinition");function dt(e,t){return a(async function(i,r){let{items:s}=await t.aggregate({view:e,filter:R(r.filter,e,t.schemaKnowledge),aggregates:(r.aggregates??[{function:"count"}]).map(Lr),groupBy:r.groupBy,query:r.query});return s.flatMap(o=>o.aggregates.map(u=>{if(u.aggregate==="histogram"){let{aggregate:l,property:m,buckets:f}=u;return{aggregate:l,property:m,value:null,buckets:f,group:o.group??null}}let{aggregate:d,property:p,value:c}=u;return{aggregate:d,property:p,value:c,buckets:null,group:o.group??null}}))},"aggregateResolver")}a(dt,"makeAggregateResolver");function mt(e,t){return a(async function(i,r){let s=R(r.filter,e,t.schemaKnowledge);return t.count({view:e,filter:s})},"countResolver")}a(mt,"makeCountResolver");import{Kind as ke,isObjectType as vr,getNamedType as kr}from"graphql";function re(e,t){let n=[];for(let i of e.selections)if(i.kind===ke.FIELD)n.push(i);else if(i.kind===ke.INLINE_FRAGMENT&&i.selectionSet)n.push(...re(i.selectionSet,t));else if(i.kind===ke.FRAGMENT_SPREAD){let r=t[i.name.value];r&&n.push(...re(r.selectionSet,t))}return n}a(re,"collectFields");var br=new Set(["space","externalId"]);function ft(e,t,n){let i=[],r=new Map;for(let s of re(e,n.fragments)){let o=s.name.value;if(o==="__typename"||br.has(o))continue;if(!s.selectionSet){i.push(o);continue}let u=n.schema.getType(t);if(vr(u)){let d=u.getFields()[o];if(d){let p=kr(d.type).name,c=ft(s.selectionSet,p,n);r.set(o,{select:c});continue}}i.push(o)}return{scalars:i,connections:r}}a(ft,"buildTree");function be(e,t,n){return e?ft(e,t,n):{scalars:[],connections:new Map}}a(be,"buildSelectionTree");function ne(e,t){let n=e.fieldNodes[0]?.selectionSet;if(!n)return{scalars:[],connections:new Map};let i=re(n,e.fragments).find(r=>r.name.value==="items");return be(i?.selectionSet,t,e)}a(ne,"buildSelectionTreeFromListInfo");function gt(e,t,n){return a(async function(r,s,o,u){let{space:d,externalId:p}=s,c=be(u.fieldNodes[0]?.selectionSet,t,u),l={and:[{equals:{property:["node","space"],value:d}},{equals:{property:["node","externalId"],value:p}}]},{items:m}=await n.query({view:e,select:c,filter:l,limit:1});return m[0]??null},"getByIdResolver")}a(gt,"makeGetByIdResolver");function yt(e,t,n){return a(async function(r,s,o,u){let d=ne(u,t),p=R(s.filter,e,n.schemaKnowledge),c=Cr(s.sort,e);return n.query({view:e,select:d,filter:p,sort:c,cursor:s.cursor,limit:s.limit})},"queryResolver")}a(yt,"makeQueryResolver");function Cr(e,t){if(!(!e||e.length===0))return e.map(n=>({property:{view:t,property:n.field},direction:n.direction??"ascending",nullsFirst:n.nullsFirst}))}a(Cr,"parseSortArg");function ht(e,t,n){return a(async function(r,s,o,u){let d=ne(u,t),p={view:e,query:s.query,limit:s.limit,filter:R(s.filter,e,n.schemaKnowledge),sort:s.sort,select:d,properties:s.properties},{items:c,pageInfo:l}=await n.search(p);return{items:c,pageInfo:l}},"searchResolver")}a(ht,"makeSearchResolver");function Nr(e,t){let n={};for(let i of e.filter(O)){let r={type:"view",space:i.space,externalId:i.externalId,version:i.version},s=i.externalId;n[`query${s}`]=yt(r,s,t),n[`get${s}ById`]=gt(r,s,t),n[`count${s}`]=mt(r,t),n[`search${s}`]=ht(r,s,t),n[`aggregate${s}`]=dt(r,t)}return n}a(Nr,"buildRootValue");async function Er(e,t){let n=await We(e,t);return wt(n,t)}a(Er,"createDuneRuntime");function wt(e,t){let{schema:n,schemaKnowledge:i}=Je(e),r=new G(t.instances,i),s=Nr(e,r),o=Ze(n,s);return{schema:n,rootValue:s,runner:r,requester:o}}a(wt,"createDuneRuntimeFromViews");export{Er as a,wt as b};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{a as s}from"./chunk-EI7MMDWY.js";import Y from"fs";import ut from"path";var N="https://docs.cognite.com/cdf/access/";function m(e){return e!==null&&typeof e=="object"}s(m,"isRecord");function S(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}s(S,"isHttpError");function W(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
2
|
+
See: ${N}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
3
|
+
See: ${N}`;default:return}}s(W,"httpStatusHint");function A(e){let t=e instanceof Error?e:new Error(String(e));if(!S(t))return null;let n=W(t.status);return n?Object.assign(new Error(`${t.message}
|
|
4
|
+
${n}`),{cause:t}):null}s(A,"enrichedHttpError");function Z(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(Z,"findMissingArray");function X(e,t){if(!S(e)||e.status!==400)return!1;let n=Z(e);return n?n.some(r=>m(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}s(X,"isMissingExternalIdError");function $(e,t){return S(e)&&e.status===404||X(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 V=I;function q(e,t){return e.includes(t)}s(q,"includesValue");function Q(e){return q(M,e)}s(Q,"isAppVersionLifecycleState");function tt(e){return q(J,e)}s(tt,"isAppVersionAlias");function et(e){return typeof e.version=="string"&&Q(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||tt(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}s(et,"isAppVersion");function H(e){if(!m(e))throw new Error("Invalid version response: not an object");if(!et(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(),k=f;try{let x=JSON.parse(f);if(m(x)){let w=x.error;if(typeof w=="string")k=w;else if(m(w)){let E=w.message,F=w.code;k=typeof E=="string"?E:F!=null?`Unknown error (code: ${F})`:f}else{let E=x.message;k=typeof E=="string"?E:f}}}catch{}let j=h.headers.get("x-request-id"),K=j?` | X-Request-ID: ${j}`:"",B=Object.assign(new Error(`Upload failed: ${h.status} \u2014 ${k}${K}`),{status:h.status});throw A(B)??B}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 V(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(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,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 P=b;import y from"fs";import d from"path";import{parseAndValidateManifestConfig as nt}from"@cognite/app-sdk/vite";import{BlobReader as rt,Uint8ArrayWriter as ot,ZipWriter as st}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 st(new ot,{level:9}),o=s(async(c,p)=>{await r.add(p,new rt(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");nt(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 dt}from"@cognite/sdk";var it=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"),at=s(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=it()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),ct=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"),pt=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"),lt=s(async(e,t,n,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let o=ct(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=at(r);if(o==="entra_id"){if(!i)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return lt(n,l,i,a)}return pt(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 dt(l)))({appId:t,project:e.project,baseUrl:i,oidcTokenProvider:s(async()=>o,"oidcTokenProvider")});return await a.authenticate(),a}s(U,"getSdk");var gt=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 P(c),g=Y.readFileSync(r),u=ut.basename(r);await p.deploy(o,i,a,l,g,u,e.published)}finally{try{Y.unlinkSync(r)}catch{}}},"deploy");export{P as a,C as b,O as c,U as d,gt as e};
|
package/dist/cli/cli.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as o,e as
|
|
3
|
-
See: ${
|
|
4
|
-
See: ${
|
|
5
|
-
${n}`),{cause:t}):null}o(
|
|
2
|
+
import{a as o,e as Lt}from"../chunk-A5ASLC6T.js";import{writeSync as fp}from"fs";import{Command as yp}from"commander";var Ot="https://docs.cognite.com/cdf/access/";function j(e){return e!==null&&typeof e=="object"}o(j,"isRecord");function ce(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(ce,"isHttpError");function ro(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
3
|
+
See: ${Ot}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
4
|
+
See: ${Ot}`;default:return}}o(ro,"httpStatusHint");function te(e){let t=e instanceof Error?e:new Error(String(e));if(!ce(t))return null;let n=ro(t.status);return n?Object.assign(new Error(`${t.message}
|
|
5
|
+
${n}`),{cause:t}):null}o(te,"enrichedHttpError");function oo(e){if(!j(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(j(n)){let r=n.error;if(j(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}o(oo,"findMissingArray");function io(e,t){if(!ce(e)||e.status!==400)return!1;let n=oo(e);return n?n.some(r=>j(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}o(io,"isMissingExternalIdError");function Ke(e,t){return ce(e)&&e.status===404||io(e,t)}o(Ke,"isNotFoundError");var _t=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],jt=["ACTIVE","PREVIEW"],Ge=class Ge extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};o(Ge,"AppVersionNotFoundError");var F=Ge;function Mt(e,t){return e.includes(t)}o(Mt,"includesValue");function so(e){return Mt(_t,e)}o(so,"isAppVersionLifecycleState");function ao(e){return Mt(jt,e)}o(ao,"isAppVersionAlias");function po(e){return typeof e.version=="string"&&so(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||ao(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(po,"isAppVersion");function Nt(e){if(!j(e))throw new Error("Invalid version response: not an object");if(!po(e))throw new Error("Invalid version response: missing or malformed fields");return e}o(Nt,"parseAppVersion");var He=class He{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 te(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 p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,d=await this.client.authenticate(),l=`${this.client.getBaseUrl()}${c}`,m=new AbortController,g=setTimeout(()=>m.abort(),300*1e3),f;try{f=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${d}`},body:a,signal:m.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new Error("Upload timed out after 5 minutes"):y}finally{clearTimeout(g)}if(!f.ok){let y=await f.text(),w=y;try{let S=JSON.parse(y);if(j(S)){let x=S.error;if(typeof x=="string")w=x;else if(j(x)){let T=x.message,v=x.code;w=typeof T=="string"?T:v!=null?`Unknown error (code: ${v})`:y}else{let T=S.message;w=typeof T=="string"?T:y}}}catch{}let u=f.headers.get("x-request-id"),h=u?` | X-Request-ID: ${u}`:"",C=Object.assign(new Error(`Upload failed: ${f.status} \u2014 ${w}${h}`),{status:f.status});throw te(C)??C}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 Nt(a.data)}catch(a){throw Ke(a,[t,n])?new F(t,n):te(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/active`;try{let i=await this.client.get(r);return Nt(i.data)}catch(i){if(Ke(i,[t]))return null;throw te(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 te(s)??s}}};o(He,"AppHostingApi");var xe=He;var Be=class Be{constructor(t){this.api=new xe(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(ce(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`)}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,p=!1){console.log(`
|
|
6
6
|
\u{1F680} Deploying application via App Hosting API...
|
|
7
|
-
`);try{await this.ensureApp(t,n,r),await this.uploadVersion(t,i,s,a),
|
|
8
|
-
\u2705 Deployment successful!`)}catch(
|
|
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"),
|
|
10
|
-
${
|
|
7
|
+
`);try{await this.ensureApp(t,n,r),await this.uploadVersion(t,i,s,a),p&&await this.publishAndActivate(t,i),console.log(`
|
|
8
|
+
\u2705 Deployment successful!`)}catch(c){let d=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${d}`),{cause:c})}}};o(Be,"AppHostingClient");var E=Be;import{existsSync as Co,readFileSync as xo}from"fs";import{resolve as vo}from"path";import{array as co,boolean as lo,check as Vt,forward as Ut,literal as mo,maxLength as uo,minLength as go,nonEmpty as ne,object as Kt,optional as B,picklist as fo,pipe as M,safeParse as yo,string as L,url as ho}from"valibot";var qe=M(L(),ne("must not be empty")),Qe=M(L(),ne("must not be empty"),uo(256,"must be 256 characters or fewer")),Je=M(L(),ne("must not be empty"),ho("must be a valid URL")),Ye=M(L(),ne("must not be empty")),ze=M(L(),ne("must not be empty")),wo=M(Kt({org:Ye,project:ze,baseUrl:Je,deployClientId:B(L(),""),deploySecretName:B(L(),""),published:B(lo(),!1),idpType:B(fo(["cdf","entra_id"]),"cdf"),tenantId:B(L())}),Ut(Vt(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),Ut(Vt(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),So=Kt({name:qe,externalId:Qe,versionTag:M(L(),ne("must not be empty")),description:B(L(),""),deployments:M(co(wo),go(1,"must contain at least one deployment")),infra:B(mo("appsApi"))});function We(e){let t=yo(So,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(We,"validateAppConfig");function k(e,t={}){let{validator:n=We,existsSync:r=Co,readFileSync:i=xo}=t,s=vo(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"),p;try{p=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return n(p)}o(k,"loadAppConfig");import{CogniteClient as qo}from"@cognite/sdk";import{CogniteClient as Io}from"@cognite/sdk";var ko=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"),Eo=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=ko()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),bo=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"),Po=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"),Ao=o(async(e,t,n,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let i=bo(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`,p=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(!p.ok){let d=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
|
|
10
|
+
${d}`)}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"),le=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,p=Eo(r);if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Ao(n,p,s,a)}return Po(n,p)},"getToken");async function de(e,t,n=process.env,r){let i=await le(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new Io(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i,"oidcTokenProvider")});return await a.authenticate(),a}o(de,"getSdk");import Oo from"os";import No from"path";import _o from"open";import{buildAuthorizationUrl as jo,calculatePKCECodeChallenge as Mo,discovery as Vo,None as Uo,randomPKCECodeVerifier as Ko,randomState as Go}from"openid-client";import $o from"https";import{authorizationCodeGrant as Do}from"openid-client";function Gt(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}o(Gt,"escapeHtml");function Xe(e,t,n){let r=Gt(t),i=Gt(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
|
|
11
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); }
|
|
@@ -16,31 +16,31 @@ ${l}`)}let p=await c.json();if(!p.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(
|
|
19
|
+
</body></html>`}o(Xe,"generateHtml");async function To(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 p=await s.authorizationCodeGrant(n,a,{pkceCodeVerifier:r,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(Xe("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(Xe("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(To,"handleCallback");function Ro(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}o(Ro,"formatTimeoutMinutes");function Ht(e,t,n,r,i,s={createServer:$o.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:Do}){return new Promise((a,p)=>{let c,d=s.setTimeout(()=>{c?.close(),p(new Error(`Login timeout - no response received within ${Ro(e.loginTimeout)}`))},e.loginTimeout);c=s.createServer(t,async(l,m)=>{try{let g=await To(l,m,n,r,i,s);g.shouldClose&&(s.clearTimeout(d),c?.close(),g.error?p(g.error):g.tokens?a(g.tokens):p(new Error("No tokens received")))}catch(g){s.clearTimeout(d),c?.close(),p(g instanceof Error?g:new Error(String(g)))}}),c.on("error",l=>{s.clearTimeout(d),l.code==="EADDRINUSE"?console.error(`\u274C Port ${e.port} is already in use.`):console.error(`\u274C Server error: ${l.message}`),p(l)}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}o(Ht,"startCallbackServer");import{execFileSync as Fo}from"child_process";import Ze from"fs";import Bt from"path";function qt(e,t,n){return{key:n.readFileSync(e),cert:n.readFileSync(t)}}o(qt,"loadCertificates");function Lo(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"),qt(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(
|
|
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,
|
|
24
|
-
`);try{await n.open(
|
|
25
|
-
`),n.logger.error(
|
|
22
|
+
On Windows: Install OpenSSL or use WSL`)}}o(Lo,"generateCertificate");function Qt(e,t={existsSync:Ze.existsSync,readFileSync:o(n=>Ze.readFileSync(n),"readFileSync"),mkdirSync:o((n,r)=>{Ze.mkdirSync(n,r)},"mkdirSync"),execFileSync:Fo}){let n=Bt.join(e,"localhost-key.pem"),r=Bt.join(e,"localhost-cert.pem");return t.existsSync(n)&&t.existsSync(r)?qt(n,r,t):Lo(e,n,r,t)}o(Qt,"getOrCreateCertificates");var Ho={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:No.join(Oo.homedir(),".cdf-login")},Bo={open:_o,getOrCreateCertificates:Qt,startCallbackServer:Ht,discovery:Vo,buildAuthorizationUrl:jo,randomPKCECodeVerifier:Ko,calculatePKCECodeChallenge:Mo,randomState:Go,logger:console};async function ve(e,t=Ho,n){return n===void 0?Jt(e,t,Bo):Jt(e,t,n)}o(ve,"login");async function Jt(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,Uo()),i=n.randomPKCECodeVerifier(),s=await n.calculatePKCECodeChallenge(i),a=n.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=n.buildAuthorizationUrl(r,p).toString(),d=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(c)}catch(l){let m=l instanceof Error?l.message:String(l);n.logger.error("\u274C Failed to open browser automatically."),n.logger.error(` Reason: ${m}`),n.logger.error(`Please open this URL manually:
|
|
25
|
+
`),n.logger.error(c),n.logger.error("")}return n.startCallbackServer(t,d,r,i,a)}o(Jt,"loginImpl");async function V(e,t,n={}){let{login:r=ve,getSdk:i=de,createClient:s=o(a=>new qo(a),"createClient")}=n;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await r(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(V,"getClientForDeployment");import Yt from"enquirer";var zt="Enter custom target...";function Wt(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
|
-
${n}`)}o(
|
|
27
|
+
${n}`)}o(Wt,"deploymentNotFoundError");function _(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;Wt(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;Wt(t,e)}o(_,"findDeployment");function O(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o(O,"getMissingCredentials");async function U(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 _(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),zt],{selected:r}=await Yt.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==zt){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 Yt.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(U,"resolveDeployment");import{existsSync as Qo}from"fs";import{resolve as Jo}from"path";import{config as Yo}from"dotenv";function $(e,t={existsSync:Qo,config:Yo}){let n=Jo(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}o($,"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(
|
|
34
|
+
`),process.exit(1))}o(K,"assertAppHostingInfra");async function zo(e){let t=process.cwd();$(t);let n=k(t);K(n);let r=e.interactive?await U(n,e):_(n.deployments,e.deployment);if(!e.interactive){let l=O(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 activate --interactive\` for browser-based authentication instead.`)}let i=await V(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new E(i),{externalId:a,versionTag:p}=n,c;try{c=await s.getVersion(a,p)}catch(l){throw l instanceof F?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==="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:d}=await s.activateVersion(a,p);console.log(`\u2713 Activated ${a} @ ${p} is now ACTIVE`),d&&console.log(` Superseded ${d} \u2192 PUBLISHED`)}o(zo,"handleActivate");function Xt(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,n)=>
|
|
38
|
-
`),initial:!1};async function
|
|
39
|
-
`),i=`link .specify/memory/constitution.md in specifyDir=${n}`,
|
|
37
|
+
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>zo(n))}o(Xt,"registerActivateCommand");import{readdirSync as ci}from"fs";import{basename as un,dirname as li,normalize as di,resolve as ue}from"path";import{fileURLToPath as mi,pathToFileURL as ui}from"url";import{Logger as gi,runner as fi}from"hygen";import{safeParse as Wo}from"valibot";function me(e,t){return n=>{let r=Wo(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}o(me,"toPromptValidator");var Zt={name:me("App name",Qe),displayName:me("Display name",qe),baseUrl:me("Base URL",Je),org:me("Org",Ye),project:me("Project",ze)};function Xo(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}o(Xo,"composeValidators");function ke(e){return e.map(t=>{if(!(t.name in Zt))return t;let n=Zt[t.name];return{...t,validate:Xo(t.validate,n)}})}o(ke,"applySchemaValidators");import{execFileSync as Ee}from"child_process";function en(e={}){let{execFileSync:t=Ee}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(en,"isGitInstalled");function tn(e,t={}){let{execFileSync:n=Ee}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(tn,"isInsideGitRepo");function nn(e,t={}){let{execFileSync:n=Ee}=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(nn,"gitInitAndCommit");function rn(e={}){let{execFileSync:t=Ee}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(rn,"gitUserEmail");import{basename as sn}from"path";import an from"enquirer";function on(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(on,"kebabCase");var Zo={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 ei(e){return!!(await e([Zo])).useSpecKit}o(ei,"promptForSpecKit");async function ti(e,t,n){return e!==void 0?e:t?ei(n):!1}o(ti,"resolveSpecKit");function pn({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:i={},specKit:s,prompt:a=an.prompt.bind(an)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(v=>v[1]!==void 0)),d=Object.keys(c).length>0,l=e?sn(process.cwd()):t?sn(t):null,m=d&&l!==null,g=!m&&l?p.map(v=>v.name==="name"?{...v,initial:l}:v):p,f=ke(g),y=m?{...c,name:l}:c,w=new Set(Object.keys(y)),u=f.filter(v=>!w.has(v.name)),h=u.findIndex(v=>v.name==="baseUrl"),C;if(h!==-1){let v=u.filter(no=>no.name!=="baseUrl"),Ue=v.length>0?await a(v):{},Wr=typeof Ue.cluster=="string"?Ue.cluster:"",Xr=typeof y.cluster=="string"?y.cluster:"",Zr=`https://${(Wr||Xr).trim().replace(/\/+$/,"")||"api"}.cognitedata.com`,eo=u[h],to=await a([{...eo,initial:Zr}]);C={...Ue,...to}}else C=u.length>0?await a(u):{};let S={...y,...C},x=typeof S.name=="string"?S.name:"";x&&n(x);let T=await ti(s,u.length>0,a);return r?.(T),{...S,name:x,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:T}},"prompt")})}o(pn,"createAppPrompter");async function cn(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:`--${on(s)}`});for(let{key:s,value:a,label:p}of r){let c=e.find(l=>l.name===s)?.validate;if(!c)continue;let d=await c(a);if(d!==!0)throw new Error(`Invalid ${p}: ${d}`)}}o(cn,"validatePresets");import{cpSync as ri,mkdirSync as ln,writeFileSync as oi}from"fs";import{dirname as dn,resolve as q}from"path";import{fileURLToPath as ii}from"url";import{symlinkSync as ni}from"fs";function be({target:e,linkPath:t,label:n,symlink:r=ni}){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(be,"symlinkOrWarn");var si=q(dn(ii(import.meta.url)),"..","..","_vendor","spec-kit"),ai={branch_numbering:"sequential"},pi=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}];function mn({appDir:e,vendorDir:t=si}){let n=q(e,".specify"),r=q(n,"memory"),i=`prepare spec-kit install for appDir=${e}`;try{for(let{from:s,to:a}of pi){let p=q(e,a);i=`copy ${s} to ${a}`,ln(dn(p),{recursive:!0}),ri(q(t,s),p,{recursive:!0})}i=`write init-options.json under specifyDir=${n}`,oi(q(n,"init-options.json"),`${JSON.stringify(ai,null,2)}
|
|
39
|
+
`),i=`link .specify/memory/constitution.md in specifyDir=${n}`,ln(r,{recursive:!0}),be({target:"../../AGENTS.md",linkPath:q(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(mn,"installSpecKit");var gn=ue(li(mi(import.meta.url)),"..","..","_templates");async function yi(){let e=ue(gn,"app","new","prompt.js");return(await import(ui(e).href)).default}o(yi,"loadPromptDefs");function hi(e,t){return!e||t?null:di(e)}o(hi,"resolveDirName");function wi(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:ue(process.cwd(),r),display:r}}o(wi,"resolveAppLocation");function Si(e,t,n){let r=` npm install
|
|
40
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
|
-
`:"",
|
|
43
|
+
`:"",p=` # 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
|
|
|
@@ -49,7 +49,7 @@ ${r}
|
|
|
49
49
|
${a}
|
|
50
50
|
${i}
|
|
51
51
|
${s}
|
|
52
|
-
${
|
|
52
|
+
${p}
|
|
53
53
|
`);return}console.log(`
|
|
54
54
|
\u2705 App created successfully!
|
|
55
55
|
|
|
@@ -62,9 +62,9 @@ ${a}
|
|
|
62
62
|
${i}
|
|
63
63
|
cd "${t}"
|
|
64
64
|
${s}
|
|
65
|
-
${
|
|
66
|
-
`)}o(
|
|
67
|
-
${r}`)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}o(
|
|
65
|
+
${p}
|
|
66
|
+
`)}o(Si,"printSuccessMessage");async function Ci(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=ue(e,".agents","skills"),i=0;try{i=ci(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(Ci,"pullSkillsInto");function xi(e,t={}){let{isGitInstalled:n=en,isInsideGitRepo:r=tn,gitInitAndCommit:i=nn}=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 p=(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:",p)}}}o(xi,"maybeInitGit");async function vi(e,t){let n=e==="."||e==="./",r=hi(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},p=await yi(),c=ke(p),d=n?un(process.cwd()):r?un(r):null;await cn(c,a,d);let l=pn({isCurrentDir:n,dirName:r,onAppName:o(g=>{i=g},"onAppName"),onUseSpecKit:o(g=>{s=g},"onUseSpecKit"),presets:a,specKit:t.specKit});await fi(["app","new"],{templates:gn,cwd:process.cwd(),logger:new gi(console.log.bind(console)),createPrompter:l,debug:!!process.env.DEBUG});let m=wi(n,r,i);be({target:"AGENTS.md",linkPath:ue(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&mn({appDir:m.cwd}),await Ci(m.cwd),xi(m.cwd),Si(n,m.display,s)}o(vi,"handleCreate");function fn(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,17 +77,14 @@ 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(
|
|
81
|
-
|
|
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(`
|
|
80
|
+
Fully non-interactive`).action(vi)}o(fn,"registerCreateCommand");import{readFile as $i,unlink as Di}from"fs/promises";import{basename as Ti}from"path";import hn from"fs";import Ai from"path";import G from"fs";import b from"path";import{parseAndValidateManifestConfig as ki}from"@cognite/app-sdk/vite";import{BlobReader as Ei,Uint8ArrayWriter as bi,ZipWriter as Pi}from"@zip.js/zip.js";var et="package.json",tt="package-lock.json",yn="manifest.json",nt=".cognite",rt=class rt{constructor(t="dist"){this.distPath=b.isAbsolute(t)?t:b.join(process.cwd(),t),this.appRoot=b.dirname(this.distPath)}validateBuildDirectory(){if(!G.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=b.join(this.appRoot,et);if(!G.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=b.join(this.appRoot,tt);if(!G.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 Pi(new bi,{level:9}),i=o(async(c,d)=>{await r.add(d,new Ei(await G.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${d}`)},"addFile"),s=o(async c=>{let d=await G.promises.readdir(c,{withFileTypes:!0});for(let l of d){let m=b.join(c,l.name);l.isDirectory()?await s(m):await i(m,b.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=b.join(this.appRoot,et);await i(c,b.posix.join(nt,et));let d=b.join(this.appRoot,yn);if(G.existsSync(d)){let m=G.readFileSync(d,"utf-8");ki(m,d),await i(d,b.posix.join(nt,yn))}let l=b.join(this.appRoot,tt);await i(l,b.posix.join(nt,tt)),a=await r.close()}catch(c){let d=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${d}`)}await G.promises.writeFile(t,a);let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}};o(rt,"ApplicationPackager");var Q=rt;var ot=o(async(e,t,n)=>{let r=await new Q(`${n}/dist`).createZip("app.zip",!0);try{let{externalId:i,name:s,description:a,versionTag:p}=t,c=await de(e,n),d=new E(c),l=hn.readFileSync(r),m=Ai.basename(r);await d.deploy(i,s,a,p,l,m,e.published)}finally{try{hn.unlinkSync(r)}catch{}}},"deploy");import{execSync as Ii}from"child_process";function it(e,t=!0,n={execSync:Ii}){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(it,"buildApp");function wn(e,t){let{org:n,project:r,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://${n}.fusion.cognite.com/${r}/flows-apps/app/${encodeURIComponent(a)}?${c}`}o(wn,"generateFusionUrl");function Sn(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(`
|
|
81
|
+
`))}o(Sn,"printDeployInfo");function Cn(e,t){console.log(`
|
|
85
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 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=
|
|
83
|
+
To publish: npx @cognite/cli apps publish .${n}`),console.log(`To activate: npx @cognite/cli apps activate .${n}`);let r=wn(t,e);r&&console.log(`
|
|
87
84
|
\u{1F517} Open your app:
|
|
88
|
-
${r}`)}o(
|
|
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)
|
|
90
|
-
\u{1F4E4} Deploying to ${t.project}...`);let s=await new
|
|
85
|
+
${r}`)}o(Cn,"printDeployResult");async function Ri(e,t,n,r,i){let s=O(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.`);Sn(e,t,!1),r.skipBuild||it(n),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},n),Cn(e,t)}o(Ri,"handleDeployNonInteractive");async function Fi(e,t,n,r){Sn(e,t,!0),r.skipBuild||it(n);let i=await V(t,{interactive:!0,appId:e.externalId,orgHint:r.org});console.log(`
|
|
87
|
+
\u{1F4E4} Deploying to ${t.project}...`);let s=await new Q(`${n}/dist`).createZip("app.zip",!0);try{let a=await $i(s);await new E(i).deploy(e.externalId,e.name,e.description,e.versionTag,a,Ti(s),!1),Cn(e,t)}finally{await Di(s).catch(()=>{})}}o(Fi,"handleDeployInteractive");async function Li(e,t=process.cwd(),n={}){let{loadEnvFile:r=$,loadAppConfig:i=k,deploy:s=ot}=n;r(t);let a=i(t);if(K(a),e.interactive){let c=await U(a,e);await Fi(a,c,t,e);return}let p=_(a.deployments,e.deployment);await Ri(a,p,t,e,s)}o(Li,"handleDeploy");function xn(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",`
|
|
91
88
|
Environment (non-interactive):
|
|
92
89
|
deployClientId and deploySecretName are configured per deployment in app.json.
|
|
93
90
|
deploySecretName is the name of the environment variable that holds the client
|
|
@@ -101,42 +98,137 @@ Examples:
|
|
|
101
98
|
npx @cognite/cli apps deploy -d my-project Deploy to project by name
|
|
102
99
|
npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
|
|
103
100
|
npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
|
|
104
|
-
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>
|
|
101
|
+
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>Li(t))}o(xn,"registerDeployCommand");async function Oi(e){let t=process.cwd();$(t);let n=k(t);K(n);let r=e.interactive?await U(n,e):_(n.deployments,e.deployment);if(!e.interactive){let d=O(r);if(d.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${d.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let i=await V(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new E(i),{externalId:a,versionTag:p}=n,c;try{c=await s.getVersion(a,p)}catch(d){throw d instanceof F?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):d}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(Oi,"handlePublish");function vn(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",`
|
|
105
102
|
Examples:
|
|
106
103
|
npx @cognite/cli apps publish . Publish using env-var auth
|
|
107
|
-
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>
|
|
104
|
+
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>Oi(n))}o(vn,"registerPublishCommand");function Ni(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(Ni,"describeStatus");async function _i(e){let t=process.cwd();$(t);let n=k(t);K(n);let r=e.interactive?await U(n,e):_(n.deployments,e.deployment);if(!e.interactive){let a=O(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 V(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new E(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),p=Ni(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 F){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}o(_i,"handleStatus");function kn(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",`
|
|
108
105
|
Examples:
|
|
109
106
|
npx @cognite/cli apps status . Status using env-var auth
|
|
110
|
-
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>
|
|
111
|
-
`,"kv"),
|
|
107
|
+
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>_i(n))}o(kn,"registerStatusCommand");function En(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return fn(t),xn(t),kn(t),vn(t),Xt(t),Lt(t),t}o(En,"registerAppsCommand");import{existsSync as Ds,mkdirSync as Ts,writeFileSync as Rs}from"fs";import{dirname as gt,join as ft}from"path";import{execFile as Mi}from"child_process";import{promisify as Vi}from"util";import{platform as ji}from"os";function J(e={}){let{platform:t=ji}=e;return t()==="darwin"}o(J,"isMacOS");var bn="cognite-flows",Ui=Vi(Mi),Pn=o((e,t)=>Ui(e,t),"defaultExecFile"),Ki=-25300,Gi=Ki&255;function Hi(e){if(!(e instanceof Error)||!("code"in e)||e.code!==Gi)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(Hi,"isKeychainNotFoundError");async function An(e,t,n={}){if(!J(n))throw new Error("Keychain storage is only supported on macOS");let{execFile:r=Pn}=n;await r("security",["add-generic-password","-a",e,"-s",bn,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(An,"storeKeyInKeychain");async function In(e,t={}){if(!J(t))return null;let{execFile:n=Pn}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",bn,"-w"]);return Buffer.from(r.trim(),"base64").toString("utf-8")}catch(r){if(Hi(r))return null;throw r}}o(In,"readKeyFromKeychain");import{pbkdf2 as Qi,randomBytes as Ji}from"crypto";import{promisify as Yi}from"util";import{CompactEncrypt as zi,base64url as Wi,compactDecrypt as Od}from"jose";var Bi=new TextEncoder,qi=new TextDecoder,$n={encode:o(e=>Bi.encode(e),"encode"),decode:o(e=>qi.decode(e),"decode")};var Xi=Yi(Qi),st=6e5,Zi="sha512",es="PBKDF2-HMAC-SHA512",ts=16,ns="A256GCM",rs=32,Dn=2e6;async function os(e,t,n){return await Xi(e,t,n,rs,Zi)}o(os,"deriveKey");async function Tn(e,t,n=st){if(!Number.isInteger(n)||n<1||n>Dn)throw new Error(`Invalid iterations: must be an integer between 1 and ${Dn}`);let r=Ji(ts),i=await os(t,r,n);return await new zi($n.encode(e)).setProtectedHeader({alg:"dir",enc:ns,kdf:es,kdf_iter:n,kdf_salt:Wi.encode(r)}).encrypt(i)}o(Tn,"encryptStringAsJwe");import{calculateJwkThumbprint as is,exportJWK as ss,exportPKCS8 as as,exportSPKI as ps,generateKeyPair as cs}from"jose";async function Rn(){let{publicKey:e,privateKey:t}=await cs("EdDSA",{extractable:!0}),n=await as(t),r=await ps(e),i=await ss(e),s=await is(i);return{privateKeyPem:n,publicKeyPem:r,kid:s}}o(Rn,"generateSigningKeyPair");import{existsSync as ds,readdirSync as ms,readFileSync as us}from"fs";import{join as Pe}from"path";import{homedir as ls}from"os";import{join as Fn}from"path";function Y(e={}){let{env:t=process.env,homedir:n=ls}=e,r=t.DUNE_HOME?.trim()||Fn(n(),".dune");return{home:r,keysDir:Fn(r,"keys")}}o(Y,"getConfig");var Ae=".pub.pem",at=".key.jwe",gs=".pem",pt=".meta.json";function Ln(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(Ln,"formatLocalKeySource");function fs(e){return{existsSync:e.existsSync??ds,readdirSync:e.readdirSync??ms,readFileSync:e.readFileSync??((t,n)=>us(t,n)),isMacOS:e.isMacOS??(()=>J()),readKeyFromKeychain:e.readKeyFromKeychain??(t=>In(t))}}o(fs,"resolveDeps");function ys(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(ys,"readEmailFromMeta");function hs(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(Ae)):[]}o(hs,"publicKeyEntries");function ws(e){return e.slice(0,-Ae.length)}o(ws,"kidFromPublicKeyFilename");async function Ss(e,t,n){if(n.isMacOS()&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let r=Pe(t,`${e}${at}`);if(n.existsSync(r))return{kind:"encrypted-file",path:r};let i=Pe(t,`${e}${gs}`);return n.existsSync(i)?{kind:"legacy-unencrypted-file",path:i}:{kind:"public-only"}}o(Ss,"resolveSource");async function On(e=Y().keysDir,t={}){let n=fs(t),r=new Set,i=hs(e,n).flatMap(s=>{let a=ws(s);return!a||r.has(a)?[]:(r.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let p=await Ss(s,e,n),c=Pe(e,`${s}${pt}`),d;try{d=ys(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:Pe(e,a),email:d}}))}o(On,"discoverLocalKeys");function Nn(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(Nn,"addMonthsClamped");function ct(e){return e.toISOString().slice(0,10)}o(ct,"formatIsoDate");function _n(e=new Date){return ct(e)}o(_n,"todayIso");import Cs,{Chalk as xs}from"chalk";var lt=new xs({level:0});function jn(e){return e.isTTY?Cs:lt}o(jn,"chalkForStream");function vs(e){return e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"")}o(vs,"pemBodyOneLine");function Mn(e,t=lt,n=new Date){let r=e.issuedAt??_n(n),i=vs(e.publicKeyPem),s=" ",a=o((c,d)=>`${s}${t.cyan(c)}${t.dim(":")} ${d}
|
|
108
|
+
`,"kv"),p="";return p+=`
|
|
112
109
|
${t.bold("Add this entry to")} ${t.magenta("services/app-hosting/config/signing-keys.yaml")} ${t.bold("under")} ${t.cyan("public_keys:")}
|
|
113
110
|
|
|
114
|
-
`,
|
|
115
|
-
`,
|
|
116
|
-
`,"passphraseMismatchMsg"),
|
|
117
|
-
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${
|
|
118
|
-
`);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,
|
|
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(r)),p+=a("expires",t.green(e.expires)),p+=a("revoked_at",t.dim("null")),p}o(Mn,"renderRegistryEntry");import{email as ks,pipe as Es,safeParse as bs,string as Ps}from"valibot";var As=Es(Ps(),ks());function fe(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!bs(As,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}o(fe,"parseEmail");function ye(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(ye,"parseExpiryMonths");import $s from"enquirer";var Ie=3,Vn=`Key expiry in months (${1}-${12})`,Un="Email address for the registry entry",Kn=`Passphrase for the encrypted private key (min ${15} chars)`,Gn="Confirm passphrase",Hn=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),Bn=o(e=>`Passphrases do not match (attempt ${e}/${Ie}).
|
|
113
|
+
`,"passphraseMismatchMsg"),qn=`Passphrase confirmation failed after ${Ie} attempts`;async function ut(e){return $s.prompt(e)}o(ut,"defaultPrompt");function Qn(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}o(Qn,"parserAsValidator");async function Jn(e={}){let{prompt:t=ut}=e,{months:n}=await t({type:"input",name:"months",message:Vn,initial:String(6),validate:Qn(r=>ye(r,"expiry"))});return ye(n,"expiry")}o(Jn,"promptExpiryMonths");async function Yn(e={}){let{prompt:t=ut,gitUserEmail:n=rn}=e,{email:r}=await t({type:"input",name:"email",message:Un,initial:n(),validate:Qn(i=>fe(i,"email"))});return fe(r,"email")}o(Yn,"promptEmail");async function zn(e={}){let{prompt:t=ut,stderr:n=process.stderr}=e;for(let r=1;r<=Ie;r+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:Kn,validate:o(a=>a.length>=15?!0:Hn(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:Gn});if(i===s)return i;n.write(Bn(r))}throw new Error(qn)}o(zn,"promptPassphrase");function Fs(e){return{writeFileSync:e.writeFileSync??Rs,mkdirSync:e.mkdirSync??Ts,existsSync:e.existsSync??Ds,generateSigningKeyPair:e.generateSigningKeyPair??Rn,encryptStringAsJwe:e.encryptStringAsJwe??Tn,storeKeyInKeychain:e.storeKeyInKeychain??An,isMacOS:e.isMacOS??J,promptExpiryMonths:e.promptExpiryMonths??Jn,promptEmail:e.promptEmail??Yn,promptPassphrase:e.promptPassphrase??zn,discoverLocalKeys:e.discoverLocalKeys??(()=>On())}}o(Fs,"resolveDeps");function Xn(e,t={}){let n=Fs(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=>Ns(i,n)),r.command("list").description("List local signing identities and their storage location").action(()=>Ls(n))}o(Xn,"registerKeysCommand");async function Ls(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
|
|
114
|
+
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${Y().keysDir}).
|
|
115
|
+
`);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,Ln(a.source),a.email??"\u2014"]),i=n.map((a,p)=>Math.max(a.length,...r.map(c=>c[p].length))),s=o(a=>a.map((p,c)=>p.padEnd(i[c])).join(" ").trimEnd(),"fmt");process.stdout.write(`${s(n)}
|
|
119
116
|
`);for(let a of r)process.stdout.write(`${s(a)}
|
|
120
|
-
`)}o(
|
|
117
|
+
`)}o(Ls,"handleList");function Wn(e,t,n){let r=ft(Y().keysDir,`${e}${Ae}`);return n.mkdirSync(gt(r),{recursive:!0}),n.writeFileSync(r,t),r}o(Wn,"writePublicKey");async function Os(e,t,n,r,i){let s=r??ft(Y().keysDir,`${e}${at}`);if(i.mkdirSync(gt(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(Os,"writeEncryptedPrivateKey");async function Ns(e,t,n=new Date){let r=e.keychain!==!1&&t.isMacOS()&&!e.output,i=e.expires!==void 0?ye(e.expires):await t.promptExpiryMonths(),s=ct(Nn(n,i)),a=e.email!==void 0?fe(e.email,"--email"):await t.promptEmail(),p=r?null:await t.promptPassphrase();process.stderr.write(`
|
|
121
118
|
Generating Ed25519 keypair...
|
|
122
119
|
|
|
123
|
-
`);let{privateKeyPem:
|
|
124
|
-
`),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${
|
|
125
|
-
`)}else{if(
|
|
126
|
-
`),process.stderr.write(`Private key: ${f} (JWE, AES-256-GCM, PBKDF2-SHA512 x${
|
|
120
|
+
`);let{privateKeyPem:c,publicKeyPem:d,kid:l}=await t.generateSigningKeyPair();if(r){await t.storeKeyInKeychain(l,c);let f=Wn(l,d,t);process.stderr.write(`Public key: ${f}
|
|
121
|
+
`),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${l})
|
|
122
|
+
`)}else{if(p===null)throw new Error("passphrase is required when not using Keychain");let f=await Os(l,c,p,e.output,t),y=Wn(l,d,t);process.stderr.write(`Public key: ${y}
|
|
123
|
+
`),process.stderr.write(`Private key: ${f} (JWE, AES-256-GCM, PBKDF2-SHA512 x${st.toLocaleString()})
|
|
127
124
|
`),t.isMacOS()||process.stderr.write(` (macOS Keychain integration is the default on darwin; on this OS we use the file.)
|
|
128
|
-
`)}let
|
|
129
|
-
Signing identity (kid): ${
|
|
125
|
+
`)}let m=ft(Y().keysDir,`${l}${pt}`);t.mkdirSync(gt(m),{recursive:!0}),t.writeFileSync(m,JSON.stringify({email:a}));let g=jn(process.stderr);process.stderr.write(`
|
|
126
|
+
Signing identity (kid): ${g.green(l)}
|
|
130
127
|
`),process.stderr.write(`Expires: ${s} (${i} month${i===1?"":"s"} from today)
|
|
131
|
-
`),process.stderr.write(
|
|
132
|
-
${
|
|
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
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
`)
|
|
142
|
-
|
|
128
|
+
`),process.stderr.write(Mn({kid:l,publicKeyPem:d,email:a,expires:s},g,n)),process.stderr.write(`
|
|
129
|
+
${g.bold("Next:")} open a PR against the ${g.magenta("infrastructure")} repo with that block, then \`${g.cyan(`cognite sign -s ${l}`)}\`
|
|
130
|
+
`)}o(Ns,"handleGenerate");import{existsSync as $r,readFileSync as pe,writeFileSync as bt,mkdirSync as Fa}from"fs";import{resolve as N}from"path";import{fileURLToPath as Pr}from"url";import{CogniteClient as La}from"@cognite/sdk";import{mkdirSync as Da,readFileSync as Ta,rmSync as Ra,writeFileSync as ae}from"fs";import{resolve as H}from"path";import{generate as Er}from"@graphql-codegen/cli";import{GraphQLSchema as ha,GraphQLObjectType as wa,GraphQLNonNull as R,GraphQLList as se,GraphQLString as Z,GraphQLInt as Sa,GraphQLInputObjectType as hr,printSchema as Ca}from"graphql";function yt(e){return{space:e.space,externalId:e.externalId,version:e.version}}o(yt,"toSharedViewId");function _s(e){switch(e){case"text":return"String";case"boolean":return"Boolean";case"int32":case"int64":return"Int";case"float32":case"float64":return"Float";case"timestamp":return"DateTime";case"date":return"Date";case"json":return"JSON";case"timeseries":return"CogniteTimeSeriesReference";case"file":return"CogniteFileReference";case"sequence":return"CogniteSequenceReference";case"enum":return"String";default:return"String"}}o(_s,"dmsTypeToGraphQL");function Zn(e){if(!("source"in e)){if(e.type?.type==="direct")return e.type.list?{kind:"scalar",isList:!1,graphqlType:"JSON"}:e.type.source?{kind:"directRelation",targetView:yt(e.type.source)}:{kind:"scalar",isList:!1,graphqlType:"JSON"};if(e.type?.type==="enum"){let t=e.type,n={};if(typeof t=="object"&&t!==null&&"values"in t){let r=t.values;if(typeof r=="object"&&r!==null)for(let[i,s]of Object.entries(r))n[i]={name:typeof s=="object"&&s!==null&&"name"in s?String(s.name):void 0}}return{kind:"enum",values:Object.keys(n),valueNames:Object.fromEntries(Object.entries(n).map(([r,i])=>[r,i.name??r]))}}return{kind:"scalar",isList:e.type!==void 0&&"list"in e.type&&e.type.list===!0,graphqlType:e.type?.type?_s(e.type.type):"String"}}if("through"in e)return{kind:e.connectionType==="single_reverse_direct_relation"?"reverseDirect":"reverseList",sourceView:yt(e.source),throughProperty:e.through.identifier};if(e.connectionType==="single_edge_connection"||e.connectionType==="multi_edge_connection"){let t=e.direction==="inwards"?"inwards":"outwards";return{kind:"edge",targetView:yt(e.source),direction:t}}return{kind:"scalar"}}o(Zn,"parsePropertyDescriptor");var er=new Set(["String","Boolean","Int","Float","DateTime","Date"]);var js=new Set(["String","Int","Float","DateTime","Date"]);function $e(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:er.has(e.graphqlType??"String")}o($e,"isFilterableDescriptor");function De(e){return e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:er.has(e.graphqlType??"String")}o(De,"isSortableDescriptor");function tr(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind==="scalar"&&e.isList!==!0&&js.has(e.graphqlType??"")}o(tr,"hasInOpDescriptor");function nr(e){return e.kind==="scalar"&&e.isList===!0}o(nr,"hasListOpsDescriptor");function he(e){return e.usedFor!=="edge"}o(he,"isNodeOrAll");function D(e){return Object.entries(e.properties).map(([t,n])=>[t,Zn(n),n.description])}o(D,"parsedProperties");import{GraphQLObjectType as rr,GraphQLNonNull as we,GraphQLString as Ct,GraphQLFloat as Re,GraphQLList as Hs,GraphQLEnumType as Bs}from"graphql";import{GraphQLScalarType as z,Kind as P}from"graphql";function ht(e){switch(e.kind){case P.STRING:case P.BOOLEAN:return e.value;case P.INT:return parseInt(e.value,10);case P.FLOAT:return parseFloat(e.value);case P.OBJECT:{let t={};for(let n of e.fields)t[n.name.value]=ht(n.value);return t}case P.LIST:return e.values.map(ht);case P.NULL:return null;default:return null}}o(ht,"parseLiteralJSON");var Ms=new z({name:"DateTime",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Vs=new z({name:"Date",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),wt=new z({name:"JSON",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:ht}),Us=new z({name:"CogniteTimeSeriesReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Ks=new z({name:"CogniteFileReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Gs=new z({name:"CogniteSequenceReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Te=new z({name:"ListLimit",description:"Limit for list/search queries (1\u20131000).",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.INT?parseInt(e.value,10):null,"parseLiteral")}),W={DateTime:Ms,Date:Vs,JSON:wt,CogniteTimeSeriesReference:Us,CogniteFileReference:Ks,CogniteSequenceReference:Gs,ListLimit:Te},St={DateTime:"string",Date:"string",JSON:"unknown",CogniteTimeSeriesReference:"string",CogniteFileReference:"string",CogniteSequenceReference:"string",ListLimit:"number"};var qs=new Bs({name:"AggregateFunction",values:{count:{value:"count"},avg:{value:"avg"},sum:{value:"sum"},min:{value:"min"},max:{value:"max"},histogram:{value:"histogram"}}}),or={function:{type:new we(qs)},property:{type:Ct},interval:{type:Re}},Qs=new rr({name:"HistogramBucket",fields:{start:{type:new we(Re)},count:{type:new we(Re)}}}),ir=new rr({name:"AggregateResult",fields:{aggregate:{type:new we(Ct)},property:{type:Ct},value:{type:Re},buckets:{type:new Hs(new we(Qs))},group:{type:wt}}});import{GraphQLObjectType as vt,GraphQLNonNull as re,GraphQLList as Js,GraphQLString as xt,GraphQLBoolean as Ys}from"graphql";var zs=new vt({name:"PageInfo",fields:{endCursor:{type:xt},hasNextPage:{type:new re(Ys)}}}),Fe=new vt({name:"NodeReference",fields:{space:{type:new re(xt)},externalId:{type:new re(xt)}}});function Le(e,t){return new vt({name:`${e}Connection`,fields:{items:{type:new re(new Js(new re(t)))},pageInfo:{type:new re(zs)}}})}o(Le,"makeConnectionType");import{GraphQLInputObjectType as oe,GraphQLList as I,GraphQLNonNull as lr,GraphQLString as X,GraphQLBoolean as A,GraphQLFloat as oa,GraphQLInt as ia}from"graphql";import{GraphQLObjectType as Ws,GraphQLNonNull as sr,GraphQLList as Xs,GraphQLString as Oe,GraphQLBoolean as Zs,GraphQLInt as ea,GraphQLFloat as ta,GraphQLEnumType as na}from"graphql";function ar(e){return e==="String"?Oe:e==="Boolean"?Zs:e==="Int"?ea:e==="Float"?ta:W[e]??Oe}o(ar,"scalarForName");function pr(e){return{typeRegistry:new Map,connectionRegistry:new Map,viewsByExtId:new Map(e.map(t=>[t.externalId,t])),enumRegistry:new Map,enumFilterRegistry:new Map}}o(pr,"createTypeContext");function ra(e){let t=e.replace(/[^_A-Za-z0-9]/g,"_");return/^[0-9]/.test(t)&&(t=`_${t}`),t||"_UNKNOWN"}o(ra,"sanitizeEnumValue");function kt(e,t,n,r){let i=n.enumRegistry.get(e);if(i)return i;let s=new na({name:e,values:Object.fromEntries(t.map(a=>[ra(a),{value:a,description:r?.[a]}]))});return n.enumRegistry.set(e,s),s}o(kt,"getOrCreateEnumType");function cr(e,t){return new Ws({name:e.externalId,description:e.description??e.name,fields:o(()=>{let n={space:{type:new sr(Oe)},externalId:{type:new sr(Oe)}};for(let[r,i,s]of D(e))if(i.kind==="scalar")i.isList?n[r]={type:new Xs(ar(i.graphqlType??"String")),description:s}:n[r]={type:ar(i.graphqlType??"String"),description:s};else if(i.kind==="enum"){let a=`${e.externalId}${r.charAt(0).toUpperCase()}${r.slice(1)}`;n[r]={type:kt(a,i.values,t,i.valueNames),description:s}}else if(i.kind==="directRelation"){let a=t.typeRegistry.get(i.targetView.externalId)??Fe;n[r]={type:a,description:s}}else if(i.kind==="reverseList"||i.kind==="edge"){let a=i.kind==="reverseList"?i.sourceView.externalId:i.targetView.externalId,p=t.typeRegistry.get(a)??Fe,c=t.connectionRegistry.get(a);c||(c=Le(a,p),t.connectionRegistry.set(a,c)),n[r]={type:c,description:s}}else if(i.kind==="reverseDirect"){let a=t.typeRegistry.get(i.sourceView.externalId)??Fe;n[r]={type:a,description:s}}return n},"fields")})}o(cr,"generateViewObjectType");function ie(e,t,n){let r={isNull:{type:A},exists:{type:A},eq:{type:t}};return n.hasIn&&(r.in={type:new I(t)}),n.hasPrefix&&(r.prefix={type:X}),n.hasRange&&(r.gte={type:t},r.gt={type:t},r.lte={type:t},r.lt={type:t}),n.hasListOps&&(r.containsAny={type:new I(t)},r.containsAll={type:new I(t)},r.overlaps={type:new I(t)}),new oe({name:e,fields:r})}o(ie,"makeScalarFilter");var Ne=ie("StringFilter",X,{hasIn:!0,hasPrefix:!0}),sa=ie("BooleanFilter",A,{}),aa=ie("IntFilter",ia,{hasIn:!0,hasRange:!0}),pa=ie("FloatFilter",oa,{hasIn:!0,hasRange:!0}),ca=ie("DateTimeFilter",W.DateTime,{hasIn:!0,hasRange:!0}),la=ie("DateFilter",W.Date,{hasIn:!0,hasRange:!0}),da=new oe({name:"StringListFilter",fields:{isNull:{type:A},exists:{type:A},containsAny:{type:new I(X)},containsAll:{type:new I(X)},overlaps:{type:new I(X)}}}),Se=new oe({name:"DirectRelationRef",fields:{space:{type:new lr(X)},externalId:{type:new lr(X)}}}),ma=new oe({name:"DirectRelationFilter",fields:{isNull:{type:A},exists:{type:A},eq:{type:Se},in:{type:new I(Se)}}});function ua(e){switch(e){case"String":return Ne;case"Boolean":return sa;case"Int":return aa;case"Float":return pa;case"DateTime":return ca;case"Date":return la;default:return Ne}}o(ua,"scalarFilterForName");var dr=["space","externalId"];function mr(e,t,n){let r=t.get(e.externalId),i={};for(let a of dr)i[a]={type:Ne};let s=new Set(dr);for(let[a,p]of D(e)){if(s.has(a))continue;let c=$e(p),d=nr(p);if(!(!c&&!d))if(p.kind==="directRelation"){let l={isNull:{type:A},exists:{type:A},eq:{type:Se},in:{type:new I(Se)}};tr(p)&&(l.in={type:new I(Se)});let m=t.get(p.targetView.externalId);m&&(l.nested={type:m}),i[a]=m?{type:new oe({name:`_${e.externalId}_${a}_Filter`,fields:l})}:{type:ma}}else if(p.kind==="enum"){let l=`${e.externalId}${a.charAt(0).toUpperCase()}${a.slice(1)}`,m=kt(l,p.values,n),g=n.enumFilterRegistry.get(l);g||(g=new oe({name:`${l}Filter`,fields:{isNull:{type:A},exists:{type:A},eq:{type:m},in:{type:new I(m)}}}),n.enumFilterRegistry.set(l,g)),i[a]={type:g}}else if(d)i[a]={type:da};else{let l=p.kind==="scalar"?p.graphqlType??"String":"String",m=ua(l);m&&(i[a]={type:m})}}return{...i,hasData:{type:A},matchAll:{type:A},_and:{type:new I(r)},_or:{type:new I(r)},_not:{type:r}}}o(mr,"generateFilterFields");import{GraphQLEnumType as ur,GraphQLInputObjectType as gr,GraphQLList as ga,GraphQLNonNull as _e,GraphQLString as fa,GraphQLBoolean as ya}from"graphql";var je=new ur({name:"SortDirection",values:{ASC:{value:"ascending"},DESC:{value:"descending"}}});function fr(e){let t=[];for(let[r,i]of D(e))De(i)&&t.push(r);if(t.length===0)return null;let n=new ur({name:`${e.externalId}SortField`,values:Object.fromEntries(t.map(r=>[r,{value:r}]))});return new gr({name:`${e.externalId}Sort`,fields:{field:{type:new _e(n)},direction:{type:new _e(je)},nullsFirst:{type:ya}}})}o(fr,"generateSortInput");var yr=new gr({name:"SearchSort",fields:{property:{type:new _e(new ga(new _e(fa)))},direction:{type:je}}});function wr(e){let t=e.filter(he),n=pr(t);for(let l of t){let m=cr(l,n);n.typeRegistry.set(l.externalId,m)}let r=new Map;for(let l of t){let m=new hr({name:`${l.externalId}Filter`,fields:o(()=>mr(l,r,n),"fields")});r.set(l.externalId,m)}let i={};for(let l of t){let m=l.externalId,g=n.typeRegistry.get(m),f=n.connectionRegistry.get(m);f||(f=Le(m,g),n.connectionRegistry.set(m,f));let y=r.get(m),w=fr(l),u={limit:{type:Te},cursor:{type:Z},filter:{type:y}};w&&(u.sort={type:new se(w)}),i[`query${m}`]={type:new R(f),args:u},i[`get${m}ById`]={type:g,args:{space:{type:new R(Z)},externalId:{type:new R(Z)}}},i[`count${m}`]={type:new R(Sa),args:{filter:{type:y}}},i[`search${m}`]={type:new R(f),args:{query:{type:Z},limit:{type:Te},filter:{type:y},sort:{type:new se(new R(yr))},properties:{type:new se(new R(Z))}}},i[`aggregate${m}`]={type:new R(new se(new R(ir))),args:{filter:{type:y},aggregates:{type:new se(new R(new hr({name:`${m}AggregateRequest`,fields:or})))},groupBy:{type:new se(new R(Z))},query:{type:Z}}}}let s=[];for(let[l,m]of n.typeRegistry)s.push({name:m.name,source:`typeRegistry[${l}]`});for(let[l,m]of n.connectionRegistry)s.push({name:m.name,source:`connectionRegistry[${l}]`});let a=new Map;for(let{name:l,source:m}of s)a.has(l)||a.set(l,[]),a.get(l).push(m);for(let[l,m]of a)m.length>1&&console.error(`[dune] duplicate type "${l}" from: ${m.join(", ")}`);let p=new ha({query:new wa({name:"Query",fields:i}),types:[je,...Object.values(W),...n.enumRegistry.values()]}),c=new Map;for(let l of t){let m=new Map;for(let[g,f]of D(l))m.set(g,f);c.set(l.externalId,{view:{space:l.space,externalId:l.externalId,version:l.version},properties:m})}let d={view(l){let m=c.get(l.externalId);if(!m)throw new Error(`SchemaKnowledge: no view for externalId "${l.externalId}"`);return m},property(l,m){return c.get(l.externalId)?.properties.get(m)}};return{schema:p,sdl:Ca(p),schemaKnowledge:d}}o(wr,"buildSchema");async function Sr(e,t){let r=(await t.dataModels.retrieve([{space:e.space,externalId:e.dataModelExternalId,version:e.dataModelVersion}],{inlineViews:!1})).items[0];if(!r)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} not found`);if(!r.views?.length)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} has no views`);let i=r.views.map(a=>({space:a.space,externalId:a.externalId,version:a.version}));return(await t.views.retrieve(i,{includeInheritedProperties:!0})).items}o(Sr,"fetchViews");import{GraphQLObjectType as xa,GraphQLNonNull as va,GraphQLList as ka,isScalarType as Ea,isEnumType as ba,parse as Pa,print as Aa}from"graphql";function Et(e,t){let n=e.getType(t);if(!(n instanceof xa))return[];let r=n.getFields(),i=[];for(let[s,a]of Object.entries(r)){let p=a.type;for(;p instanceof va||p instanceof ka;)p=p.ofType;(Ea(p)||ba(p))&&i.push(s)}return i}o(Et,"scalarFieldsFor");function Ia(e,t){let n=Et(e,t),r=["space","externalId"];for(let i of["name","description"])n.includes(i)&&r.push(i);return r.join(" ")}o(Ia,"minimalRelationFields");function Cr(e,t,n){let r=[];for(let[i,s]of D(e))if(s.kind==="directRelation"||s.kind==="reverseDirect"){let a=s.kind==="directRelation"?s.targetView.externalId:s.sourceView.externalId;if(n)r.push(`${i} { ${Ia(t,a)} }`);else{let c=["space","externalId",...Et(t,a).filter(d=>d!=="space"&&d!=="externalId")];r.push(`${i} { ${c.join(" ")} }`)}}else!n&&(s.kind==="reverseList"||s.kind==="edge")&&r.push(`${i} { items { space externalId } pageInfo { hasNextPage endCursor } }`);return r}o(Cr,"relationFieldsFor");function xr(e,t,n,r){return`query ${e}(${t}) {
|
|
131
|
+
${e}(${n}) {
|
|
132
|
+
items {
|
|
133
|
+
${r}
|
|
134
|
+
}
|
|
135
|
+
pageInfo { hasNextPage endCursor }
|
|
136
|
+
}
|
|
137
|
+
}`}o(xr,"paginatedOp");function vr(e,t){let n=e.externalId,r=Et(t,n),i=Cr(e,t,!0),s=Cr(e,t,!1),a=[...r,...i].join(`
|
|
138
|
+
`),p=[...r,...s].join(`
|
|
139
|
+
`),c=!!t.getType(`${n}Sort`),d=xr(`query${n}`,c?`$limit: ListLimit, $cursor: String, $filter: ${n}Filter, $sort: [${n}Sort!]`:`$limit: ListLimit, $cursor: String, $filter: ${n}Filter`,c?"limit: $limit, cursor: $cursor, filter: $filter, sort: $sort":"limit: $limit, cursor: $cursor, filter: $filter",a),l=xr(`search${n}`,`$query: String, $limit: ListLimit, $filter: ${n}Filter, $sort: [SearchSort!], $properties: [String!]`,"query: $query, limit: $limit, filter: $filter, sort: $sort, properties: $properties",a),m=`query get${n}ById($space: String!, $externalId: String!) {
|
|
140
|
+
get${n}ById(space: $space, externalId: $externalId) {
|
|
141
|
+
${p}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
`,g=`query count${n}($filter: ${n}Filter) {
|
|
145
|
+
count${n}(filter: $filter)
|
|
146
|
+
}`,f=`query aggregate${n}($filter: ${n}Filter, $aggregates: [${n}AggregateRequest!], $groupBy: [String!], $query: String) {
|
|
147
|
+
aggregate${n}(filter: $filter, aggregates: $aggregates, groupBy: $groupBy, query: $query) {
|
|
148
|
+
aggregate
|
|
149
|
+
property
|
|
150
|
+
value
|
|
151
|
+
buckets { start count }
|
|
152
|
+
group
|
|
153
|
+
}
|
|
154
|
+
}`;return Aa(Pa([d,m,g,l,f].join(`
|
|
155
|
+
|
|
156
|
+
`)))}o(vr,"generateViewOperations");function $a(e){return{availableOnList:e.kind==="scalar",returnsMany:e.kind==="reverseList"||e.kind==="edge",filterable:$e(e),sortable:De(e)}}o($a,"fetchCharacteristics");function kr(e){return{generatedAt:new Date().toISOString(),views:e.map(t=>({space:t.space,externalId:t.externalId,version:t.version,properties:Object.fromEntries(D(t).map(([n,r])=>[n,{kind:r.kind,fetch:$a(r)}]))}))}}o(kr,"buildSdkMetadata");async function br(e,t,n){let r=await Sr(e,t),i=new Set,s=r.filter(u=>i.has(u.externalId)?(console.error(`[dune] dedup: dropped ${u.space}/${u.externalId} (duplicate externalId)`),!1):(i.add(u.externalId),!0));console.error(`[dune] views after dedup: ${s.length} (was ${r.length})`);let{schema:a,sdl:p}=wr(s),c=s.filter(he),d=H(n,e.name);Ra(d,{recursive:!0,force:!0}),Da(d,{recursive:!0}),ae(H(d,"schema.graphql"),p,"utf-8"),ae(H(d,"sdk-metadata.json"),JSON.stringify(kr(c),null,2),"utf-8"),ae(H(d,"views.generated.ts"),`import type { ViewDefinition } from '@cognite/sdk';
|
|
157
|
+
|
|
158
|
+
// Auto-generated \u2014 do not edit.
|
|
159
|
+
export const views: ViewDefinition[] = ${JSON.stringify(c,null,2)};
|
|
160
|
+
`,"utf-8"),await Er({schema:p,generates:{[H(d,"types.generated.ts")]:{plugins:["typescript"],config:{scalars:St}}}},!0);for(let u of c){let h=vr(u,a),C=H(d,`${u.externalId}.generated.ts`);await Er({schema:p,documents:h,generates:{[C]:{plugins:["typescript-operations","typescript-generic-sdk"],config:{scalars:St,namespacedImportName:"Types"}}}},!0);let S=Ta(C,"utf-8");S=S.replace(/^import \{ DocumentNode \} from 'graphql';$/m,"import type { DocumentNode } from 'graphql';").replace(/Requester<C = \{\}>/g,"Requester<C = Record<string, never>>"),S.includes("import type * as Types")||(S=S.replace(/^import type \{ DocumentNode \} from 'graphql';$/m,`import type { DocumentNode } from 'graphql';
|
|
161
|
+
import type * as Types from './types.generated.js';`)),ae(C,S)}let l=c.map(u=>u.externalId).sort((u,h)=>u.localeCompare(h)),m=o(u=>u.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[\s_-]+/).filter(Boolean).map(h=>h.charAt(0).toUpperCase()+h.slice(1).toLowerCase()).join(""),"normalizeTypeName"),g=[...l.map(u=>`import { getSdk as get${u}Sdk } from './${u}.generated.js';`),"import { views } from './views.generated.js';"].sort((u,h)=>{let C=o(S=>S.match(/from '(\.\/[^']+)'/)?.[1]??"","path");return C(u).localeCompare(C(h),void 0,{sensitivity:"base"})}).join(`
|
|
162
|
+
`),f=l.map(u=>` ...get${u}Sdk(requester),`).join(`
|
|
163
|
+
`),y=l.map(u=>{let h=m(u);return`export type {
|
|
164
|
+
${["query","get","count","search","aggregate"].flatMap(x=>{let T=x==="get"?`Get${h}ById`:`${x.charAt(0).toUpperCase()+x.slice(1)}${h}`;return[` ${T}Query`,` ${T}QueryVariables`]}).join(`,
|
|
165
|
+
`)},
|
|
166
|
+
} from './${u}.generated.js';`}).join(`
|
|
167
|
+
`);ae(H(d,"index.ts"),`import { createDuneRuntimeFromViews } from '@cognite/cli';
|
|
168
|
+
import type { CogniteClient } from '@cognite/sdk';
|
|
169
|
+
|
|
170
|
+
${g}
|
|
171
|
+
|
|
172
|
+
export * from './types.generated.js';
|
|
173
|
+
${y}
|
|
174
|
+
|
|
175
|
+
// Internal \u2014 merges all per-view getSdk() functions.
|
|
176
|
+
// Not exported: callers use createSdk() instead.
|
|
177
|
+
function makeSdk(requester: Parameters<typeof get${l[0]}Sdk>[0]) {
|
|
178
|
+
return {
|
|
179
|
+
${f}
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export type Sdk = ReturnType<typeof makeSdk>;
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Creates a fully-typed SDK backed by the Dune runtime.
|
|
187
|
+
* Queries are executed in-process via graphql-js and translated to DMS API calls \u2014
|
|
188
|
+
* no CDF GraphQL endpoint is involved.
|
|
189
|
+
*/
|
|
190
|
+
export function createSdk(client: CogniteClient): Sdk {
|
|
191
|
+
const runtime = createDuneRuntimeFromViews(views, client);
|
|
192
|
+
return makeSdk(runtime.requester);
|
|
193
|
+
}
|
|
194
|
+
`,"utf-8");let w=l.flatMap(u=>[` query${u}: vi.fn(() => Promise.resolve({ query${u}: { items: [], pageInfo: { hasNextPage: false, endCursor: null } } })),`,` get${u}ById: vi.fn(() => Promise.resolve({ get${u}ById: null })),`,` count${u}: vi.fn(() => Promise.resolve({ count${u}: 0 })),`,` search${u}: vi.fn(() => Promise.resolve({ search${u}: { items: [], pageInfo: { hasNextPage: false, endCursor: null } } })),`,` aggregate${u}: vi.fn(() => Promise.resolve({ aggregate${u}: [] })),`]).join(`
|
|
195
|
+
`);return ae(H(d,"test-helpers.ts"),`import { vi } from 'vitest';
|
|
196
|
+
|
|
197
|
+
import type { Sdk } from './index.js';
|
|
198
|
+
|
|
199
|
+
export function makeMockSdk(overrides: Partial<Sdk> = {}): Sdk {
|
|
200
|
+
return {
|
|
201
|
+
${w}
|
|
202
|
+
...overrides,
|
|
203
|
+
} as Sdk;
|
|
204
|
+
}
|
|
205
|
+
`,"utf-8"),{sdkDir:d,viewCount:c.length}}o(br,"generateSdk");var Me=Symbol("BACK");async function Dr(e,t={}){let n=process.cwd();$(n);let r=e.deployments[0],{baseUrl:i,project:s}=r;if(t.interactive){console.log(`Starting browser login...
|
|
206
|
+
`);let c=await ve(t.orgHint??r.org??void 0);if(!c?.access_token)throw new Error("No access token received");return console.log(`
|
|
207
|
+
\u2705 Authentication successful!
|
|
208
|
+
`),{token:c.access_token,baseUrl:i,project:s}}if(process.env.COGNITE_TOKEN)return{token:process.env.COGNITE_TOKEN,baseUrl:i,project:s};let a=O(r);if(a.length>0)throw new Error(`Missing deployment credentials (${a.join(", ")}). Set COGNITE_TOKEN in .env, configure deployClientId/deploySecretName, or run with --interactive for browser login.`);let p=await le(r);return console.log(`\u2705 Authenticated
|
|
209
|
+
`),{token:p,baseUrl:i,project:s}}o(Dr,"resolveAuth");async function At(e){let t=await import("enquirer"),n=t.default?.[e]??t[e];if(typeof n!="function")throw new Error(`Enquirer class "${e}" not found`);return n}o(At,"getEnquirerClass");async function Pt(e,t,n){let r=await At("Select"),i=t.map((c,d)=>({name:n(c,d),value:d})),a=await new r({message:e,choices:i.map(c=>c.name)}).run(),p=i.findIndex(c=>c.name===a);return t[p]}o(Pt,"pick");async function Oa(e,t,n){let r=await At("AutoComplete"),i=t.map((l,m)=>n(l,m)),s=new Map(i.map((l,m)=>[l,m])),p=await new r({message:e,limit:12,choices:i}).run();if(s.has(p))return t[s.get(p)];let c=o(l=>String(l).replace(/\[[0-9;]*m/g,"").trim(),"clean"),d=c(p);for(let[l,m]of s)if(c(l)===d)return t[m];for(let[l,m]of s)if(c(l).includes(d)||d.includes(c(l)))return t[m];throw new Error(`Could not match selection "${p}" to any item`)}o(Oa,"searchPick");async function Na(e,t=""){let n=await At("Input");return new n({message:e,initial:t}).run()}o(Na,"ask");async function _a(e,t,n={}){let r=await fetch(e,{method:n.method??"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:n.body!==void 0?JSON.stringify(n.body):void 0});if(!r.ok){let i=await r.text().catch(()=>"");throw new Error(`CDF API error ${r.status} ${r.statusText}: ${i}`)}return r.json()}o(_a,"cdfFetch");async function ja(e,t,n){return(await _a(`${e}/api/v1/projects/${t}/models/datamodels?includeGlobal=true&limit=1000`,n)).items??[]}o(ja,"fetchDataModels");async function Ma(e,t={}){let n=process.cwd();process.chdir(e);try{$(e);let r=k(e),{token:i,baseUrl:s,project:a}=await Dr(r,t),p=null;async function c(){return p||(p=await ja(s,a,i),p.sort((g,f)=>`${g.space}/${g.externalId}`.localeCompare(`${f.space}/${f.externalId}`))),p}o(c,"getModels");let d={chosenModel:null,sdkName:null},l=[async()=>{console.log(`
|
|
210
|
+
\u{1F510} Fetching data models...`);let g=await c();if(g.length===0)throw new Error("No data models found.");return console.log(`\u{1F50D} Found ${g.length} model(s). Type to search.
|
|
211
|
+
`),d.chosenModel=await Oa("\u{1F4E6} Select a data model:",g,f=>`${f.space} \u2192 ${f.externalId} / ${f.version}${f.name?` \u2014 ${f.name}`:""}`),!0},async()=>{let g=d.chosenModel.externalId.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9-_]/g,"-").toLowerCase(),f=await Na(`
|
|
212
|
+
SDK name (folder under src/generated_sdks/, "back" to go back):`,g);if(f.toLowerCase()==="back")return Me;let u=(JSON.parse(pe(N(e,"app.json"),"utf-8")).generatedSdks??[]).find(h=>h.name===f);if(u){console.log(`
|
|
213
|
+
\u26A0\uFE0F An SDK named "${f}" already exists in app.json:`),console.log(` ${u.dataModelSpace} / ${u.dataModelExternalId} @ ${u.dataModelVersion}`);let h=await Pt("What would you like to do?",["Replace existing entry","Pick a different name","Cancel"],C=>C);if(h==="Cancel"&&(console.log(`
|
|
214
|
+
Cancelled.
|
|
215
|
+
`),process.exit(0)),h==="Pick a different name")return Me}return d.sdkName=f,!0},async()=>{let g={name:d.sdkName,dataModelSpace:d.chosenModel.space,dataModelExternalId:d.chosenModel.externalId,dataModelVersion:String(d.chosenModel.version)};console.log(`
|
|
216
|
+
\u2500\u2500 Summary \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(` Space: ${g.dataModelSpace}`),console.log(` Model: ${g.dataModelExternalId} @ ${g.dataModelVersion}`),console.log(" Views: all"),console.log(` SDK name: ${d.sdkName}`),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let f=await Pt("Write to app.json?",["Yes","Back","Cancel"],y=>y);return f==="Back"?Me:(f==="Cancel"&&(console.log(`
|
|
217
|
+
Cancelled.
|
|
218
|
+
`),process.exit(0)),Va(e,g),!0)}],m=0;for(;m<l.length;)await l[m]()===Me?(m=Math.max(0,m-1),console.log("")):m++;return{sdkName:d.sdkName,auth:{token:i,baseUrl:s,project:a}}}finally{process.chdir(n)}}o(Ma,"runWizard");function Va(e,t){let n=N(e,"app.json"),r=JSON.parse(pe(n,"utf-8"));r.generatedSdks=[...r.generatedSdks??[],t],bt(n,JSON.stringify(r,null,2)+`
|
|
219
|
+
`);let i=N(e,".dune","sdk-configs");try{$r(i)||Fa(i,{recursive:!0}),bt(N(i,`${t.name}.json`),JSON.stringify(t,null,2)+`
|
|
220
|
+
`),console.log(`
|
|
221
|
+
\u2705 Added "${t.name}" to app.json`),console.log(` Config saved to .dune/sdk-configs/${t.name}.json`)}catch{console.log(`
|
|
222
|
+
\u2705 Added "${t.name}" to app.json`)}t.instanceSpaces&&console.log(` Scoped to: ${t.instanceSpaces.join(", ")}`),t.views&&console.log(` Views: ${t.views.map(s=>s.externalId).join(", ")}`),console.log("")}o(Va,"writeEntry");async function Ar(e,t,n,r={}){let i=n??process.cwd();$(i);let s=k(i),p=(JSON.parse(pe(N(i,"app.json"),"utf-8")).generatedSdks??[]).find(w=>w.name===e);p||(console.error(`No SDK named "${e}" in generatedSdks`),process.exit(1));let{token:c}=t??await Dr(s,r),d=s.deployments[0],l=new La({appId:s.externalId,project:d.project,baseUrl:d.baseUrl,oidcTokenProvider:o(async()=>c,"oidcTokenProvider")});await l.authenticate();let m=N(i,"src/generated_sdks");console.log(`
|
|
223
|
+
\u2699\uFE0F Generating "${p.name}" (${p.dataModelSpace}/${p.dataModelExternalId}@${p.dataModelVersion})...`);let{sdkDir:g,viewCount:f}=await br({name:p.name,space:p.dataModelSpace,dataModelExternalId:p.dataModelExternalId,dataModelVersion:p.dataModelVersion},l,m);console.log(`\u2705 Generated SDK for ${f} view(s) \u2192 ${g}`);let y=N(i,"package.json");if($r(y)){let w=JSON.parse(pe(y,"utf-8")),u=w.dependencies??{},h=[];u.graphql||(u.graphql="^16.0.0",h.push("graphql")),u["graphql-tag"]||(u["graphql-tag"]="^2.12.0",h.push("graphql-tag"));let C=N(Pr(import.meta.url),"../../package.json"),S=JSON.parse(pe(C,"utf-8")).version,x=r.linkLocal?`file:${N(Pr(import.meta.url),"../../..")}`:`^${S}`;u["@cognite/cli"]!==x&&(u["@cognite/cli"]=x,h.push("@cognite/cli")),h.length>0&&(w.dependencies=u,bt(y,JSON.stringify(w,null,2)+`
|
|
224
|
+
`,"utf-8"),console.log(`
|
|
225
|
+
\u{1F4E6} Updated package.json: ${h.join(", ")} (run npm install)`))}}o(Ar,"generate");function Ir(e){return{interactive:e.interactive,orgHint:e.org,linkLocal:e.linkLocal}}o(Ir,"sdkCommandOptions");function Tr(e){e.command("sdk").description("Add a data model SDK to app.json and generate TypeScript types").option("--interactive","Authenticate via browser login (same as apps deploy --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").option("--link-local","Point @cognite/cli at the local monorepo package (default: use published version from npm)").action(async n=>{let r=process.cwd(),i=Ir(n),{sdkName:s,auth:a}=await Ma(r,i);await Ar(s,a,r,i)}).command("generate [name]").description("Regenerate TypeScript types for an existing SDK from app.json").option("--interactive","Authenticate via browser login (same as apps deploy --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").option("--link-local","Point @cognite/cli at the local monorepo package (default: use published version from npm)").action(async(n,r)=>{let i=process.cwd(),s=Ir(r),p=JSON.parse(pe(N(i,"app.json"),"utf-8")).generatedSdks??[];p.length===0&&(console.error('No generatedSdks entries found in app.json. Run "cognite sdk" first.'),process.exit(1));let c=n??(p.length===1?p[0].name:await Pt("Which SDK to regenerate?",p,d=>d.name));await Ar(typeof c=="string"?c:c.name,void 0,i,s)})}o(Tr,"registerSdkCommand");var Rr=1e3,Ua=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function Ka(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:Ua.has(t)?[t,n]:[t,"[REDACTED]"]))}o(Ka,"sanitize");function Ga(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}o(Ga,"getCommandPath");function Fr(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(Fr,"tryLoadAppConfig");function It(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(It,"commandFromArgv");function Lr(e,t,n=k){e.hook("postAction",async(r,i)=>{try{let s={command:Ga(i),options:Ka(i.opts()),success:!0,...Fr(n)};t.track("Flows.CLI.Command",s),await t.flush(Rr)}catch{}})}o(Lr,"instrument");async function Or(e,t,n=k){try{let r={command:It(t),options:{},success:!1,...Fr(n)};e.track("Flows.CLI.Command",r),await e.flush(Rr)}catch{}}o(Or,"trackFailure");var Ha="ERR_USE_AFTER_CLOSE";function _r(e){return e instanceof Error&&"code"in e&&e.code===Ha}o(_r,"isReadlineClosedError");function Ba(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(Ba,"isPlainObject");function $t(e){return e==null||_r(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Ba(e)&&Object.keys(e).length===0)}o($t,"isPromptCancel");var Nr=!1;function jr(){Nr||(Nr=!0,process.on("uncaughtException",e=>{_r(e)&&(console.error(`
|
|
226
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{$t(e)&&(console.error(`
|
|
227
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(jr,"installCancelHandler");import Mr from"mixpanel";var qa="5c4d853e7c3b77b1eb4468d5329b278c",Ce="cognite-cli",Qa=2e3,Vr={env:process.env,init:Mr.init.bind(Mr)},Ja={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function Dt(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(Dt,"isTelemetryDisabled");function Ya(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(Ya,"isDebug");function Ur(e={}){let t=e.env??Vr.env,n=e.init??Vr.init,r=e.packageName,i=e.cliVersion,s=Ya(t);if(Dt(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
|
|
228
|
+
`),Ja;let a,p=new Set;function c(){if(a)return a;try{return a=n(qa,{geolocate:!1,keepAlive:!1}),a}catch{return}}return o(c,"getClient"),{track(d,l={}){let m=c();if(!m)return;let g={...l,applicationId:Ce,...r&&{packageName:r},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(g)}
|
|
229
|
+
`);let f=o(()=>{},"finish"),y=new Promise(w=>{f=w});p.add(y);try{m.track(d,g,f)}catch{f()}y.finally(()=>p.delete(y))},async flush(d=Qa){if(p.size===0)return;let l,m=new Promise(g=>{l=setTimeout(g,d),l.unref?.()});try{await Promise.race([Promise.allSettled([...p]),m])}finally{l&&clearTimeout(l)}s&&process.stderr.write(`[telemetry] flush done (${p.size} still pending)
|
|
230
|
+
`)}}}o(Ur,"createTelemetry");var za=1e3,Wa="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",Xa={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function Za(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(Za,"buildRelease");var ep="192.0.2.0";function tp(e){let t={...e.user,email:void 0,username:void 0,ip_address:ep,id:void 0};return{...e,user:t,server_name:void 0}}o(tp,"scrubPii");function Kr(e={}){let t=e.env??process.env;if(Dt(t))return Xa;let n=Za(e),r="production",i=null,s=null;function a(){return{dsn:Wa,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:Ce},contexts:{cli:{applicationId:Ce,node:process.version,platform:process.platform}}},beforeSend:tp}}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,d){try{let l=await p();if(!l)return;let m={level:"fatal"};d?.command&&(m.tags={command:d.command},m.contexts={cli:{applicationId:Ce,node:process.version,platform:process.platform,command:d.command}}),l.captureException(c,m)}catch{}},async flush(c=za){try{if(!i)return;await i.flush(c)}catch{}}}}o(Kr,"createErrorReporter");import{mkdirSync as np,readFileSync as rp,writeFileSync as op}from"fs";import{homedir as ip}from"os";import{resolve as Ve}from"path";import{debuglog as sp}from"util";import{lt as ap,parse as Gr}from"semver";var pp="https://registry.npmjs.org/@cognite/cli/latest",cp=1500,Hr="upgrade-check.json",Br=Ve(process.env.XDG_CACHE_HOME||Ve(ip(),".cache"),"@cognite","cli"),Tt=sp("cognite-flows");function lp(e,t){return!e||!t||!Gr(e)||!Gr(t)?!1:ap(e,t)}o(lp,"isOutdated");async function dp({timeout:e=cp,registryUrl:t=pp,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 Tt("fetchLatestVersion failed (%s): %O",t,r),null}}o(dp,"fetchLatestVersion");function mp(e=Br,t=864e5){try{let n=rp(Ve(e,Hr),"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 Tt("readUpgradeCheckCache failed (%s): %O",e,n),null}}o(mp,"readUpgradeCheckCache");function up(e,t){try{np(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};op(Ve(e,Hr),JSON.stringify(n))}catch(n){Tt("writeUpgradeCheckCache failed (%s): %O",e,n)}}o(up,"writeUpgradeCheckCache");async function gp({cacheDir:e=Br,...t}={}){let n=await dp(t);n&&up(e,n)}o(gp,"startBackgroundUpgradeCheck");function qr(e,{onOutdated:t,cacheDir:n,...r}={}){let i=mp(n);if(i){lp(e,i.latest)&&t?.(e,i.latest);return}gp({cacheDir:n,...r})}o(qr,"preActionUpgradeCheck");import{default as $g,chalkStderr as Qr}from"chalk";function Jr(e,t){let n=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],r=Math.max(...n.map(p=>[...p].length))+2,i="\u2500".repeat(r),s=o(p=>`\u2502 ${p}${" ".repeat(r-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...n.map(s),`\u2514${i}\u2518`].join(`
|
|
231
|
+
`);return Qr.bold.yellow(a)}o(Jr,"formatUpgradeWarning");function hp(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(hp,"isDep0040Warning");var Ft=process,wp=Ft.emit.bind(Ft);Ft.emit=function(e,...t){return e==="warning"&&hp(t[0])?!1:wp(e,...t)};jr();var ee=new yp;ee.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.1.0-alpha.49").showHelpAfterError().configureOutput({writeOut:o(e=>fp(1,e),"writeOut")});ee.hook("preAction",()=>{qr("1.1.0-alpha.49",{onOutdated:o((e,t)=>{console.warn(`
|
|
232
|
+
${Jr(e,t)}
|
|
233
|
+
`)},"onOutdated")})});En(ee);Xn(ee);Tr(ee);var zr=Ur({packageName:"@cognite/cli",cliVersion:"1.1.0-alpha.49"}),Yr=Kr({packageName:"@cognite/cli",cliVersion:"1.1.0-alpha.49"});Lr(ee,zr);var Rt=process.argv.slice(2);ee.parseAsync(Rt,{from:"user"}).catch(async e=>{await Or(zr,Rt),$t(e)&&(console.error(`
|
|
234
|
+
Cancelled.`),process.exit(130)),await Yr.captureError(e,{command:It(Rt)}),await Yr.flush(),console.error(e instanceof Error?`\u274C ${e.message}`:e),process.exit(1)});
|
package/dist/deploy/index.d.ts
CHANGED
|
@@ -60,9 +60,6 @@ declare class AppHostingClient {
|
|
|
60
60
|
publishVersion(appExternalId: string, version: string): Promise<void>;
|
|
61
61
|
/** Publish the version and immediately set it as the ACTIVE alias. */
|
|
62
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>;
|
|
66
63
|
/**
|
|
67
64
|
* Set the ACTIVE alias on a version. Returns the version that was
|
|
68
65
|
* previously active (if any) so callers can surface "Superseded X"
|
package/dist/deploy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e}from"../chunk-
|
|
1
|
+
import{a,b,c,d,e}from"../chunk-HE6P4LDC.js";import"../chunk-EI7MMDWY.js";export{a as AppHostingClient,b as ApplicationPackager,e as deploy,d as getSdk,c as getToken};
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o,b as r,c as e,d as f,e as m}from"./chunk-
|
|
1
|
+
import{a as o,b as r,c as e,d as f,e as m}from"./chunk-HE6P4LDC.js";import{a as p,b as t}from"./chunk-EILVJ2ZW.js";import"./chunk-EI7MMDWY.js";export{o as AppHostingClient,r as ApplicationPackager,p as createDuneRuntime,t as createDuneRuntimeFromViews,m as deploy,f as getSdk,e as getToken};
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { ViewReference, FilterDefinition, SearchSort, AggregationDefinition, AggregatedResultItem, InstancesAPI, CogniteClient, ViewDefinition } from '@cognite/sdk';
|
|
2
|
+
import { DocumentNode, GraphQLSchema } from 'graphql';
|
|
3
|
+
|
|
4
|
+
interface GenerateSdkConfig {
|
|
5
|
+
name: string;
|
|
6
|
+
space: string;
|
|
7
|
+
dataModelExternalId: string;
|
|
8
|
+
dataModelVersion: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface SharedViewId {
|
|
12
|
+
space: string;
|
|
13
|
+
externalId: string;
|
|
14
|
+
version: string;
|
|
15
|
+
}
|
|
16
|
+
type PropertyDescriptor = {
|
|
17
|
+
kind: 'scalar';
|
|
18
|
+
isList?: boolean;
|
|
19
|
+
graphqlType?: string;
|
|
20
|
+
} | {
|
|
21
|
+
kind: 'enum';
|
|
22
|
+
values: string[];
|
|
23
|
+
valueNames: Record<string, string>;
|
|
24
|
+
} | {
|
|
25
|
+
kind: 'directRelation';
|
|
26
|
+
targetView: SharedViewId;
|
|
27
|
+
} | {
|
|
28
|
+
kind: 'reverseDirect';
|
|
29
|
+
sourceView: SharedViewId;
|
|
30
|
+
throughProperty: string;
|
|
31
|
+
} | {
|
|
32
|
+
kind: 'reverseList';
|
|
33
|
+
sourceView: SharedViewId;
|
|
34
|
+
throughProperty: string;
|
|
35
|
+
} | {
|
|
36
|
+
kind: 'edge';
|
|
37
|
+
targetView: SharedViewId;
|
|
38
|
+
direction: 'outwards' | 'inwards';
|
|
39
|
+
};
|
|
40
|
+
interface SchemaView {
|
|
41
|
+
view: SharedViewId;
|
|
42
|
+
properties: Map<string, PropertyDescriptor>;
|
|
43
|
+
}
|
|
44
|
+
interface SchemaKnowledge {
|
|
45
|
+
view(ref: SharedViewId): SchemaView;
|
|
46
|
+
property(ref: SharedViewId, prop: string): PropertyDescriptor | undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Matches the Requester type emitted by @graphql-codegen/typescript-generic-sdk,
|
|
51
|
+
* so the return of createDuneRequester can be passed directly to getSdk().
|
|
52
|
+
*/
|
|
53
|
+
type DuneRequester = <TData, TVariables>(doc: DocumentNode, variables?: TVariables) => Promise<TData>;
|
|
54
|
+
|
|
55
|
+
interface PropertyRef {
|
|
56
|
+
view: ViewReference;
|
|
57
|
+
property: string;
|
|
58
|
+
}
|
|
59
|
+
interface ConnectionSelection {
|
|
60
|
+
limit?: number;
|
|
61
|
+
select: SelectionTree;
|
|
62
|
+
}
|
|
63
|
+
interface SelectionTree {
|
|
64
|
+
scalars: string[];
|
|
65
|
+
connections: Map<string, ConnectionSelection>;
|
|
66
|
+
}
|
|
67
|
+
interface SortClause {
|
|
68
|
+
property: PropertyRef;
|
|
69
|
+
direction: 'ascending' | 'descending';
|
|
70
|
+
/** When true, nulls sort before non-nulls. Defaults to false. */
|
|
71
|
+
nullsFirst?: boolean;
|
|
72
|
+
}
|
|
73
|
+
/** Pre-translated DMS logical filter (output of translateFilter in resolver layer). */
|
|
74
|
+
type LogicalFilter = FilterDefinition;
|
|
75
|
+
interface QueryInput {
|
|
76
|
+
view: ViewReference;
|
|
77
|
+
filter?: LogicalFilter;
|
|
78
|
+
sort?: SortClause[];
|
|
79
|
+
select: SelectionTree;
|
|
80
|
+
/** Page size. Defaults to INITIAL_BATCH_LIMIT if omitted. */
|
|
81
|
+
limit?: number;
|
|
82
|
+
/** Opaque cursor from a previous ListResult.pageInfo.endCursor. */
|
|
83
|
+
cursor?: string;
|
|
84
|
+
}
|
|
85
|
+
interface ListResult<T = Record<string, unknown>> {
|
|
86
|
+
items: T[];
|
|
87
|
+
pageInfo: {
|
|
88
|
+
endCursor: string | null;
|
|
89
|
+
hasNextPage: boolean;
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface SearchInput {
|
|
94
|
+
view: ViewReference;
|
|
95
|
+
/** Full-text search term. */
|
|
96
|
+
query?: string;
|
|
97
|
+
filter?: LogicalFilter;
|
|
98
|
+
sort?: SearchSort[];
|
|
99
|
+
select: SelectionTree;
|
|
100
|
+
/** Max items to return. Defaults to searchLimit config. */
|
|
101
|
+
limit?: number;
|
|
102
|
+
/** Restrict search to specific property names within the view. */
|
|
103
|
+
properties?: string[];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
interface AggregateInput {
|
|
107
|
+
view: ViewReference;
|
|
108
|
+
filter?: LogicalFilter;
|
|
109
|
+
aggregates: AggregationDefinition[];
|
|
110
|
+
groupBy?: string[];
|
|
111
|
+
/** Optional full-text query to scope which instances are aggregated. */
|
|
112
|
+
query?: string;
|
|
113
|
+
}
|
|
114
|
+
interface AggregateOutput {
|
|
115
|
+
items: AggregatedResultItem[];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
type DmsClient = Pick<InstancesAPI, 'query' | 'search' | 'aggregate' | 'retrieve' | 'upsert' | 'delete' | 'sync' | 'inspect'>;
|
|
119
|
+
interface PlannerConfig {
|
|
120
|
+
initialBatchLimit: number;
|
|
121
|
+
maxBatchLimit: number;
|
|
122
|
+
searchLimit: number;
|
|
123
|
+
inFilterChunkSize: number;
|
|
124
|
+
previewLimit: number;
|
|
125
|
+
nestedDetailLimit: number;
|
|
126
|
+
enableRemoveNotConnected: boolean;
|
|
127
|
+
max408Retries: number;
|
|
128
|
+
max429Retries: number;
|
|
129
|
+
retryBaseDelayMs: number;
|
|
130
|
+
maxConcurrentRequests: number;
|
|
131
|
+
/** Maximum SelectionTree nesting depth. Throws PlannerValidationError if exceeded. */
|
|
132
|
+
maxNestingDepth: number;
|
|
133
|
+
/** Hard ceiling for listAll without an explicit maxTotal. Throws rather than silently truncating. */
|
|
134
|
+
maxTotalItems: number;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
declare class QueryRunner {
|
|
138
|
+
private readonly dms;
|
|
139
|
+
private readonly schema;
|
|
140
|
+
private readonly config;
|
|
141
|
+
private readonly executor;
|
|
142
|
+
get schemaKnowledge(): SchemaKnowledge | undefined;
|
|
143
|
+
constructor(dms: DmsClient, schema?: SchemaKnowledge, config?: Partial<PlannerConfig>);
|
|
144
|
+
query<T = Record<string, unknown>>(input: QueryInput): Promise<ListResult<T>>;
|
|
145
|
+
/**
|
|
146
|
+
* Collects all pages until exhaustion. `input.limit` is the page size.
|
|
147
|
+
* `maxTotal` sets an explicit ceiling — without it, throws at `config.maxTotalItems`
|
|
148
|
+
* to prevent unbounded fetches.
|
|
149
|
+
*/
|
|
150
|
+
queryAll<T = Record<string, unknown>>(input: Omit<QueryInput, 'cursor'>, maxTotal?: number): Promise<T[]>;
|
|
151
|
+
/**
|
|
152
|
+
* Full-text or filter-based search returning a single (non-paginated) result set.
|
|
153
|
+
* Use for top-level discovery; DMS search has eventual consistency — do not use
|
|
154
|
+
* for writes-then-reads or where strong consistency is required.
|
|
155
|
+
*/
|
|
156
|
+
search<T = Record<string, unknown>>(input: SearchInput): Promise<ListResult<T>>;
|
|
157
|
+
/**
|
|
158
|
+
* Fetches specific nodes by space+externalId. Returns an empty array when ids is empty.
|
|
159
|
+
* Extracts view-scoped properties before returning, matching the shape of list results.
|
|
160
|
+
*/
|
|
161
|
+
getByIds<T = Record<string, unknown>>(ids: Array<{
|
|
162
|
+
space: string;
|
|
163
|
+
externalId: string;
|
|
164
|
+
}>, view: ViewReference): Promise<T[]>;
|
|
165
|
+
/**
|
|
166
|
+
* Returns the total count of instances matching the filter.
|
|
167
|
+
* Wraps the filter with hasData so only instances with data in the view are counted.
|
|
168
|
+
*/
|
|
169
|
+
count(input: {
|
|
170
|
+
view: ViewReference;
|
|
171
|
+
filter?: LogicalFilter;
|
|
172
|
+
}): Promise<number>;
|
|
173
|
+
aggregate(input: AggregateInput): Promise<AggregateOutput>;
|
|
174
|
+
/**
|
|
175
|
+
* Async generator — yields one ListResult<T> per page.
|
|
176
|
+
* Lets callers stream results or stop early without fetching remaining pages.
|
|
177
|
+
*/
|
|
178
|
+
queryPages<T = Record<string, unknown>>(input: Omit<QueryInput, 'cursor'>): AsyncGenerator<ListResult<T>>;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
interface DuneRuntime {
|
|
182
|
+
schema: GraphQLSchema;
|
|
183
|
+
rootValue: Record<string, unknown>;
|
|
184
|
+
runner: QueryRunner;
|
|
185
|
+
/** Pass directly to the generated getSdk() function. */
|
|
186
|
+
requester: DuneRequester;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Builds the full runtime from a data model config. Fetches views from CDF,
|
|
190
|
+
* builds the GraphQL schema, wires resolvers, and returns a ready requester.
|
|
191
|
+
*/
|
|
192
|
+
declare function createDuneRuntime(config: GenerateSdkConfig, client: CogniteClient): Promise<DuneRuntime>;
|
|
193
|
+
/**
|
|
194
|
+
* Builds the runtime directly from an array of ViewDefinition objects — skips the
|
|
195
|
+
* data model lookup. Useful when you already have views from sdk.views.list().
|
|
196
|
+
*/
|
|
197
|
+
declare function createDuneRuntimeFromViews(views: ViewDefinition[], client: CogniteClient): DuneRuntime;
|
|
198
|
+
|
|
199
|
+
export { type DuneRuntime, createDuneRuntime, createDuneRuntimeFromViews };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b}from"../chunk-EILVJ2ZW.js";import"../chunk-EI7MMDWY.js";export{a as createDuneRuntime,b as createDuneRuntimeFromViews};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cognite/cli",
|
|
3
|
-
"version": "1.1.0-alpha.
|
|
3
|
+
"version": "1.1.0-alpha.49",
|
|
4
4
|
"description": "CLI for Cognite Data Fusion",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Cognite",
|
|
@@ -22,6 +22,11 @@
|
|
|
22
22
|
"types": "./dist/deploy/index.d.ts",
|
|
23
23
|
"import": "./dist/deploy/index.js",
|
|
24
24
|
"default": "./dist/deploy/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./sdk-runtime": {
|
|
27
|
+
"types": "./dist/sdk-runtime/index.d.ts",
|
|
28
|
+
"import": "./dist/sdk-runtime/index.js",
|
|
29
|
+
"default": "./dist/sdk-runtime/index.js"
|
|
25
30
|
}
|
|
26
31
|
},
|
|
27
32
|
"bin": {
|
|
@@ -46,6 +51,10 @@
|
|
|
46
51
|
"dependencies": {
|
|
47
52
|
"@cognite/app-sdk": "^0.4.0",
|
|
48
53
|
"@cognite/sdk": "^10.10.0",
|
|
54
|
+
"@graphql-codegen/cli": "^7.0.0",
|
|
55
|
+
"@graphql-codegen/typescript": "^6.0.1",
|
|
56
|
+
"@graphql-codegen/typescript-generic-sdk": "^5.0.1",
|
|
57
|
+
"@graphql-codegen/typescript-operations": "^6.0.2",
|
|
49
58
|
"@sentry/node": "^10.51.0",
|
|
50
59
|
"@zip.js/zip.js": "^2.7.0",
|
|
51
60
|
"chalk": "^5.6.2",
|
|
@@ -53,6 +62,7 @@
|
|
|
53
62
|
"dotenv": "^17.4.2",
|
|
54
63
|
"enquirer": "^2.4.1",
|
|
55
64
|
"execa": "^5.1.1",
|
|
65
|
+
"graphql": "^16.13.2",
|
|
56
66
|
"hygen": "^6.2.11",
|
|
57
67
|
"jose": "^6.2.2",
|
|
58
68
|
"mixpanel": "^0.21.0",
|
|
@@ -75,14 +85,14 @@
|
|
|
75
85
|
}
|
|
76
86
|
},
|
|
77
87
|
"devDependencies": {
|
|
78
|
-
"@types/ejs": "^3.1.5",
|
|
79
|
-
"ejs": "^3.1.10",
|
|
80
88
|
"@mswjs/http-middleware": "^0.10.3",
|
|
89
|
+
"@types/ejs": "^3.1.5",
|
|
81
90
|
"@types/express": "^5.0.6",
|
|
82
91
|
"@types/node": "^24.10.1",
|
|
83
92
|
"@types/react": "^19.2.6",
|
|
84
93
|
"@types/react-dom": "^19.2.3",
|
|
85
94
|
"@types/semver": "^7.7.0",
|
|
95
|
+
"ejs": "^3.1.10",
|
|
86
96
|
"express": "^5.2.1",
|
|
87
97
|
"msw": "^2.13.6",
|
|
88
98
|
"react": "^19.2.6",
|
package/dist/chunk-QOJVLP7E.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
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};
|