@cognite/cli 1.1.0-alpha.48 → 1.1.0-alpha.50
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 +160 -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.50",
|
|
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 pe(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(pe,"isHttpError");function no(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(no,"httpStatusHint");function ee(e){let t=e instanceof Error?e:new Error(String(e));if(!pe(t))return null;let n=no(t.status);return n?Object.assign(new Error(`${t.message}
|
|
5
|
+
${n}`),{cause:t}):null}o(ee,"enrichedHttpError");function ro(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(ro,"findMissingArray");function oo(e,t){if(!pe(e)||e.status!==400)return!1;let n=ro(e);return n?n.some(r=>j(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}o(oo,"isMissingExternalIdError");function Ke(e,t){return pe(e)&&e.status===404||oo(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 io(e){return Mt(_t,e)}o(io,"isAppVersionLifecycleState");function so(e){return Mt(jt,e)}o(so,"isAppVersionAlias");function ao(e){return typeof e.version=="string"&&io(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||so(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(ao,"isAppVersion");function Nt(e){if(!j(e))throw new Error("Invalid version response: not an object");if(!ao(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 ee(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 C=JSON.parse(y);if(j(C)){let k=C.error;if(typeof k=="string")w=k;else if(j(k)){let T=k.message,x=k.code;w=typeof T=="string"?T:x!=null?`Unknown error (code: ${x})`:y}else{let T=C.message;w=typeof T=="string"?T:y}}}catch{}let u=f.headers.get("x-request-id"),h=u?` | X-Request-ID: ${u}`:"",S=Object.assign(new Error(`Upload failed: ${f.status} \u2014 ${w}${h}`),{status:f.status});throw ee(S)??S}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):ee(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 ee(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 ee(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(pe(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 So,readFileSync as Co}from"fs";import{resolve as xo}from"path";import{array as po,boolean as co,check as Vt,forward as Ut,literal as lo,maxLength as mo,minLength as uo,nonEmpty as te,object as Kt,optional as B,picklist as go,pipe as M,safeParse as fo,string as L,url as yo}from"valibot";var qe=M(L(),te("must not be empty")),Qe=M(L(),te("must not be empty"),mo(256,"must be 256 characters or fewer")),Je=M(L(),te("must not be empty"),yo("must be a valid URL")),Ye=M(L(),te("must not be empty")),ze=M(L(),te("must not be empty")),ho=M(Kt({org:Ye,project:ze,baseUrl:Je,deployClientId:B(L(),""),deploySecretName:B(L(),""),published:B(co(),!1),idpType:B(go(["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"])),wo=Kt({name:qe,externalId:Qe,versionTag:M(L(),te("must not be empty")),description:B(L(),""),deployments:M(po(ho),uo(1,"must contain at least one deployment")),infra:B(lo("appsApi"))});function We(e){let t=fo(wo,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 v(e,t={}){let{validator:n=We,existsSync:r=So,readFileSync:i=Co}=t,s=xo(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(v,"loadAppConfig");import{CogniteClient as Bo}from"@cognite/sdk";import{CogniteClient as Io}from"@cognite/sdk";var vo=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"),ko=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=vo()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),Eo=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"),bo=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"),Po=o(async(e,t,n,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let i=Eo(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"),ce=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=ko(r);if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Po(n,p,s,a)}return bo(n,p)},"getToken");async function le(e,t,n=process.env,r){let i=await ce(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(le,"getSdk");import Lo from"os";import Oo from"path";import No from"open";import{buildAuthorizationUrl as _o,calculatePKCECodeChallenge as jo,discovery as Mo,None as Vo,randomPKCECodeVerifier as Uo,randomState as Ko}from"openid-client";import Ao from"https";import{authorizationCodeGrant as $o}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 Do(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(Do,"handleCallback");function To(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}o(To,"formatTimeoutMinutes");function Ht(e,t,n,r,i,s={createServer:Ao.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:$o}){return new Promise((a,p)=>{let c,d=s.setTimeout(()=>{c?.close(),p(new Error(`Login timeout - no response received within ${To(e.loginTimeout)}`))},e.loginTimeout);c=s.createServer(t,async(l,m)=>{try{let g=await Do(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 Ro}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 Fo(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(Fo,"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:Ro}){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):Fo(e,n,r,t)}o(Qt,"getOrCreateCertificates");var Go={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:Oo.join(Lo.homedir(),".cdf-login")},Ho={open:No,getOrCreateCertificates:Qt,startCallbackServer:Ht,discovery:Mo,buildAuthorizationUrl:_o,randomPKCECodeVerifier:Uo,calculatePKCECodeChallenge:jo,randomState:Ko,logger:console};async function ve(e,t=Go,n){return n===void 0?Jt(e,t,Ho):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,Vo()),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=le,createClient:s=o(a=>new Bo(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 N(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(N,"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 N(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 Qo}from"path";import{config as Jo}from"dotenv";function $(e,t={existsSync:qo,config:Jo}){let n=Qo(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 Yo(e){let t=process.cwd();$(t);let n=v(t);K(n);let r=e.interactive?await U(n,e):N(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(Yo,"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)=>Yo(n))}o(Xt,"registerActivateCommand");import{readdirSync as pi}from"fs";import{basename as un,dirname as ci,normalize as li,resolve as me}from"path";import{fileURLToPath as di,pathToFileURL as mi}from"url";import{Logger as ui,runner as gi}from"hygen";import{safeParse as zo}from"valibot";function de(e,t){return n=>{let r=zo(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}o(de,"toPromptValidator");var Zt={name:de("App name",Qe),displayName:de("Display name",qe),baseUrl:de("Base URL",Je),org:de("Org",Ye),project:de("Project",ze)};function Wo(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}o(Wo,"composeValidators");function ke(e){return e.map(t=>{if(!(t.name in Zt))return t;let n=Zt[t.name];return{...t,validate:Wo(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 Xo={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 Zo(e){return!!(await e([Xo])).useSpecKit}o(Zo,"promptForSpecKit");async function ei(e,t,n){return e!==void 0?e:t?Zo(n):!1}o(ei,"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(x=>x[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(x=>x.name==="name"?{...x,initial:l}:x):p,f=ke(g),y=m?{...c,name:l}:c,w=new Set(Object.keys(y)),u=f.filter(x=>!w.has(x.name)),h=u.findIndex(x=>x.name==="baseUrl"),S;if(h!==-1){let x=u.filter(to=>to.name!=="baseUrl"),Ue=x.length>0?await a(x):{},zr=typeof Ue.cluster=="string"?Ue.cluster:"",Wr=typeof y.cluster=="string"?y.cluster:"",Xr=`https://${(zr||Wr).trim().replace(/\/+$/,"")||"api"}.cognitedata.com`,Zr=u[h],eo=await a([{...Zr,initial:Xr}]);S={...Ue,...eo}}else S=u.length>0?await a(u):{};let C={...y,...S},k=typeof C.name=="string"?C.name:"";k&&n(k);let T=await ei(s,u.length>0,a);return r?.(T),{...C,name:k,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 ni,mkdirSync as ln,writeFileSync as ri}from"fs";import{dirname as dn,resolve as q}from"path";import{fileURLToPath as oi}from"url";import{symlinkSync as ti}from"fs";function be({target:e,linkPath:t,label:n,symlink:r=ti}){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 ii=q(dn(oi(import.meta.url)),"..","..","_vendor","spec-kit"),si={branch_numbering:"sequential"},ai=[{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=ii}){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 ai){let p=q(e,a);i=`copy ${s} to ${a}`,ln(dn(p),{recursive:!0}),ni(q(t,s),p,{recursive:!0})}i=`write init-options.json under specifyDir=${n}`,ri(q(n,"init-options.json"),`${JSON.stringify(si,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=me(ci(di(import.meta.url)),"..","..","_templates");async function fi(){let e=me(gn,"app","new","prompt.js");return(await import(mi(e).href)).default}o(fi,"loadPromptDefs");function yi(e,t){return!e||t?null:li(e)}o(yi,"resolveDirName");function hi(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:me(process.cwd(),r),display:r}}o(hi,"resolveAppLocation");function wi(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(wi,"printSuccessMessage");async function Si(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=me(e,".agents","skills"),i=0;try{i=pi(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(Si,"pullSkillsInto");function Ci(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(Ci,"maybeInitGit");async function xi(e,t){let n=e==="."||e==="./",r=yi(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 fi(),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 gi(["app","new"],{templates:gn,cwd:process.cwd(),logger:new ui(console.log.bind(console)),createPrompter:l,debug:!!process.env.DEBUG});let m=hi(n,r,i);be({target:"AGENTS.md",linkPath:me(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&mn({appDir:m.cwd}),await Si(m.cwd),Ci(m.cwd),wi(n,m.display,s)}o(xi,"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(xi)}o(fn,"registerCreateCommand");import{readFile as Ai,unlink as $i}from"fs/promises";import{basename as Di}from"path";import hn from"fs";import Pi from"path";import G from"fs";import b from"path";import{parseAndValidateManifestConfig as vi}from"@cognite/app-sdk/vite";import{BlobReader as ki,Uint8ArrayWriter as Ei,ZipWriter as bi}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 bi(new Ei,{level:9}),i=o(async(c,d)=>{await r.add(d,new ki(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");vi(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 le(e,n),d=new E(c),l=hn.readFileSync(r),m=Pi.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 Ti(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(Ti,"handleDeployNonInteractive");async function Ri(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 Ai(s);await new E(i).deploy(e.externalId,e.name,e.description,e.versionTag,a,Di(s),!1),Cn(e,t)}finally{await $i(s).catch(()=>{})}}o(Ri,"handleDeployInteractive");async function Fi(e,t=process.cwd(),n={}){let{loadEnvFile:r=$,loadAppConfig:i=v,deploy:s=ot}=n;r(t);let a=i(t);if(K(a),e.interactive){let c=await U(a,e);await Ri(a,c,t,e);return}let p=N(a.deployments,e.deployment);await Ti(a,p,t,e,s)}o(Fi,"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,145 @@ 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=>Fi(t))}o(xn,"registerDeployCommand");async function Li(e){let t=process.cwd();$(t);let n=v(t);K(n);let r=e.interactive?await U(n,e):N(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(Li,"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)=>Li(n))}o(vn,"registerPublishCommand");function Oi(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(Oi,"describeStatus");async function Ni(e){let t=process.cwd();$(t);let n=v(t);K(n);let r=e.interactive?await U(n,e):N(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=Oi(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(Ni,"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)=>ho(n))}o(Rt,"registerStatusCommand");function _t(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return Pt(t),Ft(t),Rt(t),Ot(t),pt(t),At(t),Ge(t),t}o(_t,"registerAppsCommand");import{existsSync as li,mkdirSync as mi,writeFileSync as di}from"fs";import{dirname as Ue,join as Le}from"path";import{execFile as wo}from"child_process";import{promisify as Eo}from"util";import{platform as Co}from"os";function j(e={}){let{platform:t=Co}=e;return t()==="darwin"}o(j,"isMacOS");var Ut="cognite-flows",So=Eo(wo),Lt=o((e,t)=>So(e,t),"defaultExecFile"),vo=-25300,xo=vo&255;function bo(e){if(!(e instanceof Error)||!("code"in e)||e.code!==xo)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(bo,"isKeychainNotFoundError");async function Nt(e,t,n={}){if(!j(n))throw new Error("Keychain storage is only supported on macOS");let{execFile:r=Lt}=n;await r("security",["add-generic-password","-a",e,"-s",Ut,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(Nt,"storeKeyInKeychain");async function jt(e,t={}){if(!j(t))return null;let{execFile:n=Lt}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",Ut,"-w"]);return Buffer.from(r.trim(),"base64").toString("utf-8")}catch(r){if(bo(r))return null;throw r}}o(jt,"readKeyFromKeychain");import{pbkdf2 as ko,randomBytes as Do}from"crypto";import{promisify as Io}from"util";import{CompactEncrypt as To,base64url as $o,compactDecrypt as Ep}from"jose";var Po=new TextEncoder,Ao=new TextDecoder,Kt={encode:o(e=>Po.encode(e),"encode"),decode:o(e=>Ao.decode(e),"decode")};var Fo=Io(ko),De=6e5,Oo="sha512",Ro="PBKDF2-HMAC-SHA512",_o=16,Uo="A256GCM",Lo=32,Mt=2e6;async function No(e,t,n){return await Fo(e,t,n,Lo,Oo)}o(No,"deriveKey");async function Vt(e,t,n=De){if(!Number.isInteger(n)||n<1||n>Mt)throw new Error(`Invalid iterations: must be an integer between 1 and ${Mt}`);let r=Do(_o),i=await No(t,r,n);return await new To(Kt.encode(e)).setProtectedHeader({alg:"dir",enc:Uo,kdf:Ro,kdf_iter:n,kdf_salt:$o.encode(r)}).encrypt(i)}o(Vt,"encryptStringAsJwe");import{calculateJwkThumbprint as jo,exportJWK as Ko,exportPKCS8 as Mo,exportSPKI as Vo,generateKeyPair as Ho}from"jose";async function Ht(){let{publicKey:e,privateKey:t}=await Ho("EdDSA",{extractable:!0}),n=await Mo(t),r=await Vo(e),i=await Ko(e),s=await jo(i);return{privateKeyPem:n,publicKeyPem:r,kid:s}}o(Ht,"generateSigningKeyPair");import{existsSync as Bo,readdirSync as Yo,readFileSync as Jo}from"fs";import{join as oe}from"path";import{homedir as Go}from"os";import{join as Gt}from"path";function K(e={}){let{env:t=process.env,homedir:n=Go}=e,r=t.DUNE_HOME?.trim()||Gt(n(),".dune");return{home:r,keysDir:Gt(r,"keys")}}o(K,"getConfig");var ie=".pub.pem",Ie=".key.jwe",Xo=".pem",Te=".meta.json";function Bt(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"legacy-unencrypted-file":return`${e.path} (unencrypted \u2014 rotate)`;case"public-only":return"public-only (private key missing)"}}o(Bt,"formatLocalKeySource");function zo(e){return{existsSync:e.existsSync??Bo,readdirSync:e.readdirSync??Yo,readFileSync:e.readFileSync??((t,n)=>Jo(t,n)),isMacOS:e.isMacOS??(()=>j()),readKeyFromKeychain:e.readKeyFromKeychain??(t=>jt(t))}}o(zo,"resolveDeps");function Wo(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}o(Wo,"readEmailFromMeta");function qo(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(ie)):[]}o(qo,"publicKeyEntries");function Qo(e){return e.slice(0,-ie.length)}o(Qo,"kidFromPublicKeyFilename");async function Zo(e,t,n){if(n.isMacOS()&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let r=oe(t,`${e}${Ie}`);if(n.existsSync(r))return{kind:"encrypted-file",path:r};let i=oe(t,`${e}${Xo}`);return n.existsSync(i)?{kind:"legacy-unencrypted-file",path:i}:{kind:"public-only"}}o(Zo,"resolveSource");async function Yt(e=K().keysDir,t={}){let n=zo(t),r=new Set,i=qo(e,n).flatMap(s=>{let a=Qo(s);return!a||r.has(a)?[]:(r.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let c=await Zo(s,e,n),p=oe(e,`${s}${Te}`),l;try{l=Wo(n.readFileSync(p,"utf8"))}catch{}return{kid:s,source:c,publicKeyPath:oe(e,a),email:l}}))}o(Yt,"discoverLocalKeys");function Jt(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth()+t,i=new Date(Date.UTC(n,r+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(n,r,s))}o(Jt,"addMonthsClamped");function $e(e){return e.toISOString().slice(0,10)}o($e,"formatIsoDate");function Xt(e=new Date){return $e(e)}o(Xt,"todayIso");import ei,{Chalk as ti}from"chalk";var Fe=new ti({level:0});function zt(e){return e.isTTY?ei:Fe}o(zt,"chalkForStream");function ni(e){return e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"")}o(ni,"pemBodyOneLine");function Wt(e,t=Fe,n=new Date){let r=e.issuedAt??Xt(n),i=ni(e.publicKeyPem),s=" ",a=o((p,l)=>`${s}${t.cyan(p)}${t.dim(":")} ${l}
|
|
111
|
-
|
|
107
|
+
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>Ni(n))}o(kn,"registerStatusCommand");import{existsSync as Zn,readFileSync as ye,writeFileSync as ft,mkdirSync as Fs}from"fs";import{resolve as _}from"path";import{fileURLToPath as Ls}from"url";import{CogniteClient as Os}from"@cognite/sdk";import{mkdirSync as Ds,readFileSync as Ts,rmSync as Rs,writeFileSync as se}from"fs";import{resolve as H}from"path";import{generate as Yn}from"@graphql-codegen/cli";import{GraphQLSchema as hs,GraphQLObjectType as ws,GraphQLNonNull as R,GraphQLList as ie,GraphQLString as W,GraphQLInt as Ss,GraphQLInputObjectType as Kn,printSchema as Cs}from"graphql";function st(e){return{space:e.space,externalId:e.externalId,version:e.version}}o(st,"toSharedViewId");function _i(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(_i,"dmsTypeToGraphQL");function En(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:st(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?_i(e.type.type):"String"}}if("through"in e)return{kind:e.connectionType==="single_reverse_direct_relation"?"reverseDirect":"reverseList",sourceView:st(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:st(e.source),direction:t}}return{kind:"scalar"}}o(En,"parsePropertyDescriptor");var bn=new Set(["String","Boolean","Int","Float","DateTime","Date"]);var ji=new Set(["String","Int","Float","DateTime","Date"]);function Pe(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:bn.has(e.graphqlType??"String")}o(Pe,"isFilterableDescriptor");function Ie(e){return e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:bn.has(e.graphqlType??"String")}o(Ie,"isSortableDescriptor");function Pn(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind==="scalar"&&e.isList!==!0&&ji.has(e.graphqlType??"")}o(Pn,"hasInOpDescriptor");function In(e){return e.kind==="scalar"&&e.isList===!0}o(In,"hasListOpsDescriptor");function ue(e){return e.usedFor!=="edge"}o(ue,"isNodeOrAll");function D(e){return Object.entries(e.properties).map(([t,n])=>[t,En(n),n.description])}o(D,"parsedProperties");import{GraphQLObjectType as An,GraphQLNonNull as ge,GraphQLString as lt,GraphQLFloat as $e,GraphQLList as Hi,GraphQLEnumType as Bi}from"graphql";import{GraphQLScalarType as J,Kind as P}from"graphql";function at(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]=at(n.value);return t}case P.LIST:return e.values.map(at);case P.NULL:return null;default:return null}}o(at,"parseLiteralJSON");var Mi=new J({name:"DateTime",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Vi=new J({name:"Date",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),pt=new J({name:"JSON",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:at}),Ui=new J({name:"CogniteTimeSeriesReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Ki=new J({name:"CogniteFileReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Gi=new J({name:"CogniteSequenceReference",serialize:o(e=>e,"serialize"),parseValue:o(e=>e,"parseValue"),parseLiteral:o(e=>e.kind===P.STRING?e.value:null,"parseLiteral")}),Ae=new J({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")}),Y={DateTime:Mi,Date:Vi,JSON:pt,CogniteTimeSeriesReference:Ui,CogniteFileReference:Ki,CogniteSequenceReference:Gi,ListLimit:Ae},ct={DateTime:"string",Date:"string",JSON:"unknown",CogniteTimeSeriesReference:"string",CogniteFileReference:"string",CogniteSequenceReference:"string",ListLimit:"number"};var qi=new Bi({name:"AggregateFunction",values:{count:{value:"count"},avg:{value:"avg"},sum:{value:"sum"},min:{value:"min"},max:{value:"max"},histogram:{value:"histogram"}}}),$n={function:{type:new ge(qi)},property:{type:lt},interval:{type:$e}},Qi=new An({name:"HistogramBucket",fields:{start:{type:new ge($e)},count:{type:new ge($e)}}}),Dn=new An({name:"AggregateResult",fields:{aggregate:{type:new ge(lt)},property:{type:lt},value:{type:$e},buckets:{type:new Hi(new ge(Qi))},group:{type:pt}}});import{GraphQLObjectType as mt,GraphQLNonNull as ne,GraphQLList as Ji,GraphQLString as dt,GraphQLBoolean as Yi}from"graphql";var zi=new mt({name:"PageInfo",fields:{endCursor:{type:dt},hasNextPage:{type:new ne(Yi)}}}),De=new mt({name:"NodeReference",fields:{space:{type:new ne(dt)},externalId:{type:new ne(dt)}}});function Te(e,t){return new mt({name:`${e}Connection`,fields:{items:{type:new ne(new Ji(new ne(t)))},pageInfo:{type:new ne(zi)}}})}o(Te,"makeConnectionType");import{GraphQLInputObjectType as re,GraphQLList as A,GraphQLNonNull as On,GraphQLString as z,GraphQLBoolean as I,GraphQLFloat as os,GraphQLInt as is}from"graphql";import{GraphQLObjectType as Wi,GraphQLNonNull as Tn,GraphQLList as Xi,GraphQLString as Re,GraphQLBoolean as Zi,GraphQLInt as es,GraphQLFloat as ts,GraphQLEnumType as ns}from"graphql";function Rn(e){return e==="String"?Re:e==="Boolean"?Zi:e==="Int"?es:e==="Float"?ts:Y[e]??Re}o(Rn,"scalarForName");function Fn(e){return{typeRegistry:new Map,connectionRegistry:new Map,viewsByExtId:new Map(e.map(t=>[t.externalId,t])),enumRegistry:new Map,enumFilterRegistry:new Map}}o(Fn,"createTypeContext");function rs(e){let t=e.replace(/[^_A-Za-z0-9]/g,"_");return/^[0-9]/.test(t)&&(t=`_${t}`),t||"_UNKNOWN"}o(rs,"sanitizeEnumValue");function ut(e,t,n,r){let i=n.enumRegistry.get(e);if(i)return i;let s=new ns({name:e,values:Object.fromEntries(t.map(a=>[rs(a),{value:a,description:r?.[a]}]))});return n.enumRegistry.set(e,s),s}o(ut,"getOrCreateEnumType");function Ln(e,t){return new Wi({name:e.externalId,description:e.description??e.name,fields:o(()=>{let n={space:{type:new Tn(Re)},externalId:{type:new Tn(Re)}};for(let[r,i,s]of D(e))if(i.kind==="scalar")i.isList?n[r]={type:new Xi(Rn(i.graphqlType??"String")),description:s}:n[r]={type:Rn(i.graphqlType??"String"),description:s};else if(i.kind==="enum"){let a=`${e.externalId}${r.charAt(0).toUpperCase()}${r.slice(1)}`;n[r]={type:ut(a,i.values,t,i.valueNames),description:s}}else if(i.kind==="directRelation"){let a=t.typeRegistry.get(i.targetView.externalId)??De;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)??De,c=t.connectionRegistry.get(a);c||(c=Te(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)??De;n[r]={type:a,description:s}}return n},"fields")})}o(Ln,"generateViewObjectType");function oe(e,t,n){let r={isNull:{type:I},exists:{type:I},eq:{type:t}};return n.hasIn&&(r.in={type:new A(t)}),n.hasPrefix&&(r.prefix={type:z}),n.hasRange&&(r.gte={type:t},r.gt={type:t},r.lte={type:t},r.lt={type:t}),n.hasListOps&&(r.containsAny={type:new A(t)},r.containsAll={type:new A(t)},r.overlaps={type:new A(t)}),new re({name:e,fields:r})}o(oe,"makeScalarFilter");var Fe=oe("StringFilter",z,{hasIn:!0,hasPrefix:!0}),ss=oe("BooleanFilter",I,{}),as=oe("IntFilter",is,{hasIn:!0,hasRange:!0}),ps=oe("FloatFilter",os,{hasIn:!0,hasRange:!0}),cs=oe("DateTimeFilter",Y.DateTime,{hasIn:!0,hasRange:!0}),ls=oe("DateFilter",Y.Date,{hasIn:!0,hasRange:!0}),ds=new re({name:"StringListFilter",fields:{isNull:{type:I},exists:{type:I},containsAny:{type:new A(z)},containsAll:{type:new A(z)},overlaps:{type:new A(z)}}}),fe=new re({name:"DirectRelationRef",fields:{space:{type:new On(z)},externalId:{type:new On(z)}}}),ms=new re({name:"DirectRelationFilter",fields:{isNull:{type:I},exists:{type:I},eq:{type:fe},in:{type:new A(fe)}}});function us(e){switch(e){case"String":return Fe;case"Boolean":return ss;case"Int":return as;case"Float":return ps;case"DateTime":return cs;case"Date":return ls;default:return Fe}}o(us,"scalarFilterForName");var Nn=["space","externalId"];function _n(e,t,n){let r=t.get(e.externalId),i={};for(let a of Nn)i[a]={type:Fe};let s=new Set(Nn);for(let[a,p]of D(e)){if(s.has(a))continue;let c=Pe(p),d=In(p);if(!(!c&&!d))if(p.kind==="directRelation"){let l={isNull:{type:I},exists:{type:I},eq:{type:fe},in:{type:new A(fe)}};Pn(p)&&(l.in={type:new A(fe)});let m=t.get(p.targetView.externalId);m&&(l.nested={type:m}),i[a]=m?{type:new re({name:`_${e.externalId}_${a}_Filter`,fields:l})}:{type:ms}}else if(p.kind==="enum"){let l=`${e.externalId}${a.charAt(0).toUpperCase()}${a.slice(1)}`,m=ut(l,p.values,n),g=n.enumFilterRegistry.get(l);g||(g=new re({name:`${l}Filter`,fields:{isNull:{type:I},exists:{type:I},eq:{type:m},in:{type:new A(m)}}}),n.enumFilterRegistry.set(l,g)),i[a]={type:g}}else if(d)i[a]={type:ds};else{let l=p.kind==="scalar"?p.graphqlType??"String":"String",m=us(l);m&&(i[a]={type:m})}}return{...i,hasData:{type:I},matchAll:{type:I},_and:{type:new A(r)},_or:{type:new A(r)},_not:{type:r}}}o(_n,"generateFilterFields");import{GraphQLEnumType as jn,GraphQLInputObjectType as Mn,GraphQLList as gs,GraphQLNonNull as Le,GraphQLString as fs,GraphQLBoolean as ys}from"graphql";var Oe=new jn({name:"SortDirection",values:{ASC:{value:"ascending"},DESC:{value:"descending"}}});function Vn(e){let t=[];for(let[r,i]of D(e))Ie(i)&&t.push(r);if(t.length===0)return null;let n=new jn({name:`${e.externalId}SortField`,values:Object.fromEntries(t.map(r=>[r,{value:r}]))});return new Mn({name:`${e.externalId}Sort`,fields:{field:{type:new Le(n)},direction:{type:new Le(Oe)},nullsFirst:{type:ys}}})}o(Vn,"generateSortInput");var Un=new Mn({name:"SearchSort",fields:{property:{type:new Le(new gs(new Le(fs)))},direction:{type:Oe}}});function Gn(e){let t=e.filter(ue),n=Fn(t);for(let l of t){let m=Ln(l,n);n.typeRegistry.set(l.externalId,m)}let r=new Map;for(let l of t){let m=new Kn({name:`${l.externalId}Filter`,fields:o(()=>_n(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=Te(m,g),n.connectionRegistry.set(m,f));let y=r.get(m),w=Vn(l),u={limit:{type:Ae},cursor:{type:W},filter:{type:y}};w&&(u.sort={type:new ie(w)}),i[`query${m}`]={type:new R(f),args:u},i[`get${m}ById`]={type:g,args:{space:{type:new R(W)},externalId:{type:new R(W)}}},i[`count${m}`]={type:new R(Ss),args:{filter:{type:y}}},i[`search${m}`]={type:new R(f),args:{query:{type:W},limit:{type:Ae},filter:{type:y},sort:{type:new ie(new R(Un))},properties:{type:new ie(new R(W))}}},i[`aggregate${m}`]={type:new R(new ie(new R(Dn))),args:{filter:{type:y},aggregates:{type:new ie(new R(new Kn({name:`${m}AggregateRequest`,fields:$n})))},groupBy:{type:new ie(new R(W))},query:{type:W}}}}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 hs({query:new ws({name:"Query",fields:i}),types:[Oe,...Object.values(Y),...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:Cs(p),schemaKnowledge:d}}o(Gn,"buildSchema");async function Hn(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(Hn,"fetchViews");import{GraphQLObjectType as xs,GraphQLNonNull as vs,GraphQLList as ks,isScalarType as Es,isEnumType as bs,parse as Ps,print as Is}from"graphql";function gt(e,t){let n=e.getType(t);if(!(n instanceof xs))return[];let r=n.getFields(),i=[];for(let[s,a]of Object.entries(r)){let p=a.type;for(;p instanceof vs||p instanceof ks;)p=p.ofType;(Es(p)||bs(p))&&i.push(s)}return i}o(gt,"scalarFieldsFor");function As(e,t){let n=gt(e,t),r=["space","externalId"];for(let i of["name","description"])n.includes(i)&&r.push(i);return r.join(" ")}o(As,"minimalRelationFields");function Bn(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} { ${As(t,a)} }`);else{let c=["space","externalId",...gt(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(Bn,"relationFieldsFor");function qn(e,t,n,r){return`query ${e}(${t}) {
|
|
108
|
+
${e}(${n}) {
|
|
109
|
+
items {
|
|
110
|
+
${r}
|
|
111
|
+
}
|
|
112
|
+
pageInfo { hasNextPage endCursor }
|
|
113
|
+
}
|
|
114
|
+
}`}o(qn,"paginatedOp");function Qn(e,t){let n=e.externalId,r=gt(t,n),i=Bn(e,t,!0),s=Bn(e,t,!1),a=[...r,...i].join(`
|
|
115
|
+
`),p=[...r,...s].join(`
|
|
116
|
+
`),c=!!t.getType(`${n}Sort`),d=qn(`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=qn(`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!) {
|
|
117
|
+
get${n}ById(space: $space, externalId: $externalId) {
|
|
118
|
+
${p}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
`,g=`query count${n}($filter: ${n}Filter) {
|
|
122
|
+
count${n}(filter: $filter)
|
|
123
|
+
}`,f=`query aggregate${n}($filter: ${n}Filter, $aggregates: [${n}AggregateRequest!], $groupBy: [String!], $query: String) {
|
|
124
|
+
aggregate${n}(filter: $filter, aggregates: $aggregates, groupBy: $groupBy, query: $query) {
|
|
125
|
+
aggregate
|
|
126
|
+
property
|
|
127
|
+
value
|
|
128
|
+
buckets { start count }
|
|
129
|
+
group
|
|
130
|
+
}
|
|
131
|
+
}`;return Is(Ps([d,m,g,l,f].join(`
|
|
132
|
+
|
|
133
|
+
`)))}o(Qn,"generateViewOperations");function $s(e){return{availableOnList:e.kind==="scalar",returnsMany:e.kind==="reverseList"||e.kind==="edge",filterable:Pe(e),sortable:Ie(e)}}o($s,"fetchCharacteristics");function Jn(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:$s(r)}]))}))}}o(Jn,"buildSdkMetadata");async function zn(e,t,n){let r=await Hn(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}=Gn(s),c=s.filter(ue),d=H(n,e.name);Rs(d,{recursive:!0,force:!0}),Ds(d,{recursive:!0}),se(H(d,"schema.graphql"),p,"utf-8"),se(H(d,"sdk-metadata.json"),JSON.stringify(Jn(c),null,2),"utf-8"),se(H(d,"views.generated.ts"),`import type { ViewDefinition } from '@cognite/sdk';
|
|
134
|
+
|
|
135
|
+
// Auto-generated \u2014 do not edit.
|
|
136
|
+
export const views: ViewDefinition[] = ${JSON.stringify(c,null,2)};
|
|
137
|
+
`,"utf-8"),await Yn({schema:p,generates:{[H(d,"types.generated.ts")]:{plugins:["typescript"],config:{scalars:ct}}}},!0);for(let u of c){let h=Qn(u,a),S=H(d,`${u.externalId}.generated.ts`);await Yn({schema:p,documents:h,generates:{[S]:{plugins:["typescript-operations","typescript-generic-sdk"],config:{scalars:ct,namespacedImportName:"Types"}}}},!0);let C=Ts(S,"utf-8");C=C.replace(/^import \{ DocumentNode \} from 'graphql';$/m,"import type { DocumentNode } from 'graphql';").replace(/Requester<C = \{\}>/g,"Requester<C = Record<string, never>>"),C.includes("import type * as Types")||(C=C.replace(/^import type \{ DocumentNode \} from 'graphql';$/m,`import type { DocumentNode } from 'graphql';
|
|
138
|
+
import type * as Types from './types.generated.js';`)),se(S,C)}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 S=o(C=>C.match(/from '(\.\/[^']+)'/)?.[1]??"","path");return S(u).localeCompare(S(h),void 0,{sensitivity:"base"})}).join(`
|
|
139
|
+
`),f=l.map(u=>` ...get${u}Sdk(requester),`).join(`
|
|
140
|
+
`),y=l.map(u=>{let h=m(u);return`export type {
|
|
141
|
+
${["query","get","count","search","aggregate"].flatMap(k=>{let T=k==="get"?`Get${h}ById`:`${k.charAt(0).toUpperCase()+k.slice(1)}${h}`;return[` ${T}Query`,` ${T}QueryVariables`]}).join(`,
|
|
142
|
+
`)},
|
|
143
|
+
} from './${u}.generated.js';`}).join(`
|
|
144
|
+
`);se(H(d,"index.ts"),`import { createDuneRuntimeFromViews } from '@cognite/cli';
|
|
145
|
+
import type { CogniteClient } from '@cognite/sdk';
|
|
146
|
+
|
|
147
|
+
${g}
|
|
148
|
+
|
|
149
|
+
export * from './types.generated.js';
|
|
150
|
+
${y}
|
|
151
|
+
|
|
152
|
+
// Internal \u2014 merges all per-view getSdk() functions.
|
|
153
|
+
// Not exported: callers use createSdk() instead.
|
|
154
|
+
function makeSdk(requester: Parameters<typeof get${l[0]}Sdk>[0]) {
|
|
155
|
+
return {
|
|
156
|
+
${f}
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export type Sdk = ReturnType<typeof makeSdk>;
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Creates a fully-typed SDK backed by the Dune runtime.
|
|
164
|
+
* Queries are executed in-process via graphql-js and translated to DMS API calls \u2014
|
|
165
|
+
* no CDF GraphQL endpoint is involved.
|
|
166
|
+
*/
|
|
167
|
+
export function createSdk(client: CogniteClient): Sdk {
|
|
168
|
+
const runtime = createDuneRuntimeFromViews(views, client);
|
|
169
|
+
return makeSdk(runtime.requester);
|
|
170
|
+
}
|
|
171
|
+
`,"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(`
|
|
172
|
+
`);return se(H(d,"test-helpers.ts"),`import { vi } from 'vitest';
|
|
173
|
+
|
|
174
|
+
import type { Sdk } from './index.js';
|
|
175
|
+
|
|
176
|
+
export function makeMockSdk(overrides: Partial<Sdk> = {}): Sdk {
|
|
177
|
+
return {
|
|
178
|
+
${w}
|
|
179
|
+
...overrides,
|
|
180
|
+
} as Sdk;
|
|
181
|
+
}
|
|
182
|
+
`,"utf-8"),{sdkDir:d,viewCount:c.length}}o(zn,"generateSdk");var Ne=Symbol("BACK");async function er(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...
|
|
183
|
+
`);let c=await ve(t.orgHint??r.org??void 0);if(!c?.access_token)throw new Error("No access token received");return console.log(`
|
|
184
|
+
\u2705 Authentication successful!
|
|
185
|
+
`),{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 ce(r);return console.log(`\u2705 Authenticated
|
|
186
|
+
`),{token:p,baseUrl:i,project:s}}o(er,"resolveAuth");async function ht(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(ht,"getEnquirerClass");async function yt(e,t,n){let r=await ht("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(yt,"pick");async function Ns(e,t,n){let r=await ht("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(Ns,"searchPick");async function _s(e,t=""){let n=await ht("Input");return new n({message:e,initial:t}).run()}o(_s,"ask");async function js(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(js,"cdfFetch");async function Ms(e,t,n){return(await js(`${e}/api/v1/projects/${t}/models/datamodels?includeGlobal=true&limit=1000`,n)).items??[]}o(Ms,"fetchDataModels");async function Vs(e,t={}){let n=process.cwd();process.chdir(e);try{$(e);let r=v(e),{token:i,baseUrl:s,project:a}=await er(r,t),p=null;async function c(){return p||(p=await Ms(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(`
|
|
187
|
+
\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.
|
|
188
|
+
`),d.chosenModel=await Ns("\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 _s(`
|
|
189
|
+
SDK name (folder under src/generated_sdks/, "back" to go back):`,g);if(f.toLowerCase()==="back")return Ne;let u=(JSON.parse(ye(_(e,"app.json"),"utf-8")).generatedSdks??[]).find(h=>h.name===f);if(u){console.log(`
|
|
190
|
+
\u26A0\uFE0F An SDK named "${f}" already exists in app.json:`),console.log(` ${u.dataModelSpace} / ${u.dataModelExternalId} @ ${u.dataModelVersion}`);let h=await yt("What would you like to do?",["Replace existing entry","Pick a different name","Cancel"],S=>S);if(h==="Cancel"&&(console.log(`
|
|
191
|
+
Cancelled.
|
|
192
|
+
`),process.exit(0)),h==="Pick a different name")return Ne}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(`
|
|
193
|
+
\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 yt("Write to app.json?",["Yes","Back","Cancel"],y=>y);return f==="Back"?Ne:(f==="Cancel"&&(console.log(`
|
|
194
|
+
Cancelled.
|
|
195
|
+
`),process.exit(0)),Us(e,g),!0)}],m=0;for(;m<l.length;)await l[m]()===Ne?(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(Vs,"runWizard");function Us(e,t){let n=_(e,"app.json"),r=JSON.parse(ye(n,"utf-8"));r.generatedSdks=[...r.generatedSdks??[],t],ft(n,JSON.stringify(r,null,2)+`
|
|
196
|
+
`);let i=_(e,".dune","sdk-configs");try{Zn(i)||Fs(i,{recursive:!0}),ft(_(i,`${t.name}.json`),JSON.stringify(t,null,2)+`
|
|
197
|
+
`),console.log(`
|
|
198
|
+
\u2705 Added "${t.name}" to app.json`),console.log(` Config saved to .dune/sdk-configs/${t.name}.json`)}catch{console.log(`
|
|
199
|
+
\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(Us,"writeEntry");async function Wn(e,t,n,r={}){let i=n??process.cwd();$(i);let s=v(i),p=(JSON.parse(ye(_(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 er(s,r),d=s.deployments[0],l=new Os({appId:s.externalId,project:d.project,baseUrl:d.baseUrl,oidcTokenProvider:o(async()=>c,"oidcTokenProvider")});await l.authenticate();let m=_(i,"src/generated_sdks");console.log(`
|
|
200
|
+
\u2699\uFE0F Generating "${p.name}" (${p.dataModelSpace}/${p.dataModelExternalId}@${p.dataModelVersion})...`);let{sdkDir:g,viewCount:f}=await zn({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=_(i,"package.json");if(Zn(y)){let w=JSON.parse(ye(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 S=r.linkLocal?`file:${_(Ls(import.meta.url),"../../..")}`:"^1.1.0-alpha.50";u["@cognite/cli"]!==S&&(u["@cognite/cli"]=S,h.push("@cognite/cli")),h.length>0&&(w.dependencies=u,ft(y,JSON.stringify(w,null,2)+`
|
|
201
|
+
`,"utf-8"),console.log(`
|
|
202
|
+
\u{1F4E6} Updated package.json: ${h.join(", ")} (run npm install)`))}}o(Wn,"generate");function Xn(e){return{interactive:e.interactive,orgHint:e.org,linkLocal:e.linkLocal}}o(Xn,"sdkCommandOptions");function tr(e){e.command("sdk").summary("Add or regenerate typed GraphQL SDKs from CDF data models").description(`Add or regenerate typed GraphQL SDKs from CDF data models.
|
|
203
|
+
Run with --interactive for the guided wizard (pick a data model, update app.json, generate types).`).option("--interactive","Run the guided wizard (pick data model, update app.json, generate types)").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)").addHelpText("after",`
|
|
204
|
+
Examples:
|
|
205
|
+
npx @cognite/cli apps sdk --interactive Guided setup: pick a data model, add to app.json, generate types
|
|
206
|
+
npx @cognite/cli apps sdk generate Regenerate types for SDKs already in app.json
|
|
207
|
+
npx @cognite/cli apps sdk generate my-sdk Regenerate a specific SDK by name
|
|
208
|
+
|
|
209
|
+
Without --interactive, this command only shows help. Use --interactive for the guided wizard.
|
|
210
|
+
Non-interactive auth for generate uses the same env vars as apps deploy (COGNITE_TOKEN or deployment credentials).`).action(async function(n){if(!n.interactive){this.outputHelp();return}let r=process.cwd(),i=Xn(n),{sdkName:s,auth:a}=await Vs(r,i);await Wn(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=Xn(r),p=JSON.parse(ye(_(i,"app.json"),"utf-8")).generatedSdks??[];p.length===0&&(console.error('No generatedSdks entries found in app.json. Run "cognite apps sdk --interactive" first.'),process.exit(1));let c=n??(p.length===1?p[0].name:await yt("Which SDK to regenerate?",p,d=>d.name));await Wn(typeof c=="string"?c:c.name,void 0,i,s)})}o(tr,"registerSdkCommand");function nr(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),tr(t),t}o(nr,"registerAppsCommand");import{existsSync as La,mkdirSync as Oa,writeFileSync as Na}from"fs";import{dirname as Pt,join as It}from"path";import{execFile as Gs}from"child_process";import{promisify as Hs}from"util";import{platform as Ks}from"os";function X(e={}){let{platform:t=Ks}=e;return t()==="darwin"}o(X,"isMacOS");var rr="cognite-flows",Bs=Hs(Gs),or=o((e,t)=>Bs(e,t),"defaultExecFile"),qs=-25300,Qs=qs&255;function Js(e){if(!(e instanceof Error)||!("code"in e)||e.code!==Qs)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(Js,"isKeychainNotFoundError");async function ir(e,t,n={}){if(!X(n))throw new Error("Keychain storage is only supported on macOS");let{execFile:r=or}=n;await r("security",["add-generic-password","-a",e,"-s",rr,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(ir,"storeKeyInKeychain");async function sr(e,t={}){if(!X(t))return null;let{execFile:n=or}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",rr,"-w"]);return Buffer.from(r.trim(),"base64").toString("utf-8")}catch(r){if(Js(r))return null;throw r}}o(sr,"readKeyFromKeychain");import{pbkdf2 as Ws,randomBytes as Xs}from"crypto";import{promisify as Zs}from"util";import{CompactEncrypt as ea,base64url as ta,compactDecrypt as ru}from"jose";var Ys=new TextEncoder,zs=new TextDecoder,ar={encode:o(e=>Ys.encode(e),"encode"),decode:o(e=>zs.decode(e),"decode")};var na=Zs(Ws),wt=6e5,ra="sha512",oa="PBKDF2-HMAC-SHA512",ia=16,sa="A256GCM",aa=32,pr=2e6;async function pa(e,t,n){return await na(e,t,n,aa,ra)}o(pa,"deriveKey");async function cr(e,t,n=wt){if(!Number.isInteger(n)||n<1||n>pr)throw new Error(`Invalid iterations: must be an integer between 1 and ${pr}`);let r=Xs(ia),i=await pa(t,r,n);return await new ea(ar.encode(e)).setProtectedHeader({alg:"dir",enc:sa,kdf:oa,kdf_iter:n,kdf_salt:ta.encode(r)}).encrypt(i)}o(cr,"encryptStringAsJwe");import{calculateJwkThumbprint as ca,exportJWK as la,exportPKCS8 as da,exportSPKI as ma,generateKeyPair as ua}from"jose";async function lr(){let{publicKey:e,privateKey:t}=await ua("EdDSA",{extractable:!0}),n=await da(t),r=await ma(e),i=await la(e),s=await ca(i);return{privateKeyPem:n,publicKeyPem:r,kid:s}}o(lr,"generateSigningKeyPair");import{existsSync as fa,readdirSync as ya,readFileSync as ha}from"fs";import{join as _e}from"path";import{homedir as ga}from"os";import{join as dr}from"path";function Z(e={}){let{env:t=process.env,homedir:n=ga}=e,r=t.DUNE_HOME?.trim()||dr(n(),".dune");return{home:r,keysDir:dr(r,"keys")}}o(Z,"getConfig");var je=".pub.pem",St=".key.jwe",wa=".pem",Ct=".meta.json";function mr(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(mr,"formatLocalKeySource");function Sa(e){return{existsSync:e.existsSync??fa,readdirSync:e.readdirSync??ya,readFileSync:e.readFileSync??((t,n)=>ha(t,n)),isMacOS:e.isMacOS??(()=>X()),readKeyFromKeychain:e.readKeyFromKeychain??(t=>sr(t))}}o(Sa,"resolveDeps");function Ca(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(Ca,"readEmailFromMeta");function xa(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(je)):[]}o(xa,"publicKeyEntries");function va(e){return e.slice(0,-je.length)}o(va,"kidFromPublicKeyFilename");async function ka(e,t,n){if(n.isMacOS()&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let r=_e(t,`${e}${St}`);if(n.existsSync(r))return{kind:"encrypted-file",path:r};let i=_e(t,`${e}${wa}`);return n.existsSync(i)?{kind:"legacy-unencrypted-file",path:i}:{kind:"public-only"}}o(ka,"resolveSource");async function ur(e=Z().keysDir,t={}){let n=Sa(t),r=new Set,i=xa(e,n).flatMap(s=>{let a=va(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 ka(s,e,n),c=_e(e,`${s}${Ct}`),d;try{d=Ca(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:_e(e,a),email:d}}))}o(ur,"discoverLocalKeys");function gr(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(gr,"addMonthsClamped");function xt(e){return e.toISOString().slice(0,10)}o(xt,"formatIsoDate");function fr(e=new Date){return xt(e)}o(fr,"todayIso");import Ea,{Chalk as ba}from"chalk";var vt=new ba({level:0});function yr(e){return e.isTTY?Ea:vt}o(yr,"chalkForStream");function Pa(e){return e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"")}o(Pa,"pemBodyOneLine");function hr(e,t=vt,n=new Date){let r=e.issuedAt??fr(n),i=Pa(e.publicKeyPem),s=" ",a=o((c,d)=>`${s}${t.cyan(c)}${t.dim(":")} ${d}
|
|
211
|
+
`,"kv"),p="";return p+=`
|
|
112
212
|
${t.bold("Add this entry to")} ${t.magenta("services/app-hosting/config/signing-keys.yaml")} ${t.bold("under")} ${t.cyan("public_keys:")}
|
|
113
213
|
|
|
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,
|
|
214
|
+
`,p+=`${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
|
|
215
|
+
`,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(hr,"renderRegistryEntry");import{email as Ia,pipe as Aa,safeParse as $a,string as Da}from"valibot";var Ta=Aa(Da(),Ia());function we(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!$a(Ta,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}o(we,"parseEmail");function Se(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(Se,"parseExpiryMonths");import Fa from"enquirer";var Me=3,wr=`Key expiry in months (${1}-${12})`,Sr="Email address for the registry entry",Cr=`Passphrase for the encrypted private key (min ${15} chars)`,xr="Confirm passphrase",vr=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),kr=o(e=>`Passphrases do not match (attempt ${e}/${Me}).
|
|
216
|
+
`,"passphraseMismatchMsg"),Er=`Passphrase confirmation failed after ${Me} attempts`;async function bt(e){return Fa.prompt(e)}o(bt,"defaultPrompt");function br(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}o(br,"parserAsValidator");async function Pr(e={}){let{prompt:t=bt}=e,{months:n}=await t({type:"input",name:"months",message:wr,initial:String(6),validate:br(r=>Se(r,"expiry"))});return Se(n,"expiry")}o(Pr,"promptExpiryMonths");async function Ir(e={}){let{prompt:t=bt,gitUserEmail:n=rn}=e,{email:r}=await t({type:"input",name:"email",message:Sr,initial:n(),validate:br(i=>we(i,"email"))});return we(r,"email")}o(Ir,"promptEmail");async function Ar(e={}){let{prompt:t=bt,stderr:n=process.stderr}=e;for(let r=1;r<=Me;r+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:Cr,validate:o(a=>a.length>=15?!0:vr(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:xr});if(i===s)return i;n.write(kr(r))}throw new Error(Er)}o(Ar,"promptPassphrase");function _a(e){return{writeFileSync:e.writeFileSync??Na,mkdirSync:e.mkdirSync??Oa,existsSync:e.existsSync??La,generateSigningKeyPair:e.generateSigningKeyPair??lr,encryptStringAsJwe:e.encryptStringAsJwe??cr,storeKeyInKeychain:e.storeKeyInKeychain??ir,isMacOS:e.isMacOS??X,promptExpiryMonths:e.promptExpiryMonths??Pr,promptEmail:e.promptEmail??Ir,promptPassphrase:e.promptPassphrase??Ar,discoverLocalKeys:e.discoverLocalKeys??(()=>ur())}}o(_a,"resolveDeps");function Dr(e,t={}){let n=_a(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=>Va(i,n)),r.command("list").description("List local signing identities and their storage location").action(()=>ja(n))}o(Dr,"registerKeysCommand");async function ja(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
|
|
217
|
+
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${Z().keysDir}).
|
|
218
|
+
`);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,mr(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
219
|
`);for(let a of r)process.stdout.write(`${s(a)}
|
|
120
|
-
`)}o(
|
|
220
|
+
`)}o(ja,"handleList");function $r(e,t,n){let r=It(Z().keysDir,`${e}${je}`);return n.mkdirSync(Pt(r),{recursive:!0}),n.writeFileSync(r,t),r}o($r,"writePublicKey");async function Ma(e,t,n,r,i){let s=r??It(Z().keysDir,`${e}${St}`);if(i.mkdirSync(Pt(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(Ma,"writeEncryptedPrivateKey");async function Va(e,t,n=new Date){let r=e.keychain!==!1&&t.isMacOS()&&!e.output,i=e.expires!==void 0?Se(e.expires):await t.promptExpiryMonths(),s=xt(gr(n,i)),a=e.email!==void 0?we(e.email,"--email"):await t.promptEmail(),p=r?null:await t.promptPassphrase();process.stderr.write(`
|
|
121
221
|
Generating Ed25519 keypair...
|
|
122
222
|
|
|
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${
|
|
223
|
+
`);let{privateKeyPem:c,publicKeyPem:d,kid:l}=await t.generateSigningKeyPair();if(r){await t.storeKeyInKeychain(l,c);let f=$r(l,d,t);process.stderr.write(`Public key: ${f}
|
|
224
|
+
`),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${l})
|
|
225
|
+
`)}else{if(p===null)throw new Error("passphrase is required when not using Keychain");let f=await Ma(l,c,p,e.output,t),y=$r(l,d,t);process.stderr.write(`Public key: ${y}
|
|
226
|
+
`),process.stderr.write(`Private key: ${f} (JWE, AES-256-GCM, PBKDF2-SHA512 x${wt.toLocaleString()})
|
|
127
227
|
`),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): ${
|
|
228
|
+
`)}let m=It(Z().keysDir,`${l}${Ct}`);t.mkdirSync(Pt(m),{recursive:!0}),t.writeFileSync(m,JSON.stringify({email:a}));let g=yr(process.stderr);process.stderr.write(`
|
|
229
|
+
Signing identity (kid): ${g.green(l)}
|
|
130
230
|
`),process.stderr.write(`Expires: ${s} (${i} month${i===1?"":"s"} from today)
|
|
131
|
-
`),process.stderr.write(
|
|
132
|
-
${
|
|
133
|
-
`)}o(
|
|
134
|
-
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{
|
|
135
|
-
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(
|
|
136
|
-
`),
|
|
137
|
-
`);let f=o(()=>{},"finish"),
|
|
138
|
-
`)}}}o(
|
|
139
|
-
`);return
|
|
140
|
-
${
|
|
141
|
-
`)},"onOutdated")})});
|
|
142
|
-
Cancelled.`),process.exit(130)),await
|
|
231
|
+
`),process.stderr.write(hr({kid:l,publicKeyPem:d,email:a,expires:s},g,n)),process.stderr.write(`
|
|
232
|
+
${g.bold("Next:")} open a PR against the ${g.magenta("infrastructure")} repo with that block, then \`${g.cyan(`cognite sign -s ${l}`)}\`
|
|
233
|
+
`)}o(Va,"handleGenerate");var Tr=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 Rr(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(Rr,"tryLoadAppConfig");function At(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(At,"commandFromArgv");function Fr(e,t,n=v){e.hook("postAction",async(r,i)=>{try{let s={command:Ga(i),options:Ka(i.opts()),success:!0,...Rr(n)};t.track("Flows.CLI.Command",s),await t.flush(Tr)}catch{}})}o(Fr,"instrument");async function Lr(e,t,n=v){try{let r={command:At(t),options:{},success:!1,...Rr(n)};e.track("Flows.CLI.Command",r),await e.flush(Tr)}catch{}}o(Lr,"trackFailure");var Ha="ERR_USE_AFTER_CLOSE";function Nr(e){return e instanceof Error&&"code"in e&&e.code===Ha}o(Nr,"isReadlineClosedError");function Ba(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(Ba,"isPlainObject");function $t(e){return e==null||Nr(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Ba(e)&&Object.keys(e).length===0)}o($t,"isPromptCancel");var Or=!1;function _r(){Or||(Or=!0,process.on("uncaughtException",e=>{Nr(e)&&(console.error(`
|
|
234
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{$t(e)&&(console.error(`
|
|
235
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(_r,"installCancelHandler");import jr from"mixpanel";var qa="5c4d853e7c3b77b1eb4468d5329b278c",Ce="cognite-cli",Qa=2e3,Mr={env:process.env,init:jr.init.bind(jr)},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 Vr(e={}){let t=e.env??Mr.env,n=e.init??Mr.init,r=e.packageName,i=e.cliVersion,s=Ya(t);if(Dt(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
|
|
236
|
+
`),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)}
|
|
237
|
+
`);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)
|
|
238
|
+
`)}}}o(Vr,"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 Ur(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(Ur,"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 Kr}from"semver";var pp="https://registry.npmjs.org/@cognite/cli/latest",cp=1500,Gr="upgrade-check.json",Hr=Ve(process.env.XDG_CACHE_HOME||Ve(ip(),".cache"),"@cognite","cli"),Tt=sp("cognite-flows");function lp(e,t){return!e||!t||!Kr(e)||!Kr(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=Hr,t=864e5){try{let n=rp(Ve(e,Gr),"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,Gr),JSON.stringify(n))}catch(n){Tt("writeUpgradeCheckCache failed (%s): %O",e,n)}}o(up,"writeUpgradeCheckCache");async function gp({cacheDir:e=Hr,...t}={}){let n=await dp(t);n&&up(e,n)}o(gp,"startBackgroundUpgradeCheck");function Br(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(Br,"preActionUpgradeCheck");import{default as Dg,chalkStderr as qr}from"chalk";function Qr(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(`
|
|
239
|
+
`);return qr.bold.yellow(a)}o(Qr,"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)};_r();var ae=new yp;ae.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.1.0-alpha.50").showHelpAfterError().configureOutput({writeOut:o(e=>fp(1,e),"writeOut")});ae.hook("preAction",()=>{Br("1.1.0-alpha.50",{onOutdated:o((e,t)=>{console.warn(`
|
|
240
|
+
${Qr(e,t)}
|
|
241
|
+
`)},"onOutdated")})});nr(ae);Dr(ae);var Yr=Vr({packageName:"@cognite/cli",cliVersion:"1.1.0-alpha.50"}),Jr=Ur({packageName:"@cognite/cli",cliVersion:"1.1.0-alpha.50"});Fr(ae,Yr);var Rt=process.argv.slice(2);ae.parseAsync(Rt,{from:"user"}).catch(async e=>{await Lr(Yr,Rt),$t(e)&&(console.error(`
|
|
242
|
+
Cancelled.`),process.exit(130)),await Jr.captureError(e,{command:At(Rt)}),await Jr.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.50",
|
|
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};
|