{"version":3,"sources":["../src/index.ts","../src/app.ts","../src/error.ts","../src/net.ts","../src/permission.ts","../src/profile.ts","../src/argv.ts"],"sourcesContent":["export { default as app } from \"./app.js\";\n\n//export * from \"./agentic-auth.js\";\nexport * from \"./error.js\";\nexport * from \"./net.js\";\nexport * from \"./permission.js\";\nexport * from \"./profile.js\";\n\nexport * as argv from \"./argv.js\";","import express from \"express\"\nimport morgan from \"morgan\"\nimport cors from \"cors\"\n\nconst app: express.Application = express()\napp.use( morgan(\"combined\") )\napp.use( cors() )\napp.options( \"*\", cors() )\n\napp.use( express.json({ limit:\"1mb\" }) )\napp.use( express.urlencoded({ extended: true }) )\napp.use( express.raw({ limit:\"10mb\", type:\"*/*\" }) )\n\nexport default app","import {\n    Request, \n    Response\n} from \"express\";\nimport { inherits } from \"util\";\nimport log from \"loglevel\";\nimport { prettyJson } from \"@agentic-profile/common\";\n\n\nfunction errorCodeToStatusCode( code: any ) {\n    if( !code || !Array.isArray(code) )\n        return 500;\n    const parts = code as any[];\n    if( parts.length === 0 || parts.some(e=>Number.isFinite(e) !== true) )\n        return 500;\n\n    let result = parts[0]*100;\n    if( parts.length > 1 )\n        result += parts[1];\n\n    return result;\n}\n\n// Use this method when we have an Error object\nexport function signalError( req: Request, res: Response, err:any ) {\n    console.log( 'signalError', err );\n    const { code, details, name, message, stack, statusCode, cause } = err;\n    \n    // Handle custom error types that have a statusCode property (like ScrapingDogAPIError)\n    let httpStatusCode: number;\n    if (statusCode && typeof statusCode === 'number') {\n        httpStatusCode = statusCode;\n    } else {\n        httpStatusCode = errorCodeToStatusCode(code);\n    }\n\n    const msg = cause ? `${message ?? name} [cause] ${cause.message}` : message ?? name;\n    \n    const failure = {\n        code,\n        message: msg,\n        details: details ?? stack?.split(/\\n/).map((e:string)=>e.trim()).slice(0,7)\n    }\n    if( cause )\n        (failure as any).cause = cause;\n\n    logFailure( req,failure, err );\n    res.status( httpStatusCode ).json({ failure });\n}\n\nexport function logFailure( req: Request, failure: any, err?: any ) {\n    const auth = (req as any).auth;\n    log.error( 'ERROR:', prettyJson({\n        url: req.originalUrl,\n        headers: req.headers,\n        auth,\n        body: req.body,\n        failure,\n        errorMessage: err?.message\n    }) );\n}\n\nexport class ServerError extends Error {\n    code: number[];           // Array of HTTP status codes\n    details: string[] | undefined;  // Optional technical or support details\n\n    // code: []\n    // messagge: Human readable\n    // details: [] Tech support understandable\n    constructor(code: number[], message: string, details?: string[]) {\n        super(message);       // Call the parent class constructor\n        Error.captureStackTrace(this, this.constructor); // Attach the stack trace\n        this.name = this.constructor.name;  // Set the error name\n\n        this.code = code;     // Assign the provided status code(s)\n        this.details = details;  // Assign the provided details\n    }\n}\n\n// Ensure proper inheritance of Error class in older environments\ninherits(ServerError, Error);","import {\n    NextFunction,\n    Request, \n    Response\n} from \"express\";\n\nimport { signalError } from \"./error.js\";\n\nexport type AsyncMiddleware = (req: Request, res: Response, next: NextFunction) => Promise<any>;\n\nexport const asyncHandler = (fn: AsyncMiddleware) => function( req: Request, res: Response, next: NextFunction ) {\n    const fnReturn = fn(req,res,next)\n    return Promise.resolve(fnReturn).catch( err => {\n        signalError(req,res,err);\n    });\n}\n\nexport function baseUrl( req: Request ) {\n    return (req.protocol + \"://\" + req.get('host')).toLowerCase();\n}","import { Request } from \"express\";\n\nexport function isAdmin( req: Request ) {\n    const admin_token = process.env.ADMIN_TOKEN;\n    if( !admin_token )\n        return false;   // not set up\n\n    // auth token as a query parameter?\n    if( req.query.auth === admin_token )\n        return true;\n\n    // auth token as Authorization header?\n    const [ bearer, token ] = req.headers?.authorization?.split(/\\s+/) ?? [];\n    return bearer?.toLowerCase() === \"bearer\" && token === admin_token;\n}","import {\n    AgenticProfile,\n    JWKSet,\n    prettyJson\n} from \"@agentic-profile/common\";\n\nimport { join } from \"path\";\nimport {\n    access,\n    mkdir,\n    readFile,\n    writeFile\n} from \"fs/promises\";\n\n\ntype SaveProfileParams = {\n    dir: string,\n    profile?: AgenticProfile,\n    keyring?: JWKSet[]\n}\n\nexport async function saveProfile({ dir, profile, keyring }: SaveProfileParams) {\n    await mkdir(dir, { recursive: true });\n\n    const profilePath = join(dir, \"did.json\");\n    if( profile ) {\n        await writeFile(\n            profilePath,\n            prettyJson( profile ),\n            \"utf8\"\n        );\n    }\n\n    const keyringPath = join(dir, \"keyring.json\");\n    if( keyring ) {\n        await writeFile(\n            keyringPath,\n            prettyJson( keyring ),\n            \"utf8\"\n        );\n    }  \n\n    return { profilePath, keyringPath }\n}\n\nexport async function loadProfileAndKeyring( dir: string ) {\n    const profile = await loadProfile( dir );\n    const keyring = await loadKeyring( dir );\n    return { profile, keyring };\n}\n\nexport async function loadProfile( dir: string ) {\n    return loadJson<AgenticProfile>( dir, \"did.json\" );\n}\n\nexport async function loadKeyring( dir: string ) {\n    return loadJson<JWKSet[]>( dir, \"keyring.json\" );\n}\n\nexport async function loadJson<T>( dir: string, filename: string ): Promise<T> {\n    const path = join( dir, filename );\n    if( await fileExists( path ) !== true )\n        throw new Error(`Failed to load ${path} - file not found`);\n\n    const buffer = await readFile( path, \"utf-8\" );\n    return JSON.parse( buffer ) as T;\n}\n\n\n//\n// General util\n//\n\nasync function fileExists(path: string): Promise<boolean> {\n    try {\n        await access(path);\n        return true;\n    } catch (error) {\n        return false;\n    }\n}","import { parseArgs as nodeParseArgs } from \"util\";\nimport { sep } from \"path\";\n\nexport interface ArgvOption {\n    type: \"string\" | \"boolean\";\n    short: string;\n}\n\nexport type ArgvOptions = {\n    [key: string]: ArgvOption;\n};\n\ntype Params = {\n\targs: string[],\n\toptions: ArgvOptions\n}\n\nexport function parseArgs({args, options}: Params) {\n    const optionShortToKey = Object.fromEntries(\n        Object.entries(options).map(([key, opt]) => [opt.short, key])\n    );\n\n    const normalized = [];\n    for (let i = 0; i < args.length; i++) {\n        const current = args[i];\n        const next = args[i + 1];\n\n        // Check if next is a negative number (int or float)\n        const isNegativeNumber = /^-\\d+(\\.\\d+)?$/.test(next);\n\n        // If current is a short option like -x and next is a negative number, combine\n        if (/^-[a-zA-Z]$/.test(current) && isNegativeNumber ) {\n            const key = current[1];\n            const optionName = optionShortToKey[key];\n            if (options[optionName]?.type === \"string\") {\n                normalized.push(`${current}=${next}`);\n                i++; // skip next, already used\n                continue;\n            }\n        }\n        normalized.push(current);\n    }\n\n    return nodeParseArgs({ args: normalized, options });\n}\n\nexport function argvToCommand( argv: string[] ) {\n    const program = argv[0].split( sep ).at(-1);\n    const script = argv[1].split( sep ).slice(-2).join( sep );\n\n    return `${program} ${script}`;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qBAAoB;AACpB,oBAAmB;AACnB,kBAAiB;AAEjB,IAAM,UAA2B,eAAAA,SAAQ;AACzC,IAAI,QAAK,cAAAC,SAAO,UAAU,CAAE;AAC5B,IAAI,QAAK,YAAAC,SAAK,CAAE;AAChB,IAAI,QAAS,SAAK,YAAAA,SAAK,CAAE;AAEzB,IAAI,IAAK,eAAAF,QAAQ,KAAK,EAAE,OAAM,MAAM,CAAC,CAAE;AACvC,IAAI,IAAK,eAAAA,QAAQ,WAAW,EAAE,UAAU,KAAK,CAAC,CAAE;AAChD,IAAI,IAAK,eAAAA,QAAQ,IAAI,EAAE,OAAM,QAAQ,MAAK,MAAM,CAAC,CAAE;AAEnD,IAAO,cAAQ;;;ACTf,kBAAyB;AACzB,sBAAgB;AAChB,oBAA2B;AAG3B,SAAS,sBAAuB,MAAY;AACxC,MAAI,CAAC,QAAQ,CAAC,MAAM,QAAQ,IAAI;AAC5B,WAAO;AACX,QAAM,QAAQ;AACd,MAAI,MAAM,WAAW,KAAK,MAAM,KAAK,OAAG,OAAO,SAAS,CAAC,MAAM,IAAI;AAC/D,WAAO;AAEX,MAAI,SAAS,MAAM,CAAC,IAAE;AACtB,MAAI,MAAM,SAAS;AACf,cAAU,MAAM,CAAC;AA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