@adobe/aio-commerce-lib-app 0.2.0 → 0.3.0
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/CHANGELOG.md +14 -0
- package/dist/cjs/actions/index.cjs +815 -170
- package/dist/cjs/actions/index.d.cts +2 -2
- package/dist/cjs/app-Dx0ca6oL.d.cts +181 -0
- package/dist/cjs/commands/generate/actions/templates/business-configuration/get-config-schema.js.template +63 -0
- package/dist/cjs/commands/generate/actions/templates/business-configuration/get-configuration.js.template +104 -0
- package/dist/cjs/commands/generate/actions/templates/business-configuration/get-scope-tree.js.template +69 -0
- package/dist/cjs/commands/generate/actions/templates/business-configuration/set-configuration.js.template +125 -0
- package/dist/cjs/commands/generate/actions/templates/business-configuration/set-custom-scope-tree.js.template +83 -0
- package/dist/cjs/commands/generate/actions/templates/business-configuration/sync-commerce-scopes.js.template +113 -0
- package/dist/cjs/commands/generate/actions/templates/business-configuration/unsync-commerce-scopes.js.template +56 -0
- package/dist/cjs/commands/index.cjs +1075 -119
- package/dist/cjs/config/index.cjs +20 -1
- package/dist/cjs/config/index.d.cts +532 -3
- package/dist/cjs/config-JQ_n-5Nk.cjs +565 -0
- package/dist/cjs/error-Byj1DVHZ.cjs +344 -0
- package/dist/cjs/{index-DS3IlISO.d.cts → index-C5SutkJQ.d.cts} +1 -1
- package/dist/cjs/logging-DYwr5WQk.cjs +25 -0
- package/dist/cjs/management/index.cjs +9 -1
- package/dist/cjs/management/index.d.cts +1 -1
- package/dist/cjs/management-Dm5h0E6l.cjs +1246 -0
- package/dist/es/actions/index.d.mts +2 -2
- package/dist/es/actions/index.mjs +813 -170
- package/dist/es/app-Cx1-6dn0.d.mts +181 -0
- package/dist/es/commands/generate/actions/templates/business-configuration/get-config-schema.js.template +63 -0
- package/dist/es/commands/generate/actions/templates/business-configuration/get-configuration.js.template +104 -0
- package/dist/es/commands/generate/actions/templates/business-configuration/get-scope-tree.js.template +69 -0
- package/dist/es/commands/generate/actions/templates/business-configuration/set-configuration.js.template +125 -0
- package/dist/es/commands/generate/actions/templates/business-configuration/set-custom-scope-tree.js.template +83 -0
- package/dist/es/commands/generate/actions/templates/business-configuration/sync-commerce-scopes.js.template +113 -0
- package/dist/es/commands/generate/actions/templates/business-configuration/unsync-commerce-scopes.js.template +56 -0
- package/dist/es/commands/index.mjs +1070 -119
- package/dist/es/config/index.d.mts +532 -3
- package/dist/es/config/index.mjs +4 -1
- package/dist/es/config-BSGerqCG.mjs +457 -0
- package/dist/es/error-P7JgUTds.mjs +251 -0
- package/dist/es/{index-DQepSWYP.d.mts → index-Bxr3zvCT.d.mts} +2 -2
- package/dist/es/logging-VgerMhp6.mjs +18 -0
- package/dist/es/management/index.d.mts +2 -2
- package/dist/es/management/index.mjs +3 -1
- package/dist/es/management-Y7pwEbNI.mjs +1204 -0
- package/package.json +20 -8
- package/dist/cjs/app-C4HhkXbP.d.cts +0 -451
- package/dist/cjs/error-yAk1zzvx.cjs +0 -1
- package/dist/cjs/management-CE3_DJw4.cjs +0 -2
- package/dist/cjs/parser-Dovux8ce.cjs +0 -1
- package/dist/cjs/schemas-CdaP-Exw.cjs +0 -1
- package/dist/es/app-CMpx3D7Y.d.mts +0 -451
- package/dist/es/chunk-VmiN0kV1.mjs +0 -1
- package/dist/es/error-hBHRgZ9R.mjs +0 -1
- package/dist/es/management-BM2WcbV6.mjs +0 -2
- package/dist/es/parser-DOVfvr9l.mjs +0 -1
- package/dist/es/schemas-eemlD-xS.mjs +0 -1
- /package/dist/cjs/commands/generate/actions/templates/{custom-scripts.js.template → app-management/custom-scripts.js.template} +0 -0
- /package/dist/cjs/commands/generate/actions/templates/{get-app-config.js.template → app-management/get-app-config.js.template} +0 -0
- /package/dist/cjs/commands/generate/actions/templates/{installation.js.template → app-management/installation.js.template} +0 -0
- /package/dist/es/commands/generate/actions/templates/{custom-scripts.js.template → app-management/custom-scripts.js.template} +0 -0
- /package/dist/es/commands/generate/actions/templates/{get-app-config.js.template → app-management/get-app-config.js.template} +0 -0
- /package/dist/es/commands/generate/actions/templates/{installation.js.template → app-management/installation.js.template} +0 -0
|
@@ -1,133 +1,1084 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`)}};Directives.defaultYaml={explicit:!1,version:`1.2`},Directives.defaultTags={"!!":`tag:yaml.org,2002:`},exports.Directives=Directives})),require_anchors=__commonJSMin((exports=>{var identity=require_identity(),visit=require_visit();function anchorIsValid(anchor){if(/[\x00-\x19\s,[\]{}]/.test(anchor)){let msg=`Anchor must not contain whitespace or control characters: ${JSON.stringify(anchor)}`;throw Error(msg)}return!0}function anchorNames(root){let anchors=new Set;return visit.visit(root,{Value(_key,node){node.anchor&&anchors.add(node.anchor)}}),anchors}function findNewAnchor(prefix,exclude){for(let i=1;;++i){let name=`${prefix}${i}`;if(!exclude.has(name))return name}}function createNodeAnchors(doc,prefix){let aliasObjects=[],sourceObjects=new Map,prevAnchors=null;return{onAnchor:source=>{aliasObjects.push(source),prevAnchors??=anchorNames(doc);let anchor=findNewAnchor(prefix,prevAnchors);return prevAnchors.add(anchor),anchor},setAnchors:()=>{for(let source of aliasObjects){let ref=sourceObjects.get(source);if(typeof ref==`object`&&ref.anchor&&(identity.isScalar(ref.node)||identity.isCollection(ref.node)))ref.node.anchor=ref.anchor;else{let error=Error(`Failed to resolve repeated object (this should not happen)`);throw error.source=source,error}}},sourceObjects}}exports.anchorIsValid=anchorIsValid,exports.anchorNames=anchorNames,exports.createNodeAnchors=createNodeAnchors,exports.findNewAnchor=findNewAnchor})),require_applyReviver=__commonJSMin((exports=>{function applyReviver(reviver,obj,key,val){if(val&&typeof val==`object`)if(Array.isArray(val))for(let i=0,len=val.length;i<len;++i){let v0=val[i],v1=applyReviver(reviver,val,String(i),v0);v1===void 0?delete val[i]:v1!==v0&&(val[i]=v1)}else if(val instanceof Map)for(let k of Array.from(val.keys())){let v0=val.get(k),v1=applyReviver(reviver,val,k,v0);v1===void 0?val.delete(k):v1!==v0&&val.set(k,v1)}else if(val instanceof Set)for(let v0 of Array.from(val)){let v1=applyReviver(reviver,val,v0,v0);v1===void 0?val.delete(v0):v1!==v0&&(val.delete(v0),val.add(v1))}else for(let[k,v0]of Object.entries(val)){let v1=applyReviver(reviver,val,k,v0);v1===void 0?delete val[k]:v1!==v0&&(val[k]=v1)}return reviver.call(obj,key,val)}exports.applyReviver=applyReviver})),require_toJS=__commonJSMin((exports=>{var identity=require_identity();function toJS(value,arg,ctx){if(Array.isArray(value))return value.map((v,i)=>toJS(v,String(i),ctx));if(value&&typeof value.toJSON==`function`){if(!ctx||!identity.hasAnchor(value))return value.toJSON(arg,ctx);let data={aliasCount:0,count:1,res:void 0};ctx.anchors.set(value,data),ctx.onCreate=res$1=>{data.res=res$1,delete ctx.onCreate};let res=value.toJSON(arg,ctx);return ctx.onCreate&&ctx.onCreate(res),res}return typeof value==`bigint`&&!ctx?.keep?Number(value):value}exports.toJS=toJS})),require_Node=__commonJSMin((exports=>{var applyReviver=require_applyReviver(),identity=require_identity(),toJS=require_toJS();exports.NodeBase=class{constructor(type){Object.defineProperty(this,identity.NODE_TYPE,{value:type})}clone(){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(copy.range=this.range.slice()),copy}toJS(doc,{mapAsMap,maxAliasCount,onAnchor,reviver}={}){if(!identity.isDocument(doc))throw TypeError(`A document argument is required`);let ctx={anchors:new Map,doc,keep:!0,mapAsMap:mapAsMap===!0,mapKeyWarned:!1,maxAliasCount:typeof maxAliasCount==`number`?maxAliasCount:100},res=toJS.toJS(this,``,ctx);if(typeof onAnchor==`function`)for(let{count,res:res$1}of ctx.anchors.values())onAnchor(res$1,count);return typeof reviver==`function`?applyReviver.applyReviver(reviver,{"":res},``,res):res}}})),require_Alias=__commonJSMin((exports=>{var anchors=require_anchors(),visit=require_visit(),identity=require_identity(),Node=require_Node(),toJS=require_toJS(),Alias=class extends Node.NodeBase{constructor(source){super(identity.ALIAS),this.source=source,Object.defineProperty(this,`tag`,{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(doc,ctx){let nodes;ctx?.aliasResolveCache?nodes=ctx.aliasResolveCache:(nodes=[],visit.visit(doc,{Node:(_key,node)=>{(identity.isAlias(node)||identity.hasAnchor(node))&&nodes.push(node)}}),ctx&&(ctx.aliasResolveCache=nodes));let found;for(let node of nodes){if(node===this)break;node.anchor===this.source&&(found=node)}return found}toJSON(_arg,ctx){if(!ctx)return{source:this.source};let{anchors,doc,maxAliasCount}=ctx,source=this.resolve(doc,ctx);if(!source){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(msg)}let data=anchors.get(source);if(data||=(toJS.toJS(source,null,ctx),anchors.get(source)),data?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(maxAliasCount>=0&&(data.count+=1,data.aliasCount===0&&(data.aliasCount=getAliasCount(doc,source,anchors)),data.count*data.aliasCount>maxAliasCount))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return data.res}toString(ctx,_onComment,_onChompKeep){let src=`*${this.source}`;if(ctx){if(anchors.anchorIsValid(this.source),ctx.options.verifyAliasOrder&&!ctx.anchors.has(this.source)){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(msg)}if(ctx.implicitKey)return`${src} `}return src}};function getAliasCount(doc,node,anchors){if(identity.isAlias(node)){let source=node.resolve(doc),anchor=anchors&&source&&anchors.get(source);return anchor?anchor.count*anchor.aliasCount:0}else if(identity.isCollection(node)){let count=0;for(let item of node.items){let c=getAliasCount(doc,item,anchors);c>count&&(count=c)}return count}else if(identity.isPair(node)){let kc=getAliasCount(doc,node.key,anchors),vc=getAliasCount(doc,node.value,anchors);return Math.max(kc,vc)}return 1}exports.Alias=Alias})),require_Scalar=__commonJSMin((exports=>{var identity=require_identity(),Node=require_Node(),toJS=require_toJS();let isScalarValue=value=>!value||typeof value!=`function`&&typeof value!=`object`;var Scalar=class extends Node.NodeBase{constructor(value){super(identity.SCALAR),this.value=value}toJSON(arg,ctx){return ctx?.keep?this.value:toJS.toJS(this.value,arg,ctx)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED=`BLOCK_FOLDED`,Scalar.BLOCK_LITERAL=`BLOCK_LITERAL`,Scalar.PLAIN=`PLAIN`,Scalar.QUOTE_DOUBLE=`QUOTE_DOUBLE`,Scalar.QUOTE_SINGLE=`QUOTE_SINGLE`,exports.Scalar=Scalar,exports.isScalarValue=isScalarValue})),require_createNode=__commonJSMin((exports=>{var Alias=require_Alias(),identity=require_identity(),Scalar=require_Scalar();function findTagObject(value,tagName,tags){if(tagName){let match=tags.filter(t=>t.tag===tagName),tagObj=match.find(t=>!t.format)??match[0];if(!tagObj)throw Error(`Tag ${tagName} not found`);return tagObj}return tags.find(t=>t.identify?.(value)&&!t.format)}function createNode(value,tagName,ctx){if(identity.isDocument(value)&&(value=value.contents),identity.isNode(value))return value;if(identity.isPair(value)){let map=ctx.schema[identity.MAP].createNode?.(ctx.schema,null,ctx);return map.items.push(value),map}(value instanceof String||value instanceof Number||value instanceof Boolean||typeof BigInt<`u`&&value instanceof BigInt)&&(value=value.valueOf());let{aliasDuplicateObjects,onAnchor,onTagObj,schema,sourceObjects}=ctx,ref;if(aliasDuplicateObjects&&value&&typeof value==`object`){if(ref=sourceObjects.get(value),ref)return ref.anchor??=onAnchor(value),new Alias.Alias(ref.anchor);ref={anchor:null,node:null},sourceObjects.set(value,ref)}tagName?.startsWith(`!!`)&&(tagName=`tag:yaml.org,2002:`+tagName.slice(2));let tagObj=findTagObject(value,tagName,schema.tags);if(!tagObj){if(value&&typeof value.toJSON==`function`&&(value=value.toJSON()),!value||typeof value!=`object`){let node$1=new Scalar.Scalar(value);return ref&&(ref.node=node$1),node$1}tagObj=value instanceof Map?schema[identity.MAP]:Symbol.iterator in Object(value)?schema[identity.SEQ]:schema[identity.MAP]}onTagObj&&(onTagObj(tagObj),delete ctx.onTagObj);let node=tagObj?.createNode?tagObj.createNode(ctx.schema,value,ctx):typeof tagObj?.nodeClass?.from==`function`?tagObj.nodeClass.from(ctx.schema,value,ctx):new Scalar.Scalar(value);return tagName?node.tag=tagName:tagObj.default||(node.tag=tagObj.tag),ref&&(ref.node=node),node}exports.createNode=createNode})),require_Collection=__commonJSMin((exports=>{var createNode=require_createNode(),identity=require_identity(),Node=require_Node();function collectionFromPath(schema,path,value){let v=value;for(let i=path.length-1;i>=0;--i){let k=path[i];if(typeof k==`number`&&Number.isInteger(k)&&k>=0){let a=[];a[k]=v,v=a}else v=new Map([[k,v]])}return createNode.createNode(v,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema,sourceObjects:new Map})}let isEmptyPath=path=>path==null||typeof path==`object`&&!!path[Symbol.iterator]().next().done;exports.Collection=class extends Node.NodeBase{constructor(type,schema){super(type),Object.defineProperty(this,`schema`,{value:schema,configurable:!0,enumerable:!1,writable:!0})}clone(schema){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return schema&&(copy.schema=schema),copy.items=copy.items.map(it=>identity.isNode(it)||identity.isPair(it)?it.clone(schema):it),this.range&&(copy.range=this.range.slice()),copy}addIn(path,value){if(isEmptyPath(path))this.add(value);else{let[key,...rest]=path,node=this.get(key,!0);if(identity.isCollection(node))node.addIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}deleteIn(path){let[key,...rest]=path;if(rest.length===0)return this.delete(key);let node=this.get(key,!0);if(identity.isCollection(node))return node.deleteIn(rest);throw Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}getIn(path,keepScalar){let[key,...rest]=path,node=this.get(key,!0);return rest.length===0?!keepScalar&&identity.isScalar(node)?node.value:node:identity.isCollection(node)?node.getIn(rest,keepScalar):void 0}hasAllNullValues(allowScalar){return this.items.every(node=>{if(!identity.isPair(node))return!1;let n=node.value;return n==null||allowScalar&&identity.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(path){let[key,...rest]=path;if(rest.length===0)return this.has(key);let node=this.get(key,!0);return identity.isCollection(node)?node.hasIn(rest):!1}setIn(path,value){let[key,...rest]=path;if(rest.length===0)this.set(key,value);else{let node=this.get(key,!0);if(identity.isCollection(node))node.setIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}},exports.collectionFromPath=collectionFromPath,exports.isEmptyPath=isEmptyPath})),require_stringifyComment=__commonJSMin((exports=>{let stringifyComment=str=>str.replace(/^(?!$)(?: $)?/gm,`#`);function indentComment(comment,indent){return/^\n+$/.test(comment)?comment.substring(1):indent?comment.replace(/^(?! *$)/gm,indent):comment}exports.indentComment=indentComment,exports.lineComment=(str,indent,comment)=>str.endsWith(`
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
`;return`${str}\n${indent}${end}`}else return`${start}${fcPadding}${lines.join(` `)}${fcPadding}${end}`}function addCommentBefore({indent,options:{commentString}},lines,comment,chompKeep){if(comment&&chompKeep&&(comment=comment.replace(/^\n+/,``)),comment){let ic=stringifyComment.indentComment(commentString(comment),indent);lines.push(ic.trimStart())}}exports.stringifyCollection=stringifyCollection})),require_YAMLMap=__commonJSMin((exports=>{var stringifyCollection=require_stringifyCollection(),addPairToJSMap=require_addPairToJSMap(),Collection=require_Collection(),identity=require_identity(),Pair=require_Pair(),Scalar=require_Scalar();function findPair(items,key){let k=identity.isScalar(key)?key.value:key;for(let it of items)if(identity.isPair(it)&&(it.key===key||it.key===k||identity.isScalar(it.key)&&it.key.value===k))return it}exports.YAMLMap=class extends Collection.Collection{static get tagName(){return`tag:yaml.org,2002:map`}constructor(schema){super(identity.MAP,schema),this.items=[]}static from(schema,obj,ctx){let{keepUndefined,replacer}=ctx,map=new this(schema),add=(key,value)=>{if(typeof replacer==`function`)value=replacer.call(obj,key,value);else if(Array.isArray(replacer)&&!replacer.includes(key))return;(value!==void 0||keepUndefined)&&map.items.push(Pair.createPair(key,value,ctx))};if(obj instanceof Map)for(let[key,value]of obj)add(key,value);else if(obj&&typeof obj==`object`)for(let key of Object.keys(obj))add(key,obj[key]);return typeof schema.sortMapEntries==`function`&&map.items.sort(schema.sortMapEntries),map}add(pair,overwrite){let _pair;_pair=identity.isPair(pair)?pair:!pair||typeof pair!=`object`||!(`key`in pair)?new Pair.Pair(pair,pair?.value):new Pair.Pair(pair.key,pair.value);let prev=findPair(this.items,_pair.key),sortEntries=this.schema?.sortMapEntries;if(prev){if(!overwrite)throw Error(`Key ${_pair.key} already set`);identity.isScalar(prev.value)&&Scalar.isScalarValue(_pair.value)?prev.value.value=_pair.value:prev.value=_pair.value}else if(sortEntries){let i=this.items.findIndex(item=>sortEntries(_pair,item)<0);i===-1?this.items.push(_pair):this.items.splice(i,0,_pair)}else this.items.push(_pair)}delete(key){let it=findPair(this.items,key);return it?this.items.splice(this.items.indexOf(it),1).length>0:!1}get(key,keepScalar){let node=findPair(this.items,key)?.value;return(!keepScalar&&identity.isScalar(node)?node.value:node)??void 0}has(key){return!!findPair(this.items,key)}set(key,value){this.add(new Pair.Pair(key,value),!0)}toJSON(_,ctx,Type){let map=Type?new Type:ctx?.mapAsMap?new Map:{};ctx?.onCreate&&ctx.onCreate(map);for(let item of this.items)addPairToJSMap.addPairToJSMap(ctx,map,item);return map}toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);for(let item of this.items)if(!identity.isPair(item))throw Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);return!ctx.allNullValues&&this.hasAllNullValues(!1)&&(ctx=Object.assign({},ctx,{allNullValues:!0})),stringifyCollection.stringifyCollection(this,ctx,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:ctx.indent||``,onChompKeep,onComment})}},exports.findPair=findPair})),require_map=__commonJSMin((exports=>{var identity=require_identity(),YAMLMap=require_YAMLMap();exports.map={collection:`map`,default:!0,nodeClass:YAMLMap.YAMLMap,tag:`tag:yaml.org,2002:map`,resolve(map,onError){return identity.isMap(map)||onError(`Expected a mapping for this tag`),map},createNode:(schema,obj,ctx)=>YAMLMap.YAMLMap.from(schema,obj,ctx)}})),require_YAMLSeq=__commonJSMin((exports=>{var createNode=require_createNode(),stringifyCollection=require_stringifyCollection(),Collection=require_Collection(),identity=require_identity(),Scalar=require_Scalar(),toJS=require_toJS(),YAMLSeq=class extends Collection.Collection{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(schema){super(identity.SEQ,schema),this.items=[]}add(value){this.items.push(value)}delete(key){let idx=asItemIndex(key);return typeof idx==`number`?this.items.splice(idx,1).length>0:!1}get(key,keepScalar){let idx=asItemIndex(key);if(typeof idx!=`number`)return;let it=this.items[idx];return!keepScalar&&identity.isScalar(it)?it.value:it}has(key){let idx=asItemIndex(key);return typeof idx==`number`&&idx<this.items.length}set(key,value){let idx=asItemIndex(key);if(typeof idx!=`number`)throw Error(`Expected a valid index, not ${key}.`);let prev=this.items[idx];identity.isScalar(prev)&&Scalar.isScalarValue(value)?prev.value=value:this.items[idx]=value}toJSON(_,ctx){let seq=[];ctx?.onCreate&&ctx.onCreate(seq);let i=0;for(let item of this.items)seq.push(toJS.toJS(item,String(i++),ctx));return seq}toString(ctx,onComment,onChompKeep){return ctx?stringifyCollection.stringifyCollection(this,ctx,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(ctx.indent||``)+` `,onChompKeep,onComment}):JSON.stringify(this)}static from(schema,obj,ctx){let{replacer}=ctx,seq=new this(schema);if(obj&&Symbol.iterator in Object(obj)){let i=0;for(let it of obj){if(typeof replacer==`function`){let key=obj instanceof Set?it:String(i++);it=replacer.call(obj,key,it)}seq.items.push(createNode.createNode(it,void 0,ctx))}}return seq}};function asItemIndex(key){let idx=identity.isScalar(key)?key.value:key;return idx&&typeof idx==`string`&&(idx=Number(idx)),typeof idx==`number`&&Number.isInteger(idx)&&idx>=0?idx:null}exports.YAMLSeq=YAMLSeq})),require_seq=__commonJSMin((exports=>{var identity=require_identity(),YAMLSeq=require_YAMLSeq();exports.seq={collection:`seq`,default:!0,nodeClass:YAMLSeq.YAMLSeq,tag:`tag:yaml.org,2002:seq`,resolve(seq,onError){return identity.isSeq(seq)||onError(`Expected a sequence for this tag`),seq},createNode:(schema,obj,ctx)=>YAMLSeq.YAMLSeq.from(schema,obj,ctx)}})),require_string=__commonJSMin((exports=>{var stringifyString=require_stringifyString();exports.string={identify:value=>typeof value==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:str=>str,stringify(item,ctx,onComment,onChompKeep){return ctx=Object.assign({actualString:!0},ctx),stringifyString.stringifyString(item,ctx,onComment,onChompKeep)}}})),require_null=__commonJSMin((exports=>{var Scalar=require_Scalar();let nullTag={identify:value=>value==null,createNode:()=>new Scalar.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Scalar.Scalar(null),stringify:({source},ctx)=>typeof source==`string`&&nullTag.test.test(source)?source:ctx.options.nullStr};exports.nullTag=nullTag})),require_bool$1=__commonJSMin((exports=>{var Scalar=require_Scalar();let boolTag={identify:value=>typeof value==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:str=>new Scalar.Scalar(str[0]===`t`||str[0]===`T`),stringify({source,value},ctx){return source&&boolTag.test.test(source)&&value===(source[0]===`t`||source[0]===`T`)?source:value?ctx.options.trueStr:ctx.options.falseStr}};exports.boolTag=boolTag})),require_stringifyNumber=__commonJSMin((exports=>{function stringifyNumber({format,minFractionDigits,tag,value}){if(typeof value==`bigint`)return String(value);let num=typeof value==`number`?value:Number(value);if(!isFinite(num))return isNaN(num)?`.nan`:num<0?`-.inf`:`.inf`;let n=Object.is(value,-0)?`-0`:JSON.stringify(value);if(!format&&minFractionDigits&&(!tag||tag===`tag:yaml.org,2002:float`)&&/^\d/.test(n)){let i=n.indexOf(`.`);i<0&&(i=n.length,n+=`.`);let d=minFractionDigits-(n.length-i-1);for(;d-- >0;)n+=`0`}return n}exports.stringifyNumber=stringifyNumber})),require_float$1=__commonJSMin((exports=>{var Scalar=require_Scalar(),stringifyNumber=require_stringifyNumber();let floatNaN={identify:value=>typeof value==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:str=>str.slice(-3).toLowerCase()===`nan`?NaN:str[0]===`-`?-1/0:1/0,stringify:stringifyNumber.stringifyNumber};exports.float={identify:value=>typeof value==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(str){let node=new Scalar.Scalar(parseFloat(str)),dot=str.indexOf(`.`);return dot!==-1&&str[str.length-1]===`0`&&(node.minFractionDigits=str.length-dot-1),node},stringify:stringifyNumber.stringifyNumber},exports.floatExp={identify:value=>typeof value==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:str=>parseFloat(str),stringify(node){let num=Number(node.value);return isFinite(num)?num.toExponential():stringifyNumber.stringifyNumber(node)}},exports.floatNaN=floatNaN})),require_int$1=__commonJSMin((exports=>{var stringifyNumber=require_stringifyNumber();let intIdentify=value=>typeof value==`bigint`||Number.isInteger(value),intResolve=(str,offset,radix,{intAsBigInt})=>intAsBigInt?BigInt(str):parseInt(str.substring(offset),radix);function intStringify(node,radix,prefix){let{value}=node;return intIdentify(value)&&value>=0?prefix+value.toString(radix):stringifyNumber.stringifyNumber(node)}exports.int={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(str,_onError,opt)=>intResolve(str,0,10,opt),stringify:stringifyNumber.stringifyNumber},exports.intHex={identify:value=>intIdentify(value)&&value>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(str,_onError,opt)=>intResolve(str,2,16,opt),stringify:node=>intStringify(node,16,`0x`)},exports.intOct={identify:value=>intIdentify(value)&&value>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(str,_onError,opt)=>intResolve(str,2,8,opt),stringify:node=>intStringify(node,8,`0o`)}})),require_schema$2=__commonJSMin((exports=>{var map=require_map(),_null=require_null(),seq=require_seq(),string=require_string(),bool=require_bool$1(),float=require_float$1(),int=require_int$1();exports.schema=[map.map,seq.seq,string.string,_null.nullTag,bool.boolTag,int.intOct,int.int,int.intHex,float.floatNaN,float.floatExp,float.float]})),require_schema$1=__commonJSMin((exports=>{var Scalar=require_Scalar(),map=require_map(),seq=require_seq();function intIdentify(value){return typeof value==`bigint`||Number.isInteger(value)}let stringifyJSON=({value})=>JSON.stringify(value),jsonScalars=[{identify:value=>typeof value==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:str=>str,stringify:stringifyJSON},{identify:value=>value==null,createNode:()=>new Scalar.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:stringifyJSON},{identify:value=>typeof value==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:str=>str===`true`,stringify:stringifyJSON},{identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(str,_onError,{intAsBigInt})=>intAsBigInt?BigInt(str):parseInt(str,10),stringify:({value})=>intIdentify(value)?value.toString():JSON.stringify(value)},{identify:value=>typeof value==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:str=>parseFloat(str),stringify:stringifyJSON}];exports.schema=[map.map,seq.seq].concat(jsonScalars,{default:!0,tag:``,test:/^/,resolve(str,onError){return onError(`Unresolved plain scalar ${JSON.stringify(str)}`),str}})})),require_binary=__commonJSMin((exports=>{var node_buffer=__require(`buffer`),Scalar=require_Scalar(),stringifyString=require_stringifyString();exports.binary={identify:value=>value instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(src,onError){if(typeof node_buffer.Buffer==`function`)return node_buffer.Buffer.from(src,`base64`);if(typeof atob==`function`){let str=atob(src.replace(/[\n\r]/g,``)),buffer=new Uint8Array(str.length);for(let i=0;i<str.length;++i)buffer[i]=str.charCodeAt(i);return buffer}else return onError(`This environment does not support reading binary tags; either Buffer or atob is required`),src},stringify({comment,type,value},ctx,onComment,onChompKeep){if(!value)return``;let buf=value,str;if(typeof node_buffer.Buffer==`function`)str=buf instanceof node_buffer.Buffer?buf.toString(`base64`):node_buffer.Buffer.from(buf.buffer).toString(`base64`);else if(typeof btoa==`function`){let s=``;for(let i=0;i<buf.length;++i)s+=String.fromCharCode(buf[i]);str=btoa(s)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(type??=Scalar.Scalar.BLOCK_LITERAL,type!==Scalar.Scalar.QUOTE_DOUBLE){let lineWidth=Math.max(ctx.options.lineWidth-ctx.indent.length,ctx.options.minContentWidth),n=Math.ceil(str.length/lineWidth),lines=Array(n);for(let i=0,o=0;i<n;++i,o+=lineWidth)lines[i]=str.substr(o,lineWidth);str=lines.join(type===Scalar.Scalar.BLOCK_LITERAL?`
|
|
39
|
-
`:` `)}return stringifyString.stringifyString({comment,type,value:str},ctx,onComment,onChompKeep)}}})),require_pairs=__commonJSMin((exports=>{var identity=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLSeq=require_YAMLSeq();function resolvePairs(seq,onError){if(identity.isSeq(seq))for(let i=0;i<seq.items.length;++i){let item=seq.items[i];if(!identity.isPair(item)){if(identity.isMap(item)){item.items.length>1&&onError(`Each pair must have its own sequence indicator`);let pair=item.items[0]||new Pair.Pair(new Scalar.Scalar(null));if(item.commentBefore&&(pair.key.commentBefore=pair.key.commentBefore?`${item.commentBefore}\n${pair.key.commentBefore}`:item.commentBefore),item.comment){let cn=pair.value??pair.key;cn.comment=cn.comment?`${item.comment}\n${cn.comment}`:item.comment}item=pair}seq.items[i]=identity.isPair(item)?item:new Pair.Pair(item)}}else onError(`Expected a sequence for this tag`);return seq}function createPairs(schema,iterable,ctx){let{replacer}=ctx,pairs=new YAMLSeq.YAMLSeq(schema);pairs.tag=`tag:yaml.org,2002:pairs`;let i=0;if(iterable&&Symbol.iterator in Object(iterable))for(let it of iterable){typeof replacer==`function`&&(it=replacer.call(iterable,String(i++),it));let key,value;if(Array.isArray(it))if(it.length===2)key=it[0],value=it[1];else throw TypeError(`Expected [key, value] tuple: ${it}`);else if(it&&it instanceof Object){let keys=Object.keys(it);if(keys.length===1)key=keys[0],value=it[key];else throw TypeError(`Expected tuple with one key, not ${keys.length} keys`)}else key=it;pairs.items.push(Pair.createPair(key,value,ctx))}return pairs}let pairs={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:resolvePairs,createNode:createPairs};exports.createPairs=createPairs,exports.pairs=pairs,exports.resolvePairs=resolvePairs})),require_omap=__commonJSMin((exports=>{var identity=require_identity(),toJS=require_toJS(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),pairs=require_pairs(),YAMLOMap=class YAMLOMap extends YAMLSeq.YAMLSeq{constructor(){super(),this.add=YAMLMap.YAMLMap.prototype.add.bind(this),this.delete=YAMLMap.YAMLMap.prototype.delete.bind(this),this.get=YAMLMap.YAMLMap.prototype.get.bind(this),this.has=YAMLMap.YAMLMap.prototype.has.bind(this),this.set=YAMLMap.YAMLMap.prototype.set.bind(this),this.tag=YAMLOMap.tag}toJSON(_,ctx){if(!ctx)return super.toJSON(_);let map=new Map;ctx?.onCreate&&ctx.onCreate(map);for(let pair of this.items){let key,value;if(identity.isPair(pair)?(key=toJS.toJS(pair.key,``,ctx),value=toJS.toJS(pair.value,key,ctx)):key=toJS.toJS(pair,``,ctx),map.has(key))throw Error(`Ordered maps must not include duplicate keys`);map.set(key,value)}return map}static from(schema,iterable,ctx){let pairs$1=pairs.createPairs(schema,iterable,ctx),omap=new this;return omap.items=pairs$1.items,omap}};YAMLOMap.tag=`tag:yaml.org,2002:omap`;let omap={collection:`seq`,identify:value=>value instanceof Map,nodeClass:YAMLOMap,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(seq,onError){let pairs$1=pairs.resolvePairs(seq,onError),seenKeys=[];for(let{key}of pairs$1.items)identity.isScalar(key)&&(seenKeys.includes(key.value)?onError(`Ordered maps must not include duplicate keys: ${key.value}`):seenKeys.push(key.value));return Object.assign(new YAMLOMap,pairs$1)},createNode:(schema,iterable,ctx)=>YAMLOMap.from(schema,iterable,ctx)};exports.YAMLOMap=YAMLOMap,exports.omap=omap})),require_bool=__commonJSMin((exports=>{var Scalar=require_Scalar();function boolStringify({value,source},ctx){return source&&(value?trueTag:falseTag).test.test(source)?source:value?ctx.options.trueStr:ctx.options.falseStr}let trueTag={identify:value=>value===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Scalar.Scalar(!0),stringify:boolStringify},falseTag={identify:value=>value===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Scalar.Scalar(!1),stringify:boolStringify};exports.falseTag=falseTag,exports.trueTag=trueTag})),require_float=__commonJSMin((exports=>{var Scalar=require_Scalar(),stringifyNumber=require_stringifyNumber();let floatNaN={identify:value=>typeof value==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:str=>str.slice(-3).toLowerCase()===`nan`?NaN:str[0]===`-`?-1/0:1/0,stringify:stringifyNumber.stringifyNumber};exports.float={identify:value=>typeof value==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(str){let node=new Scalar.Scalar(parseFloat(str.replace(/_/g,``))),dot=str.indexOf(`.`);if(dot!==-1){let f=str.substring(dot+1).replace(/_/g,``);f[f.length-1]===`0`&&(node.minFractionDigits=f.length)}return node},stringify:stringifyNumber.stringifyNumber},exports.floatExp={identify:value=>typeof value==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:str=>parseFloat(str.replace(/_/g,``)),stringify(node){let num=Number(node.value);return isFinite(num)?num.toExponential():stringifyNumber.stringifyNumber(node)}},exports.floatNaN=floatNaN})),require_int=__commonJSMin((exports=>{var stringifyNumber=require_stringifyNumber();let intIdentify=value=>typeof value==`bigint`||Number.isInteger(value);function intResolve(str,offset,radix,{intAsBigInt}){let sign=str[0];if((sign===`-`||sign===`+`)&&(offset+=1),str=str.substring(offset).replace(/_/g,``),intAsBigInt){switch(radix){case 2:str=`0b${str}`;break;case 8:str=`0o${str}`;break;case 16:str=`0x${str}`;break}let n$1=BigInt(str);return sign===`-`?BigInt(-1)*n$1:n$1}let n=parseInt(str,radix);return sign===`-`?-1*n:n}function intStringify(node,radix,prefix){let{value}=node;if(intIdentify(value)){let str=value.toString(radix);return value<0?`-`+prefix+str.substr(1):prefix+str}return stringifyNumber.stringifyNumber(node)}let intBin={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(str,_onError,opt)=>intResolve(str,2,2,opt),stringify:node=>intStringify(node,2,`0b`)},intOct={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(str,_onError,opt)=>intResolve(str,1,8,opt),stringify:node=>intStringify(node,8,`0`)},int={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(str,_onError,opt)=>intResolve(str,0,10,opt),stringify:stringifyNumber.stringifyNumber},intHex={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(str,_onError,opt)=>intResolve(str,2,16,opt),stringify:node=>intStringify(node,16,`0x`)};exports.int=int,exports.intBin=intBin,exports.intHex=intHex,exports.intOct=intOct})),require_set=__commonJSMin((exports=>{var identity=require_identity(),Pair=require_Pair(),YAMLMap=require_YAMLMap(),YAMLSet=class YAMLSet extends YAMLMap.YAMLMap{constructor(schema){super(schema),this.tag=YAMLSet.tag}add(key){let pair;pair=identity.isPair(key)?key:key&&typeof key==`object`&&`key`in key&&`value`in key&&key.value===null?new Pair.Pair(key.key,null):new Pair.Pair(key,null),YAMLMap.findPair(this.items,pair.key)||this.items.push(pair)}get(key,keepPair){let pair=YAMLMap.findPair(this.items,key);return!keepPair&&identity.isPair(pair)?identity.isScalar(pair.key)?pair.key.value:pair.key:pair}set(key,value){if(typeof value!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);let prev=YAMLMap.findPair(this.items,key);prev&&!value?this.items.splice(this.items.indexOf(prev),1):!prev&&value&&this.items.push(new Pair.Pair(key))}toJSON(_,ctx){return super.toJSON(_,ctx,Set)}toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},ctx,{allNullValues:!0}),onComment,onChompKeep);throw Error(`Set items must all have null values`)}static from(schema,iterable,ctx){let{replacer}=ctx,set=new this(schema);if(iterable&&Symbol.iterator in Object(iterable))for(let value of iterable)typeof replacer==`function`&&(value=replacer.call(iterable,value,value)),set.items.push(Pair.createPair(value,null,ctx));return set}};YAMLSet.tag=`tag:yaml.org,2002:set`;let set={collection:`map`,identify:value=>value instanceof Set,nodeClass:YAMLSet,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(schema,iterable,ctx)=>YAMLSet.from(schema,iterable,ctx),resolve(map,onError){if(identity.isMap(map)){if(map.hasAllNullValues(!0))return Object.assign(new YAMLSet,map);onError(`Set items must all have null values`)}else onError(`Expected a mapping for this tag`);return map}};exports.YAMLSet=YAMLSet,exports.set=set})),require_timestamp=__commonJSMin((exports=>{var stringifyNumber=require_stringifyNumber();function parseSexagesimal(str,asBigInt){let sign=str[0],parts=sign===`-`||sign===`+`?str.substring(1):str,num=n=>asBigInt?BigInt(n):Number(n),res=parts.replace(/_/g,``).split(`:`).reduce((res$1,p)=>res$1*num(60)+num(p),num(0));return sign===`-`?num(-1)*res:res}function stringifySexagesimal(node){let{value}=node,num=n=>n;if(typeof value==`bigint`)num=n=>BigInt(n);else if(isNaN(value)||!isFinite(value))return stringifyNumber.stringifyNumber(node);let sign=``;value<0&&(sign=`-`,value*=num(-1));let _60=num(60),parts=[value%_60];return value<60?parts.unshift(0):(value=(value-parts[0])/_60,parts.unshift(value%_60),value>=60&&(value=(value-parts[0])/_60,parts.unshift(value))),sign+parts.map(n=>String(n).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}let intTime={identify:value=>typeof value==`bigint`||Number.isInteger(value),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(str,_onError,{intAsBigInt})=>parseSexagesimal(str,intAsBigInt),stringify:stringifySexagesimal},floatTime={identify:value=>typeof value==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:str=>parseSexagesimal(str,!1),stringify:stringifySexagesimal},timestamp={identify:value=>value instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(str){let match=str.match(timestamp.test);if(!match)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,year,month,day,hour,minute,second]=match.map(Number),millisec=match[7]?Number((match[7]+`00`).substr(1,3)):0,date=Date.UTC(year,month-1,day,hour||0,minute||0,second||0,millisec),tz=match[8];if(tz&&tz!==`Z`){let d=parseSexagesimal(tz,!1);Math.abs(d)<30&&(d*=60),date-=6e4*d}return new Date(date)},stringify:({value})=>value?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};exports.floatTime=floatTime,exports.intTime=intTime,exports.timestamp=timestamp})),require_schema=__commonJSMin((exports=>{var map=require_map(),_null=require_null(),seq=require_seq(),string=require_string(),binary=require_binary(),bool=require_bool(),float=require_float(),int=require_int(),merge=require_merge(),omap=require_omap(),pairs=require_pairs(),set=require_set(),timestamp=require_timestamp();exports.schema=[map.map,seq.seq,string.string,_null.nullTag,bool.trueTag,bool.falseTag,int.intBin,int.intOct,int.int,int.intHex,float.floatNaN,float.floatExp,float.float,binary.binary,merge.merge,omap.omap,pairs.pairs,set.set,timestamp.intTime,timestamp.floatTime,timestamp.timestamp]})),require_tags=__commonJSMin((exports=>{var map=require_map(),_null=require_null(),seq=require_seq(),string=require_string(),bool=require_bool$1(),float=require_float$1(),int=require_int$1(),schema=require_schema$2(),schema$1=require_schema$1(),binary=require_binary(),merge=require_merge(),omap=require_omap(),pairs=require_pairs(),schema$2=require_schema(),set=require_set(),timestamp=require_timestamp();let schemas=new Map([[`core`,schema.schema],[`failsafe`,[map.map,seq.seq,string.string]],[`json`,schema$1.schema],[`yaml11`,schema$2.schema],[`yaml-1.1`,schema$2.schema]]),tagsByName={binary:binary.binary,bool:bool.boolTag,float:float.float,floatExp:float.floatExp,floatNaN:float.floatNaN,floatTime:timestamp.floatTime,int:int.int,intHex:int.intHex,intOct:int.intOct,intTime:timestamp.intTime,map:map.map,merge:merge.merge,null:_null.nullTag,omap:omap.omap,pairs:pairs.pairs,seq:seq.seq,set:set.set,timestamp:timestamp.timestamp},coreKnownTags={"tag:yaml.org,2002:binary":binary.binary,"tag:yaml.org,2002:merge":merge.merge,"tag:yaml.org,2002:omap":omap.omap,"tag:yaml.org,2002:pairs":pairs.pairs,"tag:yaml.org,2002:set":set.set,"tag:yaml.org,2002:timestamp":timestamp.timestamp};function getTags(customTags,schemaName,addMergeTag){let schemaTags=schemas.get(schemaName);if(schemaTags&&!customTags)return addMergeTag&&!schemaTags.includes(merge.merge)?schemaTags.concat(merge.merge):schemaTags.slice();let tags=schemaTags;if(!tags)if(Array.isArray(customTags))tags=[];else{let keys=Array.from(schemas.keys()).filter(key=>key!==`yaml11`).map(key=>JSON.stringify(key)).join(`, `);throw Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`)}if(Array.isArray(customTags))for(let tag of customTags)tags=tags.concat(tag);else typeof customTags==`function`&&(tags=customTags(tags.slice()));return addMergeTag&&(tags=tags.concat(merge.merge)),tags.reduce((tags$1,tag)=>{let tagObj=typeof tag==`string`?tagsByName[tag]:tag;if(!tagObj){let tagName=JSON.stringify(tag),keys=Object.keys(tagsByName).map(key=>JSON.stringify(key)).join(`, `);throw Error(`Unknown custom tag ${tagName}; use one of ${keys}`)}return tags$1.includes(tagObj)||tags$1.push(tagObj),tags$1},[])}exports.coreKnownTags=coreKnownTags,exports.getTags=getTags})),require_Schema=__commonJSMin((exports=>{var identity=require_identity(),map=require_map(),seq=require_seq(),string=require_string(),tags=require_tags();let sortMapEntriesByKey=(a,b)=>a.key<b.key?-1:a.key>b.key?1:0;exports.Schema=class Schema{constructor({compat,customTags,merge,resolveKnownTags,schema,sortMapEntries,toStringDefaults}){this.compat=Array.isArray(compat)?tags.getTags(compat,`compat`):compat?tags.getTags(null,compat):null,this.name=typeof schema==`string`&&schema||`core`,this.knownTags=resolveKnownTags?tags.coreKnownTags:{},this.tags=tags.getTags(customTags,this.name,merge),this.toStringOptions=toStringDefaults??null,Object.defineProperty(this,identity.MAP,{value:map.map}),Object.defineProperty(this,identity.SCALAR,{value:string.string}),Object.defineProperty(this,identity.SEQ,{value:seq.seq}),this.sortMapEntries=typeof sortMapEntries==`function`?sortMapEntries:sortMapEntries===!0?sortMapEntriesByKey:null}clone(){let copy=Object.create(Schema.prototype,Object.getOwnPropertyDescriptors(this));return copy.tags=this.tags.slice(),copy}}})),require_stringifyDocument=__commonJSMin((exports=>{var identity=require_identity(),stringify=require_stringify(),stringifyComment=require_stringifyComment();function stringifyDocument(doc,options){let lines=[],hasDirectives=options.directives===!0;if(options.directives!==!1&&doc.directives){let dir=doc.directives.toString(doc);dir?(lines.push(dir),hasDirectives=!0):doc.directives.docStart&&(hasDirectives=!0)}hasDirectives&&lines.push(`---`);let ctx=stringify.createStringifyContext(doc,options),{commentString}=ctx.options;if(doc.commentBefore){lines.length!==1&&lines.unshift(``);let cs=commentString(doc.commentBefore);lines.unshift(stringifyComment.indentComment(cs,``))}let chompKeep=!1,contentComment=null;if(doc.contents){if(identity.isNode(doc.contents)){if(doc.contents.spaceBefore&&hasDirectives&&lines.push(``),doc.contents.commentBefore){let cs=commentString(doc.contents.commentBefore);lines.push(stringifyComment.indentComment(cs,``))}ctx.forceBlockIndent=!!doc.comment,contentComment=doc.contents.comment}let onChompKeep=contentComment?void 0:()=>chompKeep=!0,body=stringify.stringify(doc.contents,ctx,()=>contentComment=null,onChompKeep);contentComment&&(body+=stringifyComment.lineComment(body,``,commentString(contentComment))),(body[0]===`|`||body[0]===`>`)&&lines[lines.length-1]===`---`?lines[lines.length-1]=`--- ${body}`:lines.push(body)}else lines.push(stringify.stringify(doc.contents,ctx));if(doc.directives?.docEnd)if(doc.comment){let cs=commentString(doc.comment);cs.includes(`
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
`,nl)+1}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let start=getFirstKeyStartProps(getPrevProps(parent));return start.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let start=getFirstKeyStartProps(getPrevProps(parent));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){return this.type!==`comment`||this.indent<=indent?!1:start.every(st=>st.type===`newline`||st.type===`space`)}*documentEnd(docEnd){this.type!==`doc-mode`&&(docEnd.end?docEnd.end.push(this.sourceToken):docEnd.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(token){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;case`space`:case`comment`:default:token.end?token.end.push(this.sourceToken):token.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),require_public_api=__commonJSMin((exports=>{var composer=require_composer(),Document=require_Document(),errors=require_errors(),log=require_log(),identity=require_identity(),lineCounter=require_line_counter(),parser=require_parser();function parseOptions(options){let prettyErrors=options.prettyErrors!==!1;return{lineCounter:options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null,prettyErrors}}function parseAllDocuments(source,options={}){let{lineCounter,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter?.addNewLine),composer$1=new composer.Composer(options),docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter)for(let doc of docs)doc.errors.forEach(errors.prettifyError(source,lineCounter)),doc.warnings.forEach(errors.prettifyError(source,lineCounter));return docs.length>0?docs:Object.assign([],{empty:!0},composer$1.streamInfo())}function parseDocument(source,options={}){let{lineCounter,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter?.addNewLine),composer$1=new composer.Composer(options),doc=null;for(let _doc of composer$1.compose(parser$1.parse(source),!0,source.length))if(!doc)doc=_doc;else if(doc.options.logLevel!==`silent`){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return prettyErrors&&lineCounter&&(doc.errors.forEach(errors.prettifyError(source,lineCounter)),doc.warnings.forEach(errors.prettifyError(source,lineCounter))),doc}function parse(src,reviver,options){let _reviver;typeof reviver==`function`?_reviver=reviver:options===void 0&&reviver&&typeof reviver==`object`&&(options=reviver);let doc=parseDocument(src,options);if(!doc)return null;if(doc.warnings.forEach(warning=>log.warn(doc.options.logLevel,warning)),doc.errors.length>0){if(doc.options.logLevel!==`silent`)throw doc.errors[0];doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}function stringify(value,replacer,options){let _replacer=null;if(typeof replacer==`function`||Array.isArray(replacer)?_replacer=replacer:options===void 0&&replacer&&(options=replacer),typeof options==`string`&&(options=options.length),typeof options==`number`){let indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){let{keepUndefined}=options??replacer??{};if(!keepUndefined)return}return identity.isDocument(value)&&!_replacer?value.toString(options):new Document.Document(value,_replacer,options).toString(options)}exports.parse=parse,exports.parseAllDocuments=parseAllDocuments,exports.parseDocument=parseDocument,exports.stringify=stringify})),import_dist=__commonJSMin((exports=>{var composer=require_composer(),Document=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq();require_cst();var lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit=require_visit();exports.Composer=composer.Composer,exports.Document=Document.Document,exports.Schema=Schema.Schema,exports.YAMLError=errors.YAMLError,exports.YAMLParseError=errors.YAMLParseError,exports.YAMLWarning=errors.YAMLWarning,exports.Alias=Alias.Alias,exports.isAlias=identity.isAlias,exports.isCollection=identity.isCollection,exports.isDocument=identity.isDocument,exports.isMap=identity.isMap,exports.isNode=identity.isNode,exports.isPair=identity.isPair,exports.isScalar=identity.isScalar,exports.isSeq=identity.isSeq,exports.Pair=Pair.Pair,exports.Scalar=Scalar.Scalar,exports.YAMLMap=YAMLMap.YAMLMap,exports.YAMLSeq=YAMLSeq.YAMLSeq,exports.Lexer=lexer.Lexer,exports.LineCounter=lineCounter.LineCounter,exports.Parser=parser.Parser,exports.parse=publicApi.parse,exports.parseAllDocuments=publicApi.parseAllDocuments,exports.parseDocument=publicApi.parseDocument,exports.stringify=publicApi.stringify,exports.visit=visit.visit,exports.visitAsync=visit.visitAsync}))();async function readYamlFile(path){let doc=new import_dist.Document;if(existsSync(path))try{doc=(0,import_dist.parseDocument)(await readFile(path,`utf-8`),{keepSourceTokens:!0})}catch{let file=basename(path);throw Error(`Failed to parse ${file}`)}return doc.contents===null&&(doc.contents=new import_dist.YAMLMap),doc}function getOrCreateNode(doc,path,options,typeConfig){let node=doc.getIn(path);if(node){if(!typeConfig.typeGuard(node))throw Error(`Expected ${typeConfig.typeName} at path "${path.join(`.`)}".`);return node}doc.hasIn(path)&&doc.deleteIn(path);let pair=doc.createPair(path.at(-1),typeConfig.createNode());return options.onBeforeCreate?.(pair),path.length===1?doc.add(pair):doc.addIn(path.slice(0,-1),pair),doc.getIn(path)}function getOrCreateSeq(doc,path,options){return getOrCreateNode(doc,path,options??{},{typeGuard:import_dist.isSeq,createNode:()=>new import_dist.YAMLSeq,typeName:`sequence`})}function getOrCreateMap(doc,path,options){return getOrCreateNode(doc,path,options??{},{typeGuard:import_dist.isMap,createNode:()=>new import_dist.YAMLMap,typeName:`map`})}async function createOrUpdateExtConfig(path,config,doc){let extConfigDoc=doc??new import_dist.Document({});return config.hooks??={},config.operations??={workerProcess:[]},config.runtimeManifest??={packages:{}},await buildHooks(extConfigDoc,config.hooks),buildOperations(extConfigDoc,config.operations),buildRuntimeManifest(extConfigDoc,config.runtimeManifest),await writeExtConfig(path,extConfigDoc),extConfigDoc}function buildActionDefinition(action){let actionDef=new import_dist.YAMLMap;actionDef.set(`function`,action.function),actionDef.set(`web`,action.web??`yes`),actionDef.set(`runtime`,action.runtime??`nodejs:22`),actionDef.set(`inputs`,{LOG_LEVEL:`$LOG_LEVEL`,...action.inputs??{}}),actionDef.set(`annotations`,{...action.annotations??{"require-adobe-auth":!0,final:!0}});let includes=action.include??[];if(includes.length>0){let itemSeq=new import_dist.YAMLSeq;itemSeq.flow=!0;for(let[source,target]of includes)itemSeq.items.push(source,target);let seq=new import_dist.YAMLSeq;seq.items.push(itemSeq),actionDef.set(`include`,seq)}return action.limits!==void 0&&actionDef.set(`limits`,action.limits),actionDef}function buildOperations(extConfig,operations){getOrCreateMap(extConfig,[`operations`],{onBeforeCreate:pair=>{pair.key.spaceBefore=!0}});let workerProcess=getOrCreateSeq(extConfig,[`operations`,`workerProcess`],{onBeforeCreate:pair=>{pair.key.commentBefore=` These worker processes definitions are auto-generated. Do not remove or manually edit.`}}),missingOps=(operations.workerProcess??[]).filter(op=>workerProcess.items.find(item=>(0,import_dist.isMap)(item)&&item.get(`impl`)===op.impl)===void 0);workerProcess.items.push(...missingOps.map(op=>{let map=new import_dist.YAMLMap;return map.set(`type`,op.type),map.set(`impl`,op.impl),map}))}function buildRuntimeManifest(extConfig,manifest){getOrCreateMap(extConfig,[`runtimeManifest`],{onBeforeCreate:pair=>{pair.key.spaceBefore=!0}});let packages=manifest.packages??{};getOrCreateMap(extConfig,[`runtimeManifest`,`packages`]);for(let[name,pkg]of Object.entries(packages)){let packageDef=getOrCreateMap(extConfig,[`runtimeManifest`,`packages`,name],{onBeforeCreate:pair=>{pair.key.commentBefore=` This package definition is auto-generated. Do not remove or manually edit.`}}),actions=new import_dist.YAMLMap;packageDef.set(`license`,pkg.license??`Apache-2.0`),packageDef.set(`actions`,actions);for(let[actionName,action]of Object.entries(pkg.actions??{})){let actionDef=buildActionDefinition(action);actions.set(actionName,actionDef)}}}async function buildHooks(extConfig,hooks){let generatedHooks=`[${Object.keys(hooks).join(`, `)}]`,hooksMap=getOrCreateMap(extConfig,[`hooks`],{onBeforeCreate:pair=>{pair.key.spaceBefore=!0,pair.key.commentBefore=` The ${generatedHooks} hooks are auto-generated. Do not remove or manually edit.`}}),execCommand=getExecCommand(await detectPackageManager());for(let[name,command$1]of Object.entries(hooks)){let fullCommand=`${command$1.replaceAll(`$packageExec`,execCommand)}`,prevValue=(hooksMap.get(name)??``).trim();if(prevValue.endsWith(`js`)||prevValue.endsWith(`ts`))throw Error(`Conflicting hook definition found. The "${name}" hook needs to be a command, not a script.`);prevValue!==``&&!prevValue.includes(fullCommand)?hooksMap.set(name,`${prevValue} && ${fullCommand}`):prevValue===``&&hooksMap.set(name,fullCommand)}}async function writeExtConfig(configPath,doc){await writeFile(configPath,doc.toString({indent:2,lineWidth:0,defaultStringType:`PLAIN`}),`utf-8`)}const PACKAGE_NAME=`app-management`,GENERATED_ACTIONS_PATH=`.generated/${`actions/${PACKAGE_NAME}`}`,EXTENSION_POINT_FOLDER_PATH=`src/commerce-extensibility-1`,APP_MANIFEST_FILE=`app.commerce.manifest.json`,COMMERCE_ACTION_INPUTS=Object.fromEntries([`AIO_COMMERCE_API_BASE_URL`,`AIO_COMMERCE_AUTH_IMS_CLIENT_ID`,`AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS`,`AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID`,`AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL`,`AIO_COMMERCE_AUTH_IMS_ORG_ID`,`AIO_COMMERCE_AUTH_IMS_SCOPES`].map(variable=>[variable,`$${variable}`])),CUSTOM_SCRIPTS_LOADER_PLACEHOLDER=`// {{CUSTOM_SCRIPTS_LOADER}}`,RUNTIME_ACTIONS=[{name:`get-app-config`,templateFile:`get-app-config.js.template`},{name:`installation`,templateFile:`installation.js.template`}];function createActionConfig(actionName,options={}){return{...options,function:`${GENERATED_ACTIONS_PATH}/${actionName}.js`,web:options.web??`yes`,runtime:`nodejs:22`,annotations:{"require-adobe-auth":!0,final:!0}}}const EXT_CONFIG={hooks:{"pre-app-build":`$packageExec aio-commerce-lib-app generate manifest && $packageExec aio-commerce-lib-auth sync-ims-credentials`},operations:{workerProcess:[{type:`action`,impl:`${PACKAGE_NAME}/get-app-config`},{type:`action`,impl:`${PACKAGE_NAME}/installation`}]},runtimeManifest:{packages:{[PACKAGE_NAME]:{license:`Apache-2.0`,actions:{"get-app-config":createActionConfig(`get-app-config`),installation:createActionConfig(`installation`,{inputs:{...COMMERCE_ACTION_INPUTS,LOG_LEVEL:`$LOG_LEVEL`},limits:{timeout:6e5}})}}}}},__dirname=dirname(fileURLToPath(import.meta.url));async function run$1(){try{await generateActionFiles(await loadAppManifest()),await updateExtConfig()}catch(error){consola$1.error(stringifyError(error)),process.exit(1)}}async function loadAppManifest(){let appConfig=await parseCommerceAppConfig();return consola$1.debug(`Loaded app commerce config`),appConfig}async function updateExtConfig(){consola$1.info(`Updating ext.config.yaml...`);let extConfigPath=join(await makeOutputDirFor(EXTENSION_POINT_FOLDER_PATH),`ext.config.yaml`);await createOrUpdateExtConfig(extConfigPath,EXT_CONFIG,await readYamlFile(extConfigPath)),consola$1.success(`Updated ext.config.yaml`)}async function generateActionFiles(appManifest){consola$1.start(`Generating runtime actions...`);let outputDir=await makeOutputDirFor(join(EXTENSION_POINT_FOLDER_PATH,GENERATED_ACTIONS_PATH)),templatesDir=join(__dirname,`generate/actions/templates`),outputFiles=[];for(let action of RUNTIME_ACTIONS){let template=await readFile(join(templatesDir,action.templateFile),`utf-8`);if(action.name===`installation`){let scriptsTemplate=await generateCustomScriptsTemplate(await readFile(join(templatesDir,`custom-scripts.js.template`),`utf-8`),appManifest);template=applyCustomScripts(template,scriptsTemplate)}let actionPath=join(outputDir,`${action.name}.js`);await writeFile(actionPath,template,`utf-8`),outputFiles.push(` ${relative(process.cwd(),actionPath)}`)}consola$1.success(`Generated ${RUNTIME_ACTIONS.length} action(s) in ${GENERATED_ACTIONS_PATH}`),consola$1.log.raw(formatTree(outputFiles,{color:`green`}))}function applyCustomScripts(installationTemplate,customScriptsTemplate){return customScriptsTemplate===null?(consola$1.debug(`No custom installation steps found, skipping custom-scripts.js generation...`),installationTemplate.replace(CUSTOM_SCRIPTS_LOADER_PLACEHOLDER,`// No custom installation scripts configured`)):installationTemplate.replace(CUSTOM_SCRIPTS_LOADER_PLACEHOLDER,customScriptsTemplate).replace(`const args = { appConfig };`,`const args = { appConfig, customScriptsLoader };`)}async function generateCustomScriptsTemplate(template,appManifest){let customSteps=appManifest.installation?.customInstallationSteps||[];if(customSteps.length===0)return null;let projectRoot=await getProjectRootDirectory(),installationActionDir=join(projectRoot,EXTENSION_POINT_FOLDER_PATH,GENERATED_ACTIONS_PATH),importStatements=customSteps.map((step,index)=>{let relativeImportPath=relative(installationActionDir,join(projectRoot,step.script));return relativeImportPath.startsWith(`.`)||(relativeImportPath=`./${relativeImportPath}`),relativeImportPath=relativeImportPath.replace(/\\/g,`/`),`import * as ${`customScript${index}`} from "${relativeImportPath}";`}).join(`
|
|
117
|
-
|
|
118
|
-
|
|
2
|
+
import { c as hasCustomInstallationSteps, t as stringifyError } from "../error-P7JgUTds.mjs";
|
|
3
|
+
import { t as inspect } from "../logging-VgerMhp6.mjs";
|
|
4
|
+
import { _ as readPackageJson, d as hasBusinessConfigSchema, f as detectPackageManager, g as makeOutputDirFor, h as isESM, i as validateCommerceAppConfig, m as getProjectRootDirectory, n as readCommerceAppConfig, p as getExecCommand, s as getConfigDomains, t as parseCommerceAppConfig } from "../config-BSGerqCG.mjs";
|
|
5
|
+
import { CommerceSdkValidationError } from "@adobe/aio-commerce-lib-core/error";
|
|
6
|
+
import path, { basename, dirname, join, relative, resolve } from "path";
|
|
7
|
+
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
8
|
+
import { readFile, writeFile } from "fs/promises";
|
|
9
|
+
import consola, { consola as consola$1 } from "consola";
|
|
10
|
+
import { fileURLToPath } from "url";
|
|
11
|
+
import { Document, YAMLMap, YAMLSeq, isMap, isSeq, parseDocument } from "yaml";
|
|
12
|
+
import { colorize, formatTree } from "consola/utils";
|
|
13
|
+
import { stringify } from "safe-stable-stringify";
|
|
14
|
+
import { execSync } from "child_process";
|
|
15
|
+
import config from "@adobe/aio-lib-core-config";
|
|
16
|
+
import aioIms from "@adobe/aio-lib-ims";
|
|
17
|
+
import dotenv from "dotenv";
|
|
18
|
+
import * as prettier from "prettier";
|
|
19
|
+
|
|
20
|
+
//#region ../../packages-private/scripting-utils/source/yaml/helpers.ts
|
|
21
|
+
/**
|
|
22
|
+
* Read a YAML file and return a {@link Document}
|
|
23
|
+
* @param path - The path to the YAML file
|
|
24
|
+
*/
|
|
25
|
+
async function readYamlFile(path$1) {
|
|
26
|
+
let doc = new Document();
|
|
27
|
+
if (existsSync(path$1)) try {
|
|
28
|
+
doc = parseDocument(await readFile(path$1, "utf-8"), { keepSourceTokens: true });
|
|
29
|
+
} catch (_) {
|
|
30
|
+
const file = basename(path$1);
|
|
31
|
+
throw new Error(`Failed to parse ${file}`);
|
|
32
|
+
}
|
|
33
|
+
if (doc.contents === null) doc.contents = new YAMLMap();
|
|
34
|
+
return doc;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Generic helper to get or create a YAML node at the given path
|
|
38
|
+
* @param doc - The YAML document
|
|
39
|
+
* @param path - The path to the node
|
|
40
|
+
* @param options - The options for the node
|
|
41
|
+
* @param typeConfig - Configuration for the node type
|
|
42
|
+
* @returns The existing or newly created node
|
|
43
|
+
*/
|
|
44
|
+
function getOrCreateNode(doc, path$1, options, typeConfig) {
|
|
45
|
+
const node = doc.getIn(path$1);
|
|
46
|
+
if (node) {
|
|
47
|
+
if (!typeConfig.typeGuard(node)) throw new Error(`Expected ${typeConfig.typeName} at path "${path$1.join(".")}".`);
|
|
48
|
+
return node;
|
|
49
|
+
}
|
|
50
|
+
if (doc.hasIn(path$1)) doc.deleteIn(path$1);
|
|
51
|
+
const pair = doc.createPair(path$1.at(-1), typeConfig.createNode());
|
|
52
|
+
options.onBeforeCreate?.(pair);
|
|
53
|
+
if (path$1.length === 1) doc.add(pair);
|
|
54
|
+
else doc.addIn(path$1.slice(0, -1), pair);
|
|
55
|
+
return doc.getIn(path$1);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Get or create a sequence at the given path
|
|
59
|
+
* @param doc - The YAML document
|
|
60
|
+
* @param path - The path to the sequence
|
|
61
|
+
* @param options - The options for the sequence
|
|
62
|
+
*/
|
|
63
|
+
function getOrCreateSeq(doc, path$1, options) {
|
|
64
|
+
return getOrCreateNode(doc, path$1, options ?? {}, {
|
|
65
|
+
typeGuard: isSeq,
|
|
66
|
+
createNode: () => new YAMLSeq(),
|
|
67
|
+
typeName: "sequence"
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Get or create a map at the given path
|
|
72
|
+
* @param doc - The YAML document
|
|
73
|
+
* @param path - The path to the map
|
|
74
|
+
* @param options - The options for the map
|
|
75
|
+
*/
|
|
76
|
+
function getOrCreateMap(doc, path$1, options) {
|
|
77
|
+
return getOrCreateNode(doc, path$1, options ?? {}, {
|
|
78
|
+
typeGuard: isMap,
|
|
79
|
+
createNode: () => new YAMLMap(),
|
|
80
|
+
typeName: "map"
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
//#endregion
|
|
85
|
+
//#region ../../packages-private/scripting-utils/source/yaml/codegen.ts
|
|
86
|
+
/**
|
|
87
|
+
* Create an ext.config.yaml file
|
|
88
|
+
* @param path - The path to the ext.config.yaml file
|
|
89
|
+
* @param config - The config to build
|
|
90
|
+
* @param doc - The document to modify (a new one is created if not provided)
|
|
91
|
+
*/
|
|
92
|
+
async function createOrUpdateExtConfig(path$1, config$1, doc) {
|
|
93
|
+
const extConfigDoc = doc ?? new Document({});
|
|
94
|
+
config$1.hooks ??= {};
|
|
95
|
+
config$1.operations ??= { workerProcess: [] };
|
|
96
|
+
config$1.runtimeManifest ??= { packages: {} };
|
|
97
|
+
await buildHooks(extConfigDoc, config$1.hooks);
|
|
98
|
+
buildOperations(extConfigDoc, config$1.operations);
|
|
99
|
+
buildRuntimeManifest(extConfigDoc, config$1.runtimeManifest);
|
|
100
|
+
await writeExtConfig(path$1, extConfigDoc);
|
|
101
|
+
return extConfigDoc;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Build the definition for a runtime action
|
|
105
|
+
* @param name - The name of the action
|
|
106
|
+
* @param path - The path where the action is located
|
|
107
|
+
* @param action - The action definition
|
|
108
|
+
*/
|
|
109
|
+
function buildActionDefinition(action) {
|
|
110
|
+
const actionDef = new YAMLMap();
|
|
111
|
+
const inputs = { LOG_LEVEL: "$LOG_LEVEL" };
|
|
112
|
+
actionDef.set("function", action.function);
|
|
113
|
+
actionDef.set("web", action.web ?? "yes");
|
|
114
|
+
actionDef.set("runtime", action.runtime ?? "nodejs:22");
|
|
115
|
+
actionDef.set("inputs", {
|
|
116
|
+
...inputs,
|
|
117
|
+
...action.inputs ?? {}
|
|
118
|
+
});
|
|
119
|
+
actionDef.set("annotations", { ...action.annotations ?? {
|
|
120
|
+
"require-adobe-auth": true,
|
|
121
|
+
final: true
|
|
122
|
+
} });
|
|
123
|
+
const includes = action.include ?? [];
|
|
124
|
+
if (includes.length > 0) {
|
|
125
|
+
const itemSeq = new YAMLSeq();
|
|
126
|
+
itemSeq.flow = true;
|
|
127
|
+
for (const [source, target] of includes) itemSeq.items.push(source, target);
|
|
128
|
+
const seq = new YAMLSeq();
|
|
129
|
+
seq.items.push(itemSeq);
|
|
130
|
+
actionDef.set("include", seq);
|
|
131
|
+
}
|
|
132
|
+
if (action.limits !== void 0) actionDef.set("limits", action.limits);
|
|
133
|
+
return actionDef;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Build the `operations` section of the `ext.config.yaml` file
|
|
137
|
+
* @param extConfig - The ext.config.yaml file
|
|
138
|
+
* @param operations - The operations to build
|
|
139
|
+
*/
|
|
140
|
+
function buildOperations(extConfig, operations) {
|
|
141
|
+
getOrCreateMap(extConfig, ["operations"], { onBeforeCreate: (pair) => {
|
|
142
|
+
pair.key.spaceBefore = true;
|
|
143
|
+
} });
|
|
144
|
+
const workerProcess = getOrCreateSeq(extConfig, ["operations", "workerProcess"], { onBeforeCreate: (pair) => {
|
|
145
|
+
pair.key.commentBefore = " These worker processes definitions are auto-generated. Do not remove or manually edit.";
|
|
146
|
+
} });
|
|
147
|
+
workerProcess.items = [];
|
|
148
|
+
const ourOps = operations.workerProcess ?? [];
|
|
149
|
+
workerProcess.items.push(...ourOps.map((op) => {
|
|
150
|
+
const map = new YAMLMap();
|
|
151
|
+
map.set("type", op.type);
|
|
152
|
+
map.set("impl", op.impl);
|
|
153
|
+
return map;
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Build the `runtimeManifest` section of the `ext.config.yaml` file
|
|
158
|
+
* @param extConfig - The ext.config.yaml file
|
|
159
|
+
* @param packages - The packages to build
|
|
160
|
+
*/
|
|
161
|
+
function buildRuntimeManifest(extConfig, manifest) {
|
|
162
|
+
getOrCreateMap(extConfig, ["runtimeManifest"], { onBeforeCreate: (pair) => {
|
|
163
|
+
pair.key.spaceBefore = true;
|
|
164
|
+
} });
|
|
165
|
+
const packages = manifest.packages ?? {};
|
|
166
|
+
getOrCreateMap(extConfig, ["runtimeManifest", "packages"]);
|
|
167
|
+
for (const [name, pkg] of Object.entries(packages)) {
|
|
168
|
+
const packageDef = getOrCreateMap(extConfig, [
|
|
169
|
+
"runtimeManifest",
|
|
170
|
+
"packages",
|
|
171
|
+
name
|
|
172
|
+
], { onBeforeCreate: (pair) => {
|
|
173
|
+
pair.key.commentBefore = " This package definition is auto-generated. Do not remove or manually edit.";
|
|
174
|
+
} });
|
|
175
|
+
const actions = new YAMLMap();
|
|
176
|
+
packageDef.set("license", pkg.license ?? "Apache-2.0");
|
|
177
|
+
packageDef.set("actions", actions);
|
|
178
|
+
for (const [actionName, action] of Object.entries(pkg.actions ?? {})) {
|
|
179
|
+
const actionDef = buildActionDefinition(action);
|
|
180
|
+
actions.set(actionName, actionDef);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Build the `hooks` section of the `ext.config.yaml` file
|
|
186
|
+
* @param extConfig - The ext.config.yaml file
|
|
187
|
+
* @param hooks - The hooks to build
|
|
188
|
+
*/
|
|
189
|
+
async function buildHooks(extConfig, hooks) {
|
|
190
|
+
const generatedHooks = `[${Object.keys(hooks).join(", ")}]`;
|
|
191
|
+
const hooksMap = getOrCreateMap(extConfig, ["hooks"], { onBeforeCreate: (pair) => {
|
|
192
|
+
pair.key.spaceBefore = true;
|
|
193
|
+
pair.key.commentBefore = ` The ${generatedHooks} hooks are auto-generated. Do not remove or manually edit.`;
|
|
194
|
+
} });
|
|
195
|
+
const execCommand = getExecCommand(await detectPackageManager());
|
|
196
|
+
for (const [name, command$1] of Object.entries(hooks)) {
|
|
197
|
+
const fullCommand = `${command$1.replaceAll("$packageExec", execCommand)}`;
|
|
198
|
+
const prevValue = (hooksMap.get(name) ?? "").trim();
|
|
199
|
+
if (prevValue.endsWith("js") || prevValue.endsWith("ts")) throw new Error(`Conflicting hook definition found. The "${name}" hook needs to be a command, not a script.`);
|
|
200
|
+
if (prevValue !== "" && !prevValue.includes(fullCommand)) hooksMap.set(name, `${prevValue} && ${fullCommand}`);
|
|
201
|
+
else if (prevValue === "") hooksMap.set(name, fullCommand);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Write the ext.config.yaml file
|
|
206
|
+
* @param configPath - The path to the ext.config.yaml file
|
|
207
|
+
* @param config - The config to write
|
|
208
|
+
*/
|
|
209
|
+
async function writeExtConfig(configPath, doc) {
|
|
210
|
+
await writeFile(configPath, doc.toString({
|
|
211
|
+
indent: 2,
|
|
212
|
+
lineWidth: 0,
|
|
213
|
+
defaultStringType: "PLAIN"
|
|
214
|
+
}), "utf-8");
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
//#endregion
|
|
218
|
+
//#region source/commands/constants.ts
|
|
219
|
+
/** The name of the package containing all the generated runtime actions */
|
|
220
|
+
const PACKAGE_NAME = "app-management";
|
|
221
|
+
/** The path to the directory containing the generated files */
|
|
222
|
+
const GENERATED_PATH = ".generated";
|
|
223
|
+
/** The folder name containing the runtime actions */
|
|
224
|
+
const ACTIONS_FOLDER = `actions/${PACKAGE_NAME}`;
|
|
225
|
+
/** The path to the directory containing the generated actions */
|
|
226
|
+
const GENERATED_ACTIONS_PATH = `${GENERATED_PATH}/${ACTIONS_FOLDER}`;
|
|
227
|
+
/** The name of the extension point for extensibility. */
|
|
228
|
+
const EXTENSIBILITY_EXTENSION_POINT_ID = "commerce/extensibility/1";
|
|
229
|
+
/** The name of the extension point for configuration. */
|
|
230
|
+
const CONFIGURATION_EXTENSION_POINT_ID = "commerce/configuration/1";
|
|
231
|
+
/** The name of the configuration schema file */
|
|
232
|
+
const APP_MANIFEST_FILE = "app.commerce.manifest.json";
|
|
233
|
+
/** The name of the commerce app configuration file */
|
|
234
|
+
const COMMERCE_APP_CONFIG_FILE = "app.commerce.config";
|
|
235
|
+
/** The name of the configuration schema file */
|
|
236
|
+
const CONFIG_SCHEMA_FILE_NAME = "configuration-schema.json";
|
|
237
|
+
/** The name of the project package file */
|
|
238
|
+
const PACKAGE_JSON_FILE = "package.json";
|
|
239
|
+
/** The name of the app configuration file */
|
|
240
|
+
const APP_CONFIG_FILE = "app.config.yaml";
|
|
241
|
+
/** The name of the install configuration file */
|
|
242
|
+
const INSTALL_YAML_FILE = "install.yaml";
|
|
243
|
+
/** Get the path to the extension point folder */
|
|
244
|
+
function getExtensionPointFolderPath(extensionPointId) {
|
|
245
|
+
return `src/${extensionPointId.replaceAll("/", "-")}`;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
//#endregion
|
|
249
|
+
//#region source/commands/utils.ts
|
|
250
|
+
/** Load the app commerce config */
|
|
251
|
+
async function loadAppManifest() {
|
|
252
|
+
const appConfig = await parseCommerceAppConfig();
|
|
253
|
+
consola.debug("Loaded app commerce config");
|
|
254
|
+
return appConfig;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
//#endregion
|
|
258
|
+
//#region source/commands/generate/actions/config.ts
|
|
259
|
+
/** The list of Commerce variables that are required for the runtime actions */
|
|
260
|
+
const COMMERCE_VARIABLES = [
|
|
261
|
+
"AIO_COMMERCE_API_BASE_URL",
|
|
262
|
+
"AIO_COMMERCE_AUTH_IMS_CLIENT_ID",
|
|
263
|
+
"AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS",
|
|
264
|
+
"AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID",
|
|
265
|
+
"AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL",
|
|
266
|
+
"AIO_COMMERCE_AUTH_IMS_ORG_ID",
|
|
267
|
+
"AIO_COMMERCE_AUTH_IMS_SCOPES"
|
|
268
|
+
];
|
|
269
|
+
/** The inputs for the generated runtime actions */
|
|
270
|
+
const COMMERCE_ACTION_INPUTS = Object.fromEntries(COMMERCE_VARIABLES.map((variable) => [variable, `$${variable}`]));
|
|
271
|
+
const CUSTOM_IMPORTS_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_IMPORTS}}";
|
|
272
|
+
const CUSTOM_SCRIPTS_MAP_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_MAP}}";
|
|
273
|
+
const CUSTOM_SCRIPTS_LOADER_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_LOADER}}";
|
|
274
|
+
/**
|
|
275
|
+
* Creates a runtime action configuration.
|
|
276
|
+
* @param actionName - The name of the action.
|
|
277
|
+
* @param options - Optional configuration options.
|
|
278
|
+
*/
|
|
279
|
+
function createActionDefinition(actionName, config$1 = {}, options = {}) {
|
|
280
|
+
const def = {
|
|
281
|
+
...options,
|
|
282
|
+
function: `${GENERATED_ACTIONS_PATH}/${actionName}.js`,
|
|
283
|
+
web: options.web ?? "yes",
|
|
284
|
+
runtime: "nodejs:22",
|
|
285
|
+
annotations: {
|
|
286
|
+
"require-adobe-auth": true,
|
|
287
|
+
final: true
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
if (config$1.requiresSchema) def.include = [[`${GENERATED_PATH}/${CONFIG_SCHEMA_FILE_NAME}`, `${PACKAGE_NAME}/`]];
|
|
291
|
+
if (config$1.requiresEncryptionKey) def.inputs = {
|
|
292
|
+
...def.inputs,
|
|
293
|
+
AIO_COMMERCE_CONFIG_ENCRYPTION_KEY: "$AIO_COMMERCE_CONFIG_ENCRYPTION_KEY"
|
|
294
|
+
};
|
|
295
|
+
return def;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Gets the runtime actions to be generated from the ext.config.yaml configuration.
|
|
299
|
+
* @param extConfig - The ext.config.yaml configuration.
|
|
300
|
+
*/
|
|
301
|
+
function getRuntimeActions(extConfig, dir) {
|
|
302
|
+
return Object.entries(extConfig.runtimeManifest?.packages?.[PACKAGE_NAME]?.actions ?? {}).map(([name, _]) => ({
|
|
303
|
+
name,
|
|
304
|
+
templateFile: join(dir, `${name}.js.template`)
|
|
305
|
+
}));
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Builds the ext.config.yaml configuration for the extensibility extension.
|
|
309
|
+
* @param features - The features that are enabled for the app.
|
|
310
|
+
*/
|
|
311
|
+
function buildAppManagementExtConfig(features) {
|
|
312
|
+
const extConfig = {
|
|
313
|
+
hooks: { "pre-app-build": "EXTENSION=extensibility/1 $packageExec aio-commerce-lib-app hooks pre-app-build" },
|
|
314
|
+
operations: { workerProcess: [{
|
|
315
|
+
type: "action",
|
|
316
|
+
impl: `${PACKAGE_NAME}/get-app-config`
|
|
317
|
+
}] },
|
|
318
|
+
runtimeManifest: { packages: { [PACKAGE_NAME]: {
|
|
319
|
+
license: "Apache-2.0",
|
|
320
|
+
actions: { "get-app-config": createActionDefinition("get-app-config") }
|
|
321
|
+
} } }
|
|
322
|
+
};
|
|
323
|
+
if ([
|
|
324
|
+
"installation.customInstallationSteps",
|
|
325
|
+
"eventing.commerce",
|
|
326
|
+
"eventing.external"
|
|
327
|
+
].some((feature) => features.has(feature))) {
|
|
328
|
+
extConfig.operations.workerProcess.push({
|
|
329
|
+
type: "action",
|
|
330
|
+
impl: `${PACKAGE_NAME}/installation`
|
|
331
|
+
});
|
|
332
|
+
extConfig.runtimeManifest.packages[PACKAGE_NAME].actions.installation = createActionDefinition("installation", {}, {
|
|
333
|
+
inputs: {
|
|
334
|
+
...COMMERCE_ACTION_INPUTS,
|
|
335
|
+
LOG_LEVEL: "$LOG_LEVEL"
|
|
336
|
+
},
|
|
337
|
+
limits: { timeout: 6e5 }
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
return extConfig;
|
|
341
|
+
}
|
|
342
|
+
/** Builds the ext.config.yaml configuration for the business configuration extension. */
|
|
343
|
+
function buildBusinessConfigurationExtConfig() {
|
|
344
|
+
const actions = [
|
|
345
|
+
{
|
|
346
|
+
name: "get-scope-tree",
|
|
347
|
+
templateFile: "get-scope-tree.js.template"
|
|
348
|
+
},
|
|
349
|
+
{
|
|
350
|
+
name: "get-config-schema",
|
|
351
|
+
templateFile: "get-config-schema.js.template",
|
|
352
|
+
requiresSchema: true
|
|
353
|
+
},
|
|
354
|
+
{
|
|
355
|
+
name: "get-configuration",
|
|
356
|
+
templateFile: "get-configuration.js.template",
|
|
357
|
+
requiresSchema: true,
|
|
358
|
+
requiresEncryptionKey: true
|
|
359
|
+
},
|
|
360
|
+
{
|
|
361
|
+
name: "set-configuration",
|
|
362
|
+
templateFile: "set-configuration.js.template",
|
|
363
|
+
requiresEncryptionKey: true
|
|
364
|
+
},
|
|
365
|
+
{
|
|
366
|
+
name: "set-custom-scope-tree",
|
|
367
|
+
templateFile: "set-custom-scope-tree.js.template"
|
|
368
|
+
},
|
|
369
|
+
{
|
|
370
|
+
name: "sync-commerce-scopes",
|
|
371
|
+
templateFile: "sync-commerce-scopes.js.template"
|
|
372
|
+
},
|
|
373
|
+
{
|
|
374
|
+
name: "unsync-commerce-scopes",
|
|
375
|
+
templateFile: "unsync-commerce-scopes.js.template"
|
|
376
|
+
}
|
|
377
|
+
];
|
|
378
|
+
return {
|
|
379
|
+
hooks: { "pre-app-build": "EXTENSION=configuration/1 $packageExec aio-commerce-lib-app hooks pre-app-build" },
|
|
380
|
+
operations: { workerProcess: actions.map((action) => ({
|
|
381
|
+
type: "action",
|
|
382
|
+
impl: `${PACKAGE_NAME}/${action.name}`
|
|
383
|
+
})) },
|
|
384
|
+
runtimeManifest: { packages: { [PACKAGE_NAME]: {
|
|
385
|
+
license: "Apache-2.0",
|
|
386
|
+
actions: Object.fromEntries(actions.map((action) => [action.name, createActionDefinition(action.name, action)]))
|
|
387
|
+
} } }
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
//#endregion
|
|
392
|
+
//#region source/commands/generate/actions/main.ts
|
|
393
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
394
|
+
async function run$4(appManifest) {
|
|
395
|
+
await generateActionFiles(appManifest, getRuntimeActions(await updateExtConfig(appManifest, EXTENSIBILITY_EXTENSION_POINT_ID), "app-management"), EXTENSIBILITY_EXTENSION_POINT_ID);
|
|
396
|
+
if (hasBusinessConfigSchema(appManifest)) await generateActionFiles(appManifest, getRuntimeActions(await updateExtConfig(appManifest, CONFIGURATION_EXTENSION_POINT_ID), "business-configuration"), CONFIGURATION_EXTENSION_POINT_ID);
|
|
397
|
+
}
|
|
398
|
+
/** Run the generate actions command */
|
|
399
|
+
async function exec$5() {
|
|
400
|
+
try {
|
|
401
|
+
await run$4(await loadAppManifest());
|
|
402
|
+
} catch (error) {
|
|
403
|
+
if (error instanceof CommerceSdkValidationError) consola$1.error(error.display());
|
|
404
|
+
consola$1.error(error);
|
|
405
|
+
process.exit(1);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
/** Update the ext.config.yaml file */
|
|
409
|
+
async function updateExtConfig(appConfig, extensionPointId) {
|
|
410
|
+
consola$1.info(`Updating ext.config.yaml for ${extensionPointId}...`);
|
|
411
|
+
const extConfigPath = join(await makeOutputDirFor(getExtensionPointFolderPath(extensionPointId)), "ext.config.yaml");
|
|
412
|
+
const extConfigDoc = await readYamlFile(extConfigPath);
|
|
413
|
+
let extConfig;
|
|
414
|
+
switch (extensionPointId) {
|
|
415
|
+
case EXTENSIBILITY_EXTENSION_POINT_ID:
|
|
416
|
+
extConfig = buildAppManagementExtConfig(getConfigDomains(appConfig));
|
|
417
|
+
break;
|
|
418
|
+
case CONFIGURATION_EXTENSION_POINT_ID:
|
|
419
|
+
extConfig = buildBusinessConfigurationExtConfig();
|
|
420
|
+
break;
|
|
421
|
+
default: throw new Error(`Unsupported extension point ID: ${extensionPointId}`);
|
|
422
|
+
}
|
|
423
|
+
await createOrUpdateExtConfig(extConfigPath, extConfig, extConfigDoc);
|
|
424
|
+
return extConfig;
|
|
425
|
+
}
|
|
426
|
+
/** Generate the action files */
|
|
427
|
+
async function generateActionFiles(appManifest, actions, extensionPointId) {
|
|
428
|
+
consola$1.start("Generating runtime actions...");
|
|
429
|
+
const outputDir = await makeOutputDirFor(join(getExtensionPointFolderPath(extensionPointId), GENERATED_ACTIONS_PATH));
|
|
430
|
+
const outputFiles = [];
|
|
431
|
+
const templatesDir = join(__dirname, "generate/actions/templates");
|
|
432
|
+
for (const action of actions) {
|
|
433
|
+
let template = await readFile(join(templatesDir, action.templateFile), "utf-8");
|
|
434
|
+
if (action.name === "installation") {
|
|
435
|
+
const scriptsTemplate = await generateCustomScriptsTemplate(await readFile(join(templatesDir, "app-management", "custom-scripts.js.template"), "utf-8"), appManifest);
|
|
436
|
+
template = applyCustomScripts(template, scriptsTemplate);
|
|
437
|
+
}
|
|
438
|
+
const actionPath = join(outputDir, `${action.name}.js`);
|
|
439
|
+
await writeFile(actionPath, template, "utf-8");
|
|
440
|
+
outputFiles.push(` ${relative(process.cwd(), actionPath)}`);
|
|
441
|
+
}
|
|
442
|
+
consola$1.success(`Generated ${actions.length} action(s)`);
|
|
443
|
+
consola$1.log.raw(formatTree(outputFiles));
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Applies the given custom scripts template code to the given installation template.
|
|
447
|
+
* @param installationTemplate - The installation code runtime action template
|
|
448
|
+
* @param customScriptsTemplate - The custom scripts dynamically generated template.
|
|
449
|
+
*/
|
|
450
|
+
function applyCustomScripts(installationTemplate, customScriptsTemplate) {
|
|
451
|
+
if (customScriptsTemplate !== null) return installationTemplate.replace(CUSTOM_SCRIPTS_LOADER_PLACEHOLDER, customScriptsTemplate).replace("const args = { appConfig };", "const args = { appConfig, customScriptsLoader };");
|
|
452
|
+
consola$1.debug("No custom installation steps found, skipping custom-scripts.js generation...");
|
|
453
|
+
return installationTemplate.replace(CUSTOM_SCRIPTS_LOADER_PLACEHOLDER, "// No custom installation scripts configured");
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Generate the installation template with dynamic custom script imports
|
|
457
|
+
*/
|
|
458
|
+
async function generateCustomScriptsTemplate(template, appManifest) {
|
|
459
|
+
if (!hasCustomInstallationSteps(appManifest)) return null;
|
|
460
|
+
const projectRoot = await getProjectRootDirectory();
|
|
461
|
+
const installationActionDir = join(projectRoot, getExtensionPointFolderPath(EXTENSIBILITY_EXTENSION_POINT_ID), GENERATED_ACTIONS_PATH);
|
|
462
|
+
const customSteps = appManifest.installation.customInstallationSteps;
|
|
463
|
+
const importStatements = customSteps.map((step, index) => {
|
|
464
|
+
let relativeImportPath = relative(installationActionDir, join(projectRoot, step.script));
|
|
465
|
+
if (!relativeImportPath.startsWith(".")) relativeImportPath = `./${relativeImportPath}`;
|
|
466
|
+
relativeImportPath = relativeImportPath.replace(/\\/g, "/");
|
|
467
|
+
return `import * as ${`customScript${index}`} from "${relativeImportPath}";`;
|
|
468
|
+
}).join("\n");
|
|
469
|
+
const scriptMap = customSteps.map((step, index) => {
|
|
470
|
+
const entry = `"${step.script}": ${`customScript${index}`},`;
|
|
471
|
+
return entry.padStart(entry.length + 6);
|
|
472
|
+
}).join("\n");
|
|
473
|
+
return template.replace(CUSTOM_IMPORTS_PLACEHOLDER, importStatements).replace(CUSTOM_SCRIPTS_MAP_PLACEHOLDER, scriptMap);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
//#endregion
|
|
477
|
+
//#region source/commands/generate/manifest/main.ts
|
|
478
|
+
async function run$3(appConfig) {
|
|
479
|
+
consola$1.info("Generating app manifest...");
|
|
480
|
+
const contents = stringify(appConfig, null, 2);
|
|
481
|
+
await writeFile(join(await makeOutputDirFor(`${getExtensionPointFolderPath(EXTENSIBILITY_EXTENSION_POINT_ID)}/.generated`), APP_MANIFEST_FILE), contents, "utf-8");
|
|
482
|
+
consola$1.success(`Generated ${APP_MANIFEST_FILE}`);
|
|
483
|
+
}
|
|
484
|
+
/** Run the generate manifest command */
|
|
485
|
+
async function exec$4() {
|
|
486
|
+
try {
|
|
487
|
+
await run$3(await loadAppManifest());
|
|
488
|
+
} catch (error) {
|
|
489
|
+
if (error instanceof CommerceSdkValidationError) consola$1.error(error.display());
|
|
490
|
+
consola$1.error(error);
|
|
491
|
+
process.exit(1);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
//#endregion
|
|
496
|
+
//#region source/commands/generate/schema/main.ts
|
|
497
|
+
async function run$2(appConfig) {
|
|
498
|
+
consola$1.info("Generating configuration schema...");
|
|
499
|
+
if (!hasBusinessConfigSchema(appConfig)) {
|
|
500
|
+
consola$1.warn("Business configuration schema not found");
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
execSync("aio-commerce-lib-config validate schema");
|
|
504
|
+
const contents = stringify(appConfig.businessConfig.schema, null, 2);
|
|
505
|
+
await writeFile(join(await makeOutputDirFor(`${getExtensionPointFolderPath(CONFIGURATION_EXTENSION_POINT_ID)}/.generated`), CONFIG_SCHEMA_FILE_NAME), contents, "utf-8");
|
|
506
|
+
consola$1.success(`Generated ${CONFIG_SCHEMA_FILE_NAME}`);
|
|
507
|
+
}
|
|
508
|
+
/** Run the generate manifest command */
|
|
509
|
+
async function exec$3() {
|
|
510
|
+
try {
|
|
511
|
+
await run$2(await loadAppManifest());
|
|
512
|
+
} catch (error) {
|
|
513
|
+
if (error instanceof CommerceSdkValidationError) consola$1.error(error.display());
|
|
514
|
+
consola$1.error(error);
|
|
515
|
+
process.exit(1);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
//#endregion
|
|
520
|
+
//#region source/commands/hooks/postinstall.ts
|
|
521
|
+
async function run$1(appManifest) {
|
|
522
|
+
await run$4(appManifest);
|
|
523
|
+
await run$3(appManifest);
|
|
524
|
+
await run$2(appManifest);
|
|
525
|
+
}
|
|
526
|
+
/** Runs the postinstall hook */
|
|
527
|
+
async function exec$2() {
|
|
528
|
+
consola.debug("Running lib-app postinstall hook");
|
|
529
|
+
try {
|
|
530
|
+
await run$1(await loadAppManifest());
|
|
531
|
+
} catch (error) {
|
|
532
|
+
if (error instanceof CommerceSdkValidationError) consola.error(error.display());
|
|
533
|
+
consola.error(error);
|
|
534
|
+
process.exit(1);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
//#endregion
|
|
539
|
+
//#region ../../packages-private/scripting-utils/source/env.ts
|
|
540
|
+
/**
|
|
541
|
+
* This module exports shared environment utilities for the AIO Commerce SDK.
|
|
542
|
+
* @packageDocumentation
|
|
543
|
+
*/
|
|
544
|
+
const { context } = aioIms;
|
|
545
|
+
const IMS_KEYS = {
|
|
546
|
+
client_id: "AIO_COMMERCE_AUTH_IMS_CLIENT_ID",
|
|
547
|
+
client_secrets: "AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS",
|
|
548
|
+
technical_account_email: "AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL",
|
|
549
|
+
technical_account_id: "AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID",
|
|
550
|
+
scopes: "AIO_COMMERCE_AUTH_IMS_SCOPES",
|
|
551
|
+
ims_org_id: "AIO_COMMERCE_AUTH_IMS_ORG_ID"
|
|
552
|
+
};
|
|
553
|
+
/**
|
|
554
|
+
* Replaces or creates an environment variable in a .env file
|
|
555
|
+
* @param filePath - The path to the .env file
|
|
556
|
+
* @param key - The environment variable key to replace or create
|
|
557
|
+
* @param value - The new value for the environment variable
|
|
558
|
+
*/
|
|
559
|
+
function replaceEnvVar(filePath, key, value) {
|
|
560
|
+
const envPath = path.resolve(filePath);
|
|
561
|
+
const envLines = readFileSync(envPath, "utf8").split("\n");
|
|
562
|
+
const formattedValue = value.includes(" ") ? `"${value}"` : value;
|
|
563
|
+
let keyExists = false;
|
|
564
|
+
const updatedLines = envLines.map((line) => {
|
|
565
|
+
if (line.trim().startsWith("#") || !line.includes("=")) return line;
|
|
566
|
+
const [currentKey] = line.split("=");
|
|
567
|
+
if (currentKey === key) {
|
|
568
|
+
keyExists = true;
|
|
569
|
+
return `${key}=${formattedValue}`;
|
|
570
|
+
}
|
|
571
|
+
return line;
|
|
572
|
+
});
|
|
573
|
+
if (!keyExists) updatedLines.push(`${key}=${formattedValue}`);
|
|
574
|
+
writeFileSync(envPath, updatedLines.join("\n"), "utf8");
|
|
575
|
+
}
|
|
576
|
+
/** Returns the path to the .env file. */
|
|
577
|
+
function resolveEnvPath() {
|
|
578
|
+
const envPath = process.env.INIT_CWD ? `${process.env.INIT_CWD}/.env` : ".env";
|
|
579
|
+
return path.resolve(envPath);
|
|
580
|
+
}
|
|
581
|
+
/** Resolves the IMS server to server context from the project workspace credentials. */
|
|
582
|
+
function resolveImsS2SContext() {
|
|
583
|
+
const [credential] = (config.get("project.workspace.details.credentials") ?? []).filter(({ integration_type }) => integration_type === "oauth_server_to_server").map(({ name }) => name) ?? [];
|
|
584
|
+
if (!credential) return Promise.resolve(null);
|
|
585
|
+
return context.get(credential);
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Syncs the IMS credentials environment variables from the configured IMS context in
|
|
589
|
+
* the .env file, in a way that is compatible with `@adobe/aio-commerce-lib-auth`
|
|
590
|
+
*/
|
|
591
|
+
async function syncImsCredentials() {
|
|
592
|
+
const envPath = resolveEnvPath();
|
|
593
|
+
const envVars = dotenv.parse(readFileSync(envPath, "utf8"));
|
|
594
|
+
const imsContext = await resolveImsS2SContext();
|
|
595
|
+
if (!imsContext) return;
|
|
596
|
+
const { data } = imsContext;
|
|
597
|
+
for (const [key, value] of Object.entries(data)) {
|
|
598
|
+
const oauthKey = IMS_KEYS[key];
|
|
599
|
+
if (!oauthKey) continue;
|
|
600
|
+
if (!envVars[oauthKey] || envVars[oauthKey] !== value) replaceEnvVar(envPath, oauthKey, value);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
//#endregion
|
|
605
|
+
//#region source/commands/hooks/pre-app-build.ts
|
|
606
|
+
/**
|
|
607
|
+
* Runs the pre-app-build hook for the given extension.
|
|
608
|
+
* @param extension - The extension to run the hook for.
|
|
609
|
+
*/
|
|
610
|
+
async function run(extension) {
|
|
611
|
+
const appManifest = await loadAppManifest();
|
|
612
|
+
if (extension === "extensibility/1") {
|
|
613
|
+
await run$3(appManifest);
|
|
614
|
+
consola.info("Syncing IMS credentials...");
|
|
615
|
+
await syncImsCredentials();
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (extension === "configuration/1") {
|
|
619
|
+
await run$2(appManifest);
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
throw new Error(`Unsupported extension: ${extension}`);
|
|
623
|
+
}
|
|
624
|
+
/** Runs the pre-app-build hook */
|
|
625
|
+
async function exec$1() {
|
|
626
|
+
consola.debug("Running lib-app pre-app-build hook");
|
|
627
|
+
const extension = process.env.EXTENSION;
|
|
628
|
+
try {
|
|
629
|
+
if (!extension) throw new Error("EXTENSION environment variable is not set");
|
|
630
|
+
await run(extension);
|
|
631
|
+
} catch (error) {
|
|
632
|
+
if (error instanceof CommerceSdkValidationError) consola.error(error.display());
|
|
633
|
+
consola.error(error);
|
|
634
|
+
process.exit(1);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
//#endregion
|
|
639
|
+
//#region source/commands/init/constants.ts
|
|
640
|
+
/** The default values for the features of the commerce app config. */
|
|
641
|
+
const DOMAIN_DEFAULTS = {
|
|
642
|
+
businessConfig: { schema: [{
|
|
643
|
+
type: "list",
|
|
644
|
+
name: "sampleList",
|
|
645
|
+
label: "Sample List",
|
|
646
|
+
selectionMode: "multiple",
|
|
647
|
+
default: ["a"],
|
|
648
|
+
options: [{
|
|
649
|
+
label: "Option A",
|
|
650
|
+
value: "a"
|
|
651
|
+
}, {
|
|
652
|
+
label: "Option B",
|
|
653
|
+
value: "b"
|
|
654
|
+
}]
|
|
655
|
+
}, {
|
|
656
|
+
type: "text",
|
|
657
|
+
name: "sampleText",
|
|
658
|
+
label: "Sample Text",
|
|
659
|
+
default: "Hello, world!"
|
|
660
|
+
}] },
|
|
661
|
+
"eventing.commerce": [{
|
|
662
|
+
provider: {
|
|
663
|
+
label: "Commerce Events Provider",
|
|
664
|
+
description: "A description for your Commerce Events provider."
|
|
665
|
+
},
|
|
666
|
+
events: [{
|
|
667
|
+
name: "plugin.sample_event",
|
|
668
|
+
fields: [],
|
|
669
|
+
label: "Sample Event",
|
|
670
|
+
description: "Use case description for the event.",
|
|
671
|
+
runtimeActions: ["my-package/handle-sample-event"]
|
|
672
|
+
}]
|
|
673
|
+
}],
|
|
674
|
+
"eventing.external": [{
|
|
675
|
+
provider: {
|
|
676
|
+
label: "External Events Provider",
|
|
677
|
+
description: "A description for your External Events provider."
|
|
678
|
+
},
|
|
679
|
+
events: [{
|
|
680
|
+
name: "be-observer.sample_event",
|
|
681
|
+
label: "Sample Event",
|
|
682
|
+
description: "Use case description for the event.",
|
|
683
|
+
runtimeActions: ["my-package/handle-sample-event"]
|
|
684
|
+
}]
|
|
685
|
+
}],
|
|
686
|
+
"installation.customInstallationSteps": [{
|
|
687
|
+
name: "sample-step",
|
|
688
|
+
description: "Use case description for the step.",
|
|
689
|
+
script: "./path/to/script.js"
|
|
690
|
+
}]
|
|
691
|
+
};
|
|
692
|
+
|
|
693
|
+
//#endregion
|
|
694
|
+
//#region source/commands/init/utils.ts
|
|
695
|
+
/** Prompt the user to scaffold a new Commerce App configuration. */
|
|
696
|
+
async function promptForCommerceAppConfig() {
|
|
697
|
+
const configFormat = await consola.prompt("What format do you want to use for the config file?", {
|
|
698
|
+
type: "select",
|
|
699
|
+
default: "ts",
|
|
700
|
+
initial: "ts",
|
|
701
|
+
cancel: "reject",
|
|
702
|
+
options: [{
|
|
703
|
+
label: "TypeScript",
|
|
704
|
+
value: "ts",
|
|
705
|
+
hint: "Recommended"
|
|
706
|
+
}, {
|
|
707
|
+
label: "JavaScript",
|
|
708
|
+
value: "js"
|
|
709
|
+
}]
|
|
710
|
+
});
|
|
711
|
+
const appName = await consola.prompt("What is the name of your app?", {
|
|
712
|
+
type: "text",
|
|
713
|
+
placeholder: "Application Display Name",
|
|
714
|
+
default: "My Application",
|
|
715
|
+
cancel: "reject"
|
|
716
|
+
});
|
|
717
|
+
const featuresToAdd = await consola.prompt(`What features do you want to add to your app? ${colorize("gray", "Space to select/deselect, Enter to submit")}`, {
|
|
718
|
+
type: "multiselect",
|
|
719
|
+
initial: [],
|
|
720
|
+
required: true,
|
|
721
|
+
cancel: "reject",
|
|
722
|
+
options: [
|
|
723
|
+
{
|
|
724
|
+
label: "Business Configuration",
|
|
725
|
+
value: "businessConfig.schema"
|
|
726
|
+
},
|
|
727
|
+
{
|
|
728
|
+
label: "Commerce Events",
|
|
729
|
+
value: "eventing.commerce"
|
|
730
|
+
},
|
|
731
|
+
{
|
|
732
|
+
label: "External Events",
|
|
733
|
+
value: "eventing.external"
|
|
734
|
+
},
|
|
735
|
+
{
|
|
736
|
+
label: "Custom Installation Steps",
|
|
737
|
+
value: "installation.customInstallationSteps"
|
|
738
|
+
}
|
|
739
|
+
]
|
|
740
|
+
});
|
|
741
|
+
return {
|
|
742
|
+
appName,
|
|
743
|
+
configFile: `${COMMERCE_APP_CONFIG_FILE}.${configFormat}`,
|
|
744
|
+
domains: new Set(featuresToAdd),
|
|
745
|
+
configFormat
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
/** Create the default commerce app config file content */
|
|
749
|
+
async function getDefaultCommerceAppConfig(cwd, { appName, configFormat, domains }) {
|
|
750
|
+
const needsESM = await isESM(cwd) || configFormat === "ts";
|
|
751
|
+
const exportKeyword = needsESM ? "export default" : "module.exports =";
|
|
752
|
+
const importStatement = needsESM ? "import { defineConfig } from \"@adobe/aio-commerce-lib-app/config\";" : "const { defineConfig } = require(\"@adobe/aio-commerce-lib-app/config\");";
|
|
753
|
+
const defaultConfig = { metadata: {
|
|
754
|
+
id: appName.toLowerCase().replace(/ /g, "-"),
|
|
755
|
+
displayName: appName,
|
|
756
|
+
version: "1.0.0",
|
|
757
|
+
description: "A custom Adobe Commerce application. Fill description for your app."
|
|
758
|
+
} };
|
|
759
|
+
if (domains.has("businessConfig.schema")) defaultConfig.businessConfig = { schema: DOMAIN_DEFAULTS.businessConfig.schema };
|
|
760
|
+
if (domains.has("eventing.commerce")) defaultConfig.eventing = {
|
|
761
|
+
...defaultConfig.eventing,
|
|
762
|
+
commerce: DOMAIN_DEFAULTS["eventing.commerce"]
|
|
763
|
+
};
|
|
764
|
+
if (domains.has("eventing.external")) defaultConfig.eventing = {
|
|
765
|
+
...defaultConfig.eventing,
|
|
766
|
+
external: DOMAIN_DEFAULTS["eventing.external"]
|
|
767
|
+
};
|
|
768
|
+
if (domains.has("installation.customInstallationSteps")) defaultConfig.installation = { customInstallationSteps: DOMAIN_DEFAULTS["installation.customInstallationSteps"] };
|
|
769
|
+
return [
|
|
770
|
+
importStatement,
|
|
771
|
+
"",
|
|
772
|
+
`${exportKeyword} defineConfig(${inspect(defaultConfig, { colors: false })})`
|
|
773
|
+
].join("\n");
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Add an extension point to the app config file.
|
|
777
|
+
* @param extensionPointId - The id of the extension point.
|
|
778
|
+
* @param rootDirectory - The root directory of the project.
|
|
779
|
+
* @param commentBefore - The comment to add before the extension point include pair.
|
|
780
|
+
*/
|
|
781
|
+
async function addExtensionPointToAppConfig(extensionPointId, rootDirectory, commentBefore) {
|
|
782
|
+
const appConfigPath = join(rootDirectory, APP_CONFIG_FILE);
|
|
783
|
+
const extensionPointFolderPath = join(rootDirectory, getExtensionPointFolderPath(extensionPointId));
|
|
784
|
+
let doc;
|
|
785
|
+
const includePath = relative(rootDirectory, join(extensionPointFolderPath, "ext.config.yaml"));
|
|
786
|
+
try {
|
|
787
|
+
doc = await readYamlFile(appConfigPath);
|
|
788
|
+
} catch (error) {
|
|
789
|
+
const fallbackContent = `extensions:\n ${extensionPointId}:\n $include: "${includePath}"`;
|
|
790
|
+
throw new Error(`Failed to parse ${APP_CONFIG_FILE}. \nPlease add manually: \n\n${fallbackContent}`, { cause: error });
|
|
791
|
+
}
|
|
792
|
+
if (doc.getIn([
|
|
793
|
+
"extensions",
|
|
794
|
+
extensionPointId,
|
|
795
|
+
"$include"
|
|
796
|
+
]) === includePath) {
|
|
797
|
+
consola.success(`Extension "${extensionPointId}" already configured in ${APP_CONFIG_FILE}`);
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
consola.info(`Adding extension "${extensionPointId}" to ${APP_CONFIG_FILE}...`);
|
|
801
|
+
const extensions = getOrCreateMap(doc, ["extensions"], { onBeforeCreate: (pair) => {
|
|
802
|
+
pair.key.spaceBefore = true;
|
|
803
|
+
} });
|
|
804
|
+
getOrCreateMap(doc, ["extensions", extensionPointId], { onBeforeCreate: (pair) => {
|
|
805
|
+
pair.key.spaceBefore = extensions.items.length > 0;
|
|
806
|
+
pair.key.commentBefore = commentBefore;
|
|
807
|
+
} }).set("$include", includePath);
|
|
808
|
+
await writeFile(appConfigPath, doc.toString(), "utf-8");
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* Add an extension point to the install.yaml file.
|
|
812
|
+
* @param extensionPointId - The id of the extension point.
|
|
813
|
+
* @param rootDirectory - The root directory of the project.
|
|
814
|
+
* @param commentBefore - The comment to add before the extension point include pair.
|
|
815
|
+
*/
|
|
816
|
+
async function addExtensionPointToInstallYaml(extensionPointId, rootDirectory, commentBefore) {
|
|
817
|
+
const installYamlPath = join(rootDirectory, INSTALL_YAML_FILE);
|
|
818
|
+
let doc;
|
|
819
|
+
let extensions;
|
|
820
|
+
try {
|
|
821
|
+
doc = await readYamlFile(installYamlPath);
|
|
822
|
+
extensions = getOrCreateSeq(doc, ["extensions"], { onBeforeCreate: (pair) => {
|
|
823
|
+
pair.key.spaceBefore = true;
|
|
824
|
+
} });
|
|
825
|
+
} catch (error) {
|
|
826
|
+
const fallbackContent = `\nextensions:\n - extensionPointId: ${extensionPointId}`;
|
|
827
|
+
throw new Error(`Failed to parse ${INSTALL_YAML_FILE}. \nPlease add manually: \n\n${fallbackContent}`, { cause: error });
|
|
828
|
+
}
|
|
829
|
+
if (extensions.items.some((item) => isMap(item) && item.get("extensionPointId") === extensionPointId)) {
|
|
830
|
+
consola.success(`Extension "${extensionPointId}" already configured in ${INSTALL_YAML_FILE}`);
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
consola.info(`Adding extension "${extensionPointId}" to ${INSTALL_YAML_FILE}...`);
|
|
834
|
+
const extension = doc.createPair("extensionPointId", extensionPointId);
|
|
835
|
+
extension.key.spaceBefore = extensions.items.length > 0;
|
|
836
|
+
extension.key.commentBefore = commentBefore;
|
|
837
|
+
extensions.items.push(extension);
|
|
838
|
+
await writeFile(installYamlPath, doc.toString(), "utf-8");
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
//#endregion
|
|
842
|
+
//#region source/commands/init/lib.ts
|
|
843
|
+
/** Ensure app.commerce.config file exists, allow creating if it doesn't */
|
|
844
|
+
async function ensureCommerceAppConfig(cwd = process.cwd()) {
|
|
845
|
+
let config$1 = null;
|
|
846
|
+
try {
|
|
847
|
+
config$1 = await readCommerceAppConfig(cwd);
|
|
848
|
+
} catch (_) {}
|
|
849
|
+
if (config$1) try {
|
|
850
|
+
const validatedConfig = validateCommerceAppConfig(config$1);
|
|
851
|
+
consola$1.success(`${COMMERCE_APP_CONFIG_FILE} found and is valid. Continuing...`);
|
|
852
|
+
return {
|
|
853
|
+
config: validatedConfig,
|
|
854
|
+
domains: getConfigDomains(validatedConfig)
|
|
855
|
+
};
|
|
856
|
+
} catch (error) {
|
|
857
|
+
throw new Error(`${COMMERCE_APP_CONFIG_FILE} is invalid`, { cause: error });
|
|
858
|
+
}
|
|
859
|
+
consola$1.warn(`${COMMERCE_APP_CONFIG_FILE} not found.`);
|
|
860
|
+
if (!await consola$1.prompt(`Do you want to create a ${COMMERCE_APP_CONFIG_FILE} file? (y/n)`, {
|
|
861
|
+
type: "confirm",
|
|
862
|
+
initial: true,
|
|
863
|
+
default: false
|
|
864
|
+
})) throw new Error("Initialization cancelled.");
|
|
865
|
+
const answers = await promptForCommerceAppConfig();
|
|
866
|
+
try {
|
|
867
|
+
const configContent = await getDefaultCommerceAppConfig(cwd, answers);
|
|
868
|
+
consola$1.info(`Creating ${answers.configFile}...`);
|
|
869
|
+
const path$1 = join(await getProjectRootDirectory(cwd), answers.configFile);
|
|
870
|
+
await writeFile(path$1, await prettier.format(configContent, {
|
|
871
|
+
semi: true,
|
|
872
|
+
quoteStyle: "double",
|
|
873
|
+
arrowParens: "always",
|
|
874
|
+
bracketSameLine: true,
|
|
875
|
+
bracketSpacing: true,
|
|
876
|
+
trailingComma: "all",
|
|
877
|
+
tabWidth: 2,
|
|
878
|
+
useTabs: false,
|
|
879
|
+
printWidth: 80,
|
|
880
|
+
filepath: path$1
|
|
881
|
+
}), "utf-8");
|
|
882
|
+
consola$1.success(`Created ${answers.configFile}`);
|
|
883
|
+
return {
|
|
884
|
+
config: await parseCommerceAppConfig(cwd),
|
|
885
|
+
domains: answers.domains
|
|
886
|
+
};
|
|
887
|
+
} catch (error) {
|
|
888
|
+
throw new Error(`Failed to create ${answers.configFile}`, { cause: error });
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
/** Ensure package.json has the postinstall script */
|
|
892
|
+
async function ensurePackageJson(execCommand, cwd = process.cwd()) {
|
|
893
|
+
const postinstallScript = `${execCommand} aio-commerce-lib-app hooks postinstall`;
|
|
894
|
+
const packageJson = await readPackageJson(cwd);
|
|
895
|
+
if (!packageJson) {
|
|
896
|
+
consola$1.warn("package.json not found. Creating one...");
|
|
897
|
+
const packageJsonContent = {
|
|
898
|
+
name: "my-commerce-app",
|
|
899
|
+
version: "1.0.0",
|
|
900
|
+
private: true,
|
|
901
|
+
scripts: { postinstall: postinstallScript }
|
|
902
|
+
};
|
|
903
|
+
await writeFile(join(resolve(cwd), PACKAGE_JSON_FILE), JSON.stringify(packageJsonContent, null, 2), "utf-8");
|
|
904
|
+
consola$1.success("Wrote package.json");
|
|
905
|
+
return packageJsonContent;
|
|
906
|
+
}
|
|
907
|
+
packageJson.scripts ??= {};
|
|
908
|
+
if (packageJson.scripts.postinstall === postinstallScript || packageJson.scripts.postinstall?.includes(postinstallScript)) {
|
|
909
|
+
consola$1.success(`postinstall script already configured in ${PACKAGE_JSON_FILE}`);
|
|
910
|
+
return packageJson;
|
|
911
|
+
}
|
|
912
|
+
if (packageJson.scripts.postinstall) {
|
|
913
|
+
consola$1.warn(`${PACKAGE_JSON_FILE} already has a postinstall script. Adding a new one...`);
|
|
914
|
+
execSync(`npm pkg set scripts.postinstall="${`${packageJson.scripts.postinstall} && ${postinstallScript}`}"`);
|
|
915
|
+
} else {
|
|
916
|
+
consola$1.info(`Adding postinstall script to ${PACKAGE_JSON_FILE}...`);
|
|
917
|
+
execSync(`npm pkg set scripts.postinstall="${postinstallScript}"`);
|
|
918
|
+
}
|
|
919
|
+
consola$1.success(`Added postinstall script to ${PACKAGE_JSON_FILE}`);
|
|
920
|
+
return packageJson;
|
|
921
|
+
}
|
|
922
|
+
/** Ensure app.config.yaml has the extension reference */
|
|
923
|
+
async function ensureAppConfig(domains, cwd = process.cwd()) {
|
|
924
|
+
const rootDirectory = await getProjectRootDirectory(cwd);
|
|
925
|
+
if (domains.has("businessConfig.schema")) await addExtensionPointToAppConfig(CONFIGURATION_EXTENSION_POINT_ID, rootDirectory, " This extension is required for business configuration. Do not remove.");
|
|
926
|
+
await addExtensionPointToAppConfig(EXTENSIBILITY_EXTENSION_POINT_ID, rootDirectory, " This extension is required for app management. Do not remove.");
|
|
927
|
+
}
|
|
928
|
+
/** Install required dependencies */
|
|
929
|
+
function installDependencies(packageManager, domains, cwd = process.cwd()) {
|
|
930
|
+
consola$1.info(`Installing dependencies with ${packageManager}...`);
|
|
931
|
+
const packages = ["@adobe/aio-commerce-lib-app", "@adobe/aio-commerce-sdk"];
|
|
932
|
+
if (domains.has("businessConfig.schema")) packages.push("@adobe/aio-commerce-lib-config");
|
|
933
|
+
const packagesToInstall = packages.join(" ");
|
|
934
|
+
const installCommand = {
|
|
935
|
+
pnpm: `pnpm add ${packagesToInstall}`,
|
|
936
|
+
yarn: `yarn add ${packagesToInstall}`,
|
|
937
|
+
bun: `bun add ${packagesToInstall}`,
|
|
938
|
+
npm: `npm install ${packagesToInstall}`
|
|
939
|
+
}[packageManager];
|
|
940
|
+
try {
|
|
941
|
+
execSync(installCommand, {
|
|
942
|
+
cwd,
|
|
943
|
+
stdio: "inherit"
|
|
944
|
+
});
|
|
945
|
+
consola$1.success("Dependencies installed successfully");
|
|
946
|
+
} catch (error) {
|
|
947
|
+
throw new Error(`Failed to install dependencies automatically. Please install manually: ${installCommand}`, { cause: error });
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
/** Run the generation command */
|
|
951
|
+
async function runGeneration(appConfig, execCommand) {
|
|
952
|
+
try {
|
|
953
|
+
await run$4(appConfig);
|
|
954
|
+
await run$3(appConfig);
|
|
955
|
+
} catch (error) {
|
|
956
|
+
throw new Error(`Failed to run generation command. Please run manually: ${execCommand} aio-commerce-lib-app generate all`, { cause: error });
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
/** Ensure install.yaml has the extension reference */
|
|
960
|
+
async function ensureInstallYaml(domains, cwd = process.cwd()) {
|
|
961
|
+
const rootDirectory = await getProjectRootDirectory(cwd);
|
|
962
|
+
if (domains.has("businessConfig.schema")) await addExtensionPointToInstallYaml(CONFIGURATION_EXTENSION_POINT_ID, rootDirectory, " This extension is required for business configuration. Do not remove.");
|
|
963
|
+
await addExtensionPointToInstallYaml(EXTENSIBILITY_EXTENSION_POINT_ID, rootDirectory, " This extension is required for app management. Do not remove.");
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
//#endregion
|
|
967
|
+
//#region source/commands/init/main.ts
|
|
968
|
+
/** Initialize the project with @adobe/aio-commerce-lib-config */
|
|
969
|
+
async function exec() {
|
|
970
|
+
try {
|
|
971
|
+
consola$1.start("Initializing app...");
|
|
972
|
+
const packageManager = await detectPackageManager();
|
|
973
|
+
const execCommand = getExecCommand(packageManager);
|
|
974
|
+
await ensurePackageJson(execCommand);
|
|
975
|
+
const { config: config$1, domains } = await ensureCommerceAppConfig();
|
|
976
|
+
execSync(`npm pkg set name="${config$1.metadata.id}"`);
|
|
977
|
+
execSync(`npm pkg set version="${config$1.metadata.version}"`);
|
|
978
|
+
execSync(`npm pkg set description="${config$1.metadata.description}"`);
|
|
979
|
+
await runGeneration(config$1, execCommand);
|
|
980
|
+
await ensureAppConfig(domains);
|
|
981
|
+
await ensureInstallYaml(domains);
|
|
982
|
+
installDependencies(packageManager, domains);
|
|
983
|
+
consola$1.success("Initialization complete!");
|
|
984
|
+
consola$1.box([
|
|
985
|
+
"Next steps:",
|
|
986
|
+
" - Review and customize app.commerce.config.*",
|
|
987
|
+
" - Build and deploy your app"
|
|
988
|
+
].join("\n"));
|
|
989
|
+
} catch (error) {
|
|
990
|
+
if (error instanceof CommerceSdkValidationError) consola$1.error(error.display());
|
|
991
|
+
consola$1.error(error);
|
|
992
|
+
process.exit(1);
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
//#endregion
|
|
997
|
+
//#region source/commands/index.ts
|
|
998
|
+
const NAMESPACE = "@adobe/aio-commerce-lib-app";
|
|
999
|
+
const [command, subcommand] = process.argv.slice(2);
|
|
1000
|
+
const USAGE = `
|
|
119
1001
|
Usage: ${NAMESPACE} <command> [target]
|
|
120
1002
|
|
|
121
1003
|
Commands:
|
|
1004
|
+
init Initialize the project (recommended for first-time setup)
|
|
1005
|
+
|
|
122
1006
|
generate <target> Generate artifacts
|
|
123
1007
|
all Generate app manifest and runtime actions
|
|
124
|
-
manifest Generate app manifest only
|
|
125
1008
|
actions Generate runtime actions only
|
|
1009
|
+
manifest Generate app manifest only
|
|
1010
|
+
schema Generate configuration schema only
|
|
126
1011
|
|
|
127
1012
|
help Show this help message
|
|
128
1013
|
|
|
129
1014
|
Examples:
|
|
1015
|
+
${NAMESPACE} init
|
|
130
1016
|
${NAMESPACE} generate all
|
|
131
1017
|
${NAMESPACE} generate manifest
|
|
132
1018
|
${NAMESPACE} generate actions
|
|
133
|
-
|
|
1019
|
+
${NAMESPACE} generate schema
|
|
1020
|
+
`;
|
|
1021
|
+
/** Run all generate targets in sequence */
|
|
1022
|
+
async function generateAll() {
|
|
1023
|
+
await exec$5();
|
|
1024
|
+
consola.log.raw("");
|
|
1025
|
+
await exec$4();
|
|
1026
|
+
consola.log.raw("");
|
|
1027
|
+
await exec$3();
|
|
1028
|
+
}
|
|
1029
|
+
/** Command handlers registry mapping command names to their subcommand handlers */
|
|
1030
|
+
const COMMANDS = {
|
|
1031
|
+
init: exec,
|
|
1032
|
+
hooks: {
|
|
1033
|
+
"pre-app-build": exec$1,
|
|
1034
|
+
postinstall: exec$2
|
|
1035
|
+
},
|
|
1036
|
+
generate: {
|
|
1037
|
+
actions: exec$5,
|
|
1038
|
+
manifest: exec$4,
|
|
1039
|
+
schema: exec$3,
|
|
1040
|
+
all: generateAll
|
|
1041
|
+
}
|
|
1042
|
+
};
|
|
1043
|
+
/**
|
|
1044
|
+
* Generic command handler that dispatches to specific command implementations
|
|
1045
|
+
* @param commandName - The name of the command (for error messages)
|
|
1046
|
+
* @param target - The target subcommand to execute
|
|
1047
|
+
* @param handlers - Map of target names to handler functions
|
|
1048
|
+
*/
|
|
1049
|
+
async function handleCommand(commandName, target, handlers) {
|
|
1050
|
+
function invalidTargetError(message) {
|
|
1051
|
+
consola.error(message);
|
|
1052
|
+
consola.info(`Available targets: ${Object.keys(handlers).join(" | ")}`);
|
|
1053
|
+
process.exit(1);
|
|
1054
|
+
}
|
|
1055
|
+
if (!target) invalidTargetError(`No ${commandName} target specified`);
|
|
1056
|
+
const handler = handlers[target];
|
|
1057
|
+
if (!handler) invalidTargetError(`Unknown ${commandName} target: ${target}`);
|
|
1058
|
+
await handler();
|
|
1059
|
+
}
|
|
1060
|
+
async function main() {
|
|
1061
|
+
if (!command || command === "help" || command === "--help" || command === "-h") {
|
|
1062
|
+
consola.log.raw(USAGE);
|
|
1063
|
+
process.exit(0);
|
|
1064
|
+
}
|
|
1065
|
+
try {
|
|
1066
|
+
const handlers = COMMANDS[command];
|
|
1067
|
+
if (!handlers) {
|
|
1068
|
+
consola.error(`Unknown command: ${command}`);
|
|
1069
|
+
consola.log.raw(USAGE);
|
|
1070
|
+
process.exit(1);
|
|
1071
|
+
}
|
|
1072
|
+
if (typeof handlers === "function") {
|
|
1073
|
+
await handlers();
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
await handleCommand(command, subcommand, handlers);
|
|
1077
|
+
} catch (error) {
|
|
1078
|
+
consola.error(stringifyError(error));
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
main();
|
|
1082
|
+
|
|
1083
|
+
//#endregion
|
|
1084
|
+
export { };
|