@stacksjs/utils 0.75.515 → 0.75.519
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/dist/bytes.js +1 -1
- package/dist/clean.js +1 -1
- package/dist/colors.js +1 -1
- package/dist/debounce.js +1 -1
- package/dist/detect.js +6 -6
- package/dist/equal.js +1 -1
- package/dist/errors.js +1 -1
- package/dist/find.js +1 -1
- package/dist/git.js +1 -1
- package/dist/hash.js +1 -1
- package/dist/helpers.js +3 -3
- package/dist/macroable.js +1 -1
- package/dist/markdown.js +2 -2
- package/dist/merge.js +1 -1
- package/dist/observer.js +1 -1
- package/dist/pipeline.js +1 -1
- package/dist/safe-json.js +1 -1
- package/dist/size.js +2 -2
- package/dist/utils.js +1 -1
- package/package.json +13 -13
package/dist/bytes.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const DECIMAL_UNITS=["B","KB","MB","GB","TB","PB","EB","ZB","YB"]
|
|
1
|
+
const DECIMAL_UNITS=["B","KB","MB","GB","TB","PB","EB","ZB","YB"];const BINARY_UNITS=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];export function formatBytes(bytes,options={}){const{precision=1,binary=false,space=true,locale="en-US",minimumFractionDigits=0,maximumFractionDigits=precision}=options;if(!Number.isFinite(bytes)){throw new TypeError(`Expected a finite number, got ${typeof bytes}: ${bytes}`)}const isNegative=bytes<0;const prefix=isNegative?"-":"";if(isNegative){bytes=-bytes}if(bytes<1){const numberString=bytes.toLocaleString(locale,{minimumFractionDigits,maximumFractionDigits});return`${prefix}${numberString}${space?" ":""}B`}const base=binary?1024:1000;const units=binary?BINARY_UNITS:DECIMAL_UNITS;const exponent=Math.min(Math.floor(Math.log(bytes)/Math.log(base)),units.length-1);const value=bytes/base**exponent;const numberString=value.toLocaleString(locale,{minimumFractionDigits,maximumFractionDigits});const unit=units[exponent];const separator=space?" ":"";return`${prefix}${numberString}${separator}${unit}`}export function parseBytes(input){const match=input.trim().match(/^(-?(?:\d+(?:\.\d*)?|\.\d+))\s*([A-Za-z]+)?$/);if(!match){throw new Error(`Invalid byte string: ${input}`)}const[,numberStr,unit="B"]=match;if(numberStr===undefined){throw new Error(`Invalid byte string: ${input}`)}const number=Number(numberStr);if(!Number.isFinite(number)){throw new Error(`Invalid number in byte string: ${numberStr}`)}const normalizedUnit=unit.toUpperCase();const isBinary=normalizedUnit.endsWith("IB");const base=isBinary?1024:1000;const units=isBinary?BINARY_UNITS:DECIMAL_UNITS;const exponent=units.findIndex((value)=>value.toUpperCase()===normalizedUnit);if(exponent<0)throw new Error(`Unknown byte unit: ${unit}`);const bytes=number*base**exponent;if(!Number.isFinite(bytes))throw new RangeError("Byte value out of range");return bytes}export function compareBytes(a,b){const bytesA=typeof a==="string"?parseBytes(a):a;const bytesB=typeof b==="string"?parseBytes(b):b;return bytesA-bytesB}export const prettyBytes=formatBytes;export const readableSize=formatBytes;export{formatBytes as default};
|
package/dist/clean.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{lstatSync,readdirSync,rmSync}from"node:fs";import{dirname,isAbsolute,join,relative,sep}from"node:path";import{path as p}from"@stacksjs/path";function ownedDirectory(root,directory){const path=relative(root,directory);if(isAbsolute(path)||path===".."||path.startsWith(`..${sep}`))return
|
|
1
|
+
import{lstatSync,readdirSync,rmSync}from"node:fs";import{dirname,isAbsolute,join,relative,sep}from"node:path";import{path as p}from"@stacksjs/path";function ownedDirectory(root,directory){const path=relative(root,directory);if(isAbsolute(path)||path===".."||path.startsWith(`..${sep}`))return false;let current=root;for(const part of path.split(sep).filter(Boolean)){current=join(current,part);try{const stat=lstatSync(current);if(!stat.isDirectory()||stat.isSymbolicLink())return false}catch(error){if(error.code==="ENOENT")return false;throw error}}return true}export async function cleanProject(){const root=p.projectPath();const remove=(path)=>{if(ownedDirectory(root,dirname(path)))rmSync(path,{recursive:true,force:true})};for(const path of[p.projectPath("bun.lock"),p.projectPath("yarn.lock"),p.projectPath("node_modules"),p.frameworkCloudPath("cdk.out"),p.frameworkCloudPath("cdk.context.json"),p.cloudPath("dist.zip")])remove(path);const walk=(directory)=>{if(!ownedDirectory(root,directory))return;for(const entry of readdirSync(directory,{withFileTypes:true})){const path=join(directory,entry.name);if(entry.name==="dist"||entry.name==="node_modules")remove(path);else if(entry.isDirectory()&&!entry.isSymbolicLink())walk(path)}};walk(p.frameworkPath())}
|
package/dist/colors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const isColorSupported=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||process.stdout?.isTTY)
|
|
1
|
+
const isColorSupported=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||process.stdout?.isTTY);const colors={reset:isColorSupported?"\x1B[0m":"",black:isColorSupported?"\x1B[30m":"",red:isColorSupported?"\x1B[31m":"",green:isColorSupported?"\x1B[32m":"",yellow:isColorSupported?"\x1B[33m":"",blue:isColorSupported?"\x1B[34m":"",magenta:isColorSupported?"\x1B[35m":"",cyan:isColorSupported?"\x1B[36m":"",white:isColorSupported?"\x1B[37m":"",gray:isColorSupported?"\x1B[90m":"",grey:isColorSupported?"\x1B[90m":"",lightRed:isColorSupported?"\x1B[91m":"",lightGreen:isColorSupported?"\x1B[92m":"",lightYellow:isColorSupported?"\x1B[93m":"",lightBlue:isColorSupported?"\x1B[94m":"",lightMagenta:isColorSupported?"\x1B[95m":"",lightCyan:isColorSupported?"\x1B[96m":"",lightGray:isColorSupported?"\x1B[37m":"",lightGrey:isColorSupported?"\x1B[37m":"",bgBlack:isColorSupported?"\x1B[40m":"",bgRed:isColorSupported?"\x1B[41m":"",bgGreen:isColorSupported?"\x1B[42m":"",bgYellow:isColorSupported?"\x1B[43m":"",bgBlue:isColorSupported?"\x1B[44m":"",bgMagenta:isColorSupported?"\x1B[45m":"",bgCyan:isColorSupported?"\x1B[46m":"",bgWhite:isColorSupported?"\x1B[47m":"",bgLightRed:isColorSupported?"\x1B[101m":"",bgLightGreen:isColorSupported?"\x1B[102m":"",bgLightYellow:isColorSupported?"\x1B[103m":"",bgLightBlue:isColorSupported?"\x1B[104m":"",bgLightMagenta:isColorSupported?"\x1B[105m":"",bgLightCyan:isColorSupported?"\x1B[106m":"",bold:isColorSupported?"\x1B[1m":"",dim:isColorSupported?"\x1B[2m":"",italic:isColorSupported?"\x1B[3m":"",underline:isColorSupported?"\x1B[4m":"",inverse:isColorSupported?"\x1B[7m":"",hidden:isColorSupported?"\x1B[8m":"",strikethrough:isColorSupported?"\x1B[9m":""};function createColorFn(code,endCode=colors.reset){return(text)=>{if(!isColorSupported)return String(text);return`${code}${text}${endCode}`}}export const black=createColorFn(colors.black);export const red=createColorFn(colors.red);export const green=createColorFn(colors.green);export const yellow=createColorFn(colors.yellow);export const blue=createColorFn(colors.blue);export const magenta=createColorFn(colors.magenta);export const cyan=createColorFn(colors.cyan);export const white=createColorFn(colors.white);export const gray=createColorFn(colors.gray);export const grey=gray;export const lightRed=createColorFn(colors.lightRed);export const lightGreen=createColorFn(colors.lightGreen);export const lightYellow=createColorFn(colors.lightYellow);export const lightBlue=createColorFn(colors.lightBlue);export const lightMagenta=createColorFn(colors.lightMagenta);export const lightCyan=createColorFn(colors.lightCyan);export const lightGray=createColorFn(colors.lightGray);export const lightGrey=lightGray;export const bgBlack=createColorFn(colors.bgBlack);export const bgRed=createColorFn(colors.bgRed);export const bgGreen=createColorFn(colors.bgGreen);export const bgYellow=createColorFn(colors.bgYellow);export const bgBlue=createColorFn(colors.bgBlue);export const bgMagenta=createColorFn(colors.bgMagenta);export const bgCyan=createColorFn(colors.bgCyan);export const bgWhite=createColorFn(colors.bgWhite);export const bgLightRed=createColorFn(colors.bgLightRed);export const bgLightGreen=createColorFn(colors.bgLightGreen);export const bgLightYellow=createColorFn(colors.bgLightYellow);export const bgLightBlue=createColorFn(colors.bgLightBlue);export const bgLightMagenta=createColorFn(colors.bgLightMagenta);export const bgLightCyan=createColorFn(colors.bgLightCyan);export const bold=createColorFn(colors.bold);export const dim=createColorFn(colors.dim);export const italic=createColorFn(colors.italic);export const underline=createColorFn(colors.underline);export const inverse=createColorFn(colors.inverse);export const hidden=createColorFn(colors.hidden);export const strikethrough=createColorFn(colors.strikethrough);export const reset=createColorFn(colors.reset,"");export function stripColors(text){return text.replace(/\x1B\[\d+m/g,"")}export function supportsColor(){return!!isColorSupported}export default {black,red,green,yellow,blue,magenta,cyan,white,gray,grey,lightRed,lightGreen,lightYellow,lightBlue,lightMagenta,lightCyan,lightGray,lightGrey,bgBlack,bgRed,bgGreen,bgYellow,bgBlue,bgMagenta,bgCyan,bgWhite,bgLightRed,bgLightGreen,bgLightYellow,bgLightBlue,bgLightMagenta,bgLightCyan,bold,dim,italic,underline,inverse,hidden,strikethrough,reset,stripColors,supportsColor};
|
package/dist/debounce.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function debounce(fn,wait=0,options={}){const{leading
|
|
1
|
+
export function debounce(fn,wait=0,options={}){const{leading=false,trailing=true}=options;let timeout=null;let lastArgs=null;let lastThis=null;let result;const invokeFunc=()=>{if(lastArgs){const args=lastArgs,receiver=lastThis;lastArgs=null;lastThis=null;result=fn.apply(receiver,args)}return result};const cancel=()=>{if(timeout){clearTimeout(timeout);timeout=null}lastArgs=null;lastThis=null};const flush=()=>{if(timeout){clearTimeout(timeout);timeout=null;return invokeFunc()}return result};const debounced=function(...args){lastArgs=args;lastThis=this;const shouldCallNow=leading&&!timeout;if(timeout){clearTimeout(timeout)}timeout=setTimeout(()=>{timeout=null;if(trailing&&lastArgs){invokeFunc()}else{lastArgs=null;lastThis=null}},wait);if(shouldCallNow){return invokeFunc()}return result};debounced.cancel=cancel;debounced.flush=flush;return debounced}export function throttle(fn,wait=0){let timeout=null;let lastRun;let lastArgs=null;let lastThis=null;let result;const invokeFunc=()=>{if(lastArgs){const args=lastArgs,receiver=lastThis;lastArgs=null;lastThis=null;lastRun=Date.now();result=fn.apply(receiver,args)}return result};const cancel=()=>{if(timeout){clearTimeout(timeout);timeout=null}lastArgs=null;lastThis=null;lastRun=undefined};const throttled=function(...args){lastArgs=args;lastThis=this;const now=Date.now();const timeSinceLastRun=lastRun===undefined?1/0:now-lastRun;if(timeSinceLastRun>=wait||timeSinceLastRun<0){if(timeout){clearTimeout(timeout);timeout=null}return invokeFunc()}else if(!timeout){timeout=setTimeout(()=>{timeout=null;invokeFunc()},wait-timeSinceLastRun)}return result};throttled.cancel=cancel;return throttled}export function delay(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}
|
package/dist/detect.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
export function detectIndent(text){const lines=text.split(`
|
|
2
|
-
`)
|
|
3
|
-
`))return`\r
|
|
4
|
-
|
|
5
|
-
`))return`
|
|
6
|
-
|
|
2
|
+
`);const indents=[];for(const line of lines){if(!line.trim())continue;const match=line.match(/^(\s+)/);if(match&&match[1]!==undefined){indents.push(match[1])}}if(indents.length===0){return{amount:0,type:null,indent:""}}const indentCounts=new Map;for(const indent of indents){indentCounts.set(indent,(indentCounts.get(indent)||0)+1)}let mostCommon="";let maxCount=0;for(const[indent,count]of indentCounts){if(count>maxCount){maxCount=count;mostCommon=indent}}if(mostCommon.includes("\t")){return{amount:mostCommon.length,type:"tab",indent:mostCommon}}const spaceCount=mostCommon.length;return{amount:spaceCount,type:"space",indent:mostCommon}}export function detectNewline(text){if(!text)return null;if(text.includes(`\r
|
|
3
|
+
`)){return`\r
|
|
4
|
+
`}if(text.includes(`
|
|
5
|
+
`)){return`
|
|
6
|
+
`}if(text.includes("\r")){return"\r"}return null}export function detectNewlineGraceful(text,fallback=`
|
|
7
7
|
`){return detectNewline(text)||fallback}export function normalizeNewlines(text,newline=`
|
|
8
|
-
`){return text.replace(/\r\n|\r|\n/g,newline)}export function countNewlines(text){const crlf=(text.match(/\r\n/g)||[]).length
|
|
8
|
+
`){return text.replace(/\r\n|\r|\n/g,newline)}export function countNewlines(text){const crlf=(text.match(/\r\n/g)||[]).length;const cr=(text.match(/\r(?!\n)/g)||[]).length;const lf=(text.match(/(?<!\r)\n/g)||[]).length;return{crlf,lf,cr,total:crlf+lf+cr}}
|
package/dist/equal.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getTypeName}from"@stacksjs/types";function unorderedMatch(a,b,matches){if(a.length!==b.length)return
|
|
1
|
+
import{getTypeName}from"@stacksjs/types";function unorderedMatch(a,b,matches){if(a.length!==b.length)return false;const consumed=Array.from({length:b.length},()=>false);for(const item of a){let found=false;for(let i=0;i<b.length;i++){if(consumed[i])continue;if(matches(item,b[i])){consumed[i]=true;found=true;break}}if(!found)return false}return true}function mapsEqual(a,b,seen){if(a.size!==b.size)return false;let sameKeys=true;for(const key of a.keys()){if(!b.has(key)){sameKeys=false;break}}if(sameKeys){for(const[key,value]of a){if(!equalValues(value,b.get(key),seen))return false}return true}return unorderedMatch([...a.entries()],[...b.entries()],(x,y)=>equalValues(x[0],y[0],seen)&&equalValues(x[1],y[1],seen))}export function isDeepEqual(value1,value2,seen){if(seen&&value1&&typeof value1==="object"&&seen.get(value1)===value2)return true;const equal=equalValues(value1,value2,new WeakMap);if(equal&&value1&&typeof value1==="object"&&value2&&typeof value2==="object")seen?.set(value1,value2);return equal}function equalValues(value1,value2,seen){if(value1===value2)return true;if(typeof value1==="number"&&typeof value2==="number"&&Number.isNaN(value1)&&Number.isNaN(value2))return true;const type1=getTypeName(value1);const type2=getTypeName(value2);if(type1!==type2)return false;if(value1&&typeof value1==="object"&&value2&&typeof value2==="object"){let pairs=seen.get(value1);if(pairs?.has(value2))return true;if(!pairs)seen.set(value1,pairs=new WeakSet);pairs.add(value2);try{return compareValues(value1,value2,type1,seen)}finally{pairs.delete(value2)}}return Object.is(value1,value2)}function compareValues(value1,value2,type1,seen){if(type1==="date"){return Object.is(value1.getTime(),value2.getTime())}if(type1==="regexp"){return value1.source===value2.source&&value1.flags===value2.flags}if(type1==="map")return mapsEqual(value1,value2,seen);if(type1==="set"){return unorderedMatch([...value1],[...value2],(x,y)=>equalValues(x,y,seen))}if(ArrayBuffer.isView(value1)&&ArrayBuffer.isView(value2)){const bytes1=new Uint8Array(value1.buffer,value1.byteOffset,value1.byteLength);const bytes2=new Uint8Array(value2.buffer,value2.byteOffset,value2.byteLength);if(bytes1.length!==bytes2.length)return false;return bytes1.every((byte,i)=>byte===bytes2[i])}if(type1==="arraybuffer"){const bytes1=new Uint8Array(value1);const bytes2=new Uint8Array(value2);if(bytes1.length!==bytes2.length)return false;return bytes1.every((byte,i)=>byte===bytes2[i])}if(Array.isArray(value1)&&Array.isArray(value2)){if(value1.length!==value2.length)return false;for(let index=0;index<value1.length;index++){const own=Object.hasOwn(value1,index);if(own!==Object.hasOwn(value2,index))return false;if(own&&!equalValues(value1[index],value2[index],seen))return false}return true}if(type1==="object"){const object1=value1;const object2=value2;const keyArr=Object.keys(object1);if(keyArr.length!==Object.keys(object2).length)return false;return keyArr.every((key)=>Object.prototype.propertyIsEnumerable.call(object2,key)&&equalValues(object1[key],object2[key],seen))}return Object.is(value1,value2)}
|
package/dist/errors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function getErrorMessage(e){const message=errorProperty(e,"message");if(typeof message==="string")return message;if(e==null)return"Unknown error";try{return String(e)}catch{return"Unknown error"}}function errorProperty(value,key){if(!value||typeof value!=="object"&&typeof value!=="function")return;try{return Reflect.get(value,key)}catch{return}}export function getErrorStack(e){const stack=errorProperty(e,"stack");return typeof stack==="string"?stack:
|
|
1
|
+
export function getErrorMessage(e){const message=errorProperty(e,"message");if(typeof message==="string")return message;if(e==null)return"Unknown error";try{return String(e)}catch{return"Unknown error"}}function errorProperty(value,key){if(!value||typeof value!=="object"&&typeof value!=="function")return;try{return Reflect.get(value,key)}catch{return}}export function getErrorStack(e){const stack=errorProperty(e,"stack");return typeof stack==="string"?stack:undefined}export function getErrorCode(e){const code=errorProperty(e,"code");return typeof code==="string"?code:undefined}export function getErrorStatusCode(e){for(const key of["statusCode","status"]){const status=errorProperty(e,key);if(typeof status==="number"&&Number.isFinite(status))return status}return}export function toError(e){try{if(e instanceof Error)return e}catch{}return new Error(getErrorMessage(e),{cause:e})}
|
package/dist/find.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import fs from"node:fs/promises";import os from"node:os";import path from"node:path";import{italic}from"@stacksjs/cli";import{log}from"@stacksjs/logging";const targetFileName="buddy"
|
|
1
|
+
import fs from"node:fs/promises";import os from"node:os";import path from"node:path";import{italic}from"@stacksjs/cli";import{log}from"@stacksjs/logging";const targetFileName="buddy";const alwaysExcludePatterns=["node_modules","dist","vendor","storage/framework",/.*out.*/,/.*\/\..*/];const homeOnlyExcludePatterns=[`${os.homedir()}/Documents`,`${os.homedir()}/Pictures`,`${os.homedir()}/Library`,`${os.homedir()}/.Trash`];const MAX_CONCURRENT_FS_READS=32;let activeFsReads=0;const fsReadQueue=[];async function withFsReadSlot(operation){if(activeFsReads>=MAX_CONCURRENT_FS_READS)await new Promise((resolve)=>fsReadQueue.push(resolve));activeFsReads++;try{return await operation()}finally{activeFsReads--;fsReadQueue.shift()?.()}}export async function findStacksProjects(dir,options){const dirWasExplicit=!!dir;dir=dir||os.homedir();const excludePatterns=dirWasExplicit?alwaysExcludePatterns:[...alwaysExcludePatterns,...homeOnlyExcludePatterns];if(!options?.quiet){log.info(`Searching for Stacks projects in: ${italic(dir)}`);log.info(`This may take a few moments...`);console.log("");console.log(italic(" Please note, while Stacks is searching for projects on your machine,"));console.log(italic(" you may be asked for permissions to scan certain directories."));console.log("");log.debug(`Excluding directories: ${excludePatterns.join(", ")}`)}const foundProjects=await searchDirectory(dir,excludePatterns);if(!foundProjects)throw new Error("No Stacks projects found");return foundProjects}async function searchDirectory(directory,excludePatterns){const isExcluded=excludePatterns.some((pattern)=>typeof pattern==="string"?directory.includes(pattern):pattern.test(directory));if(isExcluded)return[];let items;try{items=await withFsReadSlot(()=>fs.readdir(directory,{withFileTypes:true}))}catch(error){console.error(`Error reading directory ${directory}:`,error);return[]}const buddyFileFound=items.some((item)=>item.isFile()&&item.name===targetFileName);const storageDirFound=items.some((item)=>item.isDirectory()&&item.name==="storage")&&await withFsReadSlot(()=>fs.access(path.join(directory,"storage/framework/core/buddy"))).then(()=>true).catch(()=>false);const children=items.filter((item)=>item.isDirectory()&&item.name!=="storage").map((item)=>searchDirectory(path.join(directory,item.name),excludePatterns));const nested=(await Promise.all(children)).flat();if(buddyFileFound&&storageDirFound)nested.push(directory);return nested}
|
package/dist/git.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execSync}from"node:child_process";import{handleError}from"@stacksjs/error-handling";export function isGitClean(){try{execSync("git diff-index --quiet HEAD --");return
|
|
1
|
+
import{execSync}from"node:child_process";import{handleError}from"@stacksjs/error-handling";export function isGitClean(){try{execSync("git diff-index --quiet HEAD --");return true}catch(error){handleError(error);return false}}
|
package/dist/hash.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{path}from"@stacksjs/path";import{hashPaths}from"@stacksjs/storage";export function originRequestFunctionHash(){try{return hashPaths(path.cloudPath("src/edge"))}catch(error){log.error("Are we in a Docker container? Failed to hash paths. Error below:");log.error(error);return}}export function websiteSourceHash(){const docsSrc=[path.projectPath("docs"),path.frameworkPath("docs/dist")]
|
|
1
|
+
import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{path}from"@stacksjs/path";import{hashPaths}from"@stacksjs/storage";export function originRequestFunctionHash(){try{return hashPaths(path.cloudPath("src/edge"))}catch(error){log.error("Are we in a Docker container? Failed to hash paths. Error below:");log.error(error);return}}export function websiteSourceHash(){const docsSrc=[path.projectPath("docs"),path.frameworkPath("docs/dist")];const websiteSrc=[path.projectPath("resources/views"),path.projectPath("resources/assets"),path.projectPath("resources/lang"),path.projectPath("resources/functions"),path.projectPath("resources/components"),path.projectPath("resources/modules"),path.projectPath("resources/stores"),path.frameworkPath("views/web")];return config.app.docMode===true?hashPaths(docsSrc):hashPaths(websiteSrc)}export function docsSourceHash(){const docsSrc=[path.projectPath("docs"),path.frameworkPath("docs/dist")];return hashPaths(docsSrc)}
|
package/dist/helpers.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import process from"node:process";import{runCommand}from"@stacksjs/cli";import{app,ui}from"@stacksjs/config";import{err,handleError}from"@stacksjs/error-handling";import{frameworkPath,projectPath}from"@stacksjs/path";import{fs,readJsonFile,readPackageJson,readTextFile,writeTextFile}from"@stacksjs/storage";export async function packageManager(){const{packageManager}=await readPackageJson(frameworkPath("package.json"));return packageManager??""}export async function ensureProjectIsInitialized(){if(!isStacksProject()){console.error("This command must be run inside a Stacks project; create one with: panx buddy new my-app");process.exit(1)}if(await isAppKeySet())return
|
|
2
|
-
`).find((line)=>line.startsWith("APP_KEY="));return!!(appKey&&appKey.length>16)}catch{return
|
|
1
|
+
import process from"node:process";import{runCommand}from"@stacksjs/cli";import{app,ui}from"@stacksjs/config";import{err,handleError}from"@stacksjs/error-handling";import{frameworkPath,projectPath}from"@stacksjs/path";import{fs,readJsonFile,readPackageJson,readTextFile,writeTextFile}from"@stacksjs/storage";export async function packageManager(){const{packageManager}=await readPackageJson(frameworkPath("package.json"));return packageManager??""}export async function ensureProjectIsInitialized(){if(!isStacksProject()){console.error("This command must be run inside a Stacks project; create one with: panx buddy new my-app");process.exit(1)}if(await isAppKeySet())return true;if(fs.existsSync(projectPath(".env")))return false;if(fs.existsSync(projectPath(".env.example")))fs.copyFileSync(projectPath(".env.example"),projectPath(".env"));else console.error("no .env.example file found");return await isAppKeySet()}export function isStacksProject(){if(!fs.existsSync(projectPath("package.json")))return false;return fs.existsSync(projectPath("config"))||fs.existsSync(projectPath("storage/framework/core"))}export async function installIfVersionMismatch(){}export async function frameworkVersion(){return(await readPackageJson(frameworkPath("package.json"))).version??""}export async function isAppKeySet(){const fromEnvironment=String(process.env.APP_KEY??"").trim();if(fromEnvironment.length>16)return true;try{const env=await readTextFile(".env",projectPath());const lines=env.data.split(`
|
|
2
|
+
`);const appKey=lines.find((line)=>line.startsWith("APP_KEY="));return!!(appKey&&appKey.length>16)}catch{return false}}export function determineResetPreset(preset){if(preset===undefined&&ui.reset)preset=ui.reset;if(preset===null)return[];const selectedPreset=preset??"tailwind";const resetImports={tailwind:'import { tailwindPreflight as reset } from "@stacksjs/ts-css/engine"',preflight:'import { tailwindPreflight as reset } from "@stacksjs/ts-css/engine"',forms:'import { tailwindFormsPreflight as reset } from "@stacksjs/ts-css/engine"'};const resetImport=resetImports[selectedPreset];return resetImport?[resetImport]:[]}export function isManifest(obj){if(!obj||typeof obj!=="object")return false;const candidate=obj;return isOptionalString(candidate.name)&&isOptionalString(candidate.version)&&isOptionalString(candidate.description)}export function isOptionalString(value){const type=typeof value;return value===null||type==="undefined"||type==="string"}export async function setEnvValue(key,value){const file=await readTextFile(projectPath(".env"));const escapedKey=key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const keyPattern=new RegExp(`^${escapedKey}=.*$`,"m");const nextValue=`${key}=${value}`;const data=keyPattern.test(file.data)?file.data.replace(keyPattern,()=>nextValue):`${file.data}${file.data.endsWith(`
|
|
3
3
|
`)?"":`
|
|
4
4
|
`}${nextValue}
|
|
5
|
-
`;await writeTextFile({path:projectPath(".env"),data})}export async function runNpmScript(script,options){const{data:manifest}=await readJsonFile("package.json",frameworkPath());if(isManifest(manifest)&&hasScript(manifest,script))return await runCommand(`bun run ${script}`,options);return err(handleError(`The ${script} script does not exist in the package.json file.`))}export function hasScript(manifest,script){const scripts=manifest.scripts;if(scripts&&typeof scripts==="object")return Boolean(scripts[script]);return
|
|
5
|
+
`;await writeTextFile({path:projectPath(".env"),data})}export async function runNpmScript(script,options){const{data:manifest}=await readJsonFile("package.json",frameworkPath());if(isManifest(manifest)&&hasScript(manifest,script))return await runCommand(`bun run ${script}`,options);return err(handleError(`The ${script} script does not exist in the package.json file.`))}export function hasScript(manifest,script){const scripts=manifest.scripts;if(scripts&&typeof scripts==="object")return Boolean(scripts[script]);return false}export function parseYaml(content){return Bun.YAML.parse(content)}export function determineDebugLevel(options){if(options?.verbose===true)return true;return app.debug===true}export function isIpv6(address){return address.family==="IPv6"||address.family===6}export function dumpYaml(content){const yaml=Bun.YAML;if(typeof yaml.stringify==="function")return yaml.stringify(content);return JSON.stringify(content,null,2)}export function loadYaml(content){return Bun.YAML.parse(content)}
|
package/dist/macroable.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const registries=new WeakMap;function parentOf(target){const parent=Object.getPrototypeOf(target);return typeof parent==="function"&&parent.prototype?parent:
|
|
1
|
+
const registries=new WeakMap;function parentOf(target){const parent=Object.getPrototypeOf(target);return typeof parent==="function"&&parent.prototype?parent:undefined}function registration(target,name){for(let current=target;current;current=parentOf(current)){const own=registries.get(current)?.get(name);if(own)return own;if(Object.hasOwn(current.prototype,name))return}}export class Macroable{static macro(name,fn,replace=false){if(name==="constructor")throw new Error("The constructor cannot be a macro");if(typeof fn!=="function")throw new TypeError("A macro must be a function");if(!replace&&name in this.prototype){if(registration(this,name))throw new Error(`Macro "${name}" is already registered`);throw new Error(`Method "${name}" already exists; pass replace to override it`)}const records=registries.get(this)??new Map;const previous=records.get(name);const original=previous?previous.original:Object.getOwnPropertyDescriptor(this.prototype,name);Object.defineProperty(this.prototype,name,{value:fn,writable:true,configurable:true,enumerable:false});records.set(name,{fn,original});registries.set(this,records)}static mixin(obj,replace=true){for(const name of Object.getOwnPropertyNames(obj)){if(name==="constructor"||!replace&&name in this.prototype)continue;const descriptor=Object.getOwnPropertyDescriptor(obj,name);if(descriptor&&typeof descriptor.value==="function")this.macro(name,descriptor.value,replace)}}static hasMacro(name){return registration(this,name)!==undefined}static flushMacros(){const records=registries.get(this);if(!records)return;for(const[name,record]of records){if(record.original)Object.defineProperty(this.prototype,name,record.original);else if(!Reflect.deleteProperty(this.prototype,name))throw new TypeError(`Cannot remove macro "${name}"`);records.delete(name)}registries.delete(this)}static getMacros(){const names=new Set;for(let current=this;current;current=parentOf(current)){for(const name of registries.get(current)?.keys()??[])names.add(name)}return[...names].filter((name)=>registration(this,name)!==undefined)}callMacro(name,...args){const found=registration(this.constructor,name);if(!found)throw new Error(`Macro "${name}" is not registered`);return found.fn.apply(this,args)}}export function createMacroable(BaseClass=class{}){return macroable(class extends BaseClass{})}export function macroable(target){const decorated=target;for(const name of["macro","mixin","hasMacro","flushMacros","getMacros"]){Object.defineProperty(decorated,name,{value:Macroable[name],writable:true,configurable:true})}return decorated}
|
package/dist/markdown.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export function markdownTable(table,options={}){const{align=[],padding
|
|
2
|
-
`)}function buildRow(cells,columnWidths,padding,delimiter,delimiterStart,delimiterEnd){const paddedCells=columnWidths.map((width,index)=>{
|
|
1
|
+
export function markdownTable(table,options={}){const{align=[],padding=true,delimiter="|",delimiterStart=true,delimiterEnd=true,alignDelimiter="-",escapeCells=true}=options;if(!table||table.length===0){return""}const normalized=table.map((row)=>row.map((cell)=>{if(cell===null||cell===undefined)return"";const text=String(cell);return escapeCells?text.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\r\n|\r|\n/g,"<br>"):text}));const columnCount=normalized.reduce((max,row)=>Math.max(max,row.length),0);const columnWidths=Array.from({length:columnCount}).fill(0);for(const row of normalized){for(let i=0;i<row.length;i++){const cellLength=row[i]?.length??0;if(cellLength>(columnWidths[i]??0)){columnWidths[i]=cellLength}}}const rows=[];if(normalized.length>0){const header=normalized[0]??[];rows.push(buildRow(header,columnWidths,padding,delimiter,delimiterStart,delimiterEnd));const separatorCells=columnWidths.map((width,index)=>{const alignment=normalizeAlignment(align[index]);return buildSeparator(width,alignment,alignDelimiter)});rows.push(buildRow(separatorCells,columnWidths,padding,delimiter,delimiterStart,delimiterEnd));for(let i=1;i<normalized.length;i++){const dataRow=normalized[i]??[];rows.push(buildRow(dataRow,columnWidths,padding,delimiter,delimiterStart,delimiterEnd))}}return rows.join(`
|
|
2
|
+
`)}function buildRow(cells,columnWidths,padding,delimiter,delimiterStart,delimiterEnd){const paddedCells=columnWidths.map((width,index)=>{const cell=cells[index]??"";return cell.padEnd(width," ")});const space=padding?" ":"";let row=paddedCells.map((cell)=>`${space}${cell}${space}`).join(delimiter);if(delimiterStart)row=delimiter+row;if(delimiterEnd)row=row+delimiter;return row}function buildSeparator(width,alignment,char){const minWidth=alignment==="center"?3:alignment?2:1;if(width<minWidth){width=minWidth}let separator=char.repeat(width);if(alignment==="left"){separator=`:${separator.slice(1)}`}else if(alignment==="right"){separator=separator.slice(0,-1)+":"}else if(alignment==="center"){separator=`:${separator.slice(2)}:`}return separator}function normalizeAlignment(align){if(!align)return null;switch(align){case"l":case"left":return"left";case"c":case"center":return"center";case"r":case"right":return"right";default:return null}}export function markdownTableFromObjects(objects,options={}){if(!objects||objects.length===0){return""}const keys=Array.from(new Set(objects.flatMap((obj)=>Object.keys(obj))));const table=[keys,...objects.map((obj)=>keys.map((key)=>obj[key]))];return markdownTable(table,options)}export{markdownTable as default};
|
package/dist/merge.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function merge(...objects){const result={};for(const obj of objects){if(!obj||typeof obj!=="object")continue;for(const key of Object.keys(obj)){if(key==="__proto__")continue;const value=obj[key]
|
|
1
|
+
export function merge(...objects){const result={};for(const obj of objects){if(!obj||typeof obj!=="object")continue;for(const key of Object.keys(obj)){if(key==="__proto__")continue;const value=obj[key];const existing=Object.hasOwn(result,key)?result[key]:undefined;if(value===undefined)continue;if(Array.isArray(value)){result[key]=Array.isArray(existing)?[...existing,...value]:[...value]}else if(isPlainObject(value)){result[key]=merge(isPlainObject(existing)?existing:{},value)}else{result[key]=value}}}return result}export function createMerger(defaults){return(...objects)=>{return merge(defaults,...objects)}}export function mergeDefaults(obj,...defaults){return merge({},...defaults,obj)}function isPlainObject(value){if(!value||typeof value!=="object")return false;const prototype=Object.getPrototypeOf(value);if(prototype===null||prototype===Object.prototype)return true;if(Object.getPrototypeOf(prototype)!==null)return false;const constructor=Object.getOwnPropertyDescriptor(prototype,"constructor")?.value;return typeof constructor==="function"&&Function.prototype.toString.call(constructor)===Function.prototype.toString.call(Object)}export const defu=mergeDefaults;export const defuArrayFn=merge;export{merge as default};
|
package/dist/observer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function isResizeObserverSupported(){return typeof window
|
|
1
|
+
export function isResizeObserverSupported(){return typeof window!=="undefined"&&typeof window.ResizeObserver==="function"}export function getResizeObserver(){if(isResizeObserverSupported()){return window.ResizeObserver}return class ResizeObserverPolyfill{callback;observedElements=new Map;pending=null;scheduling=false;constructor(callback){this.callback=callback}observe(target){if(this.observedElements.has(target))return;this.observedElements.set(target,undefined);this.scheduleCheck()}unobserve(target){this.observedElements.delete(target);if(this.observedElements.size===0)this.cancelCheck()}disconnect(){this.observedElements.clear();this.cancelCheck()}cancelCheck(){const pending=this.pending;this.pending=null;pending?.cancel?.()}scheduleCheck(){if(this.pending||this.scheduling||this.observedElements.size===0)return;const pending={};this.pending=pending;this.scheduling=true;const run=()=>{if(this.pending!==pending)return;this.pending=null;try{this.check()}finally{this.scheduleCheck()}};try{if(typeof requestAnimationFrame==="function"){const id=requestAnimationFrame(run);pending.cancel=()=>cancelAnimationFrame(id)}else{const id=setTimeout(run,16);pending.cancel=()=>clearTimeout(id)}}catch(error){if(this.pending===pending)this.pending=null;throw error}finally{this.scheduling=false}}check(){const entries=[];for(const[element,previous]of this.observedElements){const rect=element.getBoundingClientRect();if(previous&&previous.width===rect.width&&previous.height===rect.height)continue;this.observedElements.set(element,{width:rect.width,height:rect.height});entries.push({target:element,contentRect:rect,borderBoxSize:[{inlineSize:rect.width,blockSize:rect.height}],contentBoxSize:[{inlineSize:rect.width,blockSize:rect.height}],devicePixelContentBoxSize:[{inlineSize:rect.width,blockSize:rect.height}]})}if(entries.length>0)this.callback(entries,this)}}}export function createResizeObserver(callback,target){const Observer=getResizeObserver();const observer=new Observer(callback);const targets=Array.isArray(target)?target:[target];for(const element of targets){observer.observe(element)}return()=>{observer.disconnect()}}export function observeElementSize(element,callback){return createResizeObserver((entries)=>{const entry=entries.find((e)=>e.target===element);if(entry){callback(entry)}},element)}export const ResizeObserver=getResizeObserver();export default ResizeObserver;
|
package/dist/pipeline.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class Pipeline{passable;pipes=[];method="handle";static send(passable){const pipeline=new Pipeline;pipeline.passable=passable;return pipeline}through(pipes){this.pipes=[...pipes];return this}pipe(...pipes){this.pipes.push(...pipes);return this}via(method){this.method=method;return this}then(destination){
|
|
1
|
+
export class Pipeline{passable;pipes=[];method="handle";static send(passable){const pipeline=new Pipeline;pipeline.passable=passable;return pipeline}through(pipes){this.pipes=[...pipes];return this}pipe(...pipes){this.pipes.push(...pipes);return this}via(method){this.method=method;return this}then(destination){const pipeline=this.pipes.reduceRight((next,pipe)=>{return(passable)=>{if(typeof pipe==="function"){return pipe(passable,next)}const handler=pipe[this.method];if(typeof handler==="function"){return handler.call(pipe,passable,next)}return next(passable)}},destination);return pipeline(this.passable)}thenReturn(){return this.then((passable)=>passable)}}
|
package/dist/safe-json.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function safeJsonParse(text,defaultValue){if(typeof text!=="string"||text.length===0)return defaultValue;try{return JSON.parse(text)}catch{return defaultValue}}export function safeJsonParseResult(text){if(typeof text!=="string")return{ok
|
|
1
|
+
export function safeJsonParse(text,defaultValue){if(typeof text!=="string"||text.length===0)return defaultValue;try{return JSON.parse(text)}catch{return defaultValue}}export function safeJsonParseResult(text){if(typeof text!=="string")return{ok:false,reason:"not-string"};if(text.length===0)return{ok:false,reason:"empty"};try{return{ok:true,value:JSON.parse(text)}}catch(err){return{ok:false,reason:"malformed",error:err}}}export function safeJsonStringify(value,space){const ancestors=[];return JSON.stringify(value,function(_key,v){if(typeof v==="bigint")return v.toString();if(v&&typeof v==="object"){while(ancestors.length&&ancestors.at(-1)!==this)ancestors.pop();if(ancestors.includes(v))return"[Circular]";ancestors.push(v)}return v},space)}
|
package/dist/size.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{stat}from"node:fs/promises";import{join}from"node:path";import{formatBytes}from"./bytes";export async function getFileSize(filePath){try{
|
|
2
|
-
`).filter(Boolean)){const name=entry.replace(dir,"").replace(/^\//,"");files.push({name,path:entry})}}catch{}return files}export function estimateGzipSize(size){return Math.floor(size*0.3)}export function estimateBrotliSize(size){return Math.floor(size*0.25)}export function formatExportSizes(result){if(result.exports.length===0)return"No exports found"
|
|
1
|
+
import{stat}from"node:fs/promises";import{join}from"node:path";import{formatBytes}from"./bytes";export async function getFileSize(filePath){try{const stats=await stat(filePath);return stats.size}catch{return 0}}export async function getExportsSize(distPath){const exports=[];let totalSize=0;try{const files=await getAllJsFiles(distPath);for(const file of files){const size=await getFileSize(file.path);totalSize+=size;exports.push({name:file.name,size,readable:formatBytes(size)})}}catch(error){}return{totalSize,totalReadable:formatBytes(totalSize),exports:exports.sort((a,b)=>b.size-a.size)}}async function getAllJsFiles(dir){const files=[];try{const entries=await Bun.$.throws(false)`find ${dir} -type f \\( -name "*.js" -o -name "*.mjs" -o -name "*.cjs" \\)`.text();for(const entry of entries.split(`
|
|
2
|
+
`).filter(Boolean)){const name=entry.replace(dir,"").replace(/^\//,"");files.push({name,path:entry})}}catch{}return files}export function estimateGzipSize(size){return Math.floor(size*0.3)}export function estimateBrotliSize(size){return Math.floor(size*0.25)}export function formatExportSizes(result){if(result.exports.length===0){return"No exports found"}const lines=["Export Sizes:",""];const maxNameLength=Math.max(...result.exports.map((e)=>e.name.length));for(const exp of result.exports){const name=exp.name.padEnd(maxNameLength," ");lines.push(` ${name} ${exp.readable}`)}lines.push("");lines.push(`Total: ${result.totalReadable}`);lines.push(`Estimated gzipped: ${formatBytes(estimateGzipSize(result.totalSize))}`);lines.push(`Estimated brotli: ${formatBytes(estimateBrotliSize(result.totalSize))}`);return lines.join(`
|
|
3
3
|
`)}export{getExportsSize as default};
|
package/dist/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var __dirname="";import{resolve}from"@stacksjs/path";import{fs}from"@stacksjs/storage";import{kebabCase}from"@stacksjs/strings";const ignore=["readme-md"];export const components=fs.readdirSync(resolve(__dirname,"./resources/components")).map((item)=>kebabCase(item.replace(/\.stx/g,""))).filter((item)=>!ignore.includes(item))
|
|
1
|
+
var __dirname="";import{resolve}from"@stacksjs/path";import{fs}from"@stacksjs/storage";import{kebabCase}from"@stacksjs/strings";const ignore=["readme-md"];export const components=fs.readdirSync(resolve(__dirname,"./resources/components")).map((item)=>kebabCase(item.replace(/\.stx/g,""))).filter((item)=>!ignore.includes(item));export const functions=fs.readdirSync(resolve(__dirname,"./resources/functions")).map((item)=>kebabCase(item.replace(/.ts/g,""))).filter((item)=>!ignore.includes(item));
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/utils",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.519",
|
|
6
6
|
"description": "The Stacks helper functions.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -62,20 +62,20 @@
|
|
|
62
62
|
"size": "bun scripts/export-size.ts"
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@stacksjs/browser": "0.75.
|
|
66
|
-
"@stacksjs/cli": "0.75.
|
|
67
|
-
"@stacksjs/config": "0.75.
|
|
68
|
-
"@stacksjs/enums": "0.75.
|
|
69
|
-
"@stacksjs/error-handling": "0.75.
|
|
70
|
-
"@stacksjs/logging": "0.75.
|
|
71
|
-
"@stacksjs/path": "0.75.
|
|
72
|
-
"@stacksjs/storage": "0.75.
|
|
73
|
-
"@stacksjs/strings": "0.75.
|
|
74
|
-
"@stacksjs/types": "0.75.
|
|
65
|
+
"@stacksjs/browser": "0.75.519",
|
|
66
|
+
"@stacksjs/cli": "0.75.519",
|
|
67
|
+
"@stacksjs/config": "0.75.519",
|
|
68
|
+
"@stacksjs/enums": "0.75.519",
|
|
69
|
+
"@stacksjs/error-handling": "0.75.519",
|
|
70
|
+
"@stacksjs/logging": "0.75.519",
|
|
71
|
+
"@stacksjs/path": "0.75.519",
|
|
72
|
+
"@stacksjs/storage": "0.75.519",
|
|
73
|
+
"@stacksjs/strings": "0.75.519",
|
|
74
|
+
"@stacksjs/types": "0.75.519"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
|
-
"@stacksjs/arrays": "0.75.
|
|
78
|
-
"@stacksjs/lint": "0.75.
|
|
77
|
+
"@stacksjs/arrays": "0.75.519",
|
|
78
|
+
"@stacksjs/lint": "0.75.519",
|
|
79
79
|
"better-dx": "^0.2.24",
|
|
80
80
|
"filesize": "^11.0.25",
|
|
81
81
|
"markdown-table": "^3.0.4"
|