palbase 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +3 -0
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/2YUVLZLK.js +87 -0
- package/dist/chunks/{K3C2IEDS.js → 4K4MKD2J.js} +2 -2
- package/dist/chunks/{HDX6YUAB.js → 4MOCDBZP.js} +1 -1
- package/dist/chunks/{I3JNX6MZ.js → 4UPL27ED.js} +1 -1
- package/dist/chunks/6FQGUDBD.js +2 -0
- package/dist/chunks/{ZFPDYRRY.js → FVIHTHHV.js} +2 -2
- package/dist/chunks/{6OPBXB7Z.js → INXQWVHU.js} +2 -2
- package/dist/chunks/{UTRQWCMD.js → JF7KZUPL.js} +2 -2
- package/dist/chunks/{5W6XJM46.js → L6GKX3XI.js} +2 -2
- package/dist/chunks/{ECUYQ73P.js → MJPUCGXY.js} +2 -2
- package/dist/chunks/{NIJHTHNF.js → NTMO2LFH.js} +2 -2
- package/dist/chunks/{JEJ5CFTK.js → TV7W53F2.js} +2 -2
- package/dist/chunks/{TL4H6V3P.js → VTNEPJRV.js} +1 -1
- package/dist/chunks/{KRBVYYME.js → XNRYSI7A.js} +1 -1
- package/dist/chunks/{7LOMYBLN.js → XOGEEZNP.js} +2 -2
- package/dist/cli.js +84 -81
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +3 -3
- package/types/internal/src/modules/ai.d.ts +811 -0
- package/types/internal/src/modules/purchases.d.ts +1601 -294
- package/types/internal/src/modules/storage.d.ts +1 -1
- package/types/web/src/client.d.ts +6 -0
- package/types/web/src/index.d.ts +1 -0
- package/types/web/src/paywall/assets.d.ts +51 -0
- package/types/web/src/paywall/attributes.d.ts +13 -0
- package/types/web/src/paywall/index.d.ts +4 -2
- package/types/web/src/paywall/placement.d.ts +21 -7
- package/types/web/src/paywall/render.d.ts +56 -17
- package/types/web/src/paywall/resolve.d.ts +150 -115
- package/types/web/src/purchases.d.ts +23 -4
- package/dist/chunks/AN5LCF5K.js +0 -55
- package/dist/chunks/HVC2C35F.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import"./
|
|
1
|
+
/*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"./VTNEPJRV.js";import{realpathSync as Ve}from"node:fs";import{resolve as ue}from"node:path";import wt from"typescript";import{existsSync as Se,readFileSync as Ue}from"node:fs";import{dirname as de,join as pe,relative as qe,resolve as ye,sep as ee}from"node:path";var h=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},W=new Set(["palbase/backend","@palbase/backend","palgres"]),Je=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function Te(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new h(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}function he(e,t){Te(e);let n=pe(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(Se(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new h(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
|
|
3
3
|
`)}`);let o=e.parseJsonConfigFileContent(i.config,e.sys,t);r=o.options,s=o.fileNames.filter(a=>/\.d\.[cm]?ts$/.test(a))}return{options:{...r,strictNullChecks:!0,noEmit:!0,skipLibCheck:!0},ambient:s}}function be(e,t,n,r,s){Te(e);let i=e.createProgram([...new Set(n)],r,s);return{ts:e,root:t,program:i,checker:i.getTypeChecker(),packages:new Map}}function $(e,t){let n=ye(t);return!n.includes(`${ee}node_modules${ee}`)&&!/\.d\.[cm]?ts$/.test(n)&&(n===e.root||n.startsWith(e.root+ee))}function v(e,t){return!!t&&$(e,t.getSourceFile().fileName)}function xe(e,t){let n=[],r=de(ye(t)),s=null;for(;;){let i=e.packages.get(r);if(i!==void 0){s=i;break}n.push(r);let o=pe(r,"package.json");if(Se(o)){try{let c=JSON.parse(Ue(o,"utf8")).name;s=typeof c=="string"?c:null}catch{s=null}break}let a=de(r);if(a===r)break;r=a}for(let i of n)e.packages.set(i,s);return s}function te(e,t){if($(e,t))return!1;let n=xe(e,t)??"";return n==="palbase"?/[\\/]types[\\/]backend[\\/]/.test(t):W.has(n)}function we(e,t){if($(e,t))return!1;let n=xe(e,t)??"";return W.has(n)||n==="palbase"||n.startsWith("@palbase/")}function O(e,t){let n=t.getSourceFile(),{line:r}=n.getLineAndCharacterOfPosition(t.getStart(n));return`${qe(e.root,n.fileName)}:${r+1}`}function T(e,t){for(;t;){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isNonNullExpression(t)||e.isAwaitExpression(t)||e.isTypeAssertionExpression(t)||e.isSatisfiesExpression(t)){t=t.expression;continue}return t}return t}function G(e,t){if(t&&t.flags&e.ts.SymbolFlags.Alias){let n=e.checker.getAliasedSymbol(t);if(n&&n.declarations)return n}return t}function D(e,t){let n=G(e,e.checker.getSymbolAtLocation(t));return n&&(n.valueDeclaration||n.declarations&&n.declarations[0])||null}function me(e,t){let n=t;for(;n&&!e.isImportDeclaration(n)&&!e.isExportDeclaration(n);)n=n.parent;return n&&(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier&&e.isStringLiteral(n.moduleSpecifier)?n.moduleSpecifier.text:null}function I(e,t){let n=e.ts;if(t=T(n,t),!t)return null;if(n.isPropertyAccessExpression(t)){let i=e.checker.getSymbolAtLocation(t.expression);return i&&(i.declarations||[]).some(a=>n.isNamespaceImport(a)&&W.has(me(n,a)??""))?t.name.text:null}if(!n.isIdentifier(t))return null;let r=e.checker.getSymbolAtLocation(t),s=new Set;for(;r&&!s.has(r);){s.add(r);for(let i of r.declarations||[]){if((n.isImportSpecifier(i)||n.isExportSpecifier(i))&&W.has(me(n,i)??""))return(i.propertyName||i.name).text;if(te(e,i.getSourceFile().fileName))return r.name}if(!(r.flags&n.SymbolFlags.Alias))return null;r=e.checker.getImmediateAliasedSymbol(r)}return null}function ge(e,t){let n=t.expression;return I(e,e.ts.isCallExpression(n)?n.expression:n)}function P(e,t){return t&&(e.isIdentifier(t)||e.isPrivateIdentifier(t)||e.isStringLiteral(t)||e.isNumericLiteral(t))?t.text:null}function Z(e,t){let n=e.ts,r=[];for(let s of t.statements){if(!n.isClassDeclaration(s)||!(n.getDecorators(s)||[]).some(o=>ge(e,o)==="Controller"))continue;if(!s.name)throw new h(`${O(e,s)} \u2014 a @Controller class needs a name \u2014 its routes' errors are bound to it by name`);let i=[];for(let o of s.members)if(!(!n.isMethodDeclaration(o)||!o.body)&&(n.getDecorators(o)||[]).some(a=>Je.has(ge(e,a)??""))){if(P(n,o.name)===null)throw new h(`${O(e,o)} \u2014 a route method needs a plain name; the contract reaches it by name`);i.push(o)}r.push({cls:s,routes:i})}return r}var Qe=new Set([2307,2580,2582,2583,2584,2591,2592,2593,2688,2867,2868,7016]);function We(e){let t=e.getSymbol();return t?.getName()==="Response"&&(t.declarations??[]).length>0&&(t.declarations??[]).every(n=>n.getSourceFile().isDeclarationFile)}function ke(e){let{ts:t,program:n,checker:r}=e,s=!1;return function(o,a){let c=o.getSourceFile().fileName,l=o.name.getText(o.getSourceFile()),u=f=>{throw new h(`${c} \u2014 ${a}.${l}: cannot infer a safe response contract (${f}). Use a named Zod return schema for this response; any/unknown is never emitted as a successful contract.`)};if(!s){let f=[];for(let S of n.getSourceFiles()){if(f.length>=5)break;S.isDeclarationFile||n.isSourceFileFromExternalLibrary(S)||/[\\/]node_modules[\\/]/.test(S.fileName)||we(e,S.fileName)||f.push(...n.getSemanticDiagnostics(S).filter(x=>x.category===t.DiagnosticCategory.Error&&!Qe.has(x.code)))}f.length&&u(t.formatDiagnostics(f.slice(0,5),{getCanonicalFileName:S=>S,getCurrentDirectory:()=>e.root,getNewLine:()=>`
|
|
4
4
|
`})),s=!0}let m=r.getSignatureFromDeclaration(o),g=m&&r.getAwaitedType(r.getReturnTypeOfSignature(m));if(!g)return u("unresolved return type");if(g.flags&(t.TypeFlags.Void|t.TypeFlags.Undefined))return{kind:"void"};if(We(g))return{kind:"raw"};let p=new Set,d=0;function C(f,S){if(++d>2e3||p.size>24)return u(`${S}: contract is too large; name its schema`);let x=f.flags,y=t.TypeFlags;if(x&(y.Any|y.Unknown|y.Never|y.TypeParameter))return u(`${S}: ${r.typeToString(f)}`);let fe=b=>{let w=r.getPropertiesOfType(b);if(!(b.flags&y.Object)||w.length!==1||w[0].name!=="__pg"||!(w[0].flags&t.SymbolFlags.Optional)||r.getIndexInfosOfType(b).length)return!1;let N=r.getTypeOfSymbolAtLocation(w[0],o);return(N.isUnion()?N.types:[N]).every(k=>k.flags&(y.StringLiteral|y.Undefined))};if(f.isIntersection()){let b=f.types.filter(w=>!fe(w));if(b.length===1&&b.length<f.types.length)return C(b[0],S)}if(fe(f))return u(`${S}: unknown PostgreSQL payload; name its response schema`);if(x&y.StringLiteral)return`z.literal(${JSON.stringify(f.value)})`;if(x&y.NumberLiteral)return`z.literal(${JSON.stringify(f.value)})`;if(x&y.BooleanLiteral)return`z.literal(${r.typeToString(f)==="true"})`;if(x&y.String)return"z.string()";if(x&y.TemplateLiteral){let b=f;if(b.types.length>8||!b.types.every(k=>k.flags&y.String))return u(`${S}: template literal requires an explicit schema`);let w=k=>k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N="^"+w(b.texts[0]);for(let k of b.texts.slice(1,-1))if(k){let Y=w(k);N+=`(?:(?!${Y})[\\s\\S])*${Y}`}return N+="[\\s\\S]*"+w(b.texts.at(-1))+"$(?![\\s\\S])",N.length>4096?u(`${S}: template pattern is too large`):`z.string().regex(new RegExp(${JSON.stringify(N)}))`}if(x&y.Number)return"z.number().finite()";if(x&y.Boolean)return"z.boolean()";if(x&y.Null)return"z.null()";if(x&y.Undefined)return"z.undefined()";if(p.has(f))return u(`${S}: recursive response`);p.add(f);try{if(f.isUnion()){if(f.types.length>32)return u(`${S}: union has more than 32 alternatives`);let A=f.types.some(M=>M.flags&y.Null),Q=f.types.some(M=>M.flags&y.Undefined),j=f.types.filter(M=>!(M.flags&(y.Null|y.Undefined)));return(j.length===0?A?"z.null()":"z.undefined()":j.length===1?C(j[0],S):`z.union([${j.map(M=>C(M,S)).join(",")}])`)+(A&&j.length?".nullable()":"")+(Q?".optional()":"")}if(r.isTupleType(f))return u(`${S}: tuple requires an explicit schema`);if(r.isArrayType(f)){let A=r.getTypeArguments(f)[0];return A.flags&y.Never?"z.array(z.string()).length(0)":`z.array(${C(A,`${S}[]`)})`}let b=f.isIntersection()&&f.types.every(A=>A.flags&y.Object);if(!(x&y.Object)&&!b||f.getCallSignatures().length||f.getConstructSignatures().length)return u(`${S}: non-JSON type ${r.typeToString(f)}`);let w=f.symbol?.declarations?.[0];if(w&&(t.isClassDeclaration(w)||t.isClassExpression(w)))return u(`${S}: class instance ${r.typeToString(f)}`);let N=r.getPropertiesOfType(f),k=r.getIndexInfosOfType(f);return k.length?k.length!==1||!(k[0].keyType.flags&y.String)||N.length?u(`${S}: mixed or non-string index signature`):`z.record(z.string(), ${C(k[0].type,`${S}.*`)})`:N.length?`z.object({${N.map(A=>{if(A.escapedName.toString().startsWith("__@"))return u(`${S}: symbol property`);let Q=A.getName(),j=C(r.getTypeOfSymbolAtLocation(A,o),`${S}.${Q}`);return`${JSON.stringify(Q)}:${j}${A.flags&t.SymbolFlags.Optional?".optional()":""}`}).join(",")}}).strict()`:u(`${S}: empty structural type`)}finally{p.delete(f)}}return{kind:"expression",expression:C(g,"return")}}}import{resolve as Ge}from"node:path";var ne=Symbol("not a named schema");function Ee(e,t,n,r){let{ts:s}=e,i=r.getSourceFile(),o=r.name.getText(i),a=d=>new h(`${i.fileName} \u2014 ${n}.${o}: ${d}`);function c(d){if(s.isTypeReferenceNode(d)&&d.typeName.getText(i)==="Promise"&&d.typeArguments&&d.typeArguments.length===1)return c(d.typeArguments[0]);if(d.kind===s.SyntaxKind.VoidKeyword||d.kind===s.SyntaxKind.UndefinedKeyword)return null;let C=s.isArrayTypeNode(d)?d.elementType:s.isTypeReferenceNode(d)&&d.typeName.getText(i)==="Array"&&d.typeArguments&&d.typeArguments.length===1?d.typeArguments[0]:void 0,f=l(C??d);return f===ne?f:{...f,isArray:C!==void 0}}function l(d){if(s.isTypeReferenceNode(d)&&!d.typeArguments)return{typeName:d.typeName.getText(i),node:d.typeName};if(s.isTypeReferenceNode(d)&&d.typeArguments&&d.typeArguments.length===1){let C=d.typeName.getText(i);if(/^(z\.)?(infer|output|input)$/.test(C)){let f=d.typeArguments[0];if(s.isTypeQueryNode(f))return{typeName:f.exprName.getText(i),node:f.exprName};if(s.isTypeReferenceNode(f)&&!f.typeArguments)return{typeName:f.typeName.getText(i),node:f.typeName}}}if(d.kind===s.SyntaxKind.VoidKeyword)throw a("void cannot appear inside an array/Promise here");return ne}let u=()=>t(r,n);if(!r.type)return u();let m=c(r.type);if(m===null)return{kind:"void"};if(m===ne)return u();let g=Ze(e,m.node);if(!g)return u();let p=He(e,g.symbol);return p?{kind:"schema",...p,array:m.isArray}:u()}function Ze(e,t){let{ts:n,checker:r}=e,s=r.getSymbolAtLocation(n.isQualifiedName(t)?t.right:t),i=G(e,s);if(!i||!(i.flags&n.SymbolFlags.Variable))return null;let o=i.valueDeclaration;return!o||!n.isVariableDeclaration(o)||!r.getTypeOfSymbolAtLocation(i,o).getProperty("~standard")?null:{symbol:i}}function He(e,t){let n=t.valueDeclaration?.getSourceFile();if(!n||n.isDeclarationFile)return null;let r=e.checker.getSymbolAtLocation(n);if(!r)return null;let s=e.checker.getExportsOfModule(r).filter(i=>G(e,i)===t).map(i=>i.name);return s.length===0?null:{file:Ge(n.fileName),exportName:s.includes(t.name)?t.name:s[0]}}var oe={BadRequest:{code:"bad_request",status:400,codeArg:null},Unauthorized:{code:"unauthorized",status:401,codeArg:1},Forbidden:{code:"forbidden",status:403,codeArg:1},NotFound:{code:"not_found",status:404,codeArg:1},Conflict:{code:"conflict",status:409,codeArg:1},UniqueViolation:{code:"unique_violation",status:409,codeArg:2},SerializationFailure:{code:"serialization_failure",status:409,codeArg:null},DeadlockDetected:{code:"deadlock_detected",status:409,codeArg:null},TooManyRequests:{code:"too_many_requests",status:429,codeArg:null}},Xe=new Set(["HttpError","PalError"]),Ye=[{member:"page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"$page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"NotFound",code:"not_found",status:404}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"updateScoped",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}}],et=new Map([["expectOne",0],["expectNone",0],["expectAtLeast",1],["expectAtMost",1]]);function Le(e){let t={...e,ids:new WeakMap,nextId:1,providerSet:null,concrete:null,summaries:new Map,warnings:new Map,statusOf:null,round:0,cyclic:!1,grew:!1};return{analyze(n){let r;for(;t.round+=1,t.cyclic=!1,t.grew=!1,r=xt(t,n),!(!t.cyclic||!t.grew););for(let s of t.summaries.values())s.final=!0;return r},warnings(){return[...t.warnings.values()]}}}function tt(e,t,n){throw new h(`${O(e,t)} \u2014 ${n}`)}function U(e,t){let n=e.ids.get(t);return n||(n=e.nextId++,e.ids.set(t,n)),n}function ce(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Static)!==0}function De(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Abstract)!==0}function F(e,t){return!!t&&(e.isClassDeclaration(t)||e.isClassExpression(t))}function Pe(e,t){if(!t)return null;if(F(e,t))return t;if((e.isVariableDeclaration(t)||e.isPropertyDeclaration(t)||e.isPropertyAssignment(t))&&t.initializer){let n=T(e,t.initializer);if(e.isClassExpression(n))return n}return null}function nt(e,t){if(t.name)return t.name.text;let n=t.parent;if(n&&(e.isVariableDeclaration(n)||e.isPropertyDeclaration(n)||e.isPropertyAssignment(n))&&n.name&&P(e,n.name))return P(e,n.name)??void 0}function _(e,t){let n=e.ts,r=T(n,t);if(!r)return null;let s=Pe(n,D(e,n.isPropertyAccessExpression(r)?r.name:r));return s&&v(e,s)?s:null}function q(e,t){let n=e.ts,r=(t.heritageClauses||[]).find(i=>i.token===n.SyntaxKind.ExtendsKeyword),s=r&&r.types[0]&&r.types[0].expression;return s?_(e,s):null}function $e(e,t,n){for(let r=q(e,t);r;r=q(e,r))if(r===n)return!0;return!1}function V(e,t,n,r){let s=e.ts;for(let i=t;i;i=q(e,i))for(let o of i.members)if(!(P(s,o.name)!==n||ce(s,o)!==r)){if((s.isMethodDeclaration(o)||s.isGetAccessorDeclaration(o))&&o.body)return{fn:o,owner:i};if(s.isPropertyDeclaration(o)&&o.initializer){let a=T(s,o.initializer);if(s.isArrowFunction(a)||s.isFunctionExpression(a))return{fn:a,owner:i}}}return null}function rt(e){let t=e.ts;if(e.providerSet)return e.providerSet;let n=new Set;for(let r of e.program.getSourceFiles())if($(e,r.fileName)){for(let s of r.statements)if(t.isClassDeclaration(s))for(let i of t.getDecorators(s)||[]){let o=i.expression;if(!t.isCallExpression(o)||I(e,o.expression)!=="Module")continue;let a=T(t,o.arguments[0]);if(!(!a||!t.isObjectLiteralExpression(a)))for(let c of a.properties){if(!t.isPropertyAssignment(c)||P(t,c.name)!=="providers")continue;let l=T(t,c.initializer);if(t.isArrayLiteralExpression(l))for(let u of l.elements){let m=_(e,u);m&&n.add(m)}}}}return e.providerSet=n,n}function Ce(e){let t=e.ts;if(e.concrete)return e.concrete;let n=[],r=s=>{F(t,s)&&!De(t,s)&&n.push(s),t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.concrete=n,n}function Fe(e,t){let n=t.name?e.checker.getSymbolAtLocation(t.name):t.symbol;return n?e.checker.getDeclaredTypeOfSymbol(n):null}function st(e,t){let n=t&&(t.getSymbol()||t.aliasSymbol),r=n&&(n.declarations||[]).find(s=>F(e.ts,s));return r&&F(e.ts,r)&&v(e,r)?r:null}function re(e,t){return t.type?e.checker.getTypeFromTypeNode(t.type):e.checker.getTypeAtLocation(t.name||t)}function J(e,t,n){let r=e.ts;if(!t)return;if(t.isUnion()){for(let l of t.types)J(e,l,n);return}let s=r.TypeFlags,i=s.StringLike|s.NumberLike|s.BigIntLike|s.BooleanLike|s.EnumLike|s.ESSymbolLike|s.VoidLike|s.Null;if(t.flags&(s.Any|s.Unknown|i))return;let o=t.getSymbol();if(!o)return;let a=(o.declarations||[]).find(l=>F(r,l));if(a&&F(r,a)){if(!v(e,a))return;De(r,a)||n.add(a);for(let l of Ce(e))$e(e,l,a)&&n.add(l);return}if((o.declarations||[]).some(l=>v(e,l)))for(let l of Ce(e)){let u=Fe(e,l);u&&e.checker.isTypeAssignableTo(u,t)&&n.add(l)}}function ae(e,t,n){let r=st(e,t);if(r){let s=rt(e);if(s.has(r)){n.add(r);return}let i=[...s].filter(o=>o!==r&&$e(e,o,r));if(i.length===1){n.add(i[0]);return}}J(e,t,n)}function it(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function Oe(e,t){return t.fn&&it(e,t.fn)?t:{receiver:null,owner:null,fn:null}}function E(e,t,n,r=new Set){let s=e.ts,i=new Set;if(t=T(s,t),!t)return i;let o=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`;if(r.has(o))return i;r.add(o);let a=c=>{for(let l of c)i.add(l)};if(s.isNewExpression(t)){let c=_(e,t.expression);return c&&i.add(c),i}if(t.kind===s.SyntaxKind.ThisKeyword)return n.receiver&&i.add(n.receiver),i;if(s.isConditionalExpression(t))return a(E(e,t.whenTrue,n,r)),a(E(e,t.whenFalse,n,r)),i;if(s.isBinaryExpression(t)){let c=t.operatorToken.kind,l=s.SyntaxKind;if(c===l.QuestionQuestionToken||c===l.BarBarToken||c===l.AmpersandAmpersandToken)return a(E(e,t.left,n,r)),a(E(e,t.right,n,r)),i;if(c===l.CommaToken||c===l.EqualsToken)return a(E(e,t.right,n,r)),i}if(s.isCallExpression(t)){for(let c of X(e,t,n))for(let l of H(s,c.fn))a(E(e,l,c.ctx,r));if(i.size>0)return i}else if(s.isIdentifier(t)||s.isPropertyAccessExpression(t)){let c=D(e,s.isPropertyAccessExpression(t)?t.name:t);if(c&&s.isVariableDeclaration(c))return c.initializer&&a(E(e,c.initializer,Oe(c,n),r)),(!((s.getCombinedNodeFlags(c)&s.NodeFlags.Const)!==0)||!c.initializer)&&J(e,re(e,c),i),i;if(c&&s.isParameter(c)){let l=re(e,c);return c.parent&&s.isConstructorDeclaration(c.parent)?ae(e,l,i):J(e,l,i),i}if(c&&s.isPropertyDeclaration(c))return c.initializer?a(E(e,c.initializer,{receiver:c.parent,owner:c.parent,fn:null},r)):ae(e,re(e,c),i),i;if(c&&s.isGetAccessorDeclaration(c)&&c.body){for(let l of H(s,c))a(E(e,l,{receiver:c.parent,owner:c.parent,fn:c},r));if(i.size>0)return i}if(c&&s.isPropertyAssignment(c)&&(a(E(e,c.initializer,{receiver:null,owner:null,fn:null},r)),i.size>0))return i}return J(e,e.checker.getTypeAtLocation(t),i),i}function H(e,t){if(e.isArrowFunction(t)&&!e.isBlock(t.body))return[t.body];let n=e.isFunctionLike(t)?t.body:void 0;if(!n)return[];let r=[],s=i=>{if(e.isReturnStatement(i)){i.expression&&r.push(i.expression);return}e.isFunctionLike(i)||F(e,i)||e.forEachChild(i,s)};return e.forEachChild(n,s),r}function Re(e,t){return e.isPropertyAccessExpression(t)?t.name.text:e.isElementAccessExpression(t)&&e.isStringLiteralLike(t.argumentExpression)?t.argumentExpression.text:null}function ze(e,t){return e.isPropertyAccessExpression(t)?t.name:t.argumentExpression}function ot(e,t){let n=e.ts,r=Re(n,t);if(r===null)return[];let s=e.checker.getSymbolAtLocation(ze(n,t)),i=new Map;for(let o of s&&s.declarations||[]){if(!te(e,o.getSourceFile().fileName))continue;let a=o.parent,c=a&&a.name&&n.isIdentifier(a.name)?a.name.text:"";for(let l of Ye)l.member===r&&(!l.container||l.container.test(c))&&i.set(l.error.code,l.error)}return[...i.values()]}function at(e,t){let n=e.checker.getSymbolAtLocation(ze(e.ts,t));return n?(n.declarations||[]).some(r=>v(e,r)):!0}function je(e,t,n){let r=e.ts,s=[];for(let i=t;i;i=q(e,i)){for(let a of i.members){if(!r.isPropertyDeclaration(a)||!a.initializer||ce(r,a))continue;let c=T(r,a.initializer);r.isArrowFunction(c)||r.isFunctionExpression(c)||s.push({fn:a.initializer,ctx:{receiver:n,owner:i,fn:null}})}let o=i.members.find(a=>r.isConstructorDeclaration(a)&&!!a.body);if(o){s.push({fn:o,ctx:{receiver:n,owner:i,fn:o}});break}}return s}function X(e,t,n){let r=e.ts,s=T(r,t.expression);if(s.kind===r.SyntaxKind.SuperKeyword){let c=n.owner&&q(e,n.owner);return c?je(e,c,n.receiver):[]}let i=Re(r,s);if(i!==null){let c=s,l=T(r,c.expression);if(l.kind===r.SyntaxKind.SuperKeyword){let g=n.owner&&q(e,n.owner),p=g&&V(e,g,i,!1);return p?[{fn:p.fn,ctx:{receiver:n.receiver,owner:p.owner,fn:p.fn}}]:[]}let u=r.isIdentifier(l)||r.isPropertyAccessExpression(l)?_(e,l):null;if(u){let g=V(e,u,i,!0);return g?[{fn:g.fn,ctx:{receiver:null,owner:g.owner,fn:g.fn}}]:[]}if(!at(e,c))return[];let m=[];for(let g of E(e,l,n)){let p=V(e,g,i,!1);p&&m.push({fn:p.fn,ctx:{receiver:g,owner:p.owner,fn:p.fn}})}if(m.length>0)return m}let o=e.checker.getResolvedSignature(t),a=o&&o.declaration;if(a&&!r.isJSDocSignature(a)&&a.body&&v(e,a)){let c=a,l=c.parent&&F(r,c.parent)?c.parent:null,u=l&&!ce(r,c)?l:null;return[{fn:c,ctx:{receiver:u,owner:l,fn:c}}]}return[]}function Ne(e,t,n){let r=e.ts,s=T(r,t);if(!s)return[];if(r.isPropertyAccessExpression(s)){let i=D(e,s.name);if(!(i&&v(e,i)&&(r.isMethodDeclaration(i)||r.isPropertyDeclaration(i))))return[];let a=[];for(let c of E(e,s.expression,n)){let l=V(e,c,s.name.text,!1);l&&a.push({fn:l.fn,ctx:{receiver:c,owner:l.owner,fn:l.fn}})}return a}if(r.isIdentifier(s)){let i=D(e,s);if(!i||!v(e,i))return[];if(r.isFunctionDeclaration(i)&&i.body)return[{fn:i,ctx:{receiver:null,owner:null,fn:i}}];if(r.isVariableDeclaration(i)&&i.initializer){let o=T(r,i.initializer);if(r.isArrowFunction(o)||r.isFunctionExpression(o))return[{fn:o,ctx:{receiver:null,owner:null,fn:o}}]}}return[]}function K(e,t,n){let r=e.ts,s=T(r,t);if(!s)return null;if(n==="string"&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return[s.text];if(n==="number"&&r.isNumericLiteral(s))return[Number(s.text)];let i=e.checker.getTypeAtLocation(s),o=[];for(let a of i.isUnion()?i.types:[i])if(n==="string"&&a.isStringLiteral())o.push(a.value);else if(n==="number"&&a.isNumberLiteral())o.push(a.value);else return null;return o.length>0?[...new Set(o)]:null}function Ae(e,t,n){let r=O(e,t);e.warnings.has(r)||e.warnings.set(r,`${r} \u2014 ${n}`)}function ct(e,t){let n=T(e,t);return!n||e.isIdentifier(n)&&n.text==="undefined"||n.kind===e.SyntaxKind.VoidExpression}function ve(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return/^[A-Za-z]/.test(t)?t:`E${t}`}function Me(e,t,n,r,s){if(Xe.has(t)){let c=K(e,n[0],"number"),l=K(e,n[1],"string");return!l||!c||c.length!==1?(Ae(e,r,`new ${t}(status, code, \u2026) with a code or status decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code and status literal types (or declare it with defineError)`),[]):l.map(u=>({name:s&&l.length===1?s:ve(u),code:u,status:c[0]}))}let i=Object.prototype.hasOwnProperty.call(oe,t)?oe[t]:null;if(!i)return[];let o=[i.code];if(i.codeArg!==null&&n.length>i.codeArg&&!ct(e.ts,n[i.codeArg])&&(o=K(e,n[i.codeArg],"string"),!o))return Ae(e,r,`new ${t}(\u2026) with a code decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code a literal type (or declare it with defineError)`),[];let a=o;return a.map(c=>({name:s&&a.length===1?s:c===i.code?t:ve(c),code:c,status:i.status}))}function le(e,t){let n=e.ts,r=t.initializer&&T(n,t.initializer);return r&&n.isCallExpression(r)&&I(e,r.expression)==="defineError"?r:null}function Ie(e,t,n){let r=K(e,n.arguments[0],"string"),s=K(e,n.arguments[1],"number"),i=r&&r.length===1?r[0]:null,o=s&&s.length===1?s[0]:null;return(i===null||o===null)&&tt(e,n,`defineError(...) for "${t.name.getText()}" declares a typed error, so its code and status must be known when the project is built (a literal, or a constant of literal type)`),{name:t.name.getText(),code:i,status:o}}function lt(e,t){let n=null,r=s=>{if(!(n||e.isFunctionLike(s))){if(e.isCallExpression(s)&&s.expression.kind===e.SyntaxKind.SuperKeyword){n=s;return}e.forEachChild(s,r)}};return t.body&&e.forEachChild(t.body,r),n}function Be(e,t,n,r){let s=e.ts,i=(t.heritageClauses||[]).find(d=>d.token===s.SyntaxKind.ExtendsKeyword),o=i&&i.types[0]&&i.types[0].expression;if(!o)return[];let a=t.members.find(d=>s.isConstructorDeclaration(d)&&!!d.body),c=n,l=r;if(a){let d=lt(s,a);if(!d)return[];c=d.arguments,l=d}let u=nt(s,t),m=I(e,o);if(m)return Me(e,m,c,l,u);let g=D(e,o);if(g&&s.isVariableDeclaration(g)){let d=le(e,g);return d?[{...Ie(e,g,d),name:u||g.name.getText()}]:[]}let p=_(e,o);if(p){let d=Be(e,p,c,l);return d.length===1&&u?[{...d[0],name:u}]:d}return[]}function ut(e,t){let n=e.ts,r=t.arguments||[],s=I(e,t.expression);if(s)return Me(e,s,r,t);let i=T(n,t.expression),o=D(e,n.isPropertyAccessExpression(i)?i.name:i);if(!o)return[];if(n.isVariableDeclaration(o)){let c=le(e,o);if(c)return[Ie(e,o,c)]}let a=Pe(n,o);return a&&v(e,a)?Be(e,a,r,t):[]}function z(e,t,n,r,s,i,o=new Set){let a=e.ts;if(t=T(a,t),!t)return;let c=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`;if(!o.has(c)){if(o.add(c),a.isNewExpression(t)){let l=O(e,t);R(e,r,s,i,ut(e,t).map(u=>({...u,site:l})));return}if(a.isConditionalExpression(t)){z(e,t.whenTrue,n,r,s,i,o),z(e,t.whenFalse,n,r,s,i,o);return}if(a.isBinaryExpression(t)){let l=a.SyntaxKind,u=t.operatorToken.kind;(u===l.QuestionQuestionToken||u===l.BarBarToken)&&z(e,t.left,n,r,s,i,o),z(e,t.right,n,r,s,i,o);return}if(a.isCallExpression(t)){for(let l of X(e,t,n))for(let u of H(a,l.fn))z(e,u,l.ctx,r,s,i,o);return}if(a.isIdentifier(t)||a.isPropertyAccessExpression(t)){let l=D(e,a.isPropertyAccessExpression(t)?t.name:t);if(l&&(a.isVariableDeclaration(l)||a.isPropertyDeclaration(l))&&l.initializer){let u=a.isVariableDeclaration(l)?Oe(l,n):n;z(e,l.initializer,u,r,s,i,o)}}}}function se(e,t){let n=e.ts;if(!n.isFunctionLike(t))return!1;if((n.getCombinedModifierFlags(t)&n.ModifierFlags.Async)!==0)return!0;let r=e.checker.getSignatureFromDeclaration(t);if(!r)return!1;let s=e.checker.getReturnTypeOfSignature(r),i=e.checker.getPromisedTypeOfPromise;return i?i.call(e.checker,s)!==void 0:e.checker.getAwaitedType(s)!==s}function ft(e,t,n){let r=null;for(let s=t.parent;s&&s!==n;s=s.parent)e.isFunctionLike(s)&&(e.getCombinedModifierFlags(s)&e.ModifierFlags.Async)!==0&&(r=s);return r}function dt(e,t,n){for(let r=t.parent;r&&r!==n;r=r.parent)if(e.isAwaitExpression(r)||e.isForOfStatement(r)&&r.awaitModifier)return!0;return!1}function mt(e,t,n,r){for(let s=t.scopes.length-1;s>=0;s--){let i=t.scopes[s],o=ft(e.ts,n,i.node),a=r||o!==null;if(i.kind==="try"){if(!a||dt(e.ts,o||n,i.node))return i.sink}else if(i.kind==="settle"){if(a)return null}else if(i.kind==="catch"&&a&&!i.rethrows)return null}return t.root}function gt(e){let t=e.ts;if(e.statusOf)return e.statusOf;let n=new Map;for(let[s,i]of Object.entries(oe))n.set(i.code,{status:i.status,site:`palbase/backend ${s}`});let r=s=>{if(t.isVariableDeclaration(s)&&t.isIdentifier(s.name)){let i=le(e,s),o=i&&K(e,i.arguments[0],"string"),a=i&&K(e,i.arguments[1],"number");o&&a&&o.length===1&&a.length===1&&!n.has(o[0])&&n.set(o[0],{status:a[0],site:O(e,s)})}t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.statusOf=n,n}function St(e,t){let n=gt(e),r=n.get(t.code);if(!r){n.set(t.code,{status:t.status,site:t.site});return}if(r.status!==t.status)throw new h(`"${t.code}" is thrown with status ${t.status} (${t.site}) but the code carries status ${r.status} (${r.site}) \u2014 a client matches an error by its code, so one code carries one status. Throw the code's own class, or give the error its own code`)}function R(e,t,n,r,s){for(let o of s)St(e,o);let i=mt(e,t,n,r);if(i)for(let o of s)i.has(o.code)||i.set(o.code,o)}function Ke(e,t,n){if(!n)return!1;let r=!1,s=o=>{let a=!1,c=l=>{a||(e.isIdentifier(l)&&l.text===n?a=!0:e.forEachChild(l,c))};return c(o),a},i=o=>{r||e.isFunctionLike(o)&&o!==t||(e.isThrowStatement(o)&&o.expression&&s(o.expression)?r=!0:e.forEachChild(o,i))};return i(t),r}function pt(e,t){let n=T(e,t);if(n&&(e.isArrowFunction(n)||e.isFunctionExpression(n))){let r=n.parameters[0];return r?e.isIdentifier(r.name)?e.isBlock(n.body)?Ke(e,n.body,r.name.text):!1:!0:!1}return!0}function yt(e,t,n){let r=e.ts;if(!r.isPropertyAccessExpression(t)||t.name.text!==n)return!1;let s=T(r,t.expression);if(!r.isIdentifier(s)||s.text!=="Promise")return!1;let i=D(e,s);return!i||!v(e,i)}function B(e,t,n){let r=e.ts,s=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`,i=e.summaries.get(s);if(i&&(i.final||i.round===e.round))return i.busy&&(e.cyclic=!0),i.errors;i={errors:i?new Map(i.errors):new Map,busy:!0,round:e.round,final:!1},e.summaries.set(s,i);let o=i.errors.size,a={root:i.errors,scopes:[]};if(r.isFunctionLike(t)){let c=t;for(let l of c.parameters||[])l.initializer&&L(e,l.initializer,n,a);c.body&&L(e,c.body,n,a)}else L(e,t,n,a);return i.busy=!1,i.errors.size!==o&&(e.grew=!0),i.errors}function ie(e,t){return{root:e.root,scopes:[...e.scopes,t]}}function L(e,t,n,r){let s=e.ts;if(s.isTryStatement(t)){let o=new Map;L(e,t.tryBlock,n,ie(r,{kind:"try",node:t.tryBlock,sink:o}));let a=t.catchClause;(!a||(a.variableDeclaration&&s.isIdentifier(a.variableDeclaration.name)?Ke(s,a.block,a.variableDeclaration.name.text):a.variableDeclaration))&&R(e,r,t,!1,[...o.values()]),a&&L(e,a.block,n,r),t.finallyBlock&&L(e,t.finallyBlock,n,r);return}if(s.isThrowStatement(t))t.expression&&z(e,t.expression,n,r,t,!1);else if(s.isCallExpression(t)){let o=T(s,t.expression);if(yt(e,o,"allSettled")){L(e,t.expression,n,r);let u=ie(r,{kind:"settle",node:t});for(let m of t.arguments)L(e,m,n,u);return}let a=s.isPropertyAccessExpression(o)?o.name.text==="catch"?0:o.name.text==="then"&&t.arguments.length>1?1:-1:-1;if(a>=0){let u=o,m=pt(s,t.arguments[a]);L(e,u.expression,n,ie(r,{kind:"catch",node:u.expression,rethrows:m}));for(let g of t.arguments)L(e,g,n,r);return}let c=s.isPropertyAccessExpression(o)?et.get(o.name.text):void 0;c!==void 0&&t.arguments[c]&&z(e,t.arguments[c],n,r,t,!0);let l=ot(e,o);if(l.length>0){let u=O(e,t);R(e,r,t,!0,l.map(m=>({...m,site:u})))}for(let u of X(e,t,n))R(e,r,t,se(e,u.fn),[...B(e,u.fn,u.ctx).values()]);for(let u of t.arguments)for(let m of Ne(e,u,n))R(e,r,u,se(e,m.fn),[...B(e,m.fn,m.ctx).values()])}else if(s.isNewExpression(t)){let o=_(e,t.expression);if(o)for(let a of je(e,o,o))R(e,r,t,!1,[...B(e,a.fn,a.ctx).values()]);for(let a of t.arguments||[])for(let c of Ne(e,a,n))R(e,r,a,se(e,c.fn),[...B(e,c.fn,c.ctx).values()])}else if(s.isPropertyAccessExpression(t)&&!(t.parent&&s.isCallExpression(t.parent)&&t.parent.expression===t)){let o=D(e,t.name);if(o&&s.isGetAccessorDeclaration(o)&&o.body&&v(e,o))for(let a of E(e,t.expression,n)){let c=V(e,a,t.name.text,!1);c&&R(e,r,t,!1,[...B(e,c.fn,{receiver:a,owner:c.owner,fn:c.fn}).values()])}}if(F(s,t))return;let i=s.isFunctionExpression(t)||s.isFunctionDeclaration(t)?{receiver:null,owner:null,fn:t}:n;s.forEachChild(t,o=>L(e,o,i,r))}function _e(e,t,n){let r=e.ts;if(n.has(t))return[];if(n.add(t),I(e,t.expression)==="Resolve")return[t];let s=[];for(let i of X(e,t,{receiver:null,owner:null,fn:null}))for(let o of H(r,i.fn)){let a=T(r,o);r.isCallExpression(a)&&s.push(..._e(e,a,n))}return s}function Tt(e,t){let n=e.ts,r=[];for(let s of t.parameters)for(let i of n.getDecorators(s)||[]){let o=T(n,i.expression);if(n.isCallExpression(o))for(let a of _e(e,o,new Set)){let c=_(e,a.arguments[0]);if(!c)continue;let l=new Set;ae(e,Fe(e,c),l);for(let u of l){let m=V(e,u,"resolve",!1);m&&r.push({fn:m.fn,ctx:{receiver:u,owner:m.owner,fn:m.fn}})}}}return r}function ht(e){return e.charAt(0).toLowerCase()+e.slice(1)}function bt(e,t,n){let r=new Map;for(let i of Tt(e,n))for(let o of B(e,i.fn,i.ctx).values())r.has(o.code)||r.set(o.code,o);for(let i of B(e,n,{receiver:t,owner:t,fn:n}).values())r.has(i.code)||r.set(i.code,i);let s=new Map;for(let i of r.values()){let o=ht(i.name),a=s.get(o);if(a)throw new h(`${t.name.text}.${P(e.ts,n.name)} can throw two errors named "${i.name}" \u2014 "${a.code}" (${a.site}) and "${i.code}" (${i.site}). Every client names an error case after it; give one of them its own defineError`);s.set(o,i)}return[...r.values()].map(({name:i,code:o,status:a})=>({name:i,code:o,status:a}))}function xt(e,t){let n=[];for(let{cls:r,routes:s}of Z(e,t)){let i={};for(let o of s)i[P(e.ts,o.name)]=bt(e,r,o);n.push({className:r.name.text,ops:i})}return n}function _t(e,t,n={}){let r=n.typescript??wt,s=Ve(ue(e)),{options:i,ambient:o}=he(r,s);return kt(be(r,s,[Ve(ue(t)),...o],i))}function kt(e){let t=e.ts,n=ke(e),r=Le(e),s=[],i=e.program.getSourceFiles().filter(a=>$(e,a.fileName)).sort((a,c)=>a.fileName<c.fileName?-1:a.fileName>c.fileName?1:0),o=[];for(let a of i){let c=Z(e,a);if(c.length===0)continue;let l=new Map;for(let{cls:u,routes:m}of c)for(let g of m)try{l.set(`${u.name.text}.${P(t,g.name)}`,Ee(e,n,u.name.text,g))}catch(p){if(!(p instanceof h))throw p;o.push(p.message)}if(!(o.length>0))for(let{className:u,ops:m}of r.analyze(a))for(let[g,p]of Object.entries(m))s.push({file:ue(a.fileName),className:u,method:g,returns:l.get(`${u}.${g}`),throws:p})}if(o.length===1)throw new h(o[0]);if(o.length>1)throw new h(`${o.length} routes have no contract:
|
|
5
5
|
${o.map(a=>`- ${a}`).join(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{c as O}from"./
|
|
1
|
+
/*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as O}from"./TV7W53F2.js";import{a as E,b as T,e as _}from"./MJPUCGXY.js";var a=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(n,t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="BackendError",this.kind=n,this.code=t.code,this.status=t.status??0,this.requestId=t.requestId,this.fields=t.fields,this.retryAfter=t.retryAfter,this.data=t.data}};function D(e){return e instanceof a||typeof e=="object"&&e!==null&&e.name==="BackendError"&&typeof e.kind=="string"}function $(e){let n=e.body,t={code:e.code,message:e.message,status:e.status,requestId:e.requestId??se(n,"request_id"),data:b(n,"data"),cause:e};if(e.code==="network_error")return new a("network",t);if(e.status===401)return new a("unauthorized",t);if(e.status===429)return new a("rateLimited",{...t,retryAfter:oe(n)??e.retryAfter});let r=re(n);return e.status===400&&r?new a("validation",{...t,fields:r}):new a("server",t)}function P(e){return e instanceof T||e instanceof Error&&e.name==="PalbaseError"}function j(e){return Array.isArray(e)&&e.length>0&&e.every(n=>typeof n=="object"&&n!==null&&typeof n.field=="string"&&typeof n.message=="string")}function re(e){let n=b(b(e,"data"),"fields");if(j(n))return n;let t=b(e,"fields");return j(t)?t:void 0}function oe(e){return N(e,"retry_after")??N(b(e,"data"),"retryAfter")}function b(e,n){if(typeof e=="object"&&e!==null)return e[n]}function N(e,n){let t=b(e,n);return typeof t=="number"?t:void 0}function se(e,n){let t=b(e,n);return typeof t=="string"?t:void 0}var ie=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ae=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),ce=new Set(ae),de=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function S(e){return e==="then"||e==="toJSON"||de.has(e)}function A(e){return e==="call"||e==="join"||S(e)}function C(e){return typeof e=="string"&&ie.test(e)&&!ce.has(e)&&!S(e)}function B(e){return typeof e=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(e)}function I(e){_(e)}function J(e){return _(e).origin}var R=class extends Error{reason;constructor(n,t){super(n),this.name="RoomError",this.reason=t}},q=new WeakMap;async function U(e,n,t){let{pattern:r,events:o,messages:s}=pe(n),i=ue(r,t),c=q.get(e);c||q.set(e,c=new Map);let p=c;p.set(i,(p.get(i)??0)+1);let u=e.channel(i),l=()=>{let d=(p.get(i)??1)-1;d>0?p.set(i,d):(p.delete(i),u.leave())};try{await u.join()}catch{let d=u.state==="refused"?K(u.refusal,"unavailable"):"socket closed";throw l(),new R(`room ${JSON.stringify(i)} was not joined: ${d}`,d)}let m=!1,w=new Set,k=()=>{if(!m){m=!0,h();for(let d of[...w])d();l()}},h=u.onClosed(k),y=d=>{if(m)return()=>{};let v=u.on("broadcast",f=>{typeof f.event=="string"&&o.has(f.event)&&d(f.event,E(f.payload))}),g=()=>{w.delete(g),v()};return w.add(g),g};return{topic:i,on(d,v){if(typeof d=="function")return y((g,f)=>d({event:g,payload:f}));if(!o.has(d))throw new TypeError(`room ${JSON.stringify(r)} declares no event ${JSON.stringify(String(d))}`);if(typeof v!="function")throw new TypeError(`room ${JSON.stringify(r)}: on(${JSON.stringify(d)}, \u2026) takes the function the event is handed to`);return y((g,f)=>{g===d&&v(f)})},off(d){w.has(d)&&d()},async send(d,v){if(!s.has(d))throw new TypeError(`room ${JSON.stringify(r)} declares no message ${JSON.stringify(String(d))}`);let g=m?{status:"error",response:{reason:"not joined"}}:await u.push("broadcast",{type:"broadcast",event:d,payload:v});if(g.status==="ok")return;let f=K(g.response,"unavailable");throw new R(`room ${JSON.stringify(i)} did not take ${JSON.stringify(d)}: ${f}`,f)},leave:k}}function pe(e){let n=typeof e=="object"&&e!==null?e:{},t=r=>Array.isArray(r)&&r.every(o=>typeof o=="string");if(typeof n.pattern!="string"||n.pattern===""||!t(n.events)||!t(n.messages))throw new TypeError("join takes a room of the backend's generated module: its pattern, its events and its messages");return{pattern:n.pattern,events:new Set(n.events),messages:new Set(n.messages)}}function ue(e,n){let t=typeof n=="object"&&n!==null?n:{};return e.split(":").map(r=>{if(!(r.startsWith("{")&&r.endsWith("}")&&r.length>2))return r;let o=r.slice(1,-1),s=Object.hasOwn(t,o)?t[o]:void 0;if(typeof s!="string"||s==="")throw new TypeError(`room ${JSON.stringify(e)} needs a value for ${JSON.stringify(o)}`);if(s.includes(":"))throw new TypeError(`room ${JSON.stringify(e)}: the value of ${JSON.stringify(o)} is one segment of the channel's name and cannot hold ":"`);return s}).join(":")}function K(e,n){let t=e?.reason;return typeof t=="string"&&t!==""?t:n}var x=class{pending="";dataLines=[];eventName;consume(n){this.pending+=n.replace(/\r\n/g,`
|
|
3
3
|
`);let t=[],r=this.pending.indexOf(`
|
|
4
4
|
`);for(;r!==-1;){let o=this.pending.slice(0,r);this.pending=this.pending.slice(r+1);let s=o.endsWith("\r")?o.slice(0,-1):o;if(s==="")this.dataLines.length>0&&t.push({event:this.eventName,payload:this.dataLines.join(`
|
|
5
5
|
`)}),this.dataLines=[],this.eventName=void 0;else if(!s.startsWith(":")){if(s.startsWith("data:")){let i=s.slice(5);this.dataLines.push(i.startsWith(" ")?i.slice(1):i)}else if(s.startsWith("event:")){let i=s.slice(6);this.eventName=i.startsWith(" ")?i.slice(1):i}}r=this.pending.indexOf(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as g,b}from"./
|
|
1
|
+
/*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as g,b}from"./4MOCDBZP.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=v(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=E(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await U(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status];if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await P(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function U(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:$(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function $(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function v(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function E(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+O(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!e.secretKey;case"userJWT":return!!a;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function O(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function P(t,e){let n=await _(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=B(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function _(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function B(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,v as e,R as f};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import"./
|
|
1
|
+
/*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"./VTNEPJRV.js";import{pathToFileURL as i}from"node:url";import{z as c}from"zod";async function f(e){let n=new Map,t=new Map;for(let r of e){let a=`${r.className}.${r.method}`,o=t.get(r.className);if(o!==void 0&&o!==r.file)throw new Error(`two controllers are named ${r.className} (${o}, ${r.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(r.className,r.file),n.set(a,{returns:await u(r),throws:r.throws})}return r=>n.get(`${r.controller.name}.${r.fn}`)}async function u(e){let n=`${e.file} \u2014 ${e.className}.${e.method}`;switch(e.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let r=(await import(i(e.returns.file).href))[e.returns.exportName];if(!s(r))throw new Error(`${n}: its return type names ${e.returns.exportName}, which ${e.returns.file} exports as no schema (a zod, valibot or arktype schema)`);return{kind:"json",schema:r,array:e.returns.array}}case"expression":{let t=new Function("z",`return (${e.returns.expression});`)(c);if(!s(t))throw new Error(`${n}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function s(e){return typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function"}export{f as routeContracts};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as c,f as u}from"./
|
|
1
|
+
/*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as c,f as u}from"./MJPUCGXY.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,w as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as sn,c as se,d as an,e as Ee,g as S}from"./I3JNX6MZ.js";import{b as Ye,d as ht,e as tn,f as nn,g as Ge,h as Ze,k as rn,q as on}from"./ZFPDYRRY.js";import{b as $e}from"./ECUYQ73P.js";import"reflect-metadata";var gt=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],dn="a schedule is five fields \u2014 minute hour day-of-month month day-of-week, in UTC \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Xe=/^\d+$/;function $r(e,t,r){let n=new Set;for(let o of e.split(",")){let s=o.indexOf("/"),a=s===-1?o:o.slice(0,s),i=1;if(s!==-1){let f=o.slice(s+1);if(!Xe.test(f)||Number(f)<1||Number(f)>r)return;i=Number(f)}let c=t,u=r;if(a!=="*")if(a.includes("-")){let f=a.indexOf("-"),y=a.slice(0,f),E=a.slice(f+1);if(!Xe.test(y)||!Xe.test(E)||Number(y)<t||Number(E)>r||Number(y)>Number(E))return;c=Number(y),u=Number(E)}else{if(!Xe.test(a)||Number(a)<t||Number(a)>r)return;c=Number(a),u=s===-1?c:r}for(let f=c;f<=u;f+=i)n.add(f)}return n}function cn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${dn}; "${e}" is not`;let r=[];for(let u=0;u<5;u++){let f=$r(t[u],gt[u].lo,gt[u].hi);if(!f)return`${dn}; its ${gt[u].name} "${t[u]}" is not one`;r.push(f)}let[,,n,o,s]=r;s.has(7)&&s.add(0);let a=t[2].startsWith("*"),i=t[4].startsWith("*"),c=new Date(Date.UTC(2e3,0,1));for(let u=0;u<366*8+2;u++,c.setUTCDate(c.getUTCDate()+1)){if(!o.has(c.getUTCMonth()+1))continue;let f=n.has(c.getUTCDate()),y=s.has(c.getUTCDay());if(a||i?f&&y:f||y)return}return`"${e}" is never due: no date has that day in that month`}var Re=Symbol.for("palbase.backend.controller"),Se=Symbol.for("palbase.backend.routes"),wt=Symbol.for("palbase.backend.params"),bt=Symbol.for("palbase.backend.injectable"),vt=Symbol.for("palbase.backend.module"),he=Symbol.for("palbase.backend.events"),Oe=Symbol.for("palbase.backend.webhook"),ue=Symbol.for("palbase.backend.jobs");function X(e,t,r){let n=e;return Object.prototype.hasOwnProperty.call(n,t)||Object.defineProperty(n,t,{value:r(),enumerable:!1}),n[t]}var yt=Symbol.for("palbase.backend.declared");function oe(){let e=globalThis;return e[yt]instanceof Set||(e[yt]=new Set),e[yt]}var _e=new Set(["webhooks","_palbase"]);function Ls(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return r=>{let n=e.split("/").filter(Boolean)[0];if(n!==void 0&&_e.has(n))throw new TypeError(`@Controller("${e}") on ${r.name}: /${n} is the platform's; a controller is served elsewhere`);X(r,Re,()=>({basePath:e,options:t})),oe().add(r)}}function xe(e){return(t,r={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);X(n.constructor,Se,()=>[]).push({method:e,subpath:t,fn:o,options:r})}}}var qs=xe("GET"),Hs=xe("POST"),Js=xe("PUT"),Bs=xe("PATCH"),zs=xe("DELETE"),Fs=xe("QUERY");function te(e,t={}){return(r,n,o)=>{if(typeof n!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let s=X(r.constructor,wt,()=>new Map);s.has(n)||s.set(n,[]),s.get(n).push({index:o,kind:e,...t})}}function kt(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var Ks=e=>te("body",{schema:kt("Body",e)}),Ws=e=>te("query",{schema:kt("QueryParams",e)}),Vs=e=>te("headers",e===void 0?{}:{schema:kt("Headers",e)}),Ys=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return te("param",{name:e})},Gs=()=>te("user"),Zs=()=>te("optionalUser"),Xs=()=>te("req"),Qs=()=>te("requestId"),ea=()=>te("requestId"),ta=()=>te("client");function na(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return te("resolve",{resolver:e,options:t[0]})}function ra(){return e=>{X(e,bt,()=>!0),oe().add(e)}}function oa(e){return t=>{X(t,vt,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var ln=/^[a-z]+(\.[a-z_]+)+$/,Er=/^[a-z][a-z0-9-]{1,62}$/,$t=e=>e.startsWith("file.");function sa(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let r=t?.bucket;if(r!==void 0){if(typeof r!="string"||!Er.test(r))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(r)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!$t(e))throw new TypeError(`@On("${e}", { bucket: "${r}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@On("${e}") goes on a method`);X(n.constructor,he,()=>[]).push(r===void 0?{event:e,fn:o}:{event:e,fn:o,bucket:r}),oe().add(n.constructor)}}var Rr=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function aa(e){let t=e??{},r=`@Job(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Rr.test(t.name))throw new TypeError(`${r}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${r}: schedule is five fields of cron's, like "0 3 * * *"`);let n=cn(t.schedule);if(n)throw new TypeError(`${r}: ${n}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>300))throw new TypeError(`${r}: timeout is whole seconds, 1 to 300 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${r}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let o={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeout:t.timeout??30,retries:t.retry??5};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${r} on ${s.name}: a job is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(s,ue))throw new TypeError(`${r} on ${s.name}: a class is one job`);Object.defineProperty(s,ue,{value:o,enumerable:!1}),oe().add(s)}}var un=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Sr=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function ia(e){return t=>{let r=`@Webhook on ${t.name}`,n=e??{};if(typeof n.name!="string"||n.name==="")throw new TypeError(`${r}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!Sr.test(n.name))throw new TypeError(`${r}: name "${n.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(n.name==="palbase")throw new TypeError(`${r}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(n.provider===void 0&&n.signature===void 0)throw new TypeError(`${r}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(n.provider!==void 0&&n.signature!==void 0)throw new TypeError(`${r}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(n.provider!==void 0&&!un.includes(n.provider))throw new TypeError(`${r}: provider "${String(n.provider)}" is not one of ${un.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(n.signature!==void 0&&Or(n.signature,r),typeof n.secret?.env!="string"||n.secret.env==="")throw new TypeError(`${r}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let o=T(t,he)??[];if(o.length===0)throw new TypeError(`${r}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let s=new Set;for(let{event:a,bucket:i}of o){if(s.has(a))throw new TypeError(`${r}: @On("${a}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${r}: @On("${a}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${n.name}'s are a third party's`);s.add(a)}X(t,Oe,()=>({name:n.name,provider:n.provider,signature:n.signature&&{...n.signature},secret:{env:n.secret.env},events:o.map(({event:a,fn:i})=>({event:a,fn:i}))})),oe().add(t)}}function Or(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function T(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function da(){return[...oe()].filter(e=>T(e,Re)!==void 0)}function ca(e){return(T(e,Se)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Et="/_palbase/storage/upload/authorize",fn="/_palbase/storage/upload/complete",Rt="/_palbase/realtime/rooms";var _r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Te(e){if(!_r(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function mn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function pn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Qe(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var xr=/^[a-z][a-z0-9-]{1,62}$/,hn=1024,Tr=new Set(["userId","uploadId","filename"]);function pa(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let r=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof r.bucket!="string"||r.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!xr.test(r.bucket))throw new TypeError(`@Upload("${e}"): bucket "${r.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof r.pathTemplate!="string"||r.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let n=Ar(r.pathTemplate);if(n)throw new TypeError(`@Upload("${e}"): pathTemplate "${r.pathTemplate}" ${n}`);let o={bucket:r.bucket,pathTemplate:r.pathTemplate},s={...r.auth!==void 0?{auth:r.auth}:{},...r.rateLimit!==void 0?{rateLimit:r.rateLimit}:{}};return(a,i,c)=>{if(typeof i!="string"||c===void 0||typeof c.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);X(a.constructor,Se,()=>[]).push({method:"POST",subpath:e,fn:i,options:s,upload:o})}}function ha(){return te("uploadedObject")}function Ar(e){for(let r of e.matchAll(/\{([^{}]*)\}/g))if(!Tr.has(r[1]))return`names {${r[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!gn(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function gn(e){if(e===""||new TextEncoder().encode(e).byteLength>hn)return!1;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<32||r===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Pr(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(r,n)=>jr(n==="userId"?t.userId??"anonymous":n==="uploadId"?t.uploadId:t.filename??"file"))}function jr(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function yn(e,t){let r=Pr(e,t);return gn(r)?{path:r}:{problem:`the file's name makes its path longer than storage keeps (${hn} bytes)`}}function wn(e){let t=new Map;for(let r of e)r.meta.upload&&t.set(r.controller,(t.get(r.controller)??new Set).add(r.fn));for(let r of e){let n=`${r.controller.name}.${r.fn}`;if(!r.meta.upload){if(t.get(r.controller)?.has(r.fn))throw new TypeError(`${n}: @Upload and @${r.method[0]}${r.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(r.params.some(s=>s.kind==="uploadedObject"))throw new TypeError(`${n}: @UploadedObject() on ${r.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let o=r.params.find(s=>s.kind==="headers"||s.kind==="req"||s.kind==="client");if(o){let s=o.kind==="headers"?"Headers":o.kind==="req"?"Req":"Client";throw new TypeError(`${n}: @${s}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var St=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bn(e,t){if(!St(t))return"a call is a JSON object";let{route:r,method:n,query:o,uploadId:s}=t;if(typeof r!="string"||!r.startsWith("/"))return"route is the upload route's path";if(typeof n!="string"||n==="")return"method is the route's";if(typeof o!="string")return'query is the query string, "" for none';if(typeof s!="string"||s==="")return"uploadId is the upload's id";let a=Te(t.user);if(!a)return"user is { id?, session?, role }";let i=mn(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:r,method:n,query:o,uploadId:s,user:a,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let c=Cr(t.uploadedObject);return c?c.uploadId!==s?"uploadedObject is another upload's":{route:r,method:n,query:o,uploadId:s,user:a,...i?{client:i}:{},filename:"",uploadedObject:c,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Cr(e){if(!St(e))return;let{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,width:i,height:c,thumbhash:u,variants:f}=e;if(!(typeof t!="string"||typeof r!="string"||typeof n!="string"||typeof s!="string"||typeof a!="string")&&!(typeof o!="number"||!Number.isInteger(o)||o<0)&&!(i!==void 0&&typeof i!="number"||c!==void 0&&typeof c!="number"||u!==void 0&&typeof u!="string")&&!(!St(f)||!Object.values(f).every(y=>typeof y=="string")))return{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,...i!==void 0?{width:i}:{},...c!==void 0?{height:c}:{},...u!==void 0?{thumbhash:u}:{},variants:{...f}}}import{markData as Mr}from"palgres";var ge=Symbol.for("palbase.backend.room"),Pe=Symbol.for("palbase.backend.roomHooks"),Dr=6e4,Ae=255,Ur=["roles:","flags:","messaging:","debug:"],xt=e=>new TextEncoder().encode(e).byteLength,vn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function";function Nr(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(xt(e)>Ae)return`a channel is ${Ae} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=Ur.find(n=>e.startsWith(n));if(t)return`${t} channels are the platform's`;let r=new Set;for(let n of e.split(":")){if(n==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(n)){if(n==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(n))return`"${n}" \u2014 a parameter is a whole segment, {name}`;if(r.has(n))return`parameter "${n}" appears twice.`;r.add(n)}}}function kn(e){if(typeof e!="string"||e==="")return"is a name";if(xt(e)>Ae)return`is ${Ae} bytes at most`}function ka(e,t){if(typeof e!="string"||e==="")throw new TypeError('@Room(pattern, { events }): pattern is the channels it is, like "ai:{sessionId}"');let r=Nr(e);if(r)throw new TypeError(`@Room("${e}"): ${r}`);let n=t??{};if(typeof n.events!="object"||n.events===null||Array.isArray(n.events))throw new TypeError(`@Room("${e}"): events is required \u2014 what the room sends, by name, each its payload's schema ({} for none)`);for(let[a,i]of Object.entries(n.events)){let c=kn(a);if(c)throw new TypeError(`@Room("${e}"): event "${a}" ${c}`);if(!vn(i))throw new TypeError(`@Room("${e}"): event "${a}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}if(n.graceMs!==void 0&&(!Number.isSafeInteger(n.graceMs)||n.graceMs<=0))throw new TypeError(`@Room("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(n.graceMs)})`);let o={...n.events},s=n.graceMs??Dr;return a=>{let i=X(a,Pe,Tt);X(a,ge,()=>({pattern:e,events:o,graceMs:s,hooks:{...i.hooks},messages:Object.assign(Object.create(null),i.messages)})),oe().add(a)}}var Tt=()=>({hooks:Object.create(null),messages:Object.create(null)});function Ue(e){let t=`On${e[0].toUpperCase()}${e.slice(1)}`;return()=>(r,n,o)=>{if(typeof n!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof r=="function")throw new TypeError(`@${t}() on static ${r.name}.${n}: a room's methods are its instance's`);let s=X(r.constructor,Pe,Tt),a=s.hooks[e];if(a!==void 0&&a!==n)throw new TypeError(`@${t}() is declared twice in one room (${a} and ${n}). A room has one of each hook.`);s.hooks[e]=n,oe().add(r.constructor)}}var $a=Ue("authorize"),Ea=Ue("first"),Ra=Ue("join"),Sa=Ue("leave"),Oa=Ue("empty");function _a(e,t){let r=kn(e);if(r)throw new TypeError(`@OnMessage(name, schema): name ${r}`);if(!vn(t))throw new TypeError(`@OnMessage("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@OnMessage("${e}") goes on a method`);if(typeof n=="function")throw new TypeError(`@OnMessage("${e}") on static ${n.name}.${o}: a room's methods are its instance's`);let a=X(n.constructor,Pe,Tt),i=a.messages[e];if(i!==void 0&&i.fn!==o)throw new TypeError(`@OnMessage("${e}") is declared twice in one room (${i.fn} and ${o}).`);a.messages[e]={fn:o,schema:t},oe().add(n.constructor)}}function Ir(e){return T(e,ge)}function Lr(e,t){let r=e.split(":"),n=t.split(":");if(r.length!==n.length)return;let o=[];for(let s=0;s<r.length;s++){let a=r[s];if(a.length>=2&&a.startsWith("{")&&a.endsWith("}")){if(n[s]==="")return;o.push([a.slice(1,-1),n[s]])}else if(a!==n[s])return}return Object.fromEntries(o)}var qr=1e4,Hr=1e3,Jr=100,At=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ae=(e,t,r,n)=>({status:e,code:t,message:r,...n!==void 0?{retryAfter:n}:{}}),Br=new Set(["first","join","leave","empty"]);function $n(e,t){let r=new Map,n=new Map;for(let{cls:b,instance:$}of e){let w=Ir(b),R=w.pattern.split(":").map(C=>C.startsWith("{")?"{}":C).join(":"),P=n.get(R);if(P!==void 0)throw new TypeError(`@Room("${w.pattern}") on ${b.name}: ${r.get(P)?.cls.name}'s "${P}" is the same channels \u2014 one room is told of them; keep one`);n.set(R,w.pattern);for(let[C,I]of[...Object.entries(w.hooks),...Object.entries(w.messages).map(([L,U])=>[`message ${L}`,U.fn])])if(typeof $[I]!="function")throw new TypeError(`@Room("${w.pattern}") on ${b.name}: its ${C} is ${I}, which is no method of it`);r.set(w.pattern,{cls:b,instance:$,room:w})}let o=new Map,s=new Set,a=new Set,i=new _t(t.broadcast),c=b=>{let $=o.get(b);return $||($=new AbortController,o.set(b,$)),$},u=(b,$)=>{$?.abort(),o.get(b)===$&&o.delete(b)};function f(b,$,w,R,P,C,I){let L=R?.signal??AbortSignal.abort(),U=`${b.cls.name} (${$})`;return{room:$,params:Object.freeze({...w}),signal:L,count:P,user:C,emit:(M,q)=>i.send({topic:$,event:M,payload:q??{},...I!==void 0?{conn_id:I}:{}},U),owner:{hold(M){se.exit(async()=>{try{await M(L)}catch(q){L.aborted||S.error(`[palbase] ${U}: a task owner.hold ran failed`,{error:q})}}).catch(()=>{})},release:()=>u($,R)}}}function y(b){let{room:$,channel:w}=b;if(typeof $!="string"||typeof w!="string")return ae(400,"bad_request","A room's call names its room (the pattern) and its channel");let R=r.get($);return R?{entry:R,channel:w,params:Lr($,w)}:ae(404,"not_found",`This app declares no room "${$}"`)}let E=(b,$)=>ae(400,"bad_request",`"${$}" is not a channel of the room "${b}"`);async function N(b,$){let w=y(b);if("status"in w)return w;let{entry:R,channel:P,params:C}=w,I={status:200,body:{subscribe:!1,publish:!1}};if(!C)return S.warn(`[palbase] ${R.cls.name}: realtime asked about "${P}", which is not a channel of the room "${R.room.pattern}"; the join is refused`),I;let L=Te(b.user),U=L?.id;if(!U)return I;let M=R.room.hooks.authorize;if(!M)return I;let q,re;try{q=await t.run(L,`${R.cls.name}.${M}`,$,async()=>R.instance[M]({user:{id:U},params:Object.freeze({...C})})),re=zr(q)}catch(Q){if(t.isOutage(Q)||$?.aborted)throw Q;return S.error(`[palbase] ${R.cls.name}.${M} (@OnAuthorize of ${P}) failed; the join is refused`,{error:Q}),I}return re==="malformed"?(S.warn(`[palbase] ${R.cls.name}.${M} (@OnAuthorize of ${P}) answered ${Fr(q)}, which is no grant (true, { read, write } or null); the join is refused`),I):{status:200,body:re}}async function g(b,$){let w=y(b);if("status"in w)return w;if(!w.params)return E(w.entry.room.pattern,w.channel);let R=Te(b.user);if(!R?.id||typeof b.event!="string")return ae(400,"bad_request","A message names its member (user) and its event");let P=Object.hasOwn(w.entry.room.messages,b.event)?w.entry.room.messages[b.event]:void 0;if(!P)return{status:200,body:{ok:!1,reason:En(`room "${w.channel}" declares no message "${b.event}"`,Ot)}};let C=await P.schema["~standard"].validate(Mr(b.payload??{}));if(C.issues)return{status:200,body:{ok:!1,reason:Wr(C.issues)}};let I=c(w.channel),L={...f(w.entry,w.channel,w.params,I,0,{id:R.id}),payload:C.value};try{await t.run(R,`${w.entry.cls.name}.${P.fn}`,$,async()=>w.entry.instance[P.fn](L))}catch(U){if(t.isOutage(U))throw U;return $?.aborted||S.error(`[palbase] ${w.entry.cls.name}.${P.fn} (@OnMessage "${b.event}" of ${w.channel}) failed`,{error:U}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return{status:200,body:{ok:!0}}}async function A(b,$){let w=y(b);if("status"in w)return w;if(!w.params)return E(w.entry.room.pattern,w.channel);let R=b.event;if(typeof R!="string"||!Br.has(R))return ae(400,"bad_request","A room's moment is first, join, leave or empty");let P=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(P===void 0)return ae(400,"bad_request","A room's moment says its count of members");let C=R==="join"||R==="leave",I=C?Te(b.user):void 0,L=C?b.connId:void 0;if(C&&(!I?.id||typeof L!="string"||L===""))return ae(400,"bad_request",`A ${R} names its member: user and connId`);let U=`${R}\0${w.channel}\0${typeof L=="string"?L:""}`;if(C&&s.has(U))return{status:204};if(a.has(U))return ae(503,"in_progress","This moment of the room is being handled",5);a.add(U);try{let M=w.entry.room.hooks[R],q;if(R==="empty"?(q=o.get(w.channel),u(w.channel,q)):q=R==="leave"?o.get(w.channel):c(w.channel),M){let re=f(w.entry,w.channel,w.params,q,P,{id:I?.id??""},R==="join"?L:void 0);try{await t.run(I,`${w.entry.cls.name}.${M}`,$,async()=>w.entry.instance[M](re))}catch(Q){if(t.isOutage(Q))throw Q;return $?.aborted||S.error(`[palbase] ${w.entry.cls.name}.${M} (${R} of ${w.channel}) failed; realtime tells it again`,{error:Q}),ae(500,"handler_failed",`The room's ${R} could not be handled`)}}return C&&(s.add(U),s.size>qr&&s.delete(s.values().next().value)),{status:204}}finally{a.delete(U)}}return{declarations:[...r.values()].map(b=>b.room),async serve(b,$,w){return At($)?b==="authorize"?N($,w):b==="message"?g($,w):b==="lifecycle"?A($,w):ae(404,"not_found",`No room call ${JSON.stringify(b)}`):ae(400,"bad_request","A room's call is a JSON object")},close(){for(let b of o.values())b.abort();o.clear()}}}function zr(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!At(e))return"malformed";let r=Object.hasOwn(e,"read"),n=Object.hasOwn(e,"write");if(r&&typeof e.read!="boolean"||n&&typeof e.write!="boolean"||!r&&!n)return"malformed";let o=r?e.read:void 0,s=n?e.write:void 0;return o===!1?t:{subscribe:!0,publish:s!==!1}}function Fr(e){return Array.isArray(e)?"an array":At(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var Kr=20,Ot=256;function Wr(e){let t="";for(let r of e.slice(0,Kr)){let n=(r.path??[]).slice(0,8).map(s=>String(typeof s=="object"&&s!==null&&"key"in s?s.key:s).slice(0,64)).join("."),o=n===""?r.message:`${n}: ${r.message}`;if(t=t===""?o:`${t}; ${o}`,Buffer.byteLength(t)>=Ot)break}return En(t,Ot)}function En(e,t){if(Buffer.byteLength(e)<=t)return e;let r="";for(let n of e){if(Buffer.byteLength(r+n)>t-3)break;r+=n}return`${r}\u2026`}var _t=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,r){if(typeof t.event!="string"||t.event===""||xt(t.event)>Ae){S.warn(`[palbase] ${r}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Ae} bytes`);return}try{JSON.stringify(t.payload)}catch(s){S.warn(`[palbase] ${r}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let n=this.queues.get(t.topic);if(n){n.length>=Hr?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):n.push(t);return}let o=[t];this.queues.set(t.topic,o),se.exit(()=>this.drain(t.topic,o,r))}async drain(t,r,n){for(;;){if(r.length===0){this.queues.delete(t);return}let o=r.splice(0,Jr);try{await this.broadcast(o)}catch(a){S.warn(`[palbase] ${n}: ${o.length} event(s) to ${t} were not sent`,{error:a})}let s=this.dropped.get(t);s&&(this.dropped.delete(t),S.warn(`[palbase] ${n}: ${s} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as Pt,createHmac as Vr,createPublicKey as _n,timingSafeEqual as Yr,verify as xn}from"node:crypto";function Pa(e){let t=T(e,Oe);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(r=>r.event)}}function Tn(e,t,r,n={}){let o=new Map,s=[];for(let a of e){let i=T(a,Oe),c=o.get(i.name);if(c)throw new TypeError(`@Webhook "${i.name}" is declared by ${c.cls.name} and by ${a.name}: /webhooks/${i.name} is one endpoint`);let u=`@Webhook "${i.name}" (${a.name})`,f=r[i.secret.env],y;if(n.secrets!==!1)if(f===void 0||f==="")s.push(`${u} reads its signing secret from ${i.secret.env}, which is not set`);else try{y=Gr(i,f)}catch(g){s.push(`${u}: ${i.secret.env} ${g.message}`)}let E=t(a),N=new Map(i.events.map(({event:g,fn:A})=>[g,{name:`${a.name}.${A}`,call:(b,$)=>E[A](b,$)}]));o.set(i.name,{name:i.name,cls:a,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:y,events:N})}if(s.length>0)throw new Error(`[palbase] the app cannot start:
|
|
1
|
+
/*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as sn,c as se,d as an,e as Ee,g as S}from"./4UPL27ED.js";import{b as Ye,d as ht,e as tn,f as nn,g as Ge,h as Ze,k as rn,q as on}from"./FVIHTHHV.js";import{b as $e}from"./MJPUCGXY.js";import"reflect-metadata";var gt=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],dn="a schedule is five fields \u2014 minute hour day-of-month month day-of-week, in UTC \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Xe=/^\d+$/;function $r(e,t,r){let n=new Set;for(let o of e.split(",")){let s=o.indexOf("/"),a=s===-1?o:o.slice(0,s),i=1;if(s!==-1){let f=o.slice(s+1);if(!Xe.test(f)||Number(f)<1||Number(f)>r)return;i=Number(f)}let c=t,u=r;if(a!=="*")if(a.includes("-")){let f=a.indexOf("-"),y=a.slice(0,f),E=a.slice(f+1);if(!Xe.test(y)||!Xe.test(E)||Number(y)<t||Number(E)>r||Number(y)>Number(E))return;c=Number(y),u=Number(E)}else{if(!Xe.test(a)||Number(a)<t||Number(a)>r)return;c=Number(a),u=s===-1?c:r}for(let f=c;f<=u;f+=i)n.add(f)}return n}function cn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${dn}; "${e}" is not`;let r=[];for(let u=0;u<5;u++){let f=$r(t[u],gt[u].lo,gt[u].hi);if(!f)return`${dn}; its ${gt[u].name} "${t[u]}" is not one`;r.push(f)}let[,,n,o,s]=r;s.has(7)&&s.add(0);let a=t[2].startsWith("*"),i=t[4].startsWith("*"),c=new Date(Date.UTC(2e3,0,1));for(let u=0;u<366*8+2;u++,c.setUTCDate(c.getUTCDate()+1)){if(!o.has(c.getUTCMonth()+1))continue;let f=n.has(c.getUTCDate()),y=s.has(c.getUTCDay());if(a||i?f&&y:f||y)return}return`"${e}" is never due: no date has that day in that month`}var Re=Symbol.for("palbase.backend.controller"),Se=Symbol.for("palbase.backend.routes"),wt=Symbol.for("palbase.backend.params"),bt=Symbol.for("palbase.backend.injectable"),vt=Symbol.for("palbase.backend.module"),he=Symbol.for("palbase.backend.events"),Oe=Symbol.for("palbase.backend.webhook"),ue=Symbol.for("palbase.backend.jobs");function X(e,t,r){let n=e;return Object.prototype.hasOwnProperty.call(n,t)||Object.defineProperty(n,t,{value:r(),enumerable:!1}),n[t]}var yt=Symbol.for("palbase.backend.declared");function oe(){let e=globalThis;return e[yt]instanceof Set||(e[yt]=new Set),e[yt]}var _e=new Set(["webhooks","_palbase"]);function Ls(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return r=>{let n=e.split("/").filter(Boolean)[0];if(n!==void 0&&_e.has(n))throw new TypeError(`@Controller("${e}") on ${r.name}: /${n} is the platform's; a controller is served elsewhere`);X(r,Re,()=>({basePath:e,options:t})),oe().add(r)}}function xe(e){return(t,r={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);X(n.constructor,Se,()=>[]).push({method:e,subpath:t,fn:o,options:r})}}}var qs=xe("GET"),Hs=xe("POST"),Js=xe("PUT"),Bs=xe("PATCH"),zs=xe("DELETE"),Fs=xe("QUERY");function te(e,t={}){return(r,n,o)=>{if(typeof n!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let s=X(r.constructor,wt,()=>new Map);s.has(n)||s.set(n,[]),s.get(n).push({index:o,kind:e,...t})}}function kt(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var Ks=e=>te("body",{schema:kt("Body",e)}),Ws=e=>te("query",{schema:kt("QueryParams",e)}),Vs=e=>te("headers",e===void 0?{}:{schema:kt("Headers",e)}),Ys=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return te("param",{name:e})},Gs=()=>te("user"),Zs=()=>te("optionalUser"),Xs=()=>te("req"),Qs=()=>te("requestId"),ea=()=>te("requestId"),ta=()=>te("client");function na(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return te("resolve",{resolver:e,options:t[0]})}function ra(){return e=>{X(e,bt,()=>!0),oe().add(e)}}function oa(e){return t=>{X(t,vt,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var ln=/^[a-z]+(\.[a-z_]+)+$/,Er=/^[a-z][a-z0-9-]{1,62}$/,$t=e=>e.startsWith("file.");function sa(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let r=t?.bucket;if(r!==void 0){if(typeof r!="string"||!Er.test(r))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(r)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!$t(e))throw new TypeError(`@On("${e}", { bucket: "${r}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@On("${e}") goes on a method`);X(n.constructor,he,()=>[]).push(r===void 0?{event:e,fn:o}:{event:e,fn:o,bucket:r}),oe().add(n.constructor)}}var Rr=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function aa(e){let t=e??{},r=`@Job(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Rr.test(t.name))throw new TypeError(`${r}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${r}: schedule is five fields of cron's, like "0 3 * * *"`);let n=cn(t.schedule);if(n)throw new TypeError(`${r}: ${n}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>300))throw new TypeError(`${r}: timeout is whole seconds, 1 to 300 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${r}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let o={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeout:t.timeout??30,retries:t.retry??5};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${r} on ${s.name}: a job is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(s,ue))throw new TypeError(`${r} on ${s.name}: a class is one job`);Object.defineProperty(s,ue,{value:o,enumerable:!1}),oe().add(s)}}var un=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Sr=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function ia(e){return t=>{let r=`@Webhook on ${t.name}`,n=e??{};if(typeof n.name!="string"||n.name==="")throw new TypeError(`${r}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!Sr.test(n.name))throw new TypeError(`${r}: name "${n.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(n.name==="palbase")throw new TypeError(`${r}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(n.provider===void 0&&n.signature===void 0)throw new TypeError(`${r}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(n.provider!==void 0&&n.signature!==void 0)throw new TypeError(`${r}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(n.provider!==void 0&&!un.includes(n.provider))throw new TypeError(`${r}: provider "${String(n.provider)}" is not one of ${un.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(n.signature!==void 0&&Or(n.signature,r),typeof n.secret?.env!="string"||n.secret.env==="")throw new TypeError(`${r}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let o=T(t,he)??[];if(o.length===0)throw new TypeError(`${r}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let s=new Set;for(let{event:a,bucket:i}of o){if(s.has(a))throw new TypeError(`${r}: @On("${a}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${r}: @On("${a}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${n.name}'s are a third party's`);s.add(a)}X(t,Oe,()=>({name:n.name,provider:n.provider,signature:n.signature&&{...n.signature},secret:{env:n.secret.env},events:o.map(({event:a,fn:i})=>({event:a,fn:i}))})),oe().add(t)}}function Or(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function T(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function da(){return[...oe()].filter(e=>T(e,Re)!==void 0)}function ca(e){return(T(e,Se)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Et="/_palbase/storage/upload/authorize",fn="/_palbase/storage/upload/complete",Rt="/_palbase/realtime/rooms";var _r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Te(e){if(!_r(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function mn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function pn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Qe(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var xr=/^[a-z][a-z0-9-]{1,62}$/,hn=1024,Tr=new Set(["userId","uploadId","filename"]);function pa(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let r=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof r.bucket!="string"||r.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!xr.test(r.bucket))throw new TypeError(`@Upload("${e}"): bucket "${r.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof r.pathTemplate!="string"||r.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let n=Ar(r.pathTemplate);if(n)throw new TypeError(`@Upload("${e}"): pathTemplate "${r.pathTemplate}" ${n}`);let o={bucket:r.bucket,pathTemplate:r.pathTemplate},s={...r.auth!==void 0?{auth:r.auth}:{},...r.rateLimit!==void 0?{rateLimit:r.rateLimit}:{}};return(a,i,c)=>{if(typeof i!="string"||c===void 0||typeof c.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);X(a.constructor,Se,()=>[]).push({method:"POST",subpath:e,fn:i,options:s,upload:o})}}function ha(){return te("uploadedObject")}function Ar(e){for(let r of e.matchAll(/\{([^{}]*)\}/g))if(!Tr.has(r[1]))return`names {${r[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!gn(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function gn(e){if(e===""||new TextEncoder().encode(e).byteLength>hn)return!1;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<32||r===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Pr(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(r,n)=>jr(n==="userId"?t.userId??"anonymous":n==="uploadId"?t.uploadId:t.filename??"file"))}function jr(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function yn(e,t){let r=Pr(e,t);return gn(r)?{path:r}:{problem:`the file's name makes its path longer than storage keeps (${hn} bytes)`}}function wn(e){let t=new Map;for(let r of e)r.meta.upload&&t.set(r.controller,(t.get(r.controller)??new Set).add(r.fn));for(let r of e){let n=`${r.controller.name}.${r.fn}`;if(!r.meta.upload){if(t.get(r.controller)?.has(r.fn))throw new TypeError(`${n}: @Upload and @${r.method[0]}${r.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(r.params.some(s=>s.kind==="uploadedObject"))throw new TypeError(`${n}: @UploadedObject() on ${r.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let o=r.params.find(s=>s.kind==="headers"||s.kind==="req"||s.kind==="client");if(o){let s=o.kind==="headers"?"Headers":o.kind==="req"?"Req":"Client";throw new TypeError(`${n}: @${s}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var St=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bn(e,t){if(!St(t))return"a call is a JSON object";let{route:r,method:n,query:o,uploadId:s}=t;if(typeof r!="string"||!r.startsWith("/"))return"route is the upload route's path";if(typeof n!="string"||n==="")return"method is the route's";if(typeof o!="string")return'query is the query string, "" for none';if(typeof s!="string"||s==="")return"uploadId is the upload's id";let a=Te(t.user);if(!a)return"user is { id?, session?, role }";let i=mn(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:r,method:n,query:o,uploadId:s,user:a,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let c=Cr(t.uploadedObject);return c?c.uploadId!==s?"uploadedObject is another upload's":{route:r,method:n,query:o,uploadId:s,user:a,...i?{client:i}:{},filename:"",uploadedObject:c,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Cr(e){if(!St(e))return;let{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,width:i,height:c,thumbhash:u,variants:f}=e;if(!(typeof t!="string"||typeof r!="string"||typeof n!="string"||typeof s!="string"||typeof a!="string")&&!(typeof o!="number"||!Number.isInteger(o)||o<0)&&!(i!==void 0&&typeof i!="number"||c!==void 0&&typeof c!="number"||u!==void 0&&typeof u!="string")&&!(!St(f)||!Object.values(f).every(y=>typeof y=="string")))return{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,...i!==void 0?{width:i}:{},...c!==void 0?{height:c}:{},...u!==void 0?{thumbhash:u}:{},variants:{...f}}}import{markData as Mr}from"palgres";var ge=Symbol.for("palbase.backend.room"),Pe=Symbol.for("palbase.backend.roomHooks"),Dr=6e4,Ae=255,Ur=["roles:","flags:","messaging:","debug:"],xt=e=>new TextEncoder().encode(e).byteLength,vn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function";function Nr(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(xt(e)>Ae)return`a channel is ${Ae} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=Ur.find(n=>e.startsWith(n));if(t)return`${t} channels are the platform's`;let r=new Set;for(let n of e.split(":")){if(n==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(n)){if(n==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(n))return`"${n}" \u2014 a parameter is a whole segment, {name}`;if(r.has(n))return`parameter "${n}" appears twice.`;r.add(n)}}}function kn(e){if(typeof e!="string"||e==="")return"is a name";if(xt(e)>Ae)return`is ${Ae} bytes at most`}function ka(e,t){if(typeof e!="string"||e==="")throw new TypeError('@Room(pattern, { events }): pattern is the channels it is, like "ai:{sessionId}"');let r=Nr(e);if(r)throw new TypeError(`@Room("${e}"): ${r}`);let n=t??{};if(typeof n.events!="object"||n.events===null||Array.isArray(n.events))throw new TypeError(`@Room("${e}"): events is required \u2014 what the room sends, by name, each its payload's schema ({} for none)`);for(let[a,i]of Object.entries(n.events)){let c=kn(a);if(c)throw new TypeError(`@Room("${e}"): event "${a}" ${c}`);if(!vn(i))throw new TypeError(`@Room("${e}"): event "${a}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}if(n.graceMs!==void 0&&(!Number.isSafeInteger(n.graceMs)||n.graceMs<=0))throw new TypeError(`@Room("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(n.graceMs)})`);let o={...n.events},s=n.graceMs??Dr;return a=>{let i=X(a,Pe,Tt);X(a,ge,()=>({pattern:e,events:o,graceMs:s,hooks:{...i.hooks},messages:Object.assign(Object.create(null),i.messages)})),oe().add(a)}}var Tt=()=>({hooks:Object.create(null),messages:Object.create(null)});function Ue(e){let t=`On${e[0].toUpperCase()}${e.slice(1)}`;return()=>(r,n,o)=>{if(typeof n!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof r=="function")throw new TypeError(`@${t}() on static ${r.name}.${n}: a room's methods are its instance's`);let s=X(r.constructor,Pe,Tt),a=s.hooks[e];if(a!==void 0&&a!==n)throw new TypeError(`@${t}() is declared twice in one room (${a} and ${n}). A room has one of each hook.`);s.hooks[e]=n,oe().add(r.constructor)}}var $a=Ue("authorize"),Ea=Ue("first"),Ra=Ue("join"),Sa=Ue("leave"),Oa=Ue("empty");function _a(e,t){let r=kn(e);if(r)throw new TypeError(`@OnMessage(name, schema): name ${r}`);if(!vn(t))throw new TypeError(`@OnMessage("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@OnMessage("${e}") goes on a method`);if(typeof n=="function")throw new TypeError(`@OnMessage("${e}") on static ${n.name}.${o}: a room's methods are its instance's`);let a=X(n.constructor,Pe,Tt),i=a.messages[e];if(i!==void 0&&i.fn!==o)throw new TypeError(`@OnMessage("${e}") is declared twice in one room (${i.fn} and ${o}).`);a.messages[e]={fn:o,schema:t},oe().add(n.constructor)}}function Ir(e){return T(e,ge)}function Lr(e,t){let r=e.split(":"),n=t.split(":");if(r.length!==n.length)return;let o=[];for(let s=0;s<r.length;s++){let a=r[s];if(a.length>=2&&a.startsWith("{")&&a.endsWith("}")){if(n[s]==="")return;o.push([a.slice(1,-1),n[s]])}else if(a!==n[s])return}return Object.fromEntries(o)}var qr=1e4,Hr=1e3,Jr=100,At=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ae=(e,t,r,n)=>({status:e,code:t,message:r,...n!==void 0?{retryAfter:n}:{}}),Br=new Set(["first","join","leave","empty"]);function $n(e,t){let r=new Map,n=new Map;for(let{cls:b,instance:$}of e){let w=Ir(b),R=w.pattern.split(":").map(C=>C.startsWith("{")?"{}":C).join(":"),P=n.get(R);if(P!==void 0)throw new TypeError(`@Room("${w.pattern}") on ${b.name}: ${r.get(P)?.cls.name}'s "${P}" is the same channels \u2014 one room is told of them; keep one`);n.set(R,w.pattern);for(let[C,I]of[...Object.entries(w.hooks),...Object.entries(w.messages).map(([L,U])=>[`message ${L}`,U.fn])])if(typeof $[I]!="function")throw new TypeError(`@Room("${w.pattern}") on ${b.name}: its ${C} is ${I}, which is no method of it`);r.set(w.pattern,{cls:b,instance:$,room:w})}let o=new Map,s=new Set,a=new Set,i=new _t(t.broadcast),c=b=>{let $=o.get(b);return $||($=new AbortController,o.set(b,$)),$},u=(b,$)=>{$?.abort(),o.get(b)===$&&o.delete(b)};function f(b,$,w,R,P,C,I){let L=R?.signal??AbortSignal.abort(),U=`${b.cls.name} (${$})`;return{room:$,params:Object.freeze({...w}),signal:L,count:P,user:C,emit:(M,q)=>i.send({topic:$,event:M,payload:q??{},...I!==void 0?{conn_id:I}:{}},U),owner:{hold(M){se.exit(async()=>{try{await M(L)}catch(q){L.aborted||S.error(`[palbase] ${U}: a task owner.hold ran failed`,{error:q})}}).catch(()=>{})},release:()=>u($,R)}}}function y(b){let{room:$,channel:w}=b;if(typeof $!="string"||typeof w!="string")return ae(400,"bad_request","A room's call names its room (the pattern) and its channel");let R=r.get($);return R?{entry:R,channel:w,params:Lr($,w)}:ae(404,"not_found",`This app declares no room "${$}"`)}let E=(b,$)=>ae(400,"bad_request",`"${$}" is not a channel of the room "${b}"`);async function N(b,$){let w=y(b);if("status"in w)return w;let{entry:R,channel:P,params:C}=w,I={status:200,body:{subscribe:!1,publish:!1}};if(!C)return S.warn(`[palbase] ${R.cls.name}: realtime asked about "${P}", which is not a channel of the room "${R.room.pattern}"; the join is refused`),I;let L=Te(b.user),U=L?.id;if(!U)return I;let M=R.room.hooks.authorize;if(!M)return I;let q,re;try{q=await t.run(L,`${R.cls.name}.${M}`,$,async()=>R.instance[M]({user:{id:U},params:Object.freeze({...C})})),re=zr(q)}catch(Q){if(t.isOutage(Q)||$?.aborted)throw Q;return S.error(`[palbase] ${R.cls.name}.${M} (@OnAuthorize of ${P}) failed; the join is refused`,{error:Q}),I}return re==="malformed"?(S.warn(`[palbase] ${R.cls.name}.${M} (@OnAuthorize of ${P}) answered ${Fr(q)}, which is no grant (true, { read, write } or null); the join is refused`),I):{status:200,body:re}}async function g(b,$){let w=y(b);if("status"in w)return w;if(!w.params)return E(w.entry.room.pattern,w.channel);let R=Te(b.user);if(!R?.id||typeof b.event!="string")return ae(400,"bad_request","A message names its member (user) and its event");let P=Object.hasOwn(w.entry.room.messages,b.event)?w.entry.room.messages[b.event]:void 0;if(!P)return{status:200,body:{ok:!1,reason:En(`room "${w.channel}" declares no message "${b.event}"`,Ot)}};let C=await P.schema["~standard"].validate(Mr(b.payload??{}));if(C.issues)return{status:200,body:{ok:!1,reason:Wr(C.issues)}};let I=c(w.channel),L={...f(w.entry,w.channel,w.params,I,0,{id:R.id}),payload:C.value};try{await t.run(R,`${w.entry.cls.name}.${P.fn}`,$,async()=>w.entry.instance[P.fn](L))}catch(U){if(t.isOutage(U))throw U;return $?.aborted||S.error(`[palbase] ${w.entry.cls.name}.${P.fn} (@OnMessage "${b.event}" of ${w.channel}) failed`,{error:U}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return{status:200,body:{ok:!0}}}async function A(b,$){let w=y(b);if("status"in w)return w;if(!w.params)return E(w.entry.room.pattern,w.channel);let R=b.event;if(typeof R!="string"||!Br.has(R))return ae(400,"bad_request","A room's moment is first, join, leave or empty");let P=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(P===void 0)return ae(400,"bad_request","A room's moment says its count of members");let C=R==="join"||R==="leave",I=C?Te(b.user):void 0,L=C?b.connId:void 0;if(C&&(!I?.id||typeof L!="string"||L===""))return ae(400,"bad_request",`A ${R} names its member: user and connId`);let U=`${R}\0${w.channel}\0${typeof L=="string"?L:""}`;if(C&&s.has(U))return{status:204};if(a.has(U))return ae(503,"in_progress","This moment of the room is being handled",5);a.add(U);try{let M=w.entry.room.hooks[R],q;if(R==="empty"?(q=o.get(w.channel),u(w.channel,q)):q=R==="leave"?o.get(w.channel):c(w.channel),M){let re=f(w.entry,w.channel,w.params,q,P,{id:I?.id??""},R==="join"?L:void 0);try{await t.run(I,`${w.entry.cls.name}.${M}`,$,async()=>w.entry.instance[M](re))}catch(Q){if(t.isOutage(Q))throw Q;return $?.aborted||S.error(`[palbase] ${w.entry.cls.name}.${M} (${R} of ${w.channel}) failed; realtime tells it again`,{error:Q}),ae(500,"handler_failed",`The room's ${R} could not be handled`)}}return C&&(s.add(U),s.size>qr&&s.delete(s.values().next().value)),{status:204}}finally{a.delete(U)}}return{declarations:[...r.values()].map(b=>b.room),async serve(b,$,w){return At($)?b==="authorize"?N($,w):b==="message"?g($,w):b==="lifecycle"?A($,w):ae(404,"not_found",`No room call ${JSON.stringify(b)}`):ae(400,"bad_request","A room's call is a JSON object")},close(){for(let b of o.values())b.abort();o.clear()}}}function zr(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!At(e))return"malformed";let r=Object.hasOwn(e,"read"),n=Object.hasOwn(e,"write");if(r&&typeof e.read!="boolean"||n&&typeof e.write!="boolean"||!r&&!n)return"malformed";let o=r?e.read:void 0,s=n?e.write:void 0;return o===!1?t:{subscribe:!0,publish:s!==!1}}function Fr(e){return Array.isArray(e)?"an array":At(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var Kr=20,Ot=256;function Wr(e){let t="";for(let r of e.slice(0,Kr)){let n=(r.path??[]).slice(0,8).map(s=>String(typeof s=="object"&&s!==null&&"key"in s?s.key:s).slice(0,64)).join("."),o=n===""?r.message:`${n}: ${r.message}`;if(t=t===""?o:`${t}; ${o}`,Buffer.byteLength(t)>=Ot)break}return En(t,Ot)}function En(e,t){if(Buffer.byteLength(e)<=t)return e;let r="";for(let n of e){if(Buffer.byteLength(r+n)>t-3)break;r+=n}return`${r}\u2026`}var _t=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,r){if(typeof t.event!="string"||t.event===""||xt(t.event)>Ae){S.warn(`[palbase] ${r}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Ae} bytes`);return}try{JSON.stringify(t.payload)}catch(s){S.warn(`[palbase] ${r}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let n=this.queues.get(t.topic);if(n){n.length>=Hr?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):n.push(t);return}let o=[t];this.queues.set(t.topic,o),se.exit(()=>this.drain(t.topic,o,r))}async drain(t,r,n){for(;;){if(r.length===0){this.queues.delete(t);return}let o=r.splice(0,Jr);try{await this.broadcast(o)}catch(a){S.warn(`[palbase] ${n}: ${o.length} event(s) to ${t} were not sent`,{error:a})}let s=this.dropped.get(t);s&&(this.dropped.delete(t),S.warn(`[palbase] ${n}: ${s} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as Pt,createHmac as Vr,createPublicKey as _n,timingSafeEqual as Yr,verify as xn}from"node:crypto";function Pa(e){let t=T(e,Oe);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(r=>r.event)}}function Tn(e,t,r,n={}){let o=new Map,s=[];for(let a of e){let i=T(a,Oe),c=o.get(i.name);if(c)throw new TypeError(`@Webhook "${i.name}" is declared by ${c.cls.name} and by ${a.name}: /webhooks/${i.name} is one endpoint`);let u=`@Webhook "${i.name}" (${a.name})`,f=r[i.secret.env],y;if(n.secrets!==!1)if(f===void 0||f==="")s.push(`${u} reads its signing secret from ${i.secret.env}, which is not set`);else try{y=Gr(i,f)}catch(g){s.push(`${u}: ${i.secret.env} ${g.message}`)}let E=t(a),N=new Map(i.events.map(({event:g,fn:A})=>[g,{name:`${a.name}.${A}`,call:(b,$)=>E[A](b,$)}]));o.set(i.name,{name:i.name,cls:a,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:y,events:N})}if(s.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
3
|
- ${s.join(`
|
|
4
4
|
- `)}`);return o}function An(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var je=1024,Rn=1024*je;function Gr(e,t){if(e.signature)return ye(void 0,e.signature.header,1/0,io(e.signature,t));switch(e.provider){case"stripe":return ye("stripe","stripe-signature",512*je,Qr(t));case"github":return ye("github","x-hub-signature-256",25*Rn,eo(t));case"slack":return ye("slack","x-slack-signature",64*je,to(t));case"discord":return ye("discord","x-signature-ed25519",64*je,no(t));case"twilio":return{header:"x-twilio-signature",maxBytes:r=>Math.min(r,64*je),check:oo(t)};case"sendgrid":return ye("sendgrid","x-twilio-email-event-webhook-signature",Rn,so(t));case"livekit":return ye("livekit","authorization",512*je,ao(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function ye(e,t,r,n){return{header:t,maxBytes:o=>Math.min(o,r),check:(o,s)=>n(o,s)??Pn(e,o)}}function Pn(e,t){let r=jt(t.body),n;try{n=JSON.parse(r)}catch{if(n=r,e==="slack"){let o=new URLSearchParams(r).get("payload");if(o!==null)try{n=JSON.parse(o)}catch{}}}return{type:jn(e,t.headers,n),event:n,...Zr(e,t,n)}}function jn(e,t,r){switch(e){case"github":{let n=t.get("x-github-event")??"",o=we(r,"action");return n!==""&&o!==""?`${n}.${o}`:n}case"discord":{let n=Dn(r)?r.type:void 0;return n===1?"PING":n===2?"INTERACTION_CREATE":Number.isInteger(n)?`type_${String(n)}`:""}case"sendgrid":return"event_batch";case"twilio":return we(r,"EventType");case"livekit":return we(r,"event");default:return we(r,"type")}}function Zr(e,t,r){let n=o=>o?{id:o}:{};switch(e){case"stripe":case"discord":case"livekit":return n(we(r,"id"));case"slack":return n(we(r,"event_id"));case"github":{let o=t.headers.get("x-github-delivery");return o?{id:`${o}:${Cn(t.body)}`}:{}}case"sendgrid":return Array.isArray(r)?{ids:r.map(o=>we(o,"sg_event_id")||void 0)}:{};default:return{}}}var Xr=300;function Qr(e){return(t,r)=>{let n=t.headers.get("stripe-signature");if(!n)return"missing_signature";let o,s=[];for(let c of n.split(",")){let u=c.indexOf("=");if(u<=0)continue;let f=c.slice(0,u).trim(),y=c.slice(u+1).trim();if(f==="t"){if(o!==void 0)return"malformed_signature";o=y}else if(f==="v1"){let E=ne(y,"hex");if(!E)return"malformed_signature";s.push(E)}}let a=Ne(o);if(a===void 0||s.length===0)return"malformed_signature";if(Ie(a,r))return"stale_timestamp";let i=Ce("sha256",e,`${o}.`,t.body);return s.some(c=>le(c,i))?void 0:"signature_mismatch"}}function eo(e){return t=>{let r=t.headers.get("x-hub-signature-256");if(!r)return"missing_signature";let n=r.startsWith("sha256=")?ne(r.slice(7),"hex"):void 0;return n?le(n,Ce("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function to(e){return(t,r)=>{let n=t.headers.get("x-slack-signature");if(!n)return"missing_signature";let o=t.headers.get("x-slack-request-timestamp")?.trim(),s=Ne(o),a=n.startsWith("v0=")?ne(n.slice(3),"hex"):void 0;return s===void 0||!a?"malformed_signature":Ie(s,r)?"stale_timestamp":le(a,Ce("sha256",e,`v0:${o}:`,t.body))?void 0:"signature_mismatch"}}function no(e){let t=ne(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let r=_n({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(n,o)=>{let s=n.headers.get("x-signature-ed25519");if(!s)return"missing_signature";let a=n.headers.get("x-signature-timestamp")??void 0,i=Ne(a),c=ne(s,"hex");return i===void 0||!c||c.byteLength!==64?"malformed_signature":Ie(i,o)?"stale_timestamp":xn(null,Mn(a,n.body),r,c)?void 0:"signature_mismatch"}}var ro=1e3;function oo(e){return t=>{let r=t.headers.get("x-twilio-signature");if(!r)return"missing_signature";let n=ne(r.trim(),"base64");if(!n||n.byteLength!==20)return"malformed_signature";let o;try{o=new URL(t.url)}catch{return"signature_mismatch"}let s=o.searchParams.get("bodySHA256"),a="",i;if(s!==null){if(!le(Buffer.from(s.toLowerCase()),Buffer.from(Pt("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let N=1;for(let b of t.body)if(b===38&&++N>ro)return"malformed_signature";let g=new Map;for(let[b,$]of new URLSearchParams(jt(t.body))){let w=g.get(b);w||g.set(b,w=new Set),w.add($)}let A=[];for(let b of[...g.keys()].sort()){let $=[...g.get(b)].sort();for(let w of $)a+=b+w;A.push([b,$.length===1?$[0]:$])}i=Object.fromEntries(A)}let c=o.protocol==="https:"?"443":"80",u=`${o.protocol}//${o.hostname}${o.pathname}${o.search}`,f=`${o.protocol}//${o.hostname}:${o.port||c}${o.pathname}${o.search}`;if(![u,f].some(N=>le(n,Ce("sha1",e,N,a))))return"signature_mismatch";let y=t.headers.get("i-twilio-idempotency-token"),E=y?{id:`${y}:${Cn(`${u}
|
|
5
5
|
${a}`)}`}:{};return i?{type:jn("twilio",t.headers,i),event:i,...E}:{...Pn("twilio",t),...E}}}function so(e){let t;try{let r=ne(e,"base64");if(!r)throw new Error;t=_n({key:Buffer.from(r),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(r,n)=>{let o=r.headers.get("x-twilio-email-event-webhook-signature");if(!o)return"missing_signature";let s=r.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),a=Ne(s),i=ne(o.trim(),"base64");return a===void 0||!i?"malformed_signature":Ie(a,n)?"stale_timestamp":xn("sha256",Mn(s,r.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var Sn=60;function ao(e){return(t,r)=>{let n=t.headers.get("authorization");if(!n)return"missing_signature";let o=n.split(".");if(o.length!==3)return"malformed_signature";let s=On(ne(o[0],"base64url")),a=ne(o[2],"base64url");if(s?.alg!=="HS256"||!a)return"malformed_signature";if(!le(a,Ce("sha256",e,`${o[0]}.${o[1]}`)))return"signature_mismatch";let i=On(ne(o[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(r>i.exp+Sn||typeof i.nbf=="number"&&r<i.nbf-Sn)return"stale_timestamp";let c=typeof i.sha256=="string"?ne(i.sha256,"base64"):void 0;return c&&le(c,Pt("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function io(e,t){let r=e.signs.split(/(\{body\}|\{ts\})/),n=e.algo==="hmac-sha1"?"sha1":"sha256";return(o,s)=>{let a=o.headers.get(e.header);if(!a)return"missing_signature";if(e.prefix){if(!a.startsWith(e.prefix))return"malformed_signature";a=a.slice(e.prefix.length)}let i="";if(r.includes("{ts}")){i=o.headers.get(e.timestampHeader)?.trim()??"";let u=Ne(i);if(u===void 0)return"malformed_signature";if(Ie(u,s))return"stale_timestamp"}let c=ne(a.trim(),e.encoding);return c?le(c,Ce(n,t,...r.map(u=>u==="{body}"?o.body:u==="{ts}"?i:u)))?void 0:"signature_mismatch":"malformed_signature"}}var co=new TextEncoder;function Ce(e,t,...r){let n=Vr(e,t);for(let o of r)n.update(o);return n.digest()}function Cn(e){return Pt("sha256").update(e).digest("hex")}function Mn(e,t){return Buffer.concat([co.encode(e),t])}function le(e,t){return e.byteLength===t.byteLength&&Yr(e,t)}var uo={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function ne(e,t){return uo[t].test(e)?Buffer.from(e,t):void 0}function Ne(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Ie(e,t){return Math.abs(t-e)>Xr}function jt(e){return new TextDecoder().decode(e)}function On(e){if(e)try{return JSON.parse(jt(e))}catch{return}}function Dn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function we(e,t){let r=Dn(e)?e[t]:void 0;return typeof r=="string"?r:""}import"reflect-metadata";var J=class extends Error{kind;path;constructor(t,r,n,o,s){super(`
|