eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
1 lines • 1.3 kB
JavaScript
const ENCODING=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,TIME_MAX=2**48-1,ULID_LENGTH=26;function createUlidFactory(){let e=-1,t=new Uint8Array(10);return function(){let n=Date.now();if(!Number.isInteger(n)||n<0||n>TIME_MAX)throw Error(`Cannot mint a ULID: timestamp must be an integer from 0 to ${TIME_MAX}.`);if(n>e)e=n,randomFill(t);else if(!incrementRandom(t)){if(e===TIME_MAX)throw Error(`Cannot mint a ULID: random component overflowed at the maximum timestamp.`);e+=1,randomFill(t)}return`${encodeTime(e)}${encodeRandom(t)}`}}const createUlid=createUlidFactory();function isUlid(e){if(e.length!==26||ENCODING.indexOf(e[0]??``)>7)return!1;for(let t of e)if(!ENCODING.includes(t))return!1;return!0}function randomFill(e){let t=globalThis.crypto;if(typeof t?.getRandomValues!=`function`)throw Error(`Cannot mint a ULID: globalThis.crypto.getRandomValues is unavailable.`);t.getRandomValues(e)}function encodeTime(e){let t=e,n=``;for(let e=0;e<10;e+=1)n=ENCODING[t%32]+n,t=Math.floor(t/32);return n}function encodeRandom(e){let t=0,n=0,r=``;for(let i of e){for(t=t<<8|i,n+=8;n>=5;)n-=5,r+=ENCODING[t>>>n&31];t&=(1<<n)-1}return r}function incrementRandom(e){for(let t=e.length-1;t>=0;--t){let n=e[t]??0;if(n<255)return e[t]=n+1,e.fill(0,t+1),!0}return!1}export{ULID_LENGTH,createUlid,createUlidFactory,isUlid};