@alanizcreative/formation-static 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -1
- package/cjs/actions/actions.js +1 -1
- package/cjs/contentful/contentfulData.js +1 -1
- package/cjs/contentful/contentfulDataNormal.js +1 -1
- package/cjs/filters/filters.js +1 -1
- package/cjs/local/localData.js +1 -1
- package/cjs/local/localDataNormal.js +1 -1
- package/cjs/render/render.d.ts +3 -2
- package/cjs/render/render.js +1 -1
- package/cjs/render/renderTypes.d.ts +0 -1
- package/cjs/serverless/Contact/Contact.js +1 -1
- package/cjs/serverless/serverless.js +1 -1
- package/cjs/shortcodes/shortcodes.js +1 -1
- package/cjs/store/store.js +1 -1
- package/cjs/utils/escape/escape.js +1 -1
- package/cjs/utils/excerpt/excerpt.js +1 -1
- package/cjs/utils/image/image.js +1 -1
- package/cjs/utils/image/imageLocal.js +1 -1
- package/cjs/utils/json/json.d.ts +2 -2
- package/cjs/utils/json/json.js +1 -1
- package/cjs/utils/string/string.d.ts +2 -1
- package/cjs/utils/string/string.js +1 -1
- package/cjs/wordpress/wordpressData.js +1 -1
- package/cjs/wordpress/wordpressDataNormal.js +1 -1
- package/lib/actions/actions.js +1 -1
- package/lib/contentful/contentfulData.js +1 -1
- package/lib/contentful/contentfulDataNormal.js +1 -1
- package/lib/filters/filters.js +1 -1
- package/lib/local/localData.js +1 -1
- package/lib/local/localDataNormal.js +1 -1
- package/lib/render/render.d.ts +3 -2
- package/lib/render/render.js +1 -1
- package/lib/render/renderTypes.d.ts +0 -1
- package/lib/serverless/Contact/Contact.js +1 -1
- package/lib/serverless/serverless.js +1 -1
- package/lib/shortcodes/shortcodes.js +1 -1
- package/lib/store/store.js +1 -1
- package/lib/utils/escape/escape.js +1 -1
- package/lib/utils/excerpt/excerpt.js +1 -1
- package/lib/utils/image/image.js +1 -1
- package/lib/utils/image/imageLocal.js +1 -1
- package/lib/utils/json/json.d.ts +2 -2
- package/lib/utils/json/json.js +1 -1
- package/lib/utils/string/string.d.ts +2 -1
- package/lib/utils/string/string.js +1 -1
- package/lib/wordpress/wordpressData.js +1 -1
- package/lib/wordpress/wordpressDataNormal.js +1 -1
- package/package.json +9 -9
- package/cjs/utils/proto/proto.d.ts +0 -2
- package/cjs/utils/proto/proto.js +0 -1
- package/lib/utils/proto/proto.d.ts +0 -2
- package/lib/utils/proto/proto.js +0 -1
package/README.md
CHANGED
|
@@ -130,7 +130,6 @@ npm install -D @alanizcreative/formation-static
|
|
|
130
130
|
- <a href="/src/utils/object/README.md">Object</a>
|
|
131
131
|
- <a href="/src/utils/path/README.md">Path</a>
|
|
132
132
|
- <a href="/src/utils/print/README.md">Print</a>
|
|
133
|
-
- <a href="/src/utils/proto/README.md">Proto</a>
|
|
134
133
|
- <a href="/src/utils/ResponseError/README.md">Response Error</a>
|
|
135
134
|
- <a href="/src/utils/set/README.md">Set</a>
|
|
136
135
|
- <a href="/src/utils/string/README.md">String</a>
|
package/cjs/actions/actions.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setActions=exports.resetActions=exports.doActions=exports.removeAction=exports.addAction=exports.actions=void 0;const set_js_1=require("../utils/set/set.js"),string_js_1=require("../utils/string/string.js"),object_js_1=require("../utils/object/object.js"),function_js_1=require("../utils/function/function.js");let actions=new Map([["renderStart",new Set],["renderEnd",new Set],["renderItemStart",new Set],["renderItemEnd",new Set]]);exports.actions=actions;const addAction=(name,action)=>!(!(0,string_js_1.isStringStrict)(name)||!(0,function_js_1.isFunction)(action))&&((0,set_js_1.isSet)(actions.get(name))||actions.set(name,new Set),actions.get(name)?.add(action),!0);exports.addAction=addAction;const removeAction=(name,action)=>{if(!(0,string_js_1.isStringStrict)(name)||!(0,function_js_1.isFunction)(action))return!1;const actionSet=actions.get(name);return!!(0,set_js_1.isSet)(actionSet)&&actionSet.delete(action)};exports.removeAction=removeAction;const doSequentially=async(callbacks,args)=>{for(const callback of callbacks)await callback(args)},doActions=(name,args,isAsync=!1)=>{const actionSet=actions.get(name);if(!(0,set_js_1.isSetStrict)(actionSet))return;const callbacks=[];for(const callback of actionSet.values())isAsync?callbacks.push(callback):callback(args);isAsync
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setActions=exports.resetActions=exports.doActions=exports.removeAction=exports.addAction=exports.actions=void 0;const set_js_1=require("../utils/set/set.js"),string_js_1=require("../utils/string/string.js"),object_js_1=require("../utils/object/object.js"),function_js_1=require("../utils/function/function.js");let actions=new Map([["renderStart",new Set],["renderEnd",new Set],["renderItemStart",new Set],["renderItemEnd",new Set]]);exports.actions=actions;const addAction=(name,action)=>!(!(0,string_js_1.isStringStrict)(name)||!(0,function_js_1.isFunction)(action))&&((0,set_js_1.isSet)(actions.get(name))||actions.set(name,new Set),actions.get(name)?.add(action),!0);exports.addAction=addAction;const removeAction=(name,action)=>{if(!(0,string_js_1.isStringStrict)(name)||!(0,function_js_1.isFunction)(action))return!1;const actionSet=actions.get(name);return!!(0,set_js_1.isSet)(actionSet)&&actionSet.delete(action)};exports.removeAction=removeAction;const doSequentially=async(callbacks,args)=>{for(const callback of callbacks)await callback(args)},doActions=(name,args,isAsync=!1)=>{const actionSet=actions.get(name);if(!(0,set_js_1.isSetStrict)(actionSet))return;const callbacks=[];for(const callback of actionSet.values())isAsync?callbacks.push(callback):callback(args);return isAsync?doSequentially(callbacks,args).then(result=>result):void 0};exports.doActions=doActions;const resetActions=()=>{exports.actions=actions=new Map([["renderStart",new Set],["renderEnd",new Set],["renderItemStart",new Set],["renderItemEnd",new Set]])};exports.resetActions=resetActions;const setActions=args=>{if(!(0,object_js_1.isObjectStrict)(args))return!1;const newActions=Object.entries(args);return!!newActions.length&&(resetActions(),newActions.forEach(([name,action])=>{action&&addAction(name,action)}),!0)};exports.setActions=setActions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAllContentfulData=exports.getContentfulData=void 0;const contentful_resolve_response_1=__importDefault(require("contentful-resolve-response")),filters_js_1=require("../filters/filters.js"),object_js_1=require("../utils/object/object.js"),string_js_1=require("../utils/string/string.js"),config_js_1=require("../config/config.js"),store_js_1=require("../store/store.js"),contentfulDataNormal_js_1=require("./contentfulDataNormal.js"),getContentfulData=async(key,params)=>{if(!(0,string_js_1.isStringStrict)(key))throw new Error("No key");if(config_js_1.config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await(0,filters_js_1.applyFilters)("cacheData",void 0,cacheDataFilterArgs,!0);if((0,object_js_1.isObject)(cacheData))return structuredClone(cacheData)}const{space:space,devCredential:devCredential,prodCredential:prodCredential,devHost:devHost,prodHost:prodHost,env:env="master"}=config_js_1.config.cms;let accessToken=devCredential,host=devHost;if(config_js_1.config.env.prod&&(accessToken=prodCredential,host=prodHost),!(0,string_js_1.isStringStrict)(space)||!(0,string_js_1.isStringStrict)(accessToken)||!(0,string_js_1.isStringStrict)(host))throw new Error("No credentials");
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAllContentfulData=exports.getContentfulData=void 0;const contentful_resolve_response_1=__importDefault(require("contentful-resolve-response")),filters_js_1=require("../filters/filters.js"),object_js_1=require("../utils/object/object.js"),string_js_1=require("../utils/string/string.js"),config_js_1=require("../config/config.js"),store_js_1=require("../store/store.js"),contentfulDataNormal_js_1=require("./contentfulDataNormal.js"),getContentfulData=async(key,params)=>{if(!(0,string_js_1.isStringStrict)(key))throw new Error("No key");if(config_js_1.config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await(0,filters_js_1.applyFilters)("cacheData",void 0,cacheDataFilterArgs,!0);if((0,object_js_1.isObject)(cacheData))return structuredClone(cacheData)}const{space:space,devCredential:devCredential,prodCredential:prodCredential,devHost:devHost,prodHost:prodHost,env:env="master"}=config_js_1.config.cms;let accessToken=devCredential,host=devHost;if(config_js_1.config.env.prod&&(accessToken=prodCredential,host=prodHost),!(0,string_js_1.isStringStrict)(space)||!(0,string_js_1.isStringStrict)(accessToken)||!(0,string_js_1.isStringStrict)(host))throw new Error("No credentials");const url=new URL(`https://${host}/spaces/${space}/environments/${env}/entries?access_token=${accessToken}`);if((0,object_js_1.isObjectStrict)(params))for(const[key,value]of Object.entries(params))url.searchParams.set(key,value.toString());const resp=await fetch(url.toString()),data=await resp.json();if(!resp.ok){const message=(0,string_js_1.isStringStrict)(data.message)?data.message:"Bad fetch response";throw new Error(message,{cause:data})}const resolvedData=(0,contentful_resolve_response_1.default)(data),newItems=(0,contentfulDataNormal_js_1.normalizeContentfulData)(resolvedData),{total:total,limit:limit,skip:skip}=data,newData={items:newItems,total:total,limit:limit,skip:skip};if(config_js_1.config.env.cache){const cacheDataFilterArgs={key:key,type:"set",data:data};await(0,filters_js_1.applyFilters)("cacheData",newData,cacheDataFilterArgs,!0)}return newData};exports.getContentfulData=getContentfulData;const getAllContentfulData=async args=>{const{serverlessData:serverlessData,previewData:previewData}=(0,object_js_1.isObjectStrict)(args)?args:{};let allData={navigationItem:[],navigation:[],content:{page:[]}};const isServerless=null!=serverlessData,isPreview=null!=previewData,contentfulDataFilterArgs={serverlessData:serverlessData,previewData:previewData},cmsLocales=config_js_1.config.cms.locales||[],defaultLocale=cmsLocales[0],paramLocales=isPreview?[]:[...cmsLocales];if(0===paramLocales.length&¶mLocales.push(""),isServerless||isPreview){let locale,contentType="",id="";if(isServerless){const item=(0,store_js_1.getStoreItem)("slugs")[serverlessData.path];if(item){const[itemId,itemContentType,itemLocale]=item;id=itemId||"",contentType=itemContentType||"",locale=itemLocale||""}}if(isPreview&&(id=previewData.id,contentType=previewData.contentType,locale=previewData.locale),id&&(0,string_js_1.isStringSafe)(contentType)){const key=`serverless_${id}_${contentType}`,params={content_type:contentType,"sys.id":id,include:10};locale&&locale!==defaultLocale&&(params.locale=locale,paramLocales[0]=locale);const data=await getContentfulData(key,params);let{items:items}=data;items=(0,filters_js_1.applyFilters)("contentfulData",items,{...contentfulDataFilterArgs,contentType:contentType}),allData.content[contentType]=items}}if(!isServerless){const partial=config_js_1.config.partialTypes.filter(type=>(0,string_js_1.isStringSafe)(type));for(const contentType of partial){const key=`all_${contentType}`;let newItems=[];for(const locale of paramLocales){const params={content_type:contentType};locale&&locale!==defaultLocale&&(params.locale=locale);const newData=await getContentfulData(key,params);let{items:items}=newData;items=(0,filters_js_1.applyFilters)("contentfulData",items,{...contentfulDataFilterArgs,contentType:contentType}),newItems=[...newItems,...items]}allData[contentType]=newItems}}if(!isServerless&&!isPreview){const whole=config_js_1.config.wholeTypes.filter(type=>(0,string_js_1.isStringSafe)(type));for(const contentType of whole){const key=`all_${contentType}`;let newItems=[];for(const locale of paramLocales){const params={content_type:contentType,include:10};locale&&locale!==defaultLocale&&(params.locale=locale);const newData=await getContentfulData(key,params);let{items:items}=newData;items=(0,filters_js_1.applyFilters)("contentfulData",items,{...contentfulDataFilterArgs,contentType:contentType}),newItems=[...newItems,...items]}allData.content[contentType]=newItems}}return allData=(0,filters_js_1.applyFilters)("allData",allData,{type:"contentful",serverlessData:serverlessData,previewData:previewData}),allData};exports.getAllContentfulData=getAllContentfulData;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.normalizeContentfulData=void 0;const contentType_js_1=require("../utils/contentType/contentType.js"),array_js_1=require("../utils/array/array.js"),object_js_1=require("../utils/object/object.js"),string_js_1=require("../utils/string/string.js"),objectUtils_js_1=require("../utils/object/objectUtils.js"),number_js_1=require("../utils/number/number.js"),config_js_1=require("../config/config.js"),getTag=(type="text")=>({br:"br",hr:"hr",paragraph:"p",blockquote:"blockquote",bold:"b",italic:"i",underline:"u",superscript:"sup",subscript:"sub",code:"code",hyperlink:"a","entry-hyperlink":"a","asset-hyperlink":"a","heading-1":"h1","heading-2":"h2","heading-3":"h3","heading-4":"h4","heading-5":"h5","heading-6":"h6","list-item":"li","unordered-list":"ul","ordered-list":"ol",table:"table","table-row":"tr","table-cell":"td","table-header-cell":"th"}[type]||""),normalizeRichText=items=>{const newItems=[];return items.forEach(item=>{if(!(0,object_js_1.isObjectStrict)(item))return;const{nodeType:nodeType,data:data,value:value,marks:marks,content:content}=item,tag=getTag(nodeType);let contentValue,link,internalLink;if((0,string_js_1.isStringStrict)(value)&&(contentValue=value,contentValue=contentValue.replace(/\n/g,"<br>"),(0,array_js_1.isArrayStrict)(marks))){const markTags=marks.map(m=>getTag(m.type));contentValue=`${markTags.map(m=>`<${m}>`).join("")}${value}${markTags.map(m=>`</${m}>`).join("")}`}if((0,string_js_1.isStringStrict)(content)&&(contentValue=content),(0,array_js_1.isArrayStrict)(content)&&(contentValue=normalizeRichText(content)),(0,object_js_1.isObjectStrict)(data)&&(link=(0,string_js_1.isString)(data.uri)?data.uri:"",(0,object_js_1.isObjectStrict)(data.target))){const target=data.target;"entry-hyperlink"!==nodeType&&"embedded-entry-inline"!==nodeType||(internalLink=target);const url=target.fields?.file?.url;"asset-hyperlink"===nodeType&&(0,string_js_1.isString)(url)&&(link=`https:${url}`)}if(!contentValue)return;const newItem={content:contentValue};return(0,string_js_1.isStringStrict)(tag)&&(newItem.tag=tag),(0,string_js_1.isStringStrict)(link)&&(newItem.link=link),(0,object_js_1.isObjectStrict)(internalLink)&&(newItem.internalLink=normalizeItem(internalLink,[],!0)),newItems.push(newItem)}),newItems},normalizeFile=(file,fields)=>{const type=(0,string_js_1.isString)(file.contentType)?file.contentType:"",format=type?type.split("/")[1]:"";return{url:(0,string_js_1.isString)(file.url)?`https:${file.url}`:"",name:(0,string_js_1.isString)(file.fileName)?file.fileName:"",alt:(0,string_js_1.isString)(fields.description)?fields.description:"",width:(0,number_js_1.isNumber)(file.details?.image?.width)?file.details.image.width:0,height:(0,number_js_1.isNumber)(file.details?.image?.height)?file.details.image.height:0,size:(0,number_js_1.isNumber)(file.details?.size)?file.details.size:0,format:"jpeg"===format?"jpg":format,type:type}},normalizeItem=(item,data,isInternalLink=!1)=>{let newItem={};const itemCopy={...item};(0,string_js_1.isString)(itemCopy.sys?.id)&&(newItem.id=itemCopy.sys.id),(0,string_js_1.isStringStrict)(itemCopy.sys?.locale)&&(newItem.locale=itemCopy.sys.locale);let type="";if((0,string_js_1.isString)(itemCopy.sys?.type)&&(type=itemCopy.sys.type),(0,string_js_1.isString)(itemCopy.sys?.contentType?.sys?.id)&&(type=itemCopy.sys.contentType.sys.id),type&&"Link"!==type&&(newItem.contentType=(0,contentType_js_1.normalizeContentType)(type),(0,string_js_1.isString)(config_js_1.config.renderTypes[type])&&(newItem.renderType=config_js_1.config.renderTypes[type])),(0,array_js_1.isArrayStrict)(itemCopy.metadata?.tags)&&(newItem.metadata={tags:itemCopy.metadata.tags.map(t=>({id:(0,string_js_1.isString)(t.sys?.id)?t.sys.id:""}))}),(0,object_js_1.isObjectStrict)(itemCopy.fields)){const fields=itemCopy.fields,file=fields.file;if((0,object_js_1.isObjectStrict)(file))return{...normalizeFile(file,fields),...newItem};(0,objectUtils_js_1.getObjectKeys)(fields).forEach(prop=>{const field=fields[prop];if(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.normalizeContentfulData=void 0;const contentType_js_1=require("../utils/contentType/contentType.js"),array_js_1=require("../utils/array/array.js"),object_js_1=require("../utils/object/object.js"),string_js_1=require("../utils/string/string.js"),objectUtils_js_1=require("../utils/object/objectUtils.js"),number_js_1=require("../utils/number/number.js"),config_js_1=require("../config/config.js"),getTag=(type="text")=>({br:"br",hr:"hr",paragraph:"p",blockquote:"blockquote",bold:"b",italic:"i",underline:"u",superscript:"sup",subscript:"sub",code:"code",hyperlink:"a","entry-hyperlink":"a","asset-hyperlink":"a","heading-1":"h1","heading-2":"h2","heading-3":"h3","heading-4":"h4","heading-5":"h5","heading-6":"h6","list-item":"li","unordered-list":"ul","ordered-list":"ol",table:"table","table-row":"tr","table-cell":"td","table-header-cell":"th"}[type]||""),normalizeRichText=items=>{const newItems=[];return items.forEach(item=>{if(!(0,object_js_1.isObjectStrict)(item))return;const{nodeType:nodeType,data:data,value:value,marks:marks,content:content}=item,tag=getTag(nodeType);let contentValue,link,internalLink;if((0,string_js_1.isStringStrict)(value)&&(contentValue=value,contentValue=contentValue.replace(/\n/g,"<br>"),(0,array_js_1.isArrayStrict)(marks))){const markTags=marks.map(m=>getTag(m.type));contentValue=`${markTags.map(m=>`<${m}>`).join("")}${value}${markTags.map(m=>`</${m}>`).join("")}`}if((0,string_js_1.isStringStrict)(content)&&(contentValue=content),(0,array_js_1.isArrayStrict)(content)&&(contentValue=normalizeRichText(content)),(0,object_js_1.isObjectStrict)(data)&&(link=(0,string_js_1.isString)(data.uri)?data.uri:"",(0,object_js_1.isObjectStrict)(data.target))){const target=data.target;"entry-hyperlink"!==nodeType&&"embedded-entry-inline"!==nodeType||(internalLink=target);const url=target.fields?.file?.url;"asset-hyperlink"===nodeType&&(0,string_js_1.isString)(url)&&(link=`https:${url}`)}if(!contentValue)return;const newItem={content:contentValue};return(0,string_js_1.isStringStrict)(tag)&&(newItem.tag=tag),(0,string_js_1.isStringStrict)(link)&&(newItem.link=link),(0,object_js_1.isObjectStrict)(internalLink)&&(newItem.internalLink=normalizeItem(internalLink,[],!0)),newItems.push(newItem)}),newItems},normalizeFile=(file,fields)=>{const type=(0,string_js_1.isString)(file.contentType)?file.contentType:"",format=type?type.split("/")[1]:"";return{url:(0,string_js_1.isString)(file.url)?`https:${file.url}`:"",name:(0,string_js_1.isString)(file.fileName)?file.fileName:"",alt:(0,string_js_1.isString)(fields.description)?fields.description:"",width:(0,number_js_1.isNumber)(file.details?.image?.width)?file.details.image.width:0,height:(0,number_js_1.isNumber)(file.details?.image?.height)?file.details.image.height:0,size:(0,number_js_1.isNumber)(file.details?.size)?file.details.size:0,format:"jpeg"===format?"jpg":format,type:type}},normalizeItem=(item,data,isInternalLink=!1)=>{let newItem={};const itemCopy={...item};(0,string_js_1.isString)(itemCopy.sys?.id)&&(newItem.id=itemCopy.sys.id),(0,string_js_1.isStringStrict)(itemCopy.sys?.locale)&&(newItem.locale=itemCopy.sys.locale);let type="";if((0,string_js_1.isString)(itemCopy.sys?.type)&&(type=itemCopy.sys.type),(0,string_js_1.isString)(itemCopy.sys?.contentType?.sys?.id)&&(type=itemCopy.sys.contentType.sys.id),type&&"Link"!==type&&(newItem.contentType=(0,contentType_js_1.normalizeContentType)(type),(0,string_js_1.isString)(config_js_1.config.renderTypes[type])&&(newItem.renderType=config_js_1.config.renderTypes[type])),(0,array_js_1.isArrayStrict)(itemCopy.metadata?.tags)&&(newItem.metadata={tags:itemCopy.metadata.tags.map(t=>({id:(0,string_js_1.isString)(t.sys?.id)?t.sys.id:""}))}),(0,object_js_1.isObjectStrict)(itemCopy.fields)){const fields=itemCopy.fields,file=fields.file;if((0,object_js_1.isObjectStrict)(file))return{...normalizeFile(file,fields),...newItem};(0,objectUtils_js_1.getObjectKeys)(fields).forEach(prop=>{if(!(0,string_js_1.isStringSafe)(prop)||"content"===prop&&isInternalLink)return;const field=fields[prop];if((0,object_js_1.isObjectStrict)(field))if("document"===field.nodeType){const{content:content}=field;(0,array_js_1.isArrayStrict)(content)&&(newItem[prop]=content.map(c=>(0,object_js_1.isObjectStrict)(c)?normalizeItem(c,data,isInternalLink):c))}else newItem[prop]=normalizeItem(field,data,"internalLink"===prop);else(0,array_js_1.isArrayStrict)(field)?newItem[prop]=field.map(f=>(0,object_js_1.isObjectStrict)(f)?normalizeItem(f,data,isInternalLink):f):newItem[prop]=field})}if((0,string_js_1.isString)(itemCopy.nodeType)){const nodeType=itemCopy.nodeType;if("embedded-entry-block"===nodeType||"embedded-asset-block"===nodeType){const content=(0,object_js_1.isObjectStrict)(itemCopy.data?.target)?itemCopy.data.target:{};newItem=normalizeItem(content,data,isInternalLink)}else newItem.renderType="richText",newItem.tag=getTag(itemCopy.nodeType),(0,string_js_1.isString)(itemCopy.content)&&(newItem.content=itemCopy.content),(0,array_js_1.isArrayStrict)(itemCopy.content)&&(newItem.content=normalizeRichText(itemCopy.content))}return newItem},normalizeContentfulData=(data,_newData=[])=>(0,array_js_1.isArrayStrict)(data)?(data.forEach(item=>{(0,object_js_1.isObjectStrict)(item)&&_newData.push(normalizeItem(item,_newData))}),_newData):[];exports.normalizeContentfulData=normalizeContentfulData;
|
package/cjs/filters/filters.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setFilters=exports.resetFilters=exports.applyFilters=exports.removeFilter=exports.addFilter=exports.filters=void 0;const set_js_1=require("../utils/set/set.js"),string_js_1=require("../utils/string/string.js"),object_js_1=require("../utils/object/object.js"),function_js_1=require("../utils/function/function.js");let filters=new Map([["columnProps",new Set],["containerProps",new Set],["formOptionProps",new Set],["formFieldProps",new Set],["formProps",new Set],["richTextProps",new Set],["richTextOutput",new Set],["richTextContentItem",new Set],["richTextContent",new Set],["richTextContentOutput",new Set],["renderItem",new Set],["renderItemData",new Set],["renderContent",new Set],["serverlessResult",new Set],["contactResult",new Set],["cacheData",new Set],["storeData",new Set],["contentfulData",new Set],["wordpressData",new Set],["localData",new Set],["allData",new Set],["slugParts",new Set],["slug",new Set]]);exports.filters=filters;const addFilter=(name,filter)=>!(!(0,string_js_1.isStringStrict)(name)||!(0,function_js_1.isFunction)(filter))&&((0,set_js_1.isSet)(filters.get(name))||filters.set(name,new Set),filters.get(name)?.add(filter),!0);exports.addFilter=addFilter;const removeFilter=(name,filter)=>{if(!(0,string_js_1.isStringStrict)(name)||!(0,function_js_1.isFunction)(filter))return!1;const filterSet=filters.get(name);return!!(0,set_js_1.isSet)(filterSet)&&filterSet.delete(filter)};exports.removeFilter=removeFilter;const applySequentially=async(callbacks,value,args)=>{for(const callback of callbacks)value=await callback(value,args);return value},applyFilters=(name,value,args,isAsync=!1)=>{const filterSet=filters.get(name);if(!(0,set_js_1.isSetStrict)(filterSet))return value;const callbacks=[];for(const callback of filterSet.values())isAsync?callbacks.push(callback):value=callback(value,args);return isAsync?applySequentially(callbacks,value,args).then(newValue=>newValue)
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setFilters=exports.resetFilters=exports.applyFilters=exports.removeFilter=exports.addFilter=exports.filters=void 0;const set_js_1=require("../utils/set/set.js"),string_js_1=require("../utils/string/string.js"),object_js_1=require("../utils/object/object.js"),function_js_1=require("../utils/function/function.js");let filters=new Map([["columnProps",new Set],["containerProps",new Set],["formOptionProps",new Set],["formFieldProps",new Set],["formProps",new Set],["richTextProps",new Set],["richTextOutput",new Set],["richTextContentItem",new Set],["richTextContent",new Set],["richTextContentOutput",new Set],["renderItem",new Set],["renderItemData",new Set],["renderContent",new Set],["serverlessResult",new Set],["contactResult",new Set],["cacheData",new Set],["storeData",new Set],["contentfulData",new Set],["wordpressData",new Set],["localData",new Set],["allData",new Set],["slugParts",new Set],["slug",new Set]]);exports.filters=filters;const addFilter=(name,filter)=>!(!(0,string_js_1.isStringStrict)(name)||!(0,function_js_1.isFunction)(filter))&&((0,set_js_1.isSet)(filters.get(name))||filters.set(name,new Set),filters.get(name)?.add(filter),!0);exports.addFilter=addFilter;const removeFilter=(name,filter)=>{if(!(0,string_js_1.isStringStrict)(name)||!(0,function_js_1.isFunction)(filter))return!1;const filterSet=filters.get(name);return!!(0,set_js_1.isSet)(filterSet)&&filterSet.delete(filter)};exports.removeFilter=removeFilter;const applySequentially=async(callbacks,value,args)=>{for(const callback of callbacks)value=await callback(value,args);return value},applyFilters=(name,value,args,isAsync=!1)=>{const filterSet=filters.get(name);if(!(0,set_js_1.isSetStrict)(filterSet))return value;const callbacks=[];for(const callback of filterSet.values())isAsync?callbacks.push(callback):value=callback(value,args);return isAsync?applySequentially(callbacks,value,args).then(newValue=>newValue):value};exports.applyFilters=applyFilters;const resetFilters=()=>{exports.filters=filters=new Map([["columnProps",new Set],["containerProps",new Set],["formOptionProps",new Set],["formFieldProps",new Set],["formProps",new Set],["richTextProps",new Set],["richTextOutput",new Set],["richTextContentItem",new Set],["richTextContent",new Set],["richTextContentOutput",new Set],["renderItem",new Set],["renderItemData",new Set],["renderContent",new Set],["serverlessResult",new Set],["contactResult",new Set],["cacheData",new Set],["storeData",new Set],["contentfulData",new Set],["wordpressData",new Set],["localData",new Set],["allData",new Set],["slugParts",new Set],["slug",new Set]])};exports.resetFilters=resetFilters;const setFilters=args=>{if(!(0,object_js_1.isObjectStrict)(args))return!1;const newFilters=Object.entries(args);return!!newFilters.length&&(resetFilters(),newFilters.forEach(([name,filter])=>{filter&&addFilter(name,filter)}),!0)};exports.setFilters=setFilters;
|
package/cjs/local/localData.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAllLocalData=exports.getLocalData=void 0;const promises_1=require("node:fs/promises"),node_path_1=require("node:path"),object_js_1=require("../utils/object/object.js"),string_js_1=require("../utils/string/string.js"),filters_js_1=require("../filters/filters.js"),json_js_1=require("../utils/json/json.js"),config_js_1=require("../config/config.js"),localDataNormal_js_1=require("./localDataNormal.js"),getLocalData=async args=>{if(!(0,object_js_1.isObjectStrict)(args))throw new Error("No args");const{key:key,refProps:refProps,imageProps:imageProps,unsetProps:unsetProps}=args;if(!(0,string_js_1.isStringStrict)(key))throw new Error("No key");if(config_js_1.config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await(0,filters_js_1.applyFilters)("cacheData",void 0,cacheDataFilterArgs,!0),cacheItems=cacheData?.data;if((0,object_js_1.isObject)(cacheItems))return structuredClone(cacheItems)}const dir=config_js_1.config.local.dir,data={};let hasData=!1;const files=await(0,promises_1.readdir)((0,node_path_1.resolve)(dir));for(const file of files){const fileExt=(0,node_path_1.extname)(file),fileName=(0,node_path_1.basename)(file,fileExt);if(".json"!==fileExt)continue;const fileContents=await(0,promises_1.readFile)((0,node_path_1.resolve)(dir,file),{encoding:"utf8"})
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAllLocalData=exports.getLocalData=void 0;const promises_1=require("node:fs/promises"),node_path_1=require("node:path"),object_js_1=require("../utils/object/object.js"),string_js_1=require("../utils/string/string.js"),filters_js_1=require("../filters/filters.js"),json_js_1=require("../utils/json/json.js"),config_js_1=require("../config/config.js"),localDataNormal_js_1=require("./localDataNormal.js"),getLocalData=async args=>{if(!(0,object_js_1.isObjectStrict)(args))throw new Error("No args");const{key:key,refProps:refProps,imageProps:imageProps,unsetProps:unsetProps}=args;if(!(0,string_js_1.isStringStrict)(key))throw new Error("No key");if(config_js_1.config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await(0,filters_js_1.applyFilters)("cacheData",void 0,cacheDataFilterArgs,!0),cacheItems=cacheData?.data;if((0,object_js_1.isObject)(cacheItems))return structuredClone(cacheItems)}const dir=config_js_1.config.local.dir,data={};let hasData=!1;const files=await(0,promises_1.readdir)((0,node_path_1.resolve)(dir));for(const file of files){const fileExt=(0,node_path_1.extname)(file),fileName=(0,node_path_1.basename)(file,fileExt);if(".json"!==fileExt||!(0,string_js_1.isStringSafe)(fileName))continue;const fileContents=await(0,promises_1.readFile)((0,node_path_1.resolve)(dir,file),{encoding:"utf8"});data[fileName]=(0,json_js_1.getJson)(fileContents),hasData=!0}if(!hasData)throw new Error("No data");const newData=(0,localDataNormal_js_1.normalizeLocalData)(data,refProps,imageProps,unsetProps);if(config_js_1.config.env.cache){const cacheDataFilterArgs={key:key,type:"set",data:data};await(0,filters_js_1.applyFilters)("cacheData",{data:newData},cacheDataFilterArgs,!0)}return newData};exports.getLocalData=getLocalData;const getAllLocalData=async args=>{const data=await getLocalData({key:"all_file_data",refProps:args?.refProps,imageProps:args?.imageProps,unsetProps:args?.unsetProps});let allData={navigationItem:[],navigation:[],content:{page:[]}};for(const[,value]of Object.entries(data)){const{contentType:contentType}=value;if(!(0,string_js_1.isStringSafe)(contentType))continue;const isPartial=config_js_1.config.partialTypes.includes(contentType),isWhole=config_js_1.config.wholeTypes.includes(contentType);if(!isPartial&&!isWhole)continue;const val=(0,filters_js_1.applyFilters)("localData",value);isPartial&&(null==allData[contentType]&&(allData[contentType]=[]),allData[contentType].push(val)),isWhole&&(null==allData.content[contentType]&&(allData.content[contentType]=[]),allData.content[contentType].push(val))}return allData=(0,filters_js_1.applyFilters)("allData",allData,{type:"local"}),allData};exports.getAllLocalData=getAllLocalData;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.normalizeLocalData=void 0;const object_js_1=require("../utils/object/object.js"),array_js_1=require("../utils/array/array.js"),string_js_1=require("../utils/string/string.js"),store_js_1=require("../store/store.js"),normalizeLocalRefs=(data,refData,imageData,refProps=["internalLink","term","taxonomy"],imageProps=["image"],unsetProps=["content"],contentType)=>{const newData=(0,array_js_1.isArray)(data)?[]:{},isTemplate="contentTemplate"===data.renderType,isNavigation="navigation"===contentType,isNavigationItem="navigationItem"===contentType;for(const[key,value]of Object.entries(data)){const isRef=refProps.includes(key),isImage=imageProps.includes(key),isStr=(0,string_js_1.isStringStrict)(value),isArr=(0,array_js_1.isArrayStrict)(value);let newValue=value;isTemplate&&"content"===key&&isArr&&(newValue=value.map(item=>(0,string_js_1.isStringStrict)(item)?{...refData[item]}:item)),(isNavigation&&"items"===key||isNavigationItem&&"children"===key)&&isArr&&(newValue=value.map(id=>(0,string_js_1.isStringStrict)(id)?{id:id,title:refData[id]?.title}:null).filter(Boolean)),isImage&&isStr&&(newValue=imageData[value]?{...imageData[value]}:null),isRef&&isStr&&(newValue={...refData[value]},unsetProps.forEach(prop=>{newValue[prop]&&(newValue[prop]=void 0)})),isRef&&(0,array_js_1.isArrayStrict)(value)&&(newValue=value.map(refKey=>{if(!(0,string_js_1.isStringStrict)(refKey))return null;const ref=refData[refKey];if(!(0,object_js_1.isObjectStrict)(ref))return null;const newRef={...ref};return unsetProps.forEach(prop=>{newRef[prop]&&(newRef[prop]=void 0)}),newRef}).filter(Boolean)),(0,object_js_1.isObject)(newValue)&&(newValue=normalizeLocalRefs(newValue,refData,imageData,refProps,imageProps,unsetProps)),newData[key]=newValue}return newData},normalizeLocalData=(data,refProps,imageProps,unsetProps)=>{const newData={},imageMeta=(0,store_js_1.getStoreItem)("imageMeta"),refData={};for(const[key,item]of Object.entries(data))(0,object_js_1.isObjectStrict)(item)
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.normalizeLocalData=void 0;const object_js_1=require("../utils/object/object.js"),array_js_1=require("../utils/array/array.js"),string_js_1=require("../utils/string/string.js"),store_js_1=require("../store/store.js"),normalizeLocalRefs=(data,refData,imageData,refProps=["internalLink","term","taxonomy"],imageProps=["image"],unsetProps=["content"],contentType)=>{const newData=(0,array_js_1.isArray)(data)?[]:{},isTemplate="contentTemplate"===data.renderType,isNavigation="navigation"===contentType,isNavigationItem="navigationItem"===contentType;for(const[key,value]of Object.entries(data)){if(!(0,string_js_1.isStringSafe)(key))continue;const isRef=refProps.includes(key),isImage=imageProps.includes(key),isStr=(0,string_js_1.isStringStrict)(value),isArr=(0,array_js_1.isArrayStrict)(value);let newValue=value;isTemplate&&"content"===key&&isArr&&(newValue=value.map(item=>(0,string_js_1.isStringStrict)(item)?{...refData[item]}:item)),(isNavigation&&"items"===key||isNavigationItem&&"children"===key)&&isArr&&(newValue=value.map(id=>(0,string_js_1.isStringStrict)(id)?{id:id,title:refData[id]?.title}:null).filter(Boolean)),isImage&&isStr&&(newValue=imageData[value]?{...imageData[value]}:null),isRef&&isStr&&(newValue={...refData[value]},unsetProps.forEach(prop=>{newValue[prop]&&(newValue[prop]=void 0)})),isRef&&(0,array_js_1.isArrayStrict)(value)&&(newValue=value.map(refKey=>{if(!(0,string_js_1.isStringStrict)(refKey))return null;const ref=refData[refKey];if(!(0,object_js_1.isObjectStrict)(ref))return null;const newRef={...ref};return unsetProps.forEach(prop=>{newRef[prop]&&(newRef[prop]=void 0)}),newRef}).filter(Boolean)),(0,object_js_1.isObject)(newValue)&&(newValue=normalizeLocalRefs(newValue,refData,imageData,refProps,imageProps,unsetProps)),newData[key]=newValue}return newData},normalizeLocalData=(data,refProps,imageProps,unsetProps)=>{const newData={},imageMeta=(0,store_js_1.getStoreItem)("imageMeta"),refData={};for(const[key,item]of Object.entries(data)){if(!(0,object_js_1.isObjectStrict)(item)||!(0,string_js_1.isStringSafe)(key))continue;const{contentType:contentType}=item;contentType&&!(0,string_js_1.isStringSafe)(contentType)||(refData[key]={id:key,...item})}for(const[key,item]of Object.entries(refData))newData[key]=normalizeLocalRefs(item,refData,imageMeta,refProps?.filter(prop=>(0,string_js_1.isStringSafe)(prop)),imageProps?.filter(prop=>(0,string_js_1.isStringSafe)(prop)),unsetProps?.filter(prop=>(0,string_js_1.isStringSafe)(prop)),item.contentType);return newData};exports.normalizeLocalData=normalizeLocalData;
|
package/cjs/render/render.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { RenderContentArgs, RenderItemArgs, RenderItemReturn, RenderArgs, RenderReturn, RenderFunctions, RenderLayout, RenderHttpError, RenderNavigation, RenderFunctionsArgs } from './renderTypes.js';
|
|
1
|
+
import type { RenderContentArgs, RenderItem, RenderItemArgs, RenderItemReturn, RenderArgs, RenderReturn, RenderFunctions, RenderLayout, RenderHttpError, RenderNavigation, RenderFunctionsArgs, RenderMeta } from './renderTypes.js';
|
|
2
2
|
import type { RefString } from '../global/globalTypes.js';
|
|
3
3
|
declare let renderFunctions: RenderFunctions;
|
|
4
4
|
declare let renderLayout: RenderLayout;
|
|
@@ -6,6 +6,7 @@ declare let renderHttpError: RenderHttpError;
|
|
|
6
6
|
declare let renderNavigation: RenderNavigation;
|
|
7
7
|
declare const setRenderFunctions: (args: RenderFunctionsArgs) => boolean;
|
|
8
8
|
declare const renderContent: (args: RenderContentArgs, _html?: RefString) => Promise<string>;
|
|
9
|
+
declare const renderMeta: (item: RenderItem) => RenderMeta;
|
|
9
10
|
declare const renderItem: (args: RenderItemArgs, _contentType?: string) => Promise<RenderItemReturn | null>;
|
|
10
11
|
declare const render: (args: RenderArgs) => Promise<RenderReturn[] | RenderReturn>;
|
|
11
|
-
export { render, renderItem, renderContent, renderFunctions, renderLayout, renderNavigation, renderHttpError, setRenderFunctions };
|
|
12
|
+
export { render, renderItem, renderMeta, renderContent, renderFunctions, renderLayout, renderNavigation, renderHttpError, setRenderFunctions };
|
package/cjs/render/render.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setRenderFunctions=exports.renderHttpError=exports.renderNavigation=exports.renderLayout=exports.renderFunctions=exports.renderContent=exports.renderItem=exports.render=void 0;const actions_js_1=require("../actions/actions.js"),filters_js_1=require("../filters/filters.js"),link_js_1=require("../utils/link/link.js"),string_js_1=require("../utils/string/string.js"),array_js_1=require("../utils/array/array.js"),object_js_1=require("../utils/object/object.js"),function_js_1=require("../utils/function/function.js"),shortcodes_js_1=require("../shortcodes/shortcodes.js"),tag_js_1=require("../utils/tag/tag.js"),store_js_1=require("../store/store.js"),redirects_js_1=require("../redirects/redirects.js"),scripts_js_1=require("../scripts/scripts.js"),config_js_1=require("../config/config.js");let renderFunctions={};exports.renderFunctions=renderFunctions;let renderLayout=()=>"";exports.renderLayout=renderLayout;let renderHttpError=()=>"";exports.renderHttpError=renderHttpError;let renderNavigation=()=>{};exports.renderNavigation=renderNavigation;const setRenderFunctions=args=>{if(!(0,object_js_1.isObjectStrict)(args))return!1;const{functions:functions,layout:layout,navigation:navigation,httpError:httpError}=args;return!(!(0,object_js_1.isObjectStrict)(functions)||!(0,function_js_1.isFunction)(layout))&&(exports.renderFunctions=renderFunctions={...functions},exports.renderLayout=renderLayout=layout,(0,function_js_1.isFunction)(navigation)&&(exports.renderNavigation=renderNavigation=navigation),(0,function_js_1.isFunction)(httpError)&&(exports.renderHttpError=renderHttpError=httpError),!0)};exports.setRenderFunctions=setRenderFunctions;const getContentTemplate=(content,templates=[],named=!1)=>{if(!(0,array_js_1.isArrayStrict)(content))return{content:[],namedContent:{},templates:[]};const namedContent={},newContent=content.map(c=>(named&&(0,string_js_1.isString)(c.name)&&(namedContent[c.name]={...c}),(0,tag_js_1.tagExists)(c,"template")?(templates.push({...c}),{metadata:{tags:[{id:"templateBreak"}]}}):c));return{namedContent:namedContent,content:newContent,templates:structuredClone(templates)}},mapContentTemplate=(templates,content=[],namedContent={},named=!1)=>{if(!(0,array_js_1.isArrayStrict)(templates))return templates;const lastTemplateIndex=templates.length-1;return templates.forEach((t,i)=>{content[0]&&(0,tag_js_1.tagExists)(content[0],"templateBreak")&&content.length>=1&&content.shift();if((0,tag_js_1.tagExists)(t,"templateOptional")&&i===lastTemplateIndex&&!content.length)return void templates.pop();const isSlot=(0,tag_js_1.tagExists)(t,"templateSlot");let children=t.content;if((0,array_js_1.isArrayStrict)(children)&&!isSlot&&!named){let repeat;const newChildren=[...children],repeatIndex=children.findIndex(c=>{const isRepeat=(0,tag_js_1.tagExists)(c,"templateRepeat");return isRepeat&&(repeat=c),isRepeat});if(-1!==repeatIndex&&repeat){let breakIndex=content.findIndex(c=>(0,tag_js_1.tagExists)(c,"templateBreak"));breakIndex=-1===breakIndex?content.length:breakIndex;let insertIndex=repeatIndex;for(let j=insertIndex;j<breakIndex-1;j+=1)newChildren.splice(insertIndex,0,structuredClone(repeat)),insertIndex=j}children=newChildren}if(isSlot&&content.length>=1){let fill=null;return fill=named?namedContent[t.name]:content.shift(),void(fill&&(templates[i]=fill))}(0,array_js_1.isArray)(children)&&templates[i]&&(templates[i].content=mapContentTemplate(children,content,namedContent,named))}),templates},renderContent=async(args,_html={ref:""})=>{if(!(0,object_js_1.isObjectStrict)(args))return _html.ref;const{content:content,serverlessData:serverlessData,previewData:previewData,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,parents:parents,depth:depth=0}=args;let{headingsIndex:headingsIndex=-1}=args;if(!(0,array_js_1.isArrayStrict)(content))return _html.ref;for(const item of content){if(!(0,object_js_1.isObjectStrict)(item))continue;const props={...item},renderType=(0,string_js_1.isString)(props.renderType)?props.renderType:"",isRichText="richText"===renderType;let childrenArr,children=props.content;if("contentTemplate"===renderType){const isNamed=(0,tag_js_1.tagExists)(item,"templateNamed"),template=getContentTemplate((0,array_js_1.isArray)(props.content)?props.content:[],[],isNamed);children=mapContentTemplate(template.templates,template.content,template.namedContent,isNamed)}let childrenStr="";(0,array_js_1.isArrayStrict)(children)&&!isRichText&&(childrenArr=children),(0,string_js_1.isStringStrict)(children)&&!isRichText&&(childrenStr=children),"content"===renderType&&0===depth&&(headingsIndex=itemHeadings.push([])-1);let renderStart="",renderEnd="",filterType="",filterArgs={};const renderFunction=renderFunctions[renderType];if((0,function_js_1.isFunction)(renderFunction)){childrenArr&&(props.content=void 0);const renderArgs={args:props,parents:parents,itemData:itemData,itemContains:itemContains,serverlessData:serverlessData,previewData:previewData};childrenArr&&(renderArgs.children=childrenArr),"richText"===renderType&&(renderArgs.headings=itemHeadings[headingsIndex]);const renderOutput=await renderFunction(renderArgs);if((0,array_js_1.isArrayStrict)(renderOutput)){const[start,end]=renderOutput;(0,string_js_1.isString)(start)&&(renderStart=start),(0,string_js_1.isString)(end)&&(renderEnd=end)}(0,string_js_1.isString)(renderOutput)&&(renderStart=renderOutput,childrenArr=void 0),itemContains.add(renderType),filterType=renderType,filterArgs={...props,content:void 0}}const renderContentFilterArgs={renderType:filterType,args:filterArgs},[filterRenderStart,filterRenderEnd]=await(0,filters_js_1.applyFilters)("renderContent",[renderStart,renderEnd],renderContentFilterArgs,!0);if(renderStart=filterRenderStart,renderEnd=filterRenderEnd,_html.ref+=renderStart+childrenStr,childrenArr){const parentsCopy=[...parents];renderType&&parentsCopy.unshift({renderType:renderType,args:{...props,content:void 0,parents:void 0}}),await renderContent({content:childrenArr,serverlessData:serverlessData,previewData:previewData,parents:parentsCopy,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,headingsIndex:headingsIndex,depth:depth+1},_html)}_html.ref+=renderEnd}return _html.ref};exports.renderContent=renderContent;const renderItem=async(args,_contentType)=>{if(!(0,object_js_1.isObjectStrict)(args))return null;const{item:item,serverlessData:serverlessData,previewData:previewData}=args;if(!(0,object_js_1.isObjectStrict)(item))return null;const contentType=item.contentType;if(!(0,string_js_1.isStringStrict)(contentType))return null;if("taxonomy"===contentType&&!0!==item.isPage)return null;const id=item.id;if(!(0,string_js_1.isStringStrict)(id))return null;if(!(0,string_js_1.isStringStrict)(item.slug))return null;let serverlessRender=!1;const itemContains=new Set,itemHeadings=[];scripts_js_1.scripts.deps.clear(),scripts_js_1.scripts.item.clear(),scripts_js_1.scripts.meta={},scripts_js_1.styles.deps.clear(),scripts_js_1.styles.item.clear();const renderItemStartArgs={id:id,itemData:{...item},contentType:contentType,itemContains:new Set,itemHeadings:[],serverlessData:serverlessData,previewData:previewData};await(0,actions_js_1.doActions)("renderItemStart",renderItemStartArgs,!0);const title=item.title,meta={title:"",description:"",url:"",image:"",canonical:"",prev:"",next:"",index:!0,isIndex:!1,...item.meta};(0,string_js_1.isStringStrict)(item.metaTitle)&&(meta.title=item.metaTitle),(0,string_js_1.isStringStrict)(item.metaDescription)&&(meta.description=item.metaDescription),(0,string_js_1.isStringStrict)(item.metaImage?.url)&&(meta.image=item.metaImage.url),!(0,string_js_1.isStringStrict)(meta.title)&&(0,string_js_1.isStringStrict)(title)&&(meta.title=title);const slugArgs={id:id,contentType:contentType,slug:item.slug,returnParents:!0,itemData:item,page:0},s=(0,link_js_1.getSlug)(slugArgs,!0),slug=s.slug,slugIsHtml=slug.endsWith(".html"),permalink=(0,link_js_1.getPermalink)(slug,!slugIsHtml),parents=s.parents;meta.url=permalink,meta.canonical=permalink;const taxonomy="term"===contentType?item.taxonomy:"taxonomy"===contentType?item:null;item.baseUrl=permalink,item.baseType=(0,object_js_1.isObjectStrict)(taxonomy)&&(0,array_js_1.isArrayStrict)(taxonomy.contentTypes)?taxonomy.contentTypes:contentType;let formattedSlug="index"!==slug&&""!==slug?`/${slug}/`:"/";slugIsHtml&&(formattedSlug=slug);const index="index"===item.slug;let itemServerlessData;if(meta.isIndex=index,(0,object_js_1.isObjectStrict)(serverlessData)){if(!(serverlessData.path===formattedSlug&&null!=serverlessData.query))return{serverlessRender:!1};itemServerlessData=serverlessData}const itemData={...item};itemData.id=id,itemData.parents=parents,itemData.content=void 0;let contentOutput="";const contentData=item.content;(0,string_js_1.isStringStrict)(contentData)&&(contentOutput=contentData),(0,array_js_1.isArrayStrict)(contentData)&&(contentOutput=await renderContent({content:contentData,serverlessData:itemServerlessData,parents:[],itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,previewData:previewData})),contentOutput=await(0,shortcodes_js_1.doShortcodes)(contentOutput,itemData);const pag=itemData.pagination;if((0,object_js_1.isObjectStrict)(pag)){const{currentParams:currentParams,prevParams:prevParams,nextParams:nextParams}=pag,currentParamsStr=new URLSearchParams(currentParams).toString();if(currentParamsStr&&(meta.canonicalParams=`?${currentParamsStr}`),(0,string_js_1.isStringStrict)(pag.title)&&(meta.paginationTitle=pag.title),pag.prev){const prevSlugArgs={...slugArgs,params:prevParams},p=(0,link_js_1.getSlug)(prevSlugArgs,!0);meta.prev=(0,link_js_1.getPermalink)(p.slug,1===pag.prev&&!prevParams)}if(pag.next){const nextSlugArgs={...slugArgs,params:nextParams},n=(0,link_js_1.getSlug)(nextSlugArgs,!0);meta.next=(0,link_js_1.getPermalink)(n.slug,!1)}serverlessRender=!0}const cmsLocales=config_js_1.config.cms.locales,slugData=[id,(0,string_js_1.isStringStrict)(_contentType)?_contentType:contentType];if((0,string_js_1.isStringStrict)(item.locale)&&cmsLocales){const locale=item.locale;cmsLocales.includes(locale)&&locale!==cmsLocales[0]&&slugData.push(locale)}(config_js_1.config.env.dev||config_js_1.config.env.prod&&serverlessRender)&&(0,store_js_1.setStoreItem)("slugs",slugData,slugIsHtml?`/${slug}`:formattedSlug);const layoutArgs={id:id,meta:meta,contentType:contentType,content:contentOutput,slug:formattedSlug,itemContains:itemContains,itemHeadings:itemHeadings,itemData:itemData,serverlessData:serverlessData,previewData:previewData};let layoutOutput=await renderLayout(layoutArgs);const renderItemFilterArgs={id:id,contentType:contentType,slug:formattedSlug,output:layoutOutput,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,serverlessData:serverlessData,previewData:previewData};layoutOutput=await(0,filters_js_1.applyFilters)("renderItem",layoutOutput,renderItemFilterArgs,!0);const renderItemEndArgs={id:id,contentType:contentType,slug:formattedSlug,output:layoutOutput,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,serverlessData:serverlessData,previewData:previewData};return await(0,actions_js_1.doActions)("renderItemEnd",renderItemEndArgs,!0),{serverlessRender:serverlessRender,itemData:itemData,data:{slug:formattedSlug,output:layoutOutput}}};exports.renderItem=renderItem;const render=async args=>{if(!(0,object_js_1.isObjectStrict)(args))return[];const{allData:allData,serverlessData:serverlessData,previewData:previewData}=args,isServerless=null!=serverlessData,isPreview=null!=previewData;if(scripts_js_1.scripts.deps.clear(),scripts_js_1.scripts.item.clear(),scripts_js_1.scripts.meta={},scripts_js_1.styles.deps.clear(),scripts_js_1.styles.item.clear(),!(0,object_js_1.isObjectStrict)(allData))return[];const{redirect:redirect,content:content}=allData;await(0,actions_js_1.doActions)("renderStart",args,!0);const data=[];isServerless||(0,store_js_1.setStoreData)(allData),await renderNavigation({navigations:(0,store_js_1.getStoreItem)("navigations"),items:(0,store_js_1.getStoreItem)("navigationItems")}),(0,redirects_js_1.setRedirects)(redirect);for(const[contentType,contentItems]of Object.entries(content))if((0,array_js_1.isArrayStrict)(contentItems))for(const contentItem of contentItems){const item=await renderItem({item:await(0,filters_js_1.applyFilters)("renderItemData",contentItem,{contentType:contentType},!0),serverlessData:serverlessData,previewData:previewData},contentType);if(!item)continue;const{serverlessRender:serverlessRender=!1,data:itemData}=item;itemData&&(data.push(itemData),serverlessRender&&!isServerless&&(0,store_js_1.setStoreItem)("serverless",["reload"],itemData.slug))}const[outputItem]=data,output=(isServerless||isPreview)&&outputItem?outputItem:data;return await(0,actions_js_1.doActions)("renderEnd",{...args,data:output},!0),output};exports.render=render;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setRenderFunctions=exports.renderHttpError=exports.renderNavigation=exports.renderLayout=exports.renderFunctions=exports.renderContent=exports.renderMeta=exports.renderItem=exports.render=void 0;const actions_js_1=require("../actions/actions.js"),filters_js_1=require("../filters/filters.js"),link_js_1=require("../utils/link/link.js"),string_js_1=require("../utils/string/string.js"),array_js_1=require("../utils/array/array.js"),object_js_1=require("../utils/object/object.js"),function_js_1=require("../utils/function/function.js"),shortcodes_js_1=require("../shortcodes/shortcodes.js"),tag_js_1=require("../utils/tag/tag.js"),store_js_1=require("../store/store.js"),redirects_js_1=require("../redirects/redirects.js"),scripts_js_1=require("../scripts/scripts.js"),config_js_1=require("../config/config.js");let renderFunctions={};exports.renderFunctions=renderFunctions;let renderLayout=()=>"";exports.renderLayout=renderLayout;let renderHttpError=()=>"";exports.renderHttpError=renderHttpError;let renderNavigation=()=>{};exports.renderNavigation=renderNavigation;const setRenderFunctions=args=>{if(!(0,object_js_1.isObjectStrict)(args))return!1;const{functions:functions,layout:layout,navigation:navigation,httpError:httpError}=args;return!(!(0,object_js_1.isObjectStrict)(functions)||!(0,function_js_1.isFunction)(layout))&&(exports.renderFunctions=renderFunctions={...functions},exports.renderLayout=renderLayout=layout,(0,function_js_1.isFunction)(navigation)&&(exports.renderNavigation=renderNavigation=navigation),(0,function_js_1.isFunction)(httpError)&&(exports.renderHttpError=renderHttpError=httpError),!0)};exports.setRenderFunctions=setRenderFunctions;const getContentTemplate=(content,templates=[],named=!1)=>{if(!(0,array_js_1.isArrayStrict)(content))return{content:[],namedContent:{},templates:[]};const namedContent={},newContent=content.map(c=>{const{name:name}=c;return named&&(0,string_js_1.isStringSafe)(name)&&(namedContent[name]={...c}),(0,tag_js_1.tagExists)(c,"template")?(templates.push({...c}),{metadata:{tags:[{id:"templateBreak"}]}}):c});return{namedContent:namedContent,content:newContent,templates:structuredClone(templates)}},mapContentTemplate=(templates,content=[],namedContent={},named=!1)=>{if(!(0,array_js_1.isArrayStrict)(templates))return templates;const lastTemplateIndex=templates.length-1;return templates.forEach((t,i)=>{content[0]&&(0,tag_js_1.tagExists)(content[0],"templateBreak")&&content.length>=1&&content.shift();if((0,tag_js_1.tagExists)(t,"templateOptional")&&i===lastTemplateIndex&&!content.length)return void templates.pop();const isSlot=(0,tag_js_1.tagExists)(t,"templateSlot");let children=t.content;if((0,array_js_1.isArrayStrict)(children)&&!isSlot&&!named){let repeat;const newChildren=[...children],repeatIndex=children.findIndex(c=>{const isRepeat=(0,tag_js_1.tagExists)(c,"templateRepeat");return isRepeat&&(repeat=c),isRepeat});if(-1!==repeatIndex&&repeat){let breakIndex=content.findIndex(c=>(0,tag_js_1.tagExists)(c,"templateBreak"));breakIndex=-1===breakIndex?content.length:breakIndex;let insertIndex=repeatIndex;for(let j=insertIndex;j<breakIndex-1;j+=1)newChildren.splice(insertIndex,0,structuredClone(repeat)),insertIndex=j}children=newChildren}if(isSlot&&content.length>=1){let fill=null;return fill=named?namedContent[t.name]:content.shift(),void(fill&&(templates[i]=fill))}(0,array_js_1.isArray)(children)&&templates[i]&&(templates[i].content=mapContentTemplate(children,content,namedContent,named))}),templates},renderContent=async(args,_html={ref:""})=>{if(!(0,object_js_1.isObjectStrict)(args))return _html.ref;const{content:content,serverlessData:serverlessData,previewData:previewData,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,parents:parents,depth:depth=0}=args;let{headingsIndex:headingsIndex=-1}=args;if(!(0,array_js_1.isArrayStrict)(content))return _html.ref;for(const item of content){if(!(0,object_js_1.isObjectStrict)(item))continue;const props={...item},renderType=(0,string_js_1.isString)(props.renderType)?props.renderType:"",isRichText="richText"===renderType;let childrenArr,children=props.content;if("contentTemplate"===renderType){const isNamed=(0,tag_js_1.tagExists)(item,"templateNamed"),template=getContentTemplate((0,array_js_1.isArray)(props.content)?props.content:[],[],isNamed);children=mapContentTemplate(template.templates,template.content,template.namedContent,isNamed)}let childrenStr="";(0,array_js_1.isArrayStrict)(children)&&!isRichText&&(childrenArr=children),(0,string_js_1.isStringStrict)(children)&&!isRichText&&(childrenStr=children),"content"===renderType&&0===depth&&(headingsIndex=itemHeadings.push([])-1);let renderStart="",renderEnd="",filterType="",filterArgs={};const renderFunction=renderFunctions[renderType];if((0,function_js_1.isFunction)(renderFunction)){childrenArr&&(props.content=void 0);const renderArgs={args:props,parents:parents,itemData:itemData,itemContains:itemContains,serverlessData:serverlessData,previewData:previewData};childrenArr&&(renderArgs.children=childrenArr),"richText"===renderType&&(renderArgs.headings=itemHeadings[headingsIndex]);const renderOutput=await renderFunction(renderArgs);if((0,array_js_1.isArrayStrict)(renderOutput)){const[start,end]=renderOutput;(0,string_js_1.isString)(start)&&(renderStart=start),(0,string_js_1.isString)(end)&&(renderEnd=end)}(0,string_js_1.isString)(renderOutput)&&(renderStart=renderOutput,childrenArr=void 0),itemContains.add(renderType),filterType=renderType,filterArgs={...props,content:void 0}}const renderContentFilterArgs={renderType:filterType,args:filterArgs},[filterRenderStart,filterRenderEnd]=await(0,filters_js_1.applyFilters)("renderContent",[renderStart,renderEnd],renderContentFilterArgs,!0);if(renderStart=filterRenderStart,renderEnd=filterRenderEnd,_html.ref+=renderStart+childrenStr,childrenArr){const parentsCopy=[...parents];renderType&&parentsCopy.unshift({renderType:renderType,args:{...props,content:void 0,parents:void 0}}),await renderContent({content:childrenArr,serverlessData:serverlessData,previewData:previewData,parents:parentsCopy,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,headingsIndex:headingsIndex,depth:depth+1},_html)}_html.ref+=renderEnd}return _html.ref};exports.renderContent=renderContent;const renderMeta=item=>{const{title:title,slug:slug,baseUrl:baseUrl,pagination:pagination}=item,meta={title:title,description:"",url:baseUrl,image:"",canonical:baseUrl,prev:"",next:"",index:!0,isIndex:"index"===slug,...item.meta};if((0,string_js_1.isStringStrict)(item.metaTitle)&&(meta.title=item.metaTitle),(0,string_js_1.isStringStrict)(item.metaDescription)&&(meta.description=item.metaDescription),(0,string_js_1.isStringStrict)(item.metaImage?.url)&&(meta.image=item.metaImage.url),!(0,object_js_1.isObjectStrict)(pagination))return meta;const{title:paginationTitle,prev:paginationPrev,next:paginationNext,currentParams:currentParams,prevParams:prevParams,nextParams:nextParams}=pagination,currentParamsStr=new URLSearchParams(currentParams).toString();if(currentParamsStr&&(meta.canonical=`${baseUrl}?${currentParamsStr}`),(0,string_js_1.isStringStrict)(paginationTitle)&&(meta.paginationTitle=paginationTitle),paginationPrev){const prevParamsStr=new URLSearchParams(prevParams).toString();meta.prev=`${baseUrl}${prevParamsStr?`?${prevParamsStr}`:""}`}if(paginationNext){const nextParamsStr=new URLSearchParams(nextParams).toString();meta.next=`${baseUrl}?${nextParamsStr}`}return meta};exports.renderMeta=renderMeta;const renderItem=async(args,_contentType)=>{if(!(0,object_js_1.isObjectStrict)(args))return null;const{item:item,serverlessData:serverlessData,previewData:previewData}=args;if(!(0,object_js_1.isObjectStrict)(item))return null;const contentType=item.contentType;if(!(0,string_js_1.isStringStrict)(contentType))return null;if("taxonomy"===contentType&&!0!==item.isPage)return null;const id=item.id;if(!(0,string_js_1.isStringStrict)(id))return null;if(!(0,string_js_1.isStringStrict)(item.slug))return null;let serverlessRender=!1;const itemContains=new Set,itemHeadings=[];scripts_js_1.scripts.deps.clear(),scripts_js_1.scripts.item.clear(),scripts_js_1.scripts.meta={},scripts_js_1.styles.deps.clear(),scripts_js_1.styles.item.clear();const renderItemStartArgs={id:id,itemData:{...item},contentType:contentType,itemContains:new Set,itemHeadings:[],serverlessData:serverlessData,previewData:previewData};await(0,actions_js_1.doActions)("renderItemStart",renderItemStartArgs,!0);const slugArgs={id:id,contentType:contentType,slug:item.slug,returnParents:!0,itemData:item,page:0},s=(0,link_js_1.getSlug)(slugArgs,!0),slug=s.slug,slugIsHtml=slug.endsWith(".html"),permalink=(0,link_js_1.getPermalink)(slug,!slugIsHtml),parents=s.parents,taxonomy="term"===contentType?item.taxonomy:"taxonomy"===contentType?item:null;item.baseUrl=permalink,item.baseType=(0,object_js_1.isObjectStrict)(taxonomy)&&(0,array_js_1.isArrayStrict)(taxonomy.contentTypes)?taxonomy.contentTypes:contentType;let itemServerlessData,formattedSlug="index"!==slug&&""!==slug?`/${slug}/`:"/";if(slugIsHtml&&(formattedSlug=slug),(0,object_js_1.isObjectStrict)(serverlessData)){if(!(serverlessData.path===formattedSlug&&null!=serverlessData.query))return{serverlessRender:!1};itemServerlessData=serverlessData}const itemData={...item};itemData.id=id,itemData.parents=parents,itemData.content=void 0;let contentOutput="";const contentData=item.content;(0,string_js_1.isStringStrict)(contentData)&&(contentOutput=contentData),(0,array_js_1.isArrayStrict)(contentData)&&(contentOutput=await renderContent({content:contentData,serverlessData:itemServerlessData,parents:[],itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,previewData:previewData})),contentOutput=await(0,shortcodes_js_1.doShortcodes)(contentOutput,itemData),(0,object_js_1.isObjectStrict)(itemData.pagination)&&(serverlessRender=!0);const cmsLocales=config_js_1.config.cms.locales,slugData=[id,(0,string_js_1.isStringStrict)(_contentType)?_contentType:contentType];if((0,string_js_1.isStringStrict)(item.locale)&&cmsLocales){const locale=item.locale;cmsLocales.includes(locale)&&locale!==cmsLocales[0]&&slugData.push(locale)}(config_js_1.config.env.dev||config_js_1.config.env.prod&&serverlessRender)&&(0,store_js_1.setStoreItem)("slugs",slugData,slugIsHtml?`/${slug}`:formattedSlug);const layoutArgs={id:id,meta:renderMeta(itemData),contentType:contentType,content:contentOutput,slug:formattedSlug,itemContains:itemContains,itemHeadings:itemHeadings,itemData:itemData,serverlessData:serverlessData,previewData:previewData};let layoutOutput=await renderLayout(layoutArgs);const renderItemFilterArgs={id:id,contentType:contentType,slug:formattedSlug,output:layoutOutput,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,serverlessData:serverlessData,previewData:previewData};layoutOutput=await(0,filters_js_1.applyFilters)("renderItem",layoutOutput,renderItemFilterArgs,!0);const renderItemEndArgs={id:id,contentType:contentType,slug:formattedSlug,output:layoutOutput,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,serverlessData:serverlessData,previewData:previewData};return await(0,actions_js_1.doActions)("renderItemEnd",renderItemEndArgs,!0),{serverlessRender:serverlessRender,itemData:itemData,data:{slug:formattedSlug,output:layoutOutput}}};exports.renderItem=renderItem;const render=async args=>{if(!(0,object_js_1.isObjectStrict)(args))return[];const{allData:allData,serverlessData:serverlessData,previewData:previewData}=args,isServerless=null!=serverlessData,isPreview=null!=previewData;if(scripts_js_1.scripts.deps.clear(),scripts_js_1.scripts.item.clear(),scripts_js_1.scripts.meta={},scripts_js_1.styles.deps.clear(),scripts_js_1.styles.item.clear(),!(0,object_js_1.isObjectStrict)(allData))return[];const{redirect:redirect,content:content}=allData;await(0,actions_js_1.doActions)("renderStart",args,!0);const data=[];isServerless||(0,store_js_1.setStoreData)(allData),await renderNavigation({navigations:(0,store_js_1.getStoreItem)("navigations"),items:(0,store_js_1.getStoreItem)("navigationItems")}),(0,redirects_js_1.setRedirects)(redirect);for(const[contentType,contentItems]of Object.entries(content))if((0,array_js_1.isArrayStrict)(contentItems))for(const contentItem of contentItems){const item=await renderItem({item:await(0,filters_js_1.applyFilters)("renderItemData",contentItem,{contentType:contentType},!0),serverlessData:serverlessData,previewData:previewData},contentType);if(!item)continue;const{serverlessRender:serverlessRender=!1,data:itemData}=item;itemData&&(data.push(itemData),serverlessRender&&!isServerless&&(0,store_js_1.setStoreItem)("serverless",["reload"],itemData.slug))}const[outputItem]=data,output=(isServerless||isPreview)&&outputItem?outputItem:data;return await(0,actions_js_1.doActions)("renderEnd",{...args,data:output},!0),output};exports.render=render;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Contact=void 0;const config_js_1=require("../../config/config.js"),escape_js_1=require("../../utils/escape/escape.js"),array_js_1=require("../../utils/array/array.js"),string_js_1=require("../../utils/string/string.js"),object_js_1=require("../../utils/object/object.js"),objectUtils_js_1=require("../../utils/object/objectUtils.js"),filters_js_1=require("../../filters/filters.js"),link_js_1=require("../../utils/link/link.js"),store_js_1=require("../../store/store.js"),minify_js_1=require("../../utils/minify/minify.js"),file_js_1=require("../../utils/file/file.js"),recurseEmailHtml=(data,html,plain,depth=1)=>{if(!(0,object_js_1.isObject)(data))return;const isArr=(0,array_js_1.isArray)(data);(0,objectUtils_js_1.getObjectKeys)(data).forEach(label=>{const value=data[label],l=label.toString(),h=depth+1;1===depth&&(html.ref+='\n <tr>\n <td style="padding: 16px 0; border-bottom: 2px solid #ccc;">\n '),label&&!isArr&&(html.ref+=`\n <h${h} style="font-family: sans-serif; color: #222; margin: 16px 0; line-height: 1.3em">\n ${l}\n </h${h}>\n `,plain.ref+=`${l}\n`),recurseEmailHtml(value,html,plain,depth+1),(0,string_js_1.isString)(value)&&(html.ref+=`\n <p style="font-family: sans-serif; color: #222; margin: 16px 0; line-height: 1.5em;">\n ${value}\n </p>\n `,plain.ref+=value.replace(/<br\s*\/?>/gi,"\n").replace(/(<([^>]+)>)/gi,"")+"\n"),1===depth&&(html.ref+="\n </td>\n </tr>\n ",plain.ref+="\n")})},Contact=async args=>{const{id:id,action:action,inputs:inputs}=args;if(!(0,string_js_1.isStringStrict)(id))return{error:{message:"No ID"}};if(!(0,object_js_1.isObjectStrict)(inputs)||!Object.keys(inputs).length)return{error:{message:"No inputs"}};const formMetaData=(0,store_js_1.getStoreItem)("formMeta");if(!(0,object_js_1.isObjectStrict)(formMetaData))return{error:{message:"No meta"}};const meta=formMetaData[id];if(!(0,object_js_1.isObjectStrict)(meta))return{error:{message:"No meta object"}};const toEmail=meta.toEmail;if(!(0,string_js_1.isStringStrict)(toEmail))return{error:{message:"No to email"}};const toEmails=toEmail.split(","),senderEmail=meta.senderEmail;if(!(0,string_js_1.isStringStrict)(senderEmail))return{error:{message:"No sender email"}};let subject=(0,string_js_1.isStringStrict)(meta.subject)?meta.subject:"",replyToEmail="";const header=`${config_js_1.config.title} contact form submission`,footer=`This email was sent from a contact form on ${config_js_1.config.title} (${(0,link_js_1.getPermalink)()})`,outputData={},html={ref:""},plain={ref:""};for(const[name,input]of Object.entries(inputs)){const inputType=input.type,inputLabel=input.label?.trim()||`[${name}]
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Contact=void 0;const config_js_1=require("../../config/config.js"),escape_js_1=require("../../utils/escape/escape.js"),array_js_1=require("../../utils/array/array.js"),string_js_1=require("../../utils/string/string.js"),object_js_1=require("../../utils/object/object.js"),objectUtils_js_1=require("../../utils/object/objectUtils.js"),filters_js_1=require("../../filters/filters.js"),link_js_1=require("../../utils/link/link.js"),store_js_1=require("../../store/store.js"),minify_js_1=require("../../utils/minify/minify.js"),file_js_1=require("../../utils/file/file.js"),recurseEmailHtml=(data,html,plain,depth=1)=>{if(!(0,object_js_1.isObject)(data))return;const isArr=(0,array_js_1.isArray)(data);(0,objectUtils_js_1.getObjectKeys)(data).forEach(label=>{const value=data[label],l=label.toString(),h=depth+1;1===depth&&(html.ref+='\n <tr>\n <td style="padding: 16px 0; border-bottom: 2px solid #ccc;">\n '),label&&!isArr&&(html.ref+=`\n <h${h} style="font-family: sans-serif; color: #222; margin: 16px 0; line-height: 1.3em">\n ${l}\n </h${h}>\n `,plain.ref+=`${l}\n`),recurseEmailHtml(value,html,plain,depth+1),(0,string_js_1.isString)(value)&&(html.ref+=`\n <p style="font-family: sans-serif; color: #222; margin: 16px 0; line-height: 1.5em;">\n ${value}\n </p>\n `,plain.ref+=value.replace(/<br\s*\/?>/gi,"\n").replace(/(<([^>]+)>)/gi,"")+"\n"),1===depth&&(html.ref+="\n </td>\n </tr>\n ",plain.ref+="\n")})},Contact=async args=>{const{id:id,action:action,inputs:inputs}=args;if(!(0,string_js_1.isStringStrict)(id))return{error:{message:"No ID"}};if(!(0,object_js_1.isObjectStrict)(inputs)||!Object.keys(inputs).length)return{error:{message:"No inputs"}};const formMetaData=(0,store_js_1.getStoreItem)("formMeta");if(!(0,object_js_1.isObjectStrict)(formMetaData))return{error:{message:"No meta"}};const meta=formMetaData[id];if(!(0,object_js_1.isObjectStrict)(meta))return{error:{message:"No meta object"}};const toEmail=meta.toEmail;if(!(0,string_js_1.isStringStrict)(toEmail))return{error:{message:"No to email"}};const toEmails=toEmail.split(","),senderEmail=meta.senderEmail;if(!(0,string_js_1.isStringStrict)(senderEmail))return{error:{message:"No sender email"}};let subject=(0,string_js_1.isStringStrict)(meta.subject)?meta.subject:"",replyToEmail="";const header=`${config_js_1.config.title} contact form submission`,footer=`This email was sent from a contact form on ${config_js_1.config.title} (${(0,link_js_1.getPermalink)()})`,outputData={},html={ref:""},plain={ref:""};for(const[name,input]of Object.entries(inputs)){const inputType=input.type,inputLabel=(0,escape_js_1.escape)(input.label?.trim()||`[${name}]`),inputValue=input.value;if(!(0,string_js_1.isStringSafe)(inputLabel))continue;let inputValueStr="";if(inputValueStr=(0,array_js_1.isArray)(inputValue)?inputValue.map(v=>(0,file_js_1.isFile)(v)?(0,escape_js_1.escape)(v.name):(0,escape_js_1.escape)(v.toString().trim())).join("<br>"):(0,file_js_1.isFile)(inputValue)?(0,escape_js_1.escape)(inputValue.name):(0,escape_js_1.escape)(inputValue.toString().trim()),"subject"===name){subject=inputValueStr?`${(0,string_js_1.isStringStrict)(subject)?`${subject} - `:""}${inputValueStr}`:subject;continue}"email"===inputType&&inputValueStr&&(replyToEmail=inputValueStr,inputValueStr=`<a href="mailto:${inputValueStr}">${inputValueStr}</a>`);const outputValue=""===inputValueStr?"--":inputValueStr;let hasLegend=!1,legend="";if((0,string_js_1.isStringSafe)(input.legend)&&(legend=(0,escape_js_1.escape)(input.legend),hasLegend=!0),hasLegend){null==outputData[legend]&&(outputData[legend]={});null==outputData[legend][inputLabel]&&(outputData[legend][inputLabel]=[]),outputData[legend][inputLabel].push(outputValue)}if(!hasLegend){null==outputData[inputLabel]&&(outputData[inputLabel]=[]),outputData[inputLabel].push(outputValue)}}recurseEmailHtml(outputData,html,plain);const outputHtml=`\n <table width="100%" cellpadding="0" cellspacing="0" border="0">\n <tr>\n <td align="center" width="100%" style="padding: 0 16px 16px 16px;">\n <table align="center" cellpadding="0" cellspacing="0" border="0" style="margin-right: auto; margin-left: auto; border-spacing: 0; max-width: 37.5em;">\n <tr>\n <td style="padding: 32px 0 0 0;">\n <h1 style="font-family: sans-serif; color: #222; margin: 0; line-height: 1.3em;">\n ${header}\n </h1>\n </td>\n </tr>\n <tr>\n <td>\n <table border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;">\n ${html.ref}\n <tr>\n <td style="padding: 32px 0;">\n <p style="font-family: sans-serif; color: #222; margin: 0; line-height: 1.5em;">\n ${footer}\n </p>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n `,outputPlain=`${header}\n\n${plain.ref}${footer}`;subject||(subject=`${config_js_1.config.title} Contact Form`);const body={id:id,action:action,inputs:inputs,to:toEmails,sender:senderEmail,subject:subject,text:(0,minify_js_1.minify)(outputPlain),html:(0,minify_js_1.minify)(outputHtml)};return replyToEmail&&(body.replyTo=replyToEmail),await(0,filters_js_1.applyFilters)("contactResult",{},body,!0)};exports.Contact=Contact;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.doServerlessAction=exports.setServerless=exports.serverlessRender=exports.serverlessReload=exports.serverlessPreview=exports.serverlessActions=void 0;const ResponseError_js_1=require("../utils/ResponseError/ResponseError.js"),string_js_1=require("../utils/string/string.js"),object_js_1=require("../utils/object/object.js"),function_js_1=require("../utils/function/function.js"),filters_js_1=require("../filters/filters.js"),render_js_1=require("../render/render.js"),minify_js_1=require("../utils/minify/minify.js"),print_js_1=require("../utils/print/print.js");let serverlessActions={};exports.serverlessActions=serverlessActions;const serverlessPreview=request=>{const{url:url}=request,{searchParams:searchParams}=new URL(url),contentType=searchParams.get("content_type"),locale=searchParams.get("locale"),id=searchParams.get("preview");if(!(0,string_js_1.isStringStrict)(id)||!(0,string_js_1.isStringStrict)(contentType))return;const previewData={id:id,contentType:contentType};return(0,string_js_1.isStringStrict)(locale)&&(previewData.locale=locale),previewData};exports.serverlessPreview=serverlessPreview;const serverlessReload=(request,allowedParams=["page","filters"])=>{const{url:url}=request,{searchParams:searchParams,pathname:pathname}=new URL(url),path=pathname,query={};let hasParams=!1;for(const param of allowedParams){const value=searchParams.get(param);(0,string_js_1.isStringStrict)(value)&&(query[param]=value,hasParams=!0)}if(hasParams)return{query:query,path:path}};exports.serverlessReload=serverlessReload;const serverlessRender=async(getData,serverlessData,previewData)=>{try{const data=await(0,render_js_1.render)({serverlessData:serverlessData,previewData:previewData,allData:await getData({serverlessData:serverlessData,previewData:previewData})});let html="",status=200;(0,object_js_1.isObjectStrict)(data)&&(html=data.output);const isEmpty=""===html;return isEmpty&&(status=404),isEmpty&&(0,function_js_1.isFunction)(render_js_1.renderHttpError)&&(html=await(0,render_js_1.renderHttpError)({code:status})),new Response((0,minify_js_1.minify)(html),{status:status,headers:{"Content-Type":"text/html;charset=UTF-8"}})}catch(error){(0,print_js_1.print)("[FRM] Error on serverless render",error);const status=500,html=await(0,render_js_1.renderHttpError)({code:status});return new Response(html,{status:status,headers:{"Content-Type":"text/html;charset=UTF-8"}})}};exports.serverlessRender=serverlessRender;const setServerless=actions=>{(0,object_js_1.isObjectStrict)(actions)&&(exports.serverlessActions=serverlessActions={...actions})};exports.setServerless=setServerless;const doServerlessAction=async(request,env,headers,honeypotName)=>{const serverlessHeaders={"Content-Type":"application/json",...headers};try{if("POST"!==request.method)return new Response(JSON.stringify({error:"Method not allowed"}),{status:405,headers:serverlessHeaders});const data=await request.json();if(!(0,object_js_1.isObjectStrict)(data))throw new Error("Data not an object");if((0,string_js_1.isStringStrict)(honeypotName)&&(0,object_js_1.isObjectStrict)(data.inputs?.[honeypotName])){const honeypotValue=data.inputs[honeypotName].value;if((0,string_js_1.isStringStrict)(honeypotValue))return new Response(JSON.stringify({success:""}),{status:200,headers:serverlessHeaders});delete data.inputs[honeypotName]}const action=data.action;if(!(0,string_js_1.isStringStrict)(action))throw new Error("No action");let res=null;const serverlessAction=serverlessActions[action];(0,function_js_1.isFunction)(serverlessAction)&&(res=await serverlessAction(data,request,env));const serverlessResultFilterArgs={data:data,request:request,env:env};if(res=await(0,filters_js_1.applyFilters)("serverlessResult",res,serverlessResultFilterArgs,!0),!res)throw new Error("No result");if(res.error){const errorMessage=res.error.message;throw res.error.response?new ResponseError_js_1.ResponseError(errorMessage,res.error.response):new Error(errorMessage)}const options={status:200,headers:serverlessHeaders};let message="";if(res.success){const{message:successMessage,headers:successHeaders}=res.success;(0,string_js_1.isStringStrict)(successMessage)&&(message=successMessage),(0,object_js_1.isObjectStrict)(successHeaders)&&(options.headers={...options.headers,...successHeaders})}return new Response(JSON.stringify({success:message}),options)}catch(error){(0,print_js_1.print)("[FRM] Error with serverless action",error);let statusCode=500,message=error instanceof Error?error.message:"Unknown error";return error instanceof ResponseError_js_1.ResponseError&&(statusCode=error.response.status,message=error.message),new Response(JSON.stringify({error:message}),{status:statusCode,headers:serverlessHeaders})}};exports.doServerlessAction=doServerlessAction;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.doServerlessAction=exports.setServerless=exports.serverlessRender=exports.serverlessReload=exports.serverlessPreview=exports.serverlessActions=void 0;const ResponseError_js_1=require("../utils/ResponseError/ResponseError.js"),string_js_1=require("../utils/string/string.js"),object_js_1=require("../utils/object/object.js"),function_js_1=require("../utils/function/function.js"),filters_js_1=require("../filters/filters.js"),render_js_1=require("../render/render.js"),minify_js_1=require("../utils/minify/minify.js"),print_js_1=require("../utils/print/print.js");let serverlessActions={};exports.serverlessActions=serverlessActions;const serverlessPreview=request=>{const{url:url}=request,{searchParams:searchParams}=new URL(url),contentType=searchParams.get("content_type"),locale=searchParams.get("locale"),id=searchParams.get("preview");if(!(0,string_js_1.isStringStrict)(id)||!(0,string_js_1.isStringStrict)(contentType))return;const previewData={id:id,contentType:contentType};return(0,string_js_1.isStringStrict)(locale)&&(previewData.locale=locale),previewData};exports.serverlessPreview=serverlessPreview;const serverlessReload=(request,allowedParams=["page","filters"])=>{const{url:url}=request,{searchParams:searchParams,pathname:pathname}=new URL(url),path=pathname,query={};let hasParams=!1;for(const param of allowedParams){const value=searchParams.get(param);(0,string_js_1.isStringSafe)(param)&&(0,string_js_1.isStringStrict)(value)&&(query[param]=value,hasParams=!0)}if(hasParams)return{query:query,path:path}};exports.serverlessReload=serverlessReload;const serverlessRender=async(getData,serverlessData,previewData)=>{try{const data=await(0,render_js_1.render)({serverlessData:serverlessData,previewData:previewData,allData:await getData({serverlessData:serverlessData,previewData:previewData})});let html="",status=200;(0,object_js_1.isObjectStrict)(data)&&(html=data.output);const isEmpty=""===html;return isEmpty&&(status=404),isEmpty&&(0,function_js_1.isFunction)(render_js_1.renderHttpError)&&(html=await(0,render_js_1.renderHttpError)({code:status})),new Response((0,minify_js_1.minify)(html),{status:status,headers:{"Content-Type":"text/html;charset=UTF-8"}})}catch(error){(0,print_js_1.print)("[FRM] Error on serverless render",error);const status=500,html=await(0,render_js_1.renderHttpError)({code:status});return new Response(html,{status:status,headers:{"Content-Type":"text/html;charset=UTF-8"}})}};exports.serverlessRender=serverlessRender;const setServerless=actions=>{(0,object_js_1.isObjectStrict)(actions)&&(exports.serverlessActions=serverlessActions={...actions})};exports.setServerless=setServerless;const doServerlessAction=async(request,env,headers,honeypotName)=>{const serverlessHeaders={"Content-Type":"application/json",...headers};try{if("POST"!==request.method)return new Response(JSON.stringify({error:"Method not allowed"}),{status:405,headers:serverlessHeaders});const data=await request.json();if(!(0,object_js_1.isObjectStrict)(data))throw new Error("Data not an object");if((0,string_js_1.isStringStrict)(honeypotName)&&(0,object_js_1.isObjectStrict)(data.inputs?.[honeypotName])){const honeypotValue=data.inputs[honeypotName].value;if((0,string_js_1.isStringStrict)(honeypotValue))return new Response(JSON.stringify({success:""}),{status:200,headers:serverlessHeaders});delete data.inputs[honeypotName]}const action=data.action;if(!(0,string_js_1.isStringStrict)(action))throw new Error("No action");let res=null;const serverlessAction=serverlessActions[action];(0,function_js_1.isFunction)(serverlessAction)&&(res=await serverlessAction(data,request,env));const serverlessResultFilterArgs={data:data,request:request,env:env};if(res=await(0,filters_js_1.applyFilters)("serverlessResult",res,serverlessResultFilterArgs,!0),!res)throw new Error("No result");if(res.error){const errorMessage=res.error.message;throw res.error.response?new ResponseError_js_1.ResponseError(errorMessage,res.error.response):new Error(errorMessage)}const options={status:200,headers:serverlessHeaders};let message="";if(res.success){const{message:successMessage,headers:successHeaders}=res.success;(0,string_js_1.isStringStrict)(successMessage)&&(message=successMessage),(0,object_js_1.isObjectStrict)(successHeaders)&&(options.headers={...options.headers,...successHeaders})}return new Response(JSON.stringify({success:message}),options)}catch(error){(0,print_js_1.print)("[FRM] Error with serverless action",error);let statusCode=500,message=error instanceof Error?error.message:"Unknown error";return error instanceof ResponseError_js_1.ResponseError&&(statusCode=error.response.status,message=error.message),new Response(JSON.stringify({error:message}),{status:statusCode,headers:serverlessHeaders})}};exports.doServerlessAction=doServerlessAction;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.stripShortcodes=exports.setShortcodes=exports.resetShortcodes=exports.doShortcodes=exports.removeShortcode=exports.addShortcode=exports.shortcodes=void 0;const object_js_1=require("../utils/object/object.js"),array_js_1=require("../utils/array/array.js"),string_js_1=require("../utils/string/string.js"),function_js_1=require("../utils/function/function.js"),escape_js_1=require("../utils/escape/escape.js"),shortcodes=new Map;exports.shortcodes=shortcodes;const attrReg=/[\w-]+=".*?"/g,getShortcodeData=(content,tagNames,props,itemData)=>{if(!(0,string_js_1.isStringStrict)(content)||!(0,string_js_1.isStringStrict)(tagNames))return[];const reg=new RegExp(String.raw`\[(?:\/)?(?<name>${tagNames})(?:\s[^\]]*?)?\]`,"g"),matches=[...content.matchAll(reg)];if(!matches.length)return[];const data=[];return matches.forEach((opening,i)=>{const name=opening.groups?.name,tag=opening[0];if(!(0,string_js_1.isStringStrict)(name)||tag.startsWith("[/"))return;const info=props||shortcodes.get(name);if(!(0,object_js_1.isObjectStrict)(info))return;const child=info.child,hasChild=(0,string_js_1.isStringStrict)(child),startIndex=opening.index,
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.stripShortcodes=exports.setShortcodes=exports.resetShortcodes=exports.doShortcodes=exports.removeShortcode=exports.addShortcode=exports.shortcodes=void 0;const object_js_1=require("../utils/object/object.js"),array_js_1=require("../utils/array/array.js"),string_js_1=require("../utils/string/string.js"),function_js_1=require("../utils/function/function.js"),escape_js_1=require("../utils/escape/escape.js"),shortcodes=new Map;exports.shortcodes=shortcodes;const attrReg=/[\w-]+=".*?"/g,getShortcodeData=(content,tagNames,props,itemData)=>{if(!(0,string_js_1.isStringStrict)(content)||!(0,string_js_1.isStringStrict)(tagNames))return[];const reg=new RegExp(String.raw`\[(?:\/)?(?<name>${tagNames})(?:\s[^\]]*?)?\]`,"g"),matches=[...content.matchAll(reg)];if(!matches.length)return[];const data=[];return matches.forEach((opening,i)=>{const name=opening.groups?.name,tag=opening[0];if(!(0,string_js_1.isStringStrict)(name)||tag.startsWith("[/"))return;const info=props||shortcodes.get(name);if(!(0,object_js_1.isObjectStrict)(info))return;const child=info.child,hasChild=(0,string_js_1.isStringStrict)(child),startIndex=opening.index,startCount=tag.length;let endIndex=startIndex+tag.length,endCount=0;const closingTag=`[/${name}]`,closingMatch=hasChild?matches.find(m=>m[0]===closingTag):matches[i+1];closingMatch?.[0]===closingTag&&(endIndex=closingMatch.index,endCount=closingTag.length);const attrs={},attrTypes=(0,object_js_1.isObjectStrict)(info.attrTypes)?info.attrTypes:{},attr=tag.match(attrReg);(0,array_js_1.isArrayStrict)(attr)&&attr.forEach(a=>{const[key,value]=a.split("=");if(!(0,string_js_1.isStringSafe)(key))return;const type=attrTypes[key];let val=(0,escape_js_1.escape)(value.replace(/"/g,""));if("number"===type){const num=parseInt(val,10);val=isNaN(num)?0:num}"boolean"===type&&(val="true"===val),attrs[key]=val});const replaceContent=content.slice(startIndex,endIndex+endCount),innerContent=content.slice(startIndex+startCount,endIndex);let children=[];hasChild&&(children=getShortcodeData(innerContent,child,props,itemData)),data.push({name:name,replaceContent:replaceContent,content:innerContent,attr:attrs,children:children,itemData:itemData})}),data},addShortcode=(name,shortcode)=>!(!(0,string_js_1.isStringStrict)(name)||!(0,object_js_1.isObjectStrict)(shortcode))&&(shortcodes.set(name,shortcode),!0);exports.addShortcode=addShortcode;const removeShortcode=name=>!!(0,string_js_1.isStringStrict)(name)&&shortcodes.delete(name);exports.removeShortcode=removeShortcode;const doShortcodes=async(content,itemData)=>{if(!shortcodes.size)return content;const names=[...shortcodes.keys()].join("|"),data=getShortcodeData(content,names,void 0,itemData);if(!data.length)return content;let newContent=content;for(const datum of data){const{name:name,replaceContent:replaceContent}=datum,callback=shortcodes.get(name)?.callback;(0,function_js_1.isFunction)(callback)&&(newContent=newContent.replace(replaceContent,await callback({...datum,itemData:itemData})))}return newContent};exports.doShortcodes=doShortcodes;const resetShortcodes=()=>{shortcodes.clear()};exports.resetShortcodes=resetShortcodes;const setShortcodes=args=>{if(!(0,object_js_1.isObjectStrict)(args))return!1;const names=Object.entries(args);return!!names.length&&(resetShortcodes(),names.forEach(([name,shortcode])=>{addShortcode(name,shortcode)}),!0)};exports.setShortcodes=setShortcodes;const stripShortcodes=content=>{if(!shortcodes.size)return content;const names=[...shortcodes.keys()].join("|"),reg=new RegExp(String.raw`\[(?:\/)?(?<name>${names})(?:\s[^\]]*?)?\]`,"g");return content.replace(reg,()=>"")};exports.stripShortcodes=stripShortcodes;
|
package/cjs/store/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getStoreItem=exports.setStoreItem=exports.setStoreData=exports.setStore=exports.storeDir=exports.store=void 0;const contentType_js_1=require("../utils/contentType/contentType.js"),object_js_1=require("../utils/object/object.js"),string_js_1=require("../utils/string/string.js"),array_js_1=require("../utils/array/array.js"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getStoreItem=exports.setStoreItem=exports.setStoreData=exports.setStore=exports.storeDir=exports.store=void 0;const contentType_js_1=require("../utils/contentType/contentType.js"),object_js_1=require("../utils/object/object.js"),string_js_1=require("../utils/string/string.js"),array_js_1=require("../utils/array/array.js"),archive_js_1=require("../utils/archive/archive.js"),config_js_1=require("../config/config.js");let storeDir="lib/store";exports.storeDir=storeDir;const defaultStore={slugs:{},parents:{},navigations:[],navigationItems:[],formMeta:{},archiveMeta:{},imageMeta:{},taxonomies:{},serverless:{}};let store={...defaultStore};exports.store=store;const setStore=(args,dir="lib/store")=>(0,object_js_1.isObjectStrict)(args)?(exports.store=store={...defaultStore,...args},(0,string_js_1.isStringStrict)(dir)&&(exports.storeDir=storeDir=dir),store):store;exports.setStore=setStore;const setStoreItem=(prop,value,subProp)=>!(!(0,string_js_1.isStringSafe)(prop)||!(0,object_js_1.isObject)(value)||null==store[prop])&&((0,string_js_1.isStringSafe)(subProp)?store[prop][subProp]=value:store[prop]=value,!0);exports.setStoreItem=setStoreItem;const setStoreData=allData=>{if(!(0,object_js_1.isObjectStrict)(allData))return!1;const{navigation:navigation,navigationItem:navigationItem,content:content}=allData;store.navigations=(0,array_js_1.isArrayStrict)(navigation)?navigation:[],store.navigationItems=(0,array_js_1.isArrayStrict)(navigationItem)?navigationItem:[];const data={...allData,...content};return config_js_1.config.hierarchicalTypes.forEach(type=>{if(!(0,string_js_1.isStringSafe)(type))return;const items=data[type];(0,array_js_1.isArrayStrict)(items)&&items.forEach(item=>{if(!(0,object_js_1.isObjectStrict)(item))return;const{id:id,parent:parent,archive:archive,slug:slug,title:title,locale:locale}=item;if(!(0,string_js_1.isStringSafe)(id))return;const archiveType=(0,contentType_js_1.normalizeContentType)(archive);if((0,string_js_1.isStringSafe)(archiveType)){const hasLocale=(0,string_js_1.isStringSafe)(locale),archiveMeta=(0,archive_js_1.getArchiveMeta)(archiveType),newArchive={id:id,slug:slug,title:title,contentType:type,...hasLocale?archiveMeta[locale]:archiveMeta};hasLocale?(store.archiveMeta[archiveType]||(store.archiveMeta[archiveType]={}),store.archiveMeta[archiveType][locale]=newArchive):store.archiveMeta[archiveType]=newArchive}if((0,object_js_1.isObjectStrict)(parent)){const parentSlug=parent.slug,parentTitle=parent.title,parentId=parent.id;(0,string_js_1.isStringStrict)(parentSlug)&&(0,string_js_1.isStringStrict)(parentTitle)&&(0,string_js_1.isStringSafe)(parentId)&&(null==store.parents[type]&&(store.parents[type]={}),store.parents[type][id]=[parentId,parentSlug,parentTitle])}})}),!0};exports.setStoreData=setStoreData;const getStoreItem=prop=>store[prop];exports.getStoreItem=getStoreItem;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.escape=void 0;const string_js_1=require("../string/string.js"),escape=value=>{if(!(0,string_js_1.isString)(value))throw new TypeError("Value
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.escape=void 0;const string_js_1=require("../string/string.js"),escape=value=>{if(!(0,string_js_1.isString)(value))throw new TypeError("Value not a string");return value.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/\//g,"/").replace(/\\/g,"\").replace(/`/g,"`")};exports.escape=escape;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getExcerpt=void 0;const object_js_1=require("../object/object.js"),string_js_1=require("../string/string.js"),shortcodes_js_1=require("../../shortcodes/shortcodes.js"),getContentWords=args=>{const{content:content,prop:prop,limit:limit=25}=args;let{_words:_words=[]}=args;const max=limit+1,
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getExcerpt=void 0;const object_js_1=require("../object/object.js"),string_js_1=require("../string/string.js"),shortcodes_js_1=require("../../shortcodes/shortcodes.js"),getContentWords=args=>{const{content:content,prop:prop,limit:limit=25}=args;let{_words:_words=[]}=args;const max=limit+1,wordsCount=_words.length;if((0,object_js_1.isObject)(content)&&wordsCount<max){const addMax=max-wordsCount;for(const[key,value]of Object.entries(content)){if(key===prop&&(0,string_js_1.isStringStrict)(value)){const val=(0,shortcodes_js_1.stripShortcodes)(value);if((0,string_js_1.isStringStrict)(val)){let valArr=val.split(" ");valArr.length>addMax&&(valArr=valArr.slice(0,addMax)),_words=_words.concat(valArr)}}(0,object_js_1.isObject)(value)&&(_words=getContentWords({content:value,prop:prop,limit:limit,_words:_words}))}}return _words},getExcerpt=args=>{const{excerpt:excerpt,content:content,prop:prop="content",limit:limit=25,limitExcerpt:limitExcerpt=!1,more:more="…"}=(0,object_js_1.isObjectStrict)(args)?args:{};let output="";if((0,string_js_1.isStringStrict)(excerpt)){if(output=excerpt,limitExcerpt){let excerptArr=excerpt.split(" ");excerptArr.length>limit&&(excerptArr=excerptArr.slice(0,limit),output=`${excerptArr.join(" ")}${more}`)}}else{const words=getContentWords({content:content,prop:prop,limit:limit}),wordsCount=words.length;wordsCount>0&&(wordsCount>limit&&more&&words.pop(),output=`${words.join(" ")}${wordsCount>limit?more:""}`)}return output};exports.getExcerpt=getExcerpt;
|
package/cjs/utils/image/image.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getImageSizes=exports.getImageClosestSize=exports.getImage=void 0;const config_js_1=require("../../config/config.js"),string_js_1=require("../string/string.js"),array_js_1=require("../array/array.js"),number_js_1=require("../number/number.js"),object_js_1=require("../object/object.js"),dataSource_js_1=require("../dataSource/dataSource.js"),getImageUrl=(url,format,quality,width,height,params)=>{const urlObj=new URL(url);return Object.entries(params).forEach(([key,value])=>{let val=value;"%format"===val&&(val=format),"%quality"===val&&(val=`${quality}`),"%width"===val&&(val=`${width}`),"%height"===val&&(val=`${height}`),urlObj.searchParams.set(key,val)}),urlObj.toString()},getImage=(args,returnDetails=!1)=>{const{data:data,classes:classes,attr:attr,alt:imageAlt="inherit",width:width="auto",height:height="auto",lazy:lazy=!0,picture:picture=!1,quality:quality=75,source:source=config_js_1.config.source,maxWidth:maxWidth=1200,viewportWidth:viewportWidth=100,sizes:sizes,format:format="webp",params:params={fm:"%format",q:"%quality",w:"%width",h:"%height"}}=(0,object_js_1.isObjectStrict)(args)?args:{},fallback=returnDetails?{output:"",aspectRatio:0,naturalWidth:0,naturalHeight:0,src:"",srcFallback:"",srcset:[],sizes:""}:"";if(!(0,object_js_1.isObjectStrict)(data))return fallback;const{path:path="",alt:dataAlt="",width:naturalWidth=1,height:naturalHeight=1,format:naturalFormat="jpg",sizes:dataSizes}=data;let{url:url=config_js_1.config.image.remoteUrl}=data,alt="inherit"===imageAlt?dataAlt:imageAlt;(0,string_js_1.isStringStrict)(alt)||(alt="");const isLocal="local"===source,isRemote=dataSource_js_1.dataSource.isContentful(source)||"remote"===source,isWordpress=dataSource_js_1.dataSource.isWordPress(source);if(isLocal){if(!(0,string_js_1.isStringStrict)(path))return fallback;url=`${config_js_1.config.image.localUrl}/${path}`}const aspectRatio=naturalHeight/naturalWidth,aspectRatioReverse=naturalWidth/naturalHeight;let w=naturalWidth,h=naturalHeight;if((0,number_js_1.isNumber)(width)&&(w=width,h=(0,string_js_1.isString)(height)?w*aspectRatio:height),(0,number_js_1.isNumber)(height)&&(h=height,w=(0,string_js_1.isString)(width)?h*aspectRatioReverse:width),w>maxWidth&&(w=Math.round(maxWidth),h=Math.round(w*aspectRatio)),isWordpress&&dataSizes&&!dataSizes[w]){const isNatural=w===naturalWidth;isNatural||(w=getImageClosestSize(w,Object.keys(dataSizes).map(s=>parseInt(s,10))),h=Math.round(w*aspectRatio)),isNatural&&(dataSizes[w]=url)}let src=url,srcFallback=url;isLocal&&(src=`${url}.${format}`,srcFallback=`${url}.${naturalFormat}`),isRemote&&(src=getImageUrl(url,format,quality,w,h,params),srcFallback=getImageUrl(url,naturalFormat,quality,w,h,params));const sizesValue=sizes||`(min-width: ${w/16}rem) ${w/16}rem, ${viewportWidth}vw`,srcsetFallback=[];let srcset=[...config_js_1.config.image.sizes];srcset.includes(w)||srcset.push(w),srcset=srcset.filter(s=>s<=w),srcset.sort((a,b)=>a-b);const srcsetSource=[];srcset.forEach(s=>{if(isLocal){const base=`${url}${s!==naturalWidth?`@${s}`:""}`;srcsetFallback.push(`${base}.${naturalFormat} ${s}w`),srcsetSource.push(`${base}.${format} ${s}w`)}if(isRemote){const sizeHeight=Math.round(s*aspectRatio);srcsetFallback.push(getImageUrl(url,naturalFormat,quality,s,sizeHeight,params)+` ${s}w`),srcsetSource.push(getImageUrl(url,format,quality,s,sizeHeight,params)+` ${s}w`)}if(isWordpress){const sizeUrl=dataSizes?.[s];(0,string_js_1.isStringStrict)(sizeUrl)&&srcsetSource.push(`${sizeUrl} ${s}w`)}});let sourceOutput="";picture&&(sourceOutput=`<source srcset="${srcsetSource.join(", ")}" sizes="${sizesValue}" type="image/${format}">`);let eagerHackOutput="";lazy||(eagerHackOutput=`\n <img\n alt=""\n role="presentation"\n aria-hidden="true"\n src="data:image/svg+xml;charset=utf-8,%3Csvg height='${h}' width='${w}' xmlns='http://www.w3.org/2000/svg' version='1.1'%3E%3C/svg%3E" style="pointerEvents: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%"\n >\n `);const output=`\n ${eagerHackOutput}\n ${sourceOutput}\n <img\n ${(0,string_js_1.isStringStrict)(classes)?` class="${classes}"`:""}\n alt="${alt}"\n src="${picture?srcFallback:src}"\n srcset="${picture?srcsetFallback.join(", "):srcsetSource.join(", ")}"\n sizes="${sizesValue}"\n width="${w}"\n height="${h}"\n ${(0,string_js_1.isStringStrict)(attr)?` ${attr}`:""}\n ${lazy?' loading="lazy" decoding="async"':' loading="eager" fetchpriority="high"'}\n >\n `;return returnDetails?{output:output,aspectRatio:aspectRatio,naturalWidth:naturalWidth,naturalHeight:naturalHeight,src:src,srcFallback:srcFallback,srcset:srcsetSource,sizes:sizesValue}:output};exports.getImage=getImage;const getImageClosestSize=(size,sizes=[])=>(sizes.length||(sizes=config_js_1.config.image.sizes),[...sizes].reduce((prev,curr)=>Math.abs(curr-size)<=Math.abs(prev-size)?curr:prev));exports.getImageClosestSize=getImageClosestSize;const getImageSizes=args=>{const fallback={maxWidth:0,sizes:""};if(!(0,object_js_1.isObjectStrict)(args))return fallback;const{parents:parents,widths:widths,maxWidths:maxWidths,breakpoints:breakpoints,source:source=config_js_1.config.source,viewportWidth:viewportWidth=100,maxWidth:max}=args;if(!((0,array_js_1.isArrayStrict)(parents)&&(0,object_js_1.isObjectStrict)(widths)&&(0,object_js_1.isObjectStrict)(maxWidths)&&(0,array_js_1.isArrayStrict)(breakpoints)))return fallback;let containerWidth=0;const columnWidths=[];let col=1,colSmall=1,colMedium=1,colLarge=1;parents.forEach(parent=>{if(!(0,object_js_1.isObjectStrict)(parent))return;const{renderType:renderType,args:args}=parent;if((0,object_js_1.isObjectStrict)(args)){if("column"===renderType){const{width:width="Default",widthSmall:widthSmall="Default",widthMedium:widthMedium="Default",widthLarge:widthLarge="Default"}=args,base=(0,number_js_1.isNumber)(widths[width])&&widths[width]?widths[width]:1,baseSmall=(0,number_js_1.isNumber)(widths[widthSmall])&&widths[widthSmall]?widths[widthSmall]:base,baseMedium=(0,number_js_1.isNumber)(widths[widthMedium])&&widths[widthMedium]?widths[widthMedium]:baseSmall,baseLarge=(0,number_js_1.isNumber)(widths[widthLarge])&&widths[widthLarge]?widths[widthLarge]:baseMedium;col*=base,colSmall*=baseSmall,colMedium*=baseMedium,colLarge*=baseLarge,columnWidths[0]=col,columnWidths[1]=colSmall,columnWidths[2]=colMedium,columnWidths[3]=colLarge}if("container"===renderType){const{maxWidth:maxWidth="Default"}=args;(0,number_js_1.isNumber)(maxWidths[maxWidth])&&(containerWidth=maxWidths[maxWidth])}}});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getImageSizes=exports.getImageClosestSize=exports.getImage=void 0;const config_js_1=require("../../config/config.js"),string_js_1=require("../string/string.js"),array_js_1=require("../array/array.js"),number_js_1=require("../number/number.js"),object_js_1=require("../object/object.js"),dataSource_js_1=require("../dataSource/dataSource.js"),getImageUrl=(url,format,quality,width,height,params)=>{const urlObj=new URL(url);return Object.entries(params).forEach(([key,value])=>{let val=value;"%format"===val&&(val=format),"%quality"===val&&(val=`${quality}`),"%width"===val&&(val=`${width}`),"%height"===val&&(val=`${height}`),urlObj.searchParams.set(key,val)}),urlObj.toString()},getImage=(args,returnDetails=!1)=>{const{data:data,classes:classes,attr:attr,alt:imageAlt="inherit",width:width="auto",height:height="auto",lazy:lazy=!0,picture:picture=!1,quality:quality=75,source:source=config_js_1.config.source,maxWidth:maxWidth=1200,viewportWidth:viewportWidth=100,sizes:sizes,format:format="webp",params:params={fm:"%format",q:"%quality",w:"%width",h:"%height"}}=(0,object_js_1.isObjectStrict)(args)?args:{},fallback=returnDetails?{output:"",aspectRatio:0,naturalWidth:0,naturalHeight:0,src:"",srcFallback:"",srcset:[],sizes:""}:"";if(!(0,object_js_1.isObjectStrict)(data))return fallback;const{path:path="",alt:dataAlt="",width:naturalWidth=1,height:naturalHeight=1,format:naturalFormat="jpg",sizes:dataSizes}=data;let{url:url=config_js_1.config.image.remoteUrl}=data,alt="inherit"===imageAlt?dataAlt:imageAlt;(0,string_js_1.isStringStrict)(alt)||(alt="");const isLocal="local"===source,isRemote=dataSource_js_1.dataSource.isContentful(source)||"remote"===source,isWordpress=dataSource_js_1.dataSource.isWordPress(source);if(isLocal){if(!(0,string_js_1.isStringStrict)(path))return fallback;url=`${config_js_1.config.image.localUrl}/${path}`}const aspectRatio=naturalHeight/naturalWidth,aspectRatioReverse=naturalWidth/naturalHeight;let w=naturalWidth,h=naturalHeight;if((0,number_js_1.isNumber)(width)&&(w=width,h=(0,string_js_1.isString)(height)?w*aspectRatio:height),(0,number_js_1.isNumber)(height)&&(h=height,w=(0,string_js_1.isString)(width)?h*aspectRatioReverse:width),w>maxWidth&&(w=Math.round(maxWidth),h=Math.round(w*aspectRatio)),isWordpress&&dataSizes&&!dataSizes[w]){const isNatural=w===naturalWidth;isNatural||(w=getImageClosestSize(w,Object.keys(dataSizes).map(s=>parseInt(s,10))),h=Math.round(w*aspectRatio)),isNatural&&(dataSizes[w]=url)}let src=url,srcFallback=url;isLocal&&(src=`${url}.${format}`,srcFallback=`${url}.${naturalFormat}`),isRemote&&(src=getImageUrl(url,format,quality,w,h,params),srcFallback=getImageUrl(url,naturalFormat,quality,w,h,params));const sizesValue=sizes||`(min-width: ${w/16}rem) ${w/16}rem, ${viewportWidth}vw`,srcsetFallback=[];let srcset=[...config_js_1.config.image.sizes];srcset.includes(w)||srcset.push(w),srcset=srcset.filter(s=>s<=w),srcset.sort((a,b)=>a-b);const srcsetSource=[];srcset.forEach(s=>{if(isLocal){const base=`${url}${s!==naturalWidth?`@${s}`:""}`;srcsetFallback.push(`${base}.${naturalFormat} ${s}w`),srcsetSource.push(`${base}.${format} ${s}w`)}if(isRemote){const sizeHeight=Math.round(s*aspectRatio);srcsetFallback.push(getImageUrl(url,naturalFormat,quality,s,sizeHeight,params)+` ${s}w`),srcsetSource.push(getImageUrl(url,format,quality,s,sizeHeight,params)+` ${s}w`)}if(isWordpress){const sizeUrl=dataSizes?.[s];(0,string_js_1.isStringStrict)(sizeUrl)&&srcsetSource.push(`${sizeUrl} ${s}w`)}});let sourceOutput="";picture&&(sourceOutput=`<source srcset="${srcsetSource.join(", ")}" sizes="${sizesValue}" type="image/${format}">`);let eagerHackOutput="";lazy||(eagerHackOutput=`\n <img\n alt=""\n role="presentation"\n aria-hidden="true"\n src="data:image/svg+xml;charset=utf-8,%3Csvg height='${h}' width='${w}' xmlns='http://www.w3.org/2000/svg' version='1.1'%3E%3C/svg%3E" style="pointerEvents: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%"\n >\n `);const output=`\n ${eagerHackOutput}\n ${sourceOutput}\n <img\n ${(0,string_js_1.isStringStrict)(classes)?` class="${classes}"`:""}\n alt="${alt}"\n src="${picture?srcFallback:src}"\n srcset="${picture?srcsetFallback.join(", "):srcsetSource.join(", ")}"\n sizes="${sizesValue}"\n width="${w}"\n height="${h}"\n ${(0,string_js_1.isStringStrict)(attr)?` ${attr}`:""}\n ${lazy?' loading="lazy" decoding="async"':' loading="eager" fetchpriority="high"'}\n >\n `;return returnDetails?{output:output,aspectRatio:aspectRatio,naturalWidth:naturalWidth,naturalHeight:naturalHeight,src:src,srcFallback:srcFallback,srcset:srcsetSource,sizes:sizesValue}:output};exports.getImage=getImage;const getImageClosestSize=(size,sizes=[])=>(sizes.length||(sizes=config_js_1.config.image.sizes),[...sizes].reduce((prev,curr)=>Math.abs(curr-size)<=Math.abs(prev-size)?curr:prev));exports.getImageClosestSize=getImageClosestSize;const getImageSizes=args=>{const fallback={maxWidth:0,sizes:""};if(!(0,object_js_1.isObjectStrict)(args))return fallback;const{parents:parents,widths:widths,maxWidths:maxWidths,breakpoints:breakpoints,source:source=config_js_1.config.source,viewportWidth:viewportWidth=100,maxWidth:max}=args;if(!((0,array_js_1.isArrayStrict)(parents)&&(0,object_js_1.isObjectStrict)(widths)&&(0,object_js_1.isObjectStrict)(maxWidths)&&(0,array_js_1.isArrayStrict)(breakpoints)))return fallback;let containerWidth=0;const columnWidths=[];let col=1,colSmall=1,colMedium=1,colLarge=1;parents.forEach(parent=>{if(!(0,object_js_1.isObjectStrict)(parent))return;const{renderType:renderType,args:args}=parent;if((0,object_js_1.isObjectStrict)(args)){if("column"===renderType){const{width:width="Default",widthSmall:widthSmall="Default",widthMedium:widthMedium="Default",widthLarge:widthLarge="Default"}=args,base=(0,number_js_1.isNumber)(widths[width])&&widths[width]?widths[width]:1,baseSmall=(0,number_js_1.isNumber)(widths[widthSmall])&&widths[widthSmall]?widths[widthSmall]:base,baseMedium=(0,number_js_1.isNumber)(widths[widthMedium])&&widths[widthMedium]?widths[widthMedium]:baseSmall,baseLarge=(0,number_js_1.isNumber)(widths[widthLarge])&&widths[widthLarge]?widths[widthLarge]:baseMedium;col*=base,colSmall*=baseSmall,colMedium*=baseMedium,colLarge*=baseLarge,columnWidths[0]=col,columnWidths[1]=colSmall,columnWidths[2]=colMedium,columnWidths[3]=colLarge}if("container"===renderType){const{maxWidth:maxWidth="Default"}=args;(0,number_js_1.isNumber)(maxWidths[maxWidth])&&(containerWidth=maxWidths[maxWidth])}}});const columnWidthsCount=columnWidths.length,hasContainerWidth=!!containerWidth;if(!columnWidthsCount&&!hasContainerWidth)return fallback;const maxPx=(0,number_js_1.isNumber)(max)?max/2:0,maxRem=maxPx/16+"rem",hasMax=!!maxPx&&(!hasContainerWidth||maxPx<containerWidth),breakpointsCount=breakpoints.length,maxWidthArr=[],sizesArr=[],sizeFactor=viewportWidth/100;let lastWidth=1,lastBreakpoint=0,lastSize="",containerWidthAdded=!1,sizesArrCount=0,maxIndex=-1;for(let i=0;i<breakpointsCount;i+=1){const breakpoint=breakpoints[i],width=columnWidths[i];if(!(0,number_js_1.isNumber)(width))continue;const bk=0===breakpoint&&0===i?breakpoints[i+1]:breakpoint,gteContainerWidth=hasContainerWidth&&breakpoint>=containerWidth,breakpointWidth=Math.round(width*(gteContainerWidth?containerWidth:bk)),gtMaxWidth=hasMax&&breakpointWidth>maxPx,sizeWidth=gteContainerWidth?breakpointWidth/16:100*width*sizeFactor,size=gteContainerWidth?`${sizeWidth}rem`:`${sizeWidth%1==0?sizeWidth:sizeWidth.toFixed(2)}vw`;if(hasContainerWidth&&containerWidth>lastBreakpoint&&containerWidth<breakpoint){const relMaxWidth=Math.round(lastWidth*containerWidth),relSize=relMaxWidth/16+"rem";hasMax&&relMaxWidth>maxPx||(maxWidthArr.push(relMaxWidth),sizesArrCount=sizesArr.push(`(min-width: ${containerWidth/16}rem) ${relSize}`),containerWidthAdded=!0,lastSize=relSize)}gtMaxWidth||maxWidthArr.push(breakpointWidth),gtMaxWidth||lastSize===size||(sizesArrCount=sizesArr.push(breakpoint?`(min-width: ${breakpoint/16}rem) ${size}`:size)),hasMax&&maxPx>lastBreakpoint&&maxPx<breakpoint&&maxPx<breakpointWidth&&(maxIndex=sizesArrCount),lastWidth=width,lastBreakpoint=breakpoint,lastSize=size}if(!containerWidthAdded&&hasContainerWidth&&containerWidth>lastBreakpoint){const relMaxWidth=Math.round(lastWidth*containerWidth),relSize=relMaxWidth/16+"rem";hasMax&&relMaxWidth>maxPx||(maxWidthArr.push(relMaxWidth),sizesArrCount=sizesArr.push(`(min-width: ${containerWidth/16}rem) ${relSize}`),containerWidthAdded=!0)}hasMax&&maxPx>lastBreakpoint&&(maxIndex=sizesArrCount),-1!==maxIndex&&(maxWidthArr.push(maxPx),sizesArr.splice(maxIndex,0,`(min-width: ${maxRem}) ${maxRem}`));const maxWidth=2*Math.max(...maxWidthArr);if(!hasMax&&(!columnWidthsCount||1===col&&1===colSmall&&1===colMedium&&1===colLarge)){const sizeWidth=maxWidth/32+"rem";sizesArr[0]=`${viewportWidth}vw`,sizesArr[1]=`(min-width: ${sizeWidth}) ${sizeWidth}`}const sizes=sizesArr.reverse().join(", ");return"local"===source?{maxWidth:getImageClosestSize(maxWidth),sizes:sizes}:{maxWidth:maxWidth,sizes:sizes}};exports.getImageSizes=getImageSizes;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.setLocalImages=void 0;const node_path_1=require("node:path"),promises_1=require("node:fs/promises"),sharp_1=__importDefault(require("sharp")),filePath_js_1=require("../file/filePath.js"),string_js_1=require("../string/string.js"),store_js_1=require("../../store/store.js"),config_js_1=require("../../config/config.js"),setLocalImages=async()=>{const inputDir=config_js_1.config.image.inputDir,outputDir=config_js_1.config.image.outputDir;if(!(0,string_js_1.isStringStrict)(inputDir)||!(0,string_js_1.isStringStrict)(outputDir))throw new Error("No input or output directories");await(0,promises_1.mkdir)((0,node_path_1.resolve)(outputDir),{recursive:!0});const images=[],meta={};for await(const path of(0,filePath_js_1.getFilePaths)(inputDir)){const baseName=(0,node_path_1.basename)(path),ext=(0,node_path_1.extname)(baseName);if(!(0,string_js_1.isStringStrict)(ext))continue;const[base]=baseName.split(ext);if(!(0,string_js_1.
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.setLocalImages=void 0;const node_path_1=require("node:path"),promises_1=require("node:fs/promises"),sharp_1=__importDefault(require("sharp")),filePath_js_1=require("../file/filePath.js"),string_js_1=require("../string/string.js"),store_js_1=require("../../store/store.js"),config_js_1=require("../../config/config.js"),setLocalImages=async()=>{const inputDir=config_js_1.config.image.inputDir,outputDir=config_js_1.config.image.outputDir;if(!(0,string_js_1.isStringStrict)(inputDir)||!(0,string_js_1.isStringStrict)(outputDir))throw new Error("No input or output directories");await(0,promises_1.mkdir)((0,node_path_1.resolve)(outputDir),{recursive:!0});const images=[],meta={};for await(const path of(0,filePath_js_1.getFilePaths)(inputDir)){const baseName=(0,node_path_1.basename)(path),ext=(0,node_path_1.extname)(baseName);if(!(0,string_js_1.isStringStrict)(ext))continue;const[base]=baseName.split(ext);if(!(0,string_js_1.isStringSafe)(base?.trim()))continue;let[,folders]=(0,node_path_1.dirname)(path).split(`${inputDir}/`);(0,string_js_1.isStringStrict)(folders)&&folders!==baseName?await(0,promises_1.mkdir)((0,node_path_1.resolve)(outputDir,folders),{recursive:!0}):folders="";const instance=(0,sharp_1.default)(path),metadata=await(0,sharp_1.default)(path).metadata(),stats=await(0,promises_1.stat)(path),{width:width,height:height,format:fileFormat}=metadata,id=`${folders?`${folders}/`:""}${base}`,format=ext.replace(".","");meta[id]={path:id,name:baseName,type:`image/${fileFormat}`,format:format,size:stats.size,width:width,height:height};let sizes=[...config_js_1.config.image.sizes];sizes.includes(width)||sizes.push(width),sizes=sizes.filter(s=>s<=width),sizes.forEach(size=>{images.push({size:size,format:format,path:(0,node_path_1.resolve)(path),newPath:(0,node_path_1.resolve)(outputDir,folders,`${base}${size!==width?`@${size}`:""}`),instance:instance})})}if(!images.length)throw new Error("No local images to transform");return(0,store_js_1.setStoreItem)("imageMeta",meta),await Promise.all(images.map(async image=>{const{size:size,instance:instance,newPath:newPath,format:format}=image;return await instance.clone().resize(size).toFile(`${newPath}.${format}`),await instance.clone().resize(size).webp({quality:config_js_1.config.image.quality}).toFile(`${newPath}.webp`)}))};exports.setLocalImages=setLocalImages;
|
package/cjs/utils/json/json.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
declare const getJson: <T extends object>(value: string) => T
|
|
2
|
-
declare const getJsonFile: <T>(path: string, store?: boolean) => Promise<
|
|
1
|
+
declare const getJson: <T extends object>(value: string) => T;
|
|
2
|
+
declare const getJsonFile: <T>(path: string, store?: boolean) => Promise<object & T>;
|
|
3
3
|
export { getJson, getJsonFile };
|
package/cjs/utils/json/json.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=this&&this.__importStar||function(){var ownKeys=function(o){return ownKeys=Object.getOwnPropertyNames||function(o){var ar=[];for(var k in o)Object.prototype.hasOwnProperty.call(o,k)&&(ar[ar.length]=k);return ar},ownKeys(o)};return function(mod){if(mod&&mod.__esModule)return mod;var result={};if(null!=mod)for(var k=ownKeys(mod),i=0;i<k.length;i++)"default"!==k[i]&&__createBinding(result,mod,k[i]);return __setModuleDefault(result,mod),result}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.getJsonFile=exports.getJson=void 0;const object_js_1=require("../object/object.js"),path_js_1=require("../path/path.js"),filters_js_1=require("../../filters/filters.js"),getJson=value=>{
|
|
1
|
+
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=this&&this.__importStar||function(){var ownKeys=function(o){return ownKeys=Object.getOwnPropertyNames||function(o){var ar=[];for(var k in o)Object.prototype.hasOwnProperty.call(o,k)&&(ar[ar.length]=k);return ar},ownKeys(o)};return function(mod){if(mod&&mod.__esModule)return mod;var result={};if(null!=mod)for(var k=ownKeys(mod),i=0;i<k.length;i++)"default"!==k[i]&&__createBinding(result,mod,k[i]);return __setModuleDefault(result,mod),result}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.getJsonFile=exports.getJson=void 0;const object_js_1=require("../object/object.js"),path_js_1=require("../path/path.js"),filters_js_1=require("../../filters/filters.js"),getJson=value=>{const val=JSON.parse(value);if((0,object_js_1.isObject)(val))return val;throw new Error("Value not an object")};exports.getJson=getJson;const getJsonFile=async(path,store=!1)=>{const newPath=store?(0,path_js_1.getPath)(path,"store"):path,{default:obj}=await Promise.resolve(`${newPath}`).then(s=>__importStar(require(s)));if((0,object_js_1.isObject)(obj))return store?await(0,filters_js_1.applyFilters)("storeData",obj,newPath,!0):obj;throw new Error("No object in JSON file")};exports.getJsonFile=getJsonFile;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
declare const isString: (value: unknown) => value is string;
|
|
2
2
|
declare const isStringStrict: (value: unknown) => value is string;
|
|
3
|
-
|
|
3
|
+
declare const isStringSafe: (value: unknown) => value is string;
|
|
4
|
+
export { isString, isStringStrict, isStringSafe };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isStringStrict=exports.isString=void 0;const isString=value=>"string"==typeof value;exports.isString=isString;const isStringStrict=value=>isString(value)&&""!==value;exports.isStringStrict=isStringStrict;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isStringSafe=exports.isStringStrict=exports.isString=void 0;const isString=value=>"string"==typeof value;exports.isString=isString;const isStringStrict=value=>isString(value)&&""!==value;exports.isStringStrict=isStringStrict;const isStringSafe=value=>isStringStrict(value)&&"__proto__"!==value&&"constructor"!==value&&"prototype"!==value;exports.isStringSafe=isStringSafe;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAllWordPressData=exports.getWordPressData=exports.getRoute=void 0;const wordpressDataNormal_js_1=require("./wordpressDataNormal.js"),filters_js_1=require("../filters/filters.js"),object_js_1=require("../utils/object/object.js"),string_js_1=require("../utils/string/string.js"),array_js_1=require("../utils/array/array.js"),store_js_1=require("../store/store.js"),config_js_1=require("../config/config.js"),getRoute=type=>{const route=wordpressDataNormal_js_1.normalRoutes.get(type);return(0,string_js_1.isString)(route)?route:type};exports.getRoute=getRoute;const getWordPressData=async(args,_page=1)=>{if(!(0,object_js_1.isObjectStrict)(args))throw new Error("No args");const{key:key,route:route,params:params,fetcher:fetcher=fetch,options:options}=args;if(!(0,string_js_1.isStringStrict)(key))throw new Error("No key");if(config_js_1.config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await(0,filters_js_1.applyFilters)("cacheData",void 0,cacheDataFilterArgs,!0);if((0,object_js_1.isObject)(cacheData))return structuredClone(cacheData)}if(!(0,string_js_1.isStringStrict)(route))throw new Error("No route");const{devUser:devUser,prodUser:prodUser,devCredential:devCredential,prodCredential:prodCredential,devHost:devHost,prodHost:prodHost,ssl:ssl=!0}=config_js_1.config.cms;let user=devUser,pass=devCredential,host=devHost,status="any";if(config_js_1.config.env.prod&&(user=prodUser,pass=prodCredential,host=prodHost,status="publish"),!(0,string_js_1.isStringStrict)(user)||!(0,string_js_1.isStringStrict)(pass)||!(0,string_js_1.isStringStrict)(host))throw new Error("No credentials");
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAllWordPressData=exports.getWordPressData=exports.getRoute=void 0;const wordpressDataNormal_js_1=require("./wordpressDataNormal.js"),filters_js_1=require("../filters/filters.js"),object_js_1=require("../utils/object/object.js"),string_js_1=require("../utils/string/string.js"),array_js_1=require("../utils/array/array.js"),store_js_1=require("../store/store.js"),config_js_1=require("../config/config.js"),getRoute=type=>{const route=wordpressDataNormal_js_1.normalRoutes.get(type);return(0,string_js_1.isString)(route)?route:type};exports.getRoute=getRoute;const getWordPressData=async(args,_page=1)=>{if(!(0,object_js_1.isObjectStrict)(args))throw new Error("No args");const{key:key,route:route,params:params,fetcher:fetcher=fetch,options:options}=args;if(!(0,string_js_1.isStringStrict)(key))throw new Error("No key");if(config_js_1.config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await(0,filters_js_1.applyFilters)("cacheData",void 0,cacheDataFilterArgs,!0);if((0,object_js_1.isObject)(cacheData))return structuredClone(cacheData)}if(!(0,string_js_1.isStringStrict)(route))throw new Error("No route");const{devUser:devUser,prodUser:prodUser,devCredential:devCredential,prodCredential:prodCredential,devHost:devHost,prodHost:prodHost,ssl:ssl=!0}=config_js_1.config.cms;let user=devUser,pass=devCredential,host=devHost,status="any";if(config_js_1.config.env.prod&&(user=prodUser,pass=prodCredential,host=prodHost,status="publish"),!(0,string_js_1.isStringStrict)(user)||!(0,string_js_1.isStringStrict)(pass)||!(0,string_js_1.isStringStrict)(host))throw new Error("No credentials");const urlObj=new URL(`${ssl?"https":"http"}://${host}/wp-json/wp/v2/${route}?status=${status}`);let loop=!1,embed=!1;if((0,object_js_1.isObjectStrict)(params))for(const[key,value]of Object.entries(params)){let val=value;"_embed"===key&&(embed=!0),"per_page"===key&&-1===value&&(val=100,loop=!0),urlObj.searchParams.set(key,val.toString())}loop&&urlObj.searchParams.set("page",_page.toString());let url=urlObj.toString();embed||(url+="&_embed");const headers=new Headers;headers.set("Authorization",`Basic ${btoa(`${user}:${pass}`)}`);const resp=await fetcher(url,{headers:headers,...options}),data=await resp.json(),isErr=(0,object_js_1.isObjectStrict)(data)&&(0,string_js_1.isStringStrict)(data.message),message=isErr?data.message:"Bad fetch response";if(!resp.ok||isErr)throw new Error(message,{cause:data});const total=resp.headers.get("X-WP-Total"),totalPages=resp.headers.get("X-WP-TotalPages"),totalNum=(0,string_js_1.isStringStrict)(total)?parseInt(total,10):0,totalPagesNum=(0,string_js_1.isStringStrict)(totalPages)?parseInt(totalPages,10):0,dataItems=(0,array_js_1.isArray)(data)?data:[data];let newItems=(0,wordpressDataNormal_js_1.normalizeWordPressData)(dataItems,route);if(loop&&_page<totalPagesNum){const pagData=await getWordPressData({key:key,route:route,params:{per_page:-1}},_page+1),{items:pagItems}=pagData;newItems=[...newItems,...pagItems]}const newData={items:newItems,total:totalNum,pages:totalPagesNum};if(config_js_1.config.env.cache){const cacheDataFilterArgs={key:key,type:"set",data:data};await(0,filters_js_1.applyFilters)("cacheData",newData,cacheDataFilterArgs,!0)}return newData};exports.getWordPressData=getWordPressData;const getAllWordPressData=async args=>{const{serverlessData:serverlessData,previewData:previewData}=(0,object_js_1.isObjectStrict)(args)?args:{};let allData={navigationItem:[],navigation:[],content:{page:[]}};const isServerless=null!=serverlessData,isPreview=null!=previewData,wordpressDataFilterArgs={serverlessData:serverlessData,previewData:previewData};if(isServerless||isPreview){let contentType="",id="";if(isServerless){const item=(0,store_js_1.getStoreItem)("slugs")[serverlessData.path];if(item){const[itemId,itemContentType]=item;id=itemId||"",contentType=itemContentType||""}}if(isPreview&&(id=previewData.id,contentType=previewData.contentType),id&&(0,string_js_1.isStringSafe)(contentType)){const key=`serverless_${id}_${contentType}`,data=await getWordPressData({key:key,route:`${getRoute(contentType)}/${id}`});let{items:items}=data;items=(0,filters_js_1.applyFilters)("wordpressData",items,{...wordpressDataFilterArgs,contentType:contentType}),allData.content[contentType]=items}}if(!isServerless){const partial=config_js_1.config.partialTypes.filter(type=>(0,string_js_1.isStringSafe)(type));for(const contentType of partial){const isMenu="nav_menu"===contentType,isMenuItem="nav_menu_item"===contentType,partialType=isMenu?"navigation":isMenuItem?"navigationItem":contentType;allData[partialType]=[];const key=`all_${contentType}`,data=await getWordPressData({key:key,route:getRoute(contentType),params:{per_page:-1}});let{items:items}=data;isMenuItem&&(items=(0,wordpressDataNormal_js_1.normalizeWordPressMenuItems)(items)),isMenu&&(items=(0,wordpressDataNormal_js_1.normalizeWordPressMenus)(items)),items=(0,filters_js_1.applyFilters)("wordpressData",items,{...wordpressDataFilterArgs,contentType:contentType}),allData[partialType]=items}}if(!isServerless&&!isPreview){const whole=config_js_1.config.wholeTypes.filter(type=>(0,string_js_1.isStringSafe)(type));for(const contentType of whole){allData.content[contentType]=[];const key=`all_${contentType}`,data=await getWordPressData({key:key,route:getRoute(contentType),params:{per_page:-1}});let{items:items}=data;items=(0,filters_js_1.applyFilters)("wordpressData",items,{...wordpressDataFilterArgs,contentType:contentType}),allData.content[contentType]=items}}return allData=(0,filters_js_1.applyFilters)("allData",allData,{type:"wordpress",serverlessData:serverlessData,previewData:previewData}),allData};exports.getAllWordPressData=getAllWordPressData;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.normalMetaKeys=exports.normalRoutes=exports.normalizeWordPressMenus=exports.normalizeWordPressMenuItems=exports.normalizeWordPressData=void 0;const block_serialization_default_parser_1=require("@wordpress/block-serialization-default-parser"),contentType_js_1=require("../utils/contentType/contentType.js"),objectUtils_js_1=require("../utils/object/objectUtils.js"),store_js_1=require("../store/store.js"),string_js_1=require("../utils/string/string.js"),array_js_1=require("../utils/array/array.js"),object_js_1=require("../utils/object/object.js"),number_js_1=require("../utils/number/number.js"),config_js_1=require("../config/config.js"),normalRoutes=new Map([["page","pages"],["post","posts"],["taxonomy","taxonomies"],["category","categories"],["tag","tags"],["attachment","media"],["nav_menu","menus"],["nav_menu_item","menu-items"]]);exports.normalRoutes=normalRoutes;const normalMetaKeys=new Map;exports.normalMetaKeys=normalMetaKeys;const menusById=new Map,excludeProps=["_links","auto_add"],getTaxonomy=id=>{const taxonomy=(0,store_js_1.getStoreItem)("taxonomies")[id],{title:title="",slug:slug="",contentTypes:contentTypes=[]}=(0,object_js_1.isObjectStrict)(taxonomy)?taxonomy:{};return{id:id,title:title,slug:slug,contentTypes:contentTypes}},normalizeFile=file=>{const{url:url,filename:filename,alt:alt,width:width,height:height,filesizeInBytes:filesizeInBytes,subtype:subtype,mime:mime,sizes:sizes}=file;let newSizes;if((0,object_js_1.isObjectStrict)(sizes)){newSizes={};for(const[,value]of Object.entries(sizes)){const{width:width,source_url:src}=value;let{url:url}=value;(0,string_js_1.isStringStrict)(src)&&(url=src),(0,number_js_1.isNumber)(width)&&(0,string_js_1.isStringStrict)(url)&&(newSizes[width]=url)}}return{url:(0,string_js_1.isString)(url)?url:"",name:(0,string_js_1.isString)(filename)?filename:"",alt:(0,string_js_1.isString)(alt)?alt:"",width:(0,number_js_1.isNumber)(width)?width:0,height:(0,number_js_1.isNumber)(height)?height:0,size:(0,number_js_1.isNumber)(filesizeInBytes)?filesizeInBytes:0,format:"jpeg"===subtype?"jpg":subtype,type:mime,sizes:newSizes}},normalizeEmbedded=(value,item,newItem)=>{(0,objectUtils_js_1.getObjectKeys)(value).forEach(k=>{const embeds=value[k];if((0,array_js_1.isArrayStrict)(embeds)){if("author"===k){const exclude=[...excludeProps,"id","avatar_urls"];embeds.forEach(embed=>{if(!(0,object_js_1.isObjectStrict)(embed))return;const{id:id}=embed;if(item.author!==id)return;const newAuthor={id:id.toString()};Object.entries(embed).forEach(([key,val])=>{exclude.includes(key)||(newAuthor[key]=val)}),newItem.author=newAuthor})}if("up"===k&&embeds.forEach(embed=>{if(!(0,object_js_1.isObjectStrict)(embed))return;const{id:id,title:parentTitle,name:name,type:type,taxonomy:taxonomy,slug:slug}=embed;if(item.parent!==id)return;let title="";(0,string_js_1.isString)(parentTitle?.rendered)&&(title=parentTitle.rendered),(0,string_js_1.isString)(name)&&(title=name),newItem.parent={id:id.toString(),contentType:(0,string_js_1.isString)(taxonomy)?"term":type,title:title,slug:slug}}),"wp:featuredmedia"===k&&embeds.forEach(embed=>{if(!(0,object_js_1.isObjectStrict)(embed))return;const{id:id,source_url:url,media_details:details,mime_type:mimeType,alt_text:alt}=embed;if(!(0,object_js_1.isObjectStrict)(details))return;const{file:file,filesize:filesize,width:width,height:height,sizes:sizes}=details;item.featured_media===id&&(newItem.featured_media=normalizeFile({url:url,filename:file?.split("/").pop(),alt:alt,width:width,height:height,filesizeInBytes:filesize,subtype:mimeType?.split("/").pop(),mime:mimeType,sizes:sizes}))}),"wp:term"===k){const exclude=[...excludeProps,"id","name","taxonomy"];embeds.forEach(embed=>{(0,array_js_1.isArrayStrict)(embed)&&embed.forEach(e=>{if(!(0,object_js_1.isObjectStrict)(e))return;const{id:id,name:name,taxonomy:taxonomy=""}=e;let taxonomyLookup=taxonomy;"category"===taxonomy&&(taxonomyLookup="categories"),"post_tag"===taxonomy&&(taxonomyLookup="tags");const itemTaxonomy=newItem[taxonomyLookup]??item[taxonomyLookup];(0,array_js_1.isArrayStrict)(itemTaxonomy)&&(newItem[taxonomyLookup]=itemTaxonomy.map(taxonomyId=>{if(taxonomyId!==id)return taxonomyId;const newTerm={id:id.toString(),title:name,contentType:"term",taxonomy:getTaxonomy(taxonomy)};return Object.entries(e).forEach(([key,val])=>{exclude.includes(key)||(newTerm[key]=val)}),newTerm}))})})}}})},normalizeBlocks=blocks=>{const newItems=[];return blocks.forEach(block=>{const{blockName:blockName,attrs:attrs,innerBlocks:innerBlocks}=block,contentType=blockName;if(!(0,string_js_1.isStringStrict)(contentType))return;const{isItem:isItem}=attrs,attrItemArr=((0,string_js_1.isStringStrict)(isItem)?isItem:"").split(","),attrItemExists=attrItemArr.length;for(const[key,value]of Object.entries(attrs))if((0,object_js_1.isObjectStrict)(value)){if(attrItemExists&&attrItemArr.includes(key)){const itemValue=normalizeItem(value);itemValue.content=void 0,attrs[key]=itemValue}(0,string_js_1.isStringStrict)(value.mime)&&(attrs[key]=normalizeFile(value))}const newItem={contentType:contentType,...attrs},renderType=config_js_1.config.renderTypes[contentType];return(0,string_js_1.isString)(renderType)&&(newItem.renderType=renderType),(0,array_js_1.isArrayStrict)(innerBlocks)&&(newItem.content=normalizeBlocks(innerBlocks)),newItems.push(newItem)}),newItems},normalizeItem=item=>{const newItem={};for(const[key,value]of Object.entries(item)){if(excludeProps.includes(key))continue;let val=value,k=key;const isObj=(0,object_js_1.isObjectStrict)(value),isStr=(0,string_js_1.isStringStrict)(value);if("id"!==key&&"object_id"!==k||(val=value?.toString()),"type"===key&&isStr)newItem.contentType=(0,contentType_js_1.normalizeContentType)(value),(0,string_js_1.isString)(config_js_1.config.renderTypes[value])&&(newItem.renderType=config_js_1.config.renderTypes[value]);else{if("types"===key&&(k="contentTypes"),isObj){const{rendered:rendered}=value;(0,string_js_1.isString)(rendered)&&(val=rendered)}if("name"===key&&(k="title"),"_embedded"===key&&isObj)normalizeEmbedded(value,item,newItem);else{if((0,string_js_1.isStringStrict)(val)){if("excerpt"===key&&(val=val.replace(/<p>|<\/p>/g,"").trim()),"content"===key){const normalVal=normalizeBlocks((0,block_serialization_default_parser_1.parse)(val));val=normalVal.length?normalVal:val}"taxonomy"===key&&(newItem.contentType="term",val=getTaxonomy(val))}if("meta"===key&&isObj)for(const[metaKey,metaValue]of Object.entries(val)){newItem[normalMetaKeys.get(metaKey)??metaKey]=metaValue}else{if("media_details"===k&&isObj){const valObj=val,valFull=valObj.sizes?.full,sourceUrl=item.source_url,mimeType=item.mime_type;val=normalizeFile({url:sourceUrl,filename:sourceUrl?.split("/").pop(),alt:item.alt_text,width:valFull?.width,height:valFull?.height,filesizeInBytes:valObj.filesize,subtype:mimeType?.split("/")[1],mime:mimeType,sizes:valObj.sizes})}newItem[k]=val}}}}return newItem},normalizeWordPressMenuItems=items=>{const itemsObj=Object.fromEntries(items.map(item=>[item.id,item]));menusById.clear(),items.forEach(item=>{const{id:id="",title:title="",menu_order:menu_order=0,menus:menus=0}=item,parent=item.parent,hasMenuOrder=(0,number_js_1.isNumber)(menu_order);if(hasMenuOrder&&(0,object_js_1.isObjectStrict)(itemsObj[parent])&&(null==itemsObj[parent].children&&(itemsObj[parent].children=[]),itemsObj[parent].children.push({id:id,menu_order:menu_order,title:title})),hasMenuOrder&&(0,number_js_1.isNumber)(menus)&&0===parent){const menuId=menus.toString();null==menusById.get(menuId)&&menusById.set(menuId,[]),menusById.get(menuId)?.push({id:id,menu_order:menu_order,title:title})}});const newItems=[];for(const[id,obj]of Object.entries(itemsObj)){const{url:url="",title:title="",contentType:contentType="",children:children=[],object:object="",object_id:object_id="",locale:locale=""}=obj;if(!(0,string_js_1.isString)(url)||!(0,string_js_1.isStringStrict)(title))continue;const newItem={id:id,title:title},isCustom="custom"===contentType;if(!isCustom&&(0,string_js_1.isStringStrict)(object)&&(0,string_js_1.isStringStrict)(object_id)){const isTerm="taxonomy"===contentType,internalLink={contentType:isTerm?"term":object,id:object_id,slug:url.split("/").filter(Boolean).pop()};isTerm&&(internalLink.taxonomy=getTaxonomy(object)),(0,string_js_1.isStringStrict)(locale)&&(internalLink.locale=locale),newItem.link=url,newItem.internalLink=internalLink}if(isCustom){url.startsWith("http")&&!url.startsWith(config_js_1.config.env.prodUrl)?newItem.externalLink=url:newItem.link=url}(0,array_js_1.isArrayStrict)(children)&&(newItem.children=children.sort((a,b)=>a.menu_order-b.menu_order));const exclude=[...excludeProps,"url","type","type_label","object","object_id","invalid","meta","menu_order","menus","parent","contentType","status"];Object.entries(obj).forEach(([key,val])=>{exclude.includes(key)||(newItem[key]=val)}),newItems.push(newItem)}return newItems};exports.normalizeWordPressMenuItems=normalizeWordPressMenuItems;const normalizeWordPressMenus=menus=>{const newMenus=[];return menus.forEach(menu=>{const{id:id="",title:title="",description:description="",locations:locations=[],meta:meta=[]}=menu,newMenu={id:id,title:title,description:description,meta:meta,location:locations,items:menusById.get(id)?.sort((a,b)=>a.menu_order-b.menu_order)??[]};newMenus.push(newMenu)}),newMenus};exports.normalizeWordPressMenus=normalizeWordPressMenus;const normalizeWordPressData=(data,route,_newData=[])=>(0,array_js_1.isArrayStrict)(data)?("taxonomies"===route&&(data=Object.entries(data[0]).map(([key,value])=>({id:key,type:"taxonomy",...value}))),data.forEach(item=>{(0,object_js_1.isObjectStrict)(item)&&_newData.push(normalizeItem(item))}),"taxonomies"===route&&_newData.forEach(item=>{(0,store_js_1.setStoreItem)("taxonomies",item,item.id)}),_newData):[];exports.normalizeWordPressData=normalizeWordPressData;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.normalMetaKeys=exports.normalRoutes=exports.normalizeWordPressMenus=exports.normalizeWordPressMenuItems=exports.normalizeWordPressData=void 0;const block_serialization_default_parser_1=require("@wordpress/block-serialization-default-parser"),contentType_js_1=require("../utils/contentType/contentType.js"),objectUtils_js_1=require("../utils/object/objectUtils.js"),store_js_1=require("../store/store.js"),string_js_1=require("../utils/string/string.js"),array_js_1=require("../utils/array/array.js"),object_js_1=require("../utils/object/object.js"),number_js_1=require("../utils/number/number.js"),config_js_1=require("../config/config.js"),normalRoutes=new Map([["page","pages"],["post","posts"],["taxonomy","taxonomies"],["category","categories"],["tag","tags"],["attachment","media"],["nav_menu","menus"],["nav_menu_item","menu-items"]]);exports.normalRoutes=normalRoutes;const normalMetaKeys=new Map;exports.normalMetaKeys=normalMetaKeys;const menusById=new Map,excludeProps=["_links","auto_add"],getTaxonomy=id=>{const taxonomy=(0,store_js_1.getStoreItem)("taxonomies")[id],{title:title="",slug:slug="",contentTypes:contentTypes=[]}=(0,object_js_1.isObjectStrict)(taxonomy)?taxonomy:{};return{id:id,title:title,slug:slug,contentTypes:contentTypes}},normalizeFile=file=>{const{url:url,filename:filename,alt:alt,width:width,height:height,filesizeInBytes:filesizeInBytes,subtype:subtype,mime:mime,sizes:sizes}=file;let newSizes;if((0,object_js_1.isObjectStrict)(sizes)){newSizes={};for(const[,value]of Object.entries(sizes)){const{width:width,source_url:src}=value;let{url:url}=value;(0,string_js_1.isStringStrict)(src)&&(url=src),(0,number_js_1.isNumber)(width)&&(0,string_js_1.isStringStrict)(url)&&(newSizes[width]=url)}}return{url:(0,string_js_1.isString)(url)?url:"",name:(0,string_js_1.isString)(filename)?filename:"",alt:(0,string_js_1.isString)(alt)?alt:"",width:(0,number_js_1.isNumber)(width)?width:0,height:(0,number_js_1.isNumber)(height)?height:0,size:(0,number_js_1.isNumber)(filesizeInBytes)?filesizeInBytes:0,format:"jpeg"===subtype?"jpg":subtype,type:mime,sizes:newSizes}},normalizeEmbedded=(value,item,newItem)=>{(0,objectUtils_js_1.getObjectKeys)(value).forEach(k=>{const embeds=value[k];if((0,array_js_1.isArrayStrict)(embeds)){if("author"===k){const exclude=[...excludeProps,"id","avatar_urls"];embeds.forEach(embed=>{if(!(0,object_js_1.isObjectStrict)(embed))return;const{id:id}=embed;if(item.author!==id)return;const newAuthor={id:id.toString()};Object.entries(embed).forEach(([key,val])=>{!exclude.includes(key)&&(0,string_js_1.isStringSafe)(key)&&(newAuthor[key]=val)}),newItem.author=newAuthor})}if("up"===k&&embeds.forEach(embed=>{if(!(0,object_js_1.isObjectStrict)(embed))return;const{id:id,title:parentTitle,name:name,type:type,taxonomy:taxonomy,slug:slug}=embed;if(item.parent!==id)return;let title="";(0,string_js_1.isString)(parentTitle?.rendered)&&(title=parentTitle.rendered),(0,string_js_1.isString)(name)&&(title=name),newItem.parent={id:id.toString(),contentType:(0,string_js_1.isString)(taxonomy)?"term":type,title:title,slug:slug}}),"wp:featuredmedia"===k&&embeds.forEach(embed=>{if(!(0,object_js_1.isObjectStrict)(embed))return;const{id:id,source_url:url,media_details:details,mime_type:mimeType,alt_text:alt}=embed;if(!(0,object_js_1.isObjectStrict)(details))return;const{file:file,filesize:filesize,width:width,height:height,sizes:sizes}=details;item.featured_media===id&&(newItem.featured_media=normalizeFile({url:url,filename:file?.split("/").pop(),alt:alt,width:width,height:height,filesizeInBytes:filesize,subtype:mimeType?.split("/").pop(),mime:mimeType,sizes:sizes}))}),"wp:term"===k){const exclude=[...excludeProps,"id","name","taxonomy"];embeds.forEach(embed=>{(0,array_js_1.isArrayStrict)(embed)&&embed.forEach(e=>{if(!(0,object_js_1.isObjectStrict)(e))return;const{id:id,name:name,taxonomy:taxonomy=""}=e;let taxonomyLookup=taxonomy;"category"===taxonomy&&(taxonomyLookup="categories"),"post_tag"===taxonomy&&(taxonomyLookup="tags");const itemTaxonomy=newItem[taxonomyLookup]||item[taxonomyLookup];(0,string_js_1.isStringSafe)(taxonomyLookup)&&(0,array_js_1.isArrayStrict)(itemTaxonomy)&&(newItem[taxonomyLookup]=itemTaxonomy.map(taxonomyId=>{if(taxonomyId!==id)return taxonomyId;const newTerm={id:id.toString(),title:name,contentType:"term",taxonomy:getTaxonomy(taxonomy)};return Object.entries(e).forEach(([key,val])=>{!exclude.includes(key)&&(0,string_js_1.isStringSafe)(key)&&(newTerm[key]=val)}),newTerm}))})})}}})},normalizeBlocks=blocks=>{const newItems=[];return blocks.forEach(block=>{const{blockName:blockName,attrs:attrs,innerBlocks:innerBlocks}=block,contentType=blockName;if(!(0,string_js_1.isStringStrict)(contentType))return;const{isItem:isItem}=attrs,attrItemArr=((0,string_js_1.isStringStrict)(isItem)?isItem:"").split(","),attrItemExists=attrItemArr.length,newItem={contentType:contentType};for(const[key,value]of Object.entries(attrs)){if(!(0,string_js_1.isStringSafe)(key))continue;const isObj=(0,object_js_1.isObjectStrict)(value);if(isObj&&attrItemExists&&attrItemArr.includes(key)){const itemValue=normalizeItem(value);itemValue.content=void 0,newItem[key]=itemValue;continue}isObj&&(0,string_js_1.isStringStrict)(value.mime)?newItem[key]=normalizeFile(value):newItem[key]=value}const renderType=config_js_1.config.renderTypes[contentType];return(0,string_js_1.isString)(renderType)&&(newItem.renderType=renderType),(0,array_js_1.isArrayStrict)(innerBlocks)&&(newItem.content=normalizeBlocks(innerBlocks)),newItems.push(newItem)}),newItems},normalizeItem=item=>{const newItem={};for(const[key,value]of Object.entries(item)){if(excludeProps.includes(key)||!(0,string_js_1.isStringSafe)(key))continue;let val=value,k=key;const isObj=(0,object_js_1.isObjectStrict)(value),isStr=(0,string_js_1.isStringStrict)(value);if("id"!==key&&"object_id"!==k||(val=value?.toString()),"type"===key&&isStr)newItem.contentType=(0,contentType_js_1.normalizeContentType)(value),(0,string_js_1.isString)(config_js_1.config.renderTypes[value])&&(newItem.renderType=config_js_1.config.renderTypes[value]);else{if("types"===key&&(k="contentTypes"),isObj){const{rendered:rendered}=value;(0,string_js_1.isString)(rendered)&&(val=rendered)}if("name"===key&&(k="title"),"_embedded"===key&&isObj)normalizeEmbedded(value,item,newItem);else{if((0,string_js_1.isStringStrict)(val)){if("excerpt"===key&&(val=val.replace(/<p>|<\/p>/g,"").trim()),"content"===key){const normalVal=normalizeBlocks((0,block_serialization_default_parser_1.parse)(val));val=normalVal.length?normalVal:val}"taxonomy"===key&&(newItem.contentType="term",val=getTaxonomy(val))}if("meta"===key&&isObj)for(const[metaKey,metaValue]of Object.entries(val))(0,string_js_1.isStringSafe)(metaKey)&&(newItem[normalMetaKeys.get(metaKey)||metaKey]=metaValue);else{if("media_details"===k&&isObj){const valObj=val,valFull=valObj.sizes?.full,sourceUrl=item.source_url,mimeType=item.mime_type;val=normalizeFile({url:sourceUrl,filename:sourceUrl?.split("/").pop(),alt:item.alt_text,width:valFull?.width,height:valFull?.height,filesizeInBytes:valObj.filesize,subtype:mimeType?.split("/")[1],mime:mimeType,sizes:valObj.sizes})}newItem[k]=val}}}}return newItem},normalizeWordPressMenuItems=items=>{const itemsObj=Object.fromEntries(items.map(item=>[item.id,item]));menusById.clear(),items.forEach(item=>{const{id:id="",title:title="",menu_order:menu_order=0,menus:menus=0}=item,parent=item.parent,hasMenuOrder=(0,number_js_1.isNumber)(menu_order);if(hasMenuOrder&&(0,object_js_1.isObjectStrict)(itemsObj[parent])&&(null==itemsObj[parent].children&&(itemsObj[parent].children=[]),itemsObj[parent].children.push({id:id,menu_order:menu_order,title:title})),hasMenuOrder&&(0,number_js_1.isNumber)(menus)&&0===parent){const menuId=menus.toString();null==menusById.get(menuId)&&menusById.set(menuId,[]),menusById.get(menuId)?.push({id:id,menu_order:menu_order,title:title})}});const newItems=[];for(const[id,obj]of Object.entries(itemsObj)){const{url:url="",title:title="",contentType:contentType="",children:children=[],object:object="",object_id:object_id="",locale:locale=""}=obj;if(!(0,string_js_1.isString)(url)||!(0,string_js_1.isStringStrict)(title))continue;const newItem={id:id,title:title},isCustom="custom"===contentType;if(!isCustom&&(0,string_js_1.isStringStrict)(object)&&(0,string_js_1.isStringStrict)(object_id)){const isTerm="taxonomy"===contentType,internalLink={contentType:isTerm?"term":object,id:object_id,slug:url.split("/").filter(Boolean).pop()};isTerm&&(internalLink.taxonomy=getTaxonomy(object)),(0,string_js_1.isStringStrict)(locale)&&(internalLink.locale=locale),newItem.link=url,newItem.internalLink=internalLink}if(isCustom){url.startsWith("http")&&!url.startsWith(config_js_1.config.env.prodUrl)?newItem.externalLink=url:newItem.link=url}(0,array_js_1.isArrayStrict)(children)&&(newItem.children=children.sort((a,b)=>a.menu_order-b.menu_order));const exclude=[...excludeProps,"url","type","type_label","object","object_id","invalid","meta","menu_order","menus","parent","contentType","status","xfn"];Object.entries(obj).forEach(([key,val])=>{!exclude.includes(key)&&(0,string_js_1.isStringSafe)(key)&&(newItem[key]=val)}),newItems.push(newItem)}return newItems};exports.normalizeWordPressMenuItems=normalizeWordPressMenuItems;const normalizeWordPressMenus=menus=>{const newMenus=[];return menus.forEach(menu=>{const{id:id="",title:title="",description:description="",locations:locations=[],meta:meta=[]}=menu,newMenu={id:id,title:title,description:description,meta:meta,location:locations,items:menusById.get(id)?.sort((a,b)=>a.menu_order-b.menu_order)||[]};newMenus.push(newMenu)}),newMenus};exports.normalizeWordPressMenus=normalizeWordPressMenus;const normalizeWordPressData=(data,route,_newData=[])=>(0,array_js_1.isArrayStrict)(data)?("taxonomies"===route&&(data=Object.entries(data[0]).map(([key,value])=>({id:key,type:"taxonomy",...value}))),data.forEach(item=>{(0,object_js_1.isObjectStrict)(item)&&_newData.push(normalizeItem(item))}),"taxonomies"===route&&_newData.forEach(item=>{(0,store_js_1.setStoreItem)("taxonomies",item,item.id)}),_newData):[];exports.normalizeWordPressData=normalizeWordPressData;
|
package/lib/actions/actions.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isSet,isSetStrict}from"../utils/set/set.js";import{isStringStrict}from"../utils/string/string.js";import{isObjectStrict}from"../utils/object/object.js";import{isFunction}from"../utils/function/function.js";let actions=new Map([["renderStart",new Set],["renderEnd",new Set],["renderItemStart",new Set],["renderItemEnd",new Set]]);const addAction=(name,action)=>!(!isStringStrict(name)||!isFunction(action))&&(isSet(actions.get(name))||actions.set(name,new Set),actions.get(name)?.add(action),!0),removeAction=(name,action)=>{if(!isStringStrict(name)||!isFunction(action))return!1;const actionSet=actions.get(name);return!!isSet(actionSet)&&actionSet.delete(action)},doSequentially=async(callbacks,args)=>{for(const callback of callbacks)await callback(args)},doActions=(name,args,isAsync=!1)=>{const actionSet=actions.get(name);if(!isSetStrict(actionSet))return;const callbacks=[];for(const callback of actionSet.values())isAsync?callbacks.push(callback):callback(args);isAsync
|
|
1
|
+
import{isSet,isSetStrict}from"../utils/set/set.js";import{isStringStrict}from"../utils/string/string.js";import{isObjectStrict}from"../utils/object/object.js";import{isFunction}from"../utils/function/function.js";let actions=new Map([["renderStart",new Set],["renderEnd",new Set],["renderItemStart",new Set],["renderItemEnd",new Set]]);const addAction=(name,action)=>!(!isStringStrict(name)||!isFunction(action))&&(isSet(actions.get(name))||actions.set(name,new Set),actions.get(name)?.add(action),!0),removeAction=(name,action)=>{if(!isStringStrict(name)||!isFunction(action))return!1;const actionSet=actions.get(name);return!!isSet(actionSet)&&actionSet.delete(action)},doSequentially=async(callbacks,args)=>{for(const callback of callbacks)await callback(args)},doActions=(name,args,isAsync=!1)=>{const actionSet=actions.get(name);if(!isSetStrict(actionSet))return;const callbacks=[];for(const callback of actionSet.values())isAsync?callbacks.push(callback):callback(args);return isAsync?doSequentially(callbacks,args).then(result=>result):void 0},resetActions=()=>{actions=new Map([["renderStart",new Set],["renderEnd",new Set],["renderItemStart",new Set],["renderItemEnd",new Set]])},setActions=args=>{if(!isObjectStrict(args))return!1;const newActions=Object.entries(args);return!!newActions.length&&(resetActions(),newActions.forEach(([name,action])=>{action&&addAction(name,action)}),!0)};export{actions,addAction,removeAction,doActions,resetActions,setActions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import resolveResponse from"contentful-resolve-response";import{applyFilters}from"../filters/filters.js";import{isObject,isObjectStrict}from"../utils/object/object.js";import{isStringStrict}from"../utils/string/string.js";import{config}from"../config/config.js";import{getStoreItem}from"../store/store.js";import{normalizeContentfulData}from"./contentfulDataNormal.js";const getContentfulData=async(key,params)=>{if(!isStringStrict(key))throw new Error("No key");if(config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await applyFilters("cacheData",void 0,cacheDataFilterArgs,!0);if(isObject(cacheData))return structuredClone(cacheData)}const{space:space,devCredential:devCredential,prodCredential:prodCredential,devHost:devHost,prodHost:prodHost,env:env="master"}=config.cms;let accessToken=devCredential,host=devHost;if(config.env.prod&&(accessToken=prodCredential,host=prodHost),!isStringStrict(space)||!isStringStrict(accessToken)||!isStringStrict(host))throw new Error("No credentials");
|
|
1
|
+
import resolveResponse from"contentful-resolve-response";import{applyFilters}from"../filters/filters.js";import{isObject,isObjectStrict}from"../utils/object/object.js";import{isStringSafe,isStringStrict}from"../utils/string/string.js";import{config}from"../config/config.js";import{getStoreItem}from"../store/store.js";import{normalizeContentfulData}from"./contentfulDataNormal.js";const getContentfulData=async(key,params)=>{if(!isStringStrict(key))throw new Error("No key");if(config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await applyFilters("cacheData",void 0,cacheDataFilterArgs,!0);if(isObject(cacheData))return structuredClone(cacheData)}const{space:space,devCredential:devCredential,prodCredential:prodCredential,devHost:devHost,prodHost:prodHost,env:env="master"}=config.cms;let accessToken=devCredential,host=devHost;if(config.env.prod&&(accessToken=prodCredential,host=prodHost),!isStringStrict(space)||!isStringStrict(accessToken)||!isStringStrict(host))throw new Error("No credentials");const url=new URL(`https://${host}/spaces/${space}/environments/${env}/entries?access_token=${accessToken}`);if(isObjectStrict(params))for(const[key,value]of Object.entries(params))url.searchParams.set(key,value.toString());const resp=await fetch(url.toString()),data=await resp.json();if(!resp.ok){const message=isStringStrict(data.message)?data.message:"Bad fetch response";throw new Error(message,{cause:data})}const resolvedData=resolveResponse(data),newItems=normalizeContentfulData(resolvedData),{total:total,limit:limit,skip:skip}=data,newData={items:newItems,total:total,limit:limit,skip:skip};if(config.env.cache){const cacheDataFilterArgs={key:key,type:"set",data:data};await applyFilters("cacheData",newData,cacheDataFilterArgs,!0)}return newData},getAllContentfulData=async args=>{const{serverlessData:serverlessData,previewData:previewData}=isObjectStrict(args)?args:{};let allData={navigationItem:[],navigation:[],content:{page:[]}};const isServerless=null!=serverlessData,isPreview=null!=previewData,contentfulDataFilterArgs={serverlessData:serverlessData,previewData:previewData},cmsLocales=config.cms.locales||[],defaultLocale=cmsLocales[0],paramLocales=isPreview?[]:[...cmsLocales];if(0===paramLocales.length&¶mLocales.push(""),isServerless||isPreview){let locale,contentType="",id="";if(isServerless){const item=getStoreItem("slugs")[serverlessData.path];if(item){const[itemId,itemContentType,itemLocale]=item;id=itemId||"",contentType=itemContentType||"",locale=itemLocale||""}}if(isPreview&&(id=previewData.id,contentType=previewData.contentType,locale=previewData.locale),id&&isStringSafe(contentType)){const key=`serverless_${id}_${contentType}`,params={content_type:contentType,"sys.id":id,include:10};locale&&locale!==defaultLocale&&(params.locale=locale,paramLocales[0]=locale);const data=await getContentfulData(key,params);let{items:items}=data;items=applyFilters("contentfulData",items,{...contentfulDataFilterArgs,contentType:contentType}),allData.content[contentType]=items}}if(!isServerless){const partial=config.partialTypes.filter(type=>isStringSafe(type));for(const contentType of partial){const key=`all_${contentType}`;let newItems=[];for(const locale of paramLocales){const params={content_type:contentType};locale&&locale!==defaultLocale&&(params.locale=locale);const newData=await getContentfulData(key,params);let{items:items}=newData;items=applyFilters("contentfulData",items,{...contentfulDataFilterArgs,contentType:contentType}),newItems=[...newItems,...items]}allData[contentType]=newItems}}if(!isServerless&&!isPreview){const whole=config.wholeTypes.filter(type=>isStringSafe(type));for(const contentType of whole){const key=`all_${contentType}`;let newItems=[];for(const locale of paramLocales){const params={content_type:contentType,include:10};locale&&locale!==defaultLocale&&(params.locale=locale);const newData=await getContentfulData(key,params);let{items:items}=newData;items=applyFilters("contentfulData",items,{...contentfulDataFilterArgs,contentType:contentType}),newItems=[...newItems,...items]}allData.content[contentType]=newItems}}return allData=applyFilters("allData",allData,{type:"contentful",serverlessData:serverlessData,previewData:previewData}),allData};export{getContentfulData,getAllContentfulData};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{normalizeContentType}from"../utils/contentType/contentType.js";import{isArrayStrict}from"../utils/array/array.js";import{isObjectStrict}from"../utils/object/object.js";import{isString,isStringStrict}from"../utils/string/string.js";import{getObjectKeys}from"../utils/object/objectUtils.js";import{isNumber}from"../utils/number/number.js";import{config}from"../config/config.js";const getTag=(type="text")=>({br:"br",hr:"hr",paragraph:"p",blockquote:"blockquote",bold:"b",italic:"i",underline:"u",superscript:"sup",subscript:"sub",code:"code",hyperlink:"a","entry-hyperlink":"a","asset-hyperlink":"a","heading-1":"h1","heading-2":"h2","heading-3":"h3","heading-4":"h4","heading-5":"h5","heading-6":"h6","list-item":"li","unordered-list":"ul","ordered-list":"ol",table:"table","table-row":"tr","table-cell":"td","table-header-cell":"th"}[type]||""),normalizeRichText=items=>{const newItems=[];return items.forEach(item=>{if(!isObjectStrict(item))return;const{nodeType:nodeType,data:data,value:value,marks:marks,content:content}=item,tag=getTag(nodeType);let contentValue,link,internalLink;if(isStringStrict(value)&&(contentValue=value,contentValue=contentValue.replace(/\n/g,"<br>"),isArrayStrict(marks))){const markTags=marks.map(m=>getTag(m.type));contentValue=`${markTags.map(m=>`<${m}>`).join("")}${value}${markTags.map(m=>`</${m}>`).join("")}`}if(isStringStrict(content)&&(contentValue=content),isArrayStrict(content)&&(contentValue=normalizeRichText(content)),isObjectStrict(data)&&(link=isString(data.uri)?data.uri:"",isObjectStrict(data.target))){const target=data.target;"entry-hyperlink"!==nodeType&&"embedded-entry-inline"!==nodeType||(internalLink=target);const url=target.fields?.file?.url;"asset-hyperlink"===nodeType&&isString(url)&&(link=`https:${url}`)}if(!contentValue)return;const newItem={content:contentValue};return isStringStrict(tag)&&(newItem.tag=tag),isStringStrict(link)&&(newItem.link=link),isObjectStrict(internalLink)&&(newItem.internalLink=normalizeItem(internalLink,[],!0)),newItems.push(newItem)}),newItems},normalizeFile=(file,fields)=>{const type=isString(file.contentType)?file.contentType:"",format=type?type.split("/")[1]:"";return{url:isString(file.url)?`https:${file.url}`:"",name:isString(file.fileName)?file.fileName:"",alt:isString(fields.description)?fields.description:"",width:isNumber(file.details?.image?.width)?file.details.image.width:0,height:isNumber(file.details?.image?.height)?file.details.image.height:0,size:isNumber(file.details?.size)?file.details.size:0,format:"jpeg"===format?"jpg":format,type:type}},normalizeItem=(item,data,isInternalLink=!1)=>{let newItem={};const itemCopy={...item};isString(itemCopy.sys?.id)&&(newItem.id=itemCopy.sys.id),isStringStrict(itemCopy.sys?.locale)&&(newItem.locale=itemCopy.sys.locale);let type="";if(isString(itemCopy.sys?.type)&&(type=itemCopy.sys.type),isString(itemCopy.sys?.contentType?.sys?.id)&&(type=itemCopy.sys.contentType.sys.id),type&&"Link"!==type&&(newItem.contentType=normalizeContentType(type),isString(config.renderTypes[type])&&(newItem.renderType=config.renderTypes[type])),isArrayStrict(itemCopy.metadata?.tags)&&(newItem.metadata={tags:itemCopy.metadata.tags.map(t=>({id:isString(t.sys?.id)?t.sys.id:""}))}),isObjectStrict(itemCopy.fields)){const fields=itemCopy.fields,file=fields.file;if(isObjectStrict(file))return{...normalizeFile(file,fields),...newItem};getObjectKeys(fields).forEach(prop=>{const field=fields[prop];if(
|
|
1
|
+
import{normalizeContentType}from"../utils/contentType/contentType.js";import{isArrayStrict}from"../utils/array/array.js";import{isObjectStrict}from"../utils/object/object.js";import{isString,isStringSafe,isStringStrict}from"../utils/string/string.js";import{getObjectKeys}from"../utils/object/objectUtils.js";import{isNumber}from"../utils/number/number.js";import{config}from"../config/config.js";const getTag=(type="text")=>({br:"br",hr:"hr",paragraph:"p",blockquote:"blockquote",bold:"b",italic:"i",underline:"u",superscript:"sup",subscript:"sub",code:"code",hyperlink:"a","entry-hyperlink":"a","asset-hyperlink":"a","heading-1":"h1","heading-2":"h2","heading-3":"h3","heading-4":"h4","heading-5":"h5","heading-6":"h6","list-item":"li","unordered-list":"ul","ordered-list":"ol",table:"table","table-row":"tr","table-cell":"td","table-header-cell":"th"}[type]||""),normalizeRichText=items=>{const newItems=[];return items.forEach(item=>{if(!isObjectStrict(item))return;const{nodeType:nodeType,data:data,value:value,marks:marks,content:content}=item,tag=getTag(nodeType);let contentValue,link,internalLink;if(isStringStrict(value)&&(contentValue=value,contentValue=contentValue.replace(/\n/g,"<br>"),isArrayStrict(marks))){const markTags=marks.map(m=>getTag(m.type));contentValue=`${markTags.map(m=>`<${m}>`).join("")}${value}${markTags.map(m=>`</${m}>`).join("")}`}if(isStringStrict(content)&&(contentValue=content),isArrayStrict(content)&&(contentValue=normalizeRichText(content)),isObjectStrict(data)&&(link=isString(data.uri)?data.uri:"",isObjectStrict(data.target))){const target=data.target;"entry-hyperlink"!==nodeType&&"embedded-entry-inline"!==nodeType||(internalLink=target);const url=target.fields?.file?.url;"asset-hyperlink"===nodeType&&isString(url)&&(link=`https:${url}`)}if(!contentValue)return;const newItem={content:contentValue};return isStringStrict(tag)&&(newItem.tag=tag),isStringStrict(link)&&(newItem.link=link),isObjectStrict(internalLink)&&(newItem.internalLink=normalizeItem(internalLink,[],!0)),newItems.push(newItem)}),newItems},normalizeFile=(file,fields)=>{const type=isString(file.contentType)?file.contentType:"",format=type?type.split("/")[1]:"";return{url:isString(file.url)?`https:${file.url}`:"",name:isString(file.fileName)?file.fileName:"",alt:isString(fields.description)?fields.description:"",width:isNumber(file.details?.image?.width)?file.details.image.width:0,height:isNumber(file.details?.image?.height)?file.details.image.height:0,size:isNumber(file.details?.size)?file.details.size:0,format:"jpeg"===format?"jpg":format,type:type}},normalizeItem=(item,data,isInternalLink=!1)=>{let newItem={};const itemCopy={...item};isString(itemCopy.sys?.id)&&(newItem.id=itemCopy.sys.id),isStringStrict(itemCopy.sys?.locale)&&(newItem.locale=itemCopy.sys.locale);let type="";if(isString(itemCopy.sys?.type)&&(type=itemCopy.sys.type),isString(itemCopy.sys?.contentType?.sys?.id)&&(type=itemCopy.sys.contentType.sys.id),type&&"Link"!==type&&(newItem.contentType=normalizeContentType(type),isString(config.renderTypes[type])&&(newItem.renderType=config.renderTypes[type])),isArrayStrict(itemCopy.metadata?.tags)&&(newItem.metadata={tags:itemCopy.metadata.tags.map(t=>({id:isString(t.sys?.id)?t.sys.id:""}))}),isObjectStrict(itemCopy.fields)){const fields=itemCopy.fields,file=fields.file;if(isObjectStrict(file))return{...normalizeFile(file,fields),...newItem};getObjectKeys(fields).forEach(prop=>{if(!isStringSafe(prop)||"content"===prop&&isInternalLink)return;const field=fields[prop];if(isObjectStrict(field))if("document"===field.nodeType){const{content:content}=field;isArrayStrict(content)&&(newItem[prop]=content.map(c=>isObjectStrict(c)?normalizeItem(c,data,isInternalLink):c))}else newItem[prop]=normalizeItem(field,data,"internalLink"===prop);else isArrayStrict(field)?newItem[prop]=field.map(f=>isObjectStrict(f)?normalizeItem(f,data,isInternalLink):f):newItem[prop]=field})}if(isString(itemCopy.nodeType)){const nodeType=itemCopy.nodeType;if("embedded-entry-block"===nodeType||"embedded-asset-block"===nodeType){const content=isObjectStrict(itemCopy.data?.target)?itemCopy.data.target:{};newItem=normalizeItem(content,data,isInternalLink)}else newItem.renderType="richText",newItem.tag=getTag(itemCopy.nodeType),isString(itemCopy.content)&&(newItem.content=itemCopy.content),isArrayStrict(itemCopy.content)&&(newItem.content=normalizeRichText(itemCopy.content))}return newItem},normalizeContentfulData=(data,_newData=[])=>isArrayStrict(data)?(data.forEach(item=>{isObjectStrict(item)&&_newData.push(normalizeItem(item,_newData))}),_newData):[];export{normalizeContentfulData};
|
package/lib/filters/filters.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isSet,isSetStrict}from"../utils/set/set.js";import{isStringStrict}from"../utils/string/string.js";import{isObjectStrict}from"../utils/object/object.js";import{isFunction}from"../utils/function/function.js";let filters=new Map([["columnProps",new Set],["containerProps",new Set],["formOptionProps",new Set],["formFieldProps",new Set],["formProps",new Set],["richTextProps",new Set],["richTextOutput",new Set],["richTextContentItem",new Set],["richTextContent",new Set],["richTextContentOutput",new Set],["renderItem",new Set],["renderItemData",new Set],["renderContent",new Set],["serverlessResult",new Set],["contactResult",new Set],["cacheData",new Set],["storeData",new Set],["contentfulData",new Set],["wordpressData",new Set],["localData",new Set],["allData",new Set],["slugParts",new Set],["slug",new Set]]);const addFilter=(name,filter)=>!(!isStringStrict(name)||!isFunction(filter))&&(isSet(filters.get(name))||filters.set(name,new Set),filters.get(name)?.add(filter),!0),removeFilter=(name,filter)=>{if(!isStringStrict(name)||!isFunction(filter))return!1;const filterSet=filters.get(name);return!!isSet(filterSet)&&filterSet.delete(filter)},applySequentially=async(callbacks,value,args)=>{for(const callback of callbacks)value=await callback(value,args);return value},applyFilters=(name,value,args,isAsync=!1)=>{const filterSet=filters.get(name);if(!isSetStrict(filterSet))return value;const callbacks=[];for(const callback of filterSet.values())isAsync?callbacks.push(callback):value=callback(value,args);return isAsync?applySequentially(callbacks,value,args).then(newValue=>newValue)
|
|
1
|
+
import{isSet,isSetStrict}from"../utils/set/set.js";import{isStringStrict}from"../utils/string/string.js";import{isObjectStrict}from"../utils/object/object.js";import{isFunction}from"../utils/function/function.js";let filters=new Map([["columnProps",new Set],["containerProps",new Set],["formOptionProps",new Set],["formFieldProps",new Set],["formProps",new Set],["richTextProps",new Set],["richTextOutput",new Set],["richTextContentItem",new Set],["richTextContent",new Set],["richTextContentOutput",new Set],["renderItem",new Set],["renderItemData",new Set],["renderContent",new Set],["serverlessResult",new Set],["contactResult",new Set],["cacheData",new Set],["storeData",new Set],["contentfulData",new Set],["wordpressData",new Set],["localData",new Set],["allData",new Set],["slugParts",new Set],["slug",new Set]]);const addFilter=(name,filter)=>!(!isStringStrict(name)||!isFunction(filter))&&(isSet(filters.get(name))||filters.set(name,new Set),filters.get(name)?.add(filter),!0),removeFilter=(name,filter)=>{if(!isStringStrict(name)||!isFunction(filter))return!1;const filterSet=filters.get(name);return!!isSet(filterSet)&&filterSet.delete(filter)},applySequentially=async(callbacks,value,args)=>{for(const callback of callbacks)value=await callback(value,args);return value},applyFilters=(name,value,args,isAsync=!1)=>{const filterSet=filters.get(name);if(!isSetStrict(filterSet))return value;const callbacks=[];for(const callback of filterSet.values())isAsync?callbacks.push(callback):value=callback(value,args);return isAsync?applySequentially(callbacks,value,args).then(newValue=>newValue):value},resetFilters=()=>{filters=new Map([["columnProps",new Set],["containerProps",new Set],["formOptionProps",new Set],["formFieldProps",new Set],["formProps",new Set],["richTextProps",new Set],["richTextOutput",new Set],["richTextContentItem",new Set],["richTextContent",new Set],["richTextContentOutput",new Set],["renderItem",new Set],["renderItemData",new Set],["renderContent",new Set],["serverlessResult",new Set],["contactResult",new Set],["cacheData",new Set],["storeData",new Set],["contentfulData",new Set],["wordpressData",new Set],["localData",new Set],["allData",new Set],["slugParts",new Set],["slug",new Set]])},setFilters=args=>{if(!isObjectStrict(args))return!1;const newFilters=Object.entries(args);return!!newFilters.length&&(resetFilters(),newFilters.forEach(([name,filter])=>{filter&&addFilter(name,filter)}),!0)};export{filters,addFilter,removeFilter,applyFilters,resetFilters,setFilters};
|
package/lib/local/localData.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readdir,readFile}from"node:fs/promises";import{extname,basename,resolve}from"node:path";import{isObject,isObjectStrict}from"../utils/object/object.js";import{isStringStrict}from"../utils/string/string.js";import{applyFilters}from"../filters/filters.js";import{getJson}from"../utils/json/json.js";import{config}from"../config/config.js";import{normalizeLocalData}from"./localDataNormal.js";const getLocalData=async args=>{if(!isObjectStrict(args))throw new Error("No args");const{key:key,refProps:refProps,imageProps:imageProps,unsetProps:unsetProps}=args;if(!isStringStrict(key))throw new Error("No key");if(config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await applyFilters("cacheData",void 0,cacheDataFilterArgs,!0),cacheItems=cacheData?.data;if(isObject(cacheItems))return structuredClone(cacheItems)}const dir=config.local.dir,data={};let hasData=!1;const files=await readdir(resolve(dir));for(const file of files){const fileExt=extname(file),fileName=basename(file,fileExt);if(".json"!==fileExt)continue;const fileContents=await readFile(resolve(dir,file),{encoding:"utf8"})
|
|
1
|
+
import{readdir,readFile}from"node:fs/promises";import{extname,basename,resolve}from"node:path";import{isObject,isObjectStrict}from"../utils/object/object.js";import{isStringSafe,isStringStrict}from"../utils/string/string.js";import{applyFilters}from"../filters/filters.js";import{getJson}from"../utils/json/json.js";import{config}from"../config/config.js";import{normalizeLocalData}from"./localDataNormal.js";const getLocalData=async args=>{if(!isObjectStrict(args))throw new Error("No args");const{key:key,refProps:refProps,imageProps:imageProps,unsetProps:unsetProps}=args;if(!isStringStrict(key))throw new Error("No key");if(config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await applyFilters("cacheData",void 0,cacheDataFilterArgs,!0),cacheItems=cacheData?.data;if(isObject(cacheItems))return structuredClone(cacheItems)}const dir=config.local.dir,data={};let hasData=!1;const files=await readdir(resolve(dir));for(const file of files){const fileExt=extname(file),fileName=basename(file,fileExt);if(".json"!==fileExt||!isStringSafe(fileName))continue;const fileContents=await readFile(resolve(dir,file),{encoding:"utf8"});data[fileName]=getJson(fileContents),hasData=!0}if(!hasData)throw new Error("No data");const newData=normalizeLocalData(data,refProps,imageProps,unsetProps);if(config.env.cache){const cacheDataFilterArgs={key:key,type:"set",data:data};await applyFilters("cacheData",{data:newData},cacheDataFilterArgs,!0)}return newData},getAllLocalData=async args=>{const data=await getLocalData({key:"all_file_data",refProps:args?.refProps,imageProps:args?.imageProps,unsetProps:args?.unsetProps});let allData={navigationItem:[],navigation:[],content:{page:[]}};for(const[,value]of Object.entries(data)){const{contentType:contentType}=value;if(!isStringSafe(contentType))continue;const isPartial=config.partialTypes.includes(contentType),isWhole=config.wholeTypes.includes(contentType);if(!isPartial&&!isWhole)continue;const val=applyFilters("localData",value);isPartial&&(null==allData[contentType]&&(allData[contentType]=[]),allData[contentType].push(val)),isWhole&&(null==allData.content[contentType]&&(allData.content[contentType]=[]),allData.content[contentType].push(val))}return allData=applyFilters("allData",allData,{type:"local"}),allData};export{getLocalData,getAllLocalData};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject,isObjectStrict}from"../utils/object/object.js";import{isArray,isArrayStrict}from"../utils/array/array.js";import{isStringStrict}from"../utils/string/string.js";import{getStoreItem}from"../store/store.js";const normalizeLocalRefs=(data,refData,imageData,refProps=["internalLink","term","taxonomy"],imageProps=["image"],unsetProps=["content"],contentType)=>{const newData=isArray(data)?[]:{},isTemplate="contentTemplate"===data.renderType,isNavigation="navigation"===contentType,isNavigationItem="navigationItem"===contentType;for(const[key,value]of Object.entries(data)){const isRef=refProps.includes(key),isImage=imageProps.includes(key),isStr=isStringStrict(value),isArr=isArrayStrict(value);let newValue=value;isTemplate&&"content"===key&&isArr&&(newValue=value.map(item=>isStringStrict(item)?{...refData[item]}:item)),(isNavigation&&"items"===key||isNavigationItem&&"children"===key)&&isArr&&(newValue=value.map(id=>isStringStrict(id)?{id:id,title:refData[id]?.title}:null).filter(Boolean)),isImage&&isStr&&(newValue=imageData[value]?{...imageData[value]}:null),isRef&&isStr&&(newValue={...refData[value]},unsetProps.forEach(prop=>{newValue[prop]&&(newValue[prop]=void 0)})),isRef&&isArrayStrict(value)&&(newValue=value.map(refKey=>{if(!isStringStrict(refKey))return null;const ref=refData[refKey];if(!isObjectStrict(ref))return null;const newRef={...ref};return unsetProps.forEach(prop=>{newRef[prop]&&(newRef[prop]=void 0)}),newRef}).filter(Boolean)),isObject(newValue)&&(newValue=normalizeLocalRefs(newValue,refData,imageData,refProps,imageProps,unsetProps)),newData[key]=newValue}return newData},normalizeLocalData=(data,refProps,imageProps,unsetProps)=>{const newData={},imageMeta=getStoreItem("imageMeta"),refData={};for(const[key,item]of Object.entries(data))isObjectStrict(item)
|
|
1
|
+
import{isObject,isObjectStrict}from"../utils/object/object.js";import{isArray,isArrayStrict}from"../utils/array/array.js";import{isStringSafe,isStringStrict}from"../utils/string/string.js";import{getStoreItem}from"../store/store.js";const normalizeLocalRefs=(data,refData,imageData,refProps=["internalLink","term","taxonomy"],imageProps=["image"],unsetProps=["content"],contentType)=>{const newData=isArray(data)?[]:{},isTemplate="contentTemplate"===data.renderType,isNavigation="navigation"===contentType,isNavigationItem="navigationItem"===contentType;for(const[key,value]of Object.entries(data)){if(!isStringSafe(key))continue;const isRef=refProps.includes(key),isImage=imageProps.includes(key),isStr=isStringStrict(value),isArr=isArrayStrict(value);let newValue=value;isTemplate&&"content"===key&&isArr&&(newValue=value.map(item=>isStringStrict(item)?{...refData[item]}:item)),(isNavigation&&"items"===key||isNavigationItem&&"children"===key)&&isArr&&(newValue=value.map(id=>isStringStrict(id)?{id:id,title:refData[id]?.title}:null).filter(Boolean)),isImage&&isStr&&(newValue=imageData[value]?{...imageData[value]}:null),isRef&&isStr&&(newValue={...refData[value]},unsetProps.forEach(prop=>{newValue[prop]&&(newValue[prop]=void 0)})),isRef&&isArrayStrict(value)&&(newValue=value.map(refKey=>{if(!isStringStrict(refKey))return null;const ref=refData[refKey];if(!isObjectStrict(ref))return null;const newRef={...ref};return unsetProps.forEach(prop=>{newRef[prop]&&(newRef[prop]=void 0)}),newRef}).filter(Boolean)),isObject(newValue)&&(newValue=normalizeLocalRefs(newValue,refData,imageData,refProps,imageProps,unsetProps)),newData[key]=newValue}return newData},normalizeLocalData=(data,refProps,imageProps,unsetProps)=>{const newData={},imageMeta=getStoreItem("imageMeta"),refData={};for(const[key,item]of Object.entries(data)){if(!isObjectStrict(item)||!isStringSafe(key))continue;const{contentType:contentType}=item;contentType&&!isStringSafe(contentType)||(refData[key]={id:key,...item})}for(const[key,item]of Object.entries(refData))newData[key]=normalizeLocalRefs(item,refData,imageMeta,refProps?.filter(prop=>isStringSafe(prop)),imageProps?.filter(prop=>isStringSafe(prop)),unsetProps?.filter(prop=>isStringSafe(prop)),item.contentType);return newData};export{normalizeLocalData};
|
package/lib/render/render.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { RenderContentArgs, RenderItemArgs, RenderItemReturn, RenderArgs, RenderReturn, RenderFunctions, RenderLayout, RenderHttpError, RenderNavigation, RenderFunctionsArgs } from './renderTypes.js';
|
|
1
|
+
import type { RenderContentArgs, RenderItem, RenderItemArgs, RenderItemReturn, RenderArgs, RenderReturn, RenderFunctions, RenderLayout, RenderHttpError, RenderNavigation, RenderFunctionsArgs, RenderMeta } from './renderTypes.js';
|
|
2
2
|
import type { RefString } from '../global/globalTypes.js';
|
|
3
3
|
declare let renderFunctions: RenderFunctions;
|
|
4
4
|
declare let renderLayout: RenderLayout;
|
|
@@ -6,6 +6,7 @@ declare let renderHttpError: RenderHttpError;
|
|
|
6
6
|
declare let renderNavigation: RenderNavigation;
|
|
7
7
|
declare const setRenderFunctions: (args: RenderFunctionsArgs) => boolean;
|
|
8
8
|
declare const renderContent: (args: RenderContentArgs, _html?: RefString) => Promise<string>;
|
|
9
|
+
declare const renderMeta: (item: RenderItem) => RenderMeta;
|
|
9
10
|
declare const renderItem: (args: RenderItemArgs, _contentType?: string) => Promise<RenderItemReturn | null>;
|
|
10
11
|
declare const render: (args: RenderArgs) => Promise<RenderReturn[] | RenderReturn>;
|
|
11
|
-
export { render, renderItem, renderContent, renderFunctions, renderLayout, renderNavigation, renderHttpError, setRenderFunctions };
|
|
12
|
+
export { render, renderItem, renderMeta, renderContent, renderFunctions, renderLayout, renderNavigation, renderHttpError, setRenderFunctions };
|
package/lib/render/render.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{doActions}from"../actions/actions.js";import{applyFilters}from"../filters/filters.js";import{getSlug,getPermalink}from"../utils/link/link.js";import{isString,isStringStrict}from"../utils/string/string.js";import{isArray,isArrayStrict}from"../utils/array/array.js";import{isObjectStrict}from"../utils/object/object.js";import{isFunction}from"../utils/function/function.js";import{doShortcodes}from"../shortcodes/shortcodes.js";import{tagExists}from"../utils/tag/tag.js";import{setStoreData,setStoreItem,getStoreItem}from"../store/store.js";import{setRedirects}from"../redirects/redirects.js";import{scripts,styles}from"../scripts/scripts.js";import{config}from"../config/config.js";let renderFunctions={},renderLayout=()=>"",renderHttpError=()=>"",renderNavigation=()=>{};const setRenderFunctions=args=>{if(!isObjectStrict(args))return!1;const{functions:functions,layout:layout,navigation:navigation,httpError:httpError}=args;return!(!isObjectStrict(functions)||!isFunction(layout))&&(renderFunctions={...functions},renderLayout=layout,isFunction(navigation)&&(renderNavigation=navigation),isFunction(httpError)&&(renderHttpError=httpError),!0)},getContentTemplate=(content,templates=[],named=!1)=>{if(!isArrayStrict(content))return{content:[],namedContent:{},templates:[]};const namedContent={},newContent=content.map(c=>(named&&isString(c.name)&&(namedContent[c.name]={...c}),tagExists(c,"template")?(templates.push({...c}),{metadata:{tags:[{id:"templateBreak"}]}}):c));return{namedContent:namedContent,content:newContent,templates:structuredClone(templates)}},mapContentTemplate=(templates,content=[],namedContent={},named=!1)=>{if(!isArrayStrict(templates))return templates;const lastTemplateIndex=templates.length-1;return templates.forEach((t,i)=>{content[0]&&tagExists(content[0],"templateBreak")&&content.length>=1&&content.shift();if(tagExists(t,"templateOptional")&&i===lastTemplateIndex&&!content.length)return void templates.pop();const isSlot=tagExists(t,"templateSlot");let children=t.content;if(isArrayStrict(children)&&!isSlot&&!named){let repeat;const newChildren=[...children],repeatIndex=children.findIndex(c=>{const isRepeat=tagExists(c,"templateRepeat");return isRepeat&&(repeat=c),isRepeat});if(-1!==repeatIndex&&repeat){let breakIndex=content.findIndex(c=>tagExists(c,"templateBreak"));breakIndex=-1===breakIndex?content.length:breakIndex;let insertIndex=repeatIndex;for(let j=insertIndex;j<breakIndex-1;j+=1)newChildren.splice(insertIndex,0,structuredClone(repeat)),insertIndex=j}children=newChildren}if(isSlot&&content.length>=1){let fill=null;return fill=named?namedContent[t.name]:content.shift(),void(fill&&(templates[i]=fill))}isArray(children)&&templates[i]&&(templates[i].content=mapContentTemplate(children,content,namedContent,named))}),templates},renderContent=async(args,_html={ref:""})=>{if(!isObjectStrict(args))return _html.ref;const{content:content,serverlessData:serverlessData,previewData:previewData,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,parents:parents,depth:depth=0}=args;let{headingsIndex:headingsIndex=-1}=args;if(!isArrayStrict(content))return _html.ref;for(const item of content){if(!isObjectStrict(item))continue;const props={...item},renderType=isString(props.renderType)?props.renderType:"",isRichText="richText"===renderType;let childrenArr,children=props.content;if("contentTemplate"===renderType){const isNamed=tagExists(item,"templateNamed"),template=getContentTemplate(isArray(props.content)?props.content:[],[],isNamed);children=mapContentTemplate(template.templates,template.content,template.namedContent,isNamed)}let childrenStr="";isArrayStrict(children)&&!isRichText&&(childrenArr=children),isStringStrict(children)&&!isRichText&&(childrenStr=children),"content"===renderType&&0===depth&&(headingsIndex=itemHeadings.push([])-1);let renderStart="",renderEnd="",filterType="",filterArgs={};const renderFunction=renderFunctions[renderType];if(isFunction(renderFunction)){childrenArr&&(props.content=void 0);const renderArgs={args:props,parents:parents,itemData:itemData,itemContains:itemContains,serverlessData:serverlessData,previewData:previewData};childrenArr&&(renderArgs.children=childrenArr),"richText"===renderType&&(renderArgs.headings=itemHeadings[headingsIndex]);const renderOutput=await renderFunction(renderArgs);if(isArrayStrict(renderOutput)){const[start,end]=renderOutput;isString(start)&&(renderStart=start),isString(end)&&(renderEnd=end)}isString(renderOutput)&&(renderStart=renderOutput,childrenArr=void 0),itemContains.add(renderType),filterType=renderType,filterArgs={...props,content:void 0}}const renderContentFilterArgs={renderType:filterType,args:filterArgs},[filterRenderStart,filterRenderEnd]=await applyFilters("renderContent",[renderStart,renderEnd],renderContentFilterArgs,!0);if(renderStart=filterRenderStart,renderEnd=filterRenderEnd,_html.ref+=renderStart+childrenStr,childrenArr){const parentsCopy=[...parents];renderType&&parentsCopy.unshift({renderType:renderType,args:{...props,content:void 0,parents:void 0}}),await renderContent({content:childrenArr,serverlessData:serverlessData,previewData:previewData,parents:parentsCopy,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,headingsIndex:headingsIndex,depth:depth+1},_html)}_html.ref+=renderEnd}return _html.ref},renderItem=async(args,_contentType)=>{if(!isObjectStrict(args))return null;const{item:item,serverlessData:serverlessData,previewData:previewData}=args;if(!isObjectStrict(item))return null;const contentType=item.contentType;if(!isStringStrict(contentType))return null;if("taxonomy"===contentType&&!0!==item.isPage)return null;const id=item.id;if(!isStringStrict(id))return null;if(!isStringStrict(item.slug))return null;let serverlessRender=!1;const itemContains=new Set,itemHeadings=[];scripts.deps.clear(),scripts.item.clear(),scripts.meta={},styles.deps.clear(),styles.item.clear();const renderItemStartArgs={id:id,itemData:{...item},contentType:contentType,itemContains:new Set,itemHeadings:[],serverlessData:serverlessData,previewData:previewData};await doActions("renderItemStart",renderItemStartArgs,!0);const title=item.title,meta={title:"",description:"",url:"",image:"",canonical:"",prev:"",next:"",index:!0,isIndex:!1,...item.meta};isStringStrict(item.metaTitle)&&(meta.title=item.metaTitle),isStringStrict(item.metaDescription)&&(meta.description=item.metaDescription),isStringStrict(item.metaImage?.url)&&(meta.image=item.metaImage.url),!isStringStrict(meta.title)&&isStringStrict(title)&&(meta.title=title);const slugArgs={id:id,contentType:contentType,slug:item.slug,returnParents:!0,itemData:item,page:0},s=getSlug(slugArgs,!0),slug=s.slug,slugIsHtml=slug.endsWith(".html"),permalink=getPermalink(slug,!slugIsHtml),parents=s.parents;meta.url=permalink,meta.canonical=permalink;const taxonomy="term"===contentType?item.taxonomy:"taxonomy"===contentType?item:null;item.baseUrl=permalink,item.baseType=isObjectStrict(taxonomy)&&isArrayStrict(taxonomy.contentTypes)?taxonomy.contentTypes:contentType;let formattedSlug="index"!==slug&&""!==slug?`/${slug}/`:"/";slugIsHtml&&(formattedSlug=slug);const index="index"===item.slug;let itemServerlessData;if(meta.isIndex=index,isObjectStrict(serverlessData)){if(!(serverlessData.path===formattedSlug&&null!=serverlessData.query))return{serverlessRender:!1};itemServerlessData=serverlessData}const itemData={...item};itemData.id=id,itemData.parents=parents,itemData.content=void 0;let contentOutput="";const contentData=item.content;isStringStrict(contentData)&&(contentOutput=contentData),isArrayStrict(contentData)&&(contentOutput=await renderContent({content:contentData,serverlessData:itemServerlessData,parents:[],itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,previewData:previewData})),contentOutput=await doShortcodes(contentOutput,itemData);const pag=itemData.pagination;if(isObjectStrict(pag)){const{currentParams:currentParams,prevParams:prevParams,nextParams:nextParams}=pag,currentParamsStr=new URLSearchParams(currentParams).toString();if(currentParamsStr&&(meta.canonicalParams=`?${currentParamsStr}`),isStringStrict(pag.title)&&(meta.paginationTitle=pag.title),pag.prev){const prevSlugArgs={...slugArgs,params:prevParams},p=getSlug(prevSlugArgs,!0);meta.prev=getPermalink(p.slug,1===pag.prev&&!prevParams)}if(pag.next){const nextSlugArgs={...slugArgs,params:nextParams},n=getSlug(nextSlugArgs,!0);meta.next=getPermalink(n.slug,!1)}serverlessRender=!0}const cmsLocales=config.cms.locales,slugData=[id,isStringStrict(_contentType)?_contentType:contentType];if(isStringStrict(item.locale)&&cmsLocales){const locale=item.locale;cmsLocales.includes(locale)&&locale!==cmsLocales[0]&&slugData.push(locale)}(config.env.dev||config.env.prod&&serverlessRender)&&setStoreItem("slugs",slugData,slugIsHtml?`/${slug}`:formattedSlug);const layoutArgs={id:id,meta:meta,contentType:contentType,content:contentOutput,slug:formattedSlug,itemContains:itemContains,itemHeadings:itemHeadings,itemData:itemData,serverlessData:serverlessData,previewData:previewData};let layoutOutput=await renderLayout(layoutArgs);const renderItemFilterArgs={id:id,contentType:contentType,slug:formattedSlug,output:layoutOutput,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,serverlessData:serverlessData,previewData:previewData};layoutOutput=await applyFilters("renderItem",layoutOutput,renderItemFilterArgs,!0);const renderItemEndArgs={id:id,contentType:contentType,slug:formattedSlug,output:layoutOutput,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,serverlessData:serverlessData,previewData:previewData};return await doActions("renderItemEnd",renderItemEndArgs,!0),{serverlessRender:serverlessRender,itemData:itemData,data:{slug:formattedSlug,output:layoutOutput}}},render=async args=>{if(!isObjectStrict(args))return[];const{allData:allData,serverlessData:serverlessData,previewData:previewData}=args,isServerless=null!=serverlessData,isPreview=null!=previewData;if(scripts.deps.clear(),scripts.item.clear(),scripts.meta={},styles.deps.clear(),styles.item.clear(),!isObjectStrict(allData))return[];const{redirect:redirect,content:content}=allData;await doActions("renderStart",args,!0);const data=[];isServerless||setStoreData(allData),await renderNavigation({navigations:getStoreItem("navigations"),items:getStoreItem("navigationItems")}),setRedirects(redirect);for(const[contentType,contentItems]of Object.entries(content))if(isArrayStrict(contentItems))for(const contentItem of contentItems){const item=await renderItem({item:await applyFilters("renderItemData",contentItem,{contentType:contentType},!0),serverlessData:serverlessData,previewData:previewData},contentType);if(!item)continue;const{serverlessRender:serverlessRender=!1,data:itemData}=item;itemData&&(data.push(itemData),serverlessRender&&!isServerless&&setStoreItem("serverless",["reload"],itemData.slug))}const[outputItem]=data,output=(isServerless||isPreview)&&outputItem?outputItem:data;return await doActions("renderEnd",{...args,data:output},!0),output};export{render,renderItem,renderContent,renderFunctions,renderLayout,renderNavigation,renderHttpError,setRenderFunctions};
|
|
1
|
+
import{doActions}from"../actions/actions.js";import{applyFilters}from"../filters/filters.js";import{getSlug,getPermalink}from"../utils/link/link.js";import{isString,isStringSafe,isStringStrict}from"../utils/string/string.js";import{isArray,isArrayStrict}from"../utils/array/array.js";import{isObjectStrict}from"../utils/object/object.js";import{isFunction}from"../utils/function/function.js";import{doShortcodes}from"../shortcodes/shortcodes.js";import{tagExists}from"../utils/tag/tag.js";import{setStoreData,setStoreItem,getStoreItem}from"../store/store.js";import{setRedirects}from"../redirects/redirects.js";import{scripts,styles}from"../scripts/scripts.js";import{config}from"../config/config.js";let renderFunctions={},renderLayout=()=>"",renderHttpError=()=>"",renderNavigation=()=>{};const setRenderFunctions=args=>{if(!isObjectStrict(args))return!1;const{functions:functions,layout:layout,navigation:navigation,httpError:httpError}=args;return!(!isObjectStrict(functions)||!isFunction(layout))&&(renderFunctions={...functions},renderLayout=layout,isFunction(navigation)&&(renderNavigation=navigation),isFunction(httpError)&&(renderHttpError=httpError),!0)},getContentTemplate=(content,templates=[],named=!1)=>{if(!isArrayStrict(content))return{content:[],namedContent:{},templates:[]};const namedContent={},newContent=content.map(c=>{const{name:name}=c;return named&&isStringSafe(name)&&(namedContent[name]={...c}),tagExists(c,"template")?(templates.push({...c}),{metadata:{tags:[{id:"templateBreak"}]}}):c});return{namedContent:namedContent,content:newContent,templates:structuredClone(templates)}},mapContentTemplate=(templates,content=[],namedContent={},named=!1)=>{if(!isArrayStrict(templates))return templates;const lastTemplateIndex=templates.length-1;return templates.forEach((t,i)=>{content[0]&&tagExists(content[0],"templateBreak")&&content.length>=1&&content.shift();if(tagExists(t,"templateOptional")&&i===lastTemplateIndex&&!content.length)return void templates.pop();const isSlot=tagExists(t,"templateSlot");let children=t.content;if(isArrayStrict(children)&&!isSlot&&!named){let repeat;const newChildren=[...children],repeatIndex=children.findIndex(c=>{const isRepeat=tagExists(c,"templateRepeat");return isRepeat&&(repeat=c),isRepeat});if(-1!==repeatIndex&&repeat){let breakIndex=content.findIndex(c=>tagExists(c,"templateBreak"));breakIndex=-1===breakIndex?content.length:breakIndex;let insertIndex=repeatIndex;for(let j=insertIndex;j<breakIndex-1;j+=1)newChildren.splice(insertIndex,0,structuredClone(repeat)),insertIndex=j}children=newChildren}if(isSlot&&content.length>=1){let fill=null;return fill=named?namedContent[t.name]:content.shift(),void(fill&&(templates[i]=fill))}isArray(children)&&templates[i]&&(templates[i].content=mapContentTemplate(children,content,namedContent,named))}),templates},renderContent=async(args,_html={ref:""})=>{if(!isObjectStrict(args))return _html.ref;const{content:content,serverlessData:serverlessData,previewData:previewData,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,parents:parents,depth:depth=0}=args;let{headingsIndex:headingsIndex=-1}=args;if(!isArrayStrict(content))return _html.ref;for(const item of content){if(!isObjectStrict(item))continue;const props={...item},renderType=isString(props.renderType)?props.renderType:"",isRichText="richText"===renderType;let childrenArr,children=props.content;if("contentTemplate"===renderType){const isNamed=tagExists(item,"templateNamed"),template=getContentTemplate(isArray(props.content)?props.content:[],[],isNamed);children=mapContentTemplate(template.templates,template.content,template.namedContent,isNamed)}let childrenStr="";isArrayStrict(children)&&!isRichText&&(childrenArr=children),isStringStrict(children)&&!isRichText&&(childrenStr=children),"content"===renderType&&0===depth&&(headingsIndex=itemHeadings.push([])-1);let renderStart="",renderEnd="",filterType="",filterArgs={};const renderFunction=renderFunctions[renderType];if(isFunction(renderFunction)){childrenArr&&(props.content=void 0);const renderArgs={args:props,parents:parents,itemData:itemData,itemContains:itemContains,serverlessData:serverlessData,previewData:previewData};childrenArr&&(renderArgs.children=childrenArr),"richText"===renderType&&(renderArgs.headings=itemHeadings[headingsIndex]);const renderOutput=await renderFunction(renderArgs);if(isArrayStrict(renderOutput)){const[start,end]=renderOutput;isString(start)&&(renderStart=start),isString(end)&&(renderEnd=end)}isString(renderOutput)&&(renderStart=renderOutput,childrenArr=void 0),itemContains.add(renderType),filterType=renderType,filterArgs={...props,content:void 0}}const renderContentFilterArgs={renderType:filterType,args:filterArgs},[filterRenderStart,filterRenderEnd]=await applyFilters("renderContent",[renderStart,renderEnd],renderContentFilterArgs,!0);if(renderStart=filterRenderStart,renderEnd=filterRenderEnd,_html.ref+=renderStart+childrenStr,childrenArr){const parentsCopy=[...parents];renderType&&parentsCopy.unshift({renderType:renderType,args:{...props,content:void 0,parents:void 0}}),await renderContent({content:childrenArr,serverlessData:serverlessData,previewData:previewData,parents:parentsCopy,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,headingsIndex:headingsIndex,depth:depth+1},_html)}_html.ref+=renderEnd}return _html.ref},renderMeta=item=>{const{title:title,slug:slug,baseUrl:baseUrl,pagination:pagination}=item,meta={title:title,description:"",url:baseUrl,image:"",canonical:baseUrl,prev:"",next:"",index:!0,isIndex:"index"===slug,...item.meta};if(isStringStrict(item.metaTitle)&&(meta.title=item.metaTitle),isStringStrict(item.metaDescription)&&(meta.description=item.metaDescription),isStringStrict(item.metaImage?.url)&&(meta.image=item.metaImage.url),!isObjectStrict(pagination))return meta;const{title:paginationTitle,prev:paginationPrev,next:paginationNext,currentParams:currentParams,prevParams:prevParams,nextParams:nextParams}=pagination,currentParamsStr=new URLSearchParams(currentParams).toString();if(currentParamsStr&&(meta.canonical=`${baseUrl}?${currentParamsStr}`),isStringStrict(paginationTitle)&&(meta.paginationTitle=paginationTitle),paginationPrev){const prevParamsStr=new URLSearchParams(prevParams).toString();meta.prev=`${baseUrl}${prevParamsStr?`?${prevParamsStr}`:""}`}if(paginationNext){const nextParamsStr=new URLSearchParams(nextParams).toString();meta.next=`${baseUrl}?${nextParamsStr}`}return meta},renderItem=async(args,_contentType)=>{if(!isObjectStrict(args))return null;const{item:item,serverlessData:serverlessData,previewData:previewData}=args;if(!isObjectStrict(item))return null;const contentType=item.contentType;if(!isStringStrict(contentType))return null;if("taxonomy"===contentType&&!0!==item.isPage)return null;const id=item.id;if(!isStringStrict(id))return null;if(!isStringStrict(item.slug))return null;let serverlessRender=!1;const itemContains=new Set,itemHeadings=[];scripts.deps.clear(),scripts.item.clear(),scripts.meta={},styles.deps.clear(),styles.item.clear();const renderItemStartArgs={id:id,itemData:{...item},contentType:contentType,itemContains:new Set,itemHeadings:[],serverlessData:serverlessData,previewData:previewData};await doActions("renderItemStart",renderItemStartArgs,!0);const slugArgs={id:id,contentType:contentType,slug:item.slug,returnParents:!0,itemData:item,page:0},s=getSlug(slugArgs,!0),slug=s.slug,slugIsHtml=slug.endsWith(".html"),permalink=getPermalink(slug,!slugIsHtml),parents=s.parents,taxonomy="term"===contentType?item.taxonomy:"taxonomy"===contentType?item:null;item.baseUrl=permalink,item.baseType=isObjectStrict(taxonomy)&&isArrayStrict(taxonomy.contentTypes)?taxonomy.contentTypes:contentType;let itemServerlessData,formattedSlug="index"!==slug&&""!==slug?`/${slug}/`:"/";if(slugIsHtml&&(formattedSlug=slug),isObjectStrict(serverlessData)){if(!(serverlessData.path===formattedSlug&&null!=serverlessData.query))return{serverlessRender:!1};itemServerlessData=serverlessData}const itemData={...item};itemData.id=id,itemData.parents=parents,itemData.content=void 0;let contentOutput="";const contentData=item.content;isStringStrict(contentData)&&(contentOutput=contentData),isArrayStrict(contentData)&&(contentOutput=await renderContent({content:contentData,serverlessData:itemServerlessData,parents:[],itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,previewData:previewData})),contentOutput=await doShortcodes(contentOutput,itemData),isObjectStrict(itemData.pagination)&&(serverlessRender=!0);const cmsLocales=config.cms.locales,slugData=[id,isStringStrict(_contentType)?_contentType:contentType];if(isStringStrict(item.locale)&&cmsLocales){const locale=item.locale;cmsLocales.includes(locale)&&locale!==cmsLocales[0]&&slugData.push(locale)}(config.env.dev||config.env.prod&&serverlessRender)&&setStoreItem("slugs",slugData,slugIsHtml?`/${slug}`:formattedSlug);const layoutArgs={id:id,meta:renderMeta(itemData),contentType:contentType,content:contentOutput,slug:formattedSlug,itemContains:itemContains,itemHeadings:itemHeadings,itemData:itemData,serverlessData:serverlessData,previewData:previewData};let layoutOutput=await renderLayout(layoutArgs);const renderItemFilterArgs={id:id,contentType:contentType,slug:formattedSlug,output:layoutOutput,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,serverlessData:serverlessData,previewData:previewData};layoutOutput=await applyFilters("renderItem",layoutOutput,renderItemFilterArgs,!0);const renderItemEndArgs={id:id,contentType:contentType,slug:formattedSlug,output:layoutOutput,itemData:itemData,itemContains:itemContains,itemHeadings:itemHeadings,serverlessData:serverlessData,previewData:previewData};return await doActions("renderItemEnd",renderItemEndArgs,!0),{serverlessRender:serverlessRender,itemData:itemData,data:{slug:formattedSlug,output:layoutOutput}}},render=async args=>{if(!isObjectStrict(args))return[];const{allData:allData,serverlessData:serverlessData,previewData:previewData}=args,isServerless=null!=serverlessData,isPreview=null!=previewData;if(scripts.deps.clear(),scripts.item.clear(),scripts.meta={},styles.deps.clear(),styles.item.clear(),!isObjectStrict(allData))return[];const{redirect:redirect,content:content}=allData;await doActions("renderStart",args,!0);const data=[];isServerless||setStoreData(allData),await renderNavigation({navigations:getStoreItem("navigations"),items:getStoreItem("navigationItems")}),setRedirects(redirect);for(const[contentType,contentItems]of Object.entries(content))if(isArrayStrict(contentItems))for(const contentItem of contentItems){const item=await renderItem({item:await applyFilters("renderItemData",contentItem,{contentType:contentType},!0),serverlessData:serverlessData,previewData:previewData},contentType);if(!item)continue;const{serverlessRender:serverlessRender=!1,data:itemData}=item;itemData&&(data.push(itemData),serverlessRender&&!isServerless&&setStoreItem("serverless",["reload"],itemData.slug))}const[outputItem]=data,output=(isServerless||isPreview)&&outputItem?outputItem:data;return await doActions("renderEnd",{...args,data:output},!0),output};export{render,renderItem,renderMeta,renderContent,renderFunctions,renderLayout,renderNavigation,renderHttpError,setRenderFunctions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{config}from"../../config/config.js";import{escape}from"../../utils/escape/escape.js";import{isArray}from"../../utils/array/array.js";import{isString,isStringStrict}from"../../utils/string/string.js";import{isObject,isObjectStrict}from"../../utils/object/object.js";import{getObjectKeys}from"../../utils/object/objectUtils.js";import{applyFilters}from"../../filters/filters.js";import{getPermalink}from"../../utils/link/link.js";import{getStoreItem}from"../../store/store.js";import{minify}from"../../utils/minify/minify.js";import{isFile}from"../../utils/file/file.js";const recurseEmailHtml=(data,html,plain,depth=1)=>{if(!isObject(data))return;const isArr=isArray(data);getObjectKeys(data).forEach(label=>{const value=data[label],l=label.toString(),h=depth+1;1===depth&&(html.ref+='\n <tr>\n <td style="padding: 16px 0; border-bottom: 2px solid #ccc;">\n '),label&&!isArr&&(html.ref+=`\n <h${h} style="font-family: sans-serif; color: #222; margin: 16px 0; line-height: 1.3em">\n ${l}\n </h${h}>\n `,plain.ref+=`${l}\n`),recurseEmailHtml(value,html,plain,depth+1),isString(value)&&(html.ref+=`\n <p style="font-family: sans-serif; color: #222; margin: 16px 0; line-height: 1.5em;">\n ${value}\n </p>\n `,plain.ref+=value.replace(/<br\s*\/?>/gi,"\n").replace(/(<([^>]+)>)/gi,"")+"\n"),1===depth&&(html.ref+="\n </td>\n </tr>\n ",plain.ref+="\n")})},Contact=async args=>{const{id:id,action:action,inputs:inputs}=args;if(!isStringStrict(id))return{error:{message:"No ID"}};if(!isObjectStrict(inputs)||!Object.keys(inputs).length)return{error:{message:"No inputs"}};const formMetaData=getStoreItem("formMeta");if(!isObjectStrict(formMetaData))return{error:{message:"No meta"}};const meta=formMetaData[id];if(!isObjectStrict(meta))return{error:{message:"No meta object"}};const toEmail=meta.toEmail;if(!isStringStrict(toEmail))return{error:{message:"No to email"}};const toEmails=toEmail.split(","),senderEmail=meta.senderEmail;if(!isStringStrict(senderEmail))return{error:{message:"No sender email"}};let subject=isStringStrict(meta.subject)?meta.subject:"",replyToEmail="";const header=`${config.title} contact form submission`,footer=`This email was sent from a contact form on ${config.title} (${getPermalink()})`,outputData={},html={ref:""},plain={ref:""};for(const[name,input]of Object.entries(inputs)){const inputType=input.type,inputLabel=input.label?.trim()||`[${name}]
|
|
1
|
+
import{config}from"../../config/config.js";import{escape}from"../../utils/escape/escape.js";import{isArray}from"../../utils/array/array.js";import{isString,isStringSafe,isStringStrict}from"../../utils/string/string.js";import{isObject,isObjectStrict}from"../../utils/object/object.js";import{getObjectKeys}from"../../utils/object/objectUtils.js";import{applyFilters}from"../../filters/filters.js";import{getPermalink}from"../../utils/link/link.js";import{getStoreItem}from"../../store/store.js";import{minify}from"../../utils/minify/minify.js";import{isFile}from"../../utils/file/file.js";const recurseEmailHtml=(data,html,plain,depth=1)=>{if(!isObject(data))return;const isArr=isArray(data);getObjectKeys(data).forEach(label=>{const value=data[label],l=label.toString(),h=depth+1;1===depth&&(html.ref+='\n <tr>\n <td style="padding: 16px 0; border-bottom: 2px solid #ccc;">\n '),label&&!isArr&&(html.ref+=`\n <h${h} style="font-family: sans-serif; color: #222; margin: 16px 0; line-height: 1.3em">\n ${l}\n </h${h}>\n `,plain.ref+=`${l}\n`),recurseEmailHtml(value,html,plain,depth+1),isString(value)&&(html.ref+=`\n <p style="font-family: sans-serif; color: #222; margin: 16px 0; line-height: 1.5em;">\n ${value}\n </p>\n `,plain.ref+=value.replace(/<br\s*\/?>/gi,"\n").replace(/(<([^>]+)>)/gi,"")+"\n"),1===depth&&(html.ref+="\n </td>\n </tr>\n ",plain.ref+="\n")})},Contact=async args=>{const{id:id,action:action,inputs:inputs}=args;if(!isStringStrict(id))return{error:{message:"No ID"}};if(!isObjectStrict(inputs)||!Object.keys(inputs).length)return{error:{message:"No inputs"}};const formMetaData=getStoreItem("formMeta");if(!isObjectStrict(formMetaData))return{error:{message:"No meta"}};const meta=formMetaData[id];if(!isObjectStrict(meta))return{error:{message:"No meta object"}};const toEmail=meta.toEmail;if(!isStringStrict(toEmail))return{error:{message:"No to email"}};const toEmails=toEmail.split(","),senderEmail=meta.senderEmail;if(!isStringStrict(senderEmail))return{error:{message:"No sender email"}};let subject=isStringStrict(meta.subject)?meta.subject:"",replyToEmail="";const header=`${config.title} contact form submission`,footer=`This email was sent from a contact form on ${config.title} (${getPermalink()})`,outputData={},html={ref:""},plain={ref:""};for(const[name,input]of Object.entries(inputs)){const inputType=input.type,inputLabel=escape(input.label?.trim()||`[${name}]`),inputValue=input.value;if(!isStringSafe(inputLabel))continue;let inputValueStr="";if(inputValueStr=isArray(inputValue)?inputValue.map(v=>isFile(v)?escape(v.name):escape(v.toString().trim())).join("<br>"):isFile(inputValue)?escape(inputValue.name):escape(inputValue.toString().trim()),"subject"===name){subject=inputValueStr?`${isStringStrict(subject)?`${subject} - `:""}${inputValueStr}`:subject;continue}"email"===inputType&&inputValueStr&&(replyToEmail=inputValueStr,inputValueStr=`<a href="mailto:${inputValueStr}">${inputValueStr}</a>`);const outputValue=""===inputValueStr?"--":inputValueStr;let hasLegend=!1,legend="";if(isStringSafe(input.legend)&&(legend=escape(input.legend),hasLegend=!0),hasLegend){null==outputData[legend]&&(outputData[legend]={});null==outputData[legend][inputLabel]&&(outputData[legend][inputLabel]=[]),outputData[legend][inputLabel].push(outputValue)}if(!hasLegend){null==outputData[inputLabel]&&(outputData[inputLabel]=[]),outputData[inputLabel].push(outputValue)}}recurseEmailHtml(outputData,html,plain);const outputHtml=`\n <table width="100%" cellpadding="0" cellspacing="0" border="0">\n <tr>\n <td align="center" width="100%" style="padding: 0 16px 16px 16px;">\n <table align="center" cellpadding="0" cellspacing="0" border="0" style="margin-right: auto; margin-left: auto; border-spacing: 0; max-width: 37.5em;">\n <tr>\n <td style="padding: 32px 0 0 0;">\n <h1 style="font-family: sans-serif; color: #222; margin: 0; line-height: 1.3em;">\n ${header}\n </h1>\n </td>\n </tr>\n <tr>\n <td>\n <table border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;">\n ${html.ref}\n <tr>\n <td style="padding: 32px 0;">\n <p style="font-family: sans-serif; color: #222; margin: 0; line-height: 1.5em;">\n ${footer}\n </p>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n `,outputPlain=`${header}\n\n${plain.ref}${footer}`;subject||(subject=`${config.title} Contact Form`);const body={id:id,action:action,inputs:inputs,to:toEmails,sender:senderEmail,subject:subject,text:minify(outputPlain),html:minify(outputHtml)};return replyToEmail&&(body.replyTo=replyToEmail),await applyFilters("contactResult",{},body,!0)};export{Contact};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ResponseError}from"../utils/ResponseError/ResponseError.js";import{isStringStrict}from"../utils/string/string.js";import{isObjectStrict}from"../utils/object/object.js";import{isFunction}from"../utils/function/function.js";import{applyFilters}from"../filters/filters.js";import{render,renderHttpError}from"../render/render.js";import{minify}from"../utils/minify/minify.js";import{print}from"../utils/print/print.js";let serverlessActions={};const serverlessPreview=request=>{const{url:url}=request,{searchParams:searchParams}=new URL(url),contentType=searchParams.get("content_type"),locale=searchParams.get("locale"),id=searchParams.get("preview");if(!isStringStrict(id)||!isStringStrict(contentType))return;const previewData={id:id,contentType:contentType};return isStringStrict(locale)&&(previewData.locale=locale),previewData},serverlessReload=(request,allowedParams=["page","filters"])=>{const{url:url}=request,{searchParams:searchParams,pathname:pathname}=new URL(url),path=pathname,query={};let hasParams=!1;for(const param of allowedParams){const value=searchParams.get(param);isStringStrict(value)&&(query[param]=value,hasParams=!0)}if(hasParams)return{query:query,path:path}},serverlessRender=async(getData,serverlessData,previewData)=>{try{const data=await render({serverlessData:serverlessData,previewData:previewData,allData:await getData({serverlessData:serverlessData,previewData:previewData})});let html="",status=200;isObjectStrict(data)&&(html=data.output);const isEmpty=""===html;return isEmpty&&(status=404),isEmpty&&isFunction(renderHttpError)&&(html=await renderHttpError({code:status})),new Response(minify(html),{status:status,headers:{"Content-Type":"text/html;charset=UTF-8"}})}catch(error){print("[FRM] Error on serverless render",error);const status=500,html=await renderHttpError({code:status});return new Response(html,{status:status,headers:{"Content-Type":"text/html;charset=UTF-8"}})}},setServerless=actions=>{isObjectStrict(actions)&&(serverlessActions={...actions})},doServerlessAction=async(request,env,headers,honeypotName)=>{const serverlessHeaders={"Content-Type":"application/json",...headers};try{if("POST"!==request.method)return new Response(JSON.stringify({error:"Method not allowed"}),{status:405,headers:serverlessHeaders});const data=await request.json();if(!isObjectStrict(data))throw new Error("Data not an object");if(isStringStrict(honeypotName)&&isObjectStrict(data.inputs?.[honeypotName])){const honeypotValue=data.inputs[honeypotName].value;if(isStringStrict(honeypotValue))return new Response(JSON.stringify({success:""}),{status:200,headers:serverlessHeaders});delete data.inputs[honeypotName]}const action=data.action;if(!isStringStrict(action))throw new Error("No action");let res=null;const serverlessAction=serverlessActions[action];isFunction(serverlessAction)&&(res=await serverlessAction(data,request,env));const serverlessResultFilterArgs={data:data,request:request,env:env};if(res=await applyFilters("serverlessResult",res,serverlessResultFilterArgs,!0),!res)throw new Error("No result");if(res.error){const errorMessage=res.error.message;throw res.error.response?new ResponseError(errorMessage,res.error.response):new Error(errorMessage)}const options={status:200,headers:serverlessHeaders};let message="";if(res.success){const{message:successMessage,headers:successHeaders}=res.success;isStringStrict(successMessage)&&(message=successMessage),isObjectStrict(successHeaders)&&(options.headers={...options.headers,...successHeaders})}return new Response(JSON.stringify({success:message}),options)}catch(error){print("[FRM] Error with serverless action",error);let statusCode=500,message=error instanceof Error?error.message:"Unknown error";return error instanceof ResponseError&&(statusCode=error.response.status,message=error.message),new Response(JSON.stringify({error:message}),{status:statusCode,headers:serverlessHeaders})}};export{serverlessActions,serverlessPreview,serverlessReload,serverlessRender,setServerless,doServerlessAction};
|
|
1
|
+
import{ResponseError}from"../utils/ResponseError/ResponseError.js";import{isStringSafe,isStringStrict}from"../utils/string/string.js";import{isObjectStrict}from"../utils/object/object.js";import{isFunction}from"../utils/function/function.js";import{applyFilters}from"../filters/filters.js";import{render,renderHttpError}from"../render/render.js";import{minify}from"../utils/minify/minify.js";import{print}from"../utils/print/print.js";let serverlessActions={};const serverlessPreview=request=>{const{url:url}=request,{searchParams:searchParams}=new URL(url),contentType=searchParams.get("content_type"),locale=searchParams.get("locale"),id=searchParams.get("preview");if(!isStringStrict(id)||!isStringStrict(contentType))return;const previewData={id:id,contentType:contentType};return isStringStrict(locale)&&(previewData.locale=locale),previewData},serverlessReload=(request,allowedParams=["page","filters"])=>{const{url:url}=request,{searchParams:searchParams,pathname:pathname}=new URL(url),path=pathname,query={};let hasParams=!1;for(const param of allowedParams){const value=searchParams.get(param);isStringSafe(param)&&isStringStrict(value)&&(query[param]=value,hasParams=!0)}if(hasParams)return{query:query,path:path}},serverlessRender=async(getData,serverlessData,previewData)=>{try{const data=await render({serverlessData:serverlessData,previewData:previewData,allData:await getData({serverlessData:serverlessData,previewData:previewData})});let html="",status=200;isObjectStrict(data)&&(html=data.output);const isEmpty=""===html;return isEmpty&&(status=404),isEmpty&&isFunction(renderHttpError)&&(html=await renderHttpError({code:status})),new Response(minify(html),{status:status,headers:{"Content-Type":"text/html;charset=UTF-8"}})}catch(error){print("[FRM] Error on serverless render",error);const status=500,html=await renderHttpError({code:status});return new Response(html,{status:status,headers:{"Content-Type":"text/html;charset=UTF-8"}})}},setServerless=actions=>{isObjectStrict(actions)&&(serverlessActions={...actions})},doServerlessAction=async(request,env,headers,honeypotName)=>{const serverlessHeaders={"Content-Type":"application/json",...headers};try{if("POST"!==request.method)return new Response(JSON.stringify({error:"Method not allowed"}),{status:405,headers:serverlessHeaders});const data=await request.json();if(!isObjectStrict(data))throw new Error("Data not an object");if(isStringStrict(honeypotName)&&isObjectStrict(data.inputs?.[honeypotName])){const honeypotValue=data.inputs[honeypotName].value;if(isStringStrict(honeypotValue))return new Response(JSON.stringify({success:""}),{status:200,headers:serverlessHeaders});delete data.inputs[honeypotName]}const action=data.action;if(!isStringStrict(action))throw new Error("No action");let res=null;const serverlessAction=serverlessActions[action];isFunction(serverlessAction)&&(res=await serverlessAction(data,request,env));const serverlessResultFilterArgs={data:data,request:request,env:env};if(res=await applyFilters("serverlessResult",res,serverlessResultFilterArgs,!0),!res)throw new Error("No result");if(res.error){const errorMessage=res.error.message;throw res.error.response?new ResponseError(errorMessage,res.error.response):new Error(errorMessage)}const options={status:200,headers:serverlessHeaders};let message="";if(res.success){const{message:successMessage,headers:successHeaders}=res.success;isStringStrict(successMessage)&&(message=successMessage),isObjectStrict(successHeaders)&&(options.headers={...options.headers,...successHeaders})}return new Response(JSON.stringify({success:message}),options)}catch(error){print("[FRM] Error with serverless action",error);let statusCode=500,message=error instanceof Error?error.message:"Unknown error";return error instanceof ResponseError&&(statusCode=error.response.status,message=error.message),new Response(JSON.stringify({error:message}),{status:statusCode,headers:serverlessHeaders})}};export{serverlessActions,serverlessPreview,serverlessReload,serverlessRender,setServerless,doServerlessAction};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObjectStrict}from"../utils/object/object.js";import{isArrayStrict}from"../utils/array/array.js";import{isStringStrict}from"../utils/string/string.js";import{isFunction}from"../utils/function/function.js";import{escape}from"../utils/escape/escape.js";const shortcodes=new Map,attrReg=/[\w-]+=".*?"/g,getShortcodeData=(content,tagNames,props,itemData)=>{if(!isStringStrict(content)||!isStringStrict(tagNames))return[];const reg=new RegExp(String.raw`\[(?:\/)?(?<name>${tagNames})(?:\s[^\]]*?)?\]`,"g"),matches=[...content.matchAll(reg)];if(!matches.length)return[];const data=[];return matches.forEach((opening,i)=>{const name=opening.groups?.name,tag=opening[0];if(!isStringStrict(name)||tag.startsWith("[/"))return;const info=props||shortcodes.get(name);if(!isObjectStrict(info))return;const child=info.child,hasChild=isStringStrict(child),startIndex=opening.index,
|
|
1
|
+
import{isObjectStrict}from"../utils/object/object.js";import{isArrayStrict}from"../utils/array/array.js";import{isStringSafe,isStringStrict}from"../utils/string/string.js";import{isFunction}from"../utils/function/function.js";import{escape}from"../utils/escape/escape.js";const shortcodes=new Map,attrReg=/[\w-]+=".*?"/g,getShortcodeData=(content,tagNames,props,itemData)=>{if(!isStringStrict(content)||!isStringStrict(tagNames))return[];const reg=new RegExp(String.raw`\[(?:\/)?(?<name>${tagNames})(?:\s[^\]]*?)?\]`,"g"),matches=[...content.matchAll(reg)];if(!matches.length)return[];const data=[];return matches.forEach((opening,i)=>{const name=opening.groups?.name,tag=opening[0];if(!isStringStrict(name)||tag.startsWith("[/"))return;const info=props||shortcodes.get(name);if(!isObjectStrict(info))return;const child=info.child,hasChild=isStringStrict(child),startIndex=opening.index,startCount=tag.length;let endIndex=startIndex+tag.length,endCount=0;const closingTag=`[/${name}]`,closingMatch=hasChild?matches.find(m=>m[0]===closingTag):matches[i+1];closingMatch?.[0]===closingTag&&(endIndex=closingMatch.index,endCount=closingTag.length);const attrs={},attrTypes=isObjectStrict(info.attrTypes)?info.attrTypes:{},attr=tag.match(attrReg);isArrayStrict(attr)&&attr.forEach(a=>{const[key,value]=a.split("=");if(!isStringSafe(key))return;const type=attrTypes[key];let val=escape(value.replace(/"/g,""));if("number"===type){const num=parseInt(val,10);val=isNaN(num)?0:num}"boolean"===type&&(val="true"===val),attrs[key]=val});const replaceContent=content.slice(startIndex,endIndex+endCount),innerContent=content.slice(startIndex+startCount,endIndex);let children=[];hasChild&&(children=getShortcodeData(innerContent,child,props,itemData)),data.push({name:name,replaceContent:replaceContent,content:innerContent,attr:attrs,children:children,itemData:itemData})}),data},addShortcode=(name,shortcode)=>!(!isStringStrict(name)||!isObjectStrict(shortcode))&&(shortcodes.set(name,shortcode),!0),removeShortcode=name=>!!isStringStrict(name)&&shortcodes.delete(name),doShortcodes=async(content,itemData)=>{if(!shortcodes.size)return content;const names=[...shortcodes.keys()].join("|"),data=getShortcodeData(content,names,void 0,itemData);if(!data.length)return content;let newContent=content;for(const datum of data){const{name:name,replaceContent:replaceContent}=datum,callback=shortcodes.get(name)?.callback;isFunction(callback)&&(newContent=newContent.replace(replaceContent,await callback({...datum,itemData:itemData})))}return newContent},resetShortcodes=()=>{shortcodes.clear()},setShortcodes=args=>{if(!isObjectStrict(args))return!1;const names=Object.entries(args);return!!names.length&&(resetShortcodes(),names.forEach(([name,shortcode])=>{addShortcode(name,shortcode)}),!0)},stripShortcodes=content=>{if(!shortcodes.size)return content;const names=[...shortcodes.keys()].join("|"),reg=new RegExp(String.raw`\[(?:\/)?(?<name>${names})(?:\s[^\]]*?)?\]`,"g");return content.replace(reg,()=>"")};export{shortcodes,addShortcode,removeShortcode,doShortcodes,resetShortcodes,setShortcodes,stripShortcodes};
|
package/lib/store/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{normalizeContentType}from"../utils/contentType/contentType.js";import{isObject,isObjectStrict}from"../utils/object/object.js";import{isStringStrict}from"../utils/string/string.js";import{isArrayStrict}from"../utils/array/array.js";import{
|
|
1
|
+
import{normalizeContentType}from"../utils/contentType/contentType.js";import{isObject,isObjectStrict}from"../utils/object/object.js";import{isStringStrict,isStringSafe}from"../utils/string/string.js";import{isArrayStrict}from"../utils/array/array.js";import{getArchiveMeta}from"../utils/archive/archive.js";import{config}from"../config/config.js";let storeDir="lib/store";const defaultStore={slugs:{},parents:{},navigations:[],navigationItems:[],formMeta:{},archiveMeta:{},imageMeta:{},taxonomies:{},serverless:{}};let store={...defaultStore};const setStore=(args,dir="lib/store")=>isObjectStrict(args)?(store={...defaultStore,...args},isStringStrict(dir)&&(storeDir=dir),store):store,setStoreItem=(prop,value,subProp)=>!(!isStringSafe(prop)||!isObject(value)||null==store[prop])&&(isStringSafe(subProp)?store[prop][subProp]=value:store[prop]=value,!0),setStoreData=allData=>{if(!isObjectStrict(allData))return!1;const{navigation:navigation,navigationItem:navigationItem,content:content}=allData;store.navigations=isArrayStrict(navigation)?navigation:[],store.navigationItems=isArrayStrict(navigationItem)?navigationItem:[];const data={...allData,...content};return config.hierarchicalTypes.forEach(type=>{if(!isStringSafe(type))return;const items=data[type];isArrayStrict(items)&&items.forEach(item=>{if(!isObjectStrict(item))return;const{id:id,parent:parent,archive:archive,slug:slug,title:title,locale:locale}=item;if(!isStringSafe(id))return;const archiveType=normalizeContentType(archive);if(isStringSafe(archiveType)){const hasLocale=isStringSafe(locale),archiveMeta=getArchiveMeta(archiveType),newArchive={id:id,slug:slug,title:title,contentType:type,...hasLocale?archiveMeta[locale]:archiveMeta};hasLocale?(store.archiveMeta[archiveType]||(store.archiveMeta[archiveType]={}),store.archiveMeta[archiveType][locale]=newArchive):store.archiveMeta[archiveType]=newArchive}if(isObjectStrict(parent)){const parentSlug=parent.slug,parentTitle=parent.title,parentId=parent.id;isStringStrict(parentSlug)&&isStringStrict(parentTitle)&&isStringSafe(parentId)&&(null==store.parents[type]&&(store.parents[type]={}),store.parents[type][id]=[parentId,parentSlug,parentTitle])}})}),!0},getStoreItem=prop=>store[prop];export{store,storeDir,setStore,setStoreData,setStoreItem,getStoreItem};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isString}from"../string/string.js";const escape=value=>{if(!isString(value))throw new TypeError("Value
|
|
1
|
+
import{isString}from"../string/string.js";const escape=value=>{if(!isString(value))throw new TypeError("Value not a string");return value.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/\//g,"/").replace(/\\/g,"\").replace(/`/g,"`")};export{escape};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject,isObjectStrict}from"../object/object.js";import{isStringStrict}from"../string/string.js";import{stripShortcodes}from"../../shortcodes/shortcodes.js";const getContentWords=args=>{const{content:content,prop:prop,limit:limit=25}=args;let{_words:_words=[]}=args;const max=limit+1,
|
|
1
|
+
import{isObject,isObjectStrict}from"../object/object.js";import{isStringStrict}from"../string/string.js";import{stripShortcodes}from"../../shortcodes/shortcodes.js";const getContentWords=args=>{const{content:content,prop:prop,limit:limit=25}=args;let{_words:_words=[]}=args;const max=limit+1,wordsCount=_words.length;if(isObject(content)&&wordsCount<max){const addMax=max-wordsCount;for(const[key,value]of Object.entries(content)){if(key===prop&&isStringStrict(value)){const val=stripShortcodes(value);if(isStringStrict(val)){let valArr=val.split(" ");valArr.length>addMax&&(valArr=valArr.slice(0,addMax)),_words=_words.concat(valArr)}}isObject(value)&&(_words=getContentWords({content:value,prop:prop,limit:limit,_words:_words}))}}return _words},getExcerpt=args=>{const{excerpt:excerpt,content:content,prop:prop="content",limit:limit=25,limitExcerpt:limitExcerpt=!1,more:more="…"}=isObjectStrict(args)?args:{};let output="";if(isStringStrict(excerpt)){if(output=excerpt,limitExcerpt){let excerptArr=excerpt.split(" ");excerptArr.length>limit&&(excerptArr=excerptArr.slice(0,limit),output=`${excerptArr.join(" ")}${more}`)}}else{const words=getContentWords({content:content,prop:prop,limit:limit}),wordsCount=words.length;wordsCount>0&&(wordsCount>limit&&more&&words.pop(),output=`${words.join(" ")}${wordsCount>limit?more:""}`)}return output};export{getExcerpt};
|
package/lib/utils/image/image.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{config}from"../../config/config.js";import{isString,isStringStrict}from"../string/string.js";import{isArrayStrict}from"../array/array.js";import{isNumber}from"../number/number.js";import{isObjectStrict}from"../object/object.js";import{dataSource}from"../dataSource/dataSource.js";const getImageUrl=(url,format,quality,width,height,params)=>{const urlObj=new URL(url);return Object.entries(params).forEach(([key,value])=>{let val=value;"%format"===val&&(val=format),"%quality"===val&&(val=`${quality}`),"%width"===val&&(val=`${width}`),"%height"===val&&(val=`${height}`),urlObj.searchParams.set(key,val)}),urlObj.toString()},getImage=(args,returnDetails=!1)=>{const{data:data,classes:classes,attr:attr,alt:imageAlt="inherit",width:width="auto",height:height="auto",lazy:lazy=!0,picture:picture=!1,quality:quality=75,source:source=config.source,maxWidth:maxWidth=1200,viewportWidth:viewportWidth=100,sizes:sizes,format:format="webp",params:params={fm:"%format",q:"%quality",w:"%width",h:"%height"}}=isObjectStrict(args)?args:{},fallback=returnDetails?{output:"",aspectRatio:0,naturalWidth:0,naturalHeight:0,src:"",srcFallback:"",srcset:[],sizes:""}:"";if(!isObjectStrict(data))return fallback;const{path:path="",alt:dataAlt="",width:naturalWidth=1,height:naturalHeight=1,format:naturalFormat="jpg",sizes:dataSizes}=data;let{url:url=config.image.remoteUrl}=data,alt="inherit"===imageAlt?dataAlt:imageAlt;isStringStrict(alt)||(alt="");const isLocal="local"===source,isRemote=dataSource.isContentful(source)||"remote"===source,isWordpress=dataSource.isWordPress(source);if(isLocal){if(!isStringStrict(path))return fallback;url=`${config.image.localUrl}/${path}`}const aspectRatio=naturalHeight/naturalWidth,aspectRatioReverse=naturalWidth/naturalHeight;let w=naturalWidth,h=naturalHeight;if(isNumber(width)&&(w=width,h=isString(height)?w*aspectRatio:height),isNumber(height)&&(h=height,w=isString(width)?h*aspectRatioReverse:width),w>maxWidth&&(w=Math.round(maxWidth),h=Math.round(w*aspectRatio)),isWordpress&&dataSizes&&!dataSizes[w]){const isNatural=w===naturalWidth;isNatural||(w=getImageClosestSize(w,Object.keys(dataSizes).map(s=>parseInt(s,10))),h=Math.round(w*aspectRatio)),isNatural&&(dataSizes[w]=url)}let src=url,srcFallback=url;isLocal&&(src=`${url}.${format}`,srcFallback=`${url}.${naturalFormat}`),isRemote&&(src=getImageUrl(url,format,quality,w,h,params),srcFallback=getImageUrl(url,naturalFormat,quality,w,h,params));const sizesValue=sizes||`(min-width: ${w/16}rem) ${w/16}rem, ${viewportWidth}vw`,srcsetFallback=[];let srcset=[...config.image.sizes];srcset.includes(w)||srcset.push(w),srcset=srcset.filter(s=>s<=w),srcset.sort((a,b)=>a-b);const srcsetSource=[];srcset.forEach(s=>{if(isLocal){const base=`${url}${s!==naturalWidth?`@${s}`:""}`;srcsetFallback.push(`${base}.${naturalFormat} ${s}w`),srcsetSource.push(`${base}.${format} ${s}w`)}if(isRemote){const sizeHeight=Math.round(s*aspectRatio);srcsetFallback.push(getImageUrl(url,naturalFormat,quality,s,sizeHeight,params)+` ${s}w`),srcsetSource.push(getImageUrl(url,format,quality,s,sizeHeight,params)+` ${s}w`)}if(isWordpress){const sizeUrl=dataSizes?.[s];isStringStrict(sizeUrl)&&srcsetSource.push(`${sizeUrl} ${s}w`)}});let sourceOutput="";picture&&(sourceOutput=`<source srcset="${srcsetSource.join(", ")}" sizes="${sizesValue}" type="image/${format}">`);let eagerHackOutput="";lazy||(eagerHackOutput=`\n <img\n alt=""\n role="presentation"\n aria-hidden="true"\n src="data:image/svg+xml;charset=utf-8,%3Csvg height='${h}' width='${w}' xmlns='http://www.w3.org/2000/svg' version='1.1'%3E%3C/svg%3E" style="pointerEvents: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%"\n >\n `);const output=`\n ${eagerHackOutput}\n ${sourceOutput}\n <img\n ${isStringStrict(classes)?` class="${classes}"`:""}\n alt="${alt}"\n src="${picture?srcFallback:src}"\n srcset="${picture?srcsetFallback.join(", "):srcsetSource.join(", ")}"\n sizes="${sizesValue}"\n width="${w}"\n height="${h}"\n ${isStringStrict(attr)?` ${attr}`:""}\n ${lazy?' loading="lazy" decoding="async"':' loading="eager" fetchpriority="high"'}\n >\n `;return returnDetails?{output:output,aspectRatio:aspectRatio,naturalWidth:naturalWidth,naturalHeight:naturalHeight,src:src,srcFallback:srcFallback,srcset:srcsetSource,sizes:sizesValue}:output},getImageClosestSize=(size,sizes=[])=>(sizes.length||(sizes=config.image.sizes),[...sizes].reduce((prev,curr)=>Math.abs(curr-size)<=Math.abs(prev-size)?curr:prev)),getImageSizes=args=>{const fallback={maxWidth:0,sizes:""};if(!isObjectStrict(args))return fallback;const{parents:parents,widths:widths,maxWidths:maxWidths,breakpoints:breakpoints,source:source=config.source,viewportWidth:viewportWidth=100,maxWidth:max}=args;if(!(isArrayStrict(parents)&&isObjectStrict(widths)&&isObjectStrict(maxWidths)&&isArrayStrict(breakpoints)))return fallback;let containerWidth=0;const columnWidths=[];let col=1,colSmall=1,colMedium=1,colLarge=1;parents.forEach(parent=>{if(!isObjectStrict(parent))return;const{renderType:renderType,args:args}=parent;if(isObjectStrict(args)){if("column"===renderType){const{width:width="Default",widthSmall:widthSmall="Default",widthMedium:widthMedium="Default",widthLarge:widthLarge="Default"}=args,base=isNumber(widths[width])&&widths[width]?widths[width]:1,baseSmall=isNumber(widths[widthSmall])&&widths[widthSmall]?widths[widthSmall]:base,baseMedium=isNumber(widths[widthMedium])&&widths[widthMedium]?widths[widthMedium]:baseSmall,baseLarge=isNumber(widths[widthLarge])&&widths[widthLarge]?widths[widthLarge]:baseMedium;col*=base,colSmall*=baseSmall,colMedium*=baseMedium,colLarge*=baseLarge,columnWidths[0]=col,columnWidths[1]=colSmall,columnWidths[2]=colMedium,columnWidths[3]=colLarge}if("container"===renderType){const{maxWidth:maxWidth="Default"}=args;isNumber(maxWidths[maxWidth])&&(containerWidth=maxWidths[maxWidth])}}});const
|
|
1
|
+
import{config}from"../../config/config.js";import{isString,isStringStrict}from"../string/string.js";import{isArrayStrict}from"../array/array.js";import{isNumber}from"../number/number.js";import{isObjectStrict}from"../object/object.js";import{dataSource}from"../dataSource/dataSource.js";const getImageUrl=(url,format,quality,width,height,params)=>{const urlObj=new URL(url);return Object.entries(params).forEach(([key,value])=>{let val=value;"%format"===val&&(val=format),"%quality"===val&&(val=`${quality}`),"%width"===val&&(val=`${width}`),"%height"===val&&(val=`${height}`),urlObj.searchParams.set(key,val)}),urlObj.toString()},getImage=(args,returnDetails=!1)=>{const{data:data,classes:classes,attr:attr,alt:imageAlt="inherit",width:width="auto",height:height="auto",lazy:lazy=!0,picture:picture=!1,quality:quality=75,source:source=config.source,maxWidth:maxWidth=1200,viewportWidth:viewportWidth=100,sizes:sizes,format:format="webp",params:params={fm:"%format",q:"%quality",w:"%width",h:"%height"}}=isObjectStrict(args)?args:{},fallback=returnDetails?{output:"",aspectRatio:0,naturalWidth:0,naturalHeight:0,src:"",srcFallback:"",srcset:[],sizes:""}:"";if(!isObjectStrict(data))return fallback;const{path:path="",alt:dataAlt="",width:naturalWidth=1,height:naturalHeight=1,format:naturalFormat="jpg",sizes:dataSizes}=data;let{url:url=config.image.remoteUrl}=data,alt="inherit"===imageAlt?dataAlt:imageAlt;isStringStrict(alt)||(alt="");const isLocal="local"===source,isRemote=dataSource.isContentful(source)||"remote"===source,isWordpress=dataSource.isWordPress(source);if(isLocal){if(!isStringStrict(path))return fallback;url=`${config.image.localUrl}/${path}`}const aspectRatio=naturalHeight/naturalWidth,aspectRatioReverse=naturalWidth/naturalHeight;let w=naturalWidth,h=naturalHeight;if(isNumber(width)&&(w=width,h=isString(height)?w*aspectRatio:height),isNumber(height)&&(h=height,w=isString(width)?h*aspectRatioReverse:width),w>maxWidth&&(w=Math.round(maxWidth),h=Math.round(w*aspectRatio)),isWordpress&&dataSizes&&!dataSizes[w]){const isNatural=w===naturalWidth;isNatural||(w=getImageClosestSize(w,Object.keys(dataSizes).map(s=>parseInt(s,10))),h=Math.round(w*aspectRatio)),isNatural&&(dataSizes[w]=url)}let src=url,srcFallback=url;isLocal&&(src=`${url}.${format}`,srcFallback=`${url}.${naturalFormat}`),isRemote&&(src=getImageUrl(url,format,quality,w,h,params),srcFallback=getImageUrl(url,naturalFormat,quality,w,h,params));const sizesValue=sizes||`(min-width: ${w/16}rem) ${w/16}rem, ${viewportWidth}vw`,srcsetFallback=[];let srcset=[...config.image.sizes];srcset.includes(w)||srcset.push(w),srcset=srcset.filter(s=>s<=w),srcset.sort((a,b)=>a-b);const srcsetSource=[];srcset.forEach(s=>{if(isLocal){const base=`${url}${s!==naturalWidth?`@${s}`:""}`;srcsetFallback.push(`${base}.${naturalFormat} ${s}w`),srcsetSource.push(`${base}.${format} ${s}w`)}if(isRemote){const sizeHeight=Math.round(s*aspectRatio);srcsetFallback.push(getImageUrl(url,naturalFormat,quality,s,sizeHeight,params)+` ${s}w`),srcsetSource.push(getImageUrl(url,format,quality,s,sizeHeight,params)+` ${s}w`)}if(isWordpress){const sizeUrl=dataSizes?.[s];isStringStrict(sizeUrl)&&srcsetSource.push(`${sizeUrl} ${s}w`)}});let sourceOutput="";picture&&(sourceOutput=`<source srcset="${srcsetSource.join(", ")}" sizes="${sizesValue}" type="image/${format}">`);let eagerHackOutput="";lazy||(eagerHackOutput=`\n <img\n alt=""\n role="presentation"\n aria-hidden="true"\n src="data:image/svg+xml;charset=utf-8,%3Csvg height='${h}' width='${w}' xmlns='http://www.w3.org/2000/svg' version='1.1'%3E%3C/svg%3E" style="pointerEvents: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%"\n >\n `);const output=`\n ${eagerHackOutput}\n ${sourceOutput}\n <img\n ${isStringStrict(classes)?` class="${classes}"`:""}\n alt="${alt}"\n src="${picture?srcFallback:src}"\n srcset="${picture?srcsetFallback.join(", "):srcsetSource.join(", ")}"\n sizes="${sizesValue}"\n width="${w}"\n height="${h}"\n ${isStringStrict(attr)?` ${attr}`:""}\n ${lazy?' loading="lazy" decoding="async"':' loading="eager" fetchpriority="high"'}\n >\n `;return returnDetails?{output:output,aspectRatio:aspectRatio,naturalWidth:naturalWidth,naturalHeight:naturalHeight,src:src,srcFallback:srcFallback,srcset:srcsetSource,sizes:sizesValue}:output},getImageClosestSize=(size,sizes=[])=>(sizes.length||(sizes=config.image.sizes),[...sizes].reduce((prev,curr)=>Math.abs(curr-size)<=Math.abs(prev-size)?curr:prev)),getImageSizes=args=>{const fallback={maxWidth:0,sizes:""};if(!isObjectStrict(args))return fallback;const{parents:parents,widths:widths,maxWidths:maxWidths,breakpoints:breakpoints,source:source=config.source,viewportWidth:viewportWidth=100,maxWidth:max}=args;if(!(isArrayStrict(parents)&&isObjectStrict(widths)&&isObjectStrict(maxWidths)&&isArrayStrict(breakpoints)))return fallback;let containerWidth=0;const columnWidths=[];let col=1,colSmall=1,colMedium=1,colLarge=1;parents.forEach(parent=>{if(!isObjectStrict(parent))return;const{renderType:renderType,args:args}=parent;if(isObjectStrict(args)){if("column"===renderType){const{width:width="Default",widthSmall:widthSmall="Default",widthMedium:widthMedium="Default",widthLarge:widthLarge="Default"}=args,base=isNumber(widths[width])&&widths[width]?widths[width]:1,baseSmall=isNumber(widths[widthSmall])&&widths[widthSmall]?widths[widthSmall]:base,baseMedium=isNumber(widths[widthMedium])&&widths[widthMedium]?widths[widthMedium]:baseSmall,baseLarge=isNumber(widths[widthLarge])&&widths[widthLarge]?widths[widthLarge]:baseMedium;col*=base,colSmall*=baseSmall,colMedium*=baseMedium,colLarge*=baseLarge,columnWidths[0]=col,columnWidths[1]=colSmall,columnWidths[2]=colMedium,columnWidths[3]=colLarge}if("container"===renderType){const{maxWidth:maxWidth="Default"}=args;isNumber(maxWidths[maxWidth])&&(containerWidth=maxWidths[maxWidth])}}});const columnWidthsCount=columnWidths.length,hasContainerWidth=!!containerWidth;if(!columnWidthsCount&&!hasContainerWidth)return fallback;const maxPx=isNumber(max)?max/2:0,maxRem=maxPx/16+"rem",hasMax=!!maxPx&&(!hasContainerWidth||maxPx<containerWidth),breakpointsCount=breakpoints.length,maxWidthArr=[],sizesArr=[],sizeFactor=viewportWidth/100;let lastWidth=1,lastBreakpoint=0,lastSize="",containerWidthAdded=!1,sizesArrCount=0,maxIndex=-1;for(let i=0;i<breakpointsCount;i+=1){const breakpoint=breakpoints[i],width=columnWidths[i];if(!isNumber(width))continue;const bk=0===breakpoint&&0===i?breakpoints[i+1]:breakpoint,gteContainerWidth=hasContainerWidth&&breakpoint>=containerWidth,breakpointWidth=Math.round(width*(gteContainerWidth?containerWidth:bk)),gtMaxWidth=hasMax&&breakpointWidth>maxPx,sizeWidth=gteContainerWidth?breakpointWidth/16:100*width*sizeFactor,size=gteContainerWidth?`${sizeWidth}rem`:`${sizeWidth%1==0?sizeWidth:sizeWidth.toFixed(2)}vw`;if(hasContainerWidth&&containerWidth>lastBreakpoint&&containerWidth<breakpoint){const relMaxWidth=Math.round(lastWidth*containerWidth),relSize=relMaxWidth/16+"rem";hasMax&&relMaxWidth>maxPx||(maxWidthArr.push(relMaxWidth),sizesArrCount=sizesArr.push(`(min-width: ${containerWidth/16}rem) ${relSize}`),containerWidthAdded=!0,lastSize=relSize)}gtMaxWidth||maxWidthArr.push(breakpointWidth),gtMaxWidth||lastSize===size||(sizesArrCount=sizesArr.push(breakpoint?`(min-width: ${breakpoint/16}rem) ${size}`:size)),hasMax&&maxPx>lastBreakpoint&&maxPx<breakpoint&&maxPx<breakpointWidth&&(maxIndex=sizesArrCount),lastWidth=width,lastBreakpoint=breakpoint,lastSize=size}if(!containerWidthAdded&&hasContainerWidth&&containerWidth>lastBreakpoint){const relMaxWidth=Math.round(lastWidth*containerWidth),relSize=relMaxWidth/16+"rem";hasMax&&relMaxWidth>maxPx||(maxWidthArr.push(relMaxWidth),sizesArrCount=sizesArr.push(`(min-width: ${containerWidth/16}rem) ${relSize}`),containerWidthAdded=!0)}hasMax&&maxPx>lastBreakpoint&&(maxIndex=sizesArrCount),-1!==maxIndex&&(maxWidthArr.push(maxPx),sizesArr.splice(maxIndex,0,`(min-width: ${maxRem}) ${maxRem}`));const maxWidth=2*Math.max(...maxWidthArr);if(!hasMax&&(!columnWidthsCount||1===col&&1===colSmall&&1===colMedium&&1===colLarge)){const sizeWidth=maxWidth/32+"rem";sizesArr[0]=`${viewportWidth}vw`,sizesArr[1]=`(min-width: ${sizeWidth}) ${sizeWidth}`}const sizes=sizesArr.reverse().join(", ");return"local"===source?{maxWidth:getImageClosestSize(maxWidth),sizes:sizes}:{maxWidth:maxWidth,sizes:sizes}};export{getImage,getImageClosestSize,getImageSizes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{extname,resolve,basename,dirname}from"node:path";import{mkdir,stat}from"node:fs/promises";import sharp from"sharp";import{getFilePaths}from"../file/filePath.js";import{isStringStrict}from"../string/string.js";import{setStoreItem}from"../../store/store.js";import{config}from"../../config/config.js";const setLocalImages=async()=>{const inputDir=config.image.inputDir,outputDir=config.image.outputDir;if(!isStringStrict(inputDir)||!isStringStrict(outputDir))throw new Error("No input or output directories");await mkdir(resolve(outputDir),{recursive:!0});const images=[],meta={};for await(const path of getFilePaths(inputDir)){const baseName=basename(path),ext=extname(baseName);if(!isStringStrict(ext))continue;const[base]=baseName.split(ext);if(!
|
|
1
|
+
import{extname,resolve,basename,dirname}from"node:path";import{mkdir,stat}from"node:fs/promises";import sharp from"sharp";import{getFilePaths}from"../file/filePath.js";import{isStringSafe,isStringStrict}from"../string/string.js";import{setStoreItem}from"../../store/store.js";import{config}from"../../config/config.js";const setLocalImages=async()=>{const inputDir=config.image.inputDir,outputDir=config.image.outputDir;if(!isStringStrict(inputDir)||!isStringStrict(outputDir))throw new Error("No input or output directories");await mkdir(resolve(outputDir),{recursive:!0});const images=[],meta={};for await(const path of getFilePaths(inputDir)){const baseName=basename(path),ext=extname(baseName);if(!isStringStrict(ext))continue;const[base]=baseName.split(ext);if(!isStringSafe(base?.trim()))continue;let[,folders]=dirname(path).split(`${inputDir}/`);isStringStrict(folders)&&folders!==baseName?await mkdir(resolve(outputDir,folders),{recursive:!0}):folders="";const instance=sharp(path),metadata=await sharp(path).metadata(),stats=await stat(path),{width:width,height:height,format:fileFormat}=metadata,id=`${folders?`${folders}/`:""}${base}`,format=ext.replace(".","");meta[id]={path:id,name:baseName,type:`image/${fileFormat}`,format:format,size:stats.size,width:width,height:height};let sizes=[...config.image.sizes];sizes.includes(width)||sizes.push(width),sizes=sizes.filter(s=>s<=width),sizes.forEach(size=>{images.push({size:size,format:format,path:resolve(path),newPath:resolve(outputDir,folders,`${base}${size!==width?`@${size}`:""}`),instance:instance})})}if(!images.length)throw new Error("No local images to transform");return setStoreItem("imageMeta",meta),await Promise.all(images.map(async image=>{const{size:size,instance:instance,newPath:newPath,format:format}=image;return await instance.clone().resize(size).toFile(`${newPath}.${format}`),await instance.clone().resize(size).webp({quality:config.image.quality}).toFile(`${newPath}.webp`)}))};export{setLocalImages};
|
package/lib/utils/json/json.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
declare const getJson: <T extends object>(value: string) => T
|
|
2
|
-
declare const getJsonFile: <T>(path: string, store?: boolean) => Promise<
|
|
1
|
+
declare const getJson: <T extends object>(value: string) => T;
|
|
2
|
+
declare const getJsonFile: <T>(path: string, store?: boolean) => Promise<object & T>;
|
|
3
3
|
export { getJson, getJsonFile };
|
package/lib/utils/json/json.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"../object/object.js";import{getPath}from"../path/path.js";import{applyFilters}from"../../filters/filters.js";const getJson=value=>{
|
|
1
|
+
import{isObject}from"../object/object.js";import{getPath}from"../path/path.js";import{applyFilters}from"../../filters/filters.js";const getJson=value=>{const val=JSON.parse(value);if(isObject(val))return val;throw new Error("Value not an object")},getJsonFile=async(path,store=!1)=>{const newPath=store?getPath(path,"store"):path,{default:obj}=await import(newPath);if(isObject(obj))return store?await applyFilters("storeData",obj,newPath,!0):obj;throw new Error("No object in JSON file")};export{getJson,getJsonFile};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
declare const isString: (value: unknown) => value is string;
|
|
2
2
|
declare const isStringStrict: (value: unknown) => value is string;
|
|
3
|
-
|
|
3
|
+
declare const isStringSafe: (value: unknown) => value is string;
|
|
4
|
+
export { isString, isStringStrict, isStringSafe };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const isString=value=>"string"==typeof value,isStringStrict=value=>isString(value)&&""!==value;export{isString,isStringStrict};
|
|
1
|
+
const isString=value=>"string"==typeof value,isStringStrict=value=>isString(value)&&""!==value,isStringSafe=value=>isStringStrict(value)&&"__proto__"!==value&&"constructor"!==value&&"prototype"!==value;export{isString,isStringStrict,isStringSafe};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{normalizeWordPressData,normalizeWordPressMenuItems,normalizeWordPressMenus,normalRoutes}from"./wordpressDataNormal.js";import{applyFilters}from"../filters/filters.js";import{isObject,isObjectStrict}from"../utils/object/object.js";import{isString,isStringStrict}from"../utils/string/string.js";import{isArray}from"../utils/array/array.js";import{getStoreItem}from"../store/store.js";import{config}from"../config/config.js";const getRoute=type=>{const route=normalRoutes.get(type);return isString(route)?route:type},getWordPressData=async(args,_page=1)=>{if(!isObjectStrict(args))throw new Error("No args");const{key:key,route:route,params:params,fetcher:fetcher=fetch,options:options}=args;if(!isStringStrict(key))throw new Error("No key");if(config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await applyFilters("cacheData",void 0,cacheDataFilterArgs,!0);if(isObject(cacheData))return structuredClone(cacheData)}if(!isStringStrict(route))throw new Error("No route");const{devUser:devUser,prodUser:prodUser,devCredential:devCredential,prodCredential:prodCredential,devHost:devHost,prodHost:prodHost,ssl:ssl=!0}=config.cms;let user=devUser,pass=devCredential,host=devHost,status="any";if(config.env.prod&&(user=prodUser,pass=prodCredential,host=prodHost,status="publish"),!isStringStrict(user)||!isStringStrict(pass)||!isStringStrict(host))throw new Error("No credentials");
|
|
1
|
+
import{normalizeWordPressData,normalizeWordPressMenuItems,normalizeWordPressMenus,normalRoutes}from"./wordpressDataNormal.js";import{applyFilters}from"../filters/filters.js";import{isObject,isObjectStrict}from"../utils/object/object.js";import{isString,isStringSafe,isStringStrict}from"../utils/string/string.js";import{isArray}from"../utils/array/array.js";import{getStoreItem}from"../store/store.js";import{config}from"../config/config.js";const getRoute=type=>{const route=normalRoutes.get(type);return isString(route)?route:type},getWordPressData=async(args,_page=1)=>{if(!isObjectStrict(args))throw new Error("No args");const{key:key,route:route,params:params,fetcher:fetcher=fetch,options:options}=args;if(!isStringStrict(key))throw new Error("No key");if(config.env.cache){const cacheDataFilterArgs={key:key,type:"get"},cacheData=await applyFilters("cacheData",void 0,cacheDataFilterArgs,!0);if(isObject(cacheData))return structuredClone(cacheData)}if(!isStringStrict(route))throw new Error("No route");const{devUser:devUser,prodUser:prodUser,devCredential:devCredential,prodCredential:prodCredential,devHost:devHost,prodHost:prodHost,ssl:ssl=!0}=config.cms;let user=devUser,pass=devCredential,host=devHost,status="any";if(config.env.prod&&(user=prodUser,pass=prodCredential,host=prodHost,status="publish"),!isStringStrict(user)||!isStringStrict(pass)||!isStringStrict(host))throw new Error("No credentials");const urlObj=new URL(`${ssl?"https":"http"}://${host}/wp-json/wp/v2/${route}?status=${status}`);let loop=!1,embed=!1;if(isObjectStrict(params))for(const[key,value]of Object.entries(params)){let val=value;"_embed"===key&&(embed=!0),"per_page"===key&&-1===value&&(val=100,loop=!0),urlObj.searchParams.set(key,val.toString())}loop&&urlObj.searchParams.set("page",_page.toString());let url=urlObj.toString();embed||(url+="&_embed");const headers=new Headers;headers.set("Authorization",`Basic ${btoa(`${user}:${pass}`)}`);const resp=await fetcher(url,{headers:headers,...options}),data=await resp.json(),isErr=isObjectStrict(data)&&isStringStrict(data.message),message=isErr?data.message:"Bad fetch response";if(!resp.ok||isErr)throw new Error(message,{cause:data});const total=resp.headers.get("X-WP-Total"),totalPages=resp.headers.get("X-WP-TotalPages"),totalNum=isStringStrict(total)?parseInt(total,10):0,totalPagesNum=isStringStrict(totalPages)?parseInt(totalPages,10):0,dataItems=isArray(data)?data:[data];let newItems=normalizeWordPressData(dataItems,route);if(loop&&_page<totalPagesNum){const pagData=await getWordPressData({key:key,route:route,params:{per_page:-1}},_page+1),{items:pagItems}=pagData;newItems=[...newItems,...pagItems]}const newData={items:newItems,total:totalNum,pages:totalPagesNum};if(config.env.cache){const cacheDataFilterArgs={key:key,type:"set",data:data};await applyFilters("cacheData",newData,cacheDataFilterArgs,!0)}return newData},getAllWordPressData=async args=>{const{serverlessData:serverlessData,previewData:previewData}=isObjectStrict(args)?args:{};let allData={navigationItem:[],navigation:[],content:{page:[]}};const isServerless=null!=serverlessData,isPreview=null!=previewData,wordpressDataFilterArgs={serverlessData:serverlessData,previewData:previewData};if(isServerless||isPreview){let contentType="",id="";if(isServerless){const item=getStoreItem("slugs")[serverlessData.path];if(item){const[itemId,itemContentType]=item;id=itemId||"",contentType=itemContentType||""}}if(isPreview&&(id=previewData.id,contentType=previewData.contentType),id&&isStringSafe(contentType)){const key=`serverless_${id}_${contentType}`,data=await getWordPressData({key:key,route:`${getRoute(contentType)}/${id}`});let{items:items}=data;items=applyFilters("wordpressData",items,{...wordpressDataFilterArgs,contentType:contentType}),allData.content[contentType]=items}}if(!isServerless){const partial=config.partialTypes.filter(type=>isStringSafe(type));for(const contentType of partial){const isMenu="nav_menu"===contentType,isMenuItem="nav_menu_item"===contentType,partialType=isMenu?"navigation":isMenuItem?"navigationItem":contentType;allData[partialType]=[];const key=`all_${contentType}`,data=await getWordPressData({key:key,route:getRoute(contentType),params:{per_page:-1}});let{items:items}=data;isMenuItem&&(items=normalizeWordPressMenuItems(items)),isMenu&&(items=normalizeWordPressMenus(items)),items=applyFilters("wordpressData",items,{...wordpressDataFilterArgs,contentType:contentType}),allData[partialType]=items}}if(!isServerless&&!isPreview){const whole=config.wholeTypes.filter(type=>isStringSafe(type));for(const contentType of whole){allData.content[contentType]=[];const key=`all_${contentType}`,data=await getWordPressData({key:key,route:getRoute(contentType),params:{per_page:-1}});let{items:items}=data;items=applyFilters("wordpressData",items,{...wordpressDataFilterArgs,contentType:contentType}),allData.content[contentType]=items}}return allData=applyFilters("allData",allData,{type:"wordpress",serverlessData:serverlessData,previewData:previewData}),allData};export{getRoute,getWordPressData,getAllWordPressData};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parse}from"@wordpress/block-serialization-default-parser";import{normalizeContentType}from"../utils/contentType/contentType.js";import{getObjectKeys}from"../utils/object/objectUtils.js";import{getStoreItem,setStoreItem}from"../store/store.js";import{isString,isStringStrict}from"../utils/string/string.js";import{isArrayStrict}from"../utils/array/array.js";import{isObjectStrict}from"../utils/object/object.js";import{isNumber}from"../utils/number/number.js";import{config}from"../config/config.js";const normalRoutes=new Map([["page","pages"],["post","posts"],["taxonomy","taxonomies"],["category","categories"],["tag","tags"],["attachment","media"],["nav_menu","menus"],["nav_menu_item","menu-items"]]),normalMetaKeys=new Map,menusById=new Map,excludeProps=["_links","auto_add"],getTaxonomy=id=>{const taxonomy=getStoreItem("taxonomies")[id],{title:title="",slug:slug="",contentTypes:contentTypes=[]}=isObjectStrict(taxonomy)?taxonomy:{};return{id:id,title:title,slug:slug,contentTypes:contentTypes}},normalizeFile=file=>{const{url:url,filename:filename,alt:alt,width:width,height:height,filesizeInBytes:filesizeInBytes,subtype:subtype,mime:mime,sizes:sizes}=file;let newSizes;if(isObjectStrict(sizes)){newSizes={};for(const[,value]of Object.entries(sizes)){const{width:width,source_url:src}=value;let{url:url}=value;isStringStrict(src)&&(url=src),isNumber(width)&&isStringStrict(url)&&(newSizes[width]=url)}}return{url:isString(url)?url:"",name:isString(filename)?filename:"",alt:isString(alt)?alt:"",width:isNumber(width)?width:0,height:isNumber(height)?height:0,size:isNumber(filesizeInBytes)?filesizeInBytes:0,format:"jpeg"===subtype?"jpg":subtype,type:mime,sizes:newSizes}},normalizeEmbedded=(value,item,newItem)=>{getObjectKeys(value).forEach(k=>{const embeds=value[k];if(isArrayStrict(embeds)){if("author"===k){const exclude=[...excludeProps,"id","avatar_urls"];embeds.forEach(embed=>{if(!isObjectStrict(embed))return;const{id:id}=embed;if(item.author!==id)return;const newAuthor={id:id.toString()};Object.entries(embed).forEach(([key,val])=>{exclude.includes(key)
|
|
1
|
+
import{parse}from"@wordpress/block-serialization-default-parser";import{normalizeContentType}from"../utils/contentType/contentType.js";import{getObjectKeys}from"../utils/object/objectUtils.js";import{getStoreItem,setStoreItem}from"../store/store.js";import{isString,isStringSafe,isStringStrict}from"../utils/string/string.js";import{isArrayStrict}from"../utils/array/array.js";import{isObjectStrict}from"../utils/object/object.js";import{isNumber}from"../utils/number/number.js";import{config}from"../config/config.js";const normalRoutes=new Map([["page","pages"],["post","posts"],["taxonomy","taxonomies"],["category","categories"],["tag","tags"],["attachment","media"],["nav_menu","menus"],["nav_menu_item","menu-items"]]),normalMetaKeys=new Map,menusById=new Map,excludeProps=["_links","auto_add"],getTaxonomy=id=>{const taxonomy=getStoreItem("taxonomies")[id],{title:title="",slug:slug="",contentTypes:contentTypes=[]}=isObjectStrict(taxonomy)?taxonomy:{};return{id:id,title:title,slug:slug,contentTypes:contentTypes}},normalizeFile=file=>{const{url:url,filename:filename,alt:alt,width:width,height:height,filesizeInBytes:filesizeInBytes,subtype:subtype,mime:mime,sizes:sizes}=file;let newSizes;if(isObjectStrict(sizes)){newSizes={};for(const[,value]of Object.entries(sizes)){const{width:width,source_url:src}=value;let{url:url}=value;isStringStrict(src)&&(url=src),isNumber(width)&&isStringStrict(url)&&(newSizes[width]=url)}}return{url:isString(url)?url:"",name:isString(filename)?filename:"",alt:isString(alt)?alt:"",width:isNumber(width)?width:0,height:isNumber(height)?height:0,size:isNumber(filesizeInBytes)?filesizeInBytes:0,format:"jpeg"===subtype?"jpg":subtype,type:mime,sizes:newSizes}},normalizeEmbedded=(value,item,newItem)=>{getObjectKeys(value).forEach(k=>{const embeds=value[k];if(isArrayStrict(embeds)){if("author"===k){const exclude=[...excludeProps,"id","avatar_urls"];embeds.forEach(embed=>{if(!isObjectStrict(embed))return;const{id:id}=embed;if(item.author!==id)return;const newAuthor={id:id.toString()};Object.entries(embed).forEach(([key,val])=>{!exclude.includes(key)&&isStringSafe(key)&&(newAuthor[key]=val)}),newItem.author=newAuthor})}if("up"===k&&embeds.forEach(embed=>{if(!isObjectStrict(embed))return;const{id:id,title:parentTitle,name:name,type:type,taxonomy:taxonomy,slug:slug}=embed;if(item.parent!==id)return;let title="";isString(parentTitle?.rendered)&&(title=parentTitle.rendered),isString(name)&&(title=name),newItem.parent={id:id.toString(),contentType:isString(taxonomy)?"term":type,title:title,slug:slug}}),"wp:featuredmedia"===k&&embeds.forEach(embed=>{if(!isObjectStrict(embed))return;const{id:id,source_url:url,media_details:details,mime_type:mimeType,alt_text:alt}=embed;if(!isObjectStrict(details))return;const{file:file,filesize:filesize,width:width,height:height,sizes:sizes}=details;item.featured_media===id&&(newItem.featured_media=normalizeFile({url:url,filename:file?.split("/").pop(),alt:alt,width:width,height:height,filesizeInBytes:filesize,subtype:mimeType?.split("/").pop(),mime:mimeType,sizes:sizes}))}),"wp:term"===k){const exclude=[...excludeProps,"id","name","taxonomy"];embeds.forEach(embed=>{isArrayStrict(embed)&&embed.forEach(e=>{if(!isObjectStrict(e))return;const{id:id,name:name,taxonomy:taxonomy=""}=e;let taxonomyLookup=taxonomy;"category"===taxonomy&&(taxonomyLookup="categories"),"post_tag"===taxonomy&&(taxonomyLookup="tags");const itemTaxonomy=newItem[taxonomyLookup]||item[taxonomyLookup];isStringSafe(taxonomyLookup)&&isArrayStrict(itemTaxonomy)&&(newItem[taxonomyLookup]=itemTaxonomy.map(taxonomyId=>{if(taxonomyId!==id)return taxonomyId;const newTerm={id:id.toString(),title:name,contentType:"term",taxonomy:getTaxonomy(taxonomy)};return Object.entries(e).forEach(([key,val])=>{!exclude.includes(key)&&isStringSafe(key)&&(newTerm[key]=val)}),newTerm}))})})}}})},normalizeBlocks=blocks=>{const newItems=[];return blocks.forEach(block=>{const{blockName:blockName,attrs:attrs,innerBlocks:innerBlocks}=block,contentType=blockName;if(!isStringStrict(contentType))return;const{isItem:isItem}=attrs,attrItemArr=(isStringStrict(isItem)?isItem:"").split(","),attrItemExists=attrItemArr.length,newItem={contentType:contentType};for(const[key,value]of Object.entries(attrs)){if(!isStringSafe(key))continue;const isObj=isObjectStrict(value);if(isObj&&attrItemExists&&attrItemArr.includes(key)){const itemValue=normalizeItem(value);itemValue.content=void 0,newItem[key]=itemValue;continue}isObj&&isStringStrict(value.mime)?newItem[key]=normalizeFile(value):newItem[key]=value}const renderType=config.renderTypes[contentType];return isString(renderType)&&(newItem.renderType=renderType),isArrayStrict(innerBlocks)&&(newItem.content=normalizeBlocks(innerBlocks)),newItems.push(newItem)}),newItems},normalizeItem=item=>{const newItem={};for(const[key,value]of Object.entries(item)){if(excludeProps.includes(key)||!isStringSafe(key))continue;let val=value,k=key;const isObj=isObjectStrict(value),isStr=isStringStrict(value);if("id"!==key&&"object_id"!==k||(val=value?.toString()),"type"===key&&isStr)newItem.contentType=normalizeContentType(value),isString(config.renderTypes[value])&&(newItem.renderType=config.renderTypes[value]);else{if("types"===key&&(k="contentTypes"),isObj){const{rendered:rendered}=value;isString(rendered)&&(val=rendered)}if("name"===key&&(k="title"),"_embedded"===key&&isObj)normalizeEmbedded(value,item,newItem);else{if(isStringStrict(val)){if("excerpt"===key&&(val=val.replace(/<p>|<\/p>/g,"").trim()),"content"===key){const normalVal=normalizeBlocks(parse(val));val=normalVal.length?normalVal:val}"taxonomy"===key&&(newItem.contentType="term",val=getTaxonomy(val))}if("meta"===key&&isObj)for(const[metaKey,metaValue]of Object.entries(val))isStringSafe(metaKey)&&(newItem[normalMetaKeys.get(metaKey)||metaKey]=metaValue);else{if("media_details"===k&&isObj){const valObj=val,valFull=valObj.sizes?.full,sourceUrl=item.source_url,mimeType=item.mime_type;val=normalizeFile({url:sourceUrl,filename:sourceUrl?.split("/").pop(),alt:item.alt_text,width:valFull?.width,height:valFull?.height,filesizeInBytes:valObj.filesize,subtype:mimeType?.split("/")[1],mime:mimeType,sizes:valObj.sizes})}newItem[k]=val}}}}return newItem},normalizeWordPressMenuItems=items=>{const itemsObj=Object.fromEntries(items.map(item=>[item.id,item]));menusById.clear(),items.forEach(item=>{const{id:id="",title:title="",menu_order:menu_order=0,menus:menus=0}=item,parent=item.parent,hasMenuOrder=isNumber(menu_order);if(hasMenuOrder&&isObjectStrict(itemsObj[parent])&&(null==itemsObj[parent].children&&(itemsObj[parent].children=[]),itemsObj[parent].children.push({id:id,menu_order:menu_order,title:title})),hasMenuOrder&&isNumber(menus)&&0===parent){const menuId=menus.toString();null==menusById.get(menuId)&&menusById.set(menuId,[]),menusById.get(menuId)?.push({id:id,menu_order:menu_order,title:title})}});const newItems=[];for(const[id,obj]of Object.entries(itemsObj)){const{url:url="",title:title="",contentType:contentType="",children:children=[],object:object="",object_id:object_id="",locale:locale=""}=obj;if(!isString(url)||!isStringStrict(title))continue;const newItem={id:id,title:title},isCustom="custom"===contentType;if(!isCustom&&isStringStrict(object)&&isStringStrict(object_id)){const isTerm="taxonomy"===contentType,internalLink={contentType:isTerm?"term":object,id:object_id,slug:url.split("/").filter(Boolean).pop()};isTerm&&(internalLink.taxonomy=getTaxonomy(object)),isStringStrict(locale)&&(internalLink.locale=locale),newItem.link=url,newItem.internalLink=internalLink}if(isCustom){url.startsWith("http")&&!url.startsWith(config.env.prodUrl)?newItem.externalLink=url:newItem.link=url}isArrayStrict(children)&&(newItem.children=children.sort((a,b)=>a.menu_order-b.menu_order));const exclude=[...excludeProps,"url","type","type_label","object","object_id","invalid","meta","menu_order","menus","parent","contentType","status","xfn"];Object.entries(obj).forEach(([key,val])=>{!exclude.includes(key)&&isStringSafe(key)&&(newItem[key]=val)}),newItems.push(newItem)}return newItems},normalizeWordPressMenus=menus=>{const newMenus=[];return menus.forEach(menu=>{const{id:id="",title:title="",description:description="",locations:locations=[],meta:meta=[]}=menu,newMenu={id:id,title:title,description:description,meta:meta,location:locations,items:menusById.get(id)?.sort((a,b)=>a.menu_order-b.menu_order)||[]};newMenus.push(newMenu)}),newMenus},normalizeWordPressData=(data,route,_newData=[])=>isArrayStrict(data)?("taxonomies"===route&&(data=Object.entries(data[0]).map(([key,value])=>({id:key,type:"taxonomy",...value}))),data.forEach(item=>{isObjectStrict(item)&&_newData.push(normalizeItem(item))}),"taxonomies"===route&&_newData.forEach(item=>{setStoreItem("taxonomies",item,item.id)}),_newData):[];export{normalizeWordPressData,normalizeWordPressMenuItems,normalizeWordPressMenus,normalRoutes,normalMetaKeys};
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alanizcreative/formation-static",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.4",
|
|
4
4
|
"description": "Minimal static-site HTML renderer from JSON, Contentful, or WordPress data",
|
|
5
5
|
"main": "./lib/config/config.js",
|
|
6
|
-
"packageManager": "pnpm@10.
|
|
6
|
+
"packageManager": "pnpm@10.29.1",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"files": [
|
|
9
9
|
"./lib",
|
|
@@ -45,15 +45,15 @@
|
|
|
45
45
|
"license": "MIT",
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@types/contentful-resolve-response": "^0.1.33",
|
|
48
|
-
"@types/node": "^25.
|
|
49
|
-
"@vitest/coverage-v8": "^4.0.
|
|
48
|
+
"@types/node": "^25.2.2",
|
|
49
|
+
"@vitest/coverage-v8": "^4.0.18",
|
|
50
50
|
"eslint": "9.39.2",
|
|
51
|
-
"memfs": "4.
|
|
52
|
-
"release-it": "^19.2.
|
|
53
|
-
"terser": "5.
|
|
51
|
+
"memfs": "4.56.10",
|
|
52
|
+
"release-it": "^19.2.4",
|
|
53
|
+
"terser": "5.46.0",
|
|
54
54
|
"typescript": "^5.9.3",
|
|
55
|
-
"typescript-eslint": "8.
|
|
56
|
-
"vitest": "^4.0.
|
|
55
|
+
"typescript-eslint": "8.54.0",
|
|
56
|
+
"vitest": "^4.0.18"
|
|
57
57
|
},
|
|
58
58
|
"dependencies": {
|
|
59
59
|
"uuid": "^13.0.0"
|
package/cjs/utils/proto/proto.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isProto=void 0;const isProto=value=>new Set(["__proto__","constructor","prototype"]).has(value);exports.isProto=isProto;
|
package/lib/utils/proto/proto.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const isProto=value=>new Set(["__proto__","constructor","prototype"]).has(value);export{isProto};
|