@sap-ux/generator-odata-downloader 0.1.0 → 0.1.1
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/generators/app/index.js +1 -1
- package/package.json +9 -9
package/generators/app/index.js
CHANGED
|
@@ -751,7 +751,7 @@ this.composeWith({
|
|
|
751
751
|
${i}`);let s=[" getReferentialConstraints: function (navigationProperty) {",`${i}`," return undefined;"," }"].join(`
|
|
752
752
|
`),o=e.lastIndexOf(`
|
|
753
753
|
};`);return o!==-1?`${e.slice(0,o)},
|
|
754
|
-
${s}${e.slice(o)}`:e}var XZt=Vr(vo()),hQ=Vr(bs()),JZt=Vr(Xv()),XU=Vr(qZt()),QZt=require("node:fs/promises"),ZZt=require("node:path");var N1=Vr(bw()),BZt=Vr(vo()),VZt=require("node:crypto"),$Zt=Vr(kW());var jZt="0.1.0";var CTi="@sap-ux/odata-download-sub-generator",wTi="0a65e45d-6bf4-421d-b845-61e888c50e9e",au=class{static _telemetryData;static _sessionId;static async initTelemetrySettings(t){this._sessionId=(0,VZt.randomUUID)(),Pr.logger.info(`Telemetry session initialized with ID: ${this._sessionId}`);let r={consumerModule:{name:CTi,version:jZt},watchTelemetrySettingStore:!1,internalFeature:!0,resourceId:wTi,...t};try{await(0,N1.initTelemetrySettings)(r)}catch(n){Pr.logger.error(`Error initializing telemetry settings: ${n}`)}}static createTelemetryData(t){if(!this._telemetryData){let r=Kt("telemetry.unknownOs");try{r=(0,$Zt.default)()}catch{}this._telemetryData={Platform:(0,BZt.isAppStudio)()?"SBAS":"VSCode",OperatingSystem:r,SessionId:this._sessionId}}return this._telemetryData=Object.assign(this._telemetryData,t),this._telemetryData}static prepareTelemetryEvent(t,r){return{eventName:t,properties:r,measurements:{}}}static async sendTelemetry(t,r){let n=this.createTelemetryData(r),i=this.prepareTelemetryEvent(t,n);await N1.ClientFactory.getTelemetryClient().reportEvent(i,N1.SampleRate.NoSampling)}};var PTi=["eq","ne","gt","ge","lt","le"],fQ=["and","or","not"],DTi=["any","all"],NTi=["startswith","endswith","contains","matchespattern"],RTi=["expand","levels","select","skip","top","count","orderby","filter"],GZt=/\((.*)\)/,HZt=/(?!indexof)\((\w+)\)/;var $g="";function sDe({select:e,search:t,skiptoken:r,format:n,top:i,skip:s,filter:o,transform:a,orderBy:u,key:c,count:l,expand:f,action:p,func:d}={}){let m="",_=[],E={};if(c!=null&&(m+=`(${Ph(c,_)})`),(o||typeof l=="object")&&(E.$filter=dQ(typeof l=="object"?l:o,_)),a&&(E.$apply=YZt(a)),f&&(E.$expand=pQ(f)),u&&(E.$orderby=oDe(u)),l&&(typeof l=="boolean"?E.$count=!0:m+="/$count"),typeof i=="number"&&(E.$top=i),typeof s=="number"&&(E.$skip=s),p&&(m+=`/${p}`),d){if(typeof d=="string")m+=`/${d}`;else if(typeof d=="object"){let[S]=Object.keys(d),T=Ph(d[S],_);m+=`/${S}`,T!==""&&(m+=`(${T})`)}}return _.length>0&&Object.assign(E,_.reduce((S,T)=>Object.assign(S,{[`@${T.name}`]:Ph(T.value)}),{})),UTi(m,{$select:e,$search:t,$skiptoken:r,$format:n,...E})}function iDe(e,t,r=[]){return`${e} eq ${Ph(t,r)}`}function dQ(e={},t=[],r=""){return(Array.isArray(e)?e:[e]).reduce((s,o)=>{if(o){let a=n(o,t,r);a&&s.push(a)}return s},[]).join(" and ");function n(s={},o=[],a=""){let u="";return typeof s=="string"?u=s:s&&typeof s=="object"&&(u=Object.keys(s).reduce((c,l)=>{let f=s[l];if(f===void 0)return c;let p="";if(a?l===$g?p=a:HZt.test(l)?p=l.replace(HZt,(d,m)=>m.trim()===$g?`(${a})`:`(${a}/${m.trim()})`):GZt.test(l)?p=l.replace(GZt,(d,m)=>m.trim()===$g?`(${a})`:`(${a}/${m.trim()})`):p=`${a}/${l}`:p=l,l===$g&&Array.isArray(f))return c.concat(f.map(d=>iDe(p,d)));if(["number","string","boolean"].indexOf(typeof f)!==-1||f instanceof Date||f===null)c.push(iDe(p,f,o));else if(Array.isArray(f)){let d=l,m=f.map(_=>dQ(_,o,a)).filter(_=>_).map(_=>fQ.indexOf(d)!==-1?`(${_})`:_);m.length&&(fQ.indexOf(d)!==-1?m.length&&(d==="not"?c.push(WZt(m)):c.push(`(${m.join(` ${d} `)})`)):c.push(m.join(` ${d} `)))}else if(fQ.indexOf(p)!==-1){let d=p,m=Object.keys(f).map(_=>n({[_]:f[_]}));m.length&&(d==="not"?c.push(WZt(m)):c.push(`(${m.join(` ${d} `)})`))}else if(typeof f=="object")"type"in f?c.push(iDe(p,f,o)):Object.keys(f).forEach(d=>{if(f[d]!==void 0)if(PTi.indexOf(d)!==-1)c.push(`${p} ${d} ${Ph(f[d],o)}`);else if(fQ.indexOf(d)!==-1)Array.isArray(f[d])?c.push(f[d].map(m=>"("+n(m,o,p)+")").join(` ${d} `)):c.push("("+n(f[d],o,p)+")");else if(DTi.indexOf(d)!==-1){let m=i(l.toLowerCase(),f[d],d,p);m&&c.push(m)}else if(d==="has")c.push(`${p} ${d} ${Ph(f[d],o)}`);else if(d==="in"){let m=Array.isArray(f[d])?f[d]:f[d].value.map(_=>({type:f[d].type,value:_}));c.push(p+" in ("+m.map(_=>Ph(_,o)).join(",")+")")}else if(NTi.indexOf(d)!==-1)c.push(`${d}(${p},${Ph(f[d],o)})`);else{let m=n({[d]:f[d]},o,p);m&&c.push(m)}});else throw new Error(`Unexpected value type: ${f}`);return c},[]).join(" and ")),u}function i(s,o,a,u){let c="";if(typeof o=="string"||o instanceof String)c=ITi(s,o,a,u);else if(o){let l=Array.isArray(o)?o.reduce((p,d)=>d.hasOwnProperty($g)?(p.hasOwnProperty($g)||(p[$g]=[]),p[$g].push(d[$g]),p):{...p,...d},{}):o,f=n(l,t,s);c=`${u}/${a}(${f?`${s}:${f}`:""})`}return c}}function ITi(e,t,r,n){let i=r=="all"?"ne":"eq";return`${n}/${r}(${e}: ${e} ${i} '${t}')`}function MTi(e){return e=e.replace(/%/g,"%25"),e=e.replace(/\+/g,"%2B"),e=e.replace(/\//g,"%2F"),e=e.replace(/\?/g,"%3F"),e=e.replace(/#/g,"%23"),e=e.replace(/&/g,"%26"),e=e.replace(/'/g,"''"),e}function Ph(e,t){if(typeof e=="string")return`'${MTi(e)}'`;if(e instanceof Date)return e.toISOString();if(typeof e=="number")return e;if(Array.isArray(e))return`[${e.map(r=>Ph(r)).join(",")}]`;if(e===null)return e;if(typeof e=="object")switch(e.type){case"raw":case"guid":return e.value;case"duration":return`duration'${e.value}'`;case"binary":return`binary'${e.value}'`;case"alias":return Array.isArray(t)&&t.push(e),`@${e.name}`;case"json":return escape(JSON.stringify(e.value));case"decimal":return`${e.value}M`;default:return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,n])=>`${r}=${Ph(n,t)}`).join(",")}return e}function pQ(e){if(typeof e=="number")return e;if(typeof e=="string")return e.indexOf("/")===-1?e:e.split("/").reverse().reduce((t,r,n,i)=>n===0?`$expand=${r}`:n===i.length-1?`${r}(${t})`:`$expand=${r}(${t})`,"");if(Array.isArray(e))return`${e.map(t=>pQ(t)).join(",")}`;if(typeof e=="object"){let t=Object.keys(e);return t.some(r=>RTi.indexOf(r.toLowerCase())!==-1)?t.map(r=>{let n;switch(r){case"filter":n=dQ(e[r]);break;case"orderBy":n=oDe(e[r]);break;case"levels":case"count":case"skip":case"top":n=`${e[r]}`;break;default:n=pQ(e[r])}return`$${r.toLowerCase()}=${n}`}).join(";"):t.map(r=>{let n=pQ(e[r]);return n?`${r}(${n})`:r}).join(",")}return""}function YZt(e){return(Array.isArray(e)?e:[e]).reduce((t,r)=>{for(let n of Object.keys(r))switch(n){case"aggregate":{let i=r[n];i&&t.push(`aggregate(${LTi(i)})`);break}case"filter":{let i=r[n];if(i){let s=dQ(i);s&&t.push(`filter(${s})`)}break}case"groupBy":{let i=r[n];i&&t.push(`groupby(${FTi(i)})`);break}default:throw new Error(`Unsupported transform: ${n}`)}return t},[]).join("/")||void 0}function LTi(e){return(Array.isArray(e)?e:[e]).map(t=>typeof t=="string"?t:Object.keys(t).map(r=>{let n=t[r];if(!n.with&&n.as)return`${r} as ${n.as}`;if(!n.with)throw new Error(`'with' property required for '${r}'`);if(!n.as)throw new Error(`'as' property required for '${r}'`);return`${r} with ${n.with} as ${n.as}`})).join(",")}function FTi(e){if(!e.properties)throw new Error("'properties' property required for groupBy");let t=`(${e.properties.join(",")})`;return e.transform&&(t+=`,${YZt(e.transform)}`),t}function oDe(e,t=""){return Array.isArray(e)?e.map(r=>Array.isArray(r)&&r.length===2&&["asc","desc"].indexOf(r[1])!==-1?r.join(" "):r).map(r=>`${t}${String(r)}`).join(","):typeof e=="object"?Object.entries(e).map(([r,n])=>oDe(n,`${r}/`)).map(r=>`${t}${r}`).join(","):`${t}${String(e)}`}function UTi(e,t){let r=Object.getOwnPropertyNames(t).filter(n=>t[n]!==void 0&&t[n]!=="").map(n=>`${n}=${t[n]}`);return r.length?`${e}?${r.join("&")}`:e}function WZt(e){return`not (${e.join(" and ")})`}function kTi(e){let t=[];return{expands:e.reduce((n,{entityPath:i})=>{let s=i.split("/"),o=n;return s.forEach((a,u)=>{o.expand||(o.expand={}),o.expand[a]??=u===s.length-1?{}:{expand:{}},o=o.expand[a],t.includes(a)||t.push(a)}),n},{expand:{}}),entityPathParts:t}}function qTi(e,t,r=1,n){let i=t?.map(d=>({entityPath:d.fullPath,entitySetName:d.entity.entitySetName})),{expands:s,entityPathParts:o}=kTi(i),a=o.map(d=>t.find(_=>d===_.entity.entityPath?_.entity.entitySetName:void 0)?.entity.entitySetName).filter(d=>d!==void 0);Pr.logger.info(Kt("info.entityFilesToBeGenerated",{entities:a.join(", ")}));let u=e;if(n){let d=[];u.semanticKeys.forEach(x=>{if(x.value!==void 0&&x.value!=="")if(x.type==="Edm.Boolean")d.push(`${x.name} eq ${x.value}`);else{let F=String(x.value).split(","),q=["Edm.UUID","Edm.Guid"].includes(x.type),N=X=>q?X.trim():`'${X.trim()}'`;if(F.length===1)d.push(`${x.name} eq ${N(F[0])}`);else{let X=F.map(oe=>`${x.name} eq ${N(oe)}`);d.push(`(${X.join(" or ")})`)}}});let m=d.length>0?`,filter(${d.join(" and ")})`:"",_=`$root/${u.entitySetName},${n.qualifier},${n.nodeProperty}`,E=`com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=$root/${u.entitySetName},HierarchyQualifier='${n.qualifier}',NodeProperty='${n.nodeProperty}')`,S=n.isDraft?`$apply=ancestors(${_}${m},keep start)/${E}`:`$apply=${E}`,T=s?sDe(s):"",A=T?`&${T.substring(1)}`:"",C=`${u.entitySetName}?${S}${A}`;return Pr.logger.debug(`Query for odata: ${C}`),{query:C}}let c=[];u.semanticKeys.forEach(d=>{if(d.value!==void 0&&d.value!=="")if(["Edm.UUID","Edm.Guid"].includes(d.type)){let _=String(d.value).split(",").map(E=>({[d.name]:{type:"guid",value:E.trim()}}));c.push(_.length===1?_[0]:{or:_})}else if(d.type==="Edm.Boolean")c.push({[d.name]:String(d.value)==="true"});else if(d.type==="Edm.String"){let m=String(d.value).split(","),_=[];m.forEach(E=>{let S=E.trim().split("-");S.length===1?_.push({[d.name]:E.trim()}):S.length===2&&_.push({[d.name]:{ge:S[0].trim(),le:S[1].trim()}})}),c.push(_.length==1?_[0]:{or:_})}else c.push({[d.name]:d.value})});let l={};s&&Object.assign(l,s),c.length>0?Object.assign(l,{filter:c.length===1?c[0]:c,count:!0}):r&&Object.assign(l,{top:r});let f=sDe(l),p=`${u.entitySetName}${f}`;return Pr.logger.debug(`Query for odata: ${p}`),{query:p}}function jTi(e,t,r){let n=new Set(["DraftUUID","IsActiveEntity"]),i=[];for(let f of e.semanticKeys){if(f.value===void 0||f.value===""||n.has(f.name))continue;let p=f.keyName??f.name,d=String(f.value).split(",")[0].trim(),m=["Edm.UUID","Edm.Guid"].includes(f.type),_=f.type==="Edm.Boolean";i.push(`${p}=${m||_?d:`'${d}'`}`)}if(i.length===0){Pr.logger.debug(`buildNavPropHierarchyQuery: no key values available for '${e.entitySetName}', skipping nav-prop hierarchy query for '${t}'`);return}let s={DraftUUID:"00000000-0000-0000-0000-000000000000",IsActiveEntity:"true"};e.entityType?.keys?.filter(f=>f.name in s).forEach(f=>i.push(`${f.name}=${s[f.name]}`)),Pr.logger.debug(`buildNavPropHierarchyQuery: key segment for '${e.entitySetName}': (${i.join(",")})`);let a=`${`${e.entitySetName}(${i.join(",")})`}/${t}`,c=`com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=${`$root/${a}`},HierarchyQualifier='${r.qualifier}',NodeProperty='${r.nodeProperty}')`,l=`${a}?$apply=${c}`;return Pr.logger.debug(`Nav-prop hierarchy query: ${l}`),l}async function zZt(e,t,r,n,i,s=[]){let o=qTi(e,r,n,i),a=await KZt(t,o.query);for(let u of s){let c=r.find(E=>E.entity.entitySetName===u.entitySetName);if(!c){Pr.logger.debug(`fetchData: no selected entity matched hierarchy entity '${u.entitySetName}', skipping`);continue}let l=jTi(e,c.entity.entityPath,u);if(!l){Pr.logger.debug(`fetchData: could not build nav-prop hierarchy query for '${u.entitySetName}', skipping`);continue}let f=await KZt(t,l);if(!f.entityData||!a.entityData){Pr.logger.debug(`fetchData: no data returned for nav-prop hierarchy query '${u.entitySetName}', skipping merge`);continue}Pr.logger.debug(`fetchData: merging ${f.entityData.length} hierarchy records into '${c.entity.entityPath}' expanded items`);let p=c.entity.entityPath,d=u.nodeProperty.split("/")[0],m=f.entityData,_=0;for(let E of a.entityData){let S=E[p];if(Array.isArray(S))for(let T of S){let A=m.find(C=>u.entityTypeKeys.every(x=>C[x]===T[x]));A&&(T[d]=A[d],_++)}}Pr.logger.debug(`fetchData: patched '${d}' onto ${_} expanded '${p}' records`)}return{odataResult:a}}async function KZt(e,t){try{Pr.logger.info(`OData query request: ${encodeURI(e.defaults.baseURL+t).replaceAll("'","%27")}`),Pr.logger.debug(`OData query request headers: ${JSON.stringify(e.defaults.headers)}`);let r=await e.get(t),n=r?.data?.match(/"@odata\.count":(\d+)/)?.[1];return Pr.logger.info(`OData query records count: ${n}`),{entityData:r?.odata()}}catch(r){let n=Kt("errors.odataQueryError",{error:r});return Pr.logger.error(n),{error:n}}}var _c=class e{static externalServiceRequestCache={};static entityTypeRefFacetCache={};static resetExternalServiceCache(t){if(t){delete e.externalServiceRequestCache[t];return}e.externalServiceRequestCache={}}static resetRefFacetCache(){e.entityTypeRefFacetCache={}}static resetServiceCaches(){e.resetExternalServiceCache(),e.resetRefFacetCache()}};async function eer(e,t,r){if(e.metadata&&t.appAccess&&e.connectedSystem&&e.servicePath&&t.appAccess&&t.referencedEntities){e.connectedSystem.serviceProvider.log=Pr.logger;let n=e.connectedSystem?.serviceProvider.service(e.servicePath);if(n){let i=Date.now();au.sendTelemetry("ODATA_DOWNLOAD_SEND_QUERY",{time:Date()});let s=t.referencedEntities.hierarchyEntities?.find(u=>u.entitySetName===t.referencedEntities.listEntity.entitySetName),o=t.referencedEntities.hierarchyEntities?.filter(u=>u.entitySetName!==t.referencedEntities.listEntity.entitySetName&&r.some(c=>c.entity.entitySetName===u.entitySetName))??[],{odataResult:a}=await zZt(t.referencedEntities.listEntity,n,r,s?void 0:1,s,o);if(a.entityData)return au.sendTelemetry("ODATA_DOWNLOAD_RECEIVED_QUERY_RESULT",{duration:`${Date.now()-i} ms`,resultSize:`${a.entityData.length} rows`}),Pr.logger.debug(`Got result rows: ${a.entityData.length}`),{odataQueryResult:a.entityData};if(a.error)return au.sendTelemetry("ODATA_DOWNLOAD_QUERY_ERRORED",{duration:`${Date.now()-i} ms`}),`${a.error}`}}return Kt("errors.dataNotFetched")}function ter(e){let t=[];return e.Facets.forEach(r=>{if(r.$Type===XU.UIAnnotationTypes.ReferenceFacet&&r.Target.type==="AnnotationPath"){let n=r.Target.value;n.lastIndexOf("/")>-1&&t.push(n.substring(0,n.lastIndexOf("/")))}else r.$Type===XU.UIAnnotationTypes.CollectionFacet&&t.push(...ter(r))}),t}function BTi(e){if(_c.entityTypeRefFacetCache[e.name])return _c.entityTypeRefFacetCache[e.name];let t=[];return e.annotations?.UI?.Facets?.forEach(r=>{if(r.$Type===XU.UIAnnotationTypes.ReferenceFacet&&r.Target?.type==="AnnotationPath"){let n=r.Target.value;n?.lastIndexOf("/")>-1&&t.push(n.substring(0,n.lastIndexOf("/")))}r.$Type===XU.UIAnnotationTypes.CollectionFacet&&t.push(...ter(r))}),_c.entityTypeRefFacetCache[e.name]=t,t??[]}function rer(e,t="",r=[],n,i){let s={},o=e.navPropEntities;if(o&&o.length>0){let a=e.entityType?BTi(e.entityType):[];for(let u of o){let c=u.entityPath,l=i??e;if(u.entityType?.name===l?.entityType?.name||t.includes(c))continue;let f=t.concat(`${t?"/":""}${c}`);u.navPropEntities&&u.navPropEntities.length>0&&Object.assign(s,rer(u,f,r,n,i??e).entitySetsFlat);let p={fullPath:f,entity:{entityPath:u.entityPath,entitySetName:u.entitySetName,defaultSelected:a.includes(u.entityPath)||!!n?.includes(f)}},d=`${f}`;r||(r=[]),r.push({name:d,value:p,checked:p.entity.defaultSelected}),s[f]=u.entitySetName}}return{entitySetsFlat:s,choices:r}}function ner(e,t){let r=t?.map(n=>{let i=n.page?.contextPath??n.page?.routePattern?.replace(":?query:","").replaceAll(/\(\{[^}]*\}\)/g,"");return i?.startsWith(`/${e.entityPath}/`)?i.replace(`/${e.entityPath}/`,""):i}).filter(n=>n!==void 0);if(e.navPropEntities){let n=rer(e,void 0,void 0,r);return n.choices.sort((i,s)=>(i.name??"").localeCompare(s.name??"")),n}}async function ier(e,t){let n=(await JZt.UI5Config.newInstance(await(0,QZt.readFile)((0,ZZt.join)(e,hQ.FileName.Ui5Yaml),"utf-8"))).getBackendConfigsFromFioriToolsProxyMiddleware()[0],i;if(n){let s=n.url;if(n.connectPath){let o=n.connectPath.startsWith("/")?n.connectPath:`/${n.connectPath}`;s=new URL(o,n.url).href}i=(0,XZt.isAppStudio)()?n?.destination:await MZt(s,n?.client)}return{servicePath:t.uri,systemName:i}}async function ser(e){let t=await(0,hQ.getSpecificationModuleFromCache)(e.app.appRoot),r=t.getApiVersion(),n=typeof r?.version=="string"?Number.parseInt(r.version,10):0;return n<24?(Pr.logger.debug(`@sap/ux-specification from module cache API version is: ${n}. API version '24' at least is required.`),Kt("prompts.appSelection.validation.specficationApiVersionOutdated",{specApiVersion:n})):t}var oer,VTi=(...e)=>new Promise(t=>{clearTimeout(oer),oer=setTimeout(async()=>t(await eer(...e)),1e3)}),Sf={appSelection:"appSelection",toggleSelection:"toggleSelection",relatedEntitySelection:"relatedEntitySelection",skipDataDownload:"skipDataDownload",updateMainServiceMetadata:"updateMainServiceMetadata"},$Ti=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,aer=["."];async function ler(e,t,r){let n=!1;if(!r.referencedEntities?.listEntity.semanticKeys.every((a,u)=>(a.name!=="IsActiveEntity"&&!n&&(n=!!a.value),a.value!==void 0&&a.value!==""||!e[`entityKeyIdx:${u}`]))||!n)return Kt("prompts.skipDataDownload.validation.keyRequired");let s=[];r.relatedEntityChoices?.choices?.length&&(s=e[Sf.relatedEntitySelection]);let o=await VTi(t,r,s);return o}function GTi(e){return _c.resetServiceCaches(),e.appAccess=void 0,e.referencedEntities=void 0,e.servicePath=void 0,e.systemName&&(e.systemName.value=void 0),e.relatedEntityChoices.choices=[],e.relatedEntityChoices.entitySetsFlat={},e}async function fer(e){let t=[],r={appAccess:void 0,referencedEntities:void 0,servicePath:void 0,systemName:{value:void 0},connectPath:{value:void 0},relatedEntityChoices:{choices:[],entitySetsFlat:{}}},n=[],i=HTi(r,n,e?.appPath),s=await(0,gQ.getSystemSelectionQuestions)({datasourceType:{includeNone:!1},systemSelection:{includeCloudFoundryAbapEnvChoice:!1,defaultChoice:r.systemName,connectPath:r.connectPath,hideNewSystem:!0},serviceSelection:{serviceFilter:n,requiredOdataVersion:gQ.OdataVersion.v4}},(0,mQ.getHostEnvironment)()!==mQ.hostEnvironment.cli,Pr.logger);s.prompts=(0,uer.withCondition)(s.prompts,()=>!!r.appAccess);let o={odata:[]},a=YTi(r,r.relatedEntityChoices),u=KTi(5,r,s.answers,o),c=WTi(r.relatedEntityChoices,s.answers,r,o);return t.push(i,...s.prompts,XTi(s.answers,r),zTi(s.answers,r),...u,a,c),{questions:t,answers:{application:r,odataQueryResult:o,odataServiceAnswers:s.answers}}}function HTi(e,t,r){return{type:"input",guiType:"folder-browser",name:Sf.appSelection,message:Kt("prompts.appSelection.message"),default:n=>r??n.appSelection??e.appAccess?.app.appRoot,guiOptions:{mandatory:!0,breadcrumb:Kt("prompts.appSelection.breadcrumb")},validate:async n=>{if(!n)return!1;if(n===e.appAccess?.app.appRoot)return!0;t.length=0,GTi(e);let i;try{i=await(0,cer.createApplicationAccess)(n)}catch(c){let l=c;return c instanceof Error&&(l=c.message),Pr.logger.error(Kt("prompts.appSelection.validation.selectedPathDoesNotContainValidApp",{error:l})),`${Kt("prompts.appSelection.validation.selectedPathDoesNotContainValidApp")}${Kt("texts.seeLogForDetails")}`}let s=i.app.services[i.app.mainService??"mainService"];if(!s?.odataVersion?.startsWith("4."))return Kt("prompts.appSelection.validation.appMainServiceOdataVersionNotSupported",{serviceOdataVersion:s.odataVersion});let o=await ser(i);if(typeof o=="string")return o;e.appAccess=i,e.specification=o;let{servicePath:a,systemName:u}=await ier(i.app.appRoot,s);return a&&(e.servicePath=a,t.push(a)),e.systemName&&(e.systemName.value=u),e.connectPath&&(e.connectPath.value=a),!0}}}function WTi(e,t,r,n){let i;return{when:async s=>e.choices.length>0,name:Sf.relatedEntitySelection,type:"checkbox",guiOptions:{applyDefaultWhenDirty:!0},message:Kt("prompts.relatedEntitySelection.message"),choices:()=>e.choices,validate:async(s,o)=>{if(e.choices.forEach(a=>{a.disabled||(a.checked=s.some(u=>u.fullPath===a.value.fullPath))}),o&&!o[Sf.skipDataDownload]?.[0]){if(i=await ler(o,t,r),typeof i=="string")return i;n.odata=i.odataQueryResult}return!0},additionalMessages:()=>{if(i&&typeof i!="string")return{message:Kt("prompts.skipDataDownload.querySuccess",{count:i.odataQueryResult.length}),severity:z1.information}}}}function YTi(e,t){let r,n,i;return{when:()=>{if((n!==e.systemName?.value||e.servicePath!==r)&&e.referencedEntities?.listEntity){let o=ner(e.referencedEntities.listEntity,e.referencedEntities.pageObjectEntities);o&&(t.choices=o.choices,Object.assign(t.entitySetsFlat,o.entitySetsFlat)),r=e.servicePath,n=e.systemName?.value}return t.choices.length>0},name:Sf.toggleSelection,type:"confirm",message:Kt("prompts.toggleSelection.message"),labelTrue:Kt("prompts.toggleSelection.labelTrue"),labelFalse:Kt("prompts.toggleSelection.labelFalse"),default:!1,validate:o=>(o!==i&&(t.choices.forEach(a=>{if(a.disabled)return;let u=a.value;a.checked=o===!1?u.entity.defaultSelected:!1}),i=o),!0)}}function KTi(e,t,r,n){let i=[],s,o=0,a=u=>({when:async()=>{let c=t.referencedEntities?.listEntity.semanticKeys[u],l=!!c?.name&&c.name!=="IsActiveEntity";return l&&u>o&&(o=u),l},name:`entityKeyIdx:${u}`,message:()=>Kt("prompts.entityKey.message",{keyName:`${t.referencedEntities?.listEntity.semanticKeys[u]?.name} (${t.referencedEntities?.listEntity.entitySetName})`}),type:"input",guiOptions:{hint:Kt("prompts.entityKey.hint")},validate:async(c,l)=>{let f=t.referencedEntities?.listEntity.semanticKeys[u];if(f&&delete f.value,aer.includes(c))return Kt("prompts.entityKey.validation.invalidKeyValueChars",{chars:aer.join()});if(c&&f)if(f.type==="Edm.Boolean")try{f.value=JSON.parse(c)}catch{return Kt("prompts.entityKey.validation.invalidBooleanValue")}else if(["Edm.UUID","Edm.Guid"].includes(f.type)){let d=c.split(",");for(let m of d)if(!$Ti.test(m.trim()))return Kt("prompts.entityKey.validation.invalidGuidValue");f.value=c.trim()}else f.value=c.trim();let p=c.split(",");if(f?.type&&!["Edm.UUID","Edm.Guid"].includes(f.type)){for(let d of p)if(d.split("-").length>2)return f&&delete f.value,Kt("prompts.entityKey.validation.invalidRangeSpecified")}if(l&&!t.relatedEntityChoices?.choices?.length&&u===o&&!l[Sf.skipDataDownload]?.[0]&&t.referencedEntities?.listEntity.semanticKeys[u]?.name){if(s=await ler(l,r,t),typeof s=="string")return s;n.odata=s.odataQueryResult}return!0}});for(let u=0;u<e;u++)i.push(a(u));return i}function zTi(e,t){return{when:()=>!!e.metadata&&!!t.servicePath,name:Sf.skipDataDownload,type:"checkbox",message:Kt("prompts.skipDataDownload.message"),guiOptions:{hint:Kt("prompts.skipDataDownload.hint")},default:!1,choices:[{name:Kt("prompts.skipDataDownload.choiceLabel"),value:"skipDownload",checked:!1}]}}function XTi(e,t){let r;return{when:async()=>t.appAccess&&t.specification&&e?.metadata?(r=await FZt(t.appAccess,t.specification,e.metadata),typeof r=="object"&&(t.referencedEntities=r),!0):!1,name:Sf.updateMainServiceMetadata,type:"confirm",message:Kt("prompts.updateMainServiceMetadata.message"),default:!1,additionalMessages:async()=>{if(typeof r=="string")return{message:r,severity:z1.error}}}}function per(e){let t=[],r=n=>[{name:`${n.entitySetName}/${n.nodeProperty}/source`,type:"list",message:`Source: ${n.entitySetName} > ${n.missingReferentialConstraints?.navPropName}`,default:!1,choices:n.entityProperties.map(i=>({name:i,value:i}))},{name:`${n.entitySetName}/${n.nodeProperty}/target`,type:"list",message:`Target: ${n.entitySetName} > ${n.missingReferentialConstraints?.navPropName}`,default:!1,choices:n.entityProperties.map(i=>({name:i,value:i}))}];return e.forEach(n=>{!n.parentProperty&&n.missingReferentialConstraints?.navPropName&&t.push(...r(n))}),t}var _er=Vr(Ty()),ver=Vr(Oy()),yer=Vr(sc()),Eer=Vr(ger()),Ser=require("node:path");function ber(e,t,r){_c.resetExternalServiceCache();let n=pAi(e,t),i=[];return{questions:[{name:"valueHelpSelection",type:"checkbox",message:Kt("prompts.valueHelpSelection.message"),choices:()=>n,validate:async o=>{if(!o||o.length===0)return _c.resetExternalServiceCache(),!0;let a=await fAi(o,r),u=(0,Eer.default)(i,a);return i.length=0,i.push(...u),await lAi(i,r),!0}}],valueHelpData:i}}async function lAi(e,t){let r=[],n={transformResponse:s=>typeof s=="string"?JSON.parse(s):s},i=e.map(async s=>{let o=s,[a]=o.path.split(";");_c.externalServiceRequestCache[a]??=[];let l=(0,_er.convert)((0,ver.parse)(s.metadata)).entitySets.map(async f=>{let p=f.name;if(_c.externalServiceRequestCache[a].includes(p))return;_c.externalServiceRequestCache[a].push(p);let d=await t.get((0,Ser.join)(o.path,p),n);o.entityData=o.entityData??[],o.entityData?.push({entitySetName:p,items:d.data.value})});await Promise.allSettled(l),o.entityData&&r.push(o)});return await Promise.allSettled(i),r}async function fAi(e,t){let r=e.flat();return await t.fetchExternalServices(r)}function pAi(e,t){let r=(0,yer.getExternalServiceReferences)(e,t,[]),n={};for(let s of r)if(s.type==="value-list"){if(PZt.includes(s.target))continue;let[o]=s.value.split(";"),a=s.target.split("/").pop();a&&(n[o]??={},n[o][a]??=[],n[o][a].push(s))}else s.type==="code-list"&&(n[s.value]??={},n[s.value]["Code list"]??=[],n[s.value]["Code list"].push(s));let i=[];for(let s of Object.values(n))for(let[o,a]of Object.entries(s)){let u=a.map(c=>{if(c.type==="value-list")return c.target.replace(/\/[^/]*$/,"");if(c.type==="code-list"&&c.collectionPath)return c.collectionPath}).filter(c=>c!==void 0);i.push({name:`${o} (${u.join()})`,value:a})}return i.sort((s,o)=>s.name.localeCompare(o.name))}var Cer=Vr(_Y());var Pr=class e extends xer.default{vscode;appWizard;static _logger=Dh.DefaultLogger;generatorVersion=this.rootGeneratorVersion();prompts;setPromptsCallback;state={};constructor(t,r){super(t,{...r,skipInstall:!0},{unique:"namespace"}),(0,Dh.setYeomanEnvConflicterForce)(this.env,!0),this.options.force=!0,this.prompts=new wRe([{description:Kt("steps.odataDownloader.description"),name:Kt("steps.odataDownloader.name")},{description:Kt("steps.valueHelpSelection.description"),name:Kt("steps.valueHelpSelection.name")}]),this.setPromptsCallback=n=>{this.prompts&&this.prompts.setCallback(n)},typeof r.appWizard?.setHeaderTitle=="function"&&r.appWizard.setHeaderTitle(Kt("texts.generatorTitle"),`${this.rootGeneratorName()}@${this.rootGeneratorVersion()}`)}static get logger(){return e._logger}async initializing(){await bxe(),e._logger=this._configureLogging(this.options.logLevel,this.options.logger,this.options.vscode),await au.initTelemetrySettings(),au.sendTelemetry("ODATA_DOWNLOADER_STARTED",{startUpTime:Date()})}async prompting(){try{let{answers:{application:t,odataQueryResult:r,odataServiceAnswers:n},questions:i}=await fer(this.options?.data),s=await this.prompt(i);if(this.state.entityOData=r.odata,this.state.entityPropertyToEntitySet=t.relatedEntityChoices.entitySetsFlat,this.state.appRootPath=t.appAccess?.getAppRoot(),this.state.mainServicePath=n.servicePath,this.state.mainServiceName=t.appAccess?.app.mainService,this.state.appEntities=t.referencedEntities,this.state.appRootPath){this.state.mockServerConfig=await(0,Gg.getMockServerConfig)(this.state.appRootPath);let o;this.state.mockServerConfig?.services&&(e.logger.debug(`Mock config: ${JSON.stringify(this.state.mockServerConfig)}`),o=this.state.mockServerConfig.services.find(a=>a.urlPath.replaceAll(/(^\/)|(\/$)/g,"")===this.state.mainServicePath?.replaceAll(/(^\/)|(\/$)/g,""))),this.state.mockDataRootPath=o?.mockdataPath??(0,lT.join)(Gg.DirName.Webapp,Gg.DirName.LocalService,Gg.DirName.Mockdata)}if(this.state.updateMainServiceMetadata=s[Sf.updateMainServiceMetadata],this.state.mainServiceMetadata=n.metadata,s[Sf.skipDataDownload]?.[0]||await this._promptMissingReferentialConstraints(t,s),n.servicePath&&n.metadata&&n.connectedSystem?.serviceProvider instanceof Ter.AbapServiceProvider){let{questions:o,valueHelpData:a}=ber(n.servicePath,n.metadata,n.connectedSystem?.serviceProvider);await this.prompt(o),this.state.valueHelpData=a}}catch(t){e.logger.error(t),this._exitOnError(t)}}async writing(){if(this.state.appRootPath){if(this.state.entityOData&&this.state.entityPropertyToEntitySet&&this.state.appEntities)try{let t=Date.now();au.sendTelemetry("ODATA_DOWNLOADER_WRITE_DATA_FILES_START",{time:Date()}),this.destinationRoot((0,lT.join)(this.state.appRootPath));let r=nDe(this.state.entityOData,this.state.entityPropertyToEntitySet,this.state.appEntities.listEntity.entitySetName,this.state.appEntities.hierarchyEntities);e.logger.info(Kt("info.entityFilesToBeGenerated",{entities:Object.keys(r).join(", ")}));let n=Object.entries(r);n.forEach(([i,s])=>{this.writeDestinationJSON((0,lT.join)(this.state.mockDataRootPath,`${i}.json`),s)}),this.state.appEntities.hierarchyEntities?.filter(i=>i.missingReferentialConstraints&&n.some(([s])=>s===i.entitySetName))?.forEach(i=>{let s=(0,lT.join)(this.state.mockDataRootPath,`${i.entitySetName}.js`),o=this.destinationPath(s),{navPropName:a,constraints:u}=i.missingReferentialConstraints;if(this.fs.exists(o)){let c=this.fs.read(o),l=kZt(c,a,u);l!==c?(this.writeDestination(s,l),e.logger.info(`Updated referential constraint file: ${i.entitySetName}.js`)):e.logger.debug(`Referential constraint for '${a}' already present in ${i.entitySetName}.js \u2014 skipping`)}else{let c=UZt(a,u);this.writeDestination(s,c),e.logger.info(`Written referential constraint file: ${i.entitySetName}.js`)}}),au.sendTelemetry("ODATA_DOWNLOADER_WRITE_DATA_FILES_END",{writeFileDuration:`${Date.now()-t} ms`,numberOfFiles:`${n.length}`})}catch(t){e.logger.error(t),au.sendTelemetry("ODATA_DOWNLOADER_WRITING_DATA_ERROR",{writeFileErrorTime:Date()})}else e.logger.info(Kt("info.noServiceEntityData"));if(this.state.valueHelpData?.length)try{let t=Date.now();au.sendTelemetry("ODATA_DOWNLOADER_WRITE_VALUE_HELP_FILES_START",{time:Date()});let r=(0,lT.join)(this.state.appRootPath,Gg.DirName.Webapp);if(await(0,Aer.writeExternalServiceMetadata)(this.fs,r,this.state.valueHelpData,this.state.mainServiceName,this.state.mainServicePath),this.state.mockServerConfig){let n={webappPath:r,packageJsonConfig:{skip:!0},ui5MockYamlConfig:{overwrite:!0}};n.ui5MockYamlConfig&&this.state.mainServiceName&&(n.ui5MockYamlConfig.resolveExternalServiceReferences={[this.state.mainServiceName]:!0},await(0,Cer.generateMockserverConfig)(this.state.appRootPath,n,this.fs))}au.sendTelemetry("ODATA_DOWNLOADER_WRITE_VALUE_HELP_DATA_FILES_END",{writeFileDuration:`${Date.now()-t} ms`,numberOfExternalServices:`${this.state.valueHelpData.length}`})}catch(t){e.logger.error(t),au.sendTelemetry("ODATA_DOWNLOADER_WRITING_BALUE_HELP_DATA_ERROR",{writeFileErrorTime:Date()})}else e.logger.info(Kt("info.noValueHelpData"));if(this.state.updateMainServiceMetadata&&this.state.mainServiceMetadata&&this.state.mainServiceName){let t=(0,lT.join)(this.state.appRootPath,Gg.DirName.Webapp,Gg.DirName.LocalService,this.state.mainServiceName,"metadata.xml");this.writeDestination(t,(0,Oer.default)(this.state.mainServiceMetadata,{indent:4}))}}}async _promptMissingReferentialConstraints(t,r){let n=t.referencedEntities?.listEntity.entitySetName,i=new Set([...n?[n]:[],...(r[Sf.relatedEntitySelection]??[]).map(o=>o.entity.entitySetName)]),s=t.referencedEntities?.hierarchyEntities?.filter(o=>!o.parentProperty&&o.missingReferentialConstraints&&i.has(o.entitySetName))??[];if(s.length>0){this.prompts.splice(1,0,[{name:Kt("steps.addConstraints.name"),description:Kt("steps.addConstraints.description")}]);let o=per(s),a=await this.prompt(o),u=[t.referencedEntities?.listEntity,...t.referencedEntities?.pageObjectEntities??[]];s.forEach(c=>{let l=a[`${c.entitySetName}/${c.nodeProperty}/source`],f=a[`${c.entitySetName}/${c.nodeProperty}/target`];if(l&&f){c.missingReferentialConstraints.constraints=[{sourceProperty:l,targetProperty:f}],c.parentProperty=l;let p=u.find(d=>d?.entitySetName===c.entitySetName)?.entityType;c.parentPropertyType=p?.entityProperties.find(d=>d.name===l)?.type??"Edm.String"}})}}_exitOnError(t){throw(0,Dh.getHostEnvironment)()!==Dh.hostEnvironment.cli&&this.appWizard?.showError(t,kk.notification),new Error(t)}_configureLogging(t,r,n){let i=new Dh.LogWrapper(this.rootGeneratorName(),this.log,t,r,n);return i.info(Kt("info.loggingInitialised",{logLevel:i.getLogLevel()})),i}};
|
|
754
|
+
${s}${e.slice(o)}`:e}var XZt=Vr(vo()),hQ=Vr(bs()),JZt=Vr(Xv()),XU=Vr(qZt()),QZt=require("node:fs/promises"),ZZt=require("node:path");var N1=Vr(bw()),BZt=Vr(vo()),VZt=require("node:crypto"),$Zt=Vr(kW());var jZt="0.1.1";var CTi="@sap-ux/odata-download-sub-generator",wTi="0a65e45d-6bf4-421d-b845-61e888c50e9e",au=class{static _telemetryData;static _sessionId;static async initTelemetrySettings(t){this._sessionId=(0,VZt.randomUUID)(),Pr.logger.info(`Telemetry session initialized with ID: ${this._sessionId}`);let r={consumerModule:{name:CTi,version:jZt},watchTelemetrySettingStore:!1,internalFeature:!0,resourceId:wTi,...t};try{await(0,N1.initTelemetrySettings)(r)}catch(n){Pr.logger.error(`Error initializing telemetry settings: ${n}`)}}static createTelemetryData(t){if(!this._telemetryData){let r=Kt("telemetry.unknownOs");try{r=(0,$Zt.default)()}catch{}this._telemetryData={Platform:(0,BZt.isAppStudio)()?"SBAS":"VSCode",OperatingSystem:r,SessionId:this._sessionId}}return this._telemetryData=Object.assign(this._telemetryData,t),this._telemetryData}static prepareTelemetryEvent(t,r){return{eventName:t,properties:r,measurements:{}}}static async sendTelemetry(t,r){let n=this.createTelemetryData(r),i=this.prepareTelemetryEvent(t,n);await N1.ClientFactory.getTelemetryClient().reportEvent(i,N1.SampleRate.NoSampling)}};var PTi=["eq","ne","gt","ge","lt","le"],fQ=["and","or","not"],DTi=["any","all"],NTi=["startswith","endswith","contains","matchespattern"],RTi=["expand","levels","select","skip","top","count","orderby","filter"],GZt=/\((.*)\)/,HZt=/(?!indexof)\((\w+)\)/;var $g="";function sDe({select:e,search:t,skiptoken:r,format:n,top:i,skip:s,filter:o,transform:a,orderBy:u,key:c,count:l,expand:f,action:p,func:d}={}){let m="",_=[],E={};if(c!=null&&(m+=`(${Ph(c,_)})`),(o||typeof l=="object")&&(E.$filter=dQ(typeof l=="object"?l:o,_)),a&&(E.$apply=YZt(a)),f&&(E.$expand=pQ(f)),u&&(E.$orderby=oDe(u)),l&&(typeof l=="boolean"?E.$count=!0:m+="/$count"),typeof i=="number"&&(E.$top=i),typeof s=="number"&&(E.$skip=s),p&&(m+=`/${p}`),d){if(typeof d=="string")m+=`/${d}`;else if(typeof d=="object"){let[S]=Object.keys(d),T=Ph(d[S],_);m+=`/${S}`,T!==""&&(m+=`(${T})`)}}return _.length>0&&Object.assign(E,_.reduce((S,T)=>Object.assign(S,{[`@${T.name}`]:Ph(T.value)}),{})),UTi(m,{$select:e,$search:t,$skiptoken:r,$format:n,...E})}function iDe(e,t,r=[]){return`${e} eq ${Ph(t,r)}`}function dQ(e={},t=[],r=""){return(Array.isArray(e)?e:[e]).reduce((s,o)=>{if(o){let a=n(o,t,r);a&&s.push(a)}return s},[]).join(" and ");function n(s={},o=[],a=""){let u="";return typeof s=="string"?u=s:s&&typeof s=="object"&&(u=Object.keys(s).reduce((c,l)=>{let f=s[l];if(f===void 0)return c;let p="";if(a?l===$g?p=a:HZt.test(l)?p=l.replace(HZt,(d,m)=>m.trim()===$g?`(${a})`:`(${a}/${m.trim()})`):GZt.test(l)?p=l.replace(GZt,(d,m)=>m.trim()===$g?`(${a})`:`(${a}/${m.trim()})`):p=`${a}/${l}`:p=l,l===$g&&Array.isArray(f))return c.concat(f.map(d=>iDe(p,d)));if(["number","string","boolean"].indexOf(typeof f)!==-1||f instanceof Date||f===null)c.push(iDe(p,f,o));else if(Array.isArray(f)){let d=l,m=f.map(_=>dQ(_,o,a)).filter(_=>_).map(_=>fQ.indexOf(d)!==-1?`(${_})`:_);m.length&&(fQ.indexOf(d)!==-1?m.length&&(d==="not"?c.push(WZt(m)):c.push(`(${m.join(` ${d} `)})`)):c.push(m.join(` ${d} `)))}else if(fQ.indexOf(p)!==-1){let d=p,m=Object.keys(f).map(_=>n({[_]:f[_]}));m.length&&(d==="not"?c.push(WZt(m)):c.push(`(${m.join(` ${d} `)})`))}else if(typeof f=="object")"type"in f?c.push(iDe(p,f,o)):Object.keys(f).forEach(d=>{if(f[d]!==void 0)if(PTi.indexOf(d)!==-1)c.push(`${p} ${d} ${Ph(f[d],o)}`);else if(fQ.indexOf(d)!==-1)Array.isArray(f[d])?c.push(f[d].map(m=>"("+n(m,o,p)+")").join(` ${d} `)):c.push("("+n(f[d],o,p)+")");else if(DTi.indexOf(d)!==-1){let m=i(l.toLowerCase(),f[d],d,p);m&&c.push(m)}else if(d==="has")c.push(`${p} ${d} ${Ph(f[d],o)}`);else if(d==="in"){let m=Array.isArray(f[d])?f[d]:f[d].value.map(_=>({type:f[d].type,value:_}));c.push(p+" in ("+m.map(_=>Ph(_,o)).join(",")+")")}else if(NTi.indexOf(d)!==-1)c.push(`${d}(${p},${Ph(f[d],o)})`);else{let m=n({[d]:f[d]},o,p);m&&c.push(m)}});else throw new Error(`Unexpected value type: ${f}`);return c},[]).join(" and ")),u}function i(s,o,a,u){let c="";if(typeof o=="string"||o instanceof String)c=ITi(s,o,a,u);else if(o){let l=Array.isArray(o)?o.reduce((p,d)=>d.hasOwnProperty($g)?(p.hasOwnProperty($g)||(p[$g]=[]),p[$g].push(d[$g]),p):{...p,...d},{}):o,f=n(l,t,s);c=`${u}/${a}(${f?`${s}:${f}`:""})`}return c}}function ITi(e,t,r,n){let i=r=="all"?"ne":"eq";return`${n}/${r}(${e}: ${e} ${i} '${t}')`}function MTi(e){return e=e.replace(/%/g,"%25"),e=e.replace(/\+/g,"%2B"),e=e.replace(/\//g,"%2F"),e=e.replace(/\?/g,"%3F"),e=e.replace(/#/g,"%23"),e=e.replace(/&/g,"%26"),e=e.replace(/'/g,"''"),e}function Ph(e,t){if(typeof e=="string")return`'${MTi(e)}'`;if(e instanceof Date)return e.toISOString();if(typeof e=="number")return e;if(Array.isArray(e))return`[${e.map(r=>Ph(r)).join(",")}]`;if(e===null)return e;if(typeof e=="object")switch(e.type){case"raw":case"guid":return e.value;case"duration":return`duration'${e.value}'`;case"binary":return`binary'${e.value}'`;case"alias":return Array.isArray(t)&&t.push(e),`@${e.name}`;case"json":return escape(JSON.stringify(e.value));case"decimal":return`${e.value}M`;default:return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,n])=>`${r}=${Ph(n,t)}`).join(",")}return e}function pQ(e){if(typeof e=="number")return e;if(typeof e=="string")return e.indexOf("/")===-1?e:e.split("/").reverse().reduce((t,r,n,i)=>n===0?`$expand=${r}`:n===i.length-1?`${r}(${t})`:`$expand=${r}(${t})`,"");if(Array.isArray(e))return`${e.map(t=>pQ(t)).join(",")}`;if(typeof e=="object"){let t=Object.keys(e);return t.some(r=>RTi.indexOf(r.toLowerCase())!==-1)?t.map(r=>{let n;switch(r){case"filter":n=dQ(e[r]);break;case"orderBy":n=oDe(e[r]);break;case"levels":case"count":case"skip":case"top":n=`${e[r]}`;break;default:n=pQ(e[r])}return`$${r.toLowerCase()}=${n}`}).join(";"):t.map(r=>{let n=pQ(e[r]);return n?`${r}(${n})`:r}).join(",")}return""}function YZt(e){return(Array.isArray(e)?e:[e]).reduce((t,r)=>{for(let n of Object.keys(r))switch(n){case"aggregate":{let i=r[n];i&&t.push(`aggregate(${LTi(i)})`);break}case"filter":{let i=r[n];if(i){let s=dQ(i);s&&t.push(`filter(${s})`)}break}case"groupBy":{let i=r[n];i&&t.push(`groupby(${FTi(i)})`);break}default:throw new Error(`Unsupported transform: ${n}`)}return t},[]).join("/")||void 0}function LTi(e){return(Array.isArray(e)?e:[e]).map(t=>typeof t=="string"?t:Object.keys(t).map(r=>{let n=t[r];if(!n.with&&n.as)return`${r} as ${n.as}`;if(!n.with)throw new Error(`'with' property required for '${r}'`);if(!n.as)throw new Error(`'as' property required for '${r}'`);return`${r} with ${n.with} as ${n.as}`})).join(",")}function FTi(e){if(!e.properties)throw new Error("'properties' property required for groupBy");let t=`(${e.properties.join(",")})`;return e.transform&&(t+=`,${YZt(e.transform)}`),t}function oDe(e,t=""){return Array.isArray(e)?e.map(r=>Array.isArray(r)&&r.length===2&&["asc","desc"].indexOf(r[1])!==-1?r.join(" "):r).map(r=>`${t}${String(r)}`).join(","):typeof e=="object"?Object.entries(e).map(([r,n])=>oDe(n,`${r}/`)).map(r=>`${t}${r}`).join(","):`${t}${String(e)}`}function UTi(e,t){let r=Object.getOwnPropertyNames(t).filter(n=>t[n]!==void 0&&t[n]!=="").map(n=>`${n}=${t[n]}`);return r.length?`${e}?${r.join("&")}`:e}function WZt(e){return`not (${e.join(" and ")})`}function kTi(e){let t=[];return{expands:e.reduce((n,{entityPath:i})=>{let s=i.split("/"),o=n;return s.forEach((a,u)=>{o.expand||(o.expand={}),o.expand[a]??=u===s.length-1?{}:{expand:{}},o=o.expand[a],t.includes(a)||t.push(a)}),n},{expand:{}}),entityPathParts:t}}function qTi(e,t,r=1,n){let i=t?.map(d=>({entityPath:d.fullPath,entitySetName:d.entity.entitySetName})),{expands:s,entityPathParts:o}=kTi(i),a=o.map(d=>t.find(_=>d===_.entity.entityPath?_.entity.entitySetName:void 0)?.entity.entitySetName).filter(d=>d!==void 0);Pr.logger.info(Kt("info.entityFilesToBeGenerated",{entities:a.join(", ")}));let u=e;if(n){let d=[];u.semanticKeys.forEach(x=>{if(x.value!==void 0&&x.value!=="")if(x.type==="Edm.Boolean")d.push(`${x.name} eq ${x.value}`);else{let F=String(x.value).split(","),q=["Edm.UUID","Edm.Guid"].includes(x.type),N=X=>q?X.trim():`'${X.trim()}'`;if(F.length===1)d.push(`${x.name} eq ${N(F[0])}`);else{let X=F.map(oe=>`${x.name} eq ${N(oe)}`);d.push(`(${X.join(" or ")})`)}}});let m=d.length>0?`,filter(${d.join(" and ")})`:"",_=`$root/${u.entitySetName},${n.qualifier},${n.nodeProperty}`,E=`com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=$root/${u.entitySetName},HierarchyQualifier='${n.qualifier}',NodeProperty='${n.nodeProperty}')`,S=n.isDraft?`$apply=ancestors(${_}${m},keep start)/${E}`:`$apply=${E}`,T=s?sDe(s):"",A=T?`&${T.substring(1)}`:"",C=`${u.entitySetName}?${S}${A}`;return Pr.logger.debug(`Query for odata: ${C}`),{query:C}}let c=[];u.semanticKeys.forEach(d=>{if(d.value!==void 0&&d.value!=="")if(["Edm.UUID","Edm.Guid"].includes(d.type)){let _=String(d.value).split(",").map(E=>({[d.name]:{type:"guid",value:E.trim()}}));c.push(_.length===1?_[0]:{or:_})}else if(d.type==="Edm.Boolean")c.push({[d.name]:String(d.value)==="true"});else if(d.type==="Edm.String"){let m=String(d.value).split(","),_=[];m.forEach(E=>{let S=E.trim().split("-");S.length===1?_.push({[d.name]:E.trim()}):S.length===2&&_.push({[d.name]:{ge:S[0].trim(),le:S[1].trim()}})}),c.push(_.length==1?_[0]:{or:_})}else c.push({[d.name]:d.value})});let l={};s&&Object.assign(l,s),c.length>0?Object.assign(l,{filter:c.length===1?c[0]:c,count:!0}):r&&Object.assign(l,{top:r});let f=sDe(l),p=`${u.entitySetName}${f}`;return Pr.logger.debug(`Query for odata: ${p}`),{query:p}}function jTi(e,t,r){let n=new Set(["DraftUUID","IsActiveEntity"]),i=[];for(let f of e.semanticKeys){if(f.value===void 0||f.value===""||n.has(f.name))continue;let p=f.keyName??f.name,d=String(f.value).split(",")[0].trim(),m=["Edm.UUID","Edm.Guid"].includes(f.type),_=f.type==="Edm.Boolean";i.push(`${p}=${m||_?d:`'${d}'`}`)}if(i.length===0){Pr.logger.debug(`buildNavPropHierarchyQuery: no key values available for '${e.entitySetName}', skipping nav-prop hierarchy query for '${t}'`);return}let s={DraftUUID:"00000000-0000-0000-0000-000000000000",IsActiveEntity:"true"};e.entityType?.keys?.filter(f=>f.name in s).forEach(f=>i.push(`${f.name}=${s[f.name]}`)),Pr.logger.debug(`buildNavPropHierarchyQuery: key segment for '${e.entitySetName}': (${i.join(",")})`);let a=`${`${e.entitySetName}(${i.join(",")})`}/${t}`,c=`com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=${`$root/${a}`},HierarchyQualifier='${r.qualifier}',NodeProperty='${r.nodeProperty}')`,l=`${a}?$apply=${c}`;return Pr.logger.debug(`Nav-prop hierarchy query: ${l}`),l}async function zZt(e,t,r,n,i,s=[]){let o=qTi(e,r,n,i),a=await KZt(t,o.query);for(let u of s){let c=r.find(E=>E.entity.entitySetName===u.entitySetName);if(!c){Pr.logger.debug(`fetchData: no selected entity matched hierarchy entity '${u.entitySetName}', skipping`);continue}let l=jTi(e,c.entity.entityPath,u);if(!l){Pr.logger.debug(`fetchData: could not build nav-prop hierarchy query for '${u.entitySetName}', skipping`);continue}let f=await KZt(t,l);if(!f.entityData||!a.entityData){Pr.logger.debug(`fetchData: no data returned for nav-prop hierarchy query '${u.entitySetName}', skipping merge`);continue}Pr.logger.debug(`fetchData: merging ${f.entityData.length} hierarchy records into '${c.entity.entityPath}' expanded items`);let p=c.entity.entityPath,d=u.nodeProperty.split("/")[0],m=f.entityData,_=0;for(let E of a.entityData){let S=E[p];if(Array.isArray(S))for(let T of S){let A=m.find(C=>u.entityTypeKeys.every(x=>C[x]===T[x]));A&&(T[d]=A[d],_++)}}Pr.logger.debug(`fetchData: patched '${d}' onto ${_} expanded '${p}' records`)}return{odataResult:a}}async function KZt(e,t){try{Pr.logger.info(`OData query request: ${encodeURI(e.defaults.baseURL+t).replaceAll("'","%27")}`),Pr.logger.debug(`OData query request headers: ${JSON.stringify(e.defaults.headers)}`);let r=await e.get(t),n=r?.data?.match(/"@odata\.count":(\d+)/)?.[1];return Pr.logger.info(`OData query records count: ${n}`),{entityData:r?.odata()}}catch(r){let n=Kt("errors.odataQueryError",{error:r});return Pr.logger.error(n),{error:n}}}var _c=class e{static externalServiceRequestCache={};static entityTypeRefFacetCache={};static resetExternalServiceCache(t){if(t){delete e.externalServiceRequestCache[t];return}e.externalServiceRequestCache={}}static resetRefFacetCache(){e.entityTypeRefFacetCache={}}static resetServiceCaches(){e.resetExternalServiceCache(),e.resetRefFacetCache()}};async function eer(e,t,r){if(e.metadata&&t.appAccess&&e.connectedSystem&&e.servicePath&&t.appAccess&&t.referencedEntities){e.connectedSystem.serviceProvider.log=Pr.logger;let n=e.connectedSystem?.serviceProvider.service(e.servicePath);if(n){let i=Date.now();au.sendTelemetry("ODATA_DOWNLOAD_SEND_QUERY",{time:Date()});let s=t.referencedEntities.hierarchyEntities?.find(u=>u.entitySetName===t.referencedEntities.listEntity.entitySetName),o=t.referencedEntities.hierarchyEntities?.filter(u=>u.entitySetName!==t.referencedEntities.listEntity.entitySetName&&r.some(c=>c.entity.entitySetName===u.entitySetName))??[],{odataResult:a}=await zZt(t.referencedEntities.listEntity,n,r,s?void 0:1,s,o);if(a.entityData)return au.sendTelemetry("ODATA_DOWNLOAD_RECEIVED_QUERY_RESULT",{duration:`${Date.now()-i} ms`,resultSize:`${a.entityData.length} rows`}),Pr.logger.debug(`Got result rows: ${a.entityData.length}`),{odataQueryResult:a.entityData};if(a.error)return au.sendTelemetry("ODATA_DOWNLOAD_QUERY_ERRORED",{duration:`${Date.now()-i} ms`}),`${a.error}`}}return Kt("errors.dataNotFetched")}function ter(e){let t=[];return e.Facets.forEach(r=>{if(r.$Type===XU.UIAnnotationTypes.ReferenceFacet&&r.Target.type==="AnnotationPath"){let n=r.Target.value;n.lastIndexOf("/")>-1&&t.push(n.substring(0,n.lastIndexOf("/")))}else r.$Type===XU.UIAnnotationTypes.CollectionFacet&&t.push(...ter(r))}),t}function BTi(e){if(_c.entityTypeRefFacetCache[e.name])return _c.entityTypeRefFacetCache[e.name];let t=[];return e.annotations?.UI?.Facets?.forEach(r=>{if(r.$Type===XU.UIAnnotationTypes.ReferenceFacet&&r.Target?.type==="AnnotationPath"){let n=r.Target.value;n?.lastIndexOf("/")>-1&&t.push(n.substring(0,n.lastIndexOf("/")))}r.$Type===XU.UIAnnotationTypes.CollectionFacet&&t.push(...ter(r))}),_c.entityTypeRefFacetCache[e.name]=t,t??[]}function rer(e,t="",r=[],n,i){let s={},o=e.navPropEntities;if(o&&o.length>0){let a=e.entityType?BTi(e.entityType):[];for(let u of o){let c=u.entityPath,l=i??e;if(u.entityType?.name===l?.entityType?.name||t.includes(c))continue;let f=t.concat(`${t?"/":""}${c}`);u.navPropEntities&&u.navPropEntities.length>0&&Object.assign(s,rer(u,f,r,n,i??e).entitySetsFlat);let p={fullPath:f,entity:{entityPath:u.entityPath,entitySetName:u.entitySetName,defaultSelected:a.includes(u.entityPath)||!!n?.includes(f)}},d=`${f}`;r||(r=[]),r.push({name:d,value:p,checked:p.entity.defaultSelected}),s[f]=u.entitySetName}}return{entitySetsFlat:s,choices:r}}function ner(e,t){let r=t?.map(n=>{let i=n.page?.contextPath??n.page?.routePattern?.replace(":?query:","").replaceAll(/\(\{[^}]*\}\)/g,"");return i?.startsWith(`/${e.entityPath}/`)?i.replace(`/${e.entityPath}/`,""):i}).filter(n=>n!==void 0);if(e.navPropEntities){let n=rer(e,void 0,void 0,r);return n.choices.sort((i,s)=>(i.name??"").localeCompare(s.name??"")),n}}async function ier(e,t){let n=(await JZt.UI5Config.newInstance(await(0,QZt.readFile)((0,ZZt.join)(e,hQ.FileName.Ui5Yaml),"utf-8"))).getBackendConfigsFromFioriToolsProxyMiddleware()[0],i;if(n){let s=n.url;if(n.connectPath){let o=n.connectPath.startsWith("/")?n.connectPath:`/${n.connectPath}`;s=new URL(o,n.url).href}i=(0,XZt.isAppStudio)()?n?.destination:await MZt(s,n?.client)}return{servicePath:t.uri,systemName:i}}async function ser(e){let t=await(0,hQ.getSpecificationModuleFromCache)(e.app.appRoot),r=t.getApiVersion(),n=typeof r?.version=="string"?Number.parseInt(r.version,10):0;return n<24?(Pr.logger.debug(`@sap/ux-specification from module cache API version is: ${n}. API version '24' at least is required.`),Kt("prompts.appSelection.validation.specficationApiVersionOutdated",{specApiVersion:n})):t}var oer,VTi=(...e)=>new Promise(t=>{clearTimeout(oer),oer=setTimeout(async()=>t(await eer(...e)),1e3)}),Sf={appSelection:"appSelection",toggleSelection:"toggleSelection",relatedEntitySelection:"relatedEntitySelection",skipDataDownload:"skipDataDownload",updateMainServiceMetadata:"updateMainServiceMetadata"},$Ti=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,aer=["."];async function ler(e,t,r){let n=!1;if(!r.referencedEntities?.listEntity.semanticKeys.every((a,u)=>(a.name!=="IsActiveEntity"&&!n&&(n=!!a.value),a.value!==void 0&&a.value!==""||!e[`entityKeyIdx:${u}`]))||!n)return Kt("prompts.skipDataDownload.validation.keyRequired");let s=[];r.relatedEntityChoices?.choices?.length&&(s=e[Sf.relatedEntitySelection]);let o=await VTi(t,r,s);return o}function GTi(e){return _c.resetServiceCaches(),e.appAccess=void 0,e.referencedEntities=void 0,e.servicePath=void 0,e.systemName&&(e.systemName.value=void 0),e.relatedEntityChoices.choices=[],e.relatedEntityChoices.entitySetsFlat={},e}async function fer(e){let t=[],r={appAccess:void 0,referencedEntities:void 0,servicePath:void 0,systemName:{value:void 0},connectPath:{value:void 0},relatedEntityChoices:{choices:[],entitySetsFlat:{}}},n=[],i=HTi(r,n,e?.appPath),s=await(0,gQ.getSystemSelectionQuestions)({datasourceType:{includeNone:!1},systemSelection:{includeCloudFoundryAbapEnvChoice:!1,defaultChoice:r.systemName,connectPath:r.connectPath,hideNewSystem:!0},serviceSelection:{serviceFilter:n,requiredOdataVersion:gQ.OdataVersion.v4}},(0,mQ.getHostEnvironment)()!==mQ.hostEnvironment.cli,Pr.logger);s.prompts=(0,uer.withCondition)(s.prompts,()=>!!r.appAccess);let o={odata:[]},a=YTi(r,r.relatedEntityChoices),u=KTi(5,r,s.answers,o),c=WTi(r.relatedEntityChoices,s.answers,r,o);return t.push(i,...s.prompts,XTi(s.answers,r),zTi(s.answers,r),...u,a,c),{questions:t,answers:{application:r,odataQueryResult:o,odataServiceAnswers:s.answers}}}function HTi(e,t,r){return{type:"input",guiType:"folder-browser",name:Sf.appSelection,message:Kt("prompts.appSelection.message"),default:n=>r??n.appSelection??e.appAccess?.app.appRoot,guiOptions:{mandatory:!0,breadcrumb:Kt("prompts.appSelection.breadcrumb")},validate:async n=>{if(!n)return!1;if(n===e.appAccess?.app.appRoot)return!0;t.length=0,GTi(e);let i;try{i=await(0,cer.createApplicationAccess)(n)}catch(c){let l=c;return c instanceof Error&&(l=c.message),Pr.logger.error(Kt("prompts.appSelection.validation.selectedPathDoesNotContainValidApp",{error:l})),`${Kt("prompts.appSelection.validation.selectedPathDoesNotContainValidApp")}${Kt("texts.seeLogForDetails")}`}let s=i.app.services[i.app.mainService??"mainService"];if(!s?.odataVersion?.startsWith("4."))return Kt("prompts.appSelection.validation.appMainServiceOdataVersionNotSupported",{serviceOdataVersion:s.odataVersion});let o=await ser(i);if(typeof o=="string")return o;e.appAccess=i,e.specification=o;let{servicePath:a,systemName:u}=await ier(i.app.appRoot,s);return a&&(e.servicePath=a,t.push(a)),e.systemName&&(e.systemName.value=u),e.connectPath&&(e.connectPath.value=a),!0}}}function WTi(e,t,r,n){let i;return{when:async s=>e.choices.length>0,name:Sf.relatedEntitySelection,type:"checkbox",guiOptions:{applyDefaultWhenDirty:!0},message:Kt("prompts.relatedEntitySelection.message"),choices:()=>e.choices,validate:async(s,o)=>{if(e.choices.forEach(a=>{a.disabled||(a.checked=s.some(u=>u.fullPath===a.value.fullPath))}),o&&!o[Sf.skipDataDownload]?.[0]){if(i=await ler(o,t,r),typeof i=="string")return i;n.odata=i.odataQueryResult}return!0},additionalMessages:()=>{if(i&&typeof i!="string")return{message:Kt("prompts.skipDataDownload.querySuccess",{count:i.odataQueryResult.length}),severity:z1.information}}}}function YTi(e,t){let r,n,i;return{when:()=>{if((n!==e.systemName?.value||e.servicePath!==r)&&e.referencedEntities?.listEntity){let o=ner(e.referencedEntities.listEntity,e.referencedEntities.pageObjectEntities);o&&(t.choices=o.choices,Object.assign(t.entitySetsFlat,o.entitySetsFlat)),r=e.servicePath,n=e.systemName?.value}return t.choices.length>0},name:Sf.toggleSelection,type:"confirm",message:Kt("prompts.toggleSelection.message"),labelTrue:Kt("prompts.toggleSelection.labelTrue"),labelFalse:Kt("prompts.toggleSelection.labelFalse"),default:!1,validate:o=>(o!==i&&(t.choices.forEach(a=>{if(a.disabled)return;let u=a.value;a.checked=o===!1?u.entity.defaultSelected:!1}),i=o),!0)}}function KTi(e,t,r,n){let i=[],s,o=0,a=u=>({when:async()=>{let c=t.referencedEntities?.listEntity.semanticKeys[u],l=!!c?.name&&c.name!=="IsActiveEntity";return l&&u>o&&(o=u),l},name:`entityKeyIdx:${u}`,message:()=>Kt("prompts.entityKey.message",{keyName:`${t.referencedEntities?.listEntity.semanticKeys[u]?.name} (${t.referencedEntities?.listEntity.entitySetName})`}),type:"input",guiOptions:{hint:Kt("prompts.entityKey.hint")},validate:async(c,l)=>{let f=t.referencedEntities?.listEntity.semanticKeys[u];if(f&&delete f.value,aer.includes(c))return Kt("prompts.entityKey.validation.invalidKeyValueChars",{chars:aer.join()});if(c&&f)if(f.type==="Edm.Boolean")try{f.value=JSON.parse(c)}catch{return Kt("prompts.entityKey.validation.invalidBooleanValue")}else if(["Edm.UUID","Edm.Guid"].includes(f.type)){let d=c.split(",");for(let m of d)if(!$Ti.test(m.trim()))return Kt("prompts.entityKey.validation.invalidGuidValue");f.value=c.trim()}else f.value=c.trim();let p=c.split(",");if(f?.type&&!["Edm.UUID","Edm.Guid"].includes(f.type)){for(let d of p)if(d.split("-").length>2)return f&&delete f.value,Kt("prompts.entityKey.validation.invalidRangeSpecified")}if(l&&!t.relatedEntityChoices?.choices?.length&&u===o&&!l[Sf.skipDataDownload]?.[0]&&t.referencedEntities?.listEntity.semanticKeys[u]?.name){if(s=await ler(l,r,t),typeof s=="string")return s;n.odata=s.odataQueryResult}return!0}});for(let u=0;u<e;u++)i.push(a(u));return i}function zTi(e,t){return{when:()=>!!e.metadata&&!!t.servicePath,name:Sf.skipDataDownload,type:"checkbox",message:Kt("prompts.skipDataDownload.message"),guiOptions:{hint:Kt("prompts.skipDataDownload.hint")},default:!1,choices:[{name:Kt("prompts.skipDataDownload.choiceLabel"),value:"skipDownload",checked:!1}]}}function XTi(e,t){let r;return{when:async()=>t.appAccess&&t.specification&&e?.metadata?(r=await FZt(t.appAccess,t.specification,e.metadata),typeof r=="object"&&(t.referencedEntities=r),!0):!1,name:Sf.updateMainServiceMetadata,type:"confirm",message:Kt("prompts.updateMainServiceMetadata.message"),default:!1,additionalMessages:async()=>{if(typeof r=="string")return{message:r,severity:z1.error}}}}function per(e){let t=[],r=n=>[{name:`${n.entitySetName}/${n.nodeProperty}/source`,type:"list",message:`Source: ${n.entitySetName} > ${n.missingReferentialConstraints?.navPropName}`,default:!1,choices:n.entityProperties.map(i=>({name:i,value:i}))},{name:`${n.entitySetName}/${n.nodeProperty}/target`,type:"list",message:`Target: ${n.entitySetName} > ${n.missingReferentialConstraints?.navPropName}`,default:!1,choices:n.entityProperties.map(i=>({name:i,value:i}))}];return e.forEach(n=>{!n.parentProperty&&n.missingReferentialConstraints?.navPropName&&t.push(...r(n))}),t}var _er=Vr(Ty()),ver=Vr(Oy()),yer=Vr(sc()),Eer=Vr(ger()),Ser=require("node:path");function ber(e,t,r){_c.resetExternalServiceCache();let n=pAi(e,t),i=[];return{questions:[{name:"valueHelpSelection",type:"checkbox",message:Kt("prompts.valueHelpSelection.message"),choices:()=>n,validate:async o=>{if(!o||o.length===0)return _c.resetExternalServiceCache(),!0;let a=await fAi(o,r),u=(0,Eer.default)(i,a);return i.length=0,i.push(...u),await lAi(i,r),!0}}],valueHelpData:i}}async function lAi(e,t){let r=[],n={transformResponse:s=>typeof s=="string"?JSON.parse(s):s},i=e.map(async s=>{let o=s,[a]=o.path.split(";");_c.externalServiceRequestCache[a]??=[];let l=(0,_er.convert)((0,ver.parse)(s.metadata)).entitySets.map(async f=>{let p=f.name;if(_c.externalServiceRequestCache[a].includes(p))return;_c.externalServiceRequestCache[a].push(p);let d=await t.get((0,Ser.join)(o.path,p),n);o.entityData=o.entityData??[],o.entityData?.push({entitySetName:p,items:d.data.value})});await Promise.allSettled(l),o.entityData&&r.push(o)});return await Promise.allSettled(i),r}async function fAi(e,t){let r=e.flat();return await t.fetchExternalServices(r)}function pAi(e,t){let r=(0,yer.getExternalServiceReferences)(e,t,[]),n={};for(let s of r)if(s.type==="value-list"){if(PZt.includes(s.target))continue;let[o]=s.value.split(";"),a=s.target.split("/").pop();a&&(n[o]??={},n[o][a]??=[],n[o][a].push(s))}else s.type==="code-list"&&(n[s.value]??={},n[s.value]["Code list"]??=[],n[s.value]["Code list"].push(s));let i=[];for(let s of Object.values(n))for(let[o,a]of Object.entries(s)){let u=a.map(c=>{if(c.type==="value-list")return c.target.replace(/\/[^/]*$/,"");if(c.type==="code-list"&&c.collectionPath)return c.collectionPath}).filter(c=>c!==void 0);i.push({name:`${o} (${u.join()})`,value:a})}return i.sort((s,o)=>s.name.localeCompare(o.name))}var Cer=Vr(_Y());var Pr=class e extends xer.default{vscode;appWizard;static _logger=Dh.DefaultLogger;generatorVersion=this.rootGeneratorVersion();prompts;setPromptsCallback;state={};constructor(t,r){super(t,{...r,skipInstall:!0},{unique:"namespace"}),(0,Dh.setYeomanEnvConflicterForce)(this.env,!0),this.options.force=!0,this.prompts=new wRe([{description:Kt("steps.odataDownloader.description"),name:Kt("steps.odataDownloader.name")},{description:Kt("steps.valueHelpSelection.description"),name:Kt("steps.valueHelpSelection.name")}]),this.setPromptsCallback=n=>{this.prompts&&this.prompts.setCallback(n)},typeof r.appWizard?.setHeaderTitle=="function"&&r.appWizard.setHeaderTitle(Kt("texts.generatorTitle"),`${this.rootGeneratorName()}@${this.rootGeneratorVersion()}`)}static get logger(){return e._logger}async initializing(){await bxe(),e._logger=this._configureLogging(this.options.logLevel,this.options.logger,this.options.vscode),await au.initTelemetrySettings(),au.sendTelemetry("ODATA_DOWNLOADER_STARTED",{startUpTime:Date()})}async prompting(){try{let{answers:{application:t,odataQueryResult:r,odataServiceAnswers:n},questions:i}=await fer(this.options?.data),s=await this.prompt(i);if(this.state.entityOData=r.odata,this.state.entityPropertyToEntitySet=t.relatedEntityChoices.entitySetsFlat,this.state.appRootPath=t.appAccess?.getAppRoot(),this.state.mainServicePath=n.servicePath,this.state.mainServiceName=t.appAccess?.app.mainService,this.state.appEntities=t.referencedEntities,this.state.appRootPath){this.state.mockServerConfig=await(0,Gg.getMockServerConfig)(this.state.appRootPath);let o;this.state.mockServerConfig?.services&&(e.logger.debug(`Mock config: ${JSON.stringify(this.state.mockServerConfig)}`),o=this.state.mockServerConfig.services.find(a=>a.urlPath.replaceAll(/(^\/)|(\/$)/g,"")===this.state.mainServicePath?.replaceAll(/(^\/)|(\/$)/g,""))),this.state.mockDataRootPath=o?.mockdataPath??(0,lT.join)(Gg.DirName.Webapp,Gg.DirName.LocalService,Gg.DirName.Mockdata)}if(this.state.updateMainServiceMetadata=s[Sf.updateMainServiceMetadata],this.state.mainServiceMetadata=n.metadata,s[Sf.skipDataDownload]?.[0]||await this._promptMissingReferentialConstraints(t,s),n.servicePath&&n.metadata&&n.connectedSystem?.serviceProvider instanceof Ter.AbapServiceProvider){let{questions:o,valueHelpData:a}=ber(n.servicePath,n.metadata,n.connectedSystem?.serviceProvider);await this.prompt(o),this.state.valueHelpData=a}}catch(t){e.logger.error(t),this._exitOnError(t)}}async writing(){if(this.state.appRootPath){if(this.state.entityOData&&this.state.entityPropertyToEntitySet&&this.state.appEntities)try{let t=Date.now();au.sendTelemetry("ODATA_DOWNLOADER_WRITE_DATA_FILES_START",{time:Date()}),this.destinationRoot((0,lT.join)(this.state.appRootPath));let r=nDe(this.state.entityOData,this.state.entityPropertyToEntitySet,this.state.appEntities.listEntity.entitySetName,this.state.appEntities.hierarchyEntities);e.logger.info(Kt("info.entityFilesToBeGenerated",{entities:Object.keys(r).join(", ")}));let n=Object.entries(r);n.forEach(([i,s])=>{this.writeDestinationJSON((0,lT.join)(this.state.mockDataRootPath,`${i}.json`),s)}),this.state.appEntities.hierarchyEntities?.filter(i=>i.missingReferentialConstraints&&n.some(([s])=>s===i.entitySetName))?.forEach(i=>{let s=(0,lT.join)(this.state.mockDataRootPath,`${i.entitySetName}.js`),o=this.destinationPath(s),{navPropName:a,constraints:u}=i.missingReferentialConstraints;if(this.fs.exists(o)){let c=this.fs.read(o),l=kZt(c,a,u);l!==c?(this.writeDestination(s,l),e.logger.info(`Updated referential constraint file: ${i.entitySetName}.js`)):e.logger.debug(`Referential constraint for '${a}' already present in ${i.entitySetName}.js \u2014 skipping`)}else{let c=UZt(a,u);this.writeDestination(s,c),e.logger.info(`Written referential constraint file: ${i.entitySetName}.js`)}}),au.sendTelemetry("ODATA_DOWNLOADER_WRITE_DATA_FILES_END",{writeFileDuration:`${Date.now()-t} ms`,numberOfFiles:`${n.length}`})}catch(t){e.logger.error(t),au.sendTelemetry("ODATA_DOWNLOADER_WRITING_DATA_ERROR",{writeFileErrorTime:Date()})}else e.logger.info(Kt("info.noServiceEntityData"));if(this.state.valueHelpData?.length)try{let t=Date.now();au.sendTelemetry("ODATA_DOWNLOADER_WRITE_VALUE_HELP_FILES_START",{time:Date()});let r=(0,lT.join)(this.state.appRootPath,Gg.DirName.Webapp);if(await(0,Aer.writeExternalServiceMetadata)(this.fs,r,this.state.valueHelpData,this.state.mainServiceName,this.state.mainServicePath),this.state.mockServerConfig){let n={webappPath:r,packageJsonConfig:{skip:!0},ui5MockYamlConfig:{overwrite:!0}};n.ui5MockYamlConfig&&this.state.mainServiceName&&(n.ui5MockYamlConfig.resolveExternalServiceReferences={[this.state.mainServiceName]:!0},await(0,Cer.generateMockserverConfig)(this.state.appRootPath,n,this.fs))}au.sendTelemetry("ODATA_DOWNLOADER_WRITE_VALUE_HELP_DATA_FILES_END",{writeFileDuration:`${Date.now()-t} ms`,numberOfExternalServices:`${this.state.valueHelpData.length}`})}catch(t){e.logger.error(t),au.sendTelemetry("ODATA_DOWNLOADER_WRITING_BALUE_HELP_DATA_ERROR",{writeFileErrorTime:Date()})}else e.logger.info(Kt("info.noValueHelpData"));if(this.state.updateMainServiceMetadata&&this.state.mainServiceMetadata&&this.state.mainServiceName){let t=(0,lT.join)(this.state.appRootPath,Gg.DirName.Webapp,Gg.DirName.LocalService,this.state.mainServiceName,"metadata.xml");this.writeDestination(t,(0,Oer.default)(this.state.mainServiceMetadata,{indent:4}))}}}async _promptMissingReferentialConstraints(t,r){let n=t.referencedEntities?.listEntity.entitySetName,i=new Set([...n?[n]:[],...(r[Sf.relatedEntitySelection]??[]).map(o=>o.entity.entitySetName)]),s=t.referencedEntities?.hierarchyEntities?.filter(o=>!o.parentProperty&&o.missingReferentialConstraints&&i.has(o.entitySetName))??[];if(s.length>0){this.prompts.splice(1,0,[{name:Kt("steps.addConstraints.name"),description:Kt("steps.addConstraints.description")}]);let o=per(s),a=await this.prompt(o),u=[t.referencedEntities?.listEntity,...t.referencedEntities?.pageObjectEntities??[]];s.forEach(c=>{let l=a[`${c.entitySetName}/${c.nodeProperty}/source`],f=a[`${c.entitySetName}/${c.nodeProperty}/target`];if(l&&f){c.missingReferentialConstraints.constraints=[{sourceProperty:l,targetProperty:f}],c.parentProperty=l;let p=u.find(d=>d?.entitySetName===c.entitySetName)?.entityType;c.parentPropertyType=p?.entityProperties.find(d=>d.name===l)?.type??"Edm.String"}})}}_exitOnError(t){throw(0,Dh.getHostEnvironment)()!==Dh.hostEnvironment.cli&&this.appWizard?.showError(t,kk.notification),new Error(t)}_configureLogging(t,r,n){let i=new Dh.LogWrapper(this.rootGeneratorName(),this.log,t,r,n);return i.info(Kt("info.loggingInitialised",{logLevel:i.getLogLevel()})),i}};
|
|
755
755
|
/*! Bundled license information:
|
|
756
756
|
|
|
757
757
|
mime-db/index.js:
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@sap-ux/generator-odata-downloader",
|
|
3
3
|
"displayName": "Fiori Elements Data Downloader",
|
|
4
4
|
"description": "Yeoman generator that supports download of app data, typically for mock data server use.",
|
|
5
|
-
"version": "0.1.
|
|
5
|
+
"version": "0.1.1",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
8
8
|
"url": "https://github.com/SAP/open-ux-tools.git",
|
|
@@ -24,8 +24,8 @@
|
|
|
24
24
|
"prebuilds",
|
|
25
25
|
"yeoman.png"
|
|
26
26
|
],
|
|
27
|
-
"
|
|
28
|
-
"
|
|
27
|
+
"dependencies": {},
|
|
28
|
+
"devDependencies": {
|
|
29
29
|
"@sap-devx/yeoman-ui-types": "1.23.0",
|
|
30
30
|
"@sap-ux/annotation-converter": "0.10.21",
|
|
31
31
|
"@sap-ux/edmx-parser": "0.10.0",
|
|
@@ -43,17 +43,17 @@
|
|
|
43
43
|
"rimraf": "6.1.3",
|
|
44
44
|
"yeoman-generator": "5.10.0",
|
|
45
45
|
"@sap-ux/axios-extension": "1.25.35",
|
|
46
|
-
"@sap-ux/
|
|
46
|
+
"@sap-ux/btp-utils": "1.1.15",
|
|
47
|
+
"@sap-ux/inquirer-common": "0.11.44",
|
|
47
48
|
"@sap-ux/logger": "0.8.5",
|
|
48
49
|
"@sap-ux/mockserver-config-writer": "0.9.76",
|
|
49
|
-
"@sap-ux/
|
|
50
|
-
"@sap-ux/odata-service-inquirer": "2.20.21",
|
|
51
|
-
"@sap-ux/btp-utils": "1.1.15",
|
|
50
|
+
"@sap-ux/fiori-generator-shared": "0.13.105",
|
|
52
51
|
"@sap-ux/odata-service-writer": "0.31.12",
|
|
52
|
+
"@sap-ux/odata-service-inquirer": "2.20.21",
|
|
53
|
+
"@sap-ux/project-access": "1.36.3",
|
|
53
54
|
"@sap-ux/store": "1.5.13",
|
|
54
55
|
"@sap-ux/telemetry": "0.6.104",
|
|
55
|
-
"@sap-ux/ui5-config": "0.30.4"
|
|
56
|
-
"@sap-ux/project-access": "1.36.3"
|
|
56
|
+
"@sap-ux/ui5-config": "0.30.4"
|
|
57
57
|
},
|
|
58
58
|
"engines": {
|
|
59
59
|
"node": ">=20.x"
|